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
72325_61
/* * Copyright (C) 2009-2011 Institute for Computational Biomedicine, * Weill Medical College of Cornell University * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package edu.cornell.med.icb.goby.alignments.processors; import com.google.protobuf.ByteString; import edu.cornell.med.icb.goby.alignments.Alignments; import edu.cornell.med.icb.goby.alignments.ConcatSortedAlignmentReader; import edu.cornell.med.icb.goby.reads.RandomAccessSequenceInterface; import edu.cornell.med.icb.goby.util.WarningCounter; import it.unimi.dsi.fastutil.ints.IntArrayFIFOQueue; import it.unimi.dsi.fastutil.ints.IntArraySet; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectListIterator; import it.unimi.dsi.lang.MutableString; import org.apache.log4j.Logger; import java.io.IOException; import java.util.Random; /** * Support to realign reads on the fly in the proximity of indels. This implementation starts randomly filtering out alignments * from the source if more than 500,000 entries make it into the sliding realignment window. The more alignments are added * past the threshold the more difficult it become to add new ones. This strategy helps consuming all memory in the realignment * step working with alignments that have artefactual peaks of very high coverage. * * @author Fabien Campagne * Date: Apr 30, 2011 * Time: 11:58:07 AM */ public class RealignmentProcessor implements AlignmentProcessorInterface { int windowLength = 0; int currentTargetIndex = -1; private int numTargets; private int processedCount; private int numEntriesRealigned; @Override public int getModifiedCount() { return numEntriesRealigned; } @Override public int getProcessedCount() { return processedCount; } /** * The targetIndex that was active and for which we may still have entries stored in the corresponding pool: */ private int previousActiveTargetIndex = -1; /** * The FIFO queue that holds target indices that have entries pooled in tinfo: */ private IntArrayFIFOQueue activeTargetIndices = new IntArrayFIFOQueue(); private WarningCounter genomeNull = new WarningCounter(2); ObjectArrayList<InfoForTarget> targetInfo = new ObjectArrayList<InfoForTarget>(); final SkipToIterator iterator; private RandomAccessSequenceInterface genome; public RealignmentProcessor(final ConcatSortedAlignmentReader sortedReaders) { iterator = new SkipToSortedReader(sortedReaders); numTargets = sortedReaders.getNumberOfTargets(); targetInfo = new ObjectArrayList<InfoForTarget>(numTargets); } public RealignmentProcessor(final ObjectListIterator<Alignments.AlignmentEntry> entryIterator) { iterator = new SkipToListIterator(entryIterator); } int enqueuedCount = 0; public Alignments.AlignmentEntry nextRealignedEntry(final int targetIndex, final int position) throws IOException { boolean mustLoadPool; if (activeTargetIndices.isEmpty()) { // nothing seen yet, load the pool mustLoadPool = true; } else { //determine if the pool has enough entry within windowSize: InfoForTarget backTargetInfo = targetInfo.get(activeTargetIndices.firstInt()); // windowLength is zero at the beginning int wl = windowLength == 0 ? 1000 : windowLength; mustLoadPool = backTargetInfo.entriesInWindow.isEmpty() || backTargetInfo.maxEntryPosition < backTargetInfo.windowStartPosition + wl; } if (mustLoadPool) { // fill the window pool only if we don't have enough entries to return already. int windowStartPosition = Integer.MAX_VALUE; int minTargetIndex = Integer.MAX_VALUE; // push entries to the pool until we have a pool windowLength wide: Alignments.AlignmentEntry entry; do { entry = iterator.skipTo(targetIndex, position); if (entry != null) { minTargetIndex = Math.min(minTargetIndex, entry.getTargetIndex()); final int entryTargetIndex = entry.getTargetIndex(); // push new targetIndices to activeTargetIndices: if (activeTargetIndices.isEmpty() || activeTargetIndices.lastInt() != entryTargetIndex) { activeTargetIndices.enqueue(entryTargetIndex); } final InfoForTarget frontInfo = reallocateTargetInfo(entryTargetIndex); // System.out.printf("windowStartPosition=%,d %n",windowStartPosition); pushEntryToPool(frontInfo, position, entry); windowStartPosition = frontInfo.windowStartPosition; } else if (activeTargetIndices.isEmpty()) { // entry == null and none stored in windows // we could not find anything to return at all. Return null here. return null; } } while (entry != null && entry.getPosition() < windowStartPosition + windowLength); } // check if we still have entries in the previously active target: int backTargetIndex = activeTargetIndices.firstInt(); if (targetInfo.get(backTargetIndex).entriesInWindow.isEmpty()) { activeTargetIndices.dequeueInt(); // targetInfo.remove(0); targetInfo.get(0).clear(); if (activeTargetIndices.isEmpty()) { // no more targets, we are done. return null; } backTargetIndex = activeTargetIndices.firstInt(); } final InfoForTarget backInfo = targetInfo.get(backTargetIndex); // the pool info we will use to dequeue the entry at the back of the window // System.out.printf("back is holding %d entries %n", backInfo.entriesInWindow.size()); // now find the entry at the left of the realignment window on the active target: if (backInfo.entriesInWindow.isEmpty()) { return null; } Alignments.AlignmentEntry returnedEntry = backInfo.remove(); if (backInfo.positionsWithSpanningIndel.size() > 0) { returnedEntry = realign(returnedEntry, backInfo); } // advance the windowStartPosition int previousWindowStart = backInfo.windowStartPosition; int windowStartPosition = Math.max(backInfo.windowStartPosition, returnedEntry.getPosition()); // remove indel locations that are now outside the new window position if (previousWindowStart != windowStartPosition) { int lastPosition = windowStartPosition - 1; backInfo.removeIndels(previousWindowStart, lastPosition); } backInfo.windowStartPosition = windowStartPosition; ++processedCount; return returnedEntry; } private InfoForTarget reallocateTargetInfo(int targetIndex) { int intermediateTargetIndex = targetInfo.size() - 1; while (intermediateTargetIndex <= targetIndex) { targetInfo.add(new InfoForTarget(++intermediateTargetIndex)); numTargets = targetInfo.size(); } return targetInfo.get(targetIndex); } private final boolean[] directions = new boolean[]{true, false}; private Alignments.AlignmentEntry realign(final Alignments.AlignmentEntry entry, InfoForTarget tinfo) { int currentBestScore = 0; ObservedIndel bestScoreIndel = null; boolean bestScoreDirection = false; for (ObservedIndel indel : tinfo.potentialIndels) { if (entryOverlapsIndel(indel, entry)) { for (boolean direction : directions) { final int realignedScore = score(entry, indel, direction, currentBestScore, genome); if (realignedScore > currentBestScore) { currentBestScore = realignedScore; bestScoreIndel = indel; bestScoreDirection = direction; } } } } if (currentBestScore == 0) { return entry; } else { // actually modify entry to realign through the indel: ++numEntriesRealigned; return realign(entry, bestScoreIndel, bestScoreDirection, currentBestScore); } } /** * Return true if the alignment overlaps the indel. * * @param indel * @param entry * @return */ private boolean entryOverlapsIndel(final ObservedIndel indel, final Alignments.AlignmentEntry entry) { final int entryStart = entry.getPosition(); final int entryEnd = entryStart + entry.getTargetAlignedLength(); final int indelStart = indel.getStart(); final int indelEnd = indel.getEnd(); return entryStart <= indelStart && indelEnd <= entryEnd || entryStart < indelEnd && entryEnd > indelStart || entryEnd > indelStart && entryStart < indelEnd; } private Alignments.AlignmentEntry realign(Alignments.AlignmentEntry entry, ObservedIndel indel, boolean shiftForward, int scoreDelta) { // use entry as prototype: Alignments.AlignmentEntry.Builder builder = Alignments.AlignmentEntry.newBuilder(entry); // update the score to reflect the realignment: builder.setScore(entry.getScore() + scoreDelta); final int indelLength = indel.positionSpan(); // target aligned length increases by the length of gaps in the reads, since we support only read deletions at this time, // targetAlignedLength is incremented with the length of the indel. // TODO: revise to change QueryAlignedLength when implementing support for read insertions. builder.setTargetAlignedLength(builder.getTargetAlignedLength() + indelLength); int entryPosition = entry.getPosition(); final int originalEntryPosition = entryPosition; if (!shiftForward && indel.isReadInsertion()) { // shifting to the left a read insertion, must shift alignment start position to the right entryPosition = entry.getPosition() - indelLength; builder.setPosition(entryPosition); // when entry position changes, we need to update the pool to reflect the new entry sort order // this is accomplished by wrapping this processor with a LocalSortProcessor instance. } final int indelOffsetInAlignment = indel.getStart() - entryPosition; final int varCount = entry.getSequenceVariationsCount(); final int targetIndex = entry.getTargetIndex(); int score = 0; final int direction = shiftForward ? 1 : -1; if (genome == null) { genomeNull.warn(LOG, "Genome must not be null outside of Junit tests."); return entry; } /* *Reference positions for which the alignment does not agree with the reference, 0-based: */ IntArraySet variantPositions = new IntArraySet(); // determine if rewrittenVariations become compatible with reference when indel is introduced in this alignment: // increase the score by 1 for every base that beomes compatible. ObjectArrayList<Alignments.SequenceVariation> rewrittenVariations = new ObjectArrayList<Alignments.SequenceVariation>(); for (int i = 0; i < varCount; i++) { Alignments.SequenceVariation var = entry.getSequenceVariations(i); // check if var becomes compatible with reference when var's varPosition is shifted by the length of the indel in the specified shiftForward // newGenomicPosition is zero-based final int newGenomicPosition = var.getPosition() + (direction * indelLength) + originalEntryPosition - 1; for (int j = 0; j < var.getTo().length(); ++j) { final char toBase = var.getTo().charAt(j); final int index = newGenomicPosition + j; if (index < 0 || index > genome.getLength(targetIndex)) { score += -10; } else { final boolean compatible = genome.get(targetIndex, newGenomicPosition + j) == toBase; if (!compatible) { // we keep only sequence variatiations that continue to be incompatible with the reference after inserting the indel: rewrittenVariations.add(var); } variantPositions.add(var.getPosition() + entryPosition + j - 1); } } } // Determine which previously unchanged bases become incompatible with the reference when the the indel is introduced // startAlignment and endAlignment are zero-based int startAlignment = shiftForward ? entryPosition + indelOffsetInAlignment : entryPosition; int endAlignment = shiftForward ? entry.getTargetAlignedLength() + entryPosition : indelOffsetInAlignment + entryPosition + (direction * indelLength); // String pre = getGenomeSegment(genome, targetIndex, startAlignment, endAlignment); // String post = getGenomeSegment(genome, targetIndex, startAlignment + (direction * indelLength), endAlignment + (direction * indelLength)); // System.out.printf(" pre and post alignments: %n%s\n%s%n", pre, post); // pos is zero-based: for (int pos = startAlignment; pos < endAlignment; pos++) { // both variantPositions and pos are zero-based: if (!variantPositions.contains(pos)) { // this base matched the reference sequence: final int realignedPos = pos + (direction * indelLength); // if the realigned varPosition lies outside of the reference penalize heavily with -10, otherwise // count -1 for every new mismatch introduced by the indel: assert realignedPos >= 0 : "realignedPos cannot be negative for best indel."; final char fromBase = genome.get(targetIndex, realignedPos); final char toBase = genome.get(targetIndex, pos); final boolean compatible = fromBase == toBase; if (!compatible) { Alignments.SequenceVariation.Builder varBuilder = Alignments.SequenceVariation.newBuilder(); // varPosition is one-based while realignedPos and entryPos are zero-based: final int varPosition = direction * (realignedPos - entryPosition) + 1; varBuilder.setPosition(varPosition); varBuilder.setFrom(Character.toString(fromBase)); varBuilder.setTo(Character.toString(toBase)); varBuilder.setToQuality(byteArray((byte) Byte.MAX_VALUE)); int readIndex = entry.getMatchingReverseStrand() ? entry.getQueryLength() - indelOffsetInAlignment + (shiftForward ? 1 : indelLength) : varPosition; varBuilder.setReadIndex(readIndex); rewrittenVariations.add(varBuilder.build()); } } } // finally, add the indel into the revised alignment: Alignments.SequenceVariation.Builder varBuilder = Alignments.SequenceVariation.newBuilder(); // fix varPosition for negative strand, var positions are one-based: final int varPosition = shiftForward ? indelOffsetInAlignment + 1 : indel.getStart() - entryPosition + 1; varBuilder.setPosition(varPosition); varBuilder.setFrom(indel.from); varBuilder.setTo(indel.to); // we set readIndex to the left most varPosition before the read gap, by convention, see http://tinyurl.com/goby-sequence-variations (read deletion) int readIndex = entry.getMatchingReverseStrand() ? entry.getQueryLength() - indelOffsetInAlignment + (shiftForward ? 1 : indelLength) : varPosition; varBuilder.setReadIndex(readIndex); rewrittenVariations.add(varBuilder.build()); builder = builder.clearSequenceVariations(); for (Alignments.SequenceVariation var : rewrittenVariations) { builder = builder.addSequenceVariations(var); } final Alignments.AlignmentEntry alignmentEntry = builder.build(); // System.out.printf("realigned queryIndex=%d%n", alignmentEntry.getQueryIndex()); return alignmentEntry; } private ByteString byteArray(byte... a) { return ByteString.copyFrom(a); } /** * Score the realignment of an entry with respect to a potential indel. * * @param entry The entry to score as if it was realigned with respect to the indel * @param indel The indel under consideration. * @param shiftForward Whether the indel should be introduced by shifting bases forward * @param currentBestScore The current maximum score over a set of indels under consideration. @return The score obtained when realigning the entry with respect to the provided indel. * @param genome The genome to use to lookup reference bases * @return The score that would be observed if the indel was inserted into the alignment represented by entry. */ public final int score(final Alignments.AlignmentEntry entry, final ObservedIndel indel, final boolean shiftForward, final int currentBestScore, final RandomAccessSequenceInterface genome) { int entryPosition = entry.getPosition(); int indelOffsetInAlignment = indel.getStart() - entryPosition; int indelLength = indel.positionSpan(); int varCount = entry.getSequenceVariationsCount(); int targetIndex = entry.getTargetIndex(); int score = 0; int direction = shiftForward ? 1 : -1; if (genome == null) { genomeNull.warn(LOG, "Genome must not be null outside of JUnit tests."); return Integer.MIN_VALUE; } final int targetLength = genome.getLength(targetIndex); /* *Reference positions for which the alignment does not agree with the reference, 0-based: */ IntArraySet variantPositions = new IntArraySet(); // determine if variations become compatible with reference when indel is introduced in this alignment: // increase the score by 1 for every base that beomes compatible. for (int i = 0; i < varCount; i++) { Alignments.SequenceVariation var = entry.getSequenceVariations(i); // check if var becomes compatible with reference when var's position is shifted by the length of the indel in the specified shiftForward // newGenomicPosition is zero-based // final int originalGenomicPosition = var.getPosition() + entryPosition - 1; final int newGenomicPosition = var.getPosition() + (direction * indelLength) + entryPosition - 1; for (int j = 0; j < var.getTo().length(); ++j) { final char toBase = var.getTo().charAt(j); final int index = newGenomicPosition + j; if (index < 0 || index > genome.getLength(targetIndex)) { score += -10; } else { final boolean compatible = genome.get(targetIndex, newGenomicPosition + j) == toBase; score += compatible ? 1 : 0; // store which reference positions are different from the reference: variantPositions.add(var.getPosition() + entryPosition + j - 1); } } } // Determine which previously unchanged bases become incompatible with the reference when the the indel is introduced // Consider the span of reference between the indel insertion point and the end of the reference alignment going in the direction of extension. // startAlignment and endAlignment are zero-based int startAlignment = shiftForward ? entryPosition + indelOffsetInAlignment : entryPosition; int endAlignment = shiftForward ? entry.getTargetAlignedLength() + entryPosition : indelOffsetInAlignment + entryPosition + (direction * indelLength); // String pre = getGenomeSegment(genome, targetIndex, startAlignment, endAlignment); // // String post = getGenomeSegment(genome, targetIndex, startAlignment + indelLength, endAlignment + indelLength); // System.out.printf(" pre and post alignments: %n%s\n%s%n", pre, post); // pos is zero-based: endAlignment = Math.min(endAlignment, genome.getLength(targetIndex) - 1); for (int pos = startAlignment; pos < endAlignment; pos++) { // both variantPositions and pos are zero-based: if (!variantPositions.contains(pos)) { // this base matched the reference sequence: final int realignedPos = pos + (direction * indelLength); // if the realigned position lies outside of the reference penalize heavily with -10, otherwise // count -1 for every new mismatch introduced by the indel: if (realignedPos < 0 || realignedPos >= targetLength) { score += -10; } else { final char refBase = genome.get(targetIndex, pos); final char newRefBase = genome.get(targetIndex, realignedPos); score += (refBase == newRefBase) ? 0 : -1; } } // System.out.printf("indelOffsetInAlignment: %d shiftForward: %b score: %d%n", indelOffsetInAlignment, shiftForward, score); } // System.out.printf("indelOffsetInAlignment: %d shiftForward: %b score: %d%n", indelOffsetInAlignment, shiftForward, score); return score; } private String getGenomeSegment(RandomAccessSequenceInterface genome, int targetIndex, int startAlignment, int endAlignment) { MutableString sequence = new MutableString(); for (int pos = startAlignment; pos < endAlignment; pos++) { sequence.append(genome.get(targetIndex, pos)); } return sequence.toString(); } public void pushEntryToPool(InfoForTarget tinfo, int position, Alignments.AlignmentEntry entry) { // the window start is only decreased in the pushing step, never increased. final int entryPosition = entry.getPosition(); tinfo.windowStartPosition = Math.min(tinfo.windowStartPosition, entryPosition); tinfo.maxEntryPosition = Math.max(tinfo.maxEntryPosition, entryPosition); // set window length to twice the longest read length. windowLength = Math.max(windowLength, entry.getQueryLength() * 2); // detect if the entry contains an indel. Update the window indel state accordingly for (int i = 0; i < entry.getSequenceVariationsCount(); ++i) { final Alignments.SequenceVariation var = entry.getSequenceVariations(i); if (isIndel(var)) { // start and last position are zero-based: A--CAC start=1 end=3 final int startPosition = var.getPosition() + entryPosition - 1; final int lastPosition = var.getPosition() + entryPosition + Math.max(var.getFrom().length(), var.getTo().length()) - 1; tinfo.addIndel(startPosition, lastPosition, var.getFrom(), var.getTo()); } } enqueuedCount += tinfo.add(entry) ? 1 : 0; } private boolean isIndel(Alignments.SequenceVariation var) { return (var.getFrom().indexOf('-') >= 0 || var.getTo().indexOf('-') >= 0); } public void setGenome(RandomAccessSequenceInterface genome) { this.genome = genome; } private static final Logger LOG = Logger.getLogger(RealignmentProcessor.class); }
CampagneLaboratory/goby
src/edu/cornell/med/icb/goby/alignments/processors/RealignmentProcessor.java
6,286
// String pre = getGenomeSegment(genome, targetIndex, startAlignment, endAlignment);
line_comment
nl
/* * Copyright (C) 2009-2011 Institute for Computational Biomedicine, * Weill Medical College of Cornell University * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package edu.cornell.med.icb.goby.alignments.processors; import com.google.protobuf.ByteString; import edu.cornell.med.icb.goby.alignments.Alignments; import edu.cornell.med.icb.goby.alignments.ConcatSortedAlignmentReader; import edu.cornell.med.icb.goby.reads.RandomAccessSequenceInterface; import edu.cornell.med.icb.goby.util.WarningCounter; import it.unimi.dsi.fastutil.ints.IntArrayFIFOQueue; import it.unimi.dsi.fastutil.ints.IntArraySet; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectListIterator; import it.unimi.dsi.lang.MutableString; import org.apache.log4j.Logger; import java.io.IOException; import java.util.Random; /** * Support to realign reads on the fly in the proximity of indels. This implementation starts randomly filtering out alignments * from the source if more than 500,000 entries make it into the sliding realignment window. The more alignments are added * past the threshold the more difficult it become to add new ones. This strategy helps consuming all memory in the realignment * step working with alignments that have artefactual peaks of very high coverage. * * @author Fabien Campagne * Date: Apr 30, 2011 * Time: 11:58:07 AM */ public class RealignmentProcessor implements AlignmentProcessorInterface { int windowLength = 0; int currentTargetIndex = -1; private int numTargets; private int processedCount; private int numEntriesRealigned; @Override public int getModifiedCount() { return numEntriesRealigned; } @Override public int getProcessedCount() { return processedCount; } /** * The targetIndex that was active and for which we may still have entries stored in the corresponding pool: */ private int previousActiveTargetIndex = -1; /** * The FIFO queue that holds target indices that have entries pooled in tinfo: */ private IntArrayFIFOQueue activeTargetIndices = new IntArrayFIFOQueue(); private WarningCounter genomeNull = new WarningCounter(2); ObjectArrayList<InfoForTarget> targetInfo = new ObjectArrayList<InfoForTarget>(); final SkipToIterator iterator; private RandomAccessSequenceInterface genome; public RealignmentProcessor(final ConcatSortedAlignmentReader sortedReaders) { iterator = new SkipToSortedReader(sortedReaders); numTargets = sortedReaders.getNumberOfTargets(); targetInfo = new ObjectArrayList<InfoForTarget>(numTargets); } public RealignmentProcessor(final ObjectListIterator<Alignments.AlignmentEntry> entryIterator) { iterator = new SkipToListIterator(entryIterator); } int enqueuedCount = 0; public Alignments.AlignmentEntry nextRealignedEntry(final int targetIndex, final int position) throws IOException { boolean mustLoadPool; if (activeTargetIndices.isEmpty()) { // nothing seen yet, load the pool mustLoadPool = true; } else { //determine if the pool has enough entry within windowSize: InfoForTarget backTargetInfo = targetInfo.get(activeTargetIndices.firstInt()); // windowLength is zero at the beginning int wl = windowLength == 0 ? 1000 : windowLength; mustLoadPool = backTargetInfo.entriesInWindow.isEmpty() || backTargetInfo.maxEntryPosition < backTargetInfo.windowStartPosition + wl; } if (mustLoadPool) { // fill the window pool only if we don't have enough entries to return already. int windowStartPosition = Integer.MAX_VALUE; int minTargetIndex = Integer.MAX_VALUE; // push entries to the pool until we have a pool windowLength wide: Alignments.AlignmentEntry entry; do { entry = iterator.skipTo(targetIndex, position); if (entry != null) { minTargetIndex = Math.min(minTargetIndex, entry.getTargetIndex()); final int entryTargetIndex = entry.getTargetIndex(); // push new targetIndices to activeTargetIndices: if (activeTargetIndices.isEmpty() || activeTargetIndices.lastInt() != entryTargetIndex) { activeTargetIndices.enqueue(entryTargetIndex); } final InfoForTarget frontInfo = reallocateTargetInfo(entryTargetIndex); // System.out.printf("windowStartPosition=%,d %n",windowStartPosition); pushEntryToPool(frontInfo, position, entry); windowStartPosition = frontInfo.windowStartPosition; } else if (activeTargetIndices.isEmpty()) { // entry == null and none stored in windows // we could not find anything to return at all. Return null here. return null; } } while (entry != null && entry.getPosition() < windowStartPosition + windowLength); } // check if we still have entries in the previously active target: int backTargetIndex = activeTargetIndices.firstInt(); if (targetInfo.get(backTargetIndex).entriesInWindow.isEmpty()) { activeTargetIndices.dequeueInt(); // targetInfo.remove(0); targetInfo.get(0).clear(); if (activeTargetIndices.isEmpty()) { // no more targets, we are done. return null; } backTargetIndex = activeTargetIndices.firstInt(); } final InfoForTarget backInfo = targetInfo.get(backTargetIndex); // the pool info we will use to dequeue the entry at the back of the window // System.out.printf("back is holding %d entries %n", backInfo.entriesInWindow.size()); // now find the entry at the left of the realignment window on the active target: if (backInfo.entriesInWindow.isEmpty()) { return null; } Alignments.AlignmentEntry returnedEntry = backInfo.remove(); if (backInfo.positionsWithSpanningIndel.size() > 0) { returnedEntry = realign(returnedEntry, backInfo); } // advance the windowStartPosition int previousWindowStart = backInfo.windowStartPosition; int windowStartPosition = Math.max(backInfo.windowStartPosition, returnedEntry.getPosition()); // remove indel locations that are now outside the new window position if (previousWindowStart != windowStartPosition) { int lastPosition = windowStartPosition - 1; backInfo.removeIndels(previousWindowStart, lastPosition); } backInfo.windowStartPosition = windowStartPosition; ++processedCount; return returnedEntry; } private InfoForTarget reallocateTargetInfo(int targetIndex) { int intermediateTargetIndex = targetInfo.size() - 1; while (intermediateTargetIndex <= targetIndex) { targetInfo.add(new InfoForTarget(++intermediateTargetIndex)); numTargets = targetInfo.size(); } return targetInfo.get(targetIndex); } private final boolean[] directions = new boolean[]{true, false}; private Alignments.AlignmentEntry realign(final Alignments.AlignmentEntry entry, InfoForTarget tinfo) { int currentBestScore = 0; ObservedIndel bestScoreIndel = null; boolean bestScoreDirection = false; for (ObservedIndel indel : tinfo.potentialIndels) { if (entryOverlapsIndel(indel, entry)) { for (boolean direction : directions) { final int realignedScore = score(entry, indel, direction, currentBestScore, genome); if (realignedScore > currentBestScore) { currentBestScore = realignedScore; bestScoreIndel = indel; bestScoreDirection = direction; } } } } if (currentBestScore == 0) { return entry; } else { // actually modify entry to realign through the indel: ++numEntriesRealigned; return realign(entry, bestScoreIndel, bestScoreDirection, currentBestScore); } } /** * Return true if the alignment overlaps the indel. * * @param indel * @param entry * @return */ private boolean entryOverlapsIndel(final ObservedIndel indel, final Alignments.AlignmentEntry entry) { final int entryStart = entry.getPosition(); final int entryEnd = entryStart + entry.getTargetAlignedLength(); final int indelStart = indel.getStart(); final int indelEnd = indel.getEnd(); return entryStart <= indelStart && indelEnd <= entryEnd || entryStart < indelEnd && entryEnd > indelStart || entryEnd > indelStart && entryStart < indelEnd; } private Alignments.AlignmentEntry realign(Alignments.AlignmentEntry entry, ObservedIndel indel, boolean shiftForward, int scoreDelta) { // use entry as prototype: Alignments.AlignmentEntry.Builder builder = Alignments.AlignmentEntry.newBuilder(entry); // update the score to reflect the realignment: builder.setScore(entry.getScore() + scoreDelta); final int indelLength = indel.positionSpan(); // target aligned length increases by the length of gaps in the reads, since we support only read deletions at this time, // targetAlignedLength is incremented with the length of the indel. // TODO: revise to change QueryAlignedLength when implementing support for read insertions. builder.setTargetAlignedLength(builder.getTargetAlignedLength() + indelLength); int entryPosition = entry.getPosition(); final int originalEntryPosition = entryPosition; if (!shiftForward && indel.isReadInsertion()) { // shifting to the left a read insertion, must shift alignment start position to the right entryPosition = entry.getPosition() - indelLength; builder.setPosition(entryPosition); // when entry position changes, we need to update the pool to reflect the new entry sort order // this is accomplished by wrapping this processor with a LocalSortProcessor instance. } final int indelOffsetInAlignment = indel.getStart() - entryPosition; final int varCount = entry.getSequenceVariationsCount(); final int targetIndex = entry.getTargetIndex(); int score = 0; final int direction = shiftForward ? 1 : -1; if (genome == null) { genomeNull.warn(LOG, "Genome must not be null outside of Junit tests."); return entry; } /* *Reference positions for which the alignment does not agree with the reference, 0-based: */ IntArraySet variantPositions = new IntArraySet(); // determine if rewrittenVariations become compatible with reference when indel is introduced in this alignment: // increase the score by 1 for every base that beomes compatible. ObjectArrayList<Alignments.SequenceVariation> rewrittenVariations = new ObjectArrayList<Alignments.SequenceVariation>(); for (int i = 0; i < varCount; i++) { Alignments.SequenceVariation var = entry.getSequenceVariations(i); // check if var becomes compatible with reference when var's varPosition is shifted by the length of the indel in the specified shiftForward // newGenomicPosition is zero-based final int newGenomicPosition = var.getPosition() + (direction * indelLength) + originalEntryPosition - 1; for (int j = 0; j < var.getTo().length(); ++j) { final char toBase = var.getTo().charAt(j); final int index = newGenomicPosition + j; if (index < 0 || index > genome.getLength(targetIndex)) { score += -10; } else { final boolean compatible = genome.get(targetIndex, newGenomicPosition + j) == toBase; if (!compatible) { // we keep only sequence variatiations that continue to be incompatible with the reference after inserting the indel: rewrittenVariations.add(var); } variantPositions.add(var.getPosition() + entryPosition + j - 1); } } } // Determine which previously unchanged bases become incompatible with the reference when the the indel is introduced // startAlignment and endAlignment are zero-based int startAlignment = shiftForward ? entryPosition + indelOffsetInAlignment : entryPosition; int endAlignment = shiftForward ? entry.getTargetAlignedLength() + entryPosition : indelOffsetInAlignment + entryPosition + (direction * indelLength); // String pre = getGenomeSegment(genome, targetIndex, startAlignment, endAlignment); // String post = getGenomeSegment(genome, targetIndex, startAlignment + (direction * indelLength), endAlignment + (direction * indelLength)); // System.out.printf(" pre and post alignments: %n%s\n%s%n", pre, post); // pos is zero-based: for (int pos = startAlignment; pos < endAlignment; pos++) { // both variantPositions and pos are zero-based: if (!variantPositions.contains(pos)) { // this base matched the reference sequence: final int realignedPos = pos + (direction * indelLength); // if the realigned varPosition lies outside of the reference penalize heavily with -10, otherwise // count -1 for every new mismatch introduced by the indel: assert realignedPos >= 0 : "realignedPos cannot be negative for best indel."; final char fromBase = genome.get(targetIndex, realignedPos); final char toBase = genome.get(targetIndex, pos); final boolean compatible = fromBase == toBase; if (!compatible) { Alignments.SequenceVariation.Builder varBuilder = Alignments.SequenceVariation.newBuilder(); // varPosition is one-based while realignedPos and entryPos are zero-based: final int varPosition = direction * (realignedPos - entryPosition) + 1; varBuilder.setPosition(varPosition); varBuilder.setFrom(Character.toString(fromBase)); varBuilder.setTo(Character.toString(toBase)); varBuilder.setToQuality(byteArray((byte) Byte.MAX_VALUE)); int readIndex = entry.getMatchingReverseStrand() ? entry.getQueryLength() - indelOffsetInAlignment + (shiftForward ? 1 : indelLength) : varPosition; varBuilder.setReadIndex(readIndex); rewrittenVariations.add(varBuilder.build()); } } } // finally, add the indel into the revised alignment: Alignments.SequenceVariation.Builder varBuilder = Alignments.SequenceVariation.newBuilder(); // fix varPosition for negative strand, var positions are one-based: final int varPosition = shiftForward ? indelOffsetInAlignment + 1 : indel.getStart() - entryPosition + 1; varBuilder.setPosition(varPosition); varBuilder.setFrom(indel.from); varBuilder.setTo(indel.to); // we set readIndex to the left most varPosition before the read gap, by convention, see http://tinyurl.com/goby-sequence-variations (read deletion) int readIndex = entry.getMatchingReverseStrand() ? entry.getQueryLength() - indelOffsetInAlignment + (shiftForward ? 1 : indelLength) : varPosition; varBuilder.setReadIndex(readIndex); rewrittenVariations.add(varBuilder.build()); builder = builder.clearSequenceVariations(); for (Alignments.SequenceVariation var : rewrittenVariations) { builder = builder.addSequenceVariations(var); } final Alignments.AlignmentEntry alignmentEntry = builder.build(); // System.out.printf("realigned queryIndex=%d%n", alignmentEntry.getQueryIndex()); return alignmentEntry; } private ByteString byteArray(byte... a) { return ByteString.copyFrom(a); } /** * Score the realignment of an entry with respect to a potential indel. * * @param entry The entry to score as if it was realigned with respect to the indel * @param indel The indel under consideration. * @param shiftForward Whether the indel should be introduced by shifting bases forward * @param currentBestScore The current maximum score over a set of indels under consideration. @return The score obtained when realigning the entry with respect to the provided indel. * @param genome The genome to use to lookup reference bases * @return The score that would be observed if the indel was inserted into the alignment represented by entry. */ public final int score(final Alignments.AlignmentEntry entry, final ObservedIndel indel, final boolean shiftForward, final int currentBestScore, final RandomAccessSequenceInterface genome) { int entryPosition = entry.getPosition(); int indelOffsetInAlignment = indel.getStart() - entryPosition; int indelLength = indel.positionSpan(); int varCount = entry.getSequenceVariationsCount(); int targetIndex = entry.getTargetIndex(); int score = 0; int direction = shiftForward ? 1 : -1; if (genome == null) { genomeNull.warn(LOG, "Genome must not be null outside of JUnit tests."); return Integer.MIN_VALUE; } final int targetLength = genome.getLength(targetIndex); /* *Reference positions for which the alignment does not agree with the reference, 0-based: */ IntArraySet variantPositions = new IntArraySet(); // determine if variations become compatible with reference when indel is introduced in this alignment: // increase the score by 1 for every base that beomes compatible. for (int i = 0; i < varCount; i++) { Alignments.SequenceVariation var = entry.getSequenceVariations(i); // check if var becomes compatible with reference when var's position is shifted by the length of the indel in the specified shiftForward // newGenomicPosition is zero-based // final int originalGenomicPosition = var.getPosition() + entryPosition - 1; final int newGenomicPosition = var.getPosition() + (direction * indelLength) + entryPosition - 1; for (int j = 0; j < var.getTo().length(); ++j) { final char toBase = var.getTo().charAt(j); final int index = newGenomicPosition + j; if (index < 0 || index > genome.getLength(targetIndex)) { score += -10; } else { final boolean compatible = genome.get(targetIndex, newGenomicPosition + j) == toBase; score += compatible ? 1 : 0; // store which reference positions are different from the reference: variantPositions.add(var.getPosition() + entryPosition + j - 1); } } } // Determine which previously unchanged bases become incompatible with the reference when the the indel is introduced // Consider the span of reference between the indel insertion point and the end of the reference alignment going in the direction of extension. // startAlignment and endAlignment are zero-based int startAlignment = shiftForward ? entryPosition + indelOffsetInAlignment : entryPosition; int endAlignment = shiftForward ? entry.getTargetAlignedLength() + entryPosition : indelOffsetInAlignment + entryPosition + (direction * indelLength); // String pre<SUF> // // String post = getGenomeSegment(genome, targetIndex, startAlignment + indelLength, endAlignment + indelLength); // System.out.printf(" pre and post alignments: %n%s\n%s%n", pre, post); // pos is zero-based: endAlignment = Math.min(endAlignment, genome.getLength(targetIndex) - 1); for (int pos = startAlignment; pos < endAlignment; pos++) { // both variantPositions and pos are zero-based: if (!variantPositions.contains(pos)) { // this base matched the reference sequence: final int realignedPos = pos + (direction * indelLength); // if the realigned position lies outside of the reference penalize heavily with -10, otherwise // count -1 for every new mismatch introduced by the indel: if (realignedPos < 0 || realignedPos >= targetLength) { score += -10; } else { final char refBase = genome.get(targetIndex, pos); final char newRefBase = genome.get(targetIndex, realignedPos); score += (refBase == newRefBase) ? 0 : -1; } } // System.out.printf("indelOffsetInAlignment: %d shiftForward: %b score: %d%n", indelOffsetInAlignment, shiftForward, score); } // System.out.printf("indelOffsetInAlignment: %d shiftForward: %b score: %d%n", indelOffsetInAlignment, shiftForward, score); return score; } private String getGenomeSegment(RandomAccessSequenceInterface genome, int targetIndex, int startAlignment, int endAlignment) { MutableString sequence = new MutableString(); for (int pos = startAlignment; pos < endAlignment; pos++) { sequence.append(genome.get(targetIndex, pos)); } return sequence.toString(); } public void pushEntryToPool(InfoForTarget tinfo, int position, Alignments.AlignmentEntry entry) { // the window start is only decreased in the pushing step, never increased. final int entryPosition = entry.getPosition(); tinfo.windowStartPosition = Math.min(tinfo.windowStartPosition, entryPosition); tinfo.maxEntryPosition = Math.max(tinfo.maxEntryPosition, entryPosition); // set window length to twice the longest read length. windowLength = Math.max(windowLength, entry.getQueryLength() * 2); // detect if the entry contains an indel. Update the window indel state accordingly for (int i = 0; i < entry.getSequenceVariationsCount(); ++i) { final Alignments.SequenceVariation var = entry.getSequenceVariations(i); if (isIndel(var)) { // start and last position are zero-based: A--CAC start=1 end=3 final int startPosition = var.getPosition() + entryPosition - 1; final int lastPosition = var.getPosition() + entryPosition + Math.max(var.getFrom().length(), var.getTo().length()) - 1; tinfo.addIndel(startPosition, lastPosition, var.getFrom(), var.getTo()); } } enqueuedCount += tinfo.add(entry) ? 1 : 0; } private boolean isIndel(Alignments.SequenceVariation var) { return (var.getFrom().indexOf('-') >= 0 || var.getTo().indexOf('-') >= 0); } public void setGenome(RandomAccessSequenceInterface genome) { this.genome = genome; } private static final Logger LOG = Logger.getLogger(RealignmentProcessor.class); }
36429_1
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.pepsoft.util; import org.pepsoft.util.mdc.MDCCapturingRuntimeException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Map; import java.util.Set; import static org.pepsoft.util.SystemUtils.JAVA_9; import static org.pepsoft.util.SystemUtils.JAVA_VERSION; /** * * @author pepijn */ public class MemoryUtils { /** * Get the memory used by a particular object instance in bytes. To prevent runaway * * @param object The object of which to determine the memory used. * @param stopAt Types of references which should not be followed. * @return The number of bytes of RAM used by the object, or -1 if the size * could not be determined. */ public static long getSize(Object object, Set<Class<?>> stopAt) { if (object == null) { return 0L; } else if (JAVA_VERSION.isAtLeast(JAVA_9)) { // TODO: support Java 9 return -1L; } else { IdentityHashMap<Object, Void> processedObjects = new IdentityHashMap<>(); return getSize(object, processedObjects, stopAt/*, "root"*/); } } private static long getSize(Object object, IdentityHashMap<Object, Void> processedObjects, Set<Class<?>> stopAt/*, String trail*/) { if (processedObjects.containsKey(object)) { // This object has already been counted return 0L; } else { // Record that this object has been counted processedObjects.put(object, null); Class<?> type = object.getClass(); if ((stopAt != null) && (! stopAt.isEmpty())) { for (Class<?> stopClass: stopAt) { if (stopClass.isAssignableFrom(type)) { return 0L; } } } long objectSize = 8L; // Housekeeping if (type.isArray()) { objectSize += 4L; // Array length Class<?> arrayType = type.getComponentType(); if (arrayType.isPrimitive()) { if (arrayType == boolean.class) { objectSize += ((boolean[]) object).length; } else if (arrayType == byte.class) { objectSize += ((byte[]) object).length; } else if (arrayType == char.class) { objectSize += ((char[]) object).length * 2L; } else if (arrayType == short.class) { objectSize += ((short[]) object).length * 2L; } else if (arrayType == int.class) { objectSize += ((int[]) object).length * 4L; } else if (arrayType == float.class) { objectSize += ((float[]) object).length * 4L; } else if (arrayType == long.class) { objectSize += ((long[]) object).length * 8L; } else { objectSize += ((double[]) object).length * 8L; } } else { Object[] array = (Object[]) object; objectSize = array.length * 4L; // References for (Object anArray : array) { if (anArray != null) { objectSize += getSize(anArray, processedObjects, stopAt/*, trail + '[' + i + ']'*/); } } } } else if (type.isPrimitive()) { objectSize += PRIMITIVE_TYPE_SIZES.get(type); } else { Class<?> myType = type; while (myType != null) { Field[] fields = myType.getDeclaredFields(); for (Field field: fields) { if (Modifier.isStatic(field.getModifiers())) { continue; } Class<?> fieldType = field.getType(); if (fieldType.isPrimitive()) { objectSize += PRIMITIVE_TYPE_SIZES.get(fieldType); } else { objectSize += 4L; // Reference field.setAccessible(true); // Will fail if a security manager is installed! try { Object value = field.get(object); if (value != null) { objectSize += getSize(value, processedObjects, stopAt/*, trail + '.' + field.getName()*/); } } catch (IllegalAccessException e) { throw new MDCCapturingRuntimeException("Access denied trying to read field " + field.getName() + " of type " + myType.getName(), e); } } } myType = myType.getSuperclass(); } } if ((objectSize % 8L) != 0L) { objectSize = ((objectSize >> 3) + 1L) << 3; } // System.out.println(trail + " (" + type.getSimpleName() + "): " + objectSize); return objectSize; } } private static final Map<Class<?>, Long> PRIMITIVE_TYPE_SIZES = new HashMap<>(); static { PRIMITIVE_TYPE_SIZES.put(boolean.class, 1L); PRIMITIVE_TYPE_SIZES.put(byte.class, 1L); PRIMITIVE_TYPE_SIZES.put(char.class, 2L); PRIMITIVE_TYPE_SIZES.put(short.class, 2L); PRIMITIVE_TYPE_SIZES.put(int.class, 4L); PRIMITIVE_TYPE_SIZES.put(float.class, 4L); PRIMITIVE_TYPE_SIZES.put(long.class, 8L); PRIMITIVE_TYPE_SIZES.put(double.class, 8L); } }
Captain-Chaos/Utils
src/main/java/org/pepsoft/util/MemoryUtils.java
1,630
/** * * @author pepijn */
block_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.pepsoft.util; import org.pepsoft.util.mdc.MDCCapturingRuntimeException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Map; import java.util.Set; import static org.pepsoft.util.SystemUtils.JAVA_9; import static org.pepsoft.util.SystemUtils.JAVA_VERSION; /** * * @author pepijn <SUF>*/ public class MemoryUtils { /** * Get the memory used by a particular object instance in bytes. To prevent runaway * * @param object The object of which to determine the memory used. * @param stopAt Types of references which should not be followed. * @return The number of bytes of RAM used by the object, or -1 if the size * could not be determined. */ public static long getSize(Object object, Set<Class<?>> stopAt) { if (object == null) { return 0L; } else if (JAVA_VERSION.isAtLeast(JAVA_9)) { // TODO: support Java 9 return -1L; } else { IdentityHashMap<Object, Void> processedObjects = new IdentityHashMap<>(); return getSize(object, processedObjects, stopAt/*, "root"*/); } } private static long getSize(Object object, IdentityHashMap<Object, Void> processedObjects, Set<Class<?>> stopAt/*, String trail*/) { if (processedObjects.containsKey(object)) { // This object has already been counted return 0L; } else { // Record that this object has been counted processedObjects.put(object, null); Class<?> type = object.getClass(); if ((stopAt != null) && (! stopAt.isEmpty())) { for (Class<?> stopClass: stopAt) { if (stopClass.isAssignableFrom(type)) { return 0L; } } } long objectSize = 8L; // Housekeeping if (type.isArray()) { objectSize += 4L; // Array length Class<?> arrayType = type.getComponentType(); if (arrayType.isPrimitive()) { if (arrayType == boolean.class) { objectSize += ((boolean[]) object).length; } else if (arrayType == byte.class) { objectSize += ((byte[]) object).length; } else if (arrayType == char.class) { objectSize += ((char[]) object).length * 2L; } else if (arrayType == short.class) { objectSize += ((short[]) object).length * 2L; } else if (arrayType == int.class) { objectSize += ((int[]) object).length * 4L; } else if (arrayType == float.class) { objectSize += ((float[]) object).length * 4L; } else if (arrayType == long.class) { objectSize += ((long[]) object).length * 8L; } else { objectSize += ((double[]) object).length * 8L; } } else { Object[] array = (Object[]) object; objectSize = array.length * 4L; // References for (Object anArray : array) { if (anArray != null) { objectSize += getSize(anArray, processedObjects, stopAt/*, trail + '[' + i + ']'*/); } } } } else if (type.isPrimitive()) { objectSize += PRIMITIVE_TYPE_SIZES.get(type); } else { Class<?> myType = type; while (myType != null) { Field[] fields = myType.getDeclaredFields(); for (Field field: fields) { if (Modifier.isStatic(field.getModifiers())) { continue; } Class<?> fieldType = field.getType(); if (fieldType.isPrimitive()) { objectSize += PRIMITIVE_TYPE_SIZES.get(fieldType); } else { objectSize += 4L; // Reference field.setAccessible(true); // Will fail if a security manager is installed! try { Object value = field.get(object); if (value != null) { objectSize += getSize(value, processedObjects, stopAt/*, trail + '.' + field.getName()*/); } } catch (IllegalAccessException e) { throw new MDCCapturingRuntimeException("Access denied trying to read field " + field.getName() + " of type " + myType.getName(), e); } } } myType = myType.getSuperclass(); } } if ((objectSize % 8L) != 0L) { objectSize = ((objectSize >> 3) + 1L) << 3; } // System.out.println(trail + " (" + type.getSimpleName() + "): " + objectSize); return objectSize; } } private static final Map<Class<?>, Long> PRIMITIVE_TYPE_SIZES = new HashMap<>(); static { PRIMITIVE_TYPE_SIZES.put(boolean.class, 1L); PRIMITIVE_TYPE_SIZES.put(byte.class, 1L); PRIMITIVE_TYPE_SIZES.put(char.class, 2L); PRIMITIVE_TYPE_SIZES.put(short.class, 2L); PRIMITIVE_TYPE_SIZES.put(int.class, 4L); PRIMITIVE_TYPE_SIZES.put(float.class, 4L); PRIMITIVE_TYPE_SIZES.put(long.class, 8L); PRIMITIVE_TYPE_SIZES.put(double.class, 8L); } }
56877_1
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.pepsoft.worldpainter.layers.exporters; import com.google.common.collect.ImmutableMap; import org.pepsoft.minecraft.Chunk; import org.pepsoft.minecraft.Material; import org.pepsoft.util.PerlinNoise; import org.pepsoft.util.Version; import org.pepsoft.worldpainter.Dimension; import org.pepsoft.worldpainter.HeightTransform; import org.pepsoft.worldpainter.Platform; import org.pepsoft.worldpainter.Tile; import org.pepsoft.worldpainter.exporting.AbstractLayerExporter; import org.pepsoft.worldpainter.exporting.FirstPassLayerExporter; import org.pepsoft.worldpainter.layers.Resources; import org.pepsoft.worldpainter.layers.Void; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.*; import static org.pepsoft.minecraft.Constants.*; import static org.pepsoft.minecraft.Material.*; import static org.pepsoft.util.MathUtils.clamp; import static org.pepsoft.worldpainter.Constants.*; import static org.pepsoft.worldpainter.DefaultPlugin.ATTRIBUTE_MC_VERSION; import static org.pepsoft.worldpainter.Dimension.Role.CAVE_FLOOR; import static org.pepsoft.worldpainter.layers.exporters.ResourcesExporter.ResourcesExporterSettings.defaultSettings; /** * * @author pepijn */ public class ResourcesExporter extends AbstractLayerExporter<Resources> implements FirstPassLayerExporter { public ResourcesExporter(Dimension dimension, Platform platform, ExporterSettings settings) { super(dimension, platform, (settings != null) ? settings : defaultSettings(platform, dimension.getAnchor(), dimension.getMinHeight(), dimension.getMaxHeight()), Resources.INSTANCE); final ResourcesExporterSettings resourcesSettings = (ResourcesExporterSettings) super.settings; final Set<Material> allMaterials = resourcesSettings.getMaterials(); final List<Material> activeMaterials = new ArrayList<>(allMaterials.size()); for (Material material: allMaterials) { if (resourcesSettings.getChance(material) > 0) { activeMaterials.add(material); } } this.activeMaterials = activeMaterials.toArray(new Material[activeMaterials.size()]); noiseGenerators = new PerlinNoise[this.activeMaterials.length]; final long[] seedOffsets = new long[this.activeMaterials.length]; minLevels = new int[this.activeMaterials.length]; maxLevels = new int[this.activeMaterials.length]; chances = new float[this.activeMaterials.length][16]; for (int i = 0; i < this.activeMaterials.length; i++) { noiseGenerators[i] = new PerlinNoise(0); seedOffsets[i] = resourcesSettings.getSeedOffset(this.activeMaterials[i]); minLevels[i] = resourcesSettings.getMinLevel(this.activeMaterials[i]); maxLevels[i] = resourcesSettings.getMaxLevel(this.activeMaterials[i]); chances[i] = new float[16]; for (int j = 0; j < 16; j++) { chances[i][j] = PerlinNoise.getLevelForPromillage(Math.min(resourcesSettings.getChance(this.activeMaterials[i]) * j / 8f, 1000f)); } } for (int i = 0; i < this.activeMaterials.length; i++) { if (noiseGenerators[i].getSeed() != (dimension.getSeed() + seedOffsets[i])) { noiseGenerators[i].setSeed(dimension.getSeed() + seedOffsets[i]); } } } @Override public void render(Tile tile, Chunk chunk) { final int minimumLevel = ((ResourcesExporterSettings) super.settings).getMinimumLevel(); final int xOffset = (chunk.getxPos() & 7) << 4; final int zOffset = (chunk.getzPos() & 7) << 4; final boolean coverSteepTerrain = dimension.isCoverSteepTerrain(), nether = (dimension.getAnchor().dim == DIM_NETHER); // int[] counts = new int[256]; for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { final int localX = xOffset + x, localY = zOffset + z; final int worldX = tile.getX() * TILE_SIZE + localX, worldY = tile.getY() * TILE_SIZE + localY; if (tile.getBitLayerValue(Void.INSTANCE, localX, localY)) { continue; } final int resourcesValue = Math.max(minimumLevel, tile.getLayerValue(Resources.INSTANCE, localX, localY)); if (resourcesValue > 0) { final int terrainheight = tile.getIntHeight(localX, localY); final int topLayerDepth = dimension.getTopLayerDepth(worldX, worldY, terrainheight); int subsurfaceMaxHeight = terrainheight - topLayerDepth; if (coverSteepTerrain) { subsurfaceMaxHeight = Math.min(subsurfaceMaxHeight, Math.min(Math.min(dimension.getIntHeightAt(worldX - 1, worldY, Integer.MAX_VALUE), dimension.getIntHeightAt(worldX + 1, worldY, Integer.MAX_VALUE)), Math.min(dimension.getIntHeightAt(worldX, worldY - 1, Integer.MAX_VALUE), dimension.getIntHeightAt(worldX, worldY + 1, Integer.MAX_VALUE)))); } final double dx = worldX / TINY_BLOBS, dy = worldY / TINY_BLOBS; final double dirtX = worldX / SMALL_BLOBS, dirtY = worldY / SMALL_BLOBS; // Capping to maxY really shouldn't be necessary, but we've // had several reports from the wild of this going higher // than maxHeight, so there must be some obscure way in // which the terrainHeight can be raised too high for (int y = Math.min(subsurfaceMaxHeight, maxZ); y > minZ; y--) { final double dz = y / TINY_BLOBS; final double dirtZ = y / SMALL_BLOBS; for (int i = 0; i < activeMaterials.length; i++) { final float chance = chances[i][resourcesValue]; if ((chance <= 0.5f) && (y >= minLevels[i]) && (y <= maxLevels[i]) && (activeMaterials[i].isNamedOneOf(MC_DIRT, MC_GRAVEL) ? (noiseGenerators[i].getPerlinNoise(dirtX, dirtY, dirtZ) >= chance) : (noiseGenerators[i].getPerlinNoise(dx, dy, dz) >= chance))) { // counts[oreType]++; final Material existingMaterial = chunk.getMaterial(x, y, z); if (existingMaterial.isNamed(MC_DEEPSLATE) && ORE_TO_DEEPSLATE_VARIANT.containsKey(activeMaterials[i].name)) { chunk.setMaterial(x, y, z, ORE_TO_DEEPSLATE_VARIANT.get(activeMaterials[i].name)); } else if (nether && (activeMaterials[i].isNamed(MC_GOLD_ORE))) { chunk.setMaterial(x, y, z, NETHER_GOLD_ORE); } else { chunk.setMaterial(x, y, z, activeMaterials[i]); } break; } } } } } } // System.out.println("Tile " + tile.getX() + "," + tile.getY()); // for (i = 0; i < 256; i++) { // if (counts[i] > 0) { // System.out.printf("Exported %6d of ore type %3d%n", counts[i], i); // } // } // System.out.println(); } // TODO: resource frequenties onderzoeken met Statistics tool! private final Material[] activeMaterials; private final PerlinNoise[] noiseGenerators; private final int[] minLevels, maxLevels; private final float[][] chances; private static final Map<String, Material> ORE_TO_DEEPSLATE_VARIANT = ImmutableMap.of( MC_COAL_ORE, DEEPSLATE_COAL_ORE, MC_COPPER_ORE, DEEPSLATE_COPPER_ORE, MC_LAPIS_ORE, DEEPSLATE_LAPIS_ORE, MC_IRON_ORE, DEEPSLATE_IRON_ORE, MC_GOLD_ORE, DEEPSLATE_GOLD_ORE, MC_REDSTONE_ORE, DEEPSLATE_REDSTONE_ORE, MC_DIAMOND_ORE, DEEPSLATE_DIAMOND_ORE, MC_EMERALD_ORE, DEEPSLATE_EMERALD_ORE ); public static class ResourcesExporterSettings implements ExporterSettings { private ResourcesExporterSettings(Map<Material, ResourceSettings> settings) { this.settings = settings; } @Override public boolean isApplyEverywhere() { return minimumLevel > 0; } public int getMinimumLevel() { return minimumLevel; } public void setMinimumLevel(int minimumLevel) { this.minimumLevel = minimumLevel; } public Set<Material> getMaterials() { return settings.keySet(); } public int getMinLevel(Material material) { return settings.get(material).minLevel; } public void setMinLevel(Material material, int minLevel) { settings.get(material).minLevel = minLevel; } public int getMaxLevel(Material material) { return settings.get(material).maxLevel; } public void setMaxLevel(Material material, int maxLevel) { settings.get(material).maxLevel = maxLevel; } public int getChance(Material material) { return settings.get(material).chance; } public void setChance(Material material, int chance) { settings.get(material).chance = chance; } public long getSeedOffset(Material material) { return settings.get(material).seedOffset; } @Override public Resources getLayer() { return Resources.INSTANCE; } @Override public void setMinMaxHeight(int oldMinHeight, int newMinHeight, int oldMaxHeight, int newMaxHeight, HeightTransform transform) { for (Material material: settings.keySet()) { int maxLevel = settings.get(material).maxLevel; if (maxLevel == (oldMaxHeight - 1)) { maxLevel = newMaxHeight - 1; } else if (maxLevel > 1) { maxLevel = clamp(newMinHeight, transform.transformHeight(maxLevel), newMaxHeight - 1); } // TODO: do the same for minLevels? Or do we WANT those to stay put? settings.get(material).maxLevel = maxLevel; } } @Override public ResourcesExporterSettings clone() { try { ResourcesExporterSettings clone = (ResourcesExporterSettings) super.clone(); clone.settings = new LinkedHashMap<>(); settings.forEach((material, settings) -> clone.settings.put(material, settings.clone())); return clone; } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } public static ResourcesExporterSettings defaultSettings(Platform platform, Dimension.Anchor anchor, int minHeight, int maxHeight) { final Random random = new Random(); final Map<Material, ResourceSettings> settings = new HashMap<>(); final Version mcVersion = platform.getAttribute(ATTRIBUTE_MC_VERSION); switch (anchor.dim) { case DIM_NORMAL: // TODO make these normal distributions or something else more similar to Minecraft settings.put(DIRT, new ResourceSettings(DIRT, 0, maxHeight - 1, 57, random.nextLong())); settings.put(GRAVEL, new ResourceSettings(GRAVEL, minHeight, maxHeight - 1, 28, random.nextLong())); settings.put(GOLD_ORE, new ResourceSettings(GOLD_ORE, minHeight, 31, 1, random.nextLong())); settings.put(IRON_ORE, new ResourceSettings(IRON_ORE, minHeight, maxHeight - 1, 6, random.nextLong())); settings.put(COAL, new ResourceSettings(COAL, 0, maxHeight - 1, 10, random.nextLong())); settings.put(LAPIS_LAZULI_ORE, new ResourceSettings(LAPIS_LAZULI_ORE, minHeight, 31, 1, random.nextLong())); settings.put(DIAMOND_ORE, new ResourceSettings(DIAMOND_ORE, minHeight, 15, 1, random.nextLong())); settings.put(REDSTONE_ORE, new ResourceSettings(REDSTONE_ORE, minHeight, 15, 8, random.nextLong())); settings.put(STATIONARY_WATER, new ResourceSettings(STATIONARY_WATER, minHeight, maxHeight - 1, 1, random.nextLong())); settings.put(STATIONARY_LAVA, new ResourceSettings(STATIONARY_LAVA, minHeight, 15, 2, random.nextLong())); settings.put(EMERALD_ORE, new ResourceSettings(EMERALD_ORE, 64, maxHeight - 1, mcVersion.isAtLeast(V_1_2) ? 1 : 0, random.nextLong())); settings.put(COPPER_ORE, new ResourceSettings(COPPER_ORE, 0, 88, mcVersion.isAtLeast(V_1_17) ? 6 : 0, random.nextLong())); settings.put(QUARTZ_ORE, new ResourceSettings(QUARTZ_ORE, minHeight, maxHeight - 1, 0, random.nextLong())); settings.put(ANCIENT_DEBRIS, new ResourceSettings(ANCIENT_DEBRIS, minHeight, maxHeight - 1, 0, random.nextLong())); break; case DIM_NETHER: settings.put(QUARTZ_ORE, new ResourceSettings(QUARTZ_ORE, minHeight, maxHeight - 1, mcVersion.isAtLeast(V_1_2) ? 7 : 0, random.nextLong())); settings.put(GOLD_ORE, new ResourceSettings(GOLD_ORE, minHeight, maxHeight - 1, mcVersion.isAtLeast(V_1_15) ? 3 : 0, random.nextLong())); settings.put(ANCIENT_DEBRIS, new ResourceSettings(ANCIENT_DEBRIS, minHeight, maxHeight - 1, mcVersion.isAtLeast(V_1_15) ? 1 : 0, random.nextLong())); settings.put(DIRT, new ResourceSettings(DIRT, 0, maxHeight - 1, 0, random.nextLong())); settings.put(GRAVEL, new ResourceSettings(GRAVEL, minHeight, maxHeight - 1, 0, random.nextLong())); settings.put(IRON_ORE, new ResourceSettings(IRON_ORE, minHeight, maxHeight - 1, 0, random.nextLong())); settings.put(COAL, new ResourceSettings(COAL, 0, maxHeight - 1, 0, random.nextLong())); settings.put(LAPIS_LAZULI_ORE, new ResourceSettings(LAPIS_LAZULI_ORE, minHeight, 31, 0, random.nextLong())); settings.put(DIAMOND_ORE, new ResourceSettings(DIAMOND_ORE, minHeight, 15, 0, random.nextLong())); settings.put(REDSTONE_ORE, new ResourceSettings(REDSTONE_ORE, minHeight, 15, 0, random.nextLong())); settings.put(STATIONARY_WATER, new ResourceSettings(STATIONARY_WATER, minHeight, maxHeight - 1, 0, random.nextLong())); settings.put(STATIONARY_LAVA, new ResourceSettings(STATIONARY_LAVA, minHeight, 15, 0, random.nextLong())); settings.put(EMERALD_ORE, new ResourceSettings(EMERALD_ORE, 64, maxHeight - 1, 0, random.nextLong())); settings.put(COPPER_ORE, new ResourceSettings(COPPER_ORE, 0, 88, 0, random.nextLong())); break; case DIM_END: settings.put(DIRT, new ResourceSettings(DIRT, 0, maxHeight - 1, 0, random.nextLong())); settings.put(GRAVEL, new ResourceSettings(GRAVEL, minHeight, maxHeight - 1, 0, random.nextLong())); settings.put(GOLD_ORE, new ResourceSettings(GOLD_ORE, minHeight, 31, 0, random.nextLong())); settings.put(IRON_ORE, new ResourceSettings(IRON_ORE, minHeight, maxHeight - 1, 0, random.nextLong())); settings.put(COAL, new ResourceSettings(COAL, 0, maxHeight - 1, 0, random.nextLong())); settings.put(LAPIS_LAZULI_ORE, new ResourceSettings(LAPIS_LAZULI_ORE, minHeight, 31, 0, random.nextLong())); settings.put(DIAMOND_ORE, new ResourceSettings(DIAMOND_ORE, minHeight, 15, 0, random.nextLong())); settings.put(REDSTONE_ORE, new ResourceSettings(REDSTONE_ORE, minHeight, 15, 0, random.nextLong())); settings.put(STATIONARY_WATER, new ResourceSettings(STATIONARY_WATER, minHeight, maxHeight - 1, 0, random.nextLong())); settings.put(STATIONARY_LAVA, new ResourceSettings(STATIONARY_LAVA, minHeight, 15, 0, random.nextLong())); settings.put(EMERALD_ORE, new ResourceSettings(EMERALD_ORE, 64, maxHeight - 1, 0, random.nextLong())); settings.put(COPPER_ORE, new ResourceSettings(COPPER_ORE, 0, 88, 0, random.nextLong())); settings.put(QUARTZ_ORE, new ResourceSettings(QUARTZ_ORE, minHeight, maxHeight - 1, 0, random.nextLong())); settings.put(ANCIENT_DEBRIS, new ResourceSettings(ANCIENT_DEBRIS, minHeight, maxHeight - 1, 0, random.nextLong())); break; default: throw new IllegalArgumentException("Dimension " + anchor.dim + " not supported"); } final ResourcesExporterSettings result = new ResourcesExporterSettings(settings); if (anchor.role == CAVE_FLOOR) { result.setMinimumLevel(0); } return result; } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); if (version < 1) { // Legacy conversions // Fix static water and lava if (! maxLevels.containsKey(BLK_WATER)) { logger.warn("Fixing water and lava settings"); maxLevels.put(BLK_WATER, maxLevels.get(BLK_STATIONARY_WATER)); chances.put(BLK_WATER, chances.get(BLK_STATIONARY_WATER)); seedOffsets.put(BLK_WATER, seedOffsets.get(BLK_STATIONARY_WATER)); maxLevels.put(BLK_LAVA, maxLevels.get(BLK_STATIONARY_LAVA)); chances.put(BLK_LAVA, chances.get(BLK_STATIONARY_LAVA)); seedOffsets.put(BLK_LAVA, seedOffsets.get(BLK_STATIONARY_LAVA)); maxLevels.remove(BLK_STATIONARY_WATER); chances.remove(BLK_STATIONARY_WATER); seedOffsets.remove(BLK_STATIONARY_WATER); maxLevels.remove(BLK_STATIONARY_LAVA); chances.remove(BLK_STATIONARY_LAVA); seedOffsets.remove(BLK_STATIONARY_LAVA); } if (! maxLevels.containsKey(BLK_EMERALD_ORE)) { maxLevels.put(BLK_EMERALD_ORE, 31); chances.put(BLK_EMERALD_ORE, 0); } Random random = new Random(); if (! seedOffsets.containsKey(BLK_EMERALD_ORE)) { seedOffsets.put(BLK_EMERALD_ORE, random.nextLong()); } if (minLevels == null) { minLevels = new HashMap<>(); for (int blockType: maxLevels.keySet()) { minLevels.put(blockType, 0); } } if (! minLevels.containsKey(BLK_QUARTZ_ORE)) { minLevels.put(BLK_QUARTZ_ORE, 0); maxLevels.put(BLK_QUARTZ_ORE, 255); chances.put(BLK_QUARTZ_ORE, 0); seedOffsets.put(BLK_QUARTZ_ORE, random.nextLong()); } // Convert integer-based settings to material-based settings settings = new LinkedHashMap<>(); for (int blockType: maxLevels.keySet()) { Material material = get(blockType); settings.put(material, new ResourceSettings(material, minLevels.get(blockType), maxLevels.get(blockType), chances.get(blockType), seedOffsets.get(blockType))); } minLevels = null; maxLevels = null; chances = null; seedOffsets = null; } if (version < 2) { // Add new resources final Random random = new Random(); settings.put(COPPER_ORE, new ResourceSettings(COPPER_ORE, 0, 88, 0, random.nextLong())); settings.put(ANCIENT_DEBRIS, new ResourceSettings(ANCIENT_DEBRIS, -64, 319, 0, random.nextLong())); } if (version < 3) { if (settings.containsKey(WATER)) { settings.put(STATIONARY_WATER, settings.get(WATER)); settings.remove(WATER); } if (settings.containsKey(LAVA)) { settings.put(STATIONARY_LAVA, settings.get(LAVA)); settings.remove(LAVA); } } version = 3; } private int minimumLevel = 8; private Map<Material, ResourceSettings> settings; /** @deprecated */ @Deprecated private Map<Integer, Integer> maxLevels = null; /** @deprecated */ @Deprecated private Map<Integer, Integer> chances = null; /** @deprecated */ @Deprecated private Map<Integer, Long> seedOffsets = null; /** @deprecated */ @Deprecated private Map<Integer, Integer> minLevels = null; private int version = 3; private static final long serialVersionUID = 1L; private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ResourcesExporter.class); } static class ResourceSettings implements Serializable, Cloneable { ResourceSettings(Material material, int minLevel, int maxLevel, int chance, long seedOffset) { this.material = material; this.minLevel = minLevel; this.maxLevel = maxLevel; this.chance = chance; this.seedOffset = seedOffset; } @Override public ResourceSettings clone() { try { return (ResourceSettings) super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(e); } } Material material; int minLevel, maxLevel, chance; long seedOffset; private static final long serialVersionUID = 1L; } }
Captain-Chaos/WorldPainter
WorldPainter/WPCore/src/main/java/org/pepsoft/worldpainter/layers/exporters/ResourcesExporter.java
6,938
/** * * @author pepijn */
block_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.pepsoft.worldpainter.layers.exporters; import com.google.common.collect.ImmutableMap; import org.pepsoft.minecraft.Chunk; import org.pepsoft.minecraft.Material; import org.pepsoft.util.PerlinNoise; import org.pepsoft.util.Version; import org.pepsoft.worldpainter.Dimension; import org.pepsoft.worldpainter.HeightTransform; import org.pepsoft.worldpainter.Platform; import org.pepsoft.worldpainter.Tile; import org.pepsoft.worldpainter.exporting.AbstractLayerExporter; import org.pepsoft.worldpainter.exporting.FirstPassLayerExporter; import org.pepsoft.worldpainter.layers.Resources; import org.pepsoft.worldpainter.layers.Void; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.*; import static org.pepsoft.minecraft.Constants.*; import static org.pepsoft.minecraft.Material.*; import static org.pepsoft.util.MathUtils.clamp; import static org.pepsoft.worldpainter.Constants.*; import static org.pepsoft.worldpainter.DefaultPlugin.ATTRIBUTE_MC_VERSION; import static org.pepsoft.worldpainter.Dimension.Role.CAVE_FLOOR; import static org.pepsoft.worldpainter.layers.exporters.ResourcesExporter.ResourcesExporterSettings.defaultSettings; /** * * @author pepijn <SUF>*/ public class ResourcesExporter extends AbstractLayerExporter<Resources> implements FirstPassLayerExporter { public ResourcesExporter(Dimension dimension, Platform platform, ExporterSettings settings) { super(dimension, platform, (settings != null) ? settings : defaultSettings(platform, dimension.getAnchor(), dimension.getMinHeight(), dimension.getMaxHeight()), Resources.INSTANCE); final ResourcesExporterSettings resourcesSettings = (ResourcesExporterSettings) super.settings; final Set<Material> allMaterials = resourcesSettings.getMaterials(); final List<Material> activeMaterials = new ArrayList<>(allMaterials.size()); for (Material material: allMaterials) { if (resourcesSettings.getChance(material) > 0) { activeMaterials.add(material); } } this.activeMaterials = activeMaterials.toArray(new Material[activeMaterials.size()]); noiseGenerators = new PerlinNoise[this.activeMaterials.length]; final long[] seedOffsets = new long[this.activeMaterials.length]; minLevels = new int[this.activeMaterials.length]; maxLevels = new int[this.activeMaterials.length]; chances = new float[this.activeMaterials.length][16]; for (int i = 0; i < this.activeMaterials.length; i++) { noiseGenerators[i] = new PerlinNoise(0); seedOffsets[i] = resourcesSettings.getSeedOffset(this.activeMaterials[i]); minLevels[i] = resourcesSettings.getMinLevel(this.activeMaterials[i]); maxLevels[i] = resourcesSettings.getMaxLevel(this.activeMaterials[i]); chances[i] = new float[16]; for (int j = 0; j < 16; j++) { chances[i][j] = PerlinNoise.getLevelForPromillage(Math.min(resourcesSettings.getChance(this.activeMaterials[i]) * j / 8f, 1000f)); } } for (int i = 0; i < this.activeMaterials.length; i++) { if (noiseGenerators[i].getSeed() != (dimension.getSeed() + seedOffsets[i])) { noiseGenerators[i].setSeed(dimension.getSeed() + seedOffsets[i]); } } } @Override public void render(Tile tile, Chunk chunk) { final int minimumLevel = ((ResourcesExporterSettings) super.settings).getMinimumLevel(); final int xOffset = (chunk.getxPos() & 7) << 4; final int zOffset = (chunk.getzPos() & 7) << 4; final boolean coverSteepTerrain = dimension.isCoverSteepTerrain(), nether = (dimension.getAnchor().dim == DIM_NETHER); // int[] counts = new int[256]; for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { final int localX = xOffset + x, localY = zOffset + z; final int worldX = tile.getX() * TILE_SIZE + localX, worldY = tile.getY() * TILE_SIZE + localY; if (tile.getBitLayerValue(Void.INSTANCE, localX, localY)) { continue; } final int resourcesValue = Math.max(minimumLevel, tile.getLayerValue(Resources.INSTANCE, localX, localY)); if (resourcesValue > 0) { final int terrainheight = tile.getIntHeight(localX, localY); final int topLayerDepth = dimension.getTopLayerDepth(worldX, worldY, terrainheight); int subsurfaceMaxHeight = terrainheight - topLayerDepth; if (coverSteepTerrain) { subsurfaceMaxHeight = Math.min(subsurfaceMaxHeight, Math.min(Math.min(dimension.getIntHeightAt(worldX - 1, worldY, Integer.MAX_VALUE), dimension.getIntHeightAt(worldX + 1, worldY, Integer.MAX_VALUE)), Math.min(dimension.getIntHeightAt(worldX, worldY - 1, Integer.MAX_VALUE), dimension.getIntHeightAt(worldX, worldY + 1, Integer.MAX_VALUE)))); } final double dx = worldX / TINY_BLOBS, dy = worldY / TINY_BLOBS; final double dirtX = worldX / SMALL_BLOBS, dirtY = worldY / SMALL_BLOBS; // Capping to maxY really shouldn't be necessary, but we've // had several reports from the wild of this going higher // than maxHeight, so there must be some obscure way in // which the terrainHeight can be raised too high for (int y = Math.min(subsurfaceMaxHeight, maxZ); y > minZ; y--) { final double dz = y / TINY_BLOBS; final double dirtZ = y / SMALL_BLOBS; for (int i = 0; i < activeMaterials.length; i++) { final float chance = chances[i][resourcesValue]; if ((chance <= 0.5f) && (y >= minLevels[i]) && (y <= maxLevels[i]) && (activeMaterials[i].isNamedOneOf(MC_DIRT, MC_GRAVEL) ? (noiseGenerators[i].getPerlinNoise(dirtX, dirtY, dirtZ) >= chance) : (noiseGenerators[i].getPerlinNoise(dx, dy, dz) >= chance))) { // counts[oreType]++; final Material existingMaterial = chunk.getMaterial(x, y, z); if (existingMaterial.isNamed(MC_DEEPSLATE) && ORE_TO_DEEPSLATE_VARIANT.containsKey(activeMaterials[i].name)) { chunk.setMaterial(x, y, z, ORE_TO_DEEPSLATE_VARIANT.get(activeMaterials[i].name)); } else if (nether && (activeMaterials[i].isNamed(MC_GOLD_ORE))) { chunk.setMaterial(x, y, z, NETHER_GOLD_ORE); } else { chunk.setMaterial(x, y, z, activeMaterials[i]); } break; } } } } } } // System.out.println("Tile " + tile.getX() + "," + tile.getY()); // for (i = 0; i < 256; i++) { // if (counts[i] > 0) { // System.out.printf("Exported %6d of ore type %3d%n", counts[i], i); // } // } // System.out.println(); } // TODO: resource frequenties onderzoeken met Statistics tool! private final Material[] activeMaterials; private final PerlinNoise[] noiseGenerators; private final int[] minLevels, maxLevels; private final float[][] chances; private static final Map<String, Material> ORE_TO_DEEPSLATE_VARIANT = ImmutableMap.of( MC_COAL_ORE, DEEPSLATE_COAL_ORE, MC_COPPER_ORE, DEEPSLATE_COPPER_ORE, MC_LAPIS_ORE, DEEPSLATE_LAPIS_ORE, MC_IRON_ORE, DEEPSLATE_IRON_ORE, MC_GOLD_ORE, DEEPSLATE_GOLD_ORE, MC_REDSTONE_ORE, DEEPSLATE_REDSTONE_ORE, MC_DIAMOND_ORE, DEEPSLATE_DIAMOND_ORE, MC_EMERALD_ORE, DEEPSLATE_EMERALD_ORE ); public static class ResourcesExporterSettings implements ExporterSettings { private ResourcesExporterSettings(Map<Material, ResourceSettings> settings) { this.settings = settings; } @Override public boolean isApplyEverywhere() { return minimumLevel > 0; } public int getMinimumLevel() { return minimumLevel; } public void setMinimumLevel(int minimumLevel) { this.minimumLevel = minimumLevel; } public Set<Material> getMaterials() { return settings.keySet(); } public int getMinLevel(Material material) { return settings.get(material).minLevel; } public void setMinLevel(Material material, int minLevel) { settings.get(material).minLevel = minLevel; } public int getMaxLevel(Material material) { return settings.get(material).maxLevel; } public void setMaxLevel(Material material, int maxLevel) { settings.get(material).maxLevel = maxLevel; } public int getChance(Material material) { return settings.get(material).chance; } public void setChance(Material material, int chance) { settings.get(material).chance = chance; } public long getSeedOffset(Material material) { return settings.get(material).seedOffset; } @Override public Resources getLayer() { return Resources.INSTANCE; } @Override public void setMinMaxHeight(int oldMinHeight, int newMinHeight, int oldMaxHeight, int newMaxHeight, HeightTransform transform) { for (Material material: settings.keySet()) { int maxLevel = settings.get(material).maxLevel; if (maxLevel == (oldMaxHeight - 1)) { maxLevel = newMaxHeight - 1; } else if (maxLevel > 1) { maxLevel = clamp(newMinHeight, transform.transformHeight(maxLevel), newMaxHeight - 1); } // TODO: do the same for minLevels? Or do we WANT those to stay put? settings.get(material).maxLevel = maxLevel; } } @Override public ResourcesExporterSettings clone() { try { ResourcesExporterSettings clone = (ResourcesExporterSettings) super.clone(); clone.settings = new LinkedHashMap<>(); settings.forEach((material, settings) -> clone.settings.put(material, settings.clone())); return clone; } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } public static ResourcesExporterSettings defaultSettings(Platform platform, Dimension.Anchor anchor, int minHeight, int maxHeight) { final Random random = new Random(); final Map<Material, ResourceSettings> settings = new HashMap<>(); final Version mcVersion = platform.getAttribute(ATTRIBUTE_MC_VERSION); switch (anchor.dim) { case DIM_NORMAL: // TODO make these normal distributions or something else more similar to Minecraft settings.put(DIRT, new ResourceSettings(DIRT, 0, maxHeight - 1, 57, random.nextLong())); settings.put(GRAVEL, new ResourceSettings(GRAVEL, minHeight, maxHeight - 1, 28, random.nextLong())); settings.put(GOLD_ORE, new ResourceSettings(GOLD_ORE, minHeight, 31, 1, random.nextLong())); settings.put(IRON_ORE, new ResourceSettings(IRON_ORE, minHeight, maxHeight - 1, 6, random.nextLong())); settings.put(COAL, new ResourceSettings(COAL, 0, maxHeight - 1, 10, random.nextLong())); settings.put(LAPIS_LAZULI_ORE, new ResourceSettings(LAPIS_LAZULI_ORE, minHeight, 31, 1, random.nextLong())); settings.put(DIAMOND_ORE, new ResourceSettings(DIAMOND_ORE, minHeight, 15, 1, random.nextLong())); settings.put(REDSTONE_ORE, new ResourceSettings(REDSTONE_ORE, minHeight, 15, 8, random.nextLong())); settings.put(STATIONARY_WATER, new ResourceSettings(STATIONARY_WATER, minHeight, maxHeight - 1, 1, random.nextLong())); settings.put(STATIONARY_LAVA, new ResourceSettings(STATIONARY_LAVA, minHeight, 15, 2, random.nextLong())); settings.put(EMERALD_ORE, new ResourceSettings(EMERALD_ORE, 64, maxHeight - 1, mcVersion.isAtLeast(V_1_2) ? 1 : 0, random.nextLong())); settings.put(COPPER_ORE, new ResourceSettings(COPPER_ORE, 0, 88, mcVersion.isAtLeast(V_1_17) ? 6 : 0, random.nextLong())); settings.put(QUARTZ_ORE, new ResourceSettings(QUARTZ_ORE, minHeight, maxHeight - 1, 0, random.nextLong())); settings.put(ANCIENT_DEBRIS, new ResourceSettings(ANCIENT_DEBRIS, minHeight, maxHeight - 1, 0, random.nextLong())); break; case DIM_NETHER: settings.put(QUARTZ_ORE, new ResourceSettings(QUARTZ_ORE, minHeight, maxHeight - 1, mcVersion.isAtLeast(V_1_2) ? 7 : 0, random.nextLong())); settings.put(GOLD_ORE, new ResourceSettings(GOLD_ORE, minHeight, maxHeight - 1, mcVersion.isAtLeast(V_1_15) ? 3 : 0, random.nextLong())); settings.put(ANCIENT_DEBRIS, new ResourceSettings(ANCIENT_DEBRIS, minHeight, maxHeight - 1, mcVersion.isAtLeast(V_1_15) ? 1 : 0, random.nextLong())); settings.put(DIRT, new ResourceSettings(DIRT, 0, maxHeight - 1, 0, random.nextLong())); settings.put(GRAVEL, new ResourceSettings(GRAVEL, minHeight, maxHeight - 1, 0, random.nextLong())); settings.put(IRON_ORE, new ResourceSettings(IRON_ORE, minHeight, maxHeight - 1, 0, random.nextLong())); settings.put(COAL, new ResourceSettings(COAL, 0, maxHeight - 1, 0, random.nextLong())); settings.put(LAPIS_LAZULI_ORE, new ResourceSettings(LAPIS_LAZULI_ORE, minHeight, 31, 0, random.nextLong())); settings.put(DIAMOND_ORE, new ResourceSettings(DIAMOND_ORE, minHeight, 15, 0, random.nextLong())); settings.put(REDSTONE_ORE, new ResourceSettings(REDSTONE_ORE, minHeight, 15, 0, random.nextLong())); settings.put(STATIONARY_WATER, new ResourceSettings(STATIONARY_WATER, minHeight, maxHeight - 1, 0, random.nextLong())); settings.put(STATIONARY_LAVA, new ResourceSettings(STATIONARY_LAVA, minHeight, 15, 0, random.nextLong())); settings.put(EMERALD_ORE, new ResourceSettings(EMERALD_ORE, 64, maxHeight - 1, 0, random.nextLong())); settings.put(COPPER_ORE, new ResourceSettings(COPPER_ORE, 0, 88, 0, random.nextLong())); break; case DIM_END: settings.put(DIRT, new ResourceSettings(DIRT, 0, maxHeight - 1, 0, random.nextLong())); settings.put(GRAVEL, new ResourceSettings(GRAVEL, minHeight, maxHeight - 1, 0, random.nextLong())); settings.put(GOLD_ORE, new ResourceSettings(GOLD_ORE, minHeight, 31, 0, random.nextLong())); settings.put(IRON_ORE, new ResourceSettings(IRON_ORE, minHeight, maxHeight - 1, 0, random.nextLong())); settings.put(COAL, new ResourceSettings(COAL, 0, maxHeight - 1, 0, random.nextLong())); settings.put(LAPIS_LAZULI_ORE, new ResourceSettings(LAPIS_LAZULI_ORE, minHeight, 31, 0, random.nextLong())); settings.put(DIAMOND_ORE, new ResourceSettings(DIAMOND_ORE, minHeight, 15, 0, random.nextLong())); settings.put(REDSTONE_ORE, new ResourceSettings(REDSTONE_ORE, minHeight, 15, 0, random.nextLong())); settings.put(STATIONARY_WATER, new ResourceSettings(STATIONARY_WATER, minHeight, maxHeight - 1, 0, random.nextLong())); settings.put(STATIONARY_LAVA, new ResourceSettings(STATIONARY_LAVA, minHeight, 15, 0, random.nextLong())); settings.put(EMERALD_ORE, new ResourceSettings(EMERALD_ORE, 64, maxHeight - 1, 0, random.nextLong())); settings.put(COPPER_ORE, new ResourceSettings(COPPER_ORE, 0, 88, 0, random.nextLong())); settings.put(QUARTZ_ORE, new ResourceSettings(QUARTZ_ORE, minHeight, maxHeight - 1, 0, random.nextLong())); settings.put(ANCIENT_DEBRIS, new ResourceSettings(ANCIENT_DEBRIS, minHeight, maxHeight - 1, 0, random.nextLong())); break; default: throw new IllegalArgumentException("Dimension " + anchor.dim + " not supported"); } final ResourcesExporterSettings result = new ResourcesExporterSettings(settings); if (anchor.role == CAVE_FLOOR) { result.setMinimumLevel(0); } return result; } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); if (version < 1) { // Legacy conversions // Fix static water and lava if (! maxLevels.containsKey(BLK_WATER)) { logger.warn("Fixing water and lava settings"); maxLevels.put(BLK_WATER, maxLevels.get(BLK_STATIONARY_WATER)); chances.put(BLK_WATER, chances.get(BLK_STATIONARY_WATER)); seedOffsets.put(BLK_WATER, seedOffsets.get(BLK_STATIONARY_WATER)); maxLevels.put(BLK_LAVA, maxLevels.get(BLK_STATIONARY_LAVA)); chances.put(BLK_LAVA, chances.get(BLK_STATIONARY_LAVA)); seedOffsets.put(BLK_LAVA, seedOffsets.get(BLK_STATIONARY_LAVA)); maxLevels.remove(BLK_STATIONARY_WATER); chances.remove(BLK_STATIONARY_WATER); seedOffsets.remove(BLK_STATIONARY_WATER); maxLevels.remove(BLK_STATIONARY_LAVA); chances.remove(BLK_STATIONARY_LAVA); seedOffsets.remove(BLK_STATIONARY_LAVA); } if (! maxLevels.containsKey(BLK_EMERALD_ORE)) { maxLevels.put(BLK_EMERALD_ORE, 31); chances.put(BLK_EMERALD_ORE, 0); } Random random = new Random(); if (! seedOffsets.containsKey(BLK_EMERALD_ORE)) { seedOffsets.put(BLK_EMERALD_ORE, random.nextLong()); } if (minLevels == null) { minLevels = new HashMap<>(); for (int blockType: maxLevels.keySet()) { minLevels.put(blockType, 0); } } if (! minLevels.containsKey(BLK_QUARTZ_ORE)) { minLevels.put(BLK_QUARTZ_ORE, 0); maxLevels.put(BLK_QUARTZ_ORE, 255); chances.put(BLK_QUARTZ_ORE, 0); seedOffsets.put(BLK_QUARTZ_ORE, random.nextLong()); } // Convert integer-based settings to material-based settings settings = new LinkedHashMap<>(); for (int blockType: maxLevels.keySet()) { Material material = get(blockType); settings.put(material, new ResourceSettings(material, minLevels.get(blockType), maxLevels.get(blockType), chances.get(blockType), seedOffsets.get(blockType))); } minLevels = null; maxLevels = null; chances = null; seedOffsets = null; } if (version < 2) { // Add new resources final Random random = new Random(); settings.put(COPPER_ORE, new ResourceSettings(COPPER_ORE, 0, 88, 0, random.nextLong())); settings.put(ANCIENT_DEBRIS, new ResourceSettings(ANCIENT_DEBRIS, -64, 319, 0, random.nextLong())); } if (version < 3) { if (settings.containsKey(WATER)) { settings.put(STATIONARY_WATER, settings.get(WATER)); settings.remove(WATER); } if (settings.containsKey(LAVA)) { settings.put(STATIONARY_LAVA, settings.get(LAVA)); settings.remove(LAVA); } } version = 3; } private int minimumLevel = 8; private Map<Material, ResourceSettings> settings; /** @deprecated */ @Deprecated private Map<Integer, Integer> maxLevels = null; /** @deprecated */ @Deprecated private Map<Integer, Integer> chances = null; /** @deprecated */ @Deprecated private Map<Integer, Long> seedOffsets = null; /** @deprecated */ @Deprecated private Map<Integer, Integer> minLevels = null; private int version = 3; private static final long serialVersionUID = 1L; private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ResourcesExporter.class); } static class ResourceSettings implements Serializable, Cloneable { ResourceSettings(Material material, int minLevel, int maxLevel, int chance, long seedOffset) { this.material = material; this.minLevel = minLevel; this.maxLevel = maxLevel; this.chance = chance; this.seedOffset = seedOffset; } @Override public ResourceSettings clone() { try { return (ResourceSettings) super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(e); } } Material material; int minLevel, maxLevel, chance; long seedOffset; private static final long serialVersionUID = 1L; } }
21975_16
package com.shuyu.aliplay; import android.content.Context; import android.media.AudioManager; import android.net.Uri; import android.os.Handler; import android.os.Looper; import android.view.Surface; import android.view.SurfaceHolder; import androidx.annotation.Size; import com.aliyun.player.AliPlayer; import com.aliyun.player.AliPlayerFactory; import com.aliyun.player.IPlayer; import com.aliyun.player.bean.ErrorInfo; import com.aliyun.player.bean.InfoBean; import com.aliyun.player.bean.InfoCode; import com.aliyun.player.source.UrlSource; import java.io.FileDescriptor; import java.io.IOException; import java.util.HashMap; import java.util.Map; import tv.danmaku.ijk.media.player.AbstractMediaPlayer; import tv.danmaku.ijk.media.player.IMediaPlayer; import tv.danmaku.ijk.media.player.MediaInfo; import tv.danmaku.ijk.media.player.misc.ITrackInfo; /** * 阿里播放器 * Created by https://github.com/iuhni on 2022/05/16. * @link https://github.com/CarGuo/GSYVideoPlayer/issues/3575 */ public class AliMediaPlayer extends AbstractMediaPlayer { private String TAG = AliMediaPlayer.class.getSimpleName(); protected Context mAppContext; protected Surface mSurface; protected AliPlayer mInternalPlayer; protected Map<String, String> mHeaders = new HashMap<>(); protected String mDataSource; protected UrlSource mMediaSource; protected int mVideoWidth; protected int mVideoHeight; //原视频的buffered private long mVideoBufferedPosition = 0; //原视频的currentPosition private long mCurrentPosition = 0; public AliMediaPlayer(Context context) { mAppContext = context.getApplicationContext(); } @Override public void setDisplay(SurfaceHolder sh) { if (sh == null) setSurface(null); else setSurface(sh.getSurface()); } @Override public void setSurface(Surface surface) { mSurface = surface; if (mInternalPlayer != null) { if (surface != null && !surface.isValid()) { mSurface = null; } mInternalPlayer.setSurface(surface); } } @Override public void setDataSource(Context context, Uri uri, Map<String, String> headers) throws IOException, IllegalArgumentException, SecurityException, IllegalStateException { if (headers != null) { mHeaders.clear(); mHeaders.putAll(headers); } setDataSource(context, uri); } @Override public void setDataSource(String path) throws IOException, IllegalArgumentException, SecurityException, IllegalStateException { setDataSource(mAppContext, Uri.parse(path)); } @Override public void setDataSource(Context context, Uri uri) throws IOException, IllegalArgumentException, SecurityException, IllegalStateException { mDataSource = uri.toString(); UrlSource urlSource = new UrlSource(); urlSource.setUri(uri.toString());//播放地址,可以是第三方点播地址,或阿里云直播服务中的拉流地址。 mMediaSource = urlSource; } @Override public void setDataSource(FileDescriptor fd) throws IOException, IllegalArgumentException, IllegalStateException { throw new UnsupportedOperationException("no support"); } @Override public String getDataSource() { return mDataSource; } @Override public void prepareAsync() throws IllegalStateException { if (mInternalPlayer != null) throw new IllegalStateException("can't prepare a prepared player"); prepareAsyncInternal(); isWaitOnSeekComplete = false; } @Override public void start() throws IllegalStateException { if (mInternalPlayer == null) return; mInternalPlayer.start(); } @Override public void stop() throws IllegalStateException { if (mInternalPlayer == null) return; mInternalPlayer.stop(); } @Override public void pause() throws IllegalStateException { if (mInternalPlayer == null) return; mInternalPlayer.pause(); } @Override public void setScreenOnWhilePlaying(boolean screenOn) { } @Override public int getVideoWidth() { return mVideoWidth; } @Override public int getVideoHeight() { return mVideoHeight; } @Override public boolean isPlaying() { if (mInternalPlayer == null) { return false; } return mPlayState == IPlayer.started; } /** * 是否等待Seek完成 */ private boolean isWaitOnSeekComplete = false; @Override public void seekTo(long msec) throws IllegalStateException { if (mInternalPlayer == null) { return; } if (msec < 0 || msec > getDuration()) { return; } isWaitOnSeekComplete = true; mCurrentPosition = msec; mInternalPlayer.seekTo(msec); } @Override public long getCurrentPosition() { if (mInternalPlayer == null) return 0; return mCurrentPosition; } @Override public long getDuration() { if (mInternalPlayer == null) return 0; return mInternalPlayer.getDuration(); } @Override public int getVideoSarNum() { return 1; } @Override public int getVideoSarDen() { return 1; } @Override public void reset() { if (mInternalPlayer != null) { stop(); mInternalPlayer.release(); mInternalPlayer = null; } mSurface = null; mDataSource = null; mVideoWidth = 0; mVideoHeight = 0; mPlayState = IPlayer.unknow; } @Override public void release() { if (mInternalPlayer != null) { reset(); } } @Override public void setVolume(float leftVolume, float rightVolume) { if (mInternalPlayer != null) mInternalPlayer.setVolume((leftVolume + rightVolume) / 2); } protected int audioSessionId = AudioManager.AUDIO_SESSION_ID_GENERATE; @Override public int getAudioSessionId() { return audioSessionId; } @Override public MediaInfo getMediaInfo() { return null; } @Override public void setLogEnabled(boolean enable) { } @Override public boolean isPlayable() { return false; } @Override public void setAudioStreamType(int streamtype) { } @Override public void setKeepInBackground(boolean keepInBackground) { } @Override public void setWakeMode(Context context, int mode) { } protected boolean isLooping = false; @Override public void setLooping(boolean looping) { isLooping = looping; } @Override public boolean isLooping() { return isLooping; } @Override public ITrackInfo[] getTrackInfo() { return new ITrackInfo[0]; } private String deviceId; public void setDeviceId(String deviceId) { this.deviceId = deviceId; } protected void prepareAsyncInternal() { new Handler(Looper.myLooper()).post( new Runnable() { @Override public void run() { boolean preferExtensionDecoders = true; boolean useExtensionRenderers = true;//是否开启扩展 //创建播放器 mInternalPlayer = AliPlayerFactory.createAliPlayer(mAppContext); //Android播放器SDK提供了H.264、H.265的硬解码能力,同时提供了enableHardwareDecoder提供开关。默认开,并且在硬解初始化失败时,自动切换为软解,保证视频的正常播放。示例如下: // //开启硬解。默认开启 // mInternalPlayer.enableHardwareDecoder(GSYVideoType.isMediaCodec()); if (mSurface != null) { mInternalPlayer.setSurface(mSurface); } //埋点日志上报功能默认开启,当traceId设置为DisableAnalytics时,则关闭埋点日志上报。当traceId设置为其他参数时,则开启埋点日志上报。 //建议传递traceId,便于跟踪日志。traceId为设备或用户的唯一标识符,通常为imei或idfa。 if (deviceId != null && deviceId.length() > 0) { mInternalPlayer.setTraceId(deviceId); } // headers[0]="Host:xxx.com";//比如需要设置Host到header中。 // config.setCustomHeaders(headers); if (mHeaders != null && mHeaders.size() > 0 && mInternalPlayer.getConfig() != null) { String[] itemsArray = new String[mHeaders.size()]; int i = 0; for (Map.Entry<String, String> entry : mHeaders.entrySet()) { itemsArray[i] = entry.getKey() + ":" + entry.getValue(); i++; } mInternalPlayer.getConfig().setCustomHeaders(itemsArray); } //设置准备回调 mInternalPlayer.setOnPreparedListener(onPreparedListener); //第一帧显示 mInternalPlayer.setOnRenderingStartListener(onRenderingStartListener); //播放器出错监听 mInternalPlayer.setOnErrorListener(onErrorListener); // //播放器加载回调 mInternalPlayer.setOnLoadingStatusListener(onLoadingStatusListener); // mAliyunRenderView.setOnTrackReadyListenenr(new VideoPlayerOnTrackReadyListenner(this)); // //播放器状态 mInternalPlayer.setOnStateChangedListener(onStateChangedListener); // //播放结束 mInternalPlayer.setOnCompletionListener(onCompletionListener); // //播放信息监听 mInternalPlayer.setOnInfoListener(onInfoListener); // //trackChange监听 // mAliyunRenderView.setOnTrackChangedListener(new VideoPlayerTrackChangedListener(this)); // //字幕显示和隐藏 // mAliyunRenderView.setOnSubtitleDisplayListener(new VideoPlayerSubtitleDeisplayListener(this)); // //seek结束事件 mInternalPlayer.setOnSeekCompleteListener(onSeekCompleteListener); // //截图监听事件 // mAliyunRenderView.setOnSnapShotListener(new VideoPlayerOnSnapShotListener(this)); // //sei监听事件 // mAliyunRenderView.setOnSeiDataListener(new VideoPlayerOnSeiDataListener(this)); // mAliyunRenderView.setOnVerifyTimeExpireCallback(new VideoPlayerOnVerifyStsCallback(this)); //设置视频宽高变化监听 mInternalPlayer.setOnVideoSizeChangedListener(onVideoSizeChangedListener); mInternalPlayer.setLoop(isLooping); mInternalPlayer.setDataSource(mMediaSource); mInternalPlayer.prepare(); // mInternalPlayer.setPlayWhenReady(false); } } ); } /** * 是否带上header */ protected boolean isPreview = false; /** * 是否需要带上header * setDataSource之前生效 */ public void setPreview(boolean preview) { isPreview = preview; } public boolean isPreview() { return isPreview; } /** * 倍速播放 * * @param speed 倍速播放,默认为1 */ public void setSpeed(@Size(min = 0) float speed) { if (mInternalPlayer != null) { mInternalPlayer.setSpeed(speed); } } public float getSpeed() { return mInternalPlayer.getSpeed(); } public int getBufferedPercentage() { if (mInternalPlayer == null) { return 0; } int percent = 0; if (getDuration() > 0) { percent = (int) ((float) mVideoBufferedPosition / getDuration() * 100f); } //Log.e(TAG, "getBufferedPercentage percent = " + percent + " mVideoBufferedPosition = " + mVideoBufferedPosition + " getDuration = " + getDuration()); return percent; } protected boolean isPreparing = true; private IPlayer.OnPreparedListener onPreparedListener = new IPlayer.OnPreparedListener() { @Override public void onPrepared() { if (isPreparing) { notifyOnPrepared(); isPreparing = false; } } }; private IPlayer.OnRenderingStartListener onRenderingStartListener = new IPlayer.OnRenderingStartListener() { @Override public void onRenderingStart() { //Log.e(TAG, "onRenderingStartListener "); } }; private IPlayer.OnErrorListener onErrorListener = new IPlayer.OnErrorListener() { @Override public void onError(ErrorInfo errorInfo) { notifyOnError(IMediaPlayer.MEDIA_ERROR_UNKNOWN, IMediaPlayer.MEDIA_ERROR_UNKNOWN); //Log.e(TAG, "onErrorListener " + errorInfo.getCode().toString() + errorInfo.getMsg() + errorInfo.getExtra()); } }; private IPlayer.OnInfoListener onInfoListener = new IPlayer.OnInfoListener() { @Override public void onInfo(InfoBean infoBean) { sourceVideoPlayerInfo(infoBean); //Log.e(TAG, "onInfoListener " + infoBean.getCode().toString() + infoBean.getExtraValue() + infoBean.getExtraMsg()); } }; private long netSpeedLong = -1; /** * 原视频Info */ private void sourceVideoPlayerInfo(InfoBean infoBean) { if (isWaitOnSeekComplete) { return; } if (infoBean.getCode() == InfoCode.CurrentDownloadSpeed) { //当前下载速度 netSpeedLong = infoBean.getExtraValue(); //Log.e(TAG, "sourceVideoPlayerInfo CurrentDownloadSpeed = " + netSpeedLong); } else if (infoBean.getCode() == InfoCode.BufferedPosition) { //更新bufferedPosition mVideoBufferedPosition = infoBean.getExtraValue(); } else if (infoBean.getCode() == InfoCode.CurrentPosition) { //更新currentPosition mCurrentPosition = infoBean.getExtraValue(); } } public long getNetSpeed() { return netSpeedLong; } private IPlayer.OnLoadingStatusListener onLoadingStatusListener = new IPlayer.OnLoadingStatusListener() { @Override public void onLoadingBegin() { //Log.e(TAG, "onLoadingStatusListener onLoadingBegin "); notifyOnInfo(IMediaPlayer.MEDIA_INFO_BUFFERING_START, 0); } @Override public void onLoadingProgress(int percent, float netSpeed) { //Log.e(TAG, "onLoadingStatusListener onLoadingProgress percent = " + percent + " netSpeed = " + netSpeed); } @Override public void onLoadingEnd() { //Log.e(TAG, "onLoadingStatusListener onLoadingEnd "); notifyOnInfo(IMediaPlayer.MEDIA_INFO_BUFFERING_END, 0); } }; //视频播放状态 private int mPlayState = IPlayer.unknow; private IPlayer.OnStateChangedListener onStateChangedListener = new IPlayer.OnStateChangedListener() { @Override public void onStateChanged(int i) { mPlayState = i; //Log.e(TAG, "onStateChangedListener onStateChanged " + i); } }; private IPlayer.OnCompletionListener onCompletionListener = new IPlayer.OnCompletionListener() { @Override public void onCompletion() { notifyOnCompletion(); //Log.e(TAG, "onCompletionListener onCompletion "); } }; private IPlayer.OnVideoSizeChangedListener onVideoSizeChangedListener = new IPlayer.OnVideoSizeChangedListener() { @Override public void onVideoSizeChanged(int width, int height) { mVideoWidth = width; mVideoHeight = height; notifyOnVideoSizeChanged(width, height, 1, 1); //Log.e(TAG, "onVideoSizeChangedListener " + width + " " + height); } }; private IPlayer.OnSeekCompleteListener onSeekCompleteListener = new IPlayer.OnSeekCompleteListener() { @Override public void onSeekComplete() { isWaitOnSeekComplete = false; //Log.e(TAG, "onSeekCompleteListener onSeekComplete "); } }; }
CarGuo/GSYVideoPlayer
gsyVideoPlayer-aliplay/src/main/java/com/shuyu/aliplay/AliMediaPlayer.java
4,530
//Log.e(TAG, "onVideoSizeChangedListener " + width + " " + height);
line_comment
nl
package com.shuyu.aliplay; import android.content.Context; import android.media.AudioManager; import android.net.Uri; import android.os.Handler; import android.os.Looper; import android.view.Surface; import android.view.SurfaceHolder; import androidx.annotation.Size; import com.aliyun.player.AliPlayer; import com.aliyun.player.AliPlayerFactory; import com.aliyun.player.IPlayer; import com.aliyun.player.bean.ErrorInfo; import com.aliyun.player.bean.InfoBean; import com.aliyun.player.bean.InfoCode; import com.aliyun.player.source.UrlSource; import java.io.FileDescriptor; import java.io.IOException; import java.util.HashMap; import java.util.Map; import tv.danmaku.ijk.media.player.AbstractMediaPlayer; import tv.danmaku.ijk.media.player.IMediaPlayer; import tv.danmaku.ijk.media.player.MediaInfo; import tv.danmaku.ijk.media.player.misc.ITrackInfo; /** * 阿里播放器 * Created by https://github.com/iuhni on 2022/05/16. * @link https://github.com/CarGuo/GSYVideoPlayer/issues/3575 */ public class AliMediaPlayer extends AbstractMediaPlayer { private String TAG = AliMediaPlayer.class.getSimpleName(); protected Context mAppContext; protected Surface mSurface; protected AliPlayer mInternalPlayer; protected Map<String, String> mHeaders = new HashMap<>(); protected String mDataSource; protected UrlSource mMediaSource; protected int mVideoWidth; protected int mVideoHeight; //原视频的buffered private long mVideoBufferedPosition = 0; //原视频的currentPosition private long mCurrentPosition = 0; public AliMediaPlayer(Context context) { mAppContext = context.getApplicationContext(); } @Override public void setDisplay(SurfaceHolder sh) { if (sh == null) setSurface(null); else setSurface(sh.getSurface()); } @Override public void setSurface(Surface surface) { mSurface = surface; if (mInternalPlayer != null) { if (surface != null && !surface.isValid()) { mSurface = null; } mInternalPlayer.setSurface(surface); } } @Override public void setDataSource(Context context, Uri uri, Map<String, String> headers) throws IOException, IllegalArgumentException, SecurityException, IllegalStateException { if (headers != null) { mHeaders.clear(); mHeaders.putAll(headers); } setDataSource(context, uri); } @Override public void setDataSource(String path) throws IOException, IllegalArgumentException, SecurityException, IllegalStateException { setDataSource(mAppContext, Uri.parse(path)); } @Override public void setDataSource(Context context, Uri uri) throws IOException, IllegalArgumentException, SecurityException, IllegalStateException { mDataSource = uri.toString(); UrlSource urlSource = new UrlSource(); urlSource.setUri(uri.toString());//播放地址,可以是第三方点播地址,或阿里云直播服务中的拉流地址。 mMediaSource = urlSource; } @Override public void setDataSource(FileDescriptor fd) throws IOException, IllegalArgumentException, IllegalStateException { throw new UnsupportedOperationException("no support"); } @Override public String getDataSource() { return mDataSource; } @Override public void prepareAsync() throws IllegalStateException { if (mInternalPlayer != null) throw new IllegalStateException("can't prepare a prepared player"); prepareAsyncInternal(); isWaitOnSeekComplete = false; } @Override public void start() throws IllegalStateException { if (mInternalPlayer == null) return; mInternalPlayer.start(); } @Override public void stop() throws IllegalStateException { if (mInternalPlayer == null) return; mInternalPlayer.stop(); } @Override public void pause() throws IllegalStateException { if (mInternalPlayer == null) return; mInternalPlayer.pause(); } @Override public void setScreenOnWhilePlaying(boolean screenOn) { } @Override public int getVideoWidth() { return mVideoWidth; } @Override public int getVideoHeight() { return mVideoHeight; } @Override public boolean isPlaying() { if (mInternalPlayer == null) { return false; } return mPlayState == IPlayer.started; } /** * 是否等待Seek完成 */ private boolean isWaitOnSeekComplete = false; @Override public void seekTo(long msec) throws IllegalStateException { if (mInternalPlayer == null) { return; } if (msec < 0 || msec > getDuration()) { return; } isWaitOnSeekComplete = true; mCurrentPosition = msec; mInternalPlayer.seekTo(msec); } @Override public long getCurrentPosition() { if (mInternalPlayer == null) return 0; return mCurrentPosition; } @Override public long getDuration() { if (mInternalPlayer == null) return 0; return mInternalPlayer.getDuration(); } @Override public int getVideoSarNum() { return 1; } @Override public int getVideoSarDen() { return 1; } @Override public void reset() { if (mInternalPlayer != null) { stop(); mInternalPlayer.release(); mInternalPlayer = null; } mSurface = null; mDataSource = null; mVideoWidth = 0; mVideoHeight = 0; mPlayState = IPlayer.unknow; } @Override public void release() { if (mInternalPlayer != null) { reset(); } } @Override public void setVolume(float leftVolume, float rightVolume) { if (mInternalPlayer != null) mInternalPlayer.setVolume((leftVolume + rightVolume) / 2); } protected int audioSessionId = AudioManager.AUDIO_SESSION_ID_GENERATE; @Override public int getAudioSessionId() { return audioSessionId; } @Override public MediaInfo getMediaInfo() { return null; } @Override public void setLogEnabled(boolean enable) { } @Override public boolean isPlayable() { return false; } @Override public void setAudioStreamType(int streamtype) { } @Override public void setKeepInBackground(boolean keepInBackground) { } @Override public void setWakeMode(Context context, int mode) { } protected boolean isLooping = false; @Override public void setLooping(boolean looping) { isLooping = looping; } @Override public boolean isLooping() { return isLooping; } @Override public ITrackInfo[] getTrackInfo() { return new ITrackInfo[0]; } private String deviceId; public void setDeviceId(String deviceId) { this.deviceId = deviceId; } protected void prepareAsyncInternal() { new Handler(Looper.myLooper()).post( new Runnable() { @Override public void run() { boolean preferExtensionDecoders = true; boolean useExtensionRenderers = true;//是否开启扩展 //创建播放器 mInternalPlayer = AliPlayerFactory.createAliPlayer(mAppContext); //Android播放器SDK提供了H.264、H.265的硬解码能力,同时提供了enableHardwareDecoder提供开关。默认开,并且在硬解初始化失败时,自动切换为软解,保证视频的正常播放。示例如下: // //开启硬解。默认开启 // mInternalPlayer.enableHardwareDecoder(GSYVideoType.isMediaCodec()); if (mSurface != null) { mInternalPlayer.setSurface(mSurface); } //埋点日志上报功能默认开启,当traceId设置为DisableAnalytics时,则关闭埋点日志上报。当traceId设置为其他参数时,则开启埋点日志上报。 //建议传递traceId,便于跟踪日志。traceId为设备或用户的唯一标识符,通常为imei或idfa。 if (deviceId != null && deviceId.length() > 0) { mInternalPlayer.setTraceId(deviceId); } // headers[0]="Host:xxx.com";//比如需要设置Host到header中。 // config.setCustomHeaders(headers); if (mHeaders != null && mHeaders.size() > 0 && mInternalPlayer.getConfig() != null) { String[] itemsArray = new String[mHeaders.size()]; int i = 0; for (Map.Entry<String, String> entry : mHeaders.entrySet()) { itemsArray[i] = entry.getKey() + ":" + entry.getValue(); i++; } mInternalPlayer.getConfig().setCustomHeaders(itemsArray); } //设置准备回调 mInternalPlayer.setOnPreparedListener(onPreparedListener); //第一帧显示 mInternalPlayer.setOnRenderingStartListener(onRenderingStartListener); //播放器出错监听 mInternalPlayer.setOnErrorListener(onErrorListener); // //播放器加载回调 mInternalPlayer.setOnLoadingStatusListener(onLoadingStatusListener); // mAliyunRenderView.setOnTrackReadyListenenr(new VideoPlayerOnTrackReadyListenner(this)); // //播放器状态 mInternalPlayer.setOnStateChangedListener(onStateChangedListener); // //播放结束 mInternalPlayer.setOnCompletionListener(onCompletionListener); // //播放信息监听 mInternalPlayer.setOnInfoListener(onInfoListener); // //trackChange监听 // mAliyunRenderView.setOnTrackChangedListener(new VideoPlayerTrackChangedListener(this)); // //字幕显示和隐藏 // mAliyunRenderView.setOnSubtitleDisplayListener(new VideoPlayerSubtitleDeisplayListener(this)); // //seek结束事件 mInternalPlayer.setOnSeekCompleteListener(onSeekCompleteListener); // //截图监听事件 // mAliyunRenderView.setOnSnapShotListener(new VideoPlayerOnSnapShotListener(this)); // //sei监听事件 // mAliyunRenderView.setOnSeiDataListener(new VideoPlayerOnSeiDataListener(this)); // mAliyunRenderView.setOnVerifyTimeExpireCallback(new VideoPlayerOnVerifyStsCallback(this)); //设置视频宽高变化监听 mInternalPlayer.setOnVideoSizeChangedListener(onVideoSizeChangedListener); mInternalPlayer.setLoop(isLooping); mInternalPlayer.setDataSource(mMediaSource); mInternalPlayer.prepare(); // mInternalPlayer.setPlayWhenReady(false); } } ); } /** * 是否带上header */ protected boolean isPreview = false; /** * 是否需要带上header * setDataSource之前生效 */ public void setPreview(boolean preview) { isPreview = preview; } public boolean isPreview() { return isPreview; } /** * 倍速播放 * * @param speed 倍速播放,默认为1 */ public void setSpeed(@Size(min = 0) float speed) { if (mInternalPlayer != null) { mInternalPlayer.setSpeed(speed); } } public float getSpeed() { return mInternalPlayer.getSpeed(); } public int getBufferedPercentage() { if (mInternalPlayer == null) { return 0; } int percent = 0; if (getDuration() > 0) { percent = (int) ((float) mVideoBufferedPosition / getDuration() * 100f); } //Log.e(TAG, "getBufferedPercentage percent = " + percent + " mVideoBufferedPosition = " + mVideoBufferedPosition + " getDuration = " + getDuration()); return percent; } protected boolean isPreparing = true; private IPlayer.OnPreparedListener onPreparedListener = new IPlayer.OnPreparedListener() { @Override public void onPrepared() { if (isPreparing) { notifyOnPrepared(); isPreparing = false; } } }; private IPlayer.OnRenderingStartListener onRenderingStartListener = new IPlayer.OnRenderingStartListener() { @Override public void onRenderingStart() { //Log.e(TAG, "onRenderingStartListener "); } }; private IPlayer.OnErrorListener onErrorListener = new IPlayer.OnErrorListener() { @Override public void onError(ErrorInfo errorInfo) { notifyOnError(IMediaPlayer.MEDIA_ERROR_UNKNOWN, IMediaPlayer.MEDIA_ERROR_UNKNOWN); //Log.e(TAG, "onErrorListener " + errorInfo.getCode().toString() + errorInfo.getMsg() + errorInfo.getExtra()); } }; private IPlayer.OnInfoListener onInfoListener = new IPlayer.OnInfoListener() { @Override public void onInfo(InfoBean infoBean) { sourceVideoPlayerInfo(infoBean); //Log.e(TAG, "onInfoListener " + infoBean.getCode().toString() + infoBean.getExtraValue() + infoBean.getExtraMsg()); } }; private long netSpeedLong = -1; /** * 原视频Info */ private void sourceVideoPlayerInfo(InfoBean infoBean) { if (isWaitOnSeekComplete) { return; } if (infoBean.getCode() == InfoCode.CurrentDownloadSpeed) { //当前下载速度 netSpeedLong = infoBean.getExtraValue(); //Log.e(TAG, "sourceVideoPlayerInfo CurrentDownloadSpeed = " + netSpeedLong); } else if (infoBean.getCode() == InfoCode.BufferedPosition) { //更新bufferedPosition mVideoBufferedPosition = infoBean.getExtraValue(); } else if (infoBean.getCode() == InfoCode.CurrentPosition) { //更新currentPosition mCurrentPosition = infoBean.getExtraValue(); } } public long getNetSpeed() { return netSpeedLong; } private IPlayer.OnLoadingStatusListener onLoadingStatusListener = new IPlayer.OnLoadingStatusListener() { @Override public void onLoadingBegin() { //Log.e(TAG, "onLoadingStatusListener onLoadingBegin "); notifyOnInfo(IMediaPlayer.MEDIA_INFO_BUFFERING_START, 0); } @Override public void onLoadingProgress(int percent, float netSpeed) { //Log.e(TAG, "onLoadingStatusListener onLoadingProgress percent = " + percent + " netSpeed = " + netSpeed); } @Override public void onLoadingEnd() { //Log.e(TAG, "onLoadingStatusListener onLoadingEnd "); notifyOnInfo(IMediaPlayer.MEDIA_INFO_BUFFERING_END, 0); } }; //视频播放状态 private int mPlayState = IPlayer.unknow; private IPlayer.OnStateChangedListener onStateChangedListener = new IPlayer.OnStateChangedListener() { @Override public void onStateChanged(int i) { mPlayState = i; //Log.e(TAG, "onStateChangedListener onStateChanged " + i); } }; private IPlayer.OnCompletionListener onCompletionListener = new IPlayer.OnCompletionListener() { @Override public void onCompletion() { notifyOnCompletion(); //Log.e(TAG, "onCompletionListener onCompletion "); } }; private IPlayer.OnVideoSizeChangedListener onVideoSizeChangedListener = new IPlayer.OnVideoSizeChangedListener() { @Override public void onVideoSizeChanged(int width, int height) { mVideoWidth = width; mVideoHeight = height; notifyOnVideoSizeChanged(width, height, 1, 1); //Log.e(TAG, "onVideoSizeChangedListener<SUF> } }; private IPlayer.OnSeekCompleteListener onSeekCompleteListener = new IPlayer.OnSeekCompleteListener() { @Override public void onSeekComplete() { isWaitOnSeekComplete = false; //Log.e(TAG, "onSeekCompleteListener onSeekComplete "); } }; }
11692_30
// Mastermind versie 1.0 // author: Caspar Steinebach import java.util.*; // Import Library public class Main { // Hoofdklasse static char[] codeComputer = new char[4]; static char[] codeMens = new char[4]; static String doorgeven = "abcd"; public static void main(String[] args) { clearScreen(); System.out.println("** MASTERMIND - Caspar Steinebach **"); System.out.println("toets 'q' om het spel te verlaten"); lijstLettersRandom(); while (true) { lettersKloppen(); checkRun(); } } static void clearScreen() { System.out.flush(); } static void lijstLettersRandom() { // Deze methode laat de computer een code genereren. String alfabet = "abcdef"; // Dit zijn de beschikbare letters. Random r = new Random(); // een nieuwe randomgeneratoer wordt aangemaakt met de naam 'r'. for (int i = 0; i < 4; i++) { // forloop om een dobbelsteen te gooien. char willekeur = alfabet.charAt(r.nextInt(6)); // willekeurig karakter uit de string alfabet (uit die 6 karaters) wordt gekozen. codeComputer[i] = willekeur; // karakters worden in de charArray 'codeComputer' gestopt. } //System.out.println(codeComputer); doorgeven = String.valueOf(codeComputer); // 'codeComputer' wordt omgezet in een string en opgeslagen in de string 'doorgeven' } static void lettersKloppen() { //deze methode laat de gebruiker letters intoetsen en slaat ze op in een Array System.out.println("-------------------------------------"); System.out.println("Voer je code in: 4 letters (a t/m f)"); Scanner scanner = new Scanner(System.in); String invoer = scanner.nextLine(); if (invoer.equals("q")){ // Als de gebruiker 'q' intoetst dan eindigt het spel System.out.print("Bedankt en tot ziens!"); System.exit(0); } codeMens = invoer.toCharArray(); // De string invoer wordt in losse leters omgezet en in de charArray 'codeMens' gezet. Om later weer te gebruiken als het spel over is. (zie regel 67). } static void checkRun() { // deze methode checkt op juiste letters op de juiste plek int lettersJuistePlek = 0; // Een int wordt aangemaakt die als teller genereert om de gebruiker te laten weten hoeveel letters op de juiste plek staan. int goedeLettersOnjuistePlek = 0; // Een int wordt aangemaakt die als teller genereert om de gebruiker te laten weten hoeveel letters op de juiste plek staan. for (int i = 0; i < 4; i++) { // Forloop om door de verschillende lettercombinaties te lopen en te checken of if (codeComputer[i] == codeMens[i]) { // de combinatie klopt. Als die klopt heeft de speler de code gekraakt. lettersJuistePlek += 1; // Bij elke goede letter gaat de teller 1 omhoog. } } if (lettersJuistePlek == 4) { // Als de teller op '4' staat dan heeft de speler alle letters goed geraden en System.out.println("********** Gewonnen! **********"); // is de code gekraakt. Een felicitatie valt de speler ten deel. System.out.println("De juiste codecombinatie was : " + doorgeven); System.exit(0); // Het spel is afgelopen en wordt automatisch afgesloten. } lettersJuistePlek = 0; // Als niet alle letters goed zijn, dan betekent dat dat de code niet gekraakt is. // In dat geval wordt de teller weer op '0' gezet en worden de cijfers opnieuw if (codeComputer[0] == codeMens[0]) { // met elkaar vergeleken. Hier de eerste letter. lettersJuistePlek += 1; // Teller 'lettersJuistePlek' gaat 1 omhoog als die klopt } else { // Als de eerste letter niet overeenkomst gaan we kijen of hij vaker voorkomt for (int i = 0; i < 4; i++) { if (codeComputer[i] == codeMens[0]) { // hij wordt veregeleken met andere letters goedeLettersOnjuistePlek += 1; // als die ergens op een andere plek voorkomt dan wordt de teller met 1 verhoogt } } } if (codeComputer[1] == codeMens[1]) { // Hier de tweede letter. lettersJuistePlek += 1; // Teller 'lettersJuistePlek' gaat 1 omhoog als die klopt } else { for (int i = 0; i < 4; i++) { // Als de eerste letter niet overeenkomst gaan we kijen of hij vaker voorkomt if (codeComputer[i] == codeMens[1]) { goedeLettersOnjuistePlek += 1; } } } if (codeComputer[2] == codeMens[2]) { // Hier de derde letter lettersJuistePlek += 1; // Teller 'lettersJuistePlek' gaat 1 omhoog als die klopt } else { for (int i = 0; i < 4; i++) { if (codeComputer[i] == codeMens[2]) { goedeLettersOnjuistePlek += 1; } } } if (codeComputer[3] == codeMens[3]) { // Hier de vierde letter lettersJuistePlek += 1; // Teller 'lettersJuistePlek' gaat 1 omhoog als die klopt } else { for (int i = 0; i < 4; i++) { if (codeComputer[i] == codeMens[3]) { goedeLettersOnjuistePlek += 1; } } } System.out.println("Aantal letters op de juiste plek: " + lettersJuistePlek); // Een print van hoeveel letters er op de juiste plek staan. System.out.println("Aantal goede letters op een onjuiste plek: " + goedeLettersOnjuistePlek); // Een print wordt gemaakt van hoeveel letters er voorkomend zijn maar niet op de juiste plek staan. } } /* Mastermind De opdracht Programmeer het spel Mastermind tegen de computer, waarbij je gebruik maakt van Object Oriented Programming. Hieronder staat het spelverloop uitgelegd. Spelverloop De computer kiest random vier letters uit de verzameling {a, b, c, d, e, f}. De gekozen rij wordt verder “code” genoemd. De volgorde is van belang; een letter mag vaker voorkomen. De gebruiker moet de verborgen code proberen te achterhalen. De gebruiker geeft een code van vier letters op. De computer geeft een reactie op de ingegeven code, door te antwoorden met: -> het aantal correcte letters die op de juiste plaats staan -> het aantal correcte letters dat NIET op de juiste plaats staat De gebruiker geeft nu een nieuwe code op, gebaseerd op deze nieuwe informatie. Als alle vier letters op de juiste plaats staan, is de code gekraakt en het spel ten einde. Een lopend spel kan worden beëindigd door het invoeren van een q; alle andere invoer moet ofwel correct zijn (dus in de verzameling voorkomen), ofwel resulteren in opnieuw bevragen van de gebruiker */
CasparSteinebach/Qien1
Mastermind/Mastermind.java
2,181
// Als de eerste letter niet overeenkomst gaan we kijen of hij vaker voorkomt
line_comment
nl
// Mastermind versie 1.0 // author: Caspar Steinebach import java.util.*; // Import Library public class Main { // Hoofdklasse static char[] codeComputer = new char[4]; static char[] codeMens = new char[4]; static String doorgeven = "abcd"; public static void main(String[] args) { clearScreen(); System.out.println("** MASTERMIND - Caspar Steinebach **"); System.out.println("toets 'q' om het spel te verlaten"); lijstLettersRandom(); while (true) { lettersKloppen(); checkRun(); } } static void clearScreen() { System.out.flush(); } static void lijstLettersRandom() { // Deze methode laat de computer een code genereren. String alfabet = "abcdef"; // Dit zijn de beschikbare letters. Random r = new Random(); // een nieuwe randomgeneratoer wordt aangemaakt met de naam 'r'. for (int i = 0; i < 4; i++) { // forloop om een dobbelsteen te gooien. char willekeur = alfabet.charAt(r.nextInt(6)); // willekeurig karakter uit de string alfabet (uit die 6 karaters) wordt gekozen. codeComputer[i] = willekeur; // karakters worden in de charArray 'codeComputer' gestopt. } //System.out.println(codeComputer); doorgeven = String.valueOf(codeComputer); // 'codeComputer' wordt omgezet in een string en opgeslagen in de string 'doorgeven' } static void lettersKloppen() { //deze methode laat de gebruiker letters intoetsen en slaat ze op in een Array System.out.println("-------------------------------------"); System.out.println("Voer je code in: 4 letters (a t/m f)"); Scanner scanner = new Scanner(System.in); String invoer = scanner.nextLine(); if (invoer.equals("q")){ // Als de gebruiker 'q' intoetst dan eindigt het spel System.out.print("Bedankt en tot ziens!"); System.exit(0); } codeMens = invoer.toCharArray(); // De string invoer wordt in losse leters omgezet en in de charArray 'codeMens' gezet. Om later weer te gebruiken als het spel over is. (zie regel 67). } static void checkRun() { // deze methode checkt op juiste letters op de juiste plek int lettersJuistePlek = 0; // Een int wordt aangemaakt die als teller genereert om de gebruiker te laten weten hoeveel letters op de juiste plek staan. int goedeLettersOnjuistePlek = 0; // Een int wordt aangemaakt die als teller genereert om de gebruiker te laten weten hoeveel letters op de juiste plek staan. for (int i = 0; i < 4; i++) { // Forloop om door de verschillende lettercombinaties te lopen en te checken of if (codeComputer[i] == codeMens[i]) { // de combinatie klopt. Als die klopt heeft de speler de code gekraakt. lettersJuistePlek += 1; // Bij elke goede letter gaat de teller 1 omhoog. } } if (lettersJuistePlek == 4) { // Als de teller op '4' staat dan heeft de speler alle letters goed geraden en System.out.println("********** Gewonnen! **********"); // is de code gekraakt. Een felicitatie valt de speler ten deel. System.out.println("De juiste codecombinatie was : " + doorgeven); System.exit(0); // Het spel is afgelopen en wordt automatisch afgesloten. } lettersJuistePlek = 0; // Als niet alle letters goed zijn, dan betekent dat dat de code niet gekraakt is. // In dat geval wordt de teller weer op '0' gezet en worden de cijfers opnieuw if (codeComputer[0] == codeMens[0]) { // met elkaar vergeleken. Hier de eerste letter. lettersJuistePlek += 1; // Teller 'lettersJuistePlek' gaat 1 omhoog als die klopt } else { // Als de eerste letter niet overeenkomst gaan we kijen of hij vaker voorkomt for (int i = 0; i < 4; i++) { if (codeComputer[i] == codeMens[0]) { // hij wordt veregeleken met andere letters goedeLettersOnjuistePlek += 1; // als die ergens op een andere plek voorkomt dan wordt de teller met 1 verhoogt } } } if (codeComputer[1] == codeMens[1]) { // Hier de tweede letter. lettersJuistePlek += 1; // Teller 'lettersJuistePlek' gaat 1 omhoog als die klopt } else { for (int i = 0; i < 4; i++) { // Als de<SUF> if (codeComputer[i] == codeMens[1]) { goedeLettersOnjuistePlek += 1; } } } if (codeComputer[2] == codeMens[2]) { // Hier de derde letter lettersJuistePlek += 1; // Teller 'lettersJuistePlek' gaat 1 omhoog als die klopt } else { for (int i = 0; i < 4; i++) { if (codeComputer[i] == codeMens[2]) { goedeLettersOnjuistePlek += 1; } } } if (codeComputer[3] == codeMens[3]) { // Hier de vierde letter lettersJuistePlek += 1; // Teller 'lettersJuistePlek' gaat 1 omhoog als die klopt } else { for (int i = 0; i < 4; i++) { if (codeComputer[i] == codeMens[3]) { goedeLettersOnjuistePlek += 1; } } } System.out.println("Aantal letters op de juiste plek: " + lettersJuistePlek); // Een print van hoeveel letters er op de juiste plek staan. System.out.println("Aantal goede letters op een onjuiste plek: " + goedeLettersOnjuistePlek); // Een print wordt gemaakt van hoeveel letters er voorkomend zijn maar niet op de juiste plek staan. } } /* Mastermind De opdracht Programmeer het spel Mastermind tegen de computer, waarbij je gebruik maakt van Object Oriented Programming. Hieronder staat het spelverloop uitgelegd. Spelverloop De computer kiest random vier letters uit de verzameling {a, b, c, d, e, f}. De gekozen rij wordt verder “code” genoemd. De volgorde is van belang; een letter mag vaker voorkomen. De gebruiker moet de verborgen code proberen te achterhalen. De gebruiker geeft een code van vier letters op. De computer geeft een reactie op de ingegeven code, door te antwoorden met: -> het aantal correcte letters die op de juiste plaats staan -> het aantal correcte letters dat NIET op de juiste plaats staat De gebruiker geeft nu een nieuwe code op, gebaseerd op deze nieuwe informatie. Als alle vier letters op de juiste plaats staan, is de code gekraakt en het spel ten einde. Een lopend spel kan worden beëindigd door het invoeren van een q; alle andere invoer moet ofwel correct zijn (dus in de verzameling voorkomen), ofwel resulteren in opnieuw bevragen van de gebruiker */
7316_1
package com.company; import java.util.*; public class Spel { Scanner scanner = new Scanner(System.in); Speelbord speelbord = new Speelbord(); Speler speler2 = new Speler(0, 0, "naamSpeler"); Speler speler1 = new Speler(0, 0, "naamSpeler"); public void Start() { speelbord.getSpeelbord(0,0,0); tweeSpelers(2); } public void tweeSpelers(int aantalSpelers) { Scanner scanner = new Scanner(System.in); System.out.println("Naam speler1: "); String naamSpeler1 = scanner.nextLine(); speler1.changeNaam(naamSpeler1); System.out.println("Naam speler2: "); String naamSpeler2 = scanner.nextLine(); speler2.changeNaam(naamSpeler2); System.out.println("We spelen met " + aantalSpelers); System.out.println("Leuk dat jullie meedoen " + speler1.getNaam() + " en " + speler2.getNaam() + "!"); System.out.println("We gaan beginnen!"); System.out.println(speler1.getNaam() + ", gooi een dobbelsteen (toets g) of pak een steen (p)"); while (true) { String gVoorGooien = scanner.nextLine(); if (gVoorGooien.equals("p")) { System.out.println("Welke steen wil je pakken?"); Integer steenPakken = scanner.nextInt(); speelbord.spelerEenSteenPakken(steenPakken); } if (gVoorGooien.equals("g")) { speler1.Dobbelen(); speler1.keuzeMaken(); System.out.println("Je gooit met " + speler1.aantalDobbelstenen() + " dobbelstenen."); System.out.println(speler1.getNaam() + " je hebt nu " + speler1.hoeveelheidPunten() + " punten."); System.out.println(speler1.getNaam() + " gooit nog een keer (toets g) of pak een steen (p)"); } else { System.out.println("toets g om de dobbelsteen te gooien"); } } } public void spelSpeler1(){ System.out.println(speler1.getNaam() + ", gooi een dobbelsteen (toets g) of pak een steen (p)"); while (true) { String gVoorGooien = scanner.nextLine(); if (gVoorGooien.equals("p")) { System.out.println("Welke steen wil je pakken?"); Integer steenPakken = scanner.nextInt(); speelbord.spelerEenSteenPakken(steenPakken); } if (gVoorGooien.equals("g")) { speler1.Dobbelen(); speler1.keuzeMaken(); System.out.println("Je gooit met " + speler1.aantalDobbelstenen() + " dobbelstenen."); System.out.println(speler1.getNaam() + " je hebt nu " + speler1.hoeveelheidPunten() + " punten."); System.out.println(speler1.getNaam() + " gooit nog een keer (toets g) of pak een steen (p)"); } else { System.out.println("toets g om de dobbelsteen te gooien"); } } } //=============== Oude Methodes ============== public int aantalSpelers(){ System.out.println("**** REGENWORMEN ****"); //System.out.println("Met hoeveel spelers wil je spelen? (2, 3 of 4 spelers)"); //int aantalSpelers = scanner.nextInt(); int aantalSpelers = 2; spelersAanmelden(aantalSpelers); return aantalSpelers; } public void spelersAanmelden(int aantalSpelers){ if (aantalSpelers == 2){ System.out.println("2 spelers"); tweeSpelers(2); } else { System.out.println("Aantal spelers is minimaal 2 en maximaal 4 "); aantalSpelers(); } } }
CasparSteinebach/Regenwormen2020
src/com/company/Spel.java
1,242
//System.out.println("Met hoeveel spelers wil je spelen? (2, 3 of 4 spelers)");
line_comment
nl
package com.company; import java.util.*; public class Spel { Scanner scanner = new Scanner(System.in); Speelbord speelbord = new Speelbord(); Speler speler2 = new Speler(0, 0, "naamSpeler"); Speler speler1 = new Speler(0, 0, "naamSpeler"); public void Start() { speelbord.getSpeelbord(0,0,0); tweeSpelers(2); } public void tweeSpelers(int aantalSpelers) { Scanner scanner = new Scanner(System.in); System.out.println("Naam speler1: "); String naamSpeler1 = scanner.nextLine(); speler1.changeNaam(naamSpeler1); System.out.println("Naam speler2: "); String naamSpeler2 = scanner.nextLine(); speler2.changeNaam(naamSpeler2); System.out.println("We spelen met " + aantalSpelers); System.out.println("Leuk dat jullie meedoen " + speler1.getNaam() + " en " + speler2.getNaam() + "!"); System.out.println("We gaan beginnen!"); System.out.println(speler1.getNaam() + ", gooi een dobbelsteen (toets g) of pak een steen (p)"); while (true) { String gVoorGooien = scanner.nextLine(); if (gVoorGooien.equals("p")) { System.out.println("Welke steen wil je pakken?"); Integer steenPakken = scanner.nextInt(); speelbord.spelerEenSteenPakken(steenPakken); } if (gVoorGooien.equals("g")) { speler1.Dobbelen(); speler1.keuzeMaken(); System.out.println("Je gooit met " + speler1.aantalDobbelstenen() + " dobbelstenen."); System.out.println(speler1.getNaam() + " je hebt nu " + speler1.hoeveelheidPunten() + " punten."); System.out.println(speler1.getNaam() + " gooit nog een keer (toets g) of pak een steen (p)"); } else { System.out.println("toets g om de dobbelsteen te gooien"); } } } public void spelSpeler1(){ System.out.println(speler1.getNaam() + ", gooi een dobbelsteen (toets g) of pak een steen (p)"); while (true) { String gVoorGooien = scanner.nextLine(); if (gVoorGooien.equals("p")) { System.out.println("Welke steen wil je pakken?"); Integer steenPakken = scanner.nextInt(); speelbord.spelerEenSteenPakken(steenPakken); } if (gVoorGooien.equals("g")) { speler1.Dobbelen(); speler1.keuzeMaken(); System.out.println("Je gooit met " + speler1.aantalDobbelstenen() + " dobbelstenen."); System.out.println(speler1.getNaam() + " je hebt nu " + speler1.hoeveelheidPunten() + " punten."); System.out.println(speler1.getNaam() + " gooit nog een keer (toets g) of pak een steen (p)"); } else { System.out.println("toets g om de dobbelsteen te gooien"); } } } //=============== Oude Methodes ============== public int aantalSpelers(){ System.out.println("**** REGENWORMEN ****"); //System.out.println("Met hoeveel<SUF> //int aantalSpelers = scanner.nextInt(); int aantalSpelers = 2; spelersAanmelden(aantalSpelers); return aantalSpelers; } public void spelersAanmelden(int aantalSpelers){ if (aantalSpelers == 2){ System.out.println("2 spelers"); tweeSpelers(2); } else { System.out.println("Aantal spelers is minimaal 2 en maximaal 4 "); aantalSpelers(); } } }
68167_0
package com.company; import java.util.Scanner; public class YahtzeeSpel { Scanner scanner = new Scanner(System.in); Speler speler1 = new Speler("Sjaak"); Speler speler2 = new Speler("Piet"); public void spelen(){ System.out.println("****** WELKOM BIJ YAHTZEE ******"); System.out.println("Speler 1, wat is je naam? "); speler1.naam = scanner.nextLine(); System.out.println("Speler 2, wat is je naam? "); speler2.naam = scanner.nextLine(); speler1.spelen(); speler2.spelen(); System.out.println("worpen " + speler1.naam); speler1.worpenlijstSpeler(); System.out.println(); System.out.println("worpen " + speler2.naam); speler2.worpenlijstSpeler(); } /* public void spelen() { while (spel) { Worp worp = new Worp(); worp.setArrays(); System.out.println("Gooi de dobbelstenen met [ENTER] of verlaat Yathzee met [q]"); String invoer = scanner.nextLine(); if (invoer.equals("q")) { spel = false; } if (invoer.isEmpty()) { worp.getWorp(); worpAantal++; for (int i = 0; i < 3; i++) { System.out.println("Dit was worp: " + worpAantal); System.out.println("Wat wil je vasthouden? (toets [q] om het spel te verlaten)"); System.out.println("toets de nummers van de dobbelstenen die je wilt houden."); System.out.println("een dobbelsteen met x heb je al gekozen. Toets [ENTER] om een beurt over te slaan."); worp.vasthouden(); worp.flushArrays(); worp.printUitslag(); System.out.println("jouw gegooide dobbelstenen: "); worp.getVerzamelijst(); speler1.worpenlijstSpeler(); worp.getWorp(); worpAantal++; if (worpAantal == 3) { spel = false; } } worpAantal = 0; } } } */ }
CasparSteinebach/Yathzee
src/com/company/YahtzeeSpel.java
709
/* public void spelen() { while (spel) { Worp worp = new Worp(); worp.setArrays(); System.out.println("Gooi de dobbelstenen met [ENTER] of verlaat Yathzee met [q]"); String invoer = scanner.nextLine(); if (invoer.equals("q")) { spel = false; } if (invoer.isEmpty()) { worp.getWorp(); worpAantal++; for (int i = 0; i < 3; i++) { System.out.println("Dit was worp: " + worpAantal); System.out.println("Wat wil je vasthouden? (toets [q] om het spel te verlaten)"); System.out.println("toets de nummers van de dobbelstenen die je wilt houden."); System.out.println("een dobbelsteen met x heb je al gekozen. Toets [ENTER] om een beurt over te slaan."); worp.vasthouden(); worp.flushArrays(); worp.printUitslag(); System.out.println("jouw gegooide dobbelstenen: "); worp.getVerzamelijst(); speler1.worpenlijstSpeler(); worp.getWorp(); worpAantal++; if (worpAantal == 3) { spel = false; } } worpAantal = 0; } } } */
block_comment
nl
package com.company; import java.util.Scanner; public class YahtzeeSpel { Scanner scanner = new Scanner(System.in); Speler speler1 = new Speler("Sjaak"); Speler speler2 = new Speler("Piet"); public void spelen(){ System.out.println("****** WELKOM BIJ YAHTZEE ******"); System.out.println("Speler 1, wat is je naam? "); speler1.naam = scanner.nextLine(); System.out.println("Speler 2, wat is je naam? "); speler2.naam = scanner.nextLine(); speler1.spelen(); speler2.spelen(); System.out.println("worpen " + speler1.naam); speler1.worpenlijstSpeler(); System.out.println(); System.out.println("worpen " + speler2.naam); speler2.worpenlijstSpeler(); } /* public void spelen()<SUF>*/ }
97783_17
/** * Copyright (C) 2012 GridLine <[email protected]> * * 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 * */ package nl.gridline.model.upr; import java.util.Date; import java.util.NavigableMap; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import nl.gridline.zieook.api.Updatable; /** * Tracks what url's a user has visited in the UPR, specifically it tracks the URL's of collection items. * <p /> * Project upr-api<br /> * Visited.java created 7 dec. 2011 * <p /> * Copyright, all rights reserved 2011 GridLine Amsterdam * @author <a href="mailto:[email protected]">Job</a> * @version $Revision:$, $Date:$ */ @XmlRootElement(name = "visited") @XmlAccessorType(XmlAccessType.FIELD) public class Visit extends EventLog implements Updatable<Visit> { @XmlElement(name = "recommender") private String recommender; @XmlElement(name = "recommender-apikey") private String apikey; @XmlElement(name = "url") private String url; @XmlElement(name = "user_id") private Long userId; @XmlElement(name = "content_provider") private String cp; /** * */ private static final long serialVersionUID = 3593628095422562232L; public Visit() { } /** * @param cp * @param url * @param userId */ public Visit(String recommender, String url, String cp, Long userId) { this.userId = userId; this.cp = cp; this.recommender = recommender; this.url = url; } public Visit(String recommender, String url, String cp, Long userId, Date created, Date updated) { super(created, updated); this.userId = userId; this.cp = cp; this.recommender = recommender; this.url = url; } public Visit(NavigableMap<byte[], byte[]> map) { super(map); userId = ModelConstants.getUserId(map); url = ModelConstants.getUrl(map); recommender = ModelConstants.getRecommender(map); apikey = ModelConstants.getApiKey(map); cp = ModelConstants.getCp(map); } /* * (non-Javadoc) * * @see nl.gridline.model.upr.EventLog#toMap() */ @Override public NavigableMap<byte[], byte[]> toMap() { NavigableMap<byte[], byte[]> map = super.toMap(); return toMap(map); } /* * (non-Javadoc) * * @see nl.gridline.model.upr.EventLog#toMap(java.util.NavigableMap) */ @Override public NavigableMap<byte[], byte[]> toMap(NavigableMap<byte[], byte[]> map) { super.toMap(map); ModelConstants.putUserId(map, userId); ModelConstants.putUrl(map, url); ModelConstants.putRecommender(map, recommender); ModelConstants.putApiKey(map, apikey); ModelConstants.putCp(map, cp); return map; } /* * (non-Javadoc) * * @see nl.gridline.zieook.api.Updatable#update(java.lang.Object) */ @Override public Visit update(Visit updates) { if (updates == null) { return this; } super.update(updates); if (updates.apikey != null) { apikey = updates.apikey; } if (updates.url != null) { url = updates.url; } if (updates.recommender != null) { recommender = updates.recommender; } if (updates.userId != null) { userId = updates.userId; } if (updates.cp != null) { cp = updates.cp; } return this; } /** * @return The recommender. */ public String getRecommender() { return recommender; } /** * @param recommender The cp to set. */ public void setRecommender(String recommender) { this.recommender = recommender; } /** * @return The url. */ public String getUrl() { return url; } /** * @param url The url to set. */ public void setUrl(String url) { this.url = url; } /** * @return The userId. */ public Long getUserId() { return userId; } /** * @param userId The userId to set. */ public void setUserId(Long userId) { this.userId = userId; } /** * @return The apikey. */ public String getApikey() { return apikey; } /** * @param apikey The apikey to set. */ public void setApikey(String apikey) { this.apikey = apikey; } public String getCp() { return cp; } public void setCp(String cp) { this.cp = cp; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((apikey == null) ? 0 : apikey.hashCode()); result = prime * result + ((cp == null) ? 0 : cp.hashCode()); result = prime * result + ((recommender == null) ? 0 : recommender.hashCode()); result = prime * result + ((url == null) ? 0 : url.hashCode()); result = prime * result + ((userId == null) ? 0 : userId.hashCode()); return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } Visit other = (Visit) obj; if (apikey == null) { if (other.apikey != null) { return false; } } else if (!apikey.equals(other.apikey)) { return false; } if (cp == null) { if (other.cp != null) { return false; } } else if (!cp.equals(other.cp)) { return false; } if (recommender == null) { if (other.recommender != null) { return false; } } else if (!recommender.equals(other.recommender)) { return false; } if (url == null) { if (other.url != null) { return false; } } else if (!url.equals(other.url)) { return false; } if (userId == null) { if (other.userId != null) { return false; } } else if (!userId.equals(other.userId)) { return false; } return true; } // naam van instelling // URL waarop actie is uitgevoerd // Timestamp van actie }
CatchPlus/User-Profile-Repository
upr-api/src/main/java/nl/gridline/model/upr/Visit.java
2,436
// URL waarop actie is uitgevoerd
line_comment
nl
/** * Copyright (C) 2012 GridLine <[email protected]> * * 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 * */ package nl.gridline.model.upr; import java.util.Date; import java.util.NavigableMap; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import nl.gridline.zieook.api.Updatable; /** * Tracks what url's a user has visited in the UPR, specifically it tracks the URL's of collection items. * <p /> * Project upr-api<br /> * Visited.java created 7 dec. 2011 * <p /> * Copyright, all rights reserved 2011 GridLine Amsterdam * @author <a href="mailto:[email protected]">Job</a> * @version $Revision:$, $Date:$ */ @XmlRootElement(name = "visited") @XmlAccessorType(XmlAccessType.FIELD) public class Visit extends EventLog implements Updatable<Visit> { @XmlElement(name = "recommender") private String recommender; @XmlElement(name = "recommender-apikey") private String apikey; @XmlElement(name = "url") private String url; @XmlElement(name = "user_id") private Long userId; @XmlElement(name = "content_provider") private String cp; /** * */ private static final long serialVersionUID = 3593628095422562232L; public Visit() { } /** * @param cp * @param url * @param userId */ public Visit(String recommender, String url, String cp, Long userId) { this.userId = userId; this.cp = cp; this.recommender = recommender; this.url = url; } public Visit(String recommender, String url, String cp, Long userId, Date created, Date updated) { super(created, updated); this.userId = userId; this.cp = cp; this.recommender = recommender; this.url = url; } public Visit(NavigableMap<byte[], byte[]> map) { super(map); userId = ModelConstants.getUserId(map); url = ModelConstants.getUrl(map); recommender = ModelConstants.getRecommender(map); apikey = ModelConstants.getApiKey(map); cp = ModelConstants.getCp(map); } /* * (non-Javadoc) * * @see nl.gridline.model.upr.EventLog#toMap() */ @Override public NavigableMap<byte[], byte[]> toMap() { NavigableMap<byte[], byte[]> map = super.toMap(); return toMap(map); } /* * (non-Javadoc) * * @see nl.gridline.model.upr.EventLog#toMap(java.util.NavigableMap) */ @Override public NavigableMap<byte[], byte[]> toMap(NavigableMap<byte[], byte[]> map) { super.toMap(map); ModelConstants.putUserId(map, userId); ModelConstants.putUrl(map, url); ModelConstants.putRecommender(map, recommender); ModelConstants.putApiKey(map, apikey); ModelConstants.putCp(map, cp); return map; } /* * (non-Javadoc) * * @see nl.gridline.zieook.api.Updatable#update(java.lang.Object) */ @Override public Visit update(Visit updates) { if (updates == null) { return this; } super.update(updates); if (updates.apikey != null) { apikey = updates.apikey; } if (updates.url != null) { url = updates.url; } if (updates.recommender != null) { recommender = updates.recommender; } if (updates.userId != null) { userId = updates.userId; } if (updates.cp != null) { cp = updates.cp; } return this; } /** * @return The recommender. */ public String getRecommender() { return recommender; } /** * @param recommender The cp to set. */ public void setRecommender(String recommender) { this.recommender = recommender; } /** * @return The url. */ public String getUrl() { return url; } /** * @param url The url to set. */ public void setUrl(String url) { this.url = url; } /** * @return The userId. */ public Long getUserId() { return userId; } /** * @param userId The userId to set. */ public void setUserId(Long userId) { this.userId = userId; } /** * @return The apikey. */ public String getApikey() { return apikey; } /** * @param apikey The apikey to set. */ public void setApikey(String apikey) { this.apikey = apikey; } public String getCp() { return cp; } public void setCp(String cp) { this.cp = cp; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((apikey == null) ? 0 : apikey.hashCode()); result = prime * result + ((cp == null) ? 0 : cp.hashCode()); result = prime * result + ((recommender == null) ? 0 : recommender.hashCode()); result = prime * result + ((url == null) ? 0 : url.hashCode()); result = prime * result + ((userId == null) ? 0 : userId.hashCode()); return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } Visit other = (Visit) obj; if (apikey == null) { if (other.apikey != null) { return false; } } else if (!apikey.equals(other.apikey)) { return false; } if (cp == null) { if (other.cp != null) { return false; } } else if (!cp.equals(other.cp)) { return false; } if (recommender == null) { if (other.recommender != null) { return false; } } else if (!recommender.equals(other.recommender)) { return false; } if (url == null) { if (other.url != null) { return false; } } else if (!url.equals(other.url)) { return false; } if (userId == null) { if (other.userId != null) { return false; } } else if (!userId.equals(other.userId)) { return false; } return true; } // naam van instelling // URL waarop<SUF> // Timestamp van actie }
35170_0
package vocrep.controllers; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringReader; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.net.MalformedURLException; import java.net.URL; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPathExpressionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.ServletRequestBindingException; import org.springframework.web.bind.ServletRequestUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import vocrep.service.ICacheAPI; import vocrep.service.ICatchAPI; import vocrep.service.VocRepUtils; @SuppressWarnings("unused") @Controller public class SearchController{ @Autowired ServletContext servletContext; @Autowired ICatchAPI iCatchAPI; @Autowired ICacheAPI iCacheAPI; @Value(value="#{appProperties.pathtofilterschemes}") private String pathToFilterSchemes; @RequestMapping(value = "/search.do", method = RequestMethod.GET) public void search(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) throws TransformerFactoryConfigurationError, TransformerException, MalformedURLException, IOException, ServletRequestBindingException, ParserConfigurationException, SAXException, XPathExpressionException { String query = ServletRequestUtils.getStringParameter(request, "query"); String match = ServletRequestUtils.getStringParameter(request, "match"); if (match == null) match = ""; String label = ServletRequestUtils.getStringParameter(request, "label"); String lang = ServletRequestUtils.getStringParameter(request, "taal"); String group = ServletRequestUtils.getStringParameter(request, "group"); boolean loggedon = request.getSession().getAttribute("loggedon") == null ? false : (Boolean)request.getSession().getAttribute("loggedon"); Writer buffer = new StringWriter(); Document doc = null; File file = new File(servletContext.getRealPath("/WEB-INF/xsl/search.xslt")); Transformer transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(file)); URL searchUrl = null; if(query != null && match != null && label != null && lang != null && group != null) { searchUrl = getSeacrhConceptUrl(query, match, label, lang, group); transformer.setParameter("loggedon", loggedon); transformer.setParameter("lang", lang); transformer.setParameter("query", query); transformer.setParameter("match", match); transformer.setParameter("label", label); transformer.setParameter("group", group); } doc = BuildContent(searchUrl, loggedon); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1"); transformer.transform(new DOMSource(doc),new StreamResult(buffer)); response.setContentType("text/html"); response.getWriter().write(buffer.toString()); } // TODO: Je kan alleen zoeken met een regex wanneer ook een schema (in dit geval group) bekend is. // Dit moet of hier of op de frontend opgevangen worden en duidelijk worden gemaakt naar de gebruiker private URL getSeacrhConceptUrl(String query, String match, String label, String lang, String group) throws MalformedURLException, UnsupportedEncodingException { if(group.isEmpty()) return iCatchAPI.getFreeSearchUri(query, match, label, lang); else return iCatchAPI.getSearchConceptsUri(query, match, label, lang, group); } private Document BuildContent(URL uri, boolean isLoggedOn) throws IOException, SAXException, ParserConfigurationException, TransformerConfigurationException, TransformerException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); File filters = new File(pathToFilterSchemes+"filterschemes.xml"); StringBuffer buffer = new StringBuffer(); if(uri != null) buffer.append("<concepts>"+VocRepUtils.GetOuterXml(VocRepUtils.GetXMLDocumentForURI(uri).getDocumentElement())+"</concepts>"); // groupschema's willen we altijd hebben Document schemes = iCacheAPI.GetSchemeCache(); if(schemes == null) { schemes = getAllSchemes(); iCacheAPI.CacheDocument(schemes); } buffer.append(VocRepUtils.GetOuterXml(schemes)); //only apply filtering when not logged on if (filters.exists()) buffer = VocRepUtils.applySchemeFilters(filters, buffer); Document document = builder.parse(new InputSource(new StringReader("<search>"+ buffer.toString()+"</search>"))); return document; } private Document getAllSchemes() throws MalformedURLException, ParserConfigurationException, SAXException, IOException, TransformerConfigurationException, TransformerException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); StringBuffer buffer = new StringBuffer(); for(Node childNode = VocRepUtils.GetXMLDocumentForURI(iCatchAPI.getAllConceptschemeGroups()).getDocumentElement().getFirstChild(); childNode!=null;){ Node nextChild = childNode.getNextSibling(); //we slaan het eerste kindje over (statuscode) childNode = nextChild; //String uri = childNode.getFirstChild().getNodeValue(); String uri = getUriURL(VocRepUtils.GetOuterXml(childNode)); if(uri != "") { Document groupSchemes = VocRepUtils.GetXMLDocumentForURI(iCatchAPI.getAllConceptschemes(uri)); buffer.append("<group>"+VocRepUtils.GetOuterXml(childNode)+"<schemes>"+VocRepUtils.GetOuterXml(groupSchemes)+"</schemes></group>"); } } Document document = builder.parse(new InputSource(new StringReader("<groups>"+buffer.toString()+"</groups>"))); return document; } //TODO: Please refactor private String getUriURL(String node) { String[] buf = node.split("<uri>"); if(buf.length < 2) return ""; return buf[1].split("</uri>")[0]; } }
CatchPlus/VocabularyBrowser
src/main/java/vocrep/controllers/SearchController.java
2,146
// TODO: Je kan alleen zoeken met een regex wanneer ook een schema (in dit geval group) bekend is.
line_comment
nl
package vocrep.controllers; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringReader; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.net.MalformedURLException; import java.net.URL; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPathExpressionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.ServletRequestBindingException; import org.springframework.web.bind.ServletRequestUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import vocrep.service.ICacheAPI; import vocrep.service.ICatchAPI; import vocrep.service.VocRepUtils; @SuppressWarnings("unused") @Controller public class SearchController{ @Autowired ServletContext servletContext; @Autowired ICatchAPI iCatchAPI; @Autowired ICacheAPI iCacheAPI; @Value(value="#{appProperties.pathtofilterschemes}") private String pathToFilterSchemes; @RequestMapping(value = "/search.do", method = RequestMethod.GET) public void search(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) throws TransformerFactoryConfigurationError, TransformerException, MalformedURLException, IOException, ServletRequestBindingException, ParserConfigurationException, SAXException, XPathExpressionException { String query = ServletRequestUtils.getStringParameter(request, "query"); String match = ServletRequestUtils.getStringParameter(request, "match"); if (match == null) match = ""; String label = ServletRequestUtils.getStringParameter(request, "label"); String lang = ServletRequestUtils.getStringParameter(request, "taal"); String group = ServletRequestUtils.getStringParameter(request, "group"); boolean loggedon = request.getSession().getAttribute("loggedon") == null ? false : (Boolean)request.getSession().getAttribute("loggedon"); Writer buffer = new StringWriter(); Document doc = null; File file = new File(servletContext.getRealPath("/WEB-INF/xsl/search.xslt")); Transformer transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(file)); URL searchUrl = null; if(query != null && match != null && label != null && lang != null && group != null) { searchUrl = getSeacrhConceptUrl(query, match, label, lang, group); transformer.setParameter("loggedon", loggedon); transformer.setParameter("lang", lang); transformer.setParameter("query", query); transformer.setParameter("match", match); transformer.setParameter("label", label); transformer.setParameter("group", group); } doc = BuildContent(searchUrl, loggedon); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1"); transformer.transform(new DOMSource(doc),new StreamResult(buffer)); response.setContentType("text/html"); response.getWriter().write(buffer.toString()); } // TODO: Je<SUF> // Dit moet of hier of op de frontend opgevangen worden en duidelijk worden gemaakt naar de gebruiker private URL getSeacrhConceptUrl(String query, String match, String label, String lang, String group) throws MalformedURLException, UnsupportedEncodingException { if(group.isEmpty()) return iCatchAPI.getFreeSearchUri(query, match, label, lang); else return iCatchAPI.getSearchConceptsUri(query, match, label, lang, group); } private Document BuildContent(URL uri, boolean isLoggedOn) throws IOException, SAXException, ParserConfigurationException, TransformerConfigurationException, TransformerException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); File filters = new File(pathToFilterSchemes+"filterschemes.xml"); StringBuffer buffer = new StringBuffer(); if(uri != null) buffer.append("<concepts>"+VocRepUtils.GetOuterXml(VocRepUtils.GetXMLDocumentForURI(uri).getDocumentElement())+"</concepts>"); // groupschema's willen we altijd hebben Document schemes = iCacheAPI.GetSchemeCache(); if(schemes == null) { schemes = getAllSchemes(); iCacheAPI.CacheDocument(schemes); } buffer.append(VocRepUtils.GetOuterXml(schemes)); //only apply filtering when not logged on if (filters.exists()) buffer = VocRepUtils.applySchemeFilters(filters, buffer); Document document = builder.parse(new InputSource(new StringReader("<search>"+ buffer.toString()+"</search>"))); return document; } private Document getAllSchemes() throws MalformedURLException, ParserConfigurationException, SAXException, IOException, TransformerConfigurationException, TransformerException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); StringBuffer buffer = new StringBuffer(); for(Node childNode = VocRepUtils.GetXMLDocumentForURI(iCatchAPI.getAllConceptschemeGroups()).getDocumentElement().getFirstChild(); childNode!=null;){ Node nextChild = childNode.getNextSibling(); //we slaan het eerste kindje over (statuscode) childNode = nextChild; //String uri = childNode.getFirstChild().getNodeValue(); String uri = getUriURL(VocRepUtils.GetOuterXml(childNode)); if(uri != "") { Document groupSchemes = VocRepUtils.GetXMLDocumentForURI(iCatchAPI.getAllConceptschemes(uri)); buffer.append("<group>"+VocRepUtils.GetOuterXml(childNode)+"<schemes>"+VocRepUtils.GetOuterXml(groupSchemes)+"</schemes></group>"); } } Document document = builder.parse(new InputSource(new StringReader("<groups>"+buffer.toString()+"</groups>"))); return document; } //TODO: Please refactor private String getUriURL(String node) { String[] buf = node.split("<uri>"); if(buf.length < 2) return ""; return buf[1].split("</uri>")[0]; } }
100806_0
package easik.ui; import java.util.LinkedList; import java.util.List; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import easik.view.vertex.QueryNode; /** * * @author Sarah van der Laan * */ public class DefineQueryAddDialog extends OptionsDialog { private static final long serialVersionUID = 4044546505124282150L; /** The inputs for our fields */ private JScrollPane insertInto; /** The query no which we are editing */ private QueryNode ourNode; /** * * @param parent * @param title * @param inNode */ public DefineQueryAddDialog(JFrame parent, String title, QueryNode inNode) { super(parent, title); setSize(300, 200); ourNode = inNode; showDialog(); } /** * * * @return */ @Override public List<Option> getOptions() { LinkedList<Option> opts = new LinkedList<>(); // text???? opts.add(new Option(new JLabel("'Insert Into' Statement"), insertInto = JUtils.textArea(ourNode.getUpdate()))); return opts; } /** * * * @return */ public String getUpdate() { return JUtils.taText(insertInto); } }
CategoricalData/CQL
src/easik/ui/DefineQueryAddDialog.java
378
/** * * @author Sarah van der Laan * */
block_comment
nl
package easik.ui; import java.util.LinkedList; import java.util.List; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import easik.view.vertex.QueryNode; /** * * @author Sarah van<SUF>*/ public class DefineQueryAddDialog extends OptionsDialog { private static final long serialVersionUID = 4044546505124282150L; /** The inputs for our fields */ private JScrollPane insertInto; /** The query no which we are editing */ private QueryNode ourNode; /** * * @param parent * @param title * @param inNode */ public DefineQueryAddDialog(JFrame parent, String title, QueryNode inNode) { super(parent, title); setSize(300, 200); ourNode = inNode; showDialog(); } /** * * * @return */ @Override public List<Option> getOptions() { LinkedList<Option> opts = new LinkedList<>(); // text???? opts.add(new Option(new JLabel("'Insert Into' Statement"), insertInto = JUtils.textArea(ourNode.getUpdate()))); return opts; } /** * * * @return */ public String getUpdate() { return JUtils.taText(insertInto); } }
211039_1
package servlets; import java.io.IOException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; import com.spoledge.audao.db.dao.DaoException; import database.DataSourceConnector; import database.dao.BrugerDao; import database.dao.DaoFactory; import database.dao.ModalitetDao; import database.dao.PETCTKontrolskemaDao; import database.dao.RekvisitionDao; import database.dao.mysql.BrugerDaoImpl; import database.dao.mysql.BrugerDaoImplExtended; import database.dao.mysql.ModalitetDaoImpl; import database.dao.mysql.PETCTKontrolskemaDaoImpl; import database.dao.mysql.RekvisitionDaoImpl; import database.dto.Bruger; import database.dto.CtKontrastKontrolskema; import database.dto.Modalitet; import database.dto.PETCTKontrolskema; import database.dto.PETCTKontrolskema.Formaal; import database.dto.PETCTKontrolskema.KemoOgStraale; import database.dto.RekvisitionExtended; import database.dto.RekvisitionExtended.AmbulantKoersel; import database.dto.RekvisitionExtended.HenvistTil; import database.dto.RekvisitionExtended.HospitalOenske; import database.dto.RekvisitionExtended.IndlaeggelseTransport; import database.dto.RekvisitionExtended.Prioritering; import database.dto.RekvisitionExtended.Samtykke; import database.dto.RekvisitionExtended.Status; import database.interfaces.IDataSourceConnector.ConnectionException; //import dto.DTOexRequest; //import dto.DTOexRequest.Status; /**@author Rúni * Servlet implementation class TestServlet */ @WebServlet("/TestServlet") public class TestServlet extends HttpServlet { private static final long serialVersionUID = 1L; private DataSource dataSource; /** * @see HttpServlet#HttpServlet() */ public TestServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Statement statement = null; ResultSet resultSet = null; Connection connection = null; // Get Connection and Statement try { connection = DataSourceConnector.getConnection(); statement = connection.createStatement(); } catch (SQLException e){ e.printStackTrace(); }catch (ConnectionException e1) { e1.printStackTrace(); } // testUser(statement, connection); // testMrKontrol(statement, connection); // testExRequest(connection); System.out.println("##########tester bruger dto#############"); testBruger(connection); System.out.println("\n \n#############tester petCtKontrolskema#########"); testPetCtKontrolskema(connection); System.out.println("\n \n#############test exrequest###################"); testExRequest(connection); System.out.println("\n \n#############test modalitet###################"); testModalitet(connection); System.out.println("\n \n#############test mrKontrol###################"); testMrKontrol(statement, connection); System.out.println("\n \n#############test rettigheder#################"); testRettigheder(connection); System.out.println("\n \n############# test adv search#################"); testAdvSearch(connection); // testBrugerValidering(connection); } private void testAdvSearch(Connection connection) { RekvisitionExtended[] r = null; RekvisitionDaoImpl dao = new RekvisitionDaoImpl(connection); // test: "Røntgen" r = dao.findByAdvSearch(null, null, null, null, null, null, null); System.out.println("################ adv search########################"); System.out.println("arrayStørrelse: " + r.length); for (RekvisitionExtended rekvisition : r) { System.out.println(rekvisition.getRekvisitionId()); } System.out.println(r.length + " funde rekvisitioner###################"); System.out.println("############### dynamic search####################"); RekvisitionExtended[] rek = dao.findDynamic("status=?", 0, -1, new Object[]{Status.PENDING}); for (RekvisitionExtended rekvisition : rek) { System.out.println("id: " + rekvisition.getRekvisitionId()); System.out.println("status: " + rekvisition.getStatus()); } } private void testPetCtKontrolskema(Connection conn){ //kan være null Boolean setDMRegime= null; Boolean setPOKontrast= null; Boolean setPreMed= null; //kan ikke være null Boolean setDiabetes= true; Boolean setKanPtLiggeStille30= true; Boolean setKlaustrofobi= false; Boolean setNedsatNyreFkt= true; Boolean setOperation= false; Boolean setBiopsi= true; Boolean setAllergi= false; Boolean setFedme= true; Boolean setIVKontrast= false; Boolean setPtTaalerFaste= false; Boolean setRelKontraIndCT= true; Boolean setRespInsuff= false; Boolean setSmerter= true; String setAktuelPKreatAndetText = "det ser ikke så godt ud"; String setAllergiText= null; String setBiopsiText= null; String setDatoForslag= null; String setDMBeh= null; String setFormaalAndetText= null; String setFormaalBehandlingsktrlText= null; String setFormaalRecidivText= null; String setOperationText= null; String setRelKontraIndCTText= null; String setTidlBilledDiagnostik= null; Integer setAktuelPKreatinin= null; Integer setPetctKontrolskemaId= null; Integer setSidstePKreatinin= null; Integer setVaegt= null; Date setAktuelPKreatTimestamp= null; Date setSidstePKreatTimestamp= null; Formaal setFormaal= null; KemoOgStraale setKemoOgStraale= null; PETCTKontrolskema dto = new PETCTKontrolskema(); PETCTKontrolskemaDao dao = new PETCTKontrolskemaDaoImpl(conn); dto.setAktuelAndetTekst(setAktuelPKreatAndetText); dto.setAktuelPKreatinin(setAktuelPKreatinin); dto.setAktuelPKreatTimestamp(setAktuelPKreatTimestamp); dto.setAllergi(setAllergi); dto.setAllergiTekst(setAllergiText); dto.setBiopsi(setBiopsi); dto.setBiopsiTekst(setBiopsiText); dto.setDiabetes(setDiabetes); dto.setDMBeh(setDMBeh); dto.setDMRegime(setDMRegime); dto.setFedme(setFedme); dto.setFormaal(setFormaal); dto.setFormaalTekst(setFormaalAndetText); dto.setIVKontrast(setIVKontrast); dto.setKanPtLiggeStille30(setKanPtLiggeStille30); dto.setKemoOgStraale(setKemoOgStraale); dto.setKlaustrofobi(setKlaustrofobi); dto.setNedsatNyreFkt(setNedsatNyreFkt); dto.setOperation(setOperation); dto.setOperationTekst(setOperationText); dto.setPETCTKontrolskemaId(setPetctKontrolskemaId); dto.setPOKontrast(setPOKontrast); dto.setPreMed(setPreMed); dto.setPtTaalerFaste(setPtTaalerFaste); dto.setRespInsuff(setRespInsuff); dto.setSidstePKreatinin(setSidstePKreatinin); dto.setSidstePKreatTimestamp(setSidstePKreatTimestamp); dto.setSmerter(setSmerter); dto.setVaegt(setVaegt); int pk = 0; try { System.out.println("indsætter petctkontrol dto i database"); pk = dao.insert(dto); System.out.println("###########dto indsat med#######"); System.out.println("pk: " + pk); } catch (DaoException e) { System.err.println("petCtKontrol dto blev ikke succesfuldt sat ind i database \n"); System.err.println(e.getMessage()); System.out.println("\n ########################################"); } System.out.println("henter petctkontrolskema med pk: " + pk); PETCTKontrolskema fdto = dao.findByPrimaryKey(pk); System.out.println("fdto " + fdto); System.out.println("pk: " + (fdto == null ? "no dto found" : fdto.getPETCTKontrolskemaId())); System.out.println("aktuelpkreatinandettekst: " + (fdto == null ? "no dto found" : fdto.getAktuelPKreatinin())); System.out.println("########################################"); System.out.println("henter ikke eksisterende objekt... pk: " + pk + 1000); fdto = dao.findByPrimaryKey(pk+1000); try{ System.out.println("aktuelpkreatinandettekst: " + fdto.getAktuelPKreatinin()); } catch (NullPointerException e){ System.out.println("nullPointerException kastet - objektet er null"); } } private void testMrKontrol(Statement statement, Connection connection) { CtKontrastKontrolskema m = new CtKontrastKontrolskema(); m.setAllergi(true); m.setAminoglykosider(false); m.setAstma(true); m.setBetaBlokkere(false); m.setCtKontrastKontrolskemaId(-1); m.setDiabetes(null); m.setHjertesygdom(false); m.setHypertension(true); m.setHyperthyreoidisme(false); m.setInterleukin2(true); m.setKontraststofreaktion(false); m.setMetformin(null); m.setMyokardieinfarkt(false); m.setNsaidPraeparat(true); // m.setNyrefunktion(_val); m.setNyreopereret(false); m.setOver70(true); m.setPKreatininTimestamp(new Date()); m.setPKreatininVaerdi("meget h�j"); m.setProteinuri(true); m.setPtHoejde(198); m.setPtVaegt(32); m.setUrinsyregigt(true); } private void testBruger(Connection conn){ int id = 2; String brugernavn = "mumming"; String fuldtnavn = "Martin Nielsen"; String kodeord = "1234"; boolean erAktiv = true; Bruger dto = new Bruger(); //dto.setBrugerId(id); dto.setBrugerNavn(brugernavn); dto.setErAktiv(erAktiv); dto.setFuldtNavn(fuldtnavn); dto.setKodeord(kodeord); BrugerDao dao = DaoFactory.createBrugerDao(conn); try { System.out.println("\n forsøger at inds�tte bruger i database"); System.out.println("#######bruger til inds�tning#####"); System.out.println("brugerId: " + id); System.out.println("brugernavn: " + brugernavn); System.out.println("erAktiv: " + erAktiv); System.out.println("################"); Bruger alreadyExist = dao.findByPrimaryKey(id); if(alreadyExist != null){ System.out.println("bruger findes allerede med id= " + id); System.out.println("#########fundet bruger###########"); System.out.println("brugerid: " + alreadyExist.getBrugerId()); System.out.println("brugernavn: " + alreadyExist.getBrugerNavn()); System.out.println("erAktiv: " + alreadyExist.getErAktiv()); System.out.println("#################################"); System.out.println("brugerid på givne dto ignoreres, og bliver automatisk sat i database"); } int pk = dao.insert(dto); System.out.println("bruger tilføjet database"); System.out.println("####tilføjet bruger#########"); System.out.println("brugerId: " + pk); } catch (DaoException e) { System.err.println("fejlede at tilføje bruger til database"); System.err.println(e.getMessage()); } try { System.out.println("\n forsøger at hente bruger fra database"); System.out.println("#######user#####"); System.out.println("brugerId: " + id); Bruger nDto = dao.findByPrimaryKey(id); System.out.println("#####fundet bruger#######"); System.out.println("brugerId: " + nDto.getBrugerId()); System.out.println("brugernavn: " + nDto.getBrugerNavn()); System.out.println("erAktiv: " + nDto.getErAktiv()); } catch (Exception e) { System.err.println("fejlede at hente bruger fra database"); } try { System.out.println("#######findByUserName#####"); BrugerDaoImplExtended bdie = null; bdie = new BrugerDaoImplExtended(conn); Bruger b = bdie.findByUserName(brugernavn, kodeord); System.out.println(b.getBrugerNavn()); System.out.println("################"); } catch(Exception e){ System.out.println("Fejlede i at finde bruger efter brugernavn"); } erAktiv = !erAktiv; try{ System.out.println("\n forsøger at opdatere erAktiv for bruger i database"); System.out.println("######opdatering til bruger######"); System.out.println("userid: " + id); System.out.println("isActive: " + erAktiv); System.out.println("################"); dto.setErAktiv(erAktiv); dao.update(id, dto); System.out.println("bruger opdateret"); }catch (DaoException e){ System.err.println("fejlede at opdatere bruger i database"); System.err.println(e.getMessage()); } } private void testBrugerValidering(Connection conn){ String brugernavn = "mumming"; String kodeord = "1234"; BrugerDao brugerDao = null; brugerDao = new BrugerDaoImpl(conn); System.out.println("######VALIDERING AF BRUGER######"); // if(brugerDao.validate(brugernavn, kodeord)){ System.out.println("User was validated."); // } else{ System.out.println("User was NOT validated."); // } System.out.println("################"); } private void testBrugerInput(String message, Bruger dto, BrugerDao dao, int id, String brugernavn, boolean erAktiv){ } private void testExRequest(Connection conn){ Integer primaryKey = new Integer(2); // DTOexRequest dtod = new DTOexRequest(-1, 2, 1, 0, Status.PENDING, new Timestamp(new Date().getTime()), null, new Timestamp(new Date(0).getTime()), null); // DaoFactory f = new DaoFactory(); System.err.println("trying to get dao \n"); RekvisitionDao dao = DaoFactory.createRekvisitionDao(conn); System.err.println("dao aquired"); RekvisitionExtended dto = new RekvisitionExtended(); dto.setAmbulant(true); dto.setAmbulantKoersel(AmbulantKoersel.LIGGENDE); dto.setCave("utrolig farligt alts�"); dto.setDatoForslag("198-123-1"); dto.setGraviditet(true); dto.setHenvistTil(HenvistTil.RADIOLOGISK); dto.setHospitalOenske(HospitalOenske.FREDERIKSSUND); dto.setIndlaeggelseTransport(IndlaeggelseTransport.GAA_MED_PORTOER); dto.setPrioritering(Prioritering.PAKKEFORLOEB); dto.setRekvisitionId(primaryKey); // primary key dto.setSamtykke(Samtykke.JA); dto.setStatus(Status.APPROVED); dto.setUdfIndlagt(false); dto.setUndersoegelsesTypeId(2); try { // test insert System.out.println("insert dto: pr-key: " + dto.getRekvisitionId() + "..."); dao.insert(dto); System.out.println("dto inserted"); // test findByPrimary key by searching for previous inserted object System.out.println("searching for inserted dto pr-key: " + dto.getRekvisitionId() + "..."); RekvisitionExtended r = dao.findByPrimaryKey(dto.getRekvisitionId()); System.out.println("objects primary key: " + r.getRekvisitionId()); //test update of status System.out.println("updating status..."); System.out.println("current status: " + dto.getStatus().toString() + " vs " + r.getStatus() ); dto.setStatus(Status.CANCELED); boolean success = dao.update(dto.getRekvisitionId(), dto); System.out.println("update was a success: " + success); r = dao.findByPrimaryKey(primaryKey); System.out.println("new status vs old: " + r.getStatus() + " vs " + dto.getStatus()); } catch (DaoException e) { System.err.println("failed to insert row"); System.err.println(e.getMessage()); } } private void testModalitet(Connection conn){ Modalitet dto = new Modalitet(); dto.setModalitetNavn("test modalitet"); ModalitetDao dao = new ModalitetDaoImpl(conn); try { System.out.println("indsætter Modalitetdto ind i database..."); System.out.println("#######Modalitet##########"); System.out.println("modalitetnavn: " + dto.getModalitetNavn()); System.out.println("##########################"); int id = dao.insert(dto); System.out.println("dto indsat med id: " + id); } catch (DaoException e) { System.err.println("Failed to insert dto into database"); System.err.println(e.getMessage()); } } private void testRettigheder(Connection conn){ } // private void testUser(Statement statement, Connection connection) { // ResultSet resultSet = null; // try { // String query = "SELECT * FROM users"; // resultSet = statement.executeQuery(query); // while (resultSet.next()) { // System.out.println(resultSet.getString(1) + resultSet.getString(2) + resultSet.getString(3)); // } // } catch (SQLException e) { // e.printStackTrace(); // }finally { // try { if(null!=resultSet)resultSet.close();} catch (SQLException e) // {e.printStackTrace();} // try { if(null!=statement)statement.close();} catch (SQLException e) // {e.printStackTrace();} // try { if(null!=connection)connection.close();} catch (SQLException e) // {e.printStackTrace();} // } // } }
Catpaw42/Area51_E2014
Xray/src/servlets/TestServlet.java
6,228
/** * @see HttpServlet#HttpServlet() */
block_comment
nl
package servlets; import java.io.IOException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; import com.spoledge.audao.db.dao.DaoException; import database.DataSourceConnector; import database.dao.BrugerDao; import database.dao.DaoFactory; import database.dao.ModalitetDao; import database.dao.PETCTKontrolskemaDao; import database.dao.RekvisitionDao; import database.dao.mysql.BrugerDaoImpl; import database.dao.mysql.BrugerDaoImplExtended; import database.dao.mysql.ModalitetDaoImpl; import database.dao.mysql.PETCTKontrolskemaDaoImpl; import database.dao.mysql.RekvisitionDaoImpl; import database.dto.Bruger; import database.dto.CtKontrastKontrolskema; import database.dto.Modalitet; import database.dto.PETCTKontrolskema; import database.dto.PETCTKontrolskema.Formaal; import database.dto.PETCTKontrolskema.KemoOgStraale; import database.dto.RekvisitionExtended; import database.dto.RekvisitionExtended.AmbulantKoersel; import database.dto.RekvisitionExtended.HenvistTil; import database.dto.RekvisitionExtended.HospitalOenske; import database.dto.RekvisitionExtended.IndlaeggelseTransport; import database.dto.RekvisitionExtended.Prioritering; import database.dto.RekvisitionExtended.Samtykke; import database.dto.RekvisitionExtended.Status; import database.interfaces.IDataSourceConnector.ConnectionException; //import dto.DTOexRequest; //import dto.DTOexRequest.Status; /**@author Rúni * Servlet implementation class TestServlet */ @WebServlet("/TestServlet") public class TestServlet extends HttpServlet { private static final long serialVersionUID = 1L; private DataSource dataSource; /** * @see HttpServlet#HttpServlet() <SUF>*/ public TestServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Statement statement = null; ResultSet resultSet = null; Connection connection = null; // Get Connection and Statement try { connection = DataSourceConnector.getConnection(); statement = connection.createStatement(); } catch (SQLException e){ e.printStackTrace(); }catch (ConnectionException e1) { e1.printStackTrace(); } // testUser(statement, connection); // testMrKontrol(statement, connection); // testExRequest(connection); System.out.println("##########tester bruger dto#############"); testBruger(connection); System.out.println("\n \n#############tester petCtKontrolskema#########"); testPetCtKontrolskema(connection); System.out.println("\n \n#############test exrequest###################"); testExRequest(connection); System.out.println("\n \n#############test modalitet###################"); testModalitet(connection); System.out.println("\n \n#############test mrKontrol###################"); testMrKontrol(statement, connection); System.out.println("\n \n#############test rettigheder#################"); testRettigheder(connection); System.out.println("\n \n############# test adv search#################"); testAdvSearch(connection); // testBrugerValidering(connection); } private void testAdvSearch(Connection connection) { RekvisitionExtended[] r = null; RekvisitionDaoImpl dao = new RekvisitionDaoImpl(connection); // test: "Røntgen" r = dao.findByAdvSearch(null, null, null, null, null, null, null); System.out.println("################ adv search########################"); System.out.println("arrayStørrelse: " + r.length); for (RekvisitionExtended rekvisition : r) { System.out.println(rekvisition.getRekvisitionId()); } System.out.println(r.length + " funde rekvisitioner###################"); System.out.println("############### dynamic search####################"); RekvisitionExtended[] rek = dao.findDynamic("status=?", 0, -1, new Object[]{Status.PENDING}); for (RekvisitionExtended rekvisition : rek) { System.out.println("id: " + rekvisition.getRekvisitionId()); System.out.println("status: " + rekvisition.getStatus()); } } private void testPetCtKontrolskema(Connection conn){ //kan være null Boolean setDMRegime= null; Boolean setPOKontrast= null; Boolean setPreMed= null; //kan ikke være null Boolean setDiabetes= true; Boolean setKanPtLiggeStille30= true; Boolean setKlaustrofobi= false; Boolean setNedsatNyreFkt= true; Boolean setOperation= false; Boolean setBiopsi= true; Boolean setAllergi= false; Boolean setFedme= true; Boolean setIVKontrast= false; Boolean setPtTaalerFaste= false; Boolean setRelKontraIndCT= true; Boolean setRespInsuff= false; Boolean setSmerter= true; String setAktuelPKreatAndetText = "det ser ikke så godt ud"; String setAllergiText= null; String setBiopsiText= null; String setDatoForslag= null; String setDMBeh= null; String setFormaalAndetText= null; String setFormaalBehandlingsktrlText= null; String setFormaalRecidivText= null; String setOperationText= null; String setRelKontraIndCTText= null; String setTidlBilledDiagnostik= null; Integer setAktuelPKreatinin= null; Integer setPetctKontrolskemaId= null; Integer setSidstePKreatinin= null; Integer setVaegt= null; Date setAktuelPKreatTimestamp= null; Date setSidstePKreatTimestamp= null; Formaal setFormaal= null; KemoOgStraale setKemoOgStraale= null; PETCTKontrolskema dto = new PETCTKontrolskema(); PETCTKontrolskemaDao dao = new PETCTKontrolskemaDaoImpl(conn); dto.setAktuelAndetTekst(setAktuelPKreatAndetText); dto.setAktuelPKreatinin(setAktuelPKreatinin); dto.setAktuelPKreatTimestamp(setAktuelPKreatTimestamp); dto.setAllergi(setAllergi); dto.setAllergiTekst(setAllergiText); dto.setBiopsi(setBiopsi); dto.setBiopsiTekst(setBiopsiText); dto.setDiabetes(setDiabetes); dto.setDMBeh(setDMBeh); dto.setDMRegime(setDMRegime); dto.setFedme(setFedme); dto.setFormaal(setFormaal); dto.setFormaalTekst(setFormaalAndetText); dto.setIVKontrast(setIVKontrast); dto.setKanPtLiggeStille30(setKanPtLiggeStille30); dto.setKemoOgStraale(setKemoOgStraale); dto.setKlaustrofobi(setKlaustrofobi); dto.setNedsatNyreFkt(setNedsatNyreFkt); dto.setOperation(setOperation); dto.setOperationTekst(setOperationText); dto.setPETCTKontrolskemaId(setPetctKontrolskemaId); dto.setPOKontrast(setPOKontrast); dto.setPreMed(setPreMed); dto.setPtTaalerFaste(setPtTaalerFaste); dto.setRespInsuff(setRespInsuff); dto.setSidstePKreatinin(setSidstePKreatinin); dto.setSidstePKreatTimestamp(setSidstePKreatTimestamp); dto.setSmerter(setSmerter); dto.setVaegt(setVaegt); int pk = 0; try { System.out.println("indsætter petctkontrol dto i database"); pk = dao.insert(dto); System.out.println("###########dto indsat med#######"); System.out.println("pk: " + pk); } catch (DaoException e) { System.err.println("petCtKontrol dto blev ikke succesfuldt sat ind i database \n"); System.err.println(e.getMessage()); System.out.println("\n ########################################"); } System.out.println("henter petctkontrolskema med pk: " + pk); PETCTKontrolskema fdto = dao.findByPrimaryKey(pk); System.out.println("fdto " + fdto); System.out.println("pk: " + (fdto == null ? "no dto found" : fdto.getPETCTKontrolskemaId())); System.out.println("aktuelpkreatinandettekst: " + (fdto == null ? "no dto found" : fdto.getAktuelPKreatinin())); System.out.println("########################################"); System.out.println("henter ikke eksisterende objekt... pk: " + pk + 1000); fdto = dao.findByPrimaryKey(pk+1000); try{ System.out.println("aktuelpkreatinandettekst: " + fdto.getAktuelPKreatinin()); } catch (NullPointerException e){ System.out.println("nullPointerException kastet - objektet er null"); } } private void testMrKontrol(Statement statement, Connection connection) { CtKontrastKontrolskema m = new CtKontrastKontrolskema(); m.setAllergi(true); m.setAminoglykosider(false); m.setAstma(true); m.setBetaBlokkere(false); m.setCtKontrastKontrolskemaId(-1); m.setDiabetes(null); m.setHjertesygdom(false); m.setHypertension(true); m.setHyperthyreoidisme(false); m.setInterleukin2(true); m.setKontraststofreaktion(false); m.setMetformin(null); m.setMyokardieinfarkt(false); m.setNsaidPraeparat(true); // m.setNyrefunktion(_val); m.setNyreopereret(false); m.setOver70(true); m.setPKreatininTimestamp(new Date()); m.setPKreatininVaerdi("meget h�j"); m.setProteinuri(true); m.setPtHoejde(198); m.setPtVaegt(32); m.setUrinsyregigt(true); } private void testBruger(Connection conn){ int id = 2; String brugernavn = "mumming"; String fuldtnavn = "Martin Nielsen"; String kodeord = "1234"; boolean erAktiv = true; Bruger dto = new Bruger(); //dto.setBrugerId(id); dto.setBrugerNavn(brugernavn); dto.setErAktiv(erAktiv); dto.setFuldtNavn(fuldtnavn); dto.setKodeord(kodeord); BrugerDao dao = DaoFactory.createBrugerDao(conn); try { System.out.println("\n forsøger at inds�tte bruger i database"); System.out.println("#######bruger til inds�tning#####"); System.out.println("brugerId: " + id); System.out.println("brugernavn: " + brugernavn); System.out.println("erAktiv: " + erAktiv); System.out.println("################"); Bruger alreadyExist = dao.findByPrimaryKey(id); if(alreadyExist != null){ System.out.println("bruger findes allerede med id= " + id); System.out.println("#########fundet bruger###########"); System.out.println("brugerid: " + alreadyExist.getBrugerId()); System.out.println("brugernavn: " + alreadyExist.getBrugerNavn()); System.out.println("erAktiv: " + alreadyExist.getErAktiv()); System.out.println("#################################"); System.out.println("brugerid på givne dto ignoreres, og bliver automatisk sat i database"); } int pk = dao.insert(dto); System.out.println("bruger tilføjet database"); System.out.println("####tilføjet bruger#########"); System.out.println("brugerId: " + pk); } catch (DaoException e) { System.err.println("fejlede at tilføje bruger til database"); System.err.println(e.getMessage()); } try { System.out.println("\n forsøger at hente bruger fra database"); System.out.println("#######user#####"); System.out.println("brugerId: " + id); Bruger nDto = dao.findByPrimaryKey(id); System.out.println("#####fundet bruger#######"); System.out.println("brugerId: " + nDto.getBrugerId()); System.out.println("brugernavn: " + nDto.getBrugerNavn()); System.out.println("erAktiv: " + nDto.getErAktiv()); } catch (Exception e) { System.err.println("fejlede at hente bruger fra database"); } try { System.out.println("#######findByUserName#####"); BrugerDaoImplExtended bdie = null; bdie = new BrugerDaoImplExtended(conn); Bruger b = bdie.findByUserName(brugernavn, kodeord); System.out.println(b.getBrugerNavn()); System.out.println("################"); } catch(Exception e){ System.out.println("Fejlede i at finde bruger efter brugernavn"); } erAktiv = !erAktiv; try{ System.out.println("\n forsøger at opdatere erAktiv for bruger i database"); System.out.println("######opdatering til bruger######"); System.out.println("userid: " + id); System.out.println("isActive: " + erAktiv); System.out.println("################"); dto.setErAktiv(erAktiv); dao.update(id, dto); System.out.println("bruger opdateret"); }catch (DaoException e){ System.err.println("fejlede at opdatere bruger i database"); System.err.println(e.getMessage()); } } private void testBrugerValidering(Connection conn){ String brugernavn = "mumming"; String kodeord = "1234"; BrugerDao brugerDao = null; brugerDao = new BrugerDaoImpl(conn); System.out.println("######VALIDERING AF BRUGER######"); // if(brugerDao.validate(brugernavn, kodeord)){ System.out.println("User was validated."); // } else{ System.out.println("User was NOT validated."); // } System.out.println("################"); } private void testBrugerInput(String message, Bruger dto, BrugerDao dao, int id, String brugernavn, boolean erAktiv){ } private void testExRequest(Connection conn){ Integer primaryKey = new Integer(2); // DTOexRequest dtod = new DTOexRequest(-1, 2, 1, 0, Status.PENDING, new Timestamp(new Date().getTime()), null, new Timestamp(new Date(0).getTime()), null); // DaoFactory f = new DaoFactory(); System.err.println("trying to get dao \n"); RekvisitionDao dao = DaoFactory.createRekvisitionDao(conn); System.err.println("dao aquired"); RekvisitionExtended dto = new RekvisitionExtended(); dto.setAmbulant(true); dto.setAmbulantKoersel(AmbulantKoersel.LIGGENDE); dto.setCave("utrolig farligt alts�"); dto.setDatoForslag("198-123-1"); dto.setGraviditet(true); dto.setHenvistTil(HenvistTil.RADIOLOGISK); dto.setHospitalOenske(HospitalOenske.FREDERIKSSUND); dto.setIndlaeggelseTransport(IndlaeggelseTransport.GAA_MED_PORTOER); dto.setPrioritering(Prioritering.PAKKEFORLOEB); dto.setRekvisitionId(primaryKey); // primary key dto.setSamtykke(Samtykke.JA); dto.setStatus(Status.APPROVED); dto.setUdfIndlagt(false); dto.setUndersoegelsesTypeId(2); try { // test insert System.out.println("insert dto: pr-key: " + dto.getRekvisitionId() + "..."); dao.insert(dto); System.out.println("dto inserted"); // test findByPrimary key by searching for previous inserted object System.out.println("searching for inserted dto pr-key: " + dto.getRekvisitionId() + "..."); RekvisitionExtended r = dao.findByPrimaryKey(dto.getRekvisitionId()); System.out.println("objects primary key: " + r.getRekvisitionId()); //test update of status System.out.println("updating status..."); System.out.println("current status: " + dto.getStatus().toString() + " vs " + r.getStatus() ); dto.setStatus(Status.CANCELED); boolean success = dao.update(dto.getRekvisitionId(), dto); System.out.println("update was a success: " + success); r = dao.findByPrimaryKey(primaryKey); System.out.println("new status vs old: " + r.getStatus() + " vs " + dto.getStatus()); } catch (DaoException e) { System.err.println("failed to insert row"); System.err.println(e.getMessage()); } } private void testModalitet(Connection conn){ Modalitet dto = new Modalitet(); dto.setModalitetNavn("test modalitet"); ModalitetDao dao = new ModalitetDaoImpl(conn); try { System.out.println("indsætter Modalitetdto ind i database..."); System.out.println("#######Modalitet##########"); System.out.println("modalitetnavn: " + dto.getModalitetNavn()); System.out.println("##########################"); int id = dao.insert(dto); System.out.println("dto indsat med id: " + id); } catch (DaoException e) { System.err.println("Failed to insert dto into database"); System.err.println(e.getMessage()); } } private void testRettigheder(Connection conn){ } // private void testUser(Statement statement, Connection connection) { // ResultSet resultSet = null; // try { // String query = "SELECT * FROM users"; // resultSet = statement.executeQuery(query); // while (resultSet.next()) { // System.out.println(resultSet.getString(1) + resultSet.getString(2) + resultSet.getString(3)); // } // } catch (SQLException e) { // e.printStackTrace(); // }finally { // try { if(null!=resultSet)resultSet.close();} catch (SQLException e) // {e.printStackTrace();} // try { if(null!=statement)statement.close();} catch (SQLException e) // {e.printStackTrace();} // try { if(null!=connection)connection.close();} catch (SQLException e) // {e.printStackTrace();} // } // } }
85746_21
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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. ******************************************************************************/ //this class is based on and contains source code from on libgdx scene2d Actor.class package org.catrobat.catroid.libgdx3dwrapper.scene; import android.support.annotation.IntDef; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Quaternion; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.physics.bullet.dynamics.btRigidBody; import com.badlogic.gdx.physics.bullet.linearmath.btMotionState; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.DelayedRemovalArray; import com.badlogic.gdx.utils.Disposable; import org.catrobat.catroid.libgdx3dwrapper.actions.Action3d; import org.catrobat.catroid.libgdx3dwrapper.actions.Event3d; import org.catrobat.catroid.physics.Entity; import org.catrobat.catroid.physics.EventListener3d; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import static com.badlogic.gdx.math.Matrix4.M03; import static com.badlogic.gdx.math.Matrix4.M13; import static com.badlogic.gdx.math.Matrix4.M23; public class Actor3d { public ModelInstance modelInstance; public btRigidBody body; protected Entity.MotionState motionState; protected Matrix4 transform; protected final Array<Action3d> actions = new Array(0); private boolean visible; private final Vector3 motionImpulse = new Vector3(); private final Vector3 motionAngularImpulse = new Vector3(); private final Vector3 motionPositionBuffer = new Vector3(); private final Quaternion rotationQuaternion = new Quaternion(); private final DelayedRemovalArray<EventListener3d> listeners = new DelayedRemovalArray(0); private final DelayedRemovalArray<EventListener3d> captureListeners = new DelayedRemovalArray(0); //private Group parent; private float rotation = 0f; public Actor3d() { } public Actor3d(Entity.MotionState motionState, btRigidBody rigidBody) { this.body = rigidBody; this.motionState = motionState; rotation = getDirectionInUserInterfaceDimensionUnit(); } public boolean fire(Event3d event) { //if (event.getStage() == null) event.setStage(getStage()); event.setTarget(this); // // Collect ancestors so event propagation is unaffected by hierarchy changes. // Array<Group> ancestors = Pools.obtain(Array.class); // Group parent = this.parent; // while (parent != null) { // ancestors.add(parent); // parent = parent.parent; // } try { // Notify all parent capture listeners, starting at the root. Ancestors may stop an event before children receive it. // Object[] ancestorsArray = ancestors.items; // for (int i = ancestors.size - 1; i >= 0; i--) { // Group currentTarget = (Group)ancestorsArray[i]; // currentTarget.notify(event, true); // if (event.isStopped()) return event.isCancelled(); // } // Notify the target capture listeners. notify(event, true); if (event.isStopped()) return event.isCancelled(); // Notify the target listeners. notify(event, false); if (!event.getBubbles()) return event.isCancelled(); if (event.isStopped()) return event.isCancelled(); // Notify all parent listeners, starting at the target. Children may stop an event before ancestors receive it. // for (int i = 0, n = ancestors.size; i < n; i++) { // ((Group)ancestorsArray[i]).notify(event, false); // if (event.isStopped()) return event.isCancelled(); // } return event.isCancelled(); } finally { // ancestors.clear(); // Pools.free(ancestors); } } public boolean notify(Event3d event, boolean capture) { if (event.getTarget() == null) throw new IllegalArgumentException("The event target cannot be null."); DelayedRemovalArray<EventListener3d> listeners = capture ? captureListeners : this.listeners; if (listeners.size == 0) return event.isCancelled(); event.setListenerActor(this); event.setCapture(capture); //if (event.getStage() == null) event.setStage(stage); listeners.begin(); for (int i = 0, n = listeners.size; i < n; i++) { EventListener3d listener = listeners.get(i); if (listener.handle(event)) { event.handle(); // if (event instanceof InputEvent) { // InputEvent inputEvent = (InputEvent)event; // if (inputEvent.getType() == Type.touchDown) { // event.getStage().addTouchFocus(listener, this, inputEvent.getTarget(), inputEvent.getPointer(), // inputEvent.getButton()); // } // } } } listeners.end(); return event.isCancelled(); } public boolean addListener(EventListener3d listener) { if (!listeners.contains(listener, true)) { listeners.add(listener); return true; } return false; } public boolean removeListener(EventListener3d listener) { return listeners.removeValue(listener, true); } public Array<EventListener3d> getListeners() { return listeners; } public boolean addCaptureListener(EventListener3d listener) { if (!captureListeners.contains(listener, true)) captureListeners.add(listener); return true; } public boolean removeCaptureListener(EventListener3d listener) { return captureListeners.removeValue(listener, true); } public Array<EventListener3d> getCaptureListeners() { return captureListeners; } public void addAction(Action3d action) { action.setActor(this); actions.add(action); Gdx.graphics.requestRendering(); } public void removeAction(Action3d action) { if (actions.removeValue(action, true)) action.setActor(null); } public Array<Action3d> getActions() { return actions; } /** * Removes all actions on this actor. */ public void clearActions() { for (int i = actions.size - 1; i >= 0; i--) actions.get(i).setActor(null); actions.clear(); } /** * Removes all listeners on this actor. */ public void clearListeners() { listeners.clear(); captureListeners.clear(); } /** * Removes all actions and listeners on this actor. */ public void clear() { clearActions(); clearListeners(); } public boolean isVisible() { return visible; } /** * If false, the actor will not be drawn and will not receive touch events. Default is true. */ public void setVisible(boolean visible) { this.visible = visible; } //region motions private void resetMotionBuffers() { motionImpulse.set(0,0,0); motionAngularImpulse.set(0,0,0); motionPositionBuffer.set(0,0,0); } public void setXInUserInterfaceDimensionUnit(Float x) { resetMotionBuffers(); motionState.transform.getTranslation(motionPositionBuffer); motionPositionBuffer.x = x; motionState.transform.setTranslation(motionPositionBuffer); body.setWorldTransform(motionState.transform); body.activate(); } public void setYInUserInterfaceDimensionUnit(Float y) { resetMotionBuffers(); motionState.transform.getTranslation(motionPositionBuffer); motionPositionBuffer.y = y; motionState.transform.setTranslation(motionPositionBuffer); body.setWorldTransform(motionState.transform); body.activate(); } public void setZInUserInterfaceDimensionUnit(Float z) { resetMotionBuffers(); motionState.transform.getTranslation(motionPositionBuffer); motionPositionBuffer.z = z; motionState.transform.setTranslation(motionPositionBuffer); body.setWorldTransform(motionState.transform); body.activate(); } public void changeXInUserInterfaceDimensionUnit(Float x) { resetMotionBuffers(); motionState.transform.trn(x,0,0); body.setWorldTransform(motionState.transform); body.activate(); } public void changeYInUserInterfaceDimensionUnit(Float y) { resetMotionBuffers(); motionState.transform.trn(0,y,0); body.setWorldTransform(motionState.transform); body.activate(); } public void changeZInUserInterfaceDimensionUnit(Float z) { resetMotionBuffers(); motionState.transform.trn(0,0,z); body.setWorldTransform(motionState.transform); body.activate(); } public float getXInUserInterfaceDimensionUnit() { return motionState.transform.val[M03]; } public float getYInUserInterfaceDimensionUnit() { return motionState.transform.val[M13]; } public float getZInUserInterfaceDimensionUnit() { return motionState.transform.val[M23]; } public void setPositionInUserInterfaceDimensionUnit(float currentX, float currentY, float currentZ) { //todo use velocity?? motionState.transform.setTranslation(currentX,currentY,currentZ); body.setWorldTransform(motionState.transform); body.activate(); } public void changeDirectionInUserInterfaceDimensionUnit(Float newDegrees) { rotateBy(newDegrees); } public float getDirectionInUserInterfaceDimensionUnit() { return getRotation(); } public void setDirectionInUserInterfaceDimensionUnit(Float degrees) { degrees = degrees % 360; float rotationAngle = getRotation(); rotateBy(degrees - rotationAngle); } public float getRotation () { motionState.transform.getRotation(rotationQuaternion); return rotationQuaternion.getAngleAround(Vector3.Y); } public void rotateBy (float amountInDegrees) { motionState.transform.rotate(Vector3.Y,amountInDegrees); body.setWorldTransform(motionState.transform); body.activate(); } //endregion public void setWorldTransform(Matrix4 transform) { if (body != null) { body.setWorldTransform(transform); } modelInstance.transform.set(transform); } public static class MotionState extends btMotionState implements Disposable { private final Matrix4 transform; public MotionState(final Matrix4 transform) { this.transform = transform; } @Override public void getWorldTransform(Matrix4 worldTrans) { worldTrans.set(transform); } @Override public void setWorldTransform(Matrix4 worldTrans) { transform.set(worldTrans); } @Override public void dispose() { delete(); } } }
Catrobat/Catroid3D
catroid3d/src/org/catrobat/catroid/libgdx3dwrapper/scene/Actor3d.java
3,309
// InputEvent inputEvent = (InputEvent)event;
line_comment
nl
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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. ******************************************************************************/ //this class is based on and contains source code from on libgdx scene2d Actor.class package org.catrobat.catroid.libgdx3dwrapper.scene; import android.support.annotation.IntDef; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Quaternion; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.physics.bullet.dynamics.btRigidBody; import com.badlogic.gdx.physics.bullet.linearmath.btMotionState; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.DelayedRemovalArray; import com.badlogic.gdx.utils.Disposable; import org.catrobat.catroid.libgdx3dwrapper.actions.Action3d; import org.catrobat.catroid.libgdx3dwrapper.actions.Event3d; import org.catrobat.catroid.physics.Entity; import org.catrobat.catroid.physics.EventListener3d; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import static com.badlogic.gdx.math.Matrix4.M03; import static com.badlogic.gdx.math.Matrix4.M13; import static com.badlogic.gdx.math.Matrix4.M23; public class Actor3d { public ModelInstance modelInstance; public btRigidBody body; protected Entity.MotionState motionState; protected Matrix4 transform; protected final Array<Action3d> actions = new Array(0); private boolean visible; private final Vector3 motionImpulse = new Vector3(); private final Vector3 motionAngularImpulse = new Vector3(); private final Vector3 motionPositionBuffer = new Vector3(); private final Quaternion rotationQuaternion = new Quaternion(); private final DelayedRemovalArray<EventListener3d> listeners = new DelayedRemovalArray(0); private final DelayedRemovalArray<EventListener3d> captureListeners = new DelayedRemovalArray(0); //private Group parent; private float rotation = 0f; public Actor3d() { } public Actor3d(Entity.MotionState motionState, btRigidBody rigidBody) { this.body = rigidBody; this.motionState = motionState; rotation = getDirectionInUserInterfaceDimensionUnit(); } public boolean fire(Event3d event) { //if (event.getStage() == null) event.setStage(getStage()); event.setTarget(this); // // Collect ancestors so event propagation is unaffected by hierarchy changes. // Array<Group> ancestors = Pools.obtain(Array.class); // Group parent = this.parent; // while (parent != null) { // ancestors.add(parent); // parent = parent.parent; // } try { // Notify all parent capture listeners, starting at the root. Ancestors may stop an event before children receive it. // Object[] ancestorsArray = ancestors.items; // for (int i = ancestors.size - 1; i >= 0; i--) { // Group currentTarget = (Group)ancestorsArray[i]; // currentTarget.notify(event, true); // if (event.isStopped()) return event.isCancelled(); // } // Notify the target capture listeners. notify(event, true); if (event.isStopped()) return event.isCancelled(); // Notify the target listeners. notify(event, false); if (!event.getBubbles()) return event.isCancelled(); if (event.isStopped()) return event.isCancelled(); // Notify all parent listeners, starting at the target. Children may stop an event before ancestors receive it. // for (int i = 0, n = ancestors.size; i < n; i++) { // ((Group)ancestorsArray[i]).notify(event, false); // if (event.isStopped()) return event.isCancelled(); // } return event.isCancelled(); } finally { // ancestors.clear(); // Pools.free(ancestors); } } public boolean notify(Event3d event, boolean capture) { if (event.getTarget() == null) throw new IllegalArgumentException("The event target cannot be null."); DelayedRemovalArray<EventListener3d> listeners = capture ? captureListeners : this.listeners; if (listeners.size == 0) return event.isCancelled(); event.setListenerActor(this); event.setCapture(capture); //if (event.getStage() == null) event.setStage(stage); listeners.begin(); for (int i = 0, n = listeners.size; i < n; i++) { EventListener3d listener = listeners.get(i); if (listener.handle(event)) { event.handle(); // if (event instanceof InputEvent) { // InputEvent inputEvent<SUF> // if (inputEvent.getType() == Type.touchDown) { // event.getStage().addTouchFocus(listener, this, inputEvent.getTarget(), inputEvent.getPointer(), // inputEvent.getButton()); // } // } } } listeners.end(); return event.isCancelled(); } public boolean addListener(EventListener3d listener) { if (!listeners.contains(listener, true)) { listeners.add(listener); return true; } return false; } public boolean removeListener(EventListener3d listener) { return listeners.removeValue(listener, true); } public Array<EventListener3d> getListeners() { return listeners; } public boolean addCaptureListener(EventListener3d listener) { if (!captureListeners.contains(listener, true)) captureListeners.add(listener); return true; } public boolean removeCaptureListener(EventListener3d listener) { return captureListeners.removeValue(listener, true); } public Array<EventListener3d> getCaptureListeners() { return captureListeners; } public void addAction(Action3d action) { action.setActor(this); actions.add(action); Gdx.graphics.requestRendering(); } public void removeAction(Action3d action) { if (actions.removeValue(action, true)) action.setActor(null); } public Array<Action3d> getActions() { return actions; } /** * Removes all actions on this actor. */ public void clearActions() { for (int i = actions.size - 1; i >= 0; i--) actions.get(i).setActor(null); actions.clear(); } /** * Removes all listeners on this actor. */ public void clearListeners() { listeners.clear(); captureListeners.clear(); } /** * Removes all actions and listeners on this actor. */ public void clear() { clearActions(); clearListeners(); } public boolean isVisible() { return visible; } /** * If false, the actor will not be drawn and will not receive touch events. Default is true. */ public void setVisible(boolean visible) { this.visible = visible; } //region motions private void resetMotionBuffers() { motionImpulse.set(0,0,0); motionAngularImpulse.set(0,0,0); motionPositionBuffer.set(0,0,0); } public void setXInUserInterfaceDimensionUnit(Float x) { resetMotionBuffers(); motionState.transform.getTranslation(motionPositionBuffer); motionPositionBuffer.x = x; motionState.transform.setTranslation(motionPositionBuffer); body.setWorldTransform(motionState.transform); body.activate(); } public void setYInUserInterfaceDimensionUnit(Float y) { resetMotionBuffers(); motionState.transform.getTranslation(motionPositionBuffer); motionPositionBuffer.y = y; motionState.transform.setTranslation(motionPositionBuffer); body.setWorldTransform(motionState.transform); body.activate(); } public void setZInUserInterfaceDimensionUnit(Float z) { resetMotionBuffers(); motionState.transform.getTranslation(motionPositionBuffer); motionPositionBuffer.z = z; motionState.transform.setTranslation(motionPositionBuffer); body.setWorldTransform(motionState.transform); body.activate(); } public void changeXInUserInterfaceDimensionUnit(Float x) { resetMotionBuffers(); motionState.transform.trn(x,0,0); body.setWorldTransform(motionState.transform); body.activate(); } public void changeYInUserInterfaceDimensionUnit(Float y) { resetMotionBuffers(); motionState.transform.trn(0,y,0); body.setWorldTransform(motionState.transform); body.activate(); } public void changeZInUserInterfaceDimensionUnit(Float z) { resetMotionBuffers(); motionState.transform.trn(0,0,z); body.setWorldTransform(motionState.transform); body.activate(); } public float getXInUserInterfaceDimensionUnit() { return motionState.transform.val[M03]; } public float getYInUserInterfaceDimensionUnit() { return motionState.transform.val[M13]; } public float getZInUserInterfaceDimensionUnit() { return motionState.transform.val[M23]; } public void setPositionInUserInterfaceDimensionUnit(float currentX, float currentY, float currentZ) { //todo use velocity?? motionState.transform.setTranslation(currentX,currentY,currentZ); body.setWorldTransform(motionState.transform); body.activate(); } public void changeDirectionInUserInterfaceDimensionUnit(Float newDegrees) { rotateBy(newDegrees); } public float getDirectionInUserInterfaceDimensionUnit() { return getRotation(); } public void setDirectionInUserInterfaceDimensionUnit(Float degrees) { degrees = degrees % 360; float rotationAngle = getRotation(); rotateBy(degrees - rotationAngle); } public float getRotation () { motionState.transform.getRotation(rotationQuaternion); return rotationQuaternion.getAngleAround(Vector3.Y); } public void rotateBy (float amountInDegrees) { motionState.transform.rotate(Vector3.Y,amountInDegrees); body.setWorldTransform(motionState.transform); body.activate(); } //endregion public void setWorldTransform(Matrix4 transform) { if (body != null) { body.setWorldTransform(transform); } modelInstance.transform.set(transform); } public static class MotionState extends btMotionState implements Disposable { private final Matrix4 transform; public MotionState(final Matrix4 transform) { this.transform = transform; } @Override public void getWorldTransform(Matrix4 worldTrans) { worldTrans.set(transform); } @Override public void setWorldTransform(Matrix4 worldTrans) { transform.set(worldTrans); } @Override public void dispose() { delete(); } } }
17249_41
package ca.cumulonimbus.barometernetwork; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; /** * Calculate the phase of the moon given a date. * * https://code.google.com/p/moonphase/ */ public class MoonPhase { public static final double MY_PI = 3.14159265358979323846; public static final double MY_TWO_PI = 6.28318530717958647692; public static final double EPOCH = 2444238.5; /* 1980 January 0.0. */ public static final double SUN_ELONG_EPOCH = 278.833540; /* * Ecliptic * longitude of the * Sun at epoch * 1980.0. */ public static final double SUN_ELONG_PERIGEE = 282.596403; /* * Ecliptic * longitude of * the Sun at * perigee. */ public static final double ECCENT_EARTH_ORBIT = 0.016718; /* * Eccentricity of * Earth's orbit. */ public static final double MOON_MEAN_LONGITUDE_EPOCH = 64.975464; /* * Moon's * mean * lonigitude * at the * epoch. */ public static final double MOON_MEAN_LONGITUDE_PERIGREE = 349.383063; /* * Mean * longitude * of * the * perigee * at * the * epoch * . */ public static final double KEPLER_EPSILON = 1E-6; /* * Accurancy of the Kepler * equation. */ public static final long RC_MIN_BCE_TO_1_CE = 1721424L; /* * Days between * 1.5-Jan-4713 BCE * and 1.5-Jan-0001 * CE */ public static final double SYNMONTH = 29.53058868; /* * Synodic month (new * Moon to new Moon) */ public static final int DAY_LAST = 365; public static final boolean orthodox_calendar = false; public static final int mvec[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; public static final int greg[] = { 1582, 10, 5, 14 }; public static final int YEAR = 0; public static final int MONTH = 1; public static final int FIRST_DAY = 2; public static final int LAST_DAY = 3; // private instance fields private Calendar _curCal; private double _JD; private double _phase; private static double _moonAgeAsDays; /* * public MoonPhase(Prefs prefs){ * * this(Calendar.getInstance(prefs)); //_curCal.setTime(new Date());// * _curCal.setTimeInMillis(System.currentTimeMillis()); * * } */ public MoonPhase(Calendar c) { // / TODO: Add timezone adjustments here _curCal = c; // _curCal = adjustTimeZone(c, getCurrentTimeZone()); } /* * Some useful mathematical functions used by John Walkers `phase()' * function. */ public static double FIXANGLE(double a) { return (a) - 360.0 * (Math.floor((a) / 360.0)); } public static double TORAD(double d) { return (d) * (MY_PI / 180.0); } public static double TODEG(double r) { return (r) * (180.0 / MY_PI); } /* * Solves the equation of Kepler. */ public static double kepler(double m) { double e; double delta; e = m = TORAD(m); do { delta = e - ECCENT_EARTH_ORBIT * Math.sin(e) - m; e -= delta / (1.0 - ECCENT_EARTH_ORBIT * Math.cos(e)); } while (Math.abs(delta) - KEPLER_EPSILON > 0.0); return (e); } /* * Computes the number of days in February --- respecting the Gregorian * Reformation period likewise the leap year rule as used by the Eastern * orthodox churches --- and returns them. */ public static int days_of_february(int year) { int day; if ((year > greg[YEAR]) || ((year == greg[YEAR]) && (greg[MONTH] == 1 || ((greg[MONTH] == 2) && (greg[LAST_DAY] >= 28))))) { if (orthodox_calendar) day = ((year & 3) != 0) ? 28 : ((!((year % 100) != 0)) ? (((year % 9) == 2 || (year % 9) == 6) ? 29 : 28) : 29); else day = ((year & 3) != 0) ? 28 : ((!((year % 100) != 0) && ((year % 400) != 0)) ? 28 : 29); } else day = ((year & 3) != 0) ? 28 : 29; /* * Exception, the year 4 AD was historically NO leap year! */ if (year == 4) day--; return (day); } public static int SGN(double gc_x) { return gc_x < 0 ? -1 : gc_x > 0 ? 1 : 0; } /** * <p> * Calculates the phase of the Moon and returns the illuminated fraction of * the Moon's disc as a value within the range of -99.9~...0.0...+99.9~, * which has a negative sign in case the Moon wanes, otherwise the sign is * positive. The New Moon phase is around the 0.0 value and the Full Moon * phase is around the +/-99.9~ value. The argument is the time for which * the phase is requested, expressed as a Julian date and fraction. * </p> * <p> * This function is taken from the program "moontool" by John Walker, * February 1988, which is in the public domain. So see it for more * information! It is adapted (crippled) and `pretty-printed' to the * requirements of Gcal, which means it is lacking all the other useful * computations of astronomical values of the original code. * </p> * * <p> * Here is the blurb from "moontool": * </p> * <p> * ...The algorithms used in this program to calculate the positions Sun and * Moon as seen from the Earth are given in the book "Practical Astronomy * With Your Calculator" by Peter Duffett-Smith, Second Edition, Cambridge * University Press, 1981. Ignore the word "Calculator" in the title; this * is an essential reference if you're interested in developing software * which calculates planetary positions, orbits, eclipses, and the like. If * you're interested in pursuing such programming, you should also obtain: * </p> * * <p> * "Astronomical Formulae for Calculators" by Jean Meeus, Third Edition, * Willmann-Bell, 1985. A must-have. * </p> * * </p>"Planetary Programs and Tables from -4000 to +2800" by Pierre * Bretagnon and Jean-Louis Simon, Willmann-Bell, 1986. If you want the * utmost (outside of JPL) accuracy for the planets, it's here.</p> * * <p> * "Celestial BASIC" by Eric Burgess, Revised Edition, Sybex, 1985. Very * cookbook oriented, and many of the algorithms are hard to dig out of the * turgid BASIC code, but you'll probably want it anyway. * </p> * * <p> * Many of these references can be obtained from Willmann-Bell, P.O. Box * 35025, Richmond, VA 23235, USA. Phone: (804) 320-7016. In addition to * their own publications, they stock most of the standard references for * mathematical and positional astronomy. * </p> * * <p> * This program was written by: * </p> * * <p> * John Walker<br> * Autodesk, Inc.<br> * 2320 Marinship Way<br> * Sausalito, CA 94965<br> * (415) 332-2344 Ext. 829 * </p> * * <p> * Usenet: {sun!well}!acad!kelvin * </p> * * <p> * This program is in the public domain: "Do what thou wilt shall be the * whole of the law". I'd appreciate receiving any bug fixes and/or * enhancements, which I'll incorporate in future versions of the program. * Please leave the original attribution information intact so that credit * and blame may be properly apportioned. * </p> */ public static double phase(double julian_date) { double date_within_epoch; double sun_eccent; double sun_mean_anomaly; double sun_perigree_co_ordinates_to_epoch; double sun_geocentric_elong; double moon_evection; double moon_variation; double moon_mean_anomaly; double moon_mean_longitude; double moon_annual_equation; double moon_correction_term1; double moon_correction_term2; double moon_correction_equation_of_center; double moon_corrected_anomaly; double moon_corrected_longitude; double moon_present_age; double moon_present_phase; double moon_present_longitude; /* * Calculation of the Sun's position. */ date_within_epoch = julian_date - EPOCH; sun_mean_anomaly = FIXANGLE((360.0 / 365.2422) * date_within_epoch); sun_perigree_co_ordinates_to_epoch = FIXANGLE(sun_mean_anomaly + SUN_ELONG_EPOCH - SUN_ELONG_PERIGEE); sun_eccent = kepler(sun_perigree_co_ordinates_to_epoch); sun_eccent = Math.sqrt((1.0 + ECCENT_EARTH_ORBIT) / (1.0 - ECCENT_EARTH_ORBIT)) * Math.tan(sun_eccent / 2.0); sun_eccent = 2.0 * TODEG(atan(sun_eccent)); sun_geocentric_elong = FIXANGLE(sun_eccent + SUN_ELONG_PERIGEE); /* * Calculation of the Moon's position. */ moon_mean_longitude = FIXANGLE(13.1763966 * date_within_epoch + MOON_MEAN_LONGITUDE_EPOCH); moon_mean_anomaly = FIXANGLE(moon_mean_longitude - 0.1114041 * date_within_epoch - MOON_MEAN_LONGITUDE_PERIGREE); moon_evection = 1.2739 * Math.sin(TORAD(2.0 * (moon_mean_longitude - sun_geocentric_elong) - moon_mean_anomaly)); moon_annual_equation = 0.1858 * Math .sin(TORAD(sun_perigree_co_ordinates_to_epoch)); moon_correction_term1 = 0.37 * Math .sin(TORAD(sun_perigree_co_ordinates_to_epoch)); moon_corrected_anomaly = moon_mean_anomaly + moon_evection - moon_annual_equation - moon_correction_term1; moon_correction_equation_of_center = 6.2886 * Math .sin(TORAD(moon_corrected_anomaly)); moon_correction_term2 = 0.214 * Math .sin(TORAD(2.0 * moon_corrected_anomaly)); moon_corrected_longitude = moon_mean_longitude + moon_evection + moon_correction_equation_of_center - moon_annual_equation + moon_correction_term2; moon_variation = 0.6583 * Math .sin(TORAD(2.0 * (moon_corrected_longitude - sun_geocentric_elong))); // true longitude moon_present_longitude = moon_corrected_longitude + moon_variation; moon_present_age = moon_present_longitude - sun_geocentric_elong; moon_present_phase = 100.0 * ((1.0 - Math.cos(TORAD(moon_present_age))) / 2.0); if (0.0 < FIXANGLE(moon_present_age) - 180.0) { moon_present_phase = -moon_present_phase; } _moonAgeAsDays = SYNMONTH * (FIXANGLE(moon_present_age) / 360.0); return moon_present_phase; } /** * UCTTOJ -- Convert GMT date and time to astronomical Julian time (i.e. * Julian date plus day fraction, expressed as a double). * * @param cal * Calendar object * @return JD float Julian date * <p> * Converted to Java by [email protected] from original file * mooncalc.c, part of moontool * http://www.fourmilab.ch/moontoolw/moont16s.zip * </p> */ public static double calendarToJD(Calendar cal) { /* * Algorithm as given in Meeus, Astronomical Algorithms, Chapter 7, page * 61 */ long year = cal.get(Calendar.YEAR); int mon = cal.get(Calendar.MONTH); int mday = cal.get(Calendar.DATE); int hour = cal.get(Calendar.HOUR_OF_DAY); int min = cal.get(Calendar.MINUTE); int sec = cal.get(Calendar.SECOND); int a, b, m; long y; m = mon + 1; y = year; if (m <= 2) { y--; m += 12; } /* * Determine whether date is in Julian or Gregorian calendar based on * canonical date of calendar reform. */ if ((year < 1582) || ((year == 1582) && ((mon < 9) || (mon == 9 && mday < 5)))) { b = 0; } else { a = ((int) (y / 100)); b = 2 - a + (a / 4); } return (((long) (365.25 * (y + 4716))) + ((int) (30.6001 * (m + 1))) + mday + b - 1524.5) + ((sec + 60L * (min + 60L * hour)) / 86400.0); } /** * Returns current phase as double value Uses class Calendar field _curCal * */ public double getPhase() { /* !!! TODO: insert timezone correction here */ _JD = calendarToJD(_curCal); _phase = phase(_JD); return _phase; } public int getPhaseIndex() { return computePhaseIndex(_curCal); } /** * Computes the moon phase index as a value from 0 to 7 Used to display the * phase name and the moon image for the current phase * * @param cal * Calendar calendar object for today's date * @return moon index 0..7 * */ private static int computePhaseIndex(Calendar cal) { int day_year[] = { -1, -1, 30, 58, 89, 119, 150, 180, 211, 241, 272, 303, 333 }; // String moon_phase_name[] = { "New Moon", // 0 // "Waxing crescent", // 1 // "First quarter", // 2 // "Waxing gibbous", // 3 // "Full Moon", // 4 // "Waning gibbous", // 5 // "Third quarter", // 6 // "Waning crescent" }; // 7 int phase; // Moon phase // double factor; // Moon phase factor int year, month, day, hour, min, sec; year = cal.get(Calendar.YEAR); month = cal.get(Calendar.MONTH) + 1; // 0 = Jan, 1 = Feb, etc. day = cal.get(Calendar.DATE); hour = cal.get(Calendar.HOUR); min = cal.get(Calendar.MINUTE); sec = cal.get(Calendar.SECOND); double day_exact = day + hour / 24 + min / 1440 + sec / 86400; // int phase; // Moon phase int cent; // Century number (1979 = 20) int epact; // Age of the moon on Jan. 1 double diy; // Day in the year int golden; // Moon's golden number if (month < 0 || month > 12) { month = 0; // Just in case } // Just in case diy = day_exact + day_year[month]; // Day in the year if ((month > 2) && isLeapYearP(year)) { diy++; } // Leapyear fixup cent = (year / 100) + 1; // Century number golden = (year % 19) + 1; // Golden number epact = ((11 * golden) + 20 // Golden number + (((8 * cent) + 5) / 25) - 5 // 400 year cycle - (((3 * cent) / 4) - 12)) % 30; // Leap year correction if (epact <= 0) { epact += 30; } // Age range is 1 .. 30 if ((epact == 25 && golden > 11) || epact == 24) { epact++; // Calculate the phase, using the magic numbers defined above. // Note that (phase and 7) is equivalent to (phase mod 8) and // is needed on two days per year (when the algorithm yields 8). } // Calculate the phase, using the magic numbers defined above. // Note that (phase and 7) is equivalent to (phase mod 8) and // is needed on two days per year (when the algorithm yields 8). // this.factor = ((((diy + (double)epact) * 6) + 11) % 100 ); phase = ((((((int) diy + epact) * 6) + 11) % 177) / 22) & 7; return (phase); } /** * isLeapYearP Return true if the year is a leapyear */ private static boolean isLeapYearP(int year) { return ((year % 4 == 0) && ((year % 400 == 0) || (year % 100 != 0))); } public void updateCal(Calendar c) { _curCal = c; _JD = calendarToJD(_curCal); _phase = phase(_JD); } public String getMoonAgeAsDays() { int aom_d = (int) _moonAgeAsDays; int aom_h = (int) (24 * (_moonAgeAsDays - Math.floor(_moonAgeAsDays))); int aom_m = (int) (1440 * (_moonAgeAsDays - Math.floor(_moonAgeAsDays))) % 60; return "" + aom_d + (aom_d == 1 ? " day, " : " days, ") + aom_h + (aom_h == 1 ? " hour, " : " hours, ") + aom_m + (aom_m == 1 ? " minute" : " minutes"); } static public double atan(double x) { double SQRT3 = 1.732050807568877294; boolean signChange = false; boolean Invert = false; int sp = 0; double x2, a; // check up the sign change if (x < 0.) { x = -x; signChange = true; } // check up the invertation if (x > 1.) { x = 1 / x; Invert = true; } // process shrinking the domain until x<PI/12 while (x > Math.PI / 12) { sp++; a = x + SQRT3; a = 1 / a; x = x * SQRT3; x = x - 1; x = x * a; } // calculation core x2 = x * x; a = x2 + 1.4087812; a = 0.55913709 / a; a = a + 0.60310579; a = a - (x2 * 0.05160454); a = a * x; // process until sp=0 while (sp > 0) { a = a + Math.PI / 6; sp--; } // invertation took place if (Invert) a = Math.PI / 2 - a; // sign change took place if (signChange) a = -a; // return a; } // public static void main(String args[]) { // System.out.println(new // SimpleDateFormat("EEEE, dd-MMMM-yyyy HH:mm zzzz").format(new Date())); // // MoonPhase mp = new MoonPhase(); // System.out.printf("Current phase: %f%n", mp.getPhase()); // System.out.println("Moon Age: " + mp.getMoonAgeAsDays()); // // Calendar c = Calendar.getInstance(); // c.setTimeInMillis(System.currentTimeMillis()); // c.add(Calendar.DAY_OF_WEEK, -22); // // for (int i=0; i< 33; i++){ // c.add(Calendar.DAY_OF_WEEK, 1); // mp.updateCal(c); // System.out.format("%1$td-%1$tB,%1$tY %1$tH:%1$tM:%1$tS ",c); // System.out.printf("%f%n", mp.getPhase()); // } // System.out.println( new // SimpleDateFormat("EEEE, dd-MMMM-yyyy HH:mm zzzz").format(c.getTime())); // double JD = calendarToJD_BAD_WRONG(c); // double JD2 =calendarToJD(c); // // System.out.println("Julian Date: " + JD); // System.out.println("Julian Date2: " + JD2); // System.out.println("Parsed Phase: " + phase(JD)); // System.out.println("Parsed Phase2: " + phase(JD2)); // // c.add(Calendar.DAY_OF_WEEK, 1); // JD = calendarToJD_BAD_WRONG(c); // System.out.println("Parsed Phase +1 day: " + phase(JD)); // System.out.printf("F 22-Jan-2008 2454488.0649868953 %.8f\n", // phase(2454488.0649868953)); // System.out.printf("N 07-Mar-2008 2454533.2179779503 %.8f\n", // phase(2454533.2179779503)); // System.out.printf("F 21-Mar-2008 2454547.2769324942 %.8f\n", // phase(2454547.2769324942)); // System.out.printf("N 27-Dec-2008 2454828.0159972804 %.8f\n", // phase(2454828.0159972804)); // System.out.printf("F 11-Jan-2009 2454842.6434176303 %.8f\n", // phase(2454842.6434176303)); // System.out.printf("N 07-Mar-2008 2454533.2179779503 %.8f\n", // phase(2454533.2179779503)); private static Calendar adjustTimeZone(Calendar c, int offsetInHours) { long currTime = c.getTime().getTime(); c.setTime(new Date(currTime + offsetInHours * 1000 * 60 * 60)); return c; } public int getCurrentTimeZone() { return TimeZone.getDefault().getRawOffset() / 1000 * 60 * 60; } }
Cbsoftware/PressureNet
src/ca/cumulonimbus/barometernetwork/MoonPhase.java
6,995
// Moon's golden number
line_comment
nl
package ca.cumulonimbus.barometernetwork; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; /** * Calculate the phase of the moon given a date. * * https://code.google.com/p/moonphase/ */ public class MoonPhase { public static final double MY_PI = 3.14159265358979323846; public static final double MY_TWO_PI = 6.28318530717958647692; public static final double EPOCH = 2444238.5; /* 1980 January 0.0. */ public static final double SUN_ELONG_EPOCH = 278.833540; /* * Ecliptic * longitude of the * Sun at epoch * 1980.0. */ public static final double SUN_ELONG_PERIGEE = 282.596403; /* * Ecliptic * longitude of * the Sun at * perigee. */ public static final double ECCENT_EARTH_ORBIT = 0.016718; /* * Eccentricity of * Earth's orbit. */ public static final double MOON_MEAN_LONGITUDE_EPOCH = 64.975464; /* * Moon's * mean * lonigitude * at the * epoch. */ public static final double MOON_MEAN_LONGITUDE_PERIGREE = 349.383063; /* * Mean * longitude * of * the * perigee * at * the * epoch * . */ public static final double KEPLER_EPSILON = 1E-6; /* * Accurancy of the Kepler * equation. */ public static final long RC_MIN_BCE_TO_1_CE = 1721424L; /* * Days between * 1.5-Jan-4713 BCE * and 1.5-Jan-0001 * CE */ public static final double SYNMONTH = 29.53058868; /* * Synodic month (new * Moon to new Moon) */ public static final int DAY_LAST = 365; public static final boolean orthodox_calendar = false; public static final int mvec[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; public static final int greg[] = { 1582, 10, 5, 14 }; public static final int YEAR = 0; public static final int MONTH = 1; public static final int FIRST_DAY = 2; public static final int LAST_DAY = 3; // private instance fields private Calendar _curCal; private double _JD; private double _phase; private static double _moonAgeAsDays; /* * public MoonPhase(Prefs prefs){ * * this(Calendar.getInstance(prefs)); //_curCal.setTime(new Date());// * _curCal.setTimeInMillis(System.currentTimeMillis()); * * } */ public MoonPhase(Calendar c) { // / TODO: Add timezone adjustments here _curCal = c; // _curCal = adjustTimeZone(c, getCurrentTimeZone()); } /* * Some useful mathematical functions used by John Walkers `phase()' * function. */ public static double FIXANGLE(double a) { return (a) - 360.0 * (Math.floor((a) / 360.0)); } public static double TORAD(double d) { return (d) * (MY_PI / 180.0); } public static double TODEG(double r) { return (r) * (180.0 / MY_PI); } /* * Solves the equation of Kepler. */ public static double kepler(double m) { double e; double delta; e = m = TORAD(m); do { delta = e - ECCENT_EARTH_ORBIT * Math.sin(e) - m; e -= delta / (1.0 - ECCENT_EARTH_ORBIT * Math.cos(e)); } while (Math.abs(delta) - KEPLER_EPSILON > 0.0); return (e); } /* * Computes the number of days in February --- respecting the Gregorian * Reformation period likewise the leap year rule as used by the Eastern * orthodox churches --- and returns them. */ public static int days_of_february(int year) { int day; if ((year > greg[YEAR]) || ((year == greg[YEAR]) && (greg[MONTH] == 1 || ((greg[MONTH] == 2) && (greg[LAST_DAY] >= 28))))) { if (orthodox_calendar) day = ((year & 3) != 0) ? 28 : ((!((year % 100) != 0)) ? (((year % 9) == 2 || (year % 9) == 6) ? 29 : 28) : 29); else day = ((year & 3) != 0) ? 28 : ((!((year % 100) != 0) && ((year % 400) != 0)) ? 28 : 29); } else day = ((year & 3) != 0) ? 28 : 29; /* * Exception, the year 4 AD was historically NO leap year! */ if (year == 4) day--; return (day); } public static int SGN(double gc_x) { return gc_x < 0 ? -1 : gc_x > 0 ? 1 : 0; } /** * <p> * Calculates the phase of the Moon and returns the illuminated fraction of * the Moon's disc as a value within the range of -99.9~...0.0...+99.9~, * which has a negative sign in case the Moon wanes, otherwise the sign is * positive. The New Moon phase is around the 0.0 value and the Full Moon * phase is around the +/-99.9~ value. The argument is the time for which * the phase is requested, expressed as a Julian date and fraction. * </p> * <p> * This function is taken from the program "moontool" by John Walker, * February 1988, which is in the public domain. So see it for more * information! It is adapted (crippled) and `pretty-printed' to the * requirements of Gcal, which means it is lacking all the other useful * computations of astronomical values of the original code. * </p> * * <p> * Here is the blurb from "moontool": * </p> * <p> * ...The algorithms used in this program to calculate the positions Sun and * Moon as seen from the Earth are given in the book "Practical Astronomy * With Your Calculator" by Peter Duffett-Smith, Second Edition, Cambridge * University Press, 1981. Ignore the word "Calculator" in the title; this * is an essential reference if you're interested in developing software * which calculates planetary positions, orbits, eclipses, and the like. If * you're interested in pursuing such programming, you should also obtain: * </p> * * <p> * "Astronomical Formulae for Calculators" by Jean Meeus, Third Edition, * Willmann-Bell, 1985. A must-have. * </p> * * </p>"Planetary Programs and Tables from -4000 to +2800" by Pierre * Bretagnon and Jean-Louis Simon, Willmann-Bell, 1986. If you want the * utmost (outside of JPL) accuracy for the planets, it's here.</p> * * <p> * "Celestial BASIC" by Eric Burgess, Revised Edition, Sybex, 1985. Very * cookbook oriented, and many of the algorithms are hard to dig out of the * turgid BASIC code, but you'll probably want it anyway. * </p> * * <p> * Many of these references can be obtained from Willmann-Bell, P.O. Box * 35025, Richmond, VA 23235, USA. Phone: (804) 320-7016. In addition to * their own publications, they stock most of the standard references for * mathematical and positional astronomy. * </p> * * <p> * This program was written by: * </p> * * <p> * John Walker<br> * Autodesk, Inc.<br> * 2320 Marinship Way<br> * Sausalito, CA 94965<br> * (415) 332-2344 Ext. 829 * </p> * * <p> * Usenet: {sun!well}!acad!kelvin * </p> * * <p> * This program is in the public domain: "Do what thou wilt shall be the * whole of the law". I'd appreciate receiving any bug fixes and/or * enhancements, which I'll incorporate in future versions of the program. * Please leave the original attribution information intact so that credit * and blame may be properly apportioned. * </p> */ public static double phase(double julian_date) { double date_within_epoch; double sun_eccent; double sun_mean_anomaly; double sun_perigree_co_ordinates_to_epoch; double sun_geocentric_elong; double moon_evection; double moon_variation; double moon_mean_anomaly; double moon_mean_longitude; double moon_annual_equation; double moon_correction_term1; double moon_correction_term2; double moon_correction_equation_of_center; double moon_corrected_anomaly; double moon_corrected_longitude; double moon_present_age; double moon_present_phase; double moon_present_longitude; /* * Calculation of the Sun's position. */ date_within_epoch = julian_date - EPOCH; sun_mean_anomaly = FIXANGLE((360.0 / 365.2422) * date_within_epoch); sun_perigree_co_ordinates_to_epoch = FIXANGLE(sun_mean_anomaly + SUN_ELONG_EPOCH - SUN_ELONG_PERIGEE); sun_eccent = kepler(sun_perigree_co_ordinates_to_epoch); sun_eccent = Math.sqrt((1.0 + ECCENT_EARTH_ORBIT) / (1.0 - ECCENT_EARTH_ORBIT)) * Math.tan(sun_eccent / 2.0); sun_eccent = 2.0 * TODEG(atan(sun_eccent)); sun_geocentric_elong = FIXANGLE(sun_eccent + SUN_ELONG_PERIGEE); /* * Calculation of the Moon's position. */ moon_mean_longitude = FIXANGLE(13.1763966 * date_within_epoch + MOON_MEAN_LONGITUDE_EPOCH); moon_mean_anomaly = FIXANGLE(moon_mean_longitude - 0.1114041 * date_within_epoch - MOON_MEAN_LONGITUDE_PERIGREE); moon_evection = 1.2739 * Math.sin(TORAD(2.0 * (moon_mean_longitude - sun_geocentric_elong) - moon_mean_anomaly)); moon_annual_equation = 0.1858 * Math .sin(TORAD(sun_perigree_co_ordinates_to_epoch)); moon_correction_term1 = 0.37 * Math .sin(TORAD(sun_perigree_co_ordinates_to_epoch)); moon_corrected_anomaly = moon_mean_anomaly + moon_evection - moon_annual_equation - moon_correction_term1; moon_correction_equation_of_center = 6.2886 * Math .sin(TORAD(moon_corrected_anomaly)); moon_correction_term2 = 0.214 * Math .sin(TORAD(2.0 * moon_corrected_anomaly)); moon_corrected_longitude = moon_mean_longitude + moon_evection + moon_correction_equation_of_center - moon_annual_equation + moon_correction_term2; moon_variation = 0.6583 * Math .sin(TORAD(2.0 * (moon_corrected_longitude - sun_geocentric_elong))); // true longitude moon_present_longitude = moon_corrected_longitude + moon_variation; moon_present_age = moon_present_longitude - sun_geocentric_elong; moon_present_phase = 100.0 * ((1.0 - Math.cos(TORAD(moon_present_age))) / 2.0); if (0.0 < FIXANGLE(moon_present_age) - 180.0) { moon_present_phase = -moon_present_phase; } _moonAgeAsDays = SYNMONTH * (FIXANGLE(moon_present_age) / 360.0); return moon_present_phase; } /** * UCTTOJ -- Convert GMT date and time to astronomical Julian time (i.e. * Julian date plus day fraction, expressed as a double). * * @param cal * Calendar object * @return JD float Julian date * <p> * Converted to Java by [email protected] from original file * mooncalc.c, part of moontool * http://www.fourmilab.ch/moontoolw/moont16s.zip * </p> */ public static double calendarToJD(Calendar cal) { /* * Algorithm as given in Meeus, Astronomical Algorithms, Chapter 7, page * 61 */ long year = cal.get(Calendar.YEAR); int mon = cal.get(Calendar.MONTH); int mday = cal.get(Calendar.DATE); int hour = cal.get(Calendar.HOUR_OF_DAY); int min = cal.get(Calendar.MINUTE); int sec = cal.get(Calendar.SECOND); int a, b, m; long y; m = mon + 1; y = year; if (m <= 2) { y--; m += 12; } /* * Determine whether date is in Julian or Gregorian calendar based on * canonical date of calendar reform. */ if ((year < 1582) || ((year == 1582) && ((mon < 9) || (mon == 9 && mday < 5)))) { b = 0; } else { a = ((int) (y / 100)); b = 2 - a + (a / 4); } return (((long) (365.25 * (y + 4716))) + ((int) (30.6001 * (m + 1))) + mday + b - 1524.5) + ((sec + 60L * (min + 60L * hour)) / 86400.0); } /** * Returns current phase as double value Uses class Calendar field _curCal * */ public double getPhase() { /* !!! TODO: insert timezone correction here */ _JD = calendarToJD(_curCal); _phase = phase(_JD); return _phase; } public int getPhaseIndex() { return computePhaseIndex(_curCal); } /** * Computes the moon phase index as a value from 0 to 7 Used to display the * phase name and the moon image for the current phase * * @param cal * Calendar calendar object for today's date * @return moon index 0..7 * */ private static int computePhaseIndex(Calendar cal) { int day_year[] = { -1, -1, 30, 58, 89, 119, 150, 180, 211, 241, 272, 303, 333 }; // String moon_phase_name[] = { "New Moon", // 0 // "Waxing crescent", // 1 // "First quarter", // 2 // "Waxing gibbous", // 3 // "Full Moon", // 4 // "Waning gibbous", // 5 // "Third quarter", // 6 // "Waning crescent" }; // 7 int phase; // Moon phase // double factor; // Moon phase factor int year, month, day, hour, min, sec; year = cal.get(Calendar.YEAR); month = cal.get(Calendar.MONTH) + 1; // 0 = Jan, 1 = Feb, etc. day = cal.get(Calendar.DATE); hour = cal.get(Calendar.HOUR); min = cal.get(Calendar.MINUTE); sec = cal.get(Calendar.SECOND); double day_exact = day + hour / 24 + min / 1440 + sec / 86400; // int phase; // Moon phase int cent; // Century number (1979 = 20) int epact; // Age of the moon on Jan. 1 double diy; // Day in the year int golden; // Moon's golden<SUF> if (month < 0 || month > 12) { month = 0; // Just in case } // Just in case diy = day_exact + day_year[month]; // Day in the year if ((month > 2) && isLeapYearP(year)) { diy++; } // Leapyear fixup cent = (year / 100) + 1; // Century number golden = (year % 19) + 1; // Golden number epact = ((11 * golden) + 20 // Golden number + (((8 * cent) + 5) / 25) - 5 // 400 year cycle - (((3 * cent) / 4) - 12)) % 30; // Leap year correction if (epact <= 0) { epact += 30; } // Age range is 1 .. 30 if ((epact == 25 && golden > 11) || epact == 24) { epact++; // Calculate the phase, using the magic numbers defined above. // Note that (phase and 7) is equivalent to (phase mod 8) and // is needed on two days per year (when the algorithm yields 8). } // Calculate the phase, using the magic numbers defined above. // Note that (phase and 7) is equivalent to (phase mod 8) and // is needed on two days per year (when the algorithm yields 8). // this.factor = ((((diy + (double)epact) * 6) + 11) % 100 ); phase = ((((((int) diy + epact) * 6) + 11) % 177) / 22) & 7; return (phase); } /** * isLeapYearP Return true if the year is a leapyear */ private static boolean isLeapYearP(int year) { return ((year % 4 == 0) && ((year % 400 == 0) || (year % 100 != 0))); } public void updateCal(Calendar c) { _curCal = c; _JD = calendarToJD(_curCal); _phase = phase(_JD); } public String getMoonAgeAsDays() { int aom_d = (int) _moonAgeAsDays; int aom_h = (int) (24 * (_moonAgeAsDays - Math.floor(_moonAgeAsDays))); int aom_m = (int) (1440 * (_moonAgeAsDays - Math.floor(_moonAgeAsDays))) % 60; return "" + aom_d + (aom_d == 1 ? " day, " : " days, ") + aom_h + (aom_h == 1 ? " hour, " : " hours, ") + aom_m + (aom_m == 1 ? " minute" : " minutes"); } static public double atan(double x) { double SQRT3 = 1.732050807568877294; boolean signChange = false; boolean Invert = false; int sp = 0; double x2, a; // check up the sign change if (x < 0.) { x = -x; signChange = true; } // check up the invertation if (x > 1.) { x = 1 / x; Invert = true; } // process shrinking the domain until x<PI/12 while (x > Math.PI / 12) { sp++; a = x + SQRT3; a = 1 / a; x = x * SQRT3; x = x - 1; x = x * a; } // calculation core x2 = x * x; a = x2 + 1.4087812; a = 0.55913709 / a; a = a + 0.60310579; a = a - (x2 * 0.05160454); a = a * x; // process until sp=0 while (sp > 0) { a = a + Math.PI / 6; sp--; } // invertation took place if (Invert) a = Math.PI / 2 - a; // sign change took place if (signChange) a = -a; // return a; } // public static void main(String args[]) { // System.out.println(new // SimpleDateFormat("EEEE, dd-MMMM-yyyy HH:mm zzzz").format(new Date())); // // MoonPhase mp = new MoonPhase(); // System.out.printf("Current phase: %f%n", mp.getPhase()); // System.out.println("Moon Age: " + mp.getMoonAgeAsDays()); // // Calendar c = Calendar.getInstance(); // c.setTimeInMillis(System.currentTimeMillis()); // c.add(Calendar.DAY_OF_WEEK, -22); // // for (int i=0; i< 33; i++){ // c.add(Calendar.DAY_OF_WEEK, 1); // mp.updateCal(c); // System.out.format("%1$td-%1$tB,%1$tY %1$tH:%1$tM:%1$tS ",c); // System.out.printf("%f%n", mp.getPhase()); // } // System.out.println( new // SimpleDateFormat("EEEE, dd-MMMM-yyyy HH:mm zzzz").format(c.getTime())); // double JD = calendarToJD_BAD_WRONG(c); // double JD2 =calendarToJD(c); // // System.out.println("Julian Date: " + JD); // System.out.println("Julian Date2: " + JD2); // System.out.println("Parsed Phase: " + phase(JD)); // System.out.println("Parsed Phase2: " + phase(JD2)); // // c.add(Calendar.DAY_OF_WEEK, 1); // JD = calendarToJD_BAD_WRONG(c); // System.out.println("Parsed Phase +1 day: " + phase(JD)); // System.out.printf("F 22-Jan-2008 2454488.0649868953 %.8f\n", // phase(2454488.0649868953)); // System.out.printf("N 07-Mar-2008 2454533.2179779503 %.8f\n", // phase(2454533.2179779503)); // System.out.printf("F 21-Mar-2008 2454547.2769324942 %.8f\n", // phase(2454547.2769324942)); // System.out.printf("N 27-Dec-2008 2454828.0159972804 %.8f\n", // phase(2454828.0159972804)); // System.out.printf("F 11-Jan-2009 2454842.6434176303 %.8f\n", // phase(2454842.6434176303)); // System.out.printf("N 07-Mar-2008 2454533.2179779503 %.8f\n", // phase(2454533.2179779503)); private static Calendar adjustTimeZone(Calendar c, int offsetInHours) { long currTime = c.getTime().getTime(); c.setTime(new Date(currTime + offsetInHours * 1000 * 60 * 60)); return c; } public int getCurrentTimeZone() { return TimeZone.getDefault().getRawOffset() / 1000 * 60 * 60; } }
8080_3
/* * Copyright (c) 2016. * * This file is part of Project AGI. <http://agi.io> * * Project AGI 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. * * Project AGI 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 Project AGI. If not, see <http://www.gnu.org/licenses/>. */ /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package io.agi.core.sdr; import io.agi.core.data.Data; import io.agi.core.data.Data2d; import io.agi.core.orm.AbstractPair; import java.awt.*; /** * Encodes to binary matrix by encoding values as subsets of bits. * <p/> * The properties of SDRs are that similar input should have similar bits. * So there must be some redundancy - you can't have one bit per feature. * <p/> * This encoder assumes that each scalar input is represented as an array * of bits. * <p/> * This is an adaptation of the Nupic ScalarEncoder * https://github.com/numenta/nupic/wiki/Encoders * * @author dave */ public class ScalarEncoder implements SparseDistributedEncoder { public boolean _encodeZero = false; public int _bits = 0; public int _density = 0; public ScalarEncoder() { } public void setup( int bits, int density, boolean encodeZero ) { _bits = bits; _density = density; _encodeZero = encodeZero; } public int getBins() { // density = 2 bits = 4 // 1100 0110 0011 = 3 bins = 4-2 +1 // density = 2 bits = 5 // 11000 01100 00110 00011 = 4 bins = 5-2 +1 // density = 3 bits = 5 // 11100 01110 00111 = 3 bins = 5-3 +1 = 3 // density = 3 bits = 8 // 1110 0000 // 0111 0000 // 0011 1000 // 0001 1100 // 0000 1110 // 0000 0111 = 6 bins = 8-3 +1 = 6 return _bits - _density + 1; } @Override public Data createEncodingOutput( Data encodingInput ) { int inputs = encodingInput.getSize(); // Force the dimensions into a 2d (rectangular) shape. // Increase width to cope with extra bits. Point size = Data2d.getSize( encodingInput ); // Dimensions.DIMENSION_X, outputs int w = size.x * _bits; int h = size.y; Data encodingOutput = new Data( w, h ); return encodingOutput; } @Override public Data createDecodingOutput( Data encodingInput, Data decodingInput ) { int inputs = decodingInput.getSize(); // Assuming the same type of encoder did the encoding, we can reverse the geometric changes. // However, we assume the input was 2d Point size = Data2d.getSize( decodingInput ); // Dimensions.DIMENSION_X, outputs int w = size.x / _bits; int h = size.y; Data decodingOutput = new Data( w, h ); return decodingOutput; } @Override public void encode( Data encodingInput, Data encodingOutput ) { int inputs = encodingInput.getSize(); int bins = getBins(); for( int i = 0; i < inputs; ++i ) { float inputValue = encodingInput._values[ i ]; int offset = i * _bits; if( ( !_encodeZero ) && ( inputValue == 0.f ) ) { for( int b = 0; b < _bits; ++b ) { encodingOutput._values[ offset + b ] = 0.f; } continue; } // density = 2 bits = 5 // possible patterns are: // 11000 // 01100 // 00110 // 00011 = 4 possible bins = 5-2 +1 = 4 // // density = 3 bits = 8 // 1110 0000 // 0111 0000 // 0011 1000 // 0001 1100 // 0000 1110 // 0000 0111 = 6 bins = 8-3 +1 = 6 // 0 0.25 0.5 0.75 // 0 * 4 = [0,2) // 0.24 * 4 = [0,2) // 0.25 * 4 = [1,3) // 0.49 * 4 = [1,3) // 0.5 * 4 = [2,4) // 0.75 * 4 = [3,5) // 0.99 * 4 = [3,5) // 1 * 4 = [4,5) <-- bad, so limit it float bin = inputValue * ( float ) bins; int bin1 = Math.min( bins-1, (int)bin ); // captured case where value is 1. int bin2 = bin1 + _density; // excluding this value for( int b = 0; b < _bits; ++b ) { float bitValue = 0.f; if( ( b < bin2 ) && ( b >= bin1 ) ) { bitValue = 1.f; } encodingOutput._values[ offset + b ] = bitValue; } } } @Override public void decode( Data decodingInput, Data decodingOutput ) { // computes the decode by taking the mean position of the encoded '1' bits. // e.g. // density = 2 bits = 5 // 11000 01100 00110 00011 = 4 bins = 5-2 +1 // //Example: A scalar encoder with a range from 0 to 100 with n=12 and w=3 will //produce the following encoders: // //1 becomes 111000000000 //7 becomes 111000000000 //15 becomes 011100000000 //36 becomes 000111000000 int inputs = decodingInput.getSize(); int outputs = inputs / _bits; int bins = getBins(); float reciprocalBits = 1.f / (float)_bits; float denominatorBits = (float)( Math.max( 1, _bits -1 ) ); for( int i = 0; i < outputs; ++i ) { float output = 0.f; if( _bits == 1 ) { float bitValue = decodingInput._values[ i ]; if( bitValue > 0.f ) { output = 1.f; } } else { int offset = i * _bits; float sum = 0.f; float count = 0.f; for( int b = 0; b < _bits; ++b ) { float bitValue = decodingInput._values[ offset + b ]; if( bitValue < 1.f ) { continue; } // density = 1 bits = 1 // possible patterns are: bit / (bits-1) // 0 00000 0/1 = 0 // 1 = 1 possible bins 00001 1/1 = 1 // // density = 2 bits = 5 // possible patterns are: bit / (bits-1) // 11000 10000 0/4 = 0.0 // 01100 01000 1/4 = 0.25 // 00110 00100 2/4 = 0.5 // 00011 = 4 possible bins = 5-2 +1 = 4 00010 3/4 = 0.75 // 00001 4/4 = 1.0 // density = 3 bits = 8 // 1110 0000 0/7 = 0.0 // 0111 0000 1/7 = 0.14 // 0011 1000 2/7 = 0.28 // 0001 1100 3/7 = 0.42 // 0000 1110 4/7 = 0.57 // 0000 0111 = 6 bins = 8-3 +1 = 6 5/7 = 0.71 // 6/7 = 0.85 // 7/7 = 1.0 float bitWeight = ( float ) b / denominatorBits; // so between zero and 1 inclusive sum += bitWeight; count += 1.f; } // e.g. 11000 = 0.0 + 0.25 / 2 = 0.125 // e.g. 00011 = 0.75 + 1.0 / 2 = 0.875 // e.g. 1110 0000 = 0.0 + 0.14 + 0.28 / 3 = 0.14 0.14 would've been encoded as 0.14*(6) = 0.84 = bin 0,1,2 float meanBit = 0.f; if( count > 0.f ) { meanBit = sum / count; // mean } output = meanBit * reciprocalBits; } decodingOutput._values[ i ] = output; } } }
Cerenaut/agi
code/core/src/main/java/io/agi/core/sdr/ScalarEncoder.java
2,724
// density = 2 bits = 4
line_comment
nl
/* * Copyright (c) 2016. * * This file is part of Project AGI. <http://agi.io> * * Project AGI 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. * * Project AGI 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 Project AGI. If not, see <http://www.gnu.org/licenses/>. */ /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package io.agi.core.sdr; import io.agi.core.data.Data; import io.agi.core.data.Data2d; import io.agi.core.orm.AbstractPair; import java.awt.*; /** * Encodes to binary matrix by encoding values as subsets of bits. * <p/> * The properties of SDRs are that similar input should have similar bits. * So there must be some redundancy - you can't have one bit per feature. * <p/> * This encoder assumes that each scalar input is represented as an array * of bits. * <p/> * This is an adaptation of the Nupic ScalarEncoder * https://github.com/numenta/nupic/wiki/Encoders * * @author dave */ public class ScalarEncoder implements SparseDistributedEncoder { public boolean _encodeZero = false; public int _bits = 0; public int _density = 0; public ScalarEncoder() { } public void setup( int bits, int density, boolean encodeZero ) { _bits = bits; _density = density; _encodeZero = encodeZero; } public int getBins() { // density =<SUF> // 1100 0110 0011 = 3 bins = 4-2 +1 // density = 2 bits = 5 // 11000 01100 00110 00011 = 4 bins = 5-2 +1 // density = 3 bits = 5 // 11100 01110 00111 = 3 bins = 5-3 +1 = 3 // density = 3 bits = 8 // 1110 0000 // 0111 0000 // 0011 1000 // 0001 1100 // 0000 1110 // 0000 0111 = 6 bins = 8-3 +1 = 6 return _bits - _density + 1; } @Override public Data createEncodingOutput( Data encodingInput ) { int inputs = encodingInput.getSize(); // Force the dimensions into a 2d (rectangular) shape. // Increase width to cope with extra bits. Point size = Data2d.getSize( encodingInput ); // Dimensions.DIMENSION_X, outputs int w = size.x * _bits; int h = size.y; Data encodingOutput = new Data( w, h ); return encodingOutput; } @Override public Data createDecodingOutput( Data encodingInput, Data decodingInput ) { int inputs = decodingInput.getSize(); // Assuming the same type of encoder did the encoding, we can reverse the geometric changes. // However, we assume the input was 2d Point size = Data2d.getSize( decodingInput ); // Dimensions.DIMENSION_X, outputs int w = size.x / _bits; int h = size.y; Data decodingOutput = new Data( w, h ); return decodingOutput; } @Override public void encode( Data encodingInput, Data encodingOutput ) { int inputs = encodingInput.getSize(); int bins = getBins(); for( int i = 0; i < inputs; ++i ) { float inputValue = encodingInput._values[ i ]; int offset = i * _bits; if( ( !_encodeZero ) && ( inputValue == 0.f ) ) { for( int b = 0; b < _bits; ++b ) { encodingOutput._values[ offset + b ] = 0.f; } continue; } // density = 2 bits = 5 // possible patterns are: // 11000 // 01100 // 00110 // 00011 = 4 possible bins = 5-2 +1 = 4 // // density = 3 bits = 8 // 1110 0000 // 0111 0000 // 0011 1000 // 0001 1100 // 0000 1110 // 0000 0111 = 6 bins = 8-3 +1 = 6 // 0 0.25 0.5 0.75 // 0 * 4 = [0,2) // 0.24 * 4 = [0,2) // 0.25 * 4 = [1,3) // 0.49 * 4 = [1,3) // 0.5 * 4 = [2,4) // 0.75 * 4 = [3,5) // 0.99 * 4 = [3,5) // 1 * 4 = [4,5) <-- bad, so limit it float bin = inputValue * ( float ) bins; int bin1 = Math.min( bins-1, (int)bin ); // captured case where value is 1. int bin2 = bin1 + _density; // excluding this value for( int b = 0; b < _bits; ++b ) { float bitValue = 0.f; if( ( b < bin2 ) && ( b >= bin1 ) ) { bitValue = 1.f; } encodingOutput._values[ offset + b ] = bitValue; } } } @Override public void decode( Data decodingInput, Data decodingOutput ) { // computes the decode by taking the mean position of the encoded '1' bits. // e.g. // density = 2 bits = 5 // 11000 01100 00110 00011 = 4 bins = 5-2 +1 // //Example: A scalar encoder with a range from 0 to 100 with n=12 and w=3 will //produce the following encoders: // //1 becomes 111000000000 //7 becomes 111000000000 //15 becomes 011100000000 //36 becomes 000111000000 int inputs = decodingInput.getSize(); int outputs = inputs / _bits; int bins = getBins(); float reciprocalBits = 1.f / (float)_bits; float denominatorBits = (float)( Math.max( 1, _bits -1 ) ); for( int i = 0; i < outputs; ++i ) { float output = 0.f; if( _bits == 1 ) { float bitValue = decodingInput._values[ i ]; if( bitValue > 0.f ) { output = 1.f; } } else { int offset = i * _bits; float sum = 0.f; float count = 0.f; for( int b = 0; b < _bits; ++b ) { float bitValue = decodingInput._values[ offset + b ]; if( bitValue < 1.f ) { continue; } // density = 1 bits = 1 // possible patterns are: bit / (bits-1) // 0 00000 0/1 = 0 // 1 = 1 possible bins 00001 1/1 = 1 // // density = 2 bits = 5 // possible patterns are: bit / (bits-1) // 11000 10000 0/4 = 0.0 // 01100 01000 1/4 = 0.25 // 00110 00100 2/4 = 0.5 // 00011 = 4 possible bins = 5-2 +1 = 4 00010 3/4 = 0.75 // 00001 4/4 = 1.0 // density = 3 bits = 8 // 1110 0000 0/7 = 0.0 // 0111 0000 1/7 = 0.14 // 0011 1000 2/7 = 0.28 // 0001 1100 3/7 = 0.42 // 0000 1110 4/7 = 0.57 // 0000 0111 = 6 bins = 8-3 +1 = 6 5/7 = 0.71 // 6/7 = 0.85 // 7/7 = 1.0 float bitWeight = ( float ) b / denominatorBits; // so between zero and 1 inclusive sum += bitWeight; count += 1.f; } // e.g. 11000 = 0.0 + 0.25 / 2 = 0.125 // e.g. 00011 = 0.75 + 1.0 / 2 = 0.875 // e.g. 1110 0000 = 0.0 + 0.14 + 0.28 / 3 = 0.14 0.14 would've been encoded as 0.14*(6) = 0.84 = bin 0,1,2 float meanBit = 0.f; if( count > 0.f ) { meanBit = sum / count; // mean } output = meanBit * reciprocalBits; } decodingOutput._values[ i ] = output; } } }
174333_3
package nl.cerios.cerioscoop.service; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Time; import java.util.ArrayList; import java.util.List; import java.util.Random; import javax.annotation.Resource; import javax.ejb.Stateless; import javax.sql.DataSource; import nl.cerios.cerioscoop.ValueObjects.ShowPresentationVO; import nl.cerios.cerioscoop.ValueObjects.ShowsPresentationVO; import nl.cerios.cerioscoop.domain.Customer; import nl.cerios.cerioscoop.domain.Movie; import nl.cerios.cerioscoop.domain.MovieBuilder; import nl.cerios.cerioscoop.domain.Show; import nl.cerios.cerioscoop.domain.User; import nl.cerios.cerioscoop.util.DateUtils; @Stateless //Stateless is de status van de gevulde opjecten. Best Practice is stateless. public class GeneralService { @Resource(name = "jdbc/cerioscoop") //Content Dependency Injection techniek private DataSource dataSource; private DateUtils dateUtils = new DateUtils(); public List<Movie> getMovies(){ final List<Movie> movies = new ArrayList<>(); try (final Connection connection = dataSource.getConnection()) { //AutoCloseable final Statement statement = connection.createStatement(); final ResultSet resultSet = statement.executeQuery("SELECT movie_id, title, movie_description FROM movie"); while (resultSet.next()) { final Movie movie = new MovieBuilder() .withMovieId(resultSet.getBigDecimal("movie_id").toBigInteger()) .withMovieTitle(resultSet.getString("title")) .withMovieDescription(resultSet.getString("movie_description")) .build(); movies.add(movie); } return movies; }catch (final SQLException e) { throw new ServiceException("Something went terribly wrong while retrieving the movie.", e); } } public List<Show> getShows(){ final List<Show> shows = new ArrayList<>(); try (final Connection connection = dataSource.getConnection()){ final Statement statement = connection.createStatement(); final ResultSet resultSet = statement.executeQuery("SELECT show_id, movie_id, room_id, show_date, show_time, available_places, show_price FROM show_table"); { while (resultSet.next()) { final int showId = resultSet.getInt("show_id"); final int movieId = resultSet.getInt("movie_id"); final int roomId = resultSet.getInt("room_id"); final Date showDate = resultSet.getDate("show_date"); final Time showTime = resultSet.getTime("show_time"); final int availablePlaces = resultSet.getInt("available_places"); final float showPrice = resultSet.getInt("show_price"); shows.add(new Show(showId, movieId, roomId, showDate, showTime, availablePlaces, showPrice)); } return shows; } }catch (final SQLException e) { throw new ServiceException("Something went terribly wrong while retrieving the first date.", e); } } public List<Customer> getCustomers(){ final List<Customer> customers = new ArrayList<>(); try (final Connection connection = dataSource.getConnection()){ final Statement statement = connection.createStatement(); final ResultSet resultSet = statement.executeQuery("SELECT customer_id, first_name, last_name, username, password, email FROM customer"); { while (resultSet.next()) { final int customerId = resultSet.getInt("customer_id"); final String firstName = resultSet.getString("first_name"); final String lastName = resultSet.getString("last_name"); final String username = resultSet.getString("username"); final String password = resultSet.getString("password"); final String email = resultSet.getString("email"); customers.add(new Customer(customerId, firstName, lastName, username, password, email)); } return customers; } }catch (final SQLException e) { throw new ServiceException("Something went terribly wrong while retrieving the customers.", e); } } /** * Returns a first showing record. * * @return firstShowing */ public Show getFirstShowforToday(final List<Show> listOfShows){ Show firstShow = null; for (final Show show : listOfShows) { if(dateUtils.toDateTime(show.getShowDate(), show.getShowTime()).after(dateUtils.getCurrentSqlTime())){ if(firstShow == null){ //hier wordt voor 1x eerstVolgendeFilm gevuld firstShow = show; } else if(show.getShowTime().before(firstShow.getShowTime())){ firstShow = show; } } } return firstShow; } public Movie getMovieByMovieId(final int movieId, final List<Movie> listOfMovies) throws MovieNotFoundException { final List<Movie> movies = listOfMovies; Movie movieByMovieId = null; for (final Movie movieItem : movies){ if (movieItem.getMovieId().intValue() == movieId) { movieByMovieId = movieItem; } } return movieByMovieId; } public void registerCustomer(final Customer customer){ try (final Connection connection = dataSource.getConnection(); final PreparedStatement preparedStatement = connection.prepareStatement( "INSERT INTO customer (first_name, last_name, username, password, email) VALUES (?,?,?,?,?)")) { preparedStatement.setString(1, customer.getFirstName()); preparedStatement.setString(2, customer.getLastName()); preparedStatement.setString(3, customer.getUsername()); preparedStatement.setString(4, customer.getPassword()); preparedStatement.setString(5, customer.getEmail()); preparedStatement.executeUpdate(); System.out.println("Data inserted."); }catch (final SQLException e) { throw new ServiceException("Something went wrong while inserting the customer items.", e); } } public User authenticateCustomer(User customer, List<Customer> listOfCustomers){ final List<Customer> dbCustomers = listOfCustomers; final String usernameCustomer = customer.getUsername(); final String passwordCustomer = customer.getPassword(); User authenticatedCustomer = null; for (final Customer customerItem : dbCustomers){ if(customerItem.getUsername().equals(usernameCustomer) && customerItem.getPassword().equals(passwordCustomer)){ authenticatedCustomer = customerItem; } } return authenticatedCustomer; } public Boolean authenticateUser(User authenticatedUser){ if(authenticatedUser == null){ return false; } return true; } public List<ShowsPresentationVO> generateShowTable(final List<Show> shows, final List<Movie> movies) throws MovieNotFoundException { List<ShowsPresentationVO> todaysShowsTable = new ArrayList<ShowsPresentationVO>(); // voeg alle shows toe aan de tabel for (Show todaysShow : shows) { ShowsPresentationVO existingShowsPresentationVORow = null; // checkt of de movie van de huidige tabel al is opgenomen for (ShowsPresentationVO showsRowIter : todaysShowsTable) { if (todaysShow.getMovieId() == showsRowIter.getMovie().getMovieId().intValue()) {// hier bestaat de movie al in de index ShowPresentationVO newShowPresentationVO = new ShowPresentationVO(); newShowPresentationVO.setShow(todaysShow); newShowPresentationVO.setSoldOut(checkIfThereAreNoAvailablePlaces(todaysShow.getAvailablePlaces())); showsRowIter.shows.add(newShowPresentationVO); existingShowsPresentationVORow = showsRowIter; } } if (existingShowsPresentationVORow == null) {//Nieuwe MovieRow worst gemaakt ShowPresentationVO newShowPresentationVO = new ShowPresentationVO(); newShowPresentationVO.setShow(todaysShow); newShowPresentationVO.setSoldOut(checkIfThereAreNoAvailablePlaces(todaysShow.getAvailablePlaces())); ShowsPresentationVO newShowsPresentationRowVO = new ShowsPresentationVO(); List<ShowPresentationVO> showPresentationVOList = new ArrayList<ShowPresentationVO>(); showPresentationVOList.add(newShowPresentationVO); newShowsPresentationRowVO.setMovie(getMovieByMovieId(todaysShow.getMovieId(), movies)); newShowsPresentationRowVO.setShowsPresentationVO(showPresentationVOList); todaysShowsTable.add(newShowsPresentationRowVO); } } return todaysShowsTable; } public String generateRandomUsername(){ char[] chars = "abcdefghijklmnopqrstuvwxyz1234567890".toCharArray(); StringBuilder sb = new StringBuilder(); Random random = new Random(); for (int i = 0; i < 20; i++) { char c = chars[random.nextInt(chars.length)]; sb.append(c); } return sb.toString(); } public Boolean checkIfThereAreNoAvailablePlaces(int availablePlaces){ if(availablePlaces == 0){ return true; }else{ return false; } } }
Cerios/cerioscoop-web
src/main/java/nl/cerios/cerioscoop/service/GeneralService.java
2,747
//hier wordt voor 1x eerstVolgendeFilm gevuld
line_comment
nl
package nl.cerios.cerioscoop.service; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Time; import java.util.ArrayList; import java.util.List; import java.util.Random; import javax.annotation.Resource; import javax.ejb.Stateless; import javax.sql.DataSource; import nl.cerios.cerioscoop.ValueObjects.ShowPresentationVO; import nl.cerios.cerioscoop.ValueObjects.ShowsPresentationVO; import nl.cerios.cerioscoop.domain.Customer; import nl.cerios.cerioscoop.domain.Movie; import nl.cerios.cerioscoop.domain.MovieBuilder; import nl.cerios.cerioscoop.domain.Show; import nl.cerios.cerioscoop.domain.User; import nl.cerios.cerioscoop.util.DateUtils; @Stateless //Stateless is de status van de gevulde opjecten. Best Practice is stateless. public class GeneralService { @Resource(name = "jdbc/cerioscoop") //Content Dependency Injection techniek private DataSource dataSource; private DateUtils dateUtils = new DateUtils(); public List<Movie> getMovies(){ final List<Movie> movies = new ArrayList<>(); try (final Connection connection = dataSource.getConnection()) { //AutoCloseable final Statement statement = connection.createStatement(); final ResultSet resultSet = statement.executeQuery("SELECT movie_id, title, movie_description FROM movie"); while (resultSet.next()) { final Movie movie = new MovieBuilder() .withMovieId(resultSet.getBigDecimal("movie_id").toBigInteger()) .withMovieTitle(resultSet.getString("title")) .withMovieDescription(resultSet.getString("movie_description")) .build(); movies.add(movie); } return movies; }catch (final SQLException e) { throw new ServiceException("Something went terribly wrong while retrieving the movie.", e); } } public List<Show> getShows(){ final List<Show> shows = new ArrayList<>(); try (final Connection connection = dataSource.getConnection()){ final Statement statement = connection.createStatement(); final ResultSet resultSet = statement.executeQuery("SELECT show_id, movie_id, room_id, show_date, show_time, available_places, show_price FROM show_table"); { while (resultSet.next()) { final int showId = resultSet.getInt("show_id"); final int movieId = resultSet.getInt("movie_id"); final int roomId = resultSet.getInt("room_id"); final Date showDate = resultSet.getDate("show_date"); final Time showTime = resultSet.getTime("show_time"); final int availablePlaces = resultSet.getInt("available_places"); final float showPrice = resultSet.getInt("show_price"); shows.add(new Show(showId, movieId, roomId, showDate, showTime, availablePlaces, showPrice)); } return shows; } }catch (final SQLException e) { throw new ServiceException("Something went terribly wrong while retrieving the first date.", e); } } public List<Customer> getCustomers(){ final List<Customer> customers = new ArrayList<>(); try (final Connection connection = dataSource.getConnection()){ final Statement statement = connection.createStatement(); final ResultSet resultSet = statement.executeQuery("SELECT customer_id, first_name, last_name, username, password, email FROM customer"); { while (resultSet.next()) { final int customerId = resultSet.getInt("customer_id"); final String firstName = resultSet.getString("first_name"); final String lastName = resultSet.getString("last_name"); final String username = resultSet.getString("username"); final String password = resultSet.getString("password"); final String email = resultSet.getString("email"); customers.add(new Customer(customerId, firstName, lastName, username, password, email)); } return customers; } }catch (final SQLException e) { throw new ServiceException("Something went terribly wrong while retrieving the customers.", e); } } /** * Returns a first showing record. * * @return firstShowing */ public Show getFirstShowforToday(final List<Show> listOfShows){ Show firstShow = null; for (final Show show : listOfShows) { if(dateUtils.toDateTime(show.getShowDate(), show.getShowTime()).after(dateUtils.getCurrentSqlTime())){ if(firstShow == null){ //hier wordt<SUF> firstShow = show; } else if(show.getShowTime().before(firstShow.getShowTime())){ firstShow = show; } } } return firstShow; } public Movie getMovieByMovieId(final int movieId, final List<Movie> listOfMovies) throws MovieNotFoundException { final List<Movie> movies = listOfMovies; Movie movieByMovieId = null; for (final Movie movieItem : movies){ if (movieItem.getMovieId().intValue() == movieId) { movieByMovieId = movieItem; } } return movieByMovieId; } public void registerCustomer(final Customer customer){ try (final Connection connection = dataSource.getConnection(); final PreparedStatement preparedStatement = connection.prepareStatement( "INSERT INTO customer (first_name, last_name, username, password, email) VALUES (?,?,?,?,?)")) { preparedStatement.setString(1, customer.getFirstName()); preparedStatement.setString(2, customer.getLastName()); preparedStatement.setString(3, customer.getUsername()); preparedStatement.setString(4, customer.getPassword()); preparedStatement.setString(5, customer.getEmail()); preparedStatement.executeUpdate(); System.out.println("Data inserted."); }catch (final SQLException e) { throw new ServiceException("Something went wrong while inserting the customer items.", e); } } public User authenticateCustomer(User customer, List<Customer> listOfCustomers){ final List<Customer> dbCustomers = listOfCustomers; final String usernameCustomer = customer.getUsername(); final String passwordCustomer = customer.getPassword(); User authenticatedCustomer = null; for (final Customer customerItem : dbCustomers){ if(customerItem.getUsername().equals(usernameCustomer) && customerItem.getPassword().equals(passwordCustomer)){ authenticatedCustomer = customerItem; } } return authenticatedCustomer; } public Boolean authenticateUser(User authenticatedUser){ if(authenticatedUser == null){ return false; } return true; } public List<ShowsPresentationVO> generateShowTable(final List<Show> shows, final List<Movie> movies) throws MovieNotFoundException { List<ShowsPresentationVO> todaysShowsTable = new ArrayList<ShowsPresentationVO>(); // voeg alle shows toe aan de tabel for (Show todaysShow : shows) { ShowsPresentationVO existingShowsPresentationVORow = null; // checkt of de movie van de huidige tabel al is opgenomen for (ShowsPresentationVO showsRowIter : todaysShowsTable) { if (todaysShow.getMovieId() == showsRowIter.getMovie().getMovieId().intValue()) {// hier bestaat de movie al in de index ShowPresentationVO newShowPresentationVO = new ShowPresentationVO(); newShowPresentationVO.setShow(todaysShow); newShowPresentationVO.setSoldOut(checkIfThereAreNoAvailablePlaces(todaysShow.getAvailablePlaces())); showsRowIter.shows.add(newShowPresentationVO); existingShowsPresentationVORow = showsRowIter; } } if (existingShowsPresentationVORow == null) {//Nieuwe MovieRow worst gemaakt ShowPresentationVO newShowPresentationVO = new ShowPresentationVO(); newShowPresentationVO.setShow(todaysShow); newShowPresentationVO.setSoldOut(checkIfThereAreNoAvailablePlaces(todaysShow.getAvailablePlaces())); ShowsPresentationVO newShowsPresentationRowVO = new ShowsPresentationVO(); List<ShowPresentationVO> showPresentationVOList = new ArrayList<ShowPresentationVO>(); showPresentationVOList.add(newShowPresentationVO); newShowsPresentationRowVO.setMovie(getMovieByMovieId(todaysShow.getMovieId(), movies)); newShowsPresentationRowVO.setShowsPresentationVO(showPresentationVOList); todaysShowsTable.add(newShowsPresentationRowVO); } } return todaysShowsTable; } public String generateRandomUsername(){ char[] chars = "abcdefghijklmnopqrstuvwxyz1234567890".toCharArray(); StringBuilder sb = new StringBuilder(); Random random = new Random(); for (int i = 0; i < 20; i++) { char c = chars[random.nextInt(chars.length)]; sb.append(c); } return sb.toString(); } public Boolean checkIfThereAreNoAvailablePlaces(int availablePlaces){ if(availablePlaces == 0){ return true; }else{ return false; } } }
108587_0
package com.Code.Pakket.management.service; import com.Code.Pakket.management.exceptions.PakketjeNietGevondenException; import com.Code.Pakket.management.model.Bedrijf; import com.Code.Pakket.management.model.Pakketje; import com.Code.Pakket.management.repository.PakketjeRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import java.util.List; //De Service communiceert met de JPA repository om database operations uit te voeren. @Service public class PakketjeServiceImplimentation implements PakketjeService { // @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection") @Autowired private PakketjeRepository pakketjeRepository; public PakketjeServiceImplimentation(PakketjeRepository pakketjeRepository) { } @Override public Pakketje pakketjeOpslaan(Pakketje pakketje) { return pakketjeRepository.save(pakketje); } @Override public List<Pakketje> getAllePakketjes() { return pakketjeRepository.findAll(); } public List<Pakketje> getAllePakketjesBezorgdByStatus(String status){ return pakketjeRepository.getAllePakketjesBezorgdByStatus(status); } @Override public Pakketje getPakketjeById(int id) { return pakketjeRepository.findById(id).orElse(null); } @Override public void verwijderPakketje(Pakketje pakketje) { this.pakketjeRepository.delete(pakketje); } }
Cezarpop12/PakketManagementBackendMain
src/main/java/com/Code/Pakket/management/service/PakketjeServiceImplimentation.java
520
//De Service communiceert met de JPA repository om database operations uit te voeren.
line_comment
nl
package com.Code.Pakket.management.service; import com.Code.Pakket.management.exceptions.PakketjeNietGevondenException; import com.Code.Pakket.management.model.Bedrijf; import com.Code.Pakket.management.model.Pakketje; import com.Code.Pakket.management.repository.PakketjeRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import java.util.List; //De Service<SUF> @Service public class PakketjeServiceImplimentation implements PakketjeService { // @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection") @Autowired private PakketjeRepository pakketjeRepository; public PakketjeServiceImplimentation(PakketjeRepository pakketjeRepository) { } @Override public Pakketje pakketjeOpslaan(Pakketje pakketje) { return pakketjeRepository.save(pakketje); } @Override public List<Pakketje> getAllePakketjes() { return pakketjeRepository.findAll(); } public List<Pakketje> getAllePakketjesBezorgdByStatus(String status){ return pakketjeRepository.getAllePakketjesBezorgdByStatus(status); } @Override public Pakketje getPakketjeById(int id) { return pakketjeRepository.findById(id).orElse(null); } @Override public void verwijderPakketje(Pakketje pakketje) { this.pakketjeRepository.delete(pakketje); } }
82214_8
/* * Copyright (C) 2012-2019 Jorrit "Chainfire" Jongma * * 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 eu.chainfire.libsuperuser; import android.content.Context; import android.os.Handler; import android.widget.Toast; import androidx.annotation.AnyThread; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /** * Base application class to extend from, solving some issues with * toasts and AsyncTasks you are likely to run into */ @SuppressWarnings("WeakerAccess") public class Application extends android.app.Application { /** * Shows a toast message * * @param context Any context belonging to this application * @param message The message to show */ @AnyThread public static void toast(@Nullable Context context, @NonNull String message) { // this is a static method so it is easier to call, // as the context checking and casting is done for you if (context == null) return; if (!(context instanceof Application)) { context = context.getApplicationContext(); } if (context instanceof Application) { final Context c = context; final String m = message; ((Application) context).runInApplicationThread(new Runnable() { @Override public void run() { Toast.makeText(c, m, Toast.LENGTH_LONG).show(); } }); } } private static final Handler mApplicationHandler = new Handler(); /** * Run a runnable in the main application thread * * @param r Runnable to run */ @AnyThread public void runInApplicationThread(@NonNull Runnable r) { mApplicationHandler.post(r); } @Override public void onCreate() { super.onCreate(); try { // workaround bug in AsyncTask, can show up (for example) when you toast from a service // this makes sure AsyncTask's internal handler is created from the right (main) thread Class.forName("android.os.AsyncTask"); } catch (ClassNotFoundException e) { // will never happen } } }
Chainfire/libsuperuser
libsuperuser/src/eu/chainfire/libsuperuser/Application.java
689
// will never happen
line_comment
nl
/* * Copyright (C) 2012-2019 Jorrit "Chainfire" Jongma * * 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 eu.chainfire.libsuperuser; import android.content.Context; import android.os.Handler; import android.widget.Toast; import androidx.annotation.AnyThread; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /** * Base application class to extend from, solving some issues with * toasts and AsyncTasks you are likely to run into */ @SuppressWarnings("WeakerAccess") public class Application extends android.app.Application { /** * Shows a toast message * * @param context Any context belonging to this application * @param message The message to show */ @AnyThread public static void toast(@Nullable Context context, @NonNull String message) { // this is a static method so it is easier to call, // as the context checking and casting is done for you if (context == null) return; if (!(context instanceof Application)) { context = context.getApplicationContext(); } if (context instanceof Application) { final Context c = context; final String m = message; ((Application) context).runInApplicationThread(new Runnable() { @Override public void run() { Toast.makeText(c, m, Toast.LENGTH_LONG).show(); } }); } } private static final Handler mApplicationHandler = new Handler(); /** * Run a runnable in the main application thread * * @param r Runnable to run */ @AnyThread public void runInApplicationThread(@NonNull Runnable r) { mApplicationHandler.post(r); } @Override public void onCreate() { super.onCreate(); try { // workaround bug in AsyncTask, can show up (for example) when you toast from a service // this makes sure AsyncTask's internal handler is created from the right (main) thread Class.forName("android.os.AsyncTask"); } catch (ClassNotFoundException e) { // will never<SUF> } } }
43856_52
package nl.eti1b5.database.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import nl.eti1b5.database.DatabaseManager; import nl.eti1b5.model.Materiaal; import nl.eti1b5.model.Reparatie; /** * Data access object wat de reparatie tabel beheert in de database * Haalt de gegevens van een reparatie op en schrijft ze weg naar de database * * @author Projectgroep ETI2b3 2014-2015 kwartiel 1 * @since 22 okt. 2014 */ public class ReparatieDao { // Databasemanager met de connectie naar de database private DatabaseManager manager; /** * Constructor voor het ophalen van de singleton instantie van de databasemanager */ public ReparatieDao() { manager = DatabaseManager.getInstance(); } /** * Constructor voor het meegegeven van de singleton instantie van de databasemanager * @param manager Singleton instantie van de databasemanager */ public ReparatieDao(DatabaseManager manager) { this.manager = manager; } /** * Methode voor het opvragen van alle reparaties uit de database * @return een lijst met alle reparaties */ public ArrayList<Reparatie> getReparaties() { // Lijst met de resultaten van de query ArrayList<Reparatie> reparatieLijst = new ArrayList<>(); // De connectie met de database op Connection connection = manager.getConnection(); // De te execturen sql querys try { // Query die alle gegevens uit de tabel reparatie haalt String reparatieQuery = "select * from reparatie " + "natural join omschrijving"; PreparedStatement reparatieStatement = connection.prepareStatement(reparatieQuery); ResultSet reparatieSet = reparatieStatement.executeQuery(); // Zolang er nog gegevens in de tabel staan while(reparatieSet.next()) { // De gegevens van een rij int reparatieNummer = reparatieSet.getInt("Reparatienr"); String kenteken = reparatieSet.getString("Kenteken"); int omschrijvingsNummer = reparatieSet.getInt("Omschrijvingsnr"); Timestamp begintijd = reparatieSet.getTimestamp("Begintijd"); Timestamp eindtijd = reparatieSet.getTimestamp("EindTijd"); boolean reparatiestatus = reparatieSet.getBoolean("Reparatiestatus"); boolean betaalstatus = reparatieSet.getBoolean("Betaalstatus"); // Query die alle materiaalnummer uit de koppeltabel haalt String materiaalNummersQuery = "select * from ReparatieMateriaal " + "inner join materiaal " + "on reparatieMateriaal.Materiaalnr = Materiaal.materiaalnr " + "where Reparatienr = ?"; PreparedStatement materiaalNummersStatement = connection.prepareStatement(materiaalNummersQuery); materiaalNummersStatement.setInt(1, reparatieNummer); ResultSet materiaalNummerSet = materiaalNummersStatement.executeQuery(); ArrayList<Materiaal> materialenLijst = new ArrayList<>(); while(materiaalNummerSet.next()){ int materiaalNummer = materiaalNummerSet.getInt("Materiaalnr"); int aantalgebruikt = materiaalNummerSet.getInt("Aantalgebruikt"); String naam = materiaalNummerSet.getString("Naam"); double prijs = materiaalNummerSet.getDouble("Prijs"); materialenLijst.add(new Materiaal(materiaalNummer, naam, prijs, aantalgebruikt)); } reparatieLijst.add(new Reparatie(reparatieNummer, kenteken, omschrijvingsNummer, begintijd, eindtijd, reparatiestatus, betaalstatus, materialenLijst)); } } catch (SQLException e) { System.err.println("Kan het statement niet uitvoeren"); e.printStackTrace(); } // Sluit de verbinding met de database manager.closeConnection(); // Geeft de lijst met reparaties terug return reparatieLijst; } /** * Methode voor het opvragen van alle reparaties die verbonden zijn aan een werknemer. * @param werknemerNummer Het nummer van de werknemer waarvan de reparaties moeten worden opgevraagd * @return een lijst met alle reparaties van de werknemer */ public ArrayList<Reparatie> eigenReparaties(int werknemerNummer) { // Lijst met de resultaten van de query ArrayList<Reparatie> reparatieLijst = new ArrayList<>(); // De connectie met de database op Connection connection = manager.getConnection(); // De te execturen sql querys try { // Query die alle gegevens uit de tabel reparatie haalt String reparatieQuery = "Select * from reparatie " + "Inner Join planning " + "on reparatie.reparatieNr = planning.reparatieNr " + "where werknemernr = "+ werknemerNummer; PreparedStatement reparatieStatement = connection.prepareStatement(reparatieQuery); ResultSet reparatieSet = reparatieStatement.executeQuery(); // Zolang er nog gegevens in de tabel staan while(reparatieSet.next()) { // De gegevens van een rij int reparatieNummer = reparatieSet.getInt("Reparatienr"); String kenteken = reparatieSet.getString("Kenteken"); int omschrijvingsNummer = reparatieSet.getInt("Omschrijvingsnr"); Timestamp begintijd = reparatieSet.getTimestamp("Begintijd"); Timestamp eindtijd = reparatieSet.getTimestamp("EindTijd"); boolean reparatiestatus = reparatieSet.getBoolean("Reparatiestatus"); boolean betaalstatus = reparatieSet.getBoolean("Betaalstatus"); // Query die alle materiaalnummer uit de koppeltabel haalt String materiaalNummersQuery = "select * from ReparatieMateriaal " + "natural join omschrijving " + "inner join materiaal " + "on reparatieMateriaal.Materiaalnr = Materiaal.materiaalnr " + "where Reparatienr = ?"; PreparedStatement materiaalNummersStatement = connection.prepareStatement(materiaalNummersQuery); materiaalNummersStatement.setInt(1, reparatieNummer); ResultSet materiaalNummerSet = materiaalNummersStatement.executeQuery(); ArrayList<Materiaal> materialenLijst = new ArrayList<>(); while(materiaalNummerSet.next()){ int materiaalNummer = materiaalNummerSet.getInt("Materiaalnr"); int aantalgebruikt = materiaalNummerSet.getInt("Aantalgebruikt"); String naam = materiaalNummerSet.getString("Naam"); double prijs = materiaalNummerSet.getDouble("Prijs"); materialenLijst.add(new Materiaal(materiaalNummer, naam, prijs, aantalgebruikt)); } reparatieLijst.add(new Reparatie(reparatieNummer, kenteken, omschrijvingsNummer, begintijd, eindtijd, reparatiestatus, betaalstatus, materialenLijst)); } } catch (SQLException e) { System.err.println("Kan het statement niet uitvoeren"); e.printStackTrace(); } // Sluit de verbinding met de database manager.closeConnection(); // Geeft de lijst met reparaties terug return reparatieLijst; } /** * Methode voor het opvragen van een reparatie aan de hand van het reparatienummer * @param reparatienr Het nummer van de reparatie die moet worden opgevraagd * @return de reparaties */ public Reparatie getReparatie(int reparatienr) { Reparatie reparatie = null; // De connectie met de database op Connection connection = manager.getConnection(); // De te execturen sql querys try { // Query die alle gegevens uit de tabel reparatie haalt String reparatieQuery = "select * from reparatie " + "where reparatienr = ?"; PreparedStatement reparatieStatement = connection.prepareStatement(reparatieQuery); reparatieStatement.setInt(1, reparatienr); ResultSet reparatieSet = reparatieStatement.executeQuery(); // Zolang er nog gegevens in de tabel staan while(reparatieSet.next()) { // De gegevens van een rij int reparatieNummer = reparatieSet.getInt("Reparatienr"); String kenteken = reparatieSet.getString("Kenteken"); int omschrijvingsNummer = reparatieSet.getInt("Omschrijvingsnr"); Timestamp begintijd = reparatieSet.getTimestamp("Begintijd"); Timestamp eindtijd = reparatieSet.getTimestamp("EindTijd"); boolean reparatiestatus = reparatieSet.getBoolean("Reparatiestatus"); boolean betaalstatus = reparatieSet.getBoolean("Betaalstatus"); // Query die alle materiaalnummer uit de koppeltabel haalt String materiaalNummersQuery = "select * from ReparatieMateriaal " + "inner join materiaal " + "on reparatieMateriaal.Materiaalnr = Materiaal.materiaalnr " + "where Reparatienr = ?"; PreparedStatement materiaalNummersStatement = connection.prepareStatement(materiaalNummersQuery); materiaalNummersStatement.setInt(1, reparatieNummer); ResultSet materiaalNummerSet = materiaalNummersStatement.executeQuery(); ArrayList<Materiaal> materialenLijst = new ArrayList<>(); while(materiaalNummerSet.next()){ int materiaalNummer = materiaalNummerSet.getInt("Materiaalnr"); int aantalgebruikt = materiaalNummerSet.getInt("Aantalgebruikt"); String naam = materiaalNummerSet.getString("Naam"); double prijs = materiaalNummerSet.getDouble("Prijs"); materialenLijst.add(new Materiaal(materiaalNummer, naam, prijs, aantalgebruikt)); } reparatie = new Reparatie(reparatieNummer, kenteken, omschrijvingsNummer, begintijd, eindtijd, reparatiestatus, betaalstatus, materialenLijst); } } catch (SQLException e) { System.err.println("Kan het statement niet uitvoeren"); e.printStackTrace(); } return reparatie; } /** * Methode voor het opvragen van de reparaties horende bij een klant * @param klantnr Het nummer van de klant waarvan de reparaties moeten worden opgehaald * @param betaald Boolean of de op te halen reparatie wel of niet betaald moeten zijn * @return een lijst met de reparaties horende bij een klant. */ public ArrayList<Reparatie> getKlantReparaties(int klantnr, boolean betaald) { ArrayList<Reparatie> reparatieLijst = new ArrayList<>(); // De connectie met de database op Connection connection = manager.getConnection(); // De te execturen sql querys try { // Query die alle gegevens uit de tabel reparatie haalt String reparatieQuery = "select * from reparatie " + "natural join auto " + "where klantnr = ? and betaalstatus = ?"; PreparedStatement reparatieStatement = connection.prepareStatement(reparatieQuery); reparatieStatement.setInt(1, klantnr); reparatieStatement.setBoolean(2, betaald); ResultSet reparatieSet = reparatieStatement.executeQuery(); // Zolang er nog gegevens in de tabel staan while(reparatieSet.next()) { // De gegevens van een rij int reparatieNummer = reparatieSet.getInt("Reparatienr"); String kenteken = reparatieSet.getString("Kenteken"); int omschrijvingsNummer = reparatieSet.getInt("Omschrijvingsnr"); Timestamp begintijd = reparatieSet.getTimestamp("Begintijd"); Timestamp eindtijd = reparatieSet.getTimestamp("EindTijd"); boolean reparatiestatus = reparatieSet.getBoolean("Reparatiestatus"); boolean betaalstatus = reparatieSet.getBoolean("Betaalstatus"); // Query die alle materiaalnummer uit de koppeltabel haalt String materiaalNummersQuery = "select * from ReparatieMateriaal " + "inner join materiaal " + "on reparatieMateriaal.Materiaalnr = Materiaal.materiaalnr " + "where Reparatienr = ?"; PreparedStatement materiaalNummersStatement = connection.prepareStatement(materiaalNummersQuery); materiaalNummersStatement.setInt(1, reparatieNummer); ResultSet materiaalNummerSet = materiaalNummersStatement.executeQuery(); ArrayList<Materiaal> materialenLijst = new ArrayList<>(); while(materiaalNummerSet.next()){ int materiaalNummer = materiaalNummerSet.getInt("Materiaalnr"); int aantalgebruikt = materiaalNummerSet.getInt("Aantalgebruikt"); String naam = materiaalNummerSet.getString("Naam"); double prijs = materiaalNummerSet.getDouble("Prijs"); materialenLijst.add(new Materiaal(materiaalNummer, naam, prijs, aantalgebruikt)); } reparatieLijst.add(new Reparatie(reparatieNummer, kenteken, omschrijvingsNummer, begintijd, eindtijd, reparatiestatus, betaalstatus, materialenLijst)); } } catch (SQLException e) { System.err.println("Kan het statement niet uitvoeren"); e.printStackTrace(); } return reparatieLijst; } /** * Methode voor het toevoegen van een reparatie * @param reparatie de reparatie. */ public void addReparatie(Reparatie reparatie) { // Checkt of de monteur al een werknemernummer heeft // Als dit zo is dan bestaat hij al in de database en dient hij aangepast te worden System.out.println(); if(reparatie.getReparatieNummer() != 0) { this.addExistingReparatie(reparatie); } else { this.addNewReparatie(reparatie); } } /** * Methode voor het veranderen van een reparatie * @param reparatie de reparatie */ private void addExistingReparatie(Reparatie reparatie) { // Zet de verbinding op met de database Connection connection = manager.getConnection(); // De sql string met de juiste waarden voor de database String insertString = "update reparatie " + "set kenteken=?, omschrijvingsnr=?, begintijd=?, eindtijd=?, reparatiestatus=?, betaalstatus=? " + "where reparatienr=?"; try { // Het statement met de juiste sql string PreparedStatement insertStatement = connection.prepareStatement(insertString); // Meldt de attributen van de planning aan bij het statement insertStatement.setString(1, reparatie.getKenteken()); insertStatement.setInt(2, reparatie.getOmschrijvingsNummer()); insertStatement.setTimestamp(3, reparatie.getBeginTijd()); insertStatement.setTimestamp(4, reparatie.getEindTijd()); insertStatement.setBoolean(5, reparatie.getReparatieStatus()); insertStatement.setBoolean(6, reparatie.getBetaalStatus()); insertStatement.setInt(7, reparatie.getReparatieNummer()); // Voert het statement uit insertStatement.execute(); } catch (SQLException e) { e.printStackTrace(); } // Sluit de verbinding met de database manager.closeConnection(); } /** * Methode voor het wegschrijven van een planningsobject naar de database * @param reparatie Het weg te schrijven planningsobject */ private void addNewReparatie(Reparatie reparatie) { // Zet de verbinding op met de database Connection connection = manager.getConnection(); // De sql string met de juiste waarden voor de database String insertString = "insert into reparatie " + "(kenteken, omschrijvingsnr, begintijd, eindtijd, reparatiestatus, betaalstatus) " + "values " + "(?, ?, ?, ?, ?, ?)"; try { // Het statement met de juiste sql string PreparedStatement insertStatement = connection.prepareStatement(insertString); // Meldt de attributen van de planning aan bij het statement insertStatement.setString(1, reparatie.getKenteken()); insertStatement.setInt(2, reparatie.getOmschrijvingsNummer()); insertStatement.setTimestamp(3, reparatie.getBeginTijd()); insertStatement.setTimestamp(4, reparatie.getEindTijd()); insertStatement.setBoolean(5, reparatie.getReparatieStatus()); insertStatement.setBoolean(6, reparatie.getBetaalStatus()); // Voert het statement uit insertStatement.execute(); } catch (SQLException e) { e.printStackTrace(); } // Sluit de verbinding met de database manager.closeConnection(); } /** * Methode voor het opvragen van de reparaties die nog gedaan moeten worden. * @return de lijst met reparaties die nog moeten gebeuren. */ public ArrayList<Reparatie> getToDoReparaties() { // Lijst met de resultaten van de query ArrayList<Reparatie> reparatieLijst = new ArrayList<>(); // De connectie met de database op Connection connection = manager.getConnection(); // De te execturen sql querys try { // Query die alle gegevens uit de tabel reparatie haalt String reparatieQuery = "select * from reparatie " + "where reparatiestatus = false"; PreparedStatement reparatieStatement = connection.prepareStatement(reparatieQuery); ResultSet reparatieSet = reparatieStatement.executeQuery(); // Zolang er nog gegevens in de tabel staan while(reparatieSet.next()) { // De gegevens van een rij int reparatieNummer = reparatieSet.getInt("Reparatienr"); String kenteken = reparatieSet.getString("Kenteken"); int omschrijvingsNummer = reparatieSet.getInt("Omschrijvingsnr"); Timestamp begintijd = reparatieSet.getTimestamp("Begintijd"); Timestamp eindtijd = reparatieSet.getTimestamp("EindTijd"); boolean reparatiestatus = reparatieSet.getBoolean("Reparatiestatus"); boolean betaalstatus = reparatieSet.getBoolean("Betaalstatus"); // Query die alle materiaalnummer uit de koppeltabel haalt String materiaalNummersQuery = "select * from ReparatieMateriaal " + "inner join materiaal " + "on reparatieMateriaal.Materiaalnr = Materiaal.materiaalnr " + "where Reparatienr = ?"; PreparedStatement materiaalNummersStatement = connection.prepareStatement(materiaalNummersQuery); materiaalNummersStatement.setInt(1, reparatieNummer); ResultSet materiaalNummerSet = materiaalNummersStatement.executeQuery(); ArrayList<Materiaal> materialenLijst = new ArrayList<>(); while(materiaalNummerSet.next()){ int materiaalNummer = materiaalNummerSet.getInt("Materiaalnr"); int aantalgebruikt = materiaalNummerSet.getInt("Aantalgebruikt"); String naam = materiaalNummerSet.getString("Naam"); double prijs = materiaalNummerSet.getDouble("Prijs"); materialenLijst.add(new Materiaal(materiaalNummer, naam, prijs, aantalgebruikt)); } reparatieLijst.add(new Reparatie(reparatieNummer, kenteken, omschrijvingsNummer, begintijd, eindtijd, reparatiestatus, betaalstatus, materialenLijst)); } } catch (SQLException e) { System.err.println("Kan het statement niet uitvoeren"); e.printStackTrace(); } // Sluit de verbinding met de database manager.closeConnection(); // Geeft de lijst met reparaties terug return reparatieLijst; } /** * Methode voor het opvragen van de reparaties voor een bepaalde werknemer die hij nog moet doen. * @param werknemerNummer het werknemernummer van de monteur * @return een lijst met reparaties die de monteur nog moet doen. */ public ArrayList<Reparatie> eigenToDoReparaties(int werknemerNummer) { // Lijst met de resultaten van de query ArrayList<Reparatie> reparatieLijst = new ArrayList<>(); // De connectie met de database op Connection connection = manager.getConnection(); // De te execturen sql querys try { // Query die alle gegevens uit de tabel reparatie haalt String reparatieQuery = "Select * from reparatie " + "inner join planning " + "on reparatie.reparatieNr = planning.reparatieNr " + "where werknemernr = ? AND reparatieStatus = false"; PreparedStatement reparatieStatement = connection.prepareStatement(reparatieQuery); reparatieStatement.setInt(1, werknemerNummer); ResultSet reparatieSet = reparatieStatement.executeQuery(); // Zolang er nog gegevens in de tabel staan while(reparatieSet.next()) { // De gegevens van een rij int reparatieNummer = reparatieSet.getInt("Reparatienr"); String kenteken = reparatieSet.getString("Kenteken"); int omschrijvingsNummer = reparatieSet.getInt("Omschrijvingsnr"); Timestamp begintijd = reparatieSet.getTimestamp("Begintijd"); Timestamp eindtijd = reparatieSet.getTimestamp("EindTijd"); boolean reparatiestatus = reparatieSet.getBoolean("Reparatiestatus"); boolean betaalstatus = reparatieSet.getBoolean("Betaalstatus"); // Query die alle materiaalnummer uit de koppeltabel haalt String materiaalNummersQuery = "select * from ReparatieMateriaal " + "inner join materiaal " + "on reparatieMateriaal.Materiaalnr = Materiaal.materiaalnr " + "where Reparatienr = ?"; PreparedStatement materiaalNummersStatement = connection.prepareStatement(materiaalNummersQuery); materiaalNummersStatement.setInt(1, reparatieNummer); ResultSet materiaalNummerSet = materiaalNummersStatement.executeQuery(); ArrayList<Materiaal> materialenLijst = new ArrayList<>(); while(materiaalNummerSet.next()){ int materiaalNummer = materiaalNummerSet.getInt("Materiaalnr"); int aantalgebruikt = materiaalNummerSet.getInt("Aantalgebruikt"); String naam = materiaalNummerSet.getString("Naam"); double prijs = materiaalNummerSet.getDouble("Prijs"); materialenLijst.add(new Materiaal(materiaalNummer, naam, prijs, aantalgebruikt)); } reparatieLijst.add(new Reparatie(reparatieNummer, kenteken, omschrijvingsNummer, begintijd, eindtijd, reparatiestatus, betaalstatus, materialenLijst)); } } catch (SQLException e) { System.err.println("Kan het statement niet uitvoeren"); } manager.closeConnection(); // Geeft de lijst met reparaties terug return reparatieLijst; } /** * Het veranderen van een reparatie * @param reparatie de reparatie die veranderd moet worden. */ public void wijzigReparatie(Reparatie reparatie) { // De connectie met de database op Connection connection = manager.getConnection(); // De te execturen sql querys try { // Query die alle gegevens uit de tabel reparatie haalt String reparatieUpdate = "UPDATE reparatie SET reparatieStatus = ?, beginTijd = ?, eindTijd = ? WHERE kenteken = ?"; PreparedStatement reparatieStatement = connection.prepareStatement(reparatieUpdate); reparatieStatement.setBoolean(1, reparatie.getReparatieStatus()); reparatieStatement.setTimestamp(2, reparatie.getBeginTijd()); reparatieStatement.setTimestamp(3, reparatie.getEindTijd()); reparatieStatement.setString(4, reparatie.getKenteken()); reparatieStatement.executeUpdate(); } catch (SQLException e) { System.err.println("Kan het statement niet uitvoeren"); e.printStackTrace(); } // Sluit de verbinding met de database manager.closeConnection(); } }
Challio5/ProjectGarage
src/nl/eti1b5/database/dao/ReparatieDao.java
7,505
// Meldt de attributen van de planning aan bij het statement
line_comment
nl
package nl.eti1b5.database.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import nl.eti1b5.database.DatabaseManager; import nl.eti1b5.model.Materiaal; import nl.eti1b5.model.Reparatie; /** * Data access object wat de reparatie tabel beheert in de database * Haalt de gegevens van een reparatie op en schrijft ze weg naar de database * * @author Projectgroep ETI2b3 2014-2015 kwartiel 1 * @since 22 okt. 2014 */ public class ReparatieDao { // Databasemanager met de connectie naar de database private DatabaseManager manager; /** * Constructor voor het ophalen van de singleton instantie van de databasemanager */ public ReparatieDao() { manager = DatabaseManager.getInstance(); } /** * Constructor voor het meegegeven van de singleton instantie van de databasemanager * @param manager Singleton instantie van de databasemanager */ public ReparatieDao(DatabaseManager manager) { this.manager = manager; } /** * Methode voor het opvragen van alle reparaties uit de database * @return een lijst met alle reparaties */ public ArrayList<Reparatie> getReparaties() { // Lijst met de resultaten van de query ArrayList<Reparatie> reparatieLijst = new ArrayList<>(); // De connectie met de database op Connection connection = manager.getConnection(); // De te execturen sql querys try { // Query die alle gegevens uit de tabel reparatie haalt String reparatieQuery = "select * from reparatie " + "natural join omschrijving"; PreparedStatement reparatieStatement = connection.prepareStatement(reparatieQuery); ResultSet reparatieSet = reparatieStatement.executeQuery(); // Zolang er nog gegevens in de tabel staan while(reparatieSet.next()) { // De gegevens van een rij int reparatieNummer = reparatieSet.getInt("Reparatienr"); String kenteken = reparatieSet.getString("Kenteken"); int omschrijvingsNummer = reparatieSet.getInt("Omschrijvingsnr"); Timestamp begintijd = reparatieSet.getTimestamp("Begintijd"); Timestamp eindtijd = reparatieSet.getTimestamp("EindTijd"); boolean reparatiestatus = reparatieSet.getBoolean("Reparatiestatus"); boolean betaalstatus = reparatieSet.getBoolean("Betaalstatus"); // Query die alle materiaalnummer uit de koppeltabel haalt String materiaalNummersQuery = "select * from ReparatieMateriaal " + "inner join materiaal " + "on reparatieMateriaal.Materiaalnr = Materiaal.materiaalnr " + "where Reparatienr = ?"; PreparedStatement materiaalNummersStatement = connection.prepareStatement(materiaalNummersQuery); materiaalNummersStatement.setInt(1, reparatieNummer); ResultSet materiaalNummerSet = materiaalNummersStatement.executeQuery(); ArrayList<Materiaal> materialenLijst = new ArrayList<>(); while(materiaalNummerSet.next()){ int materiaalNummer = materiaalNummerSet.getInt("Materiaalnr"); int aantalgebruikt = materiaalNummerSet.getInt("Aantalgebruikt"); String naam = materiaalNummerSet.getString("Naam"); double prijs = materiaalNummerSet.getDouble("Prijs"); materialenLijst.add(new Materiaal(materiaalNummer, naam, prijs, aantalgebruikt)); } reparatieLijst.add(new Reparatie(reparatieNummer, kenteken, omschrijvingsNummer, begintijd, eindtijd, reparatiestatus, betaalstatus, materialenLijst)); } } catch (SQLException e) { System.err.println("Kan het statement niet uitvoeren"); e.printStackTrace(); } // Sluit de verbinding met de database manager.closeConnection(); // Geeft de lijst met reparaties terug return reparatieLijst; } /** * Methode voor het opvragen van alle reparaties die verbonden zijn aan een werknemer. * @param werknemerNummer Het nummer van de werknemer waarvan de reparaties moeten worden opgevraagd * @return een lijst met alle reparaties van de werknemer */ public ArrayList<Reparatie> eigenReparaties(int werknemerNummer) { // Lijst met de resultaten van de query ArrayList<Reparatie> reparatieLijst = new ArrayList<>(); // De connectie met de database op Connection connection = manager.getConnection(); // De te execturen sql querys try { // Query die alle gegevens uit de tabel reparatie haalt String reparatieQuery = "Select * from reparatie " + "Inner Join planning " + "on reparatie.reparatieNr = planning.reparatieNr " + "where werknemernr = "+ werknemerNummer; PreparedStatement reparatieStatement = connection.prepareStatement(reparatieQuery); ResultSet reparatieSet = reparatieStatement.executeQuery(); // Zolang er nog gegevens in de tabel staan while(reparatieSet.next()) { // De gegevens van een rij int reparatieNummer = reparatieSet.getInt("Reparatienr"); String kenteken = reparatieSet.getString("Kenteken"); int omschrijvingsNummer = reparatieSet.getInt("Omschrijvingsnr"); Timestamp begintijd = reparatieSet.getTimestamp("Begintijd"); Timestamp eindtijd = reparatieSet.getTimestamp("EindTijd"); boolean reparatiestatus = reparatieSet.getBoolean("Reparatiestatus"); boolean betaalstatus = reparatieSet.getBoolean("Betaalstatus"); // Query die alle materiaalnummer uit de koppeltabel haalt String materiaalNummersQuery = "select * from ReparatieMateriaal " + "natural join omschrijving " + "inner join materiaal " + "on reparatieMateriaal.Materiaalnr = Materiaal.materiaalnr " + "where Reparatienr = ?"; PreparedStatement materiaalNummersStatement = connection.prepareStatement(materiaalNummersQuery); materiaalNummersStatement.setInt(1, reparatieNummer); ResultSet materiaalNummerSet = materiaalNummersStatement.executeQuery(); ArrayList<Materiaal> materialenLijst = new ArrayList<>(); while(materiaalNummerSet.next()){ int materiaalNummer = materiaalNummerSet.getInt("Materiaalnr"); int aantalgebruikt = materiaalNummerSet.getInt("Aantalgebruikt"); String naam = materiaalNummerSet.getString("Naam"); double prijs = materiaalNummerSet.getDouble("Prijs"); materialenLijst.add(new Materiaal(materiaalNummer, naam, prijs, aantalgebruikt)); } reparatieLijst.add(new Reparatie(reparatieNummer, kenteken, omschrijvingsNummer, begintijd, eindtijd, reparatiestatus, betaalstatus, materialenLijst)); } } catch (SQLException e) { System.err.println("Kan het statement niet uitvoeren"); e.printStackTrace(); } // Sluit de verbinding met de database manager.closeConnection(); // Geeft de lijst met reparaties terug return reparatieLijst; } /** * Methode voor het opvragen van een reparatie aan de hand van het reparatienummer * @param reparatienr Het nummer van de reparatie die moet worden opgevraagd * @return de reparaties */ public Reparatie getReparatie(int reparatienr) { Reparatie reparatie = null; // De connectie met de database op Connection connection = manager.getConnection(); // De te execturen sql querys try { // Query die alle gegevens uit de tabel reparatie haalt String reparatieQuery = "select * from reparatie " + "where reparatienr = ?"; PreparedStatement reparatieStatement = connection.prepareStatement(reparatieQuery); reparatieStatement.setInt(1, reparatienr); ResultSet reparatieSet = reparatieStatement.executeQuery(); // Zolang er nog gegevens in de tabel staan while(reparatieSet.next()) { // De gegevens van een rij int reparatieNummer = reparatieSet.getInt("Reparatienr"); String kenteken = reparatieSet.getString("Kenteken"); int omschrijvingsNummer = reparatieSet.getInt("Omschrijvingsnr"); Timestamp begintijd = reparatieSet.getTimestamp("Begintijd"); Timestamp eindtijd = reparatieSet.getTimestamp("EindTijd"); boolean reparatiestatus = reparatieSet.getBoolean("Reparatiestatus"); boolean betaalstatus = reparatieSet.getBoolean("Betaalstatus"); // Query die alle materiaalnummer uit de koppeltabel haalt String materiaalNummersQuery = "select * from ReparatieMateriaal " + "inner join materiaal " + "on reparatieMateriaal.Materiaalnr = Materiaal.materiaalnr " + "where Reparatienr = ?"; PreparedStatement materiaalNummersStatement = connection.prepareStatement(materiaalNummersQuery); materiaalNummersStatement.setInt(1, reparatieNummer); ResultSet materiaalNummerSet = materiaalNummersStatement.executeQuery(); ArrayList<Materiaal> materialenLijst = new ArrayList<>(); while(materiaalNummerSet.next()){ int materiaalNummer = materiaalNummerSet.getInt("Materiaalnr"); int aantalgebruikt = materiaalNummerSet.getInt("Aantalgebruikt"); String naam = materiaalNummerSet.getString("Naam"); double prijs = materiaalNummerSet.getDouble("Prijs"); materialenLijst.add(new Materiaal(materiaalNummer, naam, prijs, aantalgebruikt)); } reparatie = new Reparatie(reparatieNummer, kenteken, omschrijvingsNummer, begintijd, eindtijd, reparatiestatus, betaalstatus, materialenLijst); } } catch (SQLException e) { System.err.println("Kan het statement niet uitvoeren"); e.printStackTrace(); } return reparatie; } /** * Methode voor het opvragen van de reparaties horende bij een klant * @param klantnr Het nummer van de klant waarvan de reparaties moeten worden opgehaald * @param betaald Boolean of de op te halen reparatie wel of niet betaald moeten zijn * @return een lijst met de reparaties horende bij een klant. */ public ArrayList<Reparatie> getKlantReparaties(int klantnr, boolean betaald) { ArrayList<Reparatie> reparatieLijst = new ArrayList<>(); // De connectie met de database op Connection connection = manager.getConnection(); // De te execturen sql querys try { // Query die alle gegevens uit de tabel reparatie haalt String reparatieQuery = "select * from reparatie " + "natural join auto " + "where klantnr = ? and betaalstatus = ?"; PreparedStatement reparatieStatement = connection.prepareStatement(reparatieQuery); reparatieStatement.setInt(1, klantnr); reparatieStatement.setBoolean(2, betaald); ResultSet reparatieSet = reparatieStatement.executeQuery(); // Zolang er nog gegevens in de tabel staan while(reparatieSet.next()) { // De gegevens van een rij int reparatieNummer = reparatieSet.getInt("Reparatienr"); String kenteken = reparatieSet.getString("Kenteken"); int omschrijvingsNummer = reparatieSet.getInt("Omschrijvingsnr"); Timestamp begintijd = reparatieSet.getTimestamp("Begintijd"); Timestamp eindtijd = reparatieSet.getTimestamp("EindTijd"); boolean reparatiestatus = reparatieSet.getBoolean("Reparatiestatus"); boolean betaalstatus = reparatieSet.getBoolean("Betaalstatus"); // Query die alle materiaalnummer uit de koppeltabel haalt String materiaalNummersQuery = "select * from ReparatieMateriaal " + "inner join materiaal " + "on reparatieMateriaal.Materiaalnr = Materiaal.materiaalnr " + "where Reparatienr = ?"; PreparedStatement materiaalNummersStatement = connection.prepareStatement(materiaalNummersQuery); materiaalNummersStatement.setInt(1, reparatieNummer); ResultSet materiaalNummerSet = materiaalNummersStatement.executeQuery(); ArrayList<Materiaal> materialenLijst = new ArrayList<>(); while(materiaalNummerSet.next()){ int materiaalNummer = materiaalNummerSet.getInt("Materiaalnr"); int aantalgebruikt = materiaalNummerSet.getInt("Aantalgebruikt"); String naam = materiaalNummerSet.getString("Naam"); double prijs = materiaalNummerSet.getDouble("Prijs"); materialenLijst.add(new Materiaal(materiaalNummer, naam, prijs, aantalgebruikt)); } reparatieLijst.add(new Reparatie(reparatieNummer, kenteken, omschrijvingsNummer, begintijd, eindtijd, reparatiestatus, betaalstatus, materialenLijst)); } } catch (SQLException e) { System.err.println("Kan het statement niet uitvoeren"); e.printStackTrace(); } return reparatieLijst; } /** * Methode voor het toevoegen van een reparatie * @param reparatie de reparatie. */ public void addReparatie(Reparatie reparatie) { // Checkt of de monteur al een werknemernummer heeft // Als dit zo is dan bestaat hij al in de database en dient hij aangepast te worden System.out.println(); if(reparatie.getReparatieNummer() != 0) { this.addExistingReparatie(reparatie); } else { this.addNewReparatie(reparatie); } } /** * Methode voor het veranderen van een reparatie * @param reparatie de reparatie */ private void addExistingReparatie(Reparatie reparatie) { // Zet de verbinding op met de database Connection connection = manager.getConnection(); // De sql string met de juiste waarden voor de database String insertString = "update reparatie " + "set kenteken=?, omschrijvingsnr=?, begintijd=?, eindtijd=?, reparatiestatus=?, betaalstatus=? " + "where reparatienr=?"; try { // Het statement met de juiste sql string PreparedStatement insertStatement = connection.prepareStatement(insertString); // Meldt de attributen van de planning aan bij het statement insertStatement.setString(1, reparatie.getKenteken()); insertStatement.setInt(2, reparatie.getOmschrijvingsNummer()); insertStatement.setTimestamp(3, reparatie.getBeginTijd()); insertStatement.setTimestamp(4, reparatie.getEindTijd()); insertStatement.setBoolean(5, reparatie.getReparatieStatus()); insertStatement.setBoolean(6, reparatie.getBetaalStatus()); insertStatement.setInt(7, reparatie.getReparatieNummer()); // Voert het statement uit insertStatement.execute(); } catch (SQLException e) { e.printStackTrace(); } // Sluit de verbinding met de database manager.closeConnection(); } /** * Methode voor het wegschrijven van een planningsobject naar de database * @param reparatie Het weg te schrijven planningsobject */ private void addNewReparatie(Reparatie reparatie) { // Zet de verbinding op met de database Connection connection = manager.getConnection(); // De sql string met de juiste waarden voor de database String insertString = "insert into reparatie " + "(kenteken, omschrijvingsnr, begintijd, eindtijd, reparatiestatus, betaalstatus) " + "values " + "(?, ?, ?, ?, ?, ?)"; try { // Het statement met de juiste sql string PreparedStatement insertStatement = connection.prepareStatement(insertString); // Meldt de<SUF> insertStatement.setString(1, reparatie.getKenteken()); insertStatement.setInt(2, reparatie.getOmschrijvingsNummer()); insertStatement.setTimestamp(3, reparatie.getBeginTijd()); insertStatement.setTimestamp(4, reparatie.getEindTijd()); insertStatement.setBoolean(5, reparatie.getReparatieStatus()); insertStatement.setBoolean(6, reparatie.getBetaalStatus()); // Voert het statement uit insertStatement.execute(); } catch (SQLException e) { e.printStackTrace(); } // Sluit de verbinding met de database manager.closeConnection(); } /** * Methode voor het opvragen van de reparaties die nog gedaan moeten worden. * @return de lijst met reparaties die nog moeten gebeuren. */ public ArrayList<Reparatie> getToDoReparaties() { // Lijst met de resultaten van de query ArrayList<Reparatie> reparatieLijst = new ArrayList<>(); // De connectie met de database op Connection connection = manager.getConnection(); // De te execturen sql querys try { // Query die alle gegevens uit de tabel reparatie haalt String reparatieQuery = "select * from reparatie " + "where reparatiestatus = false"; PreparedStatement reparatieStatement = connection.prepareStatement(reparatieQuery); ResultSet reparatieSet = reparatieStatement.executeQuery(); // Zolang er nog gegevens in de tabel staan while(reparatieSet.next()) { // De gegevens van een rij int reparatieNummer = reparatieSet.getInt("Reparatienr"); String kenteken = reparatieSet.getString("Kenteken"); int omschrijvingsNummer = reparatieSet.getInt("Omschrijvingsnr"); Timestamp begintijd = reparatieSet.getTimestamp("Begintijd"); Timestamp eindtijd = reparatieSet.getTimestamp("EindTijd"); boolean reparatiestatus = reparatieSet.getBoolean("Reparatiestatus"); boolean betaalstatus = reparatieSet.getBoolean("Betaalstatus"); // Query die alle materiaalnummer uit de koppeltabel haalt String materiaalNummersQuery = "select * from ReparatieMateriaal " + "inner join materiaal " + "on reparatieMateriaal.Materiaalnr = Materiaal.materiaalnr " + "where Reparatienr = ?"; PreparedStatement materiaalNummersStatement = connection.prepareStatement(materiaalNummersQuery); materiaalNummersStatement.setInt(1, reparatieNummer); ResultSet materiaalNummerSet = materiaalNummersStatement.executeQuery(); ArrayList<Materiaal> materialenLijst = new ArrayList<>(); while(materiaalNummerSet.next()){ int materiaalNummer = materiaalNummerSet.getInt("Materiaalnr"); int aantalgebruikt = materiaalNummerSet.getInt("Aantalgebruikt"); String naam = materiaalNummerSet.getString("Naam"); double prijs = materiaalNummerSet.getDouble("Prijs"); materialenLijst.add(new Materiaal(materiaalNummer, naam, prijs, aantalgebruikt)); } reparatieLijst.add(new Reparatie(reparatieNummer, kenteken, omschrijvingsNummer, begintijd, eindtijd, reparatiestatus, betaalstatus, materialenLijst)); } } catch (SQLException e) { System.err.println("Kan het statement niet uitvoeren"); e.printStackTrace(); } // Sluit de verbinding met de database manager.closeConnection(); // Geeft de lijst met reparaties terug return reparatieLijst; } /** * Methode voor het opvragen van de reparaties voor een bepaalde werknemer die hij nog moet doen. * @param werknemerNummer het werknemernummer van de monteur * @return een lijst met reparaties die de monteur nog moet doen. */ public ArrayList<Reparatie> eigenToDoReparaties(int werknemerNummer) { // Lijst met de resultaten van de query ArrayList<Reparatie> reparatieLijst = new ArrayList<>(); // De connectie met de database op Connection connection = manager.getConnection(); // De te execturen sql querys try { // Query die alle gegevens uit de tabel reparatie haalt String reparatieQuery = "Select * from reparatie " + "inner join planning " + "on reparatie.reparatieNr = planning.reparatieNr " + "where werknemernr = ? AND reparatieStatus = false"; PreparedStatement reparatieStatement = connection.prepareStatement(reparatieQuery); reparatieStatement.setInt(1, werknemerNummer); ResultSet reparatieSet = reparatieStatement.executeQuery(); // Zolang er nog gegevens in de tabel staan while(reparatieSet.next()) { // De gegevens van een rij int reparatieNummer = reparatieSet.getInt("Reparatienr"); String kenteken = reparatieSet.getString("Kenteken"); int omschrijvingsNummer = reparatieSet.getInt("Omschrijvingsnr"); Timestamp begintijd = reparatieSet.getTimestamp("Begintijd"); Timestamp eindtijd = reparatieSet.getTimestamp("EindTijd"); boolean reparatiestatus = reparatieSet.getBoolean("Reparatiestatus"); boolean betaalstatus = reparatieSet.getBoolean("Betaalstatus"); // Query die alle materiaalnummer uit de koppeltabel haalt String materiaalNummersQuery = "select * from ReparatieMateriaal " + "inner join materiaal " + "on reparatieMateriaal.Materiaalnr = Materiaal.materiaalnr " + "where Reparatienr = ?"; PreparedStatement materiaalNummersStatement = connection.prepareStatement(materiaalNummersQuery); materiaalNummersStatement.setInt(1, reparatieNummer); ResultSet materiaalNummerSet = materiaalNummersStatement.executeQuery(); ArrayList<Materiaal> materialenLijst = new ArrayList<>(); while(materiaalNummerSet.next()){ int materiaalNummer = materiaalNummerSet.getInt("Materiaalnr"); int aantalgebruikt = materiaalNummerSet.getInt("Aantalgebruikt"); String naam = materiaalNummerSet.getString("Naam"); double prijs = materiaalNummerSet.getDouble("Prijs"); materialenLijst.add(new Materiaal(materiaalNummer, naam, prijs, aantalgebruikt)); } reparatieLijst.add(new Reparatie(reparatieNummer, kenteken, omschrijvingsNummer, begintijd, eindtijd, reparatiestatus, betaalstatus, materialenLijst)); } } catch (SQLException e) { System.err.println("Kan het statement niet uitvoeren"); } manager.closeConnection(); // Geeft de lijst met reparaties terug return reparatieLijst; } /** * Het veranderen van een reparatie * @param reparatie de reparatie die veranderd moet worden. */ public void wijzigReparatie(Reparatie reparatie) { // De connectie met de database op Connection connection = manager.getConnection(); // De te execturen sql querys try { // Query die alle gegevens uit de tabel reparatie haalt String reparatieUpdate = "UPDATE reparatie SET reparatieStatus = ?, beginTijd = ?, eindTijd = ? WHERE kenteken = ?"; PreparedStatement reparatieStatement = connection.prepareStatement(reparatieUpdate); reparatieStatement.setBoolean(1, reparatie.getReparatieStatus()); reparatieStatement.setTimestamp(2, reparatie.getBeginTijd()); reparatieStatement.setTimestamp(3, reparatie.getEindTijd()); reparatieStatement.setString(4, reparatie.getKenteken()); reparatieStatement.executeUpdate(); } catch (SQLException e) { System.err.println("Kan het statement niet uitvoeren"); e.printStackTrace(); } // Sluit de verbinding met de database manager.closeConnection(); } }
110986_3
package org.gwlt.trailapp; import android.content.ActivityNotFoundException; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.PopupMenu; import android.widget.Toast; import java.util.ArrayList; /** * Class that represents the Main Activity of the GWLT app. This is the screen that is displayed when the user first opens the app. */ public final class MainActivity extends BaseActivity { private static ArrayList<RegionalMap> regionalMaps; // list of regional maps private Toolbar jAppToolbar; // screen's toolbar private PhotoView jPhotoView; // photo view that holds overall map @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); loadRegionalMaps(); setUpUIComponents(); } @Override public void setUpUIComponents() { // set screen toolbar jAppToolbar = findViewById(R.id.appToolbar); setSupportActionBar(jAppToolbar); setLearnMoreToolbar(jAppToolbar); // set up photo view with correct image resource jPhotoView = findViewById(R.id.mapPhotoView); jPhotoView.setImageResource(R.drawable.trust_lands); jPhotoView.setMaximumScale(BaseActivity.VIEW_MAX_SCALE); } /** * Creates a new RegionalMap using the provided parameters, adds it to the list of regionalMaps, and then returns it. * @param nameID - ID of string resource of the map name * @param imgID - ID of image resource of the map * @param menuID - ID of the menu resource of the map's list of properties * @return the new RegionalMap that has been created */ private RegionalMap addRegionalMap(int nameID, int imgID, int menuID) { RegionalMap newMap = new RegionalMap(getResources().getString(nameID), imgID, menuID); regionalMaps.add(newMap); return newMap; } /** * This function initializes the map list, creates new regionalMaps, and then adds properties to the new regionalMaps. */ private void loadRegionalMaps() { regionalMaps = new ArrayList<>(); RegionalMap otherProperties = addRegionalMap(R.string.otherProperties,R.drawable.trust_lands,R.menu.other_properties_map_menu); otherProperties.addProperty(this,R.string.bovenzi,R.mipmap.bovenzi,R.string.bovenziLink ); otherProperties.addProperty(this,R.string.nicksWoods,R.mipmap.nicks_woods_g_1,R.string.nicksWoodsLink ); otherProperties.addProperty(this,R.string.coesReservoir,R.mipmap.coes_reservoir,R.string.coesReservoirLink ); otherProperties.addProperty(this,R.string.crowHill,R.mipmap.crow_hill,R.string.crowHillLink ); otherProperties.addProperty(this,R.string.tetasset,R.mipmap.tetasset,R.string.tetassetLink ); otherProperties.addProperty(this,R.string.eastsidetrail,R.mipmap.east_side_trail_map_1,R.string.eastsideLink ); otherProperties.addProperty(this,R.string.broadmeadow,R.mipmap.broadmeadow,R.string.broadLink ); otherProperties.addProperty(this,R.string.sibley,R.mipmap.sibley,R.string.sibleyLink ); otherProperties.addProperty(this,R.string.elmersSeat,R.mipmap.elmers_seat,R.string.elmersLink ); otherProperties.addProperty(this,R.string.pineGlen, R.mipmap.pine_glen, R.string.pineLink); RegionalMap fourTownGreenway = addRegionalMap(R.string.fourTownGreenWayTxt, R.drawable.four_town_greenway_1, R.menu.four_town_greenway_menu); fourTownGreenway.addProperty(this, R.string.asnebumskit, R.mipmap.asnebumskit, R.string.asnebumskitLink); fourTownGreenway.addProperty(this, R.string.cascades, R.mipmap.cascades, R.string.cascadesLink); fourTownGreenway.addProperty(this, R.string.cookPond, R.mipmap.cooks_pond, R.string.cookPondLink); fourTownGreenway.addProperty(this, R.string.donkerCooksBrook, R.mipmap.donker_cooks_brook, R.string.donkerCooksLink); fourTownGreenway.addProperty(this, R.string.kinneywoods, R.mipmap.kinney_woods, R.string.kinneyLink); fourTownGreenway.addProperty(this, R.string.morelandWoods, R.mipmap.moreland_woods, R.string.morelandLink); fourTownGreenway.addProperty(this, R.string.southwickMuir, R.mipmap.southwick_muir, R.string.southwickLink); } /** * Gets the regional map with the provided name * @param name - name of desired regional map * @return the regional map with the provided name */ public static RegionalMap getRegionalMapWithName(String name) { for (RegionalMap map : regionalMaps) { if (map.getRegionName().equals(name)) return map; } return null; } /** * MainActivity must override this method in order to activate the popup menu button on the toolbar * @param menu - menu being added to the toolbar * @return true to activate menu */ @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuItem popupBtn = menu.findItem(R.id.popupMenu); popupBtn.setEnabled(true); popupBtn.setVisible(true); return true; } /** * MainActivity must override this method in order to provide functionality to the popup menu button on the toolbar * @param item - menu item that has been triggered * @return true to allow popup button functionality */ @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.popupMenu) { PopupMenu mapsMenu = new PopupMenu(this, jAppToolbar); mapsMenu.getMenuInflater().inflate(R.menu.maps_menu, mapsMenu.getMenu()); mapsMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { try { Intent mapIntent = new Intent(MainActivity.this, RegionalMapActivity.class); mapIntent.putExtra(RegionalMap.REGIONAL_MAP_NAME_ID, item.getTitle().toString()); startActivity(mapIntent); } catch (ActivityNotFoundException ex) { Toast.makeText(MainActivity.this, "Regional map screen could not be opened.", Toast.LENGTH_LONG).show(); } return true; } }); mapsMenu.show(); return true; } else { return super.onOptionsItemSelected(item); } } }
ChamiLamelas/TrailApp
app/src/main/java/org/gwlt/trailapp/MainActivity.java
2,025
// set screen toolbar
line_comment
nl
package org.gwlt.trailapp; import android.content.ActivityNotFoundException; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.PopupMenu; import android.widget.Toast; import java.util.ArrayList; /** * Class that represents the Main Activity of the GWLT app. This is the screen that is displayed when the user first opens the app. */ public final class MainActivity extends BaseActivity { private static ArrayList<RegionalMap> regionalMaps; // list of regional maps private Toolbar jAppToolbar; // screen's toolbar private PhotoView jPhotoView; // photo view that holds overall map @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); loadRegionalMaps(); setUpUIComponents(); } @Override public void setUpUIComponents() { // set screen<SUF> jAppToolbar = findViewById(R.id.appToolbar); setSupportActionBar(jAppToolbar); setLearnMoreToolbar(jAppToolbar); // set up photo view with correct image resource jPhotoView = findViewById(R.id.mapPhotoView); jPhotoView.setImageResource(R.drawable.trust_lands); jPhotoView.setMaximumScale(BaseActivity.VIEW_MAX_SCALE); } /** * Creates a new RegionalMap using the provided parameters, adds it to the list of regionalMaps, and then returns it. * @param nameID - ID of string resource of the map name * @param imgID - ID of image resource of the map * @param menuID - ID of the menu resource of the map's list of properties * @return the new RegionalMap that has been created */ private RegionalMap addRegionalMap(int nameID, int imgID, int menuID) { RegionalMap newMap = new RegionalMap(getResources().getString(nameID), imgID, menuID); regionalMaps.add(newMap); return newMap; } /** * This function initializes the map list, creates new regionalMaps, and then adds properties to the new regionalMaps. */ private void loadRegionalMaps() { regionalMaps = new ArrayList<>(); RegionalMap otherProperties = addRegionalMap(R.string.otherProperties,R.drawable.trust_lands,R.menu.other_properties_map_menu); otherProperties.addProperty(this,R.string.bovenzi,R.mipmap.bovenzi,R.string.bovenziLink ); otherProperties.addProperty(this,R.string.nicksWoods,R.mipmap.nicks_woods_g_1,R.string.nicksWoodsLink ); otherProperties.addProperty(this,R.string.coesReservoir,R.mipmap.coes_reservoir,R.string.coesReservoirLink ); otherProperties.addProperty(this,R.string.crowHill,R.mipmap.crow_hill,R.string.crowHillLink ); otherProperties.addProperty(this,R.string.tetasset,R.mipmap.tetasset,R.string.tetassetLink ); otherProperties.addProperty(this,R.string.eastsidetrail,R.mipmap.east_side_trail_map_1,R.string.eastsideLink ); otherProperties.addProperty(this,R.string.broadmeadow,R.mipmap.broadmeadow,R.string.broadLink ); otherProperties.addProperty(this,R.string.sibley,R.mipmap.sibley,R.string.sibleyLink ); otherProperties.addProperty(this,R.string.elmersSeat,R.mipmap.elmers_seat,R.string.elmersLink ); otherProperties.addProperty(this,R.string.pineGlen, R.mipmap.pine_glen, R.string.pineLink); RegionalMap fourTownGreenway = addRegionalMap(R.string.fourTownGreenWayTxt, R.drawable.four_town_greenway_1, R.menu.four_town_greenway_menu); fourTownGreenway.addProperty(this, R.string.asnebumskit, R.mipmap.asnebumskit, R.string.asnebumskitLink); fourTownGreenway.addProperty(this, R.string.cascades, R.mipmap.cascades, R.string.cascadesLink); fourTownGreenway.addProperty(this, R.string.cookPond, R.mipmap.cooks_pond, R.string.cookPondLink); fourTownGreenway.addProperty(this, R.string.donkerCooksBrook, R.mipmap.donker_cooks_brook, R.string.donkerCooksLink); fourTownGreenway.addProperty(this, R.string.kinneywoods, R.mipmap.kinney_woods, R.string.kinneyLink); fourTownGreenway.addProperty(this, R.string.morelandWoods, R.mipmap.moreland_woods, R.string.morelandLink); fourTownGreenway.addProperty(this, R.string.southwickMuir, R.mipmap.southwick_muir, R.string.southwickLink); } /** * Gets the regional map with the provided name * @param name - name of desired regional map * @return the regional map with the provided name */ public static RegionalMap getRegionalMapWithName(String name) { for (RegionalMap map : regionalMaps) { if (map.getRegionName().equals(name)) return map; } return null; } /** * MainActivity must override this method in order to activate the popup menu button on the toolbar * @param menu - menu being added to the toolbar * @return true to activate menu */ @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuItem popupBtn = menu.findItem(R.id.popupMenu); popupBtn.setEnabled(true); popupBtn.setVisible(true); return true; } /** * MainActivity must override this method in order to provide functionality to the popup menu button on the toolbar * @param item - menu item that has been triggered * @return true to allow popup button functionality */ @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.popupMenu) { PopupMenu mapsMenu = new PopupMenu(this, jAppToolbar); mapsMenu.getMenuInflater().inflate(R.menu.maps_menu, mapsMenu.getMenu()); mapsMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { try { Intent mapIntent = new Intent(MainActivity.this, RegionalMapActivity.class); mapIntent.putExtra(RegionalMap.REGIONAL_MAP_NAME_ID, item.getTitle().toString()); startActivity(mapIntent); } catch (ActivityNotFoundException ex) { Toast.makeText(MainActivity.this, "Regional map screen could not be opened.", Toast.LENGTH_LONG).show(); } return true; } }); mapsMenu.show(); return true; } else { return super.onOptionsItemSelected(item); } } }
18356_19
package controller; import model.Movie; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import repository.MovieRepository; import repository.WatchedMovieRepository; import utils.Validators; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping("/api") public class MovieController { //methode voor het ophalen van een film, toevoegen van een film en toevoegen van een bekeken film naar een aparte repository @Autowired private WatchedMovieRepository watchedMovieRepository; @Autowired private MovieRepository movieRepository; public MovieController() { } //Met deze methode zorg ik ervoor dat ik alle movies ophaal, zowel gekeken als niet gekeken @RequestMapping(method = RequestMethod.GET, value = "/getMovieList") public List<Movie> movieList() { List<Movie> list = new ArrayList<>(); movieRepository.findAll().forEach(list::add); watchedMovieRepository.findAll().forEach(list::add); return list; } //Code is nog niet bruikbaar, wil hier graag een methode maken met een connectie met IMBD API // private String apiURL = "http://img.omdbapi.com/?apikey=[yourkey]&"; // public void searchForMovie() { // try { // // Dit is de API request waarmee ik films wil ophalen van IMDB // URL url = new URL(apiURL); // // try (InputStream stream = url.openStream()) { // String output = convertStreamToString(stream); // // // Converteer teruggekeerde string naar JSON // JSONObject jsonObj = new JSONObject(output); // JSONObject main = jsonObj.getJSONObject("main"); // JSONArray weather = jsonObj.getJSONArray("movie"); // int movieId = (int) movie.getJSONObject(0).get("id"); // } // } catch (IOException e) { // System.out.println("Geen movies beschikbaar op het moment van de externe database"); // } // } // // private String convertStreamToString(InputStream stream) { // } //Met deze methode voeg ik een movie toe, zie de validaties voor datum toegevoegd en check of suitable age wel daadwerkelijk een getal is tussen de 0 en 100 @RequestMapping(method = RequestMethod.POST, value = "/addManuallyMovie") public Movie addManuallyMovie(@RequestBody Movie movie) { if (Validators.suitableMovieAgeMatcher(movie.getSuitableAgeMovie()) && (movie.getMovieDate().isBefore(LocalDate.now()))) { return movieRepository.save(movie); } else return null; } //Met deze methode voeg ik een vinkje toe aan movie die ik heb gezien @RequestMapping(method = RequestMethod.POST, value = "/addWatchedMovie") public Movie addWatchedMovie(@RequestBody Movie movie) { if (movie.isMovieWatched()) { return watchedMovieRepository.save(movie); } else return null; } //met deze methode wil ik de optie hebben om een film die handmatig is toegevoegd ook te kunnen wijzigen @RequestMapping(value = "/changeMovie", method = RequestMethod.POST) public Movie changeMovie(@RequestBody Movie movie) { movieRepository.delete(movie); return movieRepository.save(movie); } //Met deze methode wil ik dat de movie verwijderd kan worden @RequestMapping(value = "/deleteMovie", method = RequestMethod.POST) public void deleteMovie(@RequestBody Movie movie) { movieRepository.delete(movie); watchedMovieRepository.delete(movie); } }
Chaouki-Tiouassiouine/myMoviesApplication
src/main/java/controller/MovieController.java
1,099
//met deze methode wil ik de optie hebben om een film die handmatig is toegevoegd ook te kunnen wijzigen
line_comment
nl
package controller; import model.Movie; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import repository.MovieRepository; import repository.WatchedMovieRepository; import utils.Validators; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping("/api") public class MovieController { //methode voor het ophalen van een film, toevoegen van een film en toevoegen van een bekeken film naar een aparte repository @Autowired private WatchedMovieRepository watchedMovieRepository; @Autowired private MovieRepository movieRepository; public MovieController() { } //Met deze methode zorg ik ervoor dat ik alle movies ophaal, zowel gekeken als niet gekeken @RequestMapping(method = RequestMethod.GET, value = "/getMovieList") public List<Movie> movieList() { List<Movie> list = new ArrayList<>(); movieRepository.findAll().forEach(list::add); watchedMovieRepository.findAll().forEach(list::add); return list; } //Code is nog niet bruikbaar, wil hier graag een methode maken met een connectie met IMBD API // private String apiURL = "http://img.omdbapi.com/?apikey=[yourkey]&"; // public void searchForMovie() { // try { // // Dit is de API request waarmee ik films wil ophalen van IMDB // URL url = new URL(apiURL); // // try (InputStream stream = url.openStream()) { // String output = convertStreamToString(stream); // // // Converteer teruggekeerde string naar JSON // JSONObject jsonObj = new JSONObject(output); // JSONObject main = jsonObj.getJSONObject("main"); // JSONArray weather = jsonObj.getJSONArray("movie"); // int movieId = (int) movie.getJSONObject(0).get("id"); // } // } catch (IOException e) { // System.out.println("Geen movies beschikbaar op het moment van de externe database"); // } // } // // private String convertStreamToString(InputStream stream) { // } //Met deze methode voeg ik een movie toe, zie de validaties voor datum toegevoegd en check of suitable age wel daadwerkelijk een getal is tussen de 0 en 100 @RequestMapping(method = RequestMethod.POST, value = "/addManuallyMovie") public Movie addManuallyMovie(@RequestBody Movie movie) { if (Validators.suitableMovieAgeMatcher(movie.getSuitableAgeMovie()) && (movie.getMovieDate().isBefore(LocalDate.now()))) { return movieRepository.save(movie); } else return null; } //Met deze methode voeg ik een vinkje toe aan movie die ik heb gezien @RequestMapping(method = RequestMethod.POST, value = "/addWatchedMovie") public Movie addWatchedMovie(@RequestBody Movie movie) { if (movie.isMovieWatched()) { return watchedMovieRepository.save(movie); } else return null; } //met deze<SUF> @RequestMapping(value = "/changeMovie", method = RequestMethod.POST) public Movie changeMovie(@RequestBody Movie movie) { movieRepository.delete(movie); return movieRepository.save(movie); } //Met deze methode wil ik dat de movie verwijderd kan worden @RequestMapping(value = "/deleteMovie", method = RequestMethod.POST) public void deleteMovie(@RequestBody Movie movie) { movieRepository.delete(movie); watchedMovieRepository.delete(movie); } }
171937_0
package domein; import javafx.scene.image.ImageView; public class Edele { /** Hieronder staan de attributen van de klasse Edele */ private int naam; private int prestigepunten; private int prijsWit; private int prijsBlauw; private int prijsGroen; private int prijsRood; private int prijsZwart; private DomeinController dc; /** Dit is de constructor van de Edele */ public Edele(int naam, int prestigepunten, int prijsWit, int prijsBlauw, int prijsGroen, int prijsRood, int prijsZwart) { this.naam = naam; this.prestigepunten = prestigepunten; this.prijsWit = prijsWit; this.prijsBlauw = prijsBlauw; this.prijsGroen = prijsGroen; this.prijsRood = prijsRood; this.prijsZwart = prijsZwart; } /** Hieronder staan de getters en setters die in de klasse Edele gebruikt zijn */ public int getNaam() { return this.naam; } public int getPrestigepunten() { return this.prestigepunten; } public int getPrijsWit() { return this.prijsWit; } public int getPrijsBlauw() { return this.prijsBlauw; } public int getPrijsGroen() { return this.prijsGroen; } public int getPrijsRood() { return this.prijsRood; } public int getPrijsZwart() { return this.prijsZwart; } public ImageView getAfbeelding(){ switch (this.naam) { case 1 ->{ return new ImageView("/images/Edele/edele1.png"); } case 2 ->{ return new ImageView("/images/Edele/edele2.png"); } case 3 ->{ return new ImageView("/images/Edele/edele3.png"); } case 4 ->{ return new ImageView("/images/Edele/edele4.png"); } case 5 ->{ return new ImageView("/images/Edele/edele5.png"); } case 6 ->{ return new ImageView("/images/Edele/edele6.png"); } case 7 ->{ return new ImageView("/images/Edele/edele7.png"); } case 8 ->{ return new ImageView("/images/Edele/edele8.png"); } case 9 ->{ return new ImageView("/images/Edele/edele9.png"); } case 10 ->{ return new ImageView("/images/Edele/edele10.png"); } } return null; } }
CharanChander/SDP2023
Code/src/domein/Edele.java
857
/** Hieronder staan de attributen van de klasse Edele */
block_comment
nl
package domein; import javafx.scene.image.ImageView; public class Edele { /** Hieronder staan de<SUF>*/ private int naam; private int prestigepunten; private int prijsWit; private int prijsBlauw; private int prijsGroen; private int prijsRood; private int prijsZwart; private DomeinController dc; /** Dit is de constructor van de Edele */ public Edele(int naam, int prestigepunten, int prijsWit, int prijsBlauw, int prijsGroen, int prijsRood, int prijsZwart) { this.naam = naam; this.prestigepunten = prestigepunten; this.prijsWit = prijsWit; this.prijsBlauw = prijsBlauw; this.prijsGroen = prijsGroen; this.prijsRood = prijsRood; this.prijsZwart = prijsZwart; } /** Hieronder staan de getters en setters die in de klasse Edele gebruikt zijn */ public int getNaam() { return this.naam; } public int getPrestigepunten() { return this.prestigepunten; } public int getPrijsWit() { return this.prijsWit; } public int getPrijsBlauw() { return this.prijsBlauw; } public int getPrijsGroen() { return this.prijsGroen; } public int getPrijsRood() { return this.prijsRood; } public int getPrijsZwart() { return this.prijsZwart; } public ImageView getAfbeelding(){ switch (this.naam) { case 1 ->{ return new ImageView("/images/Edele/edele1.png"); } case 2 ->{ return new ImageView("/images/Edele/edele2.png"); } case 3 ->{ return new ImageView("/images/Edele/edele3.png"); } case 4 ->{ return new ImageView("/images/Edele/edele4.png"); } case 5 ->{ return new ImageView("/images/Edele/edele5.png"); } case 6 ->{ return new ImageView("/images/Edele/edele6.png"); } case 7 ->{ return new ImageView("/images/Edele/edele7.png"); } case 8 ->{ return new ImageView("/images/Edele/edele8.png"); } case 9 ->{ return new ImageView("/images/Edele/edele9.png"); } case 10 ->{ return new ImageView("/images/Edele/edele10.png"); } } return null; } }
52212_2
package com.hogent.ti3g05.ti3_g05_joetzapp; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.InflateException; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.parse.ParseUser; import java.util.Arrays; import java.util.List; //Geeft de mogelijkheid om naar de detailpagina van een vorming te gaan public class VormingDetail extends Activity { String titel; String locatie; String betalingswijze; String criteriaDeelnemer; String korteBeschrijving; String prijs; String tips; String websiteLocatie; String inbegrepenInPrijs; String objectId; List<String> periodes; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Animation animAlpha = AnimationUtils.loadAnimation(this, R.anim.alpha); try { setContentView(R.layout.vorming_detail); }catch (OutOfMemoryError e) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "vorming"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(), getString(R.string.error_generalException), Toast.LENGTH_SHORT).show(); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } catch (InflateException ex) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "vorming"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT).show(); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } Intent i = getIntent(); titel = i.getStringExtra("titel"); locatie = i.getStringExtra("locatie"); betalingswijze = i.getStringExtra("betalingswijze"); criteriaDeelnemer = i.getStringExtra("criteriaDeelnemers"); korteBeschrijving = i.getStringExtra("korteBeschrijving"); tips = i.getStringExtra("tips"); prijs = i.getStringExtra("prijs"); inbegrepenInPrijs = i.getStringExtra("inbegrepenInPrijs"); objectId = i.getStringExtra("objectId"); websiteLocatie = i.getStringExtra("websiteLocatie"); String[] voorlopigePeriodes = i.getStringArrayExtra("periodes"); periodes = Arrays.asList(voorlopigePeriodes); setTitle(titel); TextView txtTitel = (TextView) findViewById(R.id.titelVD); TextView txtLocatie = (TextView) findViewById(R.id.locatieVD); TextView txtbetalingswijze = (TextView) findViewById(R.id.betalingswijzeVD); TextView txtCriteriaDeelnemer = (TextView)findViewById(R.id.criteriaDeelnemerVD); TextView txtkorteBeschrijving = (TextView)findViewById(R.id.beschrijvingVD); TextView txtTips = (TextView)findViewById(R.id.tipsVD); TextView txtPrijs = (TextView) findViewById(R.id.prijs); TextView txtInbegrepenInPrijs = (TextView) findViewById(R.id.inbegrepenInPrijs); TextView txtWebsite = (TextView) findViewById(R.id.websiteLocatieVD); TextView txtPeriodes = (TextView) findViewById(R.id.periodesVD); txtTitel.setText(titel); txtLocatie.setText(locatie); txtbetalingswijze.setText(betalingswijze); txtCriteriaDeelnemer.setText(criteriaDeelnemer); txtkorteBeschrijving.setText(korteBeschrijving); txtTips.setText(tips); txtPrijs.setText("€ " + prijs); txtInbegrepenInPrijs.setText(inbegrepenInPrijs); txtWebsite.setText(websiteLocatie); StringBuilder periodesBuilder = new StringBuilder(); for (String obj : periodes){ periodesBuilder.append(obj + "\n"); } txtPeriodes.setText(periodesBuilder.toString()); final Button inschrijven = (Button) findViewById(R.id.btnInschrijvenVorming); //Enkel een monitor kan zich inschrijven, anders verberg je de knop if(ParseUser.getCurrentUser().get("soort").toString().toLowerCase().equals("administrator")) { inschrijven.setVisibility(View.GONE); } else { inschrijven.setVisibility(View.VISIBLE); } inschrijven.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { inschrijven.startAnimation(animAlpha); //Bij klikken op de knop stuur de gebruiker met de nodige gegevens door naar de inschrijvingpagina Intent inte = new Intent(getApplicationContext(), VormingInschrijven.class); inte.putExtra("periodes", periodes.toArray(new String[periodes.size()])); inte.putExtra("objectId", objectId); startActivity(inte); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.back, menu); menu.findItem(R.id.menu_load).setVisible(false); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.backMenu) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "vorming"); intent1.putExtra("herladen", "nee"); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { Intent setIntent = new Intent(VormingDetail.this, navBarMainScreen.class); setIntent.putExtra("naarfrag","vorming"); setIntent.putExtra("herladen","nee"); setIntent.addCategory(Intent.CATEGORY_HOME); setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(setIntent); } }
CharlotteErpels1993/TI3_GC05_Project
Android/TI3_G05_JoetzApp2/app/src/main/java/com/hogent/ti3g05/ti3_g05_joetzapp/VormingDetail.java
2,069
//Bij klikken op de knop stuur de gebruiker met de nodige gegevens door naar de inschrijvingpagina
line_comment
nl
package com.hogent.ti3g05.ti3_g05_joetzapp; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.InflateException; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.parse.ParseUser; import java.util.Arrays; import java.util.List; //Geeft de mogelijkheid om naar de detailpagina van een vorming te gaan public class VormingDetail extends Activity { String titel; String locatie; String betalingswijze; String criteriaDeelnemer; String korteBeschrijving; String prijs; String tips; String websiteLocatie; String inbegrepenInPrijs; String objectId; List<String> periodes; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Animation animAlpha = AnimationUtils.loadAnimation(this, R.anim.alpha); try { setContentView(R.layout.vorming_detail); }catch (OutOfMemoryError e) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "vorming"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(), getString(R.string.error_generalException), Toast.LENGTH_SHORT).show(); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } catch (InflateException ex) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "vorming"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT).show(); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } Intent i = getIntent(); titel = i.getStringExtra("titel"); locatie = i.getStringExtra("locatie"); betalingswijze = i.getStringExtra("betalingswijze"); criteriaDeelnemer = i.getStringExtra("criteriaDeelnemers"); korteBeschrijving = i.getStringExtra("korteBeschrijving"); tips = i.getStringExtra("tips"); prijs = i.getStringExtra("prijs"); inbegrepenInPrijs = i.getStringExtra("inbegrepenInPrijs"); objectId = i.getStringExtra("objectId"); websiteLocatie = i.getStringExtra("websiteLocatie"); String[] voorlopigePeriodes = i.getStringArrayExtra("periodes"); periodes = Arrays.asList(voorlopigePeriodes); setTitle(titel); TextView txtTitel = (TextView) findViewById(R.id.titelVD); TextView txtLocatie = (TextView) findViewById(R.id.locatieVD); TextView txtbetalingswijze = (TextView) findViewById(R.id.betalingswijzeVD); TextView txtCriteriaDeelnemer = (TextView)findViewById(R.id.criteriaDeelnemerVD); TextView txtkorteBeschrijving = (TextView)findViewById(R.id.beschrijvingVD); TextView txtTips = (TextView)findViewById(R.id.tipsVD); TextView txtPrijs = (TextView) findViewById(R.id.prijs); TextView txtInbegrepenInPrijs = (TextView) findViewById(R.id.inbegrepenInPrijs); TextView txtWebsite = (TextView) findViewById(R.id.websiteLocatieVD); TextView txtPeriodes = (TextView) findViewById(R.id.periodesVD); txtTitel.setText(titel); txtLocatie.setText(locatie); txtbetalingswijze.setText(betalingswijze); txtCriteriaDeelnemer.setText(criteriaDeelnemer); txtkorteBeschrijving.setText(korteBeschrijving); txtTips.setText(tips); txtPrijs.setText("€ " + prijs); txtInbegrepenInPrijs.setText(inbegrepenInPrijs); txtWebsite.setText(websiteLocatie); StringBuilder periodesBuilder = new StringBuilder(); for (String obj : periodes){ periodesBuilder.append(obj + "\n"); } txtPeriodes.setText(periodesBuilder.toString()); final Button inschrijven = (Button) findViewById(R.id.btnInschrijvenVorming); //Enkel een monitor kan zich inschrijven, anders verberg je de knop if(ParseUser.getCurrentUser().get("soort").toString().toLowerCase().equals("administrator")) { inschrijven.setVisibility(View.GONE); } else { inschrijven.setVisibility(View.VISIBLE); } inschrijven.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { inschrijven.startAnimation(animAlpha); //Bij klikken<SUF> Intent inte = new Intent(getApplicationContext(), VormingInschrijven.class); inte.putExtra("periodes", periodes.toArray(new String[periodes.size()])); inte.putExtra("objectId", objectId); startActivity(inte); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.back, menu); menu.findItem(R.id.menu_load).setVisible(false); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.backMenu) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "vorming"); intent1.putExtra("herladen", "nee"); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { Intent setIntent = new Intent(VormingDetail.this, navBarMainScreen.class); setIntent.putExtra("naarfrag","vorming"); setIntent.putExtra("herladen","nee"); setIntent.addCategory(Intent.CATEGORY_HOME); setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(setIntent); } }
81720_14
package com.chickenmobile.chickensorigins.client.renderers; import com.chickenmobile.chickensorigins.ChickensOrigins; import com.chickenmobile.chickensorigins.ChickensOriginsClient; import com.chickenmobile.chickensorigins.client.models.ButterflyWingModel; import com.chickenmobile.chickensorigins.client.particles.ParticlePixieDust; import com.chickenmobile.chickensorigins.core.registry.ModParticles; import com.chickenmobile.chickensorigins.util.WingsData; import net.minecraft.client.render.OverlayTexture; import net.minecraft.client.render.RenderLayer; import net.minecraft.client.render.VertexConsumer; import net.minecraft.client.render.VertexConsumerProvider; import net.minecraft.client.render.entity.feature.FeatureRenderer; import net.minecraft.client.render.entity.feature.FeatureRendererContext; import net.minecraft.client.render.entity.model.EntityModel; import net.minecraft.client.render.entity.model.EntityModelLoader; import net.minecraft.client.render.item.ItemRenderer; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.DyeColor; import net.minecraft.util.Identifier; import net.minecraft.util.math.random.Random; public class WingsFeatureRenderer<T extends LivingEntity, M extends EntityModel<T>> extends FeatureRenderer<T, M> { private final ButterflyWingModel<T> butterflyWings; private long lastRenderTime; private final int sparkleRenderDelay = 10; public WingsFeatureRenderer(FeatureRendererContext<T, M> context, EntityModelLoader loader) { super(context); this.butterflyWings = new ButterflyWingModel<>(loader.getModelPart(ChickensOriginsClient.BUTTERFLY)); } @Override public void render(MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, T entity, float limbAngle, float limbDistance, float tickDelta, float animationProgress, float headYaw, float headPitch) { if (entity instanceof PlayerEntity player && ChickensOrigins.IS_PIXIE.test(player)) { // Get wingType from wings data. String wingType = WingsData.WINGS_DATA.WING_MAP.getOrDefault(player.getUuidAsString(), "none"); // 'None' is a valid, even for pixie. Don't render. if (wingType == "none") { return; } Identifier layer = new Identifier(ChickensOrigins.MOD_ID, "textures/entity/" + wingType + ".png"); matrices.push(); matrices.translate(0.0D, -0.5D, 0.2D); this.getContextModel().copyStateTo(this.butterflyWings); this.butterflyWings.setAngles(entity, limbAngle, limbDistance, animationProgress, headYaw, headPitch); float[] color = DyeColor.WHITE.getColorComponents(); this.renderWings(matrices, vertexConsumers, RenderLayer.getEntityTranslucent(layer), light, color[0], color[1], color[2]); matrices.pop(); // Render pixie sparkle. renderParticles(player, wingType); } } public void renderWings(MatrixStack matrices, VertexConsumerProvider vertexConsumers, RenderLayer renderLayer, int light, float r, float g, float b) { VertexConsumer vertexConsumer = ItemRenderer.getArmorGlintConsumer(vertexConsumers, renderLayer, false, false); this.butterflyWings.render(matrices, vertexConsumer, light, OverlayTexture.DEFAULT_UV, r, g, b, 0.9F); } // Unused for now public void renderParticles(PlayerEntity player, String wingType) { //Random rand = player.world.random; // Don't render too many sparkles, render is 3x a tick (too much). This includes when game is paused in SP. if (player.age != lastRenderTime && !player.isOnGround() && player.age % sparkleRenderDelay == 0) { lastRenderTime = player.age; // Create particle based on facing of player // minecraft is off by 90deg for normal sin/cos circle mathos // double yaw = Math.toRadians(player.getBodyYaw() - 90); // double xCos = Math.cos(yaw); // double zSin = Math.sin(yaw); ParticlePixieDust.SparkleColor color = switch (wingType) { case "birdwing", "green_spotted_triangle" -> ParticlePixieDust.SparkleColor.GREEN; case "blue_morpho" -> ParticlePixieDust.SparkleColor.BLUE; case "buckeye" -> ParticlePixieDust.SparkleColor.BROWN; case "monarch" -> ParticlePixieDust.SparkleColor.ORANGE; case "pink_rose" -> ParticlePixieDust.SparkleColor.PINK; case "purple_emperor" -> ParticlePixieDust.SparkleColor.PURPLE; case "red_lacewing" -> ParticlePixieDust.SparkleColor.RED; case "tiger_swallowtail" -> ParticlePixieDust.SparkleColor.YELLOW; default -> ParticlePixieDust.SparkleColor.WHITE; }; // Create & Render the particle // player.getWorld().addParticle(ModParticles.PARTICLE_PIXIE_DUST, // player.getX() + (0.2F * xCos), // player.getY() + 0.2F + 0.1F * rand.nextGaussian(), // player.getZ() + (0.2F * zSin), // color.r, color.g, color.b); player.getWorld().addParticle(ModParticles.PARTICLE_PIXIE_DUST, player.getParticleX(1.0), player.getRandomBodyY(), player.getParticleZ(1.0), color.r, color.g, color.b); // rand.nextGaussian()) * 0.005D } } }
ChickenMobile/chickens-origins
src/main/java/com/chickenmobile/chickensorigins/client/renderers/WingsFeatureRenderer.java
1,705
// player.getZ() + (0.2F * zSin),
line_comment
nl
package com.chickenmobile.chickensorigins.client.renderers; import com.chickenmobile.chickensorigins.ChickensOrigins; import com.chickenmobile.chickensorigins.ChickensOriginsClient; import com.chickenmobile.chickensorigins.client.models.ButterflyWingModel; import com.chickenmobile.chickensorigins.client.particles.ParticlePixieDust; import com.chickenmobile.chickensorigins.core.registry.ModParticles; import com.chickenmobile.chickensorigins.util.WingsData; import net.minecraft.client.render.OverlayTexture; import net.minecraft.client.render.RenderLayer; import net.minecraft.client.render.VertexConsumer; import net.minecraft.client.render.VertexConsumerProvider; import net.minecraft.client.render.entity.feature.FeatureRenderer; import net.minecraft.client.render.entity.feature.FeatureRendererContext; import net.minecraft.client.render.entity.model.EntityModel; import net.minecraft.client.render.entity.model.EntityModelLoader; import net.minecraft.client.render.item.ItemRenderer; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.DyeColor; import net.minecraft.util.Identifier; import net.minecraft.util.math.random.Random; public class WingsFeatureRenderer<T extends LivingEntity, M extends EntityModel<T>> extends FeatureRenderer<T, M> { private final ButterflyWingModel<T> butterflyWings; private long lastRenderTime; private final int sparkleRenderDelay = 10; public WingsFeatureRenderer(FeatureRendererContext<T, M> context, EntityModelLoader loader) { super(context); this.butterflyWings = new ButterflyWingModel<>(loader.getModelPart(ChickensOriginsClient.BUTTERFLY)); } @Override public void render(MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, T entity, float limbAngle, float limbDistance, float tickDelta, float animationProgress, float headYaw, float headPitch) { if (entity instanceof PlayerEntity player && ChickensOrigins.IS_PIXIE.test(player)) { // Get wingType from wings data. String wingType = WingsData.WINGS_DATA.WING_MAP.getOrDefault(player.getUuidAsString(), "none"); // 'None' is a valid, even for pixie. Don't render. if (wingType == "none") { return; } Identifier layer = new Identifier(ChickensOrigins.MOD_ID, "textures/entity/" + wingType + ".png"); matrices.push(); matrices.translate(0.0D, -0.5D, 0.2D); this.getContextModel().copyStateTo(this.butterflyWings); this.butterflyWings.setAngles(entity, limbAngle, limbDistance, animationProgress, headYaw, headPitch); float[] color = DyeColor.WHITE.getColorComponents(); this.renderWings(matrices, vertexConsumers, RenderLayer.getEntityTranslucent(layer), light, color[0], color[1], color[2]); matrices.pop(); // Render pixie sparkle. renderParticles(player, wingType); } } public void renderWings(MatrixStack matrices, VertexConsumerProvider vertexConsumers, RenderLayer renderLayer, int light, float r, float g, float b) { VertexConsumer vertexConsumer = ItemRenderer.getArmorGlintConsumer(vertexConsumers, renderLayer, false, false); this.butterflyWings.render(matrices, vertexConsumer, light, OverlayTexture.DEFAULT_UV, r, g, b, 0.9F); } // Unused for now public void renderParticles(PlayerEntity player, String wingType) { //Random rand = player.world.random; // Don't render too many sparkles, render is 3x a tick (too much). This includes when game is paused in SP. if (player.age != lastRenderTime && !player.isOnGround() && player.age % sparkleRenderDelay == 0) { lastRenderTime = player.age; // Create particle based on facing of player // minecraft is off by 90deg for normal sin/cos circle mathos // double yaw = Math.toRadians(player.getBodyYaw() - 90); // double xCos = Math.cos(yaw); // double zSin = Math.sin(yaw); ParticlePixieDust.SparkleColor color = switch (wingType) { case "birdwing", "green_spotted_triangle" -> ParticlePixieDust.SparkleColor.GREEN; case "blue_morpho" -> ParticlePixieDust.SparkleColor.BLUE; case "buckeye" -> ParticlePixieDust.SparkleColor.BROWN; case "monarch" -> ParticlePixieDust.SparkleColor.ORANGE; case "pink_rose" -> ParticlePixieDust.SparkleColor.PINK; case "purple_emperor" -> ParticlePixieDust.SparkleColor.PURPLE; case "red_lacewing" -> ParticlePixieDust.SparkleColor.RED; case "tiger_swallowtail" -> ParticlePixieDust.SparkleColor.YELLOW; default -> ParticlePixieDust.SparkleColor.WHITE; }; // Create & Render the particle // player.getWorld().addParticle(ModParticles.PARTICLE_PIXIE_DUST, // player.getX() + (0.2F * xCos), // player.getY() + 0.2F + 0.1F * rand.nextGaussian(), // player.getZ() +<SUF> // color.r, color.g, color.b); player.getWorld().addParticle(ModParticles.PARTICLE_PIXIE_DUST, player.getParticleX(1.0), player.getRandomBodyY(), player.getParticleZ(1.0), color.r, color.g, color.b); // rand.nextGaussian()) * 0.005D } } }
117327_6
/* * Copyright (c) 2009-2011, EzWare * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer.Redistributions * in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution.Neither the name of the * EzWare nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ package net.sf.openrocket.gui.util; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.swing.AbstractAction; import javax.swing.JList; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; /** * The decorator for JList which makes it work like check list * UI can be designed using JList and which can be later decorated to become a check list * @author Eugene Ryzhikov * * @param <T> list item type */ public class CheckList<T> { private final JList<T> list; private static final MouseAdapter checkBoxEditor = new CheckListEditor(); public static class Builder { private JList<?> list; @SuppressWarnings("rawtypes") public Builder(JList<?> list) { if( null == list ){ this.list = new JList(); }else{ this.list = list; } } public Builder() { this(null); } @SuppressWarnings("unchecked") public <T> CheckList<T> build() { return new CheckList<T>((JList<T>)list); } } /** * Wraps the standard JList and makes it work like check list * @param list */ private CheckList(final JList<T> list) { if (list == null) throw new NullPointerException(); this.list = list; this.list.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION); if (!isEditorAttached()) list.addMouseListener(checkBoxEditor); this.list.setCellRenderer(new CheckListRenderer()); setupKeyboardActions(list); } @SuppressWarnings("serial") private void setupKeyboardActions(final JList<T> list) { String actionKey = "toggle-check"; list.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), actionKey); list.getActionMap().put(actionKey, new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { toggleIndex(list.getSelectedIndex()); } }); } private boolean isEditorAttached() { for (MouseListener ml : list.getMouseListeners()) { if (ml instanceof CheckListEditor) return true; } return false; } public JList<T> getList() { return list; } /** * Sets data to a check list. Simplification for setting new the model * @param data */ public void setData(Collection<T> data) { setModel(new DefaultCheckListModel<T>(data)); } /** * Sets the model for check list. * @param model */ public void setModel(DefaultCheckListModel<T> model) { list.setModel(model); } public DefaultCheckListModel<T> getModel() { return (DefaultCheckListModel<T>) list.getModel(); } /** * Returns a collection of checked items. * @return collection of checked items. Empty collection if nothing is selected */ public Collection<T> getCheckedItems() { return getModel().getCheckedItems(); } public Collection<T> getUncheckedItems() { List<T> unchecked = new ArrayList<T>(); for (int i = getModel().getSize() - 1; i >= 0; i--) { unchecked.add((T) getModel().getElementAt(i)); } unchecked.removeAll(getCheckedItems()); return unchecked; } public void checkAll() { getModel().checkAll(); } public void clearAll() { getModel().clearAll(); } /** * Resets checked elements * @param elements */ public void setCheckedItems(Collection<T> elements) { getModel().setCheckedItems(elements); } public void setUncheckedItems( Collection<T> elements ) { getModel().setUncheckedItems(elements); } public void toggleIndex(int index) { if (index >= 0 && index < list.getModel().getSize()) { DefaultCheckListModel<T> model = getModel(); model.setCheckedIndex(index, !model.isCheckedIndex(index)); } } }
ChrisLolkema/OpenRocket_V.Kenny
swing/src/net/sf/openrocket/gui/util/CheckList.java
1,736
/** * Resets checked elements * @param elements */
block_comment
nl
/* * Copyright (c) 2009-2011, EzWare * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer.Redistributions * in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution.Neither the name of the * EzWare nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ package net.sf.openrocket.gui.util; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.swing.AbstractAction; import javax.swing.JList; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; /** * The decorator for JList which makes it work like check list * UI can be designed using JList and which can be later decorated to become a check list * @author Eugene Ryzhikov * * @param <T> list item type */ public class CheckList<T> { private final JList<T> list; private static final MouseAdapter checkBoxEditor = new CheckListEditor(); public static class Builder { private JList<?> list; @SuppressWarnings("rawtypes") public Builder(JList<?> list) { if( null == list ){ this.list = new JList(); }else{ this.list = list; } } public Builder() { this(null); } @SuppressWarnings("unchecked") public <T> CheckList<T> build() { return new CheckList<T>((JList<T>)list); } } /** * Wraps the standard JList and makes it work like check list * @param list */ private CheckList(final JList<T> list) { if (list == null) throw new NullPointerException(); this.list = list; this.list.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION); if (!isEditorAttached()) list.addMouseListener(checkBoxEditor); this.list.setCellRenderer(new CheckListRenderer()); setupKeyboardActions(list); } @SuppressWarnings("serial") private void setupKeyboardActions(final JList<T> list) { String actionKey = "toggle-check"; list.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), actionKey); list.getActionMap().put(actionKey, new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { toggleIndex(list.getSelectedIndex()); } }); } private boolean isEditorAttached() { for (MouseListener ml : list.getMouseListeners()) { if (ml instanceof CheckListEditor) return true; } return false; } public JList<T> getList() { return list; } /** * Sets data to a check list. Simplification for setting new the model * @param data */ public void setData(Collection<T> data) { setModel(new DefaultCheckListModel<T>(data)); } /** * Sets the model for check list. * @param model */ public void setModel(DefaultCheckListModel<T> model) { list.setModel(model); } public DefaultCheckListModel<T> getModel() { return (DefaultCheckListModel<T>) list.getModel(); } /** * Returns a collection of checked items. * @return collection of checked items. Empty collection if nothing is selected */ public Collection<T> getCheckedItems() { return getModel().getCheckedItems(); } public Collection<T> getUncheckedItems() { List<T> unchecked = new ArrayList<T>(); for (int i = getModel().getSize() - 1; i >= 0; i--) { unchecked.add((T) getModel().getElementAt(i)); } unchecked.removeAll(getCheckedItems()); return unchecked; } public void checkAll() { getModel().checkAll(); } public void clearAll() { getModel().clearAll(); } /** * Resets checked elements<SUF>*/ public void setCheckedItems(Collection<T> elements) { getModel().setCheckedItems(elements); } public void setUncheckedItems( Collection<T> elements ) { getModel().setUncheckedItems(elements); } public void toggleIndex(int index) { if (index >= 0 && index < list.getModel().getSize()) { DefaultCheckListModel<T> model = getModel(); model.setCheckedIndex(index, !model.isCheckedIndex(index)); } } }
7818_1
public class Customer { String name; String lastName; int customerNumber; CreditCard creditCard; //A constructor //? Waarom 4 argumente as maar 3 parameters? Waarom gebruik 'this' sonder 'n punt? public Customer(String name, String lastName, CreditCard creditCard) { this(name, lastName, (int)(Math.random() * 100), creditCard); } //A constructor public Customer(String name, String lastName, int customerNumber, CreditCard creditCard) { this.name = name; this.lastName = lastName; this.customerNumber = customerNumber; this.creditCard = creditCard; } public void printName() { System.out.println("Customer " + name); } //? Waarom word metode hier gedeclareerd en niet in Creditcard zelf? public CreditCard getCreditCard() { return creditCard; } }
Chrisbuildit/Java-CreditCard-Class-inheritance
src/main/java/Customer.java
247
//? Waarom word metode hier gedeclareerd en niet in Creditcard zelf?
line_comment
nl
public class Customer { String name; String lastName; int customerNumber; CreditCard creditCard; //A constructor //? Waarom 4 argumente as maar 3 parameters? Waarom gebruik 'this' sonder 'n punt? public Customer(String name, String lastName, CreditCard creditCard) { this(name, lastName, (int)(Math.random() * 100), creditCard); } //A constructor public Customer(String name, String lastName, int customerNumber, CreditCard creditCard) { this.name = name; this.lastName = lastName; this.customerNumber = customerNumber; this.creditCard = creditCard; } public void printName() { System.out.println("Customer " + name); } //? Waarom<SUF> public CreditCard getCreditCard() { return creditCard; } }
30224_11
package nl.novi.techiteasy.controllers; import nl.novi.techiteasy.exceptions.RecordNotFoundException; import nl.novi.techiteasy.exceptions.TelevisionNameTooLongException; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; @RestController // Deze RequestMapping" op klasse niveau betekent dat elke Mapping in deze klasse begint met "localhost:8080/bonus/..." @RequestMapping(value = "/bonus") public class TelevisionControllerBonus { // De lijst is static, omdat er maar 1 lijst kan zijn. // De lijst is final, omdat de lijst op zich niet kan veranderen, enkel de waardes die er in staan. private static final List<String> televisionDatabase = new ArrayList<>(); @GetMapping("/televisions") public ResponseEntity<List<String>> getAllTelevisions() { // Return de complete lijst met een 200 status return ResponseEntity.ok(televisionDatabase); } @GetMapping("/televisions/{id}") public ResponseEntity<String> getTelevision(@PathVariable int id) { // Return de waarde die op index(id) staat en een 200 status // Wanneer de gebruiker een request doet met id=300, maar de lijst heeft maar 3 items. // Dan gooit java een IndexOutOfBoundsException. De bonus methode in de ExceptionController vangt dit op en stuurt de gebruiker een berichtje. return ResponseEntity.ok(televisionDatabase.get(id)); } @PostMapping("/televisions") public ResponseEntity<String> addTelevision(@RequestBody String television) { // Bonus bonus: check voor 20 letters: if(television.length()>20){ throw new TelevisionNameTooLongException("Televisienaam is te lang"); } else { // Voeg de televisie uit de parameter toe aan de lijst televisionDatabase.add(television); // Return de televisie uit de parameter met een 201 status return ResponseEntity.created(null).body(television); } } @DeleteMapping("/televisions/{id}") public ResponseEntity<Void> deleteTelevision(@PathVariable int id) { // Vervang de waarde op index(id) met null. Als we de waarde zouden verwijderen, zouden alle indexen die na deze waarden komen in de lijst met 1 afnemen. televisionDatabase.set(id, null); // Return een 204 status return ResponseEntity.noContent().build(); } @PutMapping("/televisions/{id}") public ResponseEntity<Void> updateTelevision(@PathVariable int id, @RequestBody String television) { // In de vorige methodes hebben we impliciet gebruik gemaakt van "IndexOUtOfBoundsException" als het id groter was dan de lijst. // In deze methode checken we daar expliciet voor en gooien we een custom exception op. if(televisionDatabase.isEmpty() || id>televisionDatabase.size()){ throw new RecordNotFoundException("Record met id: " + id + " niet gevonden in de database."); } else { // Vervang de waarde op index(id) met de television uit de parameter televisionDatabase.set(id, television); // Return een 204 status return ResponseEntity.noContent().build(); } } }
Christiaan83/backend-spring-boot-tech-it-easy
src/main/java/nl/novi/techiteasy/controllers/TelevisionControllerBonus.java
897
// Return een 204 status
line_comment
nl
package nl.novi.techiteasy.controllers; import nl.novi.techiteasy.exceptions.RecordNotFoundException; import nl.novi.techiteasy.exceptions.TelevisionNameTooLongException; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; @RestController // Deze RequestMapping" op klasse niveau betekent dat elke Mapping in deze klasse begint met "localhost:8080/bonus/..." @RequestMapping(value = "/bonus") public class TelevisionControllerBonus { // De lijst is static, omdat er maar 1 lijst kan zijn. // De lijst is final, omdat de lijst op zich niet kan veranderen, enkel de waardes die er in staan. private static final List<String> televisionDatabase = new ArrayList<>(); @GetMapping("/televisions") public ResponseEntity<List<String>> getAllTelevisions() { // Return de complete lijst met een 200 status return ResponseEntity.ok(televisionDatabase); } @GetMapping("/televisions/{id}") public ResponseEntity<String> getTelevision(@PathVariable int id) { // Return de waarde die op index(id) staat en een 200 status // Wanneer de gebruiker een request doet met id=300, maar de lijst heeft maar 3 items. // Dan gooit java een IndexOutOfBoundsException. De bonus methode in de ExceptionController vangt dit op en stuurt de gebruiker een berichtje. return ResponseEntity.ok(televisionDatabase.get(id)); } @PostMapping("/televisions") public ResponseEntity<String> addTelevision(@RequestBody String television) { // Bonus bonus: check voor 20 letters: if(television.length()>20){ throw new TelevisionNameTooLongException("Televisienaam is te lang"); } else { // Voeg de televisie uit de parameter toe aan de lijst televisionDatabase.add(television); // Return de televisie uit de parameter met een 201 status return ResponseEntity.created(null).body(television); } } @DeleteMapping("/televisions/{id}") public ResponseEntity<Void> deleteTelevision(@PathVariable int id) { // Vervang de waarde op index(id) met null. Als we de waarde zouden verwijderen, zouden alle indexen die na deze waarden komen in de lijst met 1 afnemen. televisionDatabase.set(id, null); // Return een<SUF> return ResponseEntity.noContent().build(); } @PutMapping("/televisions/{id}") public ResponseEntity<Void> updateTelevision(@PathVariable int id, @RequestBody String television) { // In de vorige methodes hebben we impliciet gebruik gemaakt van "IndexOUtOfBoundsException" als het id groter was dan de lijst. // In deze methode checken we daar expliciet voor en gooien we een custom exception op. if(televisionDatabase.isEmpty() || id>televisionDatabase.size()){ throw new RecordNotFoundException("Record met id: " + id + " niet gevonden in de database."); } else { // Vervang de waarde op index(id) met de television uit de parameter televisionDatabase.set(id, television); // Return een 204 status return ResponseEntity.noContent().build(); } } }
89845_38
package parser; import java.util.LinkedList; import errorHandling.ReturnValueTypes; import errorHandling.ReturnValue; //import parser.BinaryTree; import tokenizer.*; /** * Der Parser entwirft anhand einer Liste an Tokens einen abstrakten Syntaxbaum. * * @version 05.01.2021 * @author Christian S */ public class Parser { /** * Erstellt einen abstrakten Syntaxbaum, anhand der als Parameter angegebenen Liste. * * @param ptAST Abstrakter Syntaxbaum, welcher durch neuen Durchlauf der Methode erweitert werden soll. * Dieser AST darf nicht leer sein! * @param plTokens Liste an Tokens, welche fuer die Entwicklung des AST verwendet werden soll. * * @return Abstrakter Syntaxbaum. */ private ReturnValue<BinaryTree<Token>> createBinaryTree(BinaryTree<Token> ptAST, LinkedList<Token> plTokens) { if (plTokens.isEmpty()) { //Liste an Tokens ist leer: return new ReturnValue<BinaryTree<Token>>(ptAST, ReturnValueTypes.SUCCESS); } if (plTokens.get(0).getType().equals(TokenTypes.TOKEN_BRACKET_CLOSED)) { //Geschlossene Klammer gefunden -> Rekursion beenden: return new ReturnValue<BinaryTree<Token>>(ptAST, ReturnValueTypes.SUCCESS); } BinaryTree<Token> tNewAST = new BinaryTree<Token>(); //Speichert den neuen AST. tNewAST.setContent(ptAST.getContent()); //Operator setzten. if (plTokens.get(0).getType().equals(TokenTypes.TOKEN_BRACKET_OPENED)) { //Neue Klammer geoeffnet -> Neue Rechnung starten: plTokens.remove(0); //Klammer entfernen: BinaryTree<Token> tNewAST_RightSubTree = new BinaryTree<Token>(plTokens.get(0)); //Rechter Teilbaum ReturnValue<BinaryTree<Token>> rekursionReturnObj = new ReturnValue<BinaryTree<Token>>(); rekursionReturnObj = createBinaryTree(plTokens); //REKURSION :O if (rekursionReturnObj.getExecutionInformation() != ReturnValueTypes.SUCCESS) { //Es gab einen Fehler: return rekursionReturnObj; } tNewAST_RightSubTree = rekursionReturnObj.getReturnValue(); tNewAST.setLeftSubTree(ptAST); //Linken Teilbaum dem neuen AST hinzufuegen. tNewAST.setRightSubTree(tNewAST_RightSubTree); //Rechten Teilbaum hinzufuegen. //Rechnung aus der Liste an Tokens entfernen: int nBracketBalance = 1; while (!plTokens.isEmpty()) { if (plTokens.get(0).getType().equals(TokenTypes.TOKEN_BRACKET_OPENED)) { //Geoeffnete Klammer: nBracketBalance++; } else if (plTokens.get(0).getType().equals(TokenTypes.TOKEN_BRACKET_CLOSED)) { //Geschlossene Klammer: nBracketBalance--; } plTokens.remove(0); if (nBracketBalance == 0) { //Es wurden gleich viele Klammern geoeffnet und geschlossen -> Erster Operand wurde aus der Liste entfernt. break; } } } else { //Es wird keine neue Klammer geoeffnet, sodass keine neue Rechnung gestartet wird: BinaryTree<Token> tNewAST_RightSubTree = new BinaryTree<Token>(plTokens.get(0)); //Rechter Teilbaum. tNewAST.setLeftSubTree(ptAST); //Linken Teilbaum dem neuen AST hinzufuegen. tNewAST.setRightSubTree(tNewAST_RightSubTree); //Rechten Teilbaum hinzufuegen. plTokens.remove(0); //Token aus der Liste entfernen. } ReturnValue<BinaryTree<Token>> rekursionReturnObj = new ReturnValue<BinaryTree<Token>>(); rekursionReturnObj = createBinaryTree(tNewAST, plTokens); //REKURSION :O if (rekursionReturnObj.getExecutionInformation() != ReturnValueTypes.SUCCESS) { //Es ist ein Fehler aufgetreten: return rekursionReturnObj; } tNewAST = rekursionReturnObj.getReturnValue(); ReturnValue<BinaryTree<Token>> returnASTObj = new ReturnValue<BinaryTree<Token>>(tNewAST, ReturnValueTypes.SUCCESS); return returnASTObj; } /** * Startet den rekursiven Prozess, bei welchem ein abstrakter Syntaxbaum erstellt wird. * * @param plTokens Liste an Tokens, aus welchen der AST erstellt werden soll. Der Operator muss sich an der * ersten Position in der Liste befinden, sonst wird null zurueckgegeben. * * @return Abstrakter Syntaxbaum. */ private ReturnValue<BinaryTree<Token>> createBinaryTree(LinkedList<Token> plTokens) { if (plTokens.size() <= 3) { //Liste an Tokens ist leer, oder enthaelt nicht genug Operanden: ReturnValue<BinaryTree<Token>> tEmptyAST = new ReturnValue<BinaryTree<Token>>(new BinaryTree<Token>(), ReturnValueTypes.ERROR_NOT_ENOUGH_OPERANDS); return tEmptyAST; } else if (!plTokens.get(0).getType().equals(TokenTypes.TOKEN_OPERATOR) && !plTokens.get(0).getType().equals(TokenTypes.TOKEN_OPERATOR_BOOLEAN)) { //Es befindet sich kein Operator an der ersten Stelle in der Liste: ReturnValue<BinaryTree<Token>> tEmptyAST = new ReturnValue<BinaryTree<Token>>(new BinaryTree<Token>(), ReturnValueTypes.ERROR_SYNTAX); return tEmptyAST; } Token operatorTokenObj = new Token(plTokens.get(0).getValue(), plTokens.get(0).getType()); //Speichert den Operator als Token. plTokens.remove(0); //Operator entfernen. //Ersten Operanden herausfinden: BinaryTree<Token> tOperand1AST = new BinaryTree<Token>(); //Speichert den Teilbaum des ersten Operanden. if (plTokens.get(0).getType().equals(TokenTypes.TOKEN_BRACKET_OPENED)) { //Fuer den ersten Operanden muss eine weitere Rechnung durchgefuehrt werden: LinkedList<Token> lTokensOperand1 = new LinkedList<Token>(); plTokens.remove(0); //Klammer entfernen. lTokensOperand1.addAll(plTokens); ReturnValue<BinaryTree<Token>> tReturnOperand1 = new ReturnValue<BinaryTree<Token>>(); tReturnOperand1 = createBinaryTree(lTokensOperand1); //REKURSION :O if (tReturnOperand1.getExecutionInformation() != ReturnValueTypes.SUCCESS) { //Es ist bei der Rekursion zu einem Fehler gekommen: return tReturnOperand1; } tOperand1AST = tReturnOperand1.getReturnValue(); //Rechnung des ersten Operanden aus der Liste an Tokens entfernen: int nBracketBalance = 1; while (!plTokens.isEmpty()) { if (plTokens.get(0).getType().equals(TokenTypes.TOKEN_BRACKET_OPENED)) { //Geoeffnete Klammer: nBracketBalance++; } else if (plTokens.get(0).getType().equals(TokenTypes.TOKEN_BRACKET_CLOSED)) { //Geschlossene Klammer: nBracketBalance--; } plTokens.remove(0); if (nBracketBalance == 0) { //Es wurden gleich viele Klammern geoeffnet und geschlossen -> Erster Operand wurde aus der Liste entfernt. break; } } } else { //Fuer den ersten Operanden muss keine weitere Rechnung durchgefuehrt werden: tOperand1AST.setContent(plTokens.get(0)); plTokens.remove(0); //Operanden entfernen. } //Zweiten Operanden herausfinden: BinaryTree<Token> tOperand2AST = new BinaryTree<Token>(); //Speichert den Teilbaum des zweiten Operanden. if (plTokens.get(0).getType().equals(TokenTypes.TOKEN_BRACKET_OPENED)) { //Fuer den zweiten Operanden muss eine weitere Rechnung durchgefuehrt werden: LinkedList<Token> lTokensOperand2 = new LinkedList<Token>(); plTokens.remove(0); //Klammer entfernen. lTokensOperand2.addAll(plTokens); ReturnValue<BinaryTree<Token>> tReturnOperand2 = new ReturnValue<BinaryTree<Token>>(); tReturnOperand2 = createBinaryTree(lTokensOperand2); //REKURSION :O; if (tReturnOperand2.getExecutionInformation() != ReturnValueTypes.SUCCESS) { //Es ist bei der Rekursion zu einem Fehler gekommen: return tReturnOperand2; } tOperand2AST = tReturnOperand2.getReturnValue(); //Rechnung des zweiten Operanden aus der Liste an Tokens entfernen: int nBracketBalance = 1; while (!plTokens.isEmpty()) { if (plTokens.get(0).getType().equals(TokenTypes.TOKEN_BRACKET_OPENED)) { //Geoeffnete Klammer: nBracketBalance++; } else if (plTokens.get(0).getType().equals(TokenTypes.TOKEN_BRACKET_CLOSED)) { //Geschlossene Klammer: nBracketBalance--; } plTokens.remove(0); if (nBracketBalance == 0) { //Es wurden gleich viele Klammern geoeffnet und geschlossen -> Zweiter Operand wurde aus der Liste entfernt. break; } } } else { //Fuer den zweiten Operanden muss keine weitere Rechnung durchgefuehrt werden: tOperand2AST.setContent(plTokens.get(0)); plTokens.remove(0); //Operanden entfernen. } //Operanden wurden herausgefunden: BinaryTree<Token> tAbstractSyntaxTree = new BinaryTree<Token>(operatorTokenObj, tOperand1AST, tOperand2AST); //Abstrakter Syntaxbaum, welcher fuer die Rekursion verwendet wird. //Rekursion starten: ReturnValue<BinaryTree<Token>> rekursionReturnObj = new ReturnValue<BinaryTree<Token>>(); //Speichert den Rueckgabewert der Rekursion. rekursionReturnObj = createBinaryTree(tAbstractSyntaxTree, plTokens); //REKURSION :O if (rekursionReturnObj.getExecutionInformation() != ReturnValueTypes.SUCCESS) { return rekursionReturnObj; } tAbstractSyntaxTree = rekursionReturnObj.getReturnValue(); return new ReturnValue<BinaryTree<Token>>(tAbstractSyntaxTree, ReturnValueTypes.SUCCESS); } /** * Erstellt einen abstrakten Syntaxbaum, anhand einer Liste an Tokens. * * @param plTokens Liste an Tokens, welche verarbeitet werden sollen. * @return Abstrakter Syntaxbaum. */ public ReturnValue<BinaryTree<Token>> parse(LinkedList<Token> plTokens) { if (plTokens.isEmpty()) { //Liste an Tokens ist leer: return new ReturnValue<BinaryTree<Token>>(null, ReturnValueTypes.ERROR_SYNTAX); } else { int nOpenedBrackets = 0; int nClosedBrackets = 0; for (int i = 0; i < plTokens.size(); i++) { if (plTokens.get(i).getType().equals(TokenTypes.TOKEN_BRACKET_OPENED)) { nOpenedBrackets++; } else if (plTokens.get(i).getType().equals(TokenTypes.TOKEN_BRACKET_CLOSED)) { nClosedBrackets++; } } if (nOpenedBrackets != nClosedBrackets) { //Die Anzahl an geoeffneten und geschlossenen Klammern stimmen nicht ueberein: return new ReturnValue<BinaryTree<Token>>(null, ReturnValueTypes.ERROR_SYNTAX); } } plTokens.remove(0); if (plTokens.isEmpty()) { //Keine Tokens vorhanden: return new ReturnValue(null, ReturnValueTypes.ERROR_SYNTAX); } ReturnValue<BinaryTree<Token>> rekursionReturn = new ReturnValue<BinaryTree<Token>>(); rekursionReturn = createBinaryTree(plTokens); //REKURSION :O return rekursionReturn; } }
Christian-2003/LispInterpreter
src/parser/Parser.java
3,725
//Liste an Tokens ist leer:
line_comment
nl
package parser; import java.util.LinkedList; import errorHandling.ReturnValueTypes; import errorHandling.ReturnValue; //import parser.BinaryTree; import tokenizer.*; /** * Der Parser entwirft anhand einer Liste an Tokens einen abstrakten Syntaxbaum. * * @version 05.01.2021 * @author Christian S */ public class Parser { /** * Erstellt einen abstrakten Syntaxbaum, anhand der als Parameter angegebenen Liste. * * @param ptAST Abstrakter Syntaxbaum, welcher durch neuen Durchlauf der Methode erweitert werden soll. * Dieser AST darf nicht leer sein! * @param plTokens Liste an Tokens, welche fuer die Entwicklung des AST verwendet werden soll. * * @return Abstrakter Syntaxbaum. */ private ReturnValue<BinaryTree<Token>> createBinaryTree(BinaryTree<Token> ptAST, LinkedList<Token> plTokens) { if (plTokens.isEmpty()) { //Liste an Tokens ist leer: return new ReturnValue<BinaryTree<Token>>(ptAST, ReturnValueTypes.SUCCESS); } if (plTokens.get(0).getType().equals(TokenTypes.TOKEN_BRACKET_CLOSED)) { //Geschlossene Klammer gefunden -> Rekursion beenden: return new ReturnValue<BinaryTree<Token>>(ptAST, ReturnValueTypes.SUCCESS); } BinaryTree<Token> tNewAST = new BinaryTree<Token>(); //Speichert den neuen AST. tNewAST.setContent(ptAST.getContent()); //Operator setzten. if (plTokens.get(0).getType().equals(TokenTypes.TOKEN_BRACKET_OPENED)) { //Neue Klammer geoeffnet -> Neue Rechnung starten: plTokens.remove(0); //Klammer entfernen: BinaryTree<Token> tNewAST_RightSubTree = new BinaryTree<Token>(plTokens.get(0)); //Rechter Teilbaum ReturnValue<BinaryTree<Token>> rekursionReturnObj = new ReturnValue<BinaryTree<Token>>(); rekursionReturnObj = createBinaryTree(plTokens); //REKURSION :O if (rekursionReturnObj.getExecutionInformation() != ReturnValueTypes.SUCCESS) { //Es gab einen Fehler: return rekursionReturnObj; } tNewAST_RightSubTree = rekursionReturnObj.getReturnValue(); tNewAST.setLeftSubTree(ptAST); //Linken Teilbaum dem neuen AST hinzufuegen. tNewAST.setRightSubTree(tNewAST_RightSubTree); //Rechten Teilbaum hinzufuegen. //Rechnung aus der Liste an Tokens entfernen: int nBracketBalance = 1; while (!plTokens.isEmpty()) { if (plTokens.get(0).getType().equals(TokenTypes.TOKEN_BRACKET_OPENED)) { //Geoeffnete Klammer: nBracketBalance++; } else if (plTokens.get(0).getType().equals(TokenTypes.TOKEN_BRACKET_CLOSED)) { //Geschlossene Klammer: nBracketBalance--; } plTokens.remove(0); if (nBracketBalance == 0) { //Es wurden gleich viele Klammern geoeffnet und geschlossen -> Erster Operand wurde aus der Liste entfernt. break; } } } else { //Es wird keine neue Klammer geoeffnet, sodass keine neue Rechnung gestartet wird: BinaryTree<Token> tNewAST_RightSubTree = new BinaryTree<Token>(plTokens.get(0)); //Rechter Teilbaum. tNewAST.setLeftSubTree(ptAST); //Linken Teilbaum dem neuen AST hinzufuegen. tNewAST.setRightSubTree(tNewAST_RightSubTree); //Rechten Teilbaum hinzufuegen. plTokens.remove(0); //Token aus der Liste entfernen. } ReturnValue<BinaryTree<Token>> rekursionReturnObj = new ReturnValue<BinaryTree<Token>>(); rekursionReturnObj = createBinaryTree(tNewAST, plTokens); //REKURSION :O if (rekursionReturnObj.getExecutionInformation() != ReturnValueTypes.SUCCESS) { //Es ist ein Fehler aufgetreten: return rekursionReturnObj; } tNewAST = rekursionReturnObj.getReturnValue(); ReturnValue<BinaryTree<Token>> returnASTObj = new ReturnValue<BinaryTree<Token>>(tNewAST, ReturnValueTypes.SUCCESS); return returnASTObj; } /** * Startet den rekursiven Prozess, bei welchem ein abstrakter Syntaxbaum erstellt wird. * * @param plTokens Liste an Tokens, aus welchen der AST erstellt werden soll. Der Operator muss sich an der * ersten Position in der Liste befinden, sonst wird null zurueckgegeben. * * @return Abstrakter Syntaxbaum. */ private ReturnValue<BinaryTree<Token>> createBinaryTree(LinkedList<Token> plTokens) { if (plTokens.size() <= 3) { //Liste an Tokens ist leer, oder enthaelt nicht genug Operanden: ReturnValue<BinaryTree<Token>> tEmptyAST = new ReturnValue<BinaryTree<Token>>(new BinaryTree<Token>(), ReturnValueTypes.ERROR_NOT_ENOUGH_OPERANDS); return tEmptyAST; } else if (!plTokens.get(0).getType().equals(TokenTypes.TOKEN_OPERATOR) && !plTokens.get(0).getType().equals(TokenTypes.TOKEN_OPERATOR_BOOLEAN)) { //Es befindet sich kein Operator an der ersten Stelle in der Liste: ReturnValue<BinaryTree<Token>> tEmptyAST = new ReturnValue<BinaryTree<Token>>(new BinaryTree<Token>(), ReturnValueTypes.ERROR_SYNTAX); return tEmptyAST; } Token operatorTokenObj = new Token(plTokens.get(0).getValue(), plTokens.get(0).getType()); //Speichert den Operator als Token. plTokens.remove(0); //Operator entfernen. //Ersten Operanden herausfinden: BinaryTree<Token> tOperand1AST = new BinaryTree<Token>(); //Speichert den Teilbaum des ersten Operanden. if (plTokens.get(0).getType().equals(TokenTypes.TOKEN_BRACKET_OPENED)) { //Fuer den ersten Operanden muss eine weitere Rechnung durchgefuehrt werden: LinkedList<Token> lTokensOperand1 = new LinkedList<Token>(); plTokens.remove(0); //Klammer entfernen. lTokensOperand1.addAll(plTokens); ReturnValue<BinaryTree<Token>> tReturnOperand1 = new ReturnValue<BinaryTree<Token>>(); tReturnOperand1 = createBinaryTree(lTokensOperand1); //REKURSION :O if (tReturnOperand1.getExecutionInformation() != ReturnValueTypes.SUCCESS) { //Es ist bei der Rekursion zu einem Fehler gekommen: return tReturnOperand1; } tOperand1AST = tReturnOperand1.getReturnValue(); //Rechnung des ersten Operanden aus der Liste an Tokens entfernen: int nBracketBalance = 1; while (!plTokens.isEmpty()) { if (plTokens.get(0).getType().equals(TokenTypes.TOKEN_BRACKET_OPENED)) { //Geoeffnete Klammer: nBracketBalance++; } else if (plTokens.get(0).getType().equals(TokenTypes.TOKEN_BRACKET_CLOSED)) { //Geschlossene Klammer: nBracketBalance--; } plTokens.remove(0); if (nBracketBalance == 0) { //Es wurden gleich viele Klammern geoeffnet und geschlossen -> Erster Operand wurde aus der Liste entfernt. break; } } } else { //Fuer den ersten Operanden muss keine weitere Rechnung durchgefuehrt werden: tOperand1AST.setContent(plTokens.get(0)); plTokens.remove(0); //Operanden entfernen. } //Zweiten Operanden herausfinden: BinaryTree<Token> tOperand2AST = new BinaryTree<Token>(); //Speichert den Teilbaum des zweiten Operanden. if (plTokens.get(0).getType().equals(TokenTypes.TOKEN_BRACKET_OPENED)) { //Fuer den zweiten Operanden muss eine weitere Rechnung durchgefuehrt werden: LinkedList<Token> lTokensOperand2 = new LinkedList<Token>(); plTokens.remove(0); //Klammer entfernen. lTokensOperand2.addAll(plTokens); ReturnValue<BinaryTree<Token>> tReturnOperand2 = new ReturnValue<BinaryTree<Token>>(); tReturnOperand2 = createBinaryTree(lTokensOperand2); //REKURSION :O; if (tReturnOperand2.getExecutionInformation() != ReturnValueTypes.SUCCESS) { //Es ist bei der Rekursion zu einem Fehler gekommen: return tReturnOperand2; } tOperand2AST = tReturnOperand2.getReturnValue(); //Rechnung des zweiten Operanden aus der Liste an Tokens entfernen: int nBracketBalance = 1; while (!plTokens.isEmpty()) { if (plTokens.get(0).getType().equals(TokenTypes.TOKEN_BRACKET_OPENED)) { //Geoeffnete Klammer: nBracketBalance++; } else if (plTokens.get(0).getType().equals(TokenTypes.TOKEN_BRACKET_CLOSED)) { //Geschlossene Klammer: nBracketBalance--; } plTokens.remove(0); if (nBracketBalance == 0) { //Es wurden gleich viele Klammern geoeffnet und geschlossen -> Zweiter Operand wurde aus der Liste entfernt. break; } } } else { //Fuer den zweiten Operanden muss keine weitere Rechnung durchgefuehrt werden: tOperand2AST.setContent(plTokens.get(0)); plTokens.remove(0); //Operanden entfernen. } //Operanden wurden herausgefunden: BinaryTree<Token> tAbstractSyntaxTree = new BinaryTree<Token>(operatorTokenObj, tOperand1AST, tOperand2AST); //Abstrakter Syntaxbaum, welcher fuer die Rekursion verwendet wird. //Rekursion starten: ReturnValue<BinaryTree<Token>> rekursionReturnObj = new ReturnValue<BinaryTree<Token>>(); //Speichert den Rueckgabewert der Rekursion. rekursionReturnObj = createBinaryTree(tAbstractSyntaxTree, plTokens); //REKURSION :O if (rekursionReturnObj.getExecutionInformation() != ReturnValueTypes.SUCCESS) { return rekursionReturnObj; } tAbstractSyntaxTree = rekursionReturnObj.getReturnValue(); return new ReturnValue<BinaryTree<Token>>(tAbstractSyntaxTree, ReturnValueTypes.SUCCESS); } /** * Erstellt einen abstrakten Syntaxbaum, anhand einer Liste an Tokens. * * @param plTokens Liste an Tokens, welche verarbeitet werden sollen. * @return Abstrakter Syntaxbaum. */ public ReturnValue<BinaryTree<Token>> parse(LinkedList<Token> plTokens) { if (plTokens.isEmpty()) { //Liste an<SUF> return new ReturnValue<BinaryTree<Token>>(null, ReturnValueTypes.ERROR_SYNTAX); } else { int nOpenedBrackets = 0; int nClosedBrackets = 0; for (int i = 0; i < plTokens.size(); i++) { if (plTokens.get(i).getType().equals(TokenTypes.TOKEN_BRACKET_OPENED)) { nOpenedBrackets++; } else if (plTokens.get(i).getType().equals(TokenTypes.TOKEN_BRACKET_CLOSED)) { nClosedBrackets++; } } if (nOpenedBrackets != nClosedBrackets) { //Die Anzahl an geoeffneten und geschlossenen Klammern stimmen nicht ueberein: return new ReturnValue<BinaryTree<Token>>(null, ReturnValueTypes.ERROR_SYNTAX); } } plTokens.remove(0); if (plTokens.isEmpty()) { //Keine Tokens vorhanden: return new ReturnValue(null, ReturnValueTypes.ERROR_SYNTAX); } ReturnValue<BinaryTree<Token>> rekursionReturn = new ReturnValue<BinaryTree<Token>>(); rekursionReturn = createBinaryTree(plTokens); //REKURSION :O return rekursionReturn; } }
96421_0
package jflowsim.model.geometry2d; import jflowsim.model.numerics.UniformGrid; import java.util.LinkedList; public class Delaunay2D extends Geometry2D { private LinkedList<Point2D> pointList; private LinkedList<Triangle2D> triangleList; private Point2D center; private Point2D selectedPoint = null; private double minX, minY, maxX, maxY; public Delaunay2D() { this.center = new Point2D(0.0, 0.0); this.pointList = new LinkedList<Point2D>(); this.triangleList = new LinkedList<Triangle2D>(); super.setChanged(); super.notifyObservers(); } public Geometry2D clone() { Delaunay2D del = new Delaunay2D(); del.pointList = pointList; return del; } public void setPoint(Point2D p) { pointList.add(p); calculateValues(); super.setChanged(); super.notifyObservers(); } public void removePoint(Point2D p) { pointList.remove(p); calculateValues(); super.setChanged(); super.notifyObservers(); } // testet ob Koordinaten (x,y) innerhalb der Geometrie liegen public boolean isPointInside(double x, double y) { return false; } public void moveObject(double x, double y) { // Punkt verschieben if (selectedPoint != null) { this.selectedPoint.setX(x); this.selectedPoint.setY(y); }// // Kanten verschieben else { double dx = x - getCenterX(); double dy = y - getCenterY(); for (Point2D p : pointList) { p.setX(p.getX() + dx); p.setY(p.getY() + dy); } } calculateValues(); super.setChanged(); super.notifyObservers(); } private void calculateValues() { minY = minX = Double.MAX_VALUE; maxX = maxY = -Double.MAX_VALUE; for (Point2D p : pointList) { if (p.getX() < minX) { minX = p.getX(); } if (p.getY() < minY) { minY = p.getY(); } if (p.getX() > maxX) { maxX = p.getX(); } if (p.getY() > maxY) { maxY = p.getY(); } } this.center.setX(0.5 * (maxX - minX)); this.center.setY(0.5 * (maxY - minY)); triangulate(); } public double getCenterX() { if (selectedPoint != null) { return selectedPoint.getX(); } else { return this.center.getX(); } } public double getMinX() { return minX; } public double getMaxX() { return maxX; } public double getCenterY() { if (selectedPoint != null) { return selectedPoint.getY(); } else { return center.getY(); } } public double getMinY() { return minY; } public double getMaxY() { return maxY; } public boolean isPointOnBoundary(double x, double y, double r) { // Prüft ob Koordinate (x,y) auf einem Kontrollpunkt der Bezierkurve liegt for (Point2D p : pointList) { if ((Math.abs(x - p.getX()) < r) && (Math.abs(y - p.getY()) < r)) { this.selectedPoint = p; return true; } } this.selectedPoint = null; // Prüft ob Koordinate (x,y) auf einer Kante der Triangulierung liegt for(Triangle2D tri : triangleList){ if(tri.isPointOnBoundary(x, y, r)){ return true; } } return false; } public LinkedList<Point2D> getPointList() { return pointList; } private double getMaxDimension() { double minX = Double.MAX_VALUE; double minY = Double.MAX_VALUE; double maxX = -Double.MAX_VALUE; double maxY = -Double.MAX_VALUE; for (Point2D p : pointList) { if (p.getX() < minX) { minX = p.getX(); } if (p.getX() > maxX) { maxX = p.getX(); } if (p.getY() < minY) { minY = p.getY(); } if (p.getY() > maxY) { maxY = p.getY(); } } return Math.max(Math.abs(maxX - minX), maxY - minY); } private Triangle2D findTriangleWithEdge(Point2D p1, Point2D p2) { for (Triangle2D triangle : triangleList) { if (triangle.p1 == p1 || triangle.p2 == p1 || triangle.p3 == p1) { if (triangle.p1 == p2 || triangle.p2 == p2 || triangle.p3 == p2) { return triangle; } } } return null; } private void triangulate() { // Abbrechen bei weniger als drei Punkten if (pointList.size() < 3) { return; } // lösche alte Triangulierung triangleList.clear(); // Finde maximale Ausdehnung double m = getMaxDimension(); // baue Ausgangsdreieck Point2D p1 = new Point2D(0.0, 3.0 * m); Point2D p2 = new Point2D(3.0 * m, 0.0); Point2D p3 = new Point2D(-3.0 * m, -3.0 * m); triangleList.add(new Triangle2D(p1, p2, p3)); // Füge Punkte der Liste hinzu for (Point2D p : pointList) { LinkedList<Triangle2D> newTriangles = new LinkedList<Triangle2D>(); for (int i = 0; i < triangleList.size(); i++) { Triangle2D triangle = triangleList.get(i); if (triangle.isPointInside(p)) { // altes Dreieck entfernen triangleList.remove(i); i--; // neue Dreiecke bauen Triangle2D t1 = new Triangle2D(triangle.p1, triangle.p2, p); Triangle2D t2 = new Triangle2D(triangle.p2, triangle.p3, p); Triangle2D t3 = new Triangle2D(triangle.p3, triangle.p1, p); // neue Dreiecke hinzufügen if (t1.getArea() > 1.E-8) { newTriangles.add(t1); } if (t2.getArea() > 1.E-8) { newTriangles.add(t2); } if (t3.getArea() > 1.E-8) { newTriangles.add(t3); } // Umkreisbedingung überprüfen - Kante 1 Triangle2D tmpT1 = findTriangleWithEdge(triangle.p1, triangle.p2); if (tmpT1 != null && t1.isPointInCircumCircle(tmpT1.getOppositePoint(triangle.p1, triangle.p2))) { t1.flipEdge(tmpT1); } // Umkreisbedingung überprüfen - Kante 2 Triangle2D tmpT2 = findTriangleWithEdge(triangle.p2, triangle.p3); if (tmpT2 != null && t2.isPointInCircumCircle(tmpT2.getOppositePoint(triangle.p2, triangle.p3))) { t2.flipEdge(tmpT2); } // Umkreisbedingung überprüfen - Kante 3 Triangle2D tmpT3 = findTriangleWithEdge(triangle.p3, triangle.p1); if (tmpT3 != null && t3.isPointInCircumCircle(tmpT3.getOppositePoint(triangle.p3, triangle.p1))) { t3.flipEdge(tmpT3); } } } triangleList.addAll(newTriangles); } // alle Dreiecke mit Verbindung zum äußeren Dreieck entfernen for (int i = 0; i < triangleList.size(); i++) { Triangle2D triangle = triangleList.get(i); if (triangle.contains(p1) || triangle.contains(p2) || triangle.contains(p3)) { triangleList.remove(i); i--; } } } public LinkedList<Triangle2D> getTriangleList() { return triangleList; } public void map2Grid(UniformGrid grid) { //throw new UnsupportedOperationException("Not supported yet."); } }
ChristianFJanssen/jflowsim
src/jflowsim/model/geometry2d/Delaunay2D.java
2,539
// testet ob Koordinaten (x,y) innerhalb der Geometrie liegen
line_comment
nl
package jflowsim.model.geometry2d; import jflowsim.model.numerics.UniformGrid; import java.util.LinkedList; public class Delaunay2D extends Geometry2D { private LinkedList<Point2D> pointList; private LinkedList<Triangle2D> triangleList; private Point2D center; private Point2D selectedPoint = null; private double minX, minY, maxX, maxY; public Delaunay2D() { this.center = new Point2D(0.0, 0.0); this.pointList = new LinkedList<Point2D>(); this.triangleList = new LinkedList<Triangle2D>(); super.setChanged(); super.notifyObservers(); } public Geometry2D clone() { Delaunay2D del = new Delaunay2D(); del.pointList = pointList; return del; } public void setPoint(Point2D p) { pointList.add(p); calculateValues(); super.setChanged(); super.notifyObservers(); } public void removePoint(Point2D p) { pointList.remove(p); calculateValues(); super.setChanged(); super.notifyObservers(); } // testet ob<SUF> public boolean isPointInside(double x, double y) { return false; } public void moveObject(double x, double y) { // Punkt verschieben if (selectedPoint != null) { this.selectedPoint.setX(x); this.selectedPoint.setY(y); }// // Kanten verschieben else { double dx = x - getCenterX(); double dy = y - getCenterY(); for (Point2D p : pointList) { p.setX(p.getX() + dx); p.setY(p.getY() + dy); } } calculateValues(); super.setChanged(); super.notifyObservers(); } private void calculateValues() { minY = minX = Double.MAX_VALUE; maxX = maxY = -Double.MAX_VALUE; for (Point2D p : pointList) { if (p.getX() < minX) { minX = p.getX(); } if (p.getY() < minY) { minY = p.getY(); } if (p.getX() > maxX) { maxX = p.getX(); } if (p.getY() > maxY) { maxY = p.getY(); } } this.center.setX(0.5 * (maxX - minX)); this.center.setY(0.5 * (maxY - minY)); triangulate(); } public double getCenterX() { if (selectedPoint != null) { return selectedPoint.getX(); } else { return this.center.getX(); } } public double getMinX() { return minX; } public double getMaxX() { return maxX; } public double getCenterY() { if (selectedPoint != null) { return selectedPoint.getY(); } else { return center.getY(); } } public double getMinY() { return minY; } public double getMaxY() { return maxY; } public boolean isPointOnBoundary(double x, double y, double r) { // Prüft ob Koordinate (x,y) auf einem Kontrollpunkt der Bezierkurve liegt for (Point2D p : pointList) { if ((Math.abs(x - p.getX()) < r) && (Math.abs(y - p.getY()) < r)) { this.selectedPoint = p; return true; } } this.selectedPoint = null; // Prüft ob Koordinate (x,y) auf einer Kante der Triangulierung liegt for(Triangle2D tri : triangleList){ if(tri.isPointOnBoundary(x, y, r)){ return true; } } return false; } public LinkedList<Point2D> getPointList() { return pointList; } private double getMaxDimension() { double minX = Double.MAX_VALUE; double minY = Double.MAX_VALUE; double maxX = -Double.MAX_VALUE; double maxY = -Double.MAX_VALUE; for (Point2D p : pointList) { if (p.getX() < minX) { minX = p.getX(); } if (p.getX() > maxX) { maxX = p.getX(); } if (p.getY() < minY) { minY = p.getY(); } if (p.getY() > maxY) { maxY = p.getY(); } } return Math.max(Math.abs(maxX - minX), maxY - minY); } private Triangle2D findTriangleWithEdge(Point2D p1, Point2D p2) { for (Triangle2D triangle : triangleList) { if (triangle.p1 == p1 || triangle.p2 == p1 || triangle.p3 == p1) { if (triangle.p1 == p2 || triangle.p2 == p2 || triangle.p3 == p2) { return triangle; } } } return null; } private void triangulate() { // Abbrechen bei weniger als drei Punkten if (pointList.size() < 3) { return; } // lösche alte Triangulierung triangleList.clear(); // Finde maximale Ausdehnung double m = getMaxDimension(); // baue Ausgangsdreieck Point2D p1 = new Point2D(0.0, 3.0 * m); Point2D p2 = new Point2D(3.0 * m, 0.0); Point2D p3 = new Point2D(-3.0 * m, -3.0 * m); triangleList.add(new Triangle2D(p1, p2, p3)); // Füge Punkte der Liste hinzu for (Point2D p : pointList) { LinkedList<Triangle2D> newTriangles = new LinkedList<Triangle2D>(); for (int i = 0; i < triangleList.size(); i++) { Triangle2D triangle = triangleList.get(i); if (triangle.isPointInside(p)) { // altes Dreieck entfernen triangleList.remove(i); i--; // neue Dreiecke bauen Triangle2D t1 = new Triangle2D(triangle.p1, triangle.p2, p); Triangle2D t2 = new Triangle2D(triangle.p2, triangle.p3, p); Triangle2D t3 = new Triangle2D(triangle.p3, triangle.p1, p); // neue Dreiecke hinzufügen if (t1.getArea() > 1.E-8) { newTriangles.add(t1); } if (t2.getArea() > 1.E-8) { newTriangles.add(t2); } if (t3.getArea() > 1.E-8) { newTriangles.add(t3); } // Umkreisbedingung überprüfen - Kante 1 Triangle2D tmpT1 = findTriangleWithEdge(triangle.p1, triangle.p2); if (tmpT1 != null && t1.isPointInCircumCircle(tmpT1.getOppositePoint(triangle.p1, triangle.p2))) { t1.flipEdge(tmpT1); } // Umkreisbedingung überprüfen - Kante 2 Triangle2D tmpT2 = findTriangleWithEdge(triangle.p2, triangle.p3); if (tmpT2 != null && t2.isPointInCircumCircle(tmpT2.getOppositePoint(triangle.p2, triangle.p3))) { t2.flipEdge(tmpT2); } // Umkreisbedingung überprüfen - Kante 3 Triangle2D tmpT3 = findTriangleWithEdge(triangle.p3, triangle.p1); if (tmpT3 != null && t3.isPointInCircumCircle(tmpT3.getOppositePoint(triangle.p3, triangle.p1))) { t3.flipEdge(tmpT3); } } } triangleList.addAll(newTriangles); } // alle Dreiecke mit Verbindung zum äußeren Dreieck entfernen for (int i = 0; i < triangleList.size(); i++) { Triangle2D triangle = triangleList.get(i); if (triangle.contains(p1) || triangle.contains(p2) || triangle.contains(p3)) { triangleList.remove(i); i--; } } } public LinkedList<Triangle2D> getTriangleList() { return triangleList; } public void map2Grid(UniformGrid grid) { //throw new UnsupportedOperationException("Not supported yet."); } }
43418_1
package com.example.thomasmoreboekingssysteem; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import android.widget.ViewAnimator; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import com.google.android.material.floatingactionbutton.FloatingActionButton; import org.json.JSONException; import org.json.JSONObject; public class WachtwoordVergeten extends AppCompatActivity { Boolean admin,status; String id,naam,voornaam,wachtwoord; @SuppressLint("MissingInflatedId") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_wachtwoord_vergeten); Button button; button = findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { EditText wachtwoord1 = findViewById(R.id.textInputLayout4); EditText wachtwoord2 = findViewById(R.id.editTextTextPassword2); EditText input = findViewById(R.id.inputpersoneel); String personeelnummerinlog = input.getText().toString().trim(); String url = "https://boekingssysteem-api.azurewebsites.net/api/Persoon/get" + personeelnummerinlog.trim(); String url2 = "https://boekingssysteem-api.azurewebsites.net/api/Persoon/put" + personeelnummerinlog.trim(); JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { id = response.getString("personeelnummer"); naam = response.getString("naam"); voornaam = response.getString("voornaam"); admin = response.getBoolean("admin"); status = response.getBoolean("aanwezig"); if (personeelnummerinlog == ""){ Toast.makeText(WachtwoordVergeten.this, "Personeelnummer moet ingevuld zijn", Toast.LENGTH_LONG).show(); }else{ if (wachtwoord1.getText().toString().equals("") || wachtwoord2.getText().toString().equals("")){ Toast.makeText(WachtwoordVergeten.this, "Wachtwoorden moet ingevuld zijn", Toast.LENGTH_LONG).show(); }else{ if (!wachtwoord1.getText().toString().equals(wachtwoord2.getText().toString())){ Toast.makeText(WachtwoordVergeten.this, "Wachtwoorden moet overeen komen", Toast.LENGTH_LONG).show(); } if(wachtwoord1.getText().length() < 8 && wachtwoord2.getText().length() < 8){ Toast.makeText(WachtwoordVergeten.this, "Wachtwoord moet minstens 8 tekens lang zijn", Toast.LENGTH_LONG).show(); } else{ JSONObject data = new JSONObject(); try { wachtwoord = wachtwoord1.getText().toString(); //data.put("Content-Type", "application/json"); data.put("personeelnummer", id); data.put("naam", naam); data.put("voornaam", voornaam); data.put("aanwezig", status); data.put("admin", admin); data.put("wachtwoord", wachtwoord); } catch (JSONException e) { e.printStackTrace(); } JsonObjectRequest request = new JsonObjectRequest(Request.Method.PUT, url2, data, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // Handle the response if needed. } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("Error", error.toString()); } }); RequestQueue queue = Volley.newRequestQueue(WachtwoordVergeten.this); queue.add(request); Toast.makeText(WachtwoordVergeten.this, "Wachtwoord is aangepast", Toast.LENGTH_SHORT).show(); } } } } catch (JSONException e) { e.printStackTrace(); Toast.makeText(WachtwoordVergeten.this, "Personeelnummer niet gevonden", Toast.LENGTH_SHORT).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(WachtwoordVergeten.this, "Personeelnummer niet gevonden", Toast.LENGTH_SHORT).show(); } }); RequestQueue queue = Volley.newRequestQueue(WachtwoordVergeten.this); queue.add(request); } }); } }
ChristopheM98/Boekingssysteem-mobiel-app
app/src/main/java/com/example/thomasmoreboekingssysteem/WachtwoordVergeten.java
1,668
//boekingssysteem-api.azurewebsites.net/api/Persoon/put" + personeelnummerinlog.trim();
line_comment
nl
package com.example.thomasmoreboekingssysteem; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import android.widget.ViewAnimator; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import com.google.android.material.floatingactionbutton.FloatingActionButton; import org.json.JSONException; import org.json.JSONObject; public class WachtwoordVergeten extends AppCompatActivity { Boolean admin,status; String id,naam,voornaam,wachtwoord; @SuppressLint("MissingInflatedId") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_wachtwoord_vergeten); Button button; button = findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { EditText wachtwoord1 = findViewById(R.id.textInputLayout4); EditText wachtwoord2 = findViewById(R.id.editTextTextPassword2); EditText input = findViewById(R.id.inputpersoneel); String personeelnummerinlog = input.getText().toString().trim(); String url = "https://boekingssysteem-api.azurewebsites.net/api/Persoon/get" + personeelnummerinlog.trim(); String url2 = "https://boekingssysteem-api.azurewebsites.net/api/Persoon/put" +<SUF> JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { id = response.getString("personeelnummer"); naam = response.getString("naam"); voornaam = response.getString("voornaam"); admin = response.getBoolean("admin"); status = response.getBoolean("aanwezig"); if (personeelnummerinlog == ""){ Toast.makeText(WachtwoordVergeten.this, "Personeelnummer moet ingevuld zijn", Toast.LENGTH_LONG).show(); }else{ if (wachtwoord1.getText().toString().equals("") || wachtwoord2.getText().toString().equals("")){ Toast.makeText(WachtwoordVergeten.this, "Wachtwoorden moet ingevuld zijn", Toast.LENGTH_LONG).show(); }else{ if (!wachtwoord1.getText().toString().equals(wachtwoord2.getText().toString())){ Toast.makeText(WachtwoordVergeten.this, "Wachtwoorden moet overeen komen", Toast.LENGTH_LONG).show(); } if(wachtwoord1.getText().length() < 8 && wachtwoord2.getText().length() < 8){ Toast.makeText(WachtwoordVergeten.this, "Wachtwoord moet minstens 8 tekens lang zijn", Toast.LENGTH_LONG).show(); } else{ JSONObject data = new JSONObject(); try { wachtwoord = wachtwoord1.getText().toString(); //data.put("Content-Type", "application/json"); data.put("personeelnummer", id); data.put("naam", naam); data.put("voornaam", voornaam); data.put("aanwezig", status); data.put("admin", admin); data.put("wachtwoord", wachtwoord); } catch (JSONException e) { e.printStackTrace(); } JsonObjectRequest request = new JsonObjectRequest(Request.Method.PUT, url2, data, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // Handle the response if needed. } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("Error", error.toString()); } }); RequestQueue queue = Volley.newRequestQueue(WachtwoordVergeten.this); queue.add(request); Toast.makeText(WachtwoordVergeten.this, "Wachtwoord is aangepast", Toast.LENGTH_SHORT).show(); } } } } catch (JSONException e) { e.printStackTrace(); Toast.makeText(WachtwoordVergeten.this, "Personeelnummer niet gevonden", Toast.LENGTH_SHORT).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(WachtwoordVergeten.this, "Personeelnummer niet gevonden", Toast.LENGTH_SHORT).show(); } }); RequestQueue queue = Volley.newRequestQueue(WachtwoordVergeten.this); queue.add(request); } }); } }
113506_2
/* * Copyright (c) 2018 Cisco and/or its affiliates. * * This software is licensed to you under the terms of the Cisco Sample * Code License, Version 1.0 (the "License"). You may obtain a copy of the * License at * * https://developer.cisco.com/docs/licenses * * All use of the material herein must be in accordance with the terms of * the License. All rights not expressly granted by the License are * reserved. Unless required by applicable law or agreed to separately 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. */ package com.cisco.dnac; import android.util.Base64; import android.util.Log; import java.util.List; import cisco.com.dnac.v1.api.client.ApiInvoker; import cisco.com.dnac.v1.api.*; import api.NetworkDeviceApi; import model.CountResult; import model.NetworkDeviceListResult; import model.NetworkDeviceListResultResponse; import api.MiscApi; /* THIS FILE IS RESPONSIBLE FOR ACCESSING THE ACTUAL METHODS IN INTERACTING WITH DNAC */ public class DnacAccessClass { private String REQUEST_TAG ="DnacAccessClass"; private String cookie = null; private String username = null; private String password = null; private String DnacIPaddress = null; private ApiInvoker apiInvoker = null; private MiscApi miscApi = null; private NetworkDeviceApi networkDeviceApi = null; private static DnacAccessClass instance = null; //Device Details parameters List<String> hostname = null; List<String> managementIpAddress = null; List<String> macAddress = null; List<String> locationName = null; List<String> serialNumber = null; List<String> location = null; List<String> family = null; List<String> type = null; List<String> series = null; List<String> collectionStatus = null; List<String> collectionInterval = null; List<String> notSyncedForMinutes = null; List<String> errorCode = null; List<String> errorDescription = null; List<String> softwareVersion = null; List<String> softwareType = null; List<String> platformId = null; List<String> role = null; List<String> reachabilityStatus = null; List<String> upTime = null; List<String> associatedWlcIp = null; List<String> licenseName = null; List<String> licenseType = null; List<String> licenseStatus = null; List<String> modulename = null; List<String> moduleequpimenttype = null; List<String> moduleservicestate = null; List<String> modulevendorequipmenttype = null; List<String> modulepartnumber = null; List<String> moduleoperationstatecode = null; String id = null; // public String getcookie() { return cookie; } public String getusername() { return username; } public String getPassword() { return password;} public String getDnacIPaddress() { return DnacIPaddress; } public void setCookie(String rawCookie) { cookie = rawCookie; } public void setUsername(String username_) { username = username_; } public void setDnacIPaddress(String IpAddress) { DnacIPaddress = IpAddress; } public void setPassword(String pwd) { password = pwd; } private DnacAccessClass() { Log.e(REQUEST_TAG,"DnacAccessClass constructor"); miscApi = new MiscApi(); networkDeviceApi = new NetworkDeviceApi(); } /* SINGLETON INSTANCE FOR ACCESSING THE DNAC METHODS */ public static DnacAccessClass getInstance() { if (instance == null) { synchronized(DnacAccessClass.class) { if (instance == null) { instance = new DnacAccessClass(); } } } return instance; } /* METHOD TO RETRIEVE THE COUNT FROM DNAC * networkDeviceApi to be configured for Cookie and Dnac IP Address * */ public Integer getNetworkDeviceCount_() { Integer count = 0; Log.e(REQUEST_TAG,"entering getNetworkDeviceCount_ function "); networkDeviceApi.addHeader("cookie", cookie); networkDeviceApi.setBasePath(DnacIPaddress); try { CountResult result = networkDeviceApi.getNetworkDeviceCount(); count = result.getResponse(); Log.e(REQUEST_TAG,"result "+count); }catch (Exception e){ e.printStackTrace(); } return count; } /* METHOD TO FETCH THE AUTH TOKEN FROM DNAC * miscApi to be configured for DnacIpAddress and Authorization * */ public String getAuthToken(){ Log.e(REQUEST_TAG,"entering getAuthToken function "); String credentials = username+":"+password; String auth = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); miscApi.setBasePath(DnacIPaddress); miscApi.addHeader("Authorization",auth); try { return miscApi.postAuthToken(null,auth).getToken(); }catch (Exception e){ e.printStackTrace(); } return null; } /* METHOD TO RETRIEVE THE NETWORK DEVICE LIST FROM DNAC * networkDeviceApi to be configured for Cookie and Dnac IP Address * */ public List<NetworkDeviceListResultResponse> getNetworkDeviceAllResponse_(){ Log.e(REQUEST_TAG,"entering getDeviceList function "); networkDeviceApi.setBasePath(DnacIPaddress); networkDeviceApi.addHeader("cookie",cookie); try { return networkDeviceApi.getNetworkDevice(hostname, managementIpAddress, macAddress, locationName, serialNumber, location, family, type, series, collectionStatus, collectionInterval, notSyncedForMinutes, errorCode, errorDescription, softwareVersion, softwareType, platformId, role, reachabilityStatus, upTime, associatedWlcIp, licenseName, licenseType, licenseStatus, modulename, moduleequpimenttype, moduleservicestate, modulevendorequipmenttype, modulepartnumber, moduleoperationstatecode, id).getResponse(); }catch (Exception e){ e.printStackTrace(); } return null; } /* METHOD TO RETRIEVE THE SPECIFIC DEVICE DETAILS * networkDeviceApi to be configured for Cookie and Dnac IP Address * */ public String[] getListViewButtonDetails(){ String[] ButtonDetails =null; List<NetworkDeviceListResultResponse> networkDeviceAllResponseResponseList; networkDeviceAllResponseResponseList = getNetworkDeviceAllResponse_(); Log.e(REQUEST_TAG, "entering getListviewButtonDetails function "); ButtonDetails =new String[networkDeviceAllResponseResponseList.size()]; for (int i = 0; i < networkDeviceAllResponseResponseList.size(); i++) { ButtonDetails[i] = "MgmtIp - " + networkDeviceAllResponseResponseList.get(i).getManagementIpAddress() + "\n" + "Hostname - " + networkDeviceAllResponseResponseList.get(i).getHostname(); } return ButtonDetails; } }
CiscoDevNet/DNAC-Android-SDK
sample-app/DNAC-Android-SDK/app/src/main/java/com/cisco/dnac/DnacAccessClass.java
1,952
//Device Details parameters
line_comment
nl
/* * Copyright (c) 2018 Cisco and/or its affiliates. * * This software is licensed to you under the terms of the Cisco Sample * Code License, Version 1.0 (the "License"). You may obtain a copy of the * License at * * https://developer.cisco.com/docs/licenses * * All use of the material herein must be in accordance with the terms of * the License. All rights not expressly granted by the License are * reserved. Unless required by applicable law or agreed to separately 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. */ package com.cisco.dnac; import android.util.Base64; import android.util.Log; import java.util.List; import cisco.com.dnac.v1.api.client.ApiInvoker; import cisco.com.dnac.v1.api.*; import api.NetworkDeviceApi; import model.CountResult; import model.NetworkDeviceListResult; import model.NetworkDeviceListResultResponse; import api.MiscApi; /* THIS FILE IS RESPONSIBLE FOR ACCESSING THE ACTUAL METHODS IN INTERACTING WITH DNAC */ public class DnacAccessClass { private String REQUEST_TAG ="DnacAccessClass"; private String cookie = null; private String username = null; private String password = null; private String DnacIPaddress = null; private ApiInvoker apiInvoker = null; private MiscApi miscApi = null; private NetworkDeviceApi networkDeviceApi = null; private static DnacAccessClass instance = null; //Device Details<SUF> List<String> hostname = null; List<String> managementIpAddress = null; List<String> macAddress = null; List<String> locationName = null; List<String> serialNumber = null; List<String> location = null; List<String> family = null; List<String> type = null; List<String> series = null; List<String> collectionStatus = null; List<String> collectionInterval = null; List<String> notSyncedForMinutes = null; List<String> errorCode = null; List<String> errorDescription = null; List<String> softwareVersion = null; List<String> softwareType = null; List<String> platformId = null; List<String> role = null; List<String> reachabilityStatus = null; List<String> upTime = null; List<String> associatedWlcIp = null; List<String> licenseName = null; List<String> licenseType = null; List<String> licenseStatus = null; List<String> modulename = null; List<String> moduleequpimenttype = null; List<String> moduleservicestate = null; List<String> modulevendorequipmenttype = null; List<String> modulepartnumber = null; List<String> moduleoperationstatecode = null; String id = null; // public String getcookie() { return cookie; } public String getusername() { return username; } public String getPassword() { return password;} public String getDnacIPaddress() { return DnacIPaddress; } public void setCookie(String rawCookie) { cookie = rawCookie; } public void setUsername(String username_) { username = username_; } public void setDnacIPaddress(String IpAddress) { DnacIPaddress = IpAddress; } public void setPassword(String pwd) { password = pwd; } private DnacAccessClass() { Log.e(REQUEST_TAG,"DnacAccessClass constructor"); miscApi = new MiscApi(); networkDeviceApi = new NetworkDeviceApi(); } /* SINGLETON INSTANCE FOR ACCESSING THE DNAC METHODS */ public static DnacAccessClass getInstance() { if (instance == null) { synchronized(DnacAccessClass.class) { if (instance == null) { instance = new DnacAccessClass(); } } } return instance; } /* METHOD TO RETRIEVE THE COUNT FROM DNAC * networkDeviceApi to be configured for Cookie and Dnac IP Address * */ public Integer getNetworkDeviceCount_() { Integer count = 0; Log.e(REQUEST_TAG,"entering getNetworkDeviceCount_ function "); networkDeviceApi.addHeader("cookie", cookie); networkDeviceApi.setBasePath(DnacIPaddress); try { CountResult result = networkDeviceApi.getNetworkDeviceCount(); count = result.getResponse(); Log.e(REQUEST_TAG,"result "+count); }catch (Exception e){ e.printStackTrace(); } return count; } /* METHOD TO FETCH THE AUTH TOKEN FROM DNAC * miscApi to be configured for DnacIpAddress and Authorization * */ public String getAuthToken(){ Log.e(REQUEST_TAG,"entering getAuthToken function "); String credentials = username+":"+password; String auth = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); miscApi.setBasePath(DnacIPaddress); miscApi.addHeader("Authorization",auth); try { return miscApi.postAuthToken(null,auth).getToken(); }catch (Exception e){ e.printStackTrace(); } return null; } /* METHOD TO RETRIEVE THE NETWORK DEVICE LIST FROM DNAC * networkDeviceApi to be configured for Cookie and Dnac IP Address * */ public List<NetworkDeviceListResultResponse> getNetworkDeviceAllResponse_(){ Log.e(REQUEST_TAG,"entering getDeviceList function "); networkDeviceApi.setBasePath(DnacIPaddress); networkDeviceApi.addHeader("cookie",cookie); try { return networkDeviceApi.getNetworkDevice(hostname, managementIpAddress, macAddress, locationName, serialNumber, location, family, type, series, collectionStatus, collectionInterval, notSyncedForMinutes, errorCode, errorDescription, softwareVersion, softwareType, platformId, role, reachabilityStatus, upTime, associatedWlcIp, licenseName, licenseType, licenseStatus, modulename, moduleequpimenttype, moduleservicestate, modulevendorequipmenttype, modulepartnumber, moduleoperationstatecode, id).getResponse(); }catch (Exception e){ e.printStackTrace(); } return null; } /* METHOD TO RETRIEVE THE SPECIFIC DEVICE DETAILS * networkDeviceApi to be configured for Cookie and Dnac IP Address * */ public String[] getListViewButtonDetails(){ String[] ButtonDetails =null; List<NetworkDeviceListResultResponse> networkDeviceAllResponseResponseList; networkDeviceAllResponseResponseList = getNetworkDeviceAllResponse_(); Log.e(REQUEST_TAG, "entering getListviewButtonDetails function "); ButtonDetails =new String[networkDeviceAllResponseResponseList.size()]; for (int i = 0; i < networkDeviceAllResponseResponseList.size(); i++) { ButtonDetails[i] = "MgmtIp - " + networkDeviceAllResponseResponseList.get(i).getManagementIpAddress() + "\n" + "Hostname - " + networkDeviceAllResponseResponseList.get(i).getHostname(); } return ButtonDetails; } }
130537_9
package com.dre.brewery.filedata; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import com.dre.brewery.P; public class ConfigUpdater { private ArrayList<String> config = new ArrayList<String>(); private File file; public ConfigUpdater(File file) { this.file = file; getConfigString(); } // Returns the index of the line that starts with 'lineStart', returns -1 if not found; public int indexOfStart(String lineStart) { for (int i = 0; i < config.size(); i++) { if (config.get(i).startsWith(lineStart)) { return i; } } return -1; } // Adds some lines to the end public void appendLines(String... lines) { config.addAll(Arrays.asList(lines)); } // Replaces the line at the index with the new Line public void setLine(int index, String newLine) { config.set(index, newLine); } // adds some Lines at the index public void addLines(int index, String... newLines) { config.addAll(index, Arrays.asList(newLines)); } public void saveConfig() { StringBuilder stringBuilder = new StringBuilder(""); for (String line : config) { stringBuilder.append(line).append("\n"); } String configString = stringBuilder.toString().trim(); try { BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.write(configString); writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } private void getConfigString() { try { BufferedReader reader = new BufferedReader(new FileReader(file)); String currentLine; while((currentLine = reader.readLine()) != null) { config.add(currentLine); } reader.close(); } catch (IOException e) { e.printStackTrace(); } } // ---- Updating to newer Versions ---- // Update from a specified Config version and language to the newest version public void update(String fromVersion, String lang) { if (fromVersion.equals("0.5")) { // Version 0.5 was only released for de, but with en as setting, so default to de if (!lang.equals("de")) { lang = "de"; } } if (fromVersion.equals("0.5") || fromVersion.equals("1.0")) { if (lang.equals("de")) { update05de(); } else { update10en(); } fromVersion = "1.1"; } if (fromVersion.equals("1.1") || fromVersion.equals("1.1.1")) { if (lang.equals("de")) { update11de(); } else { update11en(); } fromVersion = "1.2"; } if (fromVersion.equals("1.2")) { if (lang.equals("de")) { update12de(); } else { update12en(); } fromVersion = "1.3"; } if (fromVersion.equals("1.3")) { if (lang.equals("de")) { update13de(); } else { update13en(); } fromVersion = "1.3.1"; } if (!fromVersion.equals("1.3.1")) { P.p.log(P.p.languageReader.get("Error_ConfigUpdate", fromVersion)); return; } saveConfig(); } // Update the Version String private void updateVersion(String to) { int index = indexOfStart("version"); String line = "version: '" + to + "'"; if (index != -1) { setLine(index, line); } else { index = indexOfStart("# Config Version"); if (index == -1) { index = indexOfStart("autosave"); } if (index == -1) { appendLines(line); } else { addLines(index, line); } } } // Updates de from 0.5 to 1.1 private void update05de() { updateVersion("1.1"); // Default language to de int index = indexOfStart("language: en"); if (index != -1) { setLine(index, "language: de"); P.p.language = "de"; } // Add the new entries for the Word Distortion above the words section String[] entries = { "# -- Chat Veränderungs Einstellungen --", "", "# Text nach den angegebenen Kommandos wird bei Trunkenheit ebenfalls Verändert (Liste) [- /gl]", "distortCommands:", "- /gl", "- /global", "- /fl", "- /s", "- /letter", "", "# Geschriebenen Text auf Schildern bei Trunkenheit verändern [false]", "distortSignText: false", "", "# Text, der zwischen diesen Buchstaben steht, wird nicht verändert (\",\" als Trennung verwenden) (Liste) [- '[,]']", "distortBypass:", "- '*,*'", "- '[,]'", "" }; index = indexOfStart("# words"); if (index == -1) { index = indexOfStart("# Diese werden von oben"); } if (index == -1) { index = indexOfStart("# replace"); } if (index == -1) { index = indexOfStart("words:"); } if (index == -1) { appendLines(entries); } else { addLines(index, entries); } // Add some new separators for overview String line = "# -- Verschiedene Einstellungen --"; index = indexOfStart("# Verschiedene Einstellungen"); if (index != -1) { setLine(index, line); } line = "# -- Rezepte für Getränke --"; index = indexOfStart("# Rezepte für Getränke"); if (index != -1) { setLine(index, line); } } // Updates en from 1.0 to 1.1 private void update10en() { // Update version String updateVersion("1.1"); // Add the new entries for the Word Distortion above the words section String[] entries = { "# -- Chat Distortion Settings --", "", "# Text after specified commands will be distorted when drunk (list) [- /gl]", "distortCommands:", "- /gl", "- /global", "- /fl", "- /s", "- /letter", "", "# Distort the Text written on a Sign while drunk [false]", "distortSignText: false", "", "# Enclose a text with these Letters to bypass Chat Distortion (Use \",\" as Separator) (list) [- '[,]']", "distortBypass:", "- '*,*'", "- '[,]'", "" }; int index = indexOfStart("# words"); if (index == -1) { index = indexOfStart("# Will be processed"); } if (index == -1) { index = indexOfStart("# replace"); } if (index == -1) { index = indexOfStart("words:"); } if (index == -1) { appendLines(entries); } else { addLines(index, entries); } // Add some new separators for overview String line = "# -- Settings --"; index = indexOfStart("# Settings"); if (index != -1) { setLine(index, line); } line = "# -- Recipes for Potions --"; index = indexOfStart("# Recipes for Potions"); if (index != -1) { setLine(index, line); } } // Updates de from 1.1 to 1.2 private void update11de() { updateVersion("1.2"); int index = indexOfStart("# Das Item kann nicht aufgesammelt werden"); if (index != -1) { setLine(index, "# Das Item kann nicht aufgesammelt werden und bleibt bis zum Despawnen liegen. (Achtung: Kann nach Serverrestart aufgesammelt werden!)"); } // Add the BarrelAccess Setting String[] lines = { "# Ob große Fässer an jedem Block geöffnet werden können, nicht nur an Zapfhahn und Schild. Bei kleinen Fässern geht dies immer. [true]", "openLargeBarrelEverywhere: true", "" }; index = indexOfStart("colorInBrewer") + 2; if (index == 1) { index = indexOfStart("colorInBarrels") + 2; } if (index == 1) { index = indexOfStart("# Autosave"); } if (index == -1) { index = indexOfStart("language") + 2; } if (index == 1) { addLines(3, lines); } else { addLines(index, lines); } // Add Plugin Support Settings lines = new String[] { "", "# -- Plugin Kompatiblität --", "", "# Andere Plugins (wenn installiert) nach Rechten zum öffnen von Fässern checken [true]", "useWorldGuard: true", "useLWC: true", "useGriefPrevention: true", "", "# Änderungen an Fassinventaren mit LogBlock aufzeichen [true]", "useLogBlock: true", "", "" }; index = indexOfStart("# -- Chat Veränderungs Einstellungen"); if (index == -1) { index = indexOfStart("# words"); } if (index == -1) { index = indexOfStart("distortCommands"); if (index > 4) { index -= 4; } } if (index != -1) { addLines(index, lines); } else { appendLines(lines); } } // Updates en from 1.1 to 1.2 private void update11en() { updateVersion("1.2"); int index = indexOfStart("# The item can not be collected"); if (index != -1) { setLine(index, "# The item can not be collected and stays on the ground until it despawns. (Warning: Can be collected after Server restart!)"); } // Add the BarrelAccess Setting String[] lines = { "# If a Large Barrel can be opened by clicking on any of its blocks, not just Spigot or Sign. This is always true for Small Barrels. [true]", "openLargeBarrelEverywhere: true", "" }; index = indexOfStart("colorInBrewer") + 2; if (index == 1) { index = indexOfStart("colorInBarrels") + 2; } if (index == 1) { index = indexOfStart("# Autosave"); } if (index == -1) { index = indexOfStart("language") + 2; } if (index == 1) { addLines(3, lines); } else { addLines(index, lines); } // Add Plugin Support Settings lines = new String[] { "", "# -- Plugin Compatibility --", "", "# Enable checking of other Plugins (if installed) for Barrel Permissions [true]", "useWorldGuard: true", "useLWC: true", "useGriefPrevention: true", "", "# Enable the Logging of Barrel Inventories to LogBlock [true]", "useLogBlock: true", "", "" }; index = indexOfStart("# -- Chat Distortion Settings"); if (index == -1) { index = indexOfStart("# words"); } if (index == -1) { index = indexOfStart("distortCommands"); if (index > 4) { index -= 4; } } if (index != -1) { addLines(index, lines); } else { appendLines(lines); } } // Update de from 1.2 to 1.3 private void update12de() { updateVersion("1.3"); // Add the new Wood Types to the Description int index = indexOfStart("# wood:"); if (index != -1) { setLine(index, "# wood: Holz des Fasses 0=alle Holzsorten 1=Birke 2=Eiche 3=Jungel 4=Fichte 5=Akazie 6=Schwarzeiche"); } // Add the Example to the Cooked Section index = indexOfStart("# cooked:"); if (index != -1) { addLines(index + 1, "# [Beispiel] MATERIAL_oder_id: Name nach Gähren"); } // Add new ingredients description String replacedLine = "# ingredients: Auflistung von 'Material oder ID,Data/Anzahl'"; String[] lines = new String[] { "# (Item-ids anstatt Material werden von Bukkit nicht mehr unterstützt und funktionieren möglicherweise in Zukunft nicht mehr!)", "# Eine Liste von allen Materialien kann hier gefunden werden: http://jd.bukkit.org/beta/apidocs/org/bukkit/Material.html", "# Es kann ein Data-Wert angegeben werden, weglassen ignoriert diesen beim hinzufügen einer Zutat" }; index = indexOfStart("# ingredients:"); if (index != -1) { setLine(index, replacedLine); addLines(index + 1, lines); } else { index = indexOfStart("# name:"); if (index != -1) { addLines(index + 1, lines); addLines(index + 1, replacedLine); } else { index = indexOfStart("# -- Rezepte für Getränke --"); if (index != -1) { addLines(index + 2, lines); addLines(index + 2, "", replacedLine); } } } // Split the Color explanation into two lines replacedLine = "# color: Farbe des Getränks nach destillieren/reifen."; lines = new String[] { "# Benutzbare Farben: DARK_RED, RED, BRIGHT_RED, ORANGE, PINK, BLUE, CYAN, WATER, GREEN, BLACK, GREY, BRIGHT_GREY" }; index = indexOfStart("# color:"); if (index != -1) { setLine(index, replacedLine); addLines(index + 1, lines); } else { index = indexOfStart("# age:"); if (index != -1) { addLines(index + 1, lines); addLines(index + 1, replacedLine); } } // Add all the new info to the effects description replacedLine = "# effects: Auflistung Effekt/Level/Dauer Besonderere Trank-Effekte beim Trinken, Dauer in sek."; lines = new String[] { "# Ein 'X' an den Namen anhängen, um ihn zu verbergen. Bsp: 'POISONX/2/10' (WEAKNESS, INCREASE_DAMAGE, SLOW und SPEED sind immer verborgen.)", "# Mögliche Effekte: http://jd.bukkit.org/rb/apidocs/org/bukkit/potion/PotionEffectType.html", "# Minimale und Maximale Level/Dauer können durch \"-\" festgelegt werden, Bsp: 'SPEED/1-2/30-40' = Level 1 und 30 sek minimal, Level 2 und 40 sek maximal", "# Diese Bereiche funktionieren auch umgekehrt, Bsp: 'POISON/3-1/20-5' für abschwächende Effekte bei guter Qualität", "# Längste mögliche Effektdauer: 1638 sek. Es muss keine Dauer für Effekte mit sofortiger Wirkung angegeben werden." }; index = indexOfStart("# effects:"); if (index != -1) { setLine(index, replacedLine); addLines(index + 1, lines); } else { index = indexOfStart("# alcohol:"); if (index != -1) { addLines(index + 1, lines); addLines(index + 1, replacedLine); } else { index = indexOfStart("# -- Rezepte für Getränke --"); if (index != -1) { addLines(index + 2, lines); addLines(index + 2, "", replacedLine); } } } if (index != -1) { index = indexOfStart("# (WEAKNESS, INCREASE_DAMAGE, SLOW und SPEED sind immer verborgen.) Mögliche Effekte:"); if (index != -1) { config.remove(index); } } index = indexOfStart("# Bei Effekten mit sofortiger Wirkung "); if (index != -1) { config.remove(index); } } // Update en from 1.2 to 1.3 private void update12en() { updateVersion("1.3"); // Add the new Wood Types to the Description int index = indexOfStart("# wood:"); if (index != -1) { setLine(index, "# wood: Wood of the barrel 0=any 1=Birch 2=Oak 3=Jungle 4=Spruce 5=Acacia 6=Dark Oak"); } // Add the Example to the Cooked Section index = indexOfStart("# cooked:"); if (index != -1) { addLines(index + 1, "# [Example] MATERIAL_or_id: Name after cooking"); } // Add new ingredients description String replacedLine = "# ingredients: List of 'material or id,data/amount'"; String[] lines = new String[] { "# (Item-ids instead of material are deprecated by bukkit and may not work in the future!)", "# A list of materials can be found here: http://jd.bukkit.org/beta/apidocs/org/bukkit/Material.html", "# You can specify a data value, omitting it will ignore the data value of the added ingredient" }; index = indexOfStart("# ingredients:"); if (index != -1) { setLine(index, replacedLine); addLines(index + 1, lines); } else { index = indexOfStart("# name:"); if (index != -1) { addLines(index + 1, lines); addLines(index + 1, replacedLine); } else { index = indexOfStart("# -- Recipes for Potions --"); if (index != -1) { addLines(index + 2, lines); addLines(index + 2, "", replacedLine); } } } // Split the Color explanation into two lines replacedLine = "# color: Color of the potion after distilling/aging."; lines = new String[] { "# Usable Colors: DARK_RED, RED, BRIGHT_RED, ORANGE, PINK, BLUE, CYAN, WATER, GREEN, BLACK, GREY, BRIGHT_GREY" }; index = indexOfStart("# color:"); if (index != -1) { setLine(index, replacedLine); addLines(index + 1, lines); } else { index = indexOfStart("# age:"); if (index != -1) { addLines(index + 1, lines); addLines(index + 1, replacedLine); } } // Add all the new info to the effects description replacedLine = "# effects: List of effect/level/duration Special potion-effect when drinking, duration in sek."; lines = new String[] { "# Suffix name with 'X' to hide effect from label. Sample: 'POISONX/2/10' (WEAKNESS, INCREASE_DAMAGE, SLOW and SPEED are always hidden.)", "# Possible Effects: http://jd.bukkit.org/rb/apidocs/org/bukkit/potion/PotionEffectType.html", "# Level or Duration ranges may be specified with a \"-\", ex. 'SPEED/1-2/30-40' = lvl 1 and 30 sec at worst and lvl 2 and 40 sec at best", "# Ranges also work high-low, ex. 'POISON/3-1/20-5' for weaker effects at good quality.", "# Highest possible Duration: 1638 sec. Instant Effects dont need any duration specified." }; index = indexOfStart("# effects:"); if (index != -1) { setLine(index, replacedLine); addLines(index + 1, lines); } else { index = indexOfStart("# alcohol:"); if (index != -1) { addLines(index + 1, lines); addLines(index + 1, replacedLine); } else { index = indexOfStart("# -- Recipes for Potions --"); if (index != -1) { addLines(index + 2, lines); addLines(index + 2, "", replacedLine); } } } if (index != -1) { index = indexOfStart("# (WEAKNESS, INCREASE_DAMAGE, SLOW and SPEED are always hidden.) Possible Effects:"); if (index != -1) { config.remove(index); } } index = indexOfStart("# instant effects "); if (index != -1) { config.remove(index); } } private void update13de() { updateVersion("1.3.1"); int index = indexOfStart("# Autosave"); String[] lines = new String[] { "# Aktiviert das Suchen nach Updates für Brewery mit der curseforge api [true]", "# Wenn ein Update gefunden wurde, wird dies bei Serverstart im log angezeigt, sowie ops benachrichtigt", "updateCheck: true", "" }; if (index == -1) { index = indexOfStart("autosave:"); if (index == -1) { index = indexOfStart("# Sprachedatei"); if (index == -1) { index = indexOfStart("language:"); } } } if (index == -1) { appendLines(lines); } else { addLines(index, lines); } } private void update13en() { updateVersion("1.3.1"); int index = indexOfStart("# Autosave"); String[] lines = new String[] { "# Enable checking for Updates, Checks the curseforge api for updates to Brewery [true]", "# If an Update is found a Message is logged on Server-start and displayed to ops joining the game", "updateCheck: true", "" }; if (index == -1) { index = indexOfStart("autosave:"); if (index == -1) { index = indexOfStart("# Languagefile"); if (index == -1) { index = indexOfStart("language:"); } } } if (index == -1) { appendLines(lines); } else { addLines(index, lines); } } }
Civcraft/Brewery
src/com/dre/brewery/filedata/ConfigUpdater.java
6,520
// Default language to de
line_comment
nl
package com.dre.brewery.filedata; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import com.dre.brewery.P; public class ConfigUpdater { private ArrayList<String> config = new ArrayList<String>(); private File file; public ConfigUpdater(File file) { this.file = file; getConfigString(); } // Returns the index of the line that starts with 'lineStart', returns -1 if not found; public int indexOfStart(String lineStart) { for (int i = 0; i < config.size(); i++) { if (config.get(i).startsWith(lineStart)) { return i; } } return -1; } // Adds some lines to the end public void appendLines(String... lines) { config.addAll(Arrays.asList(lines)); } // Replaces the line at the index with the new Line public void setLine(int index, String newLine) { config.set(index, newLine); } // adds some Lines at the index public void addLines(int index, String... newLines) { config.addAll(index, Arrays.asList(newLines)); } public void saveConfig() { StringBuilder stringBuilder = new StringBuilder(""); for (String line : config) { stringBuilder.append(line).append("\n"); } String configString = stringBuilder.toString().trim(); try { BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.write(configString); writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } private void getConfigString() { try { BufferedReader reader = new BufferedReader(new FileReader(file)); String currentLine; while((currentLine = reader.readLine()) != null) { config.add(currentLine); } reader.close(); } catch (IOException e) { e.printStackTrace(); } } // ---- Updating to newer Versions ---- // Update from a specified Config version and language to the newest version public void update(String fromVersion, String lang) { if (fromVersion.equals("0.5")) { // Version 0.5 was only released for de, but with en as setting, so default to de if (!lang.equals("de")) { lang = "de"; } } if (fromVersion.equals("0.5") || fromVersion.equals("1.0")) { if (lang.equals("de")) { update05de(); } else { update10en(); } fromVersion = "1.1"; } if (fromVersion.equals("1.1") || fromVersion.equals("1.1.1")) { if (lang.equals("de")) { update11de(); } else { update11en(); } fromVersion = "1.2"; } if (fromVersion.equals("1.2")) { if (lang.equals("de")) { update12de(); } else { update12en(); } fromVersion = "1.3"; } if (fromVersion.equals("1.3")) { if (lang.equals("de")) { update13de(); } else { update13en(); } fromVersion = "1.3.1"; } if (!fromVersion.equals("1.3.1")) { P.p.log(P.p.languageReader.get("Error_ConfigUpdate", fromVersion)); return; } saveConfig(); } // Update the Version String private void updateVersion(String to) { int index = indexOfStart("version"); String line = "version: '" + to + "'"; if (index != -1) { setLine(index, line); } else { index = indexOfStart("# Config Version"); if (index == -1) { index = indexOfStart("autosave"); } if (index == -1) { appendLines(line); } else { addLines(index, line); } } } // Updates de from 0.5 to 1.1 private void update05de() { updateVersion("1.1"); // Default language<SUF> int index = indexOfStart("language: en"); if (index != -1) { setLine(index, "language: de"); P.p.language = "de"; } // Add the new entries for the Word Distortion above the words section String[] entries = { "# -- Chat Veränderungs Einstellungen --", "", "# Text nach den angegebenen Kommandos wird bei Trunkenheit ebenfalls Verändert (Liste) [- /gl]", "distortCommands:", "- /gl", "- /global", "- /fl", "- /s", "- /letter", "", "# Geschriebenen Text auf Schildern bei Trunkenheit verändern [false]", "distortSignText: false", "", "# Text, der zwischen diesen Buchstaben steht, wird nicht verändert (\",\" als Trennung verwenden) (Liste) [- '[,]']", "distortBypass:", "- '*,*'", "- '[,]'", "" }; index = indexOfStart("# words"); if (index == -1) { index = indexOfStart("# Diese werden von oben"); } if (index == -1) { index = indexOfStart("# replace"); } if (index == -1) { index = indexOfStart("words:"); } if (index == -1) { appendLines(entries); } else { addLines(index, entries); } // Add some new separators for overview String line = "# -- Verschiedene Einstellungen --"; index = indexOfStart("# Verschiedene Einstellungen"); if (index != -1) { setLine(index, line); } line = "# -- Rezepte für Getränke --"; index = indexOfStart("# Rezepte für Getränke"); if (index != -1) { setLine(index, line); } } // Updates en from 1.0 to 1.1 private void update10en() { // Update version String updateVersion("1.1"); // Add the new entries for the Word Distortion above the words section String[] entries = { "# -- Chat Distortion Settings --", "", "# Text after specified commands will be distorted when drunk (list) [- /gl]", "distortCommands:", "- /gl", "- /global", "- /fl", "- /s", "- /letter", "", "# Distort the Text written on a Sign while drunk [false]", "distortSignText: false", "", "# Enclose a text with these Letters to bypass Chat Distortion (Use \",\" as Separator) (list) [- '[,]']", "distortBypass:", "- '*,*'", "- '[,]'", "" }; int index = indexOfStart("# words"); if (index == -1) { index = indexOfStart("# Will be processed"); } if (index == -1) { index = indexOfStart("# replace"); } if (index == -1) { index = indexOfStart("words:"); } if (index == -1) { appendLines(entries); } else { addLines(index, entries); } // Add some new separators for overview String line = "# -- Settings --"; index = indexOfStart("# Settings"); if (index != -1) { setLine(index, line); } line = "# -- Recipes for Potions --"; index = indexOfStart("# Recipes for Potions"); if (index != -1) { setLine(index, line); } } // Updates de from 1.1 to 1.2 private void update11de() { updateVersion("1.2"); int index = indexOfStart("# Das Item kann nicht aufgesammelt werden"); if (index != -1) { setLine(index, "# Das Item kann nicht aufgesammelt werden und bleibt bis zum Despawnen liegen. (Achtung: Kann nach Serverrestart aufgesammelt werden!)"); } // Add the BarrelAccess Setting String[] lines = { "# Ob große Fässer an jedem Block geöffnet werden können, nicht nur an Zapfhahn und Schild. Bei kleinen Fässern geht dies immer. [true]", "openLargeBarrelEverywhere: true", "" }; index = indexOfStart("colorInBrewer") + 2; if (index == 1) { index = indexOfStart("colorInBarrels") + 2; } if (index == 1) { index = indexOfStart("# Autosave"); } if (index == -1) { index = indexOfStart("language") + 2; } if (index == 1) { addLines(3, lines); } else { addLines(index, lines); } // Add Plugin Support Settings lines = new String[] { "", "# -- Plugin Kompatiblität --", "", "# Andere Plugins (wenn installiert) nach Rechten zum öffnen von Fässern checken [true]", "useWorldGuard: true", "useLWC: true", "useGriefPrevention: true", "", "# Änderungen an Fassinventaren mit LogBlock aufzeichen [true]", "useLogBlock: true", "", "" }; index = indexOfStart("# -- Chat Veränderungs Einstellungen"); if (index == -1) { index = indexOfStart("# words"); } if (index == -1) { index = indexOfStart("distortCommands"); if (index > 4) { index -= 4; } } if (index != -1) { addLines(index, lines); } else { appendLines(lines); } } // Updates en from 1.1 to 1.2 private void update11en() { updateVersion("1.2"); int index = indexOfStart("# The item can not be collected"); if (index != -1) { setLine(index, "# The item can not be collected and stays on the ground until it despawns. (Warning: Can be collected after Server restart!)"); } // Add the BarrelAccess Setting String[] lines = { "# If a Large Barrel can be opened by clicking on any of its blocks, not just Spigot or Sign. This is always true for Small Barrels. [true]", "openLargeBarrelEverywhere: true", "" }; index = indexOfStart("colorInBrewer") + 2; if (index == 1) { index = indexOfStart("colorInBarrels") + 2; } if (index == 1) { index = indexOfStart("# Autosave"); } if (index == -1) { index = indexOfStart("language") + 2; } if (index == 1) { addLines(3, lines); } else { addLines(index, lines); } // Add Plugin Support Settings lines = new String[] { "", "# -- Plugin Compatibility --", "", "# Enable checking of other Plugins (if installed) for Barrel Permissions [true]", "useWorldGuard: true", "useLWC: true", "useGriefPrevention: true", "", "# Enable the Logging of Barrel Inventories to LogBlock [true]", "useLogBlock: true", "", "" }; index = indexOfStart("# -- Chat Distortion Settings"); if (index == -1) { index = indexOfStart("# words"); } if (index == -1) { index = indexOfStart("distortCommands"); if (index > 4) { index -= 4; } } if (index != -1) { addLines(index, lines); } else { appendLines(lines); } } // Update de from 1.2 to 1.3 private void update12de() { updateVersion("1.3"); // Add the new Wood Types to the Description int index = indexOfStart("# wood:"); if (index != -1) { setLine(index, "# wood: Holz des Fasses 0=alle Holzsorten 1=Birke 2=Eiche 3=Jungel 4=Fichte 5=Akazie 6=Schwarzeiche"); } // Add the Example to the Cooked Section index = indexOfStart("# cooked:"); if (index != -1) { addLines(index + 1, "# [Beispiel] MATERIAL_oder_id: Name nach Gähren"); } // Add new ingredients description String replacedLine = "# ingredients: Auflistung von 'Material oder ID,Data/Anzahl'"; String[] lines = new String[] { "# (Item-ids anstatt Material werden von Bukkit nicht mehr unterstützt und funktionieren möglicherweise in Zukunft nicht mehr!)", "# Eine Liste von allen Materialien kann hier gefunden werden: http://jd.bukkit.org/beta/apidocs/org/bukkit/Material.html", "# Es kann ein Data-Wert angegeben werden, weglassen ignoriert diesen beim hinzufügen einer Zutat" }; index = indexOfStart("# ingredients:"); if (index != -1) { setLine(index, replacedLine); addLines(index + 1, lines); } else { index = indexOfStart("# name:"); if (index != -1) { addLines(index + 1, lines); addLines(index + 1, replacedLine); } else { index = indexOfStart("# -- Rezepte für Getränke --"); if (index != -1) { addLines(index + 2, lines); addLines(index + 2, "", replacedLine); } } } // Split the Color explanation into two lines replacedLine = "# color: Farbe des Getränks nach destillieren/reifen."; lines = new String[] { "# Benutzbare Farben: DARK_RED, RED, BRIGHT_RED, ORANGE, PINK, BLUE, CYAN, WATER, GREEN, BLACK, GREY, BRIGHT_GREY" }; index = indexOfStart("# color:"); if (index != -1) { setLine(index, replacedLine); addLines(index + 1, lines); } else { index = indexOfStart("# age:"); if (index != -1) { addLines(index + 1, lines); addLines(index + 1, replacedLine); } } // Add all the new info to the effects description replacedLine = "# effects: Auflistung Effekt/Level/Dauer Besonderere Trank-Effekte beim Trinken, Dauer in sek."; lines = new String[] { "# Ein 'X' an den Namen anhängen, um ihn zu verbergen. Bsp: 'POISONX/2/10' (WEAKNESS, INCREASE_DAMAGE, SLOW und SPEED sind immer verborgen.)", "# Mögliche Effekte: http://jd.bukkit.org/rb/apidocs/org/bukkit/potion/PotionEffectType.html", "# Minimale und Maximale Level/Dauer können durch \"-\" festgelegt werden, Bsp: 'SPEED/1-2/30-40' = Level 1 und 30 sek minimal, Level 2 und 40 sek maximal", "# Diese Bereiche funktionieren auch umgekehrt, Bsp: 'POISON/3-1/20-5' für abschwächende Effekte bei guter Qualität", "# Längste mögliche Effektdauer: 1638 sek. Es muss keine Dauer für Effekte mit sofortiger Wirkung angegeben werden." }; index = indexOfStart("# effects:"); if (index != -1) { setLine(index, replacedLine); addLines(index + 1, lines); } else { index = indexOfStart("# alcohol:"); if (index != -1) { addLines(index + 1, lines); addLines(index + 1, replacedLine); } else { index = indexOfStart("# -- Rezepte für Getränke --"); if (index != -1) { addLines(index + 2, lines); addLines(index + 2, "", replacedLine); } } } if (index != -1) { index = indexOfStart("# (WEAKNESS, INCREASE_DAMAGE, SLOW und SPEED sind immer verborgen.) Mögliche Effekte:"); if (index != -1) { config.remove(index); } } index = indexOfStart("# Bei Effekten mit sofortiger Wirkung "); if (index != -1) { config.remove(index); } } // Update en from 1.2 to 1.3 private void update12en() { updateVersion("1.3"); // Add the new Wood Types to the Description int index = indexOfStart("# wood:"); if (index != -1) { setLine(index, "# wood: Wood of the barrel 0=any 1=Birch 2=Oak 3=Jungle 4=Spruce 5=Acacia 6=Dark Oak"); } // Add the Example to the Cooked Section index = indexOfStart("# cooked:"); if (index != -1) { addLines(index + 1, "# [Example] MATERIAL_or_id: Name after cooking"); } // Add new ingredients description String replacedLine = "# ingredients: List of 'material or id,data/amount'"; String[] lines = new String[] { "# (Item-ids instead of material are deprecated by bukkit and may not work in the future!)", "# A list of materials can be found here: http://jd.bukkit.org/beta/apidocs/org/bukkit/Material.html", "# You can specify a data value, omitting it will ignore the data value of the added ingredient" }; index = indexOfStart("# ingredients:"); if (index != -1) { setLine(index, replacedLine); addLines(index + 1, lines); } else { index = indexOfStart("# name:"); if (index != -1) { addLines(index + 1, lines); addLines(index + 1, replacedLine); } else { index = indexOfStart("# -- Recipes for Potions --"); if (index != -1) { addLines(index + 2, lines); addLines(index + 2, "", replacedLine); } } } // Split the Color explanation into two lines replacedLine = "# color: Color of the potion after distilling/aging."; lines = new String[] { "# Usable Colors: DARK_RED, RED, BRIGHT_RED, ORANGE, PINK, BLUE, CYAN, WATER, GREEN, BLACK, GREY, BRIGHT_GREY" }; index = indexOfStart("# color:"); if (index != -1) { setLine(index, replacedLine); addLines(index + 1, lines); } else { index = indexOfStart("# age:"); if (index != -1) { addLines(index + 1, lines); addLines(index + 1, replacedLine); } } // Add all the new info to the effects description replacedLine = "# effects: List of effect/level/duration Special potion-effect when drinking, duration in sek."; lines = new String[] { "# Suffix name with 'X' to hide effect from label. Sample: 'POISONX/2/10' (WEAKNESS, INCREASE_DAMAGE, SLOW and SPEED are always hidden.)", "# Possible Effects: http://jd.bukkit.org/rb/apidocs/org/bukkit/potion/PotionEffectType.html", "# Level or Duration ranges may be specified with a \"-\", ex. 'SPEED/1-2/30-40' = lvl 1 and 30 sec at worst and lvl 2 and 40 sec at best", "# Ranges also work high-low, ex. 'POISON/3-1/20-5' for weaker effects at good quality.", "# Highest possible Duration: 1638 sec. Instant Effects dont need any duration specified." }; index = indexOfStart("# effects:"); if (index != -1) { setLine(index, replacedLine); addLines(index + 1, lines); } else { index = indexOfStart("# alcohol:"); if (index != -1) { addLines(index + 1, lines); addLines(index + 1, replacedLine); } else { index = indexOfStart("# -- Recipes for Potions --"); if (index != -1) { addLines(index + 2, lines); addLines(index + 2, "", replacedLine); } } } if (index != -1) { index = indexOfStart("# (WEAKNESS, INCREASE_DAMAGE, SLOW and SPEED are always hidden.) Possible Effects:"); if (index != -1) { config.remove(index); } } index = indexOfStart("# instant effects "); if (index != -1) { config.remove(index); } } private void update13de() { updateVersion("1.3.1"); int index = indexOfStart("# Autosave"); String[] lines = new String[] { "# Aktiviert das Suchen nach Updates für Brewery mit der curseforge api [true]", "# Wenn ein Update gefunden wurde, wird dies bei Serverstart im log angezeigt, sowie ops benachrichtigt", "updateCheck: true", "" }; if (index == -1) { index = indexOfStart("autosave:"); if (index == -1) { index = indexOfStart("# Sprachedatei"); if (index == -1) { index = indexOfStart("language:"); } } } if (index == -1) { appendLines(lines); } else { addLines(index, lines); } } private void update13en() { updateVersion("1.3.1"); int index = indexOfStart("# Autosave"); String[] lines = new String[] { "# Enable checking for Updates, Checks the curseforge api for updates to Brewery [true]", "# If an Update is found a Message is logged on Server-start and displayed to ops joining the game", "updateCheck: true", "" }; if (index == -1) { index = indexOfStart("autosave:"); if (index == -1) { index = indexOfStart("# Languagefile"); if (index == -1) { index = indexOfStart("language:"); } } } if (index == -1) { appendLines(lines); } else { addLines(index, lines); } } }
18966_0
package com.groep15.amazonsim.models.worldobject; /* * Deze interface beschrijft wat een onderdeel van het model moet kunnen om deze * te kunnen updaten. In de lijst met objecten in de wereld (zie class World) zitten * objecten die geupdate kunnen worden. Er wordt gecontroleerd of een object deze * interface implementeerd. Als dat zo is, wordt het object geupdate wanneer de * wereld update. */ public interface Updatable { boolean update(); }
ClawmanCat/WarehouseSim
src/main/java/com/groep15/amazonsim/models/worldobject/Updatable.java
125
/* * Deze interface beschrijft wat een onderdeel van het model moet kunnen om deze * te kunnen updaten. In de lijst met objecten in de wereld (zie class World) zitten * objecten die geupdate kunnen worden. Er wordt gecontroleerd of een object deze * interface implementeerd. Als dat zo is, wordt het object geupdate wanneer de * wereld update. */
block_comment
nl
package com.groep15.amazonsim.models.worldobject; /* * Deze interface beschrijft<SUF>*/ public interface Updatable { boolean update(); }
21174_2
/* * Licensed under the EUPL, Version 1.2. * You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 */ package net.dries007.tfc.network; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.function.Supplier; import org.apache.commons.lang3.mutable.MutableInt; import net.minecraft.network.FriendlyByteBuf; import net.minecraftforge.network.NetworkEvent; import net.minecraftforge.network.NetworkRegistry; import net.minecraftforge.network.PacketDistributor; import net.minecraftforge.network.simple.SimpleChannel; import net.dries007.tfc.common.capabilities.food.FoodCapability; import net.dries007.tfc.common.capabilities.heat.HeatCapability; import net.dries007.tfc.common.capabilities.size.ItemSizeManager; import net.dries007.tfc.util.*; public final class PacketHandler { private static final String VERSION = Integer.toString(1); private static final SimpleChannel CHANNEL = NetworkRegistry.newSimpleChannel(Helpers.identifier("network"), () -> VERSION, VERSION::equals, VERSION::equals); private static final MutableInt ID = new MutableInt(0); public static void send(PacketDistributor.PacketTarget target, Object message) { CHANNEL.send(target, message); } public static void init() { // Server -> Client register(ChunkWatchPacket.class, ChunkWatchPacket::encode, ChunkWatchPacket::new, ChunkWatchPacket::handle); register(ChunkUnwatchPacket.class, ChunkUnwatchPacket::encode, ChunkUnwatchPacket::new, ChunkUnwatchPacket::handle); register(CalendarUpdatePacket.class, CalendarUpdatePacket::encode, CalendarUpdatePacket::new, CalendarUpdatePacket::handle); register(FoodDataReplacePacket.class, FoodDataReplacePacket::new, FoodDataReplacePacket::handle); register(FoodDataUpdatePacket.class, FoodDataUpdatePacket::encode, FoodDataUpdatePacket::new, FoodDataUpdatePacket::handle); register(PlayerDataUpdatePacket.class, PlayerDataUpdatePacket::encode, PlayerDataUpdatePacket::new, PlayerDataUpdatePacket::handle); register(ProspectedPacket.class, ProspectedPacket::encode, ProspectedPacket::new, ProspectedPacket::handle); register(ClimateSettingsUpdatePacket.class, ClimateSettingsUpdatePacket::encode, ClimateSettingsUpdatePacket::new, ClimateSettingsUpdatePacket::handle); register(EffectExpirePacket.class, EffectExpirePacket::encode, EffectExpirePacket::new, EffectExpirePacket::handle); registerDataManager(DataManagerSyncPacket.TMetal.class, Metal.MANAGER); registerDataManager(DataManagerSyncPacket.TFuel.class, Fuel.MANAGER); registerDataManager(DataManagerSyncPacket.TFertilizer.class, Fertilizer.MANAGER); registerDataManager(DataManagerSyncPacket.TFoodDefinition.class, FoodCapability.MANAGER); registerDataManager(DataManagerSyncPacket.THeatDefinition.class, HeatCapability.MANAGER); registerDataManager(DataManagerSyncPacket.TItemSizeDefinition.class, ItemSizeManager.MANAGER); // Client -> Server register(SwitchInventoryTabPacket.class, SwitchInventoryTabPacket::encode, SwitchInventoryTabPacket::new, SwitchInventoryTabPacket::handle); register(PlaceBlockSpecialPacket.class, PlaceBlockSpecialPacket::new, PlaceBlockSpecialPacket::handle); register(ScreenButtonPacket.class, ScreenButtonPacket::encode, ScreenButtonPacket::new, ScreenButtonPacket::handle); register(PlayerDrinkPacket.class, PlayerDrinkPacket::new, PlayerDrinkPacket::handle); } @SuppressWarnings("unchecked") private static <T extends DataManagerSyncPacket<E>, E> void registerDataManager(Class<T> cls, DataManager<E> manager) { CHANNEL.registerMessage(ID.getAndIncrement(), cls, (packet, buffer) -> packet.encode(manager, buffer), buffer -> { final T packet = (T) manager.createEmptyPacket(); packet.decode(manager, buffer); return packet; }, (packet, context) -> { context.get().setPacketHandled(true); context.get().enqueueWork(() -> packet.handle(manager)); }); } private static <T> void register(Class<T> cls, BiConsumer<T, FriendlyByteBuf> encoder, Function<FriendlyByteBuf, T> decoder, BiConsumer<T, NetworkEvent.Context> handler) { CHANNEL.registerMessage(ID.getAndIncrement(), cls, encoder, decoder, (packet, context) -> { context.get().setPacketHandled(true); handler.accept(packet, context.get()); }); } private static <T> void register(Class<T> cls, Supplier<T> factory, BiConsumer<T, NetworkEvent.Context> handler) { CHANNEL.registerMessage(ID.getAndIncrement(), cls, (packet, buffer) -> {}, buffer -> factory.get(), (packet, context) -> { context.get().setPacketHandled(true); handler.accept(packet, context.get()); }); } }
CleanroomMC/TerraFirmaCraft
src/main/java/net/dries007/tfc/network/PacketHandler.java
1,398
// Client -> Server
line_comment
nl
/* * Licensed under the EUPL, Version 1.2. * You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 */ package net.dries007.tfc.network; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.function.Supplier; import org.apache.commons.lang3.mutable.MutableInt; import net.minecraft.network.FriendlyByteBuf; import net.minecraftforge.network.NetworkEvent; import net.minecraftforge.network.NetworkRegistry; import net.minecraftforge.network.PacketDistributor; import net.minecraftforge.network.simple.SimpleChannel; import net.dries007.tfc.common.capabilities.food.FoodCapability; import net.dries007.tfc.common.capabilities.heat.HeatCapability; import net.dries007.tfc.common.capabilities.size.ItemSizeManager; import net.dries007.tfc.util.*; public final class PacketHandler { private static final String VERSION = Integer.toString(1); private static final SimpleChannel CHANNEL = NetworkRegistry.newSimpleChannel(Helpers.identifier("network"), () -> VERSION, VERSION::equals, VERSION::equals); private static final MutableInt ID = new MutableInt(0); public static void send(PacketDistributor.PacketTarget target, Object message) { CHANNEL.send(target, message); } public static void init() { // Server -> Client register(ChunkWatchPacket.class, ChunkWatchPacket::encode, ChunkWatchPacket::new, ChunkWatchPacket::handle); register(ChunkUnwatchPacket.class, ChunkUnwatchPacket::encode, ChunkUnwatchPacket::new, ChunkUnwatchPacket::handle); register(CalendarUpdatePacket.class, CalendarUpdatePacket::encode, CalendarUpdatePacket::new, CalendarUpdatePacket::handle); register(FoodDataReplacePacket.class, FoodDataReplacePacket::new, FoodDataReplacePacket::handle); register(FoodDataUpdatePacket.class, FoodDataUpdatePacket::encode, FoodDataUpdatePacket::new, FoodDataUpdatePacket::handle); register(PlayerDataUpdatePacket.class, PlayerDataUpdatePacket::encode, PlayerDataUpdatePacket::new, PlayerDataUpdatePacket::handle); register(ProspectedPacket.class, ProspectedPacket::encode, ProspectedPacket::new, ProspectedPacket::handle); register(ClimateSettingsUpdatePacket.class, ClimateSettingsUpdatePacket::encode, ClimateSettingsUpdatePacket::new, ClimateSettingsUpdatePacket::handle); register(EffectExpirePacket.class, EffectExpirePacket::encode, EffectExpirePacket::new, EffectExpirePacket::handle); registerDataManager(DataManagerSyncPacket.TMetal.class, Metal.MANAGER); registerDataManager(DataManagerSyncPacket.TFuel.class, Fuel.MANAGER); registerDataManager(DataManagerSyncPacket.TFertilizer.class, Fertilizer.MANAGER); registerDataManager(DataManagerSyncPacket.TFoodDefinition.class, FoodCapability.MANAGER); registerDataManager(DataManagerSyncPacket.THeatDefinition.class, HeatCapability.MANAGER); registerDataManager(DataManagerSyncPacket.TItemSizeDefinition.class, ItemSizeManager.MANAGER); // Client -><SUF> register(SwitchInventoryTabPacket.class, SwitchInventoryTabPacket::encode, SwitchInventoryTabPacket::new, SwitchInventoryTabPacket::handle); register(PlaceBlockSpecialPacket.class, PlaceBlockSpecialPacket::new, PlaceBlockSpecialPacket::handle); register(ScreenButtonPacket.class, ScreenButtonPacket::encode, ScreenButtonPacket::new, ScreenButtonPacket::handle); register(PlayerDrinkPacket.class, PlayerDrinkPacket::new, PlayerDrinkPacket::handle); } @SuppressWarnings("unchecked") private static <T extends DataManagerSyncPacket<E>, E> void registerDataManager(Class<T> cls, DataManager<E> manager) { CHANNEL.registerMessage(ID.getAndIncrement(), cls, (packet, buffer) -> packet.encode(manager, buffer), buffer -> { final T packet = (T) manager.createEmptyPacket(); packet.decode(manager, buffer); return packet; }, (packet, context) -> { context.get().setPacketHandled(true); context.get().enqueueWork(() -> packet.handle(manager)); }); } private static <T> void register(Class<T> cls, BiConsumer<T, FriendlyByteBuf> encoder, Function<FriendlyByteBuf, T> decoder, BiConsumer<T, NetworkEvent.Context> handler) { CHANNEL.registerMessage(ID.getAndIncrement(), cls, encoder, decoder, (packet, context) -> { context.get().setPacketHandled(true); handler.accept(packet, context.get()); }); } private static <T> void register(Class<T> cls, Supplier<T> factory, BiConsumer<T, NetworkEvent.Context> handler) { CHANNEL.registerMessage(ID.getAndIncrement(), cls, (packet, buffer) -> {}, buffer -> factory.get(), (packet, context) -> { context.get().setPacketHandled(true); handler.accept(packet, context.get()); }); } }
22474_0
package Presentation; import Accessors.Accessor; import Items.*; import Slide.Slide; /** Een ingebouwde demo-presentatie * @author Ian F. Darwin, [email protected], Gert Florijn, Sylvia Stuurman * @version 1.1 2002/12/17 Gert Florijn * @version 1.2 2003/11/19 Sylvia Stuurman * @version 1.3 2004/08/17 Sylvia Stuurman * @version 1.4 2007/07/16 Sylvia Stuurman * @version 1.5 2010/03/03 Sylvia Stuurman * @version 1.6 2014/05/16 Sylvia Stuurman */ public class DemoPresentation extends Accessor { /** * Load a presentation * @param presentation The presentation that has to be loaded * @param unusedFilename A file name (in this case unused) */ public void loadFile(Presentation presentation, String unusedFilename) { presentation.setTitle("Demo Presentation"); Slide slide; slide = new Slide(); slide.setTitle("JabberPoint"); slide.append(1, "Het Java Presentatie Tool"); slide.append(2, "Copyright (c) 1996-2000: Ian Darwin"); slide.append(2, "Copyright (c) 2000-now:"); slide.append(2, "Gert Florijn en Sylvia Stuurman"); slide.append(4, "JabberPoint aanroepen zonder bestandsnaam"); slide.append(4, "laat deze presentatie zien"); slide.append(1, "Navigeren:"); slide.append(3, "Volgende slide: PgDn of Enter"); slide.append(3, "Vorige slide: PgUp of up-arrow"); slide.append(3, "Stoppen: q or Q"); presentation.append(slide); slide = new Slide(); slide.setTitle("Demonstratie van levels en stijlen"); slide.append(1, "Level 1"); slide.append(2, "Level 2"); slide.append(1, "Nogmaals level 1"); slide.append(1, "Level 1 heeft stijl nummer 1"); slide.append(2, "Level 2 heeft stijl nummer 2"); slide.append(3, "Zo ziet level 3 er uit"); slide.append(4, "En dit is level 4"); presentation.append(slide); slide = new Slide(); slide.setTitle("De derde slide"); slide.append(1, "Om een nieuwe presentatie te openen,"); slide.append(2, "gebruik File->Open uit het menu."); slide.append(1, " "); slide.append(1, "Dit is het einde van de presentatie."); slide.append(new BitmapItem(1, "JabberPoint.jpg")); presentation.append(slide); } /** * Save a presentation * @param presentation The presentation that has to be saved * @param unusedFilename A file name (in this case unused) */ public void saveFile(Presentation presentation, String unusedFilename) { throw new IllegalStateException("Save As->Demo! aangeroepen"); } }
Clibzz/OGO
src/Presentation/DemoPresentation.java
888
/** Een ingebouwde demo-presentatie * @author Ian F. Darwin, [email protected], Gert Florijn, Sylvia Stuurman * @version 1.1 2002/12/17 Gert Florijn * @version 1.2 2003/11/19 Sylvia Stuurman * @version 1.3 2004/08/17 Sylvia Stuurman * @version 1.4 2007/07/16 Sylvia Stuurman * @version 1.5 2010/03/03 Sylvia Stuurman * @version 1.6 2014/05/16 Sylvia Stuurman */
block_comment
nl
package Presentation; import Accessors.Accessor; import Items.*; import Slide.Slide; /** Een ingebouwde demo-presentatie<SUF>*/ public class DemoPresentation extends Accessor { /** * Load a presentation * @param presentation The presentation that has to be loaded * @param unusedFilename A file name (in this case unused) */ public void loadFile(Presentation presentation, String unusedFilename) { presentation.setTitle("Demo Presentation"); Slide slide; slide = new Slide(); slide.setTitle("JabberPoint"); slide.append(1, "Het Java Presentatie Tool"); slide.append(2, "Copyright (c) 1996-2000: Ian Darwin"); slide.append(2, "Copyright (c) 2000-now:"); slide.append(2, "Gert Florijn en Sylvia Stuurman"); slide.append(4, "JabberPoint aanroepen zonder bestandsnaam"); slide.append(4, "laat deze presentatie zien"); slide.append(1, "Navigeren:"); slide.append(3, "Volgende slide: PgDn of Enter"); slide.append(3, "Vorige slide: PgUp of up-arrow"); slide.append(3, "Stoppen: q or Q"); presentation.append(slide); slide = new Slide(); slide.setTitle("Demonstratie van levels en stijlen"); slide.append(1, "Level 1"); slide.append(2, "Level 2"); slide.append(1, "Nogmaals level 1"); slide.append(1, "Level 1 heeft stijl nummer 1"); slide.append(2, "Level 2 heeft stijl nummer 2"); slide.append(3, "Zo ziet level 3 er uit"); slide.append(4, "En dit is level 4"); presentation.append(slide); slide = new Slide(); slide.setTitle("De derde slide"); slide.append(1, "Om een nieuwe presentatie te openen,"); slide.append(2, "gebruik File->Open uit het menu."); slide.append(1, " "); slide.append(1, "Dit is het einde van de presentatie."); slide.append(new BitmapItem(1, "JabberPoint.jpg")); presentation.append(slide); } /** * Save a presentation * @param presentation The presentation that has to be saved * @param unusedFilename A file name (in this case unused) */ public void saveFile(Presentation presentation, String unusedFilename) { throw new IllegalStateException("Save As->Demo! aangeroepen"); } }
207968_0
package cn.nukkit.entity.passive; import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; /** * Author: BeYkeRYkt Nukkit Project */ public class EntityWolf extends EntityAnimal { public static final int NETWORK_ID = 14; public EntityWolf(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } @Override public float getWidth() { return 0.6f; } @Override public float getHeight() { return 0.85f; } @Override public String getName() { return "Wolf"; } @Override public int getNetworkId() { return NETWORK_ID; } @Override public void initEntity() { super.initEntity(); this.setMaxHealth(8); } @Override public boolean isBreedingItem(Item item) { return false; //only certain food } }
CloudburstMC/Nukkit
src/main/java/cn/nukkit/entity/passive/EntityWolf.java
296
/** * Author: BeYkeRYkt Nukkit Project */
block_comment
nl
package cn.nukkit.entity.passive; import cn.nukkit.item.Item; import cn.nukkit.level.format.FullChunk; import cn.nukkit.nbt.tag.CompoundTag; /** * Author: BeYkeRYkt Nukkit<SUF>*/ public class EntityWolf extends EntityAnimal { public static final int NETWORK_ID = 14; public EntityWolf(FullChunk chunk, CompoundTag nbt) { super(chunk, nbt); } @Override public float getWidth() { return 0.6f; } @Override public float getHeight() { return 0.85f; } @Override public String getName() { return "Wolf"; } @Override public int getNetworkId() { return NETWORK_ID; } @Override public void initEntity() { super.initEntity(); this.setMaxHealth(8); } @Override public boolean isBreedingItem(Item item) { return false; //only certain food } }
183776_1
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * Git test Door StijnVA --verwijder deze commentaar gerust */ package be.vdab.entities; import java.io.Serializable; import java.util.Collections; import java.util.Set; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import be.vdab.util.Paswoord; import be.vdab.valueobjects.EmailAdres; import java.util.LinkedHashSet; import javax.persistence.FetchType; @Entity @Table(name = "gebruiker") public class Gebruiker implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue private long id; @NotNull @Size(min = 1, max = 50, message = "{Size.tekst}") private String voornaam; @NotNull @Size(min = 1, max = 50, message = "{Size.tekst}") private String familienaam; @NotNull @Size(min = 1, max = 50, message = "{Size.tekst}") private String paswoord; @OneToMany(mappedBy = "gebruiker", fetch = FetchType.EAGER) private Set<Karakter> karakters = new LinkedHashSet<>(); public Set<Karakter> getKarakter() { return Collections.unmodifiableSet(karakters); } public void addKarakter(Karakter karakter) { karakters.add(karakter); } public void removeKarakter(Karakter karakter) { karakters.remove(karakter); } public String getVoornaam() { return voornaam; } public void setVoornaam(String voornaam) { this.voornaam = voornaam; } public String getFamilienaam() { return familienaam; } public void setFamilienaam(String familienaam) { this.familienaam = familienaam; } public String getPaswoord() { return paswoord; } public void setPaswoord(String paswoord) { String userName = this.emailAdres.toString(); this.paswoord = Paswoord.paswoordEncoder(paswoord, userName); } public long getId() { return id; } public Gebruiker() { } public Gebruiker(String voornaam, String familienaam, EmailAdres emailAdres, String paswoord) { this(); this.setVoornaam(voornaam); this.setFamilienaam(familienaam); this.setEmailAdres(emailAdres); this.setPaswoord(paswoord); } public Gebruiker(String voornaam, String familienaam, String paswoord) { this(); this.setVoornaam(voornaam); this.setFamilienaam(familienaam); this.setPaswoord(paswoord); } public Gebruiker(Gebruiker gebruiker) { this(); this.voornaam = gebruiker.getVoornaam(); this.familienaam = gebruiker.getFamilienaam(); this.paswoord = gebruiker.getPaswoord(); this.emailAdres = gebruiker.getEmailAdres(); for(Karakter k : gebruiker.karakters){ this.addKarakter(k); } } @NotNull @Valid @Embedded private EmailAdres emailAdres; public EmailAdres getEmailAdres() { return emailAdres; } public void setEmailAdres(EmailAdres emailAdres) { this.emailAdres = emailAdres; } // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result // + ((emailAdres == null) ? 0 : emailAdres.hashCode()); // return result; // } // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Gebruiker other = (Gebruiker) obj; // if (emailAdres == null) { // if (other.emailAdres != null) // return false; // } else if (!emailAdres.equals(other.emailAdres)) // return false; // return true; // } @Override public boolean equals(Object obj) { if (!(obj instanceof Gebruiker)) { return false; } else { if(emailAdres == null){ return ((Gebruiker) obj).emailAdres == null; } return ((Gebruiker) obj).emailAdres.equals(this.emailAdres); } } @Override public int hashCode() { if(emailAdres == null){ return 0; } return emailAdres.hashCode(); } public boolean isAdmin() { //TODO: make a real implementation with roles and stuff return this.voornaam.equals("admin"); } public void setId(long id){ this.id = id; } }
Cloudxtreme/JavaMUD
src/main/java/be/vdab/entities/Gebruiker.java
1,539
/* * Git test Door StijnVA --verwijder deze commentaar gerust */
block_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * Git test Door<SUF>*/ package be.vdab.entities; import java.io.Serializable; import java.util.Collections; import java.util.Set; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import be.vdab.util.Paswoord; import be.vdab.valueobjects.EmailAdres; import java.util.LinkedHashSet; import javax.persistence.FetchType; @Entity @Table(name = "gebruiker") public class Gebruiker implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue private long id; @NotNull @Size(min = 1, max = 50, message = "{Size.tekst}") private String voornaam; @NotNull @Size(min = 1, max = 50, message = "{Size.tekst}") private String familienaam; @NotNull @Size(min = 1, max = 50, message = "{Size.tekst}") private String paswoord; @OneToMany(mappedBy = "gebruiker", fetch = FetchType.EAGER) private Set<Karakter> karakters = new LinkedHashSet<>(); public Set<Karakter> getKarakter() { return Collections.unmodifiableSet(karakters); } public void addKarakter(Karakter karakter) { karakters.add(karakter); } public void removeKarakter(Karakter karakter) { karakters.remove(karakter); } public String getVoornaam() { return voornaam; } public void setVoornaam(String voornaam) { this.voornaam = voornaam; } public String getFamilienaam() { return familienaam; } public void setFamilienaam(String familienaam) { this.familienaam = familienaam; } public String getPaswoord() { return paswoord; } public void setPaswoord(String paswoord) { String userName = this.emailAdres.toString(); this.paswoord = Paswoord.paswoordEncoder(paswoord, userName); } public long getId() { return id; } public Gebruiker() { } public Gebruiker(String voornaam, String familienaam, EmailAdres emailAdres, String paswoord) { this(); this.setVoornaam(voornaam); this.setFamilienaam(familienaam); this.setEmailAdres(emailAdres); this.setPaswoord(paswoord); } public Gebruiker(String voornaam, String familienaam, String paswoord) { this(); this.setVoornaam(voornaam); this.setFamilienaam(familienaam); this.setPaswoord(paswoord); } public Gebruiker(Gebruiker gebruiker) { this(); this.voornaam = gebruiker.getVoornaam(); this.familienaam = gebruiker.getFamilienaam(); this.paswoord = gebruiker.getPaswoord(); this.emailAdres = gebruiker.getEmailAdres(); for(Karakter k : gebruiker.karakters){ this.addKarakter(k); } } @NotNull @Valid @Embedded private EmailAdres emailAdres; public EmailAdres getEmailAdres() { return emailAdres; } public void setEmailAdres(EmailAdres emailAdres) { this.emailAdres = emailAdres; } // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result // + ((emailAdres == null) ? 0 : emailAdres.hashCode()); // return result; // } // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Gebruiker other = (Gebruiker) obj; // if (emailAdres == null) { // if (other.emailAdres != null) // return false; // } else if (!emailAdres.equals(other.emailAdres)) // return false; // return true; // } @Override public boolean equals(Object obj) { if (!(obj instanceof Gebruiker)) { return false; } else { if(emailAdres == null){ return ((Gebruiker) obj).emailAdres == null; } return ((Gebruiker) obj).emailAdres.equals(this.emailAdres); } } @Override public int hashCode() { if(emailAdres == null){ return 0; } return emailAdres.hashCode(); } public boolean isAdmin() { //TODO: make a real implementation with roles and stuff return this.voornaam.equals("admin"); } public void setId(long id){ this.id = id; } }
84731_5
package nl.hz.ict.p2.zuul; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; /** * Player - Holds all state for a single user that plays the game * * It evaluates and executes the commands that the parser returns. * * @author Michael Kölling and David J. Barnes * @version 2011.08.08 */ public class Player extends GameObject { private Parser parser; private PrintStream out; /** * Create the game and initialise its internal map. */ public Player(String name, Game game, InputStream externalInputStream, OutputStream externalOutputStream) { super(name, game); out = new PrintStream(externalOutputStream); parser = new Parser(externalInputStream); } /** * Main play routine. Loops until end of play. */ public void play() { this.setCurrentRoom(getWorld().getSpawnArea()); printWelcome(); // Enter the main command loop. Here we repeatedly read commands and // execute them until the game is over. boolean finished = false; while (! finished) { out.print("> "); // print prompt, verplaatst van de parser naar hier Command command = parser.getCommand(); finished = processCommand(command); } out.println("Thank you for playing. Good bye."); } /** * Print out the opening message for the player. */ private void printWelcome() { out.println(); out.println("Welcome " + name + " to the World of Zuul!"); out.println("World of Zuul is a new, incredibly boring adventure game."); out.println("Type 'help' if you need help."); out.println(); out.println(getCurrentRoom().getLongDescription()); // Het printen verplaatst vanuit de Room klasse. } /** * Given a command, process (that is: execute) the command. * @param command The command to be processed. * @return true If the command ends the game, false otherwise. */ private boolean processCommand(Command command) { boolean wantToQuit = false; if(command.isUnknown()) { out.println("I don't know what you mean..."); return false; } String commandWord = command.getCommandWord(); if (commandWord.equals("help")) { printHelp(); } else if (commandWord.equals("go")) { goRoom(command); } else if (commandWord.equals("quit")) { wantToQuit = quit(command); } // else command not recognised. return wantToQuit; } // implementations of user commands: /** * Print out some help information. * Here we print some stupid, cryptic message and a list of the * command words. */ private void printHelp() { out.println("You are lost. You are alone. You wander"); out.println("around at the university."); out.println(); out.println("Your command words are:"); out.println(parser.showCommands()); // Het printen verplaatst vanuit de Parser (en CommandWords) klasse. } /** * Try to in to one direction. If there is an exit, enter the new * room, otherwise print an error message. */ private void goRoom(Command command) { if(!command.hasSecondWord()) { // if there is no second word, we don't know where to go... out.println("Go where?"); return; } String direction = command.getSecondWord(); Room currentRoom = getCurrentRoom(); // Try to leave current room. Room nextRoom = currentRoom.getExit(direction); if (nextRoom == null) { out.println("There is no door!"); } else { setCurrentRoom(nextRoom); out.println(getCurrentRoom().getLongDescription()); } } /** * "Quit" was entered. Check the rest of the command to see * whether we really quit the game. * @return true, if this command quits the game, false otherwise. */ private boolean quit(Command command) { if(command.hasSecondWord()) { out.println("Quit what?"); return false; } else { return true; // signal that we want to quit } } @Override public void handleRoomEvent(String event) { out.println(event); } }
Cloudxtreme/zuul-mmorpg
zuul-mmorpg/src/nl/hz/ict/p2/zuul/Player.java
1,233
// print prompt, verplaatst van de parser naar hier
line_comment
nl
package nl.hz.ict.p2.zuul; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; /** * Player - Holds all state for a single user that plays the game * * It evaluates and executes the commands that the parser returns. * * @author Michael Kölling and David J. Barnes * @version 2011.08.08 */ public class Player extends GameObject { private Parser parser; private PrintStream out; /** * Create the game and initialise its internal map. */ public Player(String name, Game game, InputStream externalInputStream, OutputStream externalOutputStream) { super(name, game); out = new PrintStream(externalOutputStream); parser = new Parser(externalInputStream); } /** * Main play routine. Loops until end of play. */ public void play() { this.setCurrentRoom(getWorld().getSpawnArea()); printWelcome(); // Enter the main command loop. Here we repeatedly read commands and // execute them until the game is over. boolean finished = false; while (! finished) { out.print("> "); // print prompt,<SUF> Command command = parser.getCommand(); finished = processCommand(command); } out.println("Thank you for playing. Good bye."); } /** * Print out the opening message for the player. */ private void printWelcome() { out.println(); out.println("Welcome " + name + " to the World of Zuul!"); out.println("World of Zuul is a new, incredibly boring adventure game."); out.println("Type 'help' if you need help."); out.println(); out.println(getCurrentRoom().getLongDescription()); // Het printen verplaatst vanuit de Room klasse. } /** * Given a command, process (that is: execute) the command. * @param command The command to be processed. * @return true If the command ends the game, false otherwise. */ private boolean processCommand(Command command) { boolean wantToQuit = false; if(command.isUnknown()) { out.println("I don't know what you mean..."); return false; } String commandWord = command.getCommandWord(); if (commandWord.equals("help")) { printHelp(); } else if (commandWord.equals("go")) { goRoom(command); } else if (commandWord.equals("quit")) { wantToQuit = quit(command); } // else command not recognised. return wantToQuit; } // implementations of user commands: /** * Print out some help information. * Here we print some stupid, cryptic message and a list of the * command words. */ private void printHelp() { out.println("You are lost. You are alone. You wander"); out.println("around at the university."); out.println(); out.println("Your command words are:"); out.println(parser.showCommands()); // Het printen verplaatst vanuit de Parser (en CommandWords) klasse. } /** * Try to in to one direction. If there is an exit, enter the new * room, otherwise print an error message. */ private void goRoom(Command command) { if(!command.hasSecondWord()) { // if there is no second word, we don't know where to go... out.println("Go where?"); return; } String direction = command.getSecondWord(); Room currentRoom = getCurrentRoom(); // Try to leave current room. Room nextRoom = currentRoom.getExit(direction); if (nextRoom == null) { out.println("There is no door!"); } else { setCurrentRoom(nextRoom); out.println(getCurrentRoom().getLongDescription()); } } /** * "Quit" was entered. Check the rest of the command to see * whether we really quit the game. * @return true, if this command quits the game, false otherwise. */ private boolean quit(Command command) { if(command.hasSecondWord()) { out.println("Quit what?"); return false; } else { return true; // signal that we want to quit } } @Override public void handleRoomEvent(String event) { out.println(event); } }
114765_2
package smos.application.registerManagement; import java.io.IOException; import java.sql.SQLException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import smos.Environment; import smos.bean.Absence; import smos.bean.Justify; import smos.bean.User; import smos.exception.DuplicatedEntityException; import smos.exception.EntityNotFoundException; import smos.exception.InvalidValueException; import smos.storage.ManagerRegister; import smos.storage.ManagerUser; import smos.storage.connectionManagement.exception.ConnectionException; import smos.utility.Utility; public class ServletInsertJustify extends HttpServlet { /** * */ private static final long serialVersionUID = 1252760418542867296L; /** * Definizione del metodo doGet * * @param pRequest * @param pResponse * */ public void doGet(HttpServletRequest pRequest, HttpServletResponse pResponse) { String gotoPage = "./registerManagement/showClassroomList.jsp"; String errorMessage = ""; HttpSession session = pRequest.getSession(); ManagerUser managerUser = ManagerUser.getInstance(); User loggedUser = (User) session.getAttribute("loggedUser"); try { if (loggedUser == null) { pResponse.sendRedirect("./index.htm"); return; } if (!managerUser.isAdministrator(loggedUser)) { errorMessage = "L'Utente collegato non ha accesso alla " + "funzionalita'!"; gotoPage = "./error.jsp"; } ManagerRegister mR= ManagerRegister.getInstance(); Justify justify=new Justify(); justify.setAcademicYear(Integer.parseInt(pRequest.getParameter("academicYear"))); justify.setDateJustify(Utility.String2Date(pRequest.getParameter("date"))); justify.setIdUser(Integer.parseInt(pRequest.getParameter("idUser"))); String idA= pRequest.getParameter("idAbsence"); int idAbsence=Integer.parseInt(idA); //String idC = pRequest.getParameter("idClassroom"); //int idClassroom= Integer.parseInt(idC); //gotoPage+=idClassroom; Absence absence = mR.getAbsenceByIdAbsence(idAbsence); if(!mR.exists(absence)){ errorMessage = "assenza non prensente nel db!"; gotoPage = "./error.jsp"; } //inserimento giustifica if(!mR.exists(justify)){ mR.insertJustify(justify, absence); session.setAttribute("justify", justify); }else throw new DuplicatedEntityException("Giustifica gia' esistente"); } catch (SQLException SQLException) { errorMessage = Environment.DEFAULT_ERROR_MESSAGE + SQLException.getMessage(); gotoPage = "./error.jsp"; SQLException.printStackTrace(); } catch (ConnectionException connectionException) { errorMessage = Environment.DEFAULT_ERROR_MESSAGE + connectionException.getMessage(); gotoPage = "./error.jsp"; connectionException.printStackTrace(); } catch (EntityNotFoundException entityNotFoundException) { errorMessage = Environment.DEFAULT_ERROR_MESSAGE + entityNotFoundException.getMessage(); gotoPage = "./error.jsp"; entityNotFoundException.printStackTrace(); } catch (InvalidValueException invalidValueException) { errorMessage = Environment.DEFAULT_ERROR_MESSAGE + invalidValueException.getMessage(); gotoPage = "./error.jsp"; invalidValueException.printStackTrace(); } catch (DuplicatedEntityException duplicatedEntityException) { errorMessage = Environment.DEFAULT_ERROR_MESSAGE + duplicatedEntityException.getMessage(); gotoPage = "./error.jsp"; duplicatedEntityException.printStackTrace(); } catch (IOException ioException) { errorMessage = Environment.DEFAULT_ERROR_MESSAGE + ioException.getMessage(); gotoPage = "./error.jsp"; ioException.printStackTrace(); } session.setAttribute("errorMessage", errorMessage); try { pResponse.sendRedirect(gotoPage); } catch (IOException ioException) { errorMessage = Environment.DEFAULT_ERROR_MESSAGE + ioException.getMessage(); gotoPage = "./error.jsp"; ioException.printStackTrace(); } } /** * Definizione del metodo doPost * * @param pRequest * @param pResponse * */ protected void doPost(HttpServletRequest pRequest, HttpServletResponse pResponse) { this.doGet(pRequest, pResponse); } }
CoEST/TraceLab
Main/Data/basic-contest/Datasets/SMOS/cc/ServletInsertJustify.txt
1,335
//int idClassroom= Integer.parseInt(idC);
line_comment
nl
package smos.application.registerManagement; import java.io.IOException; import java.sql.SQLException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import smos.Environment; import smos.bean.Absence; import smos.bean.Justify; import smos.bean.User; import smos.exception.DuplicatedEntityException; import smos.exception.EntityNotFoundException; import smos.exception.InvalidValueException; import smos.storage.ManagerRegister; import smos.storage.ManagerUser; import smos.storage.connectionManagement.exception.ConnectionException; import smos.utility.Utility; public class ServletInsertJustify extends HttpServlet { /** * */ private static final long serialVersionUID = 1252760418542867296L; /** * Definizione del metodo doGet * * @param pRequest * @param pResponse * */ public void doGet(HttpServletRequest pRequest, HttpServletResponse pResponse) { String gotoPage = "./registerManagement/showClassroomList.jsp"; String errorMessage = ""; HttpSession session = pRequest.getSession(); ManagerUser managerUser = ManagerUser.getInstance(); User loggedUser = (User) session.getAttribute("loggedUser"); try { if (loggedUser == null) { pResponse.sendRedirect("./index.htm"); return; } if (!managerUser.isAdministrator(loggedUser)) { errorMessage = "L'Utente collegato non ha accesso alla " + "funzionalita'!"; gotoPage = "./error.jsp"; } ManagerRegister mR= ManagerRegister.getInstance(); Justify justify=new Justify(); justify.setAcademicYear(Integer.parseInt(pRequest.getParameter("academicYear"))); justify.setDateJustify(Utility.String2Date(pRequest.getParameter("date"))); justify.setIdUser(Integer.parseInt(pRequest.getParameter("idUser"))); String idA= pRequest.getParameter("idAbsence"); int idAbsence=Integer.parseInt(idA); //String idC = pRequest.getParameter("idClassroom"); //int idClassroom=<SUF> //gotoPage+=idClassroom; Absence absence = mR.getAbsenceByIdAbsence(idAbsence); if(!mR.exists(absence)){ errorMessage = "assenza non prensente nel db!"; gotoPage = "./error.jsp"; } //inserimento giustifica if(!mR.exists(justify)){ mR.insertJustify(justify, absence); session.setAttribute("justify", justify); }else throw new DuplicatedEntityException("Giustifica gia' esistente"); } catch (SQLException SQLException) { errorMessage = Environment.DEFAULT_ERROR_MESSAGE + SQLException.getMessage(); gotoPage = "./error.jsp"; SQLException.printStackTrace(); } catch (ConnectionException connectionException) { errorMessage = Environment.DEFAULT_ERROR_MESSAGE + connectionException.getMessage(); gotoPage = "./error.jsp"; connectionException.printStackTrace(); } catch (EntityNotFoundException entityNotFoundException) { errorMessage = Environment.DEFAULT_ERROR_MESSAGE + entityNotFoundException.getMessage(); gotoPage = "./error.jsp"; entityNotFoundException.printStackTrace(); } catch (InvalidValueException invalidValueException) { errorMessage = Environment.DEFAULT_ERROR_MESSAGE + invalidValueException.getMessage(); gotoPage = "./error.jsp"; invalidValueException.printStackTrace(); } catch (DuplicatedEntityException duplicatedEntityException) { errorMessage = Environment.DEFAULT_ERROR_MESSAGE + duplicatedEntityException.getMessage(); gotoPage = "./error.jsp"; duplicatedEntityException.printStackTrace(); } catch (IOException ioException) { errorMessage = Environment.DEFAULT_ERROR_MESSAGE + ioException.getMessage(); gotoPage = "./error.jsp"; ioException.printStackTrace(); } session.setAttribute("errorMessage", errorMessage); try { pResponse.sendRedirect(gotoPage); } catch (IOException ioException) { errorMessage = Environment.DEFAULT_ERROR_MESSAGE + ioException.getMessage(); gotoPage = "./error.jsp"; ioException.printStackTrace(); } } /** * Definizione del metodo doPost * * @param pRequest * @param pResponse * */ protected void doPost(HttpServletRequest pRequest, HttpServletResponse pResponse) { this.doGet(pRequest, pResponse); } }
66273_4
package gad17.blatt02; /** * Objekte der Klasse Interval stellen einen Bereich von Zahlen dar. */ abstract class Interval { /** * Abfragen der unteren, inklusiven Intervallgrenze * * @return die untere, inklusive Grenze */ public abstract int getFrom(); /** * Abfragen der oberen, inklusiven Intervallgrenze * * @return die obere, inklusive Grenze */ public abstract int getTo(); /** * Diese Methode erzeugt ein Intervall aus Array-Indices. Ist die * untere Intervallberenzung größer als die obere Intervallbegrenzung * oder ist einer der Begrenzungen negativ, so wird ein leeres Intervall * zurückgegeben. * * @param from die untere, inklusive Intervallbegrenzung * @param to die obere, inklusive Intervallbegrenzung * @return ein Intervallobjekt, das den Indexbereich repräsentiert */ static Interval fromArrayIndices(int from, int to) { if (to < from) return new EmptyInterval(); else if (to < 0 || from < 0) return new EmptyInterval(); else return new NonEmptyInterval(from, to); } } /** * Objekte der Klasse NonEmptyInterval repräsentieren ein nicht-leeres * Intervall. */ class NonEmptyInterval extends Interval { private int from; private int to; @Override public int getFrom() { return from; } @Override public int getTo() { return to; } public NonEmptyInterval(int from, int to) { if (to >= from) { this.from = from; this.to = to; } else throw new RuntimeException("Invalid interval boundary"); } @Override public String toString() { return "[" + from + ";" + to + "]"; } } /** * Objekte der Klasse EmptyInterval repräsentieren ein leeres Intervall. */ class EmptyInterval extends Interval { @Override public int getFrom() { throw new RuntimeException("No lower boundary in empty interval"); } @Override public int getTo() { throw new RuntimeException("No upper boundary in empty interval"); } public EmptyInterval() { } @Override public String toString() { return "[]"; } }
Code-Connect/TUM_Homework
src/gad17/blatt02/Interval.java
680
/** * Objekte der Klasse NonEmptyInterval repräsentieren ein nicht-leeres * Intervall. */
block_comment
nl
package gad17.blatt02; /** * Objekte der Klasse Interval stellen einen Bereich von Zahlen dar. */ abstract class Interval { /** * Abfragen der unteren, inklusiven Intervallgrenze * * @return die untere, inklusive Grenze */ public abstract int getFrom(); /** * Abfragen der oberen, inklusiven Intervallgrenze * * @return die obere, inklusive Grenze */ public abstract int getTo(); /** * Diese Methode erzeugt ein Intervall aus Array-Indices. Ist die * untere Intervallberenzung größer als die obere Intervallbegrenzung * oder ist einer der Begrenzungen negativ, so wird ein leeres Intervall * zurückgegeben. * * @param from die untere, inklusive Intervallbegrenzung * @param to die obere, inklusive Intervallbegrenzung * @return ein Intervallobjekt, das den Indexbereich repräsentiert */ static Interval fromArrayIndices(int from, int to) { if (to < from) return new EmptyInterval(); else if (to < 0 || from < 0) return new EmptyInterval(); else return new NonEmptyInterval(from, to); } } /** * Objekte der Klasse<SUF>*/ class NonEmptyInterval extends Interval { private int from; private int to; @Override public int getFrom() { return from; } @Override public int getTo() { return to; } public NonEmptyInterval(int from, int to) { if (to >= from) { this.from = from; this.to = to; } else throw new RuntimeException("Invalid interval boundary"); } @Override public String toString() { return "[" + from + ";" + to + "]"; } } /** * Objekte der Klasse EmptyInterval repräsentieren ein leeres Intervall. */ class EmptyInterval extends Interval { @Override public int getFrom() { throw new RuntimeException("No lower boundary in empty interval"); } @Override public int getTo() { throw new RuntimeException("No upper boundary in empty interval"); } public EmptyInterval() { } @Override public String toString() { return "[]"; } }
16294_9
package net.daansander.coder; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.plugin.java.JavaPlugin; import java.math.BigDecimal; /** * Created by Daan on 22-5-2015. */ /** * implements Listener is zodat bukkit weet dat hier evenementen afspelen */ public class Coder extends JavaPlugin implements Listener { /** * CoderDojo Cheat Sheat door Daan Meijer * @author Daan Meijer */ /** * int = een normaal nummer en kan maximaal 2^31-1 hebben. * double = een normaal nummer met decimalen zoals: 10.34531 * boolean = is een schakelaar het kan waar of niet waar zijn * long = is groot het kan een heel groot getal zijn zoals: 9349641242334513 * float = is een soort van double * byte = is erg klein * short = is een soort van byte maar dan groter * * public = open voor elke class * protected = alleen voor classes die het 'extenden' * private = is alleen voor de class zelf * static = is open voor iedereen * final = kan je niet veranderen * synchronized = heeft voorang op alle codes * * * new = maak een nieuwe instancie aan van een class * throw = gooi een error * abstract = methods die in de class moeten zitten * interface = volledig abstracte methods * */ public void onEnable() { //Hiermee kun je events registreren /** * this staat voor deze class */ Bukkit.getServer().getPluginManager().registerEvents(this , this); //Hier maken wij een 'Runnable aan' die om de seconde iets doet Bukkit.getServer().getScheduler().runTaskTimer(this, new Runnable() { @Override public void run() { //Hier gaat gebeuren dat op de server iedere 1 seconde de bericht "1 Seconde voorbij" wordt gebroadcast(gestuurd) Bukkit.broadcastMessage("1 Seconde voorbij"); } //Java werkt in 'ticks' 20 ticks zijn 1 seconde dus 10 ticks is een halve seconde },0, 20l); } //Hiermee wordt een event aangegeven @EventHandler //onPlayerJoin is de naam je kan er zelf wat voor verzinnen //PlayerJoinEvent is een van de vele evenementen ik neem deze als voorbeeld //Als je een beetje engels zie je Player dus de player Join dus met als de player het spel joind en Event en dan is dan het Event //Dus deze event wordt gecalled wanneer er een player joind public void onPlayerJoin(PlayerJoinEvent e) { //Hier kan je dingen in uit voeren als iemand joind } //Dit is voor een command @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { //Hier checken wij of de command maakt niet uit in hoofdletters of niet "command" is if(cmd.getName().equalsIgnoreCase("command")) { //Hier kunnen we dingen uitvoeren als de command "command wordt uitgevoerd" } return true; } }
CoderDojoRotterdam/minecraft-mod-workshop
src/me/daansander/coderdojo/Main.java
918
//Hiermee wordt een event aangegeven
line_comment
nl
package net.daansander.coder; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.plugin.java.JavaPlugin; import java.math.BigDecimal; /** * Created by Daan on 22-5-2015. */ /** * implements Listener is zodat bukkit weet dat hier evenementen afspelen */ public class Coder extends JavaPlugin implements Listener { /** * CoderDojo Cheat Sheat door Daan Meijer * @author Daan Meijer */ /** * int = een normaal nummer en kan maximaal 2^31-1 hebben. * double = een normaal nummer met decimalen zoals: 10.34531 * boolean = is een schakelaar het kan waar of niet waar zijn * long = is groot het kan een heel groot getal zijn zoals: 9349641242334513 * float = is een soort van double * byte = is erg klein * short = is een soort van byte maar dan groter * * public = open voor elke class * protected = alleen voor classes die het 'extenden' * private = is alleen voor de class zelf * static = is open voor iedereen * final = kan je niet veranderen * synchronized = heeft voorang op alle codes * * * new = maak een nieuwe instancie aan van een class * throw = gooi een error * abstract = methods die in de class moeten zitten * interface = volledig abstracte methods * */ public void onEnable() { //Hiermee kun je events registreren /** * this staat voor deze class */ Bukkit.getServer().getPluginManager().registerEvents(this , this); //Hier maken wij een 'Runnable aan' die om de seconde iets doet Bukkit.getServer().getScheduler().runTaskTimer(this, new Runnable() { @Override public void run() { //Hier gaat gebeuren dat op de server iedere 1 seconde de bericht "1 Seconde voorbij" wordt gebroadcast(gestuurd) Bukkit.broadcastMessage("1 Seconde voorbij"); } //Java werkt in 'ticks' 20 ticks zijn 1 seconde dus 10 ticks is een halve seconde },0, 20l); } //Hiermee wordt<SUF> @EventHandler //onPlayerJoin is de naam je kan er zelf wat voor verzinnen //PlayerJoinEvent is een van de vele evenementen ik neem deze als voorbeeld //Als je een beetje engels zie je Player dus de player Join dus met als de player het spel joind en Event en dan is dan het Event //Dus deze event wordt gecalled wanneer er een player joind public void onPlayerJoin(PlayerJoinEvent e) { //Hier kan je dingen in uit voeren als iemand joind } //Dit is voor een command @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { //Hier checken wij of de command maakt niet uit in hoofdletters of niet "command" is if(cmd.getName().equalsIgnoreCase("command")) { //Hier kunnen we dingen uitvoeren als de command "command wordt uitgevoerd" } return true; } }
44505_0
package io.preuss.pay4day; import net.milkbowl.vault.economy.Economy; import net.milkbowl.vault.economy.EconomyResponse; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; public class Pay4Day extends JavaPlugin{ private String prefix = ChatColor.GREEN + "[Pay4Day] "; private static Economy econ = null; public void onDisable(){ getLogger().info("Pay4Day has been disabled!"); } public void onEnable(){ loadConfig(); getLogger().info("-------------------------"); getLogger().info("Created by: Preuß.IO GbR"); getLogger().info("Website: http://preuss.io/"); getLogger().info("Updates: https://dev.bukkit.org/projects/pay4day/"); getLogger().info("Authors: " + String.join(", ", getDescription().getAuthors())); getLogger().info("Version: " + getDescription().getVersion()); getLogger().info("-------------------------"); if (!setupEconomy()){ getLogger().warning(String.format("[%s] - Disabled due to no Vault dependency found! You can download it here https://dev.bukkit.org/projects/vault", new Object[] { getDescription().getName() })); getServer().getPluginManager().disablePlugin(this); return; } getLogger().warning("We have new config.yml! If you use older version than 4.0 PLEASE REMOVE YOUR OLD CONFIG.YML"); getLogger().info("-------------------------"); getLogger().info("Pay4Day has been enabled!"); } private boolean setupEconomy(){ if (getServer().getPluginManager().getPlugin("Vault") == null) { return false; } RegisteredServiceProvider<Economy> serviceProvider = getServer().getServicesManager().getRegistration(Economy.class); if (serviceProvider == null) { return false; } econ = serviceProvider.getProvider(); return econ != null; } public boolean onCommand(CommandSender commandSender, Command command, String commandLabel, String[] args){ if(command.getName().equalsIgnoreCase("pay4day")){ if (!(commandSender instanceof Player)){ getLogger().info(getConfig().getString("msg." + getConfig().getString("config.language") + ".cmd_command")); return true; }else{ if(args.length == 0){ //Classic Command if(commandSender.hasPermission("pay4day.use.classic")){ buildWeather(commandSender, "classic", getConfig().getDouble("config.price.classic")); }else{ commandSender.sendMessage(prefix + getConfig().getString("msg." + getConfig().getString("config.language") + ".permissions")); } }else if(args.length == 1){ if(args[0].equalsIgnoreCase("day")){ if(commandSender.hasPermission("pay4day.use.day")){ buildWeather(commandSender, "day", getConfig().getDouble("config.price.day")); }else{ commandSender.sendMessage(prefix + getConfig().getString("msg." + getConfig().getString("config.language") + ".permissions")); } }else if(args[0].equalsIgnoreCase("night")){ if(commandSender.hasPermission("pay4day.use.night")){ buildWeather(commandSender, "night", getConfig().getDouble("config.price.night")); }else{ commandSender.sendMessage(prefix + getConfig().getString("msg." + getConfig().getString("config.language") + ".permissions")); } }else if(args[0].equalsIgnoreCase("sun")){ if(commandSender.hasPermission("pay4day.use.sun")){ buildWeather(commandSender, "sun", getConfig().getDouble("config.price.sun")); }else{ commandSender.sendMessage(prefix + getConfig().getString("msg." + getConfig().getString("config.language") + ".permissions")); } }else if(args[0].equalsIgnoreCase("rain")){ if(commandSender.hasPermission("pay4day.use.rain")){ buildWeather(commandSender, "rain", getConfig().getDouble("config.price.rain")); }else{ commandSender.sendMessage(prefix + getConfig().getString("msg." + getConfig().getString("config.language") + ".permissions")); } }else if(args[0].equalsIgnoreCase("storm")){ if(commandSender.hasPermission("pay4day.use.storm")){ buildWeather(commandSender, "storm", getConfig().getDouble("config.price.storm")); }else{ commandSender.sendMessage(prefix + getConfig().getString("msg." + getConfig().getString("config.language") + ".permissions")); } } } } }else if(command.getName().equalsIgnoreCase("pay4night")){ getServer().dispatchCommand(commandSender, "pay4day night"); }else if(command.getName().equalsIgnoreCase("pay4sun")){ getServer().dispatchCommand(commandSender, "pay4day sun"); }else if(command.getName().equalsIgnoreCase("pay4rain")){ getServer().dispatchCommand(commandSender, "pay4day rain"); }else if(command.getName().equalsIgnoreCase("pay4storm")){ getServer().dispatchCommand(commandSender, "pay4day storm"); } return true; } private void buildWeather(CommandSender commandSender, String typ, double price) { Player player = (Player) commandSender; EconomyResponse r = econ.withdrawPlayer((OfflinePlayer) commandSender, price); if (r.transactionSuccess()){ if(typ.equalsIgnoreCase("classic")){ if(getConfig().getBoolean("config.classic.setDay")){ player.getWorld().setTime(0); }else if(getConfig().getBoolean("config.classic.setNight")){ player.getWorld().setTime(18000); }else if(getConfig().getBoolean("config.classic.setSun")){ player.getWorld().setThundering(false); player.getWorld().setStorm(false); }else if(getConfig().getBoolean("config.classic.setRain")){ player.getWorld().setThundering(false); player.getWorld().setStorm(true); }else if(getConfig().getBoolean("config.classic.setStorm")){ player.getWorld().setThundering(true); player.getWorld().setStorm(true); } }else if(typ.equalsIgnoreCase("day")){ player.getWorld().setTime(0); }else if(typ.equalsIgnoreCase("night")){ player.getWorld().setTime(18000); }else if(typ.equalsIgnoreCase("sun")){ player.getWorld().setThundering(false); player.getWorld().setStorm(false); }else if(typ.equalsIgnoreCase("rain")){ player.getWorld().setThundering(false); player.getWorld().setStorm(true); }else if(typ.equalsIgnoreCase("storm")){ player.getWorld().setThundering(true); player.getWorld().setStorm(true); } player.sendMessage(prefix + getConfig().getString("msg." + getConfig().getString("config.language") + ".surcces_msg_" + typ)); if(getConfig().getBoolean("config.sendLocalMsg")){ for(Player p : getServer().getOnlinePlayers()){ String broadcast = getConfig().getString("msg." + getConfig().getString("config.language") + ".broadcast_" + typ).replace("%price%", String.valueOf(price)); broadcast = broadcast.replace("%currency%", getConfig().getString("config.currency")); broadcast = broadcast.replace("%player%", player.getName()); p.sendMessage(prefix + broadcast); } } String str = getConfig().getString("msg." + getConfig().getString("config.language") + ".surcess_money_msg").replace("%price%", String.valueOf(price)); String surcess_money_msg = str.replace("%currency%", getConfig().getString("config.currency")); player.sendMessage(prefix + surcess_money_msg); }else{ String str = getConfig().getString("msg." + getConfig().getString("config.language") + ".surcess_money_msg").replace("%price%", String.valueOf(price)); String surcess_money_msg = str.replace("%currency%", getConfig().getString("config.currency")); player.sendMessage(prefix + surcess_money_msg); } } private void loadConfig(){ getConfig().addDefault("config.price.classic", 100.0); getConfig().addDefault("config.price.day", 100.0); getConfig().addDefault("config.price.night", 100.0); getConfig().addDefault("config.price.sun", 100.0); getConfig().addDefault("config.price.rain", 100.0); getConfig().addDefault("config.price.storm", 100.0); getConfig().addDefault("config.classic.setDay", true); getConfig().addDefault("config.classic.setNight", false); getConfig().addDefault("config.classic.setSun", true); getConfig().addDefault("config.classic.setRain", false); getConfig().addDefault("config.classic.setStorm", false); getConfig().addDefault("config.language", "en"); getConfig().addDefault("config.currency", "Dollar"); getConfig().addDefault("config.sendLocalMsg", true); /*------------------------ ENGLISH -------------------------------*/ getConfig().addDefault("msg.en.surcces_msg_classic", "Successfully set day and sun."); getConfig().addDefault("msg.en.surcces_msg_day", "Successfully set day."); getConfig().addDefault("msg.en.surcces_msg_night", "Successfully set night."); getConfig().addDefault("msg.en.surcces_msg_sun", "Successfully set sun."); getConfig().addDefault("msg.en.surcces_msg_rain", "Successfully set rain."); getConfig().addDefault("msg.en.surcces_msg_storm", "Successfully set storm."); getConfig().addDefault("msg.en.broadcast_classic", "%player% spent %price% %currency% for day and sun."); getConfig().addDefault("msg.en.broadcast_day", "%player% spent %price% %currency% for day."); getConfig().addDefault("msg.en.broadcast_night", "%player% spent %price% %currency% for night."); getConfig().addDefault("msg.en.broadcast_sun", "%player% spent %price% %currency% for sun."); getConfig().addDefault("msg.en.broadcast_rain", "%player% spent %price% %currency% for rain."); getConfig().addDefault("msg.en.broadcast_storm", "%player% spent %price% %currency% for storm."); getConfig().addDefault("msg.en.surcess_money_msg", "You spent %price% %currency%."); getConfig().addDefault("msg.en.not_enough_money", "You do not have enough money, you need %price% %currency%"); getConfig().addDefault("msg.en.permissions", "You do not have permissions for this command."); getConfig().addDefault("msg.en.cmd_command", "Only players can use this command."); /*------------------------- GERMAN ------------------------------*/ getConfig().addDefault("msg.de.surcces_msg_classic", "Du hast dir Tag & Gutes Wetter gekauft."); getConfig().addDefault("msg.de.surcces_msg_day", "Du hast dir Tag & Gutes Wetter gekauft."); getConfig().addDefault("msg.de.surcces_msg_night", "Du hast dir die Nacht gekauft."); getConfig().addDefault("msg.de.surcces_msg_sun", "Du hast dir die Sonne gekauft."); getConfig().addDefault("msg.de.surcces_msg_rain", "Du hast dir den Regen gekauft."); getConfig().addDefault("msg.de.surcces_msg_storm", "Du hast dir den Sturm gekauft."); getConfig().addDefault("msg.de.broadcast_classic", "%player% hat sich Tag & Sonne gekauft für %price% %currency%."); getConfig().addDefault("msg.de.broadcast_day", "%player% hat sich Tag gekauft für %price% %currency%."); getConfig().addDefault("msg.de.broadcast_night", "%player% hat sich Nacht gekauft für %price% %currency%."); getConfig().addDefault("msg.de.broadcast_sun", "%player% hat sich Sonne gekauft für %price% %currency%."); getConfig().addDefault("msg.de.broadcast_rain", "%player% hat sich Regen gekauft für %price% %currency%."); getConfig().addDefault("msg.de.broadcast_storm", "%player% hat sich Stumr gekauft für %price% %currency%."); getConfig().addDefault("msg.de.surcess_money_msg", "Dir wurden %price% %currency%s abgezogen"); getConfig().addDefault("msg.de.not_enough_money", "Du hast zu wenig Geld, du brauchst %price% %currency%."); getConfig().addDefault("msg.de.permissions", "Du hast nicht die Permissions für diesen Befehl."); getConfig().addDefault("msg.de.cmd_command", "Nur Spieler können diesen Befehl benutzen."); getConfig().options().copyDefaults(true); saveConfig(); } }
CodingDev/Pay4Day
src/main/java/io/preuss/pay4day/Pay4Day.java
3,858
//dev.bukkit.org/projects/vault", new Object[] { getDescription().getName() }));
line_comment
nl
package io.preuss.pay4day; import net.milkbowl.vault.economy.Economy; import net.milkbowl.vault.economy.EconomyResponse; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; public class Pay4Day extends JavaPlugin{ private String prefix = ChatColor.GREEN + "[Pay4Day] "; private static Economy econ = null; public void onDisable(){ getLogger().info("Pay4Day has been disabled!"); } public void onEnable(){ loadConfig(); getLogger().info("-------------------------"); getLogger().info("Created by: Preuß.IO GbR"); getLogger().info("Website: http://preuss.io/"); getLogger().info("Updates: https://dev.bukkit.org/projects/pay4day/"); getLogger().info("Authors: " + String.join(", ", getDescription().getAuthors())); getLogger().info("Version: " + getDescription().getVersion()); getLogger().info("-------------------------"); if (!setupEconomy()){ getLogger().warning(String.format("[%s] - Disabled due to no Vault dependency found! You can download it here https://dev.bukkit.org/projects/vault", new<SUF> getServer().getPluginManager().disablePlugin(this); return; } getLogger().warning("We have new config.yml! If you use older version than 4.0 PLEASE REMOVE YOUR OLD CONFIG.YML"); getLogger().info("-------------------------"); getLogger().info("Pay4Day has been enabled!"); } private boolean setupEconomy(){ if (getServer().getPluginManager().getPlugin("Vault") == null) { return false; } RegisteredServiceProvider<Economy> serviceProvider = getServer().getServicesManager().getRegistration(Economy.class); if (serviceProvider == null) { return false; } econ = serviceProvider.getProvider(); return econ != null; } public boolean onCommand(CommandSender commandSender, Command command, String commandLabel, String[] args){ if(command.getName().equalsIgnoreCase("pay4day")){ if (!(commandSender instanceof Player)){ getLogger().info(getConfig().getString("msg." + getConfig().getString("config.language") + ".cmd_command")); return true; }else{ if(args.length == 0){ //Classic Command if(commandSender.hasPermission("pay4day.use.classic")){ buildWeather(commandSender, "classic", getConfig().getDouble("config.price.classic")); }else{ commandSender.sendMessage(prefix + getConfig().getString("msg." + getConfig().getString("config.language") + ".permissions")); } }else if(args.length == 1){ if(args[0].equalsIgnoreCase("day")){ if(commandSender.hasPermission("pay4day.use.day")){ buildWeather(commandSender, "day", getConfig().getDouble("config.price.day")); }else{ commandSender.sendMessage(prefix + getConfig().getString("msg." + getConfig().getString("config.language") + ".permissions")); } }else if(args[0].equalsIgnoreCase("night")){ if(commandSender.hasPermission("pay4day.use.night")){ buildWeather(commandSender, "night", getConfig().getDouble("config.price.night")); }else{ commandSender.sendMessage(prefix + getConfig().getString("msg." + getConfig().getString("config.language") + ".permissions")); } }else if(args[0].equalsIgnoreCase("sun")){ if(commandSender.hasPermission("pay4day.use.sun")){ buildWeather(commandSender, "sun", getConfig().getDouble("config.price.sun")); }else{ commandSender.sendMessage(prefix + getConfig().getString("msg." + getConfig().getString("config.language") + ".permissions")); } }else if(args[0].equalsIgnoreCase("rain")){ if(commandSender.hasPermission("pay4day.use.rain")){ buildWeather(commandSender, "rain", getConfig().getDouble("config.price.rain")); }else{ commandSender.sendMessage(prefix + getConfig().getString("msg." + getConfig().getString("config.language") + ".permissions")); } }else if(args[0].equalsIgnoreCase("storm")){ if(commandSender.hasPermission("pay4day.use.storm")){ buildWeather(commandSender, "storm", getConfig().getDouble("config.price.storm")); }else{ commandSender.sendMessage(prefix + getConfig().getString("msg." + getConfig().getString("config.language") + ".permissions")); } } } } }else if(command.getName().equalsIgnoreCase("pay4night")){ getServer().dispatchCommand(commandSender, "pay4day night"); }else if(command.getName().equalsIgnoreCase("pay4sun")){ getServer().dispatchCommand(commandSender, "pay4day sun"); }else if(command.getName().equalsIgnoreCase("pay4rain")){ getServer().dispatchCommand(commandSender, "pay4day rain"); }else if(command.getName().equalsIgnoreCase("pay4storm")){ getServer().dispatchCommand(commandSender, "pay4day storm"); } return true; } private void buildWeather(CommandSender commandSender, String typ, double price) { Player player = (Player) commandSender; EconomyResponse r = econ.withdrawPlayer((OfflinePlayer) commandSender, price); if (r.transactionSuccess()){ if(typ.equalsIgnoreCase("classic")){ if(getConfig().getBoolean("config.classic.setDay")){ player.getWorld().setTime(0); }else if(getConfig().getBoolean("config.classic.setNight")){ player.getWorld().setTime(18000); }else if(getConfig().getBoolean("config.classic.setSun")){ player.getWorld().setThundering(false); player.getWorld().setStorm(false); }else if(getConfig().getBoolean("config.classic.setRain")){ player.getWorld().setThundering(false); player.getWorld().setStorm(true); }else if(getConfig().getBoolean("config.classic.setStorm")){ player.getWorld().setThundering(true); player.getWorld().setStorm(true); } }else if(typ.equalsIgnoreCase("day")){ player.getWorld().setTime(0); }else if(typ.equalsIgnoreCase("night")){ player.getWorld().setTime(18000); }else if(typ.equalsIgnoreCase("sun")){ player.getWorld().setThundering(false); player.getWorld().setStorm(false); }else if(typ.equalsIgnoreCase("rain")){ player.getWorld().setThundering(false); player.getWorld().setStorm(true); }else if(typ.equalsIgnoreCase("storm")){ player.getWorld().setThundering(true); player.getWorld().setStorm(true); } player.sendMessage(prefix + getConfig().getString("msg." + getConfig().getString("config.language") + ".surcces_msg_" + typ)); if(getConfig().getBoolean("config.sendLocalMsg")){ for(Player p : getServer().getOnlinePlayers()){ String broadcast = getConfig().getString("msg." + getConfig().getString("config.language") + ".broadcast_" + typ).replace("%price%", String.valueOf(price)); broadcast = broadcast.replace("%currency%", getConfig().getString("config.currency")); broadcast = broadcast.replace("%player%", player.getName()); p.sendMessage(prefix + broadcast); } } String str = getConfig().getString("msg." + getConfig().getString("config.language") + ".surcess_money_msg").replace("%price%", String.valueOf(price)); String surcess_money_msg = str.replace("%currency%", getConfig().getString("config.currency")); player.sendMessage(prefix + surcess_money_msg); }else{ String str = getConfig().getString("msg." + getConfig().getString("config.language") + ".surcess_money_msg").replace("%price%", String.valueOf(price)); String surcess_money_msg = str.replace("%currency%", getConfig().getString("config.currency")); player.sendMessage(prefix + surcess_money_msg); } } private void loadConfig(){ getConfig().addDefault("config.price.classic", 100.0); getConfig().addDefault("config.price.day", 100.0); getConfig().addDefault("config.price.night", 100.0); getConfig().addDefault("config.price.sun", 100.0); getConfig().addDefault("config.price.rain", 100.0); getConfig().addDefault("config.price.storm", 100.0); getConfig().addDefault("config.classic.setDay", true); getConfig().addDefault("config.classic.setNight", false); getConfig().addDefault("config.classic.setSun", true); getConfig().addDefault("config.classic.setRain", false); getConfig().addDefault("config.classic.setStorm", false); getConfig().addDefault("config.language", "en"); getConfig().addDefault("config.currency", "Dollar"); getConfig().addDefault("config.sendLocalMsg", true); /*------------------------ ENGLISH -------------------------------*/ getConfig().addDefault("msg.en.surcces_msg_classic", "Successfully set day and sun."); getConfig().addDefault("msg.en.surcces_msg_day", "Successfully set day."); getConfig().addDefault("msg.en.surcces_msg_night", "Successfully set night."); getConfig().addDefault("msg.en.surcces_msg_sun", "Successfully set sun."); getConfig().addDefault("msg.en.surcces_msg_rain", "Successfully set rain."); getConfig().addDefault("msg.en.surcces_msg_storm", "Successfully set storm."); getConfig().addDefault("msg.en.broadcast_classic", "%player% spent %price% %currency% for day and sun."); getConfig().addDefault("msg.en.broadcast_day", "%player% spent %price% %currency% for day."); getConfig().addDefault("msg.en.broadcast_night", "%player% spent %price% %currency% for night."); getConfig().addDefault("msg.en.broadcast_sun", "%player% spent %price% %currency% for sun."); getConfig().addDefault("msg.en.broadcast_rain", "%player% spent %price% %currency% for rain."); getConfig().addDefault("msg.en.broadcast_storm", "%player% spent %price% %currency% for storm."); getConfig().addDefault("msg.en.surcess_money_msg", "You spent %price% %currency%."); getConfig().addDefault("msg.en.not_enough_money", "You do not have enough money, you need %price% %currency%"); getConfig().addDefault("msg.en.permissions", "You do not have permissions for this command."); getConfig().addDefault("msg.en.cmd_command", "Only players can use this command."); /*------------------------- GERMAN ------------------------------*/ getConfig().addDefault("msg.de.surcces_msg_classic", "Du hast dir Tag & Gutes Wetter gekauft."); getConfig().addDefault("msg.de.surcces_msg_day", "Du hast dir Tag & Gutes Wetter gekauft."); getConfig().addDefault("msg.de.surcces_msg_night", "Du hast dir die Nacht gekauft."); getConfig().addDefault("msg.de.surcces_msg_sun", "Du hast dir die Sonne gekauft."); getConfig().addDefault("msg.de.surcces_msg_rain", "Du hast dir den Regen gekauft."); getConfig().addDefault("msg.de.surcces_msg_storm", "Du hast dir den Sturm gekauft."); getConfig().addDefault("msg.de.broadcast_classic", "%player% hat sich Tag & Sonne gekauft für %price% %currency%."); getConfig().addDefault("msg.de.broadcast_day", "%player% hat sich Tag gekauft für %price% %currency%."); getConfig().addDefault("msg.de.broadcast_night", "%player% hat sich Nacht gekauft für %price% %currency%."); getConfig().addDefault("msg.de.broadcast_sun", "%player% hat sich Sonne gekauft für %price% %currency%."); getConfig().addDefault("msg.de.broadcast_rain", "%player% hat sich Regen gekauft für %price% %currency%."); getConfig().addDefault("msg.de.broadcast_storm", "%player% hat sich Stumr gekauft für %price% %currency%."); getConfig().addDefault("msg.de.surcess_money_msg", "Dir wurden %price% %currency%s abgezogen"); getConfig().addDefault("msg.de.not_enough_money", "Du hast zu wenig Geld, du brauchst %price% %currency%."); getConfig().addDefault("msg.de.permissions", "Du hast nicht die Permissions für diesen Befehl."); getConfig().addDefault("msg.de.cmd_command", "Nur Spieler können diesen Befehl benutzen."); getConfig().options().copyDefaults(true); saveConfig(); } }
116580_3
package Pop.Bot; import Pop.Bot.Cosmetics.Cosmetic; import Pop.Bot.Weapons.*; import Pop.Enums.TFClasses; import Pop.PopRandomizer; import Pop.RandomizerPresets; import java.util.*; /** * Represents a randomly generated spy */ public class RandomSpy extends RandomBot { /** * Constructor */ public RandomSpy() { tfClass = TFClasses.SPY; baseHealth = 125; primaryWeaponList = new ArrayList<>(Arrays.asList( new HitscanWeapon("Upgradeable TF_WEAPON_REVOLVER", "Revolver"), //new HitscanWeapon("Festive Revolver 2014", "Festive Revolver"), // In skins //new HitscanWeapon("TTG Sam Revolver", "Sam Revolver"), // In skins new HitscanWeapon("The Ambassador"), //new HitscanWeapon("Festive Ambassador"), // In skins new HitscanWeapon("L'Etranger"), new HitscanWeapon("The Enforcer"), new HitscanWeapon("The Diamondback") )); secondaryWeaponList = new ArrayList<>( // Spies cannot have sappers or it crashes! // Arrays.asList( // "Upgradeable TF_WEAPON_BUILDER_SPY", // "The Red-Tape Recorder", // "The Ap-Sap", // "Festive Sapper", // "The Snack Attack") ); meleeWeaponList = new ArrayList<>(Arrays.asList( new Weapon("Upgradeable TF_WEAPON_KNIFE", "Knife"), //new Weapon("Festive Knife 2011", "Festive Knife"), // In skins //new Weapon("The Sharp Dresser"), // In skins //new Weapon("The Black Rose"), // In skins new Weapon("Your Eternal Reward"), // new Weapon("The Wanga Prick"), // In skins new Weapon("Conniver's Kunai"), new Weapon("The Big Earner"), new Weapon("The Spy-cicle") // "Gold Frying Pan", // "Prinny Machete", // "Saxxy") )); classOnlyCosmetics = new ArrayList<>(Arrays.asList( new Cosmetic("Fancy Fedora"), new Cosmetic("Backbiter's Billycock"), new Cosmetic("Camera Beard"), new Cosmetic("Spy Noble Hair", "Nobled Haired"), new Cosmetic("Spy Beret", "Beret"), new Cosmetic("The Familiar Fez"), new Cosmetic("Detective Noir"), new Cosmetic("Le Party Phantom"), new Cosmetic("Spy Oni Mask"), new Cosmetic("Charmer's Chapeau"), new Cosmetic("Private Eye"), new Cosmetic("Janissary Hat"), new Cosmetic("Cosa Nostra Cap"), new Cosmetic("Belltower Spec Ops"), new Cosmetic("The Counterfeit Billycock"), new Cosmetic("L'Inspecteur"), new Cosmetic("The Spectre's Spectacles"), new Cosmetic("Griffin's Gog"), new Cosmetic("Under Cover"), new Cosmetic("The Doublecross-Comm"), new Cosmetic("The Ninja Cowl"), new Cosmetic("The Stealth Steeler"), new Cosmetic("Hat of Cards"), new Cosmetic("The Scarecrow"), new Cosmetic("The Dapper Disguise"), new Cosmetic("The Bloodhound"), new Cosmetic("Base Metal Billycock", "Metal Billycock"), new Cosmetic("Bootleg Base Metal Billycock", "Bootleg Billycock"), new Cosmetic("The Megapixel Beard"), new Cosmetic("The Pom-Pommed Provocateur"), new Cosmetic("The Belgian Detective"), new Cosmetic("The Harmburg"), new Cosmetic("The Macho Mann"), new Cosmetic("L'homme Burglerre"), new Cosmetic("The Candyman's Cap"), new Cosmetic("The Hyperbaric Bowler"), new Cosmetic("Ethereal Hood"), new Cosmetic("The Napoleon Complex"), new Cosmetic("The Deep Cover Operator"), new Cosmetic("The Aviator Assassin"), new Cosmetic("Facepeeler"), new Cosmetic("Nightmare Hunter"), new Cosmetic("Rogue's Rabbit"), new Cosmetic("Shadowman's Shade"), new Cosmetic("The Graylien"), new Cosmetic("Teufort Knight"), new Cosmetic("A Hat to Kill For"), new Cosmetic("The Dead Head"), new Cosmetic("Big Topper"), new Cosmetic("Brain-Warming Wear"), new Cosmetic("Reader's Choice"), new Cosmetic("The Upgrade"), new Cosmetic("Aristotle"), new Cosmetic("Murderer's Motif"), new Cosmetic("Harry"), new Cosmetic("Shutterbug"), new Cosmetic("Avian Amante"), new Cosmetic("Voodoo Vizier"), new Cosmetic("Bird's Eye Viewer"), new Cosmetic("Crabe de Chapeau"), new Cosmetic("Particulate Protector"), new Cosmetic("Crustaceous Cowl"), new Cosmetic("Computron 5000"), new Cosmetic("Gruesome Gourd"), new Cosmetic("Festive Cover-Up") )); } /** * Generates random weapons and weapon restrictions for the bot */ @Override protected void generateRandomWeapons() { weaponRestrictions = RandomizerPresets.getWeaponRestrictionForRandomSpy(); primaryWeapon = PopRandomizer.randomElement(primaryWeaponList); meleeWeapon = PopRandomizer.randomElement(meleeWeaponList); addWeapon(primaryWeapon); addWeapon(meleeWeapon); adjustWeaponAttributesForCustomBots(); fixClassNameDueToRandomProjectileType(); } /** * Gets the main weapon the spy will use - they default to melee and never have a secondary */ @Override protected Weapon getMainWeapon() { switch(weaponRestrictions) { case PRIMARY_ONLY: return primaryWeapon; default: return meleeWeapon; } } }
CombineSlayer24/MVM-Randomizer
src/Pop/Bot/RandomSpy.java
1,667
//new HitscanWeapon("TTG Sam Revolver", "Sam Revolver"), // In skins
line_comment
nl
package Pop.Bot; import Pop.Bot.Cosmetics.Cosmetic; import Pop.Bot.Weapons.*; import Pop.Enums.TFClasses; import Pop.PopRandomizer; import Pop.RandomizerPresets; import java.util.*; /** * Represents a randomly generated spy */ public class RandomSpy extends RandomBot { /** * Constructor */ public RandomSpy() { tfClass = TFClasses.SPY; baseHealth = 125; primaryWeaponList = new ArrayList<>(Arrays.asList( new HitscanWeapon("Upgradeable TF_WEAPON_REVOLVER", "Revolver"), //new HitscanWeapon("Festive Revolver 2014", "Festive Revolver"), // In skins //new HitscanWeapon("TTG<SUF> new HitscanWeapon("The Ambassador"), //new HitscanWeapon("Festive Ambassador"), // In skins new HitscanWeapon("L'Etranger"), new HitscanWeapon("The Enforcer"), new HitscanWeapon("The Diamondback") )); secondaryWeaponList = new ArrayList<>( // Spies cannot have sappers or it crashes! // Arrays.asList( // "Upgradeable TF_WEAPON_BUILDER_SPY", // "The Red-Tape Recorder", // "The Ap-Sap", // "Festive Sapper", // "The Snack Attack") ); meleeWeaponList = new ArrayList<>(Arrays.asList( new Weapon("Upgradeable TF_WEAPON_KNIFE", "Knife"), //new Weapon("Festive Knife 2011", "Festive Knife"), // In skins //new Weapon("The Sharp Dresser"), // In skins //new Weapon("The Black Rose"), // In skins new Weapon("Your Eternal Reward"), // new Weapon("The Wanga Prick"), // In skins new Weapon("Conniver's Kunai"), new Weapon("The Big Earner"), new Weapon("The Spy-cicle") // "Gold Frying Pan", // "Prinny Machete", // "Saxxy") )); classOnlyCosmetics = new ArrayList<>(Arrays.asList( new Cosmetic("Fancy Fedora"), new Cosmetic("Backbiter's Billycock"), new Cosmetic("Camera Beard"), new Cosmetic("Spy Noble Hair", "Nobled Haired"), new Cosmetic("Spy Beret", "Beret"), new Cosmetic("The Familiar Fez"), new Cosmetic("Detective Noir"), new Cosmetic("Le Party Phantom"), new Cosmetic("Spy Oni Mask"), new Cosmetic("Charmer's Chapeau"), new Cosmetic("Private Eye"), new Cosmetic("Janissary Hat"), new Cosmetic("Cosa Nostra Cap"), new Cosmetic("Belltower Spec Ops"), new Cosmetic("The Counterfeit Billycock"), new Cosmetic("L'Inspecteur"), new Cosmetic("The Spectre's Spectacles"), new Cosmetic("Griffin's Gog"), new Cosmetic("Under Cover"), new Cosmetic("The Doublecross-Comm"), new Cosmetic("The Ninja Cowl"), new Cosmetic("The Stealth Steeler"), new Cosmetic("Hat of Cards"), new Cosmetic("The Scarecrow"), new Cosmetic("The Dapper Disguise"), new Cosmetic("The Bloodhound"), new Cosmetic("Base Metal Billycock", "Metal Billycock"), new Cosmetic("Bootleg Base Metal Billycock", "Bootleg Billycock"), new Cosmetic("The Megapixel Beard"), new Cosmetic("The Pom-Pommed Provocateur"), new Cosmetic("The Belgian Detective"), new Cosmetic("The Harmburg"), new Cosmetic("The Macho Mann"), new Cosmetic("L'homme Burglerre"), new Cosmetic("The Candyman's Cap"), new Cosmetic("The Hyperbaric Bowler"), new Cosmetic("Ethereal Hood"), new Cosmetic("The Napoleon Complex"), new Cosmetic("The Deep Cover Operator"), new Cosmetic("The Aviator Assassin"), new Cosmetic("Facepeeler"), new Cosmetic("Nightmare Hunter"), new Cosmetic("Rogue's Rabbit"), new Cosmetic("Shadowman's Shade"), new Cosmetic("The Graylien"), new Cosmetic("Teufort Knight"), new Cosmetic("A Hat to Kill For"), new Cosmetic("The Dead Head"), new Cosmetic("Big Topper"), new Cosmetic("Brain-Warming Wear"), new Cosmetic("Reader's Choice"), new Cosmetic("The Upgrade"), new Cosmetic("Aristotle"), new Cosmetic("Murderer's Motif"), new Cosmetic("Harry"), new Cosmetic("Shutterbug"), new Cosmetic("Avian Amante"), new Cosmetic("Voodoo Vizier"), new Cosmetic("Bird's Eye Viewer"), new Cosmetic("Crabe de Chapeau"), new Cosmetic("Particulate Protector"), new Cosmetic("Crustaceous Cowl"), new Cosmetic("Computron 5000"), new Cosmetic("Gruesome Gourd"), new Cosmetic("Festive Cover-Up") )); } /** * Generates random weapons and weapon restrictions for the bot */ @Override protected void generateRandomWeapons() { weaponRestrictions = RandomizerPresets.getWeaponRestrictionForRandomSpy(); primaryWeapon = PopRandomizer.randomElement(primaryWeaponList); meleeWeapon = PopRandomizer.randomElement(meleeWeaponList); addWeapon(primaryWeapon); addWeapon(meleeWeapon); adjustWeaponAttributesForCustomBots(); fixClassNameDueToRandomProjectileType(); } /** * Gets the main weapon the spy will use - they default to melee and never have a secondary */ @Override protected Weapon getMainWeapon() { switch(weaponRestrictions) { case PRIMARY_ONLY: return primaryWeapon; default: return meleeWeapon; } } }
22393_3
package steps.gui.openforms; import com.microsoft.playwright.Locator; import com.microsoft.playwright.Page; import com.microsoft.playwright.options.WaitForSelectorState; import pages.openforms.GeneriekeOpenformsPage; import pages.openforms.OpenFormsPage; import steps.gui.GeneriekeSteps; import steps.gui.login.DigidLoginSteps; import users.User; import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; public class OpenFormsSteps extends GeneriekeSteps { public final OpenFormsPage openFormsPage; protected final GeneriekeOpenformsPage genericPage; protected final DigidLoginSteps digidLoginSteps; public OpenFormsSteps(Page page) { super(page); openFormsPage = new OpenFormsPage(page); genericPage = new GeneriekeOpenformsPage(page); digidLoginSteps = new DigidLoginSteps(page); } public void navigate(String url){ page.navigate(url); } /** * Login via Digid * * @param user User */ public void login_via_digid(User user) { openFormsPage.buttonAccepteerCookies.click(); openFormsPage.inloggenDigidButton.click(); digidLoginSteps.login_via_digid(user); } /** * Valideer dat de stap als actief staat * * @param stapNaam die actief moet zijn */ public void valideer_actieve_stap(String stapNaam) { assertThat(openFormsPage.linkActiveStep).hasText(stapNaam); } /** * Valideer dat een bepaalde h1 header op het scherm staat * @param tekst */ public void controleer_h1_header_is(String tekst) { assertThat(openFormsPage.textlabelHeaderH1).hasText(tekst); } /** * Valideer dat een bepaalde h2 header op het scherm staat * @param tekst */ public void controleer_h2_header_is(String tekst) { assertThat(openFormsPage.textlabelHeaderH2).hasText(tekst); } /** * Valideer dat er een bepaalde foutmelding op het scherm staat * * @param tekst */ public void controleer_foutmelding_is_zichtbaar_met(String tekst) { assertThat(get_alert().getByText(tekst)).isVisible(); } /** * Haal de Locator op van een tekst op het scherm * * @param tekst * @return Locator waarop een actie uitgevoerd kan worden */ public Locator get_tekst(String tekst){ return page.getByText(tekst); } /** * Haal de Locator van een inputveld op * * @param tekst * @return Locator waarop een actie uitgevoerd kan worden */ public Locator get_input_veld(String tekst){ return genericPage.getInputField(tekst, false); } /** * Haal de Locator van een alert op * * @return Locator waarop een actie uitgevoerd kan worden */ public Locator get_alert(){ return page.locator("//div[contains(@role,'alert')]//div"); } /** * Valideer dat er geen foutmelding zichtbaar is op het scherm * */ public void geen_foutmelding_zichtbaar() { assertThat(page.locator("//div[@class='form-text error']")).isHidden(); } /** * Valideer dat een bepaald veld de goede waarde heeft * * @param inputName * @param prefillWaarde */ public void tekstveld_bevat_prefill_gegevens (String inputName, String prefillWaarde) { assertThat( page.locator( String.format("//input[@name='%s' and contains(@value,\"%s\")]", inputName, prefillWaarde))) .isVisible(); } /** * Valideer dat er een bepaalde foutmelding getoond wordt op het scherm * * @param locator * @param verwachteTekst */ public void validatie_toon_foutmelding(Locator locator, String verwachteTekst) { locator.blur(); locator.waitFor(new Locator.WaitForOptions().setTimeout(1000)); page.keyboard().press("Enter"); page.keyboard().press("Tab"); if (verwachteTekst == null) { geen_foutmelding_zichtbaar(); } else { controleer_foutmelding_is_zichtbaar_met(verwachteTekst); } } /** * Klik op de volgende knop * */ public void klik_volgende_knop() { wacht_op_volgende_knop_response(); klik_knop("Volgende"); } /** * Wacht totdat de validatie in de backend is uitgevoerd * */ public void wacht_op_volgende_knop_response(){ try{ page.setDefaultTimeout(2000); page.waitForResponse(res -> res.url().contains("/_check_logic"), () -> {}); } catch (Exception ex) { //ignore } finally { page.setDefaultTimeout(30000); } } /** * Haal de Locator op van de checkbox * * @param tekst * @return Locator waarop een actie uitgevoerd kan worden */ public Locator get_checkbox(String tekst){ return genericPage.getCheckbox(tekst); } /** * Selecteer een optie bij een radiobox of checkboxgroup * * @param tekst van de radio- of checkboxgroep * @param optie die geselecteerd moet worden */ public void selecteer_optie(String tekst, String optie) { genericPage.selectOption(tekst, optie); } /** * * Note that this only works on input and textarea fields * * @param veld - text of the field you want to enter the text for * @param text - text you want to enter into the field */ public void vul_tekst_in(String veld, String text) { genericPage.getInputField(veld, false).waitFor(new Locator.WaitForOptions().setTimeout(500)); genericPage.fillTextInputField(veld, text, false); } public void selecteer_login_met_digid() { openFormsPage.inloggenDigidButton.click(); } public void is_ingelogd() { openFormsPage.headerFirstFormStep.waitFor(); } public void waitUntilHeaderPageVisible() { this.openFormsPage.headerFirstFormStep.waitFor(); } public void aanvraag_zonder_DigiD_login(){ openFormsPage.aanvraagZonderDigidButton.click(); } }
CommonGround-Testing/zgw-playwright-base
src/main/java/steps/gui/openforms/OpenFormsSteps.java
1,976
/** * Valideer dat een bepaalde h2 header op het scherm staat * @param tekst */
block_comment
nl
package steps.gui.openforms; import com.microsoft.playwright.Locator; import com.microsoft.playwright.Page; import com.microsoft.playwright.options.WaitForSelectorState; import pages.openforms.GeneriekeOpenformsPage; import pages.openforms.OpenFormsPage; import steps.gui.GeneriekeSteps; import steps.gui.login.DigidLoginSteps; import users.User; import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; public class OpenFormsSteps extends GeneriekeSteps { public final OpenFormsPage openFormsPage; protected final GeneriekeOpenformsPage genericPage; protected final DigidLoginSteps digidLoginSteps; public OpenFormsSteps(Page page) { super(page); openFormsPage = new OpenFormsPage(page); genericPage = new GeneriekeOpenformsPage(page); digidLoginSteps = new DigidLoginSteps(page); } public void navigate(String url){ page.navigate(url); } /** * Login via Digid * * @param user User */ public void login_via_digid(User user) { openFormsPage.buttonAccepteerCookies.click(); openFormsPage.inloggenDigidButton.click(); digidLoginSteps.login_via_digid(user); } /** * Valideer dat de stap als actief staat * * @param stapNaam die actief moet zijn */ public void valideer_actieve_stap(String stapNaam) { assertThat(openFormsPage.linkActiveStep).hasText(stapNaam); } /** * Valideer dat een bepaalde h1 header op het scherm staat * @param tekst */ public void controleer_h1_header_is(String tekst) { assertThat(openFormsPage.textlabelHeaderH1).hasText(tekst); } /** * Valideer dat een<SUF>*/ public void controleer_h2_header_is(String tekst) { assertThat(openFormsPage.textlabelHeaderH2).hasText(tekst); } /** * Valideer dat er een bepaalde foutmelding op het scherm staat * * @param tekst */ public void controleer_foutmelding_is_zichtbaar_met(String tekst) { assertThat(get_alert().getByText(tekst)).isVisible(); } /** * Haal de Locator op van een tekst op het scherm * * @param tekst * @return Locator waarop een actie uitgevoerd kan worden */ public Locator get_tekst(String tekst){ return page.getByText(tekst); } /** * Haal de Locator van een inputveld op * * @param tekst * @return Locator waarop een actie uitgevoerd kan worden */ public Locator get_input_veld(String tekst){ return genericPage.getInputField(tekst, false); } /** * Haal de Locator van een alert op * * @return Locator waarop een actie uitgevoerd kan worden */ public Locator get_alert(){ return page.locator("//div[contains(@role,'alert')]//div"); } /** * Valideer dat er geen foutmelding zichtbaar is op het scherm * */ public void geen_foutmelding_zichtbaar() { assertThat(page.locator("//div[@class='form-text error']")).isHidden(); } /** * Valideer dat een bepaald veld de goede waarde heeft * * @param inputName * @param prefillWaarde */ public void tekstveld_bevat_prefill_gegevens (String inputName, String prefillWaarde) { assertThat( page.locator( String.format("//input[@name='%s' and contains(@value,\"%s\")]", inputName, prefillWaarde))) .isVisible(); } /** * Valideer dat er een bepaalde foutmelding getoond wordt op het scherm * * @param locator * @param verwachteTekst */ public void validatie_toon_foutmelding(Locator locator, String verwachteTekst) { locator.blur(); locator.waitFor(new Locator.WaitForOptions().setTimeout(1000)); page.keyboard().press("Enter"); page.keyboard().press("Tab"); if (verwachteTekst == null) { geen_foutmelding_zichtbaar(); } else { controleer_foutmelding_is_zichtbaar_met(verwachteTekst); } } /** * Klik op de volgende knop * */ public void klik_volgende_knop() { wacht_op_volgende_knop_response(); klik_knop("Volgende"); } /** * Wacht totdat de validatie in de backend is uitgevoerd * */ public void wacht_op_volgende_knop_response(){ try{ page.setDefaultTimeout(2000); page.waitForResponse(res -> res.url().contains("/_check_logic"), () -> {}); } catch (Exception ex) { //ignore } finally { page.setDefaultTimeout(30000); } } /** * Haal de Locator op van de checkbox * * @param tekst * @return Locator waarop een actie uitgevoerd kan worden */ public Locator get_checkbox(String tekst){ return genericPage.getCheckbox(tekst); } /** * Selecteer een optie bij een radiobox of checkboxgroup * * @param tekst van de radio- of checkboxgroep * @param optie die geselecteerd moet worden */ public void selecteer_optie(String tekst, String optie) { genericPage.selectOption(tekst, optie); } /** * * Note that this only works on input and textarea fields * * @param veld - text of the field you want to enter the text for * @param text - text you want to enter into the field */ public void vul_tekst_in(String veld, String text) { genericPage.getInputField(veld, false).waitFor(new Locator.WaitForOptions().setTimeout(500)); genericPage.fillTextInputField(veld, text, false); } public void selecteer_login_met_digid() { openFormsPage.inloggenDigidButton.click(); } public void is_ingelogd() { openFormsPage.headerFirstFormStep.waitFor(); } public void waitUntilHeaderPageVisible() { this.openFormsPage.headerFirstFormStep.waitFor(); } public void aanvraag_zonder_DigiD_login(){ openFormsPage.aanvraagZonderDigidButton.click(); } }
97448_1
package cn.tencent.DiscuzMob.ui.adapter; import android.app.Activity; import android.content.Intent; import android.text.Html; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.squareup.okhttp.CacheControl; import com.squareup.okhttp.Callback; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList; import java.util.List; import cn.tencent.DiscuzMob.base.RedNetApp; import cn.tencent.DiscuzMob.db.Modal; import cn.tencent.DiscuzMob.model.ForumThreadlistBean; import cn.tencent.DiscuzMob.ui.activity.VoteThreadDetailsActivity; import cn.tencent.DiscuzMob.utils.ImageDisplay; import cn.tencent.DiscuzMob.utils.LogUtils; import cn.tencent.DiscuzMob.utils.StringUtil; import cn.tencent.DiscuzMob.widget.AsyncRoundedImageView; import cn.tencent.DiscuzMob.base.RedNet; import cn.tencent.DiscuzMob.model.MythreadBean; import cn.tencent.DiscuzMob.net.AppNetConfig; import cn.tencent.DiscuzMob.ui.activity.ActivityThreadDetailsActivity; import cn.tencent.DiscuzMob.ui.activity.ThreadDetailsActivity; import cn.tencent.DiscuzMob.ui.activity.UserDetailActivity; import cn.tencent.DiscuzMob.utils.RednetUtils; import cn.tencent.DiscuzMob.R; import de.hdodenhof.circleimageview.CircleImageView; /** * Created by cg on 2017/7/17. */ public class MythreadsAdapter extends BaseAdapter { private List<MythreadBean.VariablesBean.ListBean> list; private String url; private Activity activity; private String tag; private ArrayList<String> tids; private boolean isAdd = false; public MythreadsAdapter(Activity activity) { this.activity = activity; } public void setData(List<MythreadBean.VariablesBean.ListBean> list) { this.list = list; notifyDataSetChanged(); } public void setTag(String tag) { this.tag = tag; } public void appendData(List<MythreadBean.VariablesBean.ListBean> list) { if (this.list != null) { this.list.addAll(list); } else { this.list = list; } notifyDataSetChanged(); } public void cleanData() { if (list != null) { list.clear(); notifyDataSetChanged(); } } @Override public int getCount() { return list == null ? 0 : list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } public void getUrl(String ucenterurl) { this.url = ucenterurl; } @Override public View getView(final int position, View convertView, final ViewGroup parent) { ViewHolder viewHolder; if (convertView == null) { viewHolder = new ViewHolder(); convertView = View.inflate(parent.getContext(), R.layout.my_thread, null); viewHolder.avatar = (CircleImageView) convertView.findViewById(R.id.avatar); viewHolder.tv_dateline = (TextView) convertView.findViewById(R.id.tv_dateline); viewHolder.tv_note = (TextView) convertView.findViewById(R.id.tv_note); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } String dateSub = RednetUtils.getDateSub(list.get(position).getDateline()); viewHolder.tv_dateline.setText(dateSub); ImageDisplay.loadCirimageView(activity,viewHolder.avatar,url + "/avatar.php?uid=" + list.get(position).getAuthorid() + "&size=midden"); // viewHolder.avatar.load(url + "/avatar.php?uid=" + list.get(position).getAuthorid() + "&size=midden"); viewHolder.tv_note.setText(Html.fromHtml(list.get(position).getNote())); viewHolder.avatar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!list.get(position).getAuthorid().equals(RedNetApp.getInstance().getUid())) { Intent intent = new Intent(activity, UserDetailActivity.class); intent.putExtra("userId", list.get(position).getUid()); activity.startActivity(intent); } } }); convertView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { LogUtils.i(list.get(position).getNotevar()+" aaaaaaaa"); if (list.get(position).getNotevar()!=null) { final String tid = list.get(position).getNotevar().getTid(); long count = Modal.getInstance().getUserAccountDao().getCount(); List<ForumThreadlistBean> data = Modal.getInstance().getUserAccountDao().getScrollData(0, count); if (null != data) { if (data.size() > 0) { tids = new ArrayList<String>(); for (int i = 0; i < data.size(); i++) { String tid1 = data.get(i).getTid(); tids.add(tid1); } if (!tids.contains(tid)) { isAdd = true; } else { isAdd = false; } } else { isAdd = true; } } else { isAdd = false; } RedNet.mHttpClient.newCall(new Request.Builder() .url(AppNetConfig.BASEURL + "?module=viewthread&tid=" + tid + "&submodule=checkpost&version=5&page=1" + "&width=360&height=480&checkavatar=1&submodule=checkpost") .cacheControl(new CacheControl.Builder().noStore().noCache().build()).build()) .enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { // mHandler.sendEmptyMessage(-10001); // page = Math.max(1, --page); } @Override public void onResponse(Response response) throws IOException { try { JSONObject json = new JSONObject(response.body().string()); JSONObject jsonObject = json.getJSONObject("Variables").getJSONObject("thread"); String special = jsonObject.getString("special"); String fid = jsonObject.getString("fid"); if (isAdd == true) { ForumThreadlistBean forumThreadlistBean = new ForumThreadlistBean(); forumThreadlistBean.setAuthor(list.get(position).getAuthor()); forumThreadlistBean.setAvatar(url + "/avatar.php?uid=" + list.get(position).getAuthorid() + "&size=midden"); forumThreadlistBean.setTid(tid); forumThreadlistBean.setSpecial(special); forumThreadlistBean.setSubject(jsonObject.getString("subject")); forumThreadlistBean.setViews(jsonObject.getString("views")); forumThreadlistBean.setReplies(jsonObject.getString("replies")); forumThreadlistBean.setDateline(jsonObject.getString("dateline")); forumThreadlistBean.setRecommend_add(jsonObject.getString("recommend_add")); forumThreadlistBean.setDigest(jsonObject.getString("digest")); forumThreadlistBean.setDisplayorder(jsonObject.getString("displayorder")); forumThreadlistBean.setImglist(null); forumThreadlistBean.setLevel(""); Modal.getInstance().getUserAccountDao().addAccount(forumThreadlistBean); } Class claz; special = TextUtils.isEmpty(special) ? "0" : special; if ("1".equals(special)) { claz = VoteThreadDetailsActivity.class; } else if ("4".equals(special)) { claz = ActivityThreadDetailsActivity.class; } else { claz = ThreadDetailsActivity.class; } Intent intent = new Intent(parent.getContext(), claz); intent.putExtra("id", tid); intent.putExtra("title", ""); intent.putExtra("fid", fid); parent.getContext().startActivity(intent); } catch (JSONException e) { e.printStackTrace(); } } }); } } }); return convertView; } class ViewHolder { private CircleImageView avatar; private TextView tv_dateline; private TextView tv_note; } }
Comsenz/Discuz-Android
app/src/main/java/cn/tencent/DiscuzMob/ui/adapter/MythreadsAdapter.java
2,762
// viewHolder.avatar.load(url + "/avatar.php?uid=" + list.get(position).getAuthorid() + "&size=midden");
line_comment
nl
package cn.tencent.DiscuzMob.ui.adapter; import android.app.Activity; import android.content.Intent; import android.text.Html; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.squareup.okhttp.CacheControl; import com.squareup.okhttp.Callback; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList; import java.util.List; import cn.tencent.DiscuzMob.base.RedNetApp; import cn.tencent.DiscuzMob.db.Modal; import cn.tencent.DiscuzMob.model.ForumThreadlistBean; import cn.tencent.DiscuzMob.ui.activity.VoteThreadDetailsActivity; import cn.tencent.DiscuzMob.utils.ImageDisplay; import cn.tencent.DiscuzMob.utils.LogUtils; import cn.tencent.DiscuzMob.utils.StringUtil; import cn.tencent.DiscuzMob.widget.AsyncRoundedImageView; import cn.tencent.DiscuzMob.base.RedNet; import cn.tencent.DiscuzMob.model.MythreadBean; import cn.tencent.DiscuzMob.net.AppNetConfig; import cn.tencent.DiscuzMob.ui.activity.ActivityThreadDetailsActivity; import cn.tencent.DiscuzMob.ui.activity.ThreadDetailsActivity; import cn.tencent.DiscuzMob.ui.activity.UserDetailActivity; import cn.tencent.DiscuzMob.utils.RednetUtils; import cn.tencent.DiscuzMob.R; import de.hdodenhof.circleimageview.CircleImageView; /** * Created by cg on 2017/7/17. */ public class MythreadsAdapter extends BaseAdapter { private List<MythreadBean.VariablesBean.ListBean> list; private String url; private Activity activity; private String tag; private ArrayList<String> tids; private boolean isAdd = false; public MythreadsAdapter(Activity activity) { this.activity = activity; } public void setData(List<MythreadBean.VariablesBean.ListBean> list) { this.list = list; notifyDataSetChanged(); } public void setTag(String tag) { this.tag = tag; } public void appendData(List<MythreadBean.VariablesBean.ListBean> list) { if (this.list != null) { this.list.addAll(list); } else { this.list = list; } notifyDataSetChanged(); } public void cleanData() { if (list != null) { list.clear(); notifyDataSetChanged(); } } @Override public int getCount() { return list == null ? 0 : list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } public void getUrl(String ucenterurl) { this.url = ucenterurl; } @Override public View getView(final int position, View convertView, final ViewGroup parent) { ViewHolder viewHolder; if (convertView == null) { viewHolder = new ViewHolder(); convertView = View.inflate(parent.getContext(), R.layout.my_thread, null); viewHolder.avatar = (CircleImageView) convertView.findViewById(R.id.avatar); viewHolder.tv_dateline = (TextView) convertView.findViewById(R.id.tv_dateline); viewHolder.tv_note = (TextView) convertView.findViewById(R.id.tv_note); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } String dateSub = RednetUtils.getDateSub(list.get(position).getDateline()); viewHolder.tv_dateline.setText(dateSub); ImageDisplay.loadCirimageView(activity,viewHolder.avatar,url + "/avatar.php?uid=" + list.get(position).getAuthorid() + "&size=midden"); // viewHolder.avatar.load(url +<SUF> viewHolder.tv_note.setText(Html.fromHtml(list.get(position).getNote())); viewHolder.avatar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!list.get(position).getAuthorid().equals(RedNetApp.getInstance().getUid())) { Intent intent = new Intent(activity, UserDetailActivity.class); intent.putExtra("userId", list.get(position).getUid()); activity.startActivity(intent); } } }); convertView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { LogUtils.i(list.get(position).getNotevar()+" aaaaaaaa"); if (list.get(position).getNotevar()!=null) { final String tid = list.get(position).getNotevar().getTid(); long count = Modal.getInstance().getUserAccountDao().getCount(); List<ForumThreadlistBean> data = Modal.getInstance().getUserAccountDao().getScrollData(0, count); if (null != data) { if (data.size() > 0) { tids = new ArrayList<String>(); for (int i = 0; i < data.size(); i++) { String tid1 = data.get(i).getTid(); tids.add(tid1); } if (!tids.contains(tid)) { isAdd = true; } else { isAdd = false; } } else { isAdd = true; } } else { isAdd = false; } RedNet.mHttpClient.newCall(new Request.Builder() .url(AppNetConfig.BASEURL + "?module=viewthread&tid=" + tid + "&submodule=checkpost&version=5&page=1" + "&width=360&height=480&checkavatar=1&submodule=checkpost") .cacheControl(new CacheControl.Builder().noStore().noCache().build()).build()) .enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { // mHandler.sendEmptyMessage(-10001); // page = Math.max(1, --page); } @Override public void onResponse(Response response) throws IOException { try { JSONObject json = new JSONObject(response.body().string()); JSONObject jsonObject = json.getJSONObject("Variables").getJSONObject("thread"); String special = jsonObject.getString("special"); String fid = jsonObject.getString("fid"); if (isAdd == true) { ForumThreadlistBean forumThreadlistBean = new ForumThreadlistBean(); forumThreadlistBean.setAuthor(list.get(position).getAuthor()); forumThreadlistBean.setAvatar(url + "/avatar.php?uid=" + list.get(position).getAuthorid() + "&size=midden"); forumThreadlistBean.setTid(tid); forumThreadlistBean.setSpecial(special); forumThreadlistBean.setSubject(jsonObject.getString("subject")); forumThreadlistBean.setViews(jsonObject.getString("views")); forumThreadlistBean.setReplies(jsonObject.getString("replies")); forumThreadlistBean.setDateline(jsonObject.getString("dateline")); forumThreadlistBean.setRecommend_add(jsonObject.getString("recommend_add")); forumThreadlistBean.setDigest(jsonObject.getString("digest")); forumThreadlistBean.setDisplayorder(jsonObject.getString("displayorder")); forumThreadlistBean.setImglist(null); forumThreadlistBean.setLevel(""); Modal.getInstance().getUserAccountDao().addAccount(forumThreadlistBean); } Class claz; special = TextUtils.isEmpty(special) ? "0" : special; if ("1".equals(special)) { claz = VoteThreadDetailsActivity.class; } else if ("4".equals(special)) { claz = ActivityThreadDetailsActivity.class; } else { claz = ThreadDetailsActivity.class; } Intent intent = new Intent(parent.getContext(), claz); intent.putExtra("id", tid); intent.putExtra("title", ""); intent.putExtra("fid", fid); parent.getContext().startActivity(intent); } catch (JSONException e) { e.printStackTrace(); } } }); } } }); return convertView; } class ViewHolder { private CircleImageView avatar; private TextView tv_dateline; private TextView tv_note; } }
42137_0
package com.jie.befamiliewijzer.config; /* CORS (Cross Origin Resource Sharing is een instelling die zorgt dat de frontend en de backend met elkaar kunnen communiceren ondanks dat ze op verschillende poorten opereren (b.v. localhost:3000 en localhost:8080). De globale cors configuratie zorgt dat je niet boven elke klasse @CrossOrigin hoeft te zetten. In deze applictie staat alsnog wel boven elke klasse ter demonstratie. Vergeet niet om in de security config ook de ".cors()" optie aan te zetten. */ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class GlobalCorsConfiguration { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"); } }; } }
ConradJie/be-familie-wijzer
src/main/java/com/jie/befamiliewijzer/config/GlobalCorsConfiguration.java
335
/* CORS (Cross Origin Resource Sharing is een instelling die zorgt dat de frontend en de backend met elkaar kunnen communiceren ondanks dat ze op verschillende poorten opereren (b.v. localhost:3000 en localhost:8080). De globale cors configuratie zorgt dat je niet boven elke klasse @CrossOrigin hoeft te zetten. In deze applictie staat alsnog wel boven elke klasse ter demonstratie. Vergeet niet om in de security config ook de ".cors()" optie aan te zetten. */
block_comment
nl
package com.jie.befamiliewijzer.config; /* CORS (Cross Origin<SUF>*/ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class GlobalCorsConfiguration { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"); } }; } }
197220_0
package modules; import java.util.Arrays; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Objects; import java.util.StringJoiner; import java.util.function.Consumer; import java.util.function.Predicate; public class TabellListe<T> implements Liste<T> { private T[] a; private int antall; private int endringer; public TabellListe(int størrelse) // konstruktør { @SuppressWarnings("unchecked") // pga. konverteringen: Object[] -> T[] T[] b = (T[]) new Object[størrelse]; // oppretter tabellen a = b; antall = 0; // foreløpig ingen verdier endringer = 0; // foreløpig ingen endringer } public TabellListe() // standardkonstruktør { this(10); // startstørrelse på 10 } public TabellListe(T[] b) // en T-tabell som parameter { this(b.length); // kaller en konstruktør for (T verdi : b) { if (verdi != null) a[antall++] = verdi; // hopper over null-verdier } } private static void fratilKontroll(int antall, int fra, int til) { if (fra < 0) // fra er negativ throw new IndexOutOfBoundsException ("fra(" + fra + ") er negativ!"); if (til > antall) // til er utenfor tabellen throw new IndexOutOfBoundsException ("til(" + til + ") > antall(" + antall + ")"); if (fra > til) // fra er større enn til throw new IllegalArgumentException ("fra(" + fra + ") > til(" + til + ") - illegalt intervall!"); } public Liste<T> subliste(int fra, int til) { fratilKontroll(antall, fra, til); TabellListe<T> liste = new TabellListe<>(til - fra); for (int i = fra, j = 0; i < til; i++, j++) liste.a[j] = a[i]; liste.antall = til - fra; return liste; } @Override public boolean leggInn(T verdi) // inn bakerst { Objects.requireNonNull(verdi, "null er ulovlig!"); // En full tabell utvides med 50% if (antall == a.length) { a = Arrays.copyOf(a,(3*antall)/2 + 1); } a[antall++] = verdi; // setter inn ny verdi endringer++; return true; } @Override public void leggInn(int indeks, T verdi) { Objects.requireNonNull(verdi, "null er ulovlig!"); indeksKontroll(indeks, true); // true: indeks = antall er lovlig // En full tabell utvides med 50% if (antall == a.length) a = Arrays.copyOf(a,(3*antall)/2 + 1); // rydder plass til den nye verdien for (int i = antall; i > indeks; i--) a[i] = a[i-1]; a[indeks] = verdi; // setter inn ny verdi antall++; // en ny verdi endringer++; // en endring } @Override public int antall() { return antall; // returnerer antallet } @Override public boolean tom() { return antall == 0; // listen er tom hvis antall er 0 } @Override public T hent(int indeks) { indeksKontroll(indeks, false); // false: indeks = antall er ulovlig return a[indeks]; // returnerer er tabellelement } @Override public int indeksTil(T verdi) { for (int i = 0; i < antall; i++) { if (a[i].equals(verdi)) return i; // funnet! } return -1; // ikke funnet! } @Override public boolean inneholder(T verdi) { return indeksTil(verdi) != -1; } @Override public T oppdater(int indeks, T verdi) { Objects.requireNonNull(verdi, "null er ulovlig!"); indeksKontroll(indeks, false); // false: indeks = antall er ulovlig T gammelverdi = a[indeks]; // tar vare på den gamle verdien a[indeks] = verdi; // oppdaterer endringer++; // en endring return gammelverdi; // returnerer den gamle verdien } @Override public T fjern(int indeks) { indeksKontroll(indeks, false); // false: indeks = antall er ulovlig T verdi = a[indeks]; antall--; // reduserer antallet // sletter ved å flytte verdier mot venstre for (int i = indeks; i < antall; i++) a[i] = a[i + 1]; a[antall] = null; // tilrettelegger for "søppeltømming" endringer++; return verdi; } @Override public boolean fjern(T verdi) { Objects.requireNonNull(verdi, "null er ulovlig!"); for (int i = 0; i < antall; i++) { if (a[i].equals(verdi)) { antall--; // reduserer antallet // sletter ved å flytte verdier mot venstre for (int j = i; j < antall; j++) a[j] = a[j + 1]; a[antall] = null; // tilrettelegger for "søppeltømming" endringer++; return true; // vellykket fjerning } } return false; // ingen fjerning } @Override public boolean fjernHvis(Predicate<? super T> p) // betingelsesfjerning { Objects.requireNonNull(p, "predikatet er null"); // kaster unntak int nyttAntall = antall; for (int i = 0, j = 0; j < antall; j++) { if (p.test(a[j])) nyttAntall--; // a[j] skal fjernes else a[i++] = a[j]; // forskyver } for (int i = nyttAntall; i < antall; i++) { a[i] = null; // tilrettelegger for "søppeltømming" } boolean fjernet = nyttAntall < antall; if (fjernet) endringer++; antall = nyttAntall; return fjernet; } @Override @SuppressWarnings("unchecked") public void nullstill() { if (a.length > 10) a = (T[])new Object[10]; else for (int i = 0; i < antall; i++) { a[i] = null; } antall = 0; endringer++; } public String toString2() { StringBuilder s = new StringBuilder("["); if (!tom()) { s.append(a[0]); for (int i = 1; i < antall; i++) { s.append(',').append(' ').append(a[i]); } } s.append(']'); return s.toString(); } @Override public String toString() { StringJoiner s = new StringJoiner(", ","[","]"); for (int i = 0; i < antall; i++) s.add(a[i].toString()); return s.toString(); } @SuppressWarnings("unchecked") public <T> T[] tilTabell(T[] b) { if (b.length < antall) return (T[]) Arrays.copyOf(a, antall, b.getClass()); System.arraycopy(a, 0, b, 0, antall); if (b.length > antall) b[antall] = null; return b; } @Override public void forEach(Consumer<? super T> action) { for (int i = 0; i < antall; i++) { action.accept(a[i]); } } @Override public Iterator<T> iterator() { return new TabellListeIterator(); } private class TabellListeIterator implements Iterator<T> { private int denne; // instansvariabel private boolean fjernOK; // instansvariabel private int iteratorendringer; // instansvariabel private TabellListeIterator() { denne = 0; fjernOK = false; iteratorendringer = endringer; } @Override public boolean hasNext() // sjekker om det er flere igjen { return denne < antall; // sjekker verdien til denne } @Override public T next() { if (iteratorendringer != endringer) { throw new ConcurrentModificationException("Listen er endret!"); } if (!hasNext()) { throw new NoSuchElementException("Tomt eller ingen verdier igjen!"); } T denneverdi = a[denne]; // henter aktuell verdi denne++; // flytter indeksen fjernOK = true; // nå kan remove() kalles return denneverdi; // returnerer verdien } @Override public void forEachRemaining(Consumer<? super T> action) { while (denne < antall) { action.accept(a[denne++]); } } @Override public void remove() { if (iteratorendringer != endringer) throw new ConcurrentModificationException("Listen er endret!"); if (!fjernOK) throw new IllegalStateException("Ulovlig tilstand!"); fjernOK = false; // remove() kan ikke kalles på nytt // verdien i denne - 1 skal fjernes da den ble returnert i siste kall // på next(), verdiene fra og med denne flyttes derfor en mot venstre antall--; // en verdi vil bli fjernet denne--; // denne må flyttes til venstre for (int i = denne; i < antall; i++) a[i] = a[i + 1]; // tetter igjen a[antall] = null; // verdien som lå lengst til høyre nulles endringer++; iteratorendringer++; } } // TabellListeIterator } // TabellListe
ConsiliumB/AlgDat
src/modules/TabellListe.java
3,136
// pga. konverteringen: Object[] -> T[]
line_comment
nl
package modules; import java.util.Arrays; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Objects; import java.util.StringJoiner; import java.util.function.Consumer; import java.util.function.Predicate; public class TabellListe<T> implements Liste<T> { private T[] a; private int antall; private int endringer; public TabellListe(int størrelse) // konstruktør { @SuppressWarnings("unchecked") // pga. konverteringen:<SUF> T[] b = (T[]) new Object[størrelse]; // oppretter tabellen a = b; antall = 0; // foreløpig ingen verdier endringer = 0; // foreløpig ingen endringer } public TabellListe() // standardkonstruktør { this(10); // startstørrelse på 10 } public TabellListe(T[] b) // en T-tabell som parameter { this(b.length); // kaller en konstruktør for (T verdi : b) { if (verdi != null) a[antall++] = verdi; // hopper over null-verdier } } private static void fratilKontroll(int antall, int fra, int til) { if (fra < 0) // fra er negativ throw new IndexOutOfBoundsException ("fra(" + fra + ") er negativ!"); if (til > antall) // til er utenfor tabellen throw new IndexOutOfBoundsException ("til(" + til + ") > antall(" + antall + ")"); if (fra > til) // fra er større enn til throw new IllegalArgumentException ("fra(" + fra + ") > til(" + til + ") - illegalt intervall!"); } public Liste<T> subliste(int fra, int til) { fratilKontroll(antall, fra, til); TabellListe<T> liste = new TabellListe<>(til - fra); for (int i = fra, j = 0; i < til; i++, j++) liste.a[j] = a[i]; liste.antall = til - fra; return liste; } @Override public boolean leggInn(T verdi) // inn bakerst { Objects.requireNonNull(verdi, "null er ulovlig!"); // En full tabell utvides med 50% if (antall == a.length) { a = Arrays.copyOf(a,(3*antall)/2 + 1); } a[antall++] = verdi; // setter inn ny verdi endringer++; return true; } @Override public void leggInn(int indeks, T verdi) { Objects.requireNonNull(verdi, "null er ulovlig!"); indeksKontroll(indeks, true); // true: indeks = antall er lovlig // En full tabell utvides med 50% if (antall == a.length) a = Arrays.copyOf(a,(3*antall)/2 + 1); // rydder plass til den nye verdien for (int i = antall; i > indeks; i--) a[i] = a[i-1]; a[indeks] = verdi; // setter inn ny verdi antall++; // en ny verdi endringer++; // en endring } @Override public int antall() { return antall; // returnerer antallet } @Override public boolean tom() { return antall == 0; // listen er tom hvis antall er 0 } @Override public T hent(int indeks) { indeksKontroll(indeks, false); // false: indeks = antall er ulovlig return a[indeks]; // returnerer er tabellelement } @Override public int indeksTil(T verdi) { for (int i = 0; i < antall; i++) { if (a[i].equals(verdi)) return i; // funnet! } return -1; // ikke funnet! } @Override public boolean inneholder(T verdi) { return indeksTil(verdi) != -1; } @Override public T oppdater(int indeks, T verdi) { Objects.requireNonNull(verdi, "null er ulovlig!"); indeksKontroll(indeks, false); // false: indeks = antall er ulovlig T gammelverdi = a[indeks]; // tar vare på den gamle verdien a[indeks] = verdi; // oppdaterer endringer++; // en endring return gammelverdi; // returnerer den gamle verdien } @Override public T fjern(int indeks) { indeksKontroll(indeks, false); // false: indeks = antall er ulovlig T verdi = a[indeks]; antall--; // reduserer antallet // sletter ved å flytte verdier mot venstre for (int i = indeks; i < antall; i++) a[i] = a[i + 1]; a[antall] = null; // tilrettelegger for "søppeltømming" endringer++; return verdi; } @Override public boolean fjern(T verdi) { Objects.requireNonNull(verdi, "null er ulovlig!"); for (int i = 0; i < antall; i++) { if (a[i].equals(verdi)) { antall--; // reduserer antallet // sletter ved å flytte verdier mot venstre for (int j = i; j < antall; j++) a[j] = a[j + 1]; a[antall] = null; // tilrettelegger for "søppeltømming" endringer++; return true; // vellykket fjerning } } return false; // ingen fjerning } @Override public boolean fjernHvis(Predicate<? super T> p) // betingelsesfjerning { Objects.requireNonNull(p, "predikatet er null"); // kaster unntak int nyttAntall = antall; for (int i = 0, j = 0; j < antall; j++) { if (p.test(a[j])) nyttAntall--; // a[j] skal fjernes else a[i++] = a[j]; // forskyver } for (int i = nyttAntall; i < antall; i++) { a[i] = null; // tilrettelegger for "søppeltømming" } boolean fjernet = nyttAntall < antall; if (fjernet) endringer++; antall = nyttAntall; return fjernet; } @Override @SuppressWarnings("unchecked") public void nullstill() { if (a.length > 10) a = (T[])new Object[10]; else for (int i = 0; i < antall; i++) { a[i] = null; } antall = 0; endringer++; } public String toString2() { StringBuilder s = new StringBuilder("["); if (!tom()) { s.append(a[0]); for (int i = 1; i < antall; i++) { s.append(',').append(' ').append(a[i]); } } s.append(']'); return s.toString(); } @Override public String toString() { StringJoiner s = new StringJoiner(", ","[","]"); for (int i = 0; i < antall; i++) s.add(a[i].toString()); return s.toString(); } @SuppressWarnings("unchecked") public <T> T[] tilTabell(T[] b) { if (b.length < antall) return (T[]) Arrays.copyOf(a, antall, b.getClass()); System.arraycopy(a, 0, b, 0, antall); if (b.length > antall) b[antall] = null; return b; } @Override public void forEach(Consumer<? super T> action) { for (int i = 0; i < antall; i++) { action.accept(a[i]); } } @Override public Iterator<T> iterator() { return new TabellListeIterator(); } private class TabellListeIterator implements Iterator<T> { private int denne; // instansvariabel private boolean fjernOK; // instansvariabel private int iteratorendringer; // instansvariabel private TabellListeIterator() { denne = 0; fjernOK = false; iteratorendringer = endringer; } @Override public boolean hasNext() // sjekker om det er flere igjen { return denne < antall; // sjekker verdien til denne } @Override public T next() { if (iteratorendringer != endringer) { throw new ConcurrentModificationException("Listen er endret!"); } if (!hasNext()) { throw new NoSuchElementException("Tomt eller ingen verdier igjen!"); } T denneverdi = a[denne]; // henter aktuell verdi denne++; // flytter indeksen fjernOK = true; // nå kan remove() kalles return denneverdi; // returnerer verdien } @Override public void forEachRemaining(Consumer<? super T> action) { while (denne < antall) { action.accept(a[denne++]); } } @Override public void remove() { if (iteratorendringer != endringer) throw new ConcurrentModificationException("Listen er endret!"); if (!fjernOK) throw new IllegalStateException("Ulovlig tilstand!"); fjernOK = false; // remove() kan ikke kalles på nytt // verdien i denne - 1 skal fjernes da den ble returnert i siste kall // på next(), verdiene fra og med denne flyttes derfor en mot venstre antall--; // en verdi vil bli fjernet denne--; // denne må flyttes til venstre for (int i = denne; i < antall; i++) a[i] = a[i + 1]; // tetter igjen a[antall] = null; // verdien som lå lengst til høyre nulles endringer++; iteratorendringer++; } } // TabellListeIterator } // TabellListe
165847_28
package com.cw.demo.fingerprint.gaa; //import android.annotation.SuppressLint; //import android.app.Activity; //import android.content.DialogInterface; //import android.hardware.usb.UsbDevice; //import android.hardware.usb.UsbManager; //import android.os.AsyncTask; //import android.os.Bundle; //import android.os.Handler; //import android.support.v7.app.AlertDialog; //import android.text.method.ScrollingMovementMethod; //import android.util.Log; //import android.view.KeyEvent; //import android.view.View; //import android.view.View.OnClickListener; //import android.view.WindowManager; //import android.widget.Button; //import android.widget.ImageView; //import android.widget.ProgressBar; //import android.widget.TextView; //import android.widget.Toast; // //import com.cw.demo.MyApplication; //import com.cw.demo.R; //import com.cw.fpgaasdk.GaaApiBHMDevice; //import com.cw.fpgaasdk.GaaApiBase; //import com.cw.fpgaasdk.GaaFingerFactory; //import com.cw.serialportsdk.USB.USBFingerManager; //import com.cw.serialportsdk.utils.DataUtils; //import com.fm.bio.ID_Fpr; // // //public class NewFpGAAActivity extends Activity implements OnClickListener { public class NewFpGAAActivity{ } // // private static final String TAG = "CwGAAActivity"; // ProgressBar bar; // ImageView fingerImage; // Button capture; // Button enroll; // Button enroll2; // Button search; // Button stop; // Button infos; // Button clear; // TextView msgText; // boolean globalControl = true; // // // public GAA_API mGaaApi; // public GaaApiBase mGaaApi; // // // @SuppressLint("HandlerLeak") // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // Log.i(TAG, "------------onCreate--------------"); // // setContentView(R.layout.fragment_capture_gaa); // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // // initview(); // } // // // @Override // protected void onStart() { // super.onStart(); // Log.i(TAG, "------------onStart--------------"); // open(); // } // // @Override // protected void onResume() { // super.onResume(); // Log.i(TAG, "------------onResume--------------"); // // } // // @Override // protected void onRestart() { // super.onRestart(); // Log.i(TAG, "------------onRestart--------------"); // } // // @Override // protected void onStop() { // super.onStop(); // Log.i(TAG, "------------onStop--------------"); // // close(); // } // // @Override // protected void onDestroy() { // super.onDestroy(); // Log.i(TAG, "------------onDestroy--------------"); // } // // public void initview() { // bar = findViewById(R.id.bar); // fingerImage = findViewById(R.id.fingerImage); // capture = findViewById(R.id.capture); // enroll = findViewById(R.id.enroll); // search = findViewById(R.id.search); // enroll2 = findViewById(R.id.enroll2); // stop = findViewById(R.id.stop); // infos = findViewById(R.id.infos); // clear = findViewById(R.id.clear); // msgText = findViewById(R.id.msg); // msgText.setMovementMethod(ScrollingMovementMethod.getInstance()); // // capture.setOnClickListener(this); // enroll.setOnClickListener(this); // search.setOnClickListener(this); // enroll2.setOnClickListener(this); // stop.setOnClickListener(this); // infos.setOnClickListener(this); // clear.setOnClickListener(this); // } // // private void open() { // MyApplication.getApp().showProgressDialog(this, getString(R.string.fp_usb_init)); // USBFingerManager.getInstance(this).openUSB(new USBFingerManager.OnUSBFingerListener() { // @Override // public void onOpenUSBFingerSuccess(String device, UsbManager usbManager, UsbDevice usbDevice) { // MyApplication.getApp().cancleProgressDialog(); // if (device.equals(GaaApiBase.ZiDevice)) { // //新固件 // mGaaApi = new GaaFingerFactory().createGAAFinger(GaaApiBase.ZiDevice,NewFpGAAActivity.this); // //// mGaaApi = new GAANewAPI(NewFpGAAActivity.this); // int ret = mGaaApi.openGAA(); // if (ret == GaaApiBase.LIVESCAN_SUCCESS) { // updateMsg("open device success 1"); // } else if (ret == GaaApiBase.LIVESCAN_NOTINIT) { // updateMsg("not init"); // } else if (ret == GaaApiBase.LIVESCAN_AUTH_FAILED) { // updateMsg("auth failed"); // } else { // updateMsg("unknown " + ret); // } // // } else if (device.equals(GaaApiBase.BHMDevice)) { // //旧固件 // mGaaApi = new GaaFingerFactory().createGAAFinger(GaaApiBase.BHMDevice,NewFpGAAActivity.this); // // //// mGaaApi = new GAAOldAPI(NewFpGAAActivity.this); // new Handler().postDelayed(new Runnable() { // @Override // public void run() { // int ret = ((GaaApiBHMDevice)mGaaApi).openGAA(); // if (ret == GaaApiBase.LIVESCAN_SUCCESS) { // updateMsg("open device success 2"); // } else if (ret == GaaApiBase.LIVESCAN_NOTINIT) { // updateMsg("not init"); // } else if (ret == GaaApiBase.LIVESCAN_AUTH_FAILED) { // updateMsg("auth failed"); // } else { // String msg = mGaaApi.ErrorInfo(ret); // updateMsg("unknown " + ret); // updateMsg("msg =" + msg); // } // } // },1000); // } else { // updateMsg("开发包和指纹模块不一致! 请联系商务 " + device); //// Toast.makeText(NewFpGAAActivity.this, "device ="+device, Toast.LENGTH_SHORT).show(); // Toast.makeText(NewFpGAAActivity.this, "开发包和指纹模块不一致! 请联系商务", Toast.LENGTH_SHORT).show(); // } // } // // @Override // public void onOpenUSBFingerFailure(String error,int errorCode) { // Log.e(TAG, error); // MyApplication.getApp().cancleProgressDialog(); // Toast.makeText(NewFpGAAActivity.this, error, Toast.LENGTH_SHORT).show(); // } // }); // // } // // private void close() { // btnStatus(true); // globalControl = false; // updateMsg("设备已关闭"); // if (mGaaApi != null) { // mGaaApi.closeGAA(); // } // USBFingerManager.getInstance(this).closeUSB(); // } // // @Override // public void onClick(View v) { // switch (v.getId()) { // case R.id.capture: // globalControl = true; // btnStatus(false); // UpAsyncTask asyncTask_up = new UpAsyncTask(); // asyncTask_up.execute(1); // break; // case R.id.enroll: // btnStatus(false); // // globalControl = true; // ImputAsyncTask asyncTask = new ImputAsyncTask(); // asyncTask.execute(1); // break; // case R.id.enroll2: //// btnStatus(false); //// //// globalControl = true; //// ImputAsyncTask2 asyncTask2 = new ImputAsyncTask2(); //// asyncTask2.execute(1); // break; // case R.id.search: // btnStatus(false); // globalControl = true; // SearchAsyncTask asyncTask_search = new SearchAsyncTask(); // asyncTask_search.execute(1); // break; // case R.id.stop: // btnStatus(true); // globalControl = false; // fingerImage.setImageBitmap(null); // break; // // case R.id.infos: //// getInfos(); // break; // case R.id.clear: // updateMsg(null); // // if (GaaApiBase.LIVESCAN_SUCCESS != mGaaApi.PSEmpty()) { // updateMsg("清空指纹库失败"); // } // updateMsg("清空指纹库成功"); // break; // } // } // // /** // * 采集图片 // */ // @SuppressLint("StaticFieldLeak") // public class UpAsyncTask extends AsyncTask<Integer, String, Integer> { // // @Override // protected Integer doInBackground(Integer... params) { // int ret = 0; // while (true) { // // if (globalControl == false) { // return -1; // } // while (mGaaApi.PSGetImage() != GaaApiBase.LIVESCAN_NO_FINGER) { // if (globalControl == false) { // return -1; // } // publishProgress("mGaaApi.PSGetImage():" + mGaaApi.PSGetImage()); // sleep(20); // } // while (mGaaApi.PSGetImage() == GaaApiBase.LIVESCAN_NO_FINGER) { // // if (globalControl == false) { // return -1; // } // publishProgress("mGaaApi.PSGetImage():" + mGaaApi.PSGetImage()); // sleep(10); // } // if ((ret = mGaaApi.PSUpImage(mGaaApi.PS_FingerBuf)) != ID_Fpr.LIVESCAN_SUCCESS) { // publishProgress("上传图像失败:" + ret); // continue; // } // publishProgress("OK"); // } // } // // // @Override // protected void onPreExecute() { // updateMsg("显示图片,请在传感器放上手指"); // return; // } // // @Override // protected void onProgressUpdate(String... values) { // if (values[0].equals("OK")) { // updateFingerImg(mGaaApi.PS_FingerBuf); // return; // } // updateMsg(values[0]); // } // } // // /** // * 录入指纹 // */ // @SuppressLint("StaticFieldLeak") // public class ImputAsyncTask extends AsyncTask<Integer, String, Integer> { // int Progress = 0; // // @Override // protected Integer doInBackground(Integer... params) { // int cnt = 1; // int ret; // // while (true) { // if (globalControl == false) { // return -1; // } // while (mGaaApi.PSGetImage() != GaaApiBase.LIVESCAN_NO_FINGER) { // if (globalControl == false) { // return -1; // } // // sleep(20); // } // while (mGaaApi.PSGetImage() == GaaApiBase.LIVESCAN_NO_FINGER) { // if (globalControl == false) { // return -1; // } // sleep(10); // } // // if ((ret = mGaaApi.PSUpImage(mGaaApi.PS_FingerBuf)) != GaaApiBase.LIVESCAN_SUCCESS) { // publishProgress("上传图像失败:" + ret); // continue; // } // publishProgress("OK"); // // byte[] mFeature = new byte[ID_Fpr.LIVESCAN_FEATURE_SIZE]; // int[] fingerId = new int[1]; // //生成模板 // if ((ret = mGaaApi.PSGenChar(mFeature, fingerId)) != GaaApiBase.LIVESCAN_SUCCESS) { // publishProgress("生成特征失败:" + ret); // continue; // } else { // publishProgress("updateProgress"); // } // // String s = DataUtils.bytesToHexString(mFeature); // publishProgress(s); // publishProgress("录入指纹成功,=====>ID:" + fingerId[0]); // return 0; // } // } // // @Override // protected void onPostExecute(Integer result) { // globalControl = false; // if (0 == result) { // bar.setProgress(100); // btnStatus(true); // } else { // bar.setProgress(0); // updateMsg("指纹录入失败,请重新录入"); // globalControl = false; // } // } // // @Override // protected void onPreExecute() { // updateMsg("录入指纹=>开始,请放上手指"); // } // // @Override // protected void onProgressUpdate(String... values) { // if (values[0].equals("OK")) { // updateFingerImg(mGaaApi.PS_FingerBuf); // return; // } // if (values[0].equals("updateProgress")) { // Progress += 50; // bar.setProgress(Progress); // return; // } // updateMsg(values[0]); // } // } // // long time; // // /** // * 搜索指纹 // */ // @SuppressLint("StaticFieldLeak") // public class SearchAsyncTask extends AsyncTask<Integer, String, Integer> { // @Override // protected Integer doInBackground(Integer... params) { // int ret; // int[] fingerId = new int[1]; // while (true) { // if (globalControl == false) { // return -1; // } // while (mGaaApi.PSGetImage() == GaaApiBase.LIVESCAN_NO_FINGER) { // if (globalControl == false) { // return -1; // } // sleep(20); // } // if ((ret = mGaaApi.PSUpImage(mGaaApi.PS_FingerBuf)) != GaaApiBase.LIVESCAN_SUCCESS) { // continue; // } // publishProgress("OK"); // // byte[] mFeature = new byte[ID_Fpr.LIVESCAN_FEATURE_SIZE]; // if (mGaaApi.PSGenChar(mFeature) != GaaApiBase.LIVESCAN_SUCCESS) { // continue; // } // time = System.currentTimeMillis(); // // int code = mGaaApi.PSSearch(mFeature, fingerId); // if (GaaApiBase.LIVESCAN_SUCCESS != code) {//mGaaApi.PSSearch(mFeature, fingerId) // publishProgress("没有找到此指纹"); // publishProgress("code = "+code); // continue; // } // //// int[] fingerId1 = new int[3]; //// mGaaApi.newTime(mFeature, fingerId1); // // updateMsg("search time = " + (System.currentTimeMillis() - time)); // publishProgress("成功搜索到此指纹,ID===> 0 =" + fingerId[0]); //// publishProgress("成功搜索到此指纹,ID===> 0 =" + fingerId1[0]+",1 = "+fingerId1[1]+",2 = "+fingerId1[2]); // } // } // // // @Override // protected void onPreExecute() { // updateMsg("搜索指纹=>开始,请放上手指"); // } // // @Override // protected void onProgressUpdate(String... values) { // if (values[0].equals("OK")) { // updateFingerImg(mGaaApi.PS_FingerBuf); // return; // } // updateMsg(values[0]); // } // } // // private void updateFingerImg(byte[] fpBmp) { // try { // updateMsg("updateFingerImg"); //// Bitmap bitmap = BitmapFactory.decodeByteArray(fpBmp, 0, fpBmp.length); //// fingerImage.setImageBitmap(bitmap); // fingerImage.setImageBitmap(mGaaApi.DataToBmp(fpBmp)); // } catch (Exception e) { // e.printStackTrace(); // } // } // // @Override // public boolean onKeyDown(int keyCode, KeyEvent event) { // // switch (keyCode) { // case KeyEvent.KEYCODE_BACK: // if (MyApplication.getApp().isShowingProgress()) // { // MyApplication.getApp().cancleProgressDialog(); // return true; // } // // Log.i(TAG, "点击了返回键"); // AlertDialog.Builder builder = new AlertDialog.Builder(this); // builder.setTitle(R.string.general_tips); // builder.setMessage(R.string.general_exit); // // //设置确定按钮 // builder.setNegativeButton(R.string.general_yes, new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // finish(); // } // }); // //设置取消按钮 // builder.setPositiveButton(R.string.general_no, null); // //显示提示框 // builder.show(); // break; // } // return super.onKeyDown(keyCode, event); // } // // public void updateMsg(final String msg) { // if (msg == null) { // msgText.setText(""); // msgText.scrollTo(0, 0); // return; // } // // runOnUiThread(new Runnable() { // @Override // public void run() { // //获取当前行数 // int lineCount = msgText.getLineCount(); // if (lineCount > 2000) { // //大于100行自动清零 // msgText.setText(""); // msgText.setText(msg); // } else { // //小于100行追加 // msgText.append("\n" + msg); // } // // //当前文本高度 // int scrollAmount = msgText.getLayout().getLineTop(msgText.getLineCount()) - msgText.getHeight(); // if (scrollAmount > 0) { // msgText.scrollTo(0, scrollAmount); // } else { // msgText.scrollTo(0, 0); // } //// int offset = lineCount * msgText.getLineHeight(); //// if (offset > msgText.getHeight()) { //// msgText.scrollTo(0, offset - msgText.getLineHeight()); //// txt_mmm.scrollTo(0, scrollAmount); //// } // } // }); // } // // private void btnStatus(boolean status) { // capture.setEnabled(status); // enroll.setEnabled(status); // search.setEnabled(status); // stop.setEnabled(!status); // infos.setEnabled(status); // clear.setEnabled(status); // bar.setProgress(0); // } // // /** // * 延时 // * // * @param time // */ // private void sleep(long time) { // try { // Thread.sleep(time); // } catch (Exception e) { // e.toString(); // } // } //}
CoreWise/CWDemo
app/src/main/java/com/cw/demo/fingerprint/gaa/NewFpGAAActivity.java
5,797
// int ret = mGaaApi.openGAA();
line_comment
nl
package com.cw.demo.fingerprint.gaa; //import android.annotation.SuppressLint; //import android.app.Activity; //import android.content.DialogInterface; //import android.hardware.usb.UsbDevice; //import android.hardware.usb.UsbManager; //import android.os.AsyncTask; //import android.os.Bundle; //import android.os.Handler; //import android.support.v7.app.AlertDialog; //import android.text.method.ScrollingMovementMethod; //import android.util.Log; //import android.view.KeyEvent; //import android.view.View; //import android.view.View.OnClickListener; //import android.view.WindowManager; //import android.widget.Button; //import android.widget.ImageView; //import android.widget.ProgressBar; //import android.widget.TextView; //import android.widget.Toast; // //import com.cw.demo.MyApplication; //import com.cw.demo.R; //import com.cw.fpgaasdk.GaaApiBHMDevice; //import com.cw.fpgaasdk.GaaApiBase; //import com.cw.fpgaasdk.GaaFingerFactory; //import com.cw.serialportsdk.USB.USBFingerManager; //import com.cw.serialportsdk.utils.DataUtils; //import com.fm.bio.ID_Fpr; // // //public class NewFpGAAActivity extends Activity implements OnClickListener { public class NewFpGAAActivity{ } // // private static final String TAG = "CwGAAActivity"; // ProgressBar bar; // ImageView fingerImage; // Button capture; // Button enroll; // Button enroll2; // Button search; // Button stop; // Button infos; // Button clear; // TextView msgText; // boolean globalControl = true; // // // public GAA_API mGaaApi; // public GaaApiBase mGaaApi; // // // @SuppressLint("HandlerLeak") // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // Log.i(TAG, "------------onCreate--------------"); // // setContentView(R.layout.fragment_capture_gaa); // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // // initview(); // } // // // @Override // protected void onStart() { // super.onStart(); // Log.i(TAG, "------------onStart--------------"); // open(); // } // // @Override // protected void onResume() { // super.onResume(); // Log.i(TAG, "------------onResume--------------"); // // } // // @Override // protected void onRestart() { // super.onRestart(); // Log.i(TAG, "------------onRestart--------------"); // } // // @Override // protected void onStop() { // super.onStop(); // Log.i(TAG, "------------onStop--------------"); // // close(); // } // // @Override // protected void onDestroy() { // super.onDestroy(); // Log.i(TAG, "------------onDestroy--------------"); // } // // public void initview() { // bar = findViewById(R.id.bar); // fingerImage = findViewById(R.id.fingerImage); // capture = findViewById(R.id.capture); // enroll = findViewById(R.id.enroll); // search = findViewById(R.id.search); // enroll2 = findViewById(R.id.enroll2); // stop = findViewById(R.id.stop); // infos = findViewById(R.id.infos); // clear = findViewById(R.id.clear); // msgText = findViewById(R.id.msg); // msgText.setMovementMethod(ScrollingMovementMethod.getInstance()); // // capture.setOnClickListener(this); // enroll.setOnClickListener(this); // search.setOnClickListener(this); // enroll2.setOnClickListener(this); // stop.setOnClickListener(this); // infos.setOnClickListener(this); // clear.setOnClickListener(this); // } // // private void open() { // MyApplication.getApp().showProgressDialog(this, getString(R.string.fp_usb_init)); // USBFingerManager.getInstance(this).openUSB(new USBFingerManager.OnUSBFingerListener() { // @Override // public void onOpenUSBFingerSuccess(String device, UsbManager usbManager, UsbDevice usbDevice) { // MyApplication.getApp().cancleProgressDialog(); // if (device.equals(GaaApiBase.ZiDevice)) { // //新固件 // mGaaApi = new GaaFingerFactory().createGAAFinger(GaaApiBase.ZiDevice,NewFpGAAActivity.this); // //// mGaaApi = new GAANewAPI(NewFpGAAActivity.this); // int ret<SUF> // if (ret == GaaApiBase.LIVESCAN_SUCCESS) { // updateMsg("open device success 1"); // } else if (ret == GaaApiBase.LIVESCAN_NOTINIT) { // updateMsg("not init"); // } else if (ret == GaaApiBase.LIVESCAN_AUTH_FAILED) { // updateMsg("auth failed"); // } else { // updateMsg("unknown " + ret); // } // // } else if (device.equals(GaaApiBase.BHMDevice)) { // //旧固件 // mGaaApi = new GaaFingerFactory().createGAAFinger(GaaApiBase.BHMDevice,NewFpGAAActivity.this); // // //// mGaaApi = new GAAOldAPI(NewFpGAAActivity.this); // new Handler().postDelayed(new Runnable() { // @Override // public void run() { // int ret = ((GaaApiBHMDevice)mGaaApi).openGAA(); // if (ret == GaaApiBase.LIVESCAN_SUCCESS) { // updateMsg("open device success 2"); // } else if (ret == GaaApiBase.LIVESCAN_NOTINIT) { // updateMsg("not init"); // } else if (ret == GaaApiBase.LIVESCAN_AUTH_FAILED) { // updateMsg("auth failed"); // } else { // String msg = mGaaApi.ErrorInfo(ret); // updateMsg("unknown " + ret); // updateMsg("msg =" + msg); // } // } // },1000); // } else { // updateMsg("开发包和指纹模块不一致! 请联系商务 " + device); //// Toast.makeText(NewFpGAAActivity.this, "device ="+device, Toast.LENGTH_SHORT).show(); // Toast.makeText(NewFpGAAActivity.this, "开发包和指纹模块不一致! 请联系商务", Toast.LENGTH_SHORT).show(); // } // } // // @Override // public void onOpenUSBFingerFailure(String error,int errorCode) { // Log.e(TAG, error); // MyApplication.getApp().cancleProgressDialog(); // Toast.makeText(NewFpGAAActivity.this, error, Toast.LENGTH_SHORT).show(); // } // }); // // } // // private void close() { // btnStatus(true); // globalControl = false; // updateMsg("设备已关闭"); // if (mGaaApi != null) { // mGaaApi.closeGAA(); // } // USBFingerManager.getInstance(this).closeUSB(); // } // // @Override // public void onClick(View v) { // switch (v.getId()) { // case R.id.capture: // globalControl = true; // btnStatus(false); // UpAsyncTask asyncTask_up = new UpAsyncTask(); // asyncTask_up.execute(1); // break; // case R.id.enroll: // btnStatus(false); // // globalControl = true; // ImputAsyncTask asyncTask = new ImputAsyncTask(); // asyncTask.execute(1); // break; // case R.id.enroll2: //// btnStatus(false); //// //// globalControl = true; //// ImputAsyncTask2 asyncTask2 = new ImputAsyncTask2(); //// asyncTask2.execute(1); // break; // case R.id.search: // btnStatus(false); // globalControl = true; // SearchAsyncTask asyncTask_search = new SearchAsyncTask(); // asyncTask_search.execute(1); // break; // case R.id.stop: // btnStatus(true); // globalControl = false; // fingerImage.setImageBitmap(null); // break; // // case R.id.infos: //// getInfos(); // break; // case R.id.clear: // updateMsg(null); // // if (GaaApiBase.LIVESCAN_SUCCESS != mGaaApi.PSEmpty()) { // updateMsg("清空指纹库失败"); // } // updateMsg("清空指纹库成功"); // break; // } // } // // /** // * 采集图片 // */ // @SuppressLint("StaticFieldLeak") // public class UpAsyncTask extends AsyncTask<Integer, String, Integer> { // // @Override // protected Integer doInBackground(Integer... params) { // int ret = 0; // while (true) { // // if (globalControl == false) { // return -1; // } // while (mGaaApi.PSGetImage() != GaaApiBase.LIVESCAN_NO_FINGER) { // if (globalControl == false) { // return -1; // } // publishProgress("mGaaApi.PSGetImage():" + mGaaApi.PSGetImage()); // sleep(20); // } // while (mGaaApi.PSGetImage() == GaaApiBase.LIVESCAN_NO_FINGER) { // // if (globalControl == false) { // return -1; // } // publishProgress("mGaaApi.PSGetImage():" + mGaaApi.PSGetImage()); // sleep(10); // } // if ((ret = mGaaApi.PSUpImage(mGaaApi.PS_FingerBuf)) != ID_Fpr.LIVESCAN_SUCCESS) { // publishProgress("上传图像失败:" + ret); // continue; // } // publishProgress("OK"); // } // } // // // @Override // protected void onPreExecute() { // updateMsg("显示图片,请在传感器放上手指"); // return; // } // // @Override // protected void onProgressUpdate(String... values) { // if (values[0].equals("OK")) { // updateFingerImg(mGaaApi.PS_FingerBuf); // return; // } // updateMsg(values[0]); // } // } // // /** // * 录入指纹 // */ // @SuppressLint("StaticFieldLeak") // public class ImputAsyncTask extends AsyncTask<Integer, String, Integer> { // int Progress = 0; // // @Override // protected Integer doInBackground(Integer... params) { // int cnt = 1; // int ret; // // while (true) { // if (globalControl == false) { // return -1; // } // while (mGaaApi.PSGetImage() != GaaApiBase.LIVESCAN_NO_FINGER) { // if (globalControl == false) { // return -1; // } // // sleep(20); // } // while (mGaaApi.PSGetImage() == GaaApiBase.LIVESCAN_NO_FINGER) { // if (globalControl == false) { // return -1; // } // sleep(10); // } // // if ((ret = mGaaApi.PSUpImage(mGaaApi.PS_FingerBuf)) != GaaApiBase.LIVESCAN_SUCCESS) { // publishProgress("上传图像失败:" + ret); // continue; // } // publishProgress("OK"); // // byte[] mFeature = new byte[ID_Fpr.LIVESCAN_FEATURE_SIZE]; // int[] fingerId = new int[1]; // //生成模板 // if ((ret = mGaaApi.PSGenChar(mFeature, fingerId)) != GaaApiBase.LIVESCAN_SUCCESS) { // publishProgress("生成特征失败:" + ret); // continue; // } else { // publishProgress("updateProgress"); // } // // String s = DataUtils.bytesToHexString(mFeature); // publishProgress(s); // publishProgress("录入指纹成功,=====>ID:" + fingerId[0]); // return 0; // } // } // // @Override // protected void onPostExecute(Integer result) { // globalControl = false; // if (0 == result) { // bar.setProgress(100); // btnStatus(true); // } else { // bar.setProgress(0); // updateMsg("指纹录入失败,请重新录入"); // globalControl = false; // } // } // // @Override // protected void onPreExecute() { // updateMsg("录入指纹=>开始,请放上手指"); // } // // @Override // protected void onProgressUpdate(String... values) { // if (values[0].equals("OK")) { // updateFingerImg(mGaaApi.PS_FingerBuf); // return; // } // if (values[0].equals("updateProgress")) { // Progress += 50; // bar.setProgress(Progress); // return; // } // updateMsg(values[0]); // } // } // // long time; // // /** // * 搜索指纹 // */ // @SuppressLint("StaticFieldLeak") // public class SearchAsyncTask extends AsyncTask<Integer, String, Integer> { // @Override // protected Integer doInBackground(Integer... params) { // int ret; // int[] fingerId = new int[1]; // while (true) { // if (globalControl == false) { // return -1; // } // while (mGaaApi.PSGetImage() == GaaApiBase.LIVESCAN_NO_FINGER) { // if (globalControl == false) { // return -1; // } // sleep(20); // } // if ((ret = mGaaApi.PSUpImage(mGaaApi.PS_FingerBuf)) != GaaApiBase.LIVESCAN_SUCCESS) { // continue; // } // publishProgress("OK"); // // byte[] mFeature = new byte[ID_Fpr.LIVESCAN_FEATURE_SIZE]; // if (mGaaApi.PSGenChar(mFeature) != GaaApiBase.LIVESCAN_SUCCESS) { // continue; // } // time = System.currentTimeMillis(); // // int code = mGaaApi.PSSearch(mFeature, fingerId); // if (GaaApiBase.LIVESCAN_SUCCESS != code) {//mGaaApi.PSSearch(mFeature, fingerId) // publishProgress("没有找到此指纹"); // publishProgress("code = "+code); // continue; // } // //// int[] fingerId1 = new int[3]; //// mGaaApi.newTime(mFeature, fingerId1); // // updateMsg("search time = " + (System.currentTimeMillis() - time)); // publishProgress("成功搜索到此指纹,ID===> 0 =" + fingerId[0]); //// publishProgress("成功搜索到此指纹,ID===> 0 =" + fingerId1[0]+",1 = "+fingerId1[1]+",2 = "+fingerId1[2]); // } // } // // // @Override // protected void onPreExecute() { // updateMsg("搜索指纹=>开始,请放上手指"); // } // // @Override // protected void onProgressUpdate(String... values) { // if (values[0].equals("OK")) { // updateFingerImg(mGaaApi.PS_FingerBuf); // return; // } // updateMsg(values[0]); // } // } // // private void updateFingerImg(byte[] fpBmp) { // try { // updateMsg("updateFingerImg"); //// Bitmap bitmap = BitmapFactory.decodeByteArray(fpBmp, 0, fpBmp.length); //// fingerImage.setImageBitmap(bitmap); // fingerImage.setImageBitmap(mGaaApi.DataToBmp(fpBmp)); // } catch (Exception e) { // e.printStackTrace(); // } // } // // @Override // public boolean onKeyDown(int keyCode, KeyEvent event) { // // switch (keyCode) { // case KeyEvent.KEYCODE_BACK: // if (MyApplication.getApp().isShowingProgress()) // { // MyApplication.getApp().cancleProgressDialog(); // return true; // } // // Log.i(TAG, "点击了返回键"); // AlertDialog.Builder builder = new AlertDialog.Builder(this); // builder.setTitle(R.string.general_tips); // builder.setMessage(R.string.general_exit); // // //设置确定按钮 // builder.setNegativeButton(R.string.general_yes, new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // finish(); // } // }); // //设置取消按钮 // builder.setPositiveButton(R.string.general_no, null); // //显示提示框 // builder.show(); // break; // } // return super.onKeyDown(keyCode, event); // } // // public void updateMsg(final String msg) { // if (msg == null) { // msgText.setText(""); // msgText.scrollTo(0, 0); // return; // } // // runOnUiThread(new Runnable() { // @Override // public void run() { // //获取当前行数 // int lineCount = msgText.getLineCount(); // if (lineCount > 2000) { // //大于100行自动清零 // msgText.setText(""); // msgText.setText(msg); // } else { // //小于100行追加 // msgText.append("\n" + msg); // } // // //当前文本高度 // int scrollAmount = msgText.getLayout().getLineTop(msgText.getLineCount()) - msgText.getHeight(); // if (scrollAmount > 0) { // msgText.scrollTo(0, scrollAmount); // } else { // msgText.scrollTo(0, 0); // } //// int offset = lineCount * msgText.getLineHeight(); //// if (offset > msgText.getHeight()) { //// msgText.scrollTo(0, offset - msgText.getLineHeight()); //// txt_mmm.scrollTo(0, scrollAmount); //// } // } // }); // } // // private void btnStatus(boolean status) { // capture.setEnabled(status); // enroll.setEnabled(status); // search.setEnabled(status); // stop.setEnabled(!status); // infos.setEnabled(status); // clear.setEnabled(status); // bar.setProgress(0); // } // // /** // * 延时 // * // * @param time // */ // private void sleep(long time) { // try { // Thread.sleep(time); // } catch (Exception e) { // e.toString(); // } // } //}
62624_8
package org.corfudb.runtime; import com.google.common.collect.ImmutableMap; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import lombok.Data; import lombok.ToString; import org.corfudb.comm.ChannelImplementation; import org.corfudb.runtime.clients.NettyClientRouter; import org.corfudb.security.tls.TlsUtils.CertStoreConfig.KeyStoreConfig; import org.corfudb.security.tls.TlsUtils.CertStoreConfig.TrustStoreConfig; import java.lang.Thread.UncaughtExceptionHandler; import java.nio.file.Path; import java.time.Duration; import java.util.Map; import java.util.UUID; @Data @ToString public class RuntimeParameters { private final long nettyShutdownQuitePeriod = 100; private final long nettyShutdownTimeout = 300; /** * True, if TLS is enabled. */ public boolean tlsEnabled = false; /** * A path to the key store. */ public String keyStore; /* * A file containing the password for the key store. */ public String ksPasswordFile; /** * A path to the trust store. */ public String trustStore; /** * A path containing the password for the trust store. */ public String tsPasswordFile; public Path disableCertExpiryCheckFile = TrustStoreConfig.DEFAULT_DISABLE_CERT_EXPIRY_CHECK_FILE; /** * True, if SASL plain text authentication is enabled. */ public boolean saslPlainTextEnabled = false; /** * A path containing the username file for SASL. */ public String usernameFile; /** * A path containing the password file for SASL. */ public String passwordFile; //endregion // region Handshake Parameters /** * Sets handshake timeout in seconds. */ public int handshakeTimeout = 10; // endregion //region Connection parameters /** * {@link Duration} before requests timeout. * This is the duration after which the logreader hole fills the address. */ public Duration requestTimeout = Duration.ofSeconds(5); /** * This timeout (in seconds) is used to detect servers that * shutdown abruptly without terminating the connection properly. */ public int idleConnectionTimeout = 7; /** * The period at which the client sends keep-alive messages to the * server (a message is only send there is no write activity on the channel * for the whole period. */ public int keepAlivePeriod = 2; /** * {@link Duration} before connections timeout. */ public Duration connectionTimeout = Duration.ofMillis(500); /** * {@link Duration} before reconnecting to a disconnected node. */ public Duration connectionRetryRate = Duration.ofSeconds(1); /** * The {@link UUID} for this client. Randomly generated by default. */ public UUID clientId = UUID.randomUUID(); /** * The type of socket which {@link NettyClientRouter}s should use. By default, * an NIO based implementation is used. */ public ChannelImplementation socketType = ChannelImplementation.NIO; /** * The {@link EventLoopGroup} which {@link NettyClientRouter}s will use. * If not specified, the runtime will generate this using the {@link ChannelImplementation} * specified in {@code socketType} and the {@link java.util.concurrent.ThreadFactory} specified in * {@code nettyThreadFactory}. */ public EventLoopGroup nettyEventLoop; /** * A string which will be used to set the * {@link com.google.common.util.concurrent.ThreadFactoryBuilder#nameFormat} for the * {@code nettyThreadFactory}. By default, this is set to "netty-%d". * If you provide your own {@code nettyEventLoop}, this field is ignored. */ public String nettyEventLoopThreadFormat = "netty-%d"; /** * The number of threads that should be available in the {@link NettyClientRouter}'s * event pool. 0 means that we will use 2x the number of processors reported in the * system. If you provide your own {@code nettyEventLoop}, this field is ignored. */ public int nettyEventLoopThreads = 0; /** * True, if the {@code NettyEventLoop} should be shutdown when the runtime is * shutdown. False otherwise. */ public boolean shutdownNettyEventLoop = true; /** * Default channel options, used if there are no options in the * {@link this#customNettyChannelOptions} field. */ public static final Map<ChannelOption, Object> DEFAULT_CHANNEL_OPTIONS = ImmutableMap.<ChannelOption, Object>builder() .put(ChannelOption.TCP_NODELAY, true) .put(ChannelOption.SO_REUSEADDR, true) .build(); /** * Netty channel options, if provided. If no options are set, we default to * the defaults in {}. */ public Map<ChannelOption, Object> customNettyChannelOptions; /** * A {@link UncaughtExceptionHandler} which handles threads that have an uncaught * exception. Used on all {@link java.util.concurrent.ThreadFactory}s the runtime creates, but if you * generate your own thread factory, this field is ignored. If this field is not set, * the runtime's default handler runs, which logs an error level message. */ public UncaughtExceptionHandler uncaughtExceptionHandler; // Register handlers region // These two handlers are provided to give some control on what happen when system is down. // For applications that want to have specific behaviour when a the system appears // unavailable, they can register their own handler for both before the rpc request and // upon cluster unreachability. // An example of how to use these handlers implementing timeout is given in // test/src/test/java/org/corfudb/runtime/CorfuRuntimeTest.java /** * SystemDownHandler is invoked at any point when the Corfu client attempts to make an RPC * request to the Corfu cluster but is unable to complete this. * NOTE: This will also be invoked during connect if the cluster is unreachable. */ public volatile Runnable systemDownHandler = () -> { }; /** * BeforeRPCHandler callback is invoked every time before an RPC call. */ public volatile Runnable beforeRpcHandler = () -> { }; //endregion /** * Get the netty channel options to be used by the netty client implementation. * * @return A map containing options which should be applied to each netty channel. */ public Map<ChannelOption, Object> getNettyChannelOptions() { return customNettyChannelOptions.size() == 0 ? DEFAULT_CHANNEL_OPTIONS : customNettyChannelOptions; } public static RuntimeParametersBuilder builder() { return new RuntimeParametersBuilder(); } public KeyStoreConfig getKeyStoreConfig() { return KeyStoreConfig.from(keyStore, ksPasswordFile); } public TrustStoreConfig getTrustStoreConfig(){ return TrustStoreConfig.from(trustStore, tsPasswordFile, disableCertExpiryCheckFile); } }
CorfuDB/CorfuDB
runtime/src/main/java/org/corfudb/runtime/RuntimeParameters.java
1,941
// region Handshake Parameters
line_comment
nl
package org.corfudb.runtime; import com.google.common.collect.ImmutableMap; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import lombok.Data; import lombok.ToString; import org.corfudb.comm.ChannelImplementation; import org.corfudb.runtime.clients.NettyClientRouter; import org.corfudb.security.tls.TlsUtils.CertStoreConfig.KeyStoreConfig; import org.corfudb.security.tls.TlsUtils.CertStoreConfig.TrustStoreConfig; import java.lang.Thread.UncaughtExceptionHandler; import java.nio.file.Path; import java.time.Duration; import java.util.Map; import java.util.UUID; @Data @ToString public class RuntimeParameters { private final long nettyShutdownQuitePeriod = 100; private final long nettyShutdownTimeout = 300; /** * True, if TLS is enabled. */ public boolean tlsEnabled = false; /** * A path to the key store. */ public String keyStore; /* * A file containing the password for the key store. */ public String ksPasswordFile; /** * A path to the trust store. */ public String trustStore; /** * A path containing the password for the trust store. */ public String tsPasswordFile; public Path disableCertExpiryCheckFile = TrustStoreConfig.DEFAULT_DISABLE_CERT_EXPIRY_CHECK_FILE; /** * True, if SASL plain text authentication is enabled. */ public boolean saslPlainTextEnabled = false; /** * A path containing the username file for SASL. */ public String usernameFile; /** * A path containing the password file for SASL. */ public String passwordFile; //endregion // region Handshake<SUF> /** * Sets handshake timeout in seconds. */ public int handshakeTimeout = 10; // endregion //region Connection parameters /** * {@link Duration} before requests timeout. * This is the duration after which the logreader hole fills the address. */ public Duration requestTimeout = Duration.ofSeconds(5); /** * This timeout (in seconds) is used to detect servers that * shutdown abruptly without terminating the connection properly. */ public int idleConnectionTimeout = 7; /** * The period at which the client sends keep-alive messages to the * server (a message is only send there is no write activity on the channel * for the whole period. */ public int keepAlivePeriod = 2; /** * {@link Duration} before connections timeout. */ public Duration connectionTimeout = Duration.ofMillis(500); /** * {@link Duration} before reconnecting to a disconnected node. */ public Duration connectionRetryRate = Duration.ofSeconds(1); /** * The {@link UUID} for this client. Randomly generated by default. */ public UUID clientId = UUID.randomUUID(); /** * The type of socket which {@link NettyClientRouter}s should use. By default, * an NIO based implementation is used. */ public ChannelImplementation socketType = ChannelImplementation.NIO; /** * The {@link EventLoopGroup} which {@link NettyClientRouter}s will use. * If not specified, the runtime will generate this using the {@link ChannelImplementation} * specified in {@code socketType} and the {@link java.util.concurrent.ThreadFactory} specified in * {@code nettyThreadFactory}. */ public EventLoopGroup nettyEventLoop; /** * A string which will be used to set the * {@link com.google.common.util.concurrent.ThreadFactoryBuilder#nameFormat} for the * {@code nettyThreadFactory}. By default, this is set to "netty-%d". * If you provide your own {@code nettyEventLoop}, this field is ignored. */ public String nettyEventLoopThreadFormat = "netty-%d"; /** * The number of threads that should be available in the {@link NettyClientRouter}'s * event pool. 0 means that we will use 2x the number of processors reported in the * system. If you provide your own {@code nettyEventLoop}, this field is ignored. */ public int nettyEventLoopThreads = 0; /** * True, if the {@code NettyEventLoop} should be shutdown when the runtime is * shutdown. False otherwise. */ public boolean shutdownNettyEventLoop = true; /** * Default channel options, used if there are no options in the * {@link this#customNettyChannelOptions} field. */ public static final Map<ChannelOption, Object> DEFAULT_CHANNEL_OPTIONS = ImmutableMap.<ChannelOption, Object>builder() .put(ChannelOption.TCP_NODELAY, true) .put(ChannelOption.SO_REUSEADDR, true) .build(); /** * Netty channel options, if provided. If no options are set, we default to * the defaults in {}. */ public Map<ChannelOption, Object> customNettyChannelOptions; /** * A {@link UncaughtExceptionHandler} which handles threads that have an uncaught * exception. Used on all {@link java.util.concurrent.ThreadFactory}s the runtime creates, but if you * generate your own thread factory, this field is ignored. If this field is not set, * the runtime's default handler runs, which logs an error level message. */ public UncaughtExceptionHandler uncaughtExceptionHandler; // Register handlers region // These two handlers are provided to give some control on what happen when system is down. // For applications that want to have specific behaviour when a the system appears // unavailable, they can register their own handler for both before the rpc request and // upon cluster unreachability. // An example of how to use these handlers implementing timeout is given in // test/src/test/java/org/corfudb/runtime/CorfuRuntimeTest.java /** * SystemDownHandler is invoked at any point when the Corfu client attempts to make an RPC * request to the Corfu cluster but is unable to complete this. * NOTE: This will also be invoked during connect if the cluster is unreachable. */ public volatile Runnable systemDownHandler = () -> { }; /** * BeforeRPCHandler callback is invoked every time before an RPC call. */ public volatile Runnable beforeRpcHandler = () -> { }; //endregion /** * Get the netty channel options to be used by the netty client implementation. * * @return A map containing options which should be applied to each netty channel. */ public Map<ChannelOption, Object> getNettyChannelOptions() { return customNettyChannelOptions.size() == 0 ? DEFAULT_CHANNEL_OPTIONS : customNettyChannelOptions; } public static RuntimeParametersBuilder builder() { return new RuntimeParametersBuilder(); } public KeyStoreConfig getKeyStoreConfig() { return KeyStoreConfig.from(keyStore, ksPasswordFile); } public TrustStoreConfig getTrustStoreConfig(){ return TrustStoreConfig.from(trustStore, tsPasswordFile, disableCertExpiryCheckFile); } }
56970_2
/* * Commons eID Project. * Copyright (C) 2008-2013 FedICT. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version * 3.0 as published by the Free Software Foundation. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, see * http://www.gnu.org/licenses/. */ package be.fedict.commons.eid.consumer; import java.io.Serializable; import java.util.HashMap; import java.util.Map; /** * Enumeration for eID Document Type. * * @author Frank Cornelis * */ public enum DocumentType implements Serializable { BELGIAN_CITIZEN("1"), KIDS_CARD("6"), BOOTSTRAP_CARD("7"), HABILITATION_CARD("8"), /** * Bewijs van inschrijving in het vreemdelingenregister ??? Tijdelijk * verblijf */ FOREIGNER_A("11"), /** * Bewijs van inschrijving in het vreemdelingenregister */ FOREIGNER_B("12"), /** * Identiteitskaart voor vreemdeling */ FOREIGNER_C("13"), /** * EG-Langdurig ingezetene */ FOREIGNER_D("14"), /** * (Verblijfs)kaart van een onderdaan van een lidstaat der EEG Verklaring * van inschrijving */ FOREIGNER_E("15"), /** * Document ter staving van duurzaam verblijf van een EU onderdaan */ FOREIGNER_E_PLUS("16"), /** * Kaart voor niet-EU familieleden van een EU-onderdaan of van een Belg * Verblijfskaart van een familielid van een burger van de Unie */ FOREIGNER_F("17"), /** * Duurzame verblijfskaart van een familielid van een burger van de Unie */ FOREIGNER_F_PLUS("18"), /** * H. Europese blauwe kaart. Toegang en verblijf voor onderdanen van derde * landen. */ EUROPEAN_BLUE_CARD_H("19"); private final int key; private DocumentType(final String value) { this.key = toKey(value); } private int toKey(final String value) { final char c1 = value.charAt(0); int key = c1 - '0'; if (2 == value.length()) { key *= 10; final char c2 = value.charAt(1); key += c2 - '0'; } return key; } private static int toKey(final byte[] value) { int key = value[0] - '0'; if (2 == value.length) { key *= 10; key += value[1] - '0'; } return key; } private static Map<Integer, DocumentType> documentTypes; static { final Map<Integer, DocumentType> documentTypes = new HashMap<Integer, DocumentType>(); for (DocumentType documentType : DocumentType.values()) { final int encodedValue = documentType.key; if (documentTypes.containsKey(encodedValue)) { throw new RuntimeException("duplicate document type enum: " + encodedValue); } documentTypes.put(encodedValue, documentType); } DocumentType.documentTypes = documentTypes; } public int getKey() { return this.key; } public static DocumentType toDocumentType(final byte[] value) { final int key = DocumentType.toKey(value); final DocumentType documentType = DocumentType.documentTypes.get(key); /* * If the key is unknown, we simply return null. */ return documentType; } public static String toString(final byte[] documentTypeValue) { return Integer.toString(DocumentType.toKey(documentTypeValue)); } }
Corilus/commons-eid
commons-eid-consumer/src/main/java/be/fedict/commons/eid/consumer/DocumentType.java
1,169
/** * Bewijs van inschrijving in het vreemdelingenregister ??? Tijdelijk * verblijf */
block_comment
nl
/* * Commons eID Project. * Copyright (C) 2008-2013 FedICT. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version * 3.0 as published by the Free Software Foundation. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, see * http://www.gnu.org/licenses/. */ package be.fedict.commons.eid.consumer; import java.io.Serializable; import java.util.HashMap; import java.util.Map; /** * Enumeration for eID Document Type. * * @author Frank Cornelis * */ public enum DocumentType implements Serializable { BELGIAN_CITIZEN("1"), KIDS_CARD("6"), BOOTSTRAP_CARD("7"), HABILITATION_CARD("8"), /** * Bewijs van inschrijving<SUF>*/ FOREIGNER_A("11"), /** * Bewijs van inschrijving in het vreemdelingenregister */ FOREIGNER_B("12"), /** * Identiteitskaart voor vreemdeling */ FOREIGNER_C("13"), /** * EG-Langdurig ingezetene */ FOREIGNER_D("14"), /** * (Verblijfs)kaart van een onderdaan van een lidstaat der EEG Verklaring * van inschrijving */ FOREIGNER_E("15"), /** * Document ter staving van duurzaam verblijf van een EU onderdaan */ FOREIGNER_E_PLUS("16"), /** * Kaart voor niet-EU familieleden van een EU-onderdaan of van een Belg * Verblijfskaart van een familielid van een burger van de Unie */ FOREIGNER_F("17"), /** * Duurzame verblijfskaart van een familielid van een burger van de Unie */ FOREIGNER_F_PLUS("18"), /** * H. Europese blauwe kaart. Toegang en verblijf voor onderdanen van derde * landen. */ EUROPEAN_BLUE_CARD_H("19"); private final int key; private DocumentType(final String value) { this.key = toKey(value); } private int toKey(final String value) { final char c1 = value.charAt(0); int key = c1 - '0'; if (2 == value.length()) { key *= 10; final char c2 = value.charAt(1); key += c2 - '0'; } return key; } private static int toKey(final byte[] value) { int key = value[0] - '0'; if (2 == value.length) { key *= 10; key += value[1] - '0'; } return key; } private static Map<Integer, DocumentType> documentTypes; static { final Map<Integer, DocumentType> documentTypes = new HashMap<Integer, DocumentType>(); for (DocumentType documentType : DocumentType.values()) { final int encodedValue = documentType.key; if (documentTypes.containsKey(encodedValue)) { throw new RuntimeException("duplicate document type enum: " + encodedValue); } documentTypes.put(encodedValue, documentType); } DocumentType.documentTypes = documentTypes; } public int getKey() { return this.key; } public static DocumentType toDocumentType(final byte[] value) { final int key = DocumentType.toKey(value); final DocumentType documentType = DocumentType.documentTypes.get(key); /* * If the key is unknown, we simply return null. */ return documentType; } public static String toString(final byte[] documentTypeValue) { return Integer.toString(DocumentType.toKey(documentTypeValue)); } }
143258_32
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.coyote; import java.io.IOException; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.Locale; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import jakarta.servlet.WriteListener; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.buf.B2CConverter; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.http.MimeHeaders; import org.apache.tomcat.util.http.parser.MediaType; import org.apache.tomcat.util.res.StringManager; /** * Response object. * * @author James Duncan Davidson [[email protected]] * @author Jason Hunter [[email protected]] * @author James Todd [[email protected]] * @author Harish Prabandham * @author Hans Bergsten [[email protected]] * @author Remy Maucherat */ public final class Response { private static final StringManager sm = StringManager.getManager(Response.class); private static final Log log = LogFactory.getLog(Response.class); // ----------------------------------------------------- Class Variables /** * Default locale as mandated by the spec. */ private static final Locale DEFAULT_LOCALE = Locale.getDefault(); // ----------------------------------------------------- Instance Variables /** * Status code. */ int status = 200; /** * Status message. */ String message = null; /** * Response headers. */ final MimeHeaders headers = new MimeHeaders(); private Supplier<Map<String,String>> trailerFieldsSupplier = null; /** * Associated output buffer. */ OutputBuffer outputBuffer; /** * Notes. */ final Object notes[] = new Object[Constants.MAX_NOTES]; /** * Committed flag. */ volatile boolean committed = false; /** * Action hook. */ volatile ActionHook hook; /** * HTTP specific fields. */ String contentType = null; String contentLanguage = null; Charset charset = null; // Retain the original name used to set the charset so exactly that name is // used in the ContentType header. Some (arguably non-specification // compliant) user agents are very particular String characterEncoding = null; long contentLength = -1; private Locale locale = DEFAULT_LOCALE; // General information private long contentWritten = 0; private long commitTimeNanos = -1; /** * Holds response writing error exception. */ private Exception errorException = null; /** * With the introduction of async processing and the possibility of * non-container threads calling sendError() tracking the current error * state and ensuring that the correct error page is called becomes more * complicated. This state attribute helps by tracking the current error * state and informing callers that attempt to change state if the change * was successful or if another thread got there first. * * <pre> * The state machine is very simple: * * 0 - NONE * 1 - NOT_REPORTED * 2 - REPORTED * * * -->---->-- >NONE * | | | * | | | setError() * ^ ^ | * | | \|/ * | |-<-NOT_REPORTED * | | * ^ | report() * | | * | \|/ * |----<----REPORTED * </pre> */ private final AtomicInteger errorState = new AtomicInteger(0); Request req; // ------------------------------------------------------------- Properties public Request getRequest() { return req; } public void setRequest( Request req ) { this.req=req; } public void setOutputBuffer(OutputBuffer outputBuffer) { this.outputBuffer = outputBuffer; } public MimeHeaders getMimeHeaders() { return headers; } protected void setHook(ActionHook hook) { this.hook = hook; } // -------------------- Per-Response "notes" -------------------- public final void setNote(int pos, Object value) { notes[pos] = value; } public final Object getNote(int pos) { return notes[pos]; } // -------------------- Actions -------------------- public void action(ActionCode actionCode, Object param) { if (hook != null) { if (param == null) { hook.action(actionCode, this); } else { hook.action(actionCode, param); } } } // -------------------- State -------------------- public int getStatus() { return status; } /** * Set the response status. * * @param status The status value to set */ public void setStatus(int status) { this.status = status; } /** * Get the status message. * * @return The message associated with the current status */ public String getMessage() { return message; } /** * Set the status message. * * @param message The status message to set */ public void setMessage(String message) { this.message = message; } public boolean isCommitted() { return committed; } public void setCommitted(boolean v) { if (v && !this.committed) { this.commitTimeNanos = System.nanoTime(); } this.committed = v; } /** * Return the time the response was committed (based on System.currentTimeMillis). * * @return the time the response was committed */ public long getCommitTime() { return System.currentTimeMillis() - TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - commitTimeNanos); } /** * Return the time the response was committed (based on System.nanoTime). * * @return the time the response was committed */ public long getCommitTimeNanos() { return commitTimeNanos; } // -----------------Error State -------------------- /** * Set the error Exception that occurred during the writing of the response * processing. * * @param ex The exception that occurred */ public void setErrorException(Exception ex) { errorException = ex; } /** * Get the Exception that occurred during the writing of the response. * * @return The exception that occurred */ public Exception getErrorException() { return errorException; } public boolean isExceptionPresent() { return errorException != null; } /** * Set the error flag. * * @return <code>false</code> if the error flag was already set */ public boolean setError() { return errorState.compareAndSet(0, 1); } /** * Error flag accessor. * * @return <code>true</code> if the response has encountered an error */ public boolean isError() { return errorState.get() > 0; } public boolean isErrorReportRequired() { return errorState.get() == 1; } public boolean setErrorReported() { return errorState.compareAndSet(1, 2); } // -------------------- Methods -------------------- public void reset() throws IllegalStateException { if (committed) { throw new IllegalStateException(); } recycle(); } // -------------------- Headers -------------------- /** * Does the response contain the given header. * <br> * Warning: This method always returns <code>false</code> for Content-Type * and Content-Length. * * @param name The name of the header of interest * * @return {@code true} if the response contains the header. */ public boolean containsHeader(String name) { return headers.getHeader(name) != null; } public void setHeader(String name, String value) { char cc=name.charAt(0); if( cc=='C' || cc=='c' ) { if( checkSpecialHeader(name, value) ) { return; } } headers.setValue(name).setString( value); } public void addHeader(String name, String value) { addHeader(name, value, null); } public void addHeader(String name, String value, Charset charset) { char cc=name.charAt(0); if( cc=='C' || cc=='c' ) { if( checkSpecialHeader(name, value) ) { return; } } MessageBytes mb = headers.addValue(name); if (charset != null) { mb.setCharset(charset); } mb.setString(value); } public void setTrailerFields(Supplier<Map<String, String>> supplier) { AtomicBoolean trailerFieldsSupported = new AtomicBoolean(false); action(ActionCode.IS_TRAILER_FIELDS_SUPPORTED, trailerFieldsSupported); if (!trailerFieldsSupported.get()) { throw new IllegalStateException(sm.getString("response.noTrailers.notSupported")); } this.trailerFieldsSupplier = supplier; } public Supplier<Map<String, String>> getTrailerFields() { return trailerFieldsSupplier; } /** * Set internal fields for special header names. * Called from set/addHeader. * Return true if the header is special, no need to set the header. */ private boolean checkSpecialHeader( String name, String value) { // XXX Eliminate redundant fields !!! // ( both header and in special fields ) if( name.equalsIgnoreCase( "Content-Type" ) ) { setContentType( value ); return true; } if( name.equalsIgnoreCase( "Content-Length" ) ) { try { long cL=Long.parseLong( value ); setContentLength( cL ); return true; } catch( NumberFormatException ex ) { // Do nothing - the spec doesn't have any "throws" // and the user might know what they're doing return false; } } return false; } /** Signal that we're done with the headers, and body will follow. * Any implementation needs to notify ContextManager, to allow * interceptors to fix headers. */ public void sendHeaders() { action(ActionCode.COMMIT, this); setCommitted(true); } // -------------------- I18N -------------------- public Locale getLocale() { return locale; } /** * Called explicitly by user to set the Content-Language and the default * encoding. * * @param locale The locale to use for this response */ public void setLocale(Locale locale) { if (locale == null) { this.locale = null; this.contentLanguage = null; return; } // Save the locale for use by getLocale() this.locale = locale; // Set the contentLanguage for header output contentLanguage = locale.toLanguageTag(); } /** * Return the content language. * * @return The language code for the language currently associated with this * response */ public String getContentLanguage() { return contentLanguage; } /** * Overrides the character encoding used in the body of the response. This * method must be called prior to writing output using getWriter(). * * @param characterEncoding The name of character encoding. * * @throws UnsupportedEncodingException If the specified name is not * recognised */ public void setCharacterEncoding(String characterEncoding) throws UnsupportedEncodingException { if (isCommitted()) { return; } if (characterEncoding == null) { this.charset = null; this.characterEncoding = null; return; } this.characterEncoding = characterEncoding; this.charset = B2CConverter.getCharset(characterEncoding); } public Charset getCharset() { return charset; } /** * @return The name of the current encoding */ public String getCharacterEncoding() { return characterEncoding; } /** * Sets the content type. * * This method must preserve any response charset that may already have * been set via a call to response.setContentType(), response.setLocale(), * or response.setCharacterEncoding(). * * @param type the content type */ public void setContentType(String type) { if (type == null) { this.contentType = null; return; } MediaType m = null; try { m = MediaType.parseMediaType(new StringReader(type)); } catch (IOException e) { // Ignore - null test below handles this } if (m == null) { // Invalid - Assume no charset and just pass through whatever // the user provided. this.contentType = type; return; } this.contentType = m.toStringNoCharset(); String charsetValue = m.getCharset(); if (charsetValue == null) { // No charset and we know value is valid as parser was successful // Pass-through user provided value in case user-agent is buggy and // requires specific format this.contentType = type; } else { // There is a charset so have to rebuild content-type without it this.contentType = m.toStringNoCharset(); charsetValue = charsetValue.trim(); if (charsetValue.length() > 0) { try { charset = B2CConverter.getCharset(charsetValue); } catch (UnsupportedEncodingException e) { log.warn(sm.getString("response.encoding.invalid", charsetValue), e); } } } } public void setContentTypeNoCharset(String type) { this.contentType = type; } public String getContentType() { String ret = contentType; if (ret != null && charset != null) { ret = ret + ";charset=" + characterEncoding; } return ret; } public void setContentLength(long contentLength) { this.contentLength = contentLength; } public int getContentLength() { long length = getContentLengthLong(); if (length < Integer.MAX_VALUE) { return (int) length; } return -1; } public long getContentLengthLong() { return contentLength; } /** * Write a chunk of bytes. * * @param chunk The ByteBuffer to write * * @throws IOException If an I/O error occurs during the write */ public void doWrite(ByteBuffer chunk) throws IOException { int len = chunk.remaining(); outputBuffer.doWrite(chunk); contentWritten += len - chunk.remaining(); } // -------------------- public void recycle() { contentType = null; contentLanguage = null; locale = DEFAULT_LOCALE; charset = null; characterEncoding = null; contentLength = -1; status = 200; message = null; committed = false; commitTimeNanos = -1; errorException = null; errorState.set(0); headers.clear(); trailerFieldsSupplier = null; // Servlet 3.1 non-blocking write listener listener = null; synchronized (nonBlockingStateLock) { fireListener = false; registeredForWrite = false; } // update counters contentWritten=0; } /** * Bytes written by application - i.e. before compression, chunking, etc. * * @return The total number of bytes written to the response by the * application. This will not be the number of bytes written to the * network which may be more or less than this value. */ public long getContentWritten() { return contentWritten; } /** * Bytes written to socket - i.e. after compression, chunking, etc. * * @param flush Should any remaining bytes be flushed before returning the * total? If {@code false} bytes remaining in the buffer will * not be included in the returned value * * @return The total number of bytes written to the socket for this response */ public long getBytesWritten(boolean flush) { if (flush) { action(ActionCode.CLIENT_FLUSH, this); } return outputBuffer.getBytesWritten(); } /* * State for non-blocking output is maintained here as it is the one point * easily reachable from the CoyoteOutputStream and the Processor which both * need access to state. */ volatile WriteListener listener; // Ensures listener is only fired after a call is isReady() private boolean fireListener = false; // Tracks write registration to prevent duplicate registrations private boolean registeredForWrite = false; // Lock used to manage concurrent access to above flags private final Object nonBlockingStateLock = new Object(); public WriteListener getWriteListener() { return listener; } public void setWriteListener(WriteListener listener) { if (listener == null) { throw new NullPointerException( sm.getString("response.nullWriteListener")); } if (getWriteListener() != null) { throw new IllegalStateException( sm.getString("response.writeListenerSet")); } // Note: This class is not used for HTTP upgrade so only need to test // for async AtomicBoolean result = new AtomicBoolean(false); action(ActionCode.ASYNC_IS_ASYNC, result); if (!result.get()) { throw new IllegalStateException( sm.getString("response.notAsync")); } this.listener = listener; // The container is responsible for the first call to // listener.onWritePossible(). If isReady() returns true, the container // needs to call listener.onWritePossible() from a new thread. If // isReady() returns false, the socket will be registered for write and // the container will call listener.onWritePossible() once data can be // written. if (isReady()) { synchronized (nonBlockingStateLock) { // Ensure we don't get multiple write registrations if // ServletOutputStream.isReady() returns false during a call to // onDataAvailable() registeredForWrite = true; // Need to set the fireListener flag otherwise when the // container tries to trigger onWritePossible, nothing will // happen fireListener = true; } action(ActionCode.DISPATCH_WRITE, null); if (!req.isRequestThread()) { // Not on a container thread so need to execute the dispatch action(ActionCode.DISPATCH_EXECUTE, null); } } } public boolean isReady() { if (listener == null) { return true; } // Assume write is not possible boolean ready = false; synchronized (nonBlockingStateLock) { if (registeredForWrite) { fireListener = true; return false; } ready = checkRegisterForWrite(); fireListener = !ready; } return ready; } public boolean checkRegisterForWrite() { AtomicBoolean ready = new AtomicBoolean(false); synchronized (nonBlockingStateLock) { if (!registeredForWrite) { action(ActionCode.NB_WRITE_INTEREST, ready); registeredForWrite = !ready.get(); } } return ready.get(); } public void onWritePossible() throws IOException { // Any buffered data left over from a previous non-blocking write is // written in the Processor so if this point is reached the app is able // to write data. boolean fire = false; synchronized (nonBlockingStateLock) { registeredForWrite = false; if (fireListener) { fireListener = false; fire = true; } } if (fire) { listener.onWritePossible(); } } }
Cosium/tomcat
java/org/apache/coyote/Response.java
5,768
// -------------------- Headers --------------------
line_comment
nl
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.coyote; import java.io.IOException; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.Locale; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import jakarta.servlet.WriteListener; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.buf.B2CConverter; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.http.MimeHeaders; import org.apache.tomcat.util.http.parser.MediaType; import org.apache.tomcat.util.res.StringManager; /** * Response object. * * @author James Duncan Davidson [[email protected]] * @author Jason Hunter [[email protected]] * @author James Todd [[email protected]] * @author Harish Prabandham * @author Hans Bergsten [[email protected]] * @author Remy Maucherat */ public final class Response { private static final StringManager sm = StringManager.getManager(Response.class); private static final Log log = LogFactory.getLog(Response.class); // ----------------------------------------------------- Class Variables /** * Default locale as mandated by the spec. */ private static final Locale DEFAULT_LOCALE = Locale.getDefault(); // ----------------------------------------------------- Instance Variables /** * Status code. */ int status = 200; /** * Status message. */ String message = null; /** * Response headers. */ final MimeHeaders headers = new MimeHeaders(); private Supplier<Map<String,String>> trailerFieldsSupplier = null; /** * Associated output buffer. */ OutputBuffer outputBuffer; /** * Notes. */ final Object notes[] = new Object[Constants.MAX_NOTES]; /** * Committed flag. */ volatile boolean committed = false; /** * Action hook. */ volatile ActionHook hook; /** * HTTP specific fields. */ String contentType = null; String contentLanguage = null; Charset charset = null; // Retain the original name used to set the charset so exactly that name is // used in the ContentType header. Some (arguably non-specification // compliant) user agents are very particular String characterEncoding = null; long contentLength = -1; private Locale locale = DEFAULT_LOCALE; // General information private long contentWritten = 0; private long commitTimeNanos = -1; /** * Holds response writing error exception. */ private Exception errorException = null; /** * With the introduction of async processing and the possibility of * non-container threads calling sendError() tracking the current error * state and ensuring that the correct error page is called becomes more * complicated. This state attribute helps by tracking the current error * state and informing callers that attempt to change state if the change * was successful or if another thread got there first. * * <pre> * The state machine is very simple: * * 0 - NONE * 1 - NOT_REPORTED * 2 - REPORTED * * * -->---->-- >NONE * | | | * | | | setError() * ^ ^ | * | | \|/ * | |-<-NOT_REPORTED * | | * ^ | report() * | | * | \|/ * |----<----REPORTED * </pre> */ private final AtomicInteger errorState = new AtomicInteger(0); Request req; // ------------------------------------------------------------- Properties public Request getRequest() { return req; } public void setRequest( Request req ) { this.req=req; } public void setOutputBuffer(OutputBuffer outputBuffer) { this.outputBuffer = outputBuffer; } public MimeHeaders getMimeHeaders() { return headers; } protected void setHook(ActionHook hook) { this.hook = hook; } // -------------------- Per-Response "notes" -------------------- public final void setNote(int pos, Object value) { notes[pos] = value; } public final Object getNote(int pos) { return notes[pos]; } // -------------------- Actions -------------------- public void action(ActionCode actionCode, Object param) { if (hook != null) { if (param == null) { hook.action(actionCode, this); } else { hook.action(actionCode, param); } } } // -------------------- State -------------------- public int getStatus() { return status; } /** * Set the response status. * * @param status The status value to set */ public void setStatus(int status) { this.status = status; } /** * Get the status message. * * @return The message associated with the current status */ public String getMessage() { return message; } /** * Set the status message. * * @param message The status message to set */ public void setMessage(String message) { this.message = message; } public boolean isCommitted() { return committed; } public void setCommitted(boolean v) { if (v && !this.committed) { this.commitTimeNanos = System.nanoTime(); } this.committed = v; } /** * Return the time the response was committed (based on System.currentTimeMillis). * * @return the time the response was committed */ public long getCommitTime() { return System.currentTimeMillis() - TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - commitTimeNanos); } /** * Return the time the response was committed (based on System.nanoTime). * * @return the time the response was committed */ public long getCommitTimeNanos() { return commitTimeNanos; } // -----------------Error State -------------------- /** * Set the error Exception that occurred during the writing of the response * processing. * * @param ex The exception that occurred */ public void setErrorException(Exception ex) { errorException = ex; } /** * Get the Exception that occurred during the writing of the response. * * @return The exception that occurred */ public Exception getErrorException() { return errorException; } public boolean isExceptionPresent() { return errorException != null; } /** * Set the error flag. * * @return <code>false</code> if the error flag was already set */ public boolean setError() { return errorState.compareAndSet(0, 1); } /** * Error flag accessor. * * @return <code>true</code> if the response has encountered an error */ public boolean isError() { return errorState.get() > 0; } public boolean isErrorReportRequired() { return errorState.get() == 1; } public boolean setErrorReported() { return errorState.compareAndSet(1, 2); } // -------------------- Methods -------------------- public void reset() throws IllegalStateException { if (committed) { throw new IllegalStateException(); } recycle(); } // -------------------- Headers<SUF> /** * Does the response contain the given header. * <br> * Warning: This method always returns <code>false</code> for Content-Type * and Content-Length. * * @param name The name of the header of interest * * @return {@code true} if the response contains the header. */ public boolean containsHeader(String name) { return headers.getHeader(name) != null; } public void setHeader(String name, String value) { char cc=name.charAt(0); if( cc=='C' || cc=='c' ) { if( checkSpecialHeader(name, value) ) { return; } } headers.setValue(name).setString( value); } public void addHeader(String name, String value) { addHeader(name, value, null); } public void addHeader(String name, String value, Charset charset) { char cc=name.charAt(0); if( cc=='C' || cc=='c' ) { if( checkSpecialHeader(name, value) ) { return; } } MessageBytes mb = headers.addValue(name); if (charset != null) { mb.setCharset(charset); } mb.setString(value); } public void setTrailerFields(Supplier<Map<String, String>> supplier) { AtomicBoolean trailerFieldsSupported = new AtomicBoolean(false); action(ActionCode.IS_TRAILER_FIELDS_SUPPORTED, trailerFieldsSupported); if (!trailerFieldsSupported.get()) { throw new IllegalStateException(sm.getString("response.noTrailers.notSupported")); } this.trailerFieldsSupplier = supplier; } public Supplier<Map<String, String>> getTrailerFields() { return trailerFieldsSupplier; } /** * Set internal fields for special header names. * Called from set/addHeader. * Return true if the header is special, no need to set the header. */ private boolean checkSpecialHeader( String name, String value) { // XXX Eliminate redundant fields !!! // ( both header and in special fields ) if( name.equalsIgnoreCase( "Content-Type" ) ) { setContentType( value ); return true; } if( name.equalsIgnoreCase( "Content-Length" ) ) { try { long cL=Long.parseLong( value ); setContentLength( cL ); return true; } catch( NumberFormatException ex ) { // Do nothing - the spec doesn't have any "throws" // and the user might know what they're doing return false; } } return false; } /** Signal that we're done with the headers, and body will follow. * Any implementation needs to notify ContextManager, to allow * interceptors to fix headers. */ public void sendHeaders() { action(ActionCode.COMMIT, this); setCommitted(true); } // -------------------- I18N -------------------- public Locale getLocale() { return locale; } /** * Called explicitly by user to set the Content-Language and the default * encoding. * * @param locale The locale to use for this response */ public void setLocale(Locale locale) { if (locale == null) { this.locale = null; this.contentLanguage = null; return; } // Save the locale for use by getLocale() this.locale = locale; // Set the contentLanguage for header output contentLanguage = locale.toLanguageTag(); } /** * Return the content language. * * @return The language code for the language currently associated with this * response */ public String getContentLanguage() { return contentLanguage; } /** * Overrides the character encoding used in the body of the response. This * method must be called prior to writing output using getWriter(). * * @param characterEncoding The name of character encoding. * * @throws UnsupportedEncodingException If the specified name is not * recognised */ public void setCharacterEncoding(String characterEncoding) throws UnsupportedEncodingException { if (isCommitted()) { return; } if (characterEncoding == null) { this.charset = null; this.characterEncoding = null; return; } this.characterEncoding = characterEncoding; this.charset = B2CConverter.getCharset(characterEncoding); } public Charset getCharset() { return charset; } /** * @return The name of the current encoding */ public String getCharacterEncoding() { return characterEncoding; } /** * Sets the content type. * * This method must preserve any response charset that may already have * been set via a call to response.setContentType(), response.setLocale(), * or response.setCharacterEncoding(). * * @param type the content type */ public void setContentType(String type) { if (type == null) { this.contentType = null; return; } MediaType m = null; try { m = MediaType.parseMediaType(new StringReader(type)); } catch (IOException e) { // Ignore - null test below handles this } if (m == null) { // Invalid - Assume no charset and just pass through whatever // the user provided. this.contentType = type; return; } this.contentType = m.toStringNoCharset(); String charsetValue = m.getCharset(); if (charsetValue == null) { // No charset and we know value is valid as parser was successful // Pass-through user provided value in case user-agent is buggy and // requires specific format this.contentType = type; } else { // There is a charset so have to rebuild content-type without it this.contentType = m.toStringNoCharset(); charsetValue = charsetValue.trim(); if (charsetValue.length() > 0) { try { charset = B2CConverter.getCharset(charsetValue); } catch (UnsupportedEncodingException e) { log.warn(sm.getString("response.encoding.invalid", charsetValue), e); } } } } public void setContentTypeNoCharset(String type) { this.contentType = type; } public String getContentType() { String ret = contentType; if (ret != null && charset != null) { ret = ret + ";charset=" + characterEncoding; } return ret; } public void setContentLength(long contentLength) { this.contentLength = contentLength; } public int getContentLength() { long length = getContentLengthLong(); if (length < Integer.MAX_VALUE) { return (int) length; } return -1; } public long getContentLengthLong() { return contentLength; } /** * Write a chunk of bytes. * * @param chunk The ByteBuffer to write * * @throws IOException If an I/O error occurs during the write */ public void doWrite(ByteBuffer chunk) throws IOException { int len = chunk.remaining(); outputBuffer.doWrite(chunk); contentWritten += len - chunk.remaining(); } // -------------------- public void recycle() { contentType = null; contentLanguage = null; locale = DEFAULT_LOCALE; charset = null; characterEncoding = null; contentLength = -1; status = 200; message = null; committed = false; commitTimeNanos = -1; errorException = null; errorState.set(0); headers.clear(); trailerFieldsSupplier = null; // Servlet 3.1 non-blocking write listener listener = null; synchronized (nonBlockingStateLock) { fireListener = false; registeredForWrite = false; } // update counters contentWritten=0; } /** * Bytes written by application - i.e. before compression, chunking, etc. * * @return The total number of bytes written to the response by the * application. This will not be the number of bytes written to the * network which may be more or less than this value. */ public long getContentWritten() { return contentWritten; } /** * Bytes written to socket - i.e. after compression, chunking, etc. * * @param flush Should any remaining bytes be flushed before returning the * total? If {@code false} bytes remaining in the buffer will * not be included in the returned value * * @return The total number of bytes written to the socket for this response */ public long getBytesWritten(boolean flush) { if (flush) { action(ActionCode.CLIENT_FLUSH, this); } return outputBuffer.getBytesWritten(); } /* * State for non-blocking output is maintained here as it is the one point * easily reachable from the CoyoteOutputStream and the Processor which both * need access to state. */ volatile WriteListener listener; // Ensures listener is only fired after a call is isReady() private boolean fireListener = false; // Tracks write registration to prevent duplicate registrations private boolean registeredForWrite = false; // Lock used to manage concurrent access to above flags private final Object nonBlockingStateLock = new Object(); public WriteListener getWriteListener() { return listener; } public void setWriteListener(WriteListener listener) { if (listener == null) { throw new NullPointerException( sm.getString("response.nullWriteListener")); } if (getWriteListener() != null) { throw new IllegalStateException( sm.getString("response.writeListenerSet")); } // Note: This class is not used for HTTP upgrade so only need to test // for async AtomicBoolean result = new AtomicBoolean(false); action(ActionCode.ASYNC_IS_ASYNC, result); if (!result.get()) { throw new IllegalStateException( sm.getString("response.notAsync")); } this.listener = listener; // The container is responsible for the first call to // listener.onWritePossible(). If isReady() returns true, the container // needs to call listener.onWritePossible() from a new thread. If // isReady() returns false, the socket will be registered for write and // the container will call listener.onWritePossible() once data can be // written. if (isReady()) { synchronized (nonBlockingStateLock) { // Ensure we don't get multiple write registrations if // ServletOutputStream.isReady() returns false during a call to // onDataAvailable() registeredForWrite = true; // Need to set the fireListener flag otherwise when the // container tries to trigger onWritePossible, nothing will // happen fireListener = true; } action(ActionCode.DISPATCH_WRITE, null); if (!req.isRequestThread()) { // Not on a container thread so need to execute the dispatch action(ActionCode.DISPATCH_EXECUTE, null); } } } public boolean isReady() { if (listener == null) { return true; } // Assume write is not possible boolean ready = false; synchronized (nonBlockingStateLock) { if (registeredForWrite) { fireListener = true; return false; } ready = checkRegisterForWrite(); fireListener = !ready; } return ready; } public boolean checkRegisterForWrite() { AtomicBoolean ready = new AtomicBoolean(false); synchronized (nonBlockingStateLock) { if (!registeredForWrite) { action(ActionCode.NB_WRITE_INTEREST, ready); registeredForWrite = !ready.get(); } } return ready.get(); } public void onWritePossible() throws IOException { // Any buffered data left over from a previous non-blocking write is // written in the Processor so if this point is reached the app is able // to write data. boolean fire = false; synchronized (nonBlockingStateLock) { registeredForWrite = false; if (fireListener) { fireListener = false; fire = true; } } if (fire) { listener.onWritePossible(); } } }
175730_17
package org.dspace.workflow; import org.apache.log4j.Logger; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.authorize.ResourcePolicy; import org.dspace.content.*; import org.dspace.core.*; import org.dspace.eperson.EPerson; import org.dspace.handle.HandleManager; import org.dspace.storage.rdbms.DatabaseManager; import org.dspace.storage.rdbms.TableRow; import org.dspace.workflow.actions.Action; import org.dspace.workflow.actions.ActionResult; import org.dspace.workflow.actions.WorkflowActionConfig; import javax.mail.MessagingException; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.MissingResourceException; /** * Created by IntelliJ IDEA. * User: bram * Date: 2-aug-2010 * Time: 17:32:44 * To change this template use File | Settings | File Templates. */ public class WorkflowManager { private static Logger log = Logger.getLogger(WorkflowManager.class); public static void start(Context context, WorkspaceItem wsi) throws SQLException, AuthorizeException, IOException, WorkflowConfigurationException, MessagingException, WorkflowException { Item myitem = wsi.getItem(); Collection collection = wsi.getCollection(); Workflow wf = WorkflowFactory.getWorkflow(collection); TableRow row = DatabaseManager.create(context, "workflowitem"); row.setColumn("item_id", myitem.getID()); row.setColumn("collection_id", wsi.getCollection().getID()); WorkflowItem wfi = new WorkflowItem(context, row); wfi.setMultipleFiles(wsi.hasMultipleFiles()); wfi.setMultipleTitles(wsi.hasMultipleTitles()); wfi.setPublishedBefore(wsi.isPublishedBefore()); wfi.update(); Step firstStep = wf.getFirstStep(); if(firstStep.isValidStep(context, wfi)){ activateFirstStep(context, wf, firstStep, wfi); } else { //Get our next step, if none is found, archive our item firstStep = wf.getNextStep(context, wfi, firstStep, ActionResult.OUTCOME_COMPLETE); if(firstStep == null){ archive(context, wfi); }else{ activateFirstStep(context, wf, firstStep, wfi); } } // remove the WorkspaceItem wsi.deleteWrapper(); } private static void activateFirstStep(Context context, Workflow wf, Step firstStep, WorkflowItem wfi) throws AuthorizeException, IOException, SQLException, WorkflowException, WorkflowConfigurationException{ WorkflowActionConfig firstActionConfig = firstStep.getUserSelectionMethod(); firstActionConfig.getProcessingAction().activate(context, wfi); log.info(LogManager.getHeader(context, "start_workflow", firstActionConfig.getProcessingAction() + " workflow_item_id=" + wfi.getID() + "item_id=" + wfi.getItem().getID() + "collection_id=" + wfi.getCollection().getID())); // record the start of the workflow w/provenance message recordStart(wfi.getItem(), firstActionConfig.getProcessingAction()); //If we don't have a UI activate it if(!firstActionConfig.hasUserInterface()){ ActionResult outcome = firstActionConfig.getProcessingAction().execute(context, wfi, firstStep, null); processOutcome(context, null, wf, firstStep, firstActionConfig, outcome, wfi); } } /* * Executes an action and returns the next. */ public static WorkflowActionConfig doState(Context c, EPerson user, HttpServletRequest request, int workflowItemId, Workflow workflow, WorkflowActionConfig currentActionConfig) throws SQLException, AuthorizeException, IOException, MessagingException, WorkflowConfigurationException, WorkflowException { try { WorkflowItem wi = WorkflowItem.find(c, workflowItemId); Step currentStep = currentActionConfig.getStep(); ActionResult outcome = currentActionConfig.getProcessingAction().execute(c, wi, currentStep, request); return processOutcome(c, user, workflow, currentStep, currentActionConfig, outcome, wi); } catch (WorkflowConfigurationException e) { log.error(LogManager.getHeader(c, "error while executing state", "workflow: " + workflow.getID() + " action: " + currentActionConfig.getId() + " workflowItemId: " + workflowItemId), e); WorkflowUtils.sendAlert(request, e); throw e; } } public static WorkflowActionConfig processOutcome(Context c, EPerson user, Workflow workflow, Step currentStep, WorkflowActionConfig currentActionConfig, ActionResult currentOutcome, WorkflowItem wfi) throws IOException, WorkflowConfigurationException, AuthorizeException, SQLException, WorkflowException { if(currentOutcome.getType() == ActionResult.TYPE.TYPE_PAGE || currentOutcome.getType() == ActionResult.TYPE.TYPE_ERROR){ //Our outcome is a page or an error, so return our current action return currentActionConfig; }else if(currentOutcome.getType() == ActionResult.TYPE.TYPE_CANCEL || currentOutcome.getType() == ActionResult.TYPE.TYPE_SUBMISSION_PAGE){ //We either pressed the cancel button or got an order to return to the submission page, so don't return an action //By not returning an action we ensure ourselfs that we go back to the submission page return null; }else if (currentOutcome.getType() == ActionResult.TYPE.TYPE_OUTCOME) { //We have completed our action search & retrieve the next action WorkflowActionConfig nextActionConfig = null; if(currentOutcome.getResult() == ActionResult.OUTCOME_COMPLETE){ nextActionConfig = currentStep.getNextAction(currentActionConfig); } if (nextActionConfig != null) { nextActionConfig.getProcessingAction().activate(c, wfi); if (nextActionConfig.hasUserInterface()) { //TODO: if user is null, then throw a decent exception ! createOwnedTask(c, wfi, currentStep, nextActionConfig, user); return nextActionConfig; } else { ActionResult newOutcome = nextActionConfig.getProcessingAction().execute(c, wfi, currentStep, null); return processOutcome(c, user, workflow, currentStep, nextActionConfig, newOutcome, wfi); } }else{ //First add it to our list of finished users, since no more actions remain WorkflowRequirementsManager.addFinishedUser(c, wfi, user); c.turnOffAuthorisationSystem(); //Check if our requirements have been met if((currentStep.isFinished(wfi) && currentOutcome.getResult() == ActionResult.OUTCOME_COMPLETE) || currentOutcome.getResult() != ActionResult.OUTCOME_COMPLETE){ //Clear all the metadata that might be saved by this step WorkflowRequirementsManager.clearStepMetadata(wfi); //Remove all the tasks WorkflowManager.deleteAllTasks(c, wfi); Step nextStep = workflow.getNextStep(c, wfi, currentStep, currentOutcome.getResult()); if(nextStep!=null){ //TODO: is generate tasks nog nodig of kan dit mee in activate? //TODO: vorige step zou meegegeven moeten worden om evt rollen te kunnen overnemen nextActionConfig = nextStep.getUserSelectionMethod(); nextActionConfig.getProcessingAction().activate(c, wfi); // nextActionConfig.getProcessingAction().generateTasks(); //Deze kunnen afhangen van de step (rol, min, max, ...). Evt verantwoordelijkheid bij userassignmentaction leggen if (nextActionConfig.hasUserInterface()) { //Since a new step has been started, stop executing actions once one with a user interface is present. c.restoreAuthSystemState(); return null; } else { ActionResult newOutcome = nextActionConfig.getProcessingAction().execute(c, wfi, nextStep, null); c.restoreAuthSystemState(); return processOutcome(c, user, workflow, nextStep, nextActionConfig, newOutcome, wfi); } }else{ if(currentOutcome.getResult() != ActionResult.OUTCOME_COMPLETE){ c.restoreAuthSystemState(); throw new WorkflowException("No alternate step was found for outcome: " + currentOutcome.getResult()); } archive(c, wfi); c.restoreAuthSystemState(); return null; } }else{ //We are done with our actions so go to the submissions page c.restoreAuthSystemState(); return null; } } } //TODO: log & go back to submission, We should not come here //TODO: remove assertion - can be used for testing (will throw assertionexception) assert false; return null; } //TODO: nakijken /** * Commit the contained item to the main archive. The item is associated * with the relevant collection, added to the search index, and any other * tasks such as assigning dates are performed. * * @return the fully archived item. */ public static Item archive(Context c, WorkflowItem wfi) throws SQLException, IOException, AuthorizeException { // FIXME: Check auth Item item = wfi.getItem(); Collection collection = wfi.getCollection(); // Remove (if any) the workflowItemroles for this item WorkflowItemRole[] workflowItemRoles = WorkflowItemRole.findAllForItem(c, wfi.getID()); for (WorkflowItemRole workflowItemRole : workflowItemRoles) { workflowItemRole.delete(); } log.info(LogManager.getHeader(c, "archive_item", "workflow_item_id=" + wfi.getID() + "item_id=" + item.getID() + "collection_id=" + collection.getID())); InstallItem.installItem(c, wfi); //Notify notifyOfArchive(c, item, collection); // Log the event log.info(LogManager.getHeader(c, "install_item", "workflow_item_id=" + wfi.getID() + ", item_id=" + item.getID() + "handle=FIXME")); return item; } //TODO: nakijken - altijd submitter mailen of config optie? /** * notify the submitter that the item is archived */ private static void notifyOfArchive(Context c, Item i, Collection coll) throws SQLException, IOException { try { // Get submitter EPerson ep = i.getSubmitter(); // Get the Locale Locale supportedLocale = I18nUtil.getEPersonLocale(ep); Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(supportedLocale, "submit_archive")); // Get the item handle to email to user String handle = HandleManager.findHandle(c, i); // Get title DCValue[] titles = i.getDC("title", null, Item.ANY); String title = ""; try { title = I18nUtil.getMessage("org.dspace.workflow.WorkflowManager.untitled"); } catch (MissingResourceException e) { title = "Untitled"; } if (titles.length > 0) { title = titles[0].value; } email.addRecipient(ep.getEmail()); email.addArgument(title); email.addArgument(coll.getMetadata("name")); email.addArgument(HandleManager.getCanonicalForm(handle)); email.send(); } catch (MessagingException e) { log.warn(LogManager.getHeader(c, "notifyOfArchive", "cannot email user" + " item_id=" + i.getID())); } } /*********************************** * WORKFLOW TASK MANAGEMENT **********************************/ /** * Deletes all tasks from this workflowflowitem * @param c the dspace context * @param wi the workflow item for whom we are to delete the tasks * @throws SQLException ... * @throws org.dspace.authorize.AuthorizeException ... */ public static void deleteAllTasks(Context c, WorkflowItem wi) throws SQLException, AuthorizeException { deleteAllPooledTasks(c, wi); List<ClaimedTask> allClaimedTasks = ClaimedTask.findByWorkflowId(c,wi.getID()); for(ClaimedTask task: allClaimedTasks){ deleteClaimedTask(c, wi, task); } } public static void deleteAllPooledTasks(Context c, WorkflowItem wi) throws SQLException, AuthorizeException { List<PoolTask> allPooledTasks = PoolTask.find(c, wi); for (PoolTask poolTask : allPooledTasks) { deletePooledTask(c, wi, poolTask); } } /* * Deletes an eperson from the taskpool of a step */ public static void deletePooledTask(Context c, WorkflowItem wi, PoolTask task) throws SQLException, AuthorizeException { if(task != null){ task.delete(); removeUserItemPolicies(c, wi.getItem(), EPerson.find(c, task.getEpersonID())); } } public static void deleteClaimedTask(Context c, WorkflowItem wi, ClaimedTask task) throws SQLException, AuthorizeException { if(task != null){ task.delete(); removeUserItemPolicies(c, wi.getItem(), EPerson.find(c, task.getOwnerID())); } } /* * Creates a task pool for a given step */ public static void createPoolTasks(Context context, WorkflowItem wi, EPerson[] epa, Step step, WorkflowActionConfig action) throws SQLException, AuthorizeException { // create a tasklist entry for each eperson for (EPerson anEpa : epa) { PoolTask task = PoolTask.create(context); task.setStepID(step.getId()); task.setWorkflowID(step.getWorkflow().getID()); task.setEpersonID(anEpa.getID()); task.setActionID(action.getId()); task.setWorkflowItemID(wi.getID()); task.update(); //Make sure this user has a task grantUserAllItemPolicies(context, wi.getItem(), anEpa); } } /* * Claims an action for a given eperson */ public static void createOwnedTask(Context c, WorkflowItem wi, Step step, WorkflowActionConfig action, EPerson e) throws SQLException, AuthorizeException { ClaimedTask task = ClaimedTask.create(c); task.setWorkflowItemID(wi.getID()); task.setStepID(step.getId()); task.setActionID(action.getId()); task.setOwnerID(e.getID()); task.setWorkflowID(step.getWorkflow().getID()); task.update(); //Make sure this user has a task grantUserAllItemPolicies(c, wi.getItem(), e); } private static void grantUserAllItemPolicies(Context context, Item item, EPerson epa) throws AuthorizeException, SQLException { //A list of policies the user has for this item List<Integer> userHasPolicies = new ArrayList<Integer>(); List<ResourcePolicy> itempols = AuthorizeManager.getPolicies(context, item); for (ResourcePolicy resourcePolicy : itempols) { if(resourcePolicy.getEPersonID() == epa.getID()){ //The user has already got this policy so it it to the list userHasPolicies.add(resourcePolicy.getAction()); } } //Make sure we don't add duplicate policies if(!userHasPolicies.contains(Constants.READ)) addPolicyToItem(context, item, Constants.READ, epa); if(!userHasPolicies.contains(Constants.WRITE)) addPolicyToItem(context, item, Constants.WRITE, epa); if(!userHasPolicies.contains(Constants.DELETE)) addPolicyToItem(context, item, Constants.DELETE, epa); if(!userHasPolicies.contains(Constants.ADD)) addPolicyToItem(context, item, Constants.ADD, epa); } private static void addPolicyToItem(Context context, Item item, int type, EPerson epa) throws AuthorizeException, SQLException { AuthorizeManager.addPolicy(context ,item, type, epa); Bundle[] bundles = item.getBundles(); for (Bundle bundle : bundles) { AuthorizeManager.addPolicy(context ,bundle, type, epa); Bitstream[] bits = bundle.getBitstreams(); for (Bitstream bit : bits) { AuthorizeManager.addPolicy(context, bit, type, epa); } } } private static void removeUserItemPolicies(Context context, Item item, EPerson e) throws SQLException, AuthorizeException { //Also remove any lingering authorizations from this user removePoliciesFromDso(context, item, e); //Remove the bundle rights Bundle[] bundles = item.getBundles(); for (Bundle bundle : bundles) { removePoliciesFromDso(context, bundle, e); Bitstream[] bitstreams = bundle.getBitstreams(); for (Bitstream bitstream : bitstreams) { removePoliciesFromDso(context, bitstream, e); } } } private static void removePoliciesFromDso(Context context, DSpaceObject item, EPerson e) throws SQLException, AuthorizeException { List<ResourcePolicy> policies = AuthorizeManager.getPolicies(context, item); AuthorizeManager.removeAllPolicies(context, item); for (ResourcePolicy resourcePolicy : policies) { if( resourcePolicy.getEPerson() ==null || resourcePolicy.getEPersonID() != e.getID()){ if(resourcePolicy.getEPerson() != null) AuthorizeManager.addPolicy(context, item, resourcePolicy.getAction(), resourcePolicy.getEPerson()); else AuthorizeManager.addPolicy(context, item, resourcePolicy.getAction(), resourcePolicy.getGroup()); } } } /** * rejects an item - rejection means undoing a submit - WorkspaceItem is * created, and the WorkflowItem is removed, user is emailed * rejection_message. * * @param c * Context * @param wi * WorkflowItem to operate on * @param e * EPerson doing the operation * @param action the action which triggered this reject * @param rejection_message * message to email to user * @return the workspace item that is created * @throws java.io.IOException ... * @throws java.sql.SQLException ... * @throws org.dspace.authorize.AuthorizeException ... */ public static WorkspaceItem rejectWorkflowItem(Context c, WorkflowItem wi, EPerson e, Action action, String rejection_message) throws SQLException, AuthorizeException, IOException { // authorize a DSpaceActions.REJECT // stop workflow deleteAllTasks(c, wi); //Also clear all info for this step WorkflowRequirementsManager.clearStepMetadata(wi); // Remove (if any) the workflowItemroles for this item WorkflowItemRole[] workflowItemRoles = WorkflowItemRole.findAllForItem(c, wi.getID()); for (WorkflowItemRole workflowItemRole : workflowItemRoles) { workflowItemRole.delete(); } // rejection provenance Item myitem = wi.getItem(); // Get current date String now = DCDate.getCurrent().toString(); // Get user's name + email address String usersName = getEPersonName(e); // Here's what happened String provDescription = action.getProvenanceStartId() + " Rejected by " + usersName + ", reason: " + rejection_message + " on " + now + " (GMT) "; // Add to item as a DC field myitem.addMetadata(MetadataSchema.DC_SCHEMA, "description", "provenance", "en", provDescription); myitem.update(); //TODO: MAKE SURE THAT SUBMITTER GETS PROPER RIGHTS // convert into personal workspace WorkspaceItem wsi = returnToWorkspace(c, wi); // notify that it's been rejected notifyOfReject(c, wi, e, rejection_message); log.info(LogManager.getHeader(c, "reject_workflow", "workflow_item_id=" + wi.getID() + "item_id=" + wi.getItem().getID() + "collection_id=" + wi.getCollection().getID() + "eperson_id=" + e.getID())); return wsi; } /** * Return the workflow item to the workspace of the submitter. The workflow * item is removed, and a workspace item created. * * @param c * Context * @param wfi * WorkflowItem to be 'dismantled' * @return the workspace item * @throws java.io.IOException ... * @throws java.sql.SQLException ... * @throws org.dspace.authorize.AuthorizeException ... */ private static WorkspaceItem returnToWorkspace(Context c, WorkflowItem wfi) throws SQLException, IOException, AuthorizeException { Item myitem = wfi.getItem(); Collection myCollection = wfi.getCollection(); // FIXME: How should this interact with the workflow system? // FIXME: Remove license // FIXME: Provenance statement? // Create the new workspace item row TableRow row = DatabaseManager.create(c, "workspaceitem"); row.setColumn("item_id", myitem.getID()); row.setColumn("collection_id", myCollection.getID()); DatabaseManager.update(c, row); int wsi_id = row.getIntColumn("workspace_item_id"); WorkspaceItem wi = WorkspaceItem.find(c, wsi_id); wi.setMultipleFiles(wfi.hasMultipleFiles()); wi.setMultipleTitles(wfi.hasMultipleTitles()); wi.setPublishedBefore(wfi.isPublishedBefore()); wi.update(); //myitem.update(); log.info(LogManager.getHeader(c, "return_to_workspace", "workflow_item_id=" + wfi.getID() + "workspace_item_id=" + wi.getID())); // Now remove the workflow object manually from the database DatabaseManager.updateQuery(c, "DELETE FROM WorkflowItem WHERE workflow_id=" + wfi.getID()); return wi; } public static String getEPersonName(EPerson e) throws SQLException { String submitter = e.getFullName(); submitter = submitter + "(" + e.getEmail() + ")"; return submitter; } // Create workflow start provenance message private static void recordStart(Item myitem, Action action) throws SQLException, IOException, AuthorizeException { // get date DCDate now = DCDate.getCurrent(); // Create provenance description String provmessage = ""; if (myitem.getSubmitter() != null) { provmessage = "Submitted by " + myitem.getSubmitter().getFullName() + " (" + myitem.getSubmitter().getEmail() + ") on " + now.toString() + " workflow start=" + action.getProvenanceStartId() + "\n"; } else // null submitter { provmessage = "Submitted by unknown (probably automated) on" + now.toString() + " workflow start=" + action.getProvenanceStartId() + "\n"; } // add sizes and checksums of bitstreams provmessage += InstallItem.getBitstreamProvenanceMessage(myitem); // Add message to the DC myitem.addMetadata(MetadataSchema.DC_SCHEMA, "description", "provenance", "en", provmessage); myitem.update(); } private static void notifyOfReject(Context c, WorkflowItem wi, EPerson e, String reason) { try { // Get the item title String title = wi.getItem().getName(); // Get the collection Collection coll = wi.getCollection(); // Get rejector's name String rejector = getEPersonName(e); Locale supportedLocale = I18nUtil.getEPersonLocale(e); Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(supportedLocale,"submit_reject")); email.addRecipient(wi.getSubmitter().getEmail()); email.addArgument(title); email.addArgument(coll.getMetadata("name")); email.addArgument(rejector); email.addArgument(reason); email.addArgument(ConfigurationManager.getProperty("dspace.url") + "/mydspace"); email.send(); } catch (Exception ex) { // log this email error log.warn(LogManager.getHeader(c, "notify_of_reject", "cannot email user" + " eperson_id" + e.getID() + " eperson_email" + e.getEmail() + " workflow_item_id" + wi.getID())); } } public static String getMyDSpaceLink() { return ConfigurationManager.getProperty("dspace.url") + "/mydspace"; } }
CottageLabs/dryad-repo
dspace/modules/atmire-workflow/atmire-workflow-api/src/main/java/org/dspace/workflow/WorkflowManager.java
7,012
//Deze kunnen afhangen van de step (rol, min, max, ...). Evt verantwoordelijkheid bij userassignmentaction leggen
line_comment
nl
package org.dspace.workflow; import org.apache.log4j.Logger; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.authorize.ResourcePolicy; import org.dspace.content.*; import org.dspace.core.*; import org.dspace.eperson.EPerson; import org.dspace.handle.HandleManager; import org.dspace.storage.rdbms.DatabaseManager; import org.dspace.storage.rdbms.TableRow; import org.dspace.workflow.actions.Action; import org.dspace.workflow.actions.ActionResult; import org.dspace.workflow.actions.WorkflowActionConfig; import javax.mail.MessagingException; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.MissingResourceException; /** * Created by IntelliJ IDEA. * User: bram * Date: 2-aug-2010 * Time: 17:32:44 * To change this template use File | Settings | File Templates. */ public class WorkflowManager { private static Logger log = Logger.getLogger(WorkflowManager.class); public static void start(Context context, WorkspaceItem wsi) throws SQLException, AuthorizeException, IOException, WorkflowConfigurationException, MessagingException, WorkflowException { Item myitem = wsi.getItem(); Collection collection = wsi.getCollection(); Workflow wf = WorkflowFactory.getWorkflow(collection); TableRow row = DatabaseManager.create(context, "workflowitem"); row.setColumn("item_id", myitem.getID()); row.setColumn("collection_id", wsi.getCollection().getID()); WorkflowItem wfi = new WorkflowItem(context, row); wfi.setMultipleFiles(wsi.hasMultipleFiles()); wfi.setMultipleTitles(wsi.hasMultipleTitles()); wfi.setPublishedBefore(wsi.isPublishedBefore()); wfi.update(); Step firstStep = wf.getFirstStep(); if(firstStep.isValidStep(context, wfi)){ activateFirstStep(context, wf, firstStep, wfi); } else { //Get our next step, if none is found, archive our item firstStep = wf.getNextStep(context, wfi, firstStep, ActionResult.OUTCOME_COMPLETE); if(firstStep == null){ archive(context, wfi); }else{ activateFirstStep(context, wf, firstStep, wfi); } } // remove the WorkspaceItem wsi.deleteWrapper(); } private static void activateFirstStep(Context context, Workflow wf, Step firstStep, WorkflowItem wfi) throws AuthorizeException, IOException, SQLException, WorkflowException, WorkflowConfigurationException{ WorkflowActionConfig firstActionConfig = firstStep.getUserSelectionMethod(); firstActionConfig.getProcessingAction().activate(context, wfi); log.info(LogManager.getHeader(context, "start_workflow", firstActionConfig.getProcessingAction() + " workflow_item_id=" + wfi.getID() + "item_id=" + wfi.getItem().getID() + "collection_id=" + wfi.getCollection().getID())); // record the start of the workflow w/provenance message recordStart(wfi.getItem(), firstActionConfig.getProcessingAction()); //If we don't have a UI activate it if(!firstActionConfig.hasUserInterface()){ ActionResult outcome = firstActionConfig.getProcessingAction().execute(context, wfi, firstStep, null); processOutcome(context, null, wf, firstStep, firstActionConfig, outcome, wfi); } } /* * Executes an action and returns the next. */ public static WorkflowActionConfig doState(Context c, EPerson user, HttpServletRequest request, int workflowItemId, Workflow workflow, WorkflowActionConfig currentActionConfig) throws SQLException, AuthorizeException, IOException, MessagingException, WorkflowConfigurationException, WorkflowException { try { WorkflowItem wi = WorkflowItem.find(c, workflowItemId); Step currentStep = currentActionConfig.getStep(); ActionResult outcome = currentActionConfig.getProcessingAction().execute(c, wi, currentStep, request); return processOutcome(c, user, workflow, currentStep, currentActionConfig, outcome, wi); } catch (WorkflowConfigurationException e) { log.error(LogManager.getHeader(c, "error while executing state", "workflow: " + workflow.getID() + " action: " + currentActionConfig.getId() + " workflowItemId: " + workflowItemId), e); WorkflowUtils.sendAlert(request, e); throw e; } } public static WorkflowActionConfig processOutcome(Context c, EPerson user, Workflow workflow, Step currentStep, WorkflowActionConfig currentActionConfig, ActionResult currentOutcome, WorkflowItem wfi) throws IOException, WorkflowConfigurationException, AuthorizeException, SQLException, WorkflowException { if(currentOutcome.getType() == ActionResult.TYPE.TYPE_PAGE || currentOutcome.getType() == ActionResult.TYPE.TYPE_ERROR){ //Our outcome is a page or an error, so return our current action return currentActionConfig; }else if(currentOutcome.getType() == ActionResult.TYPE.TYPE_CANCEL || currentOutcome.getType() == ActionResult.TYPE.TYPE_SUBMISSION_PAGE){ //We either pressed the cancel button or got an order to return to the submission page, so don't return an action //By not returning an action we ensure ourselfs that we go back to the submission page return null; }else if (currentOutcome.getType() == ActionResult.TYPE.TYPE_OUTCOME) { //We have completed our action search & retrieve the next action WorkflowActionConfig nextActionConfig = null; if(currentOutcome.getResult() == ActionResult.OUTCOME_COMPLETE){ nextActionConfig = currentStep.getNextAction(currentActionConfig); } if (nextActionConfig != null) { nextActionConfig.getProcessingAction().activate(c, wfi); if (nextActionConfig.hasUserInterface()) { //TODO: if user is null, then throw a decent exception ! createOwnedTask(c, wfi, currentStep, nextActionConfig, user); return nextActionConfig; } else { ActionResult newOutcome = nextActionConfig.getProcessingAction().execute(c, wfi, currentStep, null); return processOutcome(c, user, workflow, currentStep, nextActionConfig, newOutcome, wfi); } }else{ //First add it to our list of finished users, since no more actions remain WorkflowRequirementsManager.addFinishedUser(c, wfi, user); c.turnOffAuthorisationSystem(); //Check if our requirements have been met if((currentStep.isFinished(wfi) && currentOutcome.getResult() == ActionResult.OUTCOME_COMPLETE) || currentOutcome.getResult() != ActionResult.OUTCOME_COMPLETE){ //Clear all the metadata that might be saved by this step WorkflowRequirementsManager.clearStepMetadata(wfi); //Remove all the tasks WorkflowManager.deleteAllTasks(c, wfi); Step nextStep = workflow.getNextStep(c, wfi, currentStep, currentOutcome.getResult()); if(nextStep!=null){ //TODO: is generate tasks nog nodig of kan dit mee in activate? //TODO: vorige step zou meegegeven moeten worden om evt rollen te kunnen overnemen nextActionConfig = nextStep.getUserSelectionMethod(); nextActionConfig.getProcessingAction().activate(c, wfi); // nextActionConfig.getProcessingAction().generateTasks(); //Deze kunnen<SUF> if (nextActionConfig.hasUserInterface()) { //Since a new step has been started, stop executing actions once one with a user interface is present. c.restoreAuthSystemState(); return null; } else { ActionResult newOutcome = nextActionConfig.getProcessingAction().execute(c, wfi, nextStep, null); c.restoreAuthSystemState(); return processOutcome(c, user, workflow, nextStep, nextActionConfig, newOutcome, wfi); } }else{ if(currentOutcome.getResult() != ActionResult.OUTCOME_COMPLETE){ c.restoreAuthSystemState(); throw new WorkflowException("No alternate step was found for outcome: " + currentOutcome.getResult()); } archive(c, wfi); c.restoreAuthSystemState(); return null; } }else{ //We are done with our actions so go to the submissions page c.restoreAuthSystemState(); return null; } } } //TODO: log & go back to submission, We should not come here //TODO: remove assertion - can be used for testing (will throw assertionexception) assert false; return null; } //TODO: nakijken /** * Commit the contained item to the main archive. The item is associated * with the relevant collection, added to the search index, and any other * tasks such as assigning dates are performed. * * @return the fully archived item. */ public static Item archive(Context c, WorkflowItem wfi) throws SQLException, IOException, AuthorizeException { // FIXME: Check auth Item item = wfi.getItem(); Collection collection = wfi.getCollection(); // Remove (if any) the workflowItemroles for this item WorkflowItemRole[] workflowItemRoles = WorkflowItemRole.findAllForItem(c, wfi.getID()); for (WorkflowItemRole workflowItemRole : workflowItemRoles) { workflowItemRole.delete(); } log.info(LogManager.getHeader(c, "archive_item", "workflow_item_id=" + wfi.getID() + "item_id=" + item.getID() + "collection_id=" + collection.getID())); InstallItem.installItem(c, wfi); //Notify notifyOfArchive(c, item, collection); // Log the event log.info(LogManager.getHeader(c, "install_item", "workflow_item_id=" + wfi.getID() + ", item_id=" + item.getID() + "handle=FIXME")); return item; } //TODO: nakijken - altijd submitter mailen of config optie? /** * notify the submitter that the item is archived */ private static void notifyOfArchive(Context c, Item i, Collection coll) throws SQLException, IOException { try { // Get submitter EPerson ep = i.getSubmitter(); // Get the Locale Locale supportedLocale = I18nUtil.getEPersonLocale(ep); Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(supportedLocale, "submit_archive")); // Get the item handle to email to user String handle = HandleManager.findHandle(c, i); // Get title DCValue[] titles = i.getDC("title", null, Item.ANY); String title = ""; try { title = I18nUtil.getMessage("org.dspace.workflow.WorkflowManager.untitled"); } catch (MissingResourceException e) { title = "Untitled"; } if (titles.length > 0) { title = titles[0].value; } email.addRecipient(ep.getEmail()); email.addArgument(title); email.addArgument(coll.getMetadata("name")); email.addArgument(HandleManager.getCanonicalForm(handle)); email.send(); } catch (MessagingException e) { log.warn(LogManager.getHeader(c, "notifyOfArchive", "cannot email user" + " item_id=" + i.getID())); } } /*********************************** * WORKFLOW TASK MANAGEMENT **********************************/ /** * Deletes all tasks from this workflowflowitem * @param c the dspace context * @param wi the workflow item for whom we are to delete the tasks * @throws SQLException ... * @throws org.dspace.authorize.AuthorizeException ... */ public static void deleteAllTasks(Context c, WorkflowItem wi) throws SQLException, AuthorizeException { deleteAllPooledTasks(c, wi); List<ClaimedTask> allClaimedTasks = ClaimedTask.findByWorkflowId(c,wi.getID()); for(ClaimedTask task: allClaimedTasks){ deleteClaimedTask(c, wi, task); } } public static void deleteAllPooledTasks(Context c, WorkflowItem wi) throws SQLException, AuthorizeException { List<PoolTask> allPooledTasks = PoolTask.find(c, wi); for (PoolTask poolTask : allPooledTasks) { deletePooledTask(c, wi, poolTask); } } /* * Deletes an eperson from the taskpool of a step */ public static void deletePooledTask(Context c, WorkflowItem wi, PoolTask task) throws SQLException, AuthorizeException { if(task != null){ task.delete(); removeUserItemPolicies(c, wi.getItem(), EPerson.find(c, task.getEpersonID())); } } public static void deleteClaimedTask(Context c, WorkflowItem wi, ClaimedTask task) throws SQLException, AuthorizeException { if(task != null){ task.delete(); removeUserItemPolicies(c, wi.getItem(), EPerson.find(c, task.getOwnerID())); } } /* * Creates a task pool for a given step */ public static void createPoolTasks(Context context, WorkflowItem wi, EPerson[] epa, Step step, WorkflowActionConfig action) throws SQLException, AuthorizeException { // create a tasklist entry for each eperson for (EPerson anEpa : epa) { PoolTask task = PoolTask.create(context); task.setStepID(step.getId()); task.setWorkflowID(step.getWorkflow().getID()); task.setEpersonID(anEpa.getID()); task.setActionID(action.getId()); task.setWorkflowItemID(wi.getID()); task.update(); //Make sure this user has a task grantUserAllItemPolicies(context, wi.getItem(), anEpa); } } /* * Claims an action for a given eperson */ public static void createOwnedTask(Context c, WorkflowItem wi, Step step, WorkflowActionConfig action, EPerson e) throws SQLException, AuthorizeException { ClaimedTask task = ClaimedTask.create(c); task.setWorkflowItemID(wi.getID()); task.setStepID(step.getId()); task.setActionID(action.getId()); task.setOwnerID(e.getID()); task.setWorkflowID(step.getWorkflow().getID()); task.update(); //Make sure this user has a task grantUserAllItemPolicies(c, wi.getItem(), e); } private static void grantUserAllItemPolicies(Context context, Item item, EPerson epa) throws AuthorizeException, SQLException { //A list of policies the user has for this item List<Integer> userHasPolicies = new ArrayList<Integer>(); List<ResourcePolicy> itempols = AuthorizeManager.getPolicies(context, item); for (ResourcePolicy resourcePolicy : itempols) { if(resourcePolicy.getEPersonID() == epa.getID()){ //The user has already got this policy so it it to the list userHasPolicies.add(resourcePolicy.getAction()); } } //Make sure we don't add duplicate policies if(!userHasPolicies.contains(Constants.READ)) addPolicyToItem(context, item, Constants.READ, epa); if(!userHasPolicies.contains(Constants.WRITE)) addPolicyToItem(context, item, Constants.WRITE, epa); if(!userHasPolicies.contains(Constants.DELETE)) addPolicyToItem(context, item, Constants.DELETE, epa); if(!userHasPolicies.contains(Constants.ADD)) addPolicyToItem(context, item, Constants.ADD, epa); } private static void addPolicyToItem(Context context, Item item, int type, EPerson epa) throws AuthorizeException, SQLException { AuthorizeManager.addPolicy(context ,item, type, epa); Bundle[] bundles = item.getBundles(); for (Bundle bundle : bundles) { AuthorizeManager.addPolicy(context ,bundle, type, epa); Bitstream[] bits = bundle.getBitstreams(); for (Bitstream bit : bits) { AuthorizeManager.addPolicy(context, bit, type, epa); } } } private static void removeUserItemPolicies(Context context, Item item, EPerson e) throws SQLException, AuthorizeException { //Also remove any lingering authorizations from this user removePoliciesFromDso(context, item, e); //Remove the bundle rights Bundle[] bundles = item.getBundles(); for (Bundle bundle : bundles) { removePoliciesFromDso(context, bundle, e); Bitstream[] bitstreams = bundle.getBitstreams(); for (Bitstream bitstream : bitstreams) { removePoliciesFromDso(context, bitstream, e); } } } private static void removePoliciesFromDso(Context context, DSpaceObject item, EPerson e) throws SQLException, AuthorizeException { List<ResourcePolicy> policies = AuthorizeManager.getPolicies(context, item); AuthorizeManager.removeAllPolicies(context, item); for (ResourcePolicy resourcePolicy : policies) { if( resourcePolicy.getEPerson() ==null || resourcePolicy.getEPersonID() != e.getID()){ if(resourcePolicy.getEPerson() != null) AuthorizeManager.addPolicy(context, item, resourcePolicy.getAction(), resourcePolicy.getEPerson()); else AuthorizeManager.addPolicy(context, item, resourcePolicy.getAction(), resourcePolicy.getGroup()); } } } /** * rejects an item - rejection means undoing a submit - WorkspaceItem is * created, and the WorkflowItem is removed, user is emailed * rejection_message. * * @param c * Context * @param wi * WorkflowItem to operate on * @param e * EPerson doing the operation * @param action the action which triggered this reject * @param rejection_message * message to email to user * @return the workspace item that is created * @throws java.io.IOException ... * @throws java.sql.SQLException ... * @throws org.dspace.authorize.AuthorizeException ... */ public static WorkspaceItem rejectWorkflowItem(Context c, WorkflowItem wi, EPerson e, Action action, String rejection_message) throws SQLException, AuthorizeException, IOException { // authorize a DSpaceActions.REJECT // stop workflow deleteAllTasks(c, wi); //Also clear all info for this step WorkflowRequirementsManager.clearStepMetadata(wi); // Remove (if any) the workflowItemroles for this item WorkflowItemRole[] workflowItemRoles = WorkflowItemRole.findAllForItem(c, wi.getID()); for (WorkflowItemRole workflowItemRole : workflowItemRoles) { workflowItemRole.delete(); } // rejection provenance Item myitem = wi.getItem(); // Get current date String now = DCDate.getCurrent().toString(); // Get user's name + email address String usersName = getEPersonName(e); // Here's what happened String provDescription = action.getProvenanceStartId() + " Rejected by " + usersName + ", reason: " + rejection_message + " on " + now + " (GMT) "; // Add to item as a DC field myitem.addMetadata(MetadataSchema.DC_SCHEMA, "description", "provenance", "en", provDescription); myitem.update(); //TODO: MAKE SURE THAT SUBMITTER GETS PROPER RIGHTS // convert into personal workspace WorkspaceItem wsi = returnToWorkspace(c, wi); // notify that it's been rejected notifyOfReject(c, wi, e, rejection_message); log.info(LogManager.getHeader(c, "reject_workflow", "workflow_item_id=" + wi.getID() + "item_id=" + wi.getItem().getID() + "collection_id=" + wi.getCollection().getID() + "eperson_id=" + e.getID())); return wsi; } /** * Return the workflow item to the workspace of the submitter. The workflow * item is removed, and a workspace item created. * * @param c * Context * @param wfi * WorkflowItem to be 'dismantled' * @return the workspace item * @throws java.io.IOException ... * @throws java.sql.SQLException ... * @throws org.dspace.authorize.AuthorizeException ... */ private static WorkspaceItem returnToWorkspace(Context c, WorkflowItem wfi) throws SQLException, IOException, AuthorizeException { Item myitem = wfi.getItem(); Collection myCollection = wfi.getCollection(); // FIXME: How should this interact with the workflow system? // FIXME: Remove license // FIXME: Provenance statement? // Create the new workspace item row TableRow row = DatabaseManager.create(c, "workspaceitem"); row.setColumn("item_id", myitem.getID()); row.setColumn("collection_id", myCollection.getID()); DatabaseManager.update(c, row); int wsi_id = row.getIntColumn("workspace_item_id"); WorkspaceItem wi = WorkspaceItem.find(c, wsi_id); wi.setMultipleFiles(wfi.hasMultipleFiles()); wi.setMultipleTitles(wfi.hasMultipleTitles()); wi.setPublishedBefore(wfi.isPublishedBefore()); wi.update(); //myitem.update(); log.info(LogManager.getHeader(c, "return_to_workspace", "workflow_item_id=" + wfi.getID() + "workspace_item_id=" + wi.getID())); // Now remove the workflow object manually from the database DatabaseManager.updateQuery(c, "DELETE FROM WorkflowItem WHERE workflow_id=" + wfi.getID()); return wi; } public static String getEPersonName(EPerson e) throws SQLException { String submitter = e.getFullName(); submitter = submitter + "(" + e.getEmail() + ")"; return submitter; } // Create workflow start provenance message private static void recordStart(Item myitem, Action action) throws SQLException, IOException, AuthorizeException { // get date DCDate now = DCDate.getCurrent(); // Create provenance description String provmessage = ""; if (myitem.getSubmitter() != null) { provmessage = "Submitted by " + myitem.getSubmitter().getFullName() + " (" + myitem.getSubmitter().getEmail() + ") on " + now.toString() + " workflow start=" + action.getProvenanceStartId() + "\n"; } else // null submitter { provmessage = "Submitted by unknown (probably automated) on" + now.toString() + " workflow start=" + action.getProvenanceStartId() + "\n"; } // add sizes and checksums of bitstreams provmessage += InstallItem.getBitstreamProvenanceMessage(myitem); // Add message to the DC myitem.addMetadata(MetadataSchema.DC_SCHEMA, "description", "provenance", "en", provmessage); myitem.update(); } private static void notifyOfReject(Context c, WorkflowItem wi, EPerson e, String reason) { try { // Get the item title String title = wi.getItem().getName(); // Get the collection Collection coll = wi.getCollection(); // Get rejector's name String rejector = getEPersonName(e); Locale supportedLocale = I18nUtil.getEPersonLocale(e); Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(supportedLocale,"submit_reject")); email.addRecipient(wi.getSubmitter().getEmail()); email.addArgument(title); email.addArgument(coll.getMetadata("name")); email.addArgument(rejector); email.addArgument(reason); email.addArgument(ConfigurationManager.getProperty("dspace.url") + "/mydspace"); email.send(); } catch (Exception ex) { // log this email error log.warn(LogManager.getHeader(c, "notify_of_reject", "cannot email user" + " eperson_id" + e.getID() + " eperson_email" + e.getEmail() + " workflow_item_id" + wi.getID())); } } public static String getMyDSpaceLink() { return ConfigurationManager.getProperty("dspace.url") + "/mydspace"; } }
71795_2
package com.simibubi.create.foundation.data; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Objects; import org.apache.commons.lang3.mutable.MutableObject; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.simibubi.create.Create; import com.simibubi.create.foundation.ponder.PonderScene; import com.tterrag.registrate.AbstractRegistrate; import com.tterrag.registrate.providers.ProviderType; import net.minecraft.data.DataGenerator; import net.minecraft.data.DataProvider; import net.minecraft.data.HashCache; import net.minecraft.util.GsonHelper; /** * @deprecated Use {@link AbstractRegistrate#addRawLang} or {@link AbstractRegistrate#addDataGenerator} with {@link ProviderType#LANG} instead. */ @Deprecated(forRemoval = true) public class LangMerger implements DataProvider { private static final Gson GSON = new GsonBuilder().setPrettyPrinting() .disableHtmlEscaping() .create(); private static final String CATEGORY_HEADER = "\t\"_\": \"->------------------------] %s [------------------------<-\","; private DataGenerator gen; private final String modid; private final String displayName; private final LangPartial[] langPartials; private List<Object> mergedLangData; private List<String> langIgnore; public <T extends LangPartial> LangMerger(DataGenerator gen, String modid, String displayName, T[] langPartials) { this.gen = gen; this.modid = modid; this.displayName = displayName; this.langPartials = langPartials; this.mergedLangData = new ArrayList<>(); this.langIgnore = new ArrayList<>(); populateLangIgnore(); } protected void populateLangIgnore() { // Key prefixes added here will NOT be transferred to lang templates langIgnore.add("create.ponder.debug_"); // Ponder debug scene text langIgnore.add("create.gui.chromatic_projector"); } private boolean shouldIgnore(String key) { for (String string : langIgnore) if (key.startsWith(string)) return true; return false; } @Override public String getName() { return displayName + "'s lang merger"; } @Override public void run(HashCache cache) throws IOException { Path path = this.gen.getOutputFolder() .resolve("assets/" + modid + "/lang/" + "en_us.json"); collectExistingEntries(path); collectEntries(); if (mergedLangData.isEmpty()) return; save(cache, mergedLangData, path, "Merging en_us.json with hand-written lang entries..."); } private void collectExistingEntries(Path path) throws IOException { if (!Files.exists(path)) { Create.LOGGER.warn("Nothing to merge! It appears no lang was generated before me."); return; } try (BufferedReader reader = Files.newBufferedReader(path)) { JsonObject jsonobject = GsonHelper.fromJson(GSON, reader, JsonObject.class); addAll("Game Elements", jsonobject); reader.close(); } } protected void addAll(String header, JsonObject jsonobject) { if (jsonobject == null) return; header = String.format(CATEGORY_HEADER, header); writeData("\n"); writeData(header); writeData("\n\n"); MutableObject<String> previousKey = new MutableObject<>(""); jsonobject.entrySet() .stream() .forEachOrdered(entry -> { String key = entry.getKey(); if (shouldIgnore(key)) return; String value = entry.getValue() .getAsString(); if (!previousKey.getValue() .isEmpty() && shouldAddLineBreak(key, previousKey.getValue())) writeData("\n"); writeEntry(key, value); previousKey.setValue(key); }); writeData("\n"); } private void writeData(String data) { mergedLangData.add(data); } private void writeEntry(String key, String value) { mergedLangData.add(new LangEntry(key, value)); } protected boolean shouldAddLineBreak(String key, String previousKey) { // Always put tooltips and ponder scenes in their own paragraphs if (key.endsWith(".tooltip")) return true; if (key.startsWith(modid + ".ponder") && key.endsWith(PonderScene.TITLE_KEY)) return true; key = key.replaceFirst("\\.", ""); previousKey = previousKey.replaceFirst("\\.", ""); String[] split = key.split("\\."); String[] split2 = previousKey.split("\\."); if (split.length == 0 || split2.length == 0) return false; // Start new paragraph if keys before second point do not match return !split[0].equals(split2[0]); } private void collectEntries() { for (LangPartial partial : langPartials) addAll(partial.getDisplayName(), partial.provide() .getAsJsonObject()); } private void save(HashCache cache, List<Object> dataIn, Path target, String message) throws IOException { String data = createString(dataIn); String hash = DataProvider.SHA1.hashUnencodedChars(data) .toString(); if (!Objects.equals(cache.getHash(target), hash) || !Files.exists(target)) { Files.createDirectories(target.getParent()); try (BufferedWriter bufferedwriter = Files.newBufferedWriter(target)) { Create.LOGGER.info(message); bufferedwriter.write(data); } } cache.putNew(target, hash); } protected String createString(List<Object> data) { StringBuilder builder = new StringBuilder(); builder.append("{\n"); data.forEach(builder::append); builder.append("\t\"_\": \"Thank you for translating ").append(displayName).append("!\"\n\n"); builder.append("}"); return builder.toString(); } private class LangEntry { static final String ENTRY_FORMAT = "\t\"%s\": %s,\n"; private String key; private String value; LangEntry(String key, String value) { this.key = key; this.value = value; } @Override public String toString() { return String.format(ENTRY_FORMAT, key, GSON.toJson(value, String.class)); } } }
Creators-of-Create/Create
src/main/java/com/simibubi/create/foundation/data/LangMerger.java
1,875
// Ponder debug scene text
line_comment
nl
package com.simibubi.create.foundation.data; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Objects; import org.apache.commons.lang3.mutable.MutableObject; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.simibubi.create.Create; import com.simibubi.create.foundation.ponder.PonderScene; import com.tterrag.registrate.AbstractRegistrate; import com.tterrag.registrate.providers.ProviderType; import net.minecraft.data.DataGenerator; import net.minecraft.data.DataProvider; import net.minecraft.data.HashCache; import net.minecraft.util.GsonHelper; /** * @deprecated Use {@link AbstractRegistrate#addRawLang} or {@link AbstractRegistrate#addDataGenerator} with {@link ProviderType#LANG} instead. */ @Deprecated(forRemoval = true) public class LangMerger implements DataProvider { private static final Gson GSON = new GsonBuilder().setPrettyPrinting() .disableHtmlEscaping() .create(); private static final String CATEGORY_HEADER = "\t\"_\": \"->------------------------] %s [------------------------<-\","; private DataGenerator gen; private final String modid; private final String displayName; private final LangPartial[] langPartials; private List<Object> mergedLangData; private List<String> langIgnore; public <T extends LangPartial> LangMerger(DataGenerator gen, String modid, String displayName, T[] langPartials) { this.gen = gen; this.modid = modid; this.displayName = displayName; this.langPartials = langPartials; this.mergedLangData = new ArrayList<>(); this.langIgnore = new ArrayList<>(); populateLangIgnore(); } protected void populateLangIgnore() { // Key prefixes added here will NOT be transferred to lang templates langIgnore.add("create.ponder.debug_"); // Ponder debug<SUF> langIgnore.add("create.gui.chromatic_projector"); } private boolean shouldIgnore(String key) { for (String string : langIgnore) if (key.startsWith(string)) return true; return false; } @Override public String getName() { return displayName + "'s lang merger"; } @Override public void run(HashCache cache) throws IOException { Path path = this.gen.getOutputFolder() .resolve("assets/" + modid + "/lang/" + "en_us.json"); collectExistingEntries(path); collectEntries(); if (mergedLangData.isEmpty()) return; save(cache, mergedLangData, path, "Merging en_us.json with hand-written lang entries..."); } private void collectExistingEntries(Path path) throws IOException { if (!Files.exists(path)) { Create.LOGGER.warn("Nothing to merge! It appears no lang was generated before me."); return; } try (BufferedReader reader = Files.newBufferedReader(path)) { JsonObject jsonobject = GsonHelper.fromJson(GSON, reader, JsonObject.class); addAll("Game Elements", jsonobject); reader.close(); } } protected void addAll(String header, JsonObject jsonobject) { if (jsonobject == null) return; header = String.format(CATEGORY_HEADER, header); writeData("\n"); writeData(header); writeData("\n\n"); MutableObject<String> previousKey = new MutableObject<>(""); jsonobject.entrySet() .stream() .forEachOrdered(entry -> { String key = entry.getKey(); if (shouldIgnore(key)) return; String value = entry.getValue() .getAsString(); if (!previousKey.getValue() .isEmpty() && shouldAddLineBreak(key, previousKey.getValue())) writeData("\n"); writeEntry(key, value); previousKey.setValue(key); }); writeData("\n"); } private void writeData(String data) { mergedLangData.add(data); } private void writeEntry(String key, String value) { mergedLangData.add(new LangEntry(key, value)); } protected boolean shouldAddLineBreak(String key, String previousKey) { // Always put tooltips and ponder scenes in their own paragraphs if (key.endsWith(".tooltip")) return true; if (key.startsWith(modid + ".ponder") && key.endsWith(PonderScene.TITLE_KEY)) return true; key = key.replaceFirst("\\.", ""); previousKey = previousKey.replaceFirst("\\.", ""); String[] split = key.split("\\."); String[] split2 = previousKey.split("\\."); if (split.length == 0 || split2.length == 0) return false; // Start new paragraph if keys before second point do not match return !split[0].equals(split2[0]); } private void collectEntries() { for (LangPartial partial : langPartials) addAll(partial.getDisplayName(), partial.provide() .getAsJsonObject()); } private void save(HashCache cache, List<Object> dataIn, Path target, String message) throws IOException { String data = createString(dataIn); String hash = DataProvider.SHA1.hashUnencodedChars(data) .toString(); if (!Objects.equals(cache.getHash(target), hash) || !Files.exists(target)) { Files.createDirectories(target.getParent()); try (BufferedWriter bufferedwriter = Files.newBufferedWriter(target)) { Create.LOGGER.info(message); bufferedwriter.write(data); } } cache.putNew(target, hash); } protected String createString(List<Object> data) { StringBuilder builder = new StringBuilder(); builder.append("{\n"); data.forEach(builder::append); builder.append("\t\"_\": \"Thank you for translating ").append(displayName).append("!\"\n\n"); builder.append("}"); return builder.toString(); } private class LangEntry { static final String ENTRY_FORMAT = "\t\"%s\": %s,\n"; private String key; private String value; LangEntry(String key, String value) { this.key = key; this.value = value; } @Override public String toString() { return String.format(ENTRY_FORMAT, key, GSON.toJson(value, String.class)); } } }
72370_0
package org.mskcc.cbio.oncokb.cache; import org.apache.commons.lang3.StringUtils; import org.cbioportal.genome_nexus.component.annotation.NotationConverter; import org.cbioportal.genome_nexus.model.GenomicLocation; import org.cbioportal.genome_nexus.util.exception.InvalidHgvsException; import org.cbioportal.genome_nexus.util.exception.TypeNotSupportedException; import org.mskcc.cbio.oncokb.apiModels.CuratedGene; import org.mskcc.cbio.oncokb.bo.OncokbTranscriptService; import org.mskcc.cbio.oncokb.genomenexus.GNVariantAnnotationType; import org.mskcc.cbio.oncokb.model.*; import org.mskcc.cbio.oncokb.model.genomeNexusPreAnnotations.GenomeNexusAnnotatedVariantInfo; import org.mskcc.cbio.oncokb.util.*; import org.oncokb.oncokb_transcript.ApiException; import org.oncokb.oncokb_transcript.client.EnsemblGene; import org.oncokb.oncokb_transcript.client.TranscriptDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Component; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; import static org.mskcc.cbio.oncokb.Constants.DEFAULT_REFERENCE_GENOME; import static org.mskcc.cbio.oncokb.util.MainUtils.rangesIntersect; import static org.mskcc.cbio.oncokb.cache.Constants.REDIS_KEY_SEPARATOR; @Component public class CacheFetcher { OncokbTranscriptService oncokbTranscriptService = new OncokbTranscriptService(); NotationConverter notationConverter = new NotationConverter(); @Autowired(required = false) CacheManager cacheManager; @Cacheable(cacheResolver = "generalCacheResolver", key = "'all'") public OncoKBInfo getOncoKBInfo() { return new OncoKBInfo(); } @Cacheable(cacheResolver = "generalCacheResolver", key = "'all'") public List<CancerGene> getCancerGenes() throws ApiException, IOException { return getCancerGeneList(); } @Cacheable(cacheResolver = "generalCacheResolver", key = "'all'") public String getCancerGenesTxt() throws ApiException, IOException { String separator = "\t"; String newLine = "\n"; StringBuilder sb = new StringBuilder(); List<String> header = new ArrayList<>(); header.add("Hugo Symbol"); header.add("Entrez Gene ID"); header.add("GRCh37 Isoform"); header.add("GRCh37 RefSeq"); header.add("GRCh38 Isoform"); header.add("GRCh38 RefSeq"); header.add("# of occurrence within resources (Column D-J)"); header.add("OncoKB Annotated"); header.add("Is Oncogene"); header.add("Is Tumor Suppressor Gene"); header.add("MSK-IMPACT"); header.add("MSK-HEME"); header.add("FOUNDATION ONE"); header.add("FOUNDATION ONE HEME"); header.add("Vogelstein"); header.add("SANGER CGC(05/30/2017)"); header.add("Gene Aliases"); sb.append(MainUtils.listToString(header, separator)); sb.append(newLine); for (CancerGene cancerGene : getCancerGeneList()) { List<String> row = new ArrayList<>(); row.add(cancerGene.getHugoSymbol()); row.add(cancerGene.getEntrezGeneId().toString()); row.add(cancerGene.getGrch37Isoform()); row.add(cancerGene.getGrch37RefSeq()); row.add(cancerGene.getGrch38Isoform()); row.add(cancerGene.getGrch37RefSeq()); row.add(String.valueOf(cancerGene.getOccurrenceCount())); row.add(getStringByBoolean(cancerGene.getOncokbAnnotated())); row.add(getStringByBoolean(cancerGene.getOncogene())); row.add(getStringByBoolean(cancerGene.getTSG())); row.add(getStringByBoolean(cancerGene.getmSKImpact())); row.add(getStringByBoolean(cancerGene.getmSKHeme())); row.add(getStringByBoolean(cancerGene.getFoundation())); row.add(getStringByBoolean(cancerGene.getFoundationHeme())); row.add(getStringByBoolean(cancerGene.getVogelstein())); row.add(getStringByBoolean(cancerGene.getSangerCGC())); row.add(cancerGene.getGeneAliases().stream().sorted().collect(Collectors.joining(", "))); sb.append(MainUtils.listToString(row, separator)); sb.append(newLine); } return sb.toString(); } @Cacheable(cacheResolver = "generalCacheResolver", key = "'all'") public Set<org.oncokb.oncokb_transcript.client.Gene> getAllTranscriptGenes() throws ApiException { return oncokbTranscriptService.findTranscriptGenesBySymbols(CacheUtils.getAllGenes().stream().filter(gene -> gene.getEntrezGeneId() > 0).map(gene -> gene.getEntrezGeneId().toString()).collect(Collectors.toList())); } private List<CancerGene> getCancerGeneList() throws ApiException, IOException { List<CancerGene> cancerGenes = CancerGeneUtils.getCancerGeneList(); List<String> hugos = cancerGenes.stream().map(CancerGene::getHugoSymbol).collect(Collectors.toList()); List<Gene> genes = new ArrayList<>(); genes = oncokbTranscriptService.findGenesBySymbols(hugos); for (CancerGene cancerGene : cancerGenes) { if (cancerGene.getGeneAliases().size() == 0) { List<Gene> matched = genes.stream().filter(gene -> gene.getEntrezGeneId().equals(cancerGene.getEntrezGeneId())).collect(Collectors.toList()); if (matched.size() > 0) { Set<String> geneAlias = new HashSet<>(); Gene gene = matched.iterator().next(); geneAlias.addAll(gene.getGeneAliases()); geneAlias.add(gene.getHugoSymbol()); geneAlias.remove(cancerGene.getHugoSymbol()); cancerGene.setGeneAliases(geneAlias); } } } return cancerGenes; } @Cacheable(cacheResolver = "generalCacheResolver") public List<CuratedGene> getCuratedGenes(boolean includeEvidence) { List<CuratedGene> genes = new ArrayList<>(); for (Gene gene : CacheUtils.getAllGenes()) { // Skip all genes without entrez gene id if (gene.getEntrezGeneId() == null) { continue; } String highestSensitiveLevel = ""; String highestResistanceLevel = ""; Set<Evidence> therapeuticEvidences = EvidenceUtils.getEvidenceByGeneAndEvidenceTypes(gene, EvidenceTypeUtils.getTreatmentEvidenceTypes()); Set<Evidence> highestSensitiveLevelEvidences = EvidenceUtils.getOnlyHighestLevelEvidences(EvidenceUtils.getSensitiveEvidences(therapeuticEvidences), null, null); Set<Evidence> highestResistanceLevelEvidences = EvidenceUtils.getOnlyHighestLevelEvidences(EvidenceUtils.getResistanceEvidences(therapeuticEvidences), null, null); if (!highestSensitiveLevelEvidences.isEmpty()) { highestSensitiveLevel = highestSensitiveLevelEvidences.iterator().next().getLevelOfEvidence().getLevel(); } if (!highestResistanceLevelEvidences.isEmpty()) { highestResistanceLevel = highestResistanceLevelEvidences.iterator().next().getLevelOfEvidence().getLevel(); } genes.add( new CuratedGene( gene.getGrch37Isoform(), gene.getGrch37RefSeq(), gene.getGrch38Isoform(), gene.getGrch38RefSeq(), gene.getEntrezGeneId(), gene.getHugoSymbol(), gene.getTSG(), gene.getOncogene(), highestSensitiveLevel, highestResistanceLevel, includeEvidence ? SummaryUtils.geneSummary(gene, gene.getHugoSymbol()) : "", includeEvidence ? SummaryUtils.geneBackground(gene, gene.getHugoSymbol()) : "" ) ); } MainUtils.sortCuratedGenes(genes); return genes; } @Cacheable(cacheResolver = "generalCacheResolver") public String getCuratedGenesTxt(boolean includeEvidence) { String separator = "\t"; String newLine = "\n"; StringBuilder sb = new StringBuilder(); List<String> header = new ArrayList<>(); header.add("GRCh37 Isoform"); header.add("GRCh37 RefSeq"); header.add("GRCh38 Isoform"); header.add("GRCh38 RefSeq"); header.add("Entrez Gene ID"); header.add("Hugo Symbol"); header.add("Is Oncogene"); header.add("Is Tumor Suppressor Gene"); header.add("Highest Level of Evidence(sensitivity)"); header.add("Highest Level of Evidence(resistance)"); if (includeEvidence == Boolean.TRUE) { header.add("Summary"); header.add("Background"); } sb.append(MainUtils.listToString(header, separator)); sb.append(newLine); List<CuratedGene> genes = this.getCuratedGenes(includeEvidence == Boolean.TRUE); for (CuratedGene gene : genes) { List<String> row = new ArrayList<>(); row.add(gene.getGrch37Isoform()); row.add(gene.getGrch37RefSeq()); row.add(gene.getGrch38Isoform()); row.add(gene.getGrch38RefSeq()); row.add(String.valueOf(gene.getEntrezGeneId())); row.add(gene.getHugoSymbol()); row.add(getStringByBoolean(gene.getOncogene())); row.add(getStringByBoolean(gene.getTSG())); row.add(gene.getHighestSensitiveLevel()); row.add(gene.getHighestResistancLevel()); if (includeEvidence == Boolean.TRUE) { row.add(gene.getSummary()); row.add(gene.getBackground()); } sb.append(MainUtils.listToString(row, separator)); sb.append(newLine); } return sb.toString(); } private String getStringByBoolean(Boolean val) { return val ? "Yes" : "No"; } @Cacheable(cacheResolver = "generalCacheResolver") public Gene findGeneBySymbol(String symbol) throws ApiException { return this.oncokbTranscriptService.findGeneBySymbol(symbol); } @Cacheable( cacheResolver = "generalCacheResolver", keyGenerator = "concatKeyGenerator" ) public IndicatorQueryResp processQuery(ReferenceGenome referenceGenome, Integer entrezGeneId, String hugoSymbol, String alteration, String alterationType, String tumorType, String consequence, Integer proteinStart, Integer proteinEnd, StructuralVariantType svType, String hgvs, Set<LevelOfEvidence> levels, Boolean highestLevelOnly, Set<EvidenceType> evidenceTypes) { if (referenceGenome == null) { referenceGenome = DEFAULT_REFERENCE_GENOME; } Query query = new Query(null, referenceGenome, entrezGeneId, hugoSymbol, alteration, alterationType, svType, tumorType, consequence, proteinStart, proteinEnd, hgvs); return IndicatorUtils.processQuery( query, levels, highestLevelOnly, evidenceTypes ); } @Cacheable(cacheResolver = "generalCacheResolver", keyGenerator = "concatKeyGenerator") public Alteration getAlterationFromGenomeNexus(GNVariantAnnotationType gnVariantAnnotationType, ReferenceGenome referenceGenome, String genomicLocation) throws org.genome_nexus.ApiException { return AlterationUtils.getAlterationFromGenomeNexus(gnVariantAnnotationType, referenceGenome, genomicLocation); } public void cacheAlterationFromGenomeNexus(GenomeNexusAnnotatedVariantInfo gnAnnotatedVariantInfo) throws IllegalStateException { if (cacheManager == null) { throw new IllegalStateException("Cannot cache pre-annotated GN variants. Change property redis.enable to True."); } // Build the Alteration object from the pre-annotated GN variant object. Alteration alteration = new Alteration(); // Sometimes the VEP does not return the entrezGeneId and only returns the hugoSymbol. if (StringUtils.isNotEmpty(gnAnnotatedVariantInfo.getHugoSymbol()) || gnAnnotatedVariantInfo.getEntrezGeneId() != null) { Gene gene = GeneUtils.getGene(gnAnnotatedVariantInfo.getEntrezGeneId(), gnAnnotatedVariantInfo.getHugoSymbol()); if (gene == null) { gene = new Gene(); gene.setHugoSymbol(gnAnnotatedVariantInfo.getHugoSymbol()); gene.setEntrezGeneId(gnAnnotatedVariantInfo.getEntrezGeneId()); } alteration.setGene(gene); } alteration.setAlteration(gnAnnotatedVariantInfo.getHgvspShort()); alteration.setProteinStart(gnAnnotatedVariantInfo.getProteinStart()); alteration.setProteinEnd(gnAnnotatedVariantInfo.getProteinEnd()); alteration.setConsequence(VariantConsequenceUtils.findVariantConsequenceByTerm(gnAnnotatedVariantInfo.getConsequenceTerms())); String hgvsg = gnAnnotatedVariantInfo.getHgvsg(); String genomicLocation = gnAnnotatedVariantInfo.getGenomicLocation(); ReferenceGenome referenceGenome = gnAnnotatedVariantInfo.getReferenceGenome(); // Store pre-annotated alteration into Redis cache Cache cache = cacheManager.getCache(CacheCategory.GENERAL.getKey() + REDIS_KEY_SEPARATOR + "getAlterationFromGenomeNexus"); if (StringUtils.isNotEmpty(hgvsg)) { String cacheKey = String.join(REDIS_KEY_SEPARATOR, new String[]{GNVariantAnnotationType.HGVS_G.name(), referenceGenome.name(), hgvsg}); cache.put(cacheKey, alteration); } if (StringUtils.isNotEmpty(genomicLocation)) { String cacheKey = String.join(REDIS_KEY_SEPARATOR, new String[]{GNVariantAnnotationType.GENOMIC_LOCATION.name(), referenceGenome.name(), genomicLocation}); cache.put(cacheKey, alteration); } } @Cacheable(cacheResolver = "generalCacheResolver", keyGenerator = "concatKeyGenerator") public List<TranscriptDTO> getAllGeneEnsemblTranscript(ReferenceGenome referenceGenome) throws ApiException { List<String> ids = CacheUtils.getAllGenes().stream().map(gene -> Optional.ofNullable(referenceGenome.equals(ReferenceGenome.GRCh37.name()) ? gene.getGrch37Isoform() : gene.getGrch38Isoform()).orElse("")).filter(id -> StringUtils.isNotEmpty(id)).collect(Collectors.toList()); return oncokbTranscriptService.findEnsemblTranscriptsByIds(ids, referenceGenome); } public boolean genomicLocationShouldBeAnnotated(GNVariantAnnotationType gnVariantAnnotationType, String query, ReferenceGenome referenceGenome, Set<org.oncokb.oncokb_transcript.client.Gene> allTranscriptsGenes) throws ApiException { if (StringUtils.isEmpty(query)) { return false; }else{ query = query.trim(); } if (GNVariantAnnotationType.HGVS_G.equals(gnVariantAnnotationType)) { if (!AlterationUtils.isValidHgvsg(query)) { return false; } } // when the transcript info is not available, we should always annotate the genomic location if (allTranscriptsGenes == null || allTranscriptsGenes.isEmpty()) { return true; } GenomicLocation gl = null; try { if (gnVariantAnnotationType.equals(GNVariantAnnotationType.GENOMIC_LOCATION)) { gl = notationConverter.parseGenomicLocation(query); } else if (gnVariantAnnotationType.equals(GNVariantAnnotationType.HGVS_G)) { query = notationConverter.hgvsNormalizer(query); gl = notationConverter.hgvsgToGenomicLocation(query); } if (gl == null) { return false; } } catch (InvalidHgvsException | TypeNotSupportedException e) { // If GN throws InvalidHgvsException, we still need to check whether it's a duplication. The GN does not support dup in HGVSg format but it can still be annotated by VEP. if (query.endsWith("dup")) { return true; } else { return false; } } GenomicLocation finalGl = gl; int bpBuffer = 10000; // add some buffer on determine which genomic change should be annotated. We use the gene range from oncokb-transcript but that does not include gene regulatory sequence. Before having proper range, we use a buffer range instead. Boolean shouldBeAnnotated = allTranscriptsGenes.stream().anyMatch(gene -> { Set<EnsemblGene> ensemblGenes = gene.getEnsemblGenes().stream().filter(ensemblGene -> ensemblGene.getCanonical() && ensemblGene.getReferenceGenome().equals(referenceGenome.name())).collect(Collectors.toSet()); if (ensemblGenes.size() > 0) { return ensemblGenes.stream().anyMatch(ensemblGene -> finalGl.getChromosome().equals(ensemblGene.getChromosome()) && rangesIntersect(ensemblGene.getStart() > bpBuffer ? (ensemblGene.getStart() - bpBuffer) : 0, ensemblGene.getEnd() + bpBuffer, finalGl.getStart(), finalGl.getEnd())); } else { return false; } }); return shouldBeAnnotated; } }
Crecendow/oncokb
core/src/main/java/org/mskcc/cbio/oncokb/cache/CacheFetcher.java
5,208
// Skip all genes without entrez gene id
line_comment
nl
package org.mskcc.cbio.oncokb.cache; import org.apache.commons.lang3.StringUtils; import org.cbioportal.genome_nexus.component.annotation.NotationConverter; import org.cbioportal.genome_nexus.model.GenomicLocation; import org.cbioportal.genome_nexus.util.exception.InvalidHgvsException; import org.cbioportal.genome_nexus.util.exception.TypeNotSupportedException; import org.mskcc.cbio.oncokb.apiModels.CuratedGene; import org.mskcc.cbio.oncokb.bo.OncokbTranscriptService; import org.mskcc.cbio.oncokb.genomenexus.GNVariantAnnotationType; import org.mskcc.cbio.oncokb.model.*; import org.mskcc.cbio.oncokb.model.genomeNexusPreAnnotations.GenomeNexusAnnotatedVariantInfo; import org.mskcc.cbio.oncokb.util.*; import org.oncokb.oncokb_transcript.ApiException; import org.oncokb.oncokb_transcript.client.EnsemblGene; import org.oncokb.oncokb_transcript.client.TranscriptDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Component; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; import static org.mskcc.cbio.oncokb.Constants.DEFAULT_REFERENCE_GENOME; import static org.mskcc.cbio.oncokb.util.MainUtils.rangesIntersect; import static org.mskcc.cbio.oncokb.cache.Constants.REDIS_KEY_SEPARATOR; @Component public class CacheFetcher { OncokbTranscriptService oncokbTranscriptService = new OncokbTranscriptService(); NotationConverter notationConverter = new NotationConverter(); @Autowired(required = false) CacheManager cacheManager; @Cacheable(cacheResolver = "generalCacheResolver", key = "'all'") public OncoKBInfo getOncoKBInfo() { return new OncoKBInfo(); } @Cacheable(cacheResolver = "generalCacheResolver", key = "'all'") public List<CancerGene> getCancerGenes() throws ApiException, IOException { return getCancerGeneList(); } @Cacheable(cacheResolver = "generalCacheResolver", key = "'all'") public String getCancerGenesTxt() throws ApiException, IOException { String separator = "\t"; String newLine = "\n"; StringBuilder sb = new StringBuilder(); List<String> header = new ArrayList<>(); header.add("Hugo Symbol"); header.add("Entrez Gene ID"); header.add("GRCh37 Isoform"); header.add("GRCh37 RefSeq"); header.add("GRCh38 Isoform"); header.add("GRCh38 RefSeq"); header.add("# of occurrence within resources (Column D-J)"); header.add("OncoKB Annotated"); header.add("Is Oncogene"); header.add("Is Tumor Suppressor Gene"); header.add("MSK-IMPACT"); header.add("MSK-HEME"); header.add("FOUNDATION ONE"); header.add("FOUNDATION ONE HEME"); header.add("Vogelstein"); header.add("SANGER CGC(05/30/2017)"); header.add("Gene Aliases"); sb.append(MainUtils.listToString(header, separator)); sb.append(newLine); for (CancerGene cancerGene : getCancerGeneList()) { List<String> row = new ArrayList<>(); row.add(cancerGene.getHugoSymbol()); row.add(cancerGene.getEntrezGeneId().toString()); row.add(cancerGene.getGrch37Isoform()); row.add(cancerGene.getGrch37RefSeq()); row.add(cancerGene.getGrch38Isoform()); row.add(cancerGene.getGrch37RefSeq()); row.add(String.valueOf(cancerGene.getOccurrenceCount())); row.add(getStringByBoolean(cancerGene.getOncokbAnnotated())); row.add(getStringByBoolean(cancerGene.getOncogene())); row.add(getStringByBoolean(cancerGene.getTSG())); row.add(getStringByBoolean(cancerGene.getmSKImpact())); row.add(getStringByBoolean(cancerGene.getmSKHeme())); row.add(getStringByBoolean(cancerGene.getFoundation())); row.add(getStringByBoolean(cancerGene.getFoundationHeme())); row.add(getStringByBoolean(cancerGene.getVogelstein())); row.add(getStringByBoolean(cancerGene.getSangerCGC())); row.add(cancerGene.getGeneAliases().stream().sorted().collect(Collectors.joining(", "))); sb.append(MainUtils.listToString(row, separator)); sb.append(newLine); } return sb.toString(); } @Cacheable(cacheResolver = "generalCacheResolver", key = "'all'") public Set<org.oncokb.oncokb_transcript.client.Gene> getAllTranscriptGenes() throws ApiException { return oncokbTranscriptService.findTranscriptGenesBySymbols(CacheUtils.getAllGenes().stream().filter(gene -> gene.getEntrezGeneId() > 0).map(gene -> gene.getEntrezGeneId().toString()).collect(Collectors.toList())); } private List<CancerGene> getCancerGeneList() throws ApiException, IOException { List<CancerGene> cancerGenes = CancerGeneUtils.getCancerGeneList(); List<String> hugos = cancerGenes.stream().map(CancerGene::getHugoSymbol).collect(Collectors.toList()); List<Gene> genes = new ArrayList<>(); genes = oncokbTranscriptService.findGenesBySymbols(hugos); for (CancerGene cancerGene : cancerGenes) { if (cancerGene.getGeneAliases().size() == 0) { List<Gene> matched = genes.stream().filter(gene -> gene.getEntrezGeneId().equals(cancerGene.getEntrezGeneId())).collect(Collectors.toList()); if (matched.size() > 0) { Set<String> geneAlias = new HashSet<>(); Gene gene = matched.iterator().next(); geneAlias.addAll(gene.getGeneAliases()); geneAlias.add(gene.getHugoSymbol()); geneAlias.remove(cancerGene.getHugoSymbol()); cancerGene.setGeneAliases(geneAlias); } } } return cancerGenes; } @Cacheable(cacheResolver = "generalCacheResolver") public List<CuratedGene> getCuratedGenes(boolean includeEvidence) { List<CuratedGene> genes = new ArrayList<>(); for (Gene gene : CacheUtils.getAllGenes()) { // Skip all<SUF> if (gene.getEntrezGeneId() == null) { continue; } String highestSensitiveLevel = ""; String highestResistanceLevel = ""; Set<Evidence> therapeuticEvidences = EvidenceUtils.getEvidenceByGeneAndEvidenceTypes(gene, EvidenceTypeUtils.getTreatmentEvidenceTypes()); Set<Evidence> highestSensitiveLevelEvidences = EvidenceUtils.getOnlyHighestLevelEvidences(EvidenceUtils.getSensitiveEvidences(therapeuticEvidences), null, null); Set<Evidence> highestResistanceLevelEvidences = EvidenceUtils.getOnlyHighestLevelEvidences(EvidenceUtils.getResistanceEvidences(therapeuticEvidences), null, null); if (!highestSensitiveLevelEvidences.isEmpty()) { highestSensitiveLevel = highestSensitiveLevelEvidences.iterator().next().getLevelOfEvidence().getLevel(); } if (!highestResistanceLevelEvidences.isEmpty()) { highestResistanceLevel = highestResistanceLevelEvidences.iterator().next().getLevelOfEvidence().getLevel(); } genes.add( new CuratedGene( gene.getGrch37Isoform(), gene.getGrch37RefSeq(), gene.getGrch38Isoform(), gene.getGrch38RefSeq(), gene.getEntrezGeneId(), gene.getHugoSymbol(), gene.getTSG(), gene.getOncogene(), highestSensitiveLevel, highestResistanceLevel, includeEvidence ? SummaryUtils.geneSummary(gene, gene.getHugoSymbol()) : "", includeEvidence ? SummaryUtils.geneBackground(gene, gene.getHugoSymbol()) : "" ) ); } MainUtils.sortCuratedGenes(genes); return genes; } @Cacheable(cacheResolver = "generalCacheResolver") public String getCuratedGenesTxt(boolean includeEvidence) { String separator = "\t"; String newLine = "\n"; StringBuilder sb = new StringBuilder(); List<String> header = new ArrayList<>(); header.add("GRCh37 Isoform"); header.add("GRCh37 RefSeq"); header.add("GRCh38 Isoform"); header.add("GRCh38 RefSeq"); header.add("Entrez Gene ID"); header.add("Hugo Symbol"); header.add("Is Oncogene"); header.add("Is Tumor Suppressor Gene"); header.add("Highest Level of Evidence(sensitivity)"); header.add("Highest Level of Evidence(resistance)"); if (includeEvidence == Boolean.TRUE) { header.add("Summary"); header.add("Background"); } sb.append(MainUtils.listToString(header, separator)); sb.append(newLine); List<CuratedGene> genes = this.getCuratedGenes(includeEvidence == Boolean.TRUE); for (CuratedGene gene : genes) { List<String> row = new ArrayList<>(); row.add(gene.getGrch37Isoform()); row.add(gene.getGrch37RefSeq()); row.add(gene.getGrch38Isoform()); row.add(gene.getGrch38RefSeq()); row.add(String.valueOf(gene.getEntrezGeneId())); row.add(gene.getHugoSymbol()); row.add(getStringByBoolean(gene.getOncogene())); row.add(getStringByBoolean(gene.getTSG())); row.add(gene.getHighestSensitiveLevel()); row.add(gene.getHighestResistancLevel()); if (includeEvidence == Boolean.TRUE) { row.add(gene.getSummary()); row.add(gene.getBackground()); } sb.append(MainUtils.listToString(row, separator)); sb.append(newLine); } return sb.toString(); } private String getStringByBoolean(Boolean val) { return val ? "Yes" : "No"; } @Cacheable(cacheResolver = "generalCacheResolver") public Gene findGeneBySymbol(String symbol) throws ApiException { return this.oncokbTranscriptService.findGeneBySymbol(symbol); } @Cacheable( cacheResolver = "generalCacheResolver", keyGenerator = "concatKeyGenerator" ) public IndicatorQueryResp processQuery(ReferenceGenome referenceGenome, Integer entrezGeneId, String hugoSymbol, String alteration, String alterationType, String tumorType, String consequence, Integer proteinStart, Integer proteinEnd, StructuralVariantType svType, String hgvs, Set<LevelOfEvidence> levels, Boolean highestLevelOnly, Set<EvidenceType> evidenceTypes) { if (referenceGenome == null) { referenceGenome = DEFAULT_REFERENCE_GENOME; } Query query = new Query(null, referenceGenome, entrezGeneId, hugoSymbol, alteration, alterationType, svType, tumorType, consequence, proteinStart, proteinEnd, hgvs); return IndicatorUtils.processQuery( query, levels, highestLevelOnly, evidenceTypes ); } @Cacheable(cacheResolver = "generalCacheResolver", keyGenerator = "concatKeyGenerator") public Alteration getAlterationFromGenomeNexus(GNVariantAnnotationType gnVariantAnnotationType, ReferenceGenome referenceGenome, String genomicLocation) throws org.genome_nexus.ApiException { return AlterationUtils.getAlterationFromGenomeNexus(gnVariantAnnotationType, referenceGenome, genomicLocation); } public void cacheAlterationFromGenomeNexus(GenomeNexusAnnotatedVariantInfo gnAnnotatedVariantInfo) throws IllegalStateException { if (cacheManager == null) { throw new IllegalStateException("Cannot cache pre-annotated GN variants. Change property redis.enable to True."); } // Build the Alteration object from the pre-annotated GN variant object. Alteration alteration = new Alteration(); // Sometimes the VEP does not return the entrezGeneId and only returns the hugoSymbol. if (StringUtils.isNotEmpty(gnAnnotatedVariantInfo.getHugoSymbol()) || gnAnnotatedVariantInfo.getEntrezGeneId() != null) { Gene gene = GeneUtils.getGene(gnAnnotatedVariantInfo.getEntrezGeneId(), gnAnnotatedVariantInfo.getHugoSymbol()); if (gene == null) { gene = new Gene(); gene.setHugoSymbol(gnAnnotatedVariantInfo.getHugoSymbol()); gene.setEntrezGeneId(gnAnnotatedVariantInfo.getEntrezGeneId()); } alteration.setGene(gene); } alteration.setAlteration(gnAnnotatedVariantInfo.getHgvspShort()); alteration.setProteinStart(gnAnnotatedVariantInfo.getProteinStart()); alteration.setProteinEnd(gnAnnotatedVariantInfo.getProteinEnd()); alteration.setConsequence(VariantConsequenceUtils.findVariantConsequenceByTerm(gnAnnotatedVariantInfo.getConsequenceTerms())); String hgvsg = gnAnnotatedVariantInfo.getHgvsg(); String genomicLocation = gnAnnotatedVariantInfo.getGenomicLocation(); ReferenceGenome referenceGenome = gnAnnotatedVariantInfo.getReferenceGenome(); // Store pre-annotated alteration into Redis cache Cache cache = cacheManager.getCache(CacheCategory.GENERAL.getKey() + REDIS_KEY_SEPARATOR + "getAlterationFromGenomeNexus"); if (StringUtils.isNotEmpty(hgvsg)) { String cacheKey = String.join(REDIS_KEY_SEPARATOR, new String[]{GNVariantAnnotationType.HGVS_G.name(), referenceGenome.name(), hgvsg}); cache.put(cacheKey, alteration); } if (StringUtils.isNotEmpty(genomicLocation)) { String cacheKey = String.join(REDIS_KEY_SEPARATOR, new String[]{GNVariantAnnotationType.GENOMIC_LOCATION.name(), referenceGenome.name(), genomicLocation}); cache.put(cacheKey, alteration); } } @Cacheable(cacheResolver = "generalCacheResolver", keyGenerator = "concatKeyGenerator") public List<TranscriptDTO> getAllGeneEnsemblTranscript(ReferenceGenome referenceGenome) throws ApiException { List<String> ids = CacheUtils.getAllGenes().stream().map(gene -> Optional.ofNullable(referenceGenome.equals(ReferenceGenome.GRCh37.name()) ? gene.getGrch37Isoform() : gene.getGrch38Isoform()).orElse("")).filter(id -> StringUtils.isNotEmpty(id)).collect(Collectors.toList()); return oncokbTranscriptService.findEnsemblTranscriptsByIds(ids, referenceGenome); } public boolean genomicLocationShouldBeAnnotated(GNVariantAnnotationType gnVariantAnnotationType, String query, ReferenceGenome referenceGenome, Set<org.oncokb.oncokb_transcript.client.Gene> allTranscriptsGenes) throws ApiException { if (StringUtils.isEmpty(query)) { return false; }else{ query = query.trim(); } if (GNVariantAnnotationType.HGVS_G.equals(gnVariantAnnotationType)) { if (!AlterationUtils.isValidHgvsg(query)) { return false; } } // when the transcript info is not available, we should always annotate the genomic location if (allTranscriptsGenes == null || allTranscriptsGenes.isEmpty()) { return true; } GenomicLocation gl = null; try { if (gnVariantAnnotationType.equals(GNVariantAnnotationType.GENOMIC_LOCATION)) { gl = notationConverter.parseGenomicLocation(query); } else if (gnVariantAnnotationType.equals(GNVariantAnnotationType.HGVS_G)) { query = notationConverter.hgvsNormalizer(query); gl = notationConverter.hgvsgToGenomicLocation(query); } if (gl == null) { return false; } } catch (InvalidHgvsException | TypeNotSupportedException e) { // If GN throws InvalidHgvsException, we still need to check whether it's a duplication. The GN does not support dup in HGVSg format but it can still be annotated by VEP. if (query.endsWith("dup")) { return true; } else { return false; } } GenomicLocation finalGl = gl; int bpBuffer = 10000; // add some buffer on determine which genomic change should be annotated. We use the gene range from oncokb-transcript but that does not include gene regulatory sequence. Before having proper range, we use a buffer range instead. Boolean shouldBeAnnotated = allTranscriptsGenes.stream().anyMatch(gene -> { Set<EnsemblGene> ensemblGenes = gene.getEnsemblGenes().stream().filter(ensemblGene -> ensemblGene.getCanonical() && ensemblGene.getReferenceGenome().equals(referenceGenome.name())).collect(Collectors.toSet()); if (ensemblGenes.size() > 0) { return ensemblGenes.stream().anyMatch(ensemblGene -> finalGl.getChromosome().equals(ensemblGene.getChromosome()) && rangesIntersect(ensemblGene.getStart() > bpBuffer ? (ensemblGene.getStart() - bpBuffer) : 0, ensemblGene.getEnd() + bpBuffer, finalGl.getStart(), finalGl.getEnd())); } else { return false; } }); return shouldBeAnnotated; } }
180928_14
package solution; import java.util.ArrayList; import java.util.List; import model.Machine; import model.Problem; import model.Request; public class Evaluation { private static double nightshiftCost; private static double parallelCost; private static double overtimeBlockCost; private static double underStockPenaltyCost; private static double[] itemRevenue; private static int[] minStock; private static int[] maxStock; public static double calculateObjectiveFunction(Solution solution) throws OverStockException{ double result = 0; List<Request> shippedRequests = new ArrayList<>(); for(Day d: solution.horizon) { //add night shift cost if(d.nachtshift) result += Evaluation.nightshiftCost; //add stock cost for(int i=0; i<d.stock.length; i++) { if(d.stock[i] < minStock[i]) result += (minStock[i] - d.stock[i]) * Evaluation.underStockPenaltyCost; if(d.stock[i] > maxStock[i]) throw new OverStockException(); } //add requests to shippedRequests if they have been shipped for(Request r : d.shippedToday) { shippedRequests.add(r); } } //fix overtime for(Day d: solution.horizon) { if(d.overtime > 0) { int overtime = 0; for(Machine m: solution.problem.getMachines()) { int thisAmountOfOvertimes = 0; for(int i=solution.problem.getLastDayShiftIndex()+1; i<solution.problem.getLastOvertimeIndex()+1; i++) { if(new Idle().equals(d.jobs[m.getMachineId()][i])) { if(thisAmountOfOvertimes > overtime) { overtime = thisAmountOfOvertimes; } break; } else { if(++thisAmountOfOvertimes > overtime) { overtime = thisAmountOfOvertimes; } } } } result += overtime * Evaluation.overtimeBlockCost; } } //fix parallelwerk for(Day d: solution.horizon) { if(d.parallelwerk) { boolean inparallel = false; for(int i=0; i<solution.problem.getLastDayShiftIndex()+1; i++) { boolean blockInUse = false; for(Machine m: solution.problem.getMachines()) { if(!d.jobs[m.getMachineId()][i].equals(new Idle())) { if(blockInUse == true) { inparallel = true; break; } else { blockInUse = true; } } } if(inparallel) { break; } } if(inparallel) { result += Evaluation.parallelCost; } } } //add unshipped requests cost for(Request r: solution.problem.getRequests()) { if(!shippedRequests.contains(r)) { for(int itemId = 0; itemId < r.getAmountsRequested().length; itemId++) { result += (r.getAmountsRequested()[itemId] * itemRevenue[itemId]); } } } //check for not-full nightshifts if(solution.horizon[solution.horizon.length - 1].nachtshift) { int extraNightShiftsToPay = solution.problem.getMinimumConsecutiveNightShifts(); int count = extraNightShiftsToPay; if(extraNightShiftsToPay >= solution.horizon.length) { System.out.println("Gemene input: minAantalConsecutiveNightShifts > horizon.length"); } for(int i=1; i<count+1; i++) { if(solution.horizon[solution.horizon.length-i].nachtshift) { extraNightShiftsToPay--; } else { break; } } result += extraNightShiftsToPay * Evaluation.nightshiftCost; } //done return result; } public static void configureEvaluation(Problem problem) { Evaluation.nightshiftCost = problem.getCostOfNightShift(); Evaluation.parallelCost = problem.getCostOfParallelDay(); Evaluation.overtimeBlockCost = problem.getCostOfOvertimePerBlock(); Evaluation.underStockPenaltyCost = problem.getCostPerItemUnderMinimumStock(); Evaluation.itemRevenue = new double[problem.getItems().length]; Evaluation.minStock = new int[problem.getItems().length]; Evaluation.maxStock = new int[problem.getItems().length]; for(int i=0; i<itemRevenue.length; i++) { Evaluation.itemRevenue[i] = problem.getItems()[i].getCostPerItem(); Evaluation.minStock[i] = problem.getItems()[i].getMinAllowedInStock(); Evaluation.maxStock[i] = problem.getItems()[i].getMaxAllowedInStock(); } } public static double calculateIntermediateObjectiveFunction(Solution solution) throws OverStockException{ double result = 0; List<Request> shippedRequests = new ArrayList<>(); for(Day d: solution.horizon) { //add night shift cost if(d.nachtshift) result += Evaluation.nightshiftCost; //add stock cost for(int i=0; i<d.stock.length; i++) { if(d.stock[i] < minStock[i]) result += (minStock[i] - d.stock[i]) * Evaluation.underStockPenaltyCost; if(d.stock[i] > maxStock[i]) throw new OverStockException(); } //add requests to shippedRequests if they have been shipped for(Request r : d.shippedToday) { shippedRequests.add(r); } } //fix overtime for(Day d: solution.horizon) { if(d.overtime > 0) { int overtime = 0; for(Machine m: solution.problem.getMachines()) { for(int i=solution.problem.getLastDayShiftIndex()+1; i<solution.problem.getLastOvertimeIndex()+1; i++) { int thisAmountOfOvertimes = 0; if(d.jobs[m.getMachineId()][i].equals(new Idle())) { if(thisAmountOfOvertimes > overtime) { overtime = thisAmountOfOvertimes; } break; } else { if(++thisAmountOfOvertimes > overtime) { overtime = thisAmountOfOvertimes; } } } } result += overtime * Evaluation.overtimeBlockCost; } } //fix parallelwerk for(Day d: solution.horizon) { if(d.parallelwerk) { boolean inparallel = false; for(int i=0; i<solution.problem.getLastDayShiftIndex()+1; i++) { boolean blockInUse = false; for(Machine m: solution.problem.getMachines()) { if(!d.jobs[m.getMachineId()][i].equals(new Idle())) { if(blockInUse == true) { inparallel = true; break; } else { blockInUse = true; } } } if(inparallel) { break; } } if(inparallel) { result += Evaluation.parallelCost; } } } //add unshipped requests cost for(Request r: solution.problem.getRequests()) { if(!shippedRequests.contains(r)) { for(int itemId = 0; itemId < r.getAmountsRequested().length; itemId++) { result += (r.getAmountsRequested()[itemId] * itemRevenue[itemId]); } } } //look how close we came to fullfilling the first unfullfilled order. Request r = null; for(Request req: solution.requestOrder) { if(!shippedRequests.contains(req)) { //System.out.println("we get to this point!"); r = req; break; } } if(r != null) { //zoek de laatst mogelijke shippingdag int dayIndex = 0; for(int i=solution.horizon.length-1; i>=0; i++) { if(r.isShippingDay(i)) { //System.out.println("final shipping day found"); dayIndex = i; break; } } //System.out.println("Day " + dayIndex + ", request: " + r.getId()); //trek van de cost af: //voor elk item dat nodig is voor de request te kunnen verschepen, de hoeveelheid in stock op die dag * de revenue per item voor dat item. for(int itemId = 0; itemId < r.getAmountsRequested().length; itemId++) { int amountToSubtract = 0; if (r.getAmountsRequested()[itemId] != 0) { if (r.getAmountsRequested()[itemId] - solution.horizon[dayIndex].stock[itemId] > 0) { amountToSubtract = solution.horizon[dayIndex].stock[itemId]; } else { amountToSubtract = r.getAmountsRequested()[itemId]; } //System.out.println("subtracting: " + amountToSubtract * Evaluation.itemRevenue[itemId]); result -= amountToSubtract * Evaluation.itemRevenue[itemId]; } } } //check for not-full nightshifts if(solution.horizon[solution.horizon.length - 1].nachtshift) { int extraNightShiftsToPay = solution.problem.getMinimumConsecutiveNightShifts(); int count = extraNightShiftsToPay; if(extraNightShiftsToPay >= solution.horizon.length) { System.out.println("minAantalConsecutiveNightShifts > horizon.length"); } for(int i=1; i<count; i++) { if(solution.horizon[solution.horizon.length-i].nachtshift) { extraNightShiftsToPay--; } else { break; } } result += extraNightShiftsToPay * Evaluation.nightshiftCost; } //done return result; } }
CrimsonKobalt/AltachemScheduler
AltachemScheduler/src/solution/Evaluation.java
2,992
//trek van de cost af:
line_comment
nl
package solution; import java.util.ArrayList; import java.util.List; import model.Machine; import model.Problem; import model.Request; public class Evaluation { private static double nightshiftCost; private static double parallelCost; private static double overtimeBlockCost; private static double underStockPenaltyCost; private static double[] itemRevenue; private static int[] minStock; private static int[] maxStock; public static double calculateObjectiveFunction(Solution solution) throws OverStockException{ double result = 0; List<Request> shippedRequests = new ArrayList<>(); for(Day d: solution.horizon) { //add night shift cost if(d.nachtshift) result += Evaluation.nightshiftCost; //add stock cost for(int i=0; i<d.stock.length; i++) { if(d.stock[i] < minStock[i]) result += (minStock[i] - d.stock[i]) * Evaluation.underStockPenaltyCost; if(d.stock[i] > maxStock[i]) throw new OverStockException(); } //add requests to shippedRequests if they have been shipped for(Request r : d.shippedToday) { shippedRequests.add(r); } } //fix overtime for(Day d: solution.horizon) { if(d.overtime > 0) { int overtime = 0; for(Machine m: solution.problem.getMachines()) { int thisAmountOfOvertimes = 0; for(int i=solution.problem.getLastDayShiftIndex()+1; i<solution.problem.getLastOvertimeIndex()+1; i++) { if(new Idle().equals(d.jobs[m.getMachineId()][i])) { if(thisAmountOfOvertimes > overtime) { overtime = thisAmountOfOvertimes; } break; } else { if(++thisAmountOfOvertimes > overtime) { overtime = thisAmountOfOvertimes; } } } } result += overtime * Evaluation.overtimeBlockCost; } } //fix parallelwerk for(Day d: solution.horizon) { if(d.parallelwerk) { boolean inparallel = false; for(int i=0; i<solution.problem.getLastDayShiftIndex()+1; i++) { boolean blockInUse = false; for(Machine m: solution.problem.getMachines()) { if(!d.jobs[m.getMachineId()][i].equals(new Idle())) { if(blockInUse == true) { inparallel = true; break; } else { blockInUse = true; } } } if(inparallel) { break; } } if(inparallel) { result += Evaluation.parallelCost; } } } //add unshipped requests cost for(Request r: solution.problem.getRequests()) { if(!shippedRequests.contains(r)) { for(int itemId = 0; itemId < r.getAmountsRequested().length; itemId++) { result += (r.getAmountsRequested()[itemId] * itemRevenue[itemId]); } } } //check for not-full nightshifts if(solution.horizon[solution.horizon.length - 1].nachtshift) { int extraNightShiftsToPay = solution.problem.getMinimumConsecutiveNightShifts(); int count = extraNightShiftsToPay; if(extraNightShiftsToPay >= solution.horizon.length) { System.out.println("Gemene input: minAantalConsecutiveNightShifts > horizon.length"); } for(int i=1; i<count+1; i++) { if(solution.horizon[solution.horizon.length-i].nachtshift) { extraNightShiftsToPay--; } else { break; } } result += extraNightShiftsToPay * Evaluation.nightshiftCost; } //done return result; } public static void configureEvaluation(Problem problem) { Evaluation.nightshiftCost = problem.getCostOfNightShift(); Evaluation.parallelCost = problem.getCostOfParallelDay(); Evaluation.overtimeBlockCost = problem.getCostOfOvertimePerBlock(); Evaluation.underStockPenaltyCost = problem.getCostPerItemUnderMinimumStock(); Evaluation.itemRevenue = new double[problem.getItems().length]; Evaluation.minStock = new int[problem.getItems().length]; Evaluation.maxStock = new int[problem.getItems().length]; for(int i=0; i<itemRevenue.length; i++) { Evaluation.itemRevenue[i] = problem.getItems()[i].getCostPerItem(); Evaluation.minStock[i] = problem.getItems()[i].getMinAllowedInStock(); Evaluation.maxStock[i] = problem.getItems()[i].getMaxAllowedInStock(); } } public static double calculateIntermediateObjectiveFunction(Solution solution) throws OverStockException{ double result = 0; List<Request> shippedRequests = new ArrayList<>(); for(Day d: solution.horizon) { //add night shift cost if(d.nachtshift) result += Evaluation.nightshiftCost; //add stock cost for(int i=0; i<d.stock.length; i++) { if(d.stock[i] < minStock[i]) result += (minStock[i] - d.stock[i]) * Evaluation.underStockPenaltyCost; if(d.stock[i] > maxStock[i]) throw new OverStockException(); } //add requests to shippedRequests if they have been shipped for(Request r : d.shippedToday) { shippedRequests.add(r); } } //fix overtime for(Day d: solution.horizon) { if(d.overtime > 0) { int overtime = 0; for(Machine m: solution.problem.getMachines()) { for(int i=solution.problem.getLastDayShiftIndex()+1; i<solution.problem.getLastOvertimeIndex()+1; i++) { int thisAmountOfOvertimes = 0; if(d.jobs[m.getMachineId()][i].equals(new Idle())) { if(thisAmountOfOvertimes > overtime) { overtime = thisAmountOfOvertimes; } break; } else { if(++thisAmountOfOvertimes > overtime) { overtime = thisAmountOfOvertimes; } } } } result += overtime * Evaluation.overtimeBlockCost; } } //fix parallelwerk for(Day d: solution.horizon) { if(d.parallelwerk) { boolean inparallel = false; for(int i=0; i<solution.problem.getLastDayShiftIndex()+1; i++) { boolean blockInUse = false; for(Machine m: solution.problem.getMachines()) { if(!d.jobs[m.getMachineId()][i].equals(new Idle())) { if(blockInUse == true) { inparallel = true; break; } else { blockInUse = true; } } } if(inparallel) { break; } } if(inparallel) { result += Evaluation.parallelCost; } } } //add unshipped requests cost for(Request r: solution.problem.getRequests()) { if(!shippedRequests.contains(r)) { for(int itemId = 0; itemId < r.getAmountsRequested().length; itemId++) { result += (r.getAmountsRequested()[itemId] * itemRevenue[itemId]); } } } //look how close we came to fullfilling the first unfullfilled order. Request r = null; for(Request req: solution.requestOrder) { if(!shippedRequests.contains(req)) { //System.out.println("we get to this point!"); r = req; break; } } if(r != null) { //zoek de laatst mogelijke shippingdag int dayIndex = 0; for(int i=solution.horizon.length-1; i>=0; i++) { if(r.isShippingDay(i)) { //System.out.println("final shipping day found"); dayIndex = i; break; } } //System.out.println("Day " + dayIndex + ", request: " + r.getId()); //trek van<SUF> //voor elk item dat nodig is voor de request te kunnen verschepen, de hoeveelheid in stock op die dag * de revenue per item voor dat item. for(int itemId = 0; itemId < r.getAmountsRequested().length; itemId++) { int amountToSubtract = 0; if (r.getAmountsRequested()[itemId] != 0) { if (r.getAmountsRequested()[itemId] - solution.horizon[dayIndex].stock[itemId] > 0) { amountToSubtract = solution.horizon[dayIndex].stock[itemId]; } else { amountToSubtract = r.getAmountsRequested()[itemId]; } //System.out.println("subtracting: " + amountToSubtract * Evaluation.itemRevenue[itemId]); result -= amountToSubtract * Evaluation.itemRevenue[itemId]; } } } //check for not-full nightshifts if(solution.horizon[solution.horizon.length - 1].nachtshift) { int extraNightShiftsToPay = solution.problem.getMinimumConsecutiveNightShifts(); int count = extraNightShiftsToPay; if(extraNightShiftsToPay >= solution.horizon.length) { System.out.println("minAantalConsecutiveNightShifts > horizon.length"); } for(int i=1; i<count; i++) { if(solution.horizon[solution.horizon.length-i].nachtshift) { extraNightShiftsToPay--; } else { break; } } result += extraNightShiftsToPay * Evaluation.nightshiftCost; } //done return result; } }
196619_17
/* * L2jFrozen Project - www.l2jfrozen.com * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.l2jfrozen.gameserver.managers; import java.util.List; import java.util.Random; import java.util.concurrent.Future; import javolution.util.FastList; import org.apache.log4j.Logger; import com.l2jfrozen.Config; import com.l2jfrozen.gameserver.datatables.sql.ItemTable; import com.l2jfrozen.gameserver.datatables.sql.NpcTable; import com.l2jfrozen.gameserver.datatables.sql.SpawnTable; import com.l2jfrozen.gameserver.idfactory.IdFactory; import com.l2jfrozen.gameserver.model.L2Attackable; import com.l2jfrozen.gameserver.model.L2Object; import com.l2jfrozen.gameserver.model.L2World; import com.l2jfrozen.gameserver.model.actor.instance.L2ItemInstance; import com.l2jfrozen.gameserver.model.actor.instance.L2NpcInstance; import com.l2jfrozen.gameserver.model.actor.instance.L2PcInstance; import com.l2jfrozen.gameserver.model.entity.Announcements; import com.l2jfrozen.gameserver.model.spawn.L2Spawn; import com.l2jfrozen.gameserver.network.SystemMessageId; import com.l2jfrozen.gameserver.network.serverpackets.CreatureSay; import com.l2jfrozen.gameserver.network.serverpackets.SystemMessage; import com.l2jfrozen.gameserver.templates.L2NpcTemplate; import com.l2jfrozen.gameserver.thread.ThreadPoolManager; /** * control for sequence of Christmas. * @version 1.00 * @author Darki699 */ public class ChristmasManager { private static final Logger LOGGER = Logger.getLogger(ChristmasManager.class); protected List<L2NpcInstance> objectQueue = new FastList<>(); protected Random rand = new Random(); // X-Mas message list protected String[] message = { "Ho Ho Ho... Merry Christmas!", "God is Love...", "Christmas is all about love...", "Christmas is thus about God and Love...", "Love is the key to peace among all Lineage creature kind..", "Love is the key to peace and happiness within all creation...", "Love needs to be practiced - Love needs to flow - Love needs to make happy...", "Love starts with your partner, children and family and expands to all world.", "God bless all kind.", "God bless Lineage.", "Forgive all.", "Ask for forgiveness even from all the \"past away\" ones.", "Give love in many different ways to your family members, relatives, neighbors and \"foreigners\".", "Enhance the feeling within yourself of being a member of a far larger family than your physical family", "MOST important - Christmas is a feast of BLISS given to YOU from God and all beloved ones back home in God !!", "Open yourself for all divine bliss, forgiveness and divine help that is offered TO YOU by many others AND GOD.", "Take it easy. Relax these coming days.", "Every day is Christmas day - it is UP TO YOU to create the proper inner attitude and opening for love toward others AND from others within YOUR SELF !", "Peace and Silence. Reduced activities. More time for your most direct families. If possible NO other dates or travel may help you most to actually RECEIVE all offered bliss.", "What ever is offered to you from God either enters YOUR heart and soul or is LOST for GOOD !!! or at least until another such day - next year Christmas or so !!", "Divine bliss and love NEVER can be stored and received later.", "There is year round a huge quantity of love and bliss available from God and your Guru and other loving souls, but Christmas days are an extended period FOR ALL PLANET", "Please open your heart and accept all love and bliss - For your benefit as well as for the benefit of all your beloved ones.", "Beloved children of God", "Beyond Christmas days and beyond Christmas season - The Christmas love lives on, the Christmas bliss goes on, the Christmas feeling expands.", "The holy spirit of Christmas is the holy spirit of God and God's love for all days.", "When the Christmas spirit lives on and on...", "When the power of love created during the pre-Christmas days is kept alive and growing.", "Peace among all mankind is growing as well =)", "The holy gift of love is an eternal gift of love put into your heart like a seed.", "Dozens of millions of humans worldwide are changing in their hearts during weeks of pre-Christmas time and find their peak power of love on Christmas nights and Christmas days.", "What is special during these days, to give all of you this very special power of love, the power to forgive, the power to make others happy, power to join the loved one on his or her path of loving life.", "It only is your now decision that makes the difference !", "It only is your now focus in life that makes all the changes. It is your shift from purely worldly matters toward the power of love from God that dwells within all of us that gave you the power to change your own behavior from your normal year long behavior.", "The decision of love, peace and happiness is the right one.", "Whatever you focus on is filling your mind and subsequently filling your heart.", "No one else but you have change your focus these past Christmas days and the days of love you may have experienced in earlier Christmas seasons.", "God's love is always present.", "God's Love has always been in same power and purity and quantity available to all of you.", "Expand the spirit of Christmas love and Christmas joy to span all year of your life...", "Do all year long what is creating this special Christmas feeling of love joy and happiness.", "Expand the true Christmas feeling, expand the love you have ever given at your maximum power of love days ... ", "Expand the power of love over more and more days.", "Re-focus on what has brought your love to its peak power and refocus on those objects and actions in your focus of mind and actions.", "Remember the people and surrounding you had when feeling most happy, most loved, most magic", "People of true loving spirit - who all was present, recall their names, recall the one who may have had the greatest impact in love those hours of magic moments of love...", "The decoration of your surrounding - Decoration may help to focus on love - Or lack of decoration may make you drift away into darkness or business - away from love...", "Love songs, songs full of living joy - any of the thousands of true touching love songs and happy songs do contribute to the establishment of an inner attitude perceptible of love.", "Songs can fine tune and open our heart for love from God and our loved ones.", "Your power of will and focus of mind can keep Christmas Love and Christmas joy alive beyond Christmas season for eternity", "Enjoy your love for ever!", "Christmas can be every day - As soon as you truly love every day =)", "Christmas is when you love all and are loved by all.", "Christmas is when you are truly happy by creating true happiness in others with love from the bottom of your heart.", "Secret in God's creation is that no single person can truly love without ignition of his love.", "You need another person to love and to receive love, a person to truly fall in love to ignite your own divine fire of love. ", "God created many and all are made of love and all are made to love...", "The miracle of love only works if you want to become a fully loving member of the family of divine love.", "Once you have started to fall in love with the one God created for you - your entire eternal life will be a permanent fire of miracles of love ... Eternally !", "May all have a happy time on Christmas each year. Merry Christmas!", "Christmas day is a time for love. It is a time for showing our affection to our loved ones. It is all about love.", "Have a wonderful Christmas. May god bless our family. I love you all.", "Wish all living creatures a Happy X-mas and a Happy New Year! By the way I would like us to share a warm fellowship in all places.", "Just as animals need peace of mind, poeple and also trees need peace of mind. This is why I say, all creatures are waiting upon the Lord for their salvation. May God bless you all creatures in the whole world.", "Merry Xmas!", "May the grace of Our Mighty Father be with you all during this eve of Christmas. Have a blessed Christmas and a happy New Year.", "Merry Christmas my children. May this new year give all of the things you rightly deserve. And may peace finally be yours.", "I wish everybody a Merry Christmas! May the Holy Spirit be with you all the time.", "May you have the best of Christmas this year and all your dreams come true.", "May the miracle of Christmas fill your heart with warmth and love. Merry Christmas!" }, sender = { "Santa Claus", "Papai Noel", "Shengdan Laoren", "Santa", "Viejo Pascuero", "Sinter Klaas", "Father Christmas", "Saint Nicholas", "Joulupukki", "Pere Noel", "Saint Nikolaus", "Kanakaloka", "De Kerstman", "Winter grandfather", "Babbo Natale", "Hoteiosho", "Kaledu Senelis", "Black Peter", "Kerstman", "Julenissen", "Swiety Mikolaj", "Ded Moroz", "Julenisse", "El Nino Jesus", "Jultomten", "Reindeer Dasher", "Reindeer Dancer", "Christmas Spirit", "Reindeer Prancer", "Reindeer Vixen", "Reindeer Comet", "Reindeer Cupid", "Reindeer Donner", "Reindeer Donder", "Reindeer Dunder", "Reindeer Blitzen", "Reindeer Bliksem", "Reindeer Blixem", "Reindeer Rudolf", "Christmas Elf" }; // Presents List: protected int[] presents = { 5560, 5560, 5560, 5560, 5560, /* x-mas tree */ 5560, 5560, 5560, 5560, 5560, 5561, 5561, 5561, 5561, 5561, /* special x-mas tree */ 5562, 5562, 5562, 5562, /* 1st Carol */ 5563, 5563, 5563, 5563, /* 2nd Carol */ 5564, 5564, 5564, 5564, /* 3rd Carol */ 5565, 5565, 5565, 5565, /* 4th Carol */ 5566, 5566, 5566, 5566, /* 5th Carol */ 5583, 5583, /* 6th Carol */ 5584, 5584, /* 7th Carol */ 5585, 5585, /* 8th Carol */ 5586, 5586, /* 9th Carol */ 5587, 5587, /* 10th Carol */ 6403, 6403, 6403, 6403, /* Star Shard */ 6403, 6403, 6403, 6403, 6406, 6406, 6406, 6406, /* FireWorks */ 6407, 6407, /* Large FireWorks */ 5555, /* Token of Love */ 7836, /* Santa Hat #1 */ 9138, /* Santa Hat #2 */ 8936, /* Santa's Antlers Hat */ 6394, /* Red Party Mask */ 5808 /* Black Party Mask */ }; // The message task sent at fixed rate protected Future<?> _XMasMessageTask = null, _XMasPresentsTask = null; // Manager should only be Initialized once: protected int isManagerInit = 0; // Interval of Christmas actions: protected long _IntervalOfChristmas = 600000; // 10 minutes private final int first = 25000, last = 73099; /************************************** Initial Functions **************************************/ /** * Empty constructor Does nothing */ public ChristmasManager() { // } /** * @return an instance of <b>this</b> InstanceManager. */ public static ChristmasManager getInstance() { return SingletonHolder._instance; } /** * initialize <b>this</b> ChristmasManager * @param activeChar */ public void init(final L2PcInstance activeChar) { if (isManagerInit > 0) { activeChar.sendMessage("Christmas Manager has already begun or is processing. Please be patient...."); return; } activeChar.sendMessage("Started!!!! This will take a 2-3 hours (in order to reduce system lags to a minimum), please be patient... The process is working in the background and will spawn npcs, give presents and messages at a fixed rate."); // Tasks: spawnTrees(); startFestiveMessagesAtFixedRate(); isManagerInit++; givePresentsAtFixedRate(); isManagerInit++; checkIfOkToAnnounce(); } /** * ends <b>this</b> ChristmasManager * @param activeChar */ public void end(final L2PcInstance activeChar) { if (isManagerInit < 4) { if (activeChar != null) { activeChar.sendMessage("Christmas Manager is not activated yet. Already Ended or is now processing...."); } return; } if (activeChar != null) { activeChar.sendMessage("Terminating! This may take a while, please be patient..."); } // Tasks: ThreadPoolManager.getInstance().executeTask(new DeleteSpawns()); endFestiveMessagesAtFixedRate(); isManagerInit--; endPresentGivingAtFixedRate(); isManagerInit--; checkIfOkToAnnounce(); } /************************************ - Tree management - *************************************/ /** * Main function - spawns all trees. */ public void spawnTrees() { GetTreePos gtp = new GetTreePos(first); ThreadPoolManager.getInstance().executeTask(gtp); gtp = null; } /** * returns a random X-Mas tree Npc Id. * @return int tree Npc Id. */ protected int getTreeId() { final int[] ids = { 13006, 13007 }; return ids[rand.nextInt(ids.length)]; } /** * gets random world positions according to spawned world objects and spawns x-mas trees around them... */ public class GetTreePos implements Runnable { private int _iterator; private Future<?> _task; public GetTreePos(final int iter) { _iterator = iter; } public void setTask(final Future<?> task) { _task = task; } @Override public void run() { if (_task != null) { _task.cancel(true); _task = null; } try { L2Object obj = null; while (obj == null) { obj = SpawnTable.getInstance().getTemplate(_iterator).getLastSpawn(); _iterator++; if (obj != null && obj instanceof L2Attackable) if (rand.nextInt(100) > 10) { obj = null; } } if (rand.nextInt(100) > 50) { spawnOneTree(getTreeId(), obj.getX() + rand.nextInt(200) - 100, obj.getY() + rand.nextInt(200) - 100, obj.getZ()); } } catch (final Throwable t) { if (Config.ENABLE_ALL_EXCEPTIONS) t.printStackTrace(); } if (_iterator >= last) { isManagerInit++; SpawnSantaNPCs ssNPCs = new SpawnSantaNPCs(first); _task = ThreadPoolManager.getInstance().scheduleGeneral(ssNPCs, 300); ssNPCs.setTask(_task); ssNPCs = null; return; } _iterator++; GetTreePos gtp = new GetTreePos(_iterator); _task = ThreadPoolManager.getInstance().scheduleGeneral(gtp, 300); gtp.setTask(_task); gtp = null; } } /** * Delete all x-mas spawned trees from the world. Delete all x-mas trees spawns, and clears the L2NpcInstance tree queue. */ public class DeleteSpawns implements Runnable { @Override public void run() { if (objectQueue == null || objectQueue.isEmpty()) return; for (final L2NpcInstance deleted : objectQueue) { if (deleted == null) { continue; } try { L2World.getInstance().removeObject(deleted); deleted.decayMe(); deleted.deleteMe(); } catch (final Throwable t) { if (Config.ENABLE_ALL_EXCEPTIONS) t.printStackTrace(); continue; } } objectQueue.clear(); objectQueue = null; isManagerInit = isManagerInit - 2; checkIfOkToAnnounce(); } } /** * Spawns one x-mas tree at a given location x,y,z * @param id - int tree npc id. * @param x - int loc x * @param y - int loc y * @param z - int loc z */ protected void spawnOneTree(final int id, final int x, final int y, final int z) { try { L2NpcTemplate template1 = NpcTable.getInstance().getTemplate(id); L2Spawn spawn = new L2Spawn(template1); template1 = null; spawn.setId(IdFactory.getInstance().getNextId()); spawn.setLocx(x); spawn.setLocy(y); spawn.setLocz(z); L2NpcInstance tree = spawn.spawnOne(); L2World.getInstance().storeObject(tree); objectQueue.add(tree); spawn = null; tree = null; } catch (final Throwable t) { if (Config.ENABLE_ALL_EXCEPTIONS) t.printStackTrace(); } } /**************************** - send players festive messages - *****************************/ /** * Ends X-Mas messages sent to players, and terminates the thread. */ private void endFestiveMessagesAtFixedRate() { if (_XMasMessageTask != null) { _XMasMessageTask.cancel(true); _XMasMessageTask = null; } } /** * Starts X-Mas messages sent to all players, and initialize the thread. */ private void startFestiveMessagesAtFixedRate() { SendXMasMessage XMasMessage = new SendXMasMessage(); _XMasMessageTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(XMasMessage, 60000, _IntervalOfChristmas); XMasMessage = null; } /** * Sends X-Mas messages to all world players. * @author Darki699 */ class SendXMasMessage implements Runnable { @Override public void run() { try { for (final L2PcInstance pc : L2World.getInstance().getAllPlayers()) { if (pc == null) { continue; } else if (pc.isOnline() == 0) { continue; } pc.sendPacket(getXMasMessage()); } } catch (final Throwable t) { if (Config.ENABLE_ALL_EXCEPTIONS) t.printStackTrace(); } } } /** * Returns a random X-Mas message. * @return CreatureSay message */ protected CreatureSay getXMasMessage() { final CreatureSay cs = new CreatureSay(0, 17, getRandomSender(), getRandomXMasMessage()); return cs; } /** * Returns a random name of the X-Mas message sender, sent to players * @return String of the message sender's name */ private String getRandomSender() { return sender[rand.nextInt(sender.length)]; } /** * Returns a random X-Mas message String * @return String containing the random message. */ private String getRandomXMasMessage() { return message[rand.nextInt(message.length)]; } /******************************* - give special items trees - ********************************/ // Trees , Carols , Tokens of love, Fireworks, Santa Hats. /** * Starts X-Mas Santa presents sent to all players, and initialize the thread. */ private void givePresentsAtFixedRate() { final XMasPresentGivingTask XMasPresents = new XMasPresentGivingTask(); _XMasPresentsTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(XMasPresents, _IntervalOfChristmas, _IntervalOfChristmas * 3); } class XMasPresentGivingTask implements Runnable { @Override public void run() { try { for (final L2PcInstance pc : L2World.getInstance().getAllPlayers()) { if (pc == null) { continue; } else if (pc.isOnline() == 0) { continue; } else if (pc.getInventoryLimit() <= pc.getInventory().getSize()) { pc.sendMessage("Santa wanted to give you a Present but your inventory was full :("); continue; } else if (rand.nextInt(100) < 50) { final int itemId = getSantaRandomPresent(); L2ItemInstance item = ItemTable.getInstance().createItem("Christmas Event", itemId, 1, pc); pc.getInventory().addItem("Christmas Event", item.getItemId(), 1, pc, pc); String itemName = ItemTable.getInstance().getTemplate(itemId).getName(); item = null; SystemMessage sm; sm = new SystemMessage(SystemMessageId.EARNED_ITEM); sm.addString(itemName + " from Santa's Present Bag..."); pc.broadcastPacket(sm); itemName = null; sm = null; } } } catch (final Throwable t) { if (Config.ENABLE_ALL_EXCEPTIONS) t.printStackTrace(); } } } protected int getSantaRandomPresent() { return presents[rand.nextInt(presents.length)]; } /** * Ends X-Mas present giving to players, and terminates the thread. */ private void endPresentGivingAtFixedRate() { if (_XMasPresentsTask != null) { _XMasPresentsTask.cancel(true); _XMasPresentsTask = null; } } /************************************ - spawn NPCs in towns - ***************************************/ // NPC Ids: 31863 , 31864 public class SpawnSantaNPCs implements Runnable { private int _iterator; private Future<?> _task; public SpawnSantaNPCs(final int iter) { _iterator = iter; } public void setTask(final Future<?> task) { _task = task; } @Override public void run() { if (_task != null) { _task.cancel(true); _task = null; } try { L2Object obj = null; while (obj == null) { obj = SpawnTable.getInstance().getTemplate(_iterator).getLastSpawn(); _iterator++; if (obj != null && obj instanceof L2Attackable) { obj = null; } } if (rand.nextInt(100) < 80 && obj instanceof L2NpcInstance) { spawnOneTree(getSantaId(), obj.getX() + rand.nextInt(500) - 250, obj.getY() + rand.nextInt(500) - 250, obj.getZ()); } } catch (final Throwable t) { if (Config.ENABLE_ALL_EXCEPTIONS) t.printStackTrace(); } if (_iterator >= last) { isManagerInit++; checkIfOkToAnnounce(); return; } _iterator++; SpawnSantaNPCs ssNPCs = new SpawnSantaNPCs(_iterator); _task = ThreadPoolManager.getInstance().scheduleGeneral(ssNPCs, 300); ssNPCs.setTask(_task); ssNPCs = null; } } protected int getSantaId() { return rand.nextInt(100) < 50 ? 31863 : 31864; } protected void checkIfOkToAnnounce() { if (isManagerInit == 4) { Announcements.getInstance().announceToAll("Christmas Event has begun, have a Merry Christmas and a Happy New Year."); Announcements.getInstance().announceToAll("Christmas Event will end in 24 hours."); LOGGER.info("ChristmasManager:Init ChristmasManager was started successfully, have a festive holiday."); final EndEvent ee = new EndEvent(); Future<?> task = ThreadPoolManager.getInstance().scheduleGeneral(ee, 86400000); ee.setTask(task); task = null; isManagerInit = 5; } if (isManagerInit == 0) { Announcements.getInstance().announceToAll("Christmas Event has ended... Hope you enjoyed the festivities."); LOGGER.info("ChristmasManager:Terminated ChristmasManager."); isManagerInit = -1; } } public class EndEvent implements Runnable { private Future<?> _task; public void setTask(final Future<?> task) { _task = task; } @Override public void run() { if (_task != null) { _task.cancel(true); _task = null; } end(null); } } private static class SingletonHolder { protected static final ChristmasManager _instance = new ChristmasManager(); } }
CristianDeveloper/l2jfrozen
gameserver/head-src/com/l2jfrozen/gameserver/managers/ChristmasManager.java
8,005
/************************************ - Tree management - *************************************/
block_comment
nl
/* * L2jFrozen Project - www.l2jfrozen.com * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.l2jfrozen.gameserver.managers; import java.util.List; import java.util.Random; import java.util.concurrent.Future; import javolution.util.FastList; import org.apache.log4j.Logger; import com.l2jfrozen.Config; import com.l2jfrozen.gameserver.datatables.sql.ItemTable; import com.l2jfrozen.gameserver.datatables.sql.NpcTable; import com.l2jfrozen.gameserver.datatables.sql.SpawnTable; import com.l2jfrozen.gameserver.idfactory.IdFactory; import com.l2jfrozen.gameserver.model.L2Attackable; import com.l2jfrozen.gameserver.model.L2Object; import com.l2jfrozen.gameserver.model.L2World; import com.l2jfrozen.gameserver.model.actor.instance.L2ItemInstance; import com.l2jfrozen.gameserver.model.actor.instance.L2NpcInstance; import com.l2jfrozen.gameserver.model.actor.instance.L2PcInstance; import com.l2jfrozen.gameserver.model.entity.Announcements; import com.l2jfrozen.gameserver.model.spawn.L2Spawn; import com.l2jfrozen.gameserver.network.SystemMessageId; import com.l2jfrozen.gameserver.network.serverpackets.CreatureSay; import com.l2jfrozen.gameserver.network.serverpackets.SystemMessage; import com.l2jfrozen.gameserver.templates.L2NpcTemplate; import com.l2jfrozen.gameserver.thread.ThreadPoolManager; /** * control for sequence of Christmas. * @version 1.00 * @author Darki699 */ public class ChristmasManager { private static final Logger LOGGER = Logger.getLogger(ChristmasManager.class); protected List<L2NpcInstance> objectQueue = new FastList<>(); protected Random rand = new Random(); // X-Mas message list protected String[] message = { "Ho Ho Ho... Merry Christmas!", "God is Love...", "Christmas is all about love...", "Christmas is thus about God and Love...", "Love is the key to peace among all Lineage creature kind..", "Love is the key to peace and happiness within all creation...", "Love needs to be practiced - Love needs to flow - Love needs to make happy...", "Love starts with your partner, children and family and expands to all world.", "God bless all kind.", "God bless Lineage.", "Forgive all.", "Ask for forgiveness even from all the \"past away\" ones.", "Give love in many different ways to your family members, relatives, neighbors and \"foreigners\".", "Enhance the feeling within yourself of being a member of a far larger family than your physical family", "MOST important - Christmas is a feast of BLISS given to YOU from God and all beloved ones back home in God !!", "Open yourself for all divine bliss, forgiveness and divine help that is offered TO YOU by many others AND GOD.", "Take it easy. Relax these coming days.", "Every day is Christmas day - it is UP TO YOU to create the proper inner attitude and opening for love toward others AND from others within YOUR SELF !", "Peace and Silence. Reduced activities. More time for your most direct families. If possible NO other dates or travel may help you most to actually RECEIVE all offered bliss.", "What ever is offered to you from God either enters YOUR heart and soul or is LOST for GOOD !!! or at least until another such day - next year Christmas or so !!", "Divine bliss and love NEVER can be stored and received later.", "There is year round a huge quantity of love and bliss available from God and your Guru and other loving souls, but Christmas days are an extended period FOR ALL PLANET", "Please open your heart and accept all love and bliss - For your benefit as well as for the benefit of all your beloved ones.", "Beloved children of God", "Beyond Christmas days and beyond Christmas season - The Christmas love lives on, the Christmas bliss goes on, the Christmas feeling expands.", "The holy spirit of Christmas is the holy spirit of God and God's love for all days.", "When the Christmas spirit lives on and on...", "When the power of love created during the pre-Christmas days is kept alive and growing.", "Peace among all mankind is growing as well =)", "The holy gift of love is an eternal gift of love put into your heart like a seed.", "Dozens of millions of humans worldwide are changing in their hearts during weeks of pre-Christmas time and find their peak power of love on Christmas nights and Christmas days.", "What is special during these days, to give all of you this very special power of love, the power to forgive, the power to make others happy, power to join the loved one on his or her path of loving life.", "It only is your now decision that makes the difference !", "It only is your now focus in life that makes all the changes. It is your shift from purely worldly matters toward the power of love from God that dwells within all of us that gave you the power to change your own behavior from your normal year long behavior.", "The decision of love, peace and happiness is the right one.", "Whatever you focus on is filling your mind and subsequently filling your heart.", "No one else but you have change your focus these past Christmas days and the days of love you may have experienced in earlier Christmas seasons.", "God's love is always present.", "God's Love has always been in same power and purity and quantity available to all of you.", "Expand the spirit of Christmas love and Christmas joy to span all year of your life...", "Do all year long what is creating this special Christmas feeling of love joy and happiness.", "Expand the true Christmas feeling, expand the love you have ever given at your maximum power of love days ... ", "Expand the power of love over more and more days.", "Re-focus on what has brought your love to its peak power and refocus on those objects and actions in your focus of mind and actions.", "Remember the people and surrounding you had when feeling most happy, most loved, most magic", "People of true loving spirit - who all was present, recall their names, recall the one who may have had the greatest impact in love those hours of magic moments of love...", "The decoration of your surrounding - Decoration may help to focus on love - Or lack of decoration may make you drift away into darkness or business - away from love...", "Love songs, songs full of living joy - any of the thousands of true touching love songs and happy songs do contribute to the establishment of an inner attitude perceptible of love.", "Songs can fine tune and open our heart for love from God and our loved ones.", "Your power of will and focus of mind can keep Christmas Love and Christmas joy alive beyond Christmas season for eternity", "Enjoy your love for ever!", "Christmas can be every day - As soon as you truly love every day =)", "Christmas is when you love all and are loved by all.", "Christmas is when you are truly happy by creating true happiness in others with love from the bottom of your heart.", "Secret in God's creation is that no single person can truly love without ignition of his love.", "You need another person to love and to receive love, a person to truly fall in love to ignite your own divine fire of love. ", "God created many and all are made of love and all are made to love...", "The miracle of love only works if you want to become a fully loving member of the family of divine love.", "Once you have started to fall in love with the one God created for you - your entire eternal life will be a permanent fire of miracles of love ... Eternally !", "May all have a happy time on Christmas each year. Merry Christmas!", "Christmas day is a time for love. It is a time for showing our affection to our loved ones. It is all about love.", "Have a wonderful Christmas. May god bless our family. I love you all.", "Wish all living creatures a Happy X-mas and a Happy New Year! By the way I would like us to share a warm fellowship in all places.", "Just as animals need peace of mind, poeple and also trees need peace of mind. This is why I say, all creatures are waiting upon the Lord for their salvation. May God bless you all creatures in the whole world.", "Merry Xmas!", "May the grace of Our Mighty Father be with you all during this eve of Christmas. Have a blessed Christmas and a happy New Year.", "Merry Christmas my children. May this new year give all of the things you rightly deserve. And may peace finally be yours.", "I wish everybody a Merry Christmas! May the Holy Spirit be with you all the time.", "May you have the best of Christmas this year and all your dreams come true.", "May the miracle of Christmas fill your heart with warmth and love. Merry Christmas!" }, sender = { "Santa Claus", "Papai Noel", "Shengdan Laoren", "Santa", "Viejo Pascuero", "Sinter Klaas", "Father Christmas", "Saint Nicholas", "Joulupukki", "Pere Noel", "Saint Nikolaus", "Kanakaloka", "De Kerstman", "Winter grandfather", "Babbo Natale", "Hoteiosho", "Kaledu Senelis", "Black Peter", "Kerstman", "Julenissen", "Swiety Mikolaj", "Ded Moroz", "Julenisse", "El Nino Jesus", "Jultomten", "Reindeer Dasher", "Reindeer Dancer", "Christmas Spirit", "Reindeer Prancer", "Reindeer Vixen", "Reindeer Comet", "Reindeer Cupid", "Reindeer Donner", "Reindeer Donder", "Reindeer Dunder", "Reindeer Blitzen", "Reindeer Bliksem", "Reindeer Blixem", "Reindeer Rudolf", "Christmas Elf" }; // Presents List: protected int[] presents = { 5560, 5560, 5560, 5560, 5560, /* x-mas tree */ 5560, 5560, 5560, 5560, 5560, 5561, 5561, 5561, 5561, 5561, /* special x-mas tree */ 5562, 5562, 5562, 5562, /* 1st Carol */ 5563, 5563, 5563, 5563, /* 2nd Carol */ 5564, 5564, 5564, 5564, /* 3rd Carol */ 5565, 5565, 5565, 5565, /* 4th Carol */ 5566, 5566, 5566, 5566, /* 5th Carol */ 5583, 5583, /* 6th Carol */ 5584, 5584, /* 7th Carol */ 5585, 5585, /* 8th Carol */ 5586, 5586, /* 9th Carol */ 5587, 5587, /* 10th Carol */ 6403, 6403, 6403, 6403, /* Star Shard */ 6403, 6403, 6403, 6403, 6406, 6406, 6406, 6406, /* FireWorks */ 6407, 6407, /* Large FireWorks */ 5555, /* Token of Love */ 7836, /* Santa Hat #1 */ 9138, /* Santa Hat #2 */ 8936, /* Santa's Antlers Hat */ 6394, /* Red Party Mask */ 5808 /* Black Party Mask */ }; // The message task sent at fixed rate protected Future<?> _XMasMessageTask = null, _XMasPresentsTask = null; // Manager should only be Initialized once: protected int isManagerInit = 0; // Interval of Christmas actions: protected long _IntervalOfChristmas = 600000; // 10 minutes private final int first = 25000, last = 73099; /************************************** Initial Functions **************************************/ /** * Empty constructor Does nothing */ public ChristmasManager() { // } /** * @return an instance of <b>this</b> InstanceManager. */ public static ChristmasManager getInstance() { return SingletonHolder._instance; } /** * initialize <b>this</b> ChristmasManager * @param activeChar */ public void init(final L2PcInstance activeChar) { if (isManagerInit > 0) { activeChar.sendMessage("Christmas Manager has already begun or is processing. Please be patient...."); return; } activeChar.sendMessage("Started!!!! This will take a 2-3 hours (in order to reduce system lags to a minimum), please be patient... The process is working in the background and will spawn npcs, give presents and messages at a fixed rate."); // Tasks: spawnTrees(); startFestiveMessagesAtFixedRate(); isManagerInit++; givePresentsAtFixedRate(); isManagerInit++; checkIfOkToAnnounce(); } /** * ends <b>this</b> ChristmasManager * @param activeChar */ public void end(final L2PcInstance activeChar) { if (isManagerInit < 4) { if (activeChar != null) { activeChar.sendMessage("Christmas Manager is not activated yet. Already Ended or is now processing...."); } return; } if (activeChar != null) { activeChar.sendMessage("Terminating! This may take a while, please be patient..."); } // Tasks: ThreadPoolManager.getInstance().executeTask(new DeleteSpawns()); endFestiveMessagesAtFixedRate(); isManagerInit--; endPresentGivingAtFixedRate(); isManagerInit--; checkIfOkToAnnounce(); } /************************************ - Tree management<SUF>*/ /** * Main function - spawns all trees. */ public void spawnTrees() { GetTreePos gtp = new GetTreePos(first); ThreadPoolManager.getInstance().executeTask(gtp); gtp = null; } /** * returns a random X-Mas tree Npc Id. * @return int tree Npc Id. */ protected int getTreeId() { final int[] ids = { 13006, 13007 }; return ids[rand.nextInt(ids.length)]; } /** * gets random world positions according to spawned world objects and spawns x-mas trees around them... */ public class GetTreePos implements Runnable { private int _iterator; private Future<?> _task; public GetTreePos(final int iter) { _iterator = iter; } public void setTask(final Future<?> task) { _task = task; } @Override public void run() { if (_task != null) { _task.cancel(true); _task = null; } try { L2Object obj = null; while (obj == null) { obj = SpawnTable.getInstance().getTemplate(_iterator).getLastSpawn(); _iterator++; if (obj != null && obj instanceof L2Attackable) if (rand.nextInt(100) > 10) { obj = null; } } if (rand.nextInt(100) > 50) { spawnOneTree(getTreeId(), obj.getX() + rand.nextInt(200) - 100, obj.getY() + rand.nextInt(200) - 100, obj.getZ()); } } catch (final Throwable t) { if (Config.ENABLE_ALL_EXCEPTIONS) t.printStackTrace(); } if (_iterator >= last) { isManagerInit++; SpawnSantaNPCs ssNPCs = new SpawnSantaNPCs(first); _task = ThreadPoolManager.getInstance().scheduleGeneral(ssNPCs, 300); ssNPCs.setTask(_task); ssNPCs = null; return; } _iterator++; GetTreePos gtp = new GetTreePos(_iterator); _task = ThreadPoolManager.getInstance().scheduleGeneral(gtp, 300); gtp.setTask(_task); gtp = null; } } /** * Delete all x-mas spawned trees from the world. Delete all x-mas trees spawns, and clears the L2NpcInstance tree queue. */ public class DeleteSpawns implements Runnable { @Override public void run() { if (objectQueue == null || objectQueue.isEmpty()) return; for (final L2NpcInstance deleted : objectQueue) { if (deleted == null) { continue; } try { L2World.getInstance().removeObject(deleted); deleted.decayMe(); deleted.deleteMe(); } catch (final Throwable t) { if (Config.ENABLE_ALL_EXCEPTIONS) t.printStackTrace(); continue; } } objectQueue.clear(); objectQueue = null; isManagerInit = isManagerInit - 2; checkIfOkToAnnounce(); } } /** * Spawns one x-mas tree at a given location x,y,z * @param id - int tree npc id. * @param x - int loc x * @param y - int loc y * @param z - int loc z */ protected void spawnOneTree(final int id, final int x, final int y, final int z) { try { L2NpcTemplate template1 = NpcTable.getInstance().getTemplate(id); L2Spawn spawn = new L2Spawn(template1); template1 = null; spawn.setId(IdFactory.getInstance().getNextId()); spawn.setLocx(x); spawn.setLocy(y); spawn.setLocz(z); L2NpcInstance tree = spawn.spawnOne(); L2World.getInstance().storeObject(tree); objectQueue.add(tree); spawn = null; tree = null; } catch (final Throwable t) { if (Config.ENABLE_ALL_EXCEPTIONS) t.printStackTrace(); } } /**************************** - send players festive messages - *****************************/ /** * Ends X-Mas messages sent to players, and terminates the thread. */ private void endFestiveMessagesAtFixedRate() { if (_XMasMessageTask != null) { _XMasMessageTask.cancel(true); _XMasMessageTask = null; } } /** * Starts X-Mas messages sent to all players, and initialize the thread. */ private void startFestiveMessagesAtFixedRate() { SendXMasMessage XMasMessage = new SendXMasMessage(); _XMasMessageTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(XMasMessage, 60000, _IntervalOfChristmas); XMasMessage = null; } /** * Sends X-Mas messages to all world players. * @author Darki699 */ class SendXMasMessage implements Runnable { @Override public void run() { try { for (final L2PcInstance pc : L2World.getInstance().getAllPlayers()) { if (pc == null) { continue; } else if (pc.isOnline() == 0) { continue; } pc.sendPacket(getXMasMessage()); } } catch (final Throwable t) { if (Config.ENABLE_ALL_EXCEPTIONS) t.printStackTrace(); } } } /** * Returns a random X-Mas message. * @return CreatureSay message */ protected CreatureSay getXMasMessage() { final CreatureSay cs = new CreatureSay(0, 17, getRandomSender(), getRandomXMasMessage()); return cs; } /** * Returns a random name of the X-Mas message sender, sent to players * @return String of the message sender's name */ private String getRandomSender() { return sender[rand.nextInt(sender.length)]; } /** * Returns a random X-Mas message String * @return String containing the random message. */ private String getRandomXMasMessage() { return message[rand.nextInt(message.length)]; } /******************************* - give special items trees - ********************************/ // Trees , Carols , Tokens of love, Fireworks, Santa Hats. /** * Starts X-Mas Santa presents sent to all players, and initialize the thread. */ private void givePresentsAtFixedRate() { final XMasPresentGivingTask XMasPresents = new XMasPresentGivingTask(); _XMasPresentsTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(XMasPresents, _IntervalOfChristmas, _IntervalOfChristmas * 3); } class XMasPresentGivingTask implements Runnable { @Override public void run() { try { for (final L2PcInstance pc : L2World.getInstance().getAllPlayers()) { if (pc == null) { continue; } else if (pc.isOnline() == 0) { continue; } else if (pc.getInventoryLimit() <= pc.getInventory().getSize()) { pc.sendMessage("Santa wanted to give you a Present but your inventory was full :("); continue; } else if (rand.nextInt(100) < 50) { final int itemId = getSantaRandomPresent(); L2ItemInstance item = ItemTable.getInstance().createItem("Christmas Event", itemId, 1, pc); pc.getInventory().addItem("Christmas Event", item.getItemId(), 1, pc, pc); String itemName = ItemTable.getInstance().getTemplate(itemId).getName(); item = null; SystemMessage sm; sm = new SystemMessage(SystemMessageId.EARNED_ITEM); sm.addString(itemName + " from Santa's Present Bag..."); pc.broadcastPacket(sm); itemName = null; sm = null; } } } catch (final Throwable t) { if (Config.ENABLE_ALL_EXCEPTIONS) t.printStackTrace(); } } } protected int getSantaRandomPresent() { return presents[rand.nextInt(presents.length)]; } /** * Ends X-Mas present giving to players, and terminates the thread. */ private void endPresentGivingAtFixedRate() { if (_XMasPresentsTask != null) { _XMasPresentsTask.cancel(true); _XMasPresentsTask = null; } } /************************************ - spawn NPCs in towns - ***************************************/ // NPC Ids: 31863 , 31864 public class SpawnSantaNPCs implements Runnable { private int _iterator; private Future<?> _task; public SpawnSantaNPCs(final int iter) { _iterator = iter; } public void setTask(final Future<?> task) { _task = task; } @Override public void run() { if (_task != null) { _task.cancel(true); _task = null; } try { L2Object obj = null; while (obj == null) { obj = SpawnTable.getInstance().getTemplate(_iterator).getLastSpawn(); _iterator++; if (obj != null && obj instanceof L2Attackable) { obj = null; } } if (rand.nextInt(100) < 80 && obj instanceof L2NpcInstance) { spawnOneTree(getSantaId(), obj.getX() + rand.nextInt(500) - 250, obj.getY() + rand.nextInt(500) - 250, obj.getZ()); } } catch (final Throwable t) { if (Config.ENABLE_ALL_EXCEPTIONS) t.printStackTrace(); } if (_iterator >= last) { isManagerInit++; checkIfOkToAnnounce(); return; } _iterator++; SpawnSantaNPCs ssNPCs = new SpawnSantaNPCs(_iterator); _task = ThreadPoolManager.getInstance().scheduleGeneral(ssNPCs, 300); ssNPCs.setTask(_task); ssNPCs = null; } } protected int getSantaId() { return rand.nextInt(100) < 50 ? 31863 : 31864; } protected void checkIfOkToAnnounce() { if (isManagerInit == 4) { Announcements.getInstance().announceToAll("Christmas Event has begun, have a Merry Christmas and a Happy New Year."); Announcements.getInstance().announceToAll("Christmas Event will end in 24 hours."); LOGGER.info("ChristmasManager:Init ChristmasManager was started successfully, have a festive holiday."); final EndEvent ee = new EndEvent(); Future<?> task = ThreadPoolManager.getInstance().scheduleGeneral(ee, 86400000); ee.setTask(task); task = null; isManagerInit = 5; } if (isManagerInit == 0) { Announcements.getInstance().announceToAll("Christmas Event has ended... Hope you enjoyed the festivities."); LOGGER.info("ChristmasManager:Terminated ChristmasManager."); isManagerInit = -1; } } public class EndEvent implements Runnable { private Future<?> _task; public void setTask(final Future<?> task) { _task = task; } @Override public void run() { if (_task != null) { _task.cancel(true); _task = null; } end(null); } } private static class SingletonHolder { protected static final ChristmasManager _instance = new ChristmasManager(); } }
11974_1
/* * Copyright (C) 2016 The CyanogenMod Project * * 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.cyanogenmod.lockclock.weather; import android.content.Context; import android.content.res.Resources; import com.cyanogenmod.lockclock.R; import cyanogenmod.app.CMContextConstants; import cyanogenmod.providers.WeatherContract; import static cyanogenmod.providers.WeatherContract.WeatherColumns.WeatherCode.NOT_AVAILABLE; import static cyanogenmod.providers.WeatherContract.WeatherColumns.WeatherCode.SCATTERED_THUNDERSTORMS; import static cyanogenmod.providers.WeatherContract.WeatherColumns.WeatherCode.SCATTERED_SNOW_SHOWERS; import static cyanogenmod.providers.WeatherContract.WeatherColumns.WeatherCode.ISOLATED_THUNDERSHOWERS; import java.text.DecimalFormat; public final class Utils { private static final DecimalFormat sNoDigitsFormat = new DecimalFormat("0"); // In doubt? See https://en.wikipedia.org/wiki/Points_of_the_compass private static final double DIRECTION_NORTH = 23d; private static final double DIRECTION_NORTH_EAST = 68d; private static final double DIRECTION_EAST = 113d; private static final double DIRECTION_SOUTH_EAST = 158d; private static final double DIRECTION_SOUTH = 203d; private static final double DIRECTION_SOUTH_WEST = 248d; private static final double DIRECTION_WEST = 293d; private static final double DIRECTION_NORTH_WEST = 338d; private static boolean weatherServiceFeatureCached; private static boolean weatherServiceAvailable; /** * Returns a localized string of the wind direction * @param context Application context to access resources * @param windDirection The wind direction in degrees * @return */ public static String resolveWindDirection(Context context, double windDirection) { int resId; if (windDirection < 0) { resId = R.string.unknown; } else if (windDirection < DIRECTION_NORTH) { resId = R.string.weather_N; } else if (windDirection < DIRECTION_NORTH_EAST) { resId = R.string.weather_NE; } else if (windDirection < DIRECTION_EAST) { resId = R.string.weather_E; } else if (windDirection < DIRECTION_SOUTH_EAST) { resId = R.string.weather_SE; } else if (windDirection < DIRECTION_SOUTH) { resId = R.string.weather_S; } else if (windDirection < DIRECTION_SOUTH_WEST) { resId = R.string.weather_SW; } else if (windDirection < DIRECTION_WEST) { resId = R.string.weather_W; } else if (windDirection < DIRECTION_NORTH_WEST) { resId = R.string.weather_NW; } else { resId = R.string.weather_N; } return context.getString(resId); } /** * Returns the resource name associated to the supplied weather condition code * @param context Application context to access resources * @param conditionCode The weather condition code * @return The resource name if a valid condition code is passed, empty string otherwise */ public static String resolveWeatherCondition(Context context, int conditionCode) { final Resources res = context.getResources(); final int resId = res.getIdentifier("weather_" + Utils.addOffsetToConditionCodeFromWeatherContract(conditionCode), "string", context.getPackageName()); if (resId != 0) { return res.getString(resId); } return ""; } private static String getFormattedValue(double value, String unit) { if (Double.isNaN(value)) { return "-"; } String formatted = sNoDigitsFormat.format(value); if (formatted.equals("-0")) { formatted = "0"; } return formatted + unit; } /** * Returns a string with the format xx% (where xx is the humidity value provided) * @param humidity The humidity value * @return The formatted string if a valid value is provided, "-" otherwise. Decimals are * removed */ public static String formatHumidity(double humidity) { return getFormattedValue(humidity, "%"); } /** * Returns a localized string of the speed and speed unit * @param context Application context to access resources * @param windSpeed The wind speed * @param windSpeedUnit The speed unit. See * {@link cyanogenmod.providers.WeatherContract.WeatherColumns.WindSpeedUnit} * @return The formatted string if a valid speed and speed unit a provided. * {@link com.cyanogenmod.lockclock.R.string#unknown} otherwise */ public static String formatWindSpeed(Context context, double windSpeed, int windSpeedUnit) { if (windSpeed < 0) { return context.getString(R.string.unknown); } String localizedSpeedUnit; switch (windSpeedUnit) { case WeatherContract.WeatherColumns.WindSpeedUnit.MPH: localizedSpeedUnit = context.getString(R.string.weather_mph); break; case WeatherContract.WeatherColumns.WindSpeedUnit.KPH: localizedSpeedUnit = context.getString(R.string.weather_kph); break; default: return context.getString(R.string.unknown); } return getFormattedValue(windSpeed, localizedSpeedUnit); } /** * Helper method to convert miles to kilometers * @param miles The value in miles * @return The value in kilometers */ public static double milesToKilometers(double miles) { return miles * 1.609344d; } /** * Helper method to convert kilometers to miles * @param km The value in kilometers * @return The value in miles */ public static double kilometersToMiles(double km) { return km * 0.6214d; } /** * Adds an offset to the condition code reported by the active weather service provider. * @param conditionCode The condition code from the Weather API * @return A condition code that correctly maps to our resource IDs */ public static int addOffsetToConditionCodeFromWeatherContract(int conditionCode) { if (conditionCode <= WeatherContract.WeatherColumns.WeatherCode.SHOWERS) { return conditionCode; } else if (conditionCode <= SCATTERED_THUNDERSTORMS) { return conditionCode + 1; } else if (conditionCode <= SCATTERED_SNOW_SHOWERS) { return conditionCode + 2; } else if (conditionCode <= ISOLATED_THUNDERSHOWERS) { return conditionCode + 3; } else { return NOT_AVAILABLE; } } /** * Checks if the CM Weather service is available in this device * @param context * @return true if service is available, false otherwise */ public static boolean isWeatherServiceAvailable(Context context) { if (!weatherServiceFeatureCached) { weatherServiceAvailable = context.getPackageManager() .hasSystemFeature(CMContextConstants.Features.WEATHER_SERVICES); weatherServiceFeatureCached = true; } return weatherServiceAvailable; } }
CyanogenMod/android_packages_apps_LockClock
src/com/cyanogenmod/lockclock/weather/Utils.java
2,167
// In doubt? See https://en.wikipedia.org/wiki/Points_of_the_compass
line_comment
nl
/* * Copyright (C) 2016 The CyanogenMod Project * * 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.cyanogenmod.lockclock.weather; import android.content.Context; import android.content.res.Resources; import com.cyanogenmod.lockclock.R; import cyanogenmod.app.CMContextConstants; import cyanogenmod.providers.WeatherContract; import static cyanogenmod.providers.WeatherContract.WeatherColumns.WeatherCode.NOT_AVAILABLE; import static cyanogenmod.providers.WeatherContract.WeatherColumns.WeatherCode.SCATTERED_THUNDERSTORMS; import static cyanogenmod.providers.WeatherContract.WeatherColumns.WeatherCode.SCATTERED_SNOW_SHOWERS; import static cyanogenmod.providers.WeatherContract.WeatherColumns.WeatherCode.ISOLATED_THUNDERSHOWERS; import java.text.DecimalFormat; public final class Utils { private static final DecimalFormat sNoDigitsFormat = new DecimalFormat("0"); // In doubt?<SUF> private static final double DIRECTION_NORTH = 23d; private static final double DIRECTION_NORTH_EAST = 68d; private static final double DIRECTION_EAST = 113d; private static final double DIRECTION_SOUTH_EAST = 158d; private static final double DIRECTION_SOUTH = 203d; private static final double DIRECTION_SOUTH_WEST = 248d; private static final double DIRECTION_WEST = 293d; private static final double DIRECTION_NORTH_WEST = 338d; private static boolean weatherServiceFeatureCached; private static boolean weatherServiceAvailable; /** * Returns a localized string of the wind direction * @param context Application context to access resources * @param windDirection The wind direction in degrees * @return */ public static String resolveWindDirection(Context context, double windDirection) { int resId; if (windDirection < 0) { resId = R.string.unknown; } else if (windDirection < DIRECTION_NORTH) { resId = R.string.weather_N; } else if (windDirection < DIRECTION_NORTH_EAST) { resId = R.string.weather_NE; } else if (windDirection < DIRECTION_EAST) { resId = R.string.weather_E; } else if (windDirection < DIRECTION_SOUTH_EAST) { resId = R.string.weather_SE; } else if (windDirection < DIRECTION_SOUTH) { resId = R.string.weather_S; } else if (windDirection < DIRECTION_SOUTH_WEST) { resId = R.string.weather_SW; } else if (windDirection < DIRECTION_WEST) { resId = R.string.weather_W; } else if (windDirection < DIRECTION_NORTH_WEST) { resId = R.string.weather_NW; } else { resId = R.string.weather_N; } return context.getString(resId); } /** * Returns the resource name associated to the supplied weather condition code * @param context Application context to access resources * @param conditionCode The weather condition code * @return The resource name if a valid condition code is passed, empty string otherwise */ public static String resolveWeatherCondition(Context context, int conditionCode) { final Resources res = context.getResources(); final int resId = res.getIdentifier("weather_" + Utils.addOffsetToConditionCodeFromWeatherContract(conditionCode), "string", context.getPackageName()); if (resId != 0) { return res.getString(resId); } return ""; } private static String getFormattedValue(double value, String unit) { if (Double.isNaN(value)) { return "-"; } String formatted = sNoDigitsFormat.format(value); if (formatted.equals("-0")) { formatted = "0"; } return formatted + unit; } /** * Returns a string with the format xx% (where xx is the humidity value provided) * @param humidity The humidity value * @return The formatted string if a valid value is provided, "-" otherwise. Decimals are * removed */ public static String formatHumidity(double humidity) { return getFormattedValue(humidity, "%"); } /** * Returns a localized string of the speed and speed unit * @param context Application context to access resources * @param windSpeed The wind speed * @param windSpeedUnit The speed unit. See * {@link cyanogenmod.providers.WeatherContract.WeatherColumns.WindSpeedUnit} * @return The formatted string if a valid speed and speed unit a provided. * {@link com.cyanogenmod.lockclock.R.string#unknown} otherwise */ public static String formatWindSpeed(Context context, double windSpeed, int windSpeedUnit) { if (windSpeed < 0) { return context.getString(R.string.unknown); } String localizedSpeedUnit; switch (windSpeedUnit) { case WeatherContract.WeatherColumns.WindSpeedUnit.MPH: localizedSpeedUnit = context.getString(R.string.weather_mph); break; case WeatherContract.WeatherColumns.WindSpeedUnit.KPH: localizedSpeedUnit = context.getString(R.string.weather_kph); break; default: return context.getString(R.string.unknown); } return getFormattedValue(windSpeed, localizedSpeedUnit); } /** * Helper method to convert miles to kilometers * @param miles The value in miles * @return The value in kilometers */ public static double milesToKilometers(double miles) { return miles * 1.609344d; } /** * Helper method to convert kilometers to miles * @param km The value in kilometers * @return The value in miles */ public static double kilometersToMiles(double km) { return km * 0.6214d; } /** * Adds an offset to the condition code reported by the active weather service provider. * @param conditionCode The condition code from the Weather API * @return A condition code that correctly maps to our resource IDs */ public static int addOffsetToConditionCodeFromWeatherContract(int conditionCode) { if (conditionCode <= WeatherContract.WeatherColumns.WeatherCode.SHOWERS) { return conditionCode; } else if (conditionCode <= SCATTERED_THUNDERSTORMS) { return conditionCode + 1; } else if (conditionCode <= SCATTERED_SNOW_SHOWERS) { return conditionCode + 2; } else if (conditionCode <= ISOLATED_THUNDERSHOWERS) { return conditionCode + 3; } else { return NOT_AVAILABLE; } } /** * Checks if the CM Weather service is available in this device * @param context * @return true if service is available, false otherwise */ public static boolean isWeatherServiceAvailable(Context context) { if (!weatherServiceFeatureCached) { weatherServiceAvailable = context.getPackageManager() .hasSystemFeature(CMContextConstants.Features.WEATHER_SERVICES); weatherServiceFeatureCached = true; } return weatherServiceAvailable; } }
15945_5
/* * Copyright (c) 2009-2020 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.scene.shape; import com.jme3.math.Spline; import com.jme3.math.Vector3f; import com.jme3.scene.Mesh; import com.jme3.scene.VertexBuffer; import java.util.Iterator; import java.util.List; /** * A * <code>Curve</code> is a visual, line-based representation of a {@link Spline}. * The underlying Spline will be sampled N times, where N is the number of * segments as specified in the constructor. Each segment will represent one * line in the generated mesh. * * @author Nehon */ public class Curve extends Mesh { private Spline spline; private Vector3f temp = new Vector3f(); /** * Serialization only. Do not use. */ protected Curve() { } /** * Create a curve mesh. Use a CatmullRom spline model that does not cycle. * * @param controlPoints the control points to use to create this curve * @param nbSubSegments the number of subsegments between the control points */ public Curve(Vector3f[] controlPoints, int nbSubSegments) { this(new Spline(Spline.SplineType.CatmullRom, controlPoints, 10, false), nbSubSegments); } /** * Create a curve mesh from a Spline * * @param spline the spline to use * @param nbSubSegments the number of subsegments between the control points */ public Curve(Spline spline, int nbSubSegments) { super(); this.spline = spline; switch (spline.getType()) { case CatmullRom: this.createCatmullRomMesh(nbSubSegments); break; case Bezier: this.createBezierMesh(nbSubSegments); break; case Nurb: this.createNurbMesh(nbSubSegments); break; case Linear: default: this.createLinearMesh(); break; } } private void createCatmullRomMesh(int nbSubSegments) { float[] array = new float[((spline.getControlPoints().size() - 1) * nbSubSegments + 1) * 3]; short[] indices = new short[(spline.getControlPoints().size() - 1) * nbSubSegments * 2]; int i = 0; int cptCP = 0; for (Iterator<Vector3f> it = spline.getControlPoints().iterator(); it.hasNext();) { Vector3f vector3f = it.next(); array[i] = vector3f.x; i++; array[i] = vector3f.y; i++; array[i] = vector3f.z; i++; if (it.hasNext()) { for (int j = 1; j < nbSubSegments; j++) { spline.interpolate((float) j / nbSubSegments, cptCP, temp); array[i] = temp.getX(); i++; array[i] = temp.getY(); i++; array[i] = temp.getZ(); i++; } } cptCP++; } i = 0; int k; for (int j = 0; j < (spline.getControlPoints().size() - 1) * nbSubSegments; j++) { k = j; indices[i] = (short) k; i++; k++; indices[i] = (short) k; i++; } this.setMode(Mesh.Mode.Lines); this.setBuffer(VertexBuffer.Type.Position, 3, array); this.setBuffer(VertexBuffer.Type.Index, 2, indices);//(spline.getControlPoints().size() - 1) * nbSubSegments * 2 this.updateBound(); this.updateCounts(); } /** * This method creates the Bezier path for this curve. * * @param nbSubSegments amount of subsegments between position control * points */ private void createBezierMesh(int nbSubSegments) { if (nbSubSegments == 0) { nbSubSegments = 1; } int centerPointsAmount = (spline.getControlPoints().size() + 2) / 3; //calculating vertices float[] array = new float[((centerPointsAmount - 1) * nbSubSegments + 1) * 3]; int currentControlPoint = 0; List<Vector3f> controlPoints = spline.getControlPoints(); int lineIndex = 0; for (int i = 0; i < centerPointsAmount - 1; ++i) { Vector3f vector3f = controlPoints.get(currentControlPoint); array[lineIndex++] = vector3f.x; array[lineIndex++] = vector3f.y; array[lineIndex++] = vector3f.z; for (int j = 1; j < nbSubSegments; ++j) { spline.interpolate((float) j / nbSubSegments, currentControlPoint, temp); array[lineIndex++] = temp.getX(); array[lineIndex++] = temp.getY(); array[lineIndex++] = temp.getZ(); } currentControlPoint += 3; } Vector3f vector3f = controlPoints.get(currentControlPoint); array[lineIndex++] = vector3f.x; array[lineIndex++] = vector3f.y; array[lineIndex++] = vector3f.z; //calculating indexes int i = 0, k; short[] indices = new short[(centerPointsAmount - 1) * nbSubSegments << 1]; for (int j = 0; j < (centerPointsAmount - 1) * nbSubSegments; ++j) { k = j; indices[i++] = (short) k; ++k; indices[i++] = (short) k; } this.setMode(Mesh.Mode.Lines); this.setBuffer(VertexBuffer.Type.Position, 3, array); this.setBuffer(VertexBuffer.Type.Index, 2, indices); this.updateBound(); this.updateCounts(); } /** * This method creates the Nurb path for this curve. * * @param nbSubSegments amount of subsegments between position control * points */ private void createNurbMesh(int nbSubSegments) { if (spline.getControlPoints() != null && spline.getControlPoints().size() > 0) { if (nbSubSegments == 0) { nbSubSegments = spline.getControlPoints().size() + 1; } else { nbSubSegments = spline.getControlPoints().size() * nbSubSegments + 1; } float minKnot = spline.getMinNurbKnot(); float maxKnot = spline.getMaxNurbKnot(); float deltaU = (maxKnot - minKnot) / nbSubSegments; float[] array = new float[(nbSubSegments + 1) * 3]; float u = minKnot; Vector3f interpolationResult = new Vector3f(); for (int i = 0; i < array.length; i += 3) { spline.interpolate(u, 0, interpolationResult); array[i] = interpolationResult.x; array[i + 1] = interpolationResult.y; array[i + 2] = interpolationResult.z; u += deltaU; } //calculating indexes int i = 0; short[] indices = new short[nbSubSegments << 1]; for (int j = 0; j < nbSubSegments; ++j) { indices[i++] = (short) j; indices[i++] = (short) (j + 1); } this.setMode(Mesh.Mode.Lines); this.setBuffer(VertexBuffer.Type.Position, 3, array); this.setBuffer(VertexBuffer.Type.Index, 2, indices); this.updateBound(); this.updateCounts(); } } private void createLinearMesh() { float[] array = new float[spline.getControlPoints().size() * 3]; short[] indices = new short[(spline.getControlPoints().size() - 1) * 2]; int i = 0; int cpt = 0; int k; int j = 0; for (Iterator<Vector3f> it = spline.getControlPoints().iterator(); it.hasNext();) { Vector3f vector3f = it.next(); array[i] = vector3f.getX(); i++; array[i] = vector3f.getY(); i++; array[i] = vector3f.getZ(); i++; if (it.hasNext()) { k = j; indices[cpt] = (short) k; cpt++; k++; indices[cpt] = (short) k; cpt++; j++; } } this.setMode(Mesh.Mode.Lines); this.setBuffer(VertexBuffer.Type.Position, 3, array); this.setBuffer(VertexBuffer.Type.Index, 2, indices); this.updateBound(); this.updateCounts(); } /** * This method returns the length of the curve. * * @return the length of the curve */ public float getLength() { return spline.getTotalLength(); } }
CyberFlameGO/jmonkeyengine
jme3-core/src/main/java/com/jme3/scene/shape/Curve.java
3,051
//(spline.getControlPoints().size() - 1) * nbSubSegments * 2
line_comment
nl
/* * Copyright (c) 2009-2020 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.scene.shape; import com.jme3.math.Spline; import com.jme3.math.Vector3f; import com.jme3.scene.Mesh; import com.jme3.scene.VertexBuffer; import java.util.Iterator; import java.util.List; /** * A * <code>Curve</code> is a visual, line-based representation of a {@link Spline}. * The underlying Spline will be sampled N times, where N is the number of * segments as specified in the constructor. Each segment will represent one * line in the generated mesh. * * @author Nehon */ public class Curve extends Mesh { private Spline spline; private Vector3f temp = new Vector3f(); /** * Serialization only. Do not use. */ protected Curve() { } /** * Create a curve mesh. Use a CatmullRom spline model that does not cycle. * * @param controlPoints the control points to use to create this curve * @param nbSubSegments the number of subsegments between the control points */ public Curve(Vector3f[] controlPoints, int nbSubSegments) { this(new Spline(Spline.SplineType.CatmullRom, controlPoints, 10, false), nbSubSegments); } /** * Create a curve mesh from a Spline * * @param spline the spline to use * @param nbSubSegments the number of subsegments between the control points */ public Curve(Spline spline, int nbSubSegments) { super(); this.spline = spline; switch (spline.getType()) { case CatmullRom: this.createCatmullRomMesh(nbSubSegments); break; case Bezier: this.createBezierMesh(nbSubSegments); break; case Nurb: this.createNurbMesh(nbSubSegments); break; case Linear: default: this.createLinearMesh(); break; } } private void createCatmullRomMesh(int nbSubSegments) { float[] array = new float[((spline.getControlPoints().size() - 1) * nbSubSegments + 1) * 3]; short[] indices = new short[(spline.getControlPoints().size() - 1) * nbSubSegments * 2]; int i = 0; int cptCP = 0; for (Iterator<Vector3f> it = spline.getControlPoints().iterator(); it.hasNext();) { Vector3f vector3f = it.next(); array[i] = vector3f.x; i++; array[i] = vector3f.y; i++; array[i] = vector3f.z; i++; if (it.hasNext()) { for (int j = 1; j < nbSubSegments; j++) { spline.interpolate((float) j / nbSubSegments, cptCP, temp); array[i] = temp.getX(); i++; array[i] = temp.getY(); i++; array[i] = temp.getZ(); i++; } } cptCP++; } i = 0; int k; for (int j = 0; j < (spline.getControlPoints().size() - 1) * nbSubSegments; j++) { k = j; indices[i] = (short) k; i++; k++; indices[i] = (short) k; i++; } this.setMode(Mesh.Mode.Lines); this.setBuffer(VertexBuffer.Type.Position, 3, array); this.setBuffer(VertexBuffer.Type.Index, 2, indices);//(spline.getControlPoints().size() -<SUF> this.updateBound(); this.updateCounts(); } /** * This method creates the Bezier path for this curve. * * @param nbSubSegments amount of subsegments between position control * points */ private void createBezierMesh(int nbSubSegments) { if (nbSubSegments == 0) { nbSubSegments = 1; } int centerPointsAmount = (spline.getControlPoints().size() + 2) / 3; //calculating vertices float[] array = new float[((centerPointsAmount - 1) * nbSubSegments + 1) * 3]; int currentControlPoint = 0; List<Vector3f> controlPoints = spline.getControlPoints(); int lineIndex = 0; for (int i = 0; i < centerPointsAmount - 1; ++i) { Vector3f vector3f = controlPoints.get(currentControlPoint); array[lineIndex++] = vector3f.x; array[lineIndex++] = vector3f.y; array[lineIndex++] = vector3f.z; for (int j = 1; j < nbSubSegments; ++j) { spline.interpolate((float) j / nbSubSegments, currentControlPoint, temp); array[lineIndex++] = temp.getX(); array[lineIndex++] = temp.getY(); array[lineIndex++] = temp.getZ(); } currentControlPoint += 3; } Vector3f vector3f = controlPoints.get(currentControlPoint); array[lineIndex++] = vector3f.x; array[lineIndex++] = vector3f.y; array[lineIndex++] = vector3f.z; //calculating indexes int i = 0, k; short[] indices = new short[(centerPointsAmount - 1) * nbSubSegments << 1]; for (int j = 0; j < (centerPointsAmount - 1) * nbSubSegments; ++j) { k = j; indices[i++] = (short) k; ++k; indices[i++] = (short) k; } this.setMode(Mesh.Mode.Lines); this.setBuffer(VertexBuffer.Type.Position, 3, array); this.setBuffer(VertexBuffer.Type.Index, 2, indices); this.updateBound(); this.updateCounts(); } /** * This method creates the Nurb path for this curve. * * @param nbSubSegments amount of subsegments between position control * points */ private void createNurbMesh(int nbSubSegments) { if (spline.getControlPoints() != null && spline.getControlPoints().size() > 0) { if (nbSubSegments == 0) { nbSubSegments = spline.getControlPoints().size() + 1; } else { nbSubSegments = spline.getControlPoints().size() * nbSubSegments + 1; } float minKnot = spline.getMinNurbKnot(); float maxKnot = spline.getMaxNurbKnot(); float deltaU = (maxKnot - minKnot) / nbSubSegments; float[] array = new float[(nbSubSegments + 1) * 3]; float u = minKnot; Vector3f interpolationResult = new Vector3f(); for (int i = 0; i < array.length; i += 3) { spline.interpolate(u, 0, interpolationResult); array[i] = interpolationResult.x; array[i + 1] = interpolationResult.y; array[i + 2] = interpolationResult.z; u += deltaU; } //calculating indexes int i = 0; short[] indices = new short[nbSubSegments << 1]; for (int j = 0; j < nbSubSegments; ++j) { indices[i++] = (short) j; indices[i++] = (short) (j + 1); } this.setMode(Mesh.Mode.Lines); this.setBuffer(VertexBuffer.Type.Position, 3, array); this.setBuffer(VertexBuffer.Type.Index, 2, indices); this.updateBound(); this.updateCounts(); } } private void createLinearMesh() { float[] array = new float[spline.getControlPoints().size() * 3]; short[] indices = new short[(spline.getControlPoints().size() - 1) * 2]; int i = 0; int cpt = 0; int k; int j = 0; for (Iterator<Vector3f> it = spline.getControlPoints().iterator(); it.hasNext();) { Vector3f vector3f = it.next(); array[i] = vector3f.getX(); i++; array[i] = vector3f.getY(); i++; array[i] = vector3f.getZ(); i++; if (it.hasNext()) { k = j; indices[cpt] = (short) k; cpt++; k++; indices[cpt] = (short) k; cpt++; j++; } } this.setMode(Mesh.Mode.Lines); this.setBuffer(VertexBuffer.Type.Position, 3, array); this.setBuffer(VertexBuffer.Type.Index, 2, indices); this.updateBound(); this.updateCounts(); } /** * This method returns the length of the curve. * * @return the length of the curve */ public float getLength() { return spline.getTotalLength(); } }
117032_4
import com.cycling74.max.*; import com.cycling74.jitter.*; import java.util.Random; public class JitterGLTest extends MaxObject { JitterObject window; JitterObject render; JitterObject sketch; JitterObject handle; Random r = new Random(); public JitterGLTest(Atom[] args) { declareInlets(new int[]{DataTypes.ALL}); declareOutlets(new int[]{DataTypes.ALL}); // create our window window = new JitterObject("jit.window",new Atom[]{Atom.newAtom("bobby")}); window.setAttr("depthbuffer",1); window.setAttr("fsaa",1); // create our render object for our window render = new JitterObject("jit.gl.render",new Atom[]{Atom.newAtom("bobby")}); render.setAttr("camera",new float[] {0.f,0.f,4.f}); // create our handle handle = new JitterObject("jit.gl.handle",new Atom[]{Atom.newAtom("bobby")}); // create out sketch object sketch = new JitterObject("jit.gl.sketch",new Atom[]{Atom.newAtom("bobby")}); sketch.setAttr("lighting_enable",1); sketch.setAttr("smooth_shading",0); sketch.setAttr("displaylist",1); randomize(); } public void bang() { sketch.setAttr("position",handle.getAttr("position")); sketch.setAttr("rotate",handle.getAttr("rotate")); render.send("erase"); render.send("drawclients"); render.send("swap"); } public void randomize() { // randomize jit.gl.render's erase color render.setAttr("erase_color",new float[]{(float)r.nextGaussian(),(float)r.nextGaussian(),(float)r.nextGaussian(),1.f}); sketch.send("reset"); sketch.send("shapeslice",new int[]{20,20}); for (int i=0;i<10;i++) { sketch.send("glcolor",new float[]{(float)r.nextGaussian(),(float)r.nextGaussian(),(float)r.nextGaussian()}); sketch.send("moveto",new float[]{(float)r.nextGaussian(),(float)r.nextGaussian(),(float)r.nextGaussian()}); sketch.send("torus",new float[]{(float)r.nextGaussian()/10.f,(float)r.nextGaussian()/10.f}); } } public void notifyDeleted() { // free max peers. otherwise these will persist for a while // until the garbage collector feels like cleaning up handle.freePeer(); sketch.freePeer(); render.freePeer(); window.freePeer(); } }
Cycling74/max-mxj
java-classes/classes/JitterGLTest.java
803
// randomize jit.gl.render's erase color
line_comment
nl
import com.cycling74.max.*; import com.cycling74.jitter.*; import java.util.Random; public class JitterGLTest extends MaxObject { JitterObject window; JitterObject render; JitterObject sketch; JitterObject handle; Random r = new Random(); public JitterGLTest(Atom[] args) { declareInlets(new int[]{DataTypes.ALL}); declareOutlets(new int[]{DataTypes.ALL}); // create our window window = new JitterObject("jit.window",new Atom[]{Atom.newAtom("bobby")}); window.setAttr("depthbuffer",1); window.setAttr("fsaa",1); // create our render object for our window render = new JitterObject("jit.gl.render",new Atom[]{Atom.newAtom("bobby")}); render.setAttr("camera",new float[] {0.f,0.f,4.f}); // create our handle handle = new JitterObject("jit.gl.handle",new Atom[]{Atom.newAtom("bobby")}); // create out sketch object sketch = new JitterObject("jit.gl.sketch",new Atom[]{Atom.newAtom("bobby")}); sketch.setAttr("lighting_enable",1); sketch.setAttr("smooth_shading",0); sketch.setAttr("displaylist",1); randomize(); } public void bang() { sketch.setAttr("position",handle.getAttr("position")); sketch.setAttr("rotate",handle.getAttr("rotate")); render.send("erase"); render.send("drawclients"); render.send("swap"); } public void randomize() { // randomize jit.gl.render's<SUF> render.setAttr("erase_color",new float[]{(float)r.nextGaussian(),(float)r.nextGaussian(),(float)r.nextGaussian(),1.f}); sketch.send("reset"); sketch.send("shapeslice",new int[]{20,20}); for (int i=0;i<10;i++) { sketch.send("glcolor",new float[]{(float)r.nextGaussian(),(float)r.nextGaussian(),(float)r.nextGaussian()}); sketch.send("moveto",new float[]{(float)r.nextGaussian(),(float)r.nextGaussian(),(float)r.nextGaussian()}); sketch.send("torus",new float[]{(float)r.nextGaussian()/10.f,(float)r.nextGaussian()/10.f}); } } public void notifyDeleted() { // free max peers. otherwise these will persist for a while // until the garbage collector feels like cleaning up handle.freePeer(); sketch.freePeer(); render.freePeer(); window.freePeer(); } }
44640_7
/** * Create all entity EJBs in the uml model and put them in a hashmap * * @param entityEJBs list with all entity EJBs. * @param simpleModel the uml model. * @return HashMap with all UML Entity classes. */ private HashMap createEntityEJBs(ArrayList entityEJBs, SimpleModel simpleModel) { HashMap map = new HashMap(); for (int i = 0; i < entityEJBs.size(); i++) { Entity e = (Entity) entityEJBs.get(i); String documentation = e.getDescription().toString(); String name = e.getName().toString(); String refName = e.getRefName(); String tableName = e.getTableName(); String displayName = e.getDisplayName().toString(); String entityRootPackage = e.getRootPackage().toString(); simpleModel.addSimpleUmlPackage(entityRootPackage); String isCompositeKey = e.getIsComposite(); String isAssocation = e.getIsAssociationEntity(); // "true" or "false" // Use the refName to put all EntityEJBs in a HashMap. // Add the standard definition for the URLS. SimpleUmlClass umlClass = new SimpleUmlClass(name, SimpleModelElement.PUBLIC); // The e should be a UML Class. // Use the stereoType: simpleModel.setStereoType(JagUMLProfile.STEREOTYPE_CLASS_ENTITY, umlClass); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_DOCUMENTATION, documentation, umlClass); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_CLASS_TABLE_NAME, tableName, umlClass); if (!"".equals(displayName)) { simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_CLASS_DISPLAY_NAME, displayName, umlClass); } if ("true".equals(isCompositeKey)) { simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_CLASS_COMPOSITE_PRIMARY_KEY, e.getPrimaryKeyType().toString(), umlClass); } if ("true".equals(isAssocation)) { simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_CLASS_IS_ASSOCIATION, isAssocation, umlClass); } ArrayList fields = (ArrayList) e.getFields(); for (int j = 0; j < fields.size(); j++) { Field field = (Field) fields.get(j); String fieldType = field.getType(); String fieldName = field.getName().toString(); SimpleUmlClass type = (SimpleUmlClass) typeMappings.get(fieldType); if (type == null) { log("Unknown type: " + type + " for field " + fieldType); type = (SimpleUmlClass) typeMappings.get(this.stringType); } SimpleAttribute theAttribute = new SimpleAttribute(fieldName, SimpleModelElement.PUBLIC, type); umlClass.addSimpleAttribute(theAttribute); String foreignKey = field.getForeignKey().toString(); // "true" or "false" if the current field as a foreign key. if (field.isPrimaryKey()) { simpleModel.setStereoType(JagUMLProfile.STEREOTYPE_ATTRIBUTE_PRIMARY_KEY, theAttribute); } else if (field.isNullable() == false) { simpleModel.setStereoType(JagUMLProfile.STEREOTYPE_ATTRIBUTE_REQUIRED, theAttribute); } if (field.isForeignKey()) { // Niet duidelijk of het plaatsen van 2 stereotypes mogelijk is.... String stereoTypeForeignKey = JagUMLProfile.STEREOTYPE_ATTRIBUTE_FOREIGN_KEY; } String jdbcType = field.getJdbcType().toString(); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_ATTRIBUTE_JDBC_TYPE, jdbcType, theAttribute); String sqlType = field.getSqlType().toString(); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_ATTRIBUTE_SQL_TYPE, sqlType, theAttribute); String columnName = field.getColumnName(); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_ATTRIBUTE_COLUMN_NAME, columnName, theAttribute); boolean autoGeneratedPrimarykey = field.getHasAutoGenPrimaryKey(); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_ATTRIBUTE_AUTO_PRIMARY_KEY, "" + autoGeneratedPrimarykey, theAttribute); } SimpleUmlPackage pk = simpleModel.addSimpleUmlPackage(entityRootPackage); pk.addSimpleClassifier(umlClass); map.put(refName, umlClass); } return map; }
D-a-r-e-k/Code-Smells-Detection
Preparation/processed-dataset/god-class_2_942/4.java
1,294
// Niet duidelijk of het plaatsen van 2 stereotypes mogelijk is....
line_comment
nl
/** * Create all entity EJBs in the uml model and put them in a hashmap * * @param entityEJBs list with all entity EJBs. * @param simpleModel the uml model. * @return HashMap with all UML Entity classes. */ private HashMap createEntityEJBs(ArrayList entityEJBs, SimpleModel simpleModel) { HashMap map = new HashMap(); for (int i = 0; i < entityEJBs.size(); i++) { Entity e = (Entity) entityEJBs.get(i); String documentation = e.getDescription().toString(); String name = e.getName().toString(); String refName = e.getRefName(); String tableName = e.getTableName(); String displayName = e.getDisplayName().toString(); String entityRootPackage = e.getRootPackage().toString(); simpleModel.addSimpleUmlPackage(entityRootPackage); String isCompositeKey = e.getIsComposite(); String isAssocation = e.getIsAssociationEntity(); // "true" or "false" // Use the refName to put all EntityEJBs in a HashMap. // Add the standard definition for the URLS. SimpleUmlClass umlClass = new SimpleUmlClass(name, SimpleModelElement.PUBLIC); // The e should be a UML Class. // Use the stereoType: simpleModel.setStereoType(JagUMLProfile.STEREOTYPE_CLASS_ENTITY, umlClass); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_DOCUMENTATION, documentation, umlClass); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_CLASS_TABLE_NAME, tableName, umlClass); if (!"".equals(displayName)) { simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_CLASS_DISPLAY_NAME, displayName, umlClass); } if ("true".equals(isCompositeKey)) { simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_CLASS_COMPOSITE_PRIMARY_KEY, e.getPrimaryKeyType().toString(), umlClass); } if ("true".equals(isAssocation)) { simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_CLASS_IS_ASSOCIATION, isAssocation, umlClass); } ArrayList fields = (ArrayList) e.getFields(); for (int j = 0; j < fields.size(); j++) { Field field = (Field) fields.get(j); String fieldType = field.getType(); String fieldName = field.getName().toString(); SimpleUmlClass type = (SimpleUmlClass) typeMappings.get(fieldType); if (type == null) { log("Unknown type: " + type + " for field " + fieldType); type = (SimpleUmlClass) typeMappings.get(this.stringType); } SimpleAttribute theAttribute = new SimpleAttribute(fieldName, SimpleModelElement.PUBLIC, type); umlClass.addSimpleAttribute(theAttribute); String foreignKey = field.getForeignKey().toString(); // "true" or "false" if the current field as a foreign key. if (field.isPrimaryKey()) { simpleModel.setStereoType(JagUMLProfile.STEREOTYPE_ATTRIBUTE_PRIMARY_KEY, theAttribute); } else if (field.isNullable() == false) { simpleModel.setStereoType(JagUMLProfile.STEREOTYPE_ATTRIBUTE_REQUIRED, theAttribute); } if (field.isForeignKey()) { // Niet duidelijk<SUF> String stereoTypeForeignKey = JagUMLProfile.STEREOTYPE_ATTRIBUTE_FOREIGN_KEY; } String jdbcType = field.getJdbcType().toString(); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_ATTRIBUTE_JDBC_TYPE, jdbcType, theAttribute); String sqlType = field.getSqlType().toString(); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_ATTRIBUTE_SQL_TYPE, sqlType, theAttribute); String columnName = field.getColumnName(); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_ATTRIBUTE_COLUMN_NAME, columnName, theAttribute); boolean autoGeneratedPrimarykey = field.getHasAutoGenPrimaryKey(); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_ATTRIBUTE_AUTO_PRIMARY_KEY, "" + autoGeneratedPrimarykey, theAttribute); } SimpleUmlPackage pk = simpleModel.addSimpleUmlPackage(entityRootPackage); pk.addSimpleClassifier(umlClass); map.put(refName, umlClass); } return map; }
23598_1
/** * This class contains the main method which allows the project to be run outside of bluej * * @author Dennis Vrieling * @version 0.1 */ /** * Dit is een tekst om te kijken of ik kan pushen. * @author Dennis * */ public class CarparkMain { /** * The starting point for the car park simulation * @param arg Program Arguments */ public static void main(String[] args) { Simulator simulator = new Simulator(); simulator.run(); } }
D0pe69/Project-car-park-simulation
CarparkMain.java
163
/** * Dit is een tekst om te kijken of ik kan pushen. * @author Dennis * */
block_comment
nl
/** * This class contains the main method which allows the project to be run outside of bluej * * @author Dennis Vrieling * @version 0.1 */ /** * Dit is een<SUF>*/ public class CarparkMain { /** * The starting point for the car park simulation * @param arg Program Arguments */ public static void main(String[] args) { Simulator simulator = new Simulator(); simulator.run(); } }
90529_44
package gui; import java.awt.Color; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.Toolkit; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import javax.swing.BorderFactory; import javax.swing.JOptionPane; import javax.swing.JPanel; import common.Datalink; import common.Vars; import engine.*; public class ChessBoard extends JPanel implements MouseListener //, MouseMotionListener { private ChessFrame mother; private ChessBoardField fields[]; // Indeholder 64 Skakfelter private byte markedField; // index p� markeret skakfelt. -1, hvis intet er markeret private Datalink datalink; // Link til modellen private ArrayList<Byte> legalFields; // Felter der kan rykkes til public static final byte NONE = -1; public ChessBoard(Datalink datalink, ChessFrame mother) { loadChessPieces(); this.mother = mother; legalFields = new ArrayList<Byte>(); this.datalink = datalink; fields = new ChessBoardField[64]; markedField = NONE; setPreferredSize(new Dimension(474,474)); setLayout(new GridLayout(8,8)); setBorder(BorderFactory.createLineBorder(Color.black, 1)); for (byte i = 0 ; i < 64 ; i++) { ChessBoardField tempPanel = new ChessBoardField(i, this); tempPanel.setContent(datalink.getBoardData().getBoard()[small2big(i)]); // Baggrundsfarve if (i % 2 - ((i / 8)+1) % 2 == 0) tempPanel.setBackground(Color.white); else tempPanel.setBackground(Color.getHSBColor((float)0.2, (float)0.2, (float)0.4)); fields[i] = tempPanel; tempPanel.addMouseListener(this); //tempPanel.addMouseMotionListener(this); } for(int i = 7; i >= 0; i--) for(int j = 0; j < 8; j++) add(fields[(i*8)+j]); } private void loadChessPieces() { Vars.picBPawn = Toolkit.getDefaultToolkit().getImage("gui/graphics/bPawn.png"); } /** * Synkroniserer GUI'en br�t med br�ttet i skakmotoren * */ public void reloadBoard() { clearLegalFields(); for(byte i = 0 ; i < fields.length ; i++) fields[i].setContent(datalink.getBoardData().getBoard()[small2big(i)]); } public byte small2big(byte index) { return (byte) ((21 + index) + (index/8)*3-(index/8)); } public byte big2small(byte index) { return (byte) ((index-21)-((index-21)/10)*2); } /** * Viser lovlige tr�k for en brik i et bestemt skakfelt. Selve beregningen af legalmoves foretages i motoren. * @param pos Index p� det felt der �nskes lovlige tr�k for */ public void showLegalMoves(byte pos) { if((markedField == pos || markedField == NONE) && fields[pos].getContent() != 0) { repaintFields(legalFields); legalFields.clear(); byte legalmoves[] = datalink.getBoardData().getLegalMoves(datalink.getBoardData().getPieceAtPos(small2big(pos))); for(byte move : legalmoves) legalFields.add(big2small(move)); repaintFields(legalmoves); } } /** * Ofte er det kun nogle f� felter der skal repaintes * @param fieldsToRepaint Liste over de felter der skal repaintes */ private void repaintFields(ArrayList<Byte> fieldsToRepaint) { for (Byte CBF : fieldsToRepaint) fields[CBF].repaint(); } /** * Ofte er det kun nogle f� felter der skal repaintes * @param fieldsToRepaint Liste over de felter der skal repaintes */ private void repaintFields(byte[] fieldsToRepaint) { for (byte pos : fieldsToRepaint) fields[big2small(pos)].repaint(); } /** * Repainter hele br�ttet, ved at repainte hvert felt * */ public void repaintBoard() { paintImmediately(0, 0, getWidth(), getHeight()); for(ChessBoardField CBF : fields) CBF.paintImmediately(0, 0, CBF.getWidth(), CBF.getHeight()); paintImmediately(0, 0, getWidth(), getHeight()); } /** * Felter som kan rykkes til slettes og repaintes, * s� de ikke l�ngere indeholder en gr�n ring. */ public void clearLegalFields() { ArrayList<Byte> copy = new ArrayList<Byte>(); copy.addAll(legalFields); legalFields.clear(); for(byte field : copy) fields[field].paintImmediately(0, 0, fields[field].getWidth(), fields[field].getHeight()); } /********************** * GETTERS & SETTERS **********************/ public ChessBoardField[] getFields() { return fields; } public void setFields(ChessBoardField[] fields) { this.fields = fields; } public byte getMarkedField() { return markedField; } public void setMarkedField(byte markedField) { this.markedField = markedField; } public ArrayList<Byte> getLegalFields() { return legalFields; } public Datalink getDatalink() { return datalink; } /********************** * LISTENERS **********************/ /** * MouseListener - Lytter efter museklik */ public void mouseClicked(MouseEvent arg0) { if (arg0.getSource().getClass().getSimpleName().equals("ChessBoardField")) { ChessBoardField CBF = (ChessBoardField) arg0.getSource(); // Denne lille man�vre er n�dvendig, da Datalink.currentPlayer skifter frem og tilbage n�r AI t�nker int currentPlayer = Vars.WHITE; if (mother.getLblCurrentPlayer().getText().toString().equals("Sort trækker")) currentPlayer = Vars.BLACK; // Klikket er lovligt hvis: // 1. Der er tale om sort brik eller et lovligt felt (gr�n ring). Derudover skal det v�re sorts tur // 2. Der er tale om hvid brik eller et lovligt felt (gr�n ring). Derudover skal det v�re hvids tur // 3. Sammen med 1. og 2. skal det ved "Human vs. AI" spil v�re Humans tur eller ogs� skal det v�re to player spil // 4. Spillet m� ikke v�re slut! if ((((CBF.getContent() <= 0 || legalFields.contains(CBF.getPos())) && Datalink.currentPlayer == Vars.BLACK) || ((CBF.getContent() >= 0 || legalFields.contains(CBF.getPos())) && Datalink.currentPlayer == Vars.WHITE)) && ((currentPlayer != Datalink.aiColor && !Datalink.twoPlayerGame) || (Datalink.twoPlayerGame)) && Datalink.gameEnded == false) { // Hvis feltet der er trykket p� ikke er det felt der er markeret og // det felt man klikker p� indeholder en brik (Alts� flyt markering!) if (markedField != CBF.getPos() && CBF.getContent() != 0 && !legalFields.contains(CBF.getPos())) { byte index = markedField; markedField = CBF.getPos(); CBF.repaint(); if(index != -1) fields[index].repaint(); showLegalMoves(CBF.getPos()); } // Hvis det felt man klikker p� allerede er markeret (Fjern markering!) else if (markedField == CBF.getPos()) { markedField = NONE; CBF.repaint(); clearLegalFields(); } // Hvis det felt man klikker p� et felt der kan rykkes til (Alts� flyt brik!) else if (legalFields.contains(CBF.getPos())) { Piece pieceToMove = datalink.getBoardData().getPieceAtPos(small2big((byte)markedField)); // Tjek om "Pawn promotion" if ((pieceToMove.getType() == Piece.BPAWN && pieceToMove.getRank() == 2 && Datalink.currentPlayer == Vars.BLACK) || (pieceToMove.getType() == Piece.WPAWN && pieceToMove.getRank() == 7 && Datalink.currentPlayer == Vars.WHITE)) { Promotion pro = new Promotion(mother); pro.pack(); pro.setVisible(true); } //Slet brik fra gammel felt i gui fields[markedField].setContent((byte)0); markedField = NONE; // Flyt brik i model byte toPosition = small2big(CBF.getPos()); datalink.move(pieceToMove, toPosition); //Flyt brik til nyt felt i gui movePieceInGUI(toPosition); // if (datalink.getBoardData().canUseFiftyMoveRule() && datalink.twoPlayerGame) // { // String color; // if (datalink.currentPlayer == Vars.WHITE) // color = "hvid"; // else // color = "sort"; // // Object[] options = {"Ja", "Nej"}; // int n = JOptionPane.showOptionDialog(mother, // "Vil " + color + " benytte sig af 50-ryks-regelen? \n Det betyder at spille ender i remi", // "50-ryks-regel", // JOptionPane.YES_NO_OPTION, // JOptionPane.QUESTION_MESSAGE, // null, // options, // options[1]); // // if (n == 0) // datalink.getBoardData().useFiftyMoveRule(); // } datalink.play(); // n�ste spiller } } else if (Datalink.gameEnded) { Object[] options = {"Ja", "Nej"}; int n = JOptionPane.showOptionDialog(mother, "Vil du starte et nyt spil?", Vars.APPTITLE, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (n == 0) datalink.newAIgame(); } } } public void movePieceInGUI(int toPosition) { fields[big2small((byte)toPosition)].setContent(datalink.getBoardData().getBoard()[toPosition]); } // Disse bruges ikke, men skal v�re der! public void mouseEntered(MouseEvent arg0) {} public void mouseExited(MouseEvent arg0) {} public void mousePressed(MouseEvent arg0) {} public void mouseReleased(MouseEvent arg0) {} /** * MouseMotionListener - Lytter efter om musen flytter sig */ // public void mouseDragged(MouseEvent arg0) {} // // public void mouseMoved(MouseEvent arg0) { // ChessBoardField CBF = (ChessBoardField) arg0.getSource(); // //System.out.println(CBF.getContent()); // //System.out.println(chessboard.getDatalink().getBoardData().getBoard()[chessboard.small2big(CBF.getPos())]); // // if(markedField == NONE && Vars.ctrlPressed && // (((CBF.getContent() < 0 && Datalink.currentPlayer == Vars.BLACK) || // (CBF.getContent() > 0 && Datalink.currentPlayer == Vars.WHITE)) || Vars.debugMode)) // showLegalMoves(CBF.getPos()); // //// if(markedField == NONE && Vars.ctrlPressed) //// showMoves(CBF.getPos()); // // if (CBF.getContent() == 0 && markedField == NONE) // clearLegalFields(); // } }
DAMNinc/damnchess
src/main/java/gui/ChessBoard.java
3,809
// if (CBF.getContent() == 0 && markedField == NONE)
line_comment
nl
package gui; import java.awt.Color; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.Toolkit; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import javax.swing.BorderFactory; import javax.swing.JOptionPane; import javax.swing.JPanel; import common.Datalink; import common.Vars; import engine.*; public class ChessBoard extends JPanel implements MouseListener //, MouseMotionListener { private ChessFrame mother; private ChessBoardField fields[]; // Indeholder 64 Skakfelter private byte markedField; // index p� markeret skakfelt. -1, hvis intet er markeret private Datalink datalink; // Link til modellen private ArrayList<Byte> legalFields; // Felter der kan rykkes til public static final byte NONE = -1; public ChessBoard(Datalink datalink, ChessFrame mother) { loadChessPieces(); this.mother = mother; legalFields = new ArrayList<Byte>(); this.datalink = datalink; fields = new ChessBoardField[64]; markedField = NONE; setPreferredSize(new Dimension(474,474)); setLayout(new GridLayout(8,8)); setBorder(BorderFactory.createLineBorder(Color.black, 1)); for (byte i = 0 ; i < 64 ; i++) { ChessBoardField tempPanel = new ChessBoardField(i, this); tempPanel.setContent(datalink.getBoardData().getBoard()[small2big(i)]); // Baggrundsfarve if (i % 2 - ((i / 8)+1) % 2 == 0) tempPanel.setBackground(Color.white); else tempPanel.setBackground(Color.getHSBColor((float)0.2, (float)0.2, (float)0.4)); fields[i] = tempPanel; tempPanel.addMouseListener(this); //tempPanel.addMouseMotionListener(this); } for(int i = 7; i >= 0; i--) for(int j = 0; j < 8; j++) add(fields[(i*8)+j]); } private void loadChessPieces() { Vars.picBPawn = Toolkit.getDefaultToolkit().getImage("gui/graphics/bPawn.png"); } /** * Synkroniserer GUI'en br�t med br�ttet i skakmotoren * */ public void reloadBoard() { clearLegalFields(); for(byte i = 0 ; i < fields.length ; i++) fields[i].setContent(datalink.getBoardData().getBoard()[small2big(i)]); } public byte small2big(byte index) { return (byte) ((21 + index) + (index/8)*3-(index/8)); } public byte big2small(byte index) { return (byte) ((index-21)-((index-21)/10)*2); } /** * Viser lovlige tr�k for en brik i et bestemt skakfelt. Selve beregningen af legalmoves foretages i motoren. * @param pos Index p� det felt der �nskes lovlige tr�k for */ public void showLegalMoves(byte pos) { if((markedField == pos || markedField == NONE) && fields[pos].getContent() != 0) { repaintFields(legalFields); legalFields.clear(); byte legalmoves[] = datalink.getBoardData().getLegalMoves(datalink.getBoardData().getPieceAtPos(small2big(pos))); for(byte move : legalmoves) legalFields.add(big2small(move)); repaintFields(legalmoves); } } /** * Ofte er det kun nogle f� felter der skal repaintes * @param fieldsToRepaint Liste over de felter der skal repaintes */ private void repaintFields(ArrayList<Byte> fieldsToRepaint) { for (Byte CBF : fieldsToRepaint) fields[CBF].repaint(); } /** * Ofte er det kun nogle f� felter der skal repaintes * @param fieldsToRepaint Liste over de felter der skal repaintes */ private void repaintFields(byte[] fieldsToRepaint) { for (byte pos : fieldsToRepaint) fields[big2small(pos)].repaint(); } /** * Repainter hele br�ttet, ved at repainte hvert felt * */ public void repaintBoard() { paintImmediately(0, 0, getWidth(), getHeight()); for(ChessBoardField CBF : fields) CBF.paintImmediately(0, 0, CBF.getWidth(), CBF.getHeight()); paintImmediately(0, 0, getWidth(), getHeight()); } /** * Felter som kan rykkes til slettes og repaintes, * s� de ikke l�ngere indeholder en gr�n ring. */ public void clearLegalFields() { ArrayList<Byte> copy = new ArrayList<Byte>(); copy.addAll(legalFields); legalFields.clear(); for(byte field : copy) fields[field].paintImmediately(0, 0, fields[field].getWidth(), fields[field].getHeight()); } /********************** * GETTERS & SETTERS **********************/ public ChessBoardField[] getFields() { return fields; } public void setFields(ChessBoardField[] fields) { this.fields = fields; } public byte getMarkedField() { return markedField; } public void setMarkedField(byte markedField) { this.markedField = markedField; } public ArrayList<Byte> getLegalFields() { return legalFields; } public Datalink getDatalink() { return datalink; } /********************** * LISTENERS **********************/ /** * MouseListener - Lytter efter museklik */ public void mouseClicked(MouseEvent arg0) { if (arg0.getSource().getClass().getSimpleName().equals("ChessBoardField")) { ChessBoardField CBF = (ChessBoardField) arg0.getSource(); // Denne lille man�vre er n�dvendig, da Datalink.currentPlayer skifter frem og tilbage n�r AI t�nker int currentPlayer = Vars.WHITE; if (mother.getLblCurrentPlayer().getText().toString().equals("Sort trækker")) currentPlayer = Vars.BLACK; // Klikket er lovligt hvis: // 1. Der er tale om sort brik eller et lovligt felt (gr�n ring). Derudover skal det v�re sorts tur // 2. Der er tale om hvid brik eller et lovligt felt (gr�n ring). Derudover skal det v�re hvids tur // 3. Sammen med 1. og 2. skal det ved "Human vs. AI" spil v�re Humans tur eller ogs� skal det v�re to player spil // 4. Spillet m� ikke v�re slut! if ((((CBF.getContent() <= 0 || legalFields.contains(CBF.getPos())) && Datalink.currentPlayer == Vars.BLACK) || ((CBF.getContent() >= 0 || legalFields.contains(CBF.getPos())) && Datalink.currentPlayer == Vars.WHITE)) && ((currentPlayer != Datalink.aiColor && !Datalink.twoPlayerGame) || (Datalink.twoPlayerGame)) && Datalink.gameEnded == false) { // Hvis feltet der er trykket p� ikke er det felt der er markeret og // det felt man klikker p� indeholder en brik (Alts� flyt markering!) if (markedField != CBF.getPos() && CBF.getContent() != 0 && !legalFields.contains(CBF.getPos())) { byte index = markedField; markedField = CBF.getPos(); CBF.repaint(); if(index != -1) fields[index].repaint(); showLegalMoves(CBF.getPos()); } // Hvis det felt man klikker p� allerede er markeret (Fjern markering!) else if (markedField == CBF.getPos()) { markedField = NONE; CBF.repaint(); clearLegalFields(); } // Hvis det felt man klikker p� et felt der kan rykkes til (Alts� flyt brik!) else if (legalFields.contains(CBF.getPos())) { Piece pieceToMove = datalink.getBoardData().getPieceAtPos(small2big((byte)markedField)); // Tjek om "Pawn promotion" if ((pieceToMove.getType() == Piece.BPAWN && pieceToMove.getRank() == 2 && Datalink.currentPlayer == Vars.BLACK) || (pieceToMove.getType() == Piece.WPAWN && pieceToMove.getRank() == 7 && Datalink.currentPlayer == Vars.WHITE)) { Promotion pro = new Promotion(mother); pro.pack(); pro.setVisible(true); } //Slet brik fra gammel felt i gui fields[markedField].setContent((byte)0); markedField = NONE; // Flyt brik i model byte toPosition = small2big(CBF.getPos()); datalink.move(pieceToMove, toPosition); //Flyt brik til nyt felt i gui movePieceInGUI(toPosition); // if (datalink.getBoardData().canUseFiftyMoveRule() && datalink.twoPlayerGame) // { // String color; // if (datalink.currentPlayer == Vars.WHITE) // color = "hvid"; // else // color = "sort"; // // Object[] options = {"Ja", "Nej"}; // int n = JOptionPane.showOptionDialog(mother, // "Vil " + color + " benytte sig af 50-ryks-regelen? \n Det betyder at spille ender i remi", // "50-ryks-regel", // JOptionPane.YES_NO_OPTION, // JOptionPane.QUESTION_MESSAGE, // null, // options, // options[1]); // // if (n == 0) // datalink.getBoardData().useFiftyMoveRule(); // } datalink.play(); // n�ste spiller } } else if (Datalink.gameEnded) { Object[] options = {"Ja", "Nej"}; int n = JOptionPane.showOptionDialog(mother, "Vil du starte et nyt spil?", Vars.APPTITLE, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (n == 0) datalink.newAIgame(); } } } public void movePieceInGUI(int toPosition) { fields[big2small((byte)toPosition)].setContent(datalink.getBoardData().getBoard()[toPosition]); } // Disse bruges ikke, men skal v�re der! public void mouseEntered(MouseEvent arg0) {} public void mouseExited(MouseEvent arg0) {} public void mousePressed(MouseEvent arg0) {} public void mouseReleased(MouseEvent arg0) {} /** * MouseMotionListener - Lytter efter om musen flytter sig */ // public void mouseDragged(MouseEvent arg0) {} // // public void mouseMoved(MouseEvent arg0) { // ChessBoardField CBF = (ChessBoardField) arg0.getSource(); // //System.out.println(CBF.getContent()); // //System.out.println(chessboard.getDatalink().getBoardData().getBoard()[chessboard.small2big(CBF.getPos())]); // // if(markedField == NONE && Vars.ctrlPressed && // (((CBF.getContent() < 0 && Datalink.currentPlayer == Vars.BLACK) || // (CBF.getContent() > 0 && Datalink.currentPlayer == Vars.WHITE)) || Vars.debugMode)) // showLegalMoves(CBF.getPos()); // //// if(markedField == NONE && Vars.ctrlPressed) //// showMoves(CBF.getPos()); // // if (CBF.getContent()<SUF> // clearLegalFields(); // } }
196115_23
/* * Copyright (c), 2009 Carnegie Mellon University. * All rights reserved. * * Use in source and binary forms, with or without modifications, are permitted * provided that that following conditions are met: * * 1. Source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Permission to redistribute source and binary forms, with or without * modifications, for any purpose must be obtained from the authors. * Contact Rohit Kumar ([email protected]) for such permission. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package basilica2.agents.data; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.time.LocalDateTime; import basilica2.agents.events.PoseEvent.poseEventType; import java.util.Collections; /** * * @author rohitk */ public class State { public class Student { public String chatId; public String name; public String role = null; public Set previousRoles = new HashSet(); public int activityMetric = 0; public boolean isPresent; public String speech; public String identity; public String location = null; public String facialExp; public poseEventType pose; public String emotion; @Override public String toString() { return ("<student id=\"" + chatId + "\" name=\"" + name + "\" role=\"" + role + "\" present=\"" + isPresent + "\" />"); } } private List<Student> students = new ArrayList<Student>(); private List<String> roles = new ArrayList<String>(); private ArrayList<Student> randomizedStudentList = new ArrayList<Student>(); private int nextStudentIndex; private boolean initiated = false; private String stageName = null; private String stageType = null; private String stepName = null; private String stepType = null; private poseEventType groupPose = poseEventType.none; private String identityAllUsers = "group"; private int jointActivityMetric = 0; private Boolean multimodalDontListenWhileSpeaking = true; private LocalDateTime multimodalDontListenEnd = null; // public String conceptId; // public String conceptExecutionStatus; private Map<String, Object> stateMap = new HashMap<String, Object>(); public static State copy(State s) { // System.err.println("State.java, copy -- COPYING STATE"); State news = new State(); news.initiated = s.initiated; news.stageName = s.stageName; news.stageType = s.stageType; news.stepName = s.stepName; news.stepType = s.stepType; news.groupPose = s.groupPose; news.multimodalDontListenWhileSpeaking = s.multimodalDontListenWhileSpeaking; news.multimodalDontListenEnd = s.multimodalDontListenEnd; Map<String, Object> map = s.more(); for (String k : map.keySet()) news.stateMap.put(k, map.get(k)); // news.conceptId = s.conceptExecutionStatus; // news.conceptExecutionStatus = s.conceptExecutionStatus; for (int i = 0; i < s.students.size(); i++) { news.students.add(s.students.get(i)); } for (int i = 0; i < s.randomizedStudentList.size(); i++) { news.randomizedStudentList.add(s.randomizedStudentList.get(i)); } for (int i = 0; i < s.roles.size(); i++) { news.roles.add(s.roles.get(i)); } return news; } public Map<String, Object> more() { return stateMap; } public void initiate() { initiated = true; } public void setStepInfo(String stageName, String stageType, String stepName, String type) { this.stageName = stageName; this.stageType = stageType; this.stepName = stepName; this.stepType = type; } public void addStudent(String sid) { // System.err.println("===== State,addStudent - sid: " + sid); if (!sid.contentEquals(identityAllUsers)) { Student s = new Student(); boolean found = false; for (int i = 0; i < students.size(); i++) { if (sid.startsWith(students.get(i).chatId)) { found = true; s = students.get(i); } } if (!found) { s.chatId = sid; s.name = sid; s.role = "UNASSIGNED"; students.add(s); } s.isPresent = true; } } public void removeStudent(String sid) { for (int i = 0; i < students.size(); i++) { Student s = students.get(i); if (s.chatId.equalsIgnoreCase(sid)) { s.isPresent = false; } } } public String getStudentName(String sid) { for (int i = 0; i < students.size(); i++) { Student s = students.get(i); // if (s.isPresent) // No need to check if student is present to return name if (true) { if (s.chatId.equalsIgnoreCase(sid)) { return s.name; } } } return sid; } public void setName(String sid, String name) { // System.err.println("===== State,setName - sid: " + sid + " -- name: " + name); if (!sid.equals(identityAllUsers)) { for (int i = 0; i < students.size(); i++) { if (sid.startsWith(students.get(i).chatId)) { students.get(i).name = name; return; } } addStudent(sid); setName(sid, name); } } public void setStudentPose(String sid, poseEventType pose) { for (int i = 0; i < students.size(); i++) { if (sid.startsWith(students.get(i).chatId)) { students.get(i).pose = pose; return; } } } public poseEventType getStudentPose(String sid) { for (int i = 0; i < students.size(); i++) { Student s = students.get(i); if (s.chatId.equalsIgnoreCase(sid)) { // System.out.println("State.java, getPose - sid/chatId: " + sid + " - pose: " + s.pose.toString()); return s.pose; } } return null; } public String getLocation(String sid) { for (int i = 0; i < students.size(); i++) { Student s = students.get(i); if (s.chatId.equalsIgnoreCase(sid)) { // System.out.println("State.java, getLocation - sid/chatId: " + sid + " - Location: " + s.location); return s.location; } } return null; } public void setLocation(String sid, String location) { for (int i = 0; i < students.size(); i++) { if (sid.startsWith(students.get(i).chatId)) { students.get(i).location = location; // System.out.println("State.java, setLocation - sid/chatId: " + sid + " - Location: " + location); } } } public void addRole(String role) { // System.out.println("===== State,addRole: " + role); roles.add(role); } public void setRoles(String[] roles) { for (int i = 0; i < roles.length; i++) { addRole(roles[i]); // System.out.println("State, setRoles: Added role " + roles[i]); } } public int getNumRoles() { return roles.size(); } public void setStudentRole(String sid, String role) { for (int i = 0; i < students.size(); i++) { if (sid.startsWith(students.get(i).chatId)) { students.get(i).role = role; students.get(i).previousRoles.add(role); } } } public String getStudentRole(String sid) { for (int i = 0; i < students.size(); i++) { if (sid.startsWith(students.get(i).chatId)) { return students.get(i).role; } } return sid; } public Set getStudentPreviousRoles(String sid) { for (int i = 0; i < students.size(); i++) { if (sid.startsWith(students.get(i).chatId)) { return students.get(i).previousRoles; } } return Collections.emptySet(); } public String getRolesString() { String roleString = ""; for (String role : roles) { roleString += role + ", "; } if(roleString.length() > 2) roleString = roleString.substring(0, roleString.length() - 2); return roleString; } public int getStudentCount() { int c = 0; for (int i = 0; i < students.size(); i++) { if (students.get(i).isPresent) { c++; } } return c; } public String[] getStudentIds() { List<String> ids = new ArrayList<String>(); for (int i = 0; i < students.size(); i++) { if (students.get(i).isPresent) { ids.add(students.get(i).chatId); } } return ids.toArray(new String[0]); } public String[] getStudentIdsPresentOrNot() { List<String> ids = new ArrayList<String>(); for (int i = 0; i < students.size(); i++) { // if (students.get(i).isPresent) if (true) { ids.add(students.get(i).chatId); } } return ids.toArray(new String[0]); } public List<String> getStudentIdList() { List<String> ids = new ArrayList<String>(); for (int i = 0; i < students.size(); i++) { if (students.get(i).isPresent) { ids.add(students.get(i).chatId); } } return ids; } public String[] getRandomizedStudentIds() { setRandomizedStudentList(); String[] ids = new String[this.randomizedStudentList.size()]; // System.err.println("getRandomizedStudentIds(), this.randomizedStudentList.size() = " + String.valueOf(randomizedStudentList.size())); for (int i = 0; i < this.randomizedStudentList.size(); i++) { // System.err.println("getRandomizedStudentIds(), adding id " + this.randomizedStudentList.get(i).chatId); // System.err.println("getRandomizedStudentIds(), adding id for name " + this.randomizedStudentList.get(i).name); ids[i] = (this.randomizedStudentList.get(i).chatId); // if (students.get(i).isPresent) // { // ids[i] = (randomizedStudentList.get(i).chatId); // } } // System.err.println("getRandomizedStudentIds, returning ids = " Array.toString(ids)); // for (int i = 0; i < ids.length; i++) { // System.err.println("getRandomizedStudentIds(), ids[" + String.valueOf(i) + "] = " + ids[i]); // } return ids; } public void setRandomizedStudentList() { // System.err.println("Student names: " + Arrays.toString(getStudentNames().toArray())); this.randomizedStudentList.clear(); for (int i = 0; i < students.size(); i++) { // this.randomizedStudentList.add(students.get(i)); if (students.get(i).isPresent) { this.randomizedStudentList.add(students.get(i)); } else { // System.err.println("State, setRandomizedStudentList: student not present - chatId:" + students.get(i).chatId + " - name:" + students.get(i).name); } } Collections.shuffle(this.randomizedStudentList); setNextStudentIndex(0); // System.err.println("Randomized student names: " + Arrays.toString(getRandomizedStudentNames().toArray())); } public List<String> getStudentNames() { List<String> names = new ArrayList<String>(); for (int i = 0; i < students.size(); i++) { if (students.get(i).isPresent) { names.add(students.get(i).name); } } return names; } public List<String> getRandomizedStudentNames() { List<String> names = new ArrayList<String>(); for (int i = 0; i < randomizedStudentList.size(); i++) { if (randomizedStudentList.get(i).isPresent) { names.add(randomizedStudentList.get(i).name); } } return names; } public List<String> getAllStudentNames() { List<String> ids = new ArrayList<String>(); for (int i = 0; i < students.size(); i++) { ids.add(students.get(i).name); } return ids; } public String[] getStudentNamesByIds(String[] ids) { List<String> names = new ArrayList<String>(); for (int i = 0; i < ids.length; i++) { names.add(getStudentName(ids[i])); } return names.toArray(new String[0]); } public List<String> getStudentNamesByIdList(List<String> ids) { List<String> names = new ArrayList<String>(); for (int i = 0; i < ids.size(); i++) { names.add(getStudentName(ids.get(i))); } return names; } public String getStudentNamesString() { return getStudentNamesString(Arrays.asList(this.getStudentIds())); } public String getStudentNamesString(List<String> users) { String name = ""; for (String id : users) { name += this.getStudentName(id) + ", "; } if(name.length() > 2) name = name.substring(0, name.length() - 2); return name; } public void setNextStudentIndex(int index) { this.nextStudentIndex = index; } public int getNextStudentIndex() { return this.nextStudentIndex; } public int advanceStudentIndex() { int nextIndex = this.nextStudentIndex + 1; // System.err.println("State.java, advanceStudentIndex: initial nextIndex = " + String.valueOf(nextIndex)); if (nextIndex == students.size()) { nextIndex = 0; } setNextStudentIndex(nextIndex); // System.err.println("State.java, advanceStudentIndex: final nextIndex = " + String.valueOf(nextIndex)); return nextIndex; } public Student getStudentById(String sid) { for (int i = 0; i < students.size(); i++) { Student s = students.get(i); if (s.isPresent) { if (s.chatId.equalsIgnoreCase(sid)) { return s; } } } return null; } public String getStudentByRole(String role) { for (int i = 0; i < students.size(); i++) { Student s = students.get(i); if (s.isPresent) { if (s.role.equalsIgnoreCase(role)) { return s.chatId; } } } return null; } public void setStudentActivityMetric(String sid, int metric) { for (int i = 0; i < students.size(); i++) { if (sid.startsWith(students.get(i).chatId)) { students.get(i).activityMetric = metric; } } } public int getStudentActivityMetric(String sid) { for (int i = 0; i < students.size(); i++) { if (sid.startsWith(students.get(i).chatId)) { return students.get(i).activityMetric; } } return 0; } public void setJointActivityMetric(int metric) { jointActivityMetric = metric; } public int getJointActivityMetric() { return jointActivityMetric; } public String getStageName() { if (stageName == null) { return ""; } return stageName; } public String getStageType() { if (stageType == null) { return ""; } return stageType; } public String getStepName() { if (stepName == null) { return ""; } return stepName; } public poseEventType getGroupPose() { return groupPose; } public void setGroupPose(poseEventType pose) { this.groupPose = pose; } public void setMultimodalDontListenWhileSpeaking(Boolean dontListenWhileSpeaking) { this.multimodalDontListenWhileSpeaking = dontListenWhileSpeaking; } public Boolean getMultimodalDontListenWhileSpeaking() { return multimodalDontListenWhileSpeaking; } public LocalDateTime getMultimodalDontListenWhileSpeakingEnd() { return multimodalDontListenEnd; } public void setMultimodalDontListenWhileSpeakingEnd(LocalDateTime dontListenEnd) { this.multimodalDontListenEnd = dontListenEnd; } @Override public String toString() { String ret = "<State students=\"" + students.size() + "\" initiated=\"" + initiated + "\">\n"; ret += "\t<Stage name=\"" + stageName + "\" type=\"" + stageType + "\" />\n"; ret += "\t<Step name=\"" + stepName + "\" type=\"" + stepType + "\"/>\n"; for (int i = 0; i < students.size(); i++) { ret += ("\t" + students.get(i).toString()); } ret += "</State>"; return ret; } }
DANCEcollaborative/bazaar
BaseAgent/src/basilica2/agents/data/State.java
5,827
// System.err.println("State, setRandomizedStudentList: student not present - chatId:" + students.get(i).chatId + " - name:" + students.get(i).name);
line_comment
nl
/* * Copyright (c), 2009 Carnegie Mellon University. * All rights reserved. * * Use in source and binary forms, with or without modifications, are permitted * provided that that following conditions are met: * * 1. Source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Permission to redistribute source and binary forms, with or without * modifications, for any purpose must be obtained from the authors. * Contact Rohit Kumar ([email protected]) for such permission. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package basilica2.agents.data; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.time.LocalDateTime; import basilica2.agents.events.PoseEvent.poseEventType; import java.util.Collections; /** * * @author rohitk */ public class State { public class Student { public String chatId; public String name; public String role = null; public Set previousRoles = new HashSet(); public int activityMetric = 0; public boolean isPresent; public String speech; public String identity; public String location = null; public String facialExp; public poseEventType pose; public String emotion; @Override public String toString() { return ("<student id=\"" + chatId + "\" name=\"" + name + "\" role=\"" + role + "\" present=\"" + isPresent + "\" />"); } } private List<Student> students = new ArrayList<Student>(); private List<String> roles = new ArrayList<String>(); private ArrayList<Student> randomizedStudentList = new ArrayList<Student>(); private int nextStudentIndex; private boolean initiated = false; private String stageName = null; private String stageType = null; private String stepName = null; private String stepType = null; private poseEventType groupPose = poseEventType.none; private String identityAllUsers = "group"; private int jointActivityMetric = 0; private Boolean multimodalDontListenWhileSpeaking = true; private LocalDateTime multimodalDontListenEnd = null; // public String conceptId; // public String conceptExecutionStatus; private Map<String, Object> stateMap = new HashMap<String, Object>(); public static State copy(State s) { // System.err.println("State.java, copy -- COPYING STATE"); State news = new State(); news.initiated = s.initiated; news.stageName = s.stageName; news.stageType = s.stageType; news.stepName = s.stepName; news.stepType = s.stepType; news.groupPose = s.groupPose; news.multimodalDontListenWhileSpeaking = s.multimodalDontListenWhileSpeaking; news.multimodalDontListenEnd = s.multimodalDontListenEnd; Map<String, Object> map = s.more(); for (String k : map.keySet()) news.stateMap.put(k, map.get(k)); // news.conceptId = s.conceptExecutionStatus; // news.conceptExecutionStatus = s.conceptExecutionStatus; for (int i = 0; i < s.students.size(); i++) { news.students.add(s.students.get(i)); } for (int i = 0; i < s.randomizedStudentList.size(); i++) { news.randomizedStudentList.add(s.randomizedStudentList.get(i)); } for (int i = 0; i < s.roles.size(); i++) { news.roles.add(s.roles.get(i)); } return news; } public Map<String, Object> more() { return stateMap; } public void initiate() { initiated = true; } public void setStepInfo(String stageName, String stageType, String stepName, String type) { this.stageName = stageName; this.stageType = stageType; this.stepName = stepName; this.stepType = type; } public void addStudent(String sid) { // System.err.println("===== State,addStudent - sid: " + sid); if (!sid.contentEquals(identityAllUsers)) { Student s = new Student(); boolean found = false; for (int i = 0; i < students.size(); i++) { if (sid.startsWith(students.get(i).chatId)) { found = true; s = students.get(i); } } if (!found) { s.chatId = sid; s.name = sid; s.role = "UNASSIGNED"; students.add(s); } s.isPresent = true; } } public void removeStudent(String sid) { for (int i = 0; i < students.size(); i++) { Student s = students.get(i); if (s.chatId.equalsIgnoreCase(sid)) { s.isPresent = false; } } } public String getStudentName(String sid) { for (int i = 0; i < students.size(); i++) { Student s = students.get(i); // if (s.isPresent) // No need to check if student is present to return name if (true) { if (s.chatId.equalsIgnoreCase(sid)) { return s.name; } } } return sid; } public void setName(String sid, String name) { // System.err.println("===== State,setName - sid: " + sid + " -- name: " + name); if (!sid.equals(identityAllUsers)) { for (int i = 0; i < students.size(); i++) { if (sid.startsWith(students.get(i).chatId)) { students.get(i).name = name; return; } } addStudent(sid); setName(sid, name); } } public void setStudentPose(String sid, poseEventType pose) { for (int i = 0; i < students.size(); i++) { if (sid.startsWith(students.get(i).chatId)) { students.get(i).pose = pose; return; } } } public poseEventType getStudentPose(String sid) { for (int i = 0; i < students.size(); i++) { Student s = students.get(i); if (s.chatId.equalsIgnoreCase(sid)) { // System.out.println("State.java, getPose - sid/chatId: " + sid + " - pose: " + s.pose.toString()); return s.pose; } } return null; } public String getLocation(String sid) { for (int i = 0; i < students.size(); i++) { Student s = students.get(i); if (s.chatId.equalsIgnoreCase(sid)) { // System.out.println("State.java, getLocation - sid/chatId: " + sid + " - Location: " + s.location); return s.location; } } return null; } public void setLocation(String sid, String location) { for (int i = 0; i < students.size(); i++) { if (sid.startsWith(students.get(i).chatId)) { students.get(i).location = location; // System.out.println("State.java, setLocation - sid/chatId: " + sid + " - Location: " + location); } } } public void addRole(String role) { // System.out.println("===== State,addRole: " + role); roles.add(role); } public void setRoles(String[] roles) { for (int i = 0; i < roles.length; i++) { addRole(roles[i]); // System.out.println("State, setRoles: Added role " + roles[i]); } } public int getNumRoles() { return roles.size(); } public void setStudentRole(String sid, String role) { for (int i = 0; i < students.size(); i++) { if (sid.startsWith(students.get(i).chatId)) { students.get(i).role = role; students.get(i).previousRoles.add(role); } } } public String getStudentRole(String sid) { for (int i = 0; i < students.size(); i++) { if (sid.startsWith(students.get(i).chatId)) { return students.get(i).role; } } return sid; } public Set getStudentPreviousRoles(String sid) { for (int i = 0; i < students.size(); i++) { if (sid.startsWith(students.get(i).chatId)) { return students.get(i).previousRoles; } } return Collections.emptySet(); } public String getRolesString() { String roleString = ""; for (String role : roles) { roleString += role + ", "; } if(roleString.length() > 2) roleString = roleString.substring(0, roleString.length() - 2); return roleString; } public int getStudentCount() { int c = 0; for (int i = 0; i < students.size(); i++) { if (students.get(i).isPresent) { c++; } } return c; } public String[] getStudentIds() { List<String> ids = new ArrayList<String>(); for (int i = 0; i < students.size(); i++) { if (students.get(i).isPresent) { ids.add(students.get(i).chatId); } } return ids.toArray(new String[0]); } public String[] getStudentIdsPresentOrNot() { List<String> ids = new ArrayList<String>(); for (int i = 0; i < students.size(); i++) { // if (students.get(i).isPresent) if (true) { ids.add(students.get(i).chatId); } } return ids.toArray(new String[0]); } public List<String> getStudentIdList() { List<String> ids = new ArrayList<String>(); for (int i = 0; i < students.size(); i++) { if (students.get(i).isPresent) { ids.add(students.get(i).chatId); } } return ids; } public String[] getRandomizedStudentIds() { setRandomizedStudentList(); String[] ids = new String[this.randomizedStudentList.size()]; // System.err.println("getRandomizedStudentIds(), this.randomizedStudentList.size() = " + String.valueOf(randomizedStudentList.size())); for (int i = 0; i < this.randomizedStudentList.size(); i++) { // System.err.println("getRandomizedStudentIds(), adding id " + this.randomizedStudentList.get(i).chatId); // System.err.println("getRandomizedStudentIds(), adding id for name " + this.randomizedStudentList.get(i).name); ids[i] = (this.randomizedStudentList.get(i).chatId); // if (students.get(i).isPresent) // { // ids[i] = (randomizedStudentList.get(i).chatId); // } } // System.err.println("getRandomizedStudentIds, returning ids = " Array.toString(ids)); // for (int i = 0; i < ids.length; i++) { // System.err.println("getRandomizedStudentIds(), ids[" + String.valueOf(i) + "] = " + ids[i]); // } return ids; } public void setRandomizedStudentList() { // System.err.println("Student names: " + Arrays.toString(getStudentNames().toArray())); this.randomizedStudentList.clear(); for (int i = 0; i < students.size(); i++) { // this.randomizedStudentList.add(students.get(i)); if (students.get(i).isPresent) { this.randomizedStudentList.add(students.get(i)); } else { // System.err.println("State, setRandomizedStudentList:<SUF> } } Collections.shuffle(this.randomizedStudentList); setNextStudentIndex(0); // System.err.println("Randomized student names: " + Arrays.toString(getRandomizedStudentNames().toArray())); } public List<String> getStudentNames() { List<String> names = new ArrayList<String>(); for (int i = 0; i < students.size(); i++) { if (students.get(i).isPresent) { names.add(students.get(i).name); } } return names; } public List<String> getRandomizedStudentNames() { List<String> names = new ArrayList<String>(); for (int i = 0; i < randomizedStudentList.size(); i++) { if (randomizedStudentList.get(i).isPresent) { names.add(randomizedStudentList.get(i).name); } } return names; } public List<String> getAllStudentNames() { List<String> ids = new ArrayList<String>(); for (int i = 0; i < students.size(); i++) { ids.add(students.get(i).name); } return ids; } public String[] getStudentNamesByIds(String[] ids) { List<String> names = new ArrayList<String>(); for (int i = 0; i < ids.length; i++) { names.add(getStudentName(ids[i])); } return names.toArray(new String[0]); } public List<String> getStudentNamesByIdList(List<String> ids) { List<String> names = new ArrayList<String>(); for (int i = 0; i < ids.size(); i++) { names.add(getStudentName(ids.get(i))); } return names; } public String getStudentNamesString() { return getStudentNamesString(Arrays.asList(this.getStudentIds())); } public String getStudentNamesString(List<String> users) { String name = ""; for (String id : users) { name += this.getStudentName(id) + ", "; } if(name.length() > 2) name = name.substring(0, name.length() - 2); return name; } public void setNextStudentIndex(int index) { this.nextStudentIndex = index; } public int getNextStudentIndex() { return this.nextStudentIndex; } public int advanceStudentIndex() { int nextIndex = this.nextStudentIndex + 1; // System.err.println("State.java, advanceStudentIndex: initial nextIndex = " + String.valueOf(nextIndex)); if (nextIndex == students.size()) { nextIndex = 0; } setNextStudentIndex(nextIndex); // System.err.println("State.java, advanceStudentIndex: final nextIndex = " + String.valueOf(nextIndex)); return nextIndex; } public Student getStudentById(String sid) { for (int i = 0; i < students.size(); i++) { Student s = students.get(i); if (s.isPresent) { if (s.chatId.equalsIgnoreCase(sid)) { return s; } } } return null; } public String getStudentByRole(String role) { for (int i = 0; i < students.size(); i++) { Student s = students.get(i); if (s.isPresent) { if (s.role.equalsIgnoreCase(role)) { return s.chatId; } } } return null; } public void setStudentActivityMetric(String sid, int metric) { for (int i = 0; i < students.size(); i++) { if (sid.startsWith(students.get(i).chatId)) { students.get(i).activityMetric = metric; } } } public int getStudentActivityMetric(String sid) { for (int i = 0; i < students.size(); i++) { if (sid.startsWith(students.get(i).chatId)) { return students.get(i).activityMetric; } } return 0; } public void setJointActivityMetric(int metric) { jointActivityMetric = metric; } public int getJointActivityMetric() { return jointActivityMetric; } public String getStageName() { if (stageName == null) { return ""; } return stageName; } public String getStageType() { if (stageType == null) { return ""; } return stageType; } public String getStepName() { if (stepName == null) { return ""; } return stepName; } public poseEventType getGroupPose() { return groupPose; } public void setGroupPose(poseEventType pose) { this.groupPose = pose; } public void setMultimodalDontListenWhileSpeaking(Boolean dontListenWhileSpeaking) { this.multimodalDontListenWhileSpeaking = dontListenWhileSpeaking; } public Boolean getMultimodalDontListenWhileSpeaking() { return multimodalDontListenWhileSpeaking; } public LocalDateTime getMultimodalDontListenWhileSpeakingEnd() { return multimodalDontListenEnd; } public void setMultimodalDontListenWhileSpeakingEnd(LocalDateTime dontListenEnd) { this.multimodalDontListenEnd = dontListenEnd; } @Override public String toString() { String ret = "<State students=\"" + students.size() + "\" initiated=\"" + initiated + "\">\n"; ret += "\t<Stage name=\"" + stageName + "\" type=\"" + stageType + "\" />\n"; ret += "\t<Step name=\"" + stepName + "\" type=\"" + stepType + "\"/>\n"; for (int i = 0; i < students.size(); i++) { ret += ("\t" + students.get(i).toString()); } ret += "</State>"; return ret; } }
18395_29
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at www.github.com/MinBZK/operatieBRP. */ package nl.bzk.algemeenbrp.util.common; import java.sql.Timestamp; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; /** * Hulp methodes in het gebruik van datums (timezone UTC) binnen het model van de BRP. */ public final class DatumUtil { /** * String representation of "UTC". */ public static final String UTC = "UTC"; /** * String representation of "Europe/Amsterdam". */ public static final String NL = "Europe/Amsterdam"; /** * UTC tijdzone wordt gebruikt voor datums in de BRP. */ public static final TimeZone BRP_TIJDZONE = TimeZone.getTimeZone(UTC); /** * NL tijdzone wordt gebruikt voor datums in de BRP. */ public static final TimeZone NL_TIJDZONE = TimeZone.getTimeZone(NL); /** * UTC Zone Id. */ public static final ZoneId BRP_ZONE_ID = ZoneId.of(DatumUtil.UTC); /** * NL Zone Id. */ public static final ZoneId NL_ZONE_ID = ZoneId.of(DatumUtil.NL); private static final ZoneId ZONE_UTC = ZoneId.of(UTC); private static final String DATUM_FORMAT = "yyyyMMdd"; private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(DATUM_FORMAT); private static final int MOD_JAAR = 10000_00_00; private static final int MOD_MAAND = 1_00_00; private static final int MOD_DAG = 100; private static final int MINIMALE_DATUM = 1_01_01; private static final int MAXIMALE_MAAND = 1231; private static final int MAXIMALE_DATUM = 9999_12_31; private static final int MINIMALE_MAAND = 101; /* * Explicit private constructor voor utility class. */ private DatumUtil() { throw new AssertionError("Er mag geen instantie gemaakt worden van DatumUtil."); } /** * Converteert de gegeven datum naar een Integer in het formaat yyyyMMdd. * @param datum de datum * @return de integer waarde van de gegeven datum */ public static int vanDatumNaarInteger(final Date datum) { return Integer.parseInt(vanDatumNaarString(datum)); } /** * Converteert de gegeven datum naar een Integer in het formaat yyyyMMdd. * @param datum de datum in {@link ZonedDateTime} formaat * @return de integer waarde van de gegeven datum */ public static int vanDatumNaarInteger(final LocalDate datum) { final Calendar instance = Calendar.getInstance(); instance.set(datum.getYear(), datum.getMonthValue() - 1, datum.getDayOfMonth()); return Integer.parseInt(vanDatumNaarString(instance.getTime())); } /** * Geeft de {@link Date} waarde van een {@link LocalDateTime} object. * @param datum {@link LocalDateTime} object * @return {@link Date} object */ public static Date vanLocalDateTimeNaarDate(final LocalDateTime datum) { if (datum != null) { return Date.from(datum.toInstant(ZoneOffset.UTC)); } return null; } /** * Geeft de {@link Long} waarde van een {@link LocalDateTime} object. * @param datum {@link LocalDateTime} object * @return Long waarde */ public static Long vanLocalDateTimeNaarLong(final LocalDateTime datum) { if (datum != null) { return Date.from(datum.toInstant(ZoneOffset.UTC)).getTime(); } return null; } /** * Geeft de {@link Date} waarde van een {@link ZonedDateTime} object. * @param datum {@link ZonedDateTime} object * @return {@link Date} object */ public static Date vanDateTimeNaarDate(final ZonedDateTime datum) { if (datum != null) { return Date.from(datum.toInstant()); } return null; } /** * Geeft de {@link Long} waarde van een {@link ZonedDateTime} object. * @param datum {@link ZonedDateTime} object * @return Long waarde */ public static Long vanDateTimeNaarLong(final ZonedDateTime datum) { if (datum != null) { return Date.from(datum.toInstant()).getTime(); } return null; } /** * Van ZonedDateTime naar localdate in nederland. * @param datum {@link ZonedDateTime} object * @return de localdate in nederland. */ public static LocalDate vanZonedDateTimeNaarLocalDateNederland(final ZonedDateTime datum) { return datum.withZoneSameInstant(NL_ZONE_ID).toLocalDate(); } /** * Geeft de {@link ZonedDateTime} waarde van een long (sinds epoch). * @param tijd tijd * @return ZonedDateTime in UTC */ public static ZonedDateTime vanLongNaarZonedDateTime(final long tijd) { return ZonedDateTime.ofInstant(Instant.ofEpochMilli(tijd), DatumUtil.BRP_ZONE_ID); } /** * Geeft de {@link ZonedDateTime} waarde van een {@link Timestamp}. * @param timestamp timestamp * @return timestamp als zonedDateTime */ public static ZonedDateTime vanTimestampNaarZonedDateTime(final Timestamp timestamp) { if (timestamp == null) { return null; } return ZonedDateTime.ofInstant(Instant.ofEpochMilli(timestamp.getTime()), DatumUtil.BRP_ZONE_ID); } /** * Geeft de {@link LocalDateTime} waarde van een {@link Date} object. * @param datum {@link Date} object * @return {@link LocalDateTime} object */ public static ZonedDateTime vanDateNaarZonedDateTime(final Date datum) { if (datum != null) { return ZonedDateTime.ofInstant(Instant.ofEpochMilli(datum.getTime()), DatumUtil.BRP_ZONE_ID); } return null; } /** * Geeft de {@link java.sql.Timestamp} waarde van een {@link ZonedDateTime} object. * @param zonedDateTime {@link ZonedDateTime} object * @return {@link java.sql.Timestamp} object */ public static Timestamp vanZonedDateTimeNaarSqlTimeStamp(final ZonedDateTime zonedDateTime) { if (zonedDateTime != null) { return new Timestamp(zonedDateTime.toInstant().toEpochMilli()); } return null; } /** * Converteert de gegeven datum naar een String in het formaat 'yyyyMMdd'. * @param datum de datum * @return de string waarde van de gegeven datum */ public static String vanDatumNaarString(final Date datum) { if (datum != null) { return FORMATTER.format(vanDateNaarZonedDateTime(datum)); } return null; } /** * Maakt van een integer datum een {@link LocalDate}. * @param datum de datum als integer * @return de {@link LocalDate} */ public static LocalDate vanIntegerNaarLocalDate(final int datum) { final String datumString = String.valueOf(datum); if (datumString.length() != DATUM_FORMAT.length()) { throw new UnsupportedOperationException(String.format("%s is een ongeldige datum.", datum)); } return LocalDate.parse(datumString, FORMATTER); } /** * Maakt van een integer datum een {@link ZonedDateTime}. * @param datum de datum als integer * @return de {@link ZonedDateTime} */ public static ZonedDateTime vanIntegerNaarZonedDateTime(final int datum) { return vanIntegerNaarLocalDate(datum).atStartOfDay(NL_ZONE_ID).withZoneSameInstant(ZONE_UTC); } /** * Geeft de {@link LocalDateTime} waarde van een {@link Date} object. * @param datum {@link Date} object * @return {@link LocalDateTime} object */ public static LocalDateTime vanDateNaarLocalDateTime(final Date datum) { if (datum != null) { return LocalDateTime.ofInstant(Instant.ofEpochMilli(datum.getTime()), ZoneOffset.UTC); } return null; } /** * Converteert een String van het formaat 'yyyyMMdd' naar een {@link Date} object. * @param waarde een string in het formaat 'yyyyMMdd' * @return de datum */ public static Date vanStringNaarDatum(final String waarde) { if (waarde != null) { return Date.from(LocalDate.parse(waarde, FORMATTER).atStartOfDay(ZONE_UTC).toInstant()); } return null; } /** * Geeft de datum+tijd op dit moment. * @return de datum+tijd van dit moment */ public static Date nu() { final Calendar calendar = Calendar.getInstance(); calendar.setTimeZone(BRP_TIJDZONE); return calendar.getTime(); } /** * Geeft de datum+tijd op dit moment als ZonedDateTime. * @return nu als zonedDateTime */ public static ZonedDateTime nuAlsZonedDateTime() { return ZonedDateTime.now(); } /** * Geeft de datum+tijd op dit moment als ZonedDateTime. * @return nu als zonedDateTime */ public static ZonedDateTime nuAlsZonedDateTimeInNederland() { return ZonedDateTime.now().toInstant().atZone(NL_ZONE_ID); } /** * Geeft de datum van vandaag zonder tijd in Nederland. * @return de datum van vandaag */ public static int vandaag() { return datumRondVandaag(0); } /** * Retourneert de datum van gisteren als integer. * @return datum van gisteren als integer. */ public static Integer gisteren() { return datumRondVandaag(1); } /** * Retourneert de datum van morgen als integer. * @return datum van morgen als integer. */ public static Integer morgen() { return datumRondVandaag(-1); } /** * Retourneert een datum rond vandaag als integer. minusDagen wordt van vandaag afgetrokken. Een * negatief aantal dagen wordt opgeteld. * @param minusDagen het aantal dagen dat afgetrokken wordt van vandaag * @return datum als integer */ public static Integer datumRondVandaag(final int minusDagen) { final LocalDate date = LocalDate.now(NL_ZONE_ID).minus(minusDagen, ChronoUnit.DAYS); final String formattedDateString = FORMATTER.format(date); return Integer.parseInt(formattedDateString); } /** * bepaald de nieuwe datum door van de meegegeven datum het aantal meegegeven dagen af te trekken * @param datum peilDatum * @param minus aantal dagen voor peildatum * @return bepaalde datum */ public static Integer bepaalDatum(final int datum, final int minus) { final Integer minimaleDatum = bepaalEindDatumStrengOfBeginDatumSoepel(datum, false); final LocalDate minimaleDate = vanIntegerNaarLocalDate(minimaleDatum); final LocalDate nieuweDate = minimaleDate.minus(minus, ChronoUnit.DAYS); final String formattedDateString = FORMATTER.format(nieuweDate); return Integer.parseInt(formattedDateString); } /** * Controleert of de gegeven peildatum binnen de gegeven periode van twee datums valt. Een * peildatum gelijk aan de begindatum wordt gezien als binnen de periode (inclusief) en een * peildatum gelijk aan de eindatum wordt gezien als buiten de periode (exclusief). De begin en * einddatum zijn optioneel, wanneer elk van deze ontbreekt wordt alleen gecontroleerd of de * peildatum groter of gelijk is aan de begindatum of andersom. Beiden onbekend zal true terug * geven. * @param peilDatum de peildatum * @param beginDatum de begindatum (inclusief) * @param eindDatum de optionele einddatum (exclusief) * @return true als de peildatum binnen de gegeven periode valt, anders false */ public static boolean valtDatumBinnenPeriode(final int peilDatum, final Integer beginDatum, final Integer eindDatum) { return valtDatumBinnenPeriode(peilDatum, beginDatum, eindDatum, false); } /** * Controleert of de gegeven peildatum binnen de gegeven periode van twee datums valt. Een * peildatum gelijk aan de begindatum wordt gezien als binnen de periode (inclusief) en een * peildatum gelijk aan de eindatum wordt gezien als buiten de periode (inclusief). De begin en * einddatum zijn optioneel, wanneer elk van deze ontbreekt wordt alleen gecontroleerd of de * peildatum groter of gelijk is aan de begindatum of andersom. Beiden onbekend zal true terug * geven. * @param peilDatum de peildatum * @param beginDatum de begindatum (inclusief) * @param eindDatum de optionele einddatum (inclusief) * @return true als de peildatum binnen de gegeven periode valt, anders false */ public static boolean valtDatumBinnenPeriodeInclusief(final int peilDatum, final Integer beginDatum, final Integer eindDatum) { return valtDatumBinnenPeriode(peilDatum, beginDatum, eindDatum, true); } private static boolean valtDatumBinnenPeriode(final int peilDatum, final Integer beginDatum, final Integer eindDatum, final boolean inclusief) { if (peilDatum == 0) { return true; } final boolean peilDatumNaBeginDatum = beginDatum == null || beginDatum <= peilDatum; final boolean peilDatumVoorEindDatum = eindDatum == null || (inclusief ? peilDatum <= bepaalEindDatumSoepel(eindDatum) : peilDatum < bepaalEindDatumSoepel(eindDatum)); return peilDatumNaBeginDatum && peilDatumVoorEindDatum; } /** * Bepaald of de pijl datum binnen een periode valt waarbij inclusief de beginDatum en exclusief * de eindDatum. De vergelijking is "Streng" wat inhoud dat bij een onbekende datum elke * onzekerheid wordt afgekeurd. BV: de begin datum van een periode is gedeeltelijk onbekend * (20010000 - 20030205) 20010000 word nu de maximale waarde bepaald: 20011231 (20011231 - * 20030205); de eind datum is gedeeltelijk onbekend (20010501 - 20030000) 20030000 word nu de * minimale waarde 20030101 (20010501 - 20030101) Bij een onbekende pijldatum moet zowel de * minimale als maximale waarde binnen de periode vallen: periode 20020215 - 20030615 pijldatum * 20030000 (20030101 en 20031231) valt hier binnen. pijldatum 20020600 (20020601 en 20020630) * valt hier binnen. pijldatum 20030600 (20030601 en 20030630) valt hier buiten. pijldatum * 20020200 (20020201 en 20020228) valt hier buiten. * @param peilDatum de peildatum * @param beginDatum de begindatum * @param eindDatum de einddatum * @return true als de peildatum binnen de gegeven periode valt, anders false */ public static boolean valtDatumBinnenPeriodeStreng(final int peilDatum, final Integer beginDatum, final Integer eindDatum) { final Integer begin = bepaalBeginDatumStrengOfEindDatumSoepel(beginDatum, true); final Integer eind = bepaalEindDatumStrengOfBeginDatumSoepel(eindDatum, true); if (peilDatum % MOD_DAG == 0) { int minPeilDatum = peilDatum; int maxPeilDatum = peilDatum; if (peilDatum == 0) { minPeilDatum = MINIMALE_DATUM; maxPeilDatum = MAXIMALE_DATUM; } else if (peilDatum % MOD_MAAND == 0) { minPeilDatum += MINIMALE_MAAND; maxPeilDatum += MAXIMALE_MAAND; } else { minPeilDatum += 1; maxPeilDatum += haalLaatsteDagVanDeMaandOp(begin); } return valtDatumBinnenPeriode(minPeilDatum, begin, eind) && valtDatumBinnenPeriode(maxPeilDatum, begin, eind); } return valtDatumBinnenPeriode(peilDatum, begin, eind); } /** * Bepaalt het aantal jaren tussen twee datums. Deze methode gebruikt de SOEPEL manier van * datums vergelijken. * @param begin int representatie van begin moment 'yyyyMMdd' * @param eind int representatie van eind moment 'yyyyMMdd' * @return verschil in jaren, null if begin or eind == null. */ public static Long bepaalJarenTussenDatumsSoepel(final Integer begin, final Integer eind) { return bepaalPeriodeTussenDatumsSoepel(begin, eind, ChronoUnit.YEARS); } /** * Bepaalt het aantal dagen tussen twee datums. Deze methode gebruikt de SOEPEL manier van * datums vergelijken. * @param begin int representatie van begin moment 'yyyyMMdd' * @param eind int representatie van eind moment 'yyyyMMdd' * @return verschil in dagen, null if begin or eind == null. */ public static Long bepaalDagenTussenDatumsSoepel(final Integer begin, final Integer eind) { return bepaalPeriodeTussenDatumsSoepel(begin, eind, ChronoUnit.DAYS); } private static Long bepaalPeriodeTussenDatumsSoepel(final Integer begin, final Integer eind, final ChronoUnit periodeEenheid) { if (begin == null || eind == null) { return null; } final Integer beginDatumSoepel = bepaalEindDatumStrengOfBeginDatumSoepel(begin, false); final Integer eindDatumSoepel = bepaalBeginDatumStrengOfEindDatumSoepel(eind, false); final String dateFormat = "%08d"; final LocalDate van = LocalDate.parse(String.format(dateFormat, beginDatumSoepel), FORMATTER); final LocalDate tot = LocalDate.parse(String.format(dateFormat, eindDatumSoepel), FORMATTER); return periodeEenheid.between(van, tot); } /** * Haalt de laatste dag van de maand op. * @param datum de datum waarvan de laatste wordt opgehaald. * @return de laatste dag van de maand. */ public static int haalLaatsteDagVanDeMaandOp(final int datum) { final int jaar = datum % MOD_JAAR / MOD_MAAND; final int maand = datum % MOD_MAAND / MOD_DAG; final LocalDate date = LocalDate.of(jaar, maand, 1); return date.lengthOfMonth(); } /** * Contoleer of de datum een geldige kalander datum is. Een (deels) onbekende datum is geen * geldige kalender datum. * @param datum String representatie van de datum 'yyyyMMdd' * @return true of false. */ public static boolean isGeldigeKalenderdatum(final Integer datum) { boolean geldig = datum != null && datum != 0; if (geldig) { try { final String datumString = datum.toString(); final int jaar = Integer.parseInt(datumString.substring(0, 4)); final int maand = Integer.parseInt(datumString.substring(4, 6)); final int dag = Integer.parseInt(datumString.substring(6, 8)); final Calendar c = new GregorianCalendar(); c.setLenient(false); c.set(jaar, maand - 1, dag); c.getTime(); geldig = true; } catch (final IllegalArgumentException e) { return false; } } return geldig; } /** * Converteert een xsd-datum naar een {@link Integer}. * @param datum datum * @return datum als integer */ public static Integer vanXsdDatumNaarInteger(final String datum) { final LocalDate localDate = LocalDate.parse(datum, DateTimeFormatter.ISO_DATE); return Integer.parseInt(localDate.format(DateTimeFormatter.BASIC_ISO_DATE)); } /** * Converteert een xsd-datum naar een {@link ZonedDateTime}. * @param datumTijd datumTijd * @return date */ public static ZonedDateTime vanXsdDatumTijdNaarZonedDateTime(final String datumTijd) { if (datumTijd == null || datumTijd.isEmpty()) { return null; } return ZonedDateTime.parse(datumTijd, DateTimeFormatter.ISO_DATE_TIME).withZoneSameInstant(ZoneId.of(DatumUtil.UTC)); } /** * Converteert een xsd-datum naar een {@link java.util.Date}. * @param datumTijd datumTijd * @return date */ public static Date vanXsdDatumTijdNaarDate(final String datumTijd) { final ZonedDateTime zonedDateTime = ZonedDateTime.parse(datumTijd, DateTimeFormatter.ISO_DATE_TIME).withZoneSameInstant(ZoneId.of(DatumUtil.UTC)); final LocalDateTime toLocalDateTime = zonedDateTime.toLocalDateTime(); return Date.from(toLocalDateTime.atZone(ZoneId.of(DatumUtil.UTC)).toInstant()); } /** * Controleert of (onbekende)datum groter of gelijk is aan (onbekende)peildatum, bij onbekende datums wordt uit gegaan van minimale datums * (20160000 -> 20160101) * @param datum te controleren datum. * @param peildatum datum waarmee vergeleken wordt. * @return true indien datum >= peildatum. */ public static boolean vergelijkOnbekendeDatumsGroterOfGelijkAan(final Integer datum, final Integer peildatum) { return bepaalEindDatumStrengOfBeginDatumSoepel(datum, false) >= bepaalEindDatumStrengOfBeginDatumSoepel(peildatum, false); } private static Integer bepaalEindDatumStrengOfBeginDatumSoepel(final Integer datum, final boolean isEindDatum) { Integer resultaat = datum; if (datum == null || datum == 0) { resultaat = isEindDatum ? MAXIMALE_DATUM : MINIMALE_DATUM; } else if (datum % MOD_MAAND == 0) { resultaat += MINIMALE_MAAND; } else if (datum % MOD_DAG == 0) { resultaat += 1; } return resultaat; } private static Integer bepaalBeginDatumStrengOfEindDatumSoepel(final Integer datum, final boolean isBeginDatum) { Integer resultaat = datum; if (datum == null || datum == 0) { resultaat = isBeginDatum ? MINIMALE_DATUM : MAXIMALE_DATUM; } else if (datum % MOD_MAAND == 0) { resultaat += MAXIMALE_MAAND; } else if (datum % MOD_DAG == 0) { resultaat += haalLaatsteDagVanDeMaandOp(datum); } return resultaat; } private static Integer bepaalEindDatumSoepel(final Integer datum) { Integer resultaat = datum; if (datum == null || datum == 0) { resultaat = MAXIMALE_DATUM; } else if (datum % MOD_MAAND == 0) { resultaat += MAXIMALE_MAAND; } else if (datum % MOD_DAG == 0) { resultaat += haalLaatsteDagVanDeMaandOp(datum); } return resultaat; } }
DDDNL/OperatieBRP
Broncode/operatiebrp-code-145.3/algemeen/alg-util-common/src/main/java/nl/bzk/algemeenbrp/util/common/DatumUtil.java
7,123
/** * Retourneert de datum van gisteren als integer. * @return datum van gisteren als integer. */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at www.github.com/MinBZK/operatieBRP. */ package nl.bzk.algemeenbrp.util.common; import java.sql.Timestamp; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; /** * Hulp methodes in het gebruik van datums (timezone UTC) binnen het model van de BRP. */ public final class DatumUtil { /** * String representation of "UTC". */ public static final String UTC = "UTC"; /** * String representation of "Europe/Amsterdam". */ public static final String NL = "Europe/Amsterdam"; /** * UTC tijdzone wordt gebruikt voor datums in de BRP. */ public static final TimeZone BRP_TIJDZONE = TimeZone.getTimeZone(UTC); /** * NL tijdzone wordt gebruikt voor datums in de BRP. */ public static final TimeZone NL_TIJDZONE = TimeZone.getTimeZone(NL); /** * UTC Zone Id. */ public static final ZoneId BRP_ZONE_ID = ZoneId.of(DatumUtil.UTC); /** * NL Zone Id. */ public static final ZoneId NL_ZONE_ID = ZoneId.of(DatumUtil.NL); private static final ZoneId ZONE_UTC = ZoneId.of(UTC); private static final String DATUM_FORMAT = "yyyyMMdd"; private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(DATUM_FORMAT); private static final int MOD_JAAR = 10000_00_00; private static final int MOD_MAAND = 1_00_00; private static final int MOD_DAG = 100; private static final int MINIMALE_DATUM = 1_01_01; private static final int MAXIMALE_MAAND = 1231; private static final int MAXIMALE_DATUM = 9999_12_31; private static final int MINIMALE_MAAND = 101; /* * Explicit private constructor voor utility class. */ private DatumUtil() { throw new AssertionError("Er mag geen instantie gemaakt worden van DatumUtil."); } /** * Converteert de gegeven datum naar een Integer in het formaat yyyyMMdd. * @param datum de datum * @return de integer waarde van de gegeven datum */ public static int vanDatumNaarInteger(final Date datum) { return Integer.parseInt(vanDatumNaarString(datum)); } /** * Converteert de gegeven datum naar een Integer in het formaat yyyyMMdd. * @param datum de datum in {@link ZonedDateTime} formaat * @return de integer waarde van de gegeven datum */ public static int vanDatumNaarInteger(final LocalDate datum) { final Calendar instance = Calendar.getInstance(); instance.set(datum.getYear(), datum.getMonthValue() - 1, datum.getDayOfMonth()); return Integer.parseInt(vanDatumNaarString(instance.getTime())); } /** * Geeft de {@link Date} waarde van een {@link LocalDateTime} object. * @param datum {@link LocalDateTime} object * @return {@link Date} object */ public static Date vanLocalDateTimeNaarDate(final LocalDateTime datum) { if (datum != null) { return Date.from(datum.toInstant(ZoneOffset.UTC)); } return null; } /** * Geeft de {@link Long} waarde van een {@link LocalDateTime} object. * @param datum {@link LocalDateTime} object * @return Long waarde */ public static Long vanLocalDateTimeNaarLong(final LocalDateTime datum) { if (datum != null) { return Date.from(datum.toInstant(ZoneOffset.UTC)).getTime(); } return null; } /** * Geeft de {@link Date} waarde van een {@link ZonedDateTime} object. * @param datum {@link ZonedDateTime} object * @return {@link Date} object */ public static Date vanDateTimeNaarDate(final ZonedDateTime datum) { if (datum != null) { return Date.from(datum.toInstant()); } return null; } /** * Geeft de {@link Long} waarde van een {@link ZonedDateTime} object. * @param datum {@link ZonedDateTime} object * @return Long waarde */ public static Long vanDateTimeNaarLong(final ZonedDateTime datum) { if (datum != null) { return Date.from(datum.toInstant()).getTime(); } return null; } /** * Van ZonedDateTime naar localdate in nederland. * @param datum {@link ZonedDateTime} object * @return de localdate in nederland. */ public static LocalDate vanZonedDateTimeNaarLocalDateNederland(final ZonedDateTime datum) { return datum.withZoneSameInstant(NL_ZONE_ID).toLocalDate(); } /** * Geeft de {@link ZonedDateTime} waarde van een long (sinds epoch). * @param tijd tijd * @return ZonedDateTime in UTC */ public static ZonedDateTime vanLongNaarZonedDateTime(final long tijd) { return ZonedDateTime.ofInstant(Instant.ofEpochMilli(tijd), DatumUtil.BRP_ZONE_ID); } /** * Geeft de {@link ZonedDateTime} waarde van een {@link Timestamp}. * @param timestamp timestamp * @return timestamp als zonedDateTime */ public static ZonedDateTime vanTimestampNaarZonedDateTime(final Timestamp timestamp) { if (timestamp == null) { return null; } return ZonedDateTime.ofInstant(Instant.ofEpochMilli(timestamp.getTime()), DatumUtil.BRP_ZONE_ID); } /** * Geeft de {@link LocalDateTime} waarde van een {@link Date} object. * @param datum {@link Date} object * @return {@link LocalDateTime} object */ public static ZonedDateTime vanDateNaarZonedDateTime(final Date datum) { if (datum != null) { return ZonedDateTime.ofInstant(Instant.ofEpochMilli(datum.getTime()), DatumUtil.BRP_ZONE_ID); } return null; } /** * Geeft de {@link java.sql.Timestamp} waarde van een {@link ZonedDateTime} object. * @param zonedDateTime {@link ZonedDateTime} object * @return {@link java.sql.Timestamp} object */ public static Timestamp vanZonedDateTimeNaarSqlTimeStamp(final ZonedDateTime zonedDateTime) { if (zonedDateTime != null) { return new Timestamp(zonedDateTime.toInstant().toEpochMilli()); } return null; } /** * Converteert de gegeven datum naar een String in het formaat 'yyyyMMdd'. * @param datum de datum * @return de string waarde van de gegeven datum */ public static String vanDatumNaarString(final Date datum) { if (datum != null) { return FORMATTER.format(vanDateNaarZonedDateTime(datum)); } return null; } /** * Maakt van een integer datum een {@link LocalDate}. * @param datum de datum als integer * @return de {@link LocalDate} */ public static LocalDate vanIntegerNaarLocalDate(final int datum) { final String datumString = String.valueOf(datum); if (datumString.length() != DATUM_FORMAT.length()) { throw new UnsupportedOperationException(String.format("%s is een ongeldige datum.", datum)); } return LocalDate.parse(datumString, FORMATTER); } /** * Maakt van een integer datum een {@link ZonedDateTime}. * @param datum de datum als integer * @return de {@link ZonedDateTime} */ public static ZonedDateTime vanIntegerNaarZonedDateTime(final int datum) { return vanIntegerNaarLocalDate(datum).atStartOfDay(NL_ZONE_ID).withZoneSameInstant(ZONE_UTC); } /** * Geeft de {@link LocalDateTime} waarde van een {@link Date} object. * @param datum {@link Date} object * @return {@link LocalDateTime} object */ public static LocalDateTime vanDateNaarLocalDateTime(final Date datum) { if (datum != null) { return LocalDateTime.ofInstant(Instant.ofEpochMilli(datum.getTime()), ZoneOffset.UTC); } return null; } /** * Converteert een String van het formaat 'yyyyMMdd' naar een {@link Date} object. * @param waarde een string in het formaat 'yyyyMMdd' * @return de datum */ public static Date vanStringNaarDatum(final String waarde) { if (waarde != null) { return Date.from(LocalDate.parse(waarde, FORMATTER).atStartOfDay(ZONE_UTC).toInstant()); } return null; } /** * Geeft de datum+tijd op dit moment. * @return de datum+tijd van dit moment */ public static Date nu() { final Calendar calendar = Calendar.getInstance(); calendar.setTimeZone(BRP_TIJDZONE); return calendar.getTime(); } /** * Geeft de datum+tijd op dit moment als ZonedDateTime. * @return nu als zonedDateTime */ public static ZonedDateTime nuAlsZonedDateTime() { return ZonedDateTime.now(); } /** * Geeft de datum+tijd op dit moment als ZonedDateTime. * @return nu als zonedDateTime */ public static ZonedDateTime nuAlsZonedDateTimeInNederland() { return ZonedDateTime.now().toInstant().atZone(NL_ZONE_ID); } /** * Geeft de datum van vandaag zonder tijd in Nederland. * @return de datum van vandaag */ public static int vandaag() { return datumRondVandaag(0); } /** * Retourneert de datum<SUF>*/ public static Integer gisteren() { return datumRondVandaag(1); } /** * Retourneert de datum van morgen als integer. * @return datum van morgen als integer. */ public static Integer morgen() { return datumRondVandaag(-1); } /** * Retourneert een datum rond vandaag als integer. minusDagen wordt van vandaag afgetrokken. Een * negatief aantal dagen wordt opgeteld. * @param minusDagen het aantal dagen dat afgetrokken wordt van vandaag * @return datum als integer */ public static Integer datumRondVandaag(final int minusDagen) { final LocalDate date = LocalDate.now(NL_ZONE_ID).minus(minusDagen, ChronoUnit.DAYS); final String formattedDateString = FORMATTER.format(date); return Integer.parseInt(formattedDateString); } /** * bepaald de nieuwe datum door van de meegegeven datum het aantal meegegeven dagen af te trekken * @param datum peilDatum * @param minus aantal dagen voor peildatum * @return bepaalde datum */ public static Integer bepaalDatum(final int datum, final int minus) { final Integer minimaleDatum = bepaalEindDatumStrengOfBeginDatumSoepel(datum, false); final LocalDate minimaleDate = vanIntegerNaarLocalDate(minimaleDatum); final LocalDate nieuweDate = minimaleDate.minus(minus, ChronoUnit.DAYS); final String formattedDateString = FORMATTER.format(nieuweDate); return Integer.parseInt(formattedDateString); } /** * Controleert of de gegeven peildatum binnen de gegeven periode van twee datums valt. Een * peildatum gelijk aan de begindatum wordt gezien als binnen de periode (inclusief) en een * peildatum gelijk aan de eindatum wordt gezien als buiten de periode (exclusief). De begin en * einddatum zijn optioneel, wanneer elk van deze ontbreekt wordt alleen gecontroleerd of de * peildatum groter of gelijk is aan de begindatum of andersom. Beiden onbekend zal true terug * geven. * @param peilDatum de peildatum * @param beginDatum de begindatum (inclusief) * @param eindDatum de optionele einddatum (exclusief) * @return true als de peildatum binnen de gegeven periode valt, anders false */ public static boolean valtDatumBinnenPeriode(final int peilDatum, final Integer beginDatum, final Integer eindDatum) { return valtDatumBinnenPeriode(peilDatum, beginDatum, eindDatum, false); } /** * Controleert of de gegeven peildatum binnen de gegeven periode van twee datums valt. Een * peildatum gelijk aan de begindatum wordt gezien als binnen de periode (inclusief) en een * peildatum gelijk aan de eindatum wordt gezien als buiten de periode (inclusief). De begin en * einddatum zijn optioneel, wanneer elk van deze ontbreekt wordt alleen gecontroleerd of de * peildatum groter of gelijk is aan de begindatum of andersom. Beiden onbekend zal true terug * geven. * @param peilDatum de peildatum * @param beginDatum de begindatum (inclusief) * @param eindDatum de optionele einddatum (inclusief) * @return true als de peildatum binnen de gegeven periode valt, anders false */ public static boolean valtDatumBinnenPeriodeInclusief(final int peilDatum, final Integer beginDatum, final Integer eindDatum) { return valtDatumBinnenPeriode(peilDatum, beginDatum, eindDatum, true); } private static boolean valtDatumBinnenPeriode(final int peilDatum, final Integer beginDatum, final Integer eindDatum, final boolean inclusief) { if (peilDatum == 0) { return true; } final boolean peilDatumNaBeginDatum = beginDatum == null || beginDatum <= peilDatum; final boolean peilDatumVoorEindDatum = eindDatum == null || (inclusief ? peilDatum <= bepaalEindDatumSoepel(eindDatum) : peilDatum < bepaalEindDatumSoepel(eindDatum)); return peilDatumNaBeginDatum && peilDatumVoorEindDatum; } /** * Bepaald of de pijl datum binnen een periode valt waarbij inclusief de beginDatum en exclusief * de eindDatum. De vergelijking is "Streng" wat inhoud dat bij een onbekende datum elke * onzekerheid wordt afgekeurd. BV: de begin datum van een periode is gedeeltelijk onbekend * (20010000 - 20030205) 20010000 word nu de maximale waarde bepaald: 20011231 (20011231 - * 20030205); de eind datum is gedeeltelijk onbekend (20010501 - 20030000) 20030000 word nu de * minimale waarde 20030101 (20010501 - 20030101) Bij een onbekende pijldatum moet zowel de * minimale als maximale waarde binnen de periode vallen: periode 20020215 - 20030615 pijldatum * 20030000 (20030101 en 20031231) valt hier binnen. pijldatum 20020600 (20020601 en 20020630) * valt hier binnen. pijldatum 20030600 (20030601 en 20030630) valt hier buiten. pijldatum * 20020200 (20020201 en 20020228) valt hier buiten. * @param peilDatum de peildatum * @param beginDatum de begindatum * @param eindDatum de einddatum * @return true als de peildatum binnen de gegeven periode valt, anders false */ public static boolean valtDatumBinnenPeriodeStreng(final int peilDatum, final Integer beginDatum, final Integer eindDatum) { final Integer begin = bepaalBeginDatumStrengOfEindDatumSoepel(beginDatum, true); final Integer eind = bepaalEindDatumStrengOfBeginDatumSoepel(eindDatum, true); if (peilDatum % MOD_DAG == 0) { int minPeilDatum = peilDatum; int maxPeilDatum = peilDatum; if (peilDatum == 0) { minPeilDatum = MINIMALE_DATUM; maxPeilDatum = MAXIMALE_DATUM; } else if (peilDatum % MOD_MAAND == 0) { minPeilDatum += MINIMALE_MAAND; maxPeilDatum += MAXIMALE_MAAND; } else { minPeilDatum += 1; maxPeilDatum += haalLaatsteDagVanDeMaandOp(begin); } return valtDatumBinnenPeriode(minPeilDatum, begin, eind) && valtDatumBinnenPeriode(maxPeilDatum, begin, eind); } return valtDatumBinnenPeriode(peilDatum, begin, eind); } /** * Bepaalt het aantal jaren tussen twee datums. Deze methode gebruikt de SOEPEL manier van * datums vergelijken. * @param begin int representatie van begin moment 'yyyyMMdd' * @param eind int representatie van eind moment 'yyyyMMdd' * @return verschil in jaren, null if begin or eind == null. */ public static Long bepaalJarenTussenDatumsSoepel(final Integer begin, final Integer eind) { return bepaalPeriodeTussenDatumsSoepel(begin, eind, ChronoUnit.YEARS); } /** * Bepaalt het aantal dagen tussen twee datums. Deze methode gebruikt de SOEPEL manier van * datums vergelijken. * @param begin int representatie van begin moment 'yyyyMMdd' * @param eind int representatie van eind moment 'yyyyMMdd' * @return verschil in dagen, null if begin or eind == null. */ public static Long bepaalDagenTussenDatumsSoepel(final Integer begin, final Integer eind) { return bepaalPeriodeTussenDatumsSoepel(begin, eind, ChronoUnit.DAYS); } private static Long bepaalPeriodeTussenDatumsSoepel(final Integer begin, final Integer eind, final ChronoUnit periodeEenheid) { if (begin == null || eind == null) { return null; } final Integer beginDatumSoepel = bepaalEindDatumStrengOfBeginDatumSoepel(begin, false); final Integer eindDatumSoepel = bepaalBeginDatumStrengOfEindDatumSoepel(eind, false); final String dateFormat = "%08d"; final LocalDate van = LocalDate.parse(String.format(dateFormat, beginDatumSoepel), FORMATTER); final LocalDate tot = LocalDate.parse(String.format(dateFormat, eindDatumSoepel), FORMATTER); return periodeEenheid.between(van, tot); } /** * Haalt de laatste dag van de maand op. * @param datum de datum waarvan de laatste wordt opgehaald. * @return de laatste dag van de maand. */ public static int haalLaatsteDagVanDeMaandOp(final int datum) { final int jaar = datum % MOD_JAAR / MOD_MAAND; final int maand = datum % MOD_MAAND / MOD_DAG; final LocalDate date = LocalDate.of(jaar, maand, 1); return date.lengthOfMonth(); } /** * Contoleer of de datum een geldige kalander datum is. Een (deels) onbekende datum is geen * geldige kalender datum. * @param datum String representatie van de datum 'yyyyMMdd' * @return true of false. */ public static boolean isGeldigeKalenderdatum(final Integer datum) { boolean geldig = datum != null && datum != 0; if (geldig) { try { final String datumString = datum.toString(); final int jaar = Integer.parseInt(datumString.substring(0, 4)); final int maand = Integer.parseInt(datumString.substring(4, 6)); final int dag = Integer.parseInt(datumString.substring(6, 8)); final Calendar c = new GregorianCalendar(); c.setLenient(false); c.set(jaar, maand - 1, dag); c.getTime(); geldig = true; } catch (final IllegalArgumentException e) { return false; } } return geldig; } /** * Converteert een xsd-datum naar een {@link Integer}. * @param datum datum * @return datum als integer */ public static Integer vanXsdDatumNaarInteger(final String datum) { final LocalDate localDate = LocalDate.parse(datum, DateTimeFormatter.ISO_DATE); return Integer.parseInt(localDate.format(DateTimeFormatter.BASIC_ISO_DATE)); } /** * Converteert een xsd-datum naar een {@link ZonedDateTime}. * @param datumTijd datumTijd * @return date */ public static ZonedDateTime vanXsdDatumTijdNaarZonedDateTime(final String datumTijd) { if (datumTijd == null || datumTijd.isEmpty()) { return null; } return ZonedDateTime.parse(datumTijd, DateTimeFormatter.ISO_DATE_TIME).withZoneSameInstant(ZoneId.of(DatumUtil.UTC)); } /** * Converteert een xsd-datum naar een {@link java.util.Date}. * @param datumTijd datumTijd * @return date */ public static Date vanXsdDatumTijdNaarDate(final String datumTijd) { final ZonedDateTime zonedDateTime = ZonedDateTime.parse(datumTijd, DateTimeFormatter.ISO_DATE_TIME).withZoneSameInstant(ZoneId.of(DatumUtil.UTC)); final LocalDateTime toLocalDateTime = zonedDateTime.toLocalDateTime(); return Date.from(toLocalDateTime.atZone(ZoneId.of(DatumUtil.UTC)).toInstant()); } /** * Controleert of (onbekende)datum groter of gelijk is aan (onbekende)peildatum, bij onbekende datums wordt uit gegaan van minimale datums * (20160000 -> 20160101) * @param datum te controleren datum. * @param peildatum datum waarmee vergeleken wordt. * @return true indien datum >= peildatum. */ public static boolean vergelijkOnbekendeDatumsGroterOfGelijkAan(final Integer datum, final Integer peildatum) { return bepaalEindDatumStrengOfBeginDatumSoepel(datum, false) >= bepaalEindDatumStrengOfBeginDatumSoepel(peildatum, false); } private static Integer bepaalEindDatumStrengOfBeginDatumSoepel(final Integer datum, final boolean isEindDatum) { Integer resultaat = datum; if (datum == null || datum == 0) { resultaat = isEindDatum ? MAXIMALE_DATUM : MINIMALE_DATUM; } else if (datum % MOD_MAAND == 0) { resultaat += MINIMALE_MAAND; } else if (datum % MOD_DAG == 0) { resultaat += 1; } return resultaat; } private static Integer bepaalBeginDatumStrengOfEindDatumSoepel(final Integer datum, final boolean isBeginDatum) { Integer resultaat = datum; if (datum == null || datum == 0) { resultaat = isBeginDatum ? MINIMALE_DATUM : MAXIMALE_DATUM; } else if (datum % MOD_MAAND == 0) { resultaat += MAXIMALE_MAAND; } else if (datum % MOD_DAG == 0) { resultaat += haalLaatsteDagVanDeMaandOp(datum); } return resultaat; } private static Integer bepaalEindDatumSoepel(final Integer datum) { Integer resultaat = datum; if (datum == null || datum == 0) { resultaat = MAXIMALE_DATUM; } else if (datum % MOD_MAAND == 0) { resultaat += MAXIMALE_MAAND; } else if (datum % MOD_DAG == 0) { resultaat += haalLaatsteDagVanDeMaandOp(datum); } return resultaat; } }
127176_1
package eu.aria.dm.decision; import eu.aria.dm.moves.Move; /** * Created by WaterschootJB on 28-5-2017. */ public class MoveSelecter { private Move relevantMove; public MoveSelecter(){ // Moet checktemplates aanroepen op een subtree van de move, waarbij // Must check templates invoking a subtree of the move. } public boolean hasRelevantMove() { return false; } public Move getRelevantMove() { return relevantMove; } }
DFazekas/AVP
Agent-Core-Final/src/main/java/eu/aria/dm/decision/MoveSelecter.java
152
// Moet checktemplates aanroepen op een subtree van de move, waarbij
line_comment
nl
package eu.aria.dm.decision; import eu.aria.dm.moves.Move; /** * Created by WaterschootJB on 28-5-2017. */ public class MoveSelecter { private Move relevantMove; public MoveSelecter(){ // Moet checktemplates<SUF> // Must check templates invoking a subtree of the move. } public boolean hasRelevantMove() { return false; } public Move getRelevantMove() { return relevantMove; } }
75437_28
/******************************************************************************* * BusinessHorizon2 * * Copyright (C) * 2012-2013 Christian Gahlert, Florian Stier, Kai Westerholz, * Timo Belz, Daniel Dengler, Katharina Huber, Christian Scherer, Julius Hacker * 2013-2014 Marcel Rosenberger, Mirko Göpfrich, Annika Weis, Katharina Narlock, * Volker Meier * * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package dhbw.ka.mwi.businesshorizon2.models; import java.io.Serializable; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.NavigableSet; import java.util.SortedSet; import java.util.TreeSet; import org.apache.log4j.Logger; import com.vaadin.ui.Label; import dhbw.ka.mwi.businesshorizon2.methods.AbstractDeterministicMethod; import dhbw.ka.mwi.businesshorizon2.methods.AbstractStochasticMethod; import dhbw.ka.mwi.businesshorizon2.methods.discountedCashflow.APV; import dhbw.ka.mwi.businesshorizon2.models.Period.Period; import dhbw.ka.mwi.businesshorizon2.models.PeriodContainer.AbstractPeriodContainer; import dhbw.ka.mwi.businesshorizon2.models.PeriodContainer.CashFlowPeriodContainer; import dhbw.ka.mwi.businesshorizon2.services.persistence.ProjectAlreadyExistsException; /** * Bei dieser Klasse handelt es sich um eine Art Container-Objekt. Dieses Objekt * wird via Spring einmal pro Session erstellt und bleibt somit bestehen. Sollte * z.B. vorher gespeicherte Daten geladen werden, dann muessen diese an dieses * Objekt uebergeben werden (d.h. es ist nicht moeglich, dieses Objekt zu * ersetzen). * * @author Christian Gahlert * */ public class Project implements Serializable { /** * */ private static final long serialVersionUID = 9199799755347070847L; private static final Logger logger = Logger .getLogger("Project.class"); protected TreeSet<? extends Period> periods = new TreeSet<>(); private Date lastChanged; private User createdFrom; private String name; private String typ; private String description; private AbstractPeriodContainer stochasticPeriods, deterministicPeriods; public AbstractPeriodContainer getStochasticPeriods() { return stochasticPeriods; } public void setStochasticPeriods(AbstractPeriodContainer stochasticPeriods) { this.stochasticPeriods = stochasticPeriods; } public AbstractPeriodContainer getDeterministicPeriods() { return deterministicPeriods; } public void setDeterministicPeriods(AbstractPeriodContainer deterministicPeriods) { this.deterministicPeriods = deterministicPeriods; } private double CashFlowProbabilityOfRise; private double CashFlowStepRange; private double BorrowedCapitalProbabilityOfRise; private double BorrowedCapitalStepRange; private int periodsToForecast; private int periodsToForecast_deterministic;//Annika Weis private int specifiedPastPeriods; private int relevantPastPeriods; private int iterations; private int basisYear; private ProjectInputType projectInputType; private SortedSet<AbstractStochasticMethod> methods; /** * Die AbstractStochasticMethod wird benötigt um die zukünftigen CashFlows zu simulieren * Die AbstractDeterministicMethod wird benötigt, um an Hand von zukünftigen Cashflows den Unternehmenswert zu berechnen, * egal ob die CashFlows deterministisch eingegeben werden oder vorher mit der AbstractStochasticMethod berechnet wurden. */ private AbstractStochasticMethod stoMethod; private AbstractDeterministicMethod calcMethod; //Annika Weis private SortedSet<AbstractDeterministicMethod> methods_deterministic; protected List<Szenario> scenarios = new ArrayList<Szenario>(); private double companyValue; /** * Konstruktor des Projekts, mit dessen der Name gesetzt wird. * Außerdem werden analog zum Fachkonzept die Default-Werte der Parameter gesetzt. * * @author Christian Scherer, Marcel Rosenberger * @param Der * Name des Projekts */ public Project(String name, String description) { this.name = name; this.setDescription(description); this.projectInputType = new ProjectInputType(); this.iterations = 10000; this.specifiedPastPeriods = 6; this.relevantPastPeriods = 5; this.periodsToForecast = 3; this.periodsToForecast_deterministic = 3; //Default Wert Berechnungsmethode (APV, weil oben in der RadioButton-Liste im UI) this.setCalculationMethod(new APV()); //Default Wert Eingabemethode (FCF, weil oben in der RadioButton-Liste im UI) this.setStochasticPeriods(new CashFlowPeriodContainer()); } /** * Standardkonstruktor des Projekt * * @author Christian Scherer */ public Project() { this.projectInputType = new ProjectInputType(); } /** * Gibt die Erhöhungswahrscheinlichkeit des CashFlows zurueck. * * @author Kai Westerholz * @return */ public double getCashFlowProbabilityOfRise() { return CashFlowProbabilityOfRise; } /** * Setzt die Erhöhungswahrscheinlichkeit des CashFlows. * * @author Kai Westerholz * @param cashFlowProbabilityOfRise */ public void setCashFlowProbabilityOfRise(double cashFlowProbabilityOfRise) { CashFlowProbabilityOfRise = cashFlowProbabilityOfRise; } /** * Gibt die Schrittweise des CashFlows zurueck. * * @author Kai Westerholz * @return */ public double getCashFlowStepRange() { return CashFlowStepRange; } /** * Setzt die Schrittweise vom CashFlow. * * @author Kai Westerholz * @param cashFlowStepRange */ public void setCashFlowStepRange(double cashFlowStepRange) { CashFlowStepRange = cashFlowStepRange; } /** * Gibt die Erhöhungswahrscheinlichkeit des CashFlows zurueck. * * @author Kai Westerholz * @return Erhöhungswahrscheinlichkeit CashFlow */ public double getBorrowedCapitalProbabilityOfRise() { return BorrowedCapitalProbabilityOfRise; } /** * Setzt die Wahrscheinlichkeit der Erhoehung des Fremdkapitals. * * @author Kai Westerholz * * @param borrowedCapitalProbabilityOfRise */ public void setBorrowedCapitalProbabilityOfRise(double borrowedCapitalProbabilityOfRise) { BorrowedCapitalProbabilityOfRise = borrowedCapitalProbabilityOfRise; } /** * Gibt die Schrittweite des Fremdkapitals an. * * @author Kai Westerholz * * @return Schrittweite */ public double getBorrowedCapitalStepRange() { return BorrowedCapitalStepRange; } /** * Setzt die Schrittweite des Fremdkapitals. * * @author Kai Westerholz * @param borrowedCapitalStepRange */ public void setBorrowedCapitalStepRange(double borrowedCapitalStepRange) { BorrowedCapitalStepRange = borrowedCapitalStepRange; } /** * Gibt die Perioden in einem sortierten NavigableSet zurueck. * * @author Christian Gahlert * @return Die Perioden */ public NavigableSet<? extends Period> getPeriods() { return periods; } /** * @deprecated Bitte getter für die stochastiPeriods und DeterministicPeriods * verwenden Ueberschreibt die bisher verwendeten Methoden. Die * Perioden muessen in Form eines sortierten NavigableSet * vorliegen. * * @param periods * Die Perioden */ @Deprecated public void setPeriods(TreeSet<? extends Period> periods) { this.periods = periods; } /** * Diese Methode soll lediglich eine Liste von verfuegbaren Jahren * zurueckgeben. Ein Jahr ist verfuegbar, wenn noch keine Periode fuer das * Jahr existiert. Es wird beim aktuellen Jahr begonnen und dann * schrittweise ein Jahr runtergezaehlt. Dabei sollte z.B. nach 10 oder 20 * Jahren schluss sein (mehr Jahre wird wohl niemand eingeben wollen). * * @author Christian Gahlert * @return Die verfuegbaren Jahre absteigend sortiert */ public List<Integer> getAvailableYears() { ArrayList<Integer> years = new ArrayList<Integer>(); int start = Calendar.getInstance().get(Calendar.YEAR); boolean contains; for (int i = start; i > start - 5; i--) { contains = false; for (Period period : periods) { if (period.getYear() == i) { contains = true; break; } } if (!contains) { years.add(i); } } return years; } /** * Liesst das Datum der letzten Bearbeitung aus. Wird benötigt für die * Anwenderinformation auf dem Auswahl-screen für Projekte. * * @author Christian Scherer * @return Datum der letzten Aenderung */ public Date getLastChanged() { return lastChanged; } /** * Wird aufgerufen, wenn Aenderungen am Projekt vorgenommen wurden und * aktualisiert dann das bisherige Aenderungsdatum. * * @author Christian Scherer * @param heutiges * Datum (Aenderungszeitpunkt) */ public void setLastChanged(Date lastChanged) { this.lastChanged = lastChanged; } /** * Gibt den Namen des Projekts zurück. * * @author Christian Scherer * @return Name des Projekts */ public String getName() { return name; } public void setMethods(SortedSet<AbstractStochasticMethod> methods) { this.methods = methods; } public SortedSet<AbstractStochasticMethod> getMethods() { return methods; } //Annika Weis public void setMethods_deterministic(SortedSet<AbstractDeterministicMethod> methods_deterministic) { this.methods_deterministic = methods_deterministic; } //Annika Weis public SortedSet<AbstractDeterministicMethod> getMethods_deterministic() { return methods_deterministic; } public void setStochasticMethod(AbstractStochasticMethod method){ this.stoMethod = method; } public AbstractStochasticMethod getStochasticMethod(){ return this.stoMethod; } public void setCalculationMethod(AbstractDeterministicMethod method){ this.calcMethod = method; } public AbstractDeterministicMethod getCalculationMethod(){ return this.calcMethod; } public ProjectInputType getProjectInputType() { return projectInputType; } public void setProjectInputType(ProjectInputType projectInputType) { this.projectInputType = projectInputType; } /** * Setzt den Namen des Projekts. * * @author Christian Scherer * @param name * Name des Projekts */ public void setName(String name) { this.name = name; } /** * Gibt die Anzahl vorherzusagender Perioden des Projekts zurück. * * @author Christian Scherer * @return Anzahl vorherzusagender Perioden */ public int getPeriodsToForecast() { return periodsToForecast; } /** * Setzt die Anzahl vorherzusagender Perioden des Projekts. * * @author Christian Scherer * @param periodsToForecast * Anzahl vorherzusagender Perioden */ public void setPeriodsToForecast(int periodsToForecast) { this.periodsToForecast = periodsToForecast; } /** * Gibt die Anzahl vorherzusagender deterinistischer Perioden des Projekts zurück. * * @author Annika Weis * @return Anzahl vorherzusagender Perioden */ public int getPeriodsToForecast_deterministic() { return periodsToForecast_deterministic; } /** * Setzt die Anzahl vorherzusagender deterministischer Perioden des Projekts. * * @author Annika Weis * @param periodsToForecast_deterministic * Anzahl vorherzusagender Perioden (deterministisch) */ public void setPeriodsToForecast_deterministic(int periodsToForecast_deterministic) { if(this.getDeterministicPeriods() != null){ if(this.getDeterministicPeriods().getPeriods() != null){ this.periodsToForecast_deterministic = periodsToForecast_deterministic; logger.debug("Perioden Soll: "+periodsToForecast_deterministic+", Perioden Ist: "+this.getDeterministicPeriods().getPeriods().size()); if(this.getDeterministicPeriods().getPeriods().size() > (periodsToForecast_deterministic)){ int size = this.getDeterministicPeriods().getPeriods().size(); TreeSet<Period> _periods = (TreeSet<Period>)this.deterministicPeriods.getPeriods(); for(int i = size; i > periodsToForecast_deterministic; i--){ logger.debug("Periode gelöscht"); logger.debug(""+_periods.last().getYear()); _periods.remove(_periods.last()); } this.deterministicPeriods.setPeriods(_periods); } } } } /** * Setzt die Anzahl der anzugebenden vergangenen Perioden des Projekts. * * @author Marcel Rosenberger * @param specifiedPastPeriods * Anzahl der anzugebenden vergangenen Perioden */ public void setSpecifiedPastPeriods(int specifiedPastPeriods) { this.specifiedPastPeriods = specifiedPastPeriods; } /** * Gibt die Anzahl der anzugebenden vergangenen Perioden des Projekts zurück. * * @author Marcel Rosenberger * @return Anzahl der anzugebenden vergangenen Perioden */ public int getSpecifiedPastPeriods() { return specifiedPastPeriods; } /** * Setzt die Anzahl der vergangenen relevanten Perioden des Projekts. * * @author Christian Scherer * @param relevantPastPeriods * Anzahl der vergangenen relevanten Perioden */ public void setRelevantPastPeriods(int relevantPastPeriods) { if(this.getStochasticPeriods() != null){ if(this.getStochasticPeriods().getPeriods() != null){ this.relevantPastPeriods = relevantPastPeriods; if(this.getStochasticPeriods().getPeriods().size() > (relevantPastPeriods + 1)){ int size = this.getStochasticPeriods().getPeriods().size(); TreeSet<Period> _periods = (TreeSet<Period>) this.stochasticPeriods.getPeriods(); for(int i = size; i > (relevantPastPeriods + 1); i--){ _periods.remove(_periods.first()); } this.stochasticPeriods.setPeriods(_periods); } } } } /** * Gibt die Anzahl der vergangenen relevanten Perioden des Projekts zurück. * * @author Christian Scherer * @return Anzahl der vergangenen relevanten Perioden */ public int getRelevantPastPeriods() { return relevantPastPeriods; } /** * Gibt die Anzahl der Wiederholungen fuer die Zeitreihenanalyse des * Projekts zurück. * * @author Christian Scherer * @return Anzahl der Wiederholungen fuer die Zeitreihenanalyse */ public int getIterations() { return iterations; } /** * Setzt die Anzahl der Wiederholungen fuer die Zeitreihenanalyse des * Projekts. * * @author Christian Scherer * @param iterations * Anzahl der Wiederholungen fuer die Zeitreihenanalyse */ public void setIterations(int iterations) { this.iterations = iterations; } /** * Setzt Basis-Jahr des Projekts auf das die Cashflows abgezinst werden * muessen. * * @author Christian Scherer * @param basisYear * Basis-Jahr des Projekts auf das die Cashflows abgezinst werden * muessen */ public void setBasisYear(int basisYear) { this.basisYear = basisYear; } /** * Gibt Basis-Jahr des Projekts auf das die Cashflows abgezinst werden * muessen zurück. * * @author Christian Scherer * @return Basis-Jahr des Projekts auf das die Cashflows abgezinst werden * muessen */ public int getBasisYear() { return basisYear; } public List<Szenario> getScenarios() { return this.scenarios; } /** * Gibt nur die einbezogenen Szenarios eines Projektes zurück. * * @author Marcel Rosenberger * * @return alle einbezogenen Szenarios */ public List<Szenario> getIncludedScenarios() { List<Szenario> includedScenarios = new ArrayList<Szenario>(); for (Szenario szenario : this.scenarios){ if(szenario.isIncludeInCalculation()){ includedScenarios.add(szenario); } } return includedScenarios; } public void addScenario(Szenario scenario) { this.scenarios.add(scenario); } public User getCreatedFrom() { return createdFrom; } public void setCreatedFrom(User user) { createdFrom = user; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } public int getTotalPeriods (){ if (projectInputType.isDeterministic()==true){ return periodsToForecast_deterministic; } return specifiedPastPeriods ; } public String getTypMethod(){ if (projectInputType.isDeterministic()==true){ typ = "Deterministische Eingabe"; } else { typ = "Stochastische Eingabe"; } return typ; } public void setCompanyValue(double value){ this.companyValue = value; } public double getCompanyValue(){ return this.companyValue; } }
DHBW-Karlsruhe/businesshorizon2
businesshorizon2/src/main/java/dhbw/ka/mwi/businesshorizon2/models/Project.java
5,671
/** * Setzt die Anzahl der vergangenen relevanten Perioden des Projekts. * * @author Christian Scherer * @param relevantPastPeriods * Anzahl der vergangenen relevanten Perioden */
block_comment
nl
/******************************************************************************* * BusinessHorizon2 * * Copyright (C) * 2012-2013 Christian Gahlert, Florian Stier, Kai Westerholz, * Timo Belz, Daniel Dengler, Katharina Huber, Christian Scherer, Julius Hacker * 2013-2014 Marcel Rosenberger, Mirko Göpfrich, Annika Weis, Katharina Narlock, * Volker Meier * * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package dhbw.ka.mwi.businesshorizon2.models; import java.io.Serializable; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.NavigableSet; import java.util.SortedSet; import java.util.TreeSet; import org.apache.log4j.Logger; import com.vaadin.ui.Label; import dhbw.ka.mwi.businesshorizon2.methods.AbstractDeterministicMethod; import dhbw.ka.mwi.businesshorizon2.methods.AbstractStochasticMethod; import dhbw.ka.mwi.businesshorizon2.methods.discountedCashflow.APV; import dhbw.ka.mwi.businesshorizon2.models.Period.Period; import dhbw.ka.mwi.businesshorizon2.models.PeriodContainer.AbstractPeriodContainer; import dhbw.ka.mwi.businesshorizon2.models.PeriodContainer.CashFlowPeriodContainer; import dhbw.ka.mwi.businesshorizon2.services.persistence.ProjectAlreadyExistsException; /** * Bei dieser Klasse handelt es sich um eine Art Container-Objekt. Dieses Objekt * wird via Spring einmal pro Session erstellt und bleibt somit bestehen. Sollte * z.B. vorher gespeicherte Daten geladen werden, dann muessen diese an dieses * Objekt uebergeben werden (d.h. es ist nicht moeglich, dieses Objekt zu * ersetzen). * * @author Christian Gahlert * */ public class Project implements Serializable { /** * */ private static final long serialVersionUID = 9199799755347070847L; private static final Logger logger = Logger .getLogger("Project.class"); protected TreeSet<? extends Period> periods = new TreeSet<>(); private Date lastChanged; private User createdFrom; private String name; private String typ; private String description; private AbstractPeriodContainer stochasticPeriods, deterministicPeriods; public AbstractPeriodContainer getStochasticPeriods() { return stochasticPeriods; } public void setStochasticPeriods(AbstractPeriodContainer stochasticPeriods) { this.stochasticPeriods = stochasticPeriods; } public AbstractPeriodContainer getDeterministicPeriods() { return deterministicPeriods; } public void setDeterministicPeriods(AbstractPeriodContainer deterministicPeriods) { this.deterministicPeriods = deterministicPeriods; } private double CashFlowProbabilityOfRise; private double CashFlowStepRange; private double BorrowedCapitalProbabilityOfRise; private double BorrowedCapitalStepRange; private int periodsToForecast; private int periodsToForecast_deterministic;//Annika Weis private int specifiedPastPeriods; private int relevantPastPeriods; private int iterations; private int basisYear; private ProjectInputType projectInputType; private SortedSet<AbstractStochasticMethod> methods; /** * Die AbstractStochasticMethod wird benötigt um die zukünftigen CashFlows zu simulieren * Die AbstractDeterministicMethod wird benötigt, um an Hand von zukünftigen Cashflows den Unternehmenswert zu berechnen, * egal ob die CashFlows deterministisch eingegeben werden oder vorher mit der AbstractStochasticMethod berechnet wurden. */ private AbstractStochasticMethod stoMethod; private AbstractDeterministicMethod calcMethod; //Annika Weis private SortedSet<AbstractDeterministicMethod> methods_deterministic; protected List<Szenario> scenarios = new ArrayList<Szenario>(); private double companyValue; /** * Konstruktor des Projekts, mit dessen der Name gesetzt wird. * Außerdem werden analog zum Fachkonzept die Default-Werte der Parameter gesetzt. * * @author Christian Scherer, Marcel Rosenberger * @param Der * Name des Projekts */ public Project(String name, String description) { this.name = name; this.setDescription(description); this.projectInputType = new ProjectInputType(); this.iterations = 10000; this.specifiedPastPeriods = 6; this.relevantPastPeriods = 5; this.periodsToForecast = 3; this.periodsToForecast_deterministic = 3; //Default Wert Berechnungsmethode (APV, weil oben in der RadioButton-Liste im UI) this.setCalculationMethod(new APV()); //Default Wert Eingabemethode (FCF, weil oben in der RadioButton-Liste im UI) this.setStochasticPeriods(new CashFlowPeriodContainer()); } /** * Standardkonstruktor des Projekt * * @author Christian Scherer */ public Project() { this.projectInputType = new ProjectInputType(); } /** * Gibt die Erhöhungswahrscheinlichkeit des CashFlows zurueck. * * @author Kai Westerholz * @return */ public double getCashFlowProbabilityOfRise() { return CashFlowProbabilityOfRise; } /** * Setzt die Erhöhungswahrscheinlichkeit des CashFlows. * * @author Kai Westerholz * @param cashFlowProbabilityOfRise */ public void setCashFlowProbabilityOfRise(double cashFlowProbabilityOfRise) { CashFlowProbabilityOfRise = cashFlowProbabilityOfRise; } /** * Gibt die Schrittweise des CashFlows zurueck. * * @author Kai Westerholz * @return */ public double getCashFlowStepRange() { return CashFlowStepRange; } /** * Setzt die Schrittweise vom CashFlow. * * @author Kai Westerholz * @param cashFlowStepRange */ public void setCashFlowStepRange(double cashFlowStepRange) { CashFlowStepRange = cashFlowStepRange; } /** * Gibt die Erhöhungswahrscheinlichkeit des CashFlows zurueck. * * @author Kai Westerholz * @return Erhöhungswahrscheinlichkeit CashFlow */ public double getBorrowedCapitalProbabilityOfRise() { return BorrowedCapitalProbabilityOfRise; } /** * Setzt die Wahrscheinlichkeit der Erhoehung des Fremdkapitals. * * @author Kai Westerholz * * @param borrowedCapitalProbabilityOfRise */ public void setBorrowedCapitalProbabilityOfRise(double borrowedCapitalProbabilityOfRise) { BorrowedCapitalProbabilityOfRise = borrowedCapitalProbabilityOfRise; } /** * Gibt die Schrittweite des Fremdkapitals an. * * @author Kai Westerholz * * @return Schrittweite */ public double getBorrowedCapitalStepRange() { return BorrowedCapitalStepRange; } /** * Setzt die Schrittweite des Fremdkapitals. * * @author Kai Westerholz * @param borrowedCapitalStepRange */ public void setBorrowedCapitalStepRange(double borrowedCapitalStepRange) { BorrowedCapitalStepRange = borrowedCapitalStepRange; } /** * Gibt die Perioden in einem sortierten NavigableSet zurueck. * * @author Christian Gahlert * @return Die Perioden */ public NavigableSet<? extends Period> getPeriods() { return periods; } /** * @deprecated Bitte getter für die stochastiPeriods und DeterministicPeriods * verwenden Ueberschreibt die bisher verwendeten Methoden. Die * Perioden muessen in Form eines sortierten NavigableSet * vorliegen. * * @param periods * Die Perioden */ @Deprecated public void setPeriods(TreeSet<? extends Period> periods) { this.periods = periods; } /** * Diese Methode soll lediglich eine Liste von verfuegbaren Jahren * zurueckgeben. Ein Jahr ist verfuegbar, wenn noch keine Periode fuer das * Jahr existiert. Es wird beim aktuellen Jahr begonnen und dann * schrittweise ein Jahr runtergezaehlt. Dabei sollte z.B. nach 10 oder 20 * Jahren schluss sein (mehr Jahre wird wohl niemand eingeben wollen). * * @author Christian Gahlert * @return Die verfuegbaren Jahre absteigend sortiert */ public List<Integer> getAvailableYears() { ArrayList<Integer> years = new ArrayList<Integer>(); int start = Calendar.getInstance().get(Calendar.YEAR); boolean contains; for (int i = start; i > start - 5; i--) { contains = false; for (Period period : periods) { if (period.getYear() == i) { contains = true; break; } } if (!contains) { years.add(i); } } return years; } /** * Liesst das Datum der letzten Bearbeitung aus. Wird benötigt für die * Anwenderinformation auf dem Auswahl-screen für Projekte. * * @author Christian Scherer * @return Datum der letzten Aenderung */ public Date getLastChanged() { return lastChanged; } /** * Wird aufgerufen, wenn Aenderungen am Projekt vorgenommen wurden und * aktualisiert dann das bisherige Aenderungsdatum. * * @author Christian Scherer * @param heutiges * Datum (Aenderungszeitpunkt) */ public void setLastChanged(Date lastChanged) { this.lastChanged = lastChanged; } /** * Gibt den Namen des Projekts zurück. * * @author Christian Scherer * @return Name des Projekts */ public String getName() { return name; } public void setMethods(SortedSet<AbstractStochasticMethod> methods) { this.methods = methods; } public SortedSet<AbstractStochasticMethod> getMethods() { return methods; } //Annika Weis public void setMethods_deterministic(SortedSet<AbstractDeterministicMethod> methods_deterministic) { this.methods_deterministic = methods_deterministic; } //Annika Weis public SortedSet<AbstractDeterministicMethod> getMethods_deterministic() { return methods_deterministic; } public void setStochasticMethod(AbstractStochasticMethod method){ this.stoMethod = method; } public AbstractStochasticMethod getStochasticMethod(){ return this.stoMethod; } public void setCalculationMethod(AbstractDeterministicMethod method){ this.calcMethod = method; } public AbstractDeterministicMethod getCalculationMethod(){ return this.calcMethod; } public ProjectInputType getProjectInputType() { return projectInputType; } public void setProjectInputType(ProjectInputType projectInputType) { this.projectInputType = projectInputType; } /** * Setzt den Namen des Projekts. * * @author Christian Scherer * @param name * Name des Projekts */ public void setName(String name) { this.name = name; } /** * Gibt die Anzahl vorherzusagender Perioden des Projekts zurück. * * @author Christian Scherer * @return Anzahl vorherzusagender Perioden */ public int getPeriodsToForecast() { return periodsToForecast; } /** * Setzt die Anzahl vorherzusagender Perioden des Projekts. * * @author Christian Scherer * @param periodsToForecast * Anzahl vorherzusagender Perioden */ public void setPeriodsToForecast(int periodsToForecast) { this.periodsToForecast = periodsToForecast; } /** * Gibt die Anzahl vorherzusagender deterinistischer Perioden des Projekts zurück. * * @author Annika Weis * @return Anzahl vorherzusagender Perioden */ public int getPeriodsToForecast_deterministic() { return periodsToForecast_deterministic; } /** * Setzt die Anzahl vorherzusagender deterministischer Perioden des Projekts. * * @author Annika Weis * @param periodsToForecast_deterministic * Anzahl vorherzusagender Perioden (deterministisch) */ public void setPeriodsToForecast_deterministic(int periodsToForecast_deterministic) { if(this.getDeterministicPeriods() != null){ if(this.getDeterministicPeriods().getPeriods() != null){ this.periodsToForecast_deterministic = periodsToForecast_deterministic; logger.debug("Perioden Soll: "+periodsToForecast_deterministic+", Perioden Ist: "+this.getDeterministicPeriods().getPeriods().size()); if(this.getDeterministicPeriods().getPeriods().size() > (periodsToForecast_deterministic)){ int size = this.getDeterministicPeriods().getPeriods().size(); TreeSet<Period> _periods = (TreeSet<Period>)this.deterministicPeriods.getPeriods(); for(int i = size; i > periodsToForecast_deterministic; i--){ logger.debug("Periode gelöscht"); logger.debug(""+_periods.last().getYear()); _periods.remove(_periods.last()); } this.deterministicPeriods.setPeriods(_periods); } } } } /** * Setzt die Anzahl der anzugebenden vergangenen Perioden des Projekts. * * @author Marcel Rosenberger * @param specifiedPastPeriods * Anzahl der anzugebenden vergangenen Perioden */ public void setSpecifiedPastPeriods(int specifiedPastPeriods) { this.specifiedPastPeriods = specifiedPastPeriods; } /** * Gibt die Anzahl der anzugebenden vergangenen Perioden des Projekts zurück. * * @author Marcel Rosenberger * @return Anzahl der anzugebenden vergangenen Perioden */ public int getSpecifiedPastPeriods() { return specifiedPastPeriods; } /** * Setzt die Anzahl<SUF>*/ public void setRelevantPastPeriods(int relevantPastPeriods) { if(this.getStochasticPeriods() != null){ if(this.getStochasticPeriods().getPeriods() != null){ this.relevantPastPeriods = relevantPastPeriods; if(this.getStochasticPeriods().getPeriods().size() > (relevantPastPeriods + 1)){ int size = this.getStochasticPeriods().getPeriods().size(); TreeSet<Period> _periods = (TreeSet<Period>) this.stochasticPeriods.getPeriods(); for(int i = size; i > (relevantPastPeriods + 1); i--){ _periods.remove(_periods.first()); } this.stochasticPeriods.setPeriods(_periods); } } } } /** * Gibt die Anzahl der vergangenen relevanten Perioden des Projekts zurück. * * @author Christian Scherer * @return Anzahl der vergangenen relevanten Perioden */ public int getRelevantPastPeriods() { return relevantPastPeriods; } /** * Gibt die Anzahl der Wiederholungen fuer die Zeitreihenanalyse des * Projekts zurück. * * @author Christian Scherer * @return Anzahl der Wiederholungen fuer die Zeitreihenanalyse */ public int getIterations() { return iterations; } /** * Setzt die Anzahl der Wiederholungen fuer die Zeitreihenanalyse des * Projekts. * * @author Christian Scherer * @param iterations * Anzahl der Wiederholungen fuer die Zeitreihenanalyse */ public void setIterations(int iterations) { this.iterations = iterations; } /** * Setzt Basis-Jahr des Projekts auf das die Cashflows abgezinst werden * muessen. * * @author Christian Scherer * @param basisYear * Basis-Jahr des Projekts auf das die Cashflows abgezinst werden * muessen */ public void setBasisYear(int basisYear) { this.basisYear = basisYear; } /** * Gibt Basis-Jahr des Projekts auf das die Cashflows abgezinst werden * muessen zurück. * * @author Christian Scherer * @return Basis-Jahr des Projekts auf das die Cashflows abgezinst werden * muessen */ public int getBasisYear() { return basisYear; } public List<Szenario> getScenarios() { return this.scenarios; } /** * Gibt nur die einbezogenen Szenarios eines Projektes zurück. * * @author Marcel Rosenberger * * @return alle einbezogenen Szenarios */ public List<Szenario> getIncludedScenarios() { List<Szenario> includedScenarios = new ArrayList<Szenario>(); for (Szenario szenario : this.scenarios){ if(szenario.isIncludeInCalculation()){ includedScenarios.add(szenario); } } return includedScenarios; } public void addScenario(Szenario scenario) { this.scenarios.add(scenario); } public User getCreatedFrom() { return createdFrom; } public void setCreatedFrom(User user) { createdFrom = user; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } public int getTotalPeriods (){ if (projectInputType.isDeterministic()==true){ return periodsToForecast_deterministic; } return specifiedPastPeriods ; } public String getTypMethod(){ if (projectInputType.isDeterministic()==true){ typ = "Deterministische Eingabe"; } else { typ = "Stochastische Eingabe"; } return typ; } public void setCompanyValue(double value){ this.companyValue = value; } public double getCompanyValue(){ return this.companyValue; } }
18319_25
/******************************************************************************* * BusinessHorizon2 * * Copyright (C) * 2012-2013 Christian Gahlert, Florian Stier, Kai Westerholz, * Timo Belz, Daniel Dengler, Katharina Huber, Christian Scherer, Julius Hacker * 2013-2014 Marcel Rosenberger, Mirko Göpfrich, Annika Weis, Katharina Narlock, * Volker Meier * * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package dhbw.ka.mwi.businesshorizon2.models; import java.io.Serializable; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.NavigableSet; import java.util.SortedSet; import java.util.TreeSet; import com.vaadin.ui.Label; import dhbw.ka.mwi.businesshorizon2.methods.AbstractDeterministicMethod; import dhbw.ka.mwi.businesshorizon2.methods.AbstractStochasticMethod; import dhbw.ka.mwi.businesshorizon2.models.Period.Period; import dhbw.ka.mwi.businesshorizon2.models.PeriodContainer.AbstractPeriodContainer; import dhbw.ka.mwi.businesshorizon2.services.persistence.ProjectAlreadyExistsException; /** * Bei dieser Klasse handelt es sich um eine Art Container-Objekt. Dieses Objekt * wird via Spring einmal pro Session erstellt und bleibt somit bestehen. Sollte * z.B. vorher gespeicherte Daten geladen werden, dann muessen diese an dieses * Objekt uebergeben werden (d.h. es ist nicht moeglich, dieses Objekt zu * ersetzen). * * @author Christian Gahlert * */ public class Project implements Serializable { /** * */ private static final long serialVersionUID = 9199799755347070847L; protected TreeSet<? extends Period> periods = new TreeSet<>(); private Date lastChanged; private User createdFrom; private String name; private String typ; private String description; private AbstractPeriodContainer stochasticPeriods, deterministicPeriods; public AbstractPeriodContainer getStochasticPeriods() { return stochasticPeriods; } public void setStochasticPeriods(AbstractPeriodContainer stochasticPeriods) { this.stochasticPeriods = stochasticPeriods; } public AbstractPeriodContainer getDeterministicPeriods() { return deterministicPeriods; } public void setDeterministicPeriods(AbstractPeriodContainer deterministicPeriods) { this.deterministicPeriods = deterministicPeriods; } private double CashFlowProbabilityOfRise; private double CashFlowStepRange; private double BorrowedCapitalProbabilityOfRise; private double BorrowedCapitalStepRange; private int periodsToForecast; private int periodsToForecast_deterministic;//Annika Weis private int specifiedPastPeriods; private int relevantPastPeriods; private int iterations; private int basisYear; private ProjectInputType projectInputType; private SortedSet<AbstractStochasticMethod> methods; //Annika Weis private SortedSet<AbstractDeterministicMethod> methods_deterministic; protected List<Szenario> scenarios = new ArrayList<Szenario>(); /** * Konstruktor des Projekts, mit dessen der Name gesetzt wird. * Außerdem werden analog zum Fachkonzept die Default-Werte der Parameter gesetzt. * * @author Christian Scherer, Marcel Rosenberger * @param Der * Name des Projekts */ public Project(String name, String description) { this.name = name; this.setDescription(description); this.projectInputType = new ProjectInputType(); this.iterations = 10000; this.specifiedPastPeriods = 6; this.relevantPastPeriods = 5; this.periodsToForecast = 3; } /** * Standardkonstruktor des Projekt * * @author Christian Scherer */ public Project() { this.projectInputType = new ProjectInputType(); } /** * Gibt die Erhöhungswahrscheinlichkeit des CashFlows zurueck. * * @author Kai Westerholz * @return */ public double getCashFlowProbabilityOfRise() { return CashFlowProbabilityOfRise; } /** * Setzt die Erhöhungswahrscheinlichkeit des CashFlows. * * @author Kai Westerholz * @param cashFlowProbabilityOfRise */ public void setCashFlowProbabilityOfRise(double cashFlowProbabilityOfRise) { CashFlowProbabilityOfRise = cashFlowProbabilityOfRise; } /** * Gibt die Schrittweise des CashFlows zurueck. * * @author Kai Westerholz * @return */ public double getCashFlowStepRange() { return CashFlowStepRange; } /** * Setzt die Schrittweise vom CashFlow. * * @author Kai Westerholz * @param cashFlowStepRange */ public void setCashFlowStepRange(double cashFlowStepRange) { CashFlowStepRange = cashFlowStepRange; } /** * Gibt die Erhöhungswahrscheinlichkeit des CashFlows zurueck. * * @author Kai Westerholz * @return Erhöhungswahrscheinlichkeit CashFlow */ public double getBorrowedCapitalProbabilityOfRise() { return BorrowedCapitalProbabilityOfRise; } /** * Setzt die Wahrscheinlichkeit der Erhoehung des Fremdkapitals. * * @author Kai Westerholz * * @param borrowedCapitalProbabilityOfRise */ public void setBorrowedCapitalProbabilityOfRise(double borrowedCapitalProbabilityOfRise) { BorrowedCapitalProbabilityOfRise = borrowedCapitalProbabilityOfRise; } /** * Gibt die Schrittweite des Fremdkapitals an. * * @author Kai Westerholz * * @return Schrittweite */ public double getBorrowedCapitalStepRange() { return BorrowedCapitalStepRange; } /** * Setzt die Schrittweite des Fremdkapitals. * * @author Kai Westerholz * @param borrowedCapitalStepRange */ public void setBorrowedCapitalStepRange(double borrowedCapitalStepRange) { BorrowedCapitalStepRange = borrowedCapitalStepRange; } /** * Gibt die Perioden in einem sortierten NavigableSet zurueck. * * @author Christian Gahlert * @return Die Perioden */ public NavigableSet<? extends Period> getPeriods() { return periods; } /** * @deprecated Bitte getter für die stochastiPeriods und DeterministicPeriods * verwenden Ueberschreibt die bisher verwendeten Methoden. Die * Perioden muessen in Form eines sortierten NavigableSet * vorliegen. * * @param periods * Die Perioden */ @Deprecated public void setPeriods(TreeSet<? extends Period> periods) { this.periods = periods; } /** * Diese Methode soll lediglich eine Liste von verfuegbaren Jahren * zurueckgeben. Ein Jahr ist verfuegbar, wenn noch keine Periode fuer das * Jahr existiert. Es wird beim aktuellen Jahr begonnen und dann * schrittweise ein Jahr runtergezaehlt. Dabei sollte z.B. nach 10 oder 20 * Jahren schluss sein (mehr Jahre wird wohl niemand eingeben wollen). * * @author Christian Gahlert * @return Die verfuegbaren Jahre absteigend sortiert */ public List<Integer> getAvailableYears() { ArrayList<Integer> years = new ArrayList<Integer>(); int start = Calendar.getInstance().get(Calendar.YEAR); boolean contains; for (int i = start; i > start - 5; i--) { contains = false; for (Period period : periods) { if (period.getYear() == i) { contains = true; break; } } if (!contains) { years.add(i); } } return years; } /** * Liesst das Datum der letzten Bearbeitung aus. Wird benötigt für die * Anwenderinformation auf dem Auswahl-screen für Projekte. * * @author Christian Scherer * @return Datum der letzten Aenderung */ public Date getLastChanged() { return lastChanged; } /** * Wird aufgerufen, wenn Aenderungen am Projekt vorgenommen wurden und * aktualisiert dann das bisherige Aenderungsdatum. * * @author Christian Scherer * @param heutiges * Datum (Aenderungszeitpunkt) */ public void setLastChanged(Date lastChanged) { this.lastChanged = lastChanged; } /** * Gibt den Namen des Projekts zurück. * * @author Christian Scherer * @return Name des Projekts */ public String getName() { return name; } public void setMethods(SortedSet<AbstractStochasticMethod> methods) { this.methods = methods; } public SortedSet<AbstractStochasticMethod> getMethods() { return methods; } //Annika Weis public void setMethods_deterministic(SortedSet<AbstractDeterministicMethod> methods_deterministic) { this.methods_deterministic = methods_deterministic; } //Annika Weis public SortedSet<AbstractDeterministicMethod> getMethods_deterministic() { return methods_deterministic; } public ProjectInputType getProjectInputType() { return projectInputType; } public void setProjectInputType(ProjectInputType projectInputType) { this.projectInputType = projectInputType; } /** * Setzt den Namen des Projekts. * * @author Christian Scherer * @param name * Name des Projekts */ public void setName(String name) { this.name = name; } /** * Gibt die Anzahl vorherzusagender Perioden des Projekts zurück. * * @author Christian Scherer * @return Anzahl vorherzusagender Perioden */ public int getPeriodsToForecast() { return periodsToForecast; } /** * Setzt die Anzahl vorherzusagender Perioden des Projekts. * * @author Christian Scherer * @param periodsToForecast * Anzahl vorherzusagender Perioden */ public void setPeriodsToForecast(int periodsToForecast) { this.periodsToForecast = periodsToForecast; } /** * Gibt die Anzahl vorherzusagender deterinistischer Perioden des Projekts zurück. * * @author Annika Weis * @return Anzahl vorherzusagender Perioden */ public int getPeriodsToForecast_deterministic() { return periodsToForecast_deterministic; } /** * Setzt die Anzahl vorherzusagender deterministischer Perioden des Projekts. * * @author Annika Weis * @param periodsToForecast_deterministic * Anzahl vorherzusagender Perioden (deterministisch) */ public void setPeriodsToForecast_deterministic(int periodsToForecast_deterministic) { this.periodsToForecast_deterministic = periodsToForecast_deterministic; } /** * Setzt die Anzahl der anzugebenden vergangenen Perioden des Projekts. * * @author Marcel Rosenberger * @param specifiedPastPeriods * Anzahl der anzugebenden vergangenen Perioden */ public void setSpecifiedPastPeriods(int specifiedPastPeriods) { this.specifiedPastPeriods = specifiedPastPeriods; } /** * Gibt die Anzahl der anzugebenden vergangenen Perioden des Projekts zurück. * * @author Marcel Rosenberger * @return Anzahl der anzugebenden vergangenen Perioden */ public int getSpecifiedPastPeriods() { return specifiedPastPeriods; } /** * Setzt die Anzahl der vergangenen relevanten Perioden des Projekts. * * @author Christian Scherer * @param relevantPastPeriods * Anzahl der vergangenen relevanten Perioden */ public void setRelevantPastPeriods(int relevantPastPeriods) { this.relevantPastPeriods = relevantPastPeriods; } /** * Gibt die Anzahl der vergangenen relevanten Perioden des Projekts zurück. * * @author Christian Scherer * @return Anzahl der vergangenen relevanten Perioden */ public int getRelevantPastPeriods() { return relevantPastPeriods; } /** * Gibt die Anzahl der Wiederholungen fuer die Zeitreihenanalyse des * Projekts zurück. * * @author Christian Scherer * @return Anzahl der Wiederholungen fuer die Zeitreihenanalyse */ public int getIterations() { return iterations; } /** * Setzt die Anzahl der Wiederholungen fuer die Zeitreihenanalyse des * Projekts. * * @author Christian Scherer * @param iterations * Anzahl der Wiederholungen fuer die Zeitreihenanalyse */ public void setIterations(int iterations) { this.iterations = iterations; } /** * Setzt Basis-Jahr des Projekts auf das die Cashflows abgezinst werden * muessen. * * @author Christian Scherer * @param basisYear * Basis-Jahr des Projekts auf das die Cashflows abgezinst werden * muessen */ public void setBasisYear(int basisYear) { this.basisYear = basisYear; } /** * Gibt Basis-Jahr des Projekts auf das die Cashflows abgezinst werden * muessen zurück. * * @author Christian Scherer * @return Basis-Jahr des Projekts auf das die Cashflows abgezinst werden * muessen */ public int getBasisYear() { return basisYear; } public List<Szenario> getScenarios() { return this.scenarios; } /** * Gibt nur die einbezogenen Szenarios eines Projektes zurück. * * @author Marcel Rosenberger * * @return alle einbezogenen Szenarios */ public List<Szenario> getIncludedScenarios() { List<Szenario> includedScenarios = new ArrayList<Szenario>(); for (Szenario szenario : this.scenarios){ if(szenario.isIncludeInCalculation()){ includedScenarios.add(szenario); } } return includedScenarios; } public void addScenario(Szenario scenario) { this.scenarios.add(scenario); } public User getCreatedFrom() { return createdFrom; } public void setCreatedFrom(User user) { createdFrom = user; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } public int getTotalPeriods (){ if (projectInputType.isDeterministic()==true){ return periodsToForecast_deterministic; } return specifiedPastPeriods ; } public String getTypMethod(){ if (projectInputType.isDeterministic()==true){ typ = "Deterministische Eingabe"; } else { typ = "Stochastische Eingabe"; } return typ; } }
DHBW-Karlsruhe/businesshorizon2_old
src/main/java/dhbw/ka/mwi/businesshorizon2/models/Project.java
4,720
/** * Setzt die Anzahl der vergangenen relevanten Perioden des Projekts. * * @author Christian Scherer * @param relevantPastPeriods * Anzahl der vergangenen relevanten Perioden */
block_comment
nl
/******************************************************************************* * BusinessHorizon2 * * Copyright (C) * 2012-2013 Christian Gahlert, Florian Stier, Kai Westerholz, * Timo Belz, Daniel Dengler, Katharina Huber, Christian Scherer, Julius Hacker * 2013-2014 Marcel Rosenberger, Mirko Göpfrich, Annika Weis, Katharina Narlock, * Volker Meier * * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package dhbw.ka.mwi.businesshorizon2.models; import java.io.Serializable; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.NavigableSet; import java.util.SortedSet; import java.util.TreeSet; import com.vaadin.ui.Label; import dhbw.ka.mwi.businesshorizon2.methods.AbstractDeterministicMethod; import dhbw.ka.mwi.businesshorizon2.methods.AbstractStochasticMethod; import dhbw.ka.mwi.businesshorizon2.models.Period.Period; import dhbw.ka.mwi.businesshorizon2.models.PeriodContainer.AbstractPeriodContainer; import dhbw.ka.mwi.businesshorizon2.services.persistence.ProjectAlreadyExistsException; /** * Bei dieser Klasse handelt es sich um eine Art Container-Objekt. Dieses Objekt * wird via Spring einmal pro Session erstellt und bleibt somit bestehen. Sollte * z.B. vorher gespeicherte Daten geladen werden, dann muessen diese an dieses * Objekt uebergeben werden (d.h. es ist nicht moeglich, dieses Objekt zu * ersetzen). * * @author Christian Gahlert * */ public class Project implements Serializable { /** * */ private static final long serialVersionUID = 9199799755347070847L; protected TreeSet<? extends Period> periods = new TreeSet<>(); private Date lastChanged; private User createdFrom; private String name; private String typ; private String description; private AbstractPeriodContainer stochasticPeriods, deterministicPeriods; public AbstractPeriodContainer getStochasticPeriods() { return stochasticPeriods; } public void setStochasticPeriods(AbstractPeriodContainer stochasticPeriods) { this.stochasticPeriods = stochasticPeriods; } public AbstractPeriodContainer getDeterministicPeriods() { return deterministicPeriods; } public void setDeterministicPeriods(AbstractPeriodContainer deterministicPeriods) { this.deterministicPeriods = deterministicPeriods; } private double CashFlowProbabilityOfRise; private double CashFlowStepRange; private double BorrowedCapitalProbabilityOfRise; private double BorrowedCapitalStepRange; private int periodsToForecast; private int periodsToForecast_deterministic;//Annika Weis private int specifiedPastPeriods; private int relevantPastPeriods; private int iterations; private int basisYear; private ProjectInputType projectInputType; private SortedSet<AbstractStochasticMethod> methods; //Annika Weis private SortedSet<AbstractDeterministicMethod> methods_deterministic; protected List<Szenario> scenarios = new ArrayList<Szenario>(); /** * Konstruktor des Projekts, mit dessen der Name gesetzt wird. * Außerdem werden analog zum Fachkonzept die Default-Werte der Parameter gesetzt. * * @author Christian Scherer, Marcel Rosenberger * @param Der * Name des Projekts */ public Project(String name, String description) { this.name = name; this.setDescription(description); this.projectInputType = new ProjectInputType(); this.iterations = 10000; this.specifiedPastPeriods = 6; this.relevantPastPeriods = 5; this.periodsToForecast = 3; } /** * Standardkonstruktor des Projekt * * @author Christian Scherer */ public Project() { this.projectInputType = new ProjectInputType(); } /** * Gibt die Erhöhungswahrscheinlichkeit des CashFlows zurueck. * * @author Kai Westerholz * @return */ public double getCashFlowProbabilityOfRise() { return CashFlowProbabilityOfRise; } /** * Setzt die Erhöhungswahrscheinlichkeit des CashFlows. * * @author Kai Westerholz * @param cashFlowProbabilityOfRise */ public void setCashFlowProbabilityOfRise(double cashFlowProbabilityOfRise) { CashFlowProbabilityOfRise = cashFlowProbabilityOfRise; } /** * Gibt die Schrittweise des CashFlows zurueck. * * @author Kai Westerholz * @return */ public double getCashFlowStepRange() { return CashFlowStepRange; } /** * Setzt die Schrittweise vom CashFlow. * * @author Kai Westerholz * @param cashFlowStepRange */ public void setCashFlowStepRange(double cashFlowStepRange) { CashFlowStepRange = cashFlowStepRange; } /** * Gibt die Erhöhungswahrscheinlichkeit des CashFlows zurueck. * * @author Kai Westerholz * @return Erhöhungswahrscheinlichkeit CashFlow */ public double getBorrowedCapitalProbabilityOfRise() { return BorrowedCapitalProbabilityOfRise; } /** * Setzt die Wahrscheinlichkeit der Erhoehung des Fremdkapitals. * * @author Kai Westerholz * * @param borrowedCapitalProbabilityOfRise */ public void setBorrowedCapitalProbabilityOfRise(double borrowedCapitalProbabilityOfRise) { BorrowedCapitalProbabilityOfRise = borrowedCapitalProbabilityOfRise; } /** * Gibt die Schrittweite des Fremdkapitals an. * * @author Kai Westerholz * * @return Schrittweite */ public double getBorrowedCapitalStepRange() { return BorrowedCapitalStepRange; } /** * Setzt die Schrittweite des Fremdkapitals. * * @author Kai Westerholz * @param borrowedCapitalStepRange */ public void setBorrowedCapitalStepRange(double borrowedCapitalStepRange) { BorrowedCapitalStepRange = borrowedCapitalStepRange; } /** * Gibt die Perioden in einem sortierten NavigableSet zurueck. * * @author Christian Gahlert * @return Die Perioden */ public NavigableSet<? extends Period> getPeriods() { return periods; } /** * @deprecated Bitte getter für die stochastiPeriods und DeterministicPeriods * verwenden Ueberschreibt die bisher verwendeten Methoden. Die * Perioden muessen in Form eines sortierten NavigableSet * vorliegen. * * @param periods * Die Perioden */ @Deprecated public void setPeriods(TreeSet<? extends Period> periods) { this.periods = periods; } /** * Diese Methode soll lediglich eine Liste von verfuegbaren Jahren * zurueckgeben. Ein Jahr ist verfuegbar, wenn noch keine Periode fuer das * Jahr existiert. Es wird beim aktuellen Jahr begonnen und dann * schrittweise ein Jahr runtergezaehlt. Dabei sollte z.B. nach 10 oder 20 * Jahren schluss sein (mehr Jahre wird wohl niemand eingeben wollen). * * @author Christian Gahlert * @return Die verfuegbaren Jahre absteigend sortiert */ public List<Integer> getAvailableYears() { ArrayList<Integer> years = new ArrayList<Integer>(); int start = Calendar.getInstance().get(Calendar.YEAR); boolean contains; for (int i = start; i > start - 5; i--) { contains = false; for (Period period : periods) { if (period.getYear() == i) { contains = true; break; } } if (!contains) { years.add(i); } } return years; } /** * Liesst das Datum der letzten Bearbeitung aus. Wird benötigt für die * Anwenderinformation auf dem Auswahl-screen für Projekte. * * @author Christian Scherer * @return Datum der letzten Aenderung */ public Date getLastChanged() { return lastChanged; } /** * Wird aufgerufen, wenn Aenderungen am Projekt vorgenommen wurden und * aktualisiert dann das bisherige Aenderungsdatum. * * @author Christian Scherer * @param heutiges * Datum (Aenderungszeitpunkt) */ public void setLastChanged(Date lastChanged) { this.lastChanged = lastChanged; } /** * Gibt den Namen des Projekts zurück. * * @author Christian Scherer * @return Name des Projekts */ public String getName() { return name; } public void setMethods(SortedSet<AbstractStochasticMethod> methods) { this.methods = methods; } public SortedSet<AbstractStochasticMethod> getMethods() { return methods; } //Annika Weis public void setMethods_deterministic(SortedSet<AbstractDeterministicMethod> methods_deterministic) { this.methods_deterministic = methods_deterministic; } //Annika Weis public SortedSet<AbstractDeterministicMethod> getMethods_deterministic() { return methods_deterministic; } public ProjectInputType getProjectInputType() { return projectInputType; } public void setProjectInputType(ProjectInputType projectInputType) { this.projectInputType = projectInputType; } /** * Setzt den Namen des Projekts. * * @author Christian Scherer * @param name * Name des Projekts */ public void setName(String name) { this.name = name; } /** * Gibt die Anzahl vorherzusagender Perioden des Projekts zurück. * * @author Christian Scherer * @return Anzahl vorherzusagender Perioden */ public int getPeriodsToForecast() { return periodsToForecast; } /** * Setzt die Anzahl vorherzusagender Perioden des Projekts. * * @author Christian Scherer * @param periodsToForecast * Anzahl vorherzusagender Perioden */ public void setPeriodsToForecast(int periodsToForecast) { this.periodsToForecast = periodsToForecast; } /** * Gibt die Anzahl vorherzusagender deterinistischer Perioden des Projekts zurück. * * @author Annika Weis * @return Anzahl vorherzusagender Perioden */ public int getPeriodsToForecast_deterministic() { return periodsToForecast_deterministic; } /** * Setzt die Anzahl vorherzusagender deterministischer Perioden des Projekts. * * @author Annika Weis * @param periodsToForecast_deterministic * Anzahl vorherzusagender Perioden (deterministisch) */ public void setPeriodsToForecast_deterministic(int periodsToForecast_deterministic) { this.periodsToForecast_deterministic = periodsToForecast_deterministic; } /** * Setzt die Anzahl der anzugebenden vergangenen Perioden des Projekts. * * @author Marcel Rosenberger * @param specifiedPastPeriods * Anzahl der anzugebenden vergangenen Perioden */ public void setSpecifiedPastPeriods(int specifiedPastPeriods) { this.specifiedPastPeriods = specifiedPastPeriods; } /** * Gibt die Anzahl der anzugebenden vergangenen Perioden des Projekts zurück. * * @author Marcel Rosenberger * @return Anzahl der anzugebenden vergangenen Perioden */ public int getSpecifiedPastPeriods() { return specifiedPastPeriods; } /** * Setzt die Anzahl<SUF>*/ public void setRelevantPastPeriods(int relevantPastPeriods) { this.relevantPastPeriods = relevantPastPeriods; } /** * Gibt die Anzahl der vergangenen relevanten Perioden des Projekts zurück. * * @author Christian Scherer * @return Anzahl der vergangenen relevanten Perioden */ public int getRelevantPastPeriods() { return relevantPastPeriods; } /** * Gibt die Anzahl der Wiederholungen fuer die Zeitreihenanalyse des * Projekts zurück. * * @author Christian Scherer * @return Anzahl der Wiederholungen fuer die Zeitreihenanalyse */ public int getIterations() { return iterations; } /** * Setzt die Anzahl der Wiederholungen fuer die Zeitreihenanalyse des * Projekts. * * @author Christian Scherer * @param iterations * Anzahl der Wiederholungen fuer die Zeitreihenanalyse */ public void setIterations(int iterations) { this.iterations = iterations; } /** * Setzt Basis-Jahr des Projekts auf das die Cashflows abgezinst werden * muessen. * * @author Christian Scherer * @param basisYear * Basis-Jahr des Projekts auf das die Cashflows abgezinst werden * muessen */ public void setBasisYear(int basisYear) { this.basisYear = basisYear; } /** * Gibt Basis-Jahr des Projekts auf das die Cashflows abgezinst werden * muessen zurück. * * @author Christian Scherer * @return Basis-Jahr des Projekts auf das die Cashflows abgezinst werden * muessen */ public int getBasisYear() { return basisYear; } public List<Szenario> getScenarios() { return this.scenarios; } /** * Gibt nur die einbezogenen Szenarios eines Projektes zurück. * * @author Marcel Rosenberger * * @return alle einbezogenen Szenarios */ public List<Szenario> getIncludedScenarios() { List<Szenario> includedScenarios = new ArrayList<Szenario>(); for (Szenario szenario : this.scenarios){ if(szenario.isIncludeInCalculation()){ includedScenarios.add(szenario); } } return includedScenarios; } public void addScenario(Szenario scenario) { this.scenarios.add(scenario); } public User getCreatedFrom() { return createdFrom; } public void setCreatedFrom(User user) { createdFrom = user; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } public int getTotalPeriods (){ if (projectInputType.isDeterministic()==true){ return periodsToForecast_deterministic; } return specifiedPastPeriods ; } public String getTypMethod(){ if (projectInputType.isDeterministic()==true){ typ = "Deterministische Eingabe"; } else { typ = "Stochastische Eingabe"; } return typ; } }
143931_2
package Opties; import java.io.*; import java.util.ArrayList; import java.util.Scanner; public class OptieLijst { Optie Navigatiesysteem = new Optie(true, "Navigatiesysteem", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 50, false); Optie Motor = new Optie(true, "Motor", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 50, true); Optie Roer = new Optie(true, "Roer", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 50, false); public Optie Brandstoftank = new Optie(true, "Brandstoftank", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 50, true); public Optie Anker = new Optie(true, "Anker", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 50, false); Optie Airconditioning = new Optie(false, "Airconditioning", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 20, false); Optie Sonar = new Optie(false, "Sonar", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 20, false); Optie ExtraPKs = new Optie(false, "ExtraPKs", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 20, false); //public List<Opties.Optie> optielijst = List.of(optie1, optie2, optie3, optie4, optie5, optie6, optie7, optie8); // is voor List // is handig om te houden in het geval je de List optielijst veranderd naar ArrayList public ArrayList<Optie> optielijst = new ArrayList<Optie>(); private String Path = "ShipFlexcode" + File.separator + "src" + File.separator + "CSV_Files" + File.separator + "opties.csv"; //Bovenstaande path is een relatief path naar de juiste plek voor het bestand. Dit betekent dat de code op elk andere computer hoort te werken. public void writeToCSV() throws FileNotFoundException { //readFromCSV(); //Vul de arraylist eerst in zodat het csv bestand overschreven kan worden. StringBuilder builder = new StringBuilder(); File csv = new File(Path); PrintWriter pw = new PrintWriter(csv); try { for (int i = 0; i < optielijst.size(); i++) { builder.append(optielijst.get(i).getIsEssentieel()); builder.append(","); builder.append(optielijst.get(i).getNaam()); builder.append(","); builder.append(optielijst.get(i).getBeschrijving()); builder.append(","); builder.append(optielijst.get(i).getPrijs()); builder.append(","); builder.append(optielijst.get(i).getMiliuekorting()); builder.append("\n"); } pw.write(String.valueOf(builder)); pw.flush(); pw.close(); //System.out.println(builder); } catch (Exception e) { e.printStackTrace(); } } //Deze methode leest dingen uit een csv bestand en maakt hiermee objecten van het type Opties.Optie aan. public void readFromCSV() { BufferedReader reader = null; String line = ""; try { reader = new BufferedReader(new FileReader(Path)); optielijst.clear(); while ((line = reader.readLine()) != null) { String[] row = line.split(","); optielijst.add(new Optie(row[0], row[1], row[2], row[3], row[4])); } } catch (Exception e) { } } public void voegAlleOptiesToeAanLijst(OptieLijst optielijst) { optielijst.optielijst.add(Navigatiesysteem); optielijst.optielijst.add(Motor); optielijst.optielijst.add(Roer); optielijst.optielijst.add(Brandstoftank); optielijst.optielijst.add(Anker); optielijst.optielijst.add(Airconditioning); optielijst.optielijst.add(Sonar); optielijst.optielijst.add(ExtraPKs); } // tot hier public void printOptieLijst() { readFromCSV(); for (int i = 0; i < 202; i++) { System.out.print("-"); } System.out.println(); System.out.printf("|%-15s| %-20s| %-20s| %-100s| %-10s| %-25s|%n", "Optie nr.", "Essentiele optie", "Naam", "Beschrijving", "Prijs", "Milieukorting" ); for (int i = 0; i < 202; i++) { System.out.print("-"); } System.out.println(); for (int i = 1; i < optielijst.size(); i++) { String prijs = String.valueOf(optielijst.get(i).getPrijs()); //Dit was eerst 'doubleprijs' //String prijs = "\u20ac" + doubleprijs; //De bedoeling hiervan was om een eurosymbool te printen, maar dat lijkt niet te werken met printf if (optielijst.get(i).getIsEssentieel()) { System.out.printf("|%-15d| %-20s| %-20s| %-100s| %-10s| %-25s|%n", optielijst.indexOf(optielijst.get(i)), optielijst.get(i).getIsEssentieel(), optielijst.get(i).getNaam(), optielijst.get(i).getBeschrijving(), optielijst.get(i).getPrijs(), optielijst.get(i).getMiliuekorting() ); } } for (int i = 1; i < optielijst.size(); i++) { if (!optielijst.get(i).getIsEssentieel()) { System.out.printf("|%-15d| %-20s| %-20s| %-100s| %-10s| %-25s|%n", optielijst.indexOf(optielijst.get(i)), optielijst.get(i).getIsEssentieel(), optielijst.get(i).getNaam(), optielijst.get(i).getBeschrijving(), optielijst.get(i).getPrijs(), optielijst.get(i).getMiliuekorting() ); } } for (int i = 0; i < 202; i++) { System.out.print("-"); } System.out.println(); } public void nieuweOptie(String isEssentieel, String naam, String beschrijving, String prijs, String milieukorting) throws FileNotFoundException { Optie nieuweOptie = new Optie(isEssentieel, naam, beschrijving, prijs, milieukorting); readFromCSV(); optielijst.add(nieuweOptie); writeToCSV(); } public void nieuweOptie(boolean isEssentieel, String naam, String beschrijving, double prijs, boolean milieukorting) throws FileNotFoundException { readFromCSV(); Optie nieuweOptie = new Optie(isEssentieel, naam, beschrijving, prijs, milieukorting); optielijst.add(nieuweOptie); writeToCSV(); } }
DKnightAnon/OPT-project-1
ShipFlexcode/src/Opties/OptieLijst.java
2,291
//Bovenstaande path is een relatief path naar de juiste plek voor het bestand. Dit betekent dat de code op elk andere computer hoort te werken.
line_comment
nl
package Opties; import java.io.*; import java.util.ArrayList; import java.util.Scanner; public class OptieLijst { Optie Navigatiesysteem = new Optie(true, "Navigatiesysteem", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 50, false); Optie Motor = new Optie(true, "Motor", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 50, true); Optie Roer = new Optie(true, "Roer", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 50, false); public Optie Brandstoftank = new Optie(true, "Brandstoftank", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 50, true); public Optie Anker = new Optie(true, "Anker", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 50, false); Optie Airconditioning = new Optie(false, "Airconditioning", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 20, false); Optie Sonar = new Optie(false, "Sonar", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 20, false); Optie ExtraPKs = new Optie(false, "ExtraPKs", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 20, false); //public List<Opties.Optie> optielijst = List.of(optie1, optie2, optie3, optie4, optie5, optie6, optie7, optie8); // is voor List // is handig om te houden in het geval je de List optielijst veranderd naar ArrayList public ArrayList<Optie> optielijst = new ArrayList<Optie>(); private String Path = "ShipFlexcode" + File.separator + "src" + File.separator + "CSV_Files" + File.separator + "opties.csv"; //Bovenstaande path<SUF> public void writeToCSV() throws FileNotFoundException { //readFromCSV(); //Vul de arraylist eerst in zodat het csv bestand overschreven kan worden. StringBuilder builder = new StringBuilder(); File csv = new File(Path); PrintWriter pw = new PrintWriter(csv); try { for (int i = 0; i < optielijst.size(); i++) { builder.append(optielijst.get(i).getIsEssentieel()); builder.append(","); builder.append(optielijst.get(i).getNaam()); builder.append(","); builder.append(optielijst.get(i).getBeschrijving()); builder.append(","); builder.append(optielijst.get(i).getPrijs()); builder.append(","); builder.append(optielijst.get(i).getMiliuekorting()); builder.append("\n"); } pw.write(String.valueOf(builder)); pw.flush(); pw.close(); //System.out.println(builder); } catch (Exception e) { e.printStackTrace(); } } //Deze methode leest dingen uit een csv bestand en maakt hiermee objecten van het type Opties.Optie aan. public void readFromCSV() { BufferedReader reader = null; String line = ""; try { reader = new BufferedReader(new FileReader(Path)); optielijst.clear(); while ((line = reader.readLine()) != null) { String[] row = line.split(","); optielijst.add(new Optie(row[0], row[1], row[2], row[3], row[4])); } } catch (Exception e) { } } public void voegAlleOptiesToeAanLijst(OptieLijst optielijst) { optielijst.optielijst.add(Navigatiesysteem); optielijst.optielijst.add(Motor); optielijst.optielijst.add(Roer); optielijst.optielijst.add(Brandstoftank); optielijst.optielijst.add(Anker); optielijst.optielijst.add(Airconditioning); optielijst.optielijst.add(Sonar); optielijst.optielijst.add(ExtraPKs); } // tot hier public void printOptieLijst() { readFromCSV(); for (int i = 0; i < 202; i++) { System.out.print("-"); } System.out.println(); System.out.printf("|%-15s| %-20s| %-20s| %-100s| %-10s| %-25s|%n", "Optie nr.", "Essentiele optie", "Naam", "Beschrijving", "Prijs", "Milieukorting" ); for (int i = 0; i < 202; i++) { System.out.print("-"); } System.out.println(); for (int i = 1; i < optielijst.size(); i++) { String prijs = String.valueOf(optielijst.get(i).getPrijs()); //Dit was eerst 'doubleprijs' //String prijs = "\u20ac" + doubleprijs; //De bedoeling hiervan was om een eurosymbool te printen, maar dat lijkt niet te werken met printf if (optielijst.get(i).getIsEssentieel()) { System.out.printf("|%-15d| %-20s| %-20s| %-100s| %-10s| %-25s|%n", optielijst.indexOf(optielijst.get(i)), optielijst.get(i).getIsEssentieel(), optielijst.get(i).getNaam(), optielijst.get(i).getBeschrijving(), optielijst.get(i).getPrijs(), optielijst.get(i).getMiliuekorting() ); } } for (int i = 1; i < optielijst.size(); i++) { if (!optielijst.get(i).getIsEssentieel()) { System.out.printf("|%-15d| %-20s| %-20s| %-100s| %-10s| %-25s|%n", optielijst.indexOf(optielijst.get(i)), optielijst.get(i).getIsEssentieel(), optielijst.get(i).getNaam(), optielijst.get(i).getBeschrijving(), optielijst.get(i).getPrijs(), optielijst.get(i).getMiliuekorting() ); } } for (int i = 0; i < 202; i++) { System.out.print("-"); } System.out.println(); } public void nieuweOptie(String isEssentieel, String naam, String beschrijving, String prijs, String milieukorting) throws FileNotFoundException { Optie nieuweOptie = new Optie(isEssentieel, naam, beschrijving, prijs, milieukorting); readFromCSV(); optielijst.add(nieuweOptie); writeToCSV(); } public void nieuweOptie(boolean isEssentieel, String naam, String beschrijving, double prijs, boolean milieukorting) throws FileNotFoundException { readFromCSV(); Optie nieuweOptie = new Optie(isEssentieel, naam, beschrijving, prijs, milieukorting); optielijst.add(nieuweOptie); writeToCSV(); } }
41440_24
import java.util.*; //importeren van java.util import java.io.*; //importeren van java.io public class Phonebook { Vector <Person> people; int n; //class variable omdat het niet in de methode zelf mocht voor recursie public Phonebook(String file) { people = new Vector <Person> (); read(file); } public void read (String file) {//begin functie inlezen bestand try {//try catch voor fouten File bestandnaam = new File(file); //bestandsnaam doorgeven Scanner lezer = new Scanner(bestandnaam); //scanner voor het inlezen van het bestand while (lezer.hasNextLine()) {//while loop om door alle regels in het bestand te gaan String data = lezer.nextLine(); //volgende line in het bestand StringTokenizer st = new StringTokenizer(data, ",");//naam los van de nummers maken in tokenizer Person L = new Person(st.nextToken(), st.nextToken());//object L aanmaken en de naam en het nummer erin invoegen people.add(L); //naam toevoegen aan vector } lezer.close(); } catch (Exception error) {// als er een fout gevonden is System.out.println("Fout gevonden."); error.printStackTrace(); } } public String toString() { String allesin1 = ""; //lege string die gevuld wordt met de namen en nummers for (Person L: people) {//loop om door alle people te gaan //printen van name en number in de vector die onderdeel zijn van class Person allesin1 = allesin1 + L.name + " " + L.number + "\n"; } return allesin1; //returnen van de string met alles erin } public String number(String name) { for (Person L: people) {//loop om door alle people te gaan if (name.equals(L.name)) { return L.name + " " + L.number; } } return "Geen overeenkomsten gevonden."; //als er geen overeenkomsten zijn } public void sort(){ n = people.size(); people = sort(people);//eerste aanroep recursie } private Vector <Person> sort (Vector <Person> tosort) { //Bubblesort base case if (n == 1) { return tosort; }//body int count = 0; //zodat de recursie niet onnodig in wordt gegaan for (int i = 0; i < n-1; i++) { Person P = tosort.get(i); //haalt huidige in de vector op Person L = tosort.get(i+1); // haalt de volgende in de vector op String s2 = P.name; //zet type person om in string name String s1 = L.name; //zet type person om in string name if (isSmaller(s1, s2)) { //isSmaller om te vergelijken of s1 kleiner is dan s2 tosort.set(i, L); // draait de namen om tosort.set(i + 1, P); count = count +1; } } if (count == 0) { return tosort; } n = n-1; return sort(tosort);// recursie } private boolean isSmaller (String s1, String s2) { // returns true if s1 <s2 alphabetically boolean builtdifferent = false; //boolean voor de while loop boolean iskleiner = false; //boolean voor als s1 kleiner is dan s2 dus s2 bovenaan moet zijn int i = 0;//teller om de letters te vergelijken op pos i in de string while (!builtdifferent) {//while loop die doorgaat tot er een verschil is tussen de 2 strings if (s1.toLowerCase().charAt(i) != s2.toLowerCase().charAt(i)) { if ((int)s1.toLowerCase().charAt(i) < (int)s2.toLowerCase().charAt(i)) {// hoe lager getal hoe eerder alfabet iskleiner = true; //als s1 kleiner is dan s2 } builtdifferent = true; //voor het eindigen van de while loop }else { i++; //om door te gaan naar het volgende character van de string } } return iskleiner; } }
DMR-max/symbolic-AI-0
Phonebook.java
1,271
//zet type person om in string name
line_comment
nl
import java.util.*; //importeren van java.util import java.io.*; //importeren van java.io public class Phonebook { Vector <Person> people; int n; //class variable omdat het niet in de methode zelf mocht voor recursie public Phonebook(String file) { people = new Vector <Person> (); read(file); } public void read (String file) {//begin functie inlezen bestand try {//try catch voor fouten File bestandnaam = new File(file); //bestandsnaam doorgeven Scanner lezer = new Scanner(bestandnaam); //scanner voor het inlezen van het bestand while (lezer.hasNextLine()) {//while loop om door alle regels in het bestand te gaan String data = lezer.nextLine(); //volgende line in het bestand StringTokenizer st = new StringTokenizer(data, ",");//naam los van de nummers maken in tokenizer Person L = new Person(st.nextToken(), st.nextToken());//object L aanmaken en de naam en het nummer erin invoegen people.add(L); //naam toevoegen aan vector } lezer.close(); } catch (Exception error) {// als er een fout gevonden is System.out.println("Fout gevonden."); error.printStackTrace(); } } public String toString() { String allesin1 = ""; //lege string die gevuld wordt met de namen en nummers for (Person L: people) {//loop om door alle people te gaan //printen van name en number in de vector die onderdeel zijn van class Person allesin1 = allesin1 + L.name + " " + L.number + "\n"; } return allesin1; //returnen van de string met alles erin } public String number(String name) { for (Person L: people) {//loop om door alle people te gaan if (name.equals(L.name)) { return L.name + " " + L.number; } } return "Geen overeenkomsten gevonden."; //als er geen overeenkomsten zijn } public void sort(){ n = people.size(); people = sort(people);//eerste aanroep recursie } private Vector <Person> sort (Vector <Person> tosort) { //Bubblesort base case if (n == 1) { return tosort; }//body int count = 0; //zodat de recursie niet onnodig in wordt gegaan for (int i = 0; i < n-1; i++) { Person P = tosort.get(i); //haalt huidige in de vector op Person L = tosort.get(i+1); // haalt de volgende in de vector op String s2 = P.name; //zet type person om in string name String s1 = L.name; //zet type<SUF> if (isSmaller(s1, s2)) { //isSmaller om te vergelijken of s1 kleiner is dan s2 tosort.set(i, L); // draait de namen om tosort.set(i + 1, P); count = count +1; } } if (count == 0) { return tosort; } n = n-1; return sort(tosort);// recursie } private boolean isSmaller (String s1, String s2) { // returns true if s1 <s2 alphabetically boolean builtdifferent = false; //boolean voor de while loop boolean iskleiner = false; //boolean voor als s1 kleiner is dan s2 dus s2 bovenaan moet zijn int i = 0;//teller om de letters te vergelijken op pos i in de string while (!builtdifferent) {//while loop die doorgaat tot er een verschil is tussen de 2 strings if (s1.toLowerCase().charAt(i) != s2.toLowerCase().charAt(i)) { if ((int)s1.toLowerCase().charAt(i) < (int)s2.toLowerCase().charAt(i)) {// hoe lager getal hoe eerder alfabet iskleiner = true; //als s1 kleiner is dan s2 } builtdifferent = true; //voor het eindigen van de while loop }else { i++; //om door te gaan naar het volgende character van de string } } return iskleiner; } }
28754_9
package net.minecraft.src; import java.util.List; import java.util.Random; import net.minecraft.client.Minecraft; import org.lwjgl.input.Keyboard; public class GuiCreateWorld extends GuiScreen { private GuiScreen parentGuiScreen; private GuiTextField textboxWorldName; private GuiTextField textboxSeed; private String folderName; /** hardcore', 'creative' or 'survival */ private String gameMode; private boolean field_35365_g; private boolean field_40232_h; private boolean createClicked; /** * True if the extra options (Seed box, structure toggle button, world type button, etc.) are being shown */ private boolean moreOptions; /** The GUIButton that you click to change game modes. */ private GuiButton gameModeButton; /** * The GUIButton that you click to get to options like the seed when creating a world. */ private GuiButton moreWorldOptions; /** The GuiButton in the 'More World Options' screen. Toggles ON/OFF */ private GuiButton generateStructuresButton; /** * the GUIButton in the more world options screen. It's currently greyed out and unused in minecraft 1.0.0 */ private GuiButton worldTypeButton; /** The first line of text describing the currently selected game mode. */ private String gameModeDescriptionLine1; /** The second line of text describing the currently selected game mode. */ private String gameModeDescriptionLine2; /** The current textboxSeed text */ private String seed; /** E.g. New World, Neue Welt, Nieuwe wereld, Neuvo Mundo */ private String localizedNewWorldText; private int field_46030_z; public GuiCreateWorld(GuiScreen par1GuiScreen) { gameMode = "survival"; field_35365_g = true; field_40232_h = false; field_46030_z = 0; parentGuiScreen = par1GuiScreen; seed = ""; localizedNewWorldText = StatCollector.translateToLocal("selectWorld.newWorld"); } /** * Called from the main game loop to update the screen. */ public void updateScreen() { textboxWorldName.updateCursorCounter(); textboxSeed.updateCursorCounter(); } /** * Adds the buttons (and other controls) to the screen in question. */ public void initGui() { StringTranslate stringtranslate = StringTranslate.getInstance(); Keyboard.enableRepeatEvents(true); controlList.clear(); controlList.add(new GuiButton(0, width / 2 - 155, height - 28, 150, 20, stringtranslate.translateKey("selectWorld.create"))); controlList.add(new GuiButton(1, width / 2 + 5, height - 28, 150, 20, stringtranslate.translateKey("gui.cancel"))); controlList.add(gameModeButton = new GuiButton(2, width / 2 - 75, 100, 150, 20, stringtranslate.translateKey("selectWorld.gameMode"))); controlList.add(moreWorldOptions = new GuiButton(3, width / 2 - 75, 172, 150, 20, stringtranslate.translateKey("selectWorld.moreWorldOptions"))); controlList.add(generateStructuresButton = new GuiButton(4, width / 2 - 155, 100, 150, 20, stringtranslate.translateKey("selectWorld.mapFeatures"))); generateStructuresButton.drawButton = false; controlList.add(worldTypeButton = new GuiButton(5, width / 2 + 5, 100, 150, 20, stringtranslate.translateKey("selectWorld.mapType"))); worldTypeButton.drawButton = false; textboxWorldName = new GuiTextField(fontRenderer, width / 2 - 100, 60, 200, 20); textboxWorldName.setFocused(true); textboxWorldName.setText(localizedNewWorldText); textboxSeed = new GuiTextField(fontRenderer, width / 2 - 100, 60, 200, 20); textboxSeed.setText(seed); makeUseableName(); func_35363_g(); } /** * Makes a the name for a world save folder based on your world name, replacing specific characters for _s and * appending -s to the end until a free name is available. */ private void makeUseableName() { folderName = textboxWorldName.getText().trim(); char ac[] = ChatAllowedCharacters.allowedCharactersArray; int i = ac.length; for (int j = 0; j < i; j++) { char c = ac[j]; folderName = folderName.replace(c, '_'); } if (MathHelper.stringNullOrLengthZero(folderName)) { folderName = "World"; } folderName = func_25097_a(mc.getSaveLoader(), folderName); } private void func_35363_g() { StringTranslate stringtranslate; stringtranslate = StringTranslate.getInstance(); gameModeButton.displayString = (new StringBuilder()).append(stringtranslate.translateKey("selectWorld.gameMode")).append(" ").append(stringtranslate.translateKey((new StringBuilder()).append("selectWorld.gameMode.").append(gameMode).toString())).toString(); gameModeDescriptionLine1 = stringtranslate.translateKey((new StringBuilder()).append("selectWorld.gameMode.").append(gameMode).append(".line1").toString()); gameModeDescriptionLine2 = stringtranslate.translateKey((new StringBuilder()).append("selectWorld.gameMode.").append(gameMode).append(".line2").toString()); generateStructuresButton.displayString = (new StringBuilder()).append(stringtranslate.translateKey("selectWorld.mapFeatures")).append(" ").toString(); if (!(!field_35365_g)) { generateStructuresButton.displayString += stringtranslate.translateKey("options.on"); } else { generateStructuresButton.displayString += stringtranslate.translateKey("options.off"); } worldTypeButton.displayString = (new StringBuilder()).append(stringtranslate.translateKey("selectWorld.mapType")).append(" ").append(stringtranslate.translateKey(WorldType.worldTypes[field_46030_z].getTranslateName())).toString(); return; } public static String func_25097_a(ISaveFormat par0ISaveFormat, String par1Str) { for (par1Str = par1Str.replaceAll("[\\./\"]|COM", "_"); par0ISaveFormat.getWorldInfo(par1Str) != null; par1Str = (new StringBuilder()).append(par1Str).append("-").toString()) { } return par1Str; } /** * Called when the screen is unloaded. Used to disable keyboard repeat events */ public void onGuiClosed() { Keyboard.enableRepeatEvents(false); } /** * Fired when a control is clicked. This is the equivalent of ActionListener.actionPerformed(ActionEvent e). */ protected void actionPerformed(GuiButton par1GuiButton) { if (!par1GuiButton.enabled) { return; } if (par1GuiButton.id == 1) { mc.displayGuiScreen(parentGuiScreen); } else if (par1GuiButton.id == 0) { mc.displayGuiScreen(null); if (createClicked) { return; } createClicked = true; long l = (new Random()).nextLong(); String s = textboxSeed.getText(); if (!MathHelper.stringNullOrLengthZero(s)) { try { long l1 = Long.parseLong(s); if (l1 != 0L) { l = l1; } } catch (NumberFormatException numberformatexception) { l = s.hashCode(); } } int i = 0; if (gameMode.equals("creative")) { i = 1; mc.playerController = new PlayerControllerCreative(mc); } else { mc.playerController = new PlayerControllerSP(mc); } mc.startWorld(folderName, textboxWorldName.getText(), new WorldSettings(l, i, field_35365_g, field_40232_h, WorldType.worldTypes[field_46030_z])); mc.displayGuiScreen(null); } else if (par1GuiButton.id == 3) { moreOptions = !moreOptions; gameModeButton.drawButton = !moreOptions; generateStructuresButton.drawButton = moreOptions; worldTypeButton.drawButton = moreOptions; if (moreOptions) { StringTranslate stringtranslate = StringTranslate.getInstance(); moreWorldOptions.displayString = stringtranslate.translateKey("gui.done"); } else { StringTranslate stringtranslate1 = StringTranslate.getInstance(); moreWorldOptions.displayString = stringtranslate1.translateKey("selectWorld.moreWorldOptions"); } } else if (par1GuiButton.id == 2) { if (gameMode.equals("survival")) { field_40232_h = false; gameMode = "hardcore"; field_40232_h = true; func_35363_g(); } else if (gameMode.equals("hardcore")) { field_40232_h = false; gameMode = "creative"; func_35363_g(); field_40232_h = false; } else { gameMode = "survival"; func_35363_g(); field_40232_h = false; } func_35363_g(); } else if (par1GuiButton.id == 4) { field_35365_g = !field_35365_g; func_35363_g(); } else if (par1GuiButton.id == 5) { field_46030_z++; if (field_46030_z >= WorldType.worldTypes.length) { field_46030_z = 0; } do { if (WorldType.worldTypes[field_46030_z] != null && WorldType.worldTypes[field_46030_z].getCanBeCreated()) { break; } field_46030_z++; if (field_46030_z >= WorldType.worldTypes.length) { field_46030_z = 0; } } while (true); func_35363_g(); } } /** * Fired when a key is typed. This is the equivalent of KeyListener.keyTyped(KeyEvent e). */ protected void keyTyped(char par1, int par2) { if (textboxWorldName.getIsFocused() && !moreOptions) { textboxWorldName.textboxKeyTyped(par1, par2); localizedNewWorldText = textboxWorldName.getText(); } else if (textboxSeed.getIsFocused() && moreOptions) { textboxSeed.textboxKeyTyped(par1, par2); seed = textboxSeed.getText(); } if (par1 == '\r') { actionPerformed((GuiButton)controlList.get(0)); } ((GuiButton)controlList.get(0)).enabled = textboxWorldName.getText().length() > 0; makeUseableName(); } /** * Called when the mouse is clicked. */ protected void mouseClicked(int par1, int par2, int par3) { super.mouseClicked(par1, par2, par3); if (!moreOptions) { textboxWorldName.mouseClicked(par1, par2, par3); } else { textboxSeed.mouseClicked(par1, par2, par3); } } /** * Draws the screen and all the components in it. */ public void drawScreen(int par1, int par2, float par3) { StringTranslate stringtranslate = StringTranslate.getInstance(); drawDefaultBackground(); drawCenteredString(fontRenderer, stringtranslate.translateKey("selectWorld.create"), width / 2, 20, 0xffffff); if (!moreOptions) { drawString(fontRenderer, stringtranslate.translateKey("selectWorld.enterName"), width / 2 - 100, 47, 0xa0a0a0); drawString(fontRenderer, (new StringBuilder()).append(stringtranslate.translateKey("selectWorld.resultFolder")).append(" ").append(folderName).toString(), width / 2 - 100, 85, 0xa0a0a0); textboxWorldName.drawTextBox(); drawString(fontRenderer, gameModeDescriptionLine1, width / 2 - 100, 122, 0xa0a0a0); drawString(fontRenderer, gameModeDescriptionLine2, width / 2 - 100, 134, 0xa0a0a0); } else { drawString(fontRenderer, stringtranslate.translateKey("selectWorld.enterSeed"), width / 2 - 100, 47, 0xa0a0a0); drawString(fontRenderer, stringtranslate.translateKey("selectWorld.seedInfo"), width / 2 - 100, 85, 0xa0a0a0); drawString(fontRenderer, stringtranslate.translateKey("selectWorld.mapFeatures.info"), width / 2 - 150, 122, 0xa0a0a0); textboxSeed.drawTextBox(); } super.drawScreen(par1, par2, par3); } }
DND91/mod_Discord
GuiCreateWorld.java
3,711
/** E.g. New World, Neue Welt, Nieuwe wereld, Neuvo Mundo */
block_comment
nl
package net.minecraft.src; import java.util.List; import java.util.Random; import net.minecraft.client.Minecraft; import org.lwjgl.input.Keyboard; public class GuiCreateWorld extends GuiScreen { private GuiScreen parentGuiScreen; private GuiTextField textboxWorldName; private GuiTextField textboxSeed; private String folderName; /** hardcore', 'creative' or 'survival */ private String gameMode; private boolean field_35365_g; private boolean field_40232_h; private boolean createClicked; /** * True if the extra options (Seed box, structure toggle button, world type button, etc.) are being shown */ private boolean moreOptions; /** The GUIButton that you click to change game modes. */ private GuiButton gameModeButton; /** * The GUIButton that you click to get to options like the seed when creating a world. */ private GuiButton moreWorldOptions; /** The GuiButton in the 'More World Options' screen. Toggles ON/OFF */ private GuiButton generateStructuresButton; /** * the GUIButton in the more world options screen. It's currently greyed out and unused in minecraft 1.0.0 */ private GuiButton worldTypeButton; /** The first line of text describing the currently selected game mode. */ private String gameModeDescriptionLine1; /** The second line of text describing the currently selected game mode. */ private String gameModeDescriptionLine2; /** The current textboxSeed text */ private String seed; /** E.g. New World,<SUF>*/ private String localizedNewWorldText; private int field_46030_z; public GuiCreateWorld(GuiScreen par1GuiScreen) { gameMode = "survival"; field_35365_g = true; field_40232_h = false; field_46030_z = 0; parentGuiScreen = par1GuiScreen; seed = ""; localizedNewWorldText = StatCollector.translateToLocal("selectWorld.newWorld"); } /** * Called from the main game loop to update the screen. */ public void updateScreen() { textboxWorldName.updateCursorCounter(); textboxSeed.updateCursorCounter(); } /** * Adds the buttons (and other controls) to the screen in question. */ public void initGui() { StringTranslate stringtranslate = StringTranslate.getInstance(); Keyboard.enableRepeatEvents(true); controlList.clear(); controlList.add(new GuiButton(0, width / 2 - 155, height - 28, 150, 20, stringtranslate.translateKey("selectWorld.create"))); controlList.add(new GuiButton(1, width / 2 + 5, height - 28, 150, 20, stringtranslate.translateKey("gui.cancel"))); controlList.add(gameModeButton = new GuiButton(2, width / 2 - 75, 100, 150, 20, stringtranslate.translateKey("selectWorld.gameMode"))); controlList.add(moreWorldOptions = new GuiButton(3, width / 2 - 75, 172, 150, 20, stringtranslate.translateKey("selectWorld.moreWorldOptions"))); controlList.add(generateStructuresButton = new GuiButton(4, width / 2 - 155, 100, 150, 20, stringtranslate.translateKey("selectWorld.mapFeatures"))); generateStructuresButton.drawButton = false; controlList.add(worldTypeButton = new GuiButton(5, width / 2 + 5, 100, 150, 20, stringtranslate.translateKey("selectWorld.mapType"))); worldTypeButton.drawButton = false; textboxWorldName = new GuiTextField(fontRenderer, width / 2 - 100, 60, 200, 20); textboxWorldName.setFocused(true); textboxWorldName.setText(localizedNewWorldText); textboxSeed = new GuiTextField(fontRenderer, width / 2 - 100, 60, 200, 20); textboxSeed.setText(seed); makeUseableName(); func_35363_g(); } /** * Makes a the name for a world save folder based on your world name, replacing specific characters for _s and * appending -s to the end until a free name is available. */ private void makeUseableName() { folderName = textboxWorldName.getText().trim(); char ac[] = ChatAllowedCharacters.allowedCharactersArray; int i = ac.length; for (int j = 0; j < i; j++) { char c = ac[j]; folderName = folderName.replace(c, '_'); } if (MathHelper.stringNullOrLengthZero(folderName)) { folderName = "World"; } folderName = func_25097_a(mc.getSaveLoader(), folderName); } private void func_35363_g() { StringTranslate stringtranslate; stringtranslate = StringTranslate.getInstance(); gameModeButton.displayString = (new StringBuilder()).append(stringtranslate.translateKey("selectWorld.gameMode")).append(" ").append(stringtranslate.translateKey((new StringBuilder()).append("selectWorld.gameMode.").append(gameMode).toString())).toString(); gameModeDescriptionLine1 = stringtranslate.translateKey((new StringBuilder()).append("selectWorld.gameMode.").append(gameMode).append(".line1").toString()); gameModeDescriptionLine2 = stringtranslate.translateKey((new StringBuilder()).append("selectWorld.gameMode.").append(gameMode).append(".line2").toString()); generateStructuresButton.displayString = (new StringBuilder()).append(stringtranslate.translateKey("selectWorld.mapFeatures")).append(" ").toString(); if (!(!field_35365_g)) { generateStructuresButton.displayString += stringtranslate.translateKey("options.on"); } else { generateStructuresButton.displayString += stringtranslate.translateKey("options.off"); } worldTypeButton.displayString = (new StringBuilder()).append(stringtranslate.translateKey("selectWorld.mapType")).append(" ").append(stringtranslate.translateKey(WorldType.worldTypes[field_46030_z].getTranslateName())).toString(); return; } public static String func_25097_a(ISaveFormat par0ISaveFormat, String par1Str) { for (par1Str = par1Str.replaceAll("[\\./\"]|COM", "_"); par0ISaveFormat.getWorldInfo(par1Str) != null; par1Str = (new StringBuilder()).append(par1Str).append("-").toString()) { } return par1Str; } /** * Called when the screen is unloaded. Used to disable keyboard repeat events */ public void onGuiClosed() { Keyboard.enableRepeatEvents(false); } /** * Fired when a control is clicked. This is the equivalent of ActionListener.actionPerformed(ActionEvent e). */ protected void actionPerformed(GuiButton par1GuiButton) { if (!par1GuiButton.enabled) { return; } if (par1GuiButton.id == 1) { mc.displayGuiScreen(parentGuiScreen); } else if (par1GuiButton.id == 0) { mc.displayGuiScreen(null); if (createClicked) { return; } createClicked = true; long l = (new Random()).nextLong(); String s = textboxSeed.getText(); if (!MathHelper.stringNullOrLengthZero(s)) { try { long l1 = Long.parseLong(s); if (l1 != 0L) { l = l1; } } catch (NumberFormatException numberformatexception) { l = s.hashCode(); } } int i = 0; if (gameMode.equals("creative")) { i = 1; mc.playerController = new PlayerControllerCreative(mc); } else { mc.playerController = new PlayerControllerSP(mc); } mc.startWorld(folderName, textboxWorldName.getText(), new WorldSettings(l, i, field_35365_g, field_40232_h, WorldType.worldTypes[field_46030_z])); mc.displayGuiScreen(null); } else if (par1GuiButton.id == 3) { moreOptions = !moreOptions; gameModeButton.drawButton = !moreOptions; generateStructuresButton.drawButton = moreOptions; worldTypeButton.drawButton = moreOptions; if (moreOptions) { StringTranslate stringtranslate = StringTranslate.getInstance(); moreWorldOptions.displayString = stringtranslate.translateKey("gui.done"); } else { StringTranslate stringtranslate1 = StringTranslate.getInstance(); moreWorldOptions.displayString = stringtranslate1.translateKey("selectWorld.moreWorldOptions"); } } else if (par1GuiButton.id == 2) { if (gameMode.equals("survival")) { field_40232_h = false; gameMode = "hardcore"; field_40232_h = true; func_35363_g(); } else if (gameMode.equals("hardcore")) { field_40232_h = false; gameMode = "creative"; func_35363_g(); field_40232_h = false; } else { gameMode = "survival"; func_35363_g(); field_40232_h = false; } func_35363_g(); } else if (par1GuiButton.id == 4) { field_35365_g = !field_35365_g; func_35363_g(); } else if (par1GuiButton.id == 5) { field_46030_z++; if (field_46030_z >= WorldType.worldTypes.length) { field_46030_z = 0; } do { if (WorldType.worldTypes[field_46030_z] != null && WorldType.worldTypes[field_46030_z].getCanBeCreated()) { break; } field_46030_z++; if (field_46030_z >= WorldType.worldTypes.length) { field_46030_z = 0; } } while (true); func_35363_g(); } } /** * Fired when a key is typed. This is the equivalent of KeyListener.keyTyped(KeyEvent e). */ protected void keyTyped(char par1, int par2) { if (textboxWorldName.getIsFocused() && !moreOptions) { textboxWorldName.textboxKeyTyped(par1, par2); localizedNewWorldText = textboxWorldName.getText(); } else if (textboxSeed.getIsFocused() && moreOptions) { textboxSeed.textboxKeyTyped(par1, par2); seed = textboxSeed.getText(); } if (par1 == '\r') { actionPerformed((GuiButton)controlList.get(0)); } ((GuiButton)controlList.get(0)).enabled = textboxWorldName.getText().length() > 0; makeUseableName(); } /** * Called when the mouse is clicked. */ protected void mouseClicked(int par1, int par2, int par3) { super.mouseClicked(par1, par2, par3); if (!moreOptions) { textboxWorldName.mouseClicked(par1, par2, par3); } else { textboxSeed.mouseClicked(par1, par2, par3); } } /** * Draws the screen and all the components in it. */ public void drawScreen(int par1, int par2, float par3) { StringTranslate stringtranslate = StringTranslate.getInstance(); drawDefaultBackground(); drawCenteredString(fontRenderer, stringtranslate.translateKey("selectWorld.create"), width / 2, 20, 0xffffff); if (!moreOptions) { drawString(fontRenderer, stringtranslate.translateKey("selectWorld.enterName"), width / 2 - 100, 47, 0xa0a0a0); drawString(fontRenderer, (new StringBuilder()).append(stringtranslate.translateKey("selectWorld.resultFolder")).append(" ").append(folderName).toString(), width / 2 - 100, 85, 0xa0a0a0); textboxWorldName.drawTextBox(); drawString(fontRenderer, gameModeDescriptionLine1, width / 2 - 100, 122, 0xa0a0a0); drawString(fontRenderer, gameModeDescriptionLine2, width / 2 - 100, 134, 0xa0a0a0); } else { drawString(fontRenderer, stringtranslate.translateKey("selectWorld.enterSeed"), width / 2 - 100, 47, 0xa0a0a0); drawString(fontRenderer, stringtranslate.translateKey("selectWorld.seedInfo"), width / 2 - 100, 85, 0xa0a0a0); drawString(fontRenderer, stringtranslate.translateKey("selectWorld.mapFeatures.info"), width / 2 - 150, 122, 0xa0a0a0); textboxSeed.drawTextBox(); } super.drawScreen(par1, par2, par3); } }
53484_6
package be.dnsbelgium.mercator.vat.domain; import org.slf4j.Logger; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import static org.slf4j.LoggerFactory.getLogger; /** * This class tries to find all (valid) VAT values in a given String. * It does NOT know anything about HTTP nor HTML. * The class is using Regular Expressions to find Belgian VAT values. * * Because of the many different ways to format a Belgian VAT number, it's impossible to catch * all VAT values and to catch ONLY vat values. * The current regex is an attempt to find most real VAT values without catching too many false positives, * like phone numbers, bank accounts or other numeric strings. * */ @Service public class VatFinder { private static final Logger logger = getLogger(VatFinder.class); private final Pattern vatPattern; public static final String VAT_REGEX = // always start on a word boundary, optional VAT or BTW or VAT, optional BE, optional colon "\\b(?:VAT|BTW|TVA)?(?:BE)?:?(?:" + // Old format VAT numbers (with a leading 0 that is omitted) "0[0-9]{8}" + // Formatted as a 0 or 1, with three times three numbers and a possible separator "|[01][ .-]?[0-9]{3}[ .-]?[0-9]{3}[ .-]?[0-9]{3}" + // OR: non-zero digit, optional sep, 2 digits, optional sep, 3 digits, optional sep , 3 digits "|[1-9][ .-]?[0-9]{2}[ .-]?[0-9]{3}[ .-]?[0-9]{3}" + ")(?![0-9])"; // only matches the above when it is not followed by a digit /* // TODO add regex for NL and FR ?? // String NL_VAT_REGEX = "(?i)((NL)?0([. -])?[0-9]{3}([. -])?[0-9]{3}([. -])?[0-9]{3})B[0-9]{2}"; https://ondernemersplein.kvk.nl/btw-identificatienummer-opzoeken-controleren-en-vermelden/ Het btw-identificatienummer (btw-id) bestaat uit de landcode NL, 9 cijfers, de letter B en een controlegetal van 2 cijfers. U zet uw btw-id op uw facturen. Als u via het internet verkoopt of diensten aanbiedt, moet u het btw-id op uw website zetten */ public VatFinder() { this.vatPattern = Pattern.compile(VAT_REGEX, Pattern.CASE_INSENSITIVE); } /** * Normalizes a raw VAT number found on a web page to fit the format BExxxxxxxxxx where x is a digit * * @author Jules Dejaeghere * @param VAT Raw VAT number found on a web page * @return Nullable (if input is null) String with the normalized VAT number */ public String normalizeVAT(String VAT) { if (VAT == null) { return null; } VAT = VAT.toUpperCase(); VAT = VAT .replace(".", "") .replace("-", "") .replace(" ", "") .replace(":", "") .replace("BTW","") .replace("VAT", "") .replace("TVA", "") .replace("BE", "") ; if (VAT.length() < 10) { // Although a VAT can have another leading number, we assume that people omitting it will have a zero as leading // number. return "BE0" + VAT; } return "BE" + VAT; } /** * Determines if a normalized VAT number is valid. * A valid VAT number meet the following criteria: * - Let BE0xxx xxx xyy a VAT number * - The VAT number is valid if 97-(xxxxxxx mod 97) == yy * * @param VAT Normalized VAT number to check * @return true if the VAT is valid, false otherwise */ public boolean isValidVAT(String VAT) { if (VAT == null || VAT.length() < 9) { return false; } VAT = VAT.substring(2); int head = Integer.parseInt(VAT.substring(0, VAT.length() - 2)); int tail = Integer.parseInt(VAT.substring(8)); int checksum = (97 - (head % 97)); logger.debug("input={} head={} tail={} checksum={}", VAT, head, tail, checksum); return (checksum == tail); } public List<String> findVatValues(String text) { List<String> vatList = new ArrayList<>(); Matcher matcher = vatPattern.matcher(text); while (matcher.find()) { String match = matcher.group(0); String VAT = normalizeVAT(match); if (!vatList.contains(VAT)) { vatList.add(VAT); } } return vatList; } public List<String> findValidVatValues(String text) { List<String> vatList = findVatValues(text); return vatList.stream().filter(this::isValidVAT).collect(Collectors.toList()); } }
DNSBelgium/mercator
vat-crawler/src/main/java/be/dnsbelgium/mercator/vat/domain/VatFinder.java
1,551
/* // TODO add regex for NL and FR ?? // String NL_VAT_REGEX = "(?i)((NL)?0([. -])?[0-9]{3}([. -])?[0-9]{3}([. -])?[0-9]{3})B[0-9]{2}"; https://ondernemersplein.kvk.nl/btw-identificatienummer-opzoeken-controleren-en-vermelden/ Het btw-identificatienummer (btw-id) bestaat uit de landcode NL, 9 cijfers, de letter B en een controlegetal van 2 cijfers. U zet uw btw-id op uw facturen. Als u via het internet verkoopt of diensten aanbiedt, moet u het btw-id op uw website zetten */
block_comment
nl
package be.dnsbelgium.mercator.vat.domain; import org.slf4j.Logger; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import static org.slf4j.LoggerFactory.getLogger; /** * This class tries to find all (valid) VAT values in a given String. * It does NOT know anything about HTTP nor HTML. * The class is using Regular Expressions to find Belgian VAT values. * * Because of the many different ways to format a Belgian VAT number, it's impossible to catch * all VAT values and to catch ONLY vat values. * The current regex is an attempt to find most real VAT values without catching too many false positives, * like phone numbers, bank accounts or other numeric strings. * */ @Service public class VatFinder { private static final Logger logger = getLogger(VatFinder.class); private final Pattern vatPattern; public static final String VAT_REGEX = // always start on a word boundary, optional VAT or BTW or VAT, optional BE, optional colon "\\b(?:VAT|BTW|TVA)?(?:BE)?:?(?:" + // Old format VAT numbers (with a leading 0 that is omitted) "0[0-9]{8}" + // Formatted as a 0 or 1, with three times three numbers and a possible separator "|[01][ .-]?[0-9]{3}[ .-]?[0-9]{3}[ .-]?[0-9]{3}" + // OR: non-zero digit, optional sep, 2 digits, optional sep, 3 digits, optional sep , 3 digits "|[1-9][ .-]?[0-9]{2}[ .-]?[0-9]{3}[ .-]?[0-9]{3}" + ")(?![0-9])"; // only matches the above when it is not followed by a digit /* // TODO add regex<SUF>*/ public VatFinder() { this.vatPattern = Pattern.compile(VAT_REGEX, Pattern.CASE_INSENSITIVE); } /** * Normalizes a raw VAT number found on a web page to fit the format BExxxxxxxxxx where x is a digit * * @author Jules Dejaeghere * @param VAT Raw VAT number found on a web page * @return Nullable (if input is null) String with the normalized VAT number */ public String normalizeVAT(String VAT) { if (VAT == null) { return null; } VAT = VAT.toUpperCase(); VAT = VAT .replace(".", "") .replace("-", "") .replace(" ", "") .replace(":", "") .replace("BTW","") .replace("VAT", "") .replace("TVA", "") .replace("BE", "") ; if (VAT.length() < 10) { // Although a VAT can have another leading number, we assume that people omitting it will have a zero as leading // number. return "BE0" + VAT; } return "BE" + VAT; } /** * Determines if a normalized VAT number is valid. * A valid VAT number meet the following criteria: * - Let BE0xxx xxx xyy a VAT number * - The VAT number is valid if 97-(xxxxxxx mod 97) == yy * * @param VAT Normalized VAT number to check * @return true if the VAT is valid, false otherwise */ public boolean isValidVAT(String VAT) { if (VAT == null || VAT.length() < 9) { return false; } VAT = VAT.substring(2); int head = Integer.parseInt(VAT.substring(0, VAT.length() - 2)); int tail = Integer.parseInt(VAT.substring(8)); int checksum = (97 - (head % 97)); logger.debug("input={} head={} tail={} checksum={}", VAT, head, tail, checksum); return (checksum == tail); } public List<String> findVatValues(String text) { List<String> vatList = new ArrayList<>(); Matcher matcher = vatPattern.matcher(text); while (matcher.find()) { String match = matcher.group(0); String VAT = normalizeVAT(match); if (!vatList.contains(VAT)) { vatList.add(VAT); } } return vatList; } public List<String> findValidVatValues(String text) { List<String> vatList = findVatValues(text); return vatList.stream().filter(this::isValidVAT).collect(Collectors.toList()); } }
33621_4
/* * ENTRADA, a big data platform for network data analytics * * Copyright (C) 2016 SIDN [https://www.sidn.nl] * * This file is part of ENTRADA. * * ENTRADA 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. * * ENTRADA 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 ENTRADA. If not, see [<http://www.gnu.org/licenses/]. * */ package nl.sidn.dnslib.util; import java.math.BigInteger; import java.nio.ByteBuffer; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.RSAPublicKeySpec; import nl.sidn.dnslib.message.records.dnssec.DNSKEYResourceRecord; import nl.sidn.dnslib.message.records.dnssec.DSResourceRecord; public class KeyUtil { private static char KEY_ZONE_FLAG_MASK = 0x0100; //0000 0001 0000 0000 private static char KEY_ZONE_SEP_FLAG_MASK = 0x0101; //0000 0001 0000 0001 public static PublicKey createRSAPublicKey(byte[] key) { ByteBuffer b = ByteBuffer.wrap(key); int exponentLength = b.get() & 0xff; if (exponentLength == 0){ exponentLength = b.getChar(); } try { byte [] data = new byte[exponentLength]; b.get(data); BigInteger exponent = new BigInteger(1, data); byte [] modulusData = new byte[b.remaining()]; b.get(modulusData); BigInteger modulus = new BigInteger(1, modulusData); KeyFactory factory = KeyFactory.getInstance("RSA"); return factory.generatePublic(new RSAPublicKeySpec(modulus, exponent)); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { throw new RuntimeException("Error creating public key", e); } } /** * Bereken de keyTag(footprint) van een publieke sleutel. * De keyTag berekent een getal waarmee de publieke sleutel te herkennen is, dit is * niet per definitie uniek per publieke sleutel. * Zie IETF RFC 4034, Appendix B voor meer informatie. * @see http://www.ietf.org/rfc/rfc4034.txt * * Dit lijkt op het berekenen van 1 complement checksum (http://nl.wikipedia.org/wiki/One%27s_complement) * De onderstaande implementatie is overgenomen van versisign, zie: * http://svn.verisignlabs.com/jdnssec/dnsjava/trunk/org/xbill/DNS/KEYBase.java * @param key een base64 encoded public key * @param algorimte, de naam van het algoritme waarmee de public key is gemaakt. * @return integer waarde welke de keytag van de public key is */ public static int createKeyTag(byte[] rdata, int alg) { int foot = 0; int footprint = -1; // als de publieke sleuten met RSA/MD5 is gemaakt en gehashed dan // geld er een ander algoritme voor bepalen keytag if (1 == alg) { //MD5 int d1 = rdata[rdata.length - 3] & 0xFF; int d2 = rdata[rdata.length - 2] & 0xFF; foot = (d1 << 8) + d2; } else { int i; for (i = 0; i < rdata.length - 1; i += 2) { int d1 = rdata[i] & 0xFF; int d2 = rdata[i + 1] & 0xFF; foot += ((d1 << 8) + d2); } if (i < rdata.length) { int d1 = rdata[i] & 0xFF; foot += (d1 << 8); } foot += ((foot >> 16) & 0xFFFF); } footprint = (foot & 0xFFFF); return footprint; } public static boolean isZoneKey(DNSKEYResourceRecord key){ return (key.getFlags() & KEY_ZONE_FLAG_MASK) == KEY_ZONE_FLAG_MASK; } public static boolean isSepKey(DNSKEYResourceRecord key){ return (key.getFlags() & KEY_ZONE_SEP_FLAG_MASK) == KEY_ZONE_SEP_FLAG_MASK; } public static boolean isKeyandDSmatch(DNSKEYResourceRecord key, DSResourceRecord ds){ if(key.getAlgorithm() == ds.getAlgorithm() && key.getKeytag() == ds.getKeytag() && key.getName().equalsIgnoreCase(ds.getName()) ){ return true; } return false; } }
DNSBelgium/qlad
entrada/dnslib4java/src/main/java/nl/sidn/dnslib/util/KeyUtil.java
1,510
// als de publieke sleuten met RSA/MD5 is gemaakt en gehashed dan
line_comment
nl
/* * ENTRADA, a big data platform for network data analytics * * Copyright (C) 2016 SIDN [https://www.sidn.nl] * * This file is part of ENTRADA. * * ENTRADA 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. * * ENTRADA 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 ENTRADA. If not, see [<http://www.gnu.org/licenses/]. * */ package nl.sidn.dnslib.util; import java.math.BigInteger; import java.nio.ByteBuffer; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.RSAPublicKeySpec; import nl.sidn.dnslib.message.records.dnssec.DNSKEYResourceRecord; import nl.sidn.dnslib.message.records.dnssec.DSResourceRecord; public class KeyUtil { private static char KEY_ZONE_FLAG_MASK = 0x0100; //0000 0001 0000 0000 private static char KEY_ZONE_SEP_FLAG_MASK = 0x0101; //0000 0001 0000 0001 public static PublicKey createRSAPublicKey(byte[] key) { ByteBuffer b = ByteBuffer.wrap(key); int exponentLength = b.get() & 0xff; if (exponentLength == 0){ exponentLength = b.getChar(); } try { byte [] data = new byte[exponentLength]; b.get(data); BigInteger exponent = new BigInteger(1, data); byte [] modulusData = new byte[b.remaining()]; b.get(modulusData); BigInteger modulus = new BigInteger(1, modulusData); KeyFactory factory = KeyFactory.getInstance("RSA"); return factory.generatePublic(new RSAPublicKeySpec(modulus, exponent)); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { throw new RuntimeException("Error creating public key", e); } } /** * Bereken de keyTag(footprint) van een publieke sleutel. * De keyTag berekent een getal waarmee de publieke sleutel te herkennen is, dit is * niet per definitie uniek per publieke sleutel. * Zie IETF RFC 4034, Appendix B voor meer informatie. * @see http://www.ietf.org/rfc/rfc4034.txt * * Dit lijkt op het berekenen van 1 complement checksum (http://nl.wikipedia.org/wiki/One%27s_complement) * De onderstaande implementatie is overgenomen van versisign, zie: * http://svn.verisignlabs.com/jdnssec/dnsjava/trunk/org/xbill/DNS/KEYBase.java * @param key een base64 encoded public key * @param algorimte, de naam van het algoritme waarmee de public key is gemaakt. * @return integer waarde welke de keytag van de public key is */ public static int createKeyTag(byte[] rdata, int alg) { int foot = 0; int footprint = -1; // als de<SUF> // geld er een ander algoritme voor bepalen keytag if (1 == alg) { //MD5 int d1 = rdata[rdata.length - 3] & 0xFF; int d2 = rdata[rdata.length - 2] & 0xFF; foot = (d1 << 8) + d2; } else { int i; for (i = 0; i < rdata.length - 1; i += 2) { int d1 = rdata[i] & 0xFF; int d2 = rdata[i + 1] & 0xFF; foot += ((d1 << 8) + d2); } if (i < rdata.length) { int d1 = rdata[i] & 0xFF; foot += (d1 << 8); } foot += ((foot >> 16) & 0xFFFF); } footprint = (foot & 0xFFFF); return footprint; } public static boolean isZoneKey(DNSKEYResourceRecord key){ return (key.getFlags() & KEY_ZONE_FLAG_MASK) == KEY_ZONE_FLAG_MASK; } public static boolean isSepKey(DNSKEYResourceRecord key){ return (key.getFlags() & KEY_ZONE_SEP_FLAG_MASK) == KEY_ZONE_SEP_FLAG_MASK; } public static boolean isKeyandDSmatch(DNSKEYResourceRecord key, DSResourceRecord ds){ if(key.getAlgorithm() == ds.getAlgorithm() && key.getKeytag() == ds.getKeytag() && key.getName().equalsIgnoreCase(ds.getName()) ){ return true; } return false; } }
153646_5
// Copyright (C) 2010-2013 DOV, http://dov.vlaanderen.be/ // All rights reserved package be.vlaanderen.dov.services.xmlimport.dto; import java.util.Date; import java.util.HashSet; import java.util.Set; /** * Data transfer object that represents the InvoerLog pojo. * * @author DEBAETSP */ public final class UploadRequest { private String id; private String omschrijving; private String gebruikersnaam; private Date datumOpladen; private UploadedFile bestand; private Date datumProcessed; private Set<UploadOption> options = new HashSet<UploadOption>(); private int aantalVerwerkt; private int aantalFouten; private String partner; private Code invoerwijze; private Code status; /** * simple getter for dto. * * @return the gebruikersnaam */ public String getGebruikersnaam() { return gebruikersnaam; } /** * simple setter for dto. * * @param gebruikersnaam the gebruikersnaam to set */ public void setGebruikersnaam(String gebruikersnaam) { this.gebruikersnaam = gebruikersnaam; } /** * simple setter for dto. * * @param omschrijving the omschrijving to set */ public void setOmschrijving(String omschrijving) { this.omschrijving = omschrijving; } /** * simple getter for dto. * * @return the omschrijving */ public String getOmschrijving() { return omschrijving; } /** * simple getter for dto. * * @return the datumOpladen */ public Date getDatumOpladen() { if (datumOpladen != null) { return (Date) datumOpladen.clone(); } return null; } /** * simple setter for dto. * * @param datumOpladen the datumOpladen to set */ public void setDatumOpladen(Date datumOpladen) { this.datumOpladen = null; if (datumOpladen != null) { this.datumOpladen = (Date) datumOpladen.clone(); } } /** * simple setter for dto. * * @param datumProcessed the datumProcessed to set */ public void setDatumProcessed(Date datumProcessed) { this.datumProcessed = null; if (datumProcessed != null) { this.datumProcessed = (Date) datumProcessed.clone(); } } /** * simple getter for dto. * * @return the datumProcessed */ public Date getDatumProcessed() { if (datumProcessed != null) { return (Date) datumProcessed.clone(); } return null; } /** * simple getter for DTO. * * @return the partner */ public String getPartner() { return partner; } /** * simple getter for dto. * * @return the aantalVerwerkt */ public int getAantalVerwerkt() { return aantalVerwerkt; } /** * simple setter for dto. * * @param aantalVerwerkt the aantalVerwerkt to set */ public void setAantalVerwerkt(int aantalVerwerkt) { this.aantalVerwerkt = aantalVerwerkt; } /** * simple getter for dto. * * @return the aantalFouten */ public int getAantalFouten() { return aantalFouten; } /** * simple setter for dto. * * @param aantalFouten the aantalFouten to set */ public void setAantalFouten(int aantalFouten) { this.aantalFouten = aantalFouten; } /** * simple setter for dto. * * @param partner the partner to set */ public void setPartner(String partner) { this.partner = partner; } /** * simple getter for dto. * * @return the options */ public Set<UploadOption> getOptions() { return options; } /** * simple setter for dto. * * @param options the options to set */ public void setOptions(Set<UploadOption> options) { this.options = options; } public UploadedFile getBestand() { return bestand; } public void setBestand(UploadedFile bestand) { this.bestand = bestand; } public Code getInvoerwijze() { return invoerwijze; } public void setInvoerwijze(Code invoerwijze) { this.invoerwijze = invoerwijze; } public Code getStatus() { return status; } public void setStatus(Code status) { this.status = status; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
DOV-Vlaanderen/dov-services-quickstart
xmlimport/src/main/java/be/vlaanderen/dov/services/xmlimport/dto/UploadRequest.java
1,509
/** * simple setter for dto. * * @param omschrijving the omschrijving to set */
block_comment
nl
// Copyright (C) 2010-2013 DOV, http://dov.vlaanderen.be/ // All rights reserved package be.vlaanderen.dov.services.xmlimport.dto; import java.util.Date; import java.util.HashSet; import java.util.Set; /** * Data transfer object that represents the InvoerLog pojo. * * @author DEBAETSP */ public final class UploadRequest { private String id; private String omschrijving; private String gebruikersnaam; private Date datumOpladen; private UploadedFile bestand; private Date datumProcessed; private Set<UploadOption> options = new HashSet<UploadOption>(); private int aantalVerwerkt; private int aantalFouten; private String partner; private Code invoerwijze; private Code status; /** * simple getter for dto. * * @return the gebruikersnaam */ public String getGebruikersnaam() { return gebruikersnaam; } /** * simple setter for dto. * * @param gebruikersnaam the gebruikersnaam to set */ public void setGebruikersnaam(String gebruikersnaam) { this.gebruikersnaam = gebruikersnaam; } /** * simple setter for<SUF>*/ public void setOmschrijving(String omschrijving) { this.omschrijving = omschrijving; } /** * simple getter for dto. * * @return the omschrijving */ public String getOmschrijving() { return omschrijving; } /** * simple getter for dto. * * @return the datumOpladen */ public Date getDatumOpladen() { if (datumOpladen != null) { return (Date) datumOpladen.clone(); } return null; } /** * simple setter for dto. * * @param datumOpladen the datumOpladen to set */ public void setDatumOpladen(Date datumOpladen) { this.datumOpladen = null; if (datumOpladen != null) { this.datumOpladen = (Date) datumOpladen.clone(); } } /** * simple setter for dto. * * @param datumProcessed the datumProcessed to set */ public void setDatumProcessed(Date datumProcessed) { this.datumProcessed = null; if (datumProcessed != null) { this.datumProcessed = (Date) datumProcessed.clone(); } } /** * simple getter for dto. * * @return the datumProcessed */ public Date getDatumProcessed() { if (datumProcessed != null) { return (Date) datumProcessed.clone(); } return null; } /** * simple getter for DTO. * * @return the partner */ public String getPartner() { return partner; } /** * simple getter for dto. * * @return the aantalVerwerkt */ public int getAantalVerwerkt() { return aantalVerwerkt; } /** * simple setter for dto. * * @param aantalVerwerkt the aantalVerwerkt to set */ public void setAantalVerwerkt(int aantalVerwerkt) { this.aantalVerwerkt = aantalVerwerkt; } /** * simple getter for dto. * * @return the aantalFouten */ public int getAantalFouten() { return aantalFouten; } /** * simple setter for dto. * * @param aantalFouten the aantalFouten to set */ public void setAantalFouten(int aantalFouten) { this.aantalFouten = aantalFouten; } /** * simple setter for dto. * * @param partner the partner to set */ public void setPartner(String partner) { this.partner = partner; } /** * simple getter for dto. * * @return the options */ public Set<UploadOption> getOptions() { return options; } /** * simple setter for dto. * * @param options the options to set */ public void setOptions(Set<UploadOption> options) { this.options = options; } public UploadedFile getBestand() { return bestand; } public void setBestand(UploadedFile bestand) { this.bestand = bestand; } public Code getInvoerwijze() { return invoerwijze; } public void setInvoerwijze(Code invoerwijze) { this.invoerwijze = invoerwijze; } public Code getStatus() { return status; } public void setStatus(Code status) { this.status = status; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
28220_12
package oplossing; import opgave.SearchTree; import java.util.Iterator; import java.util.LinkedList; public class TopDownSemiSplayTwoThreeTree <E extends Comparable<E>> implements SearchTree<E> { Node<E> root = null; int nodeCount = 0; @Override public int size() { return nodeCount; } @Override public boolean isEmpty() { return nodeCount == 0; } @Override public boolean contains(E o) { //check of gereturnde node null is Node<E> node = containsRecursive(o, root); if(node != null){ splay(root, o); return true; } else{ return false; } } @Override public boolean add(E newVal) { if(root == null){ root = new Node<E>(newVal); nodeCount++; return true; } if(containsRecursive(newVal, root) != null){ return false; } nodeCount++; Node<E> leaf = findLeaf(root, newVal); if(leaf.getKey2() == null){ if(newVal.compareTo(leaf.getKey1()) == 1){ leaf.setKeys(leaf.getKey1(), newVal); } else { leaf.setKeys(newVal, leaf.getKey1()); } leaf.rebalanceChildren(); splay(root, newVal); } else{ Node<E> newLeaf = new Node<E>(newVal); leaf.addChild(newLeaf); splay(root, newVal); } return true; } public boolean remove(E e) { Node<E> node = containsRecursive(e, root); if(node == null){ return false; } E toSplay = null; nodeCount--; Boolean rootCheck = node == root; //als het een leaf is kunnen we de waarde er gewoon uithalen if(node.getChild1() == null && node.getChild2() == null && node.getChild3() == null){ if(node.getKey2() == null){ if(rootCheck){ root = null; return true; } node.getParent().removeChild(node); } node.removeValue(e); if(rootCheck){ return true; } splay(root, node.getParent().getKey1()); return true; } if(node.getKey2() == null){ if (node.getChild1() == null){ if (node == root){ root = node.getChild3(); root.setParent(null); } else { node.getParent().addChild(node.getChild3()); } } else if (node.getChild3() == null){ if (node == root){ root = node.getChild1(); root.setParent(null); } else { node.getParent().addChild(node.getChild1()); } } else { //heeft 2 kinderen //we vervangen hier de verwijderde top door de 1e sleutel van het kleinste rechterblad Node<E> smallestRightNode = smallestRightChild (node); node.setKeys(smallestRightNode.getKey1(), null); if (smallestRightNode.getKey2() == null){ smallestRightNode.getParent().removeChild(smallestRightNode); smallestRightNode.getParent().addChild(smallestRightNode.getChild3()); splay(root, smallestRightNode.getParent().getKey1()); } else { smallestRightNode.setKeys(smallestRightNode.getKey2(), null); smallestRightNode.rebalanceChildren(); splay(root, smallestRightNode.getParent().getKey1()); } return true; } } else { int amountOfChildren = node.getAmountOfChildren(); Node<E> child1 = node.getChild1(); Node<E> child2 = node.getChild2(); Node<E> child3 = node.getChild3(); if (amountOfChildren == 2){ if (e.equals(node.getKey1())){ if(node.getChild3() == null){ Node<E> smallesMiddleChild = smallestRightChildRecursive(child2); node.setKeys(smallesMiddleChild.getKey1(), node.getKey2()); if(smallesMiddleChild.getKey2() == null){ smallesMiddleChild.getParent().removeChild(smallesMiddleChild); smallesMiddleChild.getParent().addChild(smallesMiddleChild.getChild3()); } else{ smallesMiddleChild.setKeys(smallesMiddleChild.getKey2(), null); smallesMiddleChild.rebalanceChildren(); } } else { node.setKeys(node.getKey2(), null); node.rebalanceChildren(); } } else { if(node.getChild1() == null){ Node<E> largestMiddleChild = largestLeftChildRecursive(child2); if(largestMiddleChild.getKey2() == null){ node.setKeys(node.getKey1(), largestMiddleChild.getKey1()); largestMiddleChild.getParent().removeChild(largestMiddleChild); largestMiddleChild.getParent().addChild(largestMiddleChild.getChild1()); } else{ node.setKeys(node.getKey1(), largestMiddleChild.getKey2()); largestMiddleChild.setKeys(largestMiddleChild.getKey1(), null); largestMiddleChild.rebalanceChildren(); } } else{ node.setKeys(node.getKey1(), null); node.rebalanceChildren(); } } return true; } else if (amountOfChildren == 1){ if (e.equals(node.getKey1())){ node.setKeys(node.getKey2(), null); } else { node.setKeys(node.getKey1(), null); } node.rebalanceChildren(); } else { Node<E> replacementNode = null; Node<E> extraChild = null; if(e.equals(node.getKey1())){ replacementNode = largestLeftChild(node); extraChild = replacementNode.getChild1(); } else{ replacementNode = smallestRightChild(node); extraChild = replacementNode.getChild3(); } if (replacementNode.getKey2() == null){ if(e.equals(node.getKey1())) { node.setKeys(replacementNode.getKey1(), node.getKey2()); } else { node.setKeys(node.getKey1(), replacementNode.getKey1()); } replacementNode.getParent().removeChild(replacementNode); replacementNode.getParent().addChild(extraChild); } else { if(e.equals(node.getKey1())) { node.setKeys(replacementNode.getKey2(), node.getKey2()); replacementNode.setKeys(replacementNode.getKey1(), null); replacementNode.rebalanceChildren(); } else { node.setKeys(node.getKey1(), replacementNode.getKey1()); replacementNode.setKeys(replacementNode.getKey2(), null); replacementNode.rebalanceChildren(); } } splay(root, replacementNode.getParent().getKey1()); return true; } } if (!rootCheck){ splay(root, node.getKey1()); } return true; } public Node<E> smallestRightChild (Node<E> node) { return smallestRightChildRecursive(node.getChild3()); } public Node<E> smallestRightChildRecursive (Node<E> node) { if(node.getChild1() == null){ return node; } return smallestRightChildRecursive(node.getChild1()); } public Node<E> largestLeftChild (Node<E> node) { return largestLeftChildRecursive(node.getChild1()); } public Node<E> largestLeftChildRecursive (Node<E> node) { if(node.getChild3() == null){ return node; } return largestLeftChildRecursive(node.getChild3()); } public void splay(Node<E> grandParent, E keyValue){ //contains checked of de node zelf of 1 van zijn kinderen de value bevat if(root.contains(keyValue)){ return; } //it's splay time //eerst maak ik een normale splay die geen toppen gaat herverdelen etc Node<E> parent = grandParent.getChild(grandParent.whatChild(keyValue)); if(parent == null || parent.getChild(parent.whatChild(keyValue)) == null){ return; } Boolean rootCheck = grandParent == root; Node<E> val = parent.getChild(parent.whatChild(keyValue)); Node<E> newTop = new Node<>(null); Node<E> greatGrandParent = grandParent.getParent(); //neem key 1 maar zou normaal nog steeds moeten kloppen //stel is kind1 if(parent.whatChild(val.getKey1()) == 1){ //checken op welke positie onze parent staat tegenover zijn parent //als kind 1 if(grandParent.whatChild(parent.getKey1()) == 1){ newTop.setKeys(parent.getKey1(), parent.getKey2()); newTop.addChild(parent.getChild2()); grandParent.removeChild(grandParent.getChild1()); grandParent.addChild(parent.getChild3()); newTop.addChild(grandParent); newTop.addChild(val); } //als 2e kind if(grandParent.whatChild(parent.getKey1()) == 2){ newTop.setKeys(parent.getKey1(), parent.getKey2()); newTop.addChild(parent.getChild2()); Node<E> leftGrandChild = new Node<>(grandParent.getKey1()); leftGrandChild.addChild(grandParent.getChild1()); leftGrandChild.addChild(val.getChild1()); val.addChild(leftGrandChild); newTop.addChild(val); Node<E> rightChild = new Node<>(grandParent.getKey2()); rightChild.addChild(parent.getChild3()); rightChild.addChild(grandParent.getChild3()); newTop.addChild(rightChild); } //als 3e kind if(grandParent.whatChild(parent.getKey1()) == 3){ newTop.setKeys(val.getKey1(), val.getKey2()); newTop.addChild(val.getChild2()); grandParent.removeChild(grandParent.getChild3()); grandParent.addChild(val.getChild1()); newTop.addChild(grandParent); parent.removeChild(parent.getChild1()); parent.addChild(val.getChild3()); newTop.addChild(parent); } } if(parent.whatChild(val.getKey1()) == 2){ if(grandParent.whatChild(parent.getKey1()) == 1){ newTop.setKeys(parent.getKey1(), parent.getKey2()); grandParent.removeChild(grandParent.getChild1()); grandParent.addChild(parent.getChild3()); newTop.addChild(grandParent); newTop.addChild(val); newTop.addChild(parent.getChild1()); } if(grandParent.whatChild(parent.getKey1()) == 2){ Node<E> leftChild = new Node<>(grandParent.getKey1()); Node<E> rightChild = new Node<>(grandParent.getKey2()); leftChild.addChild(grandParent.getChild1()); leftChild.addChild(parent.getChild1()); rightChild.addChild(grandParent.getChild3()); rightChild.addChild(parent.getChild3()); parent.addChild(leftChild); parent.addChild(rightChild); newTop = parent; } if(grandParent.whatChild(parent.getKey1()) == 3){ if(parent.getChild1() == null){ grandParent.removeChild(grandParent.getChild3()); parent.addChild(grandParent); newTop = parent; } else{ newTop.setKeys(parent.getChild1().getKey1(), parent.getChild1().getKey2()); newTop.addChild(parent.getChild1().getChild2()); grandParent.removeChild(grandParent.getChild3()); grandParent.addChild(parent.getChild1().getChild1()); newTop.addChild(grandParent); if(parent.getChild1().getChild3() != null) { parent.addChild(parent.getChild1().getChild3()); } else { parent.removeChild(parent.getChild1()); } newTop.addChild(parent); } } } if(parent.whatChild(val.getKey1()) == 3){ if(grandParent.whatChild(parent.getKey1()) == 1){ newTop.setKeys(val.getKey1(), val.getKey2()); parent.removeChild(parent.getChild3()); parent.addChild(val.getChild1()); newTop.addChild(parent); newTop.addChild(val.getChild2()); grandParent.removeChild(grandParent.getChild1()); grandParent.addChild(val.getChild3()); newTop.addChild(grandParent); } if(grandParent.whatChild(parent.getKey1()) == 2){ if(parent.getKey2() == null){ newTop.setKeys(parent.getKey1(), grandParent.getKey2()); newTop.addChild(val); Node<E> leftChild = new Node<>(grandParent.getKey1()); leftChild.addChild(grandParent.getChild1()); leftChild.addChild(parent.getChild1()); newTop.addChild(leftChild); newTop.addChild(grandParent.getChild3()); } else{ newTop.setKeys(parent.getKey2(), grandParent.getKey2()); newTop.addChild(val); Node<E> leftChild = new Node<>(null); leftChild.setKeys(grandParent.getKey1(), parent.getKey1()); leftChild.addChild(parent.getChild1()); leftChild.addChild(grandParent.getChild1()); leftChild.addChild(parent.getChild2()); newTop.addChild(leftChild); newTop.addChild(grandParent.getChild3()); } } if(grandParent.whatChild(parent.getKey1()) == 3){ newTop.setKeys(parent.getKey1(), parent.getKey2()); newTop.addChild(parent.getChild2()); grandParent.removeChild(grandParent.getChild3()); grandParent.addChild(parent.getChild1()); newTop.addChild(grandParent); newTop.addChild(val); } } if(rootCheck){ root = newTop; root.setParent(null); } else{ greatGrandParent.addChild(newTop); } if(val.getKey1().equals(keyValue)|| (val.getKey2() != null && val.getKey2().equals(keyValue))){ return; } if(newTop.getKey1() == null){ System.out.println("hey"); } splay(newTop.getChild(newTop.whatChild(keyValue)), keyValue); } //recursieve methode waar we gewoon van een andere node als zogezegde wortel voort gaan zoeken, returned dan gezochte node public Node<E> containsRecursive(E o, Node<E> subRoot){ if(subRoot == null){ return null; } if(o.equals(subRoot.getKey1())|| (subRoot.getKey2() != null && o.equals(subRoot.getKey2()))){ return subRoot; } return containsRecursive(o, subRoot.getChild(subRoot.whatChild(o))); } //recursieve methode, ga knopen af tot hij degene vindt die geen kinderen heeft public Node<E> findLeaf(Node<E> node, E newVal){ int childNr = node.whatChild(newVal); if(node.getChild(childNr) == null){ return node; } return findLeaf(node.getChild(node.whatChild(newVal)), newVal); } @Override public void clear(){ root = null; nodeCount = 0; } @Override public Iterator iterator() { return dfs().iterator(); } public LinkedList<Comparable> dfs(){ LinkedList<Comparable> list = new LinkedList<>(); list = recursiveList(root, list); return list; } public LinkedList<Comparable> recursiveList(Node<E> node, LinkedList<Comparable> list) { if (node == null) return list; //links recursie list = recursiveList(node.getChild1(), list); //node toevoegen list.add(node.getKey1()); //evt middenrecursie if(node.getKey2() != null){ list = recursiveList(node.getChild2(), list); list.add(node.getKey2()); } //rechtsrecursei list = recursiveList(node.getChild3(), list); return list; } }
DRIESASTER/Semi_Splay_2-3_Tree
src/oplossing/TopDownSemiSplayTwoThreeTree.java
4,905
//als 3e kind
line_comment
nl
package oplossing; import opgave.SearchTree; import java.util.Iterator; import java.util.LinkedList; public class TopDownSemiSplayTwoThreeTree <E extends Comparable<E>> implements SearchTree<E> { Node<E> root = null; int nodeCount = 0; @Override public int size() { return nodeCount; } @Override public boolean isEmpty() { return nodeCount == 0; } @Override public boolean contains(E o) { //check of gereturnde node null is Node<E> node = containsRecursive(o, root); if(node != null){ splay(root, o); return true; } else{ return false; } } @Override public boolean add(E newVal) { if(root == null){ root = new Node<E>(newVal); nodeCount++; return true; } if(containsRecursive(newVal, root) != null){ return false; } nodeCount++; Node<E> leaf = findLeaf(root, newVal); if(leaf.getKey2() == null){ if(newVal.compareTo(leaf.getKey1()) == 1){ leaf.setKeys(leaf.getKey1(), newVal); } else { leaf.setKeys(newVal, leaf.getKey1()); } leaf.rebalanceChildren(); splay(root, newVal); } else{ Node<E> newLeaf = new Node<E>(newVal); leaf.addChild(newLeaf); splay(root, newVal); } return true; } public boolean remove(E e) { Node<E> node = containsRecursive(e, root); if(node == null){ return false; } E toSplay = null; nodeCount--; Boolean rootCheck = node == root; //als het een leaf is kunnen we de waarde er gewoon uithalen if(node.getChild1() == null && node.getChild2() == null && node.getChild3() == null){ if(node.getKey2() == null){ if(rootCheck){ root = null; return true; } node.getParent().removeChild(node); } node.removeValue(e); if(rootCheck){ return true; } splay(root, node.getParent().getKey1()); return true; } if(node.getKey2() == null){ if (node.getChild1() == null){ if (node == root){ root = node.getChild3(); root.setParent(null); } else { node.getParent().addChild(node.getChild3()); } } else if (node.getChild3() == null){ if (node == root){ root = node.getChild1(); root.setParent(null); } else { node.getParent().addChild(node.getChild1()); } } else { //heeft 2 kinderen //we vervangen hier de verwijderde top door de 1e sleutel van het kleinste rechterblad Node<E> smallestRightNode = smallestRightChild (node); node.setKeys(smallestRightNode.getKey1(), null); if (smallestRightNode.getKey2() == null){ smallestRightNode.getParent().removeChild(smallestRightNode); smallestRightNode.getParent().addChild(smallestRightNode.getChild3()); splay(root, smallestRightNode.getParent().getKey1()); } else { smallestRightNode.setKeys(smallestRightNode.getKey2(), null); smallestRightNode.rebalanceChildren(); splay(root, smallestRightNode.getParent().getKey1()); } return true; } } else { int amountOfChildren = node.getAmountOfChildren(); Node<E> child1 = node.getChild1(); Node<E> child2 = node.getChild2(); Node<E> child3 = node.getChild3(); if (amountOfChildren == 2){ if (e.equals(node.getKey1())){ if(node.getChild3() == null){ Node<E> smallesMiddleChild = smallestRightChildRecursive(child2); node.setKeys(smallesMiddleChild.getKey1(), node.getKey2()); if(smallesMiddleChild.getKey2() == null){ smallesMiddleChild.getParent().removeChild(smallesMiddleChild); smallesMiddleChild.getParent().addChild(smallesMiddleChild.getChild3()); } else{ smallesMiddleChild.setKeys(smallesMiddleChild.getKey2(), null); smallesMiddleChild.rebalanceChildren(); } } else { node.setKeys(node.getKey2(), null); node.rebalanceChildren(); } } else { if(node.getChild1() == null){ Node<E> largestMiddleChild = largestLeftChildRecursive(child2); if(largestMiddleChild.getKey2() == null){ node.setKeys(node.getKey1(), largestMiddleChild.getKey1()); largestMiddleChild.getParent().removeChild(largestMiddleChild); largestMiddleChild.getParent().addChild(largestMiddleChild.getChild1()); } else{ node.setKeys(node.getKey1(), largestMiddleChild.getKey2()); largestMiddleChild.setKeys(largestMiddleChild.getKey1(), null); largestMiddleChild.rebalanceChildren(); } } else{ node.setKeys(node.getKey1(), null); node.rebalanceChildren(); } } return true; } else if (amountOfChildren == 1){ if (e.equals(node.getKey1())){ node.setKeys(node.getKey2(), null); } else { node.setKeys(node.getKey1(), null); } node.rebalanceChildren(); } else { Node<E> replacementNode = null; Node<E> extraChild = null; if(e.equals(node.getKey1())){ replacementNode = largestLeftChild(node); extraChild = replacementNode.getChild1(); } else{ replacementNode = smallestRightChild(node); extraChild = replacementNode.getChild3(); } if (replacementNode.getKey2() == null){ if(e.equals(node.getKey1())) { node.setKeys(replacementNode.getKey1(), node.getKey2()); } else { node.setKeys(node.getKey1(), replacementNode.getKey1()); } replacementNode.getParent().removeChild(replacementNode); replacementNode.getParent().addChild(extraChild); } else { if(e.equals(node.getKey1())) { node.setKeys(replacementNode.getKey2(), node.getKey2()); replacementNode.setKeys(replacementNode.getKey1(), null); replacementNode.rebalanceChildren(); } else { node.setKeys(node.getKey1(), replacementNode.getKey1()); replacementNode.setKeys(replacementNode.getKey2(), null); replacementNode.rebalanceChildren(); } } splay(root, replacementNode.getParent().getKey1()); return true; } } if (!rootCheck){ splay(root, node.getKey1()); } return true; } public Node<E> smallestRightChild (Node<E> node) { return smallestRightChildRecursive(node.getChild3()); } public Node<E> smallestRightChildRecursive (Node<E> node) { if(node.getChild1() == null){ return node; } return smallestRightChildRecursive(node.getChild1()); } public Node<E> largestLeftChild (Node<E> node) { return largestLeftChildRecursive(node.getChild1()); } public Node<E> largestLeftChildRecursive (Node<E> node) { if(node.getChild3() == null){ return node; } return largestLeftChildRecursive(node.getChild3()); } public void splay(Node<E> grandParent, E keyValue){ //contains checked of de node zelf of 1 van zijn kinderen de value bevat if(root.contains(keyValue)){ return; } //it's splay time //eerst maak ik een normale splay die geen toppen gaat herverdelen etc Node<E> parent = grandParent.getChild(grandParent.whatChild(keyValue)); if(parent == null || parent.getChild(parent.whatChild(keyValue)) == null){ return; } Boolean rootCheck = grandParent == root; Node<E> val = parent.getChild(parent.whatChild(keyValue)); Node<E> newTop = new Node<>(null); Node<E> greatGrandParent = grandParent.getParent(); //neem key 1 maar zou normaal nog steeds moeten kloppen //stel is kind1 if(parent.whatChild(val.getKey1()) == 1){ //checken op welke positie onze parent staat tegenover zijn parent //als kind 1 if(grandParent.whatChild(parent.getKey1()) == 1){ newTop.setKeys(parent.getKey1(), parent.getKey2()); newTop.addChild(parent.getChild2()); grandParent.removeChild(grandParent.getChild1()); grandParent.addChild(parent.getChild3()); newTop.addChild(grandParent); newTop.addChild(val); } //als 2e kind if(grandParent.whatChild(parent.getKey1()) == 2){ newTop.setKeys(parent.getKey1(), parent.getKey2()); newTop.addChild(parent.getChild2()); Node<E> leftGrandChild = new Node<>(grandParent.getKey1()); leftGrandChild.addChild(grandParent.getChild1()); leftGrandChild.addChild(val.getChild1()); val.addChild(leftGrandChild); newTop.addChild(val); Node<E> rightChild = new Node<>(grandParent.getKey2()); rightChild.addChild(parent.getChild3()); rightChild.addChild(grandParent.getChild3()); newTop.addChild(rightChild); } //als 3e<SUF> if(grandParent.whatChild(parent.getKey1()) == 3){ newTop.setKeys(val.getKey1(), val.getKey2()); newTop.addChild(val.getChild2()); grandParent.removeChild(grandParent.getChild3()); grandParent.addChild(val.getChild1()); newTop.addChild(grandParent); parent.removeChild(parent.getChild1()); parent.addChild(val.getChild3()); newTop.addChild(parent); } } if(parent.whatChild(val.getKey1()) == 2){ if(grandParent.whatChild(parent.getKey1()) == 1){ newTop.setKeys(parent.getKey1(), parent.getKey2()); grandParent.removeChild(grandParent.getChild1()); grandParent.addChild(parent.getChild3()); newTop.addChild(grandParent); newTop.addChild(val); newTop.addChild(parent.getChild1()); } if(grandParent.whatChild(parent.getKey1()) == 2){ Node<E> leftChild = new Node<>(grandParent.getKey1()); Node<E> rightChild = new Node<>(grandParent.getKey2()); leftChild.addChild(grandParent.getChild1()); leftChild.addChild(parent.getChild1()); rightChild.addChild(grandParent.getChild3()); rightChild.addChild(parent.getChild3()); parent.addChild(leftChild); parent.addChild(rightChild); newTop = parent; } if(grandParent.whatChild(parent.getKey1()) == 3){ if(parent.getChild1() == null){ grandParent.removeChild(grandParent.getChild3()); parent.addChild(grandParent); newTop = parent; } else{ newTop.setKeys(parent.getChild1().getKey1(), parent.getChild1().getKey2()); newTop.addChild(parent.getChild1().getChild2()); grandParent.removeChild(grandParent.getChild3()); grandParent.addChild(parent.getChild1().getChild1()); newTop.addChild(grandParent); if(parent.getChild1().getChild3() != null) { parent.addChild(parent.getChild1().getChild3()); } else { parent.removeChild(parent.getChild1()); } newTop.addChild(parent); } } } if(parent.whatChild(val.getKey1()) == 3){ if(grandParent.whatChild(parent.getKey1()) == 1){ newTop.setKeys(val.getKey1(), val.getKey2()); parent.removeChild(parent.getChild3()); parent.addChild(val.getChild1()); newTop.addChild(parent); newTop.addChild(val.getChild2()); grandParent.removeChild(grandParent.getChild1()); grandParent.addChild(val.getChild3()); newTop.addChild(grandParent); } if(grandParent.whatChild(parent.getKey1()) == 2){ if(parent.getKey2() == null){ newTop.setKeys(parent.getKey1(), grandParent.getKey2()); newTop.addChild(val); Node<E> leftChild = new Node<>(grandParent.getKey1()); leftChild.addChild(grandParent.getChild1()); leftChild.addChild(parent.getChild1()); newTop.addChild(leftChild); newTop.addChild(grandParent.getChild3()); } else{ newTop.setKeys(parent.getKey2(), grandParent.getKey2()); newTop.addChild(val); Node<E> leftChild = new Node<>(null); leftChild.setKeys(grandParent.getKey1(), parent.getKey1()); leftChild.addChild(parent.getChild1()); leftChild.addChild(grandParent.getChild1()); leftChild.addChild(parent.getChild2()); newTop.addChild(leftChild); newTop.addChild(grandParent.getChild3()); } } if(grandParent.whatChild(parent.getKey1()) == 3){ newTop.setKeys(parent.getKey1(), parent.getKey2()); newTop.addChild(parent.getChild2()); grandParent.removeChild(grandParent.getChild3()); grandParent.addChild(parent.getChild1()); newTop.addChild(grandParent); newTop.addChild(val); } } if(rootCheck){ root = newTop; root.setParent(null); } else{ greatGrandParent.addChild(newTop); } if(val.getKey1().equals(keyValue)|| (val.getKey2() != null && val.getKey2().equals(keyValue))){ return; } if(newTop.getKey1() == null){ System.out.println("hey"); } splay(newTop.getChild(newTop.whatChild(keyValue)), keyValue); } //recursieve methode waar we gewoon van een andere node als zogezegde wortel voort gaan zoeken, returned dan gezochte node public Node<E> containsRecursive(E o, Node<E> subRoot){ if(subRoot == null){ return null; } if(o.equals(subRoot.getKey1())|| (subRoot.getKey2() != null && o.equals(subRoot.getKey2()))){ return subRoot; } return containsRecursive(o, subRoot.getChild(subRoot.whatChild(o))); } //recursieve methode, ga knopen af tot hij degene vindt die geen kinderen heeft public Node<E> findLeaf(Node<E> node, E newVal){ int childNr = node.whatChild(newVal); if(node.getChild(childNr) == null){ return node; } return findLeaf(node.getChild(node.whatChild(newVal)), newVal); } @Override public void clear(){ root = null; nodeCount = 0; } @Override public Iterator iterator() { return dfs().iterator(); } public LinkedList<Comparable> dfs(){ LinkedList<Comparable> list = new LinkedList<>(); list = recursiveList(root, list); return list; } public LinkedList<Comparable> recursiveList(Node<E> node, LinkedList<Comparable> list) { if (node == null) return list; //links recursie list = recursiveList(node.getChild1(), list); //node toevoegen list.add(node.getKey1()); //evt middenrecursie if(node.getKey2() != null){ list = recursiveList(node.getChild2(), list); list.add(node.getKey2()); } //rechtsrecursei list = recursiveList(node.getChild3(), list); return list; } }
180494_17
package main.java.algorithms.tsp; import java.util.ArrayList; import main.java.graphs.DistanceGrid; import main.java.graphs.grid.GridTile; import main.java.main.Vector2; //Hungarian not functional AS OF YET public class HungarianAssignment { // Punten lijst private ArrayList<GridTile> coordList; // Route om te tekenen private ArrayList<Vector2> shortestPath = new ArrayList<>(); // Distance Grid klasse private DistanceGrid dG; // uitgerekende route's tussen punten public int[][][] routeTSP; // aantal berkende route's private int berekend; // penalty van zero tabel public double[][] penaltyZero; public HungarianAssignment(ArrayList<GridTile> selectedTiles) { // Zet de geselecteerde vakjes in een lokale arraylist coordList = selectedTiles; // Nieuw DistanceGrid berekenen aan de hand van de coordinaten lijst dG = new DistanceGrid(coordList); // RouteTSP array net zo lang als het aantal punten routeTSP = new int[dG.distanceGrid.length][2][2]; } public double[] getColumn(double[][] grid, int colNumber) { // Pakt de kolom van een 2D Array int rowNumber; double[] colArray = new double[grid.length]; for (rowNumber = 0; rowNumber < grid.length; rowNumber++) { // Zet het kolomnummer in de kolom array colArray[rowNumber] = grid[rowNumber][colNumber]; } return colArray; } public double min(double[] numbers, boolean ignoreFirstZero) { // Pakt het laagste getal in een rij, en krijgt te horen of hij de // eerste nul moet negeren double lowest = 999999999; for (double num : numbers) { if (num < lowest && num != -999.0 && !(ignoreFirstZero && num == 0)) { lowest = num; } else if (ignoreFirstZero && num == 0) { ignoreFirstZero = false; } } return lowest; } public void rowMin() { // Rij minimalisatie int rowCount = 0; for (double[] row : dG.distanceGrid) { int columnCount = 0; double lowest = min(row, false); for (double column : row) { if (column == -999.0) { // TODO Wat als column -999.0 is? } else { dG.distanceGrid[rowCount][columnCount] = column - lowest; } columnCount++; } rowCount++; } } public void columnMin() { for (int colNumber = 0; colNumber < dG.distanceGrid.length; colNumber++) { double[] colArray = getColumn(dG.distanceGrid, colNumber); int rowNumber = 0; double lowest = min(colArray, false); for (double num : colArray) { if (num == -999.0) { // TODO Wat als column -999.0 is? } else { dG.distanceGrid[rowNumber][colNumber] = num - lowest; } rowNumber++; } } } public void penaltyZero() { int rowNumber = 0; double[][] zeroGrid = new double[dG.distanceGrid.length][dG.distanceGrid[0].length]; for (double[] rowPlace : dG.distanceGrid) { int columnNumber = 0; for (double columnPlace : rowPlace) { if (columnPlace == 0.0) { zeroGrid[rowNumber][columnNumber] = min(dG.distanceGrid[rowNumber], true) + min(getColumn(dG.distanceGrid, columnNumber), true); } columnNumber++; } rowNumber++; } penaltyZero = zeroGrid; } public void reducegrid() { double[][] newDistanceGrid; int from = 999; int to = 999; double lowestNumber = 999999; int rowNumber = 0; for (double[] rowPlace : dG.distanceGrid) { int columnNumber = 0; for (double columnPlace : rowPlace) { // TODO Geen System.out.println! alleen voor testen if (columnPlace == 0.0 && penaltyZero[rowNumber][columnNumber] < lowestNumber) { lowestNumber = penaltyZero[rowNumber][columnNumber]; from = columnNumber; to = rowNumber; } columnNumber++; } rowNumber++; } rowNumber = 0; newDistanceGrid = new double[dG.distanceGrid.length][dG.distanceGrid.length]; for (double[] rowPlace : dG.distanceGrid) { int columnNumber = 0; for (double columnPlace : rowPlace) { if ((columnNumber == from || rowNumber == to) || (columnNumber == to && rowNumber == from)) { newDistanceGrid[rowNumber][columnNumber] = -999; columnNumber++; } else { newDistanceGrid[rowNumber][columnNumber] = columnPlace; columnNumber++; } } rowNumber++; } // from is de index van het begin punt if(from==999||to==999) {}else { routeTSP[berekend][0][0] = coordList.get(from).getXcoord(); routeTSP[berekend][0][1] = coordList.get(from).getYcoord(); routeTSP[berekend][1][0] = coordList.get(to).getXcoord(); routeTSP[berekend][1][1] = coordList.get(to).getYcoord(); } if(from==999||to==999) { }else{ shortestPath.add(new Vector2(coordList.get(from).getXcoord(),coordList.get(from).getYcoord())); shortestPath.add(new Vector2(coordList.get(to).getXcoord(), coordList.get(to).getYcoord())); } berekend++; dG.distanceGrid = newDistanceGrid; } public ArrayList<Vector2> runHungarian() { for (int i = 0; i < dG.distanceGrid.length; i++) { rowMin(); columnMin(); penaltyZero(); reducegrid(); printPath(); printDGrid(); System.out.println(); System.out.println("----------------------------"); } System.out.println(shortestPath.toString()); return shortestPath; } private void printDGrid() { for (double[] row : dG.distanceGrid) { for (double column : row) { // TODO Geen System.out.println! alleen voor testen System.out.print(column); } System.out.println(); } } private void printPath(){ int puntC=0; for(int[][] punt:routeTSP){ puntC++; int fromToC=0; for(int[] fromTo:punt){ fromToC++; int xyC = 0; for(int xy: fromTo) { xyC++; System.out.println(String.format("%s | %s | %s",puntC,fromToC,xy)); } } } } }
DSW01-1/JavaApplicatie
src/main/java/algorithms/tsp/HungarianAssignment.java
2,125
// TODO Geen System.out.println! alleen voor testen
line_comment
nl
package main.java.algorithms.tsp; import java.util.ArrayList; import main.java.graphs.DistanceGrid; import main.java.graphs.grid.GridTile; import main.java.main.Vector2; //Hungarian not functional AS OF YET public class HungarianAssignment { // Punten lijst private ArrayList<GridTile> coordList; // Route om te tekenen private ArrayList<Vector2> shortestPath = new ArrayList<>(); // Distance Grid klasse private DistanceGrid dG; // uitgerekende route's tussen punten public int[][][] routeTSP; // aantal berkende route's private int berekend; // penalty van zero tabel public double[][] penaltyZero; public HungarianAssignment(ArrayList<GridTile> selectedTiles) { // Zet de geselecteerde vakjes in een lokale arraylist coordList = selectedTiles; // Nieuw DistanceGrid berekenen aan de hand van de coordinaten lijst dG = new DistanceGrid(coordList); // RouteTSP array net zo lang als het aantal punten routeTSP = new int[dG.distanceGrid.length][2][2]; } public double[] getColumn(double[][] grid, int colNumber) { // Pakt de kolom van een 2D Array int rowNumber; double[] colArray = new double[grid.length]; for (rowNumber = 0; rowNumber < grid.length; rowNumber++) { // Zet het kolomnummer in de kolom array colArray[rowNumber] = grid[rowNumber][colNumber]; } return colArray; } public double min(double[] numbers, boolean ignoreFirstZero) { // Pakt het laagste getal in een rij, en krijgt te horen of hij de // eerste nul moet negeren double lowest = 999999999; for (double num : numbers) { if (num < lowest && num != -999.0 && !(ignoreFirstZero && num == 0)) { lowest = num; } else if (ignoreFirstZero && num == 0) { ignoreFirstZero = false; } } return lowest; } public void rowMin() { // Rij minimalisatie int rowCount = 0; for (double[] row : dG.distanceGrid) { int columnCount = 0; double lowest = min(row, false); for (double column : row) { if (column == -999.0) { // TODO Wat als column -999.0 is? } else { dG.distanceGrid[rowCount][columnCount] = column - lowest; } columnCount++; } rowCount++; } } public void columnMin() { for (int colNumber = 0; colNumber < dG.distanceGrid.length; colNumber++) { double[] colArray = getColumn(dG.distanceGrid, colNumber); int rowNumber = 0; double lowest = min(colArray, false); for (double num : colArray) { if (num == -999.0) { // TODO Wat als column -999.0 is? } else { dG.distanceGrid[rowNumber][colNumber] = num - lowest; } rowNumber++; } } } public void penaltyZero() { int rowNumber = 0; double[][] zeroGrid = new double[dG.distanceGrid.length][dG.distanceGrid[0].length]; for (double[] rowPlace : dG.distanceGrid) { int columnNumber = 0; for (double columnPlace : rowPlace) { if (columnPlace == 0.0) { zeroGrid[rowNumber][columnNumber] = min(dG.distanceGrid[rowNumber], true) + min(getColumn(dG.distanceGrid, columnNumber), true); } columnNumber++; } rowNumber++; } penaltyZero = zeroGrid; } public void reducegrid() { double[][] newDistanceGrid; int from = 999; int to = 999; double lowestNumber = 999999; int rowNumber = 0; for (double[] rowPlace : dG.distanceGrid) { int columnNumber = 0; for (double columnPlace : rowPlace) { // TODO Geen System.out.println! alleen voor testen if (columnPlace == 0.0 && penaltyZero[rowNumber][columnNumber] < lowestNumber) { lowestNumber = penaltyZero[rowNumber][columnNumber]; from = columnNumber; to = rowNumber; } columnNumber++; } rowNumber++; } rowNumber = 0; newDistanceGrid = new double[dG.distanceGrid.length][dG.distanceGrid.length]; for (double[] rowPlace : dG.distanceGrid) { int columnNumber = 0; for (double columnPlace : rowPlace) { if ((columnNumber == from || rowNumber == to) || (columnNumber == to && rowNumber == from)) { newDistanceGrid[rowNumber][columnNumber] = -999; columnNumber++; } else { newDistanceGrid[rowNumber][columnNumber] = columnPlace; columnNumber++; } } rowNumber++; } // from is de index van het begin punt if(from==999||to==999) {}else { routeTSP[berekend][0][0] = coordList.get(from).getXcoord(); routeTSP[berekend][0][1] = coordList.get(from).getYcoord(); routeTSP[berekend][1][0] = coordList.get(to).getXcoord(); routeTSP[berekend][1][1] = coordList.get(to).getYcoord(); } if(from==999||to==999) { }else{ shortestPath.add(new Vector2(coordList.get(from).getXcoord(),coordList.get(from).getYcoord())); shortestPath.add(new Vector2(coordList.get(to).getXcoord(), coordList.get(to).getYcoord())); } berekend++; dG.distanceGrid = newDistanceGrid; } public ArrayList<Vector2> runHungarian() { for (int i = 0; i < dG.distanceGrid.length; i++) { rowMin(); columnMin(); penaltyZero(); reducegrid(); printPath(); printDGrid(); System.out.println(); System.out.println("----------------------------"); } System.out.println(shortestPath.toString()); return shortestPath; } private void printDGrid() { for (double[] row : dG.distanceGrid) { for (double column : row) { // TODO Geen<SUF> System.out.print(column); } System.out.println(); } } private void printPath(){ int puntC=0; for(int[][] punt:routeTSP){ puntC++; int fromToC=0; for(int[] fromTo:punt){ fromToC++; int xyC = 0; for(int xy: fromTo) { xyC++; System.out.println(String.format("%s | %s | %s",puntC,fromToC,xy)); } } } } }
151354_4
/* * ***************************************************************************** * Copyright (C) 2014-2024 Dennis Sheirer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * **************************************************************************** */ package io.github.dsheirer.edac; import io.github.dsheirer.log.LoggingSuppressor; import org.apache.commons.lang3.Validate; import org.apache.commons.math3.util.FastMath; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Berlekemp Massey decoder for primitive RS/BCH block codes * * Original C implementation by Simon Rockliff, 26 June 1991 */ public class BerlekempMassey { private final static Logger mLog = LoggerFactory.getLogger(BerlekempMassey.class); private static final LoggingSuppressor LOGGING_SUPPRESSOR = new LoggingSuppressor(mLog); /* Golay field size GF( 2 ** MM ) */ private int MM; /* Codeword Length: NN = 2 ** MM - 1 */ private int NN; private int MAX_NN; /* Hamming distance between codewords: NN - KK + 1 = 2 * TT + 1 */ private int KK; /* Maximum number of errors that can be corrected */ int TT; int[] alpha_to; int[] index_of; int[] gg; /** * Constructs an instance * * @param galoisFieldSize as a power of 2, e.g. for a GF(2^6) the parameter would be 6 * @param maxCorrectableErrors is Hamming Distance / 2. e.g. RS(24,16,9) would be (24 - 16) / 2, or floor(9/2). * @param generatorPolynomial for the Galois Field represented in binary as 0/1 integers where the array is in * big-endian format. For example: polynomial a6 + a1 + 1 is 1000011, as big endian: 1100001, and in array * form as {1,1,0,0,0,0,1} */ public BerlekempMassey(int galoisFieldSize, int maxCorrectableErrors, int[] generatorPolynomial) { //TODO: fix this MM = galoisFieldSize; NN = (int)FastMath.pow(2, MM) - 1; TT = maxCorrectableErrors; KK = NN - 2 * TT; } public BerlekempMassey(int bitSize, int n, int k, int[] generatorPolynomial) { Validate.isTrue(bitSize == generatorPolynomial.length - 1, "Generator polynomial length must be: bitSize + 1"); MM = bitSize; NN = n; KK = k; TT = (int)Math.floor((NN - KK) / 2); //Since this may be a shortened code, setup arrays to the max size of NN int maxNN = (int)Math.pow(2, MM) - 1; alpha_to = new int[maxNN + 1]; index_of = new int[maxNN + 1]; gg = new int[NN - KK + 1]; generate_gf(generatorPolynomial); gen_poly(); } /** * Generates the Golay Field. * * Generates a GF( 2**mm ) from the irreducible polynomial * p(X) in pp[0]..pp[mm] * * Lookup tables: * index_of[] = polynomial form * alpha_to[] = contains j=alpha**i; * * Polynomial form -> Index form index_of[j=alpha**i] = i * * alpha_to = 2 is the primitive element of GF( 2**mm ) * * @param generator_polynomial */ private void generate_gf(int[] generator_polynomial) { int i; int mask = 1; alpha_to[MM] = 0; for(i = 0; i < MM; i++) { alpha_to[i] = mask; index_of[alpha_to[i]] = i; if(generator_polynomial[i] != 0) { alpha_to[MM] ^= mask; } mask <<= 1; } index_of[alpha_to[MM]] = MM; mask >>= 1; for(i = MM + 1; i < NN; i++) { if(alpha_to[i - 1] >= mask) { alpha_to[i] = alpha_to[MM] ^ ((alpha_to[i - 1] ^ mask) << 1); } else { alpha_to[i] = alpha_to[i - 1] << 1; } index_of[alpha_to[i]] = i; } index_of[0] = -1; } /** * Generates the polynomial for a TT-error correction code. * * Length NN = ( 2 ** MM -1 ) Reed Solomon code from the product of * (X+alpha**i), i=1..2*tt */ private void gen_poly() { int i, j; gg[0] = 2; /* primitive element alpha = 2 for GF(2**mm) */ gg[1] = 1; /* g(x) = (X+alpha) initially */ for(i = 2; i <= (NN - KK); i++) { gg[i] = 1; for(j = i - 1; j > 0; j--) { if(gg[j] != 0) { gg[j] = gg[j - 1] ^ alpha_to[(index_of[gg[j]] + i) % NN]; } else { gg[j] = gg[j - 1]; } } /* gg[0] can never be zero */ gg[0] = alpha_to[(index_of[gg[0]] + i) % NN]; } /* convert gg[] to index form for quicker encoding */ for(i = 0; i <= (NN - KK); i++) { gg[i] = index_of[gg[i]]; } } /** * Decodes * * @param input * @param output * @return */ /* assume we have received bits grouped into mm-bit symbols in recd[i], i=0..(nn-1), and recd[i] is polynomial form. We first compute the 2*tt syndromes by substituting alpha**i into rec(X) and evaluating, storing the syndromes in s[i], i=1..2tt (leave s[0] zero) . Then we use the Berlekamp iteration to find the error location polynomial elp[i]. If the degree of the elp is >tt, we cannot correct all the errors and hence just put out the information symbols uncorrected. If the degree of elp is <=tt, we substitute alpha**i , i=1..n into the elp to get the roots, hence the inverse roots, the error location numbers. If the number of errors located does not equal the degree of the elp, we have more than tt errors and cannot correct them. Otherwise, we then solve for the error value at the error location and correct the error. The procedure is that found in Lin and Costello. For the cases where the number of errors is known to be too large to correct, the information symbols as received are output (the advantage of systematic encoding is that hopefully some of the information symbols will be okay and that if we are in luck, the errors are in the parity part of the transmitted codeword). Of course, these insoluble cases can be returned as error flags to the calling routine if desired. */ public boolean decode(final int[] input, int[] output) //input, output { int u, q; int[][] elp = new int[NN - KK + 2][NN - KK]; int[] d = new int[NN - KK + 2]; int[] l = new int[NN - KK + 2]; int[] u_lu = new int[NN - KK + 2]; int[] s = new int[NN - KK + 1]; int count = 0; boolean syn_error = false; int[] root = new int[TT]; int[] loc = new int[TT]; int[] z = new int[TT + 1]; int[] err = new int[NN]; int[] reg = new int[TT + 1]; boolean irrecoverable_error = false; /* put recd[i] into index form (ie as powers of alpha) */ for(int i = 0; i < NN; i++) { try { output[i] = index_of[input[i]]; } catch(Exception e) { LOGGING_SUPPRESSOR.error(getClass().toString(), 2, "Reed Solomon Decoder error for " + "class [" + getClass() + "] there may be an issue with the message parser class indices - " + "ensure the hex bit values are not larger 63", e); } } /* first form the syndromes */ for(int i = 1; i <= NN - KK; i++) { s[i] = 0; for(int j = 0; j < NN; j++) { if(output[j] != -1) { /* recd[j] in index form */ s[i] ^= alpha_to[(output[j] + i * j) % NN]; } } /* convert syndrome from polynomial form to index form */ if(s[i] != 0) { /* set flag if non-zero syndrome => error */ syn_error = true; } s[i] = index_of[s[i]]; } if(syn_error) /* if errors, try and correct */ { /* compute the error location polynomial via the Berlekamp iterative algorithm, following the terminology of Lin and Costello : d[u] is the 'mu'th discrepancy, where u='mu'+1 and 'mu' (the Greek letter!) is the step number ranging from -1 to 2*tt (see L&C), l[u] is the degree of the elp at that step, and u_l[u] is the difference between the step number and the degree of the elp. */ /* initialise table entries */ d[0] = 0; /* index form */ d[1] = s[1]; /* index form */ elp[0][0] = 0; /* index form */ elp[1][0] = 1; /* polynomial form */ for(int i = 1; i < NN - KK; i++) { elp[0][i] = -1; /* index form */ elp[1][i] = 0; /* polynomial form */ } l[0] = 0; l[1] = 0; u_lu[0] = -1; u_lu[1] = 0; u = 0; do { u++; if(d[u] == -1) { l[u + 1] = l[u]; for(int i = 0; i <= l[u]; i++) { elp[u + 1][i] = elp[u][i]; elp[u][i] = index_of[elp[u][i]]; } } else /* search for words with greatest u_lu[q] for which d[q]!=0 */ { q = u - 1; while((d[q] == -1) && (q > 0)) { q--; } /* have found first non-zero d[q] */ if(q > 0) { int j = q; do { j--; if((d[j] != -1) && (u_lu[q] < u_lu[j])) { q = j; } } while(j > 0); } ; /* have now found q such that d[u]!=0 and u_lu[q] is maximum */ /* store degree of new elp polynomial */ l[u + 1] = FastMath.max(l[u], l[q] + u - q); /* form new elp(x) */ for(int i = 0; i < NN - KK; i++) { elp[u + 1][i] = 0; } for(int i = 0; i <= l[q]; i++) { if(elp[q][i] != -1) { elp[u + 1][i + u - q] = alpha_to[(d[u] + NN - d[q] + elp[q][i]) % NN]; } } for(int i = 0; i <= l[u]; i++) { elp[u + 1][i] ^= elp[u][i]; elp[u][i] = index_of[elp[u][i]]; /*convert old elp value to index*/ } } u_lu[u + 1] = u - l[u + 1]; /* form (u+1)th discrepancy */ if(u < NN - KK) /* no discrepancy computed on last iteration */ { if(s[u + 1] != -1) { d[u + 1] = alpha_to[s[u + 1]]; } else { d[u + 1] = 0; } for(int i = 1; i <= l[u + 1]; i++) { if((s[u + 1 - i] != -1) && (elp[u + 1][i] != 0)) { d[u + 1] ^= alpha_to[(s[u + 1 - i] + index_of[elp[u + 1][i]]) % NN]; } } d[u + 1] = index_of[d[u + 1]]; /* put d[u+1] into index form */ } } while((u < NN - KK) && (l[u + 1] <= TT)); u++; if(l[u] <= TT) /* can correct error */ { /* put elp into index form */ for(int i = 0; i <= l[u]; i++) { elp[u][i] = index_of[elp[u][i]]; } /* find roots of the error location polynomial */ if(l[u] >= 0) { System.arraycopy(elp[u], 1, reg, 1, l[u]); } count = 0; for(int i = 1; i <= NN; i++) { q = 1; for(int j = 1; j <= l[u]; j++) { if(reg[j] != -1) { reg[j] = (reg[j] + j) % NN; q ^= alpha_to[reg[j]]; } ; } if(q == 0) /* store root and error location number indices */ { root[count] = i; loc[count] = NN - i; count++; } ; } ; if(count == l[u]) /* no. roots = degree of elp hence <= tt errors */ { /* form polynomial z(x) */ for(int i = 1; i <= l[u]; i++) /* Z[0] = 1 always - do not need */ { if((s[i] != -1) && (elp[u][i] != -1)) { z[i] = alpha_to[s[i]] ^ alpha_to[elp[u][i]]; } else if((s[i] != -1) && (elp[u][i] == -1)) { z[i] = alpha_to[s[i]]; } else if((s[i] == -1) && (elp[u][i] != -1)) { z[i] = alpha_to[elp[u][i]]; } else { z[i] = 0; } for(int j = 1; j < i; j++) { if((s[j] != -1) && (elp[u][i - j] != -1)) { z[i] ^= alpha_to[(elp[u][i - j] + s[j]) % NN]; } } z[i] = index_of[z[i]]; /* put into index form */ } ; /* evaluate errors at locations given by error location numbers loc[i] */ for(int i = 0; i < NN; i++) { err[i] = 0; if(output[i] != -1) /* convert recd[] to polynomial form */ { output[i] = alpha_to[output[i]]; } else { output[i] = 0; } } for(int i = 0; i < l[u]; i++) /* compute numerator of error term first */ { err[loc[i]] = 1; /* accounts for z[0] */ for(int j = 1; j <= l[u]; j++) { if(z[j] != -1) { err[loc[i]] ^= alpha_to[(z[j] + j * root[i]) % NN]; } } if(err[loc[i]] != 0) { err[loc[i]] = index_of[err[loc[i]]]; q = 0; /* form denominator of error term */ for(int j = 0; j < l[u]; j++) { if(j != i) { q += index_of[1 ^ alpha_to[(loc[j] + root[i]) % NN]]; } } q = q % NN; err[loc[i]] = alpha_to[(err[loc[i]] - q + NN) % NN]; output[loc[i]] ^= err[loc[i]]; /*recd[i] must be in polynomial form */ } } } else { /* no. roots != degree of elp => >tt errors and cannot solve */ irrecoverable_error = true; } } else { /* elp has degree >tt hence cannot solve */ irrecoverable_error = true; } } else { /* no non-zero syndromes => no errors: output received codeword */ for(int i = 0; i < NN; i++) { if(output[i] != -1) /* convert recd[] to polynomial form */ { output[i] = alpha_to[output[i]]; } else { output[i] = 0; } } } if(irrecoverable_error) { for(int i = 0; i < NN; i++) /* could return error flag if desired */ { if(output[i] != -1) /* convert recd[] to polynomial form */ { output[i] = alpha_to[output[i]]; } else { output[i] = 0; /* just output received codeword as is */ } } } return irrecoverable_error; } }
DSheirer/sdrtrunk
src/main/java/io/github/dsheirer/edac/BerlekempMassey.java
5,655
/* Hamming distance between codewords: NN - KK + 1 = 2 * TT + 1 */
block_comment
nl
/* * ***************************************************************************** * Copyright (C) 2014-2024 Dennis Sheirer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * **************************************************************************** */ package io.github.dsheirer.edac; import io.github.dsheirer.log.LoggingSuppressor; import org.apache.commons.lang3.Validate; import org.apache.commons.math3.util.FastMath; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Berlekemp Massey decoder for primitive RS/BCH block codes * * Original C implementation by Simon Rockliff, 26 June 1991 */ public class BerlekempMassey { private final static Logger mLog = LoggerFactory.getLogger(BerlekempMassey.class); private static final LoggingSuppressor LOGGING_SUPPRESSOR = new LoggingSuppressor(mLog); /* Golay field size GF( 2 ** MM ) */ private int MM; /* Codeword Length: NN = 2 ** MM - 1 */ private int NN; private int MAX_NN; /* Hamming distance between<SUF>*/ private int KK; /* Maximum number of errors that can be corrected */ int TT; int[] alpha_to; int[] index_of; int[] gg; /** * Constructs an instance * * @param galoisFieldSize as a power of 2, e.g. for a GF(2^6) the parameter would be 6 * @param maxCorrectableErrors is Hamming Distance / 2. e.g. RS(24,16,9) would be (24 - 16) / 2, or floor(9/2). * @param generatorPolynomial for the Galois Field represented in binary as 0/1 integers where the array is in * big-endian format. For example: polynomial a6 + a1 + 1 is 1000011, as big endian: 1100001, and in array * form as {1,1,0,0,0,0,1} */ public BerlekempMassey(int galoisFieldSize, int maxCorrectableErrors, int[] generatorPolynomial) { //TODO: fix this MM = galoisFieldSize; NN = (int)FastMath.pow(2, MM) - 1; TT = maxCorrectableErrors; KK = NN - 2 * TT; } public BerlekempMassey(int bitSize, int n, int k, int[] generatorPolynomial) { Validate.isTrue(bitSize == generatorPolynomial.length - 1, "Generator polynomial length must be: bitSize + 1"); MM = bitSize; NN = n; KK = k; TT = (int)Math.floor((NN - KK) / 2); //Since this may be a shortened code, setup arrays to the max size of NN int maxNN = (int)Math.pow(2, MM) - 1; alpha_to = new int[maxNN + 1]; index_of = new int[maxNN + 1]; gg = new int[NN - KK + 1]; generate_gf(generatorPolynomial); gen_poly(); } /** * Generates the Golay Field. * * Generates a GF( 2**mm ) from the irreducible polynomial * p(X) in pp[0]..pp[mm] * * Lookup tables: * index_of[] = polynomial form * alpha_to[] = contains j=alpha**i; * * Polynomial form -> Index form index_of[j=alpha**i] = i * * alpha_to = 2 is the primitive element of GF( 2**mm ) * * @param generator_polynomial */ private void generate_gf(int[] generator_polynomial) { int i; int mask = 1; alpha_to[MM] = 0; for(i = 0; i < MM; i++) { alpha_to[i] = mask; index_of[alpha_to[i]] = i; if(generator_polynomial[i] != 0) { alpha_to[MM] ^= mask; } mask <<= 1; } index_of[alpha_to[MM]] = MM; mask >>= 1; for(i = MM + 1; i < NN; i++) { if(alpha_to[i - 1] >= mask) { alpha_to[i] = alpha_to[MM] ^ ((alpha_to[i - 1] ^ mask) << 1); } else { alpha_to[i] = alpha_to[i - 1] << 1; } index_of[alpha_to[i]] = i; } index_of[0] = -1; } /** * Generates the polynomial for a TT-error correction code. * * Length NN = ( 2 ** MM -1 ) Reed Solomon code from the product of * (X+alpha**i), i=1..2*tt */ private void gen_poly() { int i, j; gg[0] = 2; /* primitive element alpha = 2 for GF(2**mm) */ gg[1] = 1; /* g(x) = (X+alpha) initially */ for(i = 2; i <= (NN - KK); i++) { gg[i] = 1; for(j = i - 1; j > 0; j--) { if(gg[j] != 0) { gg[j] = gg[j - 1] ^ alpha_to[(index_of[gg[j]] + i) % NN]; } else { gg[j] = gg[j - 1]; } } /* gg[0] can never be zero */ gg[0] = alpha_to[(index_of[gg[0]] + i) % NN]; } /* convert gg[] to index form for quicker encoding */ for(i = 0; i <= (NN - KK); i++) { gg[i] = index_of[gg[i]]; } } /** * Decodes * * @param input * @param output * @return */ /* assume we have received bits grouped into mm-bit symbols in recd[i], i=0..(nn-1), and recd[i] is polynomial form. We first compute the 2*tt syndromes by substituting alpha**i into rec(X) and evaluating, storing the syndromes in s[i], i=1..2tt (leave s[0] zero) . Then we use the Berlekamp iteration to find the error location polynomial elp[i]. If the degree of the elp is >tt, we cannot correct all the errors and hence just put out the information symbols uncorrected. If the degree of elp is <=tt, we substitute alpha**i , i=1..n into the elp to get the roots, hence the inverse roots, the error location numbers. If the number of errors located does not equal the degree of the elp, we have more than tt errors and cannot correct them. Otherwise, we then solve for the error value at the error location and correct the error. The procedure is that found in Lin and Costello. For the cases where the number of errors is known to be too large to correct, the information symbols as received are output (the advantage of systematic encoding is that hopefully some of the information symbols will be okay and that if we are in luck, the errors are in the parity part of the transmitted codeword). Of course, these insoluble cases can be returned as error flags to the calling routine if desired. */ public boolean decode(final int[] input, int[] output) //input, output { int u, q; int[][] elp = new int[NN - KK + 2][NN - KK]; int[] d = new int[NN - KK + 2]; int[] l = new int[NN - KK + 2]; int[] u_lu = new int[NN - KK + 2]; int[] s = new int[NN - KK + 1]; int count = 0; boolean syn_error = false; int[] root = new int[TT]; int[] loc = new int[TT]; int[] z = new int[TT + 1]; int[] err = new int[NN]; int[] reg = new int[TT + 1]; boolean irrecoverable_error = false; /* put recd[i] into index form (ie as powers of alpha) */ for(int i = 0; i < NN; i++) { try { output[i] = index_of[input[i]]; } catch(Exception e) { LOGGING_SUPPRESSOR.error(getClass().toString(), 2, "Reed Solomon Decoder error for " + "class [" + getClass() + "] there may be an issue with the message parser class indices - " + "ensure the hex bit values are not larger 63", e); } } /* first form the syndromes */ for(int i = 1; i <= NN - KK; i++) { s[i] = 0; for(int j = 0; j < NN; j++) { if(output[j] != -1) { /* recd[j] in index form */ s[i] ^= alpha_to[(output[j] + i * j) % NN]; } } /* convert syndrome from polynomial form to index form */ if(s[i] != 0) { /* set flag if non-zero syndrome => error */ syn_error = true; } s[i] = index_of[s[i]]; } if(syn_error) /* if errors, try and correct */ { /* compute the error location polynomial via the Berlekamp iterative algorithm, following the terminology of Lin and Costello : d[u] is the 'mu'th discrepancy, where u='mu'+1 and 'mu' (the Greek letter!) is the step number ranging from -1 to 2*tt (see L&C), l[u] is the degree of the elp at that step, and u_l[u] is the difference between the step number and the degree of the elp. */ /* initialise table entries */ d[0] = 0; /* index form */ d[1] = s[1]; /* index form */ elp[0][0] = 0; /* index form */ elp[1][0] = 1; /* polynomial form */ for(int i = 1; i < NN - KK; i++) { elp[0][i] = -1; /* index form */ elp[1][i] = 0; /* polynomial form */ } l[0] = 0; l[1] = 0; u_lu[0] = -1; u_lu[1] = 0; u = 0; do { u++; if(d[u] == -1) { l[u + 1] = l[u]; for(int i = 0; i <= l[u]; i++) { elp[u + 1][i] = elp[u][i]; elp[u][i] = index_of[elp[u][i]]; } } else /* search for words with greatest u_lu[q] for which d[q]!=0 */ { q = u - 1; while((d[q] == -1) && (q > 0)) { q--; } /* have found first non-zero d[q] */ if(q > 0) { int j = q; do { j--; if((d[j] != -1) && (u_lu[q] < u_lu[j])) { q = j; } } while(j > 0); } ; /* have now found q such that d[u]!=0 and u_lu[q] is maximum */ /* store degree of new elp polynomial */ l[u + 1] = FastMath.max(l[u], l[q] + u - q); /* form new elp(x) */ for(int i = 0; i < NN - KK; i++) { elp[u + 1][i] = 0; } for(int i = 0; i <= l[q]; i++) { if(elp[q][i] != -1) { elp[u + 1][i + u - q] = alpha_to[(d[u] + NN - d[q] + elp[q][i]) % NN]; } } for(int i = 0; i <= l[u]; i++) { elp[u + 1][i] ^= elp[u][i]; elp[u][i] = index_of[elp[u][i]]; /*convert old elp value to index*/ } } u_lu[u + 1] = u - l[u + 1]; /* form (u+1)th discrepancy */ if(u < NN - KK) /* no discrepancy computed on last iteration */ { if(s[u + 1] != -1) { d[u + 1] = alpha_to[s[u + 1]]; } else { d[u + 1] = 0; } for(int i = 1; i <= l[u + 1]; i++) { if((s[u + 1 - i] != -1) && (elp[u + 1][i] != 0)) { d[u + 1] ^= alpha_to[(s[u + 1 - i] + index_of[elp[u + 1][i]]) % NN]; } } d[u + 1] = index_of[d[u + 1]]; /* put d[u+1] into index form */ } } while((u < NN - KK) && (l[u + 1] <= TT)); u++; if(l[u] <= TT) /* can correct error */ { /* put elp into index form */ for(int i = 0; i <= l[u]; i++) { elp[u][i] = index_of[elp[u][i]]; } /* find roots of the error location polynomial */ if(l[u] >= 0) { System.arraycopy(elp[u], 1, reg, 1, l[u]); } count = 0; for(int i = 1; i <= NN; i++) { q = 1; for(int j = 1; j <= l[u]; j++) { if(reg[j] != -1) { reg[j] = (reg[j] + j) % NN; q ^= alpha_to[reg[j]]; } ; } if(q == 0) /* store root and error location number indices */ { root[count] = i; loc[count] = NN - i; count++; } ; } ; if(count == l[u]) /* no. roots = degree of elp hence <= tt errors */ { /* form polynomial z(x) */ for(int i = 1; i <= l[u]; i++) /* Z[0] = 1 always - do not need */ { if((s[i] != -1) && (elp[u][i] != -1)) { z[i] = alpha_to[s[i]] ^ alpha_to[elp[u][i]]; } else if((s[i] != -1) && (elp[u][i] == -1)) { z[i] = alpha_to[s[i]]; } else if((s[i] == -1) && (elp[u][i] != -1)) { z[i] = alpha_to[elp[u][i]]; } else { z[i] = 0; } for(int j = 1; j < i; j++) { if((s[j] != -1) && (elp[u][i - j] != -1)) { z[i] ^= alpha_to[(elp[u][i - j] + s[j]) % NN]; } } z[i] = index_of[z[i]]; /* put into index form */ } ; /* evaluate errors at locations given by error location numbers loc[i] */ for(int i = 0; i < NN; i++) { err[i] = 0; if(output[i] != -1) /* convert recd[] to polynomial form */ { output[i] = alpha_to[output[i]]; } else { output[i] = 0; } } for(int i = 0; i < l[u]; i++) /* compute numerator of error term first */ { err[loc[i]] = 1; /* accounts for z[0] */ for(int j = 1; j <= l[u]; j++) { if(z[j] != -1) { err[loc[i]] ^= alpha_to[(z[j] + j * root[i]) % NN]; } } if(err[loc[i]] != 0) { err[loc[i]] = index_of[err[loc[i]]]; q = 0; /* form denominator of error term */ for(int j = 0; j < l[u]; j++) { if(j != i) { q += index_of[1 ^ alpha_to[(loc[j] + root[i]) % NN]]; } } q = q % NN; err[loc[i]] = alpha_to[(err[loc[i]] - q + NN) % NN]; output[loc[i]] ^= err[loc[i]]; /*recd[i] must be in polynomial form */ } } } else { /* no. roots != degree of elp => >tt errors and cannot solve */ irrecoverable_error = true; } } else { /* elp has degree >tt hence cannot solve */ irrecoverable_error = true; } } else { /* no non-zero syndromes => no errors: output received codeword */ for(int i = 0; i < NN; i++) { if(output[i] != -1) /* convert recd[] to polynomial form */ { output[i] = alpha_to[output[i]]; } else { output[i] = 0; } } } if(irrecoverable_error) { for(int i = 0; i < NN; i++) /* could return error flag if desired */ { if(output[i] != -1) /* convert recd[] to polynomial form */ { output[i] = alpha_to[output[i]]; } else { output[i] = 0; /* just output received codeword as is */ } } } return irrecoverable_error; } }
101419_6
/** * Paard class * * @author Martijn van der Bruggen * (c) Hogeschool van Arnhem en Nijmegen * @version alpha release */ import java.awt.*; import java.util.Random; public class Paard { private int x; private final int paardNummer; //te lezen als x en y positie private static int aantal = 0; //totaal aantal paarden private final String naam; //naam van het paard private Color kleur; //kleur van de streep/paard private Image plaatje; Random random = new Random(); /** Constructor voor Paard, overloaded en zonder images en een default kleur */ Paard(String naam) { this.naam = naam; this.kleur = Color.orange; this.x = 0; this.paardNummer = ++aantal; } /* Constructor voor Paard overloaded*/ Paard(String naam, Color kleur, Image plaatje) { this (naam); this.kleur = kleur; this.plaatje = plaatje; } public String getNaam() { return this.naam; } public int getAfstand() { return this.x; } public int getPaardNummer() { return this.paardNummer; } public Color getKleur() { return this.kleur; } public Image getImage() { return this.plaatje; } /** * Laat het paard een willekeurig aantal posities lopen * Verhoog de x met een waarde tussen 0 en 11 */ public void loop() { this.x = this.x + random.nextInt(5); System.out.println(this.naam + " is op positie " +this.x); } }
DWJStraat/BIN-Jaar-2-2023-2024
David/Afvinkopdrachten/OWE5/OWE 5/src/Paard.java
500
/* Constructor voor Paard overloaded*/
block_comment
nl
/** * Paard class * * @author Martijn van der Bruggen * (c) Hogeschool van Arnhem en Nijmegen * @version alpha release */ import java.awt.*; import java.util.Random; public class Paard { private int x; private final int paardNummer; //te lezen als x en y positie private static int aantal = 0; //totaal aantal paarden private final String naam; //naam van het paard private Color kleur; //kleur van de streep/paard private Image plaatje; Random random = new Random(); /** Constructor voor Paard, overloaded en zonder images en een default kleur */ Paard(String naam) { this.naam = naam; this.kleur = Color.orange; this.x = 0; this.paardNummer = ++aantal; } /* Constructor voor Paard<SUF>*/ Paard(String naam, Color kleur, Image plaatje) { this (naam); this.kleur = kleur; this.plaatje = plaatje; } public String getNaam() { return this.naam; } public int getAfstand() { return this.x; } public int getPaardNummer() { return this.paardNummer; } public Color getKleur() { return this.kleur; } public Image getImage() { return this.plaatje; } /** * Laat het paard een willekeurig aantal posities lopen * Verhoog de x met een waarde tussen 0 en 11 */ public void loop() { this.x = this.x + random.nextInt(5); System.out.println(this.naam + " is op positie " +this.x); } }
143932_0
package com.example.defaultmethods; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; public class AppleTests { /*TODO @Joris ik snap niet goed wat er de bedoeling is van deze opdracht (opdracht 5) alles wat ik probeer werkt namelijk gewoon*/ @Test @DisplayName("Tests apple functionality") public void appleTest() { //Arrange Apple apple1 = new Apple(); Apple apple2 = new Apple(); //Act apple1.dispose(); apple2.eat(); //Assert assertThat(apple1.getSlicesLeft()).isEqualTo(0); assertThat(apple2.getSlicesLeft()).isEqualTo(3); } }
DaGreatCake/lambdasstreamsBenjamin
src/test/java/com/example/defaultmethods/AppleTests.java
224
/*TODO @Joris ik snap niet goed wat er de bedoeling is van deze opdracht (opdracht 5) alles wat ik probeer werkt namelijk gewoon*/
block_comment
nl
package com.example.defaultmethods; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; public class AppleTests { /*TODO @Joris ik<SUF>*/ @Test @DisplayName("Tests apple functionality") public void appleTest() { //Arrange Apple apple1 = new Apple(); Apple apple2 = new Apple(); //Act apple1.dispose(); apple2.eat(); //Assert assertThat(apple1.getSlicesLeft()).isEqualTo(0); assertThat(apple2.getSlicesLeft()).isEqualTo(3); } }
149884_0
package net.mostlyoriginal.game; import com.badlogic.gdx.audio.Music; /** * @author Daan van Yperen */ public abstract class GameRules { public static final int PERCENTAGE_CHANCE_OF_SINK_DIRTY_ESCALATION = 50; public static final int PERCENTAGE_CHANCE_OF_URINAL_DIRTY_ESCALATION = 50; public static final int PERCENTAGE_CHANCE_OF_TOILET_DIRTY_ESCALATION = 75; public static final int WALKING_SPEED_VISITORS = 50; public static final int SCREEN_WIDTH = 1280; public static final int SCREEN_HEIGHT = 720; public static final int CAMERA_ZOOM = 2; public static int lastScore = -1; public static int level = -1; public static Music music; public static boolean sfxOn=true; public static boolean musicOn=true; }
DaanVanYperen/odb-as-of-yet-unnamed
core/src/net/mostlyoriginal/game/GameRules.java
263
/** * @author Daan van Yperen */
block_comment
nl
package net.mostlyoriginal.game; import com.badlogic.gdx.audio.Music; /** * @author Daan van<SUF>*/ public abstract class GameRules { public static final int PERCENTAGE_CHANCE_OF_SINK_DIRTY_ESCALATION = 50; public static final int PERCENTAGE_CHANCE_OF_URINAL_DIRTY_ESCALATION = 50; public static final int PERCENTAGE_CHANCE_OF_TOILET_DIRTY_ESCALATION = 75; public static final int WALKING_SPEED_VISITORS = 50; public static final int SCREEN_WIDTH = 1280; public static final int SCREEN_HEIGHT = 720; public static final int CAMERA_ZOOM = 2; public static int lastScore = -1; public static int level = -1; public static Music music; public static boolean sfxOn=true; public static boolean musicOn=true; }
138125_0
package DataHandlers; import net.dv8tion.jda.core.entities.Guild; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * Breidt de DataHandler uit voor het verwerken van de voedselfunctionaliteit. */ public class FoodHandler extends DataHandler { private JSONArray food; public FoodHandler(Guild g) { super(g); food = (JSONArray) ((JSONObject) jsonObject.get(guild)).get("Food"); } @SuppressWarnings("unchecked") public void addFood(String name, String emoji) { Map<String, String> foodMap = new HashMap<>(); foodMap.put("Name", name); foodMap.put("Emoji", emoji); food.add(new JSONObject(foodMap)); save(); } public void removeFood(int i) { food.remove(i); save(); } public ArrayList<Map<String, String>> getFood() { ArrayList<Map<String, String>> foodList = new ArrayList<>(); Arrays.stream(food.toArray()).forEach((object -> { Map<String, String> f = new HashMap<>(); JSONObject obj = (JSONObject) object; Arrays.stream(obj.keySet().toArray()).forEach(s -> { String name = (String) s; f.put(name, (String) obj.get(name)); }); foodList.add(f); })); return foodList; } public int checkFood(String emoji) { ArrayList<Map<String, String>> foods = getFood(); int i = 0; while (i < foods.size() && !foods.get(i).get("Emoji").equalsIgnoreCase(emoji)) { i++; } if (i < foods.size()) { return i - 1; } else { return -1; } } }
DaanWet/DnD_Discord_Bot
src/main/java/DataHandlers/FoodHandler.java
553
/** * Breidt de DataHandler uit voor het verwerken van de voedselfunctionaliteit. */
block_comment
nl
package DataHandlers; import net.dv8tion.jda.core.entities.Guild; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * Breidt de DataHandler<SUF>*/ public class FoodHandler extends DataHandler { private JSONArray food; public FoodHandler(Guild g) { super(g); food = (JSONArray) ((JSONObject) jsonObject.get(guild)).get("Food"); } @SuppressWarnings("unchecked") public void addFood(String name, String emoji) { Map<String, String> foodMap = new HashMap<>(); foodMap.put("Name", name); foodMap.put("Emoji", emoji); food.add(new JSONObject(foodMap)); save(); } public void removeFood(int i) { food.remove(i); save(); } public ArrayList<Map<String, String>> getFood() { ArrayList<Map<String, String>> foodList = new ArrayList<>(); Arrays.stream(food.toArray()).forEach((object -> { Map<String, String> f = new HashMap<>(); JSONObject obj = (JSONObject) object; Arrays.stream(obj.keySet().toArray()).forEach(s -> { String name = (String) s; f.put(name, (String) obj.get(name)); }); foodList.add(f); })); return foodList; } public int checkFood(String emoji) { ArrayList<Map<String, String>> foods = getFood(); int i = 0; while (i < foods.size() && !foods.get(i).get("Emoji").equalsIgnoreCase(emoji)) { i++; } if (i < foods.size()) { return i - 1; } else { return -1; } } }
166677_18
package persistentie; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import domein.Spel; import domein.spelbord.Doel; import domein.spelbord.Muur; import domein.spelbord.Spelbord; import domein.spelbord.Vak; import domein.spelbord.Veld; public class SpelMapper { // selects private static final String SELECT_SPELNAMEN = "SELECT spelNaam FROM Spel"; private static final String SELECT_SPEL = "SELECT * FROM Spel WHERE spelNaam = ?"; private static final String SELECT_COUNT_SPELBORDEN = "SELECT COUNT(*) AS 'aantal' FROM Spelbord WHERE spelNaam = ?"; private static final String SELECT_SPELBORD = "SELECT * FROM Spelbord WHERE spelNaam = ?"; private static final String SELECT_SPELSTUK = "SELECT * FROM Spelstuk WHERE spelNaam = ? and spelbordNummer = ?"; private static final String SELECT_VAK = "SELECT * FROM Vak WHERE spelNaam = ? and spelbordNummer = ?"; private static final String SELECT_SPELNAAM = "SELECT spelNaam FROM Spel WHERE spelerNaam = ?"; // inserts private static final String INSERT_SPEL = "INSERT INTO Spel (spelNaam, spelerNaam) VALUES (?, ?)"; private static final String INSERT_SPELBORD = "INSERT INTO Spelbord (spelNaam, volgnummer) VALUES (?, ?)"; private static final String INSERT_SPELSTUK = "INSERT INTO Spelstuk (spelNaam, spelbordNummer, rijPos, kolPos, spelstukType) VALUES (?, ?, ?, ?, ?)"; private static final String INSERT_VAK = "INSERT INTO Vak (spelNaam, spelbordNummer, rijPos, kolPos, vakType) VALUES (?, ?, ?, ?, ?)"; // deletes private static final String DELETE_SPEL = "DELETE FROM Spel WHERE spelNaam = ?"; private static final String DELETE_SPELBORDEN = "DELETE FROM Spelbord WHERE spelNaam = ?"; private static final String DELETE_SPELSTUKKEN = "DELETE FROM Spelstuk WHERE spelNaam = ?"; private static final String DELETE_VAKKEN = "DELETE FROM Vak WHERE spelNaam = ?"; private static final String DELETE_SPELBORD = "DELETE FROM Spelbord WHERE spelNaam = ? and volgnummer = ?"; private static final String DELETE_VAKKEN_VAN_SPELBORD = "DELETE FROM Vak WHERE spelNaam = ? and spelbordNummer = ?"; private static final String DELETE_SPELSTUKKEN_VAN_SPELBORD = "DELETE FROM Spelstuk WHERE spelNaam = ? and spelbordNummer = ?"; /** * Default constructor. */ public SpelMapper() { } // methods /** * Haalt de namen van alle Spelletje op uit de databank. * * @return List met namen van de Spelletjes */ public List<String> geefSpelnamen() { List<String> namenVanSpelletjes = new ArrayList<>(); try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(SELECT_SPELNAMEN); ResultSet rs = query.executeQuery()) { while (rs.next()) { String naam = rs.getString("spelNaam"); namenVanSpelletjes.add(naam); } } catch (SQLException ex) { throw new RuntimeException(ex); } return namenVanSpelletjes; } /** * Haalt het Spel en zijn Spelborden op uit de databank, aan de hand van de * gegeven naam. * * @param naam * @return Spel */ public Spel geefSpel(String naam) { Spel spel = null; try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(SELECT_SPEL)) { query.setString(1, naam); ResultSet rs = query.executeQuery(); if (rs.next()) { Spelbord eersteSpelbord = geefSpelborden(naam); int aantalSpelborden = geefAantalSpelborden(naam); spel = new Spel(naam, eersteSpelbord, aantalSpelborden); } } catch (SQLException ex) { throw new RuntimeException(ex); } return spel; } /** * Telt het aantal spelborden in het Spel met de gegeven naam. * * @param naam * @return */ private int geefAantalSpelborden(String naam) { int aantalSpelborden = 0; try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(SELECT_COUNT_SPELBORDEN)) { query.setString(1, naam); ResultSet rs = query.executeQuery(); if (rs.next()) { aantalSpelborden = rs.getInt("aantal"); } } catch (SQLException ex) { throw new RuntimeException(ex); } return aantalSpelborden; } /** * Haalt de Spelborden en hun vakken en spelstukken op uit de databank, aan de * hand van de gegeven spelnaam. * * @param spelnaam * @return het eerste spelbord met de link naar de andere spelborden */ private Spelbord geefSpelborden(String spelnaam) { Spelbord eersteSpelbord = null; try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(SELECT_SPELBORD)) { query.setString(1, spelnaam); ResultSet rs = query.executeQuery(); int volgnummer = 0; if (rs.next()) { Vak[][] vakken = geefVakken(spelnaam, volgnummer); List<int[]> spelstukPosities = geefSpelstukPosities(spelnaam, volgnummer); int[] startPositieMannetje = spelstukPosities.get(0); spelstukPosities.remove(0); int[][] startPositiesKisten = spelstukPosities.toArray(new int[0][]); eersteSpelbord = new Spelbord(vakken, startPositieMannetje, startPositiesKisten); volgnummer++; } Spelbord tijdelijk = eersteSpelbord; while (rs.next()) { Vak[][] vakken = geefVakken(spelnaam, volgnummer); List<int[]> spelstukPosities = geefSpelstukPosities(spelnaam, volgnummer); int[] startPositieMannetje = spelstukPosities.get(0); spelstukPosities.remove(0); int[][] startPositiesKisten = spelstukPosities.toArray(new int[0][]); Spelbord spelbord = new Spelbord(vakken, startPositieMannetje, startPositiesKisten); tijdelijk.setVolgendSpelBord(spelbord); volgnummer++; tijdelijk = spelbord; } } catch (SQLException ex) { throw new RuntimeException(ex); } return eersteSpelbord; } /** * Haalt de spelstukken van een spelbord op. * * @param spelnaam * @param volgnumer van het spelbord * @return posities van de spelstukken, mannetje staat op de eerste positie in * de lijst */ private List<int[]> geefSpelstukPosities(String spelnaam, int volgnummer) { List<int[]> posities = new ArrayList<int[]>(); try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(SELECT_SPELSTUK)) { query.setString(1, spelnaam); query.setInt(2, volgnummer); ResultSet rs = query.executeQuery(); while (rs.next()) { if (rs.getString("spelstukType").equals("mannetje")) { posities.add(0, new int[] { rs.getInt("rijPos"), rs.getInt("kolPos") }); } else { posities.add(new int[] { rs.getInt("rijPos"), rs.getInt("kolPos") }); } } } catch (SQLException ex) { throw new RuntimeException(ex); } return posities; } /** * Haalt alle vakken van het spelbord met de gegeven spelnaam en volgnummer op. * * @param spelnaam * @param volgnummer van het spelbord * @return vakken */ private Vak[][] geefVakken(String spelnaam, int volgnummer) { Vak[][] vakken = new Vak[Spel.getMaxRijPos()][Spel.getMaxKolPos()]; try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(SELECT_VAK)) { query.setString(1, spelnaam); query.setInt(2, volgnummer); ResultSet rs = query.executeQuery(); while (rs.next()) { int rijPos = rs.getInt("rijPos"); int kolPos = rs.getInt("kolPos"); switch (rs.getString("vakType")) { case "veld": vakken[rijPos][kolPos] = new Veld(rijPos, kolPos); break; case "muur": vakken[rijPos][kolPos] = new Muur(rijPos, kolPos); break; case "doel": vakken[rijPos][kolPos] = new Doel(rijPos, kolPos); break; } } } catch (SQLException ex) { throw new RuntimeException(ex); } return vakken; } /** * Controleert of er al een Spel met gegeven naam bestaat in de databank. * * @param naam * @return true waneer het Spel gevonden word, anders false */ public boolean bestaatSpel(String naam) { try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(SELECT_SPEL)) { query.setString(1, naam); ResultSet rs = query.executeQuery(); if (rs.next()) { return true; } return false; } catch (SQLException ex) { throw new RuntimeException(ex); } } /** * Voegt het gegeven Spel en zijn Spelborden toe in de databank. * * @param spel * @param gebruikersnaam */ public void voegSpelToe(Spel spel, String gebruikersnaam) { String spelNaam = controleerLengte(spel.getNaam()); try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(INSERT_SPEL)) { query.setString(1, spelNaam); query.setString(2, gebruikersnaam); query.executeUpdate(); } catch (SQLException ex) { throw new RuntimeException(ex); } Spelbord tempSpelbord = spel.getEersteSpelbord(); int teller = 0; voegSpelbordToe(tempSpelbord, spelNaam, teller); while (tempSpelbord.getVolgendSpelBord() != null) { teller++; tempSpelbord = tempSpelbord.getVolgendSpelBord(); voegSpelbordToe(tempSpelbord, spelNaam, teller); } } /** * Voegt het gegeven Spelborden en zijn vakken en spelstukken toe in de * databank. * * @param spelbord * @param spelnaam * @param volgnummer */ private void voegSpelbordToe(Spelbord spelbord, String spelnaam, int volgnummer) { try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(INSERT_SPELBORD)) { query.setString(1, spelnaam); query.setInt(2, volgnummer); query.executeUpdate(); voegSpelstukkenToe(spelbord, spelnaam, volgnummer); voegVakkenToe(spelbord, spelnaam, volgnummer); } catch (SQLException ex) { throw new RuntimeException(ex); } } /** * Voegt de spelstukken van het gegeven Spelbord toe in de databank. * * @param spelbord * @param spelnaam * @param spelbordNummer */ private void voegSpelstukkenToe(Spelbord spelbord, String spelnaam, int spelbordNummer) { try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(INSERT_SPELSTUK)) { int[] positieMannetje = spelbord.getStartPositieMannetje(); query.setString(1, spelnaam); query.setInt(2, spelbordNummer); query.setInt(3, positieMannetje[0]); query.setInt(4, positieMannetje[1]); query.setString(5, "mannetje"); query.executeUpdate(); int[][] positiesKisten = spelbord.getStartPositiesKisten(); for (int[] is : positiesKisten) { query.setString(1, spelnaam); query.setInt(2, spelbordNummer); query.setInt(3, is[0]); query.setInt(4, is[1]); query.setString(5, "kist"); query.executeUpdate(); } } catch (SQLException ex) { throw new RuntimeException(ex); } } /** * Voegt de vakken van het gegeven Spelbord toe in de databank. * * @param spelbord * @param spelnaam * @param spelbordNummer */ private void voegVakkenToe(Spelbord spelbord, String spelnaam, int spelbordNummer) { try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(INSERT_VAK)) { Vak[][] vakken = spelbord.getVakken(); for (Vak[] vak1 : vakken) { for (Vak vak : vak1) { query.setString(1, spelnaam); query.setInt(2, spelbordNummer); query.setInt(3, vak.getrijPos()); query.setInt(4, vak.getkolPos()); query.setString(5, vak.getClass().getSimpleName().toLowerCase()); query.executeUpdate(); } } } catch (SQLException ex) { throw new RuntimeException(ex); } } /** * Haalt de spelnamen geassocieerd met de Speler op uit de databank. * * @param gebruikersnaam * @return spelnamen van de Speler */ public List<String> geefSpelNamen(String gebruikersnaam) { List<String> namenVanSpelletjes = new ArrayList<String>(); try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(SELECT_SPELNAAM)) { query.setString(1, gebruikersnaam); try (ResultSet rs = query.executeQuery()) { while (rs.next()) { String spelNaam = rs.getString("spelNaam"); namenVanSpelletjes.add(spelNaam); } } } catch (SQLException ex) { throw new RuntimeException(ex); } return namenVanSpelletjes; } /** * Verwijderd het Spel met de gegeven naam uit de databank. * * @param spelnaam */ public void verwijderVolledigSpel(String spelnaam) { verwijderVakken(spelnaam); verwijderSpelstukken(spelnaam); verwijderSpelborden(spelnaam); verwijderSpel(spelnaam); } /** * Verwjderd het Spel uit de databank, aan de hand van de gegeven spelnaam. * * @param spelnaam */ private void verwijderSpel(String spelnaam) { try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(DELETE_SPEL)) { query.setString(1, spelnaam); query.execute(); } catch (SQLException ex) { throw new RuntimeException(ex); } } /** * Verwjderd alle Spelborden van een Spel uit de databank, aan de hand van de * gegeven spelnaam. * * @param spelnaam */ private void verwijderSpelborden(String spelnaam) { try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(DELETE_SPELBORDEN)) { query.setString(1, spelnaam); query.execute(); } catch (SQLException ex) { throw new RuntimeException(ex); } } /** * Verwjderd alle spelstukken van een Spel uit de databank, aan de hand van de * gegeven spelnaam. * * @param spelnaam */ private void verwijderSpelstukken(String spelnaam) { try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(DELETE_SPELSTUKKEN)) { query.setString(1, spelnaam); query.execute(); } catch (SQLException ex) { throw new RuntimeException(ex); } } /** * Verwjderd alle vakken van een Spel uit de databank, aan de hand van de * gegeven spelnaam. * * @param spelnaam */ private void verwijderVakken(String spelnaam) { try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(DELETE_VAKKEN)) { query.setString(1, spelnaam); query.execute(); } catch (SQLException ex) { throw new RuntimeException(ex); } } /** * Vervangt het Spelbord in de databank met het aangepaste Spelbord. * * @param volgnummer om het volgnummer in de databank te bepalen * @param spelbord * @param spelnaam */ public void vervangSpelbord(int volgnummerProg, Spelbord spelbord, String spelnaam) { int volgnummerDatabank = bepaalVolgnummerDatabank(spelnaam, volgnummerProg); verwijderSpelstukkenVanSpelbord(volgnummerDatabank, spelnaam); verwijderVakkenVanSpelbord(volgnummerDatabank, spelnaam); verwijderSpelbord(volgnummerDatabank, spelnaam); voegSpelbordToe(spelbord, spelnaam, volgnummerDatabank); } /** * Bepaal het volgnummer van het Spelbord dat moet vervangen worden in de * databank, aan de hand van het volgnummer in het programma. * * @param spelnaam * @param volgnummerProg * @return */ private int bepaalVolgnummerDatabank(String spelnaam, int volgnummerProg) { try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(SELECT_SPELBORD)) { query.setString(1, spelnaam); ResultSet rs = query.executeQuery(); int teller = 1; while (rs.next()) { if (teller == volgnummerProg) { return rs.getInt("volgnummer"); } teller++; } } catch (SQLException ex) { throw new RuntimeException(ex); } return -1; } /** * Verwijderd een Spelbord uit de databank, aan de hand van de gegeven spelnaam * en volgnummer. * * @param volgnummer * @param spelnaam */ private void verwijderSpelbord(int volgnummer, String spelnaam) { try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(DELETE_SPELBORD)) { query.setString(1, spelnaam); query.setInt(2, volgnummer); query.execute(); } catch (SQLException ex) { throw new RuntimeException(ex); } } /** * Verwjderd alle vakken van een Spelbord uit de databank, aan de hand van de * gegeven spelnaam en volgnummer. * * @param volgnummer * @param spelnaam */ private void verwijderVakkenVanSpelbord(int volgnummer, String spelnaam) { try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(DELETE_VAKKEN_VAN_SPELBORD)) { query.setString(1, spelnaam); query.setInt(2, volgnummer); query.execute(); } catch (SQLException ex) { throw new RuntimeException(ex); } } /** * Verwjderd alle spelstukken van een Spelbord uit de databank, aan de hand van * de gegeven spelnaam en volgnummer. * * @param volgnummer * @param spelnaam */ private void verwijderSpelstukkenVanSpelbord(int volgnummer, String spelnaam) { try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(DELETE_SPELSTUKKEN_VAN_SPELBORD)) { query.setString(1, spelnaam); query.setInt(2, volgnummer); query.execute(); } catch (SQLException ex) { throw new RuntimeException(ex); } } /** * Controleerd of de input niet langer is als de maximumlengte van de databank. * Als de input langer is deze ingekort tot 20. * * @param input * @return input substring(20) */ private String controleerLengte(String input) { if (input == null) { return null; } if (input.length() > 20) { return input.substring(0, 20); } return input; } }
Daellhin/HoGent-Sokoban
src/main/persistentie/SpelMapper.java
6,930
/** * Vervangt het Spelbord in de databank met het aangepaste Spelbord. * * @param volgnummer om het volgnummer in de databank te bepalen * @param spelbord * @param spelnaam */
block_comment
nl
package persistentie; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import domein.Spel; import domein.spelbord.Doel; import domein.spelbord.Muur; import domein.spelbord.Spelbord; import domein.spelbord.Vak; import domein.spelbord.Veld; public class SpelMapper { // selects private static final String SELECT_SPELNAMEN = "SELECT spelNaam FROM Spel"; private static final String SELECT_SPEL = "SELECT * FROM Spel WHERE spelNaam = ?"; private static final String SELECT_COUNT_SPELBORDEN = "SELECT COUNT(*) AS 'aantal' FROM Spelbord WHERE spelNaam = ?"; private static final String SELECT_SPELBORD = "SELECT * FROM Spelbord WHERE spelNaam = ?"; private static final String SELECT_SPELSTUK = "SELECT * FROM Spelstuk WHERE spelNaam = ? and spelbordNummer = ?"; private static final String SELECT_VAK = "SELECT * FROM Vak WHERE spelNaam = ? and spelbordNummer = ?"; private static final String SELECT_SPELNAAM = "SELECT spelNaam FROM Spel WHERE spelerNaam = ?"; // inserts private static final String INSERT_SPEL = "INSERT INTO Spel (spelNaam, spelerNaam) VALUES (?, ?)"; private static final String INSERT_SPELBORD = "INSERT INTO Spelbord (spelNaam, volgnummer) VALUES (?, ?)"; private static final String INSERT_SPELSTUK = "INSERT INTO Spelstuk (spelNaam, spelbordNummer, rijPos, kolPos, spelstukType) VALUES (?, ?, ?, ?, ?)"; private static final String INSERT_VAK = "INSERT INTO Vak (spelNaam, spelbordNummer, rijPos, kolPos, vakType) VALUES (?, ?, ?, ?, ?)"; // deletes private static final String DELETE_SPEL = "DELETE FROM Spel WHERE spelNaam = ?"; private static final String DELETE_SPELBORDEN = "DELETE FROM Spelbord WHERE spelNaam = ?"; private static final String DELETE_SPELSTUKKEN = "DELETE FROM Spelstuk WHERE spelNaam = ?"; private static final String DELETE_VAKKEN = "DELETE FROM Vak WHERE spelNaam = ?"; private static final String DELETE_SPELBORD = "DELETE FROM Spelbord WHERE spelNaam = ? and volgnummer = ?"; private static final String DELETE_VAKKEN_VAN_SPELBORD = "DELETE FROM Vak WHERE spelNaam = ? and spelbordNummer = ?"; private static final String DELETE_SPELSTUKKEN_VAN_SPELBORD = "DELETE FROM Spelstuk WHERE spelNaam = ? and spelbordNummer = ?"; /** * Default constructor. */ public SpelMapper() { } // methods /** * Haalt de namen van alle Spelletje op uit de databank. * * @return List met namen van de Spelletjes */ public List<String> geefSpelnamen() { List<String> namenVanSpelletjes = new ArrayList<>(); try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(SELECT_SPELNAMEN); ResultSet rs = query.executeQuery()) { while (rs.next()) { String naam = rs.getString("spelNaam"); namenVanSpelletjes.add(naam); } } catch (SQLException ex) { throw new RuntimeException(ex); } return namenVanSpelletjes; } /** * Haalt het Spel en zijn Spelborden op uit de databank, aan de hand van de * gegeven naam. * * @param naam * @return Spel */ public Spel geefSpel(String naam) { Spel spel = null; try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(SELECT_SPEL)) { query.setString(1, naam); ResultSet rs = query.executeQuery(); if (rs.next()) { Spelbord eersteSpelbord = geefSpelborden(naam); int aantalSpelborden = geefAantalSpelborden(naam); spel = new Spel(naam, eersteSpelbord, aantalSpelborden); } } catch (SQLException ex) { throw new RuntimeException(ex); } return spel; } /** * Telt het aantal spelborden in het Spel met de gegeven naam. * * @param naam * @return */ private int geefAantalSpelborden(String naam) { int aantalSpelborden = 0; try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(SELECT_COUNT_SPELBORDEN)) { query.setString(1, naam); ResultSet rs = query.executeQuery(); if (rs.next()) { aantalSpelborden = rs.getInt("aantal"); } } catch (SQLException ex) { throw new RuntimeException(ex); } return aantalSpelborden; } /** * Haalt de Spelborden en hun vakken en spelstukken op uit de databank, aan de * hand van de gegeven spelnaam. * * @param spelnaam * @return het eerste spelbord met de link naar de andere spelborden */ private Spelbord geefSpelborden(String spelnaam) { Spelbord eersteSpelbord = null; try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(SELECT_SPELBORD)) { query.setString(1, spelnaam); ResultSet rs = query.executeQuery(); int volgnummer = 0; if (rs.next()) { Vak[][] vakken = geefVakken(spelnaam, volgnummer); List<int[]> spelstukPosities = geefSpelstukPosities(spelnaam, volgnummer); int[] startPositieMannetje = spelstukPosities.get(0); spelstukPosities.remove(0); int[][] startPositiesKisten = spelstukPosities.toArray(new int[0][]); eersteSpelbord = new Spelbord(vakken, startPositieMannetje, startPositiesKisten); volgnummer++; } Spelbord tijdelijk = eersteSpelbord; while (rs.next()) { Vak[][] vakken = geefVakken(spelnaam, volgnummer); List<int[]> spelstukPosities = geefSpelstukPosities(spelnaam, volgnummer); int[] startPositieMannetje = spelstukPosities.get(0); spelstukPosities.remove(0); int[][] startPositiesKisten = spelstukPosities.toArray(new int[0][]); Spelbord spelbord = new Spelbord(vakken, startPositieMannetje, startPositiesKisten); tijdelijk.setVolgendSpelBord(spelbord); volgnummer++; tijdelijk = spelbord; } } catch (SQLException ex) { throw new RuntimeException(ex); } return eersteSpelbord; } /** * Haalt de spelstukken van een spelbord op. * * @param spelnaam * @param volgnumer van het spelbord * @return posities van de spelstukken, mannetje staat op de eerste positie in * de lijst */ private List<int[]> geefSpelstukPosities(String spelnaam, int volgnummer) { List<int[]> posities = new ArrayList<int[]>(); try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(SELECT_SPELSTUK)) { query.setString(1, spelnaam); query.setInt(2, volgnummer); ResultSet rs = query.executeQuery(); while (rs.next()) { if (rs.getString("spelstukType").equals("mannetje")) { posities.add(0, new int[] { rs.getInt("rijPos"), rs.getInt("kolPos") }); } else { posities.add(new int[] { rs.getInt("rijPos"), rs.getInt("kolPos") }); } } } catch (SQLException ex) { throw new RuntimeException(ex); } return posities; } /** * Haalt alle vakken van het spelbord met de gegeven spelnaam en volgnummer op. * * @param spelnaam * @param volgnummer van het spelbord * @return vakken */ private Vak[][] geefVakken(String spelnaam, int volgnummer) { Vak[][] vakken = new Vak[Spel.getMaxRijPos()][Spel.getMaxKolPos()]; try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(SELECT_VAK)) { query.setString(1, spelnaam); query.setInt(2, volgnummer); ResultSet rs = query.executeQuery(); while (rs.next()) { int rijPos = rs.getInt("rijPos"); int kolPos = rs.getInt("kolPos"); switch (rs.getString("vakType")) { case "veld": vakken[rijPos][kolPos] = new Veld(rijPos, kolPos); break; case "muur": vakken[rijPos][kolPos] = new Muur(rijPos, kolPos); break; case "doel": vakken[rijPos][kolPos] = new Doel(rijPos, kolPos); break; } } } catch (SQLException ex) { throw new RuntimeException(ex); } return vakken; } /** * Controleert of er al een Spel met gegeven naam bestaat in de databank. * * @param naam * @return true waneer het Spel gevonden word, anders false */ public boolean bestaatSpel(String naam) { try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(SELECT_SPEL)) { query.setString(1, naam); ResultSet rs = query.executeQuery(); if (rs.next()) { return true; } return false; } catch (SQLException ex) { throw new RuntimeException(ex); } } /** * Voegt het gegeven Spel en zijn Spelborden toe in de databank. * * @param spel * @param gebruikersnaam */ public void voegSpelToe(Spel spel, String gebruikersnaam) { String spelNaam = controleerLengte(spel.getNaam()); try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(INSERT_SPEL)) { query.setString(1, spelNaam); query.setString(2, gebruikersnaam); query.executeUpdate(); } catch (SQLException ex) { throw new RuntimeException(ex); } Spelbord tempSpelbord = spel.getEersteSpelbord(); int teller = 0; voegSpelbordToe(tempSpelbord, spelNaam, teller); while (tempSpelbord.getVolgendSpelBord() != null) { teller++; tempSpelbord = tempSpelbord.getVolgendSpelBord(); voegSpelbordToe(tempSpelbord, spelNaam, teller); } } /** * Voegt het gegeven Spelborden en zijn vakken en spelstukken toe in de * databank. * * @param spelbord * @param spelnaam * @param volgnummer */ private void voegSpelbordToe(Spelbord spelbord, String spelnaam, int volgnummer) { try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(INSERT_SPELBORD)) { query.setString(1, spelnaam); query.setInt(2, volgnummer); query.executeUpdate(); voegSpelstukkenToe(spelbord, spelnaam, volgnummer); voegVakkenToe(spelbord, spelnaam, volgnummer); } catch (SQLException ex) { throw new RuntimeException(ex); } } /** * Voegt de spelstukken van het gegeven Spelbord toe in de databank. * * @param spelbord * @param spelnaam * @param spelbordNummer */ private void voegSpelstukkenToe(Spelbord spelbord, String spelnaam, int spelbordNummer) { try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(INSERT_SPELSTUK)) { int[] positieMannetje = spelbord.getStartPositieMannetje(); query.setString(1, spelnaam); query.setInt(2, spelbordNummer); query.setInt(3, positieMannetje[0]); query.setInt(4, positieMannetje[1]); query.setString(5, "mannetje"); query.executeUpdate(); int[][] positiesKisten = spelbord.getStartPositiesKisten(); for (int[] is : positiesKisten) { query.setString(1, spelnaam); query.setInt(2, spelbordNummer); query.setInt(3, is[0]); query.setInt(4, is[1]); query.setString(5, "kist"); query.executeUpdate(); } } catch (SQLException ex) { throw new RuntimeException(ex); } } /** * Voegt de vakken van het gegeven Spelbord toe in de databank. * * @param spelbord * @param spelnaam * @param spelbordNummer */ private void voegVakkenToe(Spelbord spelbord, String spelnaam, int spelbordNummer) { try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(INSERT_VAK)) { Vak[][] vakken = spelbord.getVakken(); for (Vak[] vak1 : vakken) { for (Vak vak : vak1) { query.setString(1, spelnaam); query.setInt(2, spelbordNummer); query.setInt(3, vak.getrijPos()); query.setInt(4, vak.getkolPos()); query.setString(5, vak.getClass().getSimpleName().toLowerCase()); query.executeUpdate(); } } } catch (SQLException ex) { throw new RuntimeException(ex); } } /** * Haalt de spelnamen geassocieerd met de Speler op uit de databank. * * @param gebruikersnaam * @return spelnamen van de Speler */ public List<String> geefSpelNamen(String gebruikersnaam) { List<String> namenVanSpelletjes = new ArrayList<String>(); try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(SELECT_SPELNAAM)) { query.setString(1, gebruikersnaam); try (ResultSet rs = query.executeQuery()) { while (rs.next()) { String spelNaam = rs.getString("spelNaam"); namenVanSpelletjes.add(spelNaam); } } } catch (SQLException ex) { throw new RuntimeException(ex); } return namenVanSpelletjes; } /** * Verwijderd het Spel met de gegeven naam uit de databank. * * @param spelnaam */ public void verwijderVolledigSpel(String spelnaam) { verwijderVakken(spelnaam); verwijderSpelstukken(spelnaam); verwijderSpelborden(spelnaam); verwijderSpel(spelnaam); } /** * Verwjderd het Spel uit de databank, aan de hand van de gegeven spelnaam. * * @param spelnaam */ private void verwijderSpel(String spelnaam) { try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(DELETE_SPEL)) { query.setString(1, spelnaam); query.execute(); } catch (SQLException ex) { throw new RuntimeException(ex); } } /** * Verwjderd alle Spelborden van een Spel uit de databank, aan de hand van de * gegeven spelnaam. * * @param spelnaam */ private void verwijderSpelborden(String spelnaam) { try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(DELETE_SPELBORDEN)) { query.setString(1, spelnaam); query.execute(); } catch (SQLException ex) { throw new RuntimeException(ex); } } /** * Verwjderd alle spelstukken van een Spel uit de databank, aan de hand van de * gegeven spelnaam. * * @param spelnaam */ private void verwijderSpelstukken(String spelnaam) { try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(DELETE_SPELSTUKKEN)) { query.setString(1, spelnaam); query.execute(); } catch (SQLException ex) { throw new RuntimeException(ex); } } /** * Verwjderd alle vakken van een Spel uit de databank, aan de hand van de * gegeven spelnaam. * * @param spelnaam */ private void verwijderVakken(String spelnaam) { try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(DELETE_VAKKEN)) { query.setString(1, spelnaam); query.execute(); } catch (SQLException ex) { throw new RuntimeException(ex); } } /** * Vervangt het Spelbord<SUF>*/ public void vervangSpelbord(int volgnummerProg, Spelbord spelbord, String spelnaam) { int volgnummerDatabank = bepaalVolgnummerDatabank(spelnaam, volgnummerProg); verwijderSpelstukkenVanSpelbord(volgnummerDatabank, spelnaam); verwijderVakkenVanSpelbord(volgnummerDatabank, spelnaam); verwijderSpelbord(volgnummerDatabank, spelnaam); voegSpelbordToe(spelbord, spelnaam, volgnummerDatabank); } /** * Bepaal het volgnummer van het Spelbord dat moet vervangen worden in de * databank, aan de hand van het volgnummer in het programma. * * @param spelnaam * @param volgnummerProg * @return */ private int bepaalVolgnummerDatabank(String spelnaam, int volgnummerProg) { try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(SELECT_SPELBORD)) { query.setString(1, spelnaam); ResultSet rs = query.executeQuery(); int teller = 1; while (rs.next()) { if (teller == volgnummerProg) { return rs.getInt("volgnummer"); } teller++; } } catch (SQLException ex) { throw new RuntimeException(ex); } return -1; } /** * Verwijderd een Spelbord uit de databank, aan de hand van de gegeven spelnaam * en volgnummer. * * @param volgnummer * @param spelnaam */ private void verwijderSpelbord(int volgnummer, String spelnaam) { try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(DELETE_SPELBORD)) { query.setString(1, spelnaam); query.setInt(2, volgnummer); query.execute(); } catch (SQLException ex) { throw new RuntimeException(ex); } } /** * Verwjderd alle vakken van een Spelbord uit de databank, aan de hand van de * gegeven spelnaam en volgnummer. * * @param volgnummer * @param spelnaam */ private void verwijderVakkenVanSpelbord(int volgnummer, String spelnaam) { try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(DELETE_VAKKEN_VAN_SPELBORD)) { query.setString(1, spelnaam); query.setInt(2, volgnummer); query.execute(); } catch (SQLException ex) { throw new RuntimeException(ex); } } /** * Verwjderd alle spelstukken van een Spelbord uit de databank, aan de hand van * de gegeven spelnaam en volgnummer. * * @param volgnummer * @param spelnaam */ private void verwijderSpelstukkenVanSpelbord(int volgnummer, String spelnaam) { try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL); PreparedStatement query = conn.prepareStatement(DELETE_SPELSTUKKEN_VAN_SPELBORD)) { query.setString(1, spelnaam); query.setInt(2, volgnummer); query.execute(); } catch (SQLException ex) { throw new RuntimeException(ex); } } /** * Controleerd of de input niet langer is als de maximumlengte van de databank. * Als de input langer is deze ingekort tot 20. * * @param input * @return input substring(20) */ private String controleerLengte(String input) { if (input == null) { return null; } if (input.length() > 20) { return input.substring(0, 20); } return input; } }
169865_2
package testen.beheerders; import java.math.BigDecimal; import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import domain.Adres; import domain.Contactpersoon; import domain.Contract; import domain.ContractType; import domain.Klant; import domain.Ticket; import domain.beheerders.StatistiekBeheerder; import domain.dao.StatistiekDao; import domain.dao.TicketDao; import domain.enumerations.ContractDoorlooptijd; import domain.enumerations.ContractStatus; import domain.enumerations.ContractTypeStatus; import domain.enumerations.Dienst; import domain.enumerations.StatistiekType; import domain.enumerations.TicketAanmaakManier; import domain.enumerations.TicketAanmaakTijd; import domain.enumerations.TicketUrgency; import domain.statistieken.AantalOpgelosteTicketsPerKlant; import domain.statistieken.GemiddeldeDoorlooptijdPerContractType; import domain.statistieken.Statistiek; @ExtendWith(MockitoExtension.class) public class StatistiekBeheerderTest { @Mock private StatistiekDao statistiekDao; @Mock private TicketDao ticketDao; @InjectMocks private StatistiekBeheerder statistiekBeheerder; List<StatistiekType> statistiekTypes; private List<StatistiekType> maakStatistiekTypesLijst() { List<StatistiekType> statistiekTypes = new ArrayList<>(); statistiekTypes.add(StatistiekType.AmountOfFinishedTicketsPerCustomer); statistiekTypes.add(StatistiekType.AverageDurationTicketsPerContractType); return statistiekTypes; } private List<Ticket> maakTicketsAan() { List<ContractType> lijstContractTypes; // contractTypes aanmaken lijstContractTypes = new ArrayList<>(); ContractType contractType1 = new ContractType("ContractType1", new HashSet<>(Arrays.asList(TicketAanmaakManier.Application)), TicketAanmaakTijd.AllTime, 1, ContractDoorlooptijd.OneYear, new BigDecimal(7)); ContractType contractType2 = new ContractType("ContractType2", new HashSet<>(Arrays.asList(TicketAanmaakManier.Email)), TicketAanmaakTijd.WorkingHours, 5, ContractDoorlooptijd.TwoYear, new BigDecimal(3)); ContractType contractType3 = new ContractType("ContractType3", new HashSet<>(Arrays.asList(TicketAanmaakManier.Telephone, TicketAanmaakManier.Email)), TicketAanmaakTijd.AllTime, 3, ContractDoorlooptijd.ThreeYear, new BigDecimal(1)); contractType3.setStatus(ContractTypeStatus.Inactive); lijstContractTypes.add(contractType1); lijstContractTypes.add(contractType2); lijstContractTypes.add(contractType3); // klanten + contracten aanmaken Klant klant1 = new Klant("B-Temium", Arrays.asList("+32472643661"), new Adres("BE", "9000", "Gent", "Straattraat", 5), "B-Temium Inc.", Arrays.asList(new Contactpersoon("[email protected]", "Bee", "Temium"))); Contract contract1 = new Contract(contractType1, ContractStatus.Active, LocalDate.now(), LocalDate.now().plusDays(400), klant1); Contract contract2 = new Contract(contractType1, ContractStatus.Active, LocalDate.now().plusDays(2), LocalDate.now().plusDays(380), klant1); Contract contract3 = new Contract(contractType2, ContractStatus.Active, LocalDate.now().plusDays(6), LocalDate.now().plusDays(450), klant1); // ticketList aanmaken Ticket ticket1 = new Ticket("Title1", TicketUrgency.ProductionImpacted, "omschrijving1", new ArrayList<>(), contract1, Dienst.Finance); Ticket ticket2 = new Ticket("Title2", TicketUrgency.NoProductionImpact, "omschrijving2", new ArrayList<>(), contract1, Dienst.Admin); Ticket ticket3 = new Ticket("Title3", TicketUrgency.ProductionWillBeImpacted, "omschrijving3", new ArrayList<>(), contract3, Dienst.IT); List<Ticket> ticketList = new ArrayList<>(); ticketList.add(ticket1); ticketList.add(ticket2); ticketList.add(ticket3); return ticketList; } private List<Statistiek<?>> maakStatistiekObjectenAan(List<Ticket> ticketList) { List<Statistiek<?>> statistiekLijst = new ArrayList<>(); Statistiek<?> statistiek1 = new Statistiek<>(StatistiekType.AmountOfFinishedTicketsPerCustomer, ticketList, new AantalOpgelosteTicketsPerKlant()); Statistiek<?> statistiek2 = new Statistiek<>(StatistiekType.AverageDurationTicketsPerContractType, ticketList, new GemiddeldeDoorlooptijdPerContractType()); statistiekLijst.add(statistiek1); statistiekLijst.add(statistiek2); return statistiekLijst; } @Test public void getTickets_geeftLijstTickets() { // Arange List<Ticket> ticketList = maakTicketsAan(); Mockito.when(ticketDao.findAll()).thenReturn(ticketList); // Act statistiekBeheerder.getTickets(); // Assert Mockito.verify(ticketDao).findAll(); } @Test public void getTrackedStatistiekTypes_roeptJuisteMethodeAan() { statistiekTypes = maakStatistiekTypesLijst(); Mockito.when(statistiekDao.geefTrackedStatistiekTypes()).thenReturn(statistiekTypes); List<StatistiekType> statistiekTypesTest = statistiekBeheerder.getTrackedStatistiekTypes(); Assertions.assertEquals(statistiekTypesTest, statistiekTypes); } @Test public void newStatistiekBeheerder_geeftTrackedStatistieken() { // Arange statistiekTypes = maakStatistiekTypesLijst(); Mockito.when(statistiekDao.geefTrackedStatistiekTypes()).thenReturn(statistiekTypes); List<Statistiek<?>> statistiekLijst = maakStatistiekObjectenAan(maakTicketsAan()); // Act List<Statistiek<?>> teTestenStatistiekLijst = statistiekBeheerder.getTrackedStatistieken(); // Assert Assertions.assertEquals(statistiekLijst.get(0).getType(), teTestenStatistiekLijst.get(0).getType()); Assertions.assertEquals(statistiekLijst.get(1).getType(), teTestenStatistiekLijst.get(1).getType()); // Logica voor de verwerkte map aan te maken zit in een andere klasse. // Moet dit dan getest worden? // Assertions.assertEquals(statistiekLijst.get(0).getVerwerkteData(), // teTestenStatistiekLijst.get(0).getVerwerkteData()); // Assertions.assertEquals(statistiekLijst.get(1).getVerwerkteData(), // teTestenStatistiekLijst.get(1).getVerwerkteData()); } }
Daellhin/HoGent-TicketingDesktopApp
src/testen/beheerders/StatistiekBeheerderTest.java
2,229
// Moet dit dan getest worden?
line_comment
nl
package testen.beheerders; import java.math.BigDecimal; import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import domain.Adres; import domain.Contactpersoon; import domain.Contract; import domain.ContractType; import domain.Klant; import domain.Ticket; import domain.beheerders.StatistiekBeheerder; import domain.dao.StatistiekDao; import domain.dao.TicketDao; import domain.enumerations.ContractDoorlooptijd; import domain.enumerations.ContractStatus; import domain.enumerations.ContractTypeStatus; import domain.enumerations.Dienst; import domain.enumerations.StatistiekType; import domain.enumerations.TicketAanmaakManier; import domain.enumerations.TicketAanmaakTijd; import domain.enumerations.TicketUrgency; import domain.statistieken.AantalOpgelosteTicketsPerKlant; import domain.statistieken.GemiddeldeDoorlooptijdPerContractType; import domain.statistieken.Statistiek; @ExtendWith(MockitoExtension.class) public class StatistiekBeheerderTest { @Mock private StatistiekDao statistiekDao; @Mock private TicketDao ticketDao; @InjectMocks private StatistiekBeheerder statistiekBeheerder; List<StatistiekType> statistiekTypes; private List<StatistiekType> maakStatistiekTypesLijst() { List<StatistiekType> statistiekTypes = new ArrayList<>(); statistiekTypes.add(StatistiekType.AmountOfFinishedTicketsPerCustomer); statistiekTypes.add(StatistiekType.AverageDurationTicketsPerContractType); return statistiekTypes; } private List<Ticket> maakTicketsAan() { List<ContractType> lijstContractTypes; // contractTypes aanmaken lijstContractTypes = new ArrayList<>(); ContractType contractType1 = new ContractType("ContractType1", new HashSet<>(Arrays.asList(TicketAanmaakManier.Application)), TicketAanmaakTijd.AllTime, 1, ContractDoorlooptijd.OneYear, new BigDecimal(7)); ContractType contractType2 = new ContractType("ContractType2", new HashSet<>(Arrays.asList(TicketAanmaakManier.Email)), TicketAanmaakTijd.WorkingHours, 5, ContractDoorlooptijd.TwoYear, new BigDecimal(3)); ContractType contractType3 = new ContractType("ContractType3", new HashSet<>(Arrays.asList(TicketAanmaakManier.Telephone, TicketAanmaakManier.Email)), TicketAanmaakTijd.AllTime, 3, ContractDoorlooptijd.ThreeYear, new BigDecimal(1)); contractType3.setStatus(ContractTypeStatus.Inactive); lijstContractTypes.add(contractType1); lijstContractTypes.add(contractType2); lijstContractTypes.add(contractType3); // klanten + contracten aanmaken Klant klant1 = new Klant("B-Temium", Arrays.asList("+32472643661"), new Adres("BE", "9000", "Gent", "Straattraat", 5), "B-Temium Inc.", Arrays.asList(new Contactpersoon("[email protected]", "Bee", "Temium"))); Contract contract1 = new Contract(contractType1, ContractStatus.Active, LocalDate.now(), LocalDate.now().plusDays(400), klant1); Contract contract2 = new Contract(contractType1, ContractStatus.Active, LocalDate.now().plusDays(2), LocalDate.now().plusDays(380), klant1); Contract contract3 = new Contract(contractType2, ContractStatus.Active, LocalDate.now().plusDays(6), LocalDate.now().plusDays(450), klant1); // ticketList aanmaken Ticket ticket1 = new Ticket("Title1", TicketUrgency.ProductionImpacted, "omschrijving1", new ArrayList<>(), contract1, Dienst.Finance); Ticket ticket2 = new Ticket("Title2", TicketUrgency.NoProductionImpact, "omschrijving2", new ArrayList<>(), contract1, Dienst.Admin); Ticket ticket3 = new Ticket("Title3", TicketUrgency.ProductionWillBeImpacted, "omschrijving3", new ArrayList<>(), contract3, Dienst.IT); List<Ticket> ticketList = new ArrayList<>(); ticketList.add(ticket1); ticketList.add(ticket2); ticketList.add(ticket3); return ticketList; } private List<Statistiek<?>> maakStatistiekObjectenAan(List<Ticket> ticketList) { List<Statistiek<?>> statistiekLijst = new ArrayList<>(); Statistiek<?> statistiek1 = new Statistiek<>(StatistiekType.AmountOfFinishedTicketsPerCustomer, ticketList, new AantalOpgelosteTicketsPerKlant()); Statistiek<?> statistiek2 = new Statistiek<>(StatistiekType.AverageDurationTicketsPerContractType, ticketList, new GemiddeldeDoorlooptijdPerContractType()); statistiekLijst.add(statistiek1); statistiekLijst.add(statistiek2); return statistiekLijst; } @Test public void getTickets_geeftLijstTickets() { // Arange List<Ticket> ticketList = maakTicketsAan(); Mockito.when(ticketDao.findAll()).thenReturn(ticketList); // Act statistiekBeheerder.getTickets(); // Assert Mockito.verify(ticketDao).findAll(); } @Test public void getTrackedStatistiekTypes_roeptJuisteMethodeAan() { statistiekTypes = maakStatistiekTypesLijst(); Mockito.when(statistiekDao.geefTrackedStatistiekTypes()).thenReturn(statistiekTypes); List<StatistiekType> statistiekTypesTest = statistiekBeheerder.getTrackedStatistiekTypes(); Assertions.assertEquals(statistiekTypesTest, statistiekTypes); } @Test public void newStatistiekBeheerder_geeftTrackedStatistieken() { // Arange statistiekTypes = maakStatistiekTypesLijst(); Mockito.when(statistiekDao.geefTrackedStatistiekTypes()).thenReturn(statistiekTypes); List<Statistiek<?>> statistiekLijst = maakStatistiekObjectenAan(maakTicketsAan()); // Act List<Statistiek<?>> teTestenStatistiekLijst = statistiekBeheerder.getTrackedStatistieken(); // Assert Assertions.assertEquals(statistiekLijst.get(0).getType(), teTestenStatistiekLijst.get(0).getType()); Assertions.assertEquals(statistiekLijst.get(1).getType(), teTestenStatistiekLijst.get(1).getType()); // Logica voor de verwerkte map aan te maken zit in een andere klasse. // Moet dit<SUF> // Assertions.assertEquals(statistiekLijst.get(0).getVerwerkteData(), // teTestenStatistiekLijst.get(0).getVerwerkteData()); // Assertions.assertEquals(statistiekLijst.get(1).getVerwerkteData(), // teTestenStatistiekLijst.get(1).getVerwerkteData()); } }
120081_8
package be.ugent.oplossing.model; import be.ugent.oplossing.show.RubiksReader; import javafx.scene.paint.Color; import java.io.File; import java.io.FileNotFoundException; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; public class RubiksKubus implements IRubikCube { private List<Kubusje> kubusjes; // Alle gegevens voor de 27 kubusjes werden in een excel-bestand ingevuld en bewaard. // Excel biedt dankzij z'n kolommen een duidelijk overzicht, er kan heel gestructureerd gewerkt // (en gecontroleerd) worden. // Inlezen van het bestand werd afgekeken van de gegeven code in de show-map. // (Moet niet gekend zijn voor op het examen.) public RubiksKubus() throws FileNotFoundException { kubusjes = new ArrayList<>(); Scanner sc = new Scanner(new File(Objects.requireNonNull(RubiksReader.class.getResource("kubussen_xyz.csv")).getFile())); while (sc.hasNext()) { Scanner sc_ = new Scanner(sc.nextLine()); sc_.useDelimiter(";"); int x = sc_.nextInt(); int y = sc_.nextInt(); int z = sc_.nextInt(); String[] kleuren = new String[6]; for (int i = 0; i < 6; i++) { kleuren[i] = sc_.next(); } kubusjes.add(new Kubusje(x, y, z, kleuren)); } } // Dit kan je gebruiken om zelf te testen, zolang de view er nog niet is. // Layout niet handig? Pas zelf aan. public String toString() { // kan je later met streams doen String[] strings = new String[kubusjes.size()]; int i = 0; for (Kubusje kubus : kubusjes) { strings[i++] = kubus.toString(); } return String.join("\n", strings); } // Deze methode wordt gebruikt door het showteam om de View te maken. // Meer is er niet nodig (in tegenstelling tot wat in sprint0 aangekondigd werd, // dus geen onderscheid tussen zichtbare en onzichtbare vlakjes). @Override public List<IFace> getAllFaces() { return kubusjes.stream().flatMap(e -> Arrays.stream(e.getVlakjes())).collect(Collectors.toList()); } @Override public List<IFace> getRotation(Color color, int degree) { AxisColor axisColor = AxisColor.getAxisColorFromColor(color); double angle = degree * Math.signum(axisColor.number); var rotatedFaces = kubusjes.stream() .filter(e -> e.getCentrumHoekPunt().getAxis(axisColor.axis) == axisColor.number) .flatMap(e -> e.copyAndRotate(angle, axisColor.axis).stream()); var unRotatedFaces = kubusjes.stream() .filter(e -> e.getCentrumHoekPunt().getAxis(axisColor.axis) != axisColor.number) .flatMap(e -> Arrays.stream(e.getVlakjes())); return Stream.concat(rotatedFaces, unRotatedFaces).toList(); } @Override public void rotate(Color color, boolean clockwise) { AxisColor axisColor = AxisColor.getAxisColorFromColor(color); double angle = ((clockwise ? 0 : 1) * 2 - 1) * 90 * Math.signum(axisColor.number); kubusjes.stream() .filter(e -> e.getCentrumHoekPunt().getAxis(axisColor.axis) == axisColor.number) .forEach(e -> e.rotate(angle, axisColor.axis)); } public List<Kubusje> getKubusjes() { return kubusjes; } }
Daellhin/UGent-RubicsCube
src/main/java/be/ugent/oplossing/model/RubiksKubus.java
1,095
// Deze methode wordt gebruikt door het showteam om de View te maken.
line_comment
nl
package be.ugent.oplossing.model; import be.ugent.oplossing.show.RubiksReader; import javafx.scene.paint.Color; import java.io.File; import java.io.FileNotFoundException; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; public class RubiksKubus implements IRubikCube { private List<Kubusje> kubusjes; // Alle gegevens voor de 27 kubusjes werden in een excel-bestand ingevuld en bewaard. // Excel biedt dankzij z'n kolommen een duidelijk overzicht, er kan heel gestructureerd gewerkt // (en gecontroleerd) worden. // Inlezen van het bestand werd afgekeken van de gegeven code in de show-map. // (Moet niet gekend zijn voor op het examen.) public RubiksKubus() throws FileNotFoundException { kubusjes = new ArrayList<>(); Scanner sc = new Scanner(new File(Objects.requireNonNull(RubiksReader.class.getResource("kubussen_xyz.csv")).getFile())); while (sc.hasNext()) { Scanner sc_ = new Scanner(sc.nextLine()); sc_.useDelimiter(";"); int x = sc_.nextInt(); int y = sc_.nextInt(); int z = sc_.nextInt(); String[] kleuren = new String[6]; for (int i = 0; i < 6; i++) { kleuren[i] = sc_.next(); } kubusjes.add(new Kubusje(x, y, z, kleuren)); } } // Dit kan je gebruiken om zelf te testen, zolang de view er nog niet is. // Layout niet handig? Pas zelf aan. public String toString() { // kan je later met streams doen String[] strings = new String[kubusjes.size()]; int i = 0; for (Kubusje kubus : kubusjes) { strings[i++] = kubus.toString(); } return String.join("\n", strings); } // Deze methode<SUF> // Meer is er niet nodig (in tegenstelling tot wat in sprint0 aangekondigd werd, // dus geen onderscheid tussen zichtbare en onzichtbare vlakjes). @Override public List<IFace> getAllFaces() { return kubusjes.stream().flatMap(e -> Arrays.stream(e.getVlakjes())).collect(Collectors.toList()); } @Override public List<IFace> getRotation(Color color, int degree) { AxisColor axisColor = AxisColor.getAxisColorFromColor(color); double angle = degree * Math.signum(axisColor.number); var rotatedFaces = kubusjes.stream() .filter(e -> e.getCentrumHoekPunt().getAxis(axisColor.axis) == axisColor.number) .flatMap(e -> e.copyAndRotate(angle, axisColor.axis).stream()); var unRotatedFaces = kubusjes.stream() .filter(e -> e.getCentrumHoekPunt().getAxis(axisColor.axis) != axisColor.number) .flatMap(e -> Arrays.stream(e.getVlakjes())); return Stream.concat(rotatedFaces, unRotatedFaces).toList(); } @Override public void rotate(Color color, boolean clockwise) { AxisColor axisColor = AxisColor.getAxisColorFromColor(color); double angle = ((clockwise ? 0 : 1) * 2 - 1) * 90 * Math.signum(axisColor.number); kubusjes.stream() .filter(e -> e.getCentrumHoekPunt().getAxis(axisColor.axis) == axisColor.number) .forEach(e -> e.rotate(angle, axisColor.axis)); } public List<Kubusje> getKubusjes() { return kubusjes; } }
38772_0
package Facade; public class TestBankAccount { public static void main(String[] args) { //nieuwe facade maken en bank account nr 123456 gebruiken met code 1234 BankAccountFacade accessingBank = new BankAccountFacade(123456, 1234); accessingBank.withDrawCash(50.00); accessingBank.withDrawCash(900.00); accessingBank.depositCash(200.00); accessingBank.depositCash(150.00); } }
DalderupMaurice/Facade_Pattern_Demo
src/Facade/TestBankAccount.java
143
//nieuwe facade maken en bank account nr 123456 gebruiken met code 1234
line_comment
nl
package Facade; public class TestBankAccount { public static void main(String[] args) { //nieuwe facade<SUF> BankAccountFacade accessingBank = new BankAccountFacade(123456, 1234); accessingBank.withDrawCash(50.00); accessingBank.withDrawCash(900.00); accessingBank.depositCash(200.00); accessingBank.depositCash(150.00); } }
65066_6
package com.nhlstenden.amazonsimulatie.tests; import com.nhlstenden.amazonsimulatie.models.Model; import com.nhlstenden.amazonsimulatie.models.Object3D; import com.nhlstenden.amazonsimulatie.views.DefaultWebSocketView; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class DefaultWebSocketViewTests { /** * De code hieronder is een voorbeeld van een test in Java. Je schrijf per class die je wilt testen * een testclass zoals deze. Daarin zet je al je testfuncties. Vaak schrijf je per methode (of functie) * die je wilt testen een methode zoals deze hieronder. Kijk in de methode naar de genummerde comments. * Om de test het beste te begrijpen, begin je vanaf comment #1. */ @Test public void testUpdateSignal() throws Exception { /** * Comment #2 * Deze code hieronder hebben we nodig om de DefaultWebSocketView van comment 1 te kunnen maken. * Dat onderdeel van de software heeft een zogenaamde WebSocketSession nodig (een onderdeel waarmee * informatie via een websocket naar de webbrowser kan worden verstuurd). Een WebSocketSession is * normaal gesproken een onderdeel van het websocket systeem van onze server, en we kunnen niet * zomaar een WebSocketSession aanmaken wanneer er geen server draait, laat staan geen browser is. * Om dit toch te kunnen gebruiken, 'mocken' we de class WebSocketSession. Dit mocken betekent dat * we als het ware een 'nep' versie van het object maken. Deze 'mockSession'n (zie hieronder) is * een object dat wel alle methoden heeft van een echte WebSocketSession, maar de methoden doen * simpelweg niks. Hierdoor kun je code die een WebSocketSession nodig heeft, toch laten werken. * Ga nu naar comment #3. */ WebSocketSession mockSession = mock(WebSocketSession.class); /** * Comment #3 * De code hieronder is eigenlijk de invulling van een methode van WebSocketSession. Zoals je in * comment #2 las, is de het object mockSession een 'lege' WebSocketSession. De methoden bestaan dus * wel, maar doen in feite niks. Hieronder wordt een invulling gegeven. De when() functie is onderdeel * van het systeem om te mocken, en zegt hier wanneer de methode .isOpen() wordt aangeroepen op het object * mockSession, dan moet er iets gebeuren. Wat er moet gebeuren staat achter de when() methode, in de * vorm van .thenReturn(true). De hele regel code betekent nu dat wanneer .isOpen() wordt aangeroepen * op mockSession, dan moet deze methode altijd de waarde true teruggeven. Dit onderdeel is nodig omdat * de view in de update methode gebruikmaakt van de .isOpen() methode. Ga nu naar comment #4. */ when(mockSession.isOpen()).thenReturn(true); /** * Comment 4 * De code hieronder is misschien wat onduidelijk. Wat we hier doen, is het injecteren van testcode binnen * het mockSession object. Dit doen we omdat mockSession gebruikt wordt om het JSON pakketje te versturen. * Dit object krijgt dus sowieso de JSON tekst te zien. Dit gebeurd in de methode .sendMessage(). Hier wordt * een tekstbericht verstuurd naar de browser. In dit bericht zit de JSON code. Hier kunnen we dus een test * injecteren om de validiteit van de JSON de controleren. Dit is ook wat hieronder gebeurd. De methode * doAnwser hieronder zorgt ervoor dat de code die daarin wordt gegeven wordt uitgevoerd wanneer de * methode .sendMessage wordt aangeroepen. Het onderdeel daarna met 'new TextMessage(anyString())' * betekent dat die nieuwe code moet worden uitgevoerd voor de methode .sendMessage(), wanneer er * aan .sendMessage() een object TextMessage wordt meegegeven waar elke bedenkbare string in mag * zitten (vandaar de anyString()). Ga nu naar comment #5. */ doAnswer(new Answer<Void>() { public Void answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); /** * Comment #5 * Deze code hieronder is de daadwerkelijke testcode. De methode assertThat() controleert of iets dat je opgeeft * dat waar moet zijn, daadwerkelijk ook zo is. In dit geval wordt gecontroleerd of het binnengekomen object * TextMessage (zit op index 0 van args) een JSON string in zich heeft die gelijk is aan de opgegeven string * daar rechts van. Via de is() methode wordt aangegeven dat beide strings gelijk moeten zijn. De JSON wordt * gemaakt van een Object3D dat geupdate wordt (zie update methode in de DefaultWebSocketView class). In de * JSON code hieronder zie je dat voor elke parameter in de JSON een standaardwaarde is ingevoerd. Ga nu naar * comment #6 om te zien hoe we ervoor zorgen dat de update() methode ook gebruiktmaakt van die standaardwaarden. */ assertThat(((TextMessage)args[0]).getPayload(), is("{\"command\": \"object_update\",\"parameters\": {\"uuid\":\"unique_string\",\"type\":\"type_here\",\"x\":0.0,\"y\":0.0,\"z\":0.0,\"rotationX\":0.0,\"rotationY\":0.0,\"rotationZ\":0.0,\"status\":\"status_here\"}}")); return null; } }).when(mockSession).sendMessage(new TextMessage(anyString())); /** * Comment #1 * De testfunctie waar we nu inzitten heet testUpdateSignal. Dit updatesignal slaat op het updaten van een * view binnen de simulatie. Wanneer dat gebeurd, wordt er een JSON pakketje naar de webbrowser van die * view gestuurd. We gaan dit systeem simuleren om zo de validiteit van de JSON te kunnen testen. Daarvoor * hebben we eerst een nieuwe view nodig. Die wordt hieronder aangemaakt. Om een DefaultWebSocketView aan te * maken, hebben we iets van een websocket nodig (in dit geval een sessie, zie de projectcode). Zie comment #2. */ DefaultWebSocketView view = new DefaultWebSocketView(mockSession); /** * Commeent #6 * Hieronder wordt een Object3D aangemaakt. Dit doen we omdat de view.update() methode een Object3D nodig heeft. * Voor een Object3D geldt ook dat een simulatie nodig is om een Object3D object te kunnen krijgen. Omdat we de * simulatie niet draaien, mocken we een Object3D. We maken er dus als het ware eentje na. Hier voeren we de * standaardwaarden in die de JSON code bij comment #5 gebruikt om te controleren of de .update() methode van * view werkt. Ga nu naar comment #7 om te zien welke code de test in zijn werk zet. */ Object3D mockObj3D = mock(Object3D.class); when(mockObj3D.getUUID()).thenReturn("unique_string"); when(mockObj3D.getType()).thenReturn("type_here"); when(mockObj3D.getX()).thenReturn(0.0); when(mockObj3D.getY()).thenReturn(0.0); when(mockObj3D.getZ()).thenReturn(0.0); when(mockObj3D.getRotationX()).thenReturn(0.0); when(mockObj3D.getRotationY()).thenReturn(0.0); when(mockObj3D.getRotationZ()).thenReturn(0.0); when(mockObj3D.getStatus()).thenReturn("status_here"); /** * Comment #7 * De code hieronder activeert de .update() methode van view. Deze methode maakt van een Object3D (hier mockObj3D) * een JSON pakket en verstuurd deze via een websocket connectie. In de websocket connectie hebben we onze testcode * geïnjecteerd, en dit betekent dat dan de test ook zal worden uitgoerd. */ view.update(Model.UPDATE_COMMAND, mockObj3D); } }
Damiaen/AmazonSimulatie
src/test/java/com/nhlstenden/amazonsimulatie/tests/DefaultWebSocketViewTests.java
2,315
/** * Commeent #6 * Hieronder wordt een Object3D aangemaakt. Dit doen we omdat de view.update() methode een Object3D nodig heeft. * Voor een Object3D geldt ook dat een simulatie nodig is om een Object3D object te kunnen krijgen. Omdat we de * simulatie niet draaien, mocken we een Object3D. We maken er dus als het ware eentje na. Hier voeren we de * standaardwaarden in die de JSON code bij comment #5 gebruikt om te controleren of de .update() methode van * view werkt. Ga nu naar comment #7 om te zien welke code de test in zijn werk zet. */
block_comment
nl
package com.nhlstenden.amazonsimulatie.tests; import com.nhlstenden.amazonsimulatie.models.Model; import com.nhlstenden.amazonsimulatie.models.Object3D; import com.nhlstenden.amazonsimulatie.views.DefaultWebSocketView; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class DefaultWebSocketViewTests { /** * De code hieronder is een voorbeeld van een test in Java. Je schrijf per class die je wilt testen * een testclass zoals deze. Daarin zet je al je testfuncties. Vaak schrijf je per methode (of functie) * die je wilt testen een methode zoals deze hieronder. Kijk in de methode naar de genummerde comments. * Om de test het beste te begrijpen, begin je vanaf comment #1. */ @Test public void testUpdateSignal() throws Exception { /** * Comment #2 * Deze code hieronder hebben we nodig om de DefaultWebSocketView van comment 1 te kunnen maken. * Dat onderdeel van de software heeft een zogenaamde WebSocketSession nodig (een onderdeel waarmee * informatie via een websocket naar de webbrowser kan worden verstuurd). Een WebSocketSession is * normaal gesproken een onderdeel van het websocket systeem van onze server, en we kunnen niet * zomaar een WebSocketSession aanmaken wanneer er geen server draait, laat staan geen browser is. * Om dit toch te kunnen gebruiken, 'mocken' we de class WebSocketSession. Dit mocken betekent dat * we als het ware een 'nep' versie van het object maken. Deze 'mockSession'n (zie hieronder) is * een object dat wel alle methoden heeft van een echte WebSocketSession, maar de methoden doen * simpelweg niks. Hierdoor kun je code die een WebSocketSession nodig heeft, toch laten werken. * Ga nu naar comment #3. */ WebSocketSession mockSession = mock(WebSocketSession.class); /** * Comment #3 * De code hieronder is eigenlijk de invulling van een methode van WebSocketSession. Zoals je in * comment #2 las, is de het object mockSession een 'lege' WebSocketSession. De methoden bestaan dus * wel, maar doen in feite niks. Hieronder wordt een invulling gegeven. De when() functie is onderdeel * van het systeem om te mocken, en zegt hier wanneer de methode .isOpen() wordt aangeroepen op het object * mockSession, dan moet er iets gebeuren. Wat er moet gebeuren staat achter de when() methode, in de * vorm van .thenReturn(true). De hele regel code betekent nu dat wanneer .isOpen() wordt aangeroepen * op mockSession, dan moet deze methode altijd de waarde true teruggeven. Dit onderdeel is nodig omdat * de view in de update methode gebruikmaakt van de .isOpen() methode. Ga nu naar comment #4. */ when(mockSession.isOpen()).thenReturn(true); /** * Comment 4 * De code hieronder is misschien wat onduidelijk. Wat we hier doen, is het injecteren van testcode binnen * het mockSession object. Dit doen we omdat mockSession gebruikt wordt om het JSON pakketje te versturen. * Dit object krijgt dus sowieso de JSON tekst te zien. Dit gebeurd in de methode .sendMessage(). Hier wordt * een tekstbericht verstuurd naar de browser. In dit bericht zit de JSON code. Hier kunnen we dus een test * injecteren om de validiteit van de JSON de controleren. Dit is ook wat hieronder gebeurd. De methode * doAnwser hieronder zorgt ervoor dat de code die daarin wordt gegeven wordt uitgevoerd wanneer de * methode .sendMessage wordt aangeroepen. Het onderdeel daarna met 'new TextMessage(anyString())' * betekent dat die nieuwe code moet worden uitgevoerd voor de methode .sendMessage(), wanneer er * aan .sendMessage() een object TextMessage wordt meegegeven waar elke bedenkbare string in mag * zitten (vandaar de anyString()). Ga nu naar comment #5. */ doAnswer(new Answer<Void>() { public Void answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); /** * Comment #5 * Deze code hieronder is de daadwerkelijke testcode. De methode assertThat() controleert of iets dat je opgeeft * dat waar moet zijn, daadwerkelijk ook zo is. In dit geval wordt gecontroleerd of het binnengekomen object * TextMessage (zit op index 0 van args) een JSON string in zich heeft die gelijk is aan de opgegeven string * daar rechts van. Via de is() methode wordt aangegeven dat beide strings gelijk moeten zijn. De JSON wordt * gemaakt van een Object3D dat geupdate wordt (zie update methode in de DefaultWebSocketView class). In de * JSON code hieronder zie je dat voor elke parameter in de JSON een standaardwaarde is ingevoerd. Ga nu naar * comment #6 om te zien hoe we ervoor zorgen dat de update() methode ook gebruiktmaakt van die standaardwaarden. */ assertThat(((TextMessage)args[0]).getPayload(), is("{\"command\": \"object_update\",\"parameters\": {\"uuid\":\"unique_string\",\"type\":\"type_here\",\"x\":0.0,\"y\":0.0,\"z\":0.0,\"rotationX\":0.0,\"rotationY\":0.0,\"rotationZ\":0.0,\"status\":\"status_here\"}}")); return null; } }).when(mockSession).sendMessage(new TextMessage(anyString())); /** * Comment #1 * De testfunctie waar we nu inzitten heet testUpdateSignal. Dit updatesignal slaat op het updaten van een * view binnen de simulatie. Wanneer dat gebeurd, wordt er een JSON pakketje naar de webbrowser van die * view gestuurd. We gaan dit systeem simuleren om zo de validiteit van de JSON te kunnen testen. Daarvoor * hebben we eerst een nieuwe view nodig. Die wordt hieronder aangemaakt. Om een DefaultWebSocketView aan te * maken, hebben we iets van een websocket nodig (in dit geval een sessie, zie de projectcode). Zie comment #2. */ DefaultWebSocketView view = new DefaultWebSocketView(mockSession); /** * Commeent #6 <SUF>*/ Object3D mockObj3D = mock(Object3D.class); when(mockObj3D.getUUID()).thenReturn("unique_string"); when(mockObj3D.getType()).thenReturn("type_here"); when(mockObj3D.getX()).thenReturn(0.0); when(mockObj3D.getY()).thenReturn(0.0); when(mockObj3D.getZ()).thenReturn(0.0); when(mockObj3D.getRotationX()).thenReturn(0.0); when(mockObj3D.getRotationY()).thenReturn(0.0); when(mockObj3D.getRotationZ()).thenReturn(0.0); when(mockObj3D.getStatus()).thenReturn("status_here"); /** * Comment #7 * De code hieronder activeert de .update() methode van view. Deze methode maakt van een Object3D (hier mockObj3D) * een JSON pakket en verstuurd deze via een websocket connectie. In de websocket connectie hebben we onze testcode * geïnjecteerd, en dit betekent dat dan de test ook zal worden uitgoerd. */ view.update(Model.UPDATE_COMMAND, mockObj3D); } }
154463_9
// CashDispenser.java // Represents the cash dispenser of the ATM public class CashDispenser { // the default initial number of bills in the cash dispenser private final static int INITIAL_COUNT = 500; private int count; // number of $20 bills remaining // no-argument CashDispenser constructor initializes count to default public CashDispenser() { count = INITIAL_COUNT; // set count attribute to default } // end CashDispenser constructor // simulates dispensing of specified amount of cash public void dispenseCash(int amount) { int billsRequired = amount / 20; // number of $20 bills required count -= billsRequired; // update the count of bills } // end method dispenseCash // indicates whether cash dispenser can dispense desired amount public boolean isSufficientCashAvailable(int amount) { int billsRequired = amount / 20; // number of $20 bills required if (count >= billsRequired ) return true; // enough bills available else return false; // not enough bills available } // end method isSufficientCashAvailable } // end class CashDispenser /************************************************************************** * (C) Copyright 1992-2014 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * *************************************************************************/
DanH957/ATM-Machine
CashDispenser.java
570
// end method dispenseCash
line_comment
nl
// CashDispenser.java // Represents the cash dispenser of the ATM public class CashDispenser { // the default initial number of bills in the cash dispenser private final static int INITIAL_COUNT = 500; private int count; // number of $20 bills remaining // no-argument CashDispenser constructor initializes count to default public CashDispenser() { count = INITIAL_COUNT; // set count attribute to default } // end CashDispenser constructor // simulates dispensing of specified amount of cash public void dispenseCash(int amount) { int billsRequired = amount / 20; // number of $20 bills required count -= billsRequired; // update the count of bills } // end method<SUF> // indicates whether cash dispenser can dispense desired amount public boolean isSufficientCashAvailable(int amount) { int billsRequired = amount / 20; // number of $20 bills required if (count >= billsRequired ) return true; // enough bills available else return false; // not enough bills available } // end method isSufficientCashAvailable } // end class CashDispenser /************************************************************************** * (C) Copyright 1992-2014 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * *************************************************************************/
77268_2
package com.jypec.wavelet.liftingTransforms; import com.jypec.util.arrays.ArrayTransforms; import com.jypec.wavelet.Wavelet; import com.jypec.wavelet.kernelTransforms.cdf97.KernelCdf97WaveletTransform; /** * CDF 9 7 adaptation from: * https://github.com/VadimKirilchuk/jawelet/wiki/CDF-9-7-Discrete-Wavelet-Transform * * @author Daniel * */ public class LiftingCdf97WaveletTransform implements Wavelet { private static final float COEFF_PREDICT_1 = -1.586134342f; private static final float COEFF_PREDICT_2 = 0.8829110762f; private static final float COEFF_UPDATE_1= -0.05298011854f; private static final float COEFF_UPDATE_2 = 0.4435068522f; private static final float COEFF_K = 1.230174105f; private static final float COEFF_K0 = 1.0f/COEFF_K; private static final float COEFF_K1 = COEFF_K/2.0f; /** * Adds to each odd indexed sample its neighbors multiplied by the given coefficient * Wraps around if needed, mirroring the array <br> * E.g: {1, 0, 1} with COEFF = 1 -> {1, 2, 1} <br> * {1, 0, 2, 0} with COEFF = 1 -> {1, 3, 1, 4} * @param s the signal to be treated * @param n the length of s * @param COEFF the prediction coefficient */ private void predict(float[] s, int n, float COEFF) { // Predict inner values for (int i = 1; i < n - 1; i+=2) { s[i] += COEFF * (s[i-1] + s[i+1]); } // Wrap around if (n % 2 == 0 && n > 1) { s[n-1] += 2*COEFF*s[n-2]; } } /** * Adds to each EVEN indexed sample its neighbors multiplied by the given coefficient * Wraps around if needed, mirroring the array * E.g: {1, 1, 1} with COEFF = 1 -> {3, 1, 3} * {1, 1, 2, 1} with COEFF = 1 -> {3, 1, 4, 1} * @param s the signal to be treated * @param n the length of s * @param COEFF the updating coefficient */ private void update(float[]s, int n, float COEFF) { // Update first coeff if (n > 1) { s[0] += 2*COEFF*s[1]; } // Update inner values for (int i = 2; i < n - 1; i+=2) { s[i] += COEFF * (s[i-1] + s[i+1]); } // Wrap around if (n % 2 != 0 && n > 1) { s[n-1] += 2*COEFF*s[n-2]; } } /** * Scales the ODD samples by COEFF, and the EVEN samples by 1/COEFF * @param s the signal to be scaled * @param n the length of s * @param COEFF the coefficient applied */ private void scale(float[] s, int n, float kEven, float kOdd) { for (int i = 0; i < n; i++) { if (i%2 == 1) { s[i] *= kOdd; } else { s[i] *= kEven; } } } @Override public void forwardTransform(float[] s, int n) { //predict and update predict(s, n, LiftingCdf97WaveletTransform.COEFF_PREDICT_1); update(s, n, LiftingCdf97WaveletTransform.COEFF_UPDATE_1); predict(s, n, LiftingCdf97WaveletTransform.COEFF_PREDICT_2); update(s, n, LiftingCdf97WaveletTransform.COEFF_UPDATE_2); //scale values scale(s, n, LiftingCdf97WaveletTransform.COEFF_K0, LiftingCdf97WaveletTransform.COEFF_K1); //pack values (low freq first, high freq last) ArrayTransforms.pack(s, n); } @Override public void reverseTransform(float[] s, int n) { //unpack values ArrayTransforms.unpack(s, n); //unscale values scale(s, n, 1/LiftingCdf97WaveletTransform.COEFF_K0, 1/LiftingCdf97WaveletTransform.COEFF_K1); //unpredict and unupdate update(s, n, -LiftingCdf97WaveletTransform.COEFF_UPDATE_2); predict(s, n, -LiftingCdf97WaveletTransform.COEFF_PREDICT_2); update(s, n, -LiftingCdf97WaveletTransform.COEFF_UPDATE_1); predict(s, n, -LiftingCdf97WaveletTransform.COEFF_PREDICT_1); } @Override public float maxResult(float min, float max) { return new KernelCdf97WaveletTransform().maxResult(min, max); } @Override public float minResult(float min, float max) { return new KernelCdf97WaveletTransform().minResult(min, max); } }
Daniel-BG/Jypec
src/com/jypec/wavelet/liftingTransforms/LiftingCdf97WaveletTransform.java
1,595
// Predict inner values
line_comment
nl
package com.jypec.wavelet.liftingTransforms; import com.jypec.util.arrays.ArrayTransforms; import com.jypec.wavelet.Wavelet; import com.jypec.wavelet.kernelTransforms.cdf97.KernelCdf97WaveletTransform; /** * CDF 9 7 adaptation from: * https://github.com/VadimKirilchuk/jawelet/wiki/CDF-9-7-Discrete-Wavelet-Transform * * @author Daniel * */ public class LiftingCdf97WaveletTransform implements Wavelet { private static final float COEFF_PREDICT_1 = -1.586134342f; private static final float COEFF_PREDICT_2 = 0.8829110762f; private static final float COEFF_UPDATE_1= -0.05298011854f; private static final float COEFF_UPDATE_2 = 0.4435068522f; private static final float COEFF_K = 1.230174105f; private static final float COEFF_K0 = 1.0f/COEFF_K; private static final float COEFF_K1 = COEFF_K/2.0f; /** * Adds to each odd indexed sample its neighbors multiplied by the given coefficient * Wraps around if needed, mirroring the array <br> * E.g: {1, 0, 1} with COEFF = 1 -> {1, 2, 1} <br> * {1, 0, 2, 0} with COEFF = 1 -> {1, 3, 1, 4} * @param s the signal to be treated * @param n the length of s * @param COEFF the prediction coefficient */ private void predict(float[] s, int n, float COEFF) { // Predict inner<SUF> for (int i = 1; i < n - 1; i+=2) { s[i] += COEFF * (s[i-1] + s[i+1]); } // Wrap around if (n % 2 == 0 && n > 1) { s[n-1] += 2*COEFF*s[n-2]; } } /** * Adds to each EVEN indexed sample its neighbors multiplied by the given coefficient * Wraps around if needed, mirroring the array * E.g: {1, 1, 1} with COEFF = 1 -> {3, 1, 3} * {1, 1, 2, 1} with COEFF = 1 -> {3, 1, 4, 1} * @param s the signal to be treated * @param n the length of s * @param COEFF the updating coefficient */ private void update(float[]s, int n, float COEFF) { // Update first coeff if (n > 1) { s[0] += 2*COEFF*s[1]; } // Update inner values for (int i = 2; i < n - 1; i+=2) { s[i] += COEFF * (s[i-1] + s[i+1]); } // Wrap around if (n % 2 != 0 && n > 1) { s[n-1] += 2*COEFF*s[n-2]; } } /** * Scales the ODD samples by COEFF, and the EVEN samples by 1/COEFF * @param s the signal to be scaled * @param n the length of s * @param COEFF the coefficient applied */ private void scale(float[] s, int n, float kEven, float kOdd) { for (int i = 0; i < n; i++) { if (i%2 == 1) { s[i] *= kOdd; } else { s[i] *= kEven; } } } @Override public void forwardTransform(float[] s, int n) { //predict and update predict(s, n, LiftingCdf97WaveletTransform.COEFF_PREDICT_1); update(s, n, LiftingCdf97WaveletTransform.COEFF_UPDATE_1); predict(s, n, LiftingCdf97WaveletTransform.COEFF_PREDICT_2); update(s, n, LiftingCdf97WaveletTransform.COEFF_UPDATE_2); //scale values scale(s, n, LiftingCdf97WaveletTransform.COEFF_K0, LiftingCdf97WaveletTransform.COEFF_K1); //pack values (low freq first, high freq last) ArrayTransforms.pack(s, n); } @Override public void reverseTransform(float[] s, int n) { //unpack values ArrayTransforms.unpack(s, n); //unscale values scale(s, n, 1/LiftingCdf97WaveletTransform.COEFF_K0, 1/LiftingCdf97WaveletTransform.COEFF_K1); //unpredict and unupdate update(s, n, -LiftingCdf97WaveletTransform.COEFF_UPDATE_2); predict(s, n, -LiftingCdf97WaveletTransform.COEFF_PREDICT_2); update(s, n, -LiftingCdf97WaveletTransform.COEFF_UPDATE_1); predict(s, n, -LiftingCdf97WaveletTransform.COEFF_PREDICT_1); } @Override public float maxResult(float min, float max) { return new KernelCdf97WaveletTransform().maxResult(min, max); } @Override public float minResult(float min, float max) { return new KernelCdf97WaveletTransform().minResult(min, max); } }
7822_0
package controllers; import dal.repositories.DatabaseExecutionContext; import dal.repositories.JPARecipeRepository; import dal.repositories.JPAUserRepository; import models.*; import play.db.jpa.JPAApi; import play.db.jpa.Transactional; import play.mvc.*; import views.html.*; import views.html.shared.getResults; import views.html.shared.index; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import java.util.List; public class Application extends Controller { private JPAUserRepository userRepo; private JPARecipeRepository recipeRepo; @Inject public Application(JPAUserRepository userRepo, JPARecipeRepository recipeRepo) { this.userRepo = userRepo; this.recipeRepo = recipeRepo; } @Transactional public Result index() { User user = new User("harry", "[email protected]", "hallo123"); Recipe recipe = new Recipe("Rijst", "De perfecte rijst voor bodybuilders!", false); Ingredient ingredient = new Ingredient("Water", 20, "water.pjg", Measurement.ml); Kitchenware kitchenware = new Kitchenware("Vork"); userRepo.add(user); recipeRepo.add(recipe); // TODO: // De recipe klasse persisten lukt niet, zou je hier naar kunnen kijken, // waarom hij een error geeft? return ok(index.render()); } public Result getResults() { List<User> users = userRepo.list(); List<Recipe> recipes = recipeRepo.list(); return ok(getResults.render(users, recipes)); } /*public List<User> findAll() { return entityManager.createNamedQuery("User.getAll", User.class) .getResultList(); } */ }
Daniel-Lin1/BoodschappenlijstApp
BoodschappenLijst/app/controllers/Application.java
528
// De recipe klasse persisten lukt niet, zou je hier naar kunnen kijken,
line_comment
nl
package controllers; import dal.repositories.DatabaseExecutionContext; import dal.repositories.JPARecipeRepository; import dal.repositories.JPAUserRepository; import models.*; import play.db.jpa.JPAApi; import play.db.jpa.Transactional; import play.mvc.*; import views.html.*; import views.html.shared.getResults; import views.html.shared.index; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import java.util.List; public class Application extends Controller { private JPAUserRepository userRepo; private JPARecipeRepository recipeRepo; @Inject public Application(JPAUserRepository userRepo, JPARecipeRepository recipeRepo) { this.userRepo = userRepo; this.recipeRepo = recipeRepo; } @Transactional public Result index() { User user = new User("harry", "[email protected]", "hallo123"); Recipe recipe = new Recipe("Rijst", "De perfecte rijst voor bodybuilders!", false); Ingredient ingredient = new Ingredient("Water", 20, "water.pjg", Measurement.ml); Kitchenware kitchenware = new Kitchenware("Vork"); userRepo.add(user); recipeRepo.add(recipe); // TODO: // De recipe<SUF> // waarom hij een error geeft? return ok(index.render()); } public Result getResults() { List<User> users = userRepo.list(); List<Recipe> recipes = recipeRepo.list(); return ok(getResults.render(users, recipes)); } /*public List<User> findAll() { return entityManager.createNamedQuery("User.getAll", User.class) .getResultList(); } */ }
38360_2
package game; import building.Building; import building.UnitProducingBuilding; import Enums.BuildingType; import Enums.State; import game.map.Map; import game.map.TiledMapStage; import game.UserInterface.UIManager; import multiplayer.GameManagerClient; import Player.Player; import Units.BuilderUnit; import Units.OffensiveUnit; import Units.Unit; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.maps.tiled.TiledMap; import com.badlogic.gdx.maps.tiled.TiledMapRenderer; import com.badlogic.gdx.maps.tiled.TmxMapLoader; import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer; import com.badlogic.gdx.scenes.scene2d.Stage; import com.mygdx.game.OrthographicCameraControlClass; import java.awt.*; import java.util.*; import java.util.List; /** * Created by Daniel on 26-3-2017. */ public class GameManager { private State gamestate; private int lobbyID; private String password; private Map map; private ArrayList<Player> players; private TiledMap tiledMap; private TiledMapRenderer tiledMapRenderer; private Stage stage; private OrthographicCamera orthographicCamera; private GameManagerClient gmc; private int ownPlayerid; private UIManager uiManager; private OrthographicCameraControlClass gamecamera; //Stage en Skin voor UI inladen private SpriteBatch batch; public GameManager(State gameState, int lobbyID, String password, java.util.List<Player> players, int ownPlayerId) { this.gamestate = gameState; this.lobbyID = lobbyID; this.password = password; this.players = (ArrayList<Player>) players; this.ownPlayerid = ownPlayerId; this.gmc = new GameManagerClient(this); } public State getGamestate() { return this.gamestate; } public void setGamestate(State gamestate) { this.gamestate = gamestate; } public int getLobbyID() { return this.lobbyID; } public void setLobbyID(int lobbyID) { this.lobbyID = lobbyID; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } public Map getMap() { return this.map; } public void setMap(Map map) { this.map = map; } public List<Player> getPlayers() { return players; } public UIManager getUiManager() { return uiManager; } public void setUiManager(UIManager uiManager) { this.uiManager = uiManager; } public GameManagerClient getGmc() {return gmc;} public void create() { // set camera orthographicCamera = new OrthographicCamera(); orthographicCamera.setToOrtho(false, 1920, 1080); orthographicCamera.update(); tiledMap = new TmxMapLoader().load("assets/TestMap3.tmx"); map = new Map(tiledMap, "tmpNaam"); gamecamera = new OrthographicCameraControlClass(800, tiledMap); //sets map tiledMapRenderer = new OrthogonalTiledMapRenderer(tiledMap); stage = new TiledMapStage(tiledMap, this); Gdx.input.setInputProcessor(stage); batch = new SpriteBatch(); //todo review of dit de correcte plek ervoor is. createTownCenters(); } public void render() { //todo zet dit ergens anders. hoort op de tickrate te werken. //Yeah this shit needs fixing ArrayList<Unit> toRemoveUnits = new ArrayList<>(); for (Player player : players) { List<Unit> units = player.getUnits(); for (Unit unit : units) { if (unit.getDeltaMoveTime() > unit.getSpeed()) { unit.move(map); unit.setDeltaMoveTime(0); } if(unit instanceof BuilderUnit){ //todo blame marc hiervoor BuilderUnit bUnit = (BuilderUnit) unit; if(bUnit.getPath().size() == 0){ if (bUnit.mineResource(bUnit.getResourceTile().getResource())){ //er word gemined }else{ //er word niet gemined } } } //TODO Fix this mess if(unit instanceof OffensiveUnit) { OffensiveUnit offunit = (OffensiveUnit) unit; if (offunit.getInBattleWith() != null && offunit.getDeltaBattleTime() > 1) { offunit.setDeltaBattleTime(0); for (int x = 0; x < offunit.getHitPerSecond(); x++) { offunit.attack(unit.getInBattleWith()); if (offunit.getHealth() <= 0) { toRemoveUnits.add(offunit); } if (offunit.getInBattleWith().getHealth() <= 0) { toRemoveUnits.add(offunit.getInBattleWith()); } } } offunit.setDeltaBattleTime(offunit.getDeltaBattleTime() + Gdx.graphics.getDeltaTime()); } unit.setDeltaMoveTime(unit.getDeltaMoveTime() + Gdx.graphics.getDeltaTime()); map.setHostiles(unit); } } for (Player player : players) { ArrayList<Unit> selectedUnits = (ArrayList<Unit>) player.getSelectedUnits(); for (Unit unit : toRemoveUnits) { player.removeUnit(unit); selectedUnits.remove(unit); } player.setSelectedUnits(selectedUnits); } renderCameraAndTiledMap(); batch.begin(); map.render(batch); for (Player player : players) { player.render(batch); } batch.end(); } public Player getOwnPlayer() { return getPlayers().get(ownPlayerid); } private void renderCameraAndTiledMap() { orthographicCamera = gamecamera.render(orthographicCamera); orthographicCamera.update(); tiledMapRenderer.render(); stage.act(); stage.draw(); stage.getViewport().update((int) orthographicCamera.viewportWidth, (int) orthographicCamera.viewportHeight, false); stage.getViewport().setCamera(orthographicCamera); stage.getViewport().getCamera().update(); batch.setProjectionMatrix(orthographicCamera.combined); tiledMapRenderer.setView( orthographicCamera.combined , 0 , 0 , tiledMap.getLayers().get(0).getProperties().get("width", Integer.class)//This works realy, really weird. , tiledMap.getLayers().get(0).getProperties().get("height", Integer.class)//This too ); } private void createTownCenters(){ for(int i=0; i<getPlayers().size(); i++){ Point spawnPoint = map.getSpawnPoints().get(i); Point cord = map.getTileFromCord(spawnPoint).getCoordinate(); Building townCenter = new UnitProducingBuilding(cord, 4, 4, BuildingType.TownCenter, 1000); if(map.checkBuildingPossible(townCenter)){ map.setBuildingsTiles(townCenter); getPlayers().get(i).getBuildings().add(townCenter); } } } public int getHighestUnitId(){ int highestUnitID = 0; for(Player player: getPlayers()) { highestUnitID = highestUnitID + player.getUnits().size(); } return highestUnitID; } public int getHighestBuildingId(){ int highestBuildingID = 0; for(Player player: getPlayers()) { highestBuildingID = highestBuildingID + player.getBuildings().size(); } return highestBuildingID; } }
Daniel-Lin1/Proftaak-Semester-3
DACTest/core/src/Game/GameManager.java
2,335
//todo review of dit de correcte plek ervoor is.
line_comment
nl
package game; import building.Building; import building.UnitProducingBuilding; import Enums.BuildingType; import Enums.State; import game.map.Map; import game.map.TiledMapStage; import game.UserInterface.UIManager; import multiplayer.GameManagerClient; import Player.Player; import Units.BuilderUnit; import Units.OffensiveUnit; import Units.Unit; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.maps.tiled.TiledMap; import com.badlogic.gdx.maps.tiled.TiledMapRenderer; import com.badlogic.gdx.maps.tiled.TmxMapLoader; import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer; import com.badlogic.gdx.scenes.scene2d.Stage; import com.mygdx.game.OrthographicCameraControlClass; import java.awt.*; import java.util.*; import java.util.List; /** * Created by Daniel on 26-3-2017. */ public class GameManager { private State gamestate; private int lobbyID; private String password; private Map map; private ArrayList<Player> players; private TiledMap tiledMap; private TiledMapRenderer tiledMapRenderer; private Stage stage; private OrthographicCamera orthographicCamera; private GameManagerClient gmc; private int ownPlayerid; private UIManager uiManager; private OrthographicCameraControlClass gamecamera; //Stage en Skin voor UI inladen private SpriteBatch batch; public GameManager(State gameState, int lobbyID, String password, java.util.List<Player> players, int ownPlayerId) { this.gamestate = gameState; this.lobbyID = lobbyID; this.password = password; this.players = (ArrayList<Player>) players; this.ownPlayerid = ownPlayerId; this.gmc = new GameManagerClient(this); } public State getGamestate() { return this.gamestate; } public void setGamestate(State gamestate) { this.gamestate = gamestate; } public int getLobbyID() { return this.lobbyID; } public void setLobbyID(int lobbyID) { this.lobbyID = lobbyID; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } public Map getMap() { return this.map; } public void setMap(Map map) { this.map = map; } public List<Player> getPlayers() { return players; } public UIManager getUiManager() { return uiManager; } public void setUiManager(UIManager uiManager) { this.uiManager = uiManager; } public GameManagerClient getGmc() {return gmc;} public void create() { // set camera orthographicCamera = new OrthographicCamera(); orthographicCamera.setToOrtho(false, 1920, 1080); orthographicCamera.update(); tiledMap = new TmxMapLoader().load("assets/TestMap3.tmx"); map = new Map(tiledMap, "tmpNaam"); gamecamera = new OrthographicCameraControlClass(800, tiledMap); //sets map tiledMapRenderer = new OrthogonalTiledMapRenderer(tiledMap); stage = new TiledMapStage(tiledMap, this); Gdx.input.setInputProcessor(stage); batch = new SpriteBatch(); //todo review<SUF> createTownCenters(); } public void render() { //todo zet dit ergens anders. hoort op de tickrate te werken. //Yeah this shit needs fixing ArrayList<Unit> toRemoveUnits = new ArrayList<>(); for (Player player : players) { List<Unit> units = player.getUnits(); for (Unit unit : units) { if (unit.getDeltaMoveTime() > unit.getSpeed()) { unit.move(map); unit.setDeltaMoveTime(0); } if(unit instanceof BuilderUnit){ //todo blame marc hiervoor BuilderUnit bUnit = (BuilderUnit) unit; if(bUnit.getPath().size() == 0){ if (bUnit.mineResource(bUnit.getResourceTile().getResource())){ //er word gemined }else{ //er word niet gemined } } } //TODO Fix this mess if(unit instanceof OffensiveUnit) { OffensiveUnit offunit = (OffensiveUnit) unit; if (offunit.getInBattleWith() != null && offunit.getDeltaBattleTime() > 1) { offunit.setDeltaBattleTime(0); for (int x = 0; x < offunit.getHitPerSecond(); x++) { offunit.attack(unit.getInBattleWith()); if (offunit.getHealth() <= 0) { toRemoveUnits.add(offunit); } if (offunit.getInBattleWith().getHealth() <= 0) { toRemoveUnits.add(offunit.getInBattleWith()); } } } offunit.setDeltaBattleTime(offunit.getDeltaBattleTime() + Gdx.graphics.getDeltaTime()); } unit.setDeltaMoveTime(unit.getDeltaMoveTime() + Gdx.graphics.getDeltaTime()); map.setHostiles(unit); } } for (Player player : players) { ArrayList<Unit> selectedUnits = (ArrayList<Unit>) player.getSelectedUnits(); for (Unit unit : toRemoveUnits) { player.removeUnit(unit); selectedUnits.remove(unit); } player.setSelectedUnits(selectedUnits); } renderCameraAndTiledMap(); batch.begin(); map.render(batch); for (Player player : players) { player.render(batch); } batch.end(); } public Player getOwnPlayer() { return getPlayers().get(ownPlayerid); } private void renderCameraAndTiledMap() { orthographicCamera = gamecamera.render(orthographicCamera); orthographicCamera.update(); tiledMapRenderer.render(); stage.act(); stage.draw(); stage.getViewport().update((int) orthographicCamera.viewportWidth, (int) orthographicCamera.viewportHeight, false); stage.getViewport().setCamera(orthographicCamera); stage.getViewport().getCamera().update(); batch.setProjectionMatrix(orthographicCamera.combined); tiledMapRenderer.setView( orthographicCamera.combined , 0 , 0 , tiledMap.getLayers().get(0).getProperties().get("width", Integer.class)//This works realy, really weird. , tiledMap.getLayers().get(0).getProperties().get("height", Integer.class)//This too ); } private void createTownCenters(){ for(int i=0; i<getPlayers().size(); i++){ Point spawnPoint = map.getSpawnPoints().get(i); Point cord = map.getTileFromCord(spawnPoint).getCoordinate(); Building townCenter = new UnitProducingBuilding(cord, 4, 4, BuildingType.TownCenter, 1000); if(map.checkBuildingPossible(townCenter)){ map.setBuildingsTiles(townCenter); getPlayers().get(i).getBuildings().add(townCenter); } } } public int getHighestUnitId(){ int highestUnitID = 0; for(Player player: getPlayers()) { highestUnitID = highestUnitID + player.getUnits().size(); } return highestUnitID; } public int getHighestBuildingId(){ int highestBuildingID = 0; for(Player player: getPlayers()) { highestBuildingID = highestBuildingID + player.getBuildings().size(); } return highestBuildingID; } }
144557_0
package com.ipsen.spine; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; @SpringBootApplication // TODO tijdelijk de beveiliging uitgezet @EnableMethodSecurity(securedEnabled = true) public class IpsenSpineApplication { public static void main(String[] args) { SpringApplication.run(IpsenSpineApplication.class, args); } }
DanielB-02/IPSEN3_BACKEND
src/main/java/com/ipsen/spine/IpsenSpineApplication.java
138
// TODO tijdelijk de beveiliging uitgezet
line_comment
nl
package com.ipsen.spine; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; @SpringBootApplication // TODO tijdelijk<SUF> @EnableMethodSecurity(securedEnabled = true) public class IpsenSpineApplication { public static void main(String[] args) { SpringApplication.run(IpsenSpineApplication.class, args); } }
117372_3
/* * Copyright (c) 2009-2011, EzWare * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer.Redistributions * in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution.Neither the name of the * EzWare nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ package org.oxbow.swingbits.table; import java.awt.Component; import javax.swing.JComponent; import javax.swing.JTable; import javax.swing.table.TableCellRenderer; /** * Common class for customizing table header renderer without loosing its L&F * * Created on Aug 10, 2010 * @author Eugene Ryzhikov * */ public class TableHeaderRenderer extends JComponent implements TableCellRenderer { private static final long serialVersionUID = 1L; @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { // returns component used for default header rendering // makes it independent on current L&F return table.getTableHeader().getDefaultRenderer(). getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); } // following methods are overriden for performance reasons @Override public void validate() {} @Override public void revalidate() {} @Override public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {} @Override public void firePropertyChange(String propertyName, Object oldValue, Object newValue) {} }
DanielFransiscus/laundry-desktop-app
lib/swingbits/table/TableHeaderRenderer.java
771
// makes it independent on current L&F
line_comment
nl
/* * Copyright (c) 2009-2011, EzWare * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer.Redistributions * in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution.Neither the name of the * EzWare nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ package org.oxbow.swingbits.table; import java.awt.Component; import javax.swing.JComponent; import javax.swing.JTable; import javax.swing.table.TableCellRenderer; /** * Common class for customizing table header renderer without loosing its L&F * * Created on Aug 10, 2010 * @author Eugene Ryzhikov * */ public class TableHeaderRenderer extends JComponent implements TableCellRenderer { private static final long serialVersionUID = 1L; @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { // returns component used for default header rendering // makes it<SUF> return table.getTableHeader().getDefaultRenderer(). getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); } // following methods are overriden for performance reasons @Override public void validate() {} @Override public void revalidate() {} @Override public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {} @Override public void firePropertyChange(String propertyName, Object oldValue, Object newValue) {} }
54823_13
package hsleiden.stenentijdperk.stenentijdperk.Controllers; import hsleiden.stenentijdperk.stenentijdperk.Helpers.Beschavingskaarten.Kaart; import hsleiden.stenentijdperk.stenentijdperk.Helpers.Dobbelsteen; import hsleiden.stenentijdperk.stenentijdperk.Helpers.StaticHut; import hsleiden.stenentijdperk.stenentijdperk.Helpers.Tool; import hsleiden.stenentijdperk.stenentijdperk.Managers.ViewManager; import hsleiden.stenentijdperk.stenentijdperk.Models.BoardModel; import hsleiden.stenentijdperk.stenentijdperk.Models.PlayerModel; import hsleiden.stenentijdperk.stenentijdperk.Views.ResourceView; import hsleiden.stenentijdperk.stenentijdperk.Views.TableauView; import hsleiden.stenentijdperk.stenentijdperk.observers.BoardObserver; import java.util.ArrayList; import java.util.List; public class BoardController { private PlayerController playercontroller; private BoardModel boardmodel; // TODO naar boardmodel en dan firebase private ArrayList<PlayerModel> players = new ArrayList<PlayerModel>(); private int[] gegooideWorp; public BoardController() { // TODO all references naar temp players moet naar firebase vragen. PlayerModel matt = new PlayerModel("Matt"); PlayerModel jake = new PlayerModel("Jake"); PlayerModel lucas = new PlayerModel("Lucas"); PlayerModel carlos = new PlayerModel("Carlos"); players.add(matt); players.add(jake); players.add(lucas); players.add(carlos); playercontroller = new PlayerController(); boardmodel = new BoardModel(); boardmodel.setPlayer(players.get(0)); // Begin van het spel turn eerste speler bepalen. gegooideWorp = new int[3]; } public void registerObserver(BoardObserver boardobserver) { this.boardmodel.register(boardobserver); } public Kaart getKaart(int index) { return this.boardmodel.getKaart(index); } public List<Kaart> getKaarten() { return this.boardmodel.getKaarten(); } public StaticHut getHut(int stapel) { return this.boardmodel.getHut(stapel); } public List<StaticHut> getHutStapel(int stapel) { return this.boardmodel.getHutStapel(stapel); } public void onResourceButtonClick(int index, int input) { if (!boardmodel.getPlaced() && boardmodel.requestCap(index) - boardmodel.requestVillagers(index) != 0 && playercontroller.getPositie(boardmodel.getPlayer(), index) == 0) { // Dit veranderd de hoeveelheid stamleden van een speler boardmodel.decreaseVillagers(index, input); plaatsenStamleden(index, input); } } public boolean stamledenCheck(int index, int input) { return (input > 0 && input <= playercontroller.getVillagers(boardmodel.getPlayer()) && input <= (boardmodel.requestCap(index) - boardmodel.requestVillagers(index))); } public void onButtonClick(int index) { if (vraagPhase() == 1) { buttonCheckPhase1(index); } else { buttonCheckPhase2(index); } } // Hier is het rollen voor resources. public void resolveResource(int index) { gegooideWorp[0] = index; int stamleden = playercontroller.getPositie(boardmodel.getPlayer(), index); if (stamleden != 0) { Dobbelsteen roll = new Dobbelsteen(stamleden); roll.worp(); roll.berekenTotaal(); gegooideWorp[1] = roll.getTotaal(); gegooideWorp[2] = stamleden; if (playercontroller.getTools(boardmodel.getPlayer()).size() != 0 && checkTools()) { ViewManager.loadPopupWindow(new TableauView(boardmodel.getPlayer(), this, gegooideWorp[1]).setScene()); } else { toolsGebruiken(0); } } } public void toolsGebruiken(int waarde) { int index = gegooideWorp[0]; int roltotaal = gegooideWorp[1] + waarde; int stamleden = gegooideWorp[2]; int resources = roltotaal / boardmodel.getResource(index).getWaarde(); if (resources > boardmodel.getResource(index).getHoeveelheid()) { resources = boardmodel.getResource(index).getHoeveelheid(); } boardmodel.reduceResources(index, resources); playercontroller.setPositie(boardmodel.getPlayer(), index, 0); boardmodel.getPlayer().addResources(index, resources); boardmodel.getLocaties().get(index).reduceVillager(stamleden); } private boolean checkTools() { boolean toolsLeft = false; for (Tool tool : playercontroller.getTools(boardmodel.getPlayer())) { if (tool.getStatus()) { toolsLeft = true; } } return toolsLeft; } private void gainTools(int index) { if ((playercontroller.getPositie(boardmodel.getPlayer(), index) != 0)) { ArrayList<Tool> tools = playercontroller.getTools(boardmodel.getPlayer()); if (tools.size() < 3) { playercontroller.addTool(boardmodel.getPlayer()); playercontroller.setPositie(boardmodel.getPlayer(), index, 0); } else if (tools.get(2).getLevel() != 4) { for (int i = 0; i < 3; i++) { if (tools.get(i).getLevel() == tools.get(2).getLevel()) { tools.get(i).increaseLevel(); playercontroller.setPositie(boardmodel.getPlayer(), index, 0); break; } } } } } public void endTurn() { if (boardmodel.getPlaced()) { // checkt of de speler stamleden heeft geplaast. boolean villagersLeft = true; int i = checkPlayer(); switch (i) { // Verschillede loops bepaalt door welke speler aan de beurt was case 0: // Spelers 1, 2 en 3 case 1: case 2: villagersLeft = loopPlayers(i, players); boardmodel.setPlaced(false); if (!villagersLeft) { // Als de vorige loop niks gevonden heeft dan komt deze pas villagersLeft = loopPlayers(-1, players.subList(0, i + 1)); } break; case 3: villagersLeft = loopPlayers(i - 4, players); boardmodel.setPlaced(false); break; } if (!villagersLeft) { boardmodel.setPhase(2); int turnCheck = (boardmodel.getTurn() - 1) % 4; boardmodel.setPlayer(players.get(turnCheck)); // TODO Dit moet een soort pop up worden. System.out.println("Nu komen de acties"); } } } public boolean EndTurnPhase2() { boolean eindeSpel = false; List<Integer> posities = playercontroller.vraagPosities(boardmodel.getPlayer()); if (posities.stream().allMatch(n -> n == 0)) { int i = checkPlayer(); if (i == 3) { boardmodel.setPlayer(players.get(0)); } else { i++; boardmodel.setPlayer(players.get(i)); } posities = playercontroller.vraagPosities(boardmodel.getPlayer()); } if (posities.stream().allMatch(n -> n == 0)) { System.out.println("Einde Ronde"); boardmodel.setPhase(1); for (PlayerModel player : players) { List<Integer> resources = playercontroller.vraagResources(player); int remaining = voedselBetalen(player); for (int j = 1; j < resources.size(); j++) { if (remaining != 0 && !(resources.stream().allMatch(n -> n == 0))) { for (int k = resources.get(j); k > 0; k--) { if (remaining != 0) { remaining -= 1; playercontroller.reduceResource(player, j, 1); boardmodel.addResources(j, 1); } else { break; } } } else if (resources.stream().allMatch(n -> n == 0)) { player.setPunten(player.getPunten() - 10); break; } else { break; } } playercontroller.setVillagers(player, playercontroller.getMaxVillagers(player)); for (Tool tool : playercontroller.getTools(player)) { tool.setStatus(true); } } boardmodel.notifyAllObservers(); if (checkWincondition()) { eindeSpel = true; endGame(); } } return eindeSpel; } public int vraagPhase() { return boardmodel.getPhase(); } private void moreAgriculture(int index) { if (playercontroller.getPositie(boardmodel.getPlayer(), index) != 0 && playercontroller.vraagGraan(boardmodel.getPlayer()) != 10) { playercontroller.addGraan(boardmodel.getPlayer()); playercontroller.setPositie(boardmodel.getPlayer(), index, 0); } } private void moreVillagerHut(int index) { if (playercontroller.getPositie(boardmodel.getPlayer(), index) != 0 && playercontroller.getMaxVillagers(boardmodel.getPlayer()) != 10) { playercontroller.addMaxVillagers(boardmodel.getPlayer()); playercontroller.setPositie(boardmodel.getPlayer(), index, 0); } } private void buttonCheckPhase1(int index) { if (locatieVrij(index) && !boardmodel.getPlaced()) { if (index == 6 && playercontroller.getVillagers(boardmodel.getPlayer()) >= 2) { plaatsenStamleden(index, 2); } else if (index != 6) { plaatsenStamleden(index, 1); } } } private void buttonCheckPhase2(int index) { switch (index) { case 5: moreAgriculture(index); break; case 6: moreVillagerHut(index); break; case 7: gainTools(index); break; case 8: case 9: case 10: case 11: hutActie(index - 8); break; case 12: case 13: case 14: case 15: beschavingsKaarActie(index - 12); break; } } private void beschavingsKaarActie(int index) { if ((playercontroller.getPositie(boardmodel.getPlayer(), (index + 12)) != 0)) { ViewManager.loadPopupWindow(new ResourceView(boardmodel.getPlayer(), this.playercontroller, this, (index + 1), 0, index, "beschavingskaart")); } } public void kaartGekocht(int index, List<Integer> resources, String type) { if (type.equals("beschavingskaart")) { if (resourcesBetalen(resources)) { this.boardmodel.getPlayer().addKaarten(this.boardmodel.getKaart(index)); this.boardmodel.getKaart(index).uitvoerenActie(this.boardmodel.getPlayer()); this.boardmodel.updatePunten(); this.boardmodel.removeKaart(index); } else { System.out.println("niet genoeg resources"); // TODO deze else verbeteren } this.playercontroller.setPositie(this.boardmodel.getPlayer(), (index + 12), 0); } else { if (resourcesBetalen(resources)) { int punten = (resources.get(0) * 3) + (resources.get(1) * 4) + (resources.get(2) * 5) + (resources.get(3) * 6); this.boardmodel.getPlayer().increasePunten(punten); this.boardmodel.getPlayer().addHutjes(this.boardmodel.getHut(index)); this.boardmodel.updatePunten(); this.boardmodel.removeHut(index); } else { System.out.println("niet genoeg resources"); // TODO deze else verbeteren } this.playercontroller.setPositie(this.boardmodel.getPlayer(), (index + 8), 0); } } public void kaartAnnuleer(int index, String type) { if (type.equals("beschavingskaart")) { this.playercontroller.setPositie(this.boardmodel.getPlayer(), (index + 12), 0); } else { this.playercontroller.setPositie(this.boardmodel.getPlayer(), (index + 8), 0); } } private void hutActie(int index) { if ((this.playercontroller.getPositie(this.boardmodel.getPlayer(), (index + 8)) != 0)) { if (this.boardmodel.getHut(index).getPunten() == 0) { ViewManager.loadPopupWindow(new ResourceView(this.boardmodel.getPlayer(), this.playercontroller, this, this.boardmodel.getHut(index).getKosten().get(0), this.boardmodel.getHut(index).getKosten().get(1), index, "hutkaart")); } else { if (resourcesBetalen(this.boardmodel.getHut(index).getKosten())) { this.boardmodel.getPlayer().increasePunten(this.boardmodel.getHut(index).getPunten()); this.boardmodel.getPlayer().addHutjes(this.boardmodel.getHut(index)); this.boardmodel.updatePunten(); this.boardmodel.removeHut(index); } else { System.out.println("niet genoeg resources"); // TODO deze else verbeteren } playercontroller.setPositie(this.boardmodel.getPlayer(), (index + 8), 0); } } } private int voedselBetalen(PlayerModel player) { int remaining = 0; int voedselNodig = playercontroller.getMaxVillagers(player) - playercontroller.vraagGraan(player); int voedselSpeler = playercontroller.vraagResources(player).get(0); if (voedselSpeler >= voedselNodig) { playercontroller.reduceResource(player, 0, voedselNodig); boardmodel.addResources(0, voedselNodig); } else { playercontroller.reduceResource(player, 0, voedselSpeler); remaining = voedselNodig - voedselSpeler; boardmodel.addResources(0, voedselSpeler); } return remaining; } // Methode om door lijsten spelers te loopen. private boolean loopPlayers(int start, List<PlayerModel> player) { boolean found = false; for (int j = start + 1; j < player.size(); j++) { if (playercontroller.getVillagers(player.get(j)) != 0) { boardmodel.setPlayer(player.get(j)); // Veranderd de huidige speler found = true; break; } } return found; } private int checkPlayer() { int i = 0; for (int j = 0; j < 4; j++) { if (boardmodel.getPlayer().equals(players.get(j))) { // Bepaling welke player aan de beurt is i = j; break; } } return i; } private boolean checkResourceKost(int resource, List<Integer> kost) { return boardmodel.getPlayer().getResource(resource + 1) >= kost.get(resource); } private boolean locatieVrij(int index) { boolean status = true; for (PlayerModel player : players) { if (player.getPositie(index) != 0) { status = false; } } return status; } private void plaatsenStamleden(int index, int stamleden) { boardmodel.setPlaced(true); playercontroller.setVillagers(boardmodel.getPlayer(), (playercontroller.getVillagers(boardmodel.getPlayer()) - stamleden)); playercontroller.setPositie(boardmodel.getPlayer(), index, stamleden); } private boolean resourcesBetalen(List<Integer> kost) { if (checkResourceKost(0, kost) && checkResourceKost(1, kost) && checkResourceKost(2, kost) && checkResourceKost(3, kost)) { int i = 1; for (Integer amount : kost) { playercontroller.reduceResource(boardmodel.getPlayer(), i, amount); boardmodel.changeHoeveelheid(i, amount); i++; } return true; } else { return false; } } private void endGame() { for (PlayerModel player : players) { finalPuntenCount(player); } } private boolean checkWincondition() { boolean endGame = false; for (int i = 0; i < 4; i++) { if (boardmodel.getHutStapel(i).size() == 0) { endGame = true; } } if (boardmodel.getKaarten().size() < 4) { endGame = true; } return endGame; } private void finalPuntenCount(PlayerModel player) { List<Integer> multipliers = playercontroller.getMultiplier(player); for (Tool tool : playercontroller.getTools(player)) { this.playercontroller.increasePunten(player, multipliers.get(0) * tool.getLevel()); } this.playercontroller.increasePunten(player, multipliers.get(1) * this.playercontroller.getHutjes(player).size()); this.playercontroller.increasePunten(player, multipliers.get(2) * this.playercontroller.getMaxVillagers(player)); this.playercontroller.increasePunten(player, multipliers.get(3) * this.playercontroller.vraagGraan(player)); this.playercontroller.increasePunten(player, this.playercontroller.getTreasures(player).size() * this.playercontroller.getTreasures(player).size()); this.boardmodel.updatePunten(); } // TODO tijdelijk public ArrayList<PlayerModel> getPlayers() { return this.players; } public PlayerModel getPlayer() { return boardmodel.getPlayer(); } }
DankGaming/stenentijdperk
src/main/java/hsleiden/stenentijdperk/stenentijdperk/Controllers/BoardController.java
5,476
// Methode om door lijsten spelers te loopen.
line_comment
nl
package hsleiden.stenentijdperk.stenentijdperk.Controllers; import hsleiden.stenentijdperk.stenentijdperk.Helpers.Beschavingskaarten.Kaart; import hsleiden.stenentijdperk.stenentijdperk.Helpers.Dobbelsteen; import hsleiden.stenentijdperk.stenentijdperk.Helpers.StaticHut; import hsleiden.stenentijdperk.stenentijdperk.Helpers.Tool; import hsleiden.stenentijdperk.stenentijdperk.Managers.ViewManager; import hsleiden.stenentijdperk.stenentijdperk.Models.BoardModel; import hsleiden.stenentijdperk.stenentijdperk.Models.PlayerModel; import hsleiden.stenentijdperk.stenentijdperk.Views.ResourceView; import hsleiden.stenentijdperk.stenentijdperk.Views.TableauView; import hsleiden.stenentijdperk.stenentijdperk.observers.BoardObserver; import java.util.ArrayList; import java.util.List; public class BoardController { private PlayerController playercontroller; private BoardModel boardmodel; // TODO naar boardmodel en dan firebase private ArrayList<PlayerModel> players = new ArrayList<PlayerModel>(); private int[] gegooideWorp; public BoardController() { // TODO all references naar temp players moet naar firebase vragen. PlayerModel matt = new PlayerModel("Matt"); PlayerModel jake = new PlayerModel("Jake"); PlayerModel lucas = new PlayerModel("Lucas"); PlayerModel carlos = new PlayerModel("Carlos"); players.add(matt); players.add(jake); players.add(lucas); players.add(carlos); playercontroller = new PlayerController(); boardmodel = new BoardModel(); boardmodel.setPlayer(players.get(0)); // Begin van het spel turn eerste speler bepalen. gegooideWorp = new int[3]; } public void registerObserver(BoardObserver boardobserver) { this.boardmodel.register(boardobserver); } public Kaart getKaart(int index) { return this.boardmodel.getKaart(index); } public List<Kaart> getKaarten() { return this.boardmodel.getKaarten(); } public StaticHut getHut(int stapel) { return this.boardmodel.getHut(stapel); } public List<StaticHut> getHutStapel(int stapel) { return this.boardmodel.getHutStapel(stapel); } public void onResourceButtonClick(int index, int input) { if (!boardmodel.getPlaced() && boardmodel.requestCap(index) - boardmodel.requestVillagers(index) != 0 && playercontroller.getPositie(boardmodel.getPlayer(), index) == 0) { // Dit veranderd de hoeveelheid stamleden van een speler boardmodel.decreaseVillagers(index, input); plaatsenStamleden(index, input); } } public boolean stamledenCheck(int index, int input) { return (input > 0 && input <= playercontroller.getVillagers(boardmodel.getPlayer()) && input <= (boardmodel.requestCap(index) - boardmodel.requestVillagers(index))); } public void onButtonClick(int index) { if (vraagPhase() == 1) { buttonCheckPhase1(index); } else { buttonCheckPhase2(index); } } // Hier is het rollen voor resources. public void resolveResource(int index) { gegooideWorp[0] = index; int stamleden = playercontroller.getPositie(boardmodel.getPlayer(), index); if (stamleden != 0) { Dobbelsteen roll = new Dobbelsteen(stamleden); roll.worp(); roll.berekenTotaal(); gegooideWorp[1] = roll.getTotaal(); gegooideWorp[2] = stamleden; if (playercontroller.getTools(boardmodel.getPlayer()).size() != 0 && checkTools()) { ViewManager.loadPopupWindow(new TableauView(boardmodel.getPlayer(), this, gegooideWorp[1]).setScene()); } else { toolsGebruiken(0); } } } public void toolsGebruiken(int waarde) { int index = gegooideWorp[0]; int roltotaal = gegooideWorp[1] + waarde; int stamleden = gegooideWorp[2]; int resources = roltotaal / boardmodel.getResource(index).getWaarde(); if (resources > boardmodel.getResource(index).getHoeveelheid()) { resources = boardmodel.getResource(index).getHoeveelheid(); } boardmodel.reduceResources(index, resources); playercontroller.setPositie(boardmodel.getPlayer(), index, 0); boardmodel.getPlayer().addResources(index, resources); boardmodel.getLocaties().get(index).reduceVillager(stamleden); } private boolean checkTools() { boolean toolsLeft = false; for (Tool tool : playercontroller.getTools(boardmodel.getPlayer())) { if (tool.getStatus()) { toolsLeft = true; } } return toolsLeft; } private void gainTools(int index) { if ((playercontroller.getPositie(boardmodel.getPlayer(), index) != 0)) { ArrayList<Tool> tools = playercontroller.getTools(boardmodel.getPlayer()); if (tools.size() < 3) { playercontroller.addTool(boardmodel.getPlayer()); playercontroller.setPositie(boardmodel.getPlayer(), index, 0); } else if (tools.get(2).getLevel() != 4) { for (int i = 0; i < 3; i++) { if (tools.get(i).getLevel() == tools.get(2).getLevel()) { tools.get(i).increaseLevel(); playercontroller.setPositie(boardmodel.getPlayer(), index, 0); break; } } } } } public void endTurn() { if (boardmodel.getPlaced()) { // checkt of de speler stamleden heeft geplaast. boolean villagersLeft = true; int i = checkPlayer(); switch (i) { // Verschillede loops bepaalt door welke speler aan de beurt was case 0: // Spelers 1, 2 en 3 case 1: case 2: villagersLeft = loopPlayers(i, players); boardmodel.setPlaced(false); if (!villagersLeft) { // Als de vorige loop niks gevonden heeft dan komt deze pas villagersLeft = loopPlayers(-1, players.subList(0, i + 1)); } break; case 3: villagersLeft = loopPlayers(i - 4, players); boardmodel.setPlaced(false); break; } if (!villagersLeft) { boardmodel.setPhase(2); int turnCheck = (boardmodel.getTurn() - 1) % 4; boardmodel.setPlayer(players.get(turnCheck)); // TODO Dit moet een soort pop up worden. System.out.println("Nu komen de acties"); } } } public boolean EndTurnPhase2() { boolean eindeSpel = false; List<Integer> posities = playercontroller.vraagPosities(boardmodel.getPlayer()); if (posities.stream().allMatch(n -> n == 0)) { int i = checkPlayer(); if (i == 3) { boardmodel.setPlayer(players.get(0)); } else { i++; boardmodel.setPlayer(players.get(i)); } posities = playercontroller.vraagPosities(boardmodel.getPlayer()); } if (posities.stream().allMatch(n -> n == 0)) { System.out.println("Einde Ronde"); boardmodel.setPhase(1); for (PlayerModel player : players) { List<Integer> resources = playercontroller.vraagResources(player); int remaining = voedselBetalen(player); for (int j = 1; j < resources.size(); j++) { if (remaining != 0 && !(resources.stream().allMatch(n -> n == 0))) { for (int k = resources.get(j); k > 0; k--) { if (remaining != 0) { remaining -= 1; playercontroller.reduceResource(player, j, 1); boardmodel.addResources(j, 1); } else { break; } } } else if (resources.stream().allMatch(n -> n == 0)) { player.setPunten(player.getPunten() - 10); break; } else { break; } } playercontroller.setVillagers(player, playercontroller.getMaxVillagers(player)); for (Tool tool : playercontroller.getTools(player)) { tool.setStatus(true); } } boardmodel.notifyAllObservers(); if (checkWincondition()) { eindeSpel = true; endGame(); } } return eindeSpel; } public int vraagPhase() { return boardmodel.getPhase(); } private void moreAgriculture(int index) { if (playercontroller.getPositie(boardmodel.getPlayer(), index) != 0 && playercontroller.vraagGraan(boardmodel.getPlayer()) != 10) { playercontroller.addGraan(boardmodel.getPlayer()); playercontroller.setPositie(boardmodel.getPlayer(), index, 0); } } private void moreVillagerHut(int index) { if (playercontroller.getPositie(boardmodel.getPlayer(), index) != 0 && playercontroller.getMaxVillagers(boardmodel.getPlayer()) != 10) { playercontroller.addMaxVillagers(boardmodel.getPlayer()); playercontroller.setPositie(boardmodel.getPlayer(), index, 0); } } private void buttonCheckPhase1(int index) { if (locatieVrij(index) && !boardmodel.getPlaced()) { if (index == 6 && playercontroller.getVillagers(boardmodel.getPlayer()) >= 2) { plaatsenStamleden(index, 2); } else if (index != 6) { plaatsenStamleden(index, 1); } } } private void buttonCheckPhase2(int index) { switch (index) { case 5: moreAgriculture(index); break; case 6: moreVillagerHut(index); break; case 7: gainTools(index); break; case 8: case 9: case 10: case 11: hutActie(index - 8); break; case 12: case 13: case 14: case 15: beschavingsKaarActie(index - 12); break; } } private void beschavingsKaarActie(int index) { if ((playercontroller.getPositie(boardmodel.getPlayer(), (index + 12)) != 0)) { ViewManager.loadPopupWindow(new ResourceView(boardmodel.getPlayer(), this.playercontroller, this, (index + 1), 0, index, "beschavingskaart")); } } public void kaartGekocht(int index, List<Integer> resources, String type) { if (type.equals("beschavingskaart")) { if (resourcesBetalen(resources)) { this.boardmodel.getPlayer().addKaarten(this.boardmodel.getKaart(index)); this.boardmodel.getKaart(index).uitvoerenActie(this.boardmodel.getPlayer()); this.boardmodel.updatePunten(); this.boardmodel.removeKaart(index); } else { System.out.println("niet genoeg resources"); // TODO deze else verbeteren } this.playercontroller.setPositie(this.boardmodel.getPlayer(), (index + 12), 0); } else { if (resourcesBetalen(resources)) { int punten = (resources.get(0) * 3) + (resources.get(1) * 4) + (resources.get(2) * 5) + (resources.get(3) * 6); this.boardmodel.getPlayer().increasePunten(punten); this.boardmodel.getPlayer().addHutjes(this.boardmodel.getHut(index)); this.boardmodel.updatePunten(); this.boardmodel.removeHut(index); } else { System.out.println("niet genoeg resources"); // TODO deze else verbeteren } this.playercontroller.setPositie(this.boardmodel.getPlayer(), (index + 8), 0); } } public void kaartAnnuleer(int index, String type) { if (type.equals("beschavingskaart")) { this.playercontroller.setPositie(this.boardmodel.getPlayer(), (index + 12), 0); } else { this.playercontroller.setPositie(this.boardmodel.getPlayer(), (index + 8), 0); } } private void hutActie(int index) { if ((this.playercontroller.getPositie(this.boardmodel.getPlayer(), (index + 8)) != 0)) { if (this.boardmodel.getHut(index).getPunten() == 0) { ViewManager.loadPopupWindow(new ResourceView(this.boardmodel.getPlayer(), this.playercontroller, this, this.boardmodel.getHut(index).getKosten().get(0), this.boardmodel.getHut(index).getKosten().get(1), index, "hutkaart")); } else { if (resourcesBetalen(this.boardmodel.getHut(index).getKosten())) { this.boardmodel.getPlayer().increasePunten(this.boardmodel.getHut(index).getPunten()); this.boardmodel.getPlayer().addHutjes(this.boardmodel.getHut(index)); this.boardmodel.updatePunten(); this.boardmodel.removeHut(index); } else { System.out.println("niet genoeg resources"); // TODO deze else verbeteren } playercontroller.setPositie(this.boardmodel.getPlayer(), (index + 8), 0); } } } private int voedselBetalen(PlayerModel player) { int remaining = 0; int voedselNodig = playercontroller.getMaxVillagers(player) - playercontroller.vraagGraan(player); int voedselSpeler = playercontroller.vraagResources(player).get(0); if (voedselSpeler >= voedselNodig) { playercontroller.reduceResource(player, 0, voedselNodig); boardmodel.addResources(0, voedselNodig); } else { playercontroller.reduceResource(player, 0, voedselSpeler); remaining = voedselNodig - voedselSpeler; boardmodel.addResources(0, voedselSpeler); } return remaining; } // Methode om<SUF> private boolean loopPlayers(int start, List<PlayerModel> player) { boolean found = false; for (int j = start + 1; j < player.size(); j++) { if (playercontroller.getVillagers(player.get(j)) != 0) { boardmodel.setPlayer(player.get(j)); // Veranderd de huidige speler found = true; break; } } return found; } private int checkPlayer() { int i = 0; for (int j = 0; j < 4; j++) { if (boardmodel.getPlayer().equals(players.get(j))) { // Bepaling welke player aan de beurt is i = j; break; } } return i; } private boolean checkResourceKost(int resource, List<Integer> kost) { return boardmodel.getPlayer().getResource(resource + 1) >= kost.get(resource); } private boolean locatieVrij(int index) { boolean status = true; for (PlayerModel player : players) { if (player.getPositie(index) != 0) { status = false; } } return status; } private void plaatsenStamleden(int index, int stamleden) { boardmodel.setPlaced(true); playercontroller.setVillagers(boardmodel.getPlayer(), (playercontroller.getVillagers(boardmodel.getPlayer()) - stamleden)); playercontroller.setPositie(boardmodel.getPlayer(), index, stamleden); } private boolean resourcesBetalen(List<Integer> kost) { if (checkResourceKost(0, kost) && checkResourceKost(1, kost) && checkResourceKost(2, kost) && checkResourceKost(3, kost)) { int i = 1; for (Integer amount : kost) { playercontroller.reduceResource(boardmodel.getPlayer(), i, amount); boardmodel.changeHoeveelheid(i, amount); i++; } return true; } else { return false; } } private void endGame() { for (PlayerModel player : players) { finalPuntenCount(player); } } private boolean checkWincondition() { boolean endGame = false; for (int i = 0; i < 4; i++) { if (boardmodel.getHutStapel(i).size() == 0) { endGame = true; } } if (boardmodel.getKaarten().size() < 4) { endGame = true; } return endGame; } private void finalPuntenCount(PlayerModel player) { List<Integer> multipliers = playercontroller.getMultiplier(player); for (Tool tool : playercontroller.getTools(player)) { this.playercontroller.increasePunten(player, multipliers.get(0) * tool.getLevel()); } this.playercontroller.increasePunten(player, multipliers.get(1) * this.playercontroller.getHutjes(player).size()); this.playercontroller.increasePunten(player, multipliers.get(2) * this.playercontroller.getMaxVillagers(player)); this.playercontroller.increasePunten(player, multipliers.get(3) * this.playercontroller.vraagGraan(player)); this.playercontroller.increasePunten(player, this.playercontroller.getTreasures(player).size() * this.playercontroller.getTreasures(player).size()); this.boardmodel.updatePunten(); } // TODO tijdelijk public ArrayList<PlayerModel> getPlayers() { return this.players; } public PlayerModel getPlayer() { return boardmodel.getPlayer(); } }
96559_0
package domain; import java.io.Serializable; import java.util.Objects; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name = "wedstrijdticket") @NamedQueries({ @NamedQuery(name = "WedstrijdTicket.getWedstrijdenByStadium", query = "select wt from WedstrijdTicket wt where wt.stadium.id = :id") }) public class WedstrijdTicket implements Serializable{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @ManyToOne(fetch = FetchType.LAZY) private Wedstrijd wedstrijd; @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "stadium_id") private Stadium stadium; private int tickets; //aantal tickets beschikbaar public WedstrijdTicket(Wedstrijd wedstrijd, int tickets) { this.wedstrijd = wedstrijd; this.tickets = tickets; } protected WedstrijdTicket() { } public int getTickets() { return tickets; } public Wedstrijd getWedstrijd() { return wedstrijd; } public int ticketsKopen(int aantal) { if (aantal <= 0) { return -1; } if (tickets >= aantal) { tickets -= aantal; return aantal; } int gekocht = tickets; tickets = 0; return gekocht; } public boolean uitverkocht() { return tickets == 0; } @Override public int hashCode() { return Objects.hash(tickets, wedstrijd); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; WedstrijdTicket other = (WedstrijdTicket) obj; return tickets == other.tickets && Objects.equals(wedstrijd, other.wedstrijd); } }
Darjow/FIFA-Ticket
src/main/java/domain/WedstrijdTicket.java
768
//aantal tickets beschikbaar
line_comment
nl
package domain; import java.io.Serializable; import java.util.Objects; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name = "wedstrijdticket") @NamedQueries({ @NamedQuery(name = "WedstrijdTicket.getWedstrijdenByStadium", query = "select wt from WedstrijdTicket wt where wt.stadium.id = :id") }) public class WedstrijdTicket implements Serializable{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @ManyToOne(fetch = FetchType.LAZY) private Wedstrijd wedstrijd; @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "stadium_id") private Stadium stadium; private int tickets; //aantal tickets<SUF> public WedstrijdTicket(Wedstrijd wedstrijd, int tickets) { this.wedstrijd = wedstrijd; this.tickets = tickets; } protected WedstrijdTicket() { } public int getTickets() { return tickets; } public Wedstrijd getWedstrijd() { return wedstrijd; } public int ticketsKopen(int aantal) { if (aantal <= 0) { return -1; } if (tickets >= aantal) { tickets -= aantal; return aantal; } int gekocht = tickets; tickets = 0; return gekocht; } public boolean uitverkocht() { return tickets == 0; } @Override public int hashCode() { return Objects.hash(tickets, wedstrijd); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; WedstrijdTicket other = (WedstrijdTicket) obj; return tickets == other.tickets && Objects.equals(wedstrijd, other.wedstrijd); } }
64583_0
package nl.hu.dp; import nl.hu.dp.data.*; import nl.hu.dp.domain.Adres; import nl.hu.dp.domain.OVChipkaart; import nl.hu.dp.domain.Product; import nl.hu.dp.domain.Reiziger; import java.sql.*; import java.util.ArrayList; import java.util.List; public class Main { private static Connection connection; private static ReizigerDAO RDAO; private static AdresDAO ADAO; private static OVChipkaartDAO OVDAO; private static ProductDAO PDAO; public static void main(String[] args) { try { getConnection(); //Initializing DAO's RDAO = new ReizigerDAOPsql(connection); ADAO = new AdresDAOPsql(connection); OVDAO = new OVChipkaartDAOPsql(connection); PDAO = new ProductDAOPsql(connection); //Testing testReizigerDAO(RDAO); testAdresDAO(ADAO); testOVChipkaartDAO(OVDAO); testProductDAO(PDAO); closeConnection(); }catch (SQLException sqlex){ System.err.println("Error: " + sqlex); } } public static void getConnection(){ String url = "jdbc:postgresql://localhost:5432/ovchip?user=postgres&password=postgrespw"; try { connection = DriverManager.getConnection(url); }catch (SQLException sqlex){ System.err.println("Error: " + sqlex); } } public static void closeConnection(){ try { connection.close(); }catch (SQLException sqlex){ System.err.println("[SQLERROR] " + sqlex); } } /** * P2. Reiziger DAO: persistentie van een klasse * * Deze methode test de CRUD-functionaliteit van de Reiziger DAO * * @throws SQLException */ private static void testReizigerDAO(ReizigerDAO rdao) throws SQLException { System.out.println("\n---------- Test ReizigerDAO -------------"); // Haal alle reizigers op uit de database List<Reiziger> reizigers = rdao.findAll(); System.out.println("[Test] ReizigerDAO.findAll() geeft de volgende reizigers:"); for (Reiziger r : reizigers) { System.out.println(r); } System.out.println(); // Maak een nieuwe reiziger met adres aan en persisteer deze in de database String gbdatum = "1981-03-14"; Reiziger sietske = new Reiziger(77, "S", "", "Boers", java.sql.Date.valueOf(gbdatum)); Adres adres = new Adres(20, "3249HS", "5431", "Langelaan", "Utrecht", sietske.getId()); List<OVChipkaart> ovKaarten = new ArrayList<>(); OVChipkaart ovKaart = new OVChipkaart(22, java.sql.Date.valueOf("2029-04-10"), 1, 25, 77); ovKaarten.add(ovKaart); sietske.setAdres(adres); sietske.setOvKaarten(ovKaarten); System.out.print("[Test] Eerst " + reizigers.size() + " reizigers, na ReizigerDAO.save() "); rdao.save(sietske); // Haal alle reizigers op reizigers = rdao.findAll(); System.out.println(reizigers.size() + " reizigers\n"); // Voeg aanvullende tests van de ontbrekende CRUD-operaties in. sietske.setTussenvoegsel("van"); rdao.update(sietske); // Haal een enkele reiziger op Reiziger r = rdao.findById(77); System.out.println(r.toString()); // Delete een reiziger rdao.delete(sietske); } private static void testAdresDAO(AdresDAO adao) throws SQLException { System.out.println("\n---------- Test AdresDAO -------------"); // Retrieve all adresses from the database List<Adres> adressen = adao.findAll(); System.out.println("[Test] AdresDAO.findAll() geeft de volgende adressen:"); for (Adres a : adressen) { System.out.println(a.toString()); } System.out.println(); // Create traveler to assign an adress Reiziger r = new Reiziger(78, "S", "", "Boers", java.sql.Date.valueOf("2012-04-20")); getRDAO().save(r); // Create a new adress and assign it to the traveler + persist it. Adres adres = new Adres(21, "3249HS", "5431", "Langelaan", "Utrecht", r.getId()); System.out.print("[Test] Eerst " + adressen.size() + " adressen, na AdresDAO.save() "); adao.save(adres); // Retrieve all adresses adressen = adao.findAll(); System.out.println(adressen.size() + " adressen\n"); // Update the adres with a different value adres.setHuisnummer("3241"); adao.update(adres); // Retrieve a single adress Adres a = adao.findById(21); System.out.println(a.toString()); // Delete an adress getRDAO().delete(getRDAO().findById(78)); } private static void testOVChipkaartDAO(OVChipkaartDAO ovdao) throws SQLException { System.out.println("\n---------- Test OVDAO -------------"); // Retrieve all ov-cards from the database List<OVChipkaart> ovKaarten = ovdao.findAll(); System.out.println("[Test] OVChipkaartDAO.findAll() geeft de volgende ov-kaarten:"); for (OVChipkaart ovKaart : ovKaarten) { System.out.println(ovKaart.toString()); } System.out.println(); // Create a new ov-card and persist it. OVChipkaart ovKaart = new OVChipkaart(22, java.sql.Date.valueOf("2029-04-20"), 2, 10, 1); Product product = new Product(22, "Test", "Testing", 20); ovKaart.addProduct(product); System.out.print("[Test] Eerst " + ovKaarten.size() + " ov-kaarten, na OVChipkaartDAO.save() "); ovdao.save(ovKaart); // Retrieve all ov-cards ovKaarten = ovdao.findAll(); System.out.println(ovKaarten.size() + " ov-kaarten\n"); // Update the ov-card with a different value ovKaart.setSaldo(12); System.out.println(ovKaart); ovdao.update(ovKaart); // Retrieve a single ov-card OVChipkaart ovChipkaart = ovdao.findById(22); System.out.println(ovChipkaart.toString()); //Clean up objects in database ovdao.delete(ovChipkaart); for (Product deleteProduct : ovChipkaart.getProducten()){ Main.getPDAO().delete(deleteProduct); } } private static void testProductDAO(ProductDAO pdao) throws SQLException { System.out.println("\n---------- Test PDAO -------------"); // Retrieve all products from the database List<Product> producten = pdao.findAll(); System.out.println("[Test] PDAO.findAll() geeft de volgende producten:"); for (Product product : producten) { System.out.println(product.toString()); } System.out.println(); // Create a new product and persist it. Product product = new Product(21, "Test", "Testing", 20); OVChipkaart ovKaart = new OVChipkaart(21, java.sql.Date.valueOf("2029-04-20"), 2, 10, 1); getOVDAO().save(ovKaart); product.addChipkaart(ovKaart); System.out.print("[Test] Eerst " + producten.size() + " producten, na PDAO.save() "); pdao.save(product); // Retrieve all products producten = pdao.findAll(); System.out.println(producten.size() + " producten\n"); // Update the product with a different value product.setPrijs(12); pdao.update(product); // Retrieve a single product Product product2 = pdao.findById(21); System.out.println(product2.toString()); pdao.delete(product2); getOVDAO().delete(ovKaart); } public static ReizigerDAO getRDAO() { return RDAO; } public static AdresDAO getADAO() { return ADAO; } public static OVChipkaartDAO getOVDAO() { return OVDAO; } public static ProductDAO getPDAO() { return PDAO; } }
DarkUnScripted/ovChip-DP
src/nl/hu/dp/Main.java
2,618
/** * P2. Reiziger DAO: persistentie van een klasse * * Deze methode test de CRUD-functionaliteit van de Reiziger DAO * * @throws SQLException */
block_comment
nl
package nl.hu.dp; import nl.hu.dp.data.*; import nl.hu.dp.domain.Adres; import nl.hu.dp.domain.OVChipkaart; import nl.hu.dp.domain.Product; import nl.hu.dp.domain.Reiziger; import java.sql.*; import java.util.ArrayList; import java.util.List; public class Main { private static Connection connection; private static ReizigerDAO RDAO; private static AdresDAO ADAO; private static OVChipkaartDAO OVDAO; private static ProductDAO PDAO; public static void main(String[] args) { try { getConnection(); //Initializing DAO's RDAO = new ReizigerDAOPsql(connection); ADAO = new AdresDAOPsql(connection); OVDAO = new OVChipkaartDAOPsql(connection); PDAO = new ProductDAOPsql(connection); //Testing testReizigerDAO(RDAO); testAdresDAO(ADAO); testOVChipkaartDAO(OVDAO); testProductDAO(PDAO); closeConnection(); }catch (SQLException sqlex){ System.err.println("Error: " + sqlex); } } public static void getConnection(){ String url = "jdbc:postgresql://localhost:5432/ovchip?user=postgres&password=postgrespw"; try { connection = DriverManager.getConnection(url); }catch (SQLException sqlex){ System.err.println("Error: " + sqlex); } } public static void closeConnection(){ try { connection.close(); }catch (SQLException sqlex){ System.err.println("[SQLERROR] " + sqlex); } } /** * P2. Reiziger DAO:<SUF>*/ private static void testReizigerDAO(ReizigerDAO rdao) throws SQLException { System.out.println("\n---------- Test ReizigerDAO -------------"); // Haal alle reizigers op uit de database List<Reiziger> reizigers = rdao.findAll(); System.out.println("[Test] ReizigerDAO.findAll() geeft de volgende reizigers:"); for (Reiziger r : reizigers) { System.out.println(r); } System.out.println(); // Maak een nieuwe reiziger met adres aan en persisteer deze in de database String gbdatum = "1981-03-14"; Reiziger sietske = new Reiziger(77, "S", "", "Boers", java.sql.Date.valueOf(gbdatum)); Adres adres = new Adres(20, "3249HS", "5431", "Langelaan", "Utrecht", sietske.getId()); List<OVChipkaart> ovKaarten = new ArrayList<>(); OVChipkaart ovKaart = new OVChipkaart(22, java.sql.Date.valueOf("2029-04-10"), 1, 25, 77); ovKaarten.add(ovKaart); sietske.setAdres(adres); sietske.setOvKaarten(ovKaarten); System.out.print("[Test] Eerst " + reizigers.size() + " reizigers, na ReizigerDAO.save() "); rdao.save(sietske); // Haal alle reizigers op reizigers = rdao.findAll(); System.out.println(reizigers.size() + " reizigers\n"); // Voeg aanvullende tests van de ontbrekende CRUD-operaties in. sietske.setTussenvoegsel("van"); rdao.update(sietske); // Haal een enkele reiziger op Reiziger r = rdao.findById(77); System.out.println(r.toString()); // Delete een reiziger rdao.delete(sietske); } private static void testAdresDAO(AdresDAO adao) throws SQLException { System.out.println("\n---------- Test AdresDAO -------------"); // Retrieve all adresses from the database List<Adres> adressen = adao.findAll(); System.out.println("[Test] AdresDAO.findAll() geeft de volgende adressen:"); for (Adres a : adressen) { System.out.println(a.toString()); } System.out.println(); // Create traveler to assign an adress Reiziger r = new Reiziger(78, "S", "", "Boers", java.sql.Date.valueOf("2012-04-20")); getRDAO().save(r); // Create a new adress and assign it to the traveler + persist it. Adres adres = new Adres(21, "3249HS", "5431", "Langelaan", "Utrecht", r.getId()); System.out.print("[Test] Eerst " + adressen.size() + " adressen, na AdresDAO.save() "); adao.save(adres); // Retrieve all adresses adressen = adao.findAll(); System.out.println(adressen.size() + " adressen\n"); // Update the adres with a different value adres.setHuisnummer("3241"); adao.update(adres); // Retrieve a single adress Adres a = adao.findById(21); System.out.println(a.toString()); // Delete an adress getRDAO().delete(getRDAO().findById(78)); } private static void testOVChipkaartDAO(OVChipkaartDAO ovdao) throws SQLException { System.out.println("\n---------- Test OVDAO -------------"); // Retrieve all ov-cards from the database List<OVChipkaart> ovKaarten = ovdao.findAll(); System.out.println("[Test] OVChipkaartDAO.findAll() geeft de volgende ov-kaarten:"); for (OVChipkaart ovKaart : ovKaarten) { System.out.println(ovKaart.toString()); } System.out.println(); // Create a new ov-card and persist it. OVChipkaart ovKaart = new OVChipkaart(22, java.sql.Date.valueOf("2029-04-20"), 2, 10, 1); Product product = new Product(22, "Test", "Testing", 20); ovKaart.addProduct(product); System.out.print("[Test] Eerst " + ovKaarten.size() + " ov-kaarten, na OVChipkaartDAO.save() "); ovdao.save(ovKaart); // Retrieve all ov-cards ovKaarten = ovdao.findAll(); System.out.println(ovKaarten.size() + " ov-kaarten\n"); // Update the ov-card with a different value ovKaart.setSaldo(12); System.out.println(ovKaart); ovdao.update(ovKaart); // Retrieve a single ov-card OVChipkaart ovChipkaart = ovdao.findById(22); System.out.println(ovChipkaart.toString()); //Clean up objects in database ovdao.delete(ovChipkaart); for (Product deleteProduct : ovChipkaart.getProducten()){ Main.getPDAO().delete(deleteProduct); } } private static void testProductDAO(ProductDAO pdao) throws SQLException { System.out.println("\n---------- Test PDAO -------------"); // Retrieve all products from the database List<Product> producten = pdao.findAll(); System.out.println("[Test] PDAO.findAll() geeft de volgende producten:"); for (Product product : producten) { System.out.println(product.toString()); } System.out.println(); // Create a new product and persist it. Product product = new Product(21, "Test", "Testing", 20); OVChipkaart ovKaart = new OVChipkaart(21, java.sql.Date.valueOf("2029-04-20"), 2, 10, 1); getOVDAO().save(ovKaart); product.addChipkaart(ovKaart); System.out.print("[Test] Eerst " + producten.size() + " producten, na PDAO.save() "); pdao.save(product); // Retrieve all products producten = pdao.findAll(); System.out.println(producten.size() + " producten\n"); // Update the product with a different value product.setPrijs(12); pdao.update(product); // Retrieve a single product Product product2 = pdao.findById(21); System.out.println(product2.toString()); pdao.delete(product2); getOVDAO().delete(ovKaart); } public static ReizigerDAO getRDAO() { return RDAO; } public static AdresDAO getADAO() { return ADAO; } public static OVChipkaartDAO getOVDAO() { return OVDAO; } public static ProductDAO getPDAO() { return PDAO; } }
152117_0
package theWario.cards; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.monsters.AbstractMonster; import theWario.powers.TrekkingPower; public class TrekTime extends AbstractWarioCard { public final static String ID = makeID("TrekTime"); //stupid intellij stuff POWER, SELF, UNCOMMON private static final int MAGIC = 2; private static final int UPG_MAGIC = 1; public TrekTime() { super(ID, 1, CardType.POWER, CardRarity.UNCOMMON, CardTarget.SELF); baseMagicNumber = magicNumber = MAGIC; } public void us(AbstractPlayer p, AbstractMonster m) { applyToSelf(new TrekkingPower(magicNumber)); } public void upgrade() { if (!upgraded) { upgradeName(); upgradeMagicNumber(UPG_MAGIC); } } }
DarkVexon/OldBandit
src/main/java/theWario/cards/TrekTime.java
273
//stupid intellij stuff POWER, SELF, UNCOMMON
line_comment
nl
package theWario.cards; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.monsters.AbstractMonster; import theWario.powers.TrekkingPower; public class TrekTime extends AbstractWarioCard { public final static String ID = makeID("TrekTime"); //stupid intellij<SUF> private static final int MAGIC = 2; private static final int UPG_MAGIC = 1; public TrekTime() { super(ID, 1, CardType.POWER, CardRarity.UNCOMMON, CardTarget.SELF); baseMagicNumber = magicNumber = MAGIC; } public void us(AbstractPlayer p, AbstractMonster m) { applyToSelf(new TrekkingPower(magicNumber)); } public void upgrade() { if (!upgraded) { upgradeName(); upgradeMagicNumber(UPG_MAGIC); } } }
175634_1
package gameEngine.ramses.events; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; public class EventQueueRoom { //static class die een add en resolved event functie heeft. //als een event word geadd word er bij alle eventHandlers gekeken of het hun event is. Zo ja activeer het. //private static ArrayList<Event> _allEvents = new ArrayList<Event>(); public static void addQueueItem(Event event,EventDispatcher dispatcher) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{ ArrayList<ListenerItem> listListeners = dispatcher.getAllListeners(); EventDispatcher currentParent; event.dispatcher = dispatcher; event.caster = dispatcher; callMethodsInListOfEvent(listListeners,event); if(event.isBubbles()){ currentParent = dispatcher.getParentListener(); while(currentParent != null){ event.caster = currentParent; listListeners = currentParent.getAllListeners(); callMethodsInListOfEvent(listListeners,event); currentParent = currentParent.getParentListener(); } } } private static void callMethodsInListOfEvent(ArrayList<ListenerItem> listToLoop, Event event) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{ ListenerItem currentItem; ArrayList<ListenerItem> list = listToLoop; if(list.size() > 0){ for(int i = list.size() - 1; i >= 0 ; i--){ currentItem = list.get(i); if(currentItem.getType() == event.getType()){ currentItem.getMethodData().getMethod().invoke(currentItem.getMethodData().getMethodHolder(), event); } } } } }
Darkfafi/JavaFrameworkRDP
src/gameEngine/ramses/events/EventQueueRoom.java
475
//als een event word geadd word er bij alle eventHandlers gekeken of het hun event is. Zo ja activeer het.
line_comment
nl
package gameEngine.ramses.events; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; public class EventQueueRoom { //static class die een add en resolved event functie heeft. //als een<SUF> //private static ArrayList<Event> _allEvents = new ArrayList<Event>(); public static void addQueueItem(Event event,EventDispatcher dispatcher) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{ ArrayList<ListenerItem> listListeners = dispatcher.getAllListeners(); EventDispatcher currentParent; event.dispatcher = dispatcher; event.caster = dispatcher; callMethodsInListOfEvent(listListeners,event); if(event.isBubbles()){ currentParent = dispatcher.getParentListener(); while(currentParent != null){ event.caster = currentParent; listListeners = currentParent.getAllListeners(); callMethodsInListOfEvent(listListeners,event); currentParent = currentParent.getParentListener(); } } } private static void callMethodsInListOfEvent(ArrayList<ListenerItem> listToLoop, Event event) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{ ListenerItem currentItem; ArrayList<ListenerItem> list = listToLoop; if(list.size() > 0){ for(int i = list.size() - 1; i >= 0 ; i--){ currentItem = list.get(i); if(currentItem.getType() == event.getType()){ currentItem.getMethodData().getMethod().invoke(currentItem.getMethodData().getMethodHolder(), event); } } } } }
25574_23
package com.carp.casper2.chitchat; import com.carp.nlp.lexicon.Word; import java.io.BufferedWriter; import java.io.IOException; import java.io.Writer; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.Vector; /** * Gebruikt de synoniemen lijst om onbekende woorden af te beeld op de bekende woorden uit de * patterns. Met een synoniemen lijst breid deze de patterns uit met rules om van onbekende woorden * op bekende te komen Hij maakt dus het (wiskundige) domein groter omdat er op meer dingen * getriggerd wordt, vandaar de naam. Het is een beetje onhandig om door DomainExpander gemaakt * rules weer toe te voegen. Voordat je de terminals uit een grammar haalt wil je meestal eerst die * synoniemen rules er uit plukken. <br> Je stopt er een hashset met bekende dingen in en je krijgt * een mapping terug. * * @author Oebele van der Veen * @version 1.0 */ public class DomainExpander { Vector baselevel = new Vector(); // idee // Er is een baseset waarop geprojecteerd moet worden // dit gaat met een reduction graph die iteratief opgebouwd word // reductiongraph = vector of level // level = vector of (word,backref) // baseset word in level 0 gezet en dan wordt elke element bij na gegaan // is er een synoniem s van woord x dan krijgt s een ref naar x en komt s een level hoger // daarna wordt het volgende level verwerkt. // Als er niks meer toegevoegd kan worden, dan wordt bij elke woord uit de baseset alle synoniemen // verzameld en wordt er een rule (synoniem1|..|synoniemx) do rewrite(woord) end van gemaakt. (collapsen) // mischien frontref ipv backref. Dan gaat het collapsen makkelijker. laten we dat ook doen ja // merk op dat er geen dubbelen in de reduction graph mogen voorkomen // een node van de reduction tree Set noDubArea = new HashSet(); // elk woord gooien we ook hierin (bij reference) // Dat is fijn want dan kunnen we snel doublures voorkomen Vector reductionGraph = new Vector(); //elk element is een level met nodes SynonymList synlist; /** * Maakt een Domain Expander bij een baseset en synoniemenlijst. Gegeven de bekende woorden van de * patterns in de baseset kan deze DomainExpander met de synoniemen nieuwe patterns maken * * @param baseset een HashSet met de terminals van de patterns * @param synlist een synonymList, */ public DomainExpander(Set baseset, SynonymList synlist) { // we zetten de basisset op level 0 van de reductionGraph; setBase(baseset); // even onthouden this.synlist = synlist; } /** * Slaat de mapping plat zodat deze weggeschreven kan worden Als er genoeg woorden zijn toegevoegd * dan zorgt deze functie er voor dat de data structuur wordt aangepast voor wegschrijven als * grammar rules */ public void collapse() { // de nodes van de base level hebben nu alle kinderen als hun kinderen Vector base = (Vector)reductionGraph.firstElement(); Node thisnode; for (int i = 0; i < base.size(); i++) { thisnode = (Node)base.elementAt(i); thisnode.children = thisnode.getChildren(); // de kinderen gelijk stellen aan alle kinderen } } /** * Voegt meer woorden toe aan de mapping. Dit ding voegt meer woorden toe aan de mapping. * expand(3);expand(4) is hetzelfde als expand(7) * * @param max het maximum aantal hops door de synoniemen vanaf de bekende woorden * @return hoeveel hops de laatste woorden echt zijn. Dit kan kleiner zijn dan max als er geen * synoniemen meer zijn. */ public int expand(int max) { int curlevels = reductionGraph.size(); Vector newlevel; boolean adding = true; // houd bij of er wat toegevoegd wordt, anders kunnen we ook wel stoppen. while ((adding) && (reductionGraph.size() - curlevels) < max) { newlevel = expandLevel((Vector)reductionGraph.lastElement()); reductionGraph.add(newlevel); if (newlevel.size() == 0) { adding = false; } } return reductionGraph.size() - curlevels; } private Vector expandLevel(Vector level) { System.out.println("Expanding level with " + level.size() + " elements"); System.out.println("Strings in noDubArea: " + noDubArea.size()); Vector synonyms; Node thisnode, newnode; Vector newlevel = new Vector(); String aword; for (int i = 0; i < level.size(); i++) { thisnode = ((Node)level.elementAt(i)); synonyms = synlist.getSynonymsOf(thisnode.word); if (synonyms != null) { for (int s = 0; s < synonyms.size(); s++) { aword = (String)synonyms.elementAt(s); if (!noDubArea.contains(aword)) { newnode = new Node(aword); //Node(s) stopts s ook direct in de noDubArea newlevel.add(newnode); thisnode.addChild(newnode); } } } } return newlevel; } private void setBase(Set baseSet) { Word word; String str; System.out.println("Adding base set"); if (baseSet == null) { System.out.println("Given baseset is null"); return; } Vector newlevel = new Vector(200); Iterator iterator = baseSet.iterator(); while (iterator.hasNext()) { word = (Word)iterator.next(); if (word != null) { str = word.toString(); if (str != null) { newlevel.add(new Node(str)); } } } reductionGraph.add(newlevel); System.out.println("Done"); } /** * Schrijf de synoniemen mapping naar rules. Stopt de mapping in de writer * * @param w een Writer waar de rules heen geschreven worden. */ public void writeToGrammar(Writer w) throws IOException { BufferedWriter writer = new BufferedWriter(w); String setting = "rule ^setIgnoreHead(true) ^setIgnoreTail(true) ^setMaxIgnored(256) end"; String commentaar = "// Dit bestand is automatisch gegenereert door een DomainExpander object, Het is absoluut slim hier af te blijven."; String line; Vector base = (Vector)reductionGraph.firstElement(); Node thisnode; try { writer.write(commentaar, 0, commentaar.length()); writer.newLine(); writer.newLine(); writer.newLine(); writer.write(setting, 0, setting.length()); writer.newLine(); for (int i = 0; i < base.size(); i++) { thisnode = (Node)base.elementAt(i); line = thisnode.toParserString(); if (line.length() > 0) { writer.write(line, 0, line.length()); writer.newLine(); } } } finally { writer.close(); } } private class Node { private Vector children = new Vector(); // de synonymen van dit woord in een hoger level private String word; Node(String word) { this.word = word; noDubArea.add(word); // Kijk stoppen we er gewoon direct in } public void addChild(Node node) { children.add(node); } //recursief alle kinderen verzamelen public Vector getChildren() { Vector result = new Vector(); for (int i = 0; i < children.size(); i++) { result.addAll(((Node)children.elementAt(i)).getChildren()); } result.addAll(children); return result; } public String toParserString() { // maak een "rule (childer1|childer2...) do rewrite(word) end" if (children.size() == 0) { return ""; // geen kinderen, geen regel } if (children.size() == 1) { return "rule \"" + ((Node)children.firstElement()).word + "\" do rewrite(" + word + ") end"; } StringBuffer result = new StringBuffer(); result.append("rule ("); for (int i = 0; i < children.size(); i++) { if (i > 0) { result.append("|"); } result.append("\""); result.append(((Node)children.elementAt(i)).word); result.append("\""); } result.append(") do rewrite(" + word + ") end"); return result.toString(); } } }
DaveKriewall/Rearranger
test/testData/com/wrq/rearranger/DomainExpanderTest.java
2,471
//Node(s) stopts s ook direct in de noDubArea
line_comment
nl
package com.carp.casper2.chitchat; import com.carp.nlp.lexicon.Word; import java.io.BufferedWriter; import java.io.IOException; import java.io.Writer; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.Vector; /** * Gebruikt de synoniemen lijst om onbekende woorden af te beeld op de bekende woorden uit de * patterns. Met een synoniemen lijst breid deze de patterns uit met rules om van onbekende woorden * op bekende te komen Hij maakt dus het (wiskundige) domein groter omdat er op meer dingen * getriggerd wordt, vandaar de naam. Het is een beetje onhandig om door DomainExpander gemaakt * rules weer toe te voegen. Voordat je de terminals uit een grammar haalt wil je meestal eerst die * synoniemen rules er uit plukken. <br> Je stopt er een hashset met bekende dingen in en je krijgt * een mapping terug. * * @author Oebele van der Veen * @version 1.0 */ public class DomainExpander { Vector baselevel = new Vector(); // idee // Er is een baseset waarop geprojecteerd moet worden // dit gaat met een reduction graph die iteratief opgebouwd word // reductiongraph = vector of level // level = vector of (word,backref) // baseset word in level 0 gezet en dan wordt elke element bij na gegaan // is er een synoniem s van woord x dan krijgt s een ref naar x en komt s een level hoger // daarna wordt het volgende level verwerkt. // Als er niks meer toegevoegd kan worden, dan wordt bij elke woord uit de baseset alle synoniemen // verzameld en wordt er een rule (synoniem1|..|synoniemx) do rewrite(woord) end van gemaakt. (collapsen) // mischien frontref ipv backref. Dan gaat het collapsen makkelijker. laten we dat ook doen ja // merk op dat er geen dubbelen in de reduction graph mogen voorkomen // een node van de reduction tree Set noDubArea = new HashSet(); // elk woord gooien we ook hierin (bij reference) // Dat is fijn want dan kunnen we snel doublures voorkomen Vector reductionGraph = new Vector(); //elk element is een level met nodes SynonymList synlist; /** * Maakt een Domain Expander bij een baseset en synoniemenlijst. Gegeven de bekende woorden van de * patterns in de baseset kan deze DomainExpander met de synoniemen nieuwe patterns maken * * @param baseset een HashSet met de terminals van de patterns * @param synlist een synonymList, */ public DomainExpander(Set baseset, SynonymList synlist) { // we zetten de basisset op level 0 van de reductionGraph; setBase(baseset); // even onthouden this.synlist = synlist; } /** * Slaat de mapping plat zodat deze weggeschreven kan worden Als er genoeg woorden zijn toegevoegd * dan zorgt deze functie er voor dat de data structuur wordt aangepast voor wegschrijven als * grammar rules */ public void collapse() { // de nodes van de base level hebben nu alle kinderen als hun kinderen Vector base = (Vector)reductionGraph.firstElement(); Node thisnode; for (int i = 0; i < base.size(); i++) { thisnode = (Node)base.elementAt(i); thisnode.children = thisnode.getChildren(); // de kinderen gelijk stellen aan alle kinderen } } /** * Voegt meer woorden toe aan de mapping. Dit ding voegt meer woorden toe aan de mapping. * expand(3);expand(4) is hetzelfde als expand(7) * * @param max het maximum aantal hops door de synoniemen vanaf de bekende woorden * @return hoeveel hops de laatste woorden echt zijn. Dit kan kleiner zijn dan max als er geen * synoniemen meer zijn. */ public int expand(int max) { int curlevels = reductionGraph.size(); Vector newlevel; boolean adding = true; // houd bij of er wat toegevoegd wordt, anders kunnen we ook wel stoppen. while ((adding) && (reductionGraph.size() - curlevels) < max) { newlevel = expandLevel((Vector)reductionGraph.lastElement()); reductionGraph.add(newlevel); if (newlevel.size() == 0) { adding = false; } } return reductionGraph.size() - curlevels; } private Vector expandLevel(Vector level) { System.out.println("Expanding level with " + level.size() + " elements"); System.out.println("Strings in noDubArea: " + noDubArea.size()); Vector synonyms; Node thisnode, newnode; Vector newlevel = new Vector(); String aword; for (int i = 0; i < level.size(); i++) { thisnode = ((Node)level.elementAt(i)); synonyms = synlist.getSynonymsOf(thisnode.word); if (synonyms != null) { for (int s = 0; s < synonyms.size(); s++) { aword = (String)synonyms.elementAt(s); if (!noDubArea.contains(aword)) { newnode = new Node(aword); //Node(s) stopts<SUF> newlevel.add(newnode); thisnode.addChild(newnode); } } } } return newlevel; } private void setBase(Set baseSet) { Word word; String str; System.out.println("Adding base set"); if (baseSet == null) { System.out.println("Given baseset is null"); return; } Vector newlevel = new Vector(200); Iterator iterator = baseSet.iterator(); while (iterator.hasNext()) { word = (Word)iterator.next(); if (word != null) { str = word.toString(); if (str != null) { newlevel.add(new Node(str)); } } } reductionGraph.add(newlevel); System.out.println("Done"); } /** * Schrijf de synoniemen mapping naar rules. Stopt de mapping in de writer * * @param w een Writer waar de rules heen geschreven worden. */ public void writeToGrammar(Writer w) throws IOException { BufferedWriter writer = new BufferedWriter(w); String setting = "rule ^setIgnoreHead(true) ^setIgnoreTail(true) ^setMaxIgnored(256) end"; String commentaar = "// Dit bestand is automatisch gegenereert door een DomainExpander object, Het is absoluut slim hier af te blijven."; String line; Vector base = (Vector)reductionGraph.firstElement(); Node thisnode; try { writer.write(commentaar, 0, commentaar.length()); writer.newLine(); writer.newLine(); writer.newLine(); writer.write(setting, 0, setting.length()); writer.newLine(); for (int i = 0; i < base.size(); i++) { thisnode = (Node)base.elementAt(i); line = thisnode.toParserString(); if (line.length() > 0) { writer.write(line, 0, line.length()); writer.newLine(); } } } finally { writer.close(); } } private class Node { private Vector children = new Vector(); // de synonymen van dit woord in een hoger level private String word; Node(String word) { this.word = word; noDubArea.add(word); // Kijk stoppen we er gewoon direct in } public void addChild(Node node) { children.add(node); } //recursief alle kinderen verzamelen public Vector getChildren() { Vector result = new Vector(); for (int i = 0; i < children.size(); i++) { result.addAll(((Node)children.elementAt(i)).getChildren()); } result.addAll(children); return result; } public String toParserString() { // maak een "rule (childer1|childer2...) do rewrite(word) end" if (children.size() == 0) { return ""; // geen kinderen, geen regel } if (children.size() == 1) { return "rule \"" + ((Node)children.firstElement()).word + "\" do rewrite(" + word + ") end"; } StringBuffer result = new StringBuffer(); result.append("rule ("); for (int i = 0; i < children.size(); i++) { if (i > 0) { result.append("|"); } result.append("\""); result.append(((Node)children.elementAt(i)).word); result.append("\""); } result.append(") do rewrite(" + word + ") end"); return result.toString(); } } }
30891_0
package be.ehb.debeterejokes.data; import android.app.Application; import androidx.annotation.NonNull; import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.MutableLiveData; import java.util.ArrayList; public class JokeViewModel extends AndroidViewModel { MutableLiveData<ArrayList<Joke>> jokeLiveData; public JokeViewModel(@NonNull Application application) { super(application); jokeLiveData = new MutableLiveData<>(); setupJokes(); } //Zou in 't echt uw api of db call zijn. private void setupJokes() { ArrayList<Joke> jokes = new ArrayList<>(); jokes.add(new Joke("het is blauw en het weegt niet veel", "lichtblauw")); jokes.add(new Joke("het is groen en het weegt niet veel", "lichtgroen")); jokes.add(new Joke("het is geel en het weegt niet veel", "lichtgeel")); jokes.add(new Joke("het is wit en het staat in de hoek", "een gestrafte frigo")); jokes.add(new Joke("het is wit en het ontploft", "een boemkool")); jokes.add(new Joke("het is oranje en als het regent verdwijnt het", "de mannen van de gemeente")); jokes.add(new Joke("het is grijs en als het in uw oog vliegt zijt ge dood", "een vliegtuig")); jokeLiveData.setValue(jokes); } public void addJoke(Joke newJoke){ ArrayList<Joke> jokes = jokeLiveData.getValue(); jokes.add(newJoke); jokeLiveData.setValue(jokes); } public MutableLiveData<ArrayList<Joke>> getJokeLiveData() { return jokeLiveData; } }
David-VS/DeGemiddeldeJokes
app/src/main/java/be/ehb/debeterejokes/data/JokeViewModel.java
500
//Zou in 't echt uw api of db call zijn.
line_comment
nl
package be.ehb.debeterejokes.data; import android.app.Application; import androidx.annotation.NonNull; import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.MutableLiveData; import java.util.ArrayList; public class JokeViewModel extends AndroidViewModel { MutableLiveData<ArrayList<Joke>> jokeLiveData; public JokeViewModel(@NonNull Application application) { super(application); jokeLiveData = new MutableLiveData<>(); setupJokes(); } //Zou in<SUF> private void setupJokes() { ArrayList<Joke> jokes = new ArrayList<>(); jokes.add(new Joke("het is blauw en het weegt niet veel", "lichtblauw")); jokes.add(new Joke("het is groen en het weegt niet veel", "lichtgroen")); jokes.add(new Joke("het is geel en het weegt niet veel", "lichtgeel")); jokes.add(new Joke("het is wit en het staat in de hoek", "een gestrafte frigo")); jokes.add(new Joke("het is wit en het ontploft", "een boemkool")); jokes.add(new Joke("het is oranje en als het regent verdwijnt het", "de mannen van de gemeente")); jokes.add(new Joke("het is grijs en als het in uw oog vliegt zijt ge dood", "een vliegtuig")); jokeLiveData.setValue(jokes); } public void addJoke(Joke newJoke){ ArrayList<Joke> jokes = jokeLiveData.getValue(); jokes.add(newJoke); jokeLiveData.setValue(jokes); } public MutableLiveData<ArrayList<Joke>> getJokeLiveData() { return jokeLiveData; } }
205950_3
package dev.shingi.endpoints.Models; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.UUID; public class Grootboek implements Comparable<Grootboek> { // Information from HTTP request String modifiedOn; String omschrijving; Boolean kostenplaatsVerplicht; String rekeningCode; Boolean nonactief; Integer nummer; String grootboekfunctie; String grootboekRubriek; List<Map<String, Object>> rgsCodes; List<String> btwSoort; // Geeft een enkele of combinatie van 'Geen' 'Overig' 'Hoog' 'Laag' String vatRateCode; UUID id; String uri; @Override public int compareTo(Grootboek other) { return Integer.compare(this.nummer, other.nummer); } @Override public String toString() { return nummer + " " + omschrijving; // Everything // return "Grootboek [modifiedOn=" + modifiedOn + ",\ndescription=" + omschrijving + ",\nkostenplaatsVerplicht=" // + kostenplaatsVerplicht + ",\nrekeningCode=" + rekeningCode + ",\nnonactief=" + nonactief + ",\nnummer=" // + nummer + ",\ngrootboekfunctie=" + grootboekfunctie + ",\ngrootboekRubriek=" + grootboekRubriek // + ",\nrgsCodes=" + rgsCodes + ",\nbtwSoort=" + btwSoort + ",\nvatRateCode=" + vatRateCode + ",\nid=" + id // + ",\nuri=" + uri + "]"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Grootboek that = (Grootboek) o; // Returns true if nummer and omschrijving are equal return Objects.equals(nummer, that.nummer) && Objects.equals(omschrijving, that.omschrijving); } @Override public int hashCode() { return Objects.hash(omschrijving, nummer); } public String getModifiedOn() { return modifiedOn; } public void setModifiedOn(String modifiedOn) { this.modifiedOn = modifiedOn; } public String getOmschrijving() { return omschrijving; } public void setOmschrijving(String omschrijving) { this.omschrijving = omschrijving; } public Boolean getKostenplaatsVerplicht() { return kostenplaatsVerplicht; } public void setKostenplaatsVerplicht(Boolean kostenplaatsVerplicht) { this.kostenplaatsVerplicht = kostenplaatsVerplicht; } public String getRekeningCode() { return rekeningCode; } public void setRekeningCode(String rekeningCode) { this.rekeningCode = rekeningCode; } public Boolean getNonactief() { return nonactief; } public void setNonactief(Boolean nonactief) { this.nonactief = nonactief; } public Integer getNummer() { return nummer; } public void setNummer(Integer nummer) { this.nummer = nummer; } public String getGrootboekfunctie() { return grootboekfunctie; } public void setGrootboekfunctie(String grootboekfunctie) { this.grootboekfunctie = grootboekfunctie; } public String getGrootboekRubriek() { return grootboekRubriek; } public void setGrootboekRubriek(String grootboekRubriek) { this.grootboekRubriek = grootboekRubriek; } public List<Map<String, Object>> getRgsCodes() { return rgsCodes; } public void setRgsCodes(List<Map<String, Object>> rgsCodes) { this.rgsCodes = rgsCodes; } public List<String> getBtwSoort() { return btwSoort; } public void setBtwSoort(List<String> btwSoort) { this.btwSoort = btwSoort; } public String getVatRateCode() { return vatRateCode; } public void setVatRateCode(String vatRateCode) { this.vatRateCode = vatRateCode; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } }
DavidRenger/RengerSynchronize_V2
src/main/java/dev/shingi/endpoints/Models/Grootboek.java
1,365
// + kostenplaatsVerplicht + ",\nrekeningCode=" + rekeningCode + ",\nnonactief=" + nonactief + ",\nnummer="
line_comment
nl
package dev.shingi.endpoints.Models; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.UUID; public class Grootboek implements Comparable<Grootboek> { // Information from HTTP request String modifiedOn; String omschrijving; Boolean kostenplaatsVerplicht; String rekeningCode; Boolean nonactief; Integer nummer; String grootboekfunctie; String grootboekRubriek; List<Map<String, Object>> rgsCodes; List<String> btwSoort; // Geeft een enkele of combinatie van 'Geen' 'Overig' 'Hoog' 'Laag' String vatRateCode; UUID id; String uri; @Override public int compareTo(Grootboek other) { return Integer.compare(this.nummer, other.nummer); } @Override public String toString() { return nummer + " " + omschrijving; // Everything // return "Grootboek [modifiedOn=" + modifiedOn + ",\ndescription=" + omschrijving + ",\nkostenplaatsVerplicht=" // + kostenplaatsVerplicht<SUF> // + nummer + ",\ngrootboekfunctie=" + grootboekfunctie + ",\ngrootboekRubriek=" + grootboekRubriek // + ",\nrgsCodes=" + rgsCodes + ",\nbtwSoort=" + btwSoort + ",\nvatRateCode=" + vatRateCode + ",\nid=" + id // + ",\nuri=" + uri + "]"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Grootboek that = (Grootboek) o; // Returns true if nummer and omschrijving are equal return Objects.equals(nummer, that.nummer) && Objects.equals(omschrijving, that.omschrijving); } @Override public int hashCode() { return Objects.hash(omschrijving, nummer); } public String getModifiedOn() { return modifiedOn; } public void setModifiedOn(String modifiedOn) { this.modifiedOn = modifiedOn; } public String getOmschrijving() { return omschrijving; } public void setOmschrijving(String omschrijving) { this.omschrijving = omschrijving; } public Boolean getKostenplaatsVerplicht() { return kostenplaatsVerplicht; } public void setKostenplaatsVerplicht(Boolean kostenplaatsVerplicht) { this.kostenplaatsVerplicht = kostenplaatsVerplicht; } public String getRekeningCode() { return rekeningCode; } public void setRekeningCode(String rekeningCode) { this.rekeningCode = rekeningCode; } public Boolean getNonactief() { return nonactief; } public void setNonactief(Boolean nonactief) { this.nonactief = nonactief; } public Integer getNummer() { return nummer; } public void setNummer(Integer nummer) { this.nummer = nummer; } public String getGrootboekfunctie() { return grootboekfunctie; } public void setGrootboekfunctie(String grootboekfunctie) { this.grootboekfunctie = grootboekfunctie; } public String getGrootboekRubriek() { return grootboekRubriek; } public void setGrootboekRubriek(String grootboekRubriek) { this.grootboekRubriek = grootboekRubriek; } public List<Map<String, Object>> getRgsCodes() { return rgsCodes; } public void setRgsCodes(List<Map<String, Object>> rgsCodes) { this.rgsCodes = rgsCodes; } public List<String> getBtwSoort() { return btwSoort; } public void setBtwSoort(List<String> btwSoort) { this.btwSoort = btwSoort; } public String getVatRateCode() { return vatRateCode; } public void setVatRateCode(String vatRateCode) { this.vatRateCode = vatRateCode; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } }
135658_2
package util; public final class Constants{ public static final byte PLATFORM_INTEL = 0x01; public static final byte PLATFORM_POWERPC = 0x02; public static final byte PLATFORM_MACOSX = 0x03; public static final byte PRODUCT_STARCRAFT = 0x01; public static final byte PRODUCT_BROODWAR = 0x02; public static final byte PRODUCT_WAR2BNE = 0x03; public static final byte PRODUCT_DIABLO2 = 0x04; public static final byte PRODUCT_LORDOFDESTRUCTION = 0x05; public static final byte PRODUCT_JAPANSTARCRAFT = 0x06; public static final byte PRODUCT_WARCRAFT3 = 0x07; public static final byte PRODUCT_THEFROZENTHRONE = 0x08; public static final byte PRODUCT_DIABLO = 0x09; public static final byte PRODUCT_DIABLOSHAREWARE = 0x0A; public static final byte PRODUCT_STARCRAFTSHAREWARE= 0x0B; public static String[] prods = {"STAR", "SEXP", "W2BN", "D2DV", "D2XP", "JSTR", "WAR3", "W3XP", "DRTL", "DSHR", "SSHR"}; public static String[][] IX86files = { {"IX86/STAR/", "StarCraft.exe", "Storm.dll", "NULL", "STAR.bin"}, {"IX86/STAR/", "StarCraft.exe", "Storm.dll", "NULL", "STAR.bin"}, {"IX86/W2BN/", "Warcraft II BNE.exe", "Storm.dll", "Battle.snp", "W2BN.bin"}, {"IX86/D2DV/", "Game.exe", "NULL", "NULL", "D2DV.bin"}, {"IX86/D2XP/", "Game.exe", "NULL", "NULL", "D2XP.bin"}, {"IX86/JSTR/", "StarcraftJ.exe", "Storm.dll", "Battle.snp", "JSTR.bin"}, {"IX86/WAR3/", "Warcraft III.exe", "NULL", "NULL", "WAR3.bin"}, {"IX86/WAR3/", "Warcraft III.exe", "NULL", "NULL", "WAR3.bin"}, {"IX86/DRTL/", "Diablo.exe", "Storm.dll", "Battle.snp", "DRTL.bin"}, {"IX86/DSHR/", "Diablo_s.exe", "Storm.dll", "Battle.snp", "DSHR.bin"}, {"IX86/SSHR/", "Starcraft.exe", "Storm.dll", "Battle.snp", "SSHR.bin"} }; public static int[] IX86verbytes = {0xD3, 0xD3, 0x4f, 0x0e, 0x0e, 0xa9, 0x1E, 0x1E, 0x2a, 0x2a, 0xa5}; public static String[] IX86versions = {"", "", "2.0.2.1", "1.14.3.71", "1.14.3.71", "", "", "", "2001, 5, 18, 1", "", ""}; public static String[] IX86certs = {"", "", "", "", "", "", "", "", "", "", ""}; public static String ArchivePath = "DLLs/"; public static String LogFilePath = "./Logs/"; public static String build="Build V3.1 Bug Fixes, SQL Stats tracking. (10-14-07)"; //public static String build="Build V3.0 BotNet Admin, Lockdown, Legacy Clients.(07-07-07)"; //public static String build="Build V2.9 Remote admin, extended admin commands w/ JSTR support.(01/18/06)"; public static int maxThreads=500; public static int BNLSPort=9367; public static boolean requireAuthorization=false; public static boolean trackStatistics=true; public static int ipAuthStatus=1; //default is IPBans on public static boolean displayPacketInfo=true; public static boolean displayParseInfo=false; public static boolean debugInfo=false; public static boolean enableLogging = false; public static int logKeepDuration = 7; public static boolean RunAdmin = false; public static String BotNetBotID = ""; public static String BotNetHubPW = ""; public static String BotNetDatabase = ""; public static String BotNetUsername = ""; public static String BotNetPassword = ""; public static String BotNetServer = "www.valhallalegends.com"; public static boolean LogStats = false; public static String StatsUsername = ""; public static String StatsPassword = ""; public static String StatsDatabase = ""; public static String StatsServer = "localhost"; public static int StatsQueue = 10; public static boolean StatsLogIps = false; public static boolean StatsLogCRevs = true; public static boolean StatsLogBotIDs = true; public static boolean StatsLogConns = true; public static boolean StatsCheckSchema = true; public static String DownloadPath = "./"; public static boolean RunHTTP = true; public static int HTTPPort = 81; public static int lngServerVer=0x01; public static int numOfNews=0; public static String[] strNews={"", "", "", "", ""}; }
Davnit/JBLS
util/Constants.java
1,588
//default is IPBans on
line_comment
nl
package util; public final class Constants{ public static final byte PLATFORM_INTEL = 0x01; public static final byte PLATFORM_POWERPC = 0x02; public static final byte PLATFORM_MACOSX = 0x03; public static final byte PRODUCT_STARCRAFT = 0x01; public static final byte PRODUCT_BROODWAR = 0x02; public static final byte PRODUCT_WAR2BNE = 0x03; public static final byte PRODUCT_DIABLO2 = 0x04; public static final byte PRODUCT_LORDOFDESTRUCTION = 0x05; public static final byte PRODUCT_JAPANSTARCRAFT = 0x06; public static final byte PRODUCT_WARCRAFT3 = 0x07; public static final byte PRODUCT_THEFROZENTHRONE = 0x08; public static final byte PRODUCT_DIABLO = 0x09; public static final byte PRODUCT_DIABLOSHAREWARE = 0x0A; public static final byte PRODUCT_STARCRAFTSHAREWARE= 0x0B; public static String[] prods = {"STAR", "SEXP", "W2BN", "D2DV", "D2XP", "JSTR", "WAR3", "W3XP", "DRTL", "DSHR", "SSHR"}; public static String[][] IX86files = { {"IX86/STAR/", "StarCraft.exe", "Storm.dll", "NULL", "STAR.bin"}, {"IX86/STAR/", "StarCraft.exe", "Storm.dll", "NULL", "STAR.bin"}, {"IX86/W2BN/", "Warcraft II BNE.exe", "Storm.dll", "Battle.snp", "W2BN.bin"}, {"IX86/D2DV/", "Game.exe", "NULL", "NULL", "D2DV.bin"}, {"IX86/D2XP/", "Game.exe", "NULL", "NULL", "D2XP.bin"}, {"IX86/JSTR/", "StarcraftJ.exe", "Storm.dll", "Battle.snp", "JSTR.bin"}, {"IX86/WAR3/", "Warcraft III.exe", "NULL", "NULL", "WAR3.bin"}, {"IX86/WAR3/", "Warcraft III.exe", "NULL", "NULL", "WAR3.bin"}, {"IX86/DRTL/", "Diablo.exe", "Storm.dll", "Battle.snp", "DRTL.bin"}, {"IX86/DSHR/", "Diablo_s.exe", "Storm.dll", "Battle.snp", "DSHR.bin"}, {"IX86/SSHR/", "Starcraft.exe", "Storm.dll", "Battle.snp", "SSHR.bin"} }; public static int[] IX86verbytes = {0xD3, 0xD3, 0x4f, 0x0e, 0x0e, 0xa9, 0x1E, 0x1E, 0x2a, 0x2a, 0xa5}; public static String[] IX86versions = {"", "", "2.0.2.1", "1.14.3.71", "1.14.3.71", "", "", "", "2001, 5, 18, 1", "", ""}; public static String[] IX86certs = {"", "", "", "", "", "", "", "", "", "", ""}; public static String ArchivePath = "DLLs/"; public static String LogFilePath = "./Logs/"; public static String build="Build V3.1 Bug Fixes, SQL Stats tracking. (10-14-07)"; //public static String build="Build V3.0 BotNet Admin, Lockdown, Legacy Clients.(07-07-07)"; //public static String build="Build V2.9 Remote admin, extended admin commands w/ JSTR support.(01/18/06)"; public static int maxThreads=500; public static int BNLSPort=9367; public static boolean requireAuthorization=false; public static boolean trackStatistics=true; public static int ipAuthStatus=1; //default is<SUF> public static boolean displayPacketInfo=true; public static boolean displayParseInfo=false; public static boolean debugInfo=false; public static boolean enableLogging = false; public static int logKeepDuration = 7; public static boolean RunAdmin = false; public static String BotNetBotID = ""; public static String BotNetHubPW = ""; public static String BotNetDatabase = ""; public static String BotNetUsername = ""; public static String BotNetPassword = ""; public static String BotNetServer = "www.valhallalegends.com"; public static boolean LogStats = false; public static String StatsUsername = ""; public static String StatsPassword = ""; public static String StatsDatabase = ""; public static String StatsServer = "localhost"; public static int StatsQueue = 10; public static boolean StatsLogIps = false; public static boolean StatsLogCRevs = true; public static boolean StatsLogBotIDs = true; public static boolean StatsLogConns = true; public static boolean StatsCheckSchema = true; public static String DownloadPath = "./"; public static boolean RunHTTP = true; public static int HTTPPort = 81; public static int lngServerVer=0x01; public static int numOfNews=0; public static String[] strNews={"", "", "", "", ""}; }
14108_7
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package mario.Stages; import java.awt.Rectangle; import java.awt.Graphics; import java.awt.Color; import java.awt.Font; import java.util.ArrayList; import mario.MarioData; import mario.MarioWorld; import mario.core.Collision; import mario.core.StageObject; import mario.core.interfaces.Static; /** * * @author Mike */ public class ScoreBalk extends StageObject implements Static { private int score; private int newScore; private int killedEnemy; // private String scoreString; private int lives = 3; private int coins; private MarioData marioData; public ScoreBalk(Stage game, MarioWorld marioWorld ,int x, int y, int width, int height) { super(game, x, y, width, height, "/images/nsmbtileset.png"); frames.put("muntje", new Rectangle(457, 167, 45, 48)); frames.put("coin", new Rectangle(1278, 2328, 48, 48)); setAnimation(new String[]{"coin"}); marioData = marioWorld.getMarioData(); } @Override public void doLoopAction() { //Controleerd telkens op nieuwe Score. addScore(); // scoreString = Integer.toString(score); } @Override public void draw(Graphics graphics) { Font font = new Font("Arial", Font.PLAIN, 20); graphics.setFont(font); graphics.setColor(Color.WHITE); graphics.drawString("Score: " + (int)marioData.getPoints(), 10, 30); setAnimation(new String[]{"muntje"}); // graphics.drawImage(getImage(), 50, 5, null); graphics.drawString("Coins: " + coins, 110, 30); //setAnimation(new String[]{"leven"}); // graphics.drawImage(getImage(), 20, 5, null); graphics.drawString("Lives: " + marioData.getLives(), 210, 30); graphics.drawString("Killed enemy's: " + killedEnemy, 310, 30); } //Zit in de doLoop zodat altijd de juiste Score aangegeven wordt. public void addScore() { newScore = (int) (getScore() + (getCoins() * 100) + (killedEnemy * 20)); } public void addScore(int punten) { score += punten; } public int getCoins() { return marioData.getCoins(); } public void setCoins(int coins) { marioData.setCoins(coins); } public int getLives() { return marioData.getLives(); } public void setLives(int lives) { marioData.setLives(lives); } public long getScore() { return marioData.getPoints(); } public void setScore(long score) { marioData.setPoints(score); } public void addCoin() { coins++; } public void killEnemy() { killedEnemy++; } @Override public void doCharacterCollision(ArrayList<Collision> collisions, StageObject mapObject) { } public int getKilledEnemys() { return killedEnemy; } public void setKilledEnemys(int killedEnemy) { this.killedEnemy = killedEnemy; } }
DeDanny/Mario
mario/Stages/ScoreBalk.java
1,018
//Zit in de doLoop zodat altijd de juiste Score aangegeven wordt.
line_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package mario.Stages; import java.awt.Rectangle; import java.awt.Graphics; import java.awt.Color; import java.awt.Font; import java.util.ArrayList; import mario.MarioData; import mario.MarioWorld; import mario.core.Collision; import mario.core.StageObject; import mario.core.interfaces.Static; /** * * @author Mike */ public class ScoreBalk extends StageObject implements Static { private int score; private int newScore; private int killedEnemy; // private String scoreString; private int lives = 3; private int coins; private MarioData marioData; public ScoreBalk(Stage game, MarioWorld marioWorld ,int x, int y, int width, int height) { super(game, x, y, width, height, "/images/nsmbtileset.png"); frames.put("muntje", new Rectangle(457, 167, 45, 48)); frames.put("coin", new Rectangle(1278, 2328, 48, 48)); setAnimation(new String[]{"coin"}); marioData = marioWorld.getMarioData(); } @Override public void doLoopAction() { //Controleerd telkens op nieuwe Score. addScore(); // scoreString = Integer.toString(score); } @Override public void draw(Graphics graphics) { Font font = new Font("Arial", Font.PLAIN, 20); graphics.setFont(font); graphics.setColor(Color.WHITE); graphics.drawString("Score: " + (int)marioData.getPoints(), 10, 30); setAnimation(new String[]{"muntje"}); // graphics.drawImage(getImage(), 50, 5, null); graphics.drawString("Coins: " + coins, 110, 30); //setAnimation(new String[]{"leven"}); // graphics.drawImage(getImage(), 20, 5, null); graphics.drawString("Lives: " + marioData.getLives(), 210, 30); graphics.drawString("Killed enemy's: " + killedEnemy, 310, 30); } //Zit in<SUF> public void addScore() { newScore = (int) (getScore() + (getCoins() * 100) + (killedEnemy * 20)); } public void addScore(int punten) { score += punten; } public int getCoins() { return marioData.getCoins(); } public void setCoins(int coins) { marioData.setCoins(coins); } public int getLives() { return marioData.getLives(); } public void setLives(int lives) { marioData.setLives(lives); } public long getScore() { return marioData.getPoints(); } public void setScore(long score) { marioData.setPoints(score); } public void addCoin() { coins++; } public void killEnemy() { killedEnemy++; } @Override public void doCharacterCollision(ArrayList<Collision> collisions, StageObject mapObject) { } public int getKilledEnemys() { return killedEnemy; } public void setKilledEnemys(int killedEnemy) { this.killedEnemy = killedEnemy; } }