answer
stringlengths
17
10.2M
package org.dellroad.stuff.vaadin; import com.vaadin.data.Container; import com.vaadin.data.Item; import com.vaadin.data.Property; import com.vaadin.data.util.AbstractContainer; import java.util.AbstractList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Set; /** * Support superclass for read-only {@link Container} implementations where each {@link Item} in the container * is backed by a Java object, and the Java objects are generated via {@linkplain #query a query} that returns * an ordered "query list". The container's item ID's are simply the indexes of the corresponding objects * in this list. * * <p> * This class will invoke {@link #query} as needed to (re)generate the query list. The query list is then cached, * but this class always invokes {@link #validate validate()} prior to each subsequent use to ensure the cached * list is still usable. If not, {@link #query} is invoked to regenerate it. * </p> * * <p> * Note that the query list being invalid is an orthogonal concept from the contents of the list having changed. * Invalid means "this list can no longer be used" while changed means "this list contains out-of-date information". * Normally, the latter implies the former (but not vice-versa). The list becoming invalid does not in itself not cause * any notifications to be sent, so no new query will be performed until e.g. the user interface explicitly requests * more information. * </p> * * <p> * Therefore, if the list content changes, first {@link #invalidate} and then {@link #fireItemSetChange} * should be invoked; for convenience, {@link #reload} will perform these two steps for you. On the other hand, * the list can become invalid without the content changing if e.g., the list refers to JPA entities and the * corresponding {@link javax.persistence.EntityManager} has closed. * </p> * * <p> * The subclass may forcibly invalidate the current query list via {@link #invalidate}; this merely sets an internal * flag. In some situations use of {@link #invalidate} is never necessary. * </p> * * <p> * It is also possible for the query list to generate information on-demand, thereby avoiding holding the entire * list in memory at once. * </p> * * @param <T> the type of the Java objects that back each {@link Item} in the container */ @SuppressWarnings("serial") public abstract class AbstractQueryContainer<T> extends AbstractContainer implements Container.Ordered, Container.Indexed, Container.PropertySetChangeNotifier, Container.ItemSetChangeNotifier { private final HashMap<String, PropertyDef<?>> propertyMap = new HashMap<String, PropertyDef<?>>(); private PropertyExtractor<? super T> propertyExtractor; private List<T> currentList; // Constructors protected AbstractQueryContainer(PropertyExtractor<? super T> propertyExtractor) { this.setPropertyExtractor(propertyExtractor); } protected AbstractQueryContainer(PropertyExtractor<? super T> propertyExtractor, Collection<? extends PropertyDef<?>> propertyDefs) { this(propertyExtractor); this.setProperties(propertyDefs); } // Public methods /** * Get the configured {@link PropertyExtractor} for this container. */ public PropertyExtractor<? super T> getPropertyExtractor() { return this.propertyExtractor; } public void setPropertyExtractor(PropertyExtractor<? super T> propertyExtractor) { if (propertyExtractor == null) throw new IllegalArgumentException("null extractor"); this.propertyExtractor = propertyExtractor; } public void setProperties(Collection<? extends PropertyDef<?>> propertyDefs) { if (propertyDefs == null) throw new IllegalArgumentException("null propertyDefs"); this.propertyMap.clear(); for (PropertyDef<?> propertyDef : propertyDefs) { if (this.propertyMap.put(propertyDef.getName(), propertyDef) != null) throw new IllegalArgumentException("duplicate property name `" + propertyDef.getName() + "'"); } this.fireContainerPropertySetChange(); } /** * Reload this container. * * <p> * This invalidates the current list (if any) and fires an item set change event. */ public void reload() { this.invalidate(); this.fireItemSetChange(); } // Subclass hooks and methods /** * Perform a query to generate the list of Java objects that back this container. */ protected abstract List<T> query(); /** * Determine if the given list can still be used or not. If not, {@link #query} will be invoked to refresh it. */ protected abstract boolean validate(List<T> list); /** * Invalidate the current query list, if any. */ protected void invalidate() { this.currentList = null; } // Internal methods /** * Get the Java backing object at the given index in the list. * * @return backing object, or null if {@code index} is out of range */ protected T getJavaObject(int index) { List<T> list = this.getList(); if (index < 0 || index >= list.size()) return null; return list.get(index); } /** * Get the query list, validating it and regenerating if necessary. */ protected List<T> getList() { if (this.currentList == null || !this.validate(this.currentList)) this.currentList = this.query(); return this.currentList; } // Container @Override public SimpleItem<T> getItem(Object itemId) { if (!(itemId instanceof Integer)) return null; int index = ((Integer)itemId).intValue(); T obj = this.getJavaObject(index); if (obj == null) return null; return new SimpleItem<T>(obj, this.propertyMap, this.propertyExtractor); } @Override public Collection<Integer> getItemIds() { return new IntList(this.getList().size()); } @Override public Set<String> getContainerPropertyIds() { return Collections.unmodifiableSet(this.propertyMap.keySet()); } @Override public Property getContainerProperty(Object itemId, Object propertyId) { SimpleItem<T> item = this.getItem(itemId); return item != null ? item.getItemProperty(propertyId) : null; } @Override public Class<?> getType(Object propertyId) { PropertyDef<?> propertyDef = this.propertyMap.get(propertyId); return propertyDef != null ? propertyDef.getType() : null; } @Override public int size() { return this.getList().size(); } @Override public boolean containsId(Object itemId) { if (!(itemId instanceof Integer)) return false; int index = ((Integer)itemId).intValue(); return index >= 0 && index < this.getList().size(); } /** * @throws UnsupportedOperationException always */ @Override public Item addItem(Object itemId) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException always */ @Override public Item addItem() { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException always */ @Override public boolean removeItem(Object itemId) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException always */ @Override public boolean addContainerProperty(Object propertyId, Class<?> type, Object defaultValue) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException always */ @Override public boolean removeContainerProperty(Object propertyId) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException always */ @Override public boolean removeAllItems() { throw new UnsupportedOperationException(); } // Container.Indexed /** * @throws UnsupportedOperationException always */ @Override public Object addItemAt(int index) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException always */ @Override public Item addItemAt(int index, Object newItemId) { throw new UnsupportedOperationException(); } @Override public Integer getIdByIndex(int index) { return index; } @Override public int indexOfId(Object itemId) { if (!(itemId instanceof Integer)) return -1; int index = ((Integer)itemId).intValue(); List<T> list = this.getList(); if (index < 0 || index >= list.size()) return -1; return index; } // Container.Ordered @Override public Integer nextItemId(Object itemId) { if (!(itemId instanceof Integer)) return null; int index = ((Integer)itemId).intValue(); List<T> list = this.getList(); if (index < 0 || index + 1 >= list.size()) return null; return index + 1; } @Override public Integer prevItemId(Object itemId) { if (!(itemId instanceof Integer)) return null; int index = ((Integer)itemId).intValue(); List<T> list = this.getList(); if (index - 1 < 0 || index >= list.size()) return null; return index - 1; } @Override public Integer firstItemId() { return this.getList().isEmpty() ? null : 0; } @Override public Integer lastItemId() { List<T> list = this.getList(); return list.isEmpty() ? null : list.size() - 1; } @Override public boolean isFirstId(Object itemId) { if (!(itemId instanceof Integer)) return false; int index = ((Integer)itemId).intValue(); return !this.getList().isEmpty() && index == 0; } @Override public boolean isLastId(Object itemId) { if (!(itemId instanceof Integer)) return false; int index = ((Integer)itemId).intValue(); return index == this.getList().size() - 1; } /** * @throws UnsupportedOperationException always */ @Override public Item addItemAfter(Object previousItemId) { throw new UnsupportedOperationException(); } /** * @throws UnsupportedOperationException always */ @Override public Item addItemAfter(Object previousItemId, Object newItemId) { throw new UnsupportedOperationException(); } // Container.PropertySetChangeNotifier @Override public void addListener(Container.PropertySetChangeListener listener) { super.addListener(listener); } @Override public void removeListener(Container.PropertySetChangeListener listener) { super.removeListener(listener); } // Container.ItemSetChangeNotifier @Override public void addListener(Container.ItemSetChangeListener listener) { super.addListener(listener); } @Override public void removeListener(Container.ItemSetChangeListener listener) { super.removeListener(listener); } // IntList private static class IntList extends AbstractList<Integer> { private final int max; public IntList(int max) { if (max < 0) throw new IllegalArgumentException("max < 0"); this.max = max; } @Override public int size() { return this.max; } @Override public Integer get(int index) { if (index < 0 || index >= this.max) throw new IndexOutOfBoundsException(); return index; } } }
package picard.analysis; import htsjdk.samtools.*; import htsjdk.samtools.metrics.MetricsFile; import htsjdk.samtools.util.*; import picard.cmdline.CommandLineProgram; import picard.cmdline.CommandLineProgramProperties; import picard.cmdline.Option; import picard.cmdline.StandardOptionDefinitions; import picard.cmdline.programgroups.Metrics; import picard.util.QuerySortedReadPairIteratorUtil; import java.io.File; import java.util.List; /** * Computes a number of metrics that are useful for evaluating coverage and performance of sequencing experiments. * * @author ebanks */ @CommandLineProgramProperties( usage = "Computes a number of metrics that are useful for evaluating coverage and performance of " + "sequencing experiments.", usageShort = "Writes sequencing-related metrics for a SAM or BAM file", programGroup = Metrics.class ) public class CollectWgsMetricsFromQuerySorted extends CommandLineProgram { @Option(shortName = StandardOptionDefinitions.INPUT_SHORT_NAME, doc = "Input SAM or BAM file.") public File INPUT; @Option(shortName = StandardOptionDefinitions.OUTPUT_SHORT_NAME, doc = "Output metrics file.") public File OUTPUT; @Option(shortName = "USABLE_MQ", doc = "Minimum mapping quality for a read to contribute to usable coverage.", overridable = true, optional = true) public int MINIMUM_USABLE_MAPPING_QUALITY = 20; @Option(shortName = "USABLE_Q", doc = "Minimum base quality for a base to contribute to usable coverage.", overridable = true, optional = true) public int MINIMUM_USABLE_BASE_QUALITY = 20; @Option(shortName = "RAW_MQ", doc = "Minimum mapping quality for a read to contribute to raw coverage.", overridable = true, optional = true) public int MINIMUM_RAW_MAPPING_QUALITY = 0; @Option(shortName = "RAW_Q", doc = "Minimum base quality for a base to contribute to raw coverage.", overridable = true, optional = true) public int MINIMUM_RAW_BASE_QUALITY = 3; @Option(doc = "The number of bases in the genome build of the input file to be used for calculating MEAN_COVERAGE. If not provided, we will assume that ALL bases in the genome should be used (including e.g. Ns)", overridable = true, optional = true) public Long GENOME_TERRITORY = null; private final Log log = Log.getInstance(CollectWgsMetricsFromQuerySorted.class); /** the various metrics types */ public enum FILTERING_STRINGENCY { RAW, USABLE } /** Metrics for evaluating the performance of whole genome sequencing experiments. */ public static class QuerySortedSeqMetrics extends CollectWgsMetrics.WgsMetrics { /** Identifier for metrics type */ public FILTERING_STRINGENCY TYPE; /** The total number of bases, before any filters are applied. */ public long TOTAL_BASES = 0; /** The number of passing bases, after all filters are applied. */ public long TOTAL_PASSING_BASES = 0; /** The number of read pairs, before all filters are applied. */ public long TOTAL_READ_PAIRS = 0; /** The number of duplicate read pairs, before all filters are applied. */ public long TOTAL_DUPE_PAIRS = 0; /** The number of read pairs with standard orientations from which to calculate mean insert size, after filters are applied. */ public long TOTAL_ORIENTED_PAIRS = 0; /** The mean insert size, after filters are applied. */ public double MEAN_INSERT_SIZE = 0.0; } /** A private class to track the intermediate values of certain metrics */ private class IntermediateMetrics { final QuerySortedSeqMetrics metrics = new QuerySortedSeqMetrics(); long basesExcludedByDupes = 0; long basesExcludedByMapq = 0; long basesExcludedByPairing = 0; long basesExcludedByBaseq = 0; long basesExcludedByOverlap = 0; double insertSizeSum = 0.0; } public static void main(final String[] args) { new CollectWgsMetricsFromQuerySorted().instanceMainWithExit(args); } @Override protected int doWork() { IOUtil.assertFileIsReadable(INPUT); IOUtil.assertFileIsWritable(OUTPUT); // progress tracker final ProgressLogger progress = new ProgressLogger(log, 50000000, "Processed", "read pairs"); // the SAM reader final SamReader reader = SamReaderFactory.makeDefault().open(INPUT); final PeekableIterator<SAMRecord> iterator = new PeekableIterator<>(reader.iterator()); // the metrics to keep track of final IntermediateMetrics usableMetrics = new IntermediateMetrics(); usableMetrics.metrics.TYPE = FILTERING_STRINGENCY.USABLE; final IntermediateMetrics rawMetrics = new IntermediateMetrics(); rawMetrics.metrics.TYPE = FILTERING_STRINGENCY.RAW; // Loop through all the loci by read pairs QuerySortedReadPairIteratorUtil.ReadPair pairToAnalyze = QuerySortedReadPairIteratorUtil.getNextReadPair(iterator); while (pairToAnalyze != null) { // calculate intermediate metrics calculateMetricsForRead(pairToAnalyze, usableMetrics, MINIMUM_USABLE_MAPPING_QUALITY, MINIMUM_USABLE_BASE_QUALITY); calculateMetricsForRead(pairToAnalyze, rawMetrics, MINIMUM_RAW_MAPPING_QUALITY, MINIMUM_RAW_BASE_QUALITY); // record progress progress.record(pairToAnalyze.read1); // iterate pairToAnalyze = QuerySortedReadPairIteratorUtil.getNextReadPair(iterator); } // finalize and write the metrics final long genomeTerritory = (GENOME_TERRITORY == null || GENOME_TERRITORY < 1L) ? reader.getFileHeader().getSequenceDictionary().getReferenceLength() : GENOME_TERRITORY; usableMetrics.metrics.GENOME_TERRITORY = genomeTerritory; finalizeMetrics(usableMetrics); rawMetrics.metrics.GENOME_TERRITORY = genomeTerritory; finalizeMetrics(rawMetrics); final MetricsFile<QuerySortedSeqMetrics, Integer> out = getMetricsFile(); out.addMetric(usableMetrics.metrics); out.addMetric(rawMetrics.metrics); out.write(OUTPUT); return 0; } /** * Calculate the contribution to the intermediate metrics for a given read pair * * @param pairToAnalyze the read pair to grab metrics from * @param metrics the intermediate metrics with all the data we need * @param minimumMappingQuality the minimum mapping quality * @param minimumBaseQuality the minimum base quality */ private void calculateMetricsForRead(final QuerySortedReadPairIteratorUtil.ReadPair pairToAnalyze, final IntermediateMetrics metrics, final int minimumMappingQuality, final int minimumBaseQuality) { final boolean isPaired = (pairToAnalyze.read2 != null); // how many bases do we have? final int read1bases = pairToAnalyze.read1.getReadLength(); final int read2bases = isPaired ? pairToAnalyze.read2.getReadLength() : 0; final int totalReadBases = read1bases + read2bases; // now compute metrics... metrics.metrics.TOTAL_BASES += totalReadBases; if (isPaired) metrics.metrics.TOTAL_READ_PAIRS++; // Note that CollectWgsMetrics does NOT count paired reads that are both unmapped in the PCT_EXC_UNPAIRED, but we do so here // because this tool isn't a locus iterator and we need to ensure that our passing base numbers are accurate in the end if (!isPaired || pairToAnalyze.read1.getMateUnmappedFlag() || pairToAnalyze.read2.getMateUnmappedFlag()) { metrics.basesExcludedByPairing += totalReadBases; } else if (pairToAnalyze.read1.getDuplicateReadFlag()) { metrics.metrics.TOTAL_DUPE_PAIRS++; metrics.basesExcludedByDupes += totalReadBases; } else { // determine the bad bases from the reads final BaseExclusionHelper read1exclusions = determineBaseExclusions(pairToAnalyze.read1, minimumMappingQuality, minimumBaseQuality); final BaseExclusionHelper read2exclusions = determineBaseExclusions(pairToAnalyze.read2, minimumMappingQuality, minimumBaseQuality); metrics.basesExcludedByMapq += read1exclusions.basesExcludedByMapq + read2exclusions.basesExcludedByMapq; metrics.basesExcludedByBaseq += read1exclusions.lowBQcount + read2exclusions.lowBQcount; // keep track of the total usable bases int usableBaseCount = totalReadBases; usableBaseCount -= (read1exclusions.basesExcludedByMapq + read1exclusions.lowBQcount); usableBaseCount -= (read2exclusions.basesExcludedByMapq + read2exclusions.lowBQcount); // subtract out bad bases from overlaps between the reads, but only if both reads pass mapping quality thresholds if (read1exclusions.basesExcludedByMapq == 0 && read2exclusions.basesExcludedByMapq == 0) { final int overlapCount = getOverlappingBaseCount(read1exclusions, read2exclusions, minimumBaseQuality); metrics.basesExcludedByOverlap += overlapCount; usableBaseCount -= overlapCount; } metrics.metrics.TOTAL_PASSING_BASES += usableBaseCount; final int insertSize = Math.abs(pairToAnalyze.read1.getInferredInsertSize()); if (insertSize > 0 && pairToAnalyze.read1.getProperPairFlag()) { metrics.metrics.TOTAL_ORIENTED_PAIRS++; metrics.insertSizeSum += insertSize; } } } /** * Finalize the metrics by doing some fun but easy math * * @param metrics the intermediate metrics with all the data we need */ private void finalizeMetrics(final IntermediateMetrics metrics) { setUnusedMetrics(metrics.metrics); metrics.metrics.MEAN_COVERAGE = metrics.metrics.TOTAL_PASSING_BASES / (double)metrics.metrics.GENOME_TERRITORY; metrics.metrics.PCT_EXC_DUPE = metrics.basesExcludedByDupes / (double)metrics.metrics.TOTAL_BASES; metrics.metrics.PCT_EXC_MAPQ = metrics.basesExcludedByMapq / (double)metrics.metrics.TOTAL_BASES; metrics.metrics.PCT_EXC_UNPAIRED = metrics.basesExcludedByPairing / (double)metrics.metrics.TOTAL_BASES; metrics.metrics.PCT_EXC_BASEQ = metrics.basesExcludedByBaseq / (double)metrics.metrics.TOTAL_BASES; metrics.metrics.PCT_EXC_OVERLAP = metrics.basesExcludedByOverlap / (double)metrics.metrics.TOTAL_BASES; final double totalExcludedBases = metrics.metrics.TOTAL_BASES - metrics.metrics.TOTAL_PASSING_BASES; metrics.metrics.PCT_EXC_TOTAL = totalExcludedBases / metrics.metrics.TOTAL_BASES; metrics.metrics.MEAN_INSERT_SIZE = metrics.insertSizeSum / metrics.metrics.TOTAL_ORIENTED_PAIRS; } /** * Get the count of low quality and/or softclip bases in the given read * * @param exclusions the helper object * @param minimumBaseQuality the minimum base quality * @return non-negative int */ private int getLowQualityOrSoftclipBaseCount(final BaseExclusionHelper exclusions, final int minimumBaseQuality) { final byte[] quals = exclusions.read.getBaseQualities(); int badCount = exclusions.firstUnclippedBaseIndex + (quals.length - exclusions.firstTrailingClippedBaseIndex); for (int i = exclusions.firstUnclippedBaseIndex; i < exclusions.firstTrailingClippedBaseIndex; i++) { if (quals[i] < minimumBaseQuality) badCount++; } return badCount; } /** * set the values of the unused metrics to -1 * * @param metrics the metrics object */ private void setUnusedMetrics(final QuerySortedSeqMetrics metrics) { metrics.SD_COVERAGE = -1; metrics.MEDIAN_COVERAGE = -1; metrics.MAD_COVERAGE = -1; metrics.PCT_1X = -1; metrics.PCT_5X = -1; metrics.PCT_10X = -1; metrics.PCT_15X = -1; metrics.PCT_20X = -1; metrics.PCT_25X = -1; metrics.PCT_30X = -1; metrics.PCT_40X = -1; metrics.PCT_50X = -1; metrics.PCT_60X = -1; metrics.PCT_70X = -1; metrics.PCT_80X = -1; metrics.PCT_90X = -1; metrics.PCT_100X = -1; metrics.PCT_EXC_CAPPED = -1; } /** * Get the count of overlapping bases for the given reads * * @param read1exclusions the 1st read exclusions * @param read2exclusions the 2nd read exclusions * @param minimumBaseQuality the minimum base quality * @return non-negative int */ private int getOverlappingBaseCount(final BaseExclusionHelper read1exclusions, final BaseExclusionHelper read2exclusions, final int minimumBaseQuality) { // make life easy by ensuring that reads come in coordinate order if ( read2exclusions.read.getAlignmentStart() < read1exclusions.read.getAlignmentStart() ) { return getOverlappingBaseCount(read2exclusions, read1exclusions, minimumBaseQuality); } // must be overlapping if ( read1exclusions.read.getAlignmentEnd() < read2exclusions.read.getAlignmentStart() || !read1exclusions.read.getReferenceIndex().equals(read2exclusions.read.getReferenceIndex()) ) return 0; final byte[] read1quals = read1exclusions.read.getBaseQualities(); final byte[] read2quals = read2exclusions.read.getBaseQualities(); final int indexOfOverlapInFirstRead = read1exclusions.read.getReadPositionAtReferencePosition(read2exclusions.read.getAlignmentStart(), true) - 1; final int maxPossibleOverlap = read1exclusions.firstTrailingClippedBaseIndex - indexOfOverlapInFirstRead; // the overlap cannot actually be larger than the usable bases in read2 final int actualOverlap = Math.min(maxPossibleOverlap, read2exclusions.firstTrailingClippedBaseIndex - read2exclusions.firstUnclippedBaseIndex); int numHighQualityOverlappingBases = 0; for (int i = 0; i < actualOverlap; i++) { // we count back from the end of the aligned bases (i.e. not included soft-clips) in read1 and from the front of read2 final int posInRead1 = read1exclusions.firstTrailingClippedBaseIndex - actualOverlap + i; final int posInRead2 = read2exclusions.firstUnclippedBaseIndex + i; // we only want to count it if they are both high quality (i.e. not already counted among bad bases) if (read1quals[posInRead1] >= minimumBaseQuality && read2quals[posInRead2] >= minimumBaseQuality) { numHighQualityOverlappingBases++; } } return numHighQualityOverlappingBases; } /** * Determine how many bases are excluded because of low mapping or base quality. * * @param read the read * @param minimumMappingQuality the minimum mapping quality * @param minimumBaseQuality the minimum base quality * @return non-null object */ private BaseExclusionHelper determineBaseExclusions(final SAMRecord read, final int minimumMappingQuality, final int minimumBaseQuality) { final BaseExclusionHelper exclusions = new BaseExclusionHelper(read); if (read.getMappingQuality() < minimumMappingQuality) { exclusions.basesExcludedByMapq = read.getReadLength(); } else { exclusions.lowBQcount = getLowQualityOrSoftclipBaseCount(exclusions, minimumBaseQuality); } return exclusions; } private static class BaseExclusionHelper { public SAMRecord read; public int firstUnclippedBaseIndex; public int firstTrailingClippedBaseIndex; public int basesExcludedByMapq = 0; public int lowBQcount = 0; public BaseExclusionHelper(final SAMRecord read) { this.read = read; final List<CigarElement> cigarElements = read.getCigar().getCigarElements(); firstUnclippedBaseIndex = 0; for (final CigarElement element : cigarElements) { final CigarOperator op = element.getOperator(); if (op == CigarOperator.SOFT_CLIP) { firstUnclippedBaseIndex = element.getLength(); } else if (op != CigarOperator.HARD_CLIP) { break; } } firstTrailingClippedBaseIndex = read.getReadLength(); for (int i = cigarElements.size() - 1; i >= 0; --i) { final CigarElement element = cigarElements.get(i); final CigarOperator op = element.getOperator(); if (op == CigarOperator.SOFT_CLIP) { firstTrailingClippedBaseIndex -= element.getLength(); } else if (op != CigarOperator.HARD_CLIP) { break; } } } } }
package net.cloudapp.wcnjenkins; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; public class TestBankAccount { @Test public void testDebitWithSufficientFunds(){ BankAccount account = new BankAccount(10); double amount = account.debit(5); Assert.assertEquals(5.0,amount); } @Test public void testDebitWithInsufficientFunds(){ BankAccount account = new BankAccount(10); double amount = account.debit(11); Assert.assertEquals(-1.0,amount); } @Test public void testDebitWithNegativeFunds(){ BankAccount account = new BankAccount(-10); double amount = account.debit(5); Assert.assertEquals(-5.0,amount); } }
package au.com.aitcollaboration.chessgame.game; import au.com.aitcollaboration.chessgame.board.Board; import au.com.aitcollaboration.chessgame.pieces.Pieces; import au.com.aitcollaboration.chessgame.player.Color; import au.com.aitcollaboration.chessgame.player.ComputerPlayer; import au.com.aitcollaboration.chessgame.player.HumanPlayer; import au.com.aitcollaboration.chessgame.player.Players; import au.com.aitcollaboration.chessgame.support.In; import au.com.aitcollaboration.chessgame.support.UIMessages; import au.com.aitcollaboration.chessgame.support.Utils; import java.util.LinkedList; import java.util.List; public class Game { private Board board; private Rules rules; private Players players; private boolean gameOver; private List<Board> movesHistory; private Game() { gameOver = false; movesHistory = new LinkedList<Board>(); } public Game(Board board, Rules rules, Players players) { this(); this.board = board; this.rules = rules; this.players = players; } public void start() { showGreetings(); playersSetUp(); showBoard(); runGame(); } private void showGreetings() { System.out.println(UIMessages.GREETINGS); } private void showBoard() { System.out.println(board.display()); } public void playersSetUp() { boolean multiPlayers = isMultiPlayers(); Color color = tossCoin(); Color flippedColor = color.flip(); Pieces colorPieces = board.getColoredPieces(color); Pieces flippedColorPieces = board.getColoredPieces(flippedColor); players.add(new HumanPlayer(getTextAnswer(UIMessages.INSERT_PLAYER_NAME), color, colorPieces)); if (multiPlayers) players.add(new HumanPlayer(getTextAnswer(UIMessages.INSERT_PLAYER_NAME), flippedColor, flippedColorPieces)); else players.add(new ComputerPlayer(flippedColor, flippedColorPieces)); } public boolean isMultiPlayers() { return getPlayersNumber() > 1; } private int getPlayersNumber() { while (true) { try { return getNumericAnswer(UIMessages.SELECT_NUMBER_OF_PLAYERS); } catch (NumberFormatException e) { // keep looping } } } public void runGame() { while (!gameOver) { rules.getPossibleMovesOn(board); players.play(); //TODO: remove following line and use the one commented gameOver = true; //gameOver = isGameOver(); } } public boolean isGameOver() { return rules.isMatchDraw(movesHistory) || rules.isCheckMate(board); } public void setGameOver(boolean gameOver) { this.gameOver = gameOver; } private void addMoveToHistory() { movesHistory.add(board); } public Color tossCoin() { String coinSide = getTextAnswer(UIMessages.CHOOSE_COIN_SIDE); boolean coinMatched = Utils.tossCoin(coinSide); return (coinMatched) ? Color.WHITE : Color.BLACK; } public String getTextAnswer(String question) { return In.nextLine(question); } public int getNumericAnswer(String question) throws NumberFormatException { return In.nextInt(question); } }
package cn.kunter.common.generator.make; import java.util.ArrayList; import java.util.List; import cn.kunter.common.generator.config.PackageHolder; import cn.kunter.common.generator.config.PropertyHolder; import cn.kunter.common.generator.entity.Column; import cn.kunter.common.generator.entity.Field; import cn.kunter.common.generator.entity.Method; import cn.kunter.common.generator.entity.Parameter; import cn.kunter.common.generator.entity.Table; import cn.kunter.common.generator.type.FullyQualifiedJavaType; import cn.kunter.common.generator.type.JavaVisibility; import cn.kunter.common.generator.util.DateUtil; import cn.kunter.common.generator.util.FileUtil; import cn.kunter.common.generator.util.JavaBeansUtil; import cn.kunter.common.generator.util.OutputUtilities; /** * * @author yangziran * @version 1.0 20141116 */ public class MakeExample { public static void main(String[] args) throws Exception { List<Table> tables = GetTableConfig.getTableConfig(); for (final Table table : tables) { Thread thread = new Thread(new Runnable() { public void run() { try { MakeExample.makerExample(table); } catch (Exception e) { e.printStackTrace(); } } }); thread.start(); } } /** * * @param table * @throws Exception * @author yangziran */ public static void makerExample(Table table) throws Exception { String entityPackages = PackageHolder.getEntityPackage(table.getTableName()); StringBuilder builder = new StringBuilder(); builder.append(JavaBeansUtil.getPackages(entityPackages)); builder.append(JavaBeansUtil.getImports("java.util.ArrayList", false, true)); builder.append(JavaBeansUtil.getImports("java.util.List", false, false)); boolean BigDecimal = false; boolean Date = false; for (Column column : table.getCols()) { if (column.getJavaType().equals("java.math.BigDecimal")) { BigDecimal = true; } if (column.getJavaType().equals("java.util.Date")) { Date = true; } } if (BigDecimal) { builder.append(JavaBeansUtil.getImports("java.math.BigDecimal", false, false)); } if (Date) { builder.append(JavaBeansUtil.getImports("java.util.Date", false, false)); } OutputUtilities.newLine(builder); builder.append("/**"); OutputUtilities.newLine(builder); builder.append(" * "); builder.append(table.getTableName()); builder.append(""); builder.append(table.getJavaName() + "Example"); OutputUtilities.newLine(builder); builder.append(" * "); builder.append(table.getTableName()); builder.append(""); OutputUtilities.newLine(builder); builder.append(" * @author "); OutputUtilities.newLine(builder); builder.append(" * @version 1.0 " + DateUtil.getSysDate()); OutputUtilities.newLine(builder); builder.append(" */"); builder.append(JavaBeansUtil.getJavaBeansStart(JavaVisibility.PUBLIC.getValue(), false, false, false, false, true, null, null, table.getJavaName() + "Example", table.getRemarks(), true)); for (Column column : table.getExample()) { builder.append(JavaBeansUtil.getJavaBeansField(JavaVisibility.PROTECTED.getValue(), false, false, false, false, column.getJavaName(), column.getJavaType(), column.getRemarks())); } OutputUtilities.newLine(builder); OutputUtilities.newLine(builder); OutputUtilities.javaIndent(builder, 1); builder.append(JavaVisibility.PUBLIC.getValue()).append(table.getJavaName()).append("Example() {"); OutputUtilities.newLine(builder); OutputUtilities.javaIndent(builder, 2); builder.append("oredCriteria = new ArrayList<Criteria>();"); OutputUtilities.newLine(builder); OutputUtilities.javaIndent(builder, 1); builder.append("}"); OutputUtilities.newLine(builder); for (Column column : table.getExample()) { if (column.getJavaName().equals("currentSize")) { List<String> bodyLines = new ArrayList<String>(); bodyLines.add("if (currentPage != null) {"); bodyLines.add("if (currentPage > 0) {"); bodyLines.add("--currentPage;"); bodyLines.add("}"); bodyLines.add("if (currentPage == 0) {"); bodyLines.add("currentSize = 0;"); bodyLines.add("}"); bodyLines.add("else {"); bodyLines.add("currentSize = currentPage * pageSize;"); bodyLines.add("}"); bodyLines.add("}"); bodyLines.add("return currentSize;"); builder.append(JavaBeansUtil.getMethods(1, JavaVisibility.PUBLIC.getValue(), false, false, false, false, false, false, column.getJavaType(), JavaBeansUtil.getGetterMethodName(column.getJavaName()), null, null, bodyLines, " ")); } else { builder.append(JavaBeansUtil.getJavaBeansGetter(JavaVisibility.PUBLIC.getValue(), column.getJavaName(), column.getJavaType(), column.getRemarks())); } builder.append(JavaBeansUtil.getJavaBeansSetter(JavaVisibility.PUBLIC.getValue(), column.getJavaName(), column.getJavaType(), column.getRemarks())); } List<Column> parameters = new ArrayList<Column>(); Column column = new Column(); column.setJavaName("criteria"); column.setJavaType("Criteria"); parameters.add(column); List<String> bodyLines = new ArrayList<String>(); bodyLines.add("oredCriteria.add(criteria);"); builder.append(JavaBeansUtil.getMethods(1, JavaVisibility.PUBLIC.getValue(), false, false, false, false, false, false, null, "or", parameters, null, bodyLines, null)); bodyLines = new ArrayList<String>(); bodyLines.add("Criteria criteria = createCriteriaInternal();"); bodyLines.add("oredCriteria.add(criteria);"); bodyLines.add("return criteria;"); builder.append(JavaBeansUtil.getMethods(1, JavaVisibility.PUBLIC.getValue(), false, false, false, false, false, false, "Criteria", "or", null, null, bodyLines, null)); bodyLines = new ArrayList<String>(); bodyLines.add("Criteria criteria = createCriteriaInternal();"); bodyLines.add("if (oredCriteria.size() == 0) {"); bodyLines.add("oredCriteria.add(criteria);"); bodyLines.add("}"); bodyLines.add("return criteria;"); builder.append(JavaBeansUtil.getMethods(1, JavaVisibility.PUBLIC.getValue(), false, false, false, false, false, false, "Criteria", "createCriteria", null, null, bodyLines, null)); bodyLines = new ArrayList<String>(); bodyLines.add("Criteria criteria = new Criteria();"); bodyLines.add("return criteria;"); builder.append(JavaBeansUtil.getMethods(1, JavaVisibility.PROTECTED.getValue(), false, false, false, false, false, false, "Criteria", "createCriteriaInternal", null, null, bodyLines, null)); bodyLines = new ArrayList<String>(); bodyLines.add("oredCriteria.clear();"); bodyLines.add("orderByClause = null;"); bodyLines.add("distinct = false;"); builder.append(JavaBeansUtil.getMethods(1, JavaVisibility.PUBLIC.getValue(), false, false, false, false, false, false, null, "clear", null, null, bodyLines, null)); OutputUtilities.newLine(builder); OutputUtilities.javaIndent(builder, 1); builder.append(JavaBeansUtil.getJavaBeansStart(JavaVisibility.PROTECTED.getValue(), true, true, false, false, true, null, null, "GeneratedCriteria", null, false)); Field field = new Field(); field.setVisibility(JavaVisibility.PROTECTED); field.setName("criteria"); FullyQualifiedJavaType fqjt = new FullyQualifiedJavaType("java.util.List<Criterion>"); field.setType(fqjt); OutputUtilities.newLine(builder); builder.append(field.getFormattedContent(2)); Method method = new Method(); method.setVisibility(JavaVisibility.PROTECTED); method.setConstructor(true); method.setName("GeneratedCriteria"); method.addBodyLine("super();"); method.addBodyLine("criteria = new ArrayList<Criterion>();"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); fqjt = new FullyQualifiedJavaType("boolean"); method.setReturnType(fqjt); method.setName("isValid"); method.addBodyLine("return criteria.size() > 0;"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); fqjt = new FullyQualifiedJavaType("List<Criterion>"); method.setReturnType(fqjt); method.setName("getAllCriteria"); method.addBodyLine("return criteria;"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); fqjt = new FullyQualifiedJavaType("List<Criterion>"); method.setReturnType(fqjt); method.setName("getCriteria"); method.addBodyLine("return criteria;"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PROTECTED); fqjt = new FullyQualifiedJavaType("String"); Parameter parameter = new Parameter(fqjt, "condition"); method.addParameter(parameter); method.setName("addCriterion"); method.addBodyLine("if (condition == null) {"); method.addBodyLine("throw new RuntimeException(\"Value for condition cannot be null\");"); method.addBodyLine("}"); method.addBodyLine("criteria.add(new Criterion(condition));"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PROTECTED); fqjt = new FullyQualifiedJavaType("String"); parameter = new Parameter(fqjt, "condition"); method.addParameter(parameter); fqjt = new FullyQualifiedJavaType("Object"); parameter = new Parameter(fqjt, "value"); method.addParameter(parameter); fqjt = new FullyQualifiedJavaType("String"); parameter = new Parameter(fqjt, "property"); method.addParameter(parameter); method.setName("addCriterion"); method.addBodyLine("if (value == null) {"); method.addBodyLine("throw new RuntimeException(\"Value for \" + property + \" cannot be null\");"); method.addBodyLine("}"); method.addBodyLine("criteria.add(new Criterion(condition, value));"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PROTECTED); fqjt = new FullyQualifiedJavaType("String"); parameter = new Parameter(fqjt, "condition"); method.addParameter(parameter); fqjt = new FullyQualifiedJavaType("Object"); parameter = new Parameter(fqjt, "value1"); method.addParameter(parameter); fqjt = new FullyQualifiedJavaType("Object"); parameter = new Parameter(fqjt, "value2"); method.addParameter(parameter); fqjt = new FullyQualifiedJavaType("String"); parameter = new Parameter(fqjt, "property"); method.addParameter(parameter); method.setName("addCriterion"); method.addBodyLine("if (value1 == null || value2 == null) {"); method.addBodyLine("throw new RuntimeException(\"Between values for \" + property + \" cannot be null\");"); method.addBodyLine("}"); method.addBodyLine("criteria.add(new Criterion(condition, value1, value2));"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); for (Column cols : table.getCols()) { method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); fqjt = new FullyQualifiedJavaType("Criteria"); method.setReturnType(fqjt); method.setName("and" + cols.getJavaName() + "IsNull"); method.addBodyLine("addCriterion(\"" + table.getAlias() + "." + cols.getColumnName() + " is null\");"); method.addBodyLine("return (Criteria) this;"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); fqjt = new FullyQualifiedJavaType("Criteria"); method.setReturnType(fqjt); method.setName("and" + cols.getJavaName() + "IsNotNull"); method.addBodyLine("addCriterion(\"" + table.getAlias() + "." + cols.getColumnName() + " is not null\");"); method.addBodyLine("return (Criteria) this;"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); fqjt = new FullyQualifiedJavaType("Criteria"); method.setReturnType(fqjt); fqjt = new FullyQualifiedJavaType(cols.getJavaType()); parameter = new Parameter(fqjt, "value"); method.addParameter(parameter); method.setName("and" + cols.getJavaName() + "EqualTo"); method.addBodyLine("addCriterion(\"" + table.getAlias() + "." + cols.getColumnName() + " =\", value, \"" + cols.getJavaName() + "\");"); method.addBodyLine("return (Criteria) this;"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); fqjt = new FullyQualifiedJavaType("Criteria"); method.setReturnType(fqjt); fqjt = new FullyQualifiedJavaType(cols.getJavaType()); parameter = new Parameter(fqjt, "value"); method.addParameter(parameter); method.setName("and" + cols.getJavaName() + "NotEqualTo"); method.addBodyLine("addCriterion(\"" + table.getAlias() + "." + cols.getColumnName() + " <>\", value, \"" + cols.getJavaName() + "\");"); method.addBodyLine("return (Criteria) this;"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); fqjt = new FullyQualifiedJavaType("Criteria"); method.setReturnType(fqjt); fqjt = new FullyQualifiedJavaType(cols.getJavaType()); parameter = new Parameter(fqjt, "value"); method.addParameter(parameter); method.setName("and" + cols.getJavaName() + "GreaterThan"); method.addBodyLine("addCriterion(\"" + table.getAlias() + "." + cols.getColumnName() + " >\", value, \"" + cols.getJavaName() + "\");"); method.addBodyLine("return (Criteria) this;"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); fqjt = new FullyQualifiedJavaType("Criteria"); method.setReturnType(fqjt); fqjt = new FullyQualifiedJavaType(cols.getJavaType()); parameter = new Parameter(fqjt, "value"); method.addParameter(parameter); method.setName("and" + cols.getJavaName() + "GreaterThanOrEqualTo"); method.addBodyLine("addCriterion(\"" + table.getAlias() + "." + cols.getColumnName() + " >=\", value, \"" + cols.getJavaName() + "\");"); method.addBodyLine("return (Criteria) this;"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); fqjt = new FullyQualifiedJavaType("Criteria"); method.setReturnType(fqjt); fqjt = new FullyQualifiedJavaType(cols.getJavaType()); parameter = new Parameter(fqjt, "value"); method.addParameter(parameter); method.setName("and" + cols.getJavaName() + "LessThan"); method.addBodyLine("addCriterion(\"" + table.getAlias() + "." + cols.getColumnName() + " <\", value, \"" + cols.getJavaName() + "\");"); method.addBodyLine("return (Criteria) this;"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); fqjt = new FullyQualifiedJavaType("Criteria"); method.setReturnType(fqjt); fqjt = new FullyQualifiedJavaType(cols.getJavaType()); parameter = new Parameter(fqjt, "value"); method.addParameter(parameter); method.setName("and" + cols.getJavaName() + "LessThanOrEqualTo"); method.addBodyLine("addCriterion(\"" + table.getAlias() + "." + cols.getColumnName() + " <=\", value, \"" + cols.getJavaName() + "\");"); method.addBodyLine("return (Criteria) this;"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); fqjt = new FullyQualifiedJavaType("Criteria"); method.setReturnType(fqjt); fqjt = new FullyQualifiedJavaType("List<" + cols.getJavaType() + ">"); parameter = new Parameter(fqjt, "values"); method.addParameter(parameter); method.setName("and" + cols.getJavaName() + "In"); method.addBodyLine("addCriterion(\"" + table.getAlias() + "." + cols.getColumnName() + " in\", values, \"" + cols.getJavaName() + "\");"); method.addBodyLine("return (Criteria) this;"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); fqjt = new FullyQualifiedJavaType("Criteria"); method.setReturnType(fqjt); fqjt = new FullyQualifiedJavaType("List<" + cols.getJavaType() + ">"); parameter = new Parameter(fqjt, "values"); method.addParameter(parameter); method.setName("and" + cols.getJavaName() + "NotIn"); method.addBodyLine("addCriterion(\"" + table.getAlias() + "." + cols.getColumnName() + " not in\", values, \"" + cols.getJavaName() + "\");"); method.addBodyLine("return (Criteria) this;"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); fqjt = new FullyQualifiedJavaType("Criteria"); method.setReturnType(fqjt); fqjt = new FullyQualifiedJavaType(cols.getJavaType()); parameter = new Parameter(fqjt, "value"); method.addParameter(parameter); method.setName("and" + cols.getJavaName() + "Like"); method.addBodyLine("addCriterion(\"" + table.getAlias() + "." + cols.getColumnName() + " like\", \"%\" + value + \"%\", \"" + cols.getJavaName() + "\");"); method.addBodyLine("return (Criteria) this;"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); fqjt = new FullyQualifiedJavaType("Criteria"); method.setReturnType(fqjt); fqjt = new FullyQualifiedJavaType(cols.getJavaType()); parameter = new Parameter(fqjt, "value"); method.addParameter(parameter); method.setName("and" + cols.getJavaName() + "NotLike"); method.addBodyLine("addCriterion(\"" + table.getAlias() + "." + cols.getColumnName() + " not like\", \"%\" + value + \"%\", \"" + cols.getJavaName() + "\");"); method.addBodyLine("return (Criteria) this;"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); fqjt = new FullyQualifiedJavaType("Criteria"); method.setReturnType(fqjt); fqjt = new FullyQualifiedJavaType("Integer"); parameter = new Parameter(fqjt, "value1"); method.addParameter(parameter); fqjt = new FullyQualifiedJavaType("Integer"); parameter = new Parameter(fqjt, "value2"); method.addParameter(parameter); method.setName("and" + cols.getJavaName() + "Between"); method.addBodyLine("addCriterion(\"" + table.getAlias() + "." + cols.getColumnName() + " between\", value1, value2, \"" + cols.getJavaName() + "\");"); method.addBodyLine("return (Criteria) this;"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); fqjt = new FullyQualifiedJavaType("Criteria"); method.setReturnType(fqjt); fqjt = new FullyQualifiedJavaType("Integer"); parameter = new Parameter(fqjt, "value1"); method.addParameter(parameter); fqjt = new FullyQualifiedJavaType("Integer"); parameter = new Parameter(fqjt, "value2"); method.addParameter(parameter); method.setName("and" + cols.getJavaName() + "NotBetween"); method.addBodyLine("addCriterion(\"" + table.getAlias() + "." + cols.getColumnName() + " not between\", value1, value2, \"" + cols.getJavaName() + "\");"); method.addBodyLine("return (Criteria) this;"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); } OutputUtilities.newLine(builder); OutputUtilities.javaIndent(builder, 1); builder.append(JavaBeansUtil.getJavaBeansEnd(false)); OutputUtilities.newLine(builder, 2); OutputUtilities.javaIndent(builder, 1); builder.append(JavaBeansUtil.getJavaBeansStart(JavaVisibility.PUBLIC.getValue(), false, true, false, false, true, "GeneratedCriteria", null, "Criteria", null, false)); method = new Method(); method.setVisibility(JavaVisibility.PROTECTED); method.setConstructor(true); method.setName("Criteria"); method.addBodyLine("super();"); OutputUtilities.newLine(builder); builder.append(method.getFormattedContent(2, false)); OutputUtilities.newLine(builder); OutputUtilities.javaIndent(builder, 1); builder.append(JavaBeansUtil.getJavaBeansEnd(false)); OutputUtilities.newLine(builder, 2); OutputUtilities.javaIndent(builder, 1); builder.append(JavaBeansUtil.getJavaBeansStart(JavaVisibility.PUBLIC.getValue(), false, true, false, false, true, null, null, "Criterion", null, false)); field = new Field(); field.setVisibility(JavaVisibility.PRIVATE); field.setName("condition"); fqjt = new FullyQualifiedJavaType("String"); field.setType(fqjt); OutputUtilities.newLine(builder); builder.append(field.getFormattedContent(2)); field = new Field(); field.setVisibility(JavaVisibility.PRIVATE); field.setName("value"); fqjt = new FullyQualifiedJavaType("Object"); field.setType(fqjt); OutputUtilities.newLine(builder); builder.append(field.getFormattedContent(2)); field = new Field(); field.setVisibility(JavaVisibility.PRIVATE); field.setName("secondValue"); fqjt = new FullyQualifiedJavaType("Object"); field.setType(fqjt); OutputUtilities.newLine(builder); builder.append(field.getFormattedContent(2)); field = new Field(); field.setVisibility(JavaVisibility.PRIVATE); field.setName("noValue"); fqjt = new FullyQualifiedJavaType("boolean"); field.setType(fqjt); OutputUtilities.newLine(builder); builder.append(field.getFormattedContent(2)); field = new Field(); field.setVisibility(JavaVisibility.PRIVATE); field.setName("singleValue"); fqjt = new FullyQualifiedJavaType("boolean"); field.setType(fqjt); OutputUtilities.newLine(builder); builder.append(field.getFormattedContent(2)); field = new Field(); field.setVisibility(JavaVisibility.PRIVATE); field.setName("betweenValue"); fqjt = new FullyQualifiedJavaType("boolean"); field.setType(fqjt); OutputUtilities.newLine(builder); builder.append(field.getFormattedContent(2)); field = new Field(); field.setVisibility(JavaVisibility.PRIVATE); field.setName("listValue"); fqjt = new FullyQualifiedJavaType("boolean"); field.setType(fqjt); OutputUtilities.newLine(builder); builder.append(field.getFormattedContent(2)); field = new Field(); field.setVisibility(JavaVisibility.PRIVATE); field.setName("typeHandler"); fqjt = new FullyQualifiedJavaType("String"); field.setType(fqjt); OutputUtilities.newLine(builder); builder.append(field.getFormattedContent(2)); method = new Method(); method.setVisibility(JavaVisibility.PROTECTED); method.setConstructor(true); method.setName("Criterion"); method.addBodyLine("super();"); OutputUtilities.newLine(builder); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); fqjt = new FullyQualifiedJavaType("String"); method.setReturnType(fqjt); method.setName("getCondition"); method.addBodyLine("return condition;"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); fqjt = new FullyQualifiedJavaType("Object"); method.setReturnType(fqjt); method.setName("getValue"); method.addBodyLine("return value;"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); fqjt = new FullyQualifiedJavaType("Object"); method.setReturnType(fqjt); method.setName("getSecondValue"); method.addBodyLine("return secondValue;"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); fqjt = new FullyQualifiedJavaType("boolean"); method.setReturnType(fqjt); method.setName("isNoValue"); method.addBodyLine("return noValue;"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); fqjt = new FullyQualifiedJavaType("boolean"); method.setReturnType(fqjt); method.setName("isSingleValue"); method.addBodyLine("return singleValue;"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); fqjt = new FullyQualifiedJavaType("boolean"); method.setReturnType(fqjt); method.setName("isBetweenValue"); method.addBodyLine("return betweenValue;"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); fqjt = new FullyQualifiedJavaType("boolean"); method.setReturnType(fqjt); method.setName("isListValue"); method.addBodyLine("return listValue;"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); fqjt = new FullyQualifiedJavaType("String"); method.setReturnType(fqjt); method.setName("getTypeHandler"); method.addBodyLine("return typeHandler;"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PROTECTED); method.setConstructor(true); fqjt = new FullyQualifiedJavaType("String"); parameter = new Parameter(fqjt, "condition"); method.addParameter(parameter); method.setName("Criterion"); method.addBodyLine("super();"); method.addBodyLine("this.condition = condition;"); method.addBodyLine("this.typeHandler = null;"); method.addBodyLine("this.noValue = true;"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PROTECTED); method.setConstructor(true); fqjt = new FullyQualifiedJavaType("String"); parameter = new Parameter(fqjt, "condition"); method.addParameter(parameter); fqjt = new FullyQualifiedJavaType("Object"); parameter = new Parameter(fqjt, "value"); method.addParameter(parameter); fqjt = new FullyQualifiedJavaType("String"); parameter = new Parameter(fqjt, "typeHandler"); method.addParameter(parameter); method.setName("Criterion"); method.addBodyLine("super();"); method.addBodyLine("this.condition = condition;"); method.addBodyLine("this.value = value;"); method.addBodyLine("this.typeHandler = typeHandler;"); method.addBodyLine("if (value instanceof List<?>) {"); method.addBodyLine("this.listValue = true;"); method.addBodyLine("} else {"); method.addBodyLine("this.singleValue = true;"); method.addBodyLine("}"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PROTECTED); method.setConstructor(true); fqjt = new FullyQualifiedJavaType("String"); parameter = new Parameter(fqjt, "condition"); method.addParameter(parameter); fqjt = new FullyQualifiedJavaType("Object"); parameter = new Parameter(fqjt, "value"); method.addParameter(parameter); method.setName("Criterion"); method.addBodyLine("this(condition, value, null);"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PROTECTED); method.setConstructor(true); fqjt = new FullyQualifiedJavaType("String"); parameter = new Parameter(fqjt, "condition"); method.addParameter(parameter); fqjt = new FullyQualifiedJavaType("Object"); parameter = new Parameter(fqjt, "value"); method.addParameter(parameter); fqjt = new FullyQualifiedJavaType("Object"); parameter = new Parameter(fqjt, "secondValue"); method.addParameter(parameter); fqjt = new FullyQualifiedJavaType("String"); parameter = new Parameter(fqjt, "typeHandler"); method.addParameter(parameter); method.setName("Criterion"); method.addBodyLine("super();"); method.addBodyLine("this.condition = condition;"); method.addBodyLine("this.value = value;"); method.addBodyLine("this.secondValue = secondValue;"); method.addBodyLine("this.typeHandler = typeHandler;"); method.addBodyLine("this.betweenValue = true;"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); method = new Method(); method.setVisibility(JavaVisibility.PROTECTED); method.setConstructor(true); fqjt = new FullyQualifiedJavaType("String"); parameter = new Parameter(fqjt, "condition"); method.addParameter(parameter); fqjt = new FullyQualifiedJavaType("Object"); parameter = new Parameter(fqjt, "value"); method.addParameter(parameter); fqjt = new FullyQualifiedJavaType("Object"); parameter = new Parameter(fqjt, "secondValue"); method.addParameter(parameter); method.setName("Criterion"); method.addBodyLine("this(condition, value, secondValue, null);"); OutputUtilities.newLine(builder, 2); builder.append(method.getFormattedContent(2, false)); OutputUtilities.newLine(builder); OutputUtilities.javaIndent(builder, 1); builder.append(JavaBeansUtil.getJavaBeansEnd(false)); builder.append(JavaBeansUtil.getJavaBeansEnd()); FileUtil.writeFile(PropertyHolder.getConfigProperty("target") + entityPackages.replaceAll("\\.", "/") + "/" + table.getJavaName() + "Example.java", builder.toString()); } }
package com.akiban.ais.model.aisb2; import com.akiban.ais.model.AISBuilder; import com.akiban.ais.model.AkibanInformationSchema; import com.akiban.ais.model.Group; import com.akiban.ais.model.Index; import com.akiban.ais.model.Parameter; import com.akiban.ais.model.Routine; import com.akiban.ais.model.TableName; import com.akiban.ais.model.UserTable; import com.akiban.ais.model.View; import com.akiban.ais.model.validation.AISInvariants; import com.akiban.ais.model.validation.AISValidationResults; import com.akiban.ais.model.validation.AISValidations; import com.akiban.server.error.InvalidSQLJJarURLException; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.NoSuchElementException; import java.util.Properties; public class AISBBasedBuilder { public static NewAISBuilder create() { return new ActualBuilder(); } public static NewAISBuilder create(String defaultSchema) { return new ActualBuilder().defaultSchema(defaultSchema); } private static class ActualBuilder implements NewViewBuilder, NewAkibanJoinBuilder, NewRoutineBuilder, NewSQLJJarBuilder { // NewAISProvider interface @Override public AkibanInformationSchema ais() { return ais(true); } @Override public AkibanInformationSchema ais(boolean freezeAIS) { usable = false; aisb.basicSchemaIsComplete(); aisb.groupingIsComplete(); AISValidationResults results = aisb.akibanInformationSchema().validate(AISValidations.LIVE_AIS_VALIDATIONS); results.throwIfNecessary(); if (freezeAIS) { aisb.akibanInformationSchema().freeze(); } return aisb.akibanInformationSchema(); } @Override public AkibanInformationSchema unvalidatedAIS() { aisb.basicSchemaIsComplete(); aisb.groupingIsComplete(); return aisb.akibanInformationSchema(); } // NewAISBuilder interface @Override public NewAISBuilder defaultSchema(String schema) { this.defaultSchema = schema; return this; } @Override public NewUserTableBuilder userTable(String table) { return userTable(defaultSchema, table); } @Override public NewUserTableBuilder userTable(String schema, String table) { checkUsable(); AISInvariants.checkDuplicateTables(aisb.akibanInformationSchema(), schema, table); this.schema = schema; this.userTable = table; TableName tableName= new TableName (schema, table); aisb.userTable(schema, table); aisb.createGroup(table, schema); aisb.addTableToGroup(tableName, schema, table); tablesToGroups.put(TableName.create(schema, table), tableName); uTableColumnPos = 0; return this; } @Override public NewUserTableBuilder getUserTable() { return this; } @Override public NewUserTableBuilder getUserTable(TableName table) { checkUsable(); this.schema = table.getSchemaName(); this.userTable = table.getTableName(); assert aisb.akibanInformationSchema().getTable(table) != null; uTableColumnPos = aisb.akibanInformationSchema().getTable(table).getColumns().size(); return this; } @Override public NewAISBuilder sequence (String name) { return sequence (name, 1, 1, false); } @Override public NewAISBuilder sequence (String name, long start, long increment, boolean isCycle) { checkUsable(); AISInvariants.checkDuplicateSequence(aisb.akibanInformationSchema(), defaultSchema, name); aisb.sequence(defaultSchema, name, start, increment, Long.MIN_VALUE, Long.MAX_VALUE, isCycle); return this; } @Override public NewUserTableBuilder userTable(TableName tableName) { return userTable(tableName.getSchemaName(), tableName.getTableName()); } @Override public NewViewBuilder view(String view) { return view(defaultSchema, view); } @Override public NewViewBuilder view(String schema, String view) { checkUsable(); AISInvariants.checkDuplicateTables(aisb.akibanInformationSchema(), schema, view); this.schema = schema; this.userTable = view; return this; } @Override public NewViewBuilder view(TableName viewName) { return view(viewName.getSchemaName(), viewName.getTableName()); } @Override public NewRoutineBuilder procedure(String procedure) { return procedure(defaultSchema, procedure); } @Override public NewRoutineBuilder procedure(String schema, String procedure) { checkUsable(); AISInvariants.checkDuplicateRoutine(aisb.akibanInformationSchema(), schema, procedure); this.schema = schema; this.userTable = procedure; return this; } @Override public NewRoutineBuilder procedure(TableName procedureName) { return procedure(procedureName.getSchemaName(), procedureName.getTableName()); } @Override public NewSQLJJarBuilder sqljJar(String jarName) { return sqljJar(defaultSchema, jarName); } @Override public NewSQLJJarBuilder sqljJar(String schema, String jarName) { checkUsable(); AISInvariants.checkDuplicateSQLJJar(aisb.akibanInformationSchema(), schema, jarName); this.schema = schema; this.userTable = jarName; return this; } @Override public NewSQLJJarBuilder sqljJar(TableName name) { return sqljJar(name.getSchemaName(), name.getTableName()); } @Override public NewAISGroupIndexStarter groupIndex(String indexName) { return groupIndex(indexName, null); } @Override public NewAISGroupIndexStarter groupIndex(String indexName, Index.JoinType joinType) { ActualGroupIndexBuilder actual = new ActualGroupIndexBuilder(aisb, defaultSchema); return actual.groupIndex(indexName, joinType); } // NewUserTableBuilder interface @Override public NewUserTableBuilder colLong(String name) { return colLong(name, NULLABLE_DEFAULT, null); } @Override public NewUserTableBuilder colLong(String name, boolean nullable) { return colLong(name, nullable, null); } @Override public NewUserTableBuilder autoIncLong(String name, int initialValue) { return colLong(name, false, initialValue); } private NewUserTableBuilder colLong(String name, boolean nullable, Integer initialAutoInc) { checkUsable(); aisb.column(schema, userTable, name, uTableColumnPos++, "INT", 10L, null, nullable, false, null, null); if (initialAutoInc != null) { String sequenceName = "temp-seq-" + userTable + "-" + name; long initValue = initialAutoInc.longValue(); aisb.sequence(schema, sequenceName, initValue, 1L, initValue, Long.MAX_VALUE, false); aisb.columnAsIdentity(schema, userTable, name, sequenceName, true); aisb.akibanInformationSchema(). getUserTable(schema, userTable). getColumn(name). setInitialAutoIncrementValue(initValue); } return this; } @Override public NewUserTableBuilder colBoolean(String name, boolean nullable) { checkUsable(); aisb.column(schema, userTable, name, uTableColumnPos++, "BOOLEAN", null, null, nullable, false, null, null); return this; } @Override public NewUserTableBuilder colString(String name, int length) { return colString(name, length, NULLABLE_DEFAULT); } @Override public NewUserTableBuilder colString(String name, int length, boolean nullable) { return colString(name, length, nullable, CHARSET_DEFAULT); } @Override public NewUserTableBuilder colString(String name, int length, boolean nullable, String charset) { checkUsable(); aisb.column(schema, userTable, name, uTableColumnPos++, "VARCHAR", (long)length, null, nullable, false, charset, null); return this; } @Override public NewUserTableBuilder colDouble(String name) { return colDouble(name, NULLABLE_DEFAULT); } @Override public NewUserTableBuilder colDouble(String name, boolean nullable) { checkUsable(); aisb.column(schema, userTable, name, uTableColumnPos++, "DOUBLE", null, null, nullable, false, null, null); return this; } @Override public NewUserTableBuilder colTimestamp(String name) { return colTimestamp(name, NULLABLE_DEFAULT); } @Override public NewUserTableBuilder colTimestamp(String name, boolean nullable) { aisb.column(schema, userTable, name, uTableColumnPos++, "TIMESTAMP", null, null, nullable, false, null, null); return this; } @Override public NewUserTableBuilder colBigInt(String name) { return colBigInt(name, NULLABLE_DEFAULT); } @Override public NewUserTableBuilder colBigInt(String name, boolean nullable) { aisb.column(schema, userTable, name, uTableColumnPos++, "BIGINT", null, null, nullable, false, null, null); return this; } @Override public NewUserTableBuilder colVarBinary(String name, int length) { return colVarBinary(name, length, NULLABLE_DEFAULT); } @Override public NewUserTableBuilder colVarBinary(String name, int length, boolean nullable) { aisb.column(schema, userTable, name, uTableColumnPos++, "VARBINARY", (long)length, null, nullable, false, null, null); return this; } @Override public NewUserTableBuilder colText(String name) { return colText(name, NULLABLE_DEFAULT); } @Override public NewUserTableBuilder colText(String name, boolean nullable) { aisb.column(schema, userTable, name, uTableColumnPos++, "TEXT", null, null, nullable, false, null, null); return this; } @Override public NewUserTableBuilder colDateTime (String name) { return colDateTime(name, NULLABLE_DEFAULT); } @Override public NewUserTableBuilder colDateTime (String name, boolean nullable) { aisb.column(schema, userTable, name, uTableColumnPos++, "DATETIME", null, null, nullable, false, null, null); return this; } @Override public NewUserTableBuilder pk(String... columns) { return key(PRIMARY, columns, true, Index.PRIMARY_KEY_CONSTRAINT); } @Override public NewUserTableBuilder uniqueKey(String indexName, String... columns) { return key(indexName, columns, true, Index.UNIQUE_KEY_CONSTRAINT); } @Override public NewUserTableBuilder key(String indexName, String... columns) { return key(indexName, columns, false, Index.KEY_CONSTRAINT); } private NewUserTableBuilder key(String indexName, String[] columns, boolean unique, String constraint) { checkUsable(); aisb.index(schema, userTable, indexName, unique, constraint); for (int i=0; i < columns.length; ++i) { aisb.indexColumn(schema, userTable, indexName, columns[i], i, true, null); } return this; } @Override public NewAkibanJoinBuilder joinTo(String table) { return joinTo(schema, table); } @Override public NewAkibanJoinBuilder joinTo(TableName name) { return joinTo(name.getSchemaName(), name.getTableName()); } @Override public NewAkibanJoinBuilder joinTo(String schema, String table) { String generated = "autogenerated_"+userTable+"_references_" + table; return joinTo(schema, table, generated); } @Override public NewAkibanJoinBuilder joinTo(String schema, String table, String fkName) { checkUsable(); this.fkIndexName = "__akiban_" + fkName; this.fkJoinName = "join_" + fkIndexName; this.fkIndexPos = 0; this.referencesSchema = schema; this.referencesTable = table; Group oldGroup = aisb.akibanInformationSchema().getUserTable(this.schema, this.userTable).getGroup(); aisb.index(this.schema, this.userTable, fkIndexName, false, Index.FOREIGN_KEY_CONSTRAINT); aisb.joinTables(fkJoinName, schema, table, this.schema, this.userTable); TableName fkGroupName = tablesToGroups.get(TableName.create(referencesSchema, referencesTable)); aisb.moveTreeToGroup(this.schema, this.userTable, fkGroupName, fkJoinName); aisb.akibanInformationSchema().removeGroup(oldGroup); TableName oldGroupName = tablesToGroups.put(TableName.create(this.schema, this.userTable), fkGroupName); assert oldGroup.getName().equals(oldGroupName) : oldGroup.getName() + " != " + oldGroupName; return this; } // NewAkibanJoinBuilder @Override public NewAkibanJoinBuilder on(String childColumn, String parentColumn) { checkUsable(); aisb.indexColumn(schema, userTable, fkIndexName, childColumn, fkIndexPos, true, null); aisb.joinColumns(fkJoinName, referencesSchema, referencesTable, parentColumn, schema, userTable, childColumn); return this; } @Override public NewAkibanJoinBuilder and(String childColumn, String parentColumn) { return on(childColumn, parentColumn); } // NewViewBuilder @Override public NewViewBuilder definition(String definition) { Properties properties = new Properties(); properties.put("database", schema); return definition(definition, properties); } @Override public NewViewBuilder definition(String definition, Properties properties) { aisb.view(schema, userTable, definition, properties, new HashMap<TableName,Collection<String>>()); return this; } @Override public NewViewBuilder references(String table) { return references(schema, table); } @Override public NewViewBuilder references(String schema, String table, String... columns) { checkUsable(); View view = aisb.akibanInformationSchema().getView(this.schema, this.userTable); TableName tableName = TableName.create(schema, table); Collection<String> entry = view.getTableColumnReferences().get(tableName); if (entry == null) { entry = new HashSet<>(); view.getTableColumnReferences().put(tableName, entry); } for (String colname : columns) { entry.add(colname); } return this; } // NewRoutineBuilder @Override public NewRoutineBuilder language(String language, Routine.CallingConvention callingConvention) { aisb.routine(schema, userTable, language, callingConvention); return this; } @Override public NewRoutineBuilder paramLongIn(String name) { aisb.parameter(schema, userTable, name, Parameter.Direction.IN, "BIGINT", null, null); return this; } @Override public NewRoutineBuilder paramStringIn(String name, int length) { aisb.parameter(schema, userTable, name, Parameter.Direction.IN, "VARCHAR", (long)length, null); return this; } @Override public NewRoutineBuilder paramDoubleIn(String name) { aisb.parameter(schema, userTable, name, Parameter.Direction.IN, "DOUBLE", null, null); return this; } @Override public NewRoutineBuilder paramLongOut(String name) { aisb.parameter(schema, userTable, name, Parameter.Direction.OUT, "BIGINT", null, null); return this; } @Override public NewRoutineBuilder paramStringOut(String name, int length) { aisb.parameter(schema, userTable, name, Parameter.Direction.OUT, "VARCHAR", (long)length, null); return this; } @Override public NewRoutineBuilder paramDoubleOut(String name) { aisb.parameter(schema, userTable, name, Parameter.Direction.OUT, "DOUBLE", null, null); return this; } @Override public NewRoutineBuilder externalName(String className) { return externalName(className, null); } @Override public NewRoutineBuilder externalName(String className, String methodName) { return externalName(null, className, methodName); } @Override public NewRoutineBuilder externalName(String jarName, String className, String methodName) { return externalName(defaultSchema, jarName, className, methodName); } @Override public NewRoutineBuilder externalName(String jarSchema, String jarName, String className, String methodName) { aisb.routineExternalName(schema, userTable, jarSchema, jarName, className, methodName); return this; } @Override public NewRoutineBuilder procDef(String definition) { aisb.routineDefinition(schema, userTable, definition); return this; } @Override public NewRoutineBuilder sqlAllowed(Routine.SQLAllowed sqlAllowed) { aisb.routineSQLAllowed(schema, userTable, sqlAllowed); return this; } @Override public NewRoutineBuilder dynamicResultSets(int dynamicResultSets) { aisb.routineDynamicResultSets(schema, userTable, dynamicResultSets); return this; } @Override public NewRoutineBuilder deterministic(boolean deterministic) { aisb.routineDeterministic(schema, userTable, deterministic); return this; } @Override public NewRoutineBuilder calledOnNullInput(boolean calledOnNullInput) { aisb.routineCalledOnNullInput(schema, userTable, calledOnNullInput); return this; } // NewSQLJJarBuilder @Override public NewSQLJJarBuilder url(String value, boolean checkReadable) { URL url; try { url = new URL(value); } catch (MalformedURLException ex1) { File file = new File(value); try { url = file.toURI().toURL(); } catch (MalformedURLException ex2) { // Report original failure. throw new InvalidSQLJJarURLException(schema, userTable, ex1); } if (checkReadable && file.canRead()) checkReadable = false; // Can tell quickly. } if (checkReadable) { InputStream istr = null; try { istr = url.openStream(); // Must be able to load it. } catch (IOException ex) { throw new InvalidSQLJJarURLException(schema, userTable, ex); } finally { if (istr != null) { try { istr.close(); } catch (IOException ex) { } } } } aisb.sqljJar(schema, userTable, url); return this; } // ActualBuilder interface public ActualBuilder() { aisb = new AISBuilder(); usable = true; tablesToGroups = new HashMap<>(); } // private private void checkUsable() { if (!usable) { throw new IllegalStateException("AIS has already been retrieved; can't reuse"); } } // object state private final AISBuilder aisb; private String defaultSchema; private String schema; private String userTable; private int uTableColumnPos; private String fkIndexName; private String fkJoinName; private int fkIndexPos; private String referencesSchema; private String referencesTable; private boolean usable; private final Map<TableName,TableName> tablesToGroups; // constants private static final boolean NULLABLE_DEFAULT = false; private static final String CHARSET_DEFAULT = "UTF-8"; private static final String PRIMARY = "PRIMARY"; } private static class ActualGroupIndexBuilder implements NewAISGroupIndexStarter, NewAISGroupIndexBuilder { // NewAISProvider interface @Override public AkibanInformationSchema ais(boolean freezeAIS) { return ais(); } @Override public AkibanInformationSchema ais() { if (unstartedIndex()) { throw new IllegalStateException("a groupIndex was started but not given any columns: " + indexName); } return aisb.akibanInformationSchema(); } @Override public AkibanInformationSchema unvalidatedAIS() { return aisb.akibanInformationSchema(); } // NewAISGroupIndexBuilder interface @Override public NewAISGroupIndexStarter groupIndex(String indexName) { return groupIndex(indexName, null); } @Override public NewAISGroupIndexStarter groupIndex(String indexName, Index.JoinType joinType) { this.indexName = indexName; this.groupName = null; this.position = -1; this.joinType = joinType; return this; } @Override public NewAISGroupIndexBuilder on(String table, String column) { return on(defaultSchema, table, column); } @Override public NewAISGroupIndexBuilder on(String schema, String table, String column) { UserTable userTable = aisb.akibanInformationSchema().getUserTable(schema, table); if (userTable == null) { throw new NoSuchElementException("no table " + schema + '.' + table); } if (userTable.getGroup() == null) { throw new IllegalStateException("ungrouped table: " + schema + '.' + table); } TableName localGroupName = userTable.getGroup().getName(); if (localGroupName == null) { throw new IllegalStateException("unnamed group for " + schema + '.' + table); } this.groupName = localGroupName; this.position = 0; aisb.groupIndex(this.groupName, this.indexName, false, joinType); return and(schema, table, column); } @Override public NewAISGroupIndexBuilder and(String table, String column) { return and(defaultSchema, table, column); } @Override public NewAISGroupIndexBuilder and(String schema, String table, String column) { if (unstartedIndex()) { throw new IllegalStateException("never called on(table,column) for " + indexName); } aisb.groupIndexColumn(groupName, indexName, schema, table, column, position++); return this; } // ActualFinisher interface public ActualGroupIndexBuilder(AISBuilder aisb, String defaultSchema) { this.aisb = aisb; this.defaultSchema = defaultSchema; } // private methods private boolean unstartedIndex() { // indexName is assigned as soon as groupIndex is invoked, but groupName is only resolved // by on. boolean hasUnstarted = (indexName != null) && (groupName == null); assert hasUnstarted == (position < 0) : String.format("%s but %d", hasUnstarted, position); return hasUnstarted; } // object states private final AISBuilder aisb; private final String defaultSchema; private int position; private Index.JoinType joinType; private String indexName; private TableName groupName; } }
package com.app.challenge.event.dao; import java.io.ByteArrayInputStream; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import org.springframework.jdbc.support.rowset.SqlRowSet; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.app.challenge.constants.ChallengeConstants; import com.app.challenge.domain.Player; import com.app.challenge.domain.UserAccount; import com.app.challenge.domain.UserToken; import com.app.challenge.event.vo.ChallengeVO; import com.app.challenge.event.vo.CommentVO; import com.app.challenge.event.vo.RegisterResponseVO; import com.app.challenge.fbutil.Base64; @Transactional(rollbackFor = SQLException.class) @Repository("eventManagerDao") public class EventManagerDao { @Autowired private NamedParameterJdbcTemplate namedParameterJdbcTemplate; @Transactional(rollbackFor = DataAccessException.class) public void createEvent(long challengeId) { HashMap<String, Object> params = new HashMap<String, Object>(); params.put("challengeId", challengeId); String challengeSql = "select * from challenges where challengeid=" + challengeId; Map<String, Object> queryForMap = namedParameterJdbcTemplate.queryForMap(challengeSql, params); Long creatorUid = ((Integer) queryForMap.get("creatoruid")).longValue(); String duration = ((String) queryForMap.get("duration")); params.put("creatorId", creatorUid); params.put("createdDate", new Date()); params.put("expiryindays", duration); SqlParameterSource paramMap = new MapSqlParameterSource(params); String sql = "insert into rivals.scheduler(challengeid,creatoruid,createddate,expiryindays) values(:challengeId,:creatorId,:createdDate,:expiryindays)"; try { namedParameterJdbcTemplate.update(sql, paramMap); } catch (DataAccessException e) { e.printStackTrace(); throw e; } } public boolean userExists(String emailId) { HashMap<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put(ChallengeConstants.DB_EMAIL, emailId); String sql = "SELECT EXISTS(select * from rivals.user_account where useremail=:EMAIL)"; Boolean exists = false; try { exists = namedParameterJdbcTemplate.queryForObject(sql, paramMap, Boolean.class); } catch (DataAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } return exists; } public UserToken checkUserExists(String emailId) { HashMap<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put(ChallengeConstants.DB_EMAIL, emailId); UserToken userToken = namedParameterJdbcTemplate.queryForObject("", paramMap, UserToken.class); return userToken; } @Transactional(rollbackFor = SQLException.class) public String createNewUserId(String userEmail, String token) throws SQLException { HashMap<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put(ChallengeConstants.DB_EMAIL, userEmail); paramMap.put(ChallengeConstants.DB_TOKEN, token); paramMap.put(ChallengeConstants.DB_DATE, new Date()); String sql = "insert into rivals.user_tokens(fbtoken,createddate,useremail) values(:TOKEN,:DATE,:EMAIL)"; try { namedParameterJdbcTemplate.update(sql, paramMap); } catch (DataAccessException e) { throw new SQLException(); } catch (Exception e) { throw new SQLException(); } return "Success"; } @Transactional(rollbackFor = SQLException.class) public String updateUserToken(Long uid, String userEmail, String token, String userName) throws SQLException { HashMap<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put(ChallengeConstants.DB_EMAIL, userEmail); paramMap.put(ChallengeConstants.DB_TOKEN, token); paramMap.put(ChallengeConstants.DB_DATE, new Date()); paramMap.put("uid", uid); paramMap.put("username", userName); String sql = "update rivals.user_tokens set fbtoken=:TOKEN,lastupdateddate=:DATE,useremail=:EMAIL where uid=:uid"; String sqlUsername = "update rivals.user_account set username=:username where id=:uid"; try { namedParameterJdbcTemplate.update(sql, paramMap); namedParameterJdbcTemplate.update(sqlUsername, paramMap); } catch (DataAccessException e) { e.printStackTrace(); throw new SQLException(); } catch (Exception e) { e.printStackTrace(); throw new SQLException(); } return "Success"; } @Transactional(rollbackFor = SQLException.class) public RegisterResponseVO registerDevice(UserAccount userAccount) throws SQLException { RegisterResponseVO response = new RegisterResponseVO(); byte[] bytes = Base64.decode(userAccount.getUserImage(), 0);// userAccount.getUserImage().getBytes(); ByteArrayInputStream baos = new ByteArrayInputStream(bytes); HashMap<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put(ChallengeConstants.DB_DEVICE_ID, userAccount.getDeviceId()); paramMap.put(ChallengeConstants.DB_DEVICE_TYPE, userAccount.getDeviceType()); paramMap.put(ChallengeConstants.DB_PLAYER_IMAGE, baos); paramMap.put(ChallengeConstants.DB_USERNAME, userAccount.getUserName()); paramMap.put(ChallengeConstants.DB_EMAIL, userAccount.getUserEmail()); paramMap.put(ChallengeConstants.DB_CREATED_DATE, new Date()); paramMap.put(ChallengeConstants.DB_TOKEN, userAccount.getUserToken().getFcbkToken()); paramMap.put(ChallengeConstants.DB_DATE, new Date()); paramMap.put(ChallengeConstants.DB_STATUS, userAccount.getStatus()); KeyHolder keyHolder = new GeneratedKeyHolder(); String sql = "SELECT EXISTS(select * from rivals.user_account where useremail=:EMAIL)"; Boolean userExists = false; try { userExists = namedParameterJdbcTemplate.queryForObject(sql, paramMap, Boolean.class); } catch (Exception e) { e.printStackTrace(); } if (userExists.booleanValue()) { // update block try { sql = "update rivals.user_account set deviceid=:DEVICEID, devicetype=:DEVICETYPE, userimage=:PLAYERIMAGE,lastupdateddate=:DATE"; namedParameterJdbcTemplate.update(sql, paramMap); sql = "select id from rivals.user_account where useremail=:EMAIL"; Long userId = namedParameterJdbcTemplate.queryForObject(sql, paramMap, Long.class); paramMap.put("USER_ID", userId); sql = "update rivals.user_tokens set fbtoken=:TOKEN, lastupdateddate=:DATE where uid=:USER_ID"; namedParameterJdbcTemplate.update(sql, paramMap); String gatherDataSql = "select * from rivals.user_account where id=:USER_ID"; Map<String, Object> queryForMap = namedParameterJdbcTemplate.queryForMap(gatherDataSql, paramMap); String username = (String) queryForMap.get("username"); Long totalChallenges = (Long) ((Integer) queryForMap.get("totalchallenges")).longValue(); Long totalwins = (Long) ((Integer) queryForMap.get("totalwins")).longValue(); Long totalLoseCount = totalChallenges.longValue() - totalwins.longValue(); response.setTotalLooseCount(totalLoseCount); response.setTotalWinCount(totalwins); response.setUserId(userId); response.setUserName(username); return response; } catch (Exception e) { e.printStackTrace(); throw new SQLException(); } } else { sql = "insert into rivals.user_account(deviceid,devicetype,userimage,username,useremail,createddate,status,totalchallenges,totalwins) values(:DEVICEID,:DEVICETYPE,:PLAYERIMAGE,:USERNAME,:EMAIL,:CREATED_DATE,:STATUS,0,0)"; try { SqlParameterSource paramSource = new MapSqlParameterSource(paramMap); namedParameterJdbcTemplate.update(sql, paramSource, keyHolder); Map<String, Object> keys = keyHolder.getKeys(); Long id = (Long) keys.get("GENERATED_KEY"); paramMap.put(ChallengeConstants.DB_UID, id); sql = "insert into rivals.user_tokens(uid,fbtoken,createddate,useremail) values(:UID,:TOKEN,:DATE,:EMAIL)"; namedParameterJdbcTemplate.update(sql, paramMap); String gatherDataSql = "select * from rivals.user_account where id=:UID"; Map<String, Object> queryForMap = namedParameterJdbcTemplate.queryForMap(gatherDataSql, paramMap); String username = (String) queryForMap.get("username"); Long totalChallenges = ((Integer) queryForMap.get("totalchallenges")).longValue(); Long totalwins = ((Integer) queryForMap.get("totalwins")).longValue(); Long totalLoseCount = totalChallenges.longValue() - totalwins.longValue(); response.setTotalLooseCount(totalLoseCount); response.setTotalWinCount(totalwins); response.setUserId(id); response.setUserName(username); return response; } catch (DataAccessException e) { e.printStackTrace(); throw new SQLException(); } catch (Exception e) { e.printStackTrace(); throw new SQLException(); } } } @Transactional(rollbackFor = SQLException.class) public long createNewChallenge(ChallengeVO challengeVO, String fbChallengeID, boolean isAcceptor) throws SQLException { HashMap<String, Object> paramMap = new HashMap<String, Object>(); byte[] bytes = Base64.decode(challengeVO.getPlayerImage(), 0); paramMap.put(ChallengeConstants.DB_CREATOR_UID, challengeVO.getUserID()); /* * if (!isAcceptor) paramMap.put(ChallengeConstants.DB_ACCEPTOR_UID, * null); */ if (!challengeVO.isOpenChallenge()) { paramMap.put(ChallengeConstants.DB_ACCEPTOR_MAIL_ID, challengeVO.getAcceptorEmailId()); } paramMap.put(ChallengeConstants.DB_FB_CHALLENGE_ID, fbChallengeID); paramMap.put(ChallengeConstants.DB_START_TIME, new Date()); paramMap.put(ChallengeConstants.DB_STATUS, challengeVO.getChallengeType()); paramMap.put(ChallengeConstants.DB_CREATED_DATE, new Date()); paramMap.put(ChallengeConstants.DB_CHALLENGE_TYPE, challengeVO.getChallengeType()); paramMap.put(ChallengeConstants.DB_END_TIME, new Date()); paramMap.put(ChallengeConstants.DB_DURATION, challengeVO.getDuration()); paramMap.put(ChallengeConstants.DB_TOPIC, challengeVO.getTopic()); paramMap.put(ChallengeConstants.DB_GAME_TYPE, challengeVO.getGameType()); paramMap.put(ChallengeConstants.DB_CREATOR_UNAME, challengeVO.getCreatorName()); String sql = null; if (!challengeVO.isOpenChallenge()) sql = "INSERT INTO rivals.challenges(creatoruid,fbchallengeid,starttime,wstatus,createddate,topic,challengetype,endtime,duration,gametype,acceptorfbmailid,creatorname) VALUES(:CREATORUID,:FBCHALLENGEID,:STARTTIME,:STATUS,:CREATED_DATE,:TOPIC,:CHALLENGETYPE,:ENDTIME,:DURATION,:GAMETYPE,:ACCEPTORMAILID,:CREATOR_NAME)"; else sql = "INSERT INTO rivals.challenges(creatoruid,fbchallengeid,starttime,wstatus,createddate,topic,challengetype,endtime,duration,gametype,creatorname) VALUES(:CREATORUID,:FBCHALLENGEID,:STARTTIME,:STATUS,:CREATED_DATE,:TOPIC,:CHALLENGETYPE,:ENDTIME,:DURATION,:GAMETYPE,:CREATOR_NAME)"; KeyHolder keyHolder = new GeneratedKeyHolder(); long challengeID = 0L; try { SqlParameterSource paramSource = new MapSqlParameterSource(paramMap); namedParameterJdbcTemplate.update(sql, paramSource, keyHolder); Map<String, Object> keys = keyHolder.getKeys(); challengeID = (Long) keys.get("GENERATED_KEY"); paramMap.put(ChallengeConstants.DB_CHALLENGE_ID, challengeID); paramMap.put(ChallengeConstants.DB_UID, challengeVO.getUserID()); paramMap.put(ChallengeConstants.DB_WIN_STATUS, "blank"); paramMap.put(ChallengeConstants.DB_FB_LIKES, 0); paramMap.put(ChallengeConstants.DB_PLAYERS_IMAGE, bytes); paramMap.put(ChallengeConstants.DB_PLAYER_NAME, challengeVO.getPlayerName()); paramMap.put(ChallengeConstants.DB_PLAYER_TYPE, challengeVO.getPlayerType()); StringBuffer insideQuery = new StringBuffer(); StringBuffer afterQuery = new StringBuffer(); StringBuffer sb = new StringBuffer(); sb.append( "INSERT INTO rivals.player_challenge_mapping(challengeID,uid,winstatus,fblikes,player_image,playertype,player_name"); String[] playerInfoAr = challengeVO.getPlayerInfo(); if (playerInfoAr != null) { for (int i = 0; i < playerInfoAr.length; i++) { insideQuery.append(",playerinfo" + (i + 1)); afterQuery.append(", :playerinfo" + (i + 1)); paramMap.put("playerinfo" + (i + 1), playerInfoAr[i]); } } sb.append(insideQuery); sb.append(") VALUES(:CHALLENGEID,:UID,:WINSTATUS,:FBLIKES,:PLAYER_IMAGE,:PLAYERTYPE,:PLAYER_NAME"); sb.append(afterQuery); sb.append(")"); sql = sb.toString(); namedParameterJdbcTemplate.update(sql, paramMap); } catch (DataAccessException e) { throw new SQLException(); } catch (Exception e) { throw new SQLException(); } return challengeID; } @Transactional(rollbackFor = SQLException.class) public long updateAcceptedChallenge(ChallengeVO challengeVO, String fbChallengeID, boolean isAcceptor, Date endTime) throws SQLException { HashMap<String, Object> paramMap = new HashMap<String, Object>(); byte[] bytes = Base64.decode(challengeVO.getPlayerImage(), 0); paramMap.put(ChallengeConstants.DB_ACCEPTOR_UID, challengeVO.getUserID()); paramMap.put(ChallengeConstants.DB_FB_CHALLENGE_ID, fbChallengeID); paramMap.put(ChallengeConstants.DB_START_TIME, new Date()); paramMap.put(ChallengeConstants.DB_STATUS, "INPROGRESS"); paramMap.put(ChallengeConstants.DB_CREATED_DATE, new Date()); paramMap.put(ChallengeConstants.DB_END_TIME, endTime); paramMap.put(ChallengeConstants.DB_CHALLENGE_ID, challengeVO.getChallengeId()); paramMap.put(ChallengeConstants.DB_ACCEPTORNAME, challengeVO.getAcceptorName()); String sql = "UPDATE rivals.challenges set acceptoruid = :ACCEPTORUID, fbchallengeAcceptorID = :FBCHALLENGEID, starttime = :STARTTIME, wstatus = :STATUS, ENDTIME = :ENDTIME, acceptorname=:ACCEPTOR_NAME WHERE challengeid = :CHALLENGEID"; try { SqlParameterSource paramSource = new MapSqlParameterSource(paramMap); namedParameterJdbcTemplate.update(sql, paramSource); paramMap.put(ChallengeConstants.DB_CHALLENGE_ID, challengeVO.getChallengeId()); paramMap.put(ChallengeConstants.DB_UID, challengeVO.getUserID()); paramMap.put(ChallengeConstants.DB_WIN_STATUS, null); paramMap.put(ChallengeConstants.DB_FB_LIKES, 0); paramMap.put(ChallengeConstants.DB_PLAYERS_IMAGE, bytes); paramMap.put(ChallengeConstants.DB_PLAYER_NAME, challengeVO.getPlayerName()); paramMap.put(ChallengeConstants.DB_PLAYER_TYPE, challengeVO.getPlayerType()); StringBuffer insideQuery = new StringBuffer(); StringBuffer afterQuery = new StringBuffer(); StringBuffer sb = new StringBuffer(); sb.append( "INSERT INTO rivals.player_challenge_mapping(challengeID,uid,winstatus,fblikes,player_image,playertype,player_name"); String[] playerInfoAr = challengeVO.getPlayerInfo(); if (playerInfoAr != null) { for (int i = 0; i < playerInfoAr.length; i++) { insideQuery.append(",playerinfo" + (i + 1)); afterQuery.append(", :playerinfo" + (i + 1)); paramMap.put("playerinfo" + (i + 1), playerInfoAr[i]); } } sb.append(insideQuery); sb.append(") VALUES(:CHALLENGEID,:UID,:WINSTATUS,:FBLIKES,:PLAYER_IMAGE,:PLAYERTYPE,:PLAYER_NAME"); sb.append(afterQuery); sb.append(")"); sql = sb.toString(); namedParameterJdbcTemplate.update(sql, paramMap); } catch (DataAccessException e) { throw new SQLException(); } catch (Exception e) { throw new SQLException(); } return 0; } /* * public void updateSchedullerTables(String duration,long challengeid){ * namedParameterJdbcTemplate.queryForObject(sql, paramMap, Integer.class); * } */ public List<ChallengeDomain> fetchAllChallenges(long challengeID, String status) throws SQLException { return fetchAllChallenges(challengeID, status, false); } public List<ChallengeDomain> fetchAllChallenges(long challengeID, String status, boolean fetchall) throws SQLException { List<ChallengeDomain> rows = new ArrayList<>(); String sql = null; if (fetchall) { sql = "select * from rivals.challenges"; } else { if (challengeID == 0) sql = "select * from rivals.challenges where wstatus='OPEN' OR wstatus='FRIEND' OR wstatus = 'INPROGRESS' ORDER BY challengeid DESC LIMIT 20"; else sql = "select * from rivals.challenges where wstatus='OPEN' OR wstatus='FRIEND' OR wstatus = 'INPROGRESS' AND challengeid < " + challengeID + " ORDER BY challengeid DESC LIMIT 20"; } try { rows = namedParameterJdbcTemplate.query(sql, new ChallengeRowMapper()); } catch (DataAccessException e) { e.printStackTrace(); throw new SQLException(); } catch (Exception e) { e.printStackTrace(); throw new SQLException(); } return rows; } public List<ChallengeDomain> fetchMyChallenges(long challengeID, long uid) throws SQLException { List<ChallengeDomain> rows = new ArrayList<>(); String sql = null; if (challengeID == 0) sql = "select * from rivals.challenges where creatoruid=" + uid + " OR acceptoruid=" + uid + " OR wstatus = 'OPEN' or wstatus = 'open' ORDER BY challengeid DESC LIMIT 20"; else sql = "select * from rivals.challenges where creatoruid=" + uid + " OR acceptoruid=" + uid + " AND challengeid < " + challengeID + " OR wstatus = 'OPEN' or wstatus = 'open' ORDER BY challengeid DESC LIMIT 20"; try { rows = namedParameterJdbcTemplate.query(sql, new ChallengeRowMapper()); } catch (DataAccessException e) { e.printStackTrace(); throw new SQLException(); } catch (Exception e) { e.printStackTrace(); throw new SQLException(); } return rows; } public Map<Long, UserAccount> fetchUserDetails(List<Long> uids) throws SQLException { List<UserAccount> rowsUAC = new ArrayList<>(); HashMap<String, Object> paramMap = new HashMap<String, Object>(); HashMap<Long, UserAccount> userAccountDetailMap = new HashMap<>(); paramMap.put("userIdList", uids); String sqlForUserId = "select * from rivals.user_account where id in(:userIdList)"; try { rowsUAC = namedParameterJdbcTemplate.query(sqlForUserId, paramMap, new UserAccountRowMapper()); } catch (DataAccessException e) { e.printStackTrace(); throw new SQLException(); } catch (Exception e) { e.printStackTrace(); throw new SQLException(); } for (UserAccount userAccount : rowsUAC) { long id = userAccount.getId(); userAccountDetailMap.put(id, userAccount); } return userAccountDetailMap; } public List<Player> fetchPlayersOfChallenges(Long challengeid) throws SQLException { List<Player> rows = new ArrayList<>(); String sql = "select * from rivals.player_challenge_mapping where challengeID = " + challengeid; try { rows = namedParameterJdbcTemplate.query(sql, new PlayeMapper()); } catch (DataAccessException e) { e.printStackTrace(); throw new SQLException(); } catch (Exception e) { e.printStackTrace(); throw new SQLException(); } return rows; } public String getDurationForChallengId(long challengeId) { HashMap<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("challengeId", challengeId); String sql = "select duration from rivals.challenges where challengeId = :challengeId"; try { return namedParameterJdbcTemplate.queryForObject(sql, paramMap, String.class); } catch (Exception e) { e.printStackTrace(); } return null; } public int updateEndDate(long challengeId, Date endDate) { HashMap<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("challengeId", challengeId); paramMap.put("endDate", endDate); String sql = "update rivals.challenges set endtime=:endDate where challengeId = :challengeId"; try { return namedParameterJdbcTemplate.update(sql, paramMap); } catch (Exception e) { e.printStackTrace(); } return 0; } public long insertCommentOnChallenge(CommentVO commentVO) throws SQLException { HashMap<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("CREATORUID", commentVO.getUserId()); paramMap.put("USERNAME", commentVO.getUserName()); paramMap.put("CHALLENGEID", commentVO.getChallengeId()); paramMap.put("COMMENT", commentVO.getComment()); paramMap.put("CREATEDDATE", new Date()); String sql = null; sql = "INSERT INTO rivals.comments(creatoruid,username,challengeid,comment,createddate) VALUES(:CREATORUID,:USERNAME,:CHALLENGEID,:COMMENT,:CREATEDDATE)"; KeyHolder keyHolder = new GeneratedKeyHolder(); long commentId = 0L; try { SqlParameterSource paramSource = new MapSqlParameterSource(paramMap); namedParameterJdbcTemplate.update(sql, paramSource, keyHolder); Map<String, Object> keys = keyHolder.getKeys(); commentId = (Long) keys.get("GENERATED_KEY"); } catch (Exception e) { throw new SQLException("error for comment" + e.getMessage()); } return commentId; } public Map<Long, List<String>> fetchCommentsForChallenges(List<Long> challengeIdList) throws SQLException { Map<Long, List<String>> commentMap = new HashMap<Long, List<String>>(); List<String> comments = new ArrayList<>(); HashMap<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("CHALLENGEIDS", challengeIdList); String sql = null; sql = "Select * from rivals.comments where challengeid in (:CHALLENGEIDS) order by challengeid"; try { SqlRowSet rs = namedParameterJdbcTemplate.queryForRowSet(sql, paramMap); long prev = 0; long latest = 0; while (rs.next()) { latest = rs.getLong("challengeid"); if (latest != prev & latest > 0 && prev!=0) { commentMap.put(latest, comments); comments = new ArrayList<>(); } comments.add(rs.getString("comment") != null ? rs.getString("comment") : ""); prev = latest; } if (comments.size() > 0) commentMap.put(latest, comments); } catch (Exception e) { throw new SQLException("" + e.getMessage()); } return commentMap; } @Transactional public boolean submitLike(int playerId,int userId,int challengeId){ String sql = "insert into rivals.likes(userId,challengeId,playerId) values(:userId,:challengeId,:playerId)"; HashMap<String, Object> paramMap = new HashMap<>(); paramMap.put("playerId", playerId); paramMap.put("challengeId", challengeId); paramMap.put("userId", userId); paramMap.put("like", " "); try{ namedParameterJdbcTemplate.update(sql, paramMap); sql = "UPDATE rivals.player_challenge_mapping SET fblikes = (select count(*) from rivals.likes where playerID=:playerId and challengeId=:challengeId) WHERE playerID = :playerId"; namedParameterJdbcTemplate.update(sql, paramMap); }catch(Exception e){ return false; } return true; } }
package com.catalyst.sonar.score.dao; import java.util.List; import org.sonar.api.database.DatabaseSession; import org.sonar.jpa.dao.BaseDao; /** * * The {@code SonarEntityDao<E>} class defines a dao that specifically access a * SonarEntity. What is meant by a SonarEntity is an Entity that is represented * in Sonar's database through Hibernate. As a consequence, any implementation * of this class should use only classes defined by Sonar that map directly to a * table in Sonar's database for generic type {@code <E>}. * * @author JDunn * */ public abstract class SonarEntityDao<E> extends BaseDao { public static final String KEY_LABEL = "key"; /** * Constructor with a parameter for the session to set the session. * * @param session */ public SonarEntityDao(DatabaseSession session) { super(session); } /** * Gets the first Entity of type {@code <E>} from Sonar's database. * * @param key * @return */ public E get(String key) { return getSession().getSingleResult(entityClass(), keyLabel(), key); } /** * Gets a list of all Entities of type {@code <E>} from Sonar's database. * * @param key * @return */ public List<E> getAll(String key) { return getSession().getResults(entityClass(), keyLabel(), key); } /** * Creates a record of type {@code <E>} in the database. * * @param e * @return */ public E create(E e) { return getSession().save(e); } /** * Creates a {@link ScoreEntity} in the database with the given String as * its key, and {@code null} fields. * * @param entity * @return */ public E create(String key) { return create(key, null); } /** * Creates a {@link ScoreEntity} in the database with the String key * as its key and {@code value.toString()} as its value (or relevant field). * * @param entity * @return */ public E create (String key, Object value) { String valueArg = (value != null) ? value.toString() : null; return create(key, valueArg); } /** * Creates a {@link ScoreEntity} in the database with the first String arg * as its key and the second String arg as its value (or relevant field). * * @param entity * @return */ public abstract E create(String key, String value); /** * @return the name of the column used as the key, or unique identifier, of * the Entity in Sonar's Database. Usually this is "{@code key}". If * not, this method needs to be overridden during implementation. */ protected String keyLabel() { return KEY_LABEL; } /** * When this is implemented, it MUST return the class of the generic type. * For example, if StringDao extends {@code SonarEntityDao<String>}, this * method must return {@code String.class}. * * @return (GenericParameterType).class */ protected abstract Class<E> entityClass(); }
package com.cedarsoftware.ncube.util; import groovy.lang.GroovyClassLoader; import java.io.IOException; import java.net.URL; import java.util.Enumeration; import java.util.NoSuchElementException; public class CdnClassLoader extends GroovyClassLoader { private boolean _preventRemoteBeanInfo; private boolean _preventRemoteCusomizer; /** * creates a GroovyClassLoader using the given ClassLoader as parent */ public CdnClassLoader(ClassLoader loader, boolean preventRemoteBeanInfo, boolean preventRemoteCusomizer) { super(loader, null); _preventRemoteBeanInfo = preventRemoteBeanInfo; _preventRemoteCusomizer = preventRemoteCusomizer; } /** * Finds and loads the class with the specified name from the URL search * path. Any URLs referring to JAR files are loaded and opened as needed * until the class is found. * * @param name the name of the class * @return the resulting class * @throws ClassNotFoundException if the class could not be found, * or if the loader is closed. */ protected Class<?> findClass(final String name) throws ClassNotFoundException { // We only allow loading classes off of the local classpath. // no true url classpath loading when dealing with classes. // this is for security reasons to keep injected code from loading // remotely. return super.getParent().loadClass(name); } /** * Thse need to be changed to some sort of pattern recognition * * @param name Name of resource * @return true if we should only look locally. */ protected boolean isLocalOnlyResource(String name) { // Groovy ASTTransform Service if (name.endsWith("org.codehaus.groovy.transform.ASTTransformation")) { return true; } if (name.startsWith("ncube/grv/exp/") || name.startsWith("ncube/grv/method/")) { return true; } if (_preventRemoteBeanInfo) { if (name.endsWith("BeanInfo.groovy")) { return true; } } if (_preventRemoteCusomizer) { if (name.endsWith("Customizer.groovy")) { return true; } } return name.endsWith(".class"); } public Enumeration<URL> getResources(String name) throws IOException { if (isLocalOnlyResource(name)) { return new Enumeration<URL>() { public boolean hasMoreElements() { return false; } public URL nextElement() { throw new NoSuchElementException(); } }; } return super.getResources(name); } public URL getResource(String name) { if (isLocalOnlyResource(name)) { return null; } return super.getResource(name); } }
package com.cflint.plugins.core; import com.cflint.BugInfo; import com.cflint.BugList; import com.cflint.plugins.CFLintScannerAdapter; import com.cflint.plugins.Context; import cfml.parsing.cfscript.script.CFFuncDeclStatement; import cfml.parsing.cfscript.script.CFScriptStatement; import net.htmlparser.jericho.Element; public class FunctionTypeChecker extends CFLintScannerAdapter { final String severity = "WARNING"; @Override public void expression(final CFScriptStatement expression, final Context context, final BugList bugs) { if (expression instanceof CFFuncDeclStatement) { CFFuncDeclStatement function = (CFFuncDeclStatement) expression; final int begLine = function.getLine(); final String functionType = function.getReturnType() == null? null :function.getReturnType().toString(); checkReturnType(functionType, begLine, context, bugs); } } @Override public void element(final Element element, final Context context, final BugList bugs) { if (element.getName().equals("cffunction")) { final int begLine = element.getSource().getRow(element.getBegin()); final String functionType = element.getAttributeValue("returnType"); checkReturnType(functionType, begLine, context, bugs); } } protected void checkReturnType(final String functionType, final int lineNumber, final Context context, final BugList bugs) { if (functionType == null || functionType.length() == 0) { bugs.add(new BugInfo.BugInfoBuilder().setLine(lineNumber).setMessageCode("FUNCTION_TYPE_MISSING") .setSeverity(severity).setFilename(context.getFilename()).setFunction(context.getFunctionName()) .setMessage("Function " + context.getFunctionName() + " is missing a return type.") .build()); } else if (functionType.equals("any")) { bugs.add(new BugInfo.BugInfoBuilder().setLine(lineNumber).setMessageCode("FUNCTION_TYPE_ANY") .setSeverity(severity).setFilename(context.getFilename()).setFunction(context.getFunctionName()) .setMessage("Function " + context.getFunctionName() + " return type is any. Please change to be the correct type.") .build()); } } }
package com.codeborne.selenide; import org.openqa.selenium.WebElement; public interface ShouldableWebElement extends WebElement { ShouldableWebElement should(Condition... condition); ShouldableWebElement shouldHave(Condition... condition); ShouldableWebElement shouldBe(Condition... condition); /** * Displays WebElement in human-readable format * @return e.g. <strong id=orderConfirmedStatus class=>Order has been confirmed</strong> */ @Override String toString(); }
package com.couchbase.lite.replicator; import com.couchbase.lite.CouchbaseLiteException; import com.couchbase.lite.Database; import com.couchbase.lite.Manager; import com.couchbase.lite.Status; import com.couchbase.lite.auth.Authenticator; import com.couchbase.lite.auth.AuthenticatorImpl; import com.couchbase.lite.internal.InterfaceAudience; import com.couchbase.lite.util.Log; import com.couchbase.lite.util.URIUtils; import com.couchbase.lite.util.Utils; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthState; import org.apache.http.auth.Credentials; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpClient; import org.apache.http.client.HttpResponseException; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.protocol.ClientContext; import org.apache.http.entity.StringEntity; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.HttpContext; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonParser; import org.codehaus.jackson.JsonToken; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.management.relation.RoleUnresolved; /** * Reads the continuous-mode _changes feed of a database, and sends the * individual change entries to its client's changeTrackerReceivedChange() * * @exclude */ @InterfaceAudience.Private public class ChangeTracker implements Runnable { private URL databaseURL; private ChangeTrackerClient client; private ChangeTrackerMode mode; private Object lastSequenceID; private boolean includeConflicts; private Thread thread; private boolean running = false; private HttpUriRequest request; private String filterName; private Map<String, Object> filterParams; private List<String> docIDs; private Throwable error; protected Map<String, Object> requestHeaders; protected ChangeTrackerBackoff backoff; private boolean usePOST; private int heartBeatSeconds; private int limit; private boolean caughtUp = false; private boolean continuous = false; // is enclosing replication continuous? private Authenticator authenticator; public enum ChangeTrackerMode { OneShot, LongPoll, Continuous // does not work, do not use it. } public ChangeTracker(URL databaseURL, ChangeTrackerMode mode, boolean includeConflicts, Object lastSequenceID, ChangeTrackerClient client) { this.databaseURL = databaseURL; this.mode = mode; this.includeConflicts = includeConflicts; this.lastSequenceID = lastSequenceID; this.client = client; this.requestHeaders = new HashMap<String, Object>(); this.heartBeatSeconds = 300; this.limit = 50; } public boolean isContinuous() { return continuous; } public void setContinuous(boolean continuous) { this.continuous = continuous; } public void setFilterName(String filterName) { this.filterName = filterName; } public void setFilterParams(Map<String, Object> filterParams) { this.filterParams = filterParams; } public void setClient(ChangeTrackerClient client) { this.client = client; } public String getDatabaseName() { String result = null; if (databaseURL != null) { result = databaseURL.getPath(); if (result != null) { int pathLastSlashPos = result.lastIndexOf('/'); if (pathLastSlashPos > 0) { result = result.substring(pathLastSlashPos); } } } return result; } public String getFeed() { switch (mode) { case OneShot: return "normal"; case LongPoll: return "longpoll"; case Continuous: return "continuous"; } return "normal"; } public long getHeartbeatMilliseconds() { return heartBeatSeconds * 1000; } public String getChangesFeedPath() { if (usePOST) { return "_changes"; } String path = "_changes?feed="; path += getFeed(); if (mode == ChangeTrackerMode.LongPoll) { path += String.format("&limit=%s", limit); } path += String.format("&heartbeat=%s", getHeartbeatMilliseconds()); if (includeConflicts) { path += "&style=all_docs"; } if(lastSequenceID != null) { path += "&since=" + URLEncoder.encode(lastSequenceID.toString()); } if (docIDs != null && docIDs.size() > 0) { filterName = "_doc_ids"; filterParams = new HashMap<String, Object>(); filterParams.put("doc_ids", docIDs); } if(filterName != null) { path += "&filter=" + URLEncoder.encode(filterName); if(filterParams != null) { for (String filterParamKey : filterParams.keySet()) { Object value = filterParams.get(filterParamKey); if (!(value instanceof String)) { try { value = Manager.getObjectMapper().writeValueAsString(value); } catch (IOException e) { throw new IllegalArgumentException(e); } } path += "&" + URLEncoder.encode(filterParamKey) + "=" + URLEncoder.encode(value.toString()); } } } return path; } public URL getChangesFeedURL() { String dbURLString = databaseURL.toExternalForm(); if(!dbURLString.endsWith("/")) { dbURLString += "/"; } dbURLString += getChangesFeedPath(); URL result = null; try { result = new URL(dbURLString); } catch(MalformedURLException e) { Log.e(Log.TAG_CHANGE_TRACKER, this + ": Changes feed ULR is malformed", e); } return result; } /** * Set Authenticator for BASIC Authentication */ public void setAuthenticator(Authenticator authenticator) { this.authenticator = authenticator; } @Override public void run() { running = true; HttpClient httpClient; if (client == null) { // This is a race condition that can be reproduced by calling cbpuller.start() and cbpuller.stop() // directly afterwards. What happens is that by the time the Changetracker thread fires up, // the cbpuller has already set this.client to null. See issue #109 Log.w(Log.TAG_CHANGE_TRACKER, "%s: ChangeTracker run() loop aborting because client == null", this); return; } if (mode == ChangeTrackerMode.Continuous) { // there is a failing unit test for this, and from looking at the code the Replication // object will never use Continuous mode anyway. Explicitly prevent its use until // it is demonstrated to actually work. throw new RuntimeException("ChangeTracker does not correctly support continuous mode"); } httpClient = client.getHttpClient(); backoff = new ChangeTrackerBackoff(); while (running) { URL url = getChangesFeedURL(); if (usePOST) { HttpPost postRequest = new HttpPost(url.toString()); postRequest.setHeader("Content-Type", "application/json"); StringEntity entity; try { entity = new StringEntity(changesFeedPOSTBody()); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } postRequest.setEntity(entity); request = postRequest; } else { request = new HttpGet(url.toString()); } addRequestHeaders(request); // Perform BASIC Authentication if needed boolean isUrlBasedUserInfo = false; // If the URL contains user info AND if this a DefaultHttpClient then preemptively set the auth credentials String userInfo = url.getUserInfo(); if (userInfo != null) { isUrlBasedUserInfo = true; } else { if (authenticator != null) { AuthenticatorImpl auth = (AuthenticatorImpl) authenticator; userInfo = auth.authUserInfo(); } } if (userInfo != null) { if (userInfo.contains(":") && !userInfo.trim().equals(":")) { String[] userInfoElements = userInfo.split(":"); String username = isUrlBasedUserInfo ? URIUtils.decode(userInfoElements[0]): userInfoElements[0]; String password = isUrlBasedUserInfo ? URIUtils.decode(userInfoElements[1]): userInfoElements[1]; final Credentials credentials = new UsernamePasswordCredentials(username, password); if (httpClient instanceof DefaultHttpClient) { DefaultHttpClient dhc = (DefaultHttpClient) httpClient; HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() { @Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); if (authState.getAuthScheme() == null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(credentials); } } }; dhc.addRequestInterceptor(preemptiveAuth, 0); } } else { Log.w(Log.TAG_CHANGE_TRACKER, "RemoteRequest Unable to parse user info, not setting credentials"); } } try { String maskedRemoteWithoutCredentials = getChangesFeedURL().toString(); maskedRemoteWithoutCredentials = maskedRemoteWithoutCredentials.replaceAll(": Log.v(Log.TAG_CHANGE_TRACKER, "%s: Making request to %s", this, maskedRemoteWithoutCredentials); HttpResponse response = httpClient.execute(request); StatusLine status = response.getStatusLine(); if (status.getStatusCode() >= 300 && !Utils.isTransientError(status)) { Log.e(Log.TAG_CHANGE_TRACKER, "%s: Change tracker got error %d", this, status.getStatusCode()); this.error = new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()); stop(); return; } HttpEntity entity = response.getEntity(); Log.v(Log.TAG_CHANGE_TRACKER, "%s: got response. status: %s mode: %s", this, status, mode); InputStream input = null; if (entity != null) { try { input = entity.getContent(); if (mode == ChangeTrackerMode.LongPoll) { // continuous replications Map<String, Object> fullBody = Manager.getObjectMapper().readValue(input, Map.class); boolean responseOK = receivedPollResponse(fullBody); if (mode == ChangeTrackerMode.LongPoll && responseOK) { // TODO: this logic is questionable, there's lots // TODO: of differences in the iOS changetracker code, if (!caughtUp) { caughtUp = true; client.changeTrackerCaughtUp(); } Log.v(Log.TAG_CHANGE_TRACKER, "%s: Starting new longpoll", this); backoff.resetBackoff(); continue; } else { Log.w(Log.TAG_CHANGE_TRACKER, "%s: Change tracker calling stop (LongPoll)", this); client.changeTrackerFinished(this); stop(); } } else { // one-shot replications JsonFactory jsonFactory = Manager.getObjectMapper().getJsonFactory(); JsonParser jp = jsonFactory.createJsonParser(input); while (jp.nextToken() != JsonToken.START_ARRAY) { // ignore these tokens } while (jp.nextToken() == JsonToken.START_OBJECT) { Map<String, Object> change = (Map) Manager.getObjectMapper().readValue(jp, Map.class); if (!receivedChange(change)) { Log.w(Log.TAG_CHANGE_TRACKER, "Received unparseable change line from server: %s", change); } } if (!caughtUp) { caughtUp = true; client.changeTrackerCaughtUp(); } if (isContinuous()) { // if enclosing replication is continuous mode = ChangeTrackerMode.LongPoll; } else { Log.w(Log.TAG_CHANGE_TRACKER, "%s: Change tracker calling stop (OneShot)", this); client.changeTrackerFinished(this); stopped(); break; // break out of while (running) loop } } backoff.resetBackoff(); } finally { try { entity.consumeContent(); } catch (IOException ex) { } } } } catch (Exception e) { if (!running && e instanceof IOException) { // in this case, just silently absorb the exception because it // frequently happens when we're shutting down and have to // close the socket underneath our read. } else { Log.e(Log.TAG_CHANGE_TRACKER, this + ": Exception in change tracker", e); } backoff.sleepAppropriateAmountOfTime(); } } Log.v(Log.TAG_CHANGE_TRACKER, "%s: Change tracker run loop exiting", this); } public boolean receivedChange(final Map<String,Object> change) { Object seq = change.get("seq"); if(seq == null) { return false; } //pass the change to the client on the thread that created this change tracker if(client != null) { client.changeTrackerReceivedChange(change); } lastSequenceID = seq; return true; } public boolean receivedPollResponse(Map<String,Object> response) { List<Map<String,Object>> changes = (List)response.get("results"); if(changes == null) { return false; } for (Map<String,Object> change : changes) { if(!receivedChange(change)) { return false; } } return true; } public void setUpstreamError(String message) { Log.w(Log.TAG_CHANGE_TRACKER, "Server error: %s", message); this.error = new Throwable(message); } public boolean start() { Log.d(Log.TAG_CHANGE_TRACKER, "%s: Changed tracker asked to start", this); this.error = null; String maskedRemoteWithoutCredentials = databaseURL.toExternalForm(); maskedRemoteWithoutCredentials = maskedRemoteWithoutCredentials.replaceAll(": thread = new Thread(this, "ChangeTracker-" + maskedRemoteWithoutCredentials); thread.start(); return true; } public void stop() { Log.d(Log.TAG_CHANGE_TRACKER, "%s: Changed tracker asked to stop", this); try { running = false; try { if (thread != null) { thread.interrupt(); } } catch (Exception e) { Log.d(Log.TAG_CHANGE_TRACKER, "%s: Exception interrupting thread: %s", this); } if(request != null) { Log.d(Log.TAG_CHANGE_TRACKER, "%s: Changed tracker aborting request: %s", this, request); request.abort(); } } finally { stopped(); } } /** * The reason this is synchronized is because it can be called by multiple threads, * and if those calls are interleaved, the null check will pass but then an NPE will be thrown * when client.changeTrackerStopped() is called. */ public synchronized void stopped() { Log.d(Log.TAG_CHANGE_TRACKER, "%s: Change tracker in stopped()", this); if (client != null) { Log.w(Log.TAG_CHANGE_TRACKER, "%s: Change tracker calling changeTrackerStopped, client: %s", this, client); client.changeTrackerStopped(ChangeTracker.this); } else { Log.w(Log.TAG_CHANGE_TRACKER, "%s: Change tracker not calling changeTrackerStopped, client == null", this); } client = null; } public void setRequestHeaders(Map<String, Object> requestHeaders) { this.requestHeaders = requestHeaders; } private void addRequestHeaders(HttpUriRequest request) { if (requestHeaders != null) { for (String requestHeaderKey : requestHeaders.keySet()) { request.addHeader(requestHeaderKey, requestHeaders.get(requestHeaderKey).toString()); } } } public Throwable getLastError() { return error; } public boolean isRunning() { return running; } public void setDocIDs(List<String> docIDs) { this.docIDs = docIDs; } public String changesFeedPOSTBody() { Map<String, Object> postBodyMap = changesFeedPOSTBodyMap(); try { return Manager.getObjectMapper().writeValueAsString(postBodyMap); } catch (IOException e) { throw new RuntimeException(e); } } public boolean isUsePOST() { return usePOST; } public void setUsePOST(boolean usePOST) { this.usePOST = usePOST; } public Map<String, Object> changesFeedPOSTBodyMap() { if (!usePOST) { return null; } if (docIDs != null && docIDs.size() > 0) { filterName = "_doc_ids"; filterParams = new HashMap<String, Object>(); filterParams.put("doc_ids", docIDs); } Map<String, Object> post = new HashMap<String, Object>(); post.put("feed", getFeed()); post.put("heartbeat", getHeartbeatMilliseconds()); if (includeConflicts) { post.put("style","all_docs"); } else { post.put("style", null); } if (lastSequenceID != null) { try { post.put("since", Long.parseLong(lastSequenceID.toString())); } catch (NumberFormatException e) { post.put("since", lastSequenceID.toString()); } } if (mode == ChangeTrackerMode.LongPoll && limit > 0) { post.put("limit", limit); } else { post.put("limit", null); } if (filterName != null) { post.put("filter", filterName); post.putAll(filterParams); } return post; } }
package com.ezardlabs.lostsector.camera; import com.ezardlabs.dethsquare.Screen; import com.ezardlabs.dethsquare.Script; import com.ezardlabs.dethsquare.Transform; import com.ezardlabs.dethsquare.Vector2; import com.ezardlabs.dethsquare.debug.Debug; import java.util.ArrayList; public class SmartCamera extends Script { private static final boolean debug = false; private static ArrayList<CameraPOI> pois = new ArrayList<>(); private Transform followTarget; private float maxLookahead; private Vector2 offset = new Vector2(0, 0); private Vector2 base = new Vector2(); private Vector2 inputTarget = new Vector2(); private Vector2 inputCurrent = new Vector2(); private Vector2 target = new Vector2(); private Vector2 lastFollowTargetPos = new Vector2(); private boolean isQuaking = false; private long quakeEnd = 0; private float quakeStrength = 0; public SmartCamera(Transform followTarget, float maxLookahead) { this(followTarget, maxLookahead, new Vector2()); } public SmartCamera(Transform followTarget, float maxLookahead, Vector2 offset) { this.followTarget = followTarget; this.maxLookahead = maxLookahead; this.offset = offset; } @Override public void start() { transform.position.set(followTarget.position); lastFollowTargetPos.set(followTarget.position); } @Override public void update() { inputTarget.set(0, 0); if (followTarget.position.y - lastFollowTargetPos.y < 0) { inputTarget.y -= 1; } if (followTarget.position.x - lastFollowTargetPos.x < 0) { inputTarget.x -= 1; } if (followTarget.position.y - lastFollowTargetPos.y > 0) { inputTarget.y += 1; } if (followTarget.position.x - lastFollowTargetPos.x > 0) { inputTarget.x += 1; } inputTarget.normalise(); inputTarget.multiplyBy(maxLookahead * Screen.scale); base.set((followTarget.position.x + offset.x) * Screen.scale, (followTarget.position.y + offset.y) * Screen.scale); lerp(inputCurrent, inputTarget); target.set(base.x + inputCurrent.x, base.y + inputCurrent.y); if (debug) { Debug.drawCircle(target, 30, 1, 0, 0); } target.x -= (Screen.width / 2); target.y -= (Screen.height / 2); lerp(transform.position, target); if (transform.position.x < 0) { transform.position.x = 0; } if (transform.position.y < 0) { transform.position.y = 0; } if (debug) { Debug.drawCircle(base, 100, 1, 0, 0); Debug.drawCircle(base.offset(inputTarget.dividedBy(maxLookahead).x * 100, inputTarget.dividedBy(maxLookahead).y * 100), 20, 1, 0, 0); } lastFollowTargetPos.set(followTarget.position); if (isQuaking) { updateQuake(); } } private void lerp(Vector2 current, Vector2 target) { float dx = target.x - current.x; float dy = target.y - current.y; double h = Math.sqrt(dx * dx + dy * dy); float dn = (float) (h / Math.sqrt(2.0D)); if (dn != 0) { current.x += dx / dn * (dn * 0.03F);// 0.04 current.y += dy / dn * (dn * 0.02f); } } public void setFollowTarget(Transform followTarget) { this.followTarget = followTarget; } public void startQuake(long length, float strengthFactor) { this.quakeStrength = strengthFactor * 3.125f; this.quakeEnd = (System.currentTimeMillis() + length); this.isQuaking = true; } private void updateQuake() { transform.position.x += (int) (35.0F * this.quakeStrength - Math.random() * 70.0D * this.quakeStrength); transform.position.y += (int) (35.0F * this.quakeStrength - Math.random() * 70.0D * this.quakeStrength); this.isQuaking = System.currentTimeMillis() < this.quakeEnd; } static void registerPOI(CameraPOI poi) { pois.add(poi); } static void unregisterPOI(CameraPOI poi) { pois.remove(poi); } }
package com.faforever.client.chat; import com.faforever.client.FafClientApplication; import com.faforever.client.chat.event.ChatMessageEvent; import com.faforever.client.chat.event.ChatUserCategoryChangeEvent; import com.faforever.client.config.ClientProperties; import com.faforever.client.config.ClientProperties.Irc; import com.faforever.client.fx.JavaFxUtil; import com.faforever.client.net.ConnectionState; import com.faforever.client.player.Player; import com.faforever.client.player.PlayerOnlineEvent; import com.faforever.client.player.PlayerService; import com.faforever.client.player.SocialStatus; import com.faforever.client.player.UserOfflineEvent; import com.faforever.client.player.event.CurrentPlayerInfo; import com.faforever.client.preferences.ChatPrefs; import com.faforever.client.preferences.PreferencesService; import com.faforever.client.remote.FafService; import com.faforever.client.remote.domain.SocialMessage; import com.faforever.client.ui.tray.event.UpdateApplicationBadgeEvent; import com.faforever.client.user.UserService; import com.faforever.client.user.event.LoggedOutEvent; import com.faforever.client.user.event.LoginSuccessEvent; import com.google.common.annotations.VisibleForTesting; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import com.google.common.hash.Hashing; import javafx.beans.property.ObjectProperty; import javafx.beans.property.ReadOnlyIntegerProperty; import javafx.beans.property.ReadOnlyObjectProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.MapChangeListener; import javafx.collections.ObservableList; import javafx.collections.ObservableMap; import javafx.scene.paint.Color; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import net.engio.mbassy.listener.Handler; import org.jetbrains.annotations.NotNull; import org.kitteh.irc.client.library.Client; import org.kitteh.irc.client.library.Client.Builder.Server.SecurityType; import org.kitteh.irc.client.library.defaults.DefaultClient; import org.kitteh.irc.client.library.element.Channel; import org.kitteh.irc.client.library.element.User; import org.kitteh.irc.client.library.element.mode.ChannelUserMode; import org.kitteh.irc.client.library.element.mode.Mode; import org.kitteh.irc.client.library.element.mode.ModeStatus.Action; import org.kitteh.irc.client.library.event.channel.ChannelCtcpEvent; import org.kitteh.irc.client.library.event.channel.ChannelJoinEvent; import org.kitteh.irc.client.library.event.channel.ChannelMessageEvent; import org.kitteh.irc.client.library.event.channel.ChannelModeEvent; import org.kitteh.irc.client.library.event.channel.ChannelNamesUpdatedEvent; import org.kitteh.irc.client.library.event.channel.ChannelPartEvent; import org.kitteh.irc.client.library.event.channel.ChannelTopicEvent; import org.kitteh.irc.client.library.event.client.ClientNegotiationCompleteEvent; import org.kitteh.irc.client.library.event.connection.ClientConnectionEndedEvent; import org.kitteh.irc.client.library.event.user.PrivateMessageEvent; import org.kitteh.irc.client.library.event.user.UserQuitEvent; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Service; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import static com.faforever.client.chat.ChatColorMode.DEFAULT; import static com.faforever.client.chat.ChatUserCategory.MODERATOR; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Locale.US; import static javafx.collections.FXCollections.observableHashMap; import static javafx.collections.FXCollections.observableMap; @Lazy @Service @Slf4j @Profile("!" + FafClientApplication.PROFILE_OFFLINE) @RequiredArgsConstructor public class KittehChatService implements ChatService, InitializingBean, DisposableBean { public static final int MAX_GAMES_FOR_NEWBIE_CHANNEL = 50; private static final String NEWBIE_CHANNEL_NAME = "#newbie"; private static final Set<Character> MODERATOR_PREFIXES = Set.of('~', '&', '@', '%'); private final ChatUserService chatUserService; private final PreferencesService preferencesService; private final UserService userService; private final FafService fafService; private final EventBus eventBus; private final ClientProperties clientProperties; private final PlayerService playerService; /** * Maps channels by name. */ private final ObservableMap<String, ChatChannel> channels = observableHashMap(); /** Key is the result of {@link #mapKey(String, String)}. */ private final ObservableMap<String, ChatChannelUser> chatChannelUsersByChannelAndName = observableMap(new TreeMap<>(String.CASE_INSENSITIVE_ORDER)); private final SimpleIntegerProperty unreadMessagesCount = new SimpleIntegerProperty(); @VisibleForTesting ObjectProperty<ConnectionState> connectionState = new SimpleObjectProperty<>(ConnectionState.DISCONNECTED); @VisibleForTesting String defaultChannelName; @VisibleForTesting DefaultClient client; /** * A list of channels the server wants us to join. */ private List<String> autoChannels; /** * Indicates whether the "auto channels" already have been joined. This is needed because we don't want to auto join * channels after a reconnect that the user left before the reconnect. */ private boolean autoChannelsJoined; private boolean newbieChannelJoined; @Override public void afterPropertiesSet() { eventBus.register(this); fafService.addOnMessageListener(SocialMessage.class, this::onSocialMessage); connectionState.addListener((observable, oldValue, newValue) -> { switch (newValue) { case DISCONNECTED, CONNECTING -> onDisconnected(); } }); ChatPrefs chatPrefs = preferencesService.getPreferences().getChat(); JavaFxUtil.addListener(chatPrefs.userToColorProperty(), (MapChangeListener<? super String, ? super Color>) change -> preferencesService.storeInBackground() ); JavaFxUtil.addListener(chatPrefs.groupToColorProperty(), (MapChangeListener<? super ChatUserCategory, ? super Color>) change -> { preferencesService.storeInBackground(); updateUserColors(chatPrefs.getChatColorMode()); } ); JavaFxUtil.addListener(chatPrefs.chatColorModeProperty(), (observable, oldValue, newValue) -> updateUserColors(newValue)); } private void updateUserColors(ChatColorMode chatColorMode) { if (chatColorMode == null) { chatColorMode = DEFAULT; } ChatPrefs chatPrefs = preferencesService.getPreferences().getChat(); synchronized (chatChannelUsersByChannelAndName) { if (chatColorMode == ChatColorMode.RANDOM) { chatChannelUsersByChannelAndName.values() .forEach(chatUser -> chatUser.setColor(ColorGeneratorUtil.generateRandomColor(chatUser.getUsername().hashCode()))); } else { chatChannelUsersByChannelAndName.values() .forEach(chatUser -> { if (chatPrefs.getUserToColor().containsKey(userToColorKey(chatUser.getUsername()))) { chatUser.setColor(chatPrefs.getUserToColor().get(userToColorKey(chatUser.getUsername()))); } else { if (chatUser.isModerator() && chatPrefs.getGroupToColor().containsKey(MODERATOR)) { chatUser.setColor(chatPrefs.getGroupToColor().get(MODERATOR)); } else { chatUser.setColor(chatUser.getSocialStatus() .map(status -> chatPrefs.getGroupToColor().getOrDefault(groupToColorKey(status), null)) .orElse(null)); } } }); } } } @NotNull private String userToColorKey(String username) { return username.toLowerCase(US); } @NotNull private ChatUserCategory groupToColorKey(SocialStatus socialStatus) { return switch (socialStatus) { case FRIEND -> ChatUserCategory.FRIEND; case FOE -> ChatUserCategory.FOE; default -> ChatUserCategory.OTHER; }; } @Override public ChatChannelUser getOrCreateChatUser(String username, String channelName) { Channel channel = client.getChannel(channelName).orElseThrow(() -> new IllegalArgumentException("Channel '" + channelName + "' is unknown")); User user = channel.getUser(username).orElseThrow(() -> new IllegalArgumentException("Chat user '" + username + "' is unknown for channel '" + channelName + "'")); return getOrCreateChatUser(user, channel); } private ChatChannelUser getOrCreateChatUser(User user, Channel channel) { String username = user.getNick(); boolean isModerator = channel.getUserModes(user).stream().flatMap(Collection::stream) .map(ChannelUserMode::getNickPrefix) .anyMatch(MODERATOR_PREFIXES::contains); return getOrCreateChatUser(username, channel.getName(), isModerator); } @Subscribe public void onLoginSuccessEvent(LoginSuccessEvent event) { connect(); } @Subscribe public void onLoggedOutEvent(LoggedOutEvent event) { disconnect(); eventBus.post(UpdateApplicationBadgeEvent.ofNewValue(0)); } @Subscribe public void onCurrentPlayerInfo(CurrentPlayerInfo currentPlayerInfo) { if (!newbieChannelJoined && currentPlayerInfo.getCurrentPlayer().getNumberOfGames() < MAX_GAMES_FOR_NEWBIE_CHANNEL) { joinChannel(NEWBIE_CHANNEL_NAME); } newbieChannelJoined = true; } @Subscribe public void onPlayerOnline(PlayerOnlineEvent event) { Player player = event.getPlayer(); synchronized (channels) { channels.values().parallelStream() .map(channel -> chatChannelUsersByChannelAndName.get(mapKey(player.getUsername(), channel.getName()))) .filter(Objects::nonNull) .forEach(chatChannelUser -> { chatUserService.associatePlayerToChatUser(chatChannelUser, player); eventBus.post(new ChatUserCategoryChangeEvent(chatChannelUser)); }); } } @Handler public void onConnect(ClientNegotiationCompleteEvent event) { connectionState.set(ConnectionState.CONNECTED); } @Handler private void onJoinEvent(ChannelJoinEvent event) { User user = event.getActor(); log.debug("User joined channel: {}", user); addUserToChannel(event.getChannel().getName(), getOrCreateChatUser(user, event.getChannel())); } @Handler public void onChatUserList(ChannelNamesUpdatedEvent event) { Channel channel = event.getChannel(); List<ChatChannelUser> users = channel.getUsers().stream().map(user -> getOrCreateChatUser(user, channel)).collect(Collectors.toList()); getOrCreateChannel(channel.getName()).addUsers(users); } @Handler private void onPartEvent(ChannelPartEvent event) { User user = event.getActor(); log.debug("User joined channel: {}", user); onChatUserLeftChannel(event.getChannel().getName(), user.getNick()); } @Handler private void onChatUserQuit(UserQuitEvent event) { User user = event.getUser(); synchronized (channels) { channels.values().forEach(channel -> onChatUserLeftChannel(channel.getName(), user.getNick())); } } @Handler private void onTopicChange(ChannelTopicEvent event) { Channel channel = event.getChannel(); getOrCreateChannel(channel.getName()).setTopic(event.getNewTopic().getValue().orElse("")); } @Handler private void onChannelMessage(ChannelMessageEvent event) { User user = event.getActor(); Channel channel = event.getChannel(); String source = channel.getName(); eventBus.post(new ChatMessageEvent(new ChatMessage(source, Instant.ofEpochMilli(user.getCreationTime()), user.getNick(), event.getMessage(), false))); } @Handler private void onChannelCTCP(ChannelCtcpEvent event) { User user = event.getActor(); Channel channel = event.getChannel(); String source = channel.getName(); eventBus.post(new ChatMessageEvent(new ChatMessage(source, Instant.ofEpochMilli(user.getCreationTime()), user.getNick(), event.getMessage().replace("ACTION", user.getNick()), true))); } @Handler private void onChannelModeChanged(ChannelModeEvent event) { ChatChannel channel = getOrCreateChannel(event.getChannel().getName()); event.getStatusList().getAll().forEach(channelModeStatus -> channelModeStatus.getParameter().ifPresent(username -> { Mode changedMode = channelModeStatus.getMode(); Action modeAction = channelModeStatus.getAction(); if (changedMode instanceof ChannelUserMode) { if (MODERATOR_PREFIXES.contains(((ChannelUserMode) changedMode).getNickPrefix())) { ChatChannelUser chatChannelUser = getOrCreateChatUser(username, channel.getName(), false); if (modeAction == Action.ADD) { chatChannelUser.setModerator(true); } else if (modeAction == Action.REMOVE) { chatChannelUser.setModerator(false); } eventBus.post(new ChatUserCategoryChangeEvent(chatChannelUser)); } } })); } @Handler private void onPrivateMessage(PrivateMessageEvent event) { User user = event.getActor(); log.debug("Received private message: {}", event); ChatChannelUser sender = getOrCreateChatUser(user.getNick(), user.getNick(), false); if (sender.getPlayer().map(Player::getSocialStatus).filter(status -> status == SocialStatus.FOE).isPresent() && preferencesService.getPreferences().getChat().getHideFoeMessages()) { log.debug("Suppressing chat message from foe '{}'", user.getNick()); return; } eventBus.post(new ChatMessageEvent(new ChatMessage(user.getNick(), Instant.ofEpochMilli(user.getCreationTime()), user.getNick(), event.getMessage()))); } private void joinAutoChannels() { log.debug("Joining auto channel: {}", autoChannels); if (autoChannels == null) { return; } autoChannels.forEach(this::joinChannel); autoChannelsJoined = true; } private void joinSavedAutoChannels() { ObservableList<String> savedAutoChannels = preferencesService.getPreferences().getChat().getAutoJoinChannels(); if (savedAutoChannels == null) { return; } log.debug("Joining user's saved auto channel: {}", savedAutoChannels); savedAutoChannels.forEach(this::joinChannel); } private void onDisconnected() { synchronized (channels) { channels.values().forEach(ChatChannel::clearUsers); channels.clear(); } synchronized (chatChannelUsersByChannelAndName) { chatChannelUsersByChannelAndName.clear(); } newbieChannelJoined = false; autoChannelsJoined = false; } private void addUserToChannel(String channelName, ChatChannelUser chatUser) { getOrCreateChannel(channelName).addUser(chatUser); if (chatUser.isModerator()) { onModeratorSet(channelName, chatUser.getUsername()); } } private void onChatUserLeftChannel(String channelName, String username) { if (getOrCreateChannel(channelName).removeUser(username) == null) { return; } log.debug("User '{}' left channel: {}", username, channelName); if (userService.getUsername().equalsIgnoreCase(username)) { synchronized (channels) { channels.remove(channelName); } } synchronized (chatChannelUsersByChannelAndName) { chatChannelUsersByChannelAndName.remove(mapKey(username, channelName)); } // The server doesn't yet tell us when a user goes offline, so we have to rely on the user leaving IRC. if (defaultChannelName.equals(channelName)) { eventBus.post(new UserOfflineEvent(username)); } } private void onMessage(String message) { log.debug(message); } @Handler private void onDisconnect(ClientConnectionEndedEvent event) { connectionState.set(ConnectionState.DISCONNECTED); } @NotNull private String getPassword() { return Hashing.md5().hashString(Hashing.sha256().hashString(userService.getPassword(), UTF_8).toString(), UTF_8).toString(); } private void onSocialMessage(SocialMessage socialMessage) { if (!autoChannelsJoined && socialMessage.getChannels() != null) { this.autoChannels = new ArrayList<>(socialMessage.getChannels()); autoChannels.remove(defaultChannelName); autoChannels.add(0, defaultChannelName); joinAutoChannels(); joinSavedAutoChannels(); } } @Override public void connect() { String username = userService.getUsername(); Irc irc = clientProperties.getIrc(); this.defaultChannelName = irc.getDefaultChannel(); client = (DefaultClient) Client.builder() .user(username) .realName(username) .nick(username) .server() .host(irc.getHost()) .port(irc.getPort(), SecurityType.SECURE) .secureTrustManagerFactory(new TrustEveryoneFactory()) .password(getPassword()) .then() .listeners() .input(this::onMessage) .output(this::onMessage) .then() .build(); client.getEventManager().registerEventListener(this); client.getActorTracker().setQueryChannelInformation(false); client.connect(); } @Override public void disconnect() { log.info("Disconnecting from IRC"); client.shutdown("Goodbye"); } @Override public CompletableFuture<String> sendMessageInBackground(String target, String message) { eventBus.post(new ChatMessageEvent(new ChatMessage(target, Instant.now(), userService.getUsername(), message))); return CompletableFuture.supplyAsync(() -> { client.sendMessage(target, message); return message; }); } @Override public ChatChannel getOrCreateChannel(String channelName) { synchronized (channels) { if (!channels.containsKey(channelName)) { channels.put(channelName, new ChatChannel(channelName)); } return channels.get(channelName); } } @Override public ChatChannelUser getOrCreateChatUser(String username, String channel, boolean isModerator) { synchronized (chatChannelUsersByChannelAndName) { String key = mapKey(username, channel); if (!chatChannelUsersByChannelAndName.containsKey(key)) { Optional<Player> optionalPlayer = playerService.getPlayerForUsername(username); ChatChannelUser chatChannelUser = new ChatChannelUser(username, isModerator); chatChannelUsersByChannelAndName.put(key, chatChannelUser); chatUserService.associatePlayerToChatUser(chatChannelUser, optionalPlayer.orElse(null)); } return chatChannelUsersByChannelAndName.get(key); } } @Override public void addUsersListener(String channelName, MapChangeListener<String, ChatChannelUser> listener) { getOrCreateChannel(channelName).addUsersListeners(listener); } @Override public void addChatUsersByNameListener(MapChangeListener<String, ChatChannelUser> listener) { synchronized (chatChannelUsersByChannelAndName) { JavaFxUtil.addListener(chatChannelUsersByChannelAndName, listener); } } @Override public void addChannelsListener(MapChangeListener<String, ChatChannel> listener) { JavaFxUtil.addListener(channels, listener); } @Override public void removeUsersListener(String channelName, MapChangeListener<String, ChatChannelUser> listener) { getOrCreateChannel(channelName).removeUserListener(listener); } @Override public void leaveChannel(String channelName) { client.removeChannel(channelName); } @Override public CompletableFuture<String> sendActionInBackground(String target, String action) { return CompletableFuture.supplyAsync(() -> { client.sendCtcpMessage(target, "ACTION " + action); return action; }); } @Override public void joinChannel(String channelName) { log.debug("Joining channel: {}", channelName); client.addChannel(channelName); } @Override public boolean isDefaultChannel(String channelName) { return defaultChannelName.equals(channelName); } @Override public void destroy() { close(); } public void close() { if (client != null) { client.shutdown(); } } @Override public ReadOnlyObjectProperty<ConnectionState> connectionStateProperty() { return connectionState; } @Override public void reconnect() { Set<String> currentChannels = channels.keySet(); client.reconnect(); currentChannels.forEach(this::joinChannel); } @Override public void whois(String username) { client.sendRawLine("WHOIS " + username); } @Override public void incrementUnreadMessagesCount(int delta) { eventBus.post(UpdateApplicationBadgeEvent.ofDelta(delta)); } @Override public ReadOnlyIntegerProperty unreadMessagesCount() { return unreadMessagesCount; } @Override public String getDefaultChannelName() { return defaultChannelName; } private void onModeratorSet(String channelName, String username) { getOrCreateChatUser(username, channelName, true).setModerator(true); } private String mapKey(String username, String channelName) { return username + channelName; } }
package com.instructure.canvasapi.api; import com.instructure.canvasapi.model.Assignment; import com.instructure.canvasapi.model.AssignmentGroup; import com.instructure.canvasapi.model.CanvasContext; import com.instructure.canvasapi.model.RubricCriterion; import com.instructure.canvasapi.model.ScheduleItem; import com.instructure.canvasapi.utilities.APIHelpers; import com.instructure.canvasapi.utilities.CanvasCallback; import com.instructure.canvasapi.utilities.CanvasRestAdapter; import java.util.Date; import java.util.List; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.http.Path; import retrofit.http.GET; import retrofit.http.PUT; import retrofit.http.Query; public class AssignmentAPI { private static String getAssignmentCacheFilename(long courseID, long assignmentID) { return "/courses/" + courseID + "/assignments/" + assignmentID; } private static String getAssignmentsListCacheFilename(long courseID) { return "/courses/" + courseID + "/assignments?include=submission"; } private static String getAssignmentGroupsListCacheFilename(long courseID) { return "/courses/" + courseID + "/assignments_groups"; } public interface AssignmentsInterface { @GET("/courses/{course_id}/assignments/{assignmentid}") void getAssignment(@Path("course_id") long course_id, @Path("assignmentid") long assignment_id, Callback<Assignment> callback); @GET("/courses/{course_id}/assignments?include[]=submission&include[]=rubric_assessment&needs_grading_count_by_section=true") void getAssignmentsList(@Path("course_id") long course_id, Callback<Assignment[]> callback); @GET("/{next}") void getNextPageAssignmentsList(@Path(value = "next", encode = false) String nextURL, Callback<Assignment[]>callback); @GET("/courses/{course_id}/assignment_groups") void getAssignmentGroupList(@Path("course_id") long course_id, Callback<AssignmentGroup[]> callback); @GET("/calendar_events/{event_id}") void getCalendarEvent(@Path("event_id") long event_id, Callback<ScheduleItem> callback); @GET("/calendar_events?start_date=1990-01-01&end_date=2099-12-31") void getCalendarEvents(@Query("context_codes[]") String context_id, Callback<ScheduleItem[]> callback); @PUT("/courses/{course_id}/assignments/{assignment_id}") void editAssignment(@Path("course_id") long courseId, @Path("assignment_id") long assignmentId, @Query("assignment[name]") String assignmentName, @Query("assignment[assignment_group_id]") Long assignmentGroupId, @Query(value = "assignment[submission_types][]", encodeName = false) String submissionTypes, @Query("assignment[peer_reviews]") Integer hasPeerReviews, @Query("assignment[group_category_id]") Long groupId, @Query("assignment[points_possible]") Double pointsPossible, @Query("assignment[grading_type]") String gradingType, @Query("assignment[due_at]") String dueAt, @Query("assignment[description]") String description, @Query("assignment[notify_of_update]") Integer notifyOfUpdate, @Query("assignment[unlock_at]")String unlockAt, @Query("assignment[lock_at]") String lockAt, @Query(value = "assignment[html_url]", encodeName = false) String htmlUrl, @Query(value = "assignment[url]", encodeName = false) String url, @Query("assignment[quiz_id]") Long quizId, Callback<Assignment> callback); } // Build Interface Helpers private static AssignmentsInterface buildInterface(CanvasCallback<?> callback, CanvasContext canvasContext) { RestAdapter restAdapter = CanvasRestAdapter.buildAdapter(callback, canvasContext); return restAdapter.create(AssignmentsInterface.class); } // API Calls public static void getAssignment(long courseID, long assignmentID, final CanvasCallback<Assignment> callback) { if (APIHelpers.paramIsNull(callback)) { return; } callback.readFromCache(getAssignmentCacheFilename(courseID, assignmentID)); buildInterface(callback, null).getAssignment(courseID, assignmentID, callback); } public static void getAssignmentsList(long courseID, final CanvasCallback<Assignment[]> callback) { if (APIHelpers.paramIsNull(callback)) { return; } callback.readFromCache(getAssignmentsListCacheFilename(courseID)); buildInterface(callback, null).getAssignmentsList(courseID, callback); } public static void getNextPageAssignmentsList(CanvasCallback<Assignment[]> callback, String nextURL){ if (APIHelpers.paramIsNull(callback, nextURL)) return; callback.setIsNextPage(true); buildInterface(callback, null).getNextPageAssignmentsList(nextURL, callback); } public static void getAssignmentGroupsList(long courseID, final CanvasCallback<AssignmentGroup[]> callback) { if (APIHelpers.paramIsNull(callback)) { return; } callback.readFromCache(getAssignmentGroupsListCacheFilename(courseID)); buildInterface(callback, null).getAssignmentGroupList(courseID, callback); } /* * @deprecated Use editAssignment(Assignment editedAssignment, Boolean notifyOfUpdate, final CanvasCallback<Assignment> callback) * @param assignment (Required) * @param callback (Required) * @param assignmentName (Optional) * @param assignmentGroupId (Optional) * @param submissionTypes (Optional) * @param hasPeerReviews (Optional) * @param groupId (Optional) * @param pointsPossible (Optional) * @param gradingType (Optional) * @param dateDueAt (Optional) * @param description (Optional) * @param notifyOfUpdate (Optional) * @param dateUnlockAt (Optional) * @param dateLockAt (Optional) * */ @Deprecated public static void editAssignment(Assignment assignment, String assignmentName, Long assignmentGroupId, Assignment.SUBMISSION_TYPE[] submissionTypes, Boolean hasPeerReviews, Long groupId, Double pointsPossible, Assignment.GRADING_TYPE gradingType, Date dateDueAt, String description, boolean notifyOfUpdate, Date dateUnlockAt, Date dateLockAt, final CanvasCallback<Assignment> callback){ if(APIHelpers.paramIsNull(callback, assignment)){return;} String dueAt = APIHelpers.dateToString(dateDueAt); String unlockAt = APIHelpers.dateToString(dateUnlockAt); String lockAt = APIHelpers.dateToString(dateLockAt); String newSubmissionTypes = submissionTypeArrayToAPIQueryString(submissionTypes); String newGradingType = Assignment.gradingTypeToAPIString(gradingType); Integer newHasPeerReviews = (hasPeerReviews == null) ? null : APIHelpers.booleanToInt(hasPeerReviews); Integer newNotifyOfUpdate = APIHelpers.booleanToInt(notifyOfUpdate); buildInterface(callback, null).editAssignment(assignment.getCourseId(), assignment.getId(), assignmentName, assignmentGroupId, newSubmissionTypes, newHasPeerReviews, groupId, pointsPossible, newGradingType,dueAt,description,newNotifyOfUpdate,unlockAt,lockAt,null, null, null, callback ); } public static void editAssignment(Assignment editedAssignment, Boolean notifyOfUpdate, final CanvasCallback<Assignment> callback){ Assignment.SUBMISSION_TYPE[] arrayOfSubmissionTypes = editedAssignment.getSubmissionTypes().toArray(new Assignment.SUBMISSION_TYPE[editedAssignment.getSubmissionTypes().size()]); String[] arrayOfAllowedExtensions = editedAssignment.getAllowedExtensions().toArray(new String[editedAssignment.getAllowedExtensions().size()]); editAssignment(editedAssignment.getCourseId(), editedAssignment.getId(), editedAssignment.getName(), editedAssignment.getDescription(), arrayOfSubmissionTypes, editedAssignment.getDueDate(), editedAssignment.getPointsPossible(), editedAssignment.getGradingType(), editedAssignment.getHtmlUrl(), editedAssignment.getUrl(), editedAssignment.getQuizId(), editedAssignment.getRubric(), arrayOfAllowedExtensions, editedAssignment.getAssignmentGroupId(), editedAssignment.hasPeerReviews(), editedAssignment.getlockAtDate(), editedAssignment.getUnlockAt(), null, notifyOfUpdate, callback); } private static void editAssignment(long courseId, long assignmentId, String name, String description, Assignment.SUBMISSION_TYPE[] submissionTypes, Date dueAt, double pointsPossible, Assignment.GRADING_TYPE gradingType, String htmlUrl, String url, Long quizId, List<RubricCriterion> rubric, String[] allowedExtensions, Long assignmentGroupId, Boolean hasPeerReviews, Date lockAt, Date unlockAt, Long groupCategoryId, boolean notifyOfUpdate, final CanvasCallback<Assignment> callback){ String stringDueAt = APIHelpers.dateToString(dueAt); String stringUnlockAt = APIHelpers.dateToString(unlockAt); String stringLockAt = APIHelpers.dateToString(lockAt); String newSubmissionTypes = submissionTypeArrayToAPIQueryString(submissionTypes); String newGradingType = Assignment.gradingTypeToAPIString(gradingType); Integer newHasPeerReviews = (hasPeerReviews == null) ? null : APIHelpers.booleanToInt(hasPeerReviews); Integer newNotifyOfUpdate = APIHelpers.booleanToInt(notifyOfUpdate); buildInterface(callback, null).editAssignment(courseId, assignmentId, name, assignmentGroupId, newSubmissionTypes, newHasPeerReviews, groupCategoryId, pointsPossible, newGradingType, stringDueAt, description, newNotifyOfUpdate, stringUnlockAt, stringLockAt, htmlUrl, url, quizId, callback); } /* *Converts a SUBMISSION_TYPE[] to a queryString for the API */ private static String submissionTypeArrayToAPIQueryString(Assignment.SUBMISSION_TYPE[] submissionTypes){ if(submissionTypes == null || submissionTypes.length == 0){ return null; } String submissionTypesQueryString = ""; for(int i =0; i < submissionTypes.length; i++){ submissionTypesQueryString += Assignment.submissionTypeToAPIString(submissionTypes[i]); if(i < submissionTypes.length -1){ submissionTypesQueryString += "&assignment[submission_types][]="; } } return submissionTypesQueryString; } }
package com.jayway.awaitility.core; import static com.jayway.awaitility.Duration.SAME_AS_POLL_INTERVAL; import java.lang.reflect.Method; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import org.hamcrest.Matcher; import com.jayway.awaitility.Duration; /** * A factory for creating {@link Condition} objects. It's not recommended to * instantiate this class directly. */ public class ConditionFactory { /** The timeout. */ private final Duration timeout; /** The poll interval. */ private final Duration pollInterval; /** The catch uncaught exceptions. */ private final boolean catchUncaughtExceptions; /** The alias. */ private final String alias; /** The poll delay. */ private final Duration pollDelay; /** * Instantiates a new condition factory. * * @param alias * the alias * @param timeout * the timeout * @param pollInterval * the poll interval * @param pollDelay * The poll delay * @param catchUncaughtExceptions * the catch uncaught exceptions */ public ConditionFactory(String alias, Duration timeout, Duration pollInterval, Duration pollDelay, boolean catchUncaughtExceptions) { if (pollInterval == null) { throw new IllegalArgumentException("pollInterval cannot be null"); } if (timeout == null) { throw new IllegalArgumentException("timeout cannot be null"); } if (pollDelay == null) { throw new IllegalArgumentException("pollDelay cannot be null"); } this.alias = alias; this.timeout = timeout; this.pollInterval = pollInterval; this.catchUncaughtExceptions = catchUncaughtExceptions; this.pollDelay = pollDelay; } /** * Instantiates a new condition factory. * * @param timeout * the timeout * @param pollInterval * the poll interval * @param pollDelay * The delay before the polling starts * @param catchUncaughtExceptions * the catch uncaught exceptions */ public ConditionFactory(Duration timeout, Duration pollInterval, Duration pollDelay, boolean catchUncaughtExceptions) { this(null, timeout, pollInterval, pollInterval, catchUncaughtExceptions); } /** * Await at most <code>timeout</code> before throwing a timeout exception. * * @param timeout * the timeout * @return the condition factory */ public ConditionFactory andWithTimeout(Duration timeout) { return new ConditionFactory(alias, timeout, pollInterval, pollInterval, catchUncaughtExceptions); } /** * Await at most <code>timeout</code> before throwing a timeout exception. * * @param timeout * the timeout * @return the condition factory */ public ConditionFactory atMost(Duration timeout) { return new ConditionFactory(alias, timeout, pollInterval, pollInterval, catchUncaughtExceptions); } /** * Await forever until the condition is satisfied. Caution: You can block * subsequent tests and the entire build can hang indefinitely, it's * recommended to always use a timeout. * * @return the condition factory */ public ConditionFactory forever() { return new ConditionFactory(alias, Duration.FOREVER, pollInterval, pollInterval, catchUncaughtExceptions); } /** * Specify the polling interval Awaitility will use for this await * statement. This means the frequency in which the condition is checked for * completion. * <p> * Note that the poll delay will be automatically set as to the same value * as the interval unless it's specified explicitly using * {@link #withPollDelay(Duration)}, {@link #withPollDelay(long, TimeUnit)} * or {@link ConditionFactory#andWithPollDelay(Duration), or * ConditionFactory#andWithPollDelay(long, TimeUnit)}. * </p> * * @param pollInterval * the poll interval * @return the condition factory */ public ConditionFactory andWithPollInterval(Duration pollInterval) { return new ConditionFactory(alias, timeout, pollInterval, pollInterval, catchUncaughtExceptions); } /** * Await at most <code>timeout</code> before throwing a timeout exception. * * @param timeout * the timeout * @param unit * the unit * @return the condition factory */ public ConditionFactory andWithTimeout(long timeout, TimeUnit unit) { return new ConditionFactory(alias, new Duration(timeout, unit), pollInterval, pollInterval, catchUncaughtExceptions); } /** * Specify the delay that will be used before Awaitility starts polling for * the result the first time. If you don't specify a poll delay explicitly * it'll be the same as the poll interval. * * * @param delay * the delay * @param unit * the unit * @return the condition factory */ public ConditionFactory andWithPollDelay(long delay, TimeUnit unit) { return new ConditionFactory(alias, this.timeout, pollInterval, new Duration(delay, unit), catchUncaughtExceptions); } /** * Specify the delay that will be used before Awaitility starts polling for * the result the first time. If you don't specify a poll delay explicitly * it'll be the same as the poll interval. * * * @param pollDelay * the poll delay * @return the condition factory */ public ConditionFactory andWithPollDelay(Duration pollDelay) { return new ConditionFactory(alias, this.timeout, pollInterval, pollDelay, catchUncaughtExceptions); } /** * Await at most <code>timeout</code> before throwing a timeout exception. * * @param timeout * the timeout * @param unit * the unit * @return the condition factory */ public ConditionFactory atMost(long timeout, TimeUnit unit) { return new ConditionFactory(alias, new Duration(timeout, unit), pollInterval, pollInterval, catchUncaughtExceptions); } /** * Specify the polling interval Awaitility will use for this await * statement. This means the frequency in which the condition is checked for * completion. * * <p> * Note that the poll delay will be automatically set as to the same value * as the interval unless it's specified explicitly using * {@link #withPollDelay(Duration)}, {@link #withPollDelay(long, TimeUnit)} * or {@link ConditionFactory#andWithPollDelay(Duration), or * ConditionFactory#andWithPollDelay(long, TimeUnit)}. * </p> * * * @param pollInterval * the poll interval * @param unit * the unit * @return the condition factory */ public ConditionFactory andWithPollInterval(long pollInterval, TimeUnit unit) { return new ConditionFactory(alias, timeout, new Duration(pollInterval, unit), pollDelay, catchUncaughtExceptions); } /** * Instruct Awaitility to catch uncaught exceptions from other threads. This * is useful in multi-threaded systems when you want your test to fail * regardless of which thread throwing the exception. Default is * <code>true</code>. * * @return the condition factory */ public ConditionFactory andCatchUncaughtExceptions() { return new ConditionFactory(alias, timeout, pollInterval, pollInterval, true); } /** * Await for an asynchronous operation. This method returns the same * {@link ConditionFactory} instance and is used only to get a more * fluent-like syntax. * * @return the condition factory * @throws Exception * the exception */ public ConditionFactory await() throws Exception { return this; } /** * Await for an asynchronous operation and give this await instance a * particular name. This is useful in cases when you have several await * statements in one test and you want to know which one that fails (the * alias will be shown if a timeout exception occurs). * * @param alias * the alias * @return the condition factory * @throws Exception * the exception */ public ConditionFactory await(String alias) throws Exception { return new ConditionFactory(alias, timeout, pollInterval, pollInterval, catchUncaughtExceptions); } /** * A method to increase the readability of the Awaitility DSL. It simply * returns the same condition factory instance. * * @return the condition factory * @throws Exception * the exception */ public ConditionFactory and() throws Exception { return this; } /** * Don't catch uncaught exceptions in other threads. This will <i>not</i> * make the await statement fail if exceptions occur in other threads. * * @return the condition factory */ public ConditionFactory andDontCatchUncaughtExceptions() { return new ConditionFactory(timeout, pollInterval, pollDelay, false); } /** * Specify the condition that must be met when waiting for a method call. * E.g. * * <pre> * await().until(callTo(orderService).size(), is(greaterThan(2))); * </pre> * * @param <T> * the generic type * @param ignore * the return value of the method call * @param matcher * The condition that must be met when * @throws Exception * the exception */ public <T> void until(T ignore, final Matcher<T> matcher) throws Exception { until(new MethodCaller<T>(MethodCallRecorder.getLastTarget(), MethodCallRecorder.getLastMethod(), MethodCallRecorder.getLastArgs()), matcher); } /** * Await until a {@link Callable} supplies a value matching the specified * {@link Matcher}. E.g. * * <pre> * await().until(numberOfPersons(), is(greaterThan(2))); * </pre> * * where "numberOfPersons()" returns a standard {@link Callable}: * * <pre> * private Callable&lt;Integer&gt; numberOfPersons() { * return new Callable&lt;Integer&gt;() { * public Integer call() throws Exception { * return personRepository.size(); * } * }; * } * </pre> * * Using a generic {@link Callable} as done by using this version of "until" * allows you to reuse the "numberOfPersons()" definition in multiple await * statements. I.e. you can easily create another await statement (perhaps * in a different test case) using e.g. * * <pre> * await().until(numberOfPersons(), is(equalTo(6))); * </pre> * * @param <T> * the generic type * @param supplier * the supplier that is responsible for getting the value that * should be matched. * @param matcher * the matcher The hamcrest matcher that checks whether the * condition is fulfilled. * @throws Exception * the exception */ public <T> void until(final Callable<T> supplier, final Matcher<T> matcher) throws Exception { if (supplier == null) { throw new IllegalArgumentException("You must specify a supplier (was null)."); } if (matcher == null) { throw new IllegalArgumentException("You must specify a matcher (was null)."); } until(new ConditionEvaluator() { public Boolean call() throws Exception { return matcher.matches(supplier.call()); } }); } /** * Await until a {@link Callable} returns <code>true</code>. This is method * is not as generic as the other variants of "until" but it allows for a * more precise and in some cases even more english-like syntax. E.g. * * <pre> * await().until(numberOfPersonsIsEqualToThree()); * </pre> * * where "numberOfPersonsIsEqualToThree()" returns a standard * {@link Callable} of type {@link Boolean}: * * <pre> * private Callable&lt;Boolean&gt; numberOfPersons() { * return new Callable&lt;Boolean&gt;() { * public Boolean call() throws Exception { * return personRepository.size() == 3; * } * }; * } * * @param <T> * the generic type * @param conditionEvaluator * the condition evaluator * @throws Exception * the exception */ public <T> void until(Callable<Boolean> conditionEvaluator) throws Exception { Duration pollDelayToUse = pollDelay == SAME_AS_POLL_INTERVAL ? pollInterval : pollDelay; Condition condition = new AwaitConditionImpl(alias, timeout, conditionEvaluator, pollInterval, pollDelayToUse); if (catchUncaughtExceptions) { condition.andCatchAllUncaughtExceptions(); } condition.await(); } /** * The Class MethodCaller. * * @param <T> * the generic type */ static class MethodCaller<T> implements Callable<T> { /** The target. */ private final Object target; /** The method. */ private final Method method; /** The args. */ private final Object[] args; /** * Instantiates a new method caller. * * @param target * the target * @param method * the method * @param args * the args */ public MethodCaller(Object target, Method method, Object[] args) { this.target = target; this.method = method; this.args = args; method.setAccessible(true); } /* * (non-Javadoc) * * @see java.util.concurrent.Callable#call() */ @SuppressWarnings("unchecked") public T call() throws Exception { return (T) method.invoke(target, args); } } }
package com.neverwinterdp.scribengin; import java.io.IOException; import java.nio.ByteBuffer; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import kafka.api.FetchRequest; import kafka.api.FetchRequestBuilder; import kafka.api.PartitionOffsetRequestInfo; import kafka.cluster.Broker; import kafka.common.ErrorMapping; import kafka.common.TopicAndPartition; import kafka.javaapi.FetchResponse; import kafka.javaapi.OffsetRequest; import kafka.javaapi.OffsetResponse; import kafka.javaapi.PartitionMetadata; import kafka.javaapi.TopicMetadata; import kafka.javaapi.TopicMetadataRequest; import kafka.javaapi.consumer.SimpleConsumer; import kafka.message.MessageAndOffset; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.log4j.Logger; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; public class ScribeConsumer { // Random comments: // Unique define a partition. Client name + topic name + offset // java -cp scribengin-uber-0.0.1-SNAPSHOT.jar com.neverwinterdp.scribengin.ScribeConsumer --broker-lst HOST1:PORT1,HOST2:PORT2 --checkpoint_interval 100 --partition 0 --topic scribe // checkout src/main/java/com/neverwinterdp/scribengin/ScribeConsumer.java // checkout org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter // checkout EtlMultiOutputCommitter in Camus // /usr/lib/kafka/bin/kafka-console-producer.sh --topic scribe --broker-list 10.0.2.15:9092 private static final String PRE_COMMIT_PATH_PREFIX = "/tmp"; private static final String COMMIT_PATH_PREFIX = "/user/kxae"; private static final Logger LOG = Logger.getLogger(ScribeConsumer.class.getName()); private String currTmpDataPath; private String currDataPath; private AbstractScribeCommitLogFactory scribeCommitLogFactory; private AbstractFileSystemFactory fileSystemFactory; private List<HostPort> replicaBrokers; // list of (host:port)s @Parameter(names = {"-"+Constants.OPT_KAFKA_TOPIC, "--"+Constants.OPT_KAFKA_TOPIC}) private String topic; @Parameter(names = {"-"+Constants.OPT_PARTITION, "--"+Constants.OPT_PARTITION}) private int partition; private long lastCommittedOffset; private long offset; // offset is on a per line basis. starts on the last valid offset @Parameter(names = {"-"+Constants.OPT_BROKER_LIST, "--"+Constants.OPT_BROKER_LIST}, variableArity = true) private List<HostPort> brokerList; // list of (host:port)s @Parameter(names = {"-"+Constants.OPT_CHECK_POINT_TIMER, "--"+Constants.OPT_CHECK_POINT_TIMER}, description="Check point interval in milliseconds") private long commitCheckPointInterval; private SimpleConsumer consumer; //private FileSystem fs; private Timer checkPointIntervalTimer; public ScribeConsumer() { checkPointIntervalTimer = new Timer(); replicaBrokers = new ArrayList<HostPort>(); } public void setScribeCommitLogFactory(AbstractScribeCommitLogFactory factory) { scribeCommitLogFactory = factory; } public void setFileSystemFactory(AbstractFileSystemFactory factory) { fileSystemFactory = factory; } public boolean init() throws IOException { boolean r = true; PartitionMetadata metadata = findLeader(brokerList, topic, partition); if (metadata == null) { r = false; LOG.error("Can't find meta data for Topic: " + topic + " partition: " + partition + ". In fact, meta is null."); } if (metadata.leader() == null) { r = false; LOG.error("Can't find meta data for Topic: " + topic + " partition: " + partition); } if (r) { storeReplicaBrokers(metadata); consumer = new SimpleConsumer( metadata.leader().host(), metadata.leader().port(), 10000, // timeout 64*1024, // buffersize getClientName()); scheduleCommitTimer(); } return r; } private void scheduleCommitTimer() { checkPointIntervalTimer.schedule(new TimerTask() { @Override public void run() { commit(); } }, commitCheckPointInterval); } private void commitData(String src, String dest) { FileSystem fs = null; try { fs = fileSystemFactory.build(); fs.rename(new Path(src), new Path(dest)); } catch (IOException e) { //TODO : LOG e.printStackTrace(); } finally { if (fs != null) { try { fs.close(); } catch (IOException e) { //TODO : LOG e.printStackTrace(); } } } } private synchronized void commit() { System.out.println(">> committing"); if (lastCommittedOffset != offset) { //Commit try { // First record the to-be taken action in the WAL. // Then, mv the tmp data file to it's location. long startOffset = lastCommittedOffset + 1; long endOffset = offset; System.out.println("\tstartOffset : " + String.valueOf(startOffset)); //xxx System.out.println("\tendOffset : " + String.valueOf(endOffset)); //xxx System.out.println("\ttmpDataPath : " + currTmpDataPath); //xxx System.out.println("\tDataPath : " + currDataPath); //xxx ScribeCommitLog log = scribeCommitLogFactory.build(); log.record(startOffset, endOffset, currTmpDataPath, currDataPath); commitData(currTmpDataPath, currDataPath); lastCommittedOffset = offset; generateTmpAndDestDataPaths(); } catch (IOException e) { // TODO : LOG this error e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO : LOG this error e.printStackTrace(); } } scheduleCommitTimer(); } private String getClientName() { StringBuilder sb = new StringBuilder(); sb.append("scribe_"); sb.append(topic); sb.append("_"); sb.append(partition); String r = sb.toString(); return r; } private String getCommitLogAbsPath() { return PRE_COMMIT_PATH_PREFIX + "/" + getClientName() + ".log"; } private void generateTmpAndDestDataPaths() { StringBuilder sb = new StringBuilder(); long ts = System.currentTimeMillis()/1000L; sb.append(PRE_COMMIT_PATH_PREFIX) .append("/scribe.data") .append(".") .append(ts); this.currTmpDataPath = sb.toString(); sb = new StringBuilder(); sb.append(COMMIT_PATH_PREFIX) .append("/scribe.data") .append(".") .append(ts); this.currDataPath = sb.toString(); } private String getTmpDataPathPattern() { StringBuilder sb = new StringBuilder(); sb.append(PRE_COMMIT_PATH_PREFIX) .append("/scribe.data") .append(".") .append("*"); return sb.toString(); } private long getLatestOffsetFromKafka(String topic, int partition, long startTime) { TopicAndPartition tp = new TopicAndPartition(topic, partition); Map<TopicAndPartition, PartitionOffsetRequestInfo> requestInfo = new HashMap<TopicAndPartition, PartitionOffsetRequestInfo>(); requestInfo.put(tp, new PartitionOffsetRequestInfo(startTime, 1)); OffsetRequest req = new OffsetRequest( requestInfo, kafka.api.OffsetRequest.CurrentVersion(), getClientName()); OffsetResponse resp = consumer.getOffsetsBefore(req); if (resp.hasError()) { System.out.println("error when fetching offset: " + resp.errorCode(topic, partition)); //xxx // In case you wonder what the error code really means. // System.out.println("OffsetOutOfRangeCode()" + ErrorMapping.OffsetOutOfRangeCode()); // System.out.println("BrokerNotAvailableCode()" + ErrorMapping.BrokerNotAvailableCode()); // System.out.println("InvalidFetchSizeCode()" + ErrorMapping.InvalidFetchSizeCode()); // System.out.println("InvalidMessageCode()" + ErrorMapping.InvalidMessageCode()); // System.out.println("LeaderNotAvailableCode()" + ErrorMapping.LeaderNotAvailableCode()); // System.out.println("MessageSizeTooLargeCode()" + ErrorMapping.MessageSizeTooLargeCode()); // System.out.println("NotLeaderForPartitionCode()" + ErrorMapping.NotLeaderForPartitionCode()); // System.out.println("OffsetMetadataTooLargeCode()" + ErrorMapping.OffsetMetadataTooLargeCode()); // System.out.println("ReplicaNotAvailableCode()" + ErrorMapping.ReplicaNotAvailableCode()); // System.out.println("RequestTimedOutCode()" + ErrorMapping.RequestTimedOutCode()); // System.out.println("StaleControllerEpochCode()" + ErrorMapping.StaleControllerEpochCode()); // System.out.println("UnknownCode()" + ErrorMapping.UnknownCode()); // System.out.println("UnknownTopicOrPartitionCode()" + ErrorMapping.UnknownTopicOrPartitionCode()); //LOG.error("error when fetching offset: " + resp.errorcode(topic, partition)); return 0; } return resp.offsets(topic, partition)[0]; } private void DeleteUncommittedData() throws IOException { FileSystem fs = fileSystemFactory.build(); // Corrupted log file // Clean up. Delete the tmp data file if present. FileStatus[] fileStatusArry = fs.globStatus(new Path(getTmpDataPathPattern())); for(int i = 0; i < fileStatusArry.length; i++) { FileStatus fileStatus = fileStatusArry[i]; fs.delete( fileStatus.getPath() ); } fs.close(); } private ScribeLogEntry getLatestValidEntry(ScribeCommitLog log) { ScribeLogEntry entry = null; try { do { entry = log.getLatestEntry(); } while (entry != null && !entry.isCheckSumValid()); } catch (NoSuchAlgorithmException ex) { //TODO log } return entry; } private long getLatestOffsetFromCommitLog() { // Here's where we do recovery. long r = -1; ScribeLogEntry entry = null; try { ScribeCommitLog log = scribeCommitLogFactory.build(); log.read(); entry = log.getLatestEntry(); if (entry.isCheckSumValid()) { FileSystem fs = fileSystemFactory.build(); String tmpDataFilePath = entry.getSrcPath(); if (fs.exists(new Path(tmpDataFilePath))) { // mv to the dest commitData(tmpDataFilePath, entry.getDestPath()); } else { // Data has been committed // Or, it never got around to write to the log. // Delete tmp data file just in case. DeleteUncommittedData(); } } else { DeleteUncommittedData(); entry = getLatestValidEntry(log); } } catch (IOException e) { //TODO: log.warn e.printStackTrace(); } catch (NoSuchAlgorithmException e) { //TODO: log.warn e.printStackTrace(); } if (entry != null) { r = entry.getEndOffset(); } return r; } private long getLatestOffset(String topic, int partition, long startTime) { long offsetFromCommitLog = getLatestOffsetFromCommitLog(); System.out.println(" getLatestOffsetFromCommitLog >>>> " + offsetFromCommitLog); //xxx long offsetFromKafka = getLatestOffsetFromKafka(topic, partition, startTime); long r; if (offsetFromCommitLog == -1) { r = offsetFromKafka; } else if (offsetFromCommitLog < offsetFromKafka) { r = offsetFromCommitLog; } else if (offsetFromCommitLog == offsetFromKafka) { r = offsetFromKafka; } else { // offsetFromCommitLog > offsetFromKafka // TODO: log.warn. Someone is screwing with kafka's offset r = offsetFromKafka; } return r; } private PartitionMetadata findLeader(List<HostPort> seedBrokers, String topic, int partition) { PartitionMetadata returnMetaData = null; for (HostPort broker: seedBrokers) { SimpleConsumer consumer = null; String seed = broker.getHost(); int port = broker.getPort(); try { consumer = new SimpleConsumer(seed, port, 100000, 64 * 1024, "leaderLookup"); List<String> topics = Collections.singletonList(topic); TopicMetadataRequest req = new TopicMetadataRequest(topics); kafka.javaapi.TopicMetadataResponse resp = consumer.send(req); List<TopicMetadata> metaData = resp.topicsMetadata(); for (TopicMetadata item : metaData) { for (PartitionMetadata part : item.partitionsMetadata()) { if (part.partitionId() == partition) { returnMetaData = part; return returnMetaData; } } } } catch (Exception e) { LOG.error("Error communicating with Broker " + seed + ":" + port + " while trying to find leader for " + topic + ", " + partition + " | Reason: " + e); } finally { if (consumer != null) consumer.close(); } } return returnMetaData; } private HostPort findNewLeader(String oldHost, int oldPort) throws LostLeadershipException { for (int i = 0; i < 3; i++) { boolean goToSleep = false; PartitionMetadata metadata = findLeader(replicaBrokers, topic, partition); if (metadata == null) { goToSleep = true; } else if (metadata.leader() == null) { goToSleep = true; } else if (oldHost.equalsIgnoreCase(metadata.leader().host()) && oldPort == metadata.leader().port()) { // first time through if the leader hasn't changed give ZooKeeper a second to recover // second time, assume the broker did recover before failover, or it was a non-Broker issue goToSleep = true; } else { return new HostPort(metadata.leader().host(), metadata.leader().port()); } if (goToSleep) { try { Thread.sleep(1000); } catch (InterruptedException ie) { } } } // Can't recover from a leadership disappearance. throw new LostLeadershipException(); } private void storeReplicaBrokers(PartitionMetadata metadata) { replicaBrokers.clear(); for (Broker replica: metadata.replicas()) { replicaBrokers.add(new HostPort(replica.host(), replica.port())); } } public void run() throws IOException, LostLeadershipException { generateTmpAndDestDataPaths(); lastCommittedOffset = getLatestOffset(topic, partition, kafka.api.OffsetRequest.LatestTime()); offset = lastCommittedOffset; System.out.println(">> lastCommittedOffset: " + lastCommittedOffset); //xxx while (true) { System.out.println(">> offset: " + offset); //xxx FetchRequest req = new FetchRequestBuilder() .clientId(getClientName()) .addFetch(topic, partition, offset, 100000) .build(); FetchResponse resp = consumer.fetch(req); if (resp.hasError()) { //If we got an invalid offset, reset it by asking for the last element. //For all other errors, assume the worst and find ourselves a new leader from the replica. short code = resp.errorCode(topic, partition); LOG.info("Encounter error when fetching from consumer. Error Code: " + code); if (code == ErrorMapping.OffsetOutOfRangeCode()) { // We asked for an invalid offset. For simple case ask for the last element to reset System.out.println("inside errormap"); offset = getLatestOffsetFromKafka(topic, partition, kafka.api.OffsetRequest.LatestTime()); continue; } else { String oldHost = consumer.host(); int oldPort = consumer.port(); consumer.close(); consumer = null; HostPort newHostPort = findNewLeader(oldHost, oldPort); consumer = new SimpleConsumer( newHostPort.getHost(), newHostPort.getPort(), 10000, // timeout 64*1024, // buffersize getClientName()); continue; } } long msgReadCnt = 0; StringRecordWriter writer = new StringRecordWriter(currTmpDataPath); synchronized(this) { for (MessageAndOffset messageAndOffset : resp.messageSet(topic, partition)) { long currentOffset = messageAndOffset.offset(); if (currentOffset < offset) { System.out.println("Found an old offset: " + currentOffset + "Expecting: " + offset); continue; } offset = messageAndOffset.nextOffset(); ByteBuffer payload = messageAndOffset.message().payload(); byte[] bytes = new byte[payload.limit()]; payload.get(bytes); System.out.println(String.valueOf(messageAndOffset.offset()) + ": " + new String(bytes)); // Write to HDFS /tmp partition writer.write(bytes); msgReadCnt++; }// for } writer.close(); if (msgReadCnt == 0) { try { Thread.sleep(1000); //Didn't read anything, so go to sleep for awhile. } catch(InterruptedException e) { } } } // while } public static void main(String[] args) throws IOException { ScribeConsumer sc = new ScribeConsumer(); JCommander jc = new JCommander(sc); jc.addConverterFactory(new CustomConvertFactory()); jc.parse(args); sc.setScribeCommitLogFactory(ScribeCommitLogFactory.instance(sc.getCommitLogAbsPath())); sc.setFileSystemFactory(FileSystemFactory.instance()); boolean proceed = sc.init(); if (proceed) { try { sc.run(); } catch (LostLeadershipException e) { LOG.fatal("Leader went away. Couldn't find a new leader!"); } } } }
package eu.ydp.empiria.player.client; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.user.client.ui.ComplexPanel; import com.google.gwt.user.client.ui.RootPanel; import eu.ydp.empiria.player.client.controller.communication.DisplayOptions; import eu.ydp.empiria.player.client.controller.communication.FlowOptions; import eu.ydp.empiria.player.client.controller.delivery.DeliveryEngine; import eu.ydp.empiria.player.client.util.xml.document.XMLData; import eu.ydp.empiria.player.client.version.Version; import eu.ydp.empiria.player.client.view.ViewEngine; /** * Main class with player API * @author Krzysztof Langner */ public class Player { /** JavaScript object representing this java object */ private JavaScriptObject jsObject; /** Delivery engine do manage the assessment content */ public DeliveryEngine deliveryEngine; /** View engine maintains the view tasks */ private ViewEngine viewEngine; { logVersion(); } /** * constructor * @param id */ public Player(String id){ this.jsObject = JavaScriptObject.createFunction(); PlayerGinjector injector = GWT.create( PlayerGinjector.class ); viewEngine = injector.getViewEngine(); RootPanel root = RootPanel.get(id); viewEngine.mountView(root); deliveryEngine = injector.getDeliveryEngine(); deliveryEngine.init(jsObject); } public Player(ComplexPanel container){ this.jsObject = JavaScriptObject.createFunction(); PlayerGinjector injector = GWT.create( PlayerGinjector.class ); viewEngine = injector.getViewEngine(); viewEngine.mountView(container); deliveryEngine = injector.getDeliveryEngine(); deliveryEngine.init(jsObject); } public void loadExtension(JavaScriptObject extension){ deliveryEngine.loadExtension(extension); } public void loadExtension(String extension){ deliveryEngine.loadExtension(extension); } public void load(String url){ deliveryEngine.load(url); } public void load(XMLData assessmentData, XMLData[] itemsData){ deliveryEngine.load(assessmentData, itemsData); } /** * @return js object representing this player */ public JavaScriptObject getJavaScriptObject(){ return jsObject; } public void setFlowOptions(FlowOptions o){ deliveryEngine.setFlowOptions(o); } public void setDisplayOptions(DisplayOptions o){ deliveryEngine.setDisplayOptions(o); } public String getEngineMode(){ return deliveryEngine.getEngineMode(); } private void logVersion(){ String version = Version.getVersion(); String versionMessage = "EmpiriaPlayer ver. " + version; log(versionMessage); System.out.println(versionMessage); } private native void log(String message)/*-{ if (typeof console == 'object') console.log(message); }-*/; }
package com.ociweb.gl.test; import java.util.function.Supplier; import com.ociweb.gl.api.Builder; import com.ociweb.gl.api.ClientHostPortInstance; import com.ociweb.gl.api.GreenAppParallel; import com.ociweb.gl.api.GreenCommandChannel; import com.ociweb.gl.api.GreenRuntime; import com.ociweb.gl.api.HTTPResponseListener; import com.ociweb.gl.api.HTTPResponseReader; import com.ociweb.gl.api.HeaderWritable; import com.ociweb.gl.api.HeaderWriter; import com.ociweb.gl.api.PubSubMethodListener; import com.ociweb.gl.api.StartupListener; import com.ociweb.gl.api.TimeListener; import com.ociweb.gl.api.Writable; import com.ociweb.pronghorn.network.config.HTTPContentTypeDefaults; import com.ociweb.pronghorn.network.config.HTTPHeaderDefaults; import com.ociweb.pronghorn.pipe.ChannelReader; import com.ociweb.pronghorn.stage.scheduling.ElapsedTimeRecorder; import com.ociweb.pronghorn.util.Appendables; public class ParallelClientLoadTester implements GreenAppParallel { private final String route; private final boolean insecureClient; private final int parallelTracks; private final long cyclesPerTrack; private final long responseTimeoutNS; private final Integer telemetryPort; private final String telemetryHost; private final Long rate; private final int maxInFlight; private final int maxInFlightMask; private final ParallelClientLoadTesterOutput out; private final Supplier<Writable> post; private final int maxPayloadSize; private final HTTPContentTypeDefaults contentType; private final Supplier<HTTPResponseListener> validate; private final ClientHostPortInstance[] session; private final ElapsedTimeRecorder[] elapsedTime; private int trackId = 0; private long startupTime; private long durationNanos = 0; private final long[][] callTime; private final int[] inFlightHead; private final int[] inFlightTail; private static final String RESPONDER_NAME = "responder"; private static final String CALL_TOPIC = "makeCall"; private static final String PROGRESS_NAME = "progessor"; private static final String ENDERS_TOPIC = "end"; private static final String PROGRESS_TOPIC = "progress"; private static final int PUB_MSGS = 8000; private static final int PUB_MSGS_SIZE = 48; public ParallelClientLoadTester( int cyclesPerTrack, int port, String route, String post, boolean enableTelemetry) { this( new ParallelClientLoadTesterConfig(cyclesPerTrack, port, route, enableTelemetry), post != null ? new ParallelClientLoadTesterPayload(post) : null, new DefaultParallelClientLoadTesterOutput()); } public ParallelClientLoadTester( int parallelTracks, int cyclesPerTrack, int port, String route, String post, boolean enableTelemetry) { this( new ParallelClientLoadTesterConfig(parallelTracks, cyclesPerTrack, port, route, enableTelemetry), post != null ? new ParallelClientLoadTesterPayload(post) : null, new DefaultParallelClientLoadTesterOutput()); } public ParallelClientLoadTester( ParallelClientLoadTesterConfig config, ParallelClientLoadTesterPayload payload) { this(config, payload, new DefaultParallelClientLoadTesterOutput()); } public ParallelClientLoadTester( ParallelClientLoadTesterConfig config, ParallelClientLoadTesterPayload payload, ParallelClientLoadTesterOutput out) { this.route = config.route; this.telemetryPort = config.telemetryPort; this.telemetryHost = config.telemetryHost; this.parallelTracks = config.parallelTracks; this.durationNanos = config.durationNanos; this.insecureClient = config.insecureClient; this.responseTimeoutNS = config.responseTimeoutNS; this.cyclesPerTrack = config.cyclesPerTrack; this.rate = config.rate; //bit size mask pos //0 1 0 0 //1 2 1 0,1 //2 4 3 0,1,2,3 int maxInFlightBits = config.simultaneousRequestsPerTrackBits; this.maxInFlight = 1<< maxInFlightBits; this.maxInFlightMask = maxInFlight-1; this.callTime = new long[parallelTracks][maxInFlight]; this.inFlightHead = new int[parallelTracks]; this.inFlightTail = new int[parallelTracks]; this.session = new ClientHostPortInstance[parallelTracks]; this.elapsedTime = new ElapsedTimeRecorder[parallelTracks]; int i = parallelTracks; while (--i>=0) { session[i]=new ClientHostPortInstance(config.host,config.port); elapsedTime[i] = new ElapsedTimeRecorder(); } this.contentType = null==payload ? null : payload.contentType; this.maxPayloadSize = null==payload ? 256 : payload.maxPayloadSize; this.post = null==payload? null : payload.post; this.validate = null==payload? null : payload.validate; this.out = out; } @Override public void declareConfiguration(Builder builder) { if (insecureClient) { builder.useInsecureNetClient(); } else { builder.useNetClient(); } builder.setGlobalSLALatencyNS(20_000_000); if (telemetryPort != null) { if (null == this.telemetryHost) { builder.enableTelemetry(telemetryPort); } else { builder.enableTelemetry(telemetryHost, telemetryPort); } } builder.parallelTracks(session.length); if (rate != null) { builder.setDefaultRate(rate); } builder.definePrivateTopic(2+Math.max(8, maxInFlight) ,0, CALL_TOPIC, RESPONDER_NAME, RESPONDER_NAME); builder.defineUnScopedTopic(ENDERS_TOPIC); builder.defineUnScopedTopic(PROGRESS_TOPIC); if (responseTimeoutNS > 0) { Appendables.appendNearestTimeUnit(System.out.append("Checking for timeouts at this rate: "), responseTimeoutNS).append('\n'); builder.setTimerPulseRate(responseTimeoutNS / 1_000_000); } } @Override public void declareBehavior(final GreenRuntime runtime) { Progress progress = new Progress(runtime); runtime.registerListener(PROGRESS_NAME, progress) .SLALatencyNS(200_000_000)//due to use of System out and shutdown this is allowed more time .addSubscription(ENDERS_TOPIC, progress::enderMessage) .addSubscription(PROGRESS_TOPIC, progress::progressMessage); } private class Progress implements PubSubMethodListener, StartupListener { private final GreenCommandChannel cmd4; private final long[] finished = new long[parallelTracks]; //private final long[] sendAttempts = new long[parallelTracks]; //private final long[] sendFailures = new long[parallelTracks]; private final long[] timeouts = new long[parallelTracks]; //private final long[] responsesReceived = new long[parallelTracks]; private final long[] responsesInvalid = new long[parallelTracks]; private long totalTimeSum; private long sendAttemptsSum; private long sendFailuresSum; private long timeoutsSum; private long responsesReceivedSum; private long responsesInvalidSum; private int lastPercent = 0; private long lastTime = 0; private int enderCounter; Progress(GreenRuntime runtime) { this.cmd4 = runtime.newCommandChannel(); this.cmd4.ensureDynamicMessaging(Math.max(PUB_MSGS, maxInFlight), PUB_MSGS_SIZE); } @Override public void startup() { startupTime = System.nanoTime(); out.progress(0, 0, 0); } boolean enderMessage(CharSequence topic, ChannelReader payload) { if (topic.equals(ENDERS_TOPIC)) { if (payload.hasRemainingBytes()) { int track = payload.readPackedInt(); long totalTime = payload.readPackedLong(); long sendAttempts = payload.readPackedLong(); long sendFailures = payload.readPackedLong(); long timeouts = payload.readPackedLong(); long responsesReceived = payload.readPackedLong(); long responsesInvalid = payload.readPackedLong(); //System.err.println("end of track:"+track); totalTimeSum += totalTime; sendAttemptsSum += sendAttempts; sendFailuresSum += sendFailures; timeoutsSum += timeouts; responsesReceivedSum += responsesReceived; responsesInvalidSum += responsesInvalid; } if (++enderCounter == (parallelTracks + 1)) { //we add 1 for the progress of 100% ElapsedTimeRecorder etr = new ElapsedTimeRecorder(); int t = elapsedTime.length; while (--t >= 0) { etr.add(elapsedTime[t]); } long totalMessages = parallelTracks * cyclesPerTrack; long testDuration = System.nanoTime() - startupTime; long serverCallsPerSecond = (1_000_000_000L * totalMessages) / testDuration; out.end( etr, testDuration, totalMessages, totalTimeSum, serverCallsPerSecond, sendAttemptsSum, sendFailuresSum, timeoutsSum, responsesReceivedSum, responsesInvalidSum ); return cmd4.shutdown(); } } return true; } boolean progressMessage(CharSequence topic, ChannelReader payload) { int track = payload.readPackedInt(); long countDown = payload.readPackedLong(); //long sendAttempts = payload.readPackedInt(); //long sendFailures = payload.readPackedInt(); long timeouts = payload.readPackedInt(); //long responsesReceived = payload.readPackedInt(); long responsesInvalid = payload.readPackedInt(); this.finished[track] = cyclesPerTrack - countDown; //this.sendAttempts[track] = sendAttempts; //this.sendFailures[track] = sendFailures; this.timeouts[track] = timeouts; //this.responsesReceived[track] = responsesReceived; this.responsesInvalid[track] = responsesInvalid; long sumFinished = 0; //long sumSendAttempts = 0; //long sumSendFailures = 0; long sumTimeouts = 0; //long sumResponsesReceived = 0; long sumResponsesInvalid = 0; int i = parallelTracks; while (--i >= 0) { sumFinished += this.finished[i]; //sumSendAttempts += this.sendAttempts[track]; //sumSendFailures += this.sendFailures[track]; sumTimeouts += this.timeouts[track]; //sumResponsesReceived += this.responsesReceived[i]; sumResponsesInvalid += this.responsesInvalid[i]; } long totalRequests = cyclesPerTrack * parallelTracks; int percentDone = (int)((100L * sumFinished) / totalRequests); assert(percentDone>=0); long now = 0; //updates every half a second if ((percentDone != lastPercent && ((now = System.nanoTime()) - lastTime) > 500_000_000L) || 100L == percentDone) { out.progress(percentDone, sumTimeouts, sumResponsesInvalid); lastTime = now; lastPercent = percentDone; } if (100 == percentDone) { //System.err.println(Arrays.toString(finished)+" "+cyclesPerTrack+" "+parallelTracks); //System.err.println(); return cmd4.publishTopic(ENDERS_TOPIC); } return true; } } @Override public void declareParallelBehavior(GreenRuntime runtime) { final int track = trackId++; TrackHTTPResponseListener responder = new TrackHTTPResponseListener(runtime, track); runtime.registerListener(RESPONDER_NAME, responder) .addSubscription(CALL_TOPIC, responder::callMessage) .includeHTTPSession(session[track]); } private class TrackHTTPResponseListener implements HTTPResponseListener, TimeListener, StartupListener, PubSubMethodListener { private final GreenCommandChannel cmd3; private final int track; private final HTTPResponseListener validator; private final GreenCommandChannel cmd2; private final HeaderWritable header; private final Writable writer; private long countDown; private long totalTime; private long sendAttempts; private long sendFailures; private long timeouts; private long responsesInvalid; private long responsesReceived; private boolean lastResponseOk=true; TrackHTTPResponseListener(GreenRuntime runtime, int track) { this.track = track; countDown = cyclesPerTrack; cmd3 = runtime.newCommandChannel(); cmd3.ensureDynamicMessaging(Math.max(2+((durationNanos>0?2:1)*maxInFlight),PUB_MSGS), PUB_MSGS_SIZE); if (durationNanos > 0) { cmd3.ensureDelaySupport(); } this.header = contentType != null ? new HeaderWritable() { @Override public void write(HeaderWriter writer) { writer.write(HTTPHeaderDefaults.CONTENT_TYPE, contentType.contentType()); } } : null; this.writer = post != null ? post.get() : null; this.validator = validate != null ? validate.get() : null; this.cmd2 = runtime.newCommandChannel(); if (post != null) { cmd2.ensureHTTPClientRequesting(2+maxInFlight, maxPayloadSize + 1024); } else { cmd2.ensureHTTPClientRequesting(2+maxInFlight, 0); } } boolean callMessage(CharSequence topic, ChannelReader payload) { return makeCall(); } private boolean makeCall() { long now = System.nanoTime(); boolean wasSent; sendAttempts++; if (null==writer) { wasSent = cmd2.httpGet(session[track], route); } else if (header != null) { wasSent = cmd2.httpPost(session[track], route, header, writer); } else { wasSent = cmd2.httpPost(session[track], route, writer); } if (wasSent) { callTime[track][maxInFlightMask & inFlightHead[track]++] = now; } else { sendFailures++; } return wasSent; } @Override public void startup() { long now = System.currentTimeMillis(); int i = maxInFlight; while (--i>=0) { while(!cmd3.publishTopic(CALL_TOPIC)) { //must publish this many to get the world moving Thread.yield(); if ((System.currentTimeMillis()-now) > 10_000) { out.failedToStart(maxInFlight); cmd3.shutdown(); } } //must use message to startup the system } countDown--; //we launched 1 cycle for this track on startup. } @Override public boolean responseHTTP(HTTPResponseReader reader) { //if false we already closed this one and need to skip this part if (lastResponseOk) { boolean connectionClosed = reader.isConnectionClosed(); if (connectionClosed) { out.connectionClosed(track); } long duration = System.nanoTime() - callTime[track][maxInFlightMask & inFlightTail[track]++]; /* if (duration>20_000_000) { Appendables.appendValue( Appendables.appendNearestTimeUnit(System.err, duration) .append(" long call detected for ") ,(inFlightTail[track]-1)).append("\n"); } */ ElapsedTimeRecorder.record(elapsedTime[track], duration); totalTime+=duration; responsesReceived++; if (validator != null && !validator.responseHTTP(reader)) { responsesInvalid++; } } return lastResponseOk = nextCall(); } private boolean nextCall() { if ((0xFFFF & countDown) == 0) { cmd3.publishTopic(PROGRESS_TOPIC, writer-> { writer.writePackedInt(track); writer.writePackedLong(countDown); //writer.writePackedLong(sendAttempts); //writer.writePackedLong(sendFailures); writer.writePackedLong(timeouts); //writer.writePackedLong(responsesReceived); writer.writePackedLong(responsesInvalid); }); } boolean isOk = true; if (countDown >= maxInFlight) { //others are still in flight if (durationNanos > 0) { isOk = cmd3.delay(durationNanos); } if (isOk) { isOk = cmd3.publishTopic(CALL_TOPIC); } } else { if (0==countDown) { //only end after all the inFlightMessages have returned. isOk = cmd3.publishTopic(ENDERS_TOPIC, writer -> { writer.writePackedInt(track); writer.writePackedLong(totalTime); writer.writePackedLong(sendAttempts); writer.writePackedLong(sendFailures); writer.writePackedLong(timeouts); writer.writePackedLong(responsesReceived); writer.writePackedLong(responsesInvalid); }); //System.err.println("publish end of "+track); } } //upon failure should not count down if (isOk) { countDown } return isOk; } @Override public void timeEvent(long time, int iteration) { long callTimeValue = callTime[track][maxInFlightMask & inFlightTail[track]]; if (callTimeValue != 0) { long duration = System.nanoTime() - callTimeValue; if (duration > responseTimeoutNS) { Appendables.appendNearestTimeUnit(System.out.append("Failed response detected after timeout of: "), responseTimeoutNS).append('\n'); timeouts++; while (!nextCall()) {//must run now. Thread.yield(); } } } } } }
package nta.engine.cluster; import java.io.FileNotFoundException; import java.io.IOException; import java.util.*; import java.util.concurrent.ExecutionException; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import nta.catalog.CatalogClient; import nta.catalog.FragmentServInfo; import nta.catalog.TableMetaImpl; import nta.catalog.proto.CatalogProtos.TableDescProto; import nta.engine.MasterInterfaceProtos.ServerStatusProto; import nta.engine.MasterInterfaceProtos.ServerStatusProto.Disk; import nta.engine.QueryUnitId; import nta.engine.exception.UnknownWorkerException; import nta.engine.ipc.protocolrecords.Fragment; import nta.rpc.Callback; import nta.rpc.RemoteException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.BlockLocation; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; public class ClusterManager { private final int FRAG_DIST_THRESHOLD = 3; private final Log LOG = LogFactory.getLog(ClusterManager.class); public class WorkerInfo { public int availableProcessors; public long freeMemory; public long totalMemory; public int taskNum; public List<DiskInfo> disks = new ArrayList<DiskInfo>(); } public class DiskInfo { public long freeSpace; public long totalSpace; } private class FragmentAssignInfo implements Comparable<FragmentAssignInfo> { String serverName; int fragmentNum; public FragmentAssignInfo(String serverName, int fragmentNum) { this.serverName = serverName; this.fragmentNum = fragmentNum; } public FragmentAssignInfo updateFragmentNum() { this.fragmentNum++; return this; } @Override public int compareTo(FragmentAssignInfo o) { return this.fragmentNum - o.fragmentNum; } } private Configuration conf; private final WorkerCommunicator wc; private final CatalogClient catalog; private final LeafServerTracker tracker; private int clusterSize; private Map<String, List<String>> DNSNameToHostsMap; private Map<Fragment, FragmentServingInfo> servingInfoMap; private Random rand = new Random(System.currentTimeMillis()); private Map<String, Integer> resourcePool; private Set<String> failedWorkers; public ClusterManager(WorkerCommunicator wc, Configuration conf, LeafServerTracker tracker) throws IOException { this.wc = wc; this.conf = conf; this.catalog = new CatalogClient(this.conf); this.tracker = tracker; this.DNSNameToHostsMap = Maps.newConcurrentMap(); this.servingInfoMap = Maps.newConcurrentMap(); this.resourcePool = Maps.newConcurrentMap(); this.failedWorkers = Sets.newHashSet(); this.clusterSize = 0; } public WorkerInfo getWorkerInfo(String workerName) throws RemoteException, InterruptedException, ExecutionException, UnknownWorkerException { Callback<ServerStatusProto> callback = wc.getServerStatus(workerName); for (int i = 0; i < 3 && !callback.isDone(); i++) { Thread.sleep(100); } if (callback.isDone()) { ServerStatusProto status = callback.get(); ServerStatusProto.System system = status.getSystem(); WorkerInfo info = new WorkerInfo(); info.availableProcessors = system.getAvailableProcessors(); info.freeMemory = system.getFreeMemory(); info.totalMemory = system.getTotalMemory(); info.taskNum = status.getTaskNum(); for (Disk diskStatus : status.getDiskList()) { DiskInfo diskInfo = new DiskInfo(); diskInfo.freeSpace = diskStatus.getFreeSpace(); diskInfo.totalSpace = diskStatus.getTotalSpace(); info.disks.add(diskInfo); } return info; } else { LOG.error("Failed to get the resource information!!"); return null; } } public List<QueryUnitId> getProcessingQuery(String workerName) { return null; } public void updateOnlineWorker() { String DNSName; List<String> workers; DNSNameToHostsMap.clear(); clusterSize = 0; for (String worker : tracker.getMembers()) { DNSName = worker.split(":")[0]; if (DNSNameToHostsMap.containsKey(DNSName)) { workers = DNSNameToHostsMap.get(DNSName); } else { workers = new ArrayList<String>(); } workers.add(worker); workers.removeAll(failedWorkers); if (workers.size() > 0) { clusterSize += workers.size(); DNSNameToHostsMap.put(DNSName, workers); } } for (String failed : failedWorkers) { resourcePool.remove(failed); } } public void resetResourceInfo() throws UnknownWorkerException, InterruptedException, ExecutionException { WorkerInfo info; for (List<String> hosts : DNSNameToHostsMap.values()) { for (String host : hosts) { info = getWorkerInfo(host); //Preconditions.checkState(info.availableProcessors-info.taskNum >= 0); // TODO: correct free resource computation is required if (info.availableProcessors-info.taskNum > 0) { resourcePool.put(host, (info.availableProcessors-info.taskNum) * 30); } } } } public boolean existFreeResource() { return resourcePool.size() > 0; } public boolean hasFreeResource(String host) { return resourcePool.containsKey(host); } public void getResource(String host) { int resource = resourcePool.get(host); if (--resource == 0) { resourcePool.remove(host); } else { resourcePool.put(host, resource); } } public void addResource(String host) { if (resourcePool.containsKey(host)) { resourcePool.put(host, resourcePool.get(host).intValue()+1); } else { resourcePool.put(host, 1); } } public Map<String, List<String>> getOnlineWorkers() { return this.DNSNameToHostsMap; } public void updateFragmentServingInfo2(String table) throws IOException { TableDescProto td = (TableDescProto) catalog.getTableDesc(table).getProto(); FileSystem fs = FileSystem.get(conf); Path path = new Path(td.getPath()); Map<String, StoredBlockInfo> storedBlockInfoMap = ClusterManagerUtils.makeStoredBlockInfoForHosts(fs, path); Map<Fragment, FragmentServingInfo> assignMap = ClusterManagerUtils.assignFragments(td, storedBlockInfoMap.values()); this.servingInfoMap.putAll(assignMap); } public Map<Fragment, FragmentServingInfo> getServingInfoMap() { return this.servingInfoMap; } public FragmentServingInfo getServingInfo(Fragment fragment) { return this.servingInfoMap.get(fragment); } private String getRandomWorkerNameOfHost(String host) { List<String> workers = DNSNameToHostsMap.get(host); return workers.get(rand.nextInt(workers.size())); } private List<FragmentServInfo> getFragmentLocInfo(TableDescProto desc) throws IOException { int fileIdx, blockIdx; FileSystem fs = FileSystem.get(conf); Path path = new Path(desc.getPath()); FileStatus[] files = fs.listStatus(new Path(path + "/data")); if (files == null || files.length == 0) { throw new FileNotFoundException(path.toString() + "/data"); } BlockLocation[] blocks; String[] hosts; List<FragmentServInfo> fragmentInfoList = new ArrayList<FragmentServInfo>(); for (fileIdx = 0; fileIdx < files.length; fileIdx++) { blocks = fs.getFileBlockLocations(files[fileIdx], 0, files[fileIdx].getLen()); for (blockIdx = 0; blockIdx < blocks.length; blockIdx++) { hosts = blocks[blockIdx].getHosts(); // TODO: select the proper serving node for block Fragment fragment = new Fragment(desc.getId(), files[fileIdx].getPath(), new TableMetaImpl(desc.getMeta()), blocks[blockIdx].getOffset(), blocks[blockIdx].getLength()); fragmentInfoList.add(new FragmentServInfo(hosts[0], -1, fragment)); } } return fragmentInfoList; } /** * Select a random worker * * @return * @throws Exception */ public String getRandomHost() { int n = rand.nextInt(resourcePool.size()); Iterator<String> it = resourcePool.keySet().iterator(); for (int i = 0; i < n-1; i++) { it.next(); } String randomHost = it.next(); this.getResource(randomHost); return randomHost; } public synchronized Set<String> getFailedWorkers() { return this.failedWorkers; } public synchronized void addFailedWorker(String worker) { this.failedWorkers.add(worker); } public synchronized boolean isExist(String worker) { return this.failedWorkers.contains(worker); } public synchronized void removeFailedWorker(String worker) { this.failedWorkers.remove(worker); } }
package com.pump.swing.popup; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.util.Objects; import javax.swing.JSlider; import javax.swing.SwingUtilities; import javax.swing.plaf.basic.BasicSliderUI; import com.pump.graphics.vector.VectorImage; /** * This PopupTarget points to the thumb of a JSlider. Currently this only * supports a slider that uses a BasicSliderUI. */ public class SliderThumbPopupTarget implements PopupTarget { JSlider slider; public SliderThumbPopupTarget(JSlider slider) { Objects.requireNonNull(slider); this.slider = slider; getLocalThumbScreenRect(); } /** * Return the bounds of the slider thumb relative to the JSliders coordinate * system. */ protected Rectangle getLocalThumbScreenRect() { BasicSliderUI sliderUI = slider.getUI() instanceof BasicSliderUI ? (BasicSliderUI) slider.getUI() : null; if (sliderUI == null) throw new UnsupportedOperationException("This UI is unsupported " + slider.getUI().getClass().getName()); VectorImage img = new VectorImage(); Graphics2D g = img.createGraphics(); sliderUI.paintThumb(g); g.dispose(); return img.getBounds().getBounds(); } /** * Return the bounds of the slider thumb relative to the screen. */ @Override public Rectangle getScreenBounds() { Rectangle rect = getLocalThumbScreenRect(); Point p = new Point(0, 0); SwingUtilities.convertPointToScreen(p, slider); rect.x += p.x; rect.y += p.y; return rect; } }
package com.smallchill.core.beetl; import org.beetl.sql.core.InterceptorContext; import org.beetl.sql.ext.DebugInterceptor; import com.smallchill.core.constant.Cst; import com.smallchill.core.toolbox.kit.DateKit; /** * beetlsqlsql */ public class ReportInterceptor extends DebugInterceptor { @Override public void before(InterceptorContext ctx) { if (!Cst.me().isDevMode()) { return; } String sqlId = ctx.getSqlId(); if (this.isDebugEanble(sqlId)) { ctx.put("debug.time", System.currentTimeMillis()); } StringBuilder sb = new StringBuilder(); sb.append("\nBlade beetlsql .append(" : " + ctx.getSqlId().replaceAll("\\s+", " ")).append("\n") .append(" : " + ctx.getSql().replaceAll("\\s+", " ")).append("\n") .append(" : " + formatParas(ctx.getParas())) .append("\n"); RuntimeException ex = new RuntimeException(); StackTraceElement[] traces = ex.getStackTrace(); boolean found = false; for (StackTraceElement tr : traces) { if (!found && tr.getClassName().indexOf("SQLManager") != -1) { found = true; } if (found && !tr.getClassName().startsWith("org.beetl.sql.core") && !tr.getClassName().startsWith("com.sun")) { String className = tr.getClassName(); String mehodName = tr.getMethodName(); int line = tr.getLineNumber(); sb.append(" : " + className + "." + mehodName + "(" + tr.getFileName() + ":" + line + ")").append("\n"); break; } } ctx.put("debug.sb", sb); } @Override public void after(InterceptorContext ctx) { if (!Cst.me().isDevMode()) { return; } long time = System.currentTimeMillis(); long start = (Long) ctx.get("debug.time"); StringBuilder sb = (StringBuilder) ctx.get("debug.sb"); sb.append(" : " + (time - start) + "ms").append("\n"); if (ctx.isUpdate()) { sb.append(" : ["); if (ctx.getResult().getClass().isArray()) { int[] ret = (int[]) ctx.getResult(); for (int i = 0; i < ret.length; i++) { sb.append(ret[i]); if (i != ret.length - 1) { sb.append(","); } } } else { sb.append(ctx.getResult()); } sb.append("]"); } else { sb.append(" : ").append(ctx.getResult()).append(""); } sb.append("\n").append(" println(sb.toString()); } }
package com.strider.datadefender; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.regex.Pattern; import static java.lang.Double.parseDouble; import static java.util.regex.Pattern.compile; import org.apache.commons.collections.ListUtils; import org.apache.log4j.Logger; import static org.apache.log4j.Logger.getLogger; import opennlp.tools.util.Span; import com.strider.datadefender.database.IDBFactory; import com.strider.datadefender.database.metadata.IMetaData; import com.strider.datadefender.database.metadata.MatchMetaData; import com.strider.datadefender.database.sqlbuilder.ISQLBuilder; import com.strider.datadefender.functions.Utils; import com.strider.datadefender.report.ReportUtil; import com.strider.datadefender.specialcase.SpecialCase; import com.strider.datadefender.utils.CommonUtils; import com.strider.datadefender.utils.Score; /** * * @author Armenak Grigoryan */ public class DatabaseDiscoverer extends Discoverer { private static final Logger LOG = getLogger(DatabaseDiscoverer.class); private static final String YES = "yes"; private static String[] modelList; private Object callExtention(final String function, final MatchMetaData data, final String text) throws SQLException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { if ((function == null) || function.equals("")) { LOG.warn("Function " + function + " is not defined"); return null; } Object value = null; try { final String className = Utils.getClassName(function); final String methodName = Utils.getMethodName(function); final Method method = Class.forName(className) .getMethod(methodName, new Class[] { MatchMetaData.class, String.class }); final SpecialCase instance = (SpecialCase) Class.forName(className).newInstance(); final Map<String, Object> paramValues = new HashMap<>(2); paramValues.put("metadata", data); paramValues.put("text", text); value = method.invoke(instance, data, text); } catch (InstantiationException | ClassNotFoundException ex) { LOG.error(ex.toString()); } return value; } @SuppressWarnings("unchecked") public List<MatchMetaData> discover(final IDBFactory factory, final Properties dataDiscoveryProperties, String vendor) throws ParseException, DatabaseDiscoveryException { LOG.info("Data discovery in process"); // Get the probability threshold from property file final double probabilityThreshold = parseDouble(dataDiscoveryProperties.getProperty("probability_threshold")); String calculate_score = dataDiscoveryProperties.getProperty("score_calculation"); if (CommonUtils.isEmptyString(calculate_score)) { calculate_score = "false"; } LOG.info("Probability threshold [" + probabilityThreshold + "]"); // Get list of models used in data discovery final String models = dataDiscoveryProperties.getProperty("models"); modelList = models.split(","); LOG.info("Model list [" + Arrays.toString(modelList) + "]"); List<MatchMetaData> finalList = new ArrayList<>(); for (final String model : modelList) { LOG.info("********************************"); LOG.info("Processing model " + model); LOG.info("********************************"); final Model modelPerson = createModel(dataDiscoveryProperties, model); matches = discoverAgainstSingleModel(factory, dataDiscoveryProperties, modelPerson, probabilityThreshold,vendor); finalList = ListUtils.union(finalList, matches); } final DecimalFormat decimalFormat = new DecimalFormat(" LOG.info("List of suspects:"); LOG.info(String.format("%20s %20s %20s %20s", "Table*", "Column*", "Probability*", "Model*")); final Score score = new Score(); int highRiskColumns = 0; int rowCount = 0; for (final MatchMetaData data : finalList) { // Row count if (YES.equals(calculate_score)) { LOG.debug("Skipping table rowcount..."); rowCount = ReportUtil.rowCount(factory, data.getTableName(), Integer.valueOf(dataDiscoveryProperties.getProperty("limit"))); } // Getting 5 sample values final List<String> sampleDataList = ReportUtil.sampleData(factory, data.getTableName(), data.getColumnName()); // Output LOG.info("Column : " + data.toString()); LOG.info(CommonUtils.fixedLengthString('=', data.toString().length() + 30)); LOG.info("Model : " + data.getModel()); if (YES.equals(calculate_score)) { LOG.info("Number of rows in the table : " + rowCount); LOG.info("Score : " + score.columnScore(rowCount)); } else { LOG.info("Number of rows in the table : N/A"); LOG.info("Score : N/A"); } LOG.info("Sample data"); LOG.info(CommonUtils.fixedLengthString('-', 11)); sampleDataList.forEach((sampleData) -> { LOG.info(sampleData); }); LOG.info(""); final List<Probability> probabilityList = data.getProbabilityList(); Collections.sort(probabilityList, Comparator.comparingDouble(Probability::getProbabilityValue).reversed()); int y; if (data.getProbabilityList().size() >= 5) { y = 5; } else { y = data.getProbabilityList().size(); } for (int i = 0; i < y; i++) { final Probability p = data.getProbabilityList().get(i); LOG.info(p.getSentence() + ":" + p.getProbabilityValue()); } LOG.info(""); // Score calculation is evaluated with score_calculation parameter if (YES.equals(calculate_score) && score.columnScore(rowCount).equals("High")) { highRiskColumns++; } } // Only applicable when parameter table_rowcount=yes otherwise score calculation should not be done if (YES.equals(calculate_score)) { LOG.info("Overall score: " + score.dataStoreScore()); LOG.info(""); if ((finalList != null) && (finalList.size() > 0)) { LOG.info("============================================"); final int threshold_count = Integer.valueOf(dataDiscoveryProperties.getProperty("threshold_count")); if (finalList.size() > threshold_count) { LOG.info("Number of PI [" + finalList.size() + "] columns is higher than defined threashold [" + threshold_count + "]"); } else { LOG.info("Number of PI [" + finalList.size() + "] columns is lower or equal than defined threashold [" + threshold_count + "]"); } final int threshold_highrisk = Integer.valueOf(dataDiscoveryProperties.getProperty("threshold_highrisk")); if (highRiskColumns > threshold_highrisk) { LOG.info("Number of High risk PI [" + highRiskColumns + "] columns is higher than defined threashold [" + threshold_highrisk + "]"); } else { LOG.info("Number of High risk PI [" + highRiskColumns + "] columns is lower or equal than defined threashold [" + threshold_highrisk + "]"); } } } else { LOG.info("Overall score: N/A"); } LOG.info("matches: " + matches.toString()); return matches; } private List<MatchMetaData> discoverAgainstSingleModel(final IDBFactory factory, final Properties dataDiscoveryProperties, final Model model, final double probabilityThreshold, final String vendor) throws ParseException, DatabaseDiscoveryException { final IMetaData metaData = factory.fetchMetaData(); final List<MatchMetaData> map = metaData.getMetaData(vendor); // Start running NLP algorithms for each column and collect percentage matches = new ArrayList<>(); MatchMetaData specialCaseData; final List<MatchMetaData> specialCaseDataList = new ArrayList(); boolean specialCase = false; final String extentionList = dataDiscoveryProperties.getProperty("extentions"); String[] specialCaseFunctions = null; LOG.info("Extention list: " + extentionList); if (!CommonUtils.isEmptyString(extentionList)) { specialCaseFunctions = extentionList.split(","); if ((specialCaseFunctions != null) && (specialCaseFunctions.length > 0)) { specialCase = true; } } final ISQLBuilder sqlBuilder = factory.createSQLBuilder(); List<Probability> probabilityList; for (final MatchMetaData data : map) { final String tableName = data.getTableName(); final String columnName = data.getColumnName(); LOG.info("Primary key(s) for table " + tableName + ": "+ data.getPkeys().toString() + "]"); if (data.getPkeys().contains(columnName.toLowerCase(Locale.ENGLISH))) { LOG.debug("Column [" + columnName + "] is Primary Key. Skipping this column."); continue; } LOG.info("Foreign key(s) for table " + tableName + ": "+ data.getFkeys().toString() + "]"); if (data.getFkeys().contains(columnName.toLowerCase(Locale.ENGLISH))) { LOG.debug("Column [" + columnName + "] is Foreign Key. Skipping this column."); continue; } LOG.debug("Column type: [" + data.getColumnType() + "]"); probabilityList = new ArrayList<>(); LOG.debug("Analyzing column [" + tableName + "].[" + columnName + "]"); final String tableNamePattern = dataDiscoveryProperties.getProperty("table_name_pattern"); if (!CommonUtils.isEmptyString(tableNamePattern)) { final Pattern p = compile(tableNamePattern); if (!p.matcher(tableName).matches()) { continue; } } LOG.info("Table name: " + tableName); final String table = sqlBuilder.prefixSchema(tableName); final int limit = Integer.parseInt(dataDiscoveryProperties.getProperty("limit")); final String query = sqlBuilder.buildSelectWithLimit("SELECT " + columnName + " FROM " + table + " WHERE " + columnName + " IS NOT NULL ", limit); LOG.debug("Executing query against database: " + query); try (Statement stmt = factory.getConnection().createStatement(); ResultSet resultSet = stmt.executeQuery(query);) { while (resultSet.next()) { if (data.getColumnType().equals("BLOB") || data.getColumnType().equals("GEOMETRY")) { continue; } if (model.getName().equals("location") && data.getColumnType().contains("INT")) { continue; } final String sentence = resultSet.getString(1); LOG.debug(sentence); LOG.debug("special case:" + specialCase); if (specialCaseFunctions != null && specialCase) { try { for (String specialCaseFunction : specialCaseFunctions) { if ((sentence != null) && !sentence.isEmpty()) { LOG.debug("sentence: " + sentence); LOG.debug("data: " + data); specialCaseData = (MatchMetaData) callExtention(specialCaseFunction, data, sentence); if (specialCaseData != null) { LOG.info("Adding new special case data: " + specialCaseData.toString()); specialCaseDataList.add(specialCaseData); } else { LOG.debug("No special case data found"); } } } } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { LOG.error(e.toString()); } } if ((sentence != null) &&!sentence.isEmpty()) { String processingValue; if (data.getColumnType().equals("DATE") || data.getColumnType().equals("TIMESTAMP") || data.getColumnType().equals("DATETIME")) { final DateFormat originalFormat = new SimpleDateFormat(sentence, Locale.ENGLISH); final DateFormat targetFormat = new SimpleDateFormat("MMM d, yy", Locale.ENGLISH); final java.util.Date date = originalFormat.parse(sentence); processingValue = targetFormat.format(date); } else { processingValue = sentence; } // LOG.debug(sentence); // Convert sentence into tokens final String tokens[] = model.getTokenizer().tokenize(processingValue); // Find names final Span nameSpans[] = model.getNameFinder().find(tokens); // find probabilities for names final double[] spanProbs = model.getNameFinder().probs(nameSpans); // Collect top X tokens with highest probability // display names for (int i = 0; i < nameSpans.length; i++) { final String span = nameSpans[i].toString(); if (span.length() > 2) { LOG.debug("Span: " + span); LOG.debug("Covered text is: " + tokens[nameSpans[i].getStart()]); LOG.debug("Probability is: " + spanProbs[i]); probabilityList.add(new Probability(tokens[nameSpans[i].getStart()], spanProbs[i])); } } // From OpenNLP documentation: // After every document clearAdaptiveData must be called to clear the adaptive data in the feature generators. // Not calling clearAdaptiveData can lead to a sharp drop in the detection rate after a few documents. model.getNameFinder().clearAdaptiveData(); } } } catch (SQLException sqle) { LOG.error(sqle.toString()); } final double averageProbability = calculateAverage(probabilityList); if (averageProbability >= probabilityThreshold) { data.setAverageProbability(averageProbability); data.setModel(model.getName()); data.setProbabilityList(probabilityList); matches.add(data); } } // Special processing if (!specialCaseDataList.isEmpty()) { LOG.info("Special case data is processed :" + specialCaseDataList.toString()); specialCaseDataList.forEach((specialData) -> { matches.add(specialData); }); } return matches; } }
package com.wiccanarts.common.block.tile; import com.wiccanarts.api.WiccanArtsAPI; import com.wiccanarts.common.net.PacketHandler; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Items; import net.minecraft.init.PotionTypes; import net.minecraft.init.SoundEvents; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.potion.PotionUtils; import net.minecraft.util.EnumHand; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.ITickable; import net.minecraft.util.SoundCategory; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.WorldServer; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.capability.CapabilityFluidHandler; import net.minecraftforge.fluids.capability.IFluidHandler; import javax.annotation.Nullable; import java.util.List; import java.util.Random; public class TileKettle extends TileItemInventory implements ITickable { private static final String TAG_WATER = "waterLevel"; private static final String TAG_HEAT = "heat"; private float[] colors = new float[]{0.0f, 0.39215687f, 0.0f}; private int waterLevel; private int heat; private int tickCount; private ItemStack result; public void collideItem(EntityItem entityItem) { if (!hasWater()) return; ItemStack stack = entityItem.getEntityItem(); if (stack == null || entityItem.isDead) return; if (!getWorld().isRemote) { PacketHandler.sendTileUpdateNearbyPlayers(this); fancySplash(); stack.stackSize if (stack.stackSize == 0) entityItem.setDead(); for (int i = 0; i < getSizeInventory(); i++) { if (itemHandler.getItemSimulate(i) == null) { ItemStack stackToAdd = stack.copy(); stackToAdd.stackSize = 1; itemHandler.insertItem(i, stackToAdd, false); break; } } } getWorld().playSound(null, pos, SoundEvents.ENTITY_GENERIC_SPLASH, SoundCategory.BLOCKS, 0.1F, 8F); float r = getWorld().rand.nextFloat(); float g = getWorld().rand.nextFloat(); float b = getWorld().rand.nextFloat(); colors[0] = r; colors[1] = g; colors[2] = b; } private void fancySplash() { if (getWorld() instanceof WorldServer) { for (int i = 0; i < 10; i++) { BlockPos pos = getPos(); Random rand = new Random(); float d3 = (pos.getX() + rand.nextFloat()); float d4 = (float) (pos.getY() + 1); float d5 = (pos.getZ() + rand.nextFloat()); ((WorldServer) getWorld()).spawnParticle(EnumParticleTypes.CRIT_MAGIC, d3, d4, d5, 1, 0, 0, 0, 0D); } } } private void updateRecipe() { WiccanArtsAPI.getKettleRecipes().stream().filter(kettleRecipe -> kettleRecipe.checkRecipe(itemHandler, getWorld())).forEach(kettleRecipe -> result = kettleRecipe.getResult() ); } public boolean handleWater(@Nullable EntityPlayer player, EnumHand hand, ItemStack stack) { if (stack.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, null)) { IFluidHandler fluidHandler = stack.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, null); if (waterLevel < 6) { FluidStack drainWater = fluidHandler.drain(new FluidStack(FluidRegistry.WATER, Fluid.BUCKET_VOLUME), false); if (drainWater != null && drainWater.getFluid() == FluidRegistry.WATER && drainWater.amount == Fluid.BUCKET_VOLUME) { if (player != null) getWorld().playSound(player, player.getPosition(), SoundEvents.ITEM_BUCKET_EMPTY, SoundCategory.PLAYERS, 1.0F, 5F); fluidHandler.drain(new FluidStack(FluidRegistry.WATER, Fluid.BUCKET_VOLUME), true); setWaterLevel(6); getWorld().updateComparatorOutputLevel(pos, getWorld().getBlockState(pos).getBlock()); colors = new float[]{0.0f, 0.39215687f, 0.0f}; removeItems(); } } else if (waterLevel == 6) { int fill = fluidHandler.fill(new FluidStack(FluidRegistry.WATER, Fluid.BUCKET_VOLUME), false); if (fill == Fluid.BUCKET_VOLUME) { if (player != null) getWorld().playSound(player, player.getPosition(), SoundEvents.ITEM_BUCKET_FILL, SoundCategory.PLAYERS, 1.0F, 5F); fluidHandler.fill(new FluidStack(FluidRegistry.WATER, Fluid.BUCKET_VOLUME), true); setWaterLevel(0); getWorld().updateComparatorOutputLevel(pos, getWorld().getBlockState(pos).getBlock()); removeItems(); } } } else if (!getWorld().isRemote && stack.getItem() == Items.GLASS_BOTTLE && waterLevel > 0) { if (player != null && !player.capabilities.isCreativeMode) { ItemStack potion = getPotionFromRecipe(); if (--stack.stackSize == 0) { player.setHeldItem(hand, potion); } else if (!player.inventory.addItemStackToInventory(potion)) { player.dropItem(potion, false); } else if (player instanceof EntityPlayerMP) { ((EntityPlayerMP) player).sendContainerToPlayer(player.inventoryContainer); } } if (player != null) getWorld().playSound(player, player.getPosition(), SoundEvents.ITEM_BUCKET_EMPTY, SoundCategory.PLAYERS, 1.0F, 5F); setWaterLevel(waterLevel - 1); } return true; } private void removeItems() { result = null; for (int i = 0; i < itemHandler.getSlots(); i++) { itemHandler.extractItem(i, 1, false); } } private ItemStack getPotionFromRecipe() { if (result != null && PotionUtils.getPotionFromItem(result) != PotionTypes.WATER) { return result.copy(); } return PotionUtils.addPotionToItemStack(new ItemStack(Items.POTIONITEM), PotionTypes.WATER); } @Override public void writeDataNBT(NBTTagCompound cmp) { super.writeDataNBT(cmp); cmp.setInteger(TAG_WATER, waterLevel); cmp.setInteger(TAG_HEAT, heat); } @Override public void readDataNBT(NBTTagCompound cmp) { super.readDataNBT(cmp); waterLevel = cmp.getInteger(TAG_WATER); heat = cmp.getInteger(TAG_HEAT); } @Override public void update() { List<EntityItem> entityItemList = getWorld().getEntitiesWithinAABB(EntityItem.class, new AxisAlignedBB(getPos())); entityItemList.forEach(this::collideItem); if (getWorld().rand.nextInt(10) == 0 && isHot() && hasWater()) { BlockPos pos = getPos(); float d3 = ((float) pos.getX() + getWorld().rand.nextFloat()); float d4 = ((float) pos.getY() + 0.65F); float d5 = ((float) pos.getZ() + getWorld().rand.nextFloat()); getWorld().spawnParticle(EnumParticleTypes.WATER_BUBBLE, d3, d4, d5, 0.0D, 0.1D, 0.0D); getWorld().playSound(null, getPos(), SoundEvents.BLOCK_LAVA_POP, SoundCategory.BLOCKS, 1.0F, 5F); } if (!getWorld().isRemote && tickCount % 5 == 0) { if (result != null) { double d3 = pos.getX() + 0.5; double d4 = pos.getY() + 0.65; double d5 = pos.getZ() + 0.5; if (getWorld() instanceof WorldServer) ((WorldServer) getWorld()).spawnParticle(EnumParticleTypes.SPELL, d3, d4, d5, 1, 0D, 0D, 0D, 0D); if (!hasWater()) { removeItems(); } } updateRecipe(); } if (tickCount % 10 == 0) { handleRain(); } if (tickCount % 20 == 0) { handleHeat(); } ++tickCount; } private void handleHeat() { if (isAboveFire() && heat < 5) { ++heat; } else if (!isAboveFire() && heat > 0) { --heat; } } private boolean isAboveFire() { IBlockState state = getWorld().getBlockState(getPos().down()); return state.getMaterial() == Material.FIRE; } private void handleRain() { if (waterLevel != 6 && getWorld().isRainingAt(getPos().up())) { Random rand = new Random(); if (getWorld().isRemote) { for (int i = 0; i < 4; i++) { double d3 = pos.getX() + rand.nextFloat(); double d4 = pos.getY() + 0.65F; double d5 = pos.getZ() + rand.nextFloat(); getWorld().spawnParticle(EnumParticleTypes.WATER_BUBBLE, d3, d4, d5, 0.0D, 0.0D, 0.0D); } } getWorld().playSound(null, getPos(), SoundEvents.ITEM_BUCKET_FILL, SoundCategory.BLOCKS, 0.2F, 5F); setWaterLevel(waterLevel + 1); removeItems(); } } @Override public int getSizeInventory() { return 8; } public int getWaterLevel() { return waterLevel; } public void setWaterLevel(int water) { waterLevel = water; PacketHandler.updateToNearbyPlayers(getWorld(), pos); } public boolean hasWater() { return waterLevel > 0; } public boolean isHot() { return heat == 5; } public float[] getColor() { return colors; } }
package org.exist.interpreter; import java.io.IOException; import java.util.*; import java.util.function.Predicate; import javax.annotation.Nullable; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.stream.XMLStreamException; import com.ibm.icu.text.Collator; import org.exist.debuggee.DebuggeeJoint; import org.exist.dom.persistent.DocumentImpl; import org.exist.dom.persistent.DocumentSet; import org.exist.dom.QName; import org.exist.dom.memtree.MemTreeBuilder; import org.exist.security.Subject; import org.exist.source.Source; import org.exist.stax.ExtendedXMLStreamReader; import org.exist.storage.DBBroker; import org.exist.storage.UpdateListener; import org.exist.storage.lock.LockedDocumentMap; import org.exist.util.hashtable.NamePool; import org.exist.xmldb.XmldbURI; import org.exist.xquery.AnalyzeContextInfo; import org.exist.xquery.Expression; import org.exist.xquery.FunctionCall; import org.exist.xquery.FunctionSignature; import org.exist.xquery.LocalVariable; import org.exist.xquery.Module; import org.exist.xquery.Option; import org.exist.xquery.Pragma; import org.exist.xquery.Profiler; import org.exist.xquery.TerminatedException; import org.exist.xquery.UserDefinedFunction; import org.exist.xquery.Variable; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.XQueryWatchDog; import org.exist.xquery.value.AnyURIValue; import org.exist.xquery.value.BinaryValue; import org.exist.xquery.value.NodeValue; import org.exist.xquery.value.Sequence; public interface Context { /** * Returns true if this context has a parent context (means it is a module context). * * @return true if there is a parent context. */ boolean hasParent(); XQueryContext getRootContext(); XQueryContext copyContext(); /** * Update the current dynamic context using the properties of another context. * * This is needed by {@link org.exist.xquery.functions.util.Eval}. * * @param from the context to update from */ void updateContext(XQueryContext from); /** * Prepares the current context before xquery execution. */ void prepareForExecution(); /** * Is profiling enabled? * * @return true if profiling is enabled for this context. */ boolean isProfilingEnabled(); boolean isProfilingEnabled(int verbosity); /** * Returns the {@link Profiler} instance of this context if profiling is enabled. * * @return the profiler instance. */ Profiler getProfiler(); /** * Called from the XQuery compiler to set the root expression for this context. * * @param expr the root expression. */ void setRootExpression(Expression expr); /** * Returns the root expression of the XQuery associated with this context. * * @return root expression */ Expression getRootExpression(); /** * Returns the number of expression objects in the internal representation of the query. Used to estimate the size of the query. * * @return number of expression objects */ int getExpressionCount(); void setSource(Source source); Source getSource(); /** * Declare a user-defined static prefix/namespace mapping. * * eXist internally keeps a table containing all prefix/namespace mappings it found in documents, which have been previously stored into the * database. These default mappings need not to be declared explicitely. * * @param prefix the namespace prefix. * @param uri the namespace URI. * * @throws XPathException if an error occurs when declaring the namespace * with error codes XQST0033 or XQST0070 */ void declareNamespace(String prefix, String uri) throws XPathException; void declareNamespaces(Map<String, String> namespaceMap); /** * Removes the namespace URI from the prefix/namespace mappings table. * * @param uri the namespace URI. */ void removeNamespace(String uri); /** * Declare an in-scope namespace. This is called during query execution. * * @param prefix the namespace prefix. * @param uri the namespace uri. */ void declareInScopeNamespace(String prefix, String uri); String getInScopeNamespace(String prefix); String getInScopePrefix(String uri); String getInheritedNamespace(String prefix); String getInheritedPrefix(String uri); /** * Return the namespace URI mapped to the registered prefix or null if the prefix is not registered. * * @param prefix the namespace prefix. * * @return the namespace URI. */ String getURIForPrefix(String prefix); /** * Get URI Prefix. * * @param uri the namespace URI. * * @return the prefix mapped to the registered URI or null if the URI is not registered. */ String getPrefixForURI(String uri); /** * Returns the current default function namespace. * * @return current default function namespace */ String getDefaultFunctionNamespace(); /** * Set the default function namespace. By default, this points to the namespace for XPath built-in functions. * * @param uri the namespace URI. * * @throws XPathException if an error occurs when setting the default function namespace. */ void setDefaultFunctionNamespace(String uri) throws XPathException; /** * Returns the current default element namespace. * * @return current default element namespace schema * * @throws XPathException if an error occurs when getting the default element namespace. */ String getDefaultElementNamespaceSchema() throws XPathException; /** * Set the default element namespace. By default, this points to the empty uri. * * @param uri the default element namespace schema uri * * @throws XPathException if an error occurs when setting the default element namespace schema. */ void setDefaultElementNamespaceSchema(String uri) throws XPathException; /** * Returns the current default element namespace. * * @return current default element namespace * * @throws XPathException if an error occurs when getting the default element namespace. */ String getDefaultElementNamespace() throws XPathException; /** * Set the default element namespace. By default, this points to the empty uri. * * @param uri the namespace uri * @param schema detail of the namespace schema, or null * * @throws XPathException if an error occurs when setting the default element namespace. */ void setDefaultElementNamespace(String uri, @Nullable String schema) throws XPathException; /** * Set the default collation to be used by all operators and functions on strings. * Throws an exception if the collation is unknown or cannot be instantiated. * * @param uri the collation URI * * @throws XPathException if an error occurs when setting the default collation. */ void setDefaultCollation(String uri) throws XPathException; String getDefaultCollation(); Collator getCollator(String uri) throws XPathException; Collator getDefaultCollator(); /** * Set the set of statically known documents for the current execution context. * These documents will be processed if no explicit document set has been set for the current expression * with fn:doc() or fn:collection(). * * @param docs the statically known documents */ void setStaticallyKnownDocuments(XmldbURI[] docs); void setStaticallyKnownDocuments(DocumentSet set); //TODO : not sure how these 2 options might/have to be related void setCalendar(XMLGregorianCalendar newCalendar); void setTimeZone(TimeZone newTimeZone); XMLGregorianCalendar getCalendar(); TimeZone getImplicitTimeZone(); /** * Get statically known documents * * @return set of statically known documents. * * @throws XPathException if an error occurs when getting the statically known documents. */ DocumentSet getStaticallyKnownDocuments() throws XPathException; ExtendedXMLStreamReader getXMLStreamReader(NodeValue nv) throws XMLStreamException, IOException; void setProtectedDocs(LockedDocumentMap map); LockedDocumentMap getProtectedDocs(); boolean inProtectedMode(); /** * Should loaded documents be locked? * * @return true if documents should be locked on load. */ boolean lockDocumentsOnLoad(); void addLockedDocument(DocumentImpl doc); void setShared(boolean shared); boolean isShared(); void addModifiedDoc(DocumentImpl document); void reset(); /** * Prepare this XQueryContext to be reused. This should be called when adding an XQuery to the cache. * * @param keepGlobals true if global variables should be preserved. */ void reset(boolean keepGlobals); /** * Returns true if whitespace between constructed element nodes should be stripped by default. * * @return true if whitespace should be stripped, false otherwise. */ boolean stripWhitespace(); void setStripWhitespace(boolean strip); /** * Returns true if namespaces for constructed element and document nodes should be preserved on copy by default. * * @return true if namespaces should be preserved, false otherwise. */ boolean preserveNamespaces(); /** * Set whether namespaces should be preserved. * * @param preserve true if namespaces should be preserved, false otherwise. */ void setPreserveNamespaces(final boolean preserve); /** * Returns true if namespaces for constructed element and document nodes should be inherited on copy by default. * * @return true if namespaces are inheirted, false otherwise. */ boolean inheritNamespaces(); /** * Set whether namespaces should be inherited. * * @param inherit true if namespaces should be inherited, false otherwise. */ void setInheritNamespaces(final boolean inherit); /** * Returns true if order empty is set to greatest, otherwise false for order empty is least. * * @return true if the order is empty-greatest, false otherwise. */ boolean orderEmptyGreatest(); /** * The method <code>setOrderEmptyGreatest.</code> * * @param order a <code>boolean</code> value */ void setOrderEmptyGreatest(final boolean order); /** * Get modules. * * @return iterator over all modules imported into this context */ Iterator<Module> getModules(); /** * Get root modules. * * @return iterator over all modules registered in the entire context tree */ Iterator<Module> getRootModules(); Iterator<Module> getAllModules(); /** * Get the built-in module(s) registered for the given namespace URI. * * @param namespaceURI the namespace of the module. * * @return the module, or null */ @Nullable Module[] getModules(String namespaceURI); Module[] getRootModules(String namespaceURI); void setModules(String namespaceURI, @Nullable Module[] modules); void addModule(String namespaceURI, Module module); /** * For compiled expressions: check if the source of any module imported by the current * query has changed since compilation. * * @return true if the modules are valid, false otherwise. */ boolean checkModulesValid(); void analyzeAndOptimizeIfModulesChanged(Expression expr) throws XPathException; /** * Load a built-in module from the given class name and assign it to the namespace URI. * * The specified {@code moduleClass} should be a subclass of {@link Module}. The method will try to instantiate * the class. * * If the class is not found or an exception is thrown, the method will silently fail. The * namespace URI has to be equal to the namespace URI declared by the module class. Otherwise, * the module is not loaded. * * @param namespaceURI the namespace URI of the module to load * @param moduleClass the Java class of the module to load * * @return the loaded module, or null */ @Nullable Module loadBuiltInModule(String namespaceURI, String moduleClass); /** * Declare a user-defined function. All user-defined functions are kept in a single hash map. * * @param function the function. * * @throws XPathException if an error orccurs whilst declaring the function. */ void declareFunction(UserDefinedFunction function) throws XPathException; /** * Resolve a user-defined function. * * @param name the function name * @param argCount the function arity * * @return the resolved function, or null */ @Nullable UserDefinedFunction resolveFunction(QName name, int argCount); Iterator<FunctionSignature> getSignaturesForFunction(QName name); Iterator<UserDefinedFunction> localFunctions(); /** * Declare a local variable. This is called by variable binding expressions like "let" and "for". * * @param var the variable * * @return the declare variable * * @throws XPathException if an error occurs whilst declaring the variable binding */ LocalVariable declareVariableBinding(LocalVariable var) throws XPathException; /** * Declare a global variable as by "declare variable". * * @param var the variable * * @return variable the declared variable * * @throws XPathException if an error occurs whilst declaring the global variable */ Variable declareGlobalVariable(Variable var) throws XPathException; void undeclareGlobalVariable(QName name); /** * Declare a user-defined variable. * * The value argument is converted into an XPath value (@see XPathUtil#javaObjectToXPath(Object)). * * @param qname the qualified name of the new variable. Any namespaces should have been declared before. * @param value a Java object, representing the fixed value of the variable * * @return the created Variable object * * @throws XPathException if the value cannot be converted into a known XPath value or the variable QName * references an unknown namespace-prefix. */ Variable declareVariable(String qname, Object value) throws XPathException; Variable declareVariable(QName qn, Object value) throws XPathException; /** * Try to resolve a variable. * * @param name the qualified name of the variable as string * @return the declared Variable object * @throws XPathException if the variable is unknown */ Variable resolveVariable(String name) throws XPathException; /** * Try to resolve a variable. * * @param contextInfo contextual information * @param qname the qualified name of the variable * * @return the declared Variable object * * @throws XPathException if the variable is unknown */ Variable resolveVariable(@Nullable AnalyzeContextInfo contextInfo, QName qname) throws XPathException; /** * Try to resolve a variable. * * @param qname the qualified name of the variable * * @return the declared Variable object * * @throws XPathException if the variable is unknown */ Variable resolveVariable(QName qname) throws XPathException; boolean isVarDeclared(QName qname); Map<QName, Variable> getVariables(); Map<QName, Variable> getLocalVariables(); Map<QName, Variable> getGlobalVariables(); /** * Turn on/off XPath 1.0 backwards compatibility. * * If turned on, comparison expressions will behave like in XPath 1.0, i.e. if any one of the operands is a number, * the other operand will be cast to a double. * * @param backwardsCompatible true to enable XPath 1.0 backwards compatible mode. */ void setBackwardsCompatibility(boolean backwardsCompatible); /** * XPath 1.0 backwards compatibility turned on? * * In XPath 1.0 compatible mode, additional conversions will be applied to values if a numeric value is expected. * * @return true if XPath 1.0 compatible mode is enabled. */ boolean isBackwardsCompatible(); boolean isRaiseErrorOnFailedRetrieval(); /** * Get the DBBroker instance used for the current query. * * The DBBroker is the main database access object, providing access to all internal database functions. * * @return DBBroker instance */ DBBroker getBroker(); /** * Get the subject which executes the current query. * * @return subject */ Subject getSubject(); MemTreeBuilder getDocumentBuilder(); MemTreeBuilder getDocumentBuilder(boolean explicitCreation); /** * Returns the shared name pool used by all in-memory documents which are created within this query context. * Create a name pool for every document would be a waste of memory, especially since it is likely that the * documents contain elements or attributes with similar names. * * @return the shared name pool */ NamePool getSharedNamePool(); XQueryContext getContext(); void prologEnter(Expression expr); void expressionStart(Expression expr) throws TerminatedException; void expressionEnd(Expression expr); void stackEnter(Expression expr) throws TerminatedException; void stackLeave(Expression expr); void proceed() throws TerminatedException; void proceed(Expression expr) throws TerminatedException; void proceed(Expression expr, MemTreeBuilder builder) throws TerminatedException; void setWatchDog(XQueryWatchDog watchdog); XQueryWatchDog getWatchDog(); /** * Push any document fragment created within the current execution context on the stack. */ void pushDocumentContext(); /** * Pop the last document fragment created within the current execution context off the stack. */ void popDocumentContext(); /** * Set the base URI for the evaluation context. * * This is the URI returned by the {@code fn:base-uri()} function. * * @param uri the base URI */ void setBaseURI(AnyURIValue uri); /** * Set the base URI for the evaluation context. * * A base URI specified via the base-uri directive in the XQuery prolog overwrites any other setting. * * @param uri the base URI * @param setInProlog true if it was set by a declare option in the XQuery prolog */ void setBaseURI(AnyURIValue uri, boolean setInProlog); /** * Set the path to a base directory where modules should be loaded from. Relative module paths will be resolved * against this directory. The property is usually set by the XQueryServlet or XQueryGenerator, but can also * be specified manually. * * @param path the module load path. */ void setModuleLoadPath(String path); String getModuleLoadPath(); /** * Returns true if the baseURI is declared. * * @return true if the baseURI is declared, false otherwise. */ boolean isBaseURIDeclared(); /** * Get the base URI of the evaluation context. * * This is the URI returned by the fn:base-uri() function. * * @return base URI of the evaluation context * * @throws XPathException if an error occurs */ AnyURIValue getBaseURI() throws XPathException; /** * Set the current context position, i.e. the position of the currently processed item in the context sequence. * This value is required by some expressions, e.g. fn:position(). * * @param pos the position * @param sequence the sequence */ void setContextSequencePosition(int pos, Sequence sequence); /** * Get the current context position, i.e. the position of the currently processed item in the context sequence. * * @return current context position */ int getContextPosition(); Sequence getContextSequence(); void pushInScopeNamespaces(); /** * Push all in-scope namespace declarations onto the stack. * * @param inherit true if the current namespaces become inherited * just like the previous inherited ones */ @SuppressWarnings("unchecked") void pushInScopeNamespaces(boolean inherit); void popInScopeNamespaces(); @SuppressWarnings("unchecked") void pushNamespaceContext(); void popNamespaceContext(); /** * Returns the last variable on the local variable stack. The current variable context can be restored by * passing the return value to {@link #popLocalVariables(LocalVariable)}. * * @param newContext true if there is a new context * * @return last variable on the local variable stack */ LocalVariable markLocalVariables(boolean newContext); /** * Restore the local variable stack to the position marked by variable {@code var}. * * @param var only clear variables after this variable, or null */ void popLocalVariables(@Nullable LocalVariable var); /** * Returns the current size of the stack. This is used to determine where a variable has been declared. * * @return current size of the stack */ int getCurrentStackSize(); /** * Report the start of a function execution. Adds the reported function signature to the function call stack. * * @param signature the function signature */ void functionStart(FunctionSignature signature); /** * Report the end of the currently executed function. Pops the last function signature from the function call stack. */ void functionEnd(); /** * Check if the specified function signature is found in the current function called stack. * If yes, the function might be tail recursive and needs * to be optimized. * * @param signature the function signature * * @return true if the function call is tail recursive */ boolean tailRecursiveCall(FunctionSignature signature); void mapModule(String namespace, XmldbURI uri); /** * Import one or more library modules into the function signatures and in-scope variables of the importing module. * * The prefix and location parameters are optional. * If prefix is null, the first default prefix specified by the module(s) is used. * If locationHints are empty or null, the module(s) may be read from the namespace URI. * * @param namespaceURI the namespace URI of the module(s) * @param prefix the namespace prefix of the module(s), or null * @param locationHints hints as to the location of the module(s), or null * * @return the imported module(s) * * @throws XPathException if an error occurs whilst importing the module, with the error codes: * XPST0003 * XQST0033 * XQST0046 * XQST0059 * XQST0070 * XQST0088 */ Module[] importModule(@Nullable String namespaceURI, @Nullable String prefix, @Nullable AnyURIValue[] locationHints) throws XPathException; /** * Returns the static location mapped to an XQuery source module, if known. * * @param namespaceURI the URI of the module * * @return the location string */ String getModuleLocation(String namespaceURI); /** * Returns an iterator over all module namespace URIs which are statically mapped to a known location. * * @return an iterator */ Iterator<String> getMappedModuleURIs(); /** * Add a forward reference to an undeclared function. Forward references will be resolved later. * * @param call the undeclared function */ void addForwardReference(FunctionCall call); /** * Resolve all forward references to previously undeclared functions. * * @throws XPathException of an exception occurs whilst resolving the forward references */ void resolveForwardReferences() throws XPathException; boolean optimizationsEnabled(); /** * Add a static compile-time option i.e. declare option * * @param name the name of the option * @param value the value of the option * * @throws XPathException of an exception occurs whilst adding the option */ void addOption(String name, String value) throws XPathException; /** * Add a dynamic run-time option i.e. util:declare-option * * @param name the name of the dynamic option * @param value the value of the dynamic option * * @throws XPathException if an exception occurs whilst adding the dynamic option */ void addDynamicOption(String name, String value) throws XPathException; /** * Get dynamic options that were declared at run-time * first as these have precedence, and then if not found * get static options that were declare at compile time * * @param qname option name * @return the option */ Option getOption(QName qname); Pragma getPragma(String name, String contents) throws XPathException; /** * Store the supplied in-memory document to a temporary document fragment. * * @param doc the in-memory document * @return The temporary document * * @throws XPathException if an exception occurs whilst storing the temporary document */ DocumentImpl storeTemporaryDoc(org.exist.dom.memtree.DocumentImpl doc) throws XPathException; void setAttribute(String attribute, Object value); Object getAttribute(String attribute); void registerUpdateListener(UpdateListener listener); /** * Check if the XQuery contains options that define serialization settings. If yes, * copy the corresponding settings to the current set of output properties. * * @param properties the properties object to which serialization parameters will be added. * * @throws XPathException if an error occurs while parsing the option */ void checkOptions(Properties properties) throws XPathException; void setDebuggeeJoint(DebuggeeJoint joint); DebuggeeJoint getDebuggeeJoint(); boolean isDebugMode(); boolean requireDebugMode(); void registerBinaryValueInstance(BinaryValue binaryValue); void runCleanupTasks(final Predicate<Object> predicate); }
package de.agiledojo.multienv; import java.util.Calendar; import java.util.TimeZone; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; /** * Base Application configuration * */ @Configuration @PropertySource("classpath:/de/agiledojo/multienv/conf/default.properties") @Import(ProductionEnvironmentConfiguration.class) public class MultiEnvConfiguration { @Value("${timezone.id}") private String timeZoneID; @Value("${firstDayOfWeek}") private int firstDayOfWeek; @Bean public Calendar configuredCalendar() { Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(timeZoneID)); cal.setFirstDayOfWeek(firstDayOfWeek); return cal; } @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } }
package de.frosner.datagenerator.gui.main; import static de.frosner.datagenerator.gui.verifiers.InputVerifier.isDouble; import static de.frosner.datagenerator.gui.verifiers.InputVerifier.isInteger; import static de.frosner.datagenerator.gui.verifiers.InputVerifier.isName; import static de.frosner.datagenerator.gui.verifiers.InputVerifier.verifyComponent; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.WindowEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.util.List; import javax.swing.AbstractButton; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JEditorPane; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.ScrollPaneConstants; import javax.swing.SpringLayout; import javax.swing.border.LineBorder; import javax.swing.filechooser.FileFilter; import net.sf.qualitycheck.Check; import org.jgraph.JGraph; import org.jgraph.graph.DefaultGraphCell; import com.google.common.collect.Lists; import de.frosner.datagenerator.distributions.BernoulliDistribution; import de.frosner.datagenerator.distributions.CategorialDistribution; import de.frosner.datagenerator.distributions.ContinuousVariableParameter; import de.frosner.datagenerator.distributions.FixedParameter; import de.frosner.datagenerator.distributions.GaussianDistribution; import de.frosner.datagenerator.distributions.Parameter; import de.frosner.datagenerator.distributions.VariableParameter; import de.frosner.datagenerator.exceptions.UnknownActionEventSourceException; import de.frosner.datagenerator.exceptions.UnsupportedSelectionException; import de.frosner.datagenerator.export.CsvFileExportConfiguration; import de.frosner.datagenerator.export.ExportFeatureNames; import de.frosner.datagenerator.export.ExportInstanceIds; import de.frosner.datagenerator.features.FeatureDefinition; import de.frosner.datagenerator.gui.main.GaussianFeatureEntry.MeanIsDependent; import de.frosner.datagenerator.gui.services.DataGeneratorService; import de.frosner.datagenerator.gui.services.FeatureDefinitionGraphVisualizationManager; import de.frosner.datagenerator.gui.services.FeatureParameterDependencySelectorManager; import de.frosner.datagenerator.gui.services.GenerationButtonsToggleManager; import de.frosner.datagenerator.gui.services.PreviewTableManager; import de.frosner.datagenerator.gui.services.ProgressBarManager; import de.frosner.datagenerator.gui.services.TextAreaLogManager; import de.frosner.datagenerator.util.ApplicationMetaData; import de.frosner.datagenerator.util.VisibleForTesting; public final class SwingMenu extends JFrame implements ActionListener { private static final long serialVersionUID = ApplicationMetaData.SERIAL_VERSION_UID; private static final int LINE_HEIGHT = 30; private static final int LINE_WIDTH = 180; private static final int PADDING = 5; @VisibleForTesting final JButton _addFeatureButton; @VisibleForTesting final JButton _editFeatureButton; @VisibleForTesting final JButton _removeFeatureButton; @VisibleForTesting final JButton _generateDataButton; @VisibleForTesting final JButton _abortDataGenerationButton; private final JLabel _distributionSelectorLabel; @VisibleForTesting final JComboBox _distributionSelector; private final JLabel _featureNameLabel; @VisibleForTesting final JTextField _featureNameField; private final JLabel _gaussianMeanLabel; @VisibleForTesting final JComboBox _gaussianMeanParameterTypeSelector; private final JPanel _gaussianMeanValuePanel; @VisibleForTesting final JComboBox _gaussianMeanSelector; @VisibleForTesting final JTextField _gaussianMeanField; private final JLabel _gaussianSigmaLabel; @VisibleForTesting final JTextField _gaussianSigmaField; private final JLabel _bernoulliProbabilityLabel; @VisibleForTesting final JTextField _bernoulliProbabilityField; private final JLabel _uniformCategorialNumberOfStatesLabel; @VisibleForTesting final JTextField _uniformCategorialNumberOfStatesField; private final JLabel _numberOfInstancesLabel; @VisibleForTesting final JTextField _numberOfInstancesField; private final JLabel _exportFileLabel; @VisibleForTesting final JFileChooser _exportFileDialog; @VisibleForTesting final JButton _exportFileButton; @VisibleForTesting final JTextField _exportFileField; @VisibleForTesting final JCheckBox _exportInstanceIdsBox; @VisibleForTesting final JCheckBox _exportFeatureNamesBox; @VisibleForTesting static final FileFilter CSV_FILE_FILTER = new ExtensionFileFilter("Comma Separated Values (.csv)", "csv"); @VisibleForTesting static final FileFilter ALL_FILE_FILTER = new AllFileFilter(); @VisibleForTesting final JGraph _featureGraph; private final JScrollPane _featureGraphScroller; @VisibleForTesting final VariableColumnCountTableModel _previewTableModel; @VisibleForTesting final JTable _previewTable; @VisibleForTesting final JOptionPane _featureDefinitionPane; @VisibleForTesting final FeatureDefinitionDialog _featureDefinitionDialog; private final JPanel _distributionParametersPanel; private final JPanel _featureDefinitionDialogPanel; @VisibleForTesting final JProgressBar _progressBar; @VisibleForTesting final JEditorPane _logArea; private final JScrollPane _logAreaScroller; @VisibleForTesting final JMenuBar _menuBar; private final JMenu _fileMenu; @VisibleForTesting final JMenuItem _generateDataMenuItem; @VisibleForTesting final JMenuItem _closeMenuItem; private final JMenu _featuresMenu; @VisibleForTesting final JMenuItem _addFeatureMenuItem; private final JMenu _helpMenu; private final JMenuItem _aboutMenuItem; private GenerateDataButtonWorker _generateDataButtonWorker; private JPanel _gaussianPanel; public SwingMenu() { // BEGIN frame initialization setTitle(ApplicationMetaData.getName()); setDefaultCloseOperation(EXIT_ON_CLOSE); setResizable(true); setIconImage(new ImageIcon(getClass().getClassLoader().getResource("frame_icon.png")).getImage()); // END frame initialization // BEGIN menu bar initialization _menuBar = new JMenuBar(); setJMenuBar(_menuBar); _fileMenu = new JMenu("File"); _fileMenu.setMnemonic(KeyEvent.VK_F); _generateDataMenuItem = new JMenuItem("Generate Data"); _generateDataMenuItem.addActionListener(this); _closeMenuItem = new JMenuItem("Exit"); _closeMenuItem.addActionListener(this); _fileMenu.add(_generateDataMenuItem); _fileMenu.add(_closeMenuItem); _featuresMenu = new JMenu("Features"); _featuresMenu.setMnemonic(KeyEvent.VK_A); _addFeatureMenuItem = new JMenuItem("Add Feature"); _addFeatureMenuItem.addActionListener(this); _featuresMenu.add(_addFeatureMenuItem); _helpMenu = new JMenu("Help"); _helpMenu.setMnemonic(KeyEvent.VK_O); _aboutMenuItem = new JMenuItem("About"); _aboutMenuItem.addActionListener(this); _helpMenu.add(_aboutMenuItem); _menuBar.add(_fileMenu); _menuBar.add(_featuresMenu); _menuBar.add(_helpMenu); // END menu bar initialization // BEGIN component definition _distributionSelectorLabel = new JLabel("Distribution", JLabel.RIGHT); _distributionSelector = new JComboBox(new Object[] { BernoulliFeatureEntry.KEY, UniformCategorialFeatureEntry.KEY, GaussianFeatureEntry.KEY }); _distributionSelector.addActionListener(this); _featureNameLabel = new JLabel("Name", JLabel.RIGHT); _featureNameField = new JTextField(); _featureNameField.setMinimumSize(new Dimension(LINE_WIDTH, LINE_HEIGHT)); _gaussianMeanLabel = new JLabel("Mean", JLabel.RIGHT); _gaussianMeanParameterTypeSelector = new JComboBox(new Object[] { FixedParameter.KEY, VariableParameter.KEY }); _gaussianMeanParameterTypeSelector.addActionListener(this); _gaussianMeanSelector = new JComboBox(); FeatureParameterDependencySelectorManager.manageGaussianMeanSelector(_gaussianMeanSelector); _gaussianMeanField = new JTextField(); _gaussianMeanField.setMinimumSize(new Dimension(LINE_WIDTH, LINE_HEIGHT)); _gaussianSigmaLabel = new JLabel("Sigma", JLabel.RIGHT); _gaussianSigmaField = new JTextField(); _gaussianSigmaField.setMinimumSize(new Dimension(LINE_WIDTH, LINE_HEIGHT)); _bernoulliProbabilityLabel = new JLabel("P", JLabel.RIGHT); _bernoulliProbabilityField = new JTextField(); _bernoulliProbabilityField.setMinimumSize(new Dimension(LINE_WIDTH, LINE_HEIGHT)); _uniformCategorialNumberOfStatesLabel = new JLabel("#States", JLabel.RIGHT); _uniformCategorialNumberOfStatesField = new JTextField(); _uniformCategorialNumberOfStatesField.setMinimumSize(new Dimension(LINE_WIDTH, LINE_HEIGHT)); _addFeatureButton = new JButton("Add Feature"); _addFeatureButton.addActionListener(this); _editFeatureButton = new JButton("Edit Feature"); _editFeatureButton.addActionListener(this); _featureDefinitionDialog = new FeatureDefinitionDialog(this, "Add Feature"); _featureGraph = FeatureDefinitionGraphVisualizationManager.createNewManagedJGraph(); _featureGraph.setCloneable(true); _featureGraph.setDragEnabled(false); _featureGraph.setDropEnabled(false); _featureGraph.setEdgeLabelsMovable(false); _featureGraph.setEditable(false); _featureGraph.setMoveable(false); _featureGraph.setSizeable(false); _featureGraph.setXorEnabled(false); _featureGraph.setJumpToDefaultPort(true); _featureGraphScroller = new JScrollPane(_featureGraph); _removeFeatureButton = new JButton("Remove Feature"); _removeFeatureButton.addActionListener(this); _numberOfInstancesLabel = new JLabel("#Instances", JLabel.RIGHT); _numberOfInstancesField = new JTextField(); _numberOfInstancesField.setPreferredSize(new Dimension(LINE_WIDTH, LINE_HEIGHT)); _exportFileLabel = new JLabel("Export File", JLabel.RIGHT); _exportFileDialog = new ExportFileChooser(ALL_FILE_FILTER); _exportFileDialog.addChoosableFileFilter(CSV_FILE_FILTER); _exportFileDialog.setFileFilter(CSV_FILE_FILTER); _exportFileButton = new JButton("..."); _exportFileButton.addActionListener(this); _exportFileField = new JTextField(); _exportFileField.setEditable(false); _exportFileField.setPreferredSize(new Dimension(LINE_WIDTH - 25, LINE_HEIGHT)); _exportInstanceIdsBox = new JCheckBox("Instance IDs"); _exportFeatureNamesBox = new JCheckBox("Feature Names"); _progressBar = new JProgressBar(0, 100); _progressBar.setPreferredSize(new Dimension(100, LINE_HEIGHT + 5)); ProgressBarManager.manageProgressBar(_progressBar); _generateDataButton = new JButton("Generate Data"); _generateDataButton.addActionListener(this); _abortDataGenerationButton = new JButton("Abort Generation"); _abortDataGenerationButton.addActionListener(this); _abortDataGenerationButton.setEnabled(false); GenerationButtonsToggleManager.manageButtons(Lists.newArrayList((AbstractButton) _generateDataButton, (AbstractButton) _generateDataMenuItem), Lists .newArrayList((AbstractButton) _abortDataGenerationButton)); _previewTableModel = new VariableColumnCountTableModel(10, 4); _previewTable = new JTable(_previewTableModel); _previewTable.setEnabled(false); _previewTable.setPreferredSize(new Dimension(700, 50)); PreviewTableManager.managePreviewTable(_previewTableModel); _logArea = new JEditorPane("text/html", null); _logArea.setPreferredSize(new Dimension(LINE_WIDTH, 70)); _logAreaScroller = new JScrollPane(_logArea); TextAreaLogManager.manageLogArea(_logArea); _logArea.setBorder(new LineBorder(Color.gray, 1)); _logArea.setEditable(false); _logArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12)); _logArea.setAutoscrolls(true); _logAreaScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); // END component definition // BEGIN main layout Container contentPane = getContentPane(); contentPane.setLayout(new SpringLayout()); JPanel topPanel = new JPanel(); topPanel.setLayout(new SpringLayout()); topPanel.setMaximumSize(new Dimension(0, 0)); // avoid resizing contentPane.add(topPanel); JPanel featureButtonPanel = new JPanel(); featureButtonPanel.setLayout(new SpringLayout()); topPanel.add(featureButtonPanel); featureButtonPanel.add(_addFeatureButton); featureButtonPanel.add(_editFeatureButton); featureButtonPanel.add(_removeFeatureButton); JLabel whiteSpaceLabel = new JLabel(" "); // just for adding whitespace at bottom whiteSpaceLabel.setPreferredSize(new Dimension(50, 250)); featureButtonPanel.add(whiteSpaceLabel); SpringUtilities.makeCompactGrid(featureButtonPanel, 4, 1, 0, 0, 5, 5); JPanel featureGraphPanel = new JPanel(); featureGraphPanel.setLayout(new SpringLayout()); topPanel.add(featureGraphPanel); featureGraphPanel.setLayout(new BorderLayout()); featureGraphPanel.add(_featureGraphScroller, BorderLayout.CENTER); featureGraphPanel.setPreferredSize(new Dimension(LINE_WIDTH, 5)); SpringUtilities.makeCompactGrid(topPanel, 1, 2, 0, 0, 0, 0); JPanel midPanel = new JPanel(); midPanel.setLayout(new SpringLayout()); contentPane.add(midPanel); JPanel midLeftPanel = new JPanel(); midPanel.add(midLeftPanel); midLeftPanel.setLayout(new SpringLayout()); JPanel generateDataPanel = new JPanel(); generateDataPanel.setLayout(new SpringLayout()); generateDataPanel.add(_numberOfInstancesLabel); generateDataPanel.add(_numberOfInstancesField); generateDataPanel.add(_exportFileLabel); JPanel exportFileSubPanel = new JPanel(); generateDataPanel.add(exportFileSubPanel); exportFileSubPanel.setLayout(new SpringLayout()); exportFileSubPanel.add(_exportFileField); exportFileSubPanel.add(_exportFileButton); JPanel exportCheckBoxPanel = new JPanel(); generateDataPanel.add(new JLabel()); generateDataPanel.add(exportCheckBoxPanel); exportCheckBoxPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); exportCheckBoxPanel.add(_exportInstanceIdsBox); exportCheckBoxPanel.add(_exportFeatureNamesBox); SpringUtilities.makeCompactGrid(exportFileSubPanel, 1, 2, 0, 0, 0, 0); SpringUtilities.makeCompactGrid(generateDataPanel, 3, 2, 0, 0, 0, 0); JPanel midLeftButtonPanel = new JPanel(); midLeftButtonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); midLeftButtonPanel.add(_abortDataGenerationButton); midLeftButtonPanel.add(_generateDataButton); midLeftPanel.add(generateDataPanel); midLeftPanel.add(midLeftButtonPanel); midLeftPanel.add(_progressBar); SpringUtilities.makeCompactGrid(midLeftPanel, 3, 1, 0, 0, 0, 0); midPanel.add(midLeftPanel); midPanel.add(_previewTable); SpringUtilities.makeCompactGrid(midPanel, 1, 2, 0, 0, PADDING, PADDING); contentPane.add(_logAreaScroller); SpringUtilities.makeCompactGrid(contentPane, 3, 1, 15, 15, 15, 15); // END main layout // BEGIN dialogs layout _distributionParametersPanel = new JPanel(); _distributionParametersPanel.setLayout(new MinimalCardLayout()); JPanel bernoulliPanel = new JPanel(); _distributionParametersPanel.add(bernoulliPanel, BernoulliFeatureEntry.KEY); bernoulliPanel.setLayout(new SpringLayout()); bernoulliPanel.add(_bernoulliProbabilityLabel); bernoulliPanel.add(_bernoulliProbabilityField); SpringUtilities.makeCompactGrid(bernoulliPanel, 1, 2, 0, 0, PADDING, PADDING); JPanel uniformCategorialPanel = new JPanel(); _distributionParametersPanel.add(uniformCategorialPanel, UniformCategorialFeatureEntry.KEY); uniformCategorialPanel.setLayout(new SpringLayout()); uniformCategorialPanel.add(_uniformCategorialNumberOfStatesLabel); uniformCategorialPanel.add(_uniformCategorialNumberOfStatesField); SpringUtilities.makeCompactGrid(uniformCategorialPanel, 1, 2, 0, 0, PADDING, PADDING); _gaussianPanel = new JPanel(); _distributionParametersPanel.add(_gaussianPanel, GaussianFeatureEntry.KEY); _gaussianPanel.setLayout(new SpringLayout()); _gaussianPanel.add(_gaussianMeanLabel); _gaussianPanel.add(_gaussianMeanParameterTypeSelector); _gaussianPanel.add(new JLabel()); _gaussianMeanValuePanel = new JPanel(new MinimalCardLayout()); _gaussianMeanValuePanel.add(FixedParameter.KEY, _gaussianMeanField); _gaussianMeanValuePanel.add(VariableParameter.KEY, _gaussianMeanSelector); _gaussianPanel.add(_gaussianMeanValuePanel); _gaussianPanel.add(_gaussianSigmaLabel); _gaussianPanel.add(_gaussianSigmaField); SpringUtilities.makeCompactGrid(_gaussianPanel, FeatureDefinitionDialog.GAUSSIAN_PANEL_ROWS, FeatureDefinitionDialog.GAUSSIAN_PANEL_COLUMNS, 0, 0, PADDING, PADDING); _featureDefinitionDialogPanel = new JPanel(); _featureDefinitionDialogPanel.setLayout(new BoxLayout(_featureDefinitionDialogPanel, BoxLayout.Y_AXIS)); JPanel distributionSelectionAndFeatureNamePanel = new JPanel(); distributionSelectionAndFeatureNamePanel.setLayout(new SpringLayout()); _featureDefinitionDialogPanel.add(distributionSelectionAndFeatureNamePanel); distributionSelectionAndFeatureNamePanel.add(_distributionSelectorLabel); distributionSelectionAndFeatureNamePanel.add(_distributionSelector); distributionSelectionAndFeatureNamePanel.add(_featureNameLabel); distributionSelectionAndFeatureNamePanel.add(_featureNameField); SpringUtilities.makeCompactGrid(distributionSelectionAndFeatureNamePanel, 2, 2, 0, 0, PADDING, PADDING); _featureDefinitionDialogPanel.add(Box.createRigidArea(new Dimension(0, 12))); _featureDefinitionDialogPanel.add(new JSeparator()); _featureDefinitionDialogPanel.add(Box.createRigidArea(new Dimension(0, 10))); JPanel distributionParametersLabelPanel = new JPanel(); distributionParametersLabelPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); distributionParametersLabelPanel.add(new JLabel("Distribution Parameters")); _featureDefinitionDialogPanel.add(distributionParametersLabelPanel); _featureDefinitionDialogPanel.add(Box.createRigidArea(new Dimension(0, 5))); _featureDefinitionDialogPanel.add(_distributionParametersPanel); _featureDefinitionPane = new JOptionPane(_featureDefinitionDialogPanel, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION); _featureDefinitionDialog.setContentPane(_featureDefinitionPane); _featureDefinitionDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); _featureDefinitionPane.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { String property = e.getPropertyName(); if (_featureDefinitionDialog.isVisible() && (e.getSource() == _featureDefinitionPane) && (property.equals(JOptionPane.VALUE_PROPERTY))) { if (_featureDefinitionPane.getValue().equals(JOptionPane.OK_OPTION)) { if (verifyInputs()) { addFeatureDefinition(); _featureDefinitionDialog.setVisible(false); _featureDefinitionPane.setValue(JOptionPane.UNINITIALIZED_VALUE); } else { _featureDefinitionPane.setValue(JOptionPane.UNINITIALIZED_VALUE); } } else if (_featureDefinitionPane.getValue().equals(JOptionPane.UNINITIALIZED_VALUE)) { // Do nothing as this happens when OK was clicked but inputs could not be verified } else { verifyInputs(); _featureDefinitionDialog.setVisible(false); _featureDefinitionPane.setValue(JOptionPane.UNINITIALIZED_VALUE); } } } }); _featureDefinitionDialog.setResizable(false); _featureDefinitionDialog.setLocation(getCenteredLocationOf(_featureDefinitionDialog)); _featureDefinitionDialog.pack(); // END dialog layouts // BEGIN define custom focus traversal List<Component> focusOrder = Lists.newArrayList(); focusOrder.add(_addFeatureButton); focusOrder.add(_featureGraph); focusOrder.add(_removeFeatureButton); focusOrder.add(_numberOfInstancesField); focusOrder.add(_exportFileButton); focusOrder.add(_exportInstanceIdsBox); focusOrder.add(_exportFeatureNamesBox); focusOrder.add(_generateDataButton); focusOrder.add(_abortDataGenerationButton); setFocusTraversalPolicy(new OrderedFocusTraversalPolicy(focusOrder)); // END define custom focus traversal // BEGIN finalize pack(); setLocation(getCenteredLocationOf(this)); setMinimumSize(getSize()); setVisible(true); // END finalize } public void detachGenerateDataButtonWorker() { _generateDataButtonWorker = null; } /** * @throws UnknownActionEventSourceException * if the performed {@linkplain ActionEvent} cannot be handled by the {@linkplain SwingMenu} */ @Override public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (source.equals(_addFeatureButton) || source.equals(_addFeatureMenuItem)) { _featureDefinitionDialog.setVisible(true); } else if (source.equals(_distributionSelector)) { updateCardLayoutedPanelBySelector(_distributionParametersPanel, _distributionSelector); _featureDefinitionDialog.pack(); } else if (source.equals(_gaussianMeanParameterTypeSelector)) { updateCardLayoutedPanelBySelector(_gaussianMeanValuePanel, _gaussianMeanParameterTypeSelector); SpringUtilities.makeCompactGrid(_gaussianPanel, FeatureDefinitionDialog.GAUSSIAN_PANEL_ROWS, FeatureDefinitionDialog.GAUSSIAN_PANEL_COLUMNS, 0, 0, PADDING, PADDING); _featureDefinitionDialog.pack(); } else if (source.equals(_editFeatureButton)) { final Object selectedCell = _featureGraph.getSelectionCell(); if (selectedCell != null) { FeatureDefinitionEntry selectedEntry = FeatureDefinitionGraphVisualizationManager .getFeatureDefinitionEntryByCell(selectedCell); _featureDefinitionDialog.setFeatureToEdit(selectedEntry); _featureNameField.setText(selectedEntry.getFeatureName()); if (selectedEntry instanceof BernoulliFeatureEntry) { _distributionSelector.setSelectedItem(BernoulliFeatureEntry.KEY); _bernoulliProbabilityField.setText(((BernoulliFeatureEntry) selectedEntry).getP()); } else if (selectedEntry instanceof UniformCategorialFeatureEntry) { _distributionSelector.setSelectedItem(UniformCategorialFeatureEntry.KEY); _uniformCategorialNumberOfStatesField.setText(((UniformCategorialFeatureEntry) selectedEntry) .getNumberOfStates()); } else if (selectedEntry instanceof GaussianFeatureEntry) { _distributionSelector.setSelectedItem(GaussianFeatureEntry.KEY); _gaussianMeanField.setText(((GaussianFeatureEntry) selectedEntry).getMeanAsString()); _gaussianSigmaField.setText(((GaussianFeatureEntry) selectedEntry).getSigma()); } _featureDefinitionDialog.setVisible(true); _featureDefinitionDialog.leaveEditMode(); } } else if (source.equals(_removeFeatureButton)) { DefaultGraphCell selectedCell = (DefaultGraphCell) _featureGraph.getSelectionCell(); if (selectedCell != null) { final FeatureDefinitionEntry selectedFeatureEntry = (FeatureDefinitionEntry) selectedCell .getUserObject(); new Thread(new Runnable() { @Override public void run() { DataGeneratorService.INSTANCE.removeFeatureDefinition(selectedFeatureEntry); } }).start(); } } else if (source.equals(_exportFileButton)) { if (_exportFileDialog.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { _exportFileField.setText(_exportFileDialog.getSelectedFile().getPath()); verifyComponent(_exportFileField, isName(_exportFileField.getText()).isFileName().verify()); } } else if (source.equals(_generateDataButton) || source.equals(_generateDataMenuItem)) { if (verifyComponent(_numberOfInstancesField, isInteger(_numberOfInstancesField.getText()).isPositive() .verify()) & verifyComponent(_featureGraph, _featureGraph.getModel().getRootCount() > 0) & verifyComponent(_exportFileField, isName(_exportFileField.getText()).isFileName().verify())) { final int numberOfInstances = Integer.parseInt(_numberOfInstancesField.getText()); final File exportFile = _exportFileDialog.getSelectedFile(); final ExportInstanceIds exportInstanceIds = ExportInstanceIds.when(_exportInstanceIdsBox.isSelected()); final ExportFeatureNames exportFeatureNames = ExportFeatureNames.when(_exportFeatureNamesBox .isSelected()); _generateDataButtonWorker = new GenerateDataButtonWorker(numberOfInstances, new CsvFileExportConfiguration(exportFile, exportInstanceIds, exportFeatureNames)); _generateDataButtonWorker.execute(); } } else if (source.equals(_abortDataGenerationButton)) { if (_generateDataButtonWorker != null) { _generateDataButtonWorker.cancel(true); } } else if (source.equals(_aboutMenuItem)) { JTextArea applicationMetaData = new JTextArea(ApplicationMetaData.getName() + "\nVersion: " + ApplicationMetaData.getVersion() + "\nRevision: " + ApplicationMetaData.getRevision() + "\nBuilt on: " + ApplicationMetaData.getTimestamp()); applicationMetaData.setEditable(false); JOptionPane dialog = new JOptionPane(applicationMetaData, JOptionPane.INFORMATION_MESSAGE, JOptionPane.DEFAULT_OPTION); dialog.createDialog("About").setVisible(true); } else if (source.equals(_closeMenuItem)) { this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING)); } else { throw new UnknownActionEventSourceException(source); } } private static void updateCardLayoutedPanelBySelector(JPanel cardLayoutedPanel, JComboBox selector) { Check.instanceOf(CardLayout.class, cardLayoutedPanel.getLayout()); ((CardLayout) cardLayoutedPanel.getLayout()).show(cardLayoutedPanel, (String) selector.getSelectedItem()); } private void addFeatureDefinition() { String name = _featureNameField.getText(); Object selectedItem = _distributionSelector.getSelectedItem(); final FeatureDefinition featureDefinition; final FeatureDefinitionEntry featureDefinitionEntry; if (selectedItem.equals(BernoulliFeatureEntry.KEY)) { double p = Double.parseDouble(_bernoulliProbabilityField.getText()); featureDefinition = new FeatureDefinition(name, new BernoulliDistribution(new FixedParameter<Double>(p))); featureDefinitionEntry = new BernoulliFeatureEntry(featureDefinition, _bernoulliProbabilityField.getText()); } else if (selectedItem.equals(UniformCategorialFeatureEntry.KEY)) { int numberOfStates = Integer.parseInt(_uniformCategorialNumberOfStatesField.getText()); List<Double> probabilities = Lists.newArrayList(); for (int i = 0; i < numberOfStates; i++) { probabilities.add(1D / numberOfStates); } featureDefinition = new FeatureDefinition(name, new CategorialDistribution( new FixedParameter<List<Double>>(probabilities))); featureDefinitionEntry = new UniformCategorialFeatureEntry(featureDefinition, _uniformCategorialNumberOfStatesField.getText()); } else if (selectedItem.equals(GaussianFeatureEntry.KEY)) { Parameter<Double> meanParameter; MeanIsDependent meanIsDependent; Object meanEntry; if (_gaussianMeanParameterTypeSelector.getSelectedItem().equals(FixedParameter.KEY)) { double mean = Double.parseDouble(_gaussianMeanField.getText()); meanParameter = new FixedParameter<Double>(mean); meanIsDependent = MeanIsDependent.FALSE; meanEntry = _gaussianMeanField.getText(); } else { meanIsDependent = MeanIsDependent.TRUE; meanEntry = _gaussianMeanSelector.getSelectedItem(); meanParameter = new ContinuousVariableParameter(((FeatureDefinitionEntry) meanEntry) .getFeatureDefinition()); } double sigma = Double.parseDouble(_gaussianSigmaField.getText()); featureDefinition = new FeatureDefinition(name, new GaussianDistribution(meanParameter, new FixedParameter<Double>(sigma))); featureDefinitionEntry = new GaussianFeatureEntry(featureDefinition, meanEntry, meanIsDependent, _gaussianSigmaField.getText()); } else { throw new UnsupportedSelectionException(selectedItem); } if (_featureDefinitionDialog.isInEditMode()) { new Thread(new Runnable() { @Override public void run() { DataGeneratorService.INSTANCE.replaceFeatureDefinition(_featureDefinitionDialog.getFeatureToEdit(), featureDefinitionEntry); } }).start(); } else { new Thread(new Runnable() { @Override public void run() { DataGeneratorService.INSTANCE.addFeatureDefinition(featureDefinitionEntry); } }).start(); } verifyComponent(_featureGraph, true); } private boolean verifyInputs() { String name = _featureNameField.getText(); if (!verifyComponent(_featureNameField, isName(name).isNotLongerThan(30))) { return false; } Object selectedDistribution = _distributionSelector.getSelectedItem(); if (selectedDistribution.equals(BernoulliFeatureEntry.KEY)) { return verifyComponent(_bernoulliProbabilityField, isDouble(_bernoulliProbabilityField.getText()) .isProbability()); } else if (selectedDistribution.equals(UniformCategorialFeatureEntry.KEY)) { return verifyComponent(_uniformCategorialNumberOfStatesField, isInteger( _uniformCategorialNumberOfStatesField.getText()).isPositive().isInInterval(1, 1000)); } else if (selectedDistribution.equals(GaussianFeatureEntry.KEY)) { boolean meanIsVerified; Object selectedMeanParameterType = _gaussianMeanParameterTypeSelector.getSelectedItem(); if (selectedMeanParameterType.equals(FixedParameter.KEY)) { meanIsVerified = verifyComponent(_gaussianMeanField, isDouble(_gaussianMeanField.getText()).verify()); } else if (selectedMeanParameterType.equals(VariableParameter.KEY)) { meanIsVerified = _gaussianMeanSelector.getSelectedIndex() != -1; } else { throw new UnsupportedSelectionException(selectedMeanParameterType); } boolean sigmaIsVerified = verifyComponent(_gaussianSigmaField, isDouble(_gaussianSigmaField.getText()) .isPositive()); return meanIsVerified && sigmaIsVerified; } else { throw new UnsupportedSelectionException(selectedDistribution); } } private static Point getCenteredLocationOf(Component component) { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Point middle = new Point(screenSize.width / 2, screenSize.height / 2); Point newLocation = new Point(middle.x - (component.getWidth() / 2), middle.y - (component.getHeight() / 2)); return newLocation; } }
package de.iani.cubequest.generation; import de.iani.cubequest.CubeQuest; import de.iani.cubequest.EventListener.GlobalChatMsgType; import de.iani.cubequest.QuestGiver; import de.iani.cubequest.QuestManager; import de.iani.cubequest.Reward; import de.iani.cubequest.exceptions.QuestDeletionFailedException; import de.iani.cubequest.interaction.InteractorProtecting; import de.iani.cubequest.quests.Quest; import de.iani.cubequest.util.ChatAndTextUtil; import de.iani.cubequest.util.ItemStackUtil; import de.iani.cubequest.util.Pair; import de.iani.cubequest.util.Util; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.SQLException; import java.time.LocalDate; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Deque; import java.util.EnumMap; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TreeSet; import java.util.logging.Level; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.ClickEvent; import net.md_5.bungee.api.chat.ComponentBuilder; import net.md_5.bungee.api.chat.HoverEvent; import org.bukkit.Material; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.serialization.ConfigurationSerializable; import org.bukkit.entity.EntityType; import org.bukkit.inventory.ItemStack; public class QuestGenerator implements ConfigurationSerializable { private static final int DAYS_TO_KEEP_DAILY_QUESTS = 3; private static QuestGenerator instance; private int questsToGenerate; private int questsToGenerateOnThisServer; private List<QuestSpecification> possibleQuests; private Set<QuestSpecification> lastUsedPossibilities; private Set<QuestSpecification> currentlyUsedPossibilities; private Deque<DailyQuestData> currentDailyQuests; private Map<MaterialValueOption, ValueMap<Material>> materialValues; private Map<EntityValueOption, ValueMap<EntityType>> entityValues; private LocalDate lastGeneratedForDay; // private Object saveLock = new Object(); public enum MaterialValueOption { DELIVER, PLACE, BREAK, FISH; } public enum EntityValueOption { KILL; } public static class QuestSpecificationAndDifficultyPair extends Pair<QuestSpecification, Double> { public QuestSpecificationAndDifficultyPair(QuestSpecification key, Double value) { super(key, value); } public QuestSpecification getQuestSpecification() { return super.getKey(); } public double getDifficulty() { return super.getValue(); } } public static class QuestSpeficicationBestFitComparator implements Comparator<QuestSpecificationAndDifficultyPair> { private double targetDifficulty; private Set<QuestSpecification> avoid1; private Set<QuestSpecification> avoid2; public QuestSpeficicationBestFitComparator(double targetDifficulty, Set<QuestSpecification> avoid1, Set<QuestSpecification> avoid2) { this.targetDifficulty = targetDifficulty; this.avoid1 = avoid1; this.avoid2 = avoid2; } @Override public int compare(QuestSpecificationAndDifficultyPair o1, QuestSpecificationAndDifficultyPair o2) { int result = 0; if (this.avoid1.contains(o1.getQuestSpecification())) { result += 1; } if (this.avoid1.contains(o2.getQuestSpecification())) { result -= 1; } if (result != 0) { return result; } if (this.avoid2.contains(o1.getQuestSpecification())) { result += 1; } if (this.avoid2.contains(o2.getQuestSpecification())) { result -= 1; } if (result != 0) { return result; } result = Double.compare(Math.abs(this.targetDifficulty - o1.getDifficulty()), Math.abs(this.targetDifficulty - o2.getDifficulty())); return (int) Math.signum(result); } } public static QuestGenerator getInstance() { if (instance == null) { File configFile = new File(CubeQuest.getInstance().getDataFolder(), "generator.yml"); if (!configFile.exists()) { instance = new QuestGenerator(); } else { YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); if (!config.contains("generator")) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "Could not load QuestGenerator."); instance = new QuestGenerator(); } else { instance = (QuestGenerator) config.get("generator"); } } } return instance; } private QuestGenerator() { this.possibleQuests = new ArrayList<>(); this.lastUsedPossibilities = new TreeSet<>(QuestSpecification.SIMILAR_SPECIFICATIONS_COMPARATOR); this.currentlyUsedPossibilities = new TreeSet<>(QuestSpecification.SIMILAR_SPECIFICATIONS_COMPARATOR); this.materialValues = new EnumMap<>(MaterialValueOption.class); this.entityValues = new EnumMap<>(EntityValueOption.class); refreshDailyQuests(); for (MaterialValueOption option : MaterialValueOption.values()) { ValueMap<Material> map = new ValueMap<>(Material.class, 0.0025); this.materialValues.put(option, map); } for (EntityValueOption option : EntityValueOption.values()) { ValueMap<EntityType> map = new ValueMap<>(EntityType.class, 0.1); this.entityValues.put(option, map); } } @SuppressWarnings("unchecked") public QuestGenerator(Map<String, Object> serialized) throws InvalidConfigurationException { if (instance != null) { throw new IllegalStateException("Can't initilize second instance of singleton!"); } try { this.questsToGenerate = (Integer) serialized.get("questsToGenerate"); this.questsToGenerateOnThisServer = (Integer) serialized.get("questsToGenerateOnThisServer"); this.possibleQuests = (List<QuestSpecification>) serialized.get("possibleQuests"); this.lastUsedPossibilities = new TreeSet<>(QuestSpecification.SIMILAR_SPECIFICATIONS_COMPARATOR); if (serialized.containsKey("lastUsedPossibilities")) { this.lastUsedPossibilities .addAll((List<QuestSpecification>) serialized.get("lastUsedPossibilities")); } this.currentlyUsedPossibilities = new TreeSet<>(QuestSpecification.SIMILAR_SPECIFICATIONS_COMPARATOR); if (serialized.containsKey("currentlyUsedPossibilities")) { this.currentlyUsedPossibilities.addAll( (List<QuestSpecification>) serialized.get("currentlyUsedPossibilities")); } DeliveryQuestSpecification.DeliveryQuestPossibilitiesSpecification.deserialize( (Map<String, Object>) serialized.get("deliveryQuestSpecifications")); BlockBreakQuestSpecification.BlockBreakQuestPossibilitiesSpecification.deserialize( (Map<String, Object>) serialized.get("blockBreakQuestSpecifications")); BlockPlaceQuestSpecification.BlockPlaceQuestPossibilitiesSpecification.deserialize( (Map<String, Object>) serialized.get("blockPlaceQuestSpecifications")); FishingQuestSpecification.FishingQuestPossibilitiesSpecification.deserialize( (Map<String, Object>) serialized.get("fishingQuestSpecifications")); KillEntitiesQuestSpecification.KillEntitiesQuestPossibilitiesSpecification.deserialize( (Map<String, Object>) serialized.get("killEntitiesQuestSpecifications")); Map<String, Object> mValues = (Map<String, Object>) serialized.get("materialValues"); this.materialValues = (Map<MaterialValueOption, ValueMap<Material>>) Util .deserializeEnumMap(MaterialValueOption.class, mValues); Map<String, Object> eValues = (Map<String, Object>) serialized.get("entityValues"); this.entityValues = (Map<EntityValueOption, ValueMap<EntityType>>) Util .deserializeEnumMap(EntityValueOption.class, eValues); refreshDailyQuests(); this.lastGeneratedForDay = serialized.get("lastGeneratedForDay") == null ? null : LocalDate.ofEpochDay( ((Number) serialized.get("lastGeneratedForDay")).longValue()); } catch (Exception e) { throw new InvalidConfigurationException(e); } for (QuestSpecification spec : this.possibleQuests) { if (spec instanceof InteractorProtecting) { CubeQuest.getInstance().addProtecting((InteractorProtecting) spec); } } } public void refreshDailyQuests() { try { this.currentDailyQuests = new ArrayDeque<>( CubeQuest.getInstance().getDatabaseFassade().getDailyQuestData()); } catch (SQLException e) { this.currentDailyQuests = this.currentDailyQuests == null ? new ArrayDeque<>(QuestGenerator.DAYS_TO_KEEP_DAILY_QUESTS) : this.currentDailyQuests; CubeQuest.getInstance().getLogger().log(Level.SEVERE, "Could not refresh current dailyQuests:", e); } } public List<QuestSpecification> getPossibleQuestsIncludingNulls() { return Collections.unmodifiableList(this.possibleQuests); } public void addPossibleQuest(QuestSpecification qs) { this.possibleQuests.add(qs); if (qs instanceof InteractorProtecting) { CubeQuest.getInstance().addProtecting((InteractorProtecting) qs); } saveConfig(); } public void removePossibleQuest(int index) { QuestSpecification spec = this.possibleQuests.set(index, null); if (spec != null) { if (spec instanceof InteractorProtecting) { CubeQuest.getInstance().removeProtecting((InteractorProtecting) spec); } saveConfig(); } } public void consolidatePossibleQuests() { this.possibleQuests.removeIf(qs -> qs == null); this.possibleQuests.sort(QuestSpecification.COMPARATOR); } public int getQuestsToGenerate() { return this.questsToGenerate; } public void setQuestsToGenerate(int questsToGenerate) { this.questsToGenerate = questsToGenerate; saveConfig(); } public int getQuestsToGenerateOnThisServer() { return this.questsToGenerateOnThisServer; } public void setQuestsToGenerateOnThisServer(int questsToGenerateOnThisServer) { this.questsToGenerateOnThisServer = questsToGenerateOnThisServer; saveConfig(); } public LocalDate getLastGeneratedForDay() { return this.lastGeneratedForDay; } public double getValue(MaterialValueOption o, Material m) { return this.materialValues.get(o).getValue(m); } public void setValue(MaterialValueOption o, Material m, double value) { this.materialValues.get(o).setValue(m, value); saveConfig(); } public double getValue(EntityValueOption o, EntityType t) { return this.entityValues.get(o).getValue(t); } public void setValue(EntityValueOption o, EntityType t, double value) { this.entityValues.get(o).setValue(t, value); saveConfig(); } public void generateDailyQuests() { CubeQuest.getInstance().getLogger().log(Level.INFO, "Starting to generate DailyQuests."); deleteOldDailyQuests(); DailyQuestData dqData; try { int dataId = CubeQuest.getInstance().getDatabaseFassade().reserveNewDailyQuestData(); dqData = new DailyQuestData(dataId, this.questsToGenerate); this.currentDailyQuests.addLast(dqData); } catch (SQLException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "Could not create new DailyQuestData.", e); return; } this.lastGeneratedForDay = LocalDate.now(); this.lastUsedPossibilities = this.currentlyUsedPossibilities; this.currentlyUsedPossibilities = new TreeSet<>(QuestSpecification.SIMILAR_SPECIFICATIONS_COMPARATOR); Random ran; try { ran = new Random(Util.fromBytes(MessageDigest.getInstance("MD5") .digest(Util.byteArray(this.lastGeneratedForDay.toEpochDay())))); } catch (NoSuchAlgorithmException e) { throw new AssertionError(e); } List<String> selectedServers = getServersToGenerateOn(ran, dqData); for (int i = 0; i < this.questsToGenerate; i++) { double difficulty = (this.questsToGenerate > 1 ? 0.1 + i * 0.8 / (this.questsToGenerate - 1) : 0.5) + 0.1 * ran.nextDouble(); String server = selectedServers.get(i); if (server == null) { dailyQuestGenerated(i, generateQuest(i, dqData.getDateString(), difficulty, ran)); } else { delegateDailyQuestGeneration(server, i, dqData, difficulty, ran); } } saveConfig(); } private void deleteOldDailyQuests() { if (!this.currentDailyQuests.isEmpty()) { // DailyQuests von gestern aus QuestGivern austragen for (QuestGiver giver : CubeQuest.getInstance().getDailyQuestGivers()) { for (Quest q : this.currentDailyQuests.getLast().getQuests()) { giver.removeQuest(q); } } for (Quest q : this.currentDailyQuests.getLast().getQuests()) { q.setReady(false); } while (this.currentDailyQuests.size() >= DAYS_TO_KEEP_DAILY_QUESTS) { DailyQuestData dqData = this.currentDailyQuests.removeFirst(); try { CubeQuest.getInstance().getDatabaseFassade().deleteDailyQuestData(dqData); } catch (SQLException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "Could not delete DailyQuests " + dqData + ":", e); return; } ByteArrayOutputStream msgbytes = new ByteArrayOutputStream(); DataOutputStream msgout = new DataOutputStream(msgbytes); try { msgout.writeInt(GlobalChatMsgType.DAILY_QUESTS_REMOVED.ordinal()); byte[] msgarry = msgbytes.toByteArray(); CubeQuest.getInstance().getGlobalChatAPI().sendDataToServers("CubeQuest", msgarry); } catch (IOException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "IOException trying to send GlobalChatMessage!", e); return; } for (Quest q : dqData.getQuests()) { try { QuestManager.getInstance().deleteQuest(q); } catch (QuestDeletionFailedException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "Could not delete DailyQuest " + q + ":", e); } } } } } private List<String> getServersToGenerateOn(Random ran, DailyQuestData dqData) { List<String> selectedServers = new ArrayList<>(); List<String> serversToSelectFrom = new ArrayList<>(); Map<String, Integer> serversToSelectFromWithAmountOfLegalSpecifications; try { serversToSelectFromWithAmountOfLegalSpecifications = CubeQuest.getInstance().getDatabaseFassade().getServersToGenerateDailyQuestOn(); } catch (SQLException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "SQL-Exception while trying to generate daily-quests! No quests generated.", e); return Collections.emptyList(); } serversToSelectFromWithAmountOfLegalSpecifications .remove(CubeQuest.getInstance().getBungeeServerName()); for (String server : serversToSelectFromWithAmountOfLegalSpecifications.keySet()) { for (int i = 0; i < serversToSelectFromWithAmountOfLegalSpecifications .get(server); i++) { serversToSelectFrom.add(server); } } if (serversToSelectFrom.isEmpty()) { serversToSelectFrom.add(null); } else { Collections.sort(serversToSelectFrom); Collections.shuffle(serversToSelectFrom, ran); } for (int i = 0; serversToSelectFrom.size() < this.questsToGenerate - this.questsToGenerateOnThisServer; i++) { serversToSelectFrom.add(serversToSelectFrom.get(i)); } for (int i = 0; i < this.questsToGenerate; i++) { selectedServers.add(i < this.questsToGenerateOnThisServer ? null : serversToSelectFrom.get(i - this.questsToGenerateOnThisServer)); } Collections.shuffle(selectedServers, ran); return selectedServers; } private void delegateDailyQuestGeneration(String server, int questOrdinal, DailyQuestData dqData, double difficulty, Random ran) { try { DelegatedGenerationData data = new DelegatedGenerationData(dqData.getDateString(), questOrdinal, difficulty, ran.nextLong()); CubeQuest.getInstance().getDatabaseFassade().addDelegatedQuestGeneration(server, data); } catch (SQLException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "IOException trying to save DelegatedGenerationData!", e); return; } ByteArrayOutputStream msgbytes = new ByteArrayOutputStream(); DataOutputStream msgout = new DataOutputStream(msgbytes); try { msgout.writeInt(GlobalChatMsgType.GENERATE_DAILY_QUEST.ordinal()); msgout.writeUTF(server); byte[] msgarry = msgbytes.toByteArray(); CubeQuest.getInstance().getGlobalChatAPI().sendDataToServers("CubeQuest", msgarry); } catch (IOException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "IOException trying to send GlobalChatMessage!", e); return; } } public Quest generateQuest(int dailyQuestOrdinal, String dateString, double difficulty, Random ran) { long diff = this.lastGeneratedForDay == null ? Long.MAX_VALUE : (LocalDate.now().toEpochDay() - this.lastGeneratedForDay.toEpochDay()); if (diff > 0) { this.lastGeneratedForDay = LocalDate.now(); this.lastUsedPossibilities = diff == 1 ? this.currentlyUsedPossibilities : new TreeSet<>(QuestSpecification.SIMILAR_SPECIFICATIONS_COMPARATOR); this.currentlyUsedPossibilities = new TreeSet<>(QuestSpecification.SIMILAR_SPECIFICATIONS_COMPARATOR); } if (this.possibleQuests.stream().noneMatch(qs -> qs != null && qs.isLegal())) { CubeQuest.getInstance().getLogger().log(Level.WARNING, "Could not generate a DailyQuest for this server as no QuestSpecifications were specified."); return null; } List<QuestSpecification> qsList = new ArrayList<>(); this.possibleQuests.forEach(qs -> { if (qs != null && qs.isLegal()) { qsList.add(qs); } }); qsList.sort(QuestSpecification.COMPARATOR); List<QuestSpecificationAndDifficultyPair> generatedList = new ArrayList<>(); qsList.forEach(qs -> generatedList.add(new QuestSpecificationAndDifficultyPair(qs, qs.generateQuest(ran) + 0.1 * ran.nextGaussian()))); int weighting = DeliveryQuestSpecification.DeliveryQuestPossibilitiesSpecification .getInstance().getWeighting(); for (int i = 0; i < weighting; i++) { DeliveryQuestSpecification qs = new DeliveryQuestSpecification(); generatedList.add(new QuestSpecificationAndDifficultyPair(qs, qs.generateQuest(ran) + 0.1 * ran.nextGaussian())); } weighting = BlockBreakQuestSpecification.BlockBreakQuestPossibilitiesSpecification .getInstance().getWeighting(); for (int i = 0; i < weighting; i++) { BlockBreakQuestSpecification qs = new BlockBreakQuestSpecification(); generatedList.add(new QuestSpecificationAndDifficultyPair(qs, qs.generateQuest(ran) + 0.1 * ran.nextGaussian())); } weighting = BlockPlaceQuestSpecification.BlockPlaceQuestPossibilitiesSpecification .getInstance().getWeighting(); for (int i = 0; i < weighting; i++) { BlockPlaceQuestSpecification qs = new BlockPlaceQuestSpecification(); generatedList.add(new QuestSpecificationAndDifficultyPair(qs, qs.generateQuest(ran) + 0.1 * ran.nextGaussian())); } weighting = FishingQuestSpecification.FishingQuestPossibilitiesSpecification.getInstance() .getWeighting(); for (int i = 0; i < weighting; i++) { FishingQuestSpecification qs = new FishingQuestSpecification(); generatedList.add(new QuestSpecificationAndDifficultyPair(qs, qs.generateQuest(ran) + 0.1 * ran.nextGaussian())); } weighting = KillEntitiesQuestSpecification.KillEntitiesQuestPossibilitiesSpecification .getInstance().getWeighting(); for (int i = 0; i < weighting; i++) { KillEntitiesQuestSpecification qs = new KillEntitiesQuestSpecification(); generatedList.add(new QuestSpecificationAndDifficultyPair(qs, qs.generateQuest(ran) + 0.1 * ran.nextGaussian())); } generatedList.sort(new QuestSpeficicationBestFitComparator(difficulty, this.currentlyUsedPossibilities, this.lastUsedPossibilities)); generatedList.subList(1, generatedList.size() - 1) .forEach(qsdp -> qsdp.getQuestSpecification().clearGeneratedQuest()); QuestSpecification resultSpecification = generatedList.get(0).getQuestSpecification(); this.currentlyUsedPossibilities.add(resultSpecification); String questName = ChatColor.GOLD + "DailyQuest " + ChatAndTextUtil.toRomanNumber(dailyQuestOrdinal + 1) + " vom " + dateString; Reward reward = generateReward(difficulty, ran); Quest result = resultSpecification.createGeneratedQuest(questName, reward); result.setReady(true); if (!CubeQuest.getInstance().isGeneratingDailyQuests()) { saveConfig(); } return result; } public boolean checkForDelegatedGeneration() { List<DelegatedGenerationData> dataList; try { dataList = CubeQuest.getInstance().getDatabaseFassade().popDelegatedQuestGenerations(); } catch (SQLException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "Could not pop delegated quest generations.", e); return false; } if (dataList.isEmpty()) { return false; } for (DelegatedGenerationData data : dataList) { Quest generated = generateQuest(data.questOrdinal, data.dateString, data.difficulty, new Random(data.ranSeed)); try { ByteArrayOutputStream msgbytes = new ByteArrayOutputStream(); DataOutputStream msgout = new DataOutputStream(msgbytes); msgout.writeInt(GlobalChatMsgType.DAILY_QUEST_GENERATED.ordinal()); msgout.writeInt(data.questOrdinal); msgout.writeInt(generated.getId()); byte[] msgarry = msgbytes.toByteArray(); CubeQuest.getInstance().getGlobalChatAPI().sendDataToServers("CubeQuest", msgarry); } catch (IOException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "IOException trying to send GlobalChatMessage!", e); } } return true; } public Reward generateReward(double difficulty, Random ran) { return new Reward(0, 10, 5, new ItemStack[] {ItemStackUtil.getMysteriousSpellBook()}); } public void dailyQuestGenerated(int dailyQuestOrdinal, Quest generatedQuest) { if (!CubeQuest.getInstance().isGeneratingDailyQuests()) { return; } if (generatedQuest.getSuccessMessage() == null) { generatedQuest.setSuccessMessage(CubeQuest.PLUGIN_TAG + ChatColor.GOLD + " Du hast die " + generatedQuest.getName() + " abgeschlossen!"); } DailyQuestData dqData = this.currentDailyQuests.getLast(); generatedQuest.setVisible(true); dqData.setQuest(dailyQuestOrdinal, Util.addTimeLimit(generatedQuest, dqData.getNextDayDate())); try { dqData.saveToDatabase(); } catch (SQLException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "Could not save DailyQuestData.", e); return; } try { ByteArrayOutputStream msgbytes = new ByteArrayOutputStream(); DataOutputStream msgout = new DataOutputStream(msgbytes); msgout.writeInt(GlobalChatMsgType.DAILY_QUEST_FINISHED.ordinal()); byte[] msgarry = msgbytes.toByteArray(); CubeQuest.getInstance().getGlobalChatAPI().sendDataToServers("CubeQuest", msgarry); } catch (IOException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "IOException trying to send GlobalChatMessage!", e); } if (dqData.getQuests().stream().allMatch(q -> q != null)) { for (QuestGiver giver : CubeQuest.getInstance().getDailyQuestGivers()) { for (Quest q : dqData.getQuests()) { giver.addQuest(q); } } CubeQuest.getInstance().getLogger().log(Level.INFO, "DailyQuests generated."); } } public List<Quest> getTodaysDailyQuests() { DailyQuestData dqData = this.currentDailyQuests.getLast(); return this.currentDailyQuests == null ? null : dqData.getQuests(); } public Collection<Quest> getAllDailyQuests() { Set<Quest> result = new LinkedHashSet<>(); for (DailyQuestData dqData : this.currentDailyQuests) { for (Quest q : dqData.getQuests()) { result.add(q); } } return result; } public int countLegalQuestSecifications() { int i = 0; for (QuestSpecification qs : this.possibleQuests) { if (qs != null && qs.isLegal()) { i++; } } try { CubeQuest.getInstance().getDatabaseFassade().setLegalQuestSpecificationCount(i); } catch (SQLException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "Could not update count of legal QuestSpecificaitons in database.", e); } return i; } public List<BaseComponent[]> getSpecificationInfo() { List<BaseComponent[]> result = new ArrayList<>(); int index = 1; for (QuestSpecification qs : this.possibleQuests) { if (qs != null) { ClickEvent clickEvent = new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/quest removeQuestSpecification " + index); HoverEvent hoverEvent = new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder("Spezifikation an Index " + index + " entfernen.") .create()); result.add(new ComponentBuilder(index + ": ").append(qs.getSpecificationInfo()) .append(" ").append("[Löschen]").color(ChatColor.RED).event(clickEvent) .event(hoverEvent).create()); } index++; } return result; } public List<BaseComponent[]> getDeliveryReceiverSpecificationInfo() { return DeliveryQuestSpecification.DeliveryQuestPossibilitiesSpecification.getInstance() .getReceiverSpecificationInfo(); } public List<BaseComponent[]> getDeliveryContentSpecificationInfo() { return DeliveryQuestSpecification.DeliveryQuestPossibilitiesSpecification.getInstance() .getContentSpecificationInfo(); } public List<BaseComponent[]> getBlockBreakSpecificationInfo() { return BlockBreakQuestSpecification.BlockBreakQuestPossibilitiesSpecification.getInstance() .getSpecificationInfo(); } public List<BaseComponent[]> getBlockPlaceSpecificationInfo() { return BlockPlaceQuestSpecification.BlockPlaceQuestPossibilitiesSpecification.getInstance() .getSpecificationInfo(); } public List<BaseComponent[]> getFishingSpecificationInfo() { return FishingQuestSpecification.FishingQuestPossibilitiesSpecification.getInstance() .getSpecificationInfo(); } public List<BaseComponent[]> getKillEntitiesSpecificationInfo() { return KillEntitiesQuestSpecification.KillEntitiesQuestPossibilitiesSpecification .getInstance().getSpecificationInfo(); } @Override public Map<String, Object> serialize() { Map<String, Object> result = new HashMap<>(); result.put("questsToGenerate", this.questsToGenerate); result.put("questsToGenerateOnThisServer", this.questsToGenerateOnThisServer); List<QuestSpecification> possibleQSList = new ArrayList<>(this.possibleQuests); possibleQSList.removeIf(qs -> qs == null); possibleQSList.sort(QuestSpecification.COMPARATOR); result.put("possibleQuests", possibleQSList); List<QuestSpecification> lastUsedQSList = new ArrayList<>(this.lastUsedPossibilities); result.put("lastUsedPossibilities", lastUsedQSList); List<QuestSpecification> currentlyUsedQSList = new ArrayList<>(this.currentlyUsedPossibilities); result.put("currentlyUsedPossibilities", currentlyUsedQSList); result.put("deliveryQuestSpecifications", DeliveryQuestSpecification.DeliveryQuestPossibilitiesSpecification.getInstance() .serialize()); result.put("blockBreakQuestSpecifications", BlockBreakQuestSpecification.BlockBreakQuestPossibilitiesSpecification.getInstance() .serialize()); result.put("blockPlaceQuestSpecifications", BlockPlaceQuestSpecification.BlockPlaceQuestPossibilitiesSpecification.getInstance() .serialize()); result.put("fishingQuestSpecifications", FishingQuestSpecification.FishingQuestPossibilitiesSpecification.getInstance() .serialize()); result.put("killEntitiesQuestSpecifications", KillEntitiesQuestSpecification.KillEntitiesQuestPossibilitiesSpecification .getInstance().serialize()); result.put("materialValues", Util.serializedEnumMap(this.materialValues)); result.put("entityValues", Util.serializedEnumMap(this.entityValues)); result.put("lastGeneratedForDay", this.lastGeneratedForDay == null ? null : this.lastGeneratedForDay.toEpochDay()); return result; } public void saveConfig() { countLegalQuestSecifications(); CubeQuest.getInstance().getDataFolder().mkdirs(); File configFile = new File(CubeQuest.getInstance().getDataFolder(), "generator.yml"); YamlConfiguration config = new YamlConfiguration(); config.set("generator", this); try { config.save(configFile); } catch (IOException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "Could not save QuestGenerator.", e); } } }
package de.predic8.s_security; import org.apache.kafka.clients.producer.*; import org.apache.kafka.common.serialization.*; import javax.json.*; import java.util.*; import static java.lang.Math.*; import static org.apache.kafka.clients.consumer.ConsumerConfig.*; public class SCRAMClientWithoutTLS { public static void main(String[] args) { Properties props = new Properties(); props.put(BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092"); try(Producer<String, String> producer = new KafkaProducer<>(props, new StringSerializer(), new StringSerializer())) { int i = 0; long t1 = System.currentTimeMillis(); for (; i < 10; i++) { String key = String.valueOf(round(random() * 1000)); JsonObject json = Json.createObjectBuilder() .add("windrad", key) .add("kw", Double.valueOf(round(random() * 10000000L)).intValue() / 1000.0) .build(); producer.send(new ProducerRecord<>("produktion", key, json.toString())); } System.out.println("fertig " + i + " Nachrichten in " + (System.currentTimeMillis() - t1 + " ms")); } } }
package edu.berkeley.sparrow.daemon.util; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.commons.configuration.Configuration; import org.apache.log4j.Logger; import com.google.common.base.Optional; import edu.berkeley.sparrow.daemon.SparrowConf; import edu.berkeley.sparrow.thrift.TResourceVector; /** * Utilities to aid the configuration file-based scheduler and node monitor. */ public class ConfigUtil { private final static Logger LOG = Logger.getLogger(ConfigUtil.class); /** * Parses the list of backends from a {@link Configuration}. * * Returns a map of address of backends to a {@link TResourceVector} describing the * total resource capacity for that backend. */ public static ConcurrentMap<InetSocketAddress, TResourceVector> parseBackends( Configuration conf) { if (!conf.containsKey(SparrowConf.STATIC_NODE_MONITORS) || !conf.containsKey(SparrowConf.STATIC_MEM_PER_BACKEND)) { throw new RuntimeException("Missing configuration backend list."); } ConcurrentMap<InetSocketAddress, TResourceVector> backends = new ConcurrentHashMap<InetSocketAddress, TResourceVector>(); TResourceVector nodeResources = TResources.createResourceVector( conf.getInt(SparrowConf.STATIC_MEM_PER_BACKEND)); for (String node: conf.getStringArray(SparrowConf.STATIC_NODE_MONITORS)) { Optional<InetSocketAddress> addr = Serialization.strToSocket(node); if (!addr.isPresent()) { LOG.warn("Bad backend address: " + node); continue; } backends.put(addr.get(), nodeResources); } return backends; } /** * Parses a list of schedulers from a {@code Configuration} * @return */ public static List<InetSocketAddress> parseSchedulers(Configuration conf) { if (!conf.containsKey(SparrowConf.STATIC_SCHEDULERS)) { throw new RuntimeException("Missing configuration frontend list."); } List<InetSocketAddress> frontends = new ArrayList<InetSocketAddress>(); for (String node: conf.getStringArray(SparrowConf.STATIC_SCHEDULERS)) { Optional<InetSocketAddress> addr = Serialization.strToSocket(node); if (!addr.isPresent()) { LOG.warn("Bad scheduler address: " + node); continue; } frontends.add(addr.get()); } return frontends; } }
package edu.harvard.iq.dataverse; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.logging.Logger; import javax.ejb.EJB; import javax.faces.view.ViewScoped; import javax.inject.Named; @ViewScoped @Named("AdvancedSearchPage") public class AdvancedSearchPage { private static final Logger logger = Logger.getLogger(AdvancedSearchPage.class.getCanonicalName()); @EJB DataverseServiceBean dataverseServiceBean; @EJB DatasetFieldServiceBean datasetFieldService; private Dataverse dataverse; private String query; private String title; private String author; private List<MetadataBlock> metadataBlocks; private Map<Long,List<DatasetField>> metadataFieldMap = new HashMap(); private List<DatasetField> metadataFieldList; public void init() { /** * @todo: support advanced search at any depth in the dataverse * hierarchy */ this.dataverse = dataverseServiceBean.findRootDataverse(); this.metadataBlocks = dataverseServiceBean.findAllMetadataBlocks(); this.metadataFieldList = datasetFieldService.findAllAdvancedSearchFields(); for (MetadataBlock mdb : metadataBlocks) { List datasetFields = new ArrayList(); for (DatasetField datasetField : metadataFieldList) { if (datasetField.getMetadataBlock().getId().equals(mdb.getId())) { datasetFields.add(datasetField); } } metadataFieldMap.put(mdb.getId(), datasetFields); } } public String find() throws IOException { List<String> queryStrings = new ArrayList(); String delimiter = "[\"]+"; for (DatasetField datasetField : metadataFieldList) { if (datasetField.getSearchValue() != null && !datasetField.getSearchValue().equals("")) { String myString = datasetField.getSearchValue(); if (myString.contains("\"")) { String [] tempString = datasetField.getSearchValue().split(delimiter); for (int i = 1; i < tempString.length; i++) { if (!tempString[i].equals(" ") && !tempString[i].isEmpty()) { queryStrings.add(datasetField.getSolrField() + ":" + "\"" + tempString[i].trim() + "\""); } } } else { StringTokenizer st = new StringTokenizer(datasetField.getSearchValue()); while (st.hasMoreElements()) { queryStrings.add(datasetField.getSolrField() + ":" + st.nextElement()); } } } else if (datasetField.getListValues() != null && !datasetField.getListValues().isEmpty()){ for (String value : datasetField.getListValues()) { queryStrings.add(datasetField.getSolrField() + ":" + "\"" + value + "\""); } } } query = new String(); for (String string : queryStrings) { query += string + " "; } return "/dataverse.xhtml?q=" + query + "faces-redirect=true"; } public Dataverse getDataverse() { return dataverse; } public void setDataverse(Dataverse dataverse) { this.dataverse = dataverse; } public String getQuery() { return query; } public void setQuery(String query) { this.query = query; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public List<MetadataBlock> getMetadataBlocks() { return metadataBlocks; } public void setMetadataBlocks(List<MetadataBlock> metadataBlocks) { this.metadataBlocks = metadataBlocks; } public Map<Long, List<DatasetField>> getMetadataFieldMap() { return metadataFieldMap; } public void setMetadataFieldMap(Map<Long, List<DatasetField>> metadataFieldMap) { this.metadataFieldMap = metadataFieldMap; } }
package edu.harvard.iq.dataverse; import edu.harvard.iq.dataverse.authorization.Permission; import edu.harvard.iq.dataverse.authorization.users.User; import edu.harvard.iq.dataverse.engine.command.Command; import edu.harvard.iq.dataverse.engine.command.impl.*; import java.util.HashMap; import java.util.Map; import javax.ejb.EJB; import javax.faces.view.ViewScoped; import javax.inject.Inject; import javax.inject.Named; /** * * @author gdurand */ @ViewScoped @Named public class PermissionsWrapper implements java.io.Serializable { @EJB PermissionServiceBean permissionService; @Inject DataverseSession session; private Map<Long, Map<Class<? extends Command>, Boolean>> commandMap = new HashMap<>(); /** * Check if the current Dataset can Issue Commands * * @param commandName */ private boolean canIssueCommand(DvObject dvo, Class<? extends Command> command) { if ((dvo == null) || (command == null)) { return false; } if (commandMap.containsKey(dvo.getId())) { Map<Class<? extends Command>, Boolean> dvoCommandMap = this.commandMap.get(dvo.getId()); if (dvoCommandMap.containsKey(command)) { return dvoCommandMap.get(command); } else { return addCommandtoDvoCommandMap(dvo, command, dvoCommandMap); } } else { Map newDvoCommandMap = new HashMap(); commandMap.put(dvo.getId(), newDvoCommandMap); return addCommandtoDvoCommandMap(dvo, command, newDvoCommandMap); } } private boolean addCommandtoDvoCommandMap(DvObject dvo, Class<? extends Command> command, Map<Class<? extends Command>, Boolean> dvoCommandMap) { boolean canIssueCommand; canIssueCommand = permissionService.on(dvo).canIssue(command); dvoCommandMap.put(command, canIssueCommand); return canIssueCommand; } public boolean canManageDataversePermissions(User u, Dataverse dv) { return permissionService.userOn(u, dv).has(Permission.ManageDataversePermissions); } public boolean CanIssueUpdateDataverseCommand(DvObject dvo) { return canIssueCommand(dvo, UpdateDataverseCommand.class); } public boolean CanIssuePublishDataverseCommand(DvObject dvo) { return canIssueCommand(dvo, PublishDataverseCommand.class); } public boolean CanIssueDeleteataverseCommand(DvObject dvo) { return canIssueCommand(dvo, DeleteDataverseCommand.class); } public boolean canManagePermissions(DvObject dvo) { User u = session.getUser(); return dvo instanceof Dataverse ? canManageDataversePermissions(u, (Dataverse) dvo) : canManageDatasetPermissions(u, (Dataset) dvo); } public boolean canManageDatasetPermissions(User u, Dataset ds) { return permissionService.userOn(u, ds).has(Permission.ManageDatasetPermissions); } }
package edu.ucsf.valelab.mmclearvolumeplugin; import clearvolume.renderer.ClearVolumeRendererInterface; import clearvolume.renderer.factory.ClearVolumeRendererFactory; import clearvolume.transferf.TransferFunction1D; import clearvolume.transferf.TransferFunctions; import com.google.common.eventbus.EventBus; import com.jogamp.newt.awt.NewtCanvasAWT; import coremem.fragmented.FragmentedMemory; import coremem.types.NativeTypeEnum; import ij.ImagePlus; import ij.gui.ImageWindow; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.GraphicsConfiguration; import java.awt.Window; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowFocusListener; import java.util.ArrayList; import java.util.List; import javax.swing.JFrame; import javax.swing.SwingUtilities; import org.micromanager.Studio; import org.micromanager.data.Coords; import org.micromanager.data.Datastore; import org.micromanager.data.Image; import org.micromanager.data.Metadata; import org.micromanager.data.SummaryMetadata; import org.micromanager.data.internal.DefaultImage; import org.micromanager.display.DataViewer; import org.micromanager.display.DisplaySettings; import org.micromanager.display.DisplayWindow; import org.micromanager.display.HistogramData; import org.micromanager.display.NewDisplaySettingsEvent; import org.micromanager.display.NewHistogramsEvent; import org.micromanager.display.internal.DefaultDisplaySettings; import org.micromanager.display.internal.RememberedChannelSettings; import org.micromanager.display.internal.events.DefaultDisplayAboutToShowEvent; import org.micromanager.events.internal.DefaultEventManager; /** * * @author nico */ public class Viewer implements DisplayWindow { private DisplaySettings ds_; private final Studio studio_; private Datastore store_; private ClearVolumeRendererInterface clearVolumeRenderer_; private String name_; private final EventBus displayBus_; private final JFrame cvFrame_; private Coords.CoordsBuilder coordsBuilder_; private boolean open_ = false; public Viewer(Studio studio) { studio_ = studio; DisplayWindow theDisplay = studio_.displays().getCurrentWindow(); displayBus_ = new EventBus(); cvFrame_ = new JFrame(); coordsBuilder_ = studio_.data().getCoordsBuilder(); if (theDisplay == null) { ij.IJ.error("No data set open"); return; } ds_ = theDisplay.getDisplaySettings().copy().build(); store_ = theDisplay.getDatastore(); final int nrZ = store_.getAxisLength(Coords.Z); final int nrCh = store_.getAxisLength(Coords.CHANNEL); Image randomImage = store_.getAnyImage(); // creates renderer: NativeTypeEnum nte = NativeTypeEnum.UnsignedShort; if (randomImage.getBytesPerPixel() == 1) { nte = NativeTypeEnum.UnsignedByte; } name_ = theDisplay.getName() + "-ClearVolume"; clearVolumeRenderer_ = ClearVolumeRendererFactory.newOpenCLRenderer( name_, randomImage.getWidth(), randomImage.getHeight(), nte, 768, 768, nrCh, true); final NewtCanvasAWT lNCWAWT = clearVolumeRenderer_.getNewtCanvasAWT(); cvFrame_.setTitle(name_); cvFrame_.setLayout(new BorderLayout()); final Container container = new Container(); container.setLayout(new BorderLayout()); container.add(lNCWAWT, BorderLayout.CENTER); cvFrame_.setSize(new Dimension(randomImage.getWidth(), randomImage.getHeight())); cvFrame_.add(container); SwingUtilities.invokeLater(() -> { cvFrame_.setVisible(true); }); clearVolumeRenderer_.setTransferFunction(TransferFunctions.getDefault()); clearVolumeRenderer_.setVisible(true); // create fragmented memory for each stack that needs sending to CV: final Metadata metadata = randomImage.getMetadata(); final SummaryMetadata summary = store_.getSummaryMetadata(); final int maxValue = 1 << store_.getAnyImage().getMetadata().getBitDepth(); for (int ch = 0; ch < nrCh; ch++) { FragmentedMemory lFragmentedMemory = new FragmentedMemory(); for (int i = 0; i < nrZ; i++) { // For each image in the stack build an offheap memory object: // OffHeapMemory lOffHeapMemory = OffHeapMemory.allocateBytes(nrBytesPerImage); coordsBuilder_ = coordsBuilder_.z(i).channel(ch).time(0).stagePosition(0); Coords coords = coordsBuilder_.build(); // Bypass Micro-Manager api to get access to the ByteBuffers DefaultImage image = (DefaultImage) store_.getImage(coords); // short[] pix = (short[]) image.getRawPixels(); // lOffHeapMemory.copyFrom(pix); // add the contiguous memory as fragment: lFragmentedMemory.add(image.getPixelBuffer()); } // pass data to renderer: clearVolumeRenderer_.setVolumeDataBuffer(ch, lFragmentedMemory, randomImage.getWidth(), randomImage.getHeight(), nrZ); // TODO: correct x and y voxel sizes using aspect ratio clearVolumeRenderer_.setVoxelSize(ch, metadata.getPixelSizeUm(), metadata.getPixelSizeUm(), summary.getZStepUm()); Color chColor = ds_.getChannelColors()[ch]; clearVolumeRenderer_.setTransferFunction(ch, getGradientForColor(chColor)); // clearVolumeRenderer_.setBrightness(ch, // ds_.getChannelContrastSettings()[ch].getContrastMaxes()[0] / maxValue ); // clearVolumeRenderer_.setGamma(ch, // ds_.getChannelContrastSettings()[ch].getContrastGammas()[0]); } clearVolumeRenderer_.requestDisplay(); open_ = true; } /** * Code that needs to register this instance with various managers and * listeners Could have been in the constructor, except that it is unsafe to * register our instance before it is completed. Needs to be called right * after the constructor. */ public void register() { if (!open_) { return; } final int nrZ = store_.getAxisLength(Coords.Z); final int nrCh = store_.getAxisLength(Coords.CHANNEL); displayBus_.register(this); studio_.getDisplayManager().addViewer(this); DefaultEventManager.getInstance().post(new DefaultDisplayAboutToShowEvent(this)); for (int ch = 0; ch < nrCh; ch++) { coordsBuilder_ = coordsBuilder_.z(nrZ / 2).channel(ch).time(0).stagePosition(0); Coords coords = coordsBuilder_.build(); Image middleImage = store_.getImage(coords); ArrayList<HistogramData> datas = new ArrayList<>(); for (int i = 0; i < middleImage.getNumComponents(); ++i) { HistogramData data = studio_.displays().calculateHistogramWithSettings( middleImage, i, ds_); datas.add(data); } displayBus_.post(new NewHistogramsEvent(ch, datas)); } studio_.getDisplayManager().raisedToTop(this); final DataViewer ourViewer = this; // the WindowFocusListener should go into the WindowAdapter, but there it // does not work, so add both a WindowListener and WindowFocusListener cvFrame_.addWindowFocusListener(new WindowFocusListener() { @Override public void windowGainedFocus(WindowEvent e) { System.out.println("Our window got focus"); studio_.getDisplayManager().raisedToTop(ourViewer); } @Override public void windowLostFocus(WindowEvent e) { System.out.println("Our window lost focus"); } } ); cvFrame_.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { clearVolumeRenderer_.close(); cvFrame_.dispose(); studio_.getDisplayManager().removeViewer(ourViewer); open_ = false; } @Override public void windowClosed(WindowEvent e) { } }); } @Override public void setDisplaySettings(DisplaySettings ds) { System.out.println("setDisplaySettings called"); ds_ = ds; DefaultDisplaySettings.setStandardSettings(ds_); // RememberedChannelSettings.saveSettingsToProfile(settings, // store_.getSummaryMetadata(), store_.getAxisLength(Coords.CHANNEL)); // This will cause the canvas to pick up magnification changes, note. displayBus_.post(new NewDisplaySettingsEvent(ds_, this)); } @Override public DisplaySettings getDisplaySettings() { System.out.println("getDisplaySettings called"); return ds_; } @Override public void registerForEvents(Object o) { System.out.println("Registering for events"); displayBus_.register(o); } @Override public void unregisterForEvents(Object o) { System.out.println("Unregistering for events"); displayBus_.unregister(o); } @Override public void postEvent(Object o) { System.out.println("Posting even on the EventBus"); displayBus_.post(o); } @Override public Datastore getDatastore() { System.out.println("getDatastore called"); return store_; } @Override public void setDisplayedImageTo(Coords coords) { System.out.println("setDisplayedImageTo called and ignored"); } @Override /** * Assemble all images that are showing in our volume May need to be updated * for multiple time points in the future */ public List<Image> getDisplayedImages() { System.out.println("getDisplayed Images called"); List<Image> imageList = new ArrayList<>(); final int nrZ = store_.getAxisLength(Coords.Z); final int nrCh = store_.getAxisLength(Coords.CHANNEL); for (int ch = 0; ch < nrCh; ch++) { /* for (int i = 0; i < nrZ; i++) { coordsBuilder_ = coordsBuilder_.z(i).channel(ch).time(0).stagePosition(0); Coords coords = coordsBuilder_.build(); imageList.add(store_.getImage(coords)); } */ // Only return the middle image coordsBuilder_ = coordsBuilder_.z(nrZ / 2).channel(ch).time(0).stagePosition(0); Coords coords = coordsBuilder_.build(); imageList.add(store_.getImage(coords)); } return imageList; } @Override public void requestRedraw() { System.out.println("Redraw request received"); } @Override public boolean getIsClosed() { System.out.println("getIsClosed called, answered: " + !clearVolumeRenderer_.isShowing()); return !clearVolumeRenderer_.isShowing(); } @Override public String getName() { System.out.println("Name requested, gave: " + name_); return name_; } /** * This function is in CV 1.1.2, replace when updating Returns a transfer a * simple transfer function that is a gradient from dark transparent to a * given color. The transparency of the given color is used. * * @param pColor color * @return 1D transfer function. */ private TransferFunction1D getGradientForColor(Color pColor) { final TransferFunction1D lTransfertFunction = new TransferFunction1D(); lTransfertFunction.addPoint(0, 0, 0, 0); float lNormaFactor = (float) (1.0 / 255); lTransfertFunction.addPoint(lNormaFactor * pColor.getRed(), lNormaFactor * pColor.getGreen(), lNormaFactor * pColor.getBlue(), lNormaFactor * pColor.getAlpha()); return lTransfertFunction; } // Following functions are included since we need to be a DisplayWindow, not a DataViewer @Override public void displayStatusString(String string) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void setMagnification(double d) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void adjustZoom(double d) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public double getMagnification() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void autostretch() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public ImagePlus getImagePlus() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public boolean requestToClose() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void forceClosed() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void toggleFullScreen() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public GraphicsConfiguration getScreenConfig() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public DisplayWindow duplicate() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void toFront() { cvFrame_.toFront(); } @Override public ImageWindow getImageWindow() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Window getAsWindow() { return cvFrame_.getOwner(); } @Override public void setCustomTitle(String string) { } }
/** * * AcctWorkflowcost.java * @author echeng (table2type.pl) * * the AcctWorkflowcost * * */ package edu.yu.einstein.wasp.model; import java.util.Date; import java.util.List; import javax.persistence.*; import org.hibernate.envers.Audited; import org.hibernate.envers.NotAudited; import org.hibernate.validator.constraints.*; import org.codehaus.jackson.annotate.JsonIgnore; @Entity @Audited @Table(name="acct_workflowcost") public class AcctWorkflowcost extends WaspModel { /** * workflowId * */ @Id @GeneratedValue(strategy=GenerationType.IDENTITY) protected int workflowId; /** * setWorkflowId(int workflowId) * * @param workflowId * */ public void setWorkflowId (int workflowId) { this.workflowId = workflowId; } /** * getWorkflowId() * * @return workflowId * */ public int getWorkflowId () { return this.workflowId; } /** * basecost * */ @Column(name="basecost") protected float basecost; /** * setBasecost(float basecost) * * @param basecost * */ public void setBasecost (float basecost) { this.basecost = basecost; } /** * getBasecost() * * @return basecost * */ public float getBasecost () { return this.basecost; } /** * lastUpdTs * */ @Column(name="lastupdts") protected Date lastUpdTs; /** * setLastUpdTs(Date lastUpdTs) * * @param lastUpdTs * */ public void setLastUpdTs (Date lastUpdTs) { this.lastUpdTs = lastUpdTs; } /** * getLastUpdTs() * * @return lastUpdTs * */ public Date getLastUpdTs () { return this.lastUpdTs; } /** * lastUpdUser * */ @Column(name="lastupduser") protected int lastUpdUser; /** * setLastUpdUser(int lastUpdUser) * * @param lastUpdUser * */ public void setLastUpdUser (int lastUpdUser) { this.lastUpdUser = lastUpdUser; } /** * getLastUpdUser() * * @return lastUpdUser * */ public int getLastUpdUser () { return this.lastUpdUser; } /** * job * */ @NotAudited @ManyToOne @JoinColumn(name="workflowid", insertable=false, updatable=false) protected Job job; /** * setJob (Job job) * * @param job * */ public void setJob (Job job) { this.job = job; this.workflowId = job.workflowId; } /** * getJob () * * @return job * */ public Job getJob () { return this.job; } }
package main.java.engine.objects.tower; import main.java.engine.EnvironmentKnowledge; abstract class TowerBehaviorDecorator implements ITower { /** * The base tower will have behaviors added to it ("decorations") */ protected ITower baseTower; public TowerBehaviorDecorator (ITower baseTower) { this.baseTower = baseTower; } @Override public boolean atInterval (int intervalFrequency) { return baseTower.atInterval(intervalFrequency); } @Override public double getXCoordinate () { return baseTower.getXCoordinate(); } @Override public double getYCoordinate () { return baseTower.getYCoordinate(); } @Override public double getCost () { return baseTower.getCost(); } @Override public void remove () { baseTower.remove(); } @Override public boolean callTowerActions (EnvironmentKnowledge environ) { if (baseTower.callTowerActions(environ)) { // in addition to base tower's behavior, also do additional behavior doDecoratedBehavior(environ); return true; } return false; } abstract void doDecoratedBehavior (EnvironmentKnowledge environ); }
package eu.eumssi.uima.consumer; import static org.apache.uima.fit.util.JCasUtil.select; import static org.apache.uima.fit.util.JCasUtil.selectSingle; import java.io.IOException; import java.util.UUID; import java.util.logging.Logger; import org.apache.uima.UimaContext; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.fit.descriptor.ConfigurationParameter; import org.apache.uima.fit.factory.AnalysisEngineFactory; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; import org.xml.sax.SAXException; import com.mongodb.BasicDBObject; import edu.upf.glicom.uima.ts.opinion.OpinionExpression; import eu.eumssi.uima.ts.SourceMeta; /** * @author jgrivolla * */ public class Polar2MongoConsumer extends MongoConsumerBase { private static Logger logger = Logger.getLogger(Polar2MongoConsumer.class.toString()); static final String NEUTRAL = "NEUTRAL"; static final String POSITIVE = "POSITIVE"; static final String NEGATIVE = "NEGATIVE"; /* (non-Javadoc) * @see org.apache.uima.analysis_component.CasAnnotator_ImplBase#process(org.apache.uima.cas.CAS) */ @Override public void process(JCas jCAS) throws AnalysisEngineProcessException { SourceMeta meta = selectSingle(jCAS, SourceMeta.class); String documentText = jCAS.getDocumentText(); logger.fine("\n\n=========\n\n" + meta.getDocumentId() + ": " + documentText + "\n"); double finalPol = 0; String finalPolDiscrete = NEUTRAL; for (OpinionExpression oe: select(jCAS, OpinionExpression.class)) { finalPol = finalPol + Double.parseDouble(oe.getPolarity()); } // discretize if (finalPol > 0) { finalPolDiscrete = POSITIVE; } else if (finalPol < 0) { finalPolDiscrete = NEGATIVE; } /* write to MongoDB */ BasicDBObject polObject = new BasicDBObject(); polObject.append("discrete", finalPolDiscrete); polObject.append("numeric", finalPol); BasicDBObject query = new BasicDBObject(); query.append("_id", UUID.fromString(meta.getDocumentId())); BasicDBObject updates = new BasicDBObject(); updates.append(this.outputField, polObject); updates.append("processing.queues."+this.queueName, "processed"); BasicDBObject update = new BasicDBObject(); update.append("$set", updates); update.append("$addToSet", new BasicDBObject("processing.available_data", this.queueName)); try { this.coll.update(query, update); } catch (Exception e) { logger.severe(e.toString()); logger.severe(this.coll.findOne(new BasicDBObject("_id", UUID.fromString(meta.getDocumentId()))).toString()); } } /** * return example descriptor (XML) when calling main method * @param args * @throws IOException * @throws SAXException * @throws ResourceInitializationException */ public static void main(String[] args) throws ResourceInitializationException, SAXException, IOException { AnalysisEngineFactory.createEngineDescription(Polar2MongoConsumer.class).toXML(System.out); } }
package eu.h2020.symbiote.security.config; import com.mongodb.Mongo; import com.mongodb.MongoClient; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.config.AbstractMongoConfiguration; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @Configuration @EnableMongoRepositories("eu.h2020.symbiote.security.repositories") class AppConfig extends AbstractMongoConfiguration { private final Object syncObject = new Object(); private String databaseName; private MongoClient mongoClient = null; AppConfig(@Value("${aam.database.name}") String databaseName) { this.databaseName = databaseName; } @Override protected String getDatabaseName() { return databaseName; } @Override public Mongo mongo() throws Exception { synchronized (syncObject) { if (mongoClient == null) { mongoClient = new MongoClient(); } } return mongoClient; } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
package foodtruck.server.dashboard; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.common.base.Objects; import com.google.inject.Inject; import com.google.inject.Singleton; import foodtruck.truckstops.FoodTruckStopService; import foodtruck.util.Clock; /** * @author aviolette@gmail.com * @since 10/23/11 */ @Singleton public class TruckListServlet extends HttpServlet { private final FoodTruckStopService stopService; private final Clock clock; @Inject public TruckListServlet(FoodTruckStopService service, Clock clock) { this.stopService = service; this.clock = clock; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setAttribute("nav", "trucks"); req.setAttribute("localFrameworks", "true".equals(System.getProperty("use.local.frameworks", "false"))); req.setAttribute("tab", Objects.firstNonNull(req.getParameter("tab"), "home")); req.setAttribute("trucks", stopService.findCurrentAndPreviousStop(clock.currentDay())); req.getRequestDispatcher("/WEB-INF/jsp/dashboard/truckList.jsp").forward(req, resp); } }
package com.esuta.fidm.gui.page.org; import com.esuta.fidm.gui.component.behavior.VisibleEnableBehavior; import com.esuta.fidm.gui.component.data.ObjectDataProvider; import com.esuta.fidm.gui.component.data.column.EditDeleteButtonColumn; import com.esuta.fidm.gui.component.data.table.TablePanel; import com.esuta.fidm.gui.component.form.MultiValueTextEditPanel; import com.esuta.fidm.gui.component.form.MultiValueTextPanel; import com.esuta.fidm.gui.component.modal.ObjectChooserDialog; import com.esuta.fidm.gui.component.modal.SharingPolicyViewerDialog; import com.esuta.fidm.gui.component.model.LoadableModel; import com.esuta.fidm.gui.page.PageBase; import com.esuta.fidm.gui.page.resource.PageResource; import com.esuta.fidm.gui.page.roles.PageRole; import com.esuta.fidm.gui.page.users.PageUser; import com.esuta.fidm.infra.exception.DatabaseCommunicationException; import com.esuta.fidm.infra.exception.GeneralException; import com.esuta.fidm.infra.exception.ObjectNotFoundException; import com.esuta.fidm.model.ModelService; import com.esuta.fidm.model.federation.client.ObjectTypeRestResponse; import com.esuta.fidm.repository.schema.core.*; import com.esuta.fidm.repository.schema.support.FederationIdentifierType; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.apache.wicket.RestartResponseException; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.OnChangeAjaxBehavior; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink; import org.apache.wicket.behavior.AttributeAppender; import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.form.CheckBox; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.TextArea; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.model.AbstractReadOnlyModel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.model.PropertyModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.eclipse.jetty.http.HttpStatus; import java.util.ArrayList; import java.util.List; /** * @author shood * */ public class PageOrg extends PageBase { private transient Logger LOGGER = Logger.getLogger(PageOrg.class); private static final String ID_MAIN_FORM = "mainForm"; private static final String ID_NAME = "name"; private static final String ID_DISPLAY_NAME = "displayName"; private static final String ID_DESCRIPTION = "description"; private static final String ID_LOCALITY = "locality"; private static final String ID_ORG_TYPE = "orgType"; private static final String ID_PARENT_ORG_UNIT = "parentOrgUnits"; private static final String ID_FEDERATION_CONTAINER = "federationContainer"; private static final String ID_SHARE_IN_FEDERATION = "sharedInFederation"; private static final String ID_SHARE_SUBTREE = "sharedSubtree"; private static final String ID_OVERRIDE_SHARING = "overrideParentSharing"; private static final String ID_BUTTON_SAVE = "saveButton"; private static final String ID_BUTTON_RECOMPUTE = "recomputeButton"; private static final String ID_BUTTON_CANCEL = "cancelButton"; private static final String ID_RESOURCE_IND_CONTAINER = "resourceInducementsContainer"; private static final String ID_RESOURCE_IND_BUTTON_ADD = "addResourceInducement"; private static final String ID_RESOURCE_IND_TABLE = "resourceInducementsTable"; private static final String ID_ROLE_IND_CONTAINER = "roleInducementsContainer"; private static final String ID_ROLE_IND_BUTTON_ADD = "addRoleInducement"; private static final String ID_ROLE_IND_TABLE = "roleInducementsTable"; private static final String ID_MEMBERS_CONTAINER = "memberContainer"; private static final String ID_MEMBERS_TABLE = "membersTable"; private static final String ID_GOVERNORS_CONTAINER = "governorsContainer"; private static final String ID_BUTTON_ADD_GOVERNOR = "addGovernor"; private static final String ID_GOVERNORS_TABLE = "governorsTable"; private static final String ID_SHARING_POLICY_LABEL = "sharingPolicyLabel"; private static final String ID_SHARING_POLICY_EDIT = "sharingPolicyEdit"; private static final String ID_PARENT_ORG_UNIT_CHOOSER = "parentOrgUnitChooser"; private static final String ID_GOVERNOR_CHOOSER = "governorChooser"; private static final String ID_RESOURCE_INDUCEMENT_CHOOSER = "resourceInducementChooser"; private static final String ID_ROLE_INDUCEMENT_CHOOSER = "roleInducementChooser"; private static final String ID_SHARING_POLICY_CHOOSER = "sharingPolicyChooser"; private static final String ID_SHARING_POLICY_VIEWER = "sharingPolicyViewer"; private IModel<OrgType> model; private IModel<FederationSharingPolicyType> sharingPolicyModel; public PageOrg(){ this(null); } public PageOrg(PageParameters parameters){ super(parameters); model = new LoadableModel<OrgType>(false) { @Override protected OrgType load() { return loadOrgUnit(); } }; sharingPolicyModel = new LoadableModel<FederationSharingPolicyType>(false) { @Override protected FederationSharingPolicyType load() { return loadSharingPolicy(); } }; initLayout(); } @Override protected IModel<String> createPageSubtitleModel() { return new AbstractReadOnlyModel<String>() { @Override public String getObject() { if(isLocalOrgUnit()){ return "View/Edit local org. unit."; } else { return "View/Edit copy of org. unit. Origin IP: " + getOrgUnitOriginFederationMember(); } } }; } private OrgType loadOrgUnit(){ if(!isEditingOrgUnit()){ return new OrgType(); } PageParameters parameters = getPageParameters(); String uid = parameters.get(UID_PAGE_PARAMETER_NAME).toString(); OrgType org; try { org = getModelService().readObject(OrgType.class, uid); } catch (DatabaseCommunicationException exc){ error("Couldn't retrieve org. unit with oid: '" + uid + "' from the repository. Reason: " + exc.getExceptionMessage()); LOGGER.error("Couldn't retrieve org. unit with oid: '" + uid + "' from the repository. Reason: ", exc); throw new RestartResponseException(PageOrgList.class); } return org; } private FederationSharingPolicyType loadSharingPolicy(){ if(isLocalOrgUnit()){ return null; } FederationIdentifierType identifier = model.getObject().getFederationIdentifier(); String federationMemberName = identifier.getFederationMemberId(); try { ObjectTypeRestResponse<FederationSharingPolicyType> response = getFederationServiceClient() .createGetOrgSharingPolicyRequest(getFederationMemberByName(federationMemberName), identifier); int responseStatus = response.getStatus(); if(responseStatus == HttpStatus.OK_200){ return response.getValue(); } else { LOGGER.error("Could not retrieve sharing policy for this org. unit. Reason: " + response.getMessage()); error("Could not retrieve sharing policy for this org. unit. Reason: " + response.getMessage()); return null; } } catch (DatabaseCommunicationException e) { LOGGER.error("Could not retrieve sharing policy for this org. unit.", e); error("Could not retrieve sharing policy for this org. unit. Reason: " + e); } return null; } private boolean isEditingOrgUnit(){ PageParameters parameters = getPageParameters(); return !parameters.get(UID_PAGE_PARAMETER_NAME).isEmpty(); } private boolean isLocalOrgUnit(){ if(model != null && model.getObject() != null){ OrgType org = model.getObject(); return org.getFederationIdentifier() == null; } return true; } private String getOrgUnitOriginFederationMember(){ if(model != null && model.getObject() != null && model.getObject().getFederationIdentifier() != null){ OrgType org = model.getObject(); return org.getFederationIdentifier().getFederationMemberId(); } return null; } private void initLayout(){ Form mainForm = new Form(ID_MAIN_FORM); mainForm.setOutputMarkupId(true); add(mainForm); TextField name = new TextField<>(ID_NAME, new PropertyModel<String>(model, "name")); name.setRequired(true); mainForm.add(name); TextField displayName = new TextField<>(ID_DISPLAY_NAME, new PropertyModel<String>(model, "displayName")); displayName.setRequired(true); mainForm.add(displayName); TextArea description = new TextArea<>(ID_DESCRIPTION, new PropertyModel<String>(model, "description")); mainForm.add(description); TextField locality = new TextField<>(ID_LOCALITY, new PropertyModel<String>(model, "locality")); mainForm.add(locality); MultiValueTextPanel orgType = new MultiValueTextPanel<>(ID_ORG_TYPE, new PropertyModel<List<String>>(model, "orgType"), false); mainForm.add(orgType); MultiValueTextEditPanel parentOrgUnit = new MultiValueTextEditPanel<ObjectReferenceType<OrgType>>(ID_PARENT_ORG_UNIT, new PropertyModel<List<ObjectReferenceType<OrgType>>>(model, "parentOrgUnits"), false){ @Override protected IModel<String> createTextModel(IModel<ObjectReferenceType<OrgType>> model) { return createParentOrgUnitDisplayModel(model); } @Override protected ObjectReferenceType<OrgType> createNewEmptyItem() { return new ObjectReferenceType<>(); } @Override protected void editPerformed(AjaxRequestTarget target, ObjectReferenceType<OrgType> object) { PageOrg.this.editParentOrgUnitPerformed(target); } }; mainForm.add(parentOrgUnit); TextField sharingPolicyLabel = new TextField<>(ID_SHARING_POLICY_LABEL, createSharingPolicyLabel()); sharingPolicyLabel.setOutputMarkupId(true); sharingPolicyLabel.add(AttributeAppender.replace("placeholder", "Set policy")); sharingPolicyLabel.setEnabled(false); mainForm.add(sharingPolicyLabel); AjaxLink sharingPolicyEdit = new AjaxLink(ID_SHARING_POLICY_EDIT) { @Override public void onClick(AjaxRequestTarget target) { sharingPolicyEditPerformed(target); } }; mainForm.add(sharingPolicyEdit); WebMarkupContainer federationContainer = new WebMarkupContainer(ID_FEDERATION_CONTAINER); federationContainer.setOutputMarkupId(true); federationContainer.add(new VisibleEnableBehavior(){ @Override public boolean isVisible() { //If the org. unit is not in local federation member, the section //where federation options are edited should not be visible at all. return model.getObject().getFederationIdentifier() == null; } }); mainForm.add(federationContainer); CheckBox sharedInFederation = new CheckBox(ID_SHARE_IN_FEDERATION, new PropertyModel<Boolean>(model, "sharedInFederation")); sharedInFederation.add(new OnChangeAjaxBehavior() { @Override protected void onUpdate(AjaxRequestTarget target) { target.add(getFederationContainer()); } }); federationContainer.add(sharedInFederation); CheckBox shareSubtree = new CheckBox(ID_SHARE_SUBTREE, new PropertyModel<Boolean>(model, "sharedSubtree")); shareSubtree.add(new VisibleEnableBehavior(){ @Override public boolean isEnabled() { return model.getObject().isSharedInFederation(); } }); federationContainer.add(shareSubtree); CheckBox overrideSharing = new CheckBox(ID_OVERRIDE_SHARING, new PropertyModel<Boolean>(model, "overrideParentSharing")); overrideSharing.add(new VisibleEnableBehavior(){ @Override public boolean isEnabled() { //Can't override parent sharing when the org. unit is root. if(model.getObject().getParentOrgUnits().isEmpty()){ return false; } return model.getObject().isSharedInFederation(); } }); federationContainer.add(overrideSharing); initButtons(mainForm); initModalWindows(); initInducements(mainForm); initContainers(mainForm); } private IModel<String> createSharingPolicyLabel(){ return new AbstractReadOnlyModel<String>() { @Override public String getObject() { if(model == null || model.getObject() == null || model.getObject().getSharingPolicy() == null){ return "Set Policy"; } if(!isLocalOrgUnit()){ return "View origin sharing policy"; } ObjectReferenceType sharingPolicyRef = model.getObject().getSharingPolicy(); String sharingPolicyUid = sharingPolicyRef.getUid(); try { FederationSharingPolicyType policy = getModelService().readObject(FederationSharingPolicyType.class, sharingPolicyUid); return policy.getName(); } catch (DatabaseCommunicationException e) { error("Could not load sharing policy with uid: '" + sharingPolicyUid + "' from the repository."); LOGGER.error("Could not load sharing policy with uid: '" + sharingPolicyUid + "' from the repository."); } return "Set Policy"; } }; } private void initButtons(Form mainForm){ AjaxSubmitLink cancel = new AjaxSubmitLink(ID_BUTTON_CANCEL) { @Override protected void onSubmit(AjaxRequestTarget target, Form<?> form) { cancelPerformed(); } }; cancel.setDefaultFormProcessing(false); mainForm.add(cancel); AjaxSubmitLink save = new AjaxSubmitLink(ID_BUTTON_SAVE) { @Override protected void onSubmit(AjaxRequestTarget target, Form<?> form) { savePerformed(target); } @Override protected void onError(AjaxRequestTarget target, Form<?> form) { target.add(getFeedbackPanel()); } }; mainForm.add(save); AjaxSubmitLink recompute = new AjaxSubmitLink(ID_BUTTON_RECOMPUTE) { @Override protected void onSubmit(AjaxRequestTarget target, Form<?> form) { recomputePerformed(target); } @Override protected void onError(AjaxRequestTarget target, Form<?> form) { target.add(getFeedbackPanel()); } }; recompute.add(new VisibleEnableBehavior(){ @Override public boolean isEnabled() { return isEditingOrgUnit(); } }); mainForm.add(recompute); } private void initModalWindows(){ ModalWindow resourceInducementChooser = new ObjectChooserDialog<ResourceType>(ID_RESOURCE_INDUCEMENT_CHOOSER, ResourceType.class){ @Override public void objectChoosePerformed(AjaxRequestTarget target, IModel<ResourceType> rowModel) { resourceInducementChoosePerformed(target, rowModel, isSharedInFederation()); } @Override public String getChooserTitle() { return "Choose Resource Inducement"; } @Override public List<ResourceType> applyObjectFilter(List<ResourceType> list) { return applyResourceInducementChooserFilter(list); } }; add(resourceInducementChooser); ModalWindow roleInducementChooser = new ObjectChooserDialog<RoleType>(ID_ROLE_INDUCEMENT_CHOOSER, RoleType.class){ @Override public void objectChoosePerformed(AjaxRequestTarget target, IModel<RoleType> rowModel) { roleInducementChoosePerformed(target, rowModel, isSharedInFederation()); } @Override public String getChooserTitle() { return "Choose Role Inducement"; } @Override public List<RoleType> applyObjectFilter(List<RoleType> list) { return applyRoleInducementChooserFilter(list); } }; add(roleInducementChooser); ModalWindow parentOrgUnitChooser = new ObjectChooserDialog<OrgType>(ID_PARENT_ORG_UNIT_CHOOSER, OrgType.class){ @Override public void objectChoosePerformed(AjaxRequestTarget target, IModel<OrgType> rowModel) { parentOrgUnitChoosePerformed(target, rowModel, isSharedInFederation()); } @Override public String getChooserTitle() { return "Choose parent org. unit"; } @Override public List<OrgType> applyObjectFilter(List<OrgType> list) { return applyParentOrgChooserFilter(list); } }; add(parentOrgUnitChooser); ModalWindow governorChooser = new ObjectChooserDialog<UserType>(ID_GOVERNOR_CHOOSER, UserType.class){ @Override public void objectChoosePerformed(AjaxRequestTarget target, IModel<UserType> rowModel) { governorChoosePerformed(target, rowModel, isSharedInFederation()); } @Override public String getChooserTitle() { return "Choose governor."; } @Override public List<UserType> applyObjectFilter(List<UserType> list) { return applyGovernorChooserFilter(list); } }; add(governorChooser); ModalWindow sharingPolicyChooser = new ObjectChooserDialog<FederationSharingPolicyType>(ID_SHARING_POLICY_CHOOSER, FederationSharingPolicyType.class){ @Override public void objectChoosePerformed(AjaxRequestTarget target, IModel<FederationSharingPolicyType> rowModel) { sharingPolicyChoosePerformed(target, rowModel); } @Override public String getChooserTitle() { return "Choose parent org. unit"; } @Override public boolean isSharedInFederationEnabled() { return false; } }; ((ObjectChooserDialog)sharingPolicyChooser).setSharedInFederation(true); add(sharingPolicyChooser); ModalWindow sharingPolicyViewer = new SharingPolicyViewerDialog(ID_SHARING_POLICY_VIEWER, null); add(sharingPolicyViewer); } private void initInducements(Form mainForm){ //Resource Inducements Container WebMarkupContainer resourceInducementsContainer = new WebMarkupContainer(ID_RESOURCE_IND_CONTAINER); resourceInducementsContainer.setOutputMarkupId(true); resourceInducementsContainer.setOutputMarkupPlaceholderTag(true); mainForm.add(resourceInducementsContainer); AjaxLink addResourceInducement = new AjaxLink(ID_RESOURCE_IND_BUTTON_ADD) { @Override public void onClick(AjaxRequestTarget target) { addResourceInducementPerformed(target); } }; resourceInducementsContainer.add(addResourceInducement); List<IColumn> resourceInducementColumns = createResourceInducementColumns(); final ObjectDataProvider resourceInducementsProvider = new ObjectDataProvider<ResourceType>(getPage(), ResourceType.class){ @Override public List<ResourceType> applyDataFilter(List<ResourceType> list) { List<ResourceType> resourceInducementList = new ArrayList<>(); if(model != null && model.getObject() != null){ OrgType org = model.getObject(); for(ResourceType resource: list){ for(InducementType<ResourceType> resourceInducement: org.getResourceInducements()){ if(resourceInducement.getUid().equals(resource.getUid())){ resourceInducementList.add(resource); break; } } } } return resourceInducementList; } }; TablePanel resourceInducementsTable = new TablePanel(ID_RESOURCE_IND_TABLE, resourceInducementsProvider, resourceInducementColumns, 10); resourceInducementsTable.add(new VisibleEnableBehavior(){ @Override public boolean isVisible() { return resourceInducementsProvider.size() > 0; } }); resourceInducementsTable.setShowPaging(false); resourceInducementsTable.setOutputMarkupId(true); resourceInducementsContainer.add(resourceInducementsTable); //Role Inducements Container WebMarkupContainer roleInducementsContainer = new WebMarkupContainer(ID_ROLE_IND_CONTAINER); roleInducementsContainer.setOutputMarkupId(true); roleInducementsContainer.setOutputMarkupPlaceholderTag(true); mainForm.add(roleInducementsContainer); AjaxLink addRoleInducement = new AjaxLink(ID_ROLE_IND_BUTTON_ADD) { @Override public void onClick(AjaxRequestTarget target) { addRoleInducementPerformed(target); } }; roleInducementsContainer.add(addRoleInducement); List<IColumn> roleInducementColumns = createRoleInducementColumns(); final ObjectDataProvider roleInducementsProvider = new ObjectDataProvider<RoleType>(getPage(), RoleType.class){ @Override public List<RoleType> applyDataFilter(List<RoleType> list) { List<RoleType> roleInducementList = new ArrayList<>(); if(model != null && model.getObject() != null){ OrgType org = model.getObject(); for(RoleType role: list){ for(InducementType<RoleType> roleInducement: org.getRoleInducements()){ if(roleInducement.getUid().equals(role.getUid())){ roleInducementList.add(role); break; } } } } return roleInducementList; } }; TablePanel roleInducementsTable = new TablePanel(ID_ROLE_IND_TABLE, roleInducementsProvider, roleInducementColumns, 10); roleInducementsTable.add(new VisibleEnableBehavior() { @Override public boolean isVisible() { return roleInducementsProvider.size() > 0; } }); roleInducementsTable.setOutputMarkupId(true); roleInducementsTable.setShowPaging(false); roleInducementsContainer.add(roleInducementsTable); } private List<IColumn> createResourceInducementColumns(){ List<IColumn> columns = new ArrayList<>(); columns.add(new PropertyColumn<ResourceType, String>(new Model<>("Name"), "name", "name")); columns.add(new PropertyColumn<ResourceType, String>(new Model<>("Type"), "resourceType", "resourceType")); columns.add(new EditDeleteButtonColumn<ResourceType>(new Model<>("Actions")){ @Override public void editPerformed(AjaxRequestTarget target, IModel<ResourceType> rowModel) { PageOrg.this.editResourceInducementPerformed(target, rowModel); } @Override public void removePerformed(AjaxRequestTarget target, IModel<ResourceType> rowModel) { PageOrg.this.removeResourceInducementPerformed(target, rowModel); } }); return columns; } private List<IColumn> createRoleInducementColumns(){ List<IColumn> columns = new ArrayList<>(); columns.add(new PropertyColumn<RoleType, String>(new Model<>("Name"), "name", "name")); columns.add(new PropertyColumn<RoleType, String>(new Model<>("DisplayName"), "displayName", "displayName")); columns.add(new PropertyColumn<RoleType, String>(new Model<>("Type"), "roleType", "roleType")); columns.add(new EditDeleteButtonColumn<RoleType>(new Model<>("Actions")){ @Override public void editPerformed(AjaxRequestTarget target, IModel<RoleType> rowModel) { PageOrg.this.editRoleInducementPerformed(target, rowModel); } @Override public void removePerformed(AjaxRequestTarget target, IModel<RoleType> rowModel) { PageOrg.this.removeRoleInducementPerformed(target, rowModel); } }); return columns; } private void initContainers(Form mainForm){ //Members Container WebMarkupContainer membersContainer = new WebMarkupContainer(ID_MEMBERS_CONTAINER); membersContainer.setOutputMarkupId(true); membersContainer.setOutputMarkupPlaceholderTag(true); mainForm.add(membersContainer); List<IColumn> membersColumns = createMemberColumns(); final ObjectDataProvider membersProvider = new ObjectDataProvider<UserType>(getPage(), UserType.class){ @Override public List<UserType> applyDataFilter(List<UserType> list) { List<UserType> memberList = new ArrayList<>(); if(model != null && model.getObject() != null){ String orgUid = model.getObject().getUid(); for(UserType user: list){ for(AssignmentType<OrgType> orgAssignment: user.getOrgUnitAssignments()){ if(orgAssignment.getUid().equals(orgUid)){ memberList.add(user); } } } } return memberList; } }; TablePanel membersTable = new TablePanel(ID_MEMBERS_TABLE, membersProvider, membersColumns, 10); membersTable.add(new VisibleEnableBehavior(){ @Override public boolean isVisible() { return membersProvider.size() > 0; } }); membersTable.setOutputMarkupId(true); membersContainer.add(membersTable); //Governors Container WebMarkupContainer governorsContainer = new WebMarkupContainer(ID_GOVERNORS_CONTAINER); governorsContainer.setOutputMarkupId(true); governorsContainer.setOutputMarkupPlaceholderTag(true); mainForm.add(governorsContainer); AjaxLink addOrgUnit = new AjaxLink(ID_BUTTON_ADD_GOVERNOR) { @Override public void onClick(AjaxRequestTarget target) { addGovernorPerformed(target); } }; governorsContainer.add(addOrgUnit); List<IColumn> governorsColumn = createGovernorColumns(); final ObjectDataProvider governorsProvider = new ObjectDataProvider<UserType>(getPage(), UserType.class){ @Override public List<UserType> applyDataFilter(List<UserType> list) { List<UserType> managersList = new ArrayList<>(); if(model != null && model.getObject() != null){ List<ObjectReferenceType<UserType>> managers = model.getObject().getGovernors(); for(UserType user: list){ for(ObjectReferenceType<UserType> managerRef: managers){ if(managerRef.getUid().equals(user.getUid())){ managersList.add(user); } } } } return managersList; } }; TablePanel governorsTable = new TablePanel(ID_GOVERNORS_TABLE, governorsProvider, governorsColumn, 10); governorsTable.add(new VisibleEnableBehavior(){ @Override public boolean isVisible() { return governorsProvider.size() > 0; } }); governorsTable.setOutputMarkupId(true); governorsContainer.add(governorsTable); } private List<IColumn> createMemberColumns(){ List<IColumn> columns = new ArrayList<>(); columns.add(new PropertyColumn<UserType, String>(new Model<>("Name"), "name", "name")); columns.add(new PropertyColumn<UserType, String>(new Model<>("Given Name"), "givenName", "givenName")); columns.add(new PropertyColumn<UserType, String>(new Model<>("Family Name"), "familyName", "familyName")); columns.add(new PropertyColumn<UserType, String>(new Model<>("E-mail"), "emailAddress", "emailAddress")); columns.add(new PropertyColumn<UserType, String>(new Model<>("Locality"), "locality", "locality")); columns.add(new EditDeleteButtonColumn<UserType>(new Model<>("Actions")){ @Override public void editPerformed(AjaxRequestTarget target, IModel<UserType> rowModel) { PageOrg.this.editMemberPerformed(target, rowModel); } @Override public boolean getRemoveVisible() { return false; } }); return columns; } private List<IColumn> createGovernorColumns(){ List<IColumn> columns = new ArrayList<>(); columns.add(new PropertyColumn<UserType, String>(new Model<>("Name"), "name", "name")); columns.add(new PropertyColumn<UserType, String>(new Model<>("Given Name"), "givenName", "givenName")); columns.add(new PropertyColumn<UserType, String>(new Model<>("Family Name"), "familyName", "familyName")); columns.add(new PropertyColumn<UserType, String>(new Model<>("E-mail"), "emailAddress", "emailAddress")); columns.add(new PropertyColumn<UserType, String>(new Model<>("Locality"), "locality", "locality")); columns.add(new EditDeleteButtonColumn<UserType>(new Model<>("Actions")){ @Override public void editPerformed(AjaxRequestTarget target, IModel<UserType> rowModel) { PageOrg.this.editGovernorPerformed(target, rowModel); } @Override public void removePerformed(AjaxRequestTarget target, IModel<UserType> rowModel) { PageOrg.this.removeGovernorPerformed(target, rowModel); } }); return columns; } private Form getMainForm(){ return (Form) get(ID_MAIN_FORM); } private WebMarkupContainer getFederationContainer(){ return (WebMarkupContainer) get(ID_MAIN_FORM + ":" + ID_FEDERATION_CONTAINER); } private WebMarkupContainer getResourceInducementsContainer(){ return (WebMarkupContainer) get(ID_MAIN_FORM + ":" + ID_RESOURCE_IND_CONTAINER); } private WebMarkupContainer getRoleInducementsContainer(){ return (WebMarkupContainer) get(ID_MAIN_FORM + ":" + ID_ROLE_IND_CONTAINER); } private WebMarkupContainer getMembersContainer(){ return (WebMarkupContainer) get(ID_MAIN_FORM + ":" + ID_MEMBERS_CONTAINER); } private WebMarkupContainer getGovernorsContainer(){ return (WebMarkupContainer) get(ID_MAIN_FORM + ":" + ID_GOVERNORS_CONTAINER); } private IModel<String> createParentOrgUnitDisplayModel(final IModel<ObjectReferenceType<OrgType>> parentRef){ return new LoadableModel<String>() { @Override protected String load() { if(parentRef == null || parentRef.getObject() == null || parentRef.getObject().getUid() == null){ return null; } String orgUid = parentRef.getObject().getUid(); OrgType parent = null; try { parent = getModelService().readObject(OrgType.class, orgUid); } catch (DatabaseCommunicationException e) { LOGGER.error("Parent org. unit with uid: '" + orgUid + "' does not exist."); error("Parent org. unit with uid: '" + orgUid + "' does not exist."); } if(parent == null){ return null; } return parent.getDisplayName(); } }; } private void sharingPolicyEditPerformed(AjaxRequestTarget target){ //If we are editing local org. unit, we can edit sharing policy, //else, the user is only able to view the policy rules if(isLocalOrgUnit()){ ModalWindow window = (ModalWindow) get(ID_SHARING_POLICY_CHOOSER); window.show(target); } else { SharingPolicyViewerDialog window = (SharingPolicyViewerDialog) get(ID_SHARING_POLICY_VIEWER); window.updateModel(sharingPolicyModel.getObject().getRules()); window.show(target); } } private void resourceInducementChoosePerformed(AjaxRequestTarget target, IModel<ResourceType> resourceModel, boolean isSharedInFederation){ if(resourceModel == null || resourceModel.getObject() == null){ return; } if(model.getObject() == null){ return; } String resourceUid = resourceModel.getObject().getUid(); InducementType<ResourceType> resourceInducement = new InducementType<>(resourceUid, ResourceType.class); resourceInducement.setSharedInFederation(isSharedInFederation); model.getObject().getResourceInducements().add(resourceInducement); ModalWindow window = (ModalWindow) get(ID_RESOURCE_INDUCEMENT_CHOOSER); window.close(target); target.add(getResourceInducementsContainer()); } private void roleInducementChoosePerformed(AjaxRequestTarget target, IModel<RoleType> roleModel, boolean isSharedInFederation){ if(roleModel == null || roleModel.getObject() == null){ return; } if(model.getObject() == null){ return; } String roleUid = roleModel.getObject().getUid(); InducementType<RoleType> roleInducement = new InducementType<>(roleUid, RoleType.class); roleInducement.setSharedInFederation(isSharedInFederation); model.getObject().getRoleInducements().add(roleInducement); ModalWindow window = (ModalWindow) get(ID_ROLE_INDUCEMENT_CHOOSER); window.close(target); target.add(getRoleInducementsContainer()); } private void governorChoosePerformed(AjaxRequestTarget target, IModel<UserType> governorModel, boolean sharedInFederation){ if(governorModel == null || governorModel.getObject() == null){ return; } if(model.getObject() == null){ return; } String governorUid = governorModel.getObject().getUid(); ObjectReferenceType<UserType> governorReference = new ObjectReferenceType<>(governorUid, UserType.class); governorReference.setSharedInFederation(sharedInFederation); model.getObject().getGovernors().add(governorReference); ModalWindow window = (ModalWindow) get(ID_GOVERNOR_CHOOSER); window.close(target); target.add(getGovernorsContainer()); } private void sharingPolicyChoosePerformed(AjaxRequestTarget target, IModel<FederationSharingPolicyType> rowModel){ if(rowModel == null || rowModel.getObject() == null){ return; } if(model.getObject() == null){ return; } OrgType org = model.getObject(); FederationSharingPolicyType policy = rowModel.getObject(); ObjectReferenceType<FederationSharingPolicyType> policyRef = new ObjectReferenceType<>(); policyRef.setUid(policy.getUid()); policyRef.setSharedInFederation(true); policyRef.setType(FederationSharingPolicyType.class); org.setSharingPolicy(policyRef); ModalWindow window = (ModalWindow) get(ID_SHARING_POLICY_CHOOSER); window.close(target); target.add(get(ID_MAIN_FORM + ":" + ID_SHARING_POLICY_LABEL)); } /** * TODO - filter org. unit that can be chosen as parents, some cases: * * any org. unit from sub-tree (to prevent cycles in org. unit hierarchy) * */ private List<OrgType> applyParentOrgChooserFilter(List<OrgType> list){ List<OrgType> newOrgList = new ArrayList<>(); if(model.getObject() == null || !isEditingOrgUnit()){ return list; } List<ObjectReferenceType<OrgType>> parentOrgUnits = model.getObject().getParentOrgUnits(); String currentOrgUid = model.getObject().getUid(); for(OrgType org: list){ ObjectReferenceType<OrgType> parentReference = new ObjectReferenceType<>(org.getUid(), OrgType.class); if(!parentOrgUnits.contains(parentReference) && !currentOrgUid.equals(org.getUid())){ newOrgList.add(org); } } return newOrgList; } private List<ResourceType> applyResourceInducementChooserFilter(List<ResourceType> list){ List<ResourceType> newResourceList = new ArrayList<>(); if(model.getObject() == null){ return list; } List<InducementType<ResourceType>> currentResourceInducements = model.getObject().getResourceInducements(); for(ResourceType resource: list){ InducementType<ResourceType> resourceInducement = new InducementType<>(resource.getUid(), ResourceType.class); if(!currentResourceInducements.contains(resourceInducement)){ newResourceList.add(resource); } } return newResourceList; } private List<RoleType> applyRoleInducementChooserFilter(List<RoleType> list){ List<RoleType> newRoleList = new ArrayList<>(); if(model.getObject() == null){ return list; } List<InducementType<RoleType>> currentRoleInducements = model.getObject().getRoleInducements(); for(RoleType role: list){ InducementType<RoleType> roleInducement = new InducementType<>(role.getUid(), RoleType.class); if(!currentRoleInducements.contains(roleInducement)){ newRoleList.add(role); } } return newRoleList; } private List<UserType> applyGovernorChooserFilter(List<UserType> list){ List<UserType> newUserList = new ArrayList<>(); if(model.getObject() == null){ return list; } List<ObjectReferenceType<UserType>> currentGovernors = model.getObject().getGovernors(); for(UserType user: list){ ObjectReferenceType<UserType> governorReference = new ObjectReferenceType<>(user.getUid(), UserType.class); if(!currentGovernors.contains(governorReference)){ newUserList.add(user); } } return newUserList; } private void editParentOrgUnitPerformed(AjaxRequestTarget target){ ModalWindow modal = (ModalWindow) get(ID_PARENT_ORG_UNIT_CHOOSER); modal.show(target); } private void parentOrgUnitChoosePerformed(AjaxRequestTarget target, IModel<OrgType> rowModel, boolean isSharedInFederation){ if(rowModel == null || rowModel.getObject() == null){ error("Chosen value is not a valid org. unit."); target.add(getFeedbackPanel()); return; } if(model == null || model.getObject() == null){ error("Couldn't add parent org. to this org. unit. Invalid org. unit model, please refresh this page."); target.add(getFeedbackPanel()); return; } String uid = rowModel.getObject().getUid(); ObjectReferenceType<OrgType> parentReference = new ObjectReferenceType<>(uid, OrgType.class); parentReference.setSharedInFederation(isSharedInFederation); model.getObject().getParentOrgUnits().add(parentReference); ModalWindow dialog = (ModalWindow) get(ID_PARENT_ORG_UNIT_CHOOSER); dialog.close(target); target.add(get(ID_MAIN_FORM + ":" + ID_PARENT_ORG_UNIT)); } private void editResourceInducementPerformed(AjaxRequestTarget target, IModel<ResourceType> resourceModel){ if(resourceModel == null || resourceModel.getObject() == null){ error("Couldn't edit selected resource inducement. It is no longer available."); target.add(getFeedbackPanel()); return; } PageParameters parameters = new PageParameters(); parameters.add(UID_PAGE_PARAMETER_NAME, resourceModel.getObject().getUid()); setResponsePage(new PageResource(parameters)); } private void editRoleInducementPerformed(AjaxRequestTarget target, IModel<RoleType> roleModel){ if(roleModel == null || roleModel.getObject() == null){ error("Couldn't edit selected role inducement. It is no longer available."); target.add(getFeedbackPanel()); return; } PageParameters parameters = new PageParameters(); parameters.add(UID_PAGE_PARAMETER_NAME, roleModel.getObject().getUid()); setResponsePage(new PageRole(parameters)); } private void editMemberPerformed(AjaxRequestTarget target, IModel<UserType> rowModel){ if(rowModel == null || rowModel.getObject() == null){ error("Couldn't edit selected user. It is no longer available."); target.add(getFeedbackPanel()); return; } PageParameters parameters = new PageParameters(); parameters.add(UID_PAGE_PARAMETER_NAME, rowModel.getObject().getUid()); setResponsePage(new PageUser(parameters)); } /* * Since governor is also a UserType, we can use editMemberPerformed() method * */ private void editGovernorPerformed(AjaxRequestTarget target, IModel<UserType> rowModel){ editMemberPerformed(target, rowModel); } private void addResourceInducementPerformed(AjaxRequestTarget target){ ModalWindow modal = (ModalWindow) get(ID_RESOURCE_INDUCEMENT_CHOOSER); modal.show(target); } private void addRoleInducementPerformed(AjaxRequestTarget target){ ModalWindow modal = (ModalWindow) get(ID_ROLE_INDUCEMENT_CHOOSER); modal.show(target); } private void addGovernorPerformed(AjaxRequestTarget target){ ModalWindow modal = (ModalWindow) get(ID_GOVERNOR_CHOOSER); modal.show(target); } private void removeGovernorPerformed(AjaxRequestTarget target, IModel<UserType> rowModel){ if(rowModel == null || rowModel.getObject() == null){ error("Couldn't remove selected governor assignment. Something went wrong."); target.add(getFeedbackPanel()); return; } String governorUid = rowModel.getObject().getUid(); ObjectReferenceType<UserType> governorToRemove = new ObjectReferenceType<>(); for(ObjectReferenceType<UserType> governorRef: model.getObject().getGovernors()){ if(governorRef.getUid().equals(governorUid)){ governorToRemove = governorRef; break; } } model.getObject().getGovernors().remove(governorToRemove); success("Governor with uid: '" + governorUid + "' was removed successfully."); target.add(getGovernorsContainer(), getFeedbackPanel()); } private void removeResourceInducementPerformed(AjaxRequestTarget target, IModel<ResourceType> resourceModel){ if(resourceModel == null || resourceModel.getObject() == null){ error("Couldn't remove selected resource inducement. Something went wrong."); target.add(getFeedbackPanel()); return; } String resourceInducementUid = resourceModel.getObject().getUid(); InducementType<ResourceType> resourceInducementToRemove = new InducementType<>(); for(InducementType<ResourceType> inducementRef: model.getObject().getResourceInducements()){ if(inducementRef.getUid().equals(resourceInducementUid)){ resourceInducementToRemove = inducementRef; break; } } model.getObject().getResourceInducements().remove(resourceInducementToRemove); success("Resource inducement with to resource with uid: '" + resourceInducementUid + "' was removed successfully."); target.add(getResourceInducementsContainer(), getFeedbackPanel()); } private void removeRoleInducementPerformed(AjaxRequestTarget target, IModel<RoleType> roleModel){ if(roleModel == null || roleModel.getObject() == null){ error("Couldn't remove selected role inducement. Something went wrong."); target.add(getFeedbackPanel()); return; } String roleInducementUid = roleModel.getObject().getUid(); InducementType<RoleType> roleInducementToRemove = new InducementType<>(); for(InducementType<RoleType> inducementRef: model.getObject().getRoleInducements()){ if(inducementRef.getUid().equals(roleInducementUid)){ roleInducementToRemove = inducementRef; break; } } model.getObject().getRoleInducements().remove(roleInducementToRemove); success("Role inducement with to resource with uid: '" + roleInducementUid + "' was removed successfully."); target.add(getRoleInducementsContainer(), getFeedbackPanel()); } private void cancelPerformed(){ setResponsePage(PageOrgList.class); } private void recomputePerformed(AjaxRequestTarget target){ if(model == null || model.getObject() == null){ error("Couldn't recompute org. unit."); target.add(getFeedbackPanel()); return; } OrgType orgUnit = model.getObject(); if(!isEditingOrgUnit()){ warn("Can't recompute org. unit not yet saved in repository."); target.add(getFeedbackPanel()); return; } try { getModelService().recomputeOrganizationalUnit(orgUnit); success("Org. unit: '" + orgUnit.getName() + "'(" + orgUnit.getUid() + ") RECOMPUTE was successful."); } catch (DatabaseCommunicationException | ObjectNotFoundException e) { LOGGER.error("Can't recompute org. unit: ", e); error("Can't recompute org. unit with name: '" + orgUnit.getName() + "'. Reason: " + e.getExceptionMessage()); } target.add(this, getFeedbackPanel()); } private void shareOrgSubtree(OrgType org){ String uid = org.getUid(); try { List<OrgType> allOrgUnits = getModelService().getAllObjectsOfType(OrgType.class); List<OrgType> children = new ArrayList<>(); //First, retrieve all children of target org. unit for(OrgType orgUnit: allOrgUnits){ for(ObjectReferenceType orgReference: orgUnit.getParentOrgUnits()){ if(uid.equals(orgReference.getUid())){ children.add(orgUnit); break; } } } //If the children does not override parent sharing, set sharing to true and save for(OrgType orgUnit: children){ if(!orgUnit.isOverrideParentSharing()){ orgUnit.setSharedInFederation(true); getModelService().updateObject(orgUnit); success("Org. unit: '" + orgUnit.getName() + "' federation sharing set successfully."); } } //Repeat the process recursively for entire tree for(OrgType orgUnit: children){ shareOrgSubtree(orgUnit); } } catch (DatabaseCommunicationException e) { LOGGER.error("Can't retrieve the children of org. unit: " + org.getName() + ". Reason: ", e); error("Can't retrieve the children of org. unit: " + org.getName() + ". Reason: " + e); } catch (ObjectNotFoundException e) { LOGGER.error("Can't save children org. unit. Reason: ", e); error("Can't save children org. unit. Reason: " + e); } } private void savePerformed(AjaxRequestTarget target){ ModelService modelService = getModelService(); OrgType orgUnit; if(model == null || model.getObject() == null){ error("Couldn't save org. unit."); target.add(getFeedbackPanel()); return; } orgUnit = model.getObject(); //If org. unit is shared in federation, sharing policy must be specified if(orgUnit.isSharedInFederation()){ if(orgUnit.getSharingPolicy() == null){ error("Sharing policy must be specified for org. unit shared in federation. Specify a sharing" + "policy for this org. unit or do not share it in federation."); target.add(getFeedbackPanel()); return; } } //Filtering empty org. unit types List<String> newOrgTypes = new ArrayList<>(); for(String type: orgUnit.getOrgType()){ if(type != null && StringUtils.isNotEmpty(type)){ newOrgTypes.add(type); } } orgUnit.getOrgType().clear(); orgUnit.getOrgType().addAll(newOrgTypes); //Filtering empty parent references List<ObjectReferenceType<OrgType>> newParentReferences = new ArrayList<>(); for(ObjectReferenceType<OrgType> parentRef: orgUnit.getParentOrgUnits()){ if(parentRef != null && parentRef.getUid() != null && parentRef.getType() != null){ newParentReferences.add(parentRef); } } orgUnit.getParentOrgUnits().clear(); orgUnit.getParentOrgUnits().addAll(newParentReferences); try{ if(!isEditingOrgUnit()){ modelService.createObject(orgUnit); } else { modelService.updateObject(orgUnit); if(orgUnit.isSharedSubtree()){ shareOrgSubtree(orgUnit); } } } catch (GeneralException e){ LOGGER.error("Can't add org. unit: ", e); error("Can't add org. unit with name: '" + orgUnit.getName() + "'. Reason: " + e.getExceptionMessage()); } getSession().success("Org. Unit '" + orgUnit.getName() + "' has been saved successfully."); LOGGER.info("Org. Unit '" + orgUnit.getName() + "' has been saved successfully."); setResponsePage(PageOrgList.class); target.add(getFeedbackPanel()); } }
package hudson.remoting; import java.io.EOFException; import java.io.IOException; import java.io.InterruptedIOException; import java.net.SocketTimeoutException; import java.util.logging.Level; import java.util.logging.Logger; /** * {@link CommandTransport} that implements the read operation in a synchronous fashion. * * <p> * This class uses a thread to pump commands and pass them to {@link CommandReceiver}. * * @author Kohsuke Kawaguchi */ public abstract class SynchronousCommandTransport extends CommandTransport { protected Channel channel; private static final String RDR_SOCKET_TIMEOUT_PROPERTY_NAME = SynchronousCommandTransport.class.getName() + ".failOnSocketTimeoutInReader"; /** * Enables the original aggressive behavior, when the channel reader gets * interrupted on any {@link SocketTimeoutException}. * @since 2.60 */ private static boolean RDR_FAIL_ON_SOCKET_TIMEOUT = Boolean.getBoolean(RDR_SOCKET_TIMEOUT_PROPERTY_NAME); /** * Called by {@link Channel} to read the next command to arrive from the stream. */ public abstract Command read() throws IOException, ClassNotFoundException, InterruptedException; @Override public void setup(Channel channel, CommandReceiver receiver) { this.channel = channel; new ReaderThread(receiver).start(); } private final class ReaderThread extends Thread { private int commandsReceived = 0; private int commandsExecuted = 0; private final CommandReceiver receiver; public ReaderThread(CommandReceiver receiver) { super("Channel reader thread: "+channel.getName()); this.receiver = receiver; setUncaughtExceptionHandler((t, e) -> { LOGGER.log(Level.SEVERE, "Uncaught exception in SynchronousCommandTransport.ReaderThread " + t, e); channel.terminate(new IOException("Unexpected reader termination", e)); }); } @Override public void run() { final String name =channel.getName(); try { while(!channel.isInClosed()) { Command cmd = null; try { cmd = read(); } catch (SocketTimeoutException ex) { if (RDR_FAIL_ON_SOCKET_TIMEOUT) { LOGGER.log(Level.SEVERE, "Socket timeout in the Synchronous channel reader." + " The channel will be interrupted, because " + RDR_SOCKET_TIMEOUT_PROPERTY_NAME + " is set", ex); throw ex; } // Timeout happened during the read operation. // It is not always fatal, because it may be caused by a long-running command // If channel is not closed, it's OK to continue reading the channel LOGGER.log(Level.WARNING, "Socket timeout in the Synchronous channel reader", ex); continue; } catch (EOFException e) { throw new IOException("Unexpected termination of the channel", e); } catch (ClassNotFoundException e) { LOGGER.log(Level.SEVERE, "Unable to read a command (channel " + name + ")",e); continue; } finally { commandsReceived++; } receiver.handle(cmd); commandsExecuted++; } closeRead(); } catch (InterruptedException e) { LOGGER.log(Level.SEVERE, "I/O error in channel "+name,e); channel.terminate((InterruptedIOException) new InterruptedIOException().initCause(e)); } catch (IOException e) { LOGGER.log(Level.INFO, "I/O error in channel "+name,e); channel.terminate(e); } catch (RuntimeException e) { LOGGER.log(Level.SEVERE, "Unexpected error in channel "+name,e); channel.terminate(new IOException("Unexpected reader termination", e)); throw e; } catch (Error e) { LOGGER.log(Level.SEVERE, "Unexpected error in channel "+name,e); channel.terminate(new IOException("Unexpected reader termination", e)); throw e; } finally { channel.pipeWriter.shutdown(); } } } private static final Logger LOGGER = Logger.getLogger(SynchronousCommandTransport.class.getName()); }
package im.tox.upsourcebot.filters; import com.google.common.io.ByteStreams; import org.apache.commons.codec.digest.HmacUtils; import java.io.ByteArrayInputStream; import java.io.IOException; import java.security.MessageDigest; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.core.Response; @GitHubHMAC public class GitHubHMACFilter implements ContainerRequestFilter { private byte[] secret; public GitHubHMACFilter(String secret) { this.secret = secret.getBytes(); } @Override public void filter(ContainerRequestContext requestContext) throws IOException { String hubSignature = requestContext.getHeaderString("X-Hub-Signature"); if (hubSignature == null) { requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build()); return; } byte[] requestBody = ByteStreams.toByteArray(requestContext.getEntityStream()); String hmac = "sha1=" + HmacUtils.hmacSha1Hex(secret, requestBody); if (!MessageDigest.isEqual(hmac.getBytes(), hubSignature.getBytes())) { requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build()); } requestContext.setEntityStream(new ByteArrayInputStream(requestBody)); } }
package info.faceland.strife.managers; import com.tealcube.minecraft.bukkit.TextUtils; import info.faceland.strife.conditions.AttributeCondition; import info.faceland.strife.conditions.BarrierCondition; import info.faceland.strife.conditions.BleedingCondition; import info.faceland.strife.conditions.BonusLevelCondition; import info.faceland.strife.conditions.BurningCondition; import info.faceland.strife.conditions.ChanceCondition; import info.faceland.strife.conditions.Condition; import info.faceland.strife.conditions.Condition.CompareTarget; import info.faceland.strife.conditions.Condition.Comparison; import info.faceland.strife.conditions.Condition.ConditionType; import info.faceland.strife.conditions.CorruptionCondition; import info.faceland.strife.conditions.EntityTypeCondition; import info.faceland.strife.conditions.HealthCondition; import info.faceland.strife.conditions.HeightCondition; import info.faceland.strife.conditions.LevelCondition; import info.faceland.strife.conditions.PotionCondition; import info.faceland.strife.conditions.StatCondition; import info.faceland.strife.data.StrifeMob; import info.faceland.strife.data.champion.StrifeAttribute; import info.faceland.strife.effects.Bleed; import info.faceland.strife.effects.ConsumeBleed; import info.faceland.strife.effects.ConsumeCorrupt; import info.faceland.strife.effects.Corrupt; import info.faceland.strife.effects.DealDamage; import info.faceland.strife.effects.DealDamage.DamageScale; import info.faceland.strife.effects.Effect; import info.faceland.strife.effects.ForceTarget; import info.faceland.strife.effects.Heal; import info.faceland.strife.effects.Ignite; import info.faceland.strife.effects.Knockback; import info.faceland.strife.effects.Leap; import info.faceland.strife.effects.PlaySound; import info.faceland.strife.effects.PotionEffectAction; import info.faceland.strife.effects.RestoreBarrier; import info.faceland.strife.effects.ShootProjectile; import info.faceland.strife.effects.SpawnParticle; import info.faceland.strife.effects.Speak; import info.faceland.strife.effects.Summon; import info.faceland.strife.effects.Wait; import info.faceland.strife.stats.StrifeStat; import info.faceland.strife.util.DamageUtil; import info.faceland.strife.util.DamageUtil.DamageType; import info.faceland.strife.util.LogUtil; import info.faceland.strife.util.PlayerDataUtil; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.bukkit.Particle; import org.bukkit.Sound; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.potion.PotionEffectType; public class EffectManager { private final StrifeAttributeManager strifeAttributeManager; private final StrifeMobManager aeManager; private final Map<String, Effect> loadedEffects; private final Map<String, Condition> conditions; public EffectManager(StrifeAttributeManager strifeAttributeManager, StrifeMobManager aeManager) { this.strifeAttributeManager = strifeAttributeManager; this.aeManager = aeManager; this.loadedEffects = new HashMap<>(); this.conditions = new HashMap<>(); } public void execute(String effectName, StrifeMob caster, StrifeMob target) { Effect effect = getEffect(effectName); if (effect == null) { return; } execute(effect, caster, target); } public void execute(Effect effect, StrifeMob caster, StrifeMob target) { if (effect.isForceTargetCaster()) { target = caster; } if (!PlayerDataUtil.areConditionsMet(caster, target, effect.getConditions())) { LogUtil.printDebug(" Conditions not met for effect " + effect.getName() + "... Failed."); return; } LogUtil.printDebug(" Looping targets for " + effect.getName()); if (effect.getRange() == 0) { LogUtil.printDebug(" Applying effect to " + PlayerDataUtil.getName(target.getEntity())); effect.apply(caster, target); return; } List<LivingEntity> targets = getEffectTargets(caster.getEntity(), target.getEntity(), effect.getRange()); if (!effect.isFriendly()) { targets.remove(caster.getEntity()); for (StrifeMob mob : caster.getMinions()) { targets.remove(mob.getEntity()); } } for (LivingEntity le : targets) { LogUtil.printDebug(" Applying effect to " + PlayerDataUtil.getName(le)); if (!effect.isFriendly() && caster.getEntity() instanceof Player && le instanceof Player) { if (!DamageUtil.canAttack((Player) caster.getEntity(), (Player) le)) { continue; } } effect.apply(caster, aeManager.getStatMob(le)); } } private List<LivingEntity> getEffectTargets(LivingEntity caster, LivingEntity target, double range) { List<LivingEntity> targets = new ArrayList<>(); if (target == null) { LogUtil.printError(" Missing targets! Returning empty list"); return targets; } if (range < 1) { LogUtil.printDebug(" Self casting, low or no range"); targets.add(target); return targets; } for (Entity e : target.getNearbyEntities(range, range, range)) { if (e instanceof LivingEntity && target.hasLineOfSight(e)) { targets.add((LivingEntity) e); } } targets.remove(caster); LogUtil.printDebug(" Targeting " + targets.size() + " targets!"); return targets; } public void loadEffect(String key, ConfigurationSection cs) { String type = cs.getString("type", "NULL").toUpperCase(); EffectType effectType; try { effectType = EffectType.valueOf(type); } catch (Exception e) { LogUtil.printError("Skipping effect " + key + " for invalid effect type"); return; } Effect effect = null; switch (effectType) { case HEAL: effect = new Heal(); ((Heal) effect).setAmount(cs.getDouble("amount", 1)); ((Heal) effect).setDamageScale(DamageScale.valueOf(cs.getString("scale", "FLAT"))); break; case RESTORE_BARRIER: effect = new RestoreBarrier(); ((RestoreBarrier) effect).setAmount(cs.getDouble("amount", 1)); ((RestoreBarrier) effect) .setDamageScale(DamageScale.valueOf(cs.getString("scale", "FLAT"))); break; case DAMAGE: effect = new DealDamage(); ((DealDamage) effect).setAmount(cs.getDouble("amount", 1)); try { ((DealDamage) effect).setDamageScale(DamageScale.valueOf(cs.getString("scale", "FLAT"))); ((DealDamage) effect) .setDamageType(DamageType.valueOf(cs.getString("damage-type", "TRUE"))); } catch (Exception e) { LogUtil.printError("Skipping effect " + key + " for invalid damage scale/type"); return; } break; case PROJECTILE: effect = new ShootProjectile(); ((ShootProjectile) effect).setQuantity(cs.getInt("quantity", 1)); EntityType projType; try { projType = EntityType.valueOf(cs.getString("projectile-type", "null")); } catch (Exception e) { LogUtil.printError("Skipping effect " + key + " for invalid projectile type"); return; } if (!(projType == EntityType.ARROW || projType == EntityType.THROWN_EXP_BOTTLE || projType == EntityType.SPLASH_POTION || projType == EntityType.WITHER_SKULL || projType == EntityType.SHULKER_BULLET || projType == EntityType.PRIMED_TNT || projType == EntityType.EGG || projType == EntityType.SNOWBALL || projType == EntityType.FIREBALL || projType == EntityType.DRAGON_FIREBALL || projType == EntityType.SMALL_FIREBALL)) { LogUtil.printWarning("Skipping effect " + key + " for non projectile entity"); return; } ((ShootProjectile) effect).setProjectileEntity(projType); ((ShootProjectile) effect).setVerticalBonus(cs.getDouble("vertical-bonus", 0)); ((ShootProjectile) effect).setSpread(cs.getDouble("spread", 0)); ((ShootProjectile) effect).setSpeed(cs.getDouble("speed", 1)); ((ShootProjectile) effect).setYield((float) cs.getDouble("yield", 0.0D)); ((ShootProjectile) effect).setIgnite(cs.getBoolean("ignite", false)); ((ShootProjectile) effect).setIgnite(cs.getBoolean("bounce", false)); ((ShootProjectile) effect).setHitEffects(cs.getStringList("hit-effects")); ((ShootProjectile) effect).setTargeted(cs.getBoolean("targeted", false)); ((ShootProjectile) effect).setSeeking(cs.getBoolean("seeking", false)); break; case IGNITE: effect = new Ignite(); ((Ignite) effect).setDuration(cs.getInt("duration", 20)); break; case BLEED: effect = new Bleed(); ((Bleed) effect).setAmount(cs.getInt("amount", 10)); ((Bleed) effect).setIgnoreArmor(cs.getBoolean("ignore-armor", true)); break; case CORRUPT: effect = new Corrupt(); ((Corrupt) effect).setAmount(cs.getInt("amount", 10)); break; case CONSUME_BLEED: effect = new ConsumeBleed(); ((ConsumeBleed) effect).setDamageRatio(cs.getDouble("damage-ratio", 1)); ((ConsumeBleed) effect).setHealRatio(cs.getDouble("heal-ratio", 1)); break; case CONSUME_CORRUPT: effect = new ConsumeCorrupt(); ((ConsumeCorrupt) effect).setDamageRatio(cs.getDouble("damage-ratio", 1)); ((ConsumeCorrupt) effect).setHealRatio(cs.getDouble("heal-ratio", 1)); break; case WAIT: effect = new Wait(); ((Wait) effect).setTickDelay(cs.getInt("duration", 20)); break; case SPEAK: effect = new Speak(); ((Speak) effect).setMessages( TextUtils.color(cs.getStringList("messages"))); break; case KNOCKBACK: effect = new Knockback(); ((Knockback) effect).setPower(cs.getDouble("power", 1)); break; case LEAP: effect = new Leap(); ((Leap) effect).setForward(cs.getDouble("forward", 1)); ((Leap) effect).setHeight(cs.getDouble("height", 1)); break; case SUMMON: effect = new Summon(); ((Summon) effect).setAmount(cs.getInt("amount", 1)); ((Summon) effect).setUniqueEntity(cs.getString("unique-entity")); ((Summon) effect).setLifespanSeconds(cs.getInt("lifespan-seconds", 30)); ((Summon) effect).setSoundEffect(cs.getString("sound-effect-id", null)); break; case TARGET: effect = new ForceTarget(); ((ForceTarget) effect).setOverwrite(cs.getBoolean("overwrite")); break; case POTION: effect = new PotionEffectAction(); PotionEffectType potionType; try { potionType = PotionEffectType.getByName(cs.getString("effect")); } catch (Exception e) { LogUtil.printWarning("Invalid potion effect type in effect " + key + ". Skipping."); return; } ((PotionEffectAction) effect).setPotionEffectType(potionType); ((PotionEffectAction) effect).setIntensity(cs.getInt("intensity", 0)); ((PotionEffectAction) effect).setDuration(cs.getInt("duration", 0)); break; case SOUND: effect = new PlaySound(); Sound sound; try { sound = Sound.valueOf((cs.getString("sound-type"))); } catch (Exception e) { LogUtil.printWarning("Invalid sound effect type in effect " + key + ". Skipping."); return; } ((PlaySound) effect).setSound(sound); ((PlaySound) effect).setVolume((float) cs.getDouble("volume", 1)); ((PlaySound) effect).setPitch((float) cs.getDouble("pitch", 1)); break; case PARTICLE: effect = new SpawnParticle(); Particle particle; try { particle = Particle.valueOf((cs.getString("particle-type"))); } catch (Exception e) { LogUtil.printWarning("Invalid particle effect type in effect " + key + ". Skipping."); return; } ((SpawnParticle) effect).setParticle(particle); ((SpawnParticle) effect).setQuantity(cs.getInt("quantity", 10)); ((SpawnParticle) effect).setSpeed((float) cs.getDouble("speed", 0)); ((SpawnParticle) effect).setSpread((float) cs.getDouble("spread", 1)); break; } if (effectType != EffectType.WAIT) { effect.setName(TextUtils.color(cs.getString("name", "&8Unnamed Effect"))); effect.setRange(cs.getDouble("range", 0)); effect.setForceTargetCaster(cs.getBoolean("force-target-caster", false)); effect.setFriendly(cs.getBoolean("friendly", false)); } else { effect.setName("wait"); } List<String> conditionStrings = cs.getStringList("conditions"); for (String s : conditionStrings) { Condition condition = conditions.get(s); if (condition == null) { LogUtil.printWarning("Invalid conditions " + s + " for effect " + key + ". Skipping."); continue; } effect.addCondition(conditions.get(s)); } loadedEffects.put(key, effect); LogUtil.printInfo("Loaded effect " + key + " successfully."); } public void loadCondition(String key, ConfigurationSection cs) { String type = cs.getString("type", "NULL").toUpperCase(); ConditionType conditionType; try { conditionType = ConditionType.valueOf(type); } catch (Exception e) { LogUtil.printError("Failed to load " + key + ". Invalid conditions type (" + type + ")"); return; } String compType = cs.getString("comparison", "NULL").toUpperCase(); Comparison comparison; try { comparison = Comparison.valueOf(compType); } catch (Exception e) { LogUtil.printError("Failed to load " + key + ". Invalid comparison type (" + compType + ")"); return; } String compareTargetString = cs.getString("target", "SELF"); CompareTarget compareTarget = compareTargetString.equalsIgnoreCase("SELF") ? CompareTarget.SELF : CompareTarget.OTHER; double value = cs.getDouble("value", 0); Condition condition; switch (conditionType) { case STAT: StrifeStat stat; try { stat = StrifeStat.valueOf(cs.getString("stat", null)); } catch (Exception e) { LogUtil.printError("Failed to load condition " + key + ". Invalid stat."); return; } condition = new StatCondition(stat, compareTarget, comparison, value); break; case ATTRIBUTE: StrifeAttribute attribute = strifeAttributeManager.getAttribute(cs.getString("attribute", null)); if (attribute == null) { LogUtil.printError("Failed to load condition " + key + ". Invalid attribute."); return; } condition = new AttributeCondition(attribute, compareTarget, comparison, value); break; case BARRIER: boolean percent = cs.getBoolean("percentage", false); condition = new BarrierCondition(compareTarget, comparison, value, percent); break; case CHANCE: double chance = cs.getDouble("chance", 0.5); condition = new ChanceCondition(chance); break; case HEALTH: boolean percent2 = cs.getBoolean("percentage", false); condition = new HealthCondition(compareTarget, comparison, value, percent2); break; case POTION_EFFECT: PotionEffectType potionEffectType; try { potionEffectType = PotionEffectType.getByName(cs.getString("potion-effect", "p")); } catch (Exception e) { LogUtil.printError("Failed to load " + key + ". Invalid conditions type (" + type + ")"); return; } int potionIntensity = cs.getInt("intensity", 0); condition = new PotionCondition(potionEffectType, compareTarget, comparison, potionIntensity); break; case LEVEL: condition = new LevelCondition(comparison, (int) value); break; case BONUS_LEVEL: condition = new BonusLevelCondition(comparison, (int) value); break; case ITS_OVER_ANAKIN: condition = new HeightCondition(compareTarget); break; case BLEEDING: condition = new BleedingCondition(compareTarget, cs.getBoolean("state", true)); break; case DARKNESS: condition = new CorruptionCondition(compareTarget, comparison, value); break; case BURNING: condition = new BurningCondition(compareTarget, cs.getBoolean("state", true)); break; case ENTITY_TYPE: List<String> entityTypes = cs.getStringList("types"); boolean whitelist = cs.getBoolean("whitelist", true); Set<EntityType> typesSet = new HashSet<>(); try { for (String s : entityTypes) { typesSet.add(EntityType.valueOf(s)); } } catch (Exception e) { LogUtil.printError("Failed to load condition " + key + ". Invalid entity type!"); return; } condition = new EntityTypeCondition(typesSet, whitelist); break; default: LogUtil.printError("No valid conditions found for " + key + "... somehow?"); return; } conditions.put(key, condition); } public Effect getEffect(String key) { if (loadedEffects.containsKey(key)) { return loadedEffects.get(key); } LogUtil.printWarning("Attempted to get unknown effect '" + key + "'"); return null; } public Map<String, Effect> getLoadedEffects() { return loadedEffects; } public Map<String, Condition> getConditions() { return conditions; } public enum EffectType { DAMAGE, HEAL, RESTORE_BARRIER, PROJECTILE, IGNITE, BLEED, CORRUPT, CONSUME_BLEED, CONSUME_CORRUPT, WAIT, SOUND, PARTICLE, SPEAK, KNOCKBACK, LEAP, POTION, TARGET, SUMMON } }
package innovimax.mixthem.operation; import innovimax.mixthem.io.DefaultByteReader; import innovimax.mixthem.io.DefaultByteWriter; import innovimax.mixthem.io.IByteInput; import innovimax.mixthem.io.IByteOutput; import innovimax.mixthem.io.InputResource; import java.io.IOException; import java.io.OutputStream; /** * <p>Copy all bytes.</p> * @author Innovimax * @version 1.0 */ public class DefaultByteCopy implements ICopy { private final static int BYTE_BUFFER_SIZE = 1024; public void processFile(InputResource input, OutputStream out) throws IOException { byte[] buffer = new byte[BYTE_BUFFER_SIZE]; IByteInput reader = new DefaultByteReader(input); IByteOutput writer = new DefaultByteWriter(out); while (reader.hasByte()) { final int len = reader.nextBytes(buffer, BYTE_BUFFER_SIZE); writer.writeBytes(buffer, len); } reader.close(); writer.close(); } }
package io.luna.game.model.mobile.attr; import com.google.common.base.CharMatcher; import com.google.common.base.MoreObjects; import java.util.IdentityHashMap; import java.util.Map; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; public final class AttributeKey<T> { /** * An {@link IdentityHashMap} of {@link String} keys mapped to their {@code AttributeKey} aliases. All {@code String}s * added to this map are forcibly interned so we can compare them by their identity for faster performance. */ public static final Map<String, AttributeKey> ALIASES = new IdentityHashMap<>(); /** * Aliases all attributes that will be used while Luna is online. This is called eagerly on startup. */ public static void init() { AttributeKey.forPersistent("run_energy", 100); AttributeKey.forPersistent("first_login", true); } /** * Aliases {@code name} with an initial value of {@code initialValue} that will be written to and read from the character * file. * * @param name The name of this key. * @param initialValue The initial value of this key. */ public static <T> void forPersistent(String name, T initialValue) { ALIASES.put(name, new AttributeKey<>(name, initialValue, true)); } /** * Aliases {@code name} with an initial value of {@code initialValue}. * * @param name The name of this key. * @param initialValue The initial value of this key. */ public static <T> void forTransient(String name, T initialValue) { ALIASES.put(name, new AttributeKey<>(name, initialValue, false)); } /** * The name of this alias. */ private final String name; /** * The initial value of this alias. */ private final T initialValue; /** * If the value of this alias should be serialized. */ private final boolean isPersistent; /** * The fully-qualified class name of this attribute type. */ private final String typeName; /** * Creates a new {@link AttributeKey}. * * @param name The name of this alias. * @param initialValue The initial value of this alias. * @param isPersistent If the value of this alias should be serialized. */ private AttributeKey(String name, T initialValue, boolean isPersistent) { checkState(!ALIASES.containsKey(name.intern()), "attribute already aliased"); checkArgument(!name.isEmpty(), "attribute name length <= 0"); checkArgument(CharMatcher.WHITESPACE.matchesNoneOf(name), "attribute name has whitespace characters, use underscores characters instead"); checkArgument(CharMatcher.JAVA_UPPER_CASE.matchesNoneOf(name), "attribute name has uppercase characters, use lowercase characters instead"); this.name = name.intern(); this.initialValue = initialValue; this.isPersistent = isPersistent; typeName = initialValue.getClass().getName(); } @Override public String toString() { return MoreObjects.toStringHelper(this).add("name", name).add("persistent", isPersistent).add("type", typeName) .toString(); } /** * @return The name of this alias. */ public String getName() { return name; } /** * @return The initial value of this alias. */ public T getInitialValue() { return initialValue; } /** * @return {@code true} if the value of this alias should be serialized, {@code false} otherwise. */ public boolean isPersistent() { return isPersistent; } /** * @return The fully-qualified class name of this attribute type. */ public String getTypeName() { return typeName; } }
package main.java.com.bag.server; import bftsmart.reconfiguration.util.RSAKeyLoader; import bftsmart.tom.MessageContext; import bftsmart.tom.ServiceProxy; import bftsmart.tom.util.TOMUtil; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.pool.KryoPool; import main.java.com.bag.operations.Operation; import main.java.com.bag.util.Constants; import main.java.com.bag.util.Log; import main.java.com.bag.util.storage.NodeStorage; import main.java.com.bag.util.storage.RelationshipStorage; import main.java.com.bag.util.storage.SignatureStorage; import org.jetbrains.annotations.NotNull; import java.security.PublicKey; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; /** * Class handling server communication in the global cluster. */ public class GlobalClusterSlave extends AbstractRecoverable { /** * Name of the location of the global config. */ private static final String GLOBAL_CONFIG_LOCATION = "global/config"; /** * The wrapper class instance. Used to access the global cluster if possible. */ private final ServerWrapper wrapper; /** * The id of the local cluster. */ private final int id; /** * Map which holds the signatureStorages for the consistency. */ private final Map<Long, SignatureStorage> signatureStorageMap = new TreeMap<>(); /** * The serviceProxy to establish communication with the other replicas. */ private final ServiceProxy proxy; public GlobalClusterSlave(final int id, @NotNull final ServerWrapper wrapper) { super(id, GLOBAL_CONFIG_LOCATION, wrapper); this.id = id; this.wrapper = wrapper; this.proxy = new ServiceProxy(1000 + id , GLOBAL_CONFIG_LOCATION); Log.getLogger().info("Turned on global cluster with id:" + id); } private byte[] makeEmptyAbortResult() { final Output output = new Output(0,128); final KryoPool pool = new KryoPool.Builder(super.getFactory()).softReferences().build(); final Kryo kryo = pool.borrow(); kryo.writeObject(output, Constants.ABORT); byte[] temp = output.getBuffer(); output.close(); pool.release(kryo); return temp; } //Every byte array is one request. @Override public byte[][] appExecuteBatch(final byte[][] bytes, final MessageContext[] messageContexts) { byte[][] allResults = new byte[bytes.length][]; for (int i = 0; i < bytes.length; ++i) { if (messageContexts != null && messageContexts[i] != null) { KryoPool pool = new KryoPool.Builder(super.getFactory()).softReferences().build(); Kryo kryo = pool.borrow(); Input input = new Input(bytes[i]); String type = kryo.readObject(input, String.class); if (Constants.COMMIT_MESSAGE.equals(type)) { final Long timeStamp = kryo.readObject(input, Long.class); byte[] result = executeCommit(kryo, input, timeStamp); pool.release(kryo); allResults[i] = result; } else { Log.getLogger().error("Return empty bytes for message type: " + type); allResults[i] = makeEmptyAbortResult(); updateCounts(0, 0,0,1); } } else { Log.getLogger().error("Received message with empty context!"); allResults[i] = makeEmptyAbortResult(); updateCounts(0, 0,0,1); } } return allResults; } @Override void readSpecificData(final Input input, final Kryo kryo) { final int length = kryo.readObject(input, Integer.class); for(int i = 0; i < length; i++) { try { signatureStorageMap.put(kryo.readObject(input, Long.class), kryo.readObject(input, SignatureStorage.class)); } catch (ClassCastException ex) { Log.getLogger().info("Unable to restore signatureStoreMap entry: " + i + " at server: " + id, ex); } } } @Override void writeSpecificData(final Output output, final Kryo kryo) { if(signatureStorageMap != null) { kryo.writeObject(output, signatureStorageMap.size()); for (Map.Entry<Long, SignatureStorage> entrySet : signatureStorageMap.entrySet()) { kryo.writeObject(output, entrySet.getKey()); kryo.writeObject(output, entrySet.getValue()); } } } /** * Check for conflicts and unpack things for conflict handle check. * @param kryo the kryo instance. * @param input the input. * @return the response. */ private byte[] executeCommit(final Kryo kryo, final Input input, final long timeStamp) { //Read the inputStream. final List readsSetNodeX = kryo.readObject(input, ArrayList.class); final List readsSetRelationshipX = kryo.readObject(input, ArrayList.class); final List writeSetX = kryo.readObject(input, ArrayList.class); //Create placeHolders. ArrayList<NodeStorage> readSetNode; ArrayList<RelationshipStorage> readsSetRelationship; ArrayList<Operation> localWriteSet; input.close(); Output output = new Output(128); kryo.writeObject(output, Constants.COMMIT_RESPONSE); try { readSetNode = (ArrayList<NodeStorage>) readsSetNodeX; readsSetRelationship = (ArrayList<RelationshipStorage>) readsSetRelationshipX; localWriteSet = (ArrayList<Operation>) writeSetX; } catch (Exception e) { Log.getLogger().warn("Couldn't convert received data to sets. Returning abort", e); kryo.writeObject(output, Constants.ABORT); kryo.writeObject(output, getGlobalSnapshotId()); //Send abort to client and abort byte[] returnBytes = output.getBuffer(); output.close(); return returnBytes; } if (!ConflictHandler.checkForConflict(super.getGlobalWriteSet(), localWriteSet, readSetNode, readsSetRelationship, timeStamp, wrapper.getDataBaseAccess())) { updateCounts(0, 0, 0, 1); Log.getLogger().info("Found conflict, returning abort with timestamp: " + timeStamp + " globalSnapshot at: " + getGlobalSnapshotId() + " and writes: " + localWriteSet.size() + " and reads: " + readSetNode.size() + " + " + readsSetRelationship.size()); kryo.writeObject(output, Constants.ABORT); kryo.writeObject(output, getGlobalSnapshotId()); //Send abort to client and abort byte[] returnBytes = output.getBuffer(); output.close(); if(wrapper.getLocalCLuster() != null) { signCommitWithDecisionAndDistribute(localWriteSet, Constants.ABORT, -1, kryo); } return returnBytes; } if (!localWriteSet.isEmpty() && wrapper.getLocalCLuster() != null) { super.executeCommit(localWriteSet); signCommitWithDecisionAndDistribute(localWriteSet, Constants.COMMIT, getGlobalSnapshotId(), kryo); } else { updateCounts(0, 0, 1, 0); } kryo.writeObject(output, Constants.COMMIT); kryo.writeObject(output, getGlobalSnapshotId()); byte[] returnBytes = output.getBuffer(); output.close(); Log.getLogger().info("No conflict found, returning commit with snapShot id: " + getGlobalSnapshotId() + " size: " + returnBytes.length); return returnBytes; } private void signCommitWithDecisionAndDistribute(final List<Operation> localWriteSet, final String decision, final long snapShotId, final Kryo kryo) { Log.getLogger().info("Sending signed commit to the other global replicas"); final RSAKeyLoader rsaLoader = new RSAKeyLoader(1000 + this.id, GLOBAL_CONFIG_LOCATION, false); //Todo probably will need a bigger buffer in the future. size depending on the set size? Output output = new Output(0, 100240); kryo.writeObject(output, Constants.SIGNATURE_MESSAGE); kryo.writeObject(output, decision); //Write the timeStamp to the server kryo.writeObject(output, snapShotId); kryo.writeObject(output, localWriteSet); byte[] bytes; try { bytes = TOMUtil.signMessage(rsaLoader.loadPrivateKey(), output.toBytes()); } catch (Exception e) { Log.getLogger().warn("Unable to sign message at server " + id, e); return; } final SignatureStorage signatureStorage; if(signatureStorageMap.containsKey(getGlobalSnapshotId())) { signatureStorage = signatureStorageMap.get(getGlobalSnapshotId()); } else { signatureStorage = new SignatureStorage(super.getReplica().getReplicaContext().getStaticConfiguration().getN() - 1, output.toBytes(), decision); signatureStorageMap.put(snapShotId, signatureStorage); } signatureStorage.addSignatures(id + 1000, bytes); kryo.writeObject(output, output.toBytes().length); kryo.writeObject(output, bytes.length); output.writeBytes(bytes); proxy.invokeUnordered(output.getBuffer()); output.close(); } private Output makeEmptyReadResponse(String message, Kryo kryo) { Output output = new Output(0, 10240); kryo.writeObject(output, message); kryo.writeObject(output, new ArrayList<NodeStorage>()); kryo.writeObject(output, new ArrayList<RelationshipStorage>()); return output; } /** * Handle a signature message. * @param input the message. * @param messageContext the context. * @param kryo the kryo object. */ private void handleSignatureMessage(final Input input, final MessageContext messageContext, final Kryo kryo) { //Our own message. if(id == messageContext.getSender()) { return; } final String decision = kryo.readObject(input, String.class); final Long snapShotId = kryo.readObject(input, Long.class); final List writeSet = kryo.readObject(input, ArrayList.class); final ArrayList<Operation> localWriteSet; try { localWriteSet = (ArrayList<Operation>) writeSet; } catch (ClassCastException e) { Log.getLogger().warn("Couldn't convert received signature message.", e); return; } Log.getLogger().info("Server: " + id + " Received message to sign with snapShotId: " + snapShotId + " of Server " + messageContext.getSender() + " and decision: " + decision + " and a writeSet of the length of: " + localWriteSet.size()); final int messageLength = kryo.readObject(input, Integer.class); final int signatureLength = kryo.readObject(input, Integer.class); final byte[] signature = input.readBytes(signatureLength); //Not required anymore. input.close(); final RSAKeyLoader rsaLoader = new RSAKeyLoader(messageContext.getSender(), GLOBAL_CONFIG_LOCATION, false); final PublicKey key; try { key = rsaLoader.loadPublicKey(); } catch (Exception e) { Log.getLogger().warn("Unable to load public key on server " + id + " sent by server " + messageContext.getSender(), e); return; } final byte[] message = new byte[messageLength]; System.arraycopy(input.getBuffer(), 0, message , 0, messageLength); boolean signatureMatches = TOMUtil.verifySignature(key, message, signature); if(signatureMatches) { storeSignedMessage(snapShotId, signature, messageContext, decision, message); return; } Log.getLogger().warn("Signature doesn't match of message, throwing message away."); } @Override public byte[] appExecuteUnordered(final byte[] bytes, final MessageContext messageContext) { Log.getLogger().info("Received unordered message at global replica"); KryoPool pool = new KryoPool.Builder(getFactory()).softReferences().build(); Kryo kryo = pool.borrow(); Input input = new Input(bytes); final String messageType = kryo.readObject(input, String.class); Output output = new Output(1, 404800); switch(messageType) { case Constants.READ_MESSAGE: Log.getLogger().info("Received Node read message"); try { kryo.writeObject(output, Constants.READ_MESSAGE); output = handleNodeRead(input, messageContext, kryo, output); } catch (Throwable t) { Log.getLogger().error("Error on " + Constants.READ_MESSAGE + ", returning empty read", t); output = makeEmptyReadResponse(Constants.READ_MESSAGE, kryo); } break; case Constants.RELATIONSHIP_READ_MESSAGE: Log.getLogger().info("Received Relationship read message"); try { kryo.writeObject(output, Constants.READ_MESSAGE); output = handleRelationshipRead(input, kryo, output); } catch (Throwable t) { Log.getLogger().error("Error on " + Constants.RELATIONSHIP_READ_MESSAGE + ", returning empty read", t); output = makeEmptyReadResponse(Constants.RELATIONSHIP_READ_MESSAGE, kryo); } break; case Constants.SIGNATURE_MESSAGE: Log.getLogger().info("Received signature message"); handleSignatureMessage(input, messageContext, kryo); break; case Constants.REGISTER_GLOBALLY_MESSAGE: Log.getLogger().info("Received register globally message"); output.close(); input.close(); pool.release(kryo); return handleRegisteringSlave(input, kryo); case Constants.REGISTER_GLOBALLY_CHECK: Log.getLogger().info("Received globally check message"); output.close(); input.close(); pool.release(kryo); return handleGlobalRegistryCheck(input, kryo); case Constants.COMMIT: Log.getLogger().info("Received commit message"); output.close(); byte[] result = handleReadOnlyCommit(input, kryo); input.close(); pool.release(kryo); Log.getLogger().info("Return it to client, size: " + result.length); return result; default: Log.getLogger().warn("Incorrect operation sent unordered to the server"); break; } byte[] returnValue = output.getBuffer(); Log.getLogger().info("Return it to client, size: " + returnValue.length); input.close(); output.close(); pool.release(kryo); return returnValue; } private byte[] handleReadOnlyCommit(final Input input, final Kryo kryo) { final Long timeStamp = kryo.readObject(input, Long.class); return executeCommit(kryo, input, timeStamp); } /** * Handle the check for the global registering of a slave. * @param input the incoming message. * @param kryo the kryo instance. * @return the reply */ private byte[] handleGlobalRegistryCheck(final Input input, final Kryo kryo) { final Output output = new Output(512); kryo.writeObject(output, Constants.REGISTER_GLOBALLY_CHECK); boolean decision = false; if(!wrapper.getLocalCLuster().isPrimary() || wrapper.getLocalCLuster().askIfIsPrimary(kryo.readObject(input, Integer.class), kryo.readObject(input, Integer.class), kryo)) { decision = true; } kryo.writeObject(output, decision); final byte[] result = output.getBuffer(); output.close(); input.close(); return result; } /** * This message comes from the local cluster. * Will respond true if it can register. * Message which handles slaves registering at the global cluster. * @param kryo the kryo instance. * @param input the message. * @return the message in bytes. */ private byte[] handleRegisteringSlave(final Input input, final Kryo kryo) { final int localClusterID = kryo.readObject(input, Integer.class); final int newPrimary = kryo.readObject(input, Integer.class); final int oldPrimary = kryo.readObject(input, Integer.class); final ServiceProxy localProxy = new ServiceProxy(1000 + oldPrimary, "local" + localClusterID); final Output output = new Output(512); kryo.writeObject(output, Constants.REGISTER_GLOBALLY_CHECK); kryo.writeObject(output, newPrimary); byte[] result = localProxy.invokeUnordered(output.getBuffer()); final Output nextOutput = new Output(512); kryo.writeObject(output, Constants.REGISTER_GLOBALLY_REPLY); final Input answer = new Input(result); if(Constants.REGISTER_GLOBALLY_REPLY.equals(answer.readString())) { kryo.writeObject(nextOutput, answer.readBoolean()); } final byte[] returnBuffer = nextOutput.getBuffer(); nextOutput.close(); answer.close(); localProxy.close(); output.close(); return returnBuffer; //remove currentView and edit system.config //If alright send the result to all remaining global clusters so that they update themselves. } /** * Store the signed message on the server. * If n-f messages arrived send it to client. * @param snapShotId the snapShotId as key. * @param signature the signature * @param context the message context. * @param decision the decision. * @param message the message. */ private void storeSignedMessage(final Long snapShotId, final byte[] signature, @NotNull final MessageContext context, final String decision, final byte[] message) { final SignatureStorage signatureStorage; if(!signatureStorageMap.containsKey(snapShotId)) { signatureStorage = new SignatureStorage(super.getReplica().getReplicaContext().getStaticConfiguration().getN() - 1, message, decision); signatureStorageMap.put(snapShotId, signatureStorage); Log.getLogger().warn("Replica: " + id + " did not have the transaction prepared. Might be slow or corrupted."); } else { signatureStorage = signatureStorageMap.get(snapShotId); } if(!decision.equals(signatureStorage.getDecision())) { Log.getLogger().warn("Replica: " + id + " did receive a different decision of replica: " + context.getSender() + ". Might be corrupted."); return; } signatureStorage.addSignatures(context.getSender(), signature); Log.getLogger().info("Adding signature to signatureStorage, has: " + signatureStorage.getSignatures().size()); if(signatureStorage.hasEnough()) { Log.getLogger().info("Sending update to slave signed by all members."); updateSlave(signatureStorage); signatureStorageMap.remove(snapShotId); return; } signatureStorageMap.put(snapShotId, signatureStorage); } /** * Update the slave with a transaction. * @param signatureStorage the signatureStorage with message and signatures.. */ private void updateSlave(final SignatureStorage signatureStorage) { if(this.wrapper.getLocalCLuster() != null) { this.wrapper.getLocalCLuster().propagateUpdate(signatureStorage); } } /** * Invoke a message to the global cluster. * @param input the input object. * @return the response. */ public Output invokeGlobally(final Input input) { return new Output(proxy.invokeOrdered(input.getBuffer())); } /** * Closes the global cluster and his code. */ public void close() { super.terminate(); proxy.close(); } }
package me.deftware.mixin.mixins.entity; import me.deftware.client.framework.event.events.*; import me.deftware.client.framework.global.GameKeys; import me.deftware.client.framework.global.GameMap; import me.deftware.client.framework.math.vector.Vector3d; import me.deftware.client.framework.render.camera.entity.CameraEntityMan; import me.deftware.mixin.imp.IMixinEntity; import net.minecraft.block.BlockState; import net.minecraft.client.MinecraftClient; import net.minecraft.client.network.ClientPlayerEntity; import net.minecraft.entity.Entity; import net.minecraft.util.math.Vec3d; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @SuppressWarnings("ConstantConditions") @Mixin(Entity.class) public abstract class MixinEntity implements IMixinEntity { @Shadow public boolean noClip; @Shadow protected boolean onGround; @Shadow protected boolean inNetherPortal; @Shadow public abstract boolean isSneaking(); @Shadow public abstract boolean isSprinting(); @Shadow protected abstract boolean getFlag(int id); @Shadow protected Vec3d movementMultiplier; @Shadow protected abstract void unsetRemoved(); @Shadow public abstract float getYaw(); @Shadow public abstract float getPitch(); @Shadow private boolean glowing; @SuppressWarnings("ConstantConditions") @Inject(method = "changeLookDirection", at = @At("HEAD"), cancellable = true) public void changeLookDirection(double cursorX, double cursorY, CallbackInfo ci) { if ((Object) this == MinecraftClient.getInstance().player && CameraEntityMan.isActive()) { CameraEntityMan.fakePlayer.changeLookDirection(cursorX, cursorY); CameraEntityMan.fakePlayer.setHeadYaw(CameraEntityMan.fakePlayer.getYaw()); ci.cancel(); } } @Redirect(method = "updateMovementInFluid(Lnet/minecraft/tag/Tag;D)Z", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/Entity;setVelocity(Lnet/minecraft/util/math/Vec3d;)V", opcode = 182)) private void applyFluidVelocity(Entity entity, Vec3d velocity) { if (entity == MinecraftClient.getInstance().player) { EventFluidVelocity event = new EventFluidVelocity(new Vector3d(velocity)).broadcast(); if (!event.isCanceled()) { entity.setVelocity(event.getVector3d().getMinecraftVector()); } } else { entity.setVelocity(velocity); } } @Inject(method = "pushAwayFrom", at = @At("HEAD"), cancellable = true) public void pushAwayFrom(Entity entity, CallbackInfo info) { if (((Object) this) == MinecraftClient.getInstance().player) { if (new EventEntityPush(me.deftware.client.framework.entity.Entity.newInstance(entity)).broadcast().isCanceled()) { info.cancel(); } } } @Redirect(method = "move", at = @At(value = "FIELD", target = "Lnet/minecraft/entity/Entity;noClip:Z", opcode = 180)) private boolean noClipCheck(Entity self) { boolean noClipCheck = GameMap.INSTANCE.get(GameKeys.NOCLIP, false); return (self instanceof ClientPlayerEntity && self == MinecraftClient.getInstance().player) && (noClip || noClipCheck); } @Inject(method = "slowMovement", at = @At(value = "TAIL"), cancellable = true) private void onSlowMovement(BlockState state, Vec3d multiplier, CallbackInfo ci) { if (((Object) this) == MinecraftClient.getInstance().player) { EventSlowdown event = new EventSlowdown(EventSlowdown.SlowdownType.Web); event.broadcast(); if (event.isCanceled()) { Vec3d cobSlowness = new Vec3d(0.25D, 0.05000000074505806D, 0.25D); if (multiplier.x == cobSlowness.x && multiplier.y == cobSlowness.y && multiplier.z == cobSlowness.z) { this.movementMultiplier = Vec3d.ZERO; ci.cancel(); } } } } @Redirect(method = "move", at = @At(value = "INVOKE", target = "net/minecraft/entity/Entity.isSneaking()Z", opcode = 180, ordinal = 0)) private boolean sneakingCheck(Entity self) { if (self == MinecraftClient.getInstance().player) { EventSneakingCheck event = new EventSneakingCheck(isSneaking()); event.broadcast(); if (event.isSneaking()) { return true; } } return getFlag(1); } @Inject(method = "setVelocityClient", at = @At("HEAD"), cancellable = true) private void onSetVelocityClient(double x, double y, double z, CallbackInfo ci) { if ((Object) this == MinecraftClient.getInstance().player) { EventKnockback event = new EventKnockback(x, y, z); event.broadcast(); if (event.isCanceled()) { ci.cancel(); } } } @Inject(method = "isGlowing", at = @At("HEAD"), cancellable = true) private void isGlowing(CallbackInfoReturnable<Boolean> cir) { cir.setReturnValue(glowing); } @Override public boolean getAFlag(int id) { return getFlag(id); } @Override public void setInPortal(boolean inPortal) { this.inNetherPortal = inPortal; } @Override public void removeRemovedReason() { unsetRemoved(); } }
package net.woogie.demomod.entity.mob; import com.google.common.base.Predicate; import net.minecraft.entity.Entity; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.EntityAIAttackOnCollide; import net.minecraft.entity.ai.EntityAIAvoidEntity; import net.minecraft.entity.ai.EntityAIHurtByTarget; import net.minecraft.entity.ai.EntityAILookIdle; import net.minecraft.entity.ai.EntityAINearestAttackableTarget; import net.minecraft.entity.ai.EntityAISwimming; import net.minecraft.entity.ai.EntityAIWander; import net.minecraft.entity.ai.EntityAIWatchClosest; import net.minecraft.entity.monster.EntityMob; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.woogie.demomod.Config; import net.woogie.demomod.DemoMod; import net.woogie.demomod.entity.tameable.DemoEntityTameable; public class DemoEntityMob extends EntityMob { public DemoEntityMob(World worldIn) { super(worldIn); this.experienceValue = Config.entityMobExperience; if (Config.entityMobCanSwim) { this.tasks.addTask(0, new EntityAISwimming(this)); } // avoid DemoEntityTameable if (Config.entityMobAvoidDemoEntityTameable) { this.tasks.addTask(1, new EntityAIAvoidEntity(this, new Predicate() { public boolean func_179958_a(Entity p_179958_1_) { return p_179958_1_ instanceof DemoEntityTameable; } @Override public boolean apply(Object p_apply_1_) { return this.func_179958_a((Entity) p_apply_1_); } }, Config.entityMobAvoidDemoEntityTameableRange, Config.entityMobAvoidDemoEntityTameableFarSpeed, Config.entityMobAvoidDemoEntityTameableNearSpeed)); } this.tasks.addTask(1, new EntityAIAttackOnCollide(this, Config.entityMobAIAttackOnCollideSpeed, false)); this.tasks.addTask(1, new EntityAIWander(this, Config.entityMobAIWanderSpeed)); this.tasks.addTask(1, new EntityAIWatchClosest(this, EntityPlayer.class, Config.entityMobAIWatchClosestDistance)); this.tasks.addTask(1, new EntityAILookIdle(this)); this.targetTasks.addTask(1, new EntityAINearestAttackableTarget(this, EntityPlayer.class, true)); this.targetTasks.addTask(1, new EntityAIHurtByTarget(this, false, new Class[0])); } public boolean isAIEnabled() { return true; } @Override protected void applyEntityAttributes() { super.applyEntityAttributes(); this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(Config.entityMobMaxHealth); this.getEntityAttribute(SharedMonsterAttributes.followRange).setBaseValue(Config.entityMobFollowRange); this.getEntityAttribute(SharedMonsterAttributes.knockbackResistance) .setBaseValue(Config.entityMobKnockbackResistance); this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(Config.entityMobMovementSpeed); this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(Config.entityMobAttackDamage); } @Override protected void dropFewItems(boolean recentlyHitByPlayer, int lootingLevel) { if (recentlyHitByPlayer) { int j = this.rand.nextInt(3) + this.rand.nextInt(2 + lootingLevel); for (int k = 0; k < j; ++k) { this.dropItem(DemoMod.demoItem, 1); } } } }
package nl.han.ica.ap.nlp.controller; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.antlr.v4.runtime.tree.ParseTreeWalker; import org.antlr.v4.runtime.tree.ParseTree; import org.junit.rules.ExternalResource; import nl.han.ica.ap.nlp.App; import nl.han.ica.ap.nlp.NlpParser; import nl.han.ica.ap.nlp.export.IExport; import nl.han.ica.ap.nlp.export.PowerDesignerExport; import nl.han.ica.ap.nlp.listeners.ZelfstandignaamwoordListener; import nl.han.ica.ap.nlp.model.Class; import nl.han.ica.ap.nlp.model.IAttribute; import nl.han.ica.ap.nlp.model.IClass; /** * @author Joell * */ public class TreeController { public ArrayList<IClass> classes = new ArrayList<IClass>(); public TreeController() { } public void walkTree(ParseTree tree,NlpParser parser) { ParseTreeWalker walker = new ParseTreeWalker(); ZelfstandignaamwoordListener listener = new ZelfstandignaamwoordListener(this); walker.walk(listener, tree); IExport export = new PowerDesignerExport(); System.out.println(export.export(classes)); } public void addClass(Class c) { for(IClass attribute : transformToIClassList(c.getAttributes())) { IClass existingClass = getClass(c, classes); IClass existingAttribute = getClass(attribute,classes); if(existingClass == null && existingAttribute == null){ classes.add(c); } else if(existingClass != null && existingAttribute == null) { existingClass.addAttribute(attribute); } else if(existingClass == null && existingAttribute != null) { c.getAttributes().set(c.getAttributes().indexOf(attribute), existingAttribute); classes.remove(existingAttribute); classes.add(c); } else { existingClass.addAttribute(existingAttribute); if(classes.size() > 1) { classes.remove(existingAttribute); } } } } private IClass getClass(IClass c,ArrayList<IClass> classlist) { for(IClass cInList : classlist) { if(cInList.getName().equalsIgnoreCase(c.getName()) || pluralExists(c.getName(),cInList)) { return cInList; } else if(cInList.getAttributes().size() > 0){ IClass result = getClass(c,transformToIClassList(cInList.getAttributes())); if(result != null) return result; } } return null; } private ArrayList<IClass> transformToIClassList(ArrayList<IAttribute> attributes) { ArrayList<IClass> _classes = new ArrayList<IClass>(); for(IAttribute attribute : attributes) { if(attribute instanceof IClass) { _classes.add((IClass) attribute); } } return _classes; } private boolean pluralExists(String name, IClass cInList) { if(name.equalsIgnoreCase(cInList.getName() + "s")) { return true; } else if(cInList.getName().equalsIgnoreCase(name + "s")) { cInList.setName(name); return true; } else if(name.equalsIgnoreCase(cInList.getName() + "'s")) { return true; } else if(cInList.getName().equalsIgnoreCase(name + "'s")) { cInList.setName(name); return true; } else if(name.equalsIgnoreCase(getClassSingular(cInList.getName()))){ cInList.setName(name); return true; } else if(cInList.getName().equalsIgnoreCase(getInputSingular(name))){ return true; } else { return false; } } // Krijg de stam van het ingevoerde zelfstandignaamwoord. private String getInputSingular(String name) { int inputLength= name.length(); if(name.endsWith("en")) { if(name.charAt(inputLength-3) == name.charAt(inputLength-4)) { name= name.substring(0, inputLength-3); } else { name= name.substring(0, inputLength-2); inputLength= name.length()-1; if(name.charAt(inputLength-2) == 'a' || name.charAt(inputLength-2) == 'e' || name.charAt(inputLength-2) == 'o' || name.charAt(inputLength-2) == 'i' || name.charAt(inputLength-2) == 'u') { return name; } else { name= name.replace(name.substring(inputLength), name.substring(inputLength-1)); } } } return name; } // Krijg de stam van het het bestaande zelfstandignaamwoord. private String getClassSingular(String cInList) { int cInListLength= cInList.length(); if(cInList.endsWith("en")) { if(cInList.charAt(cInListLength-3) == cInList.charAt(cInListLength-4)) { cInList= cInList.substring(0, cInListLength-3); } else { cInList= cInList.substring(0, cInListLength-2); cInListLength= cInList.length(); if(cInList.charAt(cInListLength-2) == 'a' || cInList.charAt(cInListLength-2) == 'e' || cInList.charAt(cInListLength-2) == 'o' || cInList.charAt(cInListLength-2) == 'i' || cInList.charAt(cInListLength-2) == 'u') { return cInList; } else { cInList= cInList.replace(cInList.substring(cInListLength), cInList.substring(cInListLength-1)); } } } return cInList; } }
package org.javarosa.formmanager.view; import java.util.Enumeration; import java.util.Hashtable; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.List; import org.javarosa.formmanager.activity.FormListModule; /** * @author Brian DeRenzi * */ public class FormList extends List implements CommandListener { // TODO: These should all be il8n'd private final Command CMD_EXIT = new Command("Exit", Command.BACK, 2); private final Command CMD_GETNEWFORMS = new Command("Get New Forms", Command.SCREEN, 2); private final Command CMD_VIEWMODELS = new Command("View Saved", Command.SCREEN, 3); private final Command CMD_DELETE_FORM = new Command("Delete",Command.SCREEN,4); private final Command CMD_SHAREFORMS = new Command("Share Forms", Command.SCREEN, 2); private final Command CMD_SETTINGS = new Command("Settings", Command.SCREEN, 3); private FormListModule parent = null; public FormList(FormListModule p, String title) { this(p, title, List.IMPLICIT); } public FormList(FormListModule p, String title, int listType) { super(title, listType); this.parent = p; } public void loadView(Hashtable args) { this.deleteAll(); this.createView(); this.setCommandListener(this); this.populateWithXForms(args); } private void createView() { addScreenCommands(); } private void addScreenCommands() { this.addCommand(CMD_EXIT); //this.addCommand(CMD_OPEN); this.addCommand(CMD_DELETE_FORM); this.addCommand(CMD_VIEWMODELS); this.addCommand(CMD_GETNEWFORMS); this.addCommand(CMD_SHAREFORMS); //#if polish.usePolishGui this.addCommand(CMD_SETTINGS); //#endif } /** * Put the list */ private void populateWithXForms(Hashtable listOfForms) { Integer pos = null; Enumeration e = listOfForms.keys(); while(e.hasMoreElements()){ pos = (Integer)e.nextElement(); String form = (String)listOfForms.get(pos); this.append(form,null); } } public void commandAction(Command c, Displayable arg1) { Hashtable v = new Hashtable(); // TODO Auto-generated method stub if (c == List.SELECT_COMMAND) { //LOG System.out.println("Selected a form"); v.put( new Integer(0), new Integer(this.getSelectedIndex())); Hashtable returnvals = new Hashtable(); returnvals.put(Commands.CMD_SELECT_XFORM, v); this.parent.viewCompleted(returnvals, ViewTypes.FORM_LIST); } /* if (c == CMD_DELETE_FORM) { XFormMetaData data = (XFormMetaData) formIDs.elementAt(this.getSelectedIndex()); // TODO check for any form dependancies this.mainShell.deleteForm(data.getRecordId()); createView(); } */ if (c == CMD_EXIT) { } /* if (c == CMD_GETNEWFORMS) { this.mainShell.getNewFormsByTransportPropertySetting(); } */ if (c == CMD_VIEWMODELS) { } /* if (c == CMD_SHAREFORMS) { this.mainShell.startBToothClient(); } if (c == CMD_SETTINGS) { this.mainShell.editProperties(); } */ } }
package nl.mpi.kinnate; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.File; import java.net.URI; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextArea; import nl.mpi.arbil.ImdiTable; import nl.mpi.arbil.ImdiTableModel; import nl.mpi.kinnate.EntityIndexer.EntityIndex; public class KinTypeEgoSelectionTestPanel extends JPanel { private JTextArea kinTypeStringInput; private GraphPanel graphPanel; private GraphData graphData; private EgoSelectionPanel egoSelectionPanel; private EntityIndex entityIndex; private String defaultString = "This test panel should provide a kin diagram based on selected egos and the the kintype strings entered here.\nEnter one string per line."; private String kinTypeStrings[] = new String[]{}; public KinTypeEgoSelectionTestPanel(File existingFile) { this.setLayout(new BorderLayout()); graphPanel = new GraphPanel(); egoSelectionPanel = new EgoSelectionPanel(); kinTypeStringInput = new JTextArea(defaultString); kinTypeStringInput.setBorder(javax.swing.BorderFactory.createTitledBorder("Kin Type Strings")); JPanel kinGraphPanel = new JPanel(new BorderLayout()); kinGraphPanel.add(kinTypeStringInput, BorderLayout.PAGE_START); kinGraphPanel.add(new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, egoSelectionPanel, graphPanel), BorderLayout.CENTER); ImdiTableModel imdiTableModel = new ImdiTableModel(); ImdiTable imdiTable = new ImdiTable(imdiTableModel, "Selected Nodes"); graphPanel.setImdiTableModel(imdiTableModel); JScrollPane tableScrollPane = new JScrollPane(imdiTable); // Dimension minimumSize = new Dimension(0, 0); // fieldListTabs.setMinimumSize(minimumSize); // tableScrollPane.setMinimumSize(minimumSize); entityIndex = new EntityIndex(graphPanel.getIndexParameters()); entityIndex.indexEntities(); graphData = new GraphData(); if (existingFile.exists()) { graphPanel.readSvg(existingFile); } else { graphPanel.drawNodes(graphData); } URI[] egoSelection = graphPanel.getEgoList(); graphData.setEgoNodes(entityIndex.getRelationsOfEgo(egoSelection, kinTypeStrings)); egoSelectionPanel.setEgoNodes(graphPanel.getEgoList()); kinTypeStrings = graphPanel.getKinTypeStrigs(); JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, kinGraphPanel, new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, tableScrollPane, new IndexerParametersPanel(graphPanel, entityIndex))); this.add(splitPane); kinTypeStringInput.addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { if (kinTypeStringInput.getText().equals(defaultString)) { kinTypeStringInput.setText(""); kinTypeStringInput.setForeground(Color.BLACK); } } public void focusLost(FocusEvent e) { if (kinTypeStringInput.getText().length() == 0) { kinTypeStringInput.setText(defaultString); kinTypeStringInput.setForeground(Color.lightGray); } } }); kinTypeStringInput.addKeyListener(new KeyListener() { public void keyTyped(KeyEvent e) { } public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { kinTypeStrings = kinTypeStringInput.getText().split("\n"); graphPanel.setKinTypeStrigs(kinTypeStrings); graphData.setEgoNodes(entityIndex.getRelationsOfEgo(graphPanel.getEgoList(), kinTypeStrings)); graphPanel.drawNodes(graphData); } }); boolean firstString = true; for (String currentKinTypeString : kinTypeStrings) { if (currentKinTypeString.trim().length() > 0) { if (firstString) { kinTypeStringInput.setText(""); firstString = false; } else { kinTypeStringInput.append("\n"); } kinTypeStringInput.append(currentKinTypeString.trim()); } } } public void addEgoNodes(URI[] egoSelection) { graphPanel.setEgoList(egoSelection); graphData.setEgoNodes(entityIndex.getRelationsOfEgo(egoSelection, kinTypeStrings)); graphPanel.drawNodes(graphData); egoSelectionPanel.setEgoNodes(graphPanel.getEgoList()); } }
package org.agmip.translators.dssat; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.Map; import static org.agmip.util.MapUtil.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * DSSAT Soil Data I/O API Class * * @author Meng Zhang * @version 1.0 */ public class DssatSoilOutput extends DssatCommonOutput { private static final Logger LOG = LoggerFactory.getLogger(DssatSoilOutput.class); /** * DSSAT Soil Data Output method * * @param arg0 file output path * @param result data holder object */ @Override public void writeFile(String arg0, Map result) { // Initial variables // ArrayList soilSites; // Soil site data array HashMap soilSite; // Data holder for one site of soil data ArrayList<Map> soilSistes; ArrayList soilRecords; // Soil layer data array HashMap soilRecord; // Data holder for one layer data BufferedWriter bwS; // output object StringBuilder sbTitle = new StringBuilder(); StringBuilder sbSites = new StringBuilder(); StringBuilder sbData; // construct the data info in the output StringBuilder sbLyrP2 = new StringBuilder(); // output string for second part of layer data boolean p2Flg; String[] p2Ids = {"slpx", "slpt", "slpo", "caco3", "slal", "slfe", "slmn", "slbs", "slpa", "slpb", "slke", "slmg", "slna", "slsu", "slec", "slca"}; String layerKey = "soilLayer"; // P.S. the key name might change try { // Set default value for missing data setDefVal(); soilSistes = getObjectOr(result, "soils", new ArrayList()); if (soilSistes.isEmpty()) { soilSistes.add(result); } Map expData = soilSistes.get(0); soilSite = (HashMap) getObjectOr(expData, "soil", new HashMap()); if (soilSite.isEmpty()) { return; } // decompressData(soilSites); // Initial BufferedWriter // Get File name String soilId = getObjectOr(soilSite, "soil_id", ""); String fileName; if (soilId.equals("")) { fileName = "soil.SOL"; } else { try { fileName = soilId.substring(0, 2) + ".SOL"; } catch (Exception e) { fileName = "soil.SOL"; } } arg0 = revisePath(arg0); outputFile = new File(arg0 + fileName); // boolean existFlg = outputFile.exists(); bwS = new BufferedWriter(new FileWriter(outputFile)); // Description info for output by translator sbTitle.append("!This soil file is created by DSSAT translator tool on ").append(Calendar.getInstance().getTime()).append(".\r\n"); sbTitle.append("*SOILS: "); for (int i = 0; i < soilSistes.size(); i++) { expData = soilSistes.get(i); soilSite = (HashMap) getObjectOr(expData, "soil", new HashMap()); sbError = new StringBuilder(); sbData = new StringBuilder(); // Output Soil File // Titel Section String sl_notes = getObjectOr((HashMap) soilSite, "sl_notes", defValBlank); if (!sl_notes.equals(defValBlank)) { sbTitle.append(sl_notes).append("; "); } sbData.append("!The ACE ID is ").append(getValueOr(expData, "id", "N/A")).append(".\r\n"); sbData.append("!This soil data is used for the experiment of ").append(getValueOr(expData, "exname", "N/A")).append(".\r\n!\r\n"); // Site Info Section String soil_id = getSoilID(soilSite); if (soil_id.equals("")) { sbError.append("! Warning: Incompleted record because missing data : [soil_id]\r\n"); } else if (soil_id.length() > 10) { sbError.append("! Warning: Oversized data : [soil_id] ").append(soil_id).append("\r\n"); } sbData.append(String.format("*%1$-10s %2$-11s %3$-5s %4$5s %5$s\r\n", soil_id, formatStr(11, soilSite, "sl_source", defValC), formatStr(5, transSltx(getValueOr(soilSite, "sltx", defValC)), "sltx"), formatNumStr(5, soilSite, "sldp", defValR), getObjectOr(soilSite, "soil_name", defValC).toString())); sbData.append("@SITE COUNTRY LAT LONG SCS FAMILY\r\n"); sbData.append(String.format(" %1$-11s %2$-11s %3$9s%4$8s %5$s\r\n", formatStr(11, soilSite, "sl_loc_3", defValC), formatStr(11, soilSite, "sl_loc_1", defValC), formatNumStr(8, soilSite, "soil_lat", defValR), // P.S. Definition changed 9 -> 10 (06/24) formatNumStr(8, soilSite, "soil_long", defValR), // P.S. Definition changed 9 -> 8 (06/24) getObjectOr(soilSite, "classification", defValC).toString())); sbData.append("@ SCOM SALB SLU1 SLDR SLRO SLNF SLPF SMHB SMPX SMKE\r\n"); // if (getObjectOr(soilSite, "slnf", "").equals("")) { // sbError.append("! Warning: missing data : [slnf], and will automatically use default value '1'\r\n"); // if (getObjectOr(soilSite, "slpf", "").equals("")) { // sbError.append("! Warning: missing data : [slpf], and will automatically use default value '0.92'\r\n"); sbData.append(String.format(" %1$5s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s\r\n", getObjectOr(soilSite, "sscol", defValC).toString(), formatNumStr(5, soilSite, "salb", defValR), formatNumStr(5, soilSite, "slu1", defValR), formatNumStr(5, soilSite, "sldr", defValR), formatNumStr(5, soilSite, "slro", defValR), formatNumStr(5, soilSite, "slnf", defValR), // P.S. Remove default value as '1' formatNumStr(5, soilSite, "slpf", defValR), // P.S. Remove default value as '0.92' getObjectOr(soilSite, "smhb", defValC).toString(), getObjectOr(soilSite, "smpx", defValC).toString(), getObjectOr(soilSite, "smke", defValC).toString())); // Soil Layer data section soilRecords = (ArrayList) getObjectOr(soilSite, layerKey, new ArrayList()); // part one sbData.append("@ SLB SLMH SLLL SDUL SSAT SRGF SSKS SBDM SLOC SLCL SLSI SLCF SLNI SLHW SLHB SCEC SADC\r\n"); // part two sbLyrP2.append("@ SLB SLPX SLPT SLPO CACO3 SLAL SLFE SLMN SLBS SLPA SLPB SLKE SLMG SLNA SLSU SLEC SLCA\r\n"); p2Flg = false; // Loop for laryer data for (int k = 0; k < soilRecords.size(); k++) { soilRecord = (HashMap) soilRecords.get(k); // part one sbData.append(String.format(" %1$5s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$5s %13$5s %14$5s %15$5s %16$5s %17$5s\r\n", formatNumStr(5, soilRecord, "sllb", defValR), getObjectOr(soilRecord, "slmh", defValC).toString(), formatNumStr(5, soilRecord, "slll", defValR), formatNumStr(5, soilRecord, "sldul", defValR), formatNumStr(5, soilRecord, "slsat", defValR), formatNumStr(5, soilRecord, "slrgf", defValR), formatNumStr(5, soilRecord, "sksat", defValR), formatNumStr(5, soilRecord, "slbdm", defValR), formatNumStr(5, soilRecord, "sloc", defValR), formatNumStr(5, soilRecord, "slcly", defValR), formatNumStr(5, soilRecord, "slsil", defValR), formatNumStr(5, soilRecord, "slcf", defValR), formatNumStr(5, soilRecord, "slni", defValR), formatNumStr(5, soilRecord, "slphw", defValR), formatNumStr(5, soilRecord, "slphb", defValR), formatNumStr(5, soilRecord, "slcec", defValR), formatNumStr(5, soilRecord, "sladc", defValR))); // part two sbLyrP2.append(String.format(" %1$5s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$5s %13$5s %14$5s %15$5s %16$5s %17$5s\r\n", formatNumStr(5, soilRecord, "sllb", defValR), formatNumStr(5, soilRecord, "slpx", defValR), formatNumStr(5, soilRecord, "slpt", defValR), formatNumStr(5, soilRecord, "slpo", defValR), formatNumStr(5, soilRecord, "caco3", defValR), // P.S. Different with document (DSSAT vol2.pdf) formatNumStr(5, soilRecord, "slal", defValR), formatNumStr(5, soilRecord, "slfe", defValR), formatNumStr(5, soilRecord, "slmn", defValR), formatNumStr(5, soilRecord, "slbs", defValR), formatNumStr(5, soilRecord, "slpa", defValR), formatNumStr(5, soilRecord, "slpb", defValR), formatNumStr(5, soilRecord, "slke", defValR), formatNumStr(5, soilRecord, "slmg", defValR), formatNumStr(5, soilRecord, "slna", defValR), formatNumStr(5, soilRecord, "slsu", defValR), formatNumStr(5, soilRecord, "slec", defValR), formatNumStr(5, soilRecord, "slca", defValR))); // Check if there is 2nd part of layer data for output if (!p2Flg) { for (int j = 0; j < p2Ids.length; j++) { if (!getValueOr(soilRecord, p2Ids[j], "").equals("")) { p2Flg = true; break; } } } } // Add part two if (p2Flg) { sbData.append(sbLyrP2.toString()).append("\r\n"); sbLyrP2 = new StringBuilder(); } else { sbData.append("\r\n"); } // Finish one site sbSites.append(sbError.toString()); sbSites.append(sbData.toString()); } // Output finish sbTitle.append("\r\n\r\n"); bwS.write(sbTitle.toString()); bwS.write(sbSites.toString()); bwS.close(); } catch (IOException e) { LOG.error(DssatCommonOutput.getStackTrace(e)); } } }
package org.agmip.translators.dssat; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Map; import org.agmip.core.types.AdvancedHashMap; import org.agmip.util.JSONAdapter; /** * DSSAT Soil Data I/O API Class * * @author Meng Zhang * @version 1.0 */ public class DssatSoilOutput extends DssatCommonOutput { private File outputFile; /** * Get output file object */ public File getOutputFile() { return outputFile; } /** * DSSAT Soil Data Output method * * @param arg0 file output path * @param result data holder object */ @Override public void writeFile(String arg0, AdvancedHashMap result) { // Initial variables JSONAdapter adapter = new JSONAdapter(); // JSON Adapter ArrayList soilSites; // Soil site data array AdvancedHashMap soilSite; // Data holder for one site of soil data ArrayList soilRecords; // Soil layer data array AdvancedHashMap soilRecord; // Data holder for one layer data BufferedWriter bwS; // output object StringBuilder sbData = new StringBuilder(); // construct the data info in the output StringBuilder sbLyrP2 = new StringBuilder(); // output string for second part of layer data boolean p2Flg; String[] p2Ids = {"slpx", "slpt", "slpo", "caco3", "slal", "slfe", "slmn", "slbs", "slpa", "slpb", "slke", "slmg", "slna", "slsu", "slec", "slca"}; String layerKey = "data"; // P.S. the key name might change try { // Set default value for missing data setDefVal(); soilSites = (ArrayList) result.getOr("soil", new ArrayList()); decompressData(soilSites); // Initial BufferedWriter // Get File name String exName = getExName(result); String fileName; if (exName.equals("")) { fileName = "soil.SOL"; } else { try { exName = exName.replace("\\.", ""); fileName = exName.substring(0, 8) + "_" + exName.substring(8) + "X.SOL"; } catch (Exception e) { fileName = "soil.SOL"; } } arg0 = revisePath(arg0); outputFile = new File(arg0 + fileName); bwS = new BufferedWriter(new FileWriter(outputFile)); // Output Soil File // Titel Section bwS.write("*SOILS: "); String slNote = ""; String tmp; for (int i = 0; i < soilSites.size(); i++) { tmp = (String) ((AdvancedHashMap) soilSites.get(i)).getOr("sl_notes", defValC); if (!slNote.equals(tmp)) { slNote = tmp; bwS.write(slNote + "; "); } } bwS.write("\r\n\r\n"); // Loop sites of data for (int i = 0; i < soilSites.size(); i++) { soilSite = adapter.exportRecord((Map) soilSites.get(i)); // Site Info Section sbData.append(String.format("*%1$-10s %2$-11s %3$-5s %4$5s %5$s\r\n", soilSite.getOr("soil_id", defValC).toString(), soilSite.getOr("sl_source", defValC).toString(), soilSite.getOr("sltx", defValC).toString(), formatNumStr(5, soilSite.getOr("sldp", defValR).toString()), soilSite.getOr("soil_name", defValC).toString())); sbData.append("@SITE COUNTRY LAT LONG SCS FAMILY\r\n"); sbData.append(String.format(" %1$-11s %2$-11s %3$9s%4$8s %5$s\r\n", soilSite.getOr("sl_loc_3", defValC).toString(), soilSite.getOr("sl_loc_1", defValC).toString(), formatNumStr(8, soilSite.getOr("soil_lat", defValR).toString()), // P.S. Definition changed 9 -> 10 (06/24) formatNumStr(8, soilSite.getOr("soil_long", defValR).toString()), // P.S. Definition changed 9 -> 8 (06/24) soilSite.getOr("classification", defValC).toString())); sbData.append("@ SCOM SALB SLU1 SLDR SLRO SLNF SLPF SMHB SMPX SMKE\r\n"); sbData.append(String.format(" %1$5s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$-5s %9$-5s %10$-5s\r\n", soilSite.getOr("scom", defValC).toString(), formatNumStr(5, soilSite.getOr("salb", defValR).toString()), formatNumStr(5, soilSite.getOr("slu1", defValR).toString()), formatNumStr(5, soilSite.getOr("sldr", defValR).toString()), formatNumStr(5, soilSite.getOr("slro", defValR).toString()), formatNumStr(5, soilSite.getOr("slnf", defValR).toString()), formatNumStr(5, soilSite.getOr("slpf", defValR).toString()), soilSite.getOr("smhb", defValC).toString(), soilSite.getOr("smpx", defValC).toString(), soilSite.getOr("smke", defValC).toString())); // Soil Layer data section soilRecords = (ArrayList) soilSite.getOr(layerKey, new ArrayList()); // part one sbData.append("@ SLB SLMH SLLL SDUL SSAT SRGF SSKS SBDM SLOC SLCL SLSI SLCF SLNI SLHW SLHB SCEC SADC\r\n"); // part two // Get first site record AdvancedHashMap fstRecord = new AdvancedHashMap(); if (!soilRecords.isEmpty()) { fstRecord = adapter.exportRecord((Map) soilRecords.get(0)); } // Check if there is 2nd part of layer data for output p2Flg = false; for (int j = 0; j < p2Ids.length; j++) { if (!fstRecord.getOr(p2Ids[j], "").toString().equals("")) { p2Flg = true; break; } } if (p2Flg) { // TODO CACO3 or SLCA? sbLyrP2.append("@ SLB SLPX SLPT SLPO CACO3 SLAL SLFE SLMN SLBS SLPA SLPB SLKE SLMG SLNA SLSU SLEC SLCA\r\n"); } // Loop for laryer data for (int j = 0; j < soilRecords.size(); j++) { soilRecord = adapter.exportRecord((Map) soilRecords.get(j)); // part one sbData.append(String.format(" %1$5s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$5s %13$5s %14$5s %15$5s %16$5s %17$5s\r\n", formatNumStr(5, soilRecord.getOr("sllb", defValR).toString()), //TODO Do I need to check if sllb is a valid value soilRecord.getOr("slmh", defValC).toString(), formatNumStr(5, soilRecord.getOr("slll", defValR).toString()), formatNumStr(5, soilRecord.getOr("sldul", defValR).toString()), formatNumStr(5, soilRecord.getOr("slsat", defValR).toString()), formatNumStr(5, soilRecord.getOr("slrgf", defValR).toString()), formatNumStr(5, soilRecord.getOr("sksat", defValR).toString()), formatNumStr(5, soilRecord.getOr("slbdm", defValR).toString()), formatNumStr(5, soilRecord.getOr("sloc", defValR).toString()), formatNumStr(5, soilRecord.getOr("slcly", defValR).toString()), formatNumStr(5, soilRecord.getOr("slsil", defValR).toString()), formatNumStr(5, soilRecord.getOr("slcf", defValR).toString()), formatNumStr(5, soilRecord.getOr("slni", defValR).toString()), formatNumStr(5, soilRecord.getOr("slphw", defValR).toString()), formatNumStr(5, soilRecord.getOr("slphb", defValR).toString()), formatNumStr(5, soilRecord.getOr("slcec", defValR).toString()), formatNumStr(5, soilRecord.getOr("sadc", defValR).toString()))); // part two if (p2Flg) { sbLyrP2.append(String.format(" %1$5s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$5s %13$5s %14$5s %15$5s %16$5s %17$5s\r\n", formatNumStr(5, soilRecord.getOr("sllb", defValR).toString()), formatNumStr(5, soilRecord.getOr("slpx", defValR).toString()), formatNumStr(5, soilRecord.getOr("slpt", defValR).toString()), formatNumStr(5, soilRecord.getOr("slpo", defValR).toString()), formatNumStr(5, soilRecord.getOr("caco3", defValR).toString()), // P.S. Different with document (DSSAT vol2.pdf) formatNumStr(5, soilRecord.getOr("slal", defValR).toString()), formatNumStr(5, soilRecord.getOr("slfe", defValR).toString()), formatNumStr(5, soilRecord.getOr("slmn", defValR).toString()), formatNumStr(5, soilRecord.getOr("slbs", defValR).toString()), formatNumStr(5, soilRecord.getOr("slpa", defValR).toString()), formatNumStr(5, soilRecord.getOr("slpb", defValR).toString()), formatNumStr(5, soilRecord.getOr("slke", defValR).toString()), formatNumStr(5, soilRecord.getOr("slmg", defValR).toString()), formatNumStr(5, soilRecord.getOr("slna", defValR).toString()), formatNumStr(5, soilRecord.getOr("slsu", defValR).toString()), formatNumStr(5, soilRecord.getOr("slec", defValR).toString()), formatNumStr(5, soilRecord.getOr("slca", defValR).toString()))); } } // Add part two if (p2Flg) { sbData.append(sbLyrP2.toString()).append("\r\n"); sbLyrP2 = new StringBuilder(); } else { sbData.append("\r\n"); } } // Output finish bwS.write(sbError.toString()); bwS.write(sbData.toString()); bwS.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Set default value for missing data * */ private void setDefVal() { // defValD = ""; No need to set default value for Date type in soil file defValR = "-99"; defValC = "-99"; // TODO wait for confirmation defValI = "-99"; } }
package play.mvc; import akka.stream.javadsl.Source; import akka.util.ByteString; import akka.util.ByteString$; import akka.util.ByteStringBuilder; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import play.api.libs.streams.Streams; import play.http.HttpEntity; import play.libs.Json; import scala.None$; import scala.Option; import scala.compat.java8.OptionConverters; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.Map; import java.util.Optional; /** * A status with no body */ public class StatusHeader extends Result { private static final int defaultChunkSize = 1024 * 8; public StatusHeader(int status) { super(status); } /** * Send the given input stream. * * The input stream will be sent chunked since there is no specified content length. * * @param stream The input stream to send. * @return The result. */ public Result sendInputStream(InputStream stream) { if (stream == null) { throw new NullPointerException("Null stream"); } return new Result(status(), HttpEntity.chunked(Streams.inputStreamToSource(stream, defaultChunkSize).asJava(), Optional.empty())); } /** * Send the given input stream. * * @param stream The input stream to send. * @param contentLength The length of the content in the stream. * @return The result. */ public Result sendInputStream(InputStream stream, long contentLength) { if (stream == null) { throw new NullPointerException("Null content"); } return new Result(status(), new HttpEntity.Streamed(Streams.inputStreamToSource(stream, defaultChunkSize).asJava(), Optional.of(contentLength), Optional.empty())); } /** * Send the given resource. * <p> * The resource will be loaded from the same classloader that this class comes from. * * @param resourceName The path of the resource to load. */ public Result sendResource(String resourceName) { return sendResource(resourceName, true); } /** * Send the given resource from the given classloader. * * @param resourceName The path of the resource to load. * @param classLoader The classloader to load it from. */ public Result sendResource(String resourceName, ClassLoader classLoader) { return sendResource(resourceName, classLoader, true); } /** * Send the given resource. * <p> * The resource will be loaded from the same classloader that this class comes from. * * @param resourceName The path of the resource to load. * @param inline Whether it should be served as an inline file, or as an attachment. */ public Result sendResource(String resourceName, boolean inline) { return sendResource(resourceName, this.getClass().getClassLoader(), inline); } /** * Send the given resource from the given classloader. * * @param resourceName The path of the resource to load. * @param classLoader The classloader to load it from. * @param inline Whether it should be served as an inline file, or as an attachment. */ public Result sendResource(String resourceName, ClassLoader classLoader, boolean inline) { return doSendResource(Streams.resourceToSource(classLoader, resourceName, 8192).asJava(), Optional.empty(), Optional.of(resourceName), inline); } /** * Sends the given path. * * @param path The path to send. */ public Result sendPath(Path path) { return sendPath(path, false); } /** * Sends the given path. * * @param path The path to send. * @param inline Whether it should be served as an inline file, or as an attachment. */ public Result sendPath(Path path, boolean inline) { return sendPath(path, inline, path.getFileName().toString()); } /** * Sends the given path. * * @param path The path to send. * @param inline Whether it should be served as an inline file, or as an attachment. * @param filename The file name of the path. */ public Result sendPath(Path path, boolean inline, String filename) { if (path == null) { throw new NullPointerException("null content"); } try { return doSendResource(Streams.fileToSource(path.toFile(), 8192).asJava(), Optional.of(Files.size(path)), Optional.of(filename), inline); } catch (IOException e) { throw new RuntimeException(e); } } /** * Sends the given file. * * @param file The file to send. */ private Result sendFile(File file) { return sendFile(file, true); } /** * Sends the given file. * * @param file The file to send. * @param inline True if the file should be sent inline, false if it should be sent as an attachment. */ public Result sendFile(File file, boolean inline) { if (file == null) { throw new NullPointerException("null file"); } return doSendResource(Streams.fileToSource(file, 8192).asJava(), Optional.of(file.length()), Optional.of(file.getName()), inline); } /** * Send the given file as an attachment. * * @param file The file to send. * @param fileName The name of the attachment */ public Result sendFile(File file, String fileName) { if (file == null) { throw new NullPointerException("null file"); } return doSendResource(Streams.fileToSource(file, 8192).asJava(), Optional.of(file.length()), Optional.of(fileName), true); } private Result doSendResource(Source<ByteString, ?> data, Optional<Long> contentLength, Optional<String> resourceName, boolean inline) { Map<String, String> headers = Collections.singletonMap(Http.HeaderNames.CONTENT_DISPOSITION, (inline ? "inline" : "attachment") + (resourceName.isPresent() ? "; filename=\"" + resourceName.get() + "\"" : "")); return new Result(status(), headers, new HttpEntity.Streamed( data, contentLength, resourceName.map(name -> OptionConverters.toJava(play.api.libs.MimeTypes.forFileName(name)) .orElse(Http.MimeTypes.BINARY) ) )); } /** * Send a chunked response with the given chunks. */ public Result chunked(Source<ByteString, ?> chunks) { return new Result(status(), HttpEntity.chunked(chunks, Optional.empty())); } /** * Send a chunked response with the given chunks. * * @deprecated Use {@link #chunked(Source)} instead. */ public <T> Result chunked(Results.Chunks<T> chunks) { return new Result(status(), HttpEntity.chunked( Source.from(Streams.<T>enumeratorToPublisher(chunks.enumerator, Option.<T>empty())) .<ByteString>map(t -> chunks.writable.transform().apply(t)), OptionConverters.toJava(chunks.writable.contentType()) )); } /** * Send a json result. */ public Result sendJson(JsonNode json) { return sendJson(json, "utf-8"); } /** * Send a json result. */ public Result sendJson(JsonNode json, String charset) { if (json == null) { throw new NullPointerException("Null content"); } ObjectMapper mapper = Json.mapper(); ByteStringBuilder builder = ByteString$.MODULE$.newBuilder(); try { JsonGenerator jgen = new JsonFactory(mapper) .createGenerator(new OutputStreamWriter(builder.asOutputStream(), charset)); mapper.writeValue(jgen, json); return new Result(status(), new HttpEntity.Strict(builder.result(), Optional.of("application/json;charset=" + charset))); } catch (IOException e) { throw new RuntimeException(e); } } public Result sendEntity(HttpEntity entity) { return new Result(status(),entity); } }
package org.agmip.translators.dssat; import java.io.BufferedReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import org.agmip.core.types.AdvancedHashMap; /** * DSSAT Experiment Data I/O API Class * * @author Meng Zhang * @version 1.0 */ public class DssatXFileInput extends DssatCommonInput { /** * Constructor with no parameters * Set jsonKey as "experiment" * */ public DssatXFileInput() { super(); jsonKey = "experiment"; } /** * DSSAT XFile Data input method for Controller using * * @param brMap The holder for BufferReader objects for all files * @return result data holder object */ @Override protected AdvancedHashMap readFile(HashMap brMap) throws IOException { AdvancedHashMap ret = new AdvancedHashMap(); String line; BufferedReader br; BufferedReader brw = null; HashMap mapW; String wid; String fileName; LinkedHashMap formats = new LinkedHashMap(); ArrayList trArr = new ArrayList(); ArrayList cuArr = new ArrayList(); ArrayList flArr = new ArrayList(); ArrayList saArr = new ArrayList(); ArrayList sadArr = new ArrayList(); ArrayList icArr = new ArrayList(); ArrayList icdArr = new ArrayList(); ArrayList plArr = new ArrayList(); ArrayList irArr = new ArrayList(); ArrayList irdArr = new ArrayList(); ArrayList feArr = new ArrayList(); ArrayList omArr = new ArrayList(); ArrayList chArr = new ArrayList(); ArrayList tiArr = new ArrayList(); ArrayList emArr = new ArrayList(); ArrayList haArr = new ArrayList(); ArrayList smArr = new ArrayList(); String eventKey = "data"; br = (BufferedReader) brMap.get("X"); mapW = (HashMap) brMap.get("W"); fileName = (String) brMap.get("Z"); wid = fileName.length() > 4 ? fileName.substring(0, 4) : fileName; // If XFile is no been found if (br == null) { // TODO reprot file not exist error return ret; } ret.put("treatment", trArr); ret.put("cultivar", cuArr); ret.put("field", flArr); ret.put("soil_analysis", saArr); ret.put("initial_condition", icArr); ret.put("plant", plArr); ret.put("irrigation", irArr); ret.put("fertilizer", feArr); ret.put("residue_organic", omArr); ret.put("soil_analysis", chArr); ret.put("tillage", tiArr); ret.put("emvironment", emArr); ret.put("harvest", haArr); ret.put("simulation", smArr); while ((line = br.readLine()) != null) { // Get content type of line judgeContentType(line); // Read Exp title info if (flg[0].startsWith("exp.details:") && flg[2].equals("")) { // Set variables' formats formats.clear(); formats.put("exname", 11); formats.put("local_name", 61); // Read line and save into return holder ret.put(readLine(line.substring(13), formats)); ret.put("institutes", line.substring(14, 16).trim()); } // Read General Section else if (flg[0].startsWith("general")) { // People info if (flg[1].equals("people") && flg[2].equals("data")) { ret.put("people", line.trim()); } // Address info else if (flg[1].equals("address") && flg[2].equals("data")) { String[] addr = line.split(",[ ]*"); ret.put("fl_loc_1", ""); ret.put("fl_loc_2", ""); ret.put("fl_loc_3", ""); ret.put("institutes", line.trim()); // ret.put("address", line.trim()); // P.S. no longer to use this field switch (addr.length) { case 0: break; case 1: ret.put("fl_loc_1", addr[0]); break; case 2: ret.put("fl_loc_1", addr[1]); ret.put("fl_loc_2", addr[0]); break; case 3: ret.put("fl_loc_1", addr[2]); ret.put("fl_loc_2", addr[1]); ret.put("fl_loc_3", addr[0]); break; default: ret.put("fl_loc_1", addr[addr.length - 1]); ret.put("fl_loc_2", addr[addr.length - 2]); String loc3 = ""; for (int i = 0; i < addr.length - 2; i++) { loc3 += addr[i] + ", "; } ret.put("fl_loc_3", loc3.substring(0, loc3.length() - 2)); } } // Site info else if ((flg[1].equals("site") || flg[1].equals("sites")) && flg[2].equals("data")) { //$ret[$flg[0]]["site"] = trim($line); // P.S. site is missing in the master variables list ret.put("site", line.trim()); } // Plot Info else if (flg[1].startsWith("parea") && flg[2].equals("data")) { // Set variables' formats formats.clear(); formats.put("parea", 7); formats.put("prno", 6); formats.put("plen", 6); formats.put("pldr", 6); formats.put("plsp", 6); formats.put("play", 6); formats.put("pltha", 6); formats.put("hrno", 6); formats.put("hlen", 6); formats.put("plthm", 16); // Read line and save into return holder ret.put("plot_info", readLine(line, formats)); } // Notes field else if (flg[1].equals("notes") && flg[2].equals("data")) { //$ret[$flg[0]]["notes"] = addArray($ret[$flg[0]]["notes"], " ". trim($line), ""); if (!ret.containsKey("notes")) { ret.put("notes", line.trim() + "\\r\\n"); } else { String notes = (String) ret.get("notes"); notes += line.trim() + "\\r\\n"; ret.put("notes", notes); } } else { } } // Read TREATMENTS Section else if (flg[0].startsWith("treatments")) { // Read TREATMENTS data if (flg[2].equals("data")) { // Set variables' formats formats.clear(); formats.put("trno", 2); formats.put("sq", 2); formats.put("op", 2); formats.put("co", 2); formats.put("tr_name", 26); formats.put("ge", 3); formats.put("fl", 3); formats.put("sa", 3); formats.put("ic", 3); formats.put("pl", 3); formats.put("ir", 3); formats.put("fe", 3); formats.put("om", 3); formats.put("ch", 3); formats.put("ti", 3); formats.put("em", 3); formats.put("ha", 3); formats.put("sm", 3); // Read line and save into return holder trArr.add(readLine(line, formats)); } else { } } // Read CULTIVARS Section else if (flg[0].startsWith("cultivars")) { // Read CULTIVARS data if (flg[2].equals("data")) { // Set variables' formats formats.clear(); formats.put("", 2); // P.S. ignore the data index "ge" formats.put("cr", 3); formats.put("cul_id", 7); formats.put("cul_name", 17); // Read line and save into return holder cuArr.add(readLine(line, formats)); if (cuArr.size() == 1) { ret.put("cr", line.substring(3, 5).trim()); // TODO keep for the early version; just first entry } } else { } } // Read FIELDS Section else if (flg[0].startsWith("fields")) { // Read field info 1st line if (flg[1].startsWith("l id_") && flg[2].equals("data")) { // Set variables' formats formats.clear(); formats.put("fl", 2); formats.put("id_field", 9); formats.put("wsta_id", 9); //P.S. id do not match with the master list "wth_id"; might have another id name formats.put("flsl", 6); formats.put("flob", 6); formats.put("fl_drntype", 6); formats.put("fldrd", 6); formats.put("fldrs", 6); formats.put("flst", 6); formats.put("sltx", 6); formats.put("sldp", 6); formats.put("soil_id", 11); formats.put("fl_name", line.length()); // Read line and save into return holder addToArray(flArr, readLine(line, formats), "fl"); // Read weather station id wid = line.substring(12, 20).trim(); }// // Read field info 2nd line else if (flg[1].startsWith("l ...") && flg[2].equals("data")) { // Set variables' formats formats.clear(); formats.put("fl", 2); formats.put("fl_lat", 16); formats.put("fl_long", 16); formats.put("flele", 10); formats.put("farea", 18); formats.put("", 6); // P.S. id do not find in the master list (? it seems to be calculated by other fields) formats.put("fllwr", 6); formats.put("flsla", 6); formats.put("flhst", 6); // P.S. id do not find in the master list (field histoy code) formats.put("fhdur", 6); // P.S. id do not find in the master list (duration associated with field history code in years) // Read line and save into return holder AdvancedHashMap tmp = readLine(line, formats); // Read lat and long String strLat = (String) tmp.get("fl_lat"); String strLong = (String) tmp.get("fl_long"); // If lat or long is not valid data, read data from weather file if (!checkValidValue(strLat) || !checkValidValue(strLong) || (Double.parseDouble(strLat) == 0 && Double.parseDouble(strLong) == 0)) { // check if weather is validable for (Object key : mapW.keySet()) { if (((String) key).contains(wid)) { brw = (BufferedReader) mapW.get(key); break; } } if (brw != null) { String lineW; while ((lineW = brw.readLine()) != null) { if (lineW.startsWith("@ INSI")) { lineW = brw.readLine(); strLat = lineW.substring(6, 15).trim(); strLong = lineW.substring(15, 24).trim(); break; } } // check if lat and long are valid in the weather file; if not, set invalid value for them if (!checkValidValue(strLat) || !checkValidValue(strLong) || (Double.parseDouble(strLat) == 0 && Double.parseDouble(strLong) == 0)) { strLat = defValI; strLong = defValI; } } // if weather file is not avaliable to read, set invalid value for lat and long else { strLat = defValI; strLong = defValI; } } if (flArr.isEmpty()) { ret.put("fl_lat", strLong); // TODO Keep the meta data handling for the early version ret.put("fl_long", strLat); // TODO Keep the meta data handling for the early version } tmp.put("fl_lat", strLong); tmp.put("fl_long", strLat); addToArray(flArr, tmp, "fl"); } } // Read SOIL ANALYSIS Section else if (flg[0].startsWith("soil")) { // Read SOIL ANALYSIS global data if (flg[1].startsWith("a sadat") && flg[2].equals("data")) { // Set variables' formats formats.clear(); formats.put("", 2); // P.S. ignore the data index "sa" formats.put("sadat", 6); formats.put("samhb", 6); formats.put("sampx", 6); formats.put("samke", 6); // Read line and save into return holder AdvancedHashMap tmp = readLine(line, formats); tmp.put("sadat", translateDateStr((String) tmp.get("sadat"))); saArr.add(tmp); sadArr = new ArrayList(); tmp.put(eventKey, sadArr); } // Read SOIL ANALYSIS layer data else if (flg[1].startsWith("a sadat") && flg[2].equals("data")) { // Set variables' formats formats.clear(); formats.put("", 2); // P.S. ignore the data index "sa" formats.put("sabl", 6); formats.put("sabdm", 6); formats.put("saoc", 6); formats.put("sani", 6); formats.put("saphw", 6); formats.put("saphb", 6); formats.put("sapx", 6); formats.put("sake", 6); formats.put("sasc", 6); // P.S. id do not find in the master list (Measured stable organic C by soil layer, g[C]/100g[Soil]) // Read line and save into return holder sadArr.add(readLine(line, formats)); } else { } } // Read INITIAL CONDITIONS Section else if (flg[0].startsWith("initial")) { // Read INITIAL CONDITIONS global data if (flg[1].startsWith("c pcr") && flg[2].equals("data")) { // Set variables' formats formats.clear(); formats.put("", 2); // P.S. ignore the data index "ic" formats.put("icpcr", 6); formats.put("icdat", 6); formats.put("icrt", 6); formats.put("icnd", 6); formats.put("icrz#", 6); // P.S. use the "icrz#" instead of "icrzno" formats.put("icrze", 6); formats.put("icwt", 6); formats.put("icrag", 6); formats.put("icrn", 6); formats.put("icrp", 6); formats.put("icrip", 6); formats.put("icrdp", 6); formats.put("ic_name", line.length()); // Read line and save into return holder AdvancedHashMap tmp = readLine(line, formats); tmp.put("icdat", translateDateStr((String) tmp.get("icdat"))); icArr.add(tmp); icdArr = new ArrayList(); tmp.put(eventKey, icdArr); } else // INITIAL CONDITIONS layer data if (flg[1].startsWith("c icbl") && flg[2].equals("data")) { // Set variables' formats formats.clear(); formats.put("", 2); // P.S. ignore the detail (event) data index "ic" formats.put("icbl", 6); formats.put("ich2o", 6); formats.put("icnh4", 6); formats.put("icno3", 6); // Read line and save into return holder icdArr.add(readLine(line, formats)); } else { } } // Read PLANTING DETAILS Section else if (flg[0].startsWith("planting")) { // Read PLANTING data if (flg[2].equals("data")) { // Set variables' formats formats.clear(); formats.put("", 2); // P.S. ignore the data index "pl" formats.put("pdate", 6); formats.put("pldae", 6); formats.put("plpop", 6); formats.put("plpoe", 6); formats.put("plme", 6); formats.put("plds", 6); formats.put("plrs", 6); formats.put("plrd", 6); formats.put("pldp", 6); formats.put("plmwt", 6); formats.put("page", 6); formats.put("penv", 6); formats.put("plph", 6); formats.put("plspl", 6); formats.put("pl_name", line.length()); // Read line and save into return holder AdvancedHashMap tmp = readLine(line, formats); tmp.put("pdate", translateDateStr((String) tmp.get("pdate"))); tmp.put("pldae", translateDateStr((String) tmp.get("pldae"))); plArr.add(tmp); if (plArr.size() == 1) { ret.put("pdate", translateDateStr(line.substring(3, 8).trim())); // TODO keep for the early version } } else { } } // Read IRRIGATION AND WATER MANAGEMENT Section else if (flg[0].startsWith("irrigation")) { // Read IRRIGATION global data if (flg[1].startsWith("i efir") && flg[2].equals("data")) { // Set variables' formats formats.clear(); formats.put("", 2); // P.S. ignore the data index "ir" formats.put("ireff", 6); formats.put("irmdp", 6); formats.put("irthr", 6); formats.put("irept", 6); formats.put("irstg", 6); formats.put("iame", 6); formats.put("iamt", 6); formats.put("ir_name", line.length()); // Read line and save into return holder AdvancedHashMap tmp = readLine(line, formats); irArr.add(tmp); irdArr = new ArrayList(); tmp.put(eventKey, irdArr); } // Read IRRIGATION appliction data else if (flg[1].startsWith("i idate") && flg[2].equals("data")) { // Set variables' formats formats.clear(); formats.put("", 2); // P.S. ignore the data index "ir" formats.put("idate", 6); formats.put("irop", 6); formats.put("irval", 6); // Read line and save into return holder AdvancedHashMap tmp = readLine(line, formats); tmp.put("idate", translateDateStr((String) tmp.get("idate"))); irdArr.add(tmp); } else { } } // Read FERTILIZERS (INORGANIC) Section else if (flg[0].startsWith("fertilizers")) { // Read FERTILIZERS data if (flg[2].equals("data")) { // Set variables' formats formats.clear(); formats.put("", 2); // P.S. ignore the data index "fe" formats.put("fdate", 6); formats.put("fecd", 6); formats.put("feacd", 6); formats.put("fedep", 6); formats.put("feamn", 6); formats.put("feamp", 6); formats.put("feamk", 6); formats.put("feamc", 6); formats.put("feamo", 6); formats.put("feocd", 6); formats.put("fe_name", line.length()); // Read line and save into return holder AdvancedHashMap tmp = readLine(line, formats); tmp.put("fdate", translateDateStr((String) tmp.get("fdate"))); feArr.add(tmp); } else { } } // Read RESIDUES AND OTHER ORGANIC MATERIALS Section else if (flg[0].startsWith("residues")) { // Read ORGANIC MATERIALS data if (flg[2].equals("data")) { // Set variables' formats formats.clear(); formats.put("", 2); // P.S. ignore the data index "om" formats.put("omdat", 6); // P.S. id do not match with the master list "omday" formats.put("omcd", 6); formats.put("omamt", 6); formats.put("omn%", 6); // P.S. id do not match with the master list "omnpct" formats.put("omp%", 6); // P.S. id do not match with the master list "omppct" formats.put("omk%", 6); // P.S. id do not match with the master list "omkpct" formats.put("ominp", 6); formats.put("omdep", 6); formats.put("omacd", 6); formats.put("om_name", line.length()); // Read line and save into return holder AdvancedHashMap tmp = readLine(line, formats); tmp.put("omdat", translateDateStr((String) tmp.get("omdat"))); omArr.add(tmp); } else { } } // Read CHEMICAL APPLICATIONS Section else if (flg[0].startsWith("chemical")) { // Read CHEMICAL APPLICATIONS data if (flg[2].equals("data")) { // Set variables' formats formats.clear(); formats.put("", 2); // P.S. ignore the data index "ch" formats.put("cdate", 6); formats.put("chcd", 6); formats.put("chamt", 6); formats.put("chacd", 6); formats.put("chdep", 6); formats.put("ch_targets", 6); formats.put("ch_name", line.length()); // Read line and save into return holder AdvancedHashMap tmp = readLine(line, formats); tmp.put("cdate", translateDateStr((String) tmp.get("cdate"))); chArr.add(tmp); } else { } } // Read TILLAGE Section else if (flg[0].startsWith("tillage")) { // Read TILLAGE data if (flg[2].equals("data")) { // Set variables' formats formats.clear(); formats.put("", 2); // P.S. ignore the data index "ti" formats.put("tdate", 6); formats.put("tiimp", 6); formats.put("tidep", 6); formats.put("ti_name", line.length()); // Read line and save into return holder AdvancedHashMap tmp = readLine(line, formats); tmp.put("tdate", translateDateStr((String) tmp.get("tdate"))); tiArr.add(tmp); } else { } } // Read ENVIRONMENT MODIFICATIONS Section else if (flg[0].startsWith("environment")) { // Read ENVIRONMENT MODIFICATIONS data if (flg[2].equals("data")) { // Set variables' formats formats.clear(); formats.put("", 2); // P.S. ignore the data index "em" formats.put("emday", 6); formats.put("ecdyl", 2); formats.put("emdyl", 4); formats.put("ecrad", 2); formats.put("emrad", 4); formats.put("ecmax", 2); formats.put("emmax", 4); formats.put("ecmin", 2); formats.put("emmin", 4); formats.put("ecrai", 2); formats.put("emrai", 4); formats.put("ecco2", 2); formats.put("emco2", 4); formats.put("ecdew", 2); formats.put("emdew", 4); formats.put("ecwnd", 2); formats.put("emwnd", 4); formats.put("em_name", line.length()); // Read line and save into return holder AdvancedHashMap tmp = readLine(line, formats); tmp.put("emday", translateDateStr((String) tmp.get("emday"))); emArr.add(tmp); } else { } } // Read HARVEST DETAILS Section else if (flg[0].startsWith("harvest")) { // Read HARVEST data if (flg[2].equals("data")) { // Set variables' formats formats.clear(); formats.put("", 2); // P.S. ignore the data index "em" formats.put("hdate", 6); formats.put("hastg", 6); formats.put("hacom", 6); formats.put("hasiz", 6); formats.put("hapc", 6); formats.put("habpc", 6); formats.put("ha_name", line.length()); // Read line and save into return holder AdvancedHashMap tmp = readLine(line, formats); tmp.put("hdate", translateDateStr((String) tmp.get("hdate"))); haArr.add(tmp); if (haArr.size() == 1) { ret.put("hdate", translateDateStr(line.substring(3, 8).trim())); // TODO keep for early version } } else { } } // Read SIMULATION CONTROLS Section // P.S. no need to be divided else if (flg[0].startsWith("simulation")) { // Read general info if (flg[1].startsWith("n general") && flg[2].equals("data")) { // Set variables' formats formats.clear(); formats.put("sm", 2); // formats.put("general", 12); // formats.put("nyers", 6); // formats.put("nreps", 6); // formats.put("start", 6); // formats.put("sdate", 6); // formats.put("rseed", 6); // formats.put("sname", 26); // formats.put("model", line.length()); // Read line and save into return holder AdvancedHashMap tmp = readLine(line, formats); // tmp.put("sdate", translateDateStr((String) tmp.get("sdate"))); tmp.put("general", line); addToArray(smArr, tmp, "sm"); } // Read options info else if (flg[1].startsWith("n options") && flg[2].equals("data")) { // Set variables' formats formats.clear(); formats.put("sm", 2); // formats.put("options", 12); // formats.put("water", 6); // formats.put("nitro", 6); // formats.put("symbi", 6); // formats.put("phosp", 6); // formats.put("potas", 6); // formats.put("dises", 6); // formats.put("chem", 6); // formats.put("till", 6); // formats.put("co2", 6); // Read line and save into return holder AdvancedHashMap tmp = readLine(line, formats); tmp.put("options", line); addToArray(smArr, tmp, "sm"); } // Read methods info else if (flg[1].startsWith("n methods") && flg[2].equals("data")) { // Set variables' formats formats.clear(); formats.put("sm", 2); // formats.put("methods", 12); // formats.put("wther", 6); // formats.put("incon", 6); // formats.put("light", 6); // formats.put("evapo", 6); // formats.put("infil", 6); // formats.put("photo", 6); // formats.put("hydro", 6); // formats.put("nswit", 6); // formats.put("mesom", 6); // formats.put("mesev", 6); // formats.put("mesol", 6); // Read line and save into return holder AdvancedHashMap tmp = readLine(line, formats); tmp.put("methods", line); addToArray(smArr, tmp, "sm"); } // Read management info else if (flg[1].startsWith("n management") && flg[2].equals("data")) { // Set variables' formats formats.clear(); formats.put("sm", 2); // formats.put("management", 12); // formats.put("plant", 6); // formats.put("irrig", 6); // formats.put("ferti", 6); // formats.put("resid", 6); // formats.put("harvs", 6); // Read line and save into return holder AdvancedHashMap tmp = readLine(line, formats); tmp.put("management", line); addToArray(smArr, tmp, "sm"); } // Read outputs info else if (flg[1].startsWith("n outputs") && flg[2].equals("data")) { // Set variables' formats formats.clear(); formats.put("sm", 2); // formats.put("outputs", 12); // formats.put("fname", 6); // formats.put("ovvew", 6); // formats.put("sumry", 6); // formats.put("fropt", 6); // formats.put("grout", 6); // formats.put("caout", 6); // formats.put("waout", 6); // formats.put("niout", 6); // formats.put("miout", 6); // formats.put("diout", 6); // formats.put("long", 6); // formats.put("chout", 6); // formats.put("opout", 6); // Read line and save into return holder AdvancedHashMap tmp = readLine(line, formats); tmp.put("outputs", line); addToArray(smArr, tmp, "sm"); } // Read planting info else if (flg[1].startsWith("n planting") && flg[2].equals("data")) { // Set variables' formats formats.clear(); formats.put("sm", 2); // formats.put("planting", 12); // formats.put("pfrst", 6); // formats.put("plast", 6); // formats.put("ph20l", 6); // formats.put("ph2ou", 6); // formats.put("ph20d", 6); // formats.put("pstmx", 6); // formats.put("pstmn", 6); // Read line and save into return holder AdvancedHashMap tmp = readLine(line, formats); // tmp.put("pfrst", translateDateStr((String) tmp.get("pfrst"))); // tmp.put("plast", translateDateStr((String) tmp.get("plast"))); tmp.put("planting", line); addToArray(smArr, tmp, "sm"); } // Read irrigation info else if (flg[1].startsWith("n irrigation") && flg[2].equals("data")) { // Set variables' formats formats.clear(); formats.put("sm", 2); // formats.put("irrigation", 12); // formats.put("imdep", 6); // formats.put("ithrl", 6); // formats.put("ithru", 6); // formats.put("iroff", 6); // formats.put("imeth", 6); // formats.put("iramt", 6); // formats.put("ireff", 6); // Read line and save into return holder AdvancedHashMap tmp = readLine(line, formats); tmp.put("irrigation", line); addToArray(smArr, tmp, "sm"); } // Read nitrogen info else if (flg[1].startsWith("n nitrogen") && flg[2].equals("data")) { // Set variables' formats formats.clear(); formats.put("sm", 2); // formats.put("nitrogen", 12); // formats.put("nmdep", 6); // formats.put("nmthr", 6); // formats.put("namnt", 6); // formats.put("ncode", 6); // formats.put("naoff", 6); // Read line and save into return holder AdvancedHashMap tmp = readLine(line, formats); tmp.put("nitrogen", line); addToArray(smArr, tmp, "sm"); } // Read residues info else if (flg[1].startsWith("n residues") && flg[2].equals("data")) { // Set variables' formats formats.clear(); formats.put("sm", 2); // formats.put("residues", 12); // formats.put("ripcn", 6); // formats.put("rtime", 6); // formats.put("ridep", 6); // Read line and save into return holder AdvancedHashMap tmp = readLine(line, formats); tmp.put("residues", line); addToArray(smArr, tmp, "sm"); } // Read harvest info else if (flg[1].startsWith("n harvest") && flg[2].equals("data")) { // Set variables' formats formats.clear(); formats.put("sm", 2); // formats.put("harvests", 12); // formats.put("hfrst", 6); // P.S. Keep the original value // formats.put("hlast", 6); // formats.put("hpcnp", 6); // formats.put("hrcnr", 6); // Read line and save into return holder AdvancedHashMap tmp = readLine(line, formats); // tmp.put("hlast", translateDateStr((String) tmp.get("hlast"))); tmp.put("harvests", line); addToArray(smArr, tmp, "sm"); } else { } } else { } } // br.close(); // if (brw != null) brw.close(); compressData(ret); return ret; } /** * Set reading flgs for title lines (marked with *) * * @param line the string of reading line */ @Override protected void setTitleFlgs(String line) { flg[0] = line.substring(1).trim().toLowerCase(); flg[1] = ""; flg[2] = ""; } }
package org.aksw.sml.converters.r2rml2sml; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.Resource; public class ObjectMap extends TermMap { public ObjectMap(Model model, Resource termMapResource) { super(model, termMapResource); } }
package org.apdplat.superword.tools; import java.io.InputStream; import java.util.List; import java.util.stream.Collectors; import org.apdplat.superword.model.Prefix; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; public class PrefixExtractor { private static final String SRC_HTML = "/tools/prefix_suffix.txt"; public static List<Prefix> extract() { try(InputStream in = PrefixExtractor.class.getResourceAsStream(SRC_HTML)) { Document document = Jsoup.parse(in, "utf-8", ""); return document .select("table tbody tr") .stream() .map(PrefixExtractor::extractPrefix) .filter(item -> item.getPrefix() != null) .sorted() .distinct() .collect(Collectors.toList()); }catch (Exception e){ throw new RuntimeException(e); } } public static Prefix extractPrefix(Element element){ Prefix prefix = new Prefix(); List<Element> tds = element.children(); if(tds==null || tds.size()!=3){ return prefix; } String p = tds.get(0).text().trim(); if(!p.endsWith("-")){ return prefix; } String des = tds.get(1).text(); return new Prefix(p, des); } public static void main(String[] args){ extract() .forEach(prefix -> System.out.println("prefix(wordSet, \"" + prefix.getPrefix() + "\", \"" + prefix.getDes() + "\");")); } }
package org.apdplat.word.lucene; import java.io.IOException; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.Tokenizer; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.analysis.tokenattributes.OffsetAttribute; import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute; import org.apdplat.word.lucene.attribute.*; import org.apdplat.word.segmentation.Segmentation; import org.apdplat.word.segmentation.SegmentationAlgorithm; import org.apdplat.word.segmentation.SegmentationFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Lucene * @author */ public class ChineseWordAnalyzer extends Analyzer { private static final Logger LOGGER = LoggerFactory.getLogger(ChineseWordAnalyzer.class); private Segmentation segmentation = null; public ChineseWordAnalyzer(){ this.segmentation = SegmentationFactory.getSegmentation(SegmentationAlgorithm.BidirectionalMaximumMatching); } public ChineseWordAnalyzer(String segmentationAlgorithm) { try{ SegmentationAlgorithm sa = SegmentationAlgorithm.valueOf(segmentationAlgorithm); this.segmentation = SegmentationFactory.getSegmentation(sa); }catch(Exception e){ this.segmentation = SegmentationFactory.getSegmentation(SegmentationAlgorithm.BidirectionalMaximumMatching); } } public ChineseWordAnalyzer(SegmentationAlgorithm segmentationAlgorithm) { this.segmentation = SegmentationFactory.getSegmentation(segmentationAlgorithm); } public ChineseWordAnalyzer(Segmentation segmentation) { this.segmentation = segmentation; } @Override protected TokenStreamComponents createComponents(String fieldName) { Tokenizer tokenizer = new ChineseWordTokenizer(segmentation); return new TokenStreamComponents(tokenizer); } public static void main(String args[]) throws IOException { Analyzer analyzer = new ChineseWordAnalyzer(); TokenStream tokenStream = analyzer.tokenStream("text", "APDPlat"); tokenStream.reset(); while(tokenStream.incrementToken()){ CharTermAttribute charTermAttribute = tokenStream.getAttribute(CharTermAttribute.class); OffsetAttribute offsetAttribute = tokenStream.getAttribute(OffsetAttribute.class); PositionIncrementAttribute positionIncrementAttribute = tokenStream.getAttribute(PositionIncrementAttribute.class); LOGGER.info(charTermAttribute.toString()+" ("+offsetAttribute.startOffset()+" - "+offsetAttribute.endOffset()+") "+positionIncrementAttribute.getPositionIncrement()); } tokenStream.close(); tokenStream = analyzer.tokenStream("text", "wordysc"); tokenStream.reset(); while(tokenStream.incrementToken()){ CharTermAttribute charTermAttribute = tokenStream.getAttribute(CharTermAttribute.class); OffsetAttribute offsetAttribute = tokenStream.getAttribute(OffsetAttribute.class); PositionIncrementAttribute positionIncrementAttribute = tokenStream.getAttribute(PositionIncrementAttribute.class); LOGGER.info(charTermAttribute.toString()+" ("+offsetAttribute.startOffset()+" - "+offsetAttribute.endOffset()+") "+positionIncrementAttribute.getPositionIncrement()); } tokenStream.close(); tokenStream = analyzer.tokenStream("text", "5"); tokenStream.reset(); while(tokenStream.incrementToken()){ CharTermAttribute charTermAttribute = tokenStream.getAttribute(CharTermAttribute.class); OffsetAttribute offsetAttribute = tokenStream.getAttribute(OffsetAttribute.class); PositionIncrementAttribute positionIncrementAttribute = tokenStream.getAttribute(PositionIncrementAttribute.class); PartOfSpeechAttribute partOfSpeechAttribute = tokenStream.getAttribute(PartOfSpeechAttribute.class); AcronymPinyinAttribute acronymPinyinAttribute = tokenStream.getAttribute(AcronymPinyinAttribute.class); FullPinyinAttribute fullPinyinAttribute = tokenStream.getAttribute(FullPinyinAttribute.class); SynonymAttribute synonymAttribute = tokenStream.getAttribute(SynonymAttribute.class); AntonymAttribute antonymAttribute = tokenStream.getAttribute(AntonymAttribute.class); LOGGER.info(charTermAttribute.toString()+" ("+offsetAttribute.startOffset()+" - "+offsetAttribute.endOffset()+") "+positionIncrementAttribute.getPositionIncrement()); LOGGER.info("PartOfSpeech:"+partOfSpeechAttribute.toString()); LOGGER.info("AcronymPinyin:"+acronymPinyinAttribute.toString()); LOGGER.info("FullPinyin:"+fullPinyinAttribute.toString()); LOGGER.info("Synonym:"+synonymAttribute.toString()); LOGGER.info("Antonym:"+antonymAttribute.toString()); } tokenStream.close(); } }
package org.ccci.gto.android.common.api; import android.net.Uri; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import org.ccci.gto.android.common.util.UriUtils; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.List; public abstract class AbstractApi<R extends AbstractApi.Request> { private static final int DEFAULT_ATTEMPTS = 3; @NonNull private final Uri mBaseUri; protected AbstractApi(@NonNull final String baseUri) { this(Uri.parse(baseUri.endsWith("/") ? baseUri : baseUri + "/")); } protected AbstractApi(@NonNull final Uri baseUri) { mBaseUri = baseUri; } @NonNull protected final HttpURLConnection sendRequest(@NonNull final R request) throws ApiException { return this.sendRequest(request, DEFAULT_ATTEMPTS); } @NonNull protected final HttpURLConnection sendRequest(@NonNull final R request, final int attempts) throws ApiException { try { // build the request uri final Uri.Builder uri = mBaseUri.buildUpon(); onPrepareUri(uri, request); final URL url; try { url = new URL(uri.build().toString()); } catch (final MalformedURLException e) { throw new RuntimeException("invalid Request URL: " + uri.build().toString(), e); } // prepare the request final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); onPrepareRequest(conn, request); // no need to explicitly execute, accessing the response triggers the execute // process the response onProcessResponse(conn, request); // return the connection for method specific handling return conn; } catch (final IOException e) { throw new ApiSocketException(e); } } @NonNull protected final Request.Parameter param(@NonNull final String name, @NonNull final String value) { return new Request.Parameter(name, value); } /* BEGIN request lifecycle events */ protected void onPrepareUri(@NonNull final Uri.Builder uri, @NonNull final R request) throws ApiException { // build the request uri uri.appendEncodedPath(request.path); if (request.params.size() > 0) { if (request.replaceParams) { final List<String> keys = new ArrayList<>(); for (final Request.Parameter param : request.params) { keys.add(param.name); } UriUtils.removeQueryParams(uri, keys.toArray(new String[keys.size()])); } for (final Request.Parameter param : request.params) { uri.appendQueryParameter(param.name, param.value); } } } protected void onPrepareRequest(@NonNull final HttpURLConnection conn, @NonNull final R request) throws ApiException, IOException { // build base request object conn.setRequestMethod(request.method.toString()); if (request.accept != null) { conn.addRequestProperty("Accept", request.accept.type); } conn.setInstanceFollowRedirects(request.followRedirects); } protected void onProcessResponse(@NonNull final HttpURLConnection conn, @NonNull final R request) throws ApiException, IOException { } /* END request lifecycle events */ protected static class Request { public enum Method {GET, POST, PUT, DELETE} public enum MediaType { APPLICATION_FORM_URLENCODED("application/x-www-form-urlencoded"), APPLICATION_JSON("application/json"), APPLICATION_XML("application/xml"), TEXT_PLAIN("text/plain"); final String type; private MediaType(final String type) { this.type = type; } } protected static final class Parameter { final String name; final String value; public Parameter(@NonNull final String name, @NonNull final String value) { this.name = name; this.value = value; } } @NonNull public Method method = Method.GET; // uri attributes @NonNull final String path; public final Collection<Parameter> params = new ArrayList<>(); public boolean replaceParams = false; // miscellaneous attributes @Nullable public MediaType accept = null; public boolean followRedirects = false; public Request(@NonNull final String path) { this.path = path; } } }
package org.dstadler.commons.http; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.dstadler.commons.logging.jdk.LoggerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.function.Consumer; import java.util.logging.Level; import java.util.logging.Logger; /** * Helper class which configures a {@link HttpClient} instance * for usage with BasicAuthentication user/pwd and also * disables SSL verification to work with self-signed SSL certificates * on web pages. */ public class HttpClientWrapper extends AbstractClientWrapper implements Closeable { private final static Logger log = LoggerFactory.make(); private final CloseableHttpClient httpClient; /** * Construct the {@link HttpClient} with the given authentication values * and all timeouts set to the given number of milliseconds * * @param user The username for basic authentication, use an empty string when no authentication is required * @param password The password for basic authentication, null when no authentication is required * @param timeoutMs The timeout for socket connection and reading, specified in milliseconds */ public HttpClientWrapper(String user, String password, int timeoutMs) { super(timeoutMs, true); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope(null, -1), new UsernamePasswordCredentials(user, password)); RequestConfig reqConfig = RequestConfig.custom() .setSocketTimeout(timeoutMs) .setConnectTimeout(timeoutMs) .setConnectionRequestTimeout(timeoutMs) .build(); // configure the builder for HttpClients HttpClientBuilder builder = HttpClients.custom() .setDefaultCredentialsProvider(credsProvider) .setDefaultRequestConfig(reqConfig); // add a permissive SSL Socket Factory to the builder createSSLSocketFactory(builder); // finally create the HttpClient instance this.httpClient = builder.build(); } /** * Construct the {@link HttpClient} without using authentication values * and all timeouts set to the given number of milliseconds * * @param timeoutMs The timeout for socket connection and reading, specified in milliseconds */ public HttpClientWrapper(int timeoutMs) { super(timeoutMs, false); RequestConfig reqConfig = RequestConfig.custom() .setSocketTimeout(timeoutMs) .setConnectTimeout(timeoutMs) .setConnectionRequestTimeout(timeoutMs) .build(); // configure the builder for HttpClients HttpClientBuilder builder = HttpClients.custom() .setDefaultRequestConfig(reqConfig); // add a permissive SSL Socket Factory to the builder createSSLSocketFactory(builder); // finally create the HttpClient instance this.httpClient = builder.build(); } /** * Return the current {@link HttpClient} instance. * * @return The internally used instance of the {@link HttpClient} */ public CloseableHttpClient getHttpClient() { return httpClient; } protected void simpleGetInternal(String url, Consumer<InputStream> consumer, String body) throws IOException { final HttpUriRequest httpGet = getHttpGet(url, body); final CloseableHttpResponse execute; if(withAuth) { HttpClientContext context = HttpClientContext.create(); HttpHost targetHost = getHttpHostWithAuth(url, context); execute = httpClient.execute(targetHost, httpGet, context); } else { execute = httpClient.execute(httpGet); } try (CloseableHttpResponse response = execute) { HttpEntity entity = checkAndFetch(response, url); try { consumer.accept(entity.getContent()); } finally { // ensure all content is taken out to free resources EntityUtils.consume(entity); } } } public String simplePost(String url, String body) throws IOException { HttpClientContext context = HttpClientContext.create(); HttpHost targetHost = getHttpHostWithAuth(url, context); final HttpPost httpPost = new HttpPost(url); if(body != null) { httpPost.setEntity(new StringEntity(body)); } try (CloseableHttpResponse response = httpClient.execute(targetHost, httpPost, context)) { HttpEntity entity = HttpClientWrapper.checkAndFetch(response, url); try { return IOUtils.toString(entity.getContent(), StandardCharsets.UTF_8); } finally { // ensure all content is taken out to free resources EntityUtils.consume(entity); } } } private void createSSLSocketFactory(HttpClientBuilder builder) { try { // Trust all certs, even self-signed and invalid hostnames, ... final SSLContext sslcontext = createSSLContext(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslcontext, NoopHostnameVerifier.INSTANCE) { @Override protected void prepareSocket(SSLSocket socket) throws IOException { super.prepareSocket(socket); socket.setSoTimeout(timeoutMs); // when running with Java 6 we should remove the outdated SSLv2Hello protocol as it is not // supported any more by dynaTrace after applying the FixPack for the POODLE SSLv3 attack Set<String> protocols = new HashSet<>(Arrays.asList(socket.getEnabledProtocols())); protocols.remove("SSLv2Hello"); socket.setEnabledProtocols(protocols.toArray(new String[0])); } }; builder.setSSLSocketFactory(sslsf); //builder = builder.setHostnameVerifier(new AllowAllHostnameVerifier()); } catch (GeneralSecurityException e) { log.log(Level.WARNING, "Could not create SSLSocketFactory for accepting all certificates", e); } } @Override public void close() throws IOException { httpClient.close(); } /** * Small helper method to simply query the URL without password and * return the resulting data. * * @param url The URL to query data from. * @return The resulting data read from the URL * @throws IOException If the URL is not accessible or the query returns * a HTTP code other than 200. */ public static String retrieveData(String url) throws IOException { return retrieveData(url, "", null, 10_000); } /** * Small helper method to simply query the URL without password and * return the resulting data. * * @param url The URL to query data from. * @param user The username to send * @param password The password to send * @param timeoutMs How long in milliseconds to wait for the request * @return The resulting data read from the URL * @throws IOException If the URL is not accessible or the query returns * a HTTP code other than 200. */ public static String retrieveData(String url, String user, String password, int timeoutMs) throws IOException { try (HttpClientWrapper wrapper = new HttpClientWrapper(user, password, timeoutMs)) { return wrapper.simpleGet(url); } } /** * Helper method to check the status code of the response and throw an IOException if it is * an error or moved state. * * @param response A HttpResponse that is resulting from executing a HttpMethod. * @param url The url, only used for building the error message of the exception. * * @return The {@link HttpEntity} returned from response.getEntity(). * * @throws IOException if the HTTP status code is higher than 206. */ public static HttpEntity checkAndFetch(HttpResponse response, String url) throws IOException { int statusCode = response.getStatusLine().getStatusCode(); if(statusCode > 206) { String msg = "Had HTTP StatusCode " + statusCode + " for request: " + url + ", response: " + response.getStatusLine().getReasonPhrase() + "\n" + (response.getFirstHeader("Location") == null ? "" : response.getFirstHeader("Location") + "\n") + (response.getEntity() == null ? "" : StringUtils.abbreviate(IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8), 1024)); log.warning(msg); throw new IOException(msg); } return response.getEntity(); } public static void downloadFile(String url, File destination, int timeoutMs) throws IOException, IllegalStateException { log.info("Downloading from " + url + " to " + destination); try (HttpClientWrapper client = new HttpClientWrapper(timeoutMs)) { client.simpleGet(url, inputStream -> { try { FileUtils.copyInputStreamToFile(inputStream, destination); } catch (IOException e) { throw new IllegalStateException(e); } }); } } }
package org.hildan.fxlog.controllers; import java.awt.Desktop; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.Collection; import java.util.List; import java.util.ResourceBundle; import java.util.concurrent.Callable; import java.util.function.Function; import java.util.function.Predicate; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import java.util.stream.Collectors; import javafx.application.Platform; import javafx.beans.binding.Binding; import javafx.beans.binding.Bindings; import javafx.beans.binding.StringBinding; import javafx.beans.property.BooleanProperty; import javafx.beans.property.IntegerProperty; import javafx.beans.property.Property; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.collections.transformation.FilteredList; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.input.Clipboard; import javafx.scene.input.ClipboardContent; import javafx.scene.input.KeyCode; import javafx.scene.input.ScrollEvent; import javafx.scene.layout.BorderPane; import javafx.stage.FileChooser; import javafx.stage.FileChooser.ExtensionFilter; import javafx.stage.Stage; import javafx.stage.StageStyle; import org.apache.commons.io.input.Tailer; import org.controlsfx.control.textfield.CustomTextField; import org.fxmisc.easybind.EasyBind; import org.hildan.fxlog.FXLog; import org.hildan.fxlog.coloring.Colorizer; import org.hildan.fxlog.columns.ColumnDefinition; import org.hildan.fxlog.columns.Columnizer; import org.hildan.fxlog.config.Config; import org.hildan.fxlog.core.LogEntry; import org.hildan.fxlog.core.LogTailListener; import org.hildan.fxlog.errors.ErrorDialog; import org.hildan.fxlog.filtering.Filter; import org.hildan.fxlog.themes.Css; import org.hildan.fxlog.themes.Theme; import org.hildan.fxlog.version.VersionChecker; import org.hildan.fxlog.view.StyledTableCell; import org.hildan.fxlog.view.UIUtils; import org.jetbrains.annotations.NotNull; public class MainController implements Initializable { private Config config; private Stage columnizersStage; private Stage colorizersStage; private Stage preferencesStage; private Stage aboutStage; @FXML private BorderPane mainPane; @FXML private TableView<LogEntry> logsTable; @FXML private ChoiceBox<Columnizer> columnizerSelector; @FXML private ChoiceBox<Colorizer> colorizerSelector; @FXML private CustomTextField filterField; @FXML private CustomTextField searchField; @FXML private CheckBox caseSensitiveFilterCheckbox; @FXML private Menu recentFilesMenu; @FXML private MenuItem closeMenu; @FXML private CheckMenuItem followTailMenu; @FXML private ToggleButton toggleFollowTailButton; private Property<Columnizer> columnizer; private Property<Colorizer> colorizer; private ObservableList<LogEntry> columnizedLogs; private FilteredList<LogEntry> filteredLogs; private StringProperty tailedFileName; private BooleanProperty followingTail; private BooleanProperty tailingFile; private Tailer tailer; private LogTailListener logTailListener; // to avoid garbage collection @SuppressWarnings({"FieldCanBeLocal", "unused"}) private SearchMarksController searchMarksController; @Override public void initialize(URL location, ResourceBundle resources) { config = Config.getInstance(); columnizedLogs = FXCollections.observableArrayList(); filteredLogs = new FilteredList<>(columnizedLogs); colorizer = new SimpleObjectProperty<>(); columnizer = new SimpleObjectProperty<>(); followingTail = new SimpleBooleanProperty(false); tailingFile = new SimpleBooleanProperty(false); tailedFileName = new SimpleStringProperty(); closeMenu.disableProperty().bind(tailingFile.not()); configureTitleBinding(); configureColumnizerSelector(); configureColorizerSelector(); configureFiltering(); configureSearch(); configureLogsTable(); configureRecentFilesMenu(); configureSecondaryStages(); configureAutoScroll(); } private void configureTitleBinding() { UIUtils.whenWindowReady(mainPane, window -> { Stage stage = (Stage) window; StringBinding titleBinding = createTitleBinding(tailingFile, tailedFileName); stage.titleProperty().bind(titleBinding); }); } private static StringBinding createTitleBinding(BooleanProperty appendFileName, StringProperty filename) { return Bindings.createStringBinding(() -> { String newTitle = FXLog.APP_NAME; if (appendFileName.get()) { newTitle += " - " + filename.get(); } return newTitle; }, filename, appendFileName); } /** * Binds the colorizer selector to the current colorizer property and the colorizers of the config. */ private void configureColorizerSelector() { IntegerProperty selectedIndexProp = config.getState().selectedColorizerIndexProperty(); bindSelector(colorizerSelector, config.getColorizers(), colorizer, selectedIndexProp); } /** * Binds the columnizer selector to the current columnizer property and the columnizers of the config. */ private void configureColumnizerSelector() { IntegerProperty selectedIndexProp = config.getState().selectedColumnizerIndexProperty(); bindSelector(columnizerSelector, config.getColumnizers(), columnizer, selectedIndexProp); columnizer.addListener(change -> { // re-columnizes the logs restartTailing(); }); } /** * Configures the given selector with the given {@code items}, and binds it to the given properties. * <p> * The initial values for the selector and the selectedItem are set based on {@code selectedItemIndexProperty}. * * @param selector * the selector to configure * @param items * the items to put in the selector * @param selectedItemProperty * the property to bind for the selected item * @param selectedItemIndexProperty * the property to bind for the index of the selected item * @param <T> * the type of items in the selector */ private static <T> void bindSelector(@NotNull ChoiceBox<T> selector, @NotNull ObservableList<T> items, @NotNull Property<T> selectedItemProperty, @NotNull IntegerProperty selectedItemIndexProperty) { selector.setItems(items); if (!items.isEmpty()) { int selectedIndex = selectedItemIndexProperty.get(); selectedItemProperty.setValue(items.get(selectedIndex)); selector.getSelectionModel().select(selectedIndex); } selectedItemProperty.bindBidirectional(selector.valueProperty()); selectedItemIndexProperty.bind(selector.getSelectionModel().selectedIndexProperty()); } /** * Binds the filtered logs list predicate, the current filter, and the filter text field together. */ private void configureFiltering() { Callable<Predicate<LogEntry>> createFilter = () -> { try { filterField.pseudoClassStateChanged(Css.INVALID, false); if (filterField.getText().isEmpty()) { return log -> true; } int flags = caseSensitiveFilterCheckbox.isSelected() ? 0 : Pattern.CASE_INSENSITIVE; return Filter.findInRawLog(filterField.getText(), flags); } catch (PatternSyntaxException e) { filterField.pseudoClassStateChanged(Css.INVALID, true); return log -> false; } }; Binding<Predicate<LogEntry>> filterBinding = Bindings.createObjectBinding(createFilter, filterField.textProperty(), caseSensitiveFilterCheckbox.selectedProperty()); filterField.setText(""); UIUtils.makeClearable(filterField); filteredLogs.predicateProperty().bind(filterBinding); filteredLogs.predicateProperty().addListener((obs, before, now) -> { if (followingTail.get()) { scrollToBottom(); } }); } private void configureSearch() { searchField.setText(""); UIUtils.makeClearable(searchField); searchMarksController = new SearchMarksController(config, filteredLogs, logsTable, searchField); } /** * Binds the logs table to the current colorizer, columnizer, and filtered logs list. */ private void configureLogsTable() { logsTable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); EasyBind.subscribe(columnizer, c -> { logsTable.getColumns().clear(); if (c != null) { logsTable.getColumns().addAll(getConfiguredColumns(c)); } }); logsTable.setItems(filteredLogs); } private Collection<TableColumn<LogEntry, String>> getConfiguredColumns(Columnizer columnizer) { Collection<TableColumn<LogEntry, String>> columns = columnizer.getColumns(); columns.forEach(col -> col.setCellFactory(column -> { StyledTableCell cell = new StyledTableCell(column); cell.fontProperty().bind(config.getPreferences().logsFontProperty()); cell.wrapTextProperty().bind(config.getPreferences().wrapLogsTextProperty()); cell.colorizerProperty().bind(colorizer); cell.searchTextProperty().bind(searchField.textProperty()); cell.searchHighlightStyleProperty().bind(config.getPreferences().searchHighlightStyleProperty()); return cell; })); return columns; } /** * Binds the recent files menu to the recent files in the config. */ private void configureRecentFilesMenu() { ListChangeListener<String> updateRecentFilesMenu = change -> { ObservableList<MenuItem> items = recentFilesMenu.getItems(); items.clear(); if (config.getState().getRecentFiles().isEmpty()) { MenuItem noItem = new MenuItem("No recent file"); noItem.setDisable(true); items.add(noItem); } else { config.getState().getRecentFiles().stream().map(path -> { MenuItem menuItem = new MenuItem(path); menuItem.setOnAction(event -> openRecentFile(path)); return menuItem; }).forEach(items::add); MenuItem sep = new SeparatorMenuItem(); items.add(sep); MenuItem clearItem = new MenuItem("Clear recent files"); clearItem.setOnAction(event -> config.getState().getRecentFiles().clear()); items.add(clearItem); } }; config.getState().getRecentFiles().addListener(updateRecentFilesMenu); // manual trigger the first time for initialization updateRecentFilesMenu.onChanged(null); } /** * Configures the preferences and customization stages. */ private void configureSecondaryStages() { Theme theme = config.getState().getCurrentTheme(); colorizersStage = UIUtils.createStage("popups/colorizers.fxml", "Customize Colorizers", theme); columnizersStage = UIUtils.createStage("popups/columnizers.fxml", "Customize Columnizers", theme); preferencesStage = UIUtils.createStage("popups/preferences.fxml", "Preferences", theme); aboutStage = UIUtils.createStage("popups/about.fxml", "About FX Log", theme); aboutStage.initStyle(StageStyle.UNDECORATED); aboutStage.focusedProperty().addListener((observable, wasFocused, nowFocused) -> { if (!nowFocused) { aboutStage.hide(); } }); UIUtils.whenWindowReady(mainPane, scene -> { colorizersStage.initOwner(scene); columnizersStage.initOwner(scene); preferencesStage.initOwner(scene); aboutStage.initOwner(scene); }); } private void configureAutoScroll() { followTailMenu.selectedProperty().bindBidirectional(followingTail); toggleFollowTailButton.selectedProperty().bindBidirectional(followingTail); logsTable.addEventFilter(ScrollEvent.ANY, event -> followingTail.set(false)); followingTail.addListener((obs, oldValue, newValue) -> { if (newValue) { scrollToBottom(); } else { int indexFirst = UIUtils.getFirstVisibleRowIndex(logsTable); if (indexFirst > 1 && !logsTable.getItems().isEmpty()) { logsTable.scrollTo(indexFirst - 1); } } }); logsTable.setOnKeyPressed(event -> { if (event.getCode() == KeyCode.SPACE) { followingTail.set(!followingTail.get()); } }); } private void scrollToBottom() { if (!columnizedLogs.isEmpty()) { logsTable.scrollTo(columnizedLogs.size() - 1); } } /** * Opens the custom colorizers window. */ @FXML public void editColorizers() { if (!colorizersStage.isShowing()) { colorizersStage.showAndWait(); } else { colorizersStage.toFront(); } } /** * Opens the custom columnizers window. */ @FXML public void editColumnizers() { if (!columnizersStage.isShowing()) { columnizersStage.showAndWait(); } else { columnizersStage.toFront(); } } /** * Opens the preferences window. */ @FXML public void editPreferences() { if (!preferencesStage.isShowing()) { preferencesStage.showAndWait(); } else { preferencesStage.toFront(); } } /** * Opens the about window. */ @FXML public void about() { if (!aboutStage.isShowing()) { aboutStage.showAndWait(); } else { aboutStage.toFront(); } } /** * Opens a file chooser to choose the file to tail, and starts tailing the selected file. */ @FXML public void openFile() { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Open Log File"); fileChooser.getExtensionFilters() .add(new ExtensionFilter("Log files (*.txt, *.log, *.out)", "*.txt", "*.log", "*.out")); fileChooser.getExtensionFilters().add(new ExtensionFilter("All files", "*.*")); File file = fileChooser.showOpenDialog(mainPane.getScene().getWindow()); if (file != null) { try { startTailingFile(file); } catch (FileNotFoundException e) { ErrorDialog.selectedFileNotFound(file.getPath()); } } } /** * Opens the given recent file and starts tailing it. * * @param filename * the recent file to tail */ public void openRecentFile(String filename) { try { startTailingFile(new File(filename)); } catch (FileNotFoundException e) { config.getState().removeFromRecentFiles(filename); ErrorDialog.recentFileNotFound(filename); } } /** * Starts tailing the given file, thus updating the log lines in the table. * * @param file * the file to tail * * @throws FileNotFoundException * if the file was not found */ public void startTailingFile(File file) throws FileNotFoundException { if (!file.exists()) { throw new FileNotFoundException(file.getAbsolutePath()); } closeCurrentFile(); config.getState().addToRecentFiles(file.getAbsolutePath()); logTailListener = new LogTailListener(columnizer.getValue(), columnizedLogs); logTailListener.skipEmptyLogsProperty().bind(config.getPreferences().skipEmptyLogsProperty()); logTailListener.limitNumberOfLogsProperty().bind(config.getPreferences().limitNumberOfLogsProperty()); logTailListener.maxNumberOfLogsProperty().bind(config.getPreferences().maxNumberOfLogsProperty()); tailer = Tailer.create(file, logTailListener, config.getPreferences().getTailingDelayInMillis()); tailingFile.set(true); tailedFileName.set(file.getAbsolutePath()); } /** * Closes and re-opens the file being tailed. Useful to update the columnization for instance. */ private void restartTailing() { if (!tailingFile.getValue()) { System.err.println("Can't RE-start if we're not tailing"); return; } File file = tailer.getFile(); closeCurrentFile(); try { startTailingFile(file); } catch (FileNotFoundException e) { ErrorDialog.recentFileNotFound(file.getAbsolutePath()); } } /** * Clears the current logs. */ @FXML public void clearLogs() { columnizedLogs.clear(); } /** * Closes the currently opened file. */ @FXML public void closeCurrentFile() { if (tailer != null) { logTailListener.stop(); tailer.stop(); } columnizedLogs.clear(); tailingFile.set(false); tailedFileName.set(""); } /** * Exits the application. */ @FXML public void quit() { Platform.exit(); } /** * Copy to the clipboard the raw logs corresponding to the selected lines. */ @FXML public void copyRaw() { copySelectedLogsToClipboard(LogEntry::rawLine, ""); } /** * Copy to the clipboard the tab-separated columnized logs corresponding to the selected lines. */ @FXML public void copyPretty() { List<ColumnDefinition> columnDefinitions = columnizer.getValue().getColumnDefinitions(); String headers = columnDefinitions.stream() .filter(ColumnDefinition::isVisible) .map(ColumnDefinition::getHeaderLabel) .collect(Collectors.joining("\t")); copySelectedLogsToClipboard(log -> log.toColumnizedString(columnDefinitions), headers + '\n'); } /** * Copy the selected logs to the clipboard using the given function to convert them to strings. * * @param logToLine * the function to use to convert each log into a string * @param prefix * some extra content to put before the logs */ private void copySelectedLogsToClipboard(Function<LogEntry, String> logToLine, String prefix) { String textLogs = logsTable.getSelectionModel() .getSelectedItems() .stream() .map(logToLine) .collect(Collectors.joining("\n")); ClipboardContent content = new ClipboardContent(); content.putString(prefix + textLogs); Clipboard.getSystemClipboard().setContent(content); } /** * Selects all the logs in the table. */ @FXML public void selectAll() { logsTable.getSelectionModel().selectAll(); } /** * Unselects all the logs in the table. */ @FXML public void unselectAll() { logsTable.getSelectionModel().clearSelection(); } /** * Switches to the dark theme. */ @FXML public void selectDarkTheme() { selectTheme(Theme.DARK); } /** * Switches to the bright theme. */ @FXML public void selectBrightTheme() { selectTheme(Theme.LIGHT); } private void selectTheme(Theme theme) { theme.apply(mainPane.getScene(), colorizersStage.getScene(), columnizersStage.getScene()); Config.getInstance().getState().setCurrentTheme(theme); } /** * Opens the web page containing the user manual. */ @FXML public void openUserManual() { try { Desktop.getDesktop().browse(new URI(FXLog.GITHUB_URL)); } catch (IOException | URISyntaxException e) { ErrorDialog.uncaughtException(e); } } /** * Checks for available updates of FX Log. */ @FXML public void checkForUpdates() { VersionChecker.checkForUpdates(true); } }
package org.hildan.fxlog.controllers; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.SelectionMode; import javafx.scene.control.TableRow; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.ToggleButton; import javafx.scene.input.Clipboard; import javafx.scene.input.ClipboardContent; import javafx.scene.layout.BorderPane; import javafx.stage.FileChooser; import javafx.stage.FileChooser.ExtensionFilter; import org.hildan.fxlog.coloring.Colorizer; import org.hildan.fxlog.columns.Columnizer; import org.hildan.fxlog.core.LogEntry; import org.hildan.fxlog.filtering.RawFilter; import java.io.File; import java.io.IOException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ResourceBundle; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; public class MainController implements Initializable { @FXML private BorderPane mainPane; @FXML private TableView<LogEntry> logsTable; @FXML private ToggleButton autoScrollToggleButton; @FXML private TextField filterField; private Columnizer columnizer; private Predicate<LogEntry> filter; private Colorizer colorizer; private Path currentFilePath; @Override public void initialize(URL location, ResourceBundle resources) { // TODO make it customizable columnizer = Columnizer.WEBLOGIC; colorizer = Colorizer.WEBLOGIC; configureLogsTable(); refreshFilter(); refreshLogsTable(); } private void configureLogsTable() { logsTable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); logsTable.getColumns().addAll(columnizer.getColumns()); } private void refreshFilter() { String filterText = filterField.getText(); if (!filterText.isEmpty()) { filter = new RawFilter(".*?" + filterText + ".*"); } else { filter = log -> true; } } private void refreshLogsTable() { logsTable.getItems().clear(); if (currentFilePath == null) { return; } try (Stream<String> lines = Files.lines(currentFilePath)) { lines.map(columnizer::parse).filter(filter).forEach(logsTable.getItems()::add); } catch (IOException e) { System.err.println("Error while reading the file " + currentFilePath); } logsTable.setRowFactory(table -> { final TableRow<LogEntry> row = new TableRow<LogEntry>() { @Override protected void updateItem(LogEntry log, boolean empty) { super.updateItem(log, empty); if (log != null && !empty) { System.out.println("coloring!"); colorizer.setStyle(this, log); } else { System.out.println("empty again"); } } }; return row; }); } public void openFile(@SuppressWarnings("unused") ActionEvent event) { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Open Log File"); fileChooser.getExtensionFilters().add(new ExtensionFilter("Log files (*.txt, *.log)", "*.txt", "*.log")); fileChooser.getExtensionFilters().add(new ExtensionFilter("Other files", "*.*")); File file = fileChooser.showOpenDialog(mainPane.getScene().getWindow()); if (file != null) { // a file has indeed been chosen currentFilePath = Paths.get(file.toURI()); refreshLogsTable(); } } public void closeFile(@SuppressWarnings("unused") ActionEvent event) { if (currentFilePath != null) { currentFilePath = null; refreshLogsTable(); } } public void openPreferences(@SuppressWarnings("unused") ActionEvent event) { // TODO handle preferences } public void quit(@SuppressWarnings("unused") ActionEvent event) { Platform.exit(); } public void copyRaw(@SuppressWarnings("unused") ActionEvent event) { copySelectedLogsToClipboard(LogEntry::getInitialLog); } public void copyPretty(@SuppressWarnings("unused") ActionEvent event) { copySelectedLogsToClipboard(LogEntry::toColumnizedString); } private void copySelectedLogsToClipboard(Function<LogEntry, String> logToLine) { String textLogs = logsTable.getSelectionModel() .getSelectedItems() .stream() .map(logToLine) .collect(Collectors.joining(String.format("%n"))); ClipboardContent content = new ClipboardContent(); content.putString(textLogs); Clipboard.getSystemClipboard().setContent(content); } public void selectAll(@SuppressWarnings("unused") ActionEvent event) { logsTable.getSelectionModel().selectAll(); } public void unselectAll(@SuppressWarnings("unused") ActionEvent event) { logsTable.getSelectionModel().clearSelection(); } public void toggleAutoscroll(@SuppressWarnings("unused") ActionEvent event) { // TODO handle auto-scroll } public void filterLogs(@SuppressWarnings("unused") ActionEvent event) { refreshFilter(); refreshLogsTable(); } }
package org.javarosa.xpath.expr; import org.javarosa.core.model.instance.FormInstance; import org.javarosa.core.services.InFormExpressionCacher; import org.javarosa.xpath.XPathNodeset; import org.javarosa.xpath.analysis.AnalysisInvalidException; import org.javarosa.xpath.analysis.ContainsUncacheableExpressionAnalyzer; import org.javarosa.xpath.analysis.ReferencesMainInstanceAnalyzer; import org.javarosa.xpath.analysis.XPathAnalyzable; public abstract class InFormCacheableExpr implements XPathAnalyzable { private Object justRetrieved; protected boolean isCached() { queueUpCachedValue(); return justRetrieved != null; } private void queueUpCachedValue() { if (environmentValidForCaching()) { justRetrieved = cacher.getCachedValue(this); } else { justRetrieved = null; } } Object getCachedValue() { System.out.println("Returning cached value for expression: " + ((XPathExpression)this).toPrettyString()); return justRetrieved; } void cache(Object value) { if (expressionIsCacheable(value)) { cacher.cache(this, value); } } protected boolean expressionIsCacheable(Object result) { if (environmentValidForCaching()) { try { boolean b = !referencesMainFormInstance() && !containsUncacheableSubExpression(); System.out.println("is cacheable: " + b + " " + ((XPathExpression)this).toPrettyString()); return b; } catch (AnalysisInvalidException e) { // if the analysis didn't complete then we assume it's not cacheable } } return false; } private boolean referencesMainFormInstance() throws AnalysisInvalidException { return (new ReferencesMainInstanceAnalyzer(cacher.getFormInstanceRoot())) .computeResult(this); } private boolean containsUncacheableSubExpression() throws AnalysisInvalidException { return (new ContainsUncacheableExpressionAnalyzer()).computeResult(this); } private boolean environmentValidForCaching() { return cacher.getFormInstanceRoot() != null; } private static InFormExpressionCacher cacher = new InFormExpressionCacher(); public static void enableCaching(FormInstance formInstance, boolean clearCacheFirst) { if (clearCacheFirst) { cacher.wipeCache(); } cacher.setFormInstanceRoot(formInstance.getBase().getChildAt(0).getName()); } public static void disableCaching() { cacher.setFormInstanceRoot(null); } }
package org.jboss.as.jpa.ejb3; import org.jboss.as.ejb3.component.stateful.StatefulSessionComponentInstance; import org.jboss.as.jpa.spi.SFSBContextHandle; import java.io.Serializable; /** * Implementation of SFSBContextHandle that represents an EJB3 SFSB * * @author Scott Marlow */ public class SFSBContextHandleImpl implements SFSBContextHandle { private Serializable idSFSB; public SFSBContextHandleImpl(StatefulSessionComponentInstance sfsb) { this.idSFSB = sfsb.getId(); } @Override public Object getBeanContextHandle() { return idSFSB; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SFSBContextHandleImpl that = (SFSBContextHandleImpl) o; if (idSFSB != null ? !idSFSB.equals(that.idSFSB) : that.idSFSB != null) return false; return true; } @Override public int hashCode() { return idSFSB != null ? idSFSB.hashCode() : 0; } }
package org.jboss.loom.recog.as5; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Path; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.filefilter.FileFilterUtils; import org.apache.commons.io.filefilter.IOFileFilter; import org.jboss.loom.ex.MigrationException; import org.jboss.loom.recog.AsToEapMap; import org.jboss.loom.recog.HasHashes; import org.jboss.loom.recog.IServerType; import org.jboss.loom.recog.Version; import org.jboss.loom.recog.VersionRange; import org.jboss.loom.utils.compar.ComparisonResult; import org.jboss.loom.utils.compar.FileHashComparer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author Ondrej Zizka, ozizka at redhat.com */ public class JBossAS5ServerType implements IServerType, HasHashes { private static final Logger log = LoggerFactory.getLogger( JBossAS5ServerType.class ); @Override public String getDescription() { return "JBoss AS 5.x or 6.x, or JBoss EAP 5.x"; } private static final String JAR_VERSIONS_XML = "jar-versions.xml"; private static final String HASH_FILES_PATH = "/fileHashes/as5/"; /** * First checks jar-versions.xml. If that's not present, then compares checksums of all jars. * @param homeDir * @return */ @Override public VersionRange recognizeVersion( File homeDir ) { if( ! isPresentInDir( homeDir ) ) return new VersionRange(); // Check jar-versions.xml. File jvx = new File( homeDir, JAR_VERSIONS_XML ); try { // Check if we know that file's CRC32; if so, use that version. long jarVerCrc = FileHashComparer.computeCrc32(jvx); String ver = getJarVersionsXmlCrcToVersionsMap().get( jarVerCrc ); if( ver != null ) return VersionRange.forProduct( ver, ver, new AsToEapMap() ); } catch ( IOException ex ){ log.error("Failed computing CRC32 of " + jvx.getPath() + ": " + ex.getMessage(), ex); } // No match - check .jars. IOFileFilter filter = FileFilterUtils.suffixFileFilter(".jar"); int minMismatches = Integer.MAX_VALUE; HashFile minMisHF = null; // Compare the directory against each hash file. for( HashFile hashFile : getHashFiles()) { try { InputStream is = this.getClass().getResourceAsStream( HASH_FILES_PATH + hashFile.fName ); ComparisonResult result = FileHashComparer.compareHashesAndDir( is, homeDir, filter ); log.debug(" Comparison of .jar's in %s against %s: %d of %d match.", homeDir.getPath(), hashFile.fName, result.getCountMatches(), result.getCountTotal() ); int curMismatches = result.getCountMismatches(); if( curMismatches < minMismatches){ minMisHF = hashFile; minMismatches = curMismatches; } } catch( IOException ex ) { throw new RuntimeException("Failed comparing dir " + homeDir.getPath() + " against hashfile " + hashFile.fName + ": " + ex.getMessage(), ex); } } // If there's some almost certain match, return that as recognized version. if( minMisHF != null ) return VersionRange.forProduct( minMisHF.version, minMisHF.version, new AsToEapMap() ); // Default range - all we know - AS 5 to AS 6. return new VersionRange( "5.0.0", "6" ); } @Override public boolean isPresentInDir( File homeDir ) { if( ! new File(homeDir, JAR_VERSIONS_XML).exists() ) return false; if( ! new File(homeDir, "bin/run.sh").exists() ) return false; if( ! new File(homeDir, "lib/jboss-main.jar").exists() ) return false; return true; } // Hash files. private static List<HashFile> getHashFiles(){ return HASH_FILES; } private static final List<HashFile> HASH_FILES = Arrays.asList( new HashFile( "jboss-eap-5.0.0-crc32.txt", "5.0.0"), new HashFile( "jboss-eap-5.0.0-unsigned-crc32.txt", "5.0.0"), new HashFile( "jboss-eap-5.0.1-crc32.txt", "5.0.1"), new HashFile( "jboss-eap-5.1.0-crc32.txt", "5.1.0"), new HashFile( "jboss-eap-5.1.0-unsigned-crc32.txt", "5.1.0"), new HashFile( "jboss-eap-5.1.1-crc32.txt", "5.1.1"), new HashFile( "jboss-eap-5.1.1-unsigned-crc32.txt", "5.1.1"), new HashFile( "jboss-eap-5.1.2-crc32.txt", "5.1.2"), new HashFile( "jboss-eap-5.2.0-crc32.txt", "5.2.0") ); private InputStream getHashFileForVersion( String ver ){ for( HashFile hashFile : HASH_FILES ) { if( hashFile.version.equals(ver) ){ String path = HASH_FILES_PATH + hashFile.fName; InputStream is = this.getClass().getResourceAsStream(path); if( is != null ) return is; throw new IllegalStateException("Hash file not found on classpath: " + path); } } return null; } // jar-versions.xml CRC32 -> versions. private static Map<Long, String> getJarVersionsXmlCrcToVersionsMap(){ return JAR_VERSIONS_XML_CRC_TO_VERSION_MAP; } private static final Map<Long, String> JAR_VERSIONS_XML_CRC_TO_VERSION_MAP = new HashMap(); static { Map<Long, String> map = JAR_VERSIONS_XML_CRC_TO_VERSION_MAP; map.put( 0x9f12a476L, "5.0.0"); map.put( 0x9e98373eL, "5.0.1"); map.put( 0x2b9c02cbL, "5.1.0"); map.put( 0x52e957e7L, "5.1.1"); map.put( 0x10c95871L, "5.1.2"); map.put( 0xb7414c39L, "5.2.0"); } @Override public ComparisonResult compareHashes( Version version, File serverRootDir ) throws MigrationException { if( version.verProduct == null ) throw new MigrationException("Comparing file hashes is only supported for EAP, not AS. Supplied version was: " + version.verProject); InputStream hashFile = getHashFileForVersion(version.verProduct); if( null == hashFile ) throw new MigrationException("No hash files for EAP version: " + version.verProduct); try { return FileHashComparer.compareHashesAndDir( hashFile, serverRootDir, null ); } catch( Exception ex ) { String msg = String.format("Failed comparing hashes of %s against dir %s:%n ", this.format(version), serverRootDir); throw new MigrationException( msg + ex.getMessage(), ex); } } /** * Formats a string like "JBoss AS 5.1.0" or "JBoss EAP 5.2.0+" etc. */ @Override public String format( VersionRange versionRange ) { StringBuilder sb = new StringBuilder("JBoss "); // Version unknown if( versionRange == null ) return sb.append("AS or EAP 5").toString(); // AS or EAP? sb.append( versionRange.from.verProduct == null ? "AS " : "EAP "); sb.append( versionRange.from.toString_preferProduct() ); // Range? if( versionRange.isExactVersion() ) return sb.toString(); sb.append(" - ").append( versionRange.getTo_preferProduct() ); return sb.toString(); } public String format( Version version ) { StringBuilder sb = new StringBuilder("JBoss "); // Version unknown if( version == null ) return sb.append("AS or EAP 5").toString(); // AS or EAP? sb.append( version.verProduct == null ? "AS " + version.verProject : "EAP " + version.verProduct); return sb.toString(); } static class HashFile { public String fName; public String version; public HashFile( String fName, String version ) { this.fName = fName; this.version = version; } } static class HashFileMatch{ public HashFile hashFile; public Map<Path, FileHashComparer.MatchResult> matches; } }// class
package org.jboss.msc.service; import static java.lang.Thread.holdsLock; import static org.jboss.msc.service.SecurityUtils.getCL; import static org.jboss.msc.service.SecurityUtils.setTCCL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.concurrent.Executor; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.jboss.msc.service.management.ServiceStatus; import org.jboss.msc.value.Value; /** * The service controller implementation. * * @param <S> the service type * * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> * @author <a href="mailto:flavia.rainone@jboss.com">Flavia Rainone</a> * @author <a href="mailto:ropalka@redhat.com">Richard Opalka</a> */ final class ServiceControllerImpl<S> implements ServiceController<S>, Dependent { private static final String ILLEGAL_CONTROLLER_STATE = "Illegal controller state"; private static final int DEPENDENCY_AVAILABLE_TASK = 1; private static final int DEPENDENCY_UNAVAILABLE_TASK = 1 << 1; private static final int DEPENDENCY_STARTED_TASK = 1 << 2; private static final int DEPENDENCY_STOPPED_TASK = 1 << 3; private static final int DEPENDENCY_FAILED_TASK = 1 << 4; private static final int DEPENDENCY_RETRYING_TASK = 1 << 5; /** * The service itself. */ private final Value<? extends Service<S>> serviceValue; /** * The dependencies of this service. */ private final Dependency[] dependencies; /** * The injections of this service. */ private final ValueInjection<?>[] injections; /** * The out injections of this service. */ private final ValueInjection<?>[] outInjections; /** * The set of registered service listeners. */ private final IdentityHashSet<ServiceListener<? super S>> listeners; /** * Lifecycle listeners. */ private final IdentityHashSet<LifecycleListener> lifecycleListeners; /** * Container shutdown listener. */ private ContainerShutdownListener shutdownListener; /** * The set of registered stability monitors. */ private final IdentityHashSet<StabilityMonitor> monitors; /** * The primary registration of this service. */ private final ServiceRegistrationImpl primaryRegistration; /** * The alias registrations of this service. */ private final ServiceRegistrationImpl[] aliasRegistrations; /** * The parent of this service. */ private final ServiceControllerImpl<?> parent; /** * The children of this service (only valid during {@link State#UP}). */ private final IdentityHashSet<ServiceControllerImpl<?>> children; /** * The unavailable dependencies of this service. */ private final IdentityHashSet<ServiceName> unavailableDependencies; /** * The start exception. */ private StartException startException; /** * The controller mode. */ private ServiceController.Mode mode = ServiceController.Mode.NEVER; /** * The controller state. */ private Substate state = Substate.NEW; /** * Tracks which dependent tasks have completed its execution. * First 16 bits track if dependent task have been scheduled. * Second 16 bits track whether scheduled dependent task finished its execution. */ private int execFlags; /** * The number of registrations which place a demand-to-start on this * instance. If this value is >0, propagate a demand up to all parent * dependents. If this value is >0 and mode is ON_DEMAND, we should start. */ private int demandedByCount; /** * Count for dependencies that are trying to stop. If this count is greater than zero then * dependents will be notified that a stop is necessary. */ private int stoppingDependencies; /** * The number of dependents that are currently running. The deployment will * not execute the {@code stop()} method (and subsequently leave the * {@link org.jboss.msc.service.ServiceController.State#STOPPING} state) * until all running dependents (and listeners) are stopped. */ private int runningDependents; /** * Count for failure notification. It indicates how many services have * failed to start and are not recovered so far. This count monitors * failures that happen when starting this service, and dependency related * failures as well. When incremented from 0 to 1, it is time to notify * dependents and listeners that a failure occurred. When decremented from 1 * to 0, the dependents and listeners are notified that the affected * services are retrying to start. Values larger than 1 are ignored to avoid * multiple notifications. */ private int failCount; /** * Indicates whether dependencies have been demanded. */ private boolean dependenciesDemanded = false; /** * The number of asynchronous tasks that are currently running. This * includes listeners, start/stop methods, outstanding asynchronous * start/stops, and internal tasks. */ private int asyncTasks; /** * Tasks executed last on transition outside the lock. */ private final List<Runnable> listenerTransitionTasks = new ArrayList<Runnable>(); /** * The service target for adding child services (can be {@code null} if none * were added). */ private volatile ChildServiceTarget childTarget; /** * The system nanotime of the moment in which the last lifecycle change was * initiated. */ @SuppressWarnings("VolatileLongOrDoubleField") private volatile long lifecycleTime; private static final String[] NO_STRINGS = new String[0]; static final int MAX_DEPENDENCIES = (1 << 14) - 1; ServiceControllerImpl(final Value<? extends Service<S>> serviceValue, final Dependency[] dependencies, final ValueInjection<?>[] injections, final ValueInjection<?>[] outInjections, final ServiceRegistrationImpl primaryRegistration, final ServiceRegistrationImpl[] aliasRegistrations, final Set<StabilityMonitor> monitors, final Set<? extends ServiceListener<? super S>> listeners, final Set<LifecycleListener> lifecycleListeners, final ServiceControllerImpl<?> parent) { assert dependencies.length <= MAX_DEPENDENCIES; this.serviceValue = serviceValue; this.dependencies = dependencies; this.injections = injections; this.outInjections = outInjections; this.primaryRegistration = primaryRegistration; this.aliasRegistrations = aliasRegistrations; this.listeners = new IdentityHashSet<ServiceListener<? super S>>(listeners); this.lifecycleListeners = new IdentityHashSet<LifecycleListener>(lifecycleListeners); this.monitors = new IdentityHashSet<StabilityMonitor>(monitors); // We also need to register this controller with monitors explicitly. // This allows inherited monitors to have registered all child controllers // and later to remove them when inherited stability monitor is cleared. for (final StabilityMonitor monitor : monitors) { monitor.addControllerNoCallback(this); } this.parent = parent; int depCount = dependencies.length; stoppingDependencies = parent == null ? depCount : depCount + 1; children = new IdentityHashSet<ServiceControllerImpl<?>>(); unavailableDependencies = new IdentityHashSet<ServiceName>(); } Substate getSubstateLocked() { return state; } /** * Set this instance into primary and alias registrations. * <p></p> * All notifications from registrations will be ignored until the * installation is {@link #commitInstallation(org.jboss.msc.service.ServiceController.Mode) committed}. */ void startInstallation() { Lockable lock = primaryRegistration.getLock(); synchronized (lock) { lock.acquireWrite(); try { primaryRegistration.setInstance(this); } finally { lock.releaseWrite(); } } for (ServiceRegistrationImpl aliasRegistration: aliasRegistrations) { lock = aliasRegistration.getLock(); synchronized (lock) { lock.acquireWrite(); try { aliasRegistration.setInstance(this); } finally { lock.releaseWrite(); } } } } /** * Start this service configuration connecting it to its parent and dependencies. * <p></p> * All notifications from dependencies and parents will be ignored until the * installation is {@link #commitInstallation(org.jboss.msc.service.ServiceController.Mode) committed}. */ void startConfiguration() { Lockable lock; for (Dependency dependency : dependencies) { lock = dependency.getLock(); synchronized (lock) { lock.acquireWrite(); try { dependency.addDependent(this); } finally { lock.releaseWrite(); } } } if (parent != null) { lock = parent.primaryRegistration.getLock(); synchronized (lock) { lock.acquireWrite(); try { parent.addChild(this); } finally { lock.releaseWrite(); } } } } /** * Commit the service install, kicking off the mode set and listener execution. * * @param initialMode the initial service mode */ void commitInstallation(Mode initialMode) { assert (state == Substate.NEW); assert initialMode != null; assert !holdsLock(this); final List<Runnable> listenerAddedTasks = new ArrayList<Runnable>(); synchronized (this) { if (getServiceContainer().isShutdown()) { throw new IllegalStateException ("Container is down"); } final boolean leavingRestState = isStableRestState(); getListenerTasks(ListenerNotification.LISTENER_ADDED, listenerAddedTasks); internalSetMode(initialMode); // placeholder async task for running listener added tasks addAsyncTasks(listenerAddedTasks.size() + 1); updateStabilityState(leavingRestState); } for (Runnable listenerAddedTask : listenerAddedTasks) { listenerAddedTask.run(); } final List<Runnable> tasks; synchronized (this) { if (getServiceContainer().isShutdown()) { throw new IllegalStateException ("Container is down"); } final boolean leavingRestState = isStableRestState(); // subtract one to compensate for +1 above decrementAsyncTasks(); tasks = transition(); addAsyncTasks(tasks.size()); updateStabilityState(leavingRestState); } doExecute(tasks); } /** * Roll back the service install. */ void rollbackInstallation() { final Runnable removeTask; synchronized (this) { final boolean leavingRestState = isStableRestState(); mode = Mode.REMOVE; state = Substate.CANCELLED; removeTask = new RemoveTask(); incrementAsyncTasks(); updateStabilityState(leavingRestState); } removeTask.run(); } /** * Return {@code true} only if this service controller installation is committed. * * @return true if this service controller installation is committed */ boolean isInstallationCommitted() { assert holdsLock(this); // should not be NEW nor CANCELLED return state.compareTo(Substate.CANCELLED) > 0; } /** * Controller notifications are ignored (we do not create new tasks on notification) if * either controller didn't finish its installation process or controller have been removed. * * @return true if notification must be ignored, false otherwise */ private boolean ignoreNotification() { assert holdsLock(this); return state.compareTo(Substate.REMOVING) >= 0 || state.compareTo(Substate.CANCELLED) <= 0; } /** * Determine whether a stopped controller should start. * * @return {@code true} if so */ private boolean shouldStart() { assert holdsLock(this); return mode == Mode.ACTIVE || mode == Mode.PASSIVE || demandedByCount > 0 && (mode == Mode.ON_DEMAND || mode == Mode.LAZY); } /** * Determine whether a running controller should stop. * * @return {@code true} if so */ private boolean shouldStop() { assert holdsLock(this); return mode == Mode.REMOVE || demandedByCount == 0 && mode == Mode.ON_DEMAND || mode == Mode.NEVER; } /** * Returns true if controller is in rest state and no async tasks are running, false otherwise. * @return true if stable rest state, false otherwise */ private boolean isStableRestState() { assert holdsLock(this); return asyncTasks == 0 && state.isRestState(); } private void updateStabilityState(final boolean leavingStableRestState) { assert holdsLock(this); final boolean enteringStableRestState = state.isRestState() && asyncTasks == 0; if (leavingStableRestState) { if (!enteringStableRestState) { primaryRegistration.getContainer().incrementUnstableServices(); for (StabilityMonitor monitor : monitors) { monitor.incrementUnstableServices(); } } } else { if (enteringStableRestState) { primaryRegistration.getContainer().decrementUnstableServices(); for (StabilityMonitor monitor : monitors) { monitor.decrementUnstableServices(); } if (shutdownListener != null && state == Substate.REMOVED) { shutdownListener.controllerDied(); } } } } /** * Identify the transition to take. Call under lock. * * @return the transition or {@code null} if none is needed at this time */ private Transition getTransition() { assert holdsLock(this); switch (state) { case NEW: { if (!getServiceContainer().isShutdown()) { return Transition.NEW_to_DOWN; } break; } case DOWN: { if (mode == ServiceController.Mode.REMOVE) { return Transition.DOWN_to_REMOVING; } else if (mode == ServiceController.Mode.NEVER) { return Transition.DOWN_to_WONT_START; } else if (shouldStart() && (mode != Mode.PASSIVE || stoppingDependencies == 0)) { return Transition.DOWN_to_START_REQUESTED; } else { // mode is either LAZY or ON_DEMAND with demandedByCount == 0, or mode is PASSIVE and downDep > 0 return Transition.DOWN_to_WAITING; } } case WAITING: { if (((mode != Mode.ON_DEMAND && mode != Mode.LAZY) || demandedByCount > 0) && (mode != Mode.PASSIVE || stoppingDependencies == 0)) { return Transition.WAITING_to_DOWN; } break; } case WONT_START: { if (mode != ServiceController.Mode.NEVER){ return Transition.WONT_START_to_DOWN; } break; } case STOPPING: { if (children.isEmpty()) { return Transition.STOPPING_to_DOWN; } break; } case STOP_REQUESTED: { if (shouldStart() && stoppingDependencies == 0) { return Transition.STOP_REQUESTED_to_UP; } else if (runningDependents == 0) { return Transition.STOP_REQUESTED_to_STOPPING; } break; } case UP: { if (shouldStop() || stoppingDependencies > 0) { return Transition.UP_to_STOP_REQUESTED; } break; } case START_FAILED: { if (children.isEmpty()) { if (shouldStart() && stoppingDependencies == 0) { if (startException == null) { return Transition.START_FAILED_to_STARTING; } } else if (runningDependents == 0) { return Transition.START_FAILED_to_DOWN; } } break; } case START_INITIATING: { if (shouldStart() && runningDependents == 0 && stoppingDependencies == 0 && failCount == 0) { return Transition.START_INITIATING_to_STARTING; } else { // it is possible runningDependents > 0 if this service is optional dependency to some other service return Transition.START_INITIATING_to_START_REQUESTED; } } case STARTING: { if (startException == null) { return Transition.STARTING_to_UP; } else { return Transition.STARTING_to_START_FAILED; } } case START_REQUESTED: { if (shouldStart()) { if (mode == Mode.PASSIVE && stoppingDependencies > 0) { return Transition.START_REQUESTED_to_DOWN; } if (!unavailableDependencies.isEmpty() || failCount > 0) { return Transition.START_REQUESTED_to_PROBLEM; } if (stoppingDependencies == 0 && runningDependents == 0) { // it is possible runningDependents > 0 if this service is optional dependency to some other service return Transition.START_REQUESTED_to_START_INITIATING; } } else { return Transition.START_REQUESTED_to_DOWN; } break; } case PROBLEM: { if (! shouldStart() || (unavailableDependencies.isEmpty() && failCount == 0) || mode == Mode.PASSIVE) { return Transition.PROBLEM_to_START_REQUESTED; } break; } case REMOVING: { return Transition.REMOVING_to_REMOVED; } case CANCELLED: { return Transition.CANCELLED_to_REMOVED; } case REMOVED: { // no possible actions break; } } return null; } private boolean postTransitionTasks(final List<Runnable> tasks) { assert holdsLock(this); // Listener transition tasks are executed last for ongoing transition and outside of intrinsic lock if (listenerTransitionTasks.size() > 0) { tasks.addAll(listenerTransitionTasks); listenerTransitionTasks.clear(); return true; } return false; } /** * Run the locked portion of a transition. Call under the lock. * * @return returns list of async tasks to execute */ private List<Runnable> transition() { assert holdsLock(this); if (asyncTasks != 0) { // no movement possible return Collections.EMPTY_LIST; } final List<Runnable> tasks = new ArrayList<Runnable>(); if (postTransitionTasks(tasks)) { // no movement possible return tasks; } // clean up tasks execution flags execFlags = 0; Transition transition; do { // first of all, check if dependencies & parent should be un/demanded switch (mode) { case NEVER: case REMOVE: if (dependenciesDemanded) { tasks.add(new UndemandDependenciesTask()); dependenciesDemanded = false; } break; case LAZY: { if (state == Substate.UP) { if (!dependenciesDemanded) { tasks.add(new DemandDependenciesTask()); dependenciesDemanded = true; } break; } // fall thru! } case ON_DEMAND: case PASSIVE: { if (demandedByCount > 0 && !dependenciesDemanded) { tasks.add(new DemandDependenciesTask()); dependenciesDemanded = true; } else if (demandedByCount == 0 && dependenciesDemanded) { tasks.add(new UndemandDependenciesTask()); dependenciesDemanded = false; } break; } case ACTIVE: { if (!dependenciesDemanded) { tasks.add(new DemandDependenciesTask()); dependenciesDemanded = true; } break; } } transition = getTransition(); if (transition == null) { return tasks; } getListenerTasks(transition, listenerTransitionTasks); switch (transition) { case NEW_to_DOWN: { getListenerTasks(LifecycleEvent.DOWN, listenerTransitionTasks); tasks.add(new DependencyAvailableTask()); break; } case DOWN_to_WAITING: { tasks.add(new DependencyUnavailableTask()); break; } case WAITING_to_DOWN: { tasks.add(new DependencyAvailableTask()); break; } case DOWN_to_WONT_START: { tasks.add(new DependencyUnavailableTask()); break; } case WONT_START_to_DOWN: { tasks.add(new DependencyAvailableTask()); break; } case STOPPING_to_DOWN: { getListenerTasks(LifecycleEvent.DOWN, listenerTransitionTasks); tasks.add(new DependentStoppedTask()); break; } case START_REQUESTED_to_DOWN: { break; } case START_REQUESTED_to_START_INITIATING: { lifecycleTime = System.nanoTime(); tasks.add(new DependentStartedTask()); break; } case START_REQUESTED_to_PROBLEM: { tasks.add(new DependencyUnavailableTask()); getPrimaryRegistration().getContainer().addProblem(this); for (StabilityMonitor monitor : monitors) { monitor.addProblem(this); } break; } case UP_to_STOP_REQUESTED: { lifecycleTime = System.nanoTime(); if (mode == Mode.LAZY && demandedByCount == 0) { assert dependenciesDemanded; tasks.add(new UndemandDependenciesTask()); dependenciesDemanded = false; } tasks.add(new DependencyStoppedTask()); break; } case STARTING_to_UP: { getListenerTasks(LifecycleEvent.UP, listenerTransitionTasks); tasks.add(new DependencyStartedTask()); break; } case STARTING_to_START_FAILED: { getListenerTasks(LifecycleEvent.FAILED, listenerTransitionTasks); getPrimaryRegistration().getContainer().addFailed(this); for (StabilityMonitor monitor : monitors) { monitor.addFailed(this); } ChildServiceTarget childTarget = this.childTarget; if (childTarget != null) { childTarget.valid = false; this.childTarget = null; } tasks.add(new DependencyFailedTask()); tasks.add(new RemoveChildrenTask()); tasks.add(new StopTask(false)); break; } case START_FAILED_to_STARTING: { getPrimaryRegistration().getContainer().removeFailed(this); for (StabilityMonitor monitor : monitors) { monitor.removeFailed(this); } tasks.add(new DependencyRetryingTask()); tasks.add(new StartTask()); break; } case START_INITIATING_to_STARTING: { tasks.add(new StartTask()); break; } case START_INITIATING_to_START_REQUESTED: { tasks.add(new DependentStoppedTask()); break; } case START_FAILED_to_DOWN: { getListenerTasks(LifecycleEvent.DOWN, listenerTransitionTasks); getPrimaryRegistration().getContainer().removeFailed(this); for (StabilityMonitor monitor : monitors) { monitor.removeFailed(this); } startException = null; tasks.add(new DependencyRetryingTask()); tasks.add(new DependentStoppedTask()); break; } case STOP_REQUESTED_to_UP: { tasks.add(new DependencyStartedTask()); break; } case STOP_REQUESTED_to_STOPPING: { ChildServiceTarget childTarget = this.childTarget; if (childTarget != null) { childTarget.valid = false; this.childTarget = null; } tasks.add(new StopTask(true)); tasks.add(new RemoveChildrenTask()); break; } case DOWN_to_REMOVING: { tasks.add(new DependencyUnavailableTask()); break; } case CANCELLED_to_REMOVED: getListenerTasks(LifecycleEvent.REMOVED, listenerTransitionTasks); for (StabilityMonitor monitor : monitors) { monitor.removeControllerNoCallback(this); } listeners.clear(); lifecycleListeners.clear(); break; case REMOVING_to_REMOVED: { getListenerTasks(LifecycleEvent.REMOVED, listenerTransitionTasks); tasks.add(new RemoveTask()); for (StabilityMonitor monitor : monitors) { monitor.removeControllerNoCallback(this); } listeners.clear(); lifecycleListeners.clear(); break; } case DOWN_to_START_REQUESTED: { break; } case PROBLEM_to_START_REQUESTED: { tasks.add(new DependencyAvailableTask()); getPrimaryRegistration().getContainer().removeProblem(this); for (StabilityMonitor monitor : monitors) { monitor.removeProblem(this); } break; } default: { throw new IllegalStateException(); } } state = transition.getAfter(); } while (tasks.isEmpty() && listenerTransitionTasks.isEmpty()); // Notify waiters that a transition occurred notifyAll(); if (tasks.size() > 0) { // Postponing listener transition tasks } else { postTransitionTasks(tasks); } return tasks; } private void getListenerTasks(final Transition transition, final List<Runnable> tasks) { for (ServiceListener<? super S> listener : listeners) { tasks.add(new ListenerTask(listener, transition)); } } private void getListenerTasks(final ListenerNotification notification, final List<Runnable> tasks) { for (ServiceListener<? super S> listener : listeners) { tasks.add(new ListenerTask(listener, notification)); } } private void getListenerTasks(final LifecycleEvent event, final List<Runnable> tasks) { for (LifecycleListener listener : lifecycleListeners) { tasks.add(new LifecycleListenerTask(listener, event)); } } void doExecute(final List<Runnable> tasks) { assert !holdsLock(this); if (tasks.isEmpty()) return; final Executor executor = primaryRegistration.getContainer().getExecutor(); for (Runnable task : tasks) { try { executor.execute(task); } catch (RejectedExecutionException e) { task.run(); } } } public void setMode(final ServiceController.Mode newMode) { internalSetMode(null, newMode); } private boolean internalSetMode(final ServiceController.Mode expectedMode, final ServiceController.Mode newMode) { assert !holdsLock(this); if (newMode == null) { throw new IllegalArgumentException("newMode is null"); } if (newMode != Mode.REMOVE && primaryRegistration.getContainer().isShutdown()) { throw new IllegalArgumentException("Container is shutting down"); } final List<Runnable> tasks; synchronized (this) { final boolean leavingRestState = isStableRestState(); final Mode oldMode = mode; if (expectedMode != null && expectedMode != oldMode) { return false; } if (oldMode == newMode) { return true; } internalSetMode(newMode); tasks = transition(); addAsyncTasks(tasks.size()); updateStabilityState(leavingRestState); } doExecute(tasks); return true; } private void internalSetMode(final Mode newMode) { assert holdsLock(this); final ServiceController.Mode oldMode = mode; if (oldMode == Mode.REMOVE) { if (state.compareTo(Substate.REMOVING) >= 0) { throw new IllegalStateException("Service already removed"); } } mode = newMode; } @Override public void dependencyAvailable(final ServiceName dependencyName) { final List<Runnable> tasks; synchronized (this) { final boolean leavingRestState = isStableRestState(); assert unavailableDependencies.contains(dependencyName); unavailableDependencies.remove(dependencyName); if (ignoreNotification() || !unavailableDependencies.isEmpty()) return; // we dropped it to 0 tasks = transition(); addAsyncTasks(tasks.size()); updateStabilityState(leavingRestState); } doExecute(tasks); } @Override public void dependencyUnavailable(final ServiceName dependencyName) { final List<Runnable> tasks; synchronized (this) { final boolean leavingRestState = isStableRestState(); assert !unavailableDependencies.contains(dependencyName); unavailableDependencies.add(dependencyName); if (ignoreNotification() || unavailableDependencies.size() != 1) return; // we raised it to 1 tasks = transition(); addAsyncTasks(tasks.size()); updateStabilityState(leavingRestState); } doExecute(tasks); } /** {@inheritDoc} */ public ServiceControllerImpl<?> getDependentController() { return this; } @Override public void dependencyUp() { final List<Runnable> tasks; synchronized (this) { final boolean leavingRestState = isStableRestState(); assert stoppingDependencies > 0; --stoppingDependencies; if (ignoreNotification() || stoppingDependencies != 0) return; // we dropped it to 0 tasks = transition(); addAsyncTasks(tasks.size()); updateStabilityState(leavingRestState); } doExecute(tasks); } @Override public void dependencyDown() { final List<Runnable> tasks; synchronized (this) { final boolean leavingRestState = isStableRestState(); ++stoppingDependencies; if (ignoreNotification() || stoppingDependencies != 1) return; // we raised it to 1 tasks = transition(); addAsyncTasks(tasks.size()); updateStabilityState(leavingRestState); } doExecute(tasks); } @Override public void dependencyFailed() { final List<Runnable> tasks; synchronized (this) { final boolean leavingRestState = isStableRestState(); ++failCount; if (ignoreNotification() || failCount != 1) return; // we raised it to 1 tasks = transition(); addAsyncTasks(tasks.size()); updateStabilityState(leavingRestState); } doExecute(tasks); } @Override public void dependencySucceeded() { final List<Runnable> tasks; synchronized (this) { final boolean leavingRestState = isStableRestState(); assert failCount > 0; --failCount; if (ignoreNotification() || failCount != 0) return; // we dropped it to 0 tasks = transition(); addAsyncTasks(tasks.size()); updateStabilityState(leavingRestState); } doExecute(tasks); } void dependentStarted() { dependentsStarted(1); } void dependentsStarted(final int count) { assert !holdsLock(this); synchronized (this) { runningDependents += count; } } void dependentStopped() { assert !holdsLock(this); final List<Runnable> tasks; synchronized (this) { final boolean leavingRestState = isStableRestState(); assert runningDependents > 0; --runningDependents; if (ignoreNotification() || runningDependents != 0) return; // we dropped it to 0 tasks = transition(); addAsyncTasks(tasks.size()); updateStabilityState(leavingRestState); } doExecute(tasks); } void newDependent(final ServiceName dependencyName, final Dependent dependent) { assert holdsLock(this); if (state == Substate.START_FAILED && finishedTask(DEPENDENCY_FAILED_TASK)) { dependent.dependencyFailed(); } else if ((state == Substate.STARTING || state == Substate.DOWN) && unfinishedTask(DEPENDENCY_RETRYING_TASK)) { dependent.dependencyFailed(); } if ((state == Substate.WAITING || state == Substate.WONT_START || state == Substate.REMOVING || state == Substate.PROBLEM) && finishedTask(DEPENDENCY_UNAVAILABLE_TASK)) { dependent.dependencyUnavailable(dependencyName); } else if ((state == Substate.DOWN || state == Substate.START_REQUESTED) && unfinishedTask(DEPENDENCY_AVAILABLE_TASK)) { dependent.dependencyUnavailable(dependencyName); } else if (state == Substate.NEW || state == Substate.CANCELLED || state == Substate.REMOVED) { dependent.dependencyUnavailable(dependencyName); } else if (state == Substate.UP && finishedTask(DEPENDENCY_STARTED_TASK)) { dependent.dependencyUp(); } else if (state == Substate.STOP_REQUESTED && unfinishedTask(DEPENDENCY_STOPPED_TASK)) { dependent.dependencyUp(); } } private boolean unfinishedTask(final int taskFlag) { assert holdsLock(this); final boolean taskScheduled = (execFlags & (taskFlag << 16)) != 0; final boolean taskRunning = (execFlags & taskFlag) == 0; return taskScheduled && taskRunning; } private boolean finishedTask(final int taskFlag) { assert holdsLock(this); final boolean taskUnscheduled = (execFlags & (taskFlag << 16)) == 0; final boolean taskFinished = (execFlags & taskFlag) != 0; return taskUnscheduled || taskFinished; } void addDemand() { addDemands(1); } void addDemands(final int demandedByCount) { assert !holdsLock(this); final boolean propagate; final List<Runnable> tasks; synchronized (this) { final boolean leavingRestState = isStableRestState(); final int cnt = this.demandedByCount; this.demandedByCount += demandedByCount; if (ignoreNotification()) return; boolean notStartedLazy = mode == Mode.LAZY && !(state.getState() == State.UP && state != Substate.STOP_REQUESTED); propagate = cnt == 0 && (mode == Mode.ON_DEMAND || notStartedLazy || mode == Mode.PASSIVE); if (!propagate) return; tasks = transition(); addAsyncTasks(tasks.size()); updateStabilityState(leavingRestState); } doExecute(tasks); } void removeDemand() { assert !holdsLock(this); final boolean propagate; final List<Runnable> tasks; synchronized (this) { final boolean leavingRestState = isStableRestState(); assert demandedByCount > 0; final int cnt = --demandedByCount; if (ignoreNotification()) return; boolean notStartedLazy = mode == Mode.LAZY && !(state.getState() == State.UP && state != Substate.STOP_REQUESTED); propagate = cnt == 0 && (mode == Mode.ON_DEMAND || notStartedLazy || mode == Mode.PASSIVE); if (!propagate) return; tasks = transition(); addAsyncTasks(tasks.size()); updateStabilityState(leavingRestState); } doExecute(tasks); } void addChild(final ServiceControllerImpl<?> child) { assert !holdsLock(this); synchronized (this) { if (state.getState() != State.STARTING && state.getState() != State.UP) { throw new IllegalStateException("Children cannot be added in state " + state.getState()); } children.add(child); newDependent(primaryRegistration.getName(), child); } } void removeChild(final ServiceControllerImpl<?> child) { assert !holdsLock(this); final List<Runnable> tasks; synchronized (this) { final boolean leavingRestState = isStableRestState(); if (!children.remove(child)) return; // may happen if child installation process failed if (children.size() > 0) return; // we dropped it to 0 tasks = transition(); addAsyncTasks(tasks.size()); updateStabilityState(leavingRestState); } doExecute(tasks); } IdentityHashSet<ServiceControllerImpl<?>> getChildren() { assert holdsLock(this); return children; } public ServiceControllerImpl<?> getParent() { return parent; } public ServiceContainerImpl getServiceContainer() { return primaryRegistration.getContainer(); } public ServiceController.State getState() { return state.getState(); } public S getValue() throws IllegalStateException { return serviceValue.getValue().getValue(); } public S awaitValue() throws IllegalStateException, InterruptedException { assert !holdsLock(this); synchronized (this) { for (;;) switch (state.getState()) { case UP: { return serviceValue.getValue().getValue(); } case START_FAILED: { throw new IllegalStateException("Failed to start service", startException); } case REMOVED: { throw new IllegalStateException("Service was removed"); } default: { wait(); } } } } public S awaitValue(final long time, final TimeUnit unit) throws IllegalStateException, InterruptedException, TimeoutException { assert !holdsLock(this); long now; long then = System.nanoTime(); long remaining = unit.toNanos(time); synchronized (this) { do { switch (state.getState()) { case UP: { return serviceValue.getValue().getValue(); } case START_FAILED: { throw new IllegalStateException("Failed to start service", startException); } case REMOVED: { throw new IllegalStateException("Service was removed"); } default: { wait(remaining / 1000000L, (int) (remaining % 1000000L)); } } // When will then be now? now = System.nanoTime(); remaining -= now - then; // soon... then = now; } while (remaining > 0L); throw new TimeoutException("Operation timed out"); } } public Service<S> getService() throws IllegalStateException { return serviceValue.getValue(); } public ServiceName getName() { return primaryRegistration.getName(); } private static final ServiceName[] NO_NAMES = new ServiceName[0]; public ServiceName[] getAliases() { final ServiceRegistrationImpl[] aliasRegistrations = this.aliasRegistrations; final int len = aliasRegistrations.length; if (len == 0) { return NO_NAMES; } final ServiceName[] names = new ServiceName[len]; for (int i = 0; i < len; i++) { names[i] = aliasRegistrations[i].getName(); } return names; } void addListener(final ContainerShutdownListener listener) { assert !holdsLock(this); synchronized (this) { if (state == Substate.REMOVED && asyncTasks == 0) { return; // controller is dead } if (shutdownListener != null) { return; // register listener only once } shutdownListener = listener; shutdownListener.controllerAlive(); } } public void addListener(final LifecycleListener listener) { if (listener == null) return; final List<Runnable> tasks; synchronized (this) { final boolean leavingRestState = isStableRestState(); if (lifecycleListeners.contains(listener)) return; lifecycleListeners.add(listener); if (state == Substate.UP) { listenerTransitionTasks.add(new LifecycleListenerTask(listener, LifecycleEvent.UP)); } else if (state == Substate.DOWN) { listenerTransitionTasks.add(new LifecycleListenerTask(listener, LifecycleEvent.DOWN)); } else if (state == Substate.START_FAILED) { listenerTransitionTasks.add(new LifecycleListenerTask(listener, LifecycleEvent.FAILED)); } else if (state == Substate.REMOVED) { listenerTransitionTasks.add(new LifecycleListenerTask(listener, LifecycleEvent.REMOVED)); } tasks = transition(); addAsyncTasks(tasks.size()); updateStabilityState(leavingRestState); } doExecute(tasks); } public void addListener(final ServiceListener<? super S> listener) { assert !holdsLock(this); ListenerTask listenerAddedTask, listenerRemovedTask = null; synchronized (this) { final boolean leavingRestState = isStableRestState(); if (listeners.contains(listener)) { // Duplicates not allowed throw new IllegalArgumentException("Listener " + listener + " already present on controller for " + primaryRegistration.getName()); } listeners.add(listener); listenerAddedTask = new ListenerTask(listener, ListenerNotification.LISTENER_ADDED); incrementAsyncTasks(); if (state == Substate.REMOVED) { listenerRemovedTask = new ListenerTask(listener, Transition.REMOVING_to_REMOVED); incrementAsyncTasks(); } updateStabilityState(leavingRestState); } try { listenerAddedTask.run(); } finally { if (listenerRemovedTask != null) listenerRemovedTask.run(); } } public void removeListener(final LifecycleListener listener) { synchronized (this) { lifecycleListeners.remove(listener); } } public void removeListener(final ServiceListener<? super S> listener) { synchronized (this) { listeners.remove(listener); } } @Override public StartException getStartException() { synchronized (this) { return startException; } } @Override public void retry() { assert !holdsLock(this); final List<Runnable> tasks; synchronized (this) { final boolean leavingRestState = isStableRestState(); if (failCount > 0 || state.getState() != ServiceController.State.START_FAILED) return; startException = null; tasks = transition(); addAsyncTasks(tasks.size()); updateStabilityState(leavingRestState); } doExecute(tasks); } @Override public synchronized Set<ServiceName> getImmediateUnavailableDependencies() { return unavailableDependencies.clone(); } public ServiceController.Mode getMode() { synchronized (this) { return mode; } } public boolean compareAndSetMode(final Mode expectedMode, final Mode newMode) { if (expectedMode == null) { throw new IllegalArgumentException("expectedMode is null"); } return internalSetMode(expectedMode, newMode); } ServiceStatus getStatus() { synchronized (this) { final String parentName = parent == null ? null : parent.getName().getCanonicalName(); final String name = primaryRegistration.getName().getCanonicalName(); final ServiceRegistrationImpl[] aliasRegistrations = this.aliasRegistrations; final int aliasLength = aliasRegistrations.length; final String[] aliases; if (aliasLength == 0) { aliases = NO_STRINGS; } else { aliases = new String[aliasLength]; for (int i = 0; i < aliasLength; i++) { aliases[i] = aliasRegistrations[i].getName().getCanonicalName(); } } String serviceClass = "<unknown>"; try { final Service<? extends S> value = serviceValue.getValue(); if (value != null) { serviceClass = value.getClass().getName(); } } catch (RuntimeException ignored) { } final Dependency[] dependencies = this.dependencies; final int dependenciesLength = dependencies.length; final String[] dependencyNames; if (dependenciesLength == 0) { dependencyNames = NO_STRINGS; } else { dependencyNames = new String[dependenciesLength]; for (int i = 0; i < dependenciesLength; i++) { dependencyNames[i] = dependencies[i].getName().getCanonicalName(); } } StartException startException = this.startException; return new ServiceStatus( parentName, name, aliases, serviceClass, mode.name(), state.getState().name(), state.name(), dependencyNames, failCount != 0, startException != null ? startException.toString() : null, !unavailableDependencies.isEmpty() ); } } String dumpServiceDetails() { final StringBuilder b = new StringBuilder(); IdentityHashSet<Dependent> dependents; synchronized (primaryRegistration) { dependents = primaryRegistration.getDependents().clone(); } b.append("Service Name: ").append(primaryRegistration.getName().toString()).append(" - Dependents: ").append(dependents.size()).append('\n'); for (Dependent dependent : dependents) { final ServiceControllerImpl<?> controller = dependent.getDependentController(); synchronized (controller) { b.append(" ").append(controller.getName().toString()).append(" - State: ").append(controller.state.getState()).append(" (Substate: ").append(controller.state).append(")\n"); } } b.append("Service Aliases: ").append(aliasRegistrations.length).append('\n'); for (ServiceRegistrationImpl registration : aliasRegistrations) { synchronized (registration) { dependents = registration.getDependents().clone(); } b.append(" ").append(registration.getName().toString()).append(" - Dependents: ").append(dependents.size()).append('\n'); for (Dependent dependent : dependents) { final ServiceControllerImpl<?> controller = dependent.getDependentController(); b.append(" ").append(controller.getName().toString()).append(" - State: ").append(controller.state.getState()).append(" (Substate: ").append(controller.state).append(")\n"); } } synchronized (this) { b.append("Children: ").append(children.size()).append('\n'); for (ServiceControllerImpl<?> child : children) { synchronized (child) { b.append(" ").append(child.getName().toString()).append(" - State: ").append(child.state.getState()).append(" (Substate: ").append(child.state).append(")\n"); } } final Substate state = this.state; b.append("State: ").append(state.getState()).append(" (Substate: ").append(state).append(")\n"); if (parent != null) { b.append("Parent Name: ").append(parent.getPrimaryRegistration().getName().toString()).append('\n'); } b.append("Service Mode: ").append(mode).append('\n'); if (startException != null) { b.append("Start Exception: ").append(startException.getClass().getName()).append(" (Message: ").append(startException.getMessage()).append(")\n"); } String serviceValueString = "(indeterminate)"; try { serviceValueString = serviceValue.toString(); } catch (Throwable ignored) {} b.append("Service Value: ").append(serviceValueString).append('\n'); String serviceObjectString = "(indeterminate)"; Object serviceObjectClass = "(indeterminate)"; try { Object serviceObject = serviceValue.getValue(); if (serviceObject != null) { serviceObjectClass = serviceObject.getClass(); serviceObjectString = serviceObject.toString(); } } catch (Throwable ignored) {} b.append("Service Object: ").append(serviceObjectString).append('\n'); b.append("Service Object Class: ").append(serviceObjectClass).append('\n'); b.append("Demanded By: ").append(demandedByCount).append('\n'); b.append("Stopping Dependencies: ").append(stoppingDependencies).append('\n'); b.append("Running Dependents: ").append(runningDependents).append('\n'); b.append("Fail Count: ").append(failCount).append('\n'); b.append("Unavailable Dep Count: ").append(unavailableDependencies.size()).append('\n'); for (ServiceName name : unavailableDependencies) { b.append(" ").append(name.toString()).append('\n'); } b.append("Dependencies Demanded: ").append(dependenciesDemanded ? "yes" : "no").append('\n'); b.append("Async Tasks: ").append(asyncTasks).append('\n'); if (lifecycleTime != 0L) { final long elapsedNanos = System.nanoTime() - lifecycleTime; final long now = System.currentTimeMillis(); final long stamp = now - (elapsedNanos / 1000000L); b.append("Lifecycle Timestamp: ").append(lifecycleTime).append(String.format(" = %tb %<td %<tH:%<tM:%<tS.%<tL%n", stamp)); } } b.append("Dependencies: ").append(dependencies.length).append('\n'); for (int i = 0; i < dependencies.length; i ++) { final Dependency dependency = dependencies[i]; final ServiceControllerImpl<?> controller = dependency.getDependencyController(); b.append(" ").append(dependency.getName().toString()); if (controller == null) { b.append(" (missing)\n"); } else { synchronized (controller) { b.append(" - State: ").append(controller.state.getState()).append(" (Substate: ").append(controller.state).append(")\n"); } } } return b.toString(); } void addMonitor(final StabilityMonitor stabilityMonitor) { assert !holdsLock(this); synchronized (this) { if (monitors.add(stabilityMonitor) && !isStableRestState()) { stabilityMonitor.incrementUnstableServices(); if (state == Substate.START_FAILED) { stabilityMonitor.addFailed(this); } else if (state == Substate.PROBLEM) { stabilityMonitor.addProblem(this); } } } } void removeMonitor(final StabilityMonitor stabilityMonitor) { assert !holdsLock(this); synchronized (this) { if (monitors.remove(stabilityMonitor) && !isStableRestState()) { stabilityMonitor.removeProblem(this); stabilityMonitor.removeFailed(this); stabilityMonitor.decrementUnstableServices(); } } } void removeMonitorNoCallback(final StabilityMonitor stabilityMonitor) { assert !holdsLock(this); synchronized (this) { monitors.remove(stabilityMonitor); } } Set<StabilityMonitor> getMonitors() { assert holdsLock(this); return monitors; } private enum ListenerNotification { /** Notify the listener that is has been added. */ LISTENER_ADDED, /** Notifications related to the current state. */ TRANSITION, } public Substate getSubstate() { synchronized (this) { return state; } } ServiceRegistrationImpl getPrimaryRegistration() { return primaryRegistration; } ServiceRegistrationImpl[] getAliasRegistrations() { return aliasRegistrations; } private void performInjections() { final int injectionsLength = injections.length; boolean ok = false; int i = 0; try { for (; i < injectionsLength; i++) { final ValueInjection<?> injection = injections[i]; doInject(injection); } ok = true; } finally { if (! ok) { for (; i >= 0; i injections[i].getTarget().uninject(); } } } } private void performOutInjections() { final int injectionsLength = outInjections.length; for (int i = 0; i < injectionsLength; i++) { final ValueInjection<?> injection = outInjections[i]; try { doInject(injection); } catch (Throwable t) { ServiceLogger.SERVICE.exceptionAfterComplete(t, primaryRegistration.getName()); } } } enum ContextState { // mid transition states SYNC_ASYNC_COMPLETE, SYNC_ASYNC_FAILED, // final transition states SYNC, ASYNC, COMPLETE, FAILED, } private static <T> void doInject(final ValueInjection<T> injection) { injection.getTarget().inject(injection.getSource().getValue()); } @Override public String toString() { return String.format("Controller for %s@%x", getName(), Integer.valueOf(hashCode())); } private abstract class ControllerTask implements Runnable { private ControllerTask() { assert holdsLock(ServiceControllerImpl.this); } public final void run() { assert !holdsLock(ServiceControllerImpl.this); try { beforeExecute(); if (!execute()) return; final List<Runnable> tasks; synchronized (ServiceControllerImpl.this) { final boolean leavingRestState = isStableRestState(); // Subtract one for this task decrementAsyncTasks(); tasks = transition(); addAsyncTasks(tasks.size()); updateStabilityState(leavingRestState); } doExecute(tasks); } catch (Throwable t) { ServiceLogger.SERVICE.internalServiceError(t, primaryRegistration.getName()); } finally { afterExecute(); } } void afterExecute() {} void beforeExecute() {} abstract boolean execute(); } private abstract class DependenciesControllerTask extends ControllerTask { final boolean execute() { Lockable lock; for (Dependency dependency : dependencies) { lock = dependency.getLock(); synchronized (lock) { lock.acquireWrite(); try { inform(dependency); } finally { lock.releaseWrite(); } } } if (parent != null) inform(parent); return true; } abstract void inform(Dependency dependency); abstract void inform(ServiceControllerImpl parent); } private abstract class DependentsControllerTask extends ControllerTask { private final int execFlag; private DependentsControllerTask(final int execFlag) { this.execFlag = execFlag; execFlags |= (execFlag << 16); } final boolean execute() { for (Dependent dependent : primaryRegistration.getDependents()) { inform(dependent, primaryRegistration.getName()); } for (ServiceRegistrationImpl aliasRegistration : aliasRegistrations) { for (Dependent dependent : aliasRegistration.getDependents()) { inform(dependent, aliasRegistration.getName()); } } synchronized (ServiceControllerImpl.this) { for (Dependent child : children) { inform(child, primaryRegistration.getName()); } execFlags |= execFlag; } return true; } void inform(final Dependent dependent, final ServiceName serviceName) { inform(dependent); } void inform(final Dependent dependent) {} void beforeExecute() { Lockable lock = primaryRegistration.getLock(); synchronized (lock) { lock.acquireRead(); } for (ServiceRegistrationImpl aliasRegistration : aliasRegistrations) { lock = aliasRegistration.getLock(); synchronized (lock) { lock.acquireRead(); } } } void afterExecute() { Lockable lock = primaryRegistration.getLock(); synchronized (lock) { lock.releaseRead(); } for (ServiceRegistrationImpl aliasRegistration : aliasRegistrations) { lock = aliasRegistration.getLock(); synchronized (lock) { lock.releaseRead(); } } } } private final class DemandDependenciesTask extends DependenciesControllerTask { void inform(final Dependency dependency) { dependency.addDemand(); } void inform(final ServiceControllerImpl parent) { parent.addDemand(); } } private final class UndemandDependenciesTask extends DependenciesControllerTask { void inform(final Dependency dependency) { dependency.removeDemand(); } void inform(final ServiceControllerImpl parent) { parent.removeDemand(); } } private final class DependentStartedTask extends DependenciesControllerTask { void inform(final Dependency dependency) { dependency.dependentStarted(); } void inform(final ServiceControllerImpl parent) { parent.dependentStarted(); } } private final class DependentStoppedTask extends DependenciesControllerTask { void inform(final Dependency dependency) { dependency.dependentStopped(); } void inform(final ServiceControllerImpl parent) { parent.dependentStopped(); } } private final class DependencyAvailableTask extends DependentsControllerTask { DependencyAvailableTask() { super(DEPENDENCY_AVAILABLE_TASK); } void inform(final Dependent dependent, final ServiceName name) { dependent.dependencyAvailable(name); } } private final class DependencyUnavailableTask extends DependentsControllerTask { DependencyUnavailableTask() { super(DEPENDENCY_UNAVAILABLE_TASK); } void inform(final Dependent dependent, final ServiceName name) { dependent.dependencyUnavailable(name); } } private final class DependencyStartedTask extends DependentsControllerTask { private DependencyStartedTask() { super(DEPENDENCY_STARTED_TASK); } void inform(final Dependent dependent) { dependent.dependencyUp(); } } private final class DependencyStoppedTask extends DependentsControllerTask { private DependencyStoppedTask() { super(DEPENDENCY_STOPPED_TASK); } void inform(final Dependent dependent) { dependent.dependencyDown(); } } private final class DependencyFailedTask extends DependentsControllerTask { private DependencyFailedTask() { super(DEPENDENCY_FAILED_TASK); } void inform(final Dependent dependent) { dependent.dependencyFailed(); } } private final class DependencyRetryingTask extends DependentsControllerTask { private DependencyRetryingTask() { super(DEPENDENCY_RETRYING_TASK); } void inform(final Dependent dependent) { dependent.dependencySucceeded(); } } private final class StartTask extends ControllerTask { boolean execute() { final ServiceName serviceName = primaryRegistration.getName(); final StartContextImpl context = new StartContextImpl(); try { performInjections(); final Service<? extends S> service = serviceValue.getValue(); if (service == null) { throw new IllegalArgumentException("Service is null"); } startService(service, context); synchronized (context.lock) { if (context.state != ContextState.SYNC) { return false; } context.state = ContextState.COMPLETE; } performOutInjections(); return true; } catch (StartException e) { e.setServiceName(serviceName); return startFailed(e, serviceName, context); } catch (Throwable t) { StartException e = new StartException("Failed to start service", t, serviceName); return startFailed(e, serviceName, context); } } private void startService(Service<? extends S> service, StartContext context) throws StartException { final ClassLoader contextClassLoader = setTCCL(getCL(service.getClass())); try { service.start(context); } finally { setTCCL(contextClassLoader); } } private boolean startFailed(StartException e, ServiceName serviceName, StartContextImpl context) { ServiceLogger.FAIL.startFailed(e, serviceName); synchronized (context.lock) { final ContextState oldState = context.state; if (oldState != ContextState.SYNC && oldState != ContextState.ASYNC) { ServiceLogger.FAIL.exceptionAfterComplete(e, serviceName); return false; } context.state = ContextState.FAILED; } synchronized (ServiceControllerImpl.this) { startException = e; } return true; } } private final class StopTask extends ControllerTask { private final boolean stopService; StopTask(final boolean stopService) { this.stopService = stopService; } boolean execute() { final ServiceName serviceName = primaryRegistration.getName(); final StopContextImpl context = new StopContextImpl(); boolean ok = false; try { if (stopService) { try { final Service<? extends S> service = serviceValue.getValue(); if (service != null) { stopService(service, context); ok = true; } else { ServiceLogger.ROOT.stopServiceMissing(serviceName); } } catch (Throwable t) { ServiceLogger.FAIL.stopFailed(t, serviceName); } } } finally { synchronized (context.lock) { if (ok && context.state != ContextState.SYNC) { // We want to discard the exception anyway, if there was one. Which there can't be. //noinspection ReturnInsideFinallyBlock return false; } context.state = ContextState.COMPLETE; } uninject(serviceName, injections); uninject(serviceName, outInjections); return true; } } private void stopService(Service<? extends S> service, StopContext context) { final ClassLoader contextClassLoader = setTCCL(getCL(service.getClass())); try { service.stop(context); } finally { setTCCL(contextClassLoader); } } private void uninject(final ServiceName serviceName, ValueInjection<?>[] injections) { for (ValueInjection<?> injection : injections) try { injection.getTarget().uninject(); } catch (Throwable t) { ServiceLogger.ROOT.uninjectFailed(t, serviceName, injection); } } } private final class ListenerTask extends ControllerTask { private final ListenerNotification notification; private final ServiceListener<? super S> listener; private final Transition transition; ListenerTask(final ServiceListener<? super S> listener, final Transition transition) { this.listener = listener; this.transition = transition; notification = ListenerNotification.TRANSITION; } ListenerTask(final ServiceListener<? super S> listener, final ListenerNotification notification) { this.listener = listener; transition = null; this.notification = notification; } boolean execute() { invokeListener(listener, notification, transition); return true; } private void invokeListener(final ServiceListener<? super S> listener, final ListenerNotification notification, final Transition transition) { // first set the TCCL final ClassLoader contextClassLoader = setTCCL(getCL(listener.getClass())); try { switch (notification) { case TRANSITION: { listener.transition(ServiceControllerImpl.this, transition); break; } case LISTENER_ADDED: { listener.listenerAdded(ServiceControllerImpl.this); break; } default: throw new IllegalStateException(); } } catch (Throwable t) { ServiceLogger.SERVICE.listenerFailed(t, listener); } finally { // reset TCCL setTCCL(contextClassLoader); } } } private final class LifecycleListenerTask extends ControllerTask { private final LifecycleListener listener; private final LifecycleEvent event; LifecycleListenerTask(final LifecycleListener listener, final LifecycleEvent event) { this.listener = listener; this.event = event; } boolean execute() { final ClassLoader oldCL = setTCCL(getCL(listener.getClass())); try { listener.handleEvent(ServiceControllerImpl.this, event); } catch (Throwable t) { ServiceLogger.SERVICE.listenerFailed(t, listener); } finally { setTCCL(oldCL); } return true; } } private final class RemoveChildrenTask extends ControllerTask { boolean execute() { synchronized (ServiceControllerImpl.this) { for (ServiceControllerImpl<?> child : children) child.setMode(Mode.REMOVE); } return true; } } private final class RemoveTask extends ControllerTask { boolean execute() { assert getMode() == ServiceController.Mode.REMOVE; assert getSubstate() == Substate.REMOVED || getSubstate() == Substate.CANCELLED; Lockable lock = primaryRegistration.getLock(); synchronized (lock) { lock.acquireWrite(); try { primaryRegistration.clearInstance(ServiceControllerImpl.this); } finally { lock.releaseWrite(); } } for (ServiceRegistrationImpl aliasRegistration : aliasRegistrations) { lock = aliasRegistration.getLock(); synchronized (lock) { lock.acquireWrite(); try { aliasRegistration.clearInstance(ServiceControllerImpl.this); } finally { lock.releaseWrite(); } } } for (Dependency dependency : dependencies) { lock = dependency.getLock(); synchronized (lock) { lock.acquireWrite(); try { dependency.removeDependent(ServiceControllerImpl.this); } finally { lock.releaseWrite(); } } } if (parent != null) { lock = parent.primaryRegistration.getLock(); synchronized (lock) { lock.acquireWrite(); try { parent.removeChild(ServiceControllerImpl.this); } finally { lock.releaseWrite(); } } } return true; } } private final class StartContextImpl implements StartContext { private ContextState state = ContextState.SYNC; private final Object lock = new Object(); public void failed(StartException reason) throws IllegalStateException { synchronized (lock) { if (state == ContextState.COMPLETE || state == ContextState.FAILED || state == ContextState.SYNC_ASYNC_COMPLETE || state == ContextState.SYNC_ASYNC_FAILED) { throw new IllegalStateException(ILLEGAL_CONTROLLER_STATE); } if (state == ContextState.ASYNC) { state = ContextState.FAILED; } if (state == ContextState.SYNC) { state = ContextState.SYNC_ASYNC_FAILED; } } if (reason == null) { reason = new StartException("Start failed, and additionally, a null cause was supplied"); } final ServiceName serviceName = getName(); reason.setServiceName(serviceName); ServiceLogger.FAIL.startFailed(reason, serviceName); final List<Runnable> tasks; synchronized (ServiceControllerImpl.this) { final boolean leavingRestState = isStableRestState(); startException = reason; // Subtract one for this task decrementAsyncTasks(); tasks = transition(); addAsyncTasks(tasks.size()); updateStabilityState(leavingRestState); } doExecute(tasks); } public ServiceTarget getChildTarget() { synchronized (lock) { if (state == ContextState.COMPLETE || state == ContextState.FAILED) { throw new IllegalStateException("Lifecycle context is no longer valid"); } synchronized (ServiceControllerImpl.this) { if (childTarget == null) { childTarget = new ChildServiceTarget(getServiceContainer()); } return childTarget; } } } public void asynchronous() throws IllegalStateException { synchronized (lock) { if (state == ContextState.SYNC) { state = ContextState.ASYNC; } else if (state == ContextState.SYNC_ASYNC_COMPLETE) { state = ContextState.COMPLETE; } else if (state == ContextState.SYNC_ASYNC_FAILED) { state = ContextState.FAILED; } else if (state == ContextState.ASYNC) { throw new IllegalStateException(ILLEGAL_CONTROLLER_STATE); } } } public void complete() throws IllegalStateException { synchronized (lock) { if (state == ContextState.COMPLETE || state == ContextState.FAILED || state == ContextState.SYNC_ASYNC_COMPLETE || state == ContextState.SYNC_ASYNC_FAILED) { throw new IllegalStateException(ILLEGAL_CONTROLLER_STATE); } if (state == ContextState.ASYNC) { state = ContextState.COMPLETE; } if (state == ContextState.SYNC) { state = ContextState.SYNC_ASYNC_COMPLETE; } } performOutInjections(); final List<Runnable> tasks; synchronized (ServiceControllerImpl.this) { final boolean leavingRestState = isStableRestState(); // Subtract one for this task decrementAsyncTasks(); tasks = transition(); addAsyncTasks(tasks.size()); updateStabilityState(leavingRestState); } doExecute(tasks); } public long getElapsedTime() { return System.nanoTime() - lifecycleTime; } public ServiceController<?> getController() { return ServiceControllerImpl.this; } public void execute(final Runnable command) { doExecute(Collections.<Runnable>singletonList(new Runnable() { public void run() { final ClassLoader contextClassLoader = setTCCL(getCL(command.getClass())); try { command.run(); } finally { setTCCL(contextClassLoader); } } })); } } private final class StopContextImpl implements StopContext { private ContextState state = ContextState.SYNC; private final Object lock = new Object(); public void asynchronous() throws IllegalStateException { synchronized (lock) { if (state == ContextState.SYNC) { state = ContextState.ASYNC; } else if (state == ContextState.SYNC_ASYNC_COMPLETE) { state = ContextState.COMPLETE; } else if (state == ContextState.ASYNC) { throw new IllegalStateException(ILLEGAL_CONTROLLER_STATE); } } } public void complete() throws IllegalStateException { synchronized (lock) { if (state == ContextState.COMPLETE || state == ContextState.SYNC_ASYNC_COMPLETE) { throw new IllegalStateException(ILLEGAL_CONTROLLER_STATE); } if (state == ContextState.ASYNC) { state = ContextState.COMPLETE; } if (state == ContextState.SYNC) { state = ContextState.SYNC_ASYNC_COMPLETE; } } for (ValueInjection<?> injection : injections) { injection.getTarget().uninject(); } final List<Runnable> tasks; synchronized (ServiceControllerImpl.this) { final boolean leavingRestState = isStableRestState(); // Subtract one for this task decrementAsyncTasks(); tasks = transition(); addAsyncTasks(tasks.size()); updateStabilityState(leavingRestState); } doExecute(tasks); } public ServiceController<?> getController() { return ServiceControllerImpl.this; } public void execute(final Runnable command) { doExecute(Collections.<Runnable>singletonList(new Runnable() { public void run() { final ClassLoader contextClassLoader = setTCCL(getCL(command.getClass())); try { command.run(); } finally { setTCCL(contextClassLoader); } } })); } public long getElapsedTime() { return System.nanoTime() - lifecycleTime; } } private final class ChildServiceTarget extends ServiceTargetImpl { private volatile boolean valid = true; private ChildServiceTarget(final ServiceTargetImpl parentTarget) { super(parentTarget); } <T> ServiceController<T> install(final ServiceBuilderImpl<T> serviceBuilder) throws ServiceRegistryException { if (! valid) { throw new IllegalStateException("Service target is no longer valid"); } return super.install(serviceBuilder); } protected <T> ServiceBuilder<T> createServiceBuilder(final ServiceName name, final Value<? extends Service<T>> value, final ServiceControllerImpl<?> parent) throws IllegalArgumentException { return super.createServiceBuilder(name, value, ServiceControllerImpl.this); } @Override public ServiceTarget subTarget() { return new ChildServiceTarget(this); } } private void addAsyncTasks(final int size) { assert holdsLock(this); assert size >= 0; if (size > 0) asyncTasks += size; } private void incrementAsyncTasks() { assert holdsLock(this); asyncTasks++; } private void decrementAsyncTasks() { assert holdsLock(this); assert asyncTasks > 0; asyncTasks } }
package org.jenkinsci.plugins.ghprb; import hudson.Extension; import hudson.model.AbstractProject; import hudson.model.UnprotectedRootAction; import hudson.security.ACL; import hudson.security.csrf.CrumbExclusion; import jenkins.model.Jenkins; import org.acegisecurity.Authentication; import org.acegisecurity.context.SecurityContextHolder; import org.apache.commons.io.IOUtils; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.HashSet; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletRequest; @Extension public class GhprbRootAction implements UnprotectedRootAction { static final String URL = "ghprbhook"; private static final Logger logger = Logger.getLogger(GhprbRootAction.class.getName()); public String getIconFileName() { return null; } public String getDisplayName() { return null; } public String getUrlName() { return URL; } public void doIndex(StaplerRequest req, StaplerResponse resp) { String event = req.getHeader("X-GitHub-Event"); String signature = req.getHeader("X-Hub-Signature"); String type = req.getContentType(); String payload = null; String body = null; if ("application/json".equals(type)) { body = extractRequestBody(req); if (body == null) { logger.log(Level.SEVERE, "Can't get request body for application/json."); return; } payload = body; } else if ("application/x-www-form-urlencoded".equals(type)) { body = extractRequestBody(req); if (body == null || body.length() <= 8) { logger.log(Level.SEVERE, "Request doesn't contain payload. " + "You're sending url encoded request, so you should pass github payload through 'payload' request parameter"); return; } try { String encoding = req.getCharacterEncoding(); payload = URLDecoder.decode(body.substring(8), encoding != null ? encoding : "UTF-8"); } catch (UnsupportedEncodingException e) { logger.log(Level.SEVERE, "Error while trying to decode the payload"); return; } } if (payload == null) { logger.log(Level.SEVERE, "Payload is null, maybe content type '{0}' is not supported by this plugin. " + "Please use 'application/json' or 'application/x-www-form-urlencoded'", new Object[] { type }); return; } for (GhprbWebHook webHook : getWebHooks()) { try { webHook.handleWebHook(event, payload, body, signature); } catch (Exception e) { logger.log(Level.SEVERE, "Unable to process web hook for: " + webHook.getProjectName(), e); } } } private String extractRequestBody(StaplerRequest req) { String body = null; BufferedReader br = null; try { br = req.getReader(); body = IOUtils.toString(br); } catch (IOException e) { body = null; } finally { IOUtils.closeQuietly(br); } return body; } private Set<GhprbWebHook> getWebHooks() { final Set<GhprbWebHook> webHooks = new HashSet<GhprbWebHook>(); // We need this to get access to list of repositories Authentication old = SecurityContextHolder.getContext().getAuthentication(); SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM); try { for (AbstractProject<?, ?> job : Jenkins.getInstance().getAllItems(AbstractProject.class)) { GhprbTrigger trigger = job.getTrigger(GhprbTrigger.class); if (trigger == null || trigger.getWebHook() == null) { continue; } webHooks.add(trigger.getWebHook()); } } finally { SecurityContextHolder.getContext().setAuthentication(old); } if (webHooks.size() == 0) { logger.log(Level.WARNING, "No projects found using GitHub pull request trigger"); } return webHooks; } @Extension public static class GhprbRootActionCrumbExclusion extends CrumbExclusion { @Override public boolean process(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws IOException, ServletException { String pathInfo = req.getPathInfo(); if (pathInfo != null && pathInfo.equals(getExclusionPath())) { chain.doFilter(req, resp); return true; } return false; } public String getExclusionPath() { return "/" + URL + "/"; } } }
package org.jenkinsci.plugins.p4.scm; import com.google.gson.Gson; import com.perforce.p4java.exception.P4JavaException; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.Extension; import hudson.model.TaskListener; import jenkins.scm.api.SCMHead; import jenkins.scm.api.SCMHeadCategory; import jenkins.scm.api.SCMRevision; import jenkins.scm.impl.ChangeRequestSCMHeadCategory; import jenkins.scm.impl.UncategorizedSCMHeadCategory; import jenkins.util.NonLocalizable; import org.jenkinsci.Symbol; import org.jenkinsci.plugins.p4.PerforceScm; import org.jenkinsci.plugins.p4.browsers.P4Browser; import org.jenkinsci.plugins.p4.browsers.SwarmBrowser; import org.jenkinsci.plugins.p4.changes.P4ChangeRef; import org.jenkinsci.plugins.p4.client.ClientHelper; import org.jenkinsci.plugins.p4.client.ConnectionHelper; import org.jenkinsci.plugins.p4.review.P4Review; import org.jenkinsci.plugins.p4.swarmAPI.SwarmProjectAPI; import org.jenkinsci.plugins.p4.swarmAPI.SwarmReviewAPI; import org.jenkinsci.plugins.p4.swarmAPI.SwarmReviewsAPI; import org.jenkinsci.plugins.p4.tasks.CheckoutStatus; import org.kohsuke.stapler.DataBoundConstructor; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class SwarmScmSource extends AbstractP4ScmSource { private final String url; private final String project; @DataBoundConstructor public SwarmScmSource(String id, String credential, String project, String charset, String format) throws MalformedURLException, P4JavaException { super(id, credential); this.project = project; setCharset(charset); setFormat(format); ConnectionHelper p4 = new ConnectionHelper(getOwner(), credential, null); this.url = p4.getSwarm(); } public String getUrl() { return url; } public String getProject() { return project; } @Override public P4Browser getBrowser() { return new SwarmBrowser(url); } @Override public List<P4Head> getTags(@NonNull TaskListener listener) throws Exception { List<P4Head> list = new ArrayList<>(); List<SwarmReviewsAPI.Reviews> reviews = getActiveReviews(project, listener); for (SwarmReviewsAPI.Reviews review : reviews) { String reviewID = String.valueOf(review.getId()); List<String> branches = getBranchesInReview(reviewID, project, listener); for (String branch : branches) { List<P4Path> paths = getPathsInBranch(branch, project, listener); String trgName = branch + "-" + reviewID; P4Head target = new P4Head(trgName, paths); P4ChangeRequestSCMHead tag = new P4ChangeRequestSCMHead(trgName, reviewID, paths, target); list.add(tag); } } return list; } @Override public List<P4Head> getHeads(@NonNull TaskListener listener) throws Exception { List<P4Head> list = new ArrayList<>(); List<SwarmProjectAPI.Branch> branches = getBranchesInProject(project, listener); for (SwarmProjectAPI.Branch branch : branches) { List<P4Path> paths = branch.getPaths(); P4Head head = new P4Head(branch.getId(), paths); list.add(head); } return list; } @Override public P4Revision getRevision(P4Head head, TaskListener listener) throws Exception { if (head instanceof P4ChangeRequestSCMHead) { P4ChangeRequestSCMHead changeRequest = (P4ChangeRequestSCMHead) head; String review = changeRequest.getReview(); long change = getLastChangeInReview(review, listener); P4Revision revision = new P4Revision(head, new P4ChangeRef(change)); return revision; } return super.getRevision(head, listener); } @Override public PerforceScm build(SCMHead head, SCMRevision revision) { PerforceScm scm = super.build(head, revision); if (head instanceof P4ChangeRequestSCMHead) { P4Review review = new P4Review(head.getName(), CheckoutStatus.SHELVED); scm.setReview(review); } return scm; } protected boolean isCategoryEnabled(@NonNull SCMHeadCategory category) { return true; } private List<SwarmReviewsAPI.Reviews> getActiveReviews(String project, TaskListener listener) throws Exception { String fields = "id,state,changes"; String max = "10"; String state = "state[]=needsReview&state[]=needsRevision"; StringBuffer params = new StringBuffer("?"); params.append("max=" + max).append("&"); params.append("fields=" + fields).append("&"); params.append("project=" + project).append("&"); params.append(state); URL urlApi = new URL(url + "/api/v6/reviews" + params); String apiString = apiGET(urlApi, listener); Gson gson = new Gson(); SwarmReviewsAPI api = gson.fromJson(apiString.toString(), SwarmReviewsAPI.class); return api.getReviews(); } private SwarmReviewAPI getSwarmReview(String review, TaskListener listener) throws Exception { String fields = "projects,changes,commits"; StringBuffer params = new StringBuffer("?"); params.append("fields=" + fields); URL urlApi = new URL(url + "/api/v6/reviews/" + review + params); String apiString = apiGET(urlApi, listener); Gson gson = new Gson(); SwarmReviewAPI api = gson.fromJson(apiString.toString(), SwarmReviewAPI.class); return api; } private List<String> getBranchesInReview(String review, String project, TaskListener listener) throws Exception { SwarmReviewAPI api = getSwarmReview(review, listener); HashMap<String, List<String>> projects = api.getReview().getProjects(); List<String> branches = projects.get(project); return branches; } private long getLastChangeInReview(String review, TaskListener listener) throws Exception { SwarmReviewAPI api = getSwarmReview(review, listener); List<Long> changes = api.getReview().getChanges(); long lastChange = 0; for (Long change : changes) { if (change > lastChange) { lastChange = change; } } return lastChange; } private List<P4Path> getPathsInBranch(String id, String project, TaskListener listener) throws Exception { List<SwarmProjectAPI.Branch> branches = getBranchesInProject(project, listener); for (SwarmProjectAPI.Branch branch : branches) { if (id.equals(branch.getId())) { List<P4Path> paths = branch.getPaths(); return paths; } } return new ArrayList<>(); } private List<SwarmProjectAPI.Branch> getBranchesInProject(String project, TaskListener listener) throws Exception { String fields = "branches"; StringBuffer params = new StringBuffer("?"); params.append("fields=" + fields); URL urlApi = new URL(url + "/api/v6/projects/" + project + params); String apiString = apiGET(urlApi, listener); Gson gson = new Gson(); SwarmProjectAPI api = gson.fromJson(apiString.toString(), SwarmProjectAPI.class); List<SwarmProjectAPI.Branch> branches = api.getProject().getBranches(); return branches; } private String apiGET(URL url, TaskListener listener) throws IOException { String auth = getBasicAuth(listener); HttpURLConnection http = (HttpURLConnection) url.openConnection(); http.setDoInput(true); http.setDoOutput(true); http.setUseCaches(false); http.setRequestMethod("GET"); http.setRequestProperty("Authorization", "Basic " + auth); http.connect(); int code = http.getResponseCode(); if (code == 401) { authCache = null; } StringBuffer apiString = new StringBuffer(); String inputLine; BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream(), "UTF-8")); while ((inputLine = in.readLine()) != null) { apiString.append(inputLine); } in.close(); return apiString.toString(); } private String authCache = null; private String getBasicAuth(TaskListener listener) { if (authCache != null) { return authCache; } try (ClientHelper p4 = new ClientHelper(getOwner(), credential, listener, scmSourceClient, getCharset())) { String user = p4.getUser(); String ticket = p4.getTicket(); byte[] message = (user + ":" + ticket).getBytes("UTF-8"); String encoded = javax.xml.bind.DatatypeConverter.printBase64Binary(message); authCache = encoded; return encoded; } catch (Exception e) { return null; } } @Extension @Symbol("multiSwarm") public static final class DescriptorImpl extends P4ScmSourceDescriptor { @Override public String getDisplayName() { return "Helix Swarm"; } @NonNull @Override protected SCMHeadCategory[] createCategories() { return new SCMHeadCategory[]{ new UncategorizedSCMHeadCategory(new NonLocalizable("Branches")), new ChangeRequestSCMHeadCategory(new NonLocalizable("Reviews")) }; } } }
package org.genericsystem.reactor; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; import org.genericsystem.api.core.ApiStatics; import org.genericsystem.common.Generic; import org.genericsystem.defaults.tools.TransformationObservableList; import org.genericsystem.reactor.composite.CompositeTag; import org.genericsystem.reactor.model.GenericModel; import org.genericsystem.reactor.model.GenericModel.StringExtractor; import org.genericsystem.reactor.model.InputGenericModel; import org.genericsystem.reactor.model.InputGenericModel.TriFunction; import org.genericsystem.reactor.model.ObservableListExtractor; import org.genericsystem.reactor.model.SelectorModel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.vertx.core.http.ServerWebSocket; import io.vertx.core.json.JsonObject; import javafx.beans.binding.Bindings; import javafx.beans.binding.ListBinding; import javafx.beans.property.ObjectProperty; import javafx.beans.property.Property; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.beans.value.WeakChangeListener; import javafx.collections.FXCollections; import javafx.collections.MapChangeListener; import javafx.collections.ObservableList; import javafx.collections.ObservableMap; import javafx.collections.ObservableSet; import javafx.collections.SetChangeListener; import javafx.collections.WeakMapChangeListener; import javafx.collections.WeakSetChangeListener; import javafx.util.StringConverter; /** * @author Nicolas Feybesse * * @param <N> */ public abstract class Tag<M extends Model> { private static final Logger log = LoggerFactory.getLogger(Tag.class); private final String tag; public BiConsumer<Tag<M>, ViewContext<?>> metaBinding; public final List<BiConsumer<Model, HtmlDomNode>> preFixedBindings = new ArrayList<>(); public final List<BiConsumer<Model, HtmlDomNode>> postFixedBindings = new ArrayList<>(); private final Tag<?> parent; private final List<Tag<?>> children = new ArrayList<>(); @Override public String toString() { return tag + " " + getClass().getName(); } protected Tag(Tag<?> parent, String tag) { this.tag = tag; this.parent = parent; if (parent != null) parent.getChildren().add(this); } public String getTag() { return tag; } public ServerWebSocket getWebSocket() { return getParent().getWebSocket(); } protected <W, NODE extends HtmlDomNode> void addBidirectionalBinding(Function<NODE, Property<W>> applyOnNode, Function<M, Property<W>> applyOnModel) { preFixedBindings.add((modelContext, node) -> applyOnNode.apply((NODE) node).bindBidirectional(applyOnModel.apply((M) modelContext))); } public void addPrefixBinding(Consumer<M> consumer) { preFixedBindings.add((modelContext, node) -> consumer.accept((M) modelContext)); } protected void addPostfixBinding(Consumer<M> consumer) { postFixedBindings.add((modelContext, node) -> consumer.accept((M) modelContext)); } protected <NODE extends HtmlDomNode> void addActionBinding(Function<NODE, Property<Consumer<Object>>> applyOnNode, Consumer<M> applyOnModel) { preFixedBindings.add((modelContext, node) -> applyOnNode.apply((NODE) node).setValue(o -> applyOnModel.accept((M) modelContext))); } public <NODE extends HtmlDomNode> void bindOptionalStyleClass(Function<M, ObservableValue<Boolean>> applyOnModel, String styleClass) { addPrefixBinding(modelContext -> { ObservableValue<Boolean> optional = applyOnModel.apply(modelContext); Set<String> styleClasses = modelContext.getObservableStyleClasses(this); Consumer<Boolean> consumer = bool -> { if (Boolean.TRUE.equals(bool)) styleClasses.add(styleClass); else styleClasses.remove(styleClass); }; consumer.accept(optional.getValue()); optional.addListener((o, ov, nv) -> consumer.accept(nv)); }); } protected void forEach(CompositeTag<?> parentCompositeElement) { forEach(g -> parentCompositeElement.getStringExtractor().apply(g), gs -> parentCompositeElement.getObservableListExtractor().apply(gs), (gs, extractor) -> parentCompositeElement.getModelConstructor().build(gs, extractor)); } public void forEach(ObservableListExtractor observableListExtractor) { forEach(StringExtractor.SIMPLE_CLASS_EXTRACTOR, observableListExtractor, GenericModel::new); } public void forEach(StringExtractor stringExtractor, ObservableListExtractor observableListExtractor) { forEach(stringExtractor, observableListExtractor, GenericModel::new); } public <MODEL extends Model> void forEach(Function<MODEL, ObservableList<M>> applyOnModel) { metaBinding = (childElement, viewContext) -> { M model = (M) viewContext.getModelContext(); ObservableList<M> models = applyOnModel.apply((MODEL) model); viewContext.getModelContext().setSubContexts(childElement, new TransformationObservableList<M, MODEL>(models, (index, subModel) -> { subModel.parent = model; viewContext.createViewContextChild(index, subModel, childElement); return (MODEL) subModel; }, Model::destroy)); }; } public void forEach(StringExtractor stringExtractor, ObservableListExtractor observableListExtractor, ModelConstructor<GenericModel> constructor) { metaBinding = (childElement, viewContext) -> { GenericModel model = (GenericModel) viewContext.getModelContext(); ObservableList<Generic> generics = observableListExtractor.apply(model.getGenerics()); viewContext.getModelContext().setSubContexts(childElement, new TransformationObservableList<Generic, GenericModel>(generics, (index, generic) -> { GenericModel duplicate = constructor.build(GenericModel.addToGenerics(generic, model.getGenerics()), stringExtractor); duplicate.parent = model; viewContext.createViewContextChild(index, duplicate, childElement); return duplicate; }, Model::destroy)); }; } public <MODEL extends GenericModel> void select_(Function<MODEL, ObservableValue<M>> applyOnModel, ModelConstructor<GenericModel> constructor) { select_(null, applyOnModel, constructor); } public <MODEL extends GenericModel> void select_(Function<MODEL, ObservableValue<M>> applyOnModel) { select_(null, applyOnModel, GenericModel::new); } public <MODEL extends GenericModel> void select_(StringExtractor stringExtractor, Function<MODEL, ObservableValue<M>> applyOnModelContext, ModelConstructor<GenericModel> constructor) { metaBinding = (childElement, viewContext) -> { GenericModel model = (GenericModel) viewContext.getModelContext(); ObservableValue<M> observableValue = applyOnModelContext.apply((MODEL) viewContext.getModelContext()); ObservableList<M> subModels = new ListBinding<M>() { { bind(observableValue); } @Override protected ObservableList<M> computeValue() { M value = observableValue.getValue(); return value != null ? FXCollections.singletonObservableList(value) : FXCollections.emptyObservableList(); } }; viewContext.getModelContext().setSubContexts(childElement, new TransformationObservableList<M, MODEL>(subModels, (index, selectedModel) -> { Generic[] gs = ((GenericModel) selectedModel).getGenerics(); // assert Arrays.equals(gs, gs2) : Arrays.toString(gs) + " vs " + Arrays.toString(gs2); GenericModel childModel = constructor.build(gs, stringExtractor != null ? stringExtractor : ((GenericModel) selectedModel).getStringExtractor()); childModel.parent = viewContext.getModelContext(); viewContext.createViewContextChild(index, childModel, childElement); return (MODEL) childModel; }, Model::destroy)); }; } public void select(StringExtractor stringExtractor, Function<Generic[], Generic> genericSupplier, ModelConstructor<GenericModel> constructor) { forEach(stringExtractor, gs -> { Generic generic = genericSupplier.apply(gs); return generic != null ? FXCollections.singletonObservableList(generic) : FXCollections.emptyObservableList(); }, constructor); } public void select(StringExtractor stringExtractor, Class<?> genericClass, ModelConstructor<GenericModel> constructor) { forEach(stringExtractor, gs -> FXCollections.singletonObservableList(gs[0].getRoot().find(genericClass)), constructor); } public void select(StringExtractor stringExtractor, Function<Generic[], Generic> genericSupplier) { select(stringExtractor, genericSupplier, GenericModel::new); } public void select(Function<Generic[], Generic> genericSupplier, ModelConstructor<GenericModel> constructor) { select(StringExtractor.SIMPLE_CLASS_EXTRACTOR, genericSupplier, constructor); } public void select(Function<Generic[], Generic> genericSupplier) { select(StringExtractor.SIMPLE_CLASS_EXTRACTOR, genericSupplier, GenericModel::new); } public void select(StringExtractor stringExtractor, Class<?> genericClass) { select(stringExtractor, genericClass, GenericModel::new); } @FunctionalInterface public interface ModelConstructor<M extends Model> { M build(Generic[] generics, StringExtractor stringExtractor); } public void select(Class<?> genericClass) { select(StringExtractor.SIMPLE_CLASS_EXTRACTOR, genericClass); } public void addSelectionIndex(int value) { addPrefixBinding(modelContext -> modelContext.getSelectionIndex(this).setValue(value)); } public void bindSelectionIndex(Function<M, ObservableValue<Number>> applyOnModel) { addPrefixBinding(modelContext -> modelContext.getSelectionIndex(this).bind(applyOnModel.apply(modelContext))); } public void bindBidirectionalSelectionIndex(Function<M, Property<Number>> applyOnModel) { addPrefixBinding(modelContext -> modelContext.getSelectionIndex(this).bindBidirectional(applyOnModel.apply(modelContext))); } public <SUBMODEL extends GenericModel> void bindBiDirectionalSelection(Tag<SUBMODEL> subElement) { bindBiDirectionalSelection(subElement, 0); } public <SUBMODEL extends GenericModel> void bindBiDirectionalSelection(Tag<SUBMODEL> subElement, int shift) { bindBiDirectionalSelection(subElement, SelectorModel::getSelection, shift); } protected <SUBMODEL extends GenericModel> void bindBiDirectionalSelection(Tag<SUBMODEL> subElement, Function<SelectorModel, Property<GenericModel>> applyOnModel) { bindBiDirectionalSelection(subElement, applyOnModel, 0); } protected <SUBMODEL extends GenericModel> void bindBiDirectionalSelection(Tag<SUBMODEL> subElement, Function<SelectorModel, Property<GenericModel>> applyOnModel, int shift) { addPostfixBinding(modelContext -> { List<? extends Model> subContexts = modelContext.getSubContexts(subElement); BidirectionalBinding.bind(modelContext.getSelectionIndex(this), applyOnModel.apply((SelectorModel) modelContext), number -> number.intValue() - shift >= 0 ? (GenericModel) subContexts.get(number.intValue() - shift) : null, genericModel -> subContexts.indexOf(genericModel) + shift); }); } protected <SUBMODEL extends GenericModel> void initSelection(Tag<SUBMODEL> subElement) { addPostfixBinding(modelContext -> { List<GenericModel> subContexts = (List) modelContext.getSubContexts(subElement); Generic selectedGeneric = ((GenericModel) modelContext).getGeneric(); Optional<GenericModel> selectedModel = subContexts.stream().filter(sub -> selectedGeneric.equals(sub.getGeneric())).findFirst(); if (selectedModel.isPresent()) ((SelectorModel) modelContext).getSelection().setValue(selectedModel.get()); }); } private void bindMapElement(String name, Function<M, ObservableValue<String>> applyOnModel, Function<Model, Map<String, String>> getMap) { addPrefixBinding(modelContext -> { Map<String, String> map = getMap.apply(modelContext); ChangeListener<String> listener = (o, old, newValue) -> map.put(name, newValue); ObservableValue<String> observable = applyOnModel.apply(modelContext); observable.addListener(listener); map.put(name, observable.getValue()); }); } private void bindBiDirectionalMapElement(Function<M, Property<String>> applyOnModel, String name, Function<Model, ObservableMap<String, String>> getMap) { bindBiDirectionalMapElement(applyOnModel, name, getMap, ApiStatics.STRING_CONVERTERS.get(String.class)); } private <T extends Serializable> void bindBiDirectionalMapElement(Function<M, Property<T>> applyOnModel, String name, Function<Model, ObservableMap<String, String>> getMap, StringConverter<T> stringConverter) { bindBiDirectionalMapElement(applyOnModel, name, getMap, model -> stringConverter); } private <T extends Serializable> void bindBiDirectionalMapElement(Function<M, Property<T>> applyOnModel, String name, Function<Model, ObservableMap<String, String>> getMap, Function<M, StringConverter<T>> getStringConverter) { addPrefixBinding(modelContext -> { ObservableMap<String, String> map = getMap.apply(modelContext); StringConverter<T> stringConverter = getStringConverter.apply(modelContext); ChangeListener<T> listener = (o, old, newValue) -> map.put(name, stringConverter.toString(newValue)); Property<T> observable = applyOnModel.apply(modelContext); observable.addListener(listener); map.addListener((MapChangeListener<String, String>) c -> { if (!name.equals(c.getKey())) return; try { observable.setValue(c.wasAdded() ? stringConverter.fromString(c.getValueAdded()) : null); } catch (Exception ignore) { log.warn("Conversion exception : " + ignore.getMessage()); } }); map.put(name, stringConverter.toString(observable.getValue())); }); } public <T extends Serializable> void bindOperation(Function<M, Property<T>> applyOnModel, BiConsumer<M, T> operation) { addPrefixBinding(modelContext -> { Property<T> observable = applyOnModel.apply(modelContext); observable.addListener((o, old, nva) -> operation.accept(modelContext, nva)); }); } public <T> void initProperty(Function<M, Property<T>> applyOnModel, Function<M, T> getInitialValue) { addPrefixBinding(modelContext -> { Property<T> observable = applyOnModel.apply(modelContext); observable.setValue(getInitialValue.apply(modelContext)); }); } public <T> void setProperty(String propertyName, Function<M, ObservableValue<T>> applyOnModel) { addPrefixBinding(modelContext -> { modelContext.setProperty(this, propertyName, applyOnModel.apply(modelContext)); }); } public void addStyle(String propertyName, String value) { addPrefixBinding(model -> model.getObservableStyles(this).put(propertyName, value)); } public void bindOptionalStyle(String propertyName, Function<M, ObservableValue<Boolean>> applyOnModel, String propertyValue) { bindOptionalStyle(propertyName, applyOnModel, propertyValue, ""); } public void bindOptionalStyle(String propertyName, Function<M, ObservableValue<Boolean>> applyOnModel, String propertyValue, String propertyValueFalse) { bindStyle(propertyName, model -> { ObservableValue<Boolean> optional = applyOnModel.apply(model); return Bindings.createStringBinding(() -> optional.getValue() ? propertyValue : propertyValueFalse, optional); }); } public void bindStyle(String propertyName, Function<M, ObservableValue<String>> applyOnModel) { bindMapElement(propertyName, applyOnModel, model -> model.getObservableStyles(this)); } // public void setStyleClasses(Set<String> styleClasses) { // addPrefixBinding(model -> { // ObservableSet<String> observableStyleClasses = model.getObservableStyleClasses(this); // observableStyleClasses.removeIf(styleClass -> !styleClasses.contains(styleClass)); // observableStyleClasses.addAll(styleClasses); public void addStyleClasses(String... styleClasses) { addPrefixBinding(model -> model.getObservableStyleClasses(this).addAll(Arrays.asList(styleClasses))); } // public void bindStyleClasses(ObservableSet<String> styleClasses) { // addPrefixBinding(model -> Bindings.bindContent(model.getObservableStyleClasses(this), styleClasses)); // public void bindStylesMap(ObservableMap<String, String> styles) { // addPrefixBinding(model -> Bindings.bindContent(model.getObservableStyles(this), styles)); // public void setStylesMap(Map<String, String> styles) { // addPrefixBinding(model -> model.getObservableStyles(this).putAll(styles)); public void addStyleClass(String styleClass) { addPrefixBinding(model -> model.getObservableStyleClasses(this).add(styleClass)); } public void addAttribute(String attributeName, String value) { addPrefixBinding(model -> model.getObservableAttributes(this).put(attributeName, value)); } public void bindOptionalAttribute(String attributeName, Function<M, ObservableValue<Boolean>> applyOnModel, String attributeValue) { bindOptionalAttribute(attributeName, applyOnModel, attributeValue, null); } public void bindOptionalAttribute(String attributeName, Function<M, ObservableValue<Boolean>> applyOnModel, String attributeValue, String attributeValueFalse) { bindAttribute(attributeName, model -> { ObservableValue<Boolean> optional = applyOnModel.apply(model); return Bindings.createStringBinding(() -> optional.getValue() ? attributeValue : attributeValueFalse, optional); }); } public void bindAttribute(String attributeName, Function<M, ObservableValue<String>> applyOnModel) { bindMapElement(attributeName, applyOnModel, model -> model.getObservableAttributes(this)); } public void bindBiDirectionalAttribute(Function<M, Property<String>> applyOnModel, String attributeName) { bindBiDirectionalMapElement(applyOnModel, attributeName, model -> model.getObservableAttributes(this)); } public <T extends Serializable> void bindBiDirectionalAttribute(Function<M, Property<T>> applyOnModel, String attributeName, StringConverter<T> stringConverter) { bindBiDirectionalMapElement(applyOnModel, attributeName, model -> model.getObservableAttributes(this), stringConverter); } public <T extends Serializable> void bindBiDirectionalAttribute(Function<M, Property<T>> applyOnModel, String attributeName, Function<M, StringConverter<T>> getStringConverter) { bindBiDirectionalMapElement(applyOnModel, attributeName, model -> model.getObservableAttributes(this), getStringConverter); } public void bindOptionalBiDirectionalAttribute(Function<M, Property<Boolean>> applyOnModel, String attributeName, String attributeValue) { bindOptionalBiDirectionalAttribute(applyOnModel, attributeName, attributeValue, null); } public void bindOptionalBiDirectionalAttribute(Function<M, Property<Boolean>> applyOnModel, String attributeName, String attributeValue, String attributeValueFalse) { bindBiDirectionalMapElement(applyOnModel, attributeName, model -> model.getObservableAttributes(this), new StringConverter<Boolean>() { @Override public String toString(Boolean bool) { if (bool == null || !bool) return attributeValueFalse; else return attributeValue; } @Override public Boolean fromString(String string) { if (attributeValue.equals(string)) return true; else return false; } }); } public void bindAction(TriFunction<Generic[], Serializable, Generic, Generic> operation) { addPrefixBinding(modelContext -> ((InputGenericModel) modelContext).getInputAction().setValue(operation)); } public void bindTextBidirectional(Function<M, Property<String>> applyOnModel) { addBidirectionalBinding(HtmlDomNode::getTextProperty, applyOnModel); } public void setText(String value) { addPrefixBinding(model -> model.getTextProperty(this).setValue(value)); } public void bindText(Function<M, ObservableValue<String>> applyOnModel) { addPrefixBinding(modelContext -> modelContext.getTextProperty(this).bind(applyOnModel.apply(modelContext))); } protected abstract HtmlDomNode createNode(String parentId); protected List<Tag<?>> getChildren() { return children; } @SuppressWarnings("unchecked") public <COMPONENT extends Tag<?>> COMPONENT getParent() { return (COMPONENT) parent; } private static final String MSG_TYPE = "msgType"; private static final String ADD = "A"; private static final String UPDATE = "U"; private static final String REMOVE = "R"; private static final String UPDATE_TEXT = "UT"; private static final String UPDATE_SELECTION = "US"; private static final String ADD_STYLECLASS = "AC"; private static final String REMOVE_STYLECLASS = "RC"; private static final String ADD_STYLE = "AS"; private static final String REMOVE_STYLE = "RS"; private static final String ADD_ATTRIBUTE = "AA"; private static final String REMOVE_ATTRIBUTE = "RA"; private static final String PARENT_ID = "parentId"; public static final String ID = "nodeId"; private static final String NEXT_ID = "nextId"; private static final String STYLE_PROPERTY = "styleProperty"; private static final String STYLE_VALUE = "styleValue"; private static final String ATTRIBUTE_NAME = "attributeName"; private static final String ATTRIBUTE_VALUE = "attributeValue"; private static final String STYLECLASS = "styleClass"; private static final String TEXT_CONTENT = "textContent"; private static final String TAG_HTML = "tagHtml"; private static final String ELT_TYPE = "eltType"; public class HtmlDomNode { private final String id; private final String parentId; private final StringProperty text = new SimpleStringProperty(); private final ObservableSet<String> styleClasses = FXCollections.observableSet(); private final ObservableMap<String, String> styles = FXCollections.observableHashMap(); private final ObservableMap<String, String> attributes = FXCollections.observableHashMap(); private final ChangeListener<String> textListener = (o, old, newValue) -> sendMessage(new JsonObject().put(MSG_TYPE, UPDATE_TEXT).put(ID, getId()).put(TEXT_CONTENT, newValue != null ? newValue : "")); private final MapChangeListener<String, String> stylesListener = change -> { if (!change.wasAdded() || change.getValueAdded() == null || change.getValueAdded().equals("")) { // System.out.println("Remove : " + change.getKey() + " " + change.getValueRemoved()); sendMessage(new JsonObject().put(MSG_TYPE, REMOVE_STYLE).put(ID, getId()).put(STYLE_PROPERTY, change.getKey())); } else if (change.wasAdded()) { // System.out.println("Add : " + change.getKey() + " " + change.getValueAdded()); sendMessage(new JsonObject().put(MSG_TYPE, ADD_STYLE).put(ID, getId()).put(STYLE_PROPERTY, change.getKey()).put(STYLE_VALUE, change.getValueAdded())); } }; private final MapChangeListener<String, String> attributesListener = change -> { if (!change.wasAdded() || change.getValueAdded() == null || change.getValueAdded().equals("")) { sendMessage(new JsonObject().put(MSG_TYPE, REMOVE_ATTRIBUTE).put(ID, getId()).put(ATTRIBUTE_NAME, change.getKey())); } else if (change.wasAdded()) { sendMessage(new JsonObject().put(MSG_TYPE, ADD_ATTRIBUTE).put(ID, getId()).put(ATTRIBUTE_NAME, change.getKey()).put(ATTRIBUTE_VALUE, change.getValueAdded())); } }; private final SetChangeListener<String> styleClassesListener = change -> { if (change.wasAdded()) { sendMessage(new JsonObject().put(MSG_TYPE, ADD_STYLECLASS).put(ID, getId()).put(STYLECLASS, change.getElementAdded())); } else { sendMessage(new JsonObject().put(MSG_TYPE, REMOVE_STYLECLASS).put(ID, getId()).put(STYLECLASS, change.getElementRemoved())); } }; public ObservableMap<String, String> getStyles() { return styles; } public ObservableMap<String, String> getAttributes() { return attributes; } public HtmlDomNode(String parentId) { this.parentId = parentId; this.id = String.format("%010d", Integer.parseInt(this.hashCode() + "")).substring(0, 10); text.addListener(new WeakChangeListener<>(textListener)); styles.addListener(new WeakMapChangeListener<>(stylesListener)); styleClasses.addListener(new WeakSetChangeListener<>(styleClassesListener)); attributes.addListener(new WeakMapChangeListener<>(attributesListener)); } public void sendAdd(int index) { JsonObject jsonObj = new JsonObject().put(MSG_TYPE, ADD); jsonObj.put(PARENT_ID, parentId); jsonObj.put(ID, id); jsonObj.put(TAG_HTML, getTag()); jsonObj.put(NEXT_ID, index); fillJson(jsonObj); // System.out.println(jsonObj.encodePrettily()); sendMessage(jsonObj); } public JsonObject fillJson(JsonObject jsonObj) { return null; } public void sendRemove() { sendMessage(new JsonObject().put(MSG_TYPE, REMOVE).put(ID, id)); } public void sendMessage(JsonObject jsonObj) { getWebSocket().writeFinalTextFrame(jsonObj.encode()); } public ObservableSet<String> getStyleClasses() { return styleClasses; } public Property<String> getStyle(String propertyName) { Property<String> property = new SimpleStringProperty(styles.get(propertyName)); property.addListener((c, o, n) -> styles.put(propertyName, n)); return property; } public StringProperty getTextProperty() { return text; } public String getId() { return id; } public void handleMessage(JsonObject json) { } } public class ActionHtmlNode extends HtmlDomNode { public ActionHtmlNode(String parentId) { super(parentId); } private final Property<Consumer<Object>> actionProperty = new SimpleObjectProperty<>(); public Property<Consumer<Object>> getActionProperty() { return actionProperty; } @Override public void handleMessage(JsonObject json) { getActionProperty().getValue().accept(new Object()); } } public class SelectableHtmlDomNode extends ActionHtmlNode { private static final String SELECTED_INDEX = "selectedIndex"; private Property<Number> selectionIndex = new SimpleIntegerProperty(); private final ChangeListener<Number> indexListener = (o, old, newValue) -> { System.out.println(new JsonObject().put(MSG_TYPE, UPDATE_SELECTION).put(ID, getId()).put(SELECTED_INDEX, newValue != null ? newValue : 0).encodePrettily()); sendMessage(new JsonObject().put(MSG_TYPE, UPDATE_SELECTION).put(ID, getId()).put(SELECTED_INDEX, newValue != null ? newValue : 0)); }; public SelectableHtmlDomNode(String parentId) { super(parentId); selectionIndex.addListener(new WeakChangeListener<>(indexListener)); } public Property<Number> getSelectionIndex() { return selectionIndex; } @Override public void handleMessage(JsonObject json) { if (UPDATE.equals(json.getString(MSG_TYPE))) { getSelectionIndex().setValue(json.getInteger(SELECTED_INDEX)); System.out.println("Selected index : " + getSelectionIndex().getValue()); } } } public class InputTextHtmlDomNode extends HtmlDomNode { private final Property<String> inputString = new SimpleStringProperty(); private final ObjectProperty<Consumer<Object>> enterProperty = new SimpleObjectProperty<>(); public InputTextHtmlDomNode(String parentId) { super(parentId); inputString.addListener(new WeakChangeListener<>(inputListener)); } private final ChangeListener<String> inputListener = (o, old, newValue) -> sendMessage(fillJson(new JsonObject().put(MSG_TYPE, UPDATE_TEXT).put(ID, getId()))); public Property<String> getInputString() { return inputString; } @Override public JsonObject fillJson(JsonObject jsonObj) { super.fillJson(jsonObj); return jsonObj.put("type", "text").put(TEXT_CONTENT, inputString.getValue()); } @Override public void handleMessage(JsonObject json) { if (ADD.equals(json.getString(MSG_TYPE))) getEnterProperty().get().accept(new Object()); if (UPDATE.equals(json.getString(MSG_TYPE))) { getTextProperty().setValue(json.getString(TEXT_CONTENT)); getAttributes().put("value", json.getString(TEXT_CONTENT)); } } public ObjectProperty<Consumer<Object>> getEnterProperty() { return enterProperty; } } public class InputCheckHtmlDomNode extends HtmlDomNode { private static final String CHECKED = "checked"; private final String type; public InputCheckHtmlDomNode(String parentId, String type) { super(parentId); this.type = type; } @Override public JsonObject fillJson(JsonObject jsonObj) { super.fillJson(jsonObj); return jsonObj.put("type", type); } @Override public void handleMessage(JsonObject json) { if ("checkbox".equals(json.getString(ELT_TYPE))) getAttributes().put("checked", json.getBoolean(CHECKED) ? "checked" : ""); } } }
package org.jolokia.docker.maven; import java.io.File; import java.util.*; import org.apache.maven.plugin.*; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.apache.maven.settings.Settings; import org.codehaus.plexus.PlexusConstants; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.context.Context; import org.codehaus.plexus.context.ContextException; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable; import org.fusesource.jansi.AnsiConsole; import org.jolokia.docker.maven.access.*; import org.jolokia.docker.maven.config.ImageConfiguration; import org.jolokia.docker.maven.util.*; /** * Base class for this plugin. * * @author roland * @since 26.03.14 */ public abstract class AbstractDockerMojo extends AbstractMojo implements LogHandler, Contextualizable { // prefix used for console output private static final String LOG_PREFIX = "DOCKER> "; // Key in plugin context specifying shutdown actions public static final String CONTEXT_KEY_SHUTDOWN_ACTIONS = "CONTEXT_KEY_DOCKER_SHUTDOWN_ACTIONS"; // Key for indicating that a "start" goal has run public static final String CONTEXT_KEY_START_CALLED = "CONTEXT_KEY_DOCKER_START_CALLED"; // Standard HTTPS port (IANA registered). The other 2375 with plain HTTP is used only in older // docker installaitons. public static final String DOCKER_HTTPS_PORT = "2376"; // Current maven project @Component protected MavenProject project; // Settings holding authentication info @Component protected Settings settings; // URL to docker daemon @Parameter(property = "docker.url") private String url; @Parameter(property = "docker.certPath") private String certPath; // Whether to use color @Parameter(property = "docker.useColor", defaultValue = "true") private boolean color; // Whether to skip docker alltogether @Parameter(property = "docker.skip", defaultValue = "false") private boolean skip; // Whether to restrict operation to a single image. This can be either // the image or an alias name @Parameter(property = "docker.image") private String imageToUse; // Authentication information @Parameter Map authConfig; // Relevant configuration to use @Parameter(required = true) private List<ImageConfiguration> images; // ANSI escapes for various colors (or empty strings if no coloring is used) private String errorHlColor,infoHlColor,warnHlColor,resetColor,progressHlColor; // Handler dealing with authentication credentials private AuthConfigFactory authConfigFactory; protected static String getContainerImageDescription(String container, String image, String alias) { return container.substring(0, 12) + " " + getImageDescription(image,alias); } /** * Entry point for this plugin. It will set up the helper class and then calls {@link #executeInternal(DockerAccess)} * which must be implemented by subclass. * * @throws MojoExecutionException * @throws MojoFailureException */ public void execute() throws MojoExecutionException, MojoFailureException { if (!skip) { colorInit(); DockerAccess access = null; try { access = new DockerAccessWithHttpClient(extractUrl(), getCertPath(), this); access.start(); } catch (DockerAccessException e) { throw new MojoExecutionException("Cannot create docker access object ",e); } try { executeInternal(access); } catch (DockerAccessException exp) { throw new MojoExecutionException(errorHlColor + exp.getMessage() + resetColor, exp); } finally { access.shutdown(); } } } private String getCertPath() { String path = certPath != null ? certPath : System.getenv("DOCKER_CERT_PATH"); if (path == null) { File dockerHome = new File(System.getProperty("user.home") + "/.docker"); if (dockerHome.isDirectory() && dockerHome.list(SuffixFileFilter.PEM_FILTER).length > 0) { return dockerHome.getAbsolutePath(); } } return path; } // Check both, url and env DOCKER_HOST (first takes precedence) private String extractUrl() { String connect = url != null ? url : System.getenv("DOCKER_HOST"); if (connect == null) { throw new IllegalArgumentException("No url given and now DOCKER_HOST environment variable set"); } String protocol = connect.contains(":" + DOCKER_HTTPS_PORT) ? "https:" : "http:"; return connect.replaceFirst("^tcp:", protocol); } /** * Hook for subclass for doing the real job * * @param dockerAccess access object for getting to the DockerServer */ protected abstract void executeInternal(DockerAccess dockerAccess) throws DockerAccessException, MojoExecutionException; // Registry for managed containers /** * Register a shutdown action executed during "stop" * @param shutdownAction action to register */ protected void registerShutdownAction(ShutdownAction shutdownAction) { getShutdownActions().add(shutdownAction); } /** * Return shutdown actions in reverse registration order * @return registered shutdown actions */ protected List<ShutdownAction> getShutdownActionsInExecutionOrder() { List<ShutdownAction> ret = new ArrayList<ShutdownAction>(getShutdownActions()); Collections.reverse(ret); return ret; } /** * Remove a list of shutdown actions * @param actions actions to remove */ protected void removeShutdownActions(List<ShutdownAction> actions) { getShutdownActions().removeAll(actions); } private Set<ShutdownAction> getShutdownActions() { Object obj = getPluginContext().get(CONTEXT_KEY_SHUTDOWN_ACTIONS); if (obj == null) { Set<ShutdownAction> actions = Collections.synchronizedSet(new LinkedHashSet<ShutdownAction>()); getPluginContext().put(CONTEXT_KEY_SHUTDOWN_ACTIONS, actions); return actions; } else { return (Set<ShutdownAction>) obj; } } /** * Get all images to use. Can be restricted via -Ddocker.image to pick a one or more images. The values * is taken as comma separated list. * * @return list of image configuration to use */ protected List<ImageConfiguration> getImages() { List<ImageConfiguration> ret = new ArrayList<>(); for (ImageConfiguration image : images) { if (matchesConfiguredImages(image)) { ret.add(image); } } return ret; } private boolean matchesConfiguredImages(ImageConfiguration image) { if (imageToUse == null) { return true; } Set<String> imagesAllowed = new HashSet<>(Arrays.asList(imageToUse.split("\\s*,\\s*"))); return imagesAllowed.contains(image.getName()) || imagesAllowed.contains(image.getAlias()); } // Extract authentication information @Override public void contextualize(Context context) throws ContextException { authConfigFactory = new AuthConfigFactory((PlexusContainer) context.get(PlexusConstants.PLEXUS_KEY)); } protected String getImageName(String name) { if (name != null) { return name; } else { return getDefaultUserName() + "/" + getDefaultRepoName() + ":" + project.getVersion(); } } private String getDefaultRepoName() { String repoName = project.getBuild().getFinalName(); if (repoName == null || repoName.length() == 0) { repoName = project.getArtifactId(); } return repoName; } // Repo names with '.' are considered to be remote registries private String getDefaultUserName() { String groupId = project.getGroupId(); String repo = groupId.replace('.','_').replace('-','_'); return repo.length() > 30 ? repo.substring(0,30) : repo; } // Color init private void colorInit() { if (color && System.console() != null) { AnsiConsole.systemInstall(); errorHlColor = "\u001B[0;31m"; infoHlColor = "\u001B[0;32m"; resetColor = "\u001B[0;39m"; warnHlColor = "\u001B[0;33m"; progressHlColor = "\u001B[0;36m"; } else { errorHlColor = ""; infoHlColor = ""; resetColor = ""; warnHlColor = ""; progressHlColor = ""; } } /** {@inheritDoc} */ public void debug(String message) { getLog().debug(LOG_PREFIX + message); } /** {@inheritDoc} */ public void info(String info) { getLog().info(infoHlColor + LOG_PREFIX + info + resetColor); } /** {@inheritDoc} */ public void warn(String warn) { getLog().warn(warnHlColor + LOG_PREFIX + warn + resetColor); } /** {@inheritDoc} */ public boolean isDebugEnabled() { return getLog().isDebugEnabled(); } /** {@inheritDoc} */ public void error(String error) { getLog().error(errorHlColor + error + resetColor); } private int oldProgress = 0; private int total = 0; // A progress indicator is always written out to standard out if a tty is enabled. /** {@inheritDoc} */ public void progressStart(int t) { if (getLog().isInfoEnabled()) { print(progressHlColor + " "); oldProgress = 0; total = t; } } /** {@inheritDoc} */ public void progressUpdate(int current) { if (getLog().isInfoEnabled()) { print("="); int newProgress = (current * 10 + 5) / total; if (newProgress > oldProgress) { print(" " + newProgress + "0% "); oldProgress = newProgress; } flush(); } } /** {@inheritDoc} */ public void progressFinished() { if (getLog().isInfoEnabled()) { println(resetColor); oldProgress = 0; total = 0; } } private void println(String txt) { System.out.println(txt); } private void print(String txt) { System.out.print(txt); } private void flush() { System.out.flush(); } protected AuthConfig prepareAuthConfig(String image) throws MojoExecutionException { return authConfigFactory.createAuthConfig(authConfig, image,settings); } protected static String getImageDescription(String image, String alias) { return "[" + image + "]" + (alias != null ? " \"" + alias + "\"" : ""); } // Class for registering a shutdown action protected static class ShutdownAction { // The image used private String image; // Alias of the image private final String alias; // Data container create from image private String container; protected ShutdownAction(String image, String alias, String container) { this.image = image; this.container = container; this.alias = alias; } /** * Check whether this shutdown actions applies to the given image and/or container * * @param pImage image to check * @return true if this action should be applied */ public boolean applies(String pImage) { return pImage == null || pImage.equals(image); } /** * Clean up according to the given parameters * * @param access access object for reaching docker * @param log logger to use * @param keepContainer whether to keep the container (and its data container) */ public void shutdown(DockerAccess access, LogHandler log,boolean keepContainer) throws MojoExecutionException { // Stop the container try { access.stopContainer(container); if (!keepContainer) { // Remove the container access.removeContainer(container); } log.info("Stopped" + (keepContainer ? "" : " and removed") + " container " + getContainerImageDescription(container, image, alias)); } catch (DockerAccessException e) { throw new MojoExecutionException("Cannot shutdown",e); } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) {return false;} ShutdownAction that = (ShutdownAction) o; return container.equals(that.container); } @Override public int hashCode() { return container.hashCode(); } } }
package org.jrivets.beans.guice; import static com.google.inject.matcher.Matchers.any; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import javax.annotation.PostConstruct; import com.google.inject.AbstractModule; import com.google.inject.ProvisionException; import com.google.inject.TypeLiteral; import com.google.inject.spi.InjectionListener; import com.google.inject.spi.TypeEncounter; import com.google.inject.spi.TypeListener; /** * The module adds {@link PostConstruct} annotation processing. * * @author Dmitry Spasibenko * */ public class PostConstructModule extends AbstractModule { @Override protected void configure() { bindPostConstruct(); } private void bindPostConstruct() { bindListener(any(), new TypeListener() { public <I> void hear(TypeLiteral<I> injectableType, TypeEncounter<I> encounter) { Class<? super I> type = injectableType.getRawType(); Method[] methods = type.getDeclaredMethods(); for (final Method method : methods) { final PostConstruct annotation = method.getAnnotation(PostConstruct.class); if (annotation != null) { encounter.register(new InjectionListener<I>() { public void afterInjection(I injectee) { try { method.setAccessible(true); method.invoke(injectee); } catch (InvocationTargetException ie) { Throwable e = ie.getTargetException(); throw new ProvisionException(e.getMessage(), e); } catch (IllegalAccessException e) { throw new ProvisionException(e.getMessage(), e); } } }); } } } }); } }
package org.pfaa.geologica.block; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import org.pfaa.geologica.GeoMaterial; import scala.actors.threadpool.Arrays; public class ChanceDropRegistry { private Map<GeoMaterial, ChanceDropSet> dropsByMaterial = new HashMap(); private static final ChanceDropRegistry INSTANCE = new ChanceDropRegistry(); private ChanceDropRegistry() { } public static ChanceDropRegistry instance() { return INSTANCE; } public void addChanceDrop(GeoMaterial material, ItemStack item, int bonus, float chance, boolean fortuneMultiplies) { ChanceDropSet drops = this.dropsByMaterial.get(material); if (drops == null) { drops = new ChanceDropSet(); dropsByMaterial.put(material, drops); } drops.addDrop(new ChanceDrop(item, bonus, chance, fortuneMultiplies)); } public void addChanceDrop(GeoMaterial material, ItemStack item, int bonus) { this.addChanceDrop(material, item, bonus, 1.0F, true); } public ArrayList<ItemStack> getDrops(GeoMaterial material, Random rand, int fortune) { ChanceDropSet drops = this.dropsByMaterial.get(material); return drops.getDrops(rand, fortune); } private static class ChanceDrop { public final ItemStack itemStack; public final float chance; public final int bonus; public final boolean fortuneMultiplies; public ChanceDrop(ItemStack itemStack, int bonus, float chance, boolean fortuneMultiplies) { super(); this.itemStack = itemStack; this.chance = chance; this.bonus = bonus; this.fortuneMultiplies = fortuneMultiplies; } } private static class ChanceDropSet { private List<ChanceDrop> drops; public ChanceDropSet(ChanceDrop... drops) { this.drops = new ArrayList(Arrays.asList(drops)); } public void addDrop(ChanceDrop drop) { this.drops.add(drop); } public ArrayList<ItemStack> getDrops(Random rand, int fortune) { ArrayList<ItemStack> items = new ArrayList(); for (ChanceDrop drop : this.drops) { if (rand.nextFloat() < drop.chance) { ItemStack itemStack = drop.itemStack.copy(); itemStack.stackSize += rand.nextInt(drop.bonus + 1); if (drop.fortuneMultiplies) { itemStack.stackSize *= (Math.max(rand.nextInt(fortune + 2) - 1, 0) + 1); } else { itemStack.stackSize += rand.nextInt(fortune + 1); } items.add(itemStack); } } return items; } public List<ItemStack> getQuantity(Random rand) { return this.getDrops(rand, 0); } } }
package org.squiddev.cctweaks.turtle; import dan200.computercraft.api.turtle.ITurtleAccess; import dan200.computercraft.api.turtle.TurtleCommandResult; import dan200.computercraft.shared.turtle.core.TurtlePlayer; import dan200.computercraft.shared.util.DirectionUtil; import dan200.computercraft.shared.util.InventoryUtil; import dan200.computercraft.shared.util.WorldUtil; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.server.management.ItemInWorldManager; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import org.apache.commons.lang3.tuple.Pair; import org.squiddev.cctweaks.api.IWorldPosition; import org.squiddev.cctweaks.core.Config; import org.squiddev.cctweaks.core.McEvents; import org.squiddev.cctweaks.core.utils.FakeNetHandler; import org.squiddev.cctweaks.core.utils.WorldPosition; /** * Handles various turtle actions. */ public class ToolHostPlayer extends TurtlePlayer { private final ITurtleAccess turtle; private BlockPos digPosition; private Block digBlock; private int currentDamage = -1; private int currentDamageState = -1; /** * A copy of the active stack for applying/removing attributes */ private ItemStack activeStack; private final McEvents.IDropConsumer consumer = new McEvents.IDropConsumer() { @Override public void consumeDrop(ItemStack drop) { ItemStack remainder = InventoryUtil.storeItems(drop, turtle.getInventory(), 0, turtle.getInventory().getSizeInventory(), turtle.getSelectedSlot()); if (remainder != null) { BlockPos position = getPlayerCoordinates(); WorldUtil.dropItemStack(remainder, worldObj, position, turtle.getDirection().getOpposite()); } } }; public ToolHostPlayer(ITurtleAccess turtle) { super((WorldServer) turtle.getWorld()); this.turtle = turtle; playerNetServerHandler = new FakeNetHandler(this); } public TurtleCommandResult attack(EnumFacing direction) { updateInformation(direction); Vec3 rayDir = getLook(1.0f); Vec3 rayStart = new Vec3(posX, posY, posZ); Pair<Entity, Vec3> hit = WorldUtil.rayTraceEntities(turtle.getWorld(), rayStart, rayDir, 1.5); if (hit != null) { Entity hitEntity = hit.getLeft(); loadInventory(getItem()); McEvents.addEntityConsumer(hitEntity, consumer); attackTargetEntityWithCurrentItem(hitEntity); McEvents.removeEntityConsumer(hitEntity); unloadInventory(turtle); return TurtleCommandResult.success(); } return TurtleCommandResult.failure("Nothing to attack here"); } private void setState(Block block, BlockPos pos) { theItemInWorldManager.cancelDestroyingBlock(); theItemInWorldManager.durabilityRemainingOnBlock = -1; digPosition = pos; digBlock = block; currentDamage = -1; currentDamageState = -1; } public TurtleCommandResult dig(EnumFacing direction) { updateInformation(direction); BlockPos pos = getPlayerCoordinates().offset(direction); World world = turtle.getWorld(); Block block = world.getBlockState(pos).getBlock(); if (block != digBlock || !pos.equals(digPosition)) setState(block, pos); if (!world.isAirBlock(pos) && !block.getMaterial().isLiquid()) { if (block == Blocks.bedrock || block.getBlockHardness(world, pos) <= -1) { return TurtleCommandResult.failure("Unbreakable block detected"); } loadInventory(getItem()); ItemInWorldManager manager = theItemInWorldManager; for (int i = 0; i < Config.Turtle.ToolHost.digFactor; i++) { if (currentDamageState == -1) { // TODO: Migrate checks to here manager.onBlockClicked(pos, direction.getOpposite()); currentDamageState = manager.durabilityRemainingOnBlock; } else { currentDamage++; float hardness = block.getPlayerRelativeBlockHardness(this, world, pos) * (currentDamage + 1); int hardnessState = (int) (hardness * 10); if (hardnessState != currentDamageState) { world.sendBlockBreakProgress(getEntityId(), pos, hardnessState); currentDamageState = hardnessState; } if (hardness >= 1) { IWorldPosition position = new WorldPosition(world, pos); McEvents.addBlockConsumer(position, consumer); manager.tryHarvestBlock(pos); McEvents.removeBlockConsumer(position); setState(null, null); break; } } } unloadInventory(turtle); return TurtleCommandResult.success(); } return TurtleCommandResult.failure("Nothing to dig here"); } public BlockPos getPlayerCoordinates() { return turtle.getPosition(); } @Override public Vec3 getPositionVector() { return turtle.getVisualPosition(0); } @Override public void loadInventory(ItemStack currentStack) { // Copy properties over if (currentStack != null) { getAttributeMap().applyAttributeModifiers(currentStack.getAttributeModifiers()); activeStack = currentStack.copy(); } super.loadInventory(currentStack); } @Override public ItemStack unloadInventory(ITurtleAccess turtle) { // Revert to old properties if (activeStack != null) { getAttributeMap().removeAttributeModifiers(activeStack.getAttributeModifiers()); activeStack = null; } return super.unloadInventory(turtle); } public void loadInventory() { loadInventory(getItem()); } public void unloadInventory() { unloadInventory(turtle); } /** * Basically just {@link #getHeldItem()} */ public ItemStack getItem() { return turtle.getInventory().getStackInSlot(turtle.getSelectedSlot()); } /** * Update the player information */ public void updateInformation(EnumFacing direction) { BlockPos position = turtle.getPosition(); setPositionAndRotation( position.getX() + 0.5 + 0.48 * direction.getFrontOffsetX(), position.getY() + 0.5 + 0.48 * direction.getFrontOffsetY(), position.getZ() + 0.5 + 0.48 * direction.getFrontOffsetZ(), direction.getAxis() != EnumFacing.Axis.Y ? DirectionUtil.toYawAngle(direction) : DirectionUtil.toYawAngle(turtle.getDirection()), direction.getAxis() != EnumFacing.Axis.Y ? 0 : DirectionUtil.toPitchAngle(direction) ); } }
package org.threadly.concurrent; import java.util.Collection; import java.util.Deque; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import java.util.RandomAccess; import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; import org.threadly.concurrent.lock.NativeLock; import org.threadly.concurrent.lock.VirtualLock; /** * A thread safe list implementation with an array back end. Make sure * to read the java docs carefully, as many functions behave subtly different * from the java.util.List definition. * * The design of this implementation is NOT to completely avoid synchronization. * We have a hybrid implementation of volatile and synchronized to allow for cheaper * reading, but keeping high consistency. It works with the idea that the internal * data is immutable. Each read has an immutable version of the data. Thus making * writes more expensive (almost like a CopyOnWriteArrayList). * * The difference between this and a CopyOnWriteArrayList is that it does allow some * synchronization. Which can give higher consistency guarantees for some operations. * * A couple notable points is that subList calls are very cheap, but modifications * to sublist are completely independent from their source list. * * Unlike CopyOnWriteArrayList, Iterators can attempt to modify the state of the backing * structure (assuming it still makes sense to do so). Although unlike CopyOnWriteArrayList * iterators, once an Iterator is created it will never see updates to the structure. * For that reason it is impossible to have a ConcurrentModificationExcception. * * @author jent - Mike Jensen * * @param <T> type of object to retain */ public class ConcurrentArrayList<T> implements List<T>, Deque<T>, RandomAccess { protected static <E> DataSet<E> makeEmptyDataSet(int frontPadding, int rearPadding) { if (frontPadding < 0) { throw new IllegalArgumentException("frontPadding must be >= 0"); } else if (rearPadding < 0) { throw new IllegalArgumentException("rearPadding must be >= 0"); } return new DataSet<E>(new Object[0], 0, 0, frontPadding, rearPadding); } protected final VirtualLock modificationLock; protected volatile DataSet<T> currentData; /** * Constructs a new ConcurrentArrayList with a new * internal NativeLock implementation. */ public ConcurrentArrayList() { this(0, 0); } /** * Constructs a new ConcurrentArrayList with a new * internal NativeLock implementation. Specifying * the padding amounts can optimize this implementation * more for the specific use case. If there is space in the * array for adds to the front or end, then we are * able to avoid an array copy. * * @param frontPadding padding to add to front of array to possible avoid array copies * @param rearPadding padding to add to end of array to possible avoid array copies */ public ConcurrentArrayList(int frontPadding, int rearPadding) { this(new NativeLock(), frontPadding, rearPadding); } /** * Constructs a new ConcurrentArrayList with a provided * lock implementation. * * @param modificationLock lock to synchronize on internally */ public ConcurrentArrayList(VirtualLock modificationLock) { this(modificationLock, 0, 0); } /** * Constructs a new ConcurrentArrayList with a provided * lock implementation. Specifying the padding amounts * can optimize this implementation more for the * specific use case. If there is space in the array * for adds to the front or end, then we are able to * avoid an array copy. * * @param modificationLock lock to synchronize on internally * @param frontPadding padding to add to front of array to possible avoid array copies * @param rearPadding padding to add to end of array to possible avoid array copies */ public ConcurrentArrayList(VirtualLock modificationLock, int frontPadding, int rearPadding) { this(ConcurrentArrayList.<T>makeEmptyDataSet(frontPadding, rearPadding), modificationLock); } protected ConcurrentArrayList(DataSet<T> startSet, VirtualLock modificationLock) { if (startSet == null) { throw new IllegalArgumentException("Must provide starting dataSet"); } else if (modificationLock == null) { modificationLock = new NativeLock(); } this.modificationLock = modificationLock; currentData = startSet; } /** * If you want to chain multiple calls together and * ensure that no threads modify the structure during * that time you can get the lock to prevent additional * modifications. * * @return lock used internally */ public VirtualLock getModificationLock() { return modificationLock; } /** * This changes the configuration for the front padding amount for * future modification operations. * * @param frontPadding New value to over allocate the front of new buffers */ public void setFrontPadding(int frontPadding) { if (frontPadding < 0) { throw new IllegalArgumentException("frontPadding must be >= 0"); } synchronized (modificationLock) { currentData.frontPadding = frontPadding; } } /** * This changes the configuration for the rear padding amount for * future modification operations. * * @param rearPadding New value to over allocate the rear of new buffers */ public void setRearPadding(int rearPadding) { if (rearPadding < 0) { throw new IllegalArgumentException("rearPadding must be >= 0"); } synchronized (modificationLock) { currentData.rearPadding = rearPadding; } } /** * @return current amount to added padding to the front of new buffers */ public int getFrontPadding() { return currentData.frontPadding; } /** * @return current amount to added padding to the rear of new buffers */ public int getRearPadding() { return currentData.rearPadding; } @Override public int size() { return currentData.size; } @Override public boolean isEmpty() { return currentData.size == 0; } @Override public T get(int index) { return currentData.get(index); } @Override public int indexOf(Object o) { return currentData.indexOf(o); } @Override public int lastIndexOf(Object o) { return currentData.lastIndexOf(o); } @Override public boolean contains(Object o) { return currentData.indexOf(o) >= 0; } @Override public boolean containsAll(Collection<?> c) { if (c == null || c.isEmpty()) { return true; } DataSet<T> workingSet = currentData; Iterator<?> it = c.iterator(); while (it.hasNext()) { if (workingSet.indexOf(it.next()) < 0) { return false; } } return true; } @Override public Object[] toArray() { Object[] toCopyArray = currentData.dataArray; Object[] resultArray = new Object[toCopyArray.length]; System.arraycopy(toCopyArray, 0, resultArray, 0, resultArray.length); return resultArray; } @Override public <E> E[] toArray(E[] a) { Object[] toCopyArray = currentData.dataArray; if (a.length < toCopyArray.length) { // TODO - need to implement this throw new UnsupportedOperationException("need " + toCopyArray.length + ", provided " + a.length); } System.arraycopy(toCopyArray, 0, a, 0, toCopyArray.length); return a; } @Override public boolean add(T e) { if (e == null) { return false; } synchronized (modificationLock) { currentData = currentData.add(e); } return true; } @Override public boolean remove(Object o) { return removeFirstOccurrence(o); } @Override public boolean addAll(Collection<? extends T> c) { if (c == null || c.isEmpty()) { return false; } Iterator<? extends T> it = c.iterator(); while (it.hasNext()) { if (it.next() == null) { it.remove(); } } synchronized (modificationLock) { currentData = currentData.addAll(c); } return true; } @Override public boolean addAll(int index, Collection<? extends T> c) { if (c == null || c.isEmpty()) { return false; } Iterator<? extends T> it = c.iterator(); while (it.hasNext()) { if (it.next() == null) { it.remove(); } } synchronized (modificationLock) { if (index > size()) { throw new IndexOutOfBoundsException("Index is beyond the array size: " + index); } else if (index < 0) { throw new IndexOutOfBoundsException("Index can not be negative"); } currentData = currentData.addAll(index, c); } return true; } @Override public boolean removeAll(Collection<?> c) { if (c == null || c.isEmpty()) { return false; } synchronized (modificationLock) { DataSet<T> originalSet = currentData; currentData = currentData.removeAll(c); return currentData != originalSet; } } @Override public boolean retainAll(Collection<?> c) { if (c == null || c.isEmpty()) { return false; } synchronized (modificationLock) { DataSet<T> originalSet = currentData; currentData = currentData.retainAll(c); return currentData != originalSet; } } @Override public void clear() { synchronized (modificationLock) { currentData = makeEmptyDataSet(currentData.frontPadding, currentData.rearPadding); } } @Override public void addFirst(T e) { add(0, e); } @Override public void addLast(T e) { add(e); } @Override public boolean offerFirst(T e) { addFirst(e); // this implementation has no capacity limit return true; } @Override public boolean offerLast(T e) { addLast(e); // this implementation has no capacity limit return true; } @Override public T removeFirst() { T result = pollFirst(); if (result == null) { throw new NoSuchElementException(); } return result; } @Override public T removeLast() { T result = pollLast(); if (result == null) { throw new NoSuchElementException(); } return result; } @Override public T pollFirst() { synchronized (modificationLock) { T result = peekFirst(); if (result != null) { currentData = currentData.remove(size() - 1); } return result; } } @Override public T pollLast() { synchronized (modificationLock) { T result = peekLast(); if (result != null) { currentData = currentData.remove(size() - 1); } return result; } } @Override public T getFirst() { T result = peekFirst(); if (result == null) { throw new NoSuchElementException(); } return result; } @Override public T getLast() { T result = peekLast(); if (result == null) { throw new NoSuchElementException(); } return result; } @Override public T peek() { return peekFirst(); } @Override public T peekFirst() { DataSet<T> set = currentData; if (set.size > 0) { return set.get(0); } else { return null; } } @Override public T peekLast() { DataSet<T> set = currentData; if (set.size > 0) { return set.get(set.size - 1); } else { return null; } } @Override public boolean removeFirstOccurrence(Object o) { if (o == null) { return false; } synchronized (modificationLock) { int index = currentData.indexOf(o); if (index < 0) { return false; } else { currentData = currentData.remove(index); return true; } } } @Override public boolean removeLastOccurrence(Object o) { if (o == null) { return false; } synchronized (modificationLock) { int index = currentData.lastIndexOf(o); if (index < 0) { return false; } else { currentData = currentData.remove(index); return true; } } } @Override public boolean offer(T e) { return offerLast(e); } @Override public T remove() { return removeFirst(); } @Override public T poll() { return pollFirst(); } @Override public T element() { return getFirst(); } @Override public void push(T e) { addFirst(e); } @Override public T pop() { return removeFirst(); } @Override public Iterator<T> descendingIterator() { final ListIterator<T> li = listIterator(size()); return new Iterator<T>() { @Override public boolean hasNext() { return li.hasPrevious(); } @Override public T next() { return li.previous(); } @Override public void remove() { li.remove(); } }; } @Override public T set(int index, T element) { DataSet<T> originalSet; synchronized (modificationLock) { if (index > size() - 1) { throw new IndexOutOfBoundsException("Index is beyond the array max index: " + index); } else if (index < 0) { throw new IndexOutOfBoundsException("Index can not be negative"); } originalSet = currentData; currentData = currentData.set(index, element); } return originalSet.get(index); } @Override public void add(int index, T element) { synchronized (modificationLock) { if (index > size()) { throw new IndexOutOfBoundsException("Index is beyond the array size: " + index); } else if (index < 0) { throw new IndexOutOfBoundsException("Index can not be negative"); } currentData = currentData.add(index, element); } } @Override public T remove(int index) { DataSet<T> originalSet; synchronized (modificationLock) { if (index > size() - 1) { throw new IndexOutOfBoundsException("Index is beyond the array max index: " + index); } else if (index < 0) { throw new IndexOutOfBoundsException("Index can not be negative"); } originalSet = currentData; currentData = currentData.remove(index); } return originalSet.get(index); } /** * Move a stored item to a new index. By default * a forward search will happen to find the item. * * @param item item to be moved * @param newIndex new index for placement */ public void reposition(T item, int newIndex) { reposition(item, newIndex, false); } /** * Move a stored item to a new index. If you have * an idea if it is closer to the start or end of the list * you can specify which end to start the search on. * * @param item item to be moved * @param newIndex new index for placement * @param searchBackwards true to start from the end and search backwards */ public void reposition(T item, int newIndex, boolean searchBackwards) { synchronized (modificationLock) { if (newIndex > size()) { throw new IndexOutOfBoundsException(newIndex + " is beyond the array's length: " + (size() - 1)); } int index; if (searchBackwards) { index = lastIndexOf(item); } else { index = indexOf(item); } if (index < 0) { throw new RuntimeException("Could not find item: " + item); } reposition(index, newIndex); } } /** * Move a stored item located at an index to a new index. * Provide the size for newIndex to move the item to the end of * the list. Otherwise all items after the new index will * be shifted right. * * @param originalIndex index for item to be moved to. * @param newIndex new index location for item. */ public void reposition(int originalIndex, int newIndex) { if (newIndex < 0) { throw new IndexOutOfBoundsException("new index can not be negative"); } else if (originalIndex < 0) { throw new IndexOutOfBoundsException("original index can not be negative"); } synchronized (modificationLock) { if (newIndex > size()) { throw new IndexOutOfBoundsException("new index " + newIndex + " is beyond the array's length: " + (size() - 1)); } else if (originalIndex > size()) { throw new IndexOutOfBoundsException("original index " + originalIndex + " is beyond the array's length: " + (size() - 1)); } currentData = currentData.reposition(originalIndex, newIndex); } } @Override public Iterator<T> iterator() { return listIterator(); } @Override public ListIterator<T> listIterator() { return listIterator(0); } @Override public ListIterator<T> listIterator(int index) { return new DataSetListIterator(currentData, index); } /** * This returns a sub list from the current list. The initial call * is very cheap because it uses the current data backing to produce * (no copying necessary). But any modifications to this list will * be treated as a completely new list, and wont ever reflect on the * source list. */ @Override public List<T> subList(int fromIndex, int toIndex) { DataSet<T> workingData = currentData; DataSet<T> newSet = new DataSet<T>(workingData.dataArray, workingData.dataStartIndex + fromIndex, workingData.dataEndIndex - (workingData.dataEndIndex - toIndex), currentData.frontPadding, currentData.rearPadding); // TODO - do we want to return an unmodifiable list? return new ConcurrentArrayList<T>(newSet, modificationLock); } @Override public String toString() { return currentData.toString(); } /** * This is an iterator implementation that is designed to * iterate over a given dataSet. Modifiable actions will attempt * to make changes to the parent class. * * @author jent - Mike Jensen */ protected class DataSetListIterator implements ListIterator<T> { private final DataSet<T> dataSet; private int currentIndex; public DataSetListIterator(DataSet<T> dataSet, int index) { this.dataSet = dataSet; currentIndex = index; } @Override public boolean hasNext() { return currentIndex + 1 < dataSet.size; } @Override public T next() { currentIndex++; return dataSet.get(currentIndex); } @Override public boolean hasPrevious() { return currentIndex - 1 >= 0; } @Override public T previous() { currentIndex return dataSet.get(currentIndex); } @Override public int nextIndex() { return currentIndex + 1; } @Override public int previousIndex() { return currentIndex - 1; } @Override public void remove() { // you can not cause concurrent modification exceptions with this implementation ConcurrentArrayList.this.remove(dataSet.get(currentIndex)); } @Override public void set(T e) { synchronized (modificationLock) { int globalIndex = ConcurrentArrayList.this.indexOf(dataSet.get(currentIndex)); if (globalIndex >= 0) { ConcurrentArrayList.this.set(globalIndex, e); } } } @Override public void add(T e) { synchronized (modificationLock) { int globalIndex = ConcurrentArrayList.this.indexOf(dataSet.get(currentIndex)); if (globalIndex >= 0) { ConcurrentArrayList.this.add(globalIndex + 1, e); } } } } /** * This is designed to be an immutable version of the list. * Modifiable actions will return a new instance that is based * off this one. Because the array may change in areas outside * of the scope of this dataArray, it is expected that the * modificationLock is held while any modifiable operations * are happening. * * @author jent - Mike Jensen * * @param <T> type of object that is held */ protected static class DataSet<T> { protected final Object[] dataArray; protected final int dataStartIndex; // inclusive protected final int dataEndIndex; // exclusive protected final int size; private int frontPadding; // locked around modificationLock private int rearPadding; // locked around modificationLock protected DataSet(Object[] dataArray, int dataStartIndex, int dataEndIndex, int frontPadding, int rearPadding) { this.dataArray = dataArray; this.dataStartIndex = dataStartIndex; this.dataEndIndex = dataEndIndex; this.size = dataEndIndex - dataStartIndex; this.frontPadding = frontPadding; this.rearPadding = rearPadding; } public DataSet<T> reposition(int origCurrentIndex, int origNewIndex) { int currentIndex = origCurrentIndex + dataStartIndex; int newIndex = origNewIndex + dataStartIndex; if (newIndex > currentIndex) { // move right Object[] newData = new Object[size + frontPadding + rearPadding]; if (newIndex == dataEndIndex) { System.arraycopy(dataArray, dataStartIndex, newData, frontPadding, origCurrentIndex); System.arraycopy(dataArray, currentIndex + 1, newData, frontPadding + origCurrentIndex, size - origCurrentIndex - 1); } else { //work backwards // shift end for placement of new item System.arraycopy(dataArray, newIndex, // write from new position to end newData, frontPadding + origNewIndex, size - origNewIndex); System.arraycopy(dataArray, currentIndex + 1, // write from removed position to new position newData, frontPadding + origCurrentIndex, origNewIndex - origCurrentIndex); System.arraycopy(dataArray, dataStartIndex, // write from start to removed position newData, frontPadding, origCurrentIndex); } newData[frontPadding + origNewIndex - 1] = dataArray[currentIndex]; return new DataSet<T>(newData, frontPadding, newData.length - rearPadding, frontPadding, rearPadding); } else if (newIndex < currentIndex) { // move left Object[] newData = new Object[size + frontPadding + rearPadding]; if (newIndex == dataStartIndex) { System.arraycopy(dataArray, dataStartIndex, newData, frontPadding + 1, origCurrentIndex); System.arraycopy(dataArray, currentIndex + 1, newData, frontPadding + origCurrentIndex + 1, dataEndIndex - currentIndex - 1); } else { System.arraycopy(dataArray, dataStartIndex, // write from start to new position newData, frontPadding, origNewIndex); System.arraycopy(dataArray, newIndex, // write from new position to current position newData, frontPadding + origNewIndex + 1, origCurrentIndex - origNewIndex); if (origCurrentIndex < size - 1) { System.arraycopy(dataArray, currentIndex + 1, // write from current position to end newData, frontPadding + origCurrentIndex + 1, size - origCurrentIndex - 1); } } newData[frontPadding + origNewIndex] = dataArray[currentIndex]; return new DataSet<T>(newData, frontPadding, newData.length - rearPadding, frontPadding, rearPadding); } else { // equal return this; } } private Object[] getArrayCopy(int newSize) { Object[] newData = new Object[newSize + frontPadding + rearPadding]; System.arraycopy(dataArray, dataStartIndex, newData, frontPadding, Math.min(size, newSize)); return newData; } @SuppressWarnings("unchecked") public T get(int index) { index += dataStartIndex; return (T)dataArray[index]; } public int indexOf(Object o) { for (int i = dataStartIndex; i < dataEndIndex; i++) { if (dataArray[i].equals(o)) { return i - dataStartIndex; } } return -1; } public int lastIndexOf(Object o) { for (int i = dataEndIndex - 1; i >= dataStartIndex; i if (dataArray[i].equals(o)) { return i - dataStartIndex; } } return -1; } public DataSet<T> set(int index, T element) { if (index == size) { return add(element); } else { Object[] newData = getArrayCopy(size); newData[index + frontPadding] = element; return new DataSet<T>(newData, frontPadding, newData.length - rearPadding, frontPadding, rearPadding); } } public DataSet<T> add(T e) { int index = size; if (dataArray.length - 1 < index || dataArray[index] != null) { Object[] newData = getArrayCopy(index + 1); newData[index + frontPadding] = e; return new DataSet<T>(newData, frontPadding, newData.length - rearPadding, frontPadding, rearPadding); } else { // there is space in the current array dataArray[index] = e; return new DataSet<T>(dataArray, dataStartIndex, dataEndIndex + 1, frontPadding, rearPadding); } } public DataSet<T> add(int origIndex, T element) { Object[] newData; if (origIndex == 0) { // add to front newData = new Object[size + 1 + frontPadding + rearPadding]; newData[frontPadding] = element; System.arraycopy(dataArray, dataStartIndex, newData, frontPadding + 1, size); } else if (origIndex == size) { // add to end return add(element); } else { newData = new Object[size + 1 + frontPadding + rearPadding]; System.arraycopy(dataArray, dataStartIndex, newData, frontPadding, origIndex); newData[frontPadding + origIndex] = element; System.arraycopy(dataArray, dataStartIndex + origIndex, newData, frontPadding + origIndex + 1, size - origIndex); } return new DataSet<T>(newData, frontPadding, newData.length - rearPadding, frontPadding, rearPadding); } public DataSet<T> addAll(Collection<? extends T> c) { return addAll(size, c); } public DataSet<T> addAll(int origIndex, Collection<? extends T> c) { Object[] toAdd = c.toArray(); if (origIndex == 0) { // add to front Object[] newData = new Object[size + toAdd.length + frontPadding + rearPadding]; System.arraycopy(toAdd, 0, newData, frontPadding, toAdd.length); System.arraycopy(dataArray, dataStartIndex, newData, frontPadding + toAdd.length, size); return new DataSet<T>(newData, frontPadding, newData.length - rearPadding, frontPadding, rearPadding); } else if (origIndex == size) { Object[] newData = getArrayCopy(size + toAdd.length); System.arraycopy(toAdd, 0, newData, size + frontPadding, toAdd.length); return new DataSet<T>(newData, frontPadding, newData.length - rearPadding, frontPadding, rearPadding); } else { Object[] newData = new Object[size + toAdd.length + frontPadding + rearPadding]; System.arraycopy(dataArray, dataStartIndex, newData, frontPadding, origIndex); System.arraycopy(toAdd, 0, newData, frontPadding + origIndex, toAdd.length); System.arraycopy(dataArray, dataStartIndex + origIndex, newData, frontPadding + origIndex + toAdd.length, size - origIndex); return new DataSet<T>(newData, frontPadding, newData.length - rearPadding, frontPadding, rearPadding); } } public DataSet<T> remove(int origIndex) { int index = origIndex + dataStartIndex; if (index == dataStartIndex) { return new DataSet<T>(dataArray, dataStartIndex + 1, dataEndIndex, frontPadding, rearPadding); } else if (index == dataEndIndex - 1) { return new DataSet<T>(dataArray, dataStartIndex, dataEndIndex - 1, frontPadding, rearPadding); } else { Object[] newData = new Object[size - 1 + frontPadding + rearPadding]; System.arraycopy(dataArray, dataStartIndex, newData, frontPadding, origIndex); System.arraycopy(dataArray, index + 1, newData, frontPadding + origIndex, size - origIndex - 1); return new DataSet<T>(newData, frontPadding, newData.length - rearPadding, frontPadding, rearPadding); } } // TODO - this can be optimized public DataSet<T> removeAll(Collection<?> c) { DataSet<T> result = this; Iterator<?> it = c.iterator(); while (it.hasNext()) { Object o = it.next(); int index = result.indexOf(o); while (index >= 0) { result = result.remove(index); index = result.indexOf(o); } } return result; } public DataSet<T> retainAll(Collection<?> c) { // TODO Auto-generated method stub throw new UnsupportedOperationException(); } @Override public boolean equals(Object o) { if (this == o) { return true; } else if (o instanceof DataSet) { @SuppressWarnings("rawtypes") DataSet ds = (DataSet)o; return equalsEquivelent(ds); } else { return false; } } @SuppressWarnings("rawtypes") public boolean equalsEquivelent(DataSet ds) { if (this.size != ds.size) { return false; } for (int i = 0; i < size; i++) { Object thisItem = this.get(i); Object thatItem = ds.get(i); if ((thisItem == null && thatItem != null) || (thisItem != null && ! thisItem.equals(thatItem))) { return false; } } return true; } @SuppressWarnings("rawtypes") public boolean equalsExactly(DataSet ds) { if (this == ds) { return true; } else { if (dataStartIndex != ds.dataStartIndex || dataEndIndex != ds.dataEndIndex || dataArray.length != ds.dataArray.length) { return false; } else { for (int i = 0; i < dataArray.length; i++) { if ((dataArray[i] == null && ds.dataArray[i] != null) || (dataArray[i] != null && ! dataArray[i].equals(ds.dataArray[i]))) { return false; } } return true; } } } @Override public int hashCode() { return toString().hashCode(); } @Override public String toString() { StringBuilder result = new StringBuilder(); result.append('['); for (int i = 0; i < dataArray.length; i++) { if (i != 0) { result.append(", "); } if (i == dataStartIndex) { result.append('S'); } if (dataArray[i] instanceof Delayed) { result.append(i).append('-') .append(((Delayed)dataArray[i]).getDelay(TimeUnit.MILLISECONDS)) .append(';').append(dataArray[i]); } else { result.append(i).append('-').append(dataArray[i]); } if (i == dataEndIndex - 1) { result.append('E'); } } result.append(']'); return result.toString(); } } }
package org.yogurt.protobufftools; import org.apache.commons.lang3.reflect.MethodUtils; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.Set; public class ReflectiveEncoder implements IMessageEncoder { public byte[] encode(Object o) throws Exception { Object builder = populateBuilder(new ReflectiveObject(o)); Object built = builder.getClass().getDeclaredMethod("build").invoke(builder); byte[] payload = (byte[]) built.getClass().getMethod("toByteArray").invoke(built); return new MessageWrapper().wrap(o.getClass().getCanonicalName(), payload); } public Object decode(byte[] bytes) throws Exception { Message message = new MessageWrapper().unwrap(bytes); ReflectiveObject o = new ReflectiveObject(Class.forName(message.getMessageType()).newInstance()); ReflectiveObject buffer = createBuffer(o, "parseFrom", message.getPayload()); return extractFromBuffer(o, buffer); } private Object populateBuilder(ReflectiveObject o) throws Exception { ReflectiveObject builder = createBuffer(o,"newBuilder"); for (Field field : o.getFieldsAnnotatedWith(ProtoBufferField.class)) { String fieldName = field.getAnnotation(ProtoBufferField.class).fieldName(); ReflectiveObject invoked = o.smartGet(field.getName()); if (fieldShouldBeRecursed(field)) { builder.smartSet(fieldName, populateBuilder(invoked)); } else { builder.smartSet(fieldName, invoked); } } return builder.getObject(); } private Object extractFromBuffer(ReflectiveObject o, ReflectiveObject buffer) throws Exception { Set<Field> bufferFields = o.getFieldsAnnotatedWith(ProtoBufferField.class); for (Field field : bufferFields) { ReflectiveObject fieldValue = buffer.smartGet(field.getAnnotation(ProtoBufferField.class).fieldName()); if (fieldShouldBeRecursed(field)) { o.smartSet(field.getName(), extractFromBuffer(new ReflectiveObject(field.getType()), fieldValue)); } else { o.smartSet(field.getName(), fieldValue); } } return o.getObject(); } private ReflectiveObject createBuffer(ReflectiveObject o, String methodName, Object... params) throws Exception{ return new ReflectiveObject(MethodUtils.invokeStaticMethod(getProtoBufferClass(o), methodName, params)); } private boolean fieldShouldBeRecursed(Field field) { return field.getType().getAnnotation(ProtoBufferData.class) != null; } private Class<?> getProtoBufferClass(ReflectiveObject o) { return o.getObject().getClass().getAnnotation(ProtoBufferData.class).protoBuffer(); } }
package pokefenn.totemic.block.totem; import java.util.Random; import java.util.stream.Collectors; import net.minecraft.block.Block; import net.minecraft.block.ITileEntityProvider; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.properties.PropertyEnum; import net.minecraft.block.state.BlockFaceShape; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.client.resources.I18n; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.*; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.TextComponentTranslation; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import pokefenn.totemic.ModItems; import pokefenn.totemic.Totemic; import pokefenn.totemic.api.TotemicStaffUsage; import pokefenn.totemic.api.ceremony.Ceremony; import pokefenn.totemic.lib.Strings; import pokefenn.totemic.lib.WoodVariant; import pokefenn.totemic.tileentity.totem.*; public class BlockTotemBase extends Block implements ITileEntityProvider, TotemicStaffUsage { public static final PropertyEnum<WoodVariant> WOOD = PropertyEnum.create("wood", WoodVariant.class); public BlockTotemBase() { super(Material.WOOD); setRegistryName(Strings.TOTEM_BASE_NAME); setUnlocalizedName(Strings.RESOURCE_PREFIX + Strings.TOTEM_BASE_NAME); setCreativeTab(Totemic.tabsTotem); setHardness(2); setSoundType(SoundType.WOOD); Blocks.FIRE.setFireInfo(this, 5, 5); } @Override public void onBlockClicked(World world, BlockPos pos, EntityPlayer player) { if(!world.isRemote) { TileTotemBase tile = (TileTotemBase) world.getTileEntity(pos); if(tile != null) if(player.getHeldItemMainhand().getItem() == ModItems.totemic_staff && !(tile.getState() instanceof StateTotemEffect)) { ((WorldServer) world).spawnParticle(EnumParticleTypes.SMOKE_NORMAL, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, 16, 0.6D, 0.5D, 0.6D, 0.0D); tile.resetState(); } } } @Override public EnumActionResult onTotemicStaffRightClick(World world, BlockPos pos, EntityPlayer player, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { if(!world.isRemote) return EnumActionResult.SUCCESS; TileTotemBase tile = (TileTotemBase) world.getTileEntity(pos); if(tile.getState() instanceof StateTotemEffect) { player.sendStatusMessage(new TextComponentTranslation("totemicmisc.isDoingNoCeremony"), true); } else if(tile.getState() instanceof StateSelection) { String selectors = ((StateSelection) tile.getState()).getSelectors().stream() .map(instr -> I18n.format(instr.getUnlocalizedName())) .collect(Collectors.joining(", ")); player.sendStatusMessage(new TextComponentTranslation("totemicmisc.isDoingSelection"), false); player.sendStatusMessage(new TextComponentTranslation("totemicmisc.selection", selectors), false); } else if(tile.getState() instanceof StateStartup) { Ceremony ceremony = ((StateStartup) tile.getState()).getCeremony(); player.sendStatusMessage(new TextComponentTranslation("totemicmisc.isDoingStartup"), false); player.sendStatusMessage(new TextComponentTranslation(ceremony.getUnlocalizedName()), false); } else if(tile.getState() instanceof StateCeremonyEffect) { Ceremony ceremony = ((StateCeremonyEffect) tile.getState()).getCeremony(); player.sendStatusMessage(new TextComponentTranslation("totemicmisc.isDoingCeremony"), false); player.sendStatusMessage(new TextComponentTranslation(ceremony.getUnlocalizedName()), false); } return EnumActionResult.SUCCESS; } @Override public int damageDropped(IBlockState state) { return getMetaFromState(state); } @Override public int quantityDropped(Random rand) { return 0; } @Override public void getSubBlocks(CreativeTabs tab, NonNullList<ItemStack> list) { for(int i = 0; i < WoodVariant.values().length; i++) list.add(new ItemStack(this, 1, i)); } @Override protected BlockStateContainer createBlockState() { return new BlockStateContainer(this, WOOD); } @Override public int getMetaFromState(IBlockState state) { return state.getValue(WOOD).ordinal(); } @Override public IBlockState getStateFromMeta(int meta) { return getDefaultState().withProperty(WOOD, WoodVariant.values()[meta]); } @Override public TileEntity createNewTileEntity(World world, int meta) { return new TileTotemBase(); } @Override public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) { return new AxisAlignedBB(0.125F, 0.0F, 0.125F, 0.875F, 1.0F, 0.875F); } @Override public boolean isOpaqueCube(IBlockState state) { return false; } @Override public boolean isFullCube(IBlockState state) { return false; } @Override public BlockFaceShape getBlockFaceShape(IBlockAccess world, IBlockState state, BlockPos pos, EnumFacing facing) { return BlockFaceShape.UNDEFINED; } }
package seedu.address.logic.parser; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.address.logic.parser.CliSyntax.PREFIX_TAG; import java.util.NoSuchElementException; import seedu.address.commons.exceptions.IllegalValueException; import seedu.address.logic.commands.AddCommand; import seedu.address.logic.commands.Command; import seedu.address.logic.commands.IncorrectCommand; import seedu.address.model.task.exceptions.InvalidDurationException; import seedu.address.model.task.exceptions.PastDateTimeException; //@@author A0140023E /** * Parses input arguments and creates a new AddCommand object */ public class AddCommandParser { /** * Parses the given {@code String} of arguments in the context of the AddCommand * and returns an AddCommand object for execution. */ public Command parse(String args) { DateTimeExtractor dateTimeExtractor = new DateTimeExtractor(args); // TODO Returns an exception in a method? Doesn't make sense // Returns a string? seems brittle, therefore to rewrite the class to preserve state try { // process StartEndDateTime first because it is more constrained dateTimeExtractor.processStartEndDateTime(); } catch (PastDateTimeException e) { return new IncorrectCommand(e.getMessage()); } catch (InvalidDurationException e) { return new IncorrectCommand(e.getMessage()); } catch (IllegalValueException e) { // Dates can't be parsed so we silently skip first // all other exceptions have been handled // Pass rose from Uncle to Jane by tmr // we should not return an error because that case is a valid task System.out.println("No date is found for start and end date"); } // TODO Returns an exception in a method? Doesn't make sense // Returns a string? seems brittle try { dateTimeExtractor.processDeadline(); } catch (PastDateTimeException e) { return new IncorrectCommand(e.getMessage()); } catch (IllegalValueException e) { // No date is found so we silently skip System.out.println("No date found for deadline!"); } // TODO ArgumentTokenizer became very irrelevant in this class but is it still relevant for other classes? ArgumentTokenizer argsTokenizer = new ArgumentTokenizer(PREFIX_TAG); argsTokenizer.tokenize(dateTimeExtractor.getProcessedArgs()); try { String nameArgs = argsTokenizer.getPreamble().get(); return new AddCommand(nameArgs, dateTimeExtractor.getProcessedDeadline(), dateTimeExtractor.getProcessedStartEndDateTime(), ParserUtil.toSet(argsTokenizer.getAllValues(PREFIX_TAG))); } catch (NoSuchElementException nsee) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE)); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } }
package seedu.taskitty.logic.commands; import seedu.taskitty.commons.core.Messages; import seedu.taskitty.commons.core.UnmodifiableObservableList; import seedu.taskitty.model.task.ReadOnlyTask; import seedu.taskitty.model.task.UniqueTaskList.TaskNotFoundException; /** * Deletes a task identified using it's last displayed index from the task manager. */ public class DeleteCommand extends Command { public static final String COMMAND_WORD = "delete"; public static final String CATEGORY_CHARS = "t|d|e"; public static final int DEFAULT_INDEX = 0; public static final String[] CATEGORIES = {"Todo", "Deadline", "Event"}; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Deletes the task identified by the category character and index number used in the last task listing.\n" + "Parameters: CATEGORY(default to 't' if not given or incorrect) INDEX (must be a positive integer)\n" + "Example: " + COMMAND_WORD + " " + CATEGORY_CHARS + " 1"; public static final String MESSAGE_DELETE_TASK_SUCCESS = "Deleted" + " %1$s: %2$s"; public final int categoryIndex; public final int targetIndex; public DeleteCommand(int targetIndex) { // default to Todo category if no given category this(targetIndex, DEFAULT_INDEX); } public DeleteCommand(int targetIndex, int categoryIndex) { this.targetIndex = targetIndex; this.categoryIndex = categoryIndex; } @Override public CommandResult execute() { assert categoryIndex >= 0 && categoryIndex < 3; UnmodifiableObservableList<ReadOnlyTask> lastShownList = model.getFilteredTaskList(); if (lastShownList.size() < targetIndex) { indicateAttemptToExecuteIncorrectCommand(); return new CommandResult(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX); } ReadOnlyTask taskToDelete = lastShownList.get(targetIndex - 1); try { model.deleteTask(taskToDelete); } catch (TaskNotFoundException pnfe) { assert false : "The target task cannot be missing"; } return new CommandResult(String.format(MESSAGE_DELETE_TASK_SUCCESS, CATEGORIES[categoryIndex], taskToDelete)); } }
package selling.sunshine.controller; import com.alibaba.fastjson.JSONObject; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import selling.sunshine.form.*; import selling.sunshine.model.*; import selling.sunshine.pagination.DataTablePage; import selling.sunshine.pagination.DataTableParam; import selling.sunshine.service.*; import selling.sunshine.utils.*; import javax.validation.Valid; import java.net.URLEncoder; import java.util.*; @RestController @RequestMapping("/agent") public class AgentController { private Logger logger = LoggerFactory.getLogger(AgentController.class); @Autowired private AgentService agentService; @Autowired private OrderService orderService; @Autowired private CommodityService commodityService; @Autowired private ToolService toolService; @Autowired private CustomerService customerService; @Autowired private BillService billService; @Autowired private RefundService refundService; @Autowired private ShipmentService shipmentService; /** * ,, * * @param code * @param state * @return */ @RequestMapping(method = RequestMethod.GET, value = "/bind") public ModelAndView bind(String code, String state) { ModelAndView view = new ModelAndView(); if (StringUtils.isEmpty(code) || StringUtils.isEmpty(state)) { Prompt prompt = new Prompt(PromptCode.WARNING, "", ",", "/agent/bind"); view.addObject("prompt", prompt); view.setViewName("/agent/prompt"); return view; } String openId = WechatUtil.queryOauthOpenId(code); view.addObject("wechat", openId); String url = "http://" + PlatformConfig.getValue("server_url") + "/agent/bind"; String configUrl = url + "?code=" + code + "&state=" + state; try { String shareLink = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + PlatformConfig.getValue("wechat_appid") + "&redirect_uri=" + URLEncoder.encode(url, "utf-8") + "&response_type=code&scope=snsapi_base&state=view#wechat_redirect"; Configuration configuration = WechatConfig.config(configUrl); configuration.setShareLink(shareLink); view.addObject("configuration", configuration); } catch (Exception e) { logger.error(e.getMessage()); } view.setViewName("/agent/wechat/bind"); return view; } /** * , * * @param wechat * @param form * @param result * @return */ @RequestMapping(method = RequestMethod.POST, value = "/bind") public ModelAndView bind(String wechat, @Valid AgentLoginForm form, BindingResult result) { ModelAndView view = new ModelAndView(); if (result.hasErrors() || StringUtils.isEmpty(wechat)) { Prompt prompt = new Prompt(PromptCode.WARNING, "", "", "/agent/bind"); view.addObject("prompt", prompt); view.setViewName("/agent/prompt"); return view; } Map<String, Object> condition = new HashMap<>(); condition.put("wechat", wechat); ResultData fetchResponse = agentService.fetchAgent(condition); if (fetchResponse.getResponseCode() != ResponseCode.RESPONSE_NULL) { Subject subject = SecurityUtils.getSubject(); if (!subject.isAuthenticated()) { subject.login(new UsernamePasswordToken(wechat, "")); } Prompt prompt = new Prompt(PromptCode.WARNING, "", "", "/agent/order/place"); view.addObject("prompt", prompt); view.setViewName("/agent/prompt"); return view; } Agent agent = new Agent(form.getPhone(), form.getPassword()); ResultData loginResponse = agentService.login(agent); if (loginResponse.getResponseCode() != ResponseCode.RESPONSE_OK) { Prompt prompt = new Prompt(PromptCode.WARNING, "", "", "/agent/bind"); view.addObject("prompt", prompt); view.setViewName("/agent/prompt"); return view; } agent = (Agent) loginResponse.getData(); agent.setWechat(wechat); ResultData modifyResponse = agentService.updateAgent(agent); if (modifyResponse.getResponseCode() != ResponseCode.RESPONSE_OK) { Prompt prompt = new Prompt(PromptCode.WARNING, "", ",", "/agent/bind"); view.addObject("prompt", prompt); view.setViewName("/agent/prompt"); return view; } if (!StringUtils.isEmpty(wechat)) { Subject subject = SecurityUtils.getSubject(); if (!subject.isAuthenticated()) { subject.login(new UsernamePasswordToken(wechat, "")); } } Prompt prompt = new Prompt(PromptCode.SUCCESS, "", ",!", "/agent/order/place"); view.addObject("prompt", prompt); view.setViewName("/agent/prompt"); return view; } /** * * * @return */ @RequestMapping(method = RequestMethod.GET, value = "/lethe") public ModelAndView lethe() { ModelAndView view = new ModelAndView(); String url = "http://" + PlatformConfig.getValue("server_url") + "/agent/lethe"; String configUrl = url; try { String shareLink = url; Configuration configuration = WechatConfig.config(configUrl); configuration.setShareLink(shareLink); view.addObject("configuration", configuration); } catch (Exception e) { logger.error(e.getMessage()); } view.setViewName("/agent/lethe"); return view; } /** * , * * @param form * @param result * @return */ @RequestMapping(method = RequestMethod.POST, value = "/lethe") public ModelAndView lethe(@Valid AgentLetheForm form, BindingResult result) { ModelAndView view = new ModelAndView(); if (result.hasErrors()) { Prompt prompt = new Prompt(PromptCode.DANGER, "", "", "/agent/lethe"); view.addObject("prompt", prompt); view.setViewName("/agent/prompt"); return view; } Map<String, Object> condition = new HashMap<>(); condition.put("name", form.getName()); condition.put("phone", form.getPhone()); ResultData fetchResponse = agentService.fetchAgent(condition); if (fetchResponse.getResponseCode() != ResponseCode.RESPONSE_OK) { Prompt prompt = new Prompt(PromptCode.WARNING, "", "", "/agent/lethe"); view.addObject("prompt", prompt); view.setViewName("/agent/prompt"); return view; } Agent agent = ((List<Agent>) fetchResponse.getData()).get(0); ResultData resetResponse = agentService.resetPassword(agent); if (resetResponse.getResponseCode() == ResponseCode.RESPONSE_OK) { Prompt prompt = new Prompt(PromptCode.SUCCESS, "", ",", "/agent/login"); view.addObject("prompt", prompt); view.setViewName("/agent/prompt"); return view; } else { Prompt prompt = new Prompt(PromptCode.WARNING, "", ",", "/agent/lethe"); view.addObject("prompt", prompt); view.setViewName("/agent/prompt"); return view; } } /** * * * @return */ @RequestMapping(method = RequestMethod.GET, value = "/login") public ModelAndView login() { ModelAndView view = new ModelAndView(); String url = "http://" + PlatformConfig.getValue("server_url") + "/agent/login"; String configUrl = url + ""; Configuration configuration = WechatConfig.config(configUrl); configuration.setShareLink(url); view.addObject("configuration", configuration); view.setViewName("/agent/login"); return view; } /** * , * * @param form * @param result * @return */ @RequestMapping(method = RequestMethod.POST, value = "/login") public ModelAndView login(@Valid AgentLoginForm form, BindingResult result) { ModelAndView view = new ModelAndView(); if (result.hasErrors()) { view.setViewName("redirect:/agent/login"); return view; } try { Subject subject = SecurityUtils.getSubject(); if (subject.isAuthenticated()) { view.setViewName("redirect:/agent/order/place"); return view; } subject.login(new UsernamePasswordToken(form.getPhone(), form.getPassword())); } catch (Exception e) { view.setViewName("redirect:/agent/login"); return view; } view.setViewName("redirect:/agent/order/place"); return view; } /** * * * @param code * @param state * @return */ @RequestMapping(method = RequestMethod.GET, value = "/register") public ModelAndView register(String code, String state) { ModelAndView view = new ModelAndView(); String url = "http://" + PlatformConfig.getValue("server_url") + "/agent/register"; String configUrl; if (!StringUtils.isEmpty(code) && !StringUtils.isEmpty(code)) { String openId = WechatUtil.queryOauthOpenId(code); configUrl = url + "?code=" + code + "&state=" + state; view.addObject("wechat", openId); } else { configUrl = url + ""; } try { String shareLink = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + PlatformConfig.getValue("wechat_appid") + "&redirect_uri=" + URLEncoder.encode(url, "utf-8") + "&response_type=code&scope=snsapi_base&state=view#wechat_redirect"; Configuration configuration = WechatConfig.config(configUrl); configuration.setShareLink(shareLink); view.addObject("configuration", configuration); } catch (Exception e) { logger.error(e.getMessage()); } view.setViewName("/agent/register"); return view; } /** * * * @param form * @param result * @param attr * @return */ @RequestMapping(method = RequestMethod.POST, value = "/register") public ModelAndView register(@Valid AgentForm form, BindingResult result, RedirectAttributes attr) { ModelAndView view = new ModelAndView(); if (result.hasErrors()) { view.setViewName("redirect:/agent/register"); return view; } try { Agent agent = new Agent(form.getName(), form.getGender(), form.getPhone(), form.getAddress(), form.getPassword(), form.getWechat()); ResultData createResponse = agentService.createAgent(agent); if (createResponse.getResponseCode() == ResponseCode.RESPONSE_OK) { Prompt prompt = new Prompt("", ",", "/agent/login"); view.addObject("prompt", prompt); view.setViewName("/agent/prompt"); return view; } else { view.setViewName("redirect:/agent/register"); return view; } } catch (Exception e) { view.setViewName("redirect:/agent/register"); return view; } } /** * * * @return */ @RequestMapping(method = RequestMethod.GET, value = "/me") public ModelAndView index() { ModelAndView view = new ModelAndView(); Subject subject = SecurityUtils.getSubject(); User user = (User) subject.getPrincipal(); if (user == null || user.getAgent() == null) { view.setViewName("/agent/login"); return view; } String url = "http://" + PlatformConfig.getValue("server_url") + "/agent/me"; String configUrl = url + ""; Configuration configuration = WechatConfig.config(configUrl); configuration.setShareLink(url); view.addObject("configuration", configuration); view.setViewName("/agent/me/index"); return view; } @RequestMapping(method = RequestMethod.GET, value = "/order/place") public ModelAndView placeOrder(String code) { ModelAndView view = new ModelAndView(); if (!StringUtils.isEmpty(code)) { oauth(code); } Subject subject = SecurityUtils.getSubject(); User user = (User) subject.getPrincipal(); if (user == null) { if (!StringUtils.isEmpty(code)) { Prompt prompt = new Prompt(PromptCode.WARNING, "", "", "/agent/login"); view.addObject("prompt", prompt); view.setViewName("/agent/prompt"); return view; } else { view.setViewName("/agent/login"); return view; } } Map<String, Object> condition = new HashMap<>(); condition.put("blockFlag", false); ResultData fetchGoodsResponse = commodityService.fetchCommodity(condition); if (fetchGoodsResponse.getResponseCode() == ResponseCode.RESPONSE_OK) { view.addObject("goods", fetchGoodsResponse.getData()); } condition.clear(); condition.put("agentId", user.getAgent().getAgentId()); condition.put("blockFlag", false); ResultData fetchCustomerResponse = customerService.fetchCustomer(condition); if (fetchCustomerResponse.getResponseCode() == ResponseCode.RESPONSE_OK) { view.addObject("customer", fetchCustomerResponse.getData()); } condition.clear(); ResultData fetchShipmentResponse = shipmentService.fetchShipmentConfig(condition); if (fetchShipmentResponse.getResponseCode() == ResponseCode.RESPONSE_OK) { List<ShipConfig> shipmentList = (List<ShipConfig>) fetchShipmentResponse.getData(); if (shipmentList.isEmpty()) { //shipment view.addObject("hasConfig", false); } else { int currentDay = Calendar.getInstance().get(Calendar.DAY_OF_MONTH); shipmentList.sort(new Comparator<ShipConfig>() { @Override public int compare(ShipConfig ship1, ShipConfig ship2) { return Integer.valueOf(ship1.getDate()).compareTo(Integer.valueOf(ship2.getDate())); } }); int shipDay = 0; boolean isNextMonth = false; for (ShipConfig ship : shipmentList) { if (ship.getDate() > currentDay) { shipDay = ship.getDate(); break; } } if (shipDay == 0) { shipDay = shipmentList.get(0).getDate(); isNextMonth = true; } view.addObject("hasConfig", true); view.addObject("shipDay", shipDay); view.addObject("isNextMonth", isNextMonth); } } condition.clear(); condition.put("agentId", user.getAgent().getAgentId()); ResultData queryAgentResponse = agentService.fetchAgent(condition); Agent agent = ((List<Agent>) queryAgentResponse.getData()).get(0); if (agent.isGranted()) { view.setViewName("/agent/order/place"); return view; } Prompt prompt = new Prompt(PromptCode.WARNING, "", "", "/agent/login"); view.addObject("prompt", prompt); view.setViewName("/agent/prompt"); return view; } @RequestMapping(method = RequestMethod.GET, value = "/order/modify/{orderId}") public ModelAndView modifyOrder(@PathVariable("orderId") String orderId) { ModelAndView view = new ModelAndView(); Subject subject = SecurityUtils.getSubject(); User user = (User) subject.getPrincipal(); if (user == null) { view.setViewName("/agent/login"); return view; } Map<String, Object> condition = new HashMap<>(); condition.put("blockFlag", false); ResultData fetchGoodsResponse = commodityService.fetchCommodity(condition); if (fetchGoodsResponse.getResponseCode() == ResponseCode.RESPONSE_OK) { view.addObject("goods", fetchGoodsResponse.getData()); } condition.clear(); condition.put("agentId", user.getAgent().getAgentId()); condition.put("blockFlag", false); ResultData fetchCustomerResponse = customerService.fetchCustomer(condition); if (fetchCustomerResponse.getResponseCode() == ResponseCode.RESPONSE_OK) { view.addObject("customer", fetchCustomerResponse.getData()); } condition.clear(); condition.put("orderId", orderId); ResultData fetchOrderResponse = orderService.fetchOrder(condition); if (fetchOrderResponse.getResponseCode() == ResponseCode.RESPONSE_OK) { Order order = ((List<Order>) fetchOrderResponse.getData()).get(0); view.addObject("order", order); view.addObject("status", order.getStatus()); } view.addObject("operation", "MODIFY"); condition.clear(); condition.put("agentId", user.getAgent().getAgentId()); ResultData fetchAgentResponse = agentService.fetchAgent(condition); Agent agent = ((List<Agent>) fetchAgentResponse.getData()).get(0); if (agent.isGranted()) { view.setViewName("/agent/order/modify"); return view; } Prompt prompt = new Prompt(PromptCode.WARNING, "", "", "/agent/login"); view.addObject("prompt", prompt); view.setViewName("/agent/prompt"); return view; } @RequestMapping(method = RequestMethod.POST, value = "/order/place/{type}") public ModelAndView placeOrder(@Valid OrderItemForm form, BindingResult result, RedirectAttributes attr, @PathVariable("type") String type) { ModelAndView view = new ModelAndView(); if (result.hasErrors()) { view.setViewName("redirect:/agent/order/place"); return view; } Subject subject = SecurityUtils.getSubject(); User user = (User) subject.getPrincipal(); if (user == null) { view.setViewName("/agent/login"); return view; } List<OrderItem> orderItems = new ArrayList<OrderItem>(); int length = form.getCustomerId().length; Order order = new Order(); order.setAgent(user.getAgent()); double order_price = 0; for (int i = 0; i < length; i++) { String goodsId = form.getGoodsId()[i]; String customerId = form.getCustomerId()[i]; int goodsQuantity = Integer.parseInt(form.getGoodsQuantity()[i]); double orderItemPrice = 0;//OrderItem Map<String, Object> goodsCondition = new HashMap<String, Object>(); goodsCondition.put("goodsId", goodsId); ResultData goodsData = commodityService.fetchCommodity(goodsCondition); Goods goods = null; if (goodsData.getResponseCode() == ResponseCode.RESPONSE_OK) { List<Goods> goodsList = (List<Goods>) goodsData.getData(); if (goodsList.size() != 1) { Prompt prompt = new Prompt(PromptCode.WARNING, "", "", "/agent/order/place"); attr.addFlashAttribute("prompt", prompt); view.setViewName("redirect:/agent/prompt"); return view; } goods = goodsList.get(0); } else { Prompt prompt = new Prompt(PromptCode.WARNING, "", "", "/agent/order/place"); attr.addFlashAttribute("prompt", prompt); view.setViewName("redirect:/agent/prompt"); return view; } orderItemPrice = goods.getPrice() * goodsQuantity;//OrderItem order_price += orderItemPrice;//Order OrderItem orderItem = new OrderItem(customerId, goodsId, goodsQuantity, orderItemPrice);//OrderItem orderItems.add(orderItem); } order.setOrderItems(orderItems);//Order order.setPrice(order_price); switch (type) { case "save": order.setStatus(OrderStatus.SAVED); break; case "submit": order.setStatus(OrderStatus.SUBMITTED); break; default: order.setStatus(OrderStatus.SAVED); } ResultData fetchResponse = orderService.placeOrder(order); if (fetchResponse.getResponseCode() == ResponseCode.RESPONSE_OK) { if (type.equals("save")) { Prompt prompt = new Prompt("", "", "/agent/order/manage/0"); attr.addFlashAttribute("prompt", prompt); view.setViewName("redirect:/agent/prompt"); } else if (type.equals("submit")) { view.setViewName("redirect:/order/pay/" + order.getOrderId()); } return view; } Prompt prompt = new Prompt(PromptCode.WARNING, "", "", "/agent/order/manage/0"); attr.addFlashAttribute("prompt", prompt); view.setViewName("redirect:/agent/prompt"); return view; } @RequestMapping(method = RequestMethod.GET, value = "/order/manage/{type}") public ModelAndView manageOrder(@PathVariable("type") String type) { ModelAndView view = new ModelAndView(); view.addObject("type", type); view.setViewName("/agent/order/manage"); return view; } @ResponseBody @RequestMapping(method = RequestMethod.GET, value = "/order/list/{type}") public ResultData viewOrderList(@PathVariable("type") String type) { Subject subject = SecurityUtils.getSubject(); User user = (User) subject.getPrincipal(); ResultData result = new ResultData(); if (user == null) { result.setResponseCode(ResponseCode.RESPONSE_ERROR); result.setDescription(""); return result; } List<SortRule> orderBy = new ArrayList<SortRule>(); orderBy.add(new SortRule("create_time", "desc")); Map<String, Object> condition = new HashMap<String, Object>(); condition.put("agentId", user.getAgent().getAgentId()); condition.put("status", type); condition.put("sort", orderBy); condition.put("blockFlag", false); ResultData fetchResponse = orderService.fetchOrder(condition); if (fetchResponse.getResponseCode() == ResponseCode.RESPONSE_OK) { result.setData(fetchResponse.getData()); } else { result.setResponseCode(fetchResponse.getResponseCode()); result.setDescription(fetchResponse.getDescription()); } return result; } @RequestMapping(method = RequestMethod.GET, value = "/order/detail/{orderId}") public ModelAndView viewOrder(@PathVariable("orderId") String orderId) { ModelAndView view = new ModelAndView(); Subject subject = SecurityUtils.getSubject(); User user = (User) subject.getPrincipal(); if (user == null) { view.setViewName("/agent/login"); return view; } Map<String, Object> condition = new HashMap<String, Object>(); condition.put("agentId", user.getAgent().getAgentId()); condition.put("orderId", orderId); ResultData fetchOrderResponse = orderService.fetchOrder(condition); Order order = ((List<Order>) fetchOrderResponse.getData()).get(0); view.addObject("order", order); view.addObject("status", order.getStatus()); view.addObject("operation", "VIEW"); view.setViewName("/agent/order/modify"); return view; } @RequestMapping(method = RequestMethod.GET, value = "/customer/manage") public ModelAndView manageCustomer() { ModelAndView view = new ModelAndView(); Subject subject = SecurityUtils.getSubject(); User user = (User) subject.getPrincipal(); if (user == null) { view.setViewName("/agent/login"); return view; } //Agent Map<String, Object> condition = new HashMap<>(); condition.put("agentId", user.getAgent().getAgentId()); condition.put("blockFlag", false); ResultData fetchResposne = agentService.fetchAgent(condition); if (fetchResposne.getResponseCode() == ResponseCode.RESPONSE_OK) { Agent agent = ((List<Agent>) fetchResposne.getData()).get(0); view.addObject("agent", agent); } view.setViewName("/agent/customer/manage"); return view; } @ResponseBody @RequestMapping(method = RequestMethod.POST, value = "/customer/list") public ResultData viewCustomerList() { ResultData result = new ResultData(); Subject subject = SecurityUtils.getSubject(); User user = (User) subject.getPrincipal(); if (user == null) { result.setResponseCode(ResponseCode.RESPONSE_ERROR); result.setDescription(""); return result; } Map<String, Object> condition = new HashMap<>(); condition.put("agentId", user.getAgent().getAgentId()); condition.put("blockFlag", false); ResultData fetchResponse = customerService.fetchCustomer(condition); if (fetchResponse.getResponseCode() == ResponseCode.RESPONSE_OK) { result.setData(fetchResponse.getData()); } else { result.setResponseCode(fetchResponse.getResponseCode()); result.setDescription(fetchResponse.getDescription()); } return result; } @RequestMapping(method = RequestMethod.GET, value = "/statement") public ModelAndView statement() { ModelAndView view = new ModelAndView(); Subject subject = SecurityUtils.getSubject(); User user = (User) subject.getPrincipal(); if (user == null) { view.setViewName("/agent/login"); return view; } Map<String, Object> condition = new HashMap<String, Object>(); condition.put("agentId", user.getAgent().getAgentId()); ResultData fetchAgentResponse = agentService.fetchAgent(condition); if (fetchAgentResponse.getResponseCode() != ResponseCode.RESPONSE_OK) { return view; } Agent agent = ((List<Agent>) fetchAgentResponse.getData()).get(0); view.addObject("agent", agent); ResultData fetchRefundRecordResponse = refundService.fetchRefundRecord(condition); if (fetchRefundRecordResponse.getResponseCode() != ResponseCode.RESPONSE_OK) { return view; } List<RefundRecord> refundRecords = (List<RefundRecord>) fetchRefundRecordResponse.getData(); view.addObject("refundRecords", refundRecords); view.setViewName("/agent/account/statement"); return view; } @RequestMapping(method = RequestMethod.GET, value = "/refundConfig") public ModelAndView refundConfig() { ModelAndView view = new ModelAndView(); // Map<String, Object> condition = new HashMap<String, Object>(); // ResultData fetchRefundData = refundService.fetchRefundConfig(condition); // if (fetchRefundData.getResponseCode() != ResponseCode.RESPONSE_OK) { // return view; // List<RefundConfig> configs = (List<RefundConfig>) fetchRefundData.getData(); view.setViewName("/agent/etc/refund_config"); return view; } @RequestMapping(method = RequestMethod.GET, value = "/contact") public ModelAndView contact() { ModelAndView view = new ModelAndView(); view.setViewName("/agent/etc/contact"); return view; } @RequestMapping(method = RequestMethod.GET, value = "/modifypassword") public ModelAndView modifyPassword() { ModelAndView view = new ModelAndView(); view.setViewName("/agent/etc/modify_password"); return view; } @RequestMapping(method = RequestMethod.POST, value = "modifypassword") public ModelAndView modifyPassword(@Valid PasswordForm form, BindingResult result) { ModelAndView view = new ModelAndView(); if (result.hasErrors() || StringUtils.isEmpty(form.getPassword()) || !form.getPassword().equals(form.getPassword2())) { Prompt prompt = new Prompt(PromptCode.WARNING, "", ",", "/agent/modifypassword"); view.addObject("prompt", prompt); view.setViewName("/agent/prompt"); return view; } Subject subject = SecurityUtils.getSubject(); User user = (User) subject.getPrincipal(); Map<String, Object> condition = new HashMap<>(); if (user != null) { selling.sunshine.model.lite.Agent agent = user.getAgent(); condition.put("agentId", agent.getAgentId()); condition.put("blockFlag", false); Agent target = ((List<Agent>) agentService.fetchAgent(condition).getData()).get(0); ResultData modiPassResponse = agentService.modifyPassword(target, form.getPassword()); if (modiPassResponse.getResponseCode() != ResponseCode.RESPONSE_OK) { Prompt prompt = new Prompt(PromptCode.WARNING, "", ",", "/agent/modifypassword"); view.addObject("prompt", prompt); view.setViewName("/agent/prompt"); return view; } subject.logout(); Prompt prompt = new Prompt(PromptCode.SUCCESS, "", ",,", "/agent/login"); view.addObject("prompt", prompt); view.setViewName("/agent/prompt"); return view; } else { view.setViewName("/agent/login"); return view; } } @RequestMapping(method = RequestMethod.GET, value = "/prompt") public ModelAndView prompt() { ModelAndView view = new ModelAndView(); view.setViewName("/agent/prompt"); return view; } @RequestMapping(method = RequestMethod.GET, value = "/check") public ModelAndView check() { ModelAndView view = new ModelAndView(); view.setViewName("/backend/agent/check"); return view; } @ResponseBody @RequestMapping(method = RequestMethod.POST, value = "/check") public DataTablePage<Agent> check(DataTableParam param) { DataTablePage<Agent> result = new DataTablePage<Agent>(param); if (StringUtils.isEmpty(param)) { return result; } Map<String, Object> condition = new HashMap<String, Object>(); condition.put("granted", false); ResultData fetchResponse = agentService.fetchAgent(condition, param); if (fetchResponse.getResponseCode() == ResponseCode.RESPONSE_OK) { result = (DataTablePage<Agent>) fetchResponse.getData(); } return result; } @RequestMapping(method = RequestMethod.POST, value = "/grant") public ModelAndView grant(String agentId) { ModelAndView view = new ModelAndView(); if (StringUtils.isEmpty(agentId)) { view.setViewName("redirect:/agent/check"); return view; } Agent agent = new Agent(); agent.setAgentId(agentId); agent.setGranted(true); ResultData updateResponse = agentService.updateAgent(agent); if (updateResponse.getResponseCode() != ResponseCode.RESPONSE_OK) { view.setViewName("redirect:/agent/check"); return view; } view.setViewName("redirect:/agent/check"); return view; } @RequestMapping(method = RequestMethod.GET, value = "/overview") public ModelAndView overview() { ModelAndView view = new ModelAndView(); view.setViewName("/backend/agent/overview"); return view; } @RequestMapping(method = RequestMethod.POST, value = "/overview") public DataTablePage<Agent> overview(DataTableParam param) { DataTablePage<Agent> result = new DataTablePage<>(param); if (StringUtils.isEmpty(param)) { return result; } Map<String, Object> condition = new HashMap<>(); condition.put("granted", true); List<SortRule> rule = new ArrayList<>(); rule.add(new SortRule("create_time", "desc")); condition.put("sort", rule); logger.debug(JSONObject.toJSONString(condition)); ResultData fetchResponse = agentService.fetchAgent(condition, param); if (fetchResponse.getResponseCode() == ResponseCode.RESPONSE_OK) { result = (DataTablePage<Agent>) fetchResponse.getData(); } return result; } /** * codeOAuth, * * @param code */ private void oauth(String code) { if (!StringUtils.isEmpty(code)) { try { String openId = WechatUtil.queryOauthOpenId(code); if (!StringUtils.isEmpty(openId)) { Subject subject = SecurityUtils.getSubject(); if (!subject.isAuthenticated()) { subject.login(new UsernamePasswordToken(openId, "")); } } } catch (Exception e) { logger.error(e.getMessage()); } } } }
// modification, are permitted provided that the following conditions are met: // documentation and/or other materials provided with the distribution. // 3. All advertising materials mentioning features or use of this software // must display the following acknowledgement: // This product includes software developed by CDS Networks, Inc. // 4. The name of CDS Networks, Inc. may not be used to endorse or promote // products derived from this software without specific prior // THIS SOFTWARE IS PROVIDED BY CDS NETWORKS, INC. ``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 CDS NETWORKS, INC. 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.sourceforge.jtds.jdbc; import java.sql.*; import java.math.BigDecimal; import java.util.Calendar; /** * CallableStatement is used to execute SQL stored procedures. * <p> * JDBC provides a stored procedure SQL escape that allows stored procedures to * be called in a standard way for all RDBMS's. This escape syntax has one form * that includes a result parameter and one that does not. If used, the result * parameter must be registered as an OUT parameter. The other parameters may * be used for input, output or both. Parameters are refered to sequentially, * by number. The first parameter is 1. * <p> * <code> * {?= call &lt;procedure-name&gt; [<arg1>,<arg2>, ...]}<br> * {call &lt;procedure-name&gt; [<arg1>,<arg2>, ...]} * </code> * <p> * IN parameter values are set using the set methods inherited from * PreparedStatement. The type of all OUT parameters must be registered prior * to executing the stored procedure; their values are retrieved after * execution via the get methods provided here. * <p> * A Callable statement may return a ResultSet or multiple ResultSets. Multiple * ResultSets are handled using operations inherited from Statement. * <p> * For maximum portability, a call's ResultSets and update counts should be * processed prior to getting the values of output parameters. * * @see Connection#prepareCall * @see ResultSet * @version $Id: CallableStatement_base.java,v 1.22 2004-04-21 19:45:13 bheineman Exp $ */ public class CallableStatement_base extends PreparedStatement_base implements java.sql.CallableStatement { public final static String cvsVersion = "$Id: CallableStatement_base.java,v 1.22 2004-04-21 19:45:13 bheineman Exp $"; private final static int ACCESS_UNKNOWN = 0; private final static int ACCESS_ORDINAL = 1; private final static int ACCESS_NAMED = 2; private String procedureName = null; private boolean lastWasNull = false; private int lastOutParam = -1; /** * Set to <code>ACCESS_NAMED</code> if this * <code>CallableStatement</code> is using named parameters, * <code>ACCESS_ORDINAL</code> if using ordinal * parameters and <code>ACCESS_UNKNOWN</code> if no parameter has * been set yet (and any of the two access types is still possible). */ private int accessType = ACCESS_UNKNOWN; /** * Return value of the procedure call. */ private Integer retVal = null; /** * Set if the procedure call should return a value (i.e the SQL string is * of the form &quot;{&#63=call &#133}&quot;. */ private boolean haveRetVal = false; public CallableStatement_base(TdsConnection conn_, String sql) throws SQLException { this(conn_, sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); } public CallableStatement_base(TdsConnection conn_, String sql, int type, int concurrency) throws SQLException { super(conn_, type, concurrency); // Remove any extra whitespace for comparisons. sql = sql.trim(); StringBuffer result = new StringBuffer(sql.length()); int numberOfParameters = EscapeProcessor.parameterNativeSQL(sql, result); rawQueryString = result.toString(); int length = rawQueryString.length(); int i = 0; // Skip non-whitespace characters. for (; i < length && !Character.isWhitespace(rawQueryString.charAt(i)); i++); String call = rawQueryString.substring(0, i); if (!call.equalsIgnoreCase("exec") && !call.equalsIgnoreCase("execute")) { rawQueryString = "exec " + rawQueryString; length = rawQueryString.length(); i = 4; } boolean inString = false; // Find start of stored procedure name or return variable. for (; i < length; i++) { final char ch = rawQueryString.charAt(i); if (ch == '[' || ch == '"') { inString = true; break; } else if (ch != ' ' // space && ch != '\t' // tab && ch != '\n' // newline && ch != '\r' // carriage-return && ch != '\f') { // form-feed // A non ANSI SQL-92 whitespace character was found break; } } int pos = i; if (rawQueryString.charAt(i) == '?') { int retPos = i; // Skip non-whitespace characters. for (; i < length && rawQueryString.charAt(i) != '='; i++); if (rawQueryString.charAt(i) == '=') { rawQueryString = rawQueryString.substring(0, retPos) + rawQueryString.substring(i + 1); numberOfParameters length = rawQueryString.length(); haveRetVal = true; } else { throw new SQLException("Invalid return value syntax; expected to find '=': " + sql); } } // Find the end of the procedure name for (i++; i < length; i++) { final char ch = rawQueryString.charAt(i); // While this parsing does not validate that a quoted identifier ends // with the the same style as it was opened, it does detect the procedure // name properly and lets the database validate the identifiers // (which it does anyway). if (inString) { if (ch == ']' || ch == '"') { inString = false; } } else { if (ch == '[' || ch == '"') { inString = true; } else if (ch == ' ' // space || ch == '\t' // tab || ch == '\n' // newline || ch == '\r' // carriage-return || ch == '\f') { // form-feed // An ANSI SQL-92 whitespace character was found break; } } } if (inString) { throw new SQLException("Invalid procedure name detected; expected " + "idendifer to be closed properly by \" or ]: " + sql); } // Skip non-whitespace characters. for (; i < length && !Character.isWhitespace(rawQueryString.charAt(i)); i++); procedureName = rawQueryString.substring(pos, i); if (procedureName.length() == 0) { throw new SQLException("Unable to locate procedure name in: " + sql); } parameterList = new ParameterListItem[numberOfParameters]; for (int x = 0; x < numberOfParameters; x++) { parameterList[x] = new ParameterListItem(); } } /** * Check that the <code>CallableStatement</code> is using the expected * access type. There are two possible access types, ordinal (as in * <code>setString(1, "value")</code>) and named (as in * <code>setString("@param", "value")</code>), and access to parameters * must be consistent in using only one of them. Mixing access types will * generate an <code>SQLException</code> and that is what this method is * enforcing. * * @param expected one of <code>ACCESS_ORDINAL</code> and * <code>ACCESS_NAMED</code>; if the current access * type is <code>ACCESS_UNKNOWN</code>, then it is set * to this value; otherwise if doesn't match this value * an <code>SQLException</code> is thrown * @throws SQLException if the current access type is not * <code>ACCESS_UNKNOWN</code> and is different from * <code>expected</code> */ private void checkAccessType(int expected) throws SQLException { if (accessType != expected) { if (accessType == ACCESS_UNKNOWN) { accessType = expected; } else { throw new SQLException( "Named and ordinal parameter access cannot be mixed.", "HY000"); } } } private Object getParam(int index) throws SQLException { // TODO We should check for access type, too. We can't do it in the // current implementation but we should be able to if we move the // whole conversion for getters and setters in a single place, say // ParameterUtils // checkAccessType(ACCESS_ORDINAL); // If the originally provided SQL string started with ?= then the // actual positions are shifted to the left and 1 is the return value if (haveRetVal) { if (index == 1) { return retVal; } --index; } if (index < 1) { throw new SQLException("Invalid parameter index " + index + ". JDBC indexes start at 1."); } if (index > parameterList.length) { throw new SQLException("Invalid parameter index " + index + ". This statement only has " + parameterList.length + " parameters."); } // JDBC indexes start at 1, java array indexes start at 0 :-( --index; lastWasNull = (parameterList[index] == null); return parameterList[index].value; } /** * Override <code>PreparedStatement_base.setParam</code> to take into * account an eventual output parameter (if there is one, the parameters * are actually shifted one position). */ protected void setParam(int index, Object value, int type, int scale) throws SQLException { // TODO We should check for access type, too. We can't do it in the // current implementation but we should be able to if we move the // whole conversion for getters and setters in a single place, say // ParameterUtils // checkAccessType(ACCESS_ORDINAL); super.setParam(haveRetVal ? index - 1 : index, value, type, scale); } private void addOutputValue(Object value) throws SQLException { for (lastOutParam++; lastOutParam<parameterList.length; lastOutParam++) { if (parameterList[lastOutParam].isOutput) { parameterList[lastOutParam].value = value; return; } } throw new SQLException("More output params than expected.", "HY000"); } // called by TdsStatement.moreResults protected boolean handleRetStat(PacketRetStatResult packet) { if (!super.handleRetStat(packet)) { retVal = new Integer(packet.getRetStat()); } return true; } protected boolean handleParamResult(PacketOutputParamResult packet) throws SQLException { if (!super.handleParamResult(packet)) { addOutputValue(packet.value); } return true; } public BigDecimal getBigDecimal(int parameterIndex, int scale) throws SQLException { NotImplemented(); return null; } public boolean getBoolean(int parameterIndex) throws SQLException { Object value = getParam(parameterIndex); if (value == null) { return false; } try { return ((Boolean) value).booleanValue(); } catch (Exception e) { throw new SQLException("Unable to convert parameter"); } } public byte getByte(int parameterIndex) throws SQLException { Object value = getParam(parameterIndex); if (value == null) { return 0; } try { return ((Number) value).byteValue(); } catch (Exception e) { throw new SQLException("Unable to convert parameter"); } } public byte[] getBytes(int parameterIndex) throws SQLException { Object value = getParam(parameterIndex); if (value == null) { return null; } try { return (byte[]) value; } catch (Exception e) { throw new SQLException("Unable to convert parameter"); } } public java.sql.Date getDate(int parameterIndex) throws SQLException { NotImplemented(); return null; } public double getDouble(int parameterIndex) throws SQLException { Object value = getParam(parameterIndex); if (value == null) { return 0; } try { return ((Number) value).doubleValue(); } catch (Exception e) { throw new SQLException("Unable to convert parameter"); } } public float getFloat(int parameterIndex) throws SQLException { Object value = getParam(parameterIndex); if (value == null) { return 0; } try { return ((Number) value).floatValue(); } catch (Exception e) { throw new SQLException("Unable to convert parameter"); } } public int getInt(int parameterIndex) throws SQLException { Object value = getParam(parameterIndex); if (value == null) { return 0; } try { return ((Number) value).intValue(); } catch (Exception e) { throw new SQLException("Unable to convert parameter"); } } public long getLong(int parameterIndex) throws SQLException { Object value = getParam(parameterIndex); if (value == null) { return 0; } try { return ((Number) value).longValue(); } catch (Exception e) { throw new SQLException("Unable to convert parameter"); } } // Advanced features: public Object getObject(int parameterIndex) throws SQLException { return getParam(parameterIndex); } public short getShort(int parameterIndex) throws SQLException { Object value = getParam(parameterIndex); if (value == null) { return 0; } try { return ((Number) value).shortValue(); } catch (Exception e) { throw new SQLException("Unable to convert parameter"); } } public String getString(int parameterIndex) throws SQLException { Object value = getParam(parameterIndex); try { return (String) value; } catch (Exception e) { throw new SQLException("Unable to convert parameter"); } } public java.sql.Time getTime(int parameterIndex) throws SQLException { NotImplemented(); return null; } // TODO Implement these methods public java.sql.Timestamp getTimestamp(int parameterIndex) throws SQLException { NotImplemented(); return null; } public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException { registerOutParameter(parameterIndex, sqlType, -1); } public void registerOutParameter(int parameterIndex, int sqlType, int scale) throws SQLException { checkAccessType(ACCESS_ORDINAL); internalRegisterOutParameter(parameterIndex, sqlType, scale); } public void internalRegisterOutParameter(int parameterIndex, int sqlType, int scale) throws SQLException { // SAfe If there is a return value, decrement the parameter index or // simply ignore the call if it's for the return value if (haveRetVal) { if (parameterIndex == 1) { // If it's the return value, it can only be an integral value // of some kind if (sqlType != Types.INTEGER && sqlType != Types.NUMERIC && sqlType != Types.DECIMAL && sqlType != Types.BIGINT) { throw new SQLException("Procedure return value is integer."); } return; } parameterIndex -= 1; } Object value = parameterList[parameterIndex - 1].value; // Call directly the method from PreparedStatement_base, otherwise the // index will be decremented one more time. super.setParam(parameterIndex, null, sqlType, scale); parameterList[parameterIndex - 1].isOutput = true; // Restore the original value; setParam has set it to null. parameterList[parameterIndex - 1].value = value; } public boolean wasNull() throws SQLException { return lastWasNull; } public boolean execute(Tds tds) throws SQLException { closeResults(false); lastOutParam = -1; // Setup the parameter native types and maximum sizes. Don't assign // names to parameters, it's going to crash. ParameterUtils.createParameterMapping( null, parameterList, tds, false); // Execute the stored procedure return internalExecuteCall(procedureName, parameterList, parameterList, tds, warningChain); } public BigDecimal getBigDecimal(int parameterIndex) throws SQLException { NotImplemented(); return null; } public java.sql.Date getDate(int parameterIndex, Calendar cal) throws SQLException { NotImplemented(); return null; } public java.sql.Time getTime(int parameterIndex, Calendar cal) throws SQLException { NotImplemented(); return null; } public java.sql.Timestamp getTimestamp(int parameterIndex, Calendar cal) throws SQLException { NotImplemented(); return null; } public void registerOutParameter(int paramIndex, int sqlType, String typeName) throws SQLException { NotImplemented(); } public Blob getBlob(int i) throws SQLException { NotImplemented(); return null; } public Clob getClob(int i) throws SQLException { NotImplemented(); return null; } public Object getObject(int i, java.util.Map map) throws SQLException { NotImplemented(); return null; } public Ref getRef(int i) throws SQLException { NotImplemented(); return null; } public Array getArray(int i) throws SQLException { NotImplemented(); return null; } protected int getParamNo(String parameterName, boolean checkIsOut, boolean assign) throws SQLException { checkAccessType(ACCESS_NAMED); // Check if it's the return status (its name is @RETURN_STATUS because // that's how getColumns returns it and that's what spec says should be // used as parameter name). if (parameterName.equalsIgnoreCase("@return_status")) { // if (assign) { // throw new SQLException("Parameter type is OUT: " + parameterName, // "HY000"); if (haveRetVal) { return 1; } else { // We could maybe provide the return status even if it was not // registered as output parameter throw new SQLException("No such parameter: " + parameterName, "HY000"); } } // Not the return status, look for it through the list and if not found // and assign is true, then assign it // TODO Improve the search by using a HashMap instead? for (int i = 0; i < parameterList.length; ++i) { String formalName = parameterList[i].formalName; // If the parameter name not found, we should add it if (formalName == null) { // If not assigning parameter names, break and throw the // exception if (!assign) { break; } // Ok to assign the parameter name and return the position parameterList[i].formalName = parameterName; return i + (haveRetVal ? 2 : 1); } if (formalName.equalsIgnoreCase(parameterName)) { // TODO Should we keep this check? It works with ordinals. if (checkIsOut) { if (!parameterList[i].isOutput) { throw new SQLException( "Parameter type is IN: " + parameterName, "HY000"); } } return i + (haveRetVal ? 2 : 1); } } throw new SQLException("No such parameter: " + parameterName, "HY000"); } public void registerOutParameter(String parameterName, int sqlType, String typeName) throws SQLException { NotImplemented(); } public void registerOutParameter(String parameterName, int sqlType, int scale) throws SQLException { internalRegisterOutParameter( getParamNo(parameterName, false, true), sqlType, scale); } public void registerOutParameter(String parameterName, int sqlType) throws SQLException { registerOutParameter(parameterName, sqlType, -1); } public java.sql.Array getArray(String parameterName) throws SQLException { return getArray(getParamNo(parameterName, true, false)); } public java.math.BigDecimal getBigDecimal(String parameterName) throws SQLException { return getBigDecimal(getParamNo(parameterName, true, false)); } public java.sql.Blob getBlob(String parameterName) throws SQLException { return getBlob(getParamNo(parameterName, true, false)); } public boolean getBoolean(String parameterName) throws SQLException { return getBoolean(getParamNo(parameterName, true, false)); } public byte getByte(String parameterName) throws SQLException { return getByte(getParamNo(parameterName, true, false)); } public byte[] getBytes(String parameterName) throws SQLException { return getBytes(getParamNo(parameterName, true, false)); } public java.sql.Clob getClob(String parameterName) throws SQLException { return getClob(getParamNo(parameterName, true, false)); } public java.sql.Date getDate(String parameterName) throws SQLException { return getDate(getParamNo(parameterName, true, false)); } public java.sql.Date getDate(String parameterName, java.util.Calendar cal) throws SQLException { return getDate(getParamNo(parameterName, true, false), cal); } public double getDouble(String parameterName) throws SQLException { return getDouble(getParamNo(parameterName, true, false)); } public float getFloat(String parameterName) throws SQLException { return getFloat(getParamNo(parameterName, true, false)); } public int getInt(String parameterName) throws SQLException { return getInt(getParamNo(parameterName, true, false)); } public long getLong(String parameterName) throws SQLException { return getLong(getParamNo(parameterName, true, false)); } public Object getObject(String parameterName) throws SQLException { return getObject(getParamNo(parameterName, true, false)); } public Object getObject(String parameterName, java.util.Map map) throws SQLException { return getObject(getParamNo(parameterName, true, false), map); } public java.sql.Ref getRef(String parameterName) throws SQLException { return getRef(getParamNo(parameterName, true, false)); } public short getShort(String parameterName) throws SQLException { return getShort(getParamNo(parameterName, true, false)); } public String getString(String parameterName) throws SQLException { return getString(getParamNo(parameterName, true, false)); } public java.sql.Time getTime(String parameterName) throws SQLException { return getTime(getParamNo(parameterName, true, false)); } public java.sql.Time getTime(String parameterName, java.util.Calendar cal) throws SQLException { return getTime(getParamNo(parameterName, true, false), cal); } public java.sql.Timestamp getTimestamp(String parameterName) throws SQLException { return getTimestamp(getParamNo(parameterName, true, false)); } public java.sql.Timestamp getTimestamp(String parameterName, java.util.Calendar cal) throws SQLException { return getTimestamp(getParamNo(parameterName, true, false), cal); } public java.net.URL getURL(int parameterIndex) throws SQLException { NotImplemented(); return null; } public java.net.URL getURL(String parameterName) throws SQLException { return getURL(getParamNo(parameterName, true, false)); } public void setAsciiStream(String parameterName, java.io.InputStream x, int length) throws SQLException { setAsciiStream(getParamNo(parameterName, false, true), x, length); } public void setBigDecimal(String parameterName, java.math.BigDecimal x) throws SQLException { setBigDecimal(getParamNo(parameterName, false, true), x); } public void setBinaryStream(String parameterName, java.io.InputStream x, int length) throws SQLException { setBinaryStream(getParamNo(parameterName, false, true), x, length); } public void setBoolean(String parameterName, boolean x) throws SQLException { setBoolean(getParamNo(parameterName, false, true), x); } public void setByte(String parameterName, byte x) throws SQLException { setByte(getParamNo(parameterName, false, true), x); } public void setBytes(String parameterName, byte[] x) throws SQLException { setBytes(getParamNo(parameterName, false, true), x); } public void setCharacterStream(String parameterName, java.io.Reader x, int length) throws SQLException { setCharacterStream(getParamNo(parameterName, false, true), x, length); } public void setDate(String parameterName, java.sql.Date x) throws SQLException { setDate(getParamNo(parameterName, false, true), x); } public void setDate(String parameterName, java.sql.Date x, java.util.Calendar cal) throws SQLException { setDate(getParamNo(parameterName, false, true), x, cal); } public void setDouble(String parameterName, double x) throws SQLException { setDouble(getParamNo(parameterName, false, true), x); } public void setFloat(String parameterName, float x) throws SQLException { setFloat(getParamNo(parameterName, false, true), x); } public void setInt(String parameterName, int x) throws SQLException { setInt(getParamNo(parameterName, false, true), x); } public void setLong(String parameterName, long x) throws SQLException { setLong(getParamNo(parameterName, false, true), x); } public void setNull(String parameterName, int sqlType) throws SQLException { setNull(getParamNo(parameterName, false, true), sqlType); } public void setNull(String parameterName, int sqlType, String typeName) throws SQLException { setNull(getParamNo(parameterName, false, true), sqlType, typeName); } public void setObject(String parameterName, Object x) throws SQLException { setObject(getParamNo(parameterName, false, true), x); } public void setObject(String parameterName, Object x, int targetSqlType) throws SQLException { setObject(getParamNo(parameterName, false, true), x, targetSqlType); } public void setObject(String parameterName, Object x, int targetSqlType, int scale) throws SQLException { setObject(getParamNo(parameterName, false, true), x, targetSqlType, scale); } public void setShort(String parameterName, short x) throws SQLException { setShort(getParamNo(parameterName, false, true), x); } public void setString(String parameterName, String x) throws SQLException { setString(getParamNo(parameterName, false, true), x); } public void setTime(String parameterName, java.sql.Time x) throws SQLException { setTime(getParamNo(parameterName, false, true), x); } public void setTime(String parameterName, java.sql.Time x, java.util.Calendar cal) throws SQLException { setTime(getParamNo(parameterName, false, true), x, cal); } public void setTimestamp(String parameterName, java.sql.Timestamp x) throws SQLException { setTimestamp(getParamNo(parameterName, false, true), x); } public void setTimestamp(String parameterName, java.sql.Timestamp x, java.util.Calendar cal) throws SQLException { setTimestamp(getParamNo(parameterName, false, true), x, cal); } public void setURL(String parameterName, java.net.URL x) throws SQLException { setURL(getParamNo(parameterName, false, true), x); } public String getProcedureName() { return procedureName; } }
package org.brailleblaster.wordprocessor; import org.eclipse.swt.widgets.*; import org.eclipse.swt.custom.*; import org.eclipse.swt.layout.*; import org.brailleblaster.BBIni; import org.eclipse.swt.printing.*; import org.eclipse.swt.events.*; import nu.xom.*; import nu.xom.Text; import java.io.FileInputStream; import java.io.FileReader; import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.io.Reader; import org.liblouis.liblouisutdml; import org.brailleblaster.util.Notify; import java.io.File; import java.net.URLConnection; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.logging.Logger; import java.util.logging.Level; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.daisy.printing.*; import javax.print.Doc; import javax.print.DocFlavor; import javax.print.DocFlavor.INPUT_STREAM; import javax.print.DocPrintJob; import javax.print.PrintException; import javax.print.PrintService; import javax.print.PrintServiceLookup; import javax.print.SimpleDoc; import javax.print.attribute.DocAttributeSet; import javax.print.attribute.HashDocAttributeSet; import javax.print.attribute.HashPrintRequestAttributeSet; import javax.print.attribute.PrintRequestAttributeSet; import javax.print.attribute.standard.Copies; import javax.xml.parsers.ParserConfigurationException; import org.eclipse.swt.widgets.*; import org.eclipse.swt.graphics.Color; import org.brailleblaster.importers.ImportersManager; import org.brailleblaster.localization.LocaleHandler; import org.brailleblaster.settings.Welcome; import org.brailleblaster.util.FileUtils; import org.brailleblaster.util.YesNoChoice; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.Rectangle; //import org.apache.log4j.Level; import org.apache.tika.Tika; import org.apache.tika.exception.TikaException; import org.apache.tika.io.TikaInputStream; import org.apache.tika.metadata.Metadata; import org.apache.tika.mime.MediaType; import org.apache.tika.parser.AutoDetectParser; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.Parser; import org.apache.tika.sax.ToXMLContentHandler; import org.apache.tika.sax.ToTextContentHandler; import org.xml.sax.SAXException; enum Encodings { ISO_8859_1("ISO-8859-1"), UTF_8("UTF-8"), WINDOWS_1252("WINDOWS-1252"), US_ASCII( "US-ASCII"); private final String encoding; Encodings(String encoding) { this.encoding = encoding; } public String encoding() { return encoding; } } /** * This class manages each document in an MDI environment. It controls the * braille View and the daisy View. */ public class DocumentManager { final Display display; final Shell documentWindow; final int documentNumber; final String docID; int action; int returnReason = 0; FormLayout layout; String documentName = null; boolean documentChanged = false; BBToolBar toolBar; BBMenu menu; RecentDocuments rd; UTD utd; AbstractView activeView; DaisyView daisy; BrailleView braille; BBStatusBar statusBar; boolean exitSelected = false; Document doc = null; NewDocument newDoc; String configFileList = null; static String tempPath = null; boolean haveOpenedFile = false; String translatedFileName = null; String brailleFileName = null; String daisyWorkFile = null; String tikaWorkFile = null; String newDaisyFile = "utdml-doc"; boolean textAndBraille = false; boolean saveUtdml = false; boolean metaContent = false; StyleManager sm; // separate styles from DM liblouisutdml louisutdml; String logFile = "Translate.log"; String configSettings = null; int mode = 0; boolean finished = false; private volatile boolean stopRequested = false; static final boolean[] flags = new boolean[WPManager.getMaxNumDocs()]; // static final String[] runningFiles = new // String[WPManager.getMaxNumDocs()]; static String recentFileName = null; static int recentFileNameIndex = -1; int numLines; int numChars; private Font simBrailleFont, daisyFont; boolean displayBrailleFont = false; int bvLineCount; private boolean firstTime; static int daisyFontHeight = 10; static int brailleFontHeight = 14; static boolean SimBraille = false; static boolean Courier = false; static String altFont = "unibraille29"; static String courierFont = "Courier New"; LocaleHandler lh = new LocaleHandler(); StringBuilder brailleLine = new StringBuilder(8192); StringBuilder daisyLine = new StringBuilder(8192); // character encoding for import static String encoding = null; MediaType mediaType; final String[] compressed = {"application/zip", "application/epub+zip"}; public boolean isNimas; /** * Constructor that sets things up for a new document. */ DocumentManager(Display display, int documentNumber, int action, String documentName) { this.display = display; this.documentNumber = documentNumber; docID = new Integer(documentNumber).toString(); this.action = action; this.documentName = documentName; tempPath = BBIni.getTempFilesPath() + BBIni.getFileSep(); louisutdml = liblouisutdml.getInstance(); documentWindow = new Shell(display, SWT.SHELL_TRIM); // FO setup WP window layout = new FormLayout(); documentWindow.setLayout(layout); rd = new RecentDocuments(this); sm = new StyleManager(this); utd = new UTD(this); menu = new BBMenu(this); toolBar = new BBToolBar(this); /* text window is on the left */ daisy = new DaisyView(documentWindow); braille = new BrailleView(documentWindow); // activeView = (ProtoView)daisy; statusBar = new BBStatusBar(documentWindow); documentWindow.setSize(1000, 700); documentWindow.layout(true, true); documentWindow.addListener(SWT.Close, new Listener() { public void handleEvent(Event event) { setReturn(WP.DocumentClosed); // this way clicking close box is equivalent to the 'close' item // on the menu } }); documentWindow.addListener(SWT.Dispose, new Listener() { public void handleEvent(Event event) { handleShutdown(event); } }); Monitor primary = display.getPrimaryMonitor(); Rectangle bounds = primary.getBounds(); Rectangle rect = documentWindow.getBounds(); int x = bounds.x + ((bounds.width - rect.width) / 2) + (documentNumber * 30); int y = bounds.y + ((bounds.height - rect.height) / 2) + (documentNumber * 30); documentWindow.setLocation(x, y); documentWindow.open(); setWindowTitle(" untitled"); // daisy.view.addModifyListener(daisyMod); /** * for later use braille.view.addModifyListener(brailleMod); **/ /* Find out which scalable fonts are installed */ FontData[] fd = documentWindow.getDisplay().getFontList(null, true); String fn; for (int i = 0; i < fd.length; i++) { fn = fd[i].getName(); if (fn.contentEquals("SimBraille")) { SimBraille = true; break; } ; if (fn.contentEquals(courierFont)) { Courier = true; break; } ; } if (!SimBraille) { String fontPath = BBIni.getBrailleblasterPath() + "/programData/fonts/SimBraille.ttf"; String platform = SWT.getPlatform(); if (platform.equals("win32") || platform.equals("wpf")) { fontPath = BBIni.getBrailleblasterPath() + "\\programData\\fonts\\SimBraille.ttf"; } if (!documentWindow.getDisplay().loadFont(fontPath)) { new Notify(lh.localValue("fontNotLoadedBraille")); } } ; if (Courier) { daisyFont = new Font(documentWindow.getDisplay(), courierFont, daisyFontHeight, SWT.NORMAL); } else { String fontPath = BBIni.getBrailleblasterPath() + "/programData/fonts/" + altFont + ".ttf"; String platform = SWT.getPlatform(); if (platform.equals("win32") || platform.equals("wpf")) { fontPath = BBIni.getBrailleblasterPath() + "\\programData\\fonts\\" + altFont + ".ttf"; } if (!documentWindow.getDisplay().loadFont(fontPath)) { new Notify(lh.localValue("fontNotLoadedText")); } daisyFont = new Font(documentWindow.getDisplay(), altFont, daisyFontHeight, SWT.NORMAL); } daisy.view.setFont(daisyFont); braille.view.setFont(daisyFont); braille.view.setEditable(false); if (documentNumber == 0) { new Welcome(); // This then calls the settings dialogs. } switch (action) { case WP.OpenDocumentGetFile: fileOpen(); break; case WP.DocumentFromCommandLine: openDocument(documentName); break; case WP.OpenDocumentGetRecent: // FO 04 String ext = getFileExt(documentName); if (ext.contentEquals("utd") || ext.contentEquals("xml")) { brailleFileName = getBrailleFileName(); openDocument(documentName); if (ext.contentEquals("utd")) { BBIni.setUtd(true); utd.displayTranslatedFile(documentName, brailleFileName); braille.hasChanged = false; } daisy.hasChanged = false; } else if (ext.contentEquals("zip")) { importZip(getEncodingString()); daisy.hasChanged = true; } else { if (ext.contentEquals("brf")) { openBrf(documentName); setWindowTitle("untitled"); } else { parseImport(documentName, getEncodingString()); setWindowTitle(documentName); } daisy.hasChanged = true; } daisy.view.setFocus(); break; case WP.ImportDocument: importDocument(); break; } boolean stop = false; daisy.view.setFocus(); while (!documentWindow.isDisposed() && (!stop) && (returnReason == 0)) { if (!display.readAndDispatch()) display.sleep(); for (boolean b : flags) { stop |= b; } } // get here if the window is disposed, or someone has a reason if (flags[documentNumber]) { WPManager.setCurDoc(documentNumber); flags[documentNumber] = false; // all should be false now } // Then back to WPManager } /** * Handle application shutdown signal from OS; */ void handleShutdown(Event event) { if (daisy.hasChanged) { YesNoChoice ync = new YesNoChoice(lh.localValue("hasChanged")); if (ync.result == SWT.YES) { fileSave(); } else { daisy.hasChanged = false; braille.hasChanged = false; } } event.doit = true; } /** * Clean up before closing the document. */ void finish() { documentWindow.dispose(); finished = true; } /** * Checks if a return request is valid and does any necessary processing. */ boolean setReturn(int reason) { switch (reason) { case WP.SwitchDocuments: if (WPManager.haveOtherDocuments()) { // System.out.println("Switching to next"); returnReason = reason; flags[documentNumber] = true;// this fires the interrupt return true; } new Notify(lh.localValue("oneDocument")); return false; case WP.NewDocument: returnReason = reason; break; case WP.OpenDocumentGetFile: returnReason = reason; break; case WP.DocumentClosed: returnReason = reason; break; case WP.BBClosed: returnReason = reason; break; default: break; } WPManager.setCurDoc(documentNumber); // FO 27 flags[documentNumber] = true;// this fires the interrupt return true; } /** * This method is called to resume processing on this document after working * on another. */ void resume() { if (documentWindow.isDisposed()) return; documentWindow.forceActive(); boolean stop = false; while (!documentWindow.isDisposed() && (!stop)) { if (!documentWindow.getDisplay().readAndDispatch()) documentWindow.getDisplay().sleep(); for (boolean b : DocumentManager.getflags()) { stop |= b; } } } private void setWindowTitle(String pathName) { int index = pathName.lastIndexOf(File.separatorChar); if (index == -1) { documentWindow.setText("BrailleBlaster " + pathName); } else { documentWindow.setText("BrailleBlaster " + pathName.substring(index + 1)); } } void fileDocument() { newDoc = new NewDocument(); newDoc.fillOutBody(daisy.view); doc = newDoc.getDocument(); } void fileNew() { if (!daisy.view.isVisible()) { activateViews(true); activateMenus(true); daisy.hasChanged = false; braille.hasChanged = false; haveOpenedFile = false; brailleFileName = null; documentName = null; daisy.hasChanged = false; braille.hasChanged = false; doc = null; BBIni.setUtd(false); setWindowTitle(" untitled"); daisy.view.setFocus(); } else { // if (doc != null){ returnReason = WP.NewDocument; flags[documentNumber] = true; // return; } } /* UTD or XML DOCUMENT */ void fileOpen() { if (!daisy.view.isVisible()) { activateViews(true); activateMenus(true); daisy.hasChanged = false; braille.hasChanged = false; haveOpenedFile = false; brailleFileName = null; documentName = null; daisy.hasChanged = false; braille.hasChanged = false; doc = null; BBIni.setUtd(false); setWindowTitle(" untitled"); daisy.view.setFocus(); } ; if ((doc != null) || daisy.hasChanged) { returnReason = WP.OpenDocumentGetFile; flags[documentNumber] = true; return; } haveOpenedFile = false; metaContent = false; Shell shell = new Shell(display, SWT.DIALOG_TRIM); FileDialog dialog = new FileDialog(shell, SWT.OPEN); String filterPath = "/"; String[] filterNames = new String[] { "UTDML", "XML" }; String[] filterExtensions = new String[] { "*.utd", "*.xml" }; String platform = SWT.getPlatform(); if (platform.equals("win32") || platform.equals("wpf")) { filterPath = System.getProperty("user.home"); if (filterPath == null) filterPath = "c:\\"; } dialog.setFilterNames(filterNames); dialog.setFilterExtensions(filterExtensions); dialog.setFilterPath(filterPath); documentName = dialog.open(); shell.dispose(); if (documentName != null) { openDocument(documentName); String ext = getFileExt(documentName); if (ext.contentEquals("utd")) { BBIni.setUtd(true); metaContent = true; haveOpenedFile = true; brailleFileName = getBrailleFileName(); utd.displayTranslatedFile(documentName, brailleFileName); } braille.view.setEditable(false); daisy.hasChanged = false; braille.hasChanged = false; // daisy.view.addModifyListener(daisyMod); setWindowTitle(documentName); daisy.view.setFocus(); } } void recentOpen(String path) { if (!daisy.view.isVisible()) { activateViews(true); activateMenus(true); daisy.hasChanged = false; braille.hasChanged = false; haveOpenedFile = false; brailleFileName = null; documentName = null; daisy.hasChanged = false; braille.hasChanged = false; doc = null; BBIni.setUtd(false); } if (doc != null) { // see if this recent document is already opened in current windows // set recentFileNameIndex = WPManager.isRunning(path); if (recentFileNameIndex != -1) { returnReason = WP.SwitchDocuments; flags[documentNumber] = true; return; } recentFileName = path; returnReason = WP.OpenDocumentGetRecent; flags[documentNumber] = true; return; } documentName = path; braille.view.setEditable(false); String ext = getFileExt(documentName); if (ext.contentEquals("utd") || ext.contentEquals("xml")) { brailleFileName = getBrailleFileName(); openDocument(documentName); if (ext.contentEquals("utd")) { BBIni.setUtd(true); utd.displayTranslatedFile(documentName, brailleFileName); braille.hasChanged = false; } daisy.hasChanged = false; } else if (ext.contentEquals("zip")) { importZip(getEncodingString()); } else { if (ext.contentEquals("brf")) { openBrf(documentName); setWindowTitle("untitled"); } else { parseImport(documentName, getEncodingString()); setWindowTitle(documentName); } } daisy.view.setFocus(); } void openDocument(String fileName) { Builder parser = new Builder(); try { doc = parser.build(fileName); } catch (ParsingException e) { new Notify(lh.localValue("malformedDocument")); return; } catch (IOException e) { new Notify(lh.localValue("couldNotOpen") + " " + documentName); return; } // add this file to recentDocList if ( !((fileName.contains("-tempdoc.xml")) || (fileName.contains(tempPath))) ) { rd.addDocument(fileName); } if ((getFileExt(documentName).contentEquals("brf")) || (getFileExt(documentName).contentEquals("brl"))) { setWindowTitle("untitled"); } else { setWindowTitle(documentName); haveOpenedFile = true; } numLines = 0; numChars = 0; statusBar.setText(lh.localValue("loadingDocument") + " " + documentName); daisyLine.delete(0, daisyLine.length()); final Element rootElement = doc.getRootElement();// this needs to be // final, because it // will be used by a // different thread // new Thread() { // public void run() { // while (!stopRequested) { walkTree(rootElement); // .start(); } private void walkTree(Node node) { String ext = getFileExt(documentName); final Boolean isUtd = ext.contentEquals("utd"); Node newNode; for (int i = 0; i < node.getChildCount(); i++) { newNode = node.getChild(i); if (newNode instanceof Element) { walkTree(newNode); } else if (newNode instanceof Text) { String nname = ((Element) node).getLocalName(); if (!(nname.matches("span") || nname.matches("brl") || nname.matches("body") || nname.matches("title"))) { final String value = newNode.getValue(); numLines++; numChars += value.length(); daisyLine.append(value); } // the main thread gets to execute the block inside syncExec() if (daisyLine.length() > 4096 || i == node.getChildCount() - 1) { display.syncExec(new Runnable() { public void run() { daisy.view.append(daisyLine.toString()); statusBar.setText("Read " + numChars + " characters."); } }); daisyLine.delete(0, daisyLine.length()); } } } stopRequested = true; } void openTikaDocument(String fileName) { // daisy.view.removeModifyListener(daisyMod); stopRequested = false; Builder parser = new Builder(); try { doc = parser.build(fileName); } catch (ParsingException e) { new Notify("Tika: " + lh.localValue("malformedDocument")); e.getStackTrace(); return; } catch (IOException e) { new Notify(lh.localValue("couldNotOpen") + " " + documentName); return; } numLines = 0; numChars = 0; statusBar .setText(lh.localValue("loadingDocument") + " " + documentName); final Element rootElement = doc.getRootElement();// this needs to be // final, because it // will be used by a // different thread while (!stopRequested) { walkTikaTree(rootElement); } } private void walkTikaTree(Node node) { Node newNode; numLines = 0; numChars = 0; String tags[] = { "title", "p", "i", "b", "u", "strong", "span" }; for (int i = 0; i < node.getChildCount(); i++) { newNode = node.getChild(i); if (newNode instanceof Element) { walkTikaTree(newNode); // down one level } else if (newNode instanceof Text) { String nname = ((Element) node).getLocalName(); Boolean match = false; int j = 0; while (!match && (j < tags.length)) { if (nname.matches(tags[j++])) match = true; } if (match) { String value = newNode.getValue() + "\n"; // replace Unicode with matching codepoints Matcher matcher = Pattern.compile("\\\\u((?i)[0-9a-f]{4})") .matcher(value); StringBuffer sb = new StringBuffer(); int codepoint; while (matcher.find()) { codepoint = Integer.valueOf(matcher.group(1), 16); matcher.appendReplacement(sb, String.valueOf((char) codepoint)); } matcher.appendTail(sb); value = sb.toString(); numLines++; numChars += value.length(); daisyLine.append(value); } ; // the main thread gets to execute the block inside syncExec() if (daisyLine.length() > 4096 || i == node.getChildCount() - 1) { display.syncExec(new Runnable() { public void run() { daisy.view.append(daisyLine.toString()); statusBar.setText("Read " + daisy.view.getCharCount() + " characters."); } }); daisyLine.delete(0, daisyLine.length()); } } } stopRequested = true; } void fileSave() { if (!(daisy.hasChanged || braille.hasChanged)) { new Notify(lh.localValue("noChange")); return; } String ext = ""; if (documentName != null) ext = getFileExt(documentName); /** no open file then do a Save As **/ if ((!haveOpenedFile) || ext.contentEquals("xml")) { fileSaveAs(); } else { saveDaisyWorkFile(); String fileName = new File(documentName).getName(); statusBar.setText(lh.localValue("savingFile") + " " + fileName); /* save utdml file */ if (!metaContent) { System.out.println(fileName + " " + lh.localValue("saveTextOnly")); new FileUtils().copyFile(daisyWorkFile, documentName); statusBar.setText(lh.localValue("fileSaved")); new Notify(lh.localValue("fileSaved")); } else if (translatedFileName != null) { YesNoChoice ync = new YesNoChoice( lh.localValue("confirmTranslationSaved")); if (ync.result == SWT.YES) { // System.out.println(fileName + " " + // lh.localValue("saveTextBraille")); new FileUtils().copyFile(translatedFileName, documentName); statusBar.setText(lh.localValue("fileSaved")); new Notify(lh.localValue("fileSaved")); daisy.hasChanged = false; braille.hasChanged = false; } else { new Notify(lh.localValue("noChangeSaved")); } } else { fileSaveAs(); } } } void fileSaveAs() { if (daisyWorkFile == null) { /* create the utd text file */ saveDaisyWorkFile(); } textAndBraille = false; saveUtdml = false; /* dialog asking for the type of UTDML file to save */ if (braille.view.getCharCount() != 0) { SaveOptionsDialog saveChoice = new SaveOptionsDialog(documentWindow); saveChoice.setText(lh.localValue("optionSelect")); SaveSelection result = saveChoice.open(); if (result.equals(SaveSelection.TEXT_AND_BRAILLE)) { textAndBraille = true; } else if (result.equals(SaveSelection.CANCELLED)) { return; } saveUtdml = true; } Shell shell = new Shell(display); FileDialog dialog = new FileDialog(shell, SWT.SAVE); String filterPath = System.getProperty("user.home"); // FO 04 String[] filterNames = null; String[] filterExtensions = null; if (textAndBraille) { filterNames = new String[] { "UTDML file" }; filterExtensions = new String[] { "*.utd" }; } else { filterNames = new String[] { "XML file" }; filterExtensions = new String[] { "*.xml" }; } String platform = SWT.getPlatform(); if (platform.equals("win32") || platform.equals("wpf")) { if (filterPath == null) filterPath = "c:\\"; } dialog.setFilterPath(filterPath); dialog.setFilterNames(filterNames); dialog.setFilterExtensions(filterExtensions); if (haveOpenedFile) { int i = documentName.lastIndexOf("."); String fn = documentName.substring(0, i); if (getFileExt(documentName).contentEquals("xml")) { if (textAndBraille) documentName = fn + ".utd"; else documentName = fn + ".xml"; } dialog.setFileName(documentName); } else { if (documentName != null) { if (getFileExt(documentName).contentEquals("brf")) { saveDaisyWorkFile(); int i = documentName.lastIndexOf("."); String fn = documentName.substring(0, i); newDaisyFile = fn + ".xml"; } } dialog.setFileName(newDaisyFile); } String saveTo = dialog.open(); shell.dispose(); if (saveTo == null) { return; } String fileName = new File(saveTo).getName(); statusBar.setText(lh.localValue("savingFile") + " " + fileName); /* text and braille utd */ if (textAndBraille) { if (translatedFileName == null) { new Notify(lh.localValue("noXlation")); return; } new FileUtils().copyFile(translatedFileName, saveTo); } else { new FileUtils().copyFile(daisyWorkFile, saveTo); } // add this file to recentDocList rd.addDocument(saveTo); statusBar.setText(lh.localValue("fileSaved") + " " + saveTo); documentWindow.setText("BrailleBlaster " + fileName); if (!textAndBraille) { translatedFileName = null; braille.view.replaceTextRange(0, braille.view.getCharCount(), ""); } daisy.hasChanged = false; braille.hasChanged = false; } void fileClose() { if (daisy.view == null) { System.err.println("fileCLose() - something wrong!!!"); return; } activateMenus(false); if (daisy.hasChanged || braille.hasChanged) { YesNoChoice ync = new YesNoChoice(lh.localValue("hasChanged")); if (ync.result == SWT.YES) { fileSave(); } } activateViews(false); haveOpenedFile = false; brailleFileName = null; documentName = null; doc = null; BBIni.setUtd(false); stopRequested = false; statusBar.setText(""); daisy.view.setText(""); daisy.hasChanged = false; braille.view.setText(""); braille.hasChanged = false; setWindowTitle(" untitled"); } void showBraille() { BufferedReader translation = null; try { translation = new BufferedReader(new FileReader(translatedFileName)); } catch (FileNotFoundException e) { new Notify(lh.localValue("couldNotFindFile") + " " + translatedFileName); } numLines = 0; numChars = 0; firstTime = true; boolean eof = false; String line; while (!eof) { try { line = translation.readLine(); } catch (IOException e) { new Notify(lh.localValue("problemReading") + " " + translatedFileName); return; } if (line == null) { eof = true; } else { brailleLine.append(line); brailleLine.append('\n'); numChars += line.length(); numLines++; } if ((brailleLine.length() > 4096) || (eof)) { display.syncExec(new Runnable() { public void run() { /* * Make sure we replace the braille view with the * content of the file */ if (firstTime) { braille.view.replaceTextRange(0, braille.view.getCharCount(), brailleLine.toString()); firstTime = false; } else { braille.view.append(brailleLine.toString()); } brailleLine.delete(0, brailleLine.length()); statusBar.setText(lh.localValue("textTranslated") + " " + numLines + " " + lh.localValue("textLines") + ", " + numChars + " " + lh.localValue("textCharacters")); } }); } } // end while try { translation.close(); } catch (IOException e) { new Notify(lh.localValue("problemReading") + " " + translatedFileName); } } void saveDaisyWorkFile() { createWorkDocument(); if (doc == null) { new Notify(lh.localValue("noOpenFile")); return; } /* UTD text file */ daisyWorkFile = tempPath + docID + "-tempdoc.xml"; FileOutputStream writer = null; try { writer = new FileOutputStream(daisyWorkFile); } catch (FileNotFoundException e) { new Notify(lh.localValue("cannotOpenFileW") + " " + daisyWorkFile); return; } Serializer outputDoc = new Serializer(writer); try { outputDoc.write(doc); outputDoc.flush(); } catch (IOException e) { new Notify(lh.localValue("cannotWriteFile")); return; } } void createWorkDocument() { newDoc = new NewDocument(); newDoc.fillOutBody(daisy.view); doc = newDoc.getDocument(); } void translateView(boolean display) { if (daisy.view.getCharCount() == 0) { new Notify(lh.localValue("nothingToXlate")); return; } saveDaisyWorkFile(); if (!BBIni.useUtd()) { YesNoChoice ync = new YesNoChoice(lh.localValue("askUtdml")); if (ync.result == SWT.YES) { BBIni.setUtd(true); } } translate(display); } void translate(boolean display) { configFileList = "preferences.cfg"; configSettings = null; if (BBIni.useUtd()) { configSettings = "formatFor utd\n" + "mode notUC\n"; } translatedFileName = getTranslatedFileName(); boolean result = louisutdml.translateFile(configFileList, daisyWorkFile, translatedFileName, logFile, configSettings, mode); if (!result) { new Notify(lh.localValue("translationFailed")); return; } if (!BBIni.useUtd()) { brailleFileName = getBrailleFileName(); new FileUtils().copyFile(translatedFileName, brailleFileName); } metaContent = true; braille.hasChanged = true; if (display) { if (BBIni.useUtd()) { brailleFileName = getBrailleFileName(); utd.displayTranslatedFile(translatedFileName, brailleFileName); } else { new Thread() { public void run() { showBraille(); } }.start(); } } } String getTranslatedFileName() { String s = tempPath + docID + "-doc.brl"; return s; } String getBrailleFileName() { String s = tempPath + docID + "-doc-brl.brl"; return s; } String getTikaTranslatedFileName() { String s = tempPath + docID + "-doc.html"; return s; } int getCount() { return documentNumber; } void fileEmbossNow() { if ((brailleFileName == null) || (braille.view.getCharCount() == 0)) { new Notify(lh.localValue("noXlationEmb")); return; } Shell shell = new Shell(display, SWT.DIALOG_TRIM); PrintDialog embosser = new PrintDialog(shell); PrinterData data = embosser.open(); shell.dispose(); if (data == null || data.equals("")) { return; } File translatedFile = new File(brailleFileName); PrinterDevice embosserDevice; try { embosserDevice = new PrinterDevice(data.name, true); embosserDevice.transmit(translatedFile); } catch (PrintException e) { new Notify(lh.localValue("cannotEmboss") + ": " + data.name + "\n" + e.getMessage()); } } void daisyPrint() { /** if ((daisy.view.getCharCount() == 0)) { new Notify(lh.localValue("nothingToPrint")); return; } final String printFileName = tempPath + docID + "-print.tmp"; PrintStream out = null; **/ placeholder(); } void toggleBrailleFont() { if (displayBrailleFont) { displayBrailleFont = false; } else { displayBrailleFont = true; } setBrailleFont(displayBrailleFont); } void setBrailleFont(boolean toggle) { if (toggle) { simBrailleFont = new Font(documentWindow.getDisplay(), "SimBraille", brailleFontHeight, SWT.NORMAL); braille.view.setFont(simBrailleFont); } else { // FontData[] fd = // (documentWindow.getDisplay().getSystemFont()).getFontData(); if (Courier) { simBrailleFont = new Font(documentWindow.getDisplay(), courierFont, daisyFontHeight, SWT.NORMAL); } else { simBrailleFont = new Font(documentWindow.getDisplay(), altFont, daisyFontHeight, SWT.NORMAL); } braille.view.setFont(simBrailleFont); } } void increaseFont() { daisyFontHeight += daisyFontHeight / 4; if (daisyFontHeight >= 48) { return; } if (Courier) { daisyFont = new Font(documentWindow.getDisplay(), courierFont, daisyFontHeight, SWT.NORMAL); } else { daisyFont = new Font(documentWindow.getDisplay(), altFont, daisyFontHeight, SWT.NORMAL); } daisy.view.setFont(daisyFont); brailleFontHeight += brailleFontHeight / 4; if (displayBrailleFont) { simBrailleFont = new Font(documentWindow.getDisplay(), "SimBraille", brailleFontHeight, SWT.NORMAL); braille.view.setFont(simBrailleFont); } else { braille.view.setFont(daisyFont); } } void decreaseFont() { daisyFontHeight -= daisyFontHeight / 5; if (daisyFontHeight <= 8) { return; } if (Courier) { daisyFont = new Font(documentWindow.getDisplay(), courierFont, daisyFontHeight, SWT.NORMAL); } else { daisyFont = new Font(documentWindow.getDisplay(), altFont, daisyFontHeight, SWT.NORMAL); } daisy.view.setFont(daisyFont); brailleFontHeight -= brailleFontHeight / 5; if (displayBrailleFont) { simBrailleFont = new Font(documentWindow.getDisplay(), "SimBraille", brailleFontHeight, SWT.NORMAL); braille.view.setFont(simBrailleFont); } else { braille.view.setFont(daisyFont); } } void importDocument() { if (!daisy.view.isVisible()) { activateViews(true); activateMenus(true); daisy.hasChanged = false; braille.hasChanged = false; haveOpenedFile = false; brailleFileName = null; documentName = null; daisy.hasChanged = false; doc = null; BBIni.setUtd(false); setWindowTitle(" untitled"); daisy.view.setFocus(); } if ((doc != null) || daisy.hasChanged) { returnReason = WP.ImportDocument; flags[documentNumber] = true; return; } haveOpenedFile = false; metaContent = false; Shell shell = new Shell(display, SWT.DIALOG_TRIM); FileDialog dialog = new FileDialog(shell, SWT.OPEN); String filterPath = System.getProperty("user.home"); String[] filterNames = new String[] { "ASCII Text", "Compressed archive (ZIP)", "Word Doc", "Word Docx", "Rich Text Format", "Braille BRF", "OpenOffice ODT", "PDF", "XML", "All Files (*)" }; String[] filterExtensions = new String[] { "*.txt", "*.zip", "*.doc", "*.docx", "*.rtf", "*.brf", "*.odt", "*.pdf", "*.xml", "*" }; String platform = SWT.getPlatform(); if (platform.equals("win32") || platform.equals("wpf")) { filterNames[filterNames.length-1] = "All Files (*.*)"; filterExtensions[filterExtensions.length-1] = "*.*"; filterPath = System.getProperty("user.home"); if (filterPath == null) filterPath = "c:\\"; } dialog.setFilterNames(filterNames); dialog.setFilterExtensions(filterExtensions); dialog.setFilterPath(filterPath); /* turn off change tracking */ // daisy.view.removeModifyListener(daisyMod); documentName = dialog.open(); shell.dispose(); if (documentName == null) return; Tika tika = new Tika(); File inFile = new File(documentName); String type = ""; try { type = tika.detect(inFile); } catch (IOException e) { System.err.println(inFile.getName() + ":\n" + e.getMessage()); new Notify(lh.localValue("couldNotOpen") + ":\n" + inFile.getName() + "\n" + e.getLocalizedMessage()); return; } // add this file to recentDocList rd.addDocument(documentName); boolean zip = false; for (int i=0; i<compressed.length; i++) { if (type.contentEquals(compressed[i])) { // System.out.println(type); zip = true; } } if (zip) { importZip(getEncodingString()); return; } // special case if (getFileExt(documentName).contentEquals("brf")) { openBrf(documentName); setWindowTitle("untitled"); } else { parseImport(documentName, getEncodingString()); setWindowTitle(documentName); } braille.view.setEditable(false); daisy.hasChanged = true; daisy.view.setFocus(); } void importZip(String encoding) { String [] arc = null; statusBar.setText(lh.localValue("loadingFile") + " " + documentName); try { ImportersManager im = new ImportersManager(documentName, tempPath, docID, true); arc = im.extractZipFiles(); isNimas = im.isNimas(); } catch (IOException e) { System.err.println("ImportersManager IOException: " + e.getMessage()); new Notify(lh.localValue("couldNotOpen") + ":\n" + documentName + "\n" + e.getLocalizedMessage()); } catch (Exception e) { System.err.println(e.getMessage()); new Notify(lh.localValue("couldNotOpen") + ":\n" + documentName + "\n" + e.getLocalizedMessage()); } if (arc == null) { new Notify(lh.localValue("problemReading") + ":\n" + documentName ); return; } statusBar.setText(lh.localValue("importCompleted")); String path = null; for (int i=0; i<arc.length; i++) { daisyWorkFile = tempPath + arc[i]; parseImport(daisyWorkFile, encoding); File d = new File (daisyWorkFile); if (path == null) path = d.getParentFile().getPath(); d.delete(); } if (!path.contentEquals(tempPath)) removeDirectory(new File (path)); haveOpenedFile=false; } public boolean removeDirectory(File directory) { // System.out.println("removeDirectory " + directory); if (directory == null) return false; if (!directory.exists()) return true; if (!directory.isDirectory()) return false; String[] list = directory.list(); // Some JVMs return null for File.list() when the // directory is empty. if (list != null) { for (int i = 0; i < list.length; i++) { File entry = new File(directory, list[i]); if (entry.isDirectory()) { if (!removeDirectory(entry)) return false; } else { if (!entry.delete()) return false; } } } return directory.delete(); } void parseImport(String fileName, String encoding) { /** Tika extract **/ try { useTikaParser(fileName, encoding); } catch (ParserConfigurationException e) { System.err.println("Error importing: " + fileName); return; } catch (Exception e) { System.err.println("Error importing: " + fileName); return; } openTikaDocument(tikaWorkFile); } /** Tika importer that creates a HTML formatted file **/ void useTikaParser(String docName, String encoding) throws Exception { String fn = new File(docName).getName(); int dot = fn.lastIndexOf("."); tikaWorkFile = tempPath + docID + "-" + fn.substring(0, dot) + ".html"; File workFile = new File(tikaWorkFile); try { workFile.createNewFile(); } catch (IOException e) { System.out.println("useTikaHtmlParser: Error creating Tika workfile " + e); return; } InputStream stream = TikaInputStream.get(new File(docName)); Metadata metadata = new Metadata(); metadata.add("Content-Encoding", encoding); ParseContext context = new ParseContext(); Parser parser = new AutoDetectParser(); OutputStream output = new FileOutputStream(workFile); try { ToXMLContentHandler handler = new ToXMLContentHandler(output, encoding); parser.parse(stream, handler, metadata, context); } catch (IOException e) { System.err.println("useTikaHtmlParser IOException: " + e.getMessage()); } catch (SAXException e) { System.err.println("useTikaHtmlParser SAXException: " + e.getMessage()); } catch (TikaException e) { System.err.println("useTikaHtmlParser TikaException: " + e.getMessage()); } finally { stream.close(); output.close(); } } void brailleSave() { if ((braille.view.getCharCount() == 0) || brailleFileName == null) { new Notify(lh.localValue("noXlation")); return; } Shell shell = new Shell(display); FileDialog dialog = new FileDialog(shell, SWT.SAVE); String filterPath = System.getProperty("user.home"); // FO 04 String[] filterNames = new String[] { "BRF file" }; String[] filterExtensions = new String[] { "*.brf" }; String platform = SWT.getPlatform(); if (platform.equals("win32") || platform.equals("wpf")) { if (filterPath == null) filterPath = "c:\\"; } dialog.setFilterPath(filterPath); dialog.setFilterNames(filterNames); dialog.setFilterExtensions(filterExtensions); if (haveOpenedFile) { int i = documentName.lastIndexOf("."); String fn = documentName.substring(0, i); documentName = fn + ".brf"; } else { documentName = "document-" + docID + ".brf"; } dialog.setFileName(documentName); String saveTo = dialog.open(); shell.dispose(); if (saveTo == null) { return; } String fileName = new File(saveTo).getName(); statusBar.setText(lh.localValue("savingFile") + " " + fileName); new FileUtils().copyFile(brailleFileName, saveTo); } // plain BRF file to back-translate void openBrf(String fileName) { translatedFileName = getBrailleFileName(); new FileUtils().copyFile (fileName, translatedFileName); showBraille(); // backtranslate BBIni.setUtd(false) ; configFileList = "backtranslate.cfg"; configSettings = "mode notUc\n" ; daisyWorkFile = tempPath + docID + "-tempdoc.xml"; boolean result = louisutdml.backTranslateFile(configFileList, fileName, daisyWorkFile, logFile, configSettings, mode); if (!result) { new Notify(lh.localValue("translationFailed")); return; } openDocument(daisyWorkFile); haveOpenedFile = false; } void showDaisy(String content) { /* Make sure we replace the existing view with the content of the file */ daisy.view.replaceTextRange(0, daisy.view.getCharCount(), content + "\n"); } void placeholder() { new Notify(lh.localValue("funcNotAvail")); } boolean isFinished() { return finished; } void recentDocuments() { rd.open(); } void switchDocuments() { } static boolean[] getflags() { return flags; } static void setflags(int i, boolean b) { flags[i] = b; } static void printflags() { for (boolean b : flags) System.out.print(b + ", "); } static String getRecentFileName() { return recentFileName; } boolean getDaisyHasChanged() { return daisy.hasChanged; } public String getFileExt(String fileName) { String ext = ""; String fn = fileName.toLowerCase(); int dot = fn.lastIndexOf("."); if (dot > 0) { ext = fn.substring(dot + 1); } return ext; } void activateViews(boolean state) { activateDaisyView(state); activateBrailleView(state); } void activateDaisyView(boolean active) { if (active) { daisy.view.setVisible(true); } else { daisy.view.setVisible(false); } } void activateBrailleView(boolean active) { if (active) { braille.view.setVisible(true); } else { braille.view.setVisible(false); } } void activateMenus(boolean state) { String itemToFind[] = { "Close", "Save", "Emboss Now", "Print", "Translate" }; Menu mb = documentWindow.getMenuBar(); MenuItem mi[] = mb.getItems(); String t; int i; for (i = 0; i < mi.length; i++) { t = mi[i].getText().replace("&", ""); if (t.contains("File")) { break; } } Menu f = mi[i].getMenu(); MenuItem ii[] = f.getItems(); for (i = 0; i < ii.length; i++) { t = ii[i].toString().replaceAll("&", ""); for (int j = 0; j < itemToFind.length; j++) { if (t.contains(itemToFind[j])) { ii[i].setEnabled(state); } } } Control tb[] = documentWindow.getChildren(); for (i = 0; i < tb.length; i++) { t = tb[i].toString().replace("&", ""); if (t.contains("ToolBar")) { break; } } ToolBar ttb = (ToolBar) tb[i]; ToolItem ti[] = ttb.getItems(); for (i = 0; i < ti.length; i++) { for (int j = 0; j < itemToFind.length; j++) { if (ti[i].getText().contains(itemToFind[j])) { ti[i].setEnabled(state); } } } String vb = lh.localValue("viewBraille"); for (i = 0; i < tb.length; i++) { t = tb[i].toString().replace("&", ""); if (t.contains(vb)) { tb[i].setEnabled(state); break; } } if (tb[i] instanceof Button) { Button b = (Button) tb[i]; b.setSelection(false); displayBrailleFont = false; setBrailleFont(displayBrailleFont); } } StyleManager getStyleManager() { return sm; } // encoding for Import public String getEncodingString() { encoding = null; // final Shell selShell = new Shell(display, SWT.DIALOG_TRIM | // SWT.APPLICATION_MODAL | SWT.CENTER); final Shell selShell = new Shell(display, SWT.DIALOG_TRIM | SWT.CENTER); selShell.setText(lh.localValue("specifyEncoding")); selShell.setMinimumSize(250, 100); FillLayout layout = new FillLayout(SWT.VERTICAL); layout.marginWidth = 8; selShell.setLayout(layout); Composite radioGroup = new Composite(selShell, SWT.NONE); radioGroup.setLayout(new RowLayout(SWT.VERTICAL)); Button b1 = new Button(radioGroup, SWT.RADIO); b1.setText(lh.localValue("encodeUTF8")); b1.setSelection(true); // default b1.pack(); Button b2 = new Button(radioGroup, SWT.RADIO); b2.setText(lh.localValue("encodeISO88591")); b2.pack(); Button b3 = new Button(radioGroup, SWT.RADIO); b3.setText(lh.localValue("encodeWINDOWS1252")); b3.pack(); Button b4 = new Button(radioGroup, SWT.RADIO); b4.setText(lh.localValue("encodeUSASCII")); b4.pack(); // if (SWT.getPlatform().equals("win32") || // SWT.getPlatform().equals("wpf")) { // b1.setSelection(false); // b3.setSelection(true); radioGroup.pack(); Composite c = new Composite(selShell, SWT.NONE); RowLayout clayout = new RowLayout(); clayout.type = SWT.HORIZONTAL; // clayout.spacing = 30; // clayout.marginWidth = 8; clayout.marginTop = 20; clayout.center = true; clayout.pack = true; clayout.justify = true; c.setLayout(clayout); Button bsel = new Button(c, SWT.PUSH); bsel.setText(lh.localValue("encodeSelect")); bsel.pack(); c.pack(); Control tabList[] = new Control[] { radioGroup, c, radioGroup }; try { selShell.setTabList(tabList); } catch (IllegalArgumentException e) { System.err.println("setTabList exception " + e.getMessage()); } selShell.setDefaultButton(bsel); selShell.pack(); Monitor primary = display.getPrimaryMonitor(); Rectangle bounds = primary.getBounds(); Rectangle rect = selShell.getBounds(); int x = bounds.x + (bounds.width - rect.width) / 2; int y = bounds.y + (bounds.height - rect.height) / 2; selShell.setLocation(x, y); b1.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { encoding = Encodings.UTF_8.encoding(); } }); b2.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { encoding = Encodings.ISO_8859_1.encoding(); } }); b3.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { encoding = Encodings.WINDOWS_1252.encoding(); } }); b4.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { encoding = Encodings.US_ASCII.encoding(); } }); /* Select */ bsel.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { selShell.dispose(); } }); selShell.addListener(SWT.Close, new Listener() { public void handleEvent(Event event) { event.doit = false; // must pick a value } }); selShell.open(); while (!selShell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); // nothing clicked if (encoding == null) { if (b1.getSelection()) encoding = Encodings.UTF_8.encoding(); else if (b2.getSelection()) encoding = Encodings.ISO_8859_1.encoding(); else if (b3.getSelection()) encoding = Encodings.WINDOWS_1252.encoding(); else if (b4.getSelection()) encoding = Encodings.US_ASCII.encoding(); } ; } return encoding; } }
package ljdp.minechem.common.recipe; import cpw.mods.fml.common.registry.GameRegistry; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import ljdp.minechem.api.core.Chemical; import ljdp.minechem.api.core.Element; import ljdp.minechem.api.core.EnumElement; import ljdp.minechem.api.core.EnumMolecule; import ljdp.minechem.api.core.Molecule; import ljdp.minechem.api.recipe.DecomposerRecipe; import ljdp.minechem.api.recipe.DecomposerRecipeChance; import ljdp.minechem.api.recipe.DecomposerRecipeSelect; import ljdp.minechem.api.recipe.SynthesisRecipe; import ljdp.minechem.api.util.Util; import ljdp.minechem.common.MinechemBlocks; import ljdp.minechem.common.MinechemItems; import ljdp.minechem.common.ModMinechem; import ljdp.minechem.common.items.ItemElement; import ljdp.minechem.common.recipe.RecipeJournalCloning; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.event.ForgeSubscribe; import net.minecraftforge.oredict.OreDictionary; import biomesoplenty.api.BlockReference; // BOP Inferface Layer import biomesoplenty.api.Items; // BOP Inferface Layer public class MinechemRecipes { private static final MinechemRecipes instance = new MinechemRecipes(); public ArrayList unbondingRecipes = new ArrayList(); public ArrayList synthesisRecipes = new ArrayList(); private SynthesisRecipe recipeIron; private SynthesisRecipe recipeGold; private SynthesisRecipe recipeCoalChunk; public static MinechemRecipes getInstance() { return instance; } public void RegisterRecipes() { ItemStack var1 = new ItemStack(Block.stone); new ItemStack(Block.cobblestone); ItemStack var3 = new ItemStack(Block.dirt); ItemStack var4 = new ItemStack(Block.sand); ItemStack var5 = new ItemStack(Block.gravel); ItemStack var6 = new ItemStack(Block.glass); ItemStack var7 = new ItemStack(Block.thinGlass); ItemStack oreIron = new ItemStack(Block.oreIron); ItemStack oreGold = new ItemStack(Block.oreGold); ItemStack var10 = new ItemStack(Block.oreDiamond); ItemStack var11 = new ItemStack(Block.oreEmerald); ItemStack oreCoal = new ItemStack(Block.oreCoal); ItemStack var13 = new ItemStack(Block.oreRedstone); ItemStack var14 = new ItemStack(Block.oreLapis); ItemStack ingotIron = new ItemStack(Item.ingotIron); ItemStack blockIron = new ItemStack(Block.blockIron); ItemStack var17 = new ItemStack(MinechemItems.atomicManipulator); ItemStack var18 = new ItemStack(Item.redstone); ItemStack var19 = new ItemStack(MinechemItems.testTube, 16); GameRegistry.addRecipe(var19, new Object[] { " G ", " G ", " G ", Character.valueOf('G'), var6 }); GameRegistry.addRecipe(MinechemItems.concaveLens, new Object[] { "G G", "GGG", "G G", Character.valueOf('G'), var6 }); GameRegistry.addRecipe(MinechemItems.convexLens, new Object[] { " G ", "GGG", " G ", Character.valueOf('G'), var6 }); GameRegistry.addRecipe(MinechemItems.microscopeLens, new Object[] { "A", "B", "A", Character.valueOf('A'), MinechemItems.convexLens, Character.valueOf('B'), MinechemItems.concaveLens }); GameRegistry.addRecipe(new ItemStack(MinechemBlocks.microscope), new Object[] { " LI", " PI", "III", Character.valueOf('L'), MinechemItems.microscopeLens, Character.valueOf('P'), var7, Character.valueOf('I'), ingotIron }); GameRegistry.addRecipe(new ItemStack(MinechemItems.atomicManipulator), new Object[] { "PPP", "PIP", "PPP", Character.valueOf('P'), new ItemStack(Block.pistonBase), Character.valueOf('I'), blockIron }); GameRegistry.addRecipe(new ItemStack(MinechemBlocks.decomposer), new Object[] { "III", "IAI", "IRI", Character.valueOf('A'), var17, Character.valueOf('I'), ingotIron, Character.valueOf('R'), var18 }); GameRegistry.addRecipe(new ItemStack(MinechemBlocks.synthesis), new Object[] { "IRI", "IAI", "IDI", Character.valueOf('A'), var17, Character.valueOf('I'), ingotIron, Character.valueOf('R'), var18, Character.valueOf('D'), new ItemStack(Item.diamond) }); GameRegistry.addRecipe(new ItemStack(MinechemBlocks.fusion, 16, 0), new Object[] { "ILI", "ILI", "ILI", Character.valueOf('I'), ingotIron, Character.valueOf('L'), ItemElement.createStackOf(EnumElement.Pb, 1) }); GameRegistry.addRecipe(new ItemStack(MinechemBlocks.fusion, 16, 1), new Object[] { "IWI", "IBI", "IWI", Character.valueOf('I'), ingotIron, Character.valueOf('W'), ItemElement.createStackOf(EnumElement.W, 1), Character.valueOf('B'), ItemElement.createStackOf(EnumElement.Be, 1) }); GameRegistry.addRecipe(MinechemItems.projectorLens, new Object[] { "ABA", Character.valueOf('A'), MinechemItems.concaveLens, Character.valueOf('B'), MinechemItems.convexLens }); GameRegistry.addRecipe(new ItemStack(MinechemBlocks.blueprintProjector), new Object[] { " I ", "GPL", " I ", Character.valueOf('I'), ingotIron, Character.valueOf('P'), var7, Character.valueOf('L'), MinechemItems.projectorLens, Character.valueOf('G'), new ItemStack(Block.redstoneLampIdle) }); ItemStack var20 = new ItemStack(MinechemItems.molecule, 1, EnumMolecule.polyvinylChloride.ordinal()); GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatFeet), new Object[] { " ", "P P", "P P", Character.valueOf('P'), var20 }); GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatLegs), new Object[] { "PPP", "P P", "P P", Character.valueOf('P'), var20 }); GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatTorso), new Object[] { " P ", "PPP", "PPP", Character.valueOf('P'), var20 }); GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatHead), new Object[] { "PPP", "P P", " ", Character.valueOf('P'), var20 }); GameRegistry.addRecipe(new ItemStack(MinechemBlocks.chemicalStorage), new Object[] { "LLL", "LCL", "LLL", Character.valueOf('L'), new ItemStack(MinechemItems.element, 1, EnumElement.Pb.ordinal()), Character.valueOf('C'), new ItemStack(Block.chest) }); GameRegistry.addRecipe(new ItemStack(MinechemItems.IAintAvinit), new Object[] { "ZZZ", "ZSZ", " S ", Character.valueOf('Z'), new ItemStack(Item.ingotIron), Character.valueOf('S'), new ItemStack(Item.stick) }); GameRegistry.addShapelessRecipe(new ItemStack(MinechemItems.journal), new Object[] { new ItemStack(Item.book), new ItemStack(MinechemItems.testTube) }); for (EnumElement element : EnumElement.values()) { GameRegistry.addShapelessRecipe(new ItemStack(MinechemItems.testTube), new Object[] { new ItemStack(MinechemItems.element, element.ordinal()) }); } GameRegistry.addRecipe(new RecipeJournalCloning()); Element var21 = this.element(EnumElement.C, 64); // DecomposerRecipe.add(new DecomposerRecipe(var8, new // Chemical[]{this.element(EnumElement.Fe, 4)})); DecomposerRecipe.add(new DecomposerRecipe(oreIron, new Chemical[] { this.element(EnumElement.Fe, 32) })); // DecomposerRecipe.add(new DecomposerRecipe(var9, new // Chemical[]{this.element(EnumElement.Au, 4)})); DecomposerRecipe.add(new DecomposerRecipe(oreGold, new Chemical[] { this.element(EnumElement.Au, 32) })); DecomposerRecipe.add(new DecomposerRecipe(var10, new Chemical[] { this.molecule(EnumMolecule.fullrene, 6) })); DecomposerRecipe.add(new DecomposerRecipe(oreCoal, new Chemical[] { this.element(EnumElement.C, 32) })); DecomposerRecipe.add(new DecomposerRecipe(var11, new Chemical[] { this.molecule(EnumMolecule.beryl, 4), this.element(EnumElement.Cr, 4), this.element(EnumElement.V, 4) })); DecomposerRecipe.add(new DecomposerRecipe(var14, new Chemical[] { this.molecule(EnumMolecule.lazurite, 4), this.molecule(EnumMolecule.sodalite), this.molecule(EnumMolecule.noselite), this.molecule(EnumMolecule.calcite), this.molecule(EnumMolecule.pyrite) })); ItemStack ingotGold = new ItemStack(Item.ingotGold); ItemStack var23 = new ItemStack(Item.diamond); ItemStack var24 = new ItemStack(Item.emerald); ItemStack chunkCoal = new ItemStack(Item.coal); // DecomposerRecipe.add(new DecomposerRecipe(var15, new // Chemical[]{this.element(EnumElement.Fe, 2)})); DecomposerRecipe.add(new DecomposerRecipe(ingotIron, new Chemical[] { this.element(EnumElement.Fe, 16) })); // DecomposerRecipe.add(new DecomposerRecipe(var22, new // Chemical[]{this.element(EnumElement.Au, 2)})); DecomposerRecipe.add(new DecomposerRecipe(ingotGold, new Chemical[] { this.element(EnumElement.Au, 16) })); DecomposerRecipe.add(new DecomposerRecipe(var23, new Chemical[] { this.molecule(EnumMolecule.fullrene, 4) })); DecomposerRecipe.add(new DecomposerRecipe(var24, new Chemical[] { this.molecule(EnumMolecule.beryl, 2), this.element(EnumElement.Cr, 2), this.element(EnumElement.V, 2) })); // DecomposerRecipe.add(new DecomposerRecipe(var25, new // Chemical[]{this.element(EnumElement.C, 8)})); DecomposerRecipe.add(new DecomposerRecipe(chunkCoal, new Chemical[] { this.element(EnumElement.C, 16) })); // SynthesisRecipe.add(new SynthesisRecipe(var15, false, 1000, new // Chemical[]{this.element(EnumElement.Fe, 2)})); // SynthesisRecipe.add(new SynthesisRecipe(var22, false, 1000, new // Chemical[]{this.element(EnumElement.Au, 2)})); this.recipeIron = new SynthesisRecipe(ingotIron, false, 1000, new Chemical[] { this.element(EnumElement.Fe, 16) }); this.recipeGold = new SynthesisRecipe(ingotGold, false, 1000, new Chemical[] { this.element(EnumElement.Au, 16) }); SynthesisRecipe.add(recipeIron); SynthesisRecipe.add(recipeGold); SynthesisRecipe.add(new SynthesisRecipe(var23, true, '\uea60', new Chemical[] { null, this.molecule(EnumMolecule.fullrene), null, this.molecule(EnumMolecule.fullrene), null, this.molecule(EnumMolecule.fullrene), null, this.molecule(EnumMolecule.fullrene), null })); SynthesisRecipe.add(new SynthesisRecipe(var24, true, 80000, new Chemical[] { null, this.element(EnumElement.Cr), null, this.element(EnumElement.V), this.molecule(EnumMolecule.beryl, 2), this.element(EnumElement.V), null, this.element(EnumElement.Cr), null })); // DecomposerRecipe.add(new DecomposerRecipe(new // ItemStack(Block.blockSteel), new // Chemical[]{this.element(EnumElement.Fe, 18)})); DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockIron), new Chemical[] { this.element(EnumElement.Fe, 144) })); // DecomposerRecipe.add(new DecomposerRecipe(new // ItemStack(Block.blockGold), new // Chemical[]{this.element(EnumElement.Au, 18)})); DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockGold), new Chemical[] { this.element(EnumElement.Au, 144) })); DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockDiamond), new Chemical[] { this.molecule(EnumMolecule.fullrene, 36) })); DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(Block.blockEmerald), new Chemical[] { this.molecule(EnumMolecule.beryl, 18), this.element(EnumElement.Cr, 18), this.element(EnumElement.V, 18) })); // SynthesisRecipe.add(new SynthesisRecipe(new // ItemStack(Block.blockSteel), true, 5000, new // Chemical[]{this.element(EnumElement.Fe, 2), // this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2), // this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2), // this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2), // this.element(EnumElement.Fe, 2), this.element(EnumElement.Fe, 2)})); // SynthesisRecipe.add(new SynthesisRecipe(new // ItemStack(Block.blockGold), true, 5000, new // Chemical[]{this.element(EnumElement.Au, 2), // this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2), // this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2), // this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2), // this.element(EnumElement.Au, 2), this.element(EnumElement.Au, 2)})); SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.blockDiamond), true, 120000, new Chemical[] { this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4) })); SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.blockEmerald), true, 150000, new Chemical[] { this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3), this.element(EnumElement.V, 9), this.molecule(EnumMolecule.beryl, 18), this.element(EnumElement.V, 9), this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3) })); ItemStack var26 = new ItemStack(Block.sandStone); ItemStack var27 = new ItemStack(Item.flint); DecomposerRecipe.add(new DecomposerRecipe(var26, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16) })); DecomposerRecipe.add(new DecomposerRecipe(var4, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16) })); DecomposerRecipe.add(new DecomposerRecipe(var6, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16) })); DecomposerRecipe.add(new DecomposerRecipe(var7, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 1) })); DecomposerRecipe.add(new DecomposerRecipeChance(var5, 0.35F, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide) })); DecomposerRecipe.add(new DecomposerRecipeChance(var27, 0.5F, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide) })); Molecule var28 = this.molecule(EnumMolecule.siliconDioxide, 4); Molecule var29 = this.molecule(EnumMolecule.siliconDioxide, 4); SynthesisRecipe.add(new SynthesisRecipe(var6, true, 500, new Chemical[] { var28, null, var28, null, null, null, var28, null, var28 })); SynthesisRecipe.add(new SynthesisRecipe(var4, true, 200, new Chemical[] { var28, var28, var28, var28 })); SynthesisRecipe.add(new SynthesisRecipe(var27, true, 100, new Chemical[] { null, var29, null, var29, var29, var29, null, null, null })); SynthesisRecipe.add(new SynthesisRecipe(var7, true, 50, new Chemical[] { null, null, null, this.molecule(EnumMolecule.siliconDioxide), null, null, null, null, null })); SynthesisRecipe.add(new SynthesisRecipe(var5, true, 30, new Chemical[] { null, null, null, null, null, null, null, null, this.molecule(EnumMolecule.siliconDioxide) })); ItemStack var30 = new ItemStack(Item.feather); DecomposerRecipe.add(new DecomposerRecipe(var30, new Chemical[] { this.molecule(EnumMolecule.water, 8), this.element(EnumElement.N, 6) })); SynthesisRecipe.add(new SynthesisRecipe(var30, true, 800, new Chemical[] { this.element(EnumElement.N), this.molecule(EnumMolecule.water, 2), this.element(EnumElement.N), this.element(EnumElement.N), this.molecule(EnumMolecule.water, 1), this.element(EnumElement.N), this.element(EnumElement.N), this.molecule(EnumMolecule.water, 5), this.element(EnumElement.N) })); ItemStack var31 = new ItemStack(Item.arrow); ItemStack var32 = new ItemStack(Item.paper); ItemStack var33 = new ItemStack(Item.leather); ItemStack var34 = new ItemStack(Item.snowball); ItemStack var35 = new ItemStack(Item.brick); ItemStack var36 = new ItemStack(Item.clay); ItemStack var37 = new ItemStack(Block.mycelium); ItemStack var38 = new ItemStack(Block.sapling, 1, -1); DecomposerRecipe.add(new DecomposerRecipe(var31, new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O, 2), this.element(EnumElement.N, 6) })); DecomposerRecipe.add(new DecomposerRecipeChance(var36, 0.3F, new Chemical[] { this.molecule(EnumMolecule.kaolinite) })); DecomposerRecipe.add(new DecomposerRecipeChance(var35, 0.5F, new Chemical[] { this.molecule(EnumMolecule.kaolinite) })); DecomposerRecipe.add(new DecomposerRecipe(var34, new Chemical[] { this.molecule(EnumMolecule.water) })); DecomposerRecipe.add(new DecomposerRecipeChance(var37, 0.09F, new Chemical[] { this.molecule(EnumMolecule.fingolimod) })); DecomposerRecipe.add(new DecomposerRecipeChance(var33, 0.5F, new Chemical[] { this.molecule(EnumMolecule.arginine), this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.keratin) })); DecomposerRecipe.add(new DecomposerRecipeChance(var38, 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) })); DecomposerRecipe.add(new DecomposerRecipeChance(new ItemStack(Block.sapling, 1, 1), 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) })); DecomposerRecipe.add(new DecomposerRecipeChance(new ItemStack(Block.sapling, 1, 2), 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) })); DecomposerRecipe.add(new DecomposerRecipeChance(new ItemStack(Block.sapling, 1, 3), 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) })); DecomposerRecipe.add(new DecomposerRecipeChance(var32, 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) })); SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.clay, 12), false, 100, new Chemical[] { this.molecule(EnumMolecule.kaolinite) })); SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.brick, 8), true, 400, new Chemical[] { this.molecule(EnumMolecule.kaolinite), this.molecule(EnumMolecule.kaolinite), null, this.molecule(EnumMolecule.kaolinite), this.molecule(EnumMolecule.kaolinite), null })); SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.snowball, 5), true, 20, new Chemical[] { this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water) })); SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.mycelium, 16), false, 300, new Chemical[] { this.molecule(EnumMolecule.fingolimod) })); SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.leather, 5), true, 700, new Chemical[] { this.molecule(EnumMolecule.arginine), null, null, null, this.molecule(EnumMolecule.keratin), null, null, null, this.molecule(EnumMolecule.glycine) })); SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 0), true, 20, new Chemical[] { null, null, null, null, null, null, null, null, this.molecule(EnumMolecule.cellulose) })); SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 1), true, 20, new Chemical[] { null, null, null, null, null, null, null, this.molecule(EnumMolecule.cellulose), null })); SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 2), true, 20, new Chemical[] { null, null, null, null, null, null, this.molecule(EnumMolecule.cellulose), null, null })); SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.sapling, 1, 3), true, 20, new Chemical[] { null, null, null, null, null, this.molecule(EnumMolecule.cellulose), null, null, null })); SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.paper, 16), true, 150, new Chemical[] { null, this.molecule(EnumMolecule.cellulose), null, null, this.molecule(EnumMolecule.cellulose), null, null, this.molecule(EnumMolecule.cellulose), null })); ItemStack var39 = new ItemStack(Item.slimeBall); ItemStack var40 = new ItemStack(Item.blazeRod); ItemStack var41 = new ItemStack(Item.blazePowder); ItemStack var42 = new ItemStack(Item.magmaCream); ItemStack var43 = new ItemStack(Item.ghastTear); ItemStack var44 = new ItemStack(Item.netherStar); ItemStack var45 = new ItemStack(Item.spiderEye); ItemStack var46 = new ItemStack(Item.fermentedSpiderEye); ItemStack var47 = new ItemStack(Item.netherStalkSeeds); ItemStack var48 = new ItemStack(Block.glowStone); ItemStack var49 = new ItemStack(Item.lightStoneDust); ItemStack var50 = new ItemStack(Item.potion, 1, 0); ItemStack var51 = new ItemStack(Item.bucketWater); DecomposerRecipe.add(new DecomposerRecipeSelect(var39, 0.9F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.molecule(EnumMolecule.polycyanoacrylate) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Hg) }), new DecomposerRecipe(new Chemical[] { this.molecule(EnumMolecule.water, 10) }) })); DecomposerRecipe.add(new DecomposerRecipe(var40, new Chemical[] { this.element(EnumElement.Pu, 3) })); DecomposerRecipe.add(new DecomposerRecipe(var41, new Chemical[] { this.element(EnumElement.Pu) })); DecomposerRecipe.add(new DecomposerRecipe(var42, new Chemical[] { this.element(EnumElement.Hg), this.element(EnumElement.Pu), this.molecule(EnumMolecule.polycyanoacrylate, 3) })); DecomposerRecipe.add(new DecomposerRecipe(var43, new Chemical[] { this.element(EnumElement.Yb, 4), this.element(EnumElement.No, 4) })); Element var52 = this.element(EnumElement.H, 64); Element var53 = this.element(EnumElement.He, 64); DecomposerRecipe.add(new DecomposerRecipe(var44, new Chemical[] { this.element(EnumElement.Cn, 16), var52, var52, var52, var53, var53, var53, var21, var21 })); DecomposerRecipe.add(new DecomposerRecipeChance(var45, 0.2F, new Chemical[] { this.molecule(EnumMolecule.ttx) })); DecomposerRecipe.add(new DecomposerRecipe(var46, new Chemical[] { this.element(EnumElement.Po), this.molecule(EnumMolecule.ethanol) })); DecomposerRecipe.add(new DecomposerRecipeChance(var47, 0.5F, new Chemical[] { this.molecule(EnumMolecule.amphetamine) })); DecomposerRecipe.add(new DecomposerRecipe(var48, new Chemical[] { this.element(EnumElement.P, 4) })); DecomposerRecipe.add(new DecomposerRecipe(var49, new Chemical[] { this.element(EnumElement.P) })); DecomposerRecipe.add(new DecomposerRecipe(var50, new Chemical[] { this.molecule(EnumMolecule.water, 8) })); DecomposerRecipe.add(new DecomposerRecipe(var51, new Chemical[] { this.molecule(EnumMolecule.water, 16) })); SynthesisRecipe.add(new SynthesisRecipe(var40, true, 15000, new Chemical[] { this.element(EnumElement.Pu), null, null, this.element(EnumElement.Pu), null, null, this.element(EnumElement.Pu), null, null })); SynthesisRecipe.add(new SynthesisRecipe(var42, true, 5000, new Chemical[] { null, this.element(EnumElement.Pu), null, this.molecule(EnumMolecule.polycyanoacrylate), this.element(EnumElement.Hg), this.molecule(EnumMolecule.polycyanoacrylate), null, this.molecule(EnumMolecule.polycyanoacrylate), null })); SynthesisRecipe.add(new SynthesisRecipe(var43, true, 15000, new Chemical[] { this.element(EnumElement.Yb), this.element(EnumElement.Yb), this.element(EnumElement.No), null, this.element(EnumElement.Yb, 2), this.element(EnumElement.No, 2), null, this.element(EnumElement.No), null })); SynthesisRecipe.add(new SynthesisRecipe(var44, true, 500000, new Chemical[] { var53, var53, var53, var21, this.element(EnumElement.Cn, 16), var53, var52, var52, var52 })); SynthesisRecipe.add(new SynthesisRecipe(var45, true, 2000, new Chemical[] { this.element(EnumElement.C), null, null, null, this.molecule(EnumMolecule.ttx), null, null, null, this.element(EnumElement.C) })); SynthesisRecipe.add(new SynthesisRecipe(var48, true, 500, new Chemical[] { this.element(EnumElement.P), null, this.element(EnumElement.P), this.element(EnumElement.P), null, this.element(EnumElement.P), null, null, null })); ItemStack var54 = new ItemStack(Item.sugar); ItemStack var55 = new ItemStack(Item.reed); ItemStack var56 = new ItemStack(Block.pumpkin); ItemStack var57 = new ItemStack(Block.melon); ItemStack var58 = new ItemStack(Item.speckledMelon); ItemStack var59 = new ItemStack(Item.melon); ItemStack var60 = new ItemStack(Item.carrot); ItemStack var61 = new ItemStack(Item.goldenCarrot); ItemStack var62 = new ItemStack(Item.dyePowder, 1, 3); ItemStack var63 = new ItemStack(Item.potato); ItemStack var64 = new ItemStack(Item.bread); ItemStack var65 = new ItemStack(Item.appleRed); ItemStack var66 = new ItemStack(Item.appleGold, 1, 0); new ItemStack(Item.appleGold, 1, 1); ItemStack var68 = new ItemStack(Item.chickenCooked); DecomposerRecipe.add(new DecomposerRecipeChance(var54, 0.75F, new Chemical[] { this.molecule(EnumMolecule.sucrose) })); DecomposerRecipe.add(new DecomposerRecipeChance(var55, 0.65F, new Chemical[] { this.molecule(EnumMolecule.sucrose), this.element(EnumElement.H, 2), this.element(EnumElement.O) })); DecomposerRecipe.add(new DecomposerRecipe(var62, new Chemical[] { this.molecule(EnumMolecule.theobromine) })); DecomposerRecipe.add(new DecomposerRecipe(var56, new Chemical[] { this.molecule(EnumMolecule.cucurbitacin) })); DecomposerRecipe.add(new DecomposerRecipe(var57, new Chemical[] { this.molecule(EnumMolecule.cucurbitacin), this.molecule(EnumMolecule.asparticAcid), this.molecule(EnumMolecule.water, 16) })); DecomposerRecipe.add(new DecomposerRecipe(var58, new Chemical[] { this.molecule(EnumMolecule.water, 4), this.molecule(EnumMolecule.whitePigment), this.element(EnumElement.Au, 1) })); DecomposerRecipe.add(new DecomposerRecipe(var59, new Chemical[] { this.molecule(EnumMolecule.water) })); DecomposerRecipe.add(new DecomposerRecipeChance(var60, 0.05F, new Chemical[] { this.molecule(EnumMolecule.ret) })); DecomposerRecipe.add(new DecomposerRecipeChance(var61, 0.2F, new Chemical[] { this.molecule(EnumMolecule.ret), this.element(EnumElement.Au, 4) })); DecomposerRecipe.add(new DecomposerRecipeChance(var63, 0.4F, new Chemical[] { this.molecule(EnumMolecule.water, 8), this.element(EnumElement.K, 2), this.molecule(EnumMolecule.cellulose) })); DecomposerRecipe.add(new DecomposerRecipeChance(var64, 0.1F, new Chemical[] { this.molecule(EnumMolecule.starch), this.molecule(EnumMolecule.sucrose) })); DecomposerRecipe.add(new DecomposerRecipe(var65, new Chemical[] { this.molecule(EnumMolecule.malicAcid) })); DecomposerRecipe.add(new DecomposerRecipe(var66, new Chemical[] { this.molecule(EnumMolecule.malicAcid), this.element(EnumElement.Au, 8) })); DecomposerRecipe.add(new DecomposerRecipe(var66, new Chemical[] { this.molecule(EnumMolecule.malicAcid), this.element(EnumElement.Au, 64), this.element(EnumElement.Np) })); DecomposerRecipe.add(new DecomposerRecipe(var68, new Chemical[] { this.element(EnumElement.K), this.element(EnumElement.Na), this.element(EnumElement.C, 2) })); SynthesisRecipe.add(new SynthesisRecipe(var54, false, 400, new Chemical[] { this.molecule(EnumMolecule.sucrose) })); SynthesisRecipe.add(new SynthesisRecipe(var65, false, 400, new Chemical[] { this.molecule(EnumMolecule.malicAcid), this.molecule(EnumMolecule.water, 2) })); SynthesisRecipe.add(new SynthesisRecipe(var62, false, 400, new Chemical[] { this.molecule(EnumMolecule.theobromine) })); SynthesisRecipe.add(new SynthesisRecipe(var56, false, 400, new Chemical[] { this.molecule(EnumMolecule.cucurbitacin) })); SynthesisRecipe.add(new SynthesisRecipe(var68, true, 5000, new Chemical[] { this.element(EnumElement.K, 16), this.element(EnumElement.Na, 16), this.element(EnumElement.C, 16) })); ItemStack var69 = new ItemStack(Item.gunpowder); ItemStack var70 = new ItemStack(Block.tnt); DecomposerRecipe.add(new DecomposerRecipe(var69, new Chemical[] { this.molecule(EnumMolecule.potassiumNitrate), this.element(EnumElement.S, 2), this.element(EnumElement.C) })); DecomposerRecipe.add(new DecomposerRecipe(var70, new Chemical[] { this.molecule(EnumMolecule.tnt) })); SynthesisRecipe.add(new SynthesisRecipe(var70, false, 1000, new Chemical[] { this.molecule(EnumMolecule.tnt) })); SynthesisRecipe.add(new SynthesisRecipe(var69, true, 600, new Chemical[] { this.molecule(EnumMolecule.potassiumNitrate), this.element(EnumElement.C), null, this.element(EnumElement.S, 2), null, null, null, null, null })); ItemStack var71 = new ItemStack(Block.wood, 1, -1); ItemStack var72 = new ItemStack(Block.planks, 1, -1); ItemStack var140 = new ItemStack(Block.planks, 1, 0); ItemStack var141 = new ItemStack(Block.planks, 1, 1); ItemStack var142 = new ItemStack(Block.planks, 1, 2); ItemStack var143 = new ItemStack(Block.planks, 1, 3); ItemStack var73 = new ItemStack(Item.stick); ItemStack var74 = new ItemStack(Block.wood, 1, 0); ItemStack var75 = new ItemStack(Block.wood, 1, 1); ItemStack var76 = new ItemStack(Block.wood, 1, 2); ItemStack var77 = new ItemStack(Block.wood, 1, 3); ItemStack var78 = new ItemStack(Item.doorWood); ItemStack var79 = new ItemStack(Block.pressurePlatePlanks, 1, -1); DecomposerRecipe.add(new DecomposerRecipeChance(var71, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) })); DecomposerRecipe.add(new DecomposerRecipeChance(var74, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) })); DecomposerRecipe.add(new DecomposerRecipeChance(var75, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) })); DecomposerRecipe.add(new DecomposerRecipeChance(var76, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) })); DecomposerRecipe.add(new DecomposerRecipeChance(var77, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) })); DecomposerRecipe.add(new DecomposerRecipeChance(var72, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) })); DecomposerRecipe.add(new DecomposerRecipeChance(var140, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) })); DecomposerRecipe.add(new DecomposerRecipeChance(var141, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) })); DecomposerRecipe.add(new DecomposerRecipeChance(var142, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) })); DecomposerRecipe.add(new DecomposerRecipeChance(var143, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) })); DecomposerRecipe.add(new DecomposerRecipeChance(var73, 0.3F, new Chemical[] { this.molecule(EnumMolecule.cellulose) })); DecomposerRecipe.add(new DecomposerRecipeChance(var78, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 12) })); DecomposerRecipe.add(new DecomposerRecipeChance(var79, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 4) })); Molecule var81 = this.molecule(EnumMolecule.cellulose, 1); SynthesisRecipe.add(new SynthesisRecipe(var74, true, 100, new Chemical[] { var81, var81, var81, null, var81, null, null, null, null })); SynthesisRecipe.add(new SynthesisRecipe(var75, true, 100, new Chemical[] { null, null, null, null, var81, null, var81, var81, var81 })); SynthesisRecipe.add(new SynthesisRecipe(var76, true, 100, new Chemical[] { var81, null, var81, null, null, null, var81, null, var81 })); SynthesisRecipe.add(new SynthesisRecipe(var77, true, 100, new Chemical[] { var81, null, null, var81, var81, null, var81, null, null })); ItemStack var82 = new ItemStack(Item.dyePowder, 1, 0); ItemStack var83 = new ItemStack(Item.dyePowder, 1, 1); ItemStack var84 = new ItemStack(Item.dyePowder, 1, 2); ItemStack var85 = new ItemStack(Item.dyePowder, 1, 4); ItemStack var86 = new ItemStack(Item.dyePowder, 1, 5); ItemStack var87 = new ItemStack(Item.dyePowder, 1, 6); ItemStack var88 = new ItemStack(Item.dyePowder, 1, 7); ItemStack var89 = new ItemStack(Item.dyePowder, 1, 8); ItemStack var90 = new ItemStack(Item.dyePowder, 1, 9); ItemStack var91 = new ItemStack(Item.dyePowder, 1, 10); ItemStack var92 = new ItemStack(Item.dyePowder, 1, 11); ItemStack var93 = new ItemStack(Item.dyePowder, 1, 12); ItemStack var94 = new ItemStack(Item.dyePowder, 1, 13); ItemStack var95 = new ItemStack(Item.dyePowder, 1, 14); ItemStack var96 = new ItemStack(Item.dyePowder, 1, 15); DecomposerRecipe.add(new DecomposerRecipe(var82, new Chemical[] { this.molecule(EnumMolecule.blackPigment) })); DecomposerRecipe.add(new DecomposerRecipe(var83, new Chemical[] { this.molecule(EnumMolecule.redPigment) })); DecomposerRecipe.add(new DecomposerRecipe(var84, new Chemical[] { this.molecule(EnumMolecule.greenPigment) })); DecomposerRecipe.add(new DecomposerRecipe(var85, new Chemical[] { this.molecule(EnumMolecule.lazurite) })); DecomposerRecipe.add(new DecomposerRecipe(var86, new Chemical[] { this.molecule(EnumMolecule.purplePigment) })); DecomposerRecipe.add(new DecomposerRecipe(var87, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) })); DecomposerRecipe.add(new DecomposerRecipe(var88, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) })); DecomposerRecipe.add(new DecomposerRecipe(var89, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) })); DecomposerRecipe.add(new DecomposerRecipe(var90, new Chemical[] { this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) })); DecomposerRecipe.add(new DecomposerRecipe(var91, new Chemical[] { this.molecule(EnumMolecule.limePigment) })); DecomposerRecipe.add(new DecomposerRecipe(var92, new Chemical[] { this.molecule(EnumMolecule.yellowPigment) })); DecomposerRecipe.add(new DecomposerRecipe(var93, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment) })); DecomposerRecipe.add(new DecomposerRecipe(var94, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) })); DecomposerRecipe.add(new DecomposerRecipe(var95, new Chemical[] { this.molecule(EnumMolecule.orangePigment) })); DecomposerRecipe.add(new DecomposerRecipe(var96, new Chemical[] { this.molecule(EnumMolecule.whitePigment) })); SynthesisRecipe.add(new SynthesisRecipe(var82, false, 50, new Chemical[] { this.molecule(EnumMolecule.blackPigment) })); SynthesisRecipe.add(new SynthesisRecipe(var83, false, 50, new Chemical[] { this.molecule(EnumMolecule.redPigment) })); SynthesisRecipe.add(new SynthesisRecipe(var84, false, 50, new Chemical[] { this.molecule(EnumMolecule.greenPigment) })); SynthesisRecipe.add(new SynthesisRecipe(var85, false, 50, new Chemical[] { this.molecule(EnumMolecule.lazurite) })); SynthesisRecipe.add(new SynthesisRecipe(var86, false, 50, new Chemical[] { this.molecule(EnumMolecule.purplePigment) })); SynthesisRecipe.add(new SynthesisRecipe(var87, false, 50, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) })); SynthesisRecipe.add(new SynthesisRecipe(var88, false, 50, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) })); SynthesisRecipe.add(new SynthesisRecipe(var89, false, 50, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) })); SynthesisRecipe.add(new SynthesisRecipe(var90, false, 50, new Chemical[] { this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) })); SynthesisRecipe.add(new SynthesisRecipe(var91, false, 50, new Chemical[] { this.molecule(EnumMolecule.limePigment) })); SynthesisRecipe.add(new SynthesisRecipe(var92, false, 50, new Chemical[] { this.molecule(EnumMolecule.yellowPigment) })); SynthesisRecipe.add(new SynthesisRecipe(var93, false, 50, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment) })); SynthesisRecipe.add(new SynthesisRecipe(var94, false, 50, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) })); SynthesisRecipe.add(new SynthesisRecipe(var95, false, 50, new Chemical[] { this.molecule(EnumMolecule.orangePigment) })); SynthesisRecipe.add(new SynthesisRecipe(var96, false, 50, new Chemical[] { this.molecule(EnumMolecule.whitePigment) })); ItemStack var97 = new ItemStack(Block.cloth, 1, 0); ItemStack var98 = new ItemStack(Block.cloth, 1, 1); ItemStack var99 = new ItemStack(Block.cloth, 1, 2); ItemStack var100 = new ItemStack(Block.cloth, 1, 3); ItemStack var101 = new ItemStack(Block.cloth, 1, 4); ItemStack var102 = new ItemStack(Block.cloth, 1, 5); ItemStack var103 = new ItemStack(Block.cloth, 1, 6); ItemStack var104 = new ItemStack(Block.cloth, 1, 7); ItemStack var105 = new ItemStack(Block.cloth, 1, 8); ItemStack var106 = new ItemStack(Block.cloth, 1, 9); ItemStack var107 = new ItemStack(Block.cloth, 1, 10); ItemStack var108 = new ItemStack(Block.cloth, 1, 11); new ItemStack(Block.cloth, 1, 12); ItemStack var110 = new ItemStack(Block.cloth, 1, 13); ItemStack var111 = new ItemStack(Block.cloth, 1, 14); ItemStack var112 = new ItemStack(Block.cloth, 1, 15); DecomposerRecipe.add(new DecomposerRecipeChance(var111, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment) })); DecomposerRecipe.add(new DecomposerRecipeChance(var110, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.greenPigment) })); DecomposerRecipe.add(new DecomposerRecipeChance(var108, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lazurite) })); DecomposerRecipe.add(new DecomposerRecipeChance(var107, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.purplePigment) })); DecomposerRecipe.add(new DecomposerRecipeChance(var106, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) })); DecomposerRecipe.add(new DecomposerRecipeChance(var105, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) })); DecomposerRecipe.add(new DecomposerRecipeChance(var104, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) })); DecomposerRecipe.add(new DecomposerRecipeChance(var103, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) })); DecomposerRecipe.add(new DecomposerRecipeChance(var102, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.limePigment) })); DecomposerRecipe.add(new DecomposerRecipeChance(var101, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.yellowPigment) })); DecomposerRecipe.add(new DecomposerRecipeChance(var100, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment) })); DecomposerRecipe.add(new DecomposerRecipeChance(var99, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) })); DecomposerRecipe.add(new DecomposerRecipeChance(var98, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.orangePigment) })); DecomposerRecipe.add(new DecomposerRecipeChance(var97, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment) })); DecomposerRecipe.add(new DecomposerRecipeChance(var112, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.blackPigment) })); SynthesisRecipe.add(new SynthesisRecipe(var111, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment) })); SynthesisRecipe.add(new SynthesisRecipe(var110, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.greenPigment) })); SynthesisRecipe.add(new SynthesisRecipe(var108, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lazurite) })); SynthesisRecipe.add(new SynthesisRecipe(var107, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.purplePigment) })); SynthesisRecipe.add(new SynthesisRecipe(var106, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) })); SynthesisRecipe.add(new SynthesisRecipe(var105, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) })); SynthesisRecipe.add(new SynthesisRecipe(var104, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) })); SynthesisRecipe.add(new SynthesisRecipe(var103, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) })); SynthesisRecipe.add(new SynthesisRecipe(var102, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.limePigment) })); SynthesisRecipe.add(new SynthesisRecipe(var101, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.yellowPigment) })); SynthesisRecipe.add(new SynthesisRecipe(var100, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment) })); SynthesisRecipe.add(new SynthesisRecipe(var99, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) })); SynthesisRecipe.add(new SynthesisRecipe(var98, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.orangePigment) })); SynthesisRecipe.add(new SynthesisRecipe(var97, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment) })); SynthesisRecipe.add(new SynthesisRecipe(var112, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.blackPigment) })); Molecule var113 = this.molecule(EnumMolecule.polyvinylChloride); ItemStack var114 = new ItemStack(Item.record13); ItemStack var115 = new ItemStack(Item.recordCat); ItemStack var116 = new ItemStack(Item.recordFar); ItemStack var117 = new ItemStack(Item.recordMall); ItemStack var118 = new ItemStack(Item.recordMellohi); ItemStack var119 = new ItemStack(Item.recordStal); ItemStack var120 = new ItemStack(Item.recordStrad); ItemStack var121 = new ItemStack(Item.recordWard); ItemStack var122 = new ItemStack(Item.recordChirp); DecomposerRecipe.add(new DecomposerRecipe(var114, new Chemical[] { var113 })); DecomposerRecipe.add(new DecomposerRecipe(var115, new Chemical[] { var113 })); DecomposerRecipe.add(new DecomposerRecipe(var116, new Chemical[] { var113 })); DecomposerRecipe.add(new DecomposerRecipe(var117, new Chemical[] { var113 })); DecomposerRecipe.add(new DecomposerRecipe(var118, new Chemical[] { var113 })); DecomposerRecipe.add(new DecomposerRecipe(var119, new Chemical[] { var113 })); DecomposerRecipe.add(new DecomposerRecipe(var120, new Chemical[] { var113 })); DecomposerRecipe.add(new DecomposerRecipe(var121, new Chemical[] { var113 })); DecomposerRecipe.add(new DecomposerRecipe(var122, new Chemical[] { var113 })); SynthesisRecipe.add(new SynthesisRecipe(var114, false, 1000, new Chemical[] { var113 })); SynthesisRecipe.add(new SynthesisRecipe(var115, false, 1000, new Chemical[] { null, var113 })); SynthesisRecipe.add(new SynthesisRecipe(var116, false, 1000, new Chemical[] { null, null, var113 })); SynthesisRecipe.add(new SynthesisRecipe(var117, false, 1000, new Chemical[] { null, null, null, var113 })); SynthesisRecipe.add(new SynthesisRecipe(var118, false, 1000, new Chemical[] { null, null, null, null, var113 })); SynthesisRecipe.add(new SynthesisRecipe(var119, false, 1000, new Chemical[] { null, null, null, null, null, var113 })); SynthesisRecipe.add(new SynthesisRecipe(var120, false, 1000, new Chemical[] { null, null, null, null, null, null, var113 })); SynthesisRecipe.add(new SynthesisRecipe(var121, false, 1000, new Chemical[] { null, null, null, null, null, null, null, var113 })); SynthesisRecipe.add(new SynthesisRecipe(var122, false, 1000, new Chemical[] { null, null, null, null, null, null, null, null, var113 })); ItemStack var123 = new ItemStack(Block.mushroomBrown); ItemStack var124 = new ItemStack(Block.mushroomRed); ItemStack var125 = new ItemStack(Block.cactus); DecomposerRecipe.add(new DecomposerRecipe(var123, new Chemical[] { this.molecule(EnumMolecule.psilocybin), this.molecule(EnumMolecule.water, 2) })); DecomposerRecipe.add(new DecomposerRecipe(var124, new Chemical[] { this.molecule(EnumMolecule.pantherine), this.molecule(EnumMolecule.water, 2) })); DecomposerRecipe.add(new DecomposerRecipe(var125, new Chemical[] { this.molecule(EnumMolecule.mescaline), this.molecule(EnumMolecule.water, 20) })); SynthesisRecipe.add(new SynthesisRecipe(var125, true, 200, new Chemical[] { this.molecule(EnumMolecule.water, 5), null, this.molecule(EnumMolecule.water, 5), null, this.molecule(EnumMolecule.mescaline), null, this.molecule(EnumMolecule.water, 5), null, this.molecule(EnumMolecule.water, 5) })); DecomposerRecipe.add(new DecomposerRecipeChance(var13, 0.8F, new Chemical[] { this.molecule(EnumMolecule.iron3oxide, 6), this.molecule(EnumMolecule.strontiumNitrate, 6) })); DecomposerRecipe.add(new DecomposerRecipeChance(var18, 0.42F, new Chemical[] { this.molecule(EnumMolecule.iron3oxide), this.molecule(EnumMolecule.strontiumNitrate) })); SynthesisRecipe.add(new SynthesisRecipe(var18, true, 100, new Chemical[] { null, null, this.molecule(EnumMolecule.iron3oxide), null, this.molecule(EnumMolecule.strontiumNitrate), null, null, null, null })); ItemStack var126 = new ItemStack(Item.enderPearl); DecomposerRecipe.add(new DecomposerRecipe(var126, new Chemical[] { this.element(EnumElement.Es), this.molecule(EnumMolecule.calciumCarbonate, 8) })); SynthesisRecipe.add(new SynthesisRecipe(var126, true, 5000, new Chemical[] { this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.element(EnumElement.Es), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate) })); ItemStack var127 = new ItemStack(Block.obsidian); DecomposerRecipe.add(new DecomposerRecipe(var127, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16), this.molecule(EnumMolecule.magnesiumOxide, 8) })); SynthesisRecipe.add(new SynthesisRecipe(var127, true, 1000, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.magnesiumOxide, 2), null, this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.magnesiumOxide, 2), this.molecule(EnumMolecule.magnesiumOxide, 2), this.molecule(EnumMolecule.magnesiumOxide, 2) })); ItemStack var128 = new ItemStack(Item.bone); ItemStack var129 = new ItemStack(Item.silk); new ItemStack(Block.cloth, 1, -1); new ItemStack(Block.cloth, 1, 0); DecomposerRecipe.add(new DecomposerRecipe(var128, new Chemical[] { this.molecule(EnumMolecule.hydroxylapatite) })); DecomposerRecipe.add(new DecomposerRecipeChance(var129, 0.45F, new Chemical[] { this.molecule(EnumMolecule.serine), this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.alinine) })); SynthesisRecipe.add(new SynthesisRecipe(var128, false, 100, new Chemical[] { this.molecule(EnumMolecule.hydroxylapatite) })); SynthesisRecipe.add(new SynthesisRecipe(var129, true, 150, new Chemical[] { this.molecule(EnumMolecule.serine), this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.alinine) })); ItemStack var132 = new ItemStack(Block.cobblestone); DecomposerRecipe.add(new DecomposerRecipeSelect(var1, 0.2F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fe), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Mg), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ti), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Zn), this.element(EnumElement.O) }) })); DecomposerRecipe.add(new DecomposerRecipeSelect(var132, 0.1F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fe), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Mg), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ti), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Na), this.element(EnumElement.Cl) }) })); DecomposerRecipe.add(new DecomposerRecipeSelect(var3, 0.07F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fe), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Mg), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ti), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Zn), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ga), this.element(EnumElement.As) }) })); SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.cobblestone, 8), true, 50, new Chemical[] { this.element(EnumElement.Si), null, null, null, this.element(EnumElement.O, 2), null })); SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.stone, 7), true, 50, new Chemical[] { this.element(EnumElement.Si), null, null, this.element(EnumElement.O, 2), null, null })); SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.dirt, 16), true, 50, new Chemical[] { null, null, null, null, this.element(EnumElement.O, 2), this.element(EnumElement.Si) })); ItemStack var133 = new ItemStack(Block.netherrack); ItemStack var134 = new ItemStack(Block.slowSand); ItemStack var135 = new ItemStack(Block.whiteStone); DecomposerRecipe.add(new DecomposerRecipeSelect(var133, 0.1F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O), this.element(EnumElement.Fe) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.Ni), this.element(EnumElement.Tc) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 3), this.element(EnumElement.Ti), this.element(EnumElement.Fe) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 1), this.element(EnumElement.W, 4), this.element(EnumElement.Cr, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 10), this.element(EnumElement.W, 1), this.element(EnumElement.Zn, 8), this.element(EnumElement.Be, 4) }) })); DecomposerRecipe.add(new DecomposerRecipeSelect(var134, 0.2F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb, 3), this.element(EnumElement.Be, 1), this.element(EnumElement.Si, 2), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb, 1), this.element(EnumElement.Si, 5), this.element(EnumElement.O, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 6), this.element(EnumElement.O, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Es, 1), this.element(EnumElement.O, 2) }) })); DecomposerRecipe.add(new DecomposerRecipeSelect(var135, 0.8F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O), this.element(EnumElement.H, 4), this.element(EnumElement.Li) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Es) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pu) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fr) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Nd) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O, 4) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.H, 4) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Be, 8) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Li, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Zr) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Na) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Rb) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ga), this.element(EnumElement.As) }) })); ItemStack var136 = new ItemStack(Block.plantYellow); DecomposerRecipe.add(new DecomposerRecipeChance(var136, 0.3F, new Chemical[] { new Molecule(EnumMolecule.shikimicAcid, 2) })); ItemStack var137 = new ItemStack(Item.rottenFlesh); DecomposerRecipe.add(new DecomposerRecipeChance(var137, 0.05F, new Chemical[] { new Molecule(EnumMolecule.nod, 1) })); ItemStack var138 = new ItemStack(Block.tallGrass, 1, 2); DecomposerRecipe.add(new DecomposerRecipeChance(var138, 0.07F, new Chemical[] { new Molecule(EnumMolecule.biocide, 2) })); ItemStack var139 = new ItemStack(Block.tallGrass, 1, 1); DecomposerRecipe.add(new DecomposerRecipeChance(var139, 0.1F, new Chemical[] { new Molecule(EnumMolecule.afroman, 2) })); // BOP CHEMICAL PROCESSING SECTION // END this.addDecomposerRecipesFromMolecules(); this.addSynthesisRecipesFromMolecules(); this.addUnusedSynthesisRecipes(); this.registerPoisonRecipes(EnumMolecule.poison); this.registerPoisonRecipes(EnumMolecule.sucrose); this.registerPoisonRecipes(EnumMolecule.psilocybin); this.registerPoisonRecipes(EnumMolecule.methamphetamine); this.registerPoisonRecipes(EnumMolecule.amphetamine); this.registerPoisonRecipes(EnumMolecule.pantherine); this.registerPoisonRecipes(EnumMolecule.ethanol); this.registerPoisonRecipes(EnumMolecule.penicillin); this.registerPoisonRecipes(EnumMolecule.testosterone); this.registerPoisonRecipes(EnumMolecule.xanax); this.registerPoisonRecipes(EnumMolecule.mescaline); this.registerPoisonRecipes(EnumMolecule.quinine); this.registerPoisonRecipes(EnumMolecule.sulfuricAcid); this.registerPoisonRecipes(EnumMolecule.ttx); this.registerPoisonRecipes(EnumMolecule.pal2); this.registerPoisonRecipes(EnumMolecule.nod); this.registerPoisonRecipes(EnumMolecule.afroman); } private void addDecomposerRecipesFromMolecules() { EnumMolecule[] var1 = EnumMolecule.molecules; int var2 = var1.length; for (int var3 = 0; var3 < var2; ++var3) { EnumMolecule var4 = var1[var3]; ArrayList var5 = var4.components(); Chemical[] var6 = (Chemical[]) var5.toArray(new Chemical[var5.size()]); ItemStack var7 = new ItemStack(MinechemItems.molecule, 1, var4.id()); DecomposerRecipe.add(new DecomposerRecipe(var7, var6)); } } private void addSynthesisRecipesFromMolecules() { EnumMolecule[] var1 = EnumMolecule.molecules; int var2 = var1.length; for (int var3 = 0; var3 < var2; ++var3) { EnumMolecule var4 = var1[var3]; ArrayList var5 = var4.components(); ItemStack var6 = new ItemStack(MinechemItems.molecule, 1, var4.id()); SynthesisRecipe.add(new SynthesisRecipe(var6, false, 50, var5)); } } private void addUnusedSynthesisRecipes() { Iterator var1 = DecomposerRecipe.recipes.iterator(); while (var1.hasNext()) { DecomposerRecipe var2 = (DecomposerRecipe) var1.next(); if (var2.getInput().getItemDamage() != -1) { boolean var3 = false; Iterator var4 = SynthesisRecipe.recipes.iterator(); while (true) { if (var4.hasNext()) { SynthesisRecipe var5 = (SynthesisRecipe) var4.next(); if (!Util.stacksAreSameKind(var5.getOutput(), var2.getInput())) { continue; } var3 = true; } if (!var3) { ArrayList var6 = var2.getOutputRaw(); if (var6 != null) { SynthesisRecipe.add(new SynthesisRecipe(var2.getInput(), false, 100, var6)); } } break; } } } } private ItemStack createPoisonedItemStack(Item var1, int var2, EnumMolecule var3) { ItemStack var4 = new ItemStack(MinechemItems.molecule, 1, var3.id()); ItemStack var5 = new ItemStack(var1, 1, var2); ItemStack var6 = new ItemStack(var1, 1, var2); NBTTagCompound var7 = new NBTTagCompound(); var7.setBoolean("minechem.isPoisoned", true); var7.setInteger("minechem.effectType", var3.id()); var6.setTagCompound(var7); GameRegistry.addShapelessRecipe(var6, new Object[]{var4, var5}); return var6; } private void registerPoisonRecipes(EnumMolecule var1) { this.createPoisonedItemStack(Item.appleRed, 0, var1); this.createPoisonedItemStack(Item.porkCooked, 0, var1); this.createPoisonedItemStack(Item.beefCooked, 0, var1); this.createPoisonedItemStack(Item.carrot, 0, var1); this.createPoisonedItemStack(Item.bakedPotato, 0, var1); this.createPoisonedItemStack(Item.bread, 0, var1); this.createPoisonedItemStack(Item.potato, 0, var1); this.createPoisonedItemStack(Item.bucketMilk, 0, var1); this.createPoisonedItemStack(Item.fishCooked, 0, var1); this.createPoisonedItemStack(Item.cookie, 0, var1); this.createPoisonedItemStack(Item.pumpkinPie, 0, var1); } @ForgeSubscribe public void oreEvent(OreDictionary.OreRegisterEvent var1) { String[] compounds = {"Aluminium","Titanium","Chrome", "Tungsten", "Lead", "Zinc", "Platinum", "Nickel", "Osmium", "Iron", "Gold", "Coal", "Copper", "Tin", "Silver", "RefinedIron", "Steel", "Bronze", "Brass", "Electrum", "Invar"};//,"Iridium"}; EnumElement[][] elements = {{EnumElement.Al}, {EnumElement.Ti}, {EnumElement.Cr}, {EnumElement.W}, {EnumElement.Pb}, {EnumElement.Zn}, {EnumElement.Pt}, {EnumElement.Ni}, {EnumElement.Os}, {EnumElement.Fe}, {EnumElement.Au}, {EnumElement.C}, {EnumElement.Cu}, {EnumElement.Sn}, {EnumElement.Ag}, {EnumElement.Fe}, {EnumElement.Fe, EnumElement.C}, //Steel {EnumElement.Sn, EnumElement.Cu}, {EnumElement.Cu},//Bronze {EnumElement.Zn, EnumElement.Cu}, //Brass {EnumElement.Ag, EnumElement.Au}, //Electrum {EnumElement.Fe, EnumElement.Ni} //Invar };//, EnumElement.Ir int[][] proportions = {{4},{4},{4}, {4},{4},{4}, {4},{4},{4}, {4},{4},{4}, {4},{4},{4}, {4}, {4,4}, {1,3},{1,3},{2,2},{2,1}}; String[] itemTypes = {"dustSmall", "dust", "ore" , "ingot", "block", "gear", "plate"}; //"nugget", "plate" boolean[] craftable = {true, true, false, false, false, false, false}; int[] sizeCoeff = {1, 4, 8, 4, 36, 16, 4}; for (int i=0; i<compounds.length; i++){ for (int j=0; j<itemTypes.length; j++){ if(var1.Name.equals(itemTypes[j]+compounds[i])){ System.out.print("Adding recipe for " + itemTypes[j] + compounds[i]); List<Chemical> _elems = new ArrayList<Chemical>(); for (int k=0; k<elements[i].length; k++){ _elems.add(this.element(elements[i][k], proportions[i][k]*sizeCoeff[j])); } DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, _elems.toArray(new Chemical[_elems.size()]))); if(compounds[i].equals("Iron") && itemTypes[j].equals("dust")){ SynthesisRecipe.recipes.remove(recipeIron); } if(compounds[i].equals("Gold") && itemTypes[j].equals("dust")){ SynthesisRecipe.recipes.remove(recipeGold); } if(compounds[i].equals("Coal") && itemTypes[j].equals("dust")){ SynthesisRecipe.remove(new ItemStack(Item.coal)); SynthesisRecipe.remove(new ItemStack(Block.oreCoal)); SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.coal), true, 2000, new Chemical[]{this.element(EnumElement.C,4), null, this.element(EnumElement.C,4), null, null, null, this.element(EnumElement.C,4), null, this.element(EnumElement.C,4)})); } if (craftable[j]){ SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000*sizeCoeff[j], _elems.toArray(new Chemical[_elems.size()]))); } return; } } } // BEGIN ORE DICTONARY BULLSHIT if(var1.Name.contains("uraniumOre")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.U, 4)})); } else if(var1.Name.contains("uraniumIngot")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.U, 2)})); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 5000, new Chemical[]{this.element(EnumElement.U, 2)})); } else if(var1.Name.contains("itemDropUranium")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.U, 2)})); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 5000, new Chemical[]{this.element(EnumElement.U, 2)})); } else if(var1.Name.contains("gemApatite")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Ca, 5), this.molecule(EnumMolecule.phosphate, 4), this.element(EnumElement.Cl)})); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.element(EnumElement.Ca, 5), this.molecule(EnumMolecule.phosphate, 4), this.element(EnumElement.Cl)})); // } else if(var1.Name.contains("Iridium")) { // DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Ir, 2)})); // SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.element(EnumElement.Ir, 2)})); } else if(var1.Name.contains("Ruby")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.aluminiumOxide), this.element(EnumElement.Cr)})); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.aluminiumOxide), this.element(EnumElement.Cr)})); } else if(var1.Name.contains("Sapphire")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.aluminiumOxide, 2)})); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.aluminiumOxide, 2)})); } else if(var1.Name.contains("plateSilicon")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Si, 2)})); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.element(EnumElement.Si, 2)})); } else if(var1.Name.contains("xychoriumBlue")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Cu, 1)})); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 300, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Cu, 1)})); } else if(var1.Name.contains("xychoriumRed")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Fe, 1)})); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 300, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Fe, 1)})); } else if(var1.Name.contains("xychoriumGreen")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.V, 1)})); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 300, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.V, 1)})); } else if(var1.Name.contains("xychoriumDark")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Si, 1)})); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 300, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Si, 1)})); } else if(var1.Name.contains("xychoriumLight")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Ti, 1)})); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 300, new Chemical[]{this.element(EnumElement.Zr, 2), this.element(EnumElement.Ti, 1)})); } else if(var1.Name.contains("ingotCobalt")) { // Tungsten - Cobalt Alloy DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Co, 2), this.element(EnumElement.W, 2)})); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 5000, new Chemical[]{this.element(EnumElement.Co, 2), this.element(EnumElement.W, 2)})); } else if(var1.Name.contains("ingotArdite")) { // Tungsten - Iron - Silicon Alloy DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Fe, 2), this.element(EnumElement.W, 2), this.element(EnumElement.Si, 2)})); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 5000, new Chemical[]{this.element(EnumElement.Fe, 2), this.element(EnumElement.W, 2), this.element(EnumElement.Si, 2)})); } else if(var1.Name.contains("ingotManyullyn")) { // Tungsten - Iron - Silicon - Cobalt Alloy DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.element(EnumElement.Fe, 2), this.element(EnumElement.W, 2), this.element(EnumElement.Si, 2), this.element(EnumElement.Co, 2)})); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 7000, new Chemical[]{this.element(EnumElement.Fe, 2), this.element(EnumElement.W, 2), this.element(EnumElement.Si, 2), this.element(EnumElement.Co, 2)})); } else if(var1.Name.contains("cropMaloberry")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.stevenk), this.molecule(EnumMolecule.sucrose)})); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.stevenk), this.molecule(EnumMolecule.sucrose)})); } else if(var1.Name.contains("cropDuskberry")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.psilocybin), this.element(EnumElement.S, 2)})); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.psilocybin), this.element(EnumElement.S, 2)})); } else if(var1.Name.contains("cropSkyberry")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.theobromine), this.element(EnumElement.S, 2)})); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.theobromine), this.element(EnumElement.S, 2)})); } else if(var1.Name.contains("cropBlightberry")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.quinine), this.element(EnumElement.S, 2)})); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.quinine), this.element(EnumElement.S, 2)})); } else if(var1.Name.contains("cropBlueberry")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.blueorgodye), this.molecule(EnumMolecule.sucrose, 2)})); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.blueorgodye), this.molecule(EnumMolecule.sucrose, 2)})); } else if(var1.Name.contains("cropRaspberry")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.redorgodye), this.molecule(EnumMolecule.sucrose, 2)})); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.redorgodye), this.molecule(EnumMolecule.sucrose, 2)})); } else if(var1.Name.contains("cropBlackberry")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[]{this.molecule(EnumMolecule.purpleorgodye), this.molecule(EnumMolecule.sucrose, 2)})); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[]{this.molecule(EnumMolecule.purpleorgodye), this.molecule(EnumMolecule.sucrose, 2)})); } // cropStingberry // Need to add support for BOP } // END // BEGIN MISC FUNCTIONS private Element element(EnumElement var1, int var2) { return new Element(var1, var2); } private Element element(EnumElement var1) { return new Element(var1, 1); } private Molecule molecule(EnumMolecule var1, int var2) { return new Molecule(var1, var2); } private Molecule molecule(EnumMolecule var1) { return new Molecule(var1, 1); } // END } // EOF
package app.hongs.cmdlet; import app.hongs.CoreLogger; import app.hongs.HongsError; import app.hongs.util.Data; import app.hongs.util.Tool; import java.util.ArrayList; import java.util.Formatter; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * * @author Hongs */ public class CmdletHelper { private static final String[] GETERRS = { "Can not parse rule '%chk'", "Option '%opt' is required", "Option '%opt' must be specified value", "Option '%opt' can only have one value", "Value for option '%opt' must be int", "Value for option '%opt' must be float", "Value for option '%opt' must be boolean", "Value for option '%opt' not matches: %mat", "Unrecognized option '%opt'", "Unupport anonymous options" }; / /** * * Perl Getopt::Long * @param args * @param chks * @return */ public static Map<String, Object> getOpts(String[] args, String... chks) { Map<String, Object[]> chkz = new HashMap(); Map<String, Object> newOpts = new HashMap(); List<String> newArgs = new ArrayList(); Set<String> reqOpts = new LinkedHashSet(); Set<String> errMsgs = new LinkedHashSet(); Pattern p = Pattern.compile("^([\\w\\.\\-\\|]*)(=|:|\\+|\\*)([sifb]|\\/(.+)\\/(i)?( .*)?)$"); Pattern bp = Pattern.compile("^(true|false|yes|no|y|n|1|0)$", Pattern.CASE_INSENSITIVE); Pattern tp = Pattern.compile("^(true|yes|y|1)$", Pattern.CASE_INSENSITIVE); Pattern fp = Pattern.compile("^\\d+(\\.\\d+)?$"); Pattern ip = Pattern.compile("^\\d+$"); boolean ub = false; boolean vb = false; String hlp = null ; String pre = "\r\n\t"; for (String chk : chks) { Matcher m = p.matcher(chk); if (!m.find()) { if (chk.equals("!U")) { ub = true; continue; } else if (chk.equals("!A")) { vb = true; continue; } else if (chk.startsWith("?")) { hlp = chk.substring(1); continue; } errMsgs.add(GETERRS[0].replace("%chk", chk)); continue; } String name = m.group(1); String sign = m.group(2); String type = m.group(3); if ("=".equals(sign) || "+".equals(sign)) { reqOpts.add(name); } if (type.startsWith("/")) { String reg = m.group(4); String mod = m.group(5); String err = m.group(6); Pattern pat; if (mod != null) { pat = Pattern.compile(reg, Pattern.CASE_INSENSITIVE); } else { pat = Pattern.compile(reg); } if (err != null) { err = err.trim(); } else { err = GETERRS[7]; } reg = "/"+reg+"/"+mod; chkz.put(name, new Object[] {sign.charAt(0),'r',pat,reg,err}); } else { chkz.put(name, new Object[] {sign.charAt(0), type.charAt(0)}); } } F:for (int i = 0; i < args.length; i ++) { String name = args[i]; if (name.startsWith(" name = name.substring(2); if (chkz.containsKey(name)) { Object[] chk = chkz.get(name); char sign = (Character)chk[0]; char type = (Character)chk[1]; Pattern rp = null; String reg = null; String err = null; Object val = null; List vals = null; if ('r' == type) { rp = (Pattern)chk[3]; reg = (String) chk[4]; err = (String) chk[5]; } if ('+' == sign || '*' == sign) { vals = (List)newOpts.get(name); if (vals == null) { vals = new ArrayList( ); newOpts.put(name, vals); } } W:while (i < args.length-1) { String arg = args[i + 1]; if (arg.startsWith(" if (i == 0) break; else continue F; } if (arg.startsWith("\\")) { arg = arg.substring(1); } i ++; switch (type) { case 'i': if (!ip.matcher(arg).matches()) { errMsgs.add(GETERRS[4].replace("%opt", name)); continue W; } val = Long.parseLong(arg); break; case 'f': if (!fp.matcher(arg).matches()) { errMsgs.add(GETERRS[5].replace("%opt", name)); continue W; } val = Double.parseDouble(arg); break; case 'b': if (!bp.matcher(arg).matches()) { errMsgs.add(GETERRS[6].replace("%opt", name)); continue W; } val = tp.matcher(arg).matches(); break; case 'r': if (!rp.matcher(arg).matches()) { errMsgs.add(err.replace("%opt", name).replace("%mat", reg)); continue W; } default: val = arg; } if ('+' == sign || '*' == sign) { vals.add(val ); } else { if (newOpts.containsKey(name)) { errMsgs.add(GETERRS[3].replace("%opt", name)); } else { newOpts.put(name, val ); } } continue F; } if ('b' == type) { if ('+'== sign || '*' == sign) { vals.add(true); } else { if (newOpts.containsKey(name)) { errMsgs.add(GETERRS[3].replace("%opt", name)); } else { newOpts.put(name, true); } } } else { errMsgs.add(GETERRS[2].replace("%opt", name)); } } else if (ub) { errMsgs.add(GETERRS[8].replace("%opt", name)); } else { newArgs.add( args[i]); } } else if (vb) { errMsgs.add(GETERRS[9]); } else { newArgs.add( args[i]); } } for (String name : reqOpts) { if (!newOpts.containsKey(name)) { Set<String> err = new LinkedHashSet(); err.add(GETERRS[1].replace("%opt", name)); err.addAll(errMsgs); errMsgs = err; } } if (!errMsgs.isEmpty()) { StringBuilder err = new StringBuilder(); for ( String msg : errMsgs ) { err.append(pre).append(msg); } String msg = err.toString( ); String trs = msg; if (null != hlp) { trs += pre + hlp.replaceAll("\\n", pre); } HongsError er = new HongsError(0x35, msg); er.setLocalizedOptions(trs); throw er; } else if (hlp != null && args.length == 0) { System.err.println(hlp.replaceAll("\\n",pre)); System.exit(0); } newOpts.put("", newArgs.toArray(new String[0])); return newOpts; } / /** * * () JSON . * @param data */ public static void preview(Object data) { Data.append(System.out , data, false); System.out.println(); } /** * * CoreLogger hongs.out, ; * , . * @param text */ public static void println(String text) { CoreLogger.getLogger(CoreLogger.space("hongs.out")) .trace(CoreLogger.envir( text )); } /** * * () 80 , * text 50 , . * @param text * @param rate , 0~100 */ public static void progres(String text, float rate) { StringBuilder sb = new StringBuilder(); Formatter ft = new Formatter( sb ); if (text == null) text = "" ; if (rate < 0 ) rate = 0; if (rate > 100 ) rate = 100; sb.append("["); for (int i = 0; i < 100; i += 5) { if (rate < i + 5) { sb.append(' '); } else { sb.append('='); } } sb.append("]"); ft.format(" %6.2f%% ", rate); sb.append(/* extra */ text); for (int i = sb.length(); i < 79; i += 1) { sb.append(" "); } sb.append( "\r"); if (rate == 100) { System.err.println(sb.toString()); } else { System.err.print (sb.toString()); } } /** * () * @param n * @param ok */ public static void progres(int n, int ok) { String notes = String.format("Ok(%d)", ok); float scale = (float)ok / n * 100; CmdletHelper.progres(notes, scale); } /** * () * @param n * @param ok * @param er */ public static void progres(int n, int ok, int er) { String notes = String.format("Ok(%d) Er(%d)", ok, er); float scale = (float)(er + ok) / n * 100; CmdletHelper.progres(notes, scale); } /** * (, ) * @param t () * @param n * @param ok */ public static void progres(long t, int n, int ok) { float scale = (float)ok / n * 100; t = System.currentTimeMillis() - t; float left1 = t / scale * 100 - t; String left2 = Tool.humanTime((long) left1); String left3 = String.format("Ok(%d) ETA: %s", ok, left2); CmdletHelper.progres(left3, scale); } /** * (, ) * @param t () * @param n * @param ok * @param er */ public static void progres(long t, int n, int ok, int er) { float scale = (float)( er + ok ) / n * 100; t = System.currentTimeMillis() - t; float left1 = t / scale * 100 - t; String left2 = Tool.humanTime((long) left1); String left3 = String.format("Ok(%d) Er(%d) ETA: %s", ok, er, left2); CmdletHelper.progres(left3, scale); } /** * * * try catch * * */ public static void progred() { System.err.println(""); } }
package net.littlebigisland.droidibus.ibus; /** * Message Parsing/Sending to IBus * @author Ted S <tass2001@gmail.com> * @package net.littlebigisland.droidibus */ import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * @TODO: Move all of this BS back to the service. It doesn't make sense for this to exist any longer on its own * * @author tsalmon * */ public class IBusMessageHandler { // User Provided Callback interface implementation public IBusMessageReceiver mDataReceiver = null; private Map<Byte, IBusSystemCommand> IBusSysMap = new HashMap<Byte, IBusSystemCommand>(); /** * Don't argue, this belongs here. * */ public class MessageDecoder{ public String decode(ArrayList<Byte> msg, int startByte, int endByte){ ArrayList<Byte> tempBytes = new ArrayList<Byte>(); while(startByte <= endByte){ tempBytes.add(msg.get(startByte)); startByte++; } byte[] strByte = new byte[tempBytes.size()]; for(int i = 0; i < tempBytes.size(); i++){ strByte[i] = tempBytes.get(i); } try { return new String(strByte, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return ""; } } } /** * Verify that the IBus Message is legitimate * by XORing all bytes if correct, the product * should be 0x00 * * @param ArrayList<byte> msgBuffer The buffer containing all bytes in the Message * @return boolean true if the message isn't corrupt, otherwise false */ public boolean checksumMessage(ArrayList<Byte> msgBuffer) { byte cksum = 0x00; for(byte msg : msgBuffer){ cksum = (byte) (cksum ^ msg); } return (cksum == 0x00) ? true : false; } /** * Temp * @param msg */ public void handleMessage(ArrayList<Byte> msg){ // This may be repeatedly executed but in the interest of readability // I'm not going to move it back into the class construct if(IBusSysMap.isEmpty()){ IBusSysMap.put(DeviceAddress.Radio.toByte(), new RadioSystemCommand()); IBusSysMap.put(DeviceAddress.InstrumentClusterElectronics.toByte(), new IKESystemCommand()); } // The first item in the IBus message indicates the source system try{ IBusSysMap.get(msg.get(0)).mapReceived(msg); }catch(NullPointerException npe){ // Things not in the map throw a NullPointerException } } /** * Register a callback listener * @param cb */ public void registerCallbackListener(IBusMessageReceiver cb){ mDataReceiver = cb; } } //Messages /* private byte[] volUp = new byte[] {0x50, 0x04, 0x68, 0x32, 0x11, 0x1F}; private byte[] volDown = new byte[] {0x50, 0x04, 0x68, 0x32, 0x10, 0x1E}; private byte[] nextBtnPress = new byte[] {0x50, 0x04, 0x68, 0x3B, 0x01, 0x06}; private byte[] nextBtnRls = new byte[] {0x50, 0x04, 0x68, 0x3B, 0x21, 0x26}; private byte[] prevBtnPress = new byte[] {0x50, 0x04, 0x68, 0x3B, 0x08, 0x0F}; private byte[] prevBtnRls = new byte[] {0x50, 0x04, 0x68, 0x3B, 0x28, 0x2f}; private byte[] modeBtnPress = new byte[] {(byte)0xF0, 0x04, 0x68, 0x48, 0x23,(byte) 0xF7}; private byte[] modeBtnRls = new byte[] {(byte)0xF0, 0x04, 0x68, 0x48, 0x23,(byte) 0x77}; private byte[] fuel2Rqst = new byte[] {0x3B, 0x05, (byte)0x80, 0x41, 0x05, 0x01, (byte)0xFB}; */
package org.exist.xquery.functions.xmldb; import java.io.File; import java.util.StringTokenizer; import org.exist.dom.QName; import org.exist.util.DirectoryScanner; import org.exist.util.MimeTable; import org.exist.util.MimeType; import org.exist.xmldb.EXistResource; import org.exist.xquery.Cardinality; import org.exist.xquery.FunctionSignature; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.SequenceIterator; import org.exist.xquery.value.SequenceType; import org.exist.xquery.value.StringValue; import org.exist.xquery.value.Type; import org.exist.xquery.value.ValueSequence; import org.xmldb.api.base.Collection; import org.xmldb.api.base.Resource; import org.xmldb.api.base.XMLDBException; import org.xmldb.api.modules.CollectionManagementService; /** * @author wolf */ public class XMLDBLoadFromPattern extends XMLDBAbstractCollectionManipulator { public final static FunctionSignature signatures[] = { new FunctionSignature( new QName("store-files-from-pattern", XMLDBModule.NAMESPACE_URI, XMLDBModule.PREFIX), "Store new resources into the database. Resources are read from the server's " + "file system, using file patterns. " + "The first argument denotes the collection where resources should be stored. " + "The collection can be either specified as a simple collection path or " + "an XMLDB URI. " + "The second argument is the directory in the file system wherefrom the files are read." + "The third argument is the file pattern. File pattern matching is based " + "on code from Apache's Ant, thus following the same conventions. For example: " + "*.xml matches any file ending with .xml in the current directory, **/*.xml matches files " + "in any directory below the current one. " + "The function returns a sequence of all document paths added " + "to the db. These can be directly passed to fn:doc() to retrieve the document.", new SequenceType[] { new SequenceType(Type.STRING, Cardinality.EXACTLY_ONE), new SequenceType(Type.STRING, Cardinality.EXACTLY_ONE), new SequenceType(Type.STRING, Cardinality.ONE_OR_MORE) }, new SequenceType(Type.STRING, Cardinality.ZERO_OR_MORE)), new FunctionSignature( new QName("store-files-from-pattern", XMLDBModule.NAMESPACE_URI, XMLDBModule.PREFIX), "Store new resources into the database. Resources are read from the server's " + "file system, using file patterns. " + "The first argument denotes the collection where resources should be stored. " + "The collection can be either specified as a simple collection path or " + "an XMLDB URI. " + "The second argument is the directory in the file system wherefrom the files are read." + "The third argument is the file pattern. File pattern matching is based " + "on code from Apache's Ant, thus following the same conventions. For example: " + "*.xml matches any file ending with .xml in the current directory, **/*.xml matches files " + "in any directory below the current one. " + "The fourth argument $d is used to specify a mime-type. If the mime-type " + "is something other than 'text/xml' or 'application/xml', the resource will be stored as " + "a binary resource." + "The function returns a sequence of all document paths added " + "to the db. These can be directly passed to fn:doc() to retrieve the document.", new SequenceType[] { new SequenceType(Type.STRING, Cardinality.EXACTLY_ONE), new SequenceType(Type.STRING, Cardinality.EXACTLY_ONE), new SequenceType(Type.STRING, Cardinality.ONE_OR_MORE), new SequenceType(Type.STRING, Cardinality.EXACTLY_ONE) }, new SequenceType(Type.STRING, Cardinality.ZERO_OR_MORE)), new FunctionSignature( new QName("store-files-from-pattern", XMLDBModule.NAMESPACE_URI, XMLDBModule.PREFIX), "Store new resources into the database. Resources are read from the server's " + "file system, using file patterns. " + "The first argument denotes the collection where resources should be stored. " + "The collection can be either specified as a simple collection path or " + "an XMLDB URI. " + "The second argument is the directory in the file system wherefrom the files are read." + "The third argument is the file pattern. File pattern matching is based " + "on code from Apache's Ant, thus following the same conventions. For example: " + "*.xml matches any file ending with .xml in the current directory, **/*.xml matches files " + "in any directory below the current one. " + "The fourth argument $d is used to specify a mime-type. If the mime-type " + "is something other than 'text/xml' or 'application/xml', the resource will be stored as " + "a binary resource." + "If the final boolean argument is true(), the directory structure will be kept in the collection, " + "otherwise all the matching resources, including the ones in sub-directories, will be stored " + "in the collection given in the first argument flatly." + "The function returns a sequence of all document paths added " + "to the db. These can be directly passed to fn:doc() to retrieve the document.", new SequenceType[] { new SequenceType(Type.STRING, Cardinality.EXACTLY_ONE), new SequenceType(Type.STRING, Cardinality.EXACTLY_ONE), new SequenceType(Type.STRING, Cardinality.ONE_OR_MORE), new SequenceType(Type.STRING, Cardinality.EXACTLY_ONE), new SequenceType(Type.BOOLEAN, Cardinality.EXACTLY_ONE) }, new SequenceType(Type.STRING, Cardinality.ZERO_OR_MORE)) }; public XMLDBLoadFromPattern(XQueryContext context, FunctionSignature signature) { super(context, signature); } /* (non-Javadoc) * @see org.exist.xquery.functions.xmldb.XMLDBAbstractCollectionManipulator#evalWithCollection(org.xmldb.api.base.Collection, org.exist.xquery.value.Sequence[], org.exist.xquery.value.Sequence) */ protected Sequence evalWithCollection(Collection collection, Sequence[] args, Sequence contextSequence) throws XPathException { File baseDir = new File(args[1].getStringValue()); LOG.debug("Loading files from directory: " + baseDir); Sequence patterns = args[2]; String resourceType = "XMLResource"; String mimeType = MimeType.XML_TYPE.getName(); boolean keepDirStructure = false; if(getSignature().getArgumentCount() > 3) { mimeType = args[3].getStringValue(); MimeType mime = MimeTable.getInstance().getContentType(mimeType); if(mime != null && !mime.isXMLType()) resourceType = "BinaryResource"; } if (getSignature().getArgumentCount() == 5) keepDirStructure = args[4].effectiveBooleanValue(); ValueSequence stored = new ValueSequence(); for(SequenceIterator i = patterns.iterate(); i.hasNext(); ) { String pattern = i.nextItem().getStringValue(); File[] files = DirectoryScanner.scanDir(baseDir, pattern); LOG.debug("Found: " + files.length); Collection col = collection; String relDir, prevDir = null; for(int j = 0; j < files.length; j++) { try { LOG.debug(files[j].getAbsolutePath()); String relPath = files[j].toString().substring( baseDir.toString().length() ); int p = relPath.lastIndexOf( File.separatorChar ); if( p >= 0 ) { relDir = relPath.substring( 0, p ); relDir = relDir.replace(File.separatorChar, '/'); } else { relDir = relPath; } if ( keepDirStructure && ( prevDir == null || ( !relDir.equals(prevDir) ) ) ) { col = makeColl(collection, relDir); prevDir = relDir; } //TODO : these probably need to be encoded Resource resource = col.createResource(files[j].getName(), resourceType); resource.setContent(files[j]); if("BinaryResource".equals(resourceType)) ((EXistResource)resource).setMimeType(mimeType); col.storeResource(resource); //TODO : use dedicated function in XmldbURI stored.add(new StringValue(col.getName() + "/" + resource.getId())); } catch (XMLDBException e) { LOG.warn("Could not store file " + files[j].getAbsolutePath() + ": " + e.getMessage(), e); } } } return stored; } private final Collection makeColl(Collection parentColl, String relPath) throws XMLDBException { CollectionManagementService mgtService; Collection current = parentColl, c; String token; StringTokenizer tok = new StringTokenizer(relPath, "/"); while (tok.hasMoreTokens()) { token = tok.nextToken(); c = current.getChildCollection(token); if (c == null) { mgtService = (CollectionManagementService) current.getService("CollectionManagementService", "1.0"); current = mgtService.createCollection(token); } else current = c; } return current; } }
package info.limpet.operations; import info.limpet.IChangeListener; import info.limpet.ICommand; import info.limpet.IContext; import info.limpet.IDocument; import info.limpet.IStoreGroup; import info.limpet.IStoreItem; import info.limpet.impl.Document; import info.limpet.impl.LocationDocument; import info.limpet.impl.LocationDocumentBuilder; import info.limpet.impl.NumberDocument; import info.limpet.impl.NumberDocumentBuilder; import info.limpet.impl.SampleData; import info.limpet.impl.StoreGroup; import info.limpet.impl.UIProperty; import info.limpet.operations.CollectionComplianceTests.TimePeriod; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.UUID; import javax.measure.unit.Unit; import org.eclipse.january.dataset.DatasetFactory; import org.eclipse.january.dataset.DoubleDataset; import org.eclipse.january.dataset.Maths; import org.eclipse.january.metadata.AxesMetadata; public abstract class AbstractCommand implements ICommand { private final String title; private final String description; private final boolean canUndo; private final boolean canRedo; private final IStoreGroup store; private final List<IStoreItem> inputs; private final List<Document<?>> outputs; private IStoreGroup _parent; @Override public void beingDeleted() { // ok, detach ourselves from our parent final IStoreGroup parent = this.getParent(); if(parent != null) { parent.remove(this); } // delete our children for(final Document<?> doc: outputs) { doc.beingDeleted(); } } /** * whether the command should recalculate if its children change * */ private boolean dynamic = true; final private UUID uuid; private final transient IContext context; public AbstractCommand(final String title, final String description, final IStoreGroup store, final boolean canUndo, final boolean canRedo, final List<IStoreItem> inputs, final IContext context) { this.title = title; this.description = description; this.store = store; this.canUndo = canUndo; this.canRedo = canRedo; this.context = context; this.inputs = new ArrayList<IStoreItem>(); this.outputs = new ArrayList<Document<?>>(); this.uuid = UUID.randomUUID(); // store any inputs, if we have any if (inputs != null) { this.getInputs().addAll(inputs); } } @Override public final void addChangeListener(final IChangeListener listener) { // TODO we should add change listener support } public final void addOutput(final Document<?> output) { getOutputs().add(output); // also register as a listener (esp for if it's being deleted) output.addChangeListener(this); } @Override public void addTransientChangeListener(final IChangeListener listener) { // TODO Auto-generated method stub } @Override public final boolean canRedo() { return canRedo; } @Override public final boolean canUndo() { return canUndo; } @Override public void collectionDeleted(final IStoreItem subject) { // ok, we rely on all of our inputs and outputs. // if any of them change, then we will self-destruct // ok, is this an output? // yes, clear it final List<Document<?>> toDelete = new ArrayList<Document<?>>(); toDelete.addAll(getOutputs()); // ok, we have a list of outputs. clear the outputs, // so we won't get any more outputs.clear(); for (final Document<?> t : toDelete) { // stop listening to it, so we don't get a delete message t.removeChangeListener(this); // and now delete it if (!t.equals(subject) && t.getParent() != null) { t.getParent().remove(t); } } ArrayList<IStoreItem> toDelete2 = new ArrayList<IStoreItem>(); toDelete2.addAll(getInputs()); // have safe list of inputs, now clear them getInputs().clear(); for (final IStoreItem t : toDelete2) { if (t instanceof Document<?>) { Document<?> doc = (Document<?>) t; // ok, stop listening to it doc.removeDependent(this); } else { t.removeChangeListener(this); } } // finally remove ourselves from parent if (getParent() != null) { getParent().remove(this); } } @Override public final void dataChanged(final IStoreItem subject) { // are we doing live updates? if (dynamic) { // ok, walk the tree, to see if this is // one of our inputs boolean requiresChange = false; for (final IStoreItem d : getInputs()) { if (d instanceof StoreGroup) { final StoreGroup sg = (StoreGroup) d; if (sg.contains(subject)) { requiresChange = true; break; } } else { if (d.equals(subject)) { requiresChange = true; break; } } } // is this an input to us? if (requiresChange) { // do the recalc recalculate(subject); } } } @Override public final boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final AbstractCommand other = (AbstractCommand) obj; return getUUID().equals(other.getUUID()); } @Override public void execute() { // ok, register as a listener with the input files final Iterator<IStoreItem> iter = getInputs().iterator(); while (iter.hasNext()) { final IStoreItem t = iter.next(); if (t instanceof Document<?>) { final Document<?> doc = (Document<?>) t; doc.addDependent(this); } else { t.addChangeListener(this); } } } @Override public void fireDataChanged() { // hmm, we don't really implement this, because apps listen to the // results collections, not the command. throw new IllegalArgumentException("Not implemented"); } /** * provide access to the context object * * @return the context object */ protected final IContext getContext() { return context; } @UIProperty(name = "Description", category = UIProperty.CATEGORY_LABEL) @Override public final String getDescription() { return description; } @UIProperty(name = "Dynamic updates", category = UIProperty.CATEGORY_LABEL) @Override public boolean getDynamic() { return dynamic; } @Override public final List<IStoreItem> getInputs() { return inputs; } @UIProperty(name = "Name", category = UIProperty.CATEGORY_LABEL) @Override public String getName() { return title; } protected int getNonSingletonArrayLength(final List<IStoreItem> inputs) { int size = 0; final Iterator<IStoreItem> iter = inputs.iterator(); while (iter.hasNext()) { final IDocument<?> thisC = (IDocument<?>) iter.next(); if (thisC.size() >= 1) { size = thisC.size(); break; } } return size; } @Override public final List<Document<?>> getOutputs() { return outputs; } @Override public IStoreGroup getParent() { return _parent; } public final IStoreGroup getStore() { return store; } /** * convenience function, to return the datasets as a comma separated list * * @return */ protected String getSubjectList() { final StringBuffer res = new StringBuffer(); final Iterator<IStoreItem> iter = getInputs().iterator(); int ctr = 0; while (iter.hasNext()) { final IStoreItem storeItem = iter.next(); if (ctr++ > 0) { res.append(", "); } res.append(storeItem.getName()); } return res.toString(); } @Override public UUID getUUID() { return uuid; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getUUID().hashCode(); return result; } final protected LocationDocument locationsFor(final LocationDocument track1, final Document<?> times, final TimePeriod period) { // ok, get the time values final AxesMetadata axis = times.getDataset().getFirstMetadata(AxesMetadata.class); final DoubleDataset ds = (DoubleDataset) axis.getAxes()[0]; final double[] data = ds.getData(); return locationsFor(track1, data, period); } final protected LocationDocument locationsFor(final LocationDocument track, final double[] times, final TimePeriod period) { // trim the times to the period final ArrayList<Double> dTimes = new ArrayList<Double>(); for (double thisT : times) { if (period.contains(thisT)) { dTimes.add(thisT); } } final DoubleDataset ds = (DoubleDataset) DatasetFactory.createFromObject(dTimes); final Unit<?> indexUnits = times == null ? null : SampleData.MILLIS; final LocationDocumentBuilder ldb; // ok, put the lats & longs into arrays final ArrayList<Double> latVals = new ArrayList<Double>(); final ArrayList<Double> longVals = new ArrayList<Double>(); final ArrayList<Double> timeVals = new ArrayList<Double>(); // special processing. If the document is a singleton, then // we just keep re-using the same position if (track.size() == 1) { ldb = new LocationDocumentBuilder("Interpolated locations", null, indexUnits); final Point2D pt = track.getLocationIterator().next(); for (final double t : times) { if (period.contains(t)) { ldb.add(t, pt); } } } else { final Iterator<Point2D> lIter = track.getLocationIterator(); final Iterator<Double> tIter = track.getIndexIterator(); while (lIter.hasNext()) { final double thisT = tIter.next(); final Point2D pt = lIter.next(); if (period.contains(thisT)) { latVals.add(pt.getY()); longVals.add(pt.getX()); timeVals.add(thisT); } } final DoubleDataset latDataset = DatasetFactory.createFromObject(DoubleDataset.class, latVals); final DoubleDataset DoubleDataset = DatasetFactory.createFromObject(DoubleDataset.class, longVals); final DoubleDataset timeDataset = DatasetFactory.createFromObject(DoubleDataset.class, timeVals); final DoubleDataset latInterpolated = (DoubleDataset) Maths.interpolate(timeDataset, latDataset, ds, 0, 0); final DoubleDataset longInterpolated = (DoubleDataset) Maths.interpolate(timeDataset, DoubleDataset, ds, 0, 0); // ok, now we need to re-create a locations document ldb = new LocationDocumentBuilder("Interpolated locations", null, indexUnits); for (int i = 0; i < ds.getSize(); i++) { final Point2D pt = track.getCalculator().createPoint(longInterpolated.getDouble(i), latInterpolated.getDouble(i)); ldb.add(ds.getLong(i), pt); } } return ldb.toDocument(); } @Override public void metadataChanged(final IStoreItem subject) { // TODO: do a more intelligent/informed processing of metadata changed dataChanged(subject); } final protected NumberDocument numbersFor(final NumberDocument document, final Document<?> times, final TimePeriod period) { // ok, get the time values final AxesMetadata axis = times.getDataset().getFirstMetadata(AxesMetadata.class); final DoubleDataset ds = (DoubleDataset) axis.getAxes()[0]; final double[] data = ds.getData(); return numbersFor(document, data, period); } final protected NumberDocument numbersFor(final NumberDocument document, final double[] times, final TimePeriod period) { // trim the times to the period final ArrayList<Double> dTimes = new ArrayList<Double>(); for (double thisT : times) { if (period.contains(thisT)) { dTimes.add(thisT); } } final DoubleDataset ds = (DoubleDataset) DatasetFactory.createFromObject(dTimes); final Unit<?> indexUnits = times == null ? null : SampleData.MILLIS; final NumberDocumentBuilder ldb; // ok, put the lats & longs into arrays final ArrayList<Double> headings = new ArrayList<Double>(); final ArrayList<Double> timeVals = new ArrayList<Double>(); // special processing. If the document is a singleton, then // we just keep re-using the same position if (headings.size() == 1) { ldb = new NumberDocumentBuilder("Interpolated headings", document .getUnits(), null, indexUnits); final double pt = document.getIterator().next(); for (final double t : times) { if(period.contains(t)) { ldb.add(t, pt); } } } else { final Iterator<Double> lIter = document.getIterator(); final Iterator<Double> tIter = document.getIndexIterator(); while (lIter.hasNext()) { final double thisT = tIter.next(); final double pt = lIter.next(); if (period.contains(thisT)) { headings.add(pt); timeVals.add(thisT); } } final DoubleDataset hdgDataset = DatasetFactory.createFromObject(DoubleDataset.class, headings); final DoubleDataset timeDataset = DatasetFactory.createFromObject(DoubleDataset.class, timeVals); final DoubleDataset hdgInterpolated = (DoubleDataset) Maths.interpolate(timeDataset, hdgDataset, ds, 0, 0); final DoubleDataset timeInterpolated = (DoubleDataset) Maths.interpolate(timeDataset, timeDataset, ds, 0, 0); // ok, now we need to re-create a locations document ldb = new NumberDocumentBuilder("Interpolated locations", document .getUnits(), null, indexUnits); for (int i = 0; i < ds.getSize(); i++) { ldb.add(timeInterpolated.getDouble(i), hdgInterpolated.getDouble(i)); } } return ldb.toDocument(); } protected abstract void recalculate(IStoreItem subject); @Override public void redo() { throw new UnsupportedOperationException( "Should not be called, redo not provided"); } @Override public final void removeChangeListener(final IChangeListener listener) { // TODO we should add change listener support } @Override public void removeTransientChangeListener( final IChangeListener collectionChangeListener) { // TODO Auto-generated method stub } @Override public void setDynamic(final boolean dynamic) { this.dynamic = dynamic; } @Override public final void setParent(final IStoreGroup parent) { _parent = parent; } @Override public String toString() { return getName(); } @Override public void undo() { throw new UnsupportedOperationException( "Should not be called, undo not provided"); } }
package md.frolov.legume.client; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.ui.RootLayoutPanel; import md.frolov.legume.client.activities.stream.StreamPlace; import md.frolov.legume.client.elastic.query.SearchQuery; import md.frolov.legume.client.events.LogMessageEvent; import md.frolov.legume.client.gin.WidgetInjector; /** Entry point classes define <code>onModuleLoad()</code>. */ public class Legume implements EntryPoint { private static final Logger LOG = Logger.getLogger("Legume"); private WidgetInjector injector = WidgetInjector.INSTANCE; /** This is the entry point method. */ public void onModuleLoad() { injector.activityManager().setDisplay(injector.mainView()); RootLayoutPanel.get().add(injector.mainView()); SearchQuery query = new SearchQuery("", null, new Date(), new Date()); injector.placeHistoryHandler().register(injector.placeController(), injector.eventBus(), new StreamPlace(query)); //TODO change to homeplace injector.placeHistoryHandler().handleCurrentHistory(); GWT.setUncaughtExceptionHandler(new GWT.UncaughtExceptionHandler() { @Override public void onUncaughtException(final Throwable e) { LOG.log(Level.SEVERE,"uncaught",e); injector.eventBus().fireEvent(new LogMessageEvent("Uncaught error: "+e.getMessage())); } }); } }
package com.exedio.cope.instrument; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Writer; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.StringTokenizer; import java.util.TreeSet; import com.exedio.cope.lib.Attribute; import com.exedio.cope.lib.AttributeValue; import com.exedio.cope.lib.EnumerationValue; import com.exedio.cope.lib.NotNullViolationException; import com.exedio.cope.lib.ReadOnlyViolationException; import com.exedio.cope.lib.SystemException; import com.exedio.cope.lib.Type; import com.exedio.cope.lib.UniqueConstraint; import com.exedio.cope.lib.UniqueViolationException; import com.exedio.cope.lib.util.ReactivationConstructorDummy; public final class Instrumentor implements InjectionConsumer { private final Writer output; /** * Holds several properties of the class currently * worked on. */ private JavaClass class_state=null; /** * Collects the class states of outer classes, * when operating on a inner class. * @see #class_state * @element-type InstrumentorClass */ private ArrayList class_state_stack=new ArrayList(); protected final String lineSeparator; /** * The last file level doccomment that was read. */ private String lastFileDocComment = null; public Instrumentor(Writer output) { this.output=output; final String systemLineSeparator = System.getProperty("line.separator"); if(systemLineSeparator==null) { System.out.println("warning: property \"line.separator\" is null, using LF (unix style)."); lineSeparator = "\n"; } else lineSeparator = systemLineSeparator; } public void onPackage(JavaFile javafile) throws InjectorParseException { } public void onImport(String importname) { } private boolean discardnextfeature=false; /** * Tag name for persistent classes. */ private static final String PERSISTENT_CLASS = "persistent"; /** * Tag name for persistent attributes. */ private static final String PERSISTENT_ATTRIBUTE = PERSISTENT_CLASS; /** * Tag name for unique attributes. */ private static final String UNIQUE_ATTRIBUTE = "unique"; /** * Tag name for read-only attributes. */ private static final String READ_ONLY_ATTRIBUTE = "read-only"; /** * Tag name for not-null attributes. */ private static final String NOT_NULL_ATTRIBUTE = "not-null"; /** * Tag name for mapped attributes. */ private static final String MAPPED_ATTRIBUTE = "mapped"; /** * Tag name for one qualifier of qualified attributes. */ private static final String ATTRIBUTE_QUALIFIER = "qualifier"; /** * Tag name for one variant of media attributes. */ private static final String VARIANT_MEDIA_ATTRIBUTE = "variant"; /** * Tag name for media attributes with a constant major mime type. */ private static final String MIME_MAJOR = "mime-major"; /** * Tag name for media attributes with a constant minor mime type. */ private static final String MIME_MINOR = "mime-minor"; /** * Tag name for enumeration values of enumeration attributes. */ private static final String ENUMERATION_VALUE = "value"; /** * All generated class features get this doccomment tag. */ private static final String GENERATED = "generated"; private List uniqueConstraints=null; private void handleClassComment(final JavaClass jc, final String docComment) { if(containsTag(docComment, PERSISTENT_CLASS)) { PersistentClass pc = new PersistentClass(jc); final String uniqueConstraint = Injector.findWholeDocTag(docComment, UNIQUE_ATTRIBUTE); if(uniqueConstraint!=null) { if(uniqueConstraints==null) uniqueConstraints = new ArrayList(); uniqueConstraints.add(uniqueConstraint); } } } public void onClass(final JavaClass jc) { //System.out.println("onClass("+jc.getName()+")"); discardnextfeature=false; class_state_stack.add(class_state); class_state=jc; if(lastFileDocComment != null) { handleClassComment(jc, lastFileDocComment); lastFileDocComment = null; } } private static final String lowerCamelCase(final String s) { final char first = s.charAt(0); if(Character.isLowerCase(first)) return s; else return Character.toLowerCase(first) + s.substring(1); } private static final String getShortName(final Class aClass) { final String name = aClass.getName(); final int pos = name.lastIndexOf('.'); return name.substring(pos+1); } private void writeParameterDeclarationList(final Collection parameters) throws IOException { if(parameters!=null) { boolean first = true; for(Iterator i = parameters.iterator(); i.hasNext(); ) { if(first) first = false; else output.write(','); final String parameter = (String)i.next(); output.write("final "); output.write(parameter); output.write(' '); output.write(lowerCamelCase(parameter)); } } } private void writeParameterCallList(final Collection parameters) throws IOException { if(parameters!=null) { boolean first = true; for(Iterator i = parameters.iterator(); i.hasNext(); ) { if(first) first = false; else output.write(','); final String parameter = (String)i.next(); output.write(lowerCamelCase(parameter)); } } } private void writeThrowsClause(final Collection exceptions) throws IOException { if(!exceptions.isEmpty()) { output.write("\t\t\tthrows"); boolean first = true; for(final Iterator i = exceptions.iterator(); i.hasNext(); ) { if(first) first = false; else output.write(','); output.write(lineSeparator); output.write("\t\t\t\t"); output.write(((Class)i.next()).getName()); } output.write(lineSeparator); } } private final void writeCommentHeader() throws IOException { output.write("/**"); output.write(lineSeparator); output.write(lineSeparator); output.write("\t **"); output.write(lineSeparator); } private final void writeCommentFooter() throws IOException { output.write("\t * @"+GENERATED); output.write(lineSeparator); output.write("\t *"); output.write(lineSeparator); output.write(" */"); } private static final HashMap constraintViolationText = new HashMap(5); static { constraintViolationText.put(NotNullViolationException.class, "not null"); constraintViolationText.put(ReadOnlyViolationException.class, "read only"); constraintViolationText.put(UniqueViolationException.class, "not unique"); } public void writeConstructor(final PersistentClass javaClass) throws IOException { final List initialAttributes = javaClass.getInitialAttributes(); final SortedSet constructorExceptions = javaClass.getContructorExceptions(); int constructorAccessModifier = javaClass.accessModifier; writeCommentHeader(); output.write("\t * Constructs a new "); output.write(javaClass.getName()); output.write(" with all the attributes initially needed."); for(Iterator i = initialAttributes.iterator(); i.hasNext(); ) { final PersistentAttribute initialAttribute = (PersistentAttribute)i.next(); output.write(lineSeparator); output.write("\t * @param initial"); output.write(initialAttribute.getCamelCaseName()); output.write(" the initial value for attribute {@link output.write(initialAttribute.getName()); output.write("}."); final int attributeAccessModifier = initialAttribute.accessModifier; if(constructorAccessModifier<attributeAccessModifier) constructorAccessModifier = attributeAccessModifier; } for(Iterator i = constructorExceptions.iterator(); i.hasNext(); ) { final Class constructorException = (Class)i.next(); output.write(lineSeparator); output.write("\t * @throws "); output.write(constructorException.getName()); output.write(" if"); boolean first = true; for(Iterator j = initialAttributes.iterator(); j.hasNext(); ) { final PersistentAttribute initialAttribute = (PersistentAttribute)j.next(); if(!initialAttribute.getSetterExceptions().contains(constructorException)) continue; if(first) first = false; else output.write(','); output.write(" initial"); output.write(initialAttribute.getCamelCaseName()); } output.write(" is "); output.write((String)constraintViolationText.get(constructorException)); output.write('.'); } output.write(lineSeparator); writeCommentFooter(); output.write(JavaFeature.toAccessModifierString(constructorAccessModifier)); output.write(javaClass.getName()); output.write('('); boolean first = true; for(Iterator i = initialAttributes.iterator(); i.hasNext(); ) { if(first) first = false; else output.write(','); final PersistentAttribute initialAttribute = (PersistentAttribute)i.next(); output.write(lineSeparator); output.write("\t\t\t\tfinal "); output.write(initialAttribute.getBoxedType()); output.write(" initial"); output.write(initialAttribute.getCamelCaseName()); } output.write(')'); output.write(lineSeparator); writeThrowsClause(constructorExceptions); output.write("\t{"); output.write(lineSeparator); output.write("\t\tsuper(new "+AttributeValue.class.getName()+"[]{"); output.write(lineSeparator); for(Iterator i = initialAttributes.iterator(); i.hasNext(); ) { final PersistentAttribute initialAttribute = (PersistentAttribute)i.next(); output.write("\t\t\tnew "+AttributeValue.class.getName()+"("); output.write(initialAttribute.getName()); output.write(','); if(initialAttribute.isBoxed()) output.write(initialAttribute.getBoxingPrefix()); output.write("initial"); output.write(initialAttribute.getCamelCaseName()); if(initialAttribute.isBoxed()) output.write(initialAttribute.getBoxingPostfix()); output.write("),"); output.write(lineSeparator); } output.write("\t\t});"); output.write(lineSeparator); for(Iterator i = javaClass.getContructorExceptions().iterator(); i.hasNext(); ) { final Class exception = (Class)i.next(); output.write("\t\tthrowInitial"); output.write(getShortName(exception)); output.write("();"); output.write(lineSeparator); } output.write("\t}"); } public void writeGenericConstructor(final PersistentClass persistentClass) throws IOException { writeCommentHeader(); output.write("\t * Creates an item and sets the given attributes initially."); output.write(lineSeparator); writeCommentFooter(); output.write("protected "); output.write(persistentClass.getName()); output.write("(final "+AttributeValue.class.getName()+"[] initialAttributes)"); output.write(lineSeparator); output.write("\t{"); output.write(lineSeparator); output.write("\t\tsuper(initialAttributes);"); output.write(lineSeparator); output.write("\t}"); } public void writeReactivationConstructor(final PersistentClass persistentClass) throws IOException { final boolean abstractClass = persistentClass.isAbstract(); writeCommentHeader(); output.write("\t * Reactivation constructor. Used for internal purposes only."); output.write(lineSeparator); output.write("\t * @see Item#Item(" + ReactivationConstructorDummy.class.getName() + ",int)"); output.write(lineSeparator); writeCommentFooter(); output.write( abstractClass ? "protected " : "private " ); output.write(persistentClass.getName()); output.write("("+ReactivationConstructorDummy.class.getName()+" d,final int pk)"); output.write(lineSeparator); output.write("\t{"); output.write(lineSeparator); output.write("\t\tsuper(d,pk);"); output.write(lineSeparator); output.write("\t}"); } private static final int ENUMERATION_NUMBER_AUTO_INCREMENT = 100; private void writeEnumerationClass(final PersistentEnumerationAttribute enumerationAttribute) throws IOException { // deactivated, since the parser cannot remove generated inner classes. if(true) return; writeCommentHeader(); output.write("\t * A class representing the possible states of the persistent enumeration attribute {@link output.write(enumerationAttribute.getName()); output.write("}."); output.write(lineSeparator); writeCommentFooter(); output.write("public static final class "); output.write(enumerationAttribute.getCamelCaseName()); output.write(" extends "+EnumerationValue.class.getName()); output.write(lineSeparator); output.write("\t{"); output.write(lineSeparator); int enumerationNumber = ENUMERATION_NUMBER_AUTO_INCREMENT; for(Iterator i = enumerationAttribute.enumerationValues.iterator(); i.hasNext(); ) { final String enumerationValue = (String)i.next(); output.write("\t\tpublic static final int "); output.write(enumerationValue); output.write("NUM = "); output.write(Integer.toString(enumerationNumber)); output.write(';'); output.write(lineSeparator); output.write("\t\tpublic static final "); output.write(enumerationAttribute.getCamelCaseName()); output.write(' '); output.write(enumerationValue); output.write(" = new "); output.write(enumerationAttribute.getCamelCaseName()); output.write('('); output.write(Integer.toString(enumerationNumber)); output.write(", \""); output.write(enumerationValue); output.write("\");"); output.write(lineSeparator); output.write(lineSeparator); enumerationNumber += ENUMERATION_NUMBER_AUTO_INCREMENT; } output.write("\t\tprivate "); output.write(enumerationAttribute.getCamelCaseName()); output.write("(final int number, final String code)"); output.write(lineSeparator); output.write("\t\t{"); output.write(lineSeparator); output.write("\t\t\tsuper(number, code);"); output.write(lineSeparator); output.write("\t\t}"); output.write(lineSeparator); output.write("\t}"); } private void writeAccessMethods(final PersistentAttribute persistentAttribute) throws IOException { if(persistentAttribute instanceof PersistentEnumerationAttribute) writeEnumerationClass((PersistentEnumerationAttribute)persistentAttribute); final String methodModifiers = Modifier.toString(persistentAttribute.getMethodModifiers()); final String type = persistentAttribute.getBoxedType(); final List qualifiers = persistentAttribute.qualifiers; // getter writeCommentHeader(); output.write("\t * Returns the value of the persistent attribute {@link output.write(persistentAttribute.getName()); output.write("}."); output.write(lineSeparator); writeCommentFooter(); output.write(methodModifiers); output.write(' '); output.write(type); output.write(" get"); output.write(persistentAttribute.getCamelCaseName()); output.write('('); writeParameterDeclarationList(qualifiers); output.write(')'); output.write(lineSeparator); output.write("\t{"); output.write(lineSeparator); writeGetterBody(output, persistentAttribute); output.write("\t}"); // setter if(persistentAttribute.hasSetter()) { writeCommentHeader(); output.write("\t * Sets a new value for the persistent attribute {@link output.write(persistentAttribute.getName()); output.write("}."); output.write(lineSeparator); writeCommentFooter(); output.write(methodModifiers); output.write(" void set"); output.write(persistentAttribute.getCamelCaseName()); output.write('('); if(qualifiers!=null) { writeParameterDeclarationList(qualifiers); output.write(','); } output.write("final "); output.write(type); output.write(' '); output.write(persistentAttribute.getName()); output.write(')'); output.write(lineSeparator); writeThrowsClause(persistentAttribute.getSetterExceptions()); output.write("\t{"); output.write(lineSeparator); writeSetterBody(output, persistentAttribute); output.write("\t}"); } } private void writeMediaGetterMethod(final PersistentAttribute mediaAttribute, final Class returnType, final String part, final String variant, final String literal, final String comment) throws IOException { final String methodModifiers = Modifier.toString(mediaAttribute.getMethodModifiers()); final List qualifiers = mediaAttribute.qualifiers; writeCommentHeader(); output.write("\t * "); output.write(comment); output.write(" {@link output.write(mediaAttribute.getName()); output.write("}."); output.write(lineSeparator); writeCommentFooter(); output.write(methodModifiers); output.write(' '); output.write(returnType.getName()); output.write(" get"); output.write(mediaAttribute.getCamelCaseName()); output.write(part); if(variant!=null) output.write(variant); output.write('('); writeParameterDeclarationList(qualifiers); output.write(')'); output.write(lineSeparator); output.write("\t{"); output.write(lineSeparator); output.write("\t\treturn "); if(literal!=null) { output.write('\"'); output.write(literal); output.write("\";"); } else { output.write("getMedia"); output.write(part); output.write("(this."); output.write(mediaAttribute.getName()); if(variant!=null) { if(variant.length()>0) { output.write(",\""); output.write(variant); output.write('\"'); } else output.write(",null"); } if(qualifiers!=null) { output.write(",new Object[]{"); writeParameterCallList(qualifiers); output.write('}'); } output.write(");"); } output.write(lineSeparator); output.write("\t}"); } private void writeMediaAccessMethods(final PersistentMediaAttribute mediaAttribute) throws IOException { final String methodModifiers = Modifier.toString(mediaAttribute.getMethodModifiers()); final List qualifiers = mediaAttribute.qualifiers; final String mimeMajor = mediaAttribute.mimeMajor; final String mimeMinor = mediaAttribute.mimeMinor; // getters writeMediaGetterMethod(mediaAttribute, String.class, "URL", "", null, "Returns a URL pointing to the data of the persistent attribute"); final List mediaVariants = mediaAttribute.mediaVariants; if(mediaVariants!=null) { for(Iterator i = mediaVariants.iterator(); i.hasNext(); ) writeMediaGetterMethod(mediaAttribute, String.class, "URL", (String)i.next(), null, "Returns a URL pointing to the varied data of the persistent attribute"); } writeMediaGetterMethod(mediaAttribute, String.class, "MimeMajor", null, mimeMajor, "Returns the major mime type of the persistent media attribute"); writeMediaGetterMethod(mediaAttribute, String.class, "MimeMinor", null, mimeMinor, "Returns the minor mime type of the persistent media attribute"); writeMediaGetterMethod(mediaAttribute, InputStream.class, "Data", null, null, "Returns a stream for fetching the data of the persistent media attribute"); // setters if(mediaAttribute.hasSetter()) { writeCommentHeader(); output.write("\t * Provides data for the persistent media attribute {@link output.write(mediaAttribute.getName()); output.write("}."); output.write(lineSeparator); writeCommentFooter(); output.write(methodModifiers); output.write(" void set"); output.write(mediaAttribute.getCamelCaseName()); output.write("Data("); if(qualifiers!=null) { writeParameterDeclarationList(qualifiers); output.write(','); } output.write("final " + OutputStream.class.getName() + " data"); if(mimeMajor==null) output.write(",final "+String.class.getName()+" mimeMajor"); if(mimeMinor==null) output.write(",final "+String.class.getName()+" mimeMinor"); output.write(')'); final SortedSet setterExceptions = mediaAttribute.getSetterExceptions(); writeThrowsClause(setterExceptions); if(setterExceptions.isEmpty()) output.write("throws "); output.write(IOException.class.getName()); output.write(lineSeparator); output.write("\t{"); output.write(lineSeparator); final SortedSet exceptionsToCatch = new TreeSet(mediaAttribute.getExceptionsToCatchInSetter()); exceptionsToCatch.remove(ReadOnlyViolationException.class); exceptionsToCatch.remove(UniqueViolationException.class); if(!exceptionsToCatch.isEmpty()) { output.write("\t\ttry"); output.write(lineSeparator); output.write("\t\t{"); output.write(lineSeparator); output.write('\t'); } output.write("\t\tsetMediaData(this."); output.write(mediaAttribute.getName()); if(qualifiers!=null) { output.write(",new Object[]{"); writeParameterCallList(qualifiers); output.write('}'); } output.write(",data"); output.write(mimeMajor==null ? ",mimeMajor" : ",null"); output.write(mimeMinor==null ? ",mimeMinor" : ",null"); output.write(");"); output.write(lineSeparator); if(!exceptionsToCatch.isEmpty()) { output.write("\t\t}"); output.write(lineSeparator); for(Iterator i = exceptionsToCatch.iterator(); i.hasNext(); ) writeViolationExceptionCatchClause(output, (Class)i.next()); } output.write("\t}"); } } private final void writeEquals(final PersistentAttribute persistentAttribute) throws IOException { output.write("equal("); output.write(persistentAttribute.getName()); output.write(",searched"); output.write(persistentAttribute.getCamelCaseName()); output.write(')'); } private void writeUniqueFinder(final PersistentAttribute[] persistentAttributes) throws IOException, InjectorParseException { int modifiers = -1; for(int i=0; i<persistentAttributes.length; i++) { if(modifiers==-1) modifiers = persistentAttributes[i].getMethodModifiers(); else { if(modifiers!=persistentAttributes[i].getMethodModifiers()) throw new InjectorParseException("Tried to write unique finder and found attribues with different modifiers"); } } final String methodModifiers = Modifier.toString(modifiers|Modifier.STATIC); final String className = persistentAttributes[0].getParent().getName(); writeCommentHeader(); output.write("\t * Finds a "); output.write(lowerCamelCase(className)); output.write(" by it's unique attributes"); for(int i=0; i<persistentAttributes.length; i++) { output.write(lineSeparator); output.write("\t * @param searched"); output.write(persistentAttributes[i].getCamelCaseName()); output.write(" shall be equal to attribute {@link output.write(persistentAttributes[i].getName()); output.write("}."); } output.write(lineSeparator); writeCommentFooter(); output.write(methodModifiers); output.write(' '); output.write(className); boolean first=true; for(int i=0; i<persistentAttributes.length; i++) { if(first) { output.write(" findBy"); first = false; } else output.write("And"); output.write(persistentAttributes[i].getCamelCaseName()); } output.write('('); final Set qualifiers = new HashSet(); for(int i=0; i<persistentAttributes.length; i++) { if(i>0) output.write(','); final PersistentAttribute persistentAttribute = persistentAttributes[i]; if(persistentAttribute.qualifiers != null) qualifiers.addAll(persistentAttribute.qualifiers); output.write("final "); output.write(persistentAttribute.getPersistentType()); output.write(" searched"); output.write(persistentAttribute.getCamelCaseName()); } if(!qualifiers.isEmpty()) { output.write(','); writeParameterDeclarationList(qualifiers); } output.write(')'); output.write(lineSeparator); output.write("\t{"); output.write(lineSeparator); output.write("\t\treturn ("); output.write(className); output.write(")searchUnique(TYPE,"); if(persistentAttributes.length==1) writeEquals(persistentAttributes[0]); else { output.write("and("); writeEquals(persistentAttributes[0]); for(int i = 1; i<persistentAttributes.length; i++) { output.write(','); writeEquals(persistentAttributes[i]); } output.write(')'); } output.write(");"); output.write(lineSeparator); output.write("\t}"); } private final void writeType(final PersistentClass persistentClass) throws IOException { writeCommentHeader(); output.write("\t * The persistent type information for "); output.write(lowerCamelCase(persistentClass.getName())); output.write("."); output.write(lineSeparator); writeCommentFooter(); // the TYPE variable output.write("public static final "+Type.class.getName()+" TYPE = "); output.write(lineSeparator); // open the constructor of type output.write("\t\tnew "+Type.class.getName()+"("); output.write(lineSeparator); // the class itself output.write("\t\t\t"); output.write(persistentClass.getName()); output.write(".class,"); output.write(lineSeparator); // the attributes of the class final List persistentAttributes = persistentClass.getPersistentAttributes(); if(!persistentAttributes.isEmpty()) { output.write("\t\t\tnew "+Attribute.class.getName()+"[]{"); output.write(lineSeparator); for(Iterator i = persistentAttributes.iterator(); i.hasNext(); ) { final PersistentAttribute persistentAttribute = (PersistentAttribute)i.next(); output.write("\t\t\t\t"); output.write(persistentAttribute.getName()); output.write(".initialize(\""); output.write(persistentAttribute.getName()); output.write("\","); output.write(persistentAttribute.readOnly ? "true": "false"); output.write(','); output.write(persistentAttribute.notNull ? "true": "false"); if(persistentAttribute.isItemPersistentType()) { output.write(','); output.write(persistentAttribute.getBoxedType()); output.write(".class"); } //private List qualifiers = null; output.write("),"); output.write(lineSeparator); } output.write("\t\t\t},"); } else { output.write("\t\t\tnull,"); } output.write(lineSeparator); // the unique contraints of the class final List uniqueConstraints = persistentClass.getUniqueConstraints(); if(!uniqueConstraints.isEmpty()) { output.write("\t\t\tnew "+UniqueConstraint.class.getName()+"[]{"); output.write(lineSeparator); for(Iterator i = uniqueConstraints.iterator(); i.hasNext(); ) { final PersistentAttribute[] uniqueConstraint = (PersistentAttribute[])i.next(); if(uniqueConstraint.length==1) { // shorter notation, if unique contraint does not cover multive attributes output.write("\t\t\t\tnew "+UniqueConstraint.class.getName()+'('); output.write(uniqueConstraint[0].getName()); output.write("),"); } else { // longer notation otherwise output.write("\t\t\t\tnew "+UniqueConstraint.class.getName()+"(new "+Attribute.class.getName()+"[]{"); for(int j = 0; j<uniqueConstraint.length; j++) { output.write(uniqueConstraint[j].getName()); output.write(','); } output.write("}),"); } output.write(lineSeparator); } output.write("\t\t\t}"); } else { output.write("\t\t\tnull"); } output.write(lineSeparator); // close the constructor of Type output.write("\t\t)"); output.write(lineSeparator); output.write(";"); } private void writeClassFeatures(final PersistentClass persistentClass) throws IOException, InjectorParseException { //System.out.println("onClassEnd("+jc.getName()+") persistent"); if(uniqueConstraints != null) { //System.out.println("onClassEnd("+jc.getName()+") unique"); for( final Iterator i=uniqueConstraints.iterator(); i.hasNext(); ) { final String uniqueConstraint=(String)i.next(); final List attributes = new ArrayList(); for(final StringTokenizer t=new StringTokenizer(uniqueConstraint, " "); t.hasMoreTokens(); ) { final String attributeName = t.nextToken(); final PersistentAttribute ja = persistentClass.getPersistentAttribute(attributeName); if(ja==null) throw new InjectorParseException("Attribute with name "+attributeName+" does not exist!"); attributes.add(ja); } if(attributes.isEmpty()) throw new InjectorParseException("No attributes found in unique constraint "+uniqueConstraint); persistentClass.makeUnique((PersistentAttribute[])attributes.toArray(new PersistentAttribute[]{})); } } if(!persistentClass.isInterface()) { //System.out.println("onClassEnd("+jc.getName()+") writing"); writeConstructor(persistentClass); if(persistentClass.isAbstract()) // TODO: create the constructor for all classes, but without type argument writeGenericConstructor(persistentClass); writeReactivationConstructor(persistentClass); for(final Iterator i = persistentClass.getPersistentAttributes().iterator(); i.hasNext(); ) { // write setter/getter methods final PersistentAttribute persistentAttribute = (PersistentAttribute)i.next(); //System.out.println("onClassEnd("+jc.getName()+") writing attribute "+persistentAttribute.getName()); if(persistentAttribute instanceof PersistentMediaAttribute) writeMediaAccessMethods((PersistentMediaAttribute)persistentAttribute); else writeAccessMethods(persistentAttribute); } for(final Iterator i = persistentClass.getUniqueConstraints().iterator(); i.hasNext(); ) { // write unique finder methods final PersistentAttribute[] persistentAttributes = (PersistentAttribute[])i.next(); writeUniqueFinder(persistentAttributes); } writeType(persistentClass); } } public void onClassEnd(final JavaClass javaClass) throws IOException, InjectorParseException { //System.out.println("onClassEnd("+javaClass.getName()+")"); final PersistentClass persistentClass = PersistentClass.getPersistentClass(javaClass); if(persistentClass!=null) writeClassFeatures(persistentClass); if(class_state!=javaClass) throw new RuntimeException(); class_state=(JavaClass)(class_state_stack.remove(class_state_stack.size()-1)); } public void onBehaviourHeader(JavaBehaviour jb) throws java.io.IOException { output.write(jb.getLiteral()); } public void onAttributeHeader(JavaAttribute ja) { } public void onClassFeature(final JavaFeature jf, final String docComment) throws IOException, InjectorParseException { //System.out.println("onClassFeature("+jf.getName()+" "+docComment+")"); if(!class_state.isInterface()) { if(jf instanceof JavaAttribute && Modifier.isFinal(jf.getModifiers()) && Modifier.isStatic(jf.getModifiers()) && !discardnextfeature && containsTag(docComment, PERSISTENT_ATTRIBUTE)) { final String type = jf.getType(); final JavaAttribute ja = (JavaAttribute)jf; final String persistentType; final int persistentTypeType; if("IntegerAttribute".equals(type)) { persistentType = "Integer"; persistentTypeType = PersistentAttribute.TYPE_INTEGER; } else if("BooleanAttribute".equals(type)) { persistentType = "Boolean"; persistentTypeType = PersistentAttribute.TYPE_BOOLEAN; } else if("StringAttribute".equals(type)) { persistentType = "String"; persistentTypeType = PersistentAttribute.TYPE_STRING; } else if("EnumerationAttribute".equals(type)) { persistentType = ja.getCamelCaseName(); persistentTypeType = PersistentAttribute.TYPE_ENUMERATION; } else if("ItemAttribute".equals(type)) { persistentType = Injector.findDocTag(docComment, PERSISTENT_ATTRIBUTE); persistentTypeType = PersistentAttribute.TYPE_ITEM; } else if("MediaAttribute".equals(type)) { persistentType = PersistentAttribute.MEDIA_TYPE; persistentTypeType = PersistentAttribute.TYPE_MEDIA; } else throw new RuntimeException(); final boolean readOnly = containsTag(docComment, READ_ONLY_ATTRIBUTE); final boolean notNull = containsTag(docComment, NOT_NULL_ATTRIBUTE); final boolean mapped = containsTag(docComment, MAPPED_ATTRIBUTE); final String qualifier = Injector.findDocTag(docComment, ATTRIBUTE_QUALIFIER); final List qualifiers; if(qualifier!=null) qualifiers = Collections.singletonList(qualifier); else qualifiers = null; final PersistentAttribute persistentAttribute; switch(persistentTypeType) { case PersistentAttribute.TYPE_MEDIA: { final String variant = Injector.findDocTag(docComment, VARIANT_MEDIA_ATTRIBUTE); final List variants; if(variant!=null) variants = Collections.singletonList(variant); else variants = null; final String mimeMajor = Injector.findDocTag(docComment, MIME_MAJOR); final String mimeMinor = Injector.findDocTag(docComment, MIME_MINOR); persistentAttribute = new PersistentMediaAttribute( ja, readOnly, notNull, mapped, qualifiers, variants, mimeMajor, mimeMinor); break; } case PersistentAttribute.TYPE_ENUMERATION: { final String enumerationValue = Injector.findDocTag(docComment, ENUMERATION_VALUE); final List enumerationValues; if(enumerationValue!=null) enumerationValues = Collections.singletonList(enumerationValue); else enumerationValues = null; persistentAttribute = new PersistentEnumerationAttribute( ja, persistentType, readOnly, notNull, mapped, qualifiers, enumerationValues); break; } default: persistentAttribute = new PersistentAttribute( ja, persistentType, persistentTypeType, readOnly, notNull, mapped, qualifiers); break; } if(containsTag(docComment, UNIQUE_ATTRIBUTE)) persistentAttribute.persistentClass.makeUnique(new PersistentAttribute[]{persistentAttribute}); } } discardnextfeature=false; } public boolean onDocComment(String docComment) throws IOException { //System.out.println("onDocComment("+docComment+")"); if(containsTag(docComment, GENERATED)) { discardnextfeature=true; return false; } else { output.write(docComment); return true; } } public void onFileDocComment(String docComment) throws IOException { //System.out.println("onFileDocComment("+docComment+")"); output.write(docComment); if (class_state != null) { // handle doccomment immediately handleClassComment(class_state, docComment); } else { // remember to be handled as soon as we know what class we're talking about lastFileDocComment = docComment; } } public void onFileEnd() { if(!class_state_stack.isEmpty()) throw new RuntimeException(); } private static final boolean containsTag(final String docComment, final String tagName) { return docComment!=null && docComment.indexOf('@'+tagName)>=0 ; } /** * Identation contract: * This methods is called, when output stream is immediatly after a line break, * and it should return the output stream after immediatly after a line break. * This means, doing nothing fullfils the contract. */ private void writeGetterBody(final Writer output, final PersistentAttribute attribute) throws IOException { output.write("\t\treturn "); if(attribute.isBoxed()) output.write(attribute.getUnBoxingPrefix()); output.write('('); output.write(attribute.getPersistentType()); output.write(")getAttribute(this."); output.write(attribute.getName()); final List qualifiers = attribute.qualifiers; if(qualifiers!=null) { output.write(",new Object[]{"); writeParameterCallList(qualifiers); output.write('}'); } output.write(')'); if(attribute.isBoxed()) output.write(attribute.getUnBoxingPostfix()); output.write(';'); output.write(lineSeparator); } /** * Identation contract: * This methods is called, when output stream is immediatly after a line break, * and it should return the output stream after immediatly after a line break. * This means, doing nothing fullfils the contract. */ private void writeSetterBody(final Writer output, final PersistentAttribute attribute) throws IOException { final SortedSet exceptionsToCatch = attribute.getExceptionsToCatchInSetter(); if(!exceptionsToCatch.isEmpty()) { output.write("\t\ttry"); output.write(lineSeparator); output.write("\t\t{"); output.write(lineSeparator); output.write('\t'); } output.write("\t\tsetAttribute(this."); output.write(attribute.getName()); final List qualifiers = attribute.qualifiers; if(qualifiers!=null) { output.write(",new Object[]{"); writeParameterCallList(qualifiers); output.write('}'); } output.write(','); if(attribute.isBoxed()) output.write(attribute.getBoxingPrefix()); output.write(attribute.getName()); if(attribute.isBoxed()) output.write(attribute.getBoxingPostfix()); output.write(");"); output.write(lineSeparator); if(!exceptionsToCatch.isEmpty()) { output.write("\t\t}"); output.write(lineSeparator); for(Iterator i = exceptionsToCatch.iterator(); i.hasNext(); ) writeViolationExceptionCatchClause(output, (Class)i.next()); } } private void writeViolationExceptionCatchClause(final Writer output, final Class exceptionClass) throws IOException { output.write("\t\tcatch("+exceptionClass.getName()+" e)"); output.write(lineSeparator); output.write("\t\t{"); output.write(lineSeparator); output.write("\t\t\tthrow new "+SystemException.class.getName()+"(e);"); output.write(lineSeparator); output.write("\t\t}"); output.write(lineSeparator); } }
package org.jetel.component; import java.io.IOException; import java.nio.ByteBuffer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jetel.data.DataRecord; import org.jetel.data.Defaults; import org.jetel.data.RecordKey; import org.jetel.data.SortDataRecordInternal; import org.jetel.data.tape.DataRecordTape; import org.jetel.data.tape.TapeCarousel; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.XMLConfigurationException; import org.jetel.graph.InputPort; import org.jetel.graph.Node; import org.jetel.graph.TransformationGraph; import org.jetel.util.ComponentXMLAttributes; import org.jetel.util.StringUtils; import org.jetel.util.SynchronizeUtils; import org.w3c.dom.Element; /** * <h3>Sort Component</h3> * * <!-- Sorts the incoming records based on specified key --> * * <table border="1"> * <th>Component:</th> * <tr><td><h4><i>Name:</i></h4></td> * <td>Sort</td></tr> * <tr><td><h4><i>Category:</i></h4></td> * <td></td></tr> * <tr><td><h4><i>Description:</i></h4></td> * <td>Sorts the incoming records based on specified key.<br> * The key is name (or combination of names) of field(s) from input record. * The sort order is either Ascending (default) or Descending.<br> * In case there is not enough room in internal sort buffer, it performs * external sorting - thus any number of internal records can be sorted.</td></tr> * <tr><td><h4><i>Inputs:</i></h4></td> * <td>[0]- input records</td></tr> * <tr><td><h4><i>Outputs:</i></h4></td> * <td>At least one connected output port.</td></tr> * <tr><td><h4><i>Comment:</i></h4></td> * <td></td></tr> * </table> * <br> * <table border="1"> * <th>XML attributes:</th> * <tr><td><b>type</b></td><td>"EXT_SORT"</td></tr> * <tr><td><b>id</b></td><td>component identification</td> * <tr><td><b>sortKey</b></td><td>field names separated by :;| {colon, semicolon, pipe}</td> * <tr><td><b>sortOrder</b><br><i>optional</i></td><td>one of "Ascending|Descending" {the fist letter is sufficient, if not defined, then Ascending}</td> * <tr><td><b>numberOfTapes</b><br><i>optional</i></td><td>even number greater than 2 - denotes how many tapes (temporary files) will be used when external sorting data. * <i>Default is 6 tapes.</i></td> * <!--tr><td><b>sorterInitialCapacity</b><br><i>optional</i></td><td>the initial capacity of internal sorter used for in-memory sorting records. If the * system has plenty of memory, specify high number here (5000 or more). If the system is short on memory, use low number (100).<br> * The final capacity is based on following formula:<br><code>sorter_initial_capacity * (1 - grow_factor^max_num_collections)/(1 - grow_factor)</code><br> * where:<br><code>grow_factor=1.6<br>max_num_collections=8<br>sorterInitialCapacity=2000<br></code><br>With the parameters above, the default total capacity roughly is <b>140000</b> records. The * total capacity is approximately <code>69,91 * sorterInitialCapacity</code>.<br><br> * Following tables shows Total Capacities of internal buffer for various Initial Capacity values: * <table border="1"> * <tr><th>Initial Capacity</th><th>Total Capacity</th></tr> * <tr><td>10</td><td>1000</td></tr> * <tr><td>100</td><td>7000</td></tr> * <tr><td>1000</td><td>70000</td></tr> * <tr><td>2000</td><td>140000</td></tr> * <tr><td>5000</td><td>350000</td></tr> * <tr><td>10000</td><td>700000</td></tr> * <tr><td>20000</td><td>1399000</td></tr> * <tr><td>50000</td><td>3496000</td></tr> * </table> * </tr--> * <tr><td><b>bufferCapacity</b><br><i>optional</i></td><td>What is the maximum number of records * which are sorted in-memory. If number of records exceed this size, external sorting is performed.</td></tr> * <tr><td><b>tmpDirs</b><br><i>optional</i></td><td>Semicolon (;) delimited list of directories which should be * used for creating tape files - used when external sorting is performed. Default value is equal to Java's <code>java.io.tmpdir</code> system property.</td></tr> * </table> * * <h4>Example:</h4> * <pre>&lt;Node id="SORT_CUSTOMER" type="EXT_SORT" sortKey="Name:Address" sortOrder="A"/&gt;</pre> * * @author dpavlis * @since April 4, 2002 * @revision $Revision$ */ public class ExtSort extends Node { private static final String XML_NUMBEROFTAPES_ATTRIBUTE = "numberOfTapes"; private static final String XML_SORTERINITIALCAPACITY_ATTRIBUTE = "sorterInitialCapacity"; private static final String XML_SORTORDER_ATTRIBUTE = "sortOrder"; private static final String XML_SORTKEY_ATTRIBUTE = "sortKey"; private static final String XML_BUFFER_CAPACITY_ATTRIBUTE = "bufferCapacity"; private static final String XML_TEMPORARY_DIRS = "tmpDirs"; /** Description of the Field */ public final static String COMPONENT_TYPE = "EXT_SORT"; private final static int WRITE_TO_PORT = 0; private final static int READ_FROM_PORT = 0; private SortDataRecordInternal sorter; private TapeCarousel tapeCarousel; private boolean sortOrderAscending; private String[] sortKeysNames; private ByteBuffer recordBuffer; private boolean carouselInitialized; private String[] tmpDirs; private InputPort inPort; private DataRecord inRecord; private RecordKey sortKey; private int numberOfTapes; private int internalBufferCapacity; private final static boolean DEFAULT_ASCENDING_SORT_ORDER = true; private final static int DEFAULT_NUMBER_OF_TAPES = 6; static Log logger = LogFactory.getLog(ExtSort.class); /** * Constructor for the Sort object * * @param id * Description of the Parameter * @param sortKeysNames * Description of the Parameter * @param sortOrder * Description of the Parameter */ public ExtSort(String id, String[] sortKeys, boolean sortOrder) { super(id); this.sortOrderAscending = sortOrder; this.sortKeysNames = sortKeys; carouselInitialized = false; numberOfTapes=DEFAULT_NUMBER_OF_TAPES; internalBufferCapacity=-1; } /** * Constructor for the Sort object * * @param id * Description of the Parameter * @param sortKeysNames * Description of the Parameter */ public ExtSort(String id, String[] sortKeys) { this(id, sortKeys, DEFAULT_ASCENDING_SORT_ORDER); } /** * Main processing method for the SimpleCopy object * * @since April 4, 2002 */ public void run() { boolean doMerge = false; inPort = getInputPort(READ_FROM_PORT); inRecord = new DataRecord(inPort.getMetadata()); inRecord.init(); DataRecord tmpRecord = inRecord; /* * PHASE SORT -- * * we read records from input till internal buffer is full, then we sort * internal buffer and write it to tape. Then we continue till EOF and * MERGING occures afterwards. * * If we reach EOF on input before internal buffer is full, we just sort * them and send directly to output */ while (tmpRecord != null && runIt) { try { tmpRecord = inPort.readRecord(inRecord); if (tmpRecord != null) { if (!sorter.put(inRecord)) { // we need to sort & flush buffer on to tape and merge it later doMerge = true; sorter.sort(); flushToTape(); sorter.reset(); if (!sorter.put(inRecord)) { throw new RuntimeException( "Can't store record into sorter !"); } tmpRecord = inRecord; } } } catch (IOException ex) { resultMsg = ex.getMessage(); resultCode = Node.RESULT_ERROR; closeAllOutputPorts(); return; } catch (Exception ex) { resultMsg = ex.getClass().getName() + " : " + ex.getMessage(); resultCode = Node.RESULT_FATAL_ERROR; //closeAllOutputPorts(); return; } SynchronizeUtils.cloverYield(); } if (runIt) { if (doMerge) { // sort whatever remains in sorter sorter.sort(); try { flushToTape(); // we don't need sorter any more - free all its resources sorter.free(); // flush to disk whatever remains in tapes' buffers // tapeCarousel.flush(); // merge partially sorted data from tapes phaseMerge(); } catch (IOException ex) { resultMsg = ex.getMessage(); resultCode = Node.RESULT_ERROR; closeAllOutputPorts(); return; } catch (Exception ex) { resultMsg = ex.getClass().getName() + " : " + ex.getMessage(); resultCode = Node.RESULT_FATAL_ERROR; //closeAllOutputPorts(); return; } } else { sorter.sort(); sorter.rewind(); recordBuffer.clear(); while (sorter.get(recordBuffer) && runIt) { try { writeRecordBroadcastDirect(recordBuffer); recordBuffer.clear(); } catch (IOException ex) { resultMsg = ex.getMessage(); resultCode = Node.RESULT_ERROR; closeAllOutputPorts(); return; } catch (Exception ex) { resultMsg = ex.getClass().getName() + " : " + ex.getMessage(); resultCode = Node.RESULT_FATAL_ERROR; //closeAllOutputPorts(); return; } SynchronizeUtils.cloverYield(); } sorter.free(); } } broadcastEOF(); if (runIt) { resultMsg = "OK"; } else { resultMsg = "STOPPED"; } resultCode = Node.RESULT_OK; } /** * Description of the Method * * @exception ComponentNotReadyException * Description of the Exception * @since April 4, 2002 */ public void init() throws ComponentNotReadyException { // test that we have at least one input port and one output if (inPorts.size() < 1) { throw new ComponentNotReadyException( "At least one input port has to be defined!"); } else if (outPorts.size() < 1) { throw new ComponentNotReadyException( "At least one output port has to be defined!"); } recordBuffer = ByteBuffer .allocateDirect(Defaults.Record.MAX_RECORD_SIZE); if (recordBuffer == null) { throw new ComponentNotReadyException( "Can NOT allocate internal record buffer ! Required size:" + Defaults.Record.MAX_RECORD_SIZE); } // create sorter if (internalBufferCapacity>0){ sorter = new SortDataRecordInternal(getInputPort(READ_FROM_PORT) .getMetadata(), sortKeysNames, sortOrderAscending, false, internalBufferCapacity); } else { sorter = new SortDataRecordInternal(getInputPort(READ_FROM_PORT) .getMetadata(), sortKeysNames, sortOrderAscending, false); } } /** * Performs merge of partially sorted data records stored on tapes * (in external files). * * @throws IOException * @throws InterruptedException */ private void phaseMerge() throws IOException, InterruptedException { int index; DataRecordTape targetTape; TapeCarousel targetCarousel = new TapeCarousel(tapeCarousel.numTapes(), tmpDirs); DataRecord[] sourceRecords = new DataRecord[tapeCarousel.numTapes()]; boolean[] sourceRecordsFlags = new boolean[tapeCarousel.numTapes()]; // initialize sort key which will be used when merging data sortKey = new RecordKey(sortKeysNames, inRecord.getMetadata()); sortKey.init(); // initial creation & initialization of source records for (int i = 0; i < sourceRecords.length; i++) { sourceRecords[i] = new DataRecord(inRecord.getMetadata()); sourceRecords[i].init(); } // rewind carousel with source data - so we can start reading it tapeCarousel.rewind(); // open carousel into which we will merge data targetCarousel.open(); // get first free tape from target carousel targetTape = targetCarousel.getFirstTape(); /* * MAIN MERGING loop */ do { // if we need to perform only final merging (one lewel of chunks on source tapes) // skip to final merge if (tapeCarousel.getFirstTape().getNumChunks()==1) break; /* * semi-merging of one level of data chunks */ do { loadUpRecords(tapeCarousel, sourceRecords, sourceRecordsFlags); if (hasAnyData(sourceRecordsFlags)) { targetTape.addDataChunk(); } else { break; } while (hasAnyData(sourceRecordsFlags)) { if (sortOrderAscending) { index = getLowestIndex(sourceRecords, sourceRecordsFlags); } else { index = getHighestIndex(sourceRecords, sourceRecordsFlags); } // write record to target tape recordBuffer.clear(); sourceRecords[index].serialize(recordBuffer); recordBuffer.flip(); targetTape.put(recordBuffer); // read in next record from tape from which we read last // record if (!tapeCarousel.getTape(index).get(sourceRecords[index])) { sourceRecordsFlags[index] = false; } SynchronizeUtils.cloverYield(); } targetTape.flush(false); targetTape = targetCarousel.getNextTape(); if (targetTape == null) targetTape = targetCarousel.getFirstTape(); } while (hasMoreChunks(tapeCarousel)); // switch source tapes and target tapes, then continue with merging targetCarousel.rewind(); tapeCarousel.clear(); TapeCarousel tmp = tapeCarousel; tapeCarousel = targetCarousel; targetCarousel = tmp; targetTape = targetCarousel.getFirstTape(); } while (tapeCarousel.getFirstTape().getNumChunks() > 1); // we don't need target carousel - merged records will be sent to output port targetCarousel.free(); // DEBUG START // if (logger.isDebugEnabled()) { // DataRecordTape tape = tapeCarousel.getFirstTape(); // while (tape != null) { // logger.debug(tape); // tape = tapeCarousel.getNextTape(); // DEBUG END /* * send data to output - final merge */ tapeCarousel.rewind(); loadUpRecords(tapeCarousel, sourceRecords, sourceRecordsFlags); while (hasAnyData(sourceRecordsFlags)) { if (sortOrderAscending) { index = getLowestIndex(sourceRecords, sourceRecordsFlags); } else { index = getHighestIndex(sourceRecords, sourceRecordsFlags); } // write record to out port writeRecordBroadcast(sourceRecords[index]); if (!tapeCarousel.getTape(index).get(sourceRecords[index])) { sourceRecordsFlags[index] = false; } SynchronizeUtils.cloverYield(); } // end-of-story tapeCarousel.free(); } /** * Populates source records array with records from individual tapes (included in * tape carousel). Sets flags in flags array for those records which contain valid data. * * @param tapeCarousel * @param sourceRecords * @param sourceRecordsFlags * @throws IOException */ private final void loadUpRecords(TapeCarousel tapeCarousel, DataRecord[] sourceRecords, boolean[] sourceRecordsFlags) throws IOException { for (int i = 0; i < tapeCarousel.numTapes(); i++) { DataRecordTape tape = tapeCarousel.getTape(i); if (tape.get(sourceRecords[i])) { sourceRecordsFlags[i] = true; } else { sourceRecordsFlags[i] = false; } } } /** * Checks whether tapes within tape carousel contains more data chunks * to be processed. * @param tapeCarousel * @return true if more chunks are available */ private final static boolean hasMoreChunks(TapeCarousel tapeCarousel) { boolean hasMore = false; for (int i = 0; i < tapeCarousel.numTapes(); i++) { if (tapeCarousel.getTape(i).nextDataChunk()) { hasMore = true; } } return hasMore; } /** * Returns index of the lowest record from the specified record array * * @param sourceRecords array of source records * @param flags array indicating which source records contain valid data * @return index of the lowest record within source records array of -1 if no such record * exists - i.e. there is no valid record */ private final int getLowestIndex(DataRecord[] sourceRecords, boolean[] flags) { int lowest = -1; for (int i = 0; i < flags.length; i++) { if (flags[i]) { lowest = i; break; } } for (int i = lowest + 1; i < sourceRecords.length; i++) { if (flags[i] && sortKey.compare(sourceRecords[lowest], sourceRecords[i]) == 1) { lowest = i; } } return lowest; } /** * Returns index of the highest record from the specified record array * * @param sourceRecords array of source records * @param flags array indicating which source records contain valid data * @return index of the highest record within source records array of -1 if no such record * exists - i.e. there is no valid record */ private final int getHighestIndex(DataRecord[] sourceRecords, boolean[] flags) { int highest = 1; for (int i = 0; i < flags.length; i++) { if (flags[i]) { highest = i; break; } } for (int i = highest + 1; i < sourceRecords.length; i++) { if (flags[i] && sortKey .compare(sourceRecords[highest], sourceRecords[i]) == -1) { highest = i; } } return highest; } /** * Checks that at least one valid record exists * @param flags * @return true if flahs indicate that at least one valid record exists */ private final static boolean hasAnyData(boolean[] flags) { for (int i = 0; i < flags.length; i++) { if (flags[i] == true) return true; } return false; } private void flushToTape() throws IOException { DataRecordTape tape; if (!carouselInitialized) { tapeCarousel = new TapeCarousel(numberOfTapes, tmpDirs); tapeCarousel.open(); tape = tapeCarousel.getFirstTape(); carouselInitialized = true; } else { tape = tapeCarousel.getNextTape(); if (tape == null) tape = tapeCarousel.getFirstTape(); } tape.addDataChunk(); sorter.rewind(); recordBuffer.clear(); while (sorter.get(recordBuffer) && runIt) { tape.put(recordBuffer); recordBuffer.clear(); } tape.flush(false); } /** * Sets the sortOrderAscending attribute of the Sort object * * @param ascending * The new sortOrderAscending value */ public void setSortOrderAscending(boolean ascending) { sortOrderAscending = ascending; } /** * How many tapes will be used for merging * @param numberOfTapes The numberOfTapes to set. */ public void setNumberOfTapes(int numberOfTapes) { if(numberOfTapes > 2) { this.numberOfTapes = numberOfTapes / 2 * 2; } else { numberOfTapes = 2; } } /** * What is the capacity of internal buffer used for * in-memory sorting. * * @param size buffer capacity */ public void setBufferCapacity(int size){ internalBufferCapacity = size; } /** * Description of the Method * * @return Description of the Returned Value * @since May 21, 2002 */ public void toXML(org.w3c.dom.Element xmlElement) { super.toXML(xmlElement); // sortKey attribute String sortKeys = this.sortKeysNames[0]; for (int i=1; i < this.sortKeysNames.length; i++) { sortKeys += Defaults.Component.KEY_FIELDS_DELIMITER + sortKeysNames[i]; } xmlElement.setAttribute(XML_SORTKEY_ATTRIBUTE, sortKeys); // sortOrder attribute if (this.sortOrderAscending == false) { xmlElement.setAttribute(XML_SORTORDER_ATTRIBUTE,"Descending"); }else{ xmlElement.setAttribute(XML_SORTORDER_ATTRIBUTE,"Ascending"); } // numberOfTapes attribute if (this.numberOfTapes != 6) { xmlElement.setAttribute(XML_NUMBEROFTAPES_ATTRIBUTE,String.valueOf(this.numberOfTapes)); } // sorterInitialCapacity if (this.internalBufferCapacity > 0) { xmlElement.setAttribute(XML_BUFFER_CAPACITY_ATTRIBUTE, String.valueOf(this.internalBufferCapacity)); } if (this.tmpDirs!=null){ xmlElement.setAttribute(XML_TEMPORARY_DIRS,StringUtils.stringArraytoString(tmpDirs,';') ); } } /** * Description of the Method * * @param nodeXML Description of Parameter * @return Description of the Returned Value * @since May 21, 2002 */ public static Node fromXML(TransformationGraph graph, Element xmlElement) throws XMLConfigurationException { ComponentXMLAttributes xattribs = new ComponentXMLAttributes(xmlElement, graph); ExtSort sort; try { sort = new ExtSort(xattribs.getString(XML_ID_ATTRIBUTE), xattribs.getString( XML_SORTKEY_ATTRIBUTE).split( Defaults.Component.KEY_FIELDS_DELIMITER_REGEX)); if (xattribs.exists(XML_SORTORDER_ATTRIBUTE)) { sort.setSortOrderAscending(xattribs.getString(XML_SORTORDER_ATTRIBUTE) .matches("^[Aa].*")); } if (xattribs.exists(XML_SORTERINITIALCAPACITY_ATTRIBUTE)){ //only for backward compatibility sort.setBufferCapacity(xattribs.getInteger(XML_SORTERINITIALCAPACITY_ATTRIBUTE)); } if (xattribs.exists(XML_NUMBEROFTAPES_ATTRIBUTE)){ sort.setNumberOfTapes(xattribs.getInteger(XML_NUMBEROFTAPES_ATTRIBUTE)); } if (xattribs.exists(XML_BUFFER_CAPACITY_ATTRIBUTE)){ sort.setBufferCapacity(xattribs.getInteger(XML_BUFFER_CAPACITY_ATTRIBUTE)); } if (xattribs.exists(XML_TEMPORARY_DIRS)){ sort.setTmpDirs(xattribs.getString(XML_TEMPORARY_DIRS).split(Defaults.DEFAULT_PATH_SEPARATOR_REGEX)); } } catch (Exception ex) { throw new XMLConfigurationException(COMPONENT_TYPE + ":" + xattribs.getString(XML_ID_ATTRIBUTE," unknown ID ") + ":" + ex.getMessage(),ex); } return sort; } /** * Description of the Method * * @return Description of the Return Value */ public boolean checkConfig() { return true; } /* (non-Javadoc) * @see org.jetel.graph.Node#getType() */ public String getType() { return COMPONENT_TYPE; } public String[] getTmpDirs() { return tmpDirs; } public void setTmpDirs(String[] tmpDirs) { this.tmpDirs = tmpDirs; } }
package org.jetel.lookup; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Map; import org.jetel.connection.CopySQLData; import org.jetel.connection.DBConnection; import org.jetel.connection.SQLUtil; import org.jetel.data.DataRecord; import org.jetel.data.HashKey; import org.jetel.data.RecordKey; import org.jetel.data.lookup.LookupTable; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.JetelException; import org.jetel.exception.NotFoundException; import org.jetel.graph.GraphElement; import org.jetel.graph.TransformationGraph; import org.jetel.metadata.DataRecordMetadata; import org.jetel.util.ComponentXMLAttributes; import org.jetel.util.SimpleCache; /** * Database table/SQLquery based lookup table which gets data by performing SQL * query. Caching of found values can be provided - if the constructor with * <code>numCached</code> parameter is used. The caching is performed by WeakHashMap so * it can happend that even the frequently used entry (key-value pair) is garbage collected - thus * removed from cache. * * Example using DBLookupTable: * * *@author dpavlis *@created 25. kvten 2003 *@since May 22, 2003 */ public class DBLookupTable extends GraphElement implements LookupTable { private static final String XML_LOOKUP_TYPE_DB_LOOKUP = "dbLookup"; //private static final String XML_LOOKUP_KEY = "key"; private static final String XML_METADATA_ID ="metadata"; private static final String XML_SQL_QUERY = "sqlQuery"; private static final String XML_DBCONNECTION = "dbConnection"; protected DataRecordMetadata dbMetadata; protected DBConnection dbConnection; protected PreparedStatement pStatement; protected RecordKey lookupKey; protected int[] keyFields; protected String[] keys; protected String sqlQuery; protected ResultSet resultSet; protected CopySQLData[] transMap; protected CopySQLData[] keyTransMap; protected DataRecord dbDataRecord; protected DataRecord keyDataRecord = null; // protected Map resultCache; protected SimpleCache resultCache; protected int maxCached; protected HashKey cacheKey; // public int fromCache = 0; /** * Constructor for the DBLookupTable object * *@param dbConnection Description of the Parameter *@param dbRecordMetadata Description of the Parameter *@param sqlQuery Description of the Parameter */ public DBLookupTable(String id, DBConnection dbConnection, DataRecordMetadata dbRecordMetadata, String sqlQuery) { super(id); this.dbConnection = dbConnection; this.dbMetadata = dbRecordMetadata; this.sqlQuery = sqlQuery; this.maxCached = 0; } /** * Constructor for the DBLookupTable object * *@param dbConnection Description of the Parameter *@param dbRecordMetadata Description of the Parameter *@param sqlQuery Description of the Parameter * @param dbFieldTypes List containing the types of the final record */ public DBLookupTable(String id, DBConnection dbConnection, DataRecordMetadata dbRecordMetadata, java.lang.String sqlQuery, java.util.List dbFieldTypes) { this(id, dbConnection,dbRecordMetadata,sqlQuery); } public DBLookupTable(String id, DBConnection dbConnection, DataRecordMetadata dbRecordMetadata, String sqlQuery, int numCached) { super(id); this.dbConnection = dbConnection; this.dbMetadata = dbRecordMetadata; this.sqlQuery = sqlQuery; this.maxCached=numCached; } /** * Gets the dbMetadata attribute of the DBLookupTable object.<br> * <i>init() should be called prior to calling this method (unless dbMetadata * was passed in using appropriate constructor.</i> * *@return The dbMetadata value */ public DataRecordMetadata getMetadata() { return dbMetadata; } /** * Looks-up data based on speficied key.<br> * The key value is taken from passed-in data record. If caching is enabled, the * internal cache is searched first, then the DB is queried. * *@return found DataRecord or NULL *@since May 2, 2002 */ public DataRecord get(DataRecord keyRecord) { // if cached, then try to query cache first if (resultCache!=null){ cacheKey.setDataRecord(keyRecord); DataRecord data=(DataRecord)resultCache.get(cacheKey); if (data!=null){ // fromCache++; return data; } } try { pStatement.clearParameters(); // initialization of trans map if it was not already done if (keyTransMap==null){ if (lookupKey == null) { throw new RuntimeException("RecordKey was not defined for lookup !"); } try { keyTransMap = CopySQLData.jetel2sqlTransMap( SQLUtil.getFieldTypes(pStatement.getParameterMetaData()), keyRecord,lookupKey.getKeyFields()); } catch (JetelException ex){ throw new RuntimeException("Can't create keyRecord transmap: "+ex.getMessage()); }catch (Exception ex) { // PreparedStatement parameterMetadata probably not implemented - use work-around // we only guess the correct data types on JDBC side try{ keyTransMap = CopySQLData.jetel2sqlTransMap(keyRecord,lookupKey.getKeyFields()); }catch(JetelException ex1){ throw new RuntimeException("Can't create keyRecord transmap: "+ex1.getMessage()); }catch(Exception ex1){ // some serious problem throw new RuntimeException("Can't create keyRecord transmap: "+ex1.getClass().getName()+":"+ex1.getMessage()); } } } // set prepared statement parameters for (int i = 0; i < keyTransMap.length; i++) { keyTransMap[i].jetel2sql(pStatement); } //execute query resultSet = pStatement.executeQuery(); if (resultCache!=null){ HashKey hashKey = new HashKey(lookupKey, keyRecord.duplicate()); while (fetch()) { DataRecord storeRecord=dbDataRecord.duplicate(); resultCache.put(hashKey, storeRecord); } }else { if (!fetch()) { dbDataRecord = null; } // dbDataRecord = getNext(); } } catch (SQLException ex) { throw new RuntimeException(ex.getMessage()); } return (resultCache==null ? dbDataRecord : (DataRecord)resultCache.get(cacheKey) ); } /** * Looks-up record/data based on specified array of parameters(values). * No caching is performed. * *@param keys Description of the Parameter *@return found DataRecord or NULL */ public DataRecord get(Object keys[]) { try { // set up parameters for query // statement uses indexing from 1 pStatement.clearParameters(); for (int i = 0; i < keys.length; i++) { pStatement.setObject(i + 1, keys[i]); } //execute query resultSet = pStatement.executeQuery(); if (!fetch()) { return null; } } catch (SQLException ex) { throw new RuntimeException(ex.getMessage()); } return dbDataRecord; } /** * Looks-up data based on specified key-string.<br> * If caching is enabled, the * internal cache is searched first, then the DB is queried.<br> * <b>Warning:</b>it is not recommended to mix this call with call to <code>get(DataRecord keyRecord)</code> method. * *@param keyStr string representation of the key-value *@return found DataRecord or NULL */ public DataRecord get(String keyStr) { if (resultCache!=null){ DataRecord data=(DataRecord)resultCache.get(keyStr); if (data!=null){ return data; } } try { // set up parameters for query // statement uses indexing from 1 pStatement.clearParameters(); pStatement.setString(1, keyStr); //execute query resultSet = pStatement.executeQuery(); if (resultCache!=null){ while (fetch()) { DataRecord storeRecord=dbDataRecord.duplicate(); resultCache.put(keyStr, storeRecord); } }else { dbDataRecord = getNext(); } } catch (SQLException ex) { throw new RuntimeException(ex.getMessage()); } return (resultCache==null ? dbDataRecord : (DataRecord)resultCache.get(cacheKey) ); } /** * Executes query and returns data record (statement must be initialized with * parameters prior to calling this function * *@return DataRecord obtained from DB or null if not found *@exception SQLException Description of the Exception */ private boolean fetch() throws SQLException { if (!resultSet.next()) { return false; } // initialize trans map if needed if (transMap==null){ initInternal(); } //get data from results for (int i = 0; i < transMap.length; i++) { transMap[i].sql2jetel(resultSet); } return true; } /** * Returns the next found record if previous get() method succeeded.<br> * If no more records, returns NULL * *@return The next found record *@exception JetelException Description of the Exception */ public DataRecord getNext() { if (resultCache!=null){ return (DataRecord)resultCache.getNext(); }else { try { if (!fetch()) { return null; } else { return dbDataRecord; } } catch (SQLException ex) { throw new RuntimeException(ex.getMessage()); } } } /* (non-Javadoc) * @see org.jetel.data.lookup.LookupTable#getNumFound() * * Using this method on this implementation of LookupTable * can be time consuming as it requires sequential scan through * the whole result set returned from DB (on some DBMSs). * Also, it resets the position in result set. So subsequent * calls to getNext() will start reading the data found from * the first record. */ public int getNumFound() { if (resultSet != null) { try { int curRow=resultSet.getRow(); resultSet.last(); int count=resultSet.getRow(); resultSet.first(); resultSet.absolute(curRow); return count; } catch (SQLException ex) { return -1; } } return -1; } /* (non-Javadoc) * @see org.jetel.data.lookup.LookupTable#setLookupKey(java.lang.Object) */ public void setLookupKey(Object obj){ this.keyTransMap=null; // invalidate current transmap -if it exists if (obj instanceof RecordKey){ this.lookupKey=((RecordKey)obj); this.cacheKey=new HashKey(lookupKey,null); }else{ this.lookupKey=null; this.cacheKey=null; } } /** * Initializtaion of lookup table - loading all data into it. * *@exception JetelException Description of the Exception *@since May 2, 2002 */ public void init() throws ComponentNotReadyException { // if caching is required, crate map to store records if (maxCached>0){ this.resultCache= new SimpleCache(maxCached); resultCache.enableDuplicity(); } // first try to connect to db try { //dbConnection.connect(); pStatement = dbConnection.prepareStatement(sqlQuery); /*ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY, ResultSet.CLOSE_CURSORS_AT_COMMIT);*/ } catch (SQLException ex) { throw new ComponentNotReadyException("Can't create SQL statement: " + ex.getMessage()); } } /** * We assume that query has already been executed and * we have resultSet available to get metadata. * * * @throws JetelException */ private void initInternal() { // obtain dbMetadata info if needed if (dbMetadata == null) { try { dbMetadata = SQLUtil.dbMetadata2jetel(resultSet.getMetaData()); } catch (SQLException ex) { throw new RuntimeException( "Can't automatically obtain dbMetadata (use other constructor and provide metadat for output record): " + ex.getMessage()); } } // create data record for fetching data from DB dbDataRecord = new DataRecord(dbMetadata); dbDataRecord.init(); // create trans map which will be used for fetching data try { transMap = CopySQLData.sql2JetelTransMap( SQLUtil.getFieldTypes(dbMetadata), dbMetadata, dbDataRecord); } catch (Exception ex) { throw new RuntimeException( "Can't automatically obtain dbMetadata/create transMap : " + ex.getMessage()); } } public static DBLookupTable fromXML(TransformationGraph graph, org.w3c.dom.Node nodeXML){ ComponentXMLAttributes xattribs = new ComponentXMLAttributes(nodeXML, graph); DBLookupTable lookupTable = null; String id; String type; //reading obligatory attributes try { id = xattribs.getString(XML_ID_ATTRIBUTE); type = xattribs.getString(XML_TYPE_ATTRIBUTE); } catch(NotFoundException ex) { throw new RuntimeException("Can't create lookup table - " + ex.getMessage()); } //check type if (!type.equalsIgnoreCase(XML_LOOKUP_TYPE_DB_LOOKUP)) { throw new RuntimeException("Can't create db lookup table from type " + type); } //create db lookup table //String[] keys = xattribs.getString(XML_LOOKUP_KEY).split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX); DataRecordMetadata metadata = graph.getDataRecordMetadata(xattribs.getString(XML_METADATA_ID)); lookupTable = new DBLookupTable(id, (DBConnection) graph.getConnection(xattribs.getString(XML_DBCONNECTION)), metadata, xattribs.getString(XML_SQL_QUERY)); return lookupTable; } /** * Deallocates resources */ public void free() { try { if(pStatement != null) { pStatement.close(); } resultCache = null; transMap = null; } catch (SQLException ex) { throw new RuntimeException(ex.getMessage()); } } public void setNumCached(int numCached){ if (numCached>0){ this.resultCache= new SimpleCache(numCached); this.maxCached=numCached; } } /* (non-Javadoc) * @see org.jetel.graph.GraphElement#checkConfig() */ public boolean checkConfig() { return true; } }
package org.ohmage.request.campaign; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.json.JSONObject; import org.ohmage.annotator.Annotator.ErrorCode; import org.ohmage.domain.Clazz; import org.ohmage.domain.campaign.CampaignMask; import org.ohmage.exception.DomainException; import org.ohmage.exception.InvalidRequestException; import org.ohmage.exception.ServiceException; import org.ohmage.exception.ValidationException; import org.ohmage.request.InputKeys; import org.ohmage.request.UserRequest; import org.ohmage.request.survey.SurveyUploadRequest; import org.ohmage.service.CampaignServices; import org.ohmage.service.ClassServices; import org.ohmage.service.UserCampaignServices; import org.ohmage.service.UserClassServices; import org.ohmage.service.UserServices; import org.ohmage.validator.CampaignValidators; import org.ohmage.validator.ClassValidators; import org.ohmage.validator.SurveyResponseValidators; import org.ohmage.validator.UserValidators; public class CampaignAssignmentRequest extends UserRequest { private static final Logger LOGGER = Logger.getLogger(CampaignAssignmentRequest.class); final String username; final String password; final String classId; final String campaignId; final Set<String> surveyIds; final SurveyUploadRequest uploadRequest; /** * Creates a new campaign assignment request. * * @param httpRequest The HttpServletRequest that contains the parameters * necessary for servicing this request. * * @throws InvalidRequestException Thrown if the parameters cannot be * parsed. * * @throws IOException There was an error reading from the request. */ public CampaignAssignmentRequest( final HttpServletRequest httpRequest) throws IOException, InvalidRequestException { super(httpRequest, null, TokenLocation.PARAMETER, null); String tUsername = null; String tPassword = null; String tClassId = null; String tCampaignId = null; Set<String> tSurveyIds = null; SurveyUploadRequest tUploadRequest = null; if(! isFailed()) { LOGGER.info("Creating a campaign assignment request."); String[] t; try { // Username. Required to know whom is being assigned. t = getParameterValues(InputKeys.USERNAME); if(t.length > 1) { throw new ValidationException( ErrorCode.USER_INVALID_USERNAME, "Multiple usernames were given: " + InputKeys.USERNAME); } else if(t.length == 1) { tUsername = UserValidators.validateUsername(t[0]); } if(tUsername == null) { throw new ValidationException( ErrorCode.USER_INVALID_USERNAME, "No username was given: " + InputKeys.USERNAME); } // Password. Optional. If given, requires the user to be // created. If not given, requires the user to already exist // and be in a class in which the requester is privileged. t = getParameterValues(InputKeys.NEW_PASSWORD); if(t.length > 1) { throw new ValidationException( ErrorCode.USER_INVALID_PASSWORD, "Multiple passwords were given: " + InputKeys.NEW_PASSWORD); } else if(t.length == 1) { tPassword = UserValidators.validatePlaintextPassword(t[0]); } // Class ID. Optional. If given, the requesting user must be // privileged in that class in order to add users to it. t = getParameterValues(InputKeys.CLASS_URN); if(t.length > 1) { throw new ValidationException( ErrorCode.CLASS_INVALID_ID, "Multiple class IDs were given: " + InputKeys.CLASS_URN); } else if(t.length == 1) { tClassId = ClassValidators.validateClassId(t[0]); } // Campaign ID. Required. Get the campaign's unique identifier // to know which surveys the responses belong. t = getParameterValues(InputKeys.CAMPAIGN_URN); if(t.length > 1) { throw new ValidationException( ErrorCode.CAMPAIGN_INVALID_ID, "Multiple campaign IDs were given: " + InputKeys.CAMPAIGN_URN); } else if(t.length == 1) { tCampaignId = CampaignValidators.validateCampaignId(t[0]); } if(tCampaignId == null) { throw new ValidationException( ErrorCode.CAMPAIGN_INVALID_ID, "No campaign ID was given: " + InputKeys.CAMPAIGN_URN); } // Survey IDs. Required. The list of surveys that should exist // in the user's custom campaign. t = getParameterValues(InputKeys.SURVEY_ID_LIST); if(t.length > 1) { throw new ValidationException( ErrorCode.SURVEY_INVALID_SURVEY_ID, "Multiple survey ID lists were given: " + InputKeys.SURVEY_ID_LIST); } else if(t.length == 1) { tSurveyIds = SurveyResponseValidators.validateSurveyIds(t[0]); } if((tSurveyIds == null) || (tSurveyIds.size() == 0)) { throw new ValidationException( ErrorCode.SURVEY_INVALID_SURVEY_ID, "No survey IDs were given: " + InputKeys.SURVEY_ID_LIST); } // Survey response. Optional. These are survey responses that // can be used to further configure the user's campaign. t = getParameterValues(InputKeys.SURVEYS); if(t.length > 1) { throw new ValidationException( ErrorCode.SURVEY_INVALID_RESPONSES, "Multiple survey response lists were given: " + InputKeys.SURVEYS); } else if(t.length == 1) { tUploadRequest = new SurveyUploadRequest( httpRequest, getParameterMap(), tCampaignId, t[0]); } } catch(ValidationException e) { e.logException(LOGGER); e.failRequest(this); } } username = tUsername; password = tPassword; classId = tClassId; campaignId = tCampaignId; surveyIds = tSurveyIds; uploadRequest = tUploadRequest; } /* * (non-Javadoc) * @see org.ohmage.request.Request#service() */ @Override public void service() { LOGGER.info("Servicing the campaign assignment request."); // Authenticate. if(! authenticate(AllowNewAccount.NEW_ACCOUNT_DISALLOWED)) { return; } try { // If given, verify that the class exists. if(classId != null) { LOGGER.info("Verifying that the class exists."); ClassServices.instance().checkClassExistence(classId, true); LOGGER .info( "Verifing that the requesting user is privileged in the class."); if(! Clazz .Role .PRIVILEGED .equals( UserClassServices .instance() .getUserRoleInClass( classId, getUser().getUsername()))) { throw new ServiceException( ErrorCode.CLASS_INSUFFICIENT_PERMISSIONS, "You are not privileged in the class: " + classId); } } // Verify that the campaign exists. LOGGER.info("Verifying that the campaign exists."); CampaignServices .instance().checkCampaignExistence(campaignId, true); // Create the campaign mask. CampaignMask mask; try { mask = new CampaignMask( null, null, getUser().getUsername(), username, campaignId, surveyIds); } catch(DomainException e) { throw new ServiceException( "An invalid password passed validation.", e); } // Verify that the user already exists and that the requesting user // is allowed to assign a campaign to them. if(password == null) { LOGGER.info( "Verifying that the requesting user is allowed to assign campaigns to the desired user."); UserClassServices .instance() .userIsPrivilegedInAnotherUserClass( getUser().getUsername(), username); } // Otherwise, attempt to create the new user. else { LOGGER.info("Verifying that the user doesn't already exist."); UserServices.instance().checkUserExistance(username, false); LOGGER.info("Creating the user."); UserServices.instance() .createUser( username, password, null, false, true, false, false); } // If a class ID was given, ensure that the user is part of the // as a restricted user. if(classId != null) { // Make sure the user is not already associated with the class. // If they are associated with the class in any capacity, then // this is unnecessary. if(UserClassServices .instance() .getUserRoleInClass(classId, username) == null) { // Create the single-sized map indicating to add the given Map<String, Clazz.Role> usersToAdd = new HashMap<String, Clazz.Role>(1); usersToAdd.put(username, Clazz.Role.RESTRICTED); LOGGER.info("Adding user to class."); ClassServices .instance() .updateClass( classId, null, null, usersToAdd, null); } } // Upload the survey response if one was given. if(uploadRequest != null) { uploadRequest.service(); if(uploadRequest.isFailed()) { return; } } // Create the campaign "mask". UserCampaignServices.instance().createUserCampaignMask(mask); } catch(ServiceException e) { e.logException(LOGGER); e.failRequest(this); } } /* * (non-Javadoc) * @see org.ohmage.request.Request#respond(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override public void respond( final HttpServletRequest httpRequest, final HttpServletResponse httpResponse) { if((uploadRequest != null) && (uploadRequest.isFailed())) { uploadRequest.respond(httpRequest, httpResponse); } else { super.respond(httpRequest, httpResponse, (JSONObject) null); } } }
package dict.build; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; import java.util.List; import java.util.Map; import java.util.TreeMap; import com.fasterxml.sort.SortConfig; import com.fasterxml.sort.std.TextFileSorter; import com.google.common.base.Charsets; import com.google.common.base.Splitter; import com.google.common.collect.Maps; import com.google.common.io.Files; /** * * @author Jennifer * */ public class FastBuilder { /** * Let's limit maximum memory used for pre-sorting when invoked from * command-line to be 256 megs */ public final static long MAX_HEAP_FOR_PRESORT = 256L * 1024 * 1024; /** * Also just in case our calculations are wrong, require 10 megs for * pre-sort anyway (if invoked from CLI) */ public final static long MIN_HEAP_FOR_PRESORT = 10L * 1024 * 1024; public final static String stopwords = ""; /** * * @param a char * @return boolean */ public static boolean isChinese(char a) { int v = (int)a; return (v >=19968 && v <= 171941); } public static boolean allChs(String s){ if (null == s || "".equals(s.trim())) return false; for (int i = 0; i < s.length(); i++) { if (!isChinese(s.charAt(i))) return false; } return true; } public TreeMap<String, double[]> loadPosprop() { TreeMap<String, double[]> prop = Maps.newTreeMap(); try { List<String> lines = Files.readLines(new File("pos_prop.txt"), Charsets.UTF_8); for (String l : lines) { String[] seg = l.split("\t"); prop.put(seg[0], new double[]{Double.parseDouble(seg[1]), Double.parseDouble(seg[2]), Double.parseDouble(seg[3])}); } } catch (IOException e) { e.printStackTrace(); } return prop; } public String parse(String filepath) { File in = new File(filepath); File out = new File(in.getParentFile(), "out.data"); try (BufferedReader ir = Files.newReader(in, Charsets.UTF_8); BufferedWriter ow = Files.newWriter(out, Charsets.UTF_8);) { String line = null; while (null != (line = ir.readLine())) { String[] seg = line.split(","); StringBuilder bui = new StringBuilder(); for (int i = 6; i < seg.length; ++i) { bui.append(seg[i]); } bui.append("\n"); ow.write(bui.toString()); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return out.getAbsolutePath(); } private String reverse(String raw) { StringBuilder bui = new StringBuilder(); for (int i = raw.length() - 1; i >= 0; --i) bui.append(raw.charAt(i)); return bui.toString(); } public void sortFile(File in, File out) { try { long availMem = Runtime.getRuntime().maxMemory() - (40 * 1024 * 1024); long maxMem = (availMem >> 1); if (maxMem > MAX_HEAP_FOR_PRESORT) { maxMem = MAX_HEAP_FOR_PRESORT; } else if (maxMem < MIN_HEAP_FOR_PRESORT) { maxMem = MIN_HEAP_FOR_PRESORT; } final TextFileSorter sorter = new TextFileSorter( new SortConfig().withMaxMemoryUsage(maxMem)); sorter.sort(new FileInputStream(in), new PrintStream(out)); } catch (IOException e) { e.printStackTrace(); } } public String genLeft(String rawTextFile, int maxLen, int memSize) { File rawFile = new File(rawTextFile); File dir = rawFile.getParentFile(); File ngramFile = new File(dir, "ngram_left.data"); File ngramSort = new File(dir, "sort_ngram_left.data"); File ngramfreq = new File(dir, "freq_ngram_left.data"); File ngramFreqSort = new File(dir, "freq_ngram_left_sort.data"); try (BufferedReader breader = Files.newReader(rawFile, Charsets.UTF_8); BufferedWriter writer = Files.newWriter(ngramFile, Charsets.UTF_8); BufferedWriter freqWriter = Files.newWriter(ngramfreq, Charsets.UTF_8);) { String line = null; while (null != (line = breader.readLine())) { line = line.replaceAll("[" + stopwords + "]", " ") .replaceAll("\\p{Punct}", " ") .replaceAll("\\pP", " ") .replaceAll("", " ") .replaceAll("\\p{Blank}", " ") .replaceAll("\\p{Space}", " ") .replaceAll("\\p{Cntrl}", " "); for (String sen : Splitter.on(" ").omitEmptyStrings() .splitToList(line)) { sen = reverse(sen.trim()); if (!allChs(sen)) continue; sen = "$" + sen + "$"; for (int i = 1; i < sen.length() - 1; ++i) { writer.write(sen.substring(i, Math.min(maxLen + i, sen.length())) + "\n"); } } } sortFile(ngramFile, ngramSort); try(BufferedReader nsr = Files.newReader(ngramSort, Charsets.UTF_8)) { String first = null; String curr = null; Map<String, CounterMap> stat = Maps.newHashMap(); while (null != (curr = nsr.readLine())) { if (null == first) { for (int i = 1; i < curr.length(); ++i) { String w = curr.substring(0, i); String suffix = curr.substring(i).substring(0, 1); if (stat.containsKey(w)) { stat.get(w).incr(suffix); } else { CounterMap cm = new CounterMap(); cm.incr(suffix); stat.put(w, cm); } } first = curr.substring(0, 1); } else { if (!curr.startsWith(first)) { StringBuilder builder = new StringBuilder(); for (String w : stat.keySet()) { CounterMap cm = stat.get(w); int freq = 0; double re = 0; for (String k : cm.countAll().keySet()) { freq += cm.get(k); } for (String k : cm.countAll().keySet()) { double p = cm.get(k) * 1.0 / freq; re += -1 * Math.log(p) / Math.log(2) * p; } builder.append(reverse(w)).append("\t").append(re).append("\n"); } freqWriter.write(builder.toString()); stat.clear(); first = curr.substring(0, 1); } for (int i = 1; i < curr.length(); ++i) { String w = curr.substring(0, i); String suffix = curr.substring(i).substring(0, 1); if (stat.containsKey(w)) { stat.get(w).incr(suffix); } else { CounterMap cm = new CounterMap(); cm.incr(suffix); stat.put(w, cm); } } } } } sortFile(ngramfreq, ngramFreqSort); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ngramFreqSort.getAbsolutePath(); } public String genFreqRight(String rawTextFile, int maxLen, int memSize) { File rawFile = new File(rawTextFile); File dir = rawFile.getParentFile(); File ngramFile = new File(dir, "ngram.data"); File ngramSort = new File(dir, "ngram_sort.data"); File ngramfreq = new File(dir, "freq_ngram.data"); File ngramfreqSort = new File(dir, "freq_ngram_sort.data"); try (BufferedReader breader = Files.newReader(rawFile, Charsets.UTF_8); BufferedWriter writer = Files.newWriter(ngramFile, Charsets.UTF_8); BufferedWriter freqWriter = Files.newWriter(ngramfreq, Charsets.UTF_8);) { String line = null; while (null != (line = breader.readLine())) { line = line.replaceAll("["+stopwords+"]", " ") .replaceAll("\\p{Punct}", " ") .replaceAll("\\pP", " ") .replaceAll("", " ") .replaceAll("\\p{Blank}", " ") .replaceAll("\\p{Space}", " ") .replaceAll("\\p{Cntrl}", " "); for (String sen : Splitter.on(" ").omitEmptyStrings() .splitToList(line)) { sen = sen.trim(); if (!allChs(sen)) continue; sen = "$" + sen + "$"; for (int i = 1; i < sen.length() - 1; ++i) { writer.write(sen.substring(i, Math.min(maxLen + i, sen.length())) + "\n"); } } } System.out.println("gen sorting..."); sortFile(ngramFile, ngramSort); try(BufferedReader nsr = Files.newReader(ngramSort, Charsets.UTF_8)) { String first = null; String curr = null; Map<String, CounterMap> stat = Maps.newHashMap(); while (null != (curr = nsr.readLine())) { if (null == first) { for (int i = 1; i < curr.length(); ++i) { String w = curr.substring(0, i); String suffix = curr.substring(i).substring(0, 1); if (stat.containsKey(w)) { stat.get(w).incr(suffix); } else { CounterMap cm = new CounterMap(); cm.incr(suffix); stat.put(w, cm); } } first = curr.substring(0, 1); } else { if (!curr.startsWith(first)) { StringBuilder builder = new StringBuilder(); for (String w : stat.keySet()) { CounterMap cm = stat.get(w); int freq = 0; double re = 0; for (String k : cm.countAll().keySet()) { freq += cm.get(k); } for (String k : cm.countAll().keySet()) { double p = cm.get(k) * 1.0 / freq; re += -1 * Math.log(p) / Math.log(2) * p; } builder.append(w).append("\t").append(freq).append("\t").append(re).append("\n"); } freqWriter.write(builder.toString()); stat.clear(); first = curr.substring(0, 1); } for (int i = 1; i < curr.length(); ++i) { String w = curr.substring(0, i); String suffix = curr.substring(i).substring(0, 1); if (stat.containsKey(w)) { stat.get(w).incr(suffix); } else { CounterMap cm = new CounterMap(); cm.incr(suffix); stat.put(w, cm); } } } } } sortFile(ngramfreq, ngramfreqSort); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ngramfreqSort.getAbsolutePath(); } public String mergeEntropy(String freqRight, String left) { File frFile = new File(freqRight); File lFile = new File(left); File mergeTmp = new File(frFile.getParentFile(), "merge.tmp"); File mergeTmp2 = new File(frFile.getParentFile(), "merge.tmp2"); File mergeFile = new File(frFile.getParentFile(), "merge_entropy.data"); try (BufferedReader rr = Files.newReader(frFile, Charsets.UTF_8); BufferedReader lr = Files.newReader(lFile, Charsets.UTF_8); BufferedWriter mw = Files.newWriter(mergeTmp, Charsets.UTF_8); BufferedWriter mf = Files.newWriter(mergeFile, Charsets.UTF_8);) { String line = null; while (null != (line = rr.readLine())) { mw.write(line + "\n"); } line = null; while (null != (line = lr.readLine())) { mw.write(line + "\n"); } sortFile(mergeTmp, mergeTmp2); BufferedReader br = Files.newReader(mergeTmp2, Charsets.UTF_8); String line1 = null; String line2 = null; line1 = br.readLine(); line2 = br.readLine(); while (true) { if (null == line1 || null == line2) break; String[] seg1 = line1.split("\t"); String[] seg2 = line2.split("\t"); if (!seg1[0].equals(seg2[0])) { line1 = new String(line2.getBytes()); line2 = br.readLine(); continue; } if (seg1.length < 2) { line1 = new String(line2.getBytes()); line2 = br.readLine(); continue; } line1 = br.readLine(); line2 = br.readLine(); if (seg1.length < 3 && seg2.length < 3) continue; double le = seg1.length == 2 ? Double.parseDouble(seg1[1]) : Double.parseDouble(seg2[1]); double re = seg1.length == 3 ? Double.parseDouble(seg1[2]) : Double.parseDouble(seg2[2]); int freq = seg1.length == 3 ? Integer.parseInt(seg1[1]) : Integer.parseInt(seg2[1]); double e = Math.min(le, re); mf.write(seg1[0] + "\t" + freq + "\t" + e + "\n"); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return mergeFile.toString(); } public static boolean allLetterOrNumber(String w) { for (char c : w.toLowerCase().toCharArray()) { boolean letter = c >= 'a' && c <= 'z'; boolean digit = c >= '0' && c <= '9'; if (!letter && !digit) return false; } return true; } public void extractWords(String freqFile, String entropyFile) { TreeMap<String, double[]> posProp = this.loadPosprop(); TreeMap<String, Integer> freq = new TreeMap<>(); File ffile = new File(freqFile); File efile = new File(entropyFile); File wfile = new File(efile.getParentFile(), "words.data"); File wsfile = new File(efile.getParentFile(), "words_sort.data"); try (BufferedReader fr = Files.newReader(ffile, Charsets.UTF_8); BufferedReader er = Files.newReader(efile, Charsets.UTF_8); BufferedWriter ww = Files.newWriter(wfile, Charsets.UTF_8);) { String line = null; long total = 0; while (null != (line = fr.readLine())) { String[] seg = line.split("\t"); if (seg.length < 3) continue; freq.put(seg[0], Integer.parseInt(seg[1])); total += 1; } line = null; while (null != (line = er.readLine())) { String[] seg = line.split("\t"); if (3 != seg.length) continue; String w = seg[0]; if (allLetterOrNumber(w)) { continue; } int f = Integer.parseInt(seg[1]); double e = Double.parseDouble(seg[2]); long max = -1; for (int s = 1; s < w.length(); ++s) { String lw = w.substring(0, s); String rw = w.substring(s); if (!freq.containsKey(lw) || !freq.containsKey(rw)) continue; long ff = freq.get(lw) * freq.get(rw); if (ff > max) max = ff; } double pf = f * total / max; double pmi = Math.log(pf) / Math.log(2); if (Double.isNaN(pmi)) continue; double pp = -1; if (null != posProp.get(w.subSequence(0, 1)) && null != posProp.get(w.subSequence(w.length() - 1, w.length()))) pp = Math.min(posProp.get(w.subSequence(0, 1))[0], posProp.get(w.subSequence(w.length() - 1, w.length()))[2]); if (pmi < 1 || e < 2 || pp < 0.1) continue; ww.write(w + "\t" + f + "\t" + pmi + "\t" + e + "\t" + pp + "\n"); } try { long availMem = Runtime.getRuntime().maxMemory() - (40 * 1024 * 1024); long maxMem = (availMem >> 1); if (maxMem > MAX_HEAP_FOR_PRESORT) { maxMem = MAX_HEAP_FOR_PRESORT; } else if (maxMem < MIN_HEAP_FOR_PRESORT) { maxMem = MIN_HEAP_FOR_PRESORT; } final SplitFileSorter sorter = new SplitFileSorter( new SortConfig().withMaxMemoryUsage(maxMem)); sorter.sort(new FileInputStream(wfile), new PrintStream(wsfile)); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { FastBuilder builder = new FastBuilder(); String rawpath = builder.parse("/Users/zhangcheng/Downloads/comment/test/all.csv"); // String rawpath = "/Users/zhangcheng/Downloads/data/guba/raw_data.txt"; // String rawpath = "/Users/zhangcheng/Downloads/data/xiyouji/xiyou.txt"; // String rawpath = "/Users/zhangcheng/Downloads/data/jinpingmei/jpm.txt"; String freqRight = builder.genFreqRight(rawpath, 6, 1024); String left = builder.genLeft(rawpath, 6, 1024); // String freqRight = // "/Users/zhangcheng/Documents/workspace/python/meta_search/freq_ngram_sort.data"; // String left = // "/Users/zhangcheng/Documents/workspace/python/meta_search/freq_ngram_left_sort.data"; // String freqRight = "/Users/zhangcheng/Downloads/comment/test/freq_ngram_sort.data"; // String left = "/Users/zhangcheng/Downloads/comment/test/freq_ngram_left_sort.data"; String entropyfile = builder.mergeEntropy(freqRight, left); builder.extractWords(freqRight, entropyfile); } }
public interface AutoCommand{ /** * This method should contain code run by auto script * * @param distance * @param speed * @param useSensor */ public void runAuto(double distance, double speed, boolean useSensor); //Abstract method that should hold code that is supposed to be called during auto when the command is called /** * This method should contains code that returns if the auto command is done * * @return */ public boolean autoCommandDone(); //Abstract method that should hold code that should return true if the auto command is done }
// FILE NAME: KilroyGyro.java (Team 339 - Kilroy) // ABSTRACT: // sets up and declares a gyro, includes various functions // checks to see if we have a gyro and if we do, we declare it, if we // dont then we print that to the screen, and if neither we return null // calibration, reset, getAngle (in degrees), and getRate functions // are included package org.usfirst.frc.team339.HardwareInterfaces; import edu.wpi.first.wpilibj.ADXRS450_Gyro; /** * sets up the gyro and includes the functions * * @author Becky Button * */ public class KilroyGyro { private ADXRS450_Gyro gyro; private boolean hasGyro = true; public double initGyroVal = 0.0; /** * determines based on whether we have a gyro or not, whether to declare * the gyro(if we have one), print that we dont have a gyro(if we * dont), and return null if neither apply * * @param hasGyro */ public KilroyGyro (boolean hasGyro) { // set this.hasGyro equal to hasGyro-essentially setting up shorthand this.hasGyro = hasGyro; // if we do not have a gyro if (hasGyro == false) { // print out Gyro not connected System.out.println("Gyro not connected"); } //// if we have a gyro if (hasGyro == true) { // then declare as a new gyro this.gyro = new ADXRS450_Gyro(); // If the gyro is not slightly offset, we know it is not working. if (this.isConnected()) { this.hasGyro = false; System.out.println("Gyro Not Connected"); this.gyro = null; } } // if we don't have a gyro, but we don't not have a gyro, return null else // if neither then return null this.gyro = null; // IF for some reason the gyro is not created, THEN tell the class that we // do not have a gyro. if (this.gyro == null) { this.hasGyro = false; } } /** * calibration of the gyro */ public void calibrate () { // if we do not have a gyro if (this.isConnected() == false) { // then return void return; } // then calibrate gyro this.gyro.calibrate(); } /** * resets the gyro */ public void reset () { // if we do not have a gyro if (this.isConnected() == false) { // return void return; } // then reset the gyro this.gyro.reset(); } /** * will return the gyro angle in degrees * * @return * return gyro angle */ public double getAngle () { // if we don't have a gyro if (this.isConnected() == false) { // return 339339 return 339339; } // return the angle of the gyro in degrees return this.gyro.getAngle(); } /** * returns the rate of rotation for the gyro * * @return * return rate of rotation */ public double getRate () { // if we don't have a gyro if (this.isConnected() == false) { // return the random value 339339 return 339339; } // return the rate of rotation of the gyro return this.gyro.getRate(); } /** * * @return Whether or not the gyro's angle is 0.0, which is returned * if the SPI bus is null (in wpi's Gyro class) * constructor. */ public boolean isConnected () { return (this.gyro.getAngle() == 0.0) == false && this.hasGyro == true && this.gyro != null; } }
package org.eclipse.jetty.start; import java.io.BufferedReader; import java.io.Closeable; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.ConnectException; import java.net.InetAddress; import java.net.Socket; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Properties; import java.util.Set; /** * <p> * Main start class. This class is intended to be the main class listed in the MANIFEST.MF of the start.jar archive. It allows an application to be started with * the command "java -jar start.jar". * </p> * * <p> * The behaviour of Main is controlled by the parsing of the {@link Config} "org/eclipse/start/start.config" file obtained as a resource or file. * </p> */ public class Main { private static final String START_LOG_FILENAME = "start.log"; private static final SimpleDateFormat START_LOG_ROLLOVER_DATEFORMAT = new SimpleDateFormat("yyyy_MM_dd-HHmmSSSSS.'" + START_LOG_FILENAME + "'"); private static final int EXIT_USAGE = 1; private static final int ERR_LOGGING = -1; private static final int ERR_INVOKE_MAIN = -2; private static final int ERR_NOT_STOPPED = -4; private static final int ERR_UNKNOWN = -5; private boolean _showUsage = false; private boolean _dumpVersions = false; private boolean _listConfig = false; private boolean _listOptions = false; private boolean _dryRun = false; private boolean _exec = false; private final Config _config = new Config(); private final Set<String> _sysProps = new HashSet<String>(); private final List<String> _jvmArgs = new ArrayList<String>(); private String _startConfig = null; private String _jettyHome; public static void main(String[] args) { try { Main main = new Main(); List<String> arguments = main.expandCommandLine(args); List<String> xmls = main.processCommandLine(arguments); if (xmls!=null) main.start(xmls); } catch (Throwable e) { usageExit(e,ERR_UNKNOWN); } } Main() throws IOException { _jettyHome = System.getProperty("jetty.home","."); _jettyHome = new File(_jettyHome).getCanonicalPath(); } public List<String> expandCommandLine(String[] args) throws Exception { List<String> arguments = new ArrayList<String>(); // add the command line args and look for start.ini args boolean ini = false; for (String arg : args) { if (arg.startsWith("--ini=") || arg.equals("--ini")) { ini = true; if (arg.length() > 6) { arguments.addAll(loadStartIni(new File(arg.substring(6)))); } } else if (arg.startsWith("--config=")) { _startConfig = arg.substring(9); } else { arguments.add(arg); } } // if no non-option inis, add the start.ini and start.d if (!ini) { arguments.addAll(0,parseStartIniFiles()); } return arguments; } List<String> parseStartIniFiles() { List<String> ini_args=new ArrayList<String>(); File start_ini = new File(_jettyHome,"start.ini"); if (start_ini.exists()) ini_args.addAll(loadStartIni(start_ini)); File start_d = new File(_jettyHome,"start.d"); if (start_d.isDirectory()) { File[] inis = start_d.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".ini"); } }); Arrays.sort(inis); for (File i : inis) ini_args.addAll(loadStartIni(i)); } return ini_args; } public List<String> processCommandLine(List<String> arguments) throws Exception { // The XML Configuration Files to initialize with List<String> xmls = new ArrayList<String>(); // Process the arguments int startup = 0; for (String arg : arguments) { if ("--help".equals(arg) || "-?".equals(arg)) { _showUsage = true; continue; } if ("--stop".equals(arg)) { int port = Integer.parseInt(Config.getProperty("STOP.PORT","-1")); String key = Config.getProperty("STOP.KEY",null); stop(port,key); return null; } if ("--version".equals(arg) || "-v".equals(arg) || "--info".equals(arg)) { _dumpVersions = true; continue; } if ("--list-modes".equals(arg) || "--list-options".equals(arg)) { _listOptions = true; continue; } if ("--list-config".equals(arg)) { _listConfig = true; continue; } if ("--exec-print".equals(arg) || "--dry-run".equals(arg)) { _dryRun = true; continue; } if ("--exec".equals(arg)) { _exec = true; continue; } // Special internal indicator that jetty was started by the jetty.sh Daemon if ("--daemon".equals(arg)) { File startDir = new File(System.getProperty("jetty.logs","logs")); if (!startDir.exists() || !startDir.canWrite()) startDir = new File("."); File startLog = new File(startDir, START_LOG_ROLLOVER_DATEFORMAT.format(new Date())); if (!startLog.exists() && !startLog.createNewFile()) { // Output about error is lost in majority of cases. System.err.println("Unable to create: " + startLog.getAbsolutePath()); // Toss a unique exit code indicating this failure. usageExit(ERR_LOGGING); } if (!startLog.canWrite()) { // Output about error is lost in majority of cases. System.err.println("Unable to write to: " + startLog.getAbsolutePath()); // Toss a unique exit code indicating this failure. usageExit(ERR_LOGGING); } PrintStream logger = new PrintStream(new FileOutputStream(startLog,false)); System.setOut(logger); System.setErr(logger); System.out.println("Establishing "+ START_LOG_FILENAME + " on " + new Date()); continue; } if (arg.startsWith("--pre=")) { xmls.add(startup++,arg.substring(6)); continue; } if (arg.startsWith("-D")) { String[] assign = arg.substring(2).split("=",2); _sysProps.add(assign[0]); switch (assign.length) { case 2: System.setProperty(assign[0],assign[1]); break; case 1: System.setProperty(assign[0],""); break; default: break; } continue; } if (arg.startsWith("-")) { _jvmArgs.add(arg); continue; } // Is this a Property? if (arg.indexOf('=') >= 0) { String[] assign = arg.split("=",2); switch (assign.length) { case 2: if ("OPTIONS".equals(assign[0])) { String opts[] = assign[1].split(","); for (String opt : opts) _config.addActiveOption(opt); } else { this._config.setProperty(assign[0],assign[1]); } break; case 1: this._config.setProperty(assign[0],null); break; default: break; } continue; } // Anything else is considered an XML file. if (xmls.contains(arg)) { System.out.println("WARN: Argument '" + arg + "' specified multiple times. Check start.ini?"); System.out.println("Use \"java -jar start.jar --help\" for more information."); } xmls.add(arg); } return xmls; } private void usage() { String usageResource = "org/eclipse/jetty/start/usage.txt"; InputStream usageStream = getClass().getClassLoader().getResourceAsStream(usageResource); if (usageStream == null) { System.err.println("ERROR: detailed usage resource unavailable"); usageExit(EXIT_USAGE); } BufferedReader buf = null; try { buf = new BufferedReader(new InputStreamReader(usageStream)); String line; while ((line = buf.readLine()) != null) { if (line.endsWith("@") && line.indexOf('@') != line.lastIndexOf('@')) { String indent = line.substring(0,line.indexOf("@")); String info = line.substring(line.indexOf('@'),line.lastIndexOf('@')); if (info.equals("@OPTIONS")) { List<String> sortedOptions = new ArrayList<String>(); sortedOptions.addAll(_config.getSectionIds()); Collections.sort(sortedOptions); for (String option : sortedOptions) { if ("*".equals(option) || option.trim().length() == 0) continue; System.out.print(indent); System.out.println(option); } } else if (info.equals("@CONFIGS")) { File etc = new File(System.getProperty("jetty.home","."),"etc"); if (!etc.exists() || !etc.isDirectory()) { System.out.print(indent); System.out.println("Unable to find/list " + etc); continue; } File configs[] = etc.listFiles(new FileFilter() { public boolean accept(File path) { if (!path.isFile()) { return false; } String name = path.getName().toLowerCase(); return (name.startsWith("jetty") && name.endsWith(".xml")); } }); List<File> configFiles = new ArrayList<File>(); configFiles.addAll(Arrays.asList(configs)); Collections.sort(configFiles); for (File configFile : configFiles) { System.out.print(indent); System.out.print("etc/"); System.out.println(configFile.getName()); } } else if (info.equals("@STARTINI")) { List<String> ini = loadStartIni(new File(_jettyHome,"start.ini")); if (ini != null && ini.size() > 0) { for (String a : ini) { System.out.print(indent); System.out.println(a); } } else { System.out.print(indent); System.out.println("none"); } } } else { System.out.println(line); } } } catch (IOException e) { usageExit(e,EXIT_USAGE); } finally { close(buf); } System.exit(EXIT_USAGE); } public void invokeMain(ClassLoader classloader, String classname, List<String> args) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException { Class<?> invoked_class = null; try { invoked_class = classloader.loadClass(classname); } catch (ClassNotFoundException e) { e.printStackTrace(); } if (Config.isDebug() || invoked_class == null) { if (invoked_class == null) { System.err.println("ClassNotFound: " + classname); } else { System.err.println(classname + " " + invoked_class.getPackage().getImplementationVersion()); } if (invoked_class == null) { usageExit(ERR_INVOKE_MAIN); return; } } String argArray[] = args.toArray(new String[0]); Class<?>[] method_param_types = new Class[] { argArray.getClass() }; Method main = invoked_class.getDeclaredMethod("main",method_param_types); Object[] method_params = new Object[] { argArray }; main.invoke(null,method_params); } public static void close(Closeable c) { if (c == null) { return; } try { c.close(); } catch (IOException e) { e.printStackTrace(System.err); } } public void start(List<String> xmls) throws IOException, InterruptedException { // Setup Start / Stop Monitoring int port = Integer.parseInt(Config.getProperty("STOP.PORT","-1")); String key = Config.getProperty("STOP.KEY",null); Monitor monitor = new Monitor(port,key); // Load potential Config (start.config) List<String> configuredXmls = loadConfig(xmls); // No XML defined in start.config or command line. Can't execute. if (configuredXmls.isEmpty()) { throw new FileNotFoundException("No XML configuration files specified in start.config or command line."); } // Normalize the XML config options passed on the command line. configuredXmls = resolveXmlConfigs(configuredXmls); // Get Desired Classpath based on user provided Active Options. Classpath classpath = _config.getActiveClasspath(); System.setProperty("java.class.path",classpath.toString()); ClassLoader cl = classpath.getClassLoader(); if (Config.isDebug()) { System.err.println("java.class.path=" + System.getProperty("java.class.path")); System.err.println("jetty.home=" + System.getProperty("jetty.home")); System.err.println("java.home=" + System.getProperty("java.home")); System.err.println("java.io.tmpdir=" + System.getProperty("java.io.tmpdir")); System.err.println("java.class.path=" + classpath); System.err.println("classloader=" + cl); System.err.println("classloader.parent=" + cl.getParent()); System.err.println("properties=" + Config.getProperties()); } // Show the usage information and return if (_showUsage) { usage(); return; } // Show the version information and return if (_dumpVersions) { showClasspathWithVersions(classpath); return; } // Show all options with version information if (_listOptions) { showAllOptionsWithVersions(); return; } if (_listConfig) { listConfig(); return; } // Show Command Line to execute Jetty if (_dryRun) { CommandLineBuilder cmd = buildCommandLine(classpath,configuredXmls); System.out.println(cmd.toString()); return; } // execute Jetty in another JVM if (_exec) { CommandLineBuilder cmd = buildCommandLine(classpath,configuredXmls); ProcessBuilder pbuilder = new ProcessBuilder(cmd.getArgs()); final Process process = pbuilder.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { Config.debug("Destroying " + process); process.destroy(); } }); copyInThread(process.getErrorStream(),System.err); copyInThread(process.getInputStream(),System.out); copyInThread(System.in,process.getOutputStream()); monitor.setProcess(process); process.waitFor(); return; } if (_jvmArgs.size() > 0 || _sysProps.size() > 0) { System.err.println("WARNING: System properties and/or JVM args set. Consider using --dry-run or --exec"); } // Set current context class loader to what is selected. Thread.currentThread().setContextClassLoader(cl); // Invoke the Main Class try { // Get main class as defined in start.config String classname = _config.getMainClassname(); // Check for override of start class (via "jetty.server" property) String mainClass = System.getProperty("jetty.server"); if (mainClass != null) { classname = mainClass; } // Check for override of start class (via "main.class" property) mainClass = System.getProperty("main.class"); if (mainClass != null) { classname = mainClass; } Config.debug("main.class=" + classname); invokeMain(cl,classname,configuredXmls); } catch (Exception e) { usageExit(e,ERR_INVOKE_MAIN); } } private void copyInThread(final InputStream in, final OutputStream out) { new Thread(new Runnable() { public void run() { try { byte[] buf = new byte[1024]; int len = in.read(buf); while (len > 0) { out.write(buf,0,len); len = in.read(buf); } } catch (IOException e) { // e.printStackTrace(); } } }).start(); } private String resolveXmlConfig(String xmlFilename) throws FileNotFoundException { if (!xmlFilename.toLowerCase().endsWith(".xml")) { // Nothing to resolve. return xmlFilename; } File xml = new File(xmlFilename); if (xml.exists() && xml.isFile()) { return xml.getAbsolutePath(); } xml = new File(_jettyHome,fixPath(xmlFilename)); if (xml.exists() && xml.isFile()) { return xml.getAbsolutePath(); } xml = new File(_jettyHome,fixPath("etc/" + xmlFilename)); if (xml.exists() && xml.isFile()) { return xml.getAbsolutePath(); } throw new FileNotFoundException("Unable to find XML Config: " + xmlFilename); } CommandLineBuilder buildCommandLine(Classpath classpath, List<String> xmls) throws IOException { CommandLineBuilder cmd = new CommandLineBuilder(findJavaBin()); for (String x : _jvmArgs) { cmd.addArg(x); } cmd.addRawArg("-Djetty.home=" + _jettyHome); for (String p : _sysProps) { String v = System.getProperty(p); cmd.addEqualsArg("-D" + p,v); } cmd.addArg("-cp"); cmd.addRawArg(classpath.toString()); cmd.addRawArg(_config.getMainClassname()); // Check if we need to pass properties as a file Properties properties = Config.getProperties(); if (properties.size() > 0) { File prop_file = File.createTempFile("start",".properties"); if (!_dryRun) prop_file.deleteOnExit(); properties.store(new FileOutputStream(prop_file),"start.jar properties"); cmd.addArg(prop_file.getAbsolutePath()); } for (String xml : xmls) { cmd.addRawArg(xml); } return cmd; } private String findJavaBin() { File javaHome = new File(System.getProperty("java.home")); if (!javaHome.exists()) { return null; } File javabin = findExecutable(javaHome,"bin/java"); if (javabin != null) { return javabin.getAbsolutePath(); } javabin = findExecutable(javaHome,"bin/java.exe"); if (javabin != null) { return javabin.getAbsolutePath(); } return "java"; } private File findExecutable(File root, String path) { String npath = path.replace('/',File.separatorChar); File exe = new File(root,npath); if (!exe.exists()) { return null; } return exe; } private void showAllOptionsWithVersions() { Set<String> sectionIds = _config.getSectionIds(); StringBuffer msg = new StringBuffer(); msg.append("There "); if (sectionIds.size() > 1) { msg.append("are "); } else { msg.append("is "); } msg.append(String.valueOf(sectionIds.size())); msg.append(" OPTION"); if (sectionIds.size() > 1) { msg.append("s"); } msg.append(" available to use."); System.out.println(msg); System.out.println("Each option is listed along with associated available classpath entries, in the order that they would appear from that mode."); System.out.println("Note: If using multiple options (eg: 'Server,servlet,webapp,jms,jmx') " + "then overlapping entries will not be repeated in the eventual classpath."); System.out.println(); System.out.printf("${jetty.home} = %s%n",_jettyHome); System.out.println(); for (String sectionId : sectionIds) { if (Config.DEFAULT_SECTION.equals(sectionId)) { System.out.println("GLOBAL option (Prepended Entries)"); } else if ("*".equals(sectionId)) { System.out.println("GLOBAL option (Appended Entries) (*)"); } else { System.out.printf("Option [%s]",sectionId); if (Character.isUpperCase(sectionId.charAt(0))) { System.out.print(" (Aggregate)"); } System.out.println(); } System.out.println(" Classpath sectionCP = _config.getSectionClasspath(sectionId); if (sectionCP.isEmpty()) { System.out.println("Empty option, no classpath entries active."); System.out.println(); continue; } int i = 0; for (File element : sectionCP.getElements()) { String elementPath = element.getAbsolutePath(); if (elementPath.startsWith(_jettyHome)) { elementPath = "${jetty.home}" + elementPath.substring(_jettyHome.length()); } System.out.printf("%2d: %20s | %s\n",i++,getVersion(element),elementPath); } System.out.println(); } } private void showClasspathWithVersions(Classpath classpath) { // Iterate through active classpath, and fetch Implementation Version from each entry (if present) // to dump to end user. System.out.println("Active Options: " + _config.getActiveOptions()); if (classpath.count() == 0) { System.out.println("No version information available show."); return; } System.out.println("Version Information on " + classpath.count() + " entr" + ((classpath.count() > 1)?"ies":"y") + " in the classpath."); System.out.println("Note: order presented here is how they would appear on the classpath."); System.out.println(" changes to the OPTIONS=[option,option,...] command line option will be reflected here."); int i = 0; for (File element : classpath.getElements()) { String elementPath = element.getAbsolutePath(); if (elementPath.startsWith(_jettyHome)) { elementPath = "${jetty.home}" + elementPath.substring(_jettyHome.length()); } System.out.printf("%2d: %20s | %s\n",i++,getVersion(element),elementPath); } } private String fixPath(String path) { return path.replace('/',File.separatorChar); } private String getVersion(File element) { if (element.isDirectory()) { return "(dir)"; } if (element.isFile()) { String name = element.getName().toLowerCase(); if (name.endsWith(".jar")) { return JarVersion.getVersion(element); } if (name.endsWith(".zip")) { return getZipVersion(element); } } return ""; } private String getZipVersion(File element) { // TODO - find version in zip file. Look for META-INF/MANIFEST.MF ? return ""; } private List<String> resolveXmlConfigs(List<String> xmls) throws FileNotFoundException { List<String> ret = new ArrayList<String>(); for (String xml : xmls) { ret.add(resolveXmlConfig(xml)); } return ret; } private void listConfig() { InputStream cfgstream = null; try { cfgstream = getConfigStream(); byte[] buf = new byte[4096]; int len = 0; while (len >= 0) { len = cfgstream.read(buf); if (len > 0) System.out.write(buf,0,len); } } catch (Exception e) { usageExit(e,ERR_UNKNOWN); } finally { close(cfgstream); } } /** * Load Configuration. * * No specific configuration is real until a {@link Config#getCombinedClasspath(java.util.Collection)} is used to execute the {@link Class} specified by * {@link Config#getMainClassname()} is executed. * * @param xmls * the command line specified xml configuration options. * @return the list of xml configurations arriving via command line and start.config choices. */ private List<String> loadConfig(List<String> xmls) { InputStream cfgstream = null; try { // Pass in xmls.size into Config so that conditions based on "nargs" work. _config.setArgCount(xmls.size()); cfgstream = getConfigStream(); // parse the config _config.parse(cfgstream); _jettyHome = Config.getProperty("jetty.home",_jettyHome); if (_jettyHome != null) { _jettyHome = new File(_jettyHome).getCanonicalPath(); System.setProperty("jetty.home",_jettyHome); } // Collect the configured xml configurations. List<String> ret = new ArrayList<String>(); ret.addAll(xmls); // add command line provided xmls first. for (String xmlconfig : _config.getXmlConfigs()) { // add xmlconfigs arriving via start.config if (!ret.contains(xmlconfig)) { ret.add(xmlconfig); } } return ret; } catch (Exception e) { usageExit(e,ERR_UNKNOWN); return null; // never executed (just here to satisfy javac compiler) } finally { close(cfgstream); } } private InputStream getConfigStream() throws FileNotFoundException { String config = _startConfig; if (config == null || config.length() == 0) { config = System.getProperty("START","org/eclipse/jetty/start/start.config"); } Config.debug("config=" + config); // Look up config as resource first. InputStream cfgstream = getClass().getClassLoader().getResourceAsStream(config); // resource not found, try filesystem next if (cfgstream == null) { cfgstream = new FileInputStream(config); } return cfgstream; } /** * Stop a running jetty instance. */ public void stop(int port, String key) { int _port = port; String _key = key; try { if (_port <= 0) { System.err.println("STOP.PORT system property must be specified"); } if (_key == null) { _key = ""; System.err.println("STOP.KEY system property must be specified"); System.err.println("Using empty key"); } Socket s = new Socket(InetAddress.getByName("127.0.0.1"),_port); try { OutputStream out = s.getOutputStream(); out.write((_key + "\r\nstop\r\n").getBytes()); out.flush(); } finally { s.close(); } } catch (ConnectException e) { usageExit(e,ERR_NOT_STOPPED); } catch (Exception e) { usageExit(e,ERR_UNKNOWN); } } static void usageExit(Throwable t, int exit) { t.printStackTrace(System.err); System.err.println(); System.err.println("Usage: java -jar start.jar [options] [properties] [configs]"); System.err.println(" java -jar start.jar --help # for more information"); System.exit(exit); } static void usageExit(int exit) { System.err.println(); System.err.println("Usage: java -jar start.jar [options] [properties] [configs]"); System.err.println(" java -jar start.jar --help # for more information"); System.exit(exit); } /** * Convert a start.ini format file into an argument list. */ static List<String> loadStartIni(File ini) { if (!ini.exists()) { System.err.println("Warning - can't find ini file: " + ini); // No start.ini found, skip load. return Collections.emptyList(); } List<String> args = new ArrayList<String>(); FileReader reader = null; BufferedReader buf = null; try { reader = new FileReader(ini); buf = new BufferedReader(reader); String arg; while ((arg = buf.readLine()) != null) { arg = arg.trim(); if (arg.length() == 0 || arg.startsWith(" { continue; } args.add(arg); } } catch (IOException e) { usageExit(e,ERR_UNKNOWN); } finally { Main.close(buf); Main.close(reader); } return args; } void addJvmArgs(List<String> jvmArgs) { _jvmArgs.addAll(jvmArgs); } }
package slogo.backend.impl.evaluation.commands.control; import java.util.List; import slogo.backend.evaluation.IExecutionContext; import slogo.backend.evaluation.MalformedSyntaxException; import slogo.backend.impl.evaluation.Evaluator; import slogo.backend.impl.evaluation.commands.Operation; import slogo.backend.parsing.ISyntaxNode; public class Repeat extends Operation{ public Repeat (String type, int argMin, int argMax) { super(type, 2, 2); // TODO Auto-generated constructor stub } @Override protected IExecutionContext executeRaw (List<IExecutionContext> args, IExecutionContext previous, ISyntaxNode current) { // TODO Auto-generated method stub String argumentTwo = args.get(1).environment().get("returnValue"); int times = Integer.parseInt(argumentTwo); //Error check times > 1 Evaluator e = new Evaluator(); IExecutionContext context = args.get(0); for (int i = 0 ; i<times-1; i++){ try { context = e.evaluate(current.children().get(0), context); } catch (MalformedSyntaxException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } return context; } }
package com.vmware.utils; import com.vmware.util.ArrayUtils; import org.junit.Test; import java.util.Arrays; import java.util.Objects; import java.util.stream.Stream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class TestArrayUtils { @Test public void addToArray() { Integer[] startingArray = new Integer[] {56, 23, 34}; Integer[] updatedArray = ArrayUtils.add(startingArray, 29); assertEquals(Arrays.toString(new Integer[] {23, 29, 34, 56}), Arrays.toString(updatedArray)); } @Test public void removeFromArray() { Integer[] startingArray = new Integer[] {56, 23, 34}; Integer[] updatedArray = ArrayUtils.remove(startingArray, 23); assertEquals(Arrays.toString(new Integer[] {56, 34}), Arrays.toString(updatedArray)); } @Test public void maxCheck() { Integer[] passedBuilds = new Integer[] {183, 184}; Integer[] presumedPassedBuilds = new Integer[] {181}; int newestPass = Stream.of(passedBuilds, presumedPassedBuilds).filter(Objects::nonNull).flatMap(Arrays::stream).mapToInt(Integer::intValue).max().orElse(-1); assertEquals(184, newestPass); Integer firstValue = 108; int secondValue = 109; assertTrue(secondValue > firstValue); } @Test public void findInArray() { int[] values = new int[] {23, 34, 56}; assertEquals(0, Arrays.binarySearch(values, 23)); assertEquals(-2, Arrays.binarySearch(values, 24)); assertEquals(-3, Arrays.binarySearch(values, 37)); assertEquals(2, Arrays.binarySearch(values, 56)); assertEquals(-4, Arrays.binarySearch(values, 600)); } }
package org.vrjuggler.tweek; import java.io.File; import java.util.Vector; import org.vrjuggler.tweek.beans.*; import org.vrjuggler.tweek.beans.loader.BeanInstantiationException; import org.vrjuggler.tweek.services.*; import org.vrjuggler.tweek.net.corba.*; /** * @since 1.0 */ public class TweekCore { // Public methods. public static TweekCore instance () { if ( m_instance == null ) { m_instance = new TweekCore(); } return m_instance; } public void init (String[] args) throws Exception { // This needs to be the first step to ensure that all the basic services // and viewers get loaded. findBeans(System.getProperty("TWEEK_BASE_DIR") + File.separator + "bin" + File.separator + "beans"); String[] new_args = parseTweekArgs(args); // Load the service Beans into the services registry. buildServiceRegistry(); // Register the command-line arguments with the Environment Service (if // it is available). try { EnvironmentService service = (EnvironmentService) ServiceRegistry.instance().getService("Environment"); if ( service != null ) { service.setCommandLineArgs(new_args); } } catch (ClassCastException e) { System.err.println("WARNING: Failed to register command-line arguments"); } // Load the viewer Beans into the viewers registry. buildViewerRegistry(); // Load the user's global preferences file. GlobalPreferencesService.instance().load(); m_gui = new TweekFrame(); // Now we need to register the TweekFrame instance as a listener for // BeanFocusChangeEvents. Vector viewer_beans = ViewerRegistry.instance().getAllViewers(); for ( int i = 0; i < viewer_beans.size(); i++ ) { BeanModelViewer v = (BeanModelViewer) viewer_beans.elementAt(i); v.addBeanFocusChangeListener(m_gui); } m_gui.initGUI(BeanCollectionBuilder.instance().getPanelTree()); } /** * Default constructor. */ protected TweekCore () { } /** * Searches for JavaBeans in the given path. * * @pre The GUI has not been initialized yet. */ protected void findBeans (String path) { try { BeanCollectionBuilder.instance().build(path, ! path.endsWith(".xml")); } catch (org.vrjuggler.tweek.beans.BeanPathException e) { System.out.println("WARNING: Invalid path " + path); } } /** * Looks through the given array of arguments for any that are specific to * the Tweek Java GUI. Those that are recognized are removed and handled * here. Unrecognized options are left in the array. The remaining * arguments are returned to the caller in a new array. * * @post Any Tweek-specific arguments are removed and a new array without * those arguments is returned. */ protected String[] parseTweekArgs (String[] args) { Vector save_args = new Vector(); for ( int i = 0; i < args.length; i++ ) { if ( args[i].startsWith("--beanpath=") ) { int start = args[i].indexOf('=') + 1; String path = args[i].substring(start); findBeans(path); } else { save_args.add(args[i]); } } String[] new_args = null; if ( save_args.size() > 0 ) { new_args = new String[save_args.size()]; for ( int i = 0; i < save_args.size(); i++ ) { new_args[i] = (String) save_args.elementAt(i); } } return new_args; } protected void buildServiceRegistry () { Vector services = BeanCollectionBuilder.instance().getServices(); ServiceRegistry.instance().registerService("Environment", new EnvironmentService()); for ( int i = 0; i < services.size(); i++ ) { ServiceBean service = (ServiceBean) services.elementAt(i); try { service.instantiate(); ServiceRegistry.instance().registerService(service.getServiceName(), service.getService()); } catch (BeanInstantiationException e) { System.err.println("WARNING: Failed to instantiate service '" + service.getServiceName() + "': " + e.getMessage()); } } } protected void buildViewerRegistry () { Vector viewers = BeanCollectionBuilder.instance().getViewers(); BeanTreeModel tree_model = BeanCollectionBuilder.instance().getPanelTree(); GlobalPreferencesService prefs = GlobalPreferencesService.instance(); for ( int i = 0; i < viewers.size(); i++ ) { ViewerBean viewer = (ViewerBean) viewers.elementAt(i); try { // The process of loading a new BeanViewer object is a little // involved. First, we need an instance (duh). After that, we // need to pass it the tree model, initialize its GUI, and add it // to the available choices in the global preferences. Once all // that is done, the viewer can be registered for use by other // code. viewer.instantiate(); BeanModelViewer bv = (BeanModelViewer) viewer.getViewer(); bv.initDataModel(tree_model); bv.initGUI(); prefs.addBeanViewer(viewer.getViewerName()); ViewerRegistry.instance().registerViewer(viewer.getViewerName(), viewer.getViewer()); } catch (BeanInstantiationException e) { System.err.println("WARNING: Failed to instantiate Bean viewer '" + viewer.getViewerName() + "': " + e.getMessage()); } } } // Protected data members. protected static TweekCore m_instance = null; // Private data members. private TweekFrame m_gui = null; }
package com.psddev.dari.db; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.psddev.dari.util.CodeUtils; import com.psddev.dari.util.CompactMap; import com.psddev.dari.util.DebugFilter; import com.psddev.dari.util.ObjectUtils; @DebugFilter.Path("db-schema") @SuppressWarnings("serial") public class SchemaDebugServlet extends HttpServlet { @Override protected void service( HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { new DebugFilter.PageWriter(getServletContext(), request, response) { { Database database = Database.Static.getDefault(); List<ObjectType> types = new ArrayList<ObjectType>(database.getEnvironment().getTypes()); Collections.sort(types); Set<ObjectType> selectedTypes = new HashSet<ObjectType>(); List<UUID> typeIds = page.params(UUID.class, "typeId"); if (typeIds != null) { Set<UUID> typeIdsSet = new HashSet<UUID>(); typeIdsSet.addAll(typeIds); for (ObjectType t : types) { if (typeIdsSet.contains(t.getId())) { selectedTypes.add(t); } } } startPage("Database", "Schema"); writeStart("form", "method", "get"); writeStart("select", "multiple", "multiple", "name", "typeId", "style", "width: 90%;"); for (ObjectType t : types) { writeStart("option", "selected", selectedTypes.contains(t) ? "selected" : null, "value", t.getId()); writeHtml(t.getDisplayName()); writeHtml(" (").writeHtml(t.getInternalName()).writeHtml(")"); writeEnd(); } writeEnd(); writeElement("br"); writeElement("input", "class", "btn", "type", "submit", "value", "View"); writeEnd(); includeStylesheet("/_resource/chosen/chosen.css"); includeScript("/_resource/chosen/chosen.jquery.min.js"); writeStart("script", "type", "text/javascript"); write("(function() {"); write("$('select[name=typeId]').chosen({ 'search_contains': true });"); write("})();"); writeEnd(); writeStart("style", "type", "text/css"); write(".column { display: table-cell; padding-right: 15em; text-align: center; vertical-align: top; }"); write(".column dl { margin-bottom: 0; }"); write(".type { border: 1px solid black; display: inline-block; margin-bottom: 5em; padding: 0.5em; text-align: left; }"); write(".type h2 { white-space: nowrap; }"); write(".type dt { margin-bottom: 5px; }"); write(".type dd:last-child table { margin-bottom: 0; }"); write(".type .reference { color: white; white-space: nowrap; }"); writeEnd(); writeStart("div", "class", "types"); Set<ObjectType> allTypes = new HashSet<ObjectType>(); Set<ObjectType> currentTypes = new HashSet<ObjectType>(selectedTypes); while (!currentTypes.isEmpty()) { writeStart("div", "class", "column"); allTypes.addAll(currentTypes); Set<ObjectType> nextTypes = new LinkedHashSet<ObjectType>(); for (ObjectType t : currentTypes) { Map<String, List<ObjectField>> fieldsByClass = new CompactMap<String, List<ObjectField>>(); for (ObjectField field : t.getFields()) { String declaringClass = field.getJavaDeclaringClassName(); if (declaringClass == null) { declaringClass = "Dynamic Fields"; } List<ObjectField> fields = fieldsByClass.get(declaringClass); if (fields == null) { fields = new ArrayList<ObjectField>(); fieldsByClass.put(declaringClass, fields); } fields.add(field); } writeStart("div").writeEnd(); writeStart("div", "class", "type", "id", "type-" + t.getId()); writeStart("h2").writeHtml(t.getDisplayName()).writeEnd(); writeStart("dl"); for (Map.Entry<String, List<ObjectField>> entry : fieldsByClass.entrySet()) { String className = entry.getKey(); File source = CodeUtils.getSource(className); writeStart("dt"); if (source == null) { writeHtml(className); } else { writeStart("a", "target", "_blank", "href", DebugFilter.Static.getServletPath(page.getRequest(), "code", "file", source)); writeHtml(className); writeEnd(); } writeEnd(); writeStart("dd"); writeStart("table", "class", "table table-condensed"); writeStart("tbody"); for (ObjectField field : entry.getValue()) { if (page.param(boolean.class, "nf") && !field.getInternalItemType().equals("record")) { continue; } writeStart("tr"); writeStart("td").writeHtml(field.getInternalName()).writeEnd(); writeStart("td").writeHtml(field.getInternalType()).writeEnd(); writeStart("td"); if (ObjectField.RECORD_TYPE.equals(field.getInternalItemType())) { Set<ObjectType> itemTypes = field.getTypes(); if (!ObjectUtils.isBlank(itemTypes)) { for (ObjectType itemType : itemTypes) { if (!allTypes.contains(itemType)) { nextTypes.add(itemType); } writeStart("a", "class", "label reference", "data-typeId", itemType.getId(), "href", page.url(null, "typeId", itemType.getId())); writeHtml(itemType.getDisplayName()); writeEnd(); } } } writeEnd(); writeEnd(); } writeEnd(); writeEnd(); writeEnd(); } writeEnd(); writeEnd(); } currentTypes = nextTypes; writeEnd(); } writeEnd(); includeScript("/_resource/dari/db-schema.js"); endPage(); } }; } }
package io.vertx.ext.web; import io.netty.handler.codec.http.HttpResponseStatus; import io.vertx.core.*; import io.vertx.core.buffer.Buffer; import io.vertx.core.http.*; import io.vertx.core.http.impl.HttpServerRequestInternal; import io.vertx.core.json.JsonObject; import io.vertx.core.net.SocketAddress; import io.vertx.ext.web.handler.BodyHandler; import io.vertx.ext.web.handler.ResponseContentTypeHandler; import io.vertx.ext.web.impl.RoutingContextInternal; import org.junit.Test; import java.io.IOException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import static io.vertx.core.Future.succeededFuture; import static org.junit.Assert.assertNotEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class RouterTest extends WebTestBase { @Test public void testSimpleRoute() throws Exception { router.route().handler(rc -> rc.response().end()); testRequest(HttpMethod.GET, "/", 200, "OK"); } @Test public void testSimpleRoute2() throws Exception { router.route().consumes("json").handler(rc -> rc.response().end()); testRequestWithContentType(HttpMethod.GET, "/foo", "application/json", 200, "OK"); testRequestWithContentType(HttpMethod.GET, "/foo", "application/json", 200, "OK"); testRequestWithContentType(HttpMethod.GET, "/foo", "text/json", 200, "OK"); testRequestWithContentType(HttpMethod.GET, "/foo", "text/html", 415, "Unsupported Media Type"); } @Test public void testConsumesSubtypeWildcard() throws Exception { router.route().consumes("text/*").handler(rc -> rc.response().end()); testRequestWithContentType(HttpMethod.GET, "/foo", "text/html", 200, "OK"); testRequestWithContentType(HttpMethod.GET, "/foo", "text/json", 200, "OK"); testRequestWithContentType(HttpMethod.GET, "/foo", "application/json", 415, "Unsupported Media Type"); } @Test public void testConsumesTopLevelTypeWildcard() throws Exception { router.route().consumes("*/json").handler(rc -> rc.response().end()); testRequestWithContentType(HttpMethod.GET, "/foo", "text/json", 200, "OK"); testRequestWithContentType(HttpMethod.GET, "/foo", "application/json", 200, "OK"); testRequestWithContentType(HttpMethod.GET, "/foo", "application/html", 415, "Unsupported Media Type"); } @Test public void testConsumesAll1() throws Exception { router.route().consumes("*/*").handler(rc -> rc.response().end()); testRequestWithContentType(HttpMethod.GET, "/foo", "application/json", 200, "OK"); testRequestWithContentType(HttpMethod.GET, "/foo", "text/html", 200, "OK"); testRequestWithContentType(HttpMethod.GET, "/foo", "text/html; someparam=12", 200, "OK"); testRequest(HttpMethod.GET, "/foo", 200, "OK"); } @Test public void testConsumesAll2() throws Exception { router.route().consumes("*").handler(rc -> rc.response().end()); testRequestWithContentType(HttpMethod.GET, "/foo", "application/json", 200, "OK"); testRequestWithContentType(HttpMethod.GET, "/foo", "text/html", 200, "OK"); testRequestWithContentType(HttpMethod.GET, "/foo", "text/html; someparam=12", 200, "OK"); testRequest(HttpMethod.GET, "/foo", 200, "OK"); } @Test public void testConsumesCTParamsIgnored() throws Exception { router.route().consumes("text/html").handler(rc -> rc.response().end()); testRequestWithContentType(HttpMethod.GET, "/foo", "text/html; someparam=12", 200, "OK"); } @Test public void testConsumesNoContentType() throws Exception { router.route().consumes("text/html").handler(rc -> rc.response().end()); testRequest(HttpMethod.GET, "/foo", HttpResponseStatus.BAD_REQUEST); } @Test public void testProduces() throws Exception { router.route().produces("text/html").handler(rc -> rc.response().end()); testRequestWithAccepts(HttpMethod.GET, "/foo", "text/html", 200, "OK"); testRequestWithAccepts(HttpMethod.GET, "/foo", "text/json", 406, "Not Acceptable"); testRequestWithAccepts(HttpMethod.GET, "/foo", "something/html", 406, "Not Acceptable"); testRequest(HttpMethod.GET, "/foo", 200, "OK"); } @Test public void testProducesWithParameterKey() throws Exception { router.route().produces("text/html;boo").handler(rc -> rc.response().end()); testRequestWithAccepts(HttpMethod.GET, "/foo", "text/html;boo;itWorks", 200, "OK"); testRequestWithAccepts(HttpMethod.GET, "/foo", "text/html;boo=ya", 200, "OK"); testRequestWithAccepts(HttpMethod.GET, "/foo", "text/html;boo", 200, "OK"); testRequestWithAccepts(HttpMethod.GET, "/foo", "text/html", 406, "Not Acceptable"); testRequestWithAccepts(HttpMethod.GET, "/foo", "*/*", 200, "OK"); } @Test public void testProducesWithParameter() throws Exception { router.route().produces("text/html;boo=ya").handler(rc -> rc.response().end()); testRequestWithAccepts(HttpMethod.GET, "/foo", "text/html;boo=ya", 200, "OK"); testRequestWithAccepts(HttpMethod.GET, "/foo", "text/html;boo", 406, "Not Acceptable"); testRequestWithAccepts(HttpMethod.GET, "/foo", "text/html", 406, "Not Acceptable"); } @Test public void testProducesMultiple() throws Exception { router.route().produces("text/html").produces("application/json").handler(rc -> rc.response().end()); testRequestWithAccepts(HttpMethod.GET, "/foo", "text/html", 200, "OK"); testRequestWithAccepts(HttpMethod.GET, "/foo", "application/json", 200, "OK"); testRequestWithAccepts(HttpMethod.GET, "/foo", "text/json", 406, "Not Acceptable"); testRequestWithAccepts(HttpMethod.GET, "/foo", "something/html", 406, "Not Acceptable"); testRequestWithAccepts(HttpMethod.GET, "/foo", "text/json", 406, "Not Acceptable"); testRequestWithAccepts(HttpMethod.GET, "/foo", "application/blah", 406, "Not Acceptable"); } @Test public void testProducesWithQParameterIgnored() throws Exception { router.route().produces("text/html;q").produces("text/html;q=0.1").handler(rc -> rc.response().end()); testRequestWithAccepts(HttpMethod.GET, "/foo", "text/html", 200, "OK"); testRequestWithAccepts(HttpMethod.GET, "/foo", "text/html;a", 200, "OK"); testRequestWithAccepts(HttpMethod.GET, "/foo", "text/html;q=2", 200, "OK"); testRequest(HttpMethod.GET, "/foo", 200, "OK"); testRequestWithAccepts(HttpMethod.GET, "/foo", "*/*", 200, "OK"); } @Test public void testProducesMissingSlash() throws Exception { // will assume "*/json" router.route().produces("application/json").handler(rc -> { rc.response().setStatusMessage(rc.getAcceptableContentType()); rc.response().end(); }); testRequestWithAccepts(HttpMethod.GET, "/foo", "json", 200, "application/json"); testRequestWithAccepts(HttpMethod.GET, "/foo", "text", 406, "Not Acceptable"); } @Test public void testProducesSubtypeWildcard() throws Exception { router.route().produces("text/html").handler(rc -> { rc.response().setStatusMessage(rc.getAcceptableContentType()); rc.response().end(); }); router.route().produces("text/*").handler(rc -> { rc.response().setStatusMessage(rc.getAcceptableContentType()); rc.response().end(); }); testRequestWithAccepts(HttpMethod.GET, "/foo", "text/plain", 200, "text/plain"); } @Test public void testProducesComponentWildcardAcceptTextPlain() throws Exception { router.route().produces("*/plain").handler(rc -> { rc.response().setStatusMessage(rc.getAcceptableContentType()); rc.response().end(); }); testRequestWithAccepts(HttpMethod.GET, "/foo", "text/plain", 200, "text/plain"); } @Test public void testProducesAllWildcard() throws Exception { router.route().produces("*/*").handler(rc -> { rc.response().setStatusMessage(rc.getAcceptableContentType()); rc.response().end(); }); testRequestWithAccepts(HttpMethod.GET, "/foo", "text/plain", 200, "text/plain"); } @Test public void testProducesTopLevelTypeWildcard() throws Exception { router.route().produces("application/json").handler(rc -> { rc.response().setStatusMessage(rc.getAcceptableContentType()); rc.response().end(); }); testRequestWithAccepts(HttpMethod.GET, "/foo", "*/json", 200, "application/json"); testRequestWithAccepts(HttpMethod.GET, "/foo", "*/html", 406, "Not Acceptable"); } @Test public void testProducesAll1() throws Exception { router.route().produces("application/json").handler(rc -> { rc.response().setStatusMessage(rc.getAcceptableContentType()); rc.response().end(); }); testRequestWithAccepts(HttpMethod.GET, "/foo", "*/*", 200, "application/json"); } @Test public void testProducesAll2() throws Exception { router.route().produces("application/json").handler(rc -> { rc.response().setStatusMessage(rc.getAcceptableContentType()); rc.response().end(); }); testRequestWithAccepts(HttpMethod.GET, "/foo", "*", 200, "application/json"); } @Test public void testAcceptsMultiple1() throws Exception { router.route().produces("application/json").handler(rc -> { rc.response().setStatusMessage(rc.getAcceptableContentType()); rc.response().end(); }); testRequestWithAccepts(HttpMethod.GET, "/foo", "text/html,application/json,text/plain", 200, "application/json"); testRequestWithAccepts(HttpMethod.GET, "/foo", "text/html,application/json;b,text/plain", 200, "application/json"); } @Test public void testAcceptsMultiple2() throws Exception { router.route().produces("application/json").handler(rc -> { rc.response().setStatusMessage(rc.getAcceptableContentType()); rc.response().end(); }); /* This test is for issue #729 and #740 about thread safety and errors of multiple handlers In this test case I try 100 connections in separated worker threads with random delays and old fashion Java sync http client. I've also added a timer when I call routingContext.next() */ @Test public void testMultipleHandlersMultipleConnectionsDelayed() throws Exception { router.get("/path").handler(routingContext -> { routingContext.put("response", "handler1"); routingContext.vertx().setTimer((int) (1 + Math.random() * 10), asyncResult -> routingContext.next()); }).handler(routingContext -> { routingContext.put("response", routingContext.get("response") + "handler2"); routingContext.vertx().setTimer((int) (1 + Math.random() * 10), asyncResult -> routingContext.next()); }).handler(routingContext -> { HttpServerResponse response = routingContext.response(); response.setChunked(true); response.end(routingContext.get("response") + "handler3"); }); CountDownLatch latch = new CountDownLatch(100); for (int i = 0; i < 100; i++) { // using executeBlocking should create multiple connections vertx.executeBlocking(future -> { try { Thread.sleep((int) (1 + Math.random() * 10)); testSyncRequest("GET", "/path", 200, "OK", "handler1handler2handler3"); future.complete(); } catch (Exception e) { future.fail(e); } }, asyncResult -> { assertFalse(asyncResult.failed()); assertNull(asyncResult.cause()); latch.countDown(); }); } awaitLatch(latch); } /* This test is similar to test above but it mixes right and failing requests */ @Test public void testMultipleHandlersMultipleConnectionsDelayedMixed() throws Exception { router.get("/:param").handler(routingContext -> { if (routingContext.pathParam("param").equals("fail")) { routingContext.fail(400); } else { routingContext.put("response", "handler1"); routingContext.vertx().setTimer((int) (1 + Math.random() * 10), asyncResult -> routingContext.next()); } }).failureHandler(routingContext -> { routingContext.put("response", "fhandler1"); routingContext.vertx().setTimer((int) (1 + Math.random() * 10), asyncResult -> routingContext.next()); }).handler(routingContext -> { routingContext.put("response", routingContext.get("response") + "handler2"); routingContext.vertx().setTimer((int) (1 + Math.random() * 10), asyncResult -> routingContext.next()); }).handler(routingContext -> { HttpServerResponse response = routingContext.response(); response.setChunked(true); response.end(routingContext.get("response") + "handler3"); }).failureHandler(routingContext -> { routingContext.put("response", routingContext.get("response") + "fhandler2"); routingContext.vertx().setTimer((int) (1 + Math.random() * 10), asyncResult -> routingContext.next()); }).failureHandler(routingContext -> { HttpServerResponse response = routingContext.response(); response.setChunked(true); response.setStatusMessage("ERROR"); response.setStatusCode(400); response.end(routingContext.get("response") + "fhandler3"); }); final int multipleConnections = 500; CountDownLatch latch = new CountDownLatch(multipleConnections); Handler<Promise<Object>> execute200Request = future -> { try { Thread.sleep((int) (1 + Math.random() * 10)); testSyncRequest("GET", "/path", 200, "OK", "handler1handler2handler3"); future.complete(); } catch (InterruptedException | IOException e) { e.printStackTrace(); future.fail(e); } }; Handler<Promise<Object>> execute400Request = future -> { try { Thread.sleep((int) (1 + Math.random() * 10)); testSyncRequest("GET", "/fail", 400, "ERROR", "fhandler1fhandler2fhandler3"); future.complete(); } catch (InterruptedException | IOException e) { e.printStackTrace(); future.fail(e); } }; for (int i = 0; i < multipleConnections; i++) { // using executeBlocking should create multiple connections vertx.executeBlocking((new Random().nextBoolean() ? execute200Request : execute400Request), false, objectAsyncResult -> { assertTrue(objectAsyncResult.succeeded()); latch.countDown(); }); } awaitLatch(latch); } @Test public void testMultipleSetHandlerMultipleRouteObject() throws Exception { router.get("/path").handler(routingContext -> { routingContext.put("response", "handler1"); routingContext.next(); }); router.get("/path").handler(routingContext -> { routingContext.put("response", routingContext.get("response") + "handler2"); routingContext.next(); }).handler(routingContext -> { HttpServerResponse response = routingContext.response(); response.setChunked(true); response.end(routingContext.get("response") + "handler3"); }); testRequest(HttpMethod.GET, "/path", 200, "OK", "handler1handler2handler3"); } @Test public void testSetRegexGroupsNamesMethod() throws Exception { List<String> groupNames = new ArrayList<>(); groupNames.add("hello"); Route route1 = router.getWithRegex("\\/(?<p0>[a-z]{2})"); route1.setRegexGroupsNames(groupNames); route1.handler(routingContext -> routingContext .response() .setStatusCode(200) .setStatusMessage(routingContext.pathParam("hello")) .end()); testRequest(HttpMethod.GET, "/hi", 200, "hi"); } @Test public void testRegexGroupsNamesWithMethodOverride() throws Exception { List<String> groupNames = new ArrayList<>(); groupNames.add("FirstParam"); groupNames.add("SecondParam"); Route route = router.getWithRegex("\\/([a-z]{2})([a-z]{2})"); route.setRegexGroupsNames(groupNames); route.handler(routingContext -> routingContext .response() .setStatusCode(200) .setStatusMessage(routingContext.pathParam("FirstParam") + "-" + routingContext.pathParam("SecondParam")) .end()); testRequest(HttpMethod.GET, "/aabb", 200, "aa-bb"); } @Test public void testSetRegexGroupsNamesMethodWithUnorderedGroups() throws Exception { List<String> groupNames = new ArrayList<>(); groupNames.add("firstParam"); groupNames.add("secondParam"); Route route1 = router.getWithRegex("\\/(?<p1>[a-z]{2})(?<p0>[a-z]{2})"); route1.setRegexGroupsNames(groupNames); route1.handler(routingContext -> routingContext .response() .setStatusCode(200) .setStatusMessage(routingContext.pathParam("firstParam") + "-" + routingContext.pathParam("secondParam")) .end()); testRequest(HttpMethod.GET, "/bbaa", 200, "aa-bb"); } @Test public void testSetRegexGroupsNamesMethodWithNestedRegex() throws Exception { List<String> groupNames = new ArrayList<>(); groupNames.add("firstParam"); groupNames.add("secondParam"); Route route1 = router.getWithRegex("\\/(?<p1>[a-z]{2}(?<p0>[a-z]{2}))"); route1.setRegexGroupsNames(groupNames); route1.handler(routingContext -> routingContext .response() .setStatusCode(200) .setStatusMessage(routingContext.pathParam("firstParam") + "-" + routingContext.pathParam("secondParam")) .end()); testRequest(HttpMethod.GET, "/bbaa", 200, "aa-bbaa"); } @Test public void testRegexGroupsNames() throws Exception { router.getWithRegex("\\/(?<firstParam>[a-z]{2})(?<secondParam>[a-z]{2})").handler(routingContext -> routingContext .response() .setStatusCode(200) .setStatusMessage(routingContext.pathParam("firstParam") + "-" + routingContext.pathParam("secondParam")) .end()); testRequest(HttpMethod.GET, "/aabb", 200, "aa-bb"); } @Test public void testRegexGroupsNamesWithNestedGroups() throws Exception { router.getWithRegex("\\/(?<secondParam>[a-z]{2}(?<firstParam>[a-z]{2}))").handler(routingContext -> routingContext .response() .setStatusCode(200) .setStatusMessage(routingContext.pathParam("firstParam") + "-" + routingContext.pathParam("secondParam")) .end()); testRequest(HttpMethod.GET, "/bbaa", 200, "aa-bbaa"); } private Handler<RoutingContext> generateHandler(final int i) { return routingContext -> routingContext.put(Integer.toString(i), i).next(); } @Test public void stressTestMultipleHandlers() throws Exception { final int HANDLERS_NUMBER = 100; final int REQUESTS_NUMBER = 200; Route r = router.get("/path"); for (int i = 0; i < HANDLERS_NUMBER; i++) { r.handler(generateHandler(i)); } r.handler(routingContext -> { StringBuilder sum = new StringBuilder(); for (int i = 0; i < HANDLERS_NUMBER; i++) { sum.append((Integer) routingContext.get(Integer.toString(i))); } routingContext.response() .setStatusCode(200) .setStatusMessage("OK") .end(sum.toString()); }); CountDownLatch latch = new CountDownLatch(REQUESTS_NUMBER); final StringBuilder sum = new StringBuilder(); for (int i = 0; i < HANDLERS_NUMBER; i++) { sum.append(i); } for (int i = 0; i < REQUESTS_NUMBER; i++) { // using executeBlocking should create multiple connections vertx.executeBlocking(future -> { try { Thread.sleep((int) (1 + Math.random() * 10)); testSyncRequest("GET", "/path", 200, "OK", sum.toString()); future.complete(); } catch (Exception e) { future.fail(e); } }, asyncResult -> { assertFalse(asyncResult.failed()); assertNull(asyncResult.cause()); latch.countDown(); }); } awaitLatch(latch); } @Test public void testDecodingError() throws Exception { String BAD_PARAM = "~!@\\||$%^&*()_=-%22;;%27%22:%3C%3E/?]}{"; router.route().handler(rc -> { rc.queryParams(); // Trigger decoding rc.next(); }); router.route("/path").handler(rc -> rc.response().setStatusCode(500).end()); testRequest(HttpMethod.GET, "/path?q=" + BAD_PARAM, 400, "Bad Request"); } @Test public void testRoutePathNoSlashBegin() throws Exception { String path = "?test=something"; router.route().handler(rc -> rc.response().end()); testRequest(HttpMethod.GET, path, 400, "Bad Request"); } @Test public void testMultipleHandlersWithFailuresDeadlock() throws Exception { AtomicBoolean first = new AtomicBoolean(true); CountDownLatch firstHandlerLatch = new CountDownLatch(1); CountDownLatch secondHandlerLatch = new CountDownLatch(1); router.get("/path").handler(event -> { if (!first.compareAndSet(true, false)) { // Second run, block until the second handler runs try { firstHandlerLatch.countDown(); awaitLatch(secondHandlerLatch); // Add a small delay so the exception handler happens first Thread.sleep(100); } catch (InterruptedException e) { // ignore } event.next(); } else { vertx.executeBlocking(future -> { event.next(); future.complete(); }, asyncResult -> { }); } }); router.get("/path").handler(event -> { try { awaitLatch(firstHandlerLatch); } catch (InterruptedException e) { // ignore } secondHandlerLatch.countDown(); event.fail(new NullPointerException()); }); CountDownLatch latch = new CountDownLatch(2); for (int i = 0; i < 2; i++) { vertx.executeBlocking(future -> { HttpServerRequest request = mock(HttpServerRequestInternal.class); HttpServerResponse response = mock(HttpServerResponse.class); when(request.method()).thenReturn(HttpMethod.GET); when(request.scheme()).thenReturn("http"); when(request.uri()).thenReturn("http://localhost/path"); when(request.absoluteURI()).thenReturn("http://localhost/path"); when(request.host()).thenReturn("localhost"); when(request.path()).thenReturn("/path"); when(request.response()).thenReturn(response); when(response.ended()).thenReturn(true); router.handle(request); future.complete(); }, false, asyncResult -> { assertFalse(asyncResult.failed()); assertNull(asyncResult.cause()); latch.countDown(); }); } awaitLatch(latch); } @Test public void testCustom404ErrorHandler() throws Exception { // Default 404 handler testRequest(HttpMethod.GET, "/blah", 404, "Not Found", "<html><body><h1>Resource not found</h1></body></html>"); router.errorHandler(404, routingContext -> routingContext .response() .setStatusMessage("Not Found") .setStatusCode(404) .end("Not Found custom error") ); testRequest(HttpMethod.GET, "/blah", 404, "Not Found", "Not Found custom error"); } @Test public void testDecodingErrorCustomHandler() throws Exception { String BAD_PARAM = "~!@\\||$%^&*()_=-%22;;%27%22:%3C%3E/?]}{"; router.errorHandler(400, context -> context.response().setStatusCode(500).setStatusMessage("Dumb").end()); router.route().handler(rc -> { rc.queryParams(); // Trigger decoding rc.next(); }).handler(rc -> { rc.response().setStatusCode(500).end(); }); testRequest(HttpMethod.GET, "/path?q=" + BAD_PARAM, 500, "Dumb"); } @Test public void testCustomErrorHandler() throws Exception { router.route("/path").handler(rc -> rc.fail(410)); router.errorHandler(410, context -> context.response().setStatusCode(500).setStatusMessage("Dumb").end()); testRequest(HttpMethod.GET, "/path", 500, "Dumb"); } @Test public void testErrorInCustomErrorHandler() throws Exception { router.route("/path").handler(rc -> rc.fail(410)); router.errorHandler(410, rc -> { throw new RuntimeException(); }); testRequest(HttpMethod.GET, "/path", 410, "Gone"); } @Test public void testErrorHandlingResponseClosed() throws Exception { CountDownLatch latch = new CountDownLatch(1); client.request(HttpMethod.GET, server.actualPort(), "localhost", "/path").onComplete(onSuccess(req -> { router.route().handler(rc -> { req.connection().close(); rc.response().closeHandler(v -> rc.next()); }); router.route("/path").handler(rc -> rc.response().write("")); router.errorHandler(500, rc -> { assertEquals(1, latch.getCount()); latch.countDown(); }); req.end(); })); latch.await(); } @Test public void testMethodNotAllowedCustomErrorHandler() throws Exception { router.get("/path").handler(rc -> rc.response().end()); router.post("/path").handler(rc -> rc.response().end()); router.errorHandler(405, context -> context.response().setStatusCode(context.statusCode()).setStatusMessage("Dumb").end()); testRequest(HttpMethod.PUT, "/path", 405, "Dumb"); } @Test public void testNotAcceptableCustomErrorHandler() throws Exception { router.route().produces("text/html").handler(rc -> rc.response().end()); router.errorHandler(406, context -> context.response().setStatusCode(context.statusCode()).setStatusMessage("Dumb").end()); testRequestWithAccepts(HttpMethod.GET, "/foo", "something/html", 406, "Dumb"); } @Test public void testUnsupportedMediaTypeCustomErrorHandler() throws Exception { router.route().consumes("text/html").handler(rc -> rc.response().end()); router.errorHandler(415, context -> context.response().setStatusCode(context.statusCode()).setStatusMessage("Dumb").end()); testRequestWithContentType(HttpMethod.GET, "/foo", "something/html", 415, "Dumb"); } @Test public void testMethodNotAllowedStatusCode() throws Exception { router.get("/path").handler(rc -> rc.response().end()); router.post("/path").handler(rc -> rc.response().end()); router.put("/hello").handler(rc -> rc.response().end()); testRequest(HttpMethod.PUT, "/path", HttpResponseStatus.METHOD_NOT_ALLOWED); } @Test public void testNotAcceptableStatusCode() throws Exception { router.route().produces("text/html").handler(rc -> rc.response().end()); router.route("/hello").produces("something/html").handler(rc -> rc.response().end()); testRequestWithAccepts(HttpMethod.GET, "/foo", "something/html", 406, HttpResponseStatus.NOT_ACCEPTABLE.reasonPhrase()); } @Test public void testUnsupportedMediaTypeStatusCode() throws Exception { router.route().consumes("text/html").handler(rc -> rc.response().end()); router.get("/hello").consumes("something/html").handler(rc -> rc.response().end()); testRequestWithContentType(HttpMethod.GET, "/foo", "something/html", 415, HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE.reasonPhrase()); } @Test public void testVHost() throws Exception { router.route().virtualHost("*.com").handler(ctx -> ctx.response().end()); router.route().handler(ctx -> ctx.fail(500)); testRequest(new RequestOptions() .setServer(SocketAddress.inetSocketAddress(8080, "localhost")) .setPort(80) .setHost("www.mysite.com"), req -> { }, 200, "OK", null); } @Test public void testVHostShouldFail() throws Exception { router.route().virtualHost("*.com").handler(ctx -> ctx.response().end()); router.route().handler(ctx -> ctx.fail(500)); testRequest(new RequestOptions() .setServer(SocketAddress.inetSocketAddress(8080, "localhost")) .setPort(80) .setHost("www.mysite.net"), req -> { }, 500, "Internal Server Error", null); } @Test public void testOverlappingRoutes() throws Exception { router.route(HttpMethod.PUT, "/foo/:param1").order(1).handler(routingContext -> { fail("Should not route to PUT"); }); router.route(HttpMethod.GET, "/foo/:param2").order(10).handler(routingContext -> { if (routingContext.pathParam("param1") != null) { fail("Should not have parameter from the other route."); } if (routingContext.pathParam("param2") == null) { fail("Should have parameter from the other route."); } routingContext.response().end("done"); }); testRequest(HttpMethod.GET, "/foo/bar", HttpResponseStatus.OK); } @Test public void testToString() { // Check we can compute toString() without infinite recursion assertNotNull(router.toString()); Route route = router.route("/foo/:param1"); assertNotNull(router.toString()); assertNotNull(route.toString()); } @Test public void testRouteMatching() throws Exception { router.route("/foo/bar/").handler(rc -> rc.response().setStatusMessage("socks").end()); testRequest(HttpMethod.GET, "/foo/bar", 404, "Not Found"); testRequest(HttpMethod.GET, "/foo/bar/", 200, "socks"); testRequest(HttpMethod.GET, "/foo/bar/baz", 404, "Not Found"); testRequest(HttpMethod.GET, "/foo/b", 404, "Not Found"); testRequest(HttpMethod.GET, "/f", 404, "Not Found"); } @Test public void testRouteMatchingUnsupportedMediaType() throws Exception { router.post("/api").consumes("application/json").handler(rc -> rc.response().setStatusMessage("post api").end()); router.put("/api").consumes("application/json").handler(rc -> rc.response().setStatusMessage("put api").end()); testRequestWithContentType(HttpMethod.POST, "/api", "application/json", 200, "post api"); testRequestWithContentType(HttpMethod.POST, "/api", "application/xml", 415, "Unsupported Media Type"); testRequestWithContentType(HttpMethod.PUT, "/api", "application/json", 200, "put api"); testRequestWithContentType(HttpMethod.PUT, "/api", "application/xml", 415, "Unsupported Media Type"); testRequestWithContentType(HttpMethod.PATCH, "/api", "application/json", 405, "Method Not Allowed"); } @Test public void testRouteMatchingUnsupportedMediaTypeOrder() throws Exception { router.put("/api").consumes("application/json").handler(rc -> rc.response().setStatusMessage("put api").end()); router.post("/api").consumes("application/json").handler(rc -> rc.response().setStatusMessage("post api").end()); router.get("/api").handler(rc -> rc.response().setStatusMessage("get api").end()); router.put("/api").consumes("application/xml").handler(rc -> rc.response().setStatusMessage("put api xml").end()); testRequestWithContentType(HttpMethod.POST, "/api", "application/json", 200, "post api"); testRequestWithContentType(HttpMethod.POST, "/api", "application/xml", 415, "Unsupported Media Type"); testRequestWithContentType(HttpMethod.PUT, "/api", "application/json", 200, "put api"); testRequestWithContentType(HttpMethod.PUT, "/api", "application/xml", 200, "put api xml"); testRequestWithContentType(HttpMethod.PATCH, "/api", "application/json", 405, "Method Not Allowed"); } @Test public void testRouteMatchingSupportedMediaTypes() throws Exception { router.post("/api").consumes("application/json").handler(rc -> rc.response().setStatusMessage("post api").end()); router.post("/api").consumes("application/xml").handler(rc -> rc.response().setStatusMessage("post api xml").end()); router.put("/api").consumes("application/json").handler(rc -> rc.response().setStatusMessage("put api").end()); router.put("/api").consumes("application/xml").handler(rc -> rc.response().setStatusMessage("put api xml").end()); testRequestWithContentType(HttpMethod.POST, "/api", "application/json", 200, "post api"); testRequestWithContentType(HttpMethod.POST, "/api", "application/xml", 200, "post api xml"); testRequestWithContentType(HttpMethod.PUT, "/api", "application/json", 200, "put api"); testRequestWithContentType(HttpMethod.PUT, "/api", "application/xml", 200, "put api xml"); testRequestWithContentType(HttpMethod.PATCH, "/api", "application/json", 405, "Method Not Allowed"); } @Test public void testRouteCustomVerb() throws Exception { router .route() .method(HttpMethod.valueOf("MKCOL")) .handler(rc -> rc.response().setStatusMessage("socks").end()); testRequest(HttpMethod.MKCOL, "/", 200, "socks"); } @Test public void testStatusCodeUncatchedException() throws Exception { Route route1 = router.get("/somepath/path1"); route1.handler(ctx -> { // Let's say this throws a RuntimeException throw new RuntimeException("something happened!"); }); // Define a failure handler // This will get called for any failures in the above handlers
package com.intellij.psi.impl.source; import com.intellij.extapi.psi.StubBasedPsiElementBase; import com.intellij.ide.startup.FileContent; import com.intellij.ide.util.EditSourceUtil; import com.intellij.lang.ASTFactory; import com.intellij.lang.ASTNode; import com.intellij.lang.Language; import com.intellij.navigation.ItemPresentation; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vcs.FileStatus; import com.intellij.openapi.vcs.FileStatusManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileWithId; import com.intellij.psi.*; import com.intellij.psi.impl.*; import com.intellij.psi.impl.cache.impl.CacheUtil; import com.intellij.psi.impl.file.PsiFileImplUtil; import com.intellij.psi.impl.source.codeStyle.CodeEditUtil; import com.intellij.psi.impl.source.parsing.ChameleonTransforming; import com.intellij.psi.impl.source.resolve.FileContextUtil; import com.intellij.psi.impl.source.tree.*; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.PsiElementProcessor; import com.intellij.psi.search.SearchScope; import com.intellij.psi.stubs.*; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.IStubFileElementType; import com.intellij.util.CharTable; import com.intellij.util.IncorrectOperationException; import com.intellij.util.PatchedSoftReference; import com.intellij.util.PatchedWeakReference; import com.intellij.util.indexing.FileBasedIndex; import com.intellij.util.text.CharArrayUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; public abstract class PsiFileImpl extends ElementBase implements PsiFileEx, PsiFileWithStubSupport { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.PsiFileImpl"); private IElementType myElementType; protected IElementType myContentElementType; protected PsiFile myOriginalFile = null; private final FileViewProvider myViewProvider; private static final Key<Document> HARD_REFERENCE_TO_DOCUMENT = new Key<Document>("HARD_REFERENCE_TO_DOCUMENT"); private final Object myStubLock = PsiLock.LOCK; private WeakReference<StubTree> myStub; protected final PsiManagerEx myManager; private volatile Object myTreeElementPointer; // SoftReference/WeakReference to RepositoryTreeElement when has repository id, RepositoryTreeElement otherwise public static final Key<Boolean> BUILDING_STUB = new Key<Boolean>("Don't use stubs mark!"); protected PsiFileImpl(@NotNull IElementType elementType, IElementType contentElementType, @NotNull FileViewProvider provider) { this(provider); init(elementType, contentElementType); } protected PsiFileImpl(@NotNull FileViewProvider provider ) { myManager = (PsiManagerEx)provider.getManager(); myViewProvider = provider; } public void setContentElementType(final IElementType contentElementType) { myContentElementType = contentElementType; } public IElementType getContentElementType() { return myContentElementType; } protected void init(@NotNull final IElementType elementType, final IElementType contentElementType) { myElementType = elementType; myContentElementType = contentElementType; } public TreeElement createContentLeafElement(final CharSequence text, final int startOffset, final int endOffset, final CharTable table) { return ASTFactory.leaf(myContentElementType, text, startOffset, endOffset, table); } public boolean isDirectory() { return false; } public FileElement getTreeElement() { final FileElement noLockAttempt = (FileElement)_getTreeElement(); if (noLockAttempt != null) return noLockAttempt; synchronized (myStubLock) { return getTreeElementNoLock(); } } public FileElement getTreeElementNoLock() { if (!getViewProvider().isPhysical() && _getTreeElement() == null) { setTreeElement(loadTreeElement()); } return (FileElement)_getTreeElement(); } protected boolean isKeepTreeElementByHardReference() { return !getViewProvider().isEventSystemEnabled(); } private ASTNode _getTreeElement() { final Object pointer = myTreeElementPointer; if (pointer instanceof FileElement) { return (FileElement)pointer; } else if (pointer instanceof Reference) { FileElement treeElement = (FileElement)((Reference)pointer).get(); if (treeElement != null) return treeElement; synchronized (myStubLock) { if (myTreeElementPointer == pointer) { myTreeElementPointer = null; } } } return null; } public VirtualFile getVirtualFile() { return getViewProvider().isEventSystemEnabled() ? getViewProvider().getVirtualFile() : null; } public boolean processChildren(final PsiElementProcessor<PsiFileSystemItem> processor) { return true; } public boolean isValid() { if (!getViewProvider().isPhysical()) return true; // "dummy" file final VirtualFile vFile = getViewProvider().getVirtualFile(); return vFile.isValid() && isPsiUpToDate(vFile); } protected boolean isPsiUpToDate(VirtualFile vFile) { final FileViewProvider provider = myManager.findViewProvider(vFile); return provider.getPsi(getLanguage()) == this || provider.getPsi(provider.getBaseLanguage()) == this; } public boolean isContentsLoaded() { return _getTreeElement() != null; } public FileElement loadTreeElement() { synchronized (myStubLock) { FileElement treeElement = (FileElement)_getTreeElement(); if (treeElement != null) return treeElement; final FileViewProvider viewProvider = getViewProvider(); if (viewProvider.isPhysical() && myManager.isAssertOnFileLoading(viewProvider.getVirtualFile())) { LOG.error("Access to tree elements not allowed in tests." + viewProvider.getVirtualFile().getPresentableUrl()); } // load document outside lock for better performance final Document document = viewProvider.isEventSystemEnabled() ? viewProvider.getDocument() : null; //synchronized (PsiLock.LOCK) { treeElement = createFileElement(viewProvider.getContents()); if (document != null) { treeElement.putUserData(HARD_REFERENCE_TO_DOCUMENT, document); } setTreeElement(treeElement); treeElement.setPsi(this); StubTree stub = derefStub(); if (stub != null) { final Iterator<StubElement<?>> stubs = stub.getPlainList().iterator(); stubs.next(); // Skip file stub; switchFromStubToAST(treeElement, stubs); myStub = null; } if (getViewProvider().isEventSystemEnabled()) { ((PsiDocumentManagerImpl)PsiDocumentManager.getInstance(myManager.getProject())).contentsLoaded(this); } if (LOG.isDebugEnabled() && getViewProvider().isPhysical()) { LOG.debug("Loaded text for file " + getViewProvider().getVirtualFile().getPresentableUrl()); } return treeElement; } } public ASTNode findTreeForStub(StubTree tree, StubElement<?> stub) { final Iterator<StubElement<?>> stubs = tree.getPlainList().iterator(); final StubElement<?> root = stubs.next(); final CompositeElement ast = calcTreeElement(); if (root == stub) return ast; return findTreeForStub(ast, stubs, stub); } private static ASTNode findTreeForStub(ASTNode tree, final Iterator<StubElement<?>> stubs, final StubElement stub) { if (tree instanceof ChameleonElement) { tree = ChameleonTransforming.transform((ChameleonElement)tree); } final IElementType type = tree.getElementType(); if (type instanceof IStubElementType && ((IStubElementType) type).shouldCreateStub(tree)) { final StubElement curStub = stubs.next(); if (curStub == stub) return tree; } for (ASTNode node : tree.getChildren(null)) { final ASTNode treeForStub = findTreeForStub(node, stubs, stub); if (treeForStub != null) return treeForStub; } return null; } private void switchFromStubToAST(ASTNode tree, Iterator<StubElement<?>> stubs) { if (tree instanceof ChameleonElement) { tree = ChameleonTransforming.transform((ChameleonElement)tree); } final IElementType type = tree.getElementType(); if (type instanceof IStubElementType && ((IStubElementType) type).shouldCreateStub(tree)) { final StubElement stub = stubs.next(); if (stub.getStubType() != tree.getElementType()) { rebuildStub(); assert false: "Stub and PSI element type mismatch in " + getName() + ": stub " + stub + ", AST " + tree.getElementType(); } final PsiElement psi = stub.getPsi(); ((CompositeElement)tree).setPsi(psi); final StubBasedPsiElementBase<?> base = (StubBasedPsiElementBase)psi; base.setNode(tree); base.setStub(null); if (LOG.isDebugEnabled()) { LOG.debug("Bound " + base + " to " + stub); } } for (ASTNode node : tree.getChildren(null)) { switchFromStubToAST(node, stubs); } } protected FileElement createFileElement(final CharSequence docText) { final CompositeElement xxx = ASTFactory.composite(myElementType); if (!(xxx instanceof FileElement)) { LOG.error("BUMM!"); } final FileElement treeElement = (FileElement)xxx; if (CacheUtil.isCopy(this)) { treeElement.setCharTable(new IdentityCharTable()); } TreeElement contentElement = createContentLeafElement(docText, 0, docText.length(), treeElement.getCharTable()); TreeUtil.addChildren(treeElement, contentElement); return treeElement; } public void unloadContent() { LOG.assertTrue(getTreeElement() != null); clearCaches(); myViewProvider.beforeContentsSynchronized(); setTreeElement(null); synchronized (myStubLock) { myStub = null; } } public void clearCaches() {} public String getText() { return getViewProvider().getContents().toString(); } public int getTextLength() { final ASTNode tree = _getTreeElement(); if (tree != null) return tree.getTextLength(); return getViewProvider().getContents().length(); } public TextRange getTextRange() { return new TextRange(0, getTextLength()); } public PsiElement getNextSibling() { return SharedPsiElementImplUtil.getNextSibling(this); } public PsiElement getPrevSibling() { return SharedPsiElementImplUtil.getPrevSibling(this); } public long getModificationStamp() { return getViewProvider().getModificationStamp(); } public void subtreeChanged() { doClearCaches(); getViewProvider().rootChanged(this); } private void doClearCaches() { final FileElement tree = getTreeElement(); if (tree != null) { myTreeElementPointer = tree; tree.clearCaches(); tree.putUserData(STUB_TREE_IN_PARSED_TREE, null); } synchronized (myStubLock) { myStub = null; } clearCaches(); } @SuppressWarnings({"CloneDoesntDeclareCloneNotSupportedException", "CloneDoesntCallSuperClone"}) protected PsiFileImpl clone() { FileViewProvider provider = getViewProvider().clone(); final Language language = getLanguage(); PsiFileImpl clone = (PsiFileImpl)provider.getPsi(language); assert clone != null:"Cannot find psi file with language:"+language + " from viewprovider:"+provider+" virtual file:"+getVirtualFile(); copyCopyableDataTo(clone); if (getTreeElement() != null) { // not set by provider in clone final FileElement treeClone = (FileElement)calcTreeElement().clone(); clone.myTreeElementPointer = treeClone; // should not use setTreeElement here because cloned file still have VirtualFile (SCR17963) treeClone.setPsi(clone); } if (getViewProvider().isEventSystemEnabled()) { clone.myOriginalFile = this; } else if (myOriginalFile != null) { clone.myOriginalFile = myOriginalFile; } return clone; } @NotNull public String getName() { return getViewProvider().getVirtualFile().getName(); } public PsiElement setName(@NotNull String name) throws IncorrectOperationException { checkSetName(name); doClearCaches(); return PsiFileImplUtil.setName(this, name); } public void checkSetName(String name) throws IncorrectOperationException { if (!getViewProvider().isEventSystemEnabled()) return; PsiFileImplUtil.checkSetName(this, name); } public boolean isWritable() { return getViewProvider().getVirtualFile().isWritable() && !CacheUtil.isCopy(this); } public PsiDirectory getParent() { return getContainingDirectory(); } public PsiDirectory getContainingDirectory() { final VirtualFile parentFile = getViewProvider().getVirtualFile().getParent(); if (parentFile == null) return null; return getManager().findDirectory(parentFile); } public PsiFile getContainingFile() { return this; } public void delete() throws IncorrectOperationException { checkDelete(); PsiFileImplUtil.doDelete(this); } public void checkDelete() throws IncorrectOperationException { if (!getViewProvider().isEventSystemEnabled()) { throw new IncorrectOperationException(); } CheckUtil.checkWritable(this); } public PsiFile getOriginalFile() { return myOriginalFile; } public void setOriginalFile(final PsiFile originalFile) { if (originalFile.getOriginalFile() != null) { myOriginalFile = originalFile.getOriginalFile(); } else { myOriginalFile = originalFile; } } @NotNull public PsiFile[] getPsiRoots() { final FileViewProvider viewProvider = getViewProvider(); final Set<Language> languages = viewProvider.getLanguages(); final PsiFile[] roots = new PsiFile[languages.size()]; int i = 0; for (Language language : languages) { roots[i++] = viewProvider.getPsi(language); } return roots; } public boolean isPhysical() { // TODO[ik] remove this shit with dummy file system return getViewProvider().isEventSystemEnabled(); } @NotNull public Language getLanguage() { return myElementType.getLanguage(); } @NotNull public FileViewProvider getViewProvider() { return myViewProvider; } public void setTreeElementPointer(FileElement element) { myTreeElementPointer = element; } public PsiElement findElementAt(int offset) { return getViewProvider().findElementAt(offset); } public PsiReference findReferenceAt(int offset) { return getViewProvider().findReferenceAt(offset); } @NotNull public char[] textToCharArray() { return CharArrayUtil.fromSequenceStrict(getViewProvider().getContents()); } @NotNull protected <T> T[] findChildrenByClass(Class<T> aClass) { List<T> result = new ArrayList<T>(); for (PsiElement child : getChildren()) { if (aClass.isInstance(child)) result.add((T)child); } return result.toArray((T[]) Array.newInstance(aClass, result.size())); } @Nullable protected <T> T findChildByClass(Class<T> aClass) { for (PsiElement child : getChildren()) { if (aClass.isInstance(child)) return (T)child; } return null; } public boolean isTemplateDataFile() { return false; } public PsiElement getContext() { return FileContextUtil.getFileContext(this); } public void onContentReload() { subtreeChanged(); // important! otherwise cached information is not released if (isContentsLoaded()) { unloadContent(); } } public PsiFile cacheCopy(final FileContent content) { if (isContentsLoaded()) { return this; } else { CharSequence text; if (content == null) { Document document = FileDocumentManager.getInstance().getDocument(getVirtualFile()); text = document.getCharsSequence(); } else { text = CacheUtil.getContentText(content); } FileType fileType = getFileType(); final String name = getName(); PsiFile fileCopy = PsiFileFactory.getInstance(getProject()).createFileFromText(name, fileType, text, getModificationStamp(), false, false); fileCopy.putUserData(CacheUtil.CACHE_COPY_KEY, Boolean.TRUE); ((PsiFileImpl)fileCopy).setOriginalFile(this); return fileCopy; } } @Nullable public StubElement getStub() { StubTree stubHolder = getStubTree(); return stubHolder != null ? stubHolder.getRoot() : null; } @Nullable public StubTree getStubTree() { ApplicationManager.getApplication().assertReadAccessAllowed(); if (Boolean.TRUE.equals(getUserData(BUILDING_STUB))) return null; final StubTree derefd = derefStub(); if (derefd != null) return derefd; if (getTreeElementNoLock() != null) return null; final VirtualFile vFile = getVirtualFile(); if (!(vFile instanceof VirtualFileWithId)) return null; StubTree stubHolder = StubTree.readFromVFile(vFile); if (stubHolder == null) return null; synchronized (myStubLock) { if (getTreeElementNoLock() != null) return null; final StubTree derefdOnLock = derefStub(); if (derefdOnLock != null) return derefdOnLock; myStub = new WeakReference<StubTree>(stubHolder); StubBase<PsiFile> base = (StubBase)stubHolder.getRoot(); base.setPsi(this); return derefStub(); } } @Nullable private StubTree derefStub() { synchronized (myStubLock) { return myStub != null ? myStub.get() : null; } } protected PsiFileImpl cloneImpl(FileElement treeElementClone) { PsiFileImpl clone = (PsiFileImpl)super.clone(); clone.myTreeElementPointer = treeElementClone; // should not use setTreeElement here because cloned file still have VirtualFile (SCR17963) treeElementClone.setPsi(clone); return clone; } private void setTreeElement(ASTNode treeElement){ Object newPointer; if (treeElement == null) { newPointer = null; } else if (isKeepTreeElementByHardReference()) { newPointer = treeElement; } else { newPointer = myManager.isBatchFilesProcessingMode() ? new PatchedWeakReference<ASTNode>(treeElement) : new PatchedSoftReference<ASTNode>(treeElement); } synchronized (myStubLock) { myTreeElementPointer = newPointer; } } public Object getStubLock() { return myStubLock; } public PsiManager getManager() { return myManager; } public PsiElement getNavigationElement() { return this; } public PsiElement getOriginalElement() { return this; } public final CompositeElement calcTreeElement() { // Attempt to find (loaded) tree element without taking lock first. FileElement treeElement = getTreeElement(); if (treeElement != null) return treeElement; synchronized (myStubLock) { treeElement = getTreeElement(); if (treeElement != null) return treeElement; return loadTreeElement(); } } @NotNull public PsiElement[] getChildren() { return calcTreeElement().getChildrenAsPsiElements(null, PsiElementArrayConstructor.PSI_ELEMENT_ARRAY_CONSTRUCTOR); } public PsiElement getFirstChild() { return SharedImplUtil.getFirstChild(calcTreeElement()); } public PsiElement getLastChild() { return SharedImplUtil.getLastChild(calcTreeElement()); } public void acceptChildren(@NotNull PsiElementVisitor visitor) { CompositeElement treeElement = calcTreeElement(); TreeElement childNode = treeElement.getFirstChildNode(); TreeElement prevSibling = null; while (childNode != null) { if (childNode instanceof ChameleonElement) { TreeElement newChild = (TreeElement)childNode.getTransformedFirstOrSelf(); if (newChild == null) { childNode = prevSibling == null ? treeElement.getFirstChildNode() : prevSibling.getTreeNext(); continue; } childNode = newChild; } final PsiElement psi; if (childNode instanceof PsiElement) { psi = (PsiElement)childNode; } else { psi = childNode.getPsi(); } psi.accept(visitor); prevSibling = childNode; childNode = childNode.getTreeNext(); } } public int getStartOffsetInParent() { return calcTreeElement().getStartOffsetInParent(); } public int getTextOffset() { return calcTreeElement().getTextOffset(); } public boolean textMatches(@NotNull CharSequence text) { return calcTreeElement().textMatches(text); } public boolean textMatches(@NotNull PsiElement element) { return calcTreeElement().textMatches(element); } public boolean textContains(char c) { return calcTreeElement().textContains(c); } public final PsiElement copy() { return clone(); } public PsiElement add(@NotNull PsiElement element) throws IncorrectOperationException { CheckUtil.checkWritable(this); TreeElement elementCopy = ChangeUtil.copyToElement(element); calcTreeElement().addInternal(elementCopy, elementCopy, null, null); elementCopy = ChangeUtil.decodeInformation(elementCopy); return SourceTreeToPsiMap.treeElementToPsi(elementCopy); } public PsiElement addBefore(@NotNull PsiElement element, PsiElement anchor) throws IncorrectOperationException { CheckUtil.checkWritable(this); TreeElement elementCopy = ChangeUtil.copyToElement(element); calcTreeElement().addInternal(elementCopy, elementCopy, SourceTreeToPsiMap.psiElementToTree(anchor), Boolean.TRUE); elementCopy = ChangeUtil.decodeInformation(elementCopy); return SourceTreeToPsiMap.treeElementToPsi(elementCopy); } public PsiElement addAfter(@NotNull PsiElement element, PsiElement anchor) throws IncorrectOperationException { CheckUtil.checkWritable(this); TreeElement elementCopy = ChangeUtil.copyToElement(element); calcTreeElement().addInternal(elementCopy, elementCopy, SourceTreeToPsiMap.psiElementToTree(anchor), Boolean.FALSE); elementCopy = ChangeUtil.decodeInformation(elementCopy); return SourceTreeToPsiMap.treeElementToPsi(elementCopy); } public final void checkAdd(@NotNull PsiElement element) throws IncorrectOperationException { CheckUtil.checkWritable(this); } public PsiElement addRange(PsiElement first, PsiElement last) throws IncorrectOperationException { return SharedImplUtil.addRange(this, first, last, null, null); } public PsiElement addRangeBefore(@NotNull PsiElement first, @NotNull PsiElement last, PsiElement anchor) throws IncorrectOperationException { return SharedImplUtil.addRange(this, first, last, SourceTreeToPsiMap.psiElementToTree(anchor), Boolean.TRUE); } public PsiElement addRangeAfter(PsiElement first, PsiElement last, PsiElement anchor) throws IncorrectOperationException { return SharedImplUtil.addRange(this, first, last, SourceTreeToPsiMap.psiElementToTree(anchor), Boolean.FALSE); } public void deleteChildRange(PsiElement first, PsiElement last) throws IncorrectOperationException { CheckUtil.checkWritable(this); if (first == null) { LOG.assertTrue(last == null); return; } ASTNode firstElement = SourceTreeToPsiMap.psiElementToTree(first); ASTNode lastElement = SourceTreeToPsiMap.psiElementToTree(last); CompositeElement treeElement = calcTreeElement(); LOG.assertTrue(firstElement.getTreeParent() == treeElement); LOG.assertTrue(lastElement.getTreeParent() == treeElement); CodeEditUtil.removeChildren(treeElement, firstElement, lastElement); } public PsiElement replace(@NotNull PsiElement newElement) throws IncorrectOperationException { CompositeElement treeElement = calcTreeElement(); LOG.assertTrue(treeElement.getTreeParent() != null); CheckUtil.checkWritable(this); TreeElement elementCopy = ChangeUtil.copyToElement(newElement); treeElement.getTreeParent().replaceChildInternal(treeElement, elementCopy); elementCopy = ChangeUtil.decodeInformation(elementCopy); return SourceTreeToPsiMap.treeElementToPsi(elementCopy); } public PsiReference getReference() { return null; } @NotNull public PsiReference[] getReferences() { return SharedPsiElementImplUtil.getReferences(this); } public boolean processDeclarations(@NotNull PsiScopeProcessor processor, @NotNull ResolveState state, PsiElement lastParent, @NotNull PsiElement place) { return true; } @NotNull public GlobalSearchScope getResolveScope() { return ((PsiManagerEx)getManager()).getFileManager().getResolveScope(this); } @NotNull public SearchScope getUseScope() { return ((PsiManagerEx) getManager()).getFileManager().getUseScope(this); } public ItemPresentation getPresentation() { return new ItemPresentation() { public String getPresentableText() { return getName(); } public String getLocationString() { final PsiDirectory psiDirectory = getParent(); if (psiDirectory != null) { return psiDirectory.getVirtualFile().getPresentableUrl(); } return null; } public Icon getIcon(final boolean open) { return PsiFileImpl.this.getIcon(open ? ICON_FLAG_OPEN : ICON_FLAG_CLOSED); } public TextAttributesKey getTextAttributesKey() { return null; } }; } public void navigate(boolean requestFocus) { EditSourceUtil.getDescriptor(this).navigate(requestFocus); } public boolean canNavigate() { return EditSourceUtil.canNavigate(this); } public boolean canNavigateToSource() { return canNavigate(); } public FileStatus getFileStatus() { if (!isPhysical()) return FileStatus.NOT_CHANGED; PsiFile contFile = getContainingFile(); if (contFile == null) return FileStatus.NOT_CHANGED; VirtualFile vFile = contFile.getVirtualFile(); return vFile != null ? FileStatusManager.getInstance(getProject()).getStatus(vFile) : FileStatus.NOT_CHANGED; } @NotNull public Project getProject() { final PsiManager manager = getManager(); if (manager == null) throw new PsiInvalidElementAccessException(this); return manager.getProject(); } public ASTNode getNode() { return calcTreeElement(); } public boolean isEquivalentTo(final PsiElement another) { return this == another; } private static final Key<StubTree> STUB_TREE_IN_PARSED_TREE = new Key<StubTree>("STUB_TREE_IN_PARSED_TREE"); public StubTree calcStubTree() { synchronized (myStubLock) { final FileElement fileElement = (FileElement)calcTreeElement(); StubTree tree = fileElement.getUserData(STUB_TREE_IN_PARSED_TREE); if (tree == null) { final StubElement currentStubTree = ((IStubFileElementType)getContentElementType()).getBuilder().buildStubTree(this); tree = new StubTree((PsiFileStub)currentStubTree); bindFakeStubsToTree(tree); fileElement.putUserData(STUB_TREE_IN_PARSED_TREE, tree); } return tree; } } private void bindFakeStubsToTree(StubTree stubTree) { final PsiFileImpl file = this; final Iterator<StubElement<?>> stubs = stubTree.getPlainList().iterator(); stubs.next(); // skip file root stub final FileElement fileRoot = file.getTreeElement(); assert fileRoot != null; bindStubs(fileRoot, stubs); } @Nullable private StubElement bindStubs(ASTNode tree, Iterator<StubElement<?>> stubs) { if (tree instanceof ChameleonElement) { tree = ChameleonTransforming.transform((ChameleonElement)tree); } final IElementType type = tree.getElementType(); if (type instanceof IStubElementType && ((IStubElementType) type).shouldCreateStub(tree)) { final StubElement stub = stubs.next(); if (stub.getStubType() != tree.getElementType()) { rebuildStub(); assert false: "Stub and PSI element type mismatch: stub " + stub + ", AST " + tree.getElementType(); } ((StubBase)stub).setPsi(tree.getPsi()); } for (ASTNode node : tree.getChildren(null)) { final StubElement res = bindStubs(node, stubs); if (res != null) { return res; } } return null; } private void rebuildStub() { final VirtualFile vFile = getVirtualFile(); if (vFile != null && vFile.isValid()) { ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { final Document doc = FileDocumentManager.getInstance().getCachedDocument(vFile); if (doc != null) { FileDocumentManager.getInstance().saveDocument(doc); } } }, ModalityState.NON_MODAL); FileBasedIndex.getInstance().requestReindex(vFile); } } }