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
52553_2
/** * Abstract class Figuur - write a description of the class here * * @author (your name here) * @version (version number or date here) */ public abstract class Figuur { // instance variables - replace the example below with your own private int xPosition; private int yPosition; private String color; private boolean isVisible; /** * Maak een nieuw Figuur */ public Figuur(int xPosition, int yPosition, String color) { this.xPosition = xPosition; this.yPosition = yPosition; this.color = color; } /** * Maak dit figuur zichtbaar */ public void maakZichtbaar() { isVisible = true; teken(); } /** * Maak dit figuur onzichtbaar */ public void maakOnzichtbaar() { wis(); isVisible = false; } /** * Beweeg dit figuur 20 pixels naar rechts */ public void beweegRechts() { beweegHorizontaal(20); } /** * Beweeg dit figuur 20 pixels naar links */ public void beweegLinks() { beweegHorizontaal(-20); } /** * Beweeg dit figuur 20 pixels naar boven */ public void beweegBoven() { beweegVertikaal(-20); } /** * Beweeg dit figuur 20 pixels naar beneden */ public void beweegBeneden() { beweegVertikaal(20); } /** * Beweeg dit figuur horizontaal adhv het aantal gegeven pixels */ public void beweegHorizontaal(int distance) { wis(); xPosition += distance; teken(); } /** * Beweeg dit figuur vertikaal adhv het aantal gegeven pixels */ public void beweegVertikaal(int distance) { wis(); yPosition += distance; teken(); } /** * Beweeg langzaam dit figuur horizontaal adhv het aantal gegeven pixels */ public void traagBeweegHorizontaal(int distance) { int delta; if(distance < 0) { delta = -1; distance = -distance; } else { delta = 1; } for(int i = 0; i < distance; i++) { xPosition += delta; teken(); } } /** * Beweeg langzaam dit figuur verticaal adhv het aantal gegeven pixels */ public void traagBeweegVertikaal(int distance) { int delta; if(distance < 0) { delta = -1; distance = -distance; } else { delta = 1; } for(int i = 0; i < distance; i++) { yPosition += delta; teken(); } } /** * Pas de kleur aan, mogelijke kleuren zijn "red", "yellow", "blue", "green", "magenta" and "black". */ public void veranderKleur(String newColor) { color = newColor; teken(); } /** * Wis het figuur van het scherm */ public void wis() { if(isVisible) { Canvas canvas = Canvas.getCanvas(); canvas.erase(this); } } /** * Bepaal of het figuur zichtbaar is */ public boolean isZichtbaar() { return isVisible; } /** * Geef de kleur van het figuur */ public String getKleur() { return color; } /** * Geef de positie op de x-as */ public int getXPositie() { return xPosition; } /** * Geef de positie op de y-as */ public int getYPositie() { return yPosition; } /** * Teken dit figuur op het scherm. * Dit is een abstracte method, het moet in de subclasses gedefinieerd worden. */ public abstract void teken(); }
BenVandenberk/vdab
05 OOP/Voorbeelden/FigurenVoorbeeld04/Figuur.java
1,207
/** * Maak een nieuw Figuur */
block_comment
nl
/** * Abstract class Figuur - write a description of the class here * * @author (your name here) * @version (version number or date here) */ public abstract class Figuur { // instance variables - replace the example below with your own private int xPosition; private int yPosition; private String color; private boolean isVisible; /** * Maak een nieuw<SUF>*/ public Figuur(int xPosition, int yPosition, String color) { this.xPosition = xPosition; this.yPosition = yPosition; this.color = color; } /** * Maak dit figuur zichtbaar */ public void maakZichtbaar() { isVisible = true; teken(); } /** * Maak dit figuur onzichtbaar */ public void maakOnzichtbaar() { wis(); isVisible = false; } /** * Beweeg dit figuur 20 pixels naar rechts */ public void beweegRechts() { beweegHorizontaal(20); } /** * Beweeg dit figuur 20 pixels naar links */ public void beweegLinks() { beweegHorizontaal(-20); } /** * Beweeg dit figuur 20 pixels naar boven */ public void beweegBoven() { beweegVertikaal(-20); } /** * Beweeg dit figuur 20 pixels naar beneden */ public void beweegBeneden() { beweegVertikaal(20); } /** * Beweeg dit figuur horizontaal adhv het aantal gegeven pixels */ public void beweegHorizontaal(int distance) { wis(); xPosition += distance; teken(); } /** * Beweeg dit figuur vertikaal adhv het aantal gegeven pixels */ public void beweegVertikaal(int distance) { wis(); yPosition += distance; teken(); } /** * Beweeg langzaam dit figuur horizontaal adhv het aantal gegeven pixels */ public void traagBeweegHorizontaal(int distance) { int delta; if(distance < 0) { delta = -1; distance = -distance; } else { delta = 1; } for(int i = 0; i < distance; i++) { xPosition += delta; teken(); } } /** * Beweeg langzaam dit figuur verticaal adhv het aantal gegeven pixels */ public void traagBeweegVertikaal(int distance) { int delta; if(distance < 0) { delta = -1; distance = -distance; } else { delta = 1; } for(int i = 0; i < distance; i++) { yPosition += delta; teken(); } } /** * Pas de kleur aan, mogelijke kleuren zijn "red", "yellow", "blue", "green", "magenta" and "black". */ public void veranderKleur(String newColor) { color = newColor; teken(); } /** * Wis het figuur van het scherm */ public void wis() { if(isVisible) { Canvas canvas = Canvas.getCanvas(); canvas.erase(this); } } /** * Bepaal of het figuur zichtbaar is */ public boolean isZichtbaar() { return isVisible; } /** * Geef de kleur van het figuur */ public String getKleur() { return color; } /** * Geef de positie op de x-as */ public int getXPositie() { return xPosition; } /** * Geef de positie op de y-as */ public int getYPositie() { return yPosition; } /** * Teken dit figuur op het scherm. * Dit is een abstracte method, het moet in de subclasses gedefinieerd worden. */ public abstract void teken(); }
115360_8
package android.translateapp; import android.app.NotificationManager; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; import ben.translateapp.R; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; public class AddwordActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_addword); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); setTitle("Add word"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onOptionsItemSelected(MenuItem menuItem) { if (menuItem.getItemId() == android.R.id.home) { //Als de 'back' item is geklikt dan wordt deze intent gesloten this.finish(); } return super.onOptionsItemSelected(menuItem); } public static boolean empty( final String s ) { // Null-safe, short-circuit evaluation. return s == null || s.trim().isEmpty(); } public void addWord() { SharedPreferences userSettings = getSharedPreferences("UserPreferences", MODE_PRIVATE); TextView mNederlands; TextView mFrans; String sNederlands; String sFrans; String userID; //Variabelen ophalen van de textviews mNederlands = (TextView)findViewById(R.id.dutchWord); mFrans = (TextView)findViewById(R.id.frenchWord); sNederlands = mNederlands.getText().toString(); sFrans = mFrans.getText().toString(); //Geklikt op add Word button if(!empty(sNederlands) && !empty(sFrans)){ //Connectie maken met de FirebaseDatabase FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference ref = database.getReference(); SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode userID = userSettings.getString("UserName", ""); Integer countWords = 0; //Klasse woord aanmaken Words oneWord = new Words(sNederlands, sFrans, userID, countWords); //Woord toevoegen aan de database ref.child("words").push().setValue(oneWord); Toast.makeText(this, "Woord opgeslagen!", Toast.LENGTH_SHORT).show(); //Leegmaken van de velden mNederlands.setText(""); mFrans.setText(""); } else { Toast.makeText(this, "Gelieve beide velden in te vullen!", Toast.LENGTH_LONG).show(); } this.finish(); } public void onClick(View v) { addWord(); } }
BenWitters/TranslateApp
app/src/main/java/android/translateapp/AddwordActivity.java
888
//Leegmaken van de velden
line_comment
nl
package android.translateapp; import android.app.NotificationManager; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; import ben.translateapp.R; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; public class AddwordActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_addword); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); setTitle("Add word"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onOptionsItemSelected(MenuItem menuItem) { if (menuItem.getItemId() == android.R.id.home) { //Als de 'back' item is geklikt dan wordt deze intent gesloten this.finish(); } return super.onOptionsItemSelected(menuItem); } public static boolean empty( final String s ) { // Null-safe, short-circuit evaluation. return s == null || s.trim().isEmpty(); } public void addWord() { SharedPreferences userSettings = getSharedPreferences("UserPreferences", MODE_PRIVATE); TextView mNederlands; TextView mFrans; String sNederlands; String sFrans; String userID; //Variabelen ophalen van de textviews mNederlands = (TextView)findViewById(R.id.dutchWord); mFrans = (TextView)findViewById(R.id.frenchWord); sNederlands = mNederlands.getText().toString(); sFrans = mFrans.getText().toString(); //Geklikt op add Word button if(!empty(sNederlands) && !empty(sFrans)){ //Connectie maken met de FirebaseDatabase FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference ref = database.getReference(); SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode userID = userSettings.getString("UserName", ""); Integer countWords = 0; //Klasse woord aanmaken Words oneWord = new Words(sNederlands, sFrans, userID, countWords); //Woord toevoegen aan de database ref.child("words").push().setValue(oneWord); Toast.makeText(this, "Woord opgeslagen!", Toast.LENGTH_SHORT).show(); //Leegmaken van<SUF> mNederlands.setText(""); mFrans.setText(""); } else { Toast.makeText(this, "Gelieve beide velden in te vullen!", Toast.LENGTH_LONG).show(); } this.finish(); } public void onClick(View v) { addWord(); } }
26235_2
package be.inf1.flappybird2; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.ResourceBundle; import java.util.stream.Collectors; import java.util.stream.Stream; import be.inf1.flappybird2.model.Pilaar; import be.inf1.flappybird2.model.Bird; import be.inf1.flappybird2.model.Grenzen; import javafx.animation.AnimationTimer; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.application.Platform; import javafx.fxml.FXMLLoader; import javafx.util.Duration; public class Controller { private Bird bird; private List<Pilaar> pilaren; private Grenzen grenzen; private BirdFXMLController view; private boolean gameGestart = false; private int scoreWaarde = 0; private int highScoreWaarde = 0; private Timeline movePilaren; private Pilaar laatstePilaarVoorbij = null; public Controller(BirdFXMLController view, Bird birdModel, Grenzen grenzenModel, List<Pilaar> pilaarModels) { this.view = view; this.bird = birdModel; this.grenzen = grenzenModel; this.pilaren = pilaarModels; } public void startGame() { gameGestart = true; movePilaren = new Timeline(new KeyFrame(Duration.millis(10), e -> { if (gameGestart) { updateGame(); } })); movePilaren.setCycleCount(Timeline.INDEFINITE); movePilaren.play(); } public void updateGame() { laatstePilaarVoorbij = null; // beweeg de pilaren for (Pilaar pilaar : pilaren) { pilaar.setX(pilaar.getX() - 2); // botsing detectie met de pilaar if (bird.getVogel().getBoundsInParent().intersects(pilaar.getBovenPilaar().getBoundsInParent()) || bird.getVogel().getBoundsInParent().intersects(pilaar.getOnderPilaar().getBoundsInParent())) { stopGame(); System.out.println("Botsing gedetecteerd!"); } // botsing detectie met de grenzen if (bird.getVogel().getBoundsInParent().intersects(grenzen.getBovenGrens().getBoundsInParent()) || bird.getVogel().getBoundsInParent().intersects(grenzen.getOnderGrens().getBoundsInParent())) { System.out.println("Botsing gedetecteerd!"); stopGame(); } if (!pilaar.isVoorbij() && bird.getVogel().getCenterX() > pilaar.getX() + pilaar.getDikte()) { pilaar.setVoorbij(true); verhoogScore(); } } bird.val(); } public void flap() { bird.flap(); } public void stopGame() { scoreWaarde = 0; view.updateScore(scoreWaarde); gameGestart = false; movePilaren.stop(); } public void resetGame(){ view.resetPilaren(); bird.reset(); } public void restartGame() { setGameGestart(true); movePilaren.play(); } public void verhoogScore() { scoreWaarde++; view.updateScore(scoreWaarde); if (scoreWaarde > highScoreWaarde) { highScoreWaarde = scoreWaarde; view.updateHighScore(highScoreWaarde); } System.out.println("Score: " + scoreWaarde); } public int getHighScoreWaarde() { return highScoreWaarde; } public boolean isGameGestart() { return gameGestart; } public boolean setGameGestart(boolean gameGestart) { this.gameGestart = gameGestart; return gameGestart; } }
Benjamin-sa/schoolwork
FlappyBird2/src/main/java/be/inf1/flappybird2/Controller.java
1,165
// botsing detectie met de grenzen
line_comment
nl
package be.inf1.flappybird2; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.ResourceBundle; import java.util.stream.Collectors; import java.util.stream.Stream; import be.inf1.flappybird2.model.Pilaar; import be.inf1.flappybird2.model.Bird; import be.inf1.flappybird2.model.Grenzen; import javafx.animation.AnimationTimer; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.application.Platform; import javafx.fxml.FXMLLoader; import javafx.util.Duration; public class Controller { private Bird bird; private List<Pilaar> pilaren; private Grenzen grenzen; private BirdFXMLController view; private boolean gameGestart = false; private int scoreWaarde = 0; private int highScoreWaarde = 0; private Timeline movePilaren; private Pilaar laatstePilaarVoorbij = null; public Controller(BirdFXMLController view, Bird birdModel, Grenzen grenzenModel, List<Pilaar> pilaarModels) { this.view = view; this.bird = birdModel; this.grenzen = grenzenModel; this.pilaren = pilaarModels; } public void startGame() { gameGestart = true; movePilaren = new Timeline(new KeyFrame(Duration.millis(10), e -> { if (gameGestart) { updateGame(); } })); movePilaren.setCycleCount(Timeline.INDEFINITE); movePilaren.play(); } public void updateGame() { laatstePilaarVoorbij = null; // beweeg de pilaren for (Pilaar pilaar : pilaren) { pilaar.setX(pilaar.getX() - 2); // botsing detectie met de pilaar if (bird.getVogel().getBoundsInParent().intersects(pilaar.getBovenPilaar().getBoundsInParent()) || bird.getVogel().getBoundsInParent().intersects(pilaar.getOnderPilaar().getBoundsInParent())) { stopGame(); System.out.println("Botsing gedetecteerd!"); } // botsing detectie<SUF> if (bird.getVogel().getBoundsInParent().intersects(grenzen.getBovenGrens().getBoundsInParent()) || bird.getVogel().getBoundsInParent().intersects(grenzen.getOnderGrens().getBoundsInParent())) { System.out.println("Botsing gedetecteerd!"); stopGame(); } if (!pilaar.isVoorbij() && bird.getVogel().getCenterX() > pilaar.getX() + pilaar.getDikte()) { pilaar.setVoorbij(true); verhoogScore(); } } bird.val(); } public void flap() { bird.flap(); } public void stopGame() { scoreWaarde = 0; view.updateScore(scoreWaarde); gameGestart = false; movePilaren.stop(); } public void resetGame(){ view.resetPilaren(); bird.reset(); } public void restartGame() { setGameGestart(true); movePilaren.play(); } public void verhoogScore() { scoreWaarde++; view.updateScore(scoreWaarde); if (scoreWaarde > highScoreWaarde) { highScoreWaarde = scoreWaarde; view.updateHighScore(highScoreWaarde); } System.out.println("Score: " + scoreWaarde); } public int getHighScoreWaarde() { return highScoreWaarde; } public boolean isGameGestart() { return gameGestart; } public boolean setGameGestart(boolean gameGestart) { this.gameGestart = gameGestart; return gameGestart; } }
82635_15
/* =========================================================== * GTNA : Graph-Theoretic Network Analyzer * =========================================================== * * (C) Copyright 2009-2011, by Benjamin Schiller (P2P, TU Darmstadt) * and Contributors * * Project Info: http://www.p2p.tu-darmstadt.de/research/gtna/ * * GTNA 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. * * GTNA 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/>. * * --------------------------------------- * SixTollis.java * --------------------------------------- * (C) Copyright 2009-2011, by Benjamin Schiller (P2P, TU Darmstadt) * and Contributors * * Original Author: Nico; * Contributors: -; * * Changes since 2011-05-17 * --------------------------------------- * */ package gtna.transformation.gd; import gtna.drawing.GraphPlotter; import gtna.graph.Edge; import gtna.graph.Graph; import gtna.graph.Node; import gtna.graph.spanningTree.ParentChild; import gtna.graph.spanningTree.SpanningTree; import gtna.id.ring.RingIdentifier; import gtna.id.ring.RingPartition; import gtna.metrics.edges.EdgeCrossings; import gtna.util.parameter.BooleanParameter; import gtna.util.parameter.DoubleParameter; import gtna.util.parameter.IntParameter; import gtna.util.parameter.Parameter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.TreeSet; /** * @author Nico * */ public class SixTollis extends CircularAbstract { private TreeSet<Node> waveCenterVertices, waveFrontVertices; private List<Node> vertexList, removedVertices; private HashMap<String, Edge> removedEdges; private HashMap<String, Edge>[] additionalEdges; private Edge[][] edges; private ParentChild deepestVertex; private Boolean useOriginalGraphWithoutRemovalList; private Graph g; public SixTollis(int realities, double modulus, boolean wrapAround, GraphPlotter plotter) { super("GDA_SIX_TOLLIS", new Parameter[] { new IntParameter("REALITIES", realities), new DoubleParameter("MODULUS", modulus), new BooleanParameter("WRAPAROUND", wrapAround) }); this.realities = realities; this.modulus = modulus; this.wrapAround = wrapAround; this.graphPlotter = plotter; } public GraphDrawingAbstract clone() { return new SixTollis(realities, modulus, wrapAround, graphPlotter); } @Override public Graph transform(Graph g) { useOriginalGraphWithoutRemovalList = false; initIDSpace(g); if (graphPlotter != null) graphPlotter.plotStartGraph(g, idSpace); EdgeCrossings ec = new EdgeCrossings(); int countCrossings = -1; // countCrossings = ec.calculateCrossings(g.generateEdges(), idSpace, // true); // System.out.println("Crossings randomized: " + countCrossings); this.g = g; /* * Phase 1 */ edges = new Edge[g.getNodes().length][]; Node tempVertex = null; Node currentVertex = null; Node randDst1, randDst2; Edge tempEdge; String tempEdgeString; ArrayList<Node> verticesToAdd; removedEdges = new HashMap<String, Edge>(g.computeNumberOfEdges()); HashMap<String, Edge> pairEdges = null; removedVertices = new ArrayList<Node>(); waveCenterVertices = new TreeSet<Node>(); waveFrontVertices = new TreeSet<Node>(); additionalEdges = new HashMap[g.getNodes().length]; for (int i = 0; i < g.getNodes().length; i++) { additionalEdges[i] = new HashMap<String, Edge>(); } vertexList = Arrays.asList(g.getNodes().clone()); System.out .println("Done with all init stuff, should run following loop from 1 to " + (vertexList.size() - 3)); for (int counter = 1; counter < (vertexList.size() - 3); counter++) { currentVertex = getVertex(); if (counter % (vertexList.size() / 10) == 0) { // System.out.println("Processing " + currentVertex + // " with a degree of " // + getEdges(currentVertex).size() + " (vertex " + counter + // " of " + (vertexList.size() - 3) // + ")"); } pairEdges = getPairEdges(currentVertex); for (Edge singleEdge : pairEdges.values()) { removedEdges.put(getEdgeString(singleEdge), singleEdge); } HashMap<String, Edge> currentVertexConnections = getEdges(currentVertex); int currentVertexDegree = currentVertexConnections.size(); int triangulationEdgesCount = (currentVertexDegree - 1) - pairEdges.size(); int[] outgoingEdges = filterOutgoingEdges(currentVertex, currentVertexConnections); // System.out.print(currentVertex.getIndex() + // " has a current degree of " + currentVertexDegree + ", " // + pairEdges.size() + " pair edges and a need for " + // triangulationEdgesCount // + " triangulation edges - existing edges:"); // for (Edge sE : currentVertexConnections.values()) { // System.out.print(" " + sE); // } // System.out.println(); int firstCounter = 0; int secondCounter = 1; while (triangulationEdgesCount > 0) { randDst1 = g.getNode(outgoingEdges[firstCounter]); randDst2 = g.getNode(outgoingEdges[secondCounter]); if (!randDst1.equals(randDst2) && !removedVertices.contains(randDst1) && !removedVertices.contains(randDst2)) { // System.out.println("rand1: " + randDst1.getIndex() + // "; rand2: " + randDst2.getIndex()); // System.out.print("Outgoing edges for r1:"); // for (int i : filterOutgoingEdges(randDst1, // getEdges(randDst1))) { // System.out.print(" " + i); // } // System.out.println(""); if (!connected(randDst1, randDst2)) { tempEdge = new Edge(Math.min(randDst1.getIndex(), randDst2.getIndex()), Math.max( randDst1.getIndex(), randDst2.getIndex())); tempEdgeString = getEdgeString(tempEdge); if (!additionalEdges[randDst1.getIndex()] .containsKey(tempEdgeString) && !additionalEdges[randDst2.getIndex()] .containsKey(tempEdgeString)) { // System.out.println("Adding triangulation edge " + // tempEdge); additionalEdges[randDst1.getIndex()].put( tempEdgeString, tempEdge); additionalEdges[randDst2.getIndex()].put( tempEdgeString, tempEdge); triangulationEdgesCount--; } } else { // System.out.println("Vertex " + randDst1.getIndex() + // " is already connected to " // + randDst2.getIndex()); } } secondCounter++; if (secondCounter == currentVertexDegree) { firstCounter++; secondCounter = firstCounter + 1; } if (firstCounter == (currentVertexDegree - 1) && triangulationEdgesCount > 0) throw new GDTransformationException( "Could not find anymore pair edges for " + currentVertex.getIndex()); } /* * Keep track of wave front and wave center vertices! */ verticesToAdd = new ArrayList<Node>(); for (Edge i : getEdges(currentVertex).values()) { int otherEnd; if (i.getDst() == currentVertex.getIndex()) { otherEnd = i.getSrc(); } else { otherEnd = i.getDst(); } tempVertex = g.getNode(otherEnd); if (removedVertices.contains(tempVertex)) { continue; } verticesToAdd.add(tempVertex); } Collections.shuffle(verticesToAdd); waveFrontVertices = new TreeSet<Node>(verticesToAdd); Collections.shuffle(verticesToAdd); waveCenterVertices.addAll(verticesToAdd); removedVertices.add(currentVertex); // System.out.println("Adding " + currentVertex.getIndex() + // " to removedVertices, now containing " // + removedVertices.size() + " vertices"); } LinkedList<Node> orderedVertices = orderVertices(); placeVertices(orderedVertices); /* * To avoid memory leaks: remove stuff that is not needed anymore */ waveCenterVertices = null; waveFrontVertices = null; removedEdges = null; removedVertices = null; // countCrossings = ec.calculateCrossings(g.generateEdges(), idSpace, // true); // System.out.println("Crossings after phase 1: " + countCrossings); if (graphPlotter != null) graphPlotter.plot(g, idSpace, graphPlotter.getBasename() + "-afterPhase1"); // System.out.println("Done with phase 1 of S/T"); reduceCrossingsBySwapping(g); writeIDSpace(g); if (graphPlotter != null) graphPlotter.plotFinalGraph(g, idSpace); // countCrossings = ec.calculateCrossings(g.generateEdges(), idSpace, // true); // System.out.println("Final crossings: " + countCrossings); return g; } private void placeVertices(LinkedList<Node> orderedVertices) { Node lastVertex = null; double lastPos = 0; double posDiff = modulus / partitions.length; /* * Create new RingIdentifiers in the order that was computed... */ RingIdentifier[] ids = new RingIdentifier[g.getNodes().length]; for (Node n : orderedVertices) { ids[n.getIndex()] = new RingIdentifier(lastPos, idSpace.isWrapAround()); // System.out.println("Place " + n.getIndex() + " at " + lastPos); lastPos += posDiff; } /* * ...and assign these ids to the partitions */ lastVertex = orderedVertices.getLast(); for (Node n : orderedVertices) { partitions[n.getIndex()] = new RingPartition( ids[lastVertex.getIndex()], ids[n.getIndex()]); lastVertex = n; } } private LinkedList<Node> orderVertices() { /* * Compute the longest path in a spanning tree created by DFS */ // System.out.println("Starting computation of longest path"); LinkedList<Node> longestPath = longestPath(); // System.out.println("Longest path contains " + longestPath.size() + // " vertices, total number: " // + vertexList.size()); // System.out.println("Characteristics for these vertices:"); // int counter = 0; // int sum = 0; // int[] degrees = new int[longestPath.size()]; // // for ( Node n: longestPath) { // degrees[counter++] = n.getOutDegree(); // sum += n.getOutDegree(); // } // System.out.println("Avg degree: " + ( (double)sum / counter) + // ", median degree: " + degrees[degrees.length/2]); /* * Check which vertices still need to be placed, as they do not lie on * the longestPath */ ArrayList<Node> todoList = new ArrayList<Node>(); todoList.addAll(vertexList); todoList.removeAll(longestPath); Node neighbor, singleVertex; int errors = 0; int modCounter = 0; while (!todoList.isEmpty()) { int neighborPosition = -1; /* * We will walk through the todoList with a counter: there might be * vertices that can not be placed yet, as they do have only * connections to other not yet connected vertices */ singleVertex = todoList.get(modCounter % todoList.size()); int[] outgoingEdges = singleVertex.getOutgoingEdges(); if (outgoingEdges.length == 0) { /* * Current vertex is not connected, so place it anywhere */ neighborPosition = rand.nextInt(longestPath.size()); } else if (outgoingEdges.length == 1 && todoList.contains(g.getNode(outgoingEdges[0]))) { /* * Current vertex has only one connection, and the vertex on the * other end is also in todoList, so also place this one * anywhere to ensure that all vertices get placed - phase 2 * will do the rest */ neighborPosition = rand.nextInt(longestPath.size()); } else { /* * Current vertex has more than one connection (or one * connection to a connected vertex), so let's check them */ for (int singleNeighbor : outgoingEdges) { neighbor = g.getNode(singleNeighbor); neighborPosition = longestPath.indexOf(neighbor); if (neighborPosition > -1) { /* * We found a neighbor that is contained in the list of * connected vertices - stop searching */ break; } } } if (neighborPosition == -1) { /* * The current vertex does not yet have any connection to the * longest path, so place it at a random position */ neighborPosition = rand.nextInt(longestPath.size()); } /* * As a possible position for this vertex is found: remove it from * the todoList and place it in the longestPath. Following elements * get shifted to the right */ todoList.remove(singleVertex); longestPath.add(neighborPosition, singleVertex); } return longestPath; } private ArrayList<Edge> getAllEdges(Node n) { ArrayList<Edge> vertexEdges = new ArrayList<Edge>(); if (edges[n.getIndex()] == null) { edges[n.getIndex()] = n.generateAllEdges(); } for (Edge e : edges[n.getIndex()]) vertexEdges.add(e); if (!useOriginalGraphWithoutRemovalList) { vertexEdges.addAll(additionalEdges[n.getIndex()].values()); } return vertexEdges; } private HashMap<String, Edge> getEdges(Node n) { HashMap<String, Edge> edges = new HashMap<String, Edge>(n.getDegree()); for (Edge i : getAllEdges(n)) { if (!useOriginalGraphWithoutRemovalList && (removedVertices.contains(g.getNode(i.getDst())) || removedVertices .contains(g.getNode(i.getSrc())))) { continue; } edges.put(getEdgeString(i), i); } return edges; } private int[] filterOutgoingEdges(Node n, HashMap<String, Edge> edges) { int[] result = new int[edges.size()]; int edgeCounter = 0; for (Edge sE : edges.values()) { int otherEnd; if (sE.getDst() == n.getIndex()) { otherEnd = sE.getSrc(); } else { otherEnd = sE.getDst(); } result[edgeCounter++] = otherEnd; } return result; } private Boolean connected(Node n, Node m) { int[] edges = filterOutgoingEdges(n, getEdges(n)); for (int sE : edges) { if (sE == m.getIndex()) return true; } return false; } private LinkedList<Integer> findLongestPath(SpanningTree tree, int source, int comingFrom) { LinkedList<Integer> connections = new LinkedList<Integer>(); for (int singleSrc : tree.getChildren(source)) { if (singleSrc == source) continue; connections.add(singleSrc); } connections.add(tree.getParent(source)); connections.removeFirstOccurrence(source); connections.removeFirstOccurrence(comingFrom); if (connections.size() == 0) { connections.add(source); return connections; } LinkedList<Integer> longestPath, tempPath; longestPath = new LinkedList<Integer>(); for (Integer singleConnection : connections) { if (singleConnection == null) { /* * This is the roots parent! */ continue; } tempPath = findLongestPath(tree, singleConnection, source); if (tempPath.size() > longestPath.size()) { longestPath = tempPath; } } longestPath.add(source); return longestPath; } private LinkedList<Node> longestPath() { LinkedList<Node> result = new LinkedList<Node>(); useOriginalGraphWithoutRemovalList = true; int startIndex = 0; Node start; do { start = removedVertices.get(startIndex++); } while (start.getOutDegree() == 0); deepestVertex = new ParentChild(-1, start.getIndex(), -1); // System.out.println("Starting DFS at " + start); HashMap<Integer, ParentChild> parentChildMap = new HashMap<Integer, ParentChild>( vertexList.size()); dfs(start, deepestVertex, parentChildMap); ArrayList<ParentChild> parentChildList = new ArrayList<ParentChild>(); parentChildList.addAll(parentChildMap.values()); SpanningTree tree = new SpanningTree(g, parentChildList); LinkedList<Integer> resultInTree = findLongestPath(tree, deepestVertex.getChild(), -1); for (Integer tempVertex : resultInTree) { result.add(g.getNode(tempVertex)); } return result; } private void dfs(Node n, ParentChild root, HashMap<Integer, ParentChild> visited) { int otherEnd; if (visited.containsKey(n.getIndex())) { return; } ParentChild current = new ParentChild(root.getChild(), n.getIndex(), root.getDepth() + 1); visited.put(n.getIndex(), current); if (current.getDepth() > deepestVertex.getDepth()) { deepestVertex = current; } for (Edge mEdge : getEdges(n).values()) { if (mEdge.getDst() == n.getIndex()) { otherEnd = mEdge.getSrc(); } else { otherEnd = mEdge.getDst(); } Node mVertex = g.getNode(otherEnd); dfs(mVertex, current, visited); } } /** * @return */ private Node getVertex() { /* * Retrieve any wave front vertex... */ int vDegree, tempVDegree; Node result = null; vDegree = Integer.MAX_VALUE; if (waveFrontVertices != null) { for (Node tempVertex : waveFrontVertices) { if (!removedVertices.contains(tempVertex)) { tempVDegree = getEdges(tempVertex).size(); if (tempVDegree < vDegree) { result = tempVertex; vDegree = tempVDegree; } } } if (result != null) { waveFrontVertices.remove(result); return result; } } /* * ...or a wave center vertex... */ vDegree = Integer.MAX_VALUE; if (waveCenterVertices != null) { for (Node tempVertex : waveCenterVertices) { if (!removedVertices.contains(tempVertex)) { tempVDegree = getEdges(tempVertex).size(); if (tempVDegree < vDegree) { result = tempVertex; vDegree = tempVDegree; } } } if (result != null) { waveCenterVertices.remove(result); return result; } } /* * ...or any lowest degree vertex */ resortVertexlist(); for (Node tempVertex : vertexList) { if (!removedVertices.contains(tempVertex)) { return tempVertex; } } throw new GDTransformationException("No vertex left"); } private void resortVertexlist() { if (removedVertices.isEmpty() && removedEdges.isEmpty()) { Collections.sort(vertexList); return; } // System.out.println("Resorting vertexList as already " + // removedVertices.size() + " vertices (of a total of " // + vertexList.size() + ") and " + removedEdges.size() + // " edges were removed"); /* * We may not delete vertices from the vertex list, as orderVertices * needs this later. So: as we are only interested in the vertices with * low degree, set the (internal) degree of removed vertices to the * total number of vertices */ int vDegree; int highestDegree = vertexList.size(); ArrayList<Node>[] tempVertexList = new ArrayList[highestDegree + 1]; for (int i = 0; i <= highestDegree; i++) { tempVertexList[i] = new ArrayList<Node>(); } for (Node v : vertexList) { if (removedVertices.contains(v)) { vDegree = highestDegree; } else { vDegree = getEdges(v).size(); } tempVertexList[vDegree].add(v); } List<Node> newVertexList = new ArrayList<Node>(vertexList.size()); for (int i = 0; i <= highestDegree; i++) { Collections.shuffle(tempVertexList[i]); newVertexList.addAll(tempVertexList[i]); } vertexList = newVertexList; } private HashMap<String, Edge> getPairEdges(Node n) { HashMap<String, Edge> result = new HashMap<String, Edge>(); Node tempInnerVertex; Edge tempEdge; int otherOuterEnd, otherInnerEnd; // System.out.println("\n\nCalling getPairEdges for vertex " + // n.getIndex()); HashMap<String, Edge> allOuterEdges = getEdges(n); for (Edge tempOuterEdge : allOuterEdges.values()) { // System.out.println("\n"); if (tempOuterEdge.getDst() == n.getIndex()) { otherOuterEnd = tempOuterEdge.getSrc(); } else { otherOuterEnd = tempOuterEdge.getDst(); } // System.out.println("For the edge " + tempOuterEdge + ", " + // otherOuterEnd + " is the other vertex"); HashMap<String, Edge> allInnerEdges = getEdges(g .getNode(otherOuterEnd)); for (Edge tempInnerEdge : allInnerEdges.values()) { // System.out.println(tempInnerEdge + " is an edge for " + // otherOuterEnd); if (tempInnerEdge.getDst() == otherOuterEnd) { otherInnerEnd = tempInnerEdge.getSrc(); } else { otherInnerEnd = tempInnerEdge.getDst(); } if (otherInnerEnd == n.getIndex()) { continue; } tempInnerVertex = g.getNode(otherInnerEnd); if (connected(n, tempInnerVertex)) { tempEdge = new Edge(Math.min(otherInnerEnd, otherOuterEnd), Math.max(otherInnerEnd, otherOuterEnd)); // System.out.println(getEdgeString(tempEdge) + // " is a pair edge of " + otherOuterEnd + " and " + // otherInnerEnd); result.put(getEdgeString(tempEdge), tempEdge); } else { // System.out.println("No pair edge between " + // otherOuterEnd + " and " + otherInnerEnd); } } } return result; } private String getEdgeString(Edge e) { return Math.min(e.getSrc(), e.getDst()) + "->" + Math.max(e.getSrc(), e.getDst()); } }
BenjaminSchiller/GTNA
src/gtna/transformation/gd/SixTollis.java
7,039
// "; rand2: " + randDst2.getIndex());
line_comment
nl
/* =========================================================== * GTNA : Graph-Theoretic Network Analyzer * =========================================================== * * (C) Copyright 2009-2011, by Benjamin Schiller (P2P, TU Darmstadt) * and Contributors * * Project Info: http://www.p2p.tu-darmstadt.de/research/gtna/ * * GTNA 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. * * GTNA 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/>. * * --------------------------------------- * SixTollis.java * --------------------------------------- * (C) Copyright 2009-2011, by Benjamin Schiller (P2P, TU Darmstadt) * and Contributors * * Original Author: Nico; * Contributors: -; * * Changes since 2011-05-17 * --------------------------------------- * */ package gtna.transformation.gd; import gtna.drawing.GraphPlotter; import gtna.graph.Edge; import gtna.graph.Graph; import gtna.graph.Node; import gtna.graph.spanningTree.ParentChild; import gtna.graph.spanningTree.SpanningTree; import gtna.id.ring.RingIdentifier; import gtna.id.ring.RingPartition; import gtna.metrics.edges.EdgeCrossings; import gtna.util.parameter.BooleanParameter; import gtna.util.parameter.DoubleParameter; import gtna.util.parameter.IntParameter; import gtna.util.parameter.Parameter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.TreeSet; /** * @author Nico * */ public class SixTollis extends CircularAbstract { private TreeSet<Node> waveCenterVertices, waveFrontVertices; private List<Node> vertexList, removedVertices; private HashMap<String, Edge> removedEdges; private HashMap<String, Edge>[] additionalEdges; private Edge[][] edges; private ParentChild deepestVertex; private Boolean useOriginalGraphWithoutRemovalList; private Graph g; public SixTollis(int realities, double modulus, boolean wrapAround, GraphPlotter plotter) { super("GDA_SIX_TOLLIS", new Parameter[] { new IntParameter("REALITIES", realities), new DoubleParameter("MODULUS", modulus), new BooleanParameter("WRAPAROUND", wrapAround) }); this.realities = realities; this.modulus = modulus; this.wrapAround = wrapAround; this.graphPlotter = plotter; } public GraphDrawingAbstract clone() { return new SixTollis(realities, modulus, wrapAround, graphPlotter); } @Override public Graph transform(Graph g) { useOriginalGraphWithoutRemovalList = false; initIDSpace(g); if (graphPlotter != null) graphPlotter.plotStartGraph(g, idSpace); EdgeCrossings ec = new EdgeCrossings(); int countCrossings = -1; // countCrossings = ec.calculateCrossings(g.generateEdges(), idSpace, // true); // System.out.println("Crossings randomized: " + countCrossings); this.g = g; /* * Phase 1 */ edges = new Edge[g.getNodes().length][]; Node tempVertex = null; Node currentVertex = null; Node randDst1, randDst2; Edge tempEdge; String tempEdgeString; ArrayList<Node> verticesToAdd; removedEdges = new HashMap<String, Edge>(g.computeNumberOfEdges()); HashMap<String, Edge> pairEdges = null; removedVertices = new ArrayList<Node>(); waveCenterVertices = new TreeSet<Node>(); waveFrontVertices = new TreeSet<Node>(); additionalEdges = new HashMap[g.getNodes().length]; for (int i = 0; i < g.getNodes().length; i++) { additionalEdges[i] = new HashMap<String, Edge>(); } vertexList = Arrays.asList(g.getNodes().clone()); System.out .println("Done with all init stuff, should run following loop from 1 to " + (vertexList.size() - 3)); for (int counter = 1; counter < (vertexList.size() - 3); counter++) { currentVertex = getVertex(); if (counter % (vertexList.size() / 10) == 0) { // System.out.println("Processing " + currentVertex + // " with a degree of " // + getEdges(currentVertex).size() + " (vertex " + counter + // " of " + (vertexList.size() - 3) // + ")"); } pairEdges = getPairEdges(currentVertex); for (Edge singleEdge : pairEdges.values()) { removedEdges.put(getEdgeString(singleEdge), singleEdge); } HashMap<String, Edge> currentVertexConnections = getEdges(currentVertex); int currentVertexDegree = currentVertexConnections.size(); int triangulationEdgesCount = (currentVertexDegree - 1) - pairEdges.size(); int[] outgoingEdges = filterOutgoingEdges(currentVertex, currentVertexConnections); // System.out.print(currentVertex.getIndex() + // " has a current degree of " + currentVertexDegree + ", " // + pairEdges.size() + " pair edges and a need for " + // triangulationEdgesCount // + " triangulation edges - existing edges:"); // for (Edge sE : currentVertexConnections.values()) { // System.out.print(" " + sE); // } // System.out.println(); int firstCounter = 0; int secondCounter = 1; while (triangulationEdgesCount > 0) { randDst1 = g.getNode(outgoingEdges[firstCounter]); randDst2 = g.getNode(outgoingEdges[secondCounter]); if (!randDst1.equals(randDst2) && !removedVertices.contains(randDst1) && !removedVertices.contains(randDst2)) { // System.out.println("rand1: " + randDst1.getIndex() + // "; rand2:<SUF> // System.out.print("Outgoing edges for r1:"); // for (int i : filterOutgoingEdges(randDst1, // getEdges(randDst1))) { // System.out.print(" " + i); // } // System.out.println(""); if (!connected(randDst1, randDst2)) { tempEdge = new Edge(Math.min(randDst1.getIndex(), randDst2.getIndex()), Math.max( randDst1.getIndex(), randDst2.getIndex())); tempEdgeString = getEdgeString(tempEdge); if (!additionalEdges[randDst1.getIndex()] .containsKey(tempEdgeString) && !additionalEdges[randDst2.getIndex()] .containsKey(tempEdgeString)) { // System.out.println("Adding triangulation edge " + // tempEdge); additionalEdges[randDst1.getIndex()].put( tempEdgeString, tempEdge); additionalEdges[randDst2.getIndex()].put( tempEdgeString, tempEdge); triangulationEdgesCount--; } } else { // System.out.println("Vertex " + randDst1.getIndex() + // " is already connected to " // + randDst2.getIndex()); } } secondCounter++; if (secondCounter == currentVertexDegree) { firstCounter++; secondCounter = firstCounter + 1; } if (firstCounter == (currentVertexDegree - 1) && triangulationEdgesCount > 0) throw new GDTransformationException( "Could not find anymore pair edges for " + currentVertex.getIndex()); } /* * Keep track of wave front and wave center vertices! */ verticesToAdd = new ArrayList<Node>(); for (Edge i : getEdges(currentVertex).values()) { int otherEnd; if (i.getDst() == currentVertex.getIndex()) { otherEnd = i.getSrc(); } else { otherEnd = i.getDst(); } tempVertex = g.getNode(otherEnd); if (removedVertices.contains(tempVertex)) { continue; } verticesToAdd.add(tempVertex); } Collections.shuffle(verticesToAdd); waveFrontVertices = new TreeSet<Node>(verticesToAdd); Collections.shuffle(verticesToAdd); waveCenterVertices.addAll(verticesToAdd); removedVertices.add(currentVertex); // System.out.println("Adding " + currentVertex.getIndex() + // " to removedVertices, now containing " // + removedVertices.size() + " vertices"); } LinkedList<Node> orderedVertices = orderVertices(); placeVertices(orderedVertices); /* * To avoid memory leaks: remove stuff that is not needed anymore */ waveCenterVertices = null; waveFrontVertices = null; removedEdges = null; removedVertices = null; // countCrossings = ec.calculateCrossings(g.generateEdges(), idSpace, // true); // System.out.println("Crossings after phase 1: " + countCrossings); if (graphPlotter != null) graphPlotter.plot(g, idSpace, graphPlotter.getBasename() + "-afterPhase1"); // System.out.println("Done with phase 1 of S/T"); reduceCrossingsBySwapping(g); writeIDSpace(g); if (graphPlotter != null) graphPlotter.plotFinalGraph(g, idSpace); // countCrossings = ec.calculateCrossings(g.generateEdges(), idSpace, // true); // System.out.println("Final crossings: " + countCrossings); return g; } private void placeVertices(LinkedList<Node> orderedVertices) { Node lastVertex = null; double lastPos = 0; double posDiff = modulus / partitions.length; /* * Create new RingIdentifiers in the order that was computed... */ RingIdentifier[] ids = new RingIdentifier[g.getNodes().length]; for (Node n : orderedVertices) { ids[n.getIndex()] = new RingIdentifier(lastPos, idSpace.isWrapAround()); // System.out.println("Place " + n.getIndex() + " at " + lastPos); lastPos += posDiff; } /* * ...and assign these ids to the partitions */ lastVertex = orderedVertices.getLast(); for (Node n : orderedVertices) { partitions[n.getIndex()] = new RingPartition( ids[lastVertex.getIndex()], ids[n.getIndex()]); lastVertex = n; } } private LinkedList<Node> orderVertices() { /* * Compute the longest path in a spanning tree created by DFS */ // System.out.println("Starting computation of longest path"); LinkedList<Node> longestPath = longestPath(); // System.out.println("Longest path contains " + longestPath.size() + // " vertices, total number: " // + vertexList.size()); // System.out.println("Characteristics for these vertices:"); // int counter = 0; // int sum = 0; // int[] degrees = new int[longestPath.size()]; // // for ( Node n: longestPath) { // degrees[counter++] = n.getOutDegree(); // sum += n.getOutDegree(); // } // System.out.println("Avg degree: " + ( (double)sum / counter) + // ", median degree: " + degrees[degrees.length/2]); /* * Check which vertices still need to be placed, as they do not lie on * the longestPath */ ArrayList<Node> todoList = new ArrayList<Node>(); todoList.addAll(vertexList); todoList.removeAll(longestPath); Node neighbor, singleVertex; int errors = 0; int modCounter = 0; while (!todoList.isEmpty()) { int neighborPosition = -1; /* * We will walk through the todoList with a counter: there might be * vertices that can not be placed yet, as they do have only * connections to other not yet connected vertices */ singleVertex = todoList.get(modCounter % todoList.size()); int[] outgoingEdges = singleVertex.getOutgoingEdges(); if (outgoingEdges.length == 0) { /* * Current vertex is not connected, so place it anywhere */ neighborPosition = rand.nextInt(longestPath.size()); } else if (outgoingEdges.length == 1 && todoList.contains(g.getNode(outgoingEdges[0]))) { /* * Current vertex has only one connection, and the vertex on the * other end is also in todoList, so also place this one * anywhere to ensure that all vertices get placed - phase 2 * will do the rest */ neighborPosition = rand.nextInt(longestPath.size()); } else { /* * Current vertex has more than one connection (or one * connection to a connected vertex), so let's check them */ for (int singleNeighbor : outgoingEdges) { neighbor = g.getNode(singleNeighbor); neighborPosition = longestPath.indexOf(neighbor); if (neighborPosition > -1) { /* * We found a neighbor that is contained in the list of * connected vertices - stop searching */ break; } } } if (neighborPosition == -1) { /* * The current vertex does not yet have any connection to the * longest path, so place it at a random position */ neighborPosition = rand.nextInt(longestPath.size()); } /* * As a possible position for this vertex is found: remove it from * the todoList and place it in the longestPath. Following elements * get shifted to the right */ todoList.remove(singleVertex); longestPath.add(neighborPosition, singleVertex); } return longestPath; } private ArrayList<Edge> getAllEdges(Node n) { ArrayList<Edge> vertexEdges = new ArrayList<Edge>(); if (edges[n.getIndex()] == null) { edges[n.getIndex()] = n.generateAllEdges(); } for (Edge e : edges[n.getIndex()]) vertexEdges.add(e); if (!useOriginalGraphWithoutRemovalList) { vertexEdges.addAll(additionalEdges[n.getIndex()].values()); } return vertexEdges; } private HashMap<String, Edge> getEdges(Node n) { HashMap<String, Edge> edges = new HashMap<String, Edge>(n.getDegree()); for (Edge i : getAllEdges(n)) { if (!useOriginalGraphWithoutRemovalList && (removedVertices.contains(g.getNode(i.getDst())) || removedVertices .contains(g.getNode(i.getSrc())))) { continue; } edges.put(getEdgeString(i), i); } return edges; } private int[] filterOutgoingEdges(Node n, HashMap<String, Edge> edges) { int[] result = new int[edges.size()]; int edgeCounter = 0; for (Edge sE : edges.values()) { int otherEnd; if (sE.getDst() == n.getIndex()) { otherEnd = sE.getSrc(); } else { otherEnd = sE.getDst(); } result[edgeCounter++] = otherEnd; } return result; } private Boolean connected(Node n, Node m) { int[] edges = filterOutgoingEdges(n, getEdges(n)); for (int sE : edges) { if (sE == m.getIndex()) return true; } return false; } private LinkedList<Integer> findLongestPath(SpanningTree tree, int source, int comingFrom) { LinkedList<Integer> connections = new LinkedList<Integer>(); for (int singleSrc : tree.getChildren(source)) { if (singleSrc == source) continue; connections.add(singleSrc); } connections.add(tree.getParent(source)); connections.removeFirstOccurrence(source); connections.removeFirstOccurrence(comingFrom); if (connections.size() == 0) { connections.add(source); return connections; } LinkedList<Integer> longestPath, tempPath; longestPath = new LinkedList<Integer>(); for (Integer singleConnection : connections) { if (singleConnection == null) { /* * This is the roots parent! */ continue; } tempPath = findLongestPath(tree, singleConnection, source); if (tempPath.size() > longestPath.size()) { longestPath = tempPath; } } longestPath.add(source); return longestPath; } private LinkedList<Node> longestPath() { LinkedList<Node> result = new LinkedList<Node>(); useOriginalGraphWithoutRemovalList = true; int startIndex = 0; Node start; do { start = removedVertices.get(startIndex++); } while (start.getOutDegree() == 0); deepestVertex = new ParentChild(-1, start.getIndex(), -1); // System.out.println("Starting DFS at " + start); HashMap<Integer, ParentChild> parentChildMap = new HashMap<Integer, ParentChild>( vertexList.size()); dfs(start, deepestVertex, parentChildMap); ArrayList<ParentChild> parentChildList = new ArrayList<ParentChild>(); parentChildList.addAll(parentChildMap.values()); SpanningTree tree = new SpanningTree(g, parentChildList); LinkedList<Integer> resultInTree = findLongestPath(tree, deepestVertex.getChild(), -1); for (Integer tempVertex : resultInTree) { result.add(g.getNode(tempVertex)); } return result; } private void dfs(Node n, ParentChild root, HashMap<Integer, ParentChild> visited) { int otherEnd; if (visited.containsKey(n.getIndex())) { return; } ParentChild current = new ParentChild(root.getChild(), n.getIndex(), root.getDepth() + 1); visited.put(n.getIndex(), current); if (current.getDepth() > deepestVertex.getDepth()) { deepestVertex = current; } for (Edge mEdge : getEdges(n).values()) { if (mEdge.getDst() == n.getIndex()) { otherEnd = mEdge.getSrc(); } else { otherEnd = mEdge.getDst(); } Node mVertex = g.getNode(otherEnd); dfs(mVertex, current, visited); } } /** * @return */ private Node getVertex() { /* * Retrieve any wave front vertex... */ int vDegree, tempVDegree; Node result = null; vDegree = Integer.MAX_VALUE; if (waveFrontVertices != null) { for (Node tempVertex : waveFrontVertices) { if (!removedVertices.contains(tempVertex)) { tempVDegree = getEdges(tempVertex).size(); if (tempVDegree < vDegree) { result = tempVertex; vDegree = tempVDegree; } } } if (result != null) { waveFrontVertices.remove(result); return result; } } /* * ...or a wave center vertex... */ vDegree = Integer.MAX_VALUE; if (waveCenterVertices != null) { for (Node tempVertex : waveCenterVertices) { if (!removedVertices.contains(tempVertex)) { tempVDegree = getEdges(tempVertex).size(); if (tempVDegree < vDegree) { result = tempVertex; vDegree = tempVDegree; } } } if (result != null) { waveCenterVertices.remove(result); return result; } } /* * ...or any lowest degree vertex */ resortVertexlist(); for (Node tempVertex : vertexList) { if (!removedVertices.contains(tempVertex)) { return tempVertex; } } throw new GDTransformationException("No vertex left"); } private void resortVertexlist() { if (removedVertices.isEmpty() && removedEdges.isEmpty()) { Collections.sort(vertexList); return; } // System.out.println("Resorting vertexList as already " + // removedVertices.size() + " vertices (of a total of " // + vertexList.size() + ") and " + removedEdges.size() + // " edges were removed"); /* * We may not delete vertices from the vertex list, as orderVertices * needs this later. So: as we are only interested in the vertices with * low degree, set the (internal) degree of removed vertices to the * total number of vertices */ int vDegree; int highestDegree = vertexList.size(); ArrayList<Node>[] tempVertexList = new ArrayList[highestDegree + 1]; for (int i = 0; i <= highestDegree; i++) { tempVertexList[i] = new ArrayList<Node>(); } for (Node v : vertexList) { if (removedVertices.contains(v)) { vDegree = highestDegree; } else { vDegree = getEdges(v).size(); } tempVertexList[vDegree].add(v); } List<Node> newVertexList = new ArrayList<Node>(vertexList.size()); for (int i = 0; i <= highestDegree; i++) { Collections.shuffle(tempVertexList[i]); newVertexList.addAll(tempVertexList[i]); } vertexList = newVertexList; } private HashMap<String, Edge> getPairEdges(Node n) { HashMap<String, Edge> result = new HashMap<String, Edge>(); Node tempInnerVertex; Edge tempEdge; int otherOuterEnd, otherInnerEnd; // System.out.println("\n\nCalling getPairEdges for vertex " + // n.getIndex()); HashMap<String, Edge> allOuterEdges = getEdges(n); for (Edge tempOuterEdge : allOuterEdges.values()) { // System.out.println("\n"); if (tempOuterEdge.getDst() == n.getIndex()) { otherOuterEnd = tempOuterEdge.getSrc(); } else { otherOuterEnd = tempOuterEdge.getDst(); } // System.out.println("For the edge " + tempOuterEdge + ", " + // otherOuterEnd + " is the other vertex"); HashMap<String, Edge> allInnerEdges = getEdges(g .getNode(otherOuterEnd)); for (Edge tempInnerEdge : allInnerEdges.values()) { // System.out.println(tempInnerEdge + " is an edge for " + // otherOuterEnd); if (tempInnerEdge.getDst() == otherOuterEnd) { otherInnerEnd = tempInnerEdge.getSrc(); } else { otherInnerEnd = tempInnerEdge.getDst(); } if (otherInnerEnd == n.getIndex()) { continue; } tempInnerVertex = g.getNode(otherInnerEnd); if (connected(n, tempInnerVertex)) { tempEdge = new Edge(Math.min(otherInnerEnd, otherOuterEnd), Math.max(otherInnerEnd, otherOuterEnd)); // System.out.println(getEdgeString(tempEdge) + // " is a pair edge of " + otherOuterEnd + " and " + // otherInnerEnd); result.put(getEdgeString(tempEdge), tempEdge); } else { // System.out.println("No pair edge between " + // otherOuterEnd + " and " + otherInnerEnd); } } } return result; } private String getEdgeString(Edge e) { return Math.min(e.getSrc(), e.getDst()) + "->" + Math.max(e.getSrc(), e.getDst()); } }
162754_6
/** * Copyright (c) 2002-2011 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j 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 org.neo4j.kernel; import java.io.File; import java.io.FileInputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Properties; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; import java.util.logging.Logger; import javax.transaction.TransactionManager; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.NotFoundException; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.RelationshipType; import org.neo4j.graphdb.Transaction; import org.neo4j.graphdb.TransactionFailureException; import org.neo4j.graphdb.event.KernelEventHandler; import org.neo4j.graphdb.event.TransactionEventHandler; import org.neo4j.graphdb.index.IndexManager; import org.neo4j.helpers.Service; import org.neo4j.kernel.impl.core.KernelPanicEventGenerator; import org.neo4j.kernel.impl.core.LastCommittedTxIdSetter; import org.neo4j.kernel.impl.core.LockReleaser; import org.neo4j.kernel.impl.core.NodeManager; import org.neo4j.kernel.impl.core.RelationshipTypeCreator; import org.neo4j.kernel.impl.core.TransactionEventsSyncHook; import org.neo4j.kernel.impl.core.TxEventSyncHookFactory; import org.neo4j.kernel.impl.index.IndexStore; import org.neo4j.kernel.impl.nioneo.store.FileSystemAbstraction; import org.neo4j.kernel.impl.nioneo.store.StoreId; import org.neo4j.kernel.impl.transaction.LockManager; import org.neo4j.kernel.impl.transaction.TxFinishHook; import org.neo4j.kernel.impl.transaction.TxModule; import org.neo4j.kernel.impl.transaction.xaframework.LogBufferFactory; import org.neo4j.kernel.impl.transaction.xaframework.TxIdGeneratorFactory; import org.neo4j.kernel.impl.util.StringLogger; class EmbeddedGraphDbImpl { private static final long MAX_NODE_ID = IdType.NODE.getMaxValue(); private static final long MAX_RELATIONSHIP_ID = IdType.RELATIONSHIP.getMaxValue(); private static Logger log = Logger.getLogger( EmbeddedGraphDbImpl.class.getName() ); private Transaction placeboTransaction = null; private final GraphDbInstance graphDbInstance; private final GraphDatabaseService graphDbService; private final NodeManager nodeManager; private final String storeDir; private final List<KernelEventHandler> kernelEventHandlers = new CopyOnWriteArrayList<KernelEventHandler>(); private final Collection<TransactionEventHandler<?>> transactionEventHandlers = new CopyOnWriteArraySet<TransactionEventHandler<?>>(); private final KernelPanicEventGenerator kernelPanicEventGenerator = new KernelPanicEventGenerator( kernelEventHandlers ); private final KernelData extensions; private final IndexManagerImpl indexManager; private final StringLogger msgLog; /** * A non-standard way of creating an embedded {@link GraphDatabaseService} * with a set of configuration parameters. Will most likely be removed in * future releases. * * @param storeDir the store directory for the db files * @param fileSystem * @param config configuration parameters */ public EmbeddedGraphDbImpl( String storeDir, StoreId storeId, Map<String, String> inputParams, GraphDatabaseService graphDbService, LockManagerFactory lockManagerFactory, IdGeneratorFactory idGeneratorFactory, RelationshipTypeCreator relTypeCreator, TxIdGeneratorFactory txIdFactory, TxFinishHook finishHook, LastCommittedTxIdSetter lastCommittedTxIdSetter, FileSystemAbstraction fileSystem ) { this.storeDir = storeDir; TxModule txModule = newTxModule( inputParams, finishHook ); LockManager lockManager = lockManagerFactory.create( txModule ); LockReleaser lockReleaser = new LockReleaser( lockManager, txModule.getTxManager() ); final Config config = new Config( graphDbService, storeDir, storeId, inputParams, kernelPanicEventGenerator, txModule, lockManager, lockReleaser, idGeneratorFactory, new SyncHookFactory(), relTypeCreator, txIdFactory.create( txModule.getTxManager() ), lastCommittedTxIdSetter, fileSystem ); /* * LogBufferFactory needs access to the parameters so it has to be added after the default and * user supplied configurations are consolidated */ config.getParams().put( LogBufferFactory.class, CommonFactories.defaultLogBufferFactory() ); graphDbInstance = new GraphDbInstance( storeDir, true, config ); this.msgLog = StringLogger.getLogger( storeDir ); this.graphDbService = graphDbService; IndexStore indexStore = graphDbInstance.getConfig().getIndexStore(); this.indexManager = new IndexManagerImpl( this, indexStore ); extensions = new KernelData() { @Override public Version version() { return Version.getKernel(); } @Override public Config getConfig() { return config; } @Override public Map<Object, Object> getConfigParams() { return config.getParams(); } @Override public GraphDatabaseService graphDatabase() { return EmbeddedGraphDbImpl.this.graphDbService; } }; boolean started = false; try { final KernelExtensionLoader extensionLoader; if ( "false".equalsIgnoreCase( inputParams.get( Config.LOAD_EXTENSIONS ) ) ) { extensionLoader = KernelExtensionLoader.DONT_LOAD; } else { extensionLoader = new KernelExtensionLoader() { private Collection<KernelExtension<?>> loaded; @Override public void configureKernelExtensions() { loaded = extensions.loadExtensionConfigurations( msgLog ); } @Override public void initializeIndexProviders() { extensions.loadIndexImplementations( indexManager, msgLog ); } @Override public void load() { extensions.loadExtensions( loaded, msgLog ); } }; } graphDbInstance.start( graphDbService, extensionLoader ); nodeManager = config.getGraphDbModule().getNodeManager(); /* * IndexManager has to exist before extensions load (so that * it is present and taken into consideration) but after * graphDbInstance is started so that there is access to the * nodeManager. In other words, the start() below has to be here. */ indexManager.start(); extensionLoader.load(); started = true; // must be last } catch ( Error cause ) { msgLog.logMessage( "Startup failed", cause ); throw cause; } catch ( RuntimeException cause ) { msgLog.logMessage( "Startup failed", cause ); throw cause; } finally { // If startup failed, cleanup the extensions - or they will leak if ( !started ) extensions.shutdown( msgLog ); } } private TxModule newTxModule( Map<String, String> inputParams, TxFinishHook rollbackHook ) { return Boolean.parseBoolean( inputParams.get( Config.READ_ONLY ) ) ? new TxModule( true, kernelPanicEventGenerator ) : new TxModule( this.storeDir, kernelPanicEventGenerator, rollbackHook, inputParams.get(Config.TXMANAGER_IMPLEMENTATION) ); } <T> Collection<T> getManagementBeans( Class<T> beanClass ) { KernelExtension<?> jmx = Service.load( KernelExtension.class, "kernel jmx" ); if ( jmx != null ) { Method getManagementBeans = null; Object state = jmx.getState( extensions ); if ( state != null ) { try { getManagementBeans = state.getClass().getMethod( "getManagementBeans", Class.class ); } catch ( Exception e ) { // getManagementBean will be null } } if ( getManagementBeans != null ) { try { @SuppressWarnings( "unchecked" ) Collection<T> result = (Collection<T>) getManagementBeans.invoke( state, beanClass ); if ( result == null ) return Collections.emptySet(); return result; } catch ( InvocationTargetException ex ) { Throwable cause = ex.getTargetException(); if ( cause instanceof Error ) { throw (Error) cause; } if ( cause instanceof RuntimeException ) { throw (RuntimeException) cause; } } catch ( Exception ignored ) { // exception thrown below } } } throw new UnsupportedOperationException( "Neo4j JMX support not enabled" ); } /** * A non-standard Convenience method that loads a standard property file and * converts it into a generic <Code>Map<String,String></CODE>. Will most * likely be removed in future releases. * * @param file the property file to load * @return a map containing the properties from the file * @throws IllegalArgumentException if file does not exist */ public static Map<String,String> loadConfigurations( String file ) { Properties props = new Properties(); try { FileInputStream stream = new FileInputStream( new File( file ) ); try { props.load( stream ); } finally { stream.close(); } } catch ( Exception e ) { throw new IllegalArgumentException( "Unable to load " + file, e ); } Set<Entry<Object,Object>> entries = props.entrySet(); Map<String,String> stringProps = new HashMap<String,String>(); for ( Entry<Object,Object> entry : entries ) { String key = (String) entry.getKey(); String value = (String) entry.getValue(); stringProps.put( key, value ); } return stringProps; } public Node createNode() { return nodeManager.createNode(); } public Node getNodeById( long id ) { if ( id < 0 || id > MAX_NODE_ID ) { throw new NotFoundException( "Node[" + id + "]" ); } return nodeManager.getNodeById( id ); } public Relationship getRelationshipById( long id ) { if ( id < 0 || id > MAX_RELATIONSHIP_ID ) { throw new NotFoundException( "Relationship[" + id + "]" ); } return nodeManager.getRelationshipById( id ); } public Node getReferenceNode() { return nodeManager.getReferenceNode(); } private boolean inShutdown = false; public synchronized void shutdown() { if ( inShutdown ) return; inShutdown = true; try { if ( graphDbInstance.started() ) { try { sendShutdownEvent(); } finally { extensions.shutdown( msgLog ); } } graphDbInstance.shutdown(); } finally { inShutdown = false; } } private void sendShutdownEvent() { for ( KernelEventHandler handler : this.kernelEventHandlers ) { handler.beforeShutdown(); } } public Iterable<RelationshipType> getRelationshipTypes() { return graphDbInstance.getRelationshipTypes(); } /** * @throws TransactionFailureException if unable to start transaction */ public Transaction beginTx() { if ( graphDbInstance.transactionRunning() ) { if ( placeboTransaction == null ) { placeboTransaction = new PlaceboTransaction( graphDbInstance.getTransactionManager() ); } return placeboTransaction; } TransactionManager txManager = graphDbInstance.getTransactionManager(); Transaction result = null; try { txManager.begin(); result = new TopLevelTransaction( txManager ); } catch ( Exception e ) { throw new TransactionFailureException( "Unable to begin transaction", e ); } return result; } /** * Returns a non-standard configuration object. Will most likely be removed * in future releases. * * @return a configuration object */ public Config getConfig() { return graphDbInstance.getConfig(); } @Override public String toString() { return super.toString() + " [" + storeDir + "]"; } public String getStoreDir() { return storeDir; } public Iterable<Node> getAllNodes() { return new Iterable<Node>() { @Override public Iterator<Node> iterator() { long highId = nodeManager.getHighestPossibleIdInUse( Node.class ); return new AllNodesIterator( highId ); } }; } // TODO: temporary all nodes getter, fix this with better implementation // (no NotFoundException to control flow) private class AllNodesIterator implements Iterator<Node> { private final long highId; private long currentNodeId = 0; private Node currentNode = null; AllNodesIterator( long highId ) { this.highId = highId; } @Override public synchronized boolean hasNext() { while ( currentNode == null && currentNodeId <= highId ) { try { currentNode = getNodeById( currentNodeId++ ); } catch ( NotFoundException e ) { // ok we try next } } return currentNode != null; } @Override public synchronized Node next() { if ( !hasNext() ) { throw new NoSuchElementException(); } Node nextNode = currentNode; currentNode = null; return nextNode; } @Override public void remove() { throw new UnsupportedOperationException(); } } <T> TransactionEventHandler<T> registerTransactionEventHandler( TransactionEventHandler<T> handler ) { this.transactionEventHandlers.add( handler ); return handler; } <T> TransactionEventHandler<T> unregisterTransactionEventHandler( TransactionEventHandler<T> handler ) { return unregisterHandler( this.transactionEventHandlers, handler ); } KernelEventHandler registerKernelEventHandler( KernelEventHandler handler ) { if ( this.kernelEventHandlers.contains( handler ) ) { return handler; } // Some algo for putting it in the right place for ( KernelEventHandler registeredHandler : this.kernelEventHandlers ) { KernelEventHandler.ExecutionOrder order = handler.orderComparedTo( registeredHandler ); int index = this.kernelEventHandlers.indexOf( registeredHandler ); if ( order == KernelEventHandler.ExecutionOrder.BEFORE ) { this.kernelEventHandlers.add( index, handler ); return handler; } else if ( order == KernelEventHandler.ExecutionOrder.AFTER ) { this.kernelEventHandlers.add( index + 1, handler ); return handler; } } this.kernelEventHandlers.add( handler ); return handler; } KernelEventHandler unregisterKernelEventHandler( KernelEventHandler handler ) { return unregisterHandler( this.kernelEventHandlers, handler ); } private <T> T unregisterHandler( Collection<?> setOfHandlers, T handler ) { if ( !setOfHandlers.remove( handler ) ) { throw new IllegalStateException( handler + " isn't registered" ); } return handler; } private class SyncHookFactory implements TxEventSyncHookFactory { @Override public TransactionEventsSyncHook create() { return transactionEventHandlers.isEmpty() ? null : new TransactionEventsSyncHook( nodeManager, transactionEventHandlers, getConfig().getTxModule().getTxManager() ); } } IndexManager index() { return this.indexManager; } KernelData getKernelData() { return extensions; } }
BennettSmith/community
kernel/src/main/java/org/neo4j/kernel/EmbeddedGraphDbImpl.java
4,836
// getManagementBean will be null
line_comment
nl
/** * Copyright (c) 2002-2011 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j 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 org.neo4j.kernel; import java.io.File; import java.io.FileInputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Properties; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; import java.util.logging.Logger; import javax.transaction.TransactionManager; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.NotFoundException; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.RelationshipType; import org.neo4j.graphdb.Transaction; import org.neo4j.graphdb.TransactionFailureException; import org.neo4j.graphdb.event.KernelEventHandler; import org.neo4j.graphdb.event.TransactionEventHandler; import org.neo4j.graphdb.index.IndexManager; import org.neo4j.helpers.Service; import org.neo4j.kernel.impl.core.KernelPanicEventGenerator; import org.neo4j.kernel.impl.core.LastCommittedTxIdSetter; import org.neo4j.kernel.impl.core.LockReleaser; import org.neo4j.kernel.impl.core.NodeManager; import org.neo4j.kernel.impl.core.RelationshipTypeCreator; import org.neo4j.kernel.impl.core.TransactionEventsSyncHook; import org.neo4j.kernel.impl.core.TxEventSyncHookFactory; import org.neo4j.kernel.impl.index.IndexStore; import org.neo4j.kernel.impl.nioneo.store.FileSystemAbstraction; import org.neo4j.kernel.impl.nioneo.store.StoreId; import org.neo4j.kernel.impl.transaction.LockManager; import org.neo4j.kernel.impl.transaction.TxFinishHook; import org.neo4j.kernel.impl.transaction.TxModule; import org.neo4j.kernel.impl.transaction.xaframework.LogBufferFactory; import org.neo4j.kernel.impl.transaction.xaframework.TxIdGeneratorFactory; import org.neo4j.kernel.impl.util.StringLogger; class EmbeddedGraphDbImpl { private static final long MAX_NODE_ID = IdType.NODE.getMaxValue(); private static final long MAX_RELATIONSHIP_ID = IdType.RELATIONSHIP.getMaxValue(); private static Logger log = Logger.getLogger( EmbeddedGraphDbImpl.class.getName() ); private Transaction placeboTransaction = null; private final GraphDbInstance graphDbInstance; private final GraphDatabaseService graphDbService; private final NodeManager nodeManager; private final String storeDir; private final List<KernelEventHandler> kernelEventHandlers = new CopyOnWriteArrayList<KernelEventHandler>(); private final Collection<TransactionEventHandler<?>> transactionEventHandlers = new CopyOnWriteArraySet<TransactionEventHandler<?>>(); private final KernelPanicEventGenerator kernelPanicEventGenerator = new KernelPanicEventGenerator( kernelEventHandlers ); private final KernelData extensions; private final IndexManagerImpl indexManager; private final StringLogger msgLog; /** * A non-standard way of creating an embedded {@link GraphDatabaseService} * with a set of configuration parameters. Will most likely be removed in * future releases. * * @param storeDir the store directory for the db files * @param fileSystem * @param config configuration parameters */ public EmbeddedGraphDbImpl( String storeDir, StoreId storeId, Map<String, String> inputParams, GraphDatabaseService graphDbService, LockManagerFactory lockManagerFactory, IdGeneratorFactory idGeneratorFactory, RelationshipTypeCreator relTypeCreator, TxIdGeneratorFactory txIdFactory, TxFinishHook finishHook, LastCommittedTxIdSetter lastCommittedTxIdSetter, FileSystemAbstraction fileSystem ) { this.storeDir = storeDir; TxModule txModule = newTxModule( inputParams, finishHook ); LockManager lockManager = lockManagerFactory.create( txModule ); LockReleaser lockReleaser = new LockReleaser( lockManager, txModule.getTxManager() ); final Config config = new Config( graphDbService, storeDir, storeId, inputParams, kernelPanicEventGenerator, txModule, lockManager, lockReleaser, idGeneratorFactory, new SyncHookFactory(), relTypeCreator, txIdFactory.create( txModule.getTxManager() ), lastCommittedTxIdSetter, fileSystem ); /* * LogBufferFactory needs access to the parameters so it has to be added after the default and * user supplied configurations are consolidated */ config.getParams().put( LogBufferFactory.class, CommonFactories.defaultLogBufferFactory() ); graphDbInstance = new GraphDbInstance( storeDir, true, config ); this.msgLog = StringLogger.getLogger( storeDir ); this.graphDbService = graphDbService; IndexStore indexStore = graphDbInstance.getConfig().getIndexStore(); this.indexManager = new IndexManagerImpl( this, indexStore ); extensions = new KernelData() { @Override public Version version() { return Version.getKernel(); } @Override public Config getConfig() { return config; } @Override public Map<Object, Object> getConfigParams() { return config.getParams(); } @Override public GraphDatabaseService graphDatabase() { return EmbeddedGraphDbImpl.this.graphDbService; } }; boolean started = false; try { final KernelExtensionLoader extensionLoader; if ( "false".equalsIgnoreCase( inputParams.get( Config.LOAD_EXTENSIONS ) ) ) { extensionLoader = KernelExtensionLoader.DONT_LOAD; } else { extensionLoader = new KernelExtensionLoader() { private Collection<KernelExtension<?>> loaded; @Override public void configureKernelExtensions() { loaded = extensions.loadExtensionConfigurations( msgLog ); } @Override public void initializeIndexProviders() { extensions.loadIndexImplementations( indexManager, msgLog ); } @Override public void load() { extensions.loadExtensions( loaded, msgLog ); } }; } graphDbInstance.start( graphDbService, extensionLoader ); nodeManager = config.getGraphDbModule().getNodeManager(); /* * IndexManager has to exist before extensions load (so that * it is present and taken into consideration) but after * graphDbInstance is started so that there is access to the * nodeManager. In other words, the start() below has to be here. */ indexManager.start(); extensionLoader.load(); started = true; // must be last } catch ( Error cause ) { msgLog.logMessage( "Startup failed", cause ); throw cause; } catch ( RuntimeException cause ) { msgLog.logMessage( "Startup failed", cause ); throw cause; } finally { // If startup failed, cleanup the extensions - or they will leak if ( !started ) extensions.shutdown( msgLog ); } } private TxModule newTxModule( Map<String, String> inputParams, TxFinishHook rollbackHook ) { return Boolean.parseBoolean( inputParams.get( Config.READ_ONLY ) ) ? new TxModule( true, kernelPanicEventGenerator ) : new TxModule( this.storeDir, kernelPanicEventGenerator, rollbackHook, inputParams.get(Config.TXMANAGER_IMPLEMENTATION) ); } <T> Collection<T> getManagementBeans( Class<T> beanClass ) { KernelExtension<?> jmx = Service.load( KernelExtension.class, "kernel jmx" ); if ( jmx != null ) { Method getManagementBeans = null; Object state = jmx.getState( extensions ); if ( state != null ) { try { getManagementBeans = state.getClass().getMethod( "getManagementBeans", Class.class ); } catch ( Exception e ) { // getManagementBean will<SUF> } } if ( getManagementBeans != null ) { try { @SuppressWarnings( "unchecked" ) Collection<T> result = (Collection<T>) getManagementBeans.invoke( state, beanClass ); if ( result == null ) return Collections.emptySet(); return result; } catch ( InvocationTargetException ex ) { Throwable cause = ex.getTargetException(); if ( cause instanceof Error ) { throw (Error) cause; } if ( cause instanceof RuntimeException ) { throw (RuntimeException) cause; } } catch ( Exception ignored ) { // exception thrown below } } } throw new UnsupportedOperationException( "Neo4j JMX support not enabled" ); } /** * A non-standard Convenience method that loads a standard property file and * converts it into a generic <Code>Map<String,String></CODE>. Will most * likely be removed in future releases. * * @param file the property file to load * @return a map containing the properties from the file * @throws IllegalArgumentException if file does not exist */ public static Map<String,String> loadConfigurations( String file ) { Properties props = new Properties(); try { FileInputStream stream = new FileInputStream( new File( file ) ); try { props.load( stream ); } finally { stream.close(); } } catch ( Exception e ) { throw new IllegalArgumentException( "Unable to load " + file, e ); } Set<Entry<Object,Object>> entries = props.entrySet(); Map<String,String> stringProps = new HashMap<String,String>(); for ( Entry<Object,Object> entry : entries ) { String key = (String) entry.getKey(); String value = (String) entry.getValue(); stringProps.put( key, value ); } return stringProps; } public Node createNode() { return nodeManager.createNode(); } public Node getNodeById( long id ) { if ( id < 0 || id > MAX_NODE_ID ) { throw new NotFoundException( "Node[" + id + "]" ); } return nodeManager.getNodeById( id ); } public Relationship getRelationshipById( long id ) { if ( id < 0 || id > MAX_RELATIONSHIP_ID ) { throw new NotFoundException( "Relationship[" + id + "]" ); } return nodeManager.getRelationshipById( id ); } public Node getReferenceNode() { return nodeManager.getReferenceNode(); } private boolean inShutdown = false; public synchronized void shutdown() { if ( inShutdown ) return; inShutdown = true; try { if ( graphDbInstance.started() ) { try { sendShutdownEvent(); } finally { extensions.shutdown( msgLog ); } } graphDbInstance.shutdown(); } finally { inShutdown = false; } } private void sendShutdownEvent() { for ( KernelEventHandler handler : this.kernelEventHandlers ) { handler.beforeShutdown(); } } public Iterable<RelationshipType> getRelationshipTypes() { return graphDbInstance.getRelationshipTypes(); } /** * @throws TransactionFailureException if unable to start transaction */ public Transaction beginTx() { if ( graphDbInstance.transactionRunning() ) { if ( placeboTransaction == null ) { placeboTransaction = new PlaceboTransaction( graphDbInstance.getTransactionManager() ); } return placeboTransaction; } TransactionManager txManager = graphDbInstance.getTransactionManager(); Transaction result = null; try { txManager.begin(); result = new TopLevelTransaction( txManager ); } catch ( Exception e ) { throw new TransactionFailureException( "Unable to begin transaction", e ); } return result; } /** * Returns a non-standard configuration object. Will most likely be removed * in future releases. * * @return a configuration object */ public Config getConfig() { return graphDbInstance.getConfig(); } @Override public String toString() { return super.toString() + " [" + storeDir + "]"; } public String getStoreDir() { return storeDir; } public Iterable<Node> getAllNodes() { return new Iterable<Node>() { @Override public Iterator<Node> iterator() { long highId = nodeManager.getHighestPossibleIdInUse( Node.class ); return new AllNodesIterator( highId ); } }; } // TODO: temporary all nodes getter, fix this with better implementation // (no NotFoundException to control flow) private class AllNodesIterator implements Iterator<Node> { private final long highId; private long currentNodeId = 0; private Node currentNode = null; AllNodesIterator( long highId ) { this.highId = highId; } @Override public synchronized boolean hasNext() { while ( currentNode == null && currentNodeId <= highId ) { try { currentNode = getNodeById( currentNodeId++ ); } catch ( NotFoundException e ) { // ok we try next } } return currentNode != null; } @Override public synchronized Node next() { if ( !hasNext() ) { throw new NoSuchElementException(); } Node nextNode = currentNode; currentNode = null; return nextNode; } @Override public void remove() { throw new UnsupportedOperationException(); } } <T> TransactionEventHandler<T> registerTransactionEventHandler( TransactionEventHandler<T> handler ) { this.transactionEventHandlers.add( handler ); return handler; } <T> TransactionEventHandler<T> unregisterTransactionEventHandler( TransactionEventHandler<T> handler ) { return unregisterHandler( this.transactionEventHandlers, handler ); } KernelEventHandler registerKernelEventHandler( KernelEventHandler handler ) { if ( this.kernelEventHandlers.contains( handler ) ) { return handler; } // Some algo for putting it in the right place for ( KernelEventHandler registeredHandler : this.kernelEventHandlers ) { KernelEventHandler.ExecutionOrder order = handler.orderComparedTo( registeredHandler ); int index = this.kernelEventHandlers.indexOf( registeredHandler ); if ( order == KernelEventHandler.ExecutionOrder.BEFORE ) { this.kernelEventHandlers.add( index, handler ); return handler; } else if ( order == KernelEventHandler.ExecutionOrder.AFTER ) { this.kernelEventHandlers.add( index + 1, handler ); return handler; } } this.kernelEventHandlers.add( handler ); return handler; } KernelEventHandler unregisterKernelEventHandler( KernelEventHandler handler ) { return unregisterHandler( this.kernelEventHandlers, handler ); } private <T> T unregisterHandler( Collection<?> setOfHandlers, T handler ) { if ( !setOfHandlers.remove( handler ) ) { throw new IllegalStateException( handler + " isn't registered" ); } return handler; } private class SyncHookFactory implements TxEventSyncHookFactory { @Override public TransactionEventsSyncHook create() { return transactionEventHandlers.isEmpty() ? null : new TransactionEventsSyncHook( nodeManager, transactionEventHandlers, getConfig().getTxModule().getTxManager() ); } } IndexManager index() { return this.indexManager; } KernelData getKernelData() { return extensions; } }
18019_2
/* * Copyright 2009 NaoTeam Humboldt * * 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 de.naoth.xabsleditor.parser; import de.naoth.xabsleditor.parser.XABSLOptionContext.State; import de.naoth.xabsleditor.parser.XABSLOptionContext.Transition; import edu.uci.ics.jung.graph.Graph; import java.io.Reader; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import javax.swing.text.Element; import javax.swing.text.Segment; import org.fife.ui.rsyntaxtextarea.RSyntaxDocument; import org.fife.ui.rsyntaxtextarea.SyntaxConstants; import org.fife.ui.rsyntaxtextarea.parser.AbstractParser; import org.fife.ui.rsyntaxtextarea.parser.ParseResult; import org.fife.ui.rsyntaxtextarea.parser.DefaultParserNotice; import org.fife.ui.rsyntaxtextarea.Token; import org.fife.ui.rsyntaxtextarea.parser.DefaultParseResult; /** * * @author Heinrich Mellmann */ public class XParser extends AbstractParser { public static final String SYNTAX_STYLE_XABSL = "text/xabsl"; private DefaultParseResult result; private XABSLContext xabslContext = null; protected XABSLOptionContext xabslOptionContext = null; private Token currentToken; private String currentComment; private RSyntaxDocument currentDocument; private String currentFileName = null; private XABSLAbstractParser parser; // HACK: make it beter private String fileType = ""; public XParser(XABSLContext xabslContext) { this.xabslContext = xabslContext; if(xabslContext == null) { this.xabslContext = new XABSLContext(); } result = new DefaultParseResult(this); } public XParser() { this.xabslContext = new XABSLContext(); result = new DefaultParseResult(this); } @Override public ParseResult parse(RSyntaxDocument doc, String style) { Element root = doc.getDefaultRootElement(); int lineCount = root.getElementCount(); currentDocument = doc; if (style==null || SyntaxConstants.SYNTAX_STYLE_NONE.equals(style)){ result.clearNotices(); result.setParsedLines(0, lineCount-1); return result; } try { Segment text = new Segment(); doc.getText(0, root.getEndOffset(), text); parse(text); result.setParsedLines(0, lineCount-1); } catch(Exception e) { System.err.println(e.getMessage()); } return result; }//end parse public void parse(Reader reader, String fileName) { this.currentFileName = fileName; parse(reader); } private void parse(Reader reader) { //noticeList.clear(); try { StringBuilder buffer = new StringBuilder(); int c; while((c = reader.read()) > -1) { buffer.append((char) c); } // construct char array char[] charArray = new char[buffer.length()]; buffer.getChars(0, charArray.length, charArray, 0); // create segment Segment text = new Segment(charArray, 0, charArray.length); parse(text); } catch(java.io.IOException ioe) { ioe.printStackTrace(); } } public void parse(Segment text) { result.clearNotices(); XTokenMaker tokenizer = new XTokenMaker(); currentToken = tokenizer.getTokenList(text, Token.NULL, 0); try { if(currentToken != null && currentToken.getType() != Token.NULL) { skipSpace(); if(!isToken(Token.RESERVED_WORD)) { throw new Exception("Token type is " + getNameForTokenType(currentToken.getType()) + " but " + getNameForTokenType(Token.RESERVED_WORD) + " expected."); } if(isToken("option")) { this.parser = new XABSLOptionParser(this); this.fileType = "option"; } else if(isToken("namespace")) { this.parser = new XABSLNamespaceParser(this); this.fileType = "symbol"; } else if(isToken("include")) { this.parser = new XABSLAgentParser(this); this.fileType = "agent"; } else { throw new Exception("Unknown file type."); } } // new files doesn't have any character/token -> can't be parsed! if(this.parser != null) { this.parser.parse(); skipSpace(); } if(currentToken != null && currentToken.getType() != Token.NULL) { throw new Exception("Unexpected end of file."); } } catch(Exception e) { if(this.currentFileName != null) { System.err.println("[ERROR] while parsing " + this.getCurrentFileName() + ":" + getCurrentLine() + " \n " + e.getMessage()); } else { System.err.println("[ERROR] internal parsing:" + getCurrentLine() + " \n " + e.getMessage()); } } }//end parse public String getFileType() { return fileType; } public XABSLAbstractParser getFileParser() { return parser; } public Map<String, State> getStateMap() { if(xabslOptionContext != null) { return this.xabslOptionContext.getStateMap(); } else { return new HashMap<String, State>(); } }//end getStateMap public ArrayList<Transition> getStateTransitionList() { if(xabslOptionContext != null) { return this.xabslOptionContext.getStateTransitionList(); } else { return new ArrayList<Transition>(); } } /** Get a graph suited for visualizing */ public Graph<XabslNode, XabslEdge> getOptionGraph() { if(xabslOptionContext != null) { return this.xabslOptionContext.getOptionGraph(); } else { return null; } }//end getOptionGraph public static String getNameForTokenType(int type) { switch(type) { case Token.COMMENT_DOCUMENTATION: return "COMMENT_DOCUMENTATION"; case Token.COMMENT_EOL: return "COMMENT_EOL"; case Token.COMMENT_MULTILINE: return "COMMENT_MULTILINE"; case Token.DATA_TYPE: return "DATA_TYPE"; case Token.ERROR_CHAR: return "ERROR_CHAR"; case Token.ERROR_IDENTIFIER: return "ERROR_IDENTIFIER"; case Token.ERROR_NUMBER_FORMAT: return "ERROR_NUMBER_FORMAT"; case Token.ERROR_STRING_DOUBLE: return "ERROR_STRING_DOUBLE"; case Token.FUNCTION: return "FUNCTION"; case Token.IDENTIFIER: return "IDENTIFIER"; case Token.LITERAL_BACKQUOTE: return "LITERAL_BACKQUOTE"; case Token.LITERAL_BOOLEAN: return "LITERAL_BOOLEAN"; case Token.LITERAL_CHAR: return "LITERAL_CHAR"; case Token.LITERAL_NUMBER_DECIMAL_INT: return "LITERAL_NUMBER_DECIMAL_INT"; case Token.LITERAL_NUMBER_FLOAT: return "LITERAL_NUMBER_FLOAT"; case Token.LITERAL_NUMBER_HEXADECIMAL: return "LITERAL_NUMBER_HEXADECIMAL"; case Token.LITERAL_STRING_DOUBLE_QUOTE: return "LITERAL_STRING_DOUBLE_QUOTE"; case Token.NULL: return "NULL"; case Token.DEFAULT_NUM_TOKEN_TYPES: return "NUM_TOKEN_TYPES"; case Token.OPERATOR: return "OPERATOR"; case Token.PREPROCESSOR: return "PREPROCESSOR"; case Token.RESERVED_WORD: return "RESERVED_WORD"; case Token.SEPARATOR: return "SEPARATOR"; case Token.VARIABLE: return "VARIABLE"; case Token.WHITESPACE: return "WHITESPACE"; default: return "<unknown: " + type + ">"; } }//end getNameForTokenType public static String getCommentString(String comment) { String result = comment; result = result.replaceFirst("( |\n|\r|\t)*\\/\\/( |\n|\r|\t)*", ""); result = result.replaceFirst("( |\n|\r|\t)*(\\/\\*(\\*)?)( |\n|\r|\t)*", ""); result = result.replaceFirst("( |\n|\r|\t)*\\*\\/( |\n|\r|\t)*", ""); return result; }//end getCommentString private void skipSpace() { while(currentToken != null && (currentToken.getType() == Token.WHITESPACE || currentToken.getType() == Token.NULL || currentToken.getType() == Token.COMMENT_DOCUMENTATION || currentToken.getType() == Token.COMMENT_EOL || currentToken.getType() == Token.COMMENT_MULTILINE)) { // accept only dokumentation comments (i.e. /** ... */) if( //currentToken.type == Token.COMMENT_EOL || //currentToken.type == Token.COMMENT_MULTILINE || currentToken.getType() == Token.COMMENT_DOCUMENTATION ) { currentComment = getCommentString(currentToken.getLexeme()); // remember last coment }else if(currentToken.getType() == Token.NULL) { //currentLine++; } getNextToken(); }//end while }//end skipSpace protected String parseIdentifier() throws Exception { if(isToken(Token.IDENTIFIER) || isToken(Token.ERROR_IDENTIFIER) || isToken(Token.FUNCTION)) { String id = currentToken.getLexeme(); eat(); return id; } else { result.addNotice(new DefaultParserNotice(this, "Identifier expected", getCurrentLine(), currentToken.getOffset(), Math.max(currentToken.getEndOffset(), 2))); } return null; }//end parseIdentifier private void getNextToken() { currentToken = currentToken.getNextToken(); } protected void eat() throws Exception { try { if(currentToken == null) { throw new Exception("Unexpected end of file."); } //System.out.println(currentToken.getLexeme() + " " + currentToken.type); getNextToken(); skipSpace(); } catch(Exception e) { System.out.println("ERROR: " + currentToken.toString()); } }//end eat protected void isEOF() throws Exception { if(currentToken != null) { this.result.addNotice(new DefaultParserNotice(this, "End of file expected.", getCurrentLine(), currentToken.getOffset(), currentToken.getLexeme().length())); throw new Exception("End of file expected."); } }//end isEOF protected boolean isToken(int type) throws Exception { if(currentToken == null) { return false; } return currentToken.getType() == type; }//end isToken protected boolean isToken(String keyWord) throws Exception { if(currentToken == null) { return false; } return keyWord.equals(currentToken.getLexeme()); }//end isTokenAndEat protected boolean isTokenAndEat(int type) throws Exception { if(currentToken == null) { return false; } boolean result = isToken(type); if(!result) { String message = "is " + getNameForTokenType(currentToken.getType()) + " but " + getNameForTokenType(type) + " expected"; this.result.addNotice(new DefaultParserNotice(this, message, getCurrentLine(), currentToken.getOffset(), currentToken.getLexeme().length())); throw new Exception("Unexpected token type: " + message); } eat(); return result; }//end isTokenAndEat protected boolean isTokenAndEat(String keyWord) throws Exception { if(currentToken == null) { return false; } boolean result = isToken(keyWord); if(!result) { String message = keyWord + " expected"; this.result.addNotice(new DefaultParserNotice(this, message, getCurrentLine(), currentToken.getOffset(), currentToken.getLexeme().length())); throw new Exception("Unexpected token: '" + message + "' @ " + currentFileName + ":" + getCurrentLine()); }//end if eat(); return result; }//end isTokenAndEat protected int getCurrentLine() { if(currentDocument == null) { return 0; } Element root = currentDocument.getDefaultRootElement(); return root.getElementIndex(currentToken.getOffset()); }//end getCurrentLine protected String getCurrentFileName() { return currentFileName; } public abstract class XABSLAbstractParser { protected final XParser parent; public XABSLAbstractParser(XParser parent) { this.parent = parent; } abstract void parse() throws Exception; // read comment string only once protected String getCurrentComment() { String comment = this.parent.currentComment; this.parent.currentComment = ""; return comment; }//end getCurrentComment protected XABSLContext getXABSLContext() { return this.parent.xabslContext; }//end getXABSLContext protected Token getCurrentToken() { return this.parent.currentToken; } protected void addNotice(DefaultParserNotice notice) { this.parent.result.addNotice(notice); //this.parent.noticeList.add(notice); } protected boolean isTokenAndEat(String keyWord) throws Exception { return this.parent.isTokenAndEat(keyWord); } protected boolean isTokenAndEat(int type) throws Exception { return this.parent.isTokenAndEat(type); } protected boolean isToken(String keyWord) throws Exception { return this.parent.isToken(keyWord); } protected boolean isToken(int type) throws Exception { return this.parent.isToken(type); } protected void eat() throws Exception { this.parent.eat(); } protected void isEOF() throws Exception { parent.isEOF(); } protected String parseIdentifier() throws Exception { return this.parent.parseIdentifier(); } protected int getCurrentLine(){ return this.parent.getCurrentLine(); } protected String getCurrentFileName(){ return this.parent.getCurrentFileName(); } }//end class AbstractParser }//end class XParser
BerlinUnited/xabsleditor
src/de/naoth/xabsleditor/parser/XParser.java
4,450
// HACK: make it beter
line_comment
nl
/* * Copyright 2009 NaoTeam Humboldt * * 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 de.naoth.xabsleditor.parser; import de.naoth.xabsleditor.parser.XABSLOptionContext.State; import de.naoth.xabsleditor.parser.XABSLOptionContext.Transition; import edu.uci.ics.jung.graph.Graph; import java.io.Reader; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import javax.swing.text.Element; import javax.swing.text.Segment; import org.fife.ui.rsyntaxtextarea.RSyntaxDocument; import org.fife.ui.rsyntaxtextarea.SyntaxConstants; import org.fife.ui.rsyntaxtextarea.parser.AbstractParser; import org.fife.ui.rsyntaxtextarea.parser.ParseResult; import org.fife.ui.rsyntaxtextarea.parser.DefaultParserNotice; import org.fife.ui.rsyntaxtextarea.Token; import org.fife.ui.rsyntaxtextarea.parser.DefaultParseResult; /** * * @author Heinrich Mellmann */ public class XParser extends AbstractParser { public static final String SYNTAX_STYLE_XABSL = "text/xabsl"; private DefaultParseResult result; private XABSLContext xabslContext = null; protected XABSLOptionContext xabslOptionContext = null; private Token currentToken; private String currentComment; private RSyntaxDocument currentDocument; private String currentFileName = null; private XABSLAbstractParser parser; // HACK: make<SUF> private String fileType = ""; public XParser(XABSLContext xabslContext) { this.xabslContext = xabslContext; if(xabslContext == null) { this.xabslContext = new XABSLContext(); } result = new DefaultParseResult(this); } public XParser() { this.xabslContext = new XABSLContext(); result = new DefaultParseResult(this); } @Override public ParseResult parse(RSyntaxDocument doc, String style) { Element root = doc.getDefaultRootElement(); int lineCount = root.getElementCount(); currentDocument = doc; if (style==null || SyntaxConstants.SYNTAX_STYLE_NONE.equals(style)){ result.clearNotices(); result.setParsedLines(0, lineCount-1); return result; } try { Segment text = new Segment(); doc.getText(0, root.getEndOffset(), text); parse(text); result.setParsedLines(0, lineCount-1); } catch(Exception e) { System.err.println(e.getMessage()); } return result; }//end parse public void parse(Reader reader, String fileName) { this.currentFileName = fileName; parse(reader); } private void parse(Reader reader) { //noticeList.clear(); try { StringBuilder buffer = new StringBuilder(); int c; while((c = reader.read()) > -1) { buffer.append((char) c); } // construct char array char[] charArray = new char[buffer.length()]; buffer.getChars(0, charArray.length, charArray, 0); // create segment Segment text = new Segment(charArray, 0, charArray.length); parse(text); } catch(java.io.IOException ioe) { ioe.printStackTrace(); } } public void parse(Segment text) { result.clearNotices(); XTokenMaker tokenizer = new XTokenMaker(); currentToken = tokenizer.getTokenList(text, Token.NULL, 0); try { if(currentToken != null && currentToken.getType() != Token.NULL) { skipSpace(); if(!isToken(Token.RESERVED_WORD)) { throw new Exception("Token type is " + getNameForTokenType(currentToken.getType()) + " but " + getNameForTokenType(Token.RESERVED_WORD) + " expected."); } if(isToken("option")) { this.parser = new XABSLOptionParser(this); this.fileType = "option"; } else if(isToken("namespace")) { this.parser = new XABSLNamespaceParser(this); this.fileType = "symbol"; } else if(isToken("include")) { this.parser = new XABSLAgentParser(this); this.fileType = "agent"; } else { throw new Exception("Unknown file type."); } } // new files doesn't have any character/token -> can't be parsed! if(this.parser != null) { this.parser.parse(); skipSpace(); } if(currentToken != null && currentToken.getType() != Token.NULL) { throw new Exception("Unexpected end of file."); } } catch(Exception e) { if(this.currentFileName != null) { System.err.println("[ERROR] while parsing " + this.getCurrentFileName() + ":" + getCurrentLine() + " \n " + e.getMessage()); } else { System.err.println("[ERROR] internal parsing:" + getCurrentLine() + " \n " + e.getMessage()); } } }//end parse public String getFileType() { return fileType; } public XABSLAbstractParser getFileParser() { return parser; } public Map<String, State> getStateMap() { if(xabslOptionContext != null) { return this.xabslOptionContext.getStateMap(); } else { return new HashMap<String, State>(); } }//end getStateMap public ArrayList<Transition> getStateTransitionList() { if(xabslOptionContext != null) { return this.xabslOptionContext.getStateTransitionList(); } else { return new ArrayList<Transition>(); } } /** Get a graph suited for visualizing */ public Graph<XabslNode, XabslEdge> getOptionGraph() { if(xabslOptionContext != null) { return this.xabslOptionContext.getOptionGraph(); } else { return null; } }//end getOptionGraph public static String getNameForTokenType(int type) { switch(type) { case Token.COMMENT_DOCUMENTATION: return "COMMENT_DOCUMENTATION"; case Token.COMMENT_EOL: return "COMMENT_EOL"; case Token.COMMENT_MULTILINE: return "COMMENT_MULTILINE"; case Token.DATA_TYPE: return "DATA_TYPE"; case Token.ERROR_CHAR: return "ERROR_CHAR"; case Token.ERROR_IDENTIFIER: return "ERROR_IDENTIFIER"; case Token.ERROR_NUMBER_FORMAT: return "ERROR_NUMBER_FORMAT"; case Token.ERROR_STRING_DOUBLE: return "ERROR_STRING_DOUBLE"; case Token.FUNCTION: return "FUNCTION"; case Token.IDENTIFIER: return "IDENTIFIER"; case Token.LITERAL_BACKQUOTE: return "LITERAL_BACKQUOTE"; case Token.LITERAL_BOOLEAN: return "LITERAL_BOOLEAN"; case Token.LITERAL_CHAR: return "LITERAL_CHAR"; case Token.LITERAL_NUMBER_DECIMAL_INT: return "LITERAL_NUMBER_DECIMAL_INT"; case Token.LITERAL_NUMBER_FLOAT: return "LITERAL_NUMBER_FLOAT"; case Token.LITERAL_NUMBER_HEXADECIMAL: return "LITERAL_NUMBER_HEXADECIMAL"; case Token.LITERAL_STRING_DOUBLE_QUOTE: return "LITERAL_STRING_DOUBLE_QUOTE"; case Token.NULL: return "NULL"; case Token.DEFAULT_NUM_TOKEN_TYPES: return "NUM_TOKEN_TYPES"; case Token.OPERATOR: return "OPERATOR"; case Token.PREPROCESSOR: return "PREPROCESSOR"; case Token.RESERVED_WORD: return "RESERVED_WORD"; case Token.SEPARATOR: return "SEPARATOR"; case Token.VARIABLE: return "VARIABLE"; case Token.WHITESPACE: return "WHITESPACE"; default: return "<unknown: " + type + ">"; } }//end getNameForTokenType public static String getCommentString(String comment) { String result = comment; result = result.replaceFirst("( |\n|\r|\t)*\\/\\/( |\n|\r|\t)*", ""); result = result.replaceFirst("( |\n|\r|\t)*(\\/\\*(\\*)?)( |\n|\r|\t)*", ""); result = result.replaceFirst("( |\n|\r|\t)*\\*\\/( |\n|\r|\t)*", ""); return result; }//end getCommentString private void skipSpace() { while(currentToken != null && (currentToken.getType() == Token.WHITESPACE || currentToken.getType() == Token.NULL || currentToken.getType() == Token.COMMENT_DOCUMENTATION || currentToken.getType() == Token.COMMENT_EOL || currentToken.getType() == Token.COMMENT_MULTILINE)) { // accept only dokumentation comments (i.e. /** ... */) if( //currentToken.type == Token.COMMENT_EOL || //currentToken.type == Token.COMMENT_MULTILINE || currentToken.getType() == Token.COMMENT_DOCUMENTATION ) { currentComment = getCommentString(currentToken.getLexeme()); // remember last coment }else if(currentToken.getType() == Token.NULL) { //currentLine++; } getNextToken(); }//end while }//end skipSpace protected String parseIdentifier() throws Exception { if(isToken(Token.IDENTIFIER) || isToken(Token.ERROR_IDENTIFIER) || isToken(Token.FUNCTION)) { String id = currentToken.getLexeme(); eat(); return id; } else { result.addNotice(new DefaultParserNotice(this, "Identifier expected", getCurrentLine(), currentToken.getOffset(), Math.max(currentToken.getEndOffset(), 2))); } return null; }//end parseIdentifier private void getNextToken() { currentToken = currentToken.getNextToken(); } protected void eat() throws Exception { try { if(currentToken == null) { throw new Exception("Unexpected end of file."); } //System.out.println(currentToken.getLexeme() + " " + currentToken.type); getNextToken(); skipSpace(); } catch(Exception e) { System.out.println("ERROR: " + currentToken.toString()); } }//end eat protected void isEOF() throws Exception { if(currentToken != null) { this.result.addNotice(new DefaultParserNotice(this, "End of file expected.", getCurrentLine(), currentToken.getOffset(), currentToken.getLexeme().length())); throw new Exception("End of file expected."); } }//end isEOF protected boolean isToken(int type) throws Exception { if(currentToken == null) { return false; } return currentToken.getType() == type; }//end isToken protected boolean isToken(String keyWord) throws Exception { if(currentToken == null) { return false; } return keyWord.equals(currentToken.getLexeme()); }//end isTokenAndEat protected boolean isTokenAndEat(int type) throws Exception { if(currentToken == null) { return false; } boolean result = isToken(type); if(!result) { String message = "is " + getNameForTokenType(currentToken.getType()) + " but " + getNameForTokenType(type) + " expected"; this.result.addNotice(new DefaultParserNotice(this, message, getCurrentLine(), currentToken.getOffset(), currentToken.getLexeme().length())); throw new Exception("Unexpected token type: " + message); } eat(); return result; }//end isTokenAndEat protected boolean isTokenAndEat(String keyWord) throws Exception { if(currentToken == null) { return false; } boolean result = isToken(keyWord); if(!result) { String message = keyWord + " expected"; this.result.addNotice(new DefaultParserNotice(this, message, getCurrentLine(), currentToken.getOffset(), currentToken.getLexeme().length())); throw new Exception("Unexpected token: '" + message + "' @ " + currentFileName + ":" + getCurrentLine()); }//end if eat(); return result; }//end isTokenAndEat protected int getCurrentLine() { if(currentDocument == null) { return 0; } Element root = currentDocument.getDefaultRootElement(); return root.getElementIndex(currentToken.getOffset()); }//end getCurrentLine protected String getCurrentFileName() { return currentFileName; } public abstract class XABSLAbstractParser { protected final XParser parent; public XABSLAbstractParser(XParser parent) { this.parent = parent; } abstract void parse() throws Exception; // read comment string only once protected String getCurrentComment() { String comment = this.parent.currentComment; this.parent.currentComment = ""; return comment; }//end getCurrentComment protected XABSLContext getXABSLContext() { return this.parent.xabslContext; }//end getXABSLContext protected Token getCurrentToken() { return this.parent.currentToken; } protected void addNotice(DefaultParserNotice notice) { this.parent.result.addNotice(notice); //this.parent.noticeList.add(notice); } protected boolean isTokenAndEat(String keyWord) throws Exception { return this.parent.isTokenAndEat(keyWord); } protected boolean isTokenAndEat(int type) throws Exception { return this.parent.isTokenAndEat(type); } protected boolean isToken(String keyWord) throws Exception { return this.parent.isToken(keyWord); } protected boolean isToken(int type) throws Exception { return this.parent.isToken(type); } protected void eat() throws Exception { this.parent.eat(); } protected void isEOF() throws Exception { parent.isEOF(); } protected String parseIdentifier() throws Exception { return this.parent.parseIdentifier(); } protected int getCurrentLine(){ return this.parent.getCurrentLine(); } protected String getCurrentFileName(){ return this.parent.getCurrentFileName(); } }//end class AbstractParser }//end class XParser
22196_13
package nl.noscope.emeraldextraction.objects; import android.util.Log; import nl.saxion.act.playground.model.GameBoard; import nl.saxion.act.playground.model.GameObject; /** * De miner is ons speler object, deze verplaatst zich dan ook steeds * * @author Boyd */ public class Miner extends GameObject { public static final String MINER_IMAGE = "miner"; public static final String MINER_UP = "up"; public static final String MINER_DOWN = "down"; public static final String MINER_LEFT = "links"; public static final String MINER_RIGHT = "rechts"; int position = 0; /** Returns the ImageId of the image to show. */ @Override public String getImageId() { if (position == 1) { return MINER_LEFT; } else if (position == 2) { return MINER_RIGHT; } else if (position == 3) { return MINER_UP; } else if (position == 4) { return MINER_DOWN; } else { return MINER_IMAGE; } } public void walkLeft(GameBoard gameBoard) { position = 1; int newPosX = getPositionX() - 1; int newPosY = getPositionY(); StateCheck(newPosX, newPosY, gameBoard, position); } public void walkRight(GameBoard gameBoard) { position = 2; int newPosX = getPositionX() + 1; int newPosY = getPositionY(); StateCheck(newPosX, newPosY, gameBoard, position); } public void walkUp(GameBoard gameBoard) { position = 3; int newPosX = getPositionX(); int newPosY = getPositionY() - 1; StateCheck(newPosX, newPosY, gameBoard, position); } public void walkDown(GameBoard gameBoard) { position = 4; int newPosX = getPositionX(); int newPosY = getPositionY() + 1; StateCheck(newPosX, newPosY, gameBoard, position); } private void StateCheck(int newPosX, int newPosY, GameBoard gameBoard, int direction) { // Als de nieuwe positie naast het bord is doet hij niks if (newPosX >= gameBoard.getWidth() - 1 || newPosX == 0) { return; } else if (newPosY >= gameBoard.getHeight() - 1 || newPosY == 0){ return; } // Kijk of er een object is op het nieuwe punt GameObject objectAtNewPos = gameBoard.getObject(newPosX, newPosY); if (objectAtNewPos != null) { // Miner kan niet door een aantal objecten heen if (objectAtNewPos instanceof Stone) { return; } if (objectAtNewPos instanceof Iron) { return; } if (objectAtNewPos instanceof Minecart) { return; } if (objectAtNewPos instanceof Emerald) { // Je kan een emerald niet naar beneden drukken if (direction == 4) { return; } // Duw de emerald omhoog als er vrije ruimte boven is if (direction == 3) { if (gameBoard.getObject(newPosX, newPosY - 1) == null) { gameBoard.moveObject(objectAtNewPos, newPosX, newPosY - 1); } else { return; } } // Duw de emerald naar links als er vrije ruimte links van de emerald is if (direction == 1) { if (gameBoard.getObject(newPosX - 1, newPosY) == null) { gameBoard.moveObject(objectAtNewPos, newPosX -1, newPosY); } else { return; } } // Duw de emerald naar rechts als er vrije ruimte rechts van de emerald is if (direction == 2) { if (gameBoard.getObject(newPosX + 1, newPosY) == null) { gameBoard.moveObject(objectAtNewPos, newPosX + 1, newPosY); } else { return ; } } } if (objectAtNewPos instanceof StoneMove) { // Je kan een emerald niet naar beneden drukken if (direction == 4) { return; } // Duw de emerald omhoog als er vrije ruimte boven is if (direction == 3) { if (gameBoard.getObject(newPosX, newPosY - 1) == null) { gameBoard.moveObject(objectAtNewPos, newPosX, newPosY - 1); } else { return; } } // Duw de emerald naar links als er vrije ruimte links van de emerald is if (direction == 1) { if (gameBoard.getObject(newPosX - 1, newPosY) == null) { gameBoard.moveObject(objectAtNewPos, newPosX -1, newPosY); } else { return; } } // Duw de emerald naar rechts als er vrije ruimte rechts van de emerald is if (direction == 2) { if (gameBoard.getObject(newPosX + 1, newPosY) == null) { gameBoard.moveObject(objectAtNewPos, newPosX + 1, newPosY); } else { return ; } } } if (objectAtNewPos instanceof Sand) { gameBoard.removeObject(objectAtNewPos); } } // Verplaats de miner naar zijn nieuwe positie //Log.d("Miner", "Ik verplaats nu de miner"); gameBoard.moveObject(this, newPosX, newPosY); //gameBoard.updateView(); Log.d("Miner", "Miner verplaatst"); } @Override public void onTouched(GameBoard gameBoard) { // TODO Auto-generated method stub } }
Bernardez/Speelveld
src/nl/noscope/emeraldextraction/objects/Miner.java
1,801
// Verplaats de miner naar zijn nieuwe positie
line_comment
nl
package nl.noscope.emeraldextraction.objects; import android.util.Log; import nl.saxion.act.playground.model.GameBoard; import nl.saxion.act.playground.model.GameObject; /** * De miner is ons speler object, deze verplaatst zich dan ook steeds * * @author Boyd */ public class Miner extends GameObject { public static final String MINER_IMAGE = "miner"; public static final String MINER_UP = "up"; public static final String MINER_DOWN = "down"; public static final String MINER_LEFT = "links"; public static final String MINER_RIGHT = "rechts"; int position = 0; /** Returns the ImageId of the image to show. */ @Override public String getImageId() { if (position == 1) { return MINER_LEFT; } else if (position == 2) { return MINER_RIGHT; } else if (position == 3) { return MINER_UP; } else if (position == 4) { return MINER_DOWN; } else { return MINER_IMAGE; } } public void walkLeft(GameBoard gameBoard) { position = 1; int newPosX = getPositionX() - 1; int newPosY = getPositionY(); StateCheck(newPosX, newPosY, gameBoard, position); } public void walkRight(GameBoard gameBoard) { position = 2; int newPosX = getPositionX() + 1; int newPosY = getPositionY(); StateCheck(newPosX, newPosY, gameBoard, position); } public void walkUp(GameBoard gameBoard) { position = 3; int newPosX = getPositionX(); int newPosY = getPositionY() - 1; StateCheck(newPosX, newPosY, gameBoard, position); } public void walkDown(GameBoard gameBoard) { position = 4; int newPosX = getPositionX(); int newPosY = getPositionY() + 1; StateCheck(newPosX, newPosY, gameBoard, position); } private void StateCheck(int newPosX, int newPosY, GameBoard gameBoard, int direction) { // Als de nieuwe positie naast het bord is doet hij niks if (newPosX >= gameBoard.getWidth() - 1 || newPosX == 0) { return; } else if (newPosY >= gameBoard.getHeight() - 1 || newPosY == 0){ return; } // Kijk of er een object is op het nieuwe punt GameObject objectAtNewPos = gameBoard.getObject(newPosX, newPosY); if (objectAtNewPos != null) { // Miner kan niet door een aantal objecten heen if (objectAtNewPos instanceof Stone) { return; } if (objectAtNewPos instanceof Iron) { return; } if (objectAtNewPos instanceof Minecart) { return; } if (objectAtNewPos instanceof Emerald) { // Je kan een emerald niet naar beneden drukken if (direction == 4) { return; } // Duw de emerald omhoog als er vrije ruimte boven is if (direction == 3) { if (gameBoard.getObject(newPosX, newPosY - 1) == null) { gameBoard.moveObject(objectAtNewPos, newPosX, newPosY - 1); } else { return; } } // Duw de emerald naar links als er vrije ruimte links van de emerald is if (direction == 1) { if (gameBoard.getObject(newPosX - 1, newPosY) == null) { gameBoard.moveObject(objectAtNewPos, newPosX -1, newPosY); } else { return; } } // Duw de emerald naar rechts als er vrije ruimte rechts van de emerald is if (direction == 2) { if (gameBoard.getObject(newPosX + 1, newPosY) == null) { gameBoard.moveObject(objectAtNewPos, newPosX + 1, newPosY); } else { return ; } } } if (objectAtNewPos instanceof StoneMove) { // Je kan een emerald niet naar beneden drukken if (direction == 4) { return; } // Duw de emerald omhoog als er vrije ruimte boven is if (direction == 3) { if (gameBoard.getObject(newPosX, newPosY - 1) == null) { gameBoard.moveObject(objectAtNewPos, newPosX, newPosY - 1); } else { return; } } // Duw de emerald naar links als er vrije ruimte links van de emerald is if (direction == 1) { if (gameBoard.getObject(newPosX - 1, newPosY) == null) { gameBoard.moveObject(objectAtNewPos, newPosX -1, newPosY); } else { return; } } // Duw de emerald naar rechts als er vrije ruimte rechts van de emerald is if (direction == 2) { if (gameBoard.getObject(newPosX + 1, newPosY) == null) { gameBoard.moveObject(objectAtNewPos, newPosX + 1, newPosY); } else { return ; } } } if (objectAtNewPos instanceof Sand) { gameBoard.removeObject(objectAtNewPos); } } // Verplaats de<SUF> //Log.d("Miner", "Ik verplaats nu de miner"); gameBoard.moveObject(this, newPosX, newPosY); //gameBoard.updateView(); Log.d("Miner", "Miner verplaatst"); } @Override public void onTouched(GameBoard gameBoard) { // TODO Auto-generated method stub } }
24560_13
package be.uantwerpen.minelabs.model; import be.uantwerpen.minelabs.Minelabs; import be.uantwerpen.minelabs.crafting.molecules.Atom; import be.uantwerpen.minelabs.crafting.molecules.Bond; import be.uantwerpen.minelabs.crafting.molecules.MoleculeGraphJsonFormat; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.mojang.datafixers.util.Pair; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.renderer.v1.Renderer; import net.fabricmc.fabric.api.renderer.v1.RendererAccess; import net.fabricmc.fabric.api.renderer.v1.mesh.Mesh; import net.fabricmc.fabric.api.renderer.v1.mesh.MeshBuilder; import net.fabricmc.fabric.api.renderer.v1.mesh.MutableQuadView; import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; import net.fabricmc.fabric.api.renderer.v1.model.FabricBakedModel; import net.fabricmc.fabric.api.renderer.v1.render.RenderContext; import net.minecraft.block.BlockState; import net.minecraft.client.render.model.*; import net.minecraft.client.render.model.json.JsonUnbakedModel; import net.minecraft.client.render.model.json.ModelOverrideList; import net.minecraft.client.render.model.json.ModelTransformation; import net.minecraft.client.texture.Sprite; import net.minecraft.client.texture.SpriteAtlasTexture; import net.minecraft.client.util.SpriteIdentifier; import net.minecraft.item.ItemStack; import net.minecraft.util.Identifier; import net.minecraft.util.JsonHelper; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; import net.minecraft.util.math.Quaternion; import net.minecraft.util.math.Vec3f; import net.minecraft.util.math.random.Random; import net.minecraft.world.BlockRenderView; import java.io.Reader; import java.util.*; import java.util.function.Function; import java.util.function.Supplier; @Environment(EnvType.CLIENT) public class MoleculeModel implements UnbakedModel, BakedModel, FabricBakedModel { private Mesh mesh; private static final SpriteIdentifier SPRITE_ID = new SpriteIdentifier(SpriteAtlasTexture.BLOCK_ATLAS_TEXTURE, new Identifier(Minelabs.MOD_ID, "block/mologram/sphere")); private Sprite SPRITE; private static final Identifier DEFAULT_BLOCK_MODEL = new Identifier("minecraft:block/block"); private ModelTransformation transformation; Map<String, Pair<Atom, Vec3f>> positions; Map<Pair<String, String>, Bond> bonds; private final float RADIUS = 0.10f; private final float MARGIN = 0.04f; public MoleculeModel(Map<String, Pair<Atom, Vec3f>> positions, Map<Pair<String, String>, Bond> bondMap) { this.positions = positions; this.bonds = bondMap; } public Collection<Identifier> getModelDependencies() { return List.of(DEFAULT_BLOCK_MODEL); } @Override public Collection<SpriteIdentifier> getTextureDependencies(Function<Identifier, UnbakedModel> unbakedModelGetter, Set<Pair<String, String>> unresolvedTextureReferences) { return List.of(SPRITE_ID); } @Override public List<BakedQuad> getQuads(BlockState state, Direction face, Random random) { // Don't need because we use FabricBakedModel instead. However, it's better to not return null in case some mod decides to call this function. return Collections.emptyList(); } @Override public boolean useAmbientOcclusion() { return true; // we want the block to have a shadow depending on the adjacent blocks } @Override public boolean isVanillaAdapter() { return false; // False to trigger FabricBakedModel rendering } @Override public boolean isBuiltin() { return false; } @Override public boolean hasDepth() { return false; } @Override public boolean isSideLit() { return false; } @Override public Sprite getParticleSprite() { return SPRITE; } @Override public ModelTransformation getTransformation() { return transformation; } @Override public ModelOverrideList getOverrides() { return ModelOverrideList.EMPTY; } @Override public BakedModel bake(ModelLoader loader, Function<SpriteIdentifier, Sprite> textureGetter, ModelBakeSettings rotationContainer, Identifier modelId) { SPRITE = textureGetter.apply(SPRITE_ID); JsonUnbakedModel defaultBlockModel = (JsonUnbakedModel) loader.getOrLoadModel(DEFAULT_BLOCK_MODEL); // Get its ModelTransformation transformation = defaultBlockModel.getTransformations(); // Build the mesh using the Renderer API Renderer renderer = RendererAccess.INSTANCE.getRenderer(); MeshBuilder builder = renderer.meshBuilder(); QuadEmitter emitter = builder.getEmitter(); //makeSphere(emitter, center, radius); positions.forEach((s, atomVec3fPair) -> makeSphere(emitter, atomVec3fPair.getSecond(), RADIUS, atomVec3fPair.getFirst().getColor())); //RGB color in hex bonds.forEach((s, bond) -> makeBond(emitter, positions.get(s.getFirst()).getSecond(), positions.get(s.getSecond()).getSecond(), positions.get(s.getFirst()).getFirst().getColor(), positions.get(s.getSecond()).getFirst().getColor(), bond)); mesh = builder.build(); return this; } /** * @param emitter : QuadEmitter * @param pos1 : position Atom 1 * @param pos2 : position Atom 2 * @param bond : type of bond between Atoms */ private void makeBond(QuadEmitter emitter, Vec3f pos1, Vec3f pos2, int color1, int color2, Bond bond) { if (bond == Bond.COVALENT_ZERO){ return; } Vec3f pos_diff = pos2.copy(); pos_diff.subtract(pos1); float pos_norm = ModelUtil.norm(pos_diff); List<Vec3f[]> bondQuads = switch (bond){ case COVALENT_SINGLE -> getSingleBondVertices(pos_norm); case COVALENT_DOUBLE -> getDoubleBondVertices(pos_norm); case COVALENT_TRIPLE -> getTripleBondVertices(pos_norm); default -> throw new IllegalStateException("Unknown bond count " + bond); }; // direction is the orientation of the bond Vec3f direction = pos2.copy(); direction.subtract(pos1); direction.normalize(); // compute angle between positive X and direction float angle = (float) Math.acos(direction.dot(Vec3f.POSITIVE_X)); // rotate within plane described by two vectors direction.cross(Vec3f.POSITIVE_X); direction.normalize(); Quaternion rotation = direction.getRadialQuaternion(angle); rotation.conjugate(); ModelUtil.transformQuads(bondQuads, v -> v.rotate(rotation)); ModelUtil.transformQuads(bondQuads, v -> v.add(pos1)); for (Vec3f[] quad : bondQuads) { for (int i = 0; i < 4; i++) { emitter.pos(i, quad[i]); Vec3f norm = ModelUtil.normalOnVertices(quad[i],quad[(((i+1 % 4) + 4) % 4)], quad[(((i-1 % 4) + 4) % 4)]); //zodat licht van beam lijkt te komen emitter.normal(i, norm); } float p = 15f / 32f; emitter.sprite(0, 0, p, p); emitter.sprite(1, 0, p, 0.5f); emitter.sprite(2, 0, 0.5f, 0.5f); emitter.sprite(3, 0, 0.5f, p); emitter.spriteBake(0, SPRITE, MutableQuadView.BAKE_ROTATE_NONE); // Enable texture usage if (color1==color2){ int color = color1; //TODO darken integer color emitter.spriteColor(0, color, color, color, color); } else { emitter.spriteColor(0, color1, color1, color2, color2); } // Add the quad to the mesh emitter.emit(); } } public List<Vec3f[]> getSingleBondVertices(float len) { float a = 0.05f; return getUnitBeam(len, a); } public List<Vec3f[]> getDoubleBondVertices(float len) { float a = 0.045f; float offset = 0.035f; List<Vec3f[]> quads = new ArrayList<>(); quads.addAll(ModelUtil.transformQuads(getUnitBeam(len, a), v -> v.add(0, offset, 0))); quads.addAll(ModelUtil.transformQuads(getUnitBeam(len, a), v -> v.add(0, -offset, 0))); return quads; } public List<Vec3f[]> getTripleBondVertices(float len) { float a = 0.038f; float offset = 0.045f; List<Vec3f[]> quads = new ArrayList<>(); Vec3f offsetDirection = new Vec3f(0, offset, 0); quads.addAll(ModelUtil.transformQuads(getUnitBeam(len, a), v -> v.add(offsetDirection))); offsetDirection.rotate(Vec3f.POSITIVE_X.getDegreesQuaternion(120)); quads.addAll(ModelUtil.transformQuads(getUnitBeam(len, a), v -> v.add(offsetDirection))); offsetDirection.rotate(Vec3f.POSITIVE_X.getDegreesQuaternion(120)); quads.addAll(ModelUtil.transformQuads(getUnitBeam(len, a), v -> v.add(offsetDirection))); return quads; } /** * Create a cuboid (beam) of specified length and square endpoint. * Bean follows and is centered around the x-axis. * @param len : length of beam * @param b : size of square (endpoint) */ public List<Vec3f[]> getUnitBeam(float len, float b){ float a = b/2; len -= 2 * RADIUS - 2 * MARGIN; List<Vec3f[]> quads = new ArrayList<>(); quads.add(new Vec3f[]{//links new Vec3f(0, -a, -a), new Vec3f(0, a, -a), new Vec3f(len, a, -a), new Vec3f(len, -a, -a), }); quads.add(new Vec3f[]{//rechts new Vec3f(0, a, a), new Vec3f(0, -a, a), new Vec3f(len, -a, a), new Vec3f(len, a, a), }); quads.add(new Vec3f[]{//onder new Vec3f(0, -a, a), new Vec3f(0, -a, -a), new Vec3f(len, -a, -a), new Vec3f(len, -a, a), }); quads.add(new Vec3f[]{//boven new Vec3f(0, a, -a), new Vec3f(0, a, a), new Vec3f(len, a, a), new Vec3f(len, a, -a), }); ModelUtil.transformQuads(quads, v -> v.add(RADIUS - MARGIN, 0, 0)); return quads; } private void makeSphere(QuadEmitter emitter, Vec3f center, float radius, int color) { for (Vec3f[] quad : getSphereVertices(center, radius)) { for (int i = 0; i < 4; i++) { emitter.pos(i, quad[i]); Vec3f norm = ModelUtil.normalOnVertices(quad[i],quad[(((i+1 % 4) + 4) % 4)], quad[(((i-1 % 4) + 4) % 4)]); //zodat licht van beam lijkt te komen emitter.normal(i, norm); } float p = 1; emitter.sprite(0, 0, p, p); emitter.sprite(1, 0, p, 0); emitter.sprite(2, 0, 0, 0); emitter.sprite(3, 0, 0, p); emitter.spriteBake(0, SPRITE, MutableQuadView.BAKE_ROTATE_NONE); // Enable texture usage emitter.spriteColor(0, color, color, color, color); // Add the quad to the mesh emitter.emit(); } } public List<Vec3f[]> getSphereVertices(Vec3f center, float r) { center.add(0.5f, 0.5f, 0.5f); List<Vec3f[]> quads = new ArrayList<>(); int RESOLUTION = 2; float offset = 1/(float) Math.sqrt(3); //moet genormaliseerd zijn Vec3f[] face = { new Vec3f(-offset, offset, -offset), new Vec3f(offset, offset, -offset), new Vec3f(offset, -offset, -offset), new Vec3f(-offset, -offset, -offset), }; recursiveSubdivision(face, RESOLUTION, quads); face = new Vec3f[]{ new Vec3f(-offset, -offset, offset), new Vec3f(offset, -offset, offset), new Vec3f(offset, offset, offset), new Vec3f(-offset, offset, offset), }; recursiveSubdivision(face, RESOLUTION, quads); face = new Vec3f[]{ new Vec3f(-offset, -offset, offset), new Vec3f(-offset, offset, offset), new Vec3f(-offset, offset, -offset), new Vec3f(-offset, -offset, -offset), }; recursiveSubdivision(face, RESOLUTION, quads); face = new Vec3f[]{ new Vec3f(offset, -offset, -offset), new Vec3f(offset, offset, -offset), new Vec3f(offset, offset, offset), new Vec3f(offset, -offset, offset), }; recursiveSubdivision(face, RESOLUTION, quads); face = new Vec3f[]{ new Vec3f(-offset, -offset, -offset), new Vec3f(offset, -offset, -offset), new Vec3f(offset, -offset, offset), new Vec3f(-offset, -offset, offset), }; recursiveSubdivision(face, RESOLUTION, quads); face = new Vec3f[]{ new Vec3f(-offset, offset, offset), new Vec3f(offset, offset, offset), new Vec3f(offset, offset, -offset), new Vec3f(-offset, offset, -offset), }; recursiveSubdivision(face, RESOLUTION, quads); ModelUtil.transformQuads(quads, v -> v.scale(r)); ModelUtil.transformQuads(quads, v -> v.add(center)); return quads; } private List<Vec3f[]> recursiveSubdivision(Vec3f[] quad, int RESOLUTION, List<Vec3f[]> quads){ if (RESOLUTION<=0){ quads.add(quad); } else { Vec3f va = quad[0].copy(); va.add(quad[1]); va.normalize(); Vec3f vb = quad[0].copy(); vb.add(quad[3]); vb.normalize(); Vec3f vc = quad[0].copy(); vc.add(quad[2]); vc.normalize(); Vec3f vd = quad[2].copy(); vd.add(quad[1]); vd.normalize(); Vec3f ve = quad[3].copy(); ve.add(quad[2]); ve.normalize(); recursiveSubdivision(new Vec3f[] {quad[0].copy(), va.copy(), vc.copy(), vb.copy()}, RESOLUTION-1, quads); recursiveSubdivision(new Vec3f[] {va.copy(), quad[1].copy(), vd.copy(), vc.copy()}, RESOLUTION-1, quads); recursiveSubdivision(new Vec3f[] {vc.copy(), vd.copy(), quad[2].copy(), ve.copy()}, RESOLUTION-1, quads); recursiveSubdivision(new Vec3f[] {vb.copy(), vc.copy(), ve.copy(), quad[3].copy()}, RESOLUTION-1, quads); } return quads; } @Override public void emitBlockQuads(BlockRenderView blockRenderView, BlockState blockState, BlockPos blockPos, Supplier<Random> supplier, RenderContext renderContext) { // We just render the mesh renderContext.meshConsumer().accept(mesh); } @Override public void emitItemQuads(ItemStack stack, Supplier<Random> randomSupplier, RenderContext context) { context.meshConsumer().accept(mesh); } public static MoleculeModel deserialize(Reader reader) { Map<String, Pair<Atom, Vec3f>> positions = new HashMap<>(); Map<Pair<String, String>, Bond> bondMap = new HashMap<>(); JsonObject structure = JsonHelper.deserialize(reader).getAsJsonObject("structure"); JsonArray atoms = structure.getAsJsonArray("atoms"); for (JsonElement atom: atoms) { JsonObject atomJson = atom.getAsJsonObject(); String key = atomJson.get("key").getAsString(); Atom readAtom = Atom.getBySymbol(atomJson.get("atom").getAsString()); JsonArray pos = atomJson.getAsJsonArray("position"); Vec3f vec3f = Vec3f.ZERO.copy(); float scale_factor = 4.5f; int i = 0; for (JsonElement position: pos) { switch (i) { case 0 -> { vec3f.add(position.getAsFloat() / scale_factor, 0, 0); i++; } case 1 -> { vec3f.add(0, position.getAsFloat() / scale_factor, 0); i++; } case 2 -> { vec3f.add(0, 0, position.getAsFloat() / scale_factor); i++; } } } positions.put(key, new Pair<>(readAtom, vec3f.copy())); vec3f.set(0,0,0); } JsonArray bonds = structure.getAsJsonArray("bonds"); for (JsonElement bond: bonds) { MoleculeGraphJsonFormat.BondJson bondJson = new Gson().fromJson(bond.getAsJsonObject(), MoleculeGraphJsonFormat.BondJson.class); bondMap.put(new Pair<>(bondJson.from, bondJson.to), Bond.get(bondJson.bondOrder)); } return new MoleculeModel(positions, bondMap); } }
BertJorissen/MineLabs
src/main/java/be/uantwerpen/minelabs/model/MoleculeModel.java
5,526
//TODO darken integer color
line_comment
nl
package be.uantwerpen.minelabs.model; import be.uantwerpen.minelabs.Minelabs; import be.uantwerpen.minelabs.crafting.molecules.Atom; import be.uantwerpen.minelabs.crafting.molecules.Bond; import be.uantwerpen.minelabs.crafting.molecules.MoleculeGraphJsonFormat; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.mojang.datafixers.util.Pair; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.renderer.v1.Renderer; import net.fabricmc.fabric.api.renderer.v1.RendererAccess; import net.fabricmc.fabric.api.renderer.v1.mesh.Mesh; import net.fabricmc.fabric.api.renderer.v1.mesh.MeshBuilder; import net.fabricmc.fabric.api.renderer.v1.mesh.MutableQuadView; import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; import net.fabricmc.fabric.api.renderer.v1.model.FabricBakedModel; import net.fabricmc.fabric.api.renderer.v1.render.RenderContext; import net.minecraft.block.BlockState; import net.minecraft.client.render.model.*; import net.minecraft.client.render.model.json.JsonUnbakedModel; import net.minecraft.client.render.model.json.ModelOverrideList; import net.minecraft.client.render.model.json.ModelTransformation; import net.minecraft.client.texture.Sprite; import net.minecraft.client.texture.SpriteAtlasTexture; import net.minecraft.client.util.SpriteIdentifier; import net.minecraft.item.ItemStack; import net.minecraft.util.Identifier; import net.minecraft.util.JsonHelper; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; import net.minecraft.util.math.Quaternion; import net.minecraft.util.math.Vec3f; import net.minecraft.util.math.random.Random; import net.minecraft.world.BlockRenderView; import java.io.Reader; import java.util.*; import java.util.function.Function; import java.util.function.Supplier; @Environment(EnvType.CLIENT) public class MoleculeModel implements UnbakedModel, BakedModel, FabricBakedModel { private Mesh mesh; private static final SpriteIdentifier SPRITE_ID = new SpriteIdentifier(SpriteAtlasTexture.BLOCK_ATLAS_TEXTURE, new Identifier(Minelabs.MOD_ID, "block/mologram/sphere")); private Sprite SPRITE; private static final Identifier DEFAULT_BLOCK_MODEL = new Identifier("minecraft:block/block"); private ModelTransformation transformation; Map<String, Pair<Atom, Vec3f>> positions; Map<Pair<String, String>, Bond> bonds; private final float RADIUS = 0.10f; private final float MARGIN = 0.04f; public MoleculeModel(Map<String, Pair<Atom, Vec3f>> positions, Map<Pair<String, String>, Bond> bondMap) { this.positions = positions; this.bonds = bondMap; } public Collection<Identifier> getModelDependencies() { return List.of(DEFAULT_BLOCK_MODEL); } @Override public Collection<SpriteIdentifier> getTextureDependencies(Function<Identifier, UnbakedModel> unbakedModelGetter, Set<Pair<String, String>> unresolvedTextureReferences) { return List.of(SPRITE_ID); } @Override public List<BakedQuad> getQuads(BlockState state, Direction face, Random random) { // Don't need because we use FabricBakedModel instead. However, it's better to not return null in case some mod decides to call this function. return Collections.emptyList(); } @Override public boolean useAmbientOcclusion() { return true; // we want the block to have a shadow depending on the adjacent blocks } @Override public boolean isVanillaAdapter() { return false; // False to trigger FabricBakedModel rendering } @Override public boolean isBuiltin() { return false; } @Override public boolean hasDepth() { return false; } @Override public boolean isSideLit() { return false; } @Override public Sprite getParticleSprite() { return SPRITE; } @Override public ModelTransformation getTransformation() { return transformation; } @Override public ModelOverrideList getOverrides() { return ModelOverrideList.EMPTY; } @Override public BakedModel bake(ModelLoader loader, Function<SpriteIdentifier, Sprite> textureGetter, ModelBakeSettings rotationContainer, Identifier modelId) { SPRITE = textureGetter.apply(SPRITE_ID); JsonUnbakedModel defaultBlockModel = (JsonUnbakedModel) loader.getOrLoadModel(DEFAULT_BLOCK_MODEL); // Get its ModelTransformation transformation = defaultBlockModel.getTransformations(); // Build the mesh using the Renderer API Renderer renderer = RendererAccess.INSTANCE.getRenderer(); MeshBuilder builder = renderer.meshBuilder(); QuadEmitter emitter = builder.getEmitter(); //makeSphere(emitter, center, radius); positions.forEach((s, atomVec3fPair) -> makeSphere(emitter, atomVec3fPair.getSecond(), RADIUS, atomVec3fPair.getFirst().getColor())); //RGB color in hex bonds.forEach((s, bond) -> makeBond(emitter, positions.get(s.getFirst()).getSecond(), positions.get(s.getSecond()).getSecond(), positions.get(s.getFirst()).getFirst().getColor(), positions.get(s.getSecond()).getFirst().getColor(), bond)); mesh = builder.build(); return this; } /** * @param emitter : QuadEmitter * @param pos1 : position Atom 1 * @param pos2 : position Atom 2 * @param bond : type of bond between Atoms */ private void makeBond(QuadEmitter emitter, Vec3f pos1, Vec3f pos2, int color1, int color2, Bond bond) { if (bond == Bond.COVALENT_ZERO){ return; } Vec3f pos_diff = pos2.copy(); pos_diff.subtract(pos1); float pos_norm = ModelUtil.norm(pos_diff); List<Vec3f[]> bondQuads = switch (bond){ case COVALENT_SINGLE -> getSingleBondVertices(pos_norm); case COVALENT_DOUBLE -> getDoubleBondVertices(pos_norm); case COVALENT_TRIPLE -> getTripleBondVertices(pos_norm); default -> throw new IllegalStateException("Unknown bond count " + bond); }; // direction is the orientation of the bond Vec3f direction = pos2.copy(); direction.subtract(pos1); direction.normalize(); // compute angle between positive X and direction float angle = (float) Math.acos(direction.dot(Vec3f.POSITIVE_X)); // rotate within plane described by two vectors direction.cross(Vec3f.POSITIVE_X); direction.normalize(); Quaternion rotation = direction.getRadialQuaternion(angle); rotation.conjugate(); ModelUtil.transformQuads(bondQuads, v -> v.rotate(rotation)); ModelUtil.transformQuads(bondQuads, v -> v.add(pos1)); for (Vec3f[] quad : bondQuads) { for (int i = 0; i < 4; i++) { emitter.pos(i, quad[i]); Vec3f norm = ModelUtil.normalOnVertices(quad[i],quad[(((i+1 % 4) + 4) % 4)], quad[(((i-1 % 4) + 4) % 4)]); //zodat licht van beam lijkt te komen emitter.normal(i, norm); } float p = 15f / 32f; emitter.sprite(0, 0, p, p); emitter.sprite(1, 0, p, 0.5f); emitter.sprite(2, 0, 0.5f, 0.5f); emitter.sprite(3, 0, 0.5f, p); emitter.spriteBake(0, SPRITE, MutableQuadView.BAKE_ROTATE_NONE); // Enable texture usage if (color1==color2){ int color = color1; //TODO darken<SUF> emitter.spriteColor(0, color, color, color, color); } else { emitter.spriteColor(0, color1, color1, color2, color2); } // Add the quad to the mesh emitter.emit(); } } public List<Vec3f[]> getSingleBondVertices(float len) { float a = 0.05f; return getUnitBeam(len, a); } public List<Vec3f[]> getDoubleBondVertices(float len) { float a = 0.045f; float offset = 0.035f; List<Vec3f[]> quads = new ArrayList<>(); quads.addAll(ModelUtil.transformQuads(getUnitBeam(len, a), v -> v.add(0, offset, 0))); quads.addAll(ModelUtil.transformQuads(getUnitBeam(len, a), v -> v.add(0, -offset, 0))); return quads; } public List<Vec3f[]> getTripleBondVertices(float len) { float a = 0.038f; float offset = 0.045f; List<Vec3f[]> quads = new ArrayList<>(); Vec3f offsetDirection = new Vec3f(0, offset, 0); quads.addAll(ModelUtil.transformQuads(getUnitBeam(len, a), v -> v.add(offsetDirection))); offsetDirection.rotate(Vec3f.POSITIVE_X.getDegreesQuaternion(120)); quads.addAll(ModelUtil.transformQuads(getUnitBeam(len, a), v -> v.add(offsetDirection))); offsetDirection.rotate(Vec3f.POSITIVE_X.getDegreesQuaternion(120)); quads.addAll(ModelUtil.transformQuads(getUnitBeam(len, a), v -> v.add(offsetDirection))); return quads; } /** * Create a cuboid (beam) of specified length and square endpoint. * Bean follows and is centered around the x-axis. * @param len : length of beam * @param b : size of square (endpoint) */ public List<Vec3f[]> getUnitBeam(float len, float b){ float a = b/2; len -= 2 * RADIUS - 2 * MARGIN; List<Vec3f[]> quads = new ArrayList<>(); quads.add(new Vec3f[]{//links new Vec3f(0, -a, -a), new Vec3f(0, a, -a), new Vec3f(len, a, -a), new Vec3f(len, -a, -a), }); quads.add(new Vec3f[]{//rechts new Vec3f(0, a, a), new Vec3f(0, -a, a), new Vec3f(len, -a, a), new Vec3f(len, a, a), }); quads.add(new Vec3f[]{//onder new Vec3f(0, -a, a), new Vec3f(0, -a, -a), new Vec3f(len, -a, -a), new Vec3f(len, -a, a), }); quads.add(new Vec3f[]{//boven new Vec3f(0, a, -a), new Vec3f(0, a, a), new Vec3f(len, a, a), new Vec3f(len, a, -a), }); ModelUtil.transformQuads(quads, v -> v.add(RADIUS - MARGIN, 0, 0)); return quads; } private void makeSphere(QuadEmitter emitter, Vec3f center, float radius, int color) { for (Vec3f[] quad : getSphereVertices(center, radius)) { for (int i = 0; i < 4; i++) { emitter.pos(i, quad[i]); Vec3f norm = ModelUtil.normalOnVertices(quad[i],quad[(((i+1 % 4) + 4) % 4)], quad[(((i-1 % 4) + 4) % 4)]); //zodat licht van beam lijkt te komen emitter.normal(i, norm); } float p = 1; emitter.sprite(0, 0, p, p); emitter.sprite(1, 0, p, 0); emitter.sprite(2, 0, 0, 0); emitter.sprite(3, 0, 0, p); emitter.spriteBake(0, SPRITE, MutableQuadView.BAKE_ROTATE_NONE); // Enable texture usage emitter.spriteColor(0, color, color, color, color); // Add the quad to the mesh emitter.emit(); } } public List<Vec3f[]> getSphereVertices(Vec3f center, float r) { center.add(0.5f, 0.5f, 0.5f); List<Vec3f[]> quads = new ArrayList<>(); int RESOLUTION = 2; float offset = 1/(float) Math.sqrt(3); //moet genormaliseerd zijn Vec3f[] face = { new Vec3f(-offset, offset, -offset), new Vec3f(offset, offset, -offset), new Vec3f(offset, -offset, -offset), new Vec3f(-offset, -offset, -offset), }; recursiveSubdivision(face, RESOLUTION, quads); face = new Vec3f[]{ new Vec3f(-offset, -offset, offset), new Vec3f(offset, -offset, offset), new Vec3f(offset, offset, offset), new Vec3f(-offset, offset, offset), }; recursiveSubdivision(face, RESOLUTION, quads); face = new Vec3f[]{ new Vec3f(-offset, -offset, offset), new Vec3f(-offset, offset, offset), new Vec3f(-offset, offset, -offset), new Vec3f(-offset, -offset, -offset), }; recursiveSubdivision(face, RESOLUTION, quads); face = new Vec3f[]{ new Vec3f(offset, -offset, -offset), new Vec3f(offset, offset, -offset), new Vec3f(offset, offset, offset), new Vec3f(offset, -offset, offset), }; recursiveSubdivision(face, RESOLUTION, quads); face = new Vec3f[]{ new Vec3f(-offset, -offset, -offset), new Vec3f(offset, -offset, -offset), new Vec3f(offset, -offset, offset), new Vec3f(-offset, -offset, offset), }; recursiveSubdivision(face, RESOLUTION, quads); face = new Vec3f[]{ new Vec3f(-offset, offset, offset), new Vec3f(offset, offset, offset), new Vec3f(offset, offset, -offset), new Vec3f(-offset, offset, -offset), }; recursiveSubdivision(face, RESOLUTION, quads); ModelUtil.transformQuads(quads, v -> v.scale(r)); ModelUtil.transformQuads(quads, v -> v.add(center)); return quads; } private List<Vec3f[]> recursiveSubdivision(Vec3f[] quad, int RESOLUTION, List<Vec3f[]> quads){ if (RESOLUTION<=0){ quads.add(quad); } else { Vec3f va = quad[0].copy(); va.add(quad[1]); va.normalize(); Vec3f vb = quad[0].copy(); vb.add(quad[3]); vb.normalize(); Vec3f vc = quad[0].copy(); vc.add(quad[2]); vc.normalize(); Vec3f vd = quad[2].copy(); vd.add(quad[1]); vd.normalize(); Vec3f ve = quad[3].copy(); ve.add(quad[2]); ve.normalize(); recursiveSubdivision(new Vec3f[] {quad[0].copy(), va.copy(), vc.copy(), vb.copy()}, RESOLUTION-1, quads); recursiveSubdivision(new Vec3f[] {va.copy(), quad[1].copy(), vd.copy(), vc.copy()}, RESOLUTION-1, quads); recursiveSubdivision(new Vec3f[] {vc.copy(), vd.copy(), quad[2].copy(), ve.copy()}, RESOLUTION-1, quads); recursiveSubdivision(new Vec3f[] {vb.copy(), vc.copy(), ve.copy(), quad[3].copy()}, RESOLUTION-1, quads); } return quads; } @Override public void emitBlockQuads(BlockRenderView blockRenderView, BlockState blockState, BlockPos blockPos, Supplier<Random> supplier, RenderContext renderContext) { // We just render the mesh renderContext.meshConsumer().accept(mesh); } @Override public void emitItemQuads(ItemStack stack, Supplier<Random> randomSupplier, RenderContext context) { context.meshConsumer().accept(mesh); } public static MoleculeModel deserialize(Reader reader) { Map<String, Pair<Atom, Vec3f>> positions = new HashMap<>(); Map<Pair<String, String>, Bond> bondMap = new HashMap<>(); JsonObject structure = JsonHelper.deserialize(reader).getAsJsonObject("structure"); JsonArray atoms = structure.getAsJsonArray("atoms"); for (JsonElement atom: atoms) { JsonObject atomJson = atom.getAsJsonObject(); String key = atomJson.get("key").getAsString(); Atom readAtom = Atom.getBySymbol(atomJson.get("atom").getAsString()); JsonArray pos = atomJson.getAsJsonArray("position"); Vec3f vec3f = Vec3f.ZERO.copy(); float scale_factor = 4.5f; int i = 0; for (JsonElement position: pos) { switch (i) { case 0 -> { vec3f.add(position.getAsFloat() / scale_factor, 0, 0); i++; } case 1 -> { vec3f.add(0, position.getAsFloat() / scale_factor, 0); i++; } case 2 -> { vec3f.add(0, 0, position.getAsFloat() / scale_factor); i++; } } } positions.put(key, new Pair<>(readAtom, vec3f.copy())); vec3f.set(0,0,0); } JsonArray bonds = structure.getAsJsonArray("bonds"); for (JsonElement bond: bonds) { MoleculeGraphJsonFormat.BondJson bondJson = new Gson().fromJson(bond.getAsJsonObject(), MoleculeGraphJsonFormat.BondJson.class); bondMap.put(new Pair<>(bondJson.from, bondJson.to), Bond.get(bondJson.bondOrder)); } return new MoleculeModel(positions, bondMap); } }
69567_3
/* * Copyright the State of the Netherlands * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package nl.overheid.aerius.shared.domain.v2.source.road; /** * NSL road speed types. */ public enum RoadSpeedType { /** * "buitenweg algemeen". * * Typisch buitenwegverkeer, een gemiddelde snelheid van ongeveer 60 km/h, gemiddeld ca. 0,2 stops per afgelegde km. */ NON_URBAN_TRAFFIC("B"), /** * "normaal stadsverkeer". * * Typisch stadsverkeer met een redelijke mate van congestie, een gemiddelde snelheid tussen de 15 en 30 km/h, * gemiddeld ca. 2 stops per afgelegde km. */ URBAN_TRAFFIC_NORMAL("C"), /** * "stagnerend stadsverkeer". * * Stadsverkeer met een grote mate van congestie, een gemiddelde snelheid kleiner dan 15 km/h, gemiddeld ca. 10 stops per afgelegde km. */ URBAN_TRAFFIC_STAGNATING("D"), /** * "stadsverkeer met minder congestie". * * Stadsverkeer met een relatief groter aandeel "free-flow" rijgedrag, een gemiddelde snelheid tussen de 30 en 45 km/h, * gemiddeld ca. 1,5 stop per afgelegde km. */ URBAN_TRAFFIC_FREE_FLOW("E"), /** * "buitenweg nationale weg". * * Typisch buitenwegverkeer op een nationale weg. */ NATIONAL_ROAD("NATIONAL_ROAD"); private final String legacyValue; private RoadSpeedType(final String legacyValue) { this.legacyValue = legacyValue; } public static RoadSpeedType safeLegacyValueOf(final String snelheid) { RoadSpeedType result = null; for (final RoadSpeedType speedType : values()) { if (speedType.legacyValue.equalsIgnoreCase(snelheid)) { result = speedType; } } return result; } }
BertScholten/IMAER-java
source/imaer-shared/src/main/java/nl/overheid/aerius/shared/domain/v2/source/road/RoadSpeedType.java
777
/** * "normaal stadsverkeer". * * Typisch stadsverkeer met een redelijke mate van congestie, een gemiddelde snelheid tussen de 15 en 30 km/h, * gemiddeld ca. 2 stops per afgelegde km. */
block_comment
nl
/* * Copyright the State of the Netherlands * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package nl.overheid.aerius.shared.domain.v2.source.road; /** * NSL road speed types. */ public enum RoadSpeedType { /** * "buitenweg algemeen". * * Typisch buitenwegverkeer, een gemiddelde snelheid van ongeveer 60 km/h, gemiddeld ca. 0,2 stops per afgelegde km. */ NON_URBAN_TRAFFIC("B"), /** * "normaal stadsverkeer". <SUF>*/ URBAN_TRAFFIC_NORMAL("C"), /** * "stagnerend stadsverkeer". * * Stadsverkeer met een grote mate van congestie, een gemiddelde snelheid kleiner dan 15 km/h, gemiddeld ca. 10 stops per afgelegde km. */ URBAN_TRAFFIC_STAGNATING("D"), /** * "stadsverkeer met minder congestie". * * Stadsverkeer met een relatief groter aandeel "free-flow" rijgedrag, een gemiddelde snelheid tussen de 30 en 45 km/h, * gemiddeld ca. 1,5 stop per afgelegde km. */ URBAN_TRAFFIC_FREE_FLOW("E"), /** * "buitenweg nationale weg". * * Typisch buitenwegverkeer op een nationale weg. */ NATIONAL_ROAD("NATIONAL_ROAD"); private final String legacyValue; private RoadSpeedType(final String legacyValue) { this.legacyValue = legacyValue; } public static RoadSpeedType safeLegacyValueOf(final String snelheid) { RoadSpeedType result = null; for (final RoadSpeedType speedType : values()) { if (speedType.legacyValue.equalsIgnoreCase(snelheid)) { result = speedType; } } return result; } }
34272_0
package vm; /** * * @author Filip Vondrášek (filip at vondrasek.net) */ public class Main { public static void main(String[] args) { VM vm = new VM(); vm.debug = false; vm.printInstructions = false; vm.run(); } }
Berzeger/MI-RUN
src/vm/Main.java
94
/** * * @author Filip Vondrášek (filip at vondrasek.net) */
block_comment
nl
package vm; /** * * @author Filip Vondrášek<SUF>*/ public class Main { public static void main(String[] args) { VM vm = new VM(); vm.debug = false; vm.printInstructions = false; vm.run(); } }
106383_11
/* * Created on 16 July 2006 * Copyright (C) Azureus Software, Inc, All Rights Reserved. * * 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 com.biglybt.ui.swt; import java.util.ArrayList; import java.util.Locale; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.FocusAdapter; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.TraverseEvent; import org.eclipse.swt.events.TraverseListener; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.*; import com.biglybt.core.internat.MessageText; import com.biglybt.core.util.AERunnable; import com.biglybt.core.util.Debug; import com.biglybt.core.util.SimpleTimer; import com.biglybt.core.util.SystemTime; import com.biglybt.core.util.TimerEvent; import com.biglybt.core.util.UrlUtils; import com.biglybt.ui.swt.components.LinkLabel; import com.biglybt.ui.swt.components.shell.ShellFactory; import com.biglybt.ui.swt.pifimpl.AbstractUISWTInputReceiver; import com.biglybt.ui.swt.utils.DragDropUtils; import com.biglybt.pif.ui.UIInputValidator; /** * @author amc1 * Based on CategoryAdderWindow. */ public class SimpleTextEntryWindow extends AbstractUISWTInputReceiver { private Display display; private Shell parent_shell; private Shell shell; private int textLimit; private boolean resizeable; private String loc_size_config_key; private Combo text_entry_combo; private StyledText text_entry_text; private Label link_label; private boolean detect_urls; private boolean special_escape_handling; private boolean user_hit_escape; private java.util.List<VerifyListener> verify_listeners = new ArrayList<>(); public SimpleTextEntryWindow() { } public SimpleTextEntryWindow(String sTitleKey, String sLabelKey) { setTitle(sTitleKey); setMessage(sLabelKey); } public SimpleTextEntryWindow(String sTitleKey, String sLabelKey, boolean bMultiLine) { setTitle(sTitleKey); setMessage(sLabelKey); setMultiLine(bMultiLine); } public void initTexts(String sTitleKey, String[] p0, String sLabelKey, String[] p1) { setLocalisedTitle(MessageText.getString(sTitleKey, p0)); setLocalisedMessage(MessageText.getString(sLabelKey, p1)); } public void addVerifyListener( VerifyListener l ) { verify_listeners.add( l ); } @Override protected void promptForInput() { Utils.execSWTThread(new Runnable() { @Override public void run() { promptForInput0(); if (receiver_listener == null) { Utils.readAndDispatchLoop( shell ); } } }, receiver_listener != null); } private void promptForInput0() { //shell = com.biglybt.ui.swt.components.shell.ShellFactory.createShell(Utils.findAnyShell(), SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); // link to active shell, so that when it closes, the input box closes (good for config windows) Shell parent = parent_shell; if ( parent_shell == null ){ parent = Display.getDefault().getActiveShell(); if ( parent != null && parent.getData( ShellFactory.NOT_A_GOOD_PARENT ) != null ){ parent = null; } } if (parent == null) { parent = Utils.findAnyShell(); } shell = com.biglybt.ui.swt.components.shell.ShellFactory.createShell(parent, SWT.DIALOG_TRIM | (resizeable?SWT.RESIZE:0 )); display = shell.getDisplay(); if (this.title != null) { String str = this.title; if ( textLimit > 0 ){ str += " (" + MessageText.getString( "label.limit") + " " + textLimit + ")"; } shell.setText(str); } Utils.setShellIcon(shell); GridLayout layout = new GridLayout(); layout.verticalSpacing = 10; shell.setLayout(layout); int width_hint; int height_hint; if ( loc_size_config_key != null && Utils.hasShellMetricsConfig( loc_size_config_key )){ width_hint = -1; height_hint = -1; }else{ width_hint = (this.width_hint == -1) ? 330 : this.width_hint; height_hint = (this.height_hint == -1) ? -1 : this.height_hint; } // Process any messages. GridData gridData = null; for (int i=0; i<this.messages.length; i++) { String msg = messages[i]; gridData = resizeable?new GridData(GridData.FILL_HORIZONTAL):new GridData(); gridData.widthHint = width_hint; if ( msg.toLowerCase(Locale.US).contains( "<a href" )){ StyledText text = new StyledText( shell, SWT.NULL ); text.setEditable( false ); text.setBackground( shell.getBackground()); Utils.setTextWithURLs(text, msg,false); text.setLayoutData(gridData); }else{ Label label = new Label(shell, SWT.WRAP); label.setText( msg ); label.setLayoutData(gridData); } } // Create Text object with pre-entered text. final Scrollable text_entry; if (this.choices != null) { int text_entry_flags = SWT.DROP_DOWN; if (!this.choices_allow_edit) { text_entry_flags |= SWT.READ_ONLY; } text_entry_combo = new Combo(shell, text_entry_flags); text_entry_combo.setItems(this.choices); if (textLimit > 0) { text_entry_combo.setTextLimit(textLimit); } text_entry_text = null; text_entry = text_entry_combo; } else { // We may, at a later date, allow more customisable behaviour w.r.t. to this. // (e.g. "Should we wrap this, should we provide H_SCROLL capabilities" etc.) int text_entry_flags = SWT.BORDER; if (this.multiline_mode) { text_entry_flags |= SWT.MULTI | SWT.V_SCROLL | SWT.WRAP; } else { text_entry_flags |= SWT.SINGLE; } text_entry_text = new StyledText(shell, text_entry_flags); if (textLimit > 0) { text_entry_text.setTextLimit(textLimit); } text_entry_combo = null; text_entry = text_entry_text; } if (this.preentered_text != null) { if (text_entry_text != null) { text_entry_text.setText(this.preentered_text); if (this.select_preentered_text) { int[] range = this.select_preentered_text_range; if ( range == null || range.length != 2 ){ text_entry_text.selectAll(); }else{ try{ text_entry_text.setSelection( range[0], range[1] ); }catch( Throwable e ){ text_entry_text.selectAll(); } } } } else if (text_entry_combo != null ){ text_entry_combo.setText(this.preentered_text); } } // TAB will take them out of the text entry box. text_entry.addTraverseListener(new TraverseListener() { @Override public void keyTraversed(TraverseEvent e) { if (e.detail == SWT.TRAVERSE_TAB_NEXT || e.detail == SWT.TRAVERSE_TAB_PREVIOUS) { e.doit = true; } } }); text_entry.addKeyListener(new KeyListener() { @Override public void keyPressed(KeyEvent e) { int key = e.character; if (key <= 26 && key > 0) { key += 'a' - 1; } if (key == 'a' && e.stateMask == SWT.MOD1) { if (text_entry_text != null) { text_entry_text.selectAll(); } } } @Override public void keyReleased(KeyEvent e) { } }); for ( VerifyListener l: verify_listeners ){ if ( text_entry_text != null ){ text_entry_text.addVerifyListener( l ); }else if ( text_entry_combo != null ){ text_entry_combo.addVerifyListener( l ); } } // Default behaviour - single mode results in default height of 1 line, // multiple lines has default height of 3. int line_height = this.line_height; if (line_height == -1) { line_height = (this.multiline_mode) ? 3 : 1; } gridData = resizeable?new GridData(GridData.FILL_BOTH):new GridData(); gridData.widthHint = width_hint; if ( height_hint == -1 ){ if (text_entry_text != null){ gridData.minimumHeight = text_entry_text.getLineHeight() * line_height; gridData.heightHint = gridData.minimumHeight; } }else{ gridData.heightHint = height_hint; } text_entry.setLayoutData(gridData); Composite bottom_panel = new Composite(shell, SWT.NULL); gridData = new GridData( GridData.FILL_HORIZONTAL ); bottom_panel.setLayoutData(gridData); GridLayout gLayout = new GridLayout( 2, false ); gLayout.marginTop = 0; gLayout.marginLeft = 0; gLayout.marginBottom = 0; gLayout.marginRight = 0; gLayout.marginHeight = 0; gLayout.marginWidth = 0; bottom_panel.setLayout( gLayout ); link_label = new Label( bottom_panel, SWT.NULL ); gridData = new GridData( GridData.FILL_HORIZONTAL ); link_label.setLayoutData(gridData); Composite button_panel = new Composite(bottom_panel, SWT.NULL); RowLayout rLayout = new RowLayout(); rLayout.marginTop = 0; rLayout.marginLeft = 0; rLayout.marginBottom = 0; rLayout.marginRight = 0; rLayout.fill = true; rLayout.spacing = Utils.BUTTON_MARGIN; button_panel.setLayout(rLayout); gridData = new GridData(); gridData.horizontalAlignment = SWT.END; button_panel.setLayoutData(gridData); Button[] buttons = Utils.createOKCancelButtons(button_panel); Button ok = buttons[0]; Button cancel = buttons[1]; ok.addListener(SWT.Selection, new Listener() { private void showError(String text) { String error_title = SimpleTextEntryWindow.this.title; if (error_title == null) {error_title = "";} MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK); mb.setText(error_title); mb.setMessage(text); mb.open(); } /* (non-Javadoc) * @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event) */ @Override public void handleEvent(Event event) { try { String entered_data = ""; if (text_entry_text != null) { entered_data = text_entry_text.getText(); } else if (text_entry_combo != null) { entered_data = text_entry_combo.getText(); } if (!SimpleTextEntryWindow.this.maintain_whitespace) { entered_data = entered_data.trim(); } if (textLimit > 0 && entered_data.length() > textLimit) { entered_data = entered_data.substring(0, textLimit); } if (!SimpleTextEntryWindow.this.allow_empty_input && entered_data.length() == 0) { showError(MessageText.getString("UI.cannot_submit_blank_text")); return; } UIInputValidator validator = SimpleTextEntryWindow.this.validator; if (validator != null) { String validate_result = validator.validate(entered_data); if (validate_result != null) { showError(MessageText.getString(validate_result)); return; } } SimpleTextEntryWindow.this.recordUserInput(entered_data); } catch (Exception e) { Debug.printStackTrace(e); SimpleTextEntryWindow.this.recordUserAbort(); } shell.dispose(); } }); cancel.addListener(SWT.Selection, new Listener() { /* (non-Javadoc) * @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event) */ @Override public void handleEvent(Event event) { SimpleTextEntryWindow.this.recordUserAbort(); shell.dispose(); } }); if ( special_escape_handling ){ cancel.setToolTipText( MessageText.getString( "long.press.cancel.tt" )); cancel.addListener( SWT.MouseDown, new Listener() { boolean mouseDown = false; TimerEvent timerEvent = null; public void handleEvent( Event event ) { if ( event.button != 1 ){ return; } if (timerEvent == null) { timerEvent = SimpleTimer.addEvent("MouseHold", SystemTime.getOffsetTime(1000), te -> { timerEvent = null; if (!mouseDown) { return; } Utils.execSWTThread(() -> { if (!mouseDown) { return; } if ( event.display.getCursorControl() != cancel ) { return; } mouseDown = false; user_hit_escape = true; shell.dispose(); }); }); } mouseDown = true; } }); } if ( text_entry_text != null ){ text_entry_text.addFocusListener( new FocusAdapter(){ @Override public void focusLost(FocusEvent e){ checkText(); } }); checkText(); } shell.setDefaultButton(ok); shell.addListener(SWT.Traverse, new Listener() { @Override public void handleEvent(Event e) { if ( e.character == SWT.ESC){ user_hit_escape = true; SimpleTextEntryWindow.this.recordUserAbort(); shell.dispose(); } } }); shell.addListener(SWT.Dispose, event -> { if (!isResultRecorded()) { recordUserAbort(); } Utils.execSWTThreadLater(0, this::triggerReceiverListener); }); shell.pack(); if (text_entry_text != null) DragDropUtils.createURLDropTarget(shell, text_entry_text); // don't shrink this control otherwise the manual speed entry for up/down speed on // the transfers bar doesn't work as parent shell small... boolean centre = true; if ( loc_size_config_key != null ){ if ( Utils.linkShellMetricsToConfig( shell, loc_size_config_key )){ centre = false; } } if ( centre ){ Utils.centreWindow(shell,false); } shell.open(); } private void checkText() { if ( detect_urls ){ String url = UrlUtils.parseTextForURL( text_entry_text.getText(), true ); if ( url != null ){ link_label.setText( url ); LinkLabel.makeLinkedLabel( link_label, url ); }else{ link_label.setText( "" ); LinkLabel.removeLinkedLabel( link_label ); } } } @Override public void setTextLimit(int limit) { textLimit = limit; Utils.execSWTThread(new AERunnable() { @Override public void runSupport() { if (text_entry_combo != null && !text_entry_combo.isDisposed()) { text_entry_combo.setTextLimit(textLimit); } if (text_entry_text != null && !text_entry_text.isDisposed()) { text_entry_text.setTextLimit(textLimit); } } }); } public void setResizeable( boolean b ) { resizeable = b; } public void setRememberLocationSize( String config_key ) { loc_size_config_key = config_key; resizeable = true; } public void setDetectURLs( boolean b ) { detect_urls = b; } public void setParentShell( Shell shell ) { parent_shell = shell; } @Override public void setEnableSpecialEscapeHandling(boolean b){ special_escape_handling = b; } @Override public boolean userHitEscape(){ return( user_hit_escape ); } }
BiglySoftware/BiglyBT
uis/src/com/biglybt/ui/swt/SimpleTextEntryWindow.java
5,856
/* (non-Javadoc) * @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event) */
block_comment
nl
/* * Created on 16 July 2006 * Copyright (C) Azureus Software, Inc, All Rights Reserved. * * 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 com.biglybt.ui.swt; import java.util.ArrayList; import java.util.Locale; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.FocusAdapter; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.TraverseEvent; import org.eclipse.swt.events.TraverseListener; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.*; import com.biglybt.core.internat.MessageText; import com.biglybt.core.util.AERunnable; import com.biglybt.core.util.Debug; import com.biglybt.core.util.SimpleTimer; import com.biglybt.core.util.SystemTime; import com.biglybt.core.util.TimerEvent; import com.biglybt.core.util.UrlUtils; import com.biglybt.ui.swt.components.LinkLabel; import com.biglybt.ui.swt.components.shell.ShellFactory; import com.biglybt.ui.swt.pifimpl.AbstractUISWTInputReceiver; import com.biglybt.ui.swt.utils.DragDropUtils; import com.biglybt.pif.ui.UIInputValidator; /** * @author amc1 * Based on CategoryAdderWindow. */ public class SimpleTextEntryWindow extends AbstractUISWTInputReceiver { private Display display; private Shell parent_shell; private Shell shell; private int textLimit; private boolean resizeable; private String loc_size_config_key; private Combo text_entry_combo; private StyledText text_entry_text; private Label link_label; private boolean detect_urls; private boolean special_escape_handling; private boolean user_hit_escape; private java.util.List<VerifyListener> verify_listeners = new ArrayList<>(); public SimpleTextEntryWindow() { } public SimpleTextEntryWindow(String sTitleKey, String sLabelKey) { setTitle(sTitleKey); setMessage(sLabelKey); } public SimpleTextEntryWindow(String sTitleKey, String sLabelKey, boolean bMultiLine) { setTitle(sTitleKey); setMessage(sLabelKey); setMultiLine(bMultiLine); } public void initTexts(String sTitleKey, String[] p0, String sLabelKey, String[] p1) { setLocalisedTitle(MessageText.getString(sTitleKey, p0)); setLocalisedMessage(MessageText.getString(sLabelKey, p1)); } public void addVerifyListener( VerifyListener l ) { verify_listeners.add( l ); } @Override protected void promptForInput() { Utils.execSWTThread(new Runnable() { @Override public void run() { promptForInput0(); if (receiver_listener == null) { Utils.readAndDispatchLoop( shell ); } } }, receiver_listener != null); } private void promptForInput0() { //shell = com.biglybt.ui.swt.components.shell.ShellFactory.createShell(Utils.findAnyShell(), SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); // link to active shell, so that when it closes, the input box closes (good for config windows) Shell parent = parent_shell; if ( parent_shell == null ){ parent = Display.getDefault().getActiveShell(); if ( parent != null && parent.getData( ShellFactory.NOT_A_GOOD_PARENT ) != null ){ parent = null; } } if (parent == null) { parent = Utils.findAnyShell(); } shell = com.biglybt.ui.swt.components.shell.ShellFactory.createShell(parent, SWT.DIALOG_TRIM | (resizeable?SWT.RESIZE:0 )); display = shell.getDisplay(); if (this.title != null) { String str = this.title; if ( textLimit > 0 ){ str += " (" + MessageText.getString( "label.limit") + " " + textLimit + ")"; } shell.setText(str); } Utils.setShellIcon(shell); GridLayout layout = new GridLayout(); layout.verticalSpacing = 10; shell.setLayout(layout); int width_hint; int height_hint; if ( loc_size_config_key != null && Utils.hasShellMetricsConfig( loc_size_config_key )){ width_hint = -1; height_hint = -1; }else{ width_hint = (this.width_hint == -1) ? 330 : this.width_hint; height_hint = (this.height_hint == -1) ? -1 : this.height_hint; } // Process any messages. GridData gridData = null; for (int i=0; i<this.messages.length; i++) { String msg = messages[i]; gridData = resizeable?new GridData(GridData.FILL_HORIZONTAL):new GridData(); gridData.widthHint = width_hint; if ( msg.toLowerCase(Locale.US).contains( "<a href" )){ StyledText text = new StyledText( shell, SWT.NULL ); text.setEditable( false ); text.setBackground( shell.getBackground()); Utils.setTextWithURLs(text, msg,false); text.setLayoutData(gridData); }else{ Label label = new Label(shell, SWT.WRAP); label.setText( msg ); label.setLayoutData(gridData); } } // Create Text object with pre-entered text. final Scrollable text_entry; if (this.choices != null) { int text_entry_flags = SWT.DROP_DOWN; if (!this.choices_allow_edit) { text_entry_flags |= SWT.READ_ONLY; } text_entry_combo = new Combo(shell, text_entry_flags); text_entry_combo.setItems(this.choices); if (textLimit > 0) { text_entry_combo.setTextLimit(textLimit); } text_entry_text = null; text_entry = text_entry_combo; } else { // We may, at a later date, allow more customisable behaviour w.r.t. to this. // (e.g. "Should we wrap this, should we provide H_SCROLL capabilities" etc.) int text_entry_flags = SWT.BORDER; if (this.multiline_mode) { text_entry_flags |= SWT.MULTI | SWT.V_SCROLL | SWT.WRAP; } else { text_entry_flags |= SWT.SINGLE; } text_entry_text = new StyledText(shell, text_entry_flags); if (textLimit > 0) { text_entry_text.setTextLimit(textLimit); } text_entry_combo = null; text_entry = text_entry_text; } if (this.preentered_text != null) { if (text_entry_text != null) { text_entry_text.setText(this.preentered_text); if (this.select_preentered_text) { int[] range = this.select_preentered_text_range; if ( range == null || range.length != 2 ){ text_entry_text.selectAll(); }else{ try{ text_entry_text.setSelection( range[0], range[1] ); }catch( Throwable e ){ text_entry_text.selectAll(); } } } } else if (text_entry_combo != null ){ text_entry_combo.setText(this.preentered_text); } } // TAB will take them out of the text entry box. text_entry.addTraverseListener(new TraverseListener() { @Override public void keyTraversed(TraverseEvent e) { if (e.detail == SWT.TRAVERSE_TAB_NEXT || e.detail == SWT.TRAVERSE_TAB_PREVIOUS) { e.doit = true; } } }); text_entry.addKeyListener(new KeyListener() { @Override public void keyPressed(KeyEvent e) { int key = e.character; if (key <= 26 && key > 0) { key += 'a' - 1; } if (key == 'a' && e.stateMask == SWT.MOD1) { if (text_entry_text != null) { text_entry_text.selectAll(); } } } @Override public void keyReleased(KeyEvent e) { } }); for ( VerifyListener l: verify_listeners ){ if ( text_entry_text != null ){ text_entry_text.addVerifyListener( l ); }else if ( text_entry_combo != null ){ text_entry_combo.addVerifyListener( l ); } } // Default behaviour - single mode results in default height of 1 line, // multiple lines has default height of 3. int line_height = this.line_height; if (line_height == -1) { line_height = (this.multiline_mode) ? 3 : 1; } gridData = resizeable?new GridData(GridData.FILL_BOTH):new GridData(); gridData.widthHint = width_hint; if ( height_hint == -1 ){ if (text_entry_text != null){ gridData.minimumHeight = text_entry_text.getLineHeight() * line_height; gridData.heightHint = gridData.minimumHeight; } }else{ gridData.heightHint = height_hint; } text_entry.setLayoutData(gridData); Composite bottom_panel = new Composite(shell, SWT.NULL); gridData = new GridData( GridData.FILL_HORIZONTAL ); bottom_panel.setLayoutData(gridData); GridLayout gLayout = new GridLayout( 2, false ); gLayout.marginTop = 0; gLayout.marginLeft = 0; gLayout.marginBottom = 0; gLayout.marginRight = 0; gLayout.marginHeight = 0; gLayout.marginWidth = 0; bottom_panel.setLayout( gLayout ); link_label = new Label( bottom_panel, SWT.NULL ); gridData = new GridData( GridData.FILL_HORIZONTAL ); link_label.setLayoutData(gridData); Composite button_panel = new Composite(bottom_panel, SWT.NULL); RowLayout rLayout = new RowLayout(); rLayout.marginTop = 0; rLayout.marginLeft = 0; rLayout.marginBottom = 0; rLayout.marginRight = 0; rLayout.fill = true; rLayout.spacing = Utils.BUTTON_MARGIN; button_panel.setLayout(rLayout); gridData = new GridData(); gridData.horizontalAlignment = SWT.END; button_panel.setLayoutData(gridData); Button[] buttons = Utils.createOKCancelButtons(button_panel); Button ok = buttons[0]; Button cancel = buttons[1]; ok.addListener(SWT.Selection, new Listener() { private void showError(String text) { String error_title = SimpleTextEntryWindow.this.title; if (error_title == null) {error_title = "";} MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK); mb.setText(error_title); mb.setMessage(text); mb.open(); } /* (non-Javadoc) <SUF>*/ @Override public void handleEvent(Event event) { try { String entered_data = ""; if (text_entry_text != null) { entered_data = text_entry_text.getText(); } else if (text_entry_combo != null) { entered_data = text_entry_combo.getText(); } if (!SimpleTextEntryWindow.this.maintain_whitespace) { entered_data = entered_data.trim(); } if (textLimit > 0 && entered_data.length() > textLimit) { entered_data = entered_data.substring(0, textLimit); } if (!SimpleTextEntryWindow.this.allow_empty_input && entered_data.length() == 0) { showError(MessageText.getString("UI.cannot_submit_blank_text")); return; } UIInputValidator validator = SimpleTextEntryWindow.this.validator; if (validator != null) { String validate_result = validator.validate(entered_data); if (validate_result != null) { showError(MessageText.getString(validate_result)); return; } } SimpleTextEntryWindow.this.recordUserInput(entered_data); } catch (Exception e) { Debug.printStackTrace(e); SimpleTextEntryWindow.this.recordUserAbort(); } shell.dispose(); } }); cancel.addListener(SWT.Selection, new Listener() { /* (non-Javadoc) * @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event) */ @Override public void handleEvent(Event event) { SimpleTextEntryWindow.this.recordUserAbort(); shell.dispose(); } }); if ( special_escape_handling ){ cancel.setToolTipText( MessageText.getString( "long.press.cancel.tt" )); cancel.addListener( SWT.MouseDown, new Listener() { boolean mouseDown = false; TimerEvent timerEvent = null; public void handleEvent( Event event ) { if ( event.button != 1 ){ return; } if (timerEvent == null) { timerEvent = SimpleTimer.addEvent("MouseHold", SystemTime.getOffsetTime(1000), te -> { timerEvent = null; if (!mouseDown) { return; } Utils.execSWTThread(() -> { if (!mouseDown) { return; } if ( event.display.getCursorControl() != cancel ) { return; } mouseDown = false; user_hit_escape = true; shell.dispose(); }); }); } mouseDown = true; } }); } if ( text_entry_text != null ){ text_entry_text.addFocusListener( new FocusAdapter(){ @Override public void focusLost(FocusEvent e){ checkText(); } }); checkText(); } shell.setDefaultButton(ok); shell.addListener(SWT.Traverse, new Listener() { @Override public void handleEvent(Event e) { if ( e.character == SWT.ESC){ user_hit_escape = true; SimpleTextEntryWindow.this.recordUserAbort(); shell.dispose(); } } }); shell.addListener(SWT.Dispose, event -> { if (!isResultRecorded()) { recordUserAbort(); } Utils.execSWTThreadLater(0, this::triggerReceiverListener); }); shell.pack(); if (text_entry_text != null) DragDropUtils.createURLDropTarget(shell, text_entry_text); // don't shrink this control otherwise the manual speed entry for up/down speed on // the transfers bar doesn't work as parent shell small... boolean centre = true; if ( loc_size_config_key != null ){ if ( Utils.linkShellMetricsToConfig( shell, loc_size_config_key )){ centre = false; } } if ( centre ){ Utils.centreWindow(shell,false); } shell.open(); } private void checkText() { if ( detect_urls ){ String url = UrlUtils.parseTextForURL( text_entry_text.getText(), true ); if ( url != null ){ link_label.setText( url ); LinkLabel.makeLinkedLabel( link_label, url ); }else{ link_label.setText( "" ); LinkLabel.removeLinkedLabel( link_label ); } } } @Override public void setTextLimit(int limit) { textLimit = limit; Utils.execSWTThread(new AERunnable() { @Override public void runSupport() { if (text_entry_combo != null && !text_entry_combo.isDisposed()) { text_entry_combo.setTextLimit(textLimit); } if (text_entry_text != null && !text_entry_text.isDisposed()) { text_entry_text.setTextLimit(textLimit); } } }); } public void setResizeable( boolean b ) { resizeable = b; } public void setRememberLocationSize( String config_key ) { loc_size_config_key = config_key; resizeable = true; } public void setDetectURLs( boolean b ) { detect_urls = b; } public void setParentShell( Shell shell ) { parent_shell = shell; } @Override public void setEnableSpecialEscapeHandling(boolean b){ special_escape_handling = b; } @Override public boolean userHitEscape(){ return( user_hit_escape ); } }
11659_3
package net.uyghurdev.avaroid.rssreader.data; import java.io.File; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; public class OpenHelper extends SQLiteOpenHelper { private static final String DB_PATH = "/data/data/net.uyghurdev.avaroid.rssreader/databases/"; // "/data/data/net.uyghurdev.app/databases/"; private static final String DATABASE_NAME = "rss"; private static final int DATABASE_VERSION = 3; private SQLiteDatabase db; public OpenHelper(Context ctx) { super(ctx, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE feed(_id INTEGER PRIMARY KEY AUTOINCREMENT,title TEXT,url TEXT,readCount INTEGER,newItemCount INTEGER,itemCount INTEGER, enabled INTEGER, pagenumber INTEGER, itemnumber INTEGER, item_id INTEGER);"); db.execSQL("CREATE TABLE item(_id INTEGER PRIMARY KEY AUTOINCREMENT,feedId INTEGER,title TEXT,link TEXT,description TEXT,author TEXT,imgurl TEXT,pubDate DateTime,pubDateString TEXT, isNew INTEGER);"); ContentValues cvj = new ContentValues(); cvj.put("title", "جېك بلوگى"); cvj.put("url", "http://jeckblog.com/feed/"); cvj.put("readCount", 0); cvj.put("newItemCount", 0); cvj.put("itemCount", 0); cvj.put("enabled", 1); cvj.put("pagenumber", 0); cvj.put("itemnumber", 6); cvj.put("item_id", 6); db.insert("feed", "title", cvj); ContentValues cvq = new ContentValues(); cvq.put("title", "قىسمەت"); cvq.put("url", "http://www.qismet.me/feed"); cvq.put("readCount", 0); cvq.put("newItemCount", 0); cvq.put("itemCount", 0); cvq.put("enabled", 1); cvq.put("pagenumber", 0); cvq.put("itemnumber", 7); cvq.put("item_id", 7); db.insert("feed", "title", cvq); ContentValues cva = new ContentValues(); cva.put("title", "ئالىم بىز بلوگى"); cva.put("url", "http://www.alimbiz.net/?feed=rss2"); cva.put("readCount", 0); cva.put("newItemCount", 0); cva.put("itemCount", 0); cva.put("enabled", 1); cva.put("pagenumber", 0); cva.put("itemnumber", 1); cva.put("item_id", 1); db.insert("feed", "title", cva); ContentValues cvi = new ContentValues(); cvi.put("title", "ئىزتىل تور خاتىرىسى"); cvi.put("url", "http://www.iztil.com/?feed=rss2"); cvi.put("readCount", 0); cvi.put("newItemCount", 0); cvi.put("itemCount", 0); cvi.put("enabled", 1); cvi.put("pagenumber", 0); cvi.put("itemnumber", 2); cvi.put("item_id", 2); db.insert("feed", "title", cvi); ContentValues cvu = new ContentValues(); cvu.put("title", "ئۇيغۇربەگ تور تۇراسى"); cvu.put("url", "http://www.uyghurbeg.net/feed"); cvu.put("readCount", 0); cvu.put("newItemCount", 0); cvu.put("itemCount", 0); cvu.put("enabled", 1); cvu.put("pagenumber", 0); cvu.put("itemnumber", 3); cvu.put("item_id", 3); db.insert("feed", "title", cvu); ContentValues cvum = new ContentValues(); cvum.put("title", "ئۈمىدلەن"); cvum.put("url", "http://www.umidlen.com/feed"); cvum.put("readCount", 0); cvum.put("newItemCount", 0); cvum.put("itemCount", 0); cvum.put("enabled", 1); cvum.put("pagenumber", 0); cvum.put("itemnumber", 4); cvum.put("item_id", 4); db.insert("feed", "title", cvum); ContentValues cvul = new ContentValues(); cvul.put("title", "ئالىم ئەھەت تور خاتىرىسى"); cvul.put("url", "http://www.alimahat.com/?feed=rss2"); cvul.put("readCount", 0); cvul.put("newItemCount", 0); cvul.put("itemCount", 0); cvul.put("enabled", 1); cvul.put("pagenumber", 0); cvul.put("itemnumber", 0); cvul.put("item_id", 0); db.insert("feed", "title", cvul); ContentValues cvju = new ContentValues(); cvju.put("title", "جۇلالىق بلوگى"); cvju.put("url", "http://www.julaliq.com/?feed=rss2"); cvju.put("readCount", 0); cvju.put("newItemCount", 0); cvju.put("itemCount", 0); cvju.put("enabled", 1); cvju.put("pagenumber", 0); cvju.put("itemnumber", 5); cvju.put("item_id", 5); db.insert("feed", "title", cvju); ContentValues cvn = new ContentValues(); cvn.put("title", "نازۇگۇم"); cvn.put("url", "http://www.nazugum.com/?feed=rss2"); cvn.put("readCount", 0); cvn.put("newItemCount", 0); cvn.put("itemCount", 0); cvn.put("enabled", 1); cvn.put("pagenumber", 1); cvn.put("itemnumber", 0); cvn.put("item_id", 8); db.insert("feed", "title", cvn); ContentValues cvw = new ContentValues(); cvw.put("title", "ۋەتەن بلوگى"); cvw.put("url", "http://weten.me/?feed=rss2"); cvw.put("readCount", 0); cvw.put("newItemCount", 0); cvw.put("itemCount", 0); cvw.put("enabled", 1); cvw.put("pagenumber", 1); cvw.put("itemnumber", 1); cvw.put("item_id", 9); db.insert("feed", "title", cvw); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // db.execSQL("DROP TABLE IF EXISTS " + TABLE_OBJECT); // onCreate(db); } private boolean checkdatabase() { // SQLiteDatabase checkdb = null; boolean checkdb = false; try { String myPath = DB_PATH + DATABASE_NAME; File dbfile = new File(myPath); // checkdb = // SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READWRITE); checkdb = dbfile.exists(); } catch (SQLiteException e) { System.out.println("Database doesn't exist"); } return checkdb; } public void dbOpen() { if (this.db == null || !this.db.isOpen()) { this.db = this.getWritableDatabase(); } } /* * Delete Fee by id */ // public void deleteFeed(int id) { // // TODO Auto-generated method stub // String[] args={String.valueOf(id)}; // this.db = this.getWritableDatabase(); // this.db.delete("feed", "_id=?", args); // } public void delete(String strTable, String strWhereCause, String[] args) { dbOpen(); this.db.delete(strTable, strWhereCause, args); this.db.close(); } // /* // * Get feeds to an array list of feeds // */ // public ArrayList<Feed> getFeeds() { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // ArrayList<Feed> list = new ArrayList<Feed>(); // Cursor cursor = this.db.query("feed", new String[] { // "_id", "title", "url", "newItemCount" }, null, null, null, null, // "title asc"); // cursor.moveToFirst(); // for (int m = 0; m < cursor.getCount(); m++) { // Feed feed = new Feed(); // feed.setId(cursor.getInt(0)); // feed.setTitle(cursor.getString(1)); // feed.setUrl(cursor.getString(2)); // feed.setNewItemCout(cursor.getInt(3)); // list.add(feed); // cursor.moveToNext(); // } // if (cursor != null && !cursor.isClosed()) { // cursor.close(); // } // this.db.close(); // return list; // } public Cursor getCursor(String strTable, String[] Columns, String selection, String Orders, String Limt) { dbOpen(); Cursor crsr = this.db.query(strTable, Columns, selection, null, null, null, Orders, Limt); // this.db.close(); return crsr; } public Cursor getCursorT(String strTable, String[] Columns, String selection, String[] strArgs, String Orders, String Limt) { dbOpen(); Cursor crsr = this.db.query(strTable, Columns, selection, strArgs, null, null, Orders); // this.db.close(); return crsr; } // public ArrayList<LItem> getFeedItems(int feedId) { // // TODO Auto-generated method stub // ArrayList<LItem> list = new ArrayList<LItem>(); // this.db = this.getWritableDatabase(); // Cursor cursor = this.db.query("item", new String[] { // "_id", "title", "isNew" }, "feedId=" + feedId, null, null, null, // "pubDate desc", "" + Configs.ShowCount); // // cursor.moveToFirst(); // for (int m = 0; m < cursor.getCount(); m++) { // LItem item = new LItem(); // item.setId(cursor.getInt(0)); // itemIds[m] = cursor.getInt(0); // item.setTitle(cursor.getString(1)); // item.setNewItem(cursor.getInt(2)); // list.add(item); // cursor.moveToNext(); // } // if (cursor != null && !cursor.isClosed()) { // cursor.close(); // } // this.db.close(); // return list; // } // public Item getItem(int i) { // this.db = this.getWritableDatabase(); // Cursor cursor = this.db.query("item", new String[] { // "title", "link", "description", "author", "imgurl", "pubDateString" }, // "_id=" + i, // null, null, null, "pubDate desc"); // cursor.moveToFirst(); // Item item = new Item(); // item.setTitle(cursor.getString(0)); // item.setLink(cursor.getString(1)); // item.setDescription(cursor.getString(2)); // item.setAuthor(cursor.getString(3)); // item.setImageUrl(cursor.getString(4)); // item.setPubDate(cursor.getString(5)); // if (cursor != null && !cursor.isClosed()) { // cursor.close(); // } // this.db.close(); // return item; // } // public void deleteFeedItems(int feedid) { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // this.db.delete("item", "feedId=" + feedid, null); // this.db.close(); // } public void update(String table, ContentValues cv, String whereClause, String[] whereArgs) { dbOpen(); this.db.update(table, cv, whereClause, null); this.db.close(); } // public void itemsCleared(int feedid) { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // ContentValues cv = new ContentValues(); // cv.put("readCount", 0); // cv.put("newItemCount", 0); // cv.put("itemCount", 0); // this.db.update("feed", cv, "_id=" + feedid, null); // this.db.close(); // } public void insert(String table, String nullColumnHack, ContentValues cv) { dbOpen(); this.db.insert(table, nullColumnHack, cv); this.db.close(); } // public void addFeed(String title, String url){ // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // ContentValues cv = new ContentValues(); // cv.put("title", title); // cv.put("url", url); // cv.put("readCount", 0); // cv.put("newItemCount", 0); // cv.put("itemCount", 0); // cv.put("enabled", 1); // this.db.insert("feed", "title", cv); // this.db.close(); // } // public void editFeed(int feedId, String feedTitle, String feedUrl) { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // ContentValues cv = new ContentValues(); // cv.put("title", feedTitle); // cv.put("url", feedUrl); // this.db.update("feed", cv, "_id=" + feedId, null); // this.db.close(); // } // public void clearItemTable() { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // this.db.delete("item", null, null); // } // public void clearfeedTable() { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // this.db.delete("feed", null, null); // this.db.close(); // } // public int getItemCount(String value) { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // int count = 0; // try{ // Cursor cursor = this.db.query("item", null, "title='" + value + "'", // null, //new String[] {value}, // null, null, null); // // if (cursor != null && !cursor.isClosed()) { // count = cursor.getCount(); // cursor.close(); // } // }catch(Exception e){ // // Log.d("Database", e.toString()); // } // this.db.close(); // return count; // } // public void addItem(int feedId, Item item) { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // ContentValues cv = new ContentValues(); // cv.put("feedId", feedId); // cv.put("title", item.getTitle()); // cv.put("link", item.getLink()); // cv.put("description", item.getDescription()); // cv.put("author", item.getAuthor()); // cv.put("imgurl", item.getImageUrl()); // cv.put("pubDate", Date.parse(item.getPubDate())); // cv.put("pubDateString", item.getPubDate()); // cv.put("isNew", 1); // this.db.insert("item", null, cv); // this.db.close(); // } // public void newItemRead(int id) { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // ContentValues cv = new ContentValues(); // cv.put("isNew", 0); // this.db.update("item", cv, "_id=" + id, null); // this.db.close(); // // } // public void newFeedItemRead(int feedId) { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // Cursor cursor = this.db.query("feed", new String[] {"newItemCount"}, // "_id=" + feedId, null, null, null, null); // cursor.moveToFirst(); // int newItem = cursor.getInt(0); // if (cursor != null && !cursor.isClosed()) { // cursor.close(); // } // ContentValues cv = new ContentValues(); // cv.put("newItemCount", newItem - 1); // this.db.update("feed", cv, "_id=" + feedId, null); // this.db.close(); // } // public void newItemAdded(int feedId) { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // Cursor cursor = this.db.query("feed", new String[] {"newItemCount"}, // "_id=" + feedId, null, null, null, null); // cursor.moveToFirst(); // int newItem = cursor.getInt(0); // if (cursor != null && !cursor.isClosed()) { // cursor.close(); // } // ContentValues cv = new ContentValues(); // cv.put("newItemCount", newItem + 1); // this.db.update("feed", cv, "_id=" + feedId, null); // this.db.close(); // } // public int getItemNew(int i) { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // Cursor cursor = this.db.query("item", new String[] {"isNew"}, "_id=" + i, // null, null, null, null); // cursor.moveToFirst(); // int newItem = cursor.getInt(0); // if (cursor != null && !cursor.isClosed()) { // cursor.close(); // } // this.db.close(); // return newItem; // } // public int getExistingFeed(String string) { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // int count = 0; // try{ // Cursor cursor = this.db.query("feed", null, "url='" + string + "'", null, // //new String[] {value}, // null, null, null); // // if (cursor != null && !cursor.isClosed()) { // count = cursor.getCount(); // cursor.close(); // } // }catch(Exception e){ // // Log.d("Database", e.toString()); // } // this.db.close(); // return count; // } // public int getItemCount() { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // int count = 0; // try{ // Cursor cursor = this.db.query("item", new String[] {"_id"}, null, null, // //new String[] {value}, // null, null, "_id desc"); // if (cursor != null && !cursor.isClosed()) { // count = cursor.getCount(); // cursor.close(); // } // }catch(Exception e){ // // Log.d("Database", e.toString()); // } // this.db.close(); // return count; // } // public void markAllRead() { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // ContentValues cvi = new ContentValues(); // cvi.put("isNew", 0); // this.db.update("item", cvi, null, null); // ContentValues cvf = new ContentValues(); // cvf.put("newItemCount", 0); // this.db.update("feed", cvf, null, null); // this.db.close(); // } // public void itemsRead(int feedId) { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // ContentValues cvi = new ContentValues(); // cvi.put("isNew", 0); // this.db.update("item", cvi, "feedId=" + feedId, null); // ContentValues cvf = new ContentValues(); // cvf.put("newItemCount", 0); // this.db.update("feed", cvf, "_id=" + feedId, null); // this.db.close(); // } }
Bilkan/RSSReader
src/src/net/uyghurdev/avaroid/rssreader/data/OpenHelper.java
5,808
// public void deleteFeed(int id) {
line_comment
nl
package net.uyghurdev.avaroid.rssreader.data; import java.io.File; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; public class OpenHelper extends SQLiteOpenHelper { private static final String DB_PATH = "/data/data/net.uyghurdev.avaroid.rssreader/databases/"; // "/data/data/net.uyghurdev.app/databases/"; private static final String DATABASE_NAME = "rss"; private static final int DATABASE_VERSION = 3; private SQLiteDatabase db; public OpenHelper(Context ctx) { super(ctx, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE feed(_id INTEGER PRIMARY KEY AUTOINCREMENT,title TEXT,url TEXT,readCount INTEGER,newItemCount INTEGER,itemCount INTEGER, enabled INTEGER, pagenumber INTEGER, itemnumber INTEGER, item_id INTEGER);"); db.execSQL("CREATE TABLE item(_id INTEGER PRIMARY KEY AUTOINCREMENT,feedId INTEGER,title TEXT,link TEXT,description TEXT,author TEXT,imgurl TEXT,pubDate DateTime,pubDateString TEXT, isNew INTEGER);"); ContentValues cvj = new ContentValues(); cvj.put("title", "جېك بلوگى"); cvj.put("url", "http://jeckblog.com/feed/"); cvj.put("readCount", 0); cvj.put("newItemCount", 0); cvj.put("itemCount", 0); cvj.put("enabled", 1); cvj.put("pagenumber", 0); cvj.put("itemnumber", 6); cvj.put("item_id", 6); db.insert("feed", "title", cvj); ContentValues cvq = new ContentValues(); cvq.put("title", "قىسمەت"); cvq.put("url", "http://www.qismet.me/feed"); cvq.put("readCount", 0); cvq.put("newItemCount", 0); cvq.put("itemCount", 0); cvq.put("enabled", 1); cvq.put("pagenumber", 0); cvq.put("itemnumber", 7); cvq.put("item_id", 7); db.insert("feed", "title", cvq); ContentValues cva = new ContentValues(); cva.put("title", "ئالىم بىز بلوگى"); cva.put("url", "http://www.alimbiz.net/?feed=rss2"); cva.put("readCount", 0); cva.put("newItemCount", 0); cva.put("itemCount", 0); cva.put("enabled", 1); cva.put("pagenumber", 0); cva.put("itemnumber", 1); cva.put("item_id", 1); db.insert("feed", "title", cva); ContentValues cvi = new ContentValues(); cvi.put("title", "ئىزتىل تور خاتىرىسى"); cvi.put("url", "http://www.iztil.com/?feed=rss2"); cvi.put("readCount", 0); cvi.put("newItemCount", 0); cvi.put("itemCount", 0); cvi.put("enabled", 1); cvi.put("pagenumber", 0); cvi.put("itemnumber", 2); cvi.put("item_id", 2); db.insert("feed", "title", cvi); ContentValues cvu = new ContentValues(); cvu.put("title", "ئۇيغۇربەگ تور تۇراسى"); cvu.put("url", "http://www.uyghurbeg.net/feed"); cvu.put("readCount", 0); cvu.put("newItemCount", 0); cvu.put("itemCount", 0); cvu.put("enabled", 1); cvu.put("pagenumber", 0); cvu.put("itemnumber", 3); cvu.put("item_id", 3); db.insert("feed", "title", cvu); ContentValues cvum = new ContentValues(); cvum.put("title", "ئۈمىدلەن"); cvum.put("url", "http://www.umidlen.com/feed"); cvum.put("readCount", 0); cvum.put("newItemCount", 0); cvum.put("itemCount", 0); cvum.put("enabled", 1); cvum.put("pagenumber", 0); cvum.put("itemnumber", 4); cvum.put("item_id", 4); db.insert("feed", "title", cvum); ContentValues cvul = new ContentValues(); cvul.put("title", "ئالىم ئەھەت تور خاتىرىسى"); cvul.put("url", "http://www.alimahat.com/?feed=rss2"); cvul.put("readCount", 0); cvul.put("newItemCount", 0); cvul.put("itemCount", 0); cvul.put("enabled", 1); cvul.put("pagenumber", 0); cvul.put("itemnumber", 0); cvul.put("item_id", 0); db.insert("feed", "title", cvul); ContentValues cvju = new ContentValues(); cvju.put("title", "جۇلالىق بلوگى"); cvju.put("url", "http://www.julaliq.com/?feed=rss2"); cvju.put("readCount", 0); cvju.put("newItemCount", 0); cvju.put("itemCount", 0); cvju.put("enabled", 1); cvju.put("pagenumber", 0); cvju.put("itemnumber", 5); cvju.put("item_id", 5); db.insert("feed", "title", cvju); ContentValues cvn = new ContentValues(); cvn.put("title", "نازۇگۇم"); cvn.put("url", "http://www.nazugum.com/?feed=rss2"); cvn.put("readCount", 0); cvn.put("newItemCount", 0); cvn.put("itemCount", 0); cvn.put("enabled", 1); cvn.put("pagenumber", 1); cvn.put("itemnumber", 0); cvn.put("item_id", 8); db.insert("feed", "title", cvn); ContentValues cvw = new ContentValues(); cvw.put("title", "ۋەتەن بلوگى"); cvw.put("url", "http://weten.me/?feed=rss2"); cvw.put("readCount", 0); cvw.put("newItemCount", 0); cvw.put("itemCount", 0); cvw.put("enabled", 1); cvw.put("pagenumber", 1); cvw.put("itemnumber", 1); cvw.put("item_id", 9); db.insert("feed", "title", cvw); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // db.execSQL("DROP TABLE IF EXISTS " + TABLE_OBJECT); // onCreate(db); } private boolean checkdatabase() { // SQLiteDatabase checkdb = null; boolean checkdb = false; try { String myPath = DB_PATH + DATABASE_NAME; File dbfile = new File(myPath); // checkdb = // SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READWRITE); checkdb = dbfile.exists(); } catch (SQLiteException e) { System.out.println("Database doesn't exist"); } return checkdb; } public void dbOpen() { if (this.db == null || !this.db.isOpen()) { this.db = this.getWritableDatabase(); } } /* * Delete Fee by id */ // public void<SUF> // // TODO Auto-generated method stub // String[] args={String.valueOf(id)}; // this.db = this.getWritableDatabase(); // this.db.delete("feed", "_id=?", args); // } public void delete(String strTable, String strWhereCause, String[] args) { dbOpen(); this.db.delete(strTable, strWhereCause, args); this.db.close(); } // /* // * Get feeds to an array list of feeds // */ // public ArrayList<Feed> getFeeds() { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // ArrayList<Feed> list = new ArrayList<Feed>(); // Cursor cursor = this.db.query("feed", new String[] { // "_id", "title", "url", "newItemCount" }, null, null, null, null, // "title asc"); // cursor.moveToFirst(); // for (int m = 0; m < cursor.getCount(); m++) { // Feed feed = new Feed(); // feed.setId(cursor.getInt(0)); // feed.setTitle(cursor.getString(1)); // feed.setUrl(cursor.getString(2)); // feed.setNewItemCout(cursor.getInt(3)); // list.add(feed); // cursor.moveToNext(); // } // if (cursor != null && !cursor.isClosed()) { // cursor.close(); // } // this.db.close(); // return list; // } public Cursor getCursor(String strTable, String[] Columns, String selection, String Orders, String Limt) { dbOpen(); Cursor crsr = this.db.query(strTable, Columns, selection, null, null, null, Orders, Limt); // this.db.close(); return crsr; } public Cursor getCursorT(String strTable, String[] Columns, String selection, String[] strArgs, String Orders, String Limt) { dbOpen(); Cursor crsr = this.db.query(strTable, Columns, selection, strArgs, null, null, Orders); // this.db.close(); return crsr; } // public ArrayList<LItem> getFeedItems(int feedId) { // // TODO Auto-generated method stub // ArrayList<LItem> list = new ArrayList<LItem>(); // this.db = this.getWritableDatabase(); // Cursor cursor = this.db.query("item", new String[] { // "_id", "title", "isNew" }, "feedId=" + feedId, null, null, null, // "pubDate desc", "" + Configs.ShowCount); // // cursor.moveToFirst(); // for (int m = 0; m < cursor.getCount(); m++) { // LItem item = new LItem(); // item.setId(cursor.getInt(0)); // itemIds[m] = cursor.getInt(0); // item.setTitle(cursor.getString(1)); // item.setNewItem(cursor.getInt(2)); // list.add(item); // cursor.moveToNext(); // } // if (cursor != null && !cursor.isClosed()) { // cursor.close(); // } // this.db.close(); // return list; // } // public Item getItem(int i) { // this.db = this.getWritableDatabase(); // Cursor cursor = this.db.query("item", new String[] { // "title", "link", "description", "author", "imgurl", "pubDateString" }, // "_id=" + i, // null, null, null, "pubDate desc"); // cursor.moveToFirst(); // Item item = new Item(); // item.setTitle(cursor.getString(0)); // item.setLink(cursor.getString(1)); // item.setDescription(cursor.getString(2)); // item.setAuthor(cursor.getString(3)); // item.setImageUrl(cursor.getString(4)); // item.setPubDate(cursor.getString(5)); // if (cursor != null && !cursor.isClosed()) { // cursor.close(); // } // this.db.close(); // return item; // } // public void deleteFeedItems(int feedid) { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // this.db.delete("item", "feedId=" + feedid, null); // this.db.close(); // } public void update(String table, ContentValues cv, String whereClause, String[] whereArgs) { dbOpen(); this.db.update(table, cv, whereClause, null); this.db.close(); } // public void itemsCleared(int feedid) { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // ContentValues cv = new ContentValues(); // cv.put("readCount", 0); // cv.put("newItemCount", 0); // cv.put("itemCount", 0); // this.db.update("feed", cv, "_id=" + feedid, null); // this.db.close(); // } public void insert(String table, String nullColumnHack, ContentValues cv) { dbOpen(); this.db.insert(table, nullColumnHack, cv); this.db.close(); } // public void addFeed(String title, String url){ // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // ContentValues cv = new ContentValues(); // cv.put("title", title); // cv.put("url", url); // cv.put("readCount", 0); // cv.put("newItemCount", 0); // cv.put("itemCount", 0); // cv.put("enabled", 1); // this.db.insert("feed", "title", cv); // this.db.close(); // } // public void editFeed(int feedId, String feedTitle, String feedUrl) { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // ContentValues cv = new ContentValues(); // cv.put("title", feedTitle); // cv.put("url", feedUrl); // this.db.update("feed", cv, "_id=" + feedId, null); // this.db.close(); // } // public void clearItemTable() { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // this.db.delete("item", null, null); // } // public void clearfeedTable() { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // this.db.delete("feed", null, null); // this.db.close(); // } // public int getItemCount(String value) { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // int count = 0; // try{ // Cursor cursor = this.db.query("item", null, "title='" + value + "'", // null, //new String[] {value}, // null, null, null); // // if (cursor != null && !cursor.isClosed()) { // count = cursor.getCount(); // cursor.close(); // } // }catch(Exception e){ // // Log.d("Database", e.toString()); // } // this.db.close(); // return count; // } // public void addItem(int feedId, Item item) { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // ContentValues cv = new ContentValues(); // cv.put("feedId", feedId); // cv.put("title", item.getTitle()); // cv.put("link", item.getLink()); // cv.put("description", item.getDescription()); // cv.put("author", item.getAuthor()); // cv.put("imgurl", item.getImageUrl()); // cv.put("pubDate", Date.parse(item.getPubDate())); // cv.put("pubDateString", item.getPubDate()); // cv.put("isNew", 1); // this.db.insert("item", null, cv); // this.db.close(); // } // public void newItemRead(int id) { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // ContentValues cv = new ContentValues(); // cv.put("isNew", 0); // this.db.update("item", cv, "_id=" + id, null); // this.db.close(); // // } // public void newFeedItemRead(int feedId) { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // Cursor cursor = this.db.query("feed", new String[] {"newItemCount"}, // "_id=" + feedId, null, null, null, null); // cursor.moveToFirst(); // int newItem = cursor.getInt(0); // if (cursor != null && !cursor.isClosed()) { // cursor.close(); // } // ContentValues cv = new ContentValues(); // cv.put("newItemCount", newItem - 1); // this.db.update("feed", cv, "_id=" + feedId, null); // this.db.close(); // } // public void newItemAdded(int feedId) { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // Cursor cursor = this.db.query("feed", new String[] {"newItemCount"}, // "_id=" + feedId, null, null, null, null); // cursor.moveToFirst(); // int newItem = cursor.getInt(0); // if (cursor != null && !cursor.isClosed()) { // cursor.close(); // } // ContentValues cv = new ContentValues(); // cv.put("newItemCount", newItem + 1); // this.db.update("feed", cv, "_id=" + feedId, null); // this.db.close(); // } // public int getItemNew(int i) { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // Cursor cursor = this.db.query("item", new String[] {"isNew"}, "_id=" + i, // null, null, null, null); // cursor.moveToFirst(); // int newItem = cursor.getInt(0); // if (cursor != null && !cursor.isClosed()) { // cursor.close(); // } // this.db.close(); // return newItem; // } // public int getExistingFeed(String string) { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // int count = 0; // try{ // Cursor cursor = this.db.query("feed", null, "url='" + string + "'", null, // //new String[] {value}, // null, null, null); // // if (cursor != null && !cursor.isClosed()) { // count = cursor.getCount(); // cursor.close(); // } // }catch(Exception e){ // // Log.d("Database", e.toString()); // } // this.db.close(); // return count; // } // public int getItemCount() { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // int count = 0; // try{ // Cursor cursor = this.db.query("item", new String[] {"_id"}, null, null, // //new String[] {value}, // null, null, "_id desc"); // if (cursor != null && !cursor.isClosed()) { // count = cursor.getCount(); // cursor.close(); // } // }catch(Exception e){ // // Log.d("Database", e.toString()); // } // this.db.close(); // return count; // } // public void markAllRead() { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // ContentValues cvi = new ContentValues(); // cvi.put("isNew", 0); // this.db.update("item", cvi, null, null); // ContentValues cvf = new ContentValues(); // cvf.put("newItemCount", 0); // this.db.update("feed", cvf, null, null); // this.db.close(); // } // public void itemsRead(int feedId) { // // TODO Auto-generated method stub // this.db = this.getWritableDatabase(); // ContentValues cvi = new ContentValues(); // cvi.put("isNew", 0); // this.db.update("item", cvi, "feedId=" + feedId, null); // ContentValues cvf = new ContentValues(); // cvf.put("newItemCount", 0); // this.db.update("feed", cvf, "_id=" + feedId, null); // this.db.close(); // } }
20809_0
package nl.itopia.corendon.model; import nl.itopia.corendon.data.LogAction; import nl.itopia.corendon.utils.Log; import java.sql.ResultSet; import java.sql.SQLException; import java.time.LocalDate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Jeroentje, Robin de Jong */ public class LogModel { private static final LogModel _default = new LogModel(); private final DatabaseManager dbmanager = DatabaseManager.getDefault(); private final String DEFAULTSEARCHVALUE = "Maak een keuze"; private Map<Integer, LogAction> _cache; private LogModel() { _cache = new HashMap<>(); } private LogAction resultToLogAction(ResultSet result) throws SQLException { int id = result.getInt("id"); int actionId = result.getInt("action_id"); int employeeId = result.getInt("employee_id"); int luggageId = result.getInt("luggage_id"); /* models */ LuggageModel luggagemodel = LuggageModel.getDefault(); ActionModel actionmodel = ActionModel.getDefault(); EmployeeModel employeemodel = EmployeeModel.getDefault(); LogAction logaction = new LogAction(id); logaction.date = result.getInt("date"); logaction.action = actionmodel.getAction(actionId); logaction.employee = employeemodel.getEmployee(employeeId); logaction.luggage = luggagemodel.getLuggage(luggageId); return logaction; } public List<LogAction> getLogFiles() { List<LogAction> logFiles = new ArrayList<>(); try { String sql = "SELECT * FROM log"; ResultSet result = dbmanager.doQuery(sql); while (result.next()) { logFiles.add(resultToLogAction(result)); // Add the airport to the cache // _cache.put(id, airport); } } catch (SQLException e) { Log.display("SQLEXCEPTION", e.getErrorCode(), e.getSQLState(), e.getMessage()); } return logFiles; } public List<LogAction> getLogFiles(LocalDate date, String userName) { List<LogAction> logFiles = new ArrayList<>(); try { String sql = "SELECT * FROM log {JOIN} {WHERE}"; String whereQuery = " WHERE "; String innerJoinQuery = ""; if(null != date){ /* filtering on date */ whereQuery += "DATE_FORMAT(FROM_UNIXTIME(date), '%Y-%m-%d') >= '" + date + "'"; } if(userName != null && !userName.isEmpty() && !userName.equals(DEFAULTSEARCHVALUE)){ /* filtering on username */ whereQuery += " AND employee.username = '" + userName + "'"; innerJoinQuery += " INNER JOIN employee ON log.employee_id = employee.id"; } sql = sql.replace("{JOIN}",innerJoinQuery).replace("{WHERE}", whereQuery); ResultSet result = dbmanager.doQuery(sql); while (result.next()) { logFiles.add(resultToLogAction(result)); // Add the airport to the cache // _cache.put(id, airport); } } catch (SQLException e) { Log.display("SQLEXCEPTION", e.getErrorCode(), e.getSQLState(), e.getMessage()); } return logFiles; } public int insertAction(LogAction log) { long date = log.date; int action_id = log.action.getID(); int employee_id = log.employee.getID(); int luggage_id = log.luggage.getID(); String query = "INSERT INTO log " + "(date, action_id, employee_id, luggage_id) " + "VALUES" + "('%d', '%d', '%d', '%d')"; String finalQuery = String.format( query, date, action_id, employee_id, luggage_id ); try { dbmanager.insertQuery(finalQuery); // After inserting the item, get the last added luggage // This way we can set the correct ID to the new luggage ResultSet result = dbmanager.doQuery("SELECT LAST_INSERT_ID()"); if(result.next()) { return result.getInt(1); } } catch (SQLException e) { Log.display("SQLEXCEPTION", e.getErrorCode(), e.getSQLState(), e.getMessage()); } return -1; } public static LogModel getDefault() { return _default; } }
Biodiscus/Corendon
src/nl/itopia/corendon/model/LogModel.java
1,309
/** * @author Jeroentje, Robin de Jong */
block_comment
nl
package nl.itopia.corendon.model; import nl.itopia.corendon.data.LogAction; import nl.itopia.corendon.utils.Log; import java.sql.ResultSet; import java.sql.SQLException; import java.time.LocalDate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Jeroentje, Robin<SUF>*/ public class LogModel { private static final LogModel _default = new LogModel(); private final DatabaseManager dbmanager = DatabaseManager.getDefault(); private final String DEFAULTSEARCHVALUE = "Maak een keuze"; private Map<Integer, LogAction> _cache; private LogModel() { _cache = new HashMap<>(); } private LogAction resultToLogAction(ResultSet result) throws SQLException { int id = result.getInt("id"); int actionId = result.getInt("action_id"); int employeeId = result.getInt("employee_id"); int luggageId = result.getInt("luggage_id"); /* models */ LuggageModel luggagemodel = LuggageModel.getDefault(); ActionModel actionmodel = ActionModel.getDefault(); EmployeeModel employeemodel = EmployeeModel.getDefault(); LogAction logaction = new LogAction(id); logaction.date = result.getInt("date"); logaction.action = actionmodel.getAction(actionId); logaction.employee = employeemodel.getEmployee(employeeId); logaction.luggage = luggagemodel.getLuggage(luggageId); return logaction; } public List<LogAction> getLogFiles() { List<LogAction> logFiles = new ArrayList<>(); try { String sql = "SELECT * FROM log"; ResultSet result = dbmanager.doQuery(sql); while (result.next()) { logFiles.add(resultToLogAction(result)); // Add the airport to the cache // _cache.put(id, airport); } } catch (SQLException e) { Log.display("SQLEXCEPTION", e.getErrorCode(), e.getSQLState(), e.getMessage()); } return logFiles; } public List<LogAction> getLogFiles(LocalDate date, String userName) { List<LogAction> logFiles = new ArrayList<>(); try { String sql = "SELECT * FROM log {JOIN} {WHERE}"; String whereQuery = " WHERE "; String innerJoinQuery = ""; if(null != date){ /* filtering on date */ whereQuery += "DATE_FORMAT(FROM_UNIXTIME(date), '%Y-%m-%d') >= '" + date + "'"; } if(userName != null && !userName.isEmpty() && !userName.equals(DEFAULTSEARCHVALUE)){ /* filtering on username */ whereQuery += " AND employee.username = '" + userName + "'"; innerJoinQuery += " INNER JOIN employee ON log.employee_id = employee.id"; } sql = sql.replace("{JOIN}",innerJoinQuery).replace("{WHERE}", whereQuery); ResultSet result = dbmanager.doQuery(sql); while (result.next()) { logFiles.add(resultToLogAction(result)); // Add the airport to the cache // _cache.put(id, airport); } } catch (SQLException e) { Log.display("SQLEXCEPTION", e.getErrorCode(), e.getSQLState(), e.getMessage()); } return logFiles; } public int insertAction(LogAction log) { long date = log.date; int action_id = log.action.getID(); int employee_id = log.employee.getID(); int luggage_id = log.luggage.getID(); String query = "INSERT INTO log " + "(date, action_id, employee_id, luggage_id) " + "VALUES" + "('%d', '%d', '%d', '%d')"; String finalQuery = String.format( query, date, action_id, employee_id, luggage_id ); try { dbmanager.insertQuery(finalQuery); // After inserting the item, get the last added luggage // This way we can set the correct ID to the new luggage ResultSet result = dbmanager.doQuery("SELECT LAST_INSERT_ID()"); if(result.next()) { return result.getInt(1); } } catch (SQLException e) { Log.display("SQLEXCEPTION", e.getErrorCode(), e.getSQLState(), e.getMessage()); } return -1; } public static LogModel getDefault() { return _default; } }
80148_2
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package UT; import BLL.*; import DAL.*; import java.sql.SQLException; import java.util.List; /** * * @author bert */ public class UtDaOrganism { public static void main(String[] args) throws SQLException { Organism organismNew = new Organism(); Organism organismUpdate = new Organism(); Organism organismSelectOne = new Organism(); // De objecten waarmee een insert van een organisme op uitgevoerd worden. Subfamily subfamilyNew = new Subfamily(); subfamilyNew.setSubfamilyId(1); Season seasonNew1 = new Season(); seasonNew1.setSeasonId(1); Season seasonNew2 = new Season(); seasonNew2.setSeasonId(2); List<Season> seasonsNew = new java.util.ArrayList<>(); seasonsNew.add(seasonNew1); seasonsNew.add(seasonNew2); Habitat habitatNew1 = new Habitat(); habitatNew1.setHabitatId(1); Habitat habitatNew2 = new Habitat(); habitatNew2.setHabitatId(2); List<Habitat> habitatsNew = new java.util.ArrayList<>(); habitatsNew.add(habitatNew1); habitatsNew.add(habitatNew2); Organism eatenByOrganismNew1 = new Organism(); eatenByOrganismNew1.setOrganismId(1); Organism eatenByOrganismNew2 = new Organism(); eatenByOrganismNew2.setOrganismId(2); List<Organism> eatenByOrganismsNew = new java.util.ArrayList<>(); eatenByOrganismsNew.add(eatenByOrganismNew1); eatenByOrganismsNew.add(eatenByOrganismNew2); Organism eatingOrganismNew1 = new Organism(); eatingOrganismNew1.setOrganismId(3); Organism eatingOrganismNew2 = new Organism(); eatingOrganismNew2.setOrganismId(4); List<Organism> eatingOrganismsNew = new java.util.ArrayList<>(); eatingOrganismsNew.add(eatingOrganismNew1); eatingOrganismsNew.add(eatingOrganismNew2); Geolocation geoLocationNew1 = new Geolocation(); geoLocationNew1.setGeolocationId(1); Geolocation geoLocationNew2 = new Geolocation(); geoLocationNew2.setGeolocationId(2); List<Geolocation> geoLocationsNew = new java.util.ArrayList(); geoLocationsNew.add(geoLocationNew1); geoLocationsNew.add(geoLocationNew2); organismNew.setScientificName("ScientificNameInsert"); organismNew.setCommonName("CommonNameInsert"); organismNew.setLocalName("LocalNameInsert"); organismNew.setSubfamily(subfamilyNew); organismNew.setDescription("DescriptionInsert"); organismNew.setPopulation("PopulationInsert"); organismNew.setIndigenous(Boolean.TRUE); organismNew.setCultivated(Boolean.FALSE); organismNew.setEndangered(Boolean.TRUE); organismNew.setMedicinal(Boolean.FALSE); organismNew.setBenefits("BenefitsInsert"); organismNew.setDangerous("DangerousInsert"); organismNew.setThreats("ThreatsNew"); organismNew.setOpportunities("OpportunitiesInsert"); organismNew.setLinks("LinksInsert"); organismNew.setFoodName("FoodNameInsert"); organismNew.setFoodDescription("FoodDescriptionInsert"); organismNew.setValidated(Boolean.FALSE); organismNew.setSeason(seasonsNew); organismNew.setHabitat(habitatsNew); organismNew.setEatenByOrganism(eatenByOrganismsNew); organismNew.setEatingOrganisms(eatingOrganismsNew); organismNew.setGeolocations(geoLocationsNew); // Var om het id van de geïnserted organism in op te slaan. int organismIdNew = 0; // Methode om het organisme in de db op te slaan. // Resultaten van de selectAll() methode worden afgeprint in de console. System.out.println("-----Select All organisms-----"); DaOrganism.selectAll().stream().forEach((o) -> { System.out.println(o.getCommonName()); }); if (DaOrganism.checkOrganismExist(organismNew.getScientificName())) { System.out.println("---- organismNew exists: true ----"); System.out.println("---- insert aborted ----"); } else { System.out.println("---- organismNew exists: false ----"); System.out.println("---- insert succeeded ----"); // organismIdNew = DaOrganism.insert(organismNew); // Resultaten van de selectAll() methode worden afgeprint in de console. System.out.println("-----Select All organisms-----"); DaOrganism.selectAll().stream().forEach((o) -> { System.out.println(o.getCommonName()); }); } // Details van het nieuwe organisme. if (organismIdNew > 0) { // selectOneById() methode welke een organisme retourneerd, in dit geval het organisme dat net werd aangemaakt. organismSelectOne = DaOrganism.selectOneById(organismIdNew); System.out.println("-----Select one organism (inserted)-----"); System.out.println("Id: " + Integer.toString(organismSelectOne.getOrganismId())); System.out.println("ScientificName: " + organismSelectOne.getScientificName()); System.out.println("CommonName: " + organismSelectOne.getCommonName()); System.out.println("LocalName: " + organismSelectOne.getLocalName()); System.out.println("Subfamily: " + organismSelectOne.getSubfamily().getSubfamilyName()); System.out.println("Description: " + organismSelectOne.getDescription()); System.out.println("Population: " + organismSelectOne.getPopulation()); System.out.println("Indigenous: " + Boolean.toString(organismSelectOne.getIndigenous())); System.out.println("Cultivated: " + Boolean.toString(organismSelectOne.getCultivated())); System.out.println("Endangered: " + Boolean.toString(organismSelectOne.getEndangered())); System.out.println("Medicinal: " + Boolean.toString(organismSelectOne.getMedicinal())); System.out.println("Benefits: " + organismSelectOne.getBenefits()); System.out.println("Dangerous: " + organismSelectOne.getDangerous()); System.out.println("Threats: " + organismSelectOne.getThreats()); System.out.println("Opportunities: " + organismSelectOne.getOpportunities()); System.out.println("Links: " + organismSelectOne.getLinks()); System.out.println("FoodName: " + organismSelectOne.getFoodName()); System.out.println("FoodDescription: " + organismSelectOne.getFoodDescription()); System.out.println("IsValidated: " + organismSelectOne.getValidated()); System.out.println("InsertedOn: " + new java.text.SimpleDateFormat("yyyy-MM-dd").format(organismSelectOne.getInsertedOn())); System.out.println("Seasons: "); for (Season s : organismSelectOne.getSeason()) {System.out.println("- " + s.getSeasonName());} System.out.println("Habitats: "); for (Habitat h : organismSelectOne.getHabitat()) {System.out.println("- " + h.getHabitatName());} System.out.println("EatenByOrganisms: "); for (Organism o : organismSelectOne.getEatenByOrganism()) {System.out.println("- " + o.getCommonName());} System.out.println("EatingOrganisms: "); for (Organism o : organismSelectOne.getEatingOrganisms()) {System.out.println("- " + o.getCommonName());} System.out.println("Geolocations: "); for (Geolocation g : organismSelectOne.getGeolocations()) {System.out.println("- " + g.getAreaName());} // Objecten om een update mee uit te voeren op een organismen. Subfamily subfamilyUpdate = new Subfamily(); subfamilyUpdate.setSubfamilyId(2); Season seasonUpdate1 = new Season(); seasonUpdate1.setSeasonId(3); Season seasonUpdate2 = new Season(); seasonUpdate2.setSeasonId(4); List<Season> seasonsUpdate = new java.util.ArrayList<>(); seasonsUpdate.add(seasonUpdate1); seasonsUpdate.add(seasonUpdate2); Habitat habitatUpdate1 = new Habitat(); habitatUpdate1.setHabitatId(3); Habitat habitatUpdate2 = new Habitat(); habitatUpdate2.setHabitatId(4); List<Habitat> habitatsUpdate = new java.util.ArrayList<>(); habitatsUpdate.add(habitatUpdate1); habitatsUpdate.add(habitatUpdate2); Organism eatenByOrganismUpdate1 = new Organism(); eatenByOrganismUpdate1.setOrganismId(3); Organism eatenByOrganismUpdate2 = new Organism(); eatenByOrganismUpdate2.setOrganismId(4); List<Organism> eatenByOrganismsUpdate = new java.util.ArrayList<>(); eatenByOrganismsUpdate.add(eatenByOrganismUpdate1); eatenByOrganismsUpdate.add(eatenByOrganismUpdate2); Organism eatingOrganismUpdate1 = new Organism(); eatingOrganismUpdate1.setOrganismId(1); Organism eatingOrganismUpdate2 = new Organism(); eatingOrganismUpdate2.setOrganismId(2); List<Organism> eatingOrganismsUpdate = new java.util.ArrayList<>(); eatingOrganismsUpdate.add(eatingOrganismUpdate1); eatingOrganismsUpdate.add(eatingOrganismUpdate2); Geolocation geoLocationUpdate1 = new Geolocation(); geoLocationUpdate1.setGeolocationId(3); Geolocation geoLocationUpdate2 = new Geolocation(); geoLocationUpdate2.setGeolocationId(4); List<Geolocation> geoLocationsUpdate = new java.util.ArrayList(); geoLocationsUpdate.add(geoLocationUpdate1); geoLocationsUpdate.add(geoLocationUpdate2); // Het Id wordt hier meegegeven zodat de methode weet welk organisme eht moet updaten. organismUpdate.setOrganismId(organismIdNew); organismUpdate.setScientificName("Dhofari goat"); organismUpdate.setCommonName("CommonNameUpdate"); organismUpdate.setLocalName("LocalNameUpdate"); organismUpdate.setSubfamily(subfamilyUpdate); organismUpdate.setDescription("DescriptionUpdate"); organismUpdate.setPopulation("PopulationUpdate"); organismUpdate.setIndigenous(Boolean.FALSE); organismUpdate.setCultivated(Boolean.TRUE); organismUpdate.setEndangered(Boolean.FALSE); organismUpdate.setMedicinal(Boolean.TRUE); organismUpdate.setBenefits("BenefitsUpdate"); organismUpdate.setDangerous("DangerousUpdate"); organismUpdate.setThreats("ThreatsUpdate"); organismUpdate.setOpportunities("OpportunitiesUpdate"); organismUpdate.setLinks("LinksUpdate"); organismUpdate.setFoodName("FoodNameUpdate"); organismUpdate.setFoodDescription("FoodDescriptionUpdate"); organismUpdate.setValidated(Boolean.TRUE); organismUpdate.setSeason(seasonsUpdate); organismUpdate.setHabitat(habitatsUpdate); organismUpdate.setEatenByOrganism(eatenByOrganismsUpdate); organismUpdate.setEatingOrganisms(eatingOrganismsUpdate); organismUpdate.setGeolocations(geoLocationsUpdate); if (DaOrganism.checkOrganismExist(organismUpdate.getScientificName(), organismIdNew)) { System.out.println("---- organismUpdate exists: true ----"); System.out.println("---- update aborted ----"); } else { DaOrganism.update(organismUpdate); System.out.println("---- organismUpdate exists: false ----"); System.out.println("---- update succeeded ----"); // selectOneById() methode welke een organisme retourneerd, in dit geval het organisme dat aangepast werd aangemaakt. organismSelectOne = DaOrganism.selectOneById(organismIdNew); System.out.println("-----Select one organism (updated)-----"); System.out.println("Id: " + Integer.toString(organismSelectOne.getOrganismId())); System.out.println("ScientificName: " + organismSelectOne.getScientificName()); System.out.println("CommonName: " + organismSelectOne.getCommonName()); System.out.println("LocalName: " + organismSelectOne.getLocalName()); System.out.println("Subfamily: " + organismSelectOne.getSubfamily().getSubfamilyName()); System.out.println("Description: " + organismSelectOne.getDescription()); System.out.println("Population: " + organismSelectOne.getPopulation()); System.out.println("Indigenous: " + Boolean.toString(organismSelectOne.getIndigenous())); System.out.println("Cultivated: " + Boolean.toString(organismSelectOne.getCultivated())); System.out.println("Endangered: " + Boolean.toString(organismSelectOne.getEndangered())); System.out.println("Medicinal: " + Boolean.toString(organismSelectOne.getMedicinal())); System.out.println("Benefits: " + organismSelectOne.getBenefits()); System.out.println("Dangerous: " + organismSelectOne.getDangerous()); System.out.println("Threats: " + organismSelectOne.getThreats()); System.out.println("Opportunities: " + organismSelectOne.getOpportunities()); System.out.println("Links: " + organismSelectOne.getLinks()); System.out.println("FoodName: " + organismSelectOne.getFoodName()); System.out.println("FoodDescription: " + organismSelectOne.getFoodDescription()); System.out.println("IsValidated: " + organismSelectOne.getValidated()); System.out.println("UpdatedOn: " + new java.text.SimpleDateFormat("yyyy-MM-dd").format(organismSelectOne.getUpdatedOn())); System.out.println("Seasons: "); for (Season s : organismSelectOne.getSeason()) {System.out.println("- " + s.getSeasonName());} System.out.println("Habitats: "); for (Habitat h : organismSelectOne.getHabitat()) {System.out.println("- " + h.getHabitatName());} System.out.println("EatenByOrganisms: "); for (Organism o : organismSelectOne.getEatenByOrganism()) {System.out.println("- " + o.getCommonName());} System.out.println("EatingOrganisms: "); for (Organism o : organismSelectOne.getEatingOrganisms()) {System.out.println("- " + o.getCommonName());} System.out.println("Geolocations: "); for (Geolocation g : organismSelectOne.getGeolocations()) {System.out.println("- " + g.getAreaName());} System.out.println("-----Delete organismUpdate-----"); DaOrganism.deleteOrganism(organismIdNew); } // Resultaten van de selectAll() methode worden afgeprint in de console. System.out.println("-----Select All organisms -----"); DaOrganism.selectAll().stream().forEach((o) -> { System.out.println(o.getCommonName());}); } else { System.out.println("ErrorCode: "+ organismIdNew); } } }
Biodiversity-Oman/ProjectOman
Project/jury/src/java/UT/UtDaOrganism.java
4,537
// De objecten waarmee een insert van een organisme op uitgevoerd worden.
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 UT; import BLL.*; import DAL.*; import java.sql.SQLException; import java.util.List; /** * * @author bert */ public class UtDaOrganism { public static void main(String[] args) throws SQLException { Organism organismNew = new Organism(); Organism organismUpdate = new Organism(); Organism organismSelectOne = new Organism(); // De objecten<SUF> Subfamily subfamilyNew = new Subfamily(); subfamilyNew.setSubfamilyId(1); Season seasonNew1 = new Season(); seasonNew1.setSeasonId(1); Season seasonNew2 = new Season(); seasonNew2.setSeasonId(2); List<Season> seasonsNew = new java.util.ArrayList<>(); seasonsNew.add(seasonNew1); seasonsNew.add(seasonNew2); Habitat habitatNew1 = new Habitat(); habitatNew1.setHabitatId(1); Habitat habitatNew2 = new Habitat(); habitatNew2.setHabitatId(2); List<Habitat> habitatsNew = new java.util.ArrayList<>(); habitatsNew.add(habitatNew1); habitatsNew.add(habitatNew2); Organism eatenByOrganismNew1 = new Organism(); eatenByOrganismNew1.setOrganismId(1); Organism eatenByOrganismNew2 = new Organism(); eatenByOrganismNew2.setOrganismId(2); List<Organism> eatenByOrganismsNew = new java.util.ArrayList<>(); eatenByOrganismsNew.add(eatenByOrganismNew1); eatenByOrganismsNew.add(eatenByOrganismNew2); Organism eatingOrganismNew1 = new Organism(); eatingOrganismNew1.setOrganismId(3); Organism eatingOrganismNew2 = new Organism(); eatingOrganismNew2.setOrganismId(4); List<Organism> eatingOrganismsNew = new java.util.ArrayList<>(); eatingOrganismsNew.add(eatingOrganismNew1); eatingOrganismsNew.add(eatingOrganismNew2); Geolocation geoLocationNew1 = new Geolocation(); geoLocationNew1.setGeolocationId(1); Geolocation geoLocationNew2 = new Geolocation(); geoLocationNew2.setGeolocationId(2); List<Geolocation> geoLocationsNew = new java.util.ArrayList(); geoLocationsNew.add(geoLocationNew1); geoLocationsNew.add(geoLocationNew2); organismNew.setScientificName("ScientificNameInsert"); organismNew.setCommonName("CommonNameInsert"); organismNew.setLocalName("LocalNameInsert"); organismNew.setSubfamily(subfamilyNew); organismNew.setDescription("DescriptionInsert"); organismNew.setPopulation("PopulationInsert"); organismNew.setIndigenous(Boolean.TRUE); organismNew.setCultivated(Boolean.FALSE); organismNew.setEndangered(Boolean.TRUE); organismNew.setMedicinal(Boolean.FALSE); organismNew.setBenefits("BenefitsInsert"); organismNew.setDangerous("DangerousInsert"); organismNew.setThreats("ThreatsNew"); organismNew.setOpportunities("OpportunitiesInsert"); organismNew.setLinks("LinksInsert"); organismNew.setFoodName("FoodNameInsert"); organismNew.setFoodDescription("FoodDescriptionInsert"); organismNew.setValidated(Boolean.FALSE); organismNew.setSeason(seasonsNew); organismNew.setHabitat(habitatsNew); organismNew.setEatenByOrganism(eatenByOrganismsNew); organismNew.setEatingOrganisms(eatingOrganismsNew); organismNew.setGeolocations(geoLocationsNew); // Var om het id van de geïnserted organism in op te slaan. int organismIdNew = 0; // Methode om het organisme in de db op te slaan. // Resultaten van de selectAll() methode worden afgeprint in de console. System.out.println("-----Select All organisms-----"); DaOrganism.selectAll().stream().forEach((o) -> { System.out.println(o.getCommonName()); }); if (DaOrganism.checkOrganismExist(organismNew.getScientificName())) { System.out.println("---- organismNew exists: true ----"); System.out.println("---- insert aborted ----"); } else { System.out.println("---- organismNew exists: false ----"); System.out.println("---- insert succeeded ----"); // organismIdNew = DaOrganism.insert(organismNew); // Resultaten van de selectAll() methode worden afgeprint in de console. System.out.println("-----Select All organisms-----"); DaOrganism.selectAll().stream().forEach((o) -> { System.out.println(o.getCommonName()); }); } // Details van het nieuwe organisme. if (organismIdNew > 0) { // selectOneById() methode welke een organisme retourneerd, in dit geval het organisme dat net werd aangemaakt. organismSelectOne = DaOrganism.selectOneById(organismIdNew); System.out.println("-----Select one organism (inserted)-----"); System.out.println("Id: " + Integer.toString(organismSelectOne.getOrganismId())); System.out.println("ScientificName: " + organismSelectOne.getScientificName()); System.out.println("CommonName: " + organismSelectOne.getCommonName()); System.out.println("LocalName: " + organismSelectOne.getLocalName()); System.out.println("Subfamily: " + organismSelectOne.getSubfamily().getSubfamilyName()); System.out.println("Description: " + organismSelectOne.getDescription()); System.out.println("Population: " + organismSelectOne.getPopulation()); System.out.println("Indigenous: " + Boolean.toString(organismSelectOne.getIndigenous())); System.out.println("Cultivated: " + Boolean.toString(organismSelectOne.getCultivated())); System.out.println("Endangered: " + Boolean.toString(organismSelectOne.getEndangered())); System.out.println("Medicinal: " + Boolean.toString(organismSelectOne.getMedicinal())); System.out.println("Benefits: " + organismSelectOne.getBenefits()); System.out.println("Dangerous: " + organismSelectOne.getDangerous()); System.out.println("Threats: " + organismSelectOne.getThreats()); System.out.println("Opportunities: " + organismSelectOne.getOpportunities()); System.out.println("Links: " + organismSelectOne.getLinks()); System.out.println("FoodName: " + organismSelectOne.getFoodName()); System.out.println("FoodDescription: " + organismSelectOne.getFoodDescription()); System.out.println("IsValidated: " + organismSelectOne.getValidated()); System.out.println("InsertedOn: " + new java.text.SimpleDateFormat("yyyy-MM-dd").format(organismSelectOne.getInsertedOn())); System.out.println("Seasons: "); for (Season s : organismSelectOne.getSeason()) {System.out.println("- " + s.getSeasonName());} System.out.println("Habitats: "); for (Habitat h : organismSelectOne.getHabitat()) {System.out.println("- " + h.getHabitatName());} System.out.println("EatenByOrganisms: "); for (Organism o : organismSelectOne.getEatenByOrganism()) {System.out.println("- " + o.getCommonName());} System.out.println("EatingOrganisms: "); for (Organism o : organismSelectOne.getEatingOrganisms()) {System.out.println("- " + o.getCommonName());} System.out.println("Geolocations: "); for (Geolocation g : organismSelectOne.getGeolocations()) {System.out.println("- " + g.getAreaName());} // Objecten om een update mee uit te voeren op een organismen. Subfamily subfamilyUpdate = new Subfamily(); subfamilyUpdate.setSubfamilyId(2); Season seasonUpdate1 = new Season(); seasonUpdate1.setSeasonId(3); Season seasonUpdate2 = new Season(); seasonUpdate2.setSeasonId(4); List<Season> seasonsUpdate = new java.util.ArrayList<>(); seasonsUpdate.add(seasonUpdate1); seasonsUpdate.add(seasonUpdate2); Habitat habitatUpdate1 = new Habitat(); habitatUpdate1.setHabitatId(3); Habitat habitatUpdate2 = new Habitat(); habitatUpdate2.setHabitatId(4); List<Habitat> habitatsUpdate = new java.util.ArrayList<>(); habitatsUpdate.add(habitatUpdate1); habitatsUpdate.add(habitatUpdate2); Organism eatenByOrganismUpdate1 = new Organism(); eatenByOrganismUpdate1.setOrganismId(3); Organism eatenByOrganismUpdate2 = new Organism(); eatenByOrganismUpdate2.setOrganismId(4); List<Organism> eatenByOrganismsUpdate = new java.util.ArrayList<>(); eatenByOrganismsUpdate.add(eatenByOrganismUpdate1); eatenByOrganismsUpdate.add(eatenByOrganismUpdate2); Organism eatingOrganismUpdate1 = new Organism(); eatingOrganismUpdate1.setOrganismId(1); Organism eatingOrganismUpdate2 = new Organism(); eatingOrganismUpdate2.setOrganismId(2); List<Organism> eatingOrganismsUpdate = new java.util.ArrayList<>(); eatingOrganismsUpdate.add(eatingOrganismUpdate1); eatingOrganismsUpdate.add(eatingOrganismUpdate2); Geolocation geoLocationUpdate1 = new Geolocation(); geoLocationUpdate1.setGeolocationId(3); Geolocation geoLocationUpdate2 = new Geolocation(); geoLocationUpdate2.setGeolocationId(4); List<Geolocation> geoLocationsUpdate = new java.util.ArrayList(); geoLocationsUpdate.add(geoLocationUpdate1); geoLocationsUpdate.add(geoLocationUpdate2); // Het Id wordt hier meegegeven zodat de methode weet welk organisme eht moet updaten. organismUpdate.setOrganismId(organismIdNew); organismUpdate.setScientificName("Dhofari goat"); organismUpdate.setCommonName("CommonNameUpdate"); organismUpdate.setLocalName("LocalNameUpdate"); organismUpdate.setSubfamily(subfamilyUpdate); organismUpdate.setDescription("DescriptionUpdate"); organismUpdate.setPopulation("PopulationUpdate"); organismUpdate.setIndigenous(Boolean.FALSE); organismUpdate.setCultivated(Boolean.TRUE); organismUpdate.setEndangered(Boolean.FALSE); organismUpdate.setMedicinal(Boolean.TRUE); organismUpdate.setBenefits("BenefitsUpdate"); organismUpdate.setDangerous("DangerousUpdate"); organismUpdate.setThreats("ThreatsUpdate"); organismUpdate.setOpportunities("OpportunitiesUpdate"); organismUpdate.setLinks("LinksUpdate"); organismUpdate.setFoodName("FoodNameUpdate"); organismUpdate.setFoodDescription("FoodDescriptionUpdate"); organismUpdate.setValidated(Boolean.TRUE); organismUpdate.setSeason(seasonsUpdate); organismUpdate.setHabitat(habitatsUpdate); organismUpdate.setEatenByOrganism(eatenByOrganismsUpdate); organismUpdate.setEatingOrganisms(eatingOrganismsUpdate); organismUpdate.setGeolocations(geoLocationsUpdate); if (DaOrganism.checkOrganismExist(organismUpdate.getScientificName(), organismIdNew)) { System.out.println("---- organismUpdate exists: true ----"); System.out.println("---- update aborted ----"); } else { DaOrganism.update(organismUpdate); System.out.println("---- organismUpdate exists: false ----"); System.out.println("---- update succeeded ----"); // selectOneById() methode welke een organisme retourneerd, in dit geval het organisme dat aangepast werd aangemaakt. organismSelectOne = DaOrganism.selectOneById(organismIdNew); System.out.println("-----Select one organism (updated)-----"); System.out.println("Id: " + Integer.toString(organismSelectOne.getOrganismId())); System.out.println("ScientificName: " + organismSelectOne.getScientificName()); System.out.println("CommonName: " + organismSelectOne.getCommonName()); System.out.println("LocalName: " + organismSelectOne.getLocalName()); System.out.println("Subfamily: " + organismSelectOne.getSubfamily().getSubfamilyName()); System.out.println("Description: " + organismSelectOne.getDescription()); System.out.println("Population: " + organismSelectOne.getPopulation()); System.out.println("Indigenous: " + Boolean.toString(organismSelectOne.getIndigenous())); System.out.println("Cultivated: " + Boolean.toString(organismSelectOne.getCultivated())); System.out.println("Endangered: " + Boolean.toString(organismSelectOne.getEndangered())); System.out.println("Medicinal: " + Boolean.toString(organismSelectOne.getMedicinal())); System.out.println("Benefits: " + organismSelectOne.getBenefits()); System.out.println("Dangerous: " + organismSelectOne.getDangerous()); System.out.println("Threats: " + organismSelectOne.getThreats()); System.out.println("Opportunities: " + organismSelectOne.getOpportunities()); System.out.println("Links: " + organismSelectOne.getLinks()); System.out.println("FoodName: " + organismSelectOne.getFoodName()); System.out.println("FoodDescription: " + organismSelectOne.getFoodDescription()); System.out.println("IsValidated: " + organismSelectOne.getValidated()); System.out.println("UpdatedOn: " + new java.text.SimpleDateFormat("yyyy-MM-dd").format(organismSelectOne.getUpdatedOn())); System.out.println("Seasons: "); for (Season s : organismSelectOne.getSeason()) {System.out.println("- " + s.getSeasonName());} System.out.println("Habitats: "); for (Habitat h : organismSelectOne.getHabitat()) {System.out.println("- " + h.getHabitatName());} System.out.println("EatenByOrganisms: "); for (Organism o : organismSelectOne.getEatenByOrganism()) {System.out.println("- " + o.getCommonName());} System.out.println("EatingOrganisms: "); for (Organism o : organismSelectOne.getEatingOrganisms()) {System.out.println("- " + o.getCommonName());} System.out.println("Geolocations: "); for (Geolocation g : organismSelectOne.getGeolocations()) {System.out.println("- " + g.getAreaName());} System.out.println("-----Delete organismUpdate-----"); DaOrganism.deleteOrganism(organismIdNew); } // Resultaten van de selectAll() methode worden afgeprint in de console. System.out.println("-----Select All organisms -----"); DaOrganism.selectAll().stream().forEach((o) -> { System.out.println(o.getCommonName());}); } else { System.out.println("ErrorCode: "+ organismIdNew); } } }
44537_11
//============================================================================================================= // // Project: Directional Image Analysis - OrientationJ plugins // // Author: Daniel Sage // // Organization: Biomedical Imaging Group (BIG) // Ecole Polytechnique Federale de Lausanne (EPFL), Lausanne, Switzerland // // Information: // OrientationJ: http://bigwww.epfl.ch/demo/orientation/ // MonogenicJ: http://bigwww.epfl.ch/demo/monogenic/ // // Reference on methods and plugins // Z. Püspöki, M. Storath, D. Sage, M. Unser // Transforms and Operators for Directional Bioimage Analysis: A Survey // Advances in Anatomy, Embryology and Cell Biology, vol. 219, Focus on Bio-Image Informatics // Springer International Publishing, ch. 33, 2016. // // // Reference the application measure of coherency // R. Rezakhaniha, A. Agianniotis, J.T.C. Schrauwen, A. Griffa, D. Sage, // C.V.C. Bouten, F.N. van de Vosse, M. Unser, N. Stergiopulos // Experimental Investigation of Collagen Waviness and Orientation in the Arterial Adventitia // Using Confocal Laser Scanning Microscopy // Biomechanics and Modeling in Mechanobiology, vol. 11, no. 3-4, 2012. // Reference the application direction of orientation // E. Fonck, G.G. Feigl, J. Fasel, D. Sage, M. Unser, D.A. Ruefenacht, N. Stergiopulos // Effect of Aging on Elastin Functionality in Human Cerebral Arteries // Stroke, vol. 40, no. 7, 2009. // // Conditions of use: You are free to use this software for research or // educational purposes. In addition, we expect you to include adequate // citations and acknowledgments whenever you present or publish results that // are based on it. // //============================================================================================================= package orientation; public class Corner implements Comparable<Corner> { public int x; public int y; public int t; private double harris; public Corner(int x, int y, int t, double harris) { this.x = x; this.y = y; this.t = t; this.harris = harris; } public double getHarrisIndex() { return harris; } @Override public int compareTo(Corner o) { return (o.getHarrisIndex() < this.harris ? -1 : (o.getHarrisIndex() == this.harris ? 0 : 1)); } }
Biomedical-Imaging-Group/OrientationJ
src/main/java/orientation/Corner.java
724
// C.V.C. Bouten, F.N. van de Vosse, M. Unser, N. Stergiopulos
line_comment
nl
//============================================================================================================= // // Project: Directional Image Analysis - OrientationJ plugins // // Author: Daniel Sage // // Organization: Biomedical Imaging Group (BIG) // Ecole Polytechnique Federale de Lausanne (EPFL), Lausanne, Switzerland // // Information: // OrientationJ: http://bigwww.epfl.ch/demo/orientation/ // MonogenicJ: http://bigwww.epfl.ch/demo/monogenic/ // // Reference on methods and plugins // Z. Püspöki, M. Storath, D. Sage, M. Unser // Transforms and Operators for Directional Bioimage Analysis: A Survey // Advances in Anatomy, Embryology and Cell Biology, vol. 219, Focus on Bio-Image Informatics // Springer International Publishing, ch. 33, 2016. // // // Reference the application measure of coherency // R. Rezakhaniha, A. Agianniotis, J.T.C. Schrauwen, A. Griffa, D. Sage, // C.V.C. Bouten,<SUF> // Experimental Investigation of Collagen Waviness and Orientation in the Arterial Adventitia // Using Confocal Laser Scanning Microscopy // Biomechanics and Modeling in Mechanobiology, vol. 11, no. 3-4, 2012. // Reference the application direction of orientation // E. Fonck, G.G. Feigl, J. Fasel, D. Sage, M. Unser, D.A. Ruefenacht, N. Stergiopulos // Effect of Aging on Elastin Functionality in Human Cerebral Arteries // Stroke, vol. 40, no. 7, 2009. // // Conditions of use: You are free to use this software for research or // educational purposes. In addition, we expect you to include adequate // citations and acknowledgments whenever you present or publish results that // are based on it. // //============================================================================================================= package orientation; public class Corner implements Comparable<Corner> { public int x; public int y; public int t; private double harris; public Corner(int x, int y, int t, double harris) { this.x = x; this.y = y; this.t = t; this.harris = harris; } public double getHarrisIndex() { return harris; } @Override public int compareTo(Corner o) { return (o.getHarrisIndex() < this.harris ? -1 : (o.getHarrisIndex() == this.harris ? 0 : 1)); } }
18997_10
/* * Concept profile generation and analysis for Gene-Disease paper * Copyright (C) 2015 Biosemantics Group, Leiden University Medical Center * Leiden, The Netherlands * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package KnowledgeTransfer; import org.erasmusmc.collections.IntList; import org.erasmusmc.collections.SortedIntList2FloatMap; import org.erasmusmc.collections.SortedIntListSet; import org.erasmusmc.groundhog.Groundhog; import org.erasmusmc.groundhog.GroundhogManager; import org.erasmusmc.ontology.ConceptVector; import org.erasmusmc.ontology.ConceptVectorRecord; public class ReadMedlineGroundhog { /** * @param args */ public static void main(String[] args) { String path2folder = "/home/hvanhaagen/textmining/Groundhogs/"; //String folder = "Medline1980till17Jul2012_UMLS2010ABHomologeneJochemToxV1_6"; String folder = "Medline1980till17Jul2012_UMLS2010ABHomologeneJochemToxV1_6-test38"; // Voorbeeld concept Integer cid1 = 20179; //Huntington Disease // Declareer een medline groundhog volgens de legacy code. Groundhog documentProfilesGroundhog; GroundhogManager groundhogmanager2 = new GroundhogManager(path2folder); documentProfilesGroundhog = groundhogmanager2.getGroundhog(folder); // concept id (1) -> PMIDs (many) // dit is de eerste mapping die in de medline groundhog moet zitten. SortedIntListSet pmids = documentProfilesGroundhog.getRecordIDsForConcept(cid1); // Loop over de PMIDs. Controleer voor sommige PMIDs of je Huntington in het abstract terugvindt. // for(Integer pmid:pmids){ // System.out.println(pmid); // } // Bereken het aantal artikelen waar Huntington in voorkomt. System.out.println(pmids.size()); ///////////////////////////////////////////////////////////////////////////////////////// // Neem een willekeurig PMID int random_pmid = 1280937; //Haal de concept IDs op die in dat abstract voorkomen. PMID (1) -> concept ids (many) ConceptVectorRecord cvr = documentProfilesGroundhog.get(random_pmid); // Haal de bananenschil eraf (legacy code) ConceptVector cv = cvr.getConceptVector(); SortedIntList2FloatMap sil2fm = cv.values; IntList keys = sil2fm.keys(); // Loop over de keys. De keys zijn de concept ids. Voor elk concept checken we de frequentie // hoevaak deze voorkomt in het abstract for(Integer key:keys){ float frequency = sil2fm.get(key); System.out.println(key+"\t"+frequency); } } }
BiosemanticsDotOrg/GeneDiseasePaper
java/NewConceptProfile/src/KnowledgeTransfer/ReadMedlineGroundhog.java
1,004
// Haal de bananenschil eraf (legacy code)
line_comment
nl
/* * Concept profile generation and analysis for Gene-Disease paper * Copyright (C) 2015 Biosemantics Group, Leiden University Medical Center * Leiden, The Netherlands * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package KnowledgeTransfer; import org.erasmusmc.collections.IntList; import org.erasmusmc.collections.SortedIntList2FloatMap; import org.erasmusmc.collections.SortedIntListSet; import org.erasmusmc.groundhog.Groundhog; import org.erasmusmc.groundhog.GroundhogManager; import org.erasmusmc.ontology.ConceptVector; import org.erasmusmc.ontology.ConceptVectorRecord; public class ReadMedlineGroundhog { /** * @param args */ public static void main(String[] args) { String path2folder = "/home/hvanhaagen/textmining/Groundhogs/"; //String folder = "Medline1980till17Jul2012_UMLS2010ABHomologeneJochemToxV1_6"; String folder = "Medline1980till17Jul2012_UMLS2010ABHomologeneJochemToxV1_6-test38"; // Voorbeeld concept Integer cid1 = 20179; //Huntington Disease // Declareer een medline groundhog volgens de legacy code. Groundhog documentProfilesGroundhog; GroundhogManager groundhogmanager2 = new GroundhogManager(path2folder); documentProfilesGroundhog = groundhogmanager2.getGroundhog(folder); // concept id (1) -> PMIDs (many) // dit is de eerste mapping die in de medline groundhog moet zitten. SortedIntListSet pmids = documentProfilesGroundhog.getRecordIDsForConcept(cid1); // Loop over de PMIDs. Controleer voor sommige PMIDs of je Huntington in het abstract terugvindt. // for(Integer pmid:pmids){ // System.out.println(pmid); // } // Bereken het aantal artikelen waar Huntington in voorkomt. System.out.println(pmids.size()); ///////////////////////////////////////////////////////////////////////////////////////// // Neem een willekeurig PMID int random_pmid = 1280937; //Haal de concept IDs op die in dat abstract voorkomen. PMID (1) -> concept ids (many) ConceptVectorRecord cvr = documentProfilesGroundhog.get(random_pmid); // Haal de<SUF> ConceptVector cv = cvr.getConceptVector(); SortedIntList2FloatMap sil2fm = cv.values; IntList keys = sil2fm.keys(); // Loop over de keys. De keys zijn de concept ids. Voor elk concept checken we de frequentie // hoevaak deze voorkomt in het abstract for(Integer key:keys){ float frequency = sil2fm.get(key); System.out.println(key+"\t"+frequency); } } }
160653_7
/** * SimpleFPSCamera.java * * Copyright (c) 2013-2016, F(X)yz * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of F(X)yz, any associated website, nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL F(X)yz 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. */ package org.fxyz3d.scene; import javafx.animation.AnimationTimer; import javafx.beans.property.ReadOnlyObjectProperty; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.geometry.Point3D; import javafx.scene.Group; import javafx.scene.Parent; import javafx.scene.PerspectiveCamera; import javafx.scene.Scene; import javafx.scene.SubScene; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.input.ScrollEvent; import javafx.scene.transform.Affine; import javafx.scene.transform.Rotate; import javafx.scene.transform.Transform; import javafx.scene.transform.Translate; import javafx.util.Callback; import org.fxyz3d.geometry.MathUtils; /** * A self initializing First Person Shooter camera * * @author Jason Pollastrini aka jdub1581 */ public class SimpleFPSCamera extends Parent { public SimpleFPSCamera() { initialize(); } private void update() { updateControls(); } private void updateControls() { if (fwd && !back) { moveForward(); } if (strafeL) { strafeLeft(); } if (strafeR) { strafeRight(); } if (back && !fwd) { moveBack(); } if (up && !down) { moveUp(); } if (down && !up) { moveDown(); } } /*========================================================================== Initialization */ private final Group root = new Group(); private final Affine affine = new Affine(); private final Translate t = new Translate(0, 0, 0); private final Rotate rotateX = new Rotate(0, Rotate.X_AXIS), rotateY = new Rotate(0, Rotate.Y_AXIS), rotateZ = new Rotate(0, Rotate.Z_AXIS); private boolean fwd, strafeL, strafeR, back, up, down, shift; private double mouseSpeed = 1.0, mouseModifier = 0.1; private double moveSpeed = 10.0; private double mousePosX; private double mousePosY; private double mouseOldX; private double mouseOldY; private double mouseDeltaX; private double mouseDeltaY; private void initialize() { getChildren().add(root); getTransforms().add(affine); initializeCamera(); startUpdateThread(); } public void loadControlsForSubScene(SubScene scene) { sceneProperty().addListener(l -> { if (getScene() != null) { getScene().addEventHandler(KeyEvent.ANY, ke -> { if (ke.getEventType() == KeyEvent.KEY_PRESSED) { switch (ke.getCode()) { case Q: up = true; break; case E: down = true; break; case W: fwd = true; break; case S: back = true; break; case A: strafeL = true; break; case D: strafeR = true; break; case SHIFT: shift = true; moveSpeed = 20; break; } } else if (ke.getEventType() == KeyEvent.KEY_RELEASED) { switch (ke.getCode()) { case Q: up = false; break; case E: down = false; break; case W: fwd = false; break; case S: back = false; break; case A: strafeL = false; break; case D: strafeR = false; break; case SHIFT: moveSpeed = 10; shift = false; break; } } ke.consume(); }); } }); scene.addEventHandler(MouseEvent.ANY, me -> { if (me.getEventType().equals(MouseEvent.MOUSE_PRESSED)) { mousePosX = me.getSceneX(); mousePosY = me.getSceneY(); mouseOldX = me.getSceneX(); mouseOldY = me.getSceneY(); } else if (me.getEventType().equals(MouseEvent.MOUSE_DRAGGED)) { mouseOldX = mousePosX; mouseOldY = mousePosY; mousePosX = me.getSceneX(); mousePosY = me.getSceneY(); mouseDeltaX = (mousePosX - mouseOldX); mouseDeltaY = (mousePosY - mouseOldY); mouseSpeed = 1.0; mouseModifier = 0.1; if (me.isPrimaryButtonDown()) { if (me.isControlDown()) { mouseSpeed = 0.1; } if (me.isShiftDown()) { mouseSpeed = 1.0; } t.setX(getPosition().getX()); t.setY(getPosition().getY()); t.setZ(getPosition().getZ()); affine.setToIdentity(); rotateY.setAngle( MathUtils.clamp(-360, ((rotateY.getAngle() + mouseDeltaX * (mouseSpeed * mouseModifier)) % 360 + 540) % 360 - 180, 360) ); // horizontal rotateX.setAngle( MathUtils.clamp(-45, ((rotateX.getAngle() - mouseDeltaY * (mouseSpeed * mouseModifier)) % 360 + 540) % 360 - 180, 35) ); // vertical affine.prepend(t.createConcatenation(rotateY.createConcatenation(rotateX))); } else if (me.isSecondaryButtonDown()) { /* init zoom? */ } else if (me.isMiddleButtonDown()) { /* init panning? */ } } }); scene.addEventHandler(ScrollEvent.ANY, se -> { if (se.getEventType().equals(ScrollEvent.SCROLL_STARTED)) { } else if (se.getEventType().equals(ScrollEvent.SCROLL)) { } else if (se.getEventType().equals(ScrollEvent.SCROLL_FINISHED)) { } }); } public void loadControlsForScene(Scene scene) { scene.addEventHandler(KeyEvent.ANY, ke -> { if (ke.getEventType() == KeyEvent.KEY_PRESSED) { switch (ke.getCode()) { case Q: up = true; break; case E: down = true; break; case W: fwd = true; break; case S: back = true; break; case A: strafeL = true; break; case D: strafeR = true; break; case SHIFT: shift = true; moveSpeed = 20; break; } } else if (ke.getEventType() == KeyEvent.KEY_RELEASED) { switch (ke.getCode()) { case Q: up = false; break; case E: down = false; break; case W: fwd = false; break; case S: back = false; break; case A: strafeL = false; break; case D: strafeR = false; break; case SHIFT: moveSpeed = 10; shift = false; break; } } ke.consume(); }); scene.addEventHandler(MouseEvent.ANY, me -> { if (me.getEventType().equals(MouseEvent.MOUSE_PRESSED)) { mousePosX = me.getSceneX(); mousePosY = me.getSceneY(); mouseOldX = me.getSceneX(); mouseOldY = me.getSceneY(); } else if (me.getEventType().equals(MouseEvent.MOUSE_DRAGGED)) { mouseOldX = mousePosX; mouseOldY = mousePosY; mousePosX = me.getSceneX(); mousePosY = me.getSceneY(); mouseDeltaX = (mousePosX - mouseOldX); mouseDeltaY = (mousePosY - mouseOldY); mouseSpeed = 1.0; mouseModifier = 0.1; if (me.isPrimaryButtonDown()) { if (me.isControlDown()) { mouseSpeed = 0.1; } if (me.isShiftDown()) { mouseSpeed = 1.0; } t.setX(getPosition().getX()); t.setY(getPosition().getY()); t.setZ(getPosition().getZ()); affine.setToIdentity(); rotateY.setAngle( MathUtils.clamp(-360, ((rotateY.getAngle() + mouseDeltaX * (mouseSpeed * mouseModifier)) % 360 + 540) % 360 - 180, 360) ); // horizontal rotateX.setAngle( MathUtils.clamp(-45, ((rotateX.getAngle() - mouseDeltaY * (mouseSpeed * mouseModifier)) % 360 + 540) % 360 - 180, 35) ); // vertical affine.prepend(t.createConcatenation(rotateY.createConcatenation(rotateX))); } else if (me.isSecondaryButtonDown()) { /* init zoom? */ } else if (me.isMiddleButtonDown()) { /* init panning? */ } } }); scene.addEventHandler(ScrollEvent.ANY, se -> { if (se.getEventType().equals(ScrollEvent.SCROLL_STARTED)) { } else if (se.getEventType().equals(ScrollEvent.SCROLL)) { } else if (se.getEventType().equals(ScrollEvent.SCROLL_FINISHED)) { } }); } private void initializeCamera() { getCamera().setNearClip(0.1); getCamera().setFarClip(100000); getCamera().setFieldOfView(42); getCamera().setVerticalFieldOfView(true); root.getChildren().add(getCamera()); } private void startUpdateThread() { new AnimationTimer() { @Override public void handle(long now) { update(); } }.start(); } /*========================================================================== Movement */ private void moveForward() { affine.setTx(getPosition().getX() + moveSpeed * getN().getX()); affine.setTy(getPosition().getY() + moveSpeed * getN().getY()); affine.setTz(getPosition().getZ() + moveSpeed * getN().getZ()); } private void strafeLeft() { affine.setTx(getPosition().getX() + moveSpeed * -getU().getX()); affine.setTy(getPosition().getY() + moveSpeed * -getU().getY()); affine.setTz(getPosition().getZ() + moveSpeed * -getU().getZ()); } private void strafeRight() { affine.setTx(getPosition().getX() + moveSpeed * getU().getX()); affine.setTy(getPosition().getY() + moveSpeed * getU().getY()); affine.setTz(getPosition().getZ() + moveSpeed * getU().getZ()); } private void moveBack() { affine.setTx(getPosition().getX() + moveSpeed * -getN().getX()); affine.setTy(getPosition().getY() + moveSpeed * -getN().getY()); affine.setTz(getPosition().getZ() + moveSpeed * -getN().getZ()); } private void moveUp() { affine.setTx(getPosition().getX() + moveSpeed * -getV().getX()); affine.setTy(getPosition().getY() + moveSpeed * -getV().getY()); affine.setTz(getPosition().getZ() + moveSpeed * -getV().getZ()); } private void moveDown() { affine.setTx(getPosition().getX() + moveSpeed * getV().getX()); affine.setTy(getPosition().getY() + moveSpeed * getV().getY()); affine.setTz(getPosition().getZ() + moveSpeed * getV().getZ()); } /*========================================================================== Properties */ private final ReadOnlyObjectWrapper<PerspectiveCamera> camera = new ReadOnlyObjectWrapper<>(this, "camera", new PerspectiveCamera(true)); public final PerspectiveCamera getCamera() { return camera.get(); } public ReadOnlyObjectProperty cameraProperty() { return camera.getReadOnlyProperty(); } /*========================================================================== Callbacks | R | Up| F | | P| U |mxx|mxy|mxz| |tx| V |myx|myy|myz| |ty| N |mzx|mzy|mzz| |tz| */ //Forward / look direction private final Callback<Transform, Point3D> F = (a) -> { return new Point3D(a.getMzx(), a.getMzy(), a.getMzz()); }; private final Callback<Transform, Point3D> N = (a) -> { return new Point3D(a.getMxz(), a.getMyz(), a.getMzz()); }; // up direction private final Callback<Transform, Point3D> UP = (a) -> { return new Point3D(a.getMyx(), a.getMyy(), a.getMyz()); }; private final Callback<Transform, Point3D> V = (a) -> { return new Point3D(a.getMxy(), a.getMyy(), a.getMzy()); }; // right direction private final Callback<Transform, Point3D> R = (a) -> { return new Point3D(a.getMxx(), a.getMxy(), a.getMxz()); }; private final Callback<Transform, Point3D> U = (a) -> { return new Point3D(a.getMxx(), a.getMyx(), a.getMzx()); }; //position private final Callback<Transform, Point3D> P = (a) -> { return new Point3D(a.getTx(), a.getTy(), a.getTz()); }; private Point3D getF() { return F.call(getLocalToSceneTransform()); } public Point3D getLookDirection() { return getF(); } private Point3D getN() { return N.call(getLocalToSceneTransform()); } public Point3D getLookNormal() { return getN(); } private Point3D getR() { return R.call(getLocalToSceneTransform()); } private Point3D getU() { return U.call(getLocalToSceneTransform()); } private Point3D getUp() { return UP.call(getLocalToSceneTransform()); } private Point3D getV() { return V.call(getLocalToSceneTransform()); } public final Point3D getPosition() { return P.call(getLocalToSceneTransform()); } }
Birdasaur/FXyz-DeepSpaceBranch
FXyz-Core/src/main/java/org/fxyz3d/scene/SimpleFPSCamera.java
4,896
/* init zoom? */
block_comment
nl
/** * SimpleFPSCamera.java * * Copyright (c) 2013-2016, F(X)yz * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of F(X)yz, any associated website, nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL F(X)yz 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. */ package org.fxyz3d.scene; import javafx.animation.AnimationTimer; import javafx.beans.property.ReadOnlyObjectProperty; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.geometry.Point3D; import javafx.scene.Group; import javafx.scene.Parent; import javafx.scene.PerspectiveCamera; import javafx.scene.Scene; import javafx.scene.SubScene; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.input.ScrollEvent; import javafx.scene.transform.Affine; import javafx.scene.transform.Rotate; import javafx.scene.transform.Transform; import javafx.scene.transform.Translate; import javafx.util.Callback; import org.fxyz3d.geometry.MathUtils; /** * A self initializing First Person Shooter camera * * @author Jason Pollastrini aka jdub1581 */ public class SimpleFPSCamera extends Parent { public SimpleFPSCamera() { initialize(); } private void update() { updateControls(); } private void updateControls() { if (fwd && !back) { moveForward(); } if (strafeL) { strafeLeft(); } if (strafeR) { strafeRight(); } if (back && !fwd) { moveBack(); } if (up && !down) { moveUp(); } if (down && !up) { moveDown(); } } /*========================================================================== Initialization */ private final Group root = new Group(); private final Affine affine = new Affine(); private final Translate t = new Translate(0, 0, 0); private final Rotate rotateX = new Rotate(0, Rotate.X_AXIS), rotateY = new Rotate(0, Rotate.Y_AXIS), rotateZ = new Rotate(0, Rotate.Z_AXIS); private boolean fwd, strafeL, strafeR, back, up, down, shift; private double mouseSpeed = 1.0, mouseModifier = 0.1; private double moveSpeed = 10.0; private double mousePosX; private double mousePosY; private double mouseOldX; private double mouseOldY; private double mouseDeltaX; private double mouseDeltaY; private void initialize() { getChildren().add(root); getTransforms().add(affine); initializeCamera(); startUpdateThread(); } public void loadControlsForSubScene(SubScene scene) { sceneProperty().addListener(l -> { if (getScene() != null) { getScene().addEventHandler(KeyEvent.ANY, ke -> { if (ke.getEventType() == KeyEvent.KEY_PRESSED) { switch (ke.getCode()) { case Q: up = true; break; case E: down = true; break; case W: fwd = true; break; case S: back = true; break; case A: strafeL = true; break; case D: strafeR = true; break; case SHIFT: shift = true; moveSpeed = 20; break; } } else if (ke.getEventType() == KeyEvent.KEY_RELEASED) { switch (ke.getCode()) { case Q: up = false; break; case E: down = false; break; case W: fwd = false; break; case S: back = false; break; case A: strafeL = false; break; case D: strafeR = false; break; case SHIFT: moveSpeed = 10; shift = false; break; } } ke.consume(); }); } }); scene.addEventHandler(MouseEvent.ANY, me -> { if (me.getEventType().equals(MouseEvent.MOUSE_PRESSED)) { mousePosX = me.getSceneX(); mousePosY = me.getSceneY(); mouseOldX = me.getSceneX(); mouseOldY = me.getSceneY(); } else if (me.getEventType().equals(MouseEvent.MOUSE_DRAGGED)) { mouseOldX = mousePosX; mouseOldY = mousePosY; mousePosX = me.getSceneX(); mousePosY = me.getSceneY(); mouseDeltaX = (mousePosX - mouseOldX); mouseDeltaY = (mousePosY - mouseOldY); mouseSpeed = 1.0; mouseModifier = 0.1; if (me.isPrimaryButtonDown()) { if (me.isControlDown()) { mouseSpeed = 0.1; } if (me.isShiftDown()) { mouseSpeed = 1.0; } t.setX(getPosition().getX()); t.setY(getPosition().getY()); t.setZ(getPosition().getZ()); affine.setToIdentity(); rotateY.setAngle( MathUtils.clamp(-360, ((rotateY.getAngle() + mouseDeltaX * (mouseSpeed * mouseModifier)) % 360 + 540) % 360 - 180, 360) ); // horizontal rotateX.setAngle( MathUtils.clamp(-45, ((rotateX.getAngle() - mouseDeltaY * (mouseSpeed * mouseModifier)) % 360 + 540) % 360 - 180, 35) ); // vertical affine.prepend(t.createConcatenation(rotateY.createConcatenation(rotateX))); } else if (me.isSecondaryButtonDown()) { /* init zoom? */ } else if (me.isMiddleButtonDown()) { /* init panning? */ } } }); scene.addEventHandler(ScrollEvent.ANY, se -> { if (se.getEventType().equals(ScrollEvent.SCROLL_STARTED)) { } else if (se.getEventType().equals(ScrollEvent.SCROLL)) { } else if (se.getEventType().equals(ScrollEvent.SCROLL_FINISHED)) { } }); } public void loadControlsForScene(Scene scene) { scene.addEventHandler(KeyEvent.ANY, ke -> { if (ke.getEventType() == KeyEvent.KEY_PRESSED) { switch (ke.getCode()) { case Q: up = true; break; case E: down = true; break; case W: fwd = true; break; case S: back = true; break; case A: strafeL = true; break; case D: strafeR = true; break; case SHIFT: shift = true; moveSpeed = 20; break; } } else if (ke.getEventType() == KeyEvent.KEY_RELEASED) { switch (ke.getCode()) { case Q: up = false; break; case E: down = false; break; case W: fwd = false; break; case S: back = false; break; case A: strafeL = false; break; case D: strafeR = false; break; case SHIFT: moveSpeed = 10; shift = false; break; } } ke.consume(); }); scene.addEventHandler(MouseEvent.ANY, me -> { if (me.getEventType().equals(MouseEvent.MOUSE_PRESSED)) { mousePosX = me.getSceneX(); mousePosY = me.getSceneY(); mouseOldX = me.getSceneX(); mouseOldY = me.getSceneY(); } else if (me.getEventType().equals(MouseEvent.MOUSE_DRAGGED)) { mouseOldX = mousePosX; mouseOldY = mousePosY; mousePosX = me.getSceneX(); mousePosY = me.getSceneY(); mouseDeltaX = (mousePosX - mouseOldX); mouseDeltaY = (mousePosY - mouseOldY); mouseSpeed = 1.0; mouseModifier = 0.1; if (me.isPrimaryButtonDown()) { if (me.isControlDown()) { mouseSpeed = 0.1; } if (me.isShiftDown()) { mouseSpeed = 1.0; } t.setX(getPosition().getX()); t.setY(getPosition().getY()); t.setZ(getPosition().getZ()); affine.setToIdentity(); rotateY.setAngle( MathUtils.clamp(-360, ((rotateY.getAngle() + mouseDeltaX * (mouseSpeed * mouseModifier)) % 360 + 540) % 360 - 180, 360) ); // horizontal rotateX.setAngle( MathUtils.clamp(-45, ((rotateX.getAngle() - mouseDeltaY * (mouseSpeed * mouseModifier)) % 360 + 540) % 360 - 180, 35) ); // vertical affine.prepend(t.createConcatenation(rotateY.createConcatenation(rotateX))); } else if (me.isSecondaryButtonDown()) { /* init zoom? <SUF>*/ } else if (me.isMiddleButtonDown()) { /* init panning? */ } } }); scene.addEventHandler(ScrollEvent.ANY, se -> { if (se.getEventType().equals(ScrollEvent.SCROLL_STARTED)) { } else if (se.getEventType().equals(ScrollEvent.SCROLL)) { } else if (se.getEventType().equals(ScrollEvent.SCROLL_FINISHED)) { } }); } private void initializeCamera() { getCamera().setNearClip(0.1); getCamera().setFarClip(100000); getCamera().setFieldOfView(42); getCamera().setVerticalFieldOfView(true); root.getChildren().add(getCamera()); } private void startUpdateThread() { new AnimationTimer() { @Override public void handle(long now) { update(); } }.start(); } /*========================================================================== Movement */ private void moveForward() { affine.setTx(getPosition().getX() + moveSpeed * getN().getX()); affine.setTy(getPosition().getY() + moveSpeed * getN().getY()); affine.setTz(getPosition().getZ() + moveSpeed * getN().getZ()); } private void strafeLeft() { affine.setTx(getPosition().getX() + moveSpeed * -getU().getX()); affine.setTy(getPosition().getY() + moveSpeed * -getU().getY()); affine.setTz(getPosition().getZ() + moveSpeed * -getU().getZ()); } private void strafeRight() { affine.setTx(getPosition().getX() + moveSpeed * getU().getX()); affine.setTy(getPosition().getY() + moveSpeed * getU().getY()); affine.setTz(getPosition().getZ() + moveSpeed * getU().getZ()); } private void moveBack() { affine.setTx(getPosition().getX() + moveSpeed * -getN().getX()); affine.setTy(getPosition().getY() + moveSpeed * -getN().getY()); affine.setTz(getPosition().getZ() + moveSpeed * -getN().getZ()); } private void moveUp() { affine.setTx(getPosition().getX() + moveSpeed * -getV().getX()); affine.setTy(getPosition().getY() + moveSpeed * -getV().getY()); affine.setTz(getPosition().getZ() + moveSpeed * -getV().getZ()); } private void moveDown() { affine.setTx(getPosition().getX() + moveSpeed * getV().getX()); affine.setTy(getPosition().getY() + moveSpeed * getV().getY()); affine.setTz(getPosition().getZ() + moveSpeed * getV().getZ()); } /*========================================================================== Properties */ private final ReadOnlyObjectWrapper<PerspectiveCamera> camera = new ReadOnlyObjectWrapper<>(this, "camera", new PerspectiveCamera(true)); public final PerspectiveCamera getCamera() { return camera.get(); } public ReadOnlyObjectProperty cameraProperty() { return camera.getReadOnlyProperty(); } /*========================================================================== Callbacks | R | Up| F | | P| U |mxx|mxy|mxz| |tx| V |myx|myy|myz| |ty| N |mzx|mzy|mzz| |tz| */ //Forward / look direction private final Callback<Transform, Point3D> F = (a) -> { return new Point3D(a.getMzx(), a.getMzy(), a.getMzz()); }; private final Callback<Transform, Point3D> N = (a) -> { return new Point3D(a.getMxz(), a.getMyz(), a.getMzz()); }; // up direction private final Callback<Transform, Point3D> UP = (a) -> { return new Point3D(a.getMyx(), a.getMyy(), a.getMyz()); }; private final Callback<Transform, Point3D> V = (a) -> { return new Point3D(a.getMxy(), a.getMyy(), a.getMzy()); }; // right direction private final Callback<Transform, Point3D> R = (a) -> { return new Point3D(a.getMxx(), a.getMxy(), a.getMxz()); }; private final Callback<Transform, Point3D> U = (a) -> { return new Point3D(a.getMxx(), a.getMyx(), a.getMzx()); }; //position private final Callback<Transform, Point3D> P = (a) -> { return new Point3D(a.getTx(), a.getTy(), a.getTz()); }; private Point3D getF() { return F.call(getLocalToSceneTransform()); } public Point3D getLookDirection() { return getF(); } private Point3D getN() { return N.call(getLocalToSceneTransform()); } public Point3D getLookNormal() { return getN(); } private Point3D getR() { return R.call(getLocalToSceneTransform()); } private Point3D getU() { return U.call(getLocalToSceneTransform()); } private Point3D getUp() { return UP.call(getLocalToSceneTransform()); } private Point3D getV() { return V.call(getLocalToSceneTransform()); } public final Point3D getPosition() { return P.call(getLocalToSceneTransform()); } }
30818_1
package storeEvent; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import org.apache.log4j.Logger; public class Event { private static int LAT_LON = 0x00000001; private static int GPS_ANT = 0x00000002; private static int IN_OUT = 0x00000004; private static int ODOMETER = 0x00000008; private static int DRIVERKEY = 0x00000010; private static int DATAS = 0x00000020; private static int SPEED = 0x00000040; private static int DIRECTION = 0x00000080; private static int DATA_1 = 0x00000100; private static int DATA_2 = 0x00000200; private static int DATA_3 = 0x00000400; private static int DATA_4 = 0x00000800; private static int DATA_5 = 0x00001000; private static int DATA_6 = 0x00002000; private static int DATA_7 = 0x00004000; private static int DYNAMIC = 0x00008000; private static int DATE_TIME = 0x00020000; private static Logger log = Logger.getLogger(StoreEvent.class); private static int LATLON = 1000000; public static int MES_POS = 1; public static int MES_POLL = 6; public static int MES_START = 122; public static int MES_STOP = 123; public static int MES_SPEED = 150; public static int MES_EXACC = 153; public static int MES_BREAK = 155; public static int MES_RECK = 236; public static int MES_MIL = 237; public static int MES_FAKE_STOP = 300; public static int MES_EVAL = 241; public static int MES_DEV_PLUGIN = 244; public static int MES_DEV_REMOVE = 245; public static int MES_BATT = 215; public int AntStat; public int Data1; public int Data2; public int Data3; public int Data4; public int Data5; public int Data6; public int Data7; public Timestamp dateTime; public String Description; public int Direction; public int DriverID; public int GPSStat; public int Information; public int InStat; public Double Longitude; public Double Latitude; public int MessageGroup; public int MessageID; public int ODOmeter; public int OutStat; public String Registration; public int Source; public String SourceAddress; public int Speed; public int VehicleID; public int ID; public int LeverancierID; public Boolean Verwerkt; private Boolean inUTC; public Event(ResultSet rs) { readFromResultSet(rs); } public Event(int id, Connection conn) { ID = 0; try { Statement st = conn.createStatement(); String s_sql; ResultSet rs; s_sql = "SELECT * FROM mprofevents WHERE mprofevents.\"ID\" = " + id; rs = st.executeQuery(s_sql); while (rs.next()) { readFromResultSet(rs); } } catch (SQLException e) { log.error("Error reading event from database: " + ID); ID = 0; } } private void readFromResultSet(ResultSet rs) { try { AntStat = rs.getInt(1); Data1 = rs.getInt(2); Data2 = rs.getInt(3); Data3 = rs.getInt(4); Data4 = rs.getInt(5); Data5 = rs.getInt(6); Data6 = rs.getInt(7); Data7 = rs.getInt(8); dateTime = rs.getTimestamp(9); Description = rs.getString(10); Direction = rs.getInt(11); DriverID = rs.getInt(12); GPSStat = rs.getInt(13); Information = rs.getInt(14); InStat = rs.getInt(15); Latitude = rs.getDouble(16); Longitude = rs.getDouble(17); MessageGroup = rs.getInt(18); MessageID = rs.getInt(19); ODOmeter = rs.getInt(20); OutStat = rs.getInt(21); Registration = rs.getString(22); Source = rs.getInt(23); SourceAddress = rs.getString(24); Speed = rs.getInt(25); VehicleID = rs.getInt(26); ID = rs.getInt(27); LeverancierID = rs.getInt(28); Verwerkt = rs.getBoolean(29); inUTC = true; } catch (SQLException e) { ID = 0; } } /* public void save(Boolean asNew, Connection conn) { if (ID > 0) { try { Statement st = conn.createStatement(); StringBuilder sb_insert = new StringBuilder(); sb_insert.append("INSERT INTO mprofevents VALUES ("); sb_insert.append(QueryBuilder.insert(AntStat)); sb_insert.append(QueryBuilder.insert(Data1)); sb_insert.append(QueryBuilder.insert(Data2)); sb_insert.append(QueryBuilder.insert(Data3)); sb_insert.append(QueryBuilder.insert(Data4)); sb_insert.append(QueryBuilder.insert(Data5)); sb_insert.append(QueryBuilder.insert(Data6)); sb_insert.append(QueryBuilder.insert(Data7)); // if (!inUTC) // sb_insert.append("'" + UTCtoLocalTime(DateTime, Information, dtMax).ToString("s") + "', "); // else sb_insert.append(QueryBuilder.insert(dateTime)); // "s" sb_insert.append(QueryBuilder.insert(Description)); sb_insert.append(QueryBuilder.insert(Direction)); sb_insert.append(QueryBuilder.insert(DriverID)); sb_insert.append(QueryBuilder.insert(GPSStat)); sb_insert.append(QueryBuilder.insert(Information)); sb_insert.append(QueryBuilder.insert(InStat)); sb_insert.append(QueryBuilder.insert(Latitude)); sb_insert.append(QueryBuilder.insert(Longitude)); sb_insert.append(QueryBuilder.insert(MessageGroup)); sb_insert.append(QueryBuilder.insert(MessageID)); sb_insert.append(QueryBuilder.insert(ODOmeter)); sb_insert.append(QueryBuilder.insert(OutStat)); if (Registration != null) sb_insert.append(QueryBuilder.insert(Registration)); else sb_insert.append("'', "); sb_insert.append(QueryBuilder.insert(Source)); sb_insert.append(QueryBuilder.insert(SourceAddress)); sb_insert.append(QueryBuilder.insert(Speed)); if (asNew == true) sb_insert.append(QueryBuilder.insert_last(VehicleID)); else { sb_insert.append(VehicleID + ", "); sb_insert.append(ID + ")"); } st.execute(sb_insert.toString()); st.close(); } catch (SQLException e) { ID = 0; } } } */ public void setVerwerkt(Connection conn) { if (ID > 0) { try { Statement st = conn.createStatement(); st.execute("UPDATE mprofevents SET \"Verwerkt\" = 't' WHERE mprofevents.\"ID\" = " + ID); st.close(); } catch (SQLException e) { log.error("Could not set event Processed: " + ID); ID = 0; } } } public void clean_odo() { if ((Information & ODOMETER) > 0) { if (ODOmeter == 4294967) // Speciaal geval als unit net begint te werken. Eigenlijk moet ODO op 0 beginnen ODOmeter = 0; } else ODOmeter = -1; } static public void delete(int id, Connection conn) { try { Statement st = conn.createStatement(); st.execute("DELETE FROM mprofevents WHERE mprofevents.\"ID\" = " + id); st.close(); } catch(SQLException e) { log.error("Error deleting event: " + id); } } public Integer getDistance() { if (MessageID == MES_STOP || MessageID == MES_FAKE_STOP) return Data4; /// afstand in meters als MessID == Trip End if (MessageID == MES_POS) return Data7; /// tot nog toe afgelegde afstand in meters als MessID == Position return 0; } public Integer getSpeeding() { if (MessageID == MES_SPEED) return Data3; /// aantal seconden als MessID == Speeding return 0; } public Integer getDuration() { if (MessageID == MES_STOP || MessageID == MES_FAKE_STOP) return Data3; /// aantal seceonden van de rit als MessID == Trip End if (MessageID == MES_POS) return Data6; /// aantal seconden dat de rit nu duurt als MessID == Position return Data3; } public Integer getRpm() { if (MessageID == MES_POS) return Data3; /// Toeren per minuut als MessID == Position return 0; } public Integer getBreakingLevel() { return Data2; /// Max waarde, voor elk type bericht. Alleen gevuld voor Excessive events } }
BitScience/StoreEvent
src/storeEvent/Event.java
2,868
// Speciaal geval als unit net begint te werken. Eigenlijk moet ODO op 0 beginnen
line_comment
nl
package storeEvent; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import org.apache.log4j.Logger; public class Event { private static int LAT_LON = 0x00000001; private static int GPS_ANT = 0x00000002; private static int IN_OUT = 0x00000004; private static int ODOMETER = 0x00000008; private static int DRIVERKEY = 0x00000010; private static int DATAS = 0x00000020; private static int SPEED = 0x00000040; private static int DIRECTION = 0x00000080; private static int DATA_1 = 0x00000100; private static int DATA_2 = 0x00000200; private static int DATA_3 = 0x00000400; private static int DATA_4 = 0x00000800; private static int DATA_5 = 0x00001000; private static int DATA_6 = 0x00002000; private static int DATA_7 = 0x00004000; private static int DYNAMIC = 0x00008000; private static int DATE_TIME = 0x00020000; private static Logger log = Logger.getLogger(StoreEvent.class); private static int LATLON = 1000000; public static int MES_POS = 1; public static int MES_POLL = 6; public static int MES_START = 122; public static int MES_STOP = 123; public static int MES_SPEED = 150; public static int MES_EXACC = 153; public static int MES_BREAK = 155; public static int MES_RECK = 236; public static int MES_MIL = 237; public static int MES_FAKE_STOP = 300; public static int MES_EVAL = 241; public static int MES_DEV_PLUGIN = 244; public static int MES_DEV_REMOVE = 245; public static int MES_BATT = 215; public int AntStat; public int Data1; public int Data2; public int Data3; public int Data4; public int Data5; public int Data6; public int Data7; public Timestamp dateTime; public String Description; public int Direction; public int DriverID; public int GPSStat; public int Information; public int InStat; public Double Longitude; public Double Latitude; public int MessageGroup; public int MessageID; public int ODOmeter; public int OutStat; public String Registration; public int Source; public String SourceAddress; public int Speed; public int VehicleID; public int ID; public int LeverancierID; public Boolean Verwerkt; private Boolean inUTC; public Event(ResultSet rs) { readFromResultSet(rs); } public Event(int id, Connection conn) { ID = 0; try { Statement st = conn.createStatement(); String s_sql; ResultSet rs; s_sql = "SELECT * FROM mprofevents WHERE mprofevents.\"ID\" = " + id; rs = st.executeQuery(s_sql); while (rs.next()) { readFromResultSet(rs); } } catch (SQLException e) { log.error("Error reading event from database: " + ID); ID = 0; } } private void readFromResultSet(ResultSet rs) { try { AntStat = rs.getInt(1); Data1 = rs.getInt(2); Data2 = rs.getInt(3); Data3 = rs.getInt(4); Data4 = rs.getInt(5); Data5 = rs.getInt(6); Data6 = rs.getInt(7); Data7 = rs.getInt(8); dateTime = rs.getTimestamp(9); Description = rs.getString(10); Direction = rs.getInt(11); DriverID = rs.getInt(12); GPSStat = rs.getInt(13); Information = rs.getInt(14); InStat = rs.getInt(15); Latitude = rs.getDouble(16); Longitude = rs.getDouble(17); MessageGroup = rs.getInt(18); MessageID = rs.getInt(19); ODOmeter = rs.getInt(20); OutStat = rs.getInt(21); Registration = rs.getString(22); Source = rs.getInt(23); SourceAddress = rs.getString(24); Speed = rs.getInt(25); VehicleID = rs.getInt(26); ID = rs.getInt(27); LeverancierID = rs.getInt(28); Verwerkt = rs.getBoolean(29); inUTC = true; } catch (SQLException e) { ID = 0; } } /* public void save(Boolean asNew, Connection conn) { if (ID > 0) { try { Statement st = conn.createStatement(); StringBuilder sb_insert = new StringBuilder(); sb_insert.append("INSERT INTO mprofevents VALUES ("); sb_insert.append(QueryBuilder.insert(AntStat)); sb_insert.append(QueryBuilder.insert(Data1)); sb_insert.append(QueryBuilder.insert(Data2)); sb_insert.append(QueryBuilder.insert(Data3)); sb_insert.append(QueryBuilder.insert(Data4)); sb_insert.append(QueryBuilder.insert(Data5)); sb_insert.append(QueryBuilder.insert(Data6)); sb_insert.append(QueryBuilder.insert(Data7)); // if (!inUTC) // sb_insert.append("'" + UTCtoLocalTime(DateTime, Information, dtMax).ToString("s") + "', "); // else sb_insert.append(QueryBuilder.insert(dateTime)); // "s" sb_insert.append(QueryBuilder.insert(Description)); sb_insert.append(QueryBuilder.insert(Direction)); sb_insert.append(QueryBuilder.insert(DriverID)); sb_insert.append(QueryBuilder.insert(GPSStat)); sb_insert.append(QueryBuilder.insert(Information)); sb_insert.append(QueryBuilder.insert(InStat)); sb_insert.append(QueryBuilder.insert(Latitude)); sb_insert.append(QueryBuilder.insert(Longitude)); sb_insert.append(QueryBuilder.insert(MessageGroup)); sb_insert.append(QueryBuilder.insert(MessageID)); sb_insert.append(QueryBuilder.insert(ODOmeter)); sb_insert.append(QueryBuilder.insert(OutStat)); if (Registration != null) sb_insert.append(QueryBuilder.insert(Registration)); else sb_insert.append("'', "); sb_insert.append(QueryBuilder.insert(Source)); sb_insert.append(QueryBuilder.insert(SourceAddress)); sb_insert.append(QueryBuilder.insert(Speed)); if (asNew == true) sb_insert.append(QueryBuilder.insert_last(VehicleID)); else { sb_insert.append(VehicleID + ", "); sb_insert.append(ID + ")"); } st.execute(sb_insert.toString()); st.close(); } catch (SQLException e) { ID = 0; } } } */ public void setVerwerkt(Connection conn) { if (ID > 0) { try { Statement st = conn.createStatement(); st.execute("UPDATE mprofevents SET \"Verwerkt\" = 't' WHERE mprofevents.\"ID\" = " + ID); st.close(); } catch (SQLException e) { log.error("Could not set event Processed: " + ID); ID = 0; } } } public void clean_odo() { if ((Information & ODOMETER) > 0) { if (ODOmeter == 4294967) // Speciaal geval<SUF> ODOmeter = 0; } else ODOmeter = -1; } static public void delete(int id, Connection conn) { try { Statement st = conn.createStatement(); st.execute("DELETE FROM mprofevents WHERE mprofevents.\"ID\" = " + id); st.close(); } catch(SQLException e) { log.error("Error deleting event: " + id); } } public Integer getDistance() { if (MessageID == MES_STOP || MessageID == MES_FAKE_STOP) return Data4; /// afstand in meters als MessID == Trip End if (MessageID == MES_POS) return Data7; /// tot nog toe afgelegde afstand in meters als MessID == Position return 0; } public Integer getSpeeding() { if (MessageID == MES_SPEED) return Data3; /// aantal seconden als MessID == Speeding return 0; } public Integer getDuration() { if (MessageID == MES_STOP || MessageID == MES_FAKE_STOP) return Data3; /// aantal seceonden van de rit als MessID == Trip End if (MessageID == MES_POS) return Data6; /// aantal seconden dat de rit nu duurt als MessID == Position return Data3; } public Integer getRpm() { if (MessageID == MES_POS) return Data3; /// Toeren per minuut als MessID == Position return 0; } public Integer getBreakingLevel() { return Data2; /// Max waarde, voor elk type bericht. Alleen gevuld voor Excessive events } }
78119_23
package com.blankj.subutil.util; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2016/09/19 * desc : 相机相关工具类 * </pre> */ public final class CameraUtils { // private CameraUtils() { // throw new UnsupportedOperationException("u can't instantiate me..."); // } // // /** // * 获取打开照程序界面的Intent // */ // public static Intent getOpenCameraIntent() { // return new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // } // // /** // * 获取跳转至相册选择界面的Intent // */ // public static Intent getImagePickerIntent() { // Intent intent = new Intent(Intent.ACTION_PICK, null); // return intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); // } // // /** // * 获取[跳转至相册选择界面,并跳转至裁剪界面,默认可缩放裁剪区域]的Intent // */ // public static Intent getImagePickerIntent(int outputX, int outputY, Uri fromFileURI, // Uri saveFileURI) { // return getImagePickerIntent(1, 1, outputX, outputY, true, fromFileURI, saveFileURI); // } // // /** // * 获取[跳转至相册选择界面,并跳转至裁剪界面,默认可缩放裁剪区域]的Intent // */ // public static Intent getImagePickerIntent(int aspectX, int aspectY, int outputX, int outputY, Uri fromFileURI, // Uri saveFileURI) { // return getImagePickerIntent(aspectX, aspectY, outputX, outputY, true, fromFileURI, saveFileURI); // } // // /** // * 获取[跳转至相册选择界面,并跳转至裁剪界面,可以指定是否缩放裁剪区域]的Intent // * // * @param aspectX 裁剪框尺寸比例X // * @param aspectY 裁剪框尺寸比例Y // * @param outputX 输出尺寸宽度 // * @param outputY 输出尺寸高度 // * @param canScale 是否可缩放 // * @param fromFileURI 文件来源路径URI // * @param saveFileURI 输出文件路径URI // */ // public static Intent getImagePickerIntent(int aspectX, int aspectY, int outputX, int outputY, boolean canScale, // Uri fromFileURI, Uri saveFileURI) { // Intent intent = new Intent(Intent.ACTION_PICK); // intent.setDataAndType(fromFileURI, "image/*"); // intent.putExtra("crop", "true"); // intent.putExtra("aspectX", aspectX <= 0 ? 1 : aspectX); // intent.putExtra("aspectY", aspectY <= 0 ? 1 : aspectY); // intent.putExtra("outputX", outputX); // intent.putExtra("outputY", outputY); // intent.putExtra("scale", canScale); // // 图片剪裁不足黑边解决 // intent.putExtra("scaleUpIfNeeded", true); // intent.putExtra("return-data", false); // intent.putExtra(MediaStore.EXTRA_OUTPUT, saveFileURI); // intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); // // 去除人脸识别 // return intent.putExtra("noFaceDetection", true); // } // // /** // * 获取[跳转至相册选择界面,并跳转至裁剪界面,默认可缩放裁剪区域]的Intent // */ // public static Intent getCameraIntent(final Uri saveFileURI) { // Intent mIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // return mIntent.putExtra(MediaStore.EXTRA_OUTPUT, saveFileURI); // } // // /** // * 获取[跳转至裁剪界面,默认可缩放]的Intent // */ // public static Intent getCropImageIntent(int outputX, int outputY, Uri fromFileURI, // Uri saveFileURI) { // return getCropImageIntent(1, 1, outputX, outputY, true, fromFileURI, saveFileURI); // } // // /** // * 获取[跳转至裁剪界面,默认可缩放]的Intent // */ // public static Intent getCropImageIntent(int aspectX, int aspectY, int outputX, int outputY, Uri fromFileURI, // Uri saveFileURI) { // return getCropImageIntent(aspectX, aspectY, outputX, outputY, true, fromFileURI, saveFileURI); // } // // // /** // * 获取[跳转至裁剪界面]的Intent // */ // public static Intent getCropImageIntent(int aspectX, int aspectY, int outputX, int outputY, boolean canScale, // Uri fromFileURI, Uri saveFileURI) { // Intent intent = new Intent("com.android.camera.action.CROP"); // intent.setDataAndType(fromFileURI, "image/*"); // intent.putExtra("crop", "true"); // // X方向上的比例 // intent.putExtra("aspectX", aspectX <= 0 ? 1 : aspectX); // // Y方向上的比例 // intent.putExtra("aspectY", aspectY <= 0 ? 1 : aspectY); // intent.putExtra("outputX", outputX); // intent.putExtra("outputY", outputY); // intent.putExtra("scale", canScale); // // 图片剪裁不足黑边解决 // intent.putExtra("scaleUpIfNeeded", true); // intent.putExtra("return-data", false); // // 需要将读取的文件路径和裁剪写入的路径区分,否则会造成文件0byte // intent.putExtra(MediaStore.EXTRA_OUTPUT, saveFileURI); // // true-->返回数据类型可以设置为Bitmap,但是不能传输太大,截大图用URI,小图用Bitmap或者全部使用URI // intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); // // 取消人脸识别功能 // intent.putExtra("noFaceDetection", true); // return intent; // } // // /** // * 获得选中相册的图片 // * // * @param context 上下文 // * @param data onActivityResult返回的Intent // * @return bitmap // */ // public static Bitmap getChoosedImage(final Activity context, final Intent data) { // if (data == null) return null; // Bitmap bm = null; // ContentResolver cr = context.getContentResolver(); // Uri originalUri = data.getData(); // try { // bm = MediaStore.Images.Media.getBitmap(cr, originalUri); // } catch (IOException e) { // e.printStackTrace(); // } // return bm; // } // // /** // * 获得选中相册的图片路径 // * // * @param context 上下文 // * @param data onActivityResult返回的Intent // * @return // */ // public static String getChoosedImagePath(final Activity context, final Intent data) { // if (data == null) return null; // String path = ""; // ContentResolver resolver = context.getContentResolver(); // Uri originalUri = data.getData(); // if (null == originalUri) return null; // String[] projection = {MediaStore.Images.Media.DATA}; // Cursor cursor = resolver.query(originalUri, projection, null, null, null); // if (null != cursor) { // try { // int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); // cursor.moveToFirst(); // path = cursor.getString(column_index); // } catch (IllegalArgumentException e) { // e.printStackTrace(); // } finally { // try { // if (!cursor.isClosed()) { // cursor.close(); // } // } catch (Exception e) { // e.printStackTrace(); // } // } // } // return StringUtils.isEmpty(path) ? originalUri.getPath() : null; // } // // /** // * 获取拍照之后的照片文件(JPG格式) // * // * @param data onActivityResult回调返回的数据 // * @param filePath The path of file. // * @return 文件 // */ // public static File getTakePictureFile(final Intent data, final String filePath) { // if (data == null) return null; // Bundle extras = data.getExtras(); // if (extras == null) return null; // Bitmap photo = extras.getParcelable("data"); // File file = new File(filePath); // if (ImageUtils.save(photo, file, Bitmap.CompressFormat.JPEG)) return file; // return null; // } }
Blankj/AndroidUtilCode
lib/subutil/src/main/java/com/blankj/subutil/util/CameraUtils.java
2,533
// Intent intent = new Intent(Intent.ACTION_PICK);
line_comment
nl
package com.blankj.subutil.util; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2016/09/19 * desc : 相机相关工具类 * </pre> */ public final class CameraUtils { // private CameraUtils() { // throw new UnsupportedOperationException("u can't instantiate me..."); // } // // /** // * 获取打开照程序界面的Intent // */ // public static Intent getOpenCameraIntent() { // return new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // } // // /** // * 获取跳转至相册选择界面的Intent // */ // public static Intent getImagePickerIntent() { // Intent intent = new Intent(Intent.ACTION_PICK, null); // return intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); // } // // /** // * 获取[跳转至相册选择界面,并跳转至裁剪界面,默认可缩放裁剪区域]的Intent // */ // public static Intent getImagePickerIntent(int outputX, int outputY, Uri fromFileURI, // Uri saveFileURI) { // return getImagePickerIntent(1, 1, outputX, outputY, true, fromFileURI, saveFileURI); // } // // /** // * 获取[跳转至相册选择界面,并跳转至裁剪界面,默认可缩放裁剪区域]的Intent // */ // public static Intent getImagePickerIntent(int aspectX, int aspectY, int outputX, int outputY, Uri fromFileURI, // Uri saveFileURI) { // return getImagePickerIntent(aspectX, aspectY, outputX, outputY, true, fromFileURI, saveFileURI); // } // // /** // * 获取[跳转至相册选择界面,并跳转至裁剪界面,可以指定是否缩放裁剪区域]的Intent // * // * @param aspectX 裁剪框尺寸比例X // * @param aspectY 裁剪框尺寸比例Y // * @param outputX 输出尺寸宽度 // * @param outputY 输出尺寸高度 // * @param canScale 是否可缩放 // * @param fromFileURI 文件来源路径URI // * @param saveFileURI 输出文件路径URI // */ // public static Intent getImagePickerIntent(int aspectX, int aspectY, int outputX, int outputY, boolean canScale, // Uri fromFileURI, Uri saveFileURI) { // Intent intent<SUF> // intent.setDataAndType(fromFileURI, "image/*"); // intent.putExtra("crop", "true"); // intent.putExtra("aspectX", aspectX <= 0 ? 1 : aspectX); // intent.putExtra("aspectY", aspectY <= 0 ? 1 : aspectY); // intent.putExtra("outputX", outputX); // intent.putExtra("outputY", outputY); // intent.putExtra("scale", canScale); // // 图片剪裁不足黑边解决 // intent.putExtra("scaleUpIfNeeded", true); // intent.putExtra("return-data", false); // intent.putExtra(MediaStore.EXTRA_OUTPUT, saveFileURI); // intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); // // 去除人脸识别 // return intent.putExtra("noFaceDetection", true); // } // // /** // * 获取[跳转至相册选择界面,并跳转至裁剪界面,默认可缩放裁剪区域]的Intent // */ // public static Intent getCameraIntent(final Uri saveFileURI) { // Intent mIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // return mIntent.putExtra(MediaStore.EXTRA_OUTPUT, saveFileURI); // } // // /** // * 获取[跳转至裁剪界面,默认可缩放]的Intent // */ // public static Intent getCropImageIntent(int outputX, int outputY, Uri fromFileURI, // Uri saveFileURI) { // return getCropImageIntent(1, 1, outputX, outputY, true, fromFileURI, saveFileURI); // } // // /** // * 获取[跳转至裁剪界面,默认可缩放]的Intent // */ // public static Intent getCropImageIntent(int aspectX, int aspectY, int outputX, int outputY, Uri fromFileURI, // Uri saveFileURI) { // return getCropImageIntent(aspectX, aspectY, outputX, outputY, true, fromFileURI, saveFileURI); // } // // // /** // * 获取[跳转至裁剪界面]的Intent // */ // public static Intent getCropImageIntent(int aspectX, int aspectY, int outputX, int outputY, boolean canScale, // Uri fromFileURI, Uri saveFileURI) { // Intent intent = new Intent("com.android.camera.action.CROP"); // intent.setDataAndType(fromFileURI, "image/*"); // intent.putExtra("crop", "true"); // // X方向上的比例 // intent.putExtra("aspectX", aspectX <= 0 ? 1 : aspectX); // // Y方向上的比例 // intent.putExtra("aspectY", aspectY <= 0 ? 1 : aspectY); // intent.putExtra("outputX", outputX); // intent.putExtra("outputY", outputY); // intent.putExtra("scale", canScale); // // 图片剪裁不足黑边解决 // intent.putExtra("scaleUpIfNeeded", true); // intent.putExtra("return-data", false); // // 需要将读取的文件路径和裁剪写入的路径区分,否则会造成文件0byte // intent.putExtra(MediaStore.EXTRA_OUTPUT, saveFileURI); // // true-->返回数据类型可以设置为Bitmap,但是不能传输太大,截大图用URI,小图用Bitmap或者全部使用URI // intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); // // 取消人脸识别功能 // intent.putExtra("noFaceDetection", true); // return intent; // } // // /** // * 获得选中相册的图片 // * // * @param context 上下文 // * @param data onActivityResult返回的Intent // * @return bitmap // */ // public static Bitmap getChoosedImage(final Activity context, final Intent data) { // if (data == null) return null; // Bitmap bm = null; // ContentResolver cr = context.getContentResolver(); // Uri originalUri = data.getData(); // try { // bm = MediaStore.Images.Media.getBitmap(cr, originalUri); // } catch (IOException e) { // e.printStackTrace(); // } // return bm; // } // // /** // * 获得选中相册的图片路径 // * // * @param context 上下文 // * @param data onActivityResult返回的Intent // * @return // */ // public static String getChoosedImagePath(final Activity context, final Intent data) { // if (data == null) return null; // String path = ""; // ContentResolver resolver = context.getContentResolver(); // Uri originalUri = data.getData(); // if (null == originalUri) return null; // String[] projection = {MediaStore.Images.Media.DATA}; // Cursor cursor = resolver.query(originalUri, projection, null, null, null); // if (null != cursor) { // try { // int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); // cursor.moveToFirst(); // path = cursor.getString(column_index); // } catch (IllegalArgumentException e) { // e.printStackTrace(); // } finally { // try { // if (!cursor.isClosed()) { // cursor.close(); // } // } catch (Exception e) { // e.printStackTrace(); // } // } // } // return StringUtils.isEmpty(path) ? originalUri.getPath() : null; // } // // /** // * 获取拍照之后的照片文件(JPG格式) // * // * @param data onActivityResult回调返回的数据 // * @param filePath The path of file. // * @return 文件 // */ // public static File getTakePictureFile(final Intent data, final String filePath) { // if (data == null) return null; // Bundle extras = data.getExtras(); // if (extras == null) return null; // Bitmap photo = extras.getParcelable("data"); // File file = new File(filePath); // if (ImageUtils.save(photo, file, Bitmap.CompressFormat.JPEG)) return file; // return null; // } }
10823_2
package testRetroFit; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Typeface; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; import retrofit.mime.TypedByteArray; import static android.content.Context.MODE_PRIVATE; public class LogInFragment extends Fragment { public EditText txtName; private EditText txtPwd; private EditText txtLogIn; private Button btnSignIn; private Button btnFbSignIn; private Button btnGplusSignIn; private boolean alreadyLoggedIn; /* @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_sign_in_screen, container, false); Typeface opensans = Typeface.createFromAsset(getActivity().getAssets(), "fonts/OpenSans-Regular.ttf"); Typeface roboto = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Roboto-Bold.ttf"); txtName = (EditText) rootView.findViewById(R.id.signInUsername); txtPwd = (EditText) rootView.findViewById(R.id.signInPassword); txtLogIn = (EditText) rootView.findViewById(R.id.register); btnSignIn = (Button) rootView.findViewById(R.id.signInBtn); btnFbSignIn = (Button)rootView.findViewById(R.id.btnSingInFacebook); btnGplusSignIn = (Button)rootView.findViewById(R.id.btnSingInGoogle); btnSignIn.setTypeface(opensans); btnGplusSignIn.setTypeface(opensans); btnFbSignIn.setTypeface(opensans); txtName.setTypeface(opensans); txtPwd.setTypeface(opensans); txtLogIn.setTypeface(roboto); initListeners(); initUsernameAndPassWordFields(); return rootView; } */ public void initUsernameAndPassWordFields() { SharedPreferences userDetails = getActivity().getSharedPreferences("Logindetails", Context.MODE_PRIVATE); String email = userDetails.getString("email", ""); String password = userDetails.getString("password", ""); //Haalt in de SP het email & PW op zodat deze gegevens al ingevuld kunnen worden op beide textFields in het inlogscherm. if (!email.isEmpty()) { txtName.setText(email); } if (!password.isEmpty()) { txtPwd.setText(password); } } /* public void initListeners() { btnSignIn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /* Bij het klikken op de knop wordt er gekeken of de email en pw van de gebruiker nog in de Sharedprefence zit. Staat hier niets in, dan is de gebruiker niet aangelogd. ==> We controleren dan elke veld om te zien of deze een waarde bevat. Zoja probeer dan in te loggen. Staat in de Sharedpref wel een waarde dan is de gebruiker al inglogd. Probeert hij opnieuw in te loggen met de gegevens die al in de sharedpref staan dan krijgt hij een melding dat hij al aangmeld is Probeert hij in te loggen met andere gegevens dan in de sharedpref staan dan probeert het systeem gewoon in te loggen. Zijn de inlog gegevens verkeerd dan wordt er een melding weergegeven. SharedPreferences userDetails = getActivity().getSharedPreferences("Logindetails", Context.MODE_PRIVATE); String email = userDetails.getString("email", ""); // email uit de SP ophalen String password = userDetails.getString("password", ""); //pw uit de SP ophalen if (txtName.getText().length() == 0) { txtName.setError(getString(R.string.EmptyTextFieldCannotBeEmpty)); } if (txtPwd.getText().length() == 0) { txtPwd.setError(getString(R.string.EmptyTextFieldCannotBeEmpty)); } if (email.equalsIgnoreCase(txtName.getText().toString()) && password.equals(txtPwd.getText().toString())) { // Email uit de SP zijn hetzelfde als ingegeven email? ==> Al ingelogd alreadyLoggedIn = true; } else { alreadyLoggedIn = false; } if (email.isEmpty() || password.isEmpty()) { // is de sharedpref leeg? Dan kan er niemand ingelogd zijn. alreadyLoggedIn = false; } if (alreadyLoggedIn) { //melding geven als de gebruiker al ingelogd is en nog eens probeert in te loggen met dezelfde gegevens AppMsg.makeText(getActivity(), getResources().getString(R.string.already_logged_in_as) + " " + email, AppMsg.STYLE_ALERT).show(); } else { if (!(txtName.getText().length() == 0 || txtPwd.getText().length() == 0)) { // Als beide velden een waarde bevatten mag er een inlog poging gebeuren. signIn(); } } } }); } */ /* private void signIn() { // Haal OAuth token op getJppService().getToken("password", txtName.getText().toString() + 1, txtPwd.getText().toString(), this); } */ /* @Override public void success(Token token, Response response) { //Als de login succes vol is, zet dan de token, email en password in een sharedPrefence zodat deze gegevens later kunnen worden opgehaald. SharedPreferences.Editor editor = getActivity().getSharedPreferences("Logindetails", MODE_PRIVATE).edit(); editor.putString("token", token.getAccess_token()); editor.putString("email", txtName.getText().toString()); editor.putString("password", txtPwd.getText().toString()); editor.apply(); AppMsg.makeText(getActivity(), getResources().getString(R.string.successfullLogin) + " " + txtName.getText().toString(), AppMsg.STYLE_INFO).show(); //Als het inloggen succesvol is gebeurd wissel dan naar het Home scherm (lijst met vragen) Fragment frag = new AmsHomeFragment(); FragmentManager fragMan = getFragmentManager(); FragmentTransaction fragTran = fragMan.beginTransaction(); fragTran.replace(R.id.frame_container, frag); fragTran.addToBackStack(null); fragTran.commit(); } */ /* @Override public void failure(RetrofitError error) { //Gaat het inloggen verkeerd, vang dan de json error code die retrofit teruggeeft. Match de json code aan gekende errors en geef gepaste feedback. String json = new String(((TypedByteArray) error.getResponse().getBody()).getBytes()); if (json.equals(getResources().getString(R.string.retrofit_username_or_password_wrong_json))) { AppMsg.makeText(getActivity(), getResources().getString(R.string.username_or_password_wrong), AppMsg.STYLE_ALERT).show(); } else { AppMsg.makeText(getActivity(), getResources().getString(R.string.something_went_wrong) + error, AppMsg.STYLE_ALERT).show(); } } */ }
Blaperile/kandoe-android
app/src/main/java/testRetroFit/LogInFragment.java
2,159
/* public void initListeners() { btnSignIn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /* Bij het klikken op de knop wordt er gekeken of de email en pw van de gebruiker nog in de Sharedprefence zit. Staat hier niets in, dan is de gebruiker niet aangelogd. ==> We controleren dan elke veld om te zien of deze een waarde bevat. Zoja probeer dan in te loggen. Staat in de Sharedpref wel een waarde dan is de gebruiker al inglogd. Probeert hij opnieuw in te loggen met de gegevens die al in de sharedpref staan dan krijgt hij een melding dat hij al aangmeld is Probeert hij in te loggen met andere gegevens dan in de sharedpref staan dan probeert het systeem gewoon in te loggen. Zijn de inlog gegevens verkeerd dan wordt er een melding weergegeven. SharedPreferences userDetails = getActivity().getSharedPreferences("Logindetails", Context.MODE_PRIVATE); String email = userDetails.getString("email", ""); // email uit de SP ophalen String password = userDetails.getString("password", ""); //pw uit de SP ophalen if (txtName.getText().length() == 0) { txtName.setError(getString(R.string.EmptyTextFieldCannotBeEmpty)); } if (txtPwd.getText().length() == 0) { txtPwd.setError(getString(R.string.EmptyTextFieldCannotBeEmpty)); } if (email.equalsIgnoreCase(txtName.getText().toString()) && password.equals(txtPwd.getText().toString())) { // Email uit de SP zijn hetzelfde als ingegeven email? ==> Al ingelogd alreadyLoggedIn = true; } else { alreadyLoggedIn = false; } if (email.isEmpty() || password.isEmpty()) { // is de sharedpref leeg? Dan kan er niemand ingelogd zijn. alreadyLoggedIn = false; } if (alreadyLoggedIn) { //melding geven als de gebruiker al ingelogd is en nog eens probeert in te loggen met dezelfde gegevens AppMsg.makeText(getActivity(), getResources().getString(R.string.already_logged_in_as) + " " + email, AppMsg.STYLE_ALERT).show(); } else { if (!(txtName.getText().length() == 0 || txtPwd.getText().length() == 0)) { // Als beide velden een waarde bevatten mag er een inlog poging gebeuren. signIn(); } } } }); } */
block_comment
nl
package testRetroFit; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Typeface; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; import retrofit.mime.TypedByteArray; import static android.content.Context.MODE_PRIVATE; public class LogInFragment extends Fragment { public EditText txtName; private EditText txtPwd; private EditText txtLogIn; private Button btnSignIn; private Button btnFbSignIn; private Button btnGplusSignIn; private boolean alreadyLoggedIn; /* @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_sign_in_screen, container, false); Typeface opensans = Typeface.createFromAsset(getActivity().getAssets(), "fonts/OpenSans-Regular.ttf"); Typeface roboto = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Roboto-Bold.ttf"); txtName = (EditText) rootView.findViewById(R.id.signInUsername); txtPwd = (EditText) rootView.findViewById(R.id.signInPassword); txtLogIn = (EditText) rootView.findViewById(R.id.register); btnSignIn = (Button) rootView.findViewById(R.id.signInBtn); btnFbSignIn = (Button)rootView.findViewById(R.id.btnSingInFacebook); btnGplusSignIn = (Button)rootView.findViewById(R.id.btnSingInGoogle); btnSignIn.setTypeface(opensans); btnGplusSignIn.setTypeface(opensans); btnFbSignIn.setTypeface(opensans); txtName.setTypeface(opensans); txtPwd.setTypeface(opensans); txtLogIn.setTypeface(roboto); initListeners(); initUsernameAndPassWordFields(); return rootView; } */ public void initUsernameAndPassWordFields() { SharedPreferences userDetails = getActivity().getSharedPreferences("Logindetails", Context.MODE_PRIVATE); String email = userDetails.getString("email", ""); String password = userDetails.getString("password", ""); //Haalt in de SP het email & PW op zodat deze gegevens al ingevuld kunnen worden op beide textFields in het inlogscherm. if (!email.isEmpty()) { txtName.setText(email); } if (!password.isEmpty()) { txtPwd.setText(password); } } /* public void initListeners()<SUF>*/ /* private void signIn() { // Haal OAuth token op getJppService().getToken("password", txtName.getText().toString() + 1, txtPwd.getText().toString(), this); } */ /* @Override public void success(Token token, Response response) { //Als de login succes vol is, zet dan de token, email en password in een sharedPrefence zodat deze gegevens later kunnen worden opgehaald. SharedPreferences.Editor editor = getActivity().getSharedPreferences("Logindetails", MODE_PRIVATE).edit(); editor.putString("token", token.getAccess_token()); editor.putString("email", txtName.getText().toString()); editor.putString("password", txtPwd.getText().toString()); editor.apply(); AppMsg.makeText(getActivity(), getResources().getString(R.string.successfullLogin) + " " + txtName.getText().toString(), AppMsg.STYLE_INFO).show(); //Als het inloggen succesvol is gebeurd wissel dan naar het Home scherm (lijst met vragen) Fragment frag = new AmsHomeFragment(); FragmentManager fragMan = getFragmentManager(); FragmentTransaction fragTran = fragMan.beginTransaction(); fragTran.replace(R.id.frame_container, frag); fragTran.addToBackStack(null); fragTran.commit(); } */ /* @Override public void failure(RetrofitError error) { //Gaat het inloggen verkeerd, vang dan de json error code die retrofit teruggeeft. Match de json code aan gekende errors en geef gepaste feedback. String json = new String(((TypedByteArray) error.getResponse().getBody()).getBytes()); if (json.equals(getResources().getString(R.string.retrofit_username_or_password_wrong_json))) { AppMsg.makeText(getActivity(), getResources().getString(R.string.username_or_password_wrong), AppMsg.STYLE_ALERT).show(); } else { AppMsg.makeText(getActivity(), getResources().getString(R.string.something_went_wrong) + error, AppMsg.STYLE_ALERT).show(); } } */ }
26164_0
package view; import controller.MetroTicketViewController; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.stage.Stage; import javafx.stage.StageStyle; import jxl.read.biff.BiffException; import jxl.write.WriteException; import model.MetroFacade; import model.Metrocard; import model.TicketPriceDecorator.TicketPrice; import java.awt.*; import java.io.IOException; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.ArrayList; public class MetroTicketView extends GridPane { private Stage stage = new Stage(); private MetroFacade metro; private MetroTicketViewController metroTicketViewController; private ChoiceBox choiceBox = new ChoiceBox(); private ObservableList<Integer> metroIDs; public MetroTicketView(MetroFacade metro){ this.metro = metro; this.metroTicketViewController = new MetroTicketViewController(metro, this); stage.setTitle("METROTICKET VIEW"); stage.initStyle(StageStyle.UTILITY); stage.setX(5); stage.setY(5); this.setVgap(5); this.setHgap(5); Group root = new Group(); Group newCard = new Group(); Group selectCard = new Group(); Group request = new Group(); newCard.setLayoutX(30); newCard.setLayoutY(20); //sCard meer naar onder zetten selectCard.setLayoutX(30); selectCard.setLayoutY(100); Button button = new Button("new metro card"); button.setOnAction(event -> { try { metroTicketViewController.addMetroCard(); } catch (BiffException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } }); Text text = new Text("Metro card price is €15 - 2 free rides included"); text.setX(0); text.setY(50); Text selectMetroCardText = new Text("select metro card"); selectMetroCardText.setX(60); selectMetroCardText.setY(20); Text numberOfRides = new Text("Number of rides"); numberOfRides.setX(0); numberOfRides.setY(170); TextField numberOfRidesTextField = new TextField(); numberOfRidesTextField.setLayoutX(150); numberOfRidesTextField.setLayoutY(150); CheckBox checkBox1 = new CheckBox("higher education student?"); checkBox1.setLayoutX(0); checkBox1.setLayoutY(200); ToggleGroup toggleGroup = new ToggleGroup(); RadioButton button1 = new RadioButton("younger than 24 years"); button1.setLayoutX(0); button1.setLayoutY(250); RadioButton button2 = new RadioButton("older than 64 years"); button2.setLayoutX(200); button2.setLayoutY(250); RadioButton button3 = new RadioButton("between 24 and 64 years"); button3.setLayoutX(400); button3.setLayoutY(250); button1.setToggleGroup(toggleGroup); button2.setToggleGroup(toggleGroup); button3.setToggleGroup(toggleGroup); Button addExtraRides = new Button("add extra rides to metro card"); addExtraRides.setLayoutX(30); addExtraRides.setLayoutY(320); Text explanationText = new Text(); Text totalPriceText = new Text("Total price:"); Text totalPriceValue = new Text(); addExtraRides.setOnAction(event -> { int ritten = Integer.parseInt(numberOfRidesTextField.getText()); //boolean is24Min = false; boolean is64Plus = false; boolean isStudent = false; boolean is24Min = false; String exptxt = "Basic price of ride is €2,10 "; if (toggleGroup.getSelectedToggle() == button2){ is64Plus = true; } if (checkBox1.isSelected()){ isStudent = true; } if (toggleGroup.getSelectedToggle() == button2){ is24Min = true; } //TO DO ervoor zorgen dat toegepaste kortingen in tekstje komen te staan // for (String s: metroTicketViewController.getMetroTicketsDiscountList()){ // exptxt += s; // } explanationText.setText(exptxt); int id = (int) choiceBox.getValue(); double price = metroTicketViewController.calculatePrice(is24Min, is64Plus, isStudent, id)*ritten; totalPriceValue.setText("€" + String.valueOf(round(price, 2))); }); totalPriceText.setLayoutX(30); totalPriceText.setLayoutY(380); totalPriceValue.setLayoutX(120); totalPriceValue.setLayoutY(380); explanationText.setLayoutX(30); explanationText.setLayoutY(420); Button confirmRequest = new Button("Confirm request"); confirmRequest.setOnAction(event -> { metroTicketViewController.addMetrotickets((Integer) choiceBox.getValue(), Integer.parseInt(numberOfRidesTextField.getText())); }); confirmRequest.setLayoutX(30); confirmRequest.setLayoutY(450); Button cancelRequest = new Button("Cancel request"); cancelRequest.setLayoutX(180); cancelRequest.setLayoutY(450); selectCard.getChildren().addAll(selectMetroCardText, choiceBox); newCard.getChildren().addAll(text, button, numberOfRides, numberOfRidesTextField, checkBox1, button1, button2, button3); request.getChildren().addAll(addExtraRides, totalPriceText, totalPriceValue, explanationText, confirmRequest, cancelRequest); root.getChildren().addAll(newCard, selectCard, request); Scene scene = new Scene(root, 650, 550); stage.setScene(scene); stage.sizeToScene(); stage.show(); } public void updateMetrocardIDList(ArrayList<Integer> metroCardIds){ this.metroIDs = FXCollections.observableArrayList(metroCardIds); choiceBox.setItems(metroIDs); choiceBox.setValue(metroIDs.get(0)); } public static double round(double value, int places) { if (places < 0) throw new IllegalArgumentException(); BigDecimal bd = BigDecimal.valueOf(value); bd = bd.setScale(places, RoundingMode.HALF_UP); return bd.doubleValue(); } }
Bo-vcu/26_Aesloos_Cap_Deplae_VanCriekinge_Metro
src/view/MetroTicketView.java
1,977
//sCard meer naar onder zetten
line_comment
nl
package view; import controller.MetroTicketViewController; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.stage.Stage; import javafx.stage.StageStyle; import jxl.read.biff.BiffException; import jxl.write.WriteException; import model.MetroFacade; import model.Metrocard; import model.TicketPriceDecorator.TicketPrice; import java.awt.*; import java.io.IOException; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.ArrayList; public class MetroTicketView extends GridPane { private Stage stage = new Stage(); private MetroFacade metro; private MetroTicketViewController metroTicketViewController; private ChoiceBox choiceBox = new ChoiceBox(); private ObservableList<Integer> metroIDs; public MetroTicketView(MetroFacade metro){ this.metro = metro; this.metroTicketViewController = new MetroTicketViewController(metro, this); stage.setTitle("METROTICKET VIEW"); stage.initStyle(StageStyle.UTILITY); stage.setX(5); stage.setY(5); this.setVgap(5); this.setHgap(5); Group root = new Group(); Group newCard = new Group(); Group selectCard = new Group(); Group request = new Group(); newCard.setLayoutX(30); newCard.setLayoutY(20); //sCard meer<SUF> selectCard.setLayoutX(30); selectCard.setLayoutY(100); Button button = new Button("new metro card"); button.setOnAction(event -> { try { metroTicketViewController.addMetroCard(); } catch (BiffException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } }); Text text = new Text("Metro card price is €15 - 2 free rides included"); text.setX(0); text.setY(50); Text selectMetroCardText = new Text("select metro card"); selectMetroCardText.setX(60); selectMetroCardText.setY(20); Text numberOfRides = new Text("Number of rides"); numberOfRides.setX(0); numberOfRides.setY(170); TextField numberOfRidesTextField = new TextField(); numberOfRidesTextField.setLayoutX(150); numberOfRidesTextField.setLayoutY(150); CheckBox checkBox1 = new CheckBox("higher education student?"); checkBox1.setLayoutX(0); checkBox1.setLayoutY(200); ToggleGroup toggleGroup = new ToggleGroup(); RadioButton button1 = new RadioButton("younger than 24 years"); button1.setLayoutX(0); button1.setLayoutY(250); RadioButton button2 = new RadioButton("older than 64 years"); button2.setLayoutX(200); button2.setLayoutY(250); RadioButton button3 = new RadioButton("between 24 and 64 years"); button3.setLayoutX(400); button3.setLayoutY(250); button1.setToggleGroup(toggleGroup); button2.setToggleGroup(toggleGroup); button3.setToggleGroup(toggleGroup); Button addExtraRides = new Button("add extra rides to metro card"); addExtraRides.setLayoutX(30); addExtraRides.setLayoutY(320); Text explanationText = new Text(); Text totalPriceText = new Text("Total price:"); Text totalPriceValue = new Text(); addExtraRides.setOnAction(event -> { int ritten = Integer.parseInt(numberOfRidesTextField.getText()); //boolean is24Min = false; boolean is64Plus = false; boolean isStudent = false; boolean is24Min = false; String exptxt = "Basic price of ride is €2,10 "; if (toggleGroup.getSelectedToggle() == button2){ is64Plus = true; } if (checkBox1.isSelected()){ isStudent = true; } if (toggleGroup.getSelectedToggle() == button2){ is24Min = true; } //TO DO ervoor zorgen dat toegepaste kortingen in tekstje komen te staan // for (String s: metroTicketViewController.getMetroTicketsDiscountList()){ // exptxt += s; // } explanationText.setText(exptxt); int id = (int) choiceBox.getValue(); double price = metroTicketViewController.calculatePrice(is24Min, is64Plus, isStudent, id)*ritten; totalPriceValue.setText("€" + String.valueOf(round(price, 2))); }); totalPriceText.setLayoutX(30); totalPriceText.setLayoutY(380); totalPriceValue.setLayoutX(120); totalPriceValue.setLayoutY(380); explanationText.setLayoutX(30); explanationText.setLayoutY(420); Button confirmRequest = new Button("Confirm request"); confirmRequest.setOnAction(event -> { metroTicketViewController.addMetrotickets((Integer) choiceBox.getValue(), Integer.parseInt(numberOfRidesTextField.getText())); }); confirmRequest.setLayoutX(30); confirmRequest.setLayoutY(450); Button cancelRequest = new Button("Cancel request"); cancelRequest.setLayoutX(180); cancelRequest.setLayoutY(450); selectCard.getChildren().addAll(selectMetroCardText, choiceBox); newCard.getChildren().addAll(text, button, numberOfRides, numberOfRidesTextField, checkBox1, button1, button2, button3); request.getChildren().addAll(addExtraRides, totalPriceText, totalPriceValue, explanationText, confirmRequest, cancelRequest); root.getChildren().addAll(newCard, selectCard, request); Scene scene = new Scene(root, 650, 550); stage.setScene(scene); stage.sizeToScene(); stage.show(); } public void updateMetrocardIDList(ArrayList<Integer> metroCardIds){ this.metroIDs = FXCollections.observableArrayList(metroCardIds); choiceBox.setItems(metroIDs); choiceBox.setValue(metroIDs.get(0)); } public static double round(double value, int places) { if (places < 0) throw new IllegalArgumentException(); BigDecimal bd = BigDecimal.valueOf(value); bd = bd.setScale(places, RoundingMode.HALF_UP); return bd.doubleValue(); } }
23183_2
package app.qienuren.controller; import app.qienuren.exceptions.OnderwerkException; import app.qienuren.exceptions.OverwerkException; import app.qienuren.model.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.time.YearMonth; import java.util.ArrayList; import java.util.List; @Service @Transactional public class UrenFormulierService { @Autowired UrenFormulierRepository urenFormulierRepository; @Autowired WerkdagRepository werkdagRepository; @Autowired WerkdagService werkdagService; @Autowired GebruikerRepository gebruikerRepository; @Autowired MailService mailService; public Iterable<UrenFormulier> getAllUrenFormulieren() { return urenFormulierRepository.findAll(); } public List<UrenFormulier> urenFormulieren() { return (List<UrenFormulier>) urenFormulierRepository.findAll(); } public Object addWorkDaytoUrenFormulier(UrenFormulier uf, long wdid) { Werkdag wd = werkdagRepository.findById(wdid).get(); try { uf.addWerkdayToArray(wd); return urenFormulierRepository.save(uf); } catch (Exception e) { return e.getMessage(); } } public UrenFormulier addNewUrenFormulier(UrenFormulier uf) { int maand = uf.getMaand().ordinal() + 1; YearMonth yearMonth = YearMonth.of(Integer.parseInt(uf.getJaar()), maand); int daysInMonth = yearMonth.lengthOfMonth(); for (int x = 1; x <= daysInMonth; x++) { Werkdag werkdag = werkdagService.addNewWorkday(new Werkdag(x)); addWorkDaytoUrenFormulier(uf, werkdag.getId()); } return urenFormulierRepository.save(uf); } public double getTotaalGewerkteUren(long id) { return urenFormulierRepository.findById(id).get().getTotaalGewerkteUren(); } public double getZiekteUrenbyId(long id){ return urenFormulierRepository.findById(id).get().getZiekteUren(); } public Iterable<UrenFormulier> getUrenFormulierPerMaand(int maandid) { List<UrenFormulier> localUren = new ArrayList<>(); for (UrenFormulier uren : urenFormulierRepository.findAll()) { if (uren.getMaand().ordinal() == maandid) { localUren.add(uren); } } return localUren; } public UrenFormulier getUrenFormulierById(long uid) { return urenFormulierRepository.findById(uid).get(); } public double getGewerkteUrenByID(long id) { return 0.0; } public Object setStatusUrenFormulier(long urenformulierId, String welkeGoedkeurder){ //deze methode zet de statusGoedkeuring van OPEN naar INGEDIEND_TRAINEE nadat deze // door de trainee is ingediend ter goedkeuring if (welkeGoedkeurder.equals("GEBRUIKER")) { checkMaximaalZiekuren(getZiekteUrenbyId(urenformulierId)); try { enoughWorkedthisMonth(getTotaalGewerkteUren(urenformulierId)); } catch(OnderwerkException onderwerkException) { urenFormulierRepository.save(urenFormulierRepository.findById(urenformulierId).get()); System.out.println("je hebt te weinig uren ingevuld deze maand"); return "onderwerk"; } catch (OverwerkException overwerkexception){ urenFormulierRepository.save(urenFormulierRepository.findById(urenformulierId).get()); System.out.println("Je hebt teveel uren ingevuld deze maand!"); return "overwerk"; } catch (Exception e) { urenFormulierRepository.save(urenFormulierRepository.findById(urenformulierId).get()); return "random exception"; } getUrenFormulierById(urenformulierId).setStatusGoedkeuring(StatusGoedkeuring.INGEDIEND_GEBRUIKER); urenFormulierRepository.save(urenFormulierRepository.findById(urenformulierId).get()); return "gelukt"; } //deze methode zet de statusGoedkeuring van INGEDIEND_TRAINEE of INGEDIEND_MEDEWERKER naar // GOEDGEKEURD_ADMIN nadat deze door de trainee/medewerker is ingediend ter goedkeuring // (en door bedrijf is goedgekeurd indien Trainee) if(welkeGoedkeurder.equals("ADMIN")) { getUrenFormulierById(urenformulierId).setStatusGoedkeuring(StatusGoedkeuring.GOEDGEKEURD_ADMIN); } //deze methode zet de statusGoedkeuring van INGEDIEND_TRAINEE naar GOEDGEKEURD_BEDRIJF nadat deze //door de trainee/medewerker is ingediend ter goedkeuring. Medewerker slaat deze methode over //en gaat gelijk naar goedkeuring admin! if(welkeGoedkeurder.equals("BEDRIJF")) { getUrenFormulierById(urenformulierId).setStatusGoedkeuring(StatusGoedkeuring.GOEDGEKEURD_BEDRIJF); } return getUrenFormulierById(urenformulierId); } public UrenFormulier changeDetails(UrenFormulier urenFormulier, UrenFormulier urenFormulierUpdate) { if (urenFormulierUpdate.getOpmerking() != null) { urenFormulier.setOpmerking(urenFormulierUpdate.getOpmerking()); } return urenFormulierRepository.save(urenFormulier); } public void ziekMelden(String id, UrenFormulier urenFormulier, String datumDag) { Gebruiker gebruiker = gebruikerRepository.findByUserId(id); for (UrenFormulier uf : gebruiker.getUrenFormulier()) { if (uf.getJaar().equals(urenFormulier.getJaar()) && uf.getMaand() == urenFormulier.getMaand()) { for (Werkdag werkdag : uf.getWerkdag()) { if (werkdag.getDatumDag().equals(datumDag)) { werkdagRepository.save(werkdag.ikBenZiek()); } } } } } public void enoughWorkedthisMonth(double totalHoursWorked) throws OnderwerkException { if (totalHoursWorked <= 139){ throw new OnderwerkException("Je hebt te weinig uren ingevuld deze maand"); } else if (totalHoursWorked >= 220){ throw new OverwerkException("Je hebt teveel gewerkt, take a break"); } else { return; } } // try catch blok maken als deze exception getrowt wordt. if false krijgt die een bericht terug. in classe urenformulierservice regel 80.. public void checkMaximaalZiekuren(double getZiekurenFormulier){ if (getZiekurenFormulier >= 64){ Mail teveelZiekMailCora = new Mail(); teveelZiekMailCora.setEmailTo("casparsteinebach@gmail.com"); teveelZiekMailCora.setSubject("Een medewerker heeft meer dan 9 ziektedagen. Check het even!"); teveelZiekMailCora.setText("Hoi Cora, Een medewerker is volgens zijn of haar ingediende urenformulier meer dag 9 dagen ziek geweest deze maand." + " Wil je het formulier even checken? Log dan in bij het urenregistratiesysteem van Qien." ); mailService.sendEmail(teveelZiekMailCora); System.out.println("email verzonden omdat maximaal ziekteuren zijn overschreden"); } else { System.out.println("ziekteuren zijn niet overschreden. toppiejoppie"); } } // rij 85 voor dat we enough worked this month aanroepen een functie die de ziekteuren oproept. }
Bob-Coding/qienurenappgroep1
qienuren-backend/src/main/java/app/qienuren/controller/UrenFormulierService.java
2,343
//deze methode zet de statusGoedkeuring van INGEDIEND_TRAINEE of INGEDIEND_MEDEWERKER naar
line_comment
nl
package app.qienuren.controller; import app.qienuren.exceptions.OnderwerkException; import app.qienuren.exceptions.OverwerkException; import app.qienuren.model.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.time.YearMonth; import java.util.ArrayList; import java.util.List; @Service @Transactional public class UrenFormulierService { @Autowired UrenFormulierRepository urenFormulierRepository; @Autowired WerkdagRepository werkdagRepository; @Autowired WerkdagService werkdagService; @Autowired GebruikerRepository gebruikerRepository; @Autowired MailService mailService; public Iterable<UrenFormulier> getAllUrenFormulieren() { return urenFormulierRepository.findAll(); } public List<UrenFormulier> urenFormulieren() { return (List<UrenFormulier>) urenFormulierRepository.findAll(); } public Object addWorkDaytoUrenFormulier(UrenFormulier uf, long wdid) { Werkdag wd = werkdagRepository.findById(wdid).get(); try { uf.addWerkdayToArray(wd); return urenFormulierRepository.save(uf); } catch (Exception e) { return e.getMessage(); } } public UrenFormulier addNewUrenFormulier(UrenFormulier uf) { int maand = uf.getMaand().ordinal() + 1; YearMonth yearMonth = YearMonth.of(Integer.parseInt(uf.getJaar()), maand); int daysInMonth = yearMonth.lengthOfMonth(); for (int x = 1; x <= daysInMonth; x++) { Werkdag werkdag = werkdagService.addNewWorkday(new Werkdag(x)); addWorkDaytoUrenFormulier(uf, werkdag.getId()); } return urenFormulierRepository.save(uf); } public double getTotaalGewerkteUren(long id) { return urenFormulierRepository.findById(id).get().getTotaalGewerkteUren(); } public double getZiekteUrenbyId(long id){ return urenFormulierRepository.findById(id).get().getZiekteUren(); } public Iterable<UrenFormulier> getUrenFormulierPerMaand(int maandid) { List<UrenFormulier> localUren = new ArrayList<>(); for (UrenFormulier uren : urenFormulierRepository.findAll()) { if (uren.getMaand().ordinal() == maandid) { localUren.add(uren); } } return localUren; } public UrenFormulier getUrenFormulierById(long uid) { return urenFormulierRepository.findById(uid).get(); } public double getGewerkteUrenByID(long id) { return 0.0; } public Object setStatusUrenFormulier(long urenformulierId, String welkeGoedkeurder){ //deze methode zet de statusGoedkeuring van OPEN naar INGEDIEND_TRAINEE nadat deze // door de trainee is ingediend ter goedkeuring if (welkeGoedkeurder.equals("GEBRUIKER")) { checkMaximaalZiekuren(getZiekteUrenbyId(urenformulierId)); try { enoughWorkedthisMonth(getTotaalGewerkteUren(urenformulierId)); } catch(OnderwerkException onderwerkException) { urenFormulierRepository.save(urenFormulierRepository.findById(urenformulierId).get()); System.out.println("je hebt te weinig uren ingevuld deze maand"); return "onderwerk"; } catch (OverwerkException overwerkexception){ urenFormulierRepository.save(urenFormulierRepository.findById(urenformulierId).get()); System.out.println("Je hebt teveel uren ingevuld deze maand!"); return "overwerk"; } catch (Exception e) { urenFormulierRepository.save(urenFormulierRepository.findById(urenformulierId).get()); return "random exception"; } getUrenFormulierById(urenformulierId).setStatusGoedkeuring(StatusGoedkeuring.INGEDIEND_GEBRUIKER); urenFormulierRepository.save(urenFormulierRepository.findById(urenformulierId).get()); return "gelukt"; } //deze methode<SUF> // GOEDGEKEURD_ADMIN nadat deze door de trainee/medewerker is ingediend ter goedkeuring // (en door bedrijf is goedgekeurd indien Trainee) if(welkeGoedkeurder.equals("ADMIN")) { getUrenFormulierById(urenformulierId).setStatusGoedkeuring(StatusGoedkeuring.GOEDGEKEURD_ADMIN); } //deze methode zet de statusGoedkeuring van INGEDIEND_TRAINEE naar GOEDGEKEURD_BEDRIJF nadat deze //door de trainee/medewerker is ingediend ter goedkeuring. Medewerker slaat deze methode over //en gaat gelijk naar goedkeuring admin! if(welkeGoedkeurder.equals("BEDRIJF")) { getUrenFormulierById(urenformulierId).setStatusGoedkeuring(StatusGoedkeuring.GOEDGEKEURD_BEDRIJF); } return getUrenFormulierById(urenformulierId); } public UrenFormulier changeDetails(UrenFormulier urenFormulier, UrenFormulier urenFormulierUpdate) { if (urenFormulierUpdate.getOpmerking() != null) { urenFormulier.setOpmerking(urenFormulierUpdate.getOpmerking()); } return urenFormulierRepository.save(urenFormulier); } public void ziekMelden(String id, UrenFormulier urenFormulier, String datumDag) { Gebruiker gebruiker = gebruikerRepository.findByUserId(id); for (UrenFormulier uf : gebruiker.getUrenFormulier()) { if (uf.getJaar().equals(urenFormulier.getJaar()) && uf.getMaand() == urenFormulier.getMaand()) { for (Werkdag werkdag : uf.getWerkdag()) { if (werkdag.getDatumDag().equals(datumDag)) { werkdagRepository.save(werkdag.ikBenZiek()); } } } } } public void enoughWorkedthisMonth(double totalHoursWorked) throws OnderwerkException { if (totalHoursWorked <= 139){ throw new OnderwerkException("Je hebt te weinig uren ingevuld deze maand"); } else if (totalHoursWorked >= 220){ throw new OverwerkException("Je hebt teveel gewerkt, take a break"); } else { return; } } // try catch blok maken als deze exception getrowt wordt. if false krijgt die een bericht terug. in classe urenformulierservice regel 80.. public void checkMaximaalZiekuren(double getZiekurenFormulier){ if (getZiekurenFormulier >= 64){ Mail teveelZiekMailCora = new Mail(); teveelZiekMailCora.setEmailTo("casparsteinebach@gmail.com"); teveelZiekMailCora.setSubject("Een medewerker heeft meer dan 9 ziektedagen. Check het even!"); teveelZiekMailCora.setText("Hoi Cora, Een medewerker is volgens zijn of haar ingediende urenformulier meer dag 9 dagen ziek geweest deze maand." + " Wil je het formulier even checken? Log dan in bij het urenregistratiesysteem van Qien." ); mailService.sendEmail(teveelZiekMailCora); System.out.println("email verzonden omdat maximaal ziekteuren zijn overschreden"); } else { System.out.println("ziekteuren zijn niet overschreden. toppiejoppie"); } } // rij 85 voor dat we enough worked this month aanroepen een functie die de ziekteuren oproept. }
167130_0
package keezen; import java.io.Serializable; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; public class Decks implements Serializable{ Kaart[] drawPile; Kaart[] discardPile; public Decks (){ } public Kaart[] getDrawPile(){ return drawPile; } public void setAantalKaarten(int aantalKaarten){ drawPile = new Kaart[aantalKaarten]; discardPile = new Kaart[aantalKaarten]; } public void setDrawPile(Kaart[] drawPile){ this.drawPile = drawPile; } public Kaart[] getDiscardPile(){ return discardPile; } public void setDiscardPile(Kaart[] discardPile){ this.discardPile = discardPile; } } /*public class Decks implements Serializable { Kaart[] drawPile; Kaart[] discardPile; public Decks (int aantalKaarten){ drawPile = new Kaart[aantalKaarten]; discardPile = new Kaart[aantalKaarten]; } public Kaart[] getDrawPile() { return drawPile; } public void setDrawPile(Kaart[] drawPile) { this.drawPile = drawPile; } public Kaart[] getDiscardPile() { return discardPile; } public void setDiscardPile(Kaart[] discardPile) { this.discardPile = discardPile; } }*/
Bobster94/Keezen
src/keezen/Decks.java
459
/*public class Decks implements Serializable { Kaart[] drawPile; Kaart[] discardPile; public Decks (int aantalKaarten){ drawPile = new Kaart[aantalKaarten]; discardPile = new Kaart[aantalKaarten]; } public Kaart[] getDrawPile() { return drawPile; } public void setDrawPile(Kaart[] drawPile) { this.drawPile = drawPile; } public Kaart[] getDiscardPile() { return discardPile; } public void setDiscardPile(Kaart[] discardPile) { this.discardPile = discardPile; } }*/
block_comment
nl
package keezen; import java.io.Serializable; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; public class Decks implements Serializable{ Kaart[] drawPile; Kaart[] discardPile; public Decks (){ } public Kaart[] getDrawPile(){ return drawPile; } public void setAantalKaarten(int aantalKaarten){ drawPile = new Kaart[aantalKaarten]; discardPile = new Kaart[aantalKaarten]; } public void setDrawPile(Kaart[] drawPile){ this.drawPile = drawPile; } public Kaart[] getDiscardPile(){ return discardPile; } public void setDiscardPile(Kaart[] discardPile){ this.discardPile = discardPile; } } /*public class Decks<SUF>*/
148687_1
package com.boelroy.arrowpopwindows.lib; import android.content.Context; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.widget.PopupWindow; /** * Created by boelroy on 14-2-22. */ public class PopupWindows { protected Context mContext; protected PopupWindow mWindow; protected View mRootView; protected Drawable mBackground = null; protected WindowManager mWindowManager; public PopupWindows(Context context){ mContext = context; mWindow = new PopupWindow(context); mWindow.setTouchInterceptor(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { if(motionEvent.getAction() == MotionEvent.ACTION_OUTSIDE){ mWindow.dismiss(); return true; } return false; } }); mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); } protected void onDismiss(){ } protected void onShow(){ } protected void preShow(){ if(mRootView == null) throw new IllegalStateException("SetContentView was not called with a view to display"); if(mBackground == null){ ColorDrawable dw = new ColorDrawable(0xb0000000); mWindow.setBackgroundDrawable(dw); } else mWindow.setBackgroundDrawable(mBackground); mWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT); mWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT); mWindow.setTouchable(true); mWindow.setFocusable(true); mWindow.setOutsideTouchable(true); mWindow.setContentView(mRootView); } protected void preShow(int width, int height){ if(mRootView == null) throw new IllegalStateException("SetContentView was not called with a view to display"); if(mBackground == null) mWindow.setBackgroundDrawable(new BitmapDrawable()); else mWindow.setBackgroundDrawable(mBackground); mWindow.setWidth(width); if(height == 0){ mWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT); }else{ mWindow.setHeight(height); } mWindow.setTouchable(true); mWindow.setFocusable(true); mWindow.setOutsideTouchable(true); mWindow.setContentView(mRootView); } public void setBackgroundDrawable(Drawable background) { mBackground = background; } /** * Set content view. * * @param root Root view */ public void setContentView(View root) { mRootView = root; mWindow.setContentView(root); } /** * Set content view. * * @param layoutResID Resource id */ public void setContentView(int layoutResID) { LayoutInflater inflator = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); setContentView(inflator.inflate(layoutResID, null)); } /** * Set listener on window dismissed. * * @param listener */ public void setOnDismissListener(PopupWindow.OnDismissListener listener) { mWindow.setOnDismissListener(listener); } /** * Dismiss the popup window. */ public void dismiss() { mWindow.dismiss(); } }
Boelroy/ArrowPopupWindows
lib/src/main/java/com/boelroy/arrowpopwindows/lib/PopupWindows.java
1,023
/** * Set content view. * * @param root Root view */
block_comment
nl
package com.boelroy.arrowpopwindows.lib; import android.content.Context; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.widget.PopupWindow; /** * Created by boelroy on 14-2-22. */ public class PopupWindows { protected Context mContext; protected PopupWindow mWindow; protected View mRootView; protected Drawable mBackground = null; protected WindowManager mWindowManager; public PopupWindows(Context context){ mContext = context; mWindow = new PopupWindow(context); mWindow.setTouchInterceptor(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { if(motionEvent.getAction() == MotionEvent.ACTION_OUTSIDE){ mWindow.dismiss(); return true; } return false; } }); mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); } protected void onDismiss(){ } protected void onShow(){ } protected void preShow(){ if(mRootView == null) throw new IllegalStateException("SetContentView was not called with a view to display"); if(mBackground == null){ ColorDrawable dw = new ColorDrawable(0xb0000000); mWindow.setBackgroundDrawable(dw); } else mWindow.setBackgroundDrawable(mBackground); mWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT); mWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT); mWindow.setTouchable(true); mWindow.setFocusable(true); mWindow.setOutsideTouchable(true); mWindow.setContentView(mRootView); } protected void preShow(int width, int height){ if(mRootView == null) throw new IllegalStateException("SetContentView was not called with a view to display"); if(mBackground == null) mWindow.setBackgroundDrawable(new BitmapDrawable()); else mWindow.setBackgroundDrawable(mBackground); mWindow.setWidth(width); if(height == 0){ mWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT); }else{ mWindow.setHeight(height); } mWindow.setTouchable(true); mWindow.setFocusable(true); mWindow.setOutsideTouchable(true); mWindow.setContentView(mRootView); } public void setBackgroundDrawable(Drawable background) { mBackground = background; } /** * Set content view.<SUF>*/ public void setContentView(View root) { mRootView = root; mWindow.setContentView(root); } /** * Set content view. * * @param layoutResID Resource id */ public void setContentView(int layoutResID) { LayoutInflater inflator = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); setContentView(inflator.inflate(layoutResID, null)); } /** * Set listener on window dismissed. * * @param listener */ public void setOnDismissListener(PopupWindow.OnDismissListener listener) { mWindow.setOnDismissListener(listener); } /** * Dismiss the popup window. */ public void dismiss() { mWindow.dismiss(); } }
15593_9
/* * $Id: 6ddf217d35251bfa9016c8c2f9b32c76ca3fddb6 $ * * This file is part of the iText (R) project. * Copyright (c) 1998-2016 iText Group NV * Authors: Balder Van Camp, Emiel Ackermann, et al. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License version 3 * as published by the Free Software Foundation with the addition of the * following permission added to Section 15 as permitted in Section 7(a): * FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY * ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT * OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. You should have received a copy of the GNU Affero General Public License along with this program; if not, * see http://www.gnu.org/licenses or write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA, 02110-1301 USA, or download the license from the following URL: http://itextpdf.com/terms-of-use/ * * The interactive user interfaces in modified source and object code versions of this program must display Appropriate * Legal Notices, as required under Section 5 of the GNU Affero General Public License. * * In accordance with Section 7(b) of the GNU Affero General Public License, a covered work must retain the producer * line in every PDF that is created or manipulated using iText. * * You can be released from the requirements of the license by purchasing a commercial license. Buying such a license is * mandatory as soon as you develop commercial activities involving the iText software without disclosing the source * code of your own applications. These activities include: offering paid services to customers as an ASP, serving PDFs * on the fly in a web application, shipping iText with a closed source product. * * For more information, please contact iText Software Corp. at this address: sales@itextpdf.com */ package com.itextpdf.tool.xml.html; import com.itextpdf.text.Chunk; import com.itextpdf.text.Element; import com.itextpdf.text.ListItem; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.draw.LineSeparator; import com.itextpdf.text.pdf.draw.VerticalPositionMark; import com.itextpdf.tool.xml.NoCustomContextException; import com.itextpdf.tool.xml.Tag; import com.itextpdf.tool.xml.WorkerContext; import com.itextpdf.tool.xml.css.CSS; import com.itextpdf.tool.xml.css.CssUtils; import com.itextpdf.tool.xml.exceptions.LocaleMessages; import com.itextpdf.tool.xml.exceptions.RuntimeWorkerException; import com.itextpdf.tool.xml.html.pdfelement.TabbedChunk; import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author redlab_b * */ public class ParaGraph extends AbstractTagProcessor { /* * (non-Javadoc) * * @see * com.itextpdf.tool.xml.TagProcessor#content(com.itextpdf.tool.xml.Tag, * java.util.List, com.itextpdf.text.Document, java.lang.String) */ @Override public List<Element> content(final WorkerContext ctx, final Tag tag, final String content) { List<Chunk> sanitizedChunks = HTMLUtils.sanitize(content, false); List<Element> l = new ArrayList<Element>(1); for (Chunk sanitized : sanitizedChunks) { HtmlPipelineContext myctx; try { myctx = getHtmlPipelineContext(ctx); } catch (NoCustomContextException e) { throw new RuntimeWorkerException(e); } if ((null != tag.getCSS().get(CSS.Property.TAB_INTERVAL))) { TabbedChunk tabbedChunk = new TabbedChunk(sanitized.getContent()); if (null != getLastChild(tag) && null != getLastChild(tag).getCSS().get(CSS.Property.XFA_TAB_COUNT)) { tabbedChunk.setTabCount(Integer.parseInt(getLastChild(tag).getCSS().get(CSS.Property.XFA_TAB_COUNT))); } l.add(getCssAppliers().apply(tabbedChunk, tag, myctx)); } else if (null != getLastChild(tag) && null != getLastChild(tag).getCSS().get(CSS.Property.XFA_TAB_COUNT)) { TabbedChunk tabbedChunk = new TabbedChunk(sanitized.getContent()); tabbedChunk.setTabCount(Integer.parseInt(getLastChild(tag).getCSS().get(CSS.Property.XFA_TAB_COUNT))); l.add(getCssAppliers().apply(tabbedChunk, tag, myctx)); } else { l.add(getCssAppliers().apply(sanitized, tag, myctx)); } } return l; } private Tag getLastChild(final Tag tag) { if (0 != tag.getChildren().size()) return tag.getChildren().get(tag.getChildren().size() - 1); else return null; } /* * (non-Javadoc) * * @see * com.itextpdf.tool.xml.TagProcessor#endElement(com.itextpdf.tool.xml.Tag, * java.util.List, com.itextpdf.text.Document) */ @Override public List<Element> end(final WorkerContext ctx, final Tag tag, final List<Element> currentContent) { List<Element> l = new ArrayList<Element>(1); if (currentContent.size() > 0) { List<Element> elements = new ArrayList<Element>(); List<ListItem> listItems = new ArrayList<ListItem>(); for (Element el : currentContent) { if (el instanceof ListItem) { if (!elements.isEmpty()) { processParagraphItems(ctx, tag, elements, l); elements.clear(); } listItems.add((ListItem)el); } else { if (!listItems.isEmpty()) { processListItems(ctx, tag, listItems, l); listItems.clear(); } elements.add(el); } } if (!elements.isEmpty()) { processParagraphItems(ctx, tag, elements, l); elements.clear(); } else if (!listItems.isEmpty()) { processListItems(ctx, tag, listItems, l); listItems.clear(); } } return l; } protected void processParagraphItems(final WorkerContext ctx, final Tag tag, final List<Element> paragraphItems, List<Element> l) { Paragraph p = new Paragraph(); p.setMultipliedLeading(1.2f); // Element lastElement = paragraphItems.get(paragraphItems.size() - 1); // if (lastElement instanceof Chunk && Chunk.NEWLINE.getContent().equals(((Chunk) lastElement).getContent())) { // paragraphItems.remove(paragraphItems.size() - 1); // } Map<String, String> css = tag.getCSS(); if (null != css.get(CSS.Property.TAB_INTERVAL)) { addTabIntervalContent(ctx, tag, paragraphItems, p, css.get(CSS.Property.TAB_INTERVAL)); l.add(p); } else if (null != css.get(CSS.Property.TAB_STOPS)) { // <para tabstops=".." /> could use same implementation page 62 addTabStopsContent(paragraphItems, p, css.get(CSS.Property.TAB_STOPS)); l.add(p); } else if (null != css.get(CSS.Property.XFA_TAB_STOPS)) { // <para tabStops=".." /> could use same implementation page 63 addTabStopsContent(paragraphItems, p, css.get(CSS.Property.XFA_TAB_STOPS)); // leader elements needs to be l.add(p); // extracted. } else { List<Element> paraList = currentContentToParagraph(paragraphItems, true, true, tag, ctx); if (!l.isEmpty() && !paraList.isEmpty()) { Element firstElement = paraList.get(0); if (firstElement instanceof Paragraph ) { ((Paragraph) firstElement).setSpacingBefore(0); } } for (Element e : paraList) { l.add(e); } } } protected void processListItems(final WorkerContext ctx, final Tag tag, final List<ListItem> listItems, List<Element> l) { try { com.itextpdf.text.List list = new com.itextpdf.text.List(); list.setAlignindent(false); list = (com.itextpdf.text.List) getCssAppliers().apply(list, tag, getHtmlPipelineContext(ctx)); list.setIndentationLeft(0); int i = 0; for (ListItem li : listItems) { li = (ListItem) getCssAppliers().apply(li, tag, getHtmlPipelineContext(ctx)); if (i != listItems.size() - 1) { li.setSpacingAfter(0); } if (i != 0 ) { li.setSpacingBefore(0); } i++; li.setMultipliedLeading(1.2f); list.add(li); } if (!l.isEmpty()) { Element latestElement = l.get(l.size() - 1); if (latestElement instanceof Paragraph ) { ((Paragraph) latestElement).setSpacingAfter(0); } } l.add(list); } catch (NoCustomContextException e) { throw new RuntimeWorkerException(LocaleMessages.getInstance().getMessage(LocaleMessages.NO_CUSTOM_CONTEXT), e); } } /** * Applies the tab interval of the p tag on its {@link TabbedChunk} elements. <br /> * The style "xfa-tab-count" of the {@link TabbedChunk} is multiplied with the tab interval of the p tag. This width is then added to a new {@link TabbedChunk}.</br> * Elements other than TabbedChunks are added directly to the given Paragraph p. * * @param currentContent containing the elements inside the p tag. * @param p paragraph to which the tabbed chunks will be added. * @param value the value of style "tab-interval". */ private void addTabIntervalContent(final WorkerContext ctx, final Tag tag, final List<Element> currentContent, final Paragraph p, final String value) { float width = 0; for(Element e: currentContent) { if (e instanceof TabbedChunk) { width += ((TabbedChunk) e).getTabCount()*CssUtils.getInstance().parsePxInCmMmPcToPt(value); TabbedChunk tab = new TabbedChunk(new VerticalPositionMark(), width, false); p.add(new Chunk(tab)); p.add(new Chunk((TabbedChunk) e)); } else { if (e instanceof LineSeparator) { try { HtmlPipelineContext htmlPipelineContext = getHtmlPipelineContext(ctx); Chunk newLine = (Chunk)getCssAppliers().apply(new Chunk(Chunk.NEWLINE), tag, htmlPipelineContext); p.add(newLine); } catch (NoCustomContextException e1) { throw new RuntimeWorkerException(LocaleMessages.getInstance().getMessage(LocaleMessages.NO_CUSTOM_CONTEXT), e1); } } p.add(e); } } } /** * Applies the tab stops of the p tag on its {@link TabbedChunk} elements. * * @param currentContent containing the elements inside the p tag. * @param p paragraph to which the tabbed chunks will be added. * @param value the value of style "tab-stops". */ private void addTabStopsContent(final List<Element> currentContent, final Paragraph p, final String value) { List<Chunk> tabs = new ArrayList<Chunk>(); String[] alignAndWidth = value.split(" "); float tabWidth = 0; for(int i = 0 , j = 1; j < alignAndWidth.length ; i+=2, j+=2) { tabWidth += CssUtils.getInstance().parsePxInCmMmPcToPt(alignAndWidth[j]); TabbedChunk tab = new TabbedChunk(new VerticalPositionMark(), tabWidth, true, alignAndWidth[i]); tabs.add(tab); } int tabsPerRow = tabs.size(); int currentTab = 0; for(Element e: currentContent) { if (e instanceof TabbedChunk) { if(currentTab == tabsPerRow) { currentTab = 0; } if(((TabbedChunk) e).getTabCount() != 0 /* == 1*/) { p.add(new Chunk(tabs.get(currentTab))); p.add(new Chunk((TabbedChunk) e)); ++currentTab; // } else { // wat doet een tabCount van groter dan 1? sla een tab over of count * tabWidth? // int widthMultiplier = ((TabbedChunk) e).getTabCount(); } } else { p.add(e); } } } /* * (non-Javadoc) * * @see com.itextpdf.tool.xml.TagProcessor#isStackOwner() */ @Override public boolean isStackOwner() { return true; } }
Bojo38/tourma
src/com/itextpdf/tool/xml/html/ParaGraph.java
3,841
// leader elements needs to be
line_comment
nl
/* * $Id: 6ddf217d35251bfa9016c8c2f9b32c76ca3fddb6 $ * * This file is part of the iText (R) project. * Copyright (c) 1998-2016 iText Group NV * Authors: Balder Van Camp, Emiel Ackermann, et al. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License version 3 * as published by the Free Software Foundation with the addition of the * following permission added to Section 15 as permitted in Section 7(a): * FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY * ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT * OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. You should have received a copy of the GNU Affero General Public License along with this program; if not, * see http://www.gnu.org/licenses or write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA, 02110-1301 USA, or download the license from the following URL: http://itextpdf.com/terms-of-use/ * * The interactive user interfaces in modified source and object code versions of this program must display Appropriate * Legal Notices, as required under Section 5 of the GNU Affero General Public License. * * In accordance with Section 7(b) of the GNU Affero General Public License, a covered work must retain the producer * line in every PDF that is created or manipulated using iText. * * You can be released from the requirements of the license by purchasing a commercial license. Buying such a license is * mandatory as soon as you develop commercial activities involving the iText software without disclosing the source * code of your own applications. These activities include: offering paid services to customers as an ASP, serving PDFs * on the fly in a web application, shipping iText with a closed source product. * * For more information, please contact iText Software Corp. at this address: sales@itextpdf.com */ package com.itextpdf.tool.xml.html; import com.itextpdf.text.Chunk; import com.itextpdf.text.Element; import com.itextpdf.text.ListItem; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.draw.LineSeparator; import com.itextpdf.text.pdf.draw.VerticalPositionMark; import com.itextpdf.tool.xml.NoCustomContextException; import com.itextpdf.tool.xml.Tag; import com.itextpdf.tool.xml.WorkerContext; import com.itextpdf.tool.xml.css.CSS; import com.itextpdf.tool.xml.css.CssUtils; import com.itextpdf.tool.xml.exceptions.LocaleMessages; import com.itextpdf.tool.xml.exceptions.RuntimeWorkerException; import com.itextpdf.tool.xml.html.pdfelement.TabbedChunk; import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author redlab_b * */ public class ParaGraph extends AbstractTagProcessor { /* * (non-Javadoc) * * @see * com.itextpdf.tool.xml.TagProcessor#content(com.itextpdf.tool.xml.Tag, * java.util.List, com.itextpdf.text.Document, java.lang.String) */ @Override public List<Element> content(final WorkerContext ctx, final Tag tag, final String content) { List<Chunk> sanitizedChunks = HTMLUtils.sanitize(content, false); List<Element> l = new ArrayList<Element>(1); for (Chunk sanitized : sanitizedChunks) { HtmlPipelineContext myctx; try { myctx = getHtmlPipelineContext(ctx); } catch (NoCustomContextException e) { throw new RuntimeWorkerException(e); } if ((null != tag.getCSS().get(CSS.Property.TAB_INTERVAL))) { TabbedChunk tabbedChunk = new TabbedChunk(sanitized.getContent()); if (null != getLastChild(tag) && null != getLastChild(tag).getCSS().get(CSS.Property.XFA_TAB_COUNT)) { tabbedChunk.setTabCount(Integer.parseInt(getLastChild(tag).getCSS().get(CSS.Property.XFA_TAB_COUNT))); } l.add(getCssAppliers().apply(tabbedChunk, tag, myctx)); } else if (null != getLastChild(tag) && null != getLastChild(tag).getCSS().get(CSS.Property.XFA_TAB_COUNT)) { TabbedChunk tabbedChunk = new TabbedChunk(sanitized.getContent()); tabbedChunk.setTabCount(Integer.parseInt(getLastChild(tag).getCSS().get(CSS.Property.XFA_TAB_COUNT))); l.add(getCssAppliers().apply(tabbedChunk, tag, myctx)); } else { l.add(getCssAppliers().apply(sanitized, tag, myctx)); } } return l; } private Tag getLastChild(final Tag tag) { if (0 != tag.getChildren().size()) return tag.getChildren().get(tag.getChildren().size() - 1); else return null; } /* * (non-Javadoc) * * @see * com.itextpdf.tool.xml.TagProcessor#endElement(com.itextpdf.tool.xml.Tag, * java.util.List, com.itextpdf.text.Document) */ @Override public List<Element> end(final WorkerContext ctx, final Tag tag, final List<Element> currentContent) { List<Element> l = new ArrayList<Element>(1); if (currentContent.size() > 0) { List<Element> elements = new ArrayList<Element>(); List<ListItem> listItems = new ArrayList<ListItem>(); for (Element el : currentContent) { if (el instanceof ListItem) { if (!elements.isEmpty()) { processParagraphItems(ctx, tag, elements, l); elements.clear(); } listItems.add((ListItem)el); } else { if (!listItems.isEmpty()) { processListItems(ctx, tag, listItems, l); listItems.clear(); } elements.add(el); } } if (!elements.isEmpty()) { processParagraphItems(ctx, tag, elements, l); elements.clear(); } else if (!listItems.isEmpty()) { processListItems(ctx, tag, listItems, l); listItems.clear(); } } return l; } protected void processParagraphItems(final WorkerContext ctx, final Tag tag, final List<Element> paragraphItems, List<Element> l) { Paragraph p = new Paragraph(); p.setMultipliedLeading(1.2f); // Element lastElement = paragraphItems.get(paragraphItems.size() - 1); // if (lastElement instanceof Chunk && Chunk.NEWLINE.getContent().equals(((Chunk) lastElement).getContent())) { // paragraphItems.remove(paragraphItems.size() - 1); // } Map<String, String> css = tag.getCSS(); if (null != css.get(CSS.Property.TAB_INTERVAL)) { addTabIntervalContent(ctx, tag, paragraphItems, p, css.get(CSS.Property.TAB_INTERVAL)); l.add(p); } else if (null != css.get(CSS.Property.TAB_STOPS)) { // <para tabstops=".." /> could use same implementation page 62 addTabStopsContent(paragraphItems, p, css.get(CSS.Property.TAB_STOPS)); l.add(p); } else if (null != css.get(CSS.Property.XFA_TAB_STOPS)) { // <para tabStops=".." /> could use same implementation page 63 addTabStopsContent(paragraphItems, p, css.get(CSS.Property.XFA_TAB_STOPS)); // leader elements<SUF> l.add(p); // extracted. } else { List<Element> paraList = currentContentToParagraph(paragraphItems, true, true, tag, ctx); if (!l.isEmpty() && !paraList.isEmpty()) { Element firstElement = paraList.get(0); if (firstElement instanceof Paragraph ) { ((Paragraph) firstElement).setSpacingBefore(0); } } for (Element e : paraList) { l.add(e); } } } protected void processListItems(final WorkerContext ctx, final Tag tag, final List<ListItem> listItems, List<Element> l) { try { com.itextpdf.text.List list = new com.itextpdf.text.List(); list.setAlignindent(false); list = (com.itextpdf.text.List) getCssAppliers().apply(list, tag, getHtmlPipelineContext(ctx)); list.setIndentationLeft(0); int i = 0; for (ListItem li : listItems) { li = (ListItem) getCssAppliers().apply(li, tag, getHtmlPipelineContext(ctx)); if (i != listItems.size() - 1) { li.setSpacingAfter(0); } if (i != 0 ) { li.setSpacingBefore(0); } i++; li.setMultipliedLeading(1.2f); list.add(li); } if (!l.isEmpty()) { Element latestElement = l.get(l.size() - 1); if (latestElement instanceof Paragraph ) { ((Paragraph) latestElement).setSpacingAfter(0); } } l.add(list); } catch (NoCustomContextException e) { throw new RuntimeWorkerException(LocaleMessages.getInstance().getMessage(LocaleMessages.NO_CUSTOM_CONTEXT), e); } } /** * Applies the tab interval of the p tag on its {@link TabbedChunk} elements. <br /> * The style "xfa-tab-count" of the {@link TabbedChunk} is multiplied with the tab interval of the p tag. This width is then added to a new {@link TabbedChunk}.</br> * Elements other than TabbedChunks are added directly to the given Paragraph p. * * @param currentContent containing the elements inside the p tag. * @param p paragraph to which the tabbed chunks will be added. * @param value the value of style "tab-interval". */ private void addTabIntervalContent(final WorkerContext ctx, final Tag tag, final List<Element> currentContent, final Paragraph p, final String value) { float width = 0; for(Element e: currentContent) { if (e instanceof TabbedChunk) { width += ((TabbedChunk) e).getTabCount()*CssUtils.getInstance().parsePxInCmMmPcToPt(value); TabbedChunk tab = new TabbedChunk(new VerticalPositionMark(), width, false); p.add(new Chunk(tab)); p.add(new Chunk((TabbedChunk) e)); } else { if (e instanceof LineSeparator) { try { HtmlPipelineContext htmlPipelineContext = getHtmlPipelineContext(ctx); Chunk newLine = (Chunk)getCssAppliers().apply(new Chunk(Chunk.NEWLINE), tag, htmlPipelineContext); p.add(newLine); } catch (NoCustomContextException e1) { throw new RuntimeWorkerException(LocaleMessages.getInstance().getMessage(LocaleMessages.NO_CUSTOM_CONTEXT), e1); } } p.add(e); } } } /** * Applies the tab stops of the p tag on its {@link TabbedChunk} elements. * * @param currentContent containing the elements inside the p tag. * @param p paragraph to which the tabbed chunks will be added. * @param value the value of style "tab-stops". */ private void addTabStopsContent(final List<Element> currentContent, final Paragraph p, final String value) { List<Chunk> tabs = new ArrayList<Chunk>(); String[] alignAndWidth = value.split(" "); float tabWidth = 0; for(int i = 0 , j = 1; j < alignAndWidth.length ; i+=2, j+=2) { tabWidth += CssUtils.getInstance().parsePxInCmMmPcToPt(alignAndWidth[j]); TabbedChunk tab = new TabbedChunk(new VerticalPositionMark(), tabWidth, true, alignAndWidth[i]); tabs.add(tab); } int tabsPerRow = tabs.size(); int currentTab = 0; for(Element e: currentContent) { if (e instanceof TabbedChunk) { if(currentTab == tabsPerRow) { currentTab = 0; } if(((TabbedChunk) e).getTabCount() != 0 /* == 1*/) { p.add(new Chunk(tabs.get(currentTab))); p.add(new Chunk((TabbedChunk) e)); ++currentTab; // } else { // wat doet een tabCount van groter dan 1? sla een tab over of count * tabWidth? // int widthMultiplier = ((TabbedChunk) e).getTabCount(); } } else { p.add(e); } } } /* * (non-Javadoc) * * @see com.itextpdf.tool.xml.TagProcessor#isStackOwner() */ @Override public boolean isStackOwner() { return true; } }
111889_1
package org.ijsberg.iglu.util.misc; import org.ijsberg.iglu.util.io.FSFileCollection; import org.ijsberg.iglu.util.io.FileCollection; import org.ijsberg.iglu.util.io.FileFilterRuleSet; import org.ijsberg.iglu.util.io.FileSupport; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Properties; /** * Created by J Meetsma on 4-12-2015. */ public class SearchAndReplace { /* <xs:simpleType name="RijKarakteristiekOmschrijvingType"> <xs:annotation> <xs:documentation>Waardes: Eurocity/Europese Unit Cargo/Goederen/Intercity/Intercity Expres/Internationaal/Meetwagen/Losse Loc/Losse Loc Reizigers/Leeg Materieel/Lege Motorpost/Motorpost/Onderhoud Materieel/Proef Goederen/Snelananas/Stopananas/Stoomananas Materieel/TGV/Ultrasoon/Meetwagen/Werkananas/Thalys/Sprinter/Tram */ private static Properties replacements = new Properties(); static { replacements.put("Trein","Ananas"); replacements.put("Prorail","Acme"); replacements.put("ProRail","AcMe"); replacements.put("Spoorweg", "Transportband"); replacements.put("Spoor", "Transport"); replacements.put("Goederen", "Transport"); replacements.put("Cargo", "Motion"); replacements.put("Eurocity", "Telstar"); replacements.put("Tgv", "Btw"); replacements.put("Thalys", "Aardbei"); replacements.put("Spoor", "Transport"); replacements.put("Wagen", "Krat"); replacements.put("Sprinter", "Colli"); replacements.put("Intercity", "Pallet"); replacements.put("Wissel", "Hefboom"); replacements.put("RijKarakteristiek", "Opname"); replacements.put("Reiziger", "Fruit"); replacements.put("Perron", "Steiger"); replacements.put("Baanvak", "Productielijn"); replacements.put("Kilometer", "Staffel"); replacements.put("Kilometrering", "Gradatie"); replacements.put("Dienst", "Weegschaal"); replacements.put("Ces_ovgs", "Xyz"); } private static final String BASE_DIR = "C:\\repository\\TibcoBW\\CES_OVGS_TreinNummerReeks_v1.0.2"; private static final String TARGET_DIR = "C:\\repository\\TibcoBW\\clean"; private static String[] originalNames; private static String[] destinationNames; private static void populateKeysAndValues(Properties properties) { ArrayList<String> keyList = new ArrayList<String>(); ArrayList<String> valueList = new ArrayList<String>(); for(String key : properties.stringPropertyNames()) { keyList.add(key); keyList.add(key.toLowerCase()); keyList.add(key.toUpperCase()); String value = properties.getProperty(key); valueList.add(value); valueList.add(value.toLowerCase()); valueList.add(value.toUpperCase()); } originalNames = keyList.toArray(new String[0]); destinationNames = valueList.toArray(new String[0]); } /* create new dir struct */ public static void main(String[] args) throws IOException{ populateKeysAndValues(replacements); File newDir = new File(TARGET_DIR); newDir.mkdirs(); FileSupport.emptyDirectory(newDir); FileCollection fileCollection = new FSFileCollection( BASE_DIR, new FileFilterRuleSet().setIncludeFilesWithNameMask("*.process|*.wsdl|*.xsd|*.substvar")); for(String fileName : fileCollection.getFileNames()) { String newFileName = StringSupport.replaceAll(fileName, originalNames, destinationNames); String fileContents = FileSupport.getTextFileFromFS(new File(BASE_DIR + "/" + fileName)); String newFileContents = StringSupport.replaceAll(fileContents, originalNames, destinationNames); FileSupport.saveTextFile(newFileContents, FileSupport.createFile(TARGET_DIR + "/" + newFileName)); } FileSupport.zip(newDir.listFiles()[0].getPath(), newDir.listFiles()[0].getPath() + ".zip", "*"); } }
Boncode/Iglu-Util
src/main/java/org/ijsberg/iglu/util/misc/SearchAndReplace.java
1,280
/* <xs:simpleType name="RijKarakteristiekOmschrijvingType"> <xs:annotation> <xs:documentation>Waardes: Eurocity/Europese Unit Cargo/Goederen/Intercity/Intercity Expres/Internationaal/Meetwagen/Losse Loc/Losse Loc Reizigers/Leeg Materieel/Lege Motorpost/Motorpost/Onderhoud Materieel/Proef Goederen/Snelananas/Stopananas/Stoomananas Materieel/TGV/Ultrasoon/Meetwagen/Werkananas/Thalys/Sprinter/Tram */
block_comment
nl
package org.ijsberg.iglu.util.misc; import org.ijsberg.iglu.util.io.FSFileCollection; import org.ijsberg.iglu.util.io.FileCollection; import org.ijsberg.iglu.util.io.FileFilterRuleSet; import org.ijsberg.iglu.util.io.FileSupport; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Properties; /** * Created by J Meetsma on 4-12-2015. */ public class SearchAndReplace { /* <xs:simpleType name="RijKarakteristiekOmschrijvingType"> <SUF>*/ private static Properties replacements = new Properties(); static { replacements.put("Trein","Ananas"); replacements.put("Prorail","Acme"); replacements.put("ProRail","AcMe"); replacements.put("Spoorweg", "Transportband"); replacements.put("Spoor", "Transport"); replacements.put("Goederen", "Transport"); replacements.put("Cargo", "Motion"); replacements.put("Eurocity", "Telstar"); replacements.put("Tgv", "Btw"); replacements.put("Thalys", "Aardbei"); replacements.put("Spoor", "Transport"); replacements.put("Wagen", "Krat"); replacements.put("Sprinter", "Colli"); replacements.put("Intercity", "Pallet"); replacements.put("Wissel", "Hefboom"); replacements.put("RijKarakteristiek", "Opname"); replacements.put("Reiziger", "Fruit"); replacements.put("Perron", "Steiger"); replacements.put("Baanvak", "Productielijn"); replacements.put("Kilometer", "Staffel"); replacements.put("Kilometrering", "Gradatie"); replacements.put("Dienst", "Weegschaal"); replacements.put("Ces_ovgs", "Xyz"); } private static final String BASE_DIR = "C:\\repository\\TibcoBW\\CES_OVGS_TreinNummerReeks_v1.0.2"; private static final String TARGET_DIR = "C:\\repository\\TibcoBW\\clean"; private static String[] originalNames; private static String[] destinationNames; private static void populateKeysAndValues(Properties properties) { ArrayList<String> keyList = new ArrayList<String>(); ArrayList<String> valueList = new ArrayList<String>(); for(String key : properties.stringPropertyNames()) { keyList.add(key); keyList.add(key.toLowerCase()); keyList.add(key.toUpperCase()); String value = properties.getProperty(key); valueList.add(value); valueList.add(value.toLowerCase()); valueList.add(value.toUpperCase()); } originalNames = keyList.toArray(new String[0]); destinationNames = valueList.toArray(new String[0]); } /* create new dir struct */ public static void main(String[] args) throws IOException{ populateKeysAndValues(replacements); File newDir = new File(TARGET_DIR); newDir.mkdirs(); FileSupport.emptyDirectory(newDir); FileCollection fileCollection = new FSFileCollection( BASE_DIR, new FileFilterRuleSet().setIncludeFilesWithNameMask("*.process|*.wsdl|*.xsd|*.substvar")); for(String fileName : fileCollection.getFileNames()) { String newFileName = StringSupport.replaceAll(fileName, originalNames, destinationNames); String fileContents = FileSupport.getTextFileFromFS(new File(BASE_DIR + "/" + fileName)); String newFileContents = StringSupport.replaceAll(fileContents, originalNames, destinationNames); FileSupport.saveTextFile(newFileContents, FileSupport.createFile(TARGET_DIR + "/" + newFileName)); } FileSupport.zip(newDir.listFiles()[0].getPath(), newDir.listFiles()[0].getPath() + ".zip", "*"); } }
193206_2
package com.example.myhealth; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.SharedPreferences; public class Data { private static JSONParser jParser = new JSONParser(); private static String dataURL = "http://10.0.2.2/myhealth/api"; private JSONObject json; private static List<NameValuePair> params = new ArrayList<NameValuePair>(); /* Alle mogelijke acties in de API */ private static final String ACTION_LOGIN = "login"; private static final String ACTION_DEL_MES = "measurement/delete"; //private static final String ACTION_UPLOAD_TEST = "uploadTest"; private static String ACTION_ADD_MES_BP = "bloodPressureMeasurement/add"; private static String ACTION_ADD_MES_PU = "pulseMeasurement/add"; private static String ACTION_ADD_MES_ECG = "ECGMeasurement/add"; private static String ACTION_GET_MES_BP = "bloodPressureMeasurement/"; private static String ACTION_GET_MES_PU = "pulseMeasurement/"; private static String ACTION_GET_MES_ECG = "ECGMeasurement/"; private static SharedPreferences pref; public Data(SharedPreferences pref) { this.pref = pref; } /** * @param action * Methode wordt uitgevoerd voor elke actie. Basis parameters worden meegegeven aan de API. */ public static void setParams() { params.clear(); params.add(new BasicNameValuePair("username", pref.getString("username", null))); params.add(new BasicNameValuePair("password", pref.getString("password", null))); } public static void setPrefs(SharedPreferences prefs) { pref = prefs; } /** * @param username * @param password * @return * @throws JSONException */ public static JSONObject actionLogin(String username, String password) throws JSONException { params.clear(); params.add(new BasicNameValuePair("username", username)); params.add(new BasicNameValuePair("password", password)); JSONObject json = jParser.makeHttpRequest(dataURL + "/" + ACTION_LOGIN, "GET", params); if (json != null) { System.out.println(json.getString("message")); } return json; } /** * @return * @throws JSONException */ public static ArrayList<JSONObject> actionGetMeasurementBloodPressure(String dateFrom, String dateTo) throws JSONException { setParams(); params.add(new BasicNameValuePair("dateFrom", dateFrom)); params.add(new BasicNameValuePair("dateTo", dateTo)); JSONObject json = jParser.makeHttpRequest(dataURL + "/" + ACTION_GET_MES_BP , "GET", params); return JSONArrayToArrayList(json.getJSONArray("measurements")); } /** * @return * @throws JSONException */ public static ArrayList<JSONObject> actionGetMeasurementPulse(String dateFrom, String dateTo) throws JSONException { setParams(); params.add(new BasicNameValuePair("dateFrom", dateFrom)); params.add(new BasicNameValuePair("dateTo", dateTo)); JSONObject json = jParser.makeHttpRequest(dataURL + "/" + ACTION_GET_MES_PU , "GET", params); return JSONArrayToArrayList(json.getJSONArray("measurements")); } /** * @return * @throws JSONException */ public static JSONObject actionGetMeasurementECG(int limit, int offset) throws JSONException { setParams(); params.add(new BasicNameValuePair("limit", Integer.toString(limit))); params.add(new BasicNameValuePair("offset", Integer.toString(offset))); return jParser.makeHttpRequest(dataURL + "/" + ACTION_GET_MES_ECG , "GET", params); } /** * @return * @throws JSONException */ public static JSONObject actionGetMeasurementECG(String dateFrom, String dateTo, int limit, int offset) throws JSONException { setParams(); params.add(new BasicNameValuePair("dateFrom", dateFrom)); params.add(new BasicNameValuePair("dateTo", dateTo)); params.add(new BasicNameValuePair("limit", Integer.toString(limit))); params.add(new BasicNameValuePair("offset", Integer.toString(offset))); return jParser.makeHttpRequest(dataURL + "/" + ACTION_GET_MES_ECG , "GET", params); } public static void actionAddMeasurementBloodPressure(String datetime, int low, int high) { setParams(); params.add(new BasicNameValuePair("datetime", datetime)); params.add(new BasicNameValuePair("low", low + "")); params.add(new BasicNameValuePair("high", high + "")); System.out.println(datetime + "--" + low + "--" + high); jParser.makeHttpRequest(dataURL + "/" + ACTION_ADD_MES_BP, "GET", params); } public static void actionAddMeasurementPulse(String datetime, int pulse) { setParams(); params.add(new BasicNameValuePair("datetime", datetime)); params.add(new BasicNameValuePair("value", pulse + "")); jParser.makeHttpRequest(dataURL + "/" + ACTION_ADD_MES_PU, "GET", params); } public static void actionAddMeasurementECG(String datetime, String data) { setParams(); params.add(new BasicNameValuePair("datetime", datetime)); params.add(new BasicNameValuePair("value", data + "")); jParser.makeHttpRequest(dataURL + "/" + ACTION_ADD_MES_ECG, "GET", params); } /** * @param lang */ public static void actionDeleteMeasurement(int id) { setParams(); params.add(new BasicNameValuePair("id", "" + id)); jParser.makeHttpRequest(dataURL + "/" + ACTION_DEL_MES, "GET", params); } /** * @return * @throws JSONException */ public static String actionUploadUrineTest() throws JSONException { setParams(); //JSONObject json = jParser.makeHttpRequest(dataURL, "GET", params); return null; } public static ArrayList<JSONObject> JSONArrayToArrayList(JSONArray array) throws JSONException { ArrayList<JSONObject> list = new ArrayList<JSONObject>(); for (int i=0; i<array.length(); i++) { list.add( array.getJSONObject(i) ); } return list; } }
Boonstra/4.1-MyHealth-APP
src/com/example/myhealth/Data.java
1,886
/** * @param action * Methode wordt uitgevoerd voor elke actie. Basis parameters worden meegegeven aan de API. */
block_comment
nl
package com.example.myhealth; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.SharedPreferences; public class Data { private static JSONParser jParser = new JSONParser(); private static String dataURL = "http://10.0.2.2/myhealth/api"; private JSONObject json; private static List<NameValuePair> params = new ArrayList<NameValuePair>(); /* Alle mogelijke acties in de API */ private static final String ACTION_LOGIN = "login"; private static final String ACTION_DEL_MES = "measurement/delete"; //private static final String ACTION_UPLOAD_TEST = "uploadTest"; private static String ACTION_ADD_MES_BP = "bloodPressureMeasurement/add"; private static String ACTION_ADD_MES_PU = "pulseMeasurement/add"; private static String ACTION_ADD_MES_ECG = "ECGMeasurement/add"; private static String ACTION_GET_MES_BP = "bloodPressureMeasurement/"; private static String ACTION_GET_MES_PU = "pulseMeasurement/"; private static String ACTION_GET_MES_ECG = "ECGMeasurement/"; private static SharedPreferences pref; public Data(SharedPreferences pref) { this.pref = pref; } /** * @param action <SUF>*/ public static void setParams() { params.clear(); params.add(new BasicNameValuePair("username", pref.getString("username", null))); params.add(new BasicNameValuePair("password", pref.getString("password", null))); } public static void setPrefs(SharedPreferences prefs) { pref = prefs; } /** * @param username * @param password * @return * @throws JSONException */ public static JSONObject actionLogin(String username, String password) throws JSONException { params.clear(); params.add(new BasicNameValuePair("username", username)); params.add(new BasicNameValuePair("password", password)); JSONObject json = jParser.makeHttpRequest(dataURL + "/" + ACTION_LOGIN, "GET", params); if (json != null) { System.out.println(json.getString("message")); } return json; } /** * @return * @throws JSONException */ public static ArrayList<JSONObject> actionGetMeasurementBloodPressure(String dateFrom, String dateTo) throws JSONException { setParams(); params.add(new BasicNameValuePair("dateFrom", dateFrom)); params.add(new BasicNameValuePair("dateTo", dateTo)); JSONObject json = jParser.makeHttpRequest(dataURL + "/" + ACTION_GET_MES_BP , "GET", params); return JSONArrayToArrayList(json.getJSONArray("measurements")); } /** * @return * @throws JSONException */ public static ArrayList<JSONObject> actionGetMeasurementPulse(String dateFrom, String dateTo) throws JSONException { setParams(); params.add(new BasicNameValuePair("dateFrom", dateFrom)); params.add(new BasicNameValuePair("dateTo", dateTo)); JSONObject json = jParser.makeHttpRequest(dataURL + "/" + ACTION_GET_MES_PU , "GET", params); return JSONArrayToArrayList(json.getJSONArray("measurements")); } /** * @return * @throws JSONException */ public static JSONObject actionGetMeasurementECG(int limit, int offset) throws JSONException { setParams(); params.add(new BasicNameValuePair("limit", Integer.toString(limit))); params.add(new BasicNameValuePair("offset", Integer.toString(offset))); return jParser.makeHttpRequest(dataURL + "/" + ACTION_GET_MES_ECG , "GET", params); } /** * @return * @throws JSONException */ public static JSONObject actionGetMeasurementECG(String dateFrom, String dateTo, int limit, int offset) throws JSONException { setParams(); params.add(new BasicNameValuePair("dateFrom", dateFrom)); params.add(new BasicNameValuePair("dateTo", dateTo)); params.add(new BasicNameValuePair("limit", Integer.toString(limit))); params.add(new BasicNameValuePair("offset", Integer.toString(offset))); return jParser.makeHttpRequest(dataURL + "/" + ACTION_GET_MES_ECG , "GET", params); } public static void actionAddMeasurementBloodPressure(String datetime, int low, int high) { setParams(); params.add(new BasicNameValuePair("datetime", datetime)); params.add(new BasicNameValuePair("low", low + "")); params.add(new BasicNameValuePair("high", high + "")); System.out.println(datetime + "--" + low + "--" + high); jParser.makeHttpRequest(dataURL + "/" + ACTION_ADD_MES_BP, "GET", params); } public static void actionAddMeasurementPulse(String datetime, int pulse) { setParams(); params.add(new BasicNameValuePair("datetime", datetime)); params.add(new BasicNameValuePair("value", pulse + "")); jParser.makeHttpRequest(dataURL + "/" + ACTION_ADD_MES_PU, "GET", params); } public static void actionAddMeasurementECG(String datetime, String data) { setParams(); params.add(new BasicNameValuePair("datetime", datetime)); params.add(new BasicNameValuePair("value", data + "")); jParser.makeHttpRequest(dataURL + "/" + ACTION_ADD_MES_ECG, "GET", params); } /** * @param lang */ public static void actionDeleteMeasurement(int id) { setParams(); params.add(new BasicNameValuePair("id", "" + id)); jParser.makeHttpRequest(dataURL + "/" + ACTION_DEL_MES, "GET", params); } /** * @return * @throws JSONException */ public static String actionUploadUrineTest() throws JSONException { setParams(); //JSONObject json = jParser.makeHttpRequest(dataURL, "GET", params); return null; } public static ArrayList<JSONObject> JSONArrayToArrayList(JSONArray array) throws JSONException { ArrayList<JSONObject> list = new ArrayList<JSONObject>(); for (int i=0; i<array.length(); i++) { list.add( array.getJSONObject(i) ); } return list; } }
4395_1
package io.Buttons; import game.enemies.Enemy; /** * Created by sander on 14-11-2017. */ public class Button1 extends Button { public Button1(){ PinNumber = 6; } @Override public void effect() { setGame(); //de game moet geset worden zodat deze functie toegang heeft tot de huidige arrays van alles. enemies = game.GetEnemies(); for (Enemy e: enemies) { e.damage(100000); } game.SetEnemies(enemies); game.AddGold(100000); } }
Borf/TowerDefence
src/io/Buttons/Button1.java
169
//de game moet geset worden zodat deze functie toegang heeft tot de huidige arrays van alles.
line_comment
nl
package io.Buttons; import game.enemies.Enemy; /** * Created by sander on 14-11-2017. */ public class Button1 extends Button { public Button1(){ PinNumber = 6; } @Override public void effect() { setGame(); //de game<SUF> enemies = game.GetEnemies(); for (Enemy e: enemies) { e.damage(100000); } game.SetEnemies(enemies); game.AddGold(100000); } }
28778_4
import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; import java.util.HashSet; /** * Een klasse om klanteninformatie te lezen uit een csv bestand * DE klantenfile bevat naaminfromatie, adresinformatie en contactinformatie * van 88 klanten verspreid over de wereld. * <p> * Het bestand bevat volgende informatie * CustomerID CompanyName ContactName ContactTitle Address City Region PostalCode Country Phone Fax * Informatie van 1 klant bevindt zich op 1 lijn en wordt gescheiden door ; * * @author Marc De Caluwé * @version 2019-12-01 */ public class ContactReader { private String format; private ArrayList<ContactEntry> entries; public ContactReader() { this("contacts.csv"); } public ContactReader(String filename) { // The format for the data. format = "CustomerID;Namelient;NameContact;TitleContact;Addresd;City;Region;ZIP;Country;Phone;Fax"; // Where to store the data. entries = new ArrayList<>(); // Attempt to read the complete set of data from file. try { File pFile = new File(""); File klantFile = new File(pFile.getAbsolutePath() + "/data/" + filename); Scanner klantfile = new Scanner(klantFile); // Lees het klantenbestand tot de laatste lijn while (klantfile.hasNextLine()) { String klantlijn = klantfile.nextLine(); // Splits de klant en maak er een nieuw Klant-object van ContactEntry entry = new ContactEntry(klantlijn); entries.add(entry); } klantfile.close(); } catch (FileNotFoundException e) { System.out.println("Er dook een probleem op: " + e.getMessage()); } } public ArrayList<ContactEntry> getEntries() { return entries; } /** * Print de data. */ public void printData() { for (ContactEntry entry : entries) { System.out.println(entry); } } public HashSet<Contact> loadContacts() { HashSet<Contact> klanten = new HashSet<>(); for(ContactEntry ke : getEntries()) { String[] data = ke.getData(); Contact k = new Contact(data[ContactEntry.ID]); k.setName(data[ContactEntry.NAMECONTACT]); k.setTitle(data[ContactEntry.TITLECONTACT]); k.setCity(data[ContactEntry.CITY]); k.setRegion(data[ContactEntry.REGION]); k.setCountry(data[ContactEntry.COUNTRY]); klanten.add(k); } return klanten; } public static void main(String[] args) { try { ContactReader kr = new ContactReader(); kr.printData(); System.out.println("---------------------------------------------------------------"); for (ContactEntry ke : kr.getEntries()) { String[] data = ke.getData(); // we drukken het ID en bijhorende naam van elke klant System.out.println("ID=" + data[ContactEntry.ID] + ", name=" + data[ContactEntry.NAMECLIENT]); } } catch (Exception e) { e.printStackTrace(); } } }
Boutoku/OOP-test-repository
oefeningen/src/ContactReader.java
956
// Lees het klantenbestand tot de laatste lijn
line_comment
nl
import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; import java.util.HashSet; /** * Een klasse om klanteninformatie te lezen uit een csv bestand * DE klantenfile bevat naaminfromatie, adresinformatie en contactinformatie * van 88 klanten verspreid over de wereld. * <p> * Het bestand bevat volgende informatie * CustomerID CompanyName ContactName ContactTitle Address City Region PostalCode Country Phone Fax * Informatie van 1 klant bevindt zich op 1 lijn en wordt gescheiden door ; * * @author Marc De Caluwé * @version 2019-12-01 */ public class ContactReader { private String format; private ArrayList<ContactEntry> entries; public ContactReader() { this("contacts.csv"); } public ContactReader(String filename) { // The format for the data. format = "CustomerID;Namelient;NameContact;TitleContact;Addresd;City;Region;ZIP;Country;Phone;Fax"; // Where to store the data. entries = new ArrayList<>(); // Attempt to read the complete set of data from file. try { File pFile = new File(""); File klantFile = new File(pFile.getAbsolutePath() + "/data/" + filename); Scanner klantfile = new Scanner(klantFile); // Lees het<SUF> while (klantfile.hasNextLine()) { String klantlijn = klantfile.nextLine(); // Splits de klant en maak er een nieuw Klant-object van ContactEntry entry = new ContactEntry(klantlijn); entries.add(entry); } klantfile.close(); } catch (FileNotFoundException e) { System.out.println("Er dook een probleem op: " + e.getMessage()); } } public ArrayList<ContactEntry> getEntries() { return entries; } /** * Print de data. */ public void printData() { for (ContactEntry entry : entries) { System.out.println(entry); } } public HashSet<Contact> loadContacts() { HashSet<Contact> klanten = new HashSet<>(); for(ContactEntry ke : getEntries()) { String[] data = ke.getData(); Contact k = new Contact(data[ContactEntry.ID]); k.setName(data[ContactEntry.NAMECONTACT]); k.setTitle(data[ContactEntry.TITLECONTACT]); k.setCity(data[ContactEntry.CITY]); k.setRegion(data[ContactEntry.REGION]); k.setCountry(data[ContactEntry.COUNTRY]); klanten.add(k); } return klanten; } public static void main(String[] args) { try { ContactReader kr = new ContactReader(); kr.printData(); System.out.println("---------------------------------------------------------------"); for (ContactEntry ke : kr.getEntries()) { String[] data = ke.getData(); // we drukken het ID en bijhorende naam van elke klant System.out.println("ID=" + data[ContactEntry.ID] + ", name=" + data[ContactEntry.NAMECLIENT]); } } catch (Exception e) { e.printStackTrace(); } } }
43497_19
package com.example.miraclepack; import android.Manifest; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Binder; import android.os.Build; import android.os.IBinder; import android.util.Log; import androidx.annotation.Nullable; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import androidx.core.content.ContextCompat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Locale; import java.util.Timer; import java.util.TimerTask; public class AppService extends Service implements LocationListener { private static final int NOTIFICATION_ID = 1; private static final String NOTIFICATION_CHANNEL_ID = "channel_id"; private static final float GEOFENCE_RADIUS = 75; private final MyBinder myBinder = new MyBinder(); private LocationManager locationManager; private List<Geofence> geofenceList; private MyDatabaseHelper myDB; private List<Compartment> usedCompartments; private ArrayList<Compartment> matchingCompartments; private Configuration selectedWeekday; private boolean isInList = false; private BluetoothConnection bluetooth; @Override public void onCreate() { super.onCreate(); bluetooth = new BluetoothConnection(); locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); myDB = MyDatabaseHelper.getInstance(this); geofenceList = myDB.getAllGeofences(); usedCompartments = myDB.getUsedCompartmentsOfCurrentDay(); Log.d("AppServiceMessage", "Service is gestart"); setToday(); // Initialise timer and task Timer dataUpdateTimer = new Timer(); TimerTask dataUpdateTask = new TimerTask() { @Override public void run() { changeBagStatus(); } }; // Execute method every 10 seconds long updateInterval = 5 * 1000 ; // 5 seconds dataUpdateTimer.schedule(dataUpdateTask, updateInterval, updateInterval); } // Starting foreground service and background location @Override public int onStartCommand(Intent intent, int flags, int startId) { startForeground(NOTIFICATION_ID, createNotification()); startLocationUpdates(); return START_STICKY; } // Kill service if app is closed in task manager @Override public void onTaskRemoved(Intent rootIntent) { super.onTaskRemoved(rootIntent); stopSelf(); // Stop the service when the app is removed from the recent tasks locationManager.removeUpdates(this); // Stop location updates } @Override public void onDestroy() { super.onDestroy(); locationManager.removeUpdates(this); } // Ensuring service does not support binding so that other components can't bind to the service @Nullable @Override public IBinder onBind(Intent intent) { return myBinder; } // Check if current location has changed in order to check for geofence @Override public void onLocationChanged(Location location) { checkGeofences(location); } public MyBinder getMyBinder() { return myBinder; } public LocationManager getLocationManager() { return locationManager; } public void setLocationManager(LocationManager locationManager) { this.locationManager = locationManager; } public List<Geofence> getGeofenceList() { return geofenceList; } public void setGeofenceList(List<Geofence> geofenceList) { this.geofenceList = geofenceList; } public MyDatabaseHelper getMyDB() { return myDB; } public void setMyDB(MyDatabaseHelper myDB) { this.myDB = myDB; } public List<Compartment> getUsedCompartments() { return usedCompartments; } public void setUsedCompartments(List<Compartment> usedCompartments) { this.usedCompartments = usedCompartments; } public ArrayList<Compartment> getMatchingCompartments() { return matchingCompartments; } public Configuration getSelectedWeekday() { return selectedWeekday; } public void setSelectedWeekday(Configuration selectedWeekday) { this.selectedWeekday = selectedWeekday; } public BluetoothConnection getBluetooth() { return bluetooth; } public void setBluetooth(BluetoothConnection bluetooth) { this.bluetooth = bluetooth; } //Sets the selectedWeekday to today. private void setToday() { List<Configuration> weekDays = myDB.fillConfigurations(myDB.getConfiguration()); Calendar today = Calendar.getInstance(); String day = today.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault()); for (Configuration configuration : weekDays) { if (configuration.getWeekday().equals(day)) { this.selectedWeekday = configuration; setSelectedWeekday(this.selectedWeekday); } } } //Retrieves the filled compartments from the bluetooth device. public void changeBagStatus() { matchingCompartments = this.getBluetooth().getCompartmentDataFromBluetoothDevice(); } private void startLocationUpdates() { if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { try { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 0f, this); } catch (SecurityException e) { e.printStackTrace(); } } } // Check if currently inside or outside geofence and if something inside bag is missing private void checkGeofences(Location currentLocation) { for (Geofence geofence : geofenceList) { float distance = currentLocation.distanceTo(geofence.getLocation()); if (distance > GEOFENCE_RADIUS && !isLocationInsideGeofence(currentLocation, geofence) && isContentInsideBag()) { showNotification(); } break; } } // Extra check if inside geofence in case there are multiple geofences private boolean isLocationInsideGeofence(Location location, Geofence geofence) { float[] results = new float[1]; Location.distanceBetween( location.getLatitude(), location.getLongitude(), geofence.getLatitude(), geofence.getLongitude(), results); float distanceInMeters = results[0]; return distanceInMeters <= GEOFENCE_RADIUS; } // Check if all content is inside bag according to configuration private boolean isContentInsideBag() { // The configuration items get updated, with if they are correctly filled. ArrayList<ConfigurationItem> configurationItems = compareCompartmentsAndConfigurations(selectedWeekday); boolean contentMissing = false; for (ConfigurationItem configurationItem : configurationItems) { if (!configurationItem.isStatus()) { contentMissing = true; break; } } return contentMissing; } //Checks if the compartments are filled correctly and sets their filled status to true. public ArrayList<ConfigurationItem> compareCompartmentsAndConfigurations(Configuration configuration) { this.changeBagStatus(); ArrayList<ConfigurationItem> configItemList = new ArrayList<>(); configItemList = myDB.fillConfigItems(myDB.getConfigItems(configuration)); for (ConfigurationItem configurationItem : configItemList) { this.isInList = false; int counter = 1; for (Compartment compartment : matchingCompartments) { if (isCompartmentCorrectlyFilled(compartment.getCompartmentId(), configurationItem.getCompartment().getCompartmentId(), configurationItem.getName(), counter, matchingCompartments.size())) { configurationItem.setStatus(true); break; } counter++; } } return configItemList; } //Checks if the compartment is filled when it should be filled, or left empty when it should be empty. //It does this according to the configuration. public boolean isCompartmentCorrectlyFilled(int compartmentID, int configurationCompartmentID, String configurationItemName, int counter, int listLength) { if (compartmentID == configurationCompartmentID) { this.isInList = true; if (!configurationItemName.equals("Leeg")) { return true; } } return !isInList && counter >= listLength && configurationItemName.equals("Leeg"); } private void showNotification() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NOTIFICATION_POLICY) == PackageManager.PERMISSION_GRANTED) { try { Intent intent = new Intent(this, MainActivity.class); intent.putExtra("fragment", "bag"); // Stel het doelfragment in als "bag" PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE); // Voeg de FLAG_IMMUTABLE-vlag toe NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID) .setSmallIcon(R.drawable.baseline_notifications_24) .setContentTitle("Waarschuwing!") .setContentText("Je bent mogelijk iets vergeten. Tik om het overzicht van de tas te bekijken!") .setPriority(NotificationCompat.PRIORITY_HIGH) .setContentIntent(pendingIntent) // Stel de intent in als de klikintentie .setAutoCancel(true); // Sluit de notificatie nadat erop is geklikt NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); notificationManager.notify(NOTIFICATION_ID, builder.build()); } catch (SecurityException e) { e.printStackTrace(); } } } // Creating and building notification and channel private Notification createNotification() { createNotificationChannel(); NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID) .setSmallIcon(R.drawable.baseline_notifications_24) .setContentTitle("MiraclePack") .setContentText("MiraclePack draait momenteel op de achtergrond...") .setPriority(NotificationCompat.PRIORITY_LOW); return builder.build(); } private void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence name = "MiraclePack Channel"; String description = "Channel for MiraclePack Notifications"; int importance = NotificationManager.IMPORTANCE_LOW; NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, name, importance); channel.setDescription(description); NotificationManager notificationManager = getSystemService(NotificationManager.class); if (notificationManager != null) { notificationManager.createNotificationChannel(channel); } } } public class MyBinder extends Binder { AppService getService() { return AppService.this; } } }
BramVeninga/project-innovate-IC-INF-1A
MiraclePack/app/src/main/java/com/example/miraclepack/AppService.java
3,162
// Stel de intent in als de klikintentie
line_comment
nl
package com.example.miraclepack; import android.Manifest; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Binder; import android.os.Build; import android.os.IBinder; import android.util.Log; import androidx.annotation.Nullable; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import androidx.core.content.ContextCompat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Locale; import java.util.Timer; import java.util.TimerTask; public class AppService extends Service implements LocationListener { private static final int NOTIFICATION_ID = 1; private static final String NOTIFICATION_CHANNEL_ID = "channel_id"; private static final float GEOFENCE_RADIUS = 75; private final MyBinder myBinder = new MyBinder(); private LocationManager locationManager; private List<Geofence> geofenceList; private MyDatabaseHelper myDB; private List<Compartment> usedCompartments; private ArrayList<Compartment> matchingCompartments; private Configuration selectedWeekday; private boolean isInList = false; private BluetoothConnection bluetooth; @Override public void onCreate() { super.onCreate(); bluetooth = new BluetoothConnection(); locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); myDB = MyDatabaseHelper.getInstance(this); geofenceList = myDB.getAllGeofences(); usedCompartments = myDB.getUsedCompartmentsOfCurrentDay(); Log.d("AppServiceMessage", "Service is gestart"); setToday(); // Initialise timer and task Timer dataUpdateTimer = new Timer(); TimerTask dataUpdateTask = new TimerTask() { @Override public void run() { changeBagStatus(); } }; // Execute method every 10 seconds long updateInterval = 5 * 1000 ; // 5 seconds dataUpdateTimer.schedule(dataUpdateTask, updateInterval, updateInterval); } // Starting foreground service and background location @Override public int onStartCommand(Intent intent, int flags, int startId) { startForeground(NOTIFICATION_ID, createNotification()); startLocationUpdates(); return START_STICKY; } // Kill service if app is closed in task manager @Override public void onTaskRemoved(Intent rootIntent) { super.onTaskRemoved(rootIntent); stopSelf(); // Stop the service when the app is removed from the recent tasks locationManager.removeUpdates(this); // Stop location updates } @Override public void onDestroy() { super.onDestroy(); locationManager.removeUpdates(this); } // Ensuring service does not support binding so that other components can't bind to the service @Nullable @Override public IBinder onBind(Intent intent) { return myBinder; } // Check if current location has changed in order to check for geofence @Override public void onLocationChanged(Location location) { checkGeofences(location); } public MyBinder getMyBinder() { return myBinder; } public LocationManager getLocationManager() { return locationManager; } public void setLocationManager(LocationManager locationManager) { this.locationManager = locationManager; } public List<Geofence> getGeofenceList() { return geofenceList; } public void setGeofenceList(List<Geofence> geofenceList) { this.geofenceList = geofenceList; } public MyDatabaseHelper getMyDB() { return myDB; } public void setMyDB(MyDatabaseHelper myDB) { this.myDB = myDB; } public List<Compartment> getUsedCompartments() { return usedCompartments; } public void setUsedCompartments(List<Compartment> usedCompartments) { this.usedCompartments = usedCompartments; } public ArrayList<Compartment> getMatchingCompartments() { return matchingCompartments; } public Configuration getSelectedWeekday() { return selectedWeekday; } public void setSelectedWeekday(Configuration selectedWeekday) { this.selectedWeekday = selectedWeekday; } public BluetoothConnection getBluetooth() { return bluetooth; } public void setBluetooth(BluetoothConnection bluetooth) { this.bluetooth = bluetooth; } //Sets the selectedWeekday to today. private void setToday() { List<Configuration> weekDays = myDB.fillConfigurations(myDB.getConfiguration()); Calendar today = Calendar.getInstance(); String day = today.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault()); for (Configuration configuration : weekDays) { if (configuration.getWeekday().equals(day)) { this.selectedWeekday = configuration; setSelectedWeekday(this.selectedWeekday); } } } //Retrieves the filled compartments from the bluetooth device. public void changeBagStatus() { matchingCompartments = this.getBluetooth().getCompartmentDataFromBluetoothDevice(); } private void startLocationUpdates() { if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { try { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 0f, this); } catch (SecurityException e) { e.printStackTrace(); } } } // Check if currently inside or outside geofence and if something inside bag is missing private void checkGeofences(Location currentLocation) { for (Geofence geofence : geofenceList) { float distance = currentLocation.distanceTo(geofence.getLocation()); if (distance > GEOFENCE_RADIUS && !isLocationInsideGeofence(currentLocation, geofence) && isContentInsideBag()) { showNotification(); } break; } } // Extra check if inside geofence in case there are multiple geofences private boolean isLocationInsideGeofence(Location location, Geofence geofence) { float[] results = new float[1]; Location.distanceBetween( location.getLatitude(), location.getLongitude(), geofence.getLatitude(), geofence.getLongitude(), results); float distanceInMeters = results[0]; return distanceInMeters <= GEOFENCE_RADIUS; } // Check if all content is inside bag according to configuration private boolean isContentInsideBag() { // The configuration items get updated, with if they are correctly filled. ArrayList<ConfigurationItem> configurationItems = compareCompartmentsAndConfigurations(selectedWeekday); boolean contentMissing = false; for (ConfigurationItem configurationItem : configurationItems) { if (!configurationItem.isStatus()) { contentMissing = true; break; } } return contentMissing; } //Checks if the compartments are filled correctly and sets their filled status to true. public ArrayList<ConfigurationItem> compareCompartmentsAndConfigurations(Configuration configuration) { this.changeBagStatus(); ArrayList<ConfigurationItem> configItemList = new ArrayList<>(); configItemList = myDB.fillConfigItems(myDB.getConfigItems(configuration)); for (ConfigurationItem configurationItem : configItemList) { this.isInList = false; int counter = 1; for (Compartment compartment : matchingCompartments) { if (isCompartmentCorrectlyFilled(compartment.getCompartmentId(), configurationItem.getCompartment().getCompartmentId(), configurationItem.getName(), counter, matchingCompartments.size())) { configurationItem.setStatus(true); break; } counter++; } } return configItemList; } //Checks if the compartment is filled when it should be filled, or left empty when it should be empty. //It does this according to the configuration. public boolean isCompartmentCorrectlyFilled(int compartmentID, int configurationCompartmentID, String configurationItemName, int counter, int listLength) { if (compartmentID == configurationCompartmentID) { this.isInList = true; if (!configurationItemName.equals("Leeg")) { return true; } } return !isInList && counter >= listLength && configurationItemName.equals("Leeg"); } private void showNotification() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NOTIFICATION_POLICY) == PackageManager.PERMISSION_GRANTED) { try { Intent intent = new Intent(this, MainActivity.class); intent.putExtra("fragment", "bag"); // Stel het doelfragment in als "bag" PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE); // Voeg de FLAG_IMMUTABLE-vlag toe NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID) .setSmallIcon(R.drawable.baseline_notifications_24) .setContentTitle("Waarschuwing!") .setContentText("Je bent mogelijk iets vergeten. Tik om het overzicht van de tas te bekijken!") .setPriority(NotificationCompat.PRIORITY_HIGH) .setContentIntent(pendingIntent) // Stel de<SUF> .setAutoCancel(true); // Sluit de notificatie nadat erop is geklikt NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); notificationManager.notify(NOTIFICATION_ID, builder.build()); } catch (SecurityException e) { e.printStackTrace(); } } } // Creating and building notification and channel private Notification createNotification() { createNotificationChannel(); NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID) .setSmallIcon(R.drawable.baseline_notifications_24) .setContentTitle("MiraclePack") .setContentText("MiraclePack draait momenteel op de achtergrond...") .setPriority(NotificationCompat.PRIORITY_LOW); return builder.build(); } private void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence name = "MiraclePack Channel"; String description = "Channel for MiraclePack Notifications"; int importance = NotificationManager.IMPORTANCE_LOW; NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, name, importance); channel.setDescription(description); NotificationManager notificationManager = getSystemService(NotificationManager.class); if (notificationManager != null) { notificationManager.createNotificationChannel(channel); } } } public class MyBinder extends Binder { AppService getService() { return AppService.this; } } }
79343_21
package ap.edu.darm.androidassignment; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.pm.PackageManager; import android.graphics.drawable.Drawable; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Build; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v4.content.res.ResourcesCompat; import android.util.Log; import android.view.MotionEvent; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.osmdroid.DefaultResourceProxyImpl; import org.osmdroid.tileprovider.tilesource.TileSourceFactory; import org.osmdroid.util.GeoPoint; import org.osmdroid.views.MapView; import org.osmdroid.views.Projection; import org.osmdroid.views.overlay.ItemizedIconOverlay; import org.osmdroid.views.overlay.OverlayItem; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MainActivity extends Activity { private TextView searchField; private Button searchButton; private MapView mapView; private LocationManager locationManager; private LocationListener locationListener; private RequestQueue mRequestQueue; private String urlSearch = "http://nominatim.openstreetmap.org/search?q="; private String urlLibs = "http://datasets.antwerpen.be/v4/gis/bibliotheekoverzicht.json"; private JSONObject libs; final ArrayList<OverlayItem> items = new ArrayList<OverlayItem>(); //DB MySQLLiteHelper msqlite; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (Build.VERSION.SDK_INT >= 23) { checkPermissions(); } msqlite = new MySQLLiteHelper(this); // https://github.com/osmdroid/osmdroid/wiki/How-to-use-the-osmdroid-library mapView = (MapView) findViewById(R.id.mapview); mapView.setTileSource(TileSourceFactory.MAPNIK); mapView.setBuiltInZoomControls(true); mapView.setMultiTouchControls(true); mapView.getController().setZoom(14); // http://code.tutsplus.com/tutorials/an-introduction-to-volley--cms-23800 mRequestQueue = Volley.newRequestQueue(this); searchField = (TextView) findViewById(R.id.lib_name); //----------------------------------------------------------------------------------------------------------------------------------------------- try { ArrayList<Double[]> allLibs = msqlite.getAllLibs(); //IF there's content inside the db if(allLibs.size() > 0) { for(int i = 0; i < allLibs.size(); i++) { GeoPoint g = new GeoPoint(allLibs.get(i)[0], allLibs.get(i)[1]); addMarker(g); } //If there's no content inside the db } else { // A JSONObject to post with the request. Null is allowed and indicates no parameters will be posted along with request. JSONObject obj = null; // haal alle libs op JsonObjectRequest jr = new JsonObjectRequest(Request.Method.GET, urlLibs, obj, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { hideSoftKeyBoard(); libs = response; handleJSONResponse(response); //Log.d("edu.ap.maps", libs.toString()); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("be.ap.edu.mapsaver", error.getMessage()); } }); mRequestQueue.add(jr); } } catch (Exception ex) { Log.e("Ripper", ex.getMessage()); } locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { Toast.makeText(getApplicationContext(), "GPS not enabled!", Toast.LENGTH_SHORT).show(); } else { locationListener = new MyLocationListener(); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener); } // default = meistraat mapView.getController().setCenter(new GeoPoint(51.2244, 4.38566)); } // http://codetheory.in/android-ontouchevent-ontouchlistener-motionevent-to-detect-common-gestures/ @Override public boolean dispatchTouchEvent(MotionEvent ev) { int actionType = ev.getAction(); switch(actionType) { case MotionEvent.ACTION_UP: // A Projection serves to translate between the coordinate system of // x/y on-screen pixel coordinates and that of latitude/longitude points // on the surface of the earth. You obtain a Projection from MapView.getProjection(). // You should not hold on to this object for more than one draw, since the projection of the map could change. Projection proj = this.mapView.getProjection(); GeoPoint loc = (GeoPoint)proj.fromPixels((int)ev.getX(), (int)ev.getY() - (searchField.getHeight() * 2)); //Log.d("edu.ap.maps", "Clicked"); findZone(loc); } return super.dispatchTouchEvent(ev); } private void hideSoftKeyBoard() { InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); if(imm.isAcceptingText()) { // verify if the soft keyboard is open imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); } } // http://alienryderflex.com/polygon/ // The basic idea is to find all edges of the polygon that span the 'x' position of the point you're testing against. // Then you find how many of them intersect the vertical line that extends above your point. If an even number cross above the point, // then you're outside the polygon. If an odd number cross above, then you're inside. private boolean contains(GeoPoint location, ArrayList<GeoPoint> polyLoc) { if(location==null) return false; if(polyLoc.size() == 0) return false; GeoPoint lastPoint = polyLoc.get(polyLoc.size()-1); boolean isInside = false; double x = location.getLongitude(); for(GeoPoint point: polyLoc) { double x1 = lastPoint.getLongitude(); double x2 = point.getLongitude(); double dx = x2 - x1; if (Math.abs(dx) > 180.0) { // we have, most likely, just jumped the dateline // (could do further validation to this effect if needed). // normalise the numbers. if (x > 0) { while (x1 < 0) x1 += 360; while (x2 < 0) x2 += 360; } else { while (x1 > 0) x1 -= 360; while (x2 > 0) x2 -= 360; } dx = x2 - x1; } if ((x1 <= x && x2 > x) || (x1 >= x && x2 < x)) { double grad = (point.getLatitude() - lastPoint.getLatitude()) / dx; double intersectAtLat = lastPoint.getLatitude() + ((x - x1) * grad); if (intersectAtLat > location.getLatitude()) isInside = !isInside; } lastPoint = point; } return isInside; } private void findZone(GeoPoint clickPoint) { try { JSONArray allLibs = libs.getJSONArray("data"); //Log.d("edu.ap.maps", String.valueOf(allLibs.length())); for(int i = 0; i < allLibs.length(); i++) { JSONObject obj = (JSONObject)allLibs.get(i); String tariefzone = ""; //obj.getString("tariefzone"); String tariefkleur = ""; //obj.getString("tariefkleur"); ArrayList<GeoPoint> list = new ArrayList<GeoPoint>(); JSONObject geometry = new JSONObject(obj.getString("geometry")); JSONArray coordinates = geometry.getJSONArray("coordinates"); // blijkbaar nog eens verpakt... JSONArray coordinatesInside = coordinates.getJSONArray(0); for(int j = 0; j < coordinatesInside.length(); j++) { JSONArray points = null; try { points = coordinatesInside.getJSONArray(j); GeoPoint g = new GeoPoint(points.getDouble(1), points.getDouble(0)); list.add(g); } catch(JSONException ex) { Log.e("be.ap.edu.mapsaver", ex.getMessage()); } } if(contains(clickPoint, list)) { this.addMarker(clickPoint); //Toast.makeText(this, "Tariefzone : " + tariefzone + " Tariefkleur : " + tariefkleur, Toast.LENGTH_SHORT).show(); break; } } } catch (Exception e) { Log.e("edu.ap.maps", e.getMessage()); Log.e("edu.ap.maps", String.valueOf(e.getStackTrace())); } } private void addMarker(GeoPoint g) { OverlayItem myLocationOverlayItem = new OverlayItem("Here", "Current Position", g); Drawable myCurrentLocationMarker = ResourcesCompat.getDrawable(getResources(), R.drawable.marker_default, null); myLocationOverlayItem.setMarker(myCurrentLocationMarker); items.add(myLocationOverlayItem); DefaultResourceProxyImpl resourceProxy = new DefaultResourceProxyImpl(getApplicationContext()); ItemizedIconOverlay<OverlayItem> currentLocationOverlay = new ItemizedIconOverlay<OverlayItem>(items, new ItemizedIconOverlay.OnItemGestureListener<OverlayItem>() { public boolean onItemSingleTapUp(final int index, final OverlayItem item) { return true; } public boolean onItemLongPress(final int index, final OverlayItem item) { return true; } }, resourceProxy); this.mapView.getOverlays().add(currentLocationOverlay); this.mapView.invalidate(); } private class MyLocationListener implements LocationListener { @Override public void onLocationChanged(Location loc) { mapView.getController().setCenter(new GeoPoint(loc.getLatitude(), loc.getLongitude())); } @Override public void onProviderDisabled(String provider) {} @Override public void onProviderEnabled(String provider) {} @Override public void onStatusChanged(String provider, int status, Bundle extras) {} } // START PERMISSION CHECK final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124; private void checkPermissions() { List<String> permissions = new ArrayList<>(); String message = "osmdroid permissions:"; if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { permissions.add(Manifest.permission.ACCESS_FINE_LOCATION); message += "\nLocation to show user location."; } if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); message += "\nStorage access to store map tiles."; } if(!permissions.isEmpty()) { Toast.makeText(this, message, Toast.LENGTH_LONG).show(); String[] params = permissions.toArray(new String[permissions.size()]); requestPermissions(params, REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS); } // else: We already have permissions, so handle as normal } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS: { Map<String, Integer> perms = new HashMap<>(); // Initial perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED); perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED); // Fill with results for (int i = 0; i < permissions.length; i++) perms.put(permissions[i], grantResults[i]); // Check for ACCESS_FINE_LOCATION and WRITE_EXTERNAL_STORAGE Boolean location = perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED; Boolean storage = perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED; if(location && storage) { // All Permissions Granted Toast.makeText(MainActivity.this, "All permissions granted", Toast.LENGTH_SHORT).show(); } else if (location) { Toast.makeText(this, "Storage permission is required to store map tiles to reduce data usage and for offline usage.", Toast.LENGTH_LONG).show(); } else if (storage) { Toast.makeText(this, "Location permission is required to show the user's location on map.", Toast.LENGTH_LONG).show(); } else { // !location && !storage case // Permission Denied Toast.makeText(MainActivity.this, "Storage permission is required to store map tiles to reduce data usage and for offline usage." + "\nLocation permission is required to show the user's location on map.", Toast.LENGTH_SHORT).show(); } } break; default: super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } private void handleJSONResponse(JSONObject object) { try { JSONArray data = object.getJSONArray("data"); for(int i = 0 ; i < data.length(); i++) { JSONObject obj = data.getJSONObject(i); GeoPoint g = new GeoPoint(obj.getDouble("point_lat"), obj.getDouble("point_lng")); addMarker(g); //Add to db msqlite.addLib(obj.getString("naam"), obj.getDouble("point_lat"), obj.getDouble("point_lng")); } } catch (Exception ex) { Log.e("pipi", ex.getMessage()); } } // END PERMISSION CHECK }
BramVer/Exam_AndroidApp
AndroidAssignment/app/src/main/java/ap/edu/darm/androidassignment/MainActivity.java
4,546
// blijkbaar nog eens verpakt...
line_comment
nl
package ap.edu.darm.androidassignment; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.pm.PackageManager; import android.graphics.drawable.Drawable; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Build; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v4.content.res.ResourcesCompat; import android.util.Log; import android.view.MotionEvent; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.osmdroid.DefaultResourceProxyImpl; import org.osmdroid.tileprovider.tilesource.TileSourceFactory; import org.osmdroid.util.GeoPoint; import org.osmdroid.views.MapView; import org.osmdroid.views.Projection; import org.osmdroid.views.overlay.ItemizedIconOverlay; import org.osmdroid.views.overlay.OverlayItem; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MainActivity extends Activity { private TextView searchField; private Button searchButton; private MapView mapView; private LocationManager locationManager; private LocationListener locationListener; private RequestQueue mRequestQueue; private String urlSearch = "http://nominatim.openstreetmap.org/search?q="; private String urlLibs = "http://datasets.antwerpen.be/v4/gis/bibliotheekoverzicht.json"; private JSONObject libs; final ArrayList<OverlayItem> items = new ArrayList<OverlayItem>(); //DB MySQLLiteHelper msqlite; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (Build.VERSION.SDK_INT >= 23) { checkPermissions(); } msqlite = new MySQLLiteHelper(this); // https://github.com/osmdroid/osmdroid/wiki/How-to-use-the-osmdroid-library mapView = (MapView) findViewById(R.id.mapview); mapView.setTileSource(TileSourceFactory.MAPNIK); mapView.setBuiltInZoomControls(true); mapView.setMultiTouchControls(true); mapView.getController().setZoom(14); // http://code.tutsplus.com/tutorials/an-introduction-to-volley--cms-23800 mRequestQueue = Volley.newRequestQueue(this); searchField = (TextView) findViewById(R.id.lib_name); //----------------------------------------------------------------------------------------------------------------------------------------------- try { ArrayList<Double[]> allLibs = msqlite.getAllLibs(); //IF there's content inside the db if(allLibs.size() > 0) { for(int i = 0; i < allLibs.size(); i++) { GeoPoint g = new GeoPoint(allLibs.get(i)[0], allLibs.get(i)[1]); addMarker(g); } //If there's no content inside the db } else { // A JSONObject to post with the request. Null is allowed and indicates no parameters will be posted along with request. JSONObject obj = null; // haal alle libs op JsonObjectRequest jr = new JsonObjectRequest(Request.Method.GET, urlLibs, obj, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { hideSoftKeyBoard(); libs = response; handleJSONResponse(response); //Log.d("edu.ap.maps", libs.toString()); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("be.ap.edu.mapsaver", error.getMessage()); } }); mRequestQueue.add(jr); } } catch (Exception ex) { Log.e("Ripper", ex.getMessage()); } locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { Toast.makeText(getApplicationContext(), "GPS not enabled!", Toast.LENGTH_SHORT).show(); } else { locationListener = new MyLocationListener(); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener); } // default = meistraat mapView.getController().setCenter(new GeoPoint(51.2244, 4.38566)); } // http://codetheory.in/android-ontouchevent-ontouchlistener-motionevent-to-detect-common-gestures/ @Override public boolean dispatchTouchEvent(MotionEvent ev) { int actionType = ev.getAction(); switch(actionType) { case MotionEvent.ACTION_UP: // A Projection serves to translate between the coordinate system of // x/y on-screen pixel coordinates and that of latitude/longitude points // on the surface of the earth. You obtain a Projection from MapView.getProjection(). // You should not hold on to this object for more than one draw, since the projection of the map could change. Projection proj = this.mapView.getProjection(); GeoPoint loc = (GeoPoint)proj.fromPixels((int)ev.getX(), (int)ev.getY() - (searchField.getHeight() * 2)); //Log.d("edu.ap.maps", "Clicked"); findZone(loc); } return super.dispatchTouchEvent(ev); } private void hideSoftKeyBoard() { InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); if(imm.isAcceptingText()) { // verify if the soft keyboard is open imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); } } // http://alienryderflex.com/polygon/ // The basic idea is to find all edges of the polygon that span the 'x' position of the point you're testing against. // Then you find how many of them intersect the vertical line that extends above your point. If an even number cross above the point, // then you're outside the polygon. If an odd number cross above, then you're inside. private boolean contains(GeoPoint location, ArrayList<GeoPoint> polyLoc) { if(location==null) return false; if(polyLoc.size() == 0) return false; GeoPoint lastPoint = polyLoc.get(polyLoc.size()-1); boolean isInside = false; double x = location.getLongitude(); for(GeoPoint point: polyLoc) { double x1 = lastPoint.getLongitude(); double x2 = point.getLongitude(); double dx = x2 - x1; if (Math.abs(dx) > 180.0) { // we have, most likely, just jumped the dateline // (could do further validation to this effect if needed). // normalise the numbers. if (x > 0) { while (x1 < 0) x1 += 360; while (x2 < 0) x2 += 360; } else { while (x1 > 0) x1 -= 360; while (x2 > 0) x2 -= 360; } dx = x2 - x1; } if ((x1 <= x && x2 > x) || (x1 >= x && x2 < x)) { double grad = (point.getLatitude() - lastPoint.getLatitude()) / dx; double intersectAtLat = lastPoint.getLatitude() + ((x - x1) * grad); if (intersectAtLat > location.getLatitude()) isInside = !isInside; } lastPoint = point; } return isInside; } private void findZone(GeoPoint clickPoint) { try { JSONArray allLibs = libs.getJSONArray("data"); //Log.d("edu.ap.maps", String.valueOf(allLibs.length())); for(int i = 0; i < allLibs.length(); i++) { JSONObject obj = (JSONObject)allLibs.get(i); String tariefzone = ""; //obj.getString("tariefzone"); String tariefkleur = ""; //obj.getString("tariefkleur"); ArrayList<GeoPoint> list = new ArrayList<GeoPoint>(); JSONObject geometry = new JSONObject(obj.getString("geometry")); JSONArray coordinates = geometry.getJSONArray("coordinates"); // blijkbaar nog<SUF> JSONArray coordinatesInside = coordinates.getJSONArray(0); for(int j = 0; j < coordinatesInside.length(); j++) { JSONArray points = null; try { points = coordinatesInside.getJSONArray(j); GeoPoint g = new GeoPoint(points.getDouble(1), points.getDouble(0)); list.add(g); } catch(JSONException ex) { Log.e("be.ap.edu.mapsaver", ex.getMessage()); } } if(contains(clickPoint, list)) { this.addMarker(clickPoint); //Toast.makeText(this, "Tariefzone : " + tariefzone + " Tariefkleur : " + tariefkleur, Toast.LENGTH_SHORT).show(); break; } } } catch (Exception e) { Log.e("edu.ap.maps", e.getMessage()); Log.e("edu.ap.maps", String.valueOf(e.getStackTrace())); } } private void addMarker(GeoPoint g) { OverlayItem myLocationOverlayItem = new OverlayItem("Here", "Current Position", g); Drawable myCurrentLocationMarker = ResourcesCompat.getDrawable(getResources(), R.drawable.marker_default, null); myLocationOverlayItem.setMarker(myCurrentLocationMarker); items.add(myLocationOverlayItem); DefaultResourceProxyImpl resourceProxy = new DefaultResourceProxyImpl(getApplicationContext()); ItemizedIconOverlay<OverlayItem> currentLocationOverlay = new ItemizedIconOverlay<OverlayItem>(items, new ItemizedIconOverlay.OnItemGestureListener<OverlayItem>() { public boolean onItemSingleTapUp(final int index, final OverlayItem item) { return true; } public boolean onItemLongPress(final int index, final OverlayItem item) { return true; } }, resourceProxy); this.mapView.getOverlays().add(currentLocationOverlay); this.mapView.invalidate(); } private class MyLocationListener implements LocationListener { @Override public void onLocationChanged(Location loc) { mapView.getController().setCenter(new GeoPoint(loc.getLatitude(), loc.getLongitude())); } @Override public void onProviderDisabled(String provider) {} @Override public void onProviderEnabled(String provider) {} @Override public void onStatusChanged(String provider, int status, Bundle extras) {} } // START PERMISSION CHECK final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124; private void checkPermissions() { List<String> permissions = new ArrayList<>(); String message = "osmdroid permissions:"; if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { permissions.add(Manifest.permission.ACCESS_FINE_LOCATION); message += "\nLocation to show user location."; } if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); message += "\nStorage access to store map tiles."; } if(!permissions.isEmpty()) { Toast.makeText(this, message, Toast.LENGTH_LONG).show(); String[] params = permissions.toArray(new String[permissions.size()]); requestPermissions(params, REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS); } // else: We already have permissions, so handle as normal } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS: { Map<String, Integer> perms = new HashMap<>(); // Initial perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED); perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED); // Fill with results for (int i = 0; i < permissions.length; i++) perms.put(permissions[i], grantResults[i]); // Check for ACCESS_FINE_LOCATION and WRITE_EXTERNAL_STORAGE Boolean location = perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED; Boolean storage = perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED; if(location && storage) { // All Permissions Granted Toast.makeText(MainActivity.this, "All permissions granted", Toast.LENGTH_SHORT).show(); } else if (location) { Toast.makeText(this, "Storage permission is required to store map tiles to reduce data usage and for offline usage.", Toast.LENGTH_LONG).show(); } else if (storage) { Toast.makeText(this, "Location permission is required to show the user's location on map.", Toast.LENGTH_LONG).show(); } else { // !location && !storage case // Permission Denied Toast.makeText(MainActivity.this, "Storage permission is required to store map tiles to reduce data usage and for offline usage." + "\nLocation permission is required to show the user's location on map.", Toast.LENGTH_SHORT).show(); } } break; default: super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } private void handleJSONResponse(JSONObject object) { try { JSONArray data = object.getJSONArray("data"); for(int i = 0 ; i < data.length(); i++) { JSONObject obj = data.getJSONObject(i); GeoPoint g = new GeoPoint(obj.getDouble("point_lat"), obj.getDouble("point_lng")); addMarker(g); //Add to db msqlite.addLib(obj.getString("naam"), obj.getDouble("point_lat"), obj.getDouble("point_lng")); } } catch (Exception ex) { Log.e("pipi", ex.getMessage()); } } // END PERMISSION CHECK }
167102_0
package Domein; import java.util.ArrayList; import java.util.List; public class Product { private int product_nummer; private String naam; private String beschrijving; private int prijs; // maak dit list integer naar ovchipkaart private List<Integer> alleOVChipkaarten = new ArrayList<>(); public Product(int product_nummer, String naam, String beschrijving, int prijs) { this.product_nummer = product_nummer; this.naam = naam; this.beschrijving = beschrijving; this.prijs = prijs; } public List<Integer> getAlleOVChipkaarten() { return alleOVChipkaarten; } public void addOVChipkaart(int ovChipkaartNummer) { alleOVChipkaarten.add(ovChipkaartNummer); } public void removeOVChipkaart(int ovChipkaartNummer) { alleOVChipkaarten.remove(ovChipkaartNummer); } public int getProduct_nummer() { return product_nummer; } public String getNaam() { return naam; } public String getBeschrijving() { return beschrijving; } public int getPrijs() { return prijs; } public void setNaam(String naam) { this.naam = naam; } public void setBeschrijving(String beschrijving) { this.beschrijving = beschrijving; } public void setPrijs(int prijs) { this.prijs = prijs; } @Override public String toString() { return String.format("%s, %s, %s, %s, %s", this.product_nummer, this.naam, this.beschrijving, this.prijs, this.alleOVChipkaarten); } }
BramdeGooijer/DP_OV-Chipkaart
src/main/java/Domein/Product.java
511
// maak dit list integer naar ovchipkaart
line_comment
nl
package Domein; import java.util.ArrayList; import java.util.List; public class Product { private int product_nummer; private String naam; private String beschrijving; private int prijs; // maak dit<SUF> private List<Integer> alleOVChipkaarten = new ArrayList<>(); public Product(int product_nummer, String naam, String beschrijving, int prijs) { this.product_nummer = product_nummer; this.naam = naam; this.beschrijving = beschrijving; this.prijs = prijs; } public List<Integer> getAlleOVChipkaarten() { return alleOVChipkaarten; } public void addOVChipkaart(int ovChipkaartNummer) { alleOVChipkaarten.add(ovChipkaartNummer); } public void removeOVChipkaart(int ovChipkaartNummer) { alleOVChipkaarten.remove(ovChipkaartNummer); } public int getProduct_nummer() { return product_nummer; } public String getNaam() { return naam; } public String getBeschrijving() { return beschrijving; } public int getPrijs() { return prijs; } public void setNaam(String naam) { this.naam = naam; } public void setBeschrijving(String beschrijving) { this.beschrijving = beschrijving; } public void setPrijs(int prijs) { this.prijs = prijs; } @Override public String toString() { return String.format("%s, %s, %s, %s, %s", this.product_nummer, this.naam, this.beschrijving, this.prijs, this.alleOVChipkaarten); } }
69084_0
import Domein.Adres; import Domein.Reiziger; import Interfaces.Adres.AdresDAO; import Interfaces.Adres.AdresDAOHibernate; import Interfaces.Reiziger.ReizigerDAO; import Interfaces.Reiziger.ReizigerDAOHibernate; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.query.Query; import javax.persistence.metamodel.EntityType; import javax.persistence.metamodel.Metamodel; import java.sql.Date; import java.sql.SQLException; import java.util.List; /** * Testklasse - deze klasse test alle andere klassen in deze package. * * System.out.println() is alleen in deze klasse toegestaan (behalve voor exceptions). * * @author tijmen.muller@hu.nl */ public class Main { // Creëer een factory voor Hibernate sessions. private static final SessionFactory factory; static { try { // Create a Hibernate session factory factory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { throw new ExceptionInInitializerError(ex); } } /** * Retouneer een Hibernate session. * * @return Hibernate session * @throws HibernateException */ private static Session getSession() throws HibernateException { return factory.openSession(); } public static void main(String[] args) throws SQLException { // testFetchAll(); testDAOHibernate(); } /** * P6. Haal alle (geannoteerde) entiteiten uit de database. */ private static void testFetchAll() { Session session = getSession(); try { Metamodel metamodel = session.getSessionFactory().getMetamodel(); for (EntityType<?> entityType : metamodel.getEntities()) { Query query = session.createQuery("from " + entityType.getName()); System.out.println("[Test] Alle objecten van type " + entityType.getName() + " uit database:"); for (Object o : query.list()) { System.out.println(" " + o); } System.out.println(); } } finally { session.close(); } } private static void testDAOHibernate() { Session session = getSession(); Transaction tx = session.beginTransaction(); AdresDAOHibernate adao = new AdresDAOHibernate(session, tx); ReizigerDAOHibernate rdao = new ReizigerDAOHibernate(session, tx); // maak reiziger en adres Reiziger reiziger = new Reiziger(200, "b", "de", "Gooijer", Date.valueOf("2001-01-01")); Adres adres = new Adres(200, "1218GZ", "5", "Vuurlvindermeent", "Hilversum", reiziger); // reiziger in database rdao.save(reiziger); // rdao.update(reiziger); // rdao.delete(reiziger); // adres in database adao.save(adres); // adao.update(adres); // adao.delete(adres); // // close the session session.close(); } }
BramdeGooijer/DP_OV-Chipkaart_Hibernate
src/main/java/Main.java
964
/** * Testklasse - deze klasse test alle andere klassen in deze package. * * System.out.println() is alleen in deze klasse toegestaan (behalve voor exceptions). * * @author tijmen.muller@hu.nl */
block_comment
nl
import Domein.Adres; import Domein.Reiziger; import Interfaces.Adres.AdresDAO; import Interfaces.Adres.AdresDAOHibernate; import Interfaces.Reiziger.ReizigerDAO; import Interfaces.Reiziger.ReizigerDAOHibernate; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.query.Query; import javax.persistence.metamodel.EntityType; import javax.persistence.metamodel.Metamodel; import java.sql.Date; import java.sql.SQLException; import java.util.List; /** * Testklasse - deze<SUF>*/ public class Main { // Creëer een factory voor Hibernate sessions. private static final SessionFactory factory; static { try { // Create a Hibernate session factory factory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { throw new ExceptionInInitializerError(ex); } } /** * Retouneer een Hibernate session. * * @return Hibernate session * @throws HibernateException */ private static Session getSession() throws HibernateException { return factory.openSession(); } public static void main(String[] args) throws SQLException { // testFetchAll(); testDAOHibernate(); } /** * P6. Haal alle (geannoteerde) entiteiten uit de database. */ private static void testFetchAll() { Session session = getSession(); try { Metamodel metamodel = session.getSessionFactory().getMetamodel(); for (EntityType<?> entityType : metamodel.getEntities()) { Query query = session.createQuery("from " + entityType.getName()); System.out.println("[Test] Alle objecten van type " + entityType.getName() + " uit database:"); for (Object o : query.list()) { System.out.println(" " + o); } System.out.println(); } } finally { session.close(); } } private static void testDAOHibernate() { Session session = getSession(); Transaction tx = session.beginTransaction(); AdresDAOHibernate adao = new AdresDAOHibernate(session, tx); ReizigerDAOHibernate rdao = new ReizigerDAOHibernate(session, tx); // maak reiziger en adres Reiziger reiziger = new Reiziger(200, "b", "de", "Gooijer", Date.valueOf("2001-01-01")); Adres adres = new Adres(200, "1218GZ", "5", "Vuurlvindermeent", "Hilversum", reiziger); // reiziger in database rdao.save(reiziger); // rdao.update(reiziger); // rdao.delete(reiziger); // adres in database adao.save(adres); // adao.update(adres); // adao.delete(adres); // // close the session session.close(); } }
160343_2
package test; import main.domeinLaag.*; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Calendar; import static org.junit.jupiter.api.Assertions.*; public class VluchtTest { static LuchtvaartMaatschappij lvm ; static Fabrikant f1; static VliegtuigType vtt1; static Vliegtuig vt1; static Luchthaven lh1, lh2; static Vlucht vl1, vl2; @BeforeEach public void initialize() { try { lvm = new LuchtvaartMaatschappij("NLM"); f1 = new Fabrikant("Airbus","G. Dejenelle"); vtt1 = f1.creeervliegtuigtype("A-200", 140); Calendar datum = Calendar.getInstance(); datum.set(2000, 01, 01); vt1 = new Vliegtuig(lvm, vtt1, "Luchtbus 100", datum); Land l1 = new Land("Nederland", 31); Land l2 = new Land("België", 32); lh1 = new Luchthaven("Schiphol", "ASD", true, l1); lh2 = new Luchthaven("Tegel", "TEG", true, l2); Calendar vertr = Calendar.getInstance(); vertr.set(2020, 03, 30, 14, 15, 0); Calendar aank = Calendar.getInstance(); aank.set(2020, 03, 30, 15, 15, 0); vl1 = new Vlucht(vt1, lh1, lh2, vertr, aank ); vertr.set(2020, 4, 1, 8, 15, 0); aank.set(2020, 4, 1, 9, 15, 0); vl2 = new Vlucht(vt1, lh1, lh2, vertr, aank ); } catch (Exception e){ String errorMessage = "Exception: " + e.getMessage(); System.out.println(errorMessage); } } /** * Business rule: * De bestemming moet verschillen van het vertrekpunt van de vlucht. */ @Test public void test_1_BestemmingMagNietGelijkZijnAanVertrek_False() { Vlucht vlucht = new Vlucht(); try { vlucht.zetVliegtuig(vt1); vlucht.zetVertrekpunt(lh1); Luchthaven bestemming = vlucht.getBestemming(); assertTrue(bestemming == null); vlucht.zetBestemming(lh1); // De test zou niet verder mogen komen: er moet al een exception gethrowd zijn. bestemming = vlucht.getBestemming(); assertFalse(bestemming.equals(lh1)); } catch(IllegalArgumentException e) { Luchthaven bestemming = vlucht.getBestemming(); assertFalse(bestemming.equals(lh1)); } } @Test public void test_2_BestemmingMagNietGelijkZijnAanVertrek_True() { Vlucht vlucht = new Vlucht(); Luchthaven bestemming; try { vlucht.zetVliegtuig(vt1); vlucht.zetVertrekpunt(lh2); bestemming = vlucht.getBestemming(); assertTrue(bestemming == null); vlucht.zetBestemming(lh1); bestemming = vlucht.getBestemming(); assertTrue(bestemming.equals(lh1)); } catch(IllegalArgumentException e) { bestemming = vlucht.getBestemming(); assertTrue(bestemming.equals(lh1)); } } /** * Business rule: * De vertrektijd en aankomsttijd moeten geldig zijn (dus een bestaande dag/uur/minuten combinatie * aangeven) en in de toekomst liggen. */ @Test public void test_3_AankomstTijdNietIngevuld_False() { // FOUTMELDING "geen geldige datum/tijd" Vlucht vlucht = new Vlucht(); Luchthaven bestemming; try { vlucht.zetVliegtuig(vt1); vlucht.zetVertrekpunt(lh1); vlucht.zetBestemming(lh2); Calendar vertrek = Calendar.getInstance(); vertrek.set(2025, Calendar.SEPTEMBER, 31, 24, 0); vlucht.zetVertrekTijd(vertrek); assertFalse(vlucht.getVertrekTijd() == null); assertFalse(vlucht.getAankomstTijd() == null); }catch(VluchtException e){ assertEquals("main.domeinLaag.VluchtException: Geen geldig tijdstip!", e.toString()); } } @Test public void test_5_RegistreerVluchtMetGeldigeGegevens_True() { // GEEN foutmelding Vlucht vlucht = new Vlucht(); try { Calendar vertrek = Calendar.getInstance(); Calendar aankomst = Calendar.getInstance(); vertrek.set(2025, Calendar.SEPTEMBER, 30, 12, 0); aankomst.set(2025, Calendar.SEPTEMBER, 30, 12, 0); // vlucht.zetVliegtuig(vt1); // vlucht.zetVertrekpunt(lh1); // vlucht.zetBestemming(lh2); // vlucht.zetVertrekTijd(vertrek); // vlucht.zetAankomstTijd(aankomst); vlucht = new Vlucht(vt1, lh1, lh2, vertrek, aankomst); assertNotNull(vlucht.getAankomstTijd()); assertNotNull(vlucht.getVertrekTijd()); }catch(IllegalArgumentException e){ assertNotNull(vlucht.getAankomstTijd()); assertNotNull(vlucht.getVertrekTijd()); } } @Test public void test_6_Vertrektijd1MinuutInHetVerleden_False() { // FOUTMELDING "tijd in het verleden" Vlucht vlucht = new Vlucht(); try { vlucht.zetVliegtuig(vt1); vlucht.zetVertrekpunt(lh1); vlucht.zetBestemming(lh2); }catch(IllegalArgumentException e){ } } @Test public void test_7_VertrekEnAankomstTijdInHetVerleden_False() { // FOUTMELDING 2X "tijd in het verleden" try { }catch(IllegalArgumentException e){ } } @Test public void test_8_RegistreerVluchtVanNuTotOver1Minuut_True() { // GEEN foutmelding try { }catch(IllegalArgumentException e){ } } /** * Business rule: * De aankomsttijd moet na de vertrektijd liggen. */ @Test public void test_9_VertrektijdNaAankomsttijd_False() { // FOUTMELDING "vertrektijd < aankomsttijd" Vlucht vlucht = new Vlucht(); try { vlucht.zetVliegtuig(vt1); Calendar vertrek = Calendar.getInstance(); vertrek.add(Calendar.MINUTE, 5); Calendar aankomst = Calendar.getInstance(); vlucht.zetVertrekTijd(vertrek); vlucht.zetAankomstTijd(aankomst); assertEquals("aankomsttijd voor vertrektijd", vlucht.getVertrekTijd()); }catch(IllegalArgumentException | VluchtException e){ assertEquals("main.domeinLaag.VluchtException: Aankomsttijd voor vertrektijd", e.toString()); } } @Test public void test_10_VertrektijdVoorAankomsttijd_True() { // GEEN foutmelding Vlucht vlucht = new Vlucht(); try { vlucht.zetVertrekpunt(lh1); vlucht.zetBestemming(lh2); Calendar vertrektijd = Calendar.getInstance(); Calendar aankomsttijd = Calendar.getInstance(); aankomsttijd.add(Calendar.MINUTE, 1); assertTrue("Vlucht [vluchtNummer=3, vt=null, bestemming=Luchthaven [naam=Tegel, code=TEG, werkPlaats=true, land=Land [naam=Belgi�, code=32]], vertrekpunt=Luchthaven [naam=Schiphol, code=ASD, werkPlaats=true, land=Land [naam=Nederland, code=31]], vertrekTijd=null, aankomstTijd=null, duur=null]".equals(vlucht.toString())); }catch(IllegalArgumentException e){ } } /** * Business rule: * Een vliegtuig kan maar voor ��n vlucht tegelijk gebruikt worden. */ @Test public void test_11_OverlappendeVluchtVertrektijdBinnen_False() { // FOUTMELDING "overlappende vlucht" Vlucht vlucht = new Vlucht(); try { vlucht.zetVliegtuig(vt1); Calendar vertrek = Calendar.getInstance(); Calendar aankomst = Calendar.getInstance(); vertrek.set(2020, 03, 30, 14, 35, 10); aankomst.set(2020, 03, 30, 16, 36, 10); vlucht.zetVertrekTijd(vertrek); assertTrue(vlucht.getVertrekTijd() == null); vlucht.zetAankomstTijd(aankomst); } catch (VluchtException e) { assertEquals("main.domeinLaag.VluchtException: Vliegtuig reeds bezet op Thu Apr 30 14:35:10 CEST 2020", e.toString()); } } @Test public void test_12_OverlappendeVluchtAankomsttijdBinnen_False() { // FOUTMELDING "overlappende vlucht" Vlucht vlucht = new Vlucht(); try { vlucht.zetVliegtuig(vt1); Calendar vertrek = Calendar.getInstance(); Calendar aankomst = Calendar.getInstance(); vertrek.set(2020, 03, 30, 11, 36, 10); aankomst.set(2020, 03, 30, 14, 30, 10); vlucht.zetVertrekTijd(vertrek); vlucht.zetAankomstTijd(aankomst); assertEquals("main.domeinLaag.VluchtException: Vliegtuig reeds bezet op Thu Apr 30 14:30:10 CEST 2020", vlucht.getAankomstTijd()); }catch(IllegalArgumentException | VluchtException e) { assertEquals("main.domeinLaag.VluchtException: Vliegtuig reeds bezet op Thu Apr 30 14:30:10 CEST 2020", e.toString()); } } @Test public void test_13_OverlappendeVluchtOverBestaandeHeen_False() { // FOUTMELDING "overlappende vlucht" Vlucht vlucht = new Vlucht(); try { Calendar vertrek = Calendar.getInstance(); Calendar aankomst = Calendar.getInstance(); vertrek.set(2025, Calendar.JULY, 1, 12, 43); aankomst.set(2025, Calendar.JULY, 1, 15, 36); vlucht.zetVliegtuig(vt1); vlucht.zetVertrekpunt(lh1); vlucht.zetBestemming(lh2); vlucht.zetVertrekTijd(vertrek); vlucht.zetAankomstTijd(aankomst); assertTrue(vlucht.getVertrekTijd() == null); } catch (VluchtException e) { assertTrue("overlappende vlucht".equals(e.toString())); } } @Test public void test_14_RegistreerVluchtBuitenBestaandeVlucht_True() { // GEEN foutmelding try { }catch(IllegalArgumentException e){ } } /** * Business rule: * Een vlucht mag alleen geaccepteerd worden als de volgende gegevens zijn vastgelegd: vliegtuig, * vertrekpunt, bestemming, vertrektijd, aankomsttijd. */ @Test public void test_15_VliegtuigOngeldig_False() { // FOUTMELDING "Vliegtuig ongeldig" try { }catch(IllegalArgumentException e){ } } @Test public void test_16_VertrekpuntOngeldig_False() { // FOUTMELDING NA OK "Vertrekpunt ongeldig" Vlucht vlucht = new Vlucht(); try { vlucht.zetBestemming(lh2); Calendar vertrektijd = Calendar.getInstance(); vlucht.zetVertrekTijd(vertrektijd); Calendar aankomsttijd = Calendar.getInstance(); aankomsttijd.add(Calendar.MINUTE, 1); assertTrue(vlucht.getVertrekPunt() == null); } catch (VluchtException e) { assertEquals("Vertrekpunt ongeldig", e.toString()); } } @Test public void test_17_BestemmingOngeldig_False() { // FOUTMELDING NA OK "Bestemming ongeldig" Vlucht vlucht = new Vlucht(); try { vlucht.zetVertrekpunt(lh1); Calendar vertrektijd = Calendar.getInstance(); vlucht.zetVertrekTijd(vertrektijd); Calendar aankomsttijd = Calendar.getInstance(); aankomsttijd.add(Calendar.MINUTE, 1); assertTrue(vlucht.getBestemming() == null); } catch (VluchtException e) { assertEquals("Bestemming ongeldig", e.toString()); } } @Test public void test_18_VertrektijdOngeldig_False() { // FOUTMELDING NA OK "Vetrektijd ongeldig" Vlucht vlucht = new Vlucht(); try { vlucht.zetVliegtuig(vt1); vlucht.zetVertrekpunt(lh1); vlucht.zetBestemming(lh2); Calendar aankomst = Calendar.getInstance(); aankomst.set(2002, Calendar.OCTOBER, 11, 22, 0); assert aankomst.before(Calendar.getInstance()); if(aankomst.before(Calendar.getInstance())){ throw new IllegalArgumentException("e"); } }catch(IllegalArgumentException e){ System.out.println("vertrektijd ongeldig"); } } @Test public void test_19_AankomsttijdOngeldig_False() { // FOUTMELDING NA OK "Aankomsttijd ongeldig" Vlucht vlucht = new Vlucht(); try { vlucht.zetVliegtuig(vt1); vlucht.zetVertrekpunt(lh1); vlucht.zetBestemming(lh2); Calendar vertrek = Calendar.getInstance(); vertrek.set(2002, Calendar.OCTOBER, 11, 22, 0); assert vertrek.before(Calendar.getInstance()); if (vertrek.before(Calendar.getInstance())) { throw new IllegalArgumentException("e"); } }catch(IllegalArgumentException e){ System.out.println("Aankomsttijd ongeldig"); } } @Test public void test_20_CompleetGeldigeVluchtGeregistreerd() { // GEEN FOUTMELDING NA OK try { }catch(IllegalArgumentException e){ } } /** * Business rule: * xxx */ }
BramdeGooijer/LuchtvaartMaatschappijSysteem_basis_2022_Groep_4
src/test/VluchtTest.java
4,657
/** * Business rule: * De vertrektijd en aankomsttijd moeten geldig zijn (dus een bestaande dag/uur/minuten combinatie * aangeven) en in de toekomst liggen. */
block_comment
nl
package test; import main.domeinLaag.*; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Calendar; import static org.junit.jupiter.api.Assertions.*; public class VluchtTest { static LuchtvaartMaatschappij lvm ; static Fabrikant f1; static VliegtuigType vtt1; static Vliegtuig vt1; static Luchthaven lh1, lh2; static Vlucht vl1, vl2; @BeforeEach public void initialize() { try { lvm = new LuchtvaartMaatschappij("NLM"); f1 = new Fabrikant("Airbus","G. Dejenelle"); vtt1 = f1.creeervliegtuigtype("A-200", 140); Calendar datum = Calendar.getInstance(); datum.set(2000, 01, 01); vt1 = new Vliegtuig(lvm, vtt1, "Luchtbus 100", datum); Land l1 = new Land("Nederland", 31); Land l2 = new Land("België", 32); lh1 = new Luchthaven("Schiphol", "ASD", true, l1); lh2 = new Luchthaven("Tegel", "TEG", true, l2); Calendar vertr = Calendar.getInstance(); vertr.set(2020, 03, 30, 14, 15, 0); Calendar aank = Calendar.getInstance(); aank.set(2020, 03, 30, 15, 15, 0); vl1 = new Vlucht(vt1, lh1, lh2, vertr, aank ); vertr.set(2020, 4, 1, 8, 15, 0); aank.set(2020, 4, 1, 9, 15, 0); vl2 = new Vlucht(vt1, lh1, lh2, vertr, aank ); } catch (Exception e){ String errorMessage = "Exception: " + e.getMessage(); System.out.println(errorMessage); } } /** * Business rule: * De bestemming moet verschillen van het vertrekpunt van de vlucht. */ @Test public void test_1_BestemmingMagNietGelijkZijnAanVertrek_False() { Vlucht vlucht = new Vlucht(); try { vlucht.zetVliegtuig(vt1); vlucht.zetVertrekpunt(lh1); Luchthaven bestemming = vlucht.getBestemming(); assertTrue(bestemming == null); vlucht.zetBestemming(lh1); // De test zou niet verder mogen komen: er moet al een exception gethrowd zijn. bestemming = vlucht.getBestemming(); assertFalse(bestemming.equals(lh1)); } catch(IllegalArgumentException e) { Luchthaven bestemming = vlucht.getBestemming(); assertFalse(bestemming.equals(lh1)); } } @Test public void test_2_BestemmingMagNietGelijkZijnAanVertrek_True() { Vlucht vlucht = new Vlucht(); Luchthaven bestemming; try { vlucht.zetVliegtuig(vt1); vlucht.zetVertrekpunt(lh2); bestemming = vlucht.getBestemming(); assertTrue(bestemming == null); vlucht.zetBestemming(lh1); bestemming = vlucht.getBestemming(); assertTrue(bestemming.equals(lh1)); } catch(IllegalArgumentException e) { bestemming = vlucht.getBestemming(); assertTrue(bestemming.equals(lh1)); } } /** * Business rule: <SUF>*/ @Test public void test_3_AankomstTijdNietIngevuld_False() { // FOUTMELDING "geen geldige datum/tijd" Vlucht vlucht = new Vlucht(); Luchthaven bestemming; try { vlucht.zetVliegtuig(vt1); vlucht.zetVertrekpunt(lh1); vlucht.zetBestemming(lh2); Calendar vertrek = Calendar.getInstance(); vertrek.set(2025, Calendar.SEPTEMBER, 31, 24, 0); vlucht.zetVertrekTijd(vertrek); assertFalse(vlucht.getVertrekTijd() == null); assertFalse(vlucht.getAankomstTijd() == null); }catch(VluchtException e){ assertEquals("main.domeinLaag.VluchtException: Geen geldig tijdstip!", e.toString()); } } @Test public void test_5_RegistreerVluchtMetGeldigeGegevens_True() { // GEEN foutmelding Vlucht vlucht = new Vlucht(); try { Calendar vertrek = Calendar.getInstance(); Calendar aankomst = Calendar.getInstance(); vertrek.set(2025, Calendar.SEPTEMBER, 30, 12, 0); aankomst.set(2025, Calendar.SEPTEMBER, 30, 12, 0); // vlucht.zetVliegtuig(vt1); // vlucht.zetVertrekpunt(lh1); // vlucht.zetBestemming(lh2); // vlucht.zetVertrekTijd(vertrek); // vlucht.zetAankomstTijd(aankomst); vlucht = new Vlucht(vt1, lh1, lh2, vertrek, aankomst); assertNotNull(vlucht.getAankomstTijd()); assertNotNull(vlucht.getVertrekTijd()); }catch(IllegalArgumentException e){ assertNotNull(vlucht.getAankomstTijd()); assertNotNull(vlucht.getVertrekTijd()); } } @Test public void test_6_Vertrektijd1MinuutInHetVerleden_False() { // FOUTMELDING "tijd in het verleden" Vlucht vlucht = new Vlucht(); try { vlucht.zetVliegtuig(vt1); vlucht.zetVertrekpunt(lh1); vlucht.zetBestemming(lh2); }catch(IllegalArgumentException e){ } } @Test public void test_7_VertrekEnAankomstTijdInHetVerleden_False() { // FOUTMELDING 2X "tijd in het verleden" try { }catch(IllegalArgumentException e){ } } @Test public void test_8_RegistreerVluchtVanNuTotOver1Minuut_True() { // GEEN foutmelding try { }catch(IllegalArgumentException e){ } } /** * Business rule: * De aankomsttijd moet na de vertrektijd liggen. */ @Test public void test_9_VertrektijdNaAankomsttijd_False() { // FOUTMELDING "vertrektijd < aankomsttijd" Vlucht vlucht = new Vlucht(); try { vlucht.zetVliegtuig(vt1); Calendar vertrek = Calendar.getInstance(); vertrek.add(Calendar.MINUTE, 5); Calendar aankomst = Calendar.getInstance(); vlucht.zetVertrekTijd(vertrek); vlucht.zetAankomstTijd(aankomst); assertEquals("aankomsttijd voor vertrektijd", vlucht.getVertrekTijd()); }catch(IllegalArgumentException | VluchtException e){ assertEquals("main.domeinLaag.VluchtException: Aankomsttijd voor vertrektijd", e.toString()); } } @Test public void test_10_VertrektijdVoorAankomsttijd_True() { // GEEN foutmelding Vlucht vlucht = new Vlucht(); try { vlucht.zetVertrekpunt(lh1); vlucht.zetBestemming(lh2); Calendar vertrektijd = Calendar.getInstance(); Calendar aankomsttijd = Calendar.getInstance(); aankomsttijd.add(Calendar.MINUTE, 1); assertTrue("Vlucht [vluchtNummer=3, vt=null, bestemming=Luchthaven [naam=Tegel, code=TEG, werkPlaats=true, land=Land [naam=Belgi�, code=32]], vertrekpunt=Luchthaven [naam=Schiphol, code=ASD, werkPlaats=true, land=Land [naam=Nederland, code=31]], vertrekTijd=null, aankomstTijd=null, duur=null]".equals(vlucht.toString())); }catch(IllegalArgumentException e){ } } /** * Business rule: * Een vliegtuig kan maar voor ��n vlucht tegelijk gebruikt worden. */ @Test public void test_11_OverlappendeVluchtVertrektijdBinnen_False() { // FOUTMELDING "overlappende vlucht" Vlucht vlucht = new Vlucht(); try { vlucht.zetVliegtuig(vt1); Calendar vertrek = Calendar.getInstance(); Calendar aankomst = Calendar.getInstance(); vertrek.set(2020, 03, 30, 14, 35, 10); aankomst.set(2020, 03, 30, 16, 36, 10); vlucht.zetVertrekTijd(vertrek); assertTrue(vlucht.getVertrekTijd() == null); vlucht.zetAankomstTijd(aankomst); } catch (VluchtException e) { assertEquals("main.domeinLaag.VluchtException: Vliegtuig reeds bezet op Thu Apr 30 14:35:10 CEST 2020", e.toString()); } } @Test public void test_12_OverlappendeVluchtAankomsttijdBinnen_False() { // FOUTMELDING "overlappende vlucht" Vlucht vlucht = new Vlucht(); try { vlucht.zetVliegtuig(vt1); Calendar vertrek = Calendar.getInstance(); Calendar aankomst = Calendar.getInstance(); vertrek.set(2020, 03, 30, 11, 36, 10); aankomst.set(2020, 03, 30, 14, 30, 10); vlucht.zetVertrekTijd(vertrek); vlucht.zetAankomstTijd(aankomst); assertEquals("main.domeinLaag.VluchtException: Vliegtuig reeds bezet op Thu Apr 30 14:30:10 CEST 2020", vlucht.getAankomstTijd()); }catch(IllegalArgumentException | VluchtException e) { assertEquals("main.domeinLaag.VluchtException: Vliegtuig reeds bezet op Thu Apr 30 14:30:10 CEST 2020", e.toString()); } } @Test public void test_13_OverlappendeVluchtOverBestaandeHeen_False() { // FOUTMELDING "overlappende vlucht" Vlucht vlucht = new Vlucht(); try { Calendar vertrek = Calendar.getInstance(); Calendar aankomst = Calendar.getInstance(); vertrek.set(2025, Calendar.JULY, 1, 12, 43); aankomst.set(2025, Calendar.JULY, 1, 15, 36); vlucht.zetVliegtuig(vt1); vlucht.zetVertrekpunt(lh1); vlucht.zetBestemming(lh2); vlucht.zetVertrekTijd(vertrek); vlucht.zetAankomstTijd(aankomst); assertTrue(vlucht.getVertrekTijd() == null); } catch (VluchtException e) { assertTrue("overlappende vlucht".equals(e.toString())); } } @Test public void test_14_RegistreerVluchtBuitenBestaandeVlucht_True() { // GEEN foutmelding try { }catch(IllegalArgumentException e){ } } /** * Business rule: * Een vlucht mag alleen geaccepteerd worden als de volgende gegevens zijn vastgelegd: vliegtuig, * vertrekpunt, bestemming, vertrektijd, aankomsttijd. */ @Test public void test_15_VliegtuigOngeldig_False() { // FOUTMELDING "Vliegtuig ongeldig" try { }catch(IllegalArgumentException e){ } } @Test public void test_16_VertrekpuntOngeldig_False() { // FOUTMELDING NA OK "Vertrekpunt ongeldig" Vlucht vlucht = new Vlucht(); try { vlucht.zetBestemming(lh2); Calendar vertrektijd = Calendar.getInstance(); vlucht.zetVertrekTijd(vertrektijd); Calendar aankomsttijd = Calendar.getInstance(); aankomsttijd.add(Calendar.MINUTE, 1); assertTrue(vlucht.getVertrekPunt() == null); } catch (VluchtException e) { assertEquals("Vertrekpunt ongeldig", e.toString()); } } @Test public void test_17_BestemmingOngeldig_False() { // FOUTMELDING NA OK "Bestemming ongeldig" Vlucht vlucht = new Vlucht(); try { vlucht.zetVertrekpunt(lh1); Calendar vertrektijd = Calendar.getInstance(); vlucht.zetVertrekTijd(vertrektijd); Calendar aankomsttijd = Calendar.getInstance(); aankomsttijd.add(Calendar.MINUTE, 1); assertTrue(vlucht.getBestemming() == null); } catch (VluchtException e) { assertEquals("Bestemming ongeldig", e.toString()); } } @Test public void test_18_VertrektijdOngeldig_False() { // FOUTMELDING NA OK "Vetrektijd ongeldig" Vlucht vlucht = new Vlucht(); try { vlucht.zetVliegtuig(vt1); vlucht.zetVertrekpunt(lh1); vlucht.zetBestemming(lh2); Calendar aankomst = Calendar.getInstance(); aankomst.set(2002, Calendar.OCTOBER, 11, 22, 0); assert aankomst.before(Calendar.getInstance()); if(aankomst.before(Calendar.getInstance())){ throw new IllegalArgumentException("e"); } }catch(IllegalArgumentException e){ System.out.println("vertrektijd ongeldig"); } } @Test public void test_19_AankomsttijdOngeldig_False() { // FOUTMELDING NA OK "Aankomsttijd ongeldig" Vlucht vlucht = new Vlucht(); try { vlucht.zetVliegtuig(vt1); vlucht.zetVertrekpunt(lh1); vlucht.zetBestemming(lh2); Calendar vertrek = Calendar.getInstance(); vertrek.set(2002, Calendar.OCTOBER, 11, 22, 0); assert vertrek.before(Calendar.getInstance()); if (vertrek.before(Calendar.getInstance())) { throw new IllegalArgumentException("e"); } }catch(IllegalArgumentException e){ System.out.println("Aankomsttijd ongeldig"); } } @Test public void test_20_CompleetGeldigeVluchtGeregistreerd() { // GEEN FOUTMELDING NA OK try { }catch(IllegalArgumentException e){ } } /** * Business rule: * xxx */ }
28096_21
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2020.04.07 at 05:46:22 PM CEST // package com.bylivingart.plants.buienradar; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for weergegevensType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="weergegevensType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="titel" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="link" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="omschrijving" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="language" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="copyright" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="gebruik" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="image" type="{}imageType"/> * &lt;element name="actueel_weer" type="{}actueel_weerType"/> * &lt;element name="verwachting_meerdaags" type="{}verwachting_meerdaagsType"/> * &lt;element name="verwachting_vandaag" type="{}verwachting_vandaagType"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "weergegevensType", propOrder = { "titel", "link", "omschrijving", "language", "copyright", "gebruik", "image", "actueelWeer", "verwachtingMeerdaags", "verwachtingVandaag" }) public class WeergegevensType { @XmlElement(required = true) protected String titel; @XmlElement(required = true) protected String link; @XmlElement(required = true) protected String omschrijving; @XmlElement(required = true) protected String language; @XmlElement(required = true) protected String copyright; @XmlElement(required = true) protected String gebruik; @XmlElement(required = true) protected ImageType image; @XmlElement(name = "actueel_weer", required = true) protected ActueelWeerType actueelWeer; @XmlElement(name = "verwachting_meerdaags", required = true) protected VerwachtingMeerdaagsType verwachtingMeerdaags; @XmlElement(name = "verwachting_vandaag", required = true) protected VerwachtingVandaagType verwachtingVandaag; /** * Gets the value of the titel property. * * @return possible object is * {@link String } */ public String getTitel() { return titel; } /** * Sets the value of the titel property. * * @param value allowed object is * {@link String } */ public void setTitel(String value) { this.titel = value; } /** * Gets the value of the link property. * * @return possible object is * {@link String } */ public String getLink() { return link; } /** * Sets the value of the link property. * * @param value allowed object is * {@link String } */ public void setLink(String value) { this.link = value; } /** * Gets the value of the omschrijving property. * * @return possible object is * {@link String } */ public String getOmschrijving() { return omschrijving; } /** * Sets the value of the omschrijving property. * * @param value allowed object is * {@link String } */ public void setOmschrijving(String value) { this.omschrijving = value; } /** * Gets the value of the language property. * * @return possible object is * {@link String } */ public String getLanguage() { return language; } /** * Sets the value of the language property. * * @param value allowed object is * {@link String } */ public void setLanguage(String value) { this.language = value; } /** * Gets the value of the copyright property. * * @return possible object is * {@link String } */ public String getCopyright() { return copyright; } /** * Sets the value of the copyright property. * * @param value allowed object is * {@link String } */ public void setCopyright(String value) { this.copyright = value; } /** * Gets the value of the gebruik property. * * @return possible object is * {@link String } */ public String getGebruik() { return gebruik; } /** * Sets the value of the gebruik property. * * @param value allowed object is * {@link String } */ public void setGebruik(String value) { this.gebruik = value; } /** * Gets the value of the image property. * * @return possible object is * {@link ImageType } */ public ImageType getImage() { return image; } /** * Sets the value of the image property. * * @param value allowed object is * {@link ImageType } */ public void setImage(ImageType value) { this.image = value; } /** * Gets the value of the actueelWeer property. * * @return possible object is * {@link ActueelWeerType } */ public ActueelWeerType getActueelWeer() { return actueelWeer; } /** * Sets the value of the actueelWeer property. * * @param value allowed object is * {@link ActueelWeerType } */ public void setActueelWeer(ActueelWeerType value) { this.actueelWeer = value; } /** * Gets the value of the verwachtingMeerdaags property. * * @return possible object is * {@link VerwachtingMeerdaagsType } */ public VerwachtingMeerdaagsType getVerwachtingMeerdaags() { return verwachtingMeerdaags; } /** * Sets the value of the verwachtingMeerdaags property. * * @param value allowed object is * {@link VerwachtingMeerdaagsType } */ public void setVerwachtingMeerdaags(VerwachtingMeerdaagsType value) { this.verwachtingMeerdaags = value; } /** * Gets the value of the verwachtingVandaag property. * * @return possible object is * {@link VerwachtingVandaagType } */ public VerwachtingVandaagType getVerwachtingVandaag() { return verwachtingVandaag; } /** * Sets the value of the verwachtingVandaag property. * * @param value allowed object is * {@link VerwachtingVandaagType } */ public void setVerwachtingVandaag(VerwachtingVandaagType value) { this.verwachtingVandaag = value; } }
Bramgus12/ProjectD
server/src/main/java/com/bylivingart/plants/buienradar/WeergegevensType.java
2,348
/** * Gets the value of the verwachtingMeerdaags property. * * @return possible object is * {@link VerwachtingMeerdaagsType } */
block_comment
nl
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2020.04.07 at 05:46:22 PM CEST // package com.bylivingart.plants.buienradar; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for weergegevensType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="weergegevensType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="titel" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="link" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="omschrijving" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="language" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="copyright" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="gebruik" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="image" type="{}imageType"/> * &lt;element name="actueel_weer" type="{}actueel_weerType"/> * &lt;element name="verwachting_meerdaags" type="{}verwachting_meerdaagsType"/> * &lt;element name="verwachting_vandaag" type="{}verwachting_vandaagType"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "weergegevensType", propOrder = { "titel", "link", "omschrijving", "language", "copyright", "gebruik", "image", "actueelWeer", "verwachtingMeerdaags", "verwachtingVandaag" }) public class WeergegevensType { @XmlElement(required = true) protected String titel; @XmlElement(required = true) protected String link; @XmlElement(required = true) protected String omschrijving; @XmlElement(required = true) protected String language; @XmlElement(required = true) protected String copyright; @XmlElement(required = true) protected String gebruik; @XmlElement(required = true) protected ImageType image; @XmlElement(name = "actueel_weer", required = true) protected ActueelWeerType actueelWeer; @XmlElement(name = "verwachting_meerdaags", required = true) protected VerwachtingMeerdaagsType verwachtingMeerdaags; @XmlElement(name = "verwachting_vandaag", required = true) protected VerwachtingVandaagType verwachtingVandaag; /** * Gets the value of the titel property. * * @return possible object is * {@link String } */ public String getTitel() { return titel; } /** * Sets the value of the titel property. * * @param value allowed object is * {@link String } */ public void setTitel(String value) { this.titel = value; } /** * Gets the value of the link property. * * @return possible object is * {@link String } */ public String getLink() { return link; } /** * Sets the value of the link property. * * @param value allowed object is * {@link String } */ public void setLink(String value) { this.link = value; } /** * Gets the value of the omschrijving property. * * @return possible object is * {@link String } */ public String getOmschrijving() { return omschrijving; } /** * Sets the value of the omschrijving property. * * @param value allowed object is * {@link String } */ public void setOmschrijving(String value) { this.omschrijving = value; } /** * Gets the value of the language property. * * @return possible object is * {@link String } */ public String getLanguage() { return language; } /** * Sets the value of the language property. * * @param value allowed object is * {@link String } */ public void setLanguage(String value) { this.language = value; } /** * Gets the value of the copyright property. * * @return possible object is * {@link String } */ public String getCopyright() { return copyright; } /** * Sets the value of the copyright property. * * @param value allowed object is * {@link String } */ public void setCopyright(String value) { this.copyright = value; } /** * Gets the value of the gebruik property. * * @return possible object is * {@link String } */ public String getGebruik() { return gebruik; } /** * Sets the value of the gebruik property. * * @param value allowed object is * {@link String } */ public void setGebruik(String value) { this.gebruik = value; } /** * Gets the value of the image property. * * @return possible object is * {@link ImageType } */ public ImageType getImage() { return image; } /** * Sets the value of the image property. * * @param value allowed object is * {@link ImageType } */ public void setImage(ImageType value) { this.image = value; } /** * Gets the value of the actueelWeer property. * * @return possible object is * {@link ActueelWeerType } */ public ActueelWeerType getActueelWeer() { return actueelWeer; } /** * Sets the value of the actueelWeer property. * * @param value allowed object is * {@link ActueelWeerType } */ public void setActueelWeer(ActueelWeerType value) { this.actueelWeer = value; } /** * Gets the value<SUF>*/ public VerwachtingMeerdaagsType getVerwachtingMeerdaags() { return verwachtingMeerdaags; } /** * Sets the value of the verwachtingMeerdaags property. * * @param value allowed object is * {@link VerwachtingMeerdaagsType } */ public void setVerwachtingMeerdaags(VerwachtingMeerdaagsType value) { this.verwachtingMeerdaags = value; } /** * Gets the value of the verwachtingVandaag property. * * @return possible object is * {@link VerwachtingVandaagType } */ public VerwachtingVandaagType getVerwachtingVandaag() { return verwachtingVandaag; } /** * Sets the value of the verwachtingVandaag property. * * @param value allowed object is * {@link VerwachtingVandaagType } */ public void setVerwachtingVandaag(VerwachtingVandaagType value) { this.verwachtingVandaag = value; } }
50029_0
package com.example.manillenandroid; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AlertDialog.Builder; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class ScoreOptellen extends AppCompatActivity { private TextView scoreTeam1; private TextView scoreTeam2; private EditText scoreDezeRonde; private Button team1; private Button team2; private Button stop; private int totaalTeam1; private int totaalTeam2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_score_optellen); scoreDezeRonde = (EditText) findViewById(R.id.etScoreRonde); team1 = findViewById(R.id.btnTeam1); team2 = findViewById(R.id.btnTeam2); scoreTeam1 = findViewById(R.id.tvTeam1Score); scoreTeam2 = findViewById(R.id.tvTeam2Score); team1.setText(String.valueOf(MainActivity.naamTeam1)); team2.setText(String.valueOf(MainActivity.naamTeam2)); stop = findViewById(R.id.btn_stop); final Builder scoreTeLaag = new Builder(ScoreOptellen.this); scoreTeLaag.setTitle("Let Op!"); scoreTeLaag.setMessage("De ingevulde score moet boven 0 liggen."); scoreTeLaag.setPositiveButton("OK!",null); final Builder scoreTeLaag2 = new Builder(ScoreOptellen.this); scoreTeLaag2.setTitle("Let Op!"); scoreTeLaag2.setMessage("De ingevulde score moet boven 0 liggen"); scoreTeLaag2.setPositiveButton("OK!",null); team1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (Integer.parseInt(scoreDezeRonde.getText().toString()) > 0 || scoreDezeRonde.getText().toString().equals("")) { int scoreRonde = Integer.parseInt(scoreDezeRonde.getText().toString()); totaalTeam1 = totaalTeam1 + scoreRonde; scoreTeam1.setText(String.valueOf(totaalTeam1)); if (totaalTeam1 >= Instellingen.maxScoreTotaal) { Builder gewonnenTeam1 = new Builder(ScoreOptellen.this); gewonnenTeam1.setTitle("Gewonnen"); gewonnenTeam1.setMessage("Gefeliciteerd team " + MainActivity.naamTeam1 + " je hebt gewonnen!"); gewonnenTeam1.setPositiveButton("OK!",null); gewonnenTeam1.setNeutralButton("Reset", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { openStartscherm(); totaalTeam1 = 0; totaalTeam2 = 0; MainActivity.naamTeam1 = null; MainActivity.naamTeam2 = null; scoreTeam1.setText("Team1: \n"); scoreTeam2.setText("Team2: \n"); } }); gewonnenTeam1.show(); } //Geprobeerd om lege score te voorkomen, werkt niet. // }else if (scoreDezeRonde.getText().toString().trim().isEmpty()){ // Builder scoreNietIngevuld = new Builder(ScoreOptellen.this); // scoreNietIngevuld.setTitle("Let Op!"); // scoreNietIngevuld.setMessage("De ingevulde score moet boven 0 liggen."); // scoreNietIngevuld.setPositiveButton("OK!",null); // scoreNietIngevuld.show(); } else { //POPUP KADER MET OK KNOP scoreTeLaag.show(); } } }); team2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (Integer.parseInt(scoreDezeRonde.getText().toString()) > 0){ int scoreRonde = Integer.parseInt(scoreDezeRonde.getText().toString()); totaalTeam2 = totaalTeam2 + scoreRonde; scoreTeam2.setText(String.valueOf(totaalTeam2)); if (totaalTeam2 >= Instellingen.maxScoreTotaal) { Builder gewonnenTeam2 = new Builder(ScoreOptellen.this); gewonnenTeam2.setTitle("Gewonnen"); gewonnenTeam2.setMessage("Gefeliciteerd team " + MainActivity.naamTeam2 + " je hebt gewonnen!"); gewonnenTeam2.setPositiveButton("OK!",null); gewonnenTeam2.setNeutralButton("Reset", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { openStartscherm(); totaalTeam1 = 0; totaalTeam2 = 0; MainActivity.naamTeam1 = null; MainActivity.naamTeam2 = null; scoreTeam1.setText("Team1: \n"); scoreTeam2.setText("Team2: \n"); } }); gewonnenTeam2.show(); } } else { //POPUP KADER MET OK KNOP scoreTeLaag2.show(); } } }); stop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openStartscherm(); totaalTeam1 = 0; totaalTeam2 = 0; MainActivity.naamTeam1 = null; MainActivity.naamTeam2 = null; scoreTeam1.setText("Team1: \n"); scoreTeam2.setText("Team2: \n"); } }); } public void openStartscherm() { Intent openStartschermKlasse = new Intent(this, MainActivity.class); startActivity(openStartschermKlasse); } }
Bramke/ManillenAndroid
app/src/main/java/com/example/manillenandroid/ScoreOptellen.java
1,786
//Geprobeerd om lege score te voorkomen, werkt niet.
line_comment
nl
package com.example.manillenandroid; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AlertDialog.Builder; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class ScoreOptellen extends AppCompatActivity { private TextView scoreTeam1; private TextView scoreTeam2; private EditText scoreDezeRonde; private Button team1; private Button team2; private Button stop; private int totaalTeam1; private int totaalTeam2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_score_optellen); scoreDezeRonde = (EditText) findViewById(R.id.etScoreRonde); team1 = findViewById(R.id.btnTeam1); team2 = findViewById(R.id.btnTeam2); scoreTeam1 = findViewById(R.id.tvTeam1Score); scoreTeam2 = findViewById(R.id.tvTeam2Score); team1.setText(String.valueOf(MainActivity.naamTeam1)); team2.setText(String.valueOf(MainActivity.naamTeam2)); stop = findViewById(R.id.btn_stop); final Builder scoreTeLaag = new Builder(ScoreOptellen.this); scoreTeLaag.setTitle("Let Op!"); scoreTeLaag.setMessage("De ingevulde score moet boven 0 liggen."); scoreTeLaag.setPositiveButton("OK!",null); final Builder scoreTeLaag2 = new Builder(ScoreOptellen.this); scoreTeLaag2.setTitle("Let Op!"); scoreTeLaag2.setMessage("De ingevulde score moet boven 0 liggen"); scoreTeLaag2.setPositiveButton("OK!",null); team1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (Integer.parseInt(scoreDezeRonde.getText().toString()) > 0 || scoreDezeRonde.getText().toString().equals("")) { int scoreRonde = Integer.parseInt(scoreDezeRonde.getText().toString()); totaalTeam1 = totaalTeam1 + scoreRonde; scoreTeam1.setText(String.valueOf(totaalTeam1)); if (totaalTeam1 >= Instellingen.maxScoreTotaal) { Builder gewonnenTeam1 = new Builder(ScoreOptellen.this); gewonnenTeam1.setTitle("Gewonnen"); gewonnenTeam1.setMessage("Gefeliciteerd team " + MainActivity.naamTeam1 + " je hebt gewonnen!"); gewonnenTeam1.setPositiveButton("OK!",null); gewonnenTeam1.setNeutralButton("Reset", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { openStartscherm(); totaalTeam1 = 0; totaalTeam2 = 0; MainActivity.naamTeam1 = null; MainActivity.naamTeam2 = null; scoreTeam1.setText("Team1: \n"); scoreTeam2.setText("Team2: \n"); } }); gewonnenTeam1.show(); } //Geprobeerd om<SUF> // }else if (scoreDezeRonde.getText().toString().trim().isEmpty()){ // Builder scoreNietIngevuld = new Builder(ScoreOptellen.this); // scoreNietIngevuld.setTitle("Let Op!"); // scoreNietIngevuld.setMessage("De ingevulde score moet boven 0 liggen."); // scoreNietIngevuld.setPositiveButton("OK!",null); // scoreNietIngevuld.show(); } else { //POPUP KADER MET OK KNOP scoreTeLaag.show(); } } }); team2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (Integer.parseInt(scoreDezeRonde.getText().toString()) > 0){ int scoreRonde = Integer.parseInt(scoreDezeRonde.getText().toString()); totaalTeam2 = totaalTeam2 + scoreRonde; scoreTeam2.setText(String.valueOf(totaalTeam2)); if (totaalTeam2 >= Instellingen.maxScoreTotaal) { Builder gewonnenTeam2 = new Builder(ScoreOptellen.this); gewonnenTeam2.setTitle("Gewonnen"); gewonnenTeam2.setMessage("Gefeliciteerd team " + MainActivity.naamTeam2 + " je hebt gewonnen!"); gewonnenTeam2.setPositiveButton("OK!",null); gewonnenTeam2.setNeutralButton("Reset", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { openStartscherm(); totaalTeam1 = 0; totaalTeam2 = 0; MainActivity.naamTeam1 = null; MainActivity.naamTeam2 = null; scoreTeam1.setText("Team1: \n"); scoreTeam2.setText("Team2: \n"); } }); gewonnenTeam2.show(); } } else { //POPUP KADER MET OK KNOP scoreTeLaag2.show(); } } }); stop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openStartscherm(); totaalTeam1 = 0; totaalTeam2 = 0; MainActivity.naamTeam1 = null; MainActivity.naamTeam2 = null; scoreTeam1.setText("Team1: \n"); scoreTeam2.setText("Team2: \n"); } }); } public void openStartscherm() { Intent openStartschermKlasse = new Intent(this, MainActivity.class); startActivity(openStartschermKlasse); } }
87803_1
package domein; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import persistentie.PersistentieController; public class Zoo {//DUMMY public final String PERSISTENCE_UNIT_NAME = "JPA_details"; private List<Verzorger> verzorgers; private List<Dier> dieren; private List<Gebouw> gebouwen; public Zoo() { this.dieren = new PersistentieController().geefDieren(); this.verzorgers = new PersistentieController().geefVerzorgers(); this.gebouwen = new PersistentieController().geefGebouwen(); } /* * Geeft alle dieren terug die behoren tot de diersoort met de opgegeven naam. De lijst van * dieren moet gesorteerd zijn op gewicht (laag naar hoog). */ public List<Dier> geefDierenVanSoortMetNaam(String soortNaam) { Comparator<Dier> opGewicht = Comparator.comparing(Dier::getGewicht); return dieren.stream() .filter(d -> d.getSoort().getNaam().equals(soortNaam)) .sorted(opGewicht) .collect(Collectors.toList()); } /* * Geeft het gemiddelde gewicht terug van alle dieren die verblijven in het gebouw met de * opgegeven naam. Geeft 0 terug indien er geen gebouw is met deze naam. */ public double geefGemiddeldeGewichtVanDierenInGebouwMetNaam(String gebouwNaam) { Gebouw gebouw = gebouwen.stream() .filter(g -> g.getNaam().equals(gebouwNaam)) .findFirst() .orElse(null); if(gebouw == null) { return 0; } return gebouw.getDieren().stream() .mapToDouble(Dier::getGewicht) .average() .getAsDouble(); } /* * Geeft de namen van de dieren terug die verzorgd worden door de verzorger met het opgegeven * nummer. Geeft een lege lijst terug indien er geen verzorger is met dit nummer. */ //-- public List<String> geefNamenVanDierenVanVerzorgerMetNummer(int verzorgerNummer) { Verzorger optVerzorger = verzorgers.stream() .filter(v -> v.getNummer() == verzorgerNummer) .findFirst() .orElse(null); if(optVerzorger != null) { return optVerzorger.getDieren().stream() .map(Dier::getNaam) .collect(Collectors.toList()); } return new ArrayList<String>(); } // /* // * Geeft een lijst terug van verzorgers die een of meerdere dieren verzorgen die verblijven in // * het gebouw met de opgegeven naam. Geeft een lege lijst terug indien er geen gebouw is met // * deze naam. // * NU DUMMY UITWERKING voor test gebruik in deze toepassing // * NIET VERDER UITWERKEN // */ public List<Verzorger> verzorgersInGebouwMetNaam(String gebouwNaam) { if (gebouwNaam.equalsIgnoreCase("Reptielen")) { return verzorgers; } else { return new ArrayList<>(); } } /** * De methode maakOverzichtVolgensSoort geeft een overzicht (Map) terug van * alle dieren per Soort. */ //TODO // TODO METHODE ....maakOverzichtVolgensSoort() ... hier uitschrijven // public Map<Soort, List<Dier>> maakOverzichtVolgensSoort(){ return dieren.stream() .collect(Collectors.groupingBy(Dier::getSoort)); } }
Bramke/OOPIII_Oplossingen
Ex_OOP3_1516_herex_start_vraag3_4/src/domein/Zoo.java
1,191
/* * Geeft het gemiddelde gewicht terug van alle dieren die verblijven in het gebouw met de * opgegeven naam. Geeft 0 terug indien er geen gebouw is met deze naam. */
block_comment
nl
package domein; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import persistentie.PersistentieController; public class Zoo {//DUMMY public final String PERSISTENCE_UNIT_NAME = "JPA_details"; private List<Verzorger> verzorgers; private List<Dier> dieren; private List<Gebouw> gebouwen; public Zoo() { this.dieren = new PersistentieController().geefDieren(); this.verzorgers = new PersistentieController().geefVerzorgers(); this.gebouwen = new PersistentieController().geefGebouwen(); } /* * Geeft alle dieren terug die behoren tot de diersoort met de opgegeven naam. De lijst van * dieren moet gesorteerd zijn op gewicht (laag naar hoog). */ public List<Dier> geefDierenVanSoortMetNaam(String soortNaam) { Comparator<Dier> opGewicht = Comparator.comparing(Dier::getGewicht); return dieren.stream() .filter(d -> d.getSoort().getNaam().equals(soortNaam)) .sorted(opGewicht) .collect(Collectors.toList()); } /* * Geeft het gemiddelde<SUF>*/ public double geefGemiddeldeGewichtVanDierenInGebouwMetNaam(String gebouwNaam) { Gebouw gebouw = gebouwen.stream() .filter(g -> g.getNaam().equals(gebouwNaam)) .findFirst() .orElse(null); if(gebouw == null) { return 0; } return gebouw.getDieren().stream() .mapToDouble(Dier::getGewicht) .average() .getAsDouble(); } /* * Geeft de namen van de dieren terug die verzorgd worden door de verzorger met het opgegeven * nummer. Geeft een lege lijst terug indien er geen verzorger is met dit nummer. */ //-- public List<String> geefNamenVanDierenVanVerzorgerMetNummer(int verzorgerNummer) { Verzorger optVerzorger = verzorgers.stream() .filter(v -> v.getNummer() == verzorgerNummer) .findFirst() .orElse(null); if(optVerzorger != null) { return optVerzorger.getDieren().stream() .map(Dier::getNaam) .collect(Collectors.toList()); } return new ArrayList<String>(); } // /* // * Geeft een lijst terug van verzorgers die een of meerdere dieren verzorgen die verblijven in // * het gebouw met de opgegeven naam. Geeft een lege lijst terug indien er geen gebouw is met // * deze naam. // * NU DUMMY UITWERKING voor test gebruik in deze toepassing // * NIET VERDER UITWERKEN // */ public List<Verzorger> verzorgersInGebouwMetNaam(String gebouwNaam) { if (gebouwNaam.equalsIgnoreCase("Reptielen")) { return verzorgers; } else { return new ArrayList<>(); } } /** * De methode maakOverzichtVolgensSoort geeft een overzicht (Map) terug van * alle dieren per Soort. */ //TODO // TODO METHODE ....maakOverzichtVolgensSoort() ... hier uitschrijven // public Map<Soort, List<Dier>> maakOverzichtVolgensSoort(){ return dieren.stream() .collect(Collectors.groupingBy(Dier::getSoort)); } }
14058_6
package nl.logius.resource.example; /* * This source code is protected by the EUPL version 1.2 and is part of the "PP Decrypt" example package. * * Copyright: Logius (2018) * @author: Bram van Pelt */ import java.lang.reflect.*; import java.nio.file.Files; import java.nio.file.Paths; import java.security.Security; import java.util.Map; import javax.crypto.Cipher; import nl.logius.resource.pp.util.DecryptUtil; public class main { public static void main(String [] args) { try { // In dit voorbeeld werken we me langere sleutels dan normaal wordt gebruikt in Java. // Hiervoor moet een aanpassing tijdelijk gemaakt worden aan de java security opties. Dit gebeurd in de bijgevoegde methode // Normaal kan hiervoor een patch van Oracle worden geinstalleerd. // voor java 1.8 is dat http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html fixKeyLength(); // ook bouncycastle moet worden geregistreerd als JAVA security provider. Normaal wordt dit op de server gedaan voordat de software wordt gerunned. Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); // laad de sleutels in het geheugen, normaal komen deze uit een keystore keyUtil keys = new keyUtil(); //simuleer een EncryptedID (ei) en EncryptedPseudonym (ep) String ei = new String ( Files.readAllBytes( Paths.get("F:\\workspace\\PP-Decrypt_ExamplePackage\\bin\\resources\\"+ "signed\\900095222-2-4-I.txt") ) ); String ep = new String ( Files.readAllBytes( Paths.get("F:\\workspace\\PP-Decrypt_ExamplePackage\\bin\\resources\\"+ "signed\\900095222-2-4-P.txt") ) ); //Pre-load complete, Decrypt de ei en ep String simBsn = DecryptUtil.getIdentity(ei,keys.getDecryptKey(), keys.getVerifiers()); String simPseudo = DecryptUtil.getPseudonym(ep, keys.getPDecryptKey(), keys.getPClosingKey(), keys.getPVerifiers()); //Doe er iets nuttigs mee ;) System.out.println("Identity:" + simBsn); System.out.println("Pseudo:" + simPseudo); } catch (Exception e) { e.printStackTrace(); } } public static void fixKeyLength() { String errorString = "Failed manually overriding key-length permissions."; int newMaxKeyLength; try { if ((newMaxKeyLength = Cipher.getMaxAllowedKeyLength("AES")) < 256) { Class c = Class.forName("javax.crypto.CryptoAllPermissionCollection"); Constructor con = c.getDeclaredConstructor(); con.setAccessible(true); Object allPermissionCollection = con.newInstance(); Field f = c.getDeclaredField("all_allowed"); f.setAccessible(true); f.setBoolean(allPermissionCollection, true); c = Class.forName("javax.crypto.CryptoPermissions"); con = c.getDeclaredConstructor(); con.setAccessible(true); Object allPermissions = con.newInstance(); f = c.getDeclaredField("perms"); f.setAccessible(true); ((Map) f.get(allPermissions)).put("*", allPermissionCollection); c = Class.forName("javax.crypto.JceSecurityManager"); f = c.getDeclaredField("defaultPolicy"); f.setAccessible(true); Field mf = Field.class.getDeclaredField("modifiers"); mf.setAccessible(true); mf.setInt(f, f.getModifiers() & ~Modifier.FINAL); f.set(null, allPermissions); newMaxKeyLength = Cipher.getMaxAllowedKeyLength("AES"); } } catch (Exception e) { throw new RuntimeException(errorString, e); } if (newMaxKeyLength < 256) throw new RuntimeException(errorString); // hack failed } }
BramvanPelt/PPDecryption
PP-Decrypt_ExamplePackage/src/nl/logius/resource/example/main.java
1,234
// laad de sleutels in het geheugen, normaal komen deze uit een keystore
line_comment
nl
package nl.logius.resource.example; /* * This source code is protected by the EUPL version 1.2 and is part of the "PP Decrypt" example package. * * Copyright: Logius (2018) * @author: Bram van Pelt */ import java.lang.reflect.*; import java.nio.file.Files; import java.nio.file.Paths; import java.security.Security; import java.util.Map; import javax.crypto.Cipher; import nl.logius.resource.pp.util.DecryptUtil; public class main { public static void main(String [] args) { try { // In dit voorbeeld werken we me langere sleutels dan normaal wordt gebruikt in Java. // Hiervoor moet een aanpassing tijdelijk gemaakt worden aan de java security opties. Dit gebeurd in de bijgevoegde methode // Normaal kan hiervoor een patch van Oracle worden geinstalleerd. // voor java 1.8 is dat http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html fixKeyLength(); // ook bouncycastle moet worden geregistreerd als JAVA security provider. Normaal wordt dit op de server gedaan voordat de software wordt gerunned. Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); // laad de<SUF> keyUtil keys = new keyUtil(); //simuleer een EncryptedID (ei) en EncryptedPseudonym (ep) String ei = new String ( Files.readAllBytes( Paths.get("F:\\workspace\\PP-Decrypt_ExamplePackage\\bin\\resources\\"+ "signed\\900095222-2-4-I.txt") ) ); String ep = new String ( Files.readAllBytes( Paths.get("F:\\workspace\\PP-Decrypt_ExamplePackage\\bin\\resources\\"+ "signed\\900095222-2-4-P.txt") ) ); //Pre-load complete, Decrypt de ei en ep String simBsn = DecryptUtil.getIdentity(ei,keys.getDecryptKey(), keys.getVerifiers()); String simPseudo = DecryptUtil.getPseudonym(ep, keys.getPDecryptKey(), keys.getPClosingKey(), keys.getPVerifiers()); //Doe er iets nuttigs mee ;) System.out.println("Identity:" + simBsn); System.out.println("Pseudo:" + simPseudo); } catch (Exception e) { e.printStackTrace(); } } public static void fixKeyLength() { String errorString = "Failed manually overriding key-length permissions."; int newMaxKeyLength; try { if ((newMaxKeyLength = Cipher.getMaxAllowedKeyLength("AES")) < 256) { Class c = Class.forName("javax.crypto.CryptoAllPermissionCollection"); Constructor con = c.getDeclaredConstructor(); con.setAccessible(true); Object allPermissionCollection = con.newInstance(); Field f = c.getDeclaredField("all_allowed"); f.setAccessible(true); f.setBoolean(allPermissionCollection, true); c = Class.forName("javax.crypto.CryptoPermissions"); con = c.getDeclaredConstructor(); con.setAccessible(true); Object allPermissions = con.newInstance(); f = c.getDeclaredField("perms"); f.setAccessible(true); ((Map) f.get(allPermissions)).put("*", allPermissionCollection); c = Class.forName("javax.crypto.JceSecurityManager"); f = c.getDeclaredField("defaultPolicy"); f.setAccessible(true); Field mf = Field.class.getDeclaredField("modifiers"); mf.setAccessible(true); mf.setInt(f, f.getModifiers() & ~Modifier.FINAL); f.set(null, allPermissions); newMaxKeyLength = Cipher.getMaxAllowedKeyLength("AES"); } } catch (Exception e) { throw new RuntimeException(errorString, e); } if (newMaxKeyLength < 256) throw new RuntimeException(errorString); // hack failed } }
133709_6
package activitymain.mainactivity; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; //import android.telecom.Connection; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; /* import com.mysql.fabric.xmlrpc.Client; import com.mysql.jdbc.MySQLConnection; import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource; import com.mysql.jdbc.jdbc2.optional.MysqlPooledConnection;*/ import java.util.Arrays; import java.util.HashMap; import java.util.Random; public class MainActivity extends AppCompatActivity { Button[] buttonArray = new Button[4]; Button answerBtn1, answerBtn2, answerBtn3,answerBtn4; int idNumber, currentQuestion; int[] questionPositions; int[] buttonPositions; Connection connection; int currentScore; TextView questionTextView; HashMap<Integer, String[]> questionAnswerMap = new HashMap<Integer, String[]>(); HashMap<Integer, String> answerMap = new HashMap<Integer, String>(); HashMap<Integer, String> questionMap = new HashMap<Integer, String>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initialise(); populate(); //print out question the sequence for (int item: questionPositions ) { System.out.println(item); } } public void initialise(){ DBConnect connect = new DBConnect(); ResultSet rsAnswers = connect.getData("SELECT * FROM antwoorden"); //find the buttons questionTextView = (TextView) findViewById(R.id.QuestionTextView); answerBtn1 = (Button) findViewById(R.id.answerBtn1); answerBtn2 = (Button) findViewById(R.id.answerBtn2); answerBtn3 = (Button) findViewById(R.id.answerBtn3); answerBtn4 = (Button) findViewById(R.id.answerBtn4); //initialise the buttons buttonArray[0] = answerBtn1; buttonArray[1] = answerBtn2; buttonArray[2] = answerBtn3; buttonArray[3] = answerBtn4; //Map containing he question per ID questionMap.put(0, "Vraag 1"); questionMap.put(1, "Vraag 2"); questionMap.put(2, "Vraag 3"); questionMap.put(3, "Vraag 4"); questionMap.put(4, "Vraag 5"); questionMap.put(5, "Vraag 6"); //Map containing keys with all values in it questionAnswerMap.put(0, new String[] {"1.1", "1.2", "1.3", "1.4"} ); questionAnswerMap.put(1, new String[] {"2.1", "2.2", "2.3", "2.4"} ); questionAnswerMap.put(2, new String[] {"3.1", "3.2", "3.3", "3.4"} ); questionAnswerMap.put(3, new String[] {"4.1", "4.2", "4.3", "4.4"} ); questionAnswerMap.put(4, new String[] {"5.1", "5.2", "5.3", "5.4"} ); questionAnswerMap.put(5, new String[] {"6.1", "6.2", "6.3", "6.4"} ); //stop alle data van de database in de hashmaps /* try{ System.out.println("test"); while(rsAnswers.next() == true) { System.out.println("test22"); System.out.println(rsAnswers.getInt(1) - 1 + " " + rsAnswers.getString(2) + " " + rsAnswers.getString(3) + " " + rsAnswers.getString(4) + " " + rsAnswers.getString(5)); questionAnswerMap.put(rsAnswers.getInt(1) - 1, new String[] {rsAnswers.getString(2), rsAnswers.getString(3), rsAnswers.getString(4), rsAnswers.getString(5)} ); String correctAntwoord = rsAnswers.getString(2); }} catch(Exception ex){ System.out.println(ex.getMessage()); }*/ //Map containing the correct answer answerMap.put(0, "1.1"); answerMap.put(1, "2.2"); answerMap.put(2, "3.3"); answerMap.put(3, "4.2"); answerMap.put(4, "5.3"); answerMap.put(5, "6.2"); currentQuestion = 0; questionPositions = getRandomPermutation(questionAnswerMap.size()); } public void confirmQuestion(View view){ String guessed = ""; Button pressedButton = null; //check which button has been pressed if(view.getId() == R.id.answerBtn1){ guessed = answerBtn1.getText().toString(); pressedButton = answerBtn1; } else if(view.getId() == R.id.answerBtn2){ guessed = answerBtn2.getText().toString(); pressedButton = answerBtn2; } else if(view.getId() == R.id.answerBtn3){ guessed = answerBtn3.getText().toString(); pressedButton = answerBtn3; } else if(view.getId() == R.id.answerBtn4){ guessed = answerBtn4.getText().toString(); pressedButton = answerBtn4; answerBtn4.clearAnimation(); } //if text equal to answer repopulate and put button colour to default if( guessed == answerMap.get(idNumber)){ pressedButton.setBackgroundColor(Color.GREEN); try { Thread.sleep(500); pressedButton.setBackgroundColor(Color.LTGRAY); }catch(Exception ex){} pressedButton.clearAnimation(); populate(); } } public void populate(){ //check if questionssequence is finished if(currentQuestion < questionPositions.length) { try { //assign the idnumber to get information from the hashmaps //id number is the equal of current number from the sequence System.out.println(currentQuestion); idNumber = questionPositions[currentQuestion]; //set questiontext questionTextView.setText(questionMap.get(idNumber)); //set all info of the buttons String[] answers = questionAnswerMap.get(idNumber); buttonPositions = getRandomPermutation(4); for (int i : buttonPositions) { buttonArray[i].setText(questionAnswerMap.get(idNumber)[buttonPositions[i]]); } currentQuestion++; } catch (Exception ex) { //if exception print System.out.println("Exception"); } }else{ //stop when the sequence has ended System.out.println("Exit"); System.exit(0); } } public static int[] getRandomPermutation (int length){ // initialize array and fill it with {0,1,2...} int[] array = new int[length]; for(int i = 0; i < array.length; i++) array[i] = i; for(int i = 0; i < length; i++){ // randomly chosen position in array whose element // will be swapped with the element in position i // note that when i = 0, any position can chosen (0 thru length-1) // when i = 1, only positions 1 through length -1 // NOTE: r is an instance of java.util.Random Random r = new Random(); int ran = i + r.nextInt (length-i); // perform swap int temp = array[i]; array[i] = array[ran]; array[ran] = temp; } return array; } }
Brend-Smits/TVM2
app/src/main/java/activitymain/mainactivity/MainActivity.java
2,278
//stop alle data van de database in de hashmaps
line_comment
nl
package activitymain.mainactivity; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; //import android.telecom.Connection; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; /* import com.mysql.fabric.xmlrpc.Client; import com.mysql.jdbc.MySQLConnection; import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource; import com.mysql.jdbc.jdbc2.optional.MysqlPooledConnection;*/ import java.util.Arrays; import java.util.HashMap; import java.util.Random; public class MainActivity extends AppCompatActivity { Button[] buttonArray = new Button[4]; Button answerBtn1, answerBtn2, answerBtn3,answerBtn4; int idNumber, currentQuestion; int[] questionPositions; int[] buttonPositions; Connection connection; int currentScore; TextView questionTextView; HashMap<Integer, String[]> questionAnswerMap = new HashMap<Integer, String[]>(); HashMap<Integer, String> answerMap = new HashMap<Integer, String>(); HashMap<Integer, String> questionMap = new HashMap<Integer, String>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initialise(); populate(); //print out question the sequence for (int item: questionPositions ) { System.out.println(item); } } public void initialise(){ DBConnect connect = new DBConnect(); ResultSet rsAnswers = connect.getData("SELECT * FROM antwoorden"); //find the buttons questionTextView = (TextView) findViewById(R.id.QuestionTextView); answerBtn1 = (Button) findViewById(R.id.answerBtn1); answerBtn2 = (Button) findViewById(R.id.answerBtn2); answerBtn3 = (Button) findViewById(R.id.answerBtn3); answerBtn4 = (Button) findViewById(R.id.answerBtn4); //initialise the buttons buttonArray[0] = answerBtn1; buttonArray[1] = answerBtn2; buttonArray[2] = answerBtn3; buttonArray[3] = answerBtn4; //Map containing he question per ID questionMap.put(0, "Vraag 1"); questionMap.put(1, "Vraag 2"); questionMap.put(2, "Vraag 3"); questionMap.put(3, "Vraag 4"); questionMap.put(4, "Vraag 5"); questionMap.put(5, "Vraag 6"); //Map containing keys with all values in it questionAnswerMap.put(0, new String[] {"1.1", "1.2", "1.3", "1.4"} ); questionAnswerMap.put(1, new String[] {"2.1", "2.2", "2.3", "2.4"} ); questionAnswerMap.put(2, new String[] {"3.1", "3.2", "3.3", "3.4"} ); questionAnswerMap.put(3, new String[] {"4.1", "4.2", "4.3", "4.4"} ); questionAnswerMap.put(4, new String[] {"5.1", "5.2", "5.3", "5.4"} ); questionAnswerMap.put(5, new String[] {"6.1", "6.2", "6.3", "6.4"} ); //stop alle<SUF> /* try{ System.out.println("test"); while(rsAnswers.next() == true) { System.out.println("test22"); System.out.println(rsAnswers.getInt(1) - 1 + " " + rsAnswers.getString(2) + " " + rsAnswers.getString(3) + " " + rsAnswers.getString(4) + " " + rsAnswers.getString(5)); questionAnswerMap.put(rsAnswers.getInt(1) - 1, new String[] {rsAnswers.getString(2), rsAnswers.getString(3), rsAnswers.getString(4), rsAnswers.getString(5)} ); String correctAntwoord = rsAnswers.getString(2); }} catch(Exception ex){ System.out.println(ex.getMessage()); }*/ //Map containing the correct answer answerMap.put(0, "1.1"); answerMap.put(1, "2.2"); answerMap.put(2, "3.3"); answerMap.put(3, "4.2"); answerMap.put(4, "5.3"); answerMap.put(5, "6.2"); currentQuestion = 0; questionPositions = getRandomPermutation(questionAnswerMap.size()); } public void confirmQuestion(View view){ String guessed = ""; Button pressedButton = null; //check which button has been pressed if(view.getId() == R.id.answerBtn1){ guessed = answerBtn1.getText().toString(); pressedButton = answerBtn1; } else if(view.getId() == R.id.answerBtn2){ guessed = answerBtn2.getText().toString(); pressedButton = answerBtn2; } else if(view.getId() == R.id.answerBtn3){ guessed = answerBtn3.getText().toString(); pressedButton = answerBtn3; } else if(view.getId() == R.id.answerBtn4){ guessed = answerBtn4.getText().toString(); pressedButton = answerBtn4; answerBtn4.clearAnimation(); } //if text equal to answer repopulate and put button colour to default if( guessed == answerMap.get(idNumber)){ pressedButton.setBackgroundColor(Color.GREEN); try { Thread.sleep(500); pressedButton.setBackgroundColor(Color.LTGRAY); }catch(Exception ex){} pressedButton.clearAnimation(); populate(); } } public void populate(){ //check if questionssequence is finished if(currentQuestion < questionPositions.length) { try { //assign the idnumber to get information from the hashmaps //id number is the equal of current number from the sequence System.out.println(currentQuestion); idNumber = questionPositions[currentQuestion]; //set questiontext questionTextView.setText(questionMap.get(idNumber)); //set all info of the buttons String[] answers = questionAnswerMap.get(idNumber); buttonPositions = getRandomPermutation(4); for (int i : buttonPositions) { buttonArray[i].setText(questionAnswerMap.get(idNumber)[buttonPositions[i]]); } currentQuestion++; } catch (Exception ex) { //if exception print System.out.println("Exception"); } }else{ //stop when the sequence has ended System.out.println("Exit"); System.exit(0); } } public static int[] getRandomPermutation (int length){ // initialize array and fill it with {0,1,2...} int[] array = new int[length]; for(int i = 0; i < array.length; i++) array[i] = i; for(int i = 0; i < length; i++){ // randomly chosen position in array whose element // will be swapped with the element in position i // note that when i = 0, any position can chosen (0 thru length-1) // when i = 1, only positions 1 through length -1 // NOTE: r is an instance of java.util.Random Random r = new Random(); int ran = i + r.nextInt (length-i); // perform swap int temp = array[i]; array[i] = array[ran]; array[ran] = temp; } return array; } }
10082_1
package nl.digitalthings.mebarista; import android.content.Context; import android.preference.DialogPreference; import android.util.AttributeSet; import android.view.View; import android.widget.TimePicker; import android.content.res.TypedArray; import android.text.format.DateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class TimePreference extends DialogPreference { private Calendar calendar; private TimePicker picker = null; public TimePreference(Context ctxt) { this(ctxt, null); } public TimePreference(Context ctxt, AttributeSet attrs) { this(ctxt, attrs, 0); } public TimePreference(Context ctxt, AttributeSet attrs, int defStyle) { super(ctxt, attrs, defStyle); setPositiveButtonText( "Set" ); setNegativeButtonText("Cancel"); calendar = Calendar.getInstance(); // new GregorianCalendar(); } @Override protected View onCreateDialogView() { picker = new TimePicker(getContext()); return (picker); } @Override protected void onBindDialogView(View v) { super.onBindDialogView(v); picker.setCurrentHour(calendar.get(Calendar.HOUR_OF_DAY)); picker.setCurrentMinute(calendar.get(Calendar.MINUTE)); } @Override protected void onDialogClosed(boolean positiveResult) { super.onDialogClosed(positiveResult); if (positiveResult) { System.out.println( "Selected HOUR " + picker.getCurrentHour() ); calendar.set(Calendar.HOUR_OF_DAY, picker.getCurrentHour()); calendar.set(Calendar.MINUTE, picker.getCurrentMinute()); setSummary(getSummary()); if (callChangeListener(calendar.getTimeInMillis())) { System.out.println( "dialog closed: "); Calendar fromMidnight; // = Calendar.getInstance(); //fromMidnight.setTimeInMillis(calendar.getTimeInMillis()); fromMidnight = (Calendar)calendar.clone(); // calendar.setTimeZone( fromMidnight.getTimeZone() ); fromMidnight.set(Calendar.HOUR_OF_DAY, 0); fromMidnight.set(Calendar.MINUTE, 0); fromMidnight.set(Calendar.SECOND, 0); fromMidnight.set(Calendar.MILLISECOND, 0); calendar.set( Calendar.SECOND, 0); calendar.set( Calendar.MILLISECOND, 0); calendar.set( Calendar.DST_OFFSET, 0); // dat hoeft misschien niet // persistLong((calendar.getTimeInMillis() - fromMidnight.getTimeInMillis()) / 1000); // persist in seconds! int val_seconds = calendar.get( Calendar.HOUR_OF_DAY ) * 60 * 60 + calendar.get( Calendar.MINUTE ) * 60; persistInt(val_seconds); //persist notifyChanged(); } } } @Override protected Object onGetDefaultValue(TypedArray a, int index) { return (a.getString(index)); } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { if (restoreValue) { if (false && defaultValue == null) { calendar.setTimeInMillis( getPersistedInt( 0/* System.currentTimeMillis() */ ) * 1000 ); } else { //Long stored_seconds = Long.parseLong(getPersistedString((String) defaultValue)); int stored_seconds = getPersistedInt(0); int hours = stored_seconds / 3600; calendar.set(Calendar.HOUR_OF_DAY, hours ); calendar.set(Calendar.MINUTE, ( stored_seconds - hours*3600 ) / 60 ); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); //calendar.setTimeInMillis( calendar.getTimeInMillis() + stored_millis ); } } else { if ( false && defaultValue == null) { calendar.setTimeInMillis( System.currentTimeMillis() ); } else { //Long stored_seconds = Long.parseLong(getPersistedString((String) defaultValue)); // Long stored_seconds = Long.parseLong(getPersistedString((String) defaultValue)); // int stored_seconds = Integer.parseInt( getPersistedString( "0" ) ); int stored_seconds = getPersistedInt(0); int hours = stored_seconds / 3600; calendar.set(Calendar.HOUR_OF_DAY, hours ); calendar.set(Calendar.MINUTE, ( stored_seconds - hours*3600 ) / 60 ); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); // calendar.setTimeInMillis( Long.parseLong((String) defaultValue) * 1000 ); } } setSummary(getSummary()); } @Override public CharSequence getSummary() { if (calendar == null) { return null; } return DateFormat.getTimeFormat(getContext()).format(new Date(calendar.getTimeInMillis())); } }
BrendanWalsh/mebarista
src/nl/digitalthings/mebarista/TimePreference.java
1,520
// dat hoeft misschien niet
line_comment
nl
package nl.digitalthings.mebarista; import android.content.Context; import android.preference.DialogPreference; import android.util.AttributeSet; import android.view.View; import android.widget.TimePicker; import android.content.res.TypedArray; import android.text.format.DateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class TimePreference extends DialogPreference { private Calendar calendar; private TimePicker picker = null; public TimePreference(Context ctxt) { this(ctxt, null); } public TimePreference(Context ctxt, AttributeSet attrs) { this(ctxt, attrs, 0); } public TimePreference(Context ctxt, AttributeSet attrs, int defStyle) { super(ctxt, attrs, defStyle); setPositiveButtonText( "Set" ); setNegativeButtonText("Cancel"); calendar = Calendar.getInstance(); // new GregorianCalendar(); } @Override protected View onCreateDialogView() { picker = new TimePicker(getContext()); return (picker); } @Override protected void onBindDialogView(View v) { super.onBindDialogView(v); picker.setCurrentHour(calendar.get(Calendar.HOUR_OF_DAY)); picker.setCurrentMinute(calendar.get(Calendar.MINUTE)); } @Override protected void onDialogClosed(boolean positiveResult) { super.onDialogClosed(positiveResult); if (positiveResult) { System.out.println( "Selected HOUR " + picker.getCurrentHour() ); calendar.set(Calendar.HOUR_OF_DAY, picker.getCurrentHour()); calendar.set(Calendar.MINUTE, picker.getCurrentMinute()); setSummary(getSummary()); if (callChangeListener(calendar.getTimeInMillis())) { System.out.println( "dialog closed: "); Calendar fromMidnight; // = Calendar.getInstance(); //fromMidnight.setTimeInMillis(calendar.getTimeInMillis()); fromMidnight = (Calendar)calendar.clone(); // calendar.setTimeZone( fromMidnight.getTimeZone() ); fromMidnight.set(Calendar.HOUR_OF_DAY, 0); fromMidnight.set(Calendar.MINUTE, 0); fromMidnight.set(Calendar.SECOND, 0); fromMidnight.set(Calendar.MILLISECOND, 0); calendar.set( Calendar.SECOND, 0); calendar.set( Calendar.MILLISECOND, 0); calendar.set( Calendar.DST_OFFSET, 0); // dat hoeft<SUF> // persistLong((calendar.getTimeInMillis() - fromMidnight.getTimeInMillis()) / 1000); // persist in seconds! int val_seconds = calendar.get( Calendar.HOUR_OF_DAY ) * 60 * 60 + calendar.get( Calendar.MINUTE ) * 60; persistInt(val_seconds); //persist notifyChanged(); } } } @Override protected Object onGetDefaultValue(TypedArray a, int index) { return (a.getString(index)); } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { if (restoreValue) { if (false && defaultValue == null) { calendar.setTimeInMillis( getPersistedInt( 0/* System.currentTimeMillis() */ ) * 1000 ); } else { //Long stored_seconds = Long.parseLong(getPersistedString((String) defaultValue)); int stored_seconds = getPersistedInt(0); int hours = stored_seconds / 3600; calendar.set(Calendar.HOUR_OF_DAY, hours ); calendar.set(Calendar.MINUTE, ( stored_seconds - hours*3600 ) / 60 ); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); //calendar.setTimeInMillis( calendar.getTimeInMillis() + stored_millis ); } } else { if ( false && defaultValue == null) { calendar.setTimeInMillis( System.currentTimeMillis() ); } else { //Long stored_seconds = Long.parseLong(getPersistedString((String) defaultValue)); // Long stored_seconds = Long.parseLong(getPersistedString((String) defaultValue)); // int stored_seconds = Integer.parseInt( getPersistedString( "0" ) ); int stored_seconds = getPersistedInt(0); int hours = stored_seconds / 3600; calendar.set(Calendar.HOUR_OF_DAY, hours ); calendar.set(Calendar.MINUTE, ( stored_seconds - hours*3600 ) / 60 ); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); // calendar.setTimeInMillis( Long.parseLong((String) defaultValue) * 1000 ); } } setSummary(getSummary()); } @Override public CharSequence getSummary() { if (calendar == null) { return null; } return DateFormat.getTimeFormat(getContext()).format(new Date(calendar.getTimeInMillis())); } }
201017_6
package game.model; import java.util.Collections; import java.util.Vector; /** * short description of Deck * * @author Brenden Jose * @version 1.0 * @since 27.06.2020 */ public class Deck { private Vector<Karte> deck; private int kartenImDeck; private int oberste; /** * Instantiates a new Deck. */ public Deck() { deck = new Vector<>(); deckherstellen(); } //Methoden /** * Deckherstellen. */ public void deckherstellen() { Karte.Symbol[] symbols = Karte.Symbol.values(); kartenImDeck = 0; for (int k = 0; k < 2; k++) { for (int i = 0; i < symbols.length; i++) { Karte.Symbol symbol = symbols[i]; for (int j = 0; j < 9; j++) { Karte karte = new Karte(symbol, Karte.Nummer.getNummer(j)); deck.add(karte); kartenImDeck++; } } } oberste = deck.size() - 1; assert deck.get(oberste) != null; } /** * Mischen. */ public void mischen() { Collections.shuffle(deck); } /** * Ziehen karte. * * @return the karte */ public Karte ziehen() { Karte gezogeneKarte = deck.get(oberste); deck.remove(gezogeneKarte); oberste--; kartenImDeck--; return gezogeneKarte; } /** * Add karte. * * @param karte the karte */ public void addKarte(Karte karte) { deck.add(karte); } /** * Deck leeren. */ public void deckLeeren() { deck.removeAll(deck); } /** * Gets karten im deck. * * @return the karten im deck */ public int getKartenImDeck() { return kartenImDeck; } public void setOberste(int oberste) { this.oberste = oberste; } }
Brenden7788/TschauSepp
src/game/model/Deck.java
640
/** * Deck leeren. */
block_comment
nl
package game.model; import java.util.Collections; import java.util.Vector; /** * short description of Deck * * @author Brenden Jose * @version 1.0 * @since 27.06.2020 */ public class Deck { private Vector<Karte> deck; private int kartenImDeck; private int oberste; /** * Instantiates a new Deck. */ public Deck() { deck = new Vector<>(); deckherstellen(); } //Methoden /** * Deckherstellen. */ public void deckherstellen() { Karte.Symbol[] symbols = Karte.Symbol.values(); kartenImDeck = 0; for (int k = 0; k < 2; k++) { for (int i = 0; i < symbols.length; i++) { Karte.Symbol symbol = symbols[i]; for (int j = 0; j < 9; j++) { Karte karte = new Karte(symbol, Karte.Nummer.getNummer(j)); deck.add(karte); kartenImDeck++; } } } oberste = deck.size() - 1; assert deck.get(oberste) != null; } /** * Mischen. */ public void mischen() { Collections.shuffle(deck); } /** * Ziehen karte. * * @return the karte */ public Karte ziehen() { Karte gezogeneKarte = deck.get(oberste); deck.remove(gezogeneKarte); oberste--; kartenImDeck--; return gezogeneKarte; } /** * Add karte. * * @param karte the karte */ public void addKarte(Karte karte) { deck.add(karte); } /** * Deck leeren. <SUF>*/ public void deckLeeren() { deck.removeAll(deck); } /** * Gets karten im deck. * * @return the karten im deck */ public int getKartenImDeck() { return kartenImDeck; } public void setOberste(int oberste) { this.oberste = oberste; } }
118907_4
package ui; import java.util.ArrayList; import java.util.Optional; import java.util.ResourceBundle; import domein.DomeinController; import domein.Ontwikkelingskaart; import exceptions.EdeleException; import exceptions.SpelRegelException; import javafx.event.ActionEvent; import javafx.geometry.Pos; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.control.ButtonBar.ButtonData; import javafx.scene.control.ButtonType; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; public class OntwikkelingskaartDeelScherm extends HBox { private int niveau; private DomeinController dc; private Button btnKaart; private Ontwikkelingskaart kaart; private ArrayList<Ontwikkelingskaart> lijst; private ResourceBundle bundle; private SpelScherm spelScherm; public OntwikkelingskaartDeelScherm(int niveau, DomeinController dc, SpelScherm spelScherm, ResourceBundle bundle) { this.niveau = niveau; this.dc = dc; this.bundle = bundle; this.spelScherm = spelScherm; lijst = new ArrayList<>(); this.setSpacing(10); this.setAlignment(Pos.CENTER); buildGui(); } private void buildGui() { Image stapel = new Image(getClass().getResourceAsStream(String.format("/images/Decks/niveau0%d.png", niveau))); ImageView vStapel = new ImageView(stapel); vStapel.setFitHeight(155); vStapel.setFitWidth(105); vStapel.setId("kaart"); if (dc.spel.getOntwikkelingskaartStapels().get(niveau - 1).size() == 0) { vStapel.setOpacity(0); } else { vStapel.setOpacity(100); } this.getChildren().add(vStapel); for (int i = 0; i < dc.geefOntwikkelingskaartVeld().get(niveau - 1).size(); i++) { kaart = dc.geefOntwikkelingskaartVeld().get(niveau - 1).get(i); lijst.add(kaart); this.getChildren().add(buildOntwikkelingskaart(kaart)); } } private Button buildOntwikkelingskaart(Ontwikkelingskaart kaart) { Image imgKaart = new Image(getClass().getResourceAsStream(String.format("/images/Ontwikkelingskaarten/%s.png", kaart.getImg()))); ImageView vKaart = new ImageView(imgKaart); vKaart.setFitHeight(150); vKaart.setFitWidth(100); btnKaart = new Button(); btnKaart.setGraphic(vKaart); btnKaart.setUserData(kaart); btnKaart.setOnAction(this::ontwikkelinskaartGekozen); return btnKaart; } private void ontwikkelinskaartGekozen(ActionEvent event) { Ontwikkelingskaart gekozenKaart = (Ontwikkelingskaart) ((Button) event.getSource()).getUserData(); try { vraagBevestiging(gekozenKaart); spelScherm.updateScherm(); } catch (SpelRegelException sre) { // Maak een Alert aan met het type ERROR Alert alert = new Alert(Alert.AlertType.INFORMATION); // Stel de titel en de boodschap van de Alert in alert.setTitle(bundle.getString("alertMelding")); alert.setHeaderText(null); alert.setContentText(bundle.getString(sre.getMessage())); // Toon de Alert alert.showAndWait(); } } public void vraagBevestiging(Ontwikkelingskaart gekozenKaart) { Alert alert = new Alert(AlertType.CONFIRMATION); alert.setTitle(bundle.getString("koopKaart")); alert.setHeaderText(bundle.getString("uSure")); // Toon de kaart nog eens Image image = new Image(getClass().getResourceAsStream(String.format("/images/Ontwikkelingskaarten/%s.png", gekozenKaart.getImg()))); ImageView imageView = new ImageView(image); imageView.setFitHeight(155); imageView.setFitWidth(105); // foto instellen alert.setGraphic(imageView); // Verander de tekst van de knoppen ButtonType jaButton = new ButtonType(bundle.getString("ja"), ButtonData.OK_DONE); ButtonType neeButton = new ButtonType(bundle.getString("nee"), ButtonData.CANCEL_CLOSE); alert.getButtonTypes().setAll(jaButton, neeButton); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == jaButton) { try { dc.neemKaart(niveau - 1, lijst.indexOf(gekozenKaart)); } catch (EdeleException ee) { spelScherm.kiesEdele(ee.getEdelen()); } // spelScherm.edeleGekozen(); } } }
BrentDeClercq/Splendor
src/ui/OntwikkelingskaartDeelScherm.java
1,560
// Verander de tekst van de knoppen
line_comment
nl
package ui; import java.util.ArrayList; import java.util.Optional; import java.util.ResourceBundle; import domein.DomeinController; import domein.Ontwikkelingskaart; import exceptions.EdeleException; import exceptions.SpelRegelException; import javafx.event.ActionEvent; import javafx.geometry.Pos; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.control.ButtonBar.ButtonData; import javafx.scene.control.ButtonType; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; public class OntwikkelingskaartDeelScherm extends HBox { private int niveau; private DomeinController dc; private Button btnKaart; private Ontwikkelingskaart kaart; private ArrayList<Ontwikkelingskaart> lijst; private ResourceBundle bundle; private SpelScherm spelScherm; public OntwikkelingskaartDeelScherm(int niveau, DomeinController dc, SpelScherm spelScherm, ResourceBundle bundle) { this.niveau = niveau; this.dc = dc; this.bundle = bundle; this.spelScherm = spelScherm; lijst = new ArrayList<>(); this.setSpacing(10); this.setAlignment(Pos.CENTER); buildGui(); } private void buildGui() { Image stapel = new Image(getClass().getResourceAsStream(String.format("/images/Decks/niveau0%d.png", niveau))); ImageView vStapel = new ImageView(stapel); vStapel.setFitHeight(155); vStapel.setFitWidth(105); vStapel.setId("kaart"); if (dc.spel.getOntwikkelingskaartStapels().get(niveau - 1).size() == 0) { vStapel.setOpacity(0); } else { vStapel.setOpacity(100); } this.getChildren().add(vStapel); for (int i = 0; i < dc.geefOntwikkelingskaartVeld().get(niveau - 1).size(); i++) { kaart = dc.geefOntwikkelingskaartVeld().get(niveau - 1).get(i); lijst.add(kaart); this.getChildren().add(buildOntwikkelingskaart(kaart)); } } private Button buildOntwikkelingskaart(Ontwikkelingskaart kaart) { Image imgKaart = new Image(getClass().getResourceAsStream(String.format("/images/Ontwikkelingskaarten/%s.png", kaart.getImg()))); ImageView vKaart = new ImageView(imgKaart); vKaart.setFitHeight(150); vKaart.setFitWidth(100); btnKaart = new Button(); btnKaart.setGraphic(vKaart); btnKaart.setUserData(kaart); btnKaart.setOnAction(this::ontwikkelinskaartGekozen); return btnKaart; } private void ontwikkelinskaartGekozen(ActionEvent event) { Ontwikkelingskaart gekozenKaart = (Ontwikkelingskaart) ((Button) event.getSource()).getUserData(); try { vraagBevestiging(gekozenKaart); spelScherm.updateScherm(); } catch (SpelRegelException sre) { // Maak een Alert aan met het type ERROR Alert alert = new Alert(Alert.AlertType.INFORMATION); // Stel de titel en de boodschap van de Alert in alert.setTitle(bundle.getString("alertMelding")); alert.setHeaderText(null); alert.setContentText(bundle.getString(sre.getMessage())); // Toon de Alert alert.showAndWait(); } } public void vraagBevestiging(Ontwikkelingskaart gekozenKaart) { Alert alert = new Alert(AlertType.CONFIRMATION); alert.setTitle(bundle.getString("koopKaart")); alert.setHeaderText(bundle.getString("uSure")); // Toon de kaart nog eens Image image = new Image(getClass().getResourceAsStream(String.format("/images/Ontwikkelingskaarten/%s.png", gekozenKaart.getImg()))); ImageView imageView = new ImageView(image); imageView.setFitHeight(155); imageView.setFitWidth(105); // foto instellen alert.setGraphic(imageView); // Verander de<SUF> ButtonType jaButton = new ButtonType(bundle.getString("ja"), ButtonData.OK_DONE); ButtonType neeButton = new ButtonType(bundle.getString("nee"), ButtonData.CANCEL_CLOSE); alert.getButtonTypes().setAll(jaButton, neeButton); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == jaButton) { try { dc.neemKaart(niveau - 1, lijst.indexOf(gekozenKaart)); } catch (EdeleException ee) { spelScherm.kiesEdele(ee.getEdelen()); } // spelScherm.edeleGekozen(); } } }
19582_0
package com.discord.bots; import org.javacord.api.DiscordApi; import org.javacord.api.DiscordApiBuilder; import org.javacord.api.entity.message.MessageAuthor; import org.javacord.api.entity.message.MessageBuilder; import org.javacord.api.entity.message.embed.EmbedBuilder; import org.javacord.api.entity.user.UserStatus; import org.javacord.api.interaction.SlashCommand; import org.json.JSONObject; import javax.xml.transform.Result; import java.awt.*; import java.io.File; import java.sql.*; import java.util.Random; public class Main { public static String prefix = "$$"; public static void main(String[] args) { // inloggen op discord DiscordApi api = new DiscordApiBuilder() .setToken("discord-bot-token") .login().join(); // command dat alle commands in een embed zet api.addMessageCreateListener(eventShCommands -> { if (eventShCommands.getMessageContent().trim().equalsIgnoreCase(prefix + "commands")) { EmbedBuilder embed = new EmbedBuilder() .setTitle("Commands!") .setDescription("A short list of all commands that this bot adds") .addInlineField("Ping", "Replies with pong") .addInlineField("Copy text", "Replies with a copy of the text you wrote after copy") .addInlineField("Name", "Replies with your name") .addInlineField("ID", "Replies with your ID") .addInlineField("Level", "Replies with your Discord level") .addInlineField("Commands", "Shows the list of commands you are currently looking at"); eventShCommands.getChannel().sendMessage(embed); } }); // checkt elk bericht api.addMessageCreateListener(event -> { // pak standaard gegevents uit bericht MessageAuthor eventMA = event.getMessageAuthor(); long discordID = eventMA.getId(); String discordName = eventMA.getName(); System.out.println("Initializing user " + discordName + " with ID " + discordID); try { // connect met de DB Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Discord", "username", "password"); System.out.println(discordID + " connection to DB initialized\n"); Statement statement = con.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT * FROM users WHERE discordID='" + discordID + "'"); System.out.println("Checking if user is in DB or not: "); // checkt of user die bericht stuurt in DB zit // result.next is negatief als die resultset leeg is if (!resultSet.next()) { // voer user aan DB toe als negatief System.out.print("!! User not in DB, adding!! "); // je krijgt 50 xp voor je eerste bericht statement.execute("INSERT INTO users (discordID,discordUsername,totalSentMessages, serverLevel,serverXp) VALUES (" + discordID + ", '" + discordName + "',1,0,50);"); } else { // nieuwe user toevoegen System.out.println("!! User in db !!"); // oude gegevens int oldXp = resultSet.getInt(5); int level = (resultSet.getInt(4)); Random rand = new Random(); // nieuwe xp berekenen int wonXp; int messageLength = event.getMessageContent().length(); if (level < 75) { wonXp = rand.nextInt(messageLength + 100 - level); } else { wonXp = rand.nextInt(messageLength + 25); } // checken of de user genoeg xp heeft voor levelup if (oldXp + wonXp > 1000) { statement.execute("UPDATE users " + "SET totalSentMessages = totalSentMessages + 1" + ", serverLevel = serverLevel + 1 " + ", serverXp = '" + 0 + "'" + "WHERE discordID = '" + discordID + "'"); event.getChannel().sendMessage("<@" + discordID + "> has leveled up to level " + (level + 1)); } else { System.out.println("Increasing messagecount (2) and xp"); statement.execute("UPDATE users " + "SET totalSentMessages = totalSentMessages + 1" + ", serverXp = serverXp + '" + wonXp + "'" + "WHERE discordID = '" + discordID + "'"); } } } catch (SQLException e) { throw new RuntimeException(e); } }); // id finder command api.addMessageCreateListener(eventCheckID -> { if (eventCheckID.getMessageContent().trim().equalsIgnoreCase(prefix + "ID")) { MessageAuthor eventMessageAuthor = eventCheckID.getMessageAuthor(); long discordID = eventMessageAuthor.getId(); eventCheckID.getChannel().sendMessage(String.valueOf(discordID)); } }); // level checker command api.addMessageCreateListener(eventCheckLevel -> { if (eventCheckLevel.getMessageContent().trim().equalsIgnoreCase(prefix + "level")) { MessageAuthor eventMA = eventCheckLevel.getMessageAuthor(); long discordID = eventMA.getId(); try { Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Discord", "root", "1234"); Statement statement = con.createStatement(); ResultSet resultS = statement.executeQuery("SELECT serverLevel FROM users WHERE discordID=" + discordID); if (resultS.next() == true) { int level = (resultS.getInt(1)); eventCheckLevel.getChannel().sendMessage("User <@" + discordID + "> you are level " + level); } else { eventCheckLevel.getChannel().sendMessage("You are not in the DB"); } } catch (SQLException e) { throw new RuntimeException(e); } } }); // $$ping -> reply with: "Pong!" api.addMessageCreateListener(eventPing -> { if (eventPing.getMessageContent().equalsIgnoreCase(prefix + "ping")) { eventPing.getChannel().sendMessage("Pong!"); } }); // copy arguments api.addMessageCreateListener(eventCopy -> { if (eventCopy.getMessageContent().substring(0, 6).equalsIgnoreCase(prefix + "copy")) { eventCopy.getChannel().sendMessage(eventCopy.getMessageContent().substring(6)); System.out.println("copy message tried\n"); } }); // replies with users name api.addMessageCreateListener(eventName -> { if (eventName.getMessageContent().substring(0, 6).equalsIgnoreCase(prefix + "name")) { eventName.getChannel().sendMessage(eventName.getMessageAuthor().getName()); } }); } }
BrentSimons/Java-DiscordBot-MySQL
src/main/java/com/discord/bots/Main.java
1,993
// inloggen op discord
line_comment
nl
package com.discord.bots; import org.javacord.api.DiscordApi; import org.javacord.api.DiscordApiBuilder; import org.javacord.api.entity.message.MessageAuthor; import org.javacord.api.entity.message.MessageBuilder; import org.javacord.api.entity.message.embed.EmbedBuilder; import org.javacord.api.entity.user.UserStatus; import org.javacord.api.interaction.SlashCommand; import org.json.JSONObject; import javax.xml.transform.Result; import java.awt.*; import java.io.File; import java.sql.*; import java.util.Random; public class Main { public static String prefix = "$$"; public static void main(String[] args) { // inloggen op<SUF> DiscordApi api = new DiscordApiBuilder() .setToken("discord-bot-token") .login().join(); // command dat alle commands in een embed zet api.addMessageCreateListener(eventShCommands -> { if (eventShCommands.getMessageContent().trim().equalsIgnoreCase(prefix + "commands")) { EmbedBuilder embed = new EmbedBuilder() .setTitle("Commands!") .setDescription("A short list of all commands that this bot adds") .addInlineField("Ping", "Replies with pong") .addInlineField("Copy text", "Replies with a copy of the text you wrote after copy") .addInlineField("Name", "Replies with your name") .addInlineField("ID", "Replies with your ID") .addInlineField("Level", "Replies with your Discord level") .addInlineField("Commands", "Shows the list of commands you are currently looking at"); eventShCommands.getChannel().sendMessage(embed); } }); // checkt elk bericht api.addMessageCreateListener(event -> { // pak standaard gegevents uit bericht MessageAuthor eventMA = event.getMessageAuthor(); long discordID = eventMA.getId(); String discordName = eventMA.getName(); System.out.println("Initializing user " + discordName + " with ID " + discordID); try { // connect met de DB Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Discord", "username", "password"); System.out.println(discordID + " connection to DB initialized\n"); Statement statement = con.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT * FROM users WHERE discordID='" + discordID + "'"); System.out.println("Checking if user is in DB or not: "); // checkt of user die bericht stuurt in DB zit // result.next is negatief als die resultset leeg is if (!resultSet.next()) { // voer user aan DB toe als negatief System.out.print("!! User not in DB, adding!! "); // je krijgt 50 xp voor je eerste bericht statement.execute("INSERT INTO users (discordID,discordUsername,totalSentMessages, serverLevel,serverXp) VALUES (" + discordID + ", '" + discordName + "',1,0,50);"); } else { // nieuwe user toevoegen System.out.println("!! User in db !!"); // oude gegevens int oldXp = resultSet.getInt(5); int level = (resultSet.getInt(4)); Random rand = new Random(); // nieuwe xp berekenen int wonXp; int messageLength = event.getMessageContent().length(); if (level < 75) { wonXp = rand.nextInt(messageLength + 100 - level); } else { wonXp = rand.nextInt(messageLength + 25); } // checken of de user genoeg xp heeft voor levelup if (oldXp + wonXp > 1000) { statement.execute("UPDATE users " + "SET totalSentMessages = totalSentMessages + 1" + ", serverLevel = serverLevel + 1 " + ", serverXp = '" + 0 + "'" + "WHERE discordID = '" + discordID + "'"); event.getChannel().sendMessage("<@" + discordID + "> has leveled up to level " + (level + 1)); } else { System.out.println("Increasing messagecount (2) and xp"); statement.execute("UPDATE users " + "SET totalSentMessages = totalSentMessages + 1" + ", serverXp = serverXp + '" + wonXp + "'" + "WHERE discordID = '" + discordID + "'"); } } } catch (SQLException e) { throw new RuntimeException(e); } }); // id finder command api.addMessageCreateListener(eventCheckID -> { if (eventCheckID.getMessageContent().trim().equalsIgnoreCase(prefix + "ID")) { MessageAuthor eventMessageAuthor = eventCheckID.getMessageAuthor(); long discordID = eventMessageAuthor.getId(); eventCheckID.getChannel().sendMessage(String.valueOf(discordID)); } }); // level checker command api.addMessageCreateListener(eventCheckLevel -> { if (eventCheckLevel.getMessageContent().trim().equalsIgnoreCase(prefix + "level")) { MessageAuthor eventMA = eventCheckLevel.getMessageAuthor(); long discordID = eventMA.getId(); try { Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Discord", "root", "1234"); Statement statement = con.createStatement(); ResultSet resultS = statement.executeQuery("SELECT serverLevel FROM users WHERE discordID=" + discordID); if (resultS.next() == true) { int level = (resultS.getInt(1)); eventCheckLevel.getChannel().sendMessage("User <@" + discordID + "> you are level " + level); } else { eventCheckLevel.getChannel().sendMessage("You are not in the DB"); } } catch (SQLException e) { throw new RuntimeException(e); } } }); // $$ping -> reply with: "Pong!" api.addMessageCreateListener(eventPing -> { if (eventPing.getMessageContent().equalsIgnoreCase(prefix + "ping")) { eventPing.getChannel().sendMessage("Pong!"); } }); // copy arguments api.addMessageCreateListener(eventCopy -> { if (eventCopy.getMessageContent().substring(0, 6).equalsIgnoreCase(prefix + "copy")) { eventCopy.getChannel().sendMessage(eventCopy.getMessageContent().substring(6)); System.out.println("copy message tried\n"); } }); // replies with users name api.addMessageCreateListener(eventName -> { if (eventName.getMessageContent().substring(0, 6).equalsIgnoreCase(prefix + "name")) { eventName.getChannel().sendMessage(eventName.getMessageAuthor().getName()); } }); } }
191298_0
import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.util.ArrayList; /** * @Author Carlijn Fransen * @author Brian van Wessel * @Version 1 * @Since 1 */ public class ORFGUI extends JFrame { protected JPanel oRFPredictionToolPanel; protected JTextField readFastaField; protected JButton uploadFastaButton; protected JButton zoekFileButton; protected JComboBox stopCodonComboBox; protected JComboBox startCodonComboBox; protected JLabel uploadFileStatusLabel; protected JButton findORFsButton; protected JComboBox chooseORFComboBox; protected JButton blastButton; protected JComboBox minimalORFLengthComboBox; protected JTable resultsTable; /** * The function setORFResultsTable adds the ORF results into the JTABLE. * @param results an Array containing ORF results. */ public void setORFResultsTable(String[][] results){ String [] column = {"ORF_Start","ORF_Stop","Readingframe","ORF_ID"}; DefaultTableModel model = new DefaultTableModel(results,column); resultsTable.setModel(model); resultsTable.setVisible(true); } /** * The function setORFCombobox adds all ORFs into chooseORFCombobox. * @param usedORFIDS an Arraylist ocntaining all found ORFS. */ public void setORFComobox(ArrayList<String> usedORFIDS){ for (int i = 0;i < usedORFIDS.size();i++){ chooseORFComboBox.addItem(usedORFIDS.get(i)); } } /** * The function setALLResultsTaBLE adds all Results into the JTABLE * @param results an Array containing all results. */ public void setALLResultsTable(String[][] results){ String [] column = {"ORF_Start","ORF_Stop","Readingframe","BlAST_start","BLAST_stop","Percentage_identity","E_value"}; DefaultTableModel model = new DefaultTableModel(results,column); resultsTable.setModel(model); resultsTable.setVisible(true); } /** * The function setBLASTResultsTable adds all BLAST results into the JTABLE * @param results an array containing all BLAST results. */ public void setBLASTResultsTable(String[][] results){ String [] column = {"BLAST_Start","BLAST_Stop","Percentage_identity","E_value"}; DefaultTableModel model = new DefaultTableModel(results,column); resultsTable.setModel(model); resultsTable.setVisible(true); } }
Brianvanwessel/ORFpredictionTool
src/main/java/ORFGUI.java
711
/** * @Author Carlijn Fransen * @author Brian van Wessel * @Version 1 * @Since 1 */
block_comment
nl
import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.util.ArrayList; /** * @Author Carlijn Fransen<SUF>*/ public class ORFGUI extends JFrame { protected JPanel oRFPredictionToolPanel; protected JTextField readFastaField; protected JButton uploadFastaButton; protected JButton zoekFileButton; protected JComboBox stopCodonComboBox; protected JComboBox startCodonComboBox; protected JLabel uploadFileStatusLabel; protected JButton findORFsButton; protected JComboBox chooseORFComboBox; protected JButton blastButton; protected JComboBox minimalORFLengthComboBox; protected JTable resultsTable; /** * The function setORFResultsTable adds the ORF results into the JTABLE. * @param results an Array containing ORF results. */ public void setORFResultsTable(String[][] results){ String [] column = {"ORF_Start","ORF_Stop","Readingframe","ORF_ID"}; DefaultTableModel model = new DefaultTableModel(results,column); resultsTable.setModel(model); resultsTable.setVisible(true); } /** * The function setORFCombobox adds all ORFs into chooseORFCombobox. * @param usedORFIDS an Arraylist ocntaining all found ORFS. */ public void setORFComobox(ArrayList<String> usedORFIDS){ for (int i = 0;i < usedORFIDS.size();i++){ chooseORFComboBox.addItem(usedORFIDS.get(i)); } } /** * The function setALLResultsTaBLE adds all Results into the JTABLE * @param results an Array containing all results. */ public void setALLResultsTable(String[][] results){ String [] column = {"ORF_Start","ORF_Stop","Readingframe","BlAST_start","BLAST_stop","Percentage_identity","E_value"}; DefaultTableModel model = new DefaultTableModel(results,column); resultsTable.setModel(model); resultsTable.setVisible(true); } /** * The function setBLASTResultsTable adds all BLAST results into the JTABLE * @param results an array containing all BLAST results. */ public void setBLASTResultsTable(String[][] results){ String [] column = {"BLAST_Start","BLAST_Stop","Percentage_identity","E_value"}; DefaultTableModel model = new DefaultTableModel(results,column); resultsTable.setModel(model); resultsTable.setVisible(true); } }
58785_0
package com.example.helloworld; public class Car { private String color; private String model; private int speed; private Human owner; public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public int getSpeed() { return speed; } public void setSpeed(int speed) { this.speed = speed; } public Human getOwner() { return owner; } public void setOwner(Human owner) { this.owner = owner; } //amazing addition //wel in branche ilone, maar nog niet in master private int id; //nog een hoop nieuwe dingen die nergens op slaan //maar dat komt later wel }
BrightBoost/hello-world
src/com/example/helloworld/Car.java
249
//wel in branche ilone, maar nog niet in master
line_comment
nl
package com.example.helloworld; public class Car { private String color; private String model; private int speed; private Human owner; public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public int getSpeed() { return speed; } public void setSpeed(int speed) { this.speed = speed; } public Human getOwner() { return owner; } public void setOwner(Human owner) { this.owner = owner; } //amazing addition //wel in<SUF> private int id; //nog een hoop nieuwe dingen die nergens op slaan //maar dat komt later wel }
40048_6
package exceptionsfun; import java.io.FileReader; import java.io.IOException; public class ExceptionExamples { // unchecked exceptions voorbeeld, op te lossen met beter coderen // in dit geval if statement public static void ohNoUnchecked() { String[] strings = null; //{ "!" }; int i = 1; if(strings != null && strings.length > i) { System.out.println(strings[i]); } } // checked exception, handling voorbeeld 1 public static void ohNoChecked1() throws IOException { String fileName = "blabla.txt"; FileReader fr = new FileReader(fileName); int ch; while((ch = fr.read()) != -1) { System.out.print((char)ch); } fr.close(); } // checked exception, handling voorbeeld 2 public static void ohNoChecked2() { String fileName = "blabla.txt"; FileReader fr = null; try { fr = new FileReader(fileName); int ch; while((ch = fr.read()) != -1) { System.out.print((char)ch); } fr.close(); } catch (IOException e) { e.printStackTrace(); } finally { try { if(fr != null) { fr.close(); } } catch (IOException e) { e.printStackTrace(); } } } // checked exception, handling voorbeeld 3 public static void ohNoChecked3() { String fileName = "blabla.txt"; try(FileReader fr = new FileReader(fileName)) { int ch; while((ch = fr.read()) != -1) { System.out.print((char)ch); } } catch(IOException e) { e.printStackTrace(); } } // zelf exception gooien public static void ohNoThrowException() { throw new IllegalArgumentException("blablabla"); } // zelf eigen exception gooien public static void ohNoThrowMyOwnException() { throw new VerkeerdeNaamException("dit klopt niet"); } public static void main(String[] args) { ohNoUnchecked(); ohNoChecked2(); ohNoChecked3(); try { ohNoChecked1(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Lalalalal"); } }
BrightBoost/java2april
src/exceptionsfun/ExceptionExamples.java
663
// zelf exception gooien
line_comment
nl
package exceptionsfun; import java.io.FileReader; import java.io.IOException; public class ExceptionExamples { // unchecked exceptions voorbeeld, op te lossen met beter coderen // in dit geval if statement public static void ohNoUnchecked() { String[] strings = null; //{ "!" }; int i = 1; if(strings != null && strings.length > i) { System.out.println(strings[i]); } } // checked exception, handling voorbeeld 1 public static void ohNoChecked1() throws IOException { String fileName = "blabla.txt"; FileReader fr = new FileReader(fileName); int ch; while((ch = fr.read()) != -1) { System.out.print((char)ch); } fr.close(); } // checked exception, handling voorbeeld 2 public static void ohNoChecked2() { String fileName = "blabla.txt"; FileReader fr = null; try { fr = new FileReader(fileName); int ch; while((ch = fr.read()) != -1) { System.out.print((char)ch); } fr.close(); } catch (IOException e) { e.printStackTrace(); } finally { try { if(fr != null) { fr.close(); } } catch (IOException e) { e.printStackTrace(); } } } // checked exception, handling voorbeeld 3 public static void ohNoChecked3() { String fileName = "blabla.txt"; try(FileReader fr = new FileReader(fileName)) { int ch; while((ch = fr.read()) != -1) { System.out.print((char)ch); } } catch(IOException e) { e.printStackTrace(); } } // zelf exception<SUF> public static void ohNoThrowException() { throw new IllegalArgumentException("blablabla"); } // zelf eigen exception gooien public static void ohNoThrowMyOwnException() { throw new VerkeerdeNaamException("dit klopt niet"); } public static void main(String[] args) { ohNoUnchecked(); ohNoChecked2(); ohNoChecked3(); try { ohNoChecked1(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Lalalalal"); } }
121811_3
package org.example.exceptionsfun; import java.io.FileReader; import java.io.IOException; public class ExceptionExamples { // unchecked exceptions voorbeeld, op te lossen met beter coderen // in dit geval if statement public static void ohNoUnchecked() { String[] strings = null; //{ "!" }; int i = 1; if(strings != null && strings.length > i) { System.out.println(strings[i]); } } // checked exception, handling voorbeeld 1 public static void ohNoChecked1() throws IOException { String fileName = "blabla.txt"; FileReader fr = new FileReader(fileName); int ch; while((ch = fr.read()) != -1) { System.out.print((char)ch); } fr.close(); } // checked exception, handling voorbeeld 2 public static void ohNoChecked2() { String fileName = "blabla.txt"; FileReader fr = null; try { fr = new FileReader(fileName); int ch; while((ch = fr.read()) != -1) { System.out.print((char)ch); } fr.close(); } catch (IOException e) { e.printStackTrace(); } finally { try { if(fr != null) { fr.close(); } } catch (IOException e) { e.printStackTrace(); } } } // checked exception, handling voorbeeld 3 public static void ohNoChecked3() { String fileName = "blabla.txt"; try(FileReader fr = new FileReader(fileName)) { int ch; while((ch = fr.read()) != -1) { System.out.print((char)ch); } } catch(IOException e) { e.printStackTrace(); } } // zelf exception gooien public static void ohNoThrowException() { throw new IllegalArgumentException("blablabla"); } // zelf eigen exception gooien public static void ohNoThrowMyOwnException() { throw new VerkeerdeNaamException("dit klopt niet"); } public static void main(String[] args) { ohNoUnchecked(); ohNoChecked2(); ohNoChecked3(); try { ohNoChecked1(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Lalalalal"); } }
BrightBoost/java9april
src/main/java/org/example/exceptionsfun/ExceptionExamples.java
668
// checked exception, handling voorbeeld 1
line_comment
nl
package org.example.exceptionsfun; import java.io.FileReader; import java.io.IOException; public class ExceptionExamples { // unchecked exceptions voorbeeld, op te lossen met beter coderen // in dit geval if statement public static void ohNoUnchecked() { String[] strings = null; //{ "!" }; int i = 1; if(strings != null && strings.length > i) { System.out.println(strings[i]); } } // checked exception,<SUF> public static void ohNoChecked1() throws IOException { String fileName = "blabla.txt"; FileReader fr = new FileReader(fileName); int ch; while((ch = fr.read()) != -1) { System.out.print((char)ch); } fr.close(); } // checked exception, handling voorbeeld 2 public static void ohNoChecked2() { String fileName = "blabla.txt"; FileReader fr = null; try { fr = new FileReader(fileName); int ch; while((ch = fr.read()) != -1) { System.out.print((char)ch); } fr.close(); } catch (IOException e) { e.printStackTrace(); } finally { try { if(fr != null) { fr.close(); } } catch (IOException e) { e.printStackTrace(); } } } // checked exception, handling voorbeeld 3 public static void ohNoChecked3() { String fileName = "blabla.txt"; try(FileReader fr = new FileReader(fileName)) { int ch; while((ch = fr.read()) != -1) { System.out.print((char)ch); } } catch(IOException e) { e.printStackTrace(); } } // zelf exception gooien public static void ohNoThrowException() { throw new IllegalArgumentException("blablabla"); } // zelf eigen exception gooien public static void ohNoThrowMyOwnException() { throw new VerkeerdeNaamException("dit klopt niet"); } public static void main(String[] args) { ohNoUnchecked(); ohNoChecked2(); ohNoChecked3(); try { ohNoChecked1(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Lalalalal"); } }
106837_2
package day3; import java.util.Arrays; public class StreamExamples { public static void main(String[] args) { int[] ints = {1, 23, 4, 6, 2, 8}; //enkel source + terminal operation long aantalInts = Arrays.stream(ints).count(); System.out.println("aantal: " + aantalInts); //source + 1 intermediate + terminal operation //tel hoeveel getallen groter dan 10 long aantalGroterDan10 = Arrays.stream(ints) .filter((i) -> i > 10) .count(); System.out.println("aantal groter dan 10:" + aantalGroterDan10); // sorteer + print Arrays.stream(ints) .sorted() .forEach((i) -> System.out.println(i)); // maak een stream + filter op getallen kleiner dan 10 // + sorteer + print Arrays.stream(ints) .filter(i -> i <10) .sorted() .forEach(i -> System.out.println(i)); String[] names = { "bob", "bo", "bas", "mo"}; Arrays.stream(names) .filter(s -> s.startsWith("b")) .sorted() .forEach(s -> System.out.println(s)); // maak een stream van fruitsoorten // filter op meer dan 5 letters // sorteer // limiteer naar 2 met de limit(2) methode // print de fruitsoorten String[] fruits = { "grapefruit", "lemon", "grapes", "kiwiwi", "gappel" }; Arrays.stream(fruits) .filter(fruit -> fruit.length() > 5) .sorted() .limit(2) .forEach(fruit -> System.out.println(fruit)); // maak een stream van fruitsoorten // filter op begint met * insert letter die je hebt* // skip er 1 .skip(1) // sorteer // print System.out.println("xxxxx§"); Arrays.stream(fruits) .filter(fruit -> fruit.startsWith("g")) .skip(1) .sorted() .forEach(i -> System.out.println(i)); } }
BrightBoost/july2022java
src/main/java/day3/StreamExamples.java
642
//tel hoeveel getallen groter dan 10
line_comment
nl
package day3; import java.util.Arrays; public class StreamExamples { public static void main(String[] args) { int[] ints = {1, 23, 4, 6, 2, 8}; //enkel source + terminal operation long aantalInts = Arrays.stream(ints).count(); System.out.println("aantal: " + aantalInts); //source + 1 intermediate + terminal operation //tel hoeveel<SUF> long aantalGroterDan10 = Arrays.stream(ints) .filter((i) -> i > 10) .count(); System.out.println("aantal groter dan 10:" + aantalGroterDan10); // sorteer + print Arrays.stream(ints) .sorted() .forEach((i) -> System.out.println(i)); // maak een stream + filter op getallen kleiner dan 10 // + sorteer + print Arrays.stream(ints) .filter(i -> i <10) .sorted() .forEach(i -> System.out.println(i)); String[] names = { "bob", "bo", "bas", "mo"}; Arrays.stream(names) .filter(s -> s.startsWith("b")) .sorted() .forEach(s -> System.out.println(s)); // maak een stream van fruitsoorten // filter op meer dan 5 letters // sorteer // limiteer naar 2 met de limit(2) methode // print de fruitsoorten String[] fruits = { "grapefruit", "lemon", "grapes", "kiwiwi", "gappel" }; Arrays.stream(fruits) .filter(fruit -> fruit.length() > 5) .sorted() .limit(2) .forEach(fruit -> System.out.println(fruit)); // maak een stream van fruitsoorten // filter op begint met * insert letter die je hebt* // skip er 1 .skip(1) // sorteer // print System.out.println("xxxxx§"); Arrays.stream(fruits) .filter(fruit -> fruit.startsWith("g")) .skip(1) .sorted() .forEach(i -> System.out.println(i)); } }
178223_2
package dag15; import java.lang.constant.Constable; public class Java17Switch { enum KLEUREN { BLAUW, GEEL, ROOD; } public static void main(String[] args) { int x = 8; switch(x) { default: System.out.println("Wat is dit?"); break; case 0: System.out.println("X is nul"); break; case 1: System.out.println("X is een"); break; case 2: System.out.println("X is twee"); break; } // nieuwe versie, geen break nodig bij -> switch(x) { case 0 -> System.out.println("X is nul"); case 1 -> { System.out.println("X is een"); break; } // dit mag case 2 -> System.out.println("X is twee"); default -> System.out.println("Wat is dit?"); } // waarde returnen met switch statement String getal = switch(x) { case 0 -> "X is nul"; case 1 -> "X is een"; case 2 -> "X is twee"; default -> "Wat is dit?"; }; // waarde returnen met switch statement en expliciet yield String getal1 = switch(x) { case 0: yield "X is nul"; case 1: yield "X is een"; case 2: yield "X is twee"; default: yield "Wat is dit?"; }; // waarde returnen met switch statement en meer acties String getal2 = switch(x) { case 0 -> { System.out.println("Het is nul :)"); yield "X is nul"; } case 1 -> "X is een"; case 2 -> "X is twee"; default -> "Wat is dit?"; }; // enums en switch KLEUREN kleur = KLEUREN.GEEL; String s; switch (kleur) { case ROOD: System.out.println("rood"); s = "rood"; break; case BLAUW: System.out.println("blauw"); s = "blauw"; break; case GEEL: s = "geel"; break; default: s = "watdan?!"; } System.out.println(s); // als je alle labels behandelt geen default nodig var s1 = switch (kleur) { case ROOD -> "rood"; case BLAUW -> KLEUREN.BLAUW; case GEEL -> 2; }; System.out.println(s1 + " " + s1.getClass()); } }
BrightBoost/ocp
src/main/java/dag15/Java17Switch.java
754
// waarde returnen met switch statement en expliciet yield
line_comment
nl
package dag15; import java.lang.constant.Constable; public class Java17Switch { enum KLEUREN { BLAUW, GEEL, ROOD; } public static void main(String[] args) { int x = 8; switch(x) { default: System.out.println("Wat is dit?"); break; case 0: System.out.println("X is nul"); break; case 1: System.out.println("X is een"); break; case 2: System.out.println("X is twee"); break; } // nieuwe versie, geen break nodig bij -> switch(x) { case 0 -> System.out.println("X is nul"); case 1 -> { System.out.println("X is een"); break; } // dit mag case 2 -> System.out.println("X is twee"); default -> System.out.println("Wat is dit?"); } // waarde returnen met switch statement String getal = switch(x) { case 0 -> "X is nul"; case 1 -> "X is een"; case 2 -> "X is twee"; default -> "Wat is dit?"; }; // waarde returnen<SUF> String getal1 = switch(x) { case 0: yield "X is nul"; case 1: yield "X is een"; case 2: yield "X is twee"; default: yield "Wat is dit?"; }; // waarde returnen met switch statement en meer acties String getal2 = switch(x) { case 0 -> { System.out.println("Het is nul :)"); yield "X is nul"; } case 1 -> "X is een"; case 2 -> "X is twee"; default -> "Wat is dit?"; }; // enums en switch KLEUREN kleur = KLEUREN.GEEL; String s; switch (kleur) { case ROOD: System.out.println("rood"); s = "rood"; break; case BLAUW: System.out.println("blauw"); s = "blauw"; break; case GEEL: s = "geel"; break; default: s = "watdan?!"; } System.out.println(s); // als je alle labels behandelt geen default nodig var s1 = switch (kleur) { case ROOD -> "rood"; case BLAUW -> KLEUREN.BLAUW; case GEEL -> 2; }; System.out.println(s1 + " " + s1.getClass()); } }
90511_1
package org.example.day1; public class PrimitivesAndWrappers { public static void main(String[] args) { // round nrs int i = 8; long l = 8L; byte b = 12; short s = 300; char c = 'c'; // decimals double d = 4.5; float f = 4.5f; //boolean boolean bool = true; // wrapper classes Integer i1 = 8; Long l1 = 8L; Byte b1 = 12; Short s1 = 300; Character c1 = 'c'; // decimals Double d1 = 4.5; Float f1 = 4.5f; //boolean Boolean bool1 = true; // dit mag niet - deprecated Integer i2 = new Integer(54); // valueof Integer i3 = Integer.valueOf(3); System.out.println("wat" + i3); // pas op met dit soort vragen (getal te groot voor integer, moet L achter) long l2 = 1231231231233L; // integer grapjes System.out.println(Integer.MAX_VALUE + 1); } }
BrightBoost/ocp17
src/main/java/org/example/day1/PrimitivesAndWrappers.java
326
// pas op met dit soort vragen (getal te groot voor integer, moet L achter)
line_comment
nl
package org.example.day1; public class PrimitivesAndWrappers { public static void main(String[] args) { // round nrs int i = 8; long l = 8L; byte b = 12; short s = 300; char c = 'c'; // decimals double d = 4.5; float f = 4.5f; //boolean boolean bool = true; // wrapper classes Integer i1 = 8; Long l1 = 8L; Byte b1 = 12; Short s1 = 300; Character c1 = 'c'; // decimals Double d1 = 4.5; Float f1 = 4.5f; //boolean Boolean bool1 = true; // dit mag niet - deprecated Integer i2 = new Integer(54); // valueof Integer i3 = Integer.valueOf(3); System.out.println("wat" + i3); // pas op<SUF> long l2 = 1231231231233L; // integer grapjes System.out.println(Integer.MAX_VALUE + 1); } }
30836_0
package game.spawner; import java.util.ArrayList; import java.util.List; import java.util.Random; import game.movement.Direction; import game.objects.background.BackgroundObject; import game.objects.enemies.Enemy; import VisualAndAudioData.DataClass; import game.objects.enemies.enums.EnemyEnums; import javax.xml.crypto.Data; public class SpawningCoordinator { private static SpawningCoordinator instance = new SpawningCoordinator(); private Random random = new Random(); // Al deze ranges moeten eigenlijk dynamisch berekend worden, want nu is het // niet resizable private int maximumBGOWidthRange = DataClass.getInstance().getWindowWidth() + 200; private int minimumBGOWidthRange = -200; private int maximumBGOHeightRange = DataClass.getInstance().getWindowHeight(); private int minimumBGOHeightRange = 0; private int maximumBombEnemyHeightDownRange = 0; private int minimumBombEnemyHeightDownRange = -200; //Left Spawning block private int leftEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() - 100; private int leftEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMinHeight(); private int leftEnemyMaxWidthRange = 500; private int leftEnemyMinWidthRange = 100; private int bottomLeftEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() - 100; private int bottomLeftEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() + 50; private int topLeftEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMinHeight(); private int topLeftEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMinHeight() + 100; //Right Spawning block private int rightEnemyMaxWidthRange = DataClass.getInstance().getWindowWidth() + 200; private int rightEnemyMinWidthRange = DataClass.getInstance().getWindowWidth(); private int rightEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() - 100; private int rightEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMinHeight() + 100; private int bottomRightEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() - 100; private int bottomRightEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() + 50; private int topRightEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMinHeight() + 100; private int topRightEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMinHeight() + 200; //Up spawning block private int upEnemyMaxWidthRange = DataClass.getInstance().getWindowWidth() - 50; private int upEnemyMinWidthRange = 100; private int upEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMinHeight() + 150; private int upEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMinHeight(); //Down spawning block private int downEnemyMaxWidthRange = DataClass.getInstance().getWindowWidth() - 50; private int downEnemyMinWidthRange = 50; private int downEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() + 200; private int downEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() + 50; private SpawningCoordinator () { } public static SpawningCoordinator getInstance () { return instance; } //Function used to prevent enemies of the same type of stacking on top of each other when being spawned in public boolean checkValidEnemyXCoordinate (Enemy enemyType, List<Enemy> listToCheck, int xCoordinate, int minimumRange) { for (Enemy enemy : listToCheck) { if (!enemy.getEnemyType().equals(EnemyEnums.Alien_Bomb)) { if (Math.abs(enemy.getXCoordinate() - xCoordinate) < minimumRange) { return false; } } } return true; } //Function used to prevent enemies of the same type of stacking on top of each other when being spawned in public boolean checkValidEnemyYCoordinate (Enemy enemyType, List<Enemy> listToCheck, int yCoordinate, int minimumRange) { for (Enemy enemy : listToCheck) { if (!enemy.getEnemyType().equals(EnemyEnums.Alien_Bomb)) { if (Math.abs(enemy.getYCoordinate() - yCoordinate) < minimumRange) { return false; } } } return true; } public int getRightBlockXCoordinate () { return random.nextInt((rightEnemyMaxWidthRange - rightEnemyMinWidthRange) + 1) + rightEnemyMinWidthRange; } public int getRightBlockYCoordinate () { return random.nextInt((rightEnemyMaxHeightRange - rightEnemyMinHeightRange) + 1) + rightEnemyMinHeightRange; } public int getBottomRightBlockYCoordinate () { return random.nextInt((bottomRightEnemyMaxHeightRange - bottomRightEnemyMinHeightRange) + 1) + bottomRightEnemyMinHeightRange; } public int getTopRightBlockYCoordinate () { return 0 - random.nextInt((topRightEnemyMaxHeightRange - topRightEnemyMinHeightRange) + 1) + topRightEnemyMinHeightRange; } public int getLeftBlockXCoordinate () { return 0 - random.nextInt((leftEnemyMaxWidthRange - leftEnemyMinWidthRange) + 1) + leftEnemyMinWidthRange; } public int getLeftBlockYCoordinate () { return random.nextInt((leftEnemyMaxHeightRange - leftEnemyMinHeightRange) + 1) + leftEnemyMinHeightRange; } public int getBottomLeftBlockYCoordinate () { return random.nextInt((bottomLeftEnemyMaxHeightRange - bottomLeftEnemyMinHeightRange) + 1) + bottomLeftEnemyMinHeightRange; } public int getTopLeftBlockYCoordinate () { return 0 - random.nextInt((topLeftEnemyMaxHeightRange - topLeftEnemyMinHeightRange) + 1) + topLeftEnemyMinHeightRange; } public int getUpBlockXCoordinate () { return random.nextInt((upEnemyMaxWidthRange - upEnemyMinWidthRange) + 1) + upEnemyMinWidthRange; } public int getUpBlockYCoordinate () { return 0 - random.nextInt((upEnemyMaxHeightRange - upEnemyMinHeightRange) + 1) + upEnemyMinHeightRange; } public int getDownBlockXCoordinate () { return random.nextInt((downEnemyMaxWidthRange - downEnemyMinWidthRange) + 1) + downEnemyMinWidthRange; } public int getDownBlockYCoordinate () { return random.nextInt((downEnemyMaxHeightRange - downEnemyMinHeightRange) + 1) + downEnemyMinHeightRange; } public int getRandomXBombEnemyCoordinate () { return random.nextInt((downEnemyMaxWidthRange - downEnemyMinWidthRange) + 1) + downEnemyMinWidthRange; } //Recently swapped public int getRandomYDownBombEnemyCoordinate () { return random.nextInt((downEnemyMaxHeightRange - downEnemyMinHeightRange) + 1) + downEnemyMinHeightRange; } public int getRandomYUpBombEnemyCoordinate () { return 0 - random.nextInt((upEnemyMaxHeightRange - upEnemyMinHeightRange) + 1) + upEnemyMinHeightRange; } public Direction upOrDown () { int randInt = random.nextInt((1 - 0) + 1) + 0; switch (randInt) { case (0): return Direction.DOWN; case (1): return Direction.UP; } return Direction.UP; } // Random functions used for Background objects // public boolean checkValidBGOXCoordinate (List<BackgroundObject> listToCheck, int xCoordinate, int size) { for (BackgroundObject bgObject : listToCheck) { if (Math.abs(bgObject.getXCoordinate() - xCoordinate) < size) { return false; } } return true; } public boolean checkValidBGOYCoordinate (List<BackgroundObject> listToCheck, int yCoordinate, int size) { for (BackgroundObject bgObject : listToCheck) { if (Math.abs(bgObject.getYCoordinate() - yCoordinate) < size) { return false; } } return true; } public int getRandomXBGOCoordinate () { return random.nextInt((maximumBGOWidthRange - minimumBGOWidthRange) + 1) + minimumBGOWidthRange; } public int getRandomYBGOCoordinate () { return random.nextInt((maximumBGOHeightRange - minimumBGOHeightRange) + 1) + minimumBGOHeightRange; } public List<Integer> getSpawnCoordinatesByDirection (Direction direction) { List<Integer> coordinatesList = new ArrayList<Integer>(); if (direction.equals(Direction.LEFT)) { coordinatesList.add(getRightBlockXCoordinate()); coordinatesList.add(getRightBlockYCoordinate()); } else if (direction.equals(Direction.RIGHT)) { coordinatesList.add(getLeftBlockXCoordinate()); coordinatesList.add(getLeftBlockYCoordinate()); } else if (direction.equals(Direction.DOWN)) { coordinatesList.add(getUpBlockXCoordinate()); coordinatesList.add(getUpBlockYCoordinate()); } else if (direction.equals(Direction.UP)) { coordinatesList.add(getDownBlockXCoordinate()); coordinatesList.add(getDownBlockYCoordinate()); } else if (direction.equals(Direction.LEFT_UP)) { coordinatesList.add(getRightBlockXCoordinate()); coordinatesList.add(getBottomRightBlockYCoordinate()); } else if (direction.equals(Direction.LEFT_DOWN)) { coordinatesList.add(getRightBlockXCoordinate()); coordinatesList.add(getTopRightBlockYCoordinate()); } else if (direction.equals(Direction.RIGHT_UP)) { coordinatesList.add(getLeftBlockXCoordinate()); coordinatesList.add(getBottomLeftBlockYCoordinate()); } else if (direction.equals(Direction.RIGHT_DOWN)) { coordinatesList.add(getLeftBlockXCoordinate()); coordinatesList.add(getTopLeftBlockYCoordinate()); } return coordinatesList; } }
Broozer29/Game
src/main/java/game/spawner/SpawningCoordinator.java
2,825
// Al deze ranges moeten eigenlijk dynamisch berekend worden, want nu is het
line_comment
nl
package game.spawner; import java.util.ArrayList; import java.util.List; import java.util.Random; import game.movement.Direction; import game.objects.background.BackgroundObject; import game.objects.enemies.Enemy; import VisualAndAudioData.DataClass; import game.objects.enemies.enums.EnemyEnums; import javax.xml.crypto.Data; public class SpawningCoordinator { private static SpawningCoordinator instance = new SpawningCoordinator(); private Random random = new Random(); // Al deze<SUF> // niet resizable private int maximumBGOWidthRange = DataClass.getInstance().getWindowWidth() + 200; private int minimumBGOWidthRange = -200; private int maximumBGOHeightRange = DataClass.getInstance().getWindowHeight(); private int minimumBGOHeightRange = 0; private int maximumBombEnemyHeightDownRange = 0; private int minimumBombEnemyHeightDownRange = -200; //Left Spawning block private int leftEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() - 100; private int leftEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMinHeight(); private int leftEnemyMaxWidthRange = 500; private int leftEnemyMinWidthRange = 100; private int bottomLeftEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() - 100; private int bottomLeftEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() + 50; private int topLeftEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMinHeight(); private int topLeftEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMinHeight() + 100; //Right Spawning block private int rightEnemyMaxWidthRange = DataClass.getInstance().getWindowWidth() + 200; private int rightEnemyMinWidthRange = DataClass.getInstance().getWindowWidth(); private int rightEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() - 100; private int rightEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMinHeight() + 100; private int bottomRightEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() - 100; private int bottomRightEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() + 50; private int topRightEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMinHeight() + 100; private int topRightEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMinHeight() + 200; //Up spawning block private int upEnemyMaxWidthRange = DataClass.getInstance().getWindowWidth() - 50; private int upEnemyMinWidthRange = 100; private int upEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMinHeight() + 150; private int upEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMinHeight(); //Down spawning block private int downEnemyMaxWidthRange = DataClass.getInstance().getWindowWidth() - 50; private int downEnemyMinWidthRange = 50; private int downEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() + 200; private int downEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() + 50; private SpawningCoordinator () { } public static SpawningCoordinator getInstance () { return instance; } //Function used to prevent enemies of the same type of stacking on top of each other when being spawned in public boolean checkValidEnemyXCoordinate (Enemy enemyType, List<Enemy> listToCheck, int xCoordinate, int minimumRange) { for (Enemy enemy : listToCheck) { if (!enemy.getEnemyType().equals(EnemyEnums.Alien_Bomb)) { if (Math.abs(enemy.getXCoordinate() - xCoordinate) < minimumRange) { return false; } } } return true; } //Function used to prevent enemies of the same type of stacking on top of each other when being spawned in public boolean checkValidEnemyYCoordinate (Enemy enemyType, List<Enemy> listToCheck, int yCoordinate, int minimumRange) { for (Enemy enemy : listToCheck) { if (!enemy.getEnemyType().equals(EnemyEnums.Alien_Bomb)) { if (Math.abs(enemy.getYCoordinate() - yCoordinate) < minimumRange) { return false; } } } return true; } public int getRightBlockXCoordinate () { return random.nextInt((rightEnemyMaxWidthRange - rightEnemyMinWidthRange) + 1) + rightEnemyMinWidthRange; } public int getRightBlockYCoordinate () { return random.nextInt((rightEnemyMaxHeightRange - rightEnemyMinHeightRange) + 1) + rightEnemyMinHeightRange; } public int getBottomRightBlockYCoordinate () { return random.nextInt((bottomRightEnemyMaxHeightRange - bottomRightEnemyMinHeightRange) + 1) + bottomRightEnemyMinHeightRange; } public int getTopRightBlockYCoordinate () { return 0 - random.nextInt((topRightEnemyMaxHeightRange - topRightEnemyMinHeightRange) + 1) + topRightEnemyMinHeightRange; } public int getLeftBlockXCoordinate () { return 0 - random.nextInt((leftEnemyMaxWidthRange - leftEnemyMinWidthRange) + 1) + leftEnemyMinWidthRange; } public int getLeftBlockYCoordinate () { return random.nextInt((leftEnemyMaxHeightRange - leftEnemyMinHeightRange) + 1) + leftEnemyMinHeightRange; } public int getBottomLeftBlockYCoordinate () { return random.nextInt((bottomLeftEnemyMaxHeightRange - bottomLeftEnemyMinHeightRange) + 1) + bottomLeftEnemyMinHeightRange; } public int getTopLeftBlockYCoordinate () { return 0 - random.nextInt((topLeftEnemyMaxHeightRange - topLeftEnemyMinHeightRange) + 1) + topLeftEnemyMinHeightRange; } public int getUpBlockXCoordinate () { return random.nextInt((upEnemyMaxWidthRange - upEnemyMinWidthRange) + 1) + upEnemyMinWidthRange; } public int getUpBlockYCoordinate () { return 0 - random.nextInt((upEnemyMaxHeightRange - upEnemyMinHeightRange) + 1) + upEnemyMinHeightRange; } public int getDownBlockXCoordinate () { return random.nextInt((downEnemyMaxWidthRange - downEnemyMinWidthRange) + 1) + downEnemyMinWidthRange; } public int getDownBlockYCoordinate () { return random.nextInt((downEnemyMaxHeightRange - downEnemyMinHeightRange) + 1) + downEnemyMinHeightRange; } public int getRandomXBombEnemyCoordinate () { return random.nextInt((downEnemyMaxWidthRange - downEnemyMinWidthRange) + 1) + downEnemyMinWidthRange; } //Recently swapped public int getRandomYDownBombEnemyCoordinate () { return random.nextInt((downEnemyMaxHeightRange - downEnemyMinHeightRange) + 1) + downEnemyMinHeightRange; } public int getRandomYUpBombEnemyCoordinate () { return 0 - random.nextInt((upEnemyMaxHeightRange - upEnemyMinHeightRange) + 1) + upEnemyMinHeightRange; } public Direction upOrDown () { int randInt = random.nextInt((1 - 0) + 1) + 0; switch (randInt) { case (0): return Direction.DOWN; case (1): return Direction.UP; } return Direction.UP; } // Random functions used for Background objects // public boolean checkValidBGOXCoordinate (List<BackgroundObject> listToCheck, int xCoordinate, int size) { for (BackgroundObject bgObject : listToCheck) { if (Math.abs(bgObject.getXCoordinate() - xCoordinate) < size) { return false; } } return true; } public boolean checkValidBGOYCoordinate (List<BackgroundObject> listToCheck, int yCoordinate, int size) { for (BackgroundObject bgObject : listToCheck) { if (Math.abs(bgObject.getYCoordinate() - yCoordinate) < size) { return false; } } return true; } public int getRandomXBGOCoordinate () { return random.nextInt((maximumBGOWidthRange - minimumBGOWidthRange) + 1) + minimumBGOWidthRange; } public int getRandomYBGOCoordinate () { return random.nextInt((maximumBGOHeightRange - minimumBGOHeightRange) + 1) + minimumBGOHeightRange; } public List<Integer> getSpawnCoordinatesByDirection (Direction direction) { List<Integer> coordinatesList = new ArrayList<Integer>(); if (direction.equals(Direction.LEFT)) { coordinatesList.add(getRightBlockXCoordinate()); coordinatesList.add(getRightBlockYCoordinate()); } else if (direction.equals(Direction.RIGHT)) { coordinatesList.add(getLeftBlockXCoordinate()); coordinatesList.add(getLeftBlockYCoordinate()); } else if (direction.equals(Direction.DOWN)) { coordinatesList.add(getUpBlockXCoordinate()); coordinatesList.add(getUpBlockYCoordinate()); } else if (direction.equals(Direction.UP)) { coordinatesList.add(getDownBlockXCoordinate()); coordinatesList.add(getDownBlockYCoordinate()); } else if (direction.equals(Direction.LEFT_UP)) { coordinatesList.add(getRightBlockXCoordinate()); coordinatesList.add(getBottomRightBlockYCoordinate()); } else if (direction.equals(Direction.LEFT_DOWN)) { coordinatesList.add(getRightBlockXCoordinate()); coordinatesList.add(getTopRightBlockYCoordinate()); } else if (direction.equals(Direction.RIGHT_UP)) { coordinatesList.add(getLeftBlockXCoordinate()); coordinatesList.add(getBottomLeftBlockYCoordinate()); } else if (direction.equals(Direction.RIGHT_DOWN)) { coordinatesList.add(getLeftBlockXCoordinate()); coordinatesList.add(getTopLeftBlockYCoordinate()); } return coordinatesList; } }
167540_0
package be.kdg.thegame_2048.views.game; import be.kdg.thegame_2048.models.Game; import be.kdg.thegame_2048.models.PlayerManager; import be.kdg.thegame_2048.views.undo.UndoPresenter; import be.kdg.thegame_2048.views.undo.UndoView; import be.kdg.thegame_2048.views.highscores.HighScorePresenter; import be.kdg.thegame_2048.views.highscores.HighScoreView; import be.kdg.thegame_2048.views.result.ResultPresenter; import be.kdg.thegame_2048.views.result.ResultView; import be.kdg.thegame_2048.views.start.StartPresenter; import be.kdg.thegame_2048.views.start.StartView; import javafx.scene.input.KeyCode; import javafx.util.Duration; /** * @author Jarne Van Aerde, Bryan de Ridder * @version 1.0 17/02/2017 9:28 */ public class GamePresenter { private Game modelGame; private final PlayerManager modelPlayerManager; private final GameView view; private final GameBottomView bottomView; private final GameMiddleView midView; private final GameTopView topView; private final Animation animation; private boolean alreadyWon; private boolean firstRun; private int prevScore; private int currentScore; public GamePresenter(Game modelGame, PlayerManager modelPlayerManager, GameView view) { this.modelGame = modelGame; this.modelPlayerManager = modelPlayerManager; this.view = view; this.bottomView = view.getBottomView(); this.midView = view.getMiddleView(); this.topView = view.getTopView(); this.animation = new Animation(topView, midView, this); this.firstRun = true; this.addEventHandlers(); this.currentScore = modelGame.getScore(); updateViewScore(currentScore); updateView(); } private void addEventHandlers() { this.bottomView.getBtnRestart().setOnAction(event -> { this.alreadyWon = false; this.firstRun = true; if (!modelGame.isPlayingUndo()) modelPlayerManager.saveInfoCurrentPlayer(); this.modelGame = new Game(); this.topView.getLblCurrentScoreInput().setText("0"); disableUndoButton(false); updateView(); }); this.bottomView.getBtnUndo().setOnAction(event -> { UndoView alert = new UndoView(); new UndoPresenter(modelGame, alert, view, this); this.view.setView(alert); }); this.bottomView.getBtnHighScores().setOnAction(event -> { if (!modelGame.isPlayingUndo()) modelPlayerManager.saveInfoCurrentPlayer(); HighScoreView hsView = new HighScoreView(); new HighScorePresenter(modelGame, modelPlayerManager, hsView); this.view.getScene().setRoot(hsView); }); this.bottomView.getBtnExit().setOnAction(event -> { if (!modelGame.isPlayingUndo()) modelPlayerManager.saveInfoCurrentPlayer(); modelPlayerManager.setCurrentPlayerToNull(); StartView startView = new StartView(); new StartPresenter(modelPlayerManager, startView); this.view.getScene().setRoot(startView); }); this.view.setOnKeyPressed(event -> { if (animation.getParallelTransition().getStatus() != javafx.animation.Animation.Status.RUNNING) { final KeyCode direction = event.getCode(); this.prevScore = modelGame.getScore(); switch (direction) { case DOWN: updateViewBlocks(Game.Direction.DOWN); animation.animateMovement(direction); break; case UP: updateViewBlocks(Game.Direction.UP); animation.animateMovement(direction); break; case RIGHT: updateViewBlocks(Game.Direction.RIGHT); animation.animateMovement(direction); break; case LEFT: updateViewBlocks(Game.Direction.LEFT); animation.animateMovement(direction); break; default: event.consume(); } this.currentScore = modelGame.getScore(); updateViewScore(currentScore); if (currentScore - prevScore > 0) { this.animation.animateScore(currentScore - prevScore); } } }); this.animation.getParallelTransition().setOnFinished(event -> { this.animation.resetMoveAnimation(); updateView(); }); } /** * Transfers all calculated model output to the GameView. * Also decides which block should get a popIn animation. **/ public void updateView() { int randomblockX = modelGame.getCoordRandomBlockX(); int randomblockY = modelGame.getCoordRandomBlockY(); updateRandomBlockView(randomblockX, randomblockY); for (int i = 0; i < GameMiddleView.GRID_SIZE; i++) { for (int j = 0; j < GameMiddleView.GRID_SIZE; j++) { int value = getModelBlockValue(i, j); if (firstRun) { midView.changeBlockValue(value, i, j); animation.popIn(i, j); } else if (!(i == randomblockX && j == randomblockY)) { midView.changeBlockValue(value, i, j); } } } this.firstRun = false; } private void updateRandomBlockView(int x, int y) { if (!firstRun && isMovable()) { animation.popIn(y, x); midView.changeBlockValue(2, x, y); } } private int getModelBlockValue(int x, int y) { if (modelGame.getPiece(x, y) == null) return 0; return modelGame.getPieceValue(x, y); } /** * After a move key is pressed, first animates blocks into a certain direction. * Then transfers its direction to the model classes. * @param direction should contain the direction for the game model class. **/ private void updateViewBlocks(Game.Direction direction) { modelGame.runGameCycle(direction); checkIfLostOrWin(); } /** * Scores on the top of the view are updated. * @param score can contain the current score or any other score. * * als score hoger is dan topscore -> topscore = score * score = altijd inputscore * **/ public void updateViewScore(int score) { this.modelPlayerManager.setCurrentPlayerScore(score); int bestScore = modelPlayerManager.getCurrentPlayer().getBestScore(); this.topView.getLblBestScoreInput().setText(String.valueOf(bestScore)); if (score >= bestScore) { this.topView.getLblBestScoreInput().setText(String.valueOf(score)); } this.topView.getLblCurrentScoreInput().setText(String.valueOf(score)); } /** * Model classes check if the player has won or lost. * If so, the resultView must be shown. **/ private void checkIfLostOrWin() { if (!modelGame.hasLost() && alreadyWon) return; if (modelGame.hasLost() || modelGame.hasWon()) { alreadyWon = true; if (!modelGame.isPlayingUndo()) modelPlayerManager.saveInfoCurrentPlayer(); ResultView resultView = new ResultView(); new ResultPresenter(modelPlayerManager, resultView, modelGame, view); view.setView(resultView); } } /** * @return true if there are any moves left. **/ boolean isMovable() { if (modelGame.getLastMove() != null) if (!modelGame.getLastMove().equals(modelGame.getCurrentMove())) { return true; } return false; } public int getPrevScore() { return prevScore; } public void disableUndoButton(boolean bool) { bottomView.getBtnUndo().setDisable(bool); } }
Bryanx/2048
src/be/kdg/thegame_2048/views/game/GamePresenter.java
2,241
/** * @author Jarne Van Aerde, Bryan de Ridder * @version 1.0 17/02/2017 9:28 */
block_comment
nl
package be.kdg.thegame_2048.views.game; import be.kdg.thegame_2048.models.Game; import be.kdg.thegame_2048.models.PlayerManager; import be.kdg.thegame_2048.views.undo.UndoPresenter; import be.kdg.thegame_2048.views.undo.UndoView; import be.kdg.thegame_2048.views.highscores.HighScorePresenter; import be.kdg.thegame_2048.views.highscores.HighScoreView; import be.kdg.thegame_2048.views.result.ResultPresenter; import be.kdg.thegame_2048.views.result.ResultView; import be.kdg.thegame_2048.views.start.StartPresenter; import be.kdg.thegame_2048.views.start.StartView; import javafx.scene.input.KeyCode; import javafx.util.Duration; /** * @author Jarne Van<SUF>*/ public class GamePresenter { private Game modelGame; private final PlayerManager modelPlayerManager; private final GameView view; private final GameBottomView bottomView; private final GameMiddleView midView; private final GameTopView topView; private final Animation animation; private boolean alreadyWon; private boolean firstRun; private int prevScore; private int currentScore; public GamePresenter(Game modelGame, PlayerManager modelPlayerManager, GameView view) { this.modelGame = modelGame; this.modelPlayerManager = modelPlayerManager; this.view = view; this.bottomView = view.getBottomView(); this.midView = view.getMiddleView(); this.topView = view.getTopView(); this.animation = new Animation(topView, midView, this); this.firstRun = true; this.addEventHandlers(); this.currentScore = modelGame.getScore(); updateViewScore(currentScore); updateView(); } private void addEventHandlers() { this.bottomView.getBtnRestart().setOnAction(event -> { this.alreadyWon = false; this.firstRun = true; if (!modelGame.isPlayingUndo()) modelPlayerManager.saveInfoCurrentPlayer(); this.modelGame = new Game(); this.topView.getLblCurrentScoreInput().setText("0"); disableUndoButton(false); updateView(); }); this.bottomView.getBtnUndo().setOnAction(event -> { UndoView alert = new UndoView(); new UndoPresenter(modelGame, alert, view, this); this.view.setView(alert); }); this.bottomView.getBtnHighScores().setOnAction(event -> { if (!modelGame.isPlayingUndo()) modelPlayerManager.saveInfoCurrentPlayer(); HighScoreView hsView = new HighScoreView(); new HighScorePresenter(modelGame, modelPlayerManager, hsView); this.view.getScene().setRoot(hsView); }); this.bottomView.getBtnExit().setOnAction(event -> { if (!modelGame.isPlayingUndo()) modelPlayerManager.saveInfoCurrentPlayer(); modelPlayerManager.setCurrentPlayerToNull(); StartView startView = new StartView(); new StartPresenter(modelPlayerManager, startView); this.view.getScene().setRoot(startView); }); this.view.setOnKeyPressed(event -> { if (animation.getParallelTransition().getStatus() != javafx.animation.Animation.Status.RUNNING) { final KeyCode direction = event.getCode(); this.prevScore = modelGame.getScore(); switch (direction) { case DOWN: updateViewBlocks(Game.Direction.DOWN); animation.animateMovement(direction); break; case UP: updateViewBlocks(Game.Direction.UP); animation.animateMovement(direction); break; case RIGHT: updateViewBlocks(Game.Direction.RIGHT); animation.animateMovement(direction); break; case LEFT: updateViewBlocks(Game.Direction.LEFT); animation.animateMovement(direction); break; default: event.consume(); } this.currentScore = modelGame.getScore(); updateViewScore(currentScore); if (currentScore - prevScore > 0) { this.animation.animateScore(currentScore - prevScore); } } }); this.animation.getParallelTransition().setOnFinished(event -> { this.animation.resetMoveAnimation(); updateView(); }); } /** * Transfers all calculated model output to the GameView. * Also decides which block should get a popIn animation. **/ public void updateView() { int randomblockX = modelGame.getCoordRandomBlockX(); int randomblockY = modelGame.getCoordRandomBlockY(); updateRandomBlockView(randomblockX, randomblockY); for (int i = 0; i < GameMiddleView.GRID_SIZE; i++) { for (int j = 0; j < GameMiddleView.GRID_SIZE; j++) { int value = getModelBlockValue(i, j); if (firstRun) { midView.changeBlockValue(value, i, j); animation.popIn(i, j); } else if (!(i == randomblockX && j == randomblockY)) { midView.changeBlockValue(value, i, j); } } } this.firstRun = false; } private void updateRandomBlockView(int x, int y) { if (!firstRun && isMovable()) { animation.popIn(y, x); midView.changeBlockValue(2, x, y); } } private int getModelBlockValue(int x, int y) { if (modelGame.getPiece(x, y) == null) return 0; return modelGame.getPieceValue(x, y); } /** * After a move key is pressed, first animates blocks into a certain direction. * Then transfers its direction to the model classes. * @param direction should contain the direction for the game model class. **/ private void updateViewBlocks(Game.Direction direction) { modelGame.runGameCycle(direction); checkIfLostOrWin(); } /** * Scores on the top of the view are updated. * @param score can contain the current score or any other score. * * als score hoger is dan topscore -> topscore = score * score = altijd inputscore * **/ public void updateViewScore(int score) { this.modelPlayerManager.setCurrentPlayerScore(score); int bestScore = modelPlayerManager.getCurrentPlayer().getBestScore(); this.topView.getLblBestScoreInput().setText(String.valueOf(bestScore)); if (score >= bestScore) { this.topView.getLblBestScoreInput().setText(String.valueOf(score)); } this.topView.getLblCurrentScoreInput().setText(String.valueOf(score)); } /** * Model classes check if the player has won or lost. * If so, the resultView must be shown. **/ private void checkIfLostOrWin() { if (!modelGame.hasLost() && alreadyWon) return; if (modelGame.hasLost() || modelGame.hasWon()) { alreadyWon = true; if (!modelGame.isPlayingUndo()) modelPlayerManager.saveInfoCurrentPlayer(); ResultView resultView = new ResultView(); new ResultPresenter(modelPlayerManager, resultView, modelGame, view); view.setView(resultView); } } /** * @return true if there are any moves left. **/ boolean isMovable() { if (modelGame.getLastMove() != null) if (!modelGame.getLastMove().equals(modelGame.getCurrentMove())) { return true; } return false; } public int getPrevScore() { return prevScore; } public void disableUndoButton(boolean bool) { bottomView.getBtnUndo().setDisable(bool); } }
128133_52
package be.evavzw.eva21daychallenge.activity.challenges; import android.Manifest; import android.app.Activity; import android.app.FragmentManager; import android.content.Context; import android.content.Intent; import android.content.IntentSender; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.Point; import android.location.Location; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.LocationSettingsRequest; import com.google.android.gms.location.LocationSettingsResult; import com.google.android.gms.location.LocationSettingsStatusCodes; import com.bumptech.glide.Glide; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMapOptions; import com.google.android.gms.maps.MapFragment; 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.LatLngBounds; import com.google.android.gms.maps.model.MarkerOptions; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import be.evavzw.eva21daychallenge.R; import be.evavzw.eva21daychallenge.models.Restaurant; import be.evavzw.eva21daychallenge.services.ChallengeManager; /** * Created by Pieter-Jan on 4/11/2015. */ public class RestaurantListFragment extends ChallengeFragment implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener, ResultCallback<LocationSettingsResult> { private static final String TAG = "RestaurantListFragment"; /** * Constant used in the location settings dialog. */ private static final int REQUEST_CHECK_SETTINGS = 0x1; /** * The desired interval for location updates. Inexact. Updates may be more or less frequent. */ private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 1000; /** * The fastest rate for active location updates. Exact. Updates will never be more frequent * than this value. */ private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS; /** * Provides the entry point to Google Play services. */ private GoogleApiClient mGoogleApiClient; /** * Stores parameters for requests to the FusedLocationProviderApi. */ private LocationRequest mLocationRequest; /** * Stores the types of location services the client is interested in using. Used for checking * settings to determine if the device has optimal location settings. */ private LocationSettingsRequest mLocationSettingsRequest; /** * Represents a geographical location. */ private Location mCurrentLocation; /** * Tracks the status of the location updates request. Value changes when the user presses the * Start Updates and Stop Updates buttons. */ private Boolean mRequestingLocationUpdates; private ChallengeManager challengeManager; private List<Restaurant> restaurants = new ArrayList<>(); private RecyclerView rv; private FrameLayout spinnerContainer; private ProgressBar spinner; private TextView notFound; private GoogleMap googleMap; private SupportMapFragment fragment; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.restaurant_challenge, container, false); //setupTitle(layout); challengeManager = ChallengeManager.getInstance(getContext()); rv = (RecyclerView) layout.findViewById(R.id.restaurantList); rv.setLayoutManager(new LinearLayoutManager(rv.getContext())); //setupRecyclerView(rv); spinnerContainer = (FrameLayout) layout.findViewById(R.id.list_spinner_container); spinner = (ProgressBar) layout.findViewById(R.id.list_spinner); notFound = (TextView) layout.findViewById(R.id.not_found); //new FetchRestaurantsTask(rv).execute(); //fetchChallenges(); setRetainInstance(true); //new FetchRestaurantsTask(rv).execute(); return layout; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mRequestingLocationUpdates = false; buildGoogleApiClient(); createLocationRequest(); buildLocationSettingsRequest(); if (Build.VERSION.SDK_INT >= 23) { askLocationPermission(); } else { checkLocationSettings(); } android.support.v4.app.FragmentManager fm = getChildFragmentManager(); fragment = (SupportMapFragment) fm.findFragmentById(R.id.restaurantMapFragment); if(fragment == null){ GoogleMapOptions options = new GoogleMapOptions().liteMode(true); fragment = SupportMapFragment.newInstance(options); fm.beginTransaction().replace(R.id.restaurantMapFragment, fragment).commit(); } } private void askLocationPermission() { if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 200); } else { checkLocationSettings(); } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { Log.i(TAG, "PERMISSION CALLBACK"); if (requestCode == 200) { if (grantResults.length != 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { checkLocationSettings(); } } } /** * Builds a GoogleApiClient. Uses the {@code #addApi} method to request the * LocationServices API. */ protected synchronized void buildGoogleApiClient() { Log.i(TAG, "Building GoogleApiClient"); mGoogleApiClient = new GoogleApiClient.Builder(getContext()) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } /** * Sets up the location request. Android has two location request settings: * {@code ACCESS_COARSE_LOCATION} and {@code ACCESS_FINE_LOCATION}. These settings control * the accuracy of the current location. This sample uses ACCESS_FINE_LOCATION, as defined in * the AndroidManifest.xml. * <p/> * When the ACCESS_FINE_LOCATION setting is specified, combined with a fast update * interval (5 seconds), the Fused Location Provider API returns location updates that are * accurate to within a few feet. * <p/> * These settings are appropriate for mapping applications that show real-time location * updates. */ protected void createLocationRequest() { mLocationRequest = new LocationRequest(); // Sets the desired interval for active location updates. This interval is // inexact. You may not receive updates at all if no location sources are available, or // you may receive them slower than requested. You may also receive updates faster than // requested if other applications are requesting location at a faster interval. mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS); // Sets the fastest rate for active location updates. This interval is exact, and your // application will never receive updates faster than this value. mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); } /** * Uses a {@link com.google.android.gms.location.LocationSettingsRequest.Builder} to build * a {@link com.google.android.gms.location.LocationSettingsRequest} that is used for checking * if a device has the needed location settings. */ private void buildLocationSettingsRequest() { LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder(); builder.addLocationRequest(mLocationRequest); mLocationSettingsRequest = builder.build(); } /** * Check if the device's location settings are adequate for the app's needs using the * {@link com.google.android.gms.location.SettingsApi#checkLocationSettings(GoogleApiClient, * LocationSettingsRequest)} method, with the results provided through a {@code PendingResult}. */ private void checkLocationSettings() { PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings( mGoogleApiClient, mLocationSettingsRequest ); result.setResultCallback(this); } /** * The callback invoked when * {@link com.google.android.gms.location.SettingsApi#checkLocationSettings(GoogleApiClient, * LocationSettingsRequest)} is called. Examines the * {@link com.google.android.gms.location.LocationSettingsResult} object and determines if * location settings are adequate. If they are not, begins the process of presenting a location * settings dialog to the user. */ @Override public void onResult(LocationSettingsResult locationSettingsResult) { final Status status = locationSettingsResult.getStatus(); switch (status.getStatusCode()) { case LocationSettingsStatusCodes.SUCCESS: Log.i(TAG, "All location settings are satisfied."); startLocationUpdates(); break; case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: Log.i(TAG, "Location settings are not satisfied. Show the user a dialog to " + "upgrade location settings "); try { // Show the dialog by calling startResolutionForResult(), and check the result // in onActivityResult(). status.startResolutionForResult(getActivity(), REQUEST_CHECK_SETTINGS); } catch (IntentSender.SendIntentException e) { Log.i(TAG, "PendingIntent unable to execute request."); } break; case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: Log.i(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog " + "not created."); break; } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { // Check for the integer request code originally supplied to startResolutionForResult(). case REQUEST_CHECK_SETTINGS: switch (resultCode) { case Activity.RESULT_OK: Log.i(TAG, "User agreed to make required location settings changes."); startLocationUpdates(); break; case Activity.RESULT_CANCELED: Log.i(TAG, "User chose not to make required location settings changes."); break; } break; } } /** * Requests location updates from the FusedLocationApi. */ private void startLocationUpdates() { if (mGoogleApiClient == null) { buildGoogleApiClient(); } LocationServices.FusedLocationApi.requestLocationUpdates( mGoogleApiClient, mLocationRequest, this ).setResultCallback(new ResultCallback<Status>() { @Override public void onResult(Status status) { mRequestingLocationUpdates = true; } }); } /** * Removes location updates from the FusedLocationApi. */ private void stopLocationUpdates() { // It is a good practice to remove location requests when the activity is in a paused or // stopped state. Doing so helps battery performance and is especially // recommended in applications that request frequent location updates. LocationServices.FusedLocationApi.removeLocationUpdates( mGoogleApiClient, this ).setResultCallback(new ResultCallback<Status>() { @Override public void onResult(Status status) { mRequestingLocationUpdates = false; } }); } @Override public void onStart() { //TODO: enable in release mGoogleApiClient.connect(); super.onStart(); } @Override public void onResume() { super.onResume(); buildMap(); //TODO: enable in release // Within {@code onPause()}, we pause location updates, but leave the // connection to GoogleApiClient intact. Here, we resume receiving // location updates if the user has requested them. if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) { startLocationUpdates(); } } private void buildMap(){ if(googleMap == null){ googleMap = fragment.getMap(); googleMap.getUiSettings().setMapToolbarEnabled(false); googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() { @Override public void onMapClick(LatLng latLng) { return; } }); } } @Override public void onPause() { //TODO: enable in release // Stop location updates to save battery, but don't disconnect the GoogleApiClient object. if (mGoogleApiClient.isConnected()) { stopLocationUpdates(); } super.onPause(); } @Override public void onStop() { //TODO: enable in release mGoogleApiClient.disconnect(); super.onStop(); } /** * Runs when a GoogleApiClient object successfully connects. */ @Override public void onConnected(Bundle connectionHint) { Log.i(TAG, "Connected to GoogleApiClient"); // If the initial location was never previously requested, we use // FusedLocationApi.getLastLocation() to get it. If it was previously requested, we store // its value in the Bundle and check for it in onCreate(). We // do not request it again unless the user specifically requests location updates by pressing // the Start Updates button. // // Because we cache the value of the initial location in the Bundle, it means that if the // user launches the activity, // moves to a new location, and then changes the device orientation, the original location // is displayed as the activity is re-created. if (mCurrentLocation == null) { mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); } } @Override public void onSaveInstanceState(Bundle outState) { outState.putSerializable("RESTAURANTS", (ArrayList<Restaurant>) restaurants); super.onSaveInstanceState(outState); } @Override public void onViewStateRestored(@Nullable Bundle savedInstanceState) { super.onViewStateRestored(savedInstanceState); if(savedInstanceState != null && savedInstanceState.containsKey("RESTAURANTS")){ restaurants = (List<Restaurant>) savedInstanceState.getSerializable("RESTAURANTS"); setupRecyclerView(rv); } } /** * Callback that fires when the location changes. */ @Override public void onLocationChanged(Location location) { mCurrentLocation = location; new FetchRestaurantsTask(rv, spinnerContainer).execute(mCurrentLocation.getLongitude(), mCurrentLocation.getLatitude()); stopLocationUpdates(); mGoogleApiClient.disconnect(); } @Override public void onConnectionSuspended(int cause) { Log.i(TAG, "Connection suspended"); } @Override public void onConnectionFailed(ConnectionResult result) { // Refer to the javadoc for ConnectionResult to see what error codes might be returned in // onConnectionFailed. Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode()); } /*private void setupTitle(LinearLayout layout) { ImageView iv = (ImageView) layout.findViewById(R.id.titleAvatar); Glide.with(iv.getContext()) .load(Images.getRandomCheeseDrawable()) .fitCenter() .into(iv); TextView tv = (TextView) layout.findViewById(R.id.titleText); tv.setText("Title"); }*/ private void setupRecyclerView(RecyclerView recyclerView) { //recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext())); LatLngBounds.Builder builder = LatLngBounds.builder(); if (restaurants.size() > 1) { for (Restaurant rest : restaurants) { LatLng latlng = new LatLng(rest.getLatitude(), rest.getLongitude()); builder.include(latlng); googleMap.addMarker(new MarkerOptions() .position(latlng) .title(rest.getName()) .icon(BitmapDescriptorFactory.fromResource(R.drawable.red_circle))); } googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 1)); } else if (restaurants.size() == 1) { LatLng latLng = new LatLng(restaurants.get(0).getLatitude(), restaurants.get(0).getLongitude()); googleMap.addMarker(new MarkerOptions() .position(latLng) .title(restaurants.get(0).getName()) .icon(BitmapDescriptorFactory.fromResource(R.drawable.red_circle))); googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16)); } recyclerView.setAdapter(new SimpleStringRecyclerViewAdapter(getActivity(), restaurants, getString(R.string.category_restaurant_descr))); } private static class SimpleStringRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private final TypedValue mTypedValue = new TypedValue(); private int mBackground; private List<Restaurant> mValues; private String description; public static class Description extends RecyclerView.ViewHolder { public final View mView; public final ImageView mImageView; public final TextView mTextView; public Description(View view) { super(view); mView = view; mImageView = (ImageView) view.findViewById(R.id.categoryAvatar); mTextView = (TextView) view.findViewById(R.id.categoryDescription); } @Override public String toString() { return super.toString() + " '" + mTextView.getText(); } } public static class ViewHolder extends RecyclerView.ViewHolder { public Restaurant mRestaurant; public final View mView; public final ImageView mImageView; public final TextView mTextView; public ViewHolder(View view) { super(view); mView = view; mImageView = (ImageView) view.findViewById(R.id.avatar); mTextView = (TextView) view.findViewById(android.R.id.text1); } @Override public String toString() { return super.toString() + " '" + mTextView.getText(); } } @Override public int getItemViewType(int position) { return position == 0 ? 0 : 1; } public Restaurant getValueAt(int position) { return mValues.get(position); } public SimpleStringRecyclerViewAdapter(Context context, List<Restaurant> restaurants, String description) { context.getTheme().resolveAttribute(R.attr.selectableItemBackground, mTypedValue, true); mBackground = mTypedValue.resourceId; mValues = restaurants; if (mValues.size() == 1) mValues.add(0, mValues.get(0)); /*mValues.add(3, mValues.get(0)); mValues.add(3, mValues.get(0)); mValues.add(3, mValues.get(0)); mValues.add(3, mValues.get(0)); mValues.add(3, mValues.get(0));*/ this.description = description; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == 0) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_description, parent, false); return new Description(view); } else { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false); view.setBackgroundResource(mBackground); return new ViewHolder(view); } } @Override public void onBindViewHolder(RecyclerView.ViewHolder holderr, final int position) { if (holderr instanceof ViewHolder) { final ViewHolder holder = (ViewHolder) holderr; holder.mRestaurant = mValues.get(position); holder.mTextView.setText(mValues.get(position).getName()); holder.mView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Context context = v.getContext(); Intent intent = new Intent(context, RestaurantDetailActivity.class); intent.putExtra(RestaurantDetailActivity.RESTAURANT, holder.mRestaurant); context.startActivity(intent); } }); // TODO : Fix performantie / Out of memory Glide.with(holder.mImageView.getContext()) .load("" /*holder.mRestaurant.getImage()*/) .placeholder(R.drawable.cutlery_green) .thumbnail(0.2f) .into(holder.mImageView); /*Glide.with(holder.mImageView.getContext()) .load(Images.getRandomCheeseDrawable()) .fitCenter() .into(holder.mImageView);*/ } else if (holderr instanceof Description) { final Description holder = (Description) holderr; holder.mTextView.setText(description); Glide.with(holder.mImageView.getContext()) .load("" /*holder.mRestaurant.getImage()*/) .placeholder(R.drawable.cutlery) .thumbnail(0.2f) .into(holder.mImageView); } } @Override public int getItemCount() { return mValues.size(); } } private void fetchChallenges() { //FetchRestaurantsTask fetch = new FetchRestaurantsTask(rv); //fetch.execute(); /** TIJDELIJK **/ JSONArray obj = null; try { obj = new JSONArray(Mock.restaurants); } catch (JSONException e) { e.printStackTrace(); } //voor elk object in de recipes (dus elk recept) de constructor van recept aanroepen met recipes stukje for (int i = 0; i < obj.length(); i++) { JSONObject jsonRow = null; try { jsonRow = obj.getJSONObject(i); } catch (JSONException e) { e.printStackTrace(); } try { restaurants.add(new Restaurant(jsonRow)); } catch (Exception e) { e.printStackTrace(); } } /** EINDE TIJDELIJK **/ } private class FetchRestaurantsTask extends AsyncTask<Double, String, Boolean> { List<Restaurant> list; RecyclerView recyclerView; FrameLayout spinnerContainer; public FetchRestaurantsTask(RecyclerView recyclerView, FrameLayout spinnerContainer) { super(); this.recyclerView = recyclerView; this.spinnerContainer = spinnerContainer; } @Override protected void onPreExecute() { spinnerContainer.setVisibility(View.VISIBLE); spinner.setVisibility(View.VISIBLE); notFound.setVisibility(View.INVISIBLE); } @Override protected Boolean doInBackground(Double... objects) { //Log.e("Longitude", String.valueOf(objects[0])); //Log.e("Latitude", String.valueOf(objects[1])); try { //TODO: enable in release list = challengeManager.getRestaurantsByLocation(objects[0], objects[1]); //list = challengeManager.getRestaurantsByLocationAndRadius(3.7007681,51.0310409, 10); //list = restaurants; Log.e("RestaurantListFragment", "Got Restaurants " + list.size()); return true; } catch (Exception ex) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getContext(), R.string.error500, Toast.LENGTH_SHORT).show(); } }); return false; } } @Override protected void onPostExecute(Boolean succeed) { if (!isDetached() && isAdded()) //no callback if fragment is no longer added { //setRefresh(false); if (succeed) //TODO: Remove negation after testing { Log.e("RecipeListFragment", "Post Execute called"); restaurants = list; setupRecyclerView(recyclerView); spinnerContainer.setVisibility(View.GONE); } else { Log.e("qmlskdjf", "Post Execute Failed"); spinner.setVisibility(View.INVISIBLE); notFound.setVisibility(View.VISIBLE); notFound.setText(R.string.no_restaurants_found); } } } } }
Buccaneer/3d-mobi-05-eva-android-front-end
EVA21DayChallenge/app/src/main/java/be/evavzw/eva21daychallenge/activity/challenges/RestaurantListFragment.java
7,497
//voor elk object in de recipes (dus elk recept) de constructor van recept aanroepen met recipes stukje
line_comment
nl
package be.evavzw.eva21daychallenge.activity.challenges; import android.Manifest; import android.app.Activity; import android.app.FragmentManager; import android.content.Context; import android.content.Intent; import android.content.IntentSender; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.Point; import android.location.Location; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.LocationSettingsRequest; import com.google.android.gms.location.LocationSettingsResult; import com.google.android.gms.location.LocationSettingsStatusCodes; import com.bumptech.glide.Glide; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMapOptions; import com.google.android.gms.maps.MapFragment; 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.LatLngBounds; import com.google.android.gms.maps.model.MarkerOptions; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import be.evavzw.eva21daychallenge.R; import be.evavzw.eva21daychallenge.models.Restaurant; import be.evavzw.eva21daychallenge.services.ChallengeManager; /** * Created by Pieter-Jan on 4/11/2015. */ public class RestaurantListFragment extends ChallengeFragment implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener, ResultCallback<LocationSettingsResult> { private static final String TAG = "RestaurantListFragment"; /** * Constant used in the location settings dialog. */ private static final int REQUEST_CHECK_SETTINGS = 0x1; /** * The desired interval for location updates. Inexact. Updates may be more or less frequent. */ private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 1000; /** * The fastest rate for active location updates. Exact. Updates will never be more frequent * than this value. */ private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS; /** * Provides the entry point to Google Play services. */ private GoogleApiClient mGoogleApiClient; /** * Stores parameters for requests to the FusedLocationProviderApi. */ private LocationRequest mLocationRequest; /** * Stores the types of location services the client is interested in using. Used for checking * settings to determine if the device has optimal location settings. */ private LocationSettingsRequest mLocationSettingsRequest; /** * Represents a geographical location. */ private Location mCurrentLocation; /** * Tracks the status of the location updates request. Value changes when the user presses the * Start Updates and Stop Updates buttons. */ private Boolean mRequestingLocationUpdates; private ChallengeManager challengeManager; private List<Restaurant> restaurants = new ArrayList<>(); private RecyclerView rv; private FrameLayout spinnerContainer; private ProgressBar spinner; private TextView notFound; private GoogleMap googleMap; private SupportMapFragment fragment; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.restaurant_challenge, container, false); //setupTitle(layout); challengeManager = ChallengeManager.getInstance(getContext()); rv = (RecyclerView) layout.findViewById(R.id.restaurantList); rv.setLayoutManager(new LinearLayoutManager(rv.getContext())); //setupRecyclerView(rv); spinnerContainer = (FrameLayout) layout.findViewById(R.id.list_spinner_container); spinner = (ProgressBar) layout.findViewById(R.id.list_spinner); notFound = (TextView) layout.findViewById(R.id.not_found); //new FetchRestaurantsTask(rv).execute(); //fetchChallenges(); setRetainInstance(true); //new FetchRestaurantsTask(rv).execute(); return layout; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mRequestingLocationUpdates = false; buildGoogleApiClient(); createLocationRequest(); buildLocationSettingsRequest(); if (Build.VERSION.SDK_INT >= 23) { askLocationPermission(); } else { checkLocationSettings(); } android.support.v4.app.FragmentManager fm = getChildFragmentManager(); fragment = (SupportMapFragment) fm.findFragmentById(R.id.restaurantMapFragment); if(fragment == null){ GoogleMapOptions options = new GoogleMapOptions().liteMode(true); fragment = SupportMapFragment.newInstance(options); fm.beginTransaction().replace(R.id.restaurantMapFragment, fragment).commit(); } } private void askLocationPermission() { if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 200); } else { checkLocationSettings(); } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { Log.i(TAG, "PERMISSION CALLBACK"); if (requestCode == 200) { if (grantResults.length != 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { checkLocationSettings(); } } } /** * Builds a GoogleApiClient. Uses the {@code #addApi} method to request the * LocationServices API. */ protected synchronized void buildGoogleApiClient() { Log.i(TAG, "Building GoogleApiClient"); mGoogleApiClient = new GoogleApiClient.Builder(getContext()) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } /** * Sets up the location request. Android has two location request settings: * {@code ACCESS_COARSE_LOCATION} and {@code ACCESS_FINE_LOCATION}. These settings control * the accuracy of the current location. This sample uses ACCESS_FINE_LOCATION, as defined in * the AndroidManifest.xml. * <p/> * When the ACCESS_FINE_LOCATION setting is specified, combined with a fast update * interval (5 seconds), the Fused Location Provider API returns location updates that are * accurate to within a few feet. * <p/> * These settings are appropriate for mapping applications that show real-time location * updates. */ protected void createLocationRequest() { mLocationRequest = new LocationRequest(); // Sets the desired interval for active location updates. This interval is // inexact. You may not receive updates at all if no location sources are available, or // you may receive them slower than requested. You may also receive updates faster than // requested if other applications are requesting location at a faster interval. mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS); // Sets the fastest rate for active location updates. This interval is exact, and your // application will never receive updates faster than this value. mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); } /** * Uses a {@link com.google.android.gms.location.LocationSettingsRequest.Builder} to build * a {@link com.google.android.gms.location.LocationSettingsRequest} that is used for checking * if a device has the needed location settings. */ private void buildLocationSettingsRequest() { LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder(); builder.addLocationRequest(mLocationRequest); mLocationSettingsRequest = builder.build(); } /** * Check if the device's location settings are adequate for the app's needs using the * {@link com.google.android.gms.location.SettingsApi#checkLocationSettings(GoogleApiClient, * LocationSettingsRequest)} method, with the results provided through a {@code PendingResult}. */ private void checkLocationSettings() { PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings( mGoogleApiClient, mLocationSettingsRequest ); result.setResultCallback(this); } /** * The callback invoked when * {@link com.google.android.gms.location.SettingsApi#checkLocationSettings(GoogleApiClient, * LocationSettingsRequest)} is called. Examines the * {@link com.google.android.gms.location.LocationSettingsResult} object and determines if * location settings are adequate. If they are not, begins the process of presenting a location * settings dialog to the user. */ @Override public void onResult(LocationSettingsResult locationSettingsResult) { final Status status = locationSettingsResult.getStatus(); switch (status.getStatusCode()) { case LocationSettingsStatusCodes.SUCCESS: Log.i(TAG, "All location settings are satisfied."); startLocationUpdates(); break; case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: Log.i(TAG, "Location settings are not satisfied. Show the user a dialog to " + "upgrade location settings "); try { // Show the dialog by calling startResolutionForResult(), and check the result // in onActivityResult(). status.startResolutionForResult(getActivity(), REQUEST_CHECK_SETTINGS); } catch (IntentSender.SendIntentException e) { Log.i(TAG, "PendingIntent unable to execute request."); } break; case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: Log.i(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog " + "not created."); break; } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { // Check for the integer request code originally supplied to startResolutionForResult(). case REQUEST_CHECK_SETTINGS: switch (resultCode) { case Activity.RESULT_OK: Log.i(TAG, "User agreed to make required location settings changes."); startLocationUpdates(); break; case Activity.RESULT_CANCELED: Log.i(TAG, "User chose not to make required location settings changes."); break; } break; } } /** * Requests location updates from the FusedLocationApi. */ private void startLocationUpdates() { if (mGoogleApiClient == null) { buildGoogleApiClient(); } LocationServices.FusedLocationApi.requestLocationUpdates( mGoogleApiClient, mLocationRequest, this ).setResultCallback(new ResultCallback<Status>() { @Override public void onResult(Status status) { mRequestingLocationUpdates = true; } }); } /** * Removes location updates from the FusedLocationApi. */ private void stopLocationUpdates() { // It is a good practice to remove location requests when the activity is in a paused or // stopped state. Doing so helps battery performance and is especially // recommended in applications that request frequent location updates. LocationServices.FusedLocationApi.removeLocationUpdates( mGoogleApiClient, this ).setResultCallback(new ResultCallback<Status>() { @Override public void onResult(Status status) { mRequestingLocationUpdates = false; } }); } @Override public void onStart() { //TODO: enable in release mGoogleApiClient.connect(); super.onStart(); } @Override public void onResume() { super.onResume(); buildMap(); //TODO: enable in release // Within {@code onPause()}, we pause location updates, but leave the // connection to GoogleApiClient intact. Here, we resume receiving // location updates if the user has requested them. if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) { startLocationUpdates(); } } private void buildMap(){ if(googleMap == null){ googleMap = fragment.getMap(); googleMap.getUiSettings().setMapToolbarEnabled(false); googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() { @Override public void onMapClick(LatLng latLng) { return; } }); } } @Override public void onPause() { //TODO: enable in release // Stop location updates to save battery, but don't disconnect the GoogleApiClient object. if (mGoogleApiClient.isConnected()) { stopLocationUpdates(); } super.onPause(); } @Override public void onStop() { //TODO: enable in release mGoogleApiClient.disconnect(); super.onStop(); } /** * Runs when a GoogleApiClient object successfully connects. */ @Override public void onConnected(Bundle connectionHint) { Log.i(TAG, "Connected to GoogleApiClient"); // If the initial location was never previously requested, we use // FusedLocationApi.getLastLocation() to get it. If it was previously requested, we store // its value in the Bundle and check for it in onCreate(). We // do not request it again unless the user specifically requests location updates by pressing // the Start Updates button. // // Because we cache the value of the initial location in the Bundle, it means that if the // user launches the activity, // moves to a new location, and then changes the device orientation, the original location // is displayed as the activity is re-created. if (mCurrentLocation == null) { mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); } } @Override public void onSaveInstanceState(Bundle outState) { outState.putSerializable("RESTAURANTS", (ArrayList<Restaurant>) restaurants); super.onSaveInstanceState(outState); } @Override public void onViewStateRestored(@Nullable Bundle savedInstanceState) { super.onViewStateRestored(savedInstanceState); if(savedInstanceState != null && savedInstanceState.containsKey("RESTAURANTS")){ restaurants = (List<Restaurant>) savedInstanceState.getSerializable("RESTAURANTS"); setupRecyclerView(rv); } } /** * Callback that fires when the location changes. */ @Override public void onLocationChanged(Location location) { mCurrentLocation = location; new FetchRestaurantsTask(rv, spinnerContainer).execute(mCurrentLocation.getLongitude(), mCurrentLocation.getLatitude()); stopLocationUpdates(); mGoogleApiClient.disconnect(); } @Override public void onConnectionSuspended(int cause) { Log.i(TAG, "Connection suspended"); } @Override public void onConnectionFailed(ConnectionResult result) { // Refer to the javadoc for ConnectionResult to see what error codes might be returned in // onConnectionFailed. Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode()); } /*private void setupTitle(LinearLayout layout) { ImageView iv = (ImageView) layout.findViewById(R.id.titleAvatar); Glide.with(iv.getContext()) .load(Images.getRandomCheeseDrawable()) .fitCenter() .into(iv); TextView tv = (TextView) layout.findViewById(R.id.titleText); tv.setText("Title"); }*/ private void setupRecyclerView(RecyclerView recyclerView) { //recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext())); LatLngBounds.Builder builder = LatLngBounds.builder(); if (restaurants.size() > 1) { for (Restaurant rest : restaurants) { LatLng latlng = new LatLng(rest.getLatitude(), rest.getLongitude()); builder.include(latlng); googleMap.addMarker(new MarkerOptions() .position(latlng) .title(rest.getName()) .icon(BitmapDescriptorFactory.fromResource(R.drawable.red_circle))); } googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 1)); } else if (restaurants.size() == 1) { LatLng latLng = new LatLng(restaurants.get(0).getLatitude(), restaurants.get(0).getLongitude()); googleMap.addMarker(new MarkerOptions() .position(latLng) .title(restaurants.get(0).getName()) .icon(BitmapDescriptorFactory.fromResource(R.drawable.red_circle))); googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16)); } recyclerView.setAdapter(new SimpleStringRecyclerViewAdapter(getActivity(), restaurants, getString(R.string.category_restaurant_descr))); } private static class SimpleStringRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private final TypedValue mTypedValue = new TypedValue(); private int mBackground; private List<Restaurant> mValues; private String description; public static class Description extends RecyclerView.ViewHolder { public final View mView; public final ImageView mImageView; public final TextView mTextView; public Description(View view) { super(view); mView = view; mImageView = (ImageView) view.findViewById(R.id.categoryAvatar); mTextView = (TextView) view.findViewById(R.id.categoryDescription); } @Override public String toString() { return super.toString() + " '" + mTextView.getText(); } } public static class ViewHolder extends RecyclerView.ViewHolder { public Restaurant mRestaurant; public final View mView; public final ImageView mImageView; public final TextView mTextView; public ViewHolder(View view) { super(view); mView = view; mImageView = (ImageView) view.findViewById(R.id.avatar); mTextView = (TextView) view.findViewById(android.R.id.text1); } @Override public String toString() { return super.toString() + " '" + mTextView.getText(); } } @Override public int getItemViewType(int position) { return position == 0 ? 0 : 1; } public Restaurant getValueAt(int position) { return mValues.get(position); } public SimpleStringRecyclerViewAdapter(Context context, List<Restaurant> restaurants, String description) { context.getTheme().resolveAttribute(R.attr.selectableItemBackground, mTypedValue, true); mBackground = mTypedValue.resourceId; mValues = restaurants; if (mValues.size() == 1) mValues.add(0, mValues.get(0)); /*mValues.add(3, mValues.get(0)); mValues.add(3, mValues.get(0)); mValues.add(3, mValues.get(0)); mValues.add(3, mValues.get(0)); mValues.add(3, mValues.get(0));*/ this.description = description; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == 0) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_description, parent, false); return new Description(view); } else { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false); view.setBackgroundResource(mBackground); return new ViewHolder(view); } } @Override public void onBindViewHolder(RecyclerView.ViewHolder holderr, final int position) { if (holderr instanceof ViewHolder) { final ViewHolder holder = (ViewHolder) holderr; holder.mRestaurant = mValues.get(position); holder.mTextView.setText(mValues.get(position).getName()); holder.mView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Context context = v.getContext(); Intent intent = new Intent(context, RestaurantDetailActivity.class); intent.putExtra(RestaurantDetailActivity.RESTAURANT, holder.mRestaurant); context.startActivity(intent); } }); // TODO : Fix performantie / Out of memory Glide.with(holder.mImageView.getContext()) .load("" /*holder.mRestaurant.getImage()*/) .placeholder(R.drawable.cutlery_green) .thumbnail(0.2f) .into(holder.mImageView); /*Glide.with(holder.mImageView.getContext()) .load(Images.getRandomCheeseDrawable()) .fitCenter() .into(holder.mImageView);*/ } else if (holderr instanceof Description) { final Description holder = (Description) holderr; holder.mTextView.setText(description); Glide.with(holder.mImageView.getContext()) .load("" /*holder.mRestaurant.getImage()*/) .placeholder(R.drawable.cutlery) .thumbnail(0.2f) .into(holder.mImageView); } } @Override public int getItemCount() { return mValues.size(); } } private void fetchChallenges() { //FetchRestaurantsTask fetch = new FetchRestaurantsTask(rv); //fetch.execute(); /** TIJDELIJK **/ JSONArray obj = null; try { obj = new JSONArray(Mock.restaurants); } catch (JSONException e) { e.printStackTrace(); } //voor elk<SUF> for (int i = 0; i < obj.length(); i++) { JSONObject jsonRow = null; try { jsonRow = obj.getJSONObject(i); } catch (JSONException e) { e.printStackTrace(); } try { restaurants.add(new Restaurant(jsonRow)); } catch (Exception e) { e.printStackTrace(); } } /** EINDE TIJDELIJK **/ } private class FetchRestaurantsTask extends AsyncTask<Double, String, Boolean> { List<Restaurant> list; RecyclerView recyclerView; FrameLayout spinnerContainer; public FetchRestaurantsTask(RecyclerView recyclerView, FrameLayout spinnerContainer) { super(); this.recyclerView = recyclerView; this.spinnerContainer = spinnerContainer; } @Override protected void onPreExecute() { spinnerContainer.setVisibility(View.VISIBLE); spinner.setVisibility(View.VISIBLE); notFound.setVisibility(View.INVISIBLE); } @Override protected Boolean doInBackground(Double... objects) { //Log.e("Longitude", String.valueOf(objects[0])); //Log.e("Latitude", String.valueOf(objects[1])); try { //TODO: enable in release list = challengeManager.getRestaurantsByLocation(objects[0], objects[1]); //list = challengeManager.getRestaurantsByLocationAndRadius(3.7007681,51.0310409, 10); //list = restaurants; Log.e("RestaurantListFragment", "Got Restaurants " + list.size()); return true; } catch (Exception ex) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getContext(), R.string.error500, Toast.LENGTH_SHORT).show(); } }); return false; } } @Override protected void onPostExecute(Boolean succeed) { if (!isDetached() && isAdded()) //no callback if fragment is no longer added { //setRefresh(false); if (succeed) //TODO: Remove negation after testing { Log.e("RecipeListFragment", "Post Execute called"); restaurants = list; setupRecyclerView(recyclerView); spinnerContainer.setVisibility(View.GONE); } else { Log.e("qmlskdjf", "Post Execute Failed"); spinner.setVisibility(View.INVISIBLE); notFound.setVisibility(View.VISIBLE); notFound.setText(R.string.no_restaurants_found); } } } } }
34149_8
package main; import Connectivity.UserManager; import Connectivity.DatabaseManager; import Connectivity.SearchManager; import Connectivity.TableManager; import Connectivity.ClientManager; import Connectivity.LuggageManager; import Connectivity.QueryManager; import ExterneLibraries.PDFGenerator; import java.awt.BorderLayout; import java.awt.Font; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; /** * * @author Team 1 IS106 ZoekJeKoffer */ public final class FYSApp { /* * Styling Conventions: * Properties of: - Textbox: Calibri 12px plain - Textbox Labels: Calibri 18px plain - Frame title Labels: Calibri 24px bold - Buttons: Calibri 14px plain (UPPERCASE, except for logout/login screen) Dimensions:(X = 530px, Y = 400px) GEEN BORDERS */ /** * Finals for warnings */ public static final String WARNING_REQUIRED = "Some fields are required to fill in!"; public static final String WARNING_MUST_SELECT_SOMETHING = "You must select something!"; public static final String NO_VALUE = ""; public static final double DOUBLE_ZERO = 0.0; public static final double ZERO = 0; /** * Define frame width, height and name */ public static final int MAIN_WIDTH = 340; public static final int MAIN_HEIGHT = 600; public static final String MAIN_NAME = "Zoek juh köffer"; /** * static fonts which are used within the application */ public static final Font FONT_10_PLAIN = new Font("Verdana", Font.PLAIN, 10); public static final Font FONT_10_BOLD = new Font("Verdana", Font.BOLD, 10); public static final Font FONT_12_BOLD = new Font("Verdana", Font.BOLD, 12); public static final Font FONT_16_BOLD = new Font("Verdana", Font.BOLD, 16); private static JFrame mainWindow; private DatabaseManager manager = new DatabaseManager(); private QueryManager qm = new QueryManager(manager); private LuggageManager lm = new LuggageManager(); private SearchManager sm = new SearchManager(); private TableManager tm = new TableManager(); private UserManager um = new UserManager(); private ClientManager cm = new ClientManager(); private PDFGenerator pdf = new PDFGenerator(); /** * singleton of the application */ private static FYSApp instance = new FYSApp(); private FYSApp() { } //Database en Querymanager moet hierin initialized worden; Vul nog aan. public void initialize() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { System.err.println("Error setting LookAndFeelClassName: " + e); } } // Arraylist of all the airports from the database public static ArrayList<String> airportsList; public static ArrayList<String> getAirportsList() { return airportsList; } public static void setAirports() { ArrayList<String> airports = FYSApp.getQueryManager().getAirports(); for (int i = 0; i < airports.size(); i++) { airportsList.add(airports.get(i)); } } //Start de mainwindow. en include public void startup() { mainWindow = new JFrame(MAIN_NAME); mainWindow.setSize(MAIN_WIDTH, MAIN_HEIGHT); mainWindow.setResizable(false); mainWindow.setLocationRelativeTo(null); //method shutdown om applicatie te sluiten. mainWindow.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent event) { shutdown(); } }); mainWindow.getContentPane().setLayout(new BorderLayout()); showPanel(new view.LoginScreen()); mainWindow.setVisible(true); } public void showPanel(JPanel panel) { mainWindow.getContentPane().removeAll(); mainWindow.getContentPane().add(panel, BorderLayout.CENTER); mainWindow.getContentPane().validate(); mainWindow.getContentPane().repaint(); } public void exit() { mainWindow.setVisible(false); shutdown(); } //Database shutdown moet hierin nog toegevoegd worden public static void shutdown() { mainWindow.dispose(); } // Gets current date (timestamp) public static String getDate() { String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date()); return date; } // Gets current date and time (timestamp) public static String getDateTime() { String dateTime = new SimpleDateFormat("dd-MM-yyyy:k:m") .format(new Date()); return dateTime; } /** * @return the instance of this class */ public static FYSApp getInstance() { return instance; } public QueryManager getQm() { return qm; } public static QueryManager getQueryManager() { return getInstance().qm; } public LuggageManager getLm() { return lm; } public static LuggageManager getLuggageManager() { return getInstance().lm; } public SearchManager getSm() { return sm; } public static SearchManager getSearchManager() { return getInstance().sm; } public TableManager getTm() { return tm; } public static TableManager getTableManager() { return getInstance().tm; } public UserManager getUm() { return um; } public static UserManager getUserManager() { return getInstance().um; } public ClientManager getCm() { return cm; } public static ClientManager getClientManager() { return getInstance().cm; } public DatabaseManager getDatabaseManager() { return manager; } public PDFGenerator getPDFGenerator(){ return pdf; } public static void logout() { final FYSApp applicatie = FYSApp.getInstance(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { try { applicatie.initialize(); applicatie.startup(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Application failed to launch", "Failure", JOptionPane.WARNING_MESSAGE); } } }); } public static void main(String args[]) { final FYSApp applicatie = FYSApp.getInstance(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { try { applicatie.initialize(); applicatie.startup(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Application failed to launch", "Failure", JOptionPane.WARNING_MESSAGE); } } }); } }
Buggyy/FYSApp
FYSApp-master/src/main/FYSApp.java
2,166
//Start de mainwindow. en include
line_comment
nl
package main; import Connectivity.UserManager; import Connectivity.DatabaseManager; import Connectivity.SearchManager; import Connectivity.TableManager; import Connectivity.ClientManager; import Connectivity.LuggageManager; import Connectivity.QueryManager; import ExterneLibraries.PDFGenerator; import java.awt.BorderLayout; import java.awt.Font; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; /** * * @author Team 1 IS106 ZoekJeKoffer */ public final class FYSApp { /* * Styling Conventions: * Properties of: - Textbox: Calibri 12px plain - Textbox Labels: Calibri 18px plain - Frame title Labels: Calibri 24px bold - Buttons: Calibri 14px plain (UPPERCASE, except for logout/login screen) Dimensions:(X = 530px, Y = 400px) GEEN BORDERS */ /** * Finals for warnings */ public static final String WARNING_REQUIRED = "Some fields are required to fill in!"; public static final String WARNING_MUST_SELECT_SOMETHING = "You must select something!"; public static final String NO_VALUE = ""; public static final double DOUBLE_ZERO = 0.0; public static final double ZERO = 0; /** * Define frame width, height and name */ public static final int MAIN_WIDTH = 340; public static final int MAIN_HEIGHT = 600; public static final String MAIN_NAME = "Zoek juh köffer"; /** * static fonts which are used within the application */ public static final Font FONT_10_PLAIN = new Font("Verdana", Font.PLAIN, 10); public static final Font FONT_10_BOLD = new Font("Verdana", Font.BOLD, 10); public static final Font FONT_12_BOLD = new Font("Verdana", Font.BOLD, 12); public static final Font FONT_16_BOLD = new Font("Verdana", Font.BOLD, 16); private static JFrame mainWindow; private DatabaseManager manager = new DatabaseManager(); private QueryManager qm = new QueryManager(manager); private LuggageManager lm = new LuggageManager(); private SearchManager sm = new SearchManager(); private TableManager tm = new TableManager(); private UserManager um = new UserManager(); private ClientManager cm = new ClientManager(); private PDFGenerator pdf = new PDFGenerator(); /** * singleton of the application */ private static FYSApp instance = new FYSApp(); private FYSApp() { } //Database en Querymanager moet hierin initialized worden; Vul nog aan. public void initialize() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { System.err.println("Error setting LookAndFeelClassName: " + e); } } // Arraylist of all the airports from the database public static ArrayList<String> airportsList; public static ArrayList<String> getAirportsList() { return airportsList; } public static void setAirports() { ArrayList<String> airports = FYSApp.getQueryManager().getAirports(); for (int i = 0; i < airports.size(); i++) { airportsList.add(airports.get(i)); } } //Start de<SUF> public void startup() { mainWindow = new JFrame(MAIN_NAME); mainWindow.setSize(MAIN_WIDTH, MAIN_HEIGHT); mainWindow.setResizable(false); mainWindow.setLocationRelativeTo(null); //method shutdown om applicatie te sluiten. mainWindow.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent event) { shutdown(); } }); mainWindow.getContentPane().setLayout(new BorderLayout()); showPanel(new view.LoginScreen()); mainWindow.setVisible(true); } public void showPanel(JPanel panel) { mainWindow.getContentPane().removeAll(); mainWindow.getContentPane().add(panel, BorderLayout.CENTER); mainWindow.getContentPane().validate(); mainWindow.getContentPane().repaint(); } public void exit() { mainWindow.setVisible(false); shutdown(); } //Database shutdown moet hierin nog toegevoegd worden public static void shutdown() { mainWindow.dispose(); } // Gets current date (timestamp) public static String getDate() { String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date()); return date; } // Gets current date and time (timestamp) public static String getDateTime() { String dateTime = new SimpleDateFormat("dd-MM-yyyy:k:m") .format(new Date()); return dateTime; } /** * @return the instance of this class */ public static FYSApp getInstance() { return instance; } public QueryManager getQm() { return qm; } public static QueryManager getQueryManager() { return getInstance().qm; } public LuggageManager getLm() { return lm; } public static LuggageManager getLuggageManager() { return getInstance().lm; } public SearchManager getSm() { return sm; } public static SearchManager getSearchManager() { return getInstance().sm; } public TableManager getTm() { return tm; } public static TableManager getTableManager() { return getInstance().tm; } public UserManager getUm() { return um; } public static UserManager getUserManager() { return getInstance().um; } public ClientManager getCm() { return cm; } public static ClientManager getClientManager() { return getInstance().cm; } public DatabaseManager getDatabaseManager() { return manager; } public PDFGenerator getPDFGenerator(){ return pdf; } public static void logout() { final FYSApp applicatie = FYSApp.getInstance(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { try { applicatie.initialize(); applicatie.startup(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Application failed to launch", "Failure", JOptionPane.WARNING_MESSAGE); } } }); } public static void main(String args[]) { final FYSApp applicatie = FYSApp.getInstance(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { try { applicatie.initialize(); applicatie.startup(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Application failed to launch", "Failure", JOptionPane.WARNING_MESSAGE); } } }); } }
29534_4
package activemq; import algoritmes.ConcurrentMergeSort; import helper.CustomUtilities; import org.apache.activemq.ActiveMQConnectionFactory; import javax.jms.*; import java.util.ArrayList; import java.util.List; import static helper.Config.ACTIVEMQ_URL; /** * Parallel Computing * AUTHOR: R. Lobato & C. Verra */ public class Consumer { private static String subject = "resultaat"; public static void main(String[] args) throws JMSException { ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL); Connection connection = connectionFactory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue(subject); MessageConsumer consumer = session.createConsumer(destination); int count = 0; // Lijst van Integers List<Integer> list = new ArrayList<>(); while (true) { Message message = consumer.receive(); if (message instanceof TextMessage) { count++; TextMessage textMessage = (TextMessage) message; // String aan integers opslaan String str = textMessage.getText(); // String aan integers opsplitten String[] integerStrings = str.split(" "); // Parse String Integers naar ints for (String integerString : integerStrings) { int j = Integer.parseInt(integerString); // Voeg toe aan list list.add(j); } // Als het aantal lijsten gelijk is aan het aantal producers if (count == Producer.NODES) { int[] array = list.stream().mapToInt(i -> i).toArray(); // Sorteer lijsten individueel ConcurrentMergeSort concurrentMergeSort = new ConcurrentMergeSort(array); concurrentMergeSort.sort(); if (CustomUtilities.isArraySorted(array)) break; } } } connection.close(); } }
Buggyy/Parallel-Computing
src/activemq/Consumer.java
603
// Parse String Integers naar ints
line_comment
nl
package activemq; import algoritmes.ConcurrentMergeSort; import helper.CustomUtilities; import org.apache.activemq.ActiveMQConnectionFactory; import javax.jms.*; import java.util.ArrayList; import java.util.List; import static helper.Config.ACTIVEMQ_URL; /** * Parallel Computing * AUTHOR: R. Lobato & C. Verra */ public class Consumer { private static String subject = "resultaat"; public static void main(String[] args) throws JMSException { ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL); Connection connection = connectionFactory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue(subject); MessageConsumer consumer = session.createConsumer(destination); int count = 0; // Lijst van Integers List<Integer> list = new ArrayList<>(); while (true) { Message message = consumer.receive(); if (message instanceof TextMessage) { count++; TextMessage textMessage = (TextMessage) message; // String aan integers opslaan String str = textMessage.getText(); // String aan integers opsplitten String[] integerStrings = str.split(" "); // Parse String<SUF> for (String integerString : integerStrings) { int j = Integer.parseInt(integerString); // Voeg toe aan list list.add(j); } // Als het aantal lijsten gelijk is aan het aantal producers if (count == Producer.NODES) { int[] array = list.stream().mapToInt(i -> i).toArray(); // Sorteer lijsten individueel ConcurrentMergeSort concurrentMergeSort = new ConcurrentMergeSort(array); concurrentMergeSort.sort(); if (CustomUtilities.isArraySorted(array)) break; } } } connection.close(); } }
9244_10
package org.bukkit; import java.util.Map; import com.google.common.collect.Maps; import org.bukkit.block.BlockFace; import org.bukkit.potion.Potion; /** * A list of effects that the server is able to send to players. */ public enum Effect { /** * An alternate click sound. */ CLICK2(1000, Type.SOUND), /** * A click sound. */ CLICK1(1001, Type.SOUND), /** * Sound of a bow firing. */ BOW_FIRE(1002, Type.SOUND), /** * Sound of a door opening/closing. */ DOOR_TOGGLE(1003, Type.SOUND), /** * Sound of fire being extinguished. */ EXTINGUISH(1004, Type.SOUND), /** * A song from a record. Needs the record item ID as additional info */ RECORD_PLAY(1005, Type.SOUND, Material.class), /** * Sound of ghast shrieking. */ GHAST_SHRIEK(1007, Type.SOUND), /** * Sound of ghast firing. */ GHAST_SHOOT(1008, Type.SOUND), /** * Sound of blaze firing. */ BLAZE_SHOOT(1009, Type.SOUND), /** * Sound of zombies chewing on wooden doors. */ ZOMBIE_CHEW_WOODEN_DOOR(1010, Type.SOUND), /** * Sound of zombies chewing on iron doors. */ ZOMBIE_CHEW_IRON_DOOR(1011, Type.SOUND), /** * Sound of zombies destroying a door. */ ZOMBIE_DESTROY_DOOR(1012, Type.SOUND), /** * A visual smoke effect. Needs direction as additional info. */ SMOKE(2000, Type.VISUAL, BlockFace.class), /** * Sound of a block breaking. Needs block ID as additional info. */ STEP_SOUND(2001, Type.SOUND, Material.class), /** * Visual effect of a splash potion breaking. Needs potion data value as * additional info. */ POTION_BREAK(2002, Type.VISUAL, Potion.class), /** * An ender eye signal; a visual effect. */ ENDER_SIGNAL(2003, Type.VISUAL), /** * The flames seen on a mobspawner; a visual effect. */ MOBSPAWNER_FLAMES(2004, Type.VISUAL); private final int id; private final Type type; private final Class<?> data; private static final Map<Integer, Effect> BY_ID = Maps.newHashMap(); Effect(int id, Type type) { this(id,type,null); } Effect(int id, Type type, Class<?> data) { this.id = id; this.type = type; this.data = data; } /** * Gets the ID for this effect. * * @return ID of this effect * @deprecated Magic value */ @Deprecated public int getId() { return this.id; } /** * @return The type of the effect. */ public Type getType() { return this.type; } /** * @return The class which represents data for this effect, or null if * none */ public Class<?> getData() { return this.data; } /** * Gets the Effect associated with the given ID. * * @param id ID of the Effect to return * @return Effect with the given ID * @deprecated Magic value */ @Deprecated public static Effect getById(int id) { return BY_ID.get(id); } static { for (Effect effect : values()) { BY_ID.put(effect.id, effect); } } /** * Represents the type of an effect. */ public enum Type {SOUND, VISUAL} }
Bukkit/Bukkit
src/main/java/org/bukkit/Effect.java
1,138
/** * Sound of zombies chewing on wooden doors. */
block_comment
nl
package org.bukkit; import java.util.Map; import com.google.common.collect.Maps; import org.bukkit.block.BlockFace; import org.bukkit.potion.Potion; /** * A list of effects that the server is able to send to players. */ public enum Effect { /** * An alternate click sound. */ CLICK2(1000, Type.SOUND), /** * A click sound. */ CLICK1(1001, Type.SOUND), /** * Sound of a bow firing. */ BOW_FIRE(1002, Type.SOUND), /** * Sound of a door opening/closing. */ DOOR_TOGGLE(1003, Type.SOUND), /** * Sound of fire being extinguished. */ EXTINGUISH(1004, Type.SOUND), /** * A song from a record. Needs the record item ID as additional info */ RECORD_PLAY(1005, Type.SOUND, Material.class), /** * Sound of ghast shrieking. */ GHAST_SHRIEK(1007, Type.SOUND), /** * Sound of ghast firing. */ GHAST_SHOOT(1008, Type.SOUND), /** * Sound of blaze firing. */ BLAZE_SHOOT(1009, Type.SOUND), /** * Sound of zombies<SUF>*/ ZOMBIE_CHEW_WOODEN_DOOR(1010, Type.SOUND), /** * Sound of zombies chewing on iron doors. */ ZOMBIE_CHEW_IRON_DOOR(1011, Type.SOUND), /** * Sound of zombies destroying a door. */ ZOMBIE_DESTROY_DOOR(1012, Type.SOUND), /** * A visual smoke effect. Needs direction as additional info. */ SMOKE(2000, Type.VISUAL, BlockFace.class), /** * Sound of a block breaking. Needs block ID as additional info. */ STEP_SOUND(2001, Type.SOUND, Material.class), /** * Visual effect of a splash potion breaking. Needs potion data value as * additional info. */ POTION_BREAK(2002, Type.VISUAL, Potion.class), /** * An ender eye signal; a visual effect. */ ENDER_SIGNAL(2003, Type.VISUAL), /** * The flames seen on a mobspawner; a visual effect. */ MOBSPAWNER_FLAMES(2004, Type.VISUAL); private final int id; private final Type type; private final Class<?> data; private static final Map<Integer, Effect> BY_ID = Maps.newHashMap(); Effect(int id, Type type) { this(id,type,null); } Effect(int id, Type type, Class<?> data) { this.id = id; this.type = type; this.data = data; } /** * Gets the ID for this effect. * * @return ID of this effect * @deprecated Magic value */ @Deprecated public int getId() { return this.id; } /** * @return The type of the effect. */ public Type getType() { return this.type; } /** * @return The class which represents data for this effect, or null if * none */ public Class<?> getData() { return this.data; } /** * Gets the Effect associated with the given ID. * * @param id ID of the Effect to return * @return Effect with the given ID * @deprecated Magic value */ @Deprecated public static Effect getById(int id) { return BY_ID.get(id); } static { for (Effect effect : values()) { BY_ID.put(effect.id, effect); } } /** * Represents the type of an effect. */ public enum Type {SOUND, VISUAL} }
190202_0
package com.timaar.tiimspot.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.springframework.data.elasticsearch.annotations.Document; import javax.persistence.*; import javax.validation.constraints.*; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import java.util.Objects; import com.timaar.tiimspot.domain.enumeration.AanwezigheidsStatus; /** * A PersoonEvent. */ @Entity @Table(name = "persoon_event") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) @Document(indexName = "persoonevent") public class PersoonEvent implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @NotNull @Enumerated(EnumType.STRING) @Column(name = "aanwezigheids_status", nullable = false) private AanwezigheidsStatus aanwezigheidsStatus; @OneToOne @JoinColumn(name="event_score_id") private EventScore eventScore; @ManyToOne @JoinColumn(name = "event_id") private Event event; @ManyToOne @JoinColumn(name = "persoon_id") private Persoon persoon; @OneToMany(mappedBy = "persoonEvent", cascade = CascadeType.ALL) @JsonIgnore @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) private Set<Comment> comments = new HashSet<>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public AanwezigheidsStatus getAanwezigheidsStatus() { return aanwezigheidsStatus; } public void setAanwezigheidsStatus(AanwezigheidsStatus aanwezigheidsStatus) { this.aanwezigheidsStatus = aanwezigheidsStatus; } public EventScore getEventScore() { return eventScore; } public void setEventScore(EventScore EventScore) { this.eventScore = EventScore; } public Event getEvent() { return event; } public void setEvent(Event Event) { this.event = Event; } public Persoon getPersoon() { return persoon; } public void setPersoon(Persoon Persoon) { this.persoon = Persoon; } public Set<Comment> getComments() { return comments; } public void setComments(Set<Comment> comments) { this.comments = comments; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PersoonEvent persoonEvent = (PersoonEvent) o; return Objects.equals(id, persoonEvent.id); } @Override public int hashCode() { return Objects.hashCode(id); } @Override public String toString() { return "PersoonEvent{" + "id=" + id + ", aanwezigheidsStatus='" + aanwezigheidsStatus + "'" + '}'; } }
BulkSecurityGeneratorProject/Tiimspot
src/main/java/com/timaar/tiimspot/domain/PersoonEvent.java
928
/** * A PersoonEvent. */
block_comment
nl
package com.timaar.tiimspot.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.springframework.data.elasticsearch.annotations.Document; import javax.persistence.*; import javax.validation.constraints.*; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import java.util.Objects; import com.timaar.tiimspot.domain.enumeration.AanwezigheidsStatus; /** * A PersoonEvent. <SUF>*/ @Entity @Table(name = "persoon_event") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) @Document(indexName = "persoonevent") public class PersoonEvent implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @NotNull @Enumerated(EnumType.STRING) @Column(name = "aanwezigheids_status", nullable = false) private AanwezigheidsStatus aanwezigheidsStatus; @OneToOne @JoinColumn(name="event_score_id") private EventScore eventScore; @ManyToOne @JoinColumn(name = "event_id") private Event event; @ManyToOne @JoinColumn(name = "persoon_id") private Persoon persoon; @OneToMany(mappedBy = "persoonEvent", cascade = CascadeType.ALL) @JsonIgnore @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) private Set<Comment> comments = new HashSet<>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public AanwezigheidsStatus getAanwezigheidsStatus() { return aanwezigheidsStatus; } public void setAanwezigheidsStatus(AanwezigheidsStatus aanwezigheidsStatus) { this.aanwezigheidsStatus = aanwezigheidsStatus; } public EventScore getEventScore() { return eventScore; } public void setEventScore(EventScore EventScore) { this.eventScore = EventScore; } public Event getEvent() { return event; } public void setEvent(Event Event) { this.event = Event; } public Persoon getPersoon() { return persoon; } public void setPersoon(Persoon Persoon) { this.persoon = Persoon; } public Set<Comment> getComments() { return comments; } public void setComments(Set<Comment> comments) { this.comments = comments; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PersoonEvent persoonEvent = (PersoonEvent) o; return Objects.equals(id, persoonEvent.id); } @Override public int hashCode() { return Objects.hashCode(id); } @Override public String toString() { return "PersoonEvent{" + "id=" + id + ", aanwezigheidsStatus='" + aanwezigheidsStatus + "'" + '}'; } }
56940_9
/* * eID Applet Project. * Copyright (C) 2008-2009 FedICT. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version * 3.0 as published by the Free Software Foundation. * * This software 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 this software; if not, see * http://www.gnu.org/licenses/. */ package be.fedict.eid.applet.service; import java.io.Serializable; import java.util.HashMap; import java.util.Map; /** * Enumeration for eID Document Type. * * @author Frank Cornelis * */ public enum DocumentType implements Serializable { BELGIAN_CITIZEN("1"), KIDS_CARD("6"), BOOTSTRAP_CARD("7"), HABILITATION_CARD("8"), /** * Bewijs van inschrijving in het vreemdelingenregister – Tijdelijk verblijf */ FOREIGNER_A("11"), /** * Bewijs van inschrijving in het vreemdelingenregister */ FOREIGNER_B("12"), /** * Identiteitskaart voor vreemdeling */ FOREIGNER_C("13"), /** * EG-Langdurig ingezetene */ FOREIGNER_D("14"), /** * (Verblijfs)kaart van een onderdaan van een lidstaat der EEG Verklaring * van inschrijving */ FOREIGNER_E("15"), /** * Document ter staving van duurzaam verblijf van een EU onderdaan */ FOREIGNER_E_PLUS("16"), /** * Kaart voor niet-EU familieleden van een EU-onderdaan of van een Belg * Verblijfskaart van een familielid van een burger van de Unie */ FOREIGNER_F("17"), /** * Duurzame verblijfskaart van een familielid van een burger van de Unie */ FOREIGNER_F_PLUS("18"), /** * H. Europese blauwe kaart. Toegang en verblijf voor onderdanen van derde * landen. */ EUROPEAN_BLUE_CARD_H("19"); private final int key; private DocumentType(String value) { this.key = toKey(value); } private int toKey(String value) { char c1 = value.charAt(0); int key = c1 - '0'; if (2 == value.length()) { key *= 10; char c2 = value.charAt(1); key += c2 - '0'; } return key; } private static int toKey(byte[] value) { int key = value[0] - '0'; if (2 == value.length) { key *= 10; key += value[1] - '0'; } return key; } private static Map<Integer, DocumentType> documentTypes; static { Map<Integer, DocumentType> documentTypes = new HashMap<Integer, DocumentType>(); for (DocumentType documentType : DocumentType.values()) { int encodedValue = documentType.key; if (documentTypes.containsKey(encodedValue)) { throw new RuntimeException("duplicate document type enum: " + encodedValue); } documentTypes.put(encodedValue, documentType); } DocumentType.documentTypes = documentTypes; } public int getKey() { return this.key; } public static DocumentType toDocumentType(byte[] value) { int key = toKey(value); DocumentType documentType = DocumentType.documentTypes.get(key); /* * If the key is unknown, we simply return null. */ return documentType; } public static String toString(byte[] documentTypeValue) { String str = Integer.toString(toKey(documentTypeValue)); return str; } }
BulkSecurityGeneratorProjectV2/e-Contract__eid-applet
eid-applet-service/src/main/java/be/fedict/eid/applet/service/DocumentType.java
1,146
/** * Duurzame verblijfskaart van een familielid van een burger van de Unie */
block_comment
nl
/* * eID Applet Project. * Copyright (C) 2008-2009 FedICT. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version * 3.0 as published by the Free Software Foundation. * * This software 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 this software; if not, see * http://www.gnu.org/licenses/. */ package be.fedict.eid.applet.service; import java.io.Serializable; import java.util.HashMap; import java.util.Map; /** * Enumeration for eID Document Type. * * @author Frank Cornelis * */ public enum DocumentType implements Serializable { BELGIAN_CITIZEN("1"), KIDS_CARD("6"), BOOTSTRAP_CARD("7"), HABILITATION_CARD("8"), /** * Bewijs van inschrijving in het vreemdelingenregister – Tijdelijk verblijf */ FOREIGNER_A("11"), /** * Bewijs van inschrijving in het vreemdelingenregister */ FOREIGNER_B("12"), /** * Identiteitskaart voor vreemdeling */ FOREIGNER_C("13"), /** * EG-Langdurig ingezetene */ FOREIGNER_D("14"), /** * (Verblijfs)kaart van een onderdaan van een lidstaat der EEG Verklaring * van inschrijving */ FOREIGNER_E("15"), /** * Document ter staving van duurzaam verblijf van een EU onderdaan */ FOREIGNER_E_PLUS("16"), /** * Kaart voor niet-EU familieleden van een EU-onderdaan of van een Belg * Verblijfskaart van een familielid van een burger van de Unie */ FOREIGNER_F("17"), /** * Duurzame verblijfskaart van<SUF>*/ FOREIGNER_F_PLUS("18"), /** * H. Europese blauwe kaart. Toegang en verblijf voor onderdanen van derde * landen. */ EUROPEAN_BLUE_CARD_H("19"); private final int key; private DocumentType(String value) { this.key = toKey(value); } private int toKey(String value) { char c1 = value.charAt(0); int key = c1 - '0'; if (2 == value.length()) { key *= 10; char c2 = value.charAt(1); key += c2 - '0'; } return key; } private static int toKey(byte[] value) { int key = value[0] - '0'; if (2 == value.length) { key *= 10; key += value[1] - '0'; } return key; } private static Map<Integer, DocumentType> documentTypes; static { Map<Integer, DocumentType> documentTypes = new HashMap<Integer, DocumentType>(); for (DocumentType documentType : DocumentType.values()) { int encodedValue = documentType.key; if (documentTypes.containsKey(encodedValue)) { throw new RuntimeException("duplicate document type enum: " + encodedValue); } documentTypes.put(encodedValue, documentType); } DocumentType.documentTypes = documentTypes; } public int getKey() { return this.key; } public static DocumentType toDocumentType(byte[] value) { int key = toKey(value); DocumentType documentType = DocumentType.documentTypes.get(key); /* * If the key is unknown, we simply return null. */ return documentType; } public static String toString(byte[] documentTypeValue) { String str = Integer.toString(toKey(documentTypeValue)); return str; } }
63848_30
package main.puzzle; import java.awt.Point; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.function.Consumer; import java.util.stream.Stream; import main.data.Unit; import main.ui.resource.AppColor; import main.ui.resource.AppText; import main.util.Fn; import main.util.Rational; public class Board implements Comparable<Board>, Serializable { public static int UNUSED = -2; public static int EMPTY = -1; public static int HEIGHT = 8; public static int WIDTH = 8; private final Unit unit; private final int star; private List<Chip> chips; private PuzzleMatrix<Integer> matrix; private final Stat maxStat; private final Stat stat, pt; private final double statPerc; private final int xp; @Override public int compareTo(Board o) { int size = Integer.compare(chips.size(), o.chips.size()); if (size != 0) { return size; } for (int i = 0; i < chips.size(); i++) { int id = chips.get(i).getID().compareTo(o.chips.get(i).getID()); if (id != 0) { return id; } } return 0; } // Combinator - fitness public Board(Board board) { this.unit = board.unit; this.star = board.star; this.chips = new ArrayList<>(); for (Chip c : board.chips) { this.chips.add(new Chip(c)); } colorChips(); this.matrix = new PuzzleMatrix<>(board.matrix); this.maxStat = board.maxStat; this.stat = board.stat; this.pt = board.pt; this.statPerc = board.statPerc; this.xp = board.xp; } // Combination File public Board(Unit unit, int star, Stat maxStat, List<Chip> chips_, List<Point> chipLocs) { this.unit = unit; this.star = star; this.chips = new ArrayList<>(chips_); colorChips(); this.matrix = toPlacement(unit, star, chips, chipLocs); this.maxStat = maxStat; this.stat = Stat.chipStatSum(chips); this.pt = Stat.chipPtSum(chips); this.statPerc = getStatPerc(this.stat, this.maxStat); int xp_ = 0; for (Chip chip : chips) { xp_ += chip.getCumulXP(); } xp = xp_; } // Board Template public Board(Unit unit, int star, Stat maxStat, List<Chip> candidates, BoardTemplate template) { this.unit = unit; this.star = star; int rotation = 0; int min = candidates.size(); for (int r = 0; r < 4; r += unit.getRotationStep(star)) { int count = template.getNumRotationNeeded(r, candidates); if (count < min) { min = count; rotation = r; } } BoardTemplate newTemplate = template.getRotatedTemplate(rotation); List<Puzzle> puzzles = newTemplate.getPuzzles(); this.chips = new ArrayList<>(); for (Chip candidate : candidates) { chips.add(new Chip(candidate)); } int sa = 0; boolean[] sortCache = new boolean[puzzles.size()]; while (sa < puzzles.size()) { Shape shape = puzzles.get(sa).shape; int sb = sa; while (sb + 1 < puzzles.size() && shape == puzzles.get(sb + 1).shape) { sb++; } for (int i = sa; i <= sb; i++) { int r = puzzles.get(i).rotation; if (chips.get(i).getInitRotation() == r) { sortCache[i] = true; continue; } for (int j = sa; j <= sb; j++) { if (i == j || sortCache[j]) { continue; } Chip chip = chips.get(j); if (chip.getInitRotation() == r) { Collections.swap(chips, i, j); sortCache[i] = true; break; } } } sa = sb + 1; } for (int i = 0; i < chips.size(); i++) { Chip chip = chips.get(i); chip.setRotation(puzzles.get(i).rotation); } colorChips(); this.matrix = newTemplate.getMatrix(); this.maxStat = maxStat; this.stat = Stat.chipStatSum(chips); this.pt = Stat.chipPtSum(chips); this.statPerc = getStatPerc(this.stat, this.maxStat); int xp_ = 0; for (Chip chip : chips) { xp_ += chip.getCumulXP(); } xp = xp_; } // <editor-fold defaultstate="collapsed" desc="Name"> public Unit getUnit() { return unit; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Star"> public int getStar() { return star; } public static String getStarHTML_star(int star) { String starStr = ""; for (int i = 0; i < star; i++) { starStr += AppText.TEXT_STAR_FULL; } return Fn.toHTML(Fn.htmlColor(starStr, AppColor.YELLOW_STAR)); } public static String getStarHTML_version(int version) { int nFullRed = version / 2; String fullRedStr = ""; for (int i = 0; i < nFullRed; i++) { fullRedStr += AppText.TEXT_STAR_FULL; } int nHalfRed = version % 2; String halfRedStr = ""; for (int i = 0; i < nHalfRed; i++) { halfRedStr += AppText.TEXT_STAR_EMPTY; } String yellowStr = ""; for (int i = fullRedStr.length() + halfRedStr.length(); i < 5; i++) { yellowStr += AppText.TEXT_STAR_FULL; } return Fn.toHTML(Fn.htmlColor(fullRedStr + halfRedStr, AppColor.RED_STAR) + Fn.htmlColor(yellowStr, AppColor.YELLOW_STAR) ); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Color"> public final Unit.Color getColor() { return unit.getColor(); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Rotation and Ticket"> public int getTicketCount() { int sum = 0; for (Chip chip : chips) { sum += chip.getNumTicket(); } return sum; } // public void minimizeTicket() { // for (int rotation = 0; rotation < 4; rotation += MAP_ROTATIONSTEP.get(name, star)) { // // Start a new board // Board b = new Board(this); // Set<Shape> cShapes = new HashSet<>(); // Chip[] newUsedChips = new Chip[b.chips.size()]; // // Rotate board // b.rotate(rotation); // // for (Chip chip : b.chips) { // cShapes.add(chip.getShape()); // } // // // Get indicies and candidates // for (Shape cs : cShapes) { // Set<Integer> cIndices = new HashSet<>(); // List<Chip> cCandidates = new ArrayList<>(); // for (int i = 0; i < b.chips.size(); i++) { // Chip c = b.chips.get(i); // if (c.getShape() == cs) { // cIndices.add(i); // cCandidates.add(new Chip(c)); // } // } // // Put matching initial rotation // for (Integer cIndex : cIndices) { // int r = b.chips.get(cIndex).getRotation(); // for (Chip c : cCandidates) { // if (c.getInitRotation() == r) { // c.setRotation(c.getInitRotation()); // newUsedChips[cIndex] = c; // cCandidates.remove(c); // break; // } // } // } // // Put remaining // if (!cCandidates.isEmpty()) { // int i = 0; // for (Integer ci : cIndices) { // if (newUsedChips[ci] == null) { // Chip c = cCandidates.get(i); // int r = b.chips.get(ci).getRotation(); // c.setRotation(r); // newUsedChips[ci] = cCandidates.get(i); // i++; // } // } // } // } // b.chips = Arrays.asList(newUsedChips); // // Replace if better // if (getTicketCount() > b.getTicketCount()) { // matrix = b.matrix; // chips = b.chips; // } // // Exit if 0 // if (getTicketCount() == 0) { // break; // } // } // } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="PT"> public Stat getPt() { return pt; } public static Stat getMaxPt(Unit unit, int star) { return getMaxPt(unit, star, getMaxStat(unit, star)); } public static Stat getMaxPt(Unit unit, int star, Stat stat) { int[] statArray = stat.toArray(); int[] optimalPtArray = new int[4]; for (Integer nChip : get56ChipCount(unit, star)) { for (int i = 0; i < 4; i++) { int[] dist = getPtDistribution(Chip.RATES[i], nChip, statArray[i]); int total = 0; for (int d : dist) { total += d; } if (optimalPtArray[i] < total) { optimalPtArray[i] = total; } } } int residue = getCellCount(unit, star) - (optimalPtArray[0] + optimalPtArray[1] + optimalPtArray[2] + optimalPtArray[3]); if (residue > 0) { for (int i = 0; i < 4; i++) { optimalPtArray[i] += residue; } } Stat pt = new Stat(optimalPtArray); return pt; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Stat"> public Stat getStat() { return stat; } public Stat getOldStat() { return Stat.chipOldStatSum(chips); } public Stat getCustomMaxStat() { return maxStat; } public Stat getOrigMaxStat() { return getMaxStat(unit, star); } public static Stat getMaxStat(Unit unit, int star) { return unit.getBoardStats()[Fn.limit(star - 1, 0, unit.getBoardStats().length)]; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Stat Perc"> public double getStatPerc() { return statPerc; } public double getStatPerc(int type) { Stat s = getStat(); Stat m = getCustomMaxStat(); return getStatPerc(type, s, m); } private static double getStatPerc(Stat stat, Stat max) { if (max.allZero()) { return 1.0; } if (stat.allGeq(max)) { return 1.0; } int[] sArray = stat.limit(max).toArray(); int[] mArray = max.toArray(); double s = 0; double m = 0; for (int i = 0; i < 4; i++) { s += new Rational(sArray[i]).div(Chip.RATES[i]).getDouble(); m += new Rational(mArray[i]).div(Chip.RATES[i]).getDouble(); } if (m == 0) { return 1.0; } return s / m; } public static double getStatPerc(int type, Stat stat, Stat max) { int s = stat.toArray()[type]; int m = max.toArray()[type]; if (m == 0) { return 1.0; } return (double) Math.min(s, m) / m; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="HOC, Resonance, and Version"> public Stat getResonance() { int numCell = 0; for (Chip chip : chips) { if (chip.getColor() == getColor()) { numCell += chip.getSize(); } } List<Stat> stats = new ArrayList<>(); for (int key : unit.GetResonanceStats().keySet()) { if (key <= numCell) { stats.add(unit.GetResonanceStats().get(key)); } } return new Stat(stats); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Stat Calc"> private static int[] getPtDistribution(Rational rate, int nChip, int stat) { int stat_1pt = Chip.getMaxEffStat(rate, 1); int[] ptArray = new int[nChip]; int i = 0; while (calcStat(rate, ptArray) < stat) { ptArray[i]++; int iPt = ptArray[i]; int prevLoss = iPt > 0 ? (iPt - 1) * stat_1pt - Chip.getMaxEffStat(rate, (iPt - 1)) : 0; int currentLoss = iPt * stat_1pt - Chip.getMaxEffStat(rate, iPt); int nextLoss = (iPt + 1) * stat_1pt - Chip.getMaxEffStat(rate, (iPt + 1)); if (currentLoss * 2 < prevLoss + nextLoss) { i = (i + 1) % nChip; } } return ptArray; } private static int calcStat(Rational rate, int[] pts) { int out = 0; for (int pt : pts) { out += Chip.getMaxEffStat(rate, pt); } return out; } private static List<Integer> get56ChipCount(Unit unit, int star) { int nCell = getCellCount(unit, star); List<Integer> out = new ArrayList<>(); for (int nSix = 0; nSix < nCell / 6; nSix++) { int rest = nCell - nSix * 6; if (rest % 5 == 0) { int nFive = rest / 5; out.add(nFive + nSix); } } return out; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="XP"> public int getXP() { return xp; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Mark"> public int getMarkedCellCount() { int sum = 0; for (Chip c : chips) { if (c.isMarked()) { sum += c.getSize(); } } return sum; } public int getMarkedChipCount() { int count = 0; for (Chip c : chips) { if (c.isMarked()) { count++; } } return count; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Chips"> public int getChipCount() { return chips.size(); } public List<String> getChipIDs() { List<String> IDs = new ArrayList<>(); for (Chip c : chips) { IDs.add(c.getID()); } return IDs; } public void forEachChip(Consumer<? super Chip> action) { chips.forEach(action); } public Chip getChip(String id) { for (Chip c : chips) { if (c.getID().equals(id)) { return c; } } return null; } public List<Chip> getChips() { List<Chip> out = new ArrayList<>(); for (Chip chip : chips) { out.add(new Chip(chip)); } return out; } public static boolean isChipPlaceable(PuzzleMatrix<Integer> matrix, Set<Point> cps) { for (Point cp : cps) { if (matrix.get(cp.x, cp.y) == null || matrix.get(cp.x, cp.y) != EMPTY) { return false; } } return true; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Matrix and Cells"> public static PuzzleMatrix<Integer> initMatrix(Unit unit, int star) { PuzzleMatrix<Integer> matrix = new PuzzleMatrix<>(unit.getGrid()); for (int r = 0; r < matrix.getNumRow(); r++) { for (int c = 0; c < matrix.getNumCol(); c++) { matrix.set(r, c, matrix.get(r, c) <= star ? EMPTY : UNUSED); } } return matrix; } public PuzzleMatrix<Integer> getMatrix() { return matrix; } public Point getLocation(Chip c) { int i = chips.indexOf(c); if (i < 0) { return null; } return matrix.getPivot(i); } public static int getCellCount(Unit unit, int star) { PuzzleMatrix<Integer> s = initMatrix(unit, star); return s.getNumNotContaining(UNUSED); } public static boolean rs_isValid(Unit unit, int star, String data) { String[] split = data.split(";"); String[] shapeStrs = split[0].split(","); Integer[] rotations = Stream.of(split[1].split(",")) .map(Integer::valueOf) .toArray(Integer[]::new); Point[] locations = Stream.of(split[2].split(",")) .map((s) -> s.split("\\.")) .map((sp) -> new Point(Integer.valueOf(sp[0]), Integer.valueOf(sp[1]))) .toArray(Point[]::new); PuzzleMatrix<Boolean> board = rs_getBoolMatrix(unit, star); for (int i = 0; i < shapeStrs.length; i++) { Shape shape = Shape.byId(Integer.parseInt(shapeStrs[i])); int rotation = rotations[i]; Point location = locations[i]; Set<Point> pts = rs_getPts(shape, rotation, location); for (Point p : pts) { if (p.x < 0 || WIDTH - 1 < p.x) { return false; } if (p.y < 0 || HEIGHT - 1 < p.y) { return false; } if (!board.get(p.x, p.y)) { return false; } board.set(p.x, p.y, false); } } return true; } private static PuzzleMatrix<Boolean> rs_getBoolMatrix(Unit unit, int star) { Integer[][] levelGrid = unit.getGrid(); PuzzleMatrix<Boolean> out = new PuzzleMatrix<>(HEIGHT, WIDTH, false); for (int r = 0; r < HEIGHT; r++) { for (int c = 0; c < WIDTH; c++) { out.set(r, c, levelGrid[r][c] <= star); } } return out; } private static Set<Point> rs_getPts(Shape shape, int rotation, Point location) { PuzzleMatrix<Boolean> cm = new PuzzleMatrix<>(Chip.generateMatrix(shape, rotation)); Point pivot = cm.getPivot(true); Set<Point> pts = cm.getPoints(true); pts.forEach((p) -> p.translate(location.x - pivot.x, location.y - pivot.y)); return pts; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Image"> public final void colorChips() { for (int i = 0; i < chips.size(); i++) { Chip c = chips.get(i); c.setBoardIndex(i); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="File"> public static PuzzleMatrix<Integer> toPlacement(Unit unit, int star, List<Chip> chips, List<Point> locations) { List<Puzzle> puzzles = new ArrayList<>(chips.size()); for (int i = 0; i < chips.size(); i++) { Chip c = chips.get(i); Shape s = c.getShape(); int r = c.getRotation(); Point l = locations.get(i); puzzles.add(new Puzzle(s, r, l)); } return toPlacement(unit, star, puzzles); } public static PuzzleMatrix<Integer> toPlacement(Unit unit, int star, List<Puzzle> puzzles) { // Placement PuzzleMatrix<Integer> placement = initMatrix(unit, star); for (int i = 0; i < puzzles.size(); i++) { PuzzleMatrix<Boolean> matrix = Chip.generateMatrix(puzzles.get(i).shape, puzzles.get(i).rotation); Set<Point> pts = matrix.getPoints(true); Point fp = matrix.getPivot(true); Point bp = puzzles.get(i).location; for (Point p : pts) { p.translate(bp.x - fp.x, bp.y - fp.y); placement.set(p.x, p.y, i); } } return placement; } public static List<Point> toLocation(PuzzleMatrix<Integer> placement) { List<Point> location = new ArrayList<>(); int i = 0; boolean found = true; while (found) { found = false; Point p = placement.getPivot(i); if (p != null) { found = true; location.add(p); } i++; } return location; } // </editor-fold> }
Bunnyspa/GFChipCalc
src/main/puzzle/Board.java
6,478
// int r = b.chips.get(ci).getRotation();
line_comment
nl
package main.puzzle; import java.awt.Point; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.function.Consumer; import java.util.stream.Stream; import main.data.Unit; import main.ui.resource.AppColor; import main.ui.resource.AppText; import main.util.Fn; import main.util.Rational; public class Board implements Comparable<Board>, Serializable { public static int UNUSED = -2; public static int EMPTY = -1; public static int HEIGHT = 8; public static int WIDTH = 8; private final Unit unit; private final int star; private List<Chip> chips; private PuzzleMatrix<Integer> matrix; private final Stat maxStat; private final Stat stat, pt; private final double statPerc; private final int xp; @Override public int compareTo(Board o) { int size = Integer.compare(chips.size(), o.chips.size()); if (size != 0) { return size; } for (int i = 0; i < chips.size(); i++) { int id = chips.get(i).getID().compareTo(o.chips.get(i).getID()); if (id != 0) { return id; } } return 0; } // Combinator - fitness public Board(Board board) { this.unit = board.unit; this.star = board.star; this.chips = new ArrayList<>(); for (Chip c : board.chips) { this.chips.add(new Chip(c)); } colorChips(); this.matrix = new PuzzleMatrix<>(board.matrix); this.maxStat = board.maxStat; this.stat = board.stat; this.pt = board.pt; this.statPerc = board.statPerc; this.xp = board.xp; } // Combination File public Board(Unit unit, int star, Stat maxStat, List<Chip> chips_, List<Point> chipLocs) { this.unit = unit; this.star = star; this.chips = new ArrayList<>(chips_); colorChips(); this.matrix = toPlacement(unit, star, chips, chipLocs); this.maxStat = maxStat; this.stat = Stat.chipStatSum(chips); this.pt = Stat.chipPtSum(chips); this.statPerc = getStatPerc(this.stat, this.maxStat); int xp_ = 0; for (Chip chip : chips) { xp_ += chip.getCumulXP(); } xp = xp_; } // Board Template public Board(Unit unit, int star, Stat maxStat, List<Chip> candidates, BoardTemplate template) { this.unit = unit; this.star = star; int rotation = 0; int min = candidates.size(); for (int r = 0; r < 4; r += unit.getRotationStep(star)) { int count = template.getNumRotationNeeded(r, candidates); if (count < min) { min = count; rotation = r; } } BoardTemplate newTemplate = template.getRotatedTemplate(rotation); List<Puzzle> puzzles = newTemplate.getPuzzles(); this.chips = new ArrayList<>(); for (Chip candidate : candidates) { chips.add(new Chip(candidate)); } int sa = 0; boolean[] sortCache = new boolean[puzzles.size()]; while (sa < puzzles.size()) { Shape shape = puzzles.get(sa).shape; int sb = sa; while (sb + 1 < puzzles.size() && shape == puzzles.get(sb + 1).shape) { sb++; } for (int i = sa; i <= sb; i++) { int r = puzzles.get(i).rotation; if (chips.get(i).getInitRotation() == r) { sortCache[i] = true; continue; } for (int j = sa; j <= sb; j++) { if (i == j || sortCache[j]) { continue; } Chip chip = chips.get(j); if (chip.getInitRotation() == r) { Collections.swap(chips, i, j); sortCache[i] = true; break; } } } sa = sb + 1; } for (int i = 0; i < chips.size(); i++) { Chip chip = chips.get(i); chip.setRotation(puzzles.get(i).rotation); } colorChips(); this.matrix = newTemplate.getMatrix(); this.maxStat = maxStat; this.stat = Stat.chipStatSum(chips); this.pt = Stat.chipPtSum(chips); this.statPerc = getStatPerc(this.stat, this.maxStat); int xp_ = 0; for (Chip chip : chips) { xp_ += chip.getCumulXP(); } xp = xp_; } // <editor-fold defaultstate="collapsed" desc="Name"> public Unit getUnit() { return unit; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Star"> public int getStar() { return star; } public static String getStarHTML_star(int star) { String starStr = ""; for (int i = 0; i < star; i++) { starStr += AppText.TEXT_STAR_FULL; } return Fn.toHTML(Fn.htmlColor(starStr, AppColor.YELLOW_STAR)); } public static String getStarHTML_version(int version) { int nFullRed = version / 2; String fullRedStr = ""; for (int i = 0; i < nFullRed; i++) { fullRedStr += AppText.TEXT_STAR_FULL; } int nHalfRed = version % 2; String halfRedStr = ""; for (int i = 0; i < nHalfRed; i++) { halfRedStr += AppText.TEXT_STAR_EMPTY; } String yellowStr = ""; for (int i = fullRedStr.length() + halfRedStr.length(); i < 5; i++) { yellowStr += AppText.TEXT_STAR_FULL; } return Fn.toHTML(Fn.htmlColor(fullRedStr + halfRedStr, AppColor.RED_STAR) + Fn.htmlColor(yellowStr, AppColor.YELLOW_STAR) ); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Color"> public final Unit.Color getColor() { return unit.getColor(); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Rotation and Ticket"> public int getTicketCount() { int sum = 0; for (Chip chip : chips) { sum += chip.getNumTicket(); } return sum; } // public void minimizeTicket() { // for (int rotation = 0; rotation < 4; rotation += MAP_ROTATIONSTEP.get(name, star)) { // // Start a new board // Board b = new Board(this); // Set<Shape> cShapes = new HashSet<>(); // Chip[] newUsedChips = new Chip[b.chips.size()]; // // Rotate board // b.rotate(rotation); // // for (Chip chip : b.chips) { // cShapes.add(chip.getShape()); // } // // // Get indicies and candidates // for (Shape cs : cShapes) { // Set<Integer> cIndices = new HashSet<>(); // List<Chip> cCandidates = new ArrayList<>(); // for (int i = 0; i < b.chips.size(); i++) { // Chip c = b.chips.get(i); // if (c.getShape() == cs) { // cIndices.add(i); // cCandidates.add(new Chip(c)); // } // } // // Put matching initial rotation // for (Integer cIndex : cIndices) { // int r = b.chips.get(cIndex).getRotation(); // for (Chip c : cCandidates) { // if (c.getInitRotation() == r) { // c.setRotation(c.getInitRotation()); // newUsedChips[cIndex] = c; // cCandidates.remove(c); // break; // } // } // } // // Put remaining // if (!cCandidates.isEmpty()) { // int i = 0; // for (Integer ci : cIndices) { // if (newUsedChips[ci] == null) { // Chip c = cCandidates.get(i); // int r<SUF> // c.setRotation(r); // newUsedChips[ci] = cCandidates.get(i); // i++; // } // } // } // } // b.chips = Arrays.asList(newUsedChips); // // Replace if better // if (getTicketCount() > b.getTicketCount()) { // matrix = b.matrix; // chips = b.chips; // } // // Exit if 0 // if (getTicketCount() == 0) { // break; // } // } // } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="PT"> public Stat getPt() { return pt; } public static Stat getMaxPt(Unit unit, int star) { return getMaxPt(unit, star, getMaxStat(unit, star)); } public static Stat getMaxPt(Unit unit, int star, Stat stat) { int[] statArray = stat.toArray(); int[] optimalPtArray = new int[4]; for (Integer nChip : get56ChipCount(unit, star)) { for (int i = 0; i < 4; i++) { int[] dist = getPtDistribution(Chip.RATES[i], nChip, statArray[i]); int total = 0; for (int d : dist) { total += d; } if (optimalPtArray[i] < total) { optimalPtArray[i] = total; } } } int residue = getCellCount(unit, star) - (optimalPtArray[0] + optimalPtArray[1] + optimalPtArray[2] + optimalPtArray[3]); if (residue > 0) { for (int i = 0; i < 4; i++) { optimalPtArray[i] += residue; } } Stat pt = new Stat(optimalPtArray); return pt; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Stat"> public Stat getStat() { return stat; } public Stat getOldStat() { return Stat.chipOldStatSum(chips); } public Stat getCustomMaxStat() { return maxStat; } public Stat getOrigMaxStat() { return getMaxStat(unit, star); } public static Stat getMaxStat(Unit unit, int star) { return unit.getBoardStats()[Fn.limit(star - 1, 0, unit.getBoardStats().length)]; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Stat Perc"> public double getStatPerc() { return statPerc; } public double getStatPerc(int type) { Stat s = getStat(); Stat m = getCustomMaxStat(); return getStatPerc(type, s, m); } private static double getStatPerc(Stat stat, Stat max) { if (max.allZero()) { return 1.0; } if (stat.allGeq(max)) { return 1.0; } int[] sArray = stat.limit(max).toArray(); int[] mArray = max.toArray(); double s = 0; double m = 0; for (int i = 0; i < 4; i++) { s += new Rational(sArray[i]).div(Chip.RATES[i]).getDouble(); m += new Rational(mArray[i]).div(Chip.RATES[i]).getDouble(); } if (m == 0) { return 1.0; } return s / m; } public static double getStatPerc(int type, Stat stat, Stat max) { int s = stat.toArray()[type]; int m = max.toArray()[type]; if (m == 0) { return 1.0; } return (double) Math.min(s, m) / m; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="HOC, Resonance, and Version"> public Stat getResonance() { int numCell = 0; for (Chip chip : chips) { if (chip.getColor() == getColor()) { numCell += chip.getSize(); } } List<Stat> stats = new ArrayList<>(); for (int key : unit.GetResonanceStats().keySet()) { if (key <= numCell) { stats.add(unit.GetResonanceStats().get(key)); } } return new Stat(stats); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Stat Calc"> private static int[] getPtDistribution(Rational rate, int nChip, int stat) { int stat_1pt = Chip.getMaxEffStat(rate, 1); int[] ptArray = new int[nChip]; int i = 0; while (calcStat(rate, ptArray) < stat) { ptArray[i]++; int iPt = ptArray[i]; int prevLoss = iPt > 0 ? (iPt - 1) * stat_1pt - Chip.getMaxEffStat(rate, (iPt - 1)) : 0; int currentLoss = iPt * stat_1pt - Chip.getMaxEffStat(rate, iPt); int nextLoss = (iPt + 1) * stat_1pt - Chip.getMaxEffStat(rate, (iPt + 1)); if (currentLoss * 2 < prevLoss + nextLoss) { i = (i + 1) % nChip; } } return ptArray; } private static int calcStat(Rational rate, int[] pts) { int out = 0; for (int pt : pts) { out += Chip.getMaxEffStat(rate, pt); } return out; } private static List<Integer> get56ChipCount(Unit unit, int star) { int nCell = getCellCount(unit, star); List<Integer> out = new ArrayList<>(); for (int nSix = 0; nSix < nCell / 6; nSix++) { int rest = nCell - nSix * 6; if (rest % 5 == 0) { int nFive = rest / 5; out.add(nFive + nSix); } } return out; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="XP"> public int getXP() { return xp; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Mark"> public int getMarkedCellCount() { int sum = 0; for (Chip c : chips) { if (c.isMarked()) { sum += c.getSize(); } } return sum; } public int getMarkedChipCount() { int count = 0; for (Chip c : chips) { if (c.isMarked()) { count++; } } return count; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Chips"> public int getChipCount() { return chips.size(); } public List<String> getChipIDs() { List<String> IDs = new ArrayList<>(); for (Chip c : chips) { IDs.add(c.getID()); } return IDs; } public void forEachChip(Consumer<? super Chip> action) { chips.forEach(action); } public Chip getChip(String id) { for (Chip c : chips) { if (c.getID().equals(id)) { return c; } } return null; } public List<Chip> getChips() { List<Chip> out = new ArrayList<>(); for (Chip chip : chips) { out.add(new Chip(chip)); } return out; } public static boolean isChipPlaceable(PuzzleMatrix<Integer> matrix, Set<Point> cps) { for (Point cp : cps) { if (matrix.get(cp.x, cp.y) == null || matrix.get(cp.x, cp.y) != EMPTY) { return false; } } return true; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Matrix and Cells"> public static PuzzleMatrix<Integer> initMatrix(Unit unit, int star) { PuzzleMatrix<Integer> matrix = new PuzzleMatrix<>(unit.getGrid()); for (int r = 0; r < matrix.getNumRow(); r++) { for (int c = 0; c < matrix.getNumCol(); c++) { matrix.set(r, c, matrix.get(r, c) <= star ? EMPTY : UNUSED); } } return matrix; } public PuzzleMatrix<Integer> getMatrix() { return matrix; } public Point getLocation(Chip c) { int i = chips.indexOf(c); if (i < 0) { return null; } return matrix.getPivot(i); } public static int getCellCount(Unit unit, int star) { PuzzleMatrix<Integer> s = initMatrix(unit, star); return s.getNumNotContaining(UNUSED); } public static boolean rs_isValid(Unit unit, int star, String data) { String[] split = data.split(";"); String[] shapeStrs = split[0].split(","); Integer[] rotations = Stream.of(split[1].split(",")) .map(Integer::valueOf) .toArray(Integer[]::new); Point[] locations = Stream.of(split[2].split(",")) .map((s) -> s.split("\\.")) .map((sp) -> new Point(Integer.valueOf(sp[0]), Integer.valueOf(sp[1]))) .toArray(Point[]::new); PuzzleMatrix<Boolean> board = rs_getBoolMatrix(unit, star); for (int i = 0; i < shapeStrs.length; i++) { Shape shape = Shape.byId(Integer.parseInt(shapeStrs[i])); int rotation = rotations[i]; Point location = locations[i]; Set<Point> pts = rs_getPts(shape, rotation, location); for (Point p : pts) { if (p.x < 0 || WIDTH - 1 < p.x) { return false; } if (p.y < 0 || HEIGHT - 1 < p.y) { return false; } if (!board.get(p.x, p.y)) { return false; } board.set(p.x, p.y, false); } } return true; } private static PuzzleMatrix<Boolean> rs_getBoolMatrix(Unit unit, int star) { Integer[][] levelGrid = unit.getGrid(); PuzzleMatrix<Boolean> out = new PuzzleMatrix<>(HEIGHT, WIDTH, false); for (int r = 0; r < HEIGHT; r++) { for (int c = 0; c < WIDTH; c++) { out.set(r, c, levelGrid[r][c] <= star); } } return out; } private static Set<Point> rs_getPts(Shape shape, int rotation, Point location) { PuzzleMatrix<Boolean> cm = new PuzzleMatrix<>(Chip.generateMatrix(shape, rotation)); Point pivot = cm.getPivot(true); Set<Point> pts = cm.getPoints(true); pts.forEach((p) -> p.translate(location.x - pivot.x, location.y - pivot.y)); return pts; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Image"> public final void colorChips() { for (int i = 0; i < chips.size(); i++) { Chip c = chips.get(i); c.setBoardIndex(i); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="File"> public static PuzzleMatrix<Integer> toPlacement(Unit unit, int star, List<Chip> chips, List<Point> locations) { List<Puzzle> puzzles = new ArrayList<>(chips.size()); for (int i = 0; i < chips.size(); i++) { Chip c = chips.get(i); Shape s = c.getShape(); int r = c.getRotation(); Point l = locations.get(i); puzzles.add(new Puzzle(s, r, l)); } return toPlacement(unit, star, puzzles); } public static PuzzleMatrix<Integer> toPlacement(Unit unit, int star, List<Puzzle> puzzles) { // Placement PuzzleMatrix<Integer> placement = initMatrix(unit, star); for (int i = 0; i < puzzles.size(); i++) { PuzzleMatrix<Boolean> matrix = Chip.generateMatrix(puzzles.get(i).shape, puzzles.get(i).rotation); Set<Point> pts = matrix.getPoints(true); Point fp = matrix.getPivot(true); Point bp = puzzles.get(i).location; for (Point p : pts) { p.translate(bp.x - fp.x, bp.y - fp.y); placement.set(p.x, p.y, i); } } return placement; } public static List<Point> toLocation(PuzzleMatrix<Integer> placement) { List<Point> location = new ArrayList<>(); int i = 0; boolean found = true; while (found) { found = false; Point p = placement.getPivot(i); if (p != null) { found = true; location.add(p); } i++; } return location; } // </editor-fold> }
83729_15
package org.apache.lucene.analysis.nl; /** * Copyright 2004 The Apache Software Foundation * * 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. */ import java.util.Map; /** * * A stemmer for Dutch words. The algorithm is an implementation of * the <a href="http://snowball.tartarus.org/algorithms/dutch/stemmer.html">dutch stemming</a> * algorithm in Martin Porter's snowball project. * * @author Edwin de Jonge (ejne at cbs.nl) */ public class DutchStemmer { /** * Buffer for the terms while stemming them. */ private StringBuffer sb = new StringBuffer(); private boolean _removedE; private Map _stemDict; private int _R1; private int _R2; //TODO convert to internal /* * Stemms the given term to an unique <tt>discriminator</tt>. * * @param term The term that should be stemmed. * @return Discriminator for <tt>term</tt> */ public String stem(String term) { term = term.toLowerCase(); if (!isStemmable(term)) return term; if (_stemDict != null && _stemDict.containsKey(term)) if (_stemDict.get(term) instanceof String) return (String) _stemDict.get(term); else return null; // Reset the StringBuffer. sb.delete(0, sb.length()); sb.insert(0, term); // Stemming starts here... substitute(sb); storeYandI(sb); _R1 = getRIndex(sb, 0); _R1 = Math.max(3, _R1); step1(sb); step2(sb); _R2 = getRIndex(sb, _R1); step3a(sb); step3b(sb); step4(sb); reStoreYandI(sb); return sb.toString(); } private boolean enEnding(StringBuffer sb) { String[] enend = new String[]{"ene", "en"}; for (int i = 0; i < enend.length; i++) { String end = enend[i]; String s = sb.toString(); int index = s.length() - end.length(); if (s.endsWith(end) && index >= _R1 && isValidEnEnding(sb, index - 1) ) { sb.delete(index, index + end.length()); unDouble(sb, index); return true; } } return false; } private void step1(StringBuffer sb) { if (_R1 >= sb.length()) return; String s = sb.toString(); int lengthR1 = sb.length() - _R1; int index; if (s.endsWith("heden")) { sb.replace(_R1, lengthR1 + _R1, sb.substring(_R1, lengthR1 + _R1).replaceAll("heden", "heid")); return; } if (enEnding(sb)) return; if (s.endsWith("se") && (index = s.length() - 2) >= _R1 && isValidSEnding(sb, index - 1) ) { sb.delete(index, index + 2); return; } if (s.endsWith("s") && (index = s.length() - 1) >= _R1 && isValidSEnding(sb, index - 1)) { sb.delete(index, index + 1); } } /** * Delete suffix e if in R1 and * preceded by a non-vowel, and then undouble the ending * * @param sb String being stemmed */ private void step2(StringBuffer sb) { _removedE = false; if (_R1 >= sb.length()) return; String s = sb.toString(); int index = s.length() - 1; if (index >= _R1 && s.endsWith("e") && !isVowel(sb.charAt(index - 1))) { sb.delete(index, index + 1); unDouble(sb); _removedE = true; } } /** * Delete "heid" * * @param sb String being stemmed */ private void step3a(StringBuffer sb) { if (_R2 >= sb.length()) return; String s = sb.toString(); int index = s.length() - 4; if (s.endsWith("heid") && index >= _R2 && sb.charAt(index - 1) != 'c') { sb.delete(index, index + 4); //remove heid enEnding(sb); } } /** * <p>A d-suffix, or derivational suffix, enables a new word, * often with a different grammatical category, or with a different * sense, to be built from another word. Whether a d-suffix can be * attached is discovered not from the rules of grammar, but by * referring to a dictionary. So in English, ness can be added to * certain adjectives to form corresponding nouns (littleness, * kindness, foolishness ...) but not to all adjectives * (not for example, to big, cruel, wise ...) d-suffixes can be * used to change meaning, often in rather exotic ways.</p> * Remove "ing", "end", "ig", "lijk", "baar" and "bar" * * @param sb String being stemmed */ private void step3b(StringBuffer sb) { if (_R2 >= sb.length()) return; String s = sb.toString(); int index = 0; if ((s.endsWith("end") || s.endsWith("ing")) && (index = s.length() - 3) >= _R2) { sb.delete(index, index + 3); if (sb.charAt(index - 2) == 'i' && sb.charAt(index - 1) == 'g') { if (sb.charAt(index - 3) != 'e' & index - 2 >= _R2) { index -= 2; sb.delete(index, index + 2); } } else { unDouble(sb, index); } return; } if (s.endsWith("ig") && (index = s.length() - 2) >= _R2 ) { if (sb.charAt(index - 1) != 'e') sb.delete(index, index + 2); return; } if (s.endsWith("lijk") && (index = s.length() - 4) >= _R2 ) { sb.delete(index, index + 4); step2(sb); return; } if (s.endsWith("baar") && (index = s.length() - 4) >= _R2 ) { sb.delete(index, index + 4); return; } if (s.endsWith("bar") && (index = s.length() - 3) >= _R2 ) { if (_removedE) sb.delete(index, index + 3); return; } } /** * undouble vowel * If the words ends CVD, where C is a non-vowel, D is a non-vowel other than I, and V is double a, e, o or u, remove one of the vowels from V (for example, maan -> man, brood -> brod). * * @param sb String being stemmed */ private void step4(StringBuffer sb) { if (sb.length() < 4) return; String end = sb.substring(sb.length() - 4, sb.length()); char c = end.charAt(0); char v1 = end.charAt(1); char v2 = end.charAt(2); char d = end.charAt(3); if (v1 == v2 && d != 'I' && v1 != 'i' && isVowel(v1) && !isVowel(d) && !isVowel(c)) { sb.delete(sb.length() - 2, sb.length() - 1); } } /** * Checks if a term could be stemmed. * * @return true if, and only if, the given term consists in letters. */ private boolean isStemmable(String term) { for (int c = 0; c < term.length(); c++) { if (!Character.isLetter(term.charAt(c))) return false; } return true; } /** * Substitute ä, ë, ï, ö, ü, á , é, í, ó, ú */ private void substitute(StringBuffer buffer) { for (int i = 0; i < buffer.length(); i++) { switch (buffer.charAt(i)) { case 'ä': case 'á': { buffer.setCharAt(i, 'a'); break; } case 'ë': case 'é': { buffer.setCharAt(i, 'e'); break; } case 'ü': case 'ú': { buffer.setCharAt(i, 'u'); break; } case 'ï': case 'i': { buffer.setCharAt(i, 'i'); break; } case 'ö': case 'ó': { buffer.setCharAt(i, 'o'); break; } } } } /*private boolean isValidSEnding(StringBuffer sb) { return isValidSEnding(sb, sb.length() - 1); }*/ private boolean isValidSEnding(StringBuffer sb, int index) { char c = sb.charAt(index); if (isVowel(c) || c == 'j') return false; return true; } /*private boolean isValidEnEnding(StringBuffer sb) { return isValidEnEnding(sb, sb.length() - 1); }*/ private boolean isValidEnEnding(StringBuffer sb, int index) { char c = sb.charAt(index); if (isVowel(c)) return false; if (c < 3) return false; // ends with "gem"? if (c == 'm' && sb.charAt(index - 2) == 'g' && sb.charAt(index - 1) == 'e') return false; return true; } private void unDouble(StringBuffer sb) { unDouble(sb, sb.length()); } private void unDouble(StringBuffer sb, int endIndex) { String s = sb.substring(0, endIndex); if (s.endsWith("kk") || s.endsWith("tt") || s.endsWith("dd") || s.endsWith("nn") || s.endsWith("mm") || s.endsWith("ff")) { sb.delete(endIndex - 1, endIndex); } } private int getRIndex(StringBuffer sb, int start) { if (start == 0) start = 1; int i = start; for (; i < sb.length(); i++) { //first non-vowel preceded by a vowel if (!isVowel(sb.charAt(i)) && isVowel(sb.charAt(i - 1))) { return i + 1; } } return i + 1; } private void storeYandI(StringBuffer sb) { if (sb.charAt(0) == 'y') sb.setCharAt(0, 'Y'); int last = sb.length() - 1; for (int i = 1; i < last; i++) { switch (sb.charAt(i)) { case 'i': { if (isVowel(sb.charAt(i - 1)) && isVowel(sb.charAt(i + 1)) ) sb.setCharAt(i, 'I'); break; } case 'y': { if (isVowel(sb.charAt(i - 1))) sb.setCharAt(i, 'Y'); break; } } } if (last > 0 && sb.charAt(last) == 'y' && isVowel(sb.charAt(last - 1))) sb.setCharAt(last, 'Y'); } private void reStoreYandI(StringBuffer sb) { String tmp = sb.toString(); sb.delete(0, sb.length()); sb.insert(0, tmp.replaceAll("I", "i").replaceAll("Y", "y")); } private boolean isVowel(char c) { switch (c) { case 'e': case 'a': case 'o': case 'i': case 'u': case 'y': case 'è': { return true; } } return false; } void setStemDictionary(Map dict) { _stemDict = dict; } }
BurningBright/lucene
contrib/analyzers/src/java/org/apache/lucene/analysis/nl/DutchStemmer.java
3,753
// ends with "gem"?
line_comment
nl
package org.apache.lucene.analysis.nl; /** * Copyright 2004 The Apache Software Foundation * * 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. */ import java.util.Map; /** * * A stemmer for Dutch words. The algorithm is an implementation of * the <a href="http://snowball.tartarus.org/algorithms/dutch/stemmer.html">dutch stemming</a> * algorithm in Martin Porter's snowball project. * * @author Edwin de Jonge (ejne at cbs.nl) */ public class DutchStemmer { /** * Buffer for the terms while stemming them. */ private StringBuffer sb = new StringBuffer(); private boolean _removedE; private Map _stemDict; private int _R1; private int _R2; //TODO convert to internal /* * Stemms the given term to an unique <tt>discriminator</tt>. * * @param term The term that should be stemmed. * @return Discriminator for <tt>term</tt> */ public String stem(String term) { term = term.toLowerCase(); if (!isStemmable(term)) return term; if (_stemDict != null && _stemDict.containsKey(term)) if (_stemDict.get(term) instanceof String) return (String) _stemDict.get(term); else return null; // Reset the StringBuffer. sb.delete(0, sb.length()); sb.insert(0, term); // Stemming starts here... substitute(sb); storeYandI(sb); _R1 = getRIndex(sb, 0); _R1 = Math.max(3, _R1); step1(sb); step2(sb); _R2 = getRIndex(sb, _R1); step3a(sb); step3b(sb); step4(sb); reStoreYandI(sb); return sb.toString(); } private boolean enEnding(StringBuffer sb) { String[] enend = new String[]{"ene", "en"}; for (int i = 0; i < enend.length; i++) { String end = enend[i]; String s = sb.toString(); int index = s.length() - end.length(); if (s.endsWith(end) && index >= _R1 && isValidEnEnding(sb, index - 1) ) { sb.delete(index, index + end.length()); unDouble(sb, index); return true; } } return false; } private void step1(StringBuffer sb) { if (_R1 >= sb.length()) return; String s = sb.toString(); int lengthR1 = sb.length() - _R1; int index; if (s.endsWith("heden")) { sb.replace(_R1, lengthR1 + _R1, sb.substring(_R1, lengthR1 + _R1).replaceAll("heden", "heid")); return; } if (enEnding(sb)) return; if (s.endsWith("se") && (index = s.length() - 2) >= _R1 && isValidSEnding(sb, index - 1) ) { sb.delete(index, index + 2); return; } if (s.endsWith("s") && (index = s.length() - 1) >= _R1 && isValidSEnding(sb, index - 1)) { sb.delete(index, index + 1); } } /** * Delete suffix e if in R1 and * preceded by a non-vowel, and then undouble the ending * * @param sb String being stemmed */ private void step2(StringBuffer sb) { _removedE = false; if (_R1 >= sb.length()) return; String s = sb.toString(); int index = s.length() - 1; if (index >= _R1 && s.endsWith("e") && !isVowel(sb.charAt(index - 1))) { sb.delete(index, index + 1); unDouble(sb); _removedE = true; } } /** * Delete "heid" * * @param sb String being stemmed */ private void step3a(StringBuffer sb) { if (_R2 >= sb.length()) return; String s = sb.toString(); int index = s.length() - 4; if (s.endsWith("heid") && index >= _R2 && sb.charAt(index - 1) != 'c') { sb.delete(index, index + 4); //remove heid enEnding(sb); } } /** * <p>A d-suffix, or derivational suffix, enables a new word, * often with a different grammatical category, or with a different * sense, to be built from another word. Whether a d-suffix can be * attached is discovered not from the rules of grammar, but by * referring to a dictionary. So in English, ness can be added to * certain adjectives to form corresponding nouns (littleness, * kindness, foolishness ...) but not to all adjectives * (not for example, to big, cruel, wise ...) d-suffixes can be * used to change meaning, often in rather exotic ways.</p> * Remove "ing", "end", "ig", "lijk", "baar" and "bar" * * @param sb String being stemmed */ private void step3b(StringBuffer sb) { if (_R2 >= sb.length()) return; String s = sb.toString(); int index = 0; if ((s.endsWith("end") || s.endsWith("ing")) && (index = s.length() - 3) >= _R2) { sb.delete(index, index + 3); if (sb.charAt(index - 2) == 'i' && sb.charAt(index - 1) == 'g') { if (sb.charAt(index - 3) != 'e' & index - 2 >= _R2) { index -= 2; sb.delete(index, index + 2); } } else { unDouble(sb, index); } return; } if (s.endsWith("ig") && (index = s.length() - 2) >= _R2 ) { if (sb.charAt(index - 1) != 'e') sb.delete(index, index + 2); return; } if (s.endsWith("lijk") && (index = s.length() - 4) >= _R2 ) { sb.delete(index, index + 4); step2(sb); return; } if (s.endsWith("baar") && (index = s.length() - 4) >= _R2 ) { sb.delete(index, index + 4); return; } if (s.endsWith("bar") && (index = s.length() - 3) >= _R2 ) { if (_removedE) sb.delete(index, index + 3); return; } } /** * undouble vowel * If the words ends CVD, where C is a non-vowel, D is a non-vowel other than I, and V is double a, e, o or u, remove one of the vowels from V (for example, maan -> man, brood -> brod). * * @param sb String being stemmed */ private void step4(StringBuffer sb) { if (sb.length() < 4) return; String end = sb.substring(sb.length() - 4, sb.length()); char c = end.charAt(0); char v1 = end.charAt(1); char v2 = end.charAt(2); char d = end.charAt(3); if (v1 == v2 && d != 'I' && v1 != 'i' && isVowel(v1) && !isVowel(d) && !isVowel(c)) { sb.delete(sb.length() - 2, sb.length() - 1); } } /** * Checks if a term could be stemmed. * * @return true if, and only if, the given term consists in letters. */ private boolean isStemmable(String term) { for (int c = 0; c < term.length(); c++) { if (!Character.isLetter(term.charAt(c))) return false; } return true; } /** * Substitute ä, ë, ï, ö, ü, á , é, í, ó, ú */ private void substitute(StringBuffer buffer) { for (int i = 0; i < buffer.length(); i++) { switch (buffer.charAt(i)) { case 'ä': case 'á': { buffer.setCharAt(i, 'a'); break; } case 'ë': case 'é': { buffer.setCharAt(i, 'e'); break; } case 'ü': case 'ú': { buffer.setCharAt(i, 'u'); break; } case 'ï': case 'i': { buffer.setCharAt(i, 'i'); break; } case 'ö': case 'ó': { buffer.setCharAt(i, 'o'); break; } } } } /*private boolean isValidSEnding(StringBuffer sb) { return isValidSEnding(sb, sb.length() - 1); }*/ private boolean isValidSEnding(StringBuffer sb, int index) { char c = sb.charAt(index); if (isVowel(c) || c == 'j') return false; return true; } /*private boolean isValidEnEnding(StringBuffer sb) { return isValidEnEnding(sb, sb.length() - 1); }*/ private boolean isValidEnEnding(StringBuffer sb, int index) { char c = sb.charAt(index); if (isVowel(c)) return false; if (c < 3) return false; // ends with<SUF> if (c == 'm' && sb.charAt(index - 2) == 'g' && sb.charAt(index - 1) == 'e') return false; return true; } private void unDouble(StringBuffer sb) { unDouble(sb, sb.length()); } private void unDouble(StringBuffer sb, int endIndex) { String s = sb.substring(0, endIndex); if (s.endsWith("kk") || s.endsWith("tt") || s.endsWith("dd") || s.endsWith("nn") || s.endsWith("mm") || s.endsWith("ff")) { sb.delete(endIndex - 1, endIndex); } } private int getRIndex(StringBuffer sb, int start) { if (start == 0) start = 1; int i = start; for (; i < sb.length(); i++) { //first non-vowel preceded by a vowel if (!isVowel(sb.charAt(i)) && isVowel(sb.charAt(i - 1))) { return i + 1; } } return i + 1; } private void storeYandI(StringBuffer sb) { if (sb.charAt(0) == 'y') sb.setCharAt(0, 'Y'); int last = sb.length() - 1; for (int i = 1; i < last; i++) { switch (sb.charAt(i)) { case 'i': { if (isVowel(sb.charAt(i - 1)) && isVowel(sb.charAt(i + 1)) ) sb.setCharAt(i, 'I'); break; } case 'y': { if (isVowel(sb.charAt(i - 1))) sb.setCharAt(i, 'Y'); break; } } } if (last > 0 && sb.charAt(last) == 'y' && isVowel(sb.charAt(last - 1))) sb.setCharAt(last, 'Y'); } private void reStoreYandI(StringBuffer sb) { String tmp = sb.toString(); sb.delete(0, sb.length()); sb.insert(0, tmp.replaceAll("I", "i").replaceAll("Y", "y")); } private boolean isVowel(char c) { switch (c) { case 'e': case 'a': case 'o': case 'i': case 'u': case 'y': case 'è': { return true; } } return false; } void setStemDictionary(Map dict) { _stemDict = dict; } }
115378_0
package bep.chatapp.server; import java.io.*; import java.net.*; import java.util.*; public class ChatServer { private final static int PORT = 8080; public static void main(String[] args) throws IOException { List<PrintWriter> allClients = new ArrayList<PrintWriter>(); try (ServerSocket ss = new ServerSocket(PORT)) { System.out.printf("Server started on port %d!\n", PORT); while (true) { try { Socket s = ss.accept(); // voor elke nieuwe client een aparte thread om binnenkomende chatberichten te verwerken new Thread() { public void run() { PrintWriter pw = null; // try-with-resource (scanner wordt na afloop automatisch gesloten): try (Scanner scanner = new Scanner(s.getInputStream())) { allClients.add(pw = new PrintWriter(s.getOutputStream())); while (scanner.hasNextLine()) { String message = scanner.nextLine(); System.out.println("Incoming and distributing: " + message); // schrijf het binnenkomende bericht naar alle clients! for (PrintWriter printer : allClients) { printer.println(message); printer.flush(); } } } catch (IOException ioe) { ioe.printStackTrace(); } finally { System.out.println("Client-verbinding verbroken!"); allClients.remove(pw); } } }.start(); } catch (IOException ioe) { ioe.printStackTrace(); } } } } }
BvEijkelenburg/ChatApp
src/bep/chatapp/server/ChatServer.java
479
// voor elke nieuwe client een aparte thread om binnenkomende chatberichten te verwerken
line_comment
nl
package bep.chatapp.server; import java.io.*; import java.net.*; import java.util.*; public class ChatServer { private final static int PORT = 8080; public static void main(String[] args) throws IOException { List<PrintWriter> allClients = new ArrayList<PrintWriter>(); try (ServerSocket ss = new ServerSocket(PORT)) { System.out.printf("Server started on port %d!\n", PORT); while (true) { try { Socket s = ss.accept(); // voor elke<SUF> new Thread() { public void run() { PrintWriter pw = null; // try-with-resource (scanner wordt na afloop automatisch gesloten): try (Scanner scanner = new Scanner(s.getInputStream())) { allClients.add(pw = new PrintWriter(s.getOutputStream())); while (scanner.hasNextLine()) { String message = scanner.nextLine(); System.out.println("Incoming and distributing: " + message); // schrijf het binnenkomende bericht naar alle clients! for (PrintWriter printer : allClients) { printer.println(message); printer.flush(); } } } catch (IOException ioe) { ioe.printStackTrace(); } finally { System.out.println("Client-verbinding verbroken!"); allClients.remove(pw); } } }.start(); } catch (IOException ioe) { ioe.printStackTrace(); } } } } }
19102_14
package nl.bve.dammen.domein; import java.util.ArrayList; import java.util.List; import java.util.function.BiPredicate; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; /** * @author Bart v. Eijkelenburg * * Klasse Damspel is de representatie van een Dambord. De klasse houdt * voor alle velden de status bij en bepaalt of een zet of slag uitgevoerd * kan worden. * * Een Damspel-object kan via de constructor gemaakt worden en is dan direct * speelklaar. Vervolgens zijn de volgende methoden nodig om het spel te * be�nvloeden: * * public boolean isVeldSpeelbaar(int veldId) * public boolean isZetMogelijk(int vanVeldId, int naarVeldId) * public boolean doeZet(int vanVeldId, int naarVeldId) * * De methode isVeldSpeelbaar kan gebruikt worden om bijvoorbeeld te bepalen * of op een GUI een veld geselecteerd kan worden om daarvandaan een zet of * slag te beginnen. Het resultaat is true of false; * * De methode isZetMogelijk kan gebruikt worden om te controleren of een zet * of slag is toegestaan zonder de zet of slag ook daadwerkelijk uit te voeren * Zodoende kan een gebruiker zijn keuze nog heroverwegen. Het resultaat is true * of false. * * Methode doeZet is nodig om een zet of slag daadwerkelijk uit te voeren. Het * spel zal als deze slag of zet is toegestaan, de interne status van het speel- * bord bijwerken. * * * Naast deze methoden zijn er nog: * * public void reset() * public Veld[] getVeldStatus(int veldId) * public String getMelding() * public StringProperty getMeldingProperty() * public String getSpeler() * public StringProperty getSpelerProperty() * public Damspel clone() * public String toString() * * De reset() methode kan ten allen tijde worden aangeroepen en zal het bord * volledig reseten. * * Methode getVeldStatus levert de status voor het veld met id == veldId op als string. * Deze status kan zijn: LEEG, WIT, ZWART, ZWARTDAM, WITDAM of NIETSPEELBAAR. Hiermee * kan de GUI geupdate worden. * * Methode getMelding kan gebruikt worden om na een zet eventuele berichten in de * GUI te tonen. Bijvoorbeeld met informatie waarom een zet niet lukt. * * Methode getMeldingProperty levert een property waaraan in JavaFX een listener * gekoppeld kan worden. Zodoende hoeft niet steeds gecontroleerd te worden of er * een nieuw bericht is, maar kan het bericht automatisch in een Label verschijnen. * * Methode getSpeler levert de naam van de HUIDIGE speler op (WIT of ZWART); * * Methode getSpelerProperty levert een property waaraan in JavaFX een listener * gekoppeld kan worden. Op die manier kan het speelbord bijvoorbeeld geroteerd * worden als de beurt wijzigt, of kan de naam van de speler die aan de beurt is * automatisch in een Label geplaatst worden (middels een listener). * * Methode clone kan gebruikt worden om een deep-copy van het damspel op te vragen. * Een eventuele computerspeler kan deze methode gebruiken om zetten op het bord * uit te proberen en mogelijke zetten te overwegen. * * Methode toString levert een tekstuele representatie van het dambord op. Deze * kan gebruikt worden voor testdoeleinden. * */ public class Damspel { private enum Veld { WIT, ZWART, WITDAM, ZWARTDAM, LEEG, NIETSPEELBAAR } private enum Richting { NOORDWEST, NOORDOOST, ZUIDOOST, ZUIDWEST } private enum Speler { WIT, ZWART, WIT_WINT, ZWART_WINT } private Veld[] bord = new Veld[100]; private Speler speler = Speler.ZWART; private final StringProperty meldingProperty = new SimpleStringProperty(); private final StringProperty spelerProperty = new SimpleStringProperty(); /** * Constructor maakt een volledig ingesteld nieuw dambord. */ public Damspel() { reset(); } @Override public Damspel clone() { Damspel clone = new Damspel(); clone.bord = new Veld[bord.length]; for (int i=0; i < bord.length; i++) { clone.bord[i] = bord[i]; } clone.speler = speler; clone.meldingProperty.setValue(meldingProperty.getValue()); clone.spelerProperty.setValue(spelerProperty.getValue()); return clone; } /** * De reset() methode kan ten allen tijde worden aangeroepen en zal het bord * volledig reseten. */ public void reset() { speler = Speler.WIT; spelerProperty.setValue(speler.name()); // 4 rijen met witte stenen (rij 0 t/m 3) for (int i=0; i <= 3; i++) { for (int j=i%2; j <= 9; j+=2) { bord[i*10+j] = Veld.ZWART; } } // 2 rijen zonder stenen (rij 4 en 5) for (int i=4; i <= 5; i++) { for (int j=i%2; j <= 9; j+=2) { bord[i*10+j] = Veld.LEEG; } } // 4 rijen met zwarte stenen (rij 6 t/m 9) for (int i=6; i <= 9; i++) { for (int j=i%2; j <= 9; j+=2) { bord[i*10+j] = Veld.WIT; } } // 50 onspeelbare posities for (int i=0; i <= 9; i++) { for (int j=(i+1)%2; j <= 9; j+=2) { bord[i*10+j] = Veld.NIETSPEELBAAR; } } } /** * Methode doeZet controleert of een gegeven zet mogelijk is van 'vanVeldId' * naar 'naarVeldId'. Hiervoor wordt de publieke methode isZetMogelijk gebruikt. * * Als het een slag is zullen stenen van de tegenstander van het bord gehaald * worden. Het betreffende veld wordt dan 'LEEG'. * * Wanneer het een slag is, kan het zijn dat de speler nog meer stenen kan slaan vanaf * het zojuist verkregen veld op positie 'naarVeldId'. In dat geval wijzigt de beurt * NIET. In alle andere gevallen wel. Daarbij zal de StringProperty 'spelerProperty' * geupdatet worden. * * @param vanVeldId - het veld waar de zet of slag begint * @param naarVeldId - het veld waar de zet of slag eindigt * @return {@link Boolean} */ public boolean doeZet(int vanVeldId, int naarVeldId) { if (isZetMogelijk(vanVeldId, naarVeldId)) { boolean isSlag = !bepaalMogelijkeSlagenVoorVeld(vanVeldId).isEmpty(); boolean spelersWissel = true; bord[naarVeldId] = bord[vanVeldId]; bord[vanVeldId] = Veld.LEEG; if (isSlag) { verwijderTegenstanderTussen(vanVeldId, naarVeldId); if (!bepaalMogelijkeSlagenVoorVeld(naarVeldId).isEmpty()) { spelersWissel = false; } } int veldRij = naarVeldId / 10; if (veldRij == 9 && speler == Speler.ZWART) bord[naarVeldId] = Veld.ZWARTDAM; if (veldRij == 0 && speler == Speler.WIT) bord[naarVeldId] = Veld.WITDAM; if (spelersWissel) { wisselVanSpeler(); } return true; } return false; } private void wisselVanSpeler() { speler = (speler == Speler.WIT) ? Speler.ZWART : Speler.WIT; if (getAlleSlagPositiesVoorSpeler().isEmpty() && getAlleZetPositiesVoorSpeler().isEmpty()) { if (speler == Speler.WIT) speler = Speler.ZWART_WINT; if (speler == Speler.ZWART) speler = Speler.WIT_WINT; } spelerProperty.setValue(speler.name()); } private void verwijderTegenstanderTussen(int vanVeldId, int naarVeldId) { int verschil = Math.abs(vanVeldId - naarVeldId); if (verschil >= 18 && verschil <= 22) /* normale slag */ { int tegenstanderPositie = (vanVeldId + naarVeldId) / 2; bord[tegenstanderPositie] = Veld.LEEG; } else if (verschil > 22) /* damslag */ { boolean isNoordSlag = (vanVeldId - naarVeldId) < 0; boolean isNoordWestSlag = isNoordSlag && (verschil % 11 == 0); boolean isNoordOostSlag = isNoordSlag && (verschil % 9 == 0); boolean isZuidOostSlag = !isNoordSlag && (verschil % 11 == 0); boolean isZuidWestSlag = !isNoordSlag && (verschil % 9 == 0); int tegenstanderPositie = -1; if (isNoordWestSlag) tegenstanderPositie = naarVeldId-11; if (isNoordOostSlag) tegenstanderPositie = naarVeldId-9; if (isZuidOostSlag) tegenstanderPositie = naarVeldId+11; if (isZuidWestSlag) tegenstanderPositie = naarVeldId+9; if (tegenstanderPositie != -1) { bord[tegenstanderPositie] = Veld.LEEG; } } } /** * De methode isVeldSpeelbaar kan gebruikt worden om bijvoorbeeld te bepalen * of op een GUI een veld geselecteerd kan worden om daarvandaan een zet of * slag te beginnen. Het resultaat is true of false; * * @param veldId * @return {@link Boolean} */ public boolean isVeldSpeelbaar(int veldId) { if (speler == Speler.WIT_WINT || speler == Speler.ZWART_WINT) { meldingProperty.setValue("Het spel is al afgelopen!"); return false; } if (bord[veldId] == Veld.NIETSPEELBAAR) { meldingProperty.setValue("Alleen op de donkere vlakken kan gespeeld worden!"); return false; } if (bord[veldId] == Veld.LEEG) { meldingProperty.setValue("U kunt niet vanaf een leeg veld spelen!"); return false; } boolean isGeenEigenVeld; if (speler == Speler.WIT) isGeenEigenVeld = bord[veldId] == Veld.ZWART|| bord[veldId] == Veld.ZWARTDAM; else isGeenEigenVeld = bord[veldId] == Veld.WIT|| bord[veldId] == Veld.WITDAM; if (isGeenEigenVeld) { meldingProperty.setValue("U mag geen stenen van de tegenstander verplaatsen!"); return false; } List<Integer> alleSlagPosities = getAlleSlagPositiesVoorSpeler(); if (!alleSlagPosities.isEmpty() && !alleSlagPosities.contains(veldId)) { meldingProperty.setValue("Slaan gaat voor een zet!"); return false; } List<Integer> slagenVoorVeld = bepaalMogelijkeSlagenVoorVeld(veldId); List<Integer> zettenVoorVeld = bepaalMogelijkeZettenVoorVeld(veldId); if (slagenVoorVeld.isEmpty() && zettenVoorVeld.isEmpty()) { meldingProperty.setValue("Deze steen kan niet verplaatsen!"); return false; } else { meldingProperty.setValue("Ok!"); return true; } } /** * De methode isZetMogelijk kan gebruikt worden om te controleren of een zet * of slag is toegestaan zonder de zet of slag ook daadwerkelijk uit te voeren * Zodoende kan een gebruiker zijn keuze nog heroverwegen. Het resultaat is true * of false. * * @param vanVeldId * @param naarVeldId * @return {@link Boolean} */ public boolean isZetMogelijk(int vanVeldId, int naarVeldId) { if (!isVeldSpeelbaar(vanVeldId)) { // bericht is al ge-set in andere methode return false; } List<Integer> slagPosities = bepaalMogelijkeSlagenVoorVeld(vanVeldId); if (!slagPosities.isEmpty() && !slagPosities.contains(naarVeldId)) { meldingProperty.setValue("Slaan gaat voor een zet!"); return false; } List<Integer> zetPosities = bepaalMogelijkeZettenVoorVeld(vanVeldId); if (slagPosities.contains(naarVeldId) || zetPosities.contains(naarVeldId)) { meldingProperty.setValue("Ok!"); return true; } meldingProperty.setValue("U kunt niet spelen naar dit veld!"); return false; } public List<Integer> getAlleSlagPositiesVoorSpeler() { List<Integer> alleSlagPosities = new ArrayList<Integer>(); for (int i=0; i < bord.length; i++) { if (!isVeldVanTegenstander(i)) { List<Integer> slagenVoorVeld = bepaalMogelijkeSlagenVoorVeld(i); if (!slagenVoorVeld.isEmpty()) { alleSlagPosities.add(i); } } } return alleSlagPosities; } public List<Integer> getAlleZetPositiesVoorSpeler() { List<Integer> alleZetPosities = new ArrayList<Integer>(); for (int i=0; i < bord.length; i++) { if (!isVeldVanTegenstander(i)) { List<Integer> zettenVoorVeld = bepaalMogelijkeZettenVoorVeld(i); if (!zettenVoorVeld.isEmpty()) { alleZetPosities.add(i); } } } return alleZetPosities; } public List<Integer> bepaalMogelijkeZettenVoorVeld(int veldId) { List<Integer> mogelijkeZetten = new ArrayList<Integer>(); if (bord[veldId] != Veld.LEEG && bord[veldId] != Veld.NIETSPEELBAAR) { for (Richting richting : Richting.values()) { mogelijkeZetten.addAll(zijnZettenMogelijkInRichting(richting, veldId)); } } return mogelijkeZetten; } private List<Integer> zijnZettenMogelijkInRichting(Richting richting, final int veldId) { List<Integer> mogelijkeZetten = new ArrayList<Integer>(); if (isEigenVeld(veldId)) { BiPredicate<Integer, Integer> zijnRijEnKolomVerGenoegVanBordrand = null; int VELDDT = 0, KOLOMDT = 0, RIJDT = 0, veldKolom = veldId % 10, veldRij = veldId / 10; if (richting == Richting.NOORDWEST) { KOLOMDT = -1; RIJDT = -1; VELDDT = -11; zijnRijEnKolomVerGenoegVanBordrand = (kolom, rij) -> kolom > 0 && rij > 0; } if (richting == Richting.NOORDOOST) { KOLOMDT = +1; RIJDT = -1; VELDDT = -9; zijnRijEnKolomVerGenoegVanBordrand = (kolom, rij) -> kolom < 9 && rij > 0; } if (richting == Richting.ZUIDOOST) { KOLOMDT = +1; RIJDT = +1; VELDDT = +11; zijnRijEnKolomVerGenoegVanBordrand = (kolom, rij) -> kolom < 9 && rij < 9; } if (richting == Richting.ZUIDWEST) { KOLOMDT = -1; RIJDT = +1; VELDDT = +9; zijnRijEnKolomVerGenoegVanBordrand = (kolom, rij) -> kolom > 0 && rij < 9; } int zetNaarPos = veldId + VELDDT; while (zijnRijEnKolomVerGenoegVanBordrand.test(veldKolom, veldRij) && bord[zetNaarPos] == Veld.LEEG) { if (bord[veldId] == Veld.WIT || bord[veldId] == Veld.ZWART) { if (speler == Speler.WIT) if (richting == Richting.NOORDWEST || richting == Richting.NOORDOOST) mogelijkeZetten.add(zetNaarPos); if (speler == Speler.ZWART) if (richting == Richting.ZUIDOOST || richting == Richting.ZUIDWEST) mogelijkeZetten.add(zetNaarPos); break; } mogelijkeZetten.add(zetNaarPos); veldKolom += KOLOMDT; veldRij += RIJDT; zetNaarPos += VELDDT; } } return mogelijkeZetten; } public List<Integer> bepaalMogelijkeSlagenVoorVeld(int veldId) { List<Integer> mogelijkeSlagen = new ArrayList<Integer>(); if (bord[veldId] != Veld.LEEG && bord[veldId] != Veld.NIETSPEELBAAR) { for (Richting richting : Richting.values()) { Integer slag = isSlagMogelijkInRichting(richting, veldId); if (slag != null) mogelijkeSlagen.add(slag); } } return mogelijkeSlagen; } private Integer isSlagMogelijkInRichting(Richting richting, final int veldId) { if (isEigenVeld(veldId)) { BiPredicate<Integer, Integer> zijnRijEnKolomVerGenoegVanBordrand = null; int VELDDT = 0, KOLOMDT = 0, RIJDT = 0, veldKolom = veldId % 10, veldRij = veldId / 10; if (richting == Richting.NOORDWEST) { KOLOMDT = -1; RIJDT = -1; VELDDT = -11; zijnRijEnKolomVerGenoegVanBordrand = (kolom, rij) -> kolom > 1 && rij > 1; } if (richting == Richting.NOORDOOST) { KOLOMDT = +1; RIJDT = -1; VELDDT = -9; zijnRijEnKolomVerGenoegVanBordrand = (kolom, rij) -> kolom < 8 && rij > 1; } if (richting == Richting.ZUIDOOST) { KOLOMDT = +1; RIJDT = +1; VELDDT = +11; zijnRijEnKolomVerGenoegVanBordrand = (kolom, rij) -> kolom < 8 && rij < 8; } if (richting == Richting.ZUIDWEST) { KOLOMDT = -1; RIJDT = +1; VELDDT = +9; zijnRijEnKolomVerGenoegVanBordrand = (kolom, rij) -> kolom > 1 && rij < 8; } int geslagenPos = veldId + VELDDT*1; int slagNaarPos = veldId + VELDDT*2; while (zijnRijEnKolomVerGenoegVanBordrand.test(veldKolom, veldRij)) { if (isVeldVanTegenstander(geslagenPos) && bord[slagNaarPos] == Veld.LEEG) { return slagNaarPos; } else { if (bord[veldId] == Veld.WIT || bord[veldId] == Veld.ZWART) break; if (bord[geslagenPos] != Veld.LEEG && bord[slagNaarPos] != Veld.LEEG) break; } slagNaarPos += VELDDT; geslagenPos += VELDDT; veldKolom += KOLOMDT; veldRij += RIJDT; } } return null; } private boolean isVeldVanTegenstander(int veldId) { if (speler == Speler.WIT) { return bord[veldId] == Veld.ZWART || bord[veldId] == Veld.ZWARTDAM; } else { return bord[veldId] == Veld.WIT || bord[veldId] == Veld.WITDAM; } } private boolean isEigenVeld(int veldId) { if (speler == Speler.WIT) { return bord[veldId] == Veld.WIT || bord[veldId] == Veld.WITDAM; } else { return bord[veldId] == Veld.ZWART || bord[veldId] == Veld.ZWARTDAM; } } /** * Methode getVeldStatus levert voor het gegeven veldId de status op van dat veld. * De status is een String, en kan zijn: "LEEG", "WIT", "ZWART", "ZWARTDAM", "WITDAM" * of "NIETSPEELBAAR". Hiermee kan de GUI geupdate worden. * * @return {@link String} */ public String getVeldStatus(int veldId) { return bord[veldId].name(); } /** * Methode getMelding kan gebruikt worden om na een zet eventuele berichten in de * GUI te tonen. Bijvoorbeeld met informatie waarom een zet niet lukt. * * @return {@link String} */ public String getMelding() { return meldingProperty.getValue(); } /** * Methode getMeldingProperty levert een property waaraan in JavaFX een listener * gekoppeld kan worden. Zodoende hoeft niet steeds gecontroleerd te worden of er * een nieuw bericht is, maar kan het bericht automatisch in een Label verschijnen. * * @return {@link StringProperty} */ public StringProperty getMeldingProperty() { return meldingProperty; } /** * Methode getSpeler levert de naam van de HUIDIGE speler op (WIT of ZWART); * * @return {@link String} */ public String getSpeler() { return spelerProperty.getValue(); } /** * Methode getSpelerProperty levert een property waaraan in JavaFX een listener * gekoppeld kan worden. Op die manier kan het speelbord bijvoorbeeld geroteerd * worden als de beurt wijzigt, of kan de naam van de speler die aan de beurt is * automatisch in een Label geplaatst worden (middels een listener). * * @return {@link StringProperty} */ public StringProperty getSpelerProperty() { return spelerProperty; } public String toString() { StringBuilder result = new StringBuilder(); for (int i=0; i < bord.length; i++) { if (i % 10 == 0) result.append("\n"); switch (bord[i]) { case ZWART: result.append(" Z "); break; case WIT: result.append(" W "); break; case WITDAM: result.append("WD "); break; case ZWARTDAM: result.append("ZD "); break; case LEEG: result.append(" . "); break; case NIETSPEELBAAR: result.append(" "); break; } } return result.toString(); } }
BvEijkelenburg/Dammen
src/main/java/nl/bve/dammen/domein/Damspel.java
7,161
/** * Methode getSpeler levert de naam van de HUIDIGE speler op (WIT of ZWART); * * @return {@link String} */
block_comment
nl
package nl.bve.dammen.domein; import java.util.ArrayList; import java.util.List; import java.util.function.BiPredicate; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; /** * @author Bart v. Eijkelenburg * * Klasse Damspel is de representatie van een Dambord. De klasse houdt * voor alle velden de status bij en bepaalt of een zet of slag uitgevoerd * kan worden. * * Een Damspel-object kan via de constructor gemaakt worden en is dan direct * speelklaar. Vervolgens zijn de volgende methoden nodig om het spel te * be�nvloeden: * * public boolean isVeldSpeelbaar(int veldId) * public boolean isZetMogelijk(int vanVeldId, int naarVeldId) * public boolean doeZet(int vanVeldId, int naarVeldId) * * De methode isVeldSpeelbaar kan gebruikt worden om bijvoorbeeld te bepalen * of op een GUI een veld geselecteerd kan worden om daarvandaan een zet of * slag te beginnen. Het resultaat is true of false; * * De methode isZetMogelijk kan gebruikt worden om te controleren of een zet * of slag is toegestaan zonder de zet of slag ook daadwerkelijk uit te voeren * Zodoende kan een gebruiker zijn keuze nog heroverwegen. Het resultaat is true * of false. * * Methode doeZet is nodig om een zet of slag daadwerkelijk uit te voeren. Het * spel zal als deze slag of zet is toegestaan, de interne status van het speel- * bord bijwerken. * * * Naast deze methoden zijn er nog: * * public void reset() * public Veld[] getVeldStatus(int veldId) * public String getMelding() * public StringProperty getMeldingProperty() * public String getSpeler() * public StringProperty getSpelerProperty() * public Damspel clone() * public String toString() * * De reset() methode kan ten allen tijde worden aangeroepen en zal het bord * volledig reseten. * * Methode getVeldStatus levert de status voor het veld met id == veldId op als string. * Deze status kan zijn: LEEG, WIT, ZWART, ZWARTDAM, WITDAM of NIETSPEELBAAR. Hiermee * kan de GUI geupdate worden. * * Methode getMelding kan gebruikt worden om na een zet eventuele berichten in de * GUI te tonen. Bijvoorbeeld met informatie waarom een zet niet lukt. * * Methode getMeldingProperty levert een property waaraan in JavaFX een listener * gekoppeld kan worden. Zodoende hoeft niet steeds gecontroleerd te worden of er * een nieuw bericht is, maar kan het bericht automatisch in een Label verschijnen. * * Methode getSpeler levert de naam van de HUIDIGE speler op (WIT of ZWART); * * Methode getSpelerProperty levert een property waaraan in JavaFX een listener * gekoppeld kan worden. Op die manier kan het speelbord bijvoorbeeld geroteerd * worden als de beurt wijzigt, of kan de naam van de speler die aan de beurt is * automatisch in een Label geplaatst worden (middels een listener). * * Methode clone kan gebruikt worden om een deep-copy van het damspel op te vragen. * Een eventuele computerspeler kan deze methode gebruiken om zetten op het bord * uit te proberen en mogelijke zetten te overwegen. * * Methode toString levert een tekstuele representatie van het dambord op. Deze * kan gebruikt worden voor testdoeleinden. * */ public class Damspel { private enum Veld { WIT, ZWART, WITDAM, ZWARTDAM, LEEG, NIETSPEELBAAR } private enum Richting { NOORDWEST, NOORDOOST, ZUIDOOST, ZUIDWEST } private enum Speler { WIT, ZWART, WIT_WINT, ZWART_WINT } private Veld[] bord = new Veld[100]; private Speler speler = Speler.ZWART; private final StringProperty meldingProperty = new SimpleStringProperty(); private final StringProperty spelerProperty = new SimpleStringProperty(); /** * Constructor maakt een volledig ingesteld nieuw dambord. */ public Damspel() { reset(); } @Override public Damspel clone() { Damspel clone = new Damspel(); clone.bord = new Veld[bord.length]; for (int i=0; i < bord.length; i++) { clone.bord[i] = bord[i]; } clone.speler = speler; clone.meldingProperty.setValue(meldingProperty.getValue()); clone.spelerProperty.setValue(spelerProperty.getValue()); return clone; } /** * De reset() methode kan ten allen tijde worden aangeroepen en zal het bord * volledig reseten. */ public void reset() { speler = Speler.WIT; spelerProperty.setValue(speler.name()); // 4 rijen met witte stenen (rij 0 t/m 3) for (int i=0; i <= 3; i++) { for (int j=i%2; j <= 9; j+=2) { bord[i*10+j] = Veld.ZWART; } } // 2 rijen zonder stenen (rij 4 en 5) for (int i=4; i <= 5; i++) { for (int j=i%2; j <= 9; j+=2) { bord[i*10+j] = Veld.LEEG; } } // 4 rijen met zwarte stenen (rij 6 t/m 9) for (int i=6; i <= 9; i++) { for (int j=i%2; j <= 9; j+=2) { bord[i*10+j] = Veld.WIT; } } // 50 onspeelbare posities for (int i=0; i <= 9; i++) { for (int j=(i+1)%2; j <= 9; j+=2) { bord[i*10+j] = Veld.NIETSPEELBAAR; } } } /** * Methode doeZet controleert of een gegeven zet mogelijk is van 'vanVeldId' * naar 'naarVeldId'. Hiervoor wordt de publieke methode isZetMogelijk gebruikt. * * Als het een slag is zullen stenen van de tegenstander van het bord gehaald * worden. Het betreffende veld wordt dan 'LEEG'. * * Wanneer het een slag is, kan het zijn dat de speler nog meer stenen kan slaan vanaf * het zojuist verkregen veld op positie 'naarVeldId'. In dat geval wijzigt de beurt * NIET. In alle andere gevallen wel. Daarbij zal de StringProperty 'spelerProperty' * geupdatet worden. * * @param vanVeldId - het veld waar de zet of slag begint * @param naarVeldId - het veld waar de zet of slag eindigt * @return {@link Boolean} */ public boolean doeZet(int vanVeldId, int naarVeldId) { if (isZetMogelijk(vanVeldId, naarVeldId)) { boolean isSlag = !bepaalMogelijkeSlagenVoorVeld(vanVeldId).isEmpty(); boolean spelersWissel = true; bord[naarVeldId] = bord[vanVeldId]; bord[vanVeldId] = Veld.LEEG; if (isSlag) { verwijderTegenstanderTussen(vanVeldId, naarVeldId); if (!bepaalMogelijkeSlagenVoorVeld(naarVeldId).isEmpty()) { spelersWissel = false; } } int veldRij = naarVeldId / 10; if (veldRij == 9 && speler == Speler.ZWART) bord[naarVeldId] = Veld.ZWARTDAM; if (veldRij == 0 && speler == Speler.WIT) bord[naarVeldId] = Veld.WITDAM; if (spelersWissel) { wisselVanSpeler(); } return true; } return false; } private void wisselVanSpeler() { speler = (speler == Speler.WIT) ? Speler.ZWART : Speler.WIT; if (getAlleSlagPositiesVoorSpeler().isEmpty() && getAlleZetPositiesVoorSpeler().isEmpty()) { if (speler == Speler.WIT) speler = Speler.ZWART_WINT; if (speler == Speler.ZWART) speler = Speler.WIT_WINT; } spelerProperty.setValue(speler.name()); } private void verwijderTegenstanderTussen(int vanVeldId, int naarVeldId) { int verschil = Math.abs(vanVeldId - naarVeldId); if (verschil >= 18 && verschil <= 22) /* normale slag */ { int tegenstanderPositie = (vanVeldId + naarVeldId) / 2; bord[tegenstanderPositie] = Veld.LEEG; } else if (verschil > 22) /* damslag */ { boolean isNoordSlag = (vanVeldId - naarVeldId) < 0; boolean isNoordWestSlag = isNoordSlag && (verschil % 11 == 0); boolean isNoordOostSlag = isNoordSlag && (verschil % 9 == 0); boolean isZuidOostSlag = !isNoordSlag && (verschil % 11 == 0); boolean isZuidWestSlag = !isNoordSlag && (verschil % 9 == 0); int tegenstanderPositie = -1; if (isNoordWestSlag) tegenstanderPositie = naarVeldId-11; if (isNoordOostSlag) tegenstanderPositie = naarVeldId-9; if (isZuidOostSlag) tegenstanderPositie = naarVeldId+11; if (isZuidWestSlag) tegenstanderPositie = naarVeldId+9; if (tegenstanderPositie != -1) { bord[tegenstanderPositie] = Veld.LEEG; } } } /** * De methode isVeldSpeelbaar kan gebruikt worden om bijvoorbeeld te bepalen * of op een GUI een veld geselecteerd kan worden om daarvandaan een zet of * slag te beginnen. Het resultaat is true of false; * * @param veldId * @return {@link Boolean} */ public boolean isVeldSpeelbaar(int veldId) { if (speler == Speler.WIT_WINT || speler == Speler.ZWART_WINT) { meldingProperty.setValue("Het spel is al afgelopen!"); return false; } if (bord[veldId] == Veld.NIETSPEELBAAR) { meldingProperty.setValue("Alleen op de donkere vlakken kan gespeeld worden!"); return false; } if (bord[veldId] == Veld.LEEG) { meldingProperty.setValue("U kunt niet vanaf een leeg veld spelen!"); return false; } boolean isGeenEigenVeld; if (speler == Speler.WIT) isGeenEigenVeld = bord[veldId] == Veld.ZWART|| bord[veldId] == Veld.ZWARTDAM; else isGeenEigenVeld = bord[veldId] == Veld.WIT|| bord[veldId] == Veld.WITDAM; if (isGeenEigenVeld) { meldingProperty.setValue("U mag geen stenen van de tegenstander verplaatsen!"); return false; } List<Integer> alleSlagPosities = getAlleSlagPositiesVoorSpeler(); if (!alleSlagPosities.isEmpty() && !alleSlagPosities.contains(veldId)) { meldingProperty.setValue("Slaan gaat voor een zet!"); return false; } List<Integer> slagenVoorVeld = bepaalMogelijkeSlagenVoorVeld(veldId); List<Integer> zettenVoorVeld = bepaalMogelijkeZettenVoorVeld(veldId); if (slagenVoorVeld.isEmpty() && zettenVoorVeld.isEmpty()) { meldingProperty.setValue("Deze steen kan niet verplaatsen!"); return false; } else { meldingProperty.setValue("Ok!"); return true; } } /** * De methode isZetMogelijk kan gebruikt worden om te controleren of een zet * of slag is toegestaan zonder de zet of slag ook daadwerkelijk uit te voeren * Zodoende kan een gebruiker zijn keuze nog heroverwegen. Het resultaat is true * of false. * * @param vanVeldId * @param naarVeldId * @return {@link Boolean} */ public boolean isZetMogelijk(int vanVeldId, int naarVeldId) { if (!isVeldSpeelbaar(vanVeldId)) { // bericht is al ge-set in andere methode return false; } List<Integer> slagPosities = bepaalMogelijkeSlagenVoorVeld(vanVeldId); if (!slagPosities.isEmpty() && !slagPosities.contains(naarVeldId)) { meldingProperty.setValue("Slaan gaat voor een zet!"); return false; } List<Integer> zetPosities = bepaalMogelijkeZettenVoorVeld(vanVeldId); if (slagPosities.contains(naarVeldId) || zetPosities.contains(naarVeldId)) { meldingProperty.setValue("Ok!"); return true; } meldingProperty.setValue("U kunt niet spelen naar dit veld!"); return false; } public List<Integer> getAlleSlagPositiesVoorSpeler() { List<Integer> alleSlagPosities = new ArrayList<Integer>(); for (int i=0; i < bord.length; i++) { if (!isVeldVanTegenstander(i)) { List<Integer> slagenVoorVeld = bepaalMogelijkeSlagenVoorVeld(i); if (!slagenVoorVeld.isEmpty()) { alleSlagPosities.add(i); } } } return alleSlagPosities; } public List<Integer> getAlleZetPositiesVoorSpeler() { List<Integer> alleZetPosities = new ArrayList<Integer>(); for (int i=0; i < bord.length; i++) { if (!isVeldVanTegenstander(i)) { List<Integer> zettenVoorVeld = bepaalMogelijkeZettenVoorVeld(i); if (!zettenVoorVeld.isEmpty()) { alleZetPosities.add(i); } } } return alleZetPosities; } public List<Integer> bepaalMogelijkeZettenVoorVeld(int veldId) { List<Integer> mogelijkeZetten = new ArrayList<Integer>(); if (bord[veldId] != Veld.LEEG && bord[veldId] != Veld.NIETSPEELBAAR) { for (Richting richting : Richting.values()) { mogelijkeZetten.addAll(zijnZettenMogelijkInRichting(richting, veldId)); } } return mogelijkeZetten; } private List<Integer> zijnZettenMogelijkInRichting(Richting richting, final int veldId) { List<Integer> mogelijkeZetten = new ArrayList<Integer>(); if (isEigenVeld(veldId)) { BiPredicate<Integer, Integer> zijnRijEnKolomVerGenoegVanBordrand = null; int VELDDT = 0, KOLOMDT = 0, RIJDT = 0, veldKolom = veldId % 10, veldRij = veldId / 10; if (richting == Richting.NOORDWEST) { KOLOMDT = -1; RIJDT = -1; VELDDT = -11; zijnRijEnKolomVerGenoegVanBordrand = (kolom, rij) -> kolom > 0 && rij > 0; } if (richting == Richting.NOORDOOST) { KOLOMDT = +1; RIJDT = -1; VELDDT = -9; zijnRijEnKolomVerGenoegVanBordrand = (kolom, rij) -> kolom < 9 && rij > 0; } if (richting == Richting.ZUIDOOST) { KOLOMDT = +1; RIJDT = +1; VELDDT = +11; zijnRijEnKolomVerGenoegVanBordrand = (kolom, rij) -> kolom < 9 && rij < 9; } if (richting == Richting.ZUIDWEST) { KOLOMDT = -1; RIJDT = +1; VELDDT = +9; zijnRijEnKolomVerGenoegVanBordrand = (kolom, rij) -> kolom > 0 && rij < 9; } int zetNaarPos = veldId + VELDDT; while (zijnRijEnKolomVerGenoegVanBordrand.test(veldKolom, veldRij) && bord[zetNaarPos] == Veld.LEEG) { if (bord[veldId] == Veld.WIT || bord[veldId] == Veld.ZWART) { if (speler == Speler.WIT) if (richting == Richting.NOORDWEST || richting == Richting.NOORDOOST) mogelijkeZetten.add(zetNaarPos); if (speler == Speler.ZWART) if (richting == Richting.ZUIDOOST || richting == Richting.ZUIDWEST) mogelijkeZetten.add(zetNaarPos); break; } mogelijkeZetten.add(zetNaarPos); veldKolom += KOLOMDT; veldRij += RIJDT; zetNaarPos += VELDDT; } } return mogelijkeZetten; } public List<Integer> bepaalMogelijkeSlagenVoorVeld(int veldId) { List<Integer> mogelijkeSlagen = new ArrayList<Integer>(); if (bord[veldId] != Veld.LEEG && bord[veldId] != Veld.NIETSPEELBAAR) { for (Richting richting : Richting.values()) { Integer slag = isSlagMogelijkInRichting(richting, veldId); if (slag != null) mogelijkeSlagen.add(slag); } } return mogelijkeSlagen; } private Integer isSlagMogelijkInRichting(Richting richting, final int veldId) { if (isEigenVeld(veldId)) { BiPredicate<Integer, Integer> zijnRijEnKolomVerGenoegVanBordrand = null; int VELDDT = 0, KOLOMDT = 0, RIJDT = 0, veldKolom = veldId % 10, veldRij = veldId / 10; if (richting == Richting.NOORDWEST) { KOLOMDT = -1; RIJDT = -1; VELDDT = -11; zijnRijEnKolomVerGenoegVanBordrand = (kolom, rij) -> kolom > 1 && rij > 1; } if (richting == Richting.NOORDOOST) { KOLOMDT = +1; RIJDT = -1; VELDDT = -9; zijnRijEnKolomVerGenoegVanBordrand = (kolom, rij) -> kolom < 8 && rij > 1; } if (richting == Richting.ZUIDOOST) { KOLOMDT = +1; RIJDT = +1; VELDDT = +11; zijnRijEnKolomVerGenoegVanBordrand = (kolom, rij) -> kolom < 8 && rij < 8; } if (richting == Richting.ZUIDWEST) { KOLOMDT = -1; RIJDT = +1; VELDDT = +9; zijnRijEnKolomVerGenoegVanBordrand = (kolom, rij) -> kolom > 1 && rij < 8; } int geslagenPos = veldId + VELDDT*1; int slagNaarPos = veldId + VELDDT*2; while (zijnRijEnKolomVerGenoegVanBordrand.test(veldKolom, veldRij)) { if (isVeldVanTegenstander(geslagenPos) && bord[slagNaarPos] == Veld.LEEG) { return slagNaarPos; } else { if (bord[veldId] == Veld.WIT || bord[veldId] == Veld.ZWART) break; if (bord[geslagenPos] != Veld.LEEG && bord[slagNaarPos] != Veld.LEEG) break; } slagNaarPos += VELDDT; geslagenPos += VELDDT; veldKolom += KOLOMDT; veldRij += RIJDT; } } return null; } private boolean isVeldVanTegenstander(int veldId) { if (speler == Speler.WIT) { return bord[veldId] == Veld.ZWART || bord[veldId] == Veld.ZWARTDAM; } else { return bord[veldId] == Veld.WIT || bord[veldId] == Veld.WITDAM; } } private boolean isEigenVeld(int veldId) { if (speler == Speler.WIT) { return bord[veldId] == Veld.WIT || bord[veldId] == Veld.WITDAM; } else { return bord[veldId] == Veld.ZWART || bord[veldId] == Veld.ZWARTDAM; } } /** * Methode getVeldStatus levert voor het gegeven veldId de status op van dat veld. * De status is een String, en kan zijn: "LEEG", "WIT", "ZWART", "ZWARTDAM", "WITDAM" * of "NIETSPEELBAAR". Hiermee kan de GUI geupdate worden. * * @return {@link String} */ public String getVeldStatus(int veldId) { return bord[veldId].name(); } /** * Methode getMelding kan gebruikt worden om na een zet eventuele berichten in de * GUI te tonen. Bijvoorbeeld met informatie waarom een zet niet lukt. * * @return {@link String} */ public String getMelding() { return meldingProperty.getValue(); } /** * Methode getMeldingProperty levert een property waaraan in JavaFX een listener * gekoppeld kan worden. Zodoende hoeft niet steeds gecontroleerd te worden of er * een nieuw bericht is, maar kan het bericht automatisch in een Label verschijnen. * * @return {@link StringProperty} */ public StringProperty getMeldingProperty() { return meldingProperty; } /** * Methode getSpeler levert<SUF>*/ public String getSpeler() { return spelerProperty.getValue(); } /** * Methode getSpelerProperty levert een property waaraan in JavaFX een listener * gekoppeld kan worden. Op die manier kan het speelbord bijvoorbeeld geroteerd * worden als de beurt wijzigt, of kan de naam van de speler die aan de beurt is * automatisch in een Label geplaatst worden (middels een listener). * * @return {@link StringProperty} */ public StringProperty getSpelerProperty() { return spelerProperty; } public String toString() { StringBuilder result = new StringBuilder(); for (int i=0; i < bord.length; i++) { if (i % 10 == 0) result.append("\n"); switch (bord[i]) { case ZWART: result.append(" Z "); break; case WIT: result.append(" W "); break; case WITDAM: result.append("WD "); break; case ZWARTDAM: result.append("ZD "); break; case LEEG: result.append(" . "); break; case NIETSPEELBAAR: result.append(" "); break; } } return result.toString(); } }
43986_1
package nl.bve.rabobank.parser; import java.io.File; import java.io.FileReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.events.XMLEvent; final class TransactionParserXMLStAX implements TransactionParser { private XMLStreamReader xmlSr; TransactionParserXMLStAX(File transactionsFile) throws Exception { XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); xmlSr = xmlInputFactory.createXMLStreamReader(new FileReader(transactionsFile)); } @Override public Transaction nextTransaction() { try { // Een while-loop, omdat je misschien niet als eerste xml-element een 'record' tegenkomt. while (xmlSr.hasNext()) { int eventType = xmlSr.next(); if (eventType == XMLEvent.START_ELEMENT && xmlSr.getLocalName().equalsIgnoreCase("record")) { Transaction newTransaction = new Transaction(); // attribute 0, omdat het enige attribute de reference is. Mooier zou zijn om te checken of index 0 inderdaad de reference is. newTransaction.setReference(xmlSr.getAttributeValue(0)); // while-loop om in 1 keer alle gegevens van een transaction in te lezen while (xmlSr.hasNext()) { xmlSr.next(); if (xmlSr.getEventType() == XMLEvent.START_ELEMENT) { if (xmlSr.getLocalName().equalsIgnoreCase("description")) newTransaction.setDescription(xmlSr.getElementText()); if (xmlSr.getLocalName().equalsIgnoreCase("startBalance")) newTransaction.setStartBalance(xmlSr.getElementText()); if (xmlSr.getLocalName().equalsIgnoreCase("endBalance")) newTransaction.setEndBalance(xmlSr.getElementText()); if (xmlSr.getLocalName().equalsIgnoreCase("mutation")) newTransaction.setMutation(xmlSr.getElementText()); } if (xmlSr.getEventType() == XMLEvent.END_ELEMENT) { if (xmlSr.getLocalName().equalsIgnoreCase("record")) { return newTransaction; } } } } } } catch (XMLStreamException ex) { ex.printStackTrace(); } return null; } }
BvEijkelenburg/RaboParser
src/main/java/nl/bve/rabobank/parser/TransactionParserXMLStAX.java
714
// attribute 0, omdat het enige attribute de reference is. Mooier zou zijn om te checken of index 0 inderdaad de reference is.
line_comment
nl
package nl.bve.rabobank.parser; import java.io.File; import java.io.FileReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.events.XMLEvent; final class TransactionParserXMLStAX implements TransactionParser { private XMLStreamReader xmlSr; TransactionParserXMLStAX(File transactionsFile) throws Exception { XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); xmlSr = xmlInputFactory.createXMLStreamReader(new FileReader(transactionsFile)); } @Override public Transaction nextTransaction() { try { // Een while-loop, omdat je misschien niet als eerste xml-element een 'record' tegenkomt. while (xmlSr.hasNext()) { int eventType = xmlSr.next(); if (eventType == XMLEvent.START_ELEMENT && xmlSr.getLocalName().equalsIgnoreCase("record")) { Transaction newTransaction = new Transaction(); // attribute 0,<SUF> newTransaction.setReference(xmlSr.getAttributeValue(0)); // while-loop om in 1 keer alle gegevens van een transaction in te lezen while (xmlSr.hasNext()) { xmlSr.next(); if (xmlSr.getEventType() == XMLEvent.START_ELEMENT) { if (xmlSr.getLocalName().equalsIgnoreCase("description")) newTransaction.setDescription(xmlSr.getElementText()); if (xmlSr.getLocalName().equalsIgnoreCase("startBalance")) newTransaction.setStartBalance(xmlSr.getElementText()); if (xmlSr.getLocalName().equalsIgnoreCase("endBalance")) newTransaction.setEndBalance(xmlSr.getElementText()); if (xmlSr.getLocalName().equalsIgnoreCase("mutation")) newTransaction.setMutation(xmlSr.getElementText()); } if (xmlSr.getEventType() == XMLEvent.END_ELEMENT) { if (xmlSr.getLocalName().equalsIgnoreCase("record")) { return newTransaction; } } } } } } catch (XMLStreamException ex) { ex.printStackTrace(); } return null; } }
81930_0
package proeftentamen.luchtvaartmaatschappij; import java.io.Serializable; public class Vliegtuig implements Serializable { private String type; private int aantalMotoren; private String registratieNummer; public Vliegtuig(String tp, int aM, String rN) { type = tp; aantalMotoren = aM; registratieNummer = rN; } public String getType() { return type; } public boolean equals(Object obj) { boolean result = false; if (obj instanceof Vliegtuig) { Vliegtuig anderVliegtuig = (Vliegtuig)obj; if (this.type.equals(anderVliegtuig.type) && this.aantalMotoren == anderVliegtuig.aantalMotoren && registratieNummer.equals(anderVliegtuig.registratieNummer)) { result = true; } } return result; } // Alternatief voor equals: // public boolean equals(Object obj) { // boolean result = obj instanceof Vliegtuig; // // result = result && type.equals(((Vliegtuig)obj).type); // result = result && aantalMotoren == ((Vliegtuig)obj).aantalMotoren; // result = result && registratieNummer.equals(((Vliegtuig)obj).registratieNummer); // // return result; // } public String toString() { return type + ", " + aantalMotoren + " motoren, registratie: " + registratieNummer; } }
BvEijkelenburg/v1oop-proeftentamen
src/proeftentamen/luchtvaartmaatschappij/Vliegtuig.java
471
// Alternatief voor equals:
line_comment
nl
package proeftentamen.luchtvaartmaatschappij; import java.io.Serializable; public class Vliegtuig implements Serializable { private String type; private int aantalMotoren; private String registratieNummer; public Vliegtuig(String tp, int aM, String rN) { type = tp; aantalMotoren = aM; registratieNummer = rN; } public String getType() { return type; } public boolean equals(Object obj) { boolean result = false; if (obj instanceof Vliegtuig) { Vliegtuig anderVliegtuig = (Vliegtuig)obj; if (this.type.equals(anderVliegtuig.type) && this.aantalMotoren == anderVliegtuig.aantalMotoren && registratieNummer.equals(anderVliegtuig.registratieNummer)) { result = true; } } return result; } // Alternatief voor<SUF> // public boolean equals(Object obj) { // boolean result = obj instanceof Vliegtuig; // // result = result && type.equals(((Vliegtuig)obj).type); // result = result && aantalMotoren == ((Vliegtuig)obj).aantalMotoren; // result = result && registratieNummer.equals(((Vliegtuig)obj).registratieNummer); // // return result; // } public String toString() { return type + ", " + aantalMotoren + " motoren, registratie: " + registratieNummer; } }
29359_10
package les08.opdracht8_1; public class Main { public static void main(String[] args) { /* Opgave a t/m f */ // Gebouw g; // Huis h = new Huis(10, 7, 1); // // g = h; // wel // g = new Huis(); // wel // h = g; // niet // h = (Huis)g; // wel // if (g instanceof Huis) h = (Huis)g; // wel // h.super.laatsteRenovatie = 1980; // niet /* Opgave g t/m k */ // Gebouw g; // Huis h = new Huis(10, 7, 2); // g = h; // // g.laatsteRenovatie = 1985; // binnen = 0 buiten = 1985 // h.laatsteRenovatie = 1990; // binnen = 1990 buiten = 1985 // ((Huis)g).laatsteRenovatie = 1995; // binnen = 1995 buiten = 1985 // h.renoveer(2000, 2005); // binnen = 2000 buiten = 2005 // g.isGeisoleerd = true; // niet /* Opgave l t/m o */ // Gebouw g; // Huis h = new Huis(10, 7, 3); // g = h; // // h.berekenHuur(); // klasse Huis // g.berekenHuur(); // klasse Huis // g.isoleer(); // niet // ((Huis)g).isoleer(); // wel } }
BvEijkelenburg/v1oop-werkboek
src/les08/opdracht8_1/Main.java
484
// Gebouw g;
line_comment
nl
package les08.opdracht8_1; public class Main { public static void main(String[] args) { /* Opgave a t/m f */ // Gebouw g; // Huis h = new Huis(10, 7, 1); // // g = h; // wel // g = new Huis(); // wel // h = g; // niet // h = (Huis)g; // wel // if (g instanceof Huis) h = (Huis)g; // wel // h.super.laatsteRenovatie = 1980; // niet /* Opgave g t/m k */ // Gebouw g;<SUF> // Huis h = new Huis(10, 7, 2); // g = h; // // g.laatsteRenovatie = 1985; // binnen = 0 buiten = 1985 // h.laatsteRenovatie = 1990; // binnen = 1990 buiten = 1985 // ((Huis)g).laatsteRenovatie = 1995; // binnen = 1995 buiten = 1985 // h.renoveer(2000, 2005); // binnen = 2000 buiten = 2005 // g.isGeisoleerd = true; // niet /* Opgave l t/m o */ // Gebouw g; // Huis h = new Huis(10, 7, 3); // g = h; // // h.berekenHuur(); // klasse Huis // g.berekenHuur(); // klasse Huis // g.isoleer(); // niet // ((Huis)g).isoleer(); // wel } }
23531_3
package tornado.org.cypherspider.productcrawlers; import java.io.IOException; import java.util.ArrayList; import org.jsoup.Jsoup; import org.jsoup.select.Elements; import tornado.org.cypherspider.pagecrawlers.ParadigitCrawler; import tornado.org.neo4j.ProductDatabase; import tornado.org.settings.Settings; public class FindLinksOnParadigit extends Thread { private ArrayList<String> Navlinks = new ArrayList<>(); private ArrayList<String> productlinks = new ArrayList<>(); private ArrayList<String> productnr = new ArrayList<>(); private static org.jsoup.nodes.Document doc; private Elements e; // TODO moet altijd dezelfde object blijven in de hele applicatie private static final ProductDatabase productDatabase = new ProductDatabase(); private static final ParadigitCrawler PARADIGIT_CRAWLER = new ParadigitCrawler() ; // TODO maak nieuwe Crawler voor Mycom // private final AlternateCrawler alternateCrawler = new AlternateCrawler(); private static String url = "http://www.paradigit.nl"; private static final String hyperlinkXmltag = "a"; private static final String hyperlinkAttributetag = "href"; private static final String navXmlClassTag = "PagerContainerTable"; private static final String productLinkXmlClassTag = "itemlistcombined-productimagecontainer"; public FindLinksOnParadigit() { // wrm moeilijk doen als het makkelijk kan Navlinks.add("/catalog/zpr_08ond/06_pccase/default.aspx"); Navlinks.add("/catalog/zpr_08ond/12_optdriv/default.aspx"); Navlinks.add("/catalog/zpr_08ond/01_memint/default.aspx"); Navlinks.add("/catalog/zpr_02ops/01_inthdd/default.aspx"); Navlinks.add("/catalog/zpr_02ops/01_intssd/default.aspx"); Navlinks.add("/catalog/zpr_08ond/05_mobo/default.aspx"); Navlinks.add("/catalog/zpr_08ond/04_cpu/default.aspx"); Navlinks.add("/catalog/zpr_08ond/24_cpu/default.aspx"); Navlinks.add("/catalog/zpr_08ond/03_vidcard/default.aspx"); Navlinks.add("/catalog/zpr_08ond/07_psu/default.aspx"); Navlinks.add("/catalog/zpr_05swa/01_windows/default.aspx"); Navlinks.add("/catalog/zpr_08ond/21_bare/default.aspx"); Navlinks.add("/catalog/zpr_08ond/21_bare/default.aspx"); Navlinks.add("/catalog/zpr_08ond/14_control/default.aspx"); Navlinks.add("/catalog/zpr_11kbl/12_firekbl/default.aspx"); Navlinks.add("/catalog/zpr_08ond/15_sndcard/default.aspx"); Navlinks.add("/catalog/zpr_08ond/19_tools/default.aspx"); Navlinks.add("/catalog/zpr_08ond/17_cardrea/default.aspx"); Navlinks.add("/catalog/zpr_08ond/23_coolers/default.aspx"); Navlinks.add("/catalog/zpr_08ond/25_kpas/default.aspx"); Navlinks.add("/catalog/zpr_11kbl/06_satakbl/default.aspx"); Navlinks.add("/catalog/zpr_03avi/06_tvtuner/default.aspx"); Navlinks.add("/catalog/zpr_08ond/22_ups/default.aspx"); Navlinks.add("/catalog/zpr_11kbl/08_pwrkbl/default.aspx"); } public void run() { try { for (int i = 0; i < Navlinks.size(); i++) { doc = Jsoup.connect(url + Navlinks.get(i)).get(); //System.out.println(doc.toString()); e = doc.getElementsByClass(navXmlClassTag); if (e.size() > 0) { e = e.get(0).getElementsByTag(hyperlinkXmltag); for (int j = 0; j < e.size(); j++) { String link = e.get(j).attr(hyperlinkAttributetag); if (!Navlinks.contains(link)) { Navlinks.add(link); } } } e = doc.getElementsByClass(productLinkXmlClassTag); for (int j = 0; j < e.size(); j++) { String productlink = e.get(j) .getElementsByTag(hyperlinkXmltag).get(0) .attr(hyperlinkAttributetag); productlinks.add(productlink); } } // parselinks(e); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } insertProducts(); System.out.println(productlinks.size()); Settings.setParadigitEndstate(true); if (Settings.getEndstate()) { productDatabase.registerShutdownHook(); } } private void insertProducts() { productDatabase.createDB(); for (int i = 0; i < productlinks.size(); i++) { PARADIGIT_CRAWLER.crawl(url + productlinks.get(i), productDatabase); } } public FindLinksOnParadigit(Runnable arg0) { super(arg0); // TODO Auto-generated constructor stub } public FindLinksOnParadigit(String arg0) { super(arg0); // TODO Auto-generated constructor stub } public FindLinksOnParadigit(ThreadGroup arg0, Runnable arg1) { super(arg0, arg1); // TODO Auto-generated constructor stub } public FindLinksOnParadigit(ThreadGroup arg0, String arg1) { super(arg0, arg1); // TODO Auto-generated constructor stub } public FindLinksOnParadigit(Runnable arg0, String arg1) { super(arg0, arg1); // TODO Auto-generated constructor stub } public FindLinksOnParadigit(ThreadGroup arg0, Runnable arg1, String arg2) { super(arg0, arg1, arg2); // TODO Auto-generated constructor stub } public FindLinksOnParadigit(ThreadGroup arg0, Runnable arg1, String arg2, long arg3) { super(arg0, arg1, arg2, arg3); // TODO Auto-generated constructor stub } }
Bvink/CypherSpider
src/tornado/org/cypherspider/productcrawlers/FindLinksOnParadigit.java
1,873
// wrm moeilijk doen als het makkelijk kan
line_comment
nl
package tornado.org.cypherspider.productcrawlers; import java.io.IOException; import java.util.ArrayList; import org.jsoup.Jsoup; import org.jsoup.select.Elements; import tornado.org.cypherspider.pagecrawlers.ParadigitCrawler; import tornado.org.neo4j.ProductDatabase; import tornado.org.settings.Settings; public class FindLinksOnParadigit extends Thread { private ArrayList<String> Navlinks = new ArrayList<>(); private ArrayList<String> productlinks = new ArrayList<>(); private ArrayList<String> productnr = new ArrayList<>(); private static org.jsoup.nodes.Document doc; private Elements e; // TODO moet altijd dezelfde object blijven in de hele applicatie private static final ProductDatabase productDatabase = new ProductDatabase(); private static final ParadigitCrawler PARADIGIT_CRAWLER = new ParadigitCrawler() ; // TODO maak nieuwe Crawler voor Mycom // private final AlternateCrawler alternateCrawler = new AlternateCrawler(); private static String url = "http://www.paradigit.nl"; private static final String hyperlinkXmltag = "a"; private static final String hyperlinkAttributetag = "href"; private static final String navXmlClassTag = "PagerContainerTable"; private static final String productLinkXmlClassTag = "itemlistcombined-productimagecontainer"; public FindLinksOnParadigit() { // wrm moeilijk<SUF> Navlinks.add("/catalog/zpr_08ond/06_pccase/default.aspx"); Navlinks.add("/catalog/zpr_08ond/12_optdriv/default.aspx"); Navlinks.add("/catalog/zpr_08ond/01_memint/default.aspx"); Navlinks.add("/catalog/zpr_02ops/01_inthdd/default.aspx"); Navlinks.add("/catalog/zpr_02ops/01_intssd/default.aspx"); Navlinks.add("/catalog/zpr_08ond/05_mobo/default.aspx"); Navlinks.add("/catalog/zpr_08ond/04_cpu/default.aspx"); Navlinks.add("/catalog/zpr_08ond/24_cpu/default.aspx"); Navlinks.add("/catalog/zpr_08ond/03_vidcard/default.aspx"); Navlinks.add("/catalog/zpr_08ond/07_psu/default.aspx"); Navlinks.add("/catalog/zpr_05swa/01_windows/default.aspx"); Navlinks.add("/catalog/zpr_08ond/21_bare/default.aspx"); Navlinks.add("/catalog/zpr_08ond/21_bare/default.aspx"); Navlinks.add("/catalog/zpr_08ond/14_control/default.aspx"); Navlinks.add("/catalog/zpr_11kbl/12_firekbl/default.aspx"); Navlinks.add("/catalog/zpr_08ond/15_sndcard/default.aspx"); Navlinks.add("/catalog/zpr_08ond/19_tools/default.aspx"); Navlinks.add("/catalog/zpr_08ond/17_cardrea/default.aspx"); Navlinks.add("/catalog/zpr_08ond/23_coolers/default.aspx"); Navlinks.add("/catalog/zpr_08ond/25_kpas/default.aspx"); Navlinks.add("/catalog/zpr_11kbl/06_satakbl/default.aspx"); Navlinks.add("/catalog/zpr_03avi/06_tvtuner/default.aspx"); Navlinks.add("/catalog/zpr_08ond/22_ups/default.aspx"); Navlinks.add("/catalog/zpr_11kbl/08_pwrkbl/default.aspx"); } public void run() { try { for (int i = 0; i < Navlinks.size(); i++) { doc = Jsoup.connect(url + Navlinks.get(i)).get(); //System.out.println(doc.toString()); e = doc.getElementsByClass(navXmlClassTag); if (e.size() > 0) { e = e.get(0).getElementsByTag(hyperlinkXmltag); for (int j = 0; j < e.size(); j++) { String link = e.get(j).attr(hyperlinkAttributetag); if (!Navlinks.contains(link)) { Navlinks.add(link); } } } e = doc.getElementsByClass(productLinkXmlClassTag); for (int j = 0; j < e.size(); j++) { String productlink = e.get(j) .getElementsByTag(hyperlinkXmltag).get(0) .attr(hyperlinkAttributetag); productlinks.add(productlink); } } // parselinks(e); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } insertProducts(); System.out.println(productlinks.size()); Settings.setParadigitEndstate(true); if (Settings.getEndstate()) { productDatabase.registerShutdownHook(); } } private void insertProducts() { productDatabase.createDB(); for (int i = 0; i < productlinks.size(); i++) { PARADIGIT_CRAWLER.crawl(url + productlinks.get(i), productDatabase); } } public FindLinksOnParadigit(Runnable arg0) { super(arg0); // TODO Auto-generated constructor stub } public FindLinksOnParadigit(String arg0) { super(arg0); // TODO Auto-generated constructor stub } public FindLinksOnParadigit(ThreadGroup arg0, Runnable arg1) { super(arg0, arg1); // TODO Auto-generated constructor stub } public FindLinksOnParadigit(ThreadGroup arg0, String arg1) { super(arg0, arg1); // TODO Auto-generated constructor stub } public FindLinksOnParadigit(Runnable arg0, String arg1) { super(arg0, arg1); // TODO Auto-generated constructor stub } public FindLinksOnParadigit(ThreadGroup arg0, Runnable arg1, String arg2) { super(arg0, arg1, arg2); // TODO Auto-generated constructor stub } public FindLinksOnParadigit(ThreadGroup arg0, Runnable arg1, String arg2, long arg3) { super(arg0, arg1, arg2, arg3); // TODO Auto-generated constructor stub } }
36166_12
import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; //lol class Gamebeheer { private ArrayList<Uitverkoop> uitverkoop; private ArrayList<Review> review; private ArrayList<Game> ranglijst; private static final String UITVERKOOP_BESTAND = "uitverkoop.txt"; private static final String REVIEW_BESTAND = "review.txt"; private static final String RANGLIJST_BESTAND = "ranglijst.txt"; private static final String ENQUETE_BESTAND = "enquete.txt"; private static final String GENRE_BESTAND = "genre.txt"; public Gamebeheer() { this.uitverkoop = new ArrayList<>(); this.review = new ArrayList<>(); this.ranglijst = new ArrayList<>(); } public void Addranglijst(String game, double rating, String genre, double prijs) { Game bestaandeGame = zoekRanglijst(game); if (bestaandeGame == null) { // De game staat nog niet in de ranglijst, dus voeg deze toe Game nieuweRanglijst = new Game(Game.getVolgendGameID(), game, rating, genre, prijs); ranglijst.add(nieuweRanglijst); saveRanglijst(); System.out.println("Game toegevoegd met de gameid: " + nieuweRanglijst.getGameid()); ranglijst.clear(); } else { // De game staat al in de ranglijst, dus update de bestaande game bestaandeGame.setRating(rating); bestaandeGame.setGenre(genre); bestaandeGame.setPrijs(prijs); saveRanglijst(); System.out.println("Game bijgewerkt met de gameid: " + bestaandeGame.getGameid()); } } public void AddReview(String game, double gameplayrating, double graphicsrating, double storylinerating, String tekst) { // Voeg de nieuwe review toe Review nieuweReview = new Review(Review.getVolgendReviewID(), game, gameplayrating, graphicsrating, storylinerating, tekst); review.add(nieuweReview); saveReview(); System.out.println("Review toegevoegd met de reviewid: " + nieuweReview.getReviewid()); // Update de rating in de ranglijst op basis van de nieuwe review updateRatingInRanglijst(game, gameplayrating, graphicsrating, storylinerating); } public double berekenGemiddeldeRating(String game) { double totalRating = 0; int count = 0; for (Review review : review) { if (review.getGame().equalsIgnoreCase(game)) { totalRating += (review.getGameplayrating() + review.getGraphicsrating() + review.getStorylinerating()) / 3.0; count++; } } return count == 0 ? 0 : totalRating / count; } public void updateRatingInRanglijst(String game, double gameplayrating, double graphicsrating, double storylinerating) { double nieuweReviewRating = (gameplayrating + graphicsrating + storylinerating) / 3.0; Game gameInRanglijst = zoekRanglijst(game); if (gameInRanglijst != null) { double bestaandeRating = gameInRanglijst.getRating(); double gecombineerdeRating = (bestaandeRating + nieuweReviewRating) / 2.0; gecombineerdeRating = Math.round(gecombineerdeRating * 10.0) / 10.0; // Afronden naar 1 decimaal gameInRanglijst.setRating(gecombineerdeRating); saveRanglijst(); System.out.println("Rating in de ranglijst voor " + game + " is bijgewerkt naar " + gecombineerdeRating); } else { System.out.println("Game met de naam " + game + " niet gevonden in de ranglijst."); } } public void toonReview() { try (BufferedReader reader = new BufferedReader(new FileReader(REVIEW_BESTAND))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { System.out.println("Fout bij het laden van Reviews: " + e.getMessage()); } } public double berekenKorting(double prijs, int korting) { double kortingBedrag = prijs * (korting / 100.0); return prijs - kortingBedrag; } public void voegToeAanUitverkoop(String gameNaam, int korting) { Game gameInRanglijst = zoekRanglijst(gameNaam); if (gameInRanglijst != null) { double nieuwePrijs = berekenKorting(gameInRanglijst.getPrijs(), korting); Uitverkoop nieuweUitverkoop = new Uitverkoop(Uitverkoop.getVolgendUitverkoopID(), gameNaam, korting, nieuwePrijs); uitverkoop.add(nieuweUitverkoop); saveUitverkoop(); System.out.println("Uitverkoop toegevoegd met de uitverkoopid: " + nieuweUitverkoop.getUitverkoopid()); // Update the price in the ranglijst updatePriceInRanglijst(gameNaam, nieuwePrijs); } else { System.out.println("Game niet gevonden in de ranglijst."); } } public void updatePriceInRanglijst(String gameNaam, double nieuwePrijs) { Game gameInRanglijst = zoekRanglijst(gameNaam); if (gameInRanglijst != null) { gameInRanglijst.setPrijs(nieuwePrijs); saveRanglijst(); System.out.println("Prijs in de ranglijst voor " + gameNaam + " is bijgewerkt naar " + nieuwePrijs); } else { System.out.println("Game met de naam " + gameNaam + " niet gevonden in de ranglijst."); } } // verander deze methode want er komt steeds error out of bounds!!!! public void toonUitverkoop() { uitverkoop.clear(); // Zorg dat de lijst leeg is voordat je gaat laden try { Files.lines(Paths.get(UITVERKOOP_BESTAND)) .map(line -> line.split(",")) .filter(parts -> parts.length >= 4) .forEach(parts -> { try { int id = Integer.parseInt(parts[0].trim()); String game = parts[1].split(":")[1].trim(); int korting = Integer.parseInt(parts[2].split(":")[1].trim()); double prijs = Double.parseDouble(parts[3].split(":")[1].trim()); Uitverkoop uitverkoopItem = new Uitverkoop(id, game, korting, prijs); uitverkoop.add(uitverkoopItem); System.out.println(uitverkoopItem); // Print het Uitverkoop object naar de console } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Ongeldige regel in uitverkoop bestand: " + Arrays.toString(parts)); } }); } catch (IOException e) { System.out.println("Fout bij het laden van Uitverkoop: " + e.getMessage()); } } public void verwijderUitverkoop(int uitverkoopid) { Uitverkoop teVerwijderenUitverkoop = null; for (Uitverkoop u : uitverkoop) { if (u.getUitverkoopid() == uitverkoopid) { teVerwijderenUitverkoop = u; break; } } if (teVerwijderenUitverkoop != null) { uitverkoop.remove(teVerwijderenUitverkoop); System.out.println("Uitverkoop met id " + uitverkoopid + " is verwijderd."); saveUitverkoop(); // Update de uitverkoop.txt bestand } else { System.out.println("Uitverkoop met id " + uitverkoopid + " is niet gevonden."); } } public Uitverkoop zoekUitverkoop(int uitverkoopid) { for (Uitverkoop uitverkoop : uitverkoop) { if (uitverkoop.getUitverkoopid() == uitverkoopid) { return uitverkoop; } } return null; } public void verwijderReview(int reviewid) { Review review = zoekReview(reviewid); if (review != null) { this.review.remove(review); saveReview(); System.out.println("Review met reviewid " + reviewid + " is verwijderd."); } else { System.out.println("Review met reviewid " + reviewid + " niet gevonden."); } } public Review zoekReview(int reviewid) { for (Review review : review) { if (review.getReviewid() == reviewid) { return review; } } return null; } public void verwijderRanglijst(int gameid) { Game ranglijst = zoekRanglijstid(gameid); if (ranglijst != null) { this.ranglijst.remove(ranglijst); saveRanglijst(); System.out.println("Game met gameid " + gameid + " is verwijderd."); } else { System.out.println("Game met gameid " + gameid + " niet gevonden."); } } public Game zoekRanglijstid(int gameid) { for (Game ranglijst : ranglijst) { if (ranglijst.getGameid() == gameid) { return ranglijst; } } return null; } public Game zoekRanglijst(String game) { for (Game ranglijst : ranglijst) { if (ranglijst.getGame().equalsIgnoreCase(game)) { return ranglijst; } } return null; } public void toonRanglijst() { // Load the games from the file only if the ranglijst list is empty if (ranglijst.isEmpty()) { try (BufferedReader reader = new BufferedReader(new FileReader(RANGLIJST_BESTAND))) { String line; while ((line = reader.readLine()) != null) { // Parse each line and add the Game to the list String[] parts = line.split(","); int gameid = Integer.parseInt(parts[0].trim()); String game = parts[1].substring(parts[1].indexOf(":") + 1).trim(); double rating = Double.parseDouble(parts[2].substring(parts[2].indexOf(":") + 1).trim()); String genre = parts[3].substring(parts[3].indexOf(":") + 1).trim(); double prijs = Double.parseDouble(parts[4].substring(parts[4].indexOf(":") + 1).trim()); ranglijst.add(new Game(gameid, game, rating, genre, prijs)); } } catch (IOException e) { System.out.println("Fout bij het laden van Ranglijst: " + e.getMessage()); } } // Sorteer de ranglijst op basis van rating Collections.sort(ranglijst, Comparator.comparingDouble(Game::getRating).reversed()); // Toon de gesorteerde ranglijst for (Game game : ranglijst) { System.out.println(game); } } public void saveRanglijst() { try (BufferedWriter writer = new BufferedWriter(new FileWriter(RANGLIJST_BESTAND, false))) { for (Game ranglijstItem : ranglijst) { writer.write(ranglijstItem.toString()); writer.newLine(); } } catch (IOException e) { System.out.println("Fout bij het opslaan van Ranglijst: " + e.getMessage()); } } public void saveReview() { try (BufferedWriter writer = new BufferedWriter(new FileWriter(REVIEW_BESTAND, true))) { // Voeg true toe als tweede parameter om toe te voegen in plaats van overschrijven for (Review review : review) { writer.write(review.toString()); writer.newLine(); } } catch (IOException e) { System.out.println("Fout bij het opslaan van Reviews: " + e.getMessage()); } } public void saveUitverkoop() { try (BufferedWriter writer = new BufferedWriter(new FileWriter(UITVERKOOP_BESTAND, false))) { for (Uitverkoop uitverkoopItem : uitverkoop) { writer.write(uitverkoopItem.toString()); writer.newLine(); } } catch (IOException e) { System.out.println("Fout bij het opslaan van Uitverkoop: " + e.getMessage()); } } public void updateRatingInRanglijst(String game, double nieuweRating) { Game gameInRanglijst = zoekRanglijst(game); if (gameInRanglijst != null) { double origineleRating = gameInRanglijst.getRating(); int aantalReviews = review.stream().filter(r -> r.getGame().equalsIgnoreCase(game)).toArray().length; double totaalGewicht = origineleRating + aantalReviews; double nieuweTotaalRating = origineleRating + nieuweRating; double nieuweGemiddeldeRating = nieuweTotaalRating / totaalGewicht; gameInRanglijst.setRating(nieuweGemiddeldeRating); saveRanglijst(); System.out.println("Rating in de ranglijst voor " + game + " is bijgewerkt naar " + nieuweGemiddeldeRating); } else { System.out.println("Game met de naam " + game + " niet gevonden in de ranglijst."); } } public void addGenre(String genre){ try (BufferedWriter writer = new BufferedWriter(new FileWriter(GENRE_BESTAND, true))) { writer.write(genre); writer.newLine(); } catch (IOException e) { e.printStackTrace(); } } public void toonBeschikbareGenres() { ArrayList<String> genres = new ArrayList<>(); for (Game game : ranglijst) { String genre = game.getGenre(); if (!genres.contains(genre)) { genres.add(genre); } } System.out.println("Available genres:"); for (String genre : genres) { System.out.println(genre); } } public void toonGamesOpGenre(String genre) { boolean found = false; System.out.println("Games in het genre: " + genre); for (Game game : ranglijst) { if (game.getGenre().equalsIgnoreCase(genre.trim())) { // Verwijder extra spaties en maak vergelijking case-insensitive System.out.println(game); found = true; } } if (!found) { System.out.println("Geen games gevonden in het genre: " + genre); } } public void vulEnqueteIn() { try (BufferedWriter writer = new BufferedWriter(new FileWriter(ENQUETE_BESTAND))) { // Open vragen Scanner scanner = new Scanner(System.in); System.out.println("Beantwoord de volgende open vragen:"); System.out.print("1. Hoe speelt u nomaal games? "); String antwoord1 = scanner.nextLine(); System.out.print("2. Wat vindt u leuk aan retrogames? "); String antwoord2 = scanner.nextLine(); writer.write("Open vragen:\n"); writer.write("1. Hoe speelt u normaal games? Antwoord: " + antwoord1 + "\n"); writer.write("2. Wat vindt u leuk aan retrogames? Antwoord: " + antwoord2 + "\n"); // Multiple choice vragen System.out.println("Beantwoord de volgende multiple choice vragen:"); System.out.println("1. hoe vaak speelt uw games"); System.out.println(" a) soms"); System.out.println(" b) regelmatig"); System.out.println(" c) vaak"); System.out.print("Antwoord: "); String antwoord3 = scanner.nextLine(); System.out.println("2. Op welk platform speelt u games?"); System.out.println(" a) pc"); System.out.println(" b) console"); System.out.println(" c) mobile"); System.out.print("Antwoord: "); String antwoord4 = scanner.nextLine(); writer.write("Multiple choice vragen:\n"); writer.write("1. hoe vaak speelt uw games? Antwoord: " + antwoord3 + "\n"); writer.write("2. Op welk platform speelt u games? Antwoord: " + antwoord4 + "\n"); // Conditionele vraag System.out.println("Beantwoord de volgende conditionele vraag:"); if (antwoord4.equalsIgnoreCase("a") || antwoord4.equalsIgnoreCase("a")) { System.out.println("3. Speel je op een high-end gaming systeem?"); System.out.println(" a) Ja"); System.out.println(" b) Nee"); System.out.print("Antwoord: "); String antwoord5 = scanner.nextLine(); writer.write("Conditionele vraag:\n"); writer.write("3. Speel je het spel op een high-end gaming systeem? Antwoord: " + antwoord5 + "\n"); } else { System.out.println("3. Deze vraag wordt alleen gesteld als je op pc speelt"); writer.write("Conditionele vraag:\n"); writer.write("3. Deze vraag wordt alleen gesteld als je op pc speelt.\n"); } System.out.println("Enquête succesvol ingevuld."); } catch (IOException e) { System.out.println("Fout bij het invullen van de enquête: " + e.getMessage()); } } public Uitverkoop zoekUitverkoop(String gameNaamUitverkoop) { for (Uitverkoop uitverkoopItem : uitverkoop) { if (uitverkoopItem.getGame().equalsIgnoreCase(gameNaamUitverkoop)) { return uitverkoopItem; } } return null; } }
Byrott0/PROJ1versie2
src/Gamebeheer.java
5,329
// Sorteer de ranglijst op basis van rating
line_comment
nl
import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; //lol class Gamebeheer { private ArrayList<Uitverkoop> uitverkoop; private ArrayList<Review> review; private ArrayList<Game> ranglijst; private static final String UITVERKOOP_BESTAND = "uitverkoop.txt"; private static final String REVIEW_BESTAND = "review.txt"; private static final String RANGLIJST_BESTAND = "ranglijst.txt"; private static final String ENQUETE_BESTAND = "enquete.txt"; private static final String GENRE_BESTAND = "genre.txt"; public Gamebeheer() { this.uitverkoop = new ArrayList<>(); this.review = new ArrayList<>(); this.ranglijst = new ArrayList<>(); } public void Addranglijst(String game, double rating, String genre, double prijs) { Game bestaandeGame = zoekRanglijst(game); if (bestaandeGame == null) { // De game staat nog niet in de ranglijst, dus voeg deze toe Game nieuweRanglijst = new Game(Game.getVolgendGameID(), game, rating, genre, prijs); ranglijst.add(nieuweRanglijst); saveRanglijst(); System.out.println("Game toegevoegd met de gameid: " + nieuweRanglijst.getGameid()); ranglijst.clear(); } else { // De game staat al in de ranglijst, dus update de bestaande game bestaandeGame.setRating(rating); bestaandeGame.setGenre(genre); bestaandeGame.setPrijs(prijs); saveRanglijst(); System.out.println("Game bijgewerkt met de gameid: " + bestaandeGame.getGameid()); } } public void AddReview(String game, double gameplayrating, double graphicsrating, double storylinerating, String tekst) { // Voeg de nieuwe review toe Review nieuweReview = new Review(Review.getVolgendReviewID(), game, gameplayrating, graphicsrating, storylinerating, tekst); review.add(nieuweReview); saveReview(); System.out.println("Review toegevoegd met de reviewid: " + nieuweReview.getReviewid()); // Update de rating in de ranglijst op basis van de nieuwe review updateRatingInRanglijst(game, gameplayrating, graphicsrating, storylinerating); } public double berekenGemiddeldeRating(String game) { double totalRating = 0; int count = 0; for (Review review : review) { if (review.getGame().equalsIgnoreCase(game)) { totalRating += (review.getGameplayrating() + review.getGraphicsrating() + review.getStorylinerating()) / 3.0; count++; } } return count == 0 ? 0 : totalRating / count; } public void updateRatingInRanglijst(String game, double gameplayrating, double graphicsrating, double storylinerating) { double nieuweReviewRating = (gameplayrating + graphicsrating + storylinerating) / 3.0; Game gameInRanglijst = zoekRanglijst(game); if (gameInRanglijst != null) { double bestaandeRating = gameInRanglijst.getRating(); double gecombineerdeRating = (bestaandeRating + nieuweReviewRating) / 2.0; gecombineerdeRating = Math.round(gecombineerdeRating * 10.0) / 10.0; // Afronden naar 1 decimaal gameInRanglijst.setRating(gecombineerdeRating); saveRanglijst(); System.out.println("Rating in de ranglijst voor " + game + " is bijgewerkt naar " + gecombineerdeRating); } else { System.out.println("Game met de naam " + game + " niet gevonden in de ranglijst."); } } public void toonReview() { try (BufferedReader reader = new BufferedReader(new FileReader(REVIEW_BESTAND))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { System.out.println("Fout bij het laden van Reviews: " + e.getMessage()); } } public double berekenKorting(double prijs, int korting) { double kortingBedrag = prijs * (korting / 100.0); return prijs - kortingBedrag; } public void voegToeAanUitverkoop(String gameNaam, int korting) { Game gameInRanglijst = zoekRanglijst(gameNaam); if (gameInRanglijst != null) { double nieuwePrijs = berekenKorting(gameInRanglijst.getPrijs(), korting); Uitverkoop nieuweUitverkoop = new Uitverkoop(Uitverkoop.getVolgendUitverkoopID(), gameNaam, korting, nieuwePrijs); uitverkoop.add(nieuweUitverkoop); saveUitverkoop(); System.out.println("Uitverkoop toegevoegd met de uitverkoopid: " + nieuweUitverkoop.getUitverkoopid()); // Update the price in the ranglijst updatePriceInRanglijst(gameNaam, nieuwePrijs); } else { System.out.println("Game niet gevonden in de ranglijst."); } } public void updatePriceInRanglijst(String gameNaam, double nieuwePrijs) { Game gameInRanglijst = zoekRanglijst(gameNaam); if (gameInRanglijst != null) { gameInRanglijst.setPrijs(nieuwePrijs); saveRanglijst(); System.out.println("Prijs in de ranglijst voor " + gameNaam + " is bijgewerkt naar " + nieuwePrijs); } else { System.out.println("Game met de naam " + gameNaam + " niet gevonden in de ranglijst."); } } // verander deze methode want er komt steeds error out of bounds!!!! public void toonUitverkoop() { uitverkoop.clear(); // Zorg dat de lijst leeg is voordat je gaat laden try { Files.lines(Paths.get(UITVERKOOP_BESTAND)) .map(line -> line.split(",")) .filter(parts -> parts.length >= 4) .forEach(parts -> { try { int id = Integer.parseInt(parts[0].trim()); String game = parts[1].split(":")[1].trim(); int korting = Integer.parseInt(parts[2].split(":")[1].trim()); double prijs = Double.parseDouble(parts[3].split(":")[1].trim()); Uitverkoop uitverkoopItem = new Uitverkoop(id, game, korting, prijs); uitverkoop.add(uitverkoopItem); System.out.println(uitverkoopItem); // Print het Uitverkoop object naar de console } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Ongeldige regel in uitverkoop bestand: " + Arrays.toString(parts)); } }); } catch (IOException e) { System.out.println("Fout bij het laden van Uitverkoop: " + e.getMessage()); } } public void verwijderUitverkoop(int uitverkoopid) { Uitverkoop teVerwijderenUitverkoop = null; for (Uitverkoop u : uitverkoop) { if (u.getUitverkoopid() == uitverkoopid) { teVerwijderenUitverkoop = u; break; } } if (teVerwijderenUitverkoop != null) { uitverkoop.remove(teVerwijderenUitverkoop); System.out.println("Uitverkoop met id " + uitverkoopid + " is verwijderd."); saveUitverkoop(); // Update de uitverkoop.txt bestand } else { System.out.println("Uitverkoop met id " + uitverkoopid + " is niet gevonden."); } } public Uitverkoop zoekUitverkoop(int uitverkoopid) { for (Uitverkoop uitverkoop : uitverkoop) { if (uitverkoop.getUitverkoopid() == uitverkoopid) { return uitverkoop; } } return null; } public void verwijderReview(int reviewid) { Review review = zoekReview(reviewid); if (review != null) { this.review.remove(review); saveReview(); System.out.println("Review met reviewid " + reviewid + " is verwijderd."); } else { System.out.println("Review met reviewid " + reviewid + " niet gevonden."); } } public Review zoekReview(int reviewid) { for (Review review : review) { if (review.getReviewid() == reviewid) { return review; } } return null; } public void verwijderRanglijst(int gameid) { Game ranglijst = zoekRanglijstid(gameid); if (ranglijst != null) { this.ranglijst.remove(ranglijst); saveRanglijst(); System.out.println("Game met gameid " + gameid + " is verwijderd."); } else { System.out.println("Game met gameid " + gameid + " niet gevonden."); } } public Game zoekRanglijstid(int gameid) { for (Game ranglijst : ranglijst) { if (ranglijst.getGameid() == gameid) { return ranglijst; } } return null; } public Game zoekRanglijst(String game) { for (Game ranglijst : ranglijst) { if (ranglijst.getGame().equalsIgnoreCase(game)) { return ranglijst; } } return null; } public void toonRanglijst() { // Load the games from the file only if the ranglijst list is empty if (ranglijst.isEmpty()) { try (BufferedReader reader = new BufferedReader(new FileReader(RANGLIJST_BESTAND))) { String line; while ((line = reader.readLine()) != null) { // Parse each line and add the Game to the list String[] parts = line.split(","); int gameid = Integer.parseInt(parts[0].trim()); String game = parts[1].substring(parts[1].indexOf(":") + 1).trim(); double rating = Double.parseDouble(parts[2].substring(parts[2].indexOf(":") + 1).trim()); String genre = parts[3].substring(parts[3].indexOf(":") + 1).trim(); double prijs = Double.parseDouble(parts[4].substring(parts[4].indexOf(":") + 1).trim()); ranglijst.add(new Game(gameid, game, rating, genre, prijs)); } } catch (IOException e) { System.out.println("Fout bij het laden van Ranglijst: " + e.getMessage()); } } // Sorteer de<SUF> Collections.sort(ranglijst, Comparator.comparingDouble(Game::getRating).reversed()); // Toon de gesorteerde ranglijst for (Game game : ranglijst) { System.out.println(game); } } public void saveRanglijst() { try (BufferedWriter writer = new BufferedWriter(new FileWriter(RANGLIJST_BESTAND, false))) { for (Game ranglijstItem : ranglijst) { writer.write(ranglijstItem.toString()); writer.newLine(); } } catch (IOException e) { System.out.println("Fout bij het opslaan van Ranglijst: " + e.getMessage()); } } public void saveReview() { try (BufferedWriter writer = new BufferedWriter(new FileWriter(REVIEW_BESTAND, true))) { // Voeg true toe als tweede parameter om toe te voegen in plaats van overschrijven for (Review review : review) { writer.write(review.toString()); writer.newLine(); } } catch (IOException e) { System.out.println("Fout bij het opslaan van Reviews: " + e.getMessage()); } } public void saveUitverkoop() { try (BufferedWriter writer = new BufferedWriter(new FileWriter(UITVERKOOP_BESTAND, false))) { for (Uitverkoop uitverkoopItem : uitverkoop) { writer.write(uitverkoopItem.toString()); writer.newLine(); } } catch (IOException e) { System.out.println("Fout bij het opslaan van Uitverkoop: " + e.getMessage()); } } public void updateRatingInRanglijst(String game, double nieuweRating) { Game gameInRanglijst = zoekRanglijst(game); if (gameInRanglijst != null) { double origineleRating = gameInRanglijst.getRating(); int aantalReviews = review.stream().filter(r -> r.getGame().equalsIgnoreCase(game)).toArray().length; double totaalGewicht = origineleRating + aantalReviews; double nieuweTotaalRating = origineleRating + nieuweRating; double nieuweGemiddeldeRating = nieuweTotaalRating / totaalGewicht; gameInRanglijst.setRating(nieuweGemiddeldeRating); saveRanglijst(); System.out.println("Rating in de ranglijst voor " + game + " is bijgewerkt naar " + nieuweGemiddeldeRating); } else { System.out.println("Game met de naam " + game + " niet gevonden in de ranglijst."); } } public void addGenre(String genre){ try (BufferedWriter writer = new BufferedWriter(new FileWriter(GENRE_BESTAND, true))) { writer.write(genre); writer.newLine(); } catch (IOException e) { e.printStackTrace(); } } public void toonBeschikbareGenres() { ArrayList<String> genres = new ArrayList<>(); for (Game game : ranglijst) { String genre = game.getGenre(); if (!genres.contains(genre)) { genres.add(genre); } } System.out.println("Available genres:"); for (String genre : genres) { System.out.println(genre); } } public void toonGamesOpGenre(String genre) { boolean found = false; System.out.println("Games in het genre: " + genre); for (Game game : ranglijst) { if (game.getGenre().equalsIgnoreCase(genre.trim())) { // Verwijder extra spaties en maak vergelijking case-insensitive System.out.println(game); found = true; } } if (!found) { System.out.println("Geen games gevonden in het genre: " + genre); } } public void vulEnqueteIn() { try (BufferedWriter writer = new BufferedWriter(new FileWriter(ENQUETE_BESTAND))) { // Open vragen Scanner scanner = new Scanner(System.in); System.out.println("Beantwoord de volgende open vragen:"); System.out.print("1. Hoe speelt u nomaal games? "); String antwoord1 = scanner.nextLine(); System.out.print("2. Wat vindt u leuk aan retrogames? "); String antwoord2 = scanner.nextLine(); writer.write("Open vragen:\n"); writer.write("1. Hoe speelt u normaal games? Antwoord: " + antwoord1 + "\n"); writer.write("2. Wat vindt u leuk aan retrogames? Antwoord: " + antwoord2 + "\n"); // Multiple choice vragen System.out.println("Beantwoord de volgende multiple choice vragen:"); System.out.println("1. hoe vaak speelt uw games"); System.out.println(" a) soms"); System.out.println(" b) regelmatig"); System.out.println(" c) vaak"); System.out.print("Antwoord: "); String antwoord3 = scanner.nextLine(); System.out.println("2. Op welk platform speelt u games?"); System.out.println(" a) pc"); System.out.println(" b) console"); System.out.println(" c) mobile"); System.out.print("Antwoord: "); String antwoord4 = scanner.nextLine(); writer.write("Multiple choice vragen:\n"); writer.write("1. hoe vaak speelt uw games? Antwoord: " + antwoord3 + "\n"); writer.write("2. Op welk platform speelt u games? Antwoord: " + antwoord4 + "\n"); // Conditionele vraag System.out.println("Beantwoord de volgende conditionele vraag:"); if (antwoord4.equalsIgnoreCase("a") || antwoord4.equalsIgnoreCase("a")) { System.out.println("3. Speel je op een high-end gaming systeem?"); System.out.println(" a) Ja"); System.out.println(" b) Nee"); System.out.print("Antwoord: "); String antwoord5 = scanner.nextLine(); writer.write("Conditionele vraag:\n"); writer.write("3. Speel je het spel op een high-end gaming systeem? Antwoord: " + antwoord5 + "\n"); } else { System.out.println("3. Deze vraag wordt alleen gesteld als je op pc speelt"); writer.write("Conditionele vraag:\n"); writer.write("3. Deze vraag wordt alleen gesteld als je op pc speelt.\n"); } System.out.println("Enquête succesvol ingevuld."); } catch (IOException e) { System.out.println("Fout bij het invullen van de enquête: " + e.getMessage()); } } public Uitverkoop zoekUitverkoop(String gameNaamUitverkoop) { for (Uitverkoop uitverkoopItem : uitverkoop) { if (uitverkoopItem.getGame().equalsIgnoreCase(gameNaamUitverkoop)) { return uitverkoopItem; } } return null; } }
32501_2
import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.UUID; public class Medicijn { private String naam; private String innameTijd; private final long innameTijdVerschil; private final int id; public Medicijn(String naam, String innameTijd) { this.naam = naam; this.innameTijd = innameTijd; this.id = UUID.randomUUID().hashCode(); //dit genereert een unieke id voor elk medicijn //en hashcode is een unieke waarde voor elk object wat in int teruggegeven wordt DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm"); LocalTime innameTijdLocal = LocalTime.parse(innameTijd, formatter); LocalTime now = LocalTime.now(); //datetimeformatter zorgt ervoor dat de tijd in het juiste formaat wordt geprint //localtime.parse zorgt ervoor dat de tijd in het juiste formaat wordt geprint //localtime.now zorgt ervoor dat de tijd van nu wordt geprint int innameTijdSeconds = innameTijdLocal.toSecondOfDay() / 60; int nowMinutes = now.toSecondOfDay()/ 60; long tijdVerschil = innameTijdSeconds - nowMinutes; //verschil in seconden tussen de inname tijd en de huidige tijd // Als de tijd negatief is, voeg dan 24 uur (in seconden) toe om de tijd correct in te stellen voor de volgende dag. if (tijdVerschil < 0) { tijdVerschil += 24 * 60; } this.innameTijdVerschil = tijdVerschil * 1000L; //L staat voor long type System.out.println("Ik ga wachten in minuten: " + innameTijdVerschil /1000L); } public String getNaam() { return naam; } public String getInnameTijd() { return innameTijd; } public long getInnameTijdVerschilMS() { return innameTijdVerschil; } public int getId() { return id; } public void setNaam(String naam) { this.naam = naam; } public void setInnameTijd(String innameTijd) { this.innameTijd = innameTijd; } }
Byrott0/Portfolio2
Medicijn.java
676
//datetimeformatter zorgt ervoor dat de tijd in het juiste formaat wordt geprint
line_comment
nl
import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.UUID; public class Medicijn { private String naam; private String innameTijd; private final long innameTijdVerschil; private final int id; public Medicijn(String naam, String innameTijd) { this.naam = naam; this.innameTijd = innameTijd; this.id = UUID.randomUUID().hashCode(); //dit genereert een unieke id voor elk medicijn //en hashcode is een unieke waarde voor elk object wat in int teruggegeven wordt DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm"); LocalTime innameTijdLocal = LocalTime.parse(innameTijd, formatter); LocalTime now = LocalTime.now(); //datetimeformatter zorgt<SUF> //localtime.parse zorgt ervoor dat de tijd in het juiste formaat wordt geprint //localtime.now zorgt ervoor dat de tijd van nu wordt geprint int innameTijdSeconds = innameTijdLocal.toSecondOfDay() / 60; int nowMinutes = now.toSecondOfDay()/ 60; long tijdVerschil = innameTijdSeconds - nowMinutes; //verschil in seconden tussen de inname tijd en de huidige tijd // Als de tijd negatief is, voeg dan 24 uur (in seconden) toe om de tijd correct in te stellen voor de volgende dag. if (tijdVerschil < 0) { tijdVerschil += 24 * 60; } this.innameTijdVerschil = tijdVerschil * 1000L; //L staat voor long type System.out.println("Ik ga wachten in minuten: " + innameTijdVerschil /1000L); } public String getNaam() { return naam; } public String getInnameTijd() { return innameTijd; } public long getInnameTijdVerschilMS() { return innameTijdVerschil; } public int getId() { return id; } public void setNaam(String naam) { this.naam = naam; } public void setInnameTijd(String innameTijd) { this.innameTijd = innameTijd; } }
39571_4
package at.castana.cordova.plugins.zebraprint; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Looper; import android.util.Base64; import android.util.Log; import com.zebra.sdk.comm.BluetoothConnection; import com.zebra.sdk.comm.Connection; import com.zebra.sdk.comm.ConnectionException; import com.zebra.sdk.graphics.internal.ZebraImageAndroid; import com.zebra.sdk.printer.PrinterStatus; import com.zebra.sdk.printer.SGD; import com.zebra.sdk.printer.ZebraPrinter; import com.zebra.sdk.printer.ZebraPrinterFactory; import com.zebra.sdk.printer.ZebraPrinterLanguageUnknownException; import com.zebra.sdk.printer.ZebraPrinterLinkOs; import com.zebra.sdk.printer.discovery.BluetoothDiscoverer; import com.zebra.sdk.printer.discovery.DiscoveredPrinter; import com.zebra.sdk.printer.discovery.DiscoveryHandler; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.json.JSONArray; import org.json.JSONException; import java.io.IOException; import java.util.Set; public class ZebraPrint extends CordovaPlugin implements DiscoveryHandler { private static final String LOG_TAG = "ZebraPrint"; private CallbackContext callbackContext; private boolean printerFound; private Connection thePrinterConn; private PrinterStatus printerStatus; private ZebraPrinter printer; private final int MAX_PRINT_RETRIES = 1; private int speed; private int time; private int number; public ZebraPrint() { } // @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { this.callbackContext = callbackContext; if (action.equals("printImage")) { try { JSONArray labels = args.getJSONArray(0); String MACAddress = args.getString(1); speed = args.getInt(2); time = args.getInt(3); number = args.getInt(4); for (int i = 1; i < number; i++) { labels.put(labels.get(0)); } sendImage(labels, MACAddress); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage()); e.printStackTrace(); } return true; } else if (action.equals("discoverPrinters")) { discoverPrinters(); return true; } else if (action.equals("getPrinterName")) { String MACAddress = args.getString(0); getPrinterName(MACAddress); return true; } else if (action.equals("echo")) { String echoString = args.getString(0); sendEcho(echoString); return true; } return false; } private void sendImage(final JSONArray labels, final String MACAddress) throws IOException { new Thread(new Runnable() { @Override public void run() { printLabels(labels, MACAddress); } }).start(); } private void printLabels(JSONArray labels, String MACAddress) { try { boolean isConnected = openBluetoothConnection(MACAddress); if (isConnected) { initializePrinter(); boolean isPrinterReady = getPrinterStatus(0); if (isPrinterReady) { printLabel(labels); //Voldoende wachten zodat label afgeprint is voordat we een nieuwe printer-operatie starten. // Sufficient waiting for the label to print before we start a new printer operation. //Thread.sleep(15000); //SGD.SET("device.languages", "line_print", thePrinterConn); thePrinterConn.close(); callbackContext.success(); } else { Log.e(LOG_TAG, "Printer not ready"); callbackContext.error("The printer is not ready yet."); } } else { Log.e(LOG_TAG, "Printer not connected"); callbackContext.error("The printer is not connected."); } } catch (ConnectionException e) { Log.e(LOG_TAG, "Connection exception: " + e.getMessage()); //De connectie tussen de printer & het toestel is verloren gegaan. if (e.getMessage().toLowerCase().contains("broken pipe")) { callbackContext.error("The connection between the device and the printer was interrupted. Please try again."); //Geen printer gevonden via bluetooth, -1 teruggeven zodat er gezocht wordt naar nieuwe printers. } else if (e.getMessage().toLowerCase().contains("socket might closed")) { int SEARCH_NEW_PRINTERS = -1; callbackContext.error(SEARCH_NEW_PRINTERS); } else { callbackContext.error("There was an unknown printer error. Please restart the printer and try again."); } } catch (ZebraPrinterLanguageUnknownException e) { Log.e(LOG_TAG, "ZebraPrinterLanguageUnknown exception: " + e.getMessage()); callbackContext.error("There was an unknown printer error. Please restart the printer and try again."); } catch (Exception e) { Log.e(LOG_TAG, "Exception: " + e.getMessage()); callbackContext.error(e.getMessage()); } } private void initializePrinter() throws ConnectionException, ZebraPrinterLanguageUnknownException { Log.d(LOG_TAG, "Initializing printer..."); printer = ZebraPrinterFactory.getInstance(thePrinterConn); String printerLanguage = SGD.GET("device.languages", thePrinterConn); if (!printerLanguage.contains("zpl")) { // print diff SGD.SET("device.languages", "hybrid_xml_zpl", thePrinterConn); Log.d(LOG_TAG, "printer language set..."); } } private boolean openBluetoothConnection(String MACAddress) throws ConnectionException { BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter.isEnabled()) { Log.d(LOG_TAG, "Creating a bluetooth-connection for mac-address " + MACAddress); thePrinterConn = new BluetoothConnection(MACAddress); Log.d(LOG_TAG, "Opening connection..."); thePrinterConn.open(); Log.d(LOG_TAG, "connection successfully opened..."); return true; } else { Log.d(LOG_TAG, "Bluetooth is disabled..."); callbackContext.error("Bluetooth is not turned on."); } return false; } private void printLabel(JSONArray labels) throws Exception { ZebraPrinterLinkOs zebraPrinterLinkOs = ZebraPrinterFactory.createLinkOsPrinter(printer); for (int i = labels.length() - 1; i >= 0; i--) { String base64Image = labels.get(i).toString(); byte[] decodedString = Base64.decode(base64Image, Base64.DEFAULT); Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); ZebraImageAndroid zebraimage = new ZebraImageAndroid(decodedByte); int labelHeight = Integer.valueOf(zebraimage.getHeight()); int labelSleep = (Integer.valueOf(labelHeight / 400) * 1000) * speed; Log.d(LOG_TAG, "labelHeight: " + Integer.toString(labelHeight)); Log.d(LOG_TAG, "labelSleep: " + Integer.toString(labelSleep)); // Set the length of the label first to prevent too small or too large a print if (zebraPrinterLinkOs != null && i == labels.length() - 1) { setLabelLength(zebraimage); } if (zebraPrinterLinkOs != null) { Log.d(LOG_TAG, "calling printer.printImage"); //printer.printImage(zebraimage, 20, 20, zebraimage.getWidth(), zebraimage.getHeight(), false); printer.printImage(zebraimage, 0, 0, 0, 0, false); } else { Log.d(LOG_TAG, "Storing label on printer..."); printer.storeImage("wgkimage.pcx", zebraimage, -1, -1); printImageTheOldWay(zebraimage); SGD.SET("device.languages", "line_print", thePrinterConn); } Thread.sleep(labelSleep); if (i > 0) { Thread.sleep(1000 * time); } } if (labels.length() == 0) { Log.e(LOG_TAG, "No labels for printing ..."); } } private void printImageTheOldWay(ZebraImageAndroid zebraimage) throws Exception { Log.d(LOG_TAG, "Printing image..."); String cpcl = "! 0 200 200 "; cpcl += zebraimage.getHeight(); cpcl += " 1\r\n"; // print diff cpcl += "PW 750\r\nTONE 0\r\nSPEED 6\r\nSETFF 203 5\r\nON - FEED FEED\r\nAUTO - PACE\r\nJOURNAL\r\n"; //cpcl += "TONE 0\r\nJOURNAL\r\n"; cpcl += "PCX 150 0 !<wgkimage.pcx\r\n"; cpcl += "FORM\r\n"; cpcl += "PRINT\r\n"; thePrinterConn.write(cpcl.getBytes()); } private boolean getPrinterStatus(int retryAttempt) throws Exception { try { printerStatus = printer.getCurrentStatus(); if (printerStatus.isReadyToPrint) { Log.d(LOG_TAG, "Printer is ready to print..."); return true; } else { if (printerStatus.isPaused) { throw new Exception("Printer is paused. Please activate it first."); } else if (printerStatus.isHeadOpen) { throw new Exception("Printer is open. Please close it first."); } else if (printerStatus.isPaperOut) { throw new Exception("Please complete the labels first."); } else { throw new Exception("Could not get the printer status. Please try again. " + "If this problem persists, restart the printer."); } } } catch (ConnectionException e) { if (retryAttempt < MAX_PRINT_RETRIES) { Thread.sleep(5000); return getPrinterStatus(++retryAttempt); } else { throw new Exception("Could not get the printer status. Please try again. " + "If this problem persists, restart the printer."); } } } /** * Gebruik de Zebra Android SDK om de lengte te bepalen indien de printer LINK-OS ondersteunt * * @param zebraimage * @throws Exception */ private void setLabelLength(ZebraImageAndroid zebraimage) throws Exception { ZebraPrinterLinkOs zebraPrinterLinkOs = ZebraPrinterFactory.createLinkOsPrinter(printer); if (zebraPrinterLinkOs != null) { String currentLabelLength = zebraPrinterLinkOs.getSettingValue("zpl.label_length"); Log.d(LOG_TAG, "mitja " + currentLabelLength); if (!currentLabelLength.equals(String.valueOf(zebraimage.getHeight()))) { // printer_diff Log.d(LOG_TAG, "mitja me " + zebraimage.getHeight()); zebraPrinterLinkOs.setSetting("zpl.label_length", zebraimage.getHeight() + ""); } } } private void discoverPrinters() { printerFound = false; new Thread(new Runnable() { public void run() { Looper.prepare(); try { BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter.isEnabled()) { Log.d(LOG_TAG, "Searching for printers..."); BluetoothDiscoverer.findPrinters(cordova.getActivity().getApplicationContext(), ZebraPrint.this); } else { Log.d(LOG_TAG, "Bluetooth is disabled..."); callbackContext.error("Bluetooth is not turned on."); } } catch (ConnectionException e) { Log.e(LOG_TAG, "Connection exception: " + e.getMessage()); callbackContext.error(e.getMessage()); } finally { Looper.myLooper().quit(); } } }).start(); } private void getPrinterName(final String macAddress) { new Thread(new Runnable() { @Override public void run() { String printerName = searchPrinterNameForMacAddress(macAddress); if (printerName != null) { Log.d(LOG_TAG, "Successfully found connected printer with name " + printerName); callbackContext.success(printerName); } else { callbackContext.error("No printer found. If the problem persists, restart the printer."); } } }).start(); } private void sendEcho(final String echoString) { new Thread(new Runnable() { @Override public void run() { callbackContext.success(echoString); } }).start(); } private String searchPrinterNameForMacAddress(String macAddress) { Log.d(LOG_TAG, "Connecting with printer " + macAddress + " over bluetooth..."); BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices(); if (pairedDevices.size() > 0) { // There are paired devices. Get the name and address of each paired device. for (BluetoothDevice device : pairedDevices) { Log.d(LOG_TAG, "Paired device found: " + device.getName()); if (device.getAddress().equalsIgnoreCase(macAddress)) { return device.getName(); } } } return null; } @Override public void foundPrinter(DiscoveredPrinter discoveredPrinter) { Log.d(LOG_TAG, "Printer found: " + discoveredPrinter.address); if (!printerFound) { printerFound = true; callbackContext.success(discoveredPrinter.address); } } @Override public void discoveryFinished() { Log.d(LOG_TAG, "Finished searching for printers..."); if (!printerFound) { callbackContext.error("No printer found. If the problem persists, restart the printer."); } } @Override public void discoveryError(String s) { Log.e(LOG_TAG, "An error occurred while searching for printers. Message: " + s); callbackContext.error(s); } }
ByteDoc/cordova-zebra-print
src/android/at/castana/cordova/plugins/zebraprint/ZebraPrint.java
4,127
//Geen printer gevonden via bluetooth, -1 teruggeven zodat er gezocht wordt naar nieuwe printers.
line_comment
nl
package at.castana.cordova.plugins.zebraprint; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Looper; import android.util.Base64; import android.util.Log; import com.zebra.sdk.comm.BluetoothConnection; import com.zebra.sdk.comm.Connection; import com.zebra.sdk.comm.ConnectionException; import com.zebra.sdk.graphics.internal.ZebraImageAndroid; import com.zebra.sdk.printer.PrinterStatus; import com.zebra.sdk.printer.SGD; import com.zebra.sdk.printer.ZebraPrinter; import com.zebra.sdk.printer.ZebraPrinterFactory; import com.zebra.sdk.printer.ZebraPrinterLanguageUnknownException; import com.zebra.sdk.printer.ZebraPrinterLinkOs; import com.zebra.sdk.printer.discovery.BluetoothDiscoverer; import com.zebra.sdk.printer.discovery.DiscoveredPrinter; import com.zebra.sdk.printer.discovery.DiscoveryHandler; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.json.JSONArray; import org.json.JSONException; import java.io.IOException; import java.util.Set; public class ZebraPrint extends CordovaPlugin implements DiscoveryHandler { private static final String LOG_TAG = "ZebraPrint"; private CallbackContext callbackContext; private boolean printerFound; private Connection thePrinterConn; private PrinterStatus printerStatus; private ZebraPrinter printer; private final int MAX_PRINT_RETRIES = 1; private int speed; private int time; private int number; public ZebraPrint() { } // @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { this.callbackContext = callbackContext; if (action.equals("printImage")) { try { JSONArray labels = args.getJSONArray(0); String MACAddress = args.getString(1); speed = args.getInt(2); time = args.getInt(3); number = args.getInt(4); for (int i = 1; i < number; i++) { labels.put(labels.get(0)); } sendImage(labels, MACAddress); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage()); e.printStackTrace(); } return true; } else if (action.equals("discoverPrinters")) { discoverPrinters(); return true; } else if (action.equals("getPrinterName")) { String MACAddress = args.getString(0); getPrinterName(MACAddress); return true; } else if (action.equals("echo")) { String echoString = args.getString(0); sendEcho(echoString); return true; } return false; } private void sendImage(final JSONArray labels, final String MACAddress) throws IOException { new Thread(new Runnable() { @Override public void run() { printLabels(labels, MACAddress); } }).start(); } private void printLabels(JSONArray labels, String MACAddress) { try { boolean isConnected = openBluetoothConnection(MACAddress); if (isConnected) { initializePrinter(); boolean isPrinterReady = getPrinterStatus(0); if (isPrinterReady) { printLabel(labels); //Voldoende wachten zodat label afgeprint is voordat we een nieuwe printer-operatie starten. // Sufficient waiting for the label to print before we start a new printer operation. //Thread.sleep(15000); //SGD.SET("device.languages", "line_print", thePrinterConn); thePrinterConn.close(); callbackContext.success(); } else { Log.e(LOG_TAG, "Printer not ready"); callbackContext.error("The printer is not ready yet."); } } else { Log.e(LOG_TAG, "Printer not connected"); callbackContext.error("The printer is not connected."); } } catch (ConnectionException e) { Log.e(LOG_TAG, "Connection exception: " + e.getMessage()); //De connectie tussen de printer & het toestel is verloren gegaan. if (e.getMessage().toLowerCase().contains("broken pipe")) { callbackContext.error("The connection between the device and the printer was interrupted. Please try again."); //Geen printer<SUF> } else if (e.getMessage().toLowerCase().contains("socket might closed")) { int SEARCH_NEW_PRINTERS = -1; callbackContext.error(SEARCH_NEW_PRINTERS); } else { callbackContext.error("There was an unknown printer error. Please restart the printer and try again."); } } catch (ZebraPrinterLanguageUnknownException e) { Log.e(LOG_TAG, "ZebraPrinterLanguageUnknown exception: " + e.getMessage()); callbackContext.error("There was an unknown printer error. Please restart the printer and try again."); } catch (Exception e) { Log.e(LOG_TAG, "Exception: " + e.getMessage()); callbackContext.error(e.getMessage()); } } private void initializePrinter() throws ConnectionException, ZebraPrinterLanguageUnknownException { Log.d(LOG_TAG, "Initializing printer..."); printer = ZebraPrinterFactory.getInstance(thePrinterConn); String printerLanguage = SGD.GET("device.languages", thePrinterConn); if (!printerLanguage.contains("zpl")) { // print diff SGD.SET("device.languages", "hybrid_xml_zpl", thePrinterConn); Log.d(LOG_TAG, "printer language set..."); } } private boolean openBluetoothConnection(String MACAddress) throws ConnectionException { BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter.isEnabled()) { Log.d(LOG_TAG, "Creating a bluetooth-connection for mac-address " + MACAddress); thePrinterConn = new BluetoothConnection(MACAddress); Log.d(LOG_TAG, "Opening connection..."); thePrinterConn.open(); Log.d(LOG_TAG, "connection successfully opened..."); return true; } else { Log.d(LOG_TAG, "Bluetooth is disabled..."); callbackContext.error("Bluetooth is not turned on."); } return false; } private void printLabel(JSONArray labels) throws Exception { ZebraPrinterLinkOs zebraPrinterLinkOs = ZebraPrinterFactory.createLinkOsPrinter(printer); for (int i = labels.length() - 1; i >= 0; i--) { String base64Image = labels.get(i).toString(); byte[] decodedString = Base64.decode(base64Image, Base64.DEFAULT); Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); ZebraImageAndroid zebraimage = new ZebraImageAndroid(decodedByte); int labelHeight = Integer.valueOf(zebraimage.getHeight()); int labelSleep = (Integer.valueOf(labelHeight / 400) * 1000) * speed; Log.d(LOG_TAG, "labelHeight: " + Integer.toString(labelHeight)); Log.d(LOG_TAG, "labelSleep: " + Integer.toString(labelSleep)); // Set the length of the label first to prevent too small or too large a print if (zebraPrinterLinkOs != null && i == labels.length() - 1) { setLabelLength(zebraimage); } if (zebraPrinterLinkOs != null) { Log.d(LOG_TAG, "calling printer.printImage"); //printer.printImage(zebraimage, 20, 20, zebraimage.getWidth(), zebraimage.getHeight(), false); printer.printImage(zebraimage, 0, 0, 0, 0, false); } else { Log.d(LOG_TAG, "Storing label on printer..."); printer.storeImage("wgkimage.pcx", zebraimage, -1, -1); printImageTheOldWay(zebraimage); SGD.SET("device.languages", "line_print", thePrinterConn); } Thread.sleep(labelSleep); if (i > 0) { Thread.sleep(1000 * time); } } if (labels.length() == 0) { Log.e(LOG_TAG, "No labels for printing ..."); } } private void printImageTheOldWay(ZebraImageAndroid zebraimage) throws Exception { Log.d(LOG_TAG, "Printing image..."); String cpcl = "! 0 200 200 "; cpcl += zebraimage.getHeight(); cpcl += " 1\r\n"; // print diff cpcl += "PW 750\r\nTONE 0\r\nSPEED 6\r\nSETFF 203 5\r\nON - FEED FEED\r\nAUTO - PACE\r\nJOURNAL\r\n"; //cpcl += "TONE 0\r\nJOURNAL\r\n"; cpcl += "PCX 150 0 !<wgkimage.pcx\r\n"; cpcl += "FORM\r\n"; cpcl += "PRINT\r\n"; thePrinterConn.write(cpcl.getBytes()); } private boolean getPrinterStatus(int retryAttempt) throws Exception { try { printerStatus = printer.getCurrentStatus(); if (printerStatus.isReadyToPrint) { Log.d(LOG_TAG, "Printer is ready to print..."); return true; } else { if (printerStatus.isPaused) { throw new Exception("Printer is paused. Please activate it first."); } else if (printerStatus.isHeadOpen) { throw new Exception("Printer is open. Please close it first."); } else if (printerStatus.isPaperOut) { throw new Exception("Please complete the labels first."); } else { throw new Exception("Could not get the printer status. Please try again. " + "If this problem persists, restart the printer."); } } } catch (ConnectionException e) { if (retryAttempt < MAX_PRINT_RETRIES) { Thread.sleep(5000); return getPrinterStatus(++retryAttempt); } else { throw new Exception("Could not get the printer status. Please try again. " + "If this problem persists, restart the printer."); } } } /** * Gebruik de Zebra Android SDK om de lengte te bepalen indien de printer LINK-OS ondersteunt * * @param zebraimage * @throws Exception */ private void setLabelLength(ZebraImageAndroid zebraimage) throws Exception { ZebraPrinterLinkOs zebraPrinterLinkOs = ZebraPrinterFactory.createLinkOsPrinter(printer); if (zebraPrinterLinkOs != null) { String currentLabelLength = zebraPrinterLinkOs.getSettingValue("zpl.label_length"); Log.d(LOG_TAG, "mitja " + currentLabelLength); if (!currentLabelLength.equals(String.valueOf(zebraimage.getHeight()))) { // printer_diff Log.d(LOG_TAG, "mitja me " + zebraimage.getHeight()); zebraPrinterLinkOs.setSetting("zpl.label_length", zebraimage.getHeight() + ""); } } } private void discoverPrinters() { printerFound = false; new Thread(new Runnable() { public void run() { Looper.prepare(); try { BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter.isEnabled()) { Log.d(LOG_TAG, "Searching for printers..."); BluetoothDiscoverer.findPrinters(cordova.getActivity().getApplicationContext(), ZebraPrint.this); } else { Log.d(LOG_TAG, "Bluetooth is disabled..."); callbackContext.error("Bluetooth is not turned on."); } } catch (ConnectionException e) { Log.e(LOG_TAG, "Connection exception: " + e.getMessage()); callbackContext.error(e.getMessage()); } finally { Looper.myLooper().quit(); } } }).start(); } private void getPrinterName(final String macAddress) { new Thread(new Runnable() { @Override public void run() { String printerName = searchPrinterNameForMacAddress(macAddress); if (printerName != null) { Log.d(LOG_TAG, "Successfully found connected printer with name " + printerName); callbackContext.success(printerName); } else { callbackContext.error("No printer found. If the problem persists, restart the printer."); } } }).start(); } private void sendEcho(final String echoString) { new Thread(new Runnable() { @Override public void run() { callbackContext.success(echoString); } }).start(); } private String searchPrinterNameForMacAddress(String macAddress) { Log.d(LOG_TAG, "Connecting with printer " + macAddress + " over bluetooth..."); BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices(); if (pairedDevices.size() > 0) { // There are paired devices. Get the name and address of each paired device. for (BluetoothDevice device : pairedDevices) { Log.d(LOG_TAG, "Paired device found: " + device.getName()); if (device.getAddress().equalsIgnoreCase(macAddress)) { return device.getName(); } } } return null; } @Override public void foundPrinter(DiscoveredPrinter discoveredPrinter) { Log.d(LOG_TAG, "Printer found: " + discoveredPrinter.address); if (!printerFound) { printerFound = true; callbackContext.success(discoveredPrinter.address); } } @Override public void discoveryFinished() { Log.d(LOG_TAG, "Finished searching for printers..."); if (!printerFound) { callbackContext.error("No printer found. If the problem persists, restart the printer."); } } @Override public void discoveryError(String s) { Log.e(LOG_TAG, "An error occurred while searching for printers. Message: " + s); callbackContext.error(s); } }
24370_1
package works.maatwerk.generals.models; /** * * @author Sam Dirkx */ public class Debuff { private int turns; private final Stats staticDebuff; //wat hetzelfde blijft private final Stats dynamicDebuff; //wat optelt /** * * @param turns turns that this debuff will be active. Negative numbers will mean for the rest of the game. * @param staticDebuff stats that count this turn * @param dynamicDebuff stats that will be added at the end of the turn */ public Debuff(int turns, Stats staticDebuff, Stats dynamicDebuff) { this.turns = turns; if(staticDebuff != null) this.staticDebuff = staticDebuff.cloneStats(); else this.staticDebuff = null; if(dynamicDebuff != null) this.dynamicDebuff = dynamicDebuff.cloneStats(); else this.dynamicDebuff = null; } /** * * @return */ public int getTurns() { return turns; } /** * * @return */ public Stats getStaticDebuff() { return staticDebuff; } /** * * @return */ public Stats getDynamicDebuff() { return dynamicDebuff; } public void update() { if(turns == 0) { return; } if(turns > 0) { turns--; } staticDebuff.addToThis(dynamicDebuff); } /** * * @return */ @Override public String toString() { return "Debuff{" + "turns=" + turns + ", staticDebuff=" + staticDebuff + ", dynamicDebuff=" + dynamicDebuff + '}'; } }
C-Alexander/Client
core/src/works/maatwerk/generals/models/Debuff.java
531
//wat hetzelfde blijft
line_comment
nl
package works.maatwerk.generals.models; /** * * @author Sam Dirkx */ public class Debuff { private int turns; private final Stats staticDebuff; //wat hetzelfde<SUF> private final Stats dynamicDebuff; //wat optelt /** * * @param turns turns that this debuff will be active. Negative numbers will mean for the rest of the game. * @param staticDebuff stats that count this turn * @param dynamicDebuff stats that will be added at the end of the turn */ public Debuff(int turns, Stats staticDebuff, Stats dynamicDebuff) { this.turns = turns; if(staticDebuff != null) this.staticDebuff = staticDebuff.cloneStats(); else this.staticDebuff = null; if(dynamicDebuff != null) this.dynamicDebuff = dynamicDebuff.cloneStats(); else this.dynamicDebuff = null; } /** * * @return */ public int getTurns() { return turns; } /** * * @return */ public Stats getStaticDebuff() { return staticDebuff; } /** * * @return */ public Stats getDynamicDebuff() { return dynamicDebuff; } public void update() { if(turns == 0) { return; } if(turns > 0) { turns--; } staticDebuff.addToThis(dynamicDebuff); } /** * * @return */ @Override public String toString() { return "Debuff{" + "turns=" + turns + ", staticDebuff=" + staticDebuff + ", dynamicDebuff=" + dynamicDebuff + '}'; } }
25498_0
package com.rudi.rest; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.rudi.dao.UserDAO; import com.rudi.entities.User; import jakarta.inject.Inject; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; @Path("/users") public class UserService { @Inject private UserDAO userDAO; public UserService () { this.userDAO = new UserDAO(); } @GET @Path("/test") @Produces(MediaType.TEXT_PLAIN) public String test() { return "Test successful"; } @POST @Path("/adduser") @Consumes(MediaType.APPLICATION_JSON) public void save(String jsonResponse) { userDAO = new UserDAO(); //beetje raar, @Inject werkt niet? Gson gson = new Gson(); User userToSave = gson.fromJson(jsonResponse, User.class); userDAO.saveUser(userToSave); } @POST @Path("/checkpassword") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.TEXT_PLAIN) public String checkPassword(String jsonResponse) { JsonParser parser = new JsonParser(); JsonObject object = (JsonObject) parser.parse(jsonResponse); String username = object.get("username").toString().replace("\"", ""); String password = object.get("password").toString().replace("\"", ""); User user = userDAO.getByUsername(username); return userDAO.checkPassword(user, password) ? "Password correct" : "Password incorrect"; } }
C0pyPasta/RRR
backend/src/main/java/com/rudi/rest/UserService.java
482
//beetje raar, @Inject werkt niet?
line_comment
nl
package com.rudi.rest; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.rudi.dao.UserDAO; import com.rudi.entities.User; import jakarta.inject.Inject; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; @Path("/users") public class UserService { @Inject private UserDAO userDAO; public UserService () { this.userDAO = new UserDAO(); } @GET @Path("/test") @Produces(MediaType.TEXT_PLAIN) public String test() { return "Test successful"; } @POST @Path("/adduser") @Consumes(MediaType.APPLICATION_JSON) public void save(String jsonResponse) { userDAO = new UserDAO(); //beetje raar,<SUF> Gson gson = new Gson(); User userToSave = gson.fromJson(jsonResponse, User.class); userDAO.saveUser(userToSave); } @POST @Path("/checkpassword") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.TEXT_PLAIN) public String checkPassword(String jsonResponse) { JsonParser parser = new JsonParser(); JsonObject object = (JsonObject) parser.parse(jsonResponse); String username = object.get("username").toString().replace("\"", ""); String password = object.get("password").toString().replace("\"", ""); User user = userDAO.getByUsername(username); return userDAO.checkPassword(user, password) ? "Password correct" : "Password incorrect"; } }
91777_4
package database; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * Centraliseert gedeelde database bewerkingen * @author Remi De Boer, Gerke de Boer, Michael Oosterhout */ public abstract class AbstractDAO { protected DBaccess dBaccess; protected PreparedStatement preparedStatement; public AbstractDAO(DBaccess dBaccess) { this.dBaccess = dBaccess; } /** * Maakt een preparedStatement voor de sql string. Een DAO gebruikt dit om de parameters te vullen. * * @param sql, * de SQl query */ protected void setupPreparedStatement(String sql) throws SQLException { preparedStatement = dBaccess.getConnection().prepareStatement(sql); } /** * Voert de preparedStatement uit zonder een ResultSet. Wordt gebruikt voor insert, update en * delete statements. * */ protected void executeManipulateStatement() throws SQLException { preparedStatement.executeUpdate(); } /** * Voert de preparedStatement uit met een ResultSet. Wordt gebruikt voor select statements. * */ protected ResultSet executeSelectStatement() throws SQLException { return preparedStatement.executeQuery(); } /** * Maakt een preparedStatement voor de sql string, die een gegenereerde sleutel terug moet geven. * @param sql, * de SQL query */ protected void setupPreparedStatementWithKey(String sql) throws SQLException { preparedStatement = dBaccess.getConnection().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); } /** * Voert de prepared statement uit en geeft de gegenereerde sleutel terug. * Wordt gebruikt voor een insert in een AutoIncrement tabel */ protected int executeInsertStatementWithKey() throws SQLException { preparedStatement.executeUpdate(); ResultSet resultSet = preparedStatement.getGeneratedKeys(); int gegenereerdeSleutel = 0; while (resultSet.next()) { gegenereerdeSleutel = resultSet.getInt(1); } return gegenereerdeSleutel; } protected void sqlFoutmelding(SQLException sqlException) { System.err.println("SQL Foutmelding: " + sqlException.getMessage()); } }
C10-MIW-G/Meetkunde
src/database/AbstractDAO.java
659
/** * Maakt een preparedStatement voor de sql string, die een gegenereerde sleutel terug moet geven. * @param sql, * de SQL query */
block_comment
nl
package database; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * Centraliseert gedeelde database bewerkingen * @author Remi De Boer, Gerke de Boer, Michael Oosterhout */ public abstract class AbstractDAO { protected DBaccess dBaccess; protected PreparedStatement preparedStatement; public AbstractDAO(DBaccess dBaccess) { this.dBaccess = dBaccess; } /** * Maakt een preparedStatement voor de sql string. Een DAO gebruikt dit om de parameters te vullen. * * @param sql, * de SQl query */ protected void setupPreparedStatement(String sql) throws SQLException { preparedStatement = dBaccess.getConnection().prepareStatement(sql); } /** * Voert de preparedStatement uit zonder een ResultSet. Wordt gebruikt voor insert, update en * delete statements. * */ protected void executeManipulateStatement() throws SQLException { preparedStatement.executeUpdate(); } /** * Voert de preparedStatement uit met een ResultSet. Wordt gebruikt voor select statements. * */ protected ResultSet executeSelectStatement() throws SQLException { return preparedStatement.executeQuery(); } /** * Maakt een preparedStatement<SUF>*/ protected void setupPreparedStatementWithKey(String sql) throws SQLException { preparedStatement = dBaccess.getConnection().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); } /** * Voert de prepared statement uit en geeft de gegenereerde sleutel terug. * Wordt gebruikt voor een insert in een AutoIncrement tabel */ protected int executeInsertStatementWithKey() throws SQLException { preparedStatement.executeUpdate(); ResultSet resultSet = preparedStatement.getGeneratedKeys(); int gegenereerdeSleutel = 0; while (resultSet.next()) { gegenereerdeSleutel = resultSet.getInt(1); } return gegenereerdeSleutel; } protected void sqlFoutmelding(SQLException sqlException) { System.err.println("SQL Foutmelding: " + sqlException.getMessage()); } }
112231_0
package nl.miwgroningen.ch10.vincent.libraryDemo.controller; import nl.miwgroningen.ch10.vincent.libraryDemo.model.Book; import nl.miwgroningen.ch10.vincent.libraryDemo.repository.AuthorRepository; import nl.miwgroningen.ch10.vincent.libraryDemo.repository.BookRepository; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import java.util.Optional; /** * @author Vincent Velthuizen <v.r.velthuizen@pl.hanze.nl> * <p> * Geeft toegang tot alle pagina's over boeken */ @Controller public class BookController { private final AuthorRepository authorRepository; private final BookRepository bookRepository; public BookController(AuthorRepository authorRepository, BookRepository bookRepository) { this.authorRepository = authorRepository; this.bookRepository = bookRepository; } @GetMapping({"/books/all", "/"}) protected String showBookOverview(Model model) { model.addAttribute("allBooks", bookRepository.findAll()); return "bookOverview"; } @GetMapping("/books/details/id/{bookId}") protected String showBookDetails(@PathVariable("bookId") Long bookId, Model model) { Optional<Book> book = bookRepository.findById(bookId); if (book.isPresent()) { return showDetailsForBook(model, book); } return "redirect:/books/all"; } private static String showDetailsForBook(Model model, Optional<Book> book) { model.addAttribute("bookToShowDetailsFor", book.get()); return "bookDetails"; } @GetMapping("/books/details/{title}") protected String showBookDetails(@PathVariable("title") String title, Model model) { Optional<Book> book = bookRepository.findByTitle(title); if (book.isPresent()) { return showDetailsForBook(model, book); } return "redirect:/books/all"; } @GetMapping("/books/new") protected String showNewBookForm(Model model) { return showBookFormForBook(model, new Book()); } @GetMapping("/books/edit/{bookId}") protected String showEditBookForm(@PathVariable("bookId") Long bookId, Model model) { Optional<Book> book = bookRepository.findById(bookId); if (book.isPresent()) { return showBookFormForBook(model, book.get()); } return "redirect:/books/all"; } private String showBookFormForBook(Model model, Book book) { model.addAttribute("book", book); model.addAttribute("allAuthors", authorRepository.findAll()); return "bookForm"; } @PostMapping("/books/new") protected String saveBook(@ModelAttribute("book") Book bookToBeSaved, BindingResult result) { if (!result.hasErrors()) { bookRepository.save(bookToBeSaved); } return "redirect:/books/all"; } @GetMapping("/books/delete/{bookId}") protected String deleteBook(@PathVariable("bookId") Long bookId) { Optional<Book> book = bookRepository.findById(bookId); if (book.isPresent()) { bookRepository.delete(book.get()); } return "redirect:/books/all"; } }
C10-MIW-G/libraryDemo
src/main/java/nl/miwgroningen/ch10/vincent/libraryDemo/controller/BookController.java
957
/** * @author Vincent Velthuizen <v.r.velthuizen@pl.hanze.nl> * <p> * Geeft toegang tot alle pagina's over boeken */
block_comment
nl
package nl.miwgroningen.ch10.vincent.libraryDemo.controller; import nl.miwgroningen.ch10.vincent.libraryDemo.model.Book; import nl.miwgroningen.ch10.vincent.libraryDemo.repository.AuthorRepository; import nl.miwgroningen.ch10.vincent.libraryDemo.repository.BookRepository; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import java.util.Optional; /** * @author Vincent Velthuizen<SUF>*/ @Controller public class BookController { private final AuthorRepository authorRepository; private final BookRepository bookRepository; public BookController(AuthorRepository authorRepository, BookRepository bookRepository) { this.authorRepository = authorRepository; this.bookRepository = bookRepository; } @GetMapping({"/books/all", "/"}) protected String showBookOverview(Model model) { model.addAttribute("allBooks", bookRepository.findAll()); return "bookOverview"; } @GetMapping("/books/details/id/{bookId}") protected String showBookDetails(@PathVariable("bookId") Long bookId, Model model) { Optional<Book> book = bookRepository.findById(bookId); if (book.isPresent()) { return showDetailsForBook(model, book); } return "redirect:/books/all"; } private static String showDetailsForBook(Model model, Optional<Book> book) { model.addAttribute("bookToShowDetailsFor", book.get()); return "bookDetails"; } @GetMapping("/books/details/{title}") protected String showBookDetails(@PathVariable("title") String title, Model model) { Optional<Book> book = bookRepository.findByTitle(title); if (book.isPresent()) { return showDetailsForBook(model, book); } return "redirect:/books/all"; } @GetMapping("/books/new") protected String showNewBookForm(Model model) { return showBookFormForBook(model, new Book()); } @GetMapping("/books/edit/{bookId}") protected String showEditBookForm(@PathVariable("bookId") Long bookId, Model model) { Optional<Book> book = bookRepository.findById(bookId); if (book.isPresent()) { return showBookFormForBook(model, book.get()); } return "redirect:/books/all"; } private String showBookFormForBook(Model model, Book book) { model.addAttribute("book", book); model.addAttribute("allAuthors", authorRepository.findAll()); return "bookForm"; } @PostMapping("/books/new") protected String saveBook(@ModelAttribute("book") Book bookToBeSaved, BindingResult result) { if (!result.hasErrors()) { bookRepository.save(bookToBeSaved); } return "redirect:/books/all"; } @GetMapping("/books/delete/{bookId}") protected String deleteBook(@PathVariable("bookId") Long bookId) { Optional<Book> book = bookRepository.findById(bookId); if (book.isPresent()) { bookRepository.delete(book.get()); } return "redirect:/books/all"; } }
44897_0
package model; /** * @author Vincent Velthuizen <v.r.velthuizen@pl.hanze.nl> * Eigenschappen van die personen die in vaste dienst zijn bij mijn bedrijf */ public class Werknemer extends Persoon { private static final double GRENSWAARDE_BONUS = 4500; private static final double DEFAULT_MAAND_SALARIS = 0.0; private static final int MAANDEN_PER_JAAR = 12; private double maandSalaris; public Werknemer(String naam, String woonplaats, Afdeling afdeling, double maandSalaris) { super(naam, woonplaats, afdeling); setMaandsalaris(maandSalaris); } public Werknemer(String naam) { super(naam); setMaandsalaris(DEFAULT_MAAND_SALARIS); } public Werknemer() { super(); setMaandsalaris(DEFAULT_MAAND_SALARIS); } public boolean heeftRechtOpBonus() { return maandSalaris >= GRENSWAARDE_BONUS; } @Override public double berekenJaarinkomen() { double jaarinkomen = MAANDEN_PER_JAAR * maandSalaris; if (heeftRechtOpBonus()) { jaarinkomen += maandSalaris; } return jaarinkomen; } @Override public String toString() { return String.format("%s en is een werknemer %s recht op bonus", super.toString(), heeftRechtOpBonus() ? "met" : "zonder"); } public double getMaandSalaris() { return maandSalaris; } private void setMaandsalaris(double maandSalaris) { if (maandSalaris < 0) { throw new IllegalArgumentException("Het maandsalaris mag niet negatief zijn."); } this.maandSalaris = maandSalaris; } }
C12-MIWNN/Bedrijf
src/model/Werknemer.java
530
/** * @author Vincent Velthuizen <v.r.velthuizen@pl.hanze.nl> * Eigenschappen van die personen die in vaste dienst zijn bij mijn bedrijf */
block_comment
nl
package model; /** * @author Vincent Velthuizen<SUF>*/ public class Werknemer extends Persoon { private static final double GRENSWAARDE_BONUS = 4500; private static final double DEFAULT_MAAND_SALARIS = 0.0; private static final int MAANDEN_PER_JAAR = 12; private double maandSalaris; public Werknemer(String naam, String woonplaats, Afdeling afdeling, double maandSalaris) { super(naam, woonplaats, afdeling); setMaandsalaris(maandSalaris); } public Werknemer(String naam) { super(naam); setMaandsalaris(DEFAULT_MAAND_SALARIS); } public Werknemer() { super(); setMaandsalaris(DEFAULT_MAAND_SALARIS); } public boolean heeftRechtOpBonus() { return maandSalaris >= GRENSWAARDE_BONUS; } @Override public double berekenJaarinkomen() { double jaarinkomen = MAANDEN_PER_JAAR * maandSalaris; if (heeftRechtOpBonus()) { jaarinkomen += maandSalaris; } return jaarinkomen; } @Override public String toString() { return String.format("%s en is een werknemer %s recht op bonus", super.toString(), heeftRechtOpBonus() ? "met" : "zonder"); } public double getMaandSalaris() { return maandSalaris; } private void setMaandsalaris(double maandSalaris) { if (maandSalaris < 0) { throw new IllegalArgumentException("Het maandsalaris mag niet negatief zijn."); } this.maandSalaris = maandSalaris; } }
205497_1
package nl.miwnn.se13.equipaprimavera.ReceitaDePrimavera; import nl.miwnn.se13.equipaprimavera.ReceitaDePrimavera.model.Recipe; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import java.awt.*; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; /** * @author Mirjam Schmitz * <p> * Test **/ class ExampleTest { @Test void shouldShowSimpleAssertion() { assertEquals(1,1); } // @Test // kan je testen of het aantal en/of de namen van de toegevoegde recipes in een recipebook kloppen? // // @DisplayName("Should check all items in the list") // void shouldCheckAllRecipesInTheRecipeBook() { // List<Recipe> recipeList = List.of(re, , 5, 7); // // Assertions.assertAll(() -> assertEquals(2, recipeList.get(0)), // () -> assertEquals(, recipeList.get(1)), // () -> assertEquals(, recipeList.get(2)), // () -> assertEquals(, recipeList.get(3))); // } }
C13-MIWNN/Project1_Equipa_primavera
src/test/java/nl/miwnn/se13/equipaprimavera/ReceitaDePrimavera/ExampleTest.java
412
// @Test // kan je testen of het aantal en/of de namen van de toegevoegde recipes in een recipebook kloppen?
line_comment
nl
package nl.miwnn.se13.equipaprimavera.ReceitaDePrimavera; import nl.miwnn.se13.equipaprimavera.ReceitaDePrimavera.model.Recipe; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import java.awt.*; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; /** * @author Mirjam Schmitz * <p> * Test **/ class ExampleTest { @Test void shouldShowSimpleAssertion() { assertEquals(1,1); } // @Test //<SUF> // // @DisplayName("Should check all items in the list") // void shouldCheckAllRecipesInTheRecipeBook() { // List<Recipe> recipeList = List.of(re, , 5, 7); // // Assertions.assertAll(() -> assertEquals(2, recipeList.get(0)), // () -> assertEquals(, recipeList.get(1)), // () -> assertEquals(, recipeList.get(2)), // () -> assertEquals(, recipeList.get(3))); // } }
32424_2
package com.softCare.Linc.seeder; import com.softCare.Linc.model.Circle; import com.softCare.Linc.model.CircleMember; import com.softCare.Linc.model.Task; import com.softCare.Linc.model.User; import com.softCare.Linc.service.CircleMemberServiceInterface; import com.softCare.Linc.service.CircleServiceInterface; import com.softCare.Linc.service.LincUserDetailServiceInterface; import com.softCare.Linc.service.TaskServiceInterface; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.event.EventListener; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import org.thymeleaf.standard.inline.StandardInlineMode; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Files; import java.time.LocalDate; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Optional; @Component public class Seeder { private final CircleServiceInterface circleServiceInterface; private final TaskServiceInterface taskServiceInterface; private final LincUserDetailServiceInterface lincUserDetailServiceInterface; private final CircleMemberServiceInterface circleMemberServiceInterface; final PasswordEncoder passwordEncoder; private List<Object> circles; public Seeder(CircleServiceInterface circleServiceInterface, TaskServiceInterface taskServiceInterface, LincUserDetailServiceInterface lincUserDetailServiceInterface, CircleMemberServiceInterface circleMemberServiceInterface, PasswordEncoder passwordEncoder) { this.circleServiceInterface = circleServiceInterface; this.taskServiceInterface = taskServiceInterface; this.lincUserDetailServiceInterface = lincUserDetailServiceInterface; this.circleMemberServiceInterface = circleMemberServiceInterface; this.passwordEncoder = passwordEncoder; } @EventListener public void seed(ContextRefreshedEvent contextRefreshedEvent) { circles = new ArrayList<>(); circles.addAll((Collection<?>) circleServiceInterface.findAll()); if (circles.size() == 0) { seedCircles(); } if (lincUserDetailServiceInterface.findByUsername("sysAdmin").isEmpty()) { seedUsers(); } } private void seedUsers() { // seed user "admin" User admin = new User("sysAdmin",passwordEncoder.encode("admin"),"admin@linc.nl", "0613371337"); lincUserDetailServiceInterface.save(admin); //seed permissions for the admin List<Circle> allCircles = new ArrayList<>(); allCircles.addAll((Collection<? extends Circle>) circleServiceInterface.findAll()); for (Circle allCircle : allCircles) { circleMemberServiceInterface.save(new CircleMember(admin,allCircle,true,true)); } } public void seedCircles() { Circle oomDiederik = new Circle("Fam. Janssen"); Circle tanteGeertruida = new Circle("Tante Geertruida's Circle"); Circle zorgHaantje = new Circle("Zorgboerderij 't Vliegende Schaapje"); Circle omaJantina = new Circle("Fam. Jonker"); Circle woongroep = new Circle("Woongroep Middenmeer"); Circle studentenGroep = new Circle("Thuiszorg Studenten"); circleServiceInterface.save(oomDiederik); circleServiceInterface.save(tanteGeertruida); circleServiceInterface.save(zorgHaantje); circleServiceInterface.save(omaJantina); circleServiceInterface.save(woongroep); circleServiceInterface.save(studentenGroep); User diederik = new User("Diederik", passwordEncoder.encode("diederik"), "diederik@diederik.nl", "0099009900"); User hendrik = new User("Hendrik", passwordEncoder.encode("hendrik"), "hendrik@hendrik.nl", "0099009900"); User geertruida = new User("Geertruida", passwordEncoder.encode("geertruida"), "geertruida@geertruida.nl", "0099009900"); User jantina = new User("Jantina", passwordEncoder.encode("jantina"), "jantina@jantina.nl", "0099009900"); User baas = new User("M.Veen", passwordEncoder.encode("mveen"), "mveen@mveen.nl", "0099009900"); User tess = new User("Tesss", passwordEncoder.encode("tess"), "tess@ziggo.nl", "0653976031"); // studenten groep User Mark = new User("Mark", passwordEncoder.encode("mark"), "mark@mark.nl", "0664852145"); User Timo = new User("Timo", passwordEncoder.encode("timo"), "timo@timo.nl", "0658963214"); User Madelein = new User("Madelein", passwordEncoder.encode("madelein"), "madelein@madelein.nl", "0647859631"); User Roos = new User("Roos", passwordEncoder.encode("roos"), "roos@roos.nl", "0652149325"); User Henry = new User("Henry", passwordEncoder.encode("henry"), "henry@henry.nl", "0621459874"); User Thomas = new User("Thomas", passwordEncoder.encode("thomas"), "thomas@thomas.nl", "0635841256"); User Froukje = new User("Froukje", passwordEncoder.encode("froukje"), "froukje@froukje.nl", "062345420"); User Betty = new User("Betty", passwordEncoder.encode("betty"), "betty@betty.nl", "066548515"); User Berend = new User("Berend", passwordEncoder.encode("berend"), "berend@berend.nl", "0365453564"); lincUserDetailServiceInterface.save(Mark); lincUserDetailServiceInterface.save(Timo); lincUserDetailServiceInterface.save(Madelein); lincUserDetailServiceInterface.save(Roos); lincUserDetailServiceInterface.save(Henry); lincUserDetailServiceInterface.save(Thomas); lincUserDetailServiceInterface.save(Froukje); lincUserDetailServiceInterface.save(Betty); lincUserDetailServiceInterface.save(Berend); lincUserDetailServiceInterface.save(tess); CircleMember circleMemberMark = new CircleMember(Mark, studentenGroep, false, true); CircleMember circleMemberTimo = new CircleMember(Timo, studentenGroep, false, false); CircleMember circleMemberMadelein = new CircleMember(Madelein, studentenGroep, false, false); CircleMember circleMemberRoos = new CircleMember(Roos, studentenGroep, false, false); CircleMember circleMemberHenry = new CircleMember(Henry, studentenGroep, false, false); CircleMember circleMemberThomas = new CircleMember(Thomas, studentenGroep, false, false); CircleMember circleMemberFroukje = new CircleMember(Froukje, studentenGroep, false, false); CircleMember circleMemberBetty = new CircleMember(Betty, studentenGroep, true, false); CircleMember circleMemberBerend = new CircleMember(Berend, studentenGroep, true, false); circleMemberServiceInterface.save(circleMemberMark); circleMemberServiceInterface.save(circleMemberTimo); circleMemberServiceInterface.save(circleMemberMadelein); circleMemberServiceInterface.save(circleMemberRoos); circleMemberServiceInterface.save(circleMemberHenry); circleMemberServiceInterface.save(circleMemberThomas); circleMemberServiceInterface.save(circleMemberFroukje); circleMemberServiceInterface.save(circleMemberBetty); circleMemberServiceInterface.save(circleMemberBerend); lincUserDetailServiceInterface.save(diederik); lincUserDetailServiceInterface.save(hendrik); lincUserDetailServiceInterface.save(geertruida); lincUserDetailServiceInterface.save(jantina); lincUserDetailServiceInterface.save(baas); CircleMember circleMemberDiederik = new CircleMember(diederik, oomDiederik, true, true); // CircleMember circleMemberHendrik = new CircleMember(hendrik, oomDiederik, false, false); CircleMember circleMemberGeertruida = new CircleMember(geertruida, tanteGeertruida, true, true); CircleMember circleMemberJantina = new CircleMember(jantina, omaJantina, true, false); CircleMember circleMemberBaas = new CircleMember(baas, woongroep, true, true); CircleMember circleMemberTess = new CircleMember(tess, omaJantina, false, true); circleMemberServiceInterface.save(circleMemberDiederik); // circleMemberServiceInterface.save(circleMemberHendrik); circleMemberServiceInterface.save(circleMemberGeertruida); circleMemberServiceInterface.save(circleMemberJantina); circleMemberServiceInterface.save(circleMemberBaas); circleMemberServiceInterface.save(circleMemberTess); LocalDate date1 = LocalDate.of(2022, 8, 11); LocalDate date2 = LocalDate.of(2022, 8, 7); LocalDate date3 = LocalDate.of(2022, 8, 4); LocalDate date4 = LocalDate.of(2022, 8, 30); LocalDate date5 = LocalDate.of(2022, 8, 16); LocalDate date6 = LocalDate.of(2022, 8, 27); LocalDate date7 = LocalDate.of(2022, 9, 2); LocalDate date8 = LocalDate.of(2022, 9, 14); LocalDate date9 = LocalDate.of(2022, 8, 3); LocalDate date10 = LocalDate.now().plusDays(2); LocalDate date11 = LocalDate.of(2022, 8, 9); String outdoor = "Outdoor"; String indoor = "Indoor"; String trips = "Transport"; String games = "Company"; Task task = new Task("Hulp bij zolder opruimen", "Oude foto albums wel bewaren graag!", false, date1, circleServiceInterface.findByCircleName("Fam. Janssen"), "Fam. Janssen", hendrik, hendrik.getUsername(), 90, diederik, indoor); taskServiceInterface.save(task); Circle studentenCircle = circleServiceInterface.findByCircleName("Thuiszorg Studenten"); taskServiceInterface.save(new Task("Boodschappen doen", "Boter kaas en eieren", false, date10, studentenCircle, "Thuiszorg Studenten", Berend, Madelein.getUsername(), 30, Berend, trips)); taskServiceInterface.save(new Task("Naar de apotheek", "Ze hebben gisteren gebeld, het recept is aangevuld", false, date1, studentenCircle, "Thuiszorg Studenten", Thomas, Thomas.getUsername(), 15, Timo, trips)); taskServiceInterface.save(new Task("Muffins bakken", "Betty wil graag iets bakken, ingredienten zijn al in huis", false, date3, studentenCircle, "Thuiszorg Studenten", Timo, Timo.getUsername(), 75, Timo, indoor)); taskServiceInterface.save(new Task("Vogelhuisje ophangen", "Op een rustige plek, niet pal in de zon.", false, date10, studentenCircle, "Thuiszorg Studenten", null, null, 120, Timo, outdoor)); taskServiceInterface.save(new Task("Berend moet naar de kapper", "Zelf nog even een afspraak maken", false, date6, studentenCircle, "Thuiszorg Studenten", Madelein, Madelein.getUsername(), 30, Timo, trips)); taskServiceInterface.save(new Task("Gezamelijk Formule 1 kijken", "Go Max!", false, date7, studentenCircle, "Thuiszorg Studenten", Thomas, Thomas.getUsername(), 150, Timo, games)); taskServiceInterface.save(new Task("Onkruid wieden", "Graag geen bestrijdingsmiddelen gebruiken", false, date8, studentenCircle, "Thuiszorg Studenten", null, null, 20, Timo, outdoor)); taskServiceInterface.save(new Task("Conifeer snoeien", "De buren begonnen weer te klagen over over te weinig zon", false, date4, studentenCircle, "Thuiszorg Studenten", null, null, 15, Timo, outdoor)); taskServiceInterface.save(new Task("Gras maaien", "-", false, date3, studentenCircle, "Thuiszorg Studenten", null, null, 15, Timo, outdoor)); taskServiceInterface.save(new Task("Betty helpen met DigiD aanvragen", "-", true, date8, studentenCircle, "Thuiszorg Studenten", Roos, Roos.getUsername(), 45, Timo, indoor)); taskServiceInterface.save(new Task("Kopje thee drinken", "-", true, date8, studentenCircle, "Thuiszorg Studenten", Henry, Henry.getUsername(), 15, Timo, games)); taskServiceInterface.save(new Task("Ramen lappen", "Van binnen én buiten graag", false, date7, studentenCircle, "Thuiszorg Studenten", null, null, 65, Timo, indoor)); taskServiceInterface.save(new Task("Rummikub spelen", "Berend wel laten winnen!", false, date2, studentenCircle, "Thuiszorg Studenten", null, null, 45, Timo, games)); taskServiceInterface.save(new Task("Uitje dierentuin", "", true, date2, studentenCircle, "Thuiszorg Studenten", Thomas, Thomas.getUsername(), 240, Timo, trips)); taskServiceInterface.save(new Task( "Boodschappen doen", "Havermout, melk, boter", false, circleServiceInterface.findByCircleName("Fam. Janssen"), "Fam. Janssen", date8, 30, diederik, trips)); taskServiceInterface.save(new Task( "Gras maaien", "Niet te kort AUB", false, circleServiceInterface.findByCircleName("Fam. Janssen"), "Fam. Janssen", date6, 72, hendrik, outdoor)); taskServiceInterface.save(new Task( "Naar de kapper", "Komende woensdagmiddag", false, circleServiceInterface.findByCircleName("Fam. Janssen"), "Fam. Janssen", date5, 120, diederik, trips)); taskServiceInterface.save(new Task( "Ramen wassen", "-", false, circleServiceInterface.findByCircleName("Tante Geertruida's Circle"), "Tante Geertruida", date4, 45, geertruida, indoor)); taskServiceInterface.save(new Task( "Auto APK", "Komende donderdagochtend 8 uur", false, circleServiceInterface.findByCircleName("Tante Geertruida's Circle"), "Tante Geertruida", date1, 120, geertruida, trips)); taskServiceInterface.save(new Task( "Schuur opruimen", "-", false, circleServiceInterface.findByCircleName("Tante Geertruida's Circle"), "Tante Geertruida", date6, 180, geertruida, outdoor)); taskServiceInterface.save(new Task( "Grijze container bij de weg zetten", "Komende maandagochtend voor 8 uur", false, circleServiceInterface.findByCircleName("Zorgboerderij 't Vliegende Schaapje"), "Zorgboerderij 't Haantje", date10, 2, baas, indoor)); taskServiceInterface.save(new Task( "Schutting repareren", "-", false, circleServiceInterface.findByCircleName("Zorgboerderij 't Vliegende Schaapje"), "Zorgboerderij 't Haantje", date8, 540, baas, outdoor)); taskServiceInterface.save(new Task( "Rummikub spelen", "Idealiter in het weekend", false, circleServiceInterface.findByCircleName("Zorgboerderij 't Vliegende Schaapje"), "Zorgboerderij 't Haantje", date3, 90, baas, games)); taskServiceInterface.save(new Task( "Medicijnen ophalen bij de apotheek", "Herhaalmedicatie, ligt klaar na 10:00", false, circleServiceInterface.findByCircleName("Fam. Jonker"), "Fam. Jonker", date11, 60, jantina, trips)); taskServiceInterface.save(new Task( "Gras maaien", "Achter en voor huis", false, circleServiceInterface.findByCircleName("Fam. Jonker"), "Fam. Jonker", date3, 25, jantina, outdoor)); taskServiceInterface.save(new Task( "TV repareren", "Zenders zitten niet meer op de goede plek. Jantina wil in ieder geval NPO 1, 2, en 3 weer zo snel mogelijk kijken.", false, circleServiceInterface.findByCircleName("Fam. Jonker"), "Fam. Jonker", date9, 5, jantina, indoor)); taskServiceInterface.save(new Task( "Boodschappen doen", "Havermout, melk, boter", false, circleServiceInterface.findByCircleName("Woongroep Middenmeer"), "Woongroep Middenmeer", date5, 45, baas, trips)); taskServiceInterface.save(new Task( "Vissen voeren", "2 theelepels", false, circleServiceInterface.findByCircleName("Woongroep Middenmeer"), "Woongroep Middenmeer", date5, 2, baas, indoor)); taskServiceInterface.save(new Task( "Visvoer bestellen", "Voor komend weekend in huis graag", false, circleServiceInterface.findByCircleName("Woongroep Middenmeer"), "Woongroep Middenmeer", date7, 5, baas, indoor)); // profile images File BerendFile = new File("src/main/resources/static/static/images/UserImages/Berend.png"); byte[] BerendPic = new byte[0]; try { BerendPic = FileUtils.readFileToByteArray(BerendFile); } catch (IOException e) { throw new RuntimeException(e); } Berend.setProfilePicture(BerendPic); lincUserDetailServiceInterface.save(Berend); File HenryFile = new File("src/main/resources/static/static/images/UserImages/Henry.png"); byte[] HenryPic = new byte[0]; try { HenryPic = FileUtils.readFileToByteArray(HenryFile); } catch (IOException e) { throw new RuntimeException(e); } Henry.setProfilePicture(HenryPic); lincUserDetailServiceInterface.save(Henry); File RoosFile = new File("src/main/resources/static/static/images/UserImages/Roos.png"); byte[] RoosPic = new byte[0]; try { RoosPic = FileUtils.readFileToByteArray(RoosFile); } catch (IOException e) { throw new RuntimeException(e); } Roos.setProfilePicture(RoosPic); lincUserDetailServiceInterface.save(Roos); File MarkFile = new File("src/main/resources/static/static/images/UserImages/Mark.png"); byte[] MarkPic = new byte[0]; try { MarkPic = FileUtils.readFileToByteArray(MarkFile); } catch (IOException e) { throw new RuntimeException(e); } Mark.setProfilePicture(MarkPic); lincUserDetailServiceInterface.save(Mark); File MadeleinFile = new File("src/main/resources/static/static/images/UserImages/Madelein.png"); byte[] MadeleinPic = new byte[0]; try { MadeleinPic = FileUtils.readFileToByteArray(MadeleinFile); } catch (IOException e) { throw new RuntimeException(e); } Madelein.setProfilePicture(MadeleinPic); lincUserDetailServiceInterface.save(Madelein); } }
C8-MIW-G/Linc
src/main/java/com/softCare/Linc/seeder/Seeder.java
5,727
// CircleMember circleMemberHendrik = new CircleMember(hendrik, oomDiederik, false, false);
line_comment
nl
package com.softCare.Linc.seeder; import com.softCare.Linc.model.Circle; import com.softCare.Linc.model.CircleMember; import com.softCare.Linc.model.Task; import com.softCare.Linc.model.User; import com.softCare.Linc.service.CircleMemberServiceInterface; import com.softCare.Linc.service.CircleServiceInterface; import com.softCare.Linc.service.LincUserDetailServiceInterface; import com.softCare.Linc.service.TaskServiceInterface; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.event.EventListener; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import org.thymeleaf.standard.inline.StandardInlineMode; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Files; import java.time.LocalDate; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Optional; @Component public class Seeder { private final CircleServiceInterface circleServiceInterface; private final TaskServiceInterface taskServiceInterface; private final LincUserDetailServiceInterface lincUserDetailServiceInterface; private final CircleMemberServiceInterface circleMemberServiceInterface; final PasswordEncoder passwordEncoder; private List<Object> circles; public Seeder(CircleServiceInterface circleServiceInterface, TaskServiceInterface taskServiceInterface, LincUserDetailServiceInterface lincUserDetailServiceInterface, CircleMemberServiceInterface circleMemberServiceInterface, PasswordEncoder passwordEncoder) { this.circleServiceInterface = circleServiceInterface; this.taskServiceInterface = taskServiceInterface; this.lincUserDetailServiceInterface = lincUserDetailServiceInterface; this.circleMemberServiceInterface = circleMemberServiceInterface; this.passwordEncoder = passwordEncoder; } @EventListener public void seed(ContextRefreshedEvent contextRefreshedEvent) { circles = new ArrayList<>(); circles.addAll((Collection<?>) circleServiceInterface.findAll()); if (circles.size() == 0) { seedCircles(); } if (lincUserDetailServiceInterface.findByUsername("sysAdmin").isEmpty()) { seedUsers(); } } private void seedUsers() { // seed user "admin" User admin = new User("sysAdmin",passwordEncoder.encode("admin"),"admin@linc.nl", "0613371337"); lincUserDetailServiceInterface.save(admin); //seed permissions for the admin List<Circle> allCircles = new ArrayList<>(); allCircles.addAll((Collection<? extends Circle>) circleServiceInterface.findAll()); for (Circle allCircle : allCircles) { circleMemberServiceInterface.save(new CircleMember(admin,allCircle,true,true)); } } public void seedCircles() { Circle oomDiederik = new Circle("Fam. Janssen"); Circle tanteGeertruida = new Circle("Tante Geertruida's Circle"); Circle zorgHaantje = new Circle("Zorgboerderij 't Vliegende Schaapje"); Circle omaJantina = new Circle("Fam. Jonker"); Circle woongroep = new Circle("Woongroep Middenmeer"); Circle studentenGroep = new Circle("Thuiszorg Studenten"); circleServiceInterface.save(oomDiederik); circleServiceInterface.save(tanteGeertruida); circleServiceInterface.save(zorgHaantje); circleServiceInterface.save(omaJantina); circleServiceInterface.save(woongroep); circleServiceInterface.save(studentenGroep); User diederik = new User("Diederik", passwordEncoder.encode("diederik"), "diederik@diederik.nl", "0099009900"); User hendrik = new User("Hendrik", passwordEncoder.encode("hendrik"), "hendrik@hendrik.nl", "0099009900"); User geertruida = new User("Geertruida", passwordEncoder.encode("geertruida"), "geertruida@geertruida.nl", "0099009900"); User jantina = new User("Jantina", passwordEncoder.encode("jantina"), "jantina@jantina.nl", "0099009900"); User baas = new User("M.Veen", passwordEncoder.encode("mveen"), "mveen@mveen.nl", "0099009900"); User tess = new User("Tesss", passwordEncoder.encode("tess"), "tess@ziggo.nl", "0653976031"); // studenten groep User Mark = new User("Mark", passwordEncoder.encode("mark"), "mark@mark.nl", "0664852145"); User Timo = new User("Timo", passwordEncoder.encode("timo"), "timo@timo.nl", "0658963214"); User Madelein = new User("Madelein", passwordEncoder.encode("madelein"), "madelein@madelein.nl", "0647859631"); User Roos = new User("Roos", passwordEncoder.encode("roos"), "roos@roos.nl", "0652149325"); User Henry = new User("Henry", passwordEncoder.encode("henry"), "henry@henry.nl", "0621459874"); User Thomas = new User("Thomas", passwordEncoder.encode("thomas"), "thomas@thomas.nl", "0635841256"); User Froukje = new User("Froukje", passwordEncoder.encode("froukje"), "froukje@froukje.nl", "062345420"); User Betty = new User("Betty", passwordEncoder.encode("betty"), "betty@betty.nl", "066548515"); User Berend = new User("Berend", passwordEncoder.encode("berend"), "berend@berend.nl", "0365453564"); lincUserDetailServiceInterface.save(Mark); lincUserDetailServiceInterface.save(Timo); lincUserDetailServiceInterface.save(Madelein); lincUserDetailServiceInterface.save(Roos); lincUserDetailServiceInterface.save(Henry); lincUserDetailServiceInterface.save(Thomas); lincUserDetailServiceInterface.save(Froukje); lincUserDetailServiceInterface.save(Betty); lincUserDetailServiceInterface.save(Berend); lincUserDetailServiceInterface.save(tess); CircleMember circleMemberMark = new CircleMember(Mark, studentenGroep, false, true); CircleMember circleMemberTimo = new CircleMember(Timo, studentenGroep, false, false); CircleMember circleMemberMadelein = new CircleMember(Madelein, studentenGroep, false, false); CircleMember circleMemberRoos = new CircleMember(Roos, studentenGroep, false, false); CircleMember circleMemberHenry = new CircleMember(Henry, studentenGroep, false, false); CircleMember circleMemberThomas = new CircleMember(Thomas, studentenGroep, false, false); CircleMember circleMemberFroukje = new CircleMember(Froukje, studentenGroep, false, false); CircleMember circleMemberBetty = new CircleMember(Betty, studentenGroep, true, false); CircleMember circleMemberBerend = new CircleMember(Berend, studentenGroep, true, false); circleMemberServiceInterface.save(circleMemberMark); circleMemberServiceInterface.save(circleMemberTimo); circleMemberServiceInterface.save(circleMemberMadelein); circleMemberServiceInterface.save(circleMemberRoos); circleMemberServiceInterface.save(circleMemberHenry); circleMemberServiceInterface.save(circleMemberThomas); circleMemberServiceInterface.save(circleMemberFroukje); circleMemberServiceInterface.save(circleMemberBetty); circleMemberServiceInterface.save(circleMemberBerend); lincUserDetailServiceInterface.save(diederik); lincUserDetailServiceInterface.save(hendrik); lincUserDetailServiceInterface.save(geertruida); lincUserDetailServiceInterface.save(jantina); lincUserDetailServiceInterface.save(baas); CircleMember circleMemberDiederik = new CircleMember(diederik, oomDiederik, true, true); // CircleMember circleMemberHendrik<SUF> CircleMember circleMemberGeertruida = new CircleMember(geertruida, tanteGeertruida, true, true); CircleMember circleMemberJantina = new CircleMember(jantina, omaJantina, true, false); CircleMember circleMemberBaas = new CircleMember(baas, woongroep, true, true); CircleMember circleMemberTess = new CircleMember(tess, omaJantina, false, true); circleMemberServiceInterface.save(circleMemberDiederik); // circleMemberServiceInterface.save(circleMemberHendrik); circleMemberServiceInterface.save(circleMemberGeertruida); circleMemberServiceInterface.save(circleMemberJantina); circleMemberServiceInterface.save(circleMemberBaas); circleMemberServiceInterface.save(circleMemberTess); LocalDate date1 = LocalDate.of(2022, 8, 11); LocalDate date2 = LocalDate.of(2022, 8, 7); LocalDate date3 = LocalDate.of(2022, 8, 4); LocalDate date4 = LocalDate.of(2022, 8, 30); LocalDate date5 = LocalDate.of(2022, 8, 16); LocalDate date6 = LocalDate.of(2022, 8, 27); LocalDate date7 = LocalDate.of(2022, 9, 2); LocalDate date8 = LocalDate.of(2022, 9, 14); LocalDate date9 = LocalDate.of(2022, 8, 3); LocalDate date10 = LocalDate.now().plusDays(2); LocalDate date11 = LocalDate.of(2022, 8, 9); String outdoor = "Outdoor"; String indoor = "Indoor"; String trips = "Transport"; String games = "Company"; Task task = new Task("Hulp bij zolder opruimen", "Oude foto albums wel bewaren graag!", false, date1, circleServiceInterface.findByCircleName("Fam. Janssen"), "Fam. Janssen", hendrik, hendrik.getUsername(), 90, diederik, indoor); taskServiceInterface.save(task); Circle studentenCircle = circleServiceInterface.findByCircleName("Thuiszorg Studenten"); taskServiceInterface.save(new Task("Boodschappen doen", "Boter kaas en eieren", false, date10, studentenCircle, "Thuiszorg Studenten", Berend, Madelein.getUsername(), 30, Berend, trips)); taskServiceInterface.save(new Task("Naar de apotheek", "Ze hebben gisteren gebeld, het recept is aangevuld", false, date1, studentenCircle, "Thuiszorg Studenten", Thomas, Thomas.getUsername(), 15, Timo, trips)); taskServiceInterface.save(new Task("Muffins bakken", "Betty wil graag iets bakken, ingredienten zijn al in huis", false, date3, studentenCircle, "Thuiszorg Studenten", Timo, Timo.getUsername(), 75, Timo, indoor)); taskServiceInterface.save(new Task("Vogelhuisje ophangen", "Op een rustige plek, niet pal in de zon.", false, date10, studentenCircle, "Thuiszorg Studenten", null, null, 120, Timo, outdoor)); taskServiceInterface.save(new Task("Berend moet naar de kapper", "Zelf nog even een afspraak maken", false, date6, studentenCircle, "Thuiszorg Studenten", Madelein, Madelein.getUsername(), 30, Timo, trips)); taskServiceInterface.save(new Task("Gezamelijk Formule 1 kijken", "Go Max!", false, date7, studentenCircle, "Thuiszorg Studenten", Thomas, Thomas.getUsername(), 150, Timo, games)); taskServiceInterface.save(new Task("Onkruid wieden", "Graag geen bestrijdingsmiddelen gebruiken", false, date8, studentenCircle, "Thuiszorg Studenten", null, null, 20, Timo, outdoor)); taskServiceInterface.save(new Task("Conifeer snoeien", "De buren begonnen weer te klagen over over te weinig zon", false, date4, studentenCircle, "Thuiszorg Studenten", null, null, 15, Timo, outdoor)); taskServiceInterface.save(new Task("Gras maaien", "-", false, date3, studentenCircle, "Thuiszorg Studenten", null, null, 15, Timo, outdoor)); taskServiceInterface.save(new Task("Betty helpen met DigiD aanvragen", "-", true, date8, studentenCircle, "Thuiszorg Studenten", Roos, Roos.getUsername(), 45, Timo, indoor)); taskServiceInterface.save(new Task("Kopje thee drinken", "-", true, date8, studentenCircle, "Thuiszorg Studenten", Henry, Henry.getUsername(), 15, Timo, games)); taskServiceInterface.save(new Task("Ramen lappen", "Van binnen én buiten graag", false, date7, studentenCircle, "Thuiszorg Studenten", null, null, 65, Timo, indoor)); taskServiceInterface.save(new Task("Rummikub spelen", "Berend wel laten winnen!", false, date2, studentenCircle, "Thuiszorg Studenten", null, null, 45, Timo, games)); taskServiceInterface.save(new Task("Uitje dierentuin", "", true, date2, studentenCircle, "Thuiszorg Studenten", Thomas, Thomas.getUsername(), 240, Timo, trips)); taskServiceInterface.save(new Task( "Boodschappen doen", "Havermout, melk, boter", false, circleServiceInterface.findByCircleName("Fam. Janssen"), "Fam. Janssen", date8, 30, diederik, trips)); taskServiceInterface.save(new Task( "Gras maaien", "Niet te kort AUB", false, circleServiceInterface.findByCircleName("Fam. Janssen"), "Fam. Janssen", date6, 72, hendrik, outdoor)); taskServiceInterface.save(new Task( "Naar de kapper", "Komende woensdagmiddag", false, circleServiceInterface.findByCircleName("Fam. Janssen"), "Fam. Janssen", date5, 120, diederik, trips)); taskServiceInterface.save(new Task( "Ramen wassen", "-", false, circleServiceInterface.findByCircleName("Tante Geertruida's Circle"), "Tante Geertruida", date4, 45, geertruida, indoor)); taskServiceInterface.save(new Task( "Auto APK", "Komende donderdagochtend 8 uur", false, circleServiceInterface.findByCircleName("Tante Geertruida's Circle"), "Tante Geertruida", date1, 120, geertruida, trips)); taskServiceInterface.save(new Task( "Schuur opruimen", "-", false, circleServiceInterface.findByCircleName("Tante Geertruida's Circle"), "Tante Geertruida", date6, 180, geertruida, outdoor)); taskServiceInterface.save(new Task( "Grijze container bij de weg zetten", "Komende maandagochtend voor 8 uur", false, circleServiceInterface.findByCircleName("Zorgboerderij 't Vliegende Schaapje"), "Zorgboerderij 't Haantje", date10, 2, baas, indoor)); taskServiceInterface.save(new Task( "Schutting repareren", "-", false, circleServiceInterface.findByCircleName("Zorgboerderij 't Vliegende Schaapje"), "Zorgboerderij 't Haantje", date8, 540, baas, outdoor)); taskServiceInterface.save(new Task( "Rummikub spelen", "Idealiter in het weekend", false, circleServiceInterface.findByCircleName("Zorgboerderij 't Vliegende Schaapje"), "Zorgboerderij 't Haantje", date3, 90, baas, games)); taskServiceInterface.save(new Task( "Medicijnen ophalen bij de apotheek", "Herhaalmedicatie, ligt klaar na 10:00", false, circleServiceInterface.findByCircleName("Fam. Jonker"), "Fam. Jonker", date11, 60, jantina, trips)); taskServiceInterface.save(new Task( "Gras maaien", "Achter en voor huis", false, circleServiceInterface.findByCircleName("Fam. Jonker"), "Fam. Jonker", date3, 25, jantina, outdoor)); taskServiceInterface.save(new Task( "TV repareren", "Zenders zitten niet meer op de goede plek. Jantina wil in ieder geval NPO 1, 2, en 3 weer zo snel mogelijk kijken.", false, circleServiceInterface.findByCircleName("Fam. Jonker"), "Fam. Jonker", date9, 5, jantina, indoor)); taskServiceInterface.save(new Task( "Boodschappen doen", "Havermout, melk, boter", false, circleServiceInterface.findByCircleName("Woongroep Middenmeer"), "Woongroep Middenmeer", date5, 45, baas, trips)); taskServiceInterface.save(new Task( "Vissen voeren", "2 theelepels", false, circleServiceInterface.findByCircleName("Woongroep Middenmeer"), "Woongroep Middenmeer", date5, 2, baas, indoor)); taskServiceInterface.save(new Task( "Visvoer bestellen", "Voor komend weekend in huis graag", false, circleServiceInterface.findByCircleName("Woongroep Middenmeer"), "Woongroep Middenmeer", date7, 5, baas, indoor)); // profile images File BerendFile = new File("src/main/resources/static/static/images/UserImages/Berend.png"); byte[] BerendPic = new byte[0]; try { BerendPic = FileUtils.readFileToByteArray(BerendFile); } catch (IOException e) { throw new RuntimeException(e); } Berend.setProfilePicture(BerendPic); lincUserDetailServiceInterface.save(Berend); File HenryFile = new File("src/main/resources/static/static/images/UserImages/Henry.png"); byte[] HenryPic = new byte[0]; try { HenryPic = FileUtils.readFileToByteArray(HenryFile); } catch (IOException e) { throw new RuntimeException(e); } Henry.setProfilePicture(HenryPic); lincUserDetailServiceInterface.save(Henry); File RoosFile = new File("src/main/resources/static/static/images/UserImages/Roos.png"); byte[] RoosPic = new byte[0]; try { RoosPic = FileUtils.readFileToByteArray(RoosFile); } catch (IOException e) { throw new RuntimeException(e); } Roos.setProfilePicture(RoosPic); lincUserDetailServiceInterface.save(Roos); File MarkFile = new File("src/main/resources/static/static/images/UserImages/Mark.png"); byte[] MarkPic = new byte[0]; try { MarkPic = FileUtils.readFileToByteArray(MarkFile); } catch (IOException e) { throw new RuntimeException(e); } Mark.setProfilePicture(MarkPic); lincUserDetailServiceInterface.save(Mark); File MadeleinFile = new File("src/main/resources/static/static/images/UserImages/Madelein.png"); byte[] MadeleinPic = new byte[0]; try { MadeleinPic = FileUtils.readFileToByteArray(MadeleinFile); } catch (IOException e) { throw new RuntimeException(e); } Madelein.setProfilePicture(MadeleinPic); lincUserDetailServiceInterface.save(Madelein); } }
141676_10
/*************************************************************************** * (C) Copyright 2003-2022 - Stendhal * *************************************************************************** *************************************************************************** * * * 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. * * * ***************************************************************************/ package games.stendhal.server.core.rp.achievement.factory; import java.util.Collection; import java.util.LinkedList; import games.stendhal.common.parser.Sentence; import games.stendhal.server.core.rp.achievement.Achievement; import games.stendhal.server.core.rp.achievement.Category; import games.stendhal.server.core.rp.achievement.condition.QuestWithPrefixCompletedCondition; import games.stendhal.server.entity.Entity; import games.stendhal.server.entity.npc.ChatCondition; import games.stendhal.server.entity.npc.condition.AndCondition; import games.stendhal.server.entity.npc.condition.QuestActiveCondition; import games.stendhal.server.entity.npc.condition.QuestCompletedCondition; import games.stendhal.server.entity.npc.condition.QuestNotInStateCondition; import games.stendhal.server.entity.npc.condition.QuestStartedCondition; import games.stendhal.server.entity.npc.condition.QuestStateStartsWithCondition; import games.stendhal.server.entity.player.Player; /** * Factory for quest achievements * * @author kymara */ public class FriendAchievementFactory extends AbstractAchievementFactory { public static final String ID_CHILD_FRIEND = "friend.quests.children"; public static final String ID_PRIVATE_DETECTIVE = "friend.quests.find"; public static final String ID_GOOD_SAMARITAN = "friend.karma.250"; public static final String ID_STILL_BELIEVING = "friend.meet.seasonal"; @Override protected Category getCategory() { return Category.FRIEND; } @Override public Collection<Achievement> createAchievements() { final LinkedList<Achievement> achievements = new LinkedList<Achievement>(); // TODO: add Pacifist achievement for not participating in pvp for 6 months or more (last_pvp_action_time) // Befriend Susi and complete quests for all children achievements.add(createAchievement( ID_CHILD_FRIEND, "Childrens' Friend", "Complete quests for all children", Achievement.MEDIUM_BASE_SCORE, true, new AndCondition( // Susi Quest is never set to done, therefore we check just if the quest has been started (condition "anyFriends" from FoundGirl.java) new QuestStartedCondition("susi"), // Help Tad, Semos Town Hall (Medicine for Tad) new QuestCompletedCondition("introduce_players"), // Plink, Semos Plains North new QuestCompletedCondition("plinks_toy"), // Anna, in Ados new QuestCompletedCondition("toys_collector"), // Sally, Orril River // 'completed' doesn't work for Sally - return player.hasQuest(QUEST_SLOT) && !"start".equals(player.getQuest(QUEST_SLOT)) && !"rejected".equals(player.getQuest(QUEST_SLOT)); new AndCondition( new QuestActiveCondition("campfire"), new QuestNotInStateCondition("campfire", "start")), // Annie, Kalavan city gardens new QuestStateStartsWithCondition("icecream_for_annie","eating;"), // Elisabeth, Kirdneh new QuestStateStartsWithCondition("chocolate_for_elisabeth","eating;"), // Jef, Kirdneh new QuestCompletedCondition("find_jefs_mom"), // Hughie, Ados farmhouse new AndCondition( new QuestActiveCondition("fishsoup_for_hughie"), new QuestNotInStateCondition("fishsoup_for_hughie", "start")), // Finn Farmer, George new QuestCompletedCondition("coded_message"), // Marianne, Deniran City S new AndCondition( new QuestActiveCondition("eggs_for_marianne"), new QuestNotInStateCondition("eggs_for_marianne", "start")) ))); // quests about finding people achievements.add(createAchievement( ID_PRIVATE_DETECTIVE, "Private Detective", "Find all lost and hidden people", Achievement.HARD_BASE_SCORE, true, new AndCondition( // Rat Children (Agnus) new QuestCompletedCondition("find_rat_kids"), // Find Ghosts (Carena) new QuestCompletedCondition("find_ghosts"), // Meet Angels (any of the cherubs) new ChatCondition() { @Override public boolean fire(final Player player, final Sentence sentence, final Entity entity) { if (!player.hasQuest("seven_cherubs")) { return false; } final String npcDoneText = player.getQuest("seven_cherubs"); final String[] done = npcDoneText.split(";"); final int left = 7 - done.length; return left < 0; } }, // Jef, Kirdneh new QuestCompletedCondition("find_jefs_mom") ))); // earn over 250 karma achievements.add(createAchievement( ID_GOOD_SAMARITAN, "Good Samaritan", "Earn a very good karma", Achievement.MEDIUM_BASE_SCORE, true, new ChatCondition() { @Override public boolean fire(final Player player, final Sentence sentence, final Entity entity) { return player.getKarma() > 250; } })); // meet Santa Claus and Easter Bunny achievements.add(createAchievement( ID_STILL_BELIEVING, "Still Believing", "Meet Santa Claus and Easter Bunny", Achievement.EASY_BASE_SCORE, true, new AndCondition( new QuestWithPrefixCompletedCondition("meet_santa_"), new QuestWithPrefixCompletedCondition("meet_bunny_")))); return achievements; } }
C8620/stendhal
src/games/stendhal/server/core/rp/achievement/factory/FriendAchievementFactory.java
1,834
// Annie, Kalavan city gardens
line_comment
nl
/*************************************************************************** * (C) Copyright 2003-2022 - Stendhal * *************************************************************************** *************************************************************************** * * * 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. * * * ***************************************************************************/ package games.stendhal.server.core.rp.achievement.factory; import java.util.Collection; import java.util.LinkedList; import games.stendhal.common.parser.Sentence; import games.stendhal.server.core.rp.achievement.Achievement; import games.stendhal.server.core.rp.achievement.Category; import games.stendhal.server.core.rp.achievement.condition.QuestWithPrefixCompletedCondition; import games.stendhal.server.entity.Entity; import games.stendhal.server.entity.npc.ChatCondition; import games.stendhal.server.entity.npc.condition.AndCondition; import games.stendhal.server.entity.npc.condition.QuestActiveCondition; import games.stendhal.server.entity.npc.condition.QuestCompletedCondition; import games.stendhal.server.entity.npc.condition.QuestNotInStateCondition; import games.stendhal.server.entity.npc.condition.QuestStartedCondition; import games.stendhal.server.entity.npc.condition.QuestStateStartsWithCondition; import games.stendhal.server.entity.player.Player; /** * Factory for quest achievements * * @author kymara */ public class FriendAchievementFactory extends AbstractAchievementFactory { public static final String ID_CHILD_FRIEND = "friend.quests.children"; public static final String ID_PRIVATE_DETECTIVE = "friend.quests.find"; public static final String ID_GOOD_SAMARITAN = "friend.karma.250"; public static final String ID_STILL_BELIEVING = "friend.meet.seasonal"; @Override protected Category getCategory() { return Category.FRIEND; } @Override public Collection<Achievement> createAchievements() { final LinkedList<Achievement> achievements = new LinkedList<Achievement>(); // TODO: add Pacifist achievement for not participating in pvp for 6 months or more (last_pvp_action_time) // Befriend Susi and complete quests for all children achievements.add(createAchievement( ID_CHILD_FRIEND, "Childrens' Friend", "Complete quests for all children", Achievement.MEDIUM_BASE_SCORE, true, new AndCondition( // Susi Quest is never set to done, therefore we check just if the quest has been started (condition "anyFriends" from FoundGirl.java) new QuestStartedCondition("susi"), // Help Tad, Semos Town Hall (Medicine for Tad) new QuestCompletedCondition("introduce_players"), // Plink, Semos Plains North new QuestCompletedCondition("plinks_toy"), // Anna, in Ados new QuestCompletedCondition("toys_collector"), // Sally, Orril River // 'completed' doesn't work for Sally - return player.hasQuest(QUEST_SLOT) && !"start".equals(player.getQuest(QUEST_SLOT)) && !"rejected".equals(player.getQuest(QUEST_SLOT)); new AndCondition( new QuestActiveCondition("campfire"), new QuestNotInStateCondition("campfire", "start")), // Annie, Kalavan<SUF> new QuestStateStartsWithCondition("icecream_for_annie","eating;"), // Elisabeth, Kirdneh new QuestStateStartsWithCondition("chocolate_for_elisabeth","eating;"), // Jef, Kirdneh new QuestCompletedCondition("find_jefs_mom"), // Hughie, Ados farmhouse new AndCondition( new QuestActiveCondition("fishsoup_for_hughie"), new QuestNotInStateCondition("fishsoup_for_hughie", "start")), // Finn Farmer, George new QuestCompletedCondition("coded_message"), // Marianne, Deniran City S new AndCondition( new QuestActiveCondition("eggs_for_marianne"), new QuestNotInStateCondition("eggs_for_marianne", "start")) ))); // quests about finding people achievements.add(createAchievement( ID_PRIVATE_DETECTIVE, "Private Detective", "Find all lost and hidden people", Achievement.HARD_BASE_SCORE, true, new AndCondition( // Rat Children (Agnus) new QuestCompletedCondition("find_rat_kids"), // Find Ghosts (Carena) new QuestCompletedCondition("find_ghosts"), // Meet Angels (any of the cherubs) new ChatCondition() { @Override public boolean fire(final Player player, final Sentence sentence, final Entity entity) { if (!player.hasQuest("seven_cherubs")) { return false; } final String npcDoneText = player.getQuest("seven_cherubs"); final String[] done = npcDoneText.split(";"); final int left = 7 - done.length; return left < 0; } }, // Jef, Kirdneh new QuestCompletedCondition("find_jefs_mom") ))); // earn over 250 karma achievements.add(createAchievement( ID_GOOD_SAMARITAN, "Good Samaritan", "Earn a very good karma", Achievement.MEDIUM_BASE_SCORE, true, new ChatCondition() { @Override public boolean fire(final Player player, final Sentence sentence, final Entity entity) { return player.getKarma() > 250; } })); // meet Santa Claus and Easter Bunny achievements.add(createAchievement( ID_STILL_BELIEVING, "Still Believing", "Meet Santa Claus and Easter Bunny", Achievement.EASY_BASE_SCORE, true, new AndCondition( new QuestWithPrefixCompletedCondition("meet_santa_"), new QuestWithPrefixCompletedCondition("meet_bunny_")))); return achievements; } }
131313_10
/******************************************************************************* * Copyright (c) 2011 Software Engineering Institute, TU Dortmund. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * {SecSE group} - initial API and implementation and/or initial documentation *******************************************************************************/ package carisma.check.activity2petrinet; import org.eclipse.uml2.uml.ActivityEdge; import org.eclipse.uml2.uml.ActivityNode; import org.eclipse.uml2.uml.ControlFlow; import org.eclipse.uml2.uml.Element; import org.eclipse.uml2.uml.InitialNode; import org.eclipse.uml2.uml.Activity; import org.eclipse.uml2.uml.Model; import carisma.check.activity2petrinet.petriNet.Arc; import carisma.check.activity2petrinet.petriNet.PetriNet; import carisma.check.activity2petrinet.petriNet.Place; import carisma.check.activity2petrinet.petriNet.Transition; import carisma.core.analysis.AnalysisHost; import carisma.core.analysis.DummyHost; import carisma.core.analysis.result.AnalysisResultMessage; import carisma.core.analysis.result.StatusType; import carisma.modeltype.uml2.activity.ActivityDiagramManager; /** * This Class contains the static method convert, which converts an UML 2 activity diagram to * a petri net. * @author Kubi Mensah * */ public class Convert { /** * The loaded model. */ private Model model; /** * host for report. */ private AnalysisHost host = new DummyHost(true); /** * Constructs a new convert object with the given model. * @param model the model */ public Convert(final Model model) { this.model = model; } /** * Constructs a new convert object with the given model. * @param model the model * @param analysisHost host for report */ public Convert(final Model model, final AnalysisHost analysisHost) { this.model = model; if (analysisHost != null) { this.host = analysisHost; } } /** * This method converts an uml activity diagram into a petri net. * @return returns the converted petri net */ public final PetriNet convert() { //initializing new petri net PetriNet petriNet = new PetriNet("activity_convert", "http://www.pnml.org/version-2009/grammar/pnmlcoremodel.rng"); Element initialNode = null; //determining the initial state of the activity diagram Activity activity = null; Element element = this.model.getMembers().get(0); while (activity == null) { if (element.getOwnedElements().size() == 0) { this.host.addResultMessage(new AnalysisResultMessage(StatusType.INFO, "Found no activity")); this.host.appendLineToReport("Found no activity"); return petriNet; } else if(element instanceof Activity) { activity = (Activity) element; } else { element = element.getOwnedElements().get(0); } } for (ActivityNode node : activity.getOwnedNodes()) { if (node instanceof InitialNode) { initialNode = node; } } // TODO KR: ein Aktivit�tsdigramm kann mehrere Initialnodes haben // das muss hier ber�cksichtigt werden, entsprechende places mit tokens erstellen if (initialNode == null) { this.host.addResultMessage(new AnalysisResultMessage(StatusType.INFO, "Found no initial node")); this.host.appendLineToReport("Found no initial node"); return petriNet; } // start to traverse the activity diagram from the initial state, converting it into a petri net convertRek(petriNet, initialNode); return petriNet; } /** * This recursive method traverses over each element of an UML activity diagram according to a * triple graph grammar, mapping UML 2 activities into petri nets. * @param petri The output petri net (elements are added through 'call by reference') * @param elt The node in the activity diagram from which the conversion will start. */ private void convertRek(final PetriNet petri, final Element elt) { if (elt == null) { return; } else if (ActivityDiagramManager.isDecisionOrMergeNode(elt) || ActivityDiagramManager.isFinalNode(elt) || ActivityDiagramManager.isInitialNode(elt)) { String name = " "; ActivityNode aN = (ActivityNode) elt; if (aN.getName() != null) { name = aN.getName(); } boolean exists = false; exists = !petri.addPlace(new Place(aN.getQualifiedName(), null, name)); if (exists) { return; } if (!ActivityDiagramManager.isFinalNode(aN)) { for (ActivityEdge aE : aN.getOutgoings()) { convertRek(petri , aE); } return; } //rule 2 } else if (ActivityDiagramManager.isAction(elt) || ActivityDiagramManager.isForkNode(elt) || ActivityDiagramManager.isJoinNode(elt)) { String name = " "; ActivityNode aN = (ActivityNode) elt; if (aN.getName() != null) { name = aN.getName(); } boolean exists = false; exists = !petri.addTransition(new Transition(aN.getQualifiedName(), null, name)); if (exists) { return; } for (ActivityEdge aE : aN.getOutgoings()) { convertRek(petri , aE); } return; } else if (ActivityDiagramManager.isEdge(elt)) { ControlFlow cf = (ControlFlow) elt; ActivityNode source = cf.getSource(); ActivityNode target = cf.getTarget(); //rule 3 if ( (ActivityDiagramManager.isAction(source) && ActivityDiagramManager.isAction(target)) || (ActivityDiagramManager.isAction(source) && ActivityDiagramManager.isForkNode(target)) || (ActivityDiagramManager.isAction(source) && ActivityDiagramManager.isJoinNode(target)) || (ActivityDiagramManager.isForkNode(source) && ActivityDiagramManager.isAction(target)) || (ActivityDiagramManager.isForkNode(source) && ActivityDiagramManager.isJoinNode(target)) || (ActivityDiagramManager.isJoinNode(source) && ActivityDiagramManager.isAction(target)) || (ActivityDiagramManager.isJoinNode(source) && ActivityDiagramManager.isForkNode(target)) ) { String name = " "; if (cf.getName() != null) { name = cf.getName(); } boolean exists = false; exists = !petri.addPlace(new Place(cf.getQualifiedName() + ".1", null, name)); if (exists) { return; } petri.addArc(new Arc(cf.getQualifiedName() + ".0", source.getQualifiedName(), cf.getQualifiedName() + ".1")); petri.addArc(new Arc(cf.getQualifiedName() + ".2", cf.getQualifiedName() + ".1", target.getQualifiedName())); convertRek(petri, target); return; } //rule 4 if ( (ActivityDiagramManager.isInitialNode(source) && ActivityDiagramManager.isDecisionOrMergeNode(target)) || (ActivityDiagramManager.isDecisionOrMergeNode(source) && ActivityDiagramManager.isDecisionOrMergeNode(target)) || (ActivityDiagramManager.isDecisionOrMergeNode(source) && ActivityDiagramManager.isFinalNode(target)) ) { String name = " "; if (cf.getName() != null) { name = cf.getName(); } boolean exists = false; exists = !petri.addTransition(new Transition(cf.getQualifiedName() + ".1", null, name)); if (exists) { return; } petri.addArc(new Arc(cf.getQualifiedName() + ".0", source.getQualifiedName(), cf.getQualifiedName() + ".1")); petri.addArc(new Arc(cf.getQualifiedName() + ".2", cf.getQualifiedName() + ".1", target.getQualifiedName())); convertRek(petri, target); return; } //rule 5 if ( (ActivityDiagramManager.isAction(source) && ActivityDiagramManager.isFinalNode(target)) || (ActivityDiagramManager.isAction(source) && ActivityDiagramManager.isDecisionOrMergeNode(target)) || (ActivityDiagramManager.isForkNode(source) && ActivityDiagramManager.isFinalNode(target)) || (ActivityDiagramManager.isForkNode(source) && ActivityDiagramManager.isDecisionOrMergeNode(target)) || (ActivityDiagramManager.isJoinNode(source) && ActivityDiagramManager.isFinalNode(target)) || (ActivityDiagramManager.isJoinNode(source) && ActivityDiagramManager.isDecisionOrMergeNode(target)) || //rule 6 (ActivityDiagramManager.isInitialNode(source) && ActivityDiagramManager.isAction(target)) || (ActivityDiagramManager.isInitialNode(source) && ActivityDiagramManager.isForkNode(target)) || (ActivityDiagramManager.isDecisionOrMergeNode(source) && ActivityDiagramManager.isAction(target)) || (ActivityDiagramManager.isDecisionOrMergeNode(source) && ActivityDiagramManager.isForkNode(target)) || (ActivityDiagramManager.isDecisionOrMergeNode(source) && ActivityDiagramManager.isJoinNode(target)) ) { boolean exists = false; exists = !petri.addArc(new Arc(cf.getQualifiedName(), source.getQualifiedName(), target.getQualifiedName())); if (exists) { return; } convertRek(petri, target); return; } } else { return; } } }
CARiSMA-Tool/carisma-tool
plugins/carisma.check.activity2petrinet/src/carisma/check/activity2petrinet/Convert.java
3,017
// das muss hier ber�cksichtigt werden, entsprechende places mit tokens erstellen
line_comment
nl
/******************************************************************************* * Copyright (c) 2011 Software Engineering Institute, TU Dortmund. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * {SecSE group} - initial API and implementation and/or initial documentation *******************************************************************************/ package carisma.check.activity2petrinet; import org.eclipse.uml2.uml.ActivityEdge; import org.eclipse.uml2.uml.ActivityNode; import org.eclipse.uml2.uml.ControlFlow; import org.eclipse.uml2.uml.Element; import org.eclipse.uml2.uml.InitialNode; import org.eclipse.uml2.uml.Activity; import org.eclipse.uml2.uml.Model; import carisma.check.activity2petrinet.petriNet.Arc; import carisma.check.activity2petrinet.petriNet.PetriNet; import carisma.check.activity2petrinet.petriNet.Place; import carisma.check.activity2petrinet.petriNet.Transition; import carisma.core.analysis.AnalysisHost; import carisma.core.analysis.DummyHost; import carisma.core.analysis.result.AnalysisResultMessage; import carisma.core.analysis.result.StatusType; import carisma.modeltype.uml2.activity.ActivityDiagramManager; /** * This Class contains the static method convert, which converts an UML 2 activity diagram to * a petri net. * @author Kubi Mensah * */ public class Convert { /** * The loaded model. */ private Model model; /** * host for report. */ private AnalysisHost host = new DummyHost(true); /** * Constructs a new convert object with the given model. * @param model the model */ public Convert(final Model model) { this.model = model; } /** * Constructs a new convert object with the given model. * @param model the model * @param analysisHost host for report */ public Convert(final Model model, final AnalysisHost analysisHost) { this.model = model; if (analysisHost != null) { this.host = analysisHost; } } /** * This method converts an uml activity diagram into a petri net. * @return returns the converted petri net */ public final PetriNet convert() { //initializing new petri net PetriNet petriNet = new PetriNet("activity_convert", "http://www.pnml.org/version-2009/grammar/pnmlcoremodel.rng"); Element initialNode = null; //determining the initial state of the activity diagram Activity activity = null; Element element = this.model.getMembers().get(0); while (activity == null) { if (element.getOwnedElements().size() == 0) { this.host.addResultMessage(new AnalysisResultMessage(StatusType.INFO, "Found no activity")); this.host.appendLineToReport("Found no activity"); return petriNet; } else if(element instanceof Activity) { activity = (Activity) element; } else { element = element.getOwnedElements().get(0); } } for (ActivityNode node : activity.getOwnedNodes()) { if (node instanceof InitialNode) { initialNode = node; } } // TODO KR: ein Aktivit�tsdigramm kann mehrere Initialnodes haben // das muss<SUF> if (initialNode == null) { this.host.addResultMessage(new AnalysisResultMessage(StatusType.INFO, "Found no initial node")); this.host.appendLineToReport("Found no initial node"); return petriNet; } // start to traverse the activity diagram from the initial state, converting it into a petri net convertRek(petriNet, initialNode); return petriNet; } /** * This recursive method traverses over each element of an UML activity diagram according to a * triple graph grammar, mapping UML 2 activities into petri nets. * @param petri The output petri net (elements are added through 'call by reference') * @param elt The node in the activity diagram from which the conversion will start. */ private void convertRek(final PetriNet petri, final Element elt) { if (elt == null) { return; } else if (ActivityDiagramManager.isDecisionOrMergeNode(elt) || ActivityDiagramManager.isFinalNode(elt) || ActivityDiagramManager.isInitialNode(elt)) { String name = " "; ActivityNode aN = (ActivityNode) elt; if (aN.getName() != null) { name = aN.getName(); } boolean exists = false; exists = !petri.addPlace(new Place(aN.getQualifiedName(), null, name)); if (exists) { return; } if (!ActivityDiagramManager.isFinalNode(aN)) { for (ActivityEdge aE : aN.getOutgoings()) { convertRek(petri , aE); } return; } //rule 2 } else if (ActivityDiagramManager.isAction(elt) || ActivityDiagramManager.isForkNode(elt) || ActivityDiagramManager.isJoinNode(elt)) { String name = " "; ActivityNode aN = (ActivityNode) elt; if (aN.getName() != null) { name = aN.getName(); } boolean exists = false; exists = !petri.addTransition(new Transition(aN.getQualifiedName(), null, name)); if (exists) { return; } for (ActivityEdge aE : aN.getOutgoings()) { convertRek(petri , aE); } return; } else if (ActivityDiagramManager.isEdge(elt)) { ControlFlow cf = (ControlFlow) elt; ActivityNode source = cf.getSource(); ActivityNode target = cf.getTarget(); //rule 3 if ( (ActivityDiagramManager.isAction(source) && ActivityDiagramManager.isAction(target)) || (ActivityDiagramManager.isAction(source) && ActivityDiagramManager.isForkNode(target)) || (ActivityDiagramManager.isAction(source) && ActivityDiagramManager.isJoinNode(target)) || (ActivityDiagramManager.isForkNode(source) && ActivityDiagramManager.isAction(target)) || (ActivityDiagramManager.isForkNode(source) && ActivityDiagramManager.isJoinNode(target)) || (ActivityDiagramManager.isJoinNode(source) && ActivityDiagramManager.isAction(target)) || (ActivityDiagramManager.isJoinNode(source) && ActivityDiagramManager.isForkNode(target)) ) { String name = " "; if (cf.getName() != null) { name = cf.getName(); } boolean exists = false; exists = !petri.addPlace(new Place(cf.getQualifiedName() + ".1", null, name)); if (exists) { return; } petri.addArc(new Arc(cf.getQualifiedName() + ".0", source.getQualifiedName(), cf.getQualifiedName() + ".1")); petri.addArc(new Arc(cf.getQualifiedName() + ".2", cf.getQualifiedName() + ".1", target.getQualifiedName())); convertRek(petri, target); return; } //rule 4 if ( (ActivityDiagramManager.isInitialNode(source) && ActivityDiagramManager.isDecisionOrMergeNode(target)) || (ActivityDiagramManager.isDecisionOrMergeNode(source) && ActivityDiagramManager.isDecisionOrMergeNode(target)) || (ActivityDiagramManager.isDecisionOrMergeNode(source) && ActivityDiagramManager.isFinalNode(target)) ) { String name = " "; if (cf.getName() != null) { name = cf.getName(); } boolean exists = false; exists = !petri.addTransition(new Transition(cf.getQualifiedName() + ".1", null, name)); if (exists) { return; } petri.addArc(new Arc(cf.getQualifiedName() + ".0", source.getQualifiedName(), cf.getQualifiedName() + ".1")); petri.addArc(new Arc(cf.getQualifiedName() + ".2", cf.getQualifiedName() + ".1", target.getQualifiedName())); convertRek(petri, target); return; } //rule 5 if ( (ActivityDiagramManager.isAction(source) && ActivityDiagramManager.isFinalNode(target)) || (ActivityDiagramManager.isAction(source) && ActivityDiagramManager.isDecisionOrMergeNode(target)) || (ActivityDiagramManager.isForkNode(source) && ActivityDiagramManager.isFinalNode(target)) || (ActivityDiagramManager.isForkNode(source) && ActivityDiagramManager.isDecisionOrMergeNode(target)) || (ActivityDiagramManager.isJoinNode(source) && ActivityDiagramManager.isFinalNode(target)) || (ActivityDiagramManager.isJoinNode(source) && ActivityDiagramManager.isDecisionOrMergeNode(target)) || //rule 6 (ActivityDiagramManager.isInitialNode(source) && ActivityDiagramManager.isAction(target)) || (ActivityDiagramManager.isInitialNode(source) && ActivityDiagramManager.isForkNode(target)) || (ActivityDiagramManager.isDecisionOrMergeNode(source) && ActivityDiagramManager.isAction(target)) || (ActivityDiagramManager.isDecisionOrMergeNode(source) && ActivityDiagramManager.isForkNode(target)) || (ActivityDiagramManager.isDecisionOrMergeNode(source) && ActivityDiagramManager.isJoinNode(target)) ) { boolean exists = false; exists = !petri.addArc(new Arc(cf.getQualifiedName(), source.getQualifiedName(), target.getQualifiedName())); if (exists) { return; } convertRek(petri, target); return; } } else { return; } } }
5153_1
import java.util.Arrays; import math.jwave.exceptions.JWaveException; import math.jwave.Transform; import math.jwave.transforms.AncientEgyptianDecomposition; import math.jwave.transforms.FastWaveletTransform; import math.jwave.transforms.wavelets.haar.Haar1; public class WaveletTest { public static void main(String[] args) { Transform t = new Transform( new AncientEgyptianDecomposition( new FastWaveletTransform( new Haar1( ) ) ) ); double threshold = 1.5; double[ ] arrTime = { 4., 5., 6., 5.5, 7., 3., 4.}; double[ ] arrHilb = t.forward( arrTime ); // 1-D AED FWT Haar forward System.out.println(Arrays.toString(arrTime)); System.out.println(Arrays.toString(arrHilb)); for(int i = 0; i < arrHilb.length; i++) { if(Math.abs(arrHilb[i]) > threshold) { arrHilb[i] = 1; } } double[ ] arrReco = t.reverse( arrHilb ); // 1-D AED FWT Haar reverse System.out.println(Arrays.toString(arrReco)); } }
CBLRIT/ECG-Viewer
WaveletTest.java
379
// 1-D AED FWT Haar reverse
line_comment
nl
import java.util.Arrays; import math.jwave.exceptions.JWaveException; import math.jwave.Transform; import math.jwave.transforms.AncientEgyptianDecomposition; import math.jwave.transforms.FastWaveletTransform; import math.jwave.transforms.wavelets.haar.Haar1; public class WaveletTest { public static void main(String[] args) { Transform t = new Transform( new AncientEgyptianDecomposition( new FastWaveletTransform( new Haar1( ) ) ) ); double threshold = 1.5; double[ ] arrTime = { 4., 5., 6., 5.5, 7., 3., 4.}; double[ ] arrHilb = t.forward( arrTime ); // 1-D AED FWT Haar forward System.out.println(Arrays.toString(arrTime)); System.out.println(Arrays.toString(arrHilb)); for(int i = 0; i < arrHilb.length; i++) { if(Math.abs(arrHilb[i]) > threshold) { arrHilb[i] = 1; } } double[ ] arrReco = t.reverse( arrHilb ); // 1-D AED<SUF> System.out.println(Arrays.toString(arrReco)); } }
32572_2
package nl.cjib.training.ocp.concurrency.presentatie2.deel3_cyclic_barriers; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * Een {@link CyclicBarrier} kan worden gebruikt om threads met elkaar te synchroniseren. */ public class CyclicBarriers { /** * De {@link CyclicBarrier} heeft 2 constructors: * - Bij de ene geef je alleen het aantal threads op dat nodig is om de barrier te trippen; */ private static final CyclicBarrier cyclicBarrier = new CyclicBarrier(2); /** * - Bij de andere geef je naast dat aantal ook nog een {@link Runnable} mee die uitgevoerd wordt * als de barrier getript wordt. */ private static final CyclicBarrier cyclicBarrierMetRunnable = new CyclicBarrier(2, () -> System.out.println("Barrier tripped")); public static void main(String[] args) throws InterruptedException { // met getParties haal je het aantal parties op dat nodig is om de barrier te trippen. System.out.println("Parties needed to trip the barrier: " + cyclicBarrier.getParties()); new Thread(() -> task(1)).start(); Thread.sleep(50); // met getNumberWaiting haal je het aantal parties op dat al voor de barrier aan het wachten is. System.out.println("Number waiting: " + cyclicBarrierMetRunnable.getNumberWaiting()); new Thread(() -> task(2)).start(); otherFeatures(); } private static void task(int threadNumber) { try { // Je kan await gebruiken om te wachten voor de barrier. System.out.println("Thread " + threadNumber + " waiting for barrier..."); cyclicBarrierMetRunnable.await(); System.out.println("Thread " + threadNumber + " done waiting for barrier"); // De barrier is herbruikbaar (vandaar de naam CyclicBarrier) System.out.println("Thread " + threadNumber + " waiting for barrier..."); cyclicBarrierMetRunnable.await(); System.out.println("Thread " + threadNumber + " done waiting for barrier"); } catch (InterruptedException e) { System.exit(1); } catch (BrokenBarrierException e) { e.printStackTrace(); } } private static void otherFeatures() throws InterruptedException { Thread.sleep(1000); try { // Je kan bij await ook een timeout opgeven. // Bij een timeout krijg je een TimeoutException cyclicBarrierMetRunnable.await(1, TimeUnit.SECONDS); } catch (BrokenBarrierException e) { e.printStackTrace(); } catch (TimeoutException e) { System.out.println("The barrier wasn't tripped in the timeout period"); } // Een timeout zorgt er ook voor dat de CyclicBarrier daarna broken is. System.out.println("isBroken: " + cyclicBarrierMetRunnable.isBroken()); try { cyclicBarrierMetRunnable.await(); } catch (BrokenBarrierException e) { // Dit resulteert in een BrokenBarrierException als je nog een keer probeert te wachten op de barrier System.out.println("The barrier is broken and needs to be reset"); } // Je kan de CyclicBarrier weer gereed maken voor gebruik met een reset. cyclicBarrierMetRunnable.reset(); System.out.println("isBroken na reset: " + cyclicBarrierMetRunnable.isBroken()); // Als je een reset doet vanuit een andere thread terwijl er al een thread op de barrier wacht... ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); scheduledExecutorService.schedule(cyclicBarrierMetRunnable::reset, 2, TimeUnit.SECONDS); try { System.out.println("Waiting at the barrier after the first reset..."); cyclicBarrierMetRunnable.await(); } // ...dan wordt de barrier voor dit wachtende thread ook als gebroken beschouwd // en zal deze een BrokenBarrierException geven. catch (BrokenBarrierException e) { System.out.println("The barrier was broken by resetting it again, while the thread was waiting."); } scheduledExecutorService.shutdown(); } }
CC007/OCPConcurrency
src/main/java/nl/cjib/training/ocp/concurrency/presentatie2/deel3_cyclic_barriers/CyclicBarriers.java
1,215
/** * - Bij de andere geef je naast dat aantal ook nog een {@link Runnable} mee die uitgevoerd wordt * als de barrier getript wordt. */
block_comment
nl
package nl.cjib.training.ocp.concurrency.presentatie2.deel3_cyclic_barriers; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * Een {@link CyclicBarrier} kan worden gebruikt om threads met elkaar te synchroniseren. */ public class CyclicBarriers { /** * De {@link CyclicBarrier} heeft 2 constructors: * - Bij de ene geef je alleen het aantal threads op dat nodig is om de barrier te trippen; */ private static final CyclicBarrier cyclicBarrier = new CyclicBarrier(2); /** * - Bij de<SUF>*/ private static final CyclicBarrier cyclicBarrierMetRunnable = new CyclicBarrier(2, () -> System.out.println("Barrier tripped")); public static void main(String[] args) throws InterruptedException { // met getParties haal je het aantal parties op dat nodig is om de barrier te trippen. System.out.println("Parties needed to trip the barrier: " + cyclicBarrier.getParties()); new Thread(() -> task(1)).start(); Thread.sleep(50); // met getNumberWaiting haal je het aantal parties op dat al voor de barrier aan het wachten is. System.out.println("Number waiting: " + cyclicBarrierMetRunnable.getNumberWaiting()); new Thread(() -> task(2)).start(); otherFeatures(); } private static void task(int threadNumber) { try { // Je kan await gebruiken om te wachten voor de barrier. System.out.println("Thread " + threadNumber + " waiting for barrier..."); cyclicBarrierMetRunnable.await(); System.out.println("Thread " + threadNumber + " done waiting for barrier"); // De barrier is herbruikbaar (vandaar de naam CyclicBarrier) System.out.println("Thread " + threadNumber + " waiting for barrier..."); cyclicBarrierMetRunnable.await(); System.out.println("Thread " + threadNumber + " done waiting for barrier"); } catch (InterruptedException e) { System.exit(1); } catch (BrokenBarrierException e) { e.printStackTrace(); } } private static void otherFeatures() throws InterruptedException { Thread.sleep(1000); try { // Je kan bij await ook een timeout opgeven. // Bij een timeout krijg je een TimeoutException cyclicBarrierMetRunnable.await(1, TimeUnit.SECONDS); } catch (BrokenBarrierException e) { e.printStackTrace(); } catch (TimeoutException e) { System.out.println("The barrier wasn't tripped in the timeout period"); } // Een timeout zorgt er ook voor dat de CyclicBarrier daarna broken is. System.out.println("isBroken: " + cyclicBarrierMetRunnable.isBroken()); try { cyclicBarrierMetRunnable.await(); } catch (BrokenBarrierException e) { // Dit resulteert in een BrokenBarrierException als je nog een keer probeert te wachten op de barrier System.out.println("The barrier is broken and needs to be reset"); } // Je kan de CyclicBarrier weer gereed maken voor gebruik met een reset. cyclicBarrierMetRunnable.reset(); System.out.println("isBroken na reset: " + cyclicBarrierMetRunnable.isBroken()); // Als je een reset doet vanuit een andere thread terwijl er al een thread op de barrier wacht... ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); scheduledExecutorService.schedule(cyclicBarrierMetRunnable::reset, 2, TimeUnit.SECONDS); try { System.out.println("Waiting at the barrier after the first reset..."); cyclicBarrierMetRunnable.await(); } // ...dan wordt de barrier voor dit wachtende thread ook als gebroken beschouwd // en zal deze een BrokenBarrierException geven. catch (BrokenBarrierException e) { System.out.println("The barrier was broken by resetting it again, while the thread was waiting."); } scheduledExecutorService.shutdown(); } }
30848_9
/*----------------------------------------------------------------------- * Copyright (C) 2001 Green Light District Team, Utrecht University * Copyright of the TC1 algorithm (C) Marco Wiering, Utrecht University * * This program (Green Light District) is free software. * You may redistribute it and/or modify it under the terms * of the GNU General Public License as published by * the Free Software Foundation (version 2 or later). * * 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. * See the documentation of Green Light District for further information. * * Changed to use Sarsa(0) with random decision instead of DP - S. Louring *------------------------------------------------------------------------*/ package com.github.cc007.trafficlights.algo.tlc; import com.github.cc007.trafficlights.*; import com.github.cc007.trafficlights.algo.tlc.*; import com.github.cc007.trafficlights.infra.*; import com.github.cc007.trafficlights.xml.*; import java.io.IOException; import java.util.*; /** * * This controller will decide it's Q values for the traffic lights according to * the traffic situation on the lane connected to the TrafficLight. It will * learn how to alter it's outcome by reinforcement learning. * * @author Arne K, Jilles V, Søren Louring * @version 1.1 */ public class SL2TLC extends TCRL implements InstantiationAssistant { protected Infrastructure infrastructure; protected TrafficLight[][] tls; protected Node[] allnodes; protected int num_nodes; protected ArrayList<CountEntry> count; //, p_table; protected float[][][][] q_table; //sign, pos, des, color (red=0, green=1) protected static float gamma = 0.95f; //Discount Factor; used to decrease the influence of previous V values, that's why: 0 < gamma < 1 protected static float random_chance = 0.01f; //A random gain setting is chosen instead of the on the TLC dictates with this chance protected static float alpha = 0.7f; protected final static boolean red = false, green = true; protected final static int green_index = 0, red_index = 1; protected final static String shortXMLName = "tlc-sl2"; private Random random_number; protected float time_step = 0; /** * The constructor for TL controllers * * @param The model being used. */ public SL2TLC(Infrastructure infra) throws InfraException { super(infra); Node[] nodes = infra.getAllNodes(); //Moet Edge zijn eigenlijk, alleen testSimModel knalt er dan op int num_nodes = nodes.length; count = new ArrayList<>(); int numSigns = infra.getAllInboundLanes().size(); q_table = new float[numSigns + 1][][][]; int num_specialnodes = infra.getNumSpecialNodes(); for (int i = 0; i < nodes.length; i++) { Node n = nodes[i]; DriveLane[] dls = n.getInboundLanes(); for (int j = 0; j < dls.length; j++) { DriveLane d = dls[j]; Sign s = d.getSign(); int id = s.getId(); int num_pos_on_dl = d.getCompleteLength(); q_table[id] = new float[num_pos_on_dl][][]; for (int k = 0; k < num_pos_on_dl; k++) { q_table[id][k] = new float[num_specialnodes][]; for (int l = 0; l < q_table[id][k].length; l++) { q_table[id][k][l] = new float[2]; q_table[id][k][l][0] = 0.0f; q_table[id][k][l][1] = 0.0f; //v_table[id][k][l]=0.0f; } } } } System.out.println("tl = " + numSigns); System.out.println("des = " + num_specialnodes); System.out.println("Alpha = " + alpha); random_number = new Random(GLDSim.seriesSeed[GLDSim.seriesSeedIndex]); } @Override public void reset() { for (int j = 0; j < q_table.length; j++) { if (q_table[j] != null) { for (int k = 0; k < q_table[j].length; k++) { if (q_table[j][k] != null) { for (int l = 0; l < q_table[j][k].length; l++) { if (q_table[j][k][l] != null) { q_table[j][k][l][0] = 0.0f; q_table[j][k][l][1] = 0.0f; } } } } } } System.out.println("Q table nulstillet."); } //Reset slut /** * Calculates how every traffic light should be switched Per node, per sign * the waiting roadusers are passed and per each roaduser the gain is * calculated. * * @param The TLDecision is a tuple consisting of a traffic light and a * reward (Q) value, for it to be green * @see gld.algo.tlc.TLDecision */ @Override public TLDecision[][] decideTLs() { int num_dec; int num_tld = tld.length; //Determine wheter it should be random or not boolean do_this_random = false; time_step++; random_chance = (1.0f / ((float) Math.sqrt(time_step))); if (random_number.nextFloat() < random_chance) { do_this_random = true; } for (int i = 0; i < num_tld; i++) { num_dec = tld[i].length; for (int j = 0; j < num_dec; j++) { Sign currenttl = tld[i][j].getTL(); float gain = 0; DriveLane currentlane = currenttl.getLane(); int waitingsize = currentlane.getNumRoadusersWaiting(); Iterator<Roaduser> queue = currentlane.getQueue().iterator(); if (!do_this_random) { for (; waitingsize > 0; waitingsize--) { Roaduser ru = queue.next(); int pos = ru.getPosition(); Node destination = ru.getDestNode(); gain += q_table[currenttl.getId()][pos][destination.getId()][1] - q_table[currenttl.getId()][pos][destination.getId()][0]; //red - green // System.out.println(gain + " "); } float q = gain; } else { gain = random_number.nextFloat(); } tld[i][j].setGain(gain); } } return tld; } @Override public void updateRoaduserMove(Roaduser ru, DriveLane prevlane, Sign prevsign, int prevpos, DriveLane dlanenow, Sign signnow, int posnow, PosMov[] posMovs, DriveLane desired, int penalty) { //When a roaduser leaves the city; this will if (dlanenow == null || signnow == null) { dlanenow = prevlane; signnow = prevsign; posnow = -1; return; // ?? is recalculation is not necessary ?? } //This ordening is important for the execution of the algorithm! if (prevsign.getType() == Sign.TRAFFICLIGHT && (signnow.getType() == Sign.TRAFFICLIGHT || signnow.getType() == Sign.NO_SIGN)) { Node dest = ru.getDestNode(); recalcQ(prevsign, prevpos, dest, prevsign.mayDrive(), signnow, posnow, signnow.mayDrive(), posMovs, penalty); } } protected void recalcQ(Sign tl, int pos, Node destination, boolean light, Sign tl_new, int pos_new, boolean light_new, PosMov[] posMovs, int penalty) { /* Recalculate the Q values, only one PEntry has changed, meaning also only 1 QEntry has to change */ int R; float oldQvalue = 0; float Qmark = 0; float newQvalue = 0; R = penalty + rewardFunction(tl_new, pos_new, posMovs); try { oldQvalue = q_table[tl.getId()][pos][destination.getId()][light ? green_index : red_index]; Qmark = q_table[tl_new.getId()][pos_new][destination.getId()][light_new ? green_index : red_index];// Q( [ tl' , p' ] , L') } catch (Exception e) { System.out.println("ERROR"); System.out.println("tl: " + tl.getId()); System.out.println("pos:" + pos); System.out.println("des:" + destination.getId()); } newQvalue = oldQvalue + alpha * (R + gamma * Qmark - oldQvalue); q_table[tl.getId()][pos][destination.getId()][light ? green_index : red_index] = newQvalue; } /* ========================================================================== Additional methods, used by the recalc methods ========================================================================== */ protected int rewardFunction(Sign tl_new, int pos_new, PosMov[] posMovs) { //Ok, the reward function is actually very simple; it searches for the tuple (tl_new, pos_new) in the given set int size = posMovs.length; for (int i = 0; i < size; i++) { if (posMovs[i].tlId == tl_new.getId() && posMovs[i].pos == pos_new) { return 0; } } /*int size = possiblelanes.length; for(int i=0; i<size; i++) { if( possiblelanes[i].equals(tl_new.getLane()) ) { if(ranges[i].x < pos_new) { if(ranges[i].y > pos_new) { return 0; } } } }*/ return 1; } protected Target[] ownedTargets(Sign tl, int pos, Node des, boolean light) { //This method will determine to which destinations you can go starting at this source represented in this QEntry CountEntry dummy = new CountEntry(tl, pos, des, light, tl, pos); Target[] ownedtargets; ArrayList<Target> candidate_targets; candidate_targets = new ArrayList<>(); //Use the count table to sort this out, we need all Targets from //Only the elements in the count table are used, other just give a P Iterator<CountEntry> it = count.iterator(); while (it.hasNext()) { CountEntry current_entry = it.next(); if (current_entry.sameSource(dummy) != 0) { candidate_targets.add(new Target(current_entry.tl_new, current_entry.pos_new)); } } return candidate_targets.toArray(new Target[candidate_targets.size()]); } /* ========================================================================== Internal Classes to provide a way to put entries into the tables ========================================================================== */ public class CountEntry implements XMLSerializable, TwoStageLoader { Sign tl; int pos; Node destination; boolean light; Sign tl_new; int pos_new; int value; TwoStageLoaderData loadData = new TwoStageLoaderData(); String parentName = "model.tlc"; CountEntry(Sign _tl, int _pos, Node _destination, boolean _light, Sign _tl_new, int _pos_new) { tl = _tl; pos = _pos; destination = _destination; light = _light; tl_new = _tl_new; pos_new = _pos_new; value = 1; } CountEntry() { // Empty constructor for loading } public void incrementValue() { value++; } public int getValue() { return value; } @Override public boolean equals(Object other) { if (other != null && other instanceof CountEntry) { CountEntry countnew = (CountEntry) other; if (!countnew.tl.equals(tl)) { return false; } if (countnew.pos != pos) { return false; } if (!countnew.destination.equals(destination)) { return false; } if (countnew.light != light) { return false; } if (!countnew.tl_new.equals(tl_new)) { return false; } if (countnew.pos_new != pos_new) { return false; } return true; } return false; } public int sameSource(CountEntry other) { if (other.tl.equals(tl) && other.pos == pos && other.light == light && other.destination.equals(destination)) { return value; } else { return 0; } } // XMLSerializable implementation of CountEntry @Override public void load(XMLElement myElement, XMLLoader loader) throws XMLTreeException, IOException, XMLInvalidInputException { pos = myElement.getAttribute("pos").getIntValue(); loadData.oldTlId = myElement.getAttribute("tl-id").getIntValue(); loadData.destNodeId = myElement.getAttribute("destination").getIntValue(); light = myElement.getAttribute("light").getBoolValue(); loadData.newTlId = myElement.getAttribute("newtl-id").getIntValue(); pos_new = myElement.getAttribute("new-pos").getIntValue(); value = myElement.getAttribute("value").getIntValue(); } @Override public XMLElement saveSelf() throws XMLCannotSaveException { XMLElement result = new XMLElement("count"); result.addAttribute(new XMLAttribute("tl-id", tl.getId())); result.addAttribute(new XMLAttribute("pos", pos)); result.addAttribute(new XMLAttribute("destination", destination.getId())); result.addAttribute(new XMLAttribute("light", light)); result.addAttribute(new XMLAttribute("newtl-id", tl_new.getId())); result.addAttribute(new XMLAttribute("new-pos", pos_new)); result.addAttribute(new XMLAttribute("value", value)); return result; } @Override public void saveChilds(XMLSaver saver) throws XMLTreeException, IOException, XMLCannotSaveException { // A count entry has no child objects } @Override public String getXMLName() { return parentName + ".count"; } @Override public void setParentName(String parentName) { this.parentName = parentName; } // TwoStageLoader implementation of CountEntry class TwoStageLoaderData { int oldTlId, newTlId, destNodeId; } @Override public void loadSecondStage(Map<String, Map<Integer, TwoStageLoader>> maps) { Map laneMap = maps.get("lane"); Map nodeMap = maps.get("node"); tl = ((DriveLane) (laneMap.get(loadData.oldTlId))).getSign(); tl_new = ((DriveLane) (laneMap.get(loadData.newTlId))).getSign(); destination = (Node) (nodeMap.get(loadData.destNodeId)); } } public class PEntry implements XMLSerializable, TwoStageLoader { Sign tl; int pos; Node destination; boolean light; Sign tl_new; int pos_new; float value; TwoStageLoaderData loadData = new TwoStageLoaderData(); String parentName = "model.tlc"; PEntry(Sign _tl, int _pos, Node _destination, boolean _light, Sign _tl_new, int _pos_new) { tl = _tl; pos = _pos; destination = _destination; light = _light; tl_new = _tl_new; pos_new = _pos_new; value = 0; } PEntry() { // Empty constructor for loading } public void setValue(float v) { value = v; } public float getValue() { return value; } @Override public boolean equals(Object other) { if (other != null && other instanceof PEntry) { PEntry pnew = (PEntry) other; if (!pnew.tl.equals(tl)) { return false; } if (pnew.pos != pos) { return false; } if (!pnew.destination.equals(destination)) { return false; } if (pnew.light != light) { return false; } if (!pnew.tl_new.equals(tl_new)) { return false; } if (pnew.pos_new != pos_new) { return false; } return true; } return false; } public float sameSource(CountEntry other) { if (other.tl.equals(tl) && other.pos == pos && other.light == light && other.destination.equals(destination)) { return value; } else { return -1; } } // XMLSerializable implementation of PEntry @Override public void load(XMLElement myElement, XMLLoader loader) throws XMLTreeException, IOException, XMLInvalidInputException { pos = myElement.getAttribute("pos").getIntValue(); loadData.oldTlId = myElement.getAttribute("tl-id").getIntValue(); loadData.destNodeId = myElement.getAttribute("destination").getIntValue(); light = myElement.getAttribute("light").getBoolValue(); loadData.newTlId = myElement.getAttribute("newtl-id").getIntValue(); pos_new = myElement.getAttribute("new-pos").getIntValue(); value = myElement.getAttribute("value").getFloatValue(); } @Override public XMLElement saveSelf() throws XMLCannotSaveException { XMLElement result = new XMLElement("pval"); result.addAttribute(new XMLAttribute("tl-id", tl.getId())); result.addAttribute(new XMLAttribute("pos", pos)); result.addAttribute(new XMLAttribute("destination", destination.getId())); result.addAttribute(new XMLAttribute("light", light)); result.addAttribute(new XMLAttribute("newtl-id", tl_new.getId())); result.addAttribute(new XMLAttribute("new-pos", pos_new)); result.addAttribute(new XMLAttribute("value", value)); return result; } @Override public void saveChilds(XMLSaver saver) throws XMLTreeException, IOException, XMLCannotSaveException { // A PEntry has no child objects } @Override public void setParentName(String parentName) { this.parentName = parentName; } @Override public String getXMLName() { return parentName + ".pval"; } // TwoStageLoader implementation of PEntry class TwoStageLoaderData { int oldTlId, newTlId, destNodeId; } @Override public void loadSecondStage(Map<String, Map<Integer, TwoStageLoader>> maps) { Map laneMap = maps.get("lane"); Map nodeMap = maps.get("node"); tl = ((DriveLane) (laneMap.get(loadData.oldTlId))).getSign(); tl_new = ((DriveLane) (laneMap.get(loadData.newTlId))).getSign(); destination = (Node) (nodeMap.get(loadData.destNodeId)); } } protected class Target implements XMLSerializable, TwoStageLoader { Sign tl; int pos; TwoStageLoaderData loadData = new TwoStageLoaderData(); String parentName = "model.tlc"; Target(Sign _tl, int _pos) { tl = _tl; pos = _pos; } Target() { // Empty constructor for loading } public Sign getTL() { return tl; } public int getP() { return pos; } @Override public boolean equals(Object other) { if (other != null && other instanceof Target) { Target qnew = (Target) other; if (!qnew.tl.equals(tl)) { return false; } if (qnew.pos != pos) { return false; } return true; } return false; } // XMLSerializable implementation of Target @Override public void load(XMLElement myElement, XMLLoader loader) throws XMLTreeException, IOException, XMLInvalidInputException { pos = myElement.getAttribute("pos").getIntValue(); loadData.tlId = myElement.getAttribute("tl-id").getIntValue(); } @Override public XMLElement saveSelf() throws XMLCannotSaveException { XMLElement result = new XMLElement("target"); result.addAttribute(new XMLAttribute("tl-id", tl.getId())); result.addAttribute(new XMLAttribute("pos", pos)); return result; } @Override public void saveChilds(XMLSaver saver) throws XMLTreeException, IOException, XMLCannotSaveException { // A Target has no child objects } @Override public String getXMLName() { return parentName + ".target"; } @Override public void setParentName(String parentName) { this.parentName = parentName; } // TwoStageLoader implementation of Target class TwoStageLoaderData { int tlId; } @Override public void loadSecondStage(Map<String, Map<Integer, TwoStageLoader>> maps) throws XMLInvalidInputException, XMLTreeException { Map laneMap = maps.get("lane"); tl = ((DriveLane) (laneMap.get(loadData.tlId))).getSign(); } } @Override public void showSettings(Controller c) { String[] descs = {"Gamma (discount factor)", "Random decision chance"}; float[] floats = {gamma, random_chance}; TLCSettings settings = new TLCSettings(descs, null, floats); settings = doSettingsDialog(c, settings); //OBS // Her burde laves et tjek p� om 0 < gamma < 1 og det samme med random chance gamma = settings.floats[0]; random_chance = settings.floats[1]; } // XMLSerializable, SecondStageLoader and InstantiationAssistant implementation @Override public void load(XMLElement myElement, XMLLoader loader) throws XMLTreeException, IOException, XMLInvalidInputException { super.load(myElement, loader); gamma = myElement.getAttribute("gamma").getFloatValue(); random_chance = myElement.getAttribute("random-chance").getFloatValue(); q_table = (float[][][][]) XMLArray.loadArray(this, loader); //v_table=(float[][][])XMLArray.loadArray(this,loader); count = (ArrayList<CountEntry>) XMLArray.loadArray(this, loader, this); //p_table=(ArrayList<PEntry>)XMLArray.loadArray(this,loader,this); } @Override public XMLElement saveSelf() throws XMLCannotSaveException { XMLElement result = super.saveSelf(); result.setName(shortXMLName); result.addAttribute(new XMLAttribute("random-chance", random_chance)); result.addAttribute(new XMLAttribute("gamma", gamma)); return result; } @Override public void saveChilds(XMLSaver saver) throws XMLTreeException, IOException, XMLCannotSaveException { super.saveChilds(saver); XMLArray.saveArray(q_table, this, saver, "q-table"); //XMLArray.saveArray(v_table,this,saver,"v-table"); XMLArray.saveArray(count, this, saver, "counts"); //XMLArray.saveArray(p_table,this,saver,"p-table"); } @Override public String getXMLName() { return "model." + shortXMLName; } @Override public void loadSecondStage(Map<String, Map<Integer, TwoStageLoader>> maps) throws XMLInvalidInputException, XMLTreeException { XMLUtils.loadSecondStage(count, maps); //XMLUtils.loadSecondStage(p_table.iterator(),maps); System.out.println("SL2 second stage load finished."); } @Override public boolean canCreateInstance(Class request) { return CountEntry.class.equals(request) || PEntry.class.equals(request); } @Override public Object createInstance(Class request) throws ClassNotFoundException, InstantiationException, IllegalAccessException { if (CountEntry.class.equals(request)) { return new CountEntry(); } else if (PEntry.class.equals(request)) { return new PEntry(); } else { throw new ClassNotFoundException("SL2 IntstantiationAssistant cannot make instances of " + request); } } }
CC007/TrafficLights
src/main/java/com/github/cc007/trafficlights/algo/tlc/SL2TLC.java
7,315
//red - green
line_comment
nl
/*----------------------------------------------------------------------- * Copyright (C) 2001 Green Light District Team, Utrecht University * Copyright of the TC1 algorithm (C) Marco Wiering, Utrecht University * * This program (Green Light District) is free software. * You may redistribute it and/or modify it under the terms * of the GNU General Public License as published by * the Free Software Foundation (version 2 or later). * * 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. * See the documentation of Green Light District for further information. * * Changed to use Sarsa(0) with random decision instead of DP - S. Louring *------------------------------------------------------------------------*/ package com.github.cc007.trafficlights.algo.tlc; import com.github.cc007.trafficlights.*; import com.github.cc007.trafficlights.algo.tlc.*; import com.github.cc007.trafficlights.infra.*; import com.github.cc007.trafficlights.xml.*; import java.io.IOException; import java.util.*; /** * * This controller will decide it's Q values for the traffic lights according to * the traffic situation on the lane connected to the TrafficLight. It will * learn how to alter it's outcome by reinforcement learning. * * @author Arne K, Jilles V, Søren Louring * @version 1.1 */ public class SL2TLC extends TCRL implements InstantiationAssistant { protected Infrastructure infrastructure; protected TrafficLight[][] tls; protected Node[] allnodes; protected int num_nodes; protected ArrayList<CountEntry> count; //, p_table; protected float[][][][] q_table; //sign, pos, des, color (red=0, green=1) protected static float gamma = 0.95f; //Discount Factor; used to decrease the influence of previous V values, that's why: 0 < gamma < 1 protected static float random_chance = 0.01f; //A random gain setting is chosen instead of the on the TLC dictates with this chance protected static float alpha = 0.7f; protected final static boolean red = false, green = true; protected final static int green_index = 0, red_index = 1; protected final static String shortXMLName = "tlc-sl2"; private Random random_number; protected float time_step = 0; /** * The constructor for TL controllers * * @param The model being used. */ public SL2TLC(Infrastructure infra) throws InfraException { super(infra); Node[] nodes = infra.getAllNodes(); //Moet Edge zijn eigenlijk, alleen testSimModel knalt er dan op int num_nodes = nodes.length; count = new ArrayList<>(); int numSigns = infra.getAllInboundLanes().size(); q_table = new float[numSigns + 1][][][]; int num_specialnodes = infra.getNumSpecialNodes(); for (int i = 0; i < nodes.length; i++) { Node n = nodes[i]; DriveLane[] dls = n.getInboundLanes(); for (int j = 0; j < dls.length; j++) { DriveLane d = dls[j]; Sign s = d.getSign(); int id = s.getId(); int num_pos_on_dl = d.getCompleteLength(); q_table[id] = new float[num_pos_on_dl][][]; for (int k = 0; k < num_pos_on_dl; k++) { q_table[id][k] = new float[num_specialnodes][]; for (int l = 0; l < q_table[id][k].length; l++) { q_table[id][k][l] = new float[2]; q_table[id][k][l][0] = 0.0f; q_table[id][k][l][1] = 0.0f; //v_table[id][k][l]=0.0f; } } } } System.out.println("tl = " + numSigns); System.out.println("des = " + num_specialnodes); System.out.println("Alpha = " + alpha); random_number = new Random(GLDSim.seriesSeed[GLDSim.seriesSeedIndex]); } @Override public void reset() { for (int j = 0; j < q_table.length; j++) { if (q_table[j] != null) { for (int k = 0; k < q_table[j].length; k++) { if (q_table[j][k] != null) { for (int l = 0; l < q_table[j][k].length; l++) { if (q_table[j][k][l] != null) { q_table[j][k][l][0] = 0.0f; q_table[j][k][l][1] = 0.0f; } } } } } } System.out.println("Q table nulstillet."); } //Reset slut /** * Calculates how every traffic light should be switched Per node, per sign * the waiting roadusers are passed and per each roaduser the gain is * calculated. * * @param The TLDecision is a tuple consisting of a traffic light and a * reward (Q) value, for it to be green * @see gld.algo.tlc.TLDecision */ @Override public TLDecision[][] decideTLs() { int num_dec; int num_tld = tld.length; //Determine wheter it should be random or not boolean do_this_random = false; time_step++; random_chance = (1.0f / ((float) Math.sqrt(time_step))); if (random_number.nextFloat() < random_chance) { do_this_random = true; } for (int i = 0; i < num_tld; i++) { num_dec = tld[i].length; for (int j = 0; j < num_dec; j++) { Sign currenttl = tld[i][j].getTL(); float gain = 0; DriveLane currentlane = currenttl.getLane(); int waitingsize = currentlane.getNumRoadusersWaiting(); Iterator<Roaduser> queue = currentlane.getQueue().iterator(); if (!do_this_random) { for (; waitingsize > 0; waitingsize--) { Roaduser ru = queue.next(); int pos = ru.getPosition(); Node destination = ru.getDestNode(); gain += q_table[currenttl.getId()][pos][destination.getId()][1] - q_table[currenttl.getId()][pos][destination.getId()][0]; //red -<SUF> // System.out.println(gain + " "); } float q = gain; } else { gain = random_number.nextFloat(); } tld[i][j].setGain(gain); } } return tld; } @Override public void updateRoaduserMove(Roaduser ru, DriveLane prevlane, Sign prevsign, int prevpos, DriveLane dlanenow, Sign signnow, int posnow, PosMov[] posMovs, DriveLane desired, int penalty) { //When a roaduser leaves the city; this will if (dlanenow == null || signnow == null) { dlanenow = prevlane; signnow = prevsign; posnow = -1; return; // ?? is recalculation is not necessary ?? } //This ordening is important for the execution of the algorithm! if (prevsign.getType() == Sign.TRAFFICLIGHT && (signnow.getType() == Sign.TRAFFICLIGHT || signnow.getType() == Sign.NO_SIGN)) { Node dest = ru.getDestNode(); recalcQ(prevsign, prevpos, dest, prevsign.mayDrive(), signnow, posnow, signnow.mayDrive(), posMovs, penalty); } } protected void recalcQ(Sign tl, int pos, Node destination, boolean light, Sign tl_new, int pos_new, boolean light_new, PosMov[] posMovs, int penalty) { /* Recalculate the Q values, only one PEntry has changed, meaning also only 1 QEntry has to change */ int R; float oldQvalue = 0; float Qmark = 0; float newQvalue = 0; R = penalty + rewardFunction(tl_new, pos_new, posMovs); try { oldQvalue = q_table[tl.getId()][pos][destination.getId()][light ? green_index : red_index]; Qmark = q_table[tl_new.getId()][pos_new][destination.getId()][light_new ? green_index : red_index];// Q( [ tl' , p' ] , L') } catch (Exception e) { System.out.println("ERROR"); System.out.println("tl: " + tl.getId()); System.out.println("pos:" + pos); System.out.println("des:" + destination.getId()); } newQvalue = oldQvalue + alpha * (R + gamma * Qmark - oldQvalue); q_table[tl.getId()][pos][destination.getId()][light ? green_index : red_index] = newQvalue; } /* ========================================================================== Additional methods, used by the recalc methods ========================================================================== */ protected int rewardFunction(Sign tl_new, int pos_new, PosMov[] posMovs) { //Ok, the reward function is actually very simple; it searches for the tuple (tl_new, pos_new) in the given set int size = posMovs.length; for (int i = 0; i < size; i++) { if (posMovs[i].tlId == tl_new.getId() && posMovs[i].pos == pos_new) { return 0; } } /*int size = possiblelanes.length; for(int i=0; i<size; i++) { if( possiblelanes[i].equals(tl_new.getLane()) ) { if(ranges[i].x < pos_new) { if(ranges[i].y > pos_new) { return 0; } } } }*/ return 1; } protected Target[] ownedTargets(Sign tl, int pos, Node des, boolean light) { //This method will determine to which destinations you can go starting at this source represented in this QEntry CountEntry dummy = new CountEntry(tl, pos, des, light, tl, pos); Target[] ownedtargets; ArrayList<Target> candidate_targets; candidate_targets = new ArrayList<>(); //Use the count table to sort this out, we need all Targets from //Only the elements in the count table are used, other just give a P Iterator<CountEntry> it = count.iterator(); while (it.hasNext()) { CountEntry current_entry = it.next(); if (current_entry.sameSource(dummy) != 0) { candidate_targets.add(new Target(current_entry.tl_new, current_entry.pos_new)); } } return candidate_targets.toArray(new Target[candidate_targets.size()]); } /* ========================================================================== Internal Classes to provide a way to put entries into the tables ========================================================================== */ public class CountEntry implements XMLSerializable, TwoStageLoader { Sign tl; int pos; Node destination; boolean light; Sign tl_new; int pos_new; int value; TwoStageLoaderData loadData = new TwoStageLoaderData(); String parentName = "model.tlc"; CountEntry(Sign _tl, int _pos, Node _destination, boolean _light, Sign _tl_new, int _pos_new) { tl = _tl; pos = _pos; destination = _destination; light = _light; tl_new = _tl_new; pos_new = _pos_new; value = 1; } CountEntry() { // Empty constructor for loading } public void incrementValue() { value++; } public int getValue() { return value; } @Override public boolean equals(Object other) { if (other != null && other instanceof CountEntry) { CountEntry countnew = (CountEntry) other; if (!countnew.tl.equals(tl)) { return false; } if (countnew.pos != pos) { return false; } if (!countnew.destination.equals(destination)) { return false; } if (countnew.light != light) { return false; } if (!countnew.tl_new.equals(tl_new)) { return false; } if (countnew.pos_new != pos_new) { return false; } return true; } return false; } public int sameSource(CountEntry other) { if (other.tl.equals(tl) && other.pos == pos && other.light == light && other.destination.equals(destination)) { return value; } else { return 0; } } // XMLSerializable implementation of CountEntry @Override public void load(XMLElement myElement, XMLLoader loader) throws XMLTreeException, IOException, XMLInvalidInputException { pos = myElement.getAttribute("pos").getIntValue(); loadData.oldTlId = myElement.getAttribute("tl-id").getIntValue(); loadData.destNodeId = myElement.getAttribute("destination").getIntValue(); light = myElement.getAttribute("light").getBoolValue(); loadData.newTlId = myElement.getAttribute("newtl-id").getIntValue(); pos_new = myElement.getAttribute("new-pos").getIntValue(); value = myElement.getAttribute("value").getIntValue(); } @Override public XMLElement saveSelf() throws XMLCannotSaveException { XMLElement result = new XMLElement("count"); result.addAttribute(new XMLAttribute("tl-id", tl.getId())); result.addAttribute(new XMLAttribute("pos", pos)); result.addAttribute(new XMLAttribute("destination", destination.getId())); result.addAttribute(new XMLAttribute("light", light)); result.addAttribute(new XMLAttribute("newtl-id", tl_new.getId())); result.addAttribute(new XMLAttribute("new-pos", pos_new)); result.addAttribute(new XMLAttribute("value", value)); return result; } @Override public void saveChilds(XMLSaver saver) throws XMLTreeException, IOException, XMLCannotSaveException { // A count entry has no child objects } @Override public String getXMLName() { return parentName + ".count"; } @Override public void setParentName(String parentName) { this.parentName = parentName; } // TwoStageLoader implementation of CountEntry class TwoStageLoaderData { int oldTlId, newTlId, destNodeId; } @Override public void loadSecondStage(Map<String, Map<Integer, TwoStageLoader>> maps) { Map laneMap = maps.get("lane"); Map nodeMap = maps.get("node"); tl = ((DriveLane) (laneMap.get(loadData.oldTlId))).getSign(); tl_new = ((DriveLane) (laneMap.get(loadData.newTlId))).getSign(); destination = (Node) (nodeMap.get(loadData.destNodeId)); } } public class PEntry implements XMLSerializable, TwoStageLoader { Sign tl; int pos; Node destination; boolean light; Sign tl_new; int pos_new; float value; TwoStageLoaderData loadData = new TwoStageLoaderData(); String parentName = "model.tlc"; PEntry(Sign _tl, int _pos, Node _destination, boolean _light, Sign _tl_new, int _pos_new) { tl = _tl; pos = _pos; destination = _destination; light = _light; tl_new = _tl_new; pos_new = _pos_new; value = 0; } PEntry() { // Empty constructor for loading } public void setValue(float v) { value = v; } public float getValue() { return value; } @Override public boolean equals(Object other) { if (other != null && other instanceof PEntry) { PEntry pnew = (PEntry) other; if (!pnew.tl.equals(tl)) { return false; } if (pnew.pos != pos) { return false; } if (!pnew.destination.equals(destination)) { return false; } if (pnew.light != light) { return false; } if (!pnew.tl_new.equals(tl_new)) { return false; } if (pnew.pos_new != pos_new) { return false; } return true; } return false; } public float sameSource(CountEntry other) { if (other.tl.equals(tl) && other.pos == pos && other.light == light && other.destination.equals(destination)) { return value; } else { return -1; } } // XMLSerializable implementation of PEntry @Override public void load(XMLElement myElement, XMLLoader loader) throws XMLTreeException, IOException, XMLInvalidInputException { pos = myElement.getAttribute("pos").getIntValue(); loadData.oldTlId = myElement.getAttribute("tl-id").getIntValue(); loadData.destNodeId = myElement.getAttribute("destination").getIntValue(); light = myElement.getAttribute("light").getBoolValue(); loadData.newTlId = myElement.getAttribute("newtl-id").getIntValue(); pos_new = myElement.getAttribute("new-pos").getIntValue(); value = myElement.getAttribute("value").getFloatValue(); } @Override public XMLElement saveSelf() throws XMLCannotSaveException { XMLElement result = new XMLElement("pval"); result.addAttribute(new XMLAttribute("tl-id", tl.getId())); result.addAttribute(new XMLAttribute("pos", pos)); result.addAttribute(new XMLAttribute("destination", destination.getId())); result.addAttribute(new XMLAttribute("light", light)); result.addAttribute(new XMLAttribute("newtl-id", tl_new.getId())); result.addAttribute(new XMLAttribute("new-pos", pos_new)); result.addAttribute(new XMLAttribute("value", value)); return result; } @Override public void saveChilds(XMLSaver saver) throws XMLTreeException, IOException, XMLCannotSaveException { // A PEntry has no child objects } @Override public void setParentName(String parentName) { this.parentName = parentName; } @Override public String getXMLName() { return parentName + ".pval"; } // TwoStageLoader implementation of PEntry class TwoStageLoaderData { int oldTlId, newTlId, destNodeId; } @Override public void loadSecondStage(Map<String, Map<Integer, TwoStageLoader>> maps) { Map laneMap = maps.get("lane"); Map nodeMap = maps.get("node"); tl = ((DriveLane) (laneMap.get(loadData.oldTlId))).getSign(); tl_new = ((DriveLane) (laneMap.get(loadData.newTlId))).getSign(); destination = (Node) (nodeMap.get(loadData.destNodeId)); } } protected class Target implements XMLSerializable, TwoStageLoader { Sign tl; int pos; TwoStageLoaderData loadData = new TwoStageLoaderData(); String parentName = "model.tlc"; Target(Sign _tl, int _pos) { tl = _tl; pos = _pos; } Target() { // Empty constructor for loading } public Sign getTL() { return tl; } public int getP() { return pos; } @Override public boolean equals(Object other) { if (other != null && other instanceof Target) { Target qnew = (Target) other; if (!qnew.tl.equals(tl)) { return false; } if (qnew.pos != pos) { return false; } return true; } return false; } // XMLSerializable implementation of Target @Override public void load(XMLElement myElement, XMLLoader loader) throws XMLTreeException, IOException, XMLInvalidInputException { pos = myElement.getAttribute("pos").getIntValue(); loadData.tlId = myElement.getAttribute("tl-id").getIntValue(); } @Override public XMLElement saveSelf() throws XMLCannotSaveException { XMLElement result = new XMLElement("target"); result.addAttribute(new XMLAttribute("tl-id", tl.getId())); result.addAttribute(new XMLAttribute("pos", pos)); return result; } @Override public void saveChilds(XMLSaver saver) throws XMLTreeException, IOException, XMLCannotSaveException { // A Target has no child objects } @Override public String getXMLName() { return parentName + ".target"; } @Override public void setParentName(String parentName) { this.parentName = parentName; } // TwoStageLoader implementation of Target class TwoStageLoaderData { int tlId; } @Override public void loadSecondStage(Map<String, Map<Integer, TwoStageLoader>> maps) throws XMLInvalidInputException, XMLTreeException { Map laneMap = maps.get("lane"); tl = ((DriveLane) (laneMap.get(loadData.tlId))).getSign(); } } @Override public void showSettings(Controller c) { String[] descs = {"Gamma (discount factor)", "Random decision chance"}; float[] floats = {gamma, random_chance}; TLCSettings settings = new TLCSettings(descs, null, floats); settings = doSettingsDialog(c, settings); //OBS // Her burde laves et tjek p� om 0 < gamma < 1 og det samme med random chance gamma = settings.floats[0]; random_chance = settings.floats[1]; } // XMLSerializable, SecondStageLoader and InstantiationAssistant implementation @Override public void load(XMLElement myElement, XMLLoader loader) throws XMLTreeException, IOException, XMLInvalidInputException { super.load(myElement, loader); gamma = myElement.getAttribute("gamma").getFloatValue(); random_chance = myElement.getAttribute("random-chance").getFloatValue(); q_table = (float[][][][]) XMLArray.loadArray(this, loader); //v_table=(float[][][])XMLArray.loadArray(this,loader); count = (ArrayList<CountEntry>) XMLArray.loadArray(this, loader, this); //p_table=(ArrayList<PEntry>)XMLArray.loadArray(this,loader,this); } @Override public XMLElement saveSelf() throws XMLCannotSaveException { XMLElement result = super.saveSelf(); result.setName(shortXMLName); result.addAttribute(new XMLAttribute("random-chance", random_chance)); result.addAttribute(new XMLAttribute("gamma", gamma)); return result; } @Override public void saveChilds(XMLSaver saver) throws XMLTreeException, IOException, XMLCannotSaveException { super.saveChilds(saver); XMLArray.saveArray(q_table, this, saver, "q-table"); //XMLArray.saveArray(v_table,this,saver,"v-table"); XMLArray.saveArray(count, this, saver, "counts"); //XMLArray.saveArray(p_table,this,saver,"p-table"); } @Override public String getXMLName() { return "model." + shortXMLName; } @Override public void loadSecondStage(Map<String, Map<Integer, TwoStageLoader>> maps) throws XMLInvalidInputException, XMLTreeException { XMLUtils.loadSecondStage(count, maps); //XMLUtils.loadSecondStage(p_table.iterator(),maps); System.out.println("SL2 second stage load finished."); } @Override public boolean canCreateInstance(Class request) { return CountEntry.class.equals(request) || PEntry.class.equals(request); } @Override public Object createInstance(Class request) throws ClassNotFoundException, InstantiationException, IllegalAccessException { if (CountEntry.class.equals(request)) { return new CountEntry(); } else if (PEntry.class.equals(request)) { return new PEntry(); } else { throw new ClassNotFoundException("SL2 IntstantiationAssistant cannot make instances of " + request); } } }
131603_0
/** * */ package nl.ipo.cds.domain; import static javax.persistence.EnumType.STRING; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.validation.constraints.NotNull; import nl.ipo.cds.domain.RefreshPolicy; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; /** * Dataset koppelt een Job aan Bronhouder en DatasetType.<br> * <em>Stamtabel<em>. * * @author Rob * */ @Entity //@Table(name="dataset", schema="manager") public class Dataset implements Identity { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @ManyToOne private DatasetType type; @ManyToOne private Bronhouder bronhouder; @NotNull private String uuid; @NotNull private Boolean actief = true; private String naam; // W1502 019 @Enumerated(STRING) @Column(nullable=false, columnDefinition="text default 'MANUAL'") private RefreshPolicy refreshPolicy; /** * @return the id */ @Override public Long getId() { return id; } /** * @param id * the id to set */ public void setId(Long id) { this.id = id; } /** * @return the datasetType */ public DatasetType getDatasetType() { return type; } /** * @param datasetType * the datasetType to set */ public void setDatasetType(DatasetType datasetType) { this.type = datasetType; } /** * @return the bronhouder */ public Bronhouder getBronhouder() { return bronhouder; } /** * @param bronhouder * the bronhouder to set */ public void setBronhouder(Bronhouder bronhouder) { this.bronhouder = bronhouder; } /** * @return the uuid */ public String getUuid() { return uuid; } /** * @param uuid the uuid to set */ public void setUuid(String uuid) { this.uuid = uuid; } /** * @return the actief */ public Boolean getActief() { return actief; } /** * @param actief the actief to set */ public void setActief(Boolean actief) { this.actief = actief; } public String getNaam() { return naam; } public void setNaam(String naam) { this.naam = naam; } // W1502 019 public void setRefreshPolicy(RefreshPolicy refreshPolicy) { // TODO Auto-generated method stub this.refreshPolicy = refreshPolicy; } // W1502 019 public RefreshPolicy getRefreshPolicy(){ return refreshPolicy; } public String toString(){ return "## Dataset <Actief="+actief+">(id: " + id + ", uuid: " + uuid + ", type: " + type + ", bronhouder: " + bronhouder + ", refreshPolicy: " + refreshPolicy + ")"; } @Override public boolean equals(Object obj) { if (obj instanceof Dataset == false) { return false; } if (this == obj) { return true; } final Dataset otherObject = (Dataset) obj; return new EqualsBuilder() .append(this.id, otherObject.id) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder() .append(this.id) .toHashCode(); } }
CDS-INSPIRE/InSpider
domain/src/main/java/nl/ipo/cds/domain/Dataset.java
1,224
/** * Dataset koppelt een Job aan Bronhouder en DatasetType.<br> * <em>Stamtabel<em>. * * @author Rob * */
block_comment
nl
/** * */ package nl.ipo.cds.domain; import static javax.persistence.EnumType.STRING; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.validation.constraints.NotNull; import nl.ipo.cds.domain.RefreshPolicy; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; /** * Dataset koppelt een<SUF>*/ @Entity //@Table(name="dataset", schema="manager") public class Dataset implements Identity { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @ManyToOne private DatasetType type; @ManyToOne private Bronhouder bronhouder; @NotNull private String uuid; @NotNull private Boolean actief = true; private String naam; // W1502 019 @Enumerated(STRING) @Column(nullable=false, columnDefinition="text default 'MANUAL'") private RefreshPolicy refreshPolicy; /** * @return the id */ @Override public Long getId() { return id; } /** * @param id * the id to set */ public void setId(Long id) { this.id = id; } /** * @return the datasetType */ public DatasetType getDatasetType() { return type; } /** * @param datasetType * the datasetType to set */ public void setDatasetType(DatasetType datasetType) { this.type = datasetType; } /** * @return the bronhouder */ public Bronhouder getBronhouder() { return bronhouder; } /** * @param bronhouder * the bronhouder to set */ public void setBronhouder(Bronhouder bronhouder) { this.bronhouder = bronhouder; } /** * @return the uuid */ public String getUuid() { return uuid; } /** * @param uuid the uuid to set */ public void setUuid(String uuid) { this.uuid = uuid; } /** * @return the actief */ public Boolean getActief() { return actief; } /** * @param actief the actief to set */ public void setActief(Boolean actief) { this.actief = actief; } public String getNaam() { return naam; } public void setNaam(String naam) { this.naam = naam; } // W1502 019 public void setRefreshPolicy(RefreshPolicy refreshPolicy) { // TODO Auto-generated method stub this.refreshPolicy = refreshPolicy; } // W1502 019 public RefreshPolicy getRefreshPolicy(){ return refreshPolicy; } public String toString(){ return "## Dataset <Actief="+actief+">(id: " + id + ", uuid: " + uuid + ", type: " + type + ", bronhouder: " + bronhouder + ", refreshPolicy: " + refreshPolicy + ")"; } @Override public boolean equals(Object obj) { if (obj instanceof Dataset == false) { return false; } if (this == obj) { return true; } final Dataset otherObject = (Dataset) obj; return new EqualsBuilder() .append(this.id, otherObject.id) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder() .append(this.id) .toHashCode(); } }
202331_1
package nl.ipo.cds.etl.theme.buisleidingen; import java.util.ArrayList; import java.util.List; import nl.idgis.commons.jobexecutor.JobLogger.LogLevel; import nl.ipo.cds.etl.ValidatorMessageKey; import nl.ipo.cds.validation.AttributeExpression; import nl.ipo.cds.validation.Expression; public enum Message implements ValidatorMessageKey<Message, Context> { TRANSPORTROUTE_ID_NULL, // id TRANSPORTROUTE_ID_EMPTY, // id TRANSPORTROUTE_ID_TOO_LONG, // id, maxLength TRANSPORTROUTEDEEL_ID_NULL, // id TRANSPORTROUTEDEEL_ID_EMPTY, // id TRANSPORTROUTEDEEL_ID_DUPLICATE, // id, transportroutedeelId TRANSPORTROUTEDEEL_ID_TOO_LONG, // id, transportroutedeelId, maxLength RISICOKAART_MEDEWERKER_NAAM_NULL, // id, transportroutedeelId RISICOKAART_MEDEWERKER_NAAM_EMPTY, // id, transportroutedeelId RISICOKAART_MEDEWERKER_NAAM_NOT_CONSTANT, // id, transportroutedeelId LAATSTE_MUTATIEDATUM_NULL, // id, transportroutedeelId LAATSTE_MUTATIEDATUM_FUTURE, // id, transportroutedeelId, laatsteMutatiedatum TRANSPORTROUTE_NAAM_NULL, // id, transportroutedeelId TRANSPORTROUTE_NAAM_EMPTY, // id, transportroutedeelId TRANSPORTROUTE_NAAM_CHANGED, // id, transportroutedeelId, transportrouteNaam BUISLEIDING_TYPE_NULL, // id, transportroutedeelId BUISLEIDING_TYPE_INVALID, // id, transportroutedeelId, buisleidingType OMSCHRIJVING_NULL, // id, transportroutedeelId OMSCHRIJVING_EMPTY, // id, transportroutedeelId OMSCHRIJVING_TOO_LONG, // id, transportroutedeelId, maxLength NAAM_EIGENAAR_NULL, // id, transportroutedeelId NAAM_EIGENAAR_EMPTY, // id, transportroutedeelId NAAM_EIGENAAR_TOO_LONG, // id, transportroutedeelId, maxLength UITWENDIGE_DIAMETER_NULL, // id, transportroutedeelId UITWENDIGE_DIAMETER_INVALID, // id, transportroutedeelId, uitwendigeDiameter WAND_DIKTE_NULL, // id, transportroutedeelId WAND_DIKTE_INVALID, // id, transportroutedeelId, wandDikte MAXIMALE_WERKDRUK_NULL, // id, transportroutedeelId MAXIMALE_WERKDRUK_INVALID, // id, transportroutedeelId, wandDikte GEOMETRIE_NULL, // id, transportroutedeelId GEOMETRIE_NOT_LINESTRING, // id, transportroutedeelId GEOMETRIE_NO_SRS, // id, transportroutedeelId GEOMETRIE_NOT_RD, // id, transportroutedeelId, srsName GEOMETRIE_POINT_DUPLICATION, // id, transportroutedeelId, lastLocation GEOMETRIE_DISCONTINUITY, // id, transportroutedeelId GEOMETRIE_SELF_INTERSECTION(LogLevel.WARNING), // id, transportroutedeelId, lastLocation LIGGING_BOVENKANT_NULL, // id, transportroutedeelId MATERIAAL_SOORT_NULL, // id, transportroutedeelId MATERIAAL_SOORT_EMPTY, // id, transportroutedeelId MATERIAAL_SOORT_TOO_LONG, // id, transportroutedeelId, maxLength CAS_NR_MAATGEVENDE_STOF_NULL, // id, transportroutedeelId CAS_NR_MAATGEVENDE_STOF_EMPTY, // id, transportroutedeelId CAS_NR_MAATGEVENDE_STOF_INVALID, // id, transportroutedeelId, casNrMaatgevendeStof TOELICHTING_MAATGEVENDE_STOF_NULL, // id, transportroutedeelId TOELICHTING_MAATGEVENDE_STOF_EMPTY, // id, transportroutedeelId STATUS_NULL, // id, transportroutedeelId STATUS_INVALID, // id, transportroutedeelId, status EFFECTAFSTAND_DODELIJK_INVALID, // id, transportroutedeelId, effectafstandDodelijk MAATGEVEND_SCENARIO_DODELIJK_INVALID,// id, transportroutedeelId, maatgevendScenarioDodelijk RISICOCONTOUR_TRANSPORTROUTE_NOT_FOUND, // id, transportrouteId RISICOCONTOUR_MISSING, // list of offending ids. RISICOCONTOUR_NULL, // id, transportroutedeelId RISICOCONTOUR_IN_M_AND_REDEN, // id, transportroutedeelId RISICOCONTOUR_IN_M_AND_RISICOCONTOUR,// id, transportroutedeelId RISICOCONTOUR_IN_M_INVALID, // id, transportroutedeelId, risicocontourInM RISICOCONTOUR_AND_GEEN_REDEN, // id, transportroutedeelId RISICOCONTOUR_EMPTY, RISICOCONTOUR_POINT_DUPLICATION, // id, transportroutedeelId, lastLocation RISICOCONTOUR_DISCONTINUITY, // id, transportroutedeelId RISICOCONTOUR_SELF_INTERSECTION, // id, transportroutedeelId, lastLocation RISICOCONTOUR_RING_NOT_CLOSED, // id, transportroutedeelId RISICOCONTOUR_RING_SELF_INTERSECTION, // id, transportroutedeelId, lastLocation RISICOCONTOUR_INTERIOR_RINGS_TOUCH, // id, transportroutedeelId, lastLocation RISICOCONTOUR_INTERIOR_RINGS_WITHIN, // id, transportroutedeelId RISICOCONTOUR_INTERIOR_DISCONNECTED, // id, transportroutedeelId RISICOCONTOUR_EXTERIOR_RING_CW(LogLevel.WARNING), // id, transportroutedeelId RISICOCONTOUR_INTERIOR_RING_CCW, // id, transportroutedeelId RISICOCONTOUR_INTERIOR_RING_TOUCHES_EXTERIOR, // id, transportroutedeelId, lastLocation RISICOCONTOUR_INTERIOR_RING_OUTSIDE_EXTERIOR, // id, transportroutedeelId RISICOCONTOUR_SRS_NULL, // id, transportroutedeelId RISICOCONTOUR_SRS_NOT_RD, // id, transportroutedeelId, srsName GEEN_RISICOCONTOUR_REDEN_EMPTY, // id, transportroutedeelId RISICOCONTOUR_NOT_MULTIPOLYGON, // id, transportroutedeelId RISICOCONTOUR_LAATSTE_MUTATIEDATUM_NULL, // id, transportrouteId RISICOCONTOUR_LAATSTE_MUTATIEDATUM_FUTURE, // id, transportrouteId, laatsteMutatiedatum RISICOCONTOUR_NOT_SET, // id, transportroutedeelId HAS_MORE_ERRORS(LogLevel.WARNING) ; private final LogLevel logLevel; Message () { this (LogLevel.ERROR); } Message (final LogLevel logLevel) { this.logLevel = logLevel; } @Override public boolean isBlocking() { return getLogLevel () == LogLevel.ERROR; } @Override public List<Expression<Message, Context, ?>> getMessageParameters() { final List<Expression<Message, Context, ?>> params = new ArrayList<> (); // RISICOCONTOUR_MISSING has no default parameters, it is a postcondition: if (this.equals (RISICOCONTOUR_MISSING)) { return params; } params.add (new AttributeExpression<Message, Context, String> ("id", String.class)); params.add (new AttributeExpression<Message, Context, String> ("id", String.class)); if (toString ().contains ("RISICOCONTOUR") || this == TRANSPORTROUTE_ID_EMPTY || this == TRANSPORTROUTE_ID_NULL || this == TRANSPORTROUTE_ID_TOO_LONG || this == TRANSPORTROUTEDEEL_ID_EMPTY || this == TRANSPORTROUTEDEEL_ID_NULL) { params.add (new AttributeExpression<Message, Context, String> ("transportrouteId", String.class)); } else { params.add (new AttributeExpression<Message, Context, String> ("transportroutedeelId", String.class)); } return params; } @Override public int getMaxMessageLog() { return 10; } @Override public boolean isAddToShapeFile() { return false; } @Override public LogLevel getLogLevel() { return logLevel; } @Override public Message getMaxMessageKey() { return HAS_MORE_ERRORS; } }
CDS-VRN/CDS-BIJ12
theme-buisleidingen/src/main/java/nl/ipo/cds/etl/theme/buisleidingen/Message.java
2,968
// id, transportroutedeelId, laatsteMutatiedatum
line_comment
nl
package nl.ipo.cds.etl.theme.buisleidingen; import java.util.ArrayList; import java.util.List; import nl.idgis.commons.jobexecutor.JobLogger.LogLevel; import nl.ipo.cds.etl.ValidatorMessageKey; import nl.ipo.cds.validation.AttributeExpression; import nl.ipo.cds.validation.Expression; public enum Message implements ValidatorMessageKey<Message, Context> { TRANSPORTROUTE_ID_NULL, // id TRANSPORTROUTE_ID_EMPTY, // id TRANSPORTROUTE_ID_TOO_LONG, // id, maxLength TRANSPORTROUTEDEEL_ID_NULL, // id TRANSPORTROUTEDEEL_ID_EMPTY, // id TRANSPORTROUTEDEEL_ID_DUPLICATE, // id, transportroutedeelId TRANSPORTROUTEDEEL_ID_TOO_LONG, // id, transportroutedeelId, maxLength RISICOKAART_MEDEWERKER_NAAM_NULL, // id, transportroutedeelId RISICOKAART_MEDEWERKER_NAAM_EMPTY, // id, transportroutedeelId RISICOKAART_MEDEWERKER_NAAM_NOT_CONSTANT, // id, transportroutedeelId LAATSTE_MUTATIEDATUM_NULL, // id, transportroutedeelId LAATSTE_MUTATIEDATUM_FUTURE, // id, transportroutedeelId,<SUF> TRANSPORTROUTE_NAAM_NULL, // id, transportroutedeelId TRANSPORTROUTE_NAAM_EMPTY, // id, transportroutedeelId TRANSPORTROUTE_NAAM_CHANGED, // id, transportroutedeelId, transportrouteNaam BUISLEIDING_TYPE_NULL, // id, transportroutedeelId BUISLEIDING_TYPE_INVALID, // id, transportroutedeelId, buisleidingType OMSCHRIJVING_NULL, // id, transportroutedeelId OMSCHRIJVING_EMPTY, // id, transportroutedeelId OMSCHRIJVING_TOO_LONG, // id, transportroutedeelId, maxLength NAAM_EIGENAAR_NULL, // id, transportroutedeelId NAAM_EIGENAAR_EMPTY, // id, transportroutedeelId NAAM_EIGENAAR_TOO_LONG, // id, transportroutedeelId, maxLength UITWENDIGE_DIAMETER_NULL, // id, transportroutedeelId UITWENDIGE_DIAMETER_INVALID, // id, transportroutedeelId, uitwendigeDiameter WAND_DIKTE_NULL, // id, transportroutedeelId WAND_DIKTE_INVALID, // id, transportroutedeelId, wandDikte MAXIMALE_WERKDRUK_NULL, // id, transportroutedeelId MAXIMALE_WERKDRUK_INVALID, // id, transportroutedeelId, wandDikte GEOMETRIE_NULL, // id, transportroutedeelId GEOMETRIE_NOT_LINESTRING, // id, transportroutedeelId GEOMETRIE_NO_SRS, // id, transportroutedeelId GEOMETRIE_NOT_RD, // id, transportroutedeelId, srsName GEOMETRIE_POINT_DUPLICATION, // id, transportroutedeelId, lastLocation GEOMETRIE_DISCONTINUITY, // id, transportroutedeelId GEOMETRIE_SELF_INTERSECTION(LogLevel.WARNING), // id, transportroutedeelId, lastLocation LIGGING_BOVENKANT_NULL, // id, transportroutedeelId MATERIAAL_SOORT_NULL, // id, transportroutedeelId MATERIAAL_SOORT_EMPTY, // id, transportroutedeelId MATERIAAL_SOORT_TOO_LONG, // id, transportroutedeelId, maxLength CAS_NR_MAATGEVENDE_STOF_NULL, // id, transportroutedeelId CAS_NR_MAATGEVENDE_STOF_EMPTY, // id, transportroutedeelId CAS_NR_MAATGEVENDE_STOF_INVALID, // id, transportroutedeelId, casNrMaatgevendeStof TOELICHTING_MAATGEVENDE_STOF_NULL, // id, transportroutedeelId TOELICHTING_MAATGEVENDE_STOF_EMPTY, // id, transportroutedeelId STATUS_NULL, // id, transportroutedeelId STATUS_INVALID, // id, transportroutedeelId, status EFFECTAFSTAND_DODELIJK_INVALID, // id, transportroutedeelId, effectafstandDodelijk MAATGEVEND_SCENARIO_DODELIJK_INVALID,// id, transportroutedeelId, maatgevendScenarioDodelijk RISICOCONTOUR_TRANSPORTROUTE_NOT_FOUND, // id, transportrouteId RISICOCONTOUR_MISSING, // list of offending ids. RISICOCONTOUR_NULL, // id, transportroutedeelId RISICOCONTOUR_IN_M_AND_REDEN, // id, transportroutedeelId RISICOCONTOUR_IN_M_AND_RISICOCONTOUR,// id, transportroutedeelId RISICOCONTOUR_IN_M_INVALID, // id, transportroutedeelId, risicocontourInM RISICOCONTOUR_AND_GEEN_REDEN, // id, transportroutedeelId RISICOCONTOUR_EMPTY, RISICOCONTOUR_POINT_DUPLICATION, // id, transportroutedeelId, lastLocation RISICOCONTOUR_DISCONTINUITY, // id, transportroutedeelId RISICOCONTOUR_SELF_INTERSECTION, // id, transportroutedeelId, lastLocation RISICOCONTOUR_RING_NOT_CLOSED, // id, transportroutedeelId RISICOCONTOUR_RING_SELF_INTERSECTION, // id, transportroutedeelId, lastLocation RISICOCONTOUR_INTERIOR_RINGS_TOUCH, // id, transportroutedeelId, lastLocation RISICOCONTOUR_INTERIOR_RINGS_WITHIN, // id, transportroutedeelId RISICOCONTOUR_INTERIOR_DISCONNECTED, // id, transportroutedeelId RISICOCONTOUR_EXTERIOR_RING_CW(LogLevel.WARNING), // id, transportroutedeelId RISICOCONTOUR_INTERIOR_RING_CCW, // id, transportroutedeelId RISICOCONTOUR_INTERIOR_RING_TOUCHES_EXTERIOR, // id, transportroutedeelId, lastLocation RISICOCONTOUR_INTERIOR_RING_OUTSIDE_EXTERIOR, // id, transportroutedeelId RISICOCONTOUR_SRS_NULL, // id, transportroutedeelId RISICOCONTOUR_SRS_NOT_RD, // id, transportroutedeelId, srsName GEEN_RISICOCONTOUR_REDEN_EMPTY, // id, transportroutedeelId RISICOCONTOUR_NOT_MULTIPOLYGON, // id, transportroutedeelId RISICOCONTOUR_LAATSTE_MUTATIEDATUM_NULL, // id, transportrouteId RISICOCONTOUR_LAATSTE_MUTATIEDATUM_FUTURE, // id, transportrouteId, laatsteMutatiedatum RISICOCONTOUR_NOT_SET, // id, transportroutedeelId HAS_MORE_ERRORS(LogLevel.WARNING) ; private final LogLevel logLevel; Message () { this (LogLevel.ERROR); } Message (final LogLevel logLevel) { this.logLevel = logLevel; } @Override public boolean isBlocking() { return getLogLevel () == LogLevel.ERROR; } @Override public List<Expression<Message, Context, ?>> getMessageParameters() { final List<Expression<Message, Context, ?>> params = new ArrayList<> (); // RISICOCONTOUR_MISSING has no default parameters, it is a postcondition: if (this.equals (RISICOCONTOUR_MISSING)) { return params; } params.add (new AttributeExpression<Message, Context, String> ("id", String.class)); params.add (new AttributeExpression<Message, Context, String> ("id", String.class)); if (toString ().contains ("RISICOCONTOUR") || this == TRANSPORTROUTE_ID_EMPTY || this == TRANSPORTROUTE_ID_NULL || this == TRANSPORTROUTE_ID_TOO_LONG || this == TRANSPORTROUTEDEEL_ID_EMPTY || this == TRANSPORTROUTEDEEL_ID_NULL) { params.add (new AttributeExpression<Message, Context, String> ("transportrouteId", String.class)); } else { params.add (new AttributeExpression<Message, Context, String> ("transportroutedeelId", String.class)); } return params; } @Override public int getMaxMessageLog() { return 10; } @Override public boolean isAddToShapeFile() { return false; } @Override public LogLevel getLogLevel() { return logLevel; } @Override public Message getMaxMessageKey() { return HAS_MORE_ERRORS; } }
35862_13
/** * */ package nl.ipo.cds.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.validation.constraints.NotNull; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; /** * Bronhouder bevat gegevens over bronhouders, die via de beheer applicatie * worden ingevoerd.<br> * <em>Stamtabel<em>. * * @author Rob * */ @Entity //@Table(name="bronhouder", schema="manager") public class Bronhouder implements Identity { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; /** vorm: 99xx <br> xx = CBS Provincie code<br> 20 Groningen<br> 21 Friesland<br> 22 Drenthe<br> 23 Overijssel<br> 24 Flevoland<br> 25 Gelderland<br> 26 Utrecht<br> 27 Noord-Holland<br> 28 Zuid-Holland<br> 29 Zeeland<br> 30 Noord-Brabant<br> 31 Limburg<br> */ @Column(columnDefinition = "varchar(64)", unique=true, nullable=false) private String code; @Column(unique=true, nullable=false) private String naam; @NotNull @Column (nullable = false, name = "contact_naam") private String contactNaam; @Column (name = "contact_adres") private String contactAdres; @Column (name = "contact_plaats") private String contactPlaats; @Column (name = "contact_postcode") private String contactPostcode; @Column (name = "contact_telefoonnummer") private String contactTelefoonnummer; @NotNull @Column (name = "contact_emailadres", nullable = false) private String contactEmailadres; @Column (name = "common_name", unique = true, nullable = false) private String commonName; /** * @return the id */ @Override public Long getId() { return id; } /** * @param id * the id to set */ public void setId(Long id) { this.id = id; } /** * @return the code */ public String getCode() { return code; } /** * @param code the code to set */ public void setCode(String code) { this.code = code; } /** * @return the provincie */ public String getNaam() { return naam; } /** * @param provincie * the provincie to set */ public void setNaam(String naam) { this.naam = naam; } /** * @return the naam */ public String getContactNaam() { return contactNaam; } /** * @param naam * the naam to set */ public void setContactNaam(String contactNaam) { this.contactNaam = contactNaam; } /** * @return the adres */ public String getContactAdres() { return contactAdres; } /** * @param adres * the adres to set */ public void setContactAdres(String contactAdres) { this.contactAdres = contactAdres; } /** * @return the plaats */ public String getContactPlaats() { return contactPlaats; } /** * @param plaats * the plaats to set */ public void setContactPlaats(String contactPlaats) { this.contactPlaats = contactPlaats; } /** * @return the postcode */ public String getContactPostcode() { return contactPostcode; } /** * @param postcode * the postcode to set */ public void setContactPostcode(String contactPostcode) { this.contactPostcode = contactPostcode; } /** * @return the telefoonnummer */ public String getContactTelefoonnummer() { return contactTelefoonnummer; } /** * @param telefoonnummer * the telefoonnummer to set */ public void setContactTelefoonnummer(String contactTelefoonnummer) { this.contactTelefoonnummer = contactTelefoonnummer; } /** * @return the emailadres */ public String getContactEmailadres() { return contactEmailadres; } /** * @param emailadres * the emailadres to set */ public void setContactEmailadres(String contactEmailadres) { this.contactEmailadres = contactEmailadres; } /** * Returns the "common name" of this bronhouder. The common name is used to identify * this entity in the LDAP server. * * @return This bronhouder's common name. */ public String getCommonName () { return commonName; } /** * Sets the "common name" of this bronhouder. The common name is used to identify * this entity in the LDAP server. * * @param commonName The new common name of this bronhouder. */ public void setCommonName (final String commonName) { this.commonName = commonName; } public String toString(){ return "## Bronhouder (id: " + id + ", contactNaam: " + contactNaam + ", contactAdres: " + contactAdres + ", " + contactPostcode + ", " + contactPlaats + ", email: " + contactEmailadres + ")"; } @Override public boolean equals(Object obj) { if (obj instanceof Bronhouder == false) { return false; } if (this == obj) { return true; } final Bronhouder otherObject = (Bronhouder) obj; return new EqualsBuilder() .append(this.id, otherObject.id) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder() .append(this.id) .toHashCode(); } }
CDS-VRN/InSpider
domain/src/main/java/nl/ipo/cds/domain/Bronhouder.java
1,951
/** * @param plaats * the plaats to set */
block_comment
nl
/** * */ package nl.ipo.cds.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.validation.constraints.NotNull; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; /** * Bronhouder bevat gegevens over bronhouders, die via de beheer applicatie * worden ingevoerd.<br> * <em>Stamtabel<em>. * * @author Rob * */ @Entity //@Table(name="bronhouder", schema="manager") public class Bronhouder implements Identity { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; /** vorm: 99xx <br> xx = CBS Provincie code<br> 20 Groningen<br> 21 Friesland<br> 22 Drenthe<br> 23 Overijssel<br> 24 Flevoland<br> 25 Gelderland<br> 26 Utrecht<br> 27 Noord-Holland<br> 28 Zuid-Holland<br> 29 Zeeland<br> 30 Noord-Brabant<br> 31 Limburg<br> */ @Column(columnDefinition = "varchar(64)", unique=true, nullable=false) private String code; @Column(unique=true, nullable=false) private String naam; @NotNull @Column (nullable = false, name = "contact_naam") private String contactNaam; @Column (name = "contact_adres") private String contactAdres; @Column (name = "contact_plaats") private String contactPlaats; @Column (name = "contact_postcode") private String contactPostcode; @Column (name = "contact_telefoonnummer") private String contactTelefoonnummer; @NotNull @Column (name = "contact_emailadres", nullable = false) private String contactEmailadres; @Column (name = "common_name", unique = true, nullable = false) private String commonName; /** * @return the id */ @Override public Long getId() { return id; } /** * @param id * the id to set */ public void setId(Long id) { this.id = id; } /** * @return the code */ public String getCode() { return code; } /** * @param code the code to set */ public void setCode(String code) { this.code = code; } /** * @return the provincie */ public String getNaam() { return naam; } /** * @param provincie * the provincie to set */ public void setNaam(String naam) { this.naam = naam; } /** * @return the naam */ public String getContactNaam() { return contactNaam; } /** * @param naam * the naam to set */ public void setContactNaam(String contactNaam) { this.contactNaam = contactNaam; } /** * @return the adres */ public String getContactAdres() { return contactAdres; } /** * @param adres * the adres to set */ public void setContactAdres(String contactAdres) { this.contactAdres = contactAdres; } /** * @return the plaats */ public String getContactPlaats() { return contactPlaats; } /** * @param plaats <SUF>*/ public void setContactPlaats(String contactPlaats) { this.contactPlaats = contactPlaats; } /** * @return the postcode */ public String getContactPostcode() { return contactPostcode; } /** * @param postcode * the postcode to set */ public void setContactPostcode(String contactPostcode) { this.contactPostcode = contactPostcode; } /** * @return the telefoonnummer */ public String getContactTelefoonnummer() { return contactTelefoonnummer; } /** * @param telefoonnummer * the telefoonnummer to set */ public void setContactTelefoonnummer(String contactTelefoonnummer) { this.contactTelefoonnummer = contactTelefoonnummer; } /** * @return the emailadres */ public String getContactEmailadres() { return contactEmailadres; } /** * @param emailadres * the emailadres to set */ public void setContactEmailadres(String contactEmailadres) { this.contactEmailadres = contactEmailadres; } /** * Returns the "common name" of this bronhouder. The common name is used to identify * this entity in the LDAP server. * * @return This bronhouder's common name. */ public String getCommonName () { return commonName; } /** * Sets the "common name" of this bronhouder. The common name is used to identify * this entity in the LDAP server. * * @param commonName The new common name of this bronhouder. */ public void setCommonName (final String commonName) { this.commonName = commonName; } public String toString(){ return "## Bronhouder (id: " + id + ", contactNaam: " + contactNaam + ", contactAdres: " + contactAdres + ", " + contactPostcode + ", " + contactPlaats + ", email: " + contactEmailadres + ")"; } @Override public boolean equals(Object obj) { if (obj instanceof Bronhouder == false) { return false; } if (this == obj) { return true; } final Bronhouder otherObject = (Bronhouder) obj; return new EqualsBuilder() .append(this.id, otherObject.id) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder() .append(this.id) .toHashCode(); } }
39069_9
/** * */ package nl.idgis.commons.convert.utils; import java.io.IOException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import javax.xml.stream.XMLStreamException; import nl.idgis.commons.utils.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.geotools.data.simple.SimpleFeatureCollection; import org.geotools.feature.DefaultFeatureCollection; import org.geotools.feature.simple.SimpleFeatureBuilder; import org.geotools.feature.simple.SimpleFeatureTypeBuilder; import org.geotools.geometry.jts.JTSFactoryFinder; import org.geotools.referencing.ReferencingFactoryFinder; import org.geotools.xml.PullParser; import org.opengis.feature.Property; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.referencing.crs.CRSAuthorityFactory; import org.xml.sax.SAXException; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.LineString; import com.vividsolutions.jts.geom.MultiLineString; import com.vividsolutions.jts.geom.MultiPoint; import com.vividsolutions.jts.geom.MultiPolygon; import com.vividsolutions.jts.geom.Point; import com.vividsolutions.jts.geom.Polygon; /** * @author eshuism 16 mei 2012 */ public class FeatureCollectionFactory { private static final int MAX_ATTR_NAME_LEN = 10; private static final String GEOMETRY_ATTR_NAME = "geom"; private static final Log log = LogFactory.getLog(FeatureCollectionFactory.class); String[] geometryNames = { "SHAPE", "geom", "geometry" }; /** * Create featureCollection based on geometry-errors of given job * * @param job * @return */ public SimpleFeatureCollection createFeatureCollection(PullParser parser) { log.debug("createFeatureCollection"); SimpleFeature f = null; SimpleFeatureBuilder builder = null; DefaultFeatureCollection featureCollection = new DefaultFeatureCollection(); /* * A list to collect features as we create them. */ List<SimpleFeature> features = new ArrayList<SimpleFeature>(); /* * GeometryFactory will be used to create the geometry attribute of each * feature (a Point object for the location) */ GeometryFactory geometryFactory = JTSFactoryFinder .getGeometryFactory(null); try { while ((f = (SimpleFeature) parser.parse()) != null) { // build a featuretype from the first feature if (builder == null) { SimpleFeatureType sft = createFeatureType(f); log.debug("SimpleFeatureType: " + StringUtils.maxLength(sft, 128)); builder = new SimpleFeatureBuilder(sft); } // add geometry // Geometry geometry = geometryFactory.createGeometry((Geometry) f // .getDefaultGeometry()); Geometry geometry = (Geometry) f.getDefaultGeometry(); log.debug("SimpleFeature geometry: " + StringUtils.maxLength(geometry, 64) + " ..."); builder.add(geometry); // add attributes int i = 0; Collection<Property> c = f.getProperties(); for (Iterator<Property> iterator = c.iterator(); iterator.hasNext();) { Property p = iterator.next(); String name = p.getName().toString(); boolean checkNames = checkString(name, geometryNames); if (!checkNames && p.getValue() != null) { builder.add(URLEncoder.encode(StringUtils.maxLength(p.getValue(), 255).trim(), "UTF-8")); log.debug(i++ + " + Attr: " + p.getName() + " = " + StringUtils.maxLength(p.getValue(), 64) + ""); } } SimpleFeature sf = builder.buildFeature(f.getID()); log.debug("SimpleFeature org : " + StringUtils.maxLength(f, 128)); log.debug("SimpleFeature built: " + StringUtils.maxLength(sf, 128)); featureCollection.add(sf); // features.add(sf); } } catch (XMLStreamException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } return featureCollection; // return new ListFeatureCollection(builder.getFeatureType(), features); } /** * Create the schema for your FeatureType cq shapefile */ private SimpleFeatureType createFeatureType(SimpleFeature f) { log.debug("createFeatureType from " + f); SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder(); builder.setName(f.getName()); // TODO remove hardcoded CRS try { CRSAuthorityFactory authorityFactory = ReferencingFactoryFinder .getCRSAuthorityFactory("epsg", null); builder.setCRS(authorityFactory .createCoordinateReferenceSystem("28992")); // <- Coordinate // reference // system } catch (Exception e) { throw new RuntimeException(e); } // Geometrie Object geom = f.getDefaultGeometry(); if (geom instanceof MultiPolygon){ log.debug("GEOMETRY TYPE: MultiPolygon"); builder.add(GEOMETRY_ATTR_NAME, MultiPolygon.class); } else if (geom instanceof Polygon){ log.debug("GEOMETRY TYPE: Polygon"); builder.add(GEOMETRY_ATTR_NAME, Polygon.class); } else if (geom instanceof MultiLineString){ log.debug("GEOMETRY TYPE: MultiLineString"); builder.add(GEOMETRY_ATTR_NAME, MultiLineString.class); } else if (geom instanceof LineString){ log.debug("GEOMETRY TYPE: LineString"); builder.add(GEOMETRY_ATTR_NAME, LineString.class); } else if (geom instanceof MultiPoint){ log.debug("GEOMETRY TYPE: MultiPoint"); builder.add(GEOMETRY_ATTR_NAME, MultiPoint.class); } else if (geom instanceof Point){ log.debug("GEOMETRY TYPE: Point"); builder.add(GEOMETRY_ATTR_NAME, Point.class); } else { log.error("NO TYPE FOR GEOMETRY " + geom); } builder.setDefaultGeometry(GEOMETRY_ATTR_NAME); // add attributes int i = 0; Collection<Property> c = f.getProperties(); for (Iterator<Property> iterator = c.iterator(); iterator.hasNext();) { Property p = iterator.next(); String name = p.getName().toString(); boolean checkNames = checkString(name, geometryNames); if (!checkNames && p.getValue() != null) { /* fout in ShapefileDataStore.createDbaseHeader(SimpleFeatureType) * waardoor attribuutnamen langer dan 10 chars * dezelfde kolomnaam kunnen krijgen. * De inhoud blijft dan leeg! */ if (name.length() > MAX_ATTR_NAME_LEN){ // restrict names to 8 or 9 chars + number name = name.substring(0, ((i < 10) ? (MAX_ATTR_NAME_LEN-1) : (MAX_ATTR_NAME_LEN-2))) + i; } builder.add(name, String.class); log.debug(i + " Attr: " + p.getName() + " ["+name+"] = " + p.getValue() + ""); i++; } } return builder.buildFeatureType(); } private boolean checkString(String stringToCheck, String... names) { for (int i = 0; i < names.length; i++) { if (stringToCheck.equalsIgnoreCase(names[i])) { return true; } } return false; } }
CDS-VRN/InSpider-commons
commons-convert/src/main/java/nl/idgis/commons/convert/utils/FeatureCollectionFactory.java
2,374
/* fout in ShapefileDataStore.createDbaseHeader(SimpleFeatureType) * waardoor attribuutnamen langer dan 10 chars * dezelfde kolomnaam kunnen krijgen. * De inhoud blijft dan leeg! */
block_comment
nl
/** * */ package nl.idgis.commons.convert.utils; import java.io.IOException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import javax.xml.stream.XMLStreamException; import nl.idgis.commons.utils.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.geotools.data.simple.SimpleFeatureCollection; import org.geotools.feature.DefaultFeatureCollection; import org.geotools.feature.simple.SimpleFeatureBuilder; import org.geotools.feature.simple.SimpleFeatureTypeBuilder; import org.geotools.geometry.jts.JTSFactoryFinder; import org.geotools.referencing.ReferencingFactoryFinder; import org.geotools.xml.PullParser; import org.opengis.feature.Property; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.referencing.crs.CRSAuthorityFactory; import org.xml.sax.SAXException; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.LineString; import com.vividsolutions.jts.geom.MultiLineString; import com.vividsolutions.jts.geom.MultiPoint; import com.vividsolutions.jts.geom.MultiPolygon; import com.vividsolutions.jts.geom.Point; import com.vividsolutions.jts.geom.Polygon; /** * @author eshuism 16 mei 2012 */ public class FeatureCollectionFactory { private static final int MAX_ATTR_NAME_LEN = 10; private static final String GEOMETRY_ATTR_NAME = "geom"; private static final Log log = LogFactory.getLog(FeatureCollectionFactory.class); String[] geometryNames = { "SHAPE", "geom", "geometry" }; /** * Create featureCollection based on geometry-errors of given job * * @param job * @return */ public SimpleFeatureCollection createFeatureCollection(PullParser parser) { log.debug("createFeatureCollection"); SimpleFeature f = null; SimpleFeatureBuilder builder = null; DefaultFeatureCollection featureCollection = new DefaultFeatureCollection(); /* * A list to collect features as we create them. */ List<SimpleFeature> features = new ArrayList<SimpleFeature>(); /* * GeometryFactory will be used to create the geometry attribute of each * feature (a Point object for the location) */ GeometryFactory geometryFactory = JTSFactoryFinder .getGeometryFactory(null); try { while ((f = (SimpleFeature) parser.parse()) != null) { // build a featuretype from the first feature if (builder == null) { SimpleFeatureType sft = createFeatureType(f); log.debug("SimpleFeatureType: " + StringUtils.maxLength(sft, 128)); builder = new SimpleFeatureBuilder(sft); } // add geometry // Geometry geometry = geometryFactory.createGeometry((Geometry) f // .getDefaultGeometry()); Geometry geometry = (Geometry) f.getDefaultGeometry(); log.debug("SimpleFeature geometry: " + StringUtils.maxLength(geometry, 64) + " ..."); builder.add(geometry); // add attributes int i = 0; Collection<Property> c = f.getProperties(); for (Iterator<Property> iterator = c.iterator(); iterator.hasNext();) { Property p = iterator.next(); String name = p.getName().toString(); boolean checkNames = checkString(name, geometryNames); if (!checkNames && p.getValue() != null) { builder.add(URLEncoder.encode(StringUtils.maxLength(p.getValue(), 255).trim(), "UTF-8")); log.debug(i++ + " + Attr: " + p.getName() + " = " + StringUtils.maxLength(p.getValue(), 64) + ""); } } SimpleFeature sf = builder.buildFeature(f.getID()); log.debug("SimpleFeature org : " + StringUtils.maxLength(f, 128)); log.debug("SimpleFeature built: " + StringUtils.maxLength(sf, 128)); featureCollection.add(sf); // features.add(sf); } } catch (XMLStreamException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } return featureCollection; // return new ListFeatureCollection(builder.getFeatureType(), features); } /** * Create the schema for your FeatureType cq shapefile */ private SimpleFeatureType createFeatureType(SimpleFeature f) { log.debug("createFeatureType from " + f); SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder(); builder.setName(f.getName()); // TODO remove hardcoded CRS try { CRSAuthorityFactory authorityFactory = ReferencingFactoryFinder .getCRSAuthorityFactory("epsg", null); builder.setCRS(authorityFactory .createCoordinateReferenceSystem("28992")); // <- Coordinate // reference // system } catch (Exception e) { throw new RuntimeException(e); } // Geometrie Object geom = f.getDefaultGeometry(); if (geom instanceof MultiPolygon){ log.debug("GEOMETRY TYPE: MultiPolygon"); builder.add(GEOMETRY_ATTR_NAME, MultiPolygon.class); } else if (geom instanceof Polygon){ log.debug("GEOMETRY TYPE: Polygon"); builder.add(GEOMETRY_ATTR_NAME, Polygon.class); } else if (geom instanceof MultiLineString){ log.debug("GEOMETRY TYPE: MultiLineString"); builder.add(GEOMETRY_ATTR_NAME, MultiLineString.class); } else if (geom instanceof LineString){ log.debug("GEOMETRY TYPE: LineString"); builder.add(GEOMETRY_ATTR_NAME, LineString.class); } else if (geom instanceof MultiPoint){ log.debug("GEOMETRY TYPE: MultiPoint"); builder.add(GEOMETRY_ATTR_NAME, MultiPoint.class); } else if (geom instanceof Point){ log.debug("GEOMETRY TYPE: Point"); builder.add(GEOMETRY_ATTR_NAME, Point.class); } else { log.error("NO TYPE FOR GEOMETRY " + geom); } builder.setDefaultGeometry(GEOMETRY_ATTR_NAME); // add attributes int i = 0; Collection<Property> c = f.getProperties(); for (Iterator<Property> iterator = c.iterator(); iterator.hasNext();) { Property p = iterator.next(); String name = p.getName().toString(); boolean checkNames = checkString(name, geometryNames); if (!checkNames && p.getValue() != null) { /* fout in ShapefileDataStore.createDbaseHeader(SimpleFeatureType) <SUF>*/ if (name.length() > MAX_ATTR_NAME_LEN){ // restrict names to 8 or 9 chars + number name = name.substring(0, ((i < 10) ? (MAX_ATTR_NAME_LEN-1) : (MAX_ATTR_NAME_LEN-2))) + i; } builder.add(name, String.class); log.debug(i + " Attr: " + p.getName() + " ["+name+"] = " + p.getValue() + ""); i++; } } return builder.buildFeatureType(); } private boolean checkString(String stringToCheck, String... names) { for (int i = 0; i < names.length; i++) { if (stringToCheck.equalsIgnoreCase(names[i])) { return true; } } return false; } }
201795_0
package cz.metacentrum.perun.core.api; import cz.metacentrum.perun.core.api.exceptions.InternalErrorException; import java.util.UUID; /** * Vo entity. */ public class Vo extends Auditable implements Comparable<PerunBean>, HasUuid { private String name; private String shortName; private UUID uuid; public Vo() { } public Vo(int id, String name, String shortName) { super(id); if (name == null) { throw new InternalErrorException(new NullPointerException("name is null")); } if (shortName == null) { throw new InternalErrorException(new NullPointerException("shortName is null")); } this.name = name; this.shortName = shortName; } @Deprecated public Vo(int id, String name, String shortName, String createdAt, String createdBy, String modifiedAt, String modifiedBy) { super(id, createdAt, createdBy, modifiedAt, modifiedBy, null, null); if (name == null) { throw new InternalErrorException(new NullPointerException("name is null")); } if (shortName == null) { throw new InternalErrorException(new NullPointerException("shortName is null")); } this.name = name; this.shortName = shortName; } public Vo(int id, String name, String shortName, String createdAt, String createdBy, String modifiedAt, String modifiedBy, Integer createdByUid, Integer modifiedByUid) { super(id, createdAt, createdBy, modifiedAt, modifiedBy, createdByUid, modifiedByUid); if (name == null) { throw new InternalErrorException(new NullPointerException("name is null")); } if (shortName == null) { throw new InternalErrorException(new NullPointerException("shortName is null")); } this.name = name; this.shortName = shortName; } public Vo(int id, UUID uuid, String name, String shortName, String createdAt, String createdBy, String modifiedAt, String modifiedBy, Integer createdByUid, Integer modifiedByUid) { super(id, createdAt, createdBy, modifiedAt, modifiedBy, createdByUid, modifiedByUid); if (name == null) { throw new InternalErrorException(new NullPointerException("name is null")); } if (shortName == null) { throw new InternalErrorException(new NullPointerException("shortName is null")); } this.name = name; this.shortName = shortName; this.uuid = uuid; } @Override public int compareTo(PerunBean perunBean) { if (perunBean == null) { throw new NullPointerException("PerunBean to compare with is null."); } if (perunBean instanceof Vo) { Vo vo = (Vo) perunBean; if (this.getName() == null && vo.getName() != null) { return -1; } if (vo.getName() == null && this.getName() != null) { return 1; } if (this.getName() == null && vo.getName() == null) { return 0; } return this.getName().compareToIgnoreCase(vo.getName()); } else { return (this.getId() - perunBean.getId()); } } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Vo other = (Vo) obj; if (this.getId() != other.getId()) { return false; } if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { return false; } if ((this.shortName == null) ? (other.shortName != null) : !this.shortName.equals(other.shortName)) { return false; } return true; } public String getName() { return name; } public void setName(String name) { if (name == null) { throw new InternalErrorException(new NullPointerException("name is null")); } this.name = name; } public String getShortName() { return shortName; } public void setShortName(String shortName) { if (shortName == null) { throw new InternalErrorException(new NullPointerException("shortName is null")); } this.shortName = shortName; } @Override public UUID getUuid() { return uuid; } public void setUuid(UUID uuid) { this.uuid = uuid; } @Override public int hashCode() { int hash = 7; hash = 53 * hash + this.getId(); hash = 53 * hash + (this.name != null ? this.name.hashCode() : 0); hash = 53 * hash + (this.shortName != null ? this.shortName.hashCode() : 0); return hash; } @Override public String serializeToString() { StringBuilder str = new StringBuilder(); return str.append(this.getClass().getSimpleName()).append(":[").append("id=<").append(getId()).append(">") .append(", uuid=<").append(getUuid()).append(">").append(", name=<") .append(getName() == null ? "\\0" : BeansUtils.createEscaping(getName())).append(">").append(", shortName=<") .append(getShortName() == null ? "\\0" : BeansUtils.createEscaping(getShortName())).append(">").append(']') .toString(); } @Override public String toString() { StringBuilder str = new StringBuilder(); return str.append(this.getClass().getSimpleName()).append(":[").append("id='").append(this.getId()).append('\'') .append(", uuid='").append(uuid).append('\'').append(", name='").append(name).append('\'') .append(", shortName='").append(shortName).append('\'').append(']').toString(); } }
CESNET/perun
perun-base/src/main/java/cz/metacentrum/perun/core/api/Vo.java
1,673
/** * Vo entity. */
block_comment
nl
package cz.metacentrum.perun.core.api; import cz.metacentrum.perun.core.api.exceptions.InternalErrorException; import java.util.UUID; /** * Vo entity. <SUF>*/ public class Vo extends Auditable implements Comparable<PerunBean>, HasUuid { private String name; private String shortName; private UUID uuid; public Vo() { } public Vo(int id, String name, String shortName) { super(id); if (name == null) { throw new InternalErrorException(new NullPointerException("name is null")); } if (shortName == null) { throw new InternalErrorException(new NullPointerException("shortName is null")); } this.name = name; this.shortName = shortName; } @Deprecated public Vo(int id, String name, String shortName, String createdAt, String createdBy, String modifiedAt, String modifiedBy) { super(id, createdAt, createdBy, modifiedAt, modifiedBy, null, null); if (name == null) { throw new InternalErrorException(new NullPointerException("name is null")); } if (shortName == null) { throw new InternalErrorException(new NullPointerException("shortName is null")); } this.name = name; this.shortName = shortName; } public Vo(int id, String name, String shortName, String createdAt, String createdBy, String modifiedAt, String modifiedBy, Integer createdByUid, Integer modifiedByUid) { super(id, createdAt, createdBy, modifiedAt, modifiedBy, createdByUid, modifiedByUid); if (name == null) { throw new InternalErrorException(new NullPointerException("name is null")); } if (shortName == null) { throw new InternalErrorException(new NullPointerException("shortName is null")); } this.name = name; this.shortName = shortName; } public Vo(int id, UUID uuid, String name, String shortName, String createdAt, String createdBy, String modifiedAt, String modifiedBy, Integer createdByUid, Integer modifiedByUid) { super(id, createdAt, createdBy, modifiedAt, modifiedBy, createdByUid, modifiedByUid); if (name == null) { throw new InternalErrorException(new NullPointerException("name is null")); } if (shortName == null) { throw new InternalErrorException(new NullPointerException("shortName is null")); } this.name = name; this.shortName = shortName; this.uuid = uuid; } @Override public int compareTo(PerunBean perunBean) { if (perunBean == null) { throw new NullPointerException("PerunBean to compare with is null."); } if (perunBean instanceof Vo) { Vo vo = (Vo) perunBean; if (this.getName() == null && vo.getName() != null) { return -1; } if (vo.getName() == null && this.getName() != null) { return 1; } if (this.getName() == null && vo.getName() == null) { return 0; } return this.getName().compareToIgnoreCase(vo.getName()); } else { return (this.getId() - perunBean.getId()); } } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Vo other = (Vo) obj; if (this.getId() != other.getId()) { return false; } if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { return false; } if ((this.shortName == null) ? (other.shortName != null) : !this.shortName.equals(other.shortName)) { return false; } return true; } public String getName() { return name; } public void setName(String name) { if (name == null) { throw new InternalErrorException(new NullPointerException("name is null")); } this.name = name; } public String getShortName() { return shortName; } public void setShortName(String shortName) { if (shortName == null) { throw new InternalErrorException(new NullPointerException("shortName is null")); } this.shortName = shortName; } @Override public UUID getUuid() { return uuid; } public void setUuid(UUID uuid) { this.uuid = uuid; } @Override public int hashCode() { int hash = 7; hash = 53 * hash + this.getId(); hash = 53 * hash + (this.name != null ? this.name.hashCode() : 0); hash = 53 * hash + (this.shortName != null ? this.shortName.hashCode() : 0); return hash; } @Override public String serializeToString() { StringBuilder str = new StringBuilder(); return str.append(this.getClass().getSimpleName()).append(":[").append("id=<").append(getId()).append(">") .append(", uuid=<").append(getUuid()).append(">").append(", name=<") .append(getName() == null ? "\\0" : BeansUtils.createEscaping(getName())).append(">").append(", shortName=<") .append(getShortName() == null ? "\\0" : BeansUtils.createEscaping(getShortName())).append(">").append(']') .toString(); } @Override public String toString() { StringBuilder str = new StringBuilder(); return str.append(this.getClass().getSimpleName()).append(":[").append("id='").append(this.getId()).append('\'') .append(", uuid='").append(uuid).append('\'').append(", name='").append(name).append('\'') .append(", shortName='").append(shortName).append('\'').append(']').toString(); } }
45986_14
/* * #%L * OME Bio-Formats package for reading and converting biological file formats. * %% * Copyright (C) 2005 - 2015 Open Microscopy Environment: * - Board of Regents of the University of Wisconsin-Madison * - Glencoe Software, Inc. * - University of Dundee * %% * 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, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ /*! * \file WlzService.java * \author Bill Hill * \date August 2013 * \version $Id$ * \par * Address: * MRC Human Genetics Unit, * MRC Institute of Genetics and Molecular Medicine, * University of Edinburgh, * Western General Hospital, * Edinburgh, EH4 2XU, UK. * \par * Copyright (C), [2013], * The University Court of the University of Edinburgh, * Old College, Edinburgh, UK. * * 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. * \brief Woolz service for bioformats. */ package loci.formats.services; import java.io.IOException; import loci.formats.FormatException; import loci.formats.MissingLibraryException; import loci.common.services.Service; public interface WlzService extends Service { /** * Initializes the service for the given file path. * @param file File path with which to initialize the service. * @throws IOException * @throws FormatException */ public void open(String file, String rw) throws IOException, FormatException; /** * Gets the text string for when Woolz has not been found. */ public String getNoWlzMsg(); /** * Gets the text string used for the Woolz origin label. */ public String getWlzOrgLabelName(); /** * Gets width in pixels/voxels. * @return width. */ public int getSizeX(); /** * Gets height in pixels/voxels. * @return height. */ public int getSizeY(); /** * Gets depth (number of x-y planes) in voxels. * @return depth. */ public int getSizeZ(); /** * Gets number of channels. * @return channels. */ public int getSizeC(); /** * Gets number of time samples. * @return time. */ public int getSizeT(); /** * Gets boolean for whether image is colour or not. * @return true if image is colour. */ public boolean isRGB(); /** * Gets the image pixel type. * @return pixel type. */ public int getPixelType(); /** * Gets voxel width. * @return voxel width. */ public double getVoxSzX(); /** * Gets voxel height. * @return voxel height. */ public double getVoxSzY(); /** * Gets voxel depth. * @return voxel depth. */ public double getVoxSzZ(); /** * Gets column origin. * @return column origin. */ public double getOrgX(); /** * Gets line origin. * @return line origin. */ public double getOrgY(); /** * Gets plane origin. * @return plane origin. */ public double getOrgZ(); /** * Gets supported pixel types. * @return array of supported pixel types. */ public int[] getSupPixelTypes(); /** * Sets up the service, which must have already been opened for writing. * @param orgX x origin. * @param orgY y origin. * @param orgZ z origin (set to 0 for 2D). * @param pixSzX width. * @param pixSzY height. * @param pixSzZ depth (number of planes, set to 1 for 2D). * @param pixSzC number of channels. * @param pixSzT number of time samples. * @param voxSzX pixel/voxel width. * @param voxSzY pixel/voxel heigth. * @param voxSzZ voxel deoth. * @param gType image value type. * @throws FormatException */ public void setupWrite(int orgX, int orgY, int orgZ, int pixSzX, int pixSzY, int pixSzZ, int pixSzC, int pixSzT, double voxSzX, double voxSzY, double voxSzZ, int gType) throws FormatException; /** * Closes the file. */ public void close() throws IOException; /** * Reads a rectangle of bytes in an x-y plane from the opened Woolz * object. * @return Buffer of bytes read. * @param no plane coordinate (set to 0 for 2D). * @param buf buffer for bytes. * @param x rectangle first column. * @param y rectangle first line. * @param w rectangle width (in columns). * @param h rectangle heigth (in lines). */ public byte[] readBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException; /** * Adds a rectangle of bytes in an x-y plane to the opened Woolz object. * @param no plane coordinate (set to 0 for 2D). * @param buf buffer with bytes. * @param x rectangle first column. * @param y rectangle first line. * @param w rectangle width (in columns). * @param h rectangle heigth (in lines). */ public void saveBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException; }
CGDogan/bioformats
components/formats-gpl/src/loci/formats/services/WlzService.java
2,019
/** * Gets voxel depth. * @return voxel depth. */
block_comment
nl
/* * #%L * OME Bio-Formats package for reading and converting biological file formats. * %% * Copyright (C) 2005 - 2015 Open Microscopy Environment: * - Board of Regents of the University of Wisconsin-Madison * - Glencoe Software, Inc. * - University of Dundee * %% * 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, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ /*! * \file WlzService.java * \author Bill Hill * \date August 2013 * \version $Id$ * \par * Address: * MRC Human Genetics Unit, * MRC Institute of Genetics and Molecular Medicine, * University of Edinburgh, * Western General Hospital, * Edinburgh, EH4 2XU, UK. * \par * Copyright (C), [2013], * The University Court of the University of Edinburgh, * Old College, Edinburgh, UK. * * 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. * \brief Woolz service for bioformats. */ package loci.formats.services; import java.io.IOException; import loci.formats.FormatException; import loci.formats.MissingLibraryException; import loci.common.services.Service; public interface WlzService extends Service { /** * Initializes the service for the given file path. * @param file File path with which to initialize the service. * @throws IOException * @throws FormatException */ public void open(String file, String rw) throws IOException, FormatException; /** * Gets the text string for when Woolz has not been found. */ public String getNoWlzMsg(); /** * Gets the text string used for the Woolz origin label. */ public String getWlzOrgLabelName(); /** * Gets width in pixels/voxels. * @return width. */ public int getSizeX(); /** * Gets height in pixels/voxels. * @return height. */ public int getSizeY(); /** * Gets depth (number of x-y planes) in voxels. * @return depth. */ public int getSizeZ(); /** * Gets number of channels. * @return channels. */ public int getSizeC(); /** * Gets number of time samples. * @return time. */ public int getSizeT(); /** * Gets boolean for whether image is colour or not. * @return true if image is colour. */ public boolean isRGB(); /** * Gets the image pixel type. * @return pixel type. */ public int getPixelType(); /** * Gets voxel width. * @return voxel width. */ public double getVoxSzX(); /** * Gets voxel height. * @return voxel height. */ public double getVoxSzY(); /** * Gets voxel depth.<SUF>*/ public double getVoxSzZ(); /** * Gets column origin. * @return column origin. */ public double getOrgX(); /** * Gets line origin. * @return line origin. */ public double getOrgY(); /** * Gets plane origin. * @return plane origin. */ public double getOrgZ(); /** * Gets supported pixel types. * @return array of supported pixel types. */ public int[] getSupPixelTypes(); /** * Sets up the service, which must have already been opened for writing. * @param orgX x origin. * @param orgY y origin. * @param orgZ z origin (set to 0 for 2D). * @param pixSzX width. * @param pixSzY height. * @param pixSzZ depth (number of planes, set to 1 for 2D). * @param pixSzC number of channels. * @param pixSzT number of time samples. * @param voxSzX pixel/voxel width. * @param voxSzY pixel/voxel heigth. * @param voxSzZ voxel deoth. * @param gType image value type. * @throws FormatException */ public void setupWrite(int orgX, int orgY, int orgZ, int pixSzX, int pixSzY, int pixSzZ, int pixSzC, int pixSzT, double voxSzX, double voxSzY, double voxSzZ, int gType) throws FormatException; /** * Closes the file. */ public void close() throws IOException; /** * Reads a rectangle of bytes in an x-y plane from the opened Woolz * object. * @return Buffer of bytes read. * @param no plane coordinate (set to 0 for 2D). * @param buf buffer for bytes. * @param x rectangle first column. * @param y rectangle first line. * @param w rectangle width (in columns). * @param h rectangle heigth (in lines). */ public byte[] readBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException; /** * Adds a rectangle of bytes in an x-y plane to the opened Woolz object. * @param no plane coordinate (set to 0 for 2D). * @param buf buffer with bytes. * @param x rectangle first column. * @param y rectangle first line. * @param w rectangle width (in columns). * @param h rectangle heigth (in lines). */ public void saveBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException; }
114134_19
package app.MVC.view; import app.MVC.controller.Appartement_controller; import app.MVC.modele.appartement_DAO; import javax.swing.*; import java.awt.*; import java.sql.ResultSet; import java.sql.SQLException; public class Appartement_view extends JPanel { private JButton b1, b2, searchButton, ajouteAppart; private appartement_DAO appartementDAO; private Appartement_controller appartement_controller; private JPanel panelButtons,panelLabel,global; private JTextField rue, cp, etage, prixTextField, prix_charg, preavis, dateLibre,tailleTextField, ascenseur; private JList<String> TypeListField, villeTextAppart, arrondissement; public Appartement_view(menu_view menu) throws Exception { ////////////////Instance//////////////////// this.panelButtons = new JPanel(); this.panelLabel = new JPanel(); this.global = new JPanel(); this.appartementDAO = new appartement_DAO(); this.appartement_controller = new Appartement_controller(appartementDAO, menu); //////////////Button de base//////////////// this.b1 = new JButton("Retour"); this.b2 = new JButton("Afficher appartements"); this.searchButton = new JButton("Rechercher"); this.ajouteAppart = new JButton("Ajouter"); //////////////Champ de saisie//////////// this.prixTextField = new JTextField(10); this.tailleTextField = new JTextField(10); //////////////Liste type et ville//////// StringBuilder typeTab = this.getTypesAppart(this.appartement_controller.getType()); //appelle la fonction private de cette classe StringBuilder villeTab = this.getVille(this.appartement_controller.getVilleDispo()); //appelle la fonction private de cette classe this.TypeListField = new JList<>(typeTab.toString().split("\n")); //liste de type this.villeTextAppart = new JList<>(villeTab.toString().split("\n")); // Liste de villes this.panelButtons.add(this.b1); // ajout des button this.panelButtons.add(this.b2); this.panelLabel.add(new JLabel("Type: ")); //champ de séléction this.panelLabel.add(TypeListField); //ajout this.panelLabel.add(new JLabel("Prix max :")); //champ de saisie du prix this.panelLabel.add(prixTextField); //ajout this.panelLabel.add(new JLabel("Taille :")); //champ de saisie de la taille this.panelLabel.add(tailleTextField); //ajout this.panelLabel.add(new JLabel("Ville : ")); //champ de sélection des villes this.panelLabel.add(villeTextAppart); //ajout //attribue les boutons à un controleur précis this.b1.addActionListener(appartement_controller); this.b2.addActionListener(appartement_controller); this.searchButton.addActionListener(appartement_controller); this.ajouteAppart.addActionListener(appartement_controller); this.tailleTextField.setText("0"); //initialise le champ à 0 (en string) this.prixTextField.setText("0"); //initiallise le champ à 0 (en String) this.searchButton.addActionListener(e -> { String type = TypeListField.getSelectedValue(); //donne la valeur sélectionnée | null sinon appartement_controller.setTypeAppart(type); //setters du type, pour actualiser la variable int prix = Integer.parseInt(prixTextField.getText()); //converti string vers integer car bdd en int appartement_controller.setPrixAppart(prix); //setter du prix appart, pour actualiser la variable en cas de changement int taille = Integer.parseInt(tailleTextField.getText()); //converti string vers integer car bdd en int appartement_controller.setTailleAppart(taille); //setter de la taille, pour actualiser en cas de changement String ville = villeTextAppart.getSelectedValue(); appartement_controller.setVilleAppart(ville); }); this.global.setLayout(new BorderLayout()); this.panelButtons.setBackground(Color.DARK_GRAY); //couleur de fond des button this.panelLabel.setBackground(Color.GRAY); //couleur de fond des panels this.panelButtons.setSize(1000, 1000); this.global.add(this.panelButtons, BorderLayout.PAGE_START); this.global.add(this.panelLabel, BorderLayout.PAGE_END); this.panelButtons.add(this.b1); this.panelButtons.add(this.b2); this.panelButtons.add(this.ajouteAppart); this.panelLabel.add(this.searchButton); this.add(this.global); //ajout du global au panel général } public void afficheAppart(ResultSet rs) throws SQLException { //cette procédure permet l'affiche de deux demandes du controleur -> afficheALl et afficheRqst JTextArea textArea = new JTextArea(); //champ de texte textArea.setEditable(false); //non modifiable StringBuilder sb = new StringBuilder(); //création de la chaine if(rs != null){ System.out.println("affiche appartements demandé"); //jeu de test while (rs.next()) { //parcours du résultat via une bouvle sb.append("Prix location : " + rs.getString("prix_log") + "\n"); sb.append("Prix charge: " + rs.getString("prix_charg") + "\n"); sb.append("Adresse : " + rs.getString("rue") + "\n"); sb.append("Ville : " + rs.getString("ville") + "\n"); sb.append("CP : " + rs.getString("CP") + "\n"); sb.append("Etage : " + rs.getString("etage") + "\n"); sb.append("Préavis : " + rs.getString("preavis") + "\n"); sb.append("Ascenseur : " + rs.getString("ascenseur") + "\n"); sb.append("Date libre : " + rs.getString("date_libre") + "\n"); sb.append("Taille : " + rs.getString("taille") + "m2\n"); sb.append("Type : " + rs.getString("type") + "\n"); sb.append("\n"); } JScrollPane scrollPane = new JScrollPane(textArea); //ajout d'une liste déroulante scrollPane.setPreferredSize(new Dimension(400, 300)); //initialisation de la taille this.global.add(scrollPane, BorderLayout.CENTER); //ajout au global textArea.setText(sb.toString()); } else{ System.out.println("Aucun appartements trouvé"); //jeu de test, visuel dans le terminal de textArea.setText("Aucun appartements trouvé"); } this.global.validate(); this.global.repaint(); } public void AjoutAppart() throws Exception { JTextArea textArea = new JTextArea(); textArea.setEditable(false); // Panneaux JPanel panel = new JPanel(); JPanel buttonPanel = new JPanel(); // Mise en forme des panneaux panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); // Alignement vertical panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); // marge de 20px pour chaque bordure // Listes déroulantes pour les villes, les types d'appartements et les arrondissements StringBuilder listeVille = this.getVille(this.appartement_controller.getVilleDispo()); StringBuilder listeType = this.getTypesAppart(this.appartement_controller.getType()); StringBuilder listeArrondi = this.getArrondi(this.appartement_controller.getArrondi()); // Labels pour les champs de saisie JLabel rueLabel = new JLabel("Rue:"); JLabel villeLabel = new JLabel("Ville:"); JLabel cpLabel = new JLabel("Code postal:"); JLabel etageLabel = new JLabel("Etage:"); JLabel prixLabel = new JLabel("Prix du loyer:"); JLabel prixChargLabel = new JLabel("Prix des charges:"); JLabel ascenseurLabel = new JLabel("Ascenseur:"); JLabel preavisLabel = new JLabel("Préavis (en mois):"); JLabel dateLibreLabel = new JLabel("Date de disponibilité:"); JLabel typeLabel = new JLabel("Type:"); JLabel arrondissementLabel = new JLabel("Arrondissement:"); JLabel tailleLabel = new JLabel("Taille:"); // Ajout des champs de saisie panel.add(rueLabel); panel.add(this.rue = new JTextField(20)); panel.add(villeLabel); panel.add(this.villeTextAppart = new JList<>(listeVille.toString().split("\n"))); panel.add(cpLabel); panel.add(this.cp = new JTextField(10)); panel.add(etageLabel); panel.add(this.etage = new JTextField(5)); panel.add(prixLabel); panel.add(this.prixTextField = new JTextField(10)); panel.add(prixChargLabel); panel.add(this.prix_charg = new JTextField(10)); panel.add(ascenseurLabel); panel.add(this.ascenseur = new JTextField()); panel.add(preavisLabel); panel.add(this.preavis = new JTextField(5)); panel.add(dateLibreLabel); panel.add(this.dateLibre = new JTextField(10)); panel.add(typeLabel); panel.add(this.TypeListField = new JList<>(listeType.toString().split("\n"))); panel.add(arrondissementLabel); panel.add(this.arrondissement = new JList<>(listeArrondi.toString().split("\n"))); panel.add(tailleLabel); panel.add(this.tailleTextField = new JTextField(10)); this.rue.setText("0"); //initialise le champ à 0 (en string) this.cp.setText("0"); //initialise le champ à 0 (en string) this.etage.setText("0"); //initialise le champ à 0 (en string) this.prix_charg.setText("0"); //initialise le champ à 0 (en string) this.ascenseur.setText("0"); //initialise le champ à 0 (en string) this.preavis.setText("0"); //initialise le champ à 0 (en string) this.dateLibre.setText("00/00/0000"); //initialise le champ à 0 (en string) this.tailleTextField.setText("0"); //initialise le champ à 0 (en string) this.prixTextField.setText("0"); //initiallise le champ à 0 (en String) // Boutons JButton ajouterBtn = new JButton("Ajouter appart"); JButton annulerBtn = new JButton("Annuler"); ajouterBtn.addActionListener(this.appartement_controller); ajouterBtn.addActionListener(e -> { this.appartement_controller.setRueAppart(Integer.parseInt(this.rue.getText())); this.appartement_controller.setVilleAppart(this.villeTextAppart.getSelectedValue()); this.appartement_controller.setCpAppart(Integer.parseInt(this.cp.getText())); this.appartement_controller.setEtageAppart(Integer.parseInt(this.etage.getText())); this.appartement_controller.setPrixAppart(Integer.parseInt(this.prixTextField.getText())); this.appartement_controller.setPrix_charg(Integer.parseInt(this.prix_charg.getText())); this.appartement_controller.setAscenseur(Integer.parseInt(this.ascenseur.getText())); this.appartement_controller.setPreavis(Integer.parseInt(this.preavis.getText())); this.appartement_controller.setDateLibre(this.dateLibre.getText()); this.appartement_controller.setTypeAppart(this.TypeListField.getSelectedValue()); this.appartement_controller.setArrondisement(this.arrondissement.getSelectedValue()); this.appartement_controller.setTailleAppart(Integer.parseInt(this.tailleTextField.getText())); }); buttonPanel.add(ajouterBtn); buttonPanel.add(annulerBtn); // Ajout des panneaux au panneau principal add(panel, BorderLayout.CENTER); add(buttonPanel, BorderLayout.PAGE_END); // Validation et redessin this.global.validate(); this.global.repaint(); } private StringBuilder getVille(ResultSet rs) throws SQLException{ //pour le champ de sélection JTextArea textArea = new JTextArea(); //champ de texte textArea.setEditable(false); //non modifiable StringBuilder sb = new StringBuilder(); //création de la chaine if(rs != null){ System.out.println("affiche appartements demandé"); //jeu de test while (rs.next()) { //parcours du résultat via une boucle sb.append(rs.getString("ville") + "\n"); } textArea.setText(sb.toString()); } else{ System.out.println("Aucune ville trouvée"); //jeu de test, visuel dans le terminal textArea.setText("Aucune ville trouvée"); } return sb; } private StringBuilder getTypesAppart(ResultSet rs) throws SQLException{ //pour le champ de sélection JTextArea textArea = new JTextArea(); //champ de texte textArea.setEditable(false); //non modifiable StringBuilder sb = new StringBuilder(); //création de la chaine if(rs != null){ while (rs.next()) { //parcours du résultat via une boucle sb.append(rs.getString("type") + "\n"); } textArea.setText(sb.toString()); } else{ System.out.println("Aucune ville trouvée"); //jeu de test, visuel dans le terminal textArea.setText("Aucune ville trouvée"); } return sb; } private StringBuilder getArrondi(ResultSet rs) throws SQLException{ //pour le champ de sélection JTextArea textArea = new JTextArea(); //champ de texte textArea.setEditable(false); //non modifiable StringBuilder sb = new StringBuilder(); //création de la chaine if(rs != null){ while (rs.next()) { //parcours du résultat via une boucle sb.append(rs.getString("libelle") + "\n"); } textArea.setText(sb.toString()); } else{ System.out.println("Aucun arrondissement trouvée"); //jeu de test, visuel dans le terminal textArea.setText("Aucune arrondissement trouvée"); } return sb; } }
CHANG-Toma/GestionLocation
LocationAppartement1/src/app/MVC/view/Appartement_view.java
4,402
//converti string vers integer car bdd en int
line_comment
nl
package app.MVC.view; import app.MVC.controller.Appartement_controller; import app.MVC.modele.appartement_DAO; import javax.swing.*; import java.awt.*; import java.sql.ResultSet; import java.sql.SQLException; public class Appartement_view extends JPanel { private JButton b1, b2, searchButton, ajouteAppart; private appartement_DAO appartementDAO; private Appartement_controller appartement_controller; private JPanel panelButtons,panelLabel,global; private JTextField rue, cp, etage, prixTextField, prix_charg, preavis, dateLibre,tailleTextField, ascenseur; private JList<String> TypeListField, villeTextAppart, arrondissement; public Appartement_view(menu_view menu) throws Exception { ////////////////Instance//////////////////// this.panelButtons = new JPanel(); this.panelLabel = new JPanel(); this.global = new JPanel(); this.appartementDAO = new appartement_DAO(); this.appartement_controller = new Appartement_controller(appartementDAO, menu); //////////////Button de base//////////////// this.b1 = new JButton("Retour"); this.b2 = new JButton("Afficher appartements"); this.searchButton = new JButton("Rechercher"); this.ajouteAppart = new JButton("Ajouter"); //////////////Champ de saisie//////////// this.prixTextField = new JTextField(10); this.tailleTextField = new JTextField(10); //////////////Liste type et ville//////// StringBuilder typeTab = this.getTypesAppart(this.appartement_controller.getType()); //appelle la fonction private de cette classe StringBuilder villeTab = this.getVille(this.appartement_controller.getVilleDispo()); //appelle la fonction private de cette classe this.TypeListField = new JList<>(typeTab.toString().split("\n")); //liste de type this.villeTextAppart = new JList<>(villeTab.toString().split("\n")); // Liste de villes this.panelButtons.add(this.b1); // ajout des button this.panelButtons.add(this.b2); this.panelLabel.add(new JLabel("Type: ")); //champ de séléction this.panelLabel.add(TypeListField); //ajout this.panelLabel.add(new JLabel("Prix max :")); //champ de saisie du prix this.panelLabel.add(prixTextField); //ajout this.panelLabel.add(new JLabel("Taille :")); //champ de saisie de la taille this.panelLabel.add(tailleTextField); //ajout this.panelLabel.add(new JLabel("Ville : ")); //champ de sélection des villes this.panelLabel.add(villeTextAppart); //ajout //attribue les boutons à un controleur précis this.b1.addActionListener(appartement_controller); this.b2.addActionListener(appartement_controller); this.searchButton.addActionListener(appartement_controller); this.ajouteAppart.addActionListener(appartement_controller); this.tailleTextField.setText("0"); //initialise le champ à 0 (en string) this.prixTextField.setText("0"); //initiallise le champ à 0 (en String) this.searchButton.addActionListener(e -> { String type = TypeListField.getSelectedValue(); //donne la valeur sélectionnée | null sinon appartement_controller.setTypeAppart(type); //setters du type, pour actualiser la variable int prix = Integer.parseInt(prixTextField.getText()); //converti string vers integer car bdd en int appartement_controller.setPrixAppart(prix); //setter du prix appart, pour actualiser la variable en cas de changement int taille = Integer.parseInt(tailleTextField.getText()); //converti string<SUF> appartement_controller.setTailleAppart(taille); //setter de la taille, pour actualiser en cas de changement String ville = villeTextAppart.getSelectedValue(); appartement_controller.setVilleAppart(ville); }); this.global.setLayout(new BorderLayout()); this.panelButtons.setBackground(Color.DARK_GRAY); //couleur de fond des button this.panelLabel.setBackground(Color.GRAY); //couleur de fond des panels this.panelButtons.setSize(1000, 1000); this.global.add(this.panelButtons, BorderLayout.PAGE_START); this.global.add(this.panelLabel, BorderLayout.PAGE_END); this.panelButtons.add(this.b1); this.panelButtons.add(this.b2); this.panelButtons.add(this.ajouteAppart); this.panelLabel.add(this.searchButton); this.add(this.global); //ajout du global au panel général } public void afficheAppart(ResultSet rs) throws SQLException { //cette procédure permet l'affiche de deux demandes du controleur -> afficheALl et afficheRqst JTextArea textArea = new JTextArea(); //champ de texte textArea.setEditable(false); //non modifiable StringBuilder sb = new StringBuilder(); //création de la chaine if(rs != null){ System.out.println("affiche appartements demandé"); //jeu de test while (rs.next()) { //parcours du résultat via une bouvle sb.append("Prix location : " + rs.getString("prix_log") + "\n"); sb.append("Prix charge: " + rs.getString("prix_charg") + "\n"); sb.append("Adresse : " + rs.getString("rue") + "\n"); sb.append("Ville : " + rs.getString("ville") + "\n"); sb.append("CP : " + rs.getString("CP") + "\n"); sb.append("Etage : " + rs.getString("etage") + "\n"); sb.append("Préavis : " + rs.getString("preavis") + "\n"); sb.append("Ascenseur : " + rs.getString("ascenseur") + "\n"); sb.append("Date libre : " + rs.getString("date_libre") + "\n"); sb.append("Taille : " + rs.getString("taille") + "m2\n"); sb.append("Type : " + rs.getString("type") + "\n"); sb.append("\n"); } JScrollPane scrollPane = new JScrollPane(textArea); //ajout d'une liste déroulante scrollPane.setPreferredSize(new Dimension(400, 300)); //initialisation de la taille this.global.add(scrollPane, BorderLayout.CENTER); //ajout au global textArea.setText(sb.toString()); } else{ System.out.println("Aucun appartements trouvé"); //jeu de test, visuel dans le terminal de textArea.setText("Aucun appartements trouvé"); } this.global.validate(); this.global.repaint(); } public void AjoutAppart() throws Exception { JTextArea textArea = new JTextArea(); textArea.setEditable(false); // Panneaux JPanel panel = new JPanel(); JPanel buttonPanel = new JPanel(); // Mise en forme des panneaux panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); // Alignement vertical panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); // marge de 20px pour chaque bordure // Listes déroulantes pour les villes, les types d'appartements et les arrondissements StringBuilder listeVille = this.getVille(this.appartement_controller.getVilleDispo()); StringBuilder listeType = this.getTypesAppart(this.appartement_controller.getType()); StringBuilder listeArrondi = this.getArrondi(this.appartement_controller.getArrondi()); // Labels pour les champs de saisie JLabel rueLabel = new JLabel("Rue:"); JLabel villeLabel = new JLabel("Ville:"); JLabel cpLabel = new JLabel("Code postal:"); JLabel etageLabel = new JLabel("Etage:"); JLabel prixLabel = new JLabel("Prix du loyer:"); JLabel prixChargLabel = new JLabel("Prix des charges:"); JLabel ascenseurLabel = new JLabel("Ascenseur:"); JLabel preavisLabel = new JLabel("Préavis (en mois):"); JLabel dateLibreLabel = new JLabel("Date de disponibilité:"); JLabel typeLabel = new JLabel("Type:"); JLabel arrondissementLabel = new JLabel("Arrondissement:"); JLabel tailleLabel = new JLabel("Taille:"); // Ajout des champs de saisie panel.add(rueLabel); panel.add(this.rue = new JTextField(20)); panel.add(villeLabel); panel.add(this.villeTextAppart = new JList<>(listeVille.toString().split("\n"))); panel.add(cpLabel); panel.add(this.cp = new JTextField(10)); panel.add(etageLabel); panel.add(this.etage = new JTextField(5)); panel.add(prixLabel); panel.add(this.prixTextField = new JTextField(10)); panel.add(prixChargLabel); panel.add(this.prix_charg = new JTextField(10)); panel.add(ascenseurLabel); panel.add(this.ascenseur = new JTextField()); panel.add(preavisLabel); panel.add(this.preavis = new JTextField(5)); panel.add(dateLibreLabel); panel.add(this.dateLibre = new JTextField(10)); panel.add(typeLabel); panel.add(this.TypeListField = new JList<>(listeType.toString().split("\n"))); panel.add(arrondissementLabel); panel.add(this.arrondissement = new JList<>(listeArrondi.toString().split("\n"))); panel.add(tailleLabel); panel.add(this.tailleTextField = new JTextField(10)); this.rue.setText("0"); //initialise le champ à 0 (en string) this.cp.setText("0"); //initialise le champ à 0 (en string) this.etage.setText("0"); //initialise le champ à 0 (en string) this.prix_charg.setText("0"); //initialise le champ à 0 (en string) this.ascenseur.setText("0"); //initialise le champ à 0 (en string) this.preavis.setText("0"); //initialise le champ à 0 (en string) this.dateLibre.setText("00/00/0000"); //initialise le champ à 0 (en string) this.tailleTextField.setText("0"); //initialise le champ à 0 (en string) this.prixTextField.setText("0"); //initiallise le champ à 0 (en String) // Boutons JButton ajouterBtn = new JButton("Ajouter appart"); JButton annulerBtn = new JButton("Annuler"); ajouterBtn.addActionListener(this.appartement_controller); ajouterBtn.addActionListener(e -> { this.appartement_controller.setRueAppart(Integer.parseInt(this.rue.getText())); this.appartement_controller.setVilleAppart(this.villeTextAppart.getSelectedValue()); this.appartement_controller.setCpAppart(Integer.parseInt(this.cp.getText())); this.appartement_controller.setEtageAppart(Integer.parseInt(this.etage.getText())); this.appartement_controller.setPrixAppart(Integer.parseInt(this.prixTextField.getText())); this.appartement_controller.setPrix_charg(Integer.parseInt(this.prix_charg.getText())); this.appartement_controller.setAscenseur(Integer.parseInt(this.ascenseur.getText())); this.appartement_controller.setPreavis(Integer.parseInt(this.preavis.getText())); this.appartement_controller.setDateLibre(this.dateLibre.getText()); this.appartement_controller.setTypeAppart(this.TypeListField.getSelectedValue()); this.appartement_controller.setArrondisement(this.arrondissement.getSelectedValue()); this.appartement_controller.setTailleAppart(Integer.parseInt(this.tailleTextField.getText())); }); buttonPanel.add(ajouterBtn); buttonPanel.add(annulerBtn); // Ajout des panneaux au panneau principal add(panel, BorderLayout.CENTER); add(buttonPanel, BorderLayout.PAGE_END); // Validation et redessin this.global.validate(); this.global.repaint(); } private StringBuilder getVille(ResultSet rs) throws SQLException{ //pour le champ de sélection JTextArea textArea = new JTextArea(); //champ de texte textArea.setEditable(false); //non modifiable StringBuilder sb = new StringBuilder(); //création de la chaine if(rs != null){ System.out.println("affiche appartements demandé"); //jeu de test while (rs.next()) { //parcours du résultat via une boucle sb.append(rs.getString("ville") + "\n"); } textArea.setText(sb.toString()); } else{ System.out.println("Aucune ville trouvée"); //jeu de test, visuel dans le terminal textArea.setText("Aucune ville trouvée"); } return sb; } private StringBuilder getTypesAppart(ResultSet rs) throws SQLException{ //pour le champ de sélection JTextArea textArea = new JTextArea(); //champ de texte textArea.setEditable(false); //non modifiable StringBuilder sb = new StringBuilder(); //création de la chaine if(rs != null){ while (rs.next()) { //parcours du résultat via une boucle sb.append(rs.getString("type") + "\n"); } textArea.setText(sb.toString()); } else{ System.out.println("Aucune ville trouvée"); //jeu de test, visuel dans le terminal textArea.setText("Aucune ville trouvée"); } return sb; } private StringBuilder getArrondi(ResultSet rs) throws SQLException{ //pour le champ de sélection JTextArea textArea = new JTextArea(); //champ de texte textArea.setEditable(false); //non modifiable StringBuilder sb = new StringBuilder(); //création de la chaine if(rs != null){ while (rs.next()) { //parcours du résultat via une boucle sb.append(rs.getString("libelle") + "\n"); } textArea.setText(sb.toString()); } else{ System.out.println("Aucun arrondissement trouvée"); //jeu de test, visuel dans le terminal textArea.setText("Aucune arrondissement trouvée"); } return sb; } }
135304_3
/* Copyright (c) 2010 The Regents of the University of California. All rights reserved. Permission is hereby granted, without written agreement and without license or royalty fees, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following two paragraphs appear in all copies of this software. IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package org.clothocad.core.settings; import org.clothocad.core.datums.ObjBase; import org.clothocad.core.datums.Sharable; /** * The settings wraps a Datum to store the settings. * * The philosophy here is to fill this up globally with whatever is * convenient for coding things that need to access this info. That * will make for highest retrieval rate during gets which will be far * more common than sets. The setters can be written later as the * pattern of things that would make sense to a user such that it need * not be so verbose. So, intentions will be translated into these * more specific things. * * Doing it as a persisted class will guarantee default settings are * entirely conservative on all fronts. * @author John Christopher Anderson */ public class Settings { public static boolean isRecordAllDoos() { return datum.recordAllDoos; } public static String getRootURL() { //THIS SHOULD BE REPLACED BY A DYNAMIC DETERMINATION OF THE CURRENT IP return "http://" + getHost() + ((getPort()==80) ? "" : ":" + getPort().toString()); } public static String getHost() { return "localhost"; } public static Integer getPort() { return 8080; //return 61623; } private class SettingsDatum extends ObjBase { private boolean recordAllDoos = false; private String id = "settings-datum-is-uuid"; } private static SettingsDatum datum; }
CIDARLAB/clotho3
src/main/java/org/clothocad/core/settings/Settings.java
746
//" + getHost() +
line_comment
nl
/* Copyright (c) 2010 The Regents of the University of California. All rights reserved. Permission is hereby granted, without written agreement and without license or royalty fees, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following two paragraphs appear in all copies of this software. IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package org.clothocad.core.settings; import org.clothocad.core.datums.ObjBase; import org.clothocad.core.datums.Sharable; /** * The settings wraps a Datum to store the settings. * * The philosophy here is to fill this up globally with whatever is * convenient for coding things that need to access this info. That * will make for highest retrieval rate during gets which will be far * more common than sets. The setters can be written later as the * pattern of things that would make sense to a user such that it need * not be so verbose. So, intentions will be translated into these * more specific things. * * Doing it as a persisted class will guarantee default settings are * entirely conservative on all fronts. * @author John Christopher Anderson */ public class Settings { public static boolean isRecordAllDoos() { return datum.recordAllDoos; } public static String getRootURL() { //THIS SHOULD BE REPLACED BY A DYNAMIC DETERMINATION OF THE CURRENT IP return "http://" +<SUF> ((getPort()==80) ? "" : ":" + getPort().toString()); } public static String getHost() { return "localhost"; } public static Integer getPort() { return 8080; //return 61623; } private class SettingsDatum extends ObjBase { private boolean recordAllDoos = false; private String id = "settings-datum-is-uuid"; } private static SettingsDatum datum; }
48313_2
package com.cjt2325.cameralibrary; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.ImageFormat; import android.graphics.Matrix; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.YuvImage; import android.hardware.Camera; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.media.MediaRecorder; import android.os.Build; import android.os.Environment; import android.util.Log; import android.view.Surface; import android.view.SurfaceHolder; import android.widget.ImageView; import com.cjt2325.cameralibrary.listener.ErrorListener; import com.cjt2325.cameralibrary.util.AngleUtil; import com.cjt2325.cameralibrary.util.CameraParamUtil; import com.cjt2325.cameralibrary.util.CheckPermission; import com.cjt2325.cameralibrary.util.DeviceUtil; import com.cjt2325.cameralibrary.util.FileUtil; import com.cjt2325.cameralibrary.util.LogUtil; import com.cjt2325.cameralibrary.util.ScreenUtils; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static android.graphics.Bitmap.createBitmap; /** * ===================================== * 作 者: 陈嘉桐 * 版 本:1.1.4 * 创建日期:2017/4/25 * 描 述:camera操作单例 * ===================================== */ @SuppressWarnings("deprecation") public class CameraInterface implements Camera.PreviewCallback { private static final String TAG = "CJT"; private volatile static CameraInterface mCameraInterface; public static void destroyCameraInterface() { if (mCameraInterface != null) { mCameraInterface = null; } } private Camera mCamera; private Camera.Parameters mParams; private boolean isPreviewing = false; private int SELECTED_CAMERA = -1; private int CAMERA_POST_POSITION = -1; private int CAMERA_FRONT_POSITION = -1; private SurfaceHolder mHolder = null; private float screenProp = -1.0f; private boolean isRecorder = false; private MediaRecorder mediaRecorder; private String videoFileName; private String saveVideoPath; private String videoFileAbsPath; private Bitmap videoFirstFrame = null; private ErrorListener errorLisenter; private ImageView mSwitchView; private ImageView mFlashLamp; private int preview_width; private int preview_height; private int angle = 0; private int cameraAngle = 90;//摄像头角度 默认为90度 private int rotation = 0; private byte[] firstFrame_data; public static final int TYPE_RECORDER = 0x090; public static final int TYPE_CAPTURE = 0x091; private int nowScaleRate = 0; private int recordScleRate = 0; //视频质量 private int mediaQuality = JCameraView.MEDIA_QUALITY_MIDDLE; private SensorManager sm = null; //获取CameraInterface单例 public static synchronized CameraInterface getInstance() { if (mCameraInterface == null) synchronized (CameraInterface.class) { if (mCameraInterface == null) mCameraInterface = new CameraInterface(); } return mCameraInterface; } public void setSwitchView(ImageView mSwitchView, ImageView mFlashLamp) { this.mSwitchView = mSwitchView; this.mFlashLamp = mFlashLamp; if (mSwitchView != null) { cameraAngle = CameraParamUtil.getInstance().getCameraDisplayOrientation(mSwitchView.getContext(), SELECTED_CAMERA); } } private SensorEventListener sensorEventListener = new SensorEventListener() { public void onSensorChanged(SensorEvent event) { if (Sensor.TYPE_ACCELEROMETER != event.sensor.getType()) { return; } float[] values = event.values; angle = AngleUtil.getSensorAngle(values[0], values[1]); rotationAnimation(); } public void onAccuracyChanged(Sensor sensor, int accuracy) { } }; //切换摄像头icon跟随手机角度进行旋转 private void rotationAnimation() { if (mSwitchView == null) { return; } if (rotation != angle) { int start_rotaion = 0; int end_rotation = 0; switch (rotation) { case 0: start_rotaion = 0; switch (angle) { case 90: end_rotation = -90; break; case 270: end_rotation = 90; break; } break; case 90: start_rotaion = -90; switch (angle) { case 0: end_rotation = 0; break; case 180: end_rotation = -180; break; } break; case 180: start_rotaion = 180; switch (angle) { case 90: end_rotation = 270; break; case 270: end_rotation = 90; break; } break; case 270: start_rotaion = 90; switch (angle) { case 0: end_rotation = 0; break; case 180: end_rotation = 180; break; } break; } ObjectAnimator animC = ObjectAnimator.ofFloat(mSwitchView, "rotation", start_rotaion, end_rotation); ObjectAnimator animF = ObjectAnimator.ofFloat(mFlashLamp, "rotation", start_rotaion, end_rotation); AnimatorSet set = new AnimatorSet(); set.playTogether(animC, animF); set.setDuration(500); set.start(); rotation = angle; } } @SuppressWarnings("ResultOfMethodCallIgnored") void setSaveVideoPath(String saveVideoPath) { this.saveVideoPath = saveVideoPath; File file = new File(saveVideoPath); if (!file.exists()) { file.mkdirs(); } } public void setZoom(float zoom, int type) { if (mCamera == null) { return; } if (mParams == null) { mParams = mCamera.getParameters(); } if (!mParams.isZoomSupported() || !mParams.isSmoothZoomSupported()) { return; } switch (type) { case TYPE_RECORDER: //如果不是录制视频中,上滑不会缩放 if (!isRecorder) { return; } if (zoom >= 0) { //每移动50个像素缩放一个级别 int scaleRate = (int) (zoom / 40); if (scaleRate <= mParams.getMaxZoom() && scaleRate >= nowScaleRate && recordScleRate != scaleRate) { mParams.setZoom(scaleRate); mCamera.setParameters(mParams); recordScleRate = scaleRate; } } break; case TYPE_CAPTURE: if (isRecorder) { return; } //每移动50个像素缩放一个级别 int scaleRate = (int) (zoom / 50); if (scaleRate < mParams.getMaxZoom()) { nowScaleRate += scaleRate; if (nowScaleRate < 0) { nowScaleRate = 0; } else if (nowScaleRate > mParams.getMaxZoom()) { nowScaleRate = mParams.getMaxZoom(); } mParams.setZoom(nowScaleRate); mCamera.setParameters(mParams); } LogUtil.i("setZoom = " + nowScaleRate); break; } } void setMediaQuality(int quality) { this.mediaQuality = quality; } @Override public void onPreviewFrame(byte[] data, Camera camera) { firstFrame_data = data; } public void setFlashMode(String flashMode) { if (mCamera == null) return; Camera.Parameters params = mCamera.getParameters(); params.setFlashMode(flashMode); mCamera.setParameters(params); } public interface CameraOpenOverCallback { void cameraHasOpened(); } private CameraInterface() { findAvailableCameras(); SELECTED_CAMERA = CAMERA_POST_POSITION; saveVideoPath = ""; } /** * open Camera */ void doOpenCamera(CameraOpenOverCallback callback) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { if (!CheckPermission.isCameraUseable(SELECTED_CAMERA) && this.errorLisenter != null) { this.errorLisenter.onError(); return; } } if (mCamera == null) { openCamera(SELECTED_CAMERA); } callback.cameraHasOpened(); } private void setFlashModel() { mParams = mCamera.getParameters(); mParams.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); //设置camera参数为Torch模式 mCamera.setParameters(mParams); } private synchronized void openCamera(int id) { try { this.mCamera = Camera.open(id); } catch (Exception var3) { var3.printStackTrace(); if (this.errorLisenter != null) { this.errorLisenter.onError(); } } if (Build.VERSION.SDK_INT > 17 && this.mCamera != null) { try { this.mCamera.enableShutterSound(false); } catch (Exception e) { e.printStackTrace(); Log.e("CJT", "enable shutter sound faild"); } } } public synchronized void switchCamera(SurfaceHolder holder, float screenProp) { if (SELECTED_CAMERA == CAMERA_POST_POSITION) { SELECTED_CAMERA = CAMERA_FRONT_POSITION; } else { SELECTED_CAMERA = CAMERA_POST_POSITION; } doDestroyCamera(); LogUtil.i("open start"); openCamera(SELECTED_CAMERA); // mCamera = Camera.open(); if (Build.VERSION.SDK_INT > 17 && this.mCamera != null) { try { this.mCamera.enableShutterSound(false); } catch (Exception e) { e.printStackTrace(); } } LogUtil.i("open end"); doStartPreview(holder, screenProp); } /** * doStartPreview */ public void doStartPreview(SurfaceHolder holder, float screenProp) { if (isPreviewing) { LogUtil.i("doStartPreview isPreviewing"); } if (this.screenProp < 0) { this.screenProp = screenProp; } if (holder == null) { return; } this.mHolder = holder; if (mCamera != null) { try { mParams = mCamera.getParameters(); Camera.Size previewSize = CameraParamUtil.getInstance().getPreviewSize(mParams .getSupportedPreviewSizes(), 1000, screenProp); Camera.Size pictureSize = CameraParamUtil.getInstance().getPictureSize(mParams .getSupportedPictureSizes(), 1200, screenProp); mParams.setPreviewSize(previewSize.width, previewSize.height); preview_width = previewSize.width; preview_height = previewSize.height; mParams.setPictureSize(pictureSize.width, pictureSize.height); if (CameraParamUtil.getInstance().isSupportedFocusMode( mParams.getSupportedFocusModes(), Camera.Parameters.FOCUS_MODE_AUTO)) { mParams.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO); } if (CameraParamUtil.getInstance().isSupportedPictureFormats(mParams.getSupportedPictureFormats(), ImageFormat.JPEG)) { mParams.setPictureFormat(ImageFormat.JPEG); mParams.setJpegQuality(100); } mCamera.setParameters(mParams); mParams = mCamera.getParameters(); mCamera.setPreviewDisplay(holder); //SurfaceView mCamera.setDisplayOrientation(cameraAngle);//浏览角度 mCamera.setPreviewCallback(this); //每一帧回调 mCamera.startPreview();//启动浏览 isPreviewing = true; Log.i(TAG, "=== Start Preview ==="); } catch (IOException e) { e.printStackTrace(); } } } /** * 停止预览 */ public void doStopPreview() { if (null != mCamera) { try { mCamera.setPreviewCallback(null); mCamera.stopPreview(); //这句要在stopPreview后执行,不然会卡顿或者花屏 mCamera.setPreviewDisplay(null); isPreviewing = false; Log.i(TAG, "=== Stop Preview ==="); } catch (IOException e) { e.printStackTrace(); } } } /** * 销毁Camera */ void doDestroyCamera() { errorLisenter = null; if (null != mCamera) { try { mCamera.setPreviewCallback(null); mSwitchView = null; mFlashLamp = null; mCamera.stopPreview(); //这句要在stopPreview后执行,不然会卡顿或者花屏 mCamera.setPreviewDisplay(null); mHolder = null; isPreviewing = false; mCamera.release(); mCamera = null; // destroyCameraInterface(); Log.i(TAG, "=== Destroy Camera ==="); } catch (IOException e) { e.printStackTrace(); } } else { Log.i(TAG, "=== Camera Null==="); } } /** * 拍照 */ private int nowAngle; public void takePicture(final TakePictureCallback callback) { if (mCamera == null) { return; } switch (cameraAngle) { case 90: nowAngle = Math.abs(angle + cameraAngle) % 360; break; case 270: nowAngle = Math.abs(cameraAngle - angle); break; } // Log.i("CJT", angle + " = " + cameraAngle + " = " + nowAngle); mCamera.takePicture(null, null, new Camera.PictureCallback() { @Override public void onPictureTaken(byte[] data, Camera camera) { Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); Matrix matrix = new Matrix(); if (SELECTED_CAMERA == CAMERA_POST_POSITION) { matrix.setRotate(nowAngle); } else if (SELECTED_CAMERA == CAMERA_FRONT_POSITION) { matrix.setRotate(360 - nowAngle); matrix.postScale(-1, 1); } bitmap = createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); if (callback != null) { if (nowAngle == 90 || nowAngle == 270) { callback.captureResult(bitmap, true); } else { callback.captureResult(bitmap, false); } } } }); } //启动录像 public void startRecord(Surface surface, float screenProp, ErrorCallback callback) { mCamera.setPreviewCallback(null); final int nowAngle = (angle + 90) % 360; //获取第一帧图片 Camera.Parameters parameters = mCamera.getParameters(); int width = parameters.getPreviewSize().width; int height = parameters.getPreviewSize().height; YuvImage yuv = new YuvImage(firstFrame_data, parameters.getPreviewFormat(), width, height, null); ByteArrayOutputStream out = new ByteArrayOutputStream(); yuv.compressToJpeg(new Rect(0, 0, width, height), 50, out); byte[] bytes = out.toByteArray(); videoFirstFrame = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); Matrix matrix = new Matrix(); if (SELECTED_CAMERA == CAMERA_POST_POSITION) { matrix.setRotate(nowAngle); } else if (SELECTED_CAMERA == CAMERA_FRONT_POSITION) { matrix.setRotate(270); } videoFirstFrame = createBitmap(videoFirstFrame, 0, 0, videoFirstFrame.getWidth(), videoFirstFrame .getHeight(), matrix, true); if (isRecorder) { return; } if (mCamera == null) { openCamera(SELECTED_CAMERA); } if (mediaRecorder == null) { mediaRecorder = new MediaRecorder(); } if (mParams == null) { mParams = mCamera.getParameters(); } List<String> focusModes = mParams.getSupportedFocusModes(); if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) { mParams.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO); } mCamera.setParameters(mParams); mCamera.unlock(); mediaRecorder.reset(); mediaRecorder.setCamera(mCamera); mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264); mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); Camera.Size videoSize; if (mParams.getSupportedVideoSizes() == null) { videoSize = CameraParamUtil.getInstance().getPreviewSize(mParams.getSupportedPreviewSizes(), 600, screenProp); } else { videoSize = CameraParamUtil.getInstance().getPreviewSize(mParams.getSupportedVideoSizes(), 600, screenProp); } Log.i(TAG, "setVideoSize width = " + videoSize.width + "height = " + videoSize.height); if (videoSize.width == videoSize.height) { mediaRecorder.setVideoSize(preview_width, preview_height); } else { mediaRecorder.setVideoSize(videoSize.width, videoSize.height); } // if (SELECTED_CAMERA == CAMERA_FRONT_POSITION) { // mediaRecorder.setOrientationHint(270); // } else { // mediaRecorder.setOrientationHint(nowAngle); //// mediaRecorder.setOrientationHint(90); // } if (SELECTED_CAMERA == CAMERA_FRONT_POSITION) { //手机预览倒立的处理 if (cameraAngle == 270) { //横屏 if (nowAngle == 0) { mediaRecorder.setOrientationHint(180); } else if (nowAngle == 270) { mediaRecorder.setOrientationHint(270); } else { mediaRecorder.setOrientationHint(90); } } else { if (nowAngle == 90) { mediaRecorder.setOrientationHint(270); } else if (nowAngle == 270) { mediaRecorder.setOrientationHint(90); } else { mediaRecorder.setOrientationHint(nowAngle); } } } else { mediaRecorder.setOrientationHint(nowAngle); } if (DeviceUtil.isHuaWeiRongyao()) { mediaRecorder.setVideoEncodingBitRate(4 * 100000); } else { mediaRecorder.setVideoEncodingBitRate(mediaQuality); } mediaRecorder.setPreviewDisplay(surface); videoFileName = "video_" + System.currentTimeMillis() + ".mp4"; if (saveVideoPath.equals("")) { saveVideoPath = Environment.getExternalStorageDirectory().getPath(); } videoFileAbsPath = saveVideoPath + File.separator + videoFileName; mediaRecorder.setOutputFile(videoFileAbsPath); try { mediaRecorder.prepare(); mediaRecorder.start(); isRecorder = true; } catch (IllegalStateException e) { e.printStackTrace(); Log.i("CJT", "startRecord IllegalStateException"); if (this.errorLisenter != null) { this.errorLisenter.onError(); } } catch (IOException e) { e.printStackTrace(); Log.i("CJT", "startRecord IOException"); if (this.errorLisenter != null) { this.errorLisenter.onError(); } } catch (RuntimeException e) { Log.i("CJT", "startRecord RuntimeException"); } } //停止录像 public void stopRecord(boolean isShort, StopRecordCallback callback) { if (!isRecorder) { return; } if (mediaRecorder != null) { mediaRecorder.setOnErrorListener(null); mediaRecorder.setOnInfoListener(null); mediaRecorder.setPreviewDisplay(null); try { mediaRecorder.stop(); } catch (RuntimeException e) { e.printStackTrace(); mediaRecorder = null; mediaRecorder = new MediaRecorder(); } finally { if (mediaRecorder != null) { mediaRecorder.release(); } mediaRecorder = null; isRecorder = false; } if (isShort) { if (FileUtil.deleteFile(videoFileAbsPath)) { callback.recordResult(null, null); } return; } doStopPreview(); String fileName = saveVideoPath + File.separator + videoFileName; callback.recordResult(fileName, videoFirstFrame); } } private void findAvailableCameras() { Camera.CameraInfo info = new Camera.CameraInfo(); int cameraNum = Camera.getNumberOfCameras(); for (int i = 0; i < cameraNum; i++) { Camera.getCameraInfo(i, info); switch (info.facing) { case Camera.CameraInfo.CAMERA_FACING_FRONT: CAMERA_FRONT_POSITION = info.facing; break; case Camera.CameraInfo.CAMERA_FACING_BACK: CAMERA_POST_POSITION = info.facing; break; } } } int handlerTime = 0; public void handleFocus(final Context context, final float x, final float y, final FocusCallback callback) { if (mCamera == null) { return; } final Camera.Parameters params = mCamera.getParameters(); Rect focusRect = calculateTapArea(x, y, 1f, context); mCamera.cancelAutoFocus(); if (params.getMaxNumFocusAreas() > 0) { List<Camera.Area> focusAreas = new ArrayList<>(); focusAreas.add(new Camera.Area(focusRect, 800)); params.setFocusAreas(focusAreas); } else { Log.i(TAG, "focus areas not supported"); callback.focusSuccess(); return; } final String currentFocusMode = params.getFocusMode(); try { params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO); mCamera.setParameters(params); mCamera.autoFocus(new Camera.AutoFocusCallback() { @Override public void onAutoFocus(boolean success, Camera camera) { if (success || handlerTime > 10) { Camera.Parameters params = camera.getParameters(); params.setFocusMode(currentFocusMode); camera.setParameters(params); handlerTime = 0; callback.focusSuccess(); } else { handlerTime++; handleFocus(context, x, y, callback); } } }); } catch (Exception e) { Log.e(TAG, "autoFocus failer"); } } private static Rect calculateTapArea(float x, float y, float coefficient, Context context) { float focusAreaSize = 300; int areaSize = Float.valueOf(focusAreaSize * coefficient).intValue(); int centerX = (int) (x / ScreenUtils.getScreenWidth(context) * 2000 - 1000); int centerY = (int) (y / ScreenUtils.getScreenHeight(context) * 2000 - 1000); int left = clamp(centerX - areaSize / 2, -1000, 1000); int top = clamp(centerY - areaSize / 2, -1000, 1000); RectF rectF = new RectF(left, top, left + areaSize, top + areaSize); return new Rect(Math.round(rectF.left), Math.round(rectF.top), Math.round(rectF.right), Math.round(rectF .bottom)); } private static int clamp(int x, int min, int max) { if (x > max) { return max; } if (x < min) { return min; } return x; } void setErrorLinsenter(ErrorListener errorLisenter) { this.errorLisenter = errorLisenter; } public interface StopRecordCallback { void recordResult(String url, Bitmap firstFrame); } interface ErrorCallback { void onError(); } public interface TakePictureCallback { void captureResult(Bitmap bitmap, boolean isVertical); } public interface FocusCallback { void focusSuccess(); } void registerSensorManager(Context context) { if (sm == null) { sm = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); } sm.registerListener(sensorEventListener, sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager .SENSOR_DELAY_NORMAL); } void unregisterSensorManager(Context context) { if (sm == null) { sm = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); } sm.unregisterListener(sensorEventListener); } void isPreview(boolean res) { this.isPreviewing = res; } }
CJT2325/CameraView
camera/src/main/java/com/cjt2325/cameralibrary/CameraInterface.java
7,649
/** * open Camera */
block_comment
nl
package com.cjt2325.cameralibrary; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.ImageFormat; import android.graphics.Matrix; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.YuvImage; import android.hardware.Camera; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.media.MediaRecorder; import android.os.Build; import android.os.Environment; import android.util.Log; import android.view.Surface; import android.view.SurfaceHolder; import android.widget.ImageView; import com.cjt2325.cameralibrary.listener.ErrorListener; import com.cjt2325.cameralibrary.util.AngleUtil; import com.cjt2325.cameralibrary.util.CameraParamUtil; import com.cjt2325.cameralibrary.util.CheckPermission; import com.cjt2325.cameralibrary.util.DeviceUtil; import com.cjt2325.cameralibrary.util.FileUtil; import com.cjt2325.cameralibrary.util.LogUtil; import com.cjt2325.cameralibrary.util.ScreenUtils; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static android.graphics.Bitmap.createBitmap; /** * ===================================== * 作 者: 陈嘉桐 * 版 本:1.1.4 * 创建日期:2017/4/25 * 描 述:camera操作单例 * ===================================== */ @SuppressWarnings("deprecation") public class CameraInterface implements Camera.PreviewCallback { private static final String TAG = "CJT"; private volatile static CameraInterface mCameraInterface; public static void destroyCameraInterface() { if (mCameraInterface != null) { mCameraInterface = null; } } private Camera mCamera; private Camera.Parameters mParams; private boolean isPreviewing = false; private int SELECTED_CAMERA = -1; private int CAMERA_POST_POSITION = -1; private int CAMERA_FRONT_POSITION = -1; private SurfaceHolder mHolder = null; private float screenProp = -1.0f; private boolean isRecorder = false; private MediaRecorder mediaRecorder; private String videoFileName; private String saveVideoPath; private String videoFileAbsPath; private Bitmap videoFirstFrame = null; private ErrorListener errorLisenter; private ImageView mSwitchView; private ImageView mFlashLamp; private int preview_width; private int preview_height; private int angle = 0; private int cameraAngle = 90;//摄像头角度 默认为90度 private int rotation = 0; private byte[] firstFrame_data; public static final int TYPE_RECORDER = 0x090; public static final int TYPE_CAPTURE = 0x091; private int nowScaleRate = 0; private int recordScleRate = 0; //视频质量 private int mediaQuality = JCameraView.MEDIA_QUALITY_MIDDLE; private SensorManager sm = null; //获取CameraInterface单例 public static synchronized CameraInterface getInstance() { if (mCameraInterface == null) synchronized (CameraInterface.class) { if (mCameraInterface == null) mCameraInterface = new CameraInterface(); } return mCameraInterface; } public void setSwitchView(ImageView mSwitchView, ImageView mFlashLamp) { this.mSwitchView = mSwitchView; this.mFlashLamp = mFlashLamp; if (mSwitchView != null) { cameraAngle = CameraParamUtil.getInstance().getCameraDisplayOrientation(mSwitchView.getContext(), SELECTED_CAMERA); } } private SensorEventListener sensorEventListener = new SensorEventListener() { public void onSensorChanged(SensorEvent event) { if (Sensor.TYPE_ACCELEROMETER != event.sensor.getType()) { return; } float[] values = event.values; angle = AngleUtil.getSensorAngle(values[0], values[1]); rotationAnimation(); } public void onAccuracyChanged(Sensor sensor, int accuracy) { } }; //切换摄像头icon跟随手机角度进行旋转 private void rotationAnimation() { if (mSwitchView == null) { return; } if (rotation != angle) { int start_rotaion = 0; int end_rotation = 0; switch (rotation) { case 0: start_rotaion = 0; switch (angle) { case 90: end_rotation = -90; break; case 270: end_rotation = 90; break; } break; case 90: start_rotaion = -90; switch (angle) { case 0: end_rotation = 0; break; case 180: end_rotation = -180; break; } break; case 180: start_rotaion = 180; switch (angle) { case 90: end_rotation = 270; break; case 270: end_rotation = 90; break; } break; case 270: start_rotaion = 90; switch (angle) { case 0: end_rotation = 0; break; case 180: end_rotation = 180; break; } break; } ObjectAnimator animC = ObjectAnimator.ofFloat(mSwitchView, "rotation", start_rotaion, end_rotation); ObjectAnimator animF = ObjectAnimator.ofFloat(mFlashLamp, "rotation", start_rotaion, end_rotation); AnimatorSet set = new AnimatorSet(); set.playTogether(animC, animF); set.setDuration(500); set.start(); rotation = angle; } } @SuppressWarnings("ResultOfMethodCallIgnored") void setSaveVideoPath(String saveVideoPath) { this.saveVideoPath = saveVideoPath; File file = new File(saveVideoPath); if (!file.exists()) { file.mkdirs(); } } public void setZoom(float zoom, int type) { if (mCamera == null) { return; } if (mParams == null) { mParams = mCamera.getParameters(); } if (!mParams.isZoomSupported() || !mParams.isSmoothZoomSupported()) { return; } switch (type) { case TYPE_RECORDER: //如果不是录制视频中,上滑不会缩放 if (!isRecorder) { return; } if (zoom >= 0) { //每移动50个像素缩放一个级别 int scaleRate = (int) (zoom / 40); if (scaleRate <= mParams.getMaxZoom() && scaleRate >= nowScaleRate && recordScleRate != scaleRate) { mParams.setZoom(scaleRate); mCamera.setParameters(mParams); recordScleRate = scaleRate; } } break; case TYPE_CAPTURE: if (isRecorder) { return; } //每移动50个像素缩放一个级别 int scaleRate = (int) (zoom / 50); if (scaleRate < mParams.getMaxZoom()) { nowScaleRate += scaleRate; if (nowScaleRate < 0) { nowScaleRate = 0; } else if (nowScaleRate > mParams.getMaxZoom()) { nowScaleRate = mParams.getMaxZoom(); } mParams.setZoom(nowScaleRate); mCamera.setParameters(mParams); } LogUtil.i("setZoom = " + nowScaleRate); break; } } void setMediaQuality(int quality) { this.mediaQuality = quality; } @Override public void onPreviewFrame(byte[] data, Camera camera) { firstFrame_data = data; } public void setFlashMode(String flashMode) { if (mCamera == null) return; Camera.Parameters params = mCamera.getParameters(); params.setFlashMode(flashMode); mCamera.setParameters(params); } public interface CameraOpenOverCallback { void cameraHasOpened(); } private CameraInterface() { findAvailableCameras(); SELECTED_CAMERA = CAMERA_POST_POSITION; saveVideoPath = ""; } /** * open Camera <SUF>*/ void doOpenCamera(CameraOpenOverCallback callback) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { if (!CheckPermission.isCameraUseable(SELECTED_CAMERA) && this.errorLisenter != null) { this.errorLisenter.onError(); return; } } if (mCamera == null) { openCamera(SELECTED_CAMERA); } callback.cameraHasOpened(); } private void setFlashModel() { mParams = mCamera.getParameters(); mParams.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); //设置camera参数为Torch模式 mCamera.setParameters(mParams); } private synchronized void openCamera(int id) { try { this.mCamera = Camera.open(id); } catch (Exception var3) { var3.printStackTrace(); if (this.errorLisenter != null) { this.errorLisenter.onError(); } } if (Build.VERSION.SDK_INT > 17 && this.mCamera != null) { try { this.mCamera.enableShutterSound(false); } catch (Exception e) { e.printStackTrace(); Log.e("CJT", "enable shutter sound faild"); } } } public synchronized void switchCamera(SurfaceHolder holder, float screenProp) { if (SELECTED_CAMERA == CAMERA_POST_POSITION) { SELECTED_CAMERA = CAMERA_FRONT_POSITION; } else { SELECTED_CAMERA = CAMERA_POST_POSITION; } doDestroyCamera(); LogUtil.i("open start"); openCamera(SELECTED_CAMERA); // mCamera = Camera.open(); if (Build.VERSION.SDK_INT > 17 && this.mCamera != null) { try { this.mCamera.enableShutterSound(false); } catch (Exception e) { e.printStackTrace(); } } LogUtil.i("open end"); doStartPreview(holder, screenProp); } /** * doStartPreview */ public void doStartPreview(SurfaceHolder holder, float screenProp) { if (isPreviewing) { LogUtil.i("doStartPreview isPreviewing"); } if (this.screenProp < 0) { this.screenProp = screenProp; } if (holder == null) { return; } this.mHolder = holder; if (mCamera != null) { try { mParams = mCamera.getParameters(); Camera.Size previewSize = CameraParamUtil.getInstance().getPreviewSize(mParams .getSupportedPreviewSizes(), 1000, screenProp); Camera.Size pictureSize = CameraParamUtil.getInstance().getPictureSize(mParams .getSupportedPictureSizes(), 1200, screenProp); mParams.setPreviewSize(previewSize.width, previewSize.height); preview_width = previewSize.width; preview_height = previewSize.height; mParams.setPictureSize(pictureSize.width, pictureSize.height); if (CameraParamUtil.getInstance().isSupportedFocusMode( mParams.getSupportedFocusModes(), Camera.Parameters.FOCUS_MODE_AUTO)) { mParams.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO); } if (CameraParamUtil.getInstance().isSupportedPictureFormats(mParams.getSupportedPictureFormats(), ImageFormat.JPEG)) { mParams.setPictureFormat(ImageFormat.JPEG); mParams.setJpegQuality(100); } mCamera.setParameters(mParams); mParams = mCamera.getParameters(); mCamera.setPreviewDisplay(holder); //SurfaceView mCamera.setDisplayOrientation(cameraAngle);//浏览角度 mCamera.setPreviewCallback(this); //每一帧回调 mCamera.startPreview();//启动浏览 isPreviewing = true; Log.i(TAG, "=== Start Preview ==="); } catch (IOException e) { e.printStackTrace(); } } } /** * 停止预览 */ public void doStopPreview() { if (null != mCamera) { try { mCamera.setPreviewCallback(null); mCamera.stopPreview(); //这句要在stopPreview后执行,不然会卡顿或者花屏 mCamera.setPreviewDisplay(null); isPreviewing = false; Log.i(TAG, "=== Stop Preview ==="); } catch (IOException e) { e.printStackTrace(); } } } /** * 销毁Camera */ void doDestroyCamera() { errorLisenter = null; if (null != mCamera) { try { mCamera.setPreviewCallback(null); mSwitchView = null; mFlashLamp = null; mCamera.stopPreview(); //这句要在stopPreview后执行,不然会卡顿或者花屏 mCamera.setPreviewDisplay(null); mHolder = null; isPreviewing = false; mCamera.release(); mCamera = null; // destroyCameraInterface(); Log.i(TAG, "=== Destroy Camera ==="); } catch (IOException e) { e.printStackTrace(); } } else { Log.i(TAG, "=== Camera Null==="); } } /** * 拍照 */ private int nowAngle; public void takePicture(final TakePictureCallback callback) { if (mCamera == null) { return; } switch (cameraAngle) { case 90: nowAngle = Math.abs(angle + cameraAngle) % 360; break; case 270: nowAngle = Math.abs(cameraAngle - angle); break; } // Log.i("CJT", angle + " = " + cameraAngle + " = " + nowAngle); mCamera.takePicture(null, null, new Camera.PictureCallback() { @Override public void onPictureTaken(byte[] data, Camera camera) { Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); Matrix matrix = new Matrix(); if (SELECTED_CAMERA == CAMERA_POST_POSITION) { matrix.setRotate(nowAngle); } else if (SELECTED_CAMERA == CAMERA_FRONT_POSITION) { matrix.setRotate(360 - nowAngle); matrix.postScale(-1, 1); } bitmap = createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); if (callback != null) { if (nowAngle == 90 || nowAngle == 270) { callback.captureResult(bitmap, true); } else { callback.captureResult(bitmap, false); } } } }); } //启动录像 public void startRecord(Surface surface, float screenProp, ErrorCallback callback) { mCamera.setPreviewCallback(null); final int nowAngle = (angle + 90) % 360; //获取第一帧图片 Camera.Parameters parameters = mCamera.getParameters(); int width = parameters.getPreviewSize().width; int height = parameters.getPreviewSize().height; YuvImage yuv = new YuvImage(firstFrame_data, parameters.getPreviewFormat(), width, height, null); ByteArrayOutputStream out = new ByteArrayOutputStream(); yuv.compressToJpeg(new Rect(0, 0, width, height), 50, out); byte[] bytes = out.toByteArray(); videoFirstFrame = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); Matrix matrix = new Matrix(); if (SELECTED_CAMERA == CAMERA_POST_POSITION) { matrix.setRotate(nowAngle); } else if (SELECTED_CAMERA == CAMERA_FRONT_POSITION) { matrix.setRotate(270); } videoFirstFrame = createBitmap(videoFirstFrame, 0, 0, videoFirstFrame.getWidth(), videoFirstFrame .getHeight(), matrix, true); if (isRecorder) { return; } if (mCamera == null) { openCamera(SELECTED_CAMERA); } if (mediaRecorder == null) { mediaRecorder = new MediaRecorder(); } if (mParams == null) { mParams = mCamera.getParameters(); } List<String> focusModes = mParams.getSupportedFocusModes(); if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) { mParams.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO); } mCamera.setParameters(mParams); mCamera.unlock(); mediaRecorder.reset(); mediaRecorder.setCamera(mCamera); mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264); mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); Camera.Size videoSize; if (mParams.getSupportedVideoSizes() == null) { videoSize = CameraParamUtil.getInstance().getPreviewSize(mParams.getSupportedPreviewSizes(), 600, screenProp); } else { videoSize = CameraParamUtil.getInstance().getPreviewSize(mParams.getSupportedVideoSizes(), 600, screenProp); } Log.i(TAG, "setVideoSize width = " + videoSize.width + "height = " + videoSize.height); if (videoSize.width == videoSize.height) { mediaRecorder.setVideoSize(preview_width, preview_height); } else { mediaRecorder.setVideoSize(videoSize.width, videoSize.height); } // if (SELECTED_CAMERA == CAMERA_FRONT_POSITION) { // mediaRecorder.setOrientationHint(270); // } else { // mediaRecorder.setOrientationHint(nowAngle); //// mediaRecorder.setOrientationHint(90); // } if (SELECTED_CAMERA == CAMERA_FRONT_POSITION) { //手机预览倒立的处理 if (cameraAngle == 270) { //横屏 if (nowAngle == 0) { mediaRecorder.setOrientationHint(180); } else if (nowAngle == 270) { mediaRecorder.setOrientationHint(270); } else { mediaRecorder.setOrientationHint(90); } } else { if (nowAngle == 90) { mediaRecorder.setOrientationHint(270); } else if (nowAngle == 270) { mediaRecorder.setOrientationHint(90); } else { mediaRecorder.setOrientationHint(nowAngle); } } } else { mediaRecorder.setOrientationHint(nowAngle); } if (DeviceUtil.isHuaWeiRongyao()) { mediaRecorder.setVideoEncodingBitRate(4 * 100000); } else { mediaRecorder.setVideoEncodingBitRate(mediaQuality); } mediaRecorder.setPreviewDisplay(surface); videoFileName = "video_" + System.currentTimeMillis() + ".mp4"; if (saveVideoPath.equals("")) { saveVideoPath = Environment.getExternalStorageDirectory().getPath(); } videoFileAbsPath = saveVideoPath + File.separator + videoFileName; mediaRecorder.setOutputFile(videoFileAbsPath); try { mediaRecorder.prepare(); mediaRecorder.start(); isRecorder = true; } catch (IllegalStateException e) { e.printStackTrace(); Log.i("CJT", "startRecord IllegalStateException"); if (this.errorLisenter != null) { this.errorLisenter.onError(); } } catch (IOException e) { e.printStackTrace(); Log.i("CJT", "startRecord IOException"); if (this.errorLisenter != null) { this.errorLisenter.onError(); } } catch (RuntimeException e) { Log.i("CJT", "startRecord RuntimeException"); } } //停止录像 public void stopRecord(boolean isShort, StopRecordCallback callback) { if (!isRecorder) { return; } if (mediaRecorder != null) { mediaRecorder.setOnErrorListener(null); mediaRecorder.setOnInfoListener(null); mediaRecorder.setPreviewDisplay(null); try { mediaRecorder.stop(); } catch (RuntimeException e) { e.printStackTrace(); mediaRecorder = null; mediaRecorder = new MediaRecorder(); } finally { if (mediaRecorder != null) { mediaRecorder.release(); } mediaRecorder = null; isRecorder = false; } if (isShort) { if (FileUtil.deleteFile(videoFileAbsPath)) { callback.recordResult(null, null); } return; } doStopPreview(); String fileName = saveVideoPath + File.separator + videoFileName; callback.recordResult(fileName, videoFirstFrame); } } private void findAvailableCameras() { Camera.CameraInfo info = new Camera.CameraInfo(); int cameraNum = Camera.getNumberOfCameras(); for (int i = 0; i < cameraNum; i++) { Camera.getCameraInfo(i, info); switch (info.facing) { case Camera.CameraInfo.CAMERA_FACING_FRONT: CAMERA_FRONT_POSITION = info.facing; break; case Camera.CameraInfo.CAMERA_FACING_BACK: CAMERA_POST_POSITION = info.facing; break; } } } int handlerTime = 0; public void handleFocus(final Context context, final float x, final float y, final FocusCallback callback) { if (mCamera == null) { return; } final Camera.Parameters params = mCamera.getParameters(); Rect focusRect = calculateTapArea(x, y, 1f, context); mCamera.cancelAutoFocus(); if (params.getMaxNumFocusAreas() > 0) { List<Camera.Area> focusAreas = new ArrayList<>(); focusAreas.add(new Camera.Area(focusRect, 800)); params.setFocusAreas(focusAreas); } else { Log.i(TAG, "focus areas not supported"); callback.focusSuccess(); return; } final String currentFocusMode = params.getFocusMode(); try { params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO); mCamera.setParameters(params); mCamera.autoFocus(new Camera.AutoFocusCallback() { @Override public void onAutoFocus(boolean success, Camera camera) { if (success || handlerTime > 10) { Camera.Parameters params = camera.getParameters(); params.setFocusMode(currentFocusMode); camera.setParameters(params); handlerTime = 0; callback.focusSuccess(); } else { handlerTime++; handleFocus(context, x, y, callback); } } }); } catch (Exception e) { Log.e(TAG, "autoFocus failer"); } } private static Rect calculateTapArea(float x, float y, float coefficient, Context context) { float focusAreaSize = 300; int areaSize = Float.valueOf(focusAreaSize * coefficient).intValue(); int centerX = (int) (x / ScreenUtils.getScreenWidth(context) * 2000 - 1000); int centerY = (int) (y / ScreenUtils.getScreenHeight(context) * 2000 - 1000); int left = clamp(centerX - areaSize / 2, -1000, 1000); int top = clamp(centerY - areaSize / 2, -1000, 1000); RectF rectF = new RectF(left, top, left + areaSize, top + areaSize); return new Rect(Math.round(rectF.left), Math.round(rectF.top), Math.round(rectF.right), Math.round(rectF .bottom)); } private static int clamp(int x, int min, int max) { if (x > max) { return max; } if (x < min) { return min; } return x; } void setErrorLinsenter(ErrorListener errorLisenter) { this.errorLisenter = errorLisenter; } public interface StopRecordCallback { void recordResult(String url, Bitmap firstFrame); } interface ErrorCallback { void onError(); } public interface TakePictureCallback { void captureResult(Bitmap bitmap, boolean isVertical); } public interface FocusCallback { void focusSuccess(); } void registerSensorManager(Context context) { if (sm == null) { sm = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); } sm.registerListener(sensorEventListener, sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager .SENSOR_DELAY_NORMAL); } void unregisterSensorManager(Context context) { if (sm == null) { sm = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); } sm.unregisterListener(sensorEventListener); } void isPreview(boolean res) { this.isPreviewing = res; } }
52977_0
package nl.knaw.huygens.timbuctoo.core.dto; import com.fasterxml.jackson.databind.JsonNode; import javaslang.control.Try; import nl.knaw.huygens.timbuctoo.core.dto.dataset.Collection; import nl.knaw.huygens.timbuctoo.model.properties.ReadableProperty; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Optional; import static nl.knaw.huygens.timbuctoo.logging.Logmarkers.databaseInvariant; public class DisplayNameHelper { private static final Logger LOG = LoggerFactory.getLogger(DisplayNameHelper.class); public static Optional<String> getDisplayname(GraphTraversalSource traversalSource, Vertex vertex, Collection targetCollection) { ReadableProperty displayNameProperty = targetCollection.getDisplayName(); if (displayNameProperty != null) { GraphTraversal<Vertex, Try<JsonNode>> displayNameGetter = traversalSource.V(vertex.id()).union( targetCollection.getDisplayName().traversalJson() ); if (displayNameGetter.hasNext()) { Try<JsonNode> traversalResult = displayNameGetter.next(); if (!traversalResult.isSuccess()) { LOG.debug(databaseInvariant, "Retrieving displayname failed", traversalResult.getCause()); } else { if (traversalResult.get() == null) { LOG.debug(databaseInvariant, "Displayname was null"); } else { if (!traversalResult.get().isTextual()) { LOG.debug(databaseInvariant, "Displayname was not a string but " + traversalResult.get().toString()); } else { return Optional.of(traversalResult.get().asText()); } } } } else { LOG.debug(databaseInvariant, "Displayname traversal resulted in no results: " + displayNameGetter); } } else { LOG.debug("No displayname configured for " + targetCollection.getEntityTypeName()); //FIXME: deze wordt gegooid tijdens de finish. da's raar } return Optional.empty(); } }
CLARIAH/timbuctoo
timbuctoo-instancev4/src/main/java/nl/knaw/huygens/timbuctoo/core/dto/DisplayNameHelper.java
674
//FIXME: deze wordt gegooid tijdens de finish. da's raar
line_comment
nl
package nl.knaw.huygens.timbuctoo.core.dto; import com.fasterxml.jackson.databind.JsonNode; import javaslang.control.Try; import nl.knaw.huygens.timbuctoo.core.dto.dataset.Collection; import nl.knaw.huygens.timbuctoo.model.properties.ReadableProperty; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Optional; import static nl.knaw.huygens.timbuctoo.logging.Logmarkers.databaseInvariant; public class DisplayNameHelper { private static final Logger LOG = LoggerFactory.getLogger(DisplayNameHelper.class); public static Optional<String> getDisplayname(GraphTraversalSource traversalSource, Vertex vertex, Collection targetCollection) { ReadableProperty displayNameProperty = targetCollection.getDisplayName(); if (displayNameProperty != null) { GraphTraversal<Vertex, Try<JsonNode>> displayNameGetter = traversalSource.V(vertex.id()).union( targetCollection.getDisplayName().traversalJson() ); if (displayNameGetter.hasNext()) { Try<JsonNode> traversalResult = displayNameGetter.next(); if (!traversalResult.isSuccess()) { LOG.debug(databaseInvariant, "Retrieving displayname failed", traversalResult.getCause()); } else { if (traversalResult.get() == null) { LOG.debug(databaseInvariant, "Displayname was null"); } else { if (!traversalResult.get().isTextual()) { LOG.debug(databaseInvariant, "Displayname was not a string but " + traversalResult.get().toString()); } else { return Optional.of(traversalResult.get().asText()); } } } } else { LOG.debug(databaseInvariant, "Displayname traversal resulted in no results: " + displayNameGetter); } } else { LOG.debug("No displayname configured for " + targetCollection.getEntityTypeName()); //FIXME: deze<SUF> } return Optional.empty(); } }
180678_6
package com.cmput301.cs.project.activities; import android.app.Activity; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentSender; import android.location.Location; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AutoCompleteTextView; import com.cmput301.cs.project.R; import com.cmput301.cs.project.adapters.PlaceAutocompleteAdapter; import com.cmput301.cs.project.controllers.SettingsController; import com.cmput301.cs.project.models.Destination; import com.cmput301.cs.project.utils.Utils; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.places.Place; import com.google.android.gms.location.places.PlaceBuffer; import com.google.android.gms.location.places.Places; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.MarkerOptions; /** * Map activity returns a result with a destination packaged in the intent as {@link #KEY_DESTINATION} * <p/> * It allows a user to select a place on the map or enter the place name in a text box */ // Apr 3, 2015 https://github.com/googlesamples/android-play-places/blob/master/PlaceComplete/Application/src/main/java/com/example/google/playservices/placecomplete/MainActivity.java // Mar 31, 2015 http://developer.android.com/google/auth/api-client.html#Starting public class MapActivity extends Activity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, GoogleMap.OnMapClickListener, GoogleMap.OnCameraChangeListener, GoogleMap.OnMyLocationChangeListener { public static final String KEY_DESTINATION = "key_destination"; // Request code to use when launching the resolution activity private static final int REQUEST_RESOLVE_ERROR = 1001; // Unique tag for the error dialog fragment private static final String DIALOG_ERROR = "dialog_error"; private static final String STATE_RESOLVING_ERROR = "resolving_error"; // fallback default bounds; will get updated with "my location" private static final LatLngBounds BOUNDS_GREATER_SYDNEY = new LatLngBounds( new LatLng(-34.041458, 150.790100), new LatLng(-33.682247, 151.383362)); private static final float ZOOM_PERCENTAGE = 0.8f; // 80% zoom level private AutoCompleteTextView mAddressSearch; private Destination mOriginalDestination; private GoogleApiClient mGoogleApiClient; // Bool to track whether the app is already resolving an error private boolean mResolvingError = false; private GoogleMap mGoogleMap; private PlaceAutocompleteAdapter mAdapter; private Destination mHome; private final Destination.Builder mBuilder = new Destination.Builder(); /** * Listener that handles selections from suggestions from the AutoCompleteTextView that * displays Place suggestions. * Gets the place id of the selected item and issues a request to the Places Geo Data API * to retrieve more details about the place. * * @see com.google.android.gms.location.places.GeoDataApi#getPlaceById(com.google.android.gms.common.api.GoogleApiClient, * String...) */ private AdapterView.OnItemClickListener mAutocompleteClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { /* Retrieve the place ID of the selected item from the Adapter. The adapter stores each Place suggestion in a PlaceAutocomplete object from which we read the place ID. */ final PlaceAutocompleteAdapter.PlaceAutocomplete item = mAdapter.getItem(position); final String placeId = String.valueOf(item.placeId); /* Issue a request to the Places Geo Data API to retrieve a Place object with additional details about the place. */ PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi .getPlaceById(mGoogleApiClient, placeId); placeResult.setResultCallback(mUpdatePlaceDetailsCallback); } }; /** * Callback for results from a Places Geo Data API query that shows the first place result in * the details view on screen. */ private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback = new ResultCallback<PlaceBuffer>() { @Override public void onResult(PlaceBuffer places) { if (!places.getStatus().isSuccess()) { // Request did not complete successfully return; } // Get the Place object from the buffer. final Place place = places.get(0); final LatLng latLng = place.getLatLng(); updateWithNameAndLatLng(place.getName(), latLng); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setupActionBar(); setContentView(R.layout.map_activity); setResult(RESULT_CANCELED); mResolvingError = savedInstanceState != null && savedInstanceState.getBoolean(STATE_RESOLVING_ERROR, false); buildGoogleApiClient(); final MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this); mAdapter = new PlaceAutocompleteAdapter(this, android.R.layout.simple_list_item_1, BOUNDS_GREATER_SYDNEY, null); mAddressSearch = (AutoCompleteTextView) findViewById(R.id.address_search); mAddressSearch.setAdapter(mAdapter); mAddressSearch.setOnItemClickListener(mAutocompleteClickListener); findViewById(R.id.clear).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAddressSearch.setText(""); } }); mOriginalDestination = getIntent().getParcelableExtra(KEY_DESTINATION); mHome = SettingsController.get(this).loadHomeAsDestination(); final LatLng location = mHome.getLocation(); final String name = mHome.getName(); if (location != null) { final View view = findViewById(R.id.home_btn); view.setVisibility(View.VISIBLE); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { animateMapTo(location); if (name == null) { setSearchTextWithoutAdapter(getString(R.string.home)); updateLatLng(location); } else { updateWithNameAndLatLng(name, location); } } }); } } private void updateWithNameAndLatLng(CharSequence name, LatLng latLng) { if (latLng == null) return; updateLatLng(latLng); if (latLng.equals(mHome.getLocation())) { setSearchTextWithoutAdapter(getString(R.string.formated_home, name)); } else { setSearchTextWithoutAdapter(name); } setResult(RESULT_OK, new Intent() .putExtra(KEY_DESTINATION, mBuilder .name(name.toString()) // .location(latLng) already set to the builder by updateLatLng(LatLng) .build())); } private void updateLatLng(LatLng latLng) { if (latLng == null) return; mGoogleMap.clear(); mGoogleMap.addMarker(new MarkerOptions().position(latLng)); animateMapTo(latLng); setResult(RESULT_OK, new Intent() .putExtra(KEY_DESTINATION, mBuilder .location(latLng) .build())); } private void setSearchTextWithoutAdapter(CharSequence charSequence) { //noinspection ConstantConditions incorrect NonNull annotation mAddressSearch.setAdapter(null); mAddressSearch.setText(charSequence); mAddressSearch.setAdapter(mAdapter); } @Override protected void onStart() { super.onStart(); if (!mResolvingError) { mGoogleApiClient.connect(); } } @Override protected void onStop() { mGoogleApiClient.disconnect(); super.onStop(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_RESOLVE_ERROR) { mResolvingError = false; if (resultCode == RESULT_OK) { // Make sure the app is not already connected or attempting to connect if (!mGoogleApiClient.isConnecting() && !mGoogleApiClient.isConnected()) { mGoogleApiClient.connect(); } } } else { super.onActivityResult(requestCode, resultCode, data); } } private void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(Places.GEO_DATA_API) .addApi(Places.PLACE_DETECTION_API) .addApi(LocationServices.API) .build(); } private void setupActionBar() { Utils.setupDiscardDoneBar(this, new View.OnClickListener() { @Override public void onClick(View v) { setResult(RESULT_CANCELED); finish(); } }, new View.OnClickListener() { @Override public void onClick(View v) { // setResult is called in updateWithNameAndLatLng finish(); } }); } @Override public void onMapReady(GoogleMap map) { mGoogleMap = map; map.setMyLocationEnabled(true); map.setOnMapClickListener(this); map.setOnCameraChangeListener(this); if (mOriginalDestination != null) { final String name = mOriginalDestination.getName(); final LatLng location = mOriginalDestination.getLocation(); updateWithNameAndLatLng(name, location); } else { map.setOnMyLocationChangeListener(this); } } @Override public void onMapClick(LatLng latLng) { updateWithNameAndLatLng(getText(R.string.custom_location), latLng); } @Override public void onMyLocationChange(Location l) { mGoogleMap.setOnMyLocationChangeListener(null); final LatLng latLng = new LatLng(l.getLatitude(), l.getLongitude()); updateWithNameAndLatLng(getText(R.string.custom_location), latLng); } private void animateMapTo(LatLng latLng) { mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom( latLng, mGoogleMap.getMaxZoomLevel() * ZOOM_PERCENTAGE)); } @Override public void onCameraChange(CameraPosition cameraPosition) { mAdapter.setBounds(mGoogleMap.getProjection().getVisibleRegion().latLngBounds); } @Override public void onConnected(Bundle connectionHint) { // Successfully connected to the API client. Pass it to the adapter to enable API access. mAdapter.setGoogleApiClient(mGoogleApiClient); } @Override public void onConnectionSuspended(int cause) { // Connection to the API client has been suspended. Disable API access in the client. mAdapter.setGoogleApiClient(null); } @Override public void onConnectionFailed(ConnectionResult result) { if (mResolvingError) { // Already attempting to resolve an error. return; } else if (result.hasResolution()) { try { mResolvingError = true; result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR); } catch (IntentSender.SendIntentException e) { // There was an error with the resolution intent. Try again. mGoogleApiClient.connect(); } } else { // Show dialog using GooglePlayServicesUtil.getErrorDialog() showErrorDialog(result.getErrorCode()); mResolvingError = true; } mAdapter.setGoogleApiClient(null); } // The rest of this code is all about building the error dialog /* Creates a dialog for an error message */ private void showErrorDialog(int errorCode) { // Create a fragment for the error dialog ErrorDialogFragment dialogFragment = new ErrorDialogFragment(); // Pass the error that should be displayed Bundle args = new Bundle(); args.putInt(DIALOG_ERROR, errorCode); dialogFragment.setArguments(args); dialogFragment.show(getFragmentManager(), "errordialog"); } /* Called from ErrorDialogFragment when the dialog is dismissed. */ public void onDialogDismissed() { mResolvingError = false; } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(STATE_RESOLVING_ERROR, mResolvingError); } /* A fragment to display an error dialog */ public static class ErrorDialogFragment extends DialogFragment { public ErrorDialogFragment() { } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Get the error code and retrieve the appropriate dialog int errorCode = this.getArguments().getInt(DIALOG_ERROR); return GooglePlayServicesUtil.getErrorDialog(errorCode, this.getActivity(), REQUEST_RESOLVE_ERROR); } @Override public void onDismiss(DialogInterface dialog) { ((MapActivity) getActivity()).onDialogDismissed(); } } }
CMPUT301W15T10/301-Project
src/com/cmput301/cs/project/activities/MapActivity.java
4,027
// 80% zoom level
line_comment
nl
package com.cmput301.cs.project.activities; import android.app.Activity; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentSender; import android.location.Location; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AutoCompleteTextView; import com.cmput301.cs.project.R; import com.cmput301.cs.project.adapters.PlaceAutocompleteAdapter; import com.cmput301.cs.project.controllers.SettingsController; import com.cmput301.cs.project.models.Destination; import com.cmput301.cs.project.utils.Utils; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.places.Place; import com.google.android.gms.location.places.PlaceBuffer; import com.google.android.gms.location.places.Places; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.MarkerOptions; /** * Map activity returns a result with a destination packaged in the intent as {@link #KEY_DESTINATION} * <p/> * It allows a user to select a place on the map or enter the place name in a text box */ // Apr 3, 2015 https://github.com/googlesamples/android-play-places/blob/master/PlaceComplete/Application/src/main/java/com/example/google/playservices/placecomplete/MainActivity.java // Mar 31, 2015 http://developer.android.com/google/auth/api-client.html#Starting public class MapActivity extends Activity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, GoogleMap.OnMapClickListener, GoogleMap.OnCameraChangeListener, GoogleMap.OnMyLocationChangeListener { public static final String KEY_DESTINATION = "key_destination"; // Request code to use when launching the resolution activity private static final int REQUEST_RESOLVE_ERROR = 1001; // Unique tag for the error dialog fragment private static final String DIALOG_ERROR = "dialog_error"; private static final String STATE_RESOLVING_ERROR = "resolving_error"; // fallback default bounds; will get updated with "my location" private static final LatLngBounds BOUNDS_GREATER_SYDNEY = new LatLngBounds( new LatLng(-34.041458, 150.790100), new LatLng(-33.682247, 151.383362)); private static final float ZOOM_PERCENTAGE = 0.8f; // 80% zoom<SUF> private AutoCompleteTextView mAddressSearch; private Destination mOriginalDestination; private GoogleApiClient mGoogleApiClient; // Bool to track whether the app is already resolving an error private boolean mResolvingError = false; private GoogleMap mGoogleMap; private PlaceAutocompleteAdapter mAdapter; private Destination mHome; private final Destination.Builder mBuilder = new Destination.Builder(); /** * Listener that handles selections from suggestions from the AutoCompleteTextView that * displays Place suggestions. * Gets the place id of the selected item and issues a request to the Places Geo Data API * to retrieve more details about the place. * * @see com.google.android.gms.location.places.GeoDataApi#getPlaceById(com.google.android.gms.common.api.GoogleApiClient, * String...) */ private AdapterView.OnItemClickListener mAutocompleteClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { /* Retrieve the place ID of the selected item from the Adapter. The adapter stores each Place suggestion in a PlaceAutocomplete object from which we read the place ID. */ final PlaceAutocompleteAdapter.PlaceAutocomplete item = mAdapter.getItem(position); final String placeId = String.valueOf(item.placeId); /* Issue a request to the Places Geo Data API to retrieve a Place object with additional details about the place. */ PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi .getPlaceById(mGoogleApiClient, placeId); placeResult.setResultCallback(mUpdatePlaceDetailsCallback); } }; /** * Callback for results from a Places Geo Data API query that shows the first place result in * the details view on screen. */ private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback = new ResultCallback<PlaceBuffer>() { @Override public void onResult(PlaceBuffer places) { if (!places.getStatus().isSuccess()) { // Request did not complete successfully return; } // Get the Place object from the buffer. final Place place = places.get(0); final LatLng latLng = place.getLatLng(); updateWithNameAndLatLng(place.getName(), latLng); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setupActionBar(); setContentView(R.layout.map_activity); setResult(RESULT_CANCELED); mResolvingError = savedInstanceState != null && savedInstanceState.getBoolean(STATE_RESOLVING_ERROR, false); buildGoogleApiClient(); final MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this); mAdapter = new PlaceAutocompleteAdapter(this, android.R.layout.simple_list_item_1, BOUNDS_GREATER_SYDNEY, null); mAddressSearch = (AutoCompleteTextView) findViewById(R.id.address_search); mAddressSearch.setAdapter(mAdapter); mAddressSearch.setOnItemClickListener(mAutocompleteClickListener); findViewById(R.id.clear).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAddressSearch.setText(""); } }); mOriginalDestination = getIntent().getParcelableExtra(KEY_DESTINATION); mHome = SettingsController.get(this).loadHomeAsDestination(); final LatLng location = mHome.getLocation(); final String name = mHome.getName(); if (location != null) { final View view = findViewById(R.id.home_btn); view.setVisibility(View.VISIBLE); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { animateMapTo(location); if (name == null) { setSearchTextWithoutAdapter(getString(R.string.home)); updateLatLng(location); } else { updateWithNameAndLatLng(name, location); } } }); } } private void updateWithNameAndLatLng(CharSequence name, LatLng latLng) { if (latLng == null) return; updateLatLng(latLng); if (latLng.equals(mHome.getLocation())) { setSearchTextWithoutAdapter(getString(R.string.formated_home, name)); } else { setSearchTextWithoutAdapter(name); } setResult(RESULT_OK, new Intent() .putExtra(KEY_DESTINATION, mBuilder .name(name.toString()) // .location(latLng) already set to the builder by updateLatLng(LatLng) .build())); } private void updateLatLng(LatLng latLng) { if (latLng == null) return; mGoogleMap.clear(); mGoogleMap.addMarker(new MarkerOptions().position(latLng)); animateMapTo(latLng); setResult(RESULT_OK, new Intent() .putExtra(KEY_DESTINATION, mBuilder .location(latLng) .build())); } private void setSearchTextWithoutAdapter(CharSequence charSequence) { //noinspection ConstantConditions incorrect NonNull annotation mAddressSearch.setAdapter(null); mAddressSearch.setText(charSequence); mAddressSearch.setAdapter(mAdapter); } @Override protected void onStart() { super.onStart(); if (!mResolvingError) { mGoogleApiClient.connect(); } } @Override protected void onStop() { mGoogleApiClient.disconnect(); super.onStop(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_RESOLVE_ERROR) { mResolvingError = false; if (resultCode == RESULT_OK) { // Make sure the app is not already connected or attempting to connect if (!mGoogleApiClient.isConnecting() && !mGoogleApiClient.isConnected()) { mGoogleApiClient.connect(); } } } else { super.onActivityResult(requestCode, resultCode, data); } } private void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(Places.GEO_DATA_API) .addApi(Places.PLACE_DETECTION_API) .addApi(LocationServices.API) .build(); } private void setupActionBar() { Utils.setupDiscardDoneBar(this, new View.OnClickListener() { @Override public void onClick(View v) { setResult(RESULT_CANCELED); finish(); } }, new View.OnClickListener() { @Override public void onClick(View v) { // setResult is called in updateWithNameAndLatLng finish(); } }); } @Override public void onMapReady(GoogleMap map) { mGoogleMap = map; map.setMyLocationEnabled(true); map.setOnMapClickListener(this); map.setOnCameraChangeListener(this); if (mOriginalDestination != null) { final String name = mOriginalDestination.getName(); final LatLng location = mOriginalDestination.getLocation(); updateWithNameAndLatLng(name, location); } else { map.setOnMyLocationChangeListener(this); } } @Override public void onMapClick(LatLng latLng) { updateWithNameAndLatLng(getText(R.string.custom_location), latLng); } @Override public void onMyLocationChange(Location l) { mGoogleMap.setOnMyLocationChangeListener(null); final LatLng latLng = new LatLng(l.getLatitude(), l.getLongitude()); updateWithNameAndLatLng(getText(R.string.custom_location), latLng); } private void animateMapTo(LatLng latLng) { mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom( latLng, mGoogleMap.getMaxZoomLevel() * ZOOM_PERCENTAGE)); } @Override public void onCameraChange(CameraPosition cameraPosition) { mAdapter.setBounds(mGoogleMap.getProjection().getVisibleRegion().latLngBounds); } @Override public void onConnected(Bundle connectionHint) { // Successfully connected to the API client. Pass it to the adapter to enable API access. mAdapter.setGoogleApiClient(mGoogleApiClient); } @Override public void onConnectionSuspended(int cause) { // Connection to the API client has been suspended. Disable API access in the client. mAdapter.setGoogleApiClient(null); } @Override public void onConnectionFailed(ConnectionResult result) { if (mResolvingError) { // Already attempting to resolve an error. return; } else if (result.hasResolution()) { try { mResolvingError = true; result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR); } catch (IntentSender.SendIntentException e) { // There was an error with the resolution intent. Try again. mGoogleApiClient.connect(); } } else { // Show dialog using GooglePlayServicesUtil.getErrorDialog() showErrorDialog(result.getErrorCode()); mResolvingError = true; } mAdapter.setGoogleApiClient(null); } // The rest of this code is all about building the error dialog /* Creates a dialog for an error message */ private void showErrorDialog(int errorCode) { // Create a fragment for the error dialog ErrorDialogFragment dialogFragment = new ErrorDialogFragment(); // Pass the error that should be displayed Bundle args = new Bundle(); args.putInt(DIALOG_ERROR, errorCode); dialogFragment.setArguments(args); dialogFragment.show(getFragmentManager(), "errordialog"); } /* Called from ErrorDialogFragment when the dialog is dismissed. */ public void onDialogDismissed() { mResolvingError = false; } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(STATE_RESOLVING_ERROR, mResolvingError); } /* A fragment to display an error dialog */ public static class ErrorDialogFragment extends DialogFragment { public ErrorDialogFragment() { } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Get the error code and retrieve the appropriate dialog int errorCode = this.getArguments().getInt(DIALOG_ERROR); return GooglePlayServicesUtil.getErrorDialog(errorCode, this.getActivity(), REQUEST_RESOLVE_ERROR); } @Override public void onDismiss(DialogInterface dialog) { ((MapActivity) getActivity()).onDialogDismissed(); } } }
189585_1
package com.rs.utils; import java.util.concurrent.atomic.AtomicInteger; /** * The container class that contains functions to simplify the modification of a * number. * <p> * <p> * This class is similar in functionality to {@link AtomicInteger} but does not * support atomic operations, and therefore should not be used across multiple * threads. * @author lare96 <http://github.com/lare96> */ public final class MutableNumber extends Number implements Comparable<MutableNumber> { // pure lare code, echt ongelofelijk dit /** * The constant serial version UID for serialization. */ private static final long serialVersionUID = -7475363158492415879L; /** * The value present within this counter. */ private int value; /** * Creates a new {@link MutableNumber} with {@code value}. * @param value the value present within this counter. */ public MutableNumber(int value) { this.value = value; } /** * Creates a new {@link MutableNumber} with a value of {@code 0}. */ public MutableNumber() { this(0); } @Override public String toString() { return Integer.toString(value); } @Override public int hashCode() { return Integer.hashCode(value); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(!(obj instanceof MutableNumber)) return false; MutableNumber other = (MutableNumber) obj; return value == other.value; } @Override public int compareTo(MutableNumber o) { return Integer.compare(value, o.value); } /** * {@inheritDoc} * <p> * This function equates to the {@link MutableNumber#get()} function. */ @Override public int intValue() { return value; } @Override public long longValue() { return (long) value; } @Override public float floatValue() { return (float) value; } @Override public double doubleValue() { return (double) value; } /** * Returns the value within this counter and then increments it by * {@code amount} to a maximum of {@code maximum}. * @param amount the amount to increment it by. * @param maximum the maximum amount it will be incremented to. * @return the value before it is incremented. */ public int getAndIncrement(int amount, int maximum) { int val = value; value += amount; if(value > maximum) value = maximum; return val; } /** * Returns the value within this counter and then increments it by * {@code amount}. * @param amount the amount to increment it by. * @return the value before it is incremented. */ public int getAndIncrement(int amount) { return getAndIncrement(amount, Integer.MAX_VALUE); } /** * Returns the value within this counter and then increments it by an amount * of {@code 1}. * @return the value before it is incremented. */ public int getAndIncrement() { return getAndIncrement(1); } //guys I have to go, it's me stan //It's taraweeh time, gonna go pray and come back //u guys can stay on teamviewer just shut it down when ur done, ill //tell my mom not to close the laptop //just dont do stupid stuff please xD ok -at rtnp ty <3 /** * Increments the value within this counter by {@code amount} to a maximum * of {@code maximum} and then returns it. * @param amount the amount to increment it by. * @param maximum the maximum amount it will be incremented to. * @return the value after it is incremented. */ public int incrementAndGet(int amount, int maximum) { value += amount; if(value > maximum) value = maximum; return value; } /** * Increments the value within this counter by {@code amount} and then * returns it. * @param amount the amount to increment it by. * @return the value after it is incremented. */ public int incrementAndGet(int amount) { return incrementAndGet(amount, Integer.MAX_VALUE); } /** * Increments the value within this counter by {@code 1} and then returns * it. * @return the value after it is incremented. */ public int incrementAndGet() { return incrementAndGet(1); } /** * Returns the value within this counter and then decrements it by * {@code amount} to a minimum of {@code minimum}. * @param amount the amount to decrement it by. * @param minimum the minimum amount it will be decremented to. * @return the value before it is decremented. */ public int getAndDecrement(int amount, int minimum) { int val = value; value -= amount; if(value < minimum) value = minimum; return val; } /** * Returns the value within this counter and then decrements it by * {@code amount}. * @param amount the amount to decrement it by. * @return the value before it is decremented. */ public int getAndDecrement(int amount) { return getAndDecrement(amount, Integer.MIN_VALUE); } /** * Returns the value within this counter and then decrements it by an amount * of {@code 1}. * @return the value before it is decremented. */ public int getAndDecrement() { return getAndDecrement(1); } /** * Decrements the value within this counter by {@code amount} to a minimum * of {@code minimum} and then returns it. * @param amount the amount to decrement it by. * @param minimum the minimum amount it will be decremented to. * @return the value after it is decremented. */ public int decrementAndGet(int amount, int minimum) { value -= amount; if(value < minimum) value = minimum; return value; } /** * Decrements the value within this counter by {@code amount} and then * returns it. * @param amount the amount to decrement it by. * @return the value after it is decremented. */ public int decrementAndGet(int amount) { return decrementAndGet(amount, Integer.MIN_VALUE); } /** * Decrements the value within this counter by {@code 1} and then returns * it. * @return the value after it is decremented. */ public int decrementAndGet() { return decrementAndGet(1); } /** * Gets the value present within this counter. This function equates to the * inherited {@link MutableNumber#intValue()} function. * @return the value present. */ public int get() { return value; } /** * Sets the value within this container to {@code value}. * @param value the new value to set. */ public void set(int value) { this.value = value; } }
CSS-Lletya/open727
727 server/src/com/rs/utils/MutableNumber.java
1,977
// pure lare code, echt ongelofelijk dit
line_comment
nl
package com.rs.utils; import java.util.concurrent.atomic.AtomicInteger; /** * The container class that contains functions to simplify the modification of a * number. * <p> * <p> * This class is similar in functionality to {@link AtomicInteger} but does not * support atomic operations, and therefore should not be used across multiple * threads. * @author lare96 <http://github.com/lare96> */ public final class MutableNumber extends Number implements Comparable<MutableNumber> { // pure lare<SUF> /** * The constant serial version UID for serialization. */ private static final long serialVersionUID = -7475363158492415879L; /** * The value present within this counter. */ private int value; /** * Creates a new {@link MutableNumber} with {@code value}. * @param value the value present within this counter. */ public MutableNumber(int value) { this.value = value; } /** * Creates a new {@link MutableNumber} with a value of {@code 0}. */ public MutableNumber() { this(0); } @Override public String toString() { return Integer.toString(value); } @Override public int hashCode() { return Integer.hashCode(value); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(!(obj instanceof MutableNumber)) return false; MutableNumber other = (MutableNumber) obj; return value == other.value; } @Override public int compareTo(MutableNumber o) { return Integer.compare(value, o.value); } /** * {@inheritDoc} * <p> * This function equates to the {@link MutableNumber#get()} function. */ @Override public int intValue() { return value; } @Override public long longValue() { return (long) value; } @Override public float floatValue() { return (float) value; } @Override public double doubleValue() { return (double) value; } /** * Returns the value within this counter and then increments it by * {@code amount} to a maximum of {@code maximum}. * @param amount the amount to increment it by. * @param maximum the maximum amount it will be incremented to. * @return the value before it is incremented. */ public int getAndIncrement(int amount, int maximum) { int val = value; value += amount; if(value > maximum) value = maximum; return val; } /** * Returns the value within this counter and then increments it by * {@code amount}. * @param amount the amount to increment it by. * @return the value before it is incremented. */ public int getAndIncrement(int amount) { return getAndIncrement(amount, Integer.MAX_VALUE); } /** * Returns the value within this counter and then increments it by an amount * of {@code 1}. * @return the value before it is incremented. */ public int getAndIncrement() { return getAndIncrement(1); } //guys I have to go, it's me stan //It's taraweeh time, gonna go pray and come back //u guys can stay on teamviewer just shut it down when ur done, ill //tell my mom not to close the laptop //just dont do stupid stuff please xD ok -at rtnp ty <3 /** * Increments the value within this counter by {@code amount} to a maximum * of {@code maximum} and then returns it. * @param amount the amount to increment it by. * @param maximum the maximum amount it will be incremented to. * @return the value after it is incremented. */ public int incrementAndGet(int amount, int maximum) { value += amount; if(value > maximum) value = maximum; return value; } /** * Increments the value within this counter by {@code amount} and then * returns it. * @param amount the amount to increment it by. * @return the value after it is incremented. */ public int incrementAndGet(int amount) { return incrementAndGet(amount, Integer.MAX_VALUE); } /** * Increments the value within this counter by {@code 1} and then returns * it. * @return the value after it is incremented. */ public int incrementAndGet() { return incrementAndGet(1); } /** * Returns the value within this counter and then decrements it by * {@code amount} to a minimum of {@code minimum}. * @param amount the amount to decrement it by. * @param minimum the minimum amount it will be decremented to. * @return the value before it is decremented. */ public int getAndDecrement(int amount, int minimum) { int val = value; value -= amount; if(value < minimum) value = minimum; return val; } /** * Returns the value within this counter and then decrements it by * {@code amount}. * @param amount the amount to decrement it by. * @return the value before it is decremented. */ public int getAndDecrement(int amount) { return getAndDecrement(amount, Integer.MIN_VALUE); } /** * Returns the value within this counter and then decrements it by an amount * of {@code 1}. * @return the value before it is decremented. */ public int getAndDecrement() { return getAndDecrement(1); } /** * Decrements the value within this counter by {@code amount} to a minimum * of {@code minimum} and then returns it. * @param amount the amount to decrement it by. * @param minimum the minimum amount it will be decremented to. * @return the value after it is decremented. */ public int decrementAndGet(int amount, int minimum) { value -= amount; if(value < minimum) value = minimum; return value; } /** * Decrements the value within this counter by {@code amount} and then * returns it. * @param amount the amount to decrement it by. * @return the value after it is decremented. */ public int decrementAndGet(int amount) { return decrementAndGet(amount, Integer.MIN_VALUE); } /** * Decrements the value within this counter by {@code 1} and then returns * it. * @return the value after it is decremented. */ public int decrementAndGet() { return decrementAndGet(1); } /** * Gets the value present within this counter. This function equates to the * inherited {@link MutableNumber#intValue()} function. * @return the value present. */ public int get() { return value; } /** * Sets the value within this container to {@code value}. * @param value the new value to set. */ public void set(int value) { this.value = value; } }
98425_35
/* Copyright (c) 1996-2013 Clickteam * * This source code is part of the Android exporter for Clickteam Multimedia Fusion 2. * * Permission is hereby granted to any person obtaining a legal copy * of Clickteam Multimedia Fusion 2 to use or modify this source code for * debugging, optimizing, or customizing applications created with * Clickteam Multimedia Fusion 2. Any other use of this source code is prohibited. * * 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. */ //---------------------------------------------------------------------------------- // // COBJECT : Classe de base d'un objet' // //---------------------------------------------------------------------------------- // 12/07/2016 added set BoundingBoxFromWidth ported from iOS , used in: activepicture package Objects; import java.util.ArrayList; import Animations.CAnim; import Animations.CRAni; import Banks.CImageBank; import Banks.CImageInfo; import Frame.CLayer; import Movements.CMoveBullet; import Movements.CMoveDef; import Movements.CRMvt; import OI.CObjectCommon; import Params.PARAM_SHOOT; import RunLoop.CCreateObjectInfo; import RunLoop.CObjInfo; import RunLoop.CRun; import Services.CRect; import Sprites.CMask; import Sprites.CRSpr; import Sprites.CSprite; import Sprites.IDrawable; import Values.CRVal; public abstract class CObject implements IDrawable { public final static short HOF_DESTROYED=0x0001; public final static short HOF_TRUEEVENT=0x0002; public final static short HOF_REALSPRITE=0x0004; public final static short HOF_FADEIN=0x0008; public final static short HOF_FADEOUT=0x0010; public final static short HOF_OWNERDRAW=0x0020; public final static short HOF_NOCOLLISION=0x2000; public final static short HOF_FLOAT=0x4000; public final static short HOF_STRING=(short)0x8000; // HeaderObject public short hoNumber; /// Number of the object public short hoNextSelected; /// Selected object list!!! DO NOT CHANGE POSITION!!! public CRun hoAdRunHeader; /// Run-header address public short hoHFII; /// Number of LevObj public short hoOi; /// Number of OI public short hoNumPrev; /// Same OI previous object public short hoNumNext; /// ... next public short hoType; /// Type of the object public short hoCreationId; /// Number of creation public CObjInfo hoOiList; /// Pointer to OILIST information public int hoEvents; /// Pointer to specific events public ArrayList<Integer> hoPrevNoRepeat=null; /// One-shot event handling public ArrayList<Integer> hoBaseNoRepeat=null; public int hoMark1; /// #of loop marker for the events public int hoMark2; public String hoMT_NodeName; /// Name fo the current node for path movements public int hoEventNumber; /// Number of the event called (for extensions) public CObjectCommon hoCommon; /// Common structure address public int hoCalculX; /// Low weight value public int hoX; /// X coordinate public int hoCalculY; /// Low weight value public int hoY; /// Y coordinate public int hoImgXSpot; /// Hot spot of the current image public int hoImgYSpot; public int hoImgWidth; /// Width of the current picture public int hoImgHeight; public CRect hoRect=new CRect(); /// Display rectangle public int hoImgXAP; public int hoImgYAP; public int hoOEFlags; /// Objects flags public short hoFlags; /// Flags public byte hoSelectedInOR; /// Selection lors d'un evenement OR public int hoOffsetValue; /// Values structure offset public int hoLayer; /// Layer public short hoLimitFlags; /// Collision limitation flags public short hoNextQuickDisplay; /// Quickdraw list public int hoCurrentParam; /// Address of the current parameter public int hoIdentifier; /// ASCII identifier of the object public boolean hoCallRoutine; public boolean isPaused; /// added 290.2 to check if object is paused by physics engine // Classes de gestion communes public CRCom roc; // The CRCom object public CRMvt rom; // The CRMvt object public CRAni roa; // The CRAni object public CRVal rov; // The CRVal object public CRSpr ros; // The CRSpr object public CImageInfo ifoTemp; // Temporary image info public CObject() { } // Routines diverses public void setScale(float fScaleX, float fScaleY, boolean bResample) { boolean bOldResample=false; if ((ros.rsFlags&CRSpr.RSFLAG_SCALE_RESAMPLE)!=0) bOldResample=true; if ( (roc.rcScaleX != fScaleX || roc.rcScaleY != fScaleY) || bOldResample != bResample ) { roc.rcScaleX = fScaleX; roc.rcScaleY = fScaleY; ros.rsFlags &= ~CRSpr.RSFLAG_SCALE_RESAMPLE; if ( bResample ) ros.rsFlags |= CRSpr.RSFLAG_SCALE_RESAMPLE; roc.rcChanged = true; updateImageInfo(); } } public boolean updateImageInfo() { if ( ifoTemp == null ) ifoTemp = new CImageInfo(); if ( hoAdRunHeader.rhApp.imageBank.getImageInfoEx2(ifoTemp, roc.rcImage, roc.rcAngle, roc.rcScaleX, roc.rcScaleY) ) { hoImgWidth=ifoTemp.width; hoImgHeight=ifoTemp.height; hoImgXSpot=ifoTemp.xSpot; hoImgYSpot=ifoTemp.ySpot; hoImgXAP = ifoTemp.xAP; hoImgYAP = ifoTemp.yAP; return true; } return false; } // SHOOT : Cree la balle // ---------------------- public void shtCreate(PARAM_SHOOT p, int x, int y, int dir) { int nLayer = hoLayer; int num=hoAdRunHeader.f_CreateObject(p.cdpHFII, p.cdpOi, x, y, dir, (short)(CRun.COF_NOMOVEMENT|CRun.COF_HIDDEN), nLayer, -1); if (num>=0) { // Cree le movement // ---------------- CObject pHo=hoAdRunHeader.rhObjectList[num]; if (pHo.rom!=null) { pHo.rom.initSimple(pHo, CMoveDef.MVTYPE_BULLET, false); pHo.roc.rcDir=dir; // Met la direction de depart pHo.roc.rcSpeed=p.shtSpeed; // Met la vitesse CMoveBullet mBullet=(CMoveBullet)pHo.rom.rmMovement; mBullet.init2(this); // Hide object if layer hidden // --------------------------- if (nLayer!=-1) { if ( (pHo.hoOEFlags & CObjectCommon.OEFLAG_SPRITES) != 0 ) { // Hide object if layer hidden CLayer layer=hoAdRunHeader.rhFrame.layers[nLayer]; if ( (layer.dwOptions & (CLayer.FLOPT_TOHIDE|CLayer.FLOPT_VISIBLE)) != CLayer.FLOPT_VISIBLE ) { pHo.ros.obHide(); } } } // Met l'objet dans la liste des objets selectionnes // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ hoAdRunHeader.rhEvtProg.evt_AddCurrentObject(pHo); // Force l'animation SHOOT si definie // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if ((hoOEFlags&CObjectCommon.OEFLAG_ANIMATIONS)!=0) { if (roa.anim_Exist(CAnim.ANIMID_SHOOT)) { roa.animation_Force(CAnim.ANIMID_SHOOT); roa.animation_OneLoop(); } } } else { hoAdRunHeader.destroy_Add(pHo.hoNumber); } } } // Fonctions de base public abstract void init(CObjectCommon ocPtr, CCreateObjectInfo cob); public abstract void handle(); public abstract void kill(boolean bFast); public abstract void getZoneInfos(); public abstract void draw(); public abstract CMask getCollisionMask(int flags); @Override public abstract void spriteDraw(CSprite spr, CImageBank bank, int x, int y); @Override public abstract CMask spriteGetMask(); public void modif() { } public void display() { } public void reinitDisplay() { } public int fixedValue() { return (hoCreationId << 16) | ((hoNumber) & 0xFFFF); } public void setBoundingBoxFromWidth(int cx, int cy, int hsx, int hsy) { float nAngle = roc.rcAngle; float fScaleX = roc.rcScaleX; float fScaleY = roc.rcScaleY; // No rotation if ( nAngle == 0 ) { // Stretch en X if ( fScaleX != 1.0f ) { hsx = (int)(hsx * fScaleX); cx = (int)(cx * fScaleX); } // Stretch en Y if ( fScaleY != 1.0f ) { hsy = (int)(hsy * fScaleY); cy = (int)(cy * fScaleY); } } // Rotation else { // Calculate dimensions if ( fScaleX != 1.0f ) { hsx = (int)(hsx * fScaleX); cx = (int)(cx * fScaleX); } if ( fScaleY != 1.0f ) { hsy = (int)(hsy * fScaleY); cy = (int)(cy * fScaleY); } // Rotate float alpha = (float) (nAngle * Math.PI / 180.0f); float cosa = (float) Math.cos(alpha); float sina = (float) Math.sin(alpha); int nx2, ny2; int nx4, ny4; if ( sina >= 0.0f ) { nx2 = (int)(cy * sina + 0.5f); // (1.0f-sina)); // 1-sina est ici pour l'arrondi ?? ny4 = -(int)(cx * sina + 0.5f); // (1.0f-sina)); } else { nx2 = (int)(cy * sina - 0.5f); // (1.0f-sina)); ny4 = -(int)(cx * sina - 0.5f); // (1.0f-sina)); } if ( cosa == 0.0f ) { ny2 = 0; nx4 = 0; } else if ( cosa > 0 ) { ny2 = (int)(cy * cosa + 0.5f); // (1.0f-cosa)); nx4 = (int)(cx * cosa + 0.5f); // (1.0f-cosa)); } else { ny2 = (int)(cy * cosa - 0.5f); // (1.0f-cosa)); nx4 = (int)(cx * cosa - 0.5f); // (1.0f-cosa)); } int nx3 = nx2 + nx4; int ny3 = ny2 + ny4; int nhsx = (int)(hsx * cosa + hsy * sina); int nhsy = (int)(hsy * cosa - hsx * sina); // Faire translation par rapport au hotspot int nx1 = 0; // -nhsx; int ny1 = 0; // -nhsy; // Calculer la nouvelle bounding box (? optimiser ?ventuellement) int x1 = Math.min(nx1, nx2); x1 = Math.min(x1, nx3); x1 = Math.min(x1, nx4); int x2 = Math.max(nx1, nx2); x2 = Math.max(x2, nx3); x2 = Math.max(x2, nx4); int y1 = Math.min(ny1, ny2); y1 = Math.min(y1, ny3); y1 = Math.min(y1, ny4); int y2 = Math.max(ny1, ny2); y2 = Math.max(y2, ny3); y2 = Math.max(y2, ny4); cx = x2 - x1; cy = y2 - y1; hsx = -(x1 - nhsx); hsy = -(y1 - nhsy); } hoImgWidth = cx; hoImgHeight = cy; hoImgXSpot = hsx; hoImgYSpot = hsy; } }
CTFAK/CTFAK
RuntimeData/runtime/app/src/main/java/Objects/CObject.java
4,007
// Cree le movement
line_comment
nl
/* Copyright (c) 1996-2013 Clickteam * * This source code is part of the Android exporter for Clickteam Multimedia Fusion 2. * * Permission is hereby granted to any person obtaining a legal copy * of Clickteam Multimedia Fusion 2 to use or modify this source code for * debugging, optimizing, or customizing applications created with * Clickteam Multimedia Fusion 2. Any other use of this source code is prohibited. * * 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. */ //---------------------------------------------------------------------------------- // // COBJECT : Classe de base d'un objet' // //---------------------------------------------------------------------------------- // 12/07/2016 added set BoundingBoxFromWidth ported from iOS , used in: activepicture package Objects; import java.util.ArrayList; import Animations.CAnim; import Animations.CRAni; import Banks.CImageBank; import Banks.CImageInfo; import Frame.CLayer; import Movements.CMoveBullet; import Movements.CMoveDef; import Movements.CRMvt; import OI.CObjectCommon; import Params.PARAM_SHOOT; import RunLoop.CCreateObjectInfo; import RunLoop.CObjInfo; import RunLoop.CRun; import Services.CRect; import Sprites.CMask; import Sprites.CRSpr; import Sprites.CSprite; import Sprites.IDrawable; import Values.CRVal; public abstract class CObject implements IDrawable { public final static short HOF_DESTROYED=0x0001; public final static short HOF_TRUEEVENT=0x0002; public final static short HOF_REALSPRITE=0x0004; public final static short HOF_FADEIN=0x0008; public final static short HOF_FADEOUT=0x0010; public final static short HOF_OWNERDRAW=0x0020; public final static short HOF_NOCOLLISION=0x2000; public final static short HOF_FLOAT=0x4000; public final static short HOF_STRING=(short)0x8000; // HeaderObject public short hoNumber; /// Number of the object public short hoNextSelected; /// Selected object list!!! DO NOT CHANGE POSITION!!! public CRun hoAdRunHeader; /// Run-header address public short hoHFII; /// Number of LevObj public short hoOi; /// Number of OI public short hoNumPrev; /// Same OI previous object public short hoNumNext; /// ... next public short hoType; /// Type of the object public short hoCreationId; /// Number of creation public CObjInfo hoOiList; /// Pointer to OILIST information public int hoEvents; /// Pointer to specific events public ArrayList<Integer> hoPrevNoRepeat=null; /// One-shot event handling public ArrayList<Integer> hoBaseNoRepeat=null; public int hoMark1; /// #of loop marker for the events public int hoMark2; public String hoMT_NodeName; /// Name fo the current node for path movements public int hoEventNumber; /// Number of the event called (for extensions) public CObjectCommon hoCommon; /// Common structure address public int hoCalculX; /// Low weight value public int hoX; /// X coordinate public int hoCalculY; /// Low weight value public int hoY; /// Y coordinate public int hoImgXSpot; /// Hot spot of the current image public int hoImgYSpot; public int hoImgWidth; /// Width of the current picture public int hoImgHeight; public CRect hoRect=new CRect(); /// Display rectangle public int hoImgXAP; public int hoImgYAP; public int hoOEFlags; /// Objects flags public short hoFlags; /// Flags public byte hoSelectedInOR; /// Selection lors d'un evenement OR public int hoOffsetValue; /// Values structure offset public int hoLayer; /// Layer public short hoLimitFlags; /// Collision limitation flags public short hoNextQuickDisplay; /// Quickdraw list public int hoCurrentParam; /// Address of the current parameter public int hoIdentifier; /// ASCII identifier of the object public boolean hoCallRoutine; public boolean isPaused; /// added 290.2 to check if object is paused by physics engine // Classes de gestion communes public CRCom roc; // The CRCom object public CRMvt rom; // The CRMvt object public CRAni roa; // The CRAni object public CRVal rov; // The CRVal object public CRSpr ros; // The CRSpr object public CImageInfo ifoTemp; // Temporary image info public CObject() { } // Routines diverses public void setScale(float fScaleX, float fScaleY, boolean bResample) { boolean bOldResample=false; if ((ros.rsFlags&CRSpr.RSFLAG_SCALE_RESAMPLE)!=0) bOldResample=true; if ( (roc.rcScaleX != fScaleX || roc.rcScaleY != fScaleY) || bOldResample != bResample ) { roc.rcScaleX = fScaleX; roc.rcScaleY = fScaleY; ros.rsFlags &= ~CRSpr.RSFLAG_SCALE_RESAMPLE; if ( bResample ) ros.rsFlags |= CRSpr.RSFLAG_SCALE_RESAMPLE; roc.rcChanged = true; updateImageInfo(); } } public boolean updateImageInfo() { if ( ifoTemp == null ) ifoTemp = new CImageInfo(); if ( hoAdRunHeader.rhApp.imageBank.getImageInfoEx2(ifoTemp, roc.rcImage, roc.rcAngle, roc.rcScaleX, roc.rcScaleY) ) { hoImgWidth=ifoTemp.width; hoImgHeight=ifoTemp.height; hoImgXSpot=ifoTemp.xSpot; hoImgYSpot=ifoTemp.ySpot; hoImgXAP = ifoTemp.xAP; hoImgYAP = ifoTemp.yAP; return true; } return false; } // SHOOT : Cree la balle // ---------------------- public void shtCreate(PARAM_SHOOT p, int x, int y, int dir) { int nLayer = hoLayer; int num=hoAdRunHeader.f_CreateObject(p.cdpHFII, p.cdpOi, x, y, dir, (short)(CRun.COF_NOMOVEMENT|CRun.COF_HIDDEN), nLayer, -1); if (num>=0) { // Cree le<SUF> // ---------------- CObject pHo=hoAdRunHeader.rhObjectList[num]; if (pHo.rom!=null) { pHo.rom.initSimple(pHo, CMoveDef.MVTYPE_BULLET, false); pHo.roc.rcDir=dir; // Met la direction de depart pHo.roc.rcSpeed=p.shtSpeed; // Met la vitesse CMoveBullet mBullet=(CMoveBullet)pHo.rom.rmMovement; mBullet.init2(this); // Hide object if layer hidden // --------------------------- if (nLayer!=-1) { if ( (pHo.hoOEFlags & CObjectCommon.OEFLAG_SPRITES) != 0 ) { // Hide object if layer hidden CLayer layer=hoAdRunHeader.rhFrame.layers[nLayer]; if ( (layer.dwOptions & (CLayer.FLOPT_TOHIDE|CLayer.FLOPT_VISIBLE)) != CLayer.FLOPT_VISIBLE ) { pHo.ros.obHide(); } } } // Met l'objet dans la liste des objets selectionnes // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ hoAdRunHeader.rhEvtProg.evt_AddCurrentObject(pHo); // Force l'animation SHOOT si definie // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if ((hoOEFlags&CObjectCommon.OEFLAG_ANIMATIONS)!=0) { if (roa.anim_Exist(CAnim.ANIMID_SHOOT)) { roa.animation_Force(CAnim.ANIMID_SHOOT); roa.animation_OneLoop(); } } } else { hoAdRunHeader.destroy_Add(pHo.hoNumber); } } } // Fonctions de base public abstract void init(CObjectCommon ocPtr, CCreateObjectInfo cob); public abstract void handle(); public abstract void kill(boolean bFast); public abstract void getZoneInfos(); public abstract void draw(); public abstract CMask getCollisionMask(int flags); @Override public abstract void spriteDraw(CSprite spr, CImageBank bank, int x, int y); @Override public abstract CMask spriteGetMask(); public void modif() { } public void display() { } public void reinitDisplay() { } public int fixedValue() { return (hoCreationId << 16) | ((hoNumber) & 0xFFFF); } public void setBoundingBoxFromWidth(int cx, int cy, int hsx, int hsy) { float nAngle = roc.rcAngle; float fScaleX = roc.rcScaleX; float fScaleY = roc.rcScaleY; // No rotation if ( nAngle == 0 ) { // Stretch en X if ( fScaleX != 1.0f ) { hsx = (int)(hsx * fScaleX); cx = (int)(cx * fScaleX); } // Stretch en Y if ( fScaleY != 1.0f ) { hsy = (int)(hsy * fScaleY); cy = (int)(cy * fScaleY); } } // Rotation else { // Calculate dimensions if ( fScaleX != 1.0f ) { hsx = (int)(hsx * fScaleX); cx = (int)(cx * fScaleX); } if ( fScaleY != 1.0f ) { hsy = (int)(hsy * fScaleY); cy = (int)(cy * fScaleY); } // Rotate float alpha = (float) (nAngle * Math.PI / 180.0f); float cosa = (float) Math.cos(alpha); float sina = (float) Math.sin(alpha); int nx2, ny2; int nx4, ny4; if ( sina >= 0.0f ) { nx2 = (int)(cy * sina + 0.5f); // (1.0f-sina)); // 1-sina est ici pour l'arrondi ?? ny4 = -(int)(cx * sina + 0.5f); // (1.0f-sina)); } else { nx2 = (int)(cy * sina - 0.5f); // (1.0f-sina)); ny4 = -(int)(cx * sina - 0.5f); // (1.0f-sina)); } if ( cosa == 0.0f ) { ny2 = 0; nx4 = 0; } else if ( cosa > 0 ) { ny2 = (int)(cy * cosa + 0.5f); // (1.0f-cosa)); nx4 = (int)(cx * cosa + 0.5f); // (1.0f-cosa)); } else { ny2 = (int)(cy * cosa - 0.5f); // (1.0f-cosa)); nx4 = (int)(cx * cosa - 0.5f); // (1.0f-cosa)); } int nx3 = nx2 + nx4; int ny3 = ny2 + ny4; int nhsx = (int)(hsx * cosa + hsy * sina); int nhsy = (int)(hsy * cosa - hsx * sina); // Faire translation par rapport au hotspot int nx1 = 0; // -nhsx; int ny1 = 0; // -nhsy; // Calculer la nouvelle bounding box (? optimiser ?ventuellement) int x1 = Math.min(nx1, nx2); x1 = Math.min(x1, nx3); x1 = Math.min(x1, nx4); int x2 = Math.max(nx1, nx2); x2 = Math.max(x2, nx3); x2 = Math.max(x2, nx4); int y1 = Math.min(ny1, ny2); y1 = Math.min(y1, ny3); y1 = Math.min(y1, ny4); int y2 = Math.max(ny1, ny2); y2 = Math.max(y2, ny3); y2 = Math.max(y2, ny4); cx = x2 - x1; cy = y2 - y1; hsx = -(x1 - nhsx); hsy = -(y1 - nhsy); } hoImgWidth = cx; hoImgHeight = cy; hoImgXSpot = hsx; hoImgYSpot = hsy; } }
17339_2
package character; import map.Player; public abstract class MainCharacter extends Hero { private int debt = 0; protected MainCharacter(String playername) { super(playername); this.info = "ApoRed (das heißt Red!) ist der Opa\n" + " Hasen machen nicht immer dieselben stepper sie usen auch andere stepper um ihren Horizont zu weiten, denn ein Hase ohne wissen ist nur ein Go.\n" + " // Vorbilder zu sneaken kommt immer nice, aber selbst zu seinem eigenen Vorbild zu werden ist das Ziel eines Hasen"; } // ability (Burge-Geld) genereiert Ressourcen public void ability(Player player) { // cooldown adden vlt. für alle Heros player.setFood(player.getFood() + 5); player.setStone(player.getStone() + 5); player.setWood(player.getWood() + 5); debt = debt + 5; } // ultimate (Insi-Modus) kehrt deine Schulden in Ressourcen um und outplayed // Vater Staat. Es zährt allerdings an den Kräften des MainCharacter, weswegen // es Nahrung benötigt public void ultimate(Player player) { if (debt > 50 && player.getFood() >= 10) { player.setWood(player.getWood() + debt); player.setWood(player.getWood() + debt); player.setFood(player.getFood() - 10); debt = 0; } } }
CZG-KoR/TheGame
src/character/MainCharacter.java
422
// cooldown adden vlt. für alle Heros
line_comment
nl
package character; import map.Player; public abstract class MainCharacter extends Hero { private int debt = 0; protected MainCharacter(String playername) { super(playername); this.info = "ApoRed (das heißt Red!) ist der Opa\n" + " Hasen machen nicht immer dieselben stepper sie usen auch andere stepper um ihren Horizont zu weiten, denn ein Hase ohne wissen ist nur ein Go.\n" + " // Vorbilder zu sneaken kommt immer nice, aber selbst zu seinem eigenen Vorbild zu werden ist das Ziel eines Hasen"; } // ability (Burge-Geld) genereiert Ressourcen public void ability(Player player) { // cooldown adden<SUF> player.setFood(player.getFood() + 5); player.setStone(player.getStone() + 5); player.setWood(player.getWood() + 5); debt = debt + 5; } // ultimate (Insi-Modus) kehrt deine Schulden in Ressourcen um und outplayed // Vater Staat. Es zährt allerdings an den Kräften des MainCharacter, weswegen // es Nahrung benötigt public void ultimate(Player player) { if (debt > 50 && player.getFood() >= 10) { player.setWood(player.getWood() + debt); player.setWood(player.getWood() + debt); player.setFood(player.getFood() - 10); debt = 0; } } }
84651_4
package com.example.bluetooth.programme.tcp; import com.example.bluetooth.programme.erstellen.Point; import java.util.Random; public class TCP { //alle Angaben in mm private RPoint base; private RPoint joint01; private RPoint joint02; private RPoint tcp; private int axis1DegreeTCP;//axis1Degree des TCPs private int axis2DegreeTCP;//axis2Degree des TCPs private int axis3DegreeTCP;//axis3Degree des TCPs private int axis4DegreeTCP;//axis4Degree des TCPs private int axis2DegreeOriginal; private int axis3DegreeOriginal; private int axis4DegreeOriginal; private double distanceBase_joint01; private double distanceJoint01_joint02; private double distanceJoint02_tcp; int reset; private RPoint rPointGesucht; private Point returnPoint; private String achse;//welche achse grade dran ist public TCP(){ init(); } private void init(){ base=new RPoint(0,46.75,0); distanceBase_joint01=120; distanceJoint01_joint02=120; distanceJoint02_tcp=183.7; reset=0; } private void calcJoint01(int axis1Degree,int axis2Degree){ //Axis2Degree = derzeitge Grad der Achse 2 //Achse 2 = Servomotoren an Base axis1Degree-=90; //Y, welches quasi die Höhe dieses Punktes darstellt, ist von der Stellung von Achse 1 unabhängig, da die Höhe immer gleich ist. double y=Math.sin(Math.toRadians(axis2Degree))*distanceBase_joint01; double tempHY=Math.cos(Math.toRadians(axis2Degree))*distanceBase_joint01; double z=Math.cos(Math.toRadians(axis1Degree))*tempHY; double x=Math.sin(Math.toRadians(axis1Degree))*tempHY; joint01=base.add(x,y,z); //System.out.println("JOINT01 - X: "+joint01.getX()+", Y: "+joint01.getY()+", Z: "+joint01.getZ()); } private void calcJoint02(int axis1Degree, int axis3Degree){ //Axis3Degree = derzeitge Grad der Achse 3 //Achse 3 = Servomotoren an Joint01 axis1Degree-=90; //Y, welches quasi die Höhe dieses Punktes darstellt, ist von der Stellung von Achse 1 unabhängig, da die Höhe an jeder Drehposition gleich ist. double y=Math.sin(Math.toRadians(axis3Degree))*distanceJoint01_joint02; double tempHY=Math.cos(Math.toRadians(axis3Degree))*distanceJoint01_joint02; double z=Math.cos(Math.toRadians(axis1Degree))*tempHY; double x=Math.sin(Math.toRadians(axis1Degree))*tempHY; joint02=joint01.add(x,y,z); //System.out.println("JOINT02 - X: "+joint02.getX()+", Y: "+joint02.getY()+", Z: "+joint02.getZ()); } private void calcTCP(int axis1Degree, int axis4Degree){ //Axis3Degree = derzeitge Grad der Achse 4 //Achse 4 = Servomotoren an Joint02 axis1Degree-=90; //Y, welches quasi die Höhe dieses Punktes darstellt, ist von der Stellung von Achse 1 unabhängig, da die Höhe an jeder Drehposition gleich ist. double y=Math.sin(Math.toRadians(axis4Degree))*distanceJoint02_tcp; double tempHY=Math.cos(Math.toRadians(axis4Degree))*distanceJoint02_tcp; double z=Math.cos(Math.toRadians(axis1Degree))*tempHY; double x=Math.sin(Math.toRadians(axis1Degree))*tempHY; tcp=joint02.add(x,y,z); //System.out.println("TCP - X: "+tcp.getX()+", Y: "+tcp.getY()+", Z: "+tcp.getZ()); } public RPoint getTCP(Point point){ int axis1Degree=point.getAxisOne(); int axis2Degree=point.getAxisTwo(); int axis3Degree=point.getAxisThree(); int axis4Degree=point.getAxisFour(); //den wahren Winkel der achse zur Bodenplatte berechnen -> Zettel dienen zur genauen Angabe wie gerechnet wurde axis3Degree = calcRealAngle(axis2Degree, axis3Degree); axis4Degree = calcRealAngle(axis3Degree,axis4Degree); axis1DegreeTCP=axis1Degree; axis2DegreeTCP=axis2Degree; axis3DegreeTCP=axis3Degree; axis4DegreeTCP=axis4Degree; calcJoint01(axis1Degree,axis2Degree); calcJoint02(axis1Degree,axis3Degree); calcTCP(axis1Degree,axis4Degree); return tcp; } public Point calcAxes(RPoint rPoint){ //Gibt einen Point mit den Achsengraden zurück, an denen der Roboter am rPoint steht double x=rPoint.getX(); double y=rPoint.getY(); double z=rPoint.getZ(); int axis1Degree= (int) Math.toDegrees(Math.atan(z/x)); rPointGesucht=rPoint; axis2DegreeOriginal=axis2DegreeTCP; axis3DegreeOriginal=axis3DegreeTCP; axis4DegreeOriginal=axis4DegreeTCP; test(axis1Degree,axis2DegreeOriginal,axis3DegreeOriginal,axis4DegreeOriginal,getTCP(new Point(axis1DegreeTCP,axis2DegreeTCP,axis3DegreeTCP,axis4DegreeTCP,0,0))); return returnPoint; } private void test(int axis1Degree, int axis2Degree,int axis3Degree, int axis4Degree,RPoint curRPoint){ double xSoll=rPointGesucht.getZ()/Math.sin(Math.toRadians(axis1Degree)); double ySoll = rPointGesucht.getY(); double xIst = curRPoint.getZ()/Math.sin(Math.toRadians(axis1Degree)); double yIst = curRPoint.getY(); System.out.println("xIst: "+xIst+", yIst: "+yIst); double yDiff=ySoll-yIst;//Um soviel höhe muss der TCP geändert werden double xDiff=xSoll-xIst;//Um soviel Abstand muss der TCP geändert werden double distanz=Math.sqrt(Math.abs(yDiff*yDiff)+Math.abs(xDiff*xDiff));//Distanz zum derzeitigen TCP //anhand dieser distanz wird nun im trial and error verfahren durchprobiert, welche achstenstellungen die distanz verringern Random rnd=new Random(); boolean[] bool=new boolean[]{rnd.nextBoolean(),rnd.nextBoolean(),rnd.nextBoolean()}; int axis2DegreeTemp=axis2Degree; int axis3DegreeTemp=axis3Degree; int axis4DegreeTemp=axis4Degree; if(bool[0]){ axis2DegreeTemp++; }else{ axis2DegreeTemp--; } if(bool[1]){ axis3DegreeTemp++; }else{ axis3DegreeTemp--; } if(bool[2]){ axis4DegreeTemp++; }else{ axis4DegreeTemp--; } RPoint tcpNew=getTCP(new Point(axis1Degree,axis2DegreeTemp,axis3DegreeTemp,axis4DegreeTemp,0,0)); xIst=tcpNew.getZ()/Math.sin(Math.toRadians(axis1Degree)); yIst = tcpNew.getY(); yDiff=ySoll-yIst;//Um soviel höhe muss der TCP geändert werden xDiff=xSoll-xIst;//Um soviel Abstand muss der TCP geändert werden double distanzNew=Math.sqrt(Math.abs(yDiff*yDiff)+Math.abs(xDiff*xDiff));//Distanz zum gewünschten TCP if(distanzNew<=1.0){ System.out.println("PUNKT GEFUNDEN"); returnPoint= new Point(axis1Degree,axis2DegreeTemp,axis3DegreeTemp,axis4DegreeTemp,0,0); System.out.println("Achse1: "+returnPoint.getAxisOne()+", Achse2: "+returnPoint.getAxisTwo()+", Achse3: "+returnPoint.getAxisThree()+", Achse4: "+returnPoint.getAxisFour()); }else if(axis2DegreeTemp>180||axis2DegreeTemp<0||axis3DegreeTemp>180||axis3DegreeTemp<0||axis4DegreeTemp>180||axis4DegreeTemp<0) { reset = 0; System.out.println("AUFRUF0"); curRPoint=getTCP(new Point(axis1Degree,axis2DegreeOriginal,axis3DegreeOriginal,axis4DegreeOriginal,0,0)); test(axis1Degree,axis2DegreeOriginal,axis3DegreeOriginal,axis4DegreeOriginal,curRPoint); }else{ System.out.println("distanzNew: "+distanzNew+", distanz: "+distanz); if(distanzNew<distanz){ //Änderungen haben sich dem neuen Punkt angenähert reset=0; System.out.println("IST ANGENÄHERT: "+distanzNew); System.out.println("AUFRUF1"); test(axis1Degree,axis2DegreeTemp,axis3DegreeTemp,axis4DegreeTemp,tcpNew); }else{ reset++; System.out.println("NICHT ANGENÄHERT: "+distanz+", reset wert ist auf "+reset); //Änderungen haben nichts gebracht //nun kann es sein, dass die änderungen nichts mehr bringen und eine komplett andere stellung benötigt wird. //wenn nach 5 achsenÄnderungen die distanz nicht verringert wird, dann wird resetet if(reset>=20){ System.out.println("RESET"); reset=0; curRPoint=getTCP(new Point(axis1Degree,axis2DegreeOriginal,axis3DegreeOriginal,axis4DegreeOriginal,0,0)); System.out.println("AUFRUF2"); test(axis1Degree,axis2DegreeOriginal,axis3DegreeOriginal,axis4DegreeOriginal,curRPoint); }else{ System.out.println("AUFRUF3"); test(axis1Degree,axis2Degree,axis3Degree,axis4Degree,curRPoint); } } } System.out.println("RETURN"); } private int calcRealAngle(int firstAxisDegree,int secondAxisDegree){ int x=90+secondAxisDegree; int y1=firstAxisDegree; int y=180; int y2=y-y1; int x2=y2; int x1=x-x2; //System.out.println("Real Angle: "+x1); return x1; } }
CaZZe-dv/RoboterApp
app/src/main/java/com/example/bluetooth/programme/tcp/TCP.java
3,325
//axis4Degree des TCPs
line_comment
nl
package com.example.bluetooth.programme.tcp; import com.example.bluetooth.programme.erstellen.Point; import java.util.Random; public class TCP { //alle Angaben in mm private RPoint base; private RPoint joint01; private RPoint joint02; private RPoint tcp; private int axis1DegreeTCP;//axis1Degree des TCPs private int axis2DegreeTCP;//axis2Degree des TCPs private int axis3DegreeTCP;//axis3Degree des TCPs private int axis4DegreeTCP;//axis4Degree des<SUF> private int axis2DegreeOriginal; private int axis3DegreeOriginal; private int axis4DegreeOriginal; private double distanceBase_joint01; private double distanceJoint01_joint02; private double distanceJoint02_tcp; int reset; private RPoint rPointGesucht; private Point returnPoint; private String achse;//welche achse grade dran ist public TCP(){ init(); } private void init(){ base=new RPoint(0,46.75,0); distanceBase_joint01=120; distanceJoint01_joint02=120; distanceJoint02_tcp=183.7; reset=0; } private void calcJoint01(int axis1Degree,int axis2Degree){ //Axis2Degree = derzeitge Grad der Achse 2 //Achse 2 = Servomotoren an Base axis1Degree-=90; //Y, welches quasi die Höhe dieses Punktes darstellt, ist von der Stellung von Achse 1 unabhängig, da die Höhe immer gleich ist. double y=Math.sin(Math.toRadians(axis2Degree))*distanceBase_joint01; double tempHY=Math.cos(Math.toRadians(axis2Degree))*distanceBase_joint01; double z=Math.cos(Math.toRadians(axis1Degree))*tempHY; double x=Math.sin(Math.toRadians(axis1Degree))*tempHY; joint01=base.add(x,y,z); //System.out.println("JOINT01 - X: "+joint01.getX()+", Y: "+joint01.getY()+", Z: "+joint01.getZ()); } private void calcJoint02(int axis1Degree, int axis3Degree){ //Axis3Degree = derzeitge Grad der Achse 3 //Achse 3 = Servomotoren an Joint01 axis1Degree-=90; //Y, welches quasi die Höhe dieses Punktes darstellt, ist von der Stellung von Achse 1 unabhängig, da die Höhe an jeder Drehposition gleich ist. double y=Math.sin(Math.toRadians(axis3Degree))*distanceJoint01_joint02; double tempHY=Math.cos(Math.toRadians(axis3Degree))*distanceJoint01_joint02; double z=Math.cos(Math.toRadians(axis1Degree))*tempHY; double x=Math.sin(Math.toRadians(axis1Degree))*tempHY; joint02=joint01.add(x,y,z); //System.out.println("JOINT02 - X: "+joint02.getX()+", Y: "+joint02.getY()+", Z: "+joint02.getZ()); } private void calcTCP(int axis1Degree, int axis4Degree){ //Axis3Degree = derzeitge Grad der Achse 4 //Achse 4 = Servomotoren an Joint02 axis1Degree-=90; //Y, welches quasi die Höhe dieses Punktes darstellt, ist von der Stellung von Achse 1 unabhängig, da die Höhe an jeder Drehposition gleich ist. double y=Math.sin(Math.toRadians(axis4Degree))*distanceJoint02_tcp; double tempHY=Math.cos(Math.toRadians(axis4Degree))*distanceJoint02_tcp; double z=Math.cos(Math.toRadians(axis1Degree))*tempHY; double x=Math.sin(Math.toRadians(axis1Degree))*tempHY; tcp=joint02.add(x,y,z); //System.out.println("TCP - X: "+tcp.getX()+", Y: "+tcp.getY()+", Z: "+tcp.getZ()); } public RPoint getTCP(Point point){ int axis1Degree=point.getAxisOne(); int axis2Degree=point.getAxisTwo(); int axis3Degree=point.getAxisThree(); int axis4Degree=point.getAxisFour(); //den wahren Winkel der achse zur Bodenplatte berechnen -> Zettel dienen zur genauen Angabe wie gerechnet wurde axis3Degree = calcRealAngle(axis2Degree, axis3Degree); axis4Degree = calcRealAngle(axis3Degree,axis4Degree); axis1DegreeTCP=axis1Degree; axis2DegreeTCP=axis2Degree; axis3DegreeTCP=axis3Degree; axis4DegreeTCP=axis4Degree; calcJoint01(axis1Degree,axis2Degree); calcJoint02(axis1Degree,axis3Degree); calcTCP(axis1Degree,axis4Degree); return tcp; } public Point calcAxes(RPoint rPoint){ //Gibt einen Point mit den Achsengraden zurück, an denen der Roboter am rPoint steht double x=rPoint.getX(); double y=rPoint.getY(); double z=rPoint.getZ(); int axis1Degree= (int) Math.toDegrees(Math.atan(z/x)); rPointGesucht=rPoint; axis2DegreeOriginal=axis2DegreeTCP; axis3DegreeOriginal=axis3DegreeTCP; axis4DegreeOriginal=axis4DegreeTCP; test(axis1Degree,axis2DegreeOriginal,axis3DegreeOriginal,axis4DegreeOriginal,getTCP(new Point(axis1DegreeTCP,axis2DegreeTCP,axis3DegreeTCP,axis4DegreeTCP,0,0))); return returnPoint; } private void test(int axis1Degree, int axis2Degree,int axis3Degree, int axis4Degree,RPoint curRPoint){ double xSoll=rPointGesucht.getZ()/Math.sin(Math.toRadians(axis1Degree)); double ySoll = rPointGesucht.getY(); double xIst = curRPoint.getZ()/Math.sin(Math.toRadians(axis1Degree)); double yIst = curRPoint.getY(); System.out.println("xIst: "+xIst+", yIst: "+yIst); double yDiff=ySoll-yIst;//Um soviel höhe muss der TCP geändert werden double xDiff=xSoll-xIst;//Um soviel Abstand muss der TCP geändert werden double distanz=Math.sqrt(Math.abs(yDiff*yDiff)+Math.abs(xDiff*xDiff));//Distanz zum derzeitigen TCP //anhand dieser distanz wird nun im trial and error verfahren durchprobiert, welche achstenstellungen die distanz verringern Random rnd=new Random(); boolean[] bool=new boolean[]{rnd.nextBoolean(),rnd.nextBoolean(),rnd.nextBoolean()}; int axis2DegreeTemp=axis2Degree; int axis3DegreeTemp=axis3Degree; int axis4DegreeTemp=axis4Degree; if(bool[0]){ axis2DegreeTemp++; }else{ axis2DegreeTemp--; } if(bool[1]){ axis3DegreeTemp++; }else{ axis3DegreeTemp--; } if(bool[2]){ axis4DegreeTemp++; }else{ axis4DegreeTemp--; } RPoint tcpNew=getTCP(new Point(axis1Degree,axis2DegreeTemp,axis3DegreeTemp,axis4DegreeTemp,0,0)); xIst=tcpNew.getZ()/Math.sin(Math.toRadians(axis1Degree)); yIst = tcpNew.getY(); yDiff=ySoll-yIst;//Um soviel höhe muss der TCP geändert werden xDiff=xSoll-xIst;//Um soviel Abstand muss der TCP geändert werden double distanzNew=Math.sqrt(Math.abs(yDiff*yDiff)+Math.abs(xDiff*xDiff));//Distanz zum gewünschten TCP if(distanzNew<=1.0){ System.out.println("PUNKT GEFUNDEN"); returnPoint= new Point(axis1Degree,axis2DegreeTemp,axis3DegreeTemp,axis4DegreeTemp,0,0); System.out.println("Achse1: "+returnPoint.getAxisOne()+", Achse2: "+returnPoint.getAxisTwo()+", Achse3: "+returnPoint.getAxisThree()+", Achse4: "+returnPoint.getAxisFour()); }else if(axis2DegreeTemp>180||axis2DegreeTemp<0||axis3DegreeTemp>180||axis3DegreeTemp<0||axis4DegreeTemp>180||axis4DegreeTemp<0) { reset = 0; System.out.println("AUFRUF0"); curRPoint=getTCP(new Point(axis1Degree,axis2DegreeOriginal,axis3DegreeOriginal,axis4DegreeOriginal,0,0)); test(axis1Degree,axis2DegreeOriginal,axis3DegreeOriginal,axis4DegreeOriginal,curRPoint); }else{ System.out.println("distanzNew: "+distanzNew+", distanz: "+distanz); if(distanzNew<distanz){ //Änderungen haben sich dem neuen Punkt angenähert reset=0; System.out.println("IST ANGENÄHERT: "+distanzNew); System.out.println("AUFRUF1"); test(axis1Degree,axis2DegreeTemp,axis3DegreeTemp,axis4DegreeTemp,tcpNew); }else{ reset++; System.out.println("NICHT ANGENÄHERT: "+distanz+", reset wert ist auf "+reset); //Änderungen haben nichts gebracht //nun kann es sein, dass die änderungen nichts mehr bringen und eine komplett andere stellung benötigt wird. //wenn nach 5 achsenÄnderungen die distanz nicht verringert wird, dann wird resetet if(reset>=20){ System.out.println("RESET"); reset=0; curRPoint=getTCP(new Point(axis1Degree,axis2DegreeOriginal,axis3DegreeOriginal,axis4DegreeOriginal,0,0)); System.out.println("AUFRUF2"); test(axis1Degree,axis2DegreeOriginal,axis3DegreeOriginal,axis4DegreeOriginal,curRPoint); }else{ System.out.println("AUFRUF3"); test(axis1Degree,axis2Degree,axis3Degree,axis4Degree,curRPoint); } } } System.out.println("RETURN"); } private int calcRealAngle(int firstAxisDegree,int secondAxisDegree){ int x=90+secondAxisDegree; int y1=firstAxisDegree; int y=180; int y2=y-y1; int x2=y2; int x1=x-x2; //System.out.println("Real Angle: "+x1); return x1; } }
195541_2
package nl.alvinvrolijk.kitpvp.utils; import nl.alvinvrolijk.kitpvp.data.KitPvpPlayer; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.scoreboard.DisplaySlot; import org.bukkit.scoreboard.Objective; import org.bukkit.scoreboard.Team; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.UUID; public class Scoreboard { public static void createScoreboard(Player player) { Scoreboard helper = Scoreboard.createScore(player); // Create new score helper.setTitle("&6&lKitPvP"); helper.setSlot(10, "&6Kills:"); helper.setSlot(9, "&eLoading..."); // Set placeholder helper.setSlot(8, " "); helper.setSlot(7, "&6Deaths:"); helper.setSlot(6, "&eLoading..."); // Set placeholder helper.setSlot(5, " "); helper.setSlot(4, "&6K/D Ratio:"); helper.setSlot(3, "&eLoading..."); // Set placeholder helper.setSlot(2, " "); helper.setSlot(1, "&cplay.dusdavidgames.nl"); } public static void updateScoreboard(KitPvpPlayer kitPvpPlayer) { if (Scoreboard.hasScore(kitPvpPlayer.getPlayer())) { // Check if player has a score Scoreboard helper = Scoreboard.getByPlayer(kitPvpPlayer.getPlayer()); // Get scoreboard helper // Get data int kills = kitPvpPlayer.getKills(); // Get kills int deaths = kitPvpPlayer.getDeaths(); // Get deaths // Calculate K/D ratio (WARNING: this can output unlimited digits) String killDeathRatio; try { // In case a integer is 0 (it is not possible to divide by 0, remember?) if (kills == 0 && deaths == 0) { killDeathRatio = String.valueOf(0.00); } else if (kills != 0 && deaths == 0) { killDeathRatio = String.valueOf(kills); } else if (kills == 0 && deaths != 0) { killDeathRatio = String.valueOf(0); } else { killDeathRatio = String.format(Locale.US, "%.2f", (double) kills / deaths); } } catch (NullPointerException exception) { killDeathRatio = "&cError"; } // Set data helper.setSlot(9, "&e" + kills); // Update kills helper.setSlot(6, "&e" + deaths); // Update deaths helper.setSlot(3, "&e" + killDeathRatio); // Update kill-death ratio } } public static void removeScoreboard(Player player) { if (Scoreboard.hasScore(player)) { Scoreboard.removeScore(player); } } private static HashMap<UUID, Scoreboard> players = new HashMap<>(); public static boolean hasScore(Player player) { return players.containsKey(player.getUniqueId()); } public static Scoreboard createScore(Player player) { return new Scoreboard(player); } public static Scoreboard getByPlayer(Player player) { return players.get(player.getUniqueId()); } public static Scoreboard removeScore(Player player) { return players.remove(player.getUniqueId()); } private org.bukkit.scoreboard.Scoreboard scoreboard; private Objective sidebar; private Scoreboard(Player player) { scoreboard = Bukkit.getScoreboardManager().getNewScoreboard(); sidebar = scoreboard.registerNewObjective("sidebar", "dummy", "sidebar"); sidebar.setDisplaySlot(DisplaySlot.SIDEBAR); // Create Teams for(int i=1; i<=15; i++) { Team team = scoreboard.registerNewTeam("SLOT_" + i); team.addEntry(genEntry(i)); } player.setScoreboard(scoreboard); players.put(player.getUniqueId(), this); } public void setTitle(String title) { title = ChatColor.translateAlternateColorCodes('&', title); sidebar.setDisplayName(title.length()>32 ? title.substring(0, 32) : title); } public void setSlot(int slot, String text) { Team team = scoreboard.getTeam("SLOT_" + slot); String entry = genEntry(slot); if(!scoreboard.getEntries().contains(entry)) { sidebar.getScore(entry).setScore(slot); } text = ChatColor.translateAlternateColorCodes('&', text); String pre = getFirstSplit(text); String suf = getFirstSplit(ChatColor.getLastColors(pre) + getSecondSplit(text)); team.setPrefix(pre); team.setSuffix(suf); } public void removeSlot(int slot) { String entry = genEntry(slot); if(scoreboard.getEntries().contains(entry)) { scoreboard.resetScores(entry); } } public void setSlotsFromList(List<String> list) { while(list.size()>15) { list.remove(list.size()-1); } int slot = list.size(); if(slot<15) { for(int i=(slot +1); i<=15; i++) { removeSlot(i); } } for(String line : list) { setSlot(slot, line); slot--; } } private String genEntry(int slot) { return ChatColor.values()[slot].toString(); } private String getFirstSplit(String s) { return s.length()>16 ? s.substring(0, 16) : s; } private String getSecondSplit(String s) { if(s.length()>32) { s = s.substring(0, 32); } return s.length()>16 ? s.substring(16) : ""; } }
Caaarlowsz/KitPvP-44
src/main/java/nl/alvinvrolijk/kitpvp/utils/Scoreboard.java
1,711
// Get scoreboard helper
line_comment
nl
package nl.alvinvrolijk.kitpvp.utils; import nl.alvinvrolijk.kitpvp.data.KitPvpPlayer; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.scoreboard.DisplaySlot; import org.bukkit.scoreboard.Objective; import org.bukkit.scoreboard.Team; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.UUID; public class Scoreboard { public static void createScoreboard(Player player) { Scoreboard helper = Scoreboard.createScore(player); // Create new score helper.setTitle("&6&lKitPvP"); helper.setSlot(10, "&6Kills:"); helper.setSlot(9, "&eLoading..."); // Set placeholder helper.setSlot(8, " "); helper.setSlot(7, "&6Deaths:"); helper.setSlot(6, "&eLoading..."); // Set placeholder helper.setSlot(5, " "); helper.setSlot(4, "&6K/D Ratio:"); helper.setSlot(3, "&eLoading..."); // Set placeholder helper.setSlot(2, " "); helper.setSlot(1, "&cplay.dusdavidgames.nl"); } public static void updateScoreboard(KitPvpPlayer kitPvpPlayer) { if (Scoreboard.hasScore(kitPvpPlayer.getPlayer())) { // Check if player has a score Scoreboard helper = Scoreboard.getByPlayer(kitPvpPlayer.getPlayer()); // Get scoreboard<SUF> // Get data int kills = kitPvpPlayer.getKills(); // Get kills int deaths = kitPvpPlayer.getDeaths(); // Get deaths // Calculate K/D ratio (WARNING: this can output unlimited digits) String killDeathRatio; try { // In case a integer is 0 (it is not possible to divide by 0, remember?) if (kills == 0 && deaths == 0) { killDeathRatio = String.valueOf(0.00); } else if (kills != 0 && deaths == 0) { killDeathRatio = String.valueOf(kills); } else if (kills == 0 && deaths != 0) { killDeathRatio = String.valueOf(0); } else { killDeathRatio = String.format(Locale.US, "%.2f", (double) kills / deaths); } } catch (NullPointerException exception) { killDeathRatio = "&cError"; } // Set data helper.setSlot(9, "&e" + kills); // Update kills helper.setSlot(6, "&e" + deaths); // Update deaths helper.setSlot(3, "&e" + killDeathRatio); // Update kill-death ratio } } public static void removeScoreboard(Player player) { if (Scoreboard.hasScore(player)) { Scoreboard.removeScore(player); } } private static HashMap<UUID, Scoreboard> players = new HashMap<>(); public static boolean hasScore(Player player) { return players.containsKey(player.getUniqueId()); } public static Scoreboard createScore(Player player) { return new Scoreboard(player); } public static Scoreboard getByPlayer(Player player) { return players.get(player.getUniqueId()); } public static Scoreboard removeScore(Player player) { return players.remove(player.getUniqueId()); } private org.bukkit.scoreboard.Scoreboard scoreboard; private Objective sidebar; private Scoreboard(Player player) { scoreboard = Bukkit.getScoreboardManager().getNewScoreboard(); sidebar = scoreboard.registerNewObjective("sidebar", "dummy", "sidebar"); sidebar.setDisplaySlot(DisplaySlot.SIDEBAR); // Create Teams for(int i=1; i<=15; i++) { Team team = scoreboard.registerNewTeam("SLOT_" + i); team.addEntry(genEntry(i)); } player.setScoreboard(scoreboard); players.put(player.getUniqueId(), this); } public void setTitle(String title) { title = ChatColor.translateAlternateColorCodes('&', title); sidebar.setDisplayName(title.length()>32 ? title.substring(0, 32) : title); } public void setSlot(int slot, String text) { Team team = scoreboard.getTeam("SLOT_" + slot); String entry = genEntry(slot); if(!scoreboard.getEntries().contains(entry)) { sidebar.getScore(entry).setScore(slot); } text = ChatColor.translateAlternateColorCodes('&', text); String pre = getFirstSplit(text); String suf = getFirstSplit(ChatColor.getLastColors(pre) + getSecondSplit(text)); team.setPrefix(pre); team.setSuffix(suf); } public void removeSlot(int slot) { String entry = genEntry(slot); if(scoreboard.getEntries().contains(entry)) { scoreboard.resetScores(entry); } } public void setSlotsFromList(List<String> list) { while(list.size()>15) { list.remove(list.size()-1); } int slot = list.size(); if(slot<15) { for(int i=(slot +1); i<=15; i++) { removeSlot(i); } } for(String line : list) { setSlot(slot, line); slot--; } } private String genEntry(int slot) { return ChatColor.values()[slot].toString(); } private String getFirstSplit(String s) { return s.length()>16 ? s.substring(0, 16) : s; } private String getSecondSplit(String s) { if(s.length()>32) { s = s.substring(0, 32); } return s.length()>16 ? s.substring(16) : ""; } }
158361_1
package me.goowen.kitpvp.modules.kits; import me.goowen.kitpvp.Kitpvp; import me.goowen.kitpvp.modules.config.ConfigModule; import me.goowen.kitpvp.modules.utilities.ItemBuilder; import org.bukkit.ChatColor; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import java.util.List; import java.util.Objects; public class KitsManager { private ConfigModule configModule = Kitpvp.getConfigModule(); private Kitpvp plugin = Kitpvp.getInstance(); /** * Slaat de kit op in een config vanuit de spelers inventory op basis van naam! * @param player de speler wiens inventory moet worden opgeslagen als kit! * @param name de naam van de kit! */ public void saveKit(Player player, String name) { configModule.getKitsConfig().getConfigConfiguration().set("kits." + name + ".armor", player.getInventory().getArmorContents()); configModule.getKitsConfig().getConfigConfiguration().set("kits." + name + ".items", player.getInventory().getContents()); configModule.getKitsConfig().getConfigConfiguration().set("kits." + name + ".icon", new ItemBuilder(player.getInventory().getItemInMainHand().clone()).setName(ChatColor.DARK_AQUA + name).addLoreLine(ChatColor.GRAY + "" + ChatColor.UNDERLINE + "Click to select this kit").toItemStack()); configModule.getKitsConfig().saveAsync(configModule.getKitsConfig()); } public void deleteKit(String name) { configModule.getKitsConfig().getConfigConfiguration().set("kits." + name, null); configModule.getKitsConfig().saveAsync(configModule.getKitsConfig()); } /** * Haalt de kit op uit de config en zet hem om in een inventory. * Geeft de zojuist opgehaalde kit aan de speler. * @param player de speler die de kit moet krijgen. * @param name de naam van de kit die de speler moet krijgen. */ @SuppressWarnings("unchecked") public void giveKit(Player player, String name) { FileConfiguration kitsConfig = configModule.getKitsConfig().getConfigConfiguration(); //Haalt de armor op een geeft deze. ItemStack[] content = ((List<ItemStack>) Objects.requireNonNull(kitsConfig.get("kits." + name + ".armor"))).toArray(new ItemStack[0]); player.getInventory().setArmorContents(content); //Haalt de Items in de inventory op een geeft deze. content = ((List<ItemStack>) Objects.requireNonNull(kitsConfig.get("kits." + name + ".items"))).toArray(new ItemStack[0]); player.getInventory().setContents(content); } /** * Maakt het kits menu aan en toont hem aan de speler. * @param player de speler die het menu moet krijgen */ public void kitsMenu(Player player) { try { //Maakt de inventory aan. Inventory kits = plugin.getServer().createInventory(null, 9, ChatColor.DARK_AQUA + "Kies een Kit!"); for(String name : configModule.getKitsConfig().getConfigConfiguration().getConfigurationSection("kits").getKeys(false)) { kits.addItem(configModule.getKitsConfig().getConfigConfiguration().getItemStack("kits." + name + ".icon")); } //Toont(Opent) de inventory aan de speler. player.openInventory(kits); } catch (NullPointerException exeption) { player.sendMessage(ChatColor.RED + "There are not current kits, please make some!"); } } }
Caaarlowsz/Kitpvp-21
src/main/java/me/goowen/kitpvp/modules/kits/KitsManager.java
1,043
/** * Haalt de kit op uit de config en zet hem om in een inventory. * Geeft de zojuist opgehaalde kit aan de speler. * @param player de speler die de kit moet krijgen. * @param name de naam van de kit die de speler moet krijgen. */
block_comment
nl
package me.goowen.kitpvp.modules.kits; import me.goowen.kitpvp.Kitpvp; import me.goowen.kitpvp.modules.config.ConfigModule; import me.goowen.kitpvp.modules.utilities.ItemBuilder; import org.bukkit.ChatColor; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import java.util.List; import java.util.Objects; public class KitsManager { private ConfigModule configModule = Kitpvp.getConfigModule(); private Kitpvp plugin = Kitpvp.getInstance(); /** * Slaat de kit op in een config vanuit de spelers inventory op basis van naam! * @param player de speler wiens inventory moet worden opgeslagen als kit! * @param name de naam van de kit! */ public void saveKit(Player player, String name) { configModule.getKitsConfig().getConfigConfiguration().set("kits." + name + ".armor", player.getInventory().getArmorContents()); configModule.getKitsConfig().getConfigConfiguration().set("kits." + name + ".items", player.getInventory().getContents()); configModule.getKitsConfig().getConfigConfiguration().set("kits." + name + ".icon", new ItemBuilder(player.getInventory().getItemInMainHand().clone()).setName(ChatColor.DARK_AQUA + name).addLoreLine(ChatColor.GRAY + "" + ChatColor.UNDERLINE + "Click to select this kit").toItemStack()); configModule.getKitsConfig().saveAsync(configModule.getKitsConfig()); } public void deleteKit(String name) { configModule.getKitsConfig().getConfigConfiguration().set("kits." + name, null); configModule.getKitsConfig().saveAsync(configModule.getKitsConfig()); } /** * Haalt de kit<SUF>*/ @SuppressWarnings("unchecked") public void giveKit(Player player, String name) { FileConfiguration kitsConfig = configModule.getKitsConfig().getConfigConfiguration(); //Haalt de armor op een geeft deze. ItemStack[] content = ((List<ItemStack>) Objects.requireNonNull(kitsConfig.get("kits." + name + ".armor"))).toArray(new ItemStack[0]); player.getInventory().setArmorContents(content); //Haalt de Items in de inventory op een geeft deze. content = ((List<ItemStack>) Objects.requireNonNull(kitsConfig.get("kits." + name + ".items"))).toArray(new ItemStack[0]); player.getInventory().setContents(content); } /** * Maakt het kits menu aan en toont hem aan de speler. * @param player de speler die het menu moet krijgen */ public void kitsMenu(Player player) { try { //Maakt de inventory aan. Inventory kits = plugin.getServer().createInventory(null, 9, ChatColor.DARK_AQUA + "Kies een Kit!"); for(String name : configModule.getKitsConfig().getConfigConfiguration().getConfigurationSection("kits").getKeys(false)) { kits.addItem(configModule.getKitsConfig().getConfigConfiguration().getItemStack("kits." + name + ".icon")); } //Toont(Opent) de inventory aan de speler. player.openInventory(kits); } catch (NullPointerException exeption) { player.sendMessage(ChatColor.RED + "There are not current kits, please make some!"); } } }
137152_2
package me.bmt.main; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import me.bmt.listeners.PlayerListeners; public class Main extends JavaPlugin { private static Main instance; public void log(String sting) { System.out.println(sting); } public static Main getInstance() { return instance; } public void registerListeners(){ PluginManager pm = getServer().getPluginManager(); pm.registerEvents(new PlayerListeners(this), this); //Gemaakt door CASJEKEN } public void registerCommands() { } //waneer plugin aan staat @Override public void onEnable() { getLogger().info("Aanzetten geslaagd!"); instance = this; registerListeners(); registerCommands(); } //als de plugin uit staat @Override public void onDisable(){ getLogger().info("Uitzetten geslaagd!"); instance = null; } //Commands public boolean onCommand(CommandSender sender, Command cmd, String commandlabel, String[] args) { //Starter kit if (cmd.getName().equalsIgnoreCase("Starter") && sender instanceof Player) { Player p = (Player) sender; p.getInventory().clear(); ItemStack Starterboog = new ItemStack(Material.BOW); ItemMeta m = Starterboog.getItemMeta(); m.setDisplayName("" + ChatColor.YELLOW + ChatColor.GOLD + "Starter Boog"); Starterboog.setItemMeta(m); Starterboog.addEnchantment(Enchantment.DURABILITY, 1); Starterboog.addEnchantment(Enchantment.ARROW_INFINITE, 1); p.getInventory().addItem(Starterboog); p.getInventory().addItem(new ItemStack(Material.ARROW, 1)); p.getInventory().setChestplate(new ItemStack(Material.CHAINMAIL_CHESTPLATE)); p.getInventory().setLeggings(new ItemStack(Material.CHAINMAIL_LEGGINGS)); p.getInventory().setBoots(new ItemStack(Material.GOLDEN_BOOTS)); p.getInventory().setHelmet(new ItemStack(Material.GOLDEN_HELMET)); p.getInventory().addItem(new ItemStack(Material.IRON_SWORD)); p.getInventory().addItem(new ItemStack(Material.APPLE, 15)); p.getInventory().addItem(new ItemStack(Material.GOLDEN_APPLE, 2)); p.sendMessage("" + ChatColor.RED + ChatColor.WHITE + "BMT | Kit Ontvangen!"); //Gemaakt door CASJEKEN //Archer kit if (cmd.getName().equalsIgnoreCase("Archer") && sender instanceof Player) { } p.getInventory().clear(); ItemStack ArcherBoog = new ItemStack(Material.BOW); ItemMeta n = ArcherBoog.getItemMeta(); n.setDisplayName("" + ChatColor.YELLOW + ChatColor.GOLD + "Archer Boog"); ArcherBoog.setItemMeta(m); ArcherBoog.addEnchantment(Enchantment.DURABILITY, 1); ArcherBoog.addEnchantment(Enchantment.ARROW_INFINITE, 1); ArcherBoog.addEnchantment(Enchantment.ARROW_DAMAGE, 2); ArcherBoog.addEnchantment(Enchantment.ARROW_FIRE, 1); p.getInventory().addItem(ArcherBoog); p.getInventory().addItem(new ItemStack(Material.ARROW, 1)); p.getInventory().setChestplate(new ItemStack(Material.GOLDEN_CHESTPLATE)); p.getInventory().setLeggings(new ItemStack(Material.CHAINMAIL_LEGGINGS)); p.getInventory().setBoots(new ItemStack(Material.GOLDEN_BOOTS)); p.getInventory().setHelmet(new ItemStack(Material.GOLDEN_HELMET)); ItemStack ArcherZwaard = new ItemStack(Material.WOODEN_SWORD); ItemMeta z = ArcherZwaard.getItemMeta(); z.setDisplayName("" + ChatColor.YELLOW + ChatColor.GOLD + "Archer Zwaard"); p.getInventory().addItem(ArcherZwaard); p.getInventory().addItem(new ItemStack(Material.APPLE, 15)); p.getInventory().addItem(new ItemStack(Material.GOLDEN_APPLE, 2)); p.sendMessage("" + ChatColor.RED + ChatColor.WHITE + "BMT | Kit Ontvangen!"); } //Magic kit if (cmd.getName().equalsIgnoreCase("Magic") && sender instanceof Player) { Player p = (Player) sender; p.getInventory().clear(); ItemStack Magicw = new ItemStack(Material.STICK); ItemMeta w = Magicw.getItemMeta(); w.setDisplayName("" + ChatColor.YELLOW + ChatColor.GOLD + "ToverStok"); Magicw.setItemMeta(w); Magicw.addEnchantment(Enchantment.DURABILITY, 1); Magicw.addEnchantment(Enchantment.KNOCKBACK, 2); Magicw.addEnchantment(Enchantment.DAMAGE_ALL, 2); Magicw.addEnchantment(Enchantment.FIRE_ASPECT, 1); p.getInventory().addItem(Magicw); p.getInventory().addItem(new ItemStack(Material.ARROW, 1)); p.getInventory().setChestplate(new ItemStack(Material.GOLDEN_CHESTPLATE)); p.getInventory().setLeggings(new ItemStack(Material.CHAINMAIL_LEGGINGS)); p.getInventory().setBoots(new ItemStack(Material.GOLDEN_BOOTS)); p.getInventory().setHelmet(new ItemStack(Material.GOLDEN_HELMET)); ItemStack ArcherZwaard = new ItemStack(Material.POTION); ItemMeta z = ArcherZwaard.getItemMeta(); z.setDisplayName("" + ChatColor.YELLOW + ChatColor.GOLD + "Gif Drankje"); p.getInventory().addItem(ArcherZwaard); p.getInventory().addItem(new ItemStack(Material.APPLE, 15)); p.getInventory().addItem(new ItemStack(Material.GOLDEN_APPLE, 2)); p.sendMessage("" + ChatColor.RED + ChatColor.WHITE + "BMT | Kit Ontvangen!"); } return false; } }
Caaarlowsz/Start-Kitpvp-plugin
Blackmt Kitpvp Proef/src/me/bmt/main/Main.java
1,999
//als de plugin uit staat
line_comment
nl
package me.bmt.main; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import me.bmt.listeners.PlayerListeners; public class Main extends JavaPlugin { private static Main instance; public void log(String sting) { System.out.println(sting); } public static Main getInstance() { return instance; } public void registerListeners(){ PluginManager pm = getServer().getPluginManager(); pm.registerEvents(new PlayerListeners(this), this); //Gemaakt door CASJEKEN } public void registerCommands() { } //waneer plugin aan staat @Override public void onEnable() { getLogger().info("Aanzetten geslaagd!"); instance = this; registerListeners(); registerCommands(); } //als de<SUF> @Override public void onDisable(){ getLogger().info("Uitzetten geslaagd!"); instance = null; } //Commands public boolean onCommand(CommandSender sender, Command cmd, String commandlabel, String[] args) { //Starter kit if (cmd.getName().equalsIgnoreCase("Starter") && sender instanceof Player) { Player p = (Player) sender; p.getInventory().clear(); ItemStack Starterboog = new ItemStack(Material.BOW); ItemMeta m = Starterboog.getItemMeta(); m.setDisplayName("" + ChatColor.YELLOW + ChatColor.GOLD + "Starter Boog"); Starterboog.setItemMeta(m); Starterboog.addEnchantment(Enchantment.DURABILITY, 1); Starterboog.addEnchantment(Enchantment.ARROW_INFINITE, 1); p.getInventory().addItem(Starterboog); p.getInventory().addItem(new ItemStack(Material.ARROW, 1)); p.getInventory().setChestplate(new ItemStack(Material.CHAINMAIL_CHESTPLATE)); p.getInventory().setLeggings(new ItemStack(Material.CHAINMAIL_LEGGINGS)); p.getInventory().setBoots(new ItemStack(Material.GOLDEN_BOOTS)); p.getInventory().setHelmet(new ItemStack(Material.GOLDEN_HELMET)); p.getInventory().addItem(new ItemStack(Material.IRON_SWORD)); p.getInventory().addItem(new ItemStack(Material.APPLE, 15)); p.getInventory().addItem(new ItemStack(Material.GOLDEN_APPLE, 2)); p.sendMessage("" + ChatColor.RED + ChatColor.WHITE + "BMT | Kit Ontvangen!"); //Gemaakt door CASJEKEN //Archer kit if (cmd.getName().equalsIgnoreCase("Archer") && sender instanceof Player) { } p.getInventory().clear(); ItemStack ArcherBoog = new ItemStack(Material.BOW); ItemMeta n = ArcherBoog.getItemMeta(); n.setDisplayName("" + ChatColor.YELLOW + ChatColor.GOLD + "Archer Boog"); ArcherBoog.setItemMeta(m); ArcherBoog.addEnchantment(Enchantment.DURABILITY, 1); ArcherBoog.addEnchantment(Enchantment.ARROW_INFINITE, 1); ArcherBoog.addEnchantment(Enchantment.ARROW_DAMAGE, 2); ArcherBoog.addEnchantment(Enchantment.ARROW_FIRE, 1); p.getInventory().addItem(ArcherBoog); p.getInventory().addItem(new ItemStack(Material.ARROW, 1)); p.getInventory().setChestplate(new ItemStack(Material.GOLDEN_CHESTPLATE)); p.getInventory().setLeggings(new ItemStack(Material.CHAINMAIL_LEGGINGS)); p.getInventory().setBoots(new ItemStack(Material.GOLDEN_BOOTS)); p.getInventory().setHelmet(new ItemStack(Material.GOLDEN_HELMET)); ItemStack ArcherZwaard = new ItemStack(Material.WOODEN_SWORD); ItemMeta z = ArcherZwaard.getItemMeta(); z.setDisplayName("" + ChatColor.YELLOW + ChatColor.GOLD + "Archer Zwaard"); p.getInventory().addItem(ArcherZwaard); p.getInventory().addItem(new ItemStack(Material.APPLE, 15)); p.getInventory().addItem(new ItemStack(Material.GOLDEN_APPLE, 2)); p.sendMessage("" + ChatColor.RED + ChatColor.WHITE + "BMT | Kit Ontvangen!"); } //Magic kit if (cmd.getName().equalsIgnoreCase("Magic") && sender instanceof Player) { Player p = (Player) sender; p.getInventory().clear(); ItemStack Magicw = new ItemStack(Material.STICK); ItemMeta w = Magicw.getItemMeta(); w.setDisplayName("" + ChatColor.YELLOW + ChatColor.GOLD + "ToverStok"); Magicw.setItemMeta(w); Magicw.addEnchantment(Enchantment.DURABILITY, 1); Magicw.addEnchantment(Enchantment.KNOCKBACK, 2); Magicw.addEnchantment(Enchantment.DAMAGE_ALL, 2); Magicw.addEnchantment(Enchantment.FIRE_ASPECT, 1); p.getInventory().addItem(Magicw); p.getInventory().addItem(new ItemStack(Material.ARROW, 1)); p.getInventory().setChestplate(new ItemStack(Material.GOLDEN_CHESTPLATE)); p.getInventory().setLeggings(new ItemStack(Material.CHAINMAIL_LEGGINGS)); p.getInventory().setBoots(new ItemStack(Material.GOLDEN_BOOTS)); p.getInventory().setHelmet(new ItemStack(Material.GOLDEN_HELMET)); ItemStack ArcherZwaard = new ItemStack(Material.POTION); ItemMeta z = ArcherZwaard.getItemMeta(); z.setDisplayName("" + ChatColor.YELLOW + ChatColor.GOLD + "Gif Drankje"); p.getInventory().addItem(ArcherZwaard); p.getInventory().addItem(new ItemStack(Material.APPLE, 15)); p.getInventory().addItem(new ItemStack(Material.GOLDEN_APPLE, 2)); p.sendMessage("" + ChatColor.RED + ChatColor.WHITE + "BMT | Kit Ontvangen!"); } return false; } }
57243_0
package cheese.squeeze.gameObjects; import java.util.Iterator; import java.util.List; import cheese.squeeze.helpers.AssetLoader; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; //TODO: direction bijhouden, en veranderen als we aan een gotopoint belanden. public class Mouse { private Vector2 position; private Vector2 velocity; private final float FLIKERING =100; private float EYEOPEN; private boolean open = true; private float orignSpeed; private float speed; private float tolerance = 0.02f; private Vector2 absolutePosition; private float rotation; private Vector2 mouseNose = AssetLoader.mouseNose; private Line currentLine; private Line nextLine; private Vector2 goToOrientation; private Vector2 nextGoToPoint; private boolean ended = false; public Mouse(float speed, Line line){ EYEOPEN = (float) (FLIKERING*Math.random()); float x = line.getX1(); float y = line.getY1(); //float y = 0; position = new Vector2(x,y); this.currentLine = line; this.speed = speed; this.orignSpeed = speed; //position = new Vector2(x-(mouseNose.x), y- (mouseNose.y)); velocity = new Vector2(0, 0); goToOrientation = new Vector2(0, 1); updatePath(); } public boolean isOnHorizontalLine() { if(currentLine instanceof HorizontalLine) { return true; } return false; } public void update(float delta) { EYEOPEN--; if (nextGoToPoint != null) { if(atIntersection()) { //System.out.println("intersection reached!"); //the mouse stands now at the previous nextGoToPoint setPosition(nextGoToPoint.x, nextGoToPoint.y); //nextGoToPoint is yet to be determined nextGoToPoint = null; //This mouse is now on the new line. //If there is no next line, the mouse stays on this line. currentLine = (nextLine != null) ? nextLine : currentLine; //nextLine is yet to be determined. nextLine = null; if (currentLine instanceof VerticalLine){ goToOrientation = new Vector2(0, 1); } else if (currentLine instanceof HorizontalLine) { if (getPosition().equals(currentLine.getPoint1())) goToOrientation = currentLine.getPoint2().cpy().sub(currentLine.getPoint1()); else goToOrientation = currentLine.getPoint1().cpy().sub(currentLine.getPoint2()); } //updateVelocityDirection(); //pick a new destination updatePath(); } //set the mouses new speed. if (atIntersection()) { //The mouse ran into something with a dead end. ((VerticalLine) currentLine).getGoal().activate(); velocity.set(Vector2.Zero); ended = true; } else { updateVelocityDirection(); } //move the mouse. updateVelocityDirection(); // setPosition(getX() + velocity.x * delta, getY() + velocity.y * delta); setPosition(getX() + velocity.x * 1, getY() + velocity.y * 1); //System.out.println(this.rotation); } } private void updateVelocityDirection() { if(!ended) { float angle = (float) Math.atan2(nextGoToPoint.y - getY(), nextGoToPoint.x - getX()); velocity.set((float) Math.cos(angle) * speed, (float) Math.sin(angle) * speed); //set the mouses angle. setRotation(angle * MathUtils.radiansToDegrees); } else { setRotation(90); } } public void updatePath() { Vector2 nextIntersection = currentLine.getNextIntersection(getPosition(), goToOrientation); nextLine = currentLine.getNeighbour(getPosition(), goToOrientation); if (nextIntersection == null) { nextGoToPoint = currentLine.getEndPoint(getPosition(), velocity); } else { nextGoToPoint = nextIntersection; } } private boolean atIntersection() { float dynTolerance = speed / tolerance * Gdx.graphics.getDeltaTime(); //System.out.println("dyn tol: " + dynTolerance); return Math.abs(nextGoToPoint.x - getX()) <= dynTolerance && Math.abs(nextGoToPoint.y - getY()) <= dynTolerance; } private void setRotation(float f) { this.rotation = f; } public float getX() { return position.x; } public float getY() { return position.y; } private void setPosition(float x,float y) { this.position.set(x, y); } public float getXAbs() { return this.absolutePosition.x; } public float getYAbs() { return this.absolutePosition.y; } public float getRotation() { return rotation; } public Vector2 getPosition() { return position; } public boolean isEnded() { return ended ; } public float getSpeed() { // TODO Auto-generated method stub return velocity.x + velocity.y; } //public void changeNextWayPoints(ArrayList<Vector2> newWaypoints) { // this.setPath(nPath); //} public boolean eyesOpen() { if(EYEOPEN < 0 && !open) { EYEOPEN = (float) ((FLIKERING*2)*Math.random()); open = !open; } if(EYEOPEN < 0 && open) { EYEOPEN = (float) ((FLIKERING/5)*Math.random()); open = !open; } return open; } public void setSpeed(float angle) { this.speed = this.orignSpeed + this.orignSpeed*angle; } public float getSpeedLine() { return this.speed - this.orignSpeed; } }
Camambar/CheeseSqueeze
core/src/cheese/squeeze/gameObjects/Mouse.java
1,855
//TODO: direction bijhouden, en veranderen als we aan een gotopoint belanden.
line_comment
nl
package cheese.squeeze.gameObjects; import java.util.Iterator; import java.util.List; import cheese.squeeze.helpers.AssetLoader; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; //TODO: direction<SUF> public class Mouse { private Vector2 position; private Vector2 velocity; private final float FLIKERING =100; private float EYEOPEN; private boolean open = true; private float orignSpeed; private float speed; private float tolerance = 0.02f; private Vector2 absolutePosition; private float rotation; private Vector2 mouseNose = AssetLoader.mouseNose; private Line currentLine; private Line nextLine; private Vector2 goToOrientation; private Vector2 nextGoToPoint; private boolean ended = false; public Mouse(float speed, Line line){ EYEOPEN = (float) (FLIKERING*Math.random()); float x = line.getX1(); float y = line.getY1(); //float y = 0; position = new Vector2(x,y); this.currentLine = line; this.speed = speed; this.orignSpeed = speed; //position = new Vector2(x-(mouseNose.x), y- (mouseNose.y)); velocity = new Vector2(0, 0); goToOrientation = new Vector2(0, 1); updatePath(); } public boolean isOnHorizontalLine() { if(currentLine instanceof HorizontalLine) { return true; } return false; } public void update(float delta) { EYEOPEN--; if (nextGoToPoint != null) { if(atIntersection()) { //System.out.println("intersection reached!"); //the mouse stands now at the previous nextGoToPoint setPosition(nextGoToPoint.x, nextGoToPoint.y); //nextGoToPoint is yet to be determined nextGoToPoint = null; //This mouse is now on the new line. //If there is no next line, the mouse stays on this line. currentLine = (nextLine != null) ? nextLine : currentLine; //nextLine is yet to be determined. nextLine = null; if (currentLine instanceof VerticalLine){ goToOrientation = new Vector2(0, 1); } else if (currentLine instanceof HorizontalLine) { if (getPosition().equals(currentLine.getPoint1())) goToOrientation = currentLine.getPoint2().cpy().sub(currentLine.getPoint1()); else goToOrientation = currentLine.getPoint1().cpy().sub(currentLine.getPoint2()); } //updateVelocityDirection(); //pick a new destination updatePath(); } //set the mouses new speed. if (atIntersection()) { //The mouse ran into something with a dead end. ((VerticalLine) currentLine).getGoal().activate(); velocity.set(Vector2.Zero); ended = true; } else { updateVelocityDirection(); } //move the mouse. updateVelocityDirection(); // setPosition(getX() + velocity.x * delta, getY() + velocity.y * delta); setPosition(getX() + velocity.x * 1, getY() + velocity.y * 1); //System.out.println(this.rotation); } } private void updateVelocityDirection() { if(!ended) { float angle = (float) Math.atan2(nextGoToPoint.y - getY(), nextGoToPoint.x - getX()); velocity.set((float) Math.cos(angle) * speed, (float) Math.sin(angle) * speed); //set the mouses angle. setRotation(angle * MathUtils.radiansToDegrees); } else { setRotation(90); } } public void updatePath() { Vector2 nextIntersection = currentLine.getNextIntersection(getPosition(), goToOrientation); nextLine = currentLine.getNeighbour(getPosition(), goToOrientation); if (nextIntersection == null) { nextGoToPoint = currentLine.getEndPoint(getPosition(), velocity); } else { nextGoToPoint = nextIntersection; } } private boolean atIntersection() { float dynTolerance = speed / tolerance * Gdx.graphics.getDeltaTime(); //System.out.println("dyn tol: " + dynTolerance); return Math.abs(nextGoToPoint.x - getX()) <= dynTolerance && Math.abs(nextGoToPoint.y - getY()) <= dynTolerance; } private void setRotation(float f) { this.rotation = f; } public float getX() { return position.x; } public float getY() { return position.y; } private void setPosition(float x,float y) { this.position.set(x, y); } public float getXAbs() { return this.absolutePosition.x; } public float getYAbs() { return this.absolutePosition.y; } public float getRotation() { return rotation; } public Vector2 getPosition() { return position; } public boolean isEnded() { return ended ; } public float getSpeed() { // TODO Auto-generated method stub return velocity.x + velocity.y; } //public void changeNextWayPoints(ArrayList<Vector2> newWaypoints) { // this.setPath(nPath); //} public boolean eyesOpen() { if(EYEOPEN < 0 && !open) { EYEOPEN = (float) ((FLIKERING*2)*Math.random()); open = !open; } if(EYEOPEN < 0 && open) { EYEOPEN = (float) ((FLIKERING/5)*Math.random()); open = !open; } return open; } public void setSpeed(float angle) { this.speed = this.orignSpeed + this.orignSpeed*angle; } public float getSpeedLine() { return this.speed - this.orignSpeed; } }