answer
stringlengths
17
10.2M
package org.amc.game.chess; import org.amc.game.chess.ChessBoard.ChessPieceLocation; import org.amc.game.chess.ChessBoard.Coordinate; import java.util.ArrayList; import java.util.List; /** * Contains the Rules of Chess * * @author Adrian Mclaughlin * */ public class ChessGame { private ChessBoard board; private Player currentPlayer; private Player playerOne; private Player playerTwo; List<ChessRule> chessRules; public ChessGame(ChessBoard board, Player playerOne, Player playerTwo) { this.board = board; this.playerOne = playerOne; this.playerTwo = playerTwo; this.currentPlayer = this.playerOne; chessRules=new ArrayList<>(); chessRules.add(new EnPassantRule()); chessRules.add(new CastlingRule()); } public Player getCurrentPlayer() { return currentPlayer; } /** * Changes the current player */ public void changePlayer() { if (currentPlayer.equals(playerOne)) { currentPlayer = playerTwo; } else { currentPlayer = playerOne; } } /** * Move a ChessPiece from one square to another as long as the move is valid * * @param player * Player making the move * @param move * Move * @throws InvalidMoveException * if not a valid movement */ public void move(Player player, Move move)throws InvalidMoveException{ ChessPiece piece = board.getPieceFromBoardAt(move.getStart()); if (piece == null) { throw new InvalidMoveException("No piece at " + move.getStart()); } else if (notPlayersChessPiece(player, piece)) { throw new InvalidMoveException("Player can only move their own pieces"); } else if(isPlayersKingInCheck(player, board)){ if(piece.isValidMove(board, move)){ thenMoveChessPiece(player,move); }else{ throw new InvalidMoveException("Not a valid move"); } }else if(doesAGameRuleApply(board, move)){ thenApplyGameRule(player, move); }else if(piece.isValidMove(board, move)){ thenMoveChessPiece(player,move); }else{ throw new InvalidMoveException("Not a valid move"); } } private void thenApplyGameRule(Player player,Move move) throws InvalidMoveException{ for(ChessRule rule:chessRules){ rule.applyRule(board, move); if(isPlayersKingInCheck(player, board)){ rule.unapplyRule(board, move); throw new InvalidMoveException("King is checked"); } } } private void thenMoveChessPiece(Player player,Move move) throws InvalidMoveException{ ReversibleMove reversible=new ReversibleMove(board, move); reversible.move(); if(isPlayersKingInCheck(player, board)){ reversible.undoMove(); throw new InvalidMoveException("King is checked"); } } /** * Return true if the Player owns the chess piece * @param player * @param piece * @return boolean */ private boolean notPlayersChessPiece(Player player,ChessPiece piece){ return player.getColour() != piece.getColour(); } /** * Checks to see if the game has reached it's completion * * @param playerOne * @param playerTwo * @return Boolean */ boolean isGameOver(Player playerOne, Player playerTwo) { boolean playerOneHaveTheirKing = doesThePlayerStillHaveTheirKing(playerOne); boolean playerTwoHaveTheirKing = doesThePlayerStillHaveTheirKing(playerTwo); if (!playerOneHaveTheirKing) { playerTwo.isWinner(true); return true; } else if (!playerTwoHaveTheirKing) { playerOne.isWinner(true); return true; } else { return false; } } /** * Checks to see if the Player still possesses their King * * @param player * @return false if they lost their King ChessPiece */ boolean doesThePlayerStillHaveTheirKing(Player player) { List<ChessPiece> allPlayersChessPieces = getAllPlayersChessPiecesOnTheBoard(player); for (ChessPiece piece : allPlayersChessPieces) { if (piece.getClass().equals(KingPiece.class)) { return true; } } return false; } /** * creates a List of all the Player's pieces still on the board * * @param player * @return List of ChessPieces */ List<ChessPiece> getAllPlayersChessPiecesOnTheBoard(Player player) { List<ChessPiece> pieceList = new ArrayList<ChessPiece>(); for (Coordinate letter : Coordinate.values()) { for (int i = 1; i <= 8; i++) { ChessPiece piece = board.getPieceFromBoardAt(letter.getName(), i); if (piece == null) { continue; } else { if (piece.getColour().equals(player.getColour())) { pieceList.add(piece); } } } } return pieceList; } /** * Checks to see if the opponent's ChessPieces are attacking the Player's king * @param player Player who King might be under attack * @param board ChessBoard current ChessBoard * @return Boolean true if the opponent can capture the Player's king on the next turn */ boolean isPlayersKingInCheck(Player player,ChessBoard board){ Location playersKingLocation=board.getPlayersKingLocation(player); List<ChessPieceLocation> listOfEnemysPieces=board.getListOfPlayersPiecesOnTheBoard(player==playerOne?playerTwo:playerOne); for(ChessPieceLocation pieceLocation:listOfEnemysPieces){ Move move=new Move(pieceLocation.getLocation(),playersKingLocation); if(pieceLocation.getPiece().isValidMove(board, move)){ return true; } } return false; } /** * Checks to see if a game rule applies to the Player's move * Only applies one rule per move * @param board * @param move * @return Boolean true if a Game rule applies to the Player's move */ boolean doesAGameRuleApply(ChessBoard board, Move move){ for(ChessRule rule:chessRules){ if(rule.isRuleApplicable(board, move)){ return true; } } return false; } void setGameRules(List<ChessRule> rules){ this.chessRules=rules; } void setChessBoard(ChessBoard board){ this.board=board; } }
package org.asteriskjava.lock; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import org.asteriskjava.pbx.agi.RateLimiter; import org.asteriskjava.pbx.util.LogTime; import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; public class Locker { private static final Log logger = LogFactory.getLog(Locker.class); private static volatile boolean diags = false; private static ScheduledFuture< ? > future; private static final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); private static final Object sync = new Object(); // keep references to Lockables so they can't be garbage collected between // reporting intervals private static final Map<Long, Lockable> keepList = new HashMap<>(); private static final RateLimiter waitRateLimiter = new RateLimiter(4); public static LockCloser doWithLock(final Lockable lockable) { try { if (diags) { synchronized (sync) { keepList.put(lockable.getLockableId(), lockable); } return lockWithDiags(lockable); } return simpleLock(lockable); } catch (Exception e) { throw new RuntimeException(e); } } /** * determine the caller to Locker * * @param lockable * @return */ static String getCaller(Lockable lockable) { StackTraceElement[] trace = new Exception().getStackTrace(); String name = lockable.getClass().getCanonicalName(); for (StackTraceElement element : trace) { if (element.getFileName() != null && !element.getFileName().contains(Locker.class.getSimpleName())) { name = element.getFileName() + " " + element.getMethodName() + " " + element.getLineNumber() + " " + element.getClassName(); break; } } return name; } public interface LockCloser extends AutoCloseable { public void close(); } // Once every ten seconds max private static RateLimiter warnRateLimiter = new RateLimiter(0.1); private static LockCloser simpleLock(Lockable lockable) throws InterruptedException { LogTime acquireTimer = new LogTime(); ReentrantLock lock = lockable.getInternalLock(); lock.lock(); // lock acquired! if (acquireTimer.timeTaken() > 1_000 && warnRateLimiter.tryAcquire()) { logger.warn("Locks are being held for to long, you can enable lock diagnostics by calling Locker.enable()"); } LogTime holdTimer = new LogTime(); return () -> { lock.unlock(); if (holdTimer.timeTaken() > 500 && warnRateLimiter.tryAcquire()) { logger.warn("Locks are being held for to long, you can enable lock diagnostics by calling Locker.enable()"); } }; } private static LockCloser lockWithDiags(Lockable lockable) throws InterruptedException { int offset = lockable.addLockRequested(); long waitStart = System.currentTimeMillis(); ReentrantLock lock = lockable.getInternalLock(); while (!lock.tryLock(100, TimeUnit.MILLISECONDS)) { if (!lockable.isLockDumped() && lockable.getDumpRateLimit().tryAcquire()) { lockable.setLockDumped(true); dumpThread(lockable.threadHoldingLock.get(), "Waiting on lock... blocked by... id:" + lockable.getLockableId()); } else { if (waitRateLimiter.tryAcquire()) { long elapsed = System.currentTimeMillis() - waitStart; logger.warn("waiting " + elapsed + "(MS) id:" + lockable.getLockableId()); } } lockable.setLockBlocked(true); } lockable.setLockDumped(false); lockable.addLockAcquired(1); long acquiredAt = System.currentTimeMillis(); lockable.threadHoldingLock.set(Thread.currentThread()); return new LockCloser() { @Override public void close() { // ignore any wait that may have been caused by Locker code, so // count the waiters before we release the lock long waiters = lockable.getLockRequested() - offset; lockable.addLockWaited((int) waiters); boolean dumped = lockable.isLockDumped(); // release the lock lock.unlock(); // count the time waiting and holding the lock int holdTime = (int) (System.currentTimeMillis() - acquiredAt); int waitTime = (int) (acquiredAt - waitStart); lockable.addLockTotalWaitTime(waitTime); lockable.addLockTotalHoldTime(holdTime); long averageHoldTime = lockable.getLockAverageHoldTime(); if ((waiters > 0 && holdTime > averageHoldTime * 2) || dumped) { // some threads waited String message = "Lock held for (" + holdTime + "MS), " + waiters + " threads waited for some of that time! " + getCaller(lockable) + " id:" + lockable.getLockableId(); logger.warn(message); if (holdTime > averageHoldTime * 10.0 || dumped) { Exception trace = new Exception(message); logger.error(trace, trace); } } if (holdTime > averageHoldTime * 5.0) { // long hold! String message = "Lock hold of lock (" + holdTime + "MS), average is " + lockable.getLockAverageHoldTime() + " " + getCaller(lockable) + " id:" + lockable.getLockableId(); logger.warn(message); if (holdTime > averageHoldTime * 10.0) { Exception trace = new Exception(message); logger.error(trace, trace); } } } }; } public static void dumpThread(Thread thread, String message) { if (thread != null) { StackTraceElement[] trace = thread.getStackTrace(); String dump = ""; int i = 0; for (; i < trace.length; i++) { StackTraceElement ste = trace[i]; dump += "\tat " + ste.toString(); dump += '\n'; } logger.error(message); logger.error(dump); } else { logger.error("Thread hasn't been set: " + message); } } /** * start dumping lock stats once per minute, can't be stopped once started. */ public static void enable() { synchronized (sync) { if (!diags) { diags = true; future = executor.scheduleWithFixedDelay(() -> { dumpStats(); }, 1, 1, TimeUnit.MINUTES); logger.warn("Lock checking enabled"); } else { logger.warn("Already enabled"); } } } public static void disable() { synchronized (sync) { if (diags) { diags = false; future.cancel(false); dumpStats(); logger.warn("Lock checking disabled"); } else { logger.warn("Lock checking is already disabled"); } } } private static volatile boolean first = true; static void dumpStats() { List<Lockable> lockables = new LinkedList<>(); synchronized (sync) { lockables.addAll(keepList.values()); keepList.clear(); } boolean activity = false; for (Lockable lockable : lockables) { if (lockable.wasLockBlocked()) { int waited = lockable.getLockWaited(); int waitTime = lockable.getLockTotalWaitTime(); int acquired = lockable.getLockAcquired(); int holdTime = lockable.getLockTotalHoldTime(); lockable.setLockBlocked(false); activity = true; logger.warn(lockable.asLockString()); lockable.addLockWaited(-waited); lockable.addLockTotalWaitTime(-waitTime); lockable.addLockAcquired(-acquired); lockable.addLockTotalHoldTime(-holdTime); } } if (first || activity) { logger.warn("Will dump Lock stats each minute when there is contention..."); first = false; } } }
package org.codice.nitf; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; import difflib.Delta; import difflib.DiffUtils; import difflib.Patch; import org.codice.nitf.filereader.FileType; import org.codice.nitf.filereader.ImageCompression; import org.codice.nitf.filereader.ImageCoordinatePair; import org.codice.nitf.filereader.ImageCoordinatesRepresentation; import org.codice.nitf.filereader.NitfDataExtensionSegment; import org.codice.nitf.filereader.NitfFile; import org.codice.nitf.filereader.NitfImageSegment; import org.codice.nitf.filereader.NitfSecurityClassification; import org.codice.nitf.filereader.RasterProductFormatUtilities; import org.codice.nitf.filereader.Tre; import org.codice.nitf.filereader.TreCollection; import org.codice.nitf.filereader.TreEntry; import org.codice.nitf.filereader.TreGroup; public class FileComparer { static final String OUR_OUTPUT_EXTENSION = ".OURS.txt"; static final String THEIR_OUTPUT_EXTENSION = ".THEIRS.txt"; private String filename = null; private NitfFile nitf = null; private NitfImageSegment segment1 = null; private NitfDataExtensionSegment des1 = null; private BufferedWriter out = null; FileComparer(String fileName) { filename = fileName; generateGdalMetadata(); generateOurMetadata(); compareMetadataFiles(); } private void generateOurMetadata() { try { nitf = new NitfFile(); nitf.parse(new FileInputStream(filename)); } catch (ParseException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } if (nitf.getNumberOfImageSegments() >= 1) { segment1 = nitf.getImageSegment(1); } if (nitf.getNumberOfDataExtensionSegments() >= 1) { des1 = nitf.getDataExtensionSegment(1); } outputData(); } private void outputData() { try { FileWriter fstream = new FileWriter(filename + OUR_OUTPUT_EXTENSION); out = new BufferedWriter(fstream); out.write("Driver: NITF/National Imagery Transmission Format\n"); out.write("Files: " + filename + "\n"); if (segment1 == null) { out.write(String.format("Size is 1, 1\n")); } else { out.write(String.format("Size is %d, %d\n", segment1.getNumberOfColumns(), segment1.getNumberOfRows())); } outputCoordinateSystem(); outputBaseMetadata(); outputTRExml(); outputImageStructure(); outputSubdatasets(); outputRPCs(); out.close(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } } private void outputCoordinateSystem() throws IOException { boolean haveRPC = false; if (segment1 != null) { TreCollection treCollection = segment1.getTREsRawStructure(); for (Tre tre : treCollection.getTREs()) { if (tre.getName().equals("RPC00B")) { haveRPC = true; } } } if (segment1 == null) { out.write("Coordinate System is `'\n"); } else if (segment1.getImageCoordinatesRepresentation() == ImageCoordinatesRepresentation.UTMUPSNORTH) { out.write("Coordinate System is:\n"); out.write("PROJCS[\"unnamed\",\n"); out.write(" GEOGCS[\"WGS 84\",\n"); out.write(" DATUM[\"WGS_1984\",\n"); out.write(" SPHEROID[\"WGS 84\",6378137,298.257223563,\n"); out.write(" AUTHORITY[\"EPSG\",\"7030\"]],\n"); out.write(" TOWGS84[0,0,0,0,0,0,0],\n"); out.write(" AUTHORITY[\"EPSG\",\"6326\"]],\n"); out.write(" PRIMEM[\"Greenwich\",0,\n"); out.write(" AUTHORITY[\"EPSG\",\"8901\"]],\n"); out.write(" UNIT[\"degree\",0.0174532925199433,\n"); out.write(" AUTHORITY[\"EPSG\",\"9108\"]],\n"); out.write(" AUTHORITY[\"EPSG\",\"4326\"]],\n"); out.write(" PROJECTION[\"Transverse_Mercator\"],\n"); out.write(" PARAMETER[\"latitude_of_origin\",-0],\n"); out.write(" PARAMETER[\"central_meridian\",33],\n"); out.write(" PARAMETER[\"scale_factor\",0.9996],\n"); out.write(" PARAMETER[\"false_easting\",500000],\n"); out.write(" PARAMETER[\"false_northing\",0]]\n"); } else if (haveRPC || (segment1.getImageCoordinatesRepresentation() == ImageCoordinatesRepresentation.NONE)) { out.write("Coordinate System is `'\n"); } else { out.write("Coordinate System is:\n"); out.write("GEOGCS[\"WGS 84\",\n"); out.write(" DATUM[\"WGS_1984\",\n"); out.write(" SPHEROID[\"WGS 84\",6378137,298.257223563,\n"); out.write(" AUTHORITY[\"EPSG\",\"7030\"]],\n"); out.write(" TOWGS84[0,0,0,0,0,0,0],\n"); out.write(" AUTHORITY[\"EPSG\",\"6326\"]],\n"); out.write(" PRIMEM[\"Greenwich\",0,\n"); out.write(" AUTHORITY[\"EPSG\",\"8901\"]],\n"); out.write(" UNIT[\"degree\",0.0174532925199433,\n"); out.write(" AUTHORITY[\"EPSG\",\"9108\"]],\n"); out.write(" AUTHORITY[\"EPSG\",\"4326\"]]\n"); } } private void outputBaseMetadata() throws IOException, ParseException { RasterProductFormatUtilities rpfUtils = new RasterProductFormatUtilities(); TreeMap <String, String> metadata = new TreeMap<String, String>(); metadata.put("NITF_CLEVEL", String.format("%02d", nitf.getComplexityLevel())); metadata.put("NITF_ENCRYP", "0"); switch (nitf.getFileType()) { case NSIF_ONE_ZERO: metadata.put("NITF_FHDR", "NSIF01.00"); break; case NITF_TWO_ZERO: metadata.put("NITF_FHDR", "NITF02.00"); break; case NITF_TWO_ONE: metadata.put("NITF_FHDR", "NITF02.10"); break; } metadata.put("NITF_FSCAUT", nitf.getFileSecurityMetadata().getClassificationAuthority()); metadata.put("NITF_FSCLAS", nitf.getFileSecurityMetadata().getSecurityClassification().getTextEquivalent()); metadata.put("NITF_FSCODE", nitf.getFileSecurityMetadata().getCodewords()); metadata.put("NITF_FSCTLH", nitf.getFileSecurityMetadata().getControlAndHandling()); metadata.put("NITF_FSCTLN", nitf.getFileSecurityMetadata().getSecurityControlNumber()); metadata.put("NITF_FSREL", nitf.getFileSecurityMetadata().getReleaseInstructions()); if (nitf.getFileType() == FileType.NITF_TWO_ZERO) { metadata.put("NITF_FDT", new SimpleDateFormat("ddHHmmss'Z'MMMyy").format(nitf.getFileDateTime()).toString().toUpperCase()); metadata.put("NITF_FSDWNG", nitf.getFileSecurityMetadata().getDowngradeDateOrSpecialCase().trim()); if (nitf.getFileSecurityMetadata().getDowngradeEvent() != null) { metadata.put("NITF_FSDEVT", nitf.getFileSecurityMetadata().getDowngradeEvent()); } } else { metadata.put("NITF_FBKGC", (String.format("%3d,%3d,%3d", (int)(nitf.getFileBackgroundColour().getRed() & 0xFF), (int)(nitf.getFileBackgroundColour().getGreen() & 0xFF), (int)(nitf.getFileBackgroundColour().getBlue() & 0xFF)))); metadata.put("NITF_FDT", new SimpleDateFormat("yyyyMMddHHmmss").format(nitf.getFileDateTime())); metadata.put("NITF_FSCATP", nitf.getFileSecurityMetadata().getClassificationAuthorityType()); metadata.put("NITF_FSCLSY", nitf.getFileSecurityMetadata().getSecurityClassificationSystem()); metadata.put("NITF_FSCLTX", nitf.getFileSecurityMetadata().getClassificationText()); metadata.put("NITF_FSCRSN", nitf.getFileSecurityMetadata().getClassificationReason()); metadata.put("NITF_FSDCDT", nitf.getFileSecurityMetadata().getDeclassificationDate()); metadata.put("NITF_FSDCTP", nitf.getFileSecurityMetadata().getDeclassificationType()); if (nitf.getFileSecurityMetadata().getDeclassificationExemption().length() > 0) { metadata.put("NITF_FSDCXM", String.format("%4s", nitf.getFileSecurityMetadata().getDeclassificationExemption())); } else { metadata.put("NITF_FSDCXM", ""); } metadata.put("NITF_FSDG", nitf.getFileSecurityMetadata().getDowngrade()); metadata.put("NITF_FSDGDT", nitf.getFileSecurityMetadata().getDowngradeDate()); metadata.put("NITF_FSSRDT", nitf.getFileSecurityMetadata().getSecuritySourceDate()); } metadata.put("NITF_FSCOP", nitf.getFileSecurityMetadata().getFileCopyNumber()); metadata.put("NITF_FSCPYS", nitf.getFileSecurityMetadata().getFileNumberOfCopies()); metadata.put("NITF_FTITLE", nitf.getFileTitle()); metadata.put("NITF_ONAME", nitf.getOriginatorsName()); metadata.put("NITF_OPHONE", nitf.getOriginatorsPhoneNumber()); metadata.put("NITF_OSTAID", nitf.getOriginatingStationId()); metadata.put("NITF_STYPE", nitf.getStandardType()); TreCollection treCollection = nitf.getTREsRawStructure(); addOldStyleMetadata(metadata, treCollection); if (segment1 != null) { metadata.put("NITF_ABPP", String.format("%02d", segment1.getActualBitsPerPixelPerBand())); metadata.put("NITF_CCS_COLUMN", String.format("%d", segment1.getImageLocationColumn())); metadata.put("NITF_CCS_ROW", String.format("%d", segment1.getImageLocationRow())); metadata.put("NITF_IALVL", String.format("%d", segment1.getImageAttachmentLevel())); metadata.put("NITF_IC", segment1.getImageCompression().getTextEquivalent()); metadata.put("NITF_ICAT", segment1.getImageCategory().getTextEquivalent()); if (nitf.getFileType() == FileType.NITF_TWO_ZERO) { metadata.put("NITF_IDATIM", new SimpleDateFormat("ddHHmmss'Z'MMMyy").format(segment1.getImageDateTime()).toString().toUpperCase()); metadata.put("NITF_ICORDS", segment1.getImageCoordinatesRepresentation().getTextEquivalent(nitf.getFileType())); } else { metadata.put("NITF_IDATIM", new SimpleDateFormat("yyyyMMddHHmmss").format(segment1.getImageDateTime())); if (segment1.getImageCoordinatesRepresentation() == ImageCoordinatesRepresentation.NONE) { metadata.put("NITF_ICORDS", ""); } else { metadata.put("NITF_ICORDS", segment1.getImageCoordinatesRepresentation().getTextEquivalent(nitf.getFileType())); } } metadata.put("NITF_IDLVL", String.format("%d", segment1.getImageDisplayLevel())); if (segment1.getImageCoordinatesRepresentation() != ImageCoordinatesRepresentation.NONE) { metadata.put("NITF_IGEOLO", String.format("%s%s%s%s", segment1.getImageCoordinates().getCoordinate00().getSourceFormat(), segment1.getImageCoordinates().getCoordinate0MaxCol().getSourceFormat(), segment1.getImageCoordinates().getCoordinateMaxRowMaxCol().getSourceFormat(), segment1.getImageCoordinates().getCoordinateMaxRow0().getSourceFormat())); } metadata.put("NITF_IID1", segment1.getImageIdentifier1()); if (nitf.getFileType() == FileType.NITF_TWO_ZERO) { metadata.put("NITF_ITITLE", segment1.getImageIdentifier2()); } else { metadata.put("NITF_IID2", segment1.getImageIdentifier2()); } String rpfAbbreviation = rpfUtils.getAbbreviationForFileName(segment1.getImageIdentifier2()); if (rpfAbbreviation != null) { metadata.put("NITF_SERIES_ABBREVIATION", rpfAbbreviation); } String rpfName = rpfUtils.getNameForFileName(segment1.getImageIdentifier2()); if (rpfName != null) { metadata.put("NITF_SERIES_NAME", rpfName); } metadata.put("NITF_ILOC_COLUMN", String.format("%d", segment1.getImageLocationColumn())); metadata.put("NITF_ILOC_ROW", String.format("%d", segment1.getImageLocationRow())); metadata.put("NITF_IMAG", segment1.getImageMagnification()); if (segment1.getNumberOfImageComments() > 0) { StringBuilder commentBuilder = new StringBuilder(); for (int i = 0; i < segment1.getNumberOfImageComments(); ++i) { commentBuilder.append(String.format("%-80s", segment1.getImageCommentZeroBase(i))); } metadata.put("NITF_IMAGE_COMMENTS", commentBuilder.toString()); } metadata.put("NITF_IMODE", segment1.getImageMode().getTextEquivalent()); metadata.put("NITF_IREP", segment1.getImageRepresentation().getTextEquivalent()); metadata.put("NITF_ISCAUT", segment1.getSecurityMetadata().getClassificationAuthority()); metadata.put("NITF_ISCLAS", segment1.getSecurityMetadata().getSecurityClassification().getTextEquivalent()); metadata.put("NITF_ISCODE", segment1.getSecurityMetadata().getCodewords()); metadata.put("NITF_ISCTLH", segment1.getSecurityMetadata().getControlAndHandling()); metadata.put("NITF_ISCTLN", segment1.getSecurityMetadata().getSecurityControlNumber()); if (nitf.getFileType() == FileType.NITF_TWO_ZERO) { metadata.put("NITF_ISDWNG", segment1.getSecurityMetadata().getDowngradeDateOrSpecialCase().trim()); if (segment1.getSecurityMetadata().getDowngradeEvent() != null) { metadata.put("NITF_ISDEVT", segment1.getSecurityMetadata().getDowngradeEvent()); } } else { metadata.put("NITF_ISCATP", segment1.getSecurityMetadata().getClassificationAuthorityType()); metadata.put("NITF_ISCLSY", segment1.getSecurityMetadata().getSecurityClassificationSystem()); metadata.put("NITF_ISCLTX", segment1.getSecurityMetadata().getClassificationText()); metadata.put("NITF_ISDCDT", segment1.getSecurityMetadata().getDeclassificationDate()); metadata.put("NITF_ISDCTP", segment1.getSecurityMetadata().getDeclassificationType()); metadata.put("NITF_ISCRSN", segment1.getSecurityMetadata().getClassificationReason()); if ((segment1.getSecurityMetadata().getDeclassificationExemption() != null) && (segment1.getSecurityMetadata().getDeclassificationExemption().length() > 0)) { metadata.put("NITF_ISDCXM", String.format("%4s", segment1.getSecurityMetadata().getDeclassificationExemption())); } else { metadata.put("NITF_ISDCXM", ""); } metadata.put("NITF_ISDG", segment1.getSecurityMetadata().getDowngrade()); metadata.put("NITF_ISDGDT", segment1.getSecurityMetadata().getDowngradeDate()); metadata.put("NITF_ISSRDT", segment1.getSecurityMetadata().getSecuritySourceDate()); } metadata.put("NITF_ISORCE", segment1.getImageSource()); metadata.put("NITF_ISREL", segment1.getSecurityMetadata().getReleaseInstructions()); metadata.put("NITF_PJUST", segment1.getPixelJustification().getTextEquivalent()); metadata.put("NITF_PVTYPE", segment1.getPixelValueType().getTextEquivalent()); if (segment1.getImageTargetId().length() > 0) { metadata.put("NITF_TGTID", segment1.getImageTargetId()); } else { metadata.put("NITF_TGTID", ""); } treCollection = segment1.getTREsRawStructure(); addOldStyleMetadata(metadata, treCollection); } out.write("Metadata:\n"); for (String key : metadata.keySet()) { out.write(String.format(" %s=%s\n", key, metadata.get(key))); } } private void outputImageStructure() throws IOException { if (segment1 != null) { switch (segment1.getImageCompression()) { case JPEG: case JPEGMASK: out.write("Image Structure Metadata:\n"); out.write(" COMPRESSION=JPEG\n"); break; case BILEVEL: case BILEVELMASK: case DOWNSAMPLEDJPEG: out.write("Image Structure Metadata:\n"); out.write(" COMPRESSION=BILEVEL\n"); break; case LOSSLESSJPEG: out.write("Image Structure Metadata:\n"); out.write(" COMPRESSION=LOSSLESS JPEG\n"); break; case JPEG2000: case JPEG2000MASK: out.write("Image Structure Metadata:\n"); out.write(" COMPRESSION=JPEG2000\n"); break; case VECTORQUANTIZATION: case VECTORQUANTIZATIONMASK: out.write("Image Structure Metadata:\n"); out.write(" COMPRESSION=VECTOR QUANTIZATION\n"); break; } } } private void outputSubdatasets() throws IOException { if (nitf.getNumberOfImageSegments() > 1) { out.write("Subdatasets:\n"); for (int i = 0; i < nitf.getNumberOfImageSegments(); ++i) { out.write(String.format(" SUBDATASET_%d_NAME=NITF_IM:%d:%s\n", i+1, i, filename)); out.write(String.format(" SUBDATASET_%d_DESC=Image %d of %s\n", i+1, i+1, filename)); } } } private void outputTRExml() throws IOException { if ((nitf.getTREsRawStructure().hasTREs()) || ((segment1 != null) && (segment1.getTREsRawStructure().hasTREs())) || ((des1 != null) && (des1.getTREsRawStructure().hasTREs()))) { out.write("Metadata (xml:TRE):\n"); out.write("<tres>\n"); TreCollection treCollection = nitf.getTREsRawStructure(); for (Tre tre : treCollection.getTREs()) { outputThisTre(out, tre, "file"); } if (segment1 != null) { treCollection = segment1.getTREsRawStructure(); for (Tre tre : treCollection.getTREs()) { outputThisTre(out, tre, "image"); } } if (des1 != null) { treCollection = des1.getTREsRawStructure(); for (Tre tre : treCollection.getTREs()) { outputThisTre(out, tre, "des TRE_OVERFLOW"); } } out.write("</tres>\n\n"); } } private void outputRPCs() throws IOException { TreeMap <String, String> rpc = new TreeMap<String, String>(); if (segment1 != null) { // Walk the segment1 TRE collection and add RPC entries here TreCollection treCollection = segment1.getTREsRawStructure(); for (Tre tre : treCollection.getTREs()) { if (tre.getName().equals("RPC00B")) { for (TreEntry entry : tre.getEntries()) { if (entry.getName().equals("SUCCESS")) { continue; } if (entry.getName().equals("ERR_BIAS") || entry.getName().equals("ERR_RAND")) { continue; } if (entry.getFieldValue() != null) { if (entry.getName().equals("LONG_OFF") || entry.getName().equals("LONG_SCALE") || entry.getName().equals("LAT_OFF") || entry.getName().equals("LAT_SCALE")) { // skip this, we're filtering it out for both cases } else { Integer rpcValue = Integer.parseInt(entry.getFieldValue()); rpc.put(entry.getName(), rpcValue.toString()); } } else if ((entry.getGroups() != null) && (entry.getGroups().size() > 0)) { StringBuilder builder = new StringBuilder(); for (TreGroup group : entry.getGroups()) { for (TreEntry groupEntry : group.getEntries()) { try { double fieldVal = Double.parseDouble(groupEntry.getFieldValue()); builder.append(cleanupNumberString(fieldVal)); builder.append(" "); } catch (NumberFormatException e) { builder.append(String.format("%s ", groupEntry.getFieldValue())); } } } // These are too sensitive to number formatting issues, and we're already checking // the value in the real TRE. // rpc.put(entry.getName(), builder.toString()); } } try { double longOff = Double.parseDouble(tre.getFieldValue("LONG_OFF")); double longScale = Double.parseDouble(tre.getFieldValue("LONG_SCALE")); double longMin = longOff - (longScale / 2.0); double longMax = longOff + (longScale / 2.0); rpc.put("MAX_LONG", cleanupNumberString(longMax)); rpc.put("MIN_LONG", cleanupNumberString(longMin)); double latOff = Double.parseDouble(tre.getFieldValue("LAT_OFF")); double latScale = Double.parseDouble(tre.getFieldValue("LAT_SCALE")); double latMin = latOff - (latScale / 2.0); double latMax = latOff + (latScale / 2.0); rpc.put("MAX_LAT", cleanupNumberString(latMax)); rpc.put("MIN_LAT", cleanupNumberString(latMin)); } catch (ParseException e) { e.printStackTrace(); } } } } if (rpc.keySet().size() > 0) { out.write("RPC Metadata:\n"); for (String tagname : rpc.keySet()) { out.write(String.format(" %s=%s\n", tagname, rpc.get(tagname))); } } } static private String cleanupNumberString(double fieldVal) { if (fieldVal == (int)fieldVal) { return String.format("%d", (int)fieldVal); } String naiveString = String.format("%.12g", fieldVal); if (naiveString.contains("e-")) { return naiveString.replaceAll("\\.?0*e", "e"); } else if (naiveString.contains(".")) { return naiveString.replaceAll("\\.?0*$", ""); } return naiveString; } private static void addOldStyleMetadata(TreeMap <String, String> metadata, TreCollection treCollection) { for (Tre tre : treCollection.getTREs()) { if (tre.getPrefix() != null) { // if it has a prefix, its probably an old-style NITF metadata field List<TreEntry> entries = tre.getEntries(); for (TreEntry entry: entries) { metadata.put(tre.getPrefix() + entry.getName(), rightTrim(entry.getFieldValue())); } } else if ("ICHIPB".equals(tre.getName())) { // special case List<TreEntry> entries = tre.getEntries(); for (TreEntry entry: entries) { if ("XFRM_FLAG".equals(entry.getName())) { // GDAL skips this one continue; } BigDecimal value = new BigDecimal(entry.getFieldValue().trim()).stripTrailingZeros(); if ("ANAMRPH_CORR".equals(entry.getName())) { // Special case for GDAL metadata.put("ICHIP_ANAMORPH_CORR", value.toPlainString()); } else { metadata.put("ICHIP_" + entry.getName(), value.toPlainString()); } } } } } private static void outputThisTre(BufferedWriter out, Tre tre, String location) throws IOException { doIndent(out, 1); out.write("<tre name=\"" + tre.getName().trim() + "\" location=\"" + location + "\">\n"); for (TreEntry entry : tre.getEntries()) { outputThisEntry(out, entry, 2); } doIndent(out, 1); out.write("</tre>\n"); } private static void outputThisEntry(BufferedWriter out, TreEntry entry, int indentLevel) throws IOException { if (entry.getFieldValue() != null) { doIndent(out, indentLevel); out.write("<field name=\"" + entry.getName() + "\" value=\"" + rightTrim(entry.getFieldValue()) + "\" />\n"); } if ((entry.getGroups() != null) && (entry.getGroups().size() > 0)) { doIndent(out, indentLevel); out.write("<repeated name=\"" + entry.getName() + "\" number=\"" + entry.getGroups().size() + "\">\n"); int i = 0; for (TreGroup group : entry.getGroups()) { doIndent(out, indentLevel + 1); out.write(String.format("<group index=\"%d\">\n", i)); for (TreEntry groupEntry : group.getEntries()) { outputThisEntry(out, groupEntry, indentLevel + 2); } doIndent(out, indentLevel + 1); out.write(String.format("</group>\n")); i = i + 1; } doIndent(out, indentLevel); out.write("</repeated>\n"); } } private static String rightTrim(final String s) { int i = s.length() - 1; while ((i >= 0) && Character.isWhitespace(s.charAt(i))) { i } return s.substring(0, i + 1); } private static void doIndent(BufferedWriter out, int indentLevel) throws IOException { for (int i = 0; i < indentLevel; ++i) { out.write(" "); } } // This is ugly - feel free to fix it any time. private static String makeGeoString(ImageCoordinatePair coords) { double latitude = coords.getLatitude(); double longitude = coords.getLongitude(); String northSouth = "N"; if (latitude < 0.0) { northSouth = "S"; latitude = Math.abs(latitude); } String eastWest = "E"; if (longitude < 0.0) { eastWest = "W"; longitude = Math.abs(longitude); } int latDegrees = (int)Math.floor(latitude); double minutesAndSecondsPart = (latitude -latDegrees) * 60; int latMinutes = (int)Math.floor(minutesAndSecondsPart); double secondsPart = (minutesAndSecondsPart - latMinutes) * 60; int latSeconds = (int)Math.round(secondsPart); if (latSeconds == 60) { latMinutes++; latSeconds = 0; } if (latMinutes == 60) { latDegrees++; latMinutes = 0; } int lonDegrees = (int)Math.floor(longitude); minutesAndSecondsPart = (longitude - lonDegrees) * 60; int lonMinutes = (int)Math.floor(minutesAndSecondsPart); secondsPart = (minutesAndSecondsPart - lonMinutes) * 60; int lonSeconds = (int)Math.round(secondsPart); if (lonSeconds == 60) { lonMinutes++; lonSeconds = 0; } if (lonMinutes == 60) { lonDegrees++; lonMinutes = 0; } return String.format("%02d%02d%02d%s%03d%02d%02d%s", latDegrees, latMinutes, latSeconds, northSouth, lonDegrees, lonMinutes, lonSeconds, eastWest); } private void generateGdalMetadata() { try { ProcessBuilder processBuilder = new ProcessBuilder("gdalinfo", "-nogcp", "-mdd", "xml:TRE", filename); processBuilder.environment().put("NITF_OPEN_UNDERLYING_DS", "NO"); Process process = processBuilder.start(); BufferedWriter out = null; try { FileWriter fstream = new FileWriter(filename + THEIR_OUTPUT_EXTENSION); out = new BufferedWriter(fstream); } catch (IOException e) { e.printStackTrace(); } BufferedReader infoOutputReader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"), 1000000); boolean done = false; try { do { do { String line = infoOutputReader.readLine(); if (line == null) { done = true; break; } if (line.startsWith("Origin = (")) { // System.out.println("Filtering on Origin"); continue; } if (line.startsWith("Pixel Size = (")) { // System.out.println("Filtering on Pixel Size"); continue; } if (line.startsWith(" LINE_DEN_COEFF=") || line.startsWith(" LINE_NUM_COEFF=") || line.startsWith(" SAMP_DEN_COEFF=") || line.startsWith(" SAMP_NUM_COEFF=")) { // System.out.println("Filtering out RPC coefficients"); continue; } if (line.startsWith(" LAT_SCALE=") || line.startsWith(" LONG_SCALE=") || line.startsWith(" LAT_OFF=") || line.startsWith(" LONG_OFF=")) { // System.out.println("Filtering out RPC coefficients"); continue; } if (line.startsWith("Corner Coordinates:")) { // System.out.println("Exiting on Corner Coordinates"); done = true; break; } if (line.startsWith("Band 1 Block=")) { // System.out.println("Exiting on Band 1 Block"); done = true; break; } out.write(line + "\n"); } while (infoOutputReader.ready() && (!done)); Thread.sleep(100); } while (!done); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } out.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private void compareMetadataFiles() { List<String> theirs = fileToLines(filename + THEIR_OUTPUT_EXTENSION); List<String> ours = fileToLines(filename + OUR_OUTPUT_EXTENSION); Patch patch = DiffUtils.diff(theirs, ours); if (patch.getDeltas().size() > 0) { for (Delta delta: patch.getDeltas()) { System.out.println(delta); } System.out.println(" * Done"); } else { new File(filename + THEIR_OUTPUT_EXTENSION).delete(); new File(filename + OUR_OUTPUT_EXTENSION).delete(); } } private static List<String> fileToLines(String filename) { List<String> lines = new LinkedList<String>(); String line = ""; try { BufferedReader in = new BufferedReader(new FileReader(filename)); while ((line = in.readLine()) != null) { lines.add(line); } } catch (IOException e) { e.printStackTrace(); } return lines; } }
package org.jboss.threads; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.concurrent.Executor; import java.util.concurrent.RejectedExecutionException; import org.jboss.logging.Logger; /** * A task which depends on other tasks, and which may have tasks depending upon it. Such a task is automatically * run when using a provided executor when all its dependencies are satisfied. */ public final class Dependency { private static final Logger log = Logger.getLogger(Dependency.class); private static final AtomicIntegerFieldUpdater<Dependency> depUpdater = AtomicIntegerFieldUpdater.newUpdater(Dependency.class, "remainingDependencies"); /** * Number of dependencies left before this task can start. */ @SuppressWarnings({ "UnusedDeclaration" }) private volatile int remainingDependencies; private final Executor executor; private final Object lock = new Object(); private Runner runner; private State state; Dependency(final Executor executor, final Runnable runnable, final int initialDepCount) { this.executor = executor; synchronized (lock) { runner = new Runner(runnable); state = State.WAITING; remainingDependencies = initialDepCount; } } void addDependent(Dependency task) { synchronized (lock) { switch (state) { case WAITING: case RUNNING: runner.dependents.add(task); return; case FAILED: return; case DONE: break; // fall out of lock default: throw new IllegalStateException(); } } task.dependencyFinished(); } void dependencyFinished() { final AtomicIntegerFieldUpdater<Dependency> updater = depUpdater; final int res = updater.decrementAndGet(this); if (res == 0) { final Dependency.Runner runner = this.runner; synchronized (lock) { try { executor.execute(runner); state = State.RUNNING; } catch (RejectedExecutionException e) { log.errorf(e, "Error submitting task %s to executor", runner.runnable); state = State.FAILED; // clear stuff out since this object will likely be kept alive longer than these objects need to be runner.runnable = null; runner.dependents = null; this.runner = null; } } } else if (res < 0) { // oops? updater.incrementAndGet(this); } } private void dependencyFailed() { final AtomicIntegerFieldUpdater<Dependency> updater = depUpdater; final int res = updater.decrementAndGet(this); synchronized (lock) { state = State.FAILED; final Dependency.Runner runner = this.runner; // clear stuff out since this object will likely be kept alive longer than these objects need to be runner.runnable = null; runner.dependents = null; this.runner = null; } if (res < 0) { // oops? updater.incrementAndGet(this); } } private class Runner implements Runnable { private List<Dependency> dependents = new ArrayList<Dependency>(); private Runnable runnable; public Runner(final Runnable runnable) { this.runnable = runnable; } public void run() { boolean ok = false; CTH.set(Dependency.this); try { runnable.run(); ok = true; } finally { CTH.set(null); final List<Dependency> tasks; synchronized (lock) { tasks = dependents; // clear stuff out in case some stupid executor holds on to the runnable dependents = null; runnable = null; runner = null; state = ok ? State.DONE : State.FAILED; } if (ok) { for (Dependency task : tasks) { task.dependencyFinished(); } } else { for (Dependency task : tasks) { task.dependencyFailed(); } } } } } private enum State { /** * Waiting for dependencies to be resolved. */ WAITING, /** * Now running. */ RUNNING, /** * Execution failed. */ FAILED, /** * Execution completed. */ DONE, } /** * Get the dependency task which this thread is currently running. This may be used to add dependencies on the currently * running task. * * @return the currently running task, or {@code null} if the current thread is not running a dependency task */ public static Dependency currentTask() { return CTH.get(); } private static final ThreadLocal<Dependency> CTH = new ThreadLocal<Dependency>(); }
package org.jtrfp.trcl.obj; import org.jtrfp.trcl.Model; import org.jtrfp.trcl.beh.AutoLeveling; import org.jtrfp.trcl.beh.CollidesWithTerrain; import org.jtrfp.trcl.beh.DamageableBehavior; import org.jtrfp.trcl.beh.DamagedByCollisionWithGameplayObject; import org.jtrfp.trcl.beh.DeathBehavior; import org.jtrfp.trcl.beh.DebrisOnDeathBehavior; import org.jtrfp.trcl.beh.ExplodesOnDeath; import org.jtrfp.trcl.beh.HorizAimAtPlayerBehavior; import org.jtrfp.trcl.beh.LeavesPowerupOnDeathBehavior; import org.jtrfp.trcl.beh.LoopingPositionBehavior; import org.jtrfp.trcl.beh.TerrainLocked; import org.jtrfp.trcl.beh.phy.AccelleratedByPropulsion; import org.jtrfp.trcl.beh.phy.BouncesOffSurfaces; import org.jtrfp.trcl.beh.phy.HasPropulsion; import org.jtrfp.trcl.beh.phy.MovesByVelocity; import org.jtrfp.trcl.beh.phy.RotationalDragBehavior; import org.jtrfp.trcl.beh.phy.RotationalMomentumBehavior; import org.jtrfp.trcl.beh.phy.VelocityDragBehavior; import org.jtrfp.trcl.core.TR; import org.jtrfp.trcl.file.DEFFile.EnemyDefinition; import org.jtrfp.trcl.file.DEFFile.EnemyDefinition.EnemyLogic; import org.jtrfp.trcl.file.DEFFile.EnemyPlacement; import org.jtrfp.trcl.obj.Explosion.ExplosionType; public class DEFObject extends WorldObject { private final double boundingRadius; private WorldObject ruinObject; public DEFObject(TR tr,Model model, EnemyDefinition def, EnemyPlacement pl){ super(tr,model); boundingRadius = TR.legacy2Modern(def.getBoundingBoxRadius())/1.5; final EnemyLogic logic = def.getLogic(); boolean mobile=true; boolean canTurn=true; boolean foliage=false; boolean groundLocked=false; switch(logic){ case groundDumb: mobile=false; canTurn=false; break; case groundTargeting://Ground turrets mobile=false; canTurn=true; addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer())); break; case flyingDumb: canTurn=false; break; case groundTargetingDumb: groundLocked=true; break; case flyingSmart: addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer())); break; case bankSpinDrill: break; case sphereBoss: mobile=true; break; case flyingAttackRetreatSmart: addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer())); break; case splitShipSmart: addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer())); break; case groundStaticRuin://Destroyed object is replaced with another using SimpleModel i.e. weapons bunker mobile=false; canTurn=false; break; case targetHeadingSmart: mobile=false;//Belazure's crane bots addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer())); break; case targetPitchSmart: break; case coreBossSmart: addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer())); mobile=false; break; case cityBossSmart: addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer())); mobile=false; break; case staticFiringSmart: addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer())); mobile=false; break; case sittingDuck: canTurn=false; mobile=false; break; case tunnelAttack: mobile=false; break; case takeoffAndEscape: canTurn=false; break; case fallingAsteroid: mobile=false; break; case cNome://Walky bot? groundLocked=true; break; case cNomeLegs://Walky bot? groundLocked=true; break; case cNomeFactory: mobile=false; break; case geigerBoss: addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer())); mobile=false; break; case volcanoBoss: addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer())); mobile=false; break; case volcano: canTurn=false; mobile=false; break; case missile://Silo? mobile=false; break; case bob: mobile=false; break; case alienBoss: addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer())); break; case canyonBoss1: addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer())); mobile=false; break; case canyonBoss2: addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer())); mobile=false; break; case lavaMan: addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer())); mobile=false; break; case arcticBoss: addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer())); mobile=false; break; case helicopter: break; case tree: canTurn=false; mobile=false; foliage=true; break; case ceilingStatic: canTurn=false; mobile=false; break; case bobAndAttack: addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer())); mobile=false; break; case forwardDrive: canTurn=false; groundLocked=true; break; case fallingStalag: canTurn=false; mobile=false; break; case attackRetreatBelowSky: addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer())); break; case attackRetreatAboveSky: addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer())); break; case bobAboveSky: mobile=false; break; case factory: canTurn=false; mobile=false; break; }//end switch(logic) addBehavior(new DeathBehavior()); addBehavior(new DamageableBehavior().setHealth(pl.getStrength())); addBehavior(new DamagedByCollisionWithGameplayObject()); if(!foliage)addBehavior(new DebrisOnDeathBehavior()); if(canTurn){ addBehavior(new RotationalMomentumBehavior()); addBehavior(new RotationalDragBehavior()).setDragCoefficient(.86); addBehavior(new AutoLeveling()); } if(!mobile || groundLocked){ addBehavior(new ExplodesOnDeath(ExplosionType.BigExplosion)); }else{ addBehavior(new ExplodesOnDeath(ExplosionType.Blast)); } if(mobile){ addBehavior(new MovesByVelocity()); addBehavior(new HasPropulsion()); addBehavior(new AccelleratedByPropulsion()); addBehavior(new VelocityDragBehavior()); if(groundLocked){ addBehavior(new TerrainLocked());} else {addBehavior(new BouncesOffSurfaces()); addBehavior(new CollidesWithTerrain()); } getBehavior().probeForBehavior(VelocityDragBehavior.class).setDragCoefficient(.86); getBehavior().probeForBehavior(Propelled.class).setMinPropulsion(0); getBehavior().probeForBehavior(Propelled.class).setPropulsion(def.getThrustSpeed()); addBehavior(new LoopingPositionBehavior()); }//end if(mobile) if(def.getPowerup()!=null && Math.random()*100. < def.getPowerupProbability()){addBehavior(new LeavesPowerupOnDeathBehavior(def.getPowerup()));} }//end DEFObject @Override public void destroy(){ if(ruinObject!=null)ruinObject.setVisible(true);//TODO: Switch to setActive later. super.destroy(); } /** * @return the boundingRadius */ public double getBoundingRadius() { return boundingRadius; } public void setRuinObject(DEFObject ruin) { ruinObject=ruin; } }//end DEFObject
package org.lantern; import java.nio.charset.Charset; /** * Constants for Lantern. */ public class LanternConstants { public static final int DASHCACHE_MAXAGE = 60 * 5; public static final String API_VERSION = "0.0.1"; public static final String BUILD_TIME = "build_time_tok"; public static final String UNCENSORED_ID = "-lan-"; /** * We make range requests of the form "bytes=x-y" where * y <= x + CHUNK_SIZE * in order to chunk and parallelize downloads of large entities. This * is especially important for requests to laeproxy since it is subject * to GAE's response size limits. * Because "bytes=x-y" requests bytes x through y _inclusive_, * this actually requests y - x + 1 bytes, * i.e. CHUNK_SIZE + 1 bytes * when x = 0 and y = CHUNK_SIZE. * This currently corresponds to laeproxy's RANGE_REQ_SIZE of 2000000. */ public static final long CHUNK_SIZE = 2000000 - 1; public static final String STATS_URL = "http://lanternctrl.appspot.com/stats"; public static final String VERSION_KEY = "v"; public static final int LANTERN_LOCALHOST_HTTP_PORT = 8787; public static final String USER_NAME = "un"; public static final String PASSWORD = "pwd"; public static final String DIRECT_BYTES = "db"; public static final String BYTES_PROXIED = "bp"; public static final String REQUESTS_PROXIED = "rp"; public static final String DIRECT_REQUESTS = "dr"; public static final String MACHINE_ID = "m"; public static final String COUNTRY_CODE = "cc"; public static final String WHITELIST_ADDITIONS = "wa"; public static final String WHITELIST_REMOVALS = "wr"; public static final String SERVERS = "s"; public static final String UPDATE_TIME = "ut"; public static final String ROSTER = "roster"; /** * The following are keys in the properties files. */ public static final String FORCE_CENSORED = "forceCensored"; /** * The key for the update JSON object. */ public static final String UPDATE_KEY = "uk"; public static final String UPDATE_VERSION_KEY = "number"; public static final String UPDATE_URL_KEY = "url"; public static final String UPDATE_MESSAGE_KEY = "message"; public static final String UPDATE_RELEASED_KEY = "released"; public static final String INVITES_KEY = "invites"; public static final String INVITED_EMAIL = "invem"; public static final String INVITEE_NAME = "inv_name"; public static final String INVITER_NAME = "invr_name"; public static final String INVITER_REFRESH_TOKEN = "invr_refrtok"; public static final String INVITED = "invd"; /** * The length of keys in translation property files. */ public static final int I18N_KEY_LENGTH = 40; public static final String CONNECT_ON_LAUNCH = "connectOnLaunch"; public static final String START_AT_LOGIN = "startAtLogin"; public static final String LANTERN_VERSION_HTTP_HEADER_NAME = "Lantern-Version"; public static final boolean ON_APP_ENGINE; public static final int KSCOPE_ADVERTISEMENT = 0x2111; public static final String KSCOPE_ADVERTISEMENT_KEY = "ksak"; public static final Charset UTF8 = Charset.forName("UTF8"); static { boolean tempAppEngine; try { Class.forName("org.lantern.LanternControllerUtils"); tempAppEngine = true; } catch (final ClassNotFoundException e) { tempAppEngine = false; } ON_APP_ENGINE = tempAppEngine; } }
package org.lightmare.jpa; import java.io.IOException; import java.net.URL; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import org.apache.log4j.Logger; import org.lightmare.cache.ConnectionContainer; import org.lightmare.cache.ConnectionSemaphore; import org.lightmare.config.Configuration; import org.lightmare.jndi.JndiManager; import org.lightmare.jpa.jta.HibernateConfig; import org.lightmare.libraries.LibraryLoader; import org.lightmare.utils.NamingUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; /** * Creates and caches {@link EntityManagerFactory} for each EJB bean * {@link Class}'s appropriate field (annotated by @PersistenceContext) * * @author Levan * */ public class JpaManager { private List<String> classes; private String path; private URL url; private Map<Object, Object> properties; private boolean swapDataSource; private boolean scanArchives; private ClassLoader loader; private static final String COULD_NOT_BIND_JNDI_ERROR = "could not bind connection"; private static final Logger LOG = Logger.getLogger(JpaManager.class); private JpaManager() { } /** * Checks if entity persistence.xml {@link URL} is provided * * @return boolean */ private boolean checkForURL() { return ObjectUtils.notNull(url) && ObjectUtils.available(url.toString()); } /** * Checks if entity classes or persistence.xml path are provided * * @param classes * @return boolean */ private boolean checkForBuild() { return ObjectUtils.available(classes) || ObjectUtils.available(path) || checkForURL() || swapDataSource || scanArchives; } /** * Added transaction properties for JTA data sources */ private void addTransactionManager() { if (properties == null) { properties = new HashMap<Object, Object>(); } HibernateConfig[] hibernateConfigs = HibernateConfig.values(); for (HibernateConfig hibernateConfig : hibernateConfigs) { properties.put(hibernateConfig.key, hibernateConfig.value); } } /** * Creates {@link EntityManagerFactory} by hibernate or by extended builder * {@link Ejb3ConfigurationImpl} if entity classes or persistence.xml file * path are provided * * @see Ejb3ConfigurationImpl#configure(String, Map) and * Ejb3ConfigurationImpl#createEntityManagerFactory() * * @param unitName * @return {@link EntityManagerFactory} */ @SuppressWarnings("deprecation") private EntityManagerFactory buildEntityManagerFactory(String unitName) throws IOException { EntityManagerFactory emf; Ejb3ConfigurationImpl cfg; boolean pathCheck = ObjectUtils.available(path); boolean urlCheck = checkForURL(); Ejb3ConfigurationImpl.Builder builder = new Ejb3ConfigurationImpl.Builder(); if (loader == null) { loader = LibraryLoader.getContextClassLoader(); } if (ObjectUtils.available(classes)) { builder.setClasses(classes); // Loads entity classes to current ClassLoader instance LibraryLoader.loadClasses(classes, loader); } if (pathCheck || urlCheck) { Enumeration<URL> xmls; ConfigLoader configLoader = new ConfigLoader(); if (pathCheck) { xmls = configLoader.readFile(path); } else { xmls = configLoader.readURL(url); } builder.setXmls(xmls); String shortPath = configLoader.getShortPath(); builder.setShortPath(shortPath); } builder.setSwapDataSource(swapDataSource); builder.setScanArchives(scanArchives); builder.setOverridenClassLoader(loader); cfg = builder.build(); if (ObjectUtils.notTrue(swapDataSource)) { addTransactionManager(); } Ejb3ConfigurationImpl configured = cfg.configure(unitName, properties); if (ObjectUtils.notNull(configured)) { emf = configured.buildEntityManagerFactory(); } else { emf = null; } return emf; } /** * Checks if entity classes or persistence.xml file path are provided to * create {@link EntityManagerFactory} * * @see #buildEntityManagerFactory(String, String, Map, List) * * @param unitName * @param properties * @param path * @param classes * @return {@link EntityManagerFactory} * @throws IOException */ private EntityManagerFactory createEntityManagerFactory(String unitName) throws IOException { EntityManagerFactory emf; if (checkForBuild()) { emf = buildEntityManagerFactory(unitName); } else if (properties == null) { emf = Persistence.createEntityManagerFactory(unitName); } else { emf = Persistence.createEntityManagerFactory(unitName, properties); } return emf; } /** * Binds {@link EntityManagerFactory} to {@link javax.naming.InitialContext} * * @param jndiName * @param unitName * @param emf * @throws IOException */ private void bindJndiName(ConnectionSemaphore semaphore) throws IOException { boolean bound = semaphore.isBound(); if (ObjectUtils.notTrue(bound)) { String jndiName = semaphore.getJndiName(); if (ObjectUtils.available(jndiName)) { JndiManager jndiManager = new JndiManager(); try { String fullJndiName = NamingUtils .createJpaJndiName(jndiName); if (jndiManager.lookup(fullJndiName) == null) { jndiManager.rebind(fullJndiName, semaphore.getEmf()); } } catch (IOException ex) { LOG.error(ex.getMessage(), ex); String errorMessage = StringUtils.concat( COULD_NOT_BIND_JNDI_ERROR, semaphore.getUnitName()); throw new IOException(errorMessage, ex); } } } semaphore.setBound(Boolean.TRUE); } /** * Builds connection, wraps it in {@link ConnectionSemaphore} locks and * caches appropriate instance * * @param unitName * @throws IOException */ public void setConnection(String unitName) throws IOException { ConnectionSemaphore semaphore = ConnectionContainer .getSemaphore(unitName); if (semaphore.isInProgress()) { EntityManagerFactory emf = createEntityManagerFactory(unitName); semaphore.setEmf(emf); semaphore.setInProgress(Boolean.FALSE); bindJndiName(semaphore); } else if (semaphore.getEmf() == null) { String errorMessage = String.format( "Connection %s was not in progress", unitName); throw new IOException(errorMessage); } else { bindJndiName(semaphore); } } /** * Closes passed {@link EntityManagerFactory} * * @param emf */ public static void closeEntityManagerFactory(EntityManagerFactory emf) { if (ObjectUtils.notNull(emf) && emf.isOpen()) { emf.close(); } } public static void closeEntityManager(EntityManager em) { if (ObjectUtils.notNull(em) && em.isOpen()) { em.close(); } } /** * Builder class to create {@link JpaManager} class object * * @author Levan * */ public static class Builder { private JpaManager manager; public Builder() { manager = new JpaManager(); manager.scanArchives = Boolean.TRUE; } /** * Sets {@link javax.persistence.Entity} class names to initialize * * @param classes * @return {@link Builder} */ public Builder setClasses(List<String> classes) { manager.classes = classes; return this; } /** * Sets {@link URL} for persistence.xml file * * @param url * @return {@link Builder} */ public Builder setURL(URL url) { manager.url = url; return this; } /** * Sets path for persistence.xml file * * @param path * @return {@link Builder} */ public Builder setPath(String path) { manager.path = path; return this; } /** * Sets additional persistence properties * * @param properties * @return {@link Builder} */ public Builder setProperties(Map<Object, Object> properties) { manager.properties = properties; return this; } /** * Sets boolean check property to swap jta data source value with non * jta data source value * * @param swapDataSource * @return {@link Builder} */ public Builder setSwapDataSource(boolean swapDataSource) { manager.swapDataSource = swapDataSource; return this; } /** * Sets boolean check to scan deployed archive files for * {@link javax.persistence.Entity} annotated classes * * @param scanArchives * @return {@link Builder} */ public Builder setScanArchives(boolean scanArchives) { manager.scanArchives = scanArchives; return this; } /** * Sets {@link ClassLoader} for persistence classes * * @param loader * @return {@link Builder} */ public Builder setClassLoader(ClassLoader loader) { manager.loader = loader; return this; } /** * Sets all parameters from passed {@link Configuration} instance * * @param configuration * @return {@link Builder} */ public Builder configure(Configuration configuration) { setPath(configuration.getPersXmlPath()) .setProperties(configuration.getPersistenceProperties()) .setSwapDataSource(configuration.isSwapDataSource()) .setScanArchives(configuration.isScanArchives()); return this; } public JpaManager build() { return manager; } } }
package org.mcupdater.util; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Hex; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.mcupdater.FMLStyleFormatter; import org.mcupdater.MCUApp; import org.mcupdater.api.Version; import org.mcupdater.downloadlib.DownloadQueue; import org.mcupdater.downloadlib.Downloadable; import org.mcupdater.downloadlib.TaskableExecutor; import org.mcupdater.instance.FileInfo; import org.mcupdater.instance.Instance; import org.mcupdater.model.*; import org.mcupdater.mojang.AssetIndex; import org.mcupdater.mojang.AssetIndex.Asset; import org.mcupdater.mojang.Library; import org.mcupdater.mojang.MinecraftVersion; import org.mcupdater.mojang.nbt.TagByte; import org.mcupdater.mojang.nbt.TagCompound; import org.mcupdater.mojang.nbt.TagList; import org.mcupdater.mojang.nbt.TagString; import javax.swing.*; import java.awt.image.BufferedImage; import java.io.*; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.Map.Entry; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; public class MCUpdater { private final Path MCFolder; private Path archiveFolder; private Path instanceRoot; private MCUApp parent; private final String sep = System.getProperty("file.separator"); public MessageDigest md5; public ImageIcon defaultIcon; private final Map<String,String> versionMap = new HashMap<>(); public static Logger apiLogger; private int timeoutLength = 5000; private final Gson gson = new GsonBuilder().setPrettyPrinting().create(); public static String defaultMemory = "1G"; public static String defaultPermGen = "128M"; private static MCUpdater INSTANCE; public static MCUpdater getInstance(File file) { if( INSTANCE == null ) { INSTANCE = new MCUpdater(file); if( file == null ) { apiLogger.finest("MCUpdater intialized without path"); } else { apiLogger.finest("MCUpdater intialized with path: " + file.getAbsolutePath()); } } return INSTANCE; } public static MCUpdater getInstance() { if( INSTANCE == null ) { INSTANCE = new MCUpdater(null); apiLogger.finest("MCUpdater intialized without path"); } return INSTANCE; } public static String cpDelimiter() { String osName = System.getProperty("os.name"); if (osName.startsWith("Windows")) { return ";"; } else { return ":"; } } private MCUpdater(File desiredRoot) { apiLogger = Logger.getLogger("MCU-API"); apiLogger.setLevel(Level.ALL); if(System.getProperty("os.name").startsWith("Windows")) { MCFolder = new File(System.getenv("APPDATA")).toPath().resolve(".minecraft"); archiveFolder = new File(System.getenv("APPDATA")).toPath().resolve(".MCUpdater"); } else if(System.getProperty("os.name").startsWith("Mac")) { MCFolder = new File(System.getProperty("user.home")).toPath().resolve("Library").resolve("Application Support").resolve("minecraft"); archiveFolder = new File(System.getProperty("user.home")).toPath().resolve("Library").resolve("Application Support").resolve("MCUpdater"); } else { MCFolder = new File(System.getProperty("user.home")).toPath().resolve(".minecraft"); archiveFolder = new File(System.getProperty("user.home")).toPath().resolve(".MCUpdater"); } if (!(desiredRoot == null)) { archiveFolder = desiredRoot.toPath(); } try { FileHandler apiHandler = new FileHandler(archiveFolder.resolve("MCU-API.log").toString(), 0, 3); apiHandler.setFormatter(new FMLStyleFormatter()); apiLogger.addHandler(apiHandler); } catch (SecurityException | IOException e1) { e1.printStackTrace(); // Will only be thrown if there is a problem with logging. } try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { apiLogger.log(Level.SEVERE, "No MD5 support!", e); } try { defaultIcon = new ImageIcon(MCUpdater.class.getResource("/minecraft.png")); } catch( NullPointerException e ) { _debug( "Unable to load default icon?!" ); defaultIcon = new ImageIcon(new BufferedImage(32,32,BufferedImage.TYPE_INT_ARGB)); } // configure the download cache try { DownloadCache.init(archiveFolder.resolve("cache").toFile()); } catch (IllegalArgumentException e) { _debug( "Suppressed attempt to re-init download cache?!" ); } try { long start = System.currentTimeMillis(); URL md5s = new URL("http://files.mcupdater.com/md5.dat"); URLConnection md5Con = md5s.openConnection(); md5Con.setConnectTimeout(this.timeoutLength); md5Con.setReadTimeout(this.timeoutLength); InputStreamReader input = new InputStreamReader(md5Con.getInputStream()); BufferedReader buffer = new BufferedReader(input); String currentLine; while(true){ currentLine = buffer.readLine(); if(currentLine != null){ String entry[] = currentLine.split("\\|"); versionMap.put(entry[0], entry[1]); } else { break; } } buffer.close(); input.close(); apiLogger.fine("Took "+(System.currentTimeMillis()-start)+"ms to load md5.dat"); } catch (MalformedURLException e) { apiLogger.log(Level.SEVERE, "Bad URL", e); } catch (IOException e) { apiLogger.log(Level.SEVERE, "I/O Error", e); } } public MCUApp getParent() { return parent; } public void setParent(MCUApp parent) { this.parent = parent; } public Path getMCFolder() { return MCFolder; } public Path getArchiveFolder() { return archiveFolder; } public Path getInstanceRoot() { return instanceRoot; } public void setInstanceRoot(Path instanceRoot) { this.instanceRoot = instanceRoot; apiLogger.info("Instance root changed to: " + instanceRoot.toString()); } private boolean getExcludedNames(String path, boolean forDelete) { if(path.contains("mcu" + sep)) { // never delete from the mcu folder return true; } if (path.contains("mods") && (path.contains(".zip") || path.contains(".jar"))) { // always delete mods in archive form return false; } if(path.contains("bin" + sep + "minecraft.jar")) { // always delete bin/minecraft.jar return false; } if(path.contains("bin" + sep)) { // never delete anything else in bin/ return true; } if(path.contains("resources") && !path.contains("mods")) { // never delete resources unless it is under the mods directory return true; } if(path.contains("lib" + sep)) { // never delete the lib/ folder return true; } if(path.contains("saves")) { // never delete saves return true; } if(path.contains("screenshots")) { // never delete screenshots return true; } if(path.contains("stats")) { return true; } if(path.contains("texturepacks")) { return true; } if(path.contains("lastlogin")) { return true; } if(path.contains("instance.dat")) { return true; } if(path.contains("minecraft.jar")) { return true; } if(path.contains("options.txt")) { return forDelete; } if(path.contains("META-INF" + sep)) { return true; } // Temporary hardcoding of client specific mod configs (i.e. Don't clobber on update) if(path.contains("rei_minimap" + sep)) { return true; } if(path.contains("macros" + sep)) { return true; } if(path.contains("InvTweaks")) { return true; } if(path.contains("optionsof.txt")){ return true; } if(path.contains("voxelMap")) { return true; } return false; } private List<File> recurseFolder(File folder, boolean includeFolders) { List<File> output = new ArrayList<>(); List<File> input = new ArrayList<>(Arrays.asList(folder.listFiles())); Iterator<File> fi = input.iterator(); if(includeFolders) { output.add(folder); } while(fi.hasNext()) { File entry = fi.next(); if(entry.isDirectory()) { List<File> subfolder = recurseFolder(entry, includeFolders); for (File aSubfolder : subfolder) { output.add(aSubfolder); } } else { output.add(entry); } } return output; } public boolean installMods(final ServerList server, List<GenericModule> toInstall, List<ConfigFile> configs, final Path instancePath, boolean clearExisting, final Instance instData, final ModSide side) throws FileNotFoundException { //TODO: Divide code into logical sections for better analysis if (Version.requestedFeatureLevel(server.getMCUVersion(), "2.2")) { // Sort mod list for InJar Collections.sort(toInstall, new ModuleComparator(ModuleComparator.Mode.IMPORTANCE)); } //final Path instancePath = instanceRoot.resolve(server.getServerId()); Path binPath = instancePath.resolve("bin"); final Path productionJar; //File jar = null; final File tmpFolder = instancePath.resolve("temp" + Integer.toString((new Random()).nextInt(100))).toFile(); tmpFolder.mkdirs(); Set<Downloadable> jarMods = new HashSet<>(); Set<Downloadable> generalFiles = new HashSet<>(); DownloadQueue assetsQueue = null; DownloadQueue jarQueue; DownloadQueue generalQueue; DownloadQueue libraryQueue = null; final List<String> libExtract = new ArrayList<>(); final Map<String,Boolean> modExtract = new HashMap<>(); final Map<String,Boolean> keepMeta = new TreeMap<>(); Downloadable baseJar = null; final MinecraftVersion version = MinecraftVersion.loadVersion(server.getVersion()); List<URL> jarUrl = new ArrayList<>(); Set<Downloadable> libSet = new HashSet<>(); switch (side){ case CLIENT: System.out.println("Overrides: " + server.getLibOverrides().size()); assetsQueue = parent.submitAssetsQueue("Assets", server.getServerId(), version); for (Map.Entry<String,String> entry : server.getLibOverrides().entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } for (Library lib : version.getLibraries()) { String key = StringUtils.join(Arrays.copyOfRange(lib.getName().split(":"),0,2),":"); System.out.println(lib.getName() + " - " + key); if (server.getLibOverrides().containsKey(key)) { lib.setName(server.getLibOverrides().get(key)); System.out.println(" - Replaced: " + lib.getName()); } if (lib.validForOS()) { List<URL> urls = new ArrayList<>(); try { urls.add(new URL(lib.getDownloadUrl())); } catch (MalformedURLException e) { apiLogger.log(Level.SEVERE, "Bad URL", e); } Downloadable entry = new Downloadable(lib.getName(),lib.getFilename(),"",100000,urls); libSet.add(entry); if (lib.hasNatives()) { libExtract.add(lib.getFilename()); } } } productionJar = binPath.resolve("minecraft.jar"); try { jarUrl.add(new URL("https://s3.amazonaws.com/Minecraft.Download/versions/" + server.getVersion() + "/" + server.getVersion() + ".jar")); } catch (MalformedURLException e2) { apiLogger.log(Level.SEVERE, "Bad URL", e2); } String jarMD5 = ""; for (Entry<String,String> entry : versionMap.entrySet()) { if (entry.getValue().equals(server.getVersion())) { jarMD5 = entry.getKey(); break; } } baseJar = new Downloadable("Minecraft jar","0.jar",jarMD5,3000000,jarUrl); keepMeta.put("0.jar", Version.requestedFeatureLevel(server.getVersion(), "1.6")); break; case SERVER: productionJar = instancePath.resolve("minecraft_server.jar"); try { jarUrl.add(new URL("https://s3.amazonaws.com/Minecraft.Download/versions/" + server.getVersion() + "/minecraft_server." + server.getVersion() + ".jar")); jarUrl.add(new URL("http://assets.minecraft.net/" + server.getVersion().replace(".", "_") + "/minecraft_server.jar")); } catch (MalformedURLException e2) { apiLogger.log(Level.SEVERE, "Bad URL", e2); } baseJar = new Downloadable("Server jar","0.jar","",3000000,jarUrl); keepMeta.put("0.jar", Version.requestedFeatureLevel(server.getVersion(), "1.6")); Library lib = new Library(); lib.setName("net.sf.jopt-simple:jopt-simple:4.5"); String key = StringUtils.join(Arrays.copyOfRange(lib.getName().split(":"),0,2),":"); System.out.println(lib.getName() + " - " + key); if (server.getLibOverrides().containsKey(key)) { lib.setName(server.getLibOverrides().get(key)); System.out.println(" - Replaced: " + lib.getName()); } if (lib.validForOS()) { List<URL> urls = new ArrayList<>(); try { urls.add(new URL(lib.getDownloadUrl())); } catch (MalformedURLException e) { apiLogger.log(Level.SEVERE, "Bad URL", e); } Downloadable entry = new Downloadable(lib.getName(),lib.getFilename(),"",100000,urls); libSet.add(entry); if (lib.hasNatives()) { libExtract.add(lib.getFilename()); } } break; default: apiLogger.severe("Invalid API call to MCUpdater.installMods! (side cannot be " + side.toString() + ")"); return false; } libraryQueue = parent.submitNewQueue("Libraries", server.getServerId(), libSet, instancePath.resolve("lib").toFile(), DownloadCache.getDir()); Boolean updateJar = clearExisting; if (side == ModSide.CLIENT) { if (!productionJar.toFile().exists()) { updateJar = true; } } else { updateJar = true; } Iterator<GenericModule> iMods = toInstall.iterator(); List<String> modIds = new ArrayList<>(); Map<String,String> newFilenames = new HashMap<>(); int jarModCount = 0; while (iMods.hasNext() && !updateJar) { GenericModule current = iMods.next(); if (current.getModType() == ModType.Jar) { FileInfo jarMod = instData.findJarMod(current.getId()); if (jarMod == null) { updateJar = true; } else if (current.getMD5().isEmpty() || (!current.getMD5().equalsIgnoreCase(jarMod.getMD5()))) { updateJar = true; } jarModCount++; } else { modIds.add(current.getId()); newFilenames.put(current.getId(), current.getFilename()); } } if (jarModCount != instData.getJarMods().size()) { updateJar = true; } if (updateJar && baseJar != null) { jarMods.add(baseJar); } for (FileInfo entry : instData.getInstanceFiles()) { if (!modIds.contains(entry.getModId()) || !newFilenames.get(entry.getModId()).equals(entry.getFilename())) { instancePath.resolve(entry.getFilename()).toFile().delete(); } } instData.setJarMods(new ArrayList<FileInfo>()); instData.setInstanceFiles(new ArrayList<FileInfo>()); jarModCount = 0; apiLogger.info("Instance path: " + instancePath.toString()); List<File> contents = recurseFolder(instancePath.toFile(), true); if (clearExisting){ parent.setStatus("Clearing existing configuration"); parent.log("Clearing existing configuration..."); for (File entry : new ArrayList<>(contents)) { if (getExcludedNames(entry.getPath(), true)) { contents.remove(entry); } } ListIterator<File> liClear = contents.listIterator(contents.size()); while(liClear.hasPrevious()) { File entry = liClear.previous(); entry.delete(); } } Iterator<GenericModule> itMods = toInstall.iterator(); final File buildJar = archiveFolder.resolve("build.jar").toFile(); if(buildJar.exists()) { buildJar.delete(); } int modCount = toInstall.size(); int modsLoaded = 0; int errorCount = 0; while(itMods.hasNext()) { GenericModule entry = itMods.next(); parent.log("Mod: "+entry.getName()); Collections.sort(entry.getPrioritizedUrls()); switch (entry.getModType()) { case Jar: if (updateJar) { jarMods.add(new Downloadable(entry.getName(),String.valueOf(entry.getJarOrder()) + "-" + entry.getId() + ".jar",entry.getMD5(),entry.getFilesize(),entry.getUrls())); keepMeta.put(String.valueOf(entry.getJarOrder()) + "-" + cleanForFile(entry.getId()) + ".jar", entry.getKeepMeta()); instData.addJarMod(entry.getId(), entry.getMD5()); jarModCount++; } break; case Extract: generalFiles.add(new Downloadable(entry.getName(),cleanForFile(entry.getId()) + ".zip",entry.getMD5(),entry.getFilesize(),entry.getUrls())); modExtract.put(cleanForFile(entry.getId()) + ".zip", entry.getInRoot()); break; case Option: //TODO: Unimplemented break; default: generalFiles.add(new Downloadable(entry.getName(), entry.getFilename(), entry.getMD5(),entry.getFilesize(),entry.getUrls())); instData.addMod(entry.getId(), entry.getMD5(), entry.getFilename()); } modsLoaded++; parent.log(" Done ("+modsLoaded+"/"+modCount+")"); } for (ConfigFile cfEntry : configs) { final File confFile = instancePath.resolve(cfEntry.getPath()).toFile(); if (confFile.exists() && cfEntry.isNoOverwrite()) { continue; } List<URL> configUrl = new ArrayList<>(); try { configUrl.add(new URL(cfEntry.getUrl())); } catch (MalformedURLException e) { ++errorCount; apiLogger.log(Level.SEVERE, "General Error", e); } generalFiles.add(new Downloadable(cfEntry.getPath(), cfEntry.getPath(), cfEntry.getMD5(), 10000, configUrl)); } generalQueue = parent.submitNewQueue("Instance files", server.getServerId(), generalFiles, instancePath.toFile(), DownloadCache.getDir()); jarQueue = parent.submitNewQueue("Jar build files", server.getServerId(), jarMods, tmpFolder, DownloadCache.getDir()); TaskableExecutor libExecutor = new TaskableExecutor(2, new Runnable(){ @Override public void run() { for (String entry : libExtract){ Archive.extractZip(instancePath.resolve("lib").resolve(entry).toFile(), instancePath.resolve("lib").resolve("natives").toFile(), false); } }}); if (libraryQueue != null) { libraryQueue.processQueue(libExecutor); } final File branding = new File(tmpFolder, "fmlbranding.properties"); try { branding.createNewFile(); Properties propBrand = new Properties(); propBrand.setProperty("fmlbranding", "MCUpdater: " + server.getName() + " (rev " + server.getRevision() + ")"); propBrand.store(new FileOutputStream(branding), "MCUpdater ServerPack branding"); } catch (IOException e1) { apiLogger.log(Level.SEVERE, "I/O Error", e1); } final boolean doJarUpdate = updateJar; TaskableExecutor jarExecutor = new TaskableExecutor(2, new Runnable() { @Override public void run() { if (!doJarUpdate) { try { Archive.updateArchive(productionJar.toFile(), new File[]{ branding }); } catch (IOException e1) { apiLogger.log(Level.SEVERE, "I/O Error", e1); } } else { for (Map.Entry<String,Boolean> entry : keepMeta.entrySet()) { File entryFile = new File(tmpFolder,entry.getKey()); Archive.extractZip(entryFile, tmpFolder, entry.getValue()); entryFile.delete(); } try { buildJar.createNewFile(); } catch (IOException e) { apiLogger.log(Level.SEVERE, "I/O Error", e); } boolean doManifest = true; List<File> buildList = recurseFolder(tmpFolder,true); for (File entry : new ArrayList<>(buildList)) { if (entry.getPath().contains("META-INF")) { doManifest = false; } } parent.log("Packaging updated jar..."); try { Archive.createJar(buildJar, buildList, tmpFolder.getPath() + sep, doManifest); } catch (IOException e1) { parent.log("Failed to create jar!"); apiLogger.log(Level.SEVERE, "I/O Error", e1); } try { Files.createDirectories(productionJar.getParent()); Files.copy(buildJar.toPath(), productionJar, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { apiLogger.log(Level.SEVERE, "Failed to copy new jar to instance!", e); } } List<File> tempFiles = recurseFolder(tmpFolder,true); ListIterator<File> li = tempFiles.listIterator(tempFiles.size()); while(li.hasPrevious()) { File entry = li.previous(); entry.delete(); } if (server.isGenerateList() && side != ModSide.SERVER) { writeMCServerFile(instancePath, server.getName(), server.getAddress()); } instData.setMCVersion(server.getVersion()); instData.setRevision(server.getRevision()); String jsonOut = gson.toJson(instData); try { BufferedWriter writer = Files.newBufferedWriter(getInstanceRoot().resolve(server.getServerId()).resolve("instance.json"), StandardCharsets.UTF_8); writer.append(jsonOut); writer.close(); } catch (IOException e) { apiLogger.log(Level.SEVERE, "I/O error", e); } } }); jarQueue.processQueue(jarExecutor); TaskableExecutor genExecutor = new TaskableExecutor(12, new Runnable(){ @Override public void run() { for (Map.Entry<String,Boolean> entry : modExtract.entrySet()) { if (entry.getValue()) { Archive.extractZip(instancePath.resolve(entry.getKey()).toFile(), instancePath.toFile()); } else { Archive.extractZip(instancePath.resolve(entry.getKey()).toFile(), instancePath.resolve("mods").toFile()); } instancePath.resolve(entry.getKey()).toFile().delete(); } } }); generalQueue.processQueue(genExecutor); TaskableExecutor assetsExecutor = new TaskableExecutor(8, new Runnable(){ @Override public void run() { //check virtual Gson gson = new Gson(); String indexName = version.getAssets(); if (indexName == null) { indexName = "legacy"; } File indexesPath = archiveFolder.resolve("assets").resolve("indexes").toFile(); File indexFile = new File(indexesPath, indexName + ".json"); String json; try { json = FileUtils.readFileToString(indexFile); AssetIndex index = gson.fromJson(json, AssetIndex.class); parent.log("Assets virtual: " + index.isVirtual()); if (index.isVirtual()) { //Test symlink support boolean doLinks = true; try { java.nio.file.Files.createSymbolicLink(archiveFolder.resolve("linktest"), archiveFolder.resolve("MCUpdater.log.0")); archiveFolder.resolve("linktest").toFile().delete(); } catch (Exception e) { doLinks = false; } Path assetsPath = archiveFolder.resolve("assets"); Path virtualPath = assetsPath.resolve("virtual"); for (Map.Entry<String, Asset> entry : index.getObjects().entrySet()) { Path target = virtualPath.resolve(entry.getKey()); Path original = assetsPath.resolve("objects").resolve(entry.getValue().getHash().substring(0,2)).resolve(entry.getValue().getHash()); if (!Files.exists(target)) { Files.createDirectories(target.getParent()); if (doLinks) { Files.createSymbolicLink(target, original); } else { Files.copy(original, target); } } } } } catch (IOException e) { parent.baseLogger.log(Level.SEVERE, "Assets exception! " + e.getMessage()); } } }); if (assetsQueue != null) { assetsQueue.processQueue(assetsExecutor); } if( errorCount > 0 ) { parent.baseLogger.severe("Errors were detected with this update, please verify your files. There may be a problem with the serverpack configuration or one of your download sites."); return false; } return true; } private String cleanForFile(String id) { return id.replaceAll("[^a-zA-Z_0-9\\-.]", "_"); } public void writeMCServerFile(Path installPath, String name, String ip) { apiLogger.info("Writing servers.dat"); /* byte[] header = new byte[]{ 0x0A,0x00,0x00,0x09,0x00,0x07,0x73,0x65,0x72,0x76,0x65,0x72,0x73,0x0A, 0x00,0x00,0x00,0x01,0x01,0x00,0x0B,0x68,0x69,0x64,0x65,0x41,0x64,0x64, 0x72,0x65,0x73,0x73,0x01,0x08,0x00,0x04,0x6E,0x61,0x6D,0x65,0x00, (byte) (name.length() + 12), (byte) 0xC2,(byte) 0xA7,0x41,0x5B,0x4D,0x43,0x55,0x5D,0x20,(byte) 0xC2,(byte) 0xA7,0x46 }; byte[] nameBytes = name.getBytes(); byte[] ipBytes = ip.getBytes(); byte[] middle = new byte[]{0x08,0x00,0x02,0x69,0x70,0x00,(byte) ip.length()}; byte[] end = new byte[]{0x00,0x00}; int size = header.length + nameBytes.length + middle.length + ipBytes.length + end.length; byte[] full = new byte[size]; int pos = 0; System.arraycopy(header, 0, full, pos, header.length); pos += header.length; System.arraycopy(nameBytes, 0, full, pos, nameBytes.length); pos += nameBytes.length; System.arraycopy(middle, 0, full, pos, middle.length); pos += middle.length; System.arraycopy(ipBytes, 0, full, pos, ipBytes.length); pos += ipBytes.length; System.arraycopy(end, 0, full, pos, end.length); */ TagCompound root = new TagCompound(""); TagList servers = new TagList("servers", TagList.Type.Compound); TagCompound entry = new TagCompound(""); entry.add(new TagByte("hideAddress", (byte) 1)); String symbol = new String(new byte[]{(byte) 0xc2, (byte) 0xa7}, StandardCharsets.UTF_8); entry.add(new TagString("name", symbol + "A[MCU] " + symbol + "F" + name)); entry.add(new TagString("ip",ip)); servers.add(entry); root.add(servers); List<Byte> bytes = root.toBytes(true); byte[] full = ArrayUtils.toPrimitive(bytes.toArray(new Byte[bytes.size()])); File serverFile = installPath.resolve("servers.dat").toFile(); try { serverFile.createNewFile(); FileOutputStream fos = new FileOutputStream(serverFile); fos.write(full,0,full.length); fos.close(); } catch (IOException e) { apiLogger.log(Level.SEVERE, "I/O Error", e); } } private static void _debug(String msg) { apiLogger.fine(msg); } public void setTimeout(int timeout) { this.timeoutLength = timeout; } public int getTimeout() { return this.timeoutLength; } public static String calculateGroupHash(Set<String> digests) { BigInteger hash = BigInteger.valueOf(0); for (String entry : digests) { try { BigInteger digest = new BigInteger(Hex.decodeHex(entry.toCharArray())); hash = hash.xor(digest); } catch (DecoderException e) { //e.printStackTrace(); System.out.println("Entry '" + entry + "' is not a valid hexadecimal number"); } } return Hex.encodeHexString(hash.toByteArray()); } }
package org.nanopub; import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import org.openrdf.model.URI; import org.openrdf.rio.trig.TriGWriter; import org.openrdf.rio.turtle.TurtleUtil; /** * @author Tobias Kuhn */ public class CustomTrigWriter extends TriGWriter { public CustomTrigWriter(OutputStream out) { super(out); } public CustomTrigWriter(Writer writer) { super(writer); } @Override protected void writeURI(URI uri) throws IOException { String uriString = uri.toString(); String prefix = namespaceTable.get(uriString); if (prefix != null) { // Exact match: no suffix required writer.write(prefix); writer.write(":"); return; } prefix = null; int splitIdxNorm = TurtleUtil.findURISplitIndex(uriString); // Do also split at dots: int splitIdxDot = uriString.lastIndexOf(".") + 1; if (uriString.length() == splitIdxDot) splitIdxDot = -1; int splitIdx = Math.max(splitIdxNorm, splitIdxDot); if (splitIdx > 0) { String namespace = uriString.substring(0, splitIdx); prefix = namespaceTable.get(namespace); } if (prefix != null) { // Namespace is mapped to a prefix; write abbreviated URI writer.write(prefix); writer.write(":"); writer.write(uriString.substring(splitIdx)); } else { // Write full URI writer.write("<"); writer.write(TurtleUtil.encodeURIString(uriString)); writer.write(">"); } } }
package org.opennars.entity; import org.opennars.inference.TemporalRules; import org.opennars.inference.TruthFunctions; import org.opennars.inference.TruthFunctions.EternalizedTruthValue; import org.opennars.io.Symbols; import org.opennars.io.Texts; import org.opennars.language.*; import org.opennars.main.Nar; import org.opennars.main.MiscFlags; import java.io.Serializable; import java.util.*; import org.opennars.main.Parameters; import org.opennars.storage.Memory; /** * Sentence as defined by the NARS-theory * * A Sentence is used as the premises and conclusions of all inference rules. * * @author Pei Wang * @author Patrick Hammer */ public class Sentence<T extends Term> implements Cloneable, Serializable { public boolean producedByTemporalInduction=false; /** * The content of a Sentence is a Term */ public final T term; /** * The punctuation indicates the type of the Sentence: * Judgment '.', Question '?', Goal '!', or Quest '@' */ public final char punctuation; /** * The truth value of Judgment, or desire value of Goal */ public final TruthValue truth; /** * Partial record of the derivation path */ public final Stamp stamp; /** * Whether the sentence can be revised */ private boolean revisible; /** * caches the 'getKey()' result */ private CharSequence key; private final int hash; public Sentence(final T term, final char punctuation, final TruthValue newTruth, final Stamp newStamp) { this(term, punctuation, newTruth, newStamp, true); } /** * Create a Sentence with the given fields * * @param _content The Term that forms the content of the sentence * @param punctuation The punctuation indicating the type of the sentence * @param truth The truth value of the sentence, null for question * @param stamp The stamp of the sentence indicating its derivation time and * base */ private Sentence(T _content, final char punctuation, final TruthValue truth, final Stamp stamp, final boolean normalize) { //cut interval at end for sentence in serial conjunction, and inbetween for parallel if(punctuation!=Symbols.TERM_NORMALIZING_WORKAROUND_MARK) { if(_content instanceof Conjunction) { final Conjunction c=(Conjunction)_content; if(c.getTemporalOrder()==TemporalRules.ORDER_FORWARD) { if(c.term[c.term.length-1] instanceof Interval) { long time=0; //refined: int u = 0; while(c.term.length-1-u >= 0 && c.term[c.term.length-1-u] instanceof Interval) { time += ((Interval)c.term[c.term.length-1-u]).time; u++; } final Term[] term2=new Term[c.term.length-u]; System.arraycopy(c.term, 0, term2, 0, term2.length); _content=(T) Conjunction.make(term2, c.getTemporalOrder(), c.isSpatial); //ok we removed a part of the interval, we have to transform the occurence time of the sentence back //accordingly if(!c.isSpatial && stamp!=null && stamp.getOccurrenceTime() != Stamp.ETERNAL) stamp.setOccurrenceTime(stamp.getOccurrenceTime()-time); } if(c.term[0] instanceof Interval) { long time=0; //refined: int u = 0; while(u < c.term.length && (c.term[u] instanceof Interval)) { time += ((Interval)c.term[u]).time; u++; } final Term[] term2=new Term[c.term.length-u]; System.arraycopy(c.term, u, term2, 0, term2.length); _content=(T) Conjunction.make(term2, c.getTemporalOrder(), c.isSpatial); //ok we removed a part of the interval, we have to transform the occurence time of the sentence back //accordingly if(!c.isSpatial && stamp!=null && stamp.getOccurrenceTime() != Stamp.ETERNAL) stamp.setOccurrenceTime(stamp.getOccurrenceTime()+time); } } } } this.punctuation = punctuation; if( truth != null ) { if (_content instanceof Implication || _content instanceof Equivalence) { if (((Statement) _content).getSubject().hasVarIndep() && !((Statement) _content).getPredicate().hasVarIndep()) truth.setConfidence(0.0f); if (((Statement) _content).getPredicate().hasVarIndep() && !((Statement) _content).getSubject().hasVarIndep()) truth.setConfidence(0.0f); //TODO: } else if (_content instanceof Interval && punctuation != Symbols.TERM_NORMALIZING_WORKAROUND_MARK) { truth.setConfidence(0.0f); //do it that way for now, because else further inference is interrupted. if (MiscFlags.DEBUG && MiscFlags.DEBUG_INVALID_SENTENCES) throw new IllegalStateException("Sentence content must not be Interval: " + _content + punctuation + " " + stamp); } if ((!isQuestion() && !isQuest()) && (truth == null) && punctuation != Symbols.TERM_NORMALIZING_WORKAROUND_MARK) { throw new IllegalStateException("Judgment and Goal sentences require non-null truth value"); } if (_content.subjectOrPredicateIsIndependentVar() && punctuation != Symbols.TERM_NORMALIZING_WORKAROUND_MARK) { truth.setConfidence(0.0f); //do it that way for now, because else further inference is interrupted. if (MiscFlags.DEBUG && MiscFlags.DEBUG_INVALID_SENTENCES) throw new IllegalStateException("A statement sentence is not allowed to have a independent variable as subj or pred"); } if (MiscFlags.DEBUG && MiscFlags.DEBUG_INVALID_SENTENCES && punctuation != Symbols.TERM_NORMALIZING_WORKAROUND_MARK) { if (!Term.valid(_content)) { truth.setConfidence(0.0f); if (MiscFlags.DEBUG) { System.err.println("Invalid Sentence term: " + _content); Thread.dumpStack(); } } } } if ((isQuestion() || isQuest()) && punctuation!=Symbols.TERM_NORMALIZING_WORKAROUND_MARK && !stamp.isEternal()) { stamp.setEternal(); } this.truth = truth; this.stamp = stamp; this.revisible = _content instanceof Implication || _content instanceof Equivalence || !(_content.hasVarDep()); T newTerm = null; if( _content instanceof CompoundTerm) newTerm = (T)((CompoundTerm)_content).cloneDeepVariables(); //Variable name normalization //TODO move this to Concept method, like cloneNormalized() if ( newTerm != null && normalize && _content.hasVar() && (!((CompoundTerm)_content).isNormalized() ) ) { this.term = newTerm; final CompoundTerm c = (CompoundTerm)term; final List<Variable> vars = new ArrayList(); //may contain duplicates, list for efficiency c.recurseSubtermsContainingVariables((t, parent) -> { if (t instanceof Variable) { final Variable v = ((Variable) t); vars.add(v); } }); final Map<CharSequence, CharSequence> rename = new HashMap(); boolean renamed = false; for (final Variable v : vars) { CharSequence vname = v.name(); if (!v.hasVarIndep()) vname = vname + " " + v.getScope().name(); CharSequence n = rename.get(vname); if (n == null) { //type + id rename.put(vname, n = Variable.getName(v.getType(), rename.size() + 1)); if (!n.equals(vname)) renamed = true; } v.setScope(c, n); } if (renamed) { c.invalidateName(); if (MiscFlags.DEBUG && MiscFlags.DEBUG_INVALID_SENTENCES) { if (!Term.valid(c)) { final CompoundTerm.UnableToCloneException ntc = new CompoundTerm.UnableToCloneException("Invalid term discovered after normalization: " + c + " ; prior to normalization: " + _content); ntc.printStackTrace(); throw ntc; } } } c.setNormalized(true); } else { this.term = _content; } if (isNotTermlinkNormalizer()) this.hash = Objects.hash(term, punctuation, truth, stamp.getOccurrenceTime()); else this.hash = Objects.hash(term, punctuation, truth ); } protected boolean isNotTermlinkNormalizer() { return punctuation != Symbols.TERM_NORMALIZING_WORKAROUND_MARK; } /** * To check whether two sentences are equal * * @param that The other sentence * @return Whether the two sentences have the same content */ @Override public boolean equals(final Object that) { if (this == that) return true; if (that instanceof Sentence) { final Sentence t = (Sentence) that; if (hash!=t.hash) return false; if (punctuation!=t.punctuation) return false; if (isNotTermlinkNormalizer()) { if (stamp.getOccurrenceTime()!=t.stamp.getOccurrenceTime()) return false; } if (truth==null) { if (t.truth!=null) return false; } else if (t.truth==null) { return false; } else if (!truth.equals(t.truth)) return false; if (!term.equals(t.term)) return false; if(term.term_indices != null && t.term.term_indices != null) { for(int i=0;i<term.term_indices.length;i++) { if(term.term_indices[i] != t.term.term_indices[i]) { return false; //position or scale was different } } } return stamp.equals(t.stamp, false, true, true); } return false; } /** * To produce the hashcode of a sentence * * @return a hashcode */ @Override public int hashCode() { return hash; } /** * Clone the Sentence * * @return The cloned Sentence */ @Override public Sentence clone() { return clone(term); } public Sentence clone(final boolean makeEternal) { final Sentence clon = clone(term); if(clon.stamp.getOccurrenceTime()!=Stamp.ETERNAL && makeEternal) { //change occurence time of clone clon.stamp.setEternal(); } return clon; } /** * clone with a different term * * @param t term which has to get cloned * @return sentence with the cloned term as a property */ public final Sentence clone(final Term t) { return new Sentence( t, punctuation, truth!=null ? new TruthValue(truth) : null, stamp.clone()); } /** * project a judgment to a difference occurrence time * * @param targetTime The time to be projected into * @param currentTime The current time as a reference * @return The projected belief */ public Sentence projection(final long targetTime, final long currentTime, Memory mem) { final TruthValue newTruth = projectionTruth(targetTime, currentTime, mem); final boolean eternalizing = (newTruth instanceof EternalizedTruthValue); final Stamp newStamp = eternalizing ? stamp.cloneWithNewOccurrenceTime(Stamp.ETERNAL) : stamp.cloneWithNewOccurrenceTime(targetTime); return new Sentence( term, punctuation, newTruth, newStamp, false); } public TruthValue projectionTruth(final long targetTime, final long currentTime, Memory mem) { TruthValue newTruth = null; if (!stamp.isEternal()) { newTruth = TruthFunctions.eternalize(truth, mem.narParameters); if (targetTime != Stamp.ETERNAL) { final long occurrenceTime = stamp.getOccurrenceTime(); final float factor = TruthFunctions.temporalProjection(occurrenceTime, targetTime, currentTime, mem.narParameters); final float projectedConfidence = factor * truth.getConfidence(); if (projectedConfidence > newTruth.getConfidence()) { newTruth = new TruthValue(truth.getFrequency(), projectedConfidence, mem.narParameters); } } } if (newTruth == null) newTruth = truth.clone(); return newTruth; } /** * @return property, whether the object is a judgment */ public boolean isJudgment() { return (punctuation == Symbols.JUDGMENT_MARK); } /** * @return property, whether the object is a question */ public boolean isQuestion() { return (punctuation == Symbols.QUESTION_MARK); } /** * @return property, whether the sentence is a goal */ public boolean isGoal() { return (punctuation == Symbols.GOAL_MARK); } /** * @return property, whether the sentence is a quest */ public boolean isQuest() { return (punctuation == Symbols.QUEST_MARK); } /** * @return property of the ability to revise the sentence */ public boolean getRevisible() { return revisible; } public void setRevisible(final boolean b) { revisible = b; } public int getTemporalOrder() { return term.getTemporalOrder(); } public long getOccurenceTime() { return stamp.getOccurrenceTime(); } /** * Get a String representation of the sentence * * @return The String */ @Override public String toString() { return getKey().toString(); } /** * Get a String representation of the sentence for key of Task and TaskLink * * @return The String */ public CharSequence getKey() { //key must be invalidated if content or truth change if (key == null) { final CharSequence contentName = term.name(); final boolean showOcurrenceTime = ((punctuation == Symbols.JUDGMENT_MARK) || (punctuation == Symbols.QUESTION_MARK)); int stringLength = 0; if (truth != null) { stringLength += (showOcurrenceTime ? 8 : 0) + 11 /*truthString.length()*/; } String conv = ""; if(term.term_indices != null) { conv = " [i,j,k,l]=["; for(int i = 0; i<4; i++) { //skip min sizes conv += String.valueOf(term.term_indices[i])+","; } conv = conv.substring(0, conv.length()-1) + "]"; } //suffix = [punctuation][ ][truthString][ ][occurenceTimeString] final StringBuilder suffix = new StringBuilder(stringLength).append(punctuation).append(conv); if (truth != null) { suffix.append(' '); truth.appendString(suffix, false); } if ((showOcurrenceTime) && (stamp!=null)) { suffix.append(' '); stamp.appendOcurrenceTime(suffix); } key = Texts.yarn( contentName, suffix); } return key; } /** * @param nar Reasoner instance * @param showStamp must the stamp get appended to the string? * @return textural representation of the sentence for humans */ public CharSequence toString(final Nar nar, final boolean showStamp) { final CharSequence contentName = term.name(); final long t = nar.time(); final long diff=stamp.getOccurrenceTime()-nar.time(); final long diffabs = Math.abs(diff); String timediff = ""; if(diffabs < nar.narParameters.DURATION) { timediff = "|"; } else { final Long Int = diffabs; timediff = diff>0 ? "+"+String.valueOf(Int) : "-"+String.valueOf(Int); } if(MiscFlags.TEST_RUNNING) { timediff = "!"+String.valueOf(stamp.getOccurrenceTime()); } String tenseString = ":"+timediff+":"; if(stamp.getOccurrenceTime() == Stamp.ETERNAL) tenseString=""; final CharSequence stampString = showStamp ? stamp.name() : null; int stringLength = contentName.length() + tenseString.length() + 1 + 1; if (truth != null) stringLength += 11; if (showStamp) stringLength += stampString.length()+1; String conv = ""; if(term.term_indices != null) { conv = " [i,j,k,l]=["; for(int i = 0; i<4; i++) { //skip min sizes conv += String.valueOf(term.term_indices[i])+","; } conv = conv.substring(0, conv.length()-1) + "]"; } final StringBuilder buffer = new StringBuilder(stringLength). append(contentName).append(punctuation).append(conv); if (tenseString.length() > 0) buffer.append(' ').append(tenseString); if (truth != null) { buffer.append(' '); truth.appendString(buffer, true); } if (showStamp) buffer.append(' ').append(stampString); return buffer; } /** * discounts the truth value of the sentence * */ public void discountConfidence(Parameters narParameters) { truth.setConfidence(truth.getConfidence() * narParameters.DISCOUNT_RATE).setAnalytic(false); } /** * * @return classification if the sentence is true for ever */ public boolean isEternal() { return stamp.isEternal(); } /** * * @return term of the sentence, terms are properties of sentences */ public T getTerm() { return term; } /** * * @return truth of the sentence, truths are properties of sentences */ public TruthValue getTruth() { return truth; } }
package org.realityforge.dbdiff; import java.util.List; import org.realityforge.cli.CLArgsParser; import org.realityforge.cli.CLOption; import org.realityforge.cli.CLOptionDescriptor; import org.realityforge.cli.CLUtil; /** * The entry point in which to run the tool. */ public class Main { private static final int HELP_OPT = 1; private static final int QUIET_OPT = 'q'; private static final int VERBOSE_OPT = 'v'; private static final int DATABASE_DRIVER_OPT = 2; private static final int DATABASE_DIALECT_OPT = 3; private static final CLOptionDescriptor[] OPTIONS = new CLOptionDescriptor[]{ new CLOptionDescriptor( "database-driver", CLOptionDescriptor.ARGUMENT_REQUIRED, DATABASE_DRIVER_OPT, "The jdbc driver to load prior to connecting to the databases." ), new CLOptionDescriptor( "database-dialect", CLOptionDescriptor.ARGUMENT_REQUIRED, DATABASE_DIALECT_OPT, "The database dialect to use during diff." ), new CLOptionDescriptor( "help", CLOptionDescriptor.ARGUMENT_DISALLOWED, HELP_OPT, "print this message and exit" ), new CLOptionDescriptor( "quiet", CLOptionDescriptor.ARGUMENT_DISALLOWED, QUIET_OPT, "Do not output unless an error occurs, just return 0 on no difference.", new int[]{VERBOSE_OPT} ), new CLOptionDescriptor( "verbose", CLOptionDescriptor.ARGUMENT_DISALLOWED, VERBOSE_OPT, "Verbose output of differences.", new int[]{QUIET_OPT}), }; private static final int NO_DIFFERENCE_EXIT_CODE = 0; private static final int DIFFERENCE_EXIT_CODE = 1; private static final int ERROR_PARSING_ARGS_EXIT_CODE = 2; private static final int ERROR_BAD_DRIVER_EXIT_CODE = 3; private static final int QUIET = 0; private static final int NORMAL = 1; private static final int VERBOSE = 1; private static int c_logLevel = NORMAL; private static String c_databaseDriver; private static String c_databaseDialect; private static String c_database1; private static String c_database2; public static void main( final String[] args ) { if ( !processOptions( args ) ) { System.exit( ERROR_PARSING_ARGS_EXIT_CODE ); return; } if ( VERBOSE <= c_logLevel ) { info( "Performing difference between databases" ); } try { Class.forName( c_databaseDriver ); } catch ( final Exception e ) { error( "Unable to load database driver " + c_databaseDriver + " due to " + e.getMessage() ); System.exit( ERROR_BAD_DRIVER_EXIT_CODE ); return; } final boolean difference = diff(); if ( difference ) { if ( NORMAL <= c_logLevel ) { error( "Difference found between databases" ); } System.exit( DIFFERENCE_EXIT_CODE ); } else { if ( NORMAL <= c_logLevel ) { info( "No difference found between databases" ); } System.exit( NO_DIFFERENCE_EXIT_CODE ); } } private static boolean diff() { return false; } private static boolean processOptions( final String[] args ) { // Parse the arguments final CLArgsParser parser = new CLArgsParser( args, OPTIONS ); //Make sure that there was no errors parsing arguments if ( null != parser.getErrorString() ) { error( parser.getErrorString() ); return false; } // Get a list of parsed options @SuppressWarnings( "unchecked" ) final List<CLOption> options = parser.getArguments(); for ( final CLOption option : options ) { switch ( option.getId() ) { case CLOption.TEXT_ARGUMENT: if ( null == c_database1 ) { c_database1 = option.getArgument(); } else if ( null == c_database2 ) { c_database2 = option.getArgument(); } else { error( "Unexpected 3rd test argument: " + option.getArgument() ); return false; } break; case DATABASE_DRIVER_OPT: { c_databaseDriver = option.getArgument(); break; } case DATABASE_DIALECT_OPT: { c_databaseDialect = option.getArgument(); if ( !"mssql".equals( c_databaseDialect ) ) { error( "Unsupported database dialect: " + c_databaseDialect ); return false; } break; } case VERBOSE_OPT: { c_logLevel = VERBOSE; break; } case QUIET_OPT: { c_logLevel = QUIET; break; } case HELP_OPT: { printUsage(); return false; } } } if ( null == c_databaseDriver ) { error( "Database driver must be specified" ); return false; } if ( null == c_database1 || null == c_database2 ) { error( "Two jdbc urls must supplied for the databases to check differences" ); return false; } if ( VERBOSE <= c_logLevel ) { info( "Database 1: " + c_database1 ); info( "Database 2: " + c_database2 ); } return true; } /** * Print out a usage statement */ private static void printUsage() { final String lineSeparator = System.getProperty( "line.separator" ); final StringBuilder msg = new StringBuilder(); msg.append( "java " ); msg.append( Main.class.getName() ); msg.append( " [options] database1JDBCurl database2JDBCurl" ); msg.append( lineSeparator ); msg.append( "Options: " ); msg.append( lineSeparator ); msg.append( CLUtil.describeOptions( OPTIONS ).toString() ); info( msg.toString() ); } private static void info( final String message ) { System.out.println( message ); } private static void error( final String message ) { System.out.println( "Error: " + message ); } }
package org.takes.rq.form; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URLDecoder; import java.nio.charset.Charset; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import lombok.EqualsAndHashCode; import org.takes.HttpException; import org.takes.Request; import org.takes.misc.EnglishLowerCase; import org.takes.misc.Sprintf; import org.takes.misc.VerboseIterable; import org.takes.rq.RqForm; import org.takes.rq.RqPrint; import org.takes.rq.RqWrap; /** * Base implementation of {@link RqForm}. * @author Aleksey Popov (alopen@yandex.ru) * @version $Id$ * @since 0.33 */ @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") @EqualsAndHashCode(callSuper = true, of = "req") public final class RqFormBase extends RqWrap implements RqForm { /** * Request. */ private final transient Request req; /** * Saved map. */ private final transient List<Map<String, List<String>>> saved; /** * Ctor. * @param request Original request */ public RqFormBase(final Request request) { super(request); this.saved = new CopyOnWriteArrayList<>(); this.req = request; } @Override public Iterable<String> param(final CharSequence key) throws IOException { final List<String> values = this.map().get(new EnglishLowerCase(key.toString()).string()); final Iterable<String> iter; if (values == null) { iter = new VerboseIterable<>( Collections.<String>emptyList(), new Sprintf( "there are no params \"%s\" among %d others: %s", key, this.map().size(), this.map().keySet() ) ); } else { iter = new VerboseIterable<>( values, new Sprintf( "there are only %d params by name \"%s\"", values.size(), key ) ); } return iter; } @Override public Iterable<String> names() throws IOException { return this.map().keySet(); } /** * Decode from URL. * @param txt Text * @return Decoded */ private static String decode(final CharSequence txt) { try { return URLDecoder.decode( txt.toString(), Charset.defaultCharset().name() ); } catch (final UnsupportedEncodingException ex) { throw new IllegalStateException(ex); } } /** * Create map of request parameters. * @return Parameters map or empty map in case of error. * @throws IOException If something fails reading or parsing body */ @SuppressFBWarnings("JLM_JSR166_UTILCONCURRENT_MONITORENTER") private Map<String, List<String>> map() throws IOException { synchronized (this.saved) { if (this.saved.isEmpty()) { this.saved.add(this.freshMap()); } return this.saved.get(0); } } /** * Create map of request parameter. * @return Parameters map or empty map in case of error. * @throws IOException If something fails reading or parsing body */ private Map<String, List<String>> freshMap() throws IOException { final String body = new RqPrint(this.req).printBody(); final Map<String, List<String>> map = new HashMap<>(1); // @checkstyle MultipleStringLiteralsCheck (1 line) for (final String pair : body.split("&")) { if (pair.isEmpty()) { continue; } // @checkstyle MultipleStringLiteralsCheck (1 line) final String[] parts = pair.split("=", 2); if (parts.length < 2) { throw new HttpException( HttpURLConnection.HTTP_BAD_REQUEST, String.format( "invalid form body pair: %s", pair ) ); } final String key = decode( new EnglishLowerCase(parts[0].trim()).string() ); if (!map.containsKey(key)) { map.put(key, new LinkedList<String>()); } map.get(key).add(decode(parts[1].trim())); } return map; } }
package org.testng.asserts; import java.util.Collection; import java.util.Map; import java.util.Set; /** * An assert class with various hooks allowing its behavior to be modified * by subclasses. */ public class Assertion implements IAssertLifecycle { protected void doAssert(IAssert<?> assertCommand) { onBeforeAssert(assertCommand); try { executeAssert(assertCommand); onAssertSuccess(assertCommand); } catch(AssertionError ex) { onAssertFailure(assertCommand, ex); throw ex; } finally { onAfterAssert(assertCommand); } } /** * Run the assert command in parameter. Meant to be overridden by subclasses. */ @Override public void executeAssert(IAssert<?> assertCommand) { assertCommand.doAssert(); } /** * Invoked when an assert succeeds. Meant to be overridden by subclasses. */ @Override public void onAssertSuccess(IAssert<?> assertCommand) { } /** * Invoked when an assert fails. Meant to be overridden by subclasses. * * @deprecated use onAssertFailure(IAssert assertCommand, AssertionError ex) instead of. */ @Deprecated @Override public void onAssertFailure(IAssert<?> assertCommand) { } @Override public void onAssertFailure(IAssert<?> assertCommand, AssertionError ex) { onAssertFailure(assertCommand); } /** * Invoked before an assert is run. Meant to be overridden by subclasses. */ @Override public void onBeforeAssert(IAssert<?> assertCommand) { } /** * Invoked after an assert is run. Meant to be overridden by subclasses. */ @Override public void onAfterAssert(IAssert<?> assertCommand) { } abstract private static class SimpleAssert<T> implements IAssert<T> { private final T actual; private final T expected; private final String m_message; public SimpleAssert(String message) { this(null, null, message); } public SimpleAssert(T actual, T expected) { this(actual, expected, null); } public SimpleAssert(T actual, T expected, String message) { this.actual = actual; this.expected = expected; m_message = message; } @Override public String getMessage() { return m_message; } @Override public T getActual() { return actual; } @Override public T getExpected() { return expected; } @Override abstract public void doAssert(); } public void assertTrue(final boolean condition, final String message) { doAssert(new SimpleAssert<Boolean>(condition, Boolean.TRUE) { @Override public void doAssert() { org.testng.Assert.assertTrue(condition, message); } }); } public void assertTrue(final boolean condition) { doAssert(new SimpleAssert<Boolean>(condition, Boolean.TRUE) { @Override public void doAssert() { org.testng.Assert.assertTrue(condition); } }); } public void assertFalse(final boolean condition, final String message) { doAssert(new SimpleAssert<Boolean>(condition, Boolean.FALSE, message) { @Override public void doAssert() { org.testng.Assert.assertFalse(condition, message); } }); } public void assertFalse(final boolean condition) { doAssert(new SimpleAssert<Boolean>(condition, Boolean.FALSE) { @Override public void doAssert() { org.testng.Assert.assertFalse(condition); } }); } public void fail(final String message, final Throwable realCause) { doAssert(new SimpleAssert<Object>(message) { @Override public void doAssert() { org.testng.Assert.fail(message, realCause); } }); } public void fail(final String message) { doAssert(new SimpleAssert<Object>(message) { @Override public void doAssert() { org.testng.Assert.fail(message); } }); } public void fail() { doAssert(new SimpleAssert<Object>(null) { @Override public void doAssert() { org.testng.Assert.fail(); } }); } public <T> void assertEquals(final T actual, final T expected, final String message) { doAssert(new SimpleAssert<T>(actual, expected, message) { @Override public void doAssert() { org.testng.Assert.assertEquals(actual, expected, message); } }); } public <T> void assertEquals(final T actual, final T expected) { doAssert(new SimpleAssert<T>(actual, expected) { @Override public void doAssert() { org.testng.Assert.assertEquals(actual, expected); } }); } public void assertEquals(final String actual, final String expected, final String message) { doAssert(new SimpleAssert<String>(actual, expected, message) { @Override public void doAssert() { org.testng.Assert.assertEquals(actual, expected, message); } }); } public void assertEquals(final String actual, final String expected) { doAssert(new SimpleAssert<String>(actual, expected) { @Override public void doAssert() { org.testng.Assert.assertEquals(actual, expected); } }); } public void assertEquals(final double actual, final double expected, final double delta, final String message) { doAssert(new SimpleAssert<Double>(actual, expected, message) { @Override public void doAssert() { org.testng.Assert.assertEquals(actual, expected, delta, message); } }); } public void assertEquals(final double actual, final double expected, final double delta) { doAssert(new SimpleAssert<Double>(actual, expected) { @Override public void doAssert() { org.testng.Assert.assertEquals(actual, expected, delta); } }); } public void assertEquals(final float actual, final float expected, final float delta, final String message) { doAssert(new SimpleAssert<Float>(actual, expected, message) { @Override public void doAssert() { org.testng.Assert.assertEquals(actual, expected, delta, message); } }); } public void assertEquals(final float actual, final float expected, final float delta) { doAssert(new SimpleAssert<Float>(actual, expected) { @Override public void doAssert() { org.testng.Assert.assertEquals(actual, expected, delta); } }); } public void assertEquals(final long actual, final long expected, final String message) { doAssert(new SimpleAssert<Long>(actual, expected, message) { @Override public void doAssert() { org.testng.Assert.assertEquals(actual, expected, message); } }); } public void assertEquals(final long actual, final long expected) { doAssert(new SimpleAssert<Long>(actual, expected) { @Override public void doAssert() { org.testng.Assert.assertEquals(actual, expected); } }); } public void assertEquals(final boolean actual, final boolean expected, final String message) { doAssert(new SimpleAssert<Boolean>(actual, expected, message) { @Override public void doAssert() { org.testng.Assert.assertEquals(actual, expected, message); } }); } public void assertEquals(final boolean actual, final boolean expected) { doAssert(new SimpleAssert<Boolean>(actual, expected) { @Override public void doAssert() { org.testng.Assert.assertEquals(actual, expected); } }); } public void assertEquals(final byte actual, final byte expected, final String message) { doAssert(new SimpleAssert<Byte>(actual, expected, message) { @Override public void doAssert() { org.testng.Assert.assertEquals(actual, expected, message); } }); } public void assertEquals(final byte actual, final byte expected) { doAssert(new SimpleAssert<Byte>(actual, expected) { @Override public void doAssert() { org.testng.Assert.assertEquals(actual, expected); } }); } public void assertEquals(final char actual, final char expected, final String message) { doAssert(new SimpleAssert<Character>(actual, expected, message) { @Override public void doAssert() { org.testng.Assert.assertEquals(actual, expected, message); } }); } public void assertEquals(final char actual, final char expected) { doAssert(new SimpleAssert<Character>(actual, expected) { @Override public void doAssert() { org.testng.Assert.assertEquals(actual, expected); } }); } public void assertEquals(final short actual, final short expected, final String message) { doAssert(new SimpleAssert<Short>(actual, expected, message) { @Override public void doAssert() { org.testng.Assert.assertEquals(actual, expected, message); } }); } public void assertEquals(final short actual, final short expected) { doAssert(new SimpleAssert<Short>(actual, expected) { @Override public void doAssert() { org.testng.Assert.assertEquals(actual, expected); } }); } public void assertEquals(final int actual, final int expected, final String message) { doAssert(new SimpleAssert<Integer>(actual, expected, message) { @Override public void doAssert() { org.testng.Assert.assertEquals(actual, expected, message); } }); } public void assertEquals(final int actual, final int expected) { doAssert(new SimpleAssert<Integer>(actual, expected) { @Override public void doAssert() { org.testng.Assert.assertEquals(actual, expected); } }); } public void assertNotNull(final Object object) { doAssert(new SimpleAssert<Object>(object, null) { @Override public void doAssert() { org.testng.Assert.assertNotNull(object); } }); } public void assertNotNull(final Object object, final String message) { doAssert(new SimpleAssert<Object>(object, null, message) { @Override public void doAssert() { org.testng.Assert.assertNotNull(object, message); } }); } public void assertNull(final Object object) { doAssert(new SimpleAssert<Object>(object, null) { @Override public void doAssert() { org.testng.Assert.assertNull(object); } }); } public void assertNull(final Object object, final String message) { doAssert(new SimpleAssert<Object>(object, null, message) { @Override public void doAssert() { org.testng.Assert.assertNull(object, message); } }); } public void assertSame(final Object actual, final Object expected, final String message) { doAssert(new SimpleAssert<Object>(actual, expected, message) { @Override public void doAssert() { org.testng.Assert.assertSame(actual, expected, message); } }); } public void assertSame(final Object actual, final Object expected) { doAssert(new SimpleAssert<Object>(actual, expected) { @Override public void doAssert() { org.testng.Assert.assertSame(actual, expected); } }); } public void assertNotSame(final Object actual, final Object expected, final String message) { doAssert(new SimpleAssert<Object>(actual, expected, message) { @Override public void doAssert() { org.testng.Assert.assertNotSame(actual, expected, message); } }); } public void assertNotSame(final Object actual, final Object expected) { doAssert(new SimpleAssert<Object>(actual, expected) { @Override public void doAssert() { org.testng.Assert.assertNotSame(actual, expected); } }); } public void assertEquals(final Collection<?> actual, final Collection<?> expected) { doAssert(new SimpleAssert<Collection<?>>(actual, expected) { @Override public void doAssert() { org.testng.Assert.assertEquals(actual, expected); } }); } public void assertEquals(final Collection<?> actual, final Collection<?> expected, final String message) { doAssert(new SimpleAssert<Collection<?>>(actual, expected, message) { @Override public void doAssert() { org.testng.Assert.assertEquals(actual, expected, message); } }); } public void assertEquals(final Object[] actual, final Object[] expected, final String message) { doAssert(new SimpleAssert<Object[]>(actual, expected, message) { @Override public void doAssert() { org.testng.Assert.assertEquals(actual, expected, message); } }); } public void assertEqualsNoOrder(final Object[] actual, final Object[] expected, final String message) { doAssert(new SimpleAssert<Object[]>(actual, expected, message) { @Override public void doAssert() { org.testng.Assert.assertEqualsNoOrder(actual, expected, message); } }); } public void assertEquals(final Object[] actual, final Object[] expected) { doAssert(new SimpleAssert<Object[]>(actual, expected) { @Override public void doAssert() { org.testng.Assert.assertEquals(actual, expected); } }); } public void assertEqualsNoOrder(final Object[] actual, final Object[] expected) { doAssert(new SimpleAssert<Object[]>(actual, expected) { @Override public void doAssert() { org.testng.Assert.assertEqualsNoOrder(actual, expected); } }); } public void assertEquals(final byte[] actual, final byte[] expected) { doAssert(new SimpleAssert<byte[]>(actual, expected) { @Override public void doAssert() { org.testng.Assert.assertEquals(actual, expected); } }); } public void assertEquals(final byte[] actual, final byte[] expected, final String message) { doAssert(new SimpleAssert<byte[]>(actual, expected, message) { @Override public void doAssert() { org.testng.Assert.assertEquals(actual, expected, message); } }); } public void assertEquals(final Set<?> actual, final Set<?> expected) { doAssert(new SimpleAssert<Set<?>>(actual, expected) { @Override public void doAssert() { org.testng.Assert.assertEquals(actual, expected); } }); } public void assertEquals(final Set<?> actual, final Set<?> expected, final String message) { doAssert(new SimpleAssert<Set<?>>(actual, expected, message) { @Override public void doAssert() { org.testng.Assert.assertEquals(actual, expected, message); } }); } public void assertEquals(final Map<?, ?> actual, final Map<?, ?> expected) { doAssert(new SimpleAssert<Map<?, ?>>(actual, expected) { @Override public void doAssert() { org.testng.Assert.assertEquals(actual, expected); } }); } public void assertNotEquals(final Object actual, final Object expected, final String message) { doAssert(new SimpleAssert<Object>(actual, expected, message) { @Override public void doAssert() { org.testng.Assert.assertNotEquals(actual, expected, message); } }); } public void assertNotEquals(final Object actual, final Object expected) { doAssert(new SimpleAssert<Object>(actual, expected) { @Override public void doAssert() { org.testng.Assert.assertNotEquals(actual, expected); } }); } void assertNotEquals(final String actual, final String expected, final String message) { doAssert(new SimpleAssert<String>(actual, expected, message) { @Override public void doAssert() { org.testng.Assert.assertNotEquals(actual, expected, message); } }); } void assertNotEquals(final String actual, final String expected) { doAssert(new SimpleAssert<String>(actual, expected) { @Override public void doAssert() { org.testng.Assert.assertNotEquals(actual, expected); } }); } void assertNotEquals(final long actual, final long expected, final String message) { doAssert(new SimpleAssert<Long>(actual, expected, message) { @Override public void doAssert() { org.testng.Assert.assertNotEquals(actual, expected, message); } }); } void assertNotEquals(final long actual, final long expected) { doAssert(new SimpleAssert<Long>(actual, expected) { @Override public void doAssert() { org.testng.Assert.assertNotEquals(actual, expected); } }); } void assertNotEquals(final boolean actual, final boolean expected, final String message) { doAssert(new SimpleAssert<Boolean>(actual, expected, message) { @Override public void doAssert() { org.testng.Assert.assertNotEquals(actual, expected, message); } }); } void assertNotEquals(final boolean actual, final boolean expected) { doAssert(new SimpleAssert<Boolean>(actual, expected) { @Override public void doAssert() { org.testng.Assert.assertNotEquals(actual, expected); } }); } void assertNotEquals(final byte actual, final byte expected, final String message) { doAssert(new SimpleAssert<Byte>(actual, expected, message) { @Override public void doAssert() { org.testng.Assert.assertNotEquals(actual, expected, message); } }); } void assertNotEquals(final byte actual, final byte expected) { doAssert(new SimpleAssert<Byte>(actual, expected) { @Override public void doAssert() { org.testng.Assert.assertNotEquals(actual, expected); } }); } void assertNotEquals(final char actual, final char expected, final String message) { doAssert(new SimpleAssert<Character>(actual, expected, message) { @Override public void doAssert() { org.testng.Assert.assertNotEquals(actual, expected, message); } }); } void assertNotEquals(final char actual, final char expected) { doAssert(new SimpleAssert<Character>(actual, expected) { @Override public void doAssert() { org.testng.Assert.assertNotEquals(actual, expected); } }); } void assertNotEquals(final short actual, final short expected, final String message) { doAssert(new SimpleAssert<Short>(actual, expected, message) { @Override public void doAssert() { org.testng.Assert.assertNotEquals(actual, expected, message); } }); } void assertNotEquals(final short actual, final short expected) { doAssert(new SimpleAssert<Short>(actual, expected) { @Override public void doAssert() { org.testng.Assert.assertNotEquals(actual, expected); } }); } void assertNotEquals(final int actual, final int expected, final String message) { doAssert(new SimpleAssert<Integer>(actual, expected, message) { @Override public void doAssert() { org.testng.Assert.assertNotEquals(actual, expected, message); } }); } void assertNotEquals(final int actual, final int expected) { doAssert(new SimpleAssert<Integer>(actual, expected) { @Override public void doAssert() { org.testng.Assert.assertNotEquals(actual, expected); } }); } public void assertNotEquals(final float actual, final float expected, final float delta, final String message) { doAssert(new SimpleAssert<Float>(actual, expected, message) { @Override public void doAssert() { org.testng.Assert.assertNotEquals(actual, expected, delta, message); } }); } public void assertNotEquals(final float actual, final float expected, final float delta) { doAssert(new SimpleAssert<Float>(actual, expected) { @Override public void doAssert() { org.testng.Assert.assertNotEquals(actual, expected, delta); } }); } public void assertNotEquals(final double actual, final double expected, final double delta, final String message) { doAssert(new SimpleAssert<Double>(actual, expected, message) { @Override public void doAssert() { org.testng.Assert.assertNotEquals(actual, expected, delta, message); } }); } public void assertNotEquals(final double actual, final double expected, final double delta) { doAssert(new SimpleAssert<Double>(actual, expected) { @Override public void doAssert() { org.testng.Assert.assertNotEquals(actual, expected, delta); } }); } }
package org.udger.parser; import org.sqlite.SQLiteConfig; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.lang.ref.SoftReference; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.sql.*; import java.util.*; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Main parser's class handles parser requests for user agent or IP. */ public class UdgerParser implements Closeable { private static final Logger LOG = Logger.getLogger(UdgerParser.class.getName()); private static final String DB_FILENAME = "udgerdb_v3.dat"; private static final String UDGER_UA_DEV_BRAND_LIST_URL = "https://udger.com/resources/ua-list/devices-brand-detail?brand="; private static final String ID_CRAWLER = "crawler"; private static final Pattern PAT_UNPERLIZE = Pattern.compile("^/?(.*?)/si$"); /** * Holds precalculated data for single DB. Intention is to have single ParserDbData associated with multiple UdgerParser(s) */ public static class ParserDbData { private WordDetector clientWordDetector; private WordDetector deviceWordDetector; private WordDetector osWordDetector; private List<IdRegString> clientRegstringList; private List<IdRegString> osRegstringList; private List<IdRegString> deviceRegstringList; private volatile boolean prepared = false; private final String dbFileName; public ParserDbData(String dbFileName) { this.dbFileName = dbFileName; } protected void prepare(Connection connection) throws SQLException { if (!prepared) { synchronized (this) { if (!prepared) { clientRegstringList = prepareRegexpStruct(connection, "udger_client_regex"); osRegstringList = prepareRegexpStruct(connection, "udger_os_regex"); deviceRegstringList = prepareRegexpStruct(connection, "udger_deviceclass_regex"); clientWordDetector = createWordDetector(connection, "udger_client_regex", "udger_client_regex_words"); deviceWordDetector = createWordDetector(connection, "udger_deviceclass_regex", "udger_deviceclass_regex_words"); osWordDetector = createWordDetector(connection, "udger_os_regex", "udger_os_regex_words"); prepared = true; } } } } } private static class ClientInfo { private Integer clientId; private Integer classId; } protected static class IdRegString { int id; int wordId1; int wordId2; Pattern pattern; } private ParserDbData parserDbData; private Connection connection; private final Map<String, SoftReference<Pattern>> regexCache = new HashMap<>(); private Map<String, PreparedStatement> preparedStmtMap = new HashMap<>(); private LRUCache<String, UdgerUaResult> cache; private boolean osParserEnabled = true; private boolean deviceParserEnabled = true; private boolean deviceBrandParserEnabled = true; private boolean inMemoryEnabled = false; /** * Instantiates a new udger parser with LRU cache with capacity of 10.000 items * * @param parserDbData the parser data associated with single DB */ public UdgerParser(ParserDbData parserDbData) { this(parserDbData, 10000); } /** * Instantiates a new udger parser. * * @param parserDbData the parser data associated with single DB * @param cacheCapacity the LRU cache capacity */ public UdgerParser(ParserDbData parserDbData, int cacheCapacity) { this.parserDbData = parserDbData; if (cacheCapacity > 0) { cache = new LRUCache<>(cacheCapacity); } } /** * Instantiates a new udger parser with LRU cache with capacity of 10.000 items * * @param parserDbData the parser data associated with single DB * @param inMemoryEnabled the true for in memory mode * @param cacheCapacity the LRU cache capacity */ public UdgerParser(ParserDbData parserDbData, boolean inMemoryEnabled, int cacheCapacity) { this(parserDbData, cacheCapacity); this.inMemoryEnabled = inMemoryEnabled; } @Override public void close() throws IOException { try { for (PreparedStatement preparedStmt : preparedStmtMap.values()) { preparedStmt.close(); } preparedStmtMap.clear(); if (connection != null && !connection.isClosed()) { connection.close(); connection = null; } if (cache != null) { cache.clear(); } regexCache.clear(); } catch (SQLException e) { throw new IOException(e.getMessage()); } } /** * Returns true if the sqlite DB connection has not been closed and is still valid. * * @param timeoutMillis the timeout millis * @return true, if is valid * @throws IOException Signals that an I/O exception has occurred. */ public boolean isValid(int timeoutMillis) throws IOException { try { return connection == null || connection.isValid(timeoutMillis); } catch (SQLException e) { throw new IOException("Failed to validate connection within " + timeoutMillis + " millis.", e); } } /** * Parses the user agent string and stores results of parsing in UdgerUaResult. * If the parser was initialized to use an in memory DB, then the DB is not set to read only. * This does not matter since the connection is internal to this client, as such there are * no chance of external modifications. * * @param uaString the user agent string * @return the intance of UdgerUaResult storing results of parsing * @throws SQLException the SQL exception */ public UdgerUaResult parseUa(String uaString) throws SQLException { UdgerUaResult ret; if (cache != null) { ret = cache.get(uaString); if (ret != null) { return ret; } } ret = new UdgerUaResult(uaString); prepare(); ClientInfo clientInfo = clientDetector(uaString, ret); if (osParserEnabled) { osDetector(uaString, ret, clientInfo); } if (deviceParserEnabled) { deviceDetector(uaString, ret, clientInfo); } if (deviceBrandParserEnabled) { if (ret.getOsFamilyCode() != null && !ret.getOsFamilyCode().isEmpty()) { fetchDeviceBrand(uaString, ret); } } if (cache != null) { cache.put(uaString, ret); } return ret; } /** * Parses the IP string and stores results of parsing in UdgerIpResult. * * @param ipString the IP string * @return the instance of UdgerIpResult storing results of parsing * @throws SQLException the SQL exception * @throws UnknownHostException the unknown host exception */ public UdgerIpResult parseIp(String ipString) throws SQLException, UnknownHostException { UdgerIpResult ret = new UdgerIpResult(ipString); InetAddress addr = InetAddress.getByName(ipString); Long ipv4int = null; String normalizedIp = null; if (addr instanceof Inet4Address) { ipv4int = 0L; for (byte b : addr.getAddress()) { ipv4int = ipv4int << 8 | (b & 0xFF); } normalizedIp = addr.getHostAddress(); } else if (addr instanceof Inet6Address) { normalizedIp = addr.getHostAddress().replaceAll("((?:(?:^|:)0+\\b){2,}):?(?!\\S*\\b\\1:0+\\b)(\\S*)", "::$2"); } ret.setIpClassification("Unrecognized"); ret.setIpClassificationCode("unrecognized"); if (normalizedIp != null) { prepare(); try (ResultSet ipRs = getFirstRow(UdgerSqlQuery.SQL_IP, normalizedIp)) { if (ipRs != null && ipRs.next()) { fetchUdgerIp(ipRs, ret); if (!ID_CRAWLER.equals(ret.getIpClassificationCode())) { ret.setCrawlerFamilyInfoUrl(""); } } } if (ipv4int != null) { ret.setIpVer(4); ResultSet dataCenterRs = getFirstRow(UdgerSqlQuery.SQL_DATACENTER, ipv4int, ipv4int); fetchDataCenterAndCloseRs(dataCenterRs, ret); } else { ret.setIpVer(6); int[] ipArray = ip6ToArray((Inet6Address) addr); ResultSet dataCenterRs = getFirstRow(UdgerSqlQuery.SQL_DATACENTER_RANGE6, ipArray[0], ipArray[0], ipArray[1], ipArray[1], ipArray[2], ipArray[2], ipArray[3], ipArray[3], ipArray[4], ipArray[4], ipArray[5], ipArray[5], ipArray[6], ipArray[6], ipArray[7], ipArray[7] ); fetchDataCenterAndCloseRs(dataCenterRs, ret); } } return ret; } private void fetchDataCenterAndCloseRs(ResultSet dataCenterRs, UdgerIpResult ret) throws SQLException { if (dataCenterRs != null) { try { if (dataCenterRs.next()) { fetchDataCenter(dataCenterRs, ret); } } finally { dataCenterRs.close(); } } } /** * Checks if is OS parser enabled. OS parser is enabled by default * * @return true, if is OS parser enabled */ public boolean isOsParserEnabled() { return osParserEnabled; } /** * Enable/disable the OS parser. OS parser is enabled by default. If enabled following fields * of UdgerUaResult are processed by the OS parser: * <ul> * <li>osFamily, osFamilyCode, OS, osCode, osHomePage, osIcon, osIconBig</li> * <li>osFamilyVendor, osFamilyVendorCode, osFamilyVedorHomepage, osInfoUrl</li> * </ul> * <p> * If the OSs fields are not necessary then disabling this feature can increase * the parser's performance. * * @param osParserEnabled the true if os parser is to be enabled */ public void setOsParserEnabled(boolean osParserEnabled) { this.osParserEnabled = osParserEnabled; } /** * Checks if is device parser enabled. Device parser is enabled by default * * @return true, if device parser is enabled */ public boolean isDeviceParserEnabled() { return deviceParserEnabled; } /** * Enable/disable the device parser. Device parser is enabled by default. If enabled following fields * of UdgerUaResult are filled by the device parser: * <ul> * <li>deviceClass, deviceClassCode, deviceClassIcon</li> * <li>deviceClassIconBig, deviceClassInfoUrl</li> * </ul> * <p> * If the DEVICEs fields are not necessary then disabling this feature can increase * the parser's performance. * * @param deviceParserEnabled the true if device parser is to be enabled */ public void setDeviceParserEnabled(boolean deviceParserEnabled) { this.deviceParserEnabled = deviceParserEnabled; } /** * Checks if is device brand parser enabled. Device brand parser is enabled by default. * * @return true, if device brand parser is enabled */ public boolean isDeviceBrandParserEnabled() { return deviceBrandParserEnabled; } /** * Enable/disable the device brand parser. Device brand parser is enabled by default. If enabled following fields * of UdgerUaResult are filled by the device brand parser: * <ul> * <li>deviceMarketname, deviceBrand, deviceBrandCode, deviceBrandHomepage</li> * <li>deviceBrandIcon, deviceBrandIconBig, deviceBrandInfoUrl</li> * </ul> * <p> * If the BRANDs fields are not necessary then disabling this feature can increase * the parser's performance. * * @param deviceBrandParserEnabled the true if device brand parser is to be enabled */ public void setDeviceBrandParserEnabled(boolean deviceBrandParserEnabled) { this.deviceBrandParserEnabled = deviceBrandParserEnabled; } private static WordDetector createWordDetector(Connection connection, String regexTableName, String wordTableName) throws SQLException { Set<Integer> usedWords = new HashSet<>(); addUsedWords(usedWords, connection, regexTableName, "word_id"); addUsedWords(usedWords, connection, regexTableName, "word2_id"); WordDetector result = new WordDetector(); try (final Statement statement = connection.createStatement(); final ResultSet rs = statement.executeQuery("SELECT * FROM " + wordTableName)) { if (rs != null) { while (rs.next()) { int id = rs.getInt("id"); if (usedWords.contains(id)) { String word = rs.getString("word").toLowerCase(); result.addWord(id, word); } } } } return result; } private static void addUsedWords(Set<Integer> usedWords, Connection connection, String regexTableName, String wordIdColumn) throws SQLException { try (Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery("SELECT " + wordIdColumn + " FROM " + regexTableName)) { if (rs != null) { while (rs.next()) { usedWords.add(rs.getInt(wordIdColumn)); } } } } private IdRegString findIdRegString(String uaString, Set<Integer> foundClientWords, List<IdRegString> list) { for (IdRegString irs : list) { if ((irs.wordId1 == 0 || foundClientWords.contains(irs.wordId1)) && (irs.wordId2 == 0 || foundClientWords.contains(irs.wordId2))) { Matcher matcher = irs.pattern.matcher(uaString); if (matcher.find()) return irs; } } return null; } private static List<IdRegString> prepareRegexpStruct(Connection connection, String regexpTableName) throws SQLException { List<IdRegString> ret = new ArrayList<>(); try (Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery("SELECT rowid, regstring, word_id, word2_id FROM " + regexpTableName + " ORDER BY sequence")) { if (rs != null) { while (rs.next()) { IdRegString irs = new IdRegString(); irs.id = rs.getInt("rowid"); irs.wordId1 = rs.getInt("word_id"); irs.wordId2 = rs.getInt("word2_id"); String regex = rs.getString("regstring"); Matcher m = PAT_UNPERLIZE.matcher(regex); if (m.matches()) { regex = m.group(1); } irs.pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.DOTALL); ret.add(irs); } } } return ret; } private ClientInfo clientDetector(String uaString, UdgerUaResult ret) throws SQLException { ClientInfo clientInfo = new ClientInfo(); try (ResultSet userAgentRs1 = getFirstRow(UdgerSqlQuery.SQL_CRAWLER, uaString)) { if (userAgentRs1 != null && userAgentRs1.next()) { fetchUserAgent(userAgentRs1, ret); clientInfo.classId = 99; clientInfo.clientId = -1; } else { IdRegString irs = findIdRegString(uaString, parserDbData.clientWordDetector.findWords(uaString), parserDbData.clientRegstringList); if (irs != null) { try (ResultSet userAgentRs2 = getFirstRow(UdgerSqlQuery.SQL_CLIENT, irs.id)) { if (userAgentRs2 != null && userAgentRs2.next()) { fetchUserAgent(userAgentRs2, ret); clientInfo.classId = ret.getClassId(); clientInfo.clientId = ret.getClientId(); patchVersions(irs.pattern.matcher(uaString), ret); } } } else { ret.setUaClass("Unrecognized"); ret.setUaClassCode("unrecognized"); } } } return clientInfo; } private void osDetector(String uaString, UdgerUaResult ret, ClientInfo clientInfo) throws SQLException { IdRegString irs = findIdRegString(uaString, parserDbData.osWordDetector.findWords(uaString), parserDbData.osRegstringList); if (irs != null) { try (ResultSet opSysRs = getFirstRow(UdgerSqlQuery.SQL_OS, irs.id)) { if (opSysRs != null && opSysRs.next()) { fetchOperatingSystem(opSysRs, ret); } } } else { if (clientInfo.clientId != null && clientInfo.clientId != 0) { try (ResultSet opSysRs = getFirstRow(UdgerSqlQuery.SQL_CLIENT_OS, clientInfo.clientId.toString())) { if (opSysRs != null && opSysRs.next()) { fetchOperatingSystem(opSysRs, ret); } } } } } private void deviceDetector(String uaString, UdgerUaResult ret, ClientInfo clientInfo) throws SQLException { IdRegString irs = findIdRegString(uaString, parserDbData.deviceWordDetector.findWords(uaString), parserDbData.deviceRegstringList); if (irs != null) { try (ResultSet devRs = getFirstRow(UdgerSqlQuery.SQL_DEVICE, irs.id)) { if (devRs != null && devRs.next()) { fetchDevice(devRs, ret); } } } else { if (clientInfo.classId != null && clientInfo.classId != -1) { try (ResultSet devRs = getFirstRow(UdgerSqlQuery.SQL_CLIENT_CLASS, clientInfo.classId.toString())) { if (devRs != null && devRs.next()) { fetchDevice(devRs, ret); } } } } } private void fetchDeviceBrand(String uaString, UdgerUaResult ret) throws SQLException { PreparedStatement preparedStatement = preparedStmtMap.get(UdgerSqlQuery.SQL_DEVICE_REGEX); if (preparedStatement == null) { preparedStatement = connection.prepareStatement(UdgerSqlQuery.SQL_DEVICE_REGEX); preparedStmtMap.put(UdgerSqlQuery.SQL_DEVICE_REGEX, preparedStatement); } preparedStatement.setObject(1, ret.getOsFamilyCode()); preparedStatement.setObject(2, ret.getOsCode()); try (ResultSet devRegexRs = preparedStatement.executeQuery()) { if (devRegexRs != null) { while (devRegexRs.next()) { String devId = devRegexRs.getString("id"); String regex = devRegexRs.getString("regstring"); if (devId != null && regex != null) { Pattern patRegex = getRegexFromCache(regex); Matcher matcher = patRegex.matcher(uaString); if (matcher.find()) { try (ResultSet devNameListRs = getFirstRow(UdgerSqlQuery.SQL_DEVICE_NAME_LIST, devId, matcher.group(1))) { if (devNameListRs != null && devNameListRs.next()) { ret.setDeviceMarketname(devNameListRs.getString("marketname")); ret.setDeviceBrand(devNameListRs.getString("brand")); ret.setDeviceBrandCode(devNameListRs.getString("brand_code")); ret.setDeviceBrandHomepage(devNameListRs.getString("brand_url")); ret.setDeviceBrandIcon(devNameListRs.getString("icon")); ret.setDeviceBrandIconBig(devNameListRs.getString("icon_big")); ret.setDeviceBrandInfoUrl(UDGER_UA_DEV_BRAND_LIST_URL + devNameListRs.getString("brand_code")); break; } } } } } } } } private int[] ip6ToArray(Inet6Address addr) { int ret[] = new int[8]; byte[] bytes = addr.getAddress(); for (int i = 0; i < 8; i++) { ret[i] = ((bytes[i * 2] << 8) & 0xff00) | (bytes[i * 2 + 1] & 0xff); } return ret; } private void prepare() throws SQLException { connect(); parserDbData.prepare(connection); } private void connect() throws SQLException { if (connection == null) { SQLiteConfig config = new SQLiteConfig(); config.setReadOnly(true); if (inMemoryEnabled) { // we cannot use read only for in memory DB since we need to populate this DB from the file. connection = DriverManager.getConnection("jdbc:sqlite::memory:"); File dbfile = new File(parserDbData.dbFileName); try (Statement statement = connection.createStatement()) { statement.executeUpdate("restore from " + dbfile.getPath()); } catch (Exception e) { LOG.warning("Error re-constructing in memory data base from Db file " + dbfile); } } else { connection = DriverManager.getConnection("jdbc:sqlite:" + parserDbData.dbFileName, config.toProperties()); } } } private Pattern getRegexFromCache(String regex) { SoftReference<Pattern> patRegex = regexCache.get(regex); if (patRegex == null || patRegex.get() == null) { Matcher m = PAT_UNPERLIZE.matcher(regex); if (m.matches()) { regex = m.group(1); } patRegex = new SoftReference<>(Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.DOTALL)); regexCache.put(regex, patRegex); } return patRegex.get(); } private ResultSet getFirstRow(String query, Object... params) throws SQLException { PreparedStatement preparedStatement = preparedStmtMap.get(query); if (preparedStatement == null) { preparedStatement = connection.prepareStatement(query); preparedStmtMap.put(query, preparedStatement); } for (int i = 0; i < params.length; i++) { preparedStatement.setObject(i + 1, params[i]); } preparedStatement.setMaxRows(1); return preparedStatement.executeQuery(); } private void fetchUserAgent(ResultSet rs, UdgerUaResult ret) throws SQLException { ret.setClassId(rs.getInt("class_id")); ret.setClientId(rs.getInt("client_id")); ret.setCrawlerCategory(nvl(rs.getString("crawler_category"))); ret.setCrawlerCategoryCode(nvl(rs.getString("crawler_category_code"))); ret.setCrawlerLastSeen(nvl(rs.getString("crawler_last_seen"))); ret.setCrawlerRespectRobotstxt(nvl(rs.getString("crawler_respect_robotstxt"))); ret.setUa(nvl(rs.getString("ua"))); ret.setUaClass(nvl(rs.getString("ua_class"))); ret.setUaClassCode(nvl(rs.getString("ua_class_code"))); ret.setUaEngine(nvl(rs.getString("ua_engine"))); ret.setUaFamily(nvl(rs.getString("ua_family"))); ret.setUaFamilyCode(nvl(rs.getString("ua_family_code"))); ret.setUaFamilyHomepage(nvl(rs.getString("ua_family_homepage"))); ret.setUaFamilyIcon(nvl(rs.getString("ua_family_icon"))); ret.setUaFamilyIconBig(nvl(rs.getString("ua_family_icon_big"))); ret.setUaFamilyInfoUrl(nvl(rs.getString("ua_family_info_url"))); ret.setUaFamilyVendor(nvl(rs.getString("ua_family_vendor"))); ret.setUaFamilyVendorCode(nvl(rs.getString("ua_family_vendor_code"))); ret.setUaFamilyVendorHomepage(nvl(rs.getString("ua_family_vendor_homepage"))); ret.setUaUptodateCurrentVersion(nvl(rs.getString("ua_uptodate_current_version"))); ret.setUaVersion(nvl(rs.getString("ua_version"))); ret.setUaVersionMajor(nvl(rs.getString("ua_version_major"))); } private void fetchOperatingSystem(ResultSet rs, UdgerUaResult ret) throws SQLException { ret.setOsFamily(nvl(rs.getString("os_family"))); ret.setOs(nvl(rs.getString("os"))); ret.setOsCode(nvl(rs.getString("os_code"))); ret.setOsFamilyCode(nvl(rs.getString("os_family_code"))); ret.setOsFamilyVendorHomepage(nvl(rs.getString("os_family_vendor_homepage"))); ret.setOsFamilyVendor(nvl(rs.getString("os_family_vendor"))); ret.setOsFamilyVendorCode(nvl(rs.getString("os_family_vendor_code"))); ret.setOsHomePage(nvl(rs.getString("os_home_page"))); ret.setOsIcon(nvl(rs.getString("os_icon"))); ret.setOsIconBig(nvl(rs.getString("os_icon_big"))); ret.setOsInfoUrl(nvl(rs.getString("os_info_url"))); } private void fetchDevice(ResultSet rs, UdgerUaResult ret) throws SQLException { ret.setDeviceClass(nvl(rs.getString("device_class"))); ret.setDeviceClassCode(nvl(rs.getString("device_class_code"))); ret.setDeviceClassIcon(nvl(rs.getString("device_class_icon"))); ret.setDeviceClassIconBig(nvl(rs.getString("device_class_icon_big"))); ret.setDeviceClassInfoUrl(nvl(rs.getString("device_class_info_url"))); } private void patchVersions(Matcher lastPatternMatcher, UdgerUaResult ret) { if (lastPatternMatcher != null) { String version = ""; if (lastPatternMatcher.groupCount() >= 1) { version = lastPatternMatcher.group(1); if (version == null) { version = ""; } } ret.setUaVersion(version); String versionSegments[] = version.split("\\."); if (versionSegments.length > 0) { ret.setUaVersionMajor(version.split("\\.")[0]); } else { ret.setUaVersionMajor(""); } ret.setUa((ret.getUa() != null ? ret.getUa() : "") + " " + version); } else { ret.setUaVersion(""); ret.setUaVersionMajor(""); } } private void fetchUdgerIp(ResultSet rs, UdgerIpResult ret) throws SQLException { ret.setCrawlerCategory(nvl(rs.getString("crawler_category"))); ret.setCrawlerCategoryCode(nvl(rs.getString("crawler_category_code"))); ret.setCrawlerFamily(nvl(rs.getString("crawler_family"))); ret.setCrawlerFamilyCode(nvl(rs.getString("crawler_family_code"))); ret.setCrawlerFamilyHomepage(nvl(rs.getString("crawler_family_homepage"))); ret.setCrawlerFamilyIcon(nvl(rs.getString("crawler_family_icon"))); ret.setCrawlerFamilyInfoUrl(nvl(rs.getString("crawler_family_info_url"))); ret.setCrawlerFamilyVendor(nvl(rs.getString("crawler_family_vendor"))); ret.setCrawlerFamilyVendorCode(nvl(rs.getString("crawler_family_vendor_code"))); ret.setCrawlerFamilyVendorHomepage(nvl(rs.getString("crawler_family_vendor_homepage"))); ret.setCrawlerLastSeen(nvl(rs.getString("crawler_last_seen"))); ret.setCrawlerName(nvl(rs.getString("crawler_name"))); ret.setCrawlerRespectRobotstxt(nvl(rs.getString("crawler_respect_robotstxt"))); ret.setCrawlerVer(nvl(rs.getString("crawler_ver"))); ret.setCrawlerVerMajor(nvl(rs.getString("crawler_ver_major"))); ret.setIpCity(nvl(rs.getString("ip_city"))); ret.setIpClassification(nvl(rs.getString("ip_classification"))); ret.setIpClassificationCode(nvl(rs.getString("ip_classification_code"))); ret.setIpCountry(nvl(rs.getString("ip_country"))); ret.setIpCountryCode(nvl(rs.getString("ip_country_code"))); ret.setIpHostname(nvl(rs.getString("ip_hostname"))); ret.setIpLastSeen(nvl(rs.getString("ip_last_seen"))); } private String nvl(String v) { return v != null ? v : ""; } private void fetchDataCenter(ResultSet rs, UdgerIpResult ret) throws SQLException { ret.setDataCenterHomePage(nvl(rs.getString("datacenter_homepage"))); ret.setDataCenterName(nvl(rs.getString("datacenter_name"))); ret.setDataCenterNameCode(nvl(rs.getString("datacenter_name_code"))); } }
package org.weakref.jmx; public class JmxException extends RuntimeException { private static final long serialVersionUID = 1L; public enum Reason { INVALID_ANNOTATION, MALFORMED_OBJECT_NAME, INSTANCE_ALREADY_EXISTS, INSTANCE_NOT_FOUND, MBEAN_REGISTRATION } private final Reason reason; JmxException(final Reason reason, final String message, final Object ... args) { super(String.format(message, args)); this.reason = reason; } JmxException(final Reason reason, final Throwable cause, final String message, final Object ... args) { super(String.format(message, args), cause); this.reason = reason; } public Reason getReason() { return reason; } }
package roart.service; import roart.model.ResultItem; import javax.servlet.http.*; import java.util.Vector; import java.util.Enumeration; import java.util.List; import java.util.ArrayList; import java.util.TreeMap; import java.util.Set; import java.util.TreeSet; import java.util.HashSet; import java.util.HashMap; import java.util.Map; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.TimeUnit; import java.io.*; import roart.dir.Traverse; import roart.queue.ClientQueueElement; import roart.model.FileLocation; import roart.model.FileObject; import roart.model.IndexFiles; import roart.queue.Queues; import roart.thread.ControlRunner; import roart.thread.IndexRunner; import roart.thread.OtherRunner; import roart.thread.TikaRunner; import roart.content.OtherHandler; import roart.content.ClientHandler; import roart.thread.ClientRunner; import roart.thread.DbRunner; import roart.dao.FileSystemDao; import roart.dao.SearchDao; import roart.dao.IndexFilesDao; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class ControlService { private Log log = LogFactory.getLog(this.getClass()); private static int dirsizelimit = 100; // called from ui // returns list: new file public void traverse(String add) throws Exception { ClientQueueElement e = new ClientQueueElement(com.vaadin.ui.UI.getCurrent(), "filesystem", add, null, null, null, false, false); Queues.clientQueue.add(e); } public Set<String> traverse(String add, Set<IndexFiles> newset, List<ResultItem> retList, Set<String> notfoundset, boolean newmd5, boolean nodbchange) throws Exception { Map<String, HashSet<String>> dirset = new HashMap<String, HashSet<String>>(); Set<String> filesetnew2 = new HashSet<String>(); Set<String> filesetnew = Traverse.doList(add, newset, filesetnew2, dirset, null, notfoundset, newmd5, false, nodbchange); for (String s : filesetnew2) { retList.add(new ResultItem(s)); } return filesetnew; } // called from ui // returns list: new file public void traverse() throws Exception { ClientQueueElement e = new ClientQueueElement(com.vaadin.ui.UI.getCurrent(), "filesystem", null, null, null, null, false, false); Queues.clientQueue.add(e); } public Set<String> traverse(Set<IndexFiles> newindexset, List<ResultItem> retList, Set<String> notfoundset, boolean newmd5, boolean nodbchange) throws Exception { Set<String> filesetnew = new HashSet<String>(); retList.addAll(filesystem(newindexset, filesetnew, null, notfoundset, newmd5, nodbchange)); return filesetnew; } static String[] dirlist = null; static String[] dirlistnot = null; static public String nodename = "localhost"; public static void parseconfig() { System.out.println("config2 parsed"); //log.info("config2 parsed"); nodename = roart.util.Prop.getProp().getProperty("nodename"); if (nodename == null || nodename.length() == 0) { nodename = "localhost"; } String dirliststr = roart.util.Prop.getProp().getProperty("dirlist"); String dirlistnotstr = roart.util.Prop.getProp().getProperty("dirlistnot"); dirlist = dirliststr.split(","); dirlistnot = dirlistnotstr.split(","); } private List<ResultItem> filesystem(Set<IndexFiles> indexnewset, Set<String> filesetnew, Set<String> newset, Set<String> notfoundset, boolean newmd5, boolean nodbchange) { List<ResultItem> retList = new ArrayList<ResultItem>(); Map<String, HashSet<String>> dirset = new HashMap<String, HashSet<String>>(); try { for (int i = 0; i < dirlist.length; i ++) { Set<String> filesetnew2 = Traverse.doList(dirlist[i], indexnewset, newset, dirset, dirlistnot, notfoundset, newmd5, false, nodbchange); filesetnew.addAll(filesetnew2); } } catch (Exception e) { log.info(e); log.error("Exception", e); } return retList; } // called from ui public void overlapping() { ClientQueueElement e = new ClientQueueElement(com.vaadin.ui.UI.getCurrent(), "overlapping", null, null, null, null, false, false); Queues.clientQueue.add(e); } public List<List> overlappingDo() { List<ResultItem> retList = new ArrayList<ResultItem>(); List<ResultItem> retList2 = new ArrayList<ResultItem>(); ResultItem ri = new ResultItem(); ri.add("Percent"); ri.add("Count"); ri.add("Directory 1"); ri.add("Directory 2"); retList.add(ri); ri = new ResultItem(); ri.add("Percent"); ri.add("Count"); ri.add("Count 2"); ri.add("Directory"); retList2.add(ri); Set<String> filesetnew = new HashSet<String>(); Map<Integer, List<String[]>> sortlist = new TreeMap<Integer, List<String[]>>(); Map<Integer, List<String[]>> sortlist2 = new TreeMap<Integer, List<String[]>>(); Map<String, HashSet<String>> dirset = new HashMap<String, HashSet<String>>(); Map<String, HashSet<String>> fileset = new HashMap<String, HashSet<String>>(); // filesetnew/2 will be empty before and after // dirset will contain a map of directories, and the md5 files is contains // fileset will contain a map of md5 and the directories it has files in try { Set<String> filesetnew2 = Traverse.doList2(dirset, fileset); filesetnew.addAll(filesetnew2); } catch (Exception e) { log.info(e); log.error("Exception", e); } log.info("dirs " + dirset.size()); log.info("files " + fileset.size()); // start at i+1 to avoid comparing twice List<String> keyList = new ArrayList<String>(dirset.keySet()); for (int i = 0; i < keyList.size(); i++ ) { if (dirset.get(keyList.get(i)).size() < dirsizelimit) { continue; } for (int j = i+1; j < keyList.size(); j++ ) { // set1,3 with md5 files contained in dir number i // set2,4 with md5 files contained in dir number j HashSet<String> set1 = (HashSet<String>) dirset.get(keyList.get(i)).clone(); HashSet<String> set2 = (HashSet<String>) dirset.get(keyList.get(j)).clone(); int size0 = set1.size(); if (set2.size() > size0) { size0 = set2.size(); } set1.retainAll(set2); // sum int size = set1.size(); if (size0 == 0) { size0 = 1000000; log.error("size0"); } // add result int ratio = (int) (100*size/size0); if (ratio > 50 && size > 4) { Integer intI = new Integer(ratio); String sizestr = "" + size; sizestr = " ".substring(sizestr.length()) + sizestr; String[] str = new String[]{ sizestr, keyList.get(i), keyList.get(j)}; // + " " + set1; List<String[]> strSet = sortlist.get(intI); if (strSet == null) { strSet = new ArrayList<String[]>(); } strSet.add(str); sortlist.put(intI, strSet); } } } // get biggest overlap for (Integer intI : sortlist.keySet()) { for (String[] strs : sortlist.get(intI)) { ResultItem ri2 = new ResultItem(); ri2.add("" + intI.intValue()); for (String str : strs) { ri2.add(str); } retList.add(ri2); } } for (int i = 0; i < keyList.size(); i++ ) { int fileexist = 0; String dirname = keyList.get(i); Set<String> dirs = dirset.get(dirname); int dirsize = dirs.size(); for (String md5 : dirs) { Set<String> files = fileset.get(md5); if (files != null && files.size() >= 2) { fileexist++; } } int ratio = (int) (100*fileexist/dirsize); // overlapping? if (ratio > 50 && dirsize > dirsizelimit) { Integer intI = new Integer(ratio); String sizestr = "" + dirsize; sizestr = " ".substring(sizestr.length()) + sizestr; String[] str = new String[]{sizestr, "" + fileexist, dirname}; List<String[]> strSet = sortlist2.get(intI); if (strSet == null) { strSet = new ArrayList<String[]>(); } strSet.add(str); sortlist2.put(intI, strSet); } } for (Integer intI : sortlist2.keySet()) { for (String[] strs : sortlist2.get(intI)) { ResultItem ri2 = new ResultItem(); ri2.add("" + intI.intValue()); for (String str : strs) { ri2.add(str); } retList2.add(ri2); } } List<List> retlistlist = new ArrayList<List>(); retlistlist.add(retList); retlistlist.add(retList2); return retlistlist; } // called from ui // returns list: indexed file list // returns list: tika timeout // returns list: not indexed // returns list: deleted public void index(String suffix) throws Exception { ClientQueueElement e = new ClientQueueElement(com.vaadin.ui.UI.getCurrent(), "reindexsuffix", null, suffix, null, null, true, false); Queues.clientQueue.add(e); } // called from ui // returns list: indexed file list // returns list: tika timeout // returns list: file does not exist // returns list: not indexed public void index(String add, boolean reindex) throws Exception { ClientQueueElement e = new ClientQueueElement(com.vaadin.ui.UI.getCurrent(), "index", add, null, null, null, reindex, false); Queues.clientQueue.add(e); } // called from ui // returns list: indexed file list // returns list: tika timeout // returns list: not indexed public void reindexdatelower(String date, boolean reindex) throws Exception { ClientQueueElement e = new ClientQueueElement(com.vaadin.ui.UI.getCurrent(), "reindexdate", null, null, date, null, reindex, false); Queues.clientQueue.add(e); } public void reindexdatehigher(String date, boolean reindex) throws Exception { ClientQueueElement e = new ClientQueueElement(com.vaadin.ui.UI.getCurrent(), "reindexdate", null, null, null, date, reindex, false); Queues.clientQueue.add(e); } public List<List> clientDo(ClientQueueElement el) throws Exception { String function = el.function; String filename = el.file; boolean reindex = el.reindex; boolean newmd5 = el.md5change; log.info("function " + function + " " + filename + " " + reindex); Set<List> retlistset = new HashSet<List>(); List<List> retlistlist = new ArrayList<List>(); List<ResultItem> retList = new ArrayList<ResultItem>(); retList.add(IndexFiles.getHeader()); List<ResultItem> retTikaTimeoutList = new ArrayList<ResultItem>(); retTikaTimeoutList.add(new ResultItem("Tika timeout")); List<ResultItem> retNotList = new ArrayList<ResultItem>(); retNotList.add(IndexFiles.getHeader()); List<ResultItem> retNewFilesList = new ArrayList<ResultItem>(); retNewFilesList.add(new ResultItem("New file")); List<ResultItem> retDeletedList = new ArrayList<ResultItem>(); retDeletedList.add(new ResultItem("Deleted")); List<ResultItem> retNotExistList = new ArrayList<ResultItem>(); retNotExistList.add(new ResultItem("File does not exist")); Set<String> notfoundset = new HashSet<String>(); Set<String> filesetnew = new HashSet<String>(); Set<IndexFiles> indexnewset = new HashSet<IndexFiles>(); Set<String> fileset = new HashSet<String>(); Set<String> md5set = new HashSet<String>(); List<List> retlisttmp = null; // filesystem // reindexsuffix // index // reindexdate // filesystemlucenenew DbRunner.doupdate = false; if (function.equals("filesystem") || function.equals("filesystemlucenenew") || (function.equals("index") && filename != null /*&& !reindex*/)) { if (filename != null) { filesetnew = traverse(filename, indexnewset, retNewFilesList, notfoundset, newmd5, false); } else { filesetnew = traverse(indexnewset, retNewFilesList, notfoundset, newmd5, false); } for (String file : notfoundset) { retNotExistList.add(new ResultItem(file)); } if (function.equals("filesystem")) { IndexFilesDao.commit(); retlistlist.add(retNewFilesList); DbRunner.doupdate = true; return retlistlist; } } Collection<IndexFiles> indexes = null; if (function.equals("filesystemlucenenew")) { indexes = indexnewset; } else if (function.equals("index") && filename != null && !reindex) { Set<IndexFiles> indexset = new HashSet<IndexFiles>(); for (String name : filesetnew) { String md5 = IndexFilesDao.getMd5ByFilename(name); IndexFiles index = IndexFilesDao.getByMd5(md5); indexset.add(index); } indexes = indexset; } else { indexes = IndexFilesDao.getAll(); } DbRunner.doupdate = true; String maxfailedStr = roart.util.Prop.getProp().getProperty("failedlimit"); int maxfailed = new Integer(maxfailedStr).intValue(); String maxStr = roart.util.Prop.getProp().getProperty("reindexlimit"); int max = new Integer(maxStr).intValue(); Set<IndexFiles> toindexset = new HashSet<IndexFiles>(); int i = 0; for (IndexFiles index : indexes) { // skip if indexed already, and no reindex wanted Boolean indexed = index.getIndexed(); if (indexed != null) { if (!reindex && indexed.booleanValue()) { continue; } } String md5 = index.getMd5(); if (maxfailed > index.getFailed().intValue()) { continue; } if (function.equals("reindexdate")) { i += Traverse.reindexdateFilter(el, index, toindexset, fileset, md5set); } if (function.equals("reindexsuffix")) { i += Traverse.reindexsuffixFilter(el, index, el.suffix, toindexset, fileset, md5set); } if (function.equals("index") || function.equals("filesystemlucenenew")) { i += Traverse.indexnoFilter(el, index, reindex, toindexset, fileset, md5set); } if (reindex && max > 0 && i > max) { break; } } Map<String, String> filesMapMd5 = new HashMap<String, String>(); Map<String, Boolean> indexMap = new HashMap<String, Boolean>(); for (IndexFiles index : toindexset) { String md5 = index.getMd5(); String name = Traverse.getExistingLocalFile(index); if (name == null) { log.error("filename should not be null " + md5); continue; } filesMapMd5.put(md5, name); indexMap.put(md5, index.getIndexed()); } for (String md5 : filesMapMd5.keySet()) { Traverse.indexsingle(retList, retNotList, md5, indexMap, filesMapMd5, reindex, 0); } while ((Queues.queueSize() + Queues.runSize()) > 0) { TimeUnit.SECONDS.sleep(60); Queues.queueStat(); } for (String ret : Queues.tikaTimeoutQueue) { retTikaTimeoutList.add(new ResultItem(ret)); } Queues.resetTikaTimeoutQueue(); IndexFilesDao.commit(); retlistlist.add(retList); retlistlist.add(retNotList); retlistlist.add(retNewFilesList); retlistlist.add(retDeletedList); retlistlist.add(retTikaTimeoutList); retlistlist.add(retNotExistList); return retlistlist; } // outdated, did run once, had a bug which made duplicates public List<String> cleanup() { List<String> retlist = new ArrayList<String>(); try { return roart.jpa.SearchLucene.removeDuplicate(); } catch (Exception e) { log.info(e); log.error("Exception", e); } return retlist; } // outdated, used once, when bug added filename instead of md5 public List<String> cleanup2() { List<String> retlist = new ArrayList<String>(); try { //return roart.jpa.SearchLucene.cleanup2(); } catch (Exception e) { log.info(e); log.error("Exception", e); } return retlist; } // old, probably oudated by overlapping? public List<String> cleanupfs(String dirname) { //List<String> retlist = new ArrayList<String>(); Set<String> filesetnew = new HashSet<String>(); try { String[] dirlist = { dirname }; for (int i = 0; i < dirlist.length; i ++) { Set<String> filesetnew2 = Traverse.dupdir(dirlist[i]); filesetnew.addAll(filesetnew2); } } catch (Exception e) { log.info(e); log.error("Exception", e); } return new ArrayList<String>(filesetnew); } // called from ui public void memoryusage() { ClientQueueElement e = new ClientQueueElement(com.vaadin.ui.UI.getCurrent(), "memoryusage", null, null, null, null, false, false); Queues.clientQueue.add(e); } public List<List> memoryusageDo() { List<ResultItem> retlist = new ArrayList<ResultItem>(); try { Runtime runtime = Runtime.getRuntime(); long maxMemory = runtime.maxMemory(); long allocatedMemory = runtime.totalMemory(); long freeMemory = runtime.freeMemory(); java.text.NumberFormat format = java.text.NumberFormat.getInstance(); retlist.add(new ResultItem("free memory: " + format.format(freeMemory / 1024))); retlist.add(new ResultItem("allocated memory: " + format.format(allocatedMemory / 1024))); retlist.add(new ResultItem("max memory: " + format.format(maxMemory / 1024))); retlist.add(new ResultItem("total free memory: " + format.format((freeMemory + (maxMemory - allocatedMemory)) / 1024))); } catch (Exception e) { log.info(e); log.error("Exception", e); } List<List> retlistlist = new ArrayList<List>(); retlistlist.add(retlist); return retlistlist; } // called from ui // returns list: not indexed // returns list: another with columns public void notindexed() throws Exception { ClientQueueElement e = new ClientQueueElement(com.vaadin.ui.UI.getCurrent(), "notindexed", null, null, null, null, false, false); Queues.clientQueue.add(e); } public List<List> notindexedDo() throws Exception { List<List> retlistlist = new ArrayList<List>(); List<ResultItem> retlist = new ArrayList<ResultItem>(); List<ResultItem> retlist2 = new ArrayList<ResultItem>(); ResultItem ri3 = new ResultItem(); ri3.add("Column 1"); ri3.add("Column 2"); ri3.add("Column 3"); retlist2.add(ri3); List<ResultItem> retlistyes = null; try { retlist.addAll(Traverse.notindexed()); retlistyes = Traverse.indexed(); Map<String, Integer> plusretlist = new HashMap<String, Integer>(); Map<String, Integer> plusretlistyes = new HashMap<String, Integer>(); for(ResultItem ri : retlist) { if (ri == retlist.get(0)) { continue; } String filename = ri.get().get(10); if (filename == null) { continue; } int ind = filename.lastIndexOf("."); if (ind == -1 || ind <= filename.length() - 6) { continue; } String suffix = filename.substring(ind+1); Integer i = plusretlist.get(suffix); if (i == null) { i = new Integer(0); } i++; plusretlist.put(suffix, i); } for(ResultItem ri : retlistyes) { String filename = ri.get().get(0); // or for a whole list? if (filename == null) { continue; } int ind = filename.lastIndexOf("."); if (ind == -1 || ind <= filename.length() - 6) { continue; } String suffix = filename.substring(ind+1); Integer i = plusretlistyes.get(suffix); if (i == null) { i = new Integer(0); } i++; plusretlistyes.put(suffix, i); } log.info("size " + plusretlist.size()); log.info("sizeyes " + plusretlistyes.size()); for(String string : plusretlist.keySet()) { ResultItem ri2 = new ResultItem(); ri2.add("Format"); ri2.add(string); ri2.add("" + plusretlist.get(string).intValue()); retlist2.add(ri2); } for(String string : plusretlistyes.keySet()) { ResultItem ri2 = new ResultItem(); ri2.add("Formatyes"); ri2.add(string); ri2.add("" + plusretlistyes.get(string).intValue()); retlist2.add(ri2); } } catch (Exception e) { log.info(e); log.error("Exception", e); } log.info("sizes " + retlist.size() + " " + retlist2.size() + " " + System.currentTimeMillis()); retlistlist.add(retlist); retlistlist.add(retlist2); return retlistlist; } // called from ui // returns list: indexed file list // returns list: tika timeout // returns list: new file // returns list: file does not exist // returns list: not indexed public void filesystemlucenenew() throws Exception { ClientQueueElement e = new ClientQueueElement(com.vaadin.ui.UI.getCurrent(), "filesystemlucenenew", null, null, null, null, false, false); Queues.clientQueue.add(e); } public void filesystemlucenenew(String add, boolean md5checknew) throws Exception { ClientQueueElement e = new ClientQueueElement(com.vaadin.ui.UI.getCurrent(), "filesystemlucenenew", add, null, null, null, false, md5checknew); Queues.clientQueue.add(e); } public void dbindex(String md5) throws Exception { ClientQueueElement e = new ClientQueueElement(com.vaadin.ui.UI.getCurrent(), "dbindex", md5, null, null, null, false, false); // dumb overload habit Queues.clientQueue.add(e); } public List<List> dbindexDo(ClientQueueElement el) throws Exception { String function = el.function; String md5 = el.file; log.info("function " + function + " " + md5); List<List> retlistlist = new ArrayList<List>(); List<ResultItem> indexList = new ArrayList<ResultItem>(); indexList.add(IndexFiles.getHeader()); List<ResultItem> indexfilesList = new ArrayList<ResultItem>(); indexfilesList.add(new ResultItem("Files")); List<ResultItem> filesList = new ArrayList<ResultItem>(); filesList.add(new ResultItem("Files")); IndexFiles index = IndexFilesDao.getByMd5(md5); if (index != null) { indexList.add(IndexFiles.getResultItem(index, "n/a")); Set<FileLocation> files = index.getFilelocations(); if (files != null) { for (FileLocation filename : files) { indexfilesList.add(new ResultItem(filename.toString())); } } Set<FileLocation> flSet = IndexFilesDao.getFilelocationsByMd5(md5); if (flSet != null) { for (FileLocation fl : flSet) { if (fl == null) { filesList.add(new ResultItem("")); } else { filesList.add(new ResultItem(fl.toString())); } } } } retlistlist.add(indexList); retlistlist.add(indexfilesList); retlistlist.add(filesList); return retlistlist; } public void dbsearch(String md5) throws Exception { ClientQueueElement e = new ClientQueueElement(com.vaadin.ui.UI.getCurrent(), "dbsearch", md5, null, null, null, false, false); // dumb overload habit Queues.clientQueue.add(e); } public List<List> dbsearchDo(ClientQueueElement el) throws Exception { String function = el.function; String searchexpr = el.file; int i = searchexpr.indexOf(":"); log.info("function " + function + " " + searchexpr); List<List> retlistlist = new ArrayList<List>(); if (i < 0) { return retlistlist; } String field = searchexpr.substring(0, i); String text = searchexpr.substring(i + 1); List<ResultItem> indexList = new ArrayList<ResultItem>(); indexList.add(IndexFiles.getHeader()); List<IndexFiles> indexes = IndexFilesDao.getAll(); for (IndexFiles index : indexes) { boolean match = false; if (field.equals("indexed")) { Boolean indexedB = index.getIndexed(); boolean ind = indexedB != null && indexedB.booleanValue(); if (ind && text.equals("true")) { match = true; } if (!ind && text.equals("false")) { match = true; } } if (field.equals("convertsw")) { String convertsw = index.getConvertsw(); if (convertsw != null) { match = convertsw.contains(text); } } if (field.equals("classification")) { String classification = index.getClassification(); if (classification != null) { match = classification.contains(text); } } if (field.equals("failedreason")) { String failedreason = index.getFailedreason(); if (failedreason != null) { match = failedreason.contains(text); } } if (field.equals("noindexreason")) { String noindexreason = index.getNoindexreason(); if (noindexreason != null) { match = noindexreason.contains(text); } } if (field.equals("timeoutreason")) { String timeoutreason = index.getTimeoutreason(); if (timeoutreason != null) { match = timeoutreason.contains(text); } } if (match) { indexList.add(IndexFiles.getResultItem(index, "n/a")); } } retlistlist.add(indexList); return retlistlist; } private static TikaRunner tikaRunnable = null; public static Thread tikaWorker = null; private static IndexRunner indexRunnable = null; public static Thread indexWorker = null; private static OtherRunner otherRunnable = null; public static Thread otherWorker = null; private static ClientRunner clientRunnable = null; public static Thread clientWorker = null; private static DbRunner dbRunnable = null; public static Thread dbWorker = null; private static ControlRunner controlRunnable = null; private static Thread controlWorker = null; public void startThreads() { if (tikaRunnable == null) { startTikaWorker(); } if (indexRunnable == null) { startIndexWorker(); } if (otherRunnable == null) { startOtherWorker(); } if (clientRunnable == null) { startClientWorker(); } if (dbRunnable == null) { startDbWorker(); } if (controlRunnable == null) { startControlWorker(); } } private void startControlWorker() { controlRunnable = new ControlRunner(); controlWorker = new Thread(controlRunnable); controlWorker.setName("ControlWorker"); controlWorker.start(); log.info("starting control worker"); } public void startTikaWorker() { String timeoutstr = roart.util.Prop.getProp().getProperty("tikatimeout"); int timeout = new Integer(timeoutstr).intValue(); TikaRunner.timeout = timeout; tikaRunnable = new TikaRunner(); tikaWorker = new Thread(tikaRunnable); tikaWorker.setName("TikaWorker"); tikaWorker.start(); log.info("starting tika worker"); } public void startIndexWorker() { indexRunnable = new IndexRunner(); indexWorker = new Thread(indexRunnable); indexWorker.setName("IndexWorker"); indexWorker.start(); log.info("starting index worker"); } public void startOtherWorker() { String timeoutstr = roart.util.Prop.getProp().getProperty("othertimeout"); int timeout = new Integer(timeoutstr).intValue(); OtherHandler.timeout = timeout; otherRunnable = new OtherRunner(); otherWorker = new Thread(otherRunnable); otherWorker.setName("OtherWorker"); otherWorker.start(); log.info("starting other worker"); } public void startClientWorker() { clientRunnable = new ClientRunner(); clientWorker = new Thread(clientRunnable); clientWorker.setName("ClientWorker"); clientWorker.start(); log.info("starting client worker"); } public void startDbWorker() { dbRunnable = new DbRunner(); dbWorker = new Thread(dbRunnable); dbWorker.setName("DbWorker"); dbWorker.start(); log.info("starting db worker"); } private List<List> mergeListSet(Set<List> listSet, int size) { List<List> retlistlist = new ArrayList<List>(); for (int i = 0 ; i < size ; i++ ) { List<ResultItem> retlist = new ArrayList<ResultItem>(); retlistlist.add(retlist); } for (List<List> listArray : listSet) { for (int i = 0 ; i < size ; i++ ) { retlistlist.get(i).addAll(listArray.get(i)); } } return retlistlist; } public void consistentclean(boolean clean) { // TODO Auto-generated method stub ClientQueueElement e = new ClientQueueElement(com.vaadin.ui.UI.getCurrent(), "consistentclean", null, null, null, null, clean, false); // more dumb overload Queues.clientQueue.add(e); } public List<List> consistentcleanDo(ClientQueueElement el) { boolean clean = el.reindex; List<ResultItem> delList = new ArrayList<ResultItem>(); List<ResultItem> nonexistList = new ArrayList<ResultItem>(); List<ResultItem> newList = new ArrayList<ResultItem>(); ResultItem ri = new ResultItem("Filename delete"); delList.add(ri); ri = new ResultItem("Filename nonexist"); nonexistList.add(ri); ri = new ResultItem("Filename new"); newList.add(ri); Set<String> delfileset = new HashSet<String>(); List<IndexFiles> indexes; try { indexes = IndexFilesDao.getAll(); log.info("size " + indexes.size()); for (IndexFiles index : indexes) { for (FileLocation fl : index.getFilelocations()) { if (fl.isLocal()) { String filename = fl.getFilename(); FileObject fo = FileSystemDao.get(filename); if (!FileSystemDao.exists(fo)) { delList.add(new ResultItem(filename)); delfileset.add(filename); } } } } Set<String> filesetnew = new HashSet<String>(); // just a dir list Set<String> newset = new HashSet<String>(); Set<String> notfoundset = new HashSet<String>(); filesystem(null, filesetnew, newset, notfoundset, false, true); for (String file : newset) { newList.add(new ResultItem(file)); } for (String file : notfoundset) { nonexistList.add(new ResultItem(file)); } if (clean) { for (String filename : delfileset) { String md5 = IndexFilesDao.getMd5ByFilename(filename); if (md5 != null) { IndexFiles ifile = IndexFilesDao.getByMd5(md5); FileLocation fl = new FileLocation(filename); boolean removed = ifile.removeFilelocation(fl); //log.info("fls2 size " + removed + ifile.getFilelocations().size()); } else { log.info("trying the hard way, no md5 for" + filename); for (IndexFiles index : indexes) { FileLocation fl = new FileLocation(filename); if (index.getFilelocations().contains(fl)) { boolean removed = index.removeFilelocation(fl); //log.info("fls3 size " + removed + index.getFilelocations().size()); } } } } IndexFilesDao.commit(); } } catch (Exception e) { log.info("Exception", e); } List<List> retlistlist = new ArrayList<List>(); retlistlist.add(delList); retlistlist.add(nonexistList); retlistlist.add(newList); return retlistlist; } }
package seedu.todo.models; import java.io.IOException; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import seedu.todo.commons.exceptions.CannotRedoException; import seedu.todo.commons.exceptions.CannotUndoException; import seedu.todo.storage.JsonStorage; import seedu.todo.storage.Storage; public class TodoListDB { private static TodoListDB instance = null; private static Storage storage = new JsonStorage(); private Set<Task> tasks = new LinkedHashSet<Task>(); private Set<Event> events = new LinkedHashSet<Event>(); protected TodoListDB() { // Prevent instantiation. } public List<Task> getAllTasks() { return new ArrayList<Task>(tasks); } public int countIncompleteTasks() { int count = 0; for (Task task : tasks) { if (!task.isCompleted()) count++; } return count; } public int countOverdueTasks() { LocalDateTime now = LocalDateTime.now(); int count = 0; for (Task task : tasks) { if (!task.isCompleted() && task.getDueDate().compareTo(now) < 0) count++; } return count; } public List<Event> getAllEvents() { return new ArrayList<Event>(events); } public Task createTask() { Task task = new Task(); tasks.add(task); return task; } public boolean destroyTask(Task task) { tasks.remove(task); return save(); } public Event createEvent() { Event event = new Event(); events.add(event); return event; } public boolean destroyEvent(Event event) { events.remove(event); return save(); } public static TodoListDB getInstance() { if (instance == null) { instance = new TodoListDB(); } return instance; } public boolean save() { try { storage.save(this); return true; } catch (IOException e) { return false; } } public boolean load() { try { instance = storage.load(); return true; } catch (IOException e) { return false; } } public int undoSize() { return storage.undoSize(); } public boolean undo() { try { instance = storage.undo(); return true; } catch (CannotUndoException | IOException e) { return false; } } public int redoSize() { return storage.redoSize(); } public boolean redo() { try { instance = storage.redo(); return true; } catch (CannotRedoException | IOException e) { return false; } } }
package system.mturk; import com.amazonaws.mturk.addon.BatchItemCallback; import com.amazonaws.mturk.requester.*; import com.amazonaws.mturk.requester.Comparator; import com.amazonaws.mturk.service.axis.RequesterService; import com.amazonaws.mturk.service.exception.InternalServiceException; import com.amazonaws.mturk.service.exception.ObjectAlreadyExistsException; import com.amazonaws.mturk.service.exception.ObjectDoesNotExistException; import com.amazonaws.mturk.service.exception.ServiceException; import csv.CSVLexer; import csv.CSVParser; import org.apache.log4j.Logger; import survey.Survey; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.text.*; import java.util.*; import qc.QC; import survey.SurveyException; import survey.SurveyResponse; /** * ResponseManager communicates with Mechanical Turk. This class contains methods to query the status of various HITs, * update current HITs, and pull results into a local database of responses for use inside another program. * */ public class ResponseManager { private static final Logger LOGGER = Logger.getLogger(ResponseManager.class); protected static RequesterService service = SurveyPoster.service; final protected static long maxAutoApproveDelay = 2592000l; final private static int maxwaittime = 60; /** * A map of the surveys launched during this session to their results. */ public static HashMap<String, Record> manager = new HashMap<String, Record>(); protected static void chill(int seconds){ try { Thread.sleep(seconds*1000); } catch (InterruptedException e) {} } private static boolean overTime(String name, int waittime){ if (waittime > ResponseManager.maxwaittime){ LOGGER.warn(String.format("Wait time in %s has exceeded max wait time. Cancelling request.", name)); return true; } else return false; } // public static HIT getHIT(String hitid){ while (true) { synchronized (service) { try { HIT hit = service.getHIT(hitid); return hit; } catch (InternalServiceException ise) { LOGGER.warn(ise); chill(2); } } } } private static Assignment[] getAllAssignmentsForHIT(String hitid) { while (true) { synchronized (service) { try { Assignment[] assignments = service.getAllAssignmentsForHIT(hitid); return assignments; } catch (InternalServiceException ise) { LOGGER.warn(ise); chill(2); } } } } private static HIT[] searchAllHITs () { int waittime = 1; while (true) { synchronized (service) { try{ HIT[] hits = service.searchAllHITs(); System.out.println(String.format("Found %d HITs", hits.length)); LOGGER.info(String.format("Found %d HITs", hits.length)); return hits; } catch (InternalServiceException ise) { LOGGER.warn(ise); if (overTime("searchAllHITs", waittime)) return null; chill(waittime); waittime = waittime*2; } } } } private static void extendHIT(String hitd, Integer maxAssignmentsIncrement, Long expirationIncrementInSeconds) { int waitTime = 1; while (true){ try { service.extendHIT(hitd, maxAssignmentsIncrement, expirationIncrementInSeconds); return; } catch (InternalServiceException ise) { LOGGER.warn(ise); if (overTime("extendHIT", waitTime)) return; chill(waitTime); waitTime = 2 * waitTime; } } } private static void extendHITs (List<String> hitidlist, Integer maxAssignmentsIncrement, Long expirationIncrementInSeconds, final Survey survey) { String[] hitids = (String[]) hitidlist.toArray(); int waittime = 1; while(true) { synchronized (service) { try { service.extendHITs(hitids , maxAssignmentsIncrement , expirationIncrementInSeconds , new BatchItemCallback() { @Override public void processItemResult(Object itemId, boolean succeeded, Object result, Exception itemException) { // update local copies of hits to indicate that the HIT was extended Record record = ResponseManager.manager.get(survey.sid); for (HIT hit : record.getAllHITs()) if (hit.getHITId().equals((String) itemId)) { hit.setExpiration(((HIT) result).getExpiration()); String msg = "updated expiration date of hit "+(String) itemId; ResponseManager.LOGGER.info(msg); System.out.println(msg); } } }); return; } catch (InternalServiceException ise) { LOGGER.warn(ise); if (overTime("extendHITs", waittime)) return; chill(waittime); waittime *= 2; } } } } private static void deleteHIT(String hitid) { int waittime = 1; while (true) { synchronized (service) { try { service.disposeHIT(hitid); return; } catch (InternalServiceException ise) { LOGGER.warn(ise); if (overTime("deleteHIT", waittime)) return; chill(waittime); waittime *= 2; } } } } private static void deleteHITs(List<String> hitids) { synchronized (service) { for (String hitid : hitids) { int wait = 1; while (true) { try { service.disposeHIT(hitid); break; } catch (InternalServiceException ise) { LOGGER.warn(ise); if (overTime("deleteHITs", wait)) return; chill(wait); wait *= 2; } } } } } private static void approveAssignments(List<String> assignmentids) { String msg = String.format("Attempting to approve %d assignments", assignmentids.size()); System.out.println(msg); LOGGER.info(msg); int waittime = 1; // call to the batch assignment approval method never terminated. // synch outside the foor loop so new things arent posted in the interim. synchronized (service) { for (String assignmentid : assignmentids) { while (true) { try { service.approveAssignment(assignmentid, "Thanks."); System.out.println("Approved "+assignmentid); LOGGER.info("Approved "+assignmentid); break; } catch (InternalServiceException ise) { LOGGER.warn(ise); if (overTime("approveAssignments", waittime)) return; chill(1); waittime *= 2; } } } } } /** * Expires a specific HIT. * @param hit */ public static void expireHIT(HIT hit) { while (true){ synchronized (service) { try{ service.forceExpireHIT(hit.getHITId()); return; }catch(InternalServiceException ise){ LOGGER.warn(ise); chill(1); }catch(ObjectDoesNotExistException odne) { LOGGER.warn(odne); return; } } } } public static void expireHITs(List<String> hitids) { synchronized (service) { for (String hitid : hitids) { while(true) { try { service.forceExpireHIT(hitid); String msg = String.format("Expired hit %s", hitid); LOGGER.info(msg); System.out.println(msg); break; } catch (InternalServiceException ise) { LOGGER.warn(ise); chill(1); } } } } } public static String getWebsiteURL() { synchronized (service) { while(true) { try { String websiteURL = service.getWebsiteURL(); return websiteURL; } catch (InternalServiceException ise) { chill(3); } } } } protected static QualificationRequirement answerOnce(Record record){ return new QualificationRequirement( record.qualificationType.getQualificationTypeId() , Comparator.NotEqualTo , 1 , null , false ); } public static String registerNewHitType(Record record) { int waittime = 1; synchronized (service) { while(true) { try { String keywords = (String) record.parameters.getProperty("keywords"); String description = "Can only be paid for this survey once."; QualificationType qualificationType = service.createQualificationType( record.survey.sid+MturkLibrary.TIME , keywords , description , QualificationTypeStatus.Active , new Long(Integer.MAX_VALUE) , null //test , null //answer key , null //test duration , true //autogranted , 0 //integer autogranted (count of 0) ); record.qualificationType = qualificationType; QualificationRequirement qr = answerOnce(record); String hitTypeId = service.registerHITType( maxAutoApproveDelay , Long.parseLong(MturkLibrary.props.getProperty("assignmentduration")) , Double.parseDouble((String) MturkLibrary.props.get("reward")) , (String) MturkLibrary.props.getProperty("title") , (String) MturkLibrary.props.getProperty("keywords") , (String) MturkLibrary.props.getProperty("description") , new QualificationRequirement[]{ qr } ); record.hitTypeId = hitTypeId; record.qualificationType = qualificationType; LOGGER.info(String.format("Qualification id: (%s)", qualificationType.getQualificationTypeId())); return hitTypeId; } catch (InternalServiceException ise) { LOGGER.warn(ise); if (overTime("registerNewHitType", waittime)) throw new RuntimeException("FATAL - CANNOT REGISTER HIT TYPE"); chill(waittime); waittime *= 2; } } } } public static String createHIT(String title, String description, String keywords, String xml, double reward, long assignmentDuration, long maxAutoApproveDelay, long lifetime, QualificationRequirement qr, String hitTypeId) throws ParseException { int waittime = 1; synchronized (service) { while(true) { try { HIT hitid = service.createHIT(hitTypeId , title , description , keywords , xml , reward , assignmentDuration , maxAutoApproveDelay , lifetime , 1 , "" , new QualificationRequirement[]{qr} , null ); return hitid.getHITId(); } catch (InternalServiceException ise) { LOGGER.info(ise); if (overTime("createHIT", waittime)) throw new RuntimeException("FATAL - CANNOT CREATE HIT"); chill(waittime); waittime *= 2; } catch (ObjectAlreadyExistsException e) { LOGGER.info(e); chill(waittime); waittime *= 2; } } } } public static void removeQualification(Record record) { int waittime = 1; String qualid = record.qualificationType.getQualificationTypeId(); LOGGER.info(String.format("Retiring qualification type : (%s)", qualid)); synchronized (service) { while(true) { try { service.disposeQualificationType(qualid); } catch (InternalServiceException ise) { LOGGER.info(ise); if (overTime("removeQualification", waittime)) { LOGGER.warn(String.format("Cannot remove qualification %s. Aborting.", qualid)); break; } chill(waittime); waittime *= 2; } } } } // /** * Returns a copy of the Record {@link Record} of results for argument survey. This method synchronizes on manager, * so the current contents of the Record for this survey may be stale. If there is no Record recorded yet, the * method returns null. * * @param survey * @return a copy of the Record {@link Record} associated with this Survey {@link Survey}. * @throws IOException */ public static Record getRecord(Survey survey) throws IOException, SurveyException { synchronized (manager) { Record r = manager.get(survey.sid); return r; // if (r!=null) // return manager.get(survey.sid).copy(); // else return null; } } /** * Given a Record {@link Record}, this method loops through the HITs {@link HIT} registered for the Record {@link Record} * and returns a list of HITs {@link HIT}. Note that if the argument is generated using getRecord, the resulting * list of HITs may be stale. This is generally fine for most operations in SurveyMan, but if the list must be as * fresh as possible, synchronize on manager and get the record that way. * * @param r * @return a list of HITs associated with this Record (i.e. the value associated with a given Survey {@link Survey} * in manager. */ public static List<HIT> listAvailableHITsForRecord (Record r) { List<HIT> hits = Arrays.asList(r.getAllHITs()); ArrayList<HIT> retval = new ArrayList<HIT>(); for (HIT hit : hits) { HIT thishit = getHIT(hit.getHITId()); if (thishit.getHITStatus().equals(HITStatus.Assignable)) retval.add(hit); } return retval; } private static SurveyResponse parseResponse(Assignment assignment, Survey survey) throws SurveyException, IOException { Record record = ResponseManager.getRecord(survey); return new SurveyResponse(survey, assignment, record); } protected static void addResponses(Survey survey, String hitid) throws SurveyException, IOException { boolean success = false; Record r = manager.get(survey.sid); // references to things in the record List<SurveyResponse> responses = r.responses; List<SurveyResponse> botResponses = r.botResponses; QC qc = r.qc; // local vars List<SurveyResponse> validResponsesToAdd = new ArrayList<SurveyResponse>(); List<SurveyResponse> randomResponsesToAdd = new ArrayList<SurveyResponse>(); while (!success) { try{ Assignment[] assignments = getAllAssignmentsForHIT(hitid); for (Assignment a : assignments) { if (a.getAssignmentStatus().equals(AssignmentStatus.Submitted)) { SurveyResponse sr = parseResponse(a, survey); if (QCAction.addAsValidResponse(qc.assess(sr), a, r)) validResponsesToAdd.add(sr); else randomResponsesToAdd.add(sr); } } responses.addAll(validResponsesToAdd); botResponses.addAll(randomResponsesToAdd); success=true; } catch (ServiceException se) { LOGGER.warn("ServiceException in addResponses "+se); } } } /** * Tries to parse all of the Approved assignments into a SurveyResponse {@link SurveyResponse} list according to * some date window. * * @param survey * @return a list of survey responses */ public static List<SurveyResponse> getOldResponsesByDate(Survey survey, Calendar from, Calendar to) throws SurveyException, IOException { List<SurveyResponse> responses = new ArrayList<SurveyResponse>(); for (HIT hit : searchAllHITs()) if (hit.getCreationTime().after(from) && hit.getCreationTime().before(to)) for (Assignment assignment : getAllAssignmentsForHIT(hit.getHITId())) if (assignment.getAssignmentStatus().equals(AssignmentStatus.Approved)) responses.add(parseResponse(assignment, survey)); return responses; } /** * For a specific HIT {@link HIT} Id, this function will extent the HIT's lifetime by the same length * as the original setting. The original setting is provided in the params argument. * Both arguments are typically extracted from a Record {@link Record} object associated with a * particular Survey {@link Survey} object. * * @param hitId * @param params */ public static boolean renewIfExpired(String hitId, Properties params) { HIT hit = getHIT(hitId); if (hit.getExpiration().before(Calendar.getInstance())) { long extension = Long.valueOf(params.getProperty("hitlifetime")); extendHIT(hitId, 1, extension>=60?extension:60); return true; } else return false; } /** * Renews the expiration on all HITs {@link HIT} associated with a particular survey by the length of * time originally provided. This information is extracted from ResponseManager.manager * * @param survey */ public static void renewAllIfExpired(Survey survey) throws IOException { Record record = ResponseManager.manager.get(survey.sid); List<String> toExtend = new LinkedList<String>(); long extendBy = Long.parseLong(record.parameters.getProperty("assignmentduration")); synchronized (record) { for (HIT hit : record.getAllHITs()) if (hit.getExpiration().before(Calendar.getInstance())) toExtend.add(hit.getHITId()); extendHITs(toExtend, 1, extendBy, survey); } } /** * Checks whether there are any assignable {@link HITStatus} HITs. This blocks on the manager and should * be used sparingly. * * @param survey * @return whether there are any assignable HITs. */ public static boolean hasJobs(Survey survey) { Record record = manager.get(survey); synchronized (record) { for (String hitid : record.getAllHITIds()) if (getHIT(hitid).getHITStatus().equals(HITStatus.Assignable)) return true; return false; } } /** * Wrapper for returning the number of cents currently in the user's account. * @return */ public static double getAccountBalance(){ while (true) { try { double balance = service.getAccountBalance(); return balance; } catch (ServiceException se) { LOGGER.info(se); chill(1); } } } private static List<HIT> hitTask(HITStatus inputStatus) { List<HIT> hits = new ArrayList<HIT>(); HIT[] hitarray = searchAllHITs(); for (HIT hit : hitarray){ HITStatus status = hit.getHITStatus(); if (status.equals(inputStatus)) hits.add(hit); } return hits; } /** * Returns a list of all currently unassignable HITs {@link HIT}. Note that this may include previously * unassigned HITs from old sessions (that is, the HITs may not be linked to the Surveys currently held * in manager) * @return */ public static List<HIT> unassignableHITs() { return hitTask(HITStatus.Unassignable); } /** * Deletes all expired HITs {@link HIT}. Also approves any pending assignments. * @return A list of the expired HITs. */ public static List<HIT> deleteExpiredHITs() { List<HIT> hits = new ArrayList<HIT>(); List<String> assignments = new ArrayList<String>(); List<String> hitids = new ArrayList<String>(); List<HIT> tasks = hitTask(HITStatus.Reviewable); tasks.addAll(hitTask(HITStatus.Reviewing)); for (HIT hit : tasks) if (hit.getExpiration().getTimeInMillis() < Calendar.getInstance().getTimeInMillis()){ hits.add(hit); hitids.add(hit.getHITId()); } for (HIT hit : hits) { Assignment[] assignmentsForHIT = getAllAssignmentsForHIT(hit.getHITId()); for (Assignment a : assignmentsForHIT) if (a.getAssignmentStatus().equals(AssignmentStatus.Submitted)) assignments.add(a.getAssignmentId()); } approveAssignments(assignments); deleteHITs(hitids); System.out.println(String.format("Deleted %d HITs", hitids.size())); return hits; } /** * Gets a list of all the assignable HITs currently listed on Mechanical Turk. Note that this may * include previously assigned HITs from old sessions (that is, the HITs may not be linked to the * Surveys {@link Survey} currently held in manager) * @return */ public static List<HIT> assignableHITs() { return hitTask(HITStatus.Assignable); } /** * Expires all HITs that are not listed as Reviewable or Reviewing. Reviewable assignmenst are those for * which a worker has submitted a response. Reviewing is a special state that corresponds to a staging * area where jobs wait for review. * @return */ public static List<HIT> expireOldHITs() { List<String> expiredHITIds = new LinkedList<String>(); List<HIT> expiredHITs = new LinkedList<HIT>(); HIT[] hitarray = searchAllHITs(); for (HIT hit : hitarray){ HITStatus status = hit.getHITStatus(); if (! (status.equals(HITStatus.Reviewable) || status.equals(HITStatus.Reviewing))) { expiredHITs.add(hit); expiredHITIds.add(hit.getHITId()); } } expireHITs(expiredHITIds); String msg = String.format("Expired %d HITs", expiredHITs.size()); LOGGER.info(msg); System.out.println(msg); return expiredHITs; } public static void approveAllHITs(){ HIT[] hits = searchAllHITs(); List<String> assignmentidlist = new LinkedList<String>(); for (HIT hit : hits){ Assignment[] assignments = getAllAssignmentsForHIT(hit.getHITId()); for (Assignment assignment : assignments) if (assignment.getAssignmentStatus().equals(AssignmentStatus.Submitted)) assignmentidlist.add(assignment.getAssignmentId()); } String msg1 = String.format("Attempting to approve %d assignments", assignmentidlist.size()); System.out.println(msg1); approveAssignments(assignmentidlist); String msg2 = String.format("Approved %d assignments.", assignmentidlist.size()); System.out.println(msg2); LOGGER.info(msg1 + "\n" + msg2); } public static void main(String[] args) throws IOException, SurveyException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { if (args.length < 4) { System.err.println("Usage :\n" + "\tjava -cp path/to/surveyman.jar system.mturk.ResponseManager <fromDate> <toDate> <filename> <sep>\n" + "\twhere\n" + "\t<fromDate>, <toDate>\tare dates formatted as YYYYMMDD (e.g. Jan 1, 2013 would be 20130101)\n" + "\t<filename>\t\t\t\tis the (relative or absolute) path to the file of interest\n" + "\t<sep>\t\t\t\t\tis the field separator\n"); } else { SurveyPoster.init(); Calendar from = Calendar.getInstance(); from.set(Integer.parseInt(args[0].substring(0,4)), Integer.parseInt(args[0].substring(4,6)), Integer.parseInt(args[0].substring(6,8))); System.out.println("From Date:"+new SimpleDateFormat().format(from.getTime(), new StringBuffer(), new FieldPosition(DateFormat.DATE_FIELD))); Calendar to = Calendar.getInstance(); to.set(Integer.parseInt(args[1].substring(0,4)), Integer.parseInt(args[1].substring(4,6)), Integer.parseInt(args[1].substring(6,8))); System.out.println("To Date:"+new SimpleDateFormat().format(to.getTime(), new StringBuffer(), new FieldPosition(DateFormat.DATE_FIELD))); CSVParser parser = new CSVParser(new CSVLexer(args[2], args[3])); Survey survey = parser.parse(); List<SurveyResponse> responses = getOldResponsesByDate(survey, from, to); Record record = new Record(survey, MturkLibrary.props); record.responses = responses; Runner.writeResponses(survey, record); System.out.println(String.format("Response can be found in %s", record.outputFileName)); } } }
package tutorial.minecraft; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.network.NetworkMod; import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.block.Block; import net.minecraft.block.material.MaterialLogic; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import tutorial.minecraft.block.BigGravel; import tutorial.minecraft.item.Sword; import tutorial.minecraft.item.BigFlint; import tutorial.minecraft.item.Electron; import tutorial.minecraft.item.HandCrusher; import tutorial.minecraft.item.HydrogenAtom; import tutorial.minecraft.item.LexiconBook; import tutorial.minecraft.item.Neutron; import tutorial.minecraft.item.OxygenAtom; import tutorial.minecraft.item.ParticleOfWater; import tutorial.minecraft.item.Proton; import tutorial.minecraft.item.UnnamedAtom; import tutorial.minecraft.item.WandMiner; @Mod(modid = "CaesarModID", name = "CaesarMod", version = "1.0.0") @NetworkMod(clientSideRequired = true) public class CaesarMod { private final static QuantumTab quantumTab = new QuantumTab("Quantum Energy"); private final static Block bigGravel = new BigGravel(2048, MaterialLogic.sand); private final static Item sword = new Sword(2049); private final static Item wandMiner = new WandMiner(2050); private final static Item unnamedAtom = new UnnamedAtom(2051); private final static Item lexiconBook = new LexiconBook(2052); private final static Item hydrogenAtom = new HydrogenAtom(2053); private final static Item oxygenAtom = new OxygenAtom(2054); private final static Item bigFlint = new BigFlint(2055); private final static Item proton = new Proton(2056); private final static Item neutron = new Neutron(2057); private final static Item handCrusher = new HandCrusher(2058); private final static Item electron = new Electron(2059); private final static Item particleOfWater = new ParticleOfWater(2060); @SidedProxy(clientSide = "tutorial.minecraft.ClientProxy", serverSide = "tutorial.minecraft.CommonProxy") public static CommonProxy proxy; @Instance(value = "ExampleModID") public static CaesarMod instance; @EventHandler public void preInit(FMLPreInitializationEvent event) { bigGravel.setCreativeTab(quantumTab); unnamedAtom.setCreativeTab(quantumTab); hydrogenAtom.setCreativeTab(quantumTab); oxygenAtom.setCreativeTab(quantumTab); bigFlint.setCreativeTab(quantumTab); proton.setCreativeTab(quantumTab); neutron.setCreativeTab(quantumTab); handCrusher.setCreativeTab(quantumTab); electron.setCreativeTab(quantumTab); particleOfWater.setCreativeTab(quantumTab); GameRegistry.registerBlock(bigGravel, bigGravel.getUnlocalizedName()); GameRegistry.registerItem(sword, sword.getUnlocalizedName()); GameRegistry.registerItem(wandMiner, wandMiner.getUnlocalizedName()); GameRegistry.registerItem(unnamedAtom, unnamedAtom.getUnlocalizedName()); GameRegistry.registerItem(lexiconBook, lexiconBook.getUnlocalizedName()); GameRegistry.registerItem(hydrogenAtom, hydrogenAtom.getUnlocalizedName()); GameRegistry.registerItem(oxygenAtom, oxygenAtom.getUnlocalizedName()); GameRegistry.registerItem(bigFlint, bigFlint.getUnlocalizedName()); GameRegistry.registerItem(proton, proton.getUnlocalizedName()); GameRegistry.registerItem(neutron, neutron.getUnlocalizedName()); GameRegistry.registerItem(handCrusher, handCrusher.getUnlocalizedName()); GameRegistry.registerItem(electron, electron.getUnlocalizedName()); GameRegistry.registerItem(particleOfWater, particleOfWater.getUnlocalizedName()); GameRegistry.addShapelessRecipe(new ItemStack(Item.bucketWater), particleOfWater, particleOfWater, particleOfWater, particleOfWater); GameRegistry.addShapedRecipe(new ItemStack(hydrogenAtom), " ", " x ", "y ", 'x', proton, 'y', electron); } @EventHandler public void load(FMLInitializationEvent event) { proxy.registerRenderers(); } @EventHandler public void postInit(FMLPostInitializationEvent event) { } }
package ui.issuepanel; import backend.resource.*; import filter.expression.FilterExpression; import filter.expression.Qualifier; import github.TurboIssueEvent; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.FlowPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import org.eclipse.egit.github.core.Comment; import ui.issuecolumn.IssueColumn; import util.Utility; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.HashSet; import java.util.List; import java.util.stream.Collectors; public class IssuePanelCard extends VBox { private static final String OCTICON_PULL_REQUEST = "\uf009"; private static final int CARD_WIDTH = 350; private static final String OCTICON_COMMENT = "\uf02b"; /** * A card that is constructed with an issue as argument. Its components * are bound to the issue's fields and will update automatically. */ private final TurboIssue issue; private final Model model; private FlowPane issueDetails = new FlowPane(); private IssueColumn parentPanel; private final HashSet<Integer> issuesWithNewComments; public IssuePanelCard(Model model, TurboIssue issue, IssueColumn parentPanel, HashSet<Integer> issuesWithNewComments) { this.model = model; this.issue = issue; this.parentPanel = parentPanel; this.issuesWithNewComments = issuesWithNewComments; setup(); } private void setup() { Label issueTitle = new Label("#" + issue.getId() + " " + issue.getTitle()); issueTitle.setMaxWidth(CARD_WIDTH); issueTitle.setWrapText(true); issueTitle.getStyleClass().add("issue-panel-name"); if (issue.isCurrentlyRead()) { issueTitle.getStyleClass().add("issue-panel-name-read"); } if (!issue.isOpen()) { issueTitle.getStyleClass().add("issue-panel-closed"); } setupIssueDetailsBox(); setPadding(new Insets(0, 0, 3, 0)); setSpacing(1); getChildren().addAll(issueTitle, issueDetails); if (parentPanel.getCurrentFilterExpression().getQualifierNames().contains(Qualifier.UPDATED)) { getChildren().add(getEventDisplay(issue, getUpdateFilterHours(parentPanel.getCurrentFilterExpression()))); } } /** * Creates a JavaFX node containing a graphical display of this issue's events. * @param withinHours the number of hours to bound the returned events by * @return the node */ private Node getEventDisplay(TurboIssue issue, final int withinHours) { final LocalDateTime now = LocalDateTime.now(); List<TurboIssueEvent> eventsWithinDuration = issue.getMetadata().getEvents().stream() .filter(event -> { LocalDateTime eventTime = Utility.longToLocalDateTime(event.getDate().getTime()); int hours = Utility.safeLongToInt(eventTime.until(now, ChronoUnit.HOURS)); return hours < withinHours; }) .collect(Collectors.toList()); List<Comment> commentsWithinDuration = issue.getMetadata().getComments().stream() .filter(comment -> { LocalDateTime created = Utility.longToLocalDateTime(comment.getCreatedAt().getTime()); int hours = Utility.safeLongToInt(created.until(now, ChronoUnit.HOURS)); return hours < withinHours; }) .collect(Collectors.toList()); return layoutEvents(model, issue, eventsWithinDuration, commentsWithinDuration); } /** * Given a list of issue events, returns a JavaFX node laying them out properly. * @param events * @param comments * @return */ private static Node layoutEvents(Model model, TurboIssue issue, List<TurboIssueEvent> events, List<Comment> comments) { VBox result = new VBox(); result.setSpacing(3); VBox.setMargin(result, new Insets(3, 0, 0, 0)); // Events events.stream() .map(e -> e.display(model, issue)) .forEach(e -> result.getChildren().add(e)); // Comments if (comments.size() > 0) { String names = comments.stream() .map(comment -> comment.getUser().getLogin()) .distinct() .collect(Collectors.joining(", ")); HBox commentDisplay = new HBox(); commentDisplay.getChildren().addAll( TurboIssueEvent.octicon(TurboIssueEvent.OCTICON_QUOTE), new javafx.scene.control.Label( String.format("%d comments since, involving %s.", comments.size(), names)) ); result.getChildren().add(commentDisplay); } return result; } private int getUpdateFilterHours(FilterExpression currentFilterExpression) { List<Qualifier> filters = currentFilterExpression.find(q -> q.getName().equals("updated")); assert filters.size() > 0 : "Problem with isUpdateFilter"; // Return the first of the updated qualifiers, if there are multiple Qualifier qualifier = filters.get(0); if (qualifier.getNumber().isPresent()) { return qualifier.getNumber().get(); } else { // TODO support ranges properly. getEventDisplay only supports < assert qualifier.getNumberRange().isPresent(); if (qualifier.getNumberRange().get().getStart() != null) { // TODO semantics are not exactly right return qualifier.getNumberRange().get().getStart(); } else { assert qualifier.getNumberRange().get().getEnd() != null; // TODO semantics are not exactly right return qualifier.getNumberRange().get().getEnd(); } } } private void setupIssueDetailsBox() { issueDetails.setMaxWidth(CARD_WIDTH); issueDetails.setPrefWrapLength(CARD_WIDTH); issueDetails.setHgap(3); updateDetails(); } private void updateDetails() { issueDetails.getChildren().clear(); if (issue.isPullRequest()) { Label icon = new Label(OCTICON_PULL_REQUEST); icon.getStyleClass().addAll("octicon", "issue-pull-request-icon"); issueDetails.getChildren().add(icon); } if (issue.getCommentCount() > 0){ Label commentIcon = new Label(OCTICON_COMMENT); commentIcon.getStyleClass().addAll("octicon", "comments-label-button"); Label commentCount = new Label(Integer.toString(issue.getCommentCount())); if (issuesWithNewComments.contains(issue.getId())) { commentIcon.getStyleClass().add("has-comments"); commentCount.getStyleClass().add("has-comments"); } issueDetails.getChildren().add(commentIcon); issueDetails.getChildren().add(commentCount); } for (TurboLabel label : model.getLabelsOfIssue(issue)) { issueDetails.getChildren().add(label.getNode()); } if (issue.getMilestone().isPresent() && model.getMilestoneOfIssue(issue).isPresent()) { TurboMilestone milestone = model.getMilestoneOfIssue(issue).get(); issueDetails.getChildren().add(new Label(milestone.getTitle())); } if (issue.getAssignee().isPresent() && model.getAssigneeOfIssue(issue).isPresent()) { TurboUser assignee = model.getAssigneeOfIssue(issue).get(); Label assigneeNameLabel = new Label(issue.getAssignee().get()); assigneeNameLabel.getStyleClass().add("display-box-padding"); ImageView avatar = new ImageView(); if (assignee.getAvatarURL().length() != 0) { Image image = assignee.getAvatar(); assert image != null; avatar.setImage(image); } HBox assigneeBox = new HBox(); assigneeBox.setAlignment(Pos.BASELINE_CENTER); assigneeBox.getChildren().addAll(avatar, assigneeNameLabel); issueDetails.getChildren().add(assigneeBox); } } }
package mondrian.rolap.agg; import mondrian.olap.Aggregator; import mondrian.olap.Util; import mondrian.rolap.*; import mondrian.rolap.agg.Segment.ExcludedRegion; import mondrian.rolap.sql.SqlQuery; import mondrian.spi.*; import mondrian.spi.Dialect.Datatype; import mondrian.util.ArraySortedSet; import mondrian.util.Pair; import org.olap4j.impl.UnmodifiableArrayList; import java.lang.ref.WeakReference; import java.math.BigInteger; import java.util.*; import java.util.Map.Entry; /** * Helper class that contains methods to convert between * {@link Segment} and {@link SegmentHeader}, and also * {@link SegmentWithData} and {@link SegmentBody}. * * @author LBoudreau */ public class SegmentBuilder { /** * Converts a segment plus a {@link SegmentBody} into a * {@link mondrian.rolap.agg.SegmentWithData}. * * @param segment Segment * @param sb Segment body * @return SegmentWithData */ public static SegmentWithData addData(Segment segment, SegmentBody sb) { // Load the axis keys for this segment SegmentAxis[] axes = new SegmentAxis[segment.predicates.length]; for (int i = 0; i < segment.predicates.length; i++) { StarColumnPredicate predicate = segment.predicates[i]; axes[i] = new SegmentAxis( predicate, sb.getAxisValueSets()[i], sb.getNullAxisFlags()[i]); } final SegmentDataset dataSet = createDataset(sb, axes); return new SegmentWithData(segment, dataSet, axes); } /** * Creates a SegmentDataset that contains the cached * data and is initialized to be used with the supplied segment. * * @param body Segment with which the returned dataset will be associated * @param axes Segment axes, containing actual column values * @return A SegmentDataset object that contains cached data. */ private static SegmentDataset createDataset( SegmentBody body, SegmentAxis[] axes) { final SegmentDataset dataSet; if (body instanceof DenseDoubleSegmentBody) { dataSet = new DenseDoubleSegmentDataset( axes, (double[]) body.getValueArray(), body.getNullValueIndicators()); } else if (body instanceof DenseIntSegmentBody) { dataSet = new DenseIntSegmentDataset( axes, (int[]) body.getValueArray(), body.getNullValueIndicators()); } else if (body instanceof DenseObjectSegmentBody) { dataSet = new DenseObjectSegmentDataset( axes, (Object[]) body.getValueArray()); } else if (body instanceof SparseSegmentBody) { dataSet = new SparseSegmentDataset(body.getValueMap()); } else { throw Util.newInternal( "Unknown segment body type: " + body.getClass() + ": " + body); } return dataSet; } /** * Creates a segment from a SegmentHeader. The star, * constrainedColsBitKey, constrainedColumns and measure arguments are a * helping hand, because we know what we were looking for. * * @param header The header to convert. * @param star Star * @param constrainedColumnsBitKey Constrained columns * @param constrainedColumns Constrained columns * @param measure Measure * @return Segment */ public static Segment toSegment( SegmentHeader header, RolapStar star, BitKey constrainedColumnsBitKey, RolapStar.Column[] constrainedColumns, RolapStar.Measure measure, List<StarPredicate> compoundPredicates) { final List<StarColumnPredicate> predicateList = new ArrayList<StarColumnPredicate>(); for (int i = 0; i < constrainedColumns.length; i++) { RolapStar.Column constrainedColumn = constrainedColumns[i]; final SortedSet<Comparable> values = header.getConstrainedColumns().get(i).values; StarColumnPredicate predicate; if (values == null) { predicate = new LiteralStarPredicate( constrainedColumn, true); } else if (values.size() == 1) { predicate = new ValueColumnPredicate( constrainedColumn, values.first()); } else { final List<StarColumnPredicate> valuePredicateList = new ArrayList<StarColumnPredicate>(); for (Object value : values) { valuePredicateList.add( new ValueColumnPredicate( constrainedColumn, value)); } predicate = new ListColumnPredicate( constrainedColumn, valuePredicateList); } predicateList.add(predicate); } return new Segment( star, constrainedColumnsBitKey, constrainedColumns, measure, predicateList.toArray( new StarColumnPredicate[predicateList.size()]), new ExcludedRegionList(header), compoundPredicates); } /** * Given a collection of segments, all of the same dimensionality, rolls up * to create a segment with reduced dimensionality. * * @param map Source segment headers and bodies * @param keepColumns A list of column names to keep as part of * the rolled up segment. * @param targetBitkey The column bit key to match with the * resulting segment. * @param rollupAggregator The aggregator to use to rollup. * @return Segment header and body of requested dimensionality * @param datatype The data type to use. */ public static Pair<SegmentHeader, SegmentBody> rollup( Map<SegmentHeader, SegmentBody> map, Set<String> keepColumns, BitKey targetBitkey, Aggregator rollupAggregator, Datatype datatype) { class AxisInfo { SegmentColumn column; SortedSet<Comparable> requestedValues; SortedSet<Comparable> valueSet; Comparable[] values; boolean hasNull; int src; boolean lostPredicate; } assert allHeadersHaveSameDimensionality(map.keySet()); // store the map values in a list to assure the first header // loaded here is consistent w/ the first segment processed below. List<Map.Entry<SegmentHeader, SegmentBody>> segments = UnmodifiableArrayList.of(map.entrySet()); final SegmentHeader firstHeader = segments.get(0).getKey(); final AxisInfo[] axes = new AxisInfo[keepColumns.size()]; int z = 0, j = 0; for (SegmentColumn column : firstHeader.getConstrainedColumns()) { if (keepColumns.contains(column.columnExpression)) { final AxisInfo axisInfo = axes[z++] = new AxisInfo(); axisInfo.src = j; axisInfo.column = column; axisInfo.requestedValues = column.values; } j++; } // Compute the sets of values in each axis of the target segment. These // are the intersection of the input axes. for (Map.Entry<SegmentHeader, SegmentBody> entry : segments) { final SegmentHeader header = entry.getKey(); for (AxisInfo axis : axes) { final SortedSet<Comparable> values = entry.getValue().getAxisValueSets()[axis.src]; final SegmentColumn headerColumn = header.getConstrainedColumn(axis.column.columnExpression); final boolean hasNull = entry.getValue().getNullAxisFlags()[axis.src]; final SortedSet<Comparable> requestedValues = headerColumn.getValues(); if (axis.valueSet == null) { axis.valueSet = new TreeSet<Comparable>(values); axis.hasNull = hasNull; axis.requestedValues = requestedValues; } else { final SortedSet<Comparable> filteredValues; final boolean filteredHasNull; if (axis.requestedValues == null) { filteredValues = values; filteredHasNull = hasNull; axis.column = headerColumn; } else if (requestedValues == null) { // this axis is wildcarded filteredValues = axis.requestedValues; filteredHasNull = axis.hasNull; } else { filteredValues = Util.intersect( requestedValues, axis.requestedValues); // SegmentColumn predicates cannot ask for the null // value (at present). filteredHasNull = false; } axis.valueSet = filteredValues; axis.hasNull = axis.hasNull || filteredHasNull; if (!Util.equals(axis.requestedValues, requestedValues)) { if (axis.requestedValues == null) { // Downgrade from wildcard to a specific list. axis.requestedValues = requestedValues; } else if (requestedValues != null) { // Segment requests have incompatible predicates. // Best we can say is "we must have asked for the // values that came back". axis.lostPredicate = true; } } } } } for (AxisInfo axis : axes) { axis.values = axis.valueSet.toArray(new Comparable[axis.valueSet.size()]); } // Populate cells. // (This is a rough implementation, very inefficient. It makes all // segment types pretend to be sparse, for purposes of reading. It // maps all axis ordinals to a value, then back to an axis ordinal, // even if this translation were not necessary, say if the source and // target axes had the same set of values. And it always creates a // sparse segment. // We should do really efficient rollup if the source is an array: we // should box values (e.g double to Double and back), and we should read // a stripe of values from the and add them up into a single cell. final Map<CellKey, List<Object>> cellValues = new HashMap<CellKey, List<Object>>(); for (Map.Entry<SegmentHeader, SegmentBody> entry : map.entrySet()) { final int[] pos = new int[axes.length]; final Comparable[][] valueArrays = new Comparable[firstHeader.getConstrainedColumns().size()][]; final SegmentBody body = entry.getValue(); // Copy source value sets into arrays. For axes that are being // projected away, store null. z = 0; for (SortedSet<Comparable> set : body.getAxisValueSets()) { valueArrays[z] = keepColumns.contains( firstHeader.getConstrainedColumns().get(z).columnExpression) ? set.toArray(new Comparable[set.size()]) : null; ++z; } Map<CellKey, Object> v = body.getValueMap(); entryLoop: for (Map.Entry<CellKey, Object> vEntry : v.entrySet()) { z = 0; for (int i = 0; i < vEntry.getKey().size(); i++) { final Comparable[] valueArray = valueArrays[i]; if (valueArray == null) { continue; } final int ordinal = vEntry.getKey().getOrdinals()[i]; final int targetOrdinal; if (axes[z].hasNull && ordinal == valueArray.length) { targetOrdinal = axes[z].valueSet.size(); } else { final Comparable value = valueArray[ordinal]; if (value == null) { targetOrdinal = axes[z].valueSet.size(); } else { targetOrdinal = Util.binarySearch( axes[z].values, 0, axes[z].values.length, value); } } if (targetOrdinal >= 0) { pos[z++] = targetOrdinal; } else { // This happens when one of the rollup candidate doesn't // contain the requested cell. continue entryLoop; } } final CellKey ck = CellKey.Generator.newCellKey(pos); if (!cellValues.containsKey(ck)) { cellValues.put(ck, new ArrayList<Object>()); } cellValues.get(ck).add(vEntry.getValue()); } } // Build the axis list. final List<Pair<SortedSet<Comparable>, Boolean>> axisList = new ArrayList<Pair<SortedSet<Comparable>, Boolean>>(); BigInteger bigValueCount = BigInteger.ONE; for (AxisInfo axis : axes) { axisList.add(Pair.of(axis.valueSet, axis.hasNull)); int size = axis.values.length; bigValueCount = bigValueCount.multiply( BigInteger.valueOf(axis.hasNull ? size + 1 : size)); } // The logic used here for the sparse check follows // SegmentLoader.setAxisDataAndDecideSparseUse. // The two methods use different data structures (AxisInfo/SegmentAxis) // so combining logic is probably more trouble than it's worth. final boolean sparse = bigValueCount.compareTo (BigInteger.valueOf(Integer.MAX_VALUE)) > 0 || SegmentLoader.useSparse( bigValueCount.doubleValue(), cellValues.size()); final int[] axisMultipliers = computeAxisMultipliers(axisList); final SegmentBody body; // Peak at the values and determine the best way to store them // (whether to use a dense native dataset or a sparse one. if (cellValues.size() == 0) { // Just store the data into an empty dense object dataset. body = new DenseObjectSegmentBody( new Object[0], axisList); } else if (sparse) { // The rule says we must use a sparse dataset. // First, aggregate the values of each key. final Map<CellKey, Object> data = new HashMap<CellKey, Object>(); for (Entry<CellKey, List<Object>> entry : cellValues.entrySet()) { data.put( CellKey.Generator.newCellKey(entry.getKey().getOrdinals()), rollupAggregator.aggregate( entry.getValue(), datatype)); } body = new SparseSegmentBody( data, axisList); } else { final BitSet nullValues; final int valueCount = bigValueCount.intValue(); switch (datatype) { case Integer: final int[] ints = new int[valueCount]; nullValues = Util.bitSetBetween(0, valueCount); for (Entry<CellKey, List<Object>> entry : cellValues.entrySet()) { final int offset = CellKey.Generator.getOffset( entry.getKey().getOrdinals(), axisMultipliers); final Object value = rollupAggregator.aggregate( entry.getValue(), datatype); if (value != null) { ints[offset] = (Integer) value; nullValues.clear(offset); } } body = new DenseIntSegmentBody( nullValues, ints, axisList); break; case Numeric: final double[] doubles = new double[valueCount]; nullValues = Util.bitSetBetween(0, valueCount); for (Entry<CellKey, List<Object>> entry : cellValues.entrySet()) { final int offset = CellKey.Generator.getOffset( entry.getKey().getOrdinals(), axisMultipliers); final Object value = rollupAggregator.aggregate( entry.getValue(), datatype); if (value != null) { doubles[offset] = (Double) value; nullValues.clear(offset); } } body = new DenseDoubleSegmentBody( nullValues, doubles, axisList); break; default: final Object[] objects = new Object[valueCount]; for (Entry<CellKey, List<Object>> entry : cellValues.entrySet()) { final int offset = CellKey.Generator.getOffset( entry.getKey().getOrdinals(), axisMultipliers); objects[offset] = rollupAggregator.aggregate( entry.getValue(), datatype); } body = new DenseObjectSegmentBody( objects, axisList); } } // Create header. final List<SegmentColumn> constrainedColumns = new ArrayList<SegmentColumn>(); for (int i = 0; i < axes.length; i++) { AxisInfo axisInfo = axes[i]; constrainedColumns.add( new SegmentColumn( axisInfo.column.getColumnExpression(), axisInfo.column.getValueCount(), axisInfo.lostPredicate ? axisList.get(i).left : axisInfo.column.values)); } final SegmentHeader header = new SegmentHeader( firstHeader.schemaName, firstHeader.schemaChecksum, firstHeader.cubeName, firstHeader.measureName, constrainedColumns, firstHeader.compoundPredicates, firstHeader.rolapStarFactTableName, targetBitkey, Collections.<SegmentColumn>emptyList()); return Pair.of(header, body); } private static boolean allHeadersHaveSameDimensionality( Set<SegmentHeader> headers) { final Iterator<SegmentHeader> headerIter = headers.iterator(); final SegmentHeader firstHeader = headerIter.next(); BitKey bitKey = firstHeader.getConstrainedColumnsBitKey(); while (headerIter.hasNext()) { final SegmentHeader nextHeader = headerIter.next(); if (!bitKey.equals(nextHeader.getConstrainedColumnsBitKey())) { return false; } } return true; } private static int[] computeAxisMultipliers( List<Pair<SortedSet<Comparable>, Boolean>> axes) { final int[] axisMultipliers = new int[axes.size()]; int multiplier = 1; for (int i = axes.size() - 1; i >= 0; --i) { axisMultipliers[i] = multiplier; // if the nullAxisFlag is set we need to offset by 1. int nullAxisAdjustment = axes.get(i).right ? 1 : 0; multiplier *= (axes.get(i).left.size() + nullAxisAdjustment); } return axisMultipliers; } private static class ExcludedRegionList extends AbstractList<Segment.ExcludedRegion> implements Segment.ExcludedRegion { private final int cellCount; private final SegmentHeader header; public ExcludedRegionList(SegmentHeader header) { this.header = header; int cellCount = 1; for (SegmentColumn cc : header.getExcludedRegions()) { // TODO find a way to approximate the cardinality // of wildcard columns. if (cc.values != null) { cellCount *= cc.values.size(); } } this.cellCount = cellCount; } public void describe(StringBuilder buf) { // TODO } public int getArity() { return header.getConstrainedColumns().size(); } public int getCellCount() { return cellCount; } public boolean wouldContain(Object[] keys) { assert keys.length == header.getConstrainedColumns().size(); for (int i = 0; i < keys.length; i++) { final SegmentColumn excl = header.getExcludedRegion( header.getConstrainedColumns().get(i).columnExpression); if (excl == null) { continue; } if (excl.values.contains(keys[i])) { return true; } } return false; } public ExcludedRegion get(int index) { return this; } public int size() { return 1; } } /** * Tells if the passed segment is a subset of this segment * and could be used for a rollup in cache operation. * @param segment A segment which might be a subset of the * current segment. * @return True or false. */ public static boolean isSubset( SegmentHeader header, Segment segment) { if (!segment.getStar().getSchema().getName() .equals(header.schemaName)) { return false; } if (!segment.getStar().getFactTable().getAlias() .equals(header.rolapStarFactTableName)) { return false; } if (!segment.measure.getName().equals(header.measureName)) { return false; } if (!segment.measure.getCubeName().equals(header.cubeName)) { return false; } if (segment.getConstrainedColumnsBitKey() .equals(header.constrainedColsBitKey)) { return true; } return false; } public static List<SegmentColumn> toConstrainedColumns( StarColumnPredicate[] predicates) { return toConstrainedColumns( Arrays.asList(predicates)); } public static List<SegmentColumn> toConstrainedColumns( Collection<StarColumnPredicate> predicates) { List<SegmentColumn> ccs = new ArrayList<SegmentColumn>(); for (StarColumnPredicate predicate : predicates) { final List<Comparable> values = new ArrayList<Comparable>(); predicate.values(Util.cast(values)); final Comparable[] valuesArray = values.toArray(new Comparable[values.size()]); if (valuesArray.length == 1 && valuesArray[0].equals(true)) { ccs.add( new SegmentColumn( predicate.getConstrainedColumn() .getExpression().getGenericExpression(), predicate.getConstrainedColumn().getCardinality(), null)); } else { Arrays.sort( valuesArray, Util.SqlNullSafeComparator.instance); ccs.add( new SegmentColumn( predicate.getConstrainedColumn() .getExpression().getGenericExpression(), predicate.getConstrainedColumn().getCardinality(), new ArraySortedSet(valuesArray))); } } return ccs; } /** * Creates a SegmentHeader object describing the supplied * Segment object. * * @param segment A segment object for which we want to generate * a SegmentHeader. * @return A SegmentHeader describing the supplied Segment object. */ public static SegmentHeader toHeader(Segment segment) { final List<SegmentColumn> cc = SegmentBuilder.toConstrainedColumns(segment.predicates); final List<String> cp = new ArrayList<String>(); StringBuilder buf = new StringBuilder(); for (StarPredicate compoundPredicate : segment.compoundPredicateList) { buf.setLength(0); SqlQuery query = new SqlQuery( segment.star.getSqlQueryDialect()); compoundPredicate.toSql(query, buf); cp.add(buf.toString()); } final RolapSchema schema = segment.star.getSchema(); return new SegmentHeader( schema.getName(), schema.getChecksum(), segment.measure.getCubeName(), segment.measure.getName(), cc, cp, segment.star.getFactTable().getAlias(), segment.constrainedColumnsBitKey, Collections.<SegmentColumn>emptyList()); } private static RolapStar.Column[] getConstrainedColumns( RolapStar star, BitKey bitKey) { final List<RolapStar.Column> list = new ArrayList<RolapStar.Column>(); for (int bit : bitKey) { list.add(star.getColumn(bit)); } return list.toArray(new RolapStar.Column[list.size()]); } /** * Functor to convert a segment header and body into a * {@link mondrian.rolap.agg.SegmentWithData}. */ public static interface SegmentConverter { SegmentWithData convert( SegmentHeader header, SegmentBody body); } /** * Implementation of {@link SegmentConverter} that uses an * {@link mondrian.rolap.agg.AggregationKey} * and {@link mondrian.rolap.agg.CellRequest} as context to * convert a {@link mondrian.spi.SegmentHeader}. * * <p>This is nasty. A converter might be used for several headers, not * necessarily with the context as the cell request and aggregation key. * Converters only exist for fact tables and compound predicate combinations * for which we have already done a load request.</p> * * <p>It would be much better if there was a way to convert compound * predicates from strings to predicates. Then we could obsolete the * messy context inside converters, and maybe obsolete converters * altogether.</p> */ public static class SegmentConverterImpl implements SegmentConverter { private final AggregationKey key; private final CellRequest request; public SegmentConverterImpl(AggregationKey key, CellRequest request) { this.key = key; this.request = request; } public SegmentWithData convert( SegmentHeader header, SegmentBody body) { final Segment segment = toSegment( header, key.getStar(), header.getConstrainedColumnsBitKey(), getConstrainedColumns( key.getStar(), header.getConstrainedColumnsBitKey()), request.getMeasure(), key.getCompoundPredicateList()); return addData(segment, body); } } /** * Implementation of {@link SegmentConverter} that uses a star measure * and a list of {@link StarPredicate}. */ public static class StarSegmentConverter implements SegmentConverter { private final RolapStar.Measure measure; private final List<StarPredicate> compoundPredicateList; public StarSegmentConverter( RolapStar.Measure measure, List<StarPredicate> compoundPredicateList) { // The measure is wrapped in a weak reference because // converters are put into the SegmentCacheIndex, // but the registry of indexes is based as a weak // list of the RolapStars. // Simply put, the fact that converters have a hard // link on the measure would prevents the GC from // ever cleaning the registry. The circular references // are a well known issue with weak lists. // It is harmless to use a weak reference here because // the measure is referenced by cubes and what-not, // so it can't be GC'd before its time has come. this.measure = measure; this.compoundPredicateList = compoundPredicateList; } public SegmentWithData convert( SegmentHeader header, SegmentBody body) { final Segment segment = toSegment( header, measure.getStar(), header.getConstrainedColumnsBitKey(), getConstrainedColumns( measure.getStar(), header.getConstrainedColumnsBitKey()), measure, compoundPredicateList); return addData(segment, body); } } } // End SegmentBuilder.java
import java.io.IOException; import java.lang.System; import java.net.InetAddress; import java.net.DatagramSocket; import java.net.DatagramPacket; import java.util.Scanner; /** * class WiMicServer * * Creates a WiMic server and provides interface between * client and speakers */ public class WiMicServer implements Runnable { private final int PORT = 9876; private final String LOCALHOST = "0.0.0.0"; private final String DISC_MESSAGE = "WIMIC_DISCOVER_REQ"; private final String ACK_MESSAGE = "WIMIC_DISCOVER_ACK"; private final String JOIN_MESSAGE = "WIMIC_JOIN_PASSWORD"; private final String JOIN_SUCCESS = "WIMIC_JOIN_SUCCESS"; private final String JOIN_FAIL = "WIMIC_JOIN_FAILURE"; /** * Room name */ private String name = "WiMic Server"; /** * Room PIN */ private int pin; /** * Constructor * * @param name Name of the room * @param pin PIN of the room */ WiMicServer(String name, int pin) { // Ensure first alphabet is capital this.name = name.substring(0, 1).toUpperCase() + name.substring(1); this.pin = pin; } /** * Creates socket and listen for connection */ public void run() { try { DatagramSocket socket = new DatagramSocket(PORT, InetAddress.getByName(LOCALHOST)); socket.setBroadcast(true); System.out.println(name + " is ready. Your pin is: " + pin); while (true) { receivePackets(socket); } } catch (Exception e) { // TODO System.out.println(e); } } /** * Receive packets from clients * * @param socket DatagramSocket object which is binded to port * @throws IOException if cannot receive packets */ private void receivePackets(DatagramSocket socket) throws IOException { byte[] receiveBuffer = new byte[15000]; DatagramPacket packet = new DatagramPacket( receiveBuffer, receiveBuffer.length ); socket.receive(packet); handleReceivedPacket(socket, packet); } /** * Checks if received packet is discovery packet or join packet * * @param socket DatagramSocket object * @param packet DatagramPacket object * @throws IOException thrown when can't send message */ private void handleReceivedPacket( DatagramSocket socket, DatagramPacket packet ) throws IOException { String message = new String(packet.getData()).trim(); if (message.equals(DISC_MESSAGE)) { System.out.println("Discovery packet received from " + packet.getAddress()); sendDiscoveryAck(socket, packet); } else if (message.contains(JOIN_MESSAGE)) { System.out.println("Join packet received from" + packet.getAddress()); sendJoinACK(socket, packet); } } /** * Send ACK of discovery packet * * @param socket DatagramSocket object * @param packet DatagramPacket object * @throws IOException thrown when can't send message */ private void sendDiscoveryAck(DatagramSocket socket, DatagramPacket packet) throws IOException { byte[] sendData = (ACK_MESSAGE + ";" + this.name).getBytes(); DatagramPacket sendPacket = new DatagramPacket( sendData, sendData.length, packet.getAddress(), packet.getPort() ); socket.send(sendPacket); System.out.println("Sent discovery ACK"); } /** * Send ACK of join packet * * @param socket DatagramSocket object * @param packet DatagramPacket object * @throws IOException thrown when can't send message */ private void sendJoinACK(DatagramSocket socket, DatagramPacket packet) throws IOException { String message = new String(packet.getData()).trim(); String[] request = message.split(";"); byte[] sendData; if (request.length >= 2 && validatePin(request[1])) { sendData = JOIN_SUCCESS.getBytes(); System.out.println("PIN success!"); } else { sendData = JOIN_FAIL.getBytes(); System.out.println("Invalid PIN"); } DatagramPacket sendPacket = new DatagramPacket( sendData, sendData.length, packet.getAddress(), packet.getPort() ); socket.send(sendPacket); } /** * Checks if a pin is valid * * @param pin Given pin as String * @return true if valid, else false */ private boolean validatePin(String pin) { String regex = "\\d+"; int pinInt; if (pin.matches(regex)) { pinInt = Integer.parseInt(pin); if (this.pin == pinInt) { return true; } } return false; } /** * Creates new server instance * * @param args Command line args */ public static void main(String[] args) { Scanner sc; sc = new Scanner(System.in); String name; System.out.println("Enter room name:"); name = sc.next(); // Generate a random pin double rand = Math.random() * 8999 + 1000; Thread serverThread = new Thread(new WiMicServer(name, (int) rand)); serverThread.start(); } }
package carpentersblocks.renderer; import net.minecraft.block.Block; import net.minecraft.client.renderer.Tessellator; import net.minecraft.util.Icon; import net.minecraft.util.Vec3; import net.minecraftforge.common.ForgeDirection; import carpentersblocks.data.Torch; import carpentersblocks.util.BlockProperties; import carpentersblocks.util.registry.IconRegistry; public class BlockHandlerCarpentersTorch extends BlockDeterminantRender { private Vec3[] vector = new Vec3[8]; @Override public boolean shouldRender3DInInventory() { return false; } @Override /** * Renders block */ protected boolean renderCarpentersBlock(int x, int y, int z) { renderBlocks.renderAllFaces = true; disableAO = true; Block block = BlockProperties.getCoverBlock(TE, 6); renderTorch(block, x, y, z); disableAO = false; renderBlocks.renderAllFaces = false; return true; } @Override /** * Renders side. */ protected void renderSide(int x, int y, int z, int side, double offset, Icon icon) { renderFace(Tessellator.instance, side, icon, true); } @Override /** * Override to provide custom icons. */ protected Icon getUniqueIcon(Block block, int side, Icon icon) { if (BlockProperties.hasCover(TE, 6)) { return block.getIcon(2, renderBlocks.blockAccess.getBlockMetadata(TE.xCoord, TE.yCoord, TE.zCoord)); } else { return IconRegistry.icon_generic; } } /** * Renders a torch at the given coordinates */ private void renderTorch(Block block, int x, int y, int z) { if (shouldRenderOpaque()) { renderTorchHead(x, y, z); } if (shouldRenderCover(block)) { renderTorchHandle(block, x, y, z); } } /** * Renders a torch head at the given coordinates. */ private void renderTorchHead(int x, int y, int z) { Tessellator tessellator = Tessellator.instance; tessellator.setBrightness(srcBlock.getMixedBrightnessForBlock(renderBlocks.blockAccess, TE.xCoord, TE.yCoord, TE.zCoord)); tessellator.setColorOpaque_F(1.0F, 1.0F, 1.0F); Icon icon = null; switch (Torch.getState(TE)) { case LIT: icon = IconRegistry.icon_torch_lit; break; case SMOLDERING: icon = IconRegistry.icon_torch_head_smoldering; break; case UNLIT: icon = IconRegistry.icon_torch_head_unlit; break; default: {} } float vecX = 0.0625F; float vecY = 10.0F / 16.0F; float vecZ = 0.0625F; vector[0] = renderBlocks.blockAccess.getWorldVec3Pool().getVecFromPool(-vecX, 0.5D, -vecZ); vector[1] = renderBlocks.blockAccess.getWorldVec3Pool().getVecFromPool(vecX, 0.5D, -vecZ); vector[2] = renderBlocks.blockAccess.getWorldVec3Pool().getVecFromPool(vecX, 0.5D, vecZ); vector[3] = renderBlocks.blockAccess.getWorldVec3Pool().getVecFromPool(-vecX, 0.5D, vecZ); vector[4] = renderBlocks.blockAccess.getWorldVec3Pool().getVecFromPool(-vecX, vecY, -vecZ); vector[5] = renderBlocks.blockAccess.getWorldVec3Pool().getVecFromPool(vecX, vecY, -vecZ); vector[6] = renderBlocks.blockAccess.getWorldVec3Pool().getVecFromPool(vecX, vecY, vecZ); vector[7] = renderBlocks.blockAccess.getWorldVec3Pool().getVecFromPool(-vecX, vecY, vecZ); setRotations(Torch.getFacing(TE), x, y, z); for (int side = 0; side < 6; ++side) { renderFace(tessellator, side, icon, false); } } /** * Renders a torch handle at the given coordinates. */ private void renderTorchHandle(Block block, int x, int y, int z) { float vecX = 0.0625F; float vecY = 0.5F; float vecZ = 0.0625F; vector[0] = renderBlocks.blockAccess.getWorldVec3Pool().getVecFromPool(-vecX, 0.0D, -vecZ); vector[1] = renderBlocks.blockAccess.getWorldVec3Pool().getVecFromPool(vecX, 0.0D, -vecZ); vector[2] = renderBlocks.blockAccess.getWorldVec3Pool().getVecFromPool(vecX, 0.0D, vecZ); vector[3] = renderBlocks.blockAccess.getWorldVec3Pool().getVecFromPool(-vecX, 0.0D, vecZ); vector[4] = renderBlocks.blockAccess.getWorldVec3Pool().getVecFromPool(-vecX, vecY, -vecZ); vector[5] = renderBlocks.blockAccess.getWorldVec3Pool().getVecFromPool(vecX, vecY, -vecZ); vector[6] = renderBlocks.blockAccess.getWorldVec3Pool().getVecFromPool(vecX, vecY, vecZ); vector[7] = renderBlocks.blockAccess.getWorldVec3Pool().getVecFromPool(-vecX, vecY, vecZ); setRotations(Torch.getFacing(TE), x, y, z); /* * Lightness and sides won't match here. Rotations and the ordering * of the vectors may be to blame. */ lightingHelper.setLightness(0.5F).setLightingYNeg(block, x, y, z); delegateSideRender(block, x, y, z, DOWN); lightingHelper.setLightness(1.0F).setLightingYPos(block, x, y, z); delegateSideRender(block, x, y, z, UP); lightingHelper.setLightness(0.8F).setLightingZNeg(block, x, y, z); delegateSideRender(block, x, y, z, NORTH); lightingHelper.setLightness(0.6F).setLightingZPos(block, x, y, z); delegateSideRender(block, x, y, z, SOUTH); lightingHelper.setLightness(0.8F).setLightingXNeg(block, x, y, z); delegateSideRender(block, x, y, z, WEST); lightingHelper.setLightness(0.6F).setLightingXPos(block, x, y, z); delegateSideRender(block, x, y, z, EAST); } private void setRotations(ForgeDirection facing, int x, int y, int z) { for (int vecCount = 0; vecCount < 8; ++vecCount) { if (facing.equals(ForgeDirection.UP)) { vector[vecCount].xCoord += x + 0.5D; vector[vecCount].yCoord += y; vector[vecCount].zCoord += z + 0.5D; } else { vector[vecCount].zCoord += 0.0625D; vector[vecCount].rotateAroundX(-((float)Math.PI * 3.4F / 9F)); vector[vecCount].yCoord -= 0.4375D; vector[vecCount].rotateAroundX((float)Math.PI / 2F); switch (facing) { case NORTH: vector[vecCount].rotateAroundY(0.0F); break; case SOUTH: vector[vecCount].rotateAroundY((float)Math.PI); break; case WEST: vector[vecCount].rotateAroundY((float)Math.PI / 2F); break; case EAST: vector[vecCount].rotateAroundY(-((float)Math.PI / 2F)); break; default: {} } vector[vecCount].xCoord += x + 0.5D; vector[vecCount].yCoord += y + 0.1875F; vector[vecCount].zCoord += z + 0.5D; } } } /** * Performs final rendering of face. */ private void renderFace(Tessellator tessellator, int side, Icon icon, boolean isHandle) { double uMin, uMax, vMin, vMax; if (isHandle) { uMin = icon.getInterpolatedU(7.0D); uMax = icon.getInterpolatedU(9.0D); vMin = icon.getMinV(); vMax = icon.getInterpolatedV(8.0D); } else { uMin = icon.getInterpolatedU(7.0D); uMax = icon.getInterpolatedU(9.0D); vMin = icon.getInterpolatedV(6.0D); vMax = icon.getInterpolatedV(8.0D); } Vec3 vertex1 = null; Vec3 vertex2 = null; Vec3 vertex3 = null; Vec3 vertex4 = null; switch (side) { case 0: vertex1 = vector[0]; vertex2 = vector[1]; vertex3 = vector[2]; vertex4 = vector[3]; break; case 1: vertex1 = vector[7]; vertex2 = vector[6]; vertex3 = vector[5]; vertex4 = vector[4]; break; case 2: vertex1 = vector[1]; vertex2 = vector[0]; vertex3 = vector[4]; vertex4 = vector[5]; break; case 3: vertex1 = vector[2]; vertex2 = vector[1]; vertex3 = vector[5]; vertex4 = vector[6]; break; case 4: vertex1 = vector[3]; vertex2 = vector[2]; vertex3 = vector[6]; vertex4 = vector[7]; break; case 5: vertex1 = vector[0]; vertex2 = vector[3]; vertex3 = vector[7]; vertex4 = vector[4]; break; } tessellator.addVertexWithUV(vertex1.xCoord, vertex1.yCoord, vertex1.zCoord, uMin, vMax); tessellator.addVertexWithUV(vertex2.xCoord, vertex2.yCoord, vertex2.zCoord, uMax, vMax); tessellator.addVertexWithUV(vertex3.xCoord, vertex3.yCoord, vertex3.zCoord, uMax, vMin); tessellator.addVertexWithUV(vertex4.xCoord, vertex4.yCoord, vertex4.zCoord, uMin, vMin); } }
import com.intellij.notification.Notification; import com.intellij.notification.NotificationType; import com.intellij.notification.Notifications; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.Nullable; import org.w3c.dom.Document; import org.w3c.dom.Node; import java.io.*; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class XmlSorterAction extends AnAction { private static final String ERROR_GROUP = "ErrorMessage"; private static final String ERROR_TITLE = "Error"; @Override public void update(AnActionEvent event) { super.update(event); final VirtualFile file = CommonDataKeys.VIRTUAL_FILE.getData(event.getDataContext()); event.getPresentation().setVisible(isXmlFile(file)); } @Override public void actionPerformed(AnActionEvent event) { XmlSorterDialog dialog = new XmlSorterDialog(getEventProject(event)); if (!dialog.showAndGet()) { return; } // get options boolean enableInsertSpaceDiffPrefix = dialog.enableInsertSpace(); boolean isSnakeCase = true; if (enableInsertSpaceDiffPrefix) { isSnakeCase = dialog.isSnakeCase(); } boolean enableInsertXmlEncoding = dialog.enableInsertXmlInfo(); boolean enableDeleteComment = dialog.enableDeleteComment(); int codeIndent = dialog.getCodeIndent(); // get content final Editor editor = event.getData(PlatformDataKeys.EDITOR); final String content = editor.getDocument().getText(); final String simpleContent = XmlSorterUtil.replaceAllByRegex(content, "\\s*\\n\\s*", ""); // content convert document Document document; try { document = XmlSorterUtil.parseStringToDocument(simpleContent); } catch (Exception e) { Notifications.Bus.notify(new Notification(ERROR_GROUP, ERROR_TITLE, e.getLocalizedMessage(), NotificationType.ERROR)); return; } // sort ArrayList<Node> targetNodes = XmlSorterUtil.getNodesAsList(document); Collections.sort(targetNodes, new NodeComparator()); XmlSorterUtil.removeChildNodes(document); // delete comment if (enableDeleteComment) { targetNodes = XmlSorterUtil.deleteComment(targetNodes); } // insert space if (enableInsertSpaceDiffPrefix) { targetNodes = XmlSorterUtil.insertDiffPrefixSpace(document, targetNodes, 0, isSnakeCase); } // apply sort for (Node node : targetNodes) { document.getDocumentElement().appendChild(node); } // document convert content String printString; try { printString = XmlSorterUtil.prettyStringFromDocument(document, codeIndent); } catch (IOException e) { Notifications.Bus.notify(new Notification(ERROR_GROUP, ERROR_TITLE, e.getLocalizedMessage(), NotificationType.ERROR)); return; } // write option if (!enableInsertXmlEncoding) { printString = XmlSorterUtil.replaceAllByRegex(printString, "<\\?xml.*\\?>\n", ""); } if (enableInsertSpaceDiffPrefix) { printString = XmlSorterUtil.replaceAllByRegex(printString, "\n\\s+<space/>", "\n"); } // write final String finalPrintString = printString; new WriteCommandAction.Simple(getEventProject(event)) { @Override protected void run() throws Throwable { editor.getDocument().setText(finalPrintString); } }.execute(); } private static boolean isXmlFile(@Nullable VirtualFile file) { return file != null && file.getName().endsWith(".xml"); } private class NodeComparator implements Comparator<Node> { @Override public int compare(Node node1, Node node2) { if (node1.getNodeType() == Node.COMMENT_NODE && node2.getNodeType() == Node.COMMENT_NODE) { return 0; } else if (node1.getNodeType() == Node.COMMENT_NODE && node2.getNodeType() != Node.COMMENT_NODE) { return -1; } else if (node1.getNodeType() != Node.COMMENT_NODE && node2.getNodeType() == Node.COMMENT_NODE) { return 1; } else { final String node1Name = node1.getAttributes().getNamedItem("name").getTextContent(); final String node2Name = node2.getAttributes().getNamedItem("name").getTextContent(); return node1Name.compareTo(node2Name); } } } }
package edu.cscie71.imm.slacker.plugin; import android.content.Context; import android.content.SharedPreferences; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CallbackContext; import org.json.JSONArray; import org.json.JSONException; import edu.cscie71.imm.app.slacker.client.ISlackerClient; import edu.cscie71.imm.app.slacker.client.SlackerClient; public class Slacker extends CordovaPlugin { private ISlackerClient slackerClient = new SlackerClient(); private String token = "xoxp-10020492535-10036686290-14227963249-1cb545e1ae"; private String immTestChannel = "C0F6U0R5E"; private static final String PREFS = "Slacker"; @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if (action.equals("postMessage")) { final String message = args.getString(0); final Slacker slacker = this; final CallbackContext cc = callbackContext; cordova.getThreadPool().execute(new Runnable() { public void run() { slacker.postMessage(message, cc); } }); } else if (action.equals("getChannelList")) { final boolean excludeArchivedChannels = args.getBoolean(0); final Slacker slacker = this; final CallbackContext cc = callbackContext; cordova.getThreadPool().execute(new Runnable() { public void run() { slacker.getChannelList(excludeArchivedChannels, cc); } }); } return false; } private void postMessage(String message, CallbackContext callbackContext) { String response = slackerClient.postMessage(token, immTestChannel, message); if (response.contains("\"ok\":true")) callbackContext.success(message); else callbackContext.error("Error posting to the Slack channel."); } private void getChannelList(boolean excludeArchivedChannels, CallbackContext callbackContext) { String response = slackerClient.getChannelList(token, excludeArchivedChannels); if (response.contains("\"ok\":true")) callbackContext.success(response); else callbackContext.error("Error getting channel list from Slack."); } private void storeOAuthToken(String token) { Context context = cordova.getActivity(); SharedPreferences.Editor editor = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit(); editor.putString("token", token); editor.apply(); } private String getOAuthToken() { Context context = cordova.getActivity(); SharedPreferences prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE); // Return null as default value return prefs.getString("token", null); } }
import java.nio.ByteBuffer; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import edu.emory.mathcs.backport.java.util.Collections; @SuppressWarnings("all") public class PRMC_Sample { private static PRMC_Sample SAMPLE1; private static PRMC_Sample SAMPLE2; String data; public boolean test1(Calendar c) { Date d = c.getTime(); long l = d.getTime(); Date e = c.getTime(); long j = e.getTime(); return l == j; } public void rmcFP(ByteBuffer bb) { int i = bb.getInt(); int j = bb.getInt(); } @Override public boolean equals(Object o) { PRMC_Sample rmc = (PRMC_Sample) o; if (data.equals("INF") || rmc.data.equals("INF")) return false; return data.equals(rmc.data); } public void staticPRMC() { Factory.getInstance().fee(); Factory.getInstance().fi(); Factory.getInstance().fo(); Factory.getInstance().fum(); } static class Factory { private static Factory f = new Factory(); private Factory() { } public static Factory getInstance() { return f; } public void fee() { } public void fi() { } public void fo() { } public void fum() { } } public long fpCurrentTimeMillis(Object o) { long time = -System.currentTimeMillis(); o.hashCode(); time += System.currentTimeMillis(); return time; } public void fpEnumToString(FPEnum e) { Set<String> s = new HashSet<String>(); s.add(FPEnum.fee.toString()); s.add(FPEnum.fi.toString()); s.add(FPEnum.fo.toString()); s.add(FPEnum.fum.toString()); } public void emptyList() { List l = Collections.emptyList(); List o = Collections.emptyList(); List p = Collections.emptyList(); } enum FPEnum { fee, fi, fo, fum }; public boolean validChainedFields(Chain c1) { return c1.chainedField.toString().equals(c1.chainedField.toString()); } public boolean fpChainedFieldsOfDiffBases(Chain c1, Chain c2) { return c1.chainedField.toString().equals(c2.chainedField.toString()); } public void fpMultipleStatics() { SAMPLE1 = new PRMC_Sample(); SAMPLE1.setValue(5); SAMPLE2 = new PRMC_Sample(); SAMPLE2.setValue(5); } public void setValue(int i) { } class Chain { public Chain chainedField; public String toString() { StringBuilder sb = new StringBuilder(); sb.append(" sb.append("XX"); sb.append(" sb.append("XX"); sb.append(" sb.append("XX"); sb.append(" sb.append("XX"); sb.append(" sb.append("XX"); sb.append(" return sb.toString(); } } }
package net.orfjackal.retrolambda.test; import org.junit.Test; import java.lang.reflect.*; import java.util.*; import java.util.concurrent.Callable; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertTrue; public class LambdaTest extends SuperClass { @Test public void empty_lambda() { Runnable lambda = () -> { }; lambda.run(); } @Test public void lambda_returning_a_value() throws Exception { Callable<String> lambda = () -> "some value"; assertThat(lambda.call(), is("some value")); } private interface Function1<IN, OUT> { OUT apply(IN value); } @Test public void lambda_taking_parameters() { Function1<String, Integer> lambda = (String s) -> s.getBytes().length; assertThat(lambda.apply("foo"), is(3)); } @Test public void lambda_in_project_main_sources() throws Exception { assertThat(InMainSources.callLambda(), is(42)); } private int instanceVar = 0; @Test public void lambda_using_instance_variables() { Runnable lambda = () -> { instanceVar = 42; }; lambda.run(); assertThat(instanceVar, is(42)); } @Test public void lambda_using_local_variables() { int[] localVar = new int[1]; Runnable lambda = () -> { localVar[0] = 42; }; lambda.run(); assertThat(localVar[0], is(42)); } @Test public void lambda_using_local_variables_of_primitive_types() throws Exception { boolean bool = true; byte b = 2; short s = 3; int i = 4; long l = 5; float f = 6; double d = 7; char c = 8; Callable<Integer> lambda = () -> (int) ((bool ? 1 : 0) + b + s + i + l + f + d + c); assertThat(lambda.call(), is(36)); } @Test public void method_references_to_virtual_methods() throws Exception { String foo = "foo"; Callable<String> ref = foo::toUpperCase; assertThat(ref.call(), is("FOO")); } @Test public void method_references_to_interface_methods() throws Exception { List<String> foos = Arrays.asList("foo"); Callable<Integer> ref = foos::size; assertThat(ref.call(), is(1)); } @Test public void method_references_to_static_methods() throws Exception { long expected = System.currentTimeMillis(); Callable<Long> ref = System::currentTimeMillis; assertThat(ref.call(), is(greaterThanOrEqualTo(expected))); } @Test public void method_references_to_constructors() throws Exception { Callable<List<String>> ref = ArrayList<String>::new; assertThat(ref.call(), is(instanceOf(ArrayList.class))); } @Test public void method_references_to_overridden_inherited_methods_with_super() throws Exception { Callable<String> ref = super::inheritedMethod; assertThat(ref.call(), is("superclass version")); } @Override String inheritedMethod() { return "overridden version"; } @Test public void method_references_to_private_methods() throws Exception { Callable<String> ref1 = LambdaTest::privateClassMethod; assertThat(ref1.call(), is("foo")); Callable<String> ref2 = this::privateInstanceMethod; assertThat(ref2.call(), is("foo")); // Normal method calls should still work after our magic // of making them them accessible from the lambda classes. assertThat(privateClassMethod(), is("foo")); assertThat(privateInstanceMethod(), is("foo")); } private String privateInstanceMethod() { return "foo"; } private static String privateClassMethod() { return "foo"; } /** * We could make private lambda implementation methods package-private, * so that the lambda class may call them, but we should not make any * more methods non-private than is absolutely necessary. */ @Test public void will_not_change_the_visibility_of_unrelated_methods() throws Exception { assertThat(unrelatedPrivateMethod(), is("foo")); Method method = getClass().getDeclaredMethod("unrelatedPrivateMethod"); int modifiers = method.getModifiers(); assertTrue("expected " + method.getName() + " to be private, but modifiers were: " + Modifier.toString(modifiers), Modifier.isPrivate(modifiers)); } private String unrelatedPrivateMethod() { return "foo"; } /** * We cannot just make the private methods package-private for the * lambda class to call them, because that may cause a method in subclass * to override them. */ @Test public void will_not_cause_private_methods_to_be_overridable() throws Exception { class Parent { private String privateMethod() { return "parent version"; } Callable<String> parentRef() { return this::privateMethod; } } class Child extends Parent { private String privateMethod() { // would override if were not private return "child version"; } Callable<String> childRef() { return this::privateMethod; } } Child child = new Child(); // Our test assumes that there exists a private method with // the same name and signature in super and sub classes. String name = "privateMethod"; assertThat(child.getClass().getDeclaredMethod(name), is(notNullValue())); assertThat(child.getClass().getSuperclass().getDeclaredMethod(name), is(notNullValue())); Callable<String> ref1 = child.childRef(); assertThat(ref1.call(), is("child version")); Callable<String> ref2 = child.parentRef(); assertThat(ref2.call(), is("parent version")); } } class SuperClass { String inheritedMethod() { return "superclass version"; } }
package org.neo4j.kernel.ha; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.neo4j.com.ComException; import org.neo4j.graphdb.ConstraintViolationException; import org.neo4j.graphdb.DynamicLabel; import org.neo4j.graphdb.Label; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Transaction; import org.neo4j.graphdb.TransactionFailureException; import org.neo4j.helpers.Exceptions; import org.neo4j.test.AbstractClusterTest; import org.neo4j.test.OtherThreadExecutor; import org.neo4j.test.OtherThreadRule; import org.neo4j.tooling.GlobalGraphOperations; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.Matchers.greaterThan; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static org.neo4j.test.ha.ClusterManager.allSeesAllAsAvailable; /** * This test stress tests unique constraints in a setup where writes are being issued against a slave. */ public class UniqueConstraintStressIT extends AbstractClusterTest { @Before public void setUp() { cluster.await( allSeesAllAsAvailable() ); } @Rule public OtherThreadRule<Object> slaveWork = new OtherThreadRule<>(); @Rule public OtherThreadRule<Object> masterWork = new OtherThreadRule<>(); /** Configure how long to run the test. */ private static long runtime = Long.getLong( "neo4j.UniqueConstraintStressIT.runtime", TimeUnit.SECONDS.toMillis( 10 ) ); /** Label to constrain for the current iteration of the test. */ private volatile Label label = DynamicLabel.label( "User" ); /** Property key to constrain for the current iteration of the test. */ private volatile String property; private final AtomicInteger roundNo = new AtomicInteger(0); @Test public void shouldNotAllowUniquenessViolationsUnderStress() throws Exception { // Given HighlyAvailableGraphDatabase master = cluster.getMaster(); HighlyAvailableGraphDatabase slave = cluster.getAnySlave(); // Because this is a brute-force test, we run for a user-specified time, and consider ourselves successful if no failure is found. long end = System.currentTimeMillis() + runtime; int successfulAttempts = 0; while ( end > System.currentTimeMillis() ) { // Each round of this loop: // - on a slave, creates a set of nodes with a label/property combo with all-unique values // - on the master, creates a unique constraint // - on a slave, while the master is creating the constraint, starts issuing transactions that will violate the constraint setup : { // Set a target property for the constraint for this round setLabelAndPropertyForNextRound(); // Ensure slave has constraints from previous round cluster.sync(); // Create the initial data try { slaveWork.execute( performInsert( slave ) ).get(); } catch ( ExecutionException e ) { if ( Exceptions.contains( e, "could not connect", ComException.class ) ) { // We're in a weird cluster state. The slave should be able to succeed if trying again continue; } } } stress : { // Create the constraint on the master Future<Object> constraintCreation = masterWork.execute( createConstraint( master ) ); // Concurrently start violating the data via the slave Future<Object> constraintViolation = slaveWork.execute( performInsert( slave ) ); // And then ensure all is well assertConstraintsNotViolated( constraintCreation, constraintViolation, master ); successfulAttempts++; } } assertThat( successfulAttempts, greaterThan( 0 ) ); } private void assertConstraintsNotViolated( Future<Object> constraintCreation, Future<Object> constraintViolation, HighlyAvailableGraphDatabase master ) throws InterruptedException, ExecutionException { try { constraintCreation.get(); } catch(ExecutionException e) { assertThat(e.getCause(), instanceOf( ConstraintViolationException.class)); // Constraint creation failed. Then the violating operations should have been successful constraintViolation.get(); } // If the constraint creation was successful, the violating operations should have failed, and the graph // should not contain duplicates try { constraintViolation.get(); fail( "Constraint violating operations succeeded, even though they were violating a successfully created constraint." ); } catch(ExecutionException e) { assertThat(e.getCause(), instanceOf( TransactionFailureException.class)); assertAllPropertiesAreUnique( master, label, property ); } } private void assertAllPropertiesAreUnique( HighlyAvailableGraphDatabase master, Label label, String property ) { try( Transaction tx = master.beginTx() ) { Set<Object> values = new HashSet<>(); for ( Node node : GlobalGraphOperations.at( master ).getAllNodesWithLabel( label ) ) { Object value = node.getProperty( property ); if ( values.contains( value ) ) { throw new AssertionError( label + ":" + property + " contained duplicate property value '" + value + "', despite constraint existing." ); } values.add( value ); } tx.success(); } } private OtherThreadExecutor.WorkerCommand<Object, Object> createConstraint( final HighlyAvailableGraphDatabase master ) { return new OtherThreadExecutor.WorkerCommand<Object, Object>() { @Override public Object doWork( Object state ) throws Exception { try( Transaction tx = master.beginTx() ) { master.schema().constraintFor( label ).assertPropertyIsUnique( property ).create(); tx.success(); } return null; } }; } /** * Inserts a bunch of new nodes with the label and property key currently set in the fields in this class, where * running this method twice will insert nodes with duplicate property values, assuming propertykey or label has not * changed. */ private OtherThreadExecutor.WorkerCommand<Object, Object> performInsert( final HighlyAvailableGraphDatabase slave ) { return new OtherThreadExecutor.WorkerCommand<Object, Object>() { @Override public Object doWork( Object state ) throws Exception { for ( int i = 0; i < 1000; i++ ) { try( Transaction tx = slave.beginTx() ) { slave.createNode( label ).setProperty( property, "value-" + i ); tx.success(); } } return null; } }; } private void setLabelAndPropertyForNextRound() { property = "Key-" + roundNo.incrementAndGet(); label = DynamicLabel.label("Label-" + roundNo.get()); } }
package com.adamldavis.z; import java.awt.geom.Point2D; // Assume left-to-right. public class BloomZNodePositioner extends AbstractZNodePositioner { static final int maxSize = 15; @Override protected Point2D getDependencyPosition(ZNode node, int index, int size) { return getXPoint(-1.5, index, size); } @Override protected Point2D getSubmodulePosition(ZNode node, int index, int size) { return getXPoint(-0.5, index, size); } private Point2D getXPoint(final double start, int index, int size) { return getXPoint(getYAngle(start, index, size), index / maxSize); } private Point2D getXPoint(final double angle, int pow) { float x = (float) (Math.cos(angle) * 0.8 * Math.pow(0.5, pow)); float y = (float) (Math.sin(angle) * 0.8 * Math.pow(0.5, pow)); return new Point2D.Float(x, y); } private double getYAngle(final double start, int index, int size) { int smin = Math.min(maxSize, size); final double smin1 = smin + 1.0; return Math.PI * (start + (1.0 / smin1) + (index % maxSize / smin1)); } }
import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Collections; import java.util.Enumeration; import java.util.UUID; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.servlet.ServletContainer; import org.influxdb.InfluxDB; import org.influxdb.InfluxDBFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import proxy.Proxy; import proxycontrol.MasterHeartbeatSender; import proxycontrol.MetricsManager; import proxycontrol.ProxyControl; public class Main { private static final Logger logger = LoggerFactory.getLogger(Main.class); private static final String DbName = "ProxyMetrics"; public static void main(String... args) throws Exception { if (args.length < 6) { showHelp(); return; } Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces(); logger.info(" for (NetworkInterface netint : Collections.list(nets)) logInterfaceInformation(netint); logger.info(" Proxy proxy = null; Server proxyControlServer = null; try { final int controlPort = Integer.parseInt(args[0]); final int proxyPort = Integer.parseInt(args[1]); final String proxyTo = args[2]; final String proxyTag = args[3]; final String masterUrl = args[4]; final String influxdbUrl = args[5]; final String proxyUuid = UUID.randomUUID().toString(); logger.info("Starting proxy " + proxyTag + "_" + proxyUuid); // Try to connect to influxdb final InfluxDB influxDB = connectToDatabase(influxdbUrl); // Start proxy logger.info("Proxy starting on port " + proxyPort); proxy = Proxy.startProxy(proxyPort, controlPort, proxyTo, proxyTag, proxyUuid); // Start metrics MetricsManager metricsManager = null; if(influxDB != null) { logger.info("Starting MetricsManager to influxDb"); metricsManager = new MetricsManager(proxyTag, proxyUuid, influxDB, proxy, DbName); } else { logger.error("Unable to start MetricsManager without influxDb connection"); } // Start control server ResourceConfig config = new ResourceConfig(); config.packages("proxycontrol"); ServletHolder servlet = new ServletHolder(new ServletContainer(config)); logger.info("Control server starting on port " + controlPort); proxyControlServer = new Server(controlPort);
package com.android.deskclock; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.RectF; import android.util.AttributeSet; import android.view.View; import com.android.deskclock.stopwatch.Stopwatches; /** * TODO: Insert description here. (generated by isaackatz) */ public class CircleTimerView extends View { private int mRedColor; private int mWhiteColor; private long mIntervalTime = 0; private long mIntervalStartTime = -1; private long mMarkerTime = -1; private long mCurrentIntervalTime = 0; private long mAccumulatedTime = 0; private boolean mPaused = false; private boolean mAnimate = false; private static float mStrokeSize = 4; private static float mDiamondStrokeSize = 12; private static float mMarkerStrokeSize = 2; private final Paint mPaint = new Paint(); private final Paint mFill = new Paint(); private final RectF mArcRect = new RectF(); private float mRectHalfWidth = 6f; private Resources mResources; private float mRadiusOffset; // amount to remove from radius to account for markers on circle private float mScreenDensity; // Class has 2 modes: // Timer mode - counting down. in this mode the animation is counter-clockwise and stops at 0 // Stop watch mode - counting up - in this mode the animation is clockwise and will keep the // animation until stopped. private boolean mTimerMode = false; // default is stop watch view public CircleTimerView(Context context) { this(context, null); } public CircleTimerView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public void setIntervalTime(long t) { mIntervalTime = t; postInvalidate(); } public void setMarkerTime(long t) { mMarkerTime = t; postInvalidate(); } public void reset() { mIntervalStartTime = -1; mMarkerTime = -1; postInvalidate(); } public void startIntervalAnimation() { mIntervalStartTime = Utils.getTimeNow(); mAnimate = true; invalidate(); mPaused = false; } public void stopIntervalAnimation() { mAnimate = false; mIntervalStartTime = -1; mAccumulatedTime = 0; } public boolean isAnimating() { return (mIntervalStartTime != -1); } public void pauseIntervalAnimation() { mAnimate = false; mAccumulatedTime += Utils.getTimeNow() - mIntervalStartTime; mPaused = true; } public void abortIntervalAnimation() { mAnimate = false; } public void setPassedTime(long time, boolean drawRed) { // The onDraw() method checks if mIntervalStartTime has been set before drawing any red. // Without drawRed, mIntervalStartTime should not be set here at all, and would remain at -1 // when the state is reconfigured after exiting and re-entering the application. // If the timer is currently running, this drawRed will not be set, and will have no effect // because mIntervalStartTime will be set when the thread next runs. // When the timer is not running, mIntervalStartTime will not be set upon loading the state, // and no red will be drawn, so drawRed is used to force onDraw() to draw the red portion, // despite the timer not running. mCurrentIntervalTime = mAccumulatedTime = time; if (drawRed) { mIntervalStartTime = Utils.getTimeNow(); } postInvalidate(); } private void init(Context c) { mResources = c.getResources(); mStrokeSize = mResources.getDimension(R.dimen.circletimer_circle_size); mDiamondStrokeSize = mResources.getDimension(R.dimen.circletimer_diamond_size); mMarkerStrokeSize = mResources.getDimension(R.dimen.circletimer_marker_size); mPaint.setAntiAlias(true); mPaint.setStyle(Paint.Style.STROKE); mWhiteColor = mResources.getColor(R.color.clock_white); mRedColor = mResources.getColor(R.color.clock_red); mScreenDensity = mResources.getDisplayMetrics().density; mRadiusOffset = Math.max(mStrokeSize, Math.max(mDiamondStrokeSize, mMarkerStrokeSize)); mFill.setAntiAlias(true); mFill.setStyle(Paint.Style.FILL); mFill.setColor(mRedColor); mRectHalfWidth = mDiamondStrokeSize / 2f; } public void setTimerMode(boolean mode) { mTimerMode = mode; } @Override public void onDraw(Canvas canvas) { int xCenter = getWidth() / 2 + 1; int yCenter = getHeight() / 2; mPaint.setStrokeWidth(mStrokeSize); float radius = Math.min(xCenter, yCenter) - mRadiusOffset; if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { xCenter = (int) (radius + mRadiusOffset); } if (mIntervalStartTime == -1) { // just draw a complete white circle, no red arc needed mPaint.setColor(mWhiteColor); canvas.drawCircle (xCenter, yCenter, radius, mPaint); if (mTimerMode) { drawRedDiamond(canvas, 0f, xCenter, yCenter, radius); } } else { if (mAnimate) { mCurrentIntervalTime = Utils.getTimeNow() - mIntervalStartTime + mAccumulatedTime; } //draw a combination of red and white arcs to create a circle mArcRect.top = yCenter - radius; mArcRect.bottom = yCenter + radius; mArcRect.left = xCenter - radius; mArcRect.right = xCenter + radius; float redPercent = (float)mCurrentIntervalTime / (float)mIntervalTime; // prevent timer from doing more than one full circle redPercent = (redPercent > 1 && mTimerMode) ? 1 : redPercent; float whitePercent = 1 - (redPercent > 1 ? 1 : redPercent); // draw red arc here mPaint.setColor(mRedColor); if (mTimerMode){ canvas.drawArc (mArcRect, 270, - redPercent * 360 , false, mPaint); } else { canvas.drawArc (mArcRect, 270, + redPercent * 360 , false, mPaint); } // draw white arc here mPaint.setStrokeWidth(mStrokeSize); mPaint.setColor(mWhiteColor); if (mTimerMode) { canvas.drawArc(mArcRect, 270, + whitePercent * 360, false, mPaint); } else { canvas.drawArc(mArcRect, 270 + (1 - whitePercent) * 360, whitePercent * 360, false, mPaint); } if (mMarkerTime != -1 && radius > 0 && mIntervalTime != 0) { mPaint.setStrokeWidth(mMarkerStrokeSize); float angle = (float)(mMarkerTime % mIntervalTime) / (float)mIntervalTime * 360; // draw 2dips thick marker // the formula to draw the marker 1 unit thick is: // 180 / (radius * Math.PI) // after that we have to scale it by the screen density canvas.drawArc (mArcRect, 270 + angle, mScreenDensity * (float) (360 / (radius * Math.PI)) , false, mPaint); } drawRedDiamond(canvas, redPercent, xCenter, yCenter, radius); } if (mAnimate) { invalidate(); } } protected void drawRedDiamond( Canvas canvas, float degrees, int xCenter, int yCenter, float radius) { mPaint.setColor(mRedColor); float diamondPercent; if (mTimerMode) { diamondPercent = 270 - degrees * 360; } else { diamondPercent = 270 + degrees * 360; } canvas.save(); final double diamondRadians = Math.toRadians(diamondPercent); canvas.translate(xCenter + (float) (radius * Math.cos(diamondRadians)), yCenter + (float) (radius * Math.sin(diamondRadians))); canvas.rotate(diamondPercent + 45f); canvas.drawRect(-mRectHalfWidth, -mRectHalfWidth, mRectHalfWidth, mRectHalfWidth, mFill); canvas.restore(); } public static final String PREF_CTV_PAUSED = "_ctv_paused"; public static final String PREF_CTV_INTERVAL = "_ctv_interval"; public static final String PREF_CTV_INTERVAL_START = "_ctv_interval_start"; public static final String PREF_CTV_CURRENT_INTERVAL = "_ctv_current_interval"; public static final String PREF_CTV_ACCUM_TIME = "_ctv_accum_time"; public static final String PREF_CTV_TIMER_MODE = "_ctv_timer_mode"; public static final String PREF_CTV_MARKER_TIME = "_ctv_marker_time"; // Since this view is used in multiple places, use the key to save different instances public void writeToSharedPref(SharedPreferences prefs, String key) { SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean (key + PREF_CTV_PAUSED, mPaused); editor.putLong (key + PREF_CTV_INTERVAL, mIntervalTime); editor.putLong (key + PREF_CTV_INTERVAL_START, mIntervalStartTime); editor.putLong (key + PREF_CTV_CURRENT_INTERVAL, mCurrentIntervalTime); editor.putLong (key + PREF_CTV_ACCUM_TIME, mAccumulatedTime); editor.putLong (key + PREF_CTV_MARKER_TIME, mMarkerTime); editor.putBoolean (key + PREF_CTV_TIMER_MODE, mTimerMode); editor.apply(); } public void readFromSharedPref(SharedPreferences prefs, String key) { mPaused = prefs.getBoolean(key + PREF_CTV_PAUSED, false); mIntervalTime = prefs.getLong(key + PREF_CTV_INTERVAL, 0); mIntervalStartTime = prefs.getLong(key + PREF_CTV_INTERVAL_START, -1); mCurrentIntervalTime = prefs.getLong(key + PREF_CTV_CURRENT_INTERVAL, 0); mAccumulatedTime = prefs.getLong(key + PREF_CTV_ACCUM_TIME, 0); mMarkerTime = prefs.getLong(key + PREF_CTV_MARKER_TIME, -1); mTimerMode = prefs.getBoolean(key + PREF_CTV_TIMER_MODE, false); mAnimate = (mIntervalStartTime != -1 && !mPaused); } public void clearSharedPref(SharedPreferences prefs, String key) { SharedPreferences.Editor editor = prefs.edit(); editor.remove (Stopwatches.PREF_START_TIME); editor.remove (Stopwatches.PREF_ACCUM_TIME); editor.remove (Stopwatches.PREF_STATE); editor.remove (key + PREF_CTV_PAUSED); editor.remove (key + PREF_CTV_INTERVAL); editor.remove (key + PREF_CTV_INTERVAL_START); editor.remove (key + PREF_CTV_CURRENT_INTERVAL); editor.remove (key + PREF_CTV_ACCUM_TIME); editor.remove (key + PREF_CTV_MARKER_TIME); editor.remove (key + PREF_CTV_TIMER_MODE); editor.apply(); } }
package com.android.deskclock; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.Typeface; import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.view.View; /** * TODO: Insert description here. (generated by isaackatz) */ public class CircleTimerView extends View { private int mRedColor; private int mWhiteColor; private long mIntervalTime = 0; private long mIntervalStartTime = -1; private long mMarkerTime = -1; private long mCurrentIntervalTime = 0; private long mAccumulatedTime = 0; private boolean mPaused = false; private static float mStrokeSize = 4; private static float mDiamondStrokeSize = 12; private static float mMarkerStrokeSize = 2; private final Paint mPaint = new Paint(); private final RectF mArcRect = new RectF(); private Resources mResources; private float mRadiusOffset; // amount to remove from radius to account for markers on circle // Class has 2 modes: // Timer mode - counting down. in this mode the animation is counter-clockwise and stops at 0 // Stop watch mode - counting up - in this mode the animation is clockwise and will keep the // animation until stopped. private boolean mTimerMode = false; // default is stop watch view Runnable mAnimationThread = new Runnable() { @Override public void run() { mCurrentIntervalTime = System.currentTimeMillis() - mIntervalStartTime + mAccumulatedTime; invalidate(); postDelayed(mAnimationThread, 20); } }; public CircleTimerView(Context context) { this(context, null); } public CircleTimerView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public void setIntervalTime(long t) { mIntervalTime = t; postInvalidate(); } public void setMarkerTime(long t) { mMarkerTime = mCurrentIntervalTime; postInvalidate(); } public void reset() { mIntervalStartTime = -1; mMarkerTime = -1; postInvalidate(); } public void startIntervalAnimation() { mIntervalStartTime = System.currentTimeMillis(); this.post(mAnimationThread); mPaused = false; } public void stopIntervalAnimation() { this.removeCallbacks(mAnimationThread); mIntervalStartTime = -1; mAccumulatedTime = 0; } public boolean isAnimating() { return (mIntervalStartTime != -1); } public void pauseIntervalAnimation() { this.removeCallbacks(mAnimationThread); mAccumulatedTime += System.currentTimeMillis() - mIntervalStartTime; mPaused = true; } public void setPassedTime(long time) { mAccumulatedTime = time; postInvalidate(); } private void init(Context c) { mResources = c.getResources(); mStrokeSize = mResources.getDimension(R.dimen.circletimer_circle_size); mDiamondStrokeSize = mResources.getDimension(R.dimen.circletimer_diamond_size); mMarkerStrokeSize = mResources.getDimension(R.dimen.circletimer_marker_size) * 2 + mStrokeSize; mPaint.setAntiAlias(true); mPaint.setStyle(Paint.Style.STROKE); mWhiteColor = mResources.getColor(R.color.clock_white); mRedColor = mResources.getColor(R.color.clock_red); mRadiusOffset = Math.max(mStrokeSize, Math.max(mDiamondStrokeSize, mMarkerStrokeSize)); } public void setTimerMode(boolean mode) { mTimerMode = mode; } @Override public void onDraw(Canvas canvas) { int xCenter = getWidth() / 2 + 1; int yCenter = getHeight() / 2; mPaint.setStrokeWidth(mStrokeSize); float radius = Math.min(xCenter, yCenter) - mRadiusOffset; if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { xCenter = (int) (radius + mRadiusOffset); } mPaint.setColor(mWhiteColor); canvas.drawCircle (xCenter, yCenter, radius, mPaint); mPaint.setColor(mRedColor); if (mIntervalStartTime != -1) { mArcRect.top = yCenter - radius; mArcRect.bottom = yCenter + radius; mArcRect.left = xCenter - radius; mArcRect.right = xCenter + radius; float percent = (float)mCurrentIntervalTime / (float)mIntervalTime; // prevent timer from doing more than one full circle percent = (percent > 1 && mTimerMode) ? 1 : percent; if (mTimerMode){ canvas.drawArc (mArcRect, 270, - percent * 360 , false, mPaint); } else { canvas.drawArc (mArcRect, 270, + percent * 360 , false, mPaint); } mPaint.setStrokeWidth(mDiamondStrokeSize); if (mTimerMode){ canvas.drawArc (mArcRect, 265 - percent * 360, 10 , false, mPaint); } else { canvas.drawArc (mArcRect, 265 + percent * 360, 10 , false, mPaint); } } if (mMarkerTime != -1) { mPaint.setStrokeWidth(mMarkerStrokeSize); mPaint.setColor(mWhiteColor); float angle = (float)(mMarkerTime % mIntervalTime) / (float)mIntervalTime * 360; canvas.drawArc (mArcRect, 270 + angle, 1 , false, mPaint); } } private static final String PREF_CTV_PAUSED = "_ctv_paused"; private static final String PREF_CTV_INTERVAL = "_ctv_interval"; private static final String PREF_CTV_INTERVAL_START = "_ctv_interval_start"; private static final String PREF_CTV_CURRENT_INTERVAL = "_ctv_current_interval"; private static final String PREF_CTV_ACCUM_TIME = "_ctv_accum_time"; private static final String PREF_CTV_TIMER_MODE = "_ctv_timer_mode"; private static final String PREF_CTV_MARKER_TIME = "_ctv_marker_time"; // Since this view is used in multiple places, use the key to save different instances public void writeToSharedPref(SharedPreferences prefs, String key) { SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean (key + PREF_CTV_PAUSED, mPaused); editor.putLong (key + PREF_CTV_INTERVAL, mIntervalTime); editor.putLong (key + PREF_CTV_INTERVAL_START, mIntervalStartTime); editor.putLong (key + PREF_CTV_CURRENT_INTERVAL, mCurrentIntervalTime); editor.putLong (key + PREF_CTV_ACCUM_TIME, mAccumulatedTime); editor.putLong (key + PREF_CTV_MARKER_TIME, mMarkerTime); editor.putBoolean (key + PREF_CTV_TIMER_MODE, mTimerMode); editor.apply(); } public void readFromSharedPref(SharedPreferences prefs, String key) { mPaused = prefs.getBoolean(key + PREF_CTV_PAUSED, false); mIntervalTime = prefs.getLong(key + PREF_CTV_INTERVAL, 0); mIntervalStartTime = prefs.getLong(key + PREF_CTV_INTERVAL_START, -1); mCurrentIntervalTime = prefs.getLong(key + PREF_CTV_CURRENT_INTERVAL, 0); mAccumulatedTime = prefs.getLong(key + PREF_CTV_ACCUM_TIME, 0); mMarkerTime = prefs.getLong(key + PREF_CTV_MARKER_TIME, -1); mTimerMode = prefs.getBoolean(key + PREF_CTV_TIMER_MODE, false); if (mIntervalStartTime != -1 && !mPaused) { this.post(mAnimationThread); } } }
package com.antsapps.triples; import java.util.ArrayList; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewPager; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.ActionBar.Tab; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import com.antsapps.triples.backend.Application; import com.antsapps.triples.backend.Game; import com.antsapps.triples.backend.Period; import com.antsapps.triples.backend.Statistics; import com.antsapps.triples.stats.StatisticsFragment; public class GameListActivity extends SherlockFragmentActivity implements GameHelper.GameHelperListener { private static final String TAB_NUMBER = "tab"; public static final String SIGNIN_PREFS = "signin_prefs"; public static final String SIGNED_IN_PREVIOUSLY = "signed_in_previously"; public static final String UPLOADED_EXISTING_TOP_SCORE = "uploaded_existing_top_score_2"; private ViewPager mViewPager; private TabsAdapter mTabsAdapter; private Application mApplication; private GameHelper mHelper; private GameHelper.GameHelperListener mGameHelperListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mApplication = Application.getInstance(getApplication()); setContentView(R.layout.game_overview); final ActionBar bar = getSupportActionBar(); bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); mViewPager = (ViewPager) findViewById(R.id.pager); setContentView(mViewPager); mTabsAdapter = new TabsAdapter(this, mViewPager); mTabsAdapter.addTab( bar.newTab().setText(R.string.current), CurrentGameListFragment.class, null); mTabsAdapter.addTab( bar.newTab().setText(R.string.statistics), StatisticsFragment.class, null); if (savedInstanceState != null) { bar.setSelectedNavigationItem(savedInstanceState.getInt(TAB_NUMBER, 0)); } mHelper = new GameHelper(this); mHelper.setup(this, GameHelper.CLIENT_PLUS | GameHelper.CLIENT_GAMES); } @Override protected void onStart() { super.onStart(); mHelper.onStart(this); } @Override protected void onStop() { super.onStop(); mHelper.onStop(); } @Override protected void onActivityResult(int request, int response, Intent data) { super.onActivityResult(request, response, data); mHelper.onActivityResult(request, response, data); } public GameHelper getGameHelper() { return mHelper; } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getSupportMenuInflater(); inflater.inflate(R.menu.game_list, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); menu.findItem(R.id.signout).setVisible(mHelper.isSignedIn()); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.new_game: Game game = Game.createFromSeed(System.currentTimeMillis()); mApplication.addGame(game); Intent newGameIntent = new Intent(getBaseContext(), GameActivity.class); newGameIntent.putExtra(Game.ID_TAG, game.getId()); startActivity(newGameIntent); return true; case R.id.help: Intent helpIntent = new Intent(getBaseContext(), HelpActivity.class); startActivity(helpIntent); return true; case R.id.settings: Intent settingsIntent = new Intent(getBaseContext(), SettingsActivity.class); startActivity(settingsIntent); return true; case R.id.signout: mHelper.signOut(); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(TAB_NUMBER, getSupportActionBar() .getSelectedNavigationIndex()); } @Override public void onSignInFailed() { if (mGameHelperListener != null) { mGameHelperListener.onSignInFailed(); } } @Override public void onSignInSucceeded() { if (mGameHelperListener != null) { mGameHelperListener.onSignInSucceeded(); } invalidateOptionsMenu(); uploadExistingTopScoresIfNecessary(); } @Override public void onSignOut() { if (mGameHelperListener != null) { mGameHelperListener.onSignOut(); } invalidateOptionsMenu(); } private void uploadExistingTopScoresIfNecessary() { SharedPreferences settings = getSharedPreferences(SIGNIN_PREFS, 0); if (settings.getBoolean(UPLOADED_EXISTING_TOP_SCORE, false)) { return; } Statistics stats = mApplication.getStatistics(Period.ALL_TIME); mHelper.getGamesClient().submitScore(GamesServices.Leaderboard.CLASSIC, stats.getFastestTime()); // We need an Editor object to make preference changes. // All objects are from android.context.Context SharedPreferences.Editor editor = settings.edit(); editor.putBoolean(UPLOADED_EXISTING_TOP_SCORE, true); // Commit the edits! editor.commit(); } public void setGameHelperListener(GameHelper.GameHelperListener listener) { mGameHelperListener = listener; } /** * This is a helper class that implements the management of tabs and all * details of connecting a ViewPager with associated TabHost. It relies on a * trick. Normally a tab host has a simple API for supplying a View or Intent * that each tab will show. This is not sufficient for switching between * pages. So instead we make the content part of the tab host 0dp high (it is * not shown) and the TabsAdapter supplies its own dummy view to show as the * tab content. It listens to changes in tabs, and takes care of switch to the * correct paged in the ViewPager whenever the selected tab changes. */ public static class TabsAdapter extends FragmentPagerAdapter implements ActionBar.TabListener, ViewPager.OnPageChangeListener { private final Context mContext; private final ActionBar mActionBar; private final ViewPager mViewPager; private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>(); static final class TabInfo { private final Class<?> clss; private final Bundle args; TabInfo(Class<?> _class, Bundle _args) { clss = _class; args = _args; } } public TabsAdapter(SherlockFragmentActivity activity, ViewPager pager) { super(activity.getSupportFragmentManager()); mContext = activity; mActionBar = activity.getSupportActionBar(); mViewPager = pager; mViewPager.setAdapter(this); mViewPager.setOnPageChangeListener(this); } public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) { TabInfo info = new TabInfo(clss, args); tab.setTag(info); tab.setTabListener(this); mTabs.add(info); mActionBar.addTab(tab); notifyDataSetChanged(); } @Override public int getCount() { return mTabs.size(); } @Override public Fragment getItem(int position) { TabInfo info = mTabs.get(position); return Fragment.instantiate(mContext, info.clss.getName(), info.args); } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { mActionBar.setSelectedNavigationItem(position); } @Override public void onPageScrollStateChanged(int state) { } @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { Object tag = tab.getTag(); for (int i = 0; i < mTabs.size(); i++) { if (mTabs.get(i) == tag) { mViewPager.setCurrentItem(i); } } } @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) { } @Override public void onTabReselected(Tab tab, FragmentTransaction ft) { } } }
package com.dmdirc.addons.identd; import com.dmdirc.Server; import com.dmdirc.ServerManager; import com.dmdirc.actions.ActionType; import com.dmdirc.actions.CoreActionType; import com.dmdirc.plugins.EventPlugin; import com.dmdirc.plugins.Plugin; import java.util.ArrayList; import java.util.List; /** * The Identd plugin answers ident requests from IRC servers. For privacy, it * is only active while there is an active connection attempt. * * @author Chris */ public class IdentdPlugin extends Plugin implements EventPlugin { private final List<Server> servers = new ArrayList<Server>(); /** * Creates a new instance of IdentdPlugin. */ public IdentdPlugin() { } /** {@inheritDoc} */ public boolean onLoad() { return true; } /** {@inheritDoc} */ public String getVersion() { return "0.1"; } /** {@inheritDoc} */ public String getAuthor() { return "Chris <chris@dmdirc.com>"; } /** {@inheritDoc} */ public String getDescription() { return "Answers ident requests from IRC servers"; } /** {@inheritDoc} */ public String toString() { return "Identd"; } /** {@inheritDoc} */ public void processEvent(final ActionType type, final StringBuffer format, final Object... arguments) { if (type == CoreActionType.SERVER_CONNECTING) { if (servers.size() == 0) { // TODO: Start the identd } servers.add((Server) arguments[0]); } else if (type == CoreActionType.SERVER_CONNECTED || type == CoreActionType.SERVER_CONNECTERROR) { servers.remove((Server) arguments[0]); if (servers.size() == 0) { // TODO: Stop the identd } } } /** * Retrieves the server that is bound to the specified local port. * * @param The server instance listening on the specified port */ private Server getServerByPort(final int port) { for (Server server : ServerManager.getServerManager().getServers()) { if (server.getParser().getLocalPort() == port) { return server; } } return null; } }
package com.ecyrd.jspwiki.plugin; import com.ecyrd.jspwiki.*; import com.ecyrd.jspwiki.providers.ProviderException; import org.apache.log4j.Category; import java.text.SimpleDateFormat; import java.text.ParseException; import java.util.*; /** * Builds a simple weblog. * <P> * The pageformat can use the following params:<br> * %p - Page name<br> * * <B>Parameters</B> * <UL> * <LI>days - how many days the weblog aggregator should show. * <LI>pageformat - What the entry pages should look like. * <LI>startDate - Date when to start. Format is "ddMMyy"; * <li>maxEntries - How many entries to show at most. * </UL> * * The "days" and "startDate" can also be sent in HTTP parameters, * and the names are "weblog.days" and "weblog.startDate", respectively. * * @since 1.9.21 */ // FIXME: Add "entries" param as an alternative to "days". // FIXME: Entries arrive in wrong order. public class WeblogPlugin implements WikiPlugin { private static Category log = Category.getInstance(WeblogPlugin.class); public static final int DEFAULT_DAYS = 7; public static final String DEFAULT_PAGEFORMAT = "%p_blogentry_"; public static final String DEFAULT_DATEFORMAT = "ddMMyy"; public static final String PARAM_STARTDATE = "startDate"; public static final String PARAM_DAYS = "days"; public static final String PARAM_ALLOWCOMMENTS = "allowComments"; public static final String PARAM_MAXENTRIES = "maxEntries"; public static String makeEntryPage( String pageName, String date, String entryNum ) { return TextUtil.replaceString(DEFAULT_PAGEFORMAT,"%p",pageName)+date+"_"+entryNum; } public static String makeEntryPage( String pageName ) { return TextUtil.replaceString(DEFAULT_PAGEFORMAT,"%p",pageName); } public static String makeEntryPage( String pageName, String date ) { return TextUtil.replaceString(DEFAULT_PAGEFORMAT,"%p",pageName)+date; } public String execute( WikiContext context, Map params ) throws PluginException { String weblogName = context.getPage().getName(); Calendar startTime; Calendar stopTime; int numDays; WikiEngine engine = context.getEngine(); // Parse parameters. String days; String startDay = null; boolean hasComments = false; int maxEntries; if( (days = context.getHttpParameter( "weblog."+PARAM_DAYS )) == null ) { days = (String) params.get( PARAM_DAYS ); } numDays = TextUtil.parseIntParameter( days, DEFAULT_DAYS ); if( (startDay = (String)params.get(PARAM_STARTDATE)) == null ) { startDay = context.getHttpParameter( "weblog."+PARAM_STARTDATE ); } if( TextUtil.isPositive( (String)params.get(PARAM_ALLOWCOMMENTS) ) ) { hasComments = true; } maxEntries = TextUtil.parseIntParameter( (String)params.get(PARAM_MAXENTRIES), Integer.MAX_VALUE ); // Determine the date range which to include. startTime = Calendar.getInstance(); stopTime = Calendar.getInstance(); if( startDay != null ) { SimpleDateFormat fmt = new SimpleDateFormat( DEFAULT_DATEFORMAT ); try { Date d = fmt.parse( startDay ); startTime.setTime( d ); stopTime.setTime( d ); } catch( ParseException e ) { return "Illegal time format: "+startDay; } } // We make a wild guess here that nobody can do millisecond // accuracy here. startTime.add( Calendar.DAY_OF_MONTH, -numDays ); startTime.set( Calendar.HOUR, 0 ); startTime.set( Calendar.MINUTE, 0 ); startTime.set( Calendar.SECOND, 0 ); stopTime.set( Calendar.HOUR, 23 ); stopTime.set( Calendar.MINUTE, 59 ); stopTime.set( Calendar.SECOND, 59 ); StringBuffer sb = new StringBuffer(); try { List blogEntries = findBlogEntries( engine.getPageManager(), weblogName, startTime.getTime(), stopTime.getTime() ); Collections.sort( blogEntries, new PageDateComparator() ); SimpleDateFormat entryDateFmt = new SimpleDateFormat("dd-MMM-yyyy HH:mm"); sb.append("<div class=\"weblog\">\n"); for( Iterator i = blogEntries.iterator(); i.hasNext() && maxEntries { WikiPage p = (WikiPage) i.next(); sb.append("<div class=\"weblogentry\">\n"); // Heading sb.append("<div class=\"weblogentryheading\">\n"); Date entryDate = p.getLastModified(); sb.append( entryDateFmt.format(entryDate) ); sb.append("</div>\n"); // Append the text of the latest version. Reset the // context to that page. sb.append("<div class=\"weblogentrybody\">\n"); WikiContext entryCtx = new WikiContext( engine, p ); sb.append( engine.getHTML( entryCtx, engine.getPage(p.getName()) ) ); sb.append("</div>\n"); // Append footer sb.append("<div class=\"weblogentryfooter\">\n"); String author = p.getAuthor(); if( author != null ) { if( engine.pageExists(author) ) { author = "<a href=\""+engine.getViewURL( author )+"\">"+author+"</a>"; } } else { author = "AnonymousCoward"; } sb.append("By "+author+"&nbsp;&nbsp;"); sb.append( "<a href=\""+engine.getViewURL(p.getName())+"\">Permalink</a>" ); String commentPageName = TextUtil.replaceString( p.getName(), "blogentry", "comments" ); if( hasComments ) { int numComments = guessNumberOfComments( engine, commentPageName ); // We add the number of comments to the URL so that // the user's browsers would realize that the page // has changed. sb.append( "&nbsp;&nbsp;" ); sb.append( "<a target=\"_blank\" href=\""+ engine.getBaseURL()+ "Comment.jsp?page="+ engine.encodeName(commentPageName)+ "&nc="+numComments+"\">Comments? ("+ numComments+ ")</a>" ); } sb.append("</div>\n"); // Done, close sb.append("</div>\n"); } sb.append("</div>\n"); } catch( ProviderException e ) { log.error( "Could not locate blog entries", e ); throw new PluginException( "Could not locate blog entries: "+e.getMessage() ); } return sb.toString(); } private int guessNumberOfComments( WikiEngine engine, String commentpage ) throws ProviderException { String pagedata = engine.getPureText( commentpage, WikiProvider.LATEST_VERSION ); int tags = 0; int start = 0; while( (start = pagedata.indexOf("----",start)) != -1 ) { tags++; start+=4; } return pagedata.length() > 0 ? tags+1 : 0; } /** * Attempts to locate all pages that correspond to the * blog entry pattern. Will only consider the days on the dates; not the hours and minutes. * * Returns a list of pages with their FIRST revisions. */ public List findBlogEntries( PageManager mgr, String baseName, Date start, Date end ) throws ProviderException { Collection everyone = mgr.getAllPages(); ArrayList result = new ArrayList(); baseName = makeEntryPage( baseName ); SimpleDateFormat fmt = new SimpleDateFormat(DEFAULT_DATEFORMAT); for( Iterator i = everyone.iterator(); i.hasNext(); ) { WikiPage p = (WikiPage)i.next(); String pageName = p.getName(); if( pageName.startsWith( baseName ) ) { // Check the creation date from the page name. // We do this because RCSFileProvider is very slow at getting a // specific page version. try { //log.debug("Checking: "+pageName); int firstScore = pageName.indexOf('_',baseName.length()-1 ); if( firstScore != -1 && firstScore+1 < pageName.length() ) { int secondScore = pageName.indexOf('_', firstScore+1); if( secondScore != -1 ) { String creationDate = pageName.substring( firstScore+1, secondScore ); Date pageDay = fmt.parse( creationDate ); // Add the first version of the page into the list. This way // the page modified date becomes the page creation date. if( pageDay != null && pageDay.after(start) && pageDay.before(end) ) { WikiPage firstVersion = mgr.getPageInfo( pageName, 1 ); result.add( firstVersion ); } } } } catch( Exception e ) { log.debug("Page name :"+pageName+" was suspected as a blog entry but it isn't because of parsing errors",e); } } } return result; } /** * Reverse comparison. */ private class PageDateComparator implements Comparator { public int compare( Object o1, Object o2 ) { if( o1 == null || o2 == null ) { return 0; } WikiPage page1 = (WikiPage)o1; WikiPage page2 = (WikiPage)o2; return page2.getLastModified().compareTo( page1.getLastModified() ); } } }
package com.ezevents.android.app; import java.io.IOException; import java.util.List; import android.content.Intent; import android.location.Address; import android.location.Geocoder; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; public class MapsActivity extends FragmentActivity { GoogleMap googleMap; MarkerOptions markerOptions; LatLng latLng; private double lat; private double lon; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.map); SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); Button mSecondNextButton = (Button) findViewById(R.id.maps_next); mSecondNextButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(view.getContext(), CheckListActivity.class); //attemptLogin(); startActivity(intent); } }); // Getting a reference to the map googleMap = supportMapFragment.getMap(); googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); googleMap.setMyLocationEnabled(true); // Getting reference to btn_find of the layout activity_main Button btn_find = (Button) findViewById(R.id.btn_find); // Defining button click event listener for the find button OnClickListener findClickListener = new OnClickListener() { @Override public void onClick(View v) { // Getting reference to EditText to get the user input location EditText etLocation = (EditText) findViewById(R.id.et_location); // Getting user input location String location = etLocation.getText().toString(); if(location!=null && !location.equals("")){ new GeocoderTask().execute(location); } } }; // Setting button click event listener for the find button btn_find.setOnClickListener(findClickListener); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.event_second_step, menu); return true; } // An AsyncTask class for accessing the GeoCoding Web Service private class GeocoderTask extends AsyncTask<String, Void, List<Address>>{ @Override protected List<Address> doInBackground(String... locationName) { // Creating an instance of Geocoder class Geocoder geocoder = new Geocoder(getBaseContext()); List<Address> addresses = null; try { // Getting a maximum of 3 Address that matches the input text addresses = geocoder.getFromLocationName(locationName[0], 3); } catch (IOException e) { e.printStackTrace(); } return addresses; } @Override protected void onPostExecute(List<Address> addresses) { if(addresses==null || addresses.size()==0){ Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show(); } // Clears all the existing markers on the map googleMap.clear(); // Adding Markers on Google Map for each matching address for(int i=0;i<addresses.size();i++){ Address address = addresses.get(i); // Creating an instance of GeoPoint, to display in Google Map latLng = new LatLng(address.getLatitude(), address.getLongitude()); String addressText = String.format("%s, %s", address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "", address.getCountryName()); markerOptions = new MarkerOptions(); markerOptions.position(latLng); markerOptions.title(addressText); lat = latLng.latitude; lon = latLng.longitude; googleMap.addMarker(markerOptions); // Locate the first location if(i==0) googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng)); } } } }
package com.fsck.k9.activity; import com.fsck.k9.Account; import com.fsck.k9.K9; import com.fsck.k9.Preferences; import com.fsck.k9.R; import com.fsck.k9.mail.Store; import com.fsck.k9.service.DatabaseUpgradeService; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import android.widget.TextView; /** * This activity triggers a database upgrade if necessary and displays the current upgrade progress. * * <p> * The current upgrade process works as follows: * <ol> * <li>Activities that access an account's database call * {@link #actionUpgradeDatabases(Context, Intent)} in their {@link Activity#onCreate(Bundle)} * method.</li> * <li>{@link #actionUpgradeDatabases(Context, Intent)} will call {@link K9#areDatabasesUpToDate()} * to check if we already know whether the databases have been upgraded.</li> * <li>{@link K9#areDatabasesUpToDate()} will compare the last known database version stored in a * {@link SharedPreferences} file to {@link com.fsck.k9.mail.store.LocalStore#DB_VERSION}. This * is done as an optimization because it's faster than opening all of the accounts' databases * one by one.</li> * <li>If there was an error reading the cached database version or if it shows the databases need * upgrading this activity ({@code UpgradeDatabases}) is started.</li> * <li>This activity will display a spinning progress indicator and start * {@link DatabaseUpgradeService}.</li> * <li>{@link DatabaseUpgradeService} will acquire a partial wake lock (with a 10 minute timeout), * start a background thread to perform the database upgrades, and report the progress using * {@link LocalBroadcastManager} to this activity which will update the UI accordingly.</li> * <li>Once the upgrade is complete {@link DatabaseUpgradeService} will notify this activity, * release the wake lock, and stop itself.</li> * <li>This activity will start the original activity using the intent supplied when calling * {@link #actionUpgradeDatabases(Context, Intent)}.</li> * </ol> * </p><p> * Currently we make no attempts to stop the background code (e.g. {@link MessagingController}) from * opening the accounts' databases. If this happens the upgrade is performed in one of the * background threads and not by {@link DatabaseUpgradeService}. But this is not a problem. Due to * the locking in {@link Store#getLocalInstance(Account, android.app.Application)} the upgrade * service will block in the {@link Account#getLocalStore()} call and from the outside (especially * for this activity) it will appear as if {@link DatabaseUpgradeService} is performing the upgrade. * </p> */ public class UpgradeDatabases extends K9Activity { private static final String ACTION_UPGRADE_DATABASES = "upgrade_databases"; private static final String EXTRA_START_INTENT = "start_intent"; /** * Start the {@link UpgradeDatabases} activity if necessary. * * @param context * The {@link Context} used to start the activity. * @param startIntent * After the database upgrade is complete an activity is started using this intent. * Usually this is the intent that was used to start the calling activity. * Never {@code null}. * * @return {@code true}, if the {@code UpgradeDatabases} activity was started. In this case the * calling activity is expected to finish itself.<br> * {@code false}, if the account databases don't need upgrading. */ public static boolean actionUpgradeDatabases(Context context, Intent startIntent) { if (K9.areDatabasesUpToDate()) { return false; } Intent intent = new Intent(context, UpgradeDatabases.class); intent.setAction(ACTION_UPGRADE_DATABASES); intent.putExtra(EXTRA_START_INTENT, startIntent); // Make sure this activity is only running once intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); context.startActivity(intent); return true; } private Intent mStartIntent; private TextView mUpgradeText; private LocalBroadcastManager mLocalBroadcastManager; private UpgradeDatabaseBroadcastReceiver mBroadcastReceiver; private IntentFilter mIntentFilter; private Preferences mPreferences; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // If the databases have already been upgraded there's no point in displaying this activity. if (K9.areDatabasesUpToDate()) { launchOriginalActivity(); return; } mPreferences = Preferences.getPreferences(getApplicationContext()); initializeLayout(); decodeExtras(); setupBroadcastReceiver(); } /** * Initialize the activity's layout */ private void initializeLayout() { setContentView(R.layout.upgrade_databases); mUpgradeText = (TextView) findViewById(R.id.databaseUpgradeText); } /** * Decode extras in the intent used to start this activity. */ private void decodeExtras() { Intent intent = getIntent(); mStartIntent = intent.getParcelableExtra(EXTRA_START_INTENT); } /** * Setup the broadcast receiver used to receive progress updates from * {@link DatabaseUpgradeService}. */ private void setupBroadcastReceiver() { mLocalBroadcastManager = LocalBroadcastManager.getInstance(this); mBroadcastReceiver = new UpgradeDatabaseBroadcastReceiver(); mIntentFilter = new IntentFilter(DatabaseUpgradeService.ACTION_UPGRADE_PROGRESS); mIntentFilter.addAction(DatabaseUpgradeService.ACTION_UPGRADE_COMPLETE); } @Override public void onResume() { super.onResume(); // Check if the upgrade was completed while the activity was paused. if (K9.areDatabasesUpToDate()) { launchOriginalActivity(); return; } // Register the broadcast receiver to listen for progress reports from // DatabaseUpgradeService. mLocalBroadcastManager.registerReceiver(mBroadcastReceiver, mIntentFilter); // Now that the broadcast receiver was registered start DatabaseUpgradeService. DatabaseUpgradeService.startService(this); } @Override public void onPause() { // The activity is being paused, so there's no point in listening to the progress of the // database upgrade service. mLocalBroadcastManager.unregisterReceiver(mBroadcastReceiver); super.onPause(); } /** * Finish this activity and launch the original activity using the supplied intent. */ private void launchOriginalActivity() { finish(); if (mStartIntent != null) { startActivity(mStartIntent); } } /** * Receiver for broadcasts send by {@link DatabaseUpgradeService}. */ class UpgradeDatabaseBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, final Intent intent) { String action = intent.getAction(); if (DatabaseUpgradeService.ACTION_UPGRADE_PROGRESS.equals(action)) { /* * Information on the current upgrade progress */ String accountUuid = intent.getStringExtra( DatabaseUpgradeService.EXTRA_ACCOUNT_UUID); Account account = mPreferences.getAccount(accountUuid); if (account != null) { String formatString = getString(R.string.upgrade_database_format); String upgradeStatus = String.format(formatString, account.getDescription()); mUpgradeText.setText(upgradeStatus); } } else if (DatabaseUpgradeService.ACTION_UPGRADE_COMPLETE.equals(action)) { /* * Upgrade complete */ launchOriginalActivity(); } } } }
package com.github.pozo.bkkinfo; import com.github.pozo.bkkinfo.model.Entry; import com.github.pozo.bkkinfo.model.Line; import com.github.pozo.bkkinfo.shared.LineColorHelper; import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.GradientDrawable; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.Gravity; import android.view.LayoutInflater; import android.view.ViewGroup.LayoutParams; import android.widget.LinearLayout; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; public class TableEntryRow { private static final String EMPTY_TABLE_TEXT = "Nincs a szűrésnek megfelelő tervezett forgalmi változás."; private static final String ENTRY_DETAILS = "Tovább..."; private Entry entry; private final Context context; public TableEntryRow(Context context, Entry entry) { this(context); this.entry = entry; } public TableEntryRow(Context context) { this.context = context; } public void addEmpty(final TableLayout table) { TextView textView = createEmptyTableRow(); table.addView(textView, new TableLayout.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT)); } public void add(final TableLayout activeTable) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final LinearLayout entryTableRow = (LinearLayout) inflater.inflate(R.layout.table_row, null); entryTableRow.setBackgroundResource(R.layout.row_selector); entryTableRow.setPadding(10, 10, 10, 10); entryTableRow.setLayoutParams(new LayoutParams(new TableLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT))); TableLayout tableView = (TableLayout) entryTableRow.findViewById(R.id.line_table); fillEntryTableRowLines(tableView); TextView textView = (TextView) entryTableRow.findViewById(R.id.cause); textView.setText(entry.getElnevezes()); TextView textViewFromTime = (TextView) entryTableRow.findViewById(R.id.from_time); textViewFromTime.setText(entry.getKezdSzoveg()); if (activeTable.getId() == R.id.active_table) { textViewFromTime.setTypeface(Typeface.DEFAULT,Typeface.ITALIC); textViewFromTime.setTextColor(context.getResources().getColor(R.color.gray)); } TextView textViewToTime = (TextView) entryTableRow.findViewById(R.id.to_time); textViewToTime.setText(entry.getVegeSzoveg()); entryTableRow.setOnClickListener(new TableRowClickListener(context, this, entryTableRow, activeTable)); activeTable.addView(entryTableRow, new TableLayout.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT)); LinearLayout ll = new LinearLayout(context); ll.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, 1)); ll.setBackgroundColor(Color.GRAY); activeTable.addView(ll); } private void fillEntryTableRowLines(TableLayout table) { for (Line line : entry.getLines()) { TableRow tableRow = createTableRow(); for (int i = 0; i < line.getLines().size(); i++) { if(i%2 != 0) { createLineTextView(line.getType(), line.getLines().get(i), tableRow, R.id.line_two); if(i!=0) { table.addView(tableRow); tableRow = createTableRow(); } } else { createLineTextView(line.getType(), line.getLines().get(i), tableRow, R.id.line_one); if(i == line.getLines().size()-1) { table.addView(tableRow); } } } } } private TableRow createTableRow() { LayoutInflater inflater = (LayoutInflater) context.getSystemService (Context.LAYOUT_INFLATER_SERVICE); TableRow tableRow = (TableRow) inflater.inflate(R.layout.table_line_row, null); TextView textView = (TextView) tableRow.findViewById(R.id.line_one); GradientDrawable bgShape = (GradientDrawable) textView.getBackground(); bgShape.setColor(Color.TRANSPARENT); textView = (TextView) tableRow.findViewById(R.id.line_two); bgShape = (GradientDrawable) textView.getBackground(); bgShape.setColor(Color.TRANSPARENT); return tableRow; } private void createLineTextView(String lineType, String lineName, TableRow tableRow, int cellId) { TextView textView = (TextView) tableRow.findViewById(cellId); textView.setText(lineName); correctTextSize(lineName, textView); textView.setTextColor(LineColorHelper.getTextColorByType(lineType, lineName)); GradientDrawable bgShape = (GradientDrawable) textView.getBackground(); bgShape.setColor(LineColorHelper.getColorByNameAndType(context, lineName, lineType)); } private TextView createEmptyTableRow() { TextView textView = new TextView(context); textView.setText(EMPTY_TABLE_TEXT); textView.setGravity(Gravity.CENTER); textView.setPadding(15, 15, 15, 15); textView.setTypeface(Typeface.DEFAULT, Typeface.ITALIC); return textView; } String getDescription() { if(entry.getDescription().equals("")) { return ENTRY_DETAILS; } else { return entry.getDescription() + "\n\n" + ENTRY_DETAILS; } } private void correctTextSize(String lineName, TextView textView) { if(lineName.length()>=4) { textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f); textView.setHeight((int)dipToPixels(context, 23f)); } if(lineName.length()>=6) { textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11f); textView.setHeight((int)dipToPixels(context, 23f)); } } public static float dipToPixels(Context context, float dipValue) { DisplayMetrics metrics = context.getResources().getDisplayMetrics(); return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, metrics); } public Entry getEntry() { return entry; } }
package com.googlecode.totallylazy; import com.googlecode.totallylazy.predicates.AndPredicate; import com.googlecode.totallylazy.predicates.BetweenPredicate; import com.googlecode.totallylazy.predicates.CountTo; import com.googlecode.totallylazy.predicates.EqualsPredicate; import com.googlecode.totallylazy.predicates.GreaterThanOrEqualToPredicate; import com.googlecode.totallylazy.predicates.GreaterThanPredicate; import com.googlecode.totallylazy.predicates.InPredicate; import com.googlecode.totallylazy.predicates.InstanceOf; import com.googlecode.totallylazy.predicates.LessThanOrEqualToPredicate; import com.googlecode.totallylazy.predicates.LessThanPredicate; import com.googlecode.totallylazy.predicates.LogicalPredicate; import com.googlecode.totallylazy.predicates.Not; import com.googlecode.totallylazy.predicates.NotNullPredicate; import com.googlecode.totallylazy.predicates.NullPredicate; import com.googlecode.totallylazy.predicates.OnlyOnce; import com.googlecode.totallylazy.predicates.OrPredicate; import com.googlecode.totallylazy.predicates.WherePredicate; import com.googlecode.totallylazy.predicates.WhileTrue; import java.util.Collection; import static com.googlecode.totallylazy.Sequences.sequence; public class Predicates { public static <T> LogicalPredicate<T> all() { return always(); } public static <T> LogicalPredicate<T> all(Class<T> aClass) { return always(); } public static <T> LogicalPredicate<T> always(Class<T> aClass) { return always(); } public static <T> LogicalPredicate<T> always() { return new LogicalPredicate<T>() { public boolean matches(T instance) { return true; } }; } public static <T> LogicalPredicate<T> never(Class<T> aClass) { return never(); } public static <T> LogicalPredicate<T> never() { return not(always()); } public static <T> LogicalPredicate<Collection<? extends T>> contains(final T t) { return new LogicalPredicate<Collection<? extends T>>() { public boolean matches(Collection<? extends T> other) { return other.contains(t); } }; } public static <T> LogicalPredicate<? super Iterable<T>> exists(final Predicate<? super T> predicate) { return new LogicalPredicate<Iterable<T>>() { public boolean matches(Iterable<T> iterable) { return sequence(iterable).exists(predicate); } }; } public static <T> LogicalPredicate<T> in(final T... values) { return in(sequence(values)); } public static <T> LogicalPredicate<T> in(final Sequence<T> values) { return new InPredicate<T>(values); } public static LogicalPredicate<? super Either> isLeft() { return new LogicalPredicate<Either>() { public boolean matches(Either either) { return either.isLeft(); } }; } public static LogicalPredicate<? super Either> isRight() { return new LogicalPredicate<Either>() { public boolean matches(Either either) { return either.isRight(); } }; } public static <T> LogicalPredicate<T> onlyOnce(final Predicate<? super T> predicate) { return new OnlyOnce<T>(predicate); } public static <T> LogicalPredicate<T> instanceOf(final Class t) { return new InstanceOf<T>(t); } public static <T> LogicalPredicate<T> equalTo(final T t) { return new EqualsPredicate<T>(t); } public static <T> LogicalPredicate<T> is(final T t) { return equalTo(t); } public static <S, T extends Predicate<S>> T is(final T t) { return t; } public static <T> LogicalPredicate<T> and(final Predicate<? super T>... predicates) { return new AndPredicate<T>(predicates); } public static <T> LogicalPredicate<T> or(final Predicate<? super T>... predicates) { return new OrPredicate<T>(predicates); } public static <T> LogicalPredicate<T> not(final T t) { return new Not<T>(is(t)); } public static <T> LogicalPredicate<T> not(final Predicate<? super T> t) { return new Not<T>(t); } public static <T> LogicalPredicate<T> countTo(final int count) { return new CountTo<T>(count); } public static <T> LogicalPredicate<T> whileTrue(final Predicate<? super T> t) { return new WhileTrue<T>(t); } public static <T> LogicalPredicate<T> nullValue() { return new NullPredicate<T>(); } public static <T> LogicalPredicate<T> nullValue(final Class<T> type) { return nullValue(); } public static <T> LogicalPredicate<T> notNullValue() { return new NotNullPredicate<T>(); } public static <T> LogicalPredicate<T> notNullValue(final Class<T> aClass) { return notNullValue(); } public static <T> LogicalPredicate<Option<T>> some(final Class<T> aClass) { return some(); } public static <T> LogicalPredicate<Option<T>> some() { return new LogicalPredicate<Option<T>>() { public final boolean matches(Option<T> other) { return !other.isEmpty(); } }; } public static LogicalPredicate<Class> assignableTo(final Object o) { return new LogicalPredicate<Class>() { public boolean matches(Class aClass) { return isAssignableTo(o, aClass); } }; } public static LogicalPredicate<Object> assignableTo(final Class aClass) { return new LogicalPredicate<Object>() { public boolean matches(Object o) { return isAssignableTo(o, aClass); } }; } public static boolean isAssignableTo(Object o, Class aClass) { if (o == null) return false; return aClass.isAssignableFrom(o.getClass()); } public static <T, R> LogicalPredicate<T> where(final Callable1<? super T, R> callable, final Predicate<? super R> predicate) { return new WherePredicate<T, R>(callable, predicate); } public static <T, R> LogicalPredicate<T> by(final Callable1<? super T, R> callable, final Predicate<? super R> predicate) { return where(callable, predicate); } public static <T> LogicalPredicate<? super Predicate<? super T>> matches(final T instance) { return new LogicalPredicate<Predicate<? super T>>() { public boolean matches(Predicate<? super T> predicate) { return predicate.matches(instance); } }; } public static <T extends Comparable<T>> LogicalPredicate<T> greaterThan(final T comparable) { return new GreaterThanPredicate<T>(comparable); } public static <T extends Comparable<T>> LogicalPredicate<T> greaterThanOrEqualTo(final T comparable) { return new GreaterThanOrEqualToPredicate<T>(comparable); } public static <T extends Comparable<T>> LogicalPredicate<T> lessThan(final T comparable) { return new LessThanPredicate<T>(comparable); } public static <T extends Comparable<T>> LogicalPredicate<T> lessThanOrEqualTo(final T comparable) { return new LessThanOrEqualToPredicate<T>(comparable); } public static <T extends Comparable<T>> LogicalPredicate<T> between(final T lower, final T upper) { return new BetweenPredicate<T>(lower, upper); } public static Predicate<Pair> equalTo() { return new Predicate<Pair>() { public boolean matches(Pair pair) { return pair.first().equals(pair.second()); } }; } }
package com.mambu.ant.phraseapp.api; /** * General constants for Phrase APP API integration. * * @author fgavrilescu */ final class Constants { static final String PHRASE_HOSTNAME = "api.phraseapp.com"; static final int PHRASE_PORT = 443; static final String PHRASE_PROTOCOL = "https"; static final String BASE_ENDPOINT = "https://api.phraseapp.com/api/v2/projects/%s"; private Constants() { } }
package com.shirish.camelExample; import javax.jms.ConnectionFactory; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.camel.component.ActiveMQComponent; import org.apache.camel.CamelContext; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.jms.JmsComponent; import org.apache.camel.impl.DefaultCamelContext; import org.apache.log4j.BasicConfigurator; import com.shirish.amqExample.AMQConstants; /** * @author shirish * */ public class CamelExample { public CamelExample() { } /** * @param args */ public static void main(String[] args) { try { BasicConfigurator.configure(); // create CamelContext CamelContext context = new DefaultCamelContext(); // connect to embedded ActiveMQ JMS broker //ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(AMQConstants.HostURL); //context.addComponent(AMQConstants.MQQueue, JmsComponent.jmsComponentAutoAcknowledge(connectionFactory)); ActiveMQComponent activemqcomp = ActiveMQComponent.activeMQComponent(AMQConstants.HostURL); context.addComponent(AMQConstants.MQQueue,activemqcomp); //&consumer.prefetchSize=50 //destination.consumer.prefetchSize=1 //acknowledgementModeName=AUTO_ACKNOWLEDGE //concurrentConsumers=2& // add our route to the CamelContext context.addRoutes(new RouteBuilder() { @Override public void configure() { // content-based router from(AMQConstants.MQQueue +":" + AMQConstants.VMQueueName + "?concurrentConsumers=2&destination.consumer.prefetchSize=10") .process(new Processor() { public void process(Exchange exchange) throws Exception { System.out.println( "Received XML order: " + exchange.getIn().getMandatoryBody()); Thread.sleep(1000); } }); } }); System.out.println("Starting up.. "); // start the route and let it do its work context.start(); Thread.sleep(Integer.MAX_VALUE); // stop the CamelContext context.stop(); } catch (Throwable e) { e.printStackTrace(); } } }
package com.stackexchange.stacman; import java.util.Date; import java.util.concurrent.Future; /** * Stack Exchange API Users methods */ public final class UserMethods { private StacManClient client; UserMethods(StacManClient forClient) { client = forClient; } public Future<StacManResponse<User>> getAll(String site, String filter, Integer page, Integer pageSize, Date fromDate, Date toDate, UserSort sort, Integer min, Integer max, Date minDate, Date maxDate, String minName, String maxName, Order order, String inName) { if(sort == null){ sort = UserSort.Default; } client.validateString(site, "site"); client.validatePaging(page, pageSize); client.validateSortMinMax(sort, min, max, minDate, maxDate, minName, maxName); ApiUrlBuilder ub = new ApiUrlBuilder("/users", false); ub.addParameter("site", site); ub.addParameter("filter", filter); ub.addParameter("page", page); ub.addParameter("pagesize", pageSize); ub.addParameter("fromdate", fromDate); ub.addParameter("todate", toDate); ub.addParameter("sort", sort); ub.addParameter("min", min); ub.addParameter("max", max); ub.addParameter("min", minDate); ub.addParameter("max", maxDate); ub.addParameter("min", minName); ub.addParameter("max", maxName); ub.addParameter("order", order); ub.addParameter("inname", inName); return client.createApiTask(Types.User, ub, "/users"); } public Future<StacManResponse<User>> getByIds(String site, Integer[] ids, String filter, Integer page, Integer pagesize, Date fromdate, Date todate, UserSort sort, Integer min, Integer max, Date mindate, Date maxdate, String minname, String maxname, Order order) { return getByIds(site, StacManClient.toIter(ids), filter, page, pagesize, fromdate, todate, sort, min, max, mindate, maxdate, minname, maxname, order); } public Future<StacManResponse<User>> getByIds(String site, Iterable<Integer> ids, String filter, Integer page, Integer pagesize, Date fromdate, Date todate, UserSort sort, Integer min, Integer max, Date mindate, Date maxdate, String minname, String maxname, Order order) { if(sort == null) { sort = UserSort.Default; } client.validateString(site, "site"); client.validateEnumerable(ids, "ids"); client.validatePaging(page, pagesize); client.validateSortMinMax(sort, min, max, mindate, maxdate, minname, maxname); ApiUrlBuilder ub = new ApiUrlBuilder( String.format( "/users/%1$S", StacManClient.join(";", ids) ), false ); ub.addParameter("site", site); ub.addParameter("filter", filter); ub.addParameter("page", page); ub.addParameter("pagesize", pagesize); ub.addParameter("fromdate", fromdate); ub.addParameter("todate", todate); ub.addParameter("sort", sort); ub.addParameter("min", min); ub.addParameter("max", max); ub.addParameter("min", mindate); ub.addParameter("max", maxdate); ub.addParameter("min", minname); ub.addParameter("max", maxname); ub.addParameter("order", order); return client.createApiTask(Types.User, ub, "/_users"); } public Future<StacManResponse<User>> getMe(String site, String access_token, String filter, Integer page, Integer pagesize, Date fromdate, Date todate, UserSort sort, Integer min, Integer max, Date mindate, Date maxdate, String minname, String maxname, Order order) { if(sort == null) { sort = UserSort.Default; } client.validateString(site, "site"); client.validateString(access_token, "access_token"); client.validatePaging(page, pagesize); client.validateSortMinMax(sort, min, max, mindate, maxdate, minname, maxname); ApiUrlBuilder ub = new ApiUrlBuilder("/me", true); ub.addParameter("site", site); ub.addParameter("access_token", access_token); ub.addParameter("filter", filter); ub.addParameter("page", page); ub.addParameter("pagesize", pagesize); ub.addParameter("fromdate", fromdate); ub.addParameter("todate", todate); ub.addParameter("sort", sort); ub.addParameter("min", min); ub.addParameter("max", max); ub.addParameter("min", mindate); ub.addParameter("max", maxdate); ub.addParameter("min", minname); ub.addParameter("max", maxname); ub.addParameter("order", order); return client.createApiTask(Types.User, ub, "/_users"); } public Future<StacManResponse<Answer>> getAnswers(String site, Integer[] ids, String filter, Integer page, Integer pagesize, Date fromdate, Date todate, AnswerSort sort, Date mindate, Date maxdate, Integer min, Integer max, Order order) { return getAnswers(site, StacManClient.toIter(ids), filter, page, pagesize, fromdate, todate, sort, mindate, maxdate, min, max, order); } public Future<StacManResponse<Answer>> getAnswers(String site, Iterable<Integer> ids, String filter, Integer page, Integer pagesize, Date fromdate, Date todate, AnswerSort sort, Date mindate, Date maxdate, Integer min, Integer max, Order order) { client.validateString(site, "site"); client.validateEnumerable(ids, "ids"); client.validatePaging(page, pagesize); client.validateSortMinMax(sort, mindate, maxdate, min, max); ApiUrlBuilder ub = new ApiUrlBuilder( String.format( "/users/%1$S/answers", StacManClient.join(";", ids) ), false ); ub.addParameter("site", site); ub.addParameter("filter", filter); ub.addParameter("page", page); ub.addParameter("pagesize", pagesize); ub.addParameter("fromdate", fromdate); ub.addParameter("todate", todate); ub.addParameter("sort", sort); ub.addParameter("min", mindate); ub.addParameter("max", maxdate); ub.addParameter("min", min); ub.addParameter("max", max); ub.addParameter("order", order); return client.createApiTask(Types.Answer, ub, "/_users/answers"); } public Future<StacManResponse<Answer>> getMyAnswers(String site, String access_token, String filter, Integer page, Integer pagesize, Date fromdate, Date todate, AnswerSort sort, Date mindate, Date maxdate, Integer min, Integer max, Order order) { client.validateString(site, "site"); client.validateString(access_token, "access_token"); client.validatePaging(page, pagesize); client.validateSortMinMax(sort, mindate, maxdate, min, max); ApiUrlBuilder ub = new ApiUrlBuilder("/me/answers", true); ub.addParameter("site", site); ub.addParameter("access_token", access_token); ub.addParameter("filter", filter); ub.addParameter("page", page); ub.addParameter("pagesize", pagesize); ub.addParameter("fromdate", fromdate); ub.addParameter("todate", todate); ub.addParameter("sort", sort); ub.addParameter("min", mindate); ub.addParameter("max", maxdate); ub.addParameter("min", min); ub.addParameter("max", max); ub.addParameter("order", order); return client.createApiTask(Types.Answer, ub, "/_users/answers"); } public Future<StacManResponse<Badge>> getBadges(String site, Integer[] ids, String filter, Integer page, Integer pagesize, Date fromdate, Date todate, BadgeUserSort sort, BadgeRank minrank, BadgeRank maxrank, String minname, String maxname, BadgeType mintype, BadgeType maxtype, Date mindate, Date maxdate, Order order) { return getBadges(site, StacManClient.toIter(ids), filter, page, pagesize, fromdate, todate, sort, minrank, maxrank, minname, maxname, mintype, maxtype, mindate, maxdate, order); } public Future<StacManResponse<Badge>> getBadges(String site, Iterable<Integer> ids, String filter, Integer page, Integer pagesize, Date fromdate, Date todate, BadgeUserSort sort, BadgeRank minrank, BadgeRank maxrank, String minname, String maxname, BadgeType mintype, BadgeType maxtype, Date mindate, Date maxdate, Order order) { if(sort == null) { sort = BadgeUserSort.Default; } client.validateString(site, "site"); client.validateEnumerable(ids, "ids"); client.validatePaging(page, pagesize); client.validateSortMinMax(sort, minrank, maxrank, minname, maxname, mintype, maxtype, mindate, maxdate); ApiUrlBuilder ub = new ApiUrlBuilder(String.format("/users/%1$S/badges", StacManClient.join(";", ids)), false); ub.addParameter("site", site); ub.addParameter("filter", filter); ub.addParameter("page", page); ub.addParameter("pagesize", pagesize); ub.addParameter("fromdate", fromdate); ub.addParameter("todate", todate); ub.addParameter("sort", sort); ub.addParameter("min", minrank); ub.addParameter("max", maxrank); ub.addParameter("min", minname); ub.addParameter("max", maxname); ub.addParameter("min", mintype); ub.addParameter("max", maxtype); ub.addParameter("min", mindate); ub.addParameter("max", maxdate); ub.addParameter("order", order); return client.createApiTask(Types.Badge, ub, "/_users/badges"); } Future<StacManResponse<Badge>> getMyBadges(String site, String access_token, String filter, Integer page, Integer pagesize, Date fromdate, Date todate, BadgeUserSort sort, BadgeRank minrank, BadgeRank maxrank, String minname, String maxname, BadgeType mintype, BadgeType maxtype, Date mindate, Date maxdate, Order order) { client.validateString(site, "site"); client.validateString(access_token, "access_token"); client.validatePaging(page, pagesize); client.validateSortMinMax(sort, minrank, maxrank, minname, maxname, mintype, maxtype, mindate, maxdate); ApiUrlBuilder ub = new ApiUrlBuilder("/me/badges", true); ub.addParameter("site", site); ub.addParameter("access_token", access_token); ub.addParameter("filter", filter); ub.addParameter("page", page); ub.addParameter("pagesize", pagesize); ub.addParameter("fromdate", fromdate); ub.addParameter("todate", todate); ub.addParameter("sort", sort); ub.addParameter("min", minrank); ub.addParameter("max", maxrank); ub.addParameter("min", minname); ub.addParameter("max", maxname); ub.addParameter("min", mintype); ub.addParameter("max", maxtype); ub.addParameter("min", mindate); ub.addParameter("max", maxdate); ub.addParameter("order", order); return client.createApiTask(Types.Badge, ub, "/_users/badges"); } public Future<StacManResponse<InboxItem>> getInbox(String site, String access_token, int id, String filter, Integer page, Integer pagesize) { client.validateString(site, "site"); client.validateString(access_token, "access_token"); client.validatePaging(page, pagesize); ApiUrlBuilder ub = new ApiUrlBuilder( String.format("/users/%1$S/inbox", id), true ); ub.addParameter("site", site); ub.addParameter("access_token", access_token); ub.addParameter("filter", filter); ub.addParameter("page", page); ub.addParameter("pagesize", pagesize); return client.createApiTask(Types.InboxItem, ub, "/_users/inbox"); } public Future<StacManResponse<InboxItem>> getMyInbox(String site, String access_token, String filter, Integer page, Integer pagesize) { client.validateString(site, "site"); client.validateString(access_token, "access_token"); client.validatePaging(page, pagesize); ApiUrlBuilder ub = new ApiUrlBuilder("/me/inbox", true); ub.addParameter("site", site); ub.addParameter("access_token", access_token); ub.addParameter("filter", filter); ub.addParameter("page", page); ub.addParameter("pagesize", pagesize); return client.createApiTask(Types.InboxItem, ub, "/_users/inbox"); } }
package com.valkryst.VTerminal; import com.valkryst.VTerminal.font.Font; import com.valkryst.VRadio.Radio; import lombok.Getter; import lombok.Setter; import javax.swing.*; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.image.*; public class AsciiCharacter { /** The transparent color. */ public final static Color TRANSPARENT_COLOR = new Color(0, 0, 0, 0); /** The character. */ @Getter @Setter private char character; /** Whether or not the foreground should be drawn using the background color. */ @Getter @Setter private boolean isHidden = false; /** The background color. Defaults to black. */ @Getter private Color backgroundColor = Color.BLACK; /** The foreground color. Defaults to white. */ @Getter private Color foregroundColor = Color.WHITE; /** The bounding box of the character's area. */ @Getter private final Rectangle boundingBox = new Rectangle(); /** Whether or not to draw the character as underlined. */ @Getter @Setter private boolean isUnderlined = false; /** The thickness of the underline to draw beneath the character. */ @Getter private int underlineThickness = 2; /** Whether or not the character should be flipped horizontally when drawn. */ @Getter @Setter private boolean isFlippedHorizontally = false; /** Whether or not the character should be flipped vertically when drawn. */ @Getter @Setter private boolean isFlippedVertically = false; private Timer blinkTimer; /** The amount of time, in milliseconds, before the blink effect can occur. */ @Getter private short millsBetweenBlinks = 1000; /** * Constructs a new AsciiCharacter. * * @param character * The character. */ public AsciiCharacter(final char character) { this.character = character; } @Override public String toString() { return "Character:\n" + "\tCharacter: '" + character + "'\n" + "\tBackground Color: " + backgroundColor + "\n" + "\tForeground Color: " + foregroundColor + "\n"; } @Override public boolean equals(final Object object) { if (object instanceof AsciiCharacter == false) { return false; } final AsciiCharacter otherCharacter = (AsciiCharacter) object; if (character != otherCharacter.character) { return false; } if (backgroundColor.equals(otherCharacter.backgroundColor) == false) { return false; } if (foregroundColor.equals(otherCharacter.foregroundColor) == false) { return false; } return true; } /** * Draws the character onto the specified context. * * @param gc * The graphics context to draw with. * * @param font * The font to draw with. * * @param columnIndex * The x-axis (column) coordinate where the character is to be drawn. * * @param rowIndex * The y-axis (row) coordinate where the character is to be drawn. */ public void draw(final Graphics2D gc, final Font font, int columnIndex, int rowIndex) { BufferedImage bufferedImage = font.getCharacterImage(character, backgroundColor != TRANSPARENT_COLOR); // Handle Horizontal/Vertical Flipping: if (isFlippedHorizontally || isFlippedVertically) { AffineTransform tx; if (isFlippedHorizontally && isFlippedVertically) { tx = AffineTransform.getScaleInstance(-1, -1); tx.translate(-bufferedImage.getWidth(), -bufferedImage.getHeight()); } else if (isFlippedHorizontally) { tx = AffineTransform.getScaleInstance(-1, 1); tx.translate(-bufferedImage.getWidth(), 0); } else { tx = AffineTransform.getScaleInstance(1, -1); tx.translate(0, -bufferedImage.getHeight()); } final BufferedImageOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BICUBIC); bufferedImage = op.filter(bufferedImage, null); } // Retrieve character image & set colors: Image image = bufferedImage; if (backgroundColor != TRANSPARENT_COLOR && (foregroundColor != Color.WHITE || backgroundColor != Color.BLACK)) { final BufferedImageOp op = createColorReplacementLookupOp(backgroundColor, foregroundColor); image = op.filter(bufferedImage, null); } // Draw character: final int fontWidth = font.getWidth(); final int fontHeight = font.getHeight(); columnIndex *= fontWidth; rowIndex *= fontHeight; gc.drawImage(image, columnIndex, rowIndex,null); boundingBox.setLocation(columnIndex, rowIndex); boundingBox.setSize(fontWidth, fontHeight); // Draw underline: if (isUnderlined) { gc.setColor(foregroundColor); final int y = rowIndex + fontHeight - underlineThickness; gc.fillRect(columnIndex, y, fontWidth, underlineThickness); } } private LookupOp createColorReplacementLookupOp(final Color newBgColor, final Color newFgColor) { short[] a = new short[256]; short[] r = new short[256]; short[] g = new short[256]; short[] b = new short[256]; short bga = (byte) (newBgColor.getAlpha()); short bgr = (byte) (newBgColor.getRed()); short bgg = (byte) (newBgColor.getGreen()); short bgb = (byte) (newBgColor.getBlue()); short fga = (byte) (newFgColor.getAlpha()); short fgr = (byte) (newFgColor.getRed()); short fgg = (byte) (newFgColor.getGreen()); short fgb = (byte) (newFgColor.getBlue()); for (int i = 0; i < 256; i++) { if (i == 0) { a[i] = bga; r[i] = bgr; g[i] = bgg; b[i] = bgb; } else { a[i] = fga; r[i] = fgr; g[i] = fgg; b[i] = fgb; } } short[][] table = {r, g, b, a}; return new LookupOp(new ShortLookupTable(0, table), null); } /** * Enables the blink effect. * * @param millsBetweenBlinks * The amount of time, in milliseconds, before the blink effect can occur. * * @param radio * The Radio to transmit a DRAW event to whenever a blink occurs. */ public void enableBlinkEffect(final short millsBetweenBlinks, final Radio<String> radio) { if (radio == null) { throw new NullPointerException("You must specify a Radio when enabling a blink effect."); } if (millsBetweenBlinks <= 0) { this.millsBetweenBlinks = 1000; } else { this.millsBetweenBlinks = millsBetweenBlinks; } blinkTimer = new Timer(this.millsBetweenBlinks, e -> { isHidden = !isHidden; radio.transmit("DRAW"); }); blinkTimer.setInitialDelay(this.millsBetweenBlinks); blinkTimer.setRepeats(true); blinkTimer.start(); } /** Resumes the blink effect. */ public void resumeBlinkEffect() { if (blinkTimer != null) { if (blinkTimer.isRunning() == false) { blinkTimer.start(); } } } /** Pauses the blink effect. */ public void pauseBlinkEffect() { if (blinkTimer != null) { if (blinkTimer.isRunning()) { isHidden = false; blinkTimer.stop(); } } } /** Disables the blink effect. */ public void disableBlinkEffect() { if (blinkTimer != null) { blinkTimer.stop(); blinkTimer = null; } } /** Swaps the background and foreground colors. */ public void invertColors() { final Color temp = backgroundColor; setBackgroundColor(foregroundColor); setForegroundColor(temp); } /** * Sets the new background color. * * Does nothing if the specified color is null. * * @param color * The new background color. */ public void setBackgroundColor(final Color color) { boolean canProceed = color != null; canProceed &= backgroundColor.equals(color) == false; if (canProceed) { this.backgroundColor = color; } } /** * Sets the new foreground color. * * Does nothing if the specified color is null. * * @param color * The new foreground color. */ public void setForegroundColor(final Color color) { boolean canProceed = color != null; canProceed &= foregroundColor.equals(color) == false; if (canProceed) { this.foregroundColor = color; } } /** * Sets the new underline thickness. * * If the specified thickness is negative, then the thickness is set to 1. * If the specified thickness is greater than the font height, then the thickness is set to the font height. * If the font height is greater than Byte.MAX_VALUE, then the thickness is set to Byte.MAX_VALUE. * * @param underlineThickness * The new underline thickness. */ public void setUnderlineThickness(final int underlineThickness) { if (underlineThickness > boundingBox.getHeight()) { this.underlineThickness = (int) boundingBox.getHeight(); } else if (underlineThickness <= 0) { this.underlineThickness = 1; } else { this.underlineThickness = underlineThickness; } } }
package kg.apc.perfmon.metrics; import java.util.LinkedList; import java.util.List; import java.util.StringTokenizer; import org.apache.jorphan.logging.LoggingManager; import org.apache.log.Logger; /** * * @author undera */ public class MetricParams { private static final Logger log = LoggingManager.getLoggerForClass(); String label = ""; long PID = -1; int coreID = -1; String fs = ""; String iface = ""; String[] params = new String[0]; String type = ""; String unit = ""; protected static void parseParams(String metricParams, MetricParams inst) throws NumberFormatException { //for split, avoid ':' preceeded with '\', ie do not process "\:" String[] tokens = metricParams.split("(?<!\\\\)" + AbstractPerfMonMetric.PARAMS_DELIMITER); List params = new LinkedList(); for(int i=0; i<tokens.length; i++) { inst.populateParams(tokens[i].replaceAll("\\\\:", ":"), params); } inst.params = (String[]) params.toArray(new String[0]); } protected MetricParams() { } protected void populateParams(String token, List params) throws NumberFormatException { if (token.startsWith("pid=")) { this.PID = getPIDByPID(token); } else if (token.startsWith("iface=")) { this.iface = getParamValue(token); } else if (token.startsWith("label=")) { this.label = getParamValue(token); } else if (token.startsWith("fs=")) { this.fs = getParamValue(token); } else if (token.startsWith("core=")) { this.coreID = Integer.parseInt(getParamValue(token)); } else if (token.startsWith("unit=")) { this.unit = getParamValue(token); } else { params.add(token); this.type = token; } } protected static StringTokenizer tokenizeString(String metricParams) { return new StringTokenizer(metricParams, AbstractPerfMonMetric.PARAMS_DELIMITER); } public static MetricParams createFromString(String metricParams) { MetricParams inst = new MetricParams(); parseParams(metricParams, inst); return inst; } public static String join(StringBuffer buff, final Object[] array, final String delim) { if (buff == null) { buff = new StringBuffer(); } boolean haveDelim = delim != null; for (int i = 0; i < array.length; i++) { buff.append(array[i]); // if this is the last element then don't append delim if (haveDelim && (i + 1) < array.length) { buff.append(delim); } } return buff.toString(); } public String getLabel() { return label; } public String getUnit() { return unit; } public static String getParamValue(String token) { return token.substring(token.indexOf("=") + 1); } private static long getPIDByPID(String token) { long PID; try { String PIDStr = token.substring(token.indexOf("=") + 1); PID = Long.parseLong(PIDStr); } catch (ArrayIndexOutOfBoundsException e) { log.warn("Error processing token: " + token, e); PID = -1; } catch (NumberFormatException e) { log.warn("Error processing token: " + token, e); PID = -1; } return PID; } }
package com.sometrik.framework; import java.util.ArrayList; import java.util.List; import com.sometrik.vapu.R; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; public class FWAdapter extends ArrayAdapter<View> { private List<View> viewList; private ArrayList<AdapterData> dataList; private FrameWork frame; public FWAdapter(Context context, List<View> viewList) { super(context, 0, viewList); this.frame = (FrameWork)context; // this.viewList = viewList; this.dataList = new ArrayList<AdapterData>(); } public ArrayList<String> getDataRow(int rowId) { if (dataList.size() >= rowId + 1) { return dataList.get(rowId).dataList; } Log.d("adapter", "no row found"); return null; } public void addItem(View view){ // viewList.add(view); } public void addItem(ArrayList<String> cellItems){ dataList.add(new AdapterData(cellItems)); } @Override public int getCount() { return dataList.size(); } @Override public long getItemId(int arg0) { return 0; } @Override public void clear(){ dataList = new ArrayList<AdapterData>(); } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = frame.getLayoutInflater(); convertView=inflater.inflate(R.layout.multicolumn_data, null); TextView txtFirst=(TextView) convertView.findViewById(R.id.name); TextView txtSecond=(TextView) convertView.findViewById(R.id.gender); TextView txtThird=(TextView) convertView.findViewById(R.id.age); TextView txtFourth=(TextView) convertView.findViewById(R.id.status); AdapterData data = dataList.get(position); txtFirst.setText(data.getData(0)); txtSecond.setText(data.getData(1)); txtThird.setText(data.getData(2)); txtFourth.setText(data.getData(3)); // DisplayMetrics displaymetrics = new DisplayMetrics(); //// int dp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 130, displaymetrics); // AbsListView.LayoutParams params = new AbsListView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 130); // View view = viewList.get(position); // view.setLayoutParams(params); return convertView; } public class AdapterData { private ArrayList<String> dataList; public AdapterData(ArrayList<String> dataList) { this.dataList = dataList; } public String getData(int position) { if (position < dataList.size()) { return dataList.get(position); } else { return dataList.get(0); } } } }
package thredds.servlet; import java.io.*; import java.util.*; import java.net.URI; import java.net.URISyntaxException; import javax.servlet.*; import javax.servlet.http.*; import javax.xml.parsers.FactoryConfigurationError; import org.apache.log4j.*; import org.apache.log4j.xml.DOMConfigurator; import ucar.unidata.util.StringUtil; import ucar.unidata.io.FileCache; import thredds.catalog.XMLEntityResolver; public class ServletUtil { static private org.slf4j.Logger log; static private boolean isDebugInit = false; static private boolean isLogInit = false; public static final String CONTENT_TEXT = "text/plain; charset=iso-8859-1"; public static void initDebugging(HttpServlet servlet) { if (isDebugInit) return; isDebugInit = true; ServletContext webapp = servlet.getServletContext(); String debugOn = webapp.getInitParameter("DebugOn"); if (debugOn != null) { StringTokenizer toker = new StringTokenizer(debugOn); while (toker.hasMoreTokens()) Debug.set(toker.nextToken(), true); } } /** * Initialize logging for the web application context in which the given * servlet is running. Two types of logging are supported: * * 1) Regular logging using the SLF4J API. * 2) Access logging which can write Apache common logging format logs, * use the ServletUtil.logServerSetup(String) method. * * The log directory is determined by the servlet containers content * directory. The configuration of logging is controlled by the log4j.xml * file. The log4j.xml file needs to setup at least two loggers: "thredds"; * and "threddsAccessLogger" * * @param servlet - the servlet. */ public static void initLogging(HttpServlet servlet) { // Initialize logging if not already done. if (isLogInit) return; System.out.println("+++ServletUtil.initLogging"); ServletContext servletContext = servlet.getServletContext(); // set up the log path String logPath = getContentPath(servlet) + "logs"; File logPathFile = new File(logPath); if (!logPathFile.exists()) { if (!logPathFile.mkdirs()) { throw new RuntimeException("Creation of logfile directory failed."+logPath); } } // read in Log4J config file System.setProperty("logdir", logPath); // variable substitution try { String log4Jconfig = servletContext.getInitParameter("log4j-init-file"); if (log4Jconfig == null) log4Jconfig = getRootPath(servlet) + "WEB-INF/log4j.xml"; DOMConfigurator.configure(log4Jconfig); System.out.println("+++Log4j configured from file "+log4Jconfig); } catch (FactoryConfigurationError t) { t.printStackTrace(); } /* read in user defined Log4J file String log4Jconfig = ServletUtil.getContentPath(servlet) + "log4j.xml"; File test = new File(log4Jconfig); if (test.exists()) try { DOMConfigurator.configure(log4Jconfig); System.out.println("+++Log4j configured from file "+log4Jconfig); } catch (FactoryConfigurationError t) { t.printStackTrace(); } */ log = org.slf4j.LoggerFactory.getLogger(ServletUtil.class); isLogInit = true; } /** * Gather information from the given HttpServletRequest for inclusion in both * regular logging messages and THREDDS access log messages. Call this method * at start of each doXXX() method (e.g., doGet(), doPut()) in any servlet * you implement. * * Use the SLF4J API to log a regular logging messages. Use the * logServerAccess() method to log a THREDDS access log message. * * This method gathers the following information: * 1) "ID" - an identifier for the current thread; * 2) "host" - the remote host (IP address or host name); * 3) "userid" - the id of the remote user; * 4) "startTime" - the system time in millis when this request is started (i.e., when this method is called); and * 5) "request" - The HTTP request, e.g., "GET /index.html HTTP/1.1". * * The appearance of the regular log messages and the THREDDS access log * messages are controlled in the log4j.xml configuration file. For the log * messages to look like an Apache server "common" log message, use the * following log4j pattern: * * "%X{host} %X{ident} %X{userid} [%d{dd/MMM/yyyy:HH:mm:ss}] %X{request} %m%n" * * @param req the current HttpServletRequest. */ public static void logServerAccessSetup( HttpServletRequest req) { HttpSession session = req.getSession( false); // Setup context. synchronized( ServletUtil.class) { MDC.put( "ID", Long.toString( ++logServerAccessId)); } MDC.put( "host", req.getRemoteHost()); MDC.put( "ident", (session == null) ? "-" : session.getId()); MDC.put( "userid", req.getRemoteUser() != null ? req.getRemoteUser() : "-"); MDC.put( "startTime", new Long( System.currentTimeMillis()) ); String query = req.getQueryString(); query = (query != null ) ? "?" + query : ""; StringBuffer request = new StringBuffer(); request.append( "\"").append( req.getMethod()).append( " ") .append( req.getRequestURI() ).append( query) .append( " " ).append( req.getProtocol()).append( "\"" ); MDC.put( "request", request.toString() ); log.info( "Remote host: " + req.getRemoteHost() + " - Request: " + request); } /** * Gather current thread information for inclusion in regular logging * messages. Call this method only for non-request servlet activities, e.g., * during the init() or destroy(). * * Use the SLF4J API to log a regular logging messages. * * This method gathers the following information: * 1) "ID" - an identifier for the current thread; and * 2) "startTime" - the system time in millis when this method is called. * * The appearance of the regular log messages are controlled in the * log4j.xml configuration file. * * @param msg - the information log message logged when this method finishes. */ public static void logServerSetup( String msg ) { // Setup context. synchronized ( ServletUtil.class ) { MDC.put( "ID", Long.toString( ++logServerAccessId ) ); } MDC.put( "startTime", new Long( System.currentTimeMillis() ) ); log.info( msg ); } private static volatile long logServerAccessId = 0; /** * Write log entry to THREDDS access log. * * @param resCode - the result code for this request. * @param resSizeInBytes - the number of bytes returned in this result, -1 if unknown. */ public static void logServerAccess( int resCode, long resSizeInBytes ) { long endTime = System.currentTimeMillis(); long startTime = ( (Long) MDC.get( "startTime" )).longValue(); long duration = endTime - startTime; log.info( "Request Completed - " + resCode + " - " + resSizeInBytes + " - " + duration); } public static String getRootPath(HttpServlet servlet) { ServletContext sc = servlet.getServletContext(); String rootPath = sc.getRealPath("/"); rootPath = rootPath.replace('\\','/'); return rootPath; } public static String getPath(HttpServlet servlet, String path) { ServletContext sc = servlet.getServletContext(); String spath = sc.getRealPath(path); spath = spath.replace('\\','/'); return spath; } /* public static String getRootPathUrl(HttpServlet servlet) { String rootPath = getRootPath( servlet); rootPath = StringUtil.replace(rootPath, ' ', "%20"); return rootPath; } */ private static String contextPath = null; public static String getContextPath( HttpServlet servlet ) { if ( contextPath == null ) { ServletContext servletContext = servlet.getServletContext(); String tmpContextPath = servletContext.getInitParameter( "ContextPath" ); // cannot be overridden in the ThreddsConfig file if ( tmpContextPath == null ) tmpContextPath = "thredds"; contextPath = "/"+tmpContextPath; } return contextPath; } private static String contentPath = null; public static String getContentPath(HttpServlet servlet) { if (contentPath == null) { String tmpContentPath = "../../content" + getContextPath( servlet ) + "/"; File cf = new File( getRootPath(servlet) + tmpContentPath ); try{ contentPath = cf.getCanonicalPath() +"/"; contentPath = contentPath.replace('\\','/'); } catch (IOException e) { e.printStackTrace(); } } return contentPath; } public static String getInitialContentPath(HttpServlet servlet) { return getRootPath(servlet) + "WEB-INF/initialContent/"; } public static String formFilename(String dirPath, String filePath) { if ((dirPath == null) || (filePath == null)) return null; if (filePath.startsWith("/")) filePath = filePath.substring(1); return dirPath.endsWith("/") ? dirPath + filePath : dirPath + "/" + filePath; } /** * Handle a request for a raw/static file (i.e., not a catalog or dataset request). * * Look in the content (user) directory then the root (distribution) directory * for a file that matches the given path and, if found, return it as the * content of the HttpServletResponse. If the file is forbidden (i.e., the * path contains a "..", "WEB-INF", or "META-INF" directory), send a * HttpServletResponse.SC_FORBIDDEN response. If no file matches the request * (including an "index.html" file if the path ends in "/"), send an * HttpServletResponse.SC_NOT_FOUND.. * * <ol> * <li>Make sure the path does not contain ".." directories. </li> * <li>Make sure the path does not contain "WEB-INF" or "META-INF". </li> * <li>Check for requested file in the content directory * (if the path is a directory, make sure the path ends with "/" and * check for an "index.html" file). </li> * <li>Check for requested file in the root directory * (if the path is a directory, make sure the path ends with "/" and * check for an "index.html" file).</li> * </ol * * @param path the requested path * @param servlet the servlet handling the request * @param req the HttpServletRequest * @param res the HttpServletResponse * @throws IOException if can't complete request due to IO problems. */ public static void handleRequestForRawFile( String path, HttpServlet servlet, HttpServletRequest req, HttpServletResponse res ) throws IOException { // Don't allow ".." directories in path. if ( path.indexOf( "/../" ) != -1 || path.equals( ".." ) || path.startsWith( "../" ) || path.endsWith( "/.." ) ) { res.sendError( HttpServletResponse.SC_FORBIDDEN, "Path cannot contain \"..\" directory." ); ServletUtil.logServerAccess( HttpServletResponse.SC_FORBIDDEN, -1 ); return; } // Don't allow access to WEB-INF or META-INF directories. String upper = path.toUpperCase(); if ( upper.indexOf( "WEB-INF" ) != -1 || upper.indexOf( "META-INF" ) != -1 ) { res.sendError( HttpServletResponse.SC_FORBIDDEN, "Path cannot contain \"WEB-INF\" or \"META-INF\"." ); ServletUtil.logServerAccess( HttpServletResponse.SC_FORBIDDEN, -1 ); return; } // Find a regular file File regFile = null; // Look in content directory for regular file. File cFile = new File( ServletUtil.formFilename( getContentPath( servlet), path ) ); if ( cFile.exists() ) { if ( cFile.isDirectory() ) { if ( ! path.endsWith( "/")) { String newPath = req.getRequestURL().append( "/").toString(); ServletUtil.sendPermanentRedirect( newPath, req, res ); } // If request path is a directory, check for index.html file. cFile = new File( cFile, "index.html" ); if ( cFile.exists() && ! cFile.isDirectory() ) regFile = cFile; } // If not a directory, use this file. else regFile = cFile; } if ( regFile == null ) { // Look in root directory. File rFile = new File( ServletUtil.formFilename( getRootPath( servlet), path ) ); if ( rFile.exists() ) { if ( rFile.isDirectory() ) { if ( ! path.endsWith( "/" ) ) { String newPath = req.getRequestURL().append( "/").toString(); ServletUtil.sendPermanentRedirect( newPath, req, res ); } rFile = new File( rFile, "index.html" ); if ( rFile.exists() && ! rFile.isDirectory() ) regFile = rFile; } else regFile = rFile; } } if ( regFile == null ) { res.sendError( HttpServletResponse.SC_NOT_FOUND ); // 404 ServletUtil.logServerAccess( HttpServletResponse.SC_NOT_FOUND, -1 ); return; } ServletUtil.returnFile( servlet, req, res, regFile, null ); } /** * Handle an explicit request for a content directory file (path must start * with "/content/". * * Note: As these requests will show the configuration files for the server, * these requests should be covered by security constraints. * * <ol> * <li>Make sure the path does not contain ".." directories. </li> * <li>Check for the requested file in the content directory. </li> * </ol * * @param path the requested path (must start with "/content/") * @param servlet the servlet handling the request * @param req the HttpServletRequest * @param res the HttpServletResponse * @throws IOException if can't complete request due to IO problems. */ public static void handleRequestForContentFile( String path, HttpServlet servlet, HttpServletRequest req, HttpServletResponse res ) throws IOException { handleRequestForContentOrRootFile( "/content/", path, servlet, req, res); } /** * Handle an explicit request for a root directory file (path must start * with "/root/". * * Note: As these requests will show the configuration files for the server, * these requests should be covered by security constraints. * * <ol> * <li>Make sure the path does not contain ".." directories. </li> * <li>Check for the requested file in the root directory. </li> * </ol * * @param path the requested path (must start with "/root/") * @param servlet the servlet handling the request * @param req the HttpServletRequest * @param res the HttpServletResponse * @throws IOException if can't complete request due to IO problems. */ public static void handleRequestForRootFile( String path, HttpServlet servlet, HttpServletRequest req, HttpServletResponse res ) throws IOException { handleRequestForContentOrRootFile( "/root/", path, servlet, req, res); } /** * Convenience routine used by handleRequestForContentFile() * and handleRequestForRootFile(). */ private static void handleRequestForContentOrRootFile( String pathPrefix, String path, HttpServlet servlet, HttpServletRequest req, HttpServletResponse res ) throws IOException { if ( ! pathPrefix.equals( "/content/") && ! pathPrefix.equals( "/root/")) { log.error( "handleRequestForContentFile(): The path prefix <" + pathPrefix + "> must be \"/content/\" or \"/root/\"." ); throw new IllegalArgumentException( "Path prefix must be \"/content/\" or \"/root/\"." ); } if ( ! path.startsWith( pathPrefix )) { log.error( "handleRequestForContentFile(): path <" + path + "> must start with \"" + pathPrefix + "\"."); throw new IllegalArgumentException( "Path must start with \"" + pathPrefix + "\"."); } // Don't allow ".." directories in path. if ( path.indexOf( "/../" ) != -1 || path.equals( ".." ) || path.startsWith( "../" ) || path.endsWith( "/.." ) ) { res.sendError( HttpServletResponse.SC_FORBIDDEN, "Path cannot contain \"..\" directory." ); ServletUtil.logServerAccess( HttpServletResponse.SC_FORBIDDEN, -1 ); return; } // Find the requested file. File file = new File( ServletUtil.formFilename( getContentPath( servlet), path.substring( pathPrefix.length() - 1 ) ) ); if ( file.exists() ) { // Do not allow request for a directory. if ( file.isDirectory() ) { if ( ! path.endsWith( "/" ) ) { String redirectPath = req.getRequestURL().append( "/").toString(); ServletUtil.sendPermanentRedirect( redirectPath, req, res ); return; } HtmlWriter.getInstance().writeDirectory( res, file, path ); return; } // Return the requested file. ServletUtil.returnFile( servlet, req, res, file, null ); } else { // Requested file not found. ServletUtil.logServerAccess( HttpServletResponse.SC_NOT_FOUND, -1 ); res.sendError( HttpServletResponse.SC_NOT_FOUND ); // 404 } } /** * Send a permanent redirect (HTTP status 301 "Moved Permanently") response * with the given target path. * * The given target path may be relative or absolute. If it is relative, it * will be resolved against the request URL. * * @param targetPath the path to which the client is redirected. * @param req the HttpServletRequest * @param res the HttpServletResponse * @throws IOException if can't write the response. */ public static void sendPermanentRedirect(String targetPath, HttpServletRequest req, HttpServletResponse res) throws IOException { // Absolute URL needed so resolve the target path against the request URL. URI uri = null; try { uri = new URI( req.getRequestURL().toString() ); } catch ( URISyntaxException e ) { log.error( "sendPermanentRedirect(): Bad syntax on request URL <" + req.getRequestURL() + ">.", e); ServletUtil.logServerAccess( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 0 ); res.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); return; } String absolutePath = uri.resolve( targetPath ).toString(); absolutePath = res.encodeRedirectURL( absolutePath ); res.setStatus( HttpServletResponse.SC_MOVED_PERMANENTLY ); res.addHeader( "Location", absolutePath ); String title = "Permanently Moved - 301"; String body = new StringBuffer() .append( "<p>" ) .append( "The requested URL <" ).append( req.getRequestURL() ) .append( "> has been permanently moved (HTTP status code 301)." ) .append( " Instead, please use the following URL: <a href=\"" ).append( absolutePath ).append( "\">" ).append( absolutePath ).append( "</a>." ) .append( "</p>" ) .toString(); String htmlResp = new StringBuffer() .append( HtmlWriter.getInstance().getHtmlDoctypeAndOpenTag()) .append( "<head><title>" ) .append( title ) .append( "</title></head><body>" ) .append( "<h1>" ).append( title ).append( "</h1>" ) .append( body ) .append( "</body></html>" ) .toString(); ServletUtil.logServerAccess( HttpServletResponse.SC_MOVED_PERMANENTLY, htmlResp.length() ); // Write the catalog out. PrintWriter out = res.getWriter(); res.setContentType( "text/html" ); out.print( htmlResp ); out.flush(); } /** * Write a file to the response stream. * * @param servlet called from here * @param contentPath file root path * @param path file path reletive to the root * @param res the response * @param contentType content type, or null * * @throws IOException */ public static void returnFile( HttpServlet servlet, String contentPath, String path, HttpServletRequest req, HttpServletResponse res, String contentType ) throws IOException { String filename = ServletUtil.formFilename( contentPath, path); log.debug( "returnFile(): returning file <" + filename + ">."); // No file, nothing to view if (filename == null) { ServletUtil.logServerAccess( HttpServletResponse.SC_NOT_FOUND, 0 ); res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // dontallow .. if (filename.indexOf("..") != -1) { ServletUtil.logServerAccess( HttpServletResponse.SC_FORBIDDEN, 0 ); res.sendError(HttpServletResponse.SC_FORBIDDEN); return; } // dont allow access to WEB-INF or META-INF String upper = filename.toUpperCase(); if (upper.indexOf("WEB-INF") != -1 || upper.indexOf("META-INF") != -1) { ServletUtil.logServerAccess( HttpServletResponse.SC_FORBIDDEN, 0 ); res.sendError(HttpServletResponse.SC_FORBIDDEN); return; } returnFile( servlet, req, res, new File(filename), contentType); } /** * Write a file to the response stream. * * @param servlet called from here * @param req the request * @param res the response * @param file to serve * @param contentType content type, or null * * @throws IOException */ public static void returnFile( HttpServlet servlet, HttpServletRequest req, HttpServletResponse res, File file, String contentType) throws IOException { // No file, nothing to view if (file == null) { ServletUtil.logServerAccess( HttpServletResponse.SC_NOT_FOUND, 0 ); res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // check that it exists if (!file.exists()) { ServletUtil.logServerAccess( HttpServletResponse.SC_NOT_FOUND, 0 ); res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Set the type of the file String filename = file.getPath(); if (null == contentType) { if (filename.endsWith(".html")) contentType = "text/html; charset=iso-8859-1"; else if (filename.endsWith(".xml")) contentType = "text/xml; charset=iso-8859-1"; else if (filename.endsWith(".txt") || (filename.endsWith(".log"))) contentType = CONTENT_TEXT; else if (filename.indexOf(".log.") > 0) contentType = CONTENT_TEXT; else if (filename.endsWith(".nc")) contentType = "application/x-netcdf"; else contentType = servlet.getServletContext().getMimeType( filename); if (contentType == null) contentType = "application/octet-stream"; } res.setContentType(contentType); // see if its a Range Request boolean isRangeRequest = false; long startPos = 0, endPos = Long.MAX_VALUE; String rangeRequest = req.getHeader("Range"); if (rangeRequest != null) { // bytes=12-34 or bytes=12- int pos = rangeRequest.indexOf("="); if (pos > 0) { int pos2 = rangeRequest.indexOf("-"); if (pos2 > 0) { String startString = rangeRequest.substring(pos+1, pos2); String endString = rangeRequest.substring(pos2+1); startPos = Long.parseLong(startString); if (endString.length() > 0) endPos = Long.parseLong(endString) + 1; isRangeRequest = true; } } } // set content length long fileSize = file.length(); int contentLength = (int) fileSize; if (isRangeRequest) { endPos = Math.min( endPos, fileSize); contentLength = (int) (endPos - startPos); } res.setContentLength( contentLength); boolean debugRequest = Debug.isSet("returnFile"); if (debugRequest) log.debug("returnFile(): filename = "+filename+" contentType = "+contentType + " contentLength = "+file.length()); // indicate we allow Range Requests res.addHeader("Accept-Ranges","bytes"); if (req.getMethod().equals("HEAD")) { ServletUtil.logServerAccess( HttpServletResponse.SC_OK, 0); return; } try { if (isRangeRequest) { // set before content is sent res.addHeader("Content-Range","bytes "+startPos+"-"+(endPos-1)+"/"+fileSize); res.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); ucar.unidata.io.RandomAccessFile raf = null; try { raf = FileCache.acquire(filename); thredds.util.IO.copyRafB(raf, startPos, contentLength, res.getOutputStream(), new byte[60000]); ServletUtil.logServerAccess(HttpServletResponse.SC_PARTIAL_CONTENT, contentLength); return; } finally { if (raf != null) FileCache.release(raf); } } // Return the file ServletOutputStream out = res.getOutputStream(); thredds.util.IO.copyFileB(file, out, 60000); res.flushBuffer(); out.close(); if ( debugRequest ) log.debug("returnFile(): returnFile ok = "+filename); ServletUtil.logServerAccess( HttpServletResponse.SC_OK, contentLength ); } // @todo Split up this exception handling: those from file access vs those from dealing with response // File access: catch and res.sendError() // response: don't catch (let bubble up out of doGet() etc) catch (FileNotFoundException e) { log.error("returnFile(): FileNotFoundException= "+filename); ServletUtil.logServerAccess( HttpServletResponse.SC_NOT_FOUND, 0 ); res.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (java.net.SocketException e) { log.info("returnFile(): SocketException sending file: " + filename+" "+e.getMessage()); ServletUtil.logServerAccess( 1000, 0 ); // dunno what error code to log } catch (IOException e) { String eName = e.getClass().getName(); // dont want compile time dependency on ClientAbortException if (eName.equals("org.apache.catalina.connector.ClientAbortException")) { log.info("returnFile(): ClientAbortException while sending file: " + filename+" "+e.getMessage()); ServletUtil.logServerAccess( 1000, 0 ); // dunno what error code to log return; } log.error("returnFile(): IOException ("+ e.getClass().getName() +") sending file ", e); ServletUtil.logServerAccess( HttpServletResponse.SC_NOT_FOUND, 0 ); res.sendError(HttpServletResponse.SC_NOT_FOUND, "Problem sending file: " + e.getMessage()); } } public static void returnString( String contents, HttpServletResponse res ) throws IOException { try { ServletOutputStream out = res.getOutputStream(); thredds.util.IO.copy( new ByteArrayInputStream(contents.getBytes()), out); ServletUtil.logServerAccess( HttpServletResponse.SC_OK, contents.length() ); } catch (IOException e) { log.error(" IOException sending string: ", e); ServletUtil.logServerAccess( HttpServletResponse.SC_NOT_FOUND, 0 ); res.sendError(HttpServletResponse.SC_NOT_FOUND, "Problem sending string: " + e.getMessage()); } } public static String getReletiveURL( HttpServletRequest req) { return req.getContextPath()+req.getServletPath()+req.getPathInfo(); } public static void forwardToCatalogServices(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { String reqs = "catalog="+getReletiveURL( req); String query = req.getQueryString(); if (query != null) reqs = reqs+"&"+query; log.info( "forwardToCatalogServices(): request string = \"/catalog.html?" + reqs + "\""); // dispatch to CatalogHtml servlet // "The pathname specified may be relative, although it cannot extend outside the current servlet context. // "If the path begins with a "/" it is interpreted as relative to the current context root." RequestDispatcher dispatch = req.getRequestDispatcher("/catalog.html?"+reqs); if (dispatch != null) dispatch.forward(req, res); else res.sendError(HttpServletResponse.SC_NOT_FOUND); ServletUtil.logServerAccess( HttpServletResponse.SC_NOT_FOUND, 0 ); } public static boolean saveFile(HttpServlet servlet, String contentPath, String path, HttpServletRequest req, HttpServletResponse res) { // @todo Need to use logServerAccess() below here. boolean debugRequest = Debug.isSet("SaveFile"); if (debugRequest) log.debug( " saveFile(): path= " + path ); String filename = contentPath + path; // absolute path File want = new File(filename); // backup current version if it exists int version = getBackupVersion(want.getParent(), want.getName()); String fileSave = filename + "~"+version; File file = new File( filename); if (file.exists()) { try { thredds.util.IO.copyFile(filename, fileSave); } catch (IOException e) { log.error("saveFile(): Unable to save copy of file "+filename+" to "+fileSave+"\n"+e.getMessage()); return false; } } // save new file try { OutputStream out = new BufferedOutputStream( new FileOutputStream( filename)); thredds.util.IO.copy(req.getInputStream(), out); out.close(); if ( debugRequest ) log.debug("saveFile(): ok= "+filename); res.setStatus( HttpServletResponse.SC_CREATED); ServletUtil.logServerAccess( HttpServletResponse.SC_CREATED, -1); return true; } catch (IOException e) { log.error("saveFile(): Unable to PUT file "+filename+" to "+fileSave+"\n"+e.getMessage()); return false; } } private static int getBackupVersion(String dirName, String fileName) { int maxN = 0; File dir = new File(dirName); if (!dir.exists()) return -1; String[] files = dir.list(); if (null == files) return -1; for (int i=0; i< files.length; i++) { String name = files[i]; if (name.indexOf(fileName) < 0) continue; int pos = name.indexOf('~'); if (pos < 0) continue; String ver = name.substring(pos+1); int n=0; try { n = Integer.parseInt(ver); } catch (NumberFormatException e) { log.error("Format Integer error on backup filename= "+ver); } maxN = Math.max( n, maxN); } return maxN+1; } static public boolean copyDir(String fromDir, String toDir) throws IOException { File contentFile = new File(toDir+".INIT"); if (!contentFile.exists()) { thredds.util.IO.copyDirTree(fromDir, toDir); contentFile.createNewFile(); return true; } return false; } /*************************************************************************** * Sends an error to the client. * * @param t The exception that caused the problem. * @param res The <code>HttpServletResponse</code> for the client. */ static public void handleException(Throwable t, HttpServletResponse res) { try { String message = t.getMessage(); if (message == null) message = "NULL message "+t.getClass().getName(); if (Debug.isSet("trustedMode")) { // security issue: only show stack if trusted ByteArrayOutputStream bs = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(bs); t.printStackTrace(ps); message = new String( bs.toByteArray()); } ServletUtil.logServerAccess( HttpServletResponse.SC_BAD_REQUEST, message.length()); log.error("handleException", t); t.printStackTrace(); // debugging - log.error not showing stack trace !! res.sendError(HttpServletResponse.SC_BAD_REQUEST, message); } catch (IOException e) { log.error("handleException(): IOException", e); t.printStackTrace(); } } static public void showServerInfo(HttpServlet servlet, PrintStream out) { out.println("Server Info"); out.println(" getDocumentBuilderFactoryVersion(): " + XMLEntityResolver.getDocumentBuilderFactoryVersion()); out.println(); Properties sysp = System.getProperties(); Enumeration e = sysp.propertyNames(); ArrayList list = Collections.list( e); Collections.sort(list); out.println("System Properties:"); for (int i = 0; i < list.size(); i++) { String name = (String) list.get(i); String value = System.getProperty(name); out.println(" "+name+" = "+value); } out.println(); } static public void showServletInfo(HttpServlet servlet, PrintStream out) { out.println("Servlet Info"); out.println(" getServletName(): " + servlet.getServletName()); out.println(" getRootPath(): " + getRootPath(servlet)); out.println(" Init Parameters:"); Enumeration params = servlet.getInitParameterNames(); while (params.hasMoreElements()) { String name = (String) params.nextElement(); out.println(" "+name + ": " + servlet.getInitParameter(name)); } out.println(); ServletContext context = servlet.getServletContext(); out.println("Context Info"); try { out.println(" context.getResource('/'): " + context.getResource("/")); } catch (java.net.MalformedURLException e) { } // cant happen out.println(" context.getServerInfo(): " + context.getServerInfo()); out.println(" name: " + getServerInfoName(context.getServerInfo())); out.println(" version: " + getServerInfoVersion(context.getServerInfo())); out.println(" context.getInitParameterNames():"); params = context.getInitParameterNames(); while (params.hasMoreElements()) { String name = (String) params.nextElement(); out.println(" "+name + ": " + context.getInitParameter(name)); } out.println(" context.getAttributeNames():"); params = context.getAttributeNames(); while (params.hasMoreElements()) { String name = (String) params.nextElement(); out.println(" context.getAttribute(\"" + name + "\"): " + context.getAttribute(name)); } out.println(); } /** Show the pieces of the request, for debugging */ public static String getRequestParsed(HttpServletRequest req) { return req.getRequestURI()+" = "+req.getContextPath()+"(context), "+ req.getServletPath()+"(servletPath), "+ req.getPathInfo()+"(pathInfo), "+req.getQueryString()+"(query)"; } /** This is everything except the query string */ public static String getRequestBase(HttpServletRequest req) { return req.getRequestURL().toString(); } /** The request base as a URI */ public static URI getRequestURI(HttpServletRequest req) { try { return new URI( getRequestBase( req)); } catch (URISyntaxException e) { e.printStackTrace(); return null; } } /** servletPath + pathInfo */ public static String getRequestPath(HttpServletRequest req) { StringBuffer buff = new StringBuffer(); if (req.getServletPath() != null ) buff.append( req.getServletPath()); if (req.getPathInfo() != null ) buff.append( req.getPathInfo()); return buff.toString(); } /** The entire request including query string */ public static String getRequest(HttpServletRequest req) { String query = req.getQueryString(); return getRequestBase(req)+(query == null ? "" : "?"+req.getQueryString()); } public static String getParameterIgnoreCase(HttpServletRequest req, String paramName) { Enumeration e = req.getParameterNames(); while (e.hasMoreElements()) { String s = (String) e.nextElement(); if (s.equalsIgnoreCase(paramName)) return req.getParameter( s); } return null; } public static String[] getParameterValuesIgnoreCase(HttpServletRequest req, String paramName) { Enumeration e = req.getParameterNames(); while (e.hasMoreElements()) { String s = (String) e.nextElement(); if (s.equalsIgnoreCase(paramName)) return req.getParameterValues( s); } return null; } public static String getFileURL(String filename) { filename = filename.replace('\\','/'); filename = StringUtil.replace(filename, ' ', "+"); return "file:"+filename; } public static String getFileURL2(String filename) { File f = new File(filename); try { return f.toURL().toString(); } catch (java.net.MalformedURLException e) { e.printStackTrace(); } return null; } /** * Show deatails about the request * @param servlet used to get teh servlet context, may be null * @param req the request * @return string showing the details of the request. */ static public String showRequestDetail(HttpServlet servlet, HttpServletRequest req) { StringBuffer sbuff = new StringBuffer(); sbuff.append("Request Info\n"); sbuff.append(" req.getServerName(): " + req.getServerName()+"\n"); sbuff.append(" req.getServerPort(): " + req.getServerPort()+"\n"); sbuff.append(" req.getContextPath:"+ req.getContextPath()+"\n"); sbuff.append(" req.getServletPath:"+ req.getServletPath()+"\n"); sbuff.append(" req.getPathInfo:"+ req.getPathInfo()+"\n"); sbuff.append(" req.getQueryString:"+ req.getQueryString()+"\n"); sbuff.append(" req.getRequestURI:"+ req.getRequestURI()+"\n"); sbuff.append(" getRequestBase:"+ getRequestBase(req)+"\n"); sbuff.append(" getRequest:"+ getRequest(req)+"\n"); sbuff.append("\n"); sbuff.append(" req.getPathTranslated:"+ req.getPathTranslated()+"\n"); String path = req.getPathTranslated(); if (( path != null) && (servlet != null)) { ServletContext context = servlet.getServletContext(); sbuff.append(" getMimeType:"+ context.getMimeType(path)+"\n"); } sbuff.append("\n"); sbuff.append(" req.getScheme:"+ req.getScheme()+"\n"); sbuff.append(" req.getProtocol:"+ req.getProtocol()+"\n"); sbuff.append(" req.getMethod:"+ req.getMethod()+"\n"); sbuff.append("\n"); sbuff.append(" req.getContentType:"+ req.getContentType()+"\n"); sbuff.append(" req.getContentLength:"+ req.getContentLength()+"\n"); sbuff.append(" req.getRemoteAddr():"+req.getRemoteAddr()); try { sbuff.append(" getRemoteHost():"+ java.net.InetAddress.getByName(req.getRemoteHost()).getHostName()+"\n"); } catch (java.net.UnknownHostException e) { sbuff.append(" getRemoteHost():"+ e.getMessage()+"\n"); } sbuff.append(" getRemoteUser():"+req.getRemoteUser()+"\n"); sbuff.append("\n"); sbuff.append("Request Parameters:\n"); Enumeration params = req.getParameterNames(); while (params.hasMoreElements()) { String name = (String) params.nextElement(); String values[] = req.getParameterValues(name); if (values != null) { for (int i = 0; i < values.length; i++) { sbuff.append(" "+name + " (" + i + "): " + values[i]+"\n"); } } } sbuff.append("\n"); sbuff.append("Request Headers:\n"); Enumeration names = req.getHeaderNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); Enumeration values = req.getHeaders(name); // support multiple values if (values != null) { while (values.hasMoreElements()) { String value = (String) values.nextElement(); sbuff.append(" "+name + ": " + value+"\n"); } } } sbuff.append(" return sbuff.toString(); } static public String showRequestHeaders(HttpServletRequest req) { StringBuffer sbuff = new StringBuffer(); sbuff.append("Request Headers:\n"); Enumeration names = req.getHeaderNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); Enumeration values = req.getHeaders(name); // support multiple values if (values != null) { while (values.hasMoreElements()) { String value = (String) values.nextElement(); sbuff.append(" "+name + ": " + value+"\n"); } } } return sbuff.toString(); } static public void showSession(HttpServletRequest req, HttpServletResponse res, PrintStream out) { // res.setContentType("text/html"); // Get the current session object, create one if necessary HttpSession session = req.getSession(); // Increment the hit count for this page. The value is saved // in this client's session under the name "snoop.count". Integer count = (Integer)session.getAttribute("snoop.count"); if (count == null) count = new Integer(1); else count = new Integer(count.intValue() + 1); session.setAttribute("snoop.count", count); out.println( HtmlWriter.getInstance().getHtmlDoctypeAndOpenTag()); out.println("<HEAD><TITLE>SessionSnoop</TITLE></HEAD>"); out.println("<BODY><H1>Session Snoop</H1>"); // Display the hit count for this page out.println("You've visited this page " + count + ((count.intValue() == 1) ? " time." : " times.")); out.println("<P>"); out.println("<H3>Here is your saved session data:</H3>"); Enumeration atts = session.getAttributeNames(); while (atts.hasMoreElements()) { String name = (String) atts.nextElement(); out.println(name + ": " + session.getAttribute(name) + "<BR>"); } out.println("<H3>Here are some vital stats on your session:</H3>"); out.println("Session id: " + session.getId() + " <I>(keep it secret)</I><BR>"); out.println("New session: " + session.isNew() + "<BR>"); out.println("Timeout: " + session.getMaxInactiveInterval()); out.println("<I>(" + session.getMaxInactiveInterval() / 60 + " minutes)</I><BR>"); out.println("Creation time: " + session.getCreationTime()); out.println("<I>(" + new Date(session.getCreationTime()) + ")</I><BR>"); out.println("Last access time: " + session.getLastAccessedTime()); out.println("<I>(" + new Date(session.getLastAccessedTime()) + ")</I><BR>"); out.println("Requested session ID from cookie: " + req.isRequestedSessionIdFromCookie() + "<BR>"); out.println("Requested session ID from URL: " + req.isRequestedSessionIdFromURL() + "<BR>"); out.println("Requested session ID valid: " + req.isRequestedSessionIdValid() + "<BR>"); out.println("<H3>Test URL Rewriting</H3>"); out.println("Click <A HREF=\"" + res.encodeURL(req.getRequestURI()) + "\">here</A>"); out.println("to test that session tracking works via URL"); out.println("rewriting even when cookies aren't supported."); out.println("</BODY></HTML>"); } static public void showSession(HttpServletRequest req, PrintStream out) { // res.setContentType("text/html"); // Get the current session object, create one if necessary HttpSession session = req.getSession(); out.println("Session id: " + session.getId()); out.println(" session.isNew(): " + session.isNew()); out.println(" session.getMaxInactiveInterval(): " + session.getMaxInactiveInterval()+" secs"); out.println(" session.getCreationTime(): " + session.getCreationTime()+" ("+new Date(session.getCreationTime()) + ")"); out.println(" session.getLastAccessedTime(): " + session.getLastAccessedTime()+" ("+new Date(session.getLastAccessedTime()) + ")"); out.println(" req.isRequestedSessionIdFromCookie: " + req.isRequestedSessionIdFromCookie()); out.println(" req.isRequestedSessionIdFromURL: " + req.isRequestedSessionIdFromURL()); out.println(" req.isRequestedSessionIdValid: " + req.isRequestedSessionIdValid()); out.println("Saved session Attributes:"); Enumeration atts = session.getAttributeNames(); while (atts.hasMoreElements()) { String name = (String) atts.nextElement(); out.println(" "+name + ": " + session.getAttribute(name) + "<BR>"); } } static public String showSecurity(HttpServletRequest req, String role) { StringBuffer sbuff = new StringBuffer(); sbuff.append("Security Info\n"); sbuff.append(" req.getRemoteUser(): " + req.getRemoteUser()+"\n"); sbuff.append(" req.getUserPrincipal(): " + req.getUserPrincipal()+"\n"); sbuff.append(" req.isUserInRole("+role+"):"+ req.isUserInRole(role)+"\n"); sbuff.append(" return sbuff.toString(); } static private String getServerInfoName(String serverInfo) { int slash = serverInfo.indexOf('/'); if (slash == -1) return serverInfo; else return serverInfo.substring(0, slash); } static private String getServerInfoVersion(String serverInfo) { // Version info is everything between the slash and the space int slash = serverInfo.indexOf('/'); if (slash == -1) return null; int space = serverInfo.indexOf(' ', slash); if (space == -1) space = serverInfo.length(); return serverInfo.substring(slash + 1, space); } static public void showThreads(PrintStream pw) { Thread current = Thread.currentThread(); ThreadGroup group = current.getThreadGroup(); while (true) { if (group.getParent() == null) break; group = group.getParent(); } showThreads( pw, group, current); } static private void showThreads(PrintStream pw, ThreadGroup g, Thread current) { int nthreads = g.activeCount(); pw.println("\nThread Group = "+g.getName()+" activeCount= "+nthreads); Thread[] tarray = new Thread[nthreads]; int n = g.enumerate(tarray, false); for (int i = 0; i < n; i++) { Thread thread = tarray[i]; ClassLoader loader = thread.getContextClassLoader(); String loaderName = (loader == null) ? "Default" : loader.getClass().getName(); //Thread.State state = thread.getState(); // LOOK JDK 1.5 String state = "unknown"; String id = ""; // thread.getId() LOOK JDK 1.5 pw.print(" "+id +" "+thread.getName() +" "+state +" "+loaderName); if (thread == current) pw.println(" **** CURRENT ***"); else pw.println(); } int ngroups = g.activeGroupCount(); ThreadGroup[] garray = new ThreadGroup[ngroups]; int ng = g.enumerate(garray, false); for (int i = 0; i < ng; i++) { ThreadGroup nested = garray[i]; showThreads(pw, nested, current); } } public static void main(String[] args) { String s = "C:/Program Files/you"; System.out.println("FileURL = "+getFileURL(s)); System.out.println("FileURL2 = "+getFileURL2(s)); } }
package ar.com.jolisper.metachainer.core; import java.util.HashMap; import java.util.Map; public class ChainContext { private Map<String, Object> context; public ChainContext() { context = new HashMap<String, Object>(); } public Object get(String key) { return context.get(key); } public void set(String key, Object value) { context.put(key, value); } }
package ch.unizh.ini.jaer.projects.minliu; import com.jogamp.opengl.GL; import com.jogamp.opengl.GL2; import com.jogamp.opengl.GLAutoDrawable; import com.jogamp.opengl.util.awt.TextRenderer; import java.awt.Font; import java.awt.Point; import java.awt.event.MouseEvent; import java.awt.geom.Rectangle2D; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.EventPacket; import net.sf.jaer.eventprocessing.EventFilter2DMouseAdaptor; import net.sf.jaer.graphics.FrameAnnotater; import net.sf.jaer.util.EngineeringFormat; /** * A simple utility to do hand measurements of velocity using mouse * * @author Tobi Delbruck */ @Description("A simple utility to do hand measurements of velocity using mouse") @DevelopmentStatus(DevelopmentStatus.Status.Stable) public class Speedometer extends EventFilter2DMouseAdaptor implements FrameAnnotater { private int currentTimestamp = 0; private TimePoint startPoint, endPoint; private boolean firstPoint = true; private float speed = 0, distance, deltaTimestamp; EngineeringFormat engFmt = new EngineeringFormat(); TextRenderer textRenderer = null; public Speedometer(AEChip chip) { super(chip); } @Override public EventPacket<?> filterPacket(EventPacket<?> in) { if (in.getSize() > 2) { currentTimestamp = (in.getLastTimestamp() + in.getFirstTimestamp()) / 2; } return in; } @Override public void resetFilter() { firstPoint = true; } @Override public void initFilter() { } @Override synchronized public void mouseClicked(MouseEvent e) { if (e == null || e.getPoint() == null || getMousePixel(e)==null) { firstPoint=true; startPoint=null; endPoint=null; log.info("reset to first point"); return; // handle out of bounds, which should reset } if (firstPoint) { startPoint = new TimePoint(getMousePixel(e), currentTimestamp); endPoint = null; } else { endPoint = new TimePoint(getMousePixel(e), currentTimestamp); } if (startPoint != null && endPoint != null) { distance = (float) (endPoint.distance(startPoint)); deltaTimestamp = endPoint.t - startPoint.t; speed = 1e6f * distance / deltaTimestamp; log.info(String.format("%s pps", engFmt.format(speed))); } firstPoint = !firstPoint; } private class TimePoint extends Point { int t; public TimePoint(int t, int xx, int yy) { super(xx, yy); this.t = t; } public TimePoint(Point p, int t) { super(p.x, p.y); this.t = t; } } @Override synchronized public void annotate(GLAutoDrawable drawable) { super.annotate(drawable); //To change body of generated methods, choose Tools | Templates. GL2 gl = drawable.getGL().getGL2(); drawCursor(gl, startPoint, new float[]{0, 1, 0, 1}); drawCursor(gl, endPoint, new float[]{1, 0, 0, 1}); if (startPoint != null && endPoint != null) { gl.glColor3f(1, 1, 0); gl.glBegin(GL.GL_LINES); gl.glVertex2f(startPoint.x, startPoint.y); gl.glVertex2f(endPoint.x, endPoint.y); gl.glEnd(); if (textRenderer == null) { textRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 24), true, false); } textRenderer.setColor(1, 1, 0, 1); String s = String.format("%s pps (%.0fpix /%ss)", engFmt.format(speed), distance, engFmt.format(1e-6f * deltaTimestamp)); textRenderer.beginRendering(drawable.getSurfaceWidth(), drawable.getSurfaceHeight()); // Rectangle2D r = textRenderer.getBounds(s); textRenderer.draw(s, (startPoint.x + endPoint.x) / 2, (startPoint.y + endPoint.y) / 2); textRenderer.endRendering(); } } private void drawCursor(GL2 gl, Point p, float[] color) { if (p == null) { return; } checkBlend(gl); gl.glColor4fv(color, 0); gl.glLineWidth(3f); gl.glPushMatrix(); gl.glTranslatef(p.x, p.y, 0); gl.glBegin(GL2.GL_LINES); gl.glVertex2f(0, -CURSOR_SIZE_CHIP_PIXELS / 2); gl.glVertex2f(0, +CURSOR_SIZE_CHIP_PIXELS / 2); gl.glVertex2f(-CURSOR_SIZE_CHIP_PIXELS / 2, 0); gl.glVertex2f(+CURSOR_SIZE_CHIP_PIXELS / 2, 0); gl.glEnd(); gl.glTranslatef(.5f, -.5f, 0); gl.glColor4f(0, 0, 0, 1); gl.glBegin(GL2.GL_LINES); gl.glVertex2f(0, -CURSOR_SIZE_CHIP_PIXELS / 2); gl.glVertex2f(0, +CURSOR_SIZE_CHIP_PIXELS / 2); gl.glVertex2f(-CURSOR_SIZE_CHIP_PIXELS / 2, 0); gl.glVertex2f(+CURSOR_SIZE_CHIP_PIXELS / 2, 0); gl.glEnd(); gl.glPopMatrix(); } }
package com.biggestnerd.radarjammer; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Map.Entry; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.scheduler.BukkitRunnable; import com.comphenix.protocol.PacketType; import com.comphenix.protocol.ProtocolLibrary; import com.comphenix.protocol.events.ListenerPriority; import com.comphenix.protocol.events.PacketAdapter; import com.comphenix.protocol.events.PacketContainer; import com.comphenix.protocol.events.PacketEvent; import net.md_5.bungee.api.ChatColor; public class VisibilityManager extends BukkitRunnable implements Listener{ private int minCheck; private int maxCheck; private double hFov; private double vFov; private boolean showCombatTagged; private boolean timing; private float maxSpin; private long flagTime; private int maxFlags; private int blindDuration; private long maxLogoutTime; private ConcurrentHashMap<UUID, HashSet<UUID>[]> maps; private ConcurrentHashMap<UUID, Long> blinded; private ConcurrentLinkedQueue<UUID> blindQueue; private ConcurrentHashMap<UUID, Integer> offlineTaskMap; private AtomicBoolean buffer; private CalculationThread calcThread; private AntiBypassThread antiBypassThread; private Logger log; private RadarJammer plugin; public VisibilityManager(RadarJammer plugin, int minCheck, int maxCheck, double hFov, double vFov, boolean showCombatTagged, boolean timing, float maxSpin, long flagTime, int maxFlags, int blindDuration, boolean loadtest, long maxLogoutTime) { this.plugin = plugin; log = plugin.getLogger(); maps = new ConcurrentHashMap<UUID, HashSet<UUID>[]>(); blinded = new ConcurrentHashMap<UUID, Long>(); blindQueue = new ConcurrentLinkedQueue<UUID>(); offlineTaskMap = new ConcurrentHashMap<UUID, Integer>(); buffer = new AtomicBoolean(); this.minCheck = minCheck*minCheck; this.maxCheck = maxCheck*maxCheck; this.hFov = hFov; this.vFov = vFov; boolean ctEnabled = plugin.getServer().getPluginManager().isPluginEnabled("CombatTagPlus"); if(!ctEnabled || !showCombatTagged) { this.showCombatTagged = false; } else { log.info("RadarJammer will show combat tagged players."); this.showCombatTagged = true; CombatTagManager.initialize(); } this.timing = timing; this.maxSpin = maxSpin; this.flagTime = flagTime; this.maxFlags = maxFlags; this.blindDuration = blindDuration; this.maxLogoutTime = maxLogoutTime; runTaskTimer(plugin, 1L, 1L); calcThread = new CalculationThread(); calcThread.start(); antiBypassThread = new AntiBypassThread(); antiBypassThread.start(); if(loadtest) new SyntheticLoadTest().runTaskTimerAsynchronously(plugin, 1L, 1L); log.info("VisibilityManager initialized!"); } private long lastCheckRun = 0l; enum btype { SHOW, HIDE } public int getBuffer(btype buf) { if (buffer.get()) { switch(buf) { case SHOW: return 1; case HIDE: return 3; } } else { switch(buf) { case SHOW: return 2; case HIDE: return 4; } } return -1; } @Override public void run() { long s = System.currentTimeMillis(); long b = 0l; long t = 0l; long pl = 0l; long sh = 0l; long hi = 0l; double aqp = 0.0d; boolean buff = false; // Flip buffers. synchronized(buffer) { buff = buffer.get(); buffer.set(!buff); } for(Player p : Bukkit.getOnlinePlayers()) { if(timing) { b = System.currentTimeMillis(); pl++; } if(blindQueue.remove(p.getUniqueId())) { int amplifyMin = blindDuration + (int) antiBypassThread.angleChange.get(p.getUniqueId())[3]; int amplifyTicks = amplifyMin * 7200; p.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, amplifyTicks, 1)); p.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, amplifyTicks, 1)); p.sendMessage(ChatColor.DARK_RED + "You're spinning too fast and dizziness sets in. You are temporarily blinded for " + amplifyMin + " minutes!"); } // now get the set of arrays. Careful to only deal with the "locked" ones // based on the semaphore. In this case, "true" gives low-order buffers. UUID pu = p.getUniqueId(); HashSet<UUID>[] buffers = maps.get(pu); if (buffers == null) { maps.put(pu, allocate()); continue; } HashSet<UUID> show = buffers[buff?1:2]; HashSet<UUID> hide = buffers[buff?3:4]; if(!show.isEmpty()) { for(UUID id : show) { Player o = Bukkit.getPlayer(id); if(timing) sh++; if(o != null) { log.info(String.format("Showing %s to %s", o.getName(), p.getName())); p.showPlayer(o); if (hide.remove(id)) { // prefer to show rather then hide. In case of conflict, show wins. log.info(String.format("Suppressed hide of %s from %s", o.getName(), p.getName())); } } } show.clear(); // prepare buffer for next swap. } if (p.hasPermission("jammer.bypass")) continue; if(!hide.isEmpty()) { for(UUID id : hide) { Player o = Bukkit.getPlayer(id); if(timing) hi++; if(o != null) { log.info(String.format("Hiding %s from %s", o.getName(), p.getName())); p.hidePlayer(o); } } hide.clear(); } if(timing) { t = System.currentTimeMillis(); aqp = aqp + ((double)(t-b) - aqp)/pl; } } if ((s - lastCheckRun) > 1000l && timing) { if (pl > 0) log.info(String.format("Updated %d players in %d milliseconds, spending %.2f per player. Total %d seen updates and %d hide updates", pl, (t-s), aqp, sh, hi)); else log.info("No players currently tracked."); lastCheckRun = s; } } @EventHandler public void onPlayerJoin(PlayerJoinEvent event) { Player player = event.getPlayer(); PlayerLocation location = getLocation(player); calcThread.queueLocation(location); HashSet<UUID>[] buffers = maps.get(player.getUniqueId()); if (buffers == null) { maps.put(player.getUniqueId(), allocate()); } else { for (HashSet<UUID> buffer : buffers){ buffer.clear(); } } Integer task = offlineTaskMap.remove(player.getUniqueId()); if(task != null) { plugin.getServer().getScheduler().cancelTask(task); } } @EventHandler public void onPlayerLeave(PlayerQuitEvent event) { UUID id = event.getPlayer().getUniqueId(); OfflinePlayerCheck offlineTask = new OfflinePlayerCheck(id); offlineTaskMap.put(id, offlineTask.runTaskLater(plugin, maxLogoutTime).getTaskId()); } @SuppressWarnings("unchecked") private HashSet<UUID>[] allocate() { return (HashSet<UUID>[]) new HashSet[] { new HashSet<UUID>(), new HashSet<UUID>(), new HashSet<UUID>(), new HashSet<UUID>(), new HashSet<UUID>() }; } @EventHandler public void onPlayerMove(PlayerMoveEvent event) { Player player = event.getPlayer(); PlayerLocation location = getLocation(player); calcThread.queueLocation(location); } private PlayerLocation getLocation(Player player) { boolean invis = player.hasPotionEffect(PotionEffectType.INVISIBILITY); ItemStack inHand = player.getInventory().getItemInMainHand(); ItemStack offHand = player.getInventory().getItemInOffHand(); ItemStack[] armor = player.getInventory().getArmorContents(); boolean hasArmor = false; for(ItemStack item : armor) if(item != null && item.getType() != Material.AIR) hasArmor = true; invis = invis && (inHand == null || inHand.getType() == Material.AIR) && (offHand == null || offHand.getType() == Material.AIR) && !hasArmor; return new PlayerLocation(player.getEyeLocation(), player.getUniqueId(), invis); } class CalculationThread extends Thread { private final ConcurrentHashMap<UUID, PlayerLocation> locationMap = new ConcurrentHashMap<UUID, PlayerLocation>(); private final Set<UUID> movedPlayers = Collections.synchronizedSet(new LinkedHashSet<UUID>()); private final Set<UUID> recalc = Collections.synchronizedSet(new HashSet<UUID>()); public void run() { log.info("RadarJammer: Starting calculation thread!"); long lastLoopStart = 0l; while(true) { lastLoopStart = System.currentTimeMillis(); while (System.currentTimeMillis() - lastLoopStart < 50l) { Iterator<UUID> movedIterator = movedPlayers.iterator(); if(movedIterator.hasNext()) { UUID id = movedIterator.next(); PlayerLocation next = locationMap.get(id); if (next != null) { recalc.add(id); movedPlayers.remove(id); } try { sleep(1l); }catch(InterruptedException ie) {} } } if(!recalc.isEmpty()) { doCalculations(); } if (calcRuns > 20) { showAvg(); } try { sleep(1l); }catch(InterruptedException ie) {} } } private void showAvg() { if(!timing) return; if (calcRuns == 0d || calcPerPlayerRuns == 0d) { log.info("RadarJammer Calculations Performance: none done."); } else { log.info(String.format("RadarJammer Calculations Performance: %.0f runs, %.0f players calculated for.", calcRuns, calcPerPlayerRuns)); log.info(String.format(" on average: %.5fms in setup, %.4fms per player per run, %.4fms per run", (calcSetupAverage / calcRuns), (calcPerPlayerAverage / calcPerPlayerRuns), (calcAverage / calcRuns))); } calcSetupAverage = 0d; calcPerPlayerAverage = 0d; calcPerPlayerRuns = 0d; calcAverage =0d; calcRuns = 0d; } private void queueLocation(PlayerLocation location) { if(location == null) return; locationMap.put(location.getID(), location); movedPlayers.add(location.getID()); } private double calcSetupAverage = 0d; private double calcPerPlayerAverage = 0d; private double calcPerPlayerRuns = 0d; private double calcAverage = 0d; private double calcRuns = 0d; long s_ = 0L; long b_ = 0l; long e_ = 0l; private void doCalculations() { for (UUID player : recalc) { doCalculations(locationMap.get(player)); } recalc.clear(); } private void doCalculations(PlayerLocation location) { if (location == null) return; if(timing) { calcRuns ++; s_ = System.currentTimeMillis(); e_ = System.currentTimeMillis(); calcSetupAverage += (double) (e_ - s_); } UUID id = location.getID(); Enumeration<PlayerLocation> players = locationMap.elements(); while(players.hasMoreElements()) { PlayerLocation other = players.nextElement(); UUID oid = other.getID(); if (id.equals(oid)) continue; if(timing) { calcPerPlayerRuns++; b_ = System.currentTimeMillis(); } boolean hidePlayer = shouldHide(other, location); boolean hideOther = shouldHide(location, other); /* double dist = location.getSquaredDistance(other); if(dist > minCheck) { if(dist < maxCheck) { hideOther = location.getAngle(other) > maxFov || other.isInvis(); hidePlayer = other.getAngle(location) > maxFov || location.isInvis(); } else { hidePlayer = hideOther = true; } } else { hidePlayer = hideOther = false; } */ HashSet<UUID>[] buffers = maps.get(id); if (buffers == null) return; boolean hidingOther = buffers[0].contains(oid); if(hidingOther != hideOther) { if(hideOther) { buffers[getBuffer(btype.HIDE)].add(oid); buffers[0].add(oid); } else { buffers[getBuffer(btype.SHOW)].add(oid); buffers[0].remove(oid); } } buffers = maps.get(oid); if (buffers == null) return; boolean hidingPlayer = buffers[0].contains(id); if(hidingPlayer != hidePlayer) { if(hidePlayer) { buffers[getBuffer(btype.HIDE)].add(id); buffers[0].add(id); } else { buffers[getBuffer(btype.SHOW)].add(id); buffers[0].remove(id); } } if(timing) { e_ = System.currentTimeMillis(); calcPerPlayerAverage += (e_ - b_); } } if(timing) { e_ = System.currentTimeMillis(); calcAverage += (e_ - s_); } } private boolean shouldHide(PlayerLocation loc, PlayerLocation other) { if(showCombatTagged && CombatTagManager.isTagged(loc.getID())) return false; boolean blind = blinded.containsKey(loc.getID()); if(blind || other.isInvis()) return true; double dist = loc.getSquaredDistance(other); if(dist > minCheck) { if(dist < maxCheck) { double vAngle = loc.getVerticalAngle(other); double hAngle = loc.getHorizontalAngle(other); return !(vAngle < vFov && hAngle < hFov); } else { return true; } } else { return false; } } } class AntiBypassThread extends Thread { private ConcurrentHashMap<UUID, float[]> angleChange = new ConcurrentHashMap<UUID, float[]>(); public AntiBypassThread() { ProtocolLibrary.getProtocolManager().addPacketListener(new PacketAdapter(plugin, ListenerPriority.NORMAL, PacketType.Play.Client.LOOK, PacketType.Play.Client.POSITION_LOOK) { @Override public void onPacketReceiving(PacketEvent event) { PacketContainer packet = event.getPacket(); float yaw = packet.getFloat().read(0); updatePlayer(event.getPlayer().getUniqueId(), yaw); } }); } @Override public void run() { long lastLoopStart = 0l; long lastFlagCheck = 0l; while(true) { if(System.currentTimeMillis() - lastFlagCheck > flagTime) { lastFlagCheck = System.currentTimeMillis(); for(Entry<UUID, float[]> entry : angleChange.entrySet()) { if(entry.getValue()[2] >= maxFlags) { angleChange.get(entry.getKey())[3] += 1; UUID id = entry.getKey(); log.info(id + " has reached the threshold for bypass flags, blinding them for a few minutes."); blinded.put(id, System.currentTimeMillis()); entry.getValue()[2] = 0; } } } //Every second check angle change if(System.currentTimeMillis() - lastLoopStart > 1000l) { lastLoopStart = System.currentTimeMillis(); for(Entry<UUID, Long> entry : blinded.entrySet()) { long blindLengthMillis = blindDuration * 60000; if(System.currentTimeMillis() - entry.getValue() > blindLengthMillis) { blinded.remove(entry.getKey()); } } for(Entry<UUID, float[]> entry : angleChange.entrySet()) { boolean blind = entry.getValue()[0] > maxSpin; entry.getValue()[0] = 0; if(blind) { entry.getValue()[2] += 1; } } } try { sleep(1l); }catch(InterruptedException ie) {} } } private void updatePlayer(UUID player, float newAngle) { if(!angleChange.containsKey(player)) { angleChange.put(player, new float[]{0,newAngle,0,0}); } else { float last = angleChange.get(player)[1]; float change = Math.abs(last - newAngle); angleChange.get(player)[1] = newAngle; angleChange.get(player)[0] += change; } } } class SyntheticLoadTest extends BukkitRunnable { private PlayerLocation[] locations; public SyntheticLoadTest() { locations = new PlayerLocation[100]; int i = 0; for(int x = 0; x < 10; x++) { for(int z = 0; z < 10; z++) { UUID id = UUID.randomUUID(); PlayerLocation location = new PlayerLocation(x * 10, 60, z * 10, 0, 0, id, false); locations[i++] = location; calcThread.queueLocation(location); HashSet<UUID>[] buffers = maps.get(id); if (buffers == null) { maps.put(id, allocate()); } else { for (HashSet<UUID> buffer : buffers){ buffer.clear(); } } } } } @Override public void run() { for(int i = 0; i < locations.length; i++) { if(locations[i] == null) break; locations[i].addYaw(.5F); calcThread.queueLocation(locations[i]); } } } class OfflinePlayerCheck extends BukkitRunnable { private UUID id; public OfflinePlayerCheck(UUID player) { this.id = player; } @Override public void run () { Player player = Bukkit.getPlayer(id); if(player == null || !player.isOnline()) { maps.remove(id); blinded.remove(id); blindQueue.remove(id); offlineTaskMap.remove(player); } } } }
package com.dmdirc.addons.lagdisplay; import com.dmdirc.ui.WindowManager; import com.dmdirc.util.RollingList; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.List; import javax.swing.JPanel; /** * Shows a ping history graph for the current server. * * @author chris */ public class PingHistoryPanel extends JPanel { /** * A version number for this class. It should be changed whenever the class * structure is changed (or anything else that would prevent serialized * objects being unserialized with the new class). */ private static final long serialVersionUID = 1; /** The plugin that this panel is for. */ protected final LagDisplayPlugin plugin; /** The history that we're graphing. */ protected final RollingList<Long> history; /** The maximum ping value. */ protected long maximum = 0l; /** * Creates a new history panel for the specified plugin. * * @param plugin The plugin that owns this panel */ public PingHistoryPanel(final LagDisplayPlugin plugin) { super(); setMinimumSize(new Dimension(50, 100)); setMaximumSize(new Dimension(Integer.MAX_VALUE, 100)); setOpaque(false); this.plugin = plugin; this.history = plugin.getHistory(WindowManager.getActiveServer()); for (Long value : history.getList()) { maximum = Math.max(value, maximum); } } /** {@inheritDoc} */ @Override public void paint(final Graphics g) { super.paint(g); g.setColor(Color.DARK_GRAY); g.drawLine(2, 1, 2, getHeight() - 1); g.drawLine(1, getHeight() - 2, getWidth() - 1, getHeight() - 2); g.setFont(g.getFont().deriveFont(10f)); float lastX = -1, lastY = -1; float pixelsperpointX = (getWidth() - 3) / (float) (history.getList().size() == 1 ? 1 : history.getList().size() - 1); float pixelsperpointY = (getHeight() - 10) / (float) maximum; if (history.isEmpty()) { g.drawString("No data", getWidth() / 2 - 25, getHeight() / 2 + 5); } long last1 = -1, last2 = -1; final List<Long> list = history.getList(); final List<Rectangle> rects = new ArrayList<Rectangle>(); for (int i = 0; i < list.size(); i++) { final Long value = list.get(i); float x = lastX == -1 ? 2 : lastX + pixelsperpointX; float y = getHeight() - 5 - value * pixelsperpointY; if (lastX > -1) { g.drawLine((int) lastX, (int) lastY, (int) x, (int) y); } g.drawRect((int) x - 1, (int) y - 1, 2, 2); if (plugin.shouldShowLabels() && last1 > -1 && (last2 <= last1 || last1 >= value)) { final String text = plugin.formatTime(last1); final Rectangle2D rect = g.getFont().getStringBounds(text, ((Graphics2D) g).getFontRenderContext()); final int width = 10 + (int) rect.getWidth(); final int points = (int) Math.ceil(width / pixelsperpointX); final int diffy = (int) (last1 - (10 + rect.getHeight()) / pixelsperpointY); float posX = lastX - width + 7; float posY = (float) (lastY + rect.getHeight() / 2) - 1; boolean failed = posX < 0; // Check left for (int j = Math.max(0, i - points); j < i - 1; j++) { if (list.get(j) > diffy) { failed = true; break; } } if (failed) { posX = lastX + 3; failed = posX + width > getWidth(); // Check right for (int j = i; j < Math.min(list.size(), i + points); j++) { if (list.get(j) > diffy) { failed = true; break; } } } if (!failed) { final Rectangle myrect = new Rectangle((int) posX - 2, (int) lastY - 7, 5 + (int) rect.getWidth(), 3 + (int) rect.getHeight()); for (Rectangle test : rects) { if (test.intersects(myrect)) { failed = true; } } if (!failed) { g.drawString(text, (int) posX, (int) posY); rects.add(myrect); } } } lastX = x; lastY = y; last2 = last1; last1 = value; } } }
package com.gmail.liamgomez75.parkourroll; import com.gmail.liamgomez75.parkourroll.experience.Experience; import com.gmail.liamgomez75.parkourroll.listeners.DamageListener; import com.gmail.liamgomez75.parkourroll.localisation.Localisable; import com.gmail.liamgomez75.parkourroll.localisation.Localisation; import com.gmail.liamgomez75.parkourroll.localisation.LocalisationEntry; import com.gmail.liamgomez75.parkourroll.utils.EXPConfigUtils; import com.gmail.liamgomez75.parkourroll.utils.LevelConfigUtils; import com.gmail.liamgomez75.parkourroll.utils.RateConfigUtils; import org.bukkit.ChatColor; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; /** * Parkour Roll plugin for Bukkit. * * @author Liam Gomez <liamgomez75.gmail.com> * @author JamesHealey94 <jameshealey1994.gmail.com> */ public class ParkourRoll extends JavaPlugin implements Localisable { /** * The current localisation for the plugin. */ private Localisation localisation = new Localisation(this); @Override public void onEnable() { getServer().getPluginManager().registerEvents(new DamageListener(this), this); saveDefaultConfig(); } /** * Executes the command. * * @param sender sender of the command * @param cmd command sent * @param commandLabel exact command string sent * @param args arguments given with the command * @return if the command was executed correctly */ @Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if (cmd.getName().equalsIgnoreCase("Parkourroll")) { if (args.length > 0) { if ((args[0].equalsIgnoreCase("reload"))) { return reload(sender); } else if ((args[0].equalsIgnoreCase("level"))) { if (sender instanceof Player) { final Player p = (Player) sender; final World world = p.getWorld(); final int lvlNum = LevelConfigUtils.getPlayerLevel(p, world, this); final int expNum = EXPConfigUtils.getPlayerExp(p, world, this); final int reqExp = Experience.getRequiredExp(this, lvlNum); final int rate = RateConfigUtils.getPlayerRate(p, world, this); sender.sendMessage("You are level " + lvlNum + "."); sender.sendMessage("Exp: " + expNum + "/" + reqExp); sender.sendMessage("Exp Rate: " + rate); // TODO remove? return true; } else { sender.sendMessage("You can't run that command from the console!"); return true; } } else if(args[0].equalsIgnoreCase("setlevel")) { if (args.length > 3) { if ((sender instanceof Player) && (sender.hasPermission("pkr.admin"))) { final String target = args[1]; final String worldName = args [2]; if (target != null) { int level = Integer.parseInt(args[3]); LevelConfigUtils.setPlayerLevel(target, worldName,level,this); sender.sendMessage(ChatColor.GRAY + args[1] + "has been set to level" + LevelConfigUtils.getPlayerLevel(target, worldName, this) ); } else { sender.sendMessage(ChatColor.RED + "The specified player does not exist."); } } else { final String target = args[1]; final String worldName = args [2]; if (target != null) { int level = Integer.parseInt(args[3]); LevelConfigUtils.setPlayerLevel(target, worldName,level,this); sender.sendMessage(ChatColor.GRAY + args[1] + "has been set to level" + LevelConfigUtils.getPlayerLevel(target, worldName, this) ); } else { sender.sendMessage(ChatColor.RED + "The specified player does not exist."); } } } } } } return false; } public boolean reload(CommandSender sender) { if (sender.hasPermission("pkr.admin")) { reloadConfig(); sender.sendMessage(localisation.get(LocalisationEntry.MSG_CONFIG_RELOADED)); } else { sender.sendMessage(localisation.get(LocalisationEntry.ERR_PERMISSION_DENIED)); } return true; } @Override public Localisation getLocalisation() { return localisation; } @Override public void setLocalisation(Localisation localisation) { this.localisation = localisation; } }
package com.haxademic.sketch.test; import java.util.ArrayList; import processing.core.PShape; import processing.core.PVector; import com.haxademic.core.app.P; import com.haxademic.core.app.PAppletHax; import com.haxademic.core.draw.util.OpenGLUtil; import com.haxademic.core.system.FileUtil; @SuppressWarnings("serial") public class PShapeObjDeformTest extends PAppletHax { protected PShape obj; protected PShape objOrig; protected float _spectrumInterval; protected ArrayList<PVector> vertices; protected ArrayList<Integer> sharedVertexIndices; protected float _size = 0; protected void overridePropsFile() { _appConfig.setProperty( "fills_screen", "false" ); _appConfig.setProperty( "rendering", "false" ); } public void setup() { super.setup(); OpenGLUtil.setQuality( p, OpenGLUtil.SMOOTH_HIGH ); String objFile = ""; objFile = "mode-set.obj"; objFile = "Space_Shuttle.obj"; objFile = "cacheflowe-3d.obj"; objFile = "poly-hole-tri.obj"; objFile = "pointer_cursor_2_hollow.obj"; objFile = "skull.obj"; objFile = "lego-man.obj"; objFile = "chicken.obj"; obj = p.loadShape( FileUtil.getHaxademicDataPath() + "models/" + objFile ); objOrig = p.loadShape( FileUtil.getHaxademicDataPath() + "models/" + objFile ); // build data of shared vertex connections vertices = new ArrayList<PVector>(); sharedVertexIndices = new ArrayList<Integer>(); // loop through model, finding vertices for (int j = 0; j < obj.getChildCount(); j++) { for (int i = 0; i < obj.getChild(j).getVertexCount(); i++) { // store vertex PVector vertex = objOrig.getChild(j).getVertex(i); vertices.add(vertex); // look for matching vertex, and store vertex to shared vertex match, if we find one. boolean foundMatch = false; for(int v=0; v < vertices.size(); v++) { if(foundMatch == false && vertices.get(v).dist(vertex) == 0) { sharedVertexIndices.add(v); foundMatch = true; } } // otherwise, add a new vertex match if(foundMatch == false) { sharedVertexIndices.add(vertices.size() - 1); } } } // find mesh size extent to responsively scale the mesh float outermostVertex = 0; for (PVector vertex : vertices) { if(vertex.x > outermostVertex) outermostVertex = vertex.x; if(vertex.y > outermostVertex) outermostVertex = vertex.y; if(vertex.z > outermostVertex) outermostVertex = vertex.z; } _size = outermostVertex; // spread spectrum across vertices _spectrumInterval = 512f / sharedVertexIndices.size(); P.println("vertex count: ", vertices.size()); p.smooth(OpenGLUtil.SMOOTH_HIGH); } public void drawApp() { background(0); // setup lights p.lightSpecular(230, 230, 230); p.directionalLight(200, 200, 200, -0.0f, -0.0f, 1); p.directionalLight(200, 200, 200, 0.0f, 0.0f, -1); p.specular(color(200)); p.shininess(5.0f); p.translate(p.width/2f, p.height/2f); p.translate(0, 0, -1000); p.rotateY(p.mouseX * 0.01f); p.rotateZ(p.mouseY * 0.01f); // DrawUtil.setDrawCenter(p); // for (int j = 0; j < obj.getChildCount(); j++) { // for (int i = 0; i < obj.getChild(j).getVertexCount(); i++) { // PVector v = obj.getChild(j).getVertex(i); // v.x += random(-0.01f,0.01f); // v.y += random(-0.01f,0.01f); // v.z += random(-0.01f,0.01f); // obj.getChild(j).setVertex(i,v.x,v.y,v.z); // deform from original copy // int spectrumIndex = 0; // for (int j = 0; j < obj.getChildCount(); j++) { // for (int i = 0; i < obj.getChild(j).getVertexCount(); i++) { // float amp = 1 + 0.9f * P.p.audioIn.getEqAvgBand( P.floor(_spectrumInterval * spectrumIndex) ); // PVector v = obj.getChild(j).getVertex(i); // PVector vOrig = objOrig.getChild(j).getVertex(i); // v.x = vOrig.x * amp; // v.y = vOrig.y * amp; // v.z = vOrig.z * amp; // obj.getChild(j).setVertex(i,v.x,v.y,v.z); // spectrumIndex++; // deform from original copy, using vertexIndex as the key to find the shared index int vertexIndex = 0; for (int j = 0; j < obj.getChildCount(); j++) { for (int i = 0; i < obj.getChild(j).getVertexCount(); i++) { int sharedVertexIndex = sharedVertexIndices.get(vertexIndex); PVector vOrig = vertices.get(vertexIndex); float amp = 1 + 0.5f * P.p._audioInput.getFFT().spectrum[ P.floor(_spectrumInterval * sharedVertexIndex) ]; // get shared vertex deformation // float amp = 1 + 0.1f * P.p.audioIn.getEqAvgBand( P.floor(_spectrumInterval * sharedVertexIndex) ); // get shared vertex deformation obj.getChild(j).setVertex(i, vOrig.x * amp, vOrig.y * amp, vOrig.z * amp); vertexIndex++; } } // draw! obj.disableStyle(); p.fill(200, 255, 200); p.noStroke(); // p.stroke(255); // p.strokeWeight(2); p.scale(p.height/_size * 0.8f); p.shape(obj); } }
package com.opengamma.engine.test; import java.util.concurrent.Executors; import org.fudgemsg.FudgeContext; import org.fudgemsg.FudgeFieldContainer; import com.opengamma.engine.DefaultComputationTargetResolver; import com.opengamma.engine.function.FunctionExecutionContext; import com.opengamma.engine.function.InMemoryFunctionRepository; import com.opengamma.engine.position.MockPositionSource; import com.opengamma.engine.security.MockSecuritySource; import com.opengamma.engine.view.cache.InMemoryViewComputationCacheSource; import com.opengamma.engine.view.calcnode.AbstractCalculationNode; import com.opengamma.engine.view.calcnode.ViewProcessorQuerySender; import com.opengamma.transport.FudgeMessageReceiver; import com.opengamma.transport.FudgeRequestSender; import com.opengamma.util.InetAddressUtils; import com.opengamma.util.fudge.OpenGammaFudgeContext; public class TestCalculationNode extends AbstractCalculationNode { public TestCalculationNode() { super(new InMemoryViewComputationCacheSource(OpenGammaFudgeContext.getInstance()), new InMemoryFunctionRepository (), new FunctionExecutionContext(), new DefaultComputationTargetResolver(new MockSecuritySource(), new MockPositionSource()), new ViewProcessorQuerySender(new FudgeRequestSender () { @Override public FudgeContext getFudgeContext() { return FudgeContext.GLOBAL_DEFAULT; } @Override public void sendRequest(FudgeFieldContainer request, FudgeMessageReceiver responseReceiver) { // No-op } }), InetAddressUtils.getLocalHostName(), Executors.newCachedThreadPool ()); } }
package com.tactfactory.harmony.parser; import java.util.ArrayList; import java.util.Map; import com.google.common.base.Strings; import com.tactfactory.harmony.annotation.Column.Type; import com.tactfactory.harmony.meta.ClassMetadata; import com.tactfactory.harmony.meta.EntityMetadata; import com.tactfactory.harmony.meta.EnumMetadata; import com.tactfactory.harmony.meta.FieldMetadata; import com.tactfactory.harmony.plateforme.SqliteAdapter; /** The class ClassCompletor will complete all ClassMetadatas * with the information it needs from the others ClassMetadatas. */ public class ClassCompletor { /** Class metadata. */ private Map<String, EntityMetadata> metas; /** Class metadata. */ private Map<String, EnumMetadata> enumMetas; /** * Constructor. * @param entities Entities map. */ public ClassCompletor(final Map<String, EntityMetadata> entities, final Map<String, EnumMetadata> enums) { this.metas = entities; this.enumMetas = enums; } /** * Complete classes. */ public final void execute() { /** Remove non-existing classes. */ ArrayList<EntityMetadata> nonParsed = new ArrayList<EntityMetadata>(); for (final EntityMetadata classMeta : this.metas.values()) { if (!classMeta.hasBeenParsed() && !classMeta.isInternal()) { nonParsed.add(classMeta); } } for (final EntityMetadata classMeta : nonParsed) { this.metas.remove(classMeta.getName()); } /** Update column definitions for entities. */ for (final EntityMetadata classMeta : this.metas.values()) { this.updateColumnDefinition(classMeta); } /** Update column definitions for enums. */ for (final EnumMetadata enumMeta : this.enumMetas.values()) { this.updateColumnDefinition(enumMeta); } } /** * Update fields column definition. * * @param entity The entity in which to complete fields */ private void updateColumnDefinition(final ClassMetadata entity) { for (final FieldMetadata field : entity.getFields().values()) { // Get column definition if non existent if (Strings.isNullOrEmpty(field.getColumnDefinition())) { field.setColumnDefinition( SqliteAdapter.generateColumnType(field)); } // Warn the user if the column definition is a reserved keyword SqliteAdapter.Keywords.exists(field.getColumnDefinition()); // Set default values for type if type is recognized final Type type; if (field.getHarmonyType() != null) { type = Type.fromName( field.getHarmonyType()); } else { type = Type.fromName( field.getType()); } if (type != null) { //field.setColumnDefinition(type.getValue()); if (field.isNullable() == null) { field.setNullable(type.isNullable()); } if (field.isUnique() == null) { field.setUnique(type.isUnique()); } if (field.getLength() == null) { field.setLength(type.getLength()); } if (field.getPrecision() == null) { field.setPrecision(type.getPrecision()); } if (field.getScale() == null) { field.setScale(type.getScale()); } if (field.isLocale() == null) { field.setIsLocale(type.isLocale()); } } else { if (field.isNullable() == null) { field.setNullable(false); } if (field.isUnique() == null) { field.setUnique(false); } if (field.getLength() == null) { field.setLength(null); } if (field.getPrecision() == null) { field.setPrecision(null); } if (field.getScale() == null) { field.setScale(null); } if (field.isLocale() == null) { field.setIsLocale(false); } } if (Strings.isNullOrEmpty(field.getHarmonyType())) { if (type != null) { field.setHarmonyType(type.getValue()); } else { field.setHarmonyType(field.getType()); } } } } }
package com.vinsol.expensetracker.edit; import java.io.File; import java.util.Calendar; import android.app.Activity; import android.content.Intent; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.vinsol.expensetracker.Constants; import com.vinsol.expensetracker.R; import com.vinsol.expensetracker.cameraservice.Camera; import com.vinsol.expensetracker.helpers.CameraFileSave; import com.vinsol.expensetracker.helpers.DatabaseAdapter; import com.vinsol.expensetracker.helpers.DateHelper; import com.vinsol.expensetracker.helpers.LocationHelper; import com.vinsol.expensetracker.models.Entry; import com.vinsol.expensetracker.utils.ImagePreview; import com.vinsol.expensetracker.utils.Log; public class CameraActivity extends EditAbstract { private static final int PICTURE_RESULT = 35; private LinearLayout editCameraDetails; private ImageView editImageDisplay; private RelativeLayout editLoadProgress; private float scale; private int width; private int height; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); editCameraDetails = (LinearLayout) findViewById(R.id.edit_camera_details); editImageDisplay = (ImageView) findViewById(R.id.edit_image_display); editLoadProgress = (RelativeLayout) findViewById(R.id.edit_load_progress); typeOfEntry = R.string.camera; typeOfEntryFinished = R.string.finished_cameraentry; typeOfEntryUnfinished = R.string.unfinished_cameraentry; editHelper(); scale = this.getResources().getDisplayMetrics().density; width = (int) (84 * scale + 0.5f); height = (int) (111 * scale + 0.5f); if (intentExtras.containsKey(Constants.KEY_ENTRY_LIST_EXTRA)) { if(setUnknown) { startCamera(); } File mFile; if(isFromFavorite) { mFile = fileHelper.getCameraFileSmallFavorite(mFavoriteList.favId); } else { mFile = fileHelper.getCameraFileSmallEntry(entry.id); } if (mFile.canRead() && mFile.exists()) { Drawable mDrawable = Drawable.createFromPath(mFile.getPath()); setImageResource(mDrawable); } else { editImageDisplay.setImageResource(R.drawable.no_image_small); } } setGraphicsCamera(); setClickListeners(); mDatabaseAdapter = new DatabaseAdapter(this); dateViewString = dateBarDateview.getText().toString(); if(!isFromFavorite && entry.id == null) { if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) { Entry toInsert = new Entry(); if (!dateBarDateview.getText().toString().equals(dateViewString)) { try { if (!intentExtras.containsKey(Constants.KEY_ENTRY_LIST_EXTRA)) { DateHelper mDateHelper = new DateHelper(dateBarDateview.getText().toString()); toInsert.timeInMillis = mDateHelper.getTimeMillis(); } else { if(!intentExtras.containsKey(Constants.KEY_TIME_IN_MILLIS)) { DateHelper mDateHelper = new DateHelper(dateBarDateview.getText().toString()); toInsert.timeInMillis = mDateHelper.getTimeMillis(); } else { Calendar mCalendar = Calendar.getInstance(); mCalendar.setTimeInMillis(intentExtras.getLong(Constants.KEY_TIME_IN_MILLIS)); mCalendar.setFirstDayOfWeek(Calendar.MONDAY); DateHelper mDateHelper = new DateHelper(dateBarDateview.getText().toString(),mCalendar); toInsert.timeInMillis = mDateHelper.getTimeMillis(); } } } catch (Exception e) { } } else { Calendar mCalendar = Calendar.getInstance(); mCalendar.setFirstDayOfWeek(Calendar.MONDAY); toInsert.timeInMillis = mCalendar.getTimeInMillis(); } if (LocationHelper.currentAddress != null && LocationHelper.currentAddress.trim() != "") { toInsert.location = LocationHelper.currentAddress; } toInsert.type = getString(R.string.camera); mDatabaseAdapter.open(); entry.id = mDatabaseAdapter.insertToEntryTable(toInsert).toString(); mDatabaseAdapter.close(); } } //New Entry super.setFavoriteHelper(); if (!intentExtras.containsKey(Constants.KEY_ENTRY_LIST_EXTRA)) startCamera(); } @Override protected void setFavoriteHelper() { //DO Nothing } private void setImageResource(Drawable mDrawable) { if(mDrawable.getIntrinsicHeight() > mDrawable.getIntrinsicWidth()) { editImageDisplay.setLayoutParams(new LayoutParams(width, height)); } else { editImageDisplay.setLayoutParams(new LayoutParams(height, width)); } editImageDisplay.setImageDrawable(mDrawable); } private void startCamera() { if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) { Intent camera = new Intent(this, Camera.class); File file; if(isFromFavorite) { file = fileHelper.getCameraFileLargeFavorite(mFavoriteList.favId); } else { file = fileHelper.getCameraFileLargeEntry(entry.id); } Log.d("camera file path +++++++++++++++++ "+file.toString() ); camera.putExtra(Constants.KEY_FULL_SIZE_IMAGE_PATH, file.toString()); startActivityForResult(camera, PICTURE_RESULT); } else { Toast.makeText(this, "sdcard not available", Toast.LENGTH_LONG).show(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (PICTURE_RESULT == requestCode) { if(Activity.RESULT_OK == resultCode) { isChanged = true; new SaveAndDisplayImage().execute(); } else { isChanged = false; if(!setUnknown) { File mFile; if(isFromFavorite) { mFile = fileHelper.getCameraFileSmallFavorite(mFavoriteList.favId); } else { mFile = fileHelper.getCameraFileSmallEntry(entry.id); } if (mFile.canRead()) { Drawable mDrawable = Drawable.createFromPath(mFile.getPath()); setImageResource(mDrawable); } else { DatabaseAdapter adapter = new DatabaseAdapter(this); adapter.open(); adapter.deleteEntryTableEntryID(entry.id + ""); adapter.close(); } } if(!intentExtras.containsKey(Constants.KEY_IS_COMING_FROM_SHOW_PAGE)) {finish();} } } } private class SaveAndDisplayImage extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { editLoadProgress.setVisibility(View.VISIBLE); editImageDisplay.setVisibility(View.GONE); editDelete.setEnabled(false); editSaveEntry.setEnabled(false); super.onPreExecute(); } @Override protected Void doInBackground(Void... params) { String id; if(isFromFavorite) { id = mFavoriteList.favId; } else { id = entry.id; } new CameraFileSave(CameraActivity.this).resizeImageAndSaveThumbnails(id + "",isFromFavorite); return null; } @Override protected void onPostExecute(Void result) { editLoadProgress.setVisibility(View.GONE); editImageDisplay.setVisibility(View.VISIBLE); File mFile; if(isFromFavorite) { mFile = fileHelper.getCameraFileSmallFavorite(mFavoriteList.favId); } else { mFile = fileHelper.getCameraFileSmallEntry(entry.id); } Drawable mDrawable = Drawable.createFromPath(mFile.getPath()); setImageResource(mDrawable); editDelete.setEnabled(true); editSaveEntry.setEnabled(true); super.onPostExecute(result); } } private void setGraphicsCamera() { editCameraDetails.setVisibility(View.VISIBLE); } private void setClickListeners() { ImageView editImageDisplay = (ImageView) findViewById(R.id.edit_image_display); editImageDisplay.setOnClickListener(this); Button editRetakeButton = (Button) findViewById(R.id.edit_retake_button); editRetakeButton.setOnClickListener(this); } @Override public void onClick(View v) { super.onClick(v); switch (v.getId()) { case R.id.edit_image_display: File mFile = fileHelper.getCameraFileLargeEntry(entry.id); if(mFile.canRead()) { Intent intent = new Intent(this, ImagePreview.class); intent.putExtra(Constants.KEY_ID, entry.id); startActivity(intent); } else { Toast.makeText(this, "no image to preview", Toast.LENGTH_SHORT).show(); } break; case R.id.edit_retake_button: startCamera(); default: break; } } @Override protected void deleteFile() { fileHelper.deleteAllEntryFiles(entry.id); } @Override protected Boolean checkEntryModified() { if(super.checkEntryModified() || isChanged) return true; else return false; } @Override protected boolean doTaskIfChanged() { return isChanged; } @Override protected void setDefaultTitle() { if(isFromFavorite) { ((TextView)findViewById(R.id.header_title)).setText(getString(R.string.edit_favorite)+" "+getString(R.string.finished_cameraentry)); } else { ((TextView)findViewById(R.id.header_title)).setText(getString(R.string.finished_cameraentry)); } } @Override protected boolean checkFavoriteComplete() { if(editAmount != null && !editAmount.getText().toString().equals("")) { return true; } return false; } }
package org.apache.catalina.util; import junit.framework.TestCase; public class TestContextName extends TestCase { private ContextName cn1; private ContextName cn2; private ContextName cn3; private ContextName cn4; private ContextName cn5; private ContextName cn6; private ContextName cn7; private ContextName cn8; private ContextName cn9; private ContextName cn10; private ContextName cn11; private ContextName cn12; private ContextName cn13; private ContextName cn14; private ContextName cn15; private ContextName cn16; @Override protected void setUp() throws Exception { super.setUp(); cn1 = new ContextName(null, null); cn2 = new ContextName("", null); cn3 = new ContextName("/", null); cn4 = new ContextName("/foo", null); cn5 = new ContextName("/foo/bar", null); cn6 = new ContextName(null, "A"); cn7 = new ContextName("", "B"); cn8 = new ContextName("/", "C"); cn9 = new ContextName("/foo", "D"); cn10 = new ContextName("/foo/bar", "E"); cn11 = new ContextName("ROOT"); cn12 = new ContextName("foo"); cn13 = new ContextName("foo#bar"); cn14 = new ContextName("ROOT cn15 = new ContextName("foo cn16 = new ContextName("foo#bar##E"); } public void testGetBaseName() { assertEquals("ROOT", cn1.getBaseName()); assertEquals("ROOT", cn2.getBaseName()); assertEquals("ROOT", cn3.getBaseName()); assertEquals("foo", cn4.getBaseName()); assertEquals("foo#bar", cn5.getBaseName()); assertEquals("ROOT##A", cn6.getBaseName()); assertEquals("ROOT##B", cn7.getBaseName()); assertEquals("ROOT##C", cn8.getBaseName()); assertEquals("foo##D", cn9.getBaseName()); assertEquals("foo#bar##E", cn10.getBaseName()); assertEquals("ROOT", cn11.getBaseName()); assertEquals("foo", cn12.getBaseName()); assertEquals("foo#bar", cn13.getBaseName()); assertEquals("ROOT##A", cn14.getBaseName()); assertEquals("foo##D", cn15.getBaseName()); assertEquals("foo#bar##E", cn16.getBaseName()); } public void testGetPath() { assertEquals("", cn1.getPath()); assertEquals("", cn2.getPath()); assertEquals("", cn3.getPath()); assertEquals("/foo", cn4.getPath()); assertEquals("/foo/bar", cn5.getPath()); assertEquals("", cn6.getPath()); assertEquals("", cn7.getPath()); assertEquals("", cn8.getPath()); assertEquals("/foo", cn9.getPath()); assertEquals("/foo/bar", cn10.getPath()); assertEquals("", cn11.getPath()); assertEquals("/foo", cn12.getPath()); assertEquals("/foo/bar", cn13.getPath()); assertEquals("", cn14.getPath()); assertEquals("/foo", cn15.getPath()); assertEquals("/foo/bar", cn16.getPath()); } public void testGetVersion() { assertEquals("", cn1.getVersion()); assertEquals("", cn2.getVersion()); assertEquals("", cn3.getVersion()); assertEquals("", cn4.getVersion()); assertEquals("", cn5.getVersion()); assertEquals("A", cn6.getVersion()); assertEquals("B", cn7.getVersion()); assertEquals("C", cn8.getVersion()); assertEquals("D", cn9.getVersion()); assertEquals("E", cn10.getVersion()); assertEquals("", cn11.getVersion()); assertEquals("", cn12.getVersion()); assertEquals("", cn13.getVersion()); assertEquals("A", cn14.getVersion()); assertEquals("D", cn15.getVersion()); assertEquals("E", cn16.getVersion()); } public void testGetName() { assertEquals("", cn1.getName()); assertEquals("", cn2.getName()); assertEquals("", cn3.getName()); assertEquals("/foo", cn4.getName()); assertEquals("/foo/bar", cn5.getName()); assertEquals("##A", cn6.getName()); assertEquals("##B", cn7.getName()); assertEquals("##C", cn8.getName()); assertEquals("/foo##D", cn9.getName()); assertEquals("/foo/bar##E", cn10.getName()); assertEquals("", cn11.getName()); assertEquals("/foo", cn12.getName()); assertEquals("/foo/bar", cn13.getName()); assertEquals("##A", cn14.getName()); assertEquals("/foo##D", cn15.getName()); assertEquals("/foo/bar##E", cn16.getName()); } public void testGetDisplayName() { assertEquals("/", cn1.getDisplayName()); assertEquals("/", cn2.getDisplayName()); assertEquals("/", cn3.getDisplayName()); assertEquals("/foo", cn4.getDisplayName()); assertEquals("/foo/bar", cn5.getDisplayName()); assertEquals("/##A", cn6.getDisplayName()); assertEquals("/##B", cn7.getDisplayName()); assertEquals("/##C", cn8.getDisplayName()); assertEquals("/foo##D", cn9.getDisplayName()); assertEquals("/foo/bar##E", cn10.getDisplayName()); assertEquals("/", cn11.getDisplayName()); assertEquals("/foo", cn12.getDisplayName()); assertEquals("/foo/bar", cn13.getDisplayName()); assertEquals("/##A", cn14.getDisplayName()); assertEquals("/foo##D", cn15.getDisplayName()); assertEquals("/foo/bar##E", cn16.getDisplayName()); } public void testConstructorString() { doTestConstructorString(cn1); doTestConstructorString(cn2); doTestConstructorString(cn3); doTestConstructorString(cn4); doTestConstructorString(cn5); doTestConstructorString(cn6); doTestConstructorString(cn7); doTestConstructorString(cn8); doTestConstructorString(cn9); doTestConstructorString(cn10); doTestConstructorString(cn11); doTestConstructorString(cn12); doTestConstructorString(cn13); doTestConstructorString(cn14); doTestConstructorString(cn15); doTestConstructorString(cn16); } private void doTestConstructorString(ContextName src) { doCompare(src, new ContextName(src.getBaseName())); doCompare(src, new ContextName(src.getDisplayName())); doCompare(src, new ContextName(src.getName())); } private void doCompare(ContextName cn1, ContextName cn2) { assertEquals(cn1.getBaseName(), cn2.getBaseName()); assertEquals(cn1.getDisplayName(), cn2.getDisplayName()); assertEquals(cn1.getName(), cn2.getName()); assertEquals(cn1.getPath(), cn2.getPath()); assertEquals(cn1.getVersion(), cn2.getVersion()); } }
package edu.cmu.sphinx.util; import java.io.FileNotFoundException; import java.io.IOException; import java.io.StreamCorruptedException; import java.io.StreamTokenizer; import java.io.FileReader; import java.io.Reader; import java.io.BufferedReader; import java.util.List; import java.util.ArrayList; public class ExtendedStreamTokenizer { private String path; private StreamTokenizer st; private Reader reader; private boolean atEOF = false; private List putbackList; /** * Creates and returns a stream tokenizer that has * been properly configured to parse sphinx3 data * * @param path the source of the data * * @throws FileNotFoundException if a file cannot be found */ public ExtendedStreamTokenizer(String path) throws FileNotFoundException { this(path, false); } /** * Creates and returns a stream tokenizer that has * been properly configured to parse sphinx3 data * * @param path the source of the data * @param eolIsSignificant if true eol is significant * * @throws FileNotFoundException if a file cannot be found */ public ExtendedStreamTokenizer(String path, boolean eolIsSignificant) throws FileNotFoundException { FileReader fileReader = new FileReader(path); reader = new BufferedReader(fileReader); this.path = path; st = new StreamTokenizer(reader); st.resetSyntax(); st.whitespaceChars(0, 32); st.wordChars(33, 127); st.eolIsSignificant(eolIsSignificant); st.commentChar(' putbackList = new ArrayList(); } /** * Closes the tokenizer */ public void close() throws IOException { reader.close(); } /** * Gets the next word from the tokenizer * * @throws StreamCorruptedException if the word does not match * @throws IOException if an error occurs while loading the data */ public String getString() throws StreamCorruptedException, IOException { if (putbackList.size() > 0) { return (String) putbackList.remove(putbackList.size() - 1); } else { st.nextToken(); if (st.ttype == StreamTokenizer.TT_EOF) { atEOF = true; } if (st.ttype != StreamTokenizer.TT_WORD && st.ttype != StreamTokenizer.TT_EOL && st.ttype != StreamTokenizer.TT_EOF) { corrupt("word expected but not found"); } if (st.ttype == StreamTokenizer.TT_EOL || st.ttype == StreamTokenizer.TT_EOF) { return null; } else { return st.sval; } } } /** * Puts a string back, the next get will return this string * * @param string the string to unget */ public void unget(String string) { putbackList.add(string); } /** * Determines if the stream is at the end of file * * @return true if the stream is at EOF */ public boolean isEOF() { return atEOF; } /** * Throws an error with the line and path added * * @param msg the annotation message */ private void corrupt(String msg) throws StreamCorruptedException { throw new StreamCorruptedException( msg + " at line " + st.lineno() + " in file " + path); } /** * Gets the current line number * * @return the line number */ public int getLineNumber() { return st.lineno(); } /** * Loads a word from the tokenizer and ensures that it * matches 'expecting' * * @param expecting the word read must match this * * @throws StreamCorruptedException if the word does not match * @throws IOException if an error occurs while loading the data */ public void expectString(String expecting) throws StreamCorruptedException, IOException { if (!getString().equals(expecting)) { corrupt("matching " + expecting); } } /** * Loads an integer from the tokenizer and ensures that it * matches 'expecting' * * @param name the name of the value * @param expecting the word read must match this * * @throws StreamCorruptedException if the word does not match * @throws IOException if an error occurs while loading the data */ public void expectInt(String name, int expecting) throws StreamCorruptedException, IOException { int val = getInt( name); if (val != expecting) { corrupt("Expecting integer " + expecting); } } /** * gets an integer from the tokenizer stream * * @param name the name of the parameter (for error reporting) * * @return the next word in the stream as an integer * * @throws StreamCorruptedException if the next value is not a * @throws IOException if an error occurs while loading the data * number */ public int getInt(String name) throws StreamCorruptedException, IOException { int iVal = 0; try { String val = getString(); iVal = Integer.parseInt(val); } catch (NumberFormatException nfe) { corrupt("while parsing int " + name); } return iVal; } /** * gets a double from the tokenizer stream * * @param name the name of the parameter (for error reporting) * * @return the next word in the stream as a double * * @throws StreamCorruptedException if the next value is not a * @throws IOException if an error occurs while loading the data * number */ public double getDouble(String name) throws StreamCorruptedException, IOException { double dVal = 0.0; try { String val = getString(); if (val.equals("inf")) { dVal = Double.POSITIVE_INFINITY; } else { dVal = Double.parseDouble(val); } } catch (NumberFormatException nfe) { corrupt("while parsing double " + name); } return dVal; } /** * gets a float from the tokenizer stream * * @param name the name of the parameter (for error reporting) * * @return the next word in the stream as a float * * @throws StreamCorruptedException if the next value is not a * @throws IOException if an error occurs while loading the data * number */ public float getFloat(String name) throws StreamCorruptedException, IOException { float fVal = 0.0F; try { String val = getString(); if (val.equals("inf")) { fVal = Float.POSITIVE_INFINITY; } else { fVal = Float.parseFloat(val); } } catch (NumberFormatException nfe) { corrupt("while parsing float " + name); } return fVal; } }
package pt.fccn.arquivo.pages; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.NoSuchElementException; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxBinary; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; /** * @author Hugo Viana * * *Functionality: * inspecting Arcproxy are proper performed, which meaning that all links are well linked. * Configuration file with index linked located on ROOT with monitored_indexes name * This test was made taking in consideration that p41 is the pre-prodution server and p58 and p62 is the prodution environment */ /** * @author nutchwax * */ public class Arcproxyinspection { private final WebDriver driver; private String filename_prod= "monitored_indexes"; // files which contains webepage to be fetch for prodution private String filename_pre_prod= "monitored_indexes_pre_prod"; //files which contains webepage to be fetch for pre-prodution private String broker_p58 ="p58."; private String broker_p62 ="p62."; private List<String> DateList = new ArrayList<String>(); private boolean isPredProd=false; /** * Create a new Arcproxy navigation * @param driver */ public Arcproxyinspection(WebDriver driver, boolean isPredProd){ this.driver= driver; this.isPredProd=isPredProd; } /** * The file monitered_index contains syntax with DocID and the standard wayback syntax * @param inspectDate - If it is wayback syntax compare date, if not just navigate over index * @return */ public boolean inspectArcproxy(boolean inspectDate) { BufferedReader reader=null; String id=null; String[] Url = driver.getCurrentUrl().split("/index.jsp"); String title_p58=null; String date_p58=null; String title_p62=null; String date_p62=null; //to test for a new server different than p58 or p62 if (this.isPredProd){ this.broker_p58 =""; this.broker_p62 =""; } int i =0; boolean result=true; try { if (!this.isPredProd){ reader = new BufferedReader(new FileReader(filename_prod)); } else{ reader = new BufferedReader(new FileReader(filename_pre_prod)); } while ((id = reader.readLine()) != null) { if(!inspectDate ){ title_p58=getIdTitle(broker_p58, id,Url); date_p58=getIdDate(broker_p58,id); DateList.add(date_p58); //Contains every dates of web content fetched from the file title_p62=getIdTitle(broker_p62, id,Url); date_p62=getIdDate(broker_p62,id); if (date_p58 !=null && date_p62 !=null && !isPredProd){ //If occurs same pages with different titles or dates if (!date_p58.equals(date_p62) && !title_p58.equals(title_p62)){ System.out.print("Inconsistence collection: "+ id +""); reader.close(); result = false; throw new IllegalStateException("Inconsistence collection: "+ id +""); } //If the collection is offline if (date_p58 ==null || date_p62==null){ System.out.print("Offline collection: "+ id +""); reader.close(); result = false; throw new IllegalStateException("The collection which contains " +id+ "is offline"); } else result = true; } } else { result =inspectDate(id,i); } i++; } reader.close(); } //Problems opening the file monitored_indexes catch (IOException e) { System.out.print(reader +" :"+this.getClass().getName()+"\nThere was problems opening configuration "); return false; } return result; } /** * @param server - must contain server p58. or p62. * @param id - index id * @param Url - Driver URL * @return */ private String getIdTitle (String server, String id,String[] Url){ WebDriverWait wait = new WebDriverWait(driver, 15); if (!this.isPredProd){ driver.get(server+Url[0].substring(7)+"wayback/"+id); } else{ driver.get(Url[0].substring(7)+"wayback/"+id); } //wait until title was loaded wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("title"))); return driver.getTitle(); } /** * @param server - must contains server either p58. or p62. * @param id * @return */ private String getIdDate (String server, String id){ WebElement replay_bar_with_date =null; String date=null; //This could happen when a page is offline, in that case it can not find the replay_bar with the date try { /** * Inspects if the date is accordingly with the date on the replay bar * @param id * @param i * @return */ private boolean inspectDate (String id, int i){ String server=null; server = DateList.get(i); String[] timestamp_site= null; timestamp_site= id.split("/"); if (timestamp_site[0].contains("id")) // This syntax does not contain timestamp return true; try { //date = format.parse(server); //timestamp_file = format_arquivo.format(date).trim(); if (!(server.compareTo(timestamp_site[0].trim())==0)){ // testing timespan equality System.out.print("\nDate problems on:"+id+"\nDate: "+server+"\nDate timestamp:"+timestamp_site[0]+"\n"); } } catch (Exception e) { System.out.print("\n\nProblems parsing date of the website "+id+"\n"+this.getClass()); e.printStackTrace(); return false; } return true; } }
package de.gurkenlabs.utiliti.components; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Stroke; import java.awt.event.AdjustmentEvent; import java.awt.event.AdjustmentListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.geom.Path2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.Consumer; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; import de.gurkenlabs.core.Align; import de.gurkenlabs.core.Valign; import de.gurkenlabs.litiengine.Game; import de.gurkenlabs.litiengine.Resources; import de.gurkenlabs.litiengine.SpriteSheetInfo; import de.gurkenlabs.litiengine.entities.CollisionEntity; import de.gurkenlabs.litiengine.entities.DecorMob.MovementBehavior; import de.gurkenlabs.litiengine.environment.Environment; import de.gurkenlabs.litiengine.environment.tilemap.IImageLayer; import de.gurkenlabs.litiengine.environment.tilemap.IMap; import de.gurkenlabs.litiengine.environment.tilemap.IMapLoader; import de.gurkenlabs.litiengine.environment.tilemap.IMapObject; import de.gurkenlabs.litiengine.environment.tilemap.IMapObjectLayer; import de.gurkenlabs.litiengine.environment.tilemap.ITileset; import de.gurkenlabs.litiengine.environment.tilemap.MapObjectProperty; import de.gurkenlabs.litiengine.environment.tilemap.MapObjectType; import de.gurkenlabs.litiengine.environment.tilemap.MapUtilities; import de.gurkenlabs.litiengine.environment.tilemap.TmxMapLoader; import de.gurkenlabs.litiengine.environment.tilemap.xml.Map; import de.gurkenlabs.litiengine.environment.tilemap.xml.MapObject; import de.gurkenlabs.litiengine.environment.tilemap.xml.MapObjectLayer; import de.gurkenlabs.litiengine.graphics.ImageCache; import de.gurkenlabs.litiengine.graphics.LightSource; import de.gurkenlabs.litiengine.graphics.RenderEngine; import de.gurkenlabs.litiengine.graphics.Spritesheet; import de.gurkenlabs.litiengine.gui.GuiComponent; import de.gurkenlabs.litiengine.input.Input; import de.gurkenlabs.util.MathUtilities; import de.gurkenlabs.util.geom.GeometricUtilities; import de.gurkenlabs.util.io.FileUtilities; import de.gurkenlabs.util.io.ImageSerializer; import de.gurkenlabs.utiliti.EditorScreen; import de.gurkenlabs.utiliti.Program; import de.gurkenlabs.utiliti.UndoManager; public class MapComponent extends EditorComponent { public enum TransformType { UP, DOWN, LEFT, RIGHT, UPLEFT, UPRIGHT, DOWNLEFT, DOWNRIGHT, NONE } private static final String DEFAULT_MAPOBJECTLAYER_NAME = "default"; private static final int TRANSFORM_RECT_SIZE = 6; private static final int BASE_SCROLL_SPEED = 50; private double currentTransformRectSize = TRANSFORM_RECT_SIZE; private final java.util.Map<TransformType, Rectangle2D> transformRects; private TransformType currentTransform; public static final int EDITMODE_CREATE = 0; public static final int EDITMODE_EDIT = 1; public static final int EDITMODE_MOVE = 2; private final List<Consumer<Integer>> editModeChangedConsumer; private final List<Consumer<IMapObject>> focusChangedConsumer; private final List<Consumer<Map>> mapLoadedConsumer; private int currentEditMode = EDITMODE_EDIT; private static final float[] zooms = new float[] { 0.1f, 0.25f, 0.5f, 1, 1.5f, 2f, 3f, 4f, 5f, 6f, 7f, 8f, 9f, 10f, 16f, 32f, 50f, 80f, 100f }; private int currentZoomIndex = 7; private final java.util.Map<String, Point2D> cameraFocus; private final java.util.Map<String, IMapObject> focusedObjects; private final List<Map> maps; private float scrollSpeed = BASE_SCROLL_SPEED; private Point2D startPoint; private Point2D dragPoint; private Point2D dragLocationMapObject; private boolean isMoving; private boolean isTransforming; private Dimension dragSizeMapObject; private Rectangle2D newObject; private IMapObject copiedMapObject; private int gridSize; public boolean snapToGrid = true; public boolean renderGrid = false; public boolean renderCollisionBoxes = true; private final EditorScreen screen; private boolean isLoading; public MapComponent(final EditorScreen screen) { super(ComponentType.MAP); this.editModeChangedConsumer = new CopyOnWriteArrayList<>(); this.focusChangedConsumer = new CopyOnWriteArrayList<>(); this.mapLoadedConsumer = new CopyOnWriteArrayList<>(); this.focusedObjects = new ConcurrentHashMap<>(); this.maps = new ArrayList<>(); this.cameraFocus = new ConcurrentHashMap<>(); this.transformRects = new ConcurrentHashMap<>(); this.screen = screen; Game.getCamera().onZoomChanged(zoom -> { this.currentTransformRectSize = TRANSFORM_RECT_SIZE / zoom; this.updateTransformControls(); }); this.gridSize = Program.USER_PREFERNCES.getGridSize(); } public void onEditModeChanged(Consumer<Integer> cons) { this.editModeChangedConsumer.add(cons); } public void onFocusChanged(Consumer<IMapObject> cons) { this.focusChangedConsumer.add(cons); } public void onMapLoaded(Consumer<Map> cons) { this.mapLoadedConsumer.add(cons); } @Override public void render(Graphics2D g) { if (Game.getEnvironment() == null) { return; } Color COLOR_BOUNDING_BOX_FILL = new Color(0, 0, 0, 35); Color COLOR_NAME_FILL = new Color(0, 0, 0, 60); final Color COLOR_FOCUS_FILL = new Color(0, 0, 0, 50); final Color COLOR_FOCUS_BORDER = Color.BLACK; final Color COLOR_COLLISION_FILL = new Color(255, 0, 0, 15); final Color COLOR_NOCOLLISION_FILL = new Color(255, 100, 0, 15); final Color COLOR_COLLISION_BORDER = Color.RED; final Color COLOR_NOCOLLISION_BORDER = Color.ORANGE; final Color COLOR_SPAWNPOINT = Color.GREEN; final Color COLOR_LANE = Color.YELLOW; final Color COLOR_NEWOBJECT_FILL = new Color(0, 255, 0, 50); final Color COLOR_NEWOBJECT_BORDER = Color.GREEN.darker(); final Color COLOR_TRANSFORM_RECT_FILL = new Color(255, 255, 255, 100); final Color COLOR_SHADOW_FILL = new Color(85, 130, 200, 15); final Color COLOR_SHADOW_BORDER = new Color(30, 85, 170); final BasicStroke shapeStroke = new BasicStroke(1 / Game.getCamera().getRenderScale()); if (this.renderCollisionBoxes) { // render all entities for (final IMapObjectLayer layer : Game.getEnvironment().getMap().getMapObjectLayers()) { if (layer == null) { continue; } if (!EditorScreen.instance().getMapSelectionPanel().isSelectedMapObjectLayer(layer.getName())) { continue; } if (layer.getColor() != null) { COLOR_BOUNDING_BOX_FILL = new Color(layer.getColor().getRed(), layer.getColor().getGreen(), layer.getColor().getBlue(), 15); } else { COLOR_BOUNDING_BOX_FILL = new Color(0, 0, 0, 35); } for (final IMapObject mapObject : layer.getMapObjects()) { if (mapObject == null) { continue; } String objectName = mapObject.getName(); if (objectName != null && !objectName.isEmpty()) { Rectangle2D nameBackground = new Rectangle2D.Double(mapObject.getX(), mapObject.getBoundingBox().getMaxY() - 3, mapObject.getDimension().getWidth(), 3); g.setColor(COLOR_NAME_FILL); RenderEngine.fillShape(g, nameBackground); } MapObjectType type = MapObjectType.get(mapObject.getType()); // render spawn points if (type == MapObjectType.SPAWNPOINT) { g.setColor(COLOR_SPAWNPOINT); RenderEngine.fillShape(g, new Rectangle2D.Double(mapObject.getBoundingBox().getCenterX() - 1, mapObject.getBoundingBox().getCenterY() - 1, 2, 2)); RenderEngine.drawShape(g, mapObject.getBoundingBox(), shapeStroke); } else if (type == MapObjectType.COLLISIONBOX) { g.setColor(COLOR_COLLISION_FILL); RenderEngine.fillShape(g, mapObject.getBoundingBox()); g.setColor(COLOR_COLLISION_BORDER); RenderEngine.drawShape(g, mapObject.getBoundingBox(), shapeStroke); } else if (type == MapObjectType.STATICSHADOW) { g.setColor(COLOR_SHADOW_FILL); RenderEngine.fillShape(g, mapObject.getBoundingBox()); g.setColor(COLOR_SHADOW_BORDER); RenderEngine.drawShape(g, mapObject.getBoundingBox(), shapeStroke); } else if (type == MapObjectType.LANE) { // render lane if (mapObject.getPolyline() == null || mapObject.getPolyline().getPoints().size() == 0) { continue; } // found the path for the rat final Path2D path = MapUtilities.convertPolylineToPath(mapObject); if (path == null) { continue; } g.setColor(COLOR_LANE); RenderEngine.drawShape(g, path, shapeStroke); Point2D start = new Point2D.Double(mapObject.getLocation().getX(), mapObject.getLocation().getY()); RenderEngine.fillShape(g, new Ellipse2D.Double(start.getX() - 1, start.getY() - 1, 3, 3)); RenderEngine.drawMapText(g, "#" + mapObject.getId() + "(" + mapObject.getName() + ")", start.getX(), start.getY() - 5); } // render bounding boxes final IMapObject focusedMapObject = this.getFocusedMapObject(); if (focusedMapObject == null || mapObject.getId() != focusedMapObject.getId()) { g.setColor(COLOR_BOUNDING_BOX_FILL); // don't fill rect for lightsource because it is important to judge // the color if (type != MapObjectType.LIGHTSOURCE) { if (type == MapObjectType.TRIGGER) { g.setColor(COLOR_NOCOLLISION_FILL); } RenderEngine.fillShape(g, mapObject.getBoundingBox()); } if (type == MapObjectType.TRIGGER) { g.setColor(COLOR_NOCOLLISION_BORDER); } RenderEngine.drawShape(g, mapObject.getBoundingBox(), shapeStroke); } // render collision boxes String coll = mapObject.getCustomProperty(MapObjectProperty.COLLISION); final String collisionBoxWidthFactor = mapObject.getCustomProperty(MapObjectProperty.COLLISIONBOXWIDTH); final String collisionBoxHeightFactor = mapObject.getCustomProperty(MapObjectProperty.COLLISIONBOXHEIGHT); final Align align = Align.get(mapObject.getCustomProperty(MapObjectProperty.COLLISIONALGIN)); final Valign valign = Valign.get(mapObject.getCustomProperty(MapObjectProperty.COLLISIONVALGIN)); if (coll != null && collisionBoxWidthFactor != null && collisionBoxHeightFactor != null) { boolean collision = Boolean.valueOf(coll); final Color collisionColor = collision ? COLOR_COLLISION_FILL : COLOR_NOCOLLISION_FILL; final Color collisionShapeColor = collision ? COLOR_COLLISION_BORDER : COLOR_NOCOLLISION_BORDER; float collisionBoxWidth = 0, collisionBoxHeight = 0; try { collisionBoxWidth = Float.parseFloat(collisionBoxWidthFactor); collisionBoxHeight = Float.parseFloat(collisionBoxHeightFactor); } catch (NumberFormatException | NullPointerException e) { e.printStackTrace(); } g.setColor(collisionColor); Rectangle2D collisionBox = CollisionEntity.getCollisionBox(mapObject.getLocation(), mapObject.getDimension().getWidth(), mapObject.getDimension().getHeight(), collisionBoxWidth, collisionBoxHeight, align, valign); RenderEngine.fillShape(g, collisionBox); g.setColor(collisionShapeColor); RenderEngine.drawShape(g, collisionBox, shapeStroke); } g.setColor(Color.WHITE); float textSize = 3 * zooms[this.currentZoomIndex]; g.setFont(Program.TEXT_FONT.deriveFont(textSize)); RenderEngine.drawMapText(g, objectName, mapObject.getX() + 1, mapObject.getBoundingBox().getMaxY()); } } } switch (this.currentEditMode) { case EDITMODE_CREATE: if (newObject != null) { g.setColor(COLOR_NEWOBJECT_FILL); RenderEngine.fillShape(g, newObject); g.setColor(COLOR_NEWOBJECT_BORDER); RenderEngine.drawShape(g, newObject, shapeStroke); g.setFont(g.getFont().deriveFont(Font.BOLD)); RenderEngine.drawMapText(g, newObject.getWidth() + "", newObject.getX() + newObject.getWidth() / 2 - 3, newObject.getY() - 5); RenderEngine.drawMapText(g, newObject.getHeight() + "", newObject.getX() - 10, newObject.getY() + newObject.getHeight() / 2); } break; case EDITMODE_EDIT: // draw selection final Point2D start = this.startPoint; if (start != null && !Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { final Rectangle2D rect = this.getCurrentMouseSelectionArea(); g.setColor(new Color(0, 130, 152, 30)); RenderEngine.fillShape(g, rect); if (rect.getWidth() > 0 || rect.getHeight() > 0) { g.setColor(new Color(0, 130, 152, 255)); g.setFont(g.getFont().deriveFont(Font.BOLD)); RenderEngine.drawMapText(g, rect.getWidth() + "", rect.getX() + rect.getWidth() / 2 - 3, rect.getY() - 5); RenderEngine.drawMapText(g, rect.getHeight() + "", rect.getX() - 10, rect.getY() + rect.getHeight() / 2); } g.setColor(new Color(0, 130, 152, 150)); RenderEngine.drawShape(g, rect, new BasicStroke(2 / Game.getCamera().getRenderScale(), BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[] { 1 }, 0)); } break; } // render the focus and the transform rects final Rectangle2D focus = this.getFocus(); final IMapObject focusedMapObject = this.getFocusedMapObject(); if (focus != null && focusedMapObject != null) { Stroke stroke = new BasicStroke(2 / Game.getCamera().getRenderScale(), BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[] { 1f }, 0); if (MapObjectType.get(focusedMapObject.getType()) != MapObjectType.LIGHTSOURCE) { g.setColor(COLOR_FOCUS_FILL); RenderEngine.fillShape(g, focus); } g.setColor(COLOR_FOCUS_BORDER); RenderEngine.drawShape(g, focus, stroke); // render transform rects if (!Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { Stroke transStroke = new BasicStroke(1 / Game.getCamera().getRenderScale()); for (Rectangle2D trans : this.transformRects.values()) { g.setColor(COLOR_TRANSFORM_RECT_FILL); RenderEngine.fillShape(g, trans); g.setColor(COLOR_FOCUS_BORDER); RenderEngine.drawShape(g, trans, transStroke); } } } if (focusedMapObject != null) { Point2D loc = Game.getCamera() .getViewPortLocation(new Point2D.Double(focusedMapObject.getX() + focusedMapObject.getDimension().getWidth() / 2, focusedMapObject.getY())); g.setFont(Program.TEXT_FONT.deriveFont(Font.BOLD, 15f)); g.setColor(COLOR_FOCUS_BORDER); String id = "#" + focusedMapObject.getId(); RenderEngine.drawText(g, id, loc.getX() * Game.getCamera().getRenderScale() - g.getFontMetrics().stringWidth(id) / 2, loc.getY() * Game.getCamera().getRenderScale() - (5 * this.currentTransformRectSize)); if (MapObjectType.get(focusedMapObject.getType()) == MapObjectType.TRIGGER) { g.setColor(COLOR_NOCOLLISION_BORDER); g.setFont(Program.TEXT_FONT.deriveFont(11f)); RenderEngine.drawMapText(g, focusedMapObject.getName(), focusedMapObject.getX() + 2, focusedMapObject.getY() + 5); } } // render the grid if (this.renderGrid && Game.getCamera().getRenderScale() >= 1) { g.setColor(new Color(255, 255, 255, 100)); final Stroke stroke = new BasicStroke(1 / Game.getCamera().getRenderScale()); final double viewPortX = Math.max(0, Game.getCamera().getViewPort().getX()); final double viewPortMaxX = Math.min(Game.getEnvironment().getMap().getSizeInPixels().getWidth(), Game.getCamera().getViewPort().getMaxX()); final double viewPortY = Math.max(0, Game.getCamera().getViewPort().getY()); final double viewPortMaxY = Math.min(Game.getEnvironment().getMap().getSizeInPixels().getHeight(), Game.getCamera().getViewPort().getMaxY()); final int startX = Math.max(0, (int) (viewPortX / gridSize) * gridSize); final int startY = Math.max(0, (int) (viewPortY / gridSize) * gridSize); for (int x = startX; x <= viewPortMaxX; x += gridSize) { RenderEngine.drawShape(g, new Line2D.Double(x, viewPortY, x, viewPortMaxY), stroke); } for (int y = startY; y <= viewPortMaxY; y += gridSize) { RenderEngine.drawShape(g, new Line2D.Double(viewPortX, y, viewPortMaxX, y), stroke); } } super.render(g); } public void loadMaps(String projectPath) { final List<String> files = FileUtilities.findFiles(new ArrayList<>(), Paths.get(projectPath), "tmx"); System.out.println(files.size() + " maps found in folder " + projectPath); final List<Map> maps = new ArrayList<>(); for (final String mapFile : files) { final IMapLoader tmxLoader = new TmxMapLoader(); Map map = (Map) tmxLoader.loadMap(mapFile); maps.add(map); System.out.println("map found: " + map.getFileName()); } this.loadMaps(maps); } public void loadMaps(List<Map> maps) { EditorScreen.instance().getMapObjectPanel().bind(null); this.setFocus(null); this.getMaps().clear(); maps.sort(new Comparator<Map>() { @Override public int compare(Map arg0, Map arg1) { return arg0.getName().compareTo(arg1.getName()); } }); this.getMaps().addAll(maps); EditorScreen.instance().getMapSelectionPanel().bind(this.getMaps()); } public List<Map> getMaps() { return this.maps; } public int getGridSize() { return this.gridSize; } @Override public void prepare() { Game.getCamera().setZoom(zooms[this.currentZoomIndex], 0); Program.horizontalScroll.addAdjustmentListener(new AdjustmentListener() { @Override public void adjustmentValueChanged(AdjustmentEvent e) { if (isLoading) { return; } Point2D cameraFocus = new Point2D.Double(Program.horizontalScroll.getValue(), Game.getCamera().getFocus().getY()); Game.getCamera().setFocus(cameraFocus); } }); Program.verticalScroll.addAdjustmentListener(new AdjustmentListener() { @Override public void adjustmentValueChanged(AdjustmentEvent e) { if (isLoading) { return; } Point2D cameraFocus = new Point2D.Double(Game.getCamera().getFocus().getX(), Program.verticalScroll.getValue()); Game.getCamera().setFocus(cameraFocus); } }); Game.getScreenManager().getRenderComponent().addFocusListener(new FocusListener() { @Override public void focusLost(FocusEvent e) { startPoint = null; } @Override public void focusGained(FocusEvent e) { } }); this.setupControls(); super.prepare(); this.onMouseMoved(e -> { if (this.getFocus() == null) { Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR, 0, 0); currentTransform = TransformType.NONE; return; } boolean hovered = false; if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { return; } for (TransformType type : this.transformRects.keySet()) { Rectangle2D rect = this.transformRects.get(type); Rectangle2D hoverrect = new Rectangle2D.Double(rect.getX() - rect.getWidth() * 2, rect.getY() - rect.getHeight() * 2, rect.getWidth() * 4, rect.getHeight() * 4); if (hoverrect.contains(Input.mouse().getMapLocation())) { hovered = true; if (type == TransformType.DOWN || type == TransformType.UP) { Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_TRANS_VERTICAL, 0, 0); } else if (type == TransformType.UPLEFT || type == TransformType.DOWNRIGHT) { Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_TRANS_DIAGONAL_LEFT, 0, 0); } else if (type == TransformType.UPRIGHT || type == TransformType.DOWNLEFT) { Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_TRANS_DIAGONAL_RIGHT, 0, 0); } else { Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_TRANS_HORIZONTAL, 0, 0); } currentTransform = type; break; } } if (!hovered) { Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR, 0, 0); currentTransform = TransformType.NONE; } }); this.onMousePressed(e -> { if (!this.hasFocus()) { return; } switch (this.currentEditMode) { case EDITMODE_CREATE: this.startPoint = Input.mouse().getMapLocation(); break; case EDITMODE_MOVE: break; case EDITMODE_EDIT: if (this.isMoving || this.currentTransform != TransformType.NONE) { return; } final Point2D mouse = Input.mouse().getMapLocation(); this.startPoint = mouse; boolean somethingIsFocused = false; boolean currentObjectFocused = false; for (IMapObjectLayer layer : Game.getEnvironment().getMap().getMapObjectLayers()) { if (layer == null) { continue; } if (somethingIsFocused) { break; } if (!EditorScreen.instance().getMapSelectionPanel().isSelectedMapObjectLayer(layer.getName())) { continue; } for (IMapObject mapObject : layer.getMapObjects()) { if (mapObject == null) { continue; } MapObjectType type = MapObjectType.get(mapObject.getType()); if (type == MapObjectType.LANE) { continue; } if (mapObject.getBoundingBox().contains(mouse)) { if (this.getFocusedMapObject() != null && mapObject.getId() == this.getFocusedMapObject().getId()) { currentObjectFocused = true; continue; } this.setFocus(mapObject); EditorScreen.instance().getMapObjectPanel().bind(mapObject); somethingIsFocused = true; break; } } } if (!somethingIsFocused && !currentObjectFocused) { this.setFocus(null); EditorScreen.instance().getMapObjectPanel().bind(null); } break; } }); this.onMouseDragged(e -> { if (!this.hasFocus()) { return; } switch (this.currentEditMode) { case EDITMODE_CREATE: if (startPoint == null) { return; } newObject = this.getCurrentMouseSelectionArea(); break; case EDITMODE_EDIT: if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { if (!this.isMoving) { this.isMoving = true; UndoManager.instance().mapObjectChanging(this.getFocusedMapObject()); } this.handleEntityDrag(); return; } else if (this.currentTransform != TransformType.NONE) { if (!this.isTransforming) { this.isTransforming = true; UndoManager.instance().mapObjectChanging(this.getFocusedMapObject()); } this.handleTransform(); return; } break; case EDITMODE_MOVE: if (!this.isMoving) { this.isMoving = true; UndoManager.instance().mapObjectChanging(this.getFocusedMapObject()); } this.handleEntityDrag(); break; } }); this.onMouseReleased(e -> { if (!this.hasFocus()) { return; } this.dragPoint = null; this.dragLocationMapObject = null; this.dragSizeMapObject = null; switch (this.currentEditMode) { case EDITMODE_CREATE: if (this.newObject == null) { break; } IMapObject mo = this.createNewMapObject(EditorScreen.instance().getMapObjectPanel().getObjectType()); this.newObject = null; this.setFocus(mo); EditorScreen.instance().getMapObjectPanel().bind(mo); this.setEditMode(EDITMODE_EDIT); break; case EDITMODE_MOVE: if (this.isMoving) { this.isMoving = false; UndoManager.instance().mapObjectChanged(this.getFocusedMapObject()); } break; case EDITMODE_EDIT: if (this.isMoving || this.isTransforming) { this.isMoving = false; this.isTransforming = false; UndoManager.instance().mapObjectChanged(this.getFocusedMapObject()); } if (this.startPoint == null) { return; } Rectangle2D rect = this.getCurrentMouseSelectionArea(); if (rect.getHeight() > 0 && rect.getWidth() > 0) { boolean somethingIsFocused = false; for (IMapObjectLayer layer : Game.getEnvironment().getMap().getMapObjectLayers()) { if (layer == null) { continue; } if (!EditorScreen.instance().getMapSelectionPanel().isSelectedMapObjectLayer(layer.getName())) { continue; } for (IMapObject mapObject : layer.getMapObjects()) { if (mapObject == null) { continue; } MapObjectType type = MapObjectType.get(mapObject.getType()); if (type == MapObjectType.LANE) { continue; } if (!GeometricUtilities.intersects(rect, mapObject.getBoundingBox())) { continue; } this.setFocus(mapObject); if (mapObject.equals(this.getFocusedMapObject())) { somethingIsFocused = true; continue; } EditorScreen.instance().getMapObjectPanel().bind(mapObject); somethingIsFocused = true; break; } } if (!somethingIsFocused) { this.setFocus(null); EditorScreen.instance().getMapObjectPanel().bind(null); } } break; } this.startPoint = null; }); } public void loadEnvironment(Map map) { this.isLoading = true; try { if (Game.getEnvironment() != null && Game.getEnvironment().getMap() != null) { double x = Game.getCamera().getFocus().getX(); double y = Game.getCamera().getFocus().getY(); Point2D newPoint = new Point2D.Double(x, y); this.cameraFocus.put(Game.getEnvironment().getMap().getFileName(), newPoint); } Point2D newFocus = null; if (this.cameraFocus.containsKey(map.getFileName())) { newFocus = this.cameraFocus.get(map.getFileName()); } else { newFocus = new Point2D.Double(map.getSizeInPixels().getWidth() / 2, map.getSizeInPixels().getHeight() / 2); this.cameraFocus.put(map.getFileName(), newFocus); } Game.getCamera().setFocus(new Point2D.Double(newFocus.getX(), newFocus.getY())); this.ensureUniqueIds(map); Environment env = new Environment(map); env.init(); Game.loadEnvironment(env); this.updateScrollBars(); EditorScreen.instance().getMapSelectionPanel().setSelection(map.getFileName()); EditorScreen.instance().getMapObjectPanel().bind(this.getFocusedMapObject()); for (Consumer<Map> cons : this.mapLoadedConsumer) { cons.accept(map); } } finally { this.isLoading = false; } } public void add(IMapObject mapObject, IMapObjectLayer layer) { layer.addMapObject(mapObject); Game.getEnvironment().loadFromMap(mapObject.getId()); if (MapObjectType.get(mapObject.getType()) == MapObjectType.LIGHTSOURCE) { Game.getEnvironment().getAmbientLight().createImage(); } this.setFocus(mapObject); EditorScreen.instance().getMapObjectPanel().bind(mapObject); this.setEditMode(EDITMODE_EDIT); } public void copy() { this.copiedMapObject = this.getFocusedMapObject(); } public void paste() { if (this.copiedMapObject != null) { int x = (int) Input.mouse().getMapLocation().getX(); int y = (int) Input.mouse().getMapLocation().getY(); this.newObject = new Rectangle(x, y, (int) this.copiedMapObject.getDimension().getWidth(), (int) this.copiedMapObject.getDimension().getHeight()); this.copyMapObject(this.copiedMapObject); } } public void cut() { this.copiedMapObject = this.getFocusedMapObject(); UndoManager.instance().mapObjectDeleting(this.getFocusedMapObject()); this.delete(this.getFocusedMapObject()); } public void delete() { if (this.getFocusedMapObject() == null) { return; } int n = JOptionPane.showConfirmDialog( null, "Do you really want to delete the entity [" + this.getFocusedMapObject().getId() + "]", "Delete Entity?", JOptionPane.YES_NO_OPTION); if (n == JOptionPane.OK_OPTION) { UndoManager.instance().mapObjectDeleting(this.getFocusedMapObject()); this.delete(this.getFocusedMapObject()); } } public void delete(final IMapObject mapObject) { if (mapObject == null) { return; } MapObjectType type = MapObjectType.valueOf(mapObject.getType()); Game.getEnvironment().getMap().removeMapObject(mapObject.getId()); Game.getEnvironment().remove(mapObject.getId()); if (type == MapObjectType.STATICSHADOW || type == MapObjectType.LIGHTSOURCE) { Game.getEnvironment().getAmbientLight().createImage(); } EditorScreen.instance().getMapObjectPanel().bind(null); this.setFocus(null); } public void setEditMode(int editMode) { if (editMode == this.currentEditMode) { return; } switch (editMode) { case EDITMODE_CREATE: this.setFocus(null); EditorScreen.instance().getMapObjectPanel().bind(null); break; case EDITMODE_EDIT: Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR, 0, 0); break; case EDITMODE_MOVE: Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_MOVE, 0, 0); break; } this.currentEditMode = editMode; for (Consumer<Integer> cons : this.editModeChangedConsumer) { cons.accept(this.currentEditMode); } } public void setFocus(IMapObject mapObject) { if (mapObject != null && mapObject.equals(this.getFocusedMapObject()) || mapObject == null && this.getFocusedMapObject() == null) { return; } if (Game.getEnvironment() == null || Game.getEnvironment().getMap() == null) { return; } if (this.isMoving || this.isTransforming) { return; } if (mapObject == null) { this.focusedObjects.remove(Game.getEnvironment().getMap().getFileName()); } else { this.focusedObjects.put(Game.getEnvironment().getMap().getFileName(), mapObject); } for (Consumer<IMapObject> cons : this.focusChangedConsumer) { cons.accept(this.getFocusedMapObject()); } this.updateTransformControls(); } public void setGridSize(int gridSize) { Program.USER_PREFERNCES.setGridSize(gridSize); this.gridSize = gridSize; } public void updateTransformControls() { final Rectangle2D focus = this.getFocus(); if (focus == null) { this.transformRects.clear(); return; } for (TransformType trans : TransformType.values()) { if (trans == TransformType.NONE) { continue; } Rectangle2D transRect = new Rectangle2D.Double(this.getTransX(trans, focus), this.getTransY(trans, focus), this.currentTransformRectSize, this.currentTransformRectSize); this.transformRects.put(trans, transRect); } } public void deleteMap() { if (this.getMaps() == null || this.getMaps().size() == 0) { return; } if (Game.getEnvironment() == null && Game.getEnvironment().getMap() == null) { return; } int n = JOptionPane.showConfirmDialog( null, Resources.get("hud_deleteMapMessage") + "\n" + Game.getEnvironment().getMap().getName(), Resources.get("hud_deleteMap"), JOptionPane.YES_NO_OPTION); if (n != JOptionPane.YES_OPTION) { return; } this.getMaps().removeIf(x -> x.getFileName().equals(Game.getEnvironment().getMap().getFileName())); EditorScreen.instance().getMapSelectionPanel().bind(this.getMaps()); if (this.maps.size() > 0) { this.loadEnvironment(this.maps.get(0)); } else { this.loadEnvironment(null); } } public void importMap() { if (this.getMaps() == null) { return; } JFileChooser chooser; try { String defaultPath = EditorScreen.instance().getProjectPath() != null ? EditorScreen.instance().getProjectPath() : new File(".").getCanonicalPath(); chooser = new JFileChooser(defaultPath); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setDialogType(JFileChooser.OPEN_DIALOG); chooser.setDialogTitle("Import Map"); FileFilter filter = new FileNameExtensionFilter("tmx - Tilemap XML", Map.FILE_EXTENSION); chooser.setFileFilter(filter); chooser.addChoosableFileFilter(filter); int result = chooser.showOpenDialog(null); if (result == JFileChooser.APPROVE_OPTION) { final IMapLoader tmxLoader = new TmxMapLoader(); Map map = (Map) tmxLoader.loadMap(chooser.getSelectedFile().toString()); if (map == null) { System.out.println("could not load map from file '" + chooser.getSelectedFile().toString() + "'"); return; } if (map.getMapObjectLayers().size() == 0) { // make sure there's a map object layer on the map because we need one to add any kind of entities MapObjectLayer layer = new MapObjectLayer(); layer.setName(DEFAULT_MAPOBJECTLAYER_NAME); map.addMapObjectLayer(layer); } Optional<Map> current = this.maps.stream().filter(x -> x.getFileName().equals(map.getFileName())).findFirst(); if (current.isPresent()) { int n = JOptionPane.showConfirmDialog( null, "Do you really want to replace the existing map '" + map.getFileName() + "' ?", "Replace Map", JOptionPane.YES_NO_OPTION); if (n == JOptionPane.YES_OPTION) { this.getMaps().remove(current.get()); ImageCache.MAPS.clear(); } else { return; } } this.getMaps().add(map); EditorScreen.instance().getMapSelectionPanel().bind(this.getMaps()); // remove old spritesheets for (ITileset tileSet : map.getTilesets()) { Spritesheet sprite = Spritesheet.find(tileSet.getImage().getSource()); if (sprite != null) { Spritesheet.remove(sprite.getName()); this.screen.getGameFile().getTileSets().removeIf(x -> x.getName().equals(sprite.getName())); } } for (ITileset tileSet : map.getTilesets()) { Spritesheet sprite = Spritesheet.load(tileSet); this.screen.getGameFile().getTileSets().add(new SpriteSheetInfo(sprite)); } for (IImageLayer imageLayer : map.getImageLayers()) { BufferedImage img = RenderEngine.getImage(imageLayer.getImage().getAbsoluteSourcePath(), true); Spritesheet sprite = Spritesheet.load(img, imageLayer.getImage().getSource(), img.getWidth(), img.getHeight()); this.screen.getGameFile().getTileSets().add(new SpriteSheetInfo(sprite)); } this.loadEnvironment(map); System.out.println("imported map '" + map.getFileName() + "'"); } } catch (IOException e1) { e1.printStackTrace(); } } public void exportMap() { if (this.getMaps() == null || this.getMaps().size() == 0) { return; } Map map = (Map) Game.getEnvironment().getMap(); if (map == null) { return; } JFileChooser chooser; try { String source = EditorScreen.instance().getProjectPath(); chooser = new JFileChooser(source != null ? source : new File(".").getCanonicalPath()); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setDialogType(JFileChooser.SAVE_DIALOG); chooser.setDialogTitle("Export Map"); FileFilter filter = new FileNameExtensionFilter("tmx - Tilemap XML", Map.FILE_EXTENSION); chooser.setFileFilter(filter); chooser.addChoosableFileFilter(filter); chooser.setSelectedFile(new File(map.getFileName() + "." + Map.FILE_EXTENSION)); int result = chooser.showSaveDialog(null); if (result == JFileChooser.APPROVE_OPTION) { String newFile = map.save(chooser.getSelectedFile().toString()); // save all tilesets manually because a map has a relative reference to // the tilesets String dir = FileUtilities.getParentDirPath(newFile); for (ITileset tileSet : map.getTilesets()) { ImageSerializer.saveImage(Paths.get(dir, tileSet.getImage().getSource()).toString(), Spritesheet.find(tileSet.getImage().getSource()).getImage()); } System.out.println("exported " + map.getFileName() + " to " + newFile); } } catch (IOException e1) { e1.printStackTrace(); } } public void createNewMap() { } public void zoomIn() { if (this.currentZoomIndex < zooms.length - 1) { this.currentZoomIndex++; } this.setCurrentZoom(); this.updateScrollSpeed(); } public void zoomOut() { if (this.currentZoomIndex > 0) { this.currentZoomIndex } this.setCurrentZoom(); this.updateScrollSpeed(); } private void updateScrollSpeed() { this.scrollSpeed = BASE_SCROLL_SPEED / zooms[this.currentZoomIndex]; } private IMapObject copyMapObject(IMapObject obj) { IMapObject mo = new MapObject(); mo.setType(obj.getType()); mo.setX(this.snapX(this.newObject.getX())); mo.setY(this.snapY(this.newObject.getY())); mo.setWidth((int) obj.getDimension().getWidth()); mo.setHeight((int) obj.getDimension().getHeight()); mo.setId(Game.getEnvironment().getNextMapId()); mo.setName(obj.getName()); mo.setCustomProperties(obj.getAllCustomProperties()); this.add(mo, getCurrentLayer()); UndoManager.instance().mapObjectAdded(mo); return mo; } private void ensureUniqueIds(IMap map) { int maxMapId = MapUtilities.getMaxMapId(map); List<Integer> usedIds = new ArrayList<>(); for (IMapObject obj : map.getMapObjects()) { if (usedIds.contains(obj.getId())) { obj.setId(++maxMapId); } usedIds.add(obj.getId()); } } private static IMapObjectLayer getCurrentLayer() { int layerIndex = EditorScreen.instance().getMapSelectionPanel().getSelectedLayerIndex(); if (layerIndex < 0 || layerIndex >= Game.getEnvironment().getMap().getMapObjectLayers().size()) { layerIndex = 0; } return Game.getEnvironment().getMap().getMapObjectLayers().get(layerIndex); } private IMapObject createNewMapObject(MapObjectType type) { IMapObject mo = new MapObject(); mo.setType(type.toString()); mo.setX((int) this.newObject.getX()); mo.setY((int) this.newObject.getY()); mo.setWidth((int) this.newObject.getWidth()); mo.setHeight((int) this.newObject.getHeight()); mo.setId(Game.getEnvironment().getNextMapId()); mo.setName(""); switch (type) { case PROP: mo.setCustomProperty(MapObjectProperty.COLLISIONBOXWIDTH, (this.newObject.getWidth() * 0.4) + ""); mo.setCustomProperty(MapObjectProperty.COLLISIONBOXHEIGHT, (this.newObject.getHeight() * 0.4) + ""); mo.setCustomProperty(MapObjectProperty.COLLISION, "true"); mo.setCustomProperty(MapObjectProperty.INDESTRUCTIBLE, "false"); mo.setCustomProperty(MapObjectProperty.PROP_ADDSHADOW, "true"); break; case DECORMOB: mo.setCustomProperty(MapObjectProperty.COLLISIONBOXWIDTH, (this.newObject.getWidth() * 0.4) + ""); mo.setCustomProperty(MapObjectProperty.COLLISIONBOXHEIGHT, (this.newObject.getHeight() * 0.4) + ""); mo.setCustomProperty(MapObjectProperty.COLLISION, "false"); mo.setCustomProperty(MapObjectProperty.DECORMOB_VELOCITY, "2"); mo.setCustomProperty(MapObjectProperty.DECORMOB_BEHAVIOUR, MovementBehavior.IDLE.toString()); break; case LIGHTSOURCE: mo.setCustomProperty(MapObjectProperty.LIGHTBRIGHTNESS, "180"); mo.setCustomProperty(MapObjectProperty.LIGHTCOLOR, "#ffffff"); mo.setCustomProperty(MapObjectProperty.LIGHTSHAPE, LightSource.ELLIPSE); mo.setCustomProperty(MapObjectProperty.LIGHTACTIVE, "true"); break; case SPAWNPOINT: default: break; } this.add(mo, getCurrentLayer()); UndoManager.instance().mapObjectAdded(mo); return mo; } private Rectangle2D getCurrentMouseSelectionArea() { final Point2D startPoint = this.startPoint; if (startPoint == null) { return null; } final Point2D endPoint = Input.mouse().getMapLocation(); double minX = this.snapX(Math.min(startPoint.getX(), endPoint.getX())); double maxX = this.snapX(Math.max(startPoint.getX(), endPoint.getX())); double minY = this.snapY(Math.min(startPoint.getY(), endPoint.getY())); double maxY = this.snapY(Math.max(startPoint.getY(), endPoint.getY())); double width = Math.abs(minX - maxX); double height = Math.abs(minY - maxY); return new Rectangle2D.Double(minX, minY, width, height); } private Rectangle2D getFocus() { if (this.getFocusedMapObject() != null) { return this.getFocusedMapObject().getBoundingBox(); } return null; } private IMapObject getFocusedMapObject() { if (Game.getEnvironment() != null && Game.getEnvironment().getMap() != null) { return this.focusedObjects.get(Game.getEnvironment().getMap().getFileName()); } return null; } private double getTransX(TransformType type, Rectangle2D focus) { switch (type) { case DOWN: case UP: return focus.getCenterX() - this.currentTransformRectSize / 2; case LEFT: case DOWNLEFT: case UPLEFT: return focus.getX() - this.currentTransformRectSize; case RIGHT: case DOWNRIGHT: case UPRIGHT: return focus.getMaxX(); default: return 0; } } private double getTransY(TransformType type, Rectangle2D focus) { switch (type) { case DOWN: case DOWNLEFT: case DOWNRIGHT: return focus.getMaxY(); case UP: case UPLEFT: case UPRIGHT: return focus.getY() - this.currentTransformRectSize; case LEFT: case RIGHT: return focus.getCenterY() - this.currentTransformRectSize / 2; default: return 0; } } private void handleTransform() { if (this.getFocusedMapObject() == null || this.currentEditMode != EDITMODE_EDIT || currentTransform == TransformType.NONE) { return; } if (this.dragPoint == null) { this.dragPoint = Input.mouse().getMapLocation(); this.dragLocationMapObject = new Point2D.Double(this.getFocusedMapObject().getX(), this.getFocusedMapObject().getY()); this.dragSizeMapObject = new Dimension(this.getFocusedMapObject().getDimension()); return; } double deltaX = Input.mouse().getMapLocation().getX() - this.dragPoint.getX(); double deltaY = Input.mouse().getMapLocation().getY() - this.dragPoint.getY(); double newWidth = this.dragSizeMapObject.getWidth(); double newHeight = this.dragSizeMapObject.getHeight(); double newX = this.snapX(this.dragLocationMapObject.getX()); double newY = this.snapY(this.dragLocationMapObject.getY()); switch (this.currentTransform) { case DOWN: newHeight += deltaY; break; case DOWNRIGHT: newHeight += deltaY; newWidth += deltaX; break; case DOWNLEFT: newHeight += deltaY; newWidth -= deltaX; newX += deltaX; newX = MathUtilities.clamp(newX, 0, this.dragLocationMapObject.getX() + this.dragSizeMapObject.getWidth()); break; case LEFT: newWidth -= deltaX; newX += deltaX; newX = MathUtilities.clamp(newX, 0, this.dragLocationMapObject.getX() + this.dragSizeMapObject.getWidth()); break; case RIGHT: newWidth += deltaX; break; case UP: newHeight -= deltaY; newY += deltaY; newY = MathUtilities.clamp(newY, 0, this.dragLocationMapObject.getY() + this.dragSizeMapObject.getHeight()); break; case UPLEFT: newHeight -= deltaY; newY += deltaY; newY = MathUtilities.clamp(newY, 0, this.dragLocationMapObject.getY() + this.dragSizeMapObject.getHeight()); newWidth -= deltaX; newX += deltaX; newX = MathUtilities.clamp(newX, 0, this.dragLocationMapObject.getX() + this.dragSizeMapObject.getWidth()); break; case UPRIGHT: newHeight -= deltaY; newY += deltaY; newY = MathUtilities.clamp(newY, 0, this.dragLocationMapObject.getY() + this.dragSizeMapObject.getHeight()); newWidth += deltaX; break; default: return; } this.getFocusedMapObject().setWidth(this.snapX(newWidth)); this.getFocusedMapObject().setHeight(this.snapY(newHeight)); this.getFocusedMapObject().setX(this.snapX(newX)); this.getFocusedMapObject().setY(this.snapY(newY)); Game.getEnvironment().reloadFromMap(this.getFocusedMapObject().getId()); if (MapObjectType.get(this.getFocusedMapObject().getType()) == MapObjectType.LIGHTSOURCE) { Game.getEnvironment().getAmbientLight().createImage(); } EditorScreen.instance().getMapObjectPanel().bind(this.getFocusedMapObject()); this.updateTransformControls(); } private void handleEntityDrag() { // only handle drag i if (this.getFocusedMapObject() == null || (!Input.keyboard().isPressed(KeyEvent.VK_CONTROL) && this.currentEditMode != EDITMODE_MOVE)) { return; } if (this.dragPoint == null) { this.dragPoint = Input.mouse().getMapLocation(); this.dragLocationMapObject = new Point2D.Double(this.getFocusedMapObject().getX(), this.getFocusedMapObject().getY()); return; } double deltaX = Input.mouse().getMapLocation().getX() - this.dragPoint.getX(); double deltaY = Input.mouse().getMapLocation().getY() - this.dragPoint.getY(); double newX = this.snapX(this.dragLocationMapObject.getX() + deltaX); double newY = this.snapY(this.dragLocationMapObject.getY() + deltaY); this.getFocusedMapObject().setX((int) newX); this.getFocusedMapObject().setY((int) newY); Game.getEnvironment().reloadFromMap(this.getFocusedMapObject().getId()); if (MapObjectType.get(this.getFocusedMapObject().getType()) == MapObjectType.STATICSHADOW || MapObjectType.get(this.getFocusedMapObject().getType()) == MapObjectType.LIGHTSOURCE) { Game.getEnvironment().getAmbientLight().createImage(); } EditorScreen.instance().getMapObjectPanel().bind(this.getFocusedMapObject()); this.updateTransformControls(); } private void setCurrentZoom() { Game.getCamera().setZoom(zooms[this.currentZoomIndex], 0); } private void setupControls() { Input.keyboard().onKeyReleased(KeyEvent.VK_ADD, e -> { if (this.isSuspended() || !this.isVisible()) { return; } if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { this.zoomIn(); } }); Input.keyboard().onKeyReleased(KeyEvent.VK_SUBTRACT, e -> { if (this.isSuspended() || !this.isVisible()) { return; } if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { this.zoomOut(); } }); Input.keyboard().onKeyPressed(KeyEvent.VK_SPACE, e -> { if (this.getFocusedMapObject() != null) { Game.getCamera().setFocus(new Point2D.Double(this.getFocus().getCenterX(), this.getFocus().getCenterY())); } }); Input.keyboard().onKeyPressed(KeyEvent.VK_CONTROL, e -> { if (this.currentEditMode == EDITMODE_EDIT) { this.setEditMode(EDITMODE_MOVE); } }); Input.keyboard().onKeyReleased(KeyEvent.VK_CONTROL, e -> { this.setEditMode(EDITMODE_EDIT); }); Input.keyboard().onKeyReleased(KeyEvent.VK_Z, e -> { if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { UndoManager.instance().undo(); } }); Input.keyboard().onKeyReleased(KeyEvent.VK_Y, e -> { if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { UndoManager.instance().redo(); } }); Input.keyboard().onKeyPressed(KeyEvent.VK_DELETE, e -> { if (this.isSuspended() || !this.isVisible() || this.getFocusedMapObject() == null) { return; } if (Game.getScreenManager().getRenderComponent().hasFocus()) { if (this.currentEditMode == EDITMODE_EDIT) { this.delete(); } } }); Input.mouse().onWheelMoved(e -> { if (!this.hasFocus()) { return; } // horizontal scrolling if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL) && this.dragPoint == null) { if (e.getWheelRotation() < 0) { Point2D cameraFocus = Game.getCamera().getFocus(); Point2D newFocus = new Point2D.Double(cameraFocus.getX() - this.scrollSpeed, cameraFocus.getY()); Game.getCamera().setFocus(newFocus); } else { Point2D cameraFocus = Game.getCamera().getFocus(); Point2D newFocus = new Point2D.Double(cameraFocus.getX() + this.scrollSpeed, cameraFocus.getY()); Game.getCamera().setFocus(newFocus); } Program.horizontalScroll.setValue((int) Game.getCamera().getViewPort().getCenterX()); return; } if (Input.keyboard().isPressed(KeyEvent.VK_ALT)) { if (e.getWheelRotation() < 0) { this.zoomIn(); } else { this.zoomOut(); } return; } if (e.getWheelRotation() < 0) { Point2D cameraFocus = Game.getCamera().getFocus(); Point2D newFocus = new Point2D.Double(cameraFocus.getX(), cameraFocus.getY() - this.scrollSpeed); Game.getCamera().setFocus(newFocus); } else { Point2D cameraFocus = Game.getCamera().getFocus(); Point2D newFocus = new Point2D.Double(cameraFocus.getX(), cameraFocus.getY() + this.scrollSpeed); Game.getCamera().setFocus(newFocus); } Program.verticalScroll.setValue((int) Game.getCamera().getViewPort().getCenterY()); }); } private int snapX(double x) { if (!this.snapToGrid) { return MathUtilities.clamp((int) Math.round(x), 0, (int) Game.getEnvironment().getMap().getSizeInPixels().getWidth()); } double snapped = ((int) (x / this.gridSize) * this.gridSize); return (int) Math.round(Math.min(Math.max(snapped, 0), Game.getEnvironment().getMap().getSizeInPixels().getWidth())); } private int snapY(double y) { if (!this.snapToGrid) { return MathUtilities.clamp((int) Math.round(y), 0, (int) Game.getEnvironment().getMap().getSizeInPixels().getHeight()); } double snapped = (int) (y / this.gridSize) * this.gridSize; return (int) Math.round(Math.min(Math.max(snapped, 0), Game.getEnvironment().getMap().getSizeInPixels().getHeight())); } private void updateScrollBars() { Program.horizontalScroll.setMinimum(0); Program.horizontalScroll.setMaximum(Game.getEnvironment().getMap().getSizeInPixels().width); Program.verticalScroll.setMinimum(0); Program.verticalScroll.setMaximum(Game.getEnvironment().getMap().getSizeInPixels().height); Program.horizontalScroll.setValue((int) Game.getCamera().getViewPort().getCenterX()); Program.verticalScroll.setValue((int) Game.getCamera().getViewPort().getCenterY()); } private boolean hasFocus() { if (this.isSuspended() || !this.isVisible()) { return false; } for (GuiComponent comp : this.getComponents()) { if (comp.isHovered() && !comp.isSuspended()) { return false; } } return true; } }
package de.slikey.effectlib.effect; import org.bukkit.Location; import org.bukkit.util.Vector; import de.slikey.effectlib.EffectManager; import de.slikey.effectlib.EffectType; import de.slikey.effectlib.util.ParticleEffect; import de.slikey.effectlib.util.VectorUtils; public class CubeLocationEffect extends LocationEffect { /** * Particle of the cube */ public ParticleEffect particle = ParticleEffect.FLAME; /** * Lenght of the edges */ public float edgeLenght = 3; /** * Turns the cube by this angle each iteration around the x-axis */ public double angularVelocityX = Math.PI / 200; /** * Turns the cube by this angle each iteration around the y-axis */ public double angularVelocityY = Math.PI / 170; /** * Turns the cube by this angle each iteration around the z-axis */ public double angularVelocityZ = Math.PI / 155; /** * Particles in each row */ public int particles = 8; /** * True if rotation is enable */ public boolean enableRotation = true; /** * Only the outlines are drawn */ public boolean outlineOnly = true; /** * Current step. Works as counter */ protected int step = 0; public CubeLocationEffect(EffectManager effectManager, Location location) { super(effectManager, location); type = EffectType.REPEATING; period = 5; iterations = 200; } @Override public void onRun() { if (outlineOnly) { drawCubeOutline(); } else { drawCubeWalls(); } step++; } private void drawCubeOutline() { double xRotation = 0, yRotation = 0, zRotation = 0; if (enableRotation) { xRotation = step * angularVelocityX; yRotation = step * angularVelocityY; zRotation = step * angularVelocityZ; } float a = edgeLenght / 2; // top and bottom double angleX, angleY; Vector v = new Vector(); for (int i = 0; i < 4; i++) { angleY = i * Math.PI / 2; for (int j = 0; j < 2; j++) { angleX = j * Math.PI; for (int p = 0; p <= particles; p++) { v.setX(a).setY(a); v.setZ(edgeLenght * p / particles - a); VectorUtils.rotateAroundAxisX(v, angleX); VectorUtils.rotateAroundAxisY(v, angleY); if (enableRotation) VectorUtils.rotateVector(v, xRotation, yRotation, zRotation); particle.display(location.add(v), visibleRange); location.subtract(v); } } // pillars for (int p = 0; p <= particles; p++) { v.setX(a).setZ(a); v.setY(edgeLenght * p / particles - a); VectorUtils.rotateAroundAxisY(v, angleY); if (enableRotation) VectorUtils.rotateVector(v, xRotation, yRotation, zRotation); particle.display(location.add(v), visibleRange); location.subtract(v); } } } private void drawCubeWalls() { double xRotation = 0, yRotation = 0, zRotation = 0; if (enableRotation) { xRotation = step * angularVelocityX; yRotation = step * angularVelocityY; zRotation = step * angularVelocityZ; } float a = edgeLenght / 2; for (int x = 0; x <= particles; x++) { float posX = edgeLenght * ((float) x / particles) - a; for (int y = 0; y <= particles; y++) { float posY = edgeLenght * ((float) y / particles) - a; for (int z = 0; z <= particles; z++) { if (x != 0 && x != particles && y != 0 && y != particles && z != 0 && z != particles) continue; float posZ = edgeLenght * ((float) z / particles) - a; Vector v = new Vector(posX, posY, posZ); if (enableRotation) VectorUtils.rotateVector(v, xRotation, yRotation, zRotation); particle.display(location.add(v), visibleRange); location.subtract(v); } } } } }
package dr.evomodel.substmodel; import dr.inference.model.Likelihood; import dr.inference.model.Parameter; import dr.evolution.datatype.Microsatellite; import dr.math.ModifiedBesselFirstKind; /** * @author Chieh-Hsi Wu * Implementation of models by Watkins (2007) */ public class NewMicrosatelliteModel extends AbstractSubstitutionModel { public NewMicrosatelliteModel(Microsatellite msat, FrequencyModel rootFreqModel){ super("NewMicrosatelliteModel", msat, rootFreqModel); } public void getTransitionProbabilities(double distance, double[] matrix){ int k = 0; double[] rowSums = new double[stateCount]; for(int i = 0; i < stateCount; i ++){ for(int j = 0; j < stateCount; j++){ matrix[k] = Math.exp(-distance)* ModifiedBesselFirstKind.bessi(distance,Math.abs(i-j)); rowSums[i] += matrix[k]; k++; } } k = 0; for(int i = 0; i < stateCount; i ++){ for(int j = 0; j < stateCount; j++){ matrix[k] = matrix[k]/rowSums[i]; k++; } } } protected void ratesChanged() {}; protected void setupRelativeRates(){}; protected void frequenciesChanged() {}; public static void main(String[] args){ Microsatellite msat = new Microsatellite(1,30); NewMicrosatelliteModel nmsatModel = new NewMicrosatelliteModel(msat, null); double[] probs = new double[msat.getStateCount()*msat.getStateCount()]; nmsatModel.getTransitionProbabilities(1.2,probs); int k =0; for(int i = 0; i < msat.getStateCount(); i++){ for(int j = 0; j < msat.getStateCount(); j++){ System.out.print(probs[k++]+" "); } System.out.println(); } } }
package dr.inference.mcmc; import dr.inference.loggers.Logger; import dr.inference.loggers.MCLogger; import dr.inference.markovchain.MarkovChain; import dr.inference.markovchain.MarkovChainListener; import dr.inference.model.Model; import dr.inference.model.PathLikelihood; import dr.inference.operators.CombinedOperatorSchedule; import dr.inference.operators.OperatorAnalysisPrinter; import dr.inference.operators.OperatorSchedule; import dr.inference.prior.Prior; import dr.util.Identifiable; import dr.xml.*; import org.apache.commons.math.MathException; import org.apache.commons.math.distribution.BetaDistributionImpl; /** * An MCMC analysis that estimates parameters of a probabilistic model. * * @author Andrew Rambaut * @author Alex Alekseyenko * @version $Id: MCMC.java,v 1.41 2005/07/11 14:06:25 rambaut Exp $ */ public class MarginalLikelihoodEstimator implements Runnable, Identifiable { public MarginalLikelihoodEstimator(String id, int chainLength, int burninLength, int pathSteps, // boolean linear, boolean lacing, PathScheme scheme, PathLikelihood pathLikelihood, OperatorSchedule schedule, MCLogger logger) { this.id = id; this.chainLength = chainLength; this.pathSteps = pathSteps; this.scheme = scheme; this.schedule = schedule; // deprecated // this.linear = (scheme == PathScheme.LINEAR); // this.lacing = false; // Was not such a good idea this.burninLength = burninLength; MCMCCriterion criterion = new MCMCCriterion(); pathDelta = 1.0 / pathSteps; pathParameter = 1.0; this.pathLikelihood = pathLikelihood; pathLikelihood.setPathParameter(pathParameter); mc = new MarkovChain(Prior.UNIFORM_PRIOR, pathLikelihood, schedule, criterion, 0, 0, true); this.logger = logger; } private void setDefaultBurnin() { if (burninLength == -1) { burnin = (int) (0.1 * chainLength); } else { burnin = burninLength; } } public void integrate(Integrator scheme) { setDefaultBurnin(); mc.setCurrentLength(burnin); scheme.init(); for (pathParameter = scheme.nextPathParameter(); pathParameter >= 0; pathParameter = scheme.nextPathParameter()) { pathLikelihood.setPathParameter(pathParameter); reportIteration(pathParameter, chainLength, burnin); int cl = mc.getCurrentLength(); mc.setCurrentLength(0); mc.runChain(burnin, false); mc.setCurrentLength(cl); mc.runChain(chainLength, false); (new OperatorAnalysisPrinter(schedule)).showOperatorAnalysis(System.out); ((CombinedOperatorSchedule) schedule).reset(); } } public abstract class Integrator { protected int step; protected int pathSteps; protected Integrator(int pathSteps) { this.pathSteps = pathSteps; } public void init() { step = 0; } abstract double nextPathParameter(); } public class LinearIntegrator extends Integrator { public LinearIntegrator(int pathSteps) { super(pathSteps); } double nextPathParameter() { if (step > pathSteps) return -1; double pathParameter = 1.0 - step / (pathSteps - 1); step = step + 1; return pathParameter; } } public class BetaQuantileIntegrator extends Integrator { private double alpha; public BetaQuantileIntegrator(double alpha, int pathSteps) { super(pathSteps); this.alpha = alpha; } double nextPathParameter() { double result = Math.pow((pathSteps - step)/((double)pathSteps), 1.0/alpha); step++; return result; } } public class BetaIntegrator extends Integrator { private BetaDistributionImpl betaDistribution; public BetaIntegrator(double alpha, double beta, int pathSteps) { super(pathSteps); this.betaDistribution = new BetaDistributionImpl(alpha, beta); } double nextPathParameter() { if (step > pathSteps) return -1; if (step == 0) { step += 1; return 1.0; } else if (step + 1 < pathSteps) { double ratio = (double) step / (double) (pathSteps - 1); try { step += 1; return 1.0 - betaDistribution.inverseCumulativeProbability(ratio); } catch (MathException e) { e.printStackTrace(); } } step += 1; return 0.0; } } public class GeometricIntegrator extends Integrator { public GeometricIntegrator(int pathSteps) { super(pathSteps); } double nextPathParameter() { if (step > pathSteps) { return -1; } if (step == pathSteps) { //pathSteps instead of pathSteps - 1 step += 1; return 0; } step += 1; return Math.pow(2, -(step - 1)); } } /*public void linearIntegration() { setDefaultBurnin(); mc.setCurrentLength(0); for (int step = 0; step < pathSteps; step++) { pathLikelihood.setPathParameter(pathParameter); reportIteration(pathParameter, chainLength, burnin); //mc.runChain(chainLength + burnin, false, 0); mc.runChain(chainLength + burnin, false); pathParameter -= pathDelta; } pathLikelihood.setPathParameter(0.0); reportIteration(pathParameter, chainLength, burnin); //mc.runChain(chainLength + burnin, false, 0); mc.runChain(chainLength + burnin, false); }*/ /*public void betaIntegration(double alpha, double beta) { setDefaultBurnin(); mc.setCurrentLength(0); BetaDistributionImpl betaDistribution = new BetaDistributionImpl(alpha, beta); for (int step = 0; step < pathSteps; step++) { if (step == 0) { pathParameter = 1.0; } else if (step + 1 < pathSteps) { double ratio = (double) step / (double) (pathSteps - 1); try { pathParameter = 1.0 - betaDistribution.inverseCumulativeProbability(ratio); } catch (MathException e) { e.printStackTrace(); } } else { pathParameter = 0.0; } pathLikelihood.setPathParameter(pathParameter); reportIteration(pathParameter, chainLength, burnin); //mc.runChain(chainLength + burnin, false, 0); mc.runChain(chainLength + burnin, false); (new OperatorAnalysisPrinter(schedule)).showOperatorAnalysis(System.out); ((CombinedOperatorSchedule) schedule).reset(); } }*/ private void reportIteration(double pathParameter, int cl, int burn) { System.out.println("Attempting theta = " + pathParameter + " for " + cl + " iterations + " + burn + " burnin."); } public void run() { logger.startLogging(); mc.addMarkovChainListener(chainListener); switch (scheme) { case LINEAR: integrate(new LinearIntegrator(pathSteps)); break; case GEOMETRIC: integrate(new GeometricIntegrator(pathSteps)); break; case ONE_SIDED_BETA: integrate(new BetaIntegrator(1.0, betaFactor, pathSteps)); break; case BETA: integrate(new BetaIntegrator(alphaFactor, betaFactor, pathSteps)); break; case BETA_QUANTILE: integrate(new BetaQuantileIntegrator(alphaFactor, pathSteps)); break; default: throw new RuntimeException("Illegal path scheme"); } mc.removeMarkovChainListener(chainListener); } private final MarkovChainListener chainListener = new MarkovChainListener() { // for receiving messages from subordinate MarkovChain /** * Called to update the current model keepEvery states. */ public void currentState(int state, Model currentModel) { currentState = state; if (currentState >= burnin) { logger.log(state); } } /** * Called when a new new best posterior state is found. */ public void bestState(int state, Model bestModel) { currentState = state; } /** * cleans up when the chain finishes (possibly early). */ public void finished(int chainLength) { currentState = chainLength; (new OperatorAnalysisPrinter(schedule)).showOperatorAnalysis(System.out); // logger.log(currentState); logger.stopLogging(); } }; /** * @return the current state of the MCMC analysis. */ public boolean getSpawnable() { return spawnable; } private boolean spawnable = true; public void setSpawnable(boolean spawnable) { this.spawnable = spawnable; } public void setAlphaFactor(double alpha) { alphaFactor = alpha; } public void setBetaFactor(double beta) { betaFactor = beta; } public double getAlphaFactor() { return alphaFactor; } public double getBetaFactor() { return betaFactor; } public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public String getParserName() { return MARGINAL_LIKELIHOOD_ESTIMATOR; } /** * @return a tree object based on the XML element it was passed. */ public Object parseXMLObject(XMLObject xo) throws XMLParseException { PathLikelihood pathLikelihood = (PathLikelihood) xo.getChild(PathLikelihood.class); MCLogger logger = (MCLogger) xo.getChild(MCLogger.class); int chainLength = xo.getIntegerAttribute(CHAIN_LENGTH); int pathSteps = xo.getIntegerAttribute(PATH_STEPS); int burninLength = -1; if (xo.hasAttribute(BURNIN)) { burninLength = xo.getIntegerAttribute(BURNIN); } int prerunLength = -1; if (xo.hasAttribute(PRERUN)) { prerunLength = xo.getIntegerAttribute(PRERUN); } // deprecated boolean linear = xo.getAttribute(LINEAR, true); // boolean lacing = xo.getAttribute(LACING,false); PathScheme scheme; if (linear) { scheme = PathScheme.LINEAR; } else { scheme = PathScheme.GEOMETRIC; } // new approach if (xo.hasAttribute(PATH_SCHEME)) { // change to: getAttribute once deprecated approach removed scheme = PathScheme.parseFromString(xo.getAttribute(PATH_SCHEME, PathScheme.LINEAR.getText())); } for (int i = 0; i < xo.getChildCount(); i++) { Object child = xo.getChild(i); if (child instanceof Logger) { } } CombinedOperatorSchedule os = new CombinedOperatorSchedule(); XMLObject mcmcXML = xo.getChild(MCMC); for (int i = 0; i < mcmcXML.getChildCount(); ++i) { if (mcmcXML.getChild(i) instanceof MCMC) { MCMC mcmc = (MCMC) mcmcXML.getChild(i); if (prerunLength > 0) { java.util.logging.Logger.getLogger("dr.inference").info("Path Sampling Marginal Likelihood Estimator:\n\tEquilibrating chain " + mcmc.getId() + " for " + prerunLength + " iterations."); for (Logger log : mcmc.getLoggers()) { // Stop the loggers, so nothing gets written to normal output log.stopLogging(); } mcmc.getMarkovChain().runChain(prerunLength, false); } os.addOperatorSchedule(mcmc.getOperatorSchedule()); } } if (os.getScheduleCount() == 0) { System.err.println("Error: no mcmc objects provided in construction. Bayes Factor estimation will likely fail."); } MarginalLikelihoodEstimator mle = new MarginalLikelihoodEstimator(MARGINAL_LIKELIHOOD_ESTIMATOR, chainLength, burninLength, pathSteps, scheme, pathLikelihood, os, logger); if (!xo.getAttribute(SPAWN, true)) mle.setSpawnable(false); if (xo.hasAttribute(ALPHA)) { mle.setAlphaFactor(xo.getAttribute(ALPHA, 0.5)); } if (xo.hasAttribute(BETA)) { mle.setBetaFactor(xo.getAttribute(BETA, 0.5)); } String alphaBetaText = "("; if (scheme == PathScheme.ONE_SIDED_BETA) { alphaBetaText += "1," + mle.getBetaFactor() + ")"; } else if (scheme == PathScheme.BETA) { alphaBetaText += mle.getAlphaFactor() + "," + mle.getBetaFactor() + ")"; } else if (scheme == PathScheme.BETA_QUANTILE) { alphaBetaText += mle.getAlphaFactor() + ")"; } java.util.logging.Logger.getLogger("dr.inference").info("\nCreating the Marginal Likelihood Estimator chain:" + "\n chainLength=" + chainLength + "\n pathSteps=" + pathSteps + "\n pathScheme=" + scheme.getText() + alphaBetaText + "\n If you use these results, please cite:" + "\n Alekseyenko, Rambaut, Lemey and Suchard (in preparation)"); return mle; } /** * this markov chain does most of the work. */ private final MarkovChain mc; private OperatorSchedule schedule; private String id = null; private int currentState; private final int chainLength; private int burnin; private final int burninLength; private int pathSteps; // private final boolean linear; // private final boolean lacing; private final PathScheme scheme; private double alphaFactor = 0.5; private double betaFactor = 0.5; private final double pathDelta; private double pathParameter; private final MCLogger logger; private final PathLikelihood pathLikelihood; public static final String MARGINAL_LIKELIHOOD_ESTIMATOR = "marginalLikelihoodEstimator"; public static final String CHAIN_LENGTH = "chainLength"; public static final String PATH_STEPS = "pathSteps"; public static final String LINEAR = "linear"; public static final String LACING = "lacing"; public static final String SPAWN = "spawn"; public static final String BURNIN = "burnin"; public static final String MCMC = "samplers"; public static final String PATH_SCHEME = "pathScheme"; public static final String ALPHA = "alpha"; public static final String BETA = "beta"; public static final String PRERUN = "prerun"; }
package dr.inference.operators; import dr.inference.model.Parameter; import dr.inferencexml.operators.UniformIntegerOperatorParser; import dr.math.MathUtils; /** * A generic uniform sampler/operator for use with a multi-dimensional parameter. * * @author Alexei Drummond * @author Andrew Rambaut * @version $Id: UniformOperator.java,v 1.16 2005/06/14 10:40:34 rambaut Exp $ */ public class UniformIntegerOperator extends SimpleMCMCOperator { private final int howMany; public UniformIntegerOperator(Parameter parameter, int lower, int upper, double weight, int howMany) { this.parameter = parameter; this.lower = lower; this.upper = upper; this.howMany = howMany; setWeight(weight); } public UniformIntegerOperator(Parameter parameter, int lower, int upper, double weight) { this(parameter, lower, upper, weight, 1); } /** * @return the parameter this operator acts on. */ public Parameter getParameter() { return parameter; } /** * change the parameter and return the hastings ratio. */ public final double doOperation() { for(int n = 0; n < howMany; ++n) { // do not worry about duplication, does not matter int index = MathUtils.nextInt(parameter.getDimension()); int newValue = MathUtils.nextInt(upper - lower) + lower; parameter.setParameterValue(index, newValue); } return 0.0; } //MCMCOperator INTERFACE public final String getOperatorName() { return "uniformInteger(" + parameter.getParameterName() + ")"; } public final void optimize(double targetProb) { throw new RuntimeException("This operator cannot be optimized!"); } public boolean isOptimizing() { return false; } public void setOptimizing(boolean opt) { throw new RuntimeException("This operator cannot be optimized!"); } public double getMinimumAcceptanceLevel() { return 0.1; } public double getMaximumAcceptanceLevel() { return 0.4; } public double getMinimumGoodAcceptanceLevel() { return 0.20; } public double getMaximumGoodAcceptanceLevel() { return 0.30; } public String getPerformanceSuggestion() { if (Utils.getAcceptanceProbability(this) < getMinimumAcceptanceLevel()) { return ""; } else if (Utils.getAcceptanceProbability(this) > getMaximumAcceptanceLevel()) { return ""; } else { return ""; } } public String toString() { return UniformIntegerOperatorParser.UNIFORM_INTEGER_OPERATOR + "(" + parameter.getParameterName() + ")"; } //PRIVATE STUFF private Parameter parameter = null; private final int upper; private final int lower; }
/* Open Source Software - may be modified and shared by FRC teams. The code */ /* the project. */ package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.SimpleRobot; import edu.wpi.first.wpilibj.CANJaguar; import edu.wpi.first.wpilibj.DriverStationLCD; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.Victor; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.Talon; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.Servo; import edu.wpi.first.wpilibj.can.CANTimeoutException; import edu.wpi.first.wpilibj.camera.AxisCamera; import edu.wpi.first.wpilibj.camera.AxisCameraException; import edu.wpi.first.wpilibj.image.BinaryImage; import edu.wpi.first.wpilibj.image.ColorImage; import edu.wpi.first.wpilibj.image.CriteriaCollection; import edu.wpi.first.wpilibj.image.NIVision; import edu.wpi.first.wpilibj.image.NIVisionException; import edu.wpi.first.wpilibj.image.ParticleAnalysisReport; import team1517.aerialassist.mecanum.MecanumDrive; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the SimpleRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class RobotTemplate extends SimpleRobot { boolean catapultArmed = false; final int AREA_MINIMUM = 100; double tiltValue = 0.5, rotValue = 0.85; AxisCamera camera; CriteriaCollection cc; CANJaguar aF, aB, bF, bB; DigitalInput armedSwitch; Victor rotRod1, rotRod2, angle1; Talon winchMotor; Servo tiltServo, rotServo; Joystick xyStick, steerStick, auxStick; DriverStationLCD lcd; MecanumDrive mDrive; public RobotTemplate() { camera = AxisCamera.getInstance(); cc = new CriteriaCollection(); // create the criteria for the particle filter cc.addCriteria(NIVision.MeasurementType.IMAQ_MT_AREA, AREA_MINIMUM, 215472, false); armedSwitch = new DigitalInput(1); rotRod1 = new Victor(1); rotRod2 = new Victor(2); angle1 = new Victor(3); winchMotor = new Talon(4); tiltServo = new Servo(5); rotServo = new Servo(6); xyStick = new Joystick(1); steerStick = new Joystick(2); auxStick = new Joystick(3); lcd = DriverStationLCD.getInstance(); initCANJaguars(); mDrive = new MecanumDrive(aF, aB, bF, bB); } /** * This function is called once each time the robot enters autonomous mode. */ public void autonomous() { Timer.delay(0.7);//Delays a amount of time in order for the hot goal vision targets to rotate into position. boolean isHotGoalStarting = getHotGoal(); try { while(aF.getPosition() < 0.7) { mDrive.drive(0, 1, 0); } mDrive.drive(0, 0, 0); } catch(CANTimeoutException ex) { ex.printStackTrace(); initCANJaguars(); } if(!isHotGoalStarting) { Timer.delay(4); } //Shoot. } /** * This function is called once each time the robot enters operator control. */ public void operatorControl() { boolean exceptionFree; while(isOperatorControl() && isEnabled()) { /* * Controls the drive base and also handles exceptions. */ exceptionFree = tDrive(filterJoystickInput(xyStick.getX()), filterJoystickInput(xyStick.getY()), filterJoystickInput(xyStick.getTwist())); if(!exceptionFree || getCANJaguarsPowerCycled()) { initCANJaguars(); } /* * Sets the output to the angle motor of the rot rods to the value of the y axis of the auxStick scaled by a factor of 0.7. */ angle1.set(auxStick.getY() * 0.7); /* * Controls the rot rods. */ if(auxStick.getRawButton(3)) { rotRod1.set(-0.5); rotRod2.set(0.5); } else if(auxStick.getRawButton(5)) { rotRod1.set(0.5); rotRod2.set(-0.5); } else { rotRod1.set(0); rotRod2.set(0); } /* * Manual control of the catapult winch. */ if(auxStick.getRawButton(1)) { winchMotor.set(-.75); } else if(auxStick.getRawButton(2)) { winchMotor.set(-.5); } else { winchMotor.set(0); } /* * Sets the output values of the camera axis servos. */ tiltServo.set(tiltValue); rotServo.set(rotValue); /* * Allows the user to adjust the value set to the tiltServo. */ if(auxStick.getRawAxis(6) > 0 && tiltValue <= 0.95) { tiltValue = tiltValue + 0.05; } else if(auxStick.getRawAxis(6) < 0 && tiltValue >= 0.05) { tiltValue = tiltValue - 0.05; } /* * Allows the user to adjust the value set to the rotServo. */ if(auxStick.getRawAxis(5) > 0 && rotValue <= 0.95) { rotValue = rotValue + 0.05; } else if(auxStick.getRawAxis(5) < 0 && rotValue >= 0.05) { rotValue = rotValue - 0.05; } lcd.println(DriverStationLCD.Line.kUser1, 1, "tilt " + tiltValue + " "); lcd.println(DriverStationLCD.Line.kUser2, 1, "rot " + rotValue + " "); Timer.delay(0.1); lcd.updateLCD(); } } /** * This function is called once each time the robot enters test mode. */ public void test() { while(isTest() && isEnabled()) { if(auxStick.getRawButton(1)) { lcd.println(DriverStationLCD.Line.kUser1, 1, " " + getHotGoal()); } if(auxStick.getRawButton(2)) { lcd.println(DriverStationLCD.Line.kUser2, 1, " " + getVisionDistance()); } lcd.updateLCD(); } } /** * Moves the catapult into armed position. */ void armCatapult() { if(!catapultArmed) { while(!armedSwitch.get()) { winchMotor.set(0.7); } winchMotor.set(0); catapultArmed = true; } } /** * Fires the catapult. */ void fireCataput() { if(catapultArmed) { Timer timer = new Timer(); timer.start(); while(timer.get() < 0.25)//Adjust as nessisary. { winchMotor.set(0.7); } winchMotor.set(0); catapultArmed = false; timer.stop(); } } /** * Added to abstract the drive method so that CAN can be switched to PWM easier and more simply. * @param mX The X value of the drive vector. * @param mY The Y value of the drive vector. * @param twist The turn added to the output of the drive vector. * @return True if successful, false if exceptions are thrown. */ private boolean tDrive(double mX, double mY, double twist) { return mDrive.drive(mX, mY, twist); } /** * Detects whether the hot goal is visible. * @return True if the hot goal is visible. False if the hot goal is not visible or an exception has been thrown. */ private boolean getHotGoal() { try { ColorImage image = camera.getImage(); BinaryImage thresholdImage = image.thresholdHSV(80, 140, 165, 255, 200, 255); image.free(); BinaryImage hulledImage = thresholdImage.convexHull(false); thresholdImage.free(); if(hulledImage.getNumberParticles() > 0) { lcd.println(DriverStationLCD.Line.kUser2,1, "" + hulledImage.getNumberParticles()); lcd.updateLCD(); ParticleAnalysisReport report; for(int i = 0; i < hulledImage.getNumberParticles(); i++) { report = hulledImage.getParticleAnalysisReport(i); if((report.boundingRectHeight / report.boundingRectWidth) < 1) { return true; } } report = null; } hulledImage.free(); } catch (AxisCameraException ex) { ex.printStackTrace(); return false; } catch (NIVisionException ex) { ex.printStackTrace(); return false; } return false; } /** * Used to initialize the CANJaguars. It can also be called to reinitialize them if an exception is thrown. * @return Success */ private boolean initCANJaguars() { try { aF = null; bF = null; aB = null; bB = null; aF = new CANJaguar(1); bF = new CANJaguar(2); aB = new CANJaguar(3); bB = new CANJaguar(4); aF.changeControlMode(CANJaguar.ControlMode.kPercentVbus); bF.changeControlMode(CANJaguar.ControlMode.kPercentVbus); aB.changeControlMode(CANJaguar.ControlMode.kPercentVbus); bB.changeControlMode(CANJaguar.ControlMode.kPercentVbus); aF.setSpeedReference(CANJaguar.SpeedReference.kQuadEncoder); bF.setSpeedReference(CANJaguar.SpeedReference.kQuadEncoder); aB.setSpeedReference(CANJaguar.SpeedReference.kQuadEncoder); bB.setSpeedReference(CANJaguar.SpeedReference.kQuadEncoder); aF.setPositionReference(CANJaguar.PositionReference.kQuadEncoder); bF.setPositionReference(CANJaguar.PositionReference.kQuadEncoder); aB.setPositionReference(CANJaguar.PositionReference.kQuadEncoder); bB.setPositionReference(CANJaguar.PositionReference.kQuadEncoder); aF.configEncoderCodesPerRev(100); bF.configEncoderCodesPerRev(100); aB.configEncoderCodesPerRev(100); bB.configEncoderCodesPerRev(100); } catch(CANTimeoutException ex) { ex.printStackTrace(); return false; } return true; } /** * Detects whether one or more of the CANJaguars has lost and then regained power. * @return True if power to one or more of the CANJaguars has been cycled or if a timeout exception has occurred. False otherwise. */ private boolean getCANJaguarsPowerCycled() { try { if(aF.getPowerCycled() || aB.getPowerCycled() || bF.getPowerCycled() || bB.getPowerCycled()) { return true; } } catch(CANTimeoutException ex) { ex.printStackTrace(); return true; } return false; } /** * Filters out noise from the input of the joysticks. * @param joystickValue The raw input value from the joystick. * @return The filtered value. */ double filterJoystickInput(double joystickValue) { if(Math.abs(joystickValue) > 0.1) { return (joystickValue * joystickValue * joystickValue); } else { if(xyStick.getTwist() != 0) { return 0.0000000000001; } else { return 0; } } } double getVisionDistance() { try { ColorImage image = camera.getImage(); BinaryImage thresholdImage = image.thresholdHSV(80, 140, 165, 255, 200, 255); image.free(); BinaryImage hulledImage = thresholdImage.convexHull(false); thresholdImage.free(); if(hulledImage.getNumberParticles() > 0) { ParticleAnalysisReport report; for(int i = 0; i < hulledImage.getNumberParticles(); i++) { report = hulledImage.getParticleAnalysisReport(i); if(report.boundingRectWidth / report.boundingRectHeight < 1) //1 can be reduced. { //do distance calculations. //return distance. return report.center_mass_y_normalized + 1; } } } } catch (AxisCameraException ex) { ex.printStackTrace(); return -2; } catch (NIVisionException ex) { ex.printStackTrace(); return -3; } return -1; } }
/* Open Source Software - may be modified and shared by FRC teams. The code */ /* the project. */ package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.DriverStationLCD; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.Jaguar; import edu.wpi.first.wpilibj.Joystick; //import edu.wpi.first.wpilibj.Relay; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.Timer; import java.io.* ; import java.lang.StringBuffer; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class RobotTemplate extends IterativeRobot { public void printMsg(String message) { userMessages.println(DriverStationLCD.Line.kMain6, 1, message ); userMessages.updateLCD(); } RobotDrive drivetrain; //Relay spikeA; Joystick leftStick; Joystick rightStick; //public String controlScheme = "twostick"; int leftStickX, leftStickY; DriverStationLCD userMessages; String controlScheme = "twostick"; Timer timer; DigitalInput switchA, switchB; Jaguar launcher; double voltage; //DriverStation driverStation = new DriverStation(); /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { //Instantialize objects for RobotTemplate //driverStation = new DriverStation(); rightStick = new Joystick(1); leftStick = new Joystick(2); userMessages = DriverStationLCD.getInstance(); //2-Wheel tank drive //spikeA = new Relay(1); drivetrain = new RobotDrive(1,2); launcher = new Jaguar(5); /*pistonUp = new Solenoid(1); pistonDown = new Solenoid(2); sol3 = new Solenoid(3); sol4 = new Solenoid(4); sol5 = new Solenoid(5);*/ //4-Wheel tank drive //Motors must be set in the following order: //LeftFront=1; LeftRear=2; RightFront=3; RightRear=4; //drivetrain = new RobotDrive(1,2,3,4); //drivetrain.tankDrive(leftStick, rightStick); /*pistonDown.set(true); pistonUp.set(true);*/ switchA = new DigitalInput(1); switchB = new DigitalInput(2);//remember to check port } /** * This function is called periodically during autonomous */ public void autonomousInit() { voltage = DriverStation.getInstance().getBatteryVoltage(); drivetrain.setSafetyEnabled(false); if (switchA.get() && switchB.get()) { printMsg("Moving Forward"); drivetrain.setLeftRightMotorOutputs(0.5, 0.5); Timer.delay(1); drivetrain.stopMotor(); } else if (!switchA.get() && !switchB.get()) { printMsg("Moving backward"); drivetrain.setLeftRightMotorOutputs(-0.5, -0.5); Timer.delay(1); drivetrain.stopMotor(); } else if (switchA.get() && !switchB.get()) { printMsg("turning"); drivetrain.setLeftRightMotorOutputs(0.5, -0.5); Timer.delay(1); drivetrain.stopMotor(); } else if (!switchA.get() && switchB.get()) { printMsg("turning"); drivetrain.setLeftRightMotorOutputs(-0.5, 0.5); Timer.delay(1); drivetrain.stopMotor(); } else { printMsg("Switch not detected"); //Timer.delay(15); not necessary, see below } //teleopInit(); driver station will do this automatically /*drivetrain.setLeftRightMotorOutputs(1.0, 1.0); Timer.delay(1000); drivetrain.setLeftRightMotorOutputs(-1.0, 1.0); Timer.delay(500); drivetrain.setLeftRightMotorOutputs(1.0, 1.0); Timer.delay(1000); drivetrain.setLeftRightMotorOutputs(0, 0); */ } public void telopInit() { //drivetrain.setSafetyEnabled(true); //drivetrain.tankDrive(leftStick.getY(), rightStick.getY()); //compressorA.start(); printMsg("Teleop started."); } /** * This function is called periodically during operator control */ public void teleopPeriodic() { /*if(switchA.get()){//if switch isn't tripped printMsg("Moving motor."); //victor.set(0.5); //start motor } else{ printMsg("Motor stopped"); //victor.set(0); //stop motor }*/ //getWatchdog().setEnabled(true); double rightMag; rightMag = rightStick.getMagnitude(); String rightMag2 = String.valueOf(rightMag); double leftMag; leftMag = leftStick.getMagnitude(); String leftMag2 = String.valueOf(leftMag); String someMags = new StringBuffer().append(rightMag2).append(" ").append(leftMag2).toString(); printMsg(someMags); while(isEnabled() && isOperatorControl()) { drivetrain.tankDrive(leftStick, rightStick); } //Pneumatics test code if (leftStick.getTrigger()) { launcher.set(-1); } else { //don't set to 0 to avoid conflicts with right stick } if (rightStick.getTrigger()) { launcher.set(1); } else { launcher.set(0); } //Switch between "onestick" and "twostick" control schemes if (leftStick.getRawButton(6)) { controlScheme = "twostick"; } if (leftStick.getRawButton(7)) { controlScheme = "onestick"; } if (controlScheme.equals("twostick")) { drivetrain.tankDrive(rightStick, leftStick); printMsg("Tankdrive activated."); } else if (controlScheme.equals("onestick")) { drivetrain.arcadeDrive(leftStick); printMsg("Arcade drive activated."); } if(switchA.get()){//if switch isn't tripped printMsg("Moving motor."); //victor.set(0.5); //start motor } else{ printMsg("Motor stopped"); //victor.set(0); //stop motor } //Rotate in-place left and right, respectively if (leftStick.getRawButton(8)) { drivetrain.setLeftRightMotorOutputs(-1.0, 1.0); printMsg("Rotating counterclockwise in place."); } if (leftStick.getRawButton(9)) { drivetrain.setLeftRightMotorOutputs(1.0, -1.0); printMsg("Rotating clockwise in place."); } //userMessages.println(DriverStationLCD.Line.kMain6, 1, "This is a test" ); userMessages.updateLCD(); } /*public void disabledInit() { }*/ }
package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.*; public class RobotTemplate extends IterativeRobot { //YUM! static final double PI = 3.1415926535897932384626433832795; //Maximum Robot Speed in m/s static final double NORMAL_WHEEL_SPEED = 2.7764; static final double SLOW_WHEEL_SPEED = 1.0; static final double AUTONOMOUS_WHEEL_SPEED = 0.333; //Number of Encoder Counts per Metre Travelled static final double COUNTS_PER_METRE = 900.0; //Maximum Robot Rotational Speed in rad/s static final double NORMAL_ANGULAR_VELOCITY = 4*PI; static final double SLOW_ANGULAR_VELOCITY = PI; static final double AUTONOMOUS_ANGULAR_VELOCITY = PI / 2; //Mecanum Dimensions: A = Half Robot Width, B = Half Robot Length (in metres) static final double DISTANCE_A = 0.375; static final double DISTANCE_B = 0.255; //Minimum Size of Target static final double MINIMUM_SCORE = 0.01; //Number of camera frames per second static final int FRAME_SKIP = 10; //Kicker encoder counts static final int MAX_KICKER_ENCODER_COUNTS = 850; //Max power for the winch static final double KICKER_POWER = 0.75; //dont start winching until this delay has passed after a kick static final double KICK_WINCH_DELAY = 1.25; //Delay after kick static final double KICK_MIN_DELAY = 2.0 - KICK_WINCH_DELAY; //Driver buttons static final int SLOW_BUTTON = 6; static final int TRACK_TARGET_BUTTON = 8; static final int REVERSE_BUTTON = 5; //Operator buttons static final int KICK_BUTTON = 1; static final int ROLLER_IN_BUTTON = 2; static final int ROLLER_OUT_BUTTON = 3; static final int HANGER_UP_BUTTON = 4; static final int HANGER_DOWN_BUTTON = 5; //Joysticks Joystick stickOne = new Joystick(1); Joystick stickTwo = new Joystick(2); //Wheel jaguars Jaguar jagFrontLeft = new Jaguar(1); Jaguar jagBackLeft = new Jaguar(2); Jaguar jagFrontRight = new Jaguar(3); Jaguar jagBackRight = new Jaguar(4); //Kicker Victor vicKicker = new Victor(5); //Roller Victor vicRoller = new Victor(7); //Sea shell Victor vicRelease = new Victor(8); //Extra victor Victor vicTest = new Victor(9); //Wheel encoders, reversed if needed to be PIDEncoder encFrontLeft = new PIDEncoder(1, 2, true); //Reversed PIDEncoder encBackLeft = new PIDEncoder(3, 4, true); //Reversed PIDEncoder encFrontRight = new PIDEncoder(5, 6); PIDEncoder encBackRight = new PIDEncoder(7, 8); //Encoder on the kicker Encoder encKicker = new Encoder(9, 10, false, Encoder.EncodingType.k1X); //PID Controllers for each wheel, with their speeds negated as neccessary PIDController pidFrontLeft = new PIDController(0.0, -0.00003, 0.0, encFrontLeft, jagFrontLeft, 0.005); PIDController pidBackLeft = new PIDController(0.0, -0.00003, 0.0, encBackLeft, jagBackLeft, 0.005); PIDController pidFrontRight = new PIDController(0.0, 0.00003, 0.0, encFrontRight, jagFrontRight, 0.005); PIDController pidBackRight = new PIDController(0.0, 0.00003, 0.0, encBackRight, jagBackRight, 0.005); //Light sensor on the sea shell DigitalInput releaseSensor = new DigitalInput(11); //Light sensor check if we have a ball DigitalInput ballSensor = new DigitalInput(12); //Kill switch if kicker has raised too far DigitalInput kickerKillSwitch = new DigitalInput(14); //Reverse driving boolean driveReverse; boolean reverseButtonReleased; int kickerSetpoint; //Autonomous mode int autonomousMode; //Last time the kicker was kicked double lastKickTime; //Autonomous balls kicked int ballsLeft; //If the kicker was released the last run static boolean prevRelease = false; public class KickState { //Kicker is at its setpoint static final int Default = 0; //Kicker is moving to its setpoint static final int Loading = 1; //Trigger was pressed static final int Kicking = 2; }; public class TriggerState { //Sea shell in default position, light sensor is on the tape static final int Engaged = 0; //Run the sea shell until the light sensor doesnt see the tape static final int Releasing = 1; //Run the sea shell until the light is seen again static final int Released = 2; //Identify the state of the sea shell static final int Unknown = 3; }; //Current states for state machines int currentKickState; int currentTriggerState; //Runs when the robot is turned public void robotInit() { //Reverse driving driveReverse = true; reverseButtonReleased = true; //Kicker target setpoint kickerSetpoint = 0; //Autonomous mode autonomousMode = 0; //Last time the kicker was kicked lastKickTime = 0.0; //Autonomous balls kicked ballsLeft = 0; } //Runs at the beginning of autonomous period public void autonomousInit() { } //Runs periodically during autonomous period public void autonomousPeriodic() { } //Runs continuously during autonomous period public void autonomousContinuous() { } //Runs at the beginning of teleoperated period public void teleopInit() { } //Runs periodically during teleoperated period public void teleopPeriodic() { System.out.println("Kicker encoder: " + encKicker.get()); System.out.println("FL encoder: " + encFrontLeft.pidGet()); System.out.println("BL encoder: " + encBackLeft.pidGet()); System.out.println("FR encoder: " + encFrontRight.pidGet()); System.out.println("BR encoder: " + encBackRight.pidGet()); } //A boolean object, who's value can be changed from inside a function public class BooleanHolder { //Value of object boolean value; //Defaults to false public BooleanHolder() { value = false; } //Overloaded constructor to take any value of boolean public BooleanHolder(boolean val) { value = val; } //Get boolean public final boolean get() { return value; } //Set boolean public void set(boolean val) { value = val; } } //Kicker state machine int runKickStateMachine(int curState, int setpoint, int encoder, boolean trigger, boolean ballReady, boolean forceKick, BooleanHolder winch, BooleanHolder release) { //Turn off the winch and the sea shell by default winch.set(false); release.set(false); switch(curState) { //Default (setpoint reached) case KickState.Default: { //Do not run the motors winch.set(false); release.set(false); //If you havent reached the setpoint yet if(setpoint > encoder) { //Loading return KickState.Loading; } //If the trigger is pressed and there is a ball or we are force kicking, and if we have waited long enough since the last kick if(trigger && (ballReady || forceKick) && (Timer.getFPGATimestamp() - KICK_MIN_DELAY) > lastKickTime) { //Reset lastKickTime to the current time lastKickTime = Timer.getFPGATimestamp(); //Kicking return KickState.Kicking; } } break; //Loading (havent reached setpoint) case KickState.Loading: { //Run the winch, not the sea shell winch.set(true); release.set(false); //If we have reached our setpoint if(encoder >= setpoint) { //Go back to default state return KickState.Default; } } break; //Kicking (release kicker) case KickState.Kicking: { //Dont run winch, run release winch.set(false); release.set(true); //If weve delayed long enough and joystick trigger is not pressed if(Timer.getFPGATimestamp() - KICK_WINCH_DELAY > lastKickTime && !trigger) { //Reset the encoder to our initial position encKicker.reset(); //Autonomous balls left in the zone --ballsLeft; //kickerSetpoint -= MAX_KICKER_ENCODER_COUNTS / 20; //Loading return KickState.Loading; } } break; default: return KickState.Default; } return curState; } //Trigger state machine (controls sea shell) double runTriggerStateMachine(boolean trigger, boolean sensor) { //Motor speed constants final double MOTOR_ON = 0.75; final double MOTOR_OFF = 0.0; //Motor is initially off double motorSpeed = MOTOR_OFF; switch(currentTriggerState) { //Engaged (light sensor is on the tape) case TriggerState.Engaged: { //Stop motor motorSpeed = MOTOR_OFF; if(trigger) { //Start releasing currentTriggerState = TriggerState.Releasing; } } break; //Releasing case TriggerState.Releasing: { //Run motor motorSpeed = MOTOR_ON; if(!sensor) { //Reached end of tape currentTriggerState = TriggerState.Released; } } break; //Released case TriggerState.Released: { //Run motor motorSpeed = MOTOR_ON; if(sensor) { //Tape reached again currentTriggerState = TriggerState.Engaged; } } break; //Unknown case TriggerState.Unknown: default: //Stop motor motorSpeed = MOTOR_OFF; //If it sees the tape, it is engaged, otherwise it is released currentTriggerState = sensor ? TriggerState.Engaged : TriggerState.Released; } return motorSpeed; } //Runs continuously during teleoperated period public void teleopContinuous() { getWatchdog().feed(); //Operator trigger boolean curTrigger = stickTwo.getRawButton(KICK_BUTTON); //Booleans to drive winch and sea shell, changed by call to kicker state machine BooleanHolder winch = new BooleanHolder(false); BooleanHolder release = new BooleanHolder(false); //Forcekick if trigger and hanger down button pressed boolean forceKick = stickTwo.getRawButton(KICK_BUTTON) && stickTwo.getRawButton(HANGER_DOWN_BUTTON); //Release kicker if trigger is pressed of if you need to forcekick boolean trigger = curTrigger || forceKick; //Kicker setpoint (only if we are going to release kickerSetpoint = trigger ? 0 : (int)(((stickTwo.getRawAxis(1) + 1.0) / 2.0) * MAX_KICKER_ENCODER_COUNTS); //Setpoint cannot be less than 0 kickerSetpoint = kickerSetpoint < 0 ? 0 : kickerSetpoint; //Kicker state machine (winch and release are changed by this function [Java version of pointers]) currentKickState = runKickStateMachine(currentKickState, kickerSetpoint, -encKicker.getRaw(), trigger, ballSensor.get(), forceKick, winch, release); //Run the winch based on how the kicker state machine wants it to //vicKicker.set((winch.get() && !kickerKillSwitch.get()) ? KICKER_POWER : 0.0); //Releasing this run through and didnt the last run through final boolean releaseTriggered = release.get() && !prevRelease; //Trigger state machine double vicReleaseSpeed = runTriggerStateMachine(releaseTriggered, releaseSensor.get()); //Update prevRelease to be the current value of release prevRelease = release.get(); //Run the sea shell with the speed the state machine wants vicRelease.set(-vicReleaseSpeed); //Reverse button is pressed and the reverse button was released in the last run if(stickOne.getRawButton(REVERSE_BUTTON) && reverseButtonReleased) { //It is no longer released reverseButtonReleased = false; //Reverse driving driveReverse = !driveReverse; } //Reverse button is released else if(!stickOne.getRawButton(REVERSE_BUTTON)) { reverseButtonReleased = true; } //mecanumDrive(stickOne.GetRawAxis(2), stickOne.GetRawAxis(1), stickOne.GetRawAxis(3), stickOne.GetRawButton(SLOW_BUTTON), stickOne.GetRawButton(TRACK_TARGET_BUTTON)); double speedFrontLeft, speedBackLeft, speedFrontRight, speedBackRight; //Temporary mecanum drive calculations speedFrontLeft = (-stickOne.getRawAxis(2) / 3) + (stickOne.getRawAxis(1) / 3) + (stickOne.getRawAxis(3) / 3); speedBackLeft = (-stickOne.getRawAxis(2) / 3) + (-stickOne.getRawAxis(1) / 3) + (stickOne.getRawAxis(3) / 3); speedFrontRight = (stickOne.getRawAxis(2) / 3) + (stickOne.getRawAxis(1) / 3) + (stickOne.getRawAxis(3) / 3); speedBackRight = (stickOne.getRawAxis(2) / 3) + (-stickOne.getRawAxis(1) / 3) + (stickOne.getRawAxis(3) / 3); //Reverse drive speedFrontLeft = driveReverse ? -speedFrontLeft : speedFrontLeft; speedBackLeft = driveReverse ? -speedBackLeft : speedBackLeft; speedFrontRight = driveReverse ? -speedFrontRight : speedFrontRight; speedBackRight = driveReverse ? -speedBackRight : speedBackRight; //Drive motors at calculated speed jagFrontLeft.set(speedFrontLeft); jagBackLeft.set(speedBackLeft); jagFrontRight.set(speedFrontRight); jagBackRight.set(speedBackRight); double rollerSpeed; //If roller in button is pressed then run the roller at 1.0, otherwise 0.0 rollerSpeed = stickTwo.getRawButton(ROLLER_IN_BUTTON) ? 1.0 : 0.0; //If roller out button is pressed then run the roller at -1.0, otherwise the previous value of rollerSpeed rollerSpeed = stickTwo.getRawButton(ROLLER_OUT_BUTTON) ? -1.0 : rollerSpeed; //Run the roller vicRoller.set(rollerSpeed); } }
/* Open Source Software - may be modified and shared by FRC teams. The code */ /* the project. */ package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.Compressor; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.Solenoid; import edu.wpi.first.wpilibj.Timer; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Team1482Robot extends IterativeRobot { //Initlise loop counters int m_disabledPeriodicLoops; int m_autoPeriodicLoops; int m_telePeriodicLoops; int m_dsPacketsReceivedInCurrentSecond; RobotDrive drive = new RobotDrive(1, 2); //Set up joystick and driving refrence Joystick driveJoystick = new Joystick(1); Joystick shootJoystick = new Joystick(2); public static int NUM_JOYSTICK_BUTTONS = 16; //Setup air compressor Compressor airCompressor = new Compressor(1,1); Solenoid lift = new Solenoid(1); Solenoid liftReset = new Solenoid(2); Solenoid drop = new Solenoid(3); Solenoid dropReset = new Solenoid(4); /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { } /* Example code!! modify! */ /* Iterate over all the buttons on the joystick, checking to see if each is pressed * If a button is pressed, check to see if it is newly pressed; if so, print out a * message on the console */ for (buttonNum = 1; buttonNum <= NUM_JOYSTICK_BUTTONS; buttonNum++) { if (currStick.getRawButton(buttonNum)) { // the current button is pressed, now act accordingly... if (!buttonPreviouslyPressed[buttonNum]) { // button newly pressed; print out a message if (!outputGenerated) { // print out a heading if no other button pressed this cycle outputGenerated = true; System.out.println("button pressed:" + stickString); } System.out.println(" " + buttonNum); } // remember that this button is pressed for the next iteration buttonPreviouslyPressed[buttonNum] = true; // set numOfButtonPressed appropriately if (numOfButtonPressed == 0) { // no button pressed yet this time through, set the number correctly numOfButtonPressed = buttonNum; } else { // another button (or buttons) must have already been pressed, set appropriately numOfButtonPressed = -1; } } else { buttonPreviouslyPressed[buttonNum] = false; } } // after iterating through all the buttons, add a newline to output if needed if (outputGenerated) { System.out.println("\n"); } if (numOfButtonPressed == -1) { // multiple buttons were pressed, display as if button 15 was pressed //DisplayBinaryNumberOnSolenoidLEDs(15, solenoids); } else { // display the number of the button pressed on the solenoids; // note that if no button was pressed (0), the solenoid display will be cleared (set to 0) //DisplayBinaryNumberOnSolenoidLEDs(numOfButtonPressed, solenoids); } } }
/* Open Source Software - may be modified and shared by FRC teams. The code */ /* the project. */ package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.Compressor; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.Solenoid; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.Talon; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Team1482Robot extends IterativeRobot { //initialize loop counters int m_disabledPeriodicLoops; int m_autoPeriodicLoops; int m_telePeriodicLoops; int m_teleContinuousLoops; int m_dsPacketsReceivedInCurrentSecond; int m_liftstate; int m_grabstate; //Set up Talons to do whatever (uncomment as needed) Talon drive_left = new Talon(1); Talon drive_right = new Talon(2); //Talon pwm3_motor = new Talon(3); //Talon pwm4_motor = new Talon(4); //Talon pwm5_motor = new Talon(5); //Talon pwm6_motor = new Talon(6); //Set up 2 motor drive RobotDrive drive = new RobotDrive(drive_left, drive_right); //Set up 4 motor drive (uncomment as needed) //RobotDrive drive = new Robotdrive(drive_left, drive_backleft, drive_right, drive_backright); //Set up joystick Joystick drivestick = new Joystick(1); Joystick shootstick = new Joystick(2); public static int NUM_JOYSTICK_BUTTONS = 16; //Declair joystick buttons boolean[] m_driveStickButtonState = new boolean[(NUM_JOYSTICK_BUTTONS+1)]; boolean[] m_shootStickButtonState = new boolean[(NUM_JOYSTICK_BUTTONS+1)]; //Set up air compressor and Solenoids Compressor airCompressor = new Compressor(1,1); Solenoid lift = new Solenoid(1); Solenoid liftreset = new Solenoid(2); Solenoid drop = new Solenoid(3); Solenoid dropreset = new Solenoid(4); Solenoid grab = new Solenoid(5); Solenoid grabreset = new Solenoid(6); public Team1482Robot() { System.out.println("BuiltinDefaultCode Constructor Started\n"); int buttonNum = 1; for (buttonNum = 1; buttonNum <= NUM_JOYSTICK_BUTTONS; buttonNum++) { m_driveStickButtonState[buttonNum] = false; m_shootStickButtonState[buttonNum] = false; } } /** * This function is called once when entering autonomous */ public void autonomousInit() { System.out.println("Autonomous started"); m_autoPeriodicLoops = 0; //resets loop counter on entering auto getWatchdog().setEnabled(false); getWatchdog().setExpiration(0.5); //Set up lift pistons lift.set(false); liftreset.set(true); m_liftstate = 0; //set up the garb pistons grab.set(false); grabreset.set(true); m_grabstate = 0; } /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { // insert code here } /** * This function is called once when entering teleop */ public void teleopInit() { System.out.println("Starting Teleop"); m_telePeriodicLoops = 0; m_teleContinuousLoops = 0; //resets loop counters on entering tele getWatchdog().setEnabled(true); getWatchdog().setExpiration(0.05); airCompressor.start(); //start compressor //Set up lift pistons lift.set(false); liftreset.set(true); m_liftstate = 0; //set up the garb pistons grab.set(false); grabreset.set(true); m_grabstate = 0; } /** * This function is called periodically during teleop */ public void teleopPeriodic() { m_telePeriodicLoops++; } /** * This function runs continuously during teleop */ public void teleopContinuous() { if (isEnabled()) { m_teleContinuousLoops++; double drivestick_x = drivestick.getRawAxis(1); double drivestick_y = drivestick.getRawAxis(2); //Axis values assuming XBox 360 controller drive.arcadeDrive(drivestick_y, drivestick_x); //Check button values (uncomment as needed) //boolean drivestick_1 = drivestick.getRawButton(1); //boolean drivestick_2 = drivestick.getRawButton(2); //boolean drivestick_3 = drivestick.getRawButton(3); //boolean drivestick_4 = drivestick.getRawButton(4); //etc etc if (ButtonToggle(shootstick, m_shootStickButtonState, 1) == "held") { System.out.println("Button 1 held"); } else if (ButtonToggle(shootstick, m_shootStickButtonState, 1) == "pressed") { System.out.println("Button 1 just pressed"); //When pressed //If retracted extend if(m_liftstate == 0){ lift.set(true); liftreset.set(false); m_liftstate = 1; } //If is not retracted retract else{ lift.set(false); liftreset.set(true); m_liftstate = 0; } } getWatchdog().feed(); Timer.delay(0.005); } else { Timer.delay(0.01); getWatchdog().feed(); } }
package experimentalcode.marisa.index.xtree; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.RandomAccessFile; import java.math.BigInteger; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import de.lmu.ifi.dbs.elki.data.HyperBoundingBox; import de.lmu.ifi.dbs.elki.data.ModifiableHyperBoundingBox; import de.lmu.ifi.dbs.elki.data.NumberVector; import de.lmu.ifi.dbs.elki.database.ids.DBIDUtil; import de.lmu.ifi.dbs.elki.database.query.DistanceResultPair; import de.lmu.ifi.dbs.elki.distance.distancefunction.SpatialPrimitiveDistanceFunction; import de.lmu.ifi.dbs.elki.distance.distancevalue.Distance; import de.lmu.ifi.dbs.elki.distance.distancevalue.DoubleDistance; import de.lmu.ifi.dbs.elki.index.tree.DistanceEntry; import de.lmu.ifi.dbs.elki.index.tree.LeafEntry; import de.lmu.ifi.dbs.elki.index.tree.TreeIndexHeader; import de.lmu.ifi.dbs.elki.index.tree.TreeIndexPath; import de.lmu.ifi.dbs.elki.index.tree.TreeIndexPathComponent; import de.lmu.ifi.dbs.elki.index.tree.spatial.SpatialEntry; import de.lmu.ifi.dbs.elki.index.tree.spatial.SpatialLeafEntry; import de.lmu.ifi.dbs.elki.index.tree.spatial.rstarvariants.AbstractRStarTree; import de.lmu.ifi.dbs.elki.index.tree.spatial.rstarvariants.NonFlatRStarTree; import de.lmu.ifi.dbs.elki.persistent.LRUCache; import de.lmu.ifi.dbs.elki.persistent.PersistentPageFile; import de.lmu.ifi.dbs.elki.utilities.datastructures.heap.KNNHeap; import de.lmu.ifi.dbs.elki.utilities.exceptions.AbortException; import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID; import de.lmu.ifi.dbs.elki.utilities.optionhandling.WrongParameterValueException; import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.EqualStringConstraint; import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.IntervalConstraint; import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.IntervalConstraint.IntervalBoundary; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.DoubleParameter; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.StringParameter; import experimentalcode.marisa.index.xtree.util.SplitHistory; import experimentalcode.marisa.index.xtree.util.SquareEuclideanDistanceFunction; import experimentalcode.marisa.index.xtree.util.XSplitter; import experimentalcode.marisa.utils.PQ; import experimentalcode.marisa.utils.PriorityQueue; /** * Base class for XTree implementations and other extensions; derived from * {@link NonFlatRStarTree}. * * @author Marisa Thoma * * @param <O> Object type * @param <N> Node type * @param <E> Entry type */ public abstract class XTreeBase<O extends NumberVector<O, ?>, N extends XNode<E, N>, E extends SpatialEntry> extends AbstractRStarTree<O, N, E> { /** * If <code>true</code>, the expensive call of * {@link #calculateOverlapIncrease(List, SpatialEntry, HyperBoundingBox)} is * omitted for supernodes. This may lead to longer query times, however, is * necessary for enabling the construction of the tree for some * parameterizations. * */ public boolean OMIT_OVERLAP_INCREASE_4_SUPERNODES = true; /** * Mapping id to supernode. Supernodes are appended to the end of the index * file when calling #commit(); */ protected Map<Long, N> supernodes = new HashMap<Long, N>(); /** * Relative min entries value. */ private double relativeMinEntries; /** * Relative minimum fanout. */ private double relativeMinFanout; /** * Minimum size to be allowed for page sizes after a split in case of a * minimum overlap split. */ protected int min_fanout; /** Fraction of pages to be re-inserted instead of trying a split. */ protected float reinsert_fraction = .3f; /** Maximum overlap for a split partition. */ protected float max_overlap = .2f; /** Dimensionality of the {@link NumberVector}s stored in this tree. */ protected int dimensionality; /** Number of elements (of type <O>) currently contained in this tree. */ protected long num_elements = 0; /** * The maximum overlap is calculated as the ratio of total data objects in the * overlapping region. */ public static final int DATA_OVERLAP = 0; /** * The maximum overlap is calculated as the fraction of the overlapping region * of the two original mbrs: * <code>(overlap volume of mbr 1 and mbr 2) / (volume of mbr 1 + volume of mbr 2)</code> */ public static final int VOLUME_OVERLAP = 1; /** * Type of overlap to be used for testing on maximum overlap. Must be one of * {@link #DATA_OVERLAP} and {@link #VOLUME_OVERLAP}. */ protected int overlap_type = DATA_OVERLAP; /** * OptionID for {@link #MIN_ENTRIES_PARAMETER} */ public static final OptionID MIN_ENTRIES_ID = OptionID.getOrCreateOptionID("xtree.min_entry_fraction", "The fraction (in [0,1]) of maximally allowed page entries which is to be be used as minimum number of page entries"); /** * OptionID for {@link #MIN_FANOUT_PARAMETER} */ public static final OptionID MIN_FANOUT_ID = OptionID.getOrCreateOptionID("xtree.min_fanout_fraction", "The fraction (in [0,1]) of maximally allowed directory page entries which is to be tolerated as minimum number of directory page entries for minimum overlap splits"); /** * OptionID for {@link #REINSERT_PARAMETER} */ public static final OptionID REINSERT_ID = OptionID.getOrCreateOptionID("xtree.reinsert_fraction", "The fraction (in [0,1]) of entries to be reinserted instead of performing a split"); /** * OptionID for {@link #MAX_OVERLAP_PARAMETER} */ public static final OptionID MAX_OVERLAP_ID = OptionID.getOrCreateOptionID("xtree.max_overlap_fraction", "The fraction (in [0,1]) of allowed entry overlaps. Overlap type specified in xtree.overlap_type"); /** * OptionID for {@link #OVERLAP_TYPE_PARAMETER} */ public static final OptionID OVERLAP_TYPE_ID = OptionID.getOrCreateOptionID("xtree.overlap_type", "How to calculate the maximum overlap? Options: \"DataOverlap\" = {ratio of data objects in the overlapping region}, \"VolumeOverlap\" = {(overlap volume) / (volume 1 + volume 2)}"); /** * Parameter for minimum number of entries per page; defaults to * <code>.4</code> times the number of maximum entries. */ private final DoubleParameter MIN_ENTRIES_PARAMETER = new DoubleParameter(MIN_ENTRIES_ID, new IntervalConstraint(0, IntervalBoundary.CLOSE, 1, IntervalBoundary.OPEN), 0.4); /** * Parameter for minimum number of entries per directory page when going for a * minimum overlap split; defaults to <code>.3</code> times the number of * maximum entries. */ private final DoubleParameter MIN_FANOUT_PARAMETER = new DoubleParameter(MIN_FANOUT_ID, new IntervalConstraint(0, IntervalBoundary.CLOSE, 1, IntervalBoundary.CLOSE), 0.3); /** * Parameter for the number of re-insertions to be performed instead of doing * a split; defaults to <code>.3</code> times the number of maximum entries. */ private final DoubleParameter REINSERT_PARAMETER = new DoubleParameter(REINSERT_ID, new IntervalConstraint(0, IntervalBoundary.CLOSE, 1, IntervalBoundary.OPEN), 0.3); /** * Parameter for the maximally allowed overlap. Defaults to <code>.2</code>. */ private final DoubleParameter MAX_OVERLAP_PARAMETER = new DoubleParameter(MAX_OVERLAP_ID, new IntervalConstraint(0, IntervalBoundary.OPEN, 1, IntervalBoundary.CLOSE), 0.2); /** * Parameter for defining the overlap type to be used for the maximum overlap * test. Available options: * <dl> * <dt><code>DataOverlap</code></dt> * <dd>The overlap is the ratio of total data objects in the overlapping * region.</dd> * <dt><code>VolumeOverlap</code></dt> * <dd>The overlap is the fraction of the overlapping region of the two * original mbrs:<br> * <code>(overlap volume of mbr 1 and mbr 2) / (volume of mbr 1 + volume of mbr 2)</code> * <br> * This option is faster than <code>DataOverlap</code>, however, it may result * in a tree structure which is not optimally adapted to the indexed data.</dd> * </dl> * Defaults to <code>VolumeOverlap</code>. */ private final StringParameter OVERLAP_TYPE_PARAMETER = new StringParameter(OVERLAP_TYPE_ID, new EqualStringConstraint(new String[] { "DataOverlap", "VolumeOverlap" }), "VolumeOverlap"); public static final int QUEUE_INIT = 50; /* * Creates a new RTree. */ public XTreeBase(Parameterization config) { super(config); config = config.descend(this); if(config.grab(MIN_ENTRIES_PARAMETER)) { relativeMinEntries = MIN_ENTRIES_PARAMETER.getValue(); } if(config.grab(MIN_FANOUT_PARAMETER)) { relativeMinFanout = MIN_FANOUT_PARAMETER.getValue(); } if(config.grab(REINSERT_PARAMETER)) { reinsert_fraction = REINSERT_PARAMETER.getValue().floatValue(); } if(config.grab(MAX_OVERLAP_PARAMETER)) { max_overlap = MAX_OVERLAP_PARAMETER.getValue().floatValue(); } if(config.grab(OVERLAP_TYPE_PARAMETER)) { String mOType = OVERLAP_TYPE_PARAMETER.getValue(); if(mOType.equals("DataOverlap")) { overlap_type = DATA_OVERLAP; } else if(mOType.equals("VolumeOverlap")) { overlap_type = VOLUME_OVERLAP; } else { config.reportError(new WrongParameterValueException("Wrong input parameter for overlap type '" + mOType + "'")); } } } /** * Returns true if in the specified node an overflow occurred, false * otherwise. * * @param node the node to be tested for overflow * @return true if in the specified node an overflow occurred, false otherwise */ @Override protected boolean hasOverflow(N node) { if(node.isLeaf()) { return node.getNumEntries() == leafCapacity; } else { if(node.isSuperNode()) // supernode capacity differs from normal capacity return node.getNumEntries() == node.getCapacity(); return node.getNumEntries() == dirCapacity; } } /** * Returns true if in the specified node an underflow occurred, false * otherwise. If <code>node</code> is a supernode, never returns * <code>true</code>, as this method automatically shortens the node's * capacity by one page size in case of an underflow. If this leads to a * normal page size, the node is converted into a normal (non-super) node an * it is removed from {@link #supernodes}. * * @param node the node to be tested for underflow * @return true if in the specified node an underflow occurred, false * otherwise */ @Override protected boolean hasUnderflow(N node) { if(node.isLeaf()) { return node.getNumEntries() < leafMinimum; } else { if(node.isSuperNode()) { if(node.getCapacity() - node.getNumEntries() >= dirCapacity) { int newCapacity = node.shrinkSuperNode(dirCapacity); if(newCapacity == dirCapacity) { assert !node.isSuperNode(); // convert into a normal node (and insert into the index file) if(node.isSuperNode()) { throw new IllegalStateException("This node should not be a supernode anymore"); } N n = supernodes.remove(new Long(node.getPageID())); assert (n != null); // update the old reference in the file file.writePage(node); } } return false; } return node.getNumEntries() < dirMinimum; } } /** * Computes the height of this XTree. Is called by the constructor. and should * be overwritten by subclasses if necessary. * * @return the height of this XTree */ @Override protected int computeHeight() { N node = getRoot(); int tHeight = 1; // compute height while(!node.isLeaf() && node.getNumEntries() != 0) { E entry = node.getEntry(0); node = getNode(entry.getEntryID()); tHeight++; } return tHeight; } /** * Returns the node with the specified id. Note that supernodes are kept in * main memory (in {@link #supernodes}, thus, their listing has to be tested * first. * * @param nodeID the page id of the node to be returned * @return the node with the specified id */ @Override public N getNode(Integer nodeID) { N nID = supernodes.get(new Long(nodeID)); if(nID != null) { return nID; } N n = super.getNode(nodeID); assert !n.isSuperNode(); // we should have them ALL in #supernodes return n; } @Override protected void createEmptyRoot(@SuppressWarnings("unused") O object) { N root = createNewLeafNode(leafCapacity); file.writePage(root); setHeight(1); } /** * TODO: This does not work at all for supernodes! * * Performs a bulk load on this XTree with the specified data. Is called by * the constructor and should be overwritten by subclasses if necessary. * * @param objects the data objects to be indexed */ @Override protected void bulkLoad(List<O> objects) { throw new UnsupportedOperationException("Bulk Load not supported for XTree"); } /** * Get the main memory supernode map for this tree. If it is empty, there are * no supernodes in this tree. * * @return the supernodes of this tree */ public Map<Long, N> getSupernodes() { return supernodes; } /** * Get the overlap type used for this XTree. * * @return One of * <dl> * <dt><code>{@link #DATA_OVERLAP}</code></dt> * <dd>The overlap is the ratio of total data objects in the * overlapping region.</dd> * <dt><code>{@link #VOLUME_OVERLAP}</code></dt> * <dd>The overlap is the fraction of the overlapping region of the * two original mbrs: * <code>(overlap volume of mbr 1 and mbr 2) / (volume of mbr 1 + volume of mbr 2)</code> * </dd> * </dl> */ public int get_overlap_type() { return overlap_type; } /** @return the maximally allowed overlap for this XTree. */ public float get_max_overlap() { return max_overlap; } /** @return the minimum directory capacity after a minimum overlap split */ public int get_min_fanout() { return min_fanout; } /** @return the minimum directory capacity */ public int getDirMinimum() { return super.dirMinimum; } /** @return the minimum leaf capacity */ public int getLeafMinimum() { return super.leafMinimum; } /** @return the maximum directory capacity */ public int getDirCapacity() { return super.dirCapacity; } /** @return the maximum leaf capacity */ public int getLeafCapacity() { return super.leafCapacity; } /** @return the tree's objects' dimension */ public int getDimensionality() { return dimensionality; } /** @return the number of elements in this tree */ public long getSize() { return num_elements; } /** * Writes all supernodes to the end of the file. This is only supposed to be * used for a final saving of an XTree. If another page is added to this tree, * the supernodes written to file by this operation are over-written. Note * that this tree will only be completely saved after an additional call of * {@link #close()}. * * @return the number of bytes written to file for this tree's supernodes * @throws IOException if there are any io problems when writing the tree's * supernodes */ public long commit() throws IOException { if(!(super.file instanceof PersistentPageFile)) { throw new IllegalStateException("Trying to commit a non-persistent XTree"); } long npid = super.file.getNextPageID(); XTreeHeader ph = (XTreeHeader) ((PersistentPageFile<N>) super.file).getHeader(); long offset = (ph.getReservedPages() + npid) * ph.getPageSize(); ph.setSupernode_offset(npid * ph.getPageSize()); ph.setNumberOfElements(num_elements); RandomAccessFile ra_file = ((PersistentPageFile<N>) super.file).getFile(); ph.writeHeader(ra_file); ra_file.seek(offset); long nBytes = 0; for(Iterator<N> iterator = supernodes.values().iterator(); iterator.hasNext();) { N supernode = iterator.next(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); supernode.writeSuperNode(oos); oos.close(); baos.close(); byte[] array = baos.toByteArray(); byte[] sn_array = new byte[pageSize * (int) Math.ceil((double) supernode.getCapacity() / dirCapacity)]; if(array.length > sn_array.length) { throw new IllegalStateException("Supernode is too large for fitting in " + ((int) Math.ceil((double) supernode.getCapacity() / dirCapacity)) + " pages of total size " + sn_array.length); } System.arraycopy(array, 0, sn_array, 0, array.length); ((PersistentPageFile<N>) super.file).increaseWriteAccess(); ra_file.write(sn_array); nBytes += sn_array.length; } return nBytes; } @Override protected TreeIndexHeader createHeader() { return new XTreeHeader(pageSize, dirCapacity, leafCapacity, dirMinimum, leafMinimum, min_fanout, num_elements, dimensionality, reinsert_fraction, max_overlap); } /** * Raises the "number of elements" counter. */ @Override protected void preInsert(@SuppressWarnings("unused") E entry) { num_elements++; } public boolean initializeTree(O dataObject) { super.initialize(dataObject); return true; } /** * To be called via the constructor if the tree is to be read from file. */ @Override public void initializeFromFile() { if(getFileName() == null) { throw new IllegalArgumentException("Parameter file name is not specified."); } // init the file (meaning no parameter used in createHeader() survives) XTreeHeader header = (XTreeHeader) createHeader(); // header is read here: super.file = new PersistentPageFile<N>(header, cacheSize, new LRUCache<N>(), getFileName(), getNodeClass()); super.pageSize = header.getPageSize(); super.dirCapacity = header.getDirCapacity(); super.leafCapacity = header.getLeafCapacity(); super.dirMinimum = header.getDirMinimum(); super.leafMinimum = header.getLeafMinimum(); this.min_fanout = header.getMin_fanout(); this.num_elements = header.getNumberOfElements(); this.dimensionality = header.getDimensionality(); this.reinsert_fraction = header.getReinsert_fraction(); this.max_overlap = header.getMaxOverlap(); long superNodeOffset = header.getSupernode_offset(); if(getLogger().isDebugging()) { StringBuffer msg = new StringBuffer(); msg.append(getClass()); msg.append("\n file = ").append(file.getClass()); getLogger().debugFine(msg.toString()); } // reset page id maintenance super.file.setNextPageID((int) (superNodeOffset / header.getPageSize())); // read supernodes (if there are any) if(superNodeOffset > 0) { RandomAccessFile ra_file = ((PersistentPageFile<N>) super.file).getFile(); long offset = header.getReservedPages() * pageSize + superNodeOffset; int bs = 0 // omit this: 4 // EMPTY_PAGE or FILLED_PAGE ? + 4 + 1 // isLeaf + 1 // isSupernode + 4 // number of entries + 4; // capacity byte[] buffer = new byte[bs]; try { // go to supernode region ra_file.seek(offset); while(ra_file.getFilePointer() + pageSize <= ra_file.length()) { ((PersistentPageFile<N>) super.file).increaseReadAccess(); ra_file.read(buffer); ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(buffer)); int id = ois.readInt(); ois.readBoolean(); // iLeaf boolean supernode = ois.readBoolean(); if(!supernode) { throw new IllegalStateException("Non-supernode at supernode position '" + superNodeOffset + "'"); } int numEntries = ois.readInt(); int capacity = ois.readInt(); ois.close(); N page; try { page = getNodeClass().newInstance(); } catch(IllegalAccessException e) { throw new AbortException("AccessException instantiating a supernode", e); } catch(InstantiationException e) { throw new AbortException("InstantiationException instantiating a supernode", e); } ((PersistentPageFile<N>) super.file).increaseReadAccess(); ra_file.seek(offset); byte[] superbuffer = new byte[pageSize * (int) Math.ceil((double) capacity / dirCapacity)]; // increase offset for the next position seek offset += superbuffer.length; ra_file.read(superbuffer); ois = new ObjectInputStream(new ByteArrayInputStream(buffer)); try { // read from file and add to supernode map page.readSuperNode(ois, this); } catch(ClassNotFoundException e) { throw new AbortException("ClassNotFoundException when loading a supernode", e); } assert numEntries == page.getNumEntries(); assert capacity == page.getCapacity(); assert id == page.getPageID(); } } catch(IOException e) { throw new RuntimeException("IOException caught when loading tree from file '" + getFileName() + "'" + e); } } super.initialized = true; // compute height super.height = computeHeight(); if(getLogger().isDebugging()) { StringBuffer msg = new StringBuffer(); msg.append(getClass()); msg.append("\n height = ").append(height); getLogger().debugFine(msg.toString()); } } @Override protected void initializeCapacities(O object) { /* Simulate the creation of a leaf page to get the page capacity */ try { int cap = 0; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); SpatialLeafEntry sl = new SpatialLeafEntry(DBIDUtil.importInteger(0), new double[object.getDimensionality()]); while(baos.size() <= pageSize) { sl.writeExternal(oos); oos.flush(); cap++; } // the last one caused the page to overflow. leafCapacity = cap - 1; } catch(IOException e) { throw new AbortException("Error determining page sizes.", e); } /* Simulate the creation of a directory page to get the capacity */ try { int cap = 0; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); HyperBoundingBox hb = new HyperBoundingBox(new double[object.getDimensionality()], new double[object.getDimensionality()]); XDirectoryEntry xl = new XDirectoryEntry(0, hb); while(baos.size() <= pageSize) { xl.writeExternal(oos); oos.flush(); cap++; } dirCapacity = cap - 1; } catch(IOException e) { throw new AbortException("Error determining page sizes.", e); } if(dirCapacity <= 1) { throw new IllegalArgumentException("Node size of " + pageSize + " Bytes is chosen too small!"); } if(dirCapacity < 10) { getLogger().warning("Page size is choosen very small! Maximum number of entries " + "in a directory node = " + (dirCapacity - 1)); } // minimum entries per directory node dirMinimum = (int) Math.round((dirCapacity - 1) * relativeMinEntries); if(dirMinimum < 2) { dirMinimum = 2; } // minimum entries per directory node min_fanout = (int) Math.round((dirCapacity - 1) * relativeMinFanout); if(min_fanout < 2) { min_fanout = 2; } if(leafCapacity <= 1) { throw new IllegalArgumentException("Node size of " + pageSize + " Bytes is chosen too small!"); } if(leafCapacity < 10) { getLogger().warning("Page size is choosen very small! Maximum number of entries " + "in a leaf node = " + (leafCapacity - 1)); } // minimum entries per leaf node leafMinimum = (int) Math.round((leafCapacity - 1) * relativeMinEntries); if(leafMinimum < 2) { leafMinimum = 2; } dimensionality = object.getDimensionality(); if(getLogger().isVerbose()) { getLogger().verbose("Directory Capacity: " + (dirCapacity - 1) + "\nDirectory minimum: " + dirMinimum + "\nLeaf Capacity: " + (leafCapacity - 1) + "\nLeaf Minimum: " + leafMinimum + "\nminimum fanout: " + min_fanout); } } /** * Chooses the best path of the specified subtree for insertion of the given * MBR at the specified level. The selection uses the following criteria: * <ol> * <li>Test on containment (<code>mbr</code> <em>is</em> within one of the * children)</li> * <li>If there are multiple containing children, the child with the minimum * volume is chosen.</li> * <li>Else, if the children point to leaf nodes, chooses the child with the * minimum multi-overlap increase.</li> * <li>Else, or the multi-overlap increase leads to ties, the child with the * minimum volume increase is selected.</li> * <li>If there are still ties, the child with the minimum volume is chosen.</li> * </ol> * * @param subtree the subtree to be tested for insertion * @param mbr the MBR to be inserted * @param level the level at which the MBR should be inserted (level 1 * indicates leaf-level) * @return the path of the appropriate subtree to insert the given * <code>mbr</code> */ @Override protected TreeIndexPath<E> choosePath(TreeIndexPath<E> subtree, HyperBoundingBox mbr, int level) { if(getLogger().isDebuggingFiner()) { getLogger().debugFiner("node " + subtree + ", level " + level); } N node = getNode(subtree.getLastPathComponent().getEntry()); if(node.isLeaf()) { return subtree; } // first test on containment TreeIndexPathComponent<E> containingEntry = containedTest(node, mbr); if(containingEntry != null) { TreeIndexPath<E> newSubtree = subtree.pathByAddingChild(containingEntry); if(height - subtree.getPathCount() == level) { return newSubtree; } else { return choosePath(newSubtree, mbr, level); } } TreeIndexPathComponent<E> optEntry = null; HyperBoundingBox optTestMBR = null; double optOverlapInc = 0; boolean isLeafContainer = false; // test overlap increase? if((!OMIT_OVERLAP_INCREASE_4_SUPERNODES // also test supernodes || (OMIT_OVERLAP_INCREASE_4_SUPERNODES && !node.isSuperNode())) // don't && getNode(node.getEntry(0)).isLeaf()) { // children are leafs // overlap increase is to be tested optOverlapInc = Double.POSITIVE_INFINITY; isLeafContainer = true; } double optVolume = Double.POSITIVE_INFINITY; double optVolumeInc = Double.POSITIVE_INFINITY; double tempVolume, volume; int index = 0; List<E> entries = node.getChildren(); for(Iterator<E> iterator = entries.iterator(); iterator.hasNext(); index++) { E child = iterator.next(); HyperBoundingBox childMBR = child.getMBR(); HyperBoundingBox testMBR = childMBR.union(mbr); double pairwiseOverlapInc; if(isLeafContainer) { pairwiseOverlapInc = calculateOverlapIncrease(entries, child, testMBR); if(Double.isInfinite(pairwiseOverlapInc) || Double.isNaN(pairwiseOverlapInc)) { throw new IllegalStateException("an entry's MBR is too large to calculate its overlap increase: " + pairwiseOverlapInc + "; \nplease re-scale your data s.t. it can be dealt with"); } } else { // no need to examine overlap increase? pairwiseOverlapInc = 0; } if(pairwiseOverlapInc <= optOverlapInc) { if(pairwiseOverlapInc == optOverlapInc) { // If there are multiple entries with the same overlap increase, // choose the one with the minimum volume increase. // If there are also multiple entries with the same volume increase // choose the one with the minimum volume. volume = childMBR.volume(); if(Double.isInfinite(volume) || Double.isNaN(volume)) { throw new IllegalStateException("an entry's MBR is too large to calculate its volume: " + volume + "; \nplease re-scale your data s.t. it can be dealt with"); } tempVolume = testMBR.volume(); if(Double.isInfinite(tempVolume) || Double.isNaN(tempVolume)) { throw new IllegalStateException("an entry's MBR is too large to calculate its volume: " + tempVolume + "; \nplease re-scale your data s.t. it can be dealt with"); } double volumeInc = tempVolume - volume; if(Double.isNaN(optVolumeInc)) { // has not yet been calculated optVolume = optEntry.getEntry().getMBR().volume(); optVolumeInc = optTestMBR.volume() - optVolume; } if(volumeInc < optVolumeInc) { optVolumeInc = volumeInc; optVolume = volume; optEntry = new TreeIndexPathComponent<E>(child, index); } else if(volumeInc == optVolumeInc && volume < optVolume) { // TODO: decide whether to remove this option System.out.println(" optVolumeInc = volumeInc; optVolume = volume; optEntry = new TreeIndexPathComponent<E>(child, index); } } else { // already better optOverlapInc = pairwiseOverlapInc; optVolume = Double.NaN; optVolumeInc = Double.NaN; optTestMBR = testMBR; // for later calculations optEntry = new TreeIndexPathComponent<E>(child, index); } } } assert optEntry != null; TreeIndexPath<E> newSubtree = subtree.pathByAddingChild(optEntry); if(height - subtree.getPathCount() == level) { return newSubtree; } else { return choosePath(newSubtree, mbr, level); } } /** * Celebrated by the Profiler as a lot faster than the previous variant: that * used to calculate all overlaps of the old MBR and the new MBR with all * other MBRs. Now: The overlaps are only calculated if necessary:<br> * <ul> * <li>the new MBR does not have to be tested on overlaps if the current * dimension has never changed</li> * <li>the old MBR does not have to be tested if the new MBR shows no overlaps * </li> * </ul> * Furthermore tries to avoid rounding errors arising from large value ranges * and / or larger dimensions. <br> * <br> * However: hardly any difference in real runtime! * * @param entries entries to be tested on overlap * @param ei current entry * @param testMBR extended MBR of <code>ei</code> * @return */ private double calculateOverlapIncrease(List<E> entries, E ei, HyperBoundingBox testMBR) { ModifiableHyperBoundingBox eiMBR = new ModifiableHyperBoundingBox(ei.getMBR()); ModifiableHyperBoundingBox testMBRModifiable = new ModifiableHyperBoundingBox(testMBR); double[] lb = eiMBR.getMinRef(); double[] ub = eiMBR.getMaxRef(); double[] lbT = testMBRModifiable.getMinRef(); double[] ubT = testMBRModifiable.getMaxRef(); double[] lbNext = null; // next tested lower bounds double[] ubNext = null; // and upper bounds boolean[] dimensionChanged = new boolean[lb.length]; for(int i = 0; i < dimensionChanged.length; i++) { if(lb[i] > lbT[i] || ub[i] < ubT[i]) { dimensionChanged[i] = true; } } double multiOverlapInc = 0, multiOverlapMult = 1, mOOld = 1, mONew = 1; double ol, olT; // dimensional overlap for(E ej : entries) { if(!ej.getEntryID().equals(ei.getEntryID())) { multiOverlapMult = 1; // is constant for a unchanged dimension mOOld = 1; // overlap for old MBR on changed dimensions mONew = 1; // overlap on new MBR on changed dimension ModifiableHyperBoundingBox ejMBR = new ModifiableHyperBoundingBox(ej.getMBR()); lbNext = ejMBR.getMinRef(); ubNext = ejMBR.getMaxRef(); for(int i = 0; i < dimensionChanged.length; i++) { if(dimensionChanged[i]) { if(lbT[i] > ubNext[i] || ubT[i] < lbNext[i]) { multiOverlapMult = 0; break; // old MBR has no overlap either } olT = (ubT[i] > ubNext[i] ? ubNext[i] : ubT[i]) - (lbT[i] < lbNext[i] ? lbNext[i] : lbT[i]); mONew *= olT; if(mOOld != 0) { // else: no use in calculating overlap ol = (ub[i] > ubNext[i] ? ubNext[i] : ub[i]) - (lb[i] < lbNext[i] ? lbNext[i] : lb[i]); if(ol < 0) { ol = 0; } mOOld *= ol; } } else { if(lb[i] > ubNext[i] || ub[i] < lbNext[i]) { multiOverlapMult = 0; break; } ol = (ub[i] > ubNext[i] ? ubNext[i] : ub[i]) - (lb[i] < lbNext[i] ? lbNext[i] : lb[i]); multiOverlapMult *= ol; } } if(multiOverlapMult != 0) { multiOverlapInc += multiOverlapMult * (mONew - mOOld); } } } return multiOverlapInc; } /** * Splits the specified node and returns the newly created split node. If, due * to an exceeding overlap, no split can be conducted, <code>node</code> is * converted into a supernode and <code>null</code> is returned. * * @param node the node to be split * @param splitAxis field for collecting the split axis used for this split or * <code>-1</code> if the split was not successful * @return Either the newly created split node with its split dimension logged * in <code>splitAxis</code>, or <code>null</code>, if * <code>node</code> has been converted into a supernode. */ private N split(N node, int[] splitAxis) { if(splitAxis.length != 1) { throw new IllegalArgumentException("Expecting integer container for returning the split axis"); } // choose the split dimension and the split point XSplitter splitter = new XSplitter(this, node.getChildren()); XSplitter.SplitSorting split = splitter.topologicalSplit(); double minOv = splitter.getPastOverlap(); if(split == null) { // topological split failed if(node.isLeaf()) { throw new IllegalStateException("The topological split must be successful in leaves."); } split = splitter.minimumOverlapSplit(); if(splitter.getPastOverlap() < minOv) { minOv = splitter.getPastOverlap(); // only used for logging } } if(split != null) {// do the split N newNode; newNode = node.splitEntries(split.getSortedEntries(), split.getSplitPoint()); // write changes to file file.writePage(node); file.writePage(newNode); splitAxis[0] = split.getSplitAxis(); if(getLogger().isDebugging()) { StringBuffer msg = new StringBuffer(); msg.append("Split Node ").append(node.getPageID()).append(" (").append(getClass()).append(")\n"); msg.append(" splitAxis ").append(splitAxis[0]).append("\n"); msg.append(" splitPoint ").append(split.getSplitPoint()).append("\n"); msg.append(" newNode ").append(newNode.getPageID()).append("\n"); if(getLogger().isVerbose()) { msg.append(" first: ").append(newNode.getChildren()).append("\n"); msg.append(" second: ").append(node.getChildren()).append("\n"); } getLogger().debugFine(msg.toString()); } return newNode; } else { // create supernode node.makeSuperNode(); supernodes.put((long) node.getPageID(), node); file.writePage(node); splitAxis[0] = -1; if(getLogger().isDebugging()) { StringBuffer msg = new StringBuffer(); msg.append("Created Supernode ").append(node.getPageID()).append(" (").append(getClass()).append(")\n"); msg.append(" new capacity ").append(node.getCapacity()).append("\n"); msg.append(" minimum overlap: ").append(minOv).append("\n"); getLogger().debugFine(msg.toString()); } return null; } } /** * Treatment of overflow in the specified node: if the node is not the root * node and this is the first call of overflowTreatment in the given level * during insertion the specified node will be reinserted, otherwise the node * will be split. * * @param node the node where an overflow occurred * @param path the path to the specified node * @param splitAxis field for collecting the split axis used for this split or * <code>-1</code> if the split was not successful * @return In case of a re-insertion: <code>null</code>. In case of a split: * Either the newly created split node with its split dimension logged * in <code>splitAxis</code>, or <code>null</code>, if * <code>node</code> has been converted into a supernode. */ private N overflowTreatment(N node, TreeIndexPath<E> path, int[] splitAxis) { if(node.isSuperNode()) { // only extend supernode; no re-insertions assert node.getCapacity() == node.getNumEntries(); assert node.getCapacity() > dirCapacity; node.growSuperNode(); return null; } int level = height - path.getPathCount() + 1; Boolean reInsert = reinsertions.get(level); // there was still no reinsert operation at this level if(node.getPageID() != 0 && (reInsert == null || !reInsert) && reinsert_fraction != 0) { reinsertions.put(level, true); if(getLogger().isDebugging()) { getLogger().debugFine("REINSERT " + reinsertions); } reInsert(node, level, path); return null; } // there was already a reinsert operation at this level else { return split(node, splitAxis); } } // /** // * Compute the centroid of the MBRs or data objects contained by // * <code>node</code>. Was intended to lead to more central re-insert // * distributions, however, this variant rarely avoids a supernode, and // * definitely costs more time. // * // * @param node // * @return // */ // protected O compute_centroid(N node) { // double[] d = new double[node.getDimensionality()]; // for(int i = 0; i < node.getNumEntries(); i++) { // if(node.isLeaf()) { // double[] values = ((SpatialLeafEntry) node.getEntry(i)).getValues(); // for(int j = 0; j < values.length; j++) { // d[j] += values[j]; // else { // ModifiableHyperBoundingBox mbr = new // ModifiableHyperBoundingBox(node.getEntry(i).getMBR()); // double[] min = mbr.getMinRef(); // double[] max = mbr.getMaxRef(); // for(int j = 0; j < min.length; j++) { // d[j] += min[j] + max[j]; // for(int j = 0; j < d.length; j++) { // if(node.isLeaf()) { // d[j] /= node.getNumEntries(); // else { // d[j] /= (node.getNumEntries() * 2); // // FIXME: make generic (or just hope DoubleVector is fine) // return (O) new DoubleVector(d); /** * Reinserts the specified node at the specified level. * * @param node the node to be reinserted * @param level the level of the node * @param path the path to the node */ @Override @SuppressWarnings("unchecked") protected void reInsert(N node, int level, TreeIndexPath<E> path) { HyperBoundingBox mbr = node.mbr(); SquareEuclideanDistanceFunction distFunction = new SquareEuclideanDistanceFunction(); DistanceEntry<DoubleDistance, E>[] reInsertEntries = new DistanceEntry[node.getNumEntries()]; // O centroid = compute_centroid(node); // compute the center distances of entries to the node and sort it // in decreasing order to their distances for(int i = 0; i < node.getNumEntries(); i++) { E entry = node.getEntry(i); DoubleDistance dist = distFunction.centerDistance(mbr, entry.getMBR()); // DoubleDistance dist = distFunction.maxDist(entry.getMBR(), centroid); // DoubleDistance dist = distFunction.centerDistance(entry.getMBR(), // centroid); reInsertEntries[i] = new DistanceEntry<DoubleDistance, E>(entry, dist, i); } Arrays.sort(reInsertEntries, Collections.reverseOrder()); // define how many entries will be reinserted int start = (int) (reinsert_fraction * node.getNumEntries()); if(getLogger().isDebugging()) { getLogger().debugFine("reinserting " + node.getPageID() + " ; from 0 to " + (start - 1)); } // initialize the reinsertion operation: move the remaining entries // forward node.initReInsert(start, reInsertEntries); file.writePage(node); // and adapt the mbrs TreeIndexPath<E> childPath = path; N child = node; while(childPath.getParentPath() != null) { N parent = getNode(childPath.getParentPath().getLastPathComponent().getEntry()); int indexOfChild = childPath.getLastPathComponent().getIndex(); child.adjustEntry(parent.getEntry(indexOfChild)); file.writePage(parent); childPath = childPath.getParentPath(); child = parent; } // reinsert the first entries for(int i = 0; i < start; i++) { DistanceEntry<DoubleDistance, E> re = reInsertEntries[i]; if(getLogger().isDebugging()) { getLogger().debugFine("reinsert " + re.getEntry() + (node.isLeaf() ? "" : " at " + level)); } insertEntry(re.getEntry(), level); } } /** * Inserts the specified entry at the specified level into this R*-Tree. * * @param entry the entry to be inserted * @param level the level at which the entry is to be inserted; automatically * set to <code>1</code> for leaf entries */ private void insertEntry(E entry, int level) { if(entry.isLeafEntry()) { insertLeafEntry(entry); } else { insertDirectoryEntry(entry, level); } } /** * Inserts the specified leaf entry into this R*-Tree. * * @param entry the leaf entry to be inserted */ @Override protected void insertLeafEntry(E entry) { // choose subtree for insertion HyperBoundingBox mbr = entry.getMBR(); TreeIndexPath<E> subtree = choosePath(getRootPath(), mbr, 1); if(getLogger().isDebugging()) { getLogger().debugFine("insertion-subtree " + subtree + "\n"); } N parent = getNode(subtree.getLastPathComponent().getEntry()); parent.addLeafEntry(entry); file.writePage(parent); // since adjustEntry is expensive, try to avoid unnecessary subtree updates if(!hasOverflow(parent) && // no overflow treatment (parent.getPageID() == getRootEntry().getEntryID() || // is root // below: no changes in the MBR subtree.getLastPathComponent().getEntry().getMBR().contains(((SpatialLeafEntry) entry).getValues()))) { return; // no need to adapt subtree } // adjust the tree from subtree to root adjustTree(subtree); } /** * Inserts the specified directory entry at the specified level into this * R*-Tree. * * @param entry the directory entry to be inserted * @param level the level at which the directory entry is to be inserted */ @Override protected void insertDirectoryEntry(E entry, int level) { // choose node for insertion of o HyperBoundingBox mbr = entry.getMBR(); TreeIndexPath<E> subtree = choosePath(getRootPath(), mbr, level); if(getLogger().isDebugging()) { getLogger().debugFine("subtree " + subtree); } N parent = getNode(subtree.getLastPathComponent().getEntry()); parent.addDirectoryEntry(entry); file.writePage(parent); // since adjustEntry is expensive, try to avoid unnecessary subtree updates if(!hasOverflow(parent) && // no overflow treatment (parent.getPageID() == getRootEntry().getEntryID() || // is root // below: no changes in the MBR subtree.getLastPathComponent().getEntry().getMBR().contains(entry.getMBR()))) { return; // no need to adapt subtree } // adjust the tree from subtree to root adjustTree(subtree); } /** * Adjusts the tree after insertion of some nodes. * * @param subtree the subtree to be adjusted */ @Override protected void adjustTree(TreeIndexPath<E> subtree) { if(getLogger().isDebugging()) { getLogger().debugFine("Adjust tree " + subtree); } // get the root of the subtree N node = getNode(subtree.getLastPathComponent().getEntry()); // overflow in node if(hasOverflow(node)) { if(node.isSuperNode()) { int new_capacity = node.growSuperNode(); getLogger().finest("Extending supernode to new capacity " + new_capacity); if(node.getPageID() == getRootEntry().getEntryID()) { // is root node.adjustEntry(getRootEntry()); } else { N parent = getNode(subtree.getParentPath().getLastPathComponent().getEntry()); E e = parent.getEntry(subtree.getLastPathComponent().getIndex()); HyperBoundingBox mbr = e.getMBR(); node.adjustEntry(e); if(!mbr.equals(e.getMBR())) { // MBR has changed // write changes in parent to file file.writePage(parent); adjustTree(subtree.getParentPath()); } } } else { int[] splitAxis = { -1 }; // treatment of overflow: reinsertion or split N split = overflowTreatment(node, subtree, splitAxis); // node was split if(split != null) { // if the root was split: create a new root containing the two // split nodes if(node.getPageID() == getRootEntry().getEntryID()) { TreeIndexPath<E> newRootPath = createNewRoot(node, split, splitAxis[0]); height++; adjustTree(newRootPath); } // node is not root else { // get the parent and add the new split node N parent = getNode(subtree.getParentPath().getLastPathComponent().getEntry()); if(getLogger().isDebugging()) { getLogger().debugFine("parent " + parent); } E newEntry = createNewDirectoryEntry(split); parent.addDirectoryEntry(newEntry); // The below variant does not work in the persistent version // E oldEntry = subtree.getLastPathComponent().getEntry(); // [reason: if oldEntry is modified, this must be permanent] E oldEntry = parent.getEntry(subtree.getLastPathComponent().getIndex()); // adjust split history SplitHistory sh = ((SplitHistorySpatialEntry) oldEntry).getSplitHistory(); if(sh == null) { // not yet initialized (dimension not known of this tree) sh = new SplitHistory(oldEntry.getDimensionality()); sh.setDim(splitAxis[0]); ((SplitHistorySpatialEntry) oldEntry).setSplitHistory(sh); } else { ((SplitHistorySpatialEntry) oldEntry).addSplitDimension(splitAxis[0]); } try { ((SplitHistorySpatialEntry) newEntry).setSplitHistory((SplitHistory) sh.clone()); } catch(CloneNotSupportedException e) { throw new RuntimeException("Clone of a split history should not throw an Exception", e); } // adjust the entry representing the (old) node, that has // been split node.adjustEntry(oldEntry); // write changes in parent to file file.writePage(parent); adjustTree(subtree.getParentPath()); } } } } // no overflow, only adjust parameters of the entry representing the // node else { if(node.getPageID() != getRootEntry().getEntryID()) { N parent = getNode(subtree.getParentPath().getLastPathComponent().getEntry()); E e = parent.getEntry(subtree.getLastPathComponent().getIndex()); HyperBoundingBox mbr = e.getMBR(); node.adjustEntry(e); if(node.isLeaf() || // we already know that mbr is extended !mbr.equals(e.getMBR())) { // MBR has changed // write changes in parent to file file.writePage(parent); adjustTree(subtree.getParentPath()); } } // root level is reached else { node.adjustEntry(getRootEntry()); } } } /** * Creates a new root node that points to the two specified child nodes and * return the path to the new root. * * @param oldRoot the old root of this RTree * @param newNode the new split node * @param splitAxis the split axis used for the split causing this new root * @return the path to the new root node that points to the two specified * child nodes */ protected TreeIndexPath<E> createNewRoot(final N oldRoot, final N newNode, int splitAxis) { N root = createNewDirectoryNode(dirCapacity); file.writePage(root); // get split history SplitHistory sh = null; // TODO: see whether root entry is ALWAYS a directory entry .. it SHOULD! sh = ((XDirectoryEntry) getRootEntry()).getSplitHistory(); if(sh == null) { sh = new SplitHistory(oldRoot.getDimensionality()); } sh.setDim(splitAxis); // switch the ids oldRoot.setPageID(root.getPageID()); if(!oldRoot.isLeaf()) { // TODO: test whether this is neccessary for(int i = 0; i < oldRoot.getNumEntries(); i++) { N node = getNode(oldRoot.getEntry(i)); file.writePage(node); } } // adjust supernode id if(oldRoot.isSuperNode()) { supernodes.remove(new Long(getRootEntry().getEntryID())); supernodes.put(new Long(oldRoot.getPageID()), oldRoot); } root.setPageID(getRootEntry().getEntryID()); E oldRootEntry = createNewDirectoryEntry(oldRoot); E newNodeEntry = createNewDirectoryEntry(newNode); ((SplitHistorySpatialEntry) oldRootEntry).setSplitHistory(sh); try { ((SplitHistorySpatialEntry) newNodeEntry).setSplitHistory((SplitHistory) sh.clone()); } catch(CloneNotSupportedException e) { throw new RuntimeException("Clone of a split history should not throw an Exception", e); } root.addDirectoryEntry(oldRootEntry); root.addDirectoryEntry(newNodeEntry); file.writePage(root); file.writePage(oldRoot); file.writePage(newNode); if(getLogger().isDebugging()) { String msg = "Create new Root: ID=" + root.getPageID(); msg += "\nchild1 " + oldRoot + " " + oldRoot.mbr() + " " + oldRootEntry.getMBR(); msg += "\nchild2 " + newNode + " " + newNode.mbr() + " " + newNodeEntry.getMBR(); msg += "\n"; getLogger().debugFine(msg); } // the root entry still needs to be set to the new root node's MBR return new TreeIndexPath<E>(new TreeIndexPathComponent<E>(getRootEntry(), null)); } /** * Performs a k-nearest neighbor query for the given NumberVector with the * given parameter k and the according distance function. The query result is * in ascending order to the distance to the query object. * * @param object the query object * @param k the number of nearest neighbors to be returned * @param distanceFunction the distance function that computes the distances * between the objects * @return a List of the query results */ @Override public <D extends Distance<D>> List<DistanceResultPair<D>> kNNQuery(O object, int k, SpatialPrimitiveDistanceFunction<? super O, D> distanceFunction) { if(k < 1) { throw new IllegalArgumentException("At least one enumeration has to be requested!"); } final KNNHeap<D> knnList = new KNNHeap<D>(k, distanceFunction.getDistanceFactory().infiniteDistance()); doKNNQuery(object, distanceFunction, knnList); return knnList.toSortedArrayList(); } /** * Performs a k-nearest neighbor query for the given NumberVector with the * given parameter k (in <code>knnList</code>) and the according distance * function. The query result is in ascending order to the distance to the * query object. * * @param object the query object * @param distanceFunction the distance function that computes the distances * between the objects * @param knnList the knn list containing the result */ @Override protected <D extends Distance<D>> void doKNNQuery(O object, SpatialPrimitiveDistanceFunction<? super O, D> distanceFunction, KNNHeap<D> knnList) { // candidate queue PQ<D, Integer> pq = new PQ<D, Integer>(PriorityQueue.Ascending, QUEUE_INIT); // push root pq.add(distanceFunction.getDistanceFactory().nullDistance(), getRootEntry().getEntryID()); D maxDist = distanceFunction.getDistanceFactory().infiniteDistance(); // search in tree while(!pq.isEmpty()) { D dist = pq.firstPriority(); Integer firstID = pq.removeFirst(); if(dist.compareTo(maxDist) > 0) { return; } N node = getNode(firstID); // data node if(node.isLeaf()) { for(int i = 0; i < node.getNumEntries(); i++) { E entry = node.getEntry(i); D distance = distanceFunction.minDist(entry.getMBR(), object); distanceCalcs++; if(distance.compareTo(maxDist) <= 0) { knnList.add(new DistanceResultPair<D>(distance, ((LeafEntry)entry).getDBID())); maxDist = knnList.getKNNDistance(); } } } // directory node else { for(int i = 0; i < node.getNumEntries(); i++) { E entry = node.getEntry(i); D distance = distanceFunction.minDist(entry.getMBR(), object); distanceCalcs++; if(distance.compareTo(maxDist) <= 0) { pq.add(distance, entry.getEntryID()); } } } } } /** * Returns a string representation of this XTree. * * @return a string representation of this XTree */ @Override public String toString() { StringBuffer result = new StringBuffer(); long dirNodes = 0; long superNodes = 0; long leafNodes = 0; long objects = 0; long maxSuperCapacity = -1; long minSuperCapacity = Long.MAX_VALUE; BigInteger totalCapacity = BigInteger.ZERO; int levels = 0; if(file != null) { N node = getRoot(); while(!node.isLeaf()) { if(node.getNumEntries() > 0) { E entry = node.getEntry(0); node = getNode(entry); levels++; } } de.lmu.ifi.dbs.elki.index.tree.BreadthFirstEnumeration<O, N, E> enumeration = new de.lmu.ifi.dbs.elki.index.tree.BreadthFirstEnumeration<O, N, E>(this, getRootPath()); while(enumeration.hasMoreElements()) { TreeIndexPath<E> indexPath = enumeration.nextElement(); E entry = indexPath.getLastPathComponent().getEntry(); if(entry.isLeafEntry()) { objects++; } else { node = getNode(entry); if(node.isLeaf()) { leafNodes++; } else { if(node.isSuperNode()) { superNodes++; if(node.getCapacity() > maxSuperCapacity) { maxSuperCapacity = node.getCapacity(); } if(node.getCapacity() < minSuperCapacity) { minSuperCapacity = node.getCapacity(); } } else { dirNodes++; } } totalCapacity = totalCapacity.add(BigInteger.valueOf(node.getCapacity())); } } assert objects == num_elements : "objects=" + objects + ", size=" + num_elements; result.append(getClass().getName()).append(" has ").append((levels + 1)).append(" levels.\n"); result.append(dirNodes).append(" Directory Nodes (max = ").append(dirCapacity - 1).append(", min = ").append(dirMinimum).append(")\n"); result.append(superNodes).append(" Supernodes (max = ").append(maxSuperCapacity - 1).append(", min = ").append(minSuperCapacity - 1).append(")\n"); result.append(leafNodes).append(" Data Nodes (max = ").append(leafCapacity - 1).append(", min = ").append(leafMinimum).append(")\n"); result.append(objects).append(" ").append(dimensionality).append("-dim. points in the tree \n"); result.append("min_fanout = ").append(min_fanout).append(", max_overlap = ").append(max_overlap).append((this.overlap_type == DATA_OVERLAP ? " data overlap" : " volume overlap")).append(", re_inserts = ").append(reinsert_fraction + "\n"); result.append("Read I/O-Access: ").append(file.getPhysicalReadAccess()).append("\n"); result.append("Write I/O-Access: ").append(file.getPhysicalWriteAccess()).append("\n"); result.append("Logical Page-Access: ").append(file.getLogicalPageAccess()).append("\n"); result.append("File ").append(getFileName()).append("\n"); result.append("Storage Quota ").append(BigInteger.valueOf(objects + dirNodes + superNodes + leafNodes).multiply(BigInteger.valueOf(100)).divide(totalCapacity).toString()).append("%\n"); } else { result.append(getClass().getName()).append(" is empty!\n"); } return result.toString(); } }
package org.voltcore.messaging; import java.net.InetSocketAddress; import java.net.SocketException; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Queue; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.apache.zookeeper_voltpatches.CreateMode; import org.apache.zookeeper_voltpatches.ZooDefs.Ids; import org.apache.zookeeper_voltpatches.ZooKeeper; import org.json_voltpatches.JSONArray; import org.json_voltpatches.JSONObject; import org.json_voltpatches.JSONStringer; import org.voltcore.agreement.AgreementSite; import org.voltcore.agreement.InterfaceToMessenger; import org.voltcore.logging.VoltLogger; import org.voltcore.network.VoltNetworkPool; import org.voltcore.utils.COWMap; import org.voltcore.utils.COWNavigableSet; import org.voltcore.utils.CoreUtils; import org.voltcore.utils.InstanceId; import org.voltcore.utils.PortGenerator; import org.voltcore.zk.CoreZK; import org.voltcore.zk.ZKUtil; import org.voltdb.VoltDB; import org.voltdb.utils.MiscUtils; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.google.common.primitives.Longs; /** * Host messenger contains all the code necessary to join a cluster mesh, and create mailboxes * that are addressable from anywhere within that mesh. Host messenger also provides * a ZooKeeper instance that is maintained within the mesh that can be used for distributed coordination * and failure detection. */ public class HostMessenger implements SocketJoiner.JoinHandler, InterfaceToMessenger { private static final VoltLogger logger = new VoltLogger("NETWORK"); /** * Configuration for a host messenger. The leader binds to the coordinator ip and * not the internal interface or port. Nodes that fail to become the leader will * connect to the leader using any interface, and will then advertise using the specified * internal interface/port. * * By default all interfaces are used, if one is specified then only that interface will be used. * */ public static class Config { public InetSocketAddress coordinatorIp; public String zkInterface = "127.0.0.1:2181"; public String internalInterface = ""; public int internalPort = 3021; public int deadHostTimeout = 90 * 1000; public long backwardsTimeForgivenessWindow = 1000 * 60 * 60 * 24 * 7; public VoltMessageFactory factory = new VoltMessageFactory(); public int networkThreads = Math.max(2, CoreUtils.availableProcessors() / 4); public Queue<String> coreBindIds; public Config(String coordIp, int coordPort) { if (coordIp == null || coordIp.length() == 0) { coordinatorIp = new InetSocketAddress(coordPort); } else { coordinatorIp = new InetSocketAddress(coordIp, coordPort); } initNetworkThreads(); } public Config() { this(null, 3021); } public Config(PortGenerator ports) { this(null, 3021); zkInterface = "127.0.0.1:" + ports.next(); internalPort = ports.next(); } public int getZKPort() { return MiscUtils.getPortFromHostnameColonPort(zkInterface, VoltDB.DEFAULT_ZK_PORT); } private void initNetworkThreads() { try { logger.info("Default network thread count: " + this.networkThreads); Integer networkThreadConfig = Integer.getInteger("networkThreads"); if ( networkThreadConfig != null ) { this.networkThreads = networkThreadConfig; logger.info("Overridden network thread count: " + this.networkThreads); } } catch (Exception e) { logger.error("Error setting network thread count", e); } } @Override public String toString() { JSONStringer js = new JSONStringer(); try { js.object(); js.key("coordinatorip").value(coordinatorIp.toString()); js.key("zkinterface").value(zkInterface); js.key("internalinterface").value(internalInterface); js.key("internalport").value(internalPort); js.key("deadhosttimeout").value(deadHostTimeout); js.key("backwardstimeforgivenesswindow").value(backwardsTimeForgivenessWindow); js.key("networkThreads").value(networkThreads); js.endObject(); return js.toString(); } catch (Exception e) { throw new RuntimeException(e); } } } private static final VoltLogger m_logger = new VoltLogger("org.voltdb.messaging.impl.HostMessenger"); private static final VoltLogger hostLog = new VoltLogger("HOST"); // I want to make these more dynamic at some point in the future --izzy public static final int AGREEMENT_SITE_ID = -1; public static final int STATS_SITE_ID = -2; public static final int ASYNC_COMPILER_SITE_ID = -3; public static final int CLIENT_INTERFACE_SITE_ID = -4; public static final int SYSCATALOG_SITE_ID = -5; public static final int SYSINFO_SITE_ID = -6; public static final int SNAPSHOTSCAN_SITE_ID = -7; public static final int SNAPSHOTDELETE_SITE_ID = -8; public static final int REBALANCE_SITE_ID = -9; // we should never hand out this site ID. Use it as an empty message destination public static final int VALHALLA = Integer.MIN_VALUE; int m_localHostId; private final Config m_config; private final SocketJoiner m_joiner; private final VoltNetworkPool m_network; private volatile boolean m_localhostReady = false; // memoized InstanceId private InstanceId m_instanceId = null; /* * References to other hosts in the mesh. * Updates via COW */ final COWMap<Integer, ForeignHost> m_foreignHosts = new COWMap<Integer, ForeignHost>(); /* * References to all the local mailboxes * Updates via COW */ final COWMap<Long, Mailbox> m_siteMailboxes = new COWMap<Long, Mailbox>(); /* * All failed hosts that have ever been seen. * Used to dedupe failures so that they are only processed once. */ private final COWNavigableSet<Integer> m_knownFailedHosts = new COWNavigableSet<Integer>(); private AgreementSite m_agreementSite; private ZooKeeper m_zk; private final AtomicInteger m_nextSiteId = new AtomicInteger(0); public Mailbox getMailbox(long hsId) { return m_siteMailboxes.get(hsId); } /** * * @param network * @param coordinatorIp * @param expectedHosts * @param catalogCRC * @param hostLog */ public HostMessenger( Config config) { m_config = config; m_network = new VoltNetworkPool( m_config.networkThreads, m_config.coreBindIds); m_joiner = new SocketJoiner( m_config.coordinatorIp, m_config.internalInterface, m_config.internalPort, this); } private final DisconnectFailedHostsCallback m_failedHostsCallback = new DisconnectFailedHostsCallback() { @Override public void disconnect(Set<Integer> failedHostIds) { synchronized(HostMessenger.this) { for (int hostId: failedHostIds) { m_knownFailedHosts.add(hostId); removeForeignHost(hostId); logger.warn(String.format("Host %d failed", hostId)); } } } }; /** * Synchronization protects m_knownFailedHosts and ensures that every failed host is only reported * once */ @Override public synchronized void reportForeignHostFailed(int hostId) { long initiatorSiteId = CoreUtils.getHSIdFromHostAndSite(hostId, AGREEMENT_SITE_ID); m_agreementSite.reportFault(initiatorSiteId); logger.warn(String.format("Host %d failed", hostId)); } @Override public synchronized void relayForeignHostFailed(FaultMessage fm) { m_agreementSite.reportFault(fm); m_logger.warn("Someone else claims a host failed: " + fm); } /** * Start the host messenger and connect to the leader, or become the leader * if necessary. */ public void start() throws Exception { /* * SJ uses this barrier if this node becomes the leader to know when ZooKeeper * has been finished bootstrapping. */ CountDownLatch zkInitBarrier = new CountDownLatch(1); /* * If start returns true then this node is the leader, it bound to the coordinator address * It needs to bootstrap its agreement site so that other nodes can join */ if(m_joiner.start(zkInitBarrier)) { m_network.start(); /* * m_localHostId is 0 of course. */ long agreementHSId = getHSIdForLocalSite(AGREEMENT_SITE_ID); /* * A set containing just the leader (this node) */ HashSet<Long> agreementSites = new HashSet<Long>(); agreementSites.add(agreementHSId); /* * A basic site mailbox for the agreement site */ SiteMailbox sm = new SiteMailbox(this, agreementHSId); createMailbox(agreementHSId, sm); /* * Construct the site with just this node */ m_agreementSite = new AgreementSite( agreementHSId, agreementSites, 0, sm, new InetSocketAddress( m_config.zkInterface.split(":")[0], Integer.parseInt(m_config.zkInterface.split(":")[1])), m_config.backwardsTimeForgivenessWindow, m_failedHostsCallback); m_agreementSite.start(); m_agreementSite.waitForRecovery(); m_zk = org.voltcore.zk.ZKUtil.getClient( m_config.zkInterface, 60 * 1000, ImmutableSet.<Long>copyOf(m_network.getThreadIds())); if (m_zk == null) { throw new Exception("Timed out trying to connect local ZooKeeper instance"); } CoreZK.createHierarchy(m_zk); /* * This creates the ephemeral sequential node with host id 0 which * this node already used for itself. Just recording that fact. */ final int selectedHostId = selectNewHostId(m_config.coordinatorIp.toString()); if (selectedHostId != 0) { org.voltdb.VoltDB.crashLocalVoltDB("Selected host id for coordinator was not 0, " + selectedHostId, false, null); } // Store the components of the instance ID in ZK JSONObject instance_id = new JSONObject(); instance_id.put("coord", ByteBuffer.wrap(m_config.coordinatorIp.getAddress().getAddress()).getInt()); instance_id.put("timestamp", System.currentTimeMillis()); hostLog.debug("Cluster will have instance ID:\n" + instance_id.toString(4)); byte[] payload = instance_id.toString(4).getBytes("UTF-8"); m_zk.create(CoreZK.instance_id, payload, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); /* * Store all the hosts and host ids here so that waitForGroupJoin * knows the size of the mesh. This part only registers this host */ byte hostInfoBytes[] = m_config.coordinatorIp.toString().getBytes("UTF-8"); m_zk.create(CoreZK.hosts_host + selectedHostId, hostInfoBytes, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); } zkInitBarrier.countDown(); } //For test only protected HostMessenger() { this(new Config()); } /* * The network is only available after start() finishes */ public VoltNetworkPool getNetwork() { return m_network; } public VoltMessageFactory getMessageFactory() { return m_config.factory; } /** * Get a unique ID for this cluster * @return */ public InstanceId getInstanceId() { if (m_instanceId == null) { try { byte[] data = m_zk.getData(CoreZK.instance_id, false, null); JSONObject idJSON = new JSONObject(new String(data, "UTF-8")); m_instanceId = new InstanceId(idJSON.getInt("coord"), idJSON.getLong("timestamp")); } catch (Exception e) { String msg = "Unable to get instance ID info from " + CoreZK.instance_id; hostLog.error(msg); throw new RuntimeException(msg, e); } } return m_instanceId; } /* * Take the new connection (member of the mesh) and create a foreign host for it * and put it in the map of foreign hosts */ @Override public void notifyOfJoin(int hostId, SocketChannel socket, InetSocketAddress listeningAddress) { logger.info(getHostId() + " notified of " + hostId); prepSocketChannel(socket); ForeignHost fhost = null; try { fhost = new ForeignHost(this, hostId, socket, m_config.deadHostTimeout, listeningAddress); fhost.register(this); putForeignHost(hostId, fhost); fhost.enableRead(); } catch (java.io.IOException e) { org.voltdb.VoltDB.crashLocalVoltDB("", true, e); } } /* * Set all the default options for sockets */ private void prepSocketChannel(SocketChannel sc) { try { sc.socket().setSendBufferSize(1024*1024*2); sc.socket().setReceiveBufferSize(1024*1024*2); } catch (SocketException e) { e.printStackTrace(); } } /* * Convenience method for doing the verbose COW insert into the map */ private void putForeignHost(int hostId, ForeignHost fh) { m_foreignHosts.put(hostId, fh); } /* * Convenience method for doing the verbose COW remove from the map */ private void removeForeignHost(int hostId) { ForeignHost fh = m_foreignHosts.remove(hostId); if (fh != null) { fh.close(); } } /* * Any node can serve a request to join. The coordination of generating a new host id * is done via ZK */ @Override public void requestJoin(SocketChannel socket, InetSocketAddress listeningAddress) throws Exception { /* * Generate the host id via creating an ephemeral sequential node */ Integer hostId = selectNewHostId(socket.socket().getInetAddress().getHostAddress()); prepSocketChannel(socket); ForeignHost fhost = null; try { try { /* * Write the response that advertises the cluster topology */ writeRequestJoinResponse( hostId, socket); /* * Wait for the a response from the joining node saying that it connected * to all the nodes we just advertised. Use a timeout so that the cluster can't be stuck * on failed joins. */ ByteBuffer finishedJoining = ByteBuffer.allocate(1); socket.configureBlocking(false); long start = System.currentTimeMillis(); while (finishedJoining.hasRemaining() && System.currentTimeMillis() - start < 120000) { int read = socket.read(finishedJoining); if (read == -1) { hostLog.info("New connection was unable to establish mesh"); return; } else if (read < 1) { Thread.sleep(5); } } /* * Now add the host to the mailbox system */ fhost = new ForeignHost(this, hostId, socket, m_config.deadHostTimeout, listeningAddress); fhost.register(this); putForeignHost(hostId, fhost); fhost.enableRead(); } catch (Exception e) { logger.error("Error joining new node", e); m_knownFailedHosts.add(hostId); removeForeignHost(hostId); return; } /* * And the last step is to wait for the new node to join ZooKeeper. * This node is the one to create the txn that will add the new host to the list of hosts * with agreement sites across the cluster. */ long hsId = CoreUtils.getHSIdFromHostAndSite(hostId, AGREEMENT_SITE_ID); if (!m_agreementSite.requestJoin(hsId).await(60, TimeUnit.SECONDS)) { reportForeignHostFailed(hostId); } } catch (Throwable e) { org.voltdb.VoltDB.crashLocalVoltDB("", true, e); } } /* * Generate a new host id by creating a persistent sequential node */ private Integer selectNewHostId(String address) throws Exception { String node = m_zk.create(CoreZK.hostids_host, address.getBytes("UTF-8"), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL); return Integer.valueOf(node.substring(node.length() - 10)); } /* * Advertise to a newly connecting node the topology of the cluster so that it can connect to * the rest of the nodes */ private void writeRequestJoinResponse(int hostId, SocketChannel socket) throws Exception { JSONObject jsObj = new JSONObject(); /* * Tell the new node what its host id is */ jsObj.put("newHostId", hostId); /* * Echo back the address that the node connected from */ jsObj.put("reportedAddress", ((InetSocketAddress)socket.socket().getRemoteSocketAddress()).getAddress().getHostAddress()); /* * Create an array containing an ad for every node including this one * even though the connection has already been made */ JSONArray jsArray = new JSONArray(); JSONObject hostObj = new JSONObject(); hostObj.put("hostId", getHostId()); hostObj.put("address", m_config.internalInterface.isEmpty() ? socket.socket().getLocalAddress().getHostAddress() : m_config.internalInterface); hostObj.put("port", m_config.internalPort); jsArray.put(hostObj); for (Map.Entry<Integer, ForeignHost> entry : m_foreignHosts.entrySet()) { if (entry.getValue() == null) continue; int hsId = entry.getKey(); ForeignHost fh = entry.getValue(); hostObj = new JSONObject(); hostObj.put("hostId", hsId); hostObj.put("address", fh.m_listeningAddress.getAddress().getHostAddress()); hostObj.put("port", fh.m_listeningAddress.getPort()); jsArray.put(hostObj); } jsObj.put("hosts", jsArray); byte messageBytes[] = jsObj.toString(4).getBytes("UTF-8"); ByteBuffer message = ByteBuffer.allocate(4 + messageBytes.length); message.putInt(messageBytes.length); message.put(messageBytes).flip(); while (message.hasRemaining()) { socket.write(message); } } /* * SJ invokes this method after a node finishes connecting to the entire cluster. * This method constructs all the hosts and puts them in the map */ @Override public void notifyOfHosts( int yourHostId, int[] hosts, SocketChannel[] sockets, InetSocketAddress listeningAddresses[]) throws Exception { m_localHostId = yourHostId; long agreementHSId = getHSIdForLocalSite(AGREEMENT_SITE_ID); /* * Construct the set of agreement sites based on all the hosts that are connected */ HashSet<Long> agreementSites = new HashSet<Long>(); agreementSites.add(agreementHSId); m_network.start();//network must be running for register to work for (int ii = 0; ii < hosts.length; ii++) { logger.info(yourHostId + " notified of host " + hosts[ii]); agreementSites.add(CoreUtils.getHSIdFromHostAndSite(hosts[ii], AGREEMENT_SITE_ID)); prepSocketChannel(sockets[ii]); ForeignHost fhost = null; try { fhost = new ForeignHost(this, hosts[ii], sockets[ii], m_config.deadHostTimeout, listeningAddresses[ii]); fhost.register(this); putForeignHost(hosts[ii], fhost); } catch (java.io.IOException e) { org.voltdb.VoltDB.crashLocalVoltDB("", true, e); } } /* * Create the local agreement site. It knows that it is recovering because the number of * prexisting sites is > 0 */ SiteMailbox sm = new SiteMailbox(this, agreementHSId); createMailbox(agreementHSId, sm); m_agreementSite = new AgreementSite( agreementHSId, agreementSites, yourHostId, sm, new InetSocketAddress( m_config.zkInterface.split(":")[0], Integer.parseInt(m_config.zkInterface.split(":")[1])), m_config.backwardsTimeForgivenessWindow, m_failedHostsCallback); /* * Now that the agreement site mailbox has been created it is safe * to enable read */ for (ForeignHost fh : m_foreignHosts.values()) { fh.enableRead(); } m_agreementSite.start(); /* * Do the usual thing of waiting for the agreement site * to join the cluster and creating the client */ ImmutableSet.Builder<Long> verbotenThreadBuilder = ImmutableSet.<Long>builder(); verbotenThreadBuilder.addAll(m_network.getThreadIds()); verbotenThreadBuilder.addAll(m_agreementSite.getThreadIds()); m_agreementSite.waitForRecovery(); m_zk = org.voltcore.zk.ZKUtil.getClient( m_config.zkInterface, 60 * 1000, verbotenThreadBuilder.build()); if (m_zk == null) { throw new Exception("Timed out trying to connect local ZooKeeper instance"); } /* * Publish the address of this node to ZK as seen by the leader * Also allows waitForGroupJoin to know the number of nodes in the cluster */ byte hostInfoBytes[]; if (m_config.internalInterface.isEmpty()) { InetSocketAddress addr = new InetSocketAddress(m_joiner.m_reportedInternalInterface, m_config.internalPort); hostInfoBytes = addr.toString().getBytes("UTF-8"); } else { InetSocketAddress addr = new InetSocketAddress(m_config.internalInterface, m_config.internalPort); hostInfoBytes = addr.toString().getBytes("UTF-8"); } m_zk.create(CoreZK.hosts_host + getHostId(), hostInfoBytes, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); } /** * Wait until all the nodes have built a mesh. */ public void waitForGroupJoin(int expectedHosts) { try { while (true) { ZKUtil.FutureWatcher fw = new ZKUtil.FutureWatcher(); final int numChildren = m_zk.getChildren(CoreZK.hosts, fw).size(); /* * If the target number of hosts has been reached * break out */ if ( numChildren == expectedHosts) { break; } /* * If there are extra hosts that means too many Volt procs were started. * Kill this node based on the assumption that we are the extra one. In most * cases this is correct and fine and in the worst case the cluster will hang coming up * because two or more hosts killed themselves */ if ( numChildren > expectedHosts) { org.voltdb.VoltDB.crashLocalVoltDB("Expected to find " + expectedHosts + " hosts in cluster at startup but found " + numChildren + ". Terminating this host.", false, null); } fw.get(); } } catch (Exception e) { org.voltdb.VoltDB.crashLocalVoltDB("Error waiting for hosts to be ready", false, e); } } public int getHostId() { return m_localHostId; } public long getHSIdForLocalSite(int site) { return CoreUtils.getHSIdFromHostAndSite(getHostId(), site); } public String getHostname() { String hostname = org.voltcore.utils.CoreUtils.getHostnameOrAddress(); return hostname; } public List<Integer> getLiveHostIds() { List<Integer> hostids = new ArrayList<Integer>(); hostids.addAll(m_foreignHosts.keySet()); hostids.add(m_localHostId); return hostids; } /** * Given a hostid, return the hostname for it */ @Override public String getHostnameForHostID(int hostId) { ForeignHost fh = m_foreignHosts.get(hostId); return fh == null ? "UNKNOWN" : fh.hostname(); } /** * * @param siteId * @param mailboxId * @param message * @return null if message was delivered locally or a ForeignHost * reference if a message is read to be delivered remotely. */ ForeignHost presend(long hsId, VoltMessage message) { int hostId = (int)hsId; // the local machine case if (hostId == m_localHostId) { Mailbox mbox = m_siteMailboxes.get(hsId); if (mbox != null) { mbox.deliver(message); return null; } else { hostLog.info("Mailbox is not registered for site id " + CoreUtils.getSiteIdFromHSId(hsId)); return null; } } // the foreign machine case ForeignHost fhost = m_foreignHosts.get(hostId); if (fhost == null) { if (!m_knownFailedHosts.contains(hostId)) { hostLog.warn( "Attempted to send a message to foreign host with id " + hostId + " but there is no such host."); } return null; } if (!fhost.isUp()) { //Throwable t = new Throwable(); //java.io.StringWriter sw = new java.io.StringWriter(); //java.io.PrintWriter pw = new java.io.PrintWriter(sw); //t.printStackTrace(pw); //pw.flush(); m_logger.warn("Attempted delivery of message to failed site: " + CoreUtils.hsIdToString(hsId)); //m_logger.warn(sw.toString()); return null; } return fhost; } public void registerMailbox(Mailbox mailbox) { if (!m_siteMailboxes.containsKey(mailbox.getHSId())) { throw new RuntimeException("Can only register a mailbox with an hsid alreadly generated"); } m_siteMailboxes.put(mailbox.getHSId(), mailbox); } /* * Generate a slot for the mailbox and put a noop box there. Can also * supply a value */ public long generateMailboxId(Long mailboxId) { final long hsId = mailboxId == null ? getHSIdForLocalSite(m_nextSiteId.getAndIncrement()) : mailboxId; m_siteMailboxes.put(hsId, new Mailbox() { @Override public void send(long hsId, VoltMessage message) {} @Override public void send(long[] hsIds, VoltMessage message) {} @Override public void deliver(VoltMessage message) { hostLog.info("No-op mailbox(" + CoreUtils.hsIdToString(hsId) + ") dropped message " + message); } @Override public void deliverFront(VoltMessage message) {} @Override public VoltMessage recv() {return null;} @Override public VoltMessage recvBlocking() {return null;} @Override public VoltMessage recvBlocking(long timeout) {return null;} @Override public VoltMessage recv(Subject[] s) {return null;} @Override public VoltMessage recvBlocking(Subject[] s) {return null;} @Override public VoltMessage recvBlocking(Subject[] s, long timeout) { return null;} @Override public long getHSId() {return 0L;} @Override public void setHSId(long hsId) {} }); return hsId; } /* * Create a site mailbox with a generated host id */ public Mailbox createMailbox() { final int siteId = m_nextSiteId.getAndIncrement(); long hsId = getHSIdForLocalSite(siteId); SiteMailbox sm = new SiteMailbox( this, hsId); m_siteMailboxes.put(hsId, sm); return sm; } /** * Discard a mailbox */ public void removeMailbox(long hsId) { m_siteMailboxes.remove(hsId); } public void send(final long destinationHSId, final VoltMessage message) { assert(message != null); ForeignHost host = presend(destinationHSId, message); if (host != null) { host.send(new long [] { destinationHSId }, message); } } public void send(long[] destinationHSIds, final VoltMessage message) { assert(message != null); assert(destinationHSIds != null); final HashMap<ForeignHost, ArrayList<Long>> foreignHosts = new HashMap<ForeignHost, ArrayList<Long>>(32); for (long hsId : destinationHSIds) { ForeignHost host = presend(hsId, message); if (host == null) continue; ArrayList<Long> bundle = foreignHosts.get(host); if (bundle == null) { bundle = new ArrayList<Long>(); foreignHosts.put(host, bundle); } bundle.add(hsId); } if (foreignHosts.size() == 0) return; for (Entry<ForeignHost, ArrayList<Long>> e : foreignHosts.entrySet()) { e.getKey().send(Longs.toArray(e.getValue()), message); } } /** * Block on this call until the number of ready hosts is * equal to the number of expected hosts. * * @return True if returning with all hosts ready. False if error. */ public void waitForAllHostsToBeReady(int expectedHosts) { m_localhostReady = true; try { m_zk.create(CoreZK.readyhosts_host, null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); while (true) { ZKUtil.FutureWatcher fw = new ZKUtil.FutureWatcher(); if (m_zk.getChildren(CoreZK.readyhosts, fw).size() == expectedHosts) { break; } fw.get(); } } catch (Exception e) { org.voltdb.VoltDB.crashLocalVoltDB("Error waiting for hosts to be ready", false, e); } } public synchronized boolean isLocalHostReady() { return m_localhostReady; } public void shutdown() throws InterruptedException { m_zk.close(); m_agreementSite.shutdown(); for (ForeignHost host : m_foreignHosts.values()) { // null is OK. It means this host never saw this host id up if (host != null) { host.close(); } } m_joiner.shutdown(); m_network.shutdown(); } /* * Register a custom mailbox, optinally specifying what the hsid should be. */ public void createMailbox(Long proposedHSId, Mailbox mailbox) { long hsId = 0; if (proposedHSId != null) { if (m_siteMailboxes.containsKey(proposedHSId)) { org.voltdb.VoltDB.crashLocalVoltDB( "Attempted to create a mailbox for site " + CoreUtils.hsIdToString(proposedHSId) + " twice", true, null); } hsId = proposedHSId; } else { hsId = getHSIdForLocalSite(m_nextSiteId.getAndIncrement()); mailbox.setHSId(hsId); } m_siteMailboxes.put(hsId, mailbox); } /** * Get the number of up foreign hosts. Used for test purposes. * @return The number of up foreign hosts. */ public int countForeignHosts() { int retval = 0; for (ForeignHost host : m_foreignHosts.values()) if ((host != null) && (host.isUp())) retval++; return retval; } /** * Kill a foreign host socket by id. * @param hostId The id of the foreign host to kill. */ public void closeForeignHostSocket(int hostId) { ForeignHost fh = m_foreignHosts.get(hostId); if (fh != null && fh.isUp()) { fh.killSocket(); } reportForeignHostFailed(hostId); } public ZooKeeper getZK() { return m_zk; } public void sendPoisonPill(String err) { for (ForeignHost fh : m_foreignHosts.values()) { if (fh != null && fh.isUp()) { fh.sendPoisonPill(err); } } } public boolean validateForeignHostId(Integer hostId) { return !m_knownFailedHosts.contains(hostId); } public void setDeadHostTimeout(int timeout) { Preconditions.checkArgument(timeout > 0, "Timeout value must be > 0, was %s", timeout); hostLog.info("Dead host timeout set to " + timeout + " milliseconds"); m_config.deadHostTimeout = timeout; for (ForeignHost fh : m_foreignHosts.values()) { fh.updateDeadHostTimeout(timeout); } } }
package com.leavjenn.hews; public final class Constants { public static final String KEY_ID = "id"; public static final String KEY_DELETED = "deleted"; public static final String KEY_BY = "by"; public static final String KEY_PARENT = "parent"; public static final String KEY_KIDS = "kids"; public static final String KEY_DESC = "descendants"; public static final String KEY_SCORE = "score"; public static final String KEY_TIME = "time"; public static final String KEY_TITLE = "title"; public static final String KEY_TYPE = "type"; public static final String KEY_URL = "url"; public static final String KEY_TEXT = "text"; public static final String KEY_ERROR = "error"; public static final String KEY_POST = "post"; public static final String YCOMBINATOR_ITEM_URL = "https://news.ycombinator.com/item?id="; public static final String TYPE_SEARCH = "search"; public static final String TYPE_STORY = "type_story"; public static final String STORY_TYPE_TOP_URL = "https://hacker-news.firebaseio.com/v0/topstories"; public static final String STORY_TYPE_NEW_URL = "https://hacker-news.firebaseio.com/v0/newstories"; public static final String STORY_TYPE_ASK_HN_URL = "https://hacker-news.firebaseio.com/v0/askstories"; public static final String STORY_TYPE_SHOW_HN_URL = "https://hacker-news.firebaseio.com/v0/showstories"; public static final String KEY_API_URL = "https://hacker-news.firebaseio.com/v0"; public static final String KEY_ITEM_URL = "https://hacker-news.firebaseio.com/v0/item/"; public static final String SEARCH_BASE_URL = "https://hn.algolia.com/api/v1/"; public final static int NUM_LOADING_ITEM = 25; public final static int LOADING_IDLE = 0; public final static int LOADING_IN_PROGRESS = 1; public final static int LOADING_FINISH = 2; public final static int LOADING_ERROR = 3; public final static int LOADING_PROMPT_NO_CONTENT = 4; }
package gov.nih.nci.calab.dto.search; import gov.nih.nci.calab.service.util.SpecialCharReplacer; import javax.servlet.jsp.PageContext; import org.displaytag.decorator.DisplaytagColumnDecorator; import org.displaytag.exception.DecoratorException; import org.displaytag.properties.MediaTypeEnum; /** * This decorator is used to for display tag to correctly display dynamic links on files * @author pansu * */ public class FileURLDecorator implements DisplaytagColumnDecorator { public Object decorate(Object arg0, PageContext arg1, MediaTypeEnum arg2) throws DecoratorException { WorkflowResultBean workflow = (WorkflowResultBean) arg0; String assayType = workflow.getAssay().getAssayType(); String assayName = workflow.getAssay().getAssayName(); String runName = workflow.getRun().getName(); SpecialCharReplacer specialCharReplacer = new SpecialCharReplacer(); assayType = specialCharReplacer.getReplacedString(assayType); assayName = specialCharReplacer.getReplacedString(assayName); runName = specialCharReplacer.getReplacedString(runName); String fileURL = "runFile.do?dispatch=downloadFile&fileName=" + workflow.getFile().getFilename() + "&runId=" + workflow.getRun().getId() + "&inout=" + workflow.getFile().getInoutType(); String link = "<a href=" + fileURL + ">" + workflow.getFile().getShortFilename() + "<br>" + workflow.getFile().getTimePrefix() + "</a>"; return link; } }
package org.loofer.retrofit; import android.content.Context; import android.support.annotation.NonNull; import android.util.Log; import com.google.gson.Gson; import com.google.gson.JsonParseException; import org.loofer.retrofit.cache.CookieCacheImpl; import org.loofer.retrofit.config.ConfigLoader; import org.loofer.retrofit.cookie.CookieManager; import org.loofer.retrofit.cookie.SharedPrefsCookiePersistor; import org.loofer.retrofit.download.DownLoadCallBack; import org.loofer.retrofit.download.DownSubscriber; import org.loofer.retrofit.exception.ApiException; import org.loofer.retrofit.exception.FormatException; import org.loofer.retrofit.exception.ServerException; import org.loofer.retrofit.request.Request; import org.loofer.retrofit.utils.FileUtil; import org.loofer.retrofit.utils.Utils; import java.io.File; import java.io.InputStream; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.net.Proxy; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSocketFactory; import okhttp3.Cache; import okhttp3.CertificatePinner; import okhttp3.ConnectionPool; import okhttp3.HttpUrl; import okhttp3.Interceptor; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.RequestBody; import okhttp3.ResponseBody; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Call; import retrofit2.CallAdapter; import retrofit2.Converter; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.http.FieldMap; import retrofit2.http.Part; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers; public final class Factory { private static Map<String, String> headers; private static Map<String, String> parameters; private static Retrofit.Builder retrofitBuilder; private static Retrofit retrofit; private static OkHttpClient.Builder okhttpBuilder; public static BaseApiService apiManager; private static OkHttpClient okHttpClient; private static Context mContext; private final okhttp3.Call.Factory callFactory; private final String baseUrl; private final List<Converter.Factory> converterFactories; private final List<CallAdapter.Factory> adapterFactories; private final Executor callbackExecutor; private final boolean validateEagerly; private Observable<ResponseBody> downObservable; private Map<String, Observable<ResponseBody>> downMaps = new HashMap<String, Observable<ResponseBody>>() { }; private Observable.Transformer exceptTransformer = null; public static final String TAG = "Novate"; /** * Mandatory constructor for the Novate */ Factory(okhttp3.Call.Factory callFactory, String baseUrl, Map<String, String> headers, Map<String, String> parameters, BaseApiService apiManager, List<Converter.Factory> converterFactories, List<CallAdapter.Factory> adapterFactories, Executor callbackExecutor, boolean validateEagerly) { this.callFactory = callFactory; this.baseUrl = baseUrl; this.headers = headers; this.parameters = parameters; this.apiManager = apiManager; this.converterFactories = converterFactories; this.adapterFactories = adapterFactories; this.callbackExecutor = callbackExecutor; this.validateEagerly = validateEagerly; } /** * create ApiService */ public <T> T create(final Class<T> service) { return retrofit.create(service); } /** * @param subscriber */ public <T> T call(Observable<T> observable, Subscriber<T> subscriber) { return (T) observable.compose(schedulersTransformer) .compose(handleErrTransformer()) .subscribe(subscriber); } /** * @param subscriber */ public <T> T execute(Request request, Subscriber<T> subscriber) { return handleCall(request, subscriber); } private <T> T handleCall(Request request, Subscriber<T> subscriber) { //todo dev return null; } /** * Novate execute get * <p> * return parsed data * <p> * you don't need to parse ResponseBody */ public <T> T executeGet(final String url, final Map<String, Object> maps, final ResponseCallBack<T> callBack) { final Type[] types = callBack.getClass().getGenericInterfaces(); if (MethodHandler(types) == null || MethodHandler(types).size() == 0) { return null; } final Type finalNeedType = MethodHandler(types).get(0); Log.d(TAG, "-->:" + "Type:" + types[0]); return (T) apiManager.executeGet(url, maps) .compose(schedulersTransformer) .compose(handleErrTransformer()) .subscribe(new ApiSubscriber<T>(mContext, finalNeedType, callBack)); } /** * MethodHandler */ private List<Type> MethodHandler(Type[] types) { Log.d(TAG, "types size: " + types.length); List<Type> needtypes = new ArrayList<>(); Type needParentType = null; for (Type paramType : types) { System.out.println(" " + paramType); // if Type is T if (paramType instanceof ParameterizedType) { Type[] parentypes = ((ParameterizedType) paramType).getActualTypeArguments(); Log.d(TAG, "TypeArgument: "); for (Type childtype : parentypes) { Log.d(TAG, "childtype:" + childtype); needtypes.add(childtype); //needParentType = childtype; if (childtype instanceof ParameterizedType) { Type[] childtypes = ((ParameterizedType) childtype).getActualTypeArguments(); for (Type type : childtypes) { needtypes.add(type); //needChildType = type; Log.d(TAG, "type:" + childtype); } } } } } return needtypes; } final Observable.Transformer schedulersTransformer = new Observable.Transformer() { @Override public Object call(Object observable) { return ((Observable) observable).subscribeOn(Schedulers.io()) .unsubscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); } }; final Observable.Transformer schedulersTransformerDown = new Observable.Transformer() { @Override public Object call(Object observable) { return ((Observable) observable).subscribeOn(Schedulers.io()) .unsubscribeOn(Schedulers.io()) .observeOn(Schedulers.io()); } }; /** * @param <T> * @return */ public <T> Observable.Transformer<HttpResult<T>, T> handleErrTransformer() { if (exceptTransformer != null) return exceptTransformer; else return exceptTransformer = new Observable.Transformer() { @Override public Object call(Object observable) { return ((Observable) observable) //.map(new HandleFuc<T>()) .onErrorResumeNext(new HttpResponseFunc<T>()); } }; } private static class HttpResponseFunc<T> implements Func1<java.lang.Throwable, Observable<T>> { @Override public Observable<T> call(java.lang.Throwable t) { return Observable.error(ApiException.handleException(t)); } } private class HandleFuc<T> implements Func1<HttpResult<T>, T> { @Override public T call(HttpResult<T> response) { if (response == null || (response.getData() == null && response.getResult() == null)) { throw new JsonParseException(""); } /*if (!response.isOk()) { throw new RuntimeException(response.getCode() + "" + response.getMsg() != null ? response.getMsg() : ""); } */ return response.getData(); } } /** * Retroift get * * @param url * @param maps * @param subscriber * @param <T> * @return no parse data */ public <T> T get(String url, Map<String, Object> maps, BaseSubscriber<ResponseBody> subscriber) { return (T) apiManager.executeGet(url, maps) .compose(schedulersTransformer) .compose(handleErrTransformer()) .subscribe(subscriber); } public <T> T post(String url, @FieldMap(encoded = true) Map<String, Object> parameters, Subscriber<ResponseBody> subscriber) { return (T) apiManager.executePost(url, (Map<String, Object>) parameters) .compose(schedulersTransformer) .compose(handleErrTransformer()) .subscribe(subscriber); } /** * Novate executePost * * @return parsed data * you don't need to parse ResponseBody */ public <T> T executePost(final String url, @FieldMap(encoded = true) Map<String, Object> parameters, final ResponseCallBack<T> callBack) { final Type[] types = callBack.getClass().getGenericInterfaces(); if (MethodHandler(types) == null || MethodHandler(types).size() == 0) { return null; } final Type finalNeedType = MethodHandler(types).get(0); Log.d(TAG, "-->:" + "Type:" + types[0]); return (T) apiManager.executePost(url, parameters) .compose(schedulersTransformer) .compose(handleErrTransformer()) .subscribe(new ApiSubscriber<T>(mContext, finalNeedType, callBack)); } /** * Novate Post by Form * * @param url * @param subscriber */ public <T> T form(String url, @FieldMap(encoded = true) Map<String, Object> fields, Subscriber<ResponseBody> subscriber) { return (T) apiManager.postForm(url, fields) .compose(schedulersTransformer) .compose(handleErrTransformer()) .subscribe(subscriber); } /** * Novate execute Post by Form * * @return parsed data * you don't need to parse ResponseBody */ public <T> T executeForm(final String url, final @FieldMap(encoded = true) Map<String, Object> fields, final ResponseCallBack<T> callBack) { final Type[] types = callBack.getClass().getGenericInterfaces(); if (MethodHandler(types) == null || MethodHandler(types).size() == 0) { return null; } final Type finalNeedType = MethodHandler(types).get(0); Log.d(TAG, "-->:" + "Type:" + types[0]); return (T) apiManager.postForm(url, fields) .compose(schedulersTransformer) .compose(handleErrTransformer()) .subscribe(new ApiSubscriber<T>(mContext, finalNeedType, callBack)); } /** * http Post by Body * you need to parse ResponseBody * * @param url * @param subscriber */ public void body(String url, Object body, Subscriber<ResponseBody> subscriber) { apiManager.executePostBody(url, body) .compose(schedulersTransformer) .compose(handleErrTransformer()) .subscribe(subscriber); } /** * http execute Post by body * * @return parsed data * you don't need to parse ResponseBody */ public <T> T executeBody(final String url, final Object body, final ResponseCallBack<T> callBack) { final Type[] types = callBack.getClass().getGenericInterfaces(); if (MethodHandler(types) == null || MethodHandler(types).size() == 0) { return null; } final Type finalNeedType = MethodHandler(types).get(0); Log.d(TAG, "-->:" + "Type:" + types[0]); return (T) apiManager.executePostBody(url, body) .compose(schedulersTransformer) .compose(handleErrTransformer()) .subscribe(new ApiSubscriber<T>(mContext, finalNeedType, callBack)); } /** * http Post by json * you need to parse ResponseBody * * @param url * @param jsonStr Json String * @param subscriber */ public void json(String url, String jsonStr, Subscriber<ResponseBody> subscriber) { apiManager.postRequestBody(url, Utils.createJson(jsonStr)) .compose(schedulersTransformer) .compose(handleErrTransformer()) .subscribe(subscriber); } /** * http execute Post by Json * * @param url * @param jsonStr Json String * @return parsed data * you don't need to parse ResponseBody */ public <T> T executeJson(final String url, final String jsonStr, final ResponseCallBack<T> callBack) { final Type[] types = callBack.getClass().getGenericInterfaces(); if (MethodHandler(types) == null || MethodHandler(types).size() == 0) { return null; } final Type finalNeedType = MethodHandler(types).get(0); Log.d(TAG, "-->:" + "Type:" + types[0]); return (T) apiManager.postRequestBody(url, Utils.createJson(jsonStr)) .compose(schedulersTransformer) .compose(handleErrTransformer()) .subscribe(new ApiSubscriber<T>(mContext, finalNeedType, callBack)); } /** * Novate delete * * @param url * @param maps * @param subscriber * @param <T> * @return no parse data */ public <T> T delete(String url, Map<String, T> maps, BaseSubscriber<ResponseBody> subscriber) { return (T) apiManager.executeDelete(url, (Map<String, Object>) maps) .compose(schedulersTransformer) .compose(handleErrTransformer()) .subscribe(subscriber); } /** * Novate Execute http by Delete * * @return parsed data * you don't need to parse ResponseBody */ public <T> T executeDelete(final String url, final Map<String, T> maps, final ResponseCallBack<T> callBack) { final Type[] types = callBack.getClass().getGenericInterfaces(); if (MethodHandler(types) == null || MethodHandler(types).size() == 0) { return null; } final Type finalNeedType = MethodHandler(types).get(0); Log.d(TAG, "-->:" + "Type:" + types[0]); return (T) apiManager.executeDelete(url, (Map<String, Object>) maps) .compose(schedulersTransformer) .compose(handleErrTransformer()) .subscribe(new ApiSubscriber<T>(mContext, finalNeedType, callBack)); } /** * Novate put * * @param url * @param parameters * @param subscriber * @param <T> * @return no parse data */ public <T> T put(String url, final @FieldMap(encoded = true) Map<String, T> parameters, BaseSubscriber<ResponseBody> subscriber) { return (T) apiManager.executePut(url, (Map<String, Object>) parameters) .compose(schedulersTransformer) .compose(handleErrTransformer()) .subscribe(subscriber); } /** * Novate Execute Http by Put * * @return parsed data * you don't need to parse ResponseBody */ public <T> T executePut(final String url, final @FieldMap(encoded = true) Map<String, T> parameters, final ResponseCallBack<T> callBack) { final Type[] types = callBack.getClass().getGenericInterfaces(); if (MethodHandler(types) == null || MethodHandler(types).size() == 0) { return null; } final Type finalNeedType = MethodHandler(types).get(0); Log.d(TAG, "-->:" + "Type:" + types[0]); return (T) apiManager.executePut(url, (Map<String, Object>) parameters) .compose(schedulersTransformer) .compose(handleErrTransformer()) .subscribe(new ApiSubscriber<T>(mContext, finalNeedType, callBack)); } /** * Novate Test * * @param url url * @param maps maps * @param subscriber subscriber * @param <T> T * @return */ public <T> T test(String url, Map<String, T> maps, Subscriber<ResponseBody> subscriber) { return (T) apiManager.getTest(url, (Map<String, Object>) maps) .compose(schedulersTransformer) .compose(handleErrTransformer()) .subscribe(subscriber); } /** * Novate upload * * @param url * @param requestBody requestBody * @param subscriber subscriber * @param <T> T * @return */ public <T> T upload(String url, RequestBody requestBody, Subscriber<ResponseBody> subscriber) { return (T) apiManager.postRequestBody(url, requestBody) .compose(schedulersTransformer) .compose(handleErrTransformer()) .subscribe(subscriber); } /** * uploadImage * * @param url url * @param file file * @param subscriber * @param <T> * @return */ public <T> T uploadImage(String url, File file, Subscriber<ResponseBody> subscriber) { return (T) apiManager.upLoadImage(url, Utils.createImage(file)) .compose(schedulersTransformer) .compose(handleErrTransformer()) .subscribe(subscriber); } /** * Novate upload Flie * * @param url * @param file file * @param subscriber subscriber * @param <T> T * @return */ public <T> T uploadFlie(String url, RequestBody file, Subscriber<ResponseBody> subscriber) { return (T) apiManager.postRequestBody(url, file) .compose(schedulersTransformer) .compose(handleErrTransformer()) .subscribe(subscriber); } /** * Novate upload Flie * * @param url * @param file file * @param subscriber subscriber * @param <T> T * @return */ public <T> T uploadFlie(String url, RequestBody description, MultipartBody.Part file, Subscriber<ResponseBody> subscriber) { return (T) apiManager.uploadFlie(url, description, file) .compose(schedulersTransformer) .compose(handleErrTransformer()) .subscribe(subscriber); } /** * Novate upload Flies * * @param url * @param subscriber subscriber * @param <T> T * @return */ public <T> T uploadFlies(String url, Map<String, RequestBody> files, Subscriber<ResponseBody> subscriber) { return (T) apiManager.uploadFiles(url, files) .compose(schedulersTransformer) .compose(handleErrTransformer()) .subscribe(subscriber); } /** * Novate upload Flies WithPartMap * @param url * @param partMap * @param file * @param subscriber * @param <T> * @return */ public <T> T uploadFileWithPartMap(String url, Map<String, RequestBody> partMap, @Part("file") MultipartBody.Part file, Subscriber<ResponseBody> subscriber) { return (T) apiManager.uploadFileWithPartMap(url, partMap, file) .compose(schedulersTransformer) .compose(handleErrTransformer()) .subscribe(subscriber); } /** * Novate download * * @param url * @param callBack */ public void download(String url, DownLoadCallBack callBack) { download(url, FileUtil.getFileNameWithURL(url), callBack); } /** * @param url * @param name * @param callBack */ public void download(String url, String name, DownLoadCallBack callBack) { download(FileUtil.generateFileKey(url, name), url, null, name, callBack); } /** * downloadMin * * @param url * @param callBack */ public void downloadMin(String url, DownLoadCallBack callBack) { downloadMin(FileUtil.generateFileKey(url, FileUtil.getFileNameWithURL(url)), url, callBack); } /** * downloadMin * * @param key * @param url * @param callBack */ public void downloadMin(String key, String url, DownLoadCallBack callBack) { downloadMin(key, url, FileUtil.getFileNameWithURL(url), callBack); } /** * downloadMin * * @param url * @param name * @param callBack */ public void downloadMin(String key, String url, String name, DownLoadCallBack callBack) { downloadMin(key, url, null, name, callBack); } /** * download small file * * @param url * @param savePath * @param name * @param callBack */ public void downloadMin(String key, String url, String savePath, String name, DownLoadCallBack callBack) { if (downMaps.get(key) == null) { downObservable = apiManager.downloadSmallFile(url); } else { downObservable = downMaps.get(key); } downMaps.put(key, downObservable); executeDownload(key, savePath, name, callBack); } /** * @param url * @param url * @param url * @param savePath * @param name * @param callBack */ public void download(String key, String url, String savePath, String name, DownLoadCallBack callBack) { if (downMaps.get(key) == null) { downObservable = apiManager.downloadFile(url); } else { downObservable = downMaps.get(url); } downMaps.put(key, downObservable); executeDownload(key, savePath, name, callBack); } /** * executeDownload * * @param savePath * @param name * @param callBack */ private void executeDownload(String key, String savePath, String name, DownLoadCallBack callBack) { /*if (NovateDownLoadManager.isDownLoading) { downMaps.get(key).unsubscribeOn(Schedulers.io()); NovateDownLoadManager.isDownLoading = false; NovateDownLoadManager.isCancel = true; return; }*/ //NovateDownLoadManager.isDownLoading = true; if(downMaps.get(key)!= null) { downMaps.get(key).compose(schedulersTransformerDown) .compose(handleErrTransformer()) .subscribe(new DownSubscriber<ResponseBody>(key, savePath, name, callBack, mContext)); } } /** * Mandatory Builder for the Builder */ public static final class Builder { private static final int DEFAULT_TIMEOUT = 5; private static final int DEFAULT_MAXIDLE_CONNECTIONS = 5; private static final long DEFAULT_KEEP_ALIVEDURATION = 8; private static final long caheMaxSize = 10 * 1024 * 1024; private okhttp3.Call.Factory callFactory; private String baseUrl; private Boolean isLog = false; private Boolean isCookie = false; private Boolean isCache = true; private List<InputStream> certificateList; private HostnameVerifier hostnameVerifier; private CertificatePinner certificatePinner; private List<Converter.Factory> converterFactories = new ArrayList<>(); private List<CallAdapter.Factory> adapterFactories = new ArrayList<>(); private Executor callbackExecutor; private boolean validateEagerly; private Context context; private CookieManager cookieManager; private Cache cache = null; private Proxy proxy; private File httpCacheDirectory; private SSLSocketFactory sslSocketFactory; private ConnectionPool connectionPool; private Converter.Factory converterFactory; private CallAdapter.Factory callAdapterFactory; private Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR; private Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR_OFFLINE; public Builder(Context context) { // Add the base url first. This prevents overriding its behavior but also // ensures correct behavior when using novate that consume all types. okhttpBuilder = new OkHttpClient.Builder(); retrofitBuilder = new Retrofit.Builder(); this.context = context; } /** * The HTTP client used for requests. default OkHttpClient * <p/> * This is a convenience method for calling {@link #callFactory}. * <p/> * Note: This method <b>does not</b> make a defensive copy of {@code client}. Changes to its * settings will affect subsequent requests. Pass in a {@linkplain OkHttpClient#clone() cloned} * instance to prevent this if desired. */ @NonNull public Builder client(OkHttpClient client) { retrofitBuilder.client(Utils.checkNotNull(client, "client == null")); return this; } *//* /** * Add ApiManager for serialization and deserialization of objects. public Builder addApiManager(final Class<ApiManager> service) { apiManager = retrofit.create((Utils.checkNotNull(service, "apiManager == null"))); //return retrofit.create(service); return this; }*/ /** * Specify a custom call factory for creating {@link } instances. * <p/> * Note: Calling {@link #client} automatically sets this value. */ public Builder callFactory(okhttp3.Call.Factory factory) { this.callFactory = Utils.checkNotNull(factory, "factory == null"); return this; } /** * Sets the default connect timeout for new connections. A value of 0 means no timeout, * otherwise values must be between 1 and {@link Integer#MAX_VALUE} when converted to * milliseconds. */ public Builder connectTimeout(int timeout) { return connectTimeout(timeout, TimeUnit.SECONDS); } /** * Sets the default connect timeout for new connections. A value of 0 means no timeout, * otherwise values must be between 1 and {@link Integer#MAX_VALUE} when converted to * milliseconds. */ public Builder writeTimeout(int timeout) { return writeTimeout(timeout, TimeUnit.SECONDS); } /** * open default logcat * * @param isLog * @return */ public Builder addLog(boolean isLog) { this.isLog = isLog; return this; } /** * open sync default Cookie * * @param isCookie * @return */ public Builder addCookie(boolean isCookie) { this.isCookie = isCookie; return this; } /** * open default Cache * * @param isCache * @return */ public Builder addCache(boolean isCache) { this.isCache = isCache; return this; } public Builder proxy(Proxy proxy) { okhttpBuilder.proxy(Utils.checkNotNull(proxy, "proxy == null")); return this; } /** * Sets the default write timeout for new connections. A value of 0 means no timeout, * otherwise values must be between 1 and {@link TimeUnit #MAX_VALUE} when converted to * milliseconds. */ public Builder writeTimeout(int timeout, TimeUnit unit) { if (timeout != -1) { okhttpBuilder.writeTimeout(timeout, unit); } else { okhttpBuilder.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS); } return this; } /** * Sets the connection pool used to recycle HTTP and HTTPS connections. * <p> * <p>If unset, a new connection pool will be used. */ public Builder connectionPool(ConnectionPool connectionPool) { if (connectionPool == null) throw new NullPointerException("connectionPool == null"); this.connectionPool = connectionPool; return this; } /** * Sets the default connect timeout for new connections. A value of 0 means no timeout, * otherwise values must be between 1 and {@link TimeUnit #MAX_VALUE} when converted to * milliseconds. */ public Builder connectTimeout(int timeout, TimeUnit unit) { if (timeout != -1) { okhttpBuilder.connectTimeout(timeout, unit); } else { okhttpBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS); } return this; } /** * Set an API base URL which can change over time. * * @see BaseUrl(HttpUrl) */ public Builder baseUrl(String baseUrl) { this.baseUrl = Utils.checkNotNull(baseUrl, "baseUrl == null"); return this; } /** * Add converter factory for serialization and deserialization of objects. */ public Builder addConverterFactory(Converter.Factory factory) { this.converterFactory = factory; return this; } /** * Add a call adapter factory for supporting service method return types other than {@link CallAdapter * }. */ public Builder addCallAdapterFactory(CallAdapter.Factory factory) { this.callAdapterFactory = factory; return this; } /** * Add Header for serialization and deserialization of objects. */ public <T> Builder addHeader(Map<String, T> headers) { okhttpBuilder.addInterceptor(new BaseInterceptor(Utils.checkNotNull(headers, "header == null"))); return this; } /** * Add parameters for serialization and deserialization of objects. */ public <T> Builder addParameters(Map<String, T> parameters) { okhttpBuilder.addInterceptor(new BaseInterceptor(Utils.checkNotNull(parameters, "parameters == null"))); return this; } /** * Returns a modifiable list of interceptors that observe a single network request and response. * These interceptors must call {@link Interceptor.Chain#proceed} exactly once: it is an error * for a network interceptor to short-circuit or repeat a network request. */ public Builder addInterceptor(Interceptor interceptor) { okhttpBuilder.addInterceptor(Utils.checkNotNull(interceptor, "interceptor == null")); return this; } /** * The executor on which {@link Call} methods are invoked when returning {@link Call} from * your service method. * <p/> * Note: {@code executor} is not used for {@linkplain #addCallAdapterFactory custom method * return types}. */ public Builder callbackExecutor(Executor executor) { this.callbackExecutor = Utils.checkNotNull(executor, "executor == null"); return this; } /** * When calling {@link #create} on the resulting {@link Retrofit} instance, eagerly validate * the configuration of all methods in the supplied interface. */ public Builder validateEagerly(boolean validateEagerly) { this.validateEagerly = validateEagerly; return this; } /** * Sets the handler that can accept cookies from incoming HTTP responses and provides cookies to * outgoing HTTP requests. * <p/> * <p>If unset, {@linkplain CookieManager#NO_COOKIES no cookies} will be accepted nor provided. */ public Builder cookieManager(CookieManager cookie) { if (cookie == null) throw new NullPointerException("cookieManager == null"); this.cookieManager = cookie; return this; } public Builder addSSLSocketFactory(SSLSocketFactory sslSocketFactory) { this.sslSocketFactory = sslSocketFactory; return this; } public Builder addHostnameVerifier(HostnameVerifier hostnameVerifier) { this.hostnameVerifier = hostnameVerifier; return this; } public Builder addCertificatePinner(CertificatePinner certificatePinner) { this.certificatePinner = certificatePinner; return this; } /** * Sets the handler that can accept cookies from incoming HTTP responses and provides cookies to * outgoing HTTP requests. * <p/> * <p>If unset, {@linkplain CookieManager#NO_COOKIES no cookies} will be accepted nor provided. */ public Builder addSSL(String[] hosts, int[] certificates) { if (hosts == null) throw new NullPointerException("hosts == null"); if (certificates == null) throw new NullPointerException("ids == null"); addSSLSocketFactory(RetrofitHttpsFactroy.getSSLSocketFactory(context, certificates)); addHostnameVerifier(RetrofitHttpsFactroy.getHostnameVerifier(hosts)); return this; } public Builder addNetworkInterceptor(Interceptor interceptor) { okhttpBuilder.addNetworkInterceptor(interceptor); return this; } /** * setCache * * @param cache cahe * @return Builder */ public Builder addCache(Cache cache) { int maxStale = 60 * 60 * 24 * 3; return addCache(cache, maxStale); } /** * @param cache * @param cacheTime ms * @return */ public Builder addCache(Cache cache, final int cacheTime) { addCache(cache, String.format("max-age=%d", cacheTime)); return this; } /** * @param cache * @param cacheControlValue Cache-Control * @return */ private Builder addCache(Cache cache, final String cacheControlValue) { REWRITE_CACHE_CONTROL_INTERCEPTOR = new CacheInterceptor(mContext, cacheControlValue); REWRITE_CACHE_CONTROL_INTERCEPTOR_OFFLINE = new CacheInterceptorOffline(mContext, cacheControlValue); addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR); addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR_OFFLINE); addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR_OFFLINE); this.cache = cache; return this; } /** * Create the {@link Retrofit} instance using the configured values. * <p/> * Note: If neither {@link #client} nor {@link #callFactory} is called a default {@link * OkHttpClient} will be created and used. */ public Factory build() { if (baseUrl == null) { throw new IllegalStateException("Base URL required."); } if (okhttpBuilder == null) { throw new IllegalStateException("okhttpBuilder required."); } if (retrofitBuilder == null) { throw new IllegalStateException("retrofitBuilder required."); } /** set Context. */ mContext = context; /** * Set a fixed API base URL. * * @see #baseUrl(HttpUrl) */ retrofitBuilder.baseUrl(baseUrl); /** Add converter factory for serialization and deserialization of objects. */ if (converterFactory == null) { converterFactory = GsonConverterFactory.create(); } ; retrofitBuilder.addConverterFactory(converterFactory); /** * Add a call adapter factory for supporting service method return types other than {@link * Call}. */ if (callAdapterFactory == null) { callAdapterFactory = RxJavaCallAdapterFactory.create(); } retrofitBuilder.addCallAdapterFactory(callAdapterFactory); if (isLog) { okhttpBuilder.addNetworkInterceptor( new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS)); } if (sslSocketFactory != null) { okhttpBuilder.sslSocketFactory(sslSocketFactory); } if (hostnameVerifier != null) { okhttpBuilder.hostnameVerifier(hostnameVerifier); } if (httpCacheDirectory == null) { httpCacheDirectory = new File(mContext.getCacheDir(), "Http_cache"); } if (isCache) { try { if (cache == null) { cache = new Cache(httpCacheDirectory, caheMaxSize); } addCache(cache); } catch (Exception e) { Log.e("OKHttp", "Could not create http cache", e); } if (cache == null) { cache = new Cache(httpCacheDirectory, caheMaxSize); } } if (cache != null) { okhttpBuilder.cache(cache); } /** * Sets the connection pool used to recycle HTTP and HTTPS connections. * * <p>If unset, a new connection pool will be used. */ if (connectionPool == null) { connectionPool = new ConnectionPool(DEFAULT_MAXIDLE_CONNECTIONS, DEFAULT_KEEP_ALIVEDURATION, TimeUnit.SECONDS); } okhttpBuilder.connectionPool(connectionPool); if (proxy == null) { okhttpBuilder.proxy(proxy); } /** * Sets the handler that can accept cookies from incoming HTTP responses and provides cookies to * outgoing HTTP requests. * * <p>If unset, {@link Factory CookieManager#NO_COOKIES no cookies} will be accepted nor provided. */ if (isCookie && cookieManager == null) { //okhttpBuilder.cookieJar(new NovateCookieManger(context)); okhttpBuilder.cookieJar(new CookieManager(new CookieCacheImpl(), new SharedPrefsCookiePersistor(context))); } if (cookieManager != null) { okhttpBuilder.cookieJar(cookieManager); } /** *okhttp3.Call.Factory callFactory = this.callFactory; */ if (callFactory != null) { retrofitBuilder.callFactory(callFactory); } /** * create okHttpClient */ okHttpClient = okhttpBuilder.build(); /** * set Retrofit client */ retrofitBuilder.client(okHttpClient); /** * create Retrofit */ retrofit = retrofitBuilder.build(); /** *create BaseApiService; */ apiManager = retrofit.create(BaseApiService.class); return new Factory(callFactory, baseUrl, headers, parameters, apiManager, converterFactories, adapterFactories, callbackExecutor, validateEagerly); } } /** * ApiSubscriber * * @param <T> */ class ApiSubscriber<T> extends BaseSubscriber<ResponseBody> { private ResponseCallBack<T> callBack; private Type finalNeedType; public ApiSubscriber(Context context, Type finalNeedType, ResponseCallBack<T> callBack) { this.callBack = callBack; this.finalNeedType = finalNeedType; } @Override public void onStart() { super.onStart(); // todo some common as show loadding and check netWork is NetworkAvailable if (callBack != null) { callBack.onStart(); } } @Override public void onCompleted() { // todo some common as dismiss loadding if (callBack != null) { callBack.onCompleted(); } } @Override public void onError(Throwable e) { if (callBack != null) { callBack.onError(e); } } @Override public void onNext(ResponseBody responseBody) { try { byte[] bytes = responseBody.bytes(); String jsStr = new String(bytes); Log.d("OkHttp", "ResponseBody:" + jsStr); if (callBack != null) { try { /** * if need parse baseRespone<T> use ParentType, if parse T use childType . defult parse baseRespone<T> * * callBack.onSuccee((T) JSON.parseArray(jsStr, (Class<Object>) finalNeedType)); * Type finalNeedType = needChildType; */ HttpResult<T> baseResponse = null; if (new Gson().fromJson(jsStr, finalNeedType) == null) { throw new NullPointerException(); } baseResponse = new Gson().fromJson(jsStr, finalNeedType); if (ConfigLoader.isFormat(mContext) && baseResponse.getData() == null & baseResponse.getResult() == null) { throw new FormatException(); } if (baseResponse.isOk(mContext)) { callBack.onSuccee((T) new Gson().fromJson(jsStr, finalNeedType)); } else { String msg = baseResponse.getMsg() != null ? baseResponse.getMsg() : baseResponse.getError() != null ? baseResponse.getError() : baseResponse.getMessage() != null ? baseResponse.getMessage() : "api"; ServerException serverException = new ServerException(baseResponse.getCode(), msg); callBack.onError(ApiException.handleException(serverException)); } } catch (Exception e) { e.printStackTrace(); if (callBack != null) { callBack.onError(ApiException.handleException(new FormatException())); } } } } catch (Exception e) { e.printStackTrace(); if (callBack != null) { callBack.onError(ApiException.handleException(e)); } } } } /** * ResponseCallBack <T> Support your custom data model */ public interface ResponseCallBack<T> { void onStart(); void onCompleted(); void onError(java.lang.Throwable e); void onSuccee(T response); } }
package gov.nih.nci.cananolab.ui.core; import gov.nih.nci.cananolab.service.common.GridDiscoveryServiceJob; import gov.nih.nci.cananolab.util.CaNanoLabConstants; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import org.apache.log4j.Logger; import org.apache.struts.action.ActionServlet; import org.apache.struts.action.PlugIn; import org.apache.struts.config.ModuleConfig; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.SimpleTrigger; import org.quartz.Trigger; import org.quartz.TriggerUtils; import org.quartz.ee.servlet.QuartzInitializerServlet; import org.quartz.impl.StdSchedulerFactory; /** * Create a scheduler using Quartz when container starts. Borrowed concepts from * LSD browser application. * * @author pansu, sahnih * */ public class SchedulerPlugin implements PlugIn { Logger logger = Logger.getLogger(SchedulerPlugin.class); private static Scheduler scheduler = null; public void init(ActionServlet actionServlet, ModuleConfig config) throws ServletException { System.out.println("Initializing Scheduler Plugin for Jobs..."); ServletContext context = actionServlet.getServletContext(); // Retrieve the factory from the ServletContext. // It will be put there by the Quartz Servlet StdSchedulerFactory factory = (StdSchedulerFactory) context .getAttribute(QuartzInitializerServlet.QUARTZ_FACTORY_KEY); try { // // Start the scheduler in case, it isn't started yet // if (m_startOnLoad != null // && m_startOnLoad.equals(Boolean.TRUE.toString())) { // System.out.println("Scheduler Will start in " // + m_startupDelayString + " milliseconds!"); // // wait the specified amount of time before // // starting the process. // Thread delayedScheduler = new Thread( // new DelayedSchedulerStarted(scheduler, m_startupDelay)); // // give the scheduler a name. All good code needs a name // delayedScheduler.setName("Delayed_Scheduler"); // // Start out scheduler // delayedScheduler.start(); // Retrieve the scheduler from the factory scheduler = factory.getScheduler(); if (scheduler != null) { scheduler.start(); int schedulerInterval = getIntervalInMinutes(actionServlet .getServletConfig()); initialiseJob(schedulerInterval); } } catch (SchedulerException e) { logger.error("Error setting up scheduler", e); } } // This method will be called at application shutdown time public void destroy() { System.out.println("Entering SchedulerPlugin.destroy()"); System.out.println("Exiting SchedulerPlugIn.destroy()"); } private int getIntervalInMinutes(ServletConfig servletConfig) { Integer interval = 0; try { interval = new Integer(servletConfig .getInitParameter("schedulerIntervalInMinutes")); } catch (NumberFormatException e) { // use default interval = CaNanoLabConstants.DEFAULT_GRID_DISCOVERY_INTERVAL_IN_MINS; } return interval; } public void initialiseJob(int intervalInMinutes) { try { Trigger trigger = null; if (intervalInMinutes == 0) { intervalInMinutes = CaNanoLabConstants.DEFAULT_GRID_DISCOVERY_INTERVAL_IN_MINS; // default // minutes } trigger = TriggerUtils.makeMinutelyTrigger( "GridDiscoveryServiceJobTrigger", intervalInMinutes, SimpleTrigger.REPEAT_INDEFINITELY); JobDetail jobDetail = new JobDetail("GridDiscoveryServiceJob", null, GridDiscoveryServiceJob.class); scheduler.scheduleJob(jobDetail, trigger); logger.debug("Discover Scheduler started......"); } catch (SchedulerException e) { logger.error(e.getMessage(), e); } } }
package gov.nih.nci.ncicb.cadsr.loader.ui; import gov.nih.nci.ncicb.cadsr.domain.Concept; import gov.nih.nci.ncicb.cadsr.domain.DataElement; import gov.nih.nci.ncicb.cadsr.domain.ObjectClass; import gov.nih.nci.ncicb.cadsr.loader.UserSelections; import gov.nih.nci.ncicb.cadsr.loader.event.ReviewEvent; import gov.nih.nci.ncicb.cadsr.loader.event.ReviewEventType; import gov.nih.nci.ncicb.cadsr.loader.event.ReviewListener; import gov.nih.nci.ncicb.cadsr.loader.ui.event.NavigationEvent; import gov.nih.nci.ncicb.cadsr.loader.ui.event.NavigationListener; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.ReviewableUMLNode; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.UMLNode; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.ValueMeaningNode; import gov.nih.nci.ncicb.cadsr.loader.util.RunMode; import gov.nih.nci.ncicb.cadsr.loader.util.StringUtil; import gov.nih.nci.ncicb.cadsr.loader.util.DEMappingUtil; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.List; import javax.swing.AbstractButton; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JOptionPane; import javax.swing.JPanel; public class ButtonPanel extends JPanel implements ActionListener, PropertyChangeListener { private JButton switchButton; private JCheckBox reviewButton; private NavigationButtonPanel navigationButtonPanel; private AddButtonPanel addButtonPanel; private ApplyButtonPanel applyButtonPanel; private List<NavigationListener> navigationListeners = new ArrayList<NavigationListener>(); private List<PropertyChangeListener> propChangeListeners = new ArrayList<PropertyChangeListener>(); private ConceptEditorPanel conceptEditorPanel; private Editable viewPanel; private Editable editable; static final String PREVIEW = "PREVIEW", SETUP = "SETUP", SWITCH = "SWITCH", DELETEBUTTON = "DELETEBUTTON"; static final String SWITCH_TO_DE = "Map to CDE", SWITCH_TO_OC = "Map to OC", SWITCH_TO_CONCEPT = "Map to Concepts"; private RunMode runMode = null; public void addPropertyChangeListener(PropertyChangeListener l) { propChangeListeners.add(l); applyButtonPanel.addPropertyChangeListener(l); } public ButtonPanel(ConceptEditorPanel conceptEditorPanel, Editable viewPanel, Editable editable) { this.conceptEditorPanel = conceptEditorPanel; this.viewPanel = viewPanel; this.editable = editable; UserSelections selections = UserSelections.getInstance(); runMode = (RunMode)(selections.getProperty("MODE")); switchButton = new JButton(); ReviewableUMLNode revNode = (ReviewableUMLNode)conceptEditorPanel.getNode(); switchButton.setActionCommand(SWITCH); switchButton.addActionListener(this); navigationButtonPanel = new NavigationButtonPanel(); addButtonPanel = new AddButtonPanel(conceptEditorPanel); applyButtonPanel = new ApplyButtonPanel(viewPanel, revNode); this.add(addButtonPanel); this.add(applyButtonPanel); this.add(navigationButtonPanel); this.add(switchButton); } public void update() { applyButtonPanel.update(); if(editable instanceof DEPanel) { DataElement de = (DataElement)conceptEditorPanel.getNode().getUserObject(); if(!StringUtil.isEmpty(de.getPublicId())) { setSwitchButtonText(ButtonPanel.SWITCH_TO_CONCEPT); } else { setSwitchButtonText(ButtonPanel.SWITCH_TO_DE); } } else if(editable instanceof OCPanel) { ObjectClass oc = (ObjectClass)conceptEditorPanel.getNode().getUserObject(); if(!StringUtil.isEmpty(oc.getPublicId())) { setSwitchButtonText(ButtonPanel.SWITCH_TO_CONCEPT); } else { setSwitchButtonText(ButtonPanel.SWITCH_TO_OC); } } else if(editable == null) { return; } } public void addReviewListener(ReviewListener listener) { // reviewListeners.add(listener); applyButtonPanel.addReviewListener(listener); } public void addNavigationListener(NavigationListener listener) { navigationListeners.add(listener); navigationButtonPanel.addNavigationListener(listener); applyButtonPanel.addNavigationListener(listener); } public void propertyChange(PropertyChangeEvent e) { if (e.getPropertyName().equals(SETUP)) { initButtonPanel(); } else if (e.getPropertyName().equals(SWITCH)) { switchButton.setEnabled((Boolean)e.getNewValue()); } addButtonPanel.propertyChange(e); applyButtonPanel.propertyChange(e); } private void fireNavigationEvent(NavigationEvent event) { for(NavigationListener l : navigationListeners) l.navigate(event); } private void setSwitchButtonText(String text) { switchButton.setText(text); } public void setEnabled(boolean enabled) { addButtonPanel.setVisible(enabled); applyButtonPanel.setVisible(enabled); if (enabled) { // enabling does not necessarily enable every single button initButtonPanel(); return; } // addButton.setEnabled(false); // saveButton.setEnabled(false); switchButton.setEnabled(false); // reviewButton.setEnabled(false); } private void initButtonPanel() { Concept[] concepts = conceptEditorPanel.getConcepts(); UMLNode node = conceptEditorPanel.getNode(); boolean reviewButtonState = false; if(concepts.length == 0) { if(node instanceof ValueMeaningNode) { reviewButtonState = true; } else reviewButtonState = false; } else reviewButtonState = true; switchButton.setVisible(editable instanceof DEPanel); if(editable instanceof DEPanel) { DataElement de = (DataElement)node.getUserObject(); if(DEMappingUtil.isMappedToLVD(de)) switchButton.setEnabled(false); } // disable add if DEPanel is showing if(editable instanceof DEPanel) { DataElement de = (DataElement)conceptEditorPanel.getNode().getUserObject(); if(!StringUtil.isEmpty(de.getPublicId())) { addButtonPanel.setVisible(false); reviewButtonState = true; } else { addButtonPanel.setVisible(true); } } else if(editable instanceof OCPanel) { ObjectClass oc = (ObjectClass)conceptEditorPanel.getNode().getUserObject(); if(!StringUtil.isEmpty(oc.getPublicId())) { addButtonPanel.setVisible(false); reviewButtonState = true; } else { addButtonPanel.setVisible(true); } } else if(editable == null) { addButtonPanel.setVisible(true); } applyButtonPanel.init(reviewButtonState); } public void setEditablePanel(Editable editable) { this.editable = editable; } public void navigate(NavigationEvent evt) { applyButtonPanel.navigate(evt); } private void firePropertyChangeEvent(PropertyChangeEvent evt) { for(PropertyChangeListener l : propChangeListeners) l.propertyChange(evt); } public void actionPerformed(ActionEvent evt) { AbstractButton button = (AbstractButton)evt.getSource(); if(button.getActionCommand().equals(SWITCH)) { if(switchButton.getText().equals(SWITCH_TO_DE)) { ((UMLElementViewPanel)viewPanel).switchCards(UMLElementViewPanel.DE_PANEL_KEY); switchButton.setText(SWITCH_TO_CONCEPT); addButtonPanel.setVisible(false); } else if (switchButton.getText().equals(SWITCH_TO_CONCEPT)) { ((UMLElementViewPanel)viewPanel).switchCards(UMLElementViewPanel.CONCEPT_PANEL_KEY); if(editable instanceof DEPanel) { switchButton.setText(SWITCH_TO_DE); conceptEditorPanel.getVDPanel().updateNode(conceptEditorPanel.getNode()); } else if(editable instanceof OCPanel) { switchButton.setText(SWITCH_TO_OC); } else if(editable == null) { } addButtonPanel.setVisible(true); } else if(switchButton.getText().equals(SWITCH_TO_OC)) { ((UMLElementViewPanel)viewPanel).switchCards(UMLElementViewPanel.OC_PANEL_KEY); switchButton.setText(SWITCH_TO_CONCEPT); } } } }
package wind07.gpacalculator; class Module { String modName; double credUnits; String grade; Module(String ModName, double CredUnits, String Grade){ modName = ModName; credUnits = CredUnits; grade = Grade; } }
// @@@ msg combining AND lrmc at the same time is not supported package ibis.satin.impl.sharedObjects; import ibis.ipl.IbisConfigurationException; import ibis.ipl.IbisIdentifier; import ibis.ipl.PortType; import ibis.ipl.ReadMessage; import ibis.ipl.ReceivePort; import ibis.ipl.ReceivePortIdentifier; import ibis.ipl.SendPort; import ibis.ipl.WriteMessage; import ibis.ipl.util.messagecombining.MessageCombiner; import ibis.ipl.util.messagecombining.MessageSplitter; import ibis.satin.SharedObject; import ibis.satin.impl.Config; import ibis.satin.impl.Satin; import ibis.satin.impl.communication.Communication; import ibis.satin.impl.communication.Protocol; import ibis.satin.impl.loadBalancing.Victim; import ibis.satin.impl.spawnSync.InvocationRecord; import ibis.util.TypedProperties; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; final class SOCommunication implements Config, Protocol { private static final boolean ASYNC_SO_BCAST = false; public static final boolean DISABLE_SO_BCAST = false; private Satin s; /** the current size of the accumulated so messages */ private long soCurrTotalMessageSize = 0; private long soInvocationsDelayTimer = -1; /** used to broadcast shared object invocations */ private SendPort soSendPort; /** used to receive shared object invocations */ private ReceivePort soReceivePort; private PortType soPortType; /** used to do message combining on soSendPort */ private MessageCombiner soMessageCombiner; /** a list of ibis identifiers that we still need to connect to */ private ArrayList<IbisIdentifier> toConnect = new ArrayList<IbisIdentifier>(); private HashMap<IbisIdentifier, ReceivePortIdentifier> ports = new HashMap<IbisIdentifier, ReceivePortIdentifier>(); private SharedObject sharedObject = null; private boolean receivedNack = false; protected SOCommunication(Satin s) { this.s = s; } protected void init() { if(DISABLE_SO_BCAST) return; if (LABEL_ROUTING_MCAST) { try { soPortType = getSOPortType(); SOInvocationHandler soInvocationHandler = new SOInvocationHandler(s); // Create a multicast port to bcast shared object invocations. // Connections are established later. soSendPort = s.comm.ibis.createSendPort(soPortType, "lrmc port"); soReceivePort = s.comm.ibis.createReceivePort(soPortType, "lrmc port", soInvocationHandler); if (SO_MAX_INVOCATION_DELAY > 0) { TypedProperties props = new TypedProperties(); props.setProperty("ibis.serialization", "ibis"); soMessageCombiner = new MessageCombiner(props, soSendPort); soInvocationHandler.setMessageSplitter(new MessageSplitter( props, soReceivePort)); } try { soReceivePort.enableConnections(); } catch(IbisConfigurationException e) { // LRMC ibis throws this. TODO: should it do this? // Ignored. } soReceivePort.enableMessageUpcalls(); } catch (Exception e) { commLogger.error("SATIN '" + s.ident + "': Could not start ibis: " + e, e); System.exit(1); // Could not start ibis } } else { try { soPortType = getSOPortType(); // Create a multicast port to bcast shared object invocations. // Connections are established later. soSendPort = s.comm.ibis.createSendPort(soPortType, "satin so port on " + s.ident); if (SO_MAX_INVOCATION_DELAY > 0) { TypedProperties props = new TypedProperties(); props.setProperty("ibis.serialization", "ibis"); soMessageCombiner = new MessageCombiner(props, soSendPort); } } catch (Exception e) { commLogger.error("SATIN '" + s.ident + "': Could not start ibis: " + e, e); System.exit(1); // Could not start ibis } } } public static PortType getSOPortType() throws IOException { if(LABEL_ROUTING_MCAST) { return new PortType( PortType.CONNECTION_MANY_TO_MANY, PortType.RECEIVE_EXPLICIT, PortType.RECEIVE_AUTO_UPCALLS, PortType.SERIALIZATION_OBJECT); } return new PortType( PortType.CONNECTION_ONE_TO_MANY, PortType.CONNECTION_UPCALLS, PortType.CONNECTION_DOWNCALLS, PortType.RECEIVE_EXPLICIT, PortType.RECEIVE_AUTO_UPCALLS, PortType.SERIALIZATION_OBJECT); } /** * Creates SO receive ports for new Satin instances. Do this first, to make * them available as soon as possible. */ protected void handleJoins(IbisIdentifier[] joiners) { if(DISABLE_SO_BCAST) return; // lrmc uses its own ports if (LABEL_ROUTING_MCAST) { /** Add new connections to the soSendPort */ synchronized (s) { for (int i = 0; i < joiners.length; i++) { toConnect.add(joiners[i]); } } return; } for (int i = 0; i < joiners.length; i++) { // create a receive port for this guy try { s.comm.ibis.createReceivePort(soPortType, "satin so receive port for " + joiners[i], new SOInvocationHandler(s), s.ft .getReceivePortConnectHandler(), null); } catch (Exception e) { commLogger.error("SATIN '" + s.ident + "': Could not start ibis: " + e, e); System.exit(1); // Could not start ibis } } } protected void sendAccumulatedSOInvocations() { if (SO_MAX_INVOCATION_DELAY <= 0) return; long currTime = System.currentTimeMillis(); long elapsed = currTime - soInvocationsDelayTimer; if (soInvocationsDelayTimer > 0 && (elapsed > SO_MAX_INVOCATION_DELAY || soCurrTotalMessageSize > SO_MAX_MESSAGE_SIZE)) { try { s.stats.broadcastSOInvocationsTimer.start(); soMessageCombiner.sendAccumulatedMessages(); } catch (IOException e) { System.err.println("SATIN '" + s.ident + "': unable to broadcast shared object invocations " + e); } finally { s.stats.broadcastSOInvocationsTimer.stop(); } s.stats.soRealMessageCount++; soCurrTotalMessageSize = 0; soInvocationsDelayTimer = -1; } } protected void broadcastSOInvocation(SOInvocationRecord r) { if(DISABLE_SO_BCAST) return; if (LABEL_ROUTING_MCAST) { doBroadcastSOInvocationLRMC(r); } else { if (ASYNC_SO_BCAST) { // We have to make a copy of the object first, the caller might modify it. SOInvocationRecord copy = (SOInvocationRecord) Satin.deepCopy(r); new AsyncBcaster(this, copy).start(); } else { doBroadcastSOInvocation(r); } } } /** Broadcast an so invocation */ protected void doBroadcastSOInvocationLRMC(SOInvocationRecord r) { long byteCount = 0; WriteMessage w = null; soBcastLogger.debug("SATIN '" + s.ident + "': broadcasting so invocation for: " + r.getObjectId()); connectSendPortToNewReceivers(); IbisIdentifier[] tmp; synchronized (s) { tmp = s.victims.getIbises(); } if (tmp.length == 0) return; s.stats.broadcastSOInvocationsTimer.start(); try { s.so.registerMulticast(s.so.getSOReference(r.getObjectId()), tmp); if (soSendPort != null) { try { if (SO_MAX_INVOCATION_DELAY > 0) { // do message combining w = soMessageCombiner.newMessage(); if (soInvocationsDelayTimer == -1) { soInvocationsDelayTimer = System.currentTimeMillis(); } } else { w = soSendPort.newMessage(); } w.writeByte(SO_INVOCATION); w.writeObject(r); byteCount = w.finish(); } catch (IOException e) { if (w != null) { w.finish(e); } System.err .println("SATIN '" + s.ident + "': unable to broadcast a shared object invocation: " + e); } if (SO_MAX_INVOCATION_DELAY > 0) { soCurrTotalMessageSize += byteCount; } else { s.stats.soRealMessageCount++; } } s.stats.soInvocations++; s.stats.soInvocationsBytes += byteCount; } finally { s.stats.broadcastSOInvocationsTimer.stop(); } // Try to send immediately if needed. // We might not reach a safe point for a considerable time. if (SO_MAX_INVOCATION_DELAY > 0) { sendAccumulatedSOInvocations(); } } /** Broadcast an so invocation */ protected void doBroadcastSOInvocation(SOInvocationRecord r) { long byteCount = 0; WriteMessage w = null; s.stats.broadcastSOInvocationsTimer.start(); try { connectSendPortToNewReceivers(); IbisIdentifier[] tmp; synchronized (s) { tmp = s.victims.getIbises(); } s.so.registerMulticast(s.so.getSOReference(r.getObjectId()), tmp); if (soSendPort != null && soSendPort.connectedTo().length > 0) { try { if (SO_MAX_INVOCATION_DELAY > 0) { // do message combining w = soMessageCombiner.newMessage(); if (soInvocationsDelayTimer == -1) { soInvocationsDelayTimer = System.currentTimeMillis(); } } else { w = soSendPort.newMessage(); } w.writeByte(SO_INVOCATION); w.writeObject(r); byteCount = w.finish(); } catch (IOException e) { if (w != null) { w.finish(e); } System.err .println("SATIN '" + s.ident + "': unable to broadcast a shared object invocation: " + e); } if (SO_MAX_INVOCATION_DELAY > 0) { soCurrTotalMessageSize += byteCount; } else { s.stats.soRealMessageCount++; } } s.stats.soInvocations++; s.stats.soInvocationsBytes += byteCount; } finally { s.stats.broadcastSOInvocationsTimer.stop(); } // Try to send immediately if needed. // We might not reach a safe point for a considerable time. if (SO_MAX_INVOCATION_DELAY > 0) { sendAccumulatedSOInvocations(); } } /** * This basicaly is optional, if nodes don't have the object, they will * retrieve it. However, one broadcast is more efficient (serialization is * done only once). We MUST use message combining here, we use the same receiveport * as the SO invocation messages. This is only called by exportObject. */ protected void broadcastSharedObject(SharedObject object) { if(DISABLE_SO_BCAST) return; if (LABEL_ROUTING_MCAST) { doBroadcastSharedObjectLRMC(object); } else { doBroadcastSharedObject(object); } } protected void doBroadcastSharedObject(SharedObject object) { WriteMessage w = null; long size = 0; s.stats.soBroadcastTransferTimer.start(); try { connectSendPortToNewReceivers(); if (soSendPort == null) { s.stats.soBroadcastTransferTimer.stop(); return; } IbisIdentifier[] tmp; synchronized (s) { tmp = s.victims.getIbises(); } s.so.registerMulticast(s.so.getSOReference(object.getObjectId()), tmp); try { if (SO_MAX_INVOCATION_DELAY > 0) { //do message combining w = soMessageCombiner.newMessage(); } else { w = soSendPort.newMessage(); } w.writeByte(SO_TRANSFER); s.stats.soBroadcastSerializationTimer.start(); try { w.writeObject(object); size = w.finish(); } finally { s.stats.soBroadcastSerializationTimer.stop(); } w = null; if (SO_MAX_INVOCATION_DELAY > 0) { soMessageCombiner.sendAccumulatedMessages(); } } catch (IOException e) { if (w != null) { w.finish(e); } System.err.println("SATIN '" + s.ident + "': unable to broadcast a shared object: " + e); } s.stats.soBcasts++; s.stats.soBcastBytes += size; } finally { s.stats.soBroadcastTransferTimer.stop(); } } /** Broadcast an so invocation */ protected void doBroadcastSharedObjectLRMC(SharedObject object) { soBcastLogger.info("SATIN '" + s.ident + "': broadcasting object: " + object.getObjectId()); WriteMessage w = null; long size = 0; connectSendPortToNewReceivers(); IbisIdentifier[] tmp; synchronized (s) { tmp = s.victims.getIbises(); if (tmp.length == 0) return; } if (soSendPort == null) { return; } s.stats.soBroadcastTransferTimer.start(); try { s.so.registerMulticast(s.so.getSOReference(object.getObjectId()), tmp); try { if (SO_MAX_INVOCATION_DELAY > 0) { //do message combining w = soMessageCombiner.newMessage(); } else { w = soSendPort.newMessage(); } w.writeByte(SO_TRANSFER); s.stats.soBroadcastSerializationTimer.start(); try { w.writeObject(object); size = w.finish(); } finally { s.stats.soBroadcastSerializationTimer.stop(); } w = null; if (SO_MAX_INVOCATION_DELAY > 0) { soMessageCombiner.sendAccumulatedMessages(); } } catch (IOException e) { if (w != null) { w.finish(e); } System.err.println("SATIN '" + s.ident + "': unable to broadcast a shared object: " + e); } s.stats.soBcasts++; s.stats.soBcastBytes += size; } finally { s.stats.soBroadcastTransferTimer.stop(); } } /** Remove a connection to the soSendPort */ protected void removeSOConnection(IbisIdentifier id) { Satin.assertLocked(s); ReceivePortIdentifier r = ports.remove(id); if (r != null) { Communication.disconnect(soSendPort, r); } } /** Fetch a shared object from another node. * If the Invocation record is null, any version is OK, we just test that we have a * version of the object. If it is not null, we try to satisfy the guard of the * invocation record. It might not be satisfied when this method returns, the * guard might depend on more than one shared object. */ protected void fetchObject(String objectId, IbisIdentifier source, InvocationRecord r) throws SOReferenceSourceCrashedException { if(s.so.waitForObject(objectId, source, r, SO_WAIT_FOR_UPDATES_TIME)) { return; } soLogger.debug("SATIN '" + s.ident + "': did not receive object in time, demanding it now"); // haven't got it, demand it now. sendSORequest(objectId, source, true); boolean gotIt = waitForSOReply(); if (gotIt) { soLogger.debug("SATIN '" + s.ident + "': received demanded object"); return; } soLogger.error("SATIN '" + s.ident + "': internal error: did not receive shared object after I demanded it. "); } private void sendSORequest(String objectId, IbisIdentifier source, boolean demand) throws SOReferenceSourceCrashedException { // request the shared object from the source WriteMessage w = null; try { s.lb.setCurrentVictim(source); Victim v; synchronized (s) { v = s.victims.getVictim(source); } if (v == null) { // hm we've got a problem here // push the job somewhere else? soLogger.error("SATIN '" + s.ident + "': could not " + "write shared-object request"); throw new SOReferenceSourceCrashedException(); } w = v.newMessage(); if (demand) { w.writeByte(SO_DEMAND); } else { w.writeByte(SO_REQUEST); } w.writeString(objectId); v.finish(w); } catch (IOException e) { if (w != null) { w.finish(e); } // hm we've got a problem here // push the job somewhere else? soLogger.error("SATIN '" + s.ident + "': could not " + "write shared-object request", e); throw new SOReferenceSourceCrashedException(); } } private boolean waitForSOReply() throws SOReferenceSourceCrashedException { // wait for the reply // there are three possibilities: // 1. we get the object back -> return true // 2. we get a nack back -> return false // 3. the source crashed -> exception while (true) { synchronized (s) { if (sharedObject != null) { s.so.addObject(sharedObject); sharedObject = null; s.currentVictimCrashed = false; soLogger.info("SATIN '" + s.ident + "': received shared object"); return true; } if (s.currentVictimCrashed) { s.currentVictimCrashed = false; // the source has crashed, abort the job soLogger.info("SATIN '" + s.ident + "': source crashed while waiting for SO reply"); throw new SOReferenceSourceCrashedException(); } if (receivedNack) { receivedNack = false; s.currentVictimCrashed = false; soLogger.info("SATIN '" + s.ident + "': received shared object NACK"); return false; } try { s.wait(); } catch (InterruptedException e) { // ignore } } } } boolean broadcastInProgress(SharedObjectInfo info, IbisIdentifier dest) { if (System.currentTimeMillis() - info.lastBroadcastTime > SO_WAIT_FOR_UPDATES_TIME) { return false; } for (int i = 0; i < info.destinations.length; i++) { if (info.destinations[i].equals(dest)) return true; } return false; } protected void handleSORequests() { WriteMessage wm = null; IbisIdentifier origin; String objid; boolean demand; while (true) { Victim v; synchronized (s) { if (s.so.SORequestList.getCount() == 0) { s.so.gotSORequests = false; return; } origin = s.so.SORequestList.getRequester(0); objid = s.so.SORequestList.getobjID(0); demand = s.so.SORequestList.isDemand(0); s.so.SORequestList.removeIndex(0); v = s.victims.getVictim(origin); } if (v == null) { soLogger.debug("SATIN '" + s.ident + "': vicim crached in handleSORequest"); continue; // node might have crashed } SharedObjectInfo info = s.so.getSOInfo(objid); if (ASSERTS && info == null) { soLogger.error("SATIN '" + s.ident + "': EEEK, requested shared object: " + objid + " not found! Exiting.."); System.exit(1); // Failed assertion } if (!demand && broadcastInProgress(info, v.getIdent())) { soLogger.debug("SATIN '" + s.ident + "': send NACK back in handleSORequest"); // send NACK back try { wm = v.newMessage(); wm.writeByte(SO_NACK); v.finish(wm); } catch (IOException e) { if (wm != null) { wm.finish(e); } soLogger.error("SATIN '" + s.ident + "': got exception while sending" + " shared object NACK", e); } continue; } soLogger.debug("SATIN '" + s.ident + "': send object back in handleSORequest"); sendObjectBack(v, info); } } private void sendObjectBack(Victim v, SharedObjectInfo info) { WriteMessage wm = null; long size; // No need to hold the lock while writing the object. // Updates cannot change the state of the object during the send, // they are delayed until safe a point. SharedObject so = info.sharedObject; try { s.stats.soTransferTimer.start(); try { wm = v.newMessage(); wm.writeByte(SO_TRANSFER); } catch (IOException e) { if (wm != null) { wm.finish(e); } soLogger.error("SATIN '" + s.ident + "': got exception while sending" + " shared object", e); return; } s.stats.soSerializationTimer.start(); try { wm.writeObject(so); size = v.finish(wm); } catch (IOException e) { wm.finish(e); soLogger.error("SATIN '" + s.ident + "': got exception while sending" + " shared object", e); return; } finally { s.stats.soSerializationTimer.stop(); } } finally { s.stats.soTransferTimer.stop(); } s.stats.soTransfers++; s.stats.soTransfersBytes += size; } protected void handleSORequest(ReadMessage m, boolean demand) { String objid = null; IbisIdentifier origin = m.origin().ibisIdentifier(); soLogger.info("SATIN '" + s.ident + "': got so request"); try { objid = m.readString(); // no need to finish the message. We don't do any communication } catch (IOException e) { soLogger.warn("SATIN '" + s.ident + "': got exception while reading" + " shared object request: " + e.getMessage()); } synchronized (s) { s.so.addToSORequestList(origin, objid, demand); } } /** * Receive a shared object from another node (called by the MessageHandler */ protected void handleSOTransfer(ReadMessage m) { // normal so transfer (not exportObject) SharedObject obj = null; s.stats.soDeserializationTimer.start(); try { obj = (SharedObject) m.readObject(); } catch (IOException e) { soLogger.error("SATIN '" + s.ident + "': got exception while reading" + " shared object", e); } catch (ClassNotFoundException e) { soLogger.error("SATIN '" + s.ident + "': got exception while reading" + " shared object", e); } finally { s.stats.soDeserializationTimer.stop(); } // no need to finish the read message here. // We don't block and don't do any communication synchronized (s) { sharedObject = obj; s.notifyAll(); } } protected void handleSONack(ReadMessage m) { synchronized (s) { receivedNack = true; s.notifyAll(); } } private void connectSOSendPort(IbisIdentifier ident) { String name = null; if (LABEL_ROUTING_MCAST) { name = "lrmc port"; } else { name = "satin so receive port for " + s.ident; } ReceivePortIdentifier r = Communication.connect(soSendPort, ident, name, Satin.CONNECT_TIMEOUT); if (r != null) { synchronized (s) { ports.put(ident, r); } } else { soLogger.warn("SATIN '" + s.ident + "': unable to connect to SO receive port "); // We won't broadcast the object to this receiver. // This is not really a problem, it will get the object if it // needs it. But the node has probably crashed anyway. return; } } private void connectSendPortToNewReceivers() { IbisIdentifier[] tmp; synchronized (s) { tmp = new IbisIdentifier[toConnect.size()]; for (int i = 0; i < toConnect.size(); i++) { tmp[i] = toConnect.get(i); } toConnect.clear(); } // do not keep the lock during connection setup for (int i = 0; i < tmp.length; i++) { connectSOSendPort(tmp[i]); } } public void handleMyOwnJoin() { // nothing now. } public void handleCrash(IbisIdentifier id) { // nothing now. } protected void exit() { // nothing now. } static class AsyncBcaster extends Thread { private SOCommunication c; private SOInvocationRecord r; AsyncBcaster(SOCommunication c, SOInvocationRecord r) { this.c = c; this.r = r; } public void run() { c.doBroadcastSOInvocation(r); } } }
package jade.core.behaviours; //#MIDP_EXCLUDE_FILE import jade.core.Agent; import jade.core.NotFoundException; import java.util.Vector; import java.util.Enumeration; /** This class provides support for executing JADE Behaviours in dedicated Java Threads. In order to do that it is sufficient to add to an agent a normal JADE Behaviour "wrapped" into a "threaded behaviour" as returned by the <code>wrap()</code> method of this class (see the example below). <pr><hr><blockquote><pre> ThreadedBehaviourFactory tbf = new ThreadedBehaviourFactory(); Behaviour b = // create a JADE behaviour addBehaviour(tbf.wrap(b)); </pre></blockquote><hr> This class also provides methods to control the termination of the threads dedicated to the execution of wrapped behaviours <br> <b>NOT available in MIDP</b> <br> @author Giovanni Caire - TILAB */ public class ThreadedBehaviourFactory { // Thread states (only for debugging purpose) private static final String CREATED_STATE = "CREATED"; private static final String RUNNING_STATE = "RUNNING"; private static final String CHECKING_STATE = "CHECKING"; private static final String BLOCKED_STATE = "BLOCKED"; private static final String SUSPENDED_STATE = "SUSPENDED"; private static final String TERMINATED_STATE = "TERMINATED"; private static final String INTERRUPTED_STATE = "INTERRUPTED"; private static final String ERROR_STATE = "ERROR"; private Vector threadedBehaviours = new Vector(); /** * Wraps a normal JADE Behaviour <code>b</code> into a "threaded behaviour". Adding the * wrapper behaviour to an agent results in executing <code>b</code> in a dedicated Java Therad. */ public Behaviour wrap(Behaviour b) { return new ThreadedBehaviourWrapper(b); } /** * @return The number of active threads dedicated to the execution of * wrapped behaviours. */ public int size() { return threadedBehaviours.size(); } /** * Interrupt all threaded behaviours managed by this ThreadedBehaviourFactory */ public void interrupt() { ThreadedBehaviourWrapper[] tt = getWrappers(); for (int i = 0; i < tt.length; ++i) { tt[i].interrupt(); } } /** * Blocks until all threads dedicated to the execution of threaded * behaviours complete. * @param timeout The maximum timeout to wait for threaded behaviour * termination. * @return <code>true</code> if all threaded behaviour have actually * completed, <code>false</code> otherwise. */ public synchronized boolean waitUntilEmpty(long timeout) { long time = System.currentTimeMillis(); long deadline = time + timeout; try { while(!threadedBehaviours.isEmpty()) { if (timeout > 0 && time >= deadline) { // Timeout expired break; } wait(deadline - time); time = System.currentTimeMillis(); } } catch (InterruptedException ie) { // Interrupted while waiting for threaded behaviour termination } return threadedBehaviours.isEmpty(); } /** * Interrupt a threaded behaviour. This method should be used to abort a threaded behaviour * instead of getThread().interrupt() because i) the latter may have no effect if called just after * the threaded behaviour suspended itself and ii) the threaded behaviour may be suspended * and in this case its Thread is null. * @return the Thread that was interrupted if any. */ public Thread interrupt(Behaviour b) throws NotFoundException { ThreadedBehaviourWrapper wrapper = getWrapper(b); if (wrapper != null) { return wrapper.interrupt(); } else { throw new NotFoundException(b.getBehaviourName()); } } /** * Suspend a threaded behaviour. This method has only effect if called by the threaded behaviour * itself and has the effect of releasing its dedicated Java Thread. This can later be restored * by means of the <code>resume()</code> method. */ public void suspend(Behaviour b) { ThreadedBehaviourWrapper wrapper = getWrapper(b); if (wrapper != null) { wrapper.suspend(); } } /** * Resume a threaded behaviour. Assign a new Java Thread to a threaded behaviour that is * currently suspended. */ public void resume(Behaviour b) { ThreadedBehaviourWrapper wrapper = getWrapper(b); if (wrapper != null) { wrapper.resume(); } } /** @return the Thread dedicated to the execution of the Behaviour <code>b</code> */ public Thread getThread(Behaviour b) { ThreadedBehaviourWrapper tb = getWrapper(b); if (tb != null) { return tb.getThread(); } return null; } //#APIDOC_EXCLUDE_BEGIN /** * This method is declared public for debugging purpose only * @return All the wrapper behaviours currently used by this ThreadedBehaviourFactory */ public ThreadedBehaviourWrapper[] getWrappers() { synchronized (threadedBehaviours) { ThreadedBehaviourWrapper[] wrappers = new ThreadedBehaviourWrapper[threadedBehaviours.size()]; for (int i = 0; i < wrappers.length; ++i) { wrappers[i] = (ThreadedBehaviourWrapper) threadedBehaviours.elementAt(i); } return wrappers; } } private ThreadedBehaviourWrapper getWrapper(Behaviour b) { synchronized (threadedBehaviours) { Enumeration e = threadedBehaviours.elements(); while (e.hasMoreElements()) { ThreadedBehaviourWrapper tb = (ThreadedBehaviourWrapper) e.nextElement(); if (tb.getBehaviour().equals(b)) { return tb; } } return null; } } /** * Inner class ThreadedBehaviourWrapper * This class is declared public for debugging purpose only */ public class ThreadedBehaviourWrapper extends Behaviour implements Runnable { private Thread myThread; private Behaviour myBehaviour; private volatile boolean restarted = false; private boolean finished = false; private volatile boolean suspended = false; private int exitValue; // Only for debugging purpose private volatile String threadState = CREATED_STATE; private ThreadedBehaviourWrapper(Behaviour b) { super(b.myAgent); myBehaviour = b; myBehaviour.setParent(new DummyParentBehaviour(myAgent, this)); } public void onStart() { // Be sure both the wrapped behaviour and its dummy parent are linked to the // correct agent myBehaviour.setAgent(myAgent); myBehaviour.parent.setAgent(myAgent); start(); } private void start() { // Start the dedicated thread myThread = new Thread(this); myThread.setName(myAgent.getLocalName()+"#"+myBehaviour.getBehaviourName()); myThread.start(); } public void action() { if (!finished) { block(); } } public boolean done() { return finished; } public int onEnd() { // This check only makes sense if the ThreadedBehaviourWrapper is a child // of a SerialBehaviour. In this case in fact the ThreadedBehaviourWrapper // terminates, but the parent must remain blocked. if (!myBehaviour.isRunnable()) { block(); } return exitValue; } /** Propagate the parent to the wrapped behaviour. NOTE that the <code>parent</code> member variable of the wrapped behaviour must point to the DummyParentBehaviour --> From the wrapped behaviour accessing the actual parent must always be retrieved through the getParent() method. */ protected void setParent(CompositeBehaviour parent) { super.setParent(parent); myBehaviour.setThreadedParent(parent); } public void setDataStore(DataStore ds) { myBehaviour.setDataStore(ds); } public DataStore getDataStore() { return myBehaviour.getDataStore(); } public void reset() { restarted = false; finished = false; suspended = false; myBehaviour.reset(); super.reset(); } /** Propagate a restart() call (typically this happens when this ThreadedBehaviourWrapped is directly added to the agent Scheduler and a message is received) to the wrapped threaded behaviour. */ public void restart() { myBehaviour.restart(); } /** Propagate a DOWNWARDS event (typically this happens when this ThreadedBehaviourWrapper is added as a child of a CompositeBehaviour and the latter, or an ancestor, is blocked/restarted) to the wrapped threaded behaviour. If the event is a restart, also notify the dedicated thread. */ protected void handle(RunnableChangedEvent rce) { super.handle(rce); if (!rce.isUpwards()) { myBehaviour.handle(rce); if (rce.isRunnable()) { go(); } } } private synchronized void go() { restarted = true; notifyAll(); } private synchronized void suspend() { if (Thread.currentThread() == myThread) { suspended = true; } } private synchronized void resume() { if (suspended) { suspended = false; if (myThread == null) { start(); } } } public void run() { if (threadState == CREATED_STATE) { threadedBehaviours.addElement(this); } threadState = RUNNING_STATE; try { while (true) { restarted = false; myBehaviour.actionWrapper(); synchronized (this) { // If the behaviour was restarted from outside during the action() // method, give it another chance if (restarted && (!myBehaviour.isRunnable())) { // We can't just set the runnable state of myBehaviour to true since, if myBehaviour // is a CompositeBehaviour, we may end up with myBehaviour runnable, but some of its children not runnable. // However we can't call myBehaviour.restart() here because there could be a deadlock between a thread // posting a message and the current thread (monitors are this and the agent scheduler) myBehaviour.myEvent.init(true, Behaviour.NOTIFY_DOWN); myBehaviour.handle(myBehaviour.myEvent); } if (myBehaviour.done()) { break; } else { // If we were interrupted, avoid doing anything else and terminate if (Thread.currentThread().isInterrupted() || threadState == INTERRUPTED_STATE) { throw new InterruptedException(); } // If the Behaviour suspended itself during the action() method --> Release the embedded Thread if (suspended) { threadState = SUSPENDED_STATE; myThread = null; return; } if (!myBehaviour.isRunnable()) { threadState = BLOCKED_STATE; wait(); } } } threadState = RUNNING_STATE; } exitValue = myBehaviour.onEnd(); threadState = TERMINATED_STATE; } catch (InterruptedException ie) { threadState = INTERRUPTED_STATE; System.out.println("Threaded behaviour "+myBehaviour.getBehaviourName()+" interrupted before termination"); } catch (Agent.Interrupted ae) { threadState = INTERRUPTED_STATE; System.out.println("Threaded behaviour "+myBehaviour.getBehaviourName()+" interrupted before termination"); } catch (java.lang.ThreadDeath td) { System.out.println("Threaded behaviour "+myBehaviour.getBehaviourName()+" stopped before termination"); throw td; } catch (Throwable t) { threadState = ERROR_STATE; t.printStackTrace(); } terminate(); } /** * Interrupt a threaded behaviour. This method should always be used instead of * getThread().interrupt() because the latter may have no effect if called just after * the threaded behaviour suspended itself */ private synchronized Thread interrupt() { if (myThread != null) { threadState = INTERRUPTED_STATE; myThread.interrupt(); return myThread; } else { if (threadState == SUSPENDED_STATE) { threadState = INTERRUPTED_STATE; terminate(); } return null; } } private void terminate() { finished = true; super.restart(); threadedBehaviours.removeElement(this); synchronized(ThreadedBehaviourFactory.this) { ThreadedBehaviourFactory.this.notifyAll(); } } public final Thread getThread() { return myThread; } public final Behaviour getBehaviour() { return myBehaviour; } public final String getThreadState() { return threadState; } } // END of inner class ThreadedBehaviourWrapper //#APIDOC_EXCLUDE_END /** Inner class DummyParentBehaviour. This class has the only purpose of propagating restart events in the actual wrapped behaviour to the ThreadedBehaviourWrapper. */ private class DummyParentBehaviour extends CompositeBehaviour { private ThreadedBehaviourWrapper myChild; private DummyParentBehaviour(Agent a, ThreadedBehaviourWrapper b) { super(a); myChild = b; } public boolean isRunnable() { return false; } protected void handle(RunnableChangedEvent rce) { // This is always an UPWARDS event from the threaded behaviour, but // there is no need to propagate it to the wrapper since it will // immediately block again. It would be just a waste of time. if (rce.isRunnable()) { myChild.go(); } } /** * Redefine the root() method so that both the DummyParentBehaviour * and the ThreadedBehaviourWrapper are invisible in the behaviours hierarchy */ public Behaviour root() { Behaviour r = myChild.root(); if (r == myChild) { return myChild.getBehaviour(); } else { return r; } } protected void scheduleFirst() { } protected void scheduleNext(boolean currentDone, int currentResult) { } protected boolean checkTermination(boolean currentDone, int currentResult) { return false; } protected Behaviour getCurrent() { return null; } public jade.util.leap.Collection getChildren() { return null; } } // END of inner class DummyParentBehaviour }
package org.xins.server; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import org.xins.util.MandatoryArgumentChecker; import org.xins.types.Type; import org.xins.types.TypeValueException; /** * Session. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>) * * @since XINS 0.52 */ public final class Session extends Object { // Class fields // Class functions // Constructors public Session(API api, Object id) throws IllegalArgumentException { MandatoryArgumentChecker.check("api", api, "id", id); _sessionIDType = api.getSessionIDType(); _id = id; } // Fields /** * The session ID type associated with this session, never * <code>null</code>. */ private final SessionIDType _sessionIDType; /** * The identifier for this session. */ private final Object _id; /** * Attributes for this session. This map contains {@link String} keys and * {@link Object} values. * * <p>This field is lazily initialized, so it is initially * <code>null</code>. */ private Map _attributes; // Methods /** * Gets the session ID type for this session. * * @return * the session ID type associated with this session, never * <code>null</code>. */ public SessionIDType getSessionIDType() { return _sessionIDType; } /** * Gets the identifier. * * @return * the identifier, never <code>null</code>. */ public Object getID() { return _id; } /** * Gets the identifier, converted to a string. * * @return * the session ID, converted to a {@link String}, never * <code>null</code>. */ public String getIDString() { try { return getSessionIDType().toString(_id); } catch (TypeValueException exception) { String message = "Caught unexpected " + exception.getClass().getName() + '.'; Library.RUNTIME_LOG.error(message, exception); throw new Error(message); } } public void setAttribute(String key, Object value) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("key", key); boolean debugEnabled = Library.RUNTIME_LOG.isDebugEnabled(); // If necessary init the Map and then store the entry if (_attributes == null) { if (value != null) { // Log this event String valueClass = (value == null) ? null : value.getClass().getName(); String valueString = (value == null) ? null : String.valueOf(value); Log.log_5006(key, valueClass, valueString); // Perform the actual action _attributes = new HashMap(89); _attributes.put(key, value); } else { Log.log_5007(key); } // If the value is null, then remove the entry } else if (value == null) { Log.log_5007(key); _attributes.remove(key); // XXX: Check if the map is now empty and set it to null? // Otherwise store a new entry } else { // Log this event String valueClass = (value == null) ? null : value.getClass().getName(); String valueString = (value == null) ? null : String.valueOf(value); Log.log_5006(key, valueClass, valueString); // Perform the actual action _attributes.put(key, value); } } /** * Gets all attributes and their values. * * @return * the modifiable map of attributes, or <code>null</code> if there are * no attributes. */ public Map getAttributes() { // TODO: Return an unmodifiable Map ? return _attributes; } public Object getAttribute(String key) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("key", key); if (_attributes != null) { // Get the value Object value = _attributes.get(key); // Log this event String valueClass = (value == null) ? null : value.getClass().getName(); String valueString = (value == null) ? null : String.valueOf(value); Log.log_5008(key, valueClass, valueString); return value; } else { Log.log_5008(key, null, null); return null; } } public String toString() { return _id.toString(); } }
package org.xins.server; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import org.xins.util.MandatoryArgumentChecker; import org.xins.types.Type; import org.xins.types.TypeValueException; /** * Session. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>) * * @since XINS 0.52 */ public final class Session extends Object { // Class fields /** * The logging category used by this class. This class field is never * <code>null</code>. */ private final static Logger LOG = Logger.getLogger(Session.class.getName()); // Class functions // Constructors public Session(API api, Object id) { MandatoryArgumentChecker.check("api", api, "id", id); _sessionIDType = api.getSessionIDType(); _id = id; } // Fields /** * The session ID type associated with this session, never * <code>null</code>. */ private final SessionID _sessionIDType; /** * The identifier for this session. */ private final Object _id; /** * Attributes for this session. This map contains {@link String} keys and * {@link Object} values. * * <p>This field is lazily initialized, so it is initially * <code>null</code>. */ private Map _attributes; // Methods /** * Gets the session ID type for this session. * * @return * the session ID type associated with this session, never * <code>null</code>. */ public SessionID getSessionIDType() { return _sessionIDType; } /** * Gets the identifier. * * @return * the identifier, never <code>null</code>. */ public Object getID() { return _id; } /** * Gets the identifier, converted to a string. * * @return * the session ID, converted to a {@link String}, never * <code>null</code>. */ public String getIDString() { try { return getSessionIDType().toString(_id); } catch (TypeValueException exception) { String message = "Caught unexpected " + exception.getClass().getName() + '.'; LOG.error(message, exception); throw new InternalError(message); } } public void setAttribute(String key, Object value) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("key", key); boolean debugEnabled = LOG.isDebugEnabled(); // If necessary init the Map and then store the entry if (_attributes == null) { if (value != null) { _attributes = new HashMap(89); if (debugEnabled) { String s = value instanceof String ? "\"" + value + '"' : value.getClass().getName() + " (\"" + value + "\")"; LOG.debug("Setting attribute \"" + key + "\" to " + s + '.'); } _attributes.put(key, value); } // If the value is null, then remove the entry } else if (value == null) { if (debugEnabled) { LOG.debug("Resetting session attribute \"" + key + "\"."); } _attributes.remove(key); // XXX: Check if the map is now empty and set it to null? // Otherwise store a new entry } else { if (debugEnabled) { String s = value instanceof String ? "\"" + value + '"' : value.getClass().getName() + " (\"" + value + "\")"; LOG.debug("Setting session attribute \"" + key + "\" to " + s + '.'); } _attributes.put(key, value); } } public Object getAttribute(String key) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("key", key); if (_attributes != null) { return _attributes.get(key); } else { return null; } } /** * Touches this session so the expiry timer will be reset. */ public void touch() { // TODO } }
package com.jaeksoft.searchlib.index; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.concurrent.locks.ReentrantLock; import org.apache.lucene.analysis.PerFieldAnalyzerWrapper; import org.apache.lucene.document.Document; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.search.Similarity; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.store.LockObtainFailedException; import com.jaeksoft.searchlib.Logging; import com.jaeksoft.searchlib.SearchLibException; import com.jaeksoft.searchlib.analysis.Analyzer; import com.jaeksoft.searchlib.analysis.CompiledAnalyzer; import com.jaeksoft.searchlib.analysis.LanguageEnum; import com.jaeksoft.searchlib.function.expression.SyntaxError; import com.jaeksoft.searchlib.request.SearchRequest; import com.jaeksoft.searchlib.schema.Field; import com.jaeksoft.searchlib.schema.Schema; import com.jaeksoft.searchlib.schema.SchemaField; public class WriterLocal extends WriterAbstract { private final ReentrantLock l = new ReentrantLock(true); private IndexWriter indexWriter; private ReaderLocal readerLocal; private String similarityClass; private int maxNumSegments; protected WriterLocal(IndexConfig indexConfig, ReaderLocal readerLocal) throws IOException { super(indexConfig); this.readerLocal = readerLocal; this.indexWriter = null; this.similarityClass = indexConfig.getSimilarityClass(); this.maxNumSegments = indexConfig.getMaxNumSegments(); } private void unlock() { try { Directory dir = readerLocal.getDirectory(); if (!IndexWriter.isLocked(dir)) return; IndexWriter.unlock(dir); } catch (IOException e) { Logging.logger.error(e.getMessage(), e); } } private void close() { l.lock(); try { if (indexWriter != null) { try { indexWriter.close(); } catch (CorruptIndexException e) { Logging.logger.error(e.getMessage(), e); } catch (IOException e) { Logging.logger.error(e.getMessage(), e); } finally { unlock(); } indexWriter = null; } } finally { l.unlock(); } } private void open() throws CorruptIndexException, LockObtainFailedException, IOException, InstantiationException, IllegalAccessException, ClassNotFoundException { l.lock(); try { if (indexWriter != null) return; indexWriter = openIndexWriter(readerLocal.getDirectory(), false); indexWriter.setMaxMergeDocs(1000000); if (similarityClass != null) { Similarity similarity = (Similarity) Class.forName( similarityClass).newInstance(); indexWriter.setSimilarity(similarity); } } finally { l.unlock(); } } private static IndexWriter openIndexWriter(Directory directory, boolean create) throws CorruptIndexException, LockObtainFailedException, IOException { return new IndexWriter(directory, null, create, IndexWriter.MaxFieldLength.UNLIMITED); } private final static SimpleDateFormat dateDirFormat = new SimpleDateFormat( "yyyyMMddHHmmss"); protected static File createIndex(File rootDir) throws IOException { File dataDir = new File(rootDir, dateDirFormat.format(new Date())); Directory directory = null; IndexWriter indexWriter = null; try { dataDir.mkdirs(); directory = FSDirectory.open(dataDir); indexWriter = openIndexWriter(directory, true); return dataDir; } catch (IOException e) { throw e; } finally { if (indexWriter != null) { try { indexWriter.close(); } catch (CorruptIndexException e) { Logging.logger.error(e.getMessage(), e); } catch (IOException e) { Logging.logger.error(e.getMessage(), e); } } if (directory != null) { try { directory.close(); } catch (IOException e) { Logging.logger.error(e.getMessage(), e); } } } } public void addDocument(Document document) throws CorruptIndexException, LockObtainFailedException, IOException, InstantiationException, IllegalAccessException, ClassNotFoundException { l.lock(); try { open(); indexWriter.addDocument(document); close(); } finally { l.unlock(); } } private boolean updateDoc(Schema schema, IndexDocument document) throws CorruptIndexException, IOException, NoSuchAlgorithmException, SearchLibException { if (!acceptDocument(document)) return false; if (beforeUpdateList != null) for (BeforeUpdateInterface beforeUpdate : beforeUpdateList) beforeUpdate.update(schema, document); Document doc = getLuceneDocument(schema, document); PerFieldAnalyzerWrapper pfa = schema.getIndexPerFieldAnalyzer(document .getLang()); Field uniqueField = schema.getFieldList().getUniqueField(); if (uniqueField != null) { String uniqueFieldName = uniqueField.getName(); String uniqueFieldValue = doc.get(uniqueFieldName); indexWriter.updateDocument(new Term(uniqueFieldName, uniqueFieldValue), doc, pfa); } else indexWriter.addDocument(doc, pfa); return true; } @Override public boolean updateDocument(Schema schema, IndexDocument document) throws SearchLibException { l.lock(); try { open(); boolean updated = updateDoc(schema, document); close(); if (updated) readerLocal.reload(); return updated; } catch (CorruptIndexException e) { throw new SearchLibException(e); } catch (LockObtainFailedException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } catch (InstantiationException e) { throw new SearchLibException(e); } catch (IllegalAccessException e) { throw new SearchLibException(e); } catch (ClassNotFoundException e) { throw new SearchLibException(e); } catch (NoSuchAlgorithmException e) { throw new SearchLibException(e); } finally { close(); l.unlock(); } } @Override public int updateDocuments(Schema schema, Collection<IndexDocument> documents) throws SearchLibException { l.lock(); try { int count = 0; open(); for (IndexDocument document : documents) if (updateDoc(schema, document)) count++; close(); if (count > 0) readerLocal.reload(); return count; } catch (CorruptIndexException e) { throw new SearchLibException(e); } catch (LockObtainFailedException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } catch (InstantiationException e) { throw new SearchLibException(e); } catch (IllegalAccessException e) { throw new SearchLibException(e); } catch (ClassNotFoundException e) { throw new SearchLibException(e); } catch (NoSuchAlgorithmException e) { throw new SearchLibException(e); } finally { close(); l.unlock(); } } private static Document getLuceneDocument(Schema schema, IndexDocument document) throws IOException, SearchLibException { schema.getQueryPerFieldAnalyzer(document.getLang()); Document doc = new Document(); LanguageEnum lang = document.getLang(); for (FieldContent fieldContent : document) { String fieldName = fieldContent.getField(); SchemaField field = schema.getFieldList().get(fieldName); if (field != null) { Analyzer analyzer = schema.getAnalyzer(field, lang); CompiledAnalyzer compiledAnalyzer = (analyzer == null) ? null : analyzer.getIndexAnalyzer(); for (String value : fieldContent.getValues()) { if (value == null) continue; if (compiledAnalyzer != null) if (!compiledAnalyzer.isAnyToken(fieldName, value)) continue; doc.add(field.getLuceneField(value)); } } } return doc; } @Override public void optimize() throws SearchLibException { l.lock(); try { open(); indexWriter.optimize(maxNumSegments, true); close(); } catch (CorruptIndexException e) { throw new SearchLibException(e); } catch (LockObtainFailedException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } catch (InstantiationException e) { throw new SearchLibException(e); } catch (IllegalAccessException e) { throw new SearchLibException(e); } catch (ClassNotFoundException e) { throw new SearchLibException(e); } finally { close(); l.unlock(); } } @Override public boolean deleteDocument(Schema schema, String uniqueField) throws SearchLibException { l.lock(); try { open(); indexWriter.deleteDocuments(new Term(schema.getFieldList() .getUniqueField().getName(), uniqueField)); close(); readerLocal.reload(); return true; } catch (CorruptIndexException e) { throw new SearchLibException(e); } catch (LockObtainFailedException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } catch (InstantiationException e) { throw new SearchLibException(e); } catch (IllegalAccessException e) { throw new SearchLibException(e); } catch (ClassNotFoundException e) { throw new SearchLibException(e); } finally { close(); l.unlock(); } } @Override public int deleteDocuments(Schema schema, Collection<String> uniqueFields) throws SearchLibException { String uniqueField = schema.getFieldList().getUniqueField().getName(); Term[] terms = new Term[uniqueFields.size()]; int i = 0; for (String value : uniqueFields) terms[i++] = new Term(uniqueField, value); l.lock(); try { open(); indexWriter.deleteDocuments(terms); close(); if (terms.length > 0) readerLocal.reload(); return terms.length; } catch (CorruptIndexException e) { throw new SearchLibException(e); } catch (LockObtainFailedException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } catch (InstantiationException e) { throw new SearchLibException(e); } catch (IllegalAccessException e) { throw new SearchLibException(e); } catch (ClassNotFoundException e) { throw new SearchLibException(e); } finally { close(); l.unlock(); } } @Override public int deleteDocuments(SearchRequest query) throws SearchLibException { l.lock(); try { open(); indexWriter.deleteDocuments(query.getQuery()); close(); readerLocal.reload(); return 0; } catch (CorruptIndexException e) { throw new SearchLibException(e); } catch (LockObtainFailedException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } catch (InstantiationException e) { throw new SearchLibException(e); } catch (IllegalAccessException e) { throw new SearchLibException(e); } catch (ClassNotFoundException e) { throw new SearchLibException(e); } catch (ParseException e) { throw new SearchLibException(e); } catch (SyntaxError e) { throw new SearchLibException(e); } finally { close(); l.unlock(); } } public void xmlInfo(PrintWriter writer) { // TODO Auto-generated method stub } }
package com.jaeksoft.searchlib.web; import java.io.IOException; import java.io.PrintWriter; import java.net.URI; import java.net.URISyntaxException; import java.security.NoSuchAlgorithmException; import java.util.Collection; import javax.servlet.http.HttpServletRequest; import org.apache.commons.httpclient.HttpException; import com.jaeksoft.searchlib.Client; import com.jaeksoft.searchlib.remote.StreamReadObject; import com.jaeksoft.searchlib.request.DeleteRequest; public class DeleteServlet extends AbstractServlet { private static final long serialVersionUID = -2663934578246659291L; private boolean deleteUniqDoc(Client client, String indexName, String uniq) throws NoSuchAlgorithmException, IOException, URISyntaxException { if (indexName == null) return client.deleteDocument(uniq); else return client.deleteDocument(indexName, uniq); } private boolean deleteDocById(Client client, String indexName, int docId) throws NoSuchAlgorithmException, IOException, URISyntaxException { if (indexName == null) return client.deleteDocument(docId); else return client.deleteDocument(indexName, docId); } private int deleteUniqDocs(Client client, String indexName, Collection<String> uniqFields) throws NoSuchAlgorithmException, IOException, URISyntaxException { if (indexName == null) return client.deleteDocuments(uniqFields); else return client.deleteDocuments(indexName, uniqFields); } private int deleteDocsById(Client client, String indexName, Collection<Integer> docIds) throws NoSuchAlgorithmException, IOException, URISyntaxException { if (indexName == null) return client.deleteDocumentsById(docIds); else return client.deleteDocumentsbyId(indexName, docIds); } @SuppressWarnings("unchecked") private Object doObjectRequest(HttpServletRequest request, String indexName, boolean byId) throws ServletException { StreamReadObject readObject = null; try { Client client = Client.getWebAppInstance(); readObject = new StreamReadObject(request.getInputStream()); Object obj = readObject.read(); if (obj instanceof DeleteRequest) { if (byId) return deleteDocsById(client, indexName, ((DeleteRequest<Integer>) obj).getCollection()); else return deleteUniqDocs(client, indexName, ((DeleteRequest<String>) obj).getCollection()); } else if (obj instanceof String) return deleteUniqDoc(client, indexName, (String) obj); else if (obj instanceof Integer) return deleteDocById(client, indexName, (Integer) obj); return "Error"; } catch (Exception e) { throw new ServletException(e); } finally { if (readObject != null) readObject.close(); } } @Override protected void doRequest(ServletTransaction transaction) throws ServletException { try { Client client = Client.getWebAppInstance(); HttpServletRequest request = transaction.getServletRequest(); String indexName = request.getParameter("index"); String uniq = request.getParameter("uniq"); String docId = request.getParameter("docId"); boolean byId = request.getParameter("byId") != null; Object result = null; if (uniq != null) result = deleteUniqDoc(client, indexName, uniq); else if (docId != null) result = deleteDocById(client, indexName, Integer .parseInt(docId)); else result = doObjectRequest(request, indexName, byId); PrintWriter pw = transaction.getWriter("UTF-8"); pw.println(result); } catch (Exception e) { throw new ServletException(e); } } public static boolean delete(URI uri, String indexName, String uniqueField) throws IOException, URISyntaxException { String msg = call(buildUri(uri, "/delete", indexName, "uniq=" + uniqueField)); return Boolean.getBoolean(msg.trim()); } public static int delete(URI uri, String indexName, Collection<String> uniqueFields) throws IOException, URISyntaxException { String msg = sendObject(buildUri(uri, "/delete", indexName, null), new DeleteRequest<String>(uniqueFields)); return Integer.parseInt(msg.trim()); } public static boolean deleteDocument(URI uri, String indexName, int docId) throws HttpException, IOException, URISyntaxException { String msg = call(buildUri(uri, "/delete", indexName, "id=" + docId)); return Boolean.getBoolean(msg.trim()); } public static int deleteDocuments(URI uri, String indexName, Collection<Integer> docIds) throws IOException, URISyntaxException { String msg = sendObject( buildUri(uri, "/delete", indexName, "byId=yes"), new DeleteRequest<Integer>(docIds)); return Integer.parseInt(msg.trim()); } }
package org.archive.wayback.query; import java.text.ParseException; import java.util.Iterator; import javax.servlet.http.HttpServletRequest; import org.archive.wayback.WaybackConstants; import org.archive.wayback.ReplayResultURIConverter; import org.archive.wayback.core.SearchResult; import org.archive.wayback.core.SearchResults; import org.archive.wayback.core.Timestamp; import org.archive.wayback.core.WaybackRequest; /** * Abstraction class to provide a single, (hopefully) simpler interface to * query results for UI JSPs. Handles slight massaging of SearchResults (to * fix zero-based/one-based numbers) URI fixup and creation for result pages, * and later may provide more functionality for dividing results into columns, * again to simplify UI JSPs. * * @author brad * @version $Date$, $Revision$ */ public class UIQueryResults { private WaybackRequest wbRequest; private String searchUrl; private Timestamp startTimestamp; private Timestamp endTimestamp; private Timestamp firstResultTimestamp; private Timestamp lastResultTimestamp; private int resultsReturned; private int resultsMatching; private int resultsPerPage; private int firstResult; private int lastResult; private int numPages; private int curPage; private SearchResults results; private HttpServletRequest httpRequest; private ReplayResultURIConverter uriConverter; /** * Constructor -- chew search result summaries into format easier for JSPs * to digest. * * @param httpRequest * @param wbRequest * @param results * @param uriConverter * @throws ParseException */ public UIQueryResults(HttpServletRequest httpRequest, WaybackRequest wbRequest, SearchResults results, ReplayResultURIConverter uriConverter) throws ParseException { this.searchUrl = wbRequest.get(WaybackConstants.RESULT_URL); this.startTimestamp = Timestamp.parseBefore(results. getFilter(WaybackConstants.REQUEST_START_DATE)); this.endTimestamp = Timestamp.parseBefore(results.getFilter( WaybackConstants.REQUEST_END_DATE)); this.firstResultTimestamp = Timestamp.parseBefore(results .getFirstResultDate()); this.lastResultTimestamp = Timestamp.parseBefore(results .getLastResultDate()); this.resultsReturned = Integer.parseInt(results.getFilter( WaybackConstants.RESULTS_NUM_RETURNED)); this.resultsMatching = Integer.parseInt(results.getFilter( WaybackConstants.RESULTS_NUM_RESULTS)); this.resultsPerPage = Integer.parseInt(results.getFilter( WaybackConstants.RESULTS_REQUESTED)); this.firstResult = Integer.parseInt(results.getFilter( WaybackConstants.RESULTS_FIRST_RETURNED)) + 1; this.lastResult = ((firstResult - 1) + resultsReturned); // calculate total pages: numPages = (int) Math.ceil((double)resultsMatching/(double)resultsPerPage); curPage = (int) Math.floor(((double)(firstResult-1))/(double)resultsPerPage) + 1; this.results = results; this.uriConverter = uriConverter; this.wbRequest = wbRequest; this.httpRequest = httpRequest; } /** * @return Timestamp end cutoff requested by user */ public Timestamp getEndTimestamp() { return endTimestamp; } /** * @return first Timestamp in returned ResourceResults */ public Timestamp getFirstResultTimestamp() { return firstResultTimestamp; } /** * @return last Timestamp in returned ResourceResults */ public Timestamp getLastResultTimestamp() { return lastResultTimestamp; } /** * @return URL or URL prefix requested by user */ public String getSearchUrl() { return searchUrl; } /** * @return Timestamp start cutoff requested by user */ public Timestamp getStartTimestamp() { return startTimestamp; } /** * @return Iterator of ResourceResults */ public Iterator resultsIterator() { return results.iterator(); } /** * @param result * @return URL string that will replay the specified Resource Result. */ public String resultToReplayUrl(SearchResult result) { return uriConverter.makeReplayURI(result); } /** * @return String pretty representation of end date range filter */ public String prettySearchEndDate() { return endTimestamp.prettyDate(); } /** * @return String pretty representation of start date range filter */ public String prettySearchStartDate() { return startTimestamp.prettyDate(); } /** * @return Returns the firstResult. */ public int getFirstResult() { return firstResult; } /** * @return Returns the resultsMatching. */ public int getResultsMatching() { return resultsMatching; } /** * @return Returns the resultsPerPage. */ public int getResultsPerPage() { return resultsPerPage; } /** * @return Returns the resultsReturned. */ public int getResultsReturned() { return resultsReturned; } /** * @return Returns the curPage. */ public int getCurPage() { return curPage; } /** * @return Returns the numPages. */ public int getNumPages() { return numPages; } /** * @param pageNum * @return String URL which will drive browser to search results for a * different page of results for the same query */ public String urlForPage(int pageNum) { return httpRequest.getContextPath() + "/query?" + wbRequest.getQueryArguments(pageNum); } /** * @return Returns the lastResult. */ public int getLastResult() { return lastResult; } /** * @return Returns the results. */ public SearchResults getResults() { return results; } private static void replaceAll(StringBuffer s, final String o, final String n) { int olen = o.length(); int nlen = n.length(); int found = s.indexOf(o); while(found >= 0) { s.replace(found,found + olen,n); found = s.indexOf(o,found + nlen); } } /** * return a string appropriate for inclusion as an XML tag * @param tagName * @return encoded tagName */ public static String encodeXMLEntity(final String tagName) { StringBuffer encoded = new StringBuffer(tagName); //replaceAll(encoded,";","&semi;"); replaceAll(encoded,"&","&amp;"); replaceAll(encoded,"\"","&quot;"); replaceAll(encoded,"'","&apos;"); replaceAll(encoded,"<","&lt;"); replaceAll(encoded,">","&gt;"); return encoded.toString(); } /** * return a string appropriate for inclusion as an XML tag * @param content * @return encoded content */ public static String encodeXMLContent(final String content) { StringBuffer encoded = new StringBuffer(content); replaceAll(encoded,"&","&amp;"); replaceAll(encoded,"\"","&quot;"); replaceAll(encoded,"'","&apos;"); replaceAll(encoded,"<","&lt;"); replaceAll(encoded,">","&gt;"); return encoded.toString(); } /** * return a string appropriate for inclusion as an XML tag * @param content * @return encoded content */ public static String encodeXMLEntityQuote(final String content) { StringBuffer encoded = new StringBuffer(content); replaceAll(encoded,"amp","&#38;#38;"); replaceAll(encoded,"apos","& replaceAll(encoded,"<","&#38;#60;"); replaceAll(encoded,"gt","& replaceAll(encoded,"quot","& return encoded.toString(); } }
package org.archive.wayback.replay; import java.io.IOException; import java.text.ParseException; import java.util.Enumeration; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.logging.Logger; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.archive.wayback.WaybackConstants; import org.archive.wayback.ReplayRenderer; import org.archive.wayback.ReplayResultURIConverter; import org.archive.wayback.ResourceIndex; import org.archive.wayback.ResourceStore; import org.archive.wayback.core.Resource; import org.archive.wayback.core.SearchResult; import org.archive.wayback.core.SearchResults; import org.archive.wayback.core.Timestamp; import org.archive.wayback.core.WaybackRequest; import org.archive.wayback.core.WaybackLogic; import org.archive.wayback.exception.BadQueryException; import org.archive.wayback.exception.ResourceNotInArchiveException; import org.archive.wayback.exception.WaybackException; /** * Servlet implementation for Wayback Replay requests. * * @author Brad Tofel * @version $Date$, $Revision$ */ public class ReplayServlet extends HttpServlet { private static final Logger LOGGER = Logger.getLogger(ReplayServlet.class .getName()); private static final String WMREQUEST_ATTRIBUTE = "wmrequest.attribute"; private static final long serialVersionUID = 1L; private WaybackLogic wayback = new WaybackLogic(); /** * Constructor */ public ReplayServlet() { super(); } public void init(ServletConfig c) throws ServletException { Properties p = new Properties(); for (Enumeration e = c.getInitParameterNames(); e.hasMoreElements();) { String key = (String) e.nextElement(); p.put(key, c.getInitParameter(key)); } ServletContext sc = c.getServletContext(); for (Enumeration e = sc.getInitParameterNames(); e.hasMoreElements();) { String key = (String) e.nextElement(); p.put(key, sc.getInitParameter(key)); } try { wayback.init(p); } catch (Exception e) { throw new ServletException(e.getMessage()); } } private String getMapParam(Map queryMap, String field) { String arr[] = (String[]) queryMap.get(field); if (arr == null || arr.length == 0) { return null; } return arr[0]; } private WaybackRequest parseCGIRequest(HttpServletRequest httpRequest) throws BadQueryException { WaybackRequest wbRequest = new WaybackRequest(); Map queryMap = httpRequest.getParameterMap(); Set keys = queryMap.keySet(); Iterator itr = keys.iterator(); while (itr.hasNext()) { String key = (String) itr.next(); String val = getMapParam(queryMap, key); wbRequest.put(key, val); } String referer = httpRequest.getHeader("REFERER"); if (referer == null) { referer = null; } wbRequest.put(WaybackConstants.REQUEST_REFERER_URL, referer); return wbRequest; } private SearchResult getClosest(SearchResults results, WaybackRequest wbRequest) throws ParseException { SearchResult closest = null; long closestDistance = 0; SearchResult cur = null; Timestamp wantTimestamp; wantTimestamp = Timestamp.parseBefore(wbRequest .get(WaybackConstants.REQUEST_EXACT_DATE)); Iterator itr = results.iterator(); while (itr.hasNext()) { cur = (SearchResult) itr.next(); long curDistance; try { Timestamp curTimestamp = Timestamp.parseBefore(cur .get(WaybackConstants.RESULT_CAPTURE_DATE)); curDistance = curTimestamp .absDistanceFromTimestamp(wantTimestamp); } catch (ParseException e) { continue; } if ((closest == null) || (curDistance < closestDistance)) { closest = cur; closestDistance = curDistance; } } return closest; } public void doGet(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException { WaybackRequest wbRequest = (WaybackRequest) httpRequest .getAttribute(WMREQUEST_ATTRIBUTE); ResourceIndex idx = wayback.getResourceIndex(); ResourceStore store = wayback.getResourceStore(); ReplayResultURIConverter uriConverter = wayback.getURIConverter(); ReplayRenderer renderer = wayback.getReplayRenderer(); Resource resource = null; try { if (wbRequest == null) { wbRequest = parseCGIRequest(httpRequest); } SearchResults results = idx.query(wbRequest); SearchResult closest = getClosest(results, wbRequest); // TODO loop here looking for closest online/available version? // OPTIMIZ maybe assume version is here and redirect now if not // exactly the date user requested, before retrieving it... resource = store.retrieveResource(closest); renderer.renderResource(httpRequest, httpResponse, wbRequest, closest, resource, uriConverter); } catch (ResourceNotInArchiveException nia) { LOGGER.info("NotInArchive\t" + wbRequest.get(WaybackConstants.REQUEST_URL)); renderer.renderException(httpRequest, httpResponse, wbRequest, nia); } catch (WaybackException wbe) { renderer.renderException(httpRequest, httpResponse, wbRequest, wbe); } catch (Exception e) { // TODO show something Wayback'ish to the user rather than letting // the container deal? e.printStackTrace(); throw new ServletException(e.getMessage()); } finally { if (resource != null) { resource.close(); } } } }
package org.jdesktop.swingx.calendar; import java.awt.*; import java.awt.event.*; import java.text.SimpleDateFormat; import java.text.DateFormatSymbols; import java.util.Calendar; import java.util.Date; import java.util.Hashtable; import java.util.TimeZone; import javax.swing.*; import javax.swing.border.Border; /** * Component that displays a month calendar which can be used to select a day * or range of days. By default the <code>JXMonthView</code> will display a * single calendar using the current month and year, using * <code>Calendar.SUNDAY</code> as the first day of the week. * <p> * The <code>JXMonthView</code> can be configured to display more than one * calendar at a time by calling * <code>setPreferredCalCols</code>/<code>setPreferredCalRows</code>. These * methods will set the preferred number of calendars to use in each * column/row. As these values change, the <code>Dimension</code> returned * from <code>getMinimumSize</code> and <code>getPreferredSize</code> will * be updated. The following example shows how to create a 2x2 view which is * contained within a <code>JFrame</code>: * <pre> * JXMonthView monthView = new JXMonthView(); * monthView.setPreferredCols(2); * monthView.setPreferredRows(2); * * JFrame frame = new JFrame(); * frame.getContentPane().add(monthView); * frame.pack(); * frame.setVisible(true); * </pre> * <p> * <code>JXMonthView</code> can be further configured to allow any day of the * week to be considered the first day of the week. Character * representation of those days may also be set by providing an array of * strings. * <pre> * monthView.setFirstDayOfWeek(Calendar.MONDAY); * monthView.setDaysOfTheWeek( * new String[]{"S", "M", "T", "W", "Th", "F", "S"}); * </pre> * <p> * This component supports flagging days. These flagged days, which must be * provided in sorted order, are displayed in a bold font. This can be used to * inform the user of such things as scheduled appointment. * <pre> * // Create some dates that we want to flag as being important. * Calendar cal1 = Calendar.getInstance(); * cal1.set(2004, 1, 1); * Calendar cal2 = Calendar.getInstance(); * cal2.set(2004, 1, 5); * * long[] flaggedDates = new long[] { * cal1.getTimeInMillis(), * cal2.getTimeInMillis(), * System.currentTimeMillis() * }; * * // Sort them in ascending order. * java.util.Arrays.sort(flaggedDates); * monthView.setFlaggedDates(flaggedDates); * </pre> * Applications may have the need to allow users to select different ranges of * dates. There are four modes of selection that are supported, single, * multiple, week and no selection. Once a selection is made an action is * fired, with exception of the no selection mode, to inform listeners that * selection has changed. * <pre> * // Change the selection mode to select full weeks. * monthView.setSelectionMode(JXMonthView.WEEK_SELECTION); * * // Add an action listener that will be notified when the user * // changes selection via the mouse. * monthView.addActionListener(new ActionListener() { * public void actionPerformed(ActionEvent e) { * System.out.println( * ((JXMonthView)e.getSource()).getSelectedDateSpan()); * } * }); * </pre> * * @author Joshua Outwater * @version $Revision$ */ public class JXMonthView extends JComponent { /** Mode that disallows selection of days from the calendar. */ public static final int NO_SELECTION = 0; /** Mode that allows for selection of a single day. */ public static final int SINGLE_SELECTION = 1; /** Mode that allows for selecting of multiple consecutive days. */ public static final int MULTIPLE_SELECTION = 2; /** * Mode where selections consisting of more than 7 days will * snap to a full week. */ public static final int WEEK_SELECTION = 3; /** Return value used to identify when the month down button is pressed. */ public static final int MONTH_DOWN = 1; /** Return value used to identify when the month up button is pressed. */ public static final int MONTH_UP = 2; /** * Insets used in determining the rectangle for the month string * background. */ protected Insets _monthStringInsets = new Insets(0,0,0,0); private static final int MONTH_DROP_SHADOW = 1; private static final int MONTH_LINE_DROP_SHADOW = 2; private static final int WEEK_DROP_SHADOW = 4; private int _boxPaddingX = 3; private int _boxPaddingY = 3; private int _arrowPaddingX = 3; private int _arrowPaddingY = 3; private static final int CALENDAR_SPACING = 10; private static final int DAYS_IN_WEEK = 7; private static final int MONTHS_IN_YEAR = 12; /** * Keeps track of the first date we are displaying. We use this as a * restore point for the calendar. */ private long _firstDisplayedDate; private int _firstDisplayedMonth; private int _firstDisplayedYear; private long _lastDisplayedDate; private Font _derivedFont; /** Beginning date of selection. -1 if no date is selected. */ private long _startSelectedDate = -1; /** End date of selection. -1 if no date is selected. */ private long _endSelectedDate = -1; /** For multiple selection we need to record the date we pivot around. */ private long _pivotDate = -1; /** Bounds of the selected date including its visual border. */ private Rectangle _selectedDateRect = new Rectangle(); /** The number of calendars able to be displayed horizontally. */ private int _numCalCols = 1; /** The number of calendars able to be displayed vertically. */ private int _numCalRows = 1; private int _minCalCols = 1; private int _minCalRows = 1; private long _today; private long[] _flaggedDates; private int _selectionMode = SINGLE_SELECTION; private int _boxHeight; private int _boxWidth; private int _monthBoxHeight; private int _calendarWidth; private int _calendarHeight; private int _firstDayOfWeek = Calendar.SUNDAY; private int _startX; private int _startY; private int _dropShadowMask = 0; private boolean _dirty = false; private boolean _antiAlias = false; private boolean _ltr; private boolean _traversable = false; private boolean _asKirkWouldSay_FIRE = false; private Calendar _cal; private String[] _daysOfTheWeek; private static String[] _monthsOfTheYear; private Dimension _dim = new Dimension(); private Rectangle _bounds = new Rectangle(); private Rectangle _dirtyRect = new Rectangle(); private Color _todayBackgroundColor; private Color _monthStringBackground; private Color _monthStringForeground; private Color _daysOfTheWeekForeground; private Color _selectedBackground; private SimpleDateFormat _dayOfMonthFormatter = new SimpleDateFormat("d"); private String _actionCommand = "selectionChanged"; private Timer _todayTimer = null; private ImageIcon _monthDownImage; private ImageIcon _monthUpImage; private Hashtable _dayToColorTable = new Hashtable<Integer, Color>(); /** * Create a new instance of the <code>JXMonthView</code> class using the * month and year of the current day as the first date to display. */ public JXMonthView() { this(new Date().getTime()); } /** * Create a new instance of the <code>JXMonthView</code> class using the * month and year from <code>initialTime</code> as the first date to * display. * * @param initialTime The first month to display. */ public JXMonthView(long initialTime) { super(); _ltr = getComponentOrientation().isLeftToRight(); // Set up calendar instance. _cal = Calendar.getInstance(getLocale()); _cal.setFirstDayOfWeek(_firstDayOfWeek); // Keep track of today. _cal.set(Calendar.HOUR_OF_DAY, 0); _cal.set(Calendar.MINUTE, 0); _cal.set(Calendar.SECOND, 0); _cal.set(Calendar.MILLISECOND, 0); _today = _cal.getTimeInMillis(); _cal.setTimeInMillis(initialTime); setFirstDisplayedDate(_cal.getTimeInMillis()); // Get string representation of the months of the year. _monthsOfTheYear = new DateFormatSymbols().getMonths(); setOpaque(true); setBackground(Color.WHITE); _todayBackgroundColor = getForeground(); // Restore original time value. _cal.setTimeInMillis(_firstDisplayedDate); enableEvents(AWTEvent.MOUSE_EVENT_MASK); enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK); updateUI(); } /** * Resets the UI property to a value from the current look and feel. */ public void updateUI() { super.updateUI(); String[] daysOfTheWeek = (String[])UIManager.get("JXMonthView.daysOfTheWeek"); if (daysOfTheWeek == null) { String[] dateFormatSymbols = new DateFormatSymbols().getShortWeekdays(); daysOfTheWeek = new String[DAYS_IN_WEEK]; for (int i = Calendar.SUNDAY; i <= Calendar.SATURDAY; i++) { daysOfTheWeek[i - 1] = dateFormatSymbols[i]; } } setDaysOfTheWeek(daysOfTheWeek); Color color = UIManager.getColor("JXMonthView.monthStringBackground"); if (color == null) { color = new Color(138, 173, 209); } setMonthStringBackground(color); color = UIManager.getColor("JXMonthView.monthStringForeground"); if (color == null) { color = new Color(68, 68, 68); } setMonthStringForeground(color); color = UIManager.getColor("JXMonthView.daysOfTheWeekForeground"); if (color == null) { color = new Color(68, 68, 68); } setDaysOfTheWeekForeground(color); color = UIManager.getColor("JXMonthView.selectedBackground"); if (color == null) { color = new Color(197, 220, 240); } setSelectedBackground(color); Font font = UIManager.getFont("JXMonthView.font"); if (font == null) { font = UIManager.getFont("Button.font"); } setFont(font); String imageLocation = UIManager.getString("JXMonthView.monthDownFileName"); if (imageLocation == null) { imageLocation = "resources/month-down.png"; } _monthDownImage = new ImageIcon( JXMonthView.class.getResource(imageLocation)); imageLocation = UIManager.getString("JXMonthView.monthUpFileName"); if (imageLocation == null) { imageLocation = "resources/month-up.png"; } _monthUpImage = new ImageIcon( JXMonthView.class.getResource(imageLocation)); } /** * Returns the first displayed date. * * @return long The first displayed date. */ public long getFirstDisplayedDate() { return _firstDisplayedDate; } /** * Set the first displayed date. We only use the month and year of * this date. The <code>Calendar.DAY_OF_MONTH</code> field is reset to * 1 and all other fields, with exception of the year and month , * are reset to 0. * * @param date The first displayed date. */ public void setFirstDisplayedDate(long date) { long old = _firstDisplayedDate; _cal.setTimeInMillis(date); _cal.set(Calendar.DAY_OF_MONTH, 1); _cal.set(Calendar.HOUR_OF_DAY, 0); _cal.set(Calendar.MINUTE, 0); _cal.set(Calendar.SECOND, 0); _cal.set(Calendar.MILLISECOND, 0); _firstDisplayedDate = _cal.getTimeInMillis(); _firstDisplayedMonth = _cal.get(Calendar.MONTH); _firstDisplayedYear = _cal.get(Calendar.YEAR); calculateLastDisplayedDate(); firePropertyChange("firstDisplayedDate", old, _firstDisplayedDate); repaint(); } /** * Returns the last date able to be displayed. For example, if the last * visible month was April the time returned would be April 30, 23:59:59. * * @return long The last displayed date. */ public long getLastDisplayedDate() { return _lastDisplayedDate; } private void calculateLastDisplayedDate() { long old = _lastDisplayedDate; _cal.setTimeInMillis(_firstDisplayedDate); // Figure out the last displayed date. _cal.add(Calendar.MONTH, ((_numCalCols * _numCalRows) - 1)); _cal.set(Calendar.DAY_OF_MONTH, _cal.getActualMaximum(Calendar.DAY_OF_MONTH)); _cal.set(Calendar.HOUR_OF_DAY, 23); _cal.set(Calendar.MINUTE, 59); _cal.set(Calendar.SECOND, 59); _lastDisplayedDate = _cal.getTimeInMillis(); firePropertyChange("lastDisplayedDate", old, _lastDisplayedDate); } /** * Moves the <code>date</code> into the visible region of the calendar. * If the date is greater than the last visible date it will become the * last visible date. While if it is less than the first visible date * it will become the first visible date. * * @param date Date to make visible. */ public void ensureDateVisible(long date) { if (date < _firstDisplayedDate) { setFirstDisplayedDate(date); } else if (date > _lastDisplayedDate) { _cal.setTimeInMillis(date); int month = _cal.get(Calendar.MONTH); int year = _cal.get(Calendar.YEAR); _cal.setTimeInMillis(_lastDisplayedDate); int lastMonth = _cal.get(Calendar.MONTH); int lastYear = _cal.get(Calendar.YEAR); int diffMonths = month - lastMonth + ((year - lastYear) * 12); _cal.setTimeInMillis(_firstDisplayedDate); _cal.add(Calendar.MONTH, diffMonths); setFirstDisplayedDate(_cal.getTimeInMillis()); } if (_startSelectedDate != -1 || _endSelectedDate != -1) { calculateDirtyRectForSelection(); } } /** * Returns a date span of the selected dates. The result will be null if * no dates are selected. */ public DateSpan getSelectedDateSpan() { DateSpan result = null; if (_startSelectedDate != -1) { result = new DateSpan(new Date(_startSelectedDate), new Date(_endSelectedDate)); } return result; } /** * Selects the dates in the DateSpan. This method will not change the * initial date displayed so the caller must update this if necessary. * If we are in SINGLE_SELECTION mode only the start time from the DateSpan * will be used. If we are in WEEK_SELECTION mode the span will be * modified to be valid if necessary. * * @param dateSpan DateSpan defining the selected dates. Passing * <code>null</code> will clear the selection. */ public void setSelectedDateSpan(DateSpan dateSpan) { DateSpan oldSpan = null; if (_startSelectedDate != -1 && _endSelectedDate != -1) { oldSpan = new DateSpan(_startSelectedDate, _endSelectedDate); } if (dateSpan == null) { _startSelectedDate = -1; _endSelectedDate = -1; } else { _cal.setTimeInMillis(dateSpan.getStart()); _cal.set(Calendar.HOUR_OF_DAY, 0); _cal.set(Calendar.MINUTE, 0); _cal.set(Calendar.SECOND, 0); _cal.set(Calendar.MILLISECOND, 0); _startSelectedDate = _cal.getTimeInMillis(); if (_selectionMode == SINGLE_SELECTION) { _endSelectedDate = _startSelectedDate; } else { _cal.setTimeInMillis(dateSpan.getEnd()); _cal.set(Calendar.HOUR_OF_DAY, 0); _cal.set(Calendar.MINUTE, 0); _cal.set(Calendar.SECOND, 0); _cal.set(Calendar.MILLISECOND, 0); _endSelectedDate = _cal.getTimeInMillis(); if (_selectionMode == WEEK_SELECTION) { // Make sure if we are over 7 days we span full weeks. _cal.setTimeInMillis(_startSelectedDate); int count = 1; while (_cal.getTimeInMillis() < _endSelectedDate) { _cal.add(Calendar.DAY_OF_MONTH, 1); count++; } if (count > 7) { // Make sure start date is on the beginning of the // week. _cal.setTimeInMillis(_startSelectedDate); int dayOfWeek = _cal.get(Calendar.DAY_OF_WEEK); if (dayOfWeek != _firstDayOfWeek) { // Move the start date back to the first day of the // week. int daysFromStart = dayOfWeek - _firstDayOfWeek; if (daysFromStart < 0) { daysFromStart += DAYS_IN_WEEK; } _cal.add(Calendar.DAY_OF_MONTH, -daysFromStart); count += daysFromStart; _startSelectedDate = _cal.getTimeInMillis(); } // Make sure we have full weeks. Otherwise modify the // end date. int remainder = count % 7; if (remainder != 0) { _cal.setTimeInMillis(_endSelectedDate); _cal.add(Calendar.DAY_OF_MONTH, (7 - remainder)); _endSelectedDate = _cal.getTimeInMillis(); } } } } // Restore original time value. _cal.setTimeInMillis(_firstDisplayedDate); } repaint(_dirtyRect); calculateDirtyRectForSelection(); repaint(_dirtyRect); // Fire property change. firePropertyChange("selectedDates", oldSpan, dateSpan); } /** * Returns the current selection mode for this JXMonthView. * * @return int Selection mode. */ public int getSelectionMode() { return _selectionMode; } public void setSelectionMode(int mode) throws IllegalArgumentException { if (mode != SINGLE_SELECTION && mode != MULTIPLE_SELECTION && mode != WEEK_SELECTION && mode != NO_SELECTION) { throw new IllegalArgumentException(mode + " is not a valid selection mode"); } _selectionMode = mode; } /** * An array of longs defining days that should be flagged. This array is * assumed to be in sorted order from least to greatest. */ public void setFlaggedDates(long[] flaggedDates) { _flaggedDates = flaggedDates; if (_flaggedDates == null) { repaint(); return; } // Loop through the flaggedDates and set the hour, minute, seconds and // milliseconds to 0 so we can compare times later. for (int i = 0; i < _flaggedDates.length; i++) { _cal.setTimeInMillis(_flaggedDates[i]); // We only want to compare the day, month and year // so reset all other values to 0. _cal.set(Calendar.HOUR_OF_DAY, 0); _cal.set(Calendar.MINUTE, 0); _cal.set(Calendar.SECOND, 0); _cal.set(Calendar.MILLISECOND, 0); _flaggedDates[i] = _cal.getTimeInMillis(); } // Restore the time. _cal.setTimeInMillis(_firstDisplayedDate); repaint(); } /** * Returns the padding used between days in the calendar. */ public int getBoxPaddingX() { return _boxPaddingX; } /** * Sets the number of pixels used to pad the left and right side of a day. * The padding is applied to both sides of the days. Therefore, if you * used the padding value of 3, the number of pixels between any two days * would be 6. */ public void setBoxPaddingX(int _boxPaddingX) { this._boxPaddingX = _boxPaddingX; _dirty = true; } /** * Returns the padding used above and below days in the calendar. */ public int getBoxPaddingY() { return _boxPaddingY; } /** * Sets the number of pixels used to pad the top and bottom of a day. * The padding is applied to both the top and bottom of a day. Therefore, * if you used the padding value of 3, the number of pixels between any * two days would be 6. */ public void setBoxPaddingY(int _boxPaddingY) { this._boxPaddingY = _boxPaddingY; _dirty = true; } /** * Returns whether or not the month view supports traversing months. * * @return <code>true</code> if month traversing is enabled. */ public boolean getTraversable() { return _traversable; } /** * Set whether or not the month view will display buttons to allow the * user to traverse to previous or next months. * * @param traversable set to true to enable month traversing, * false otherwise. */ public void setTraversable(boolean traversable) { _traversable = traversable; _dirty = true; repaint(); } public void setDaysOfTheWeek(String[] days) throws IllegalArgumentException, NullPointerException { if (days == null) { throw new NullPointerException("Array of days is null."); } else if (days.length != 7) { throw new IllegalArgumentException( "Array of days is not of length 7 as expected."); } // TODO: This could throw off internal size information we should // call update and then recalculate displayed calendars and start // positions. _daysOfTheWeek = days; _dirty = true; repaint(); } /** * Returns the single character representation for each day of the * week. * * @return Single character representation for the days of the week */ public String[] getDaysOfTheWeek() { String[] days = new String[7]; System.arraycopy(_daysOfTheWeek, 0, days, 0, 7); return days; } /** * Gets what the first day of the week is; e.g., * <code>Calendar.SUNDAY</code> in the U.S., <code>Calendar.MONDAY</code> * in France. * * @return int The first day of the week. */ public int getFirstDayOfWeek() { return _firstDayOfWeek; } /** * Sets what the first day of the week is; e.g., * <code>Calendar.SUNDAY</code> in US, <code>Calendar.MONDAY</code> * in France. * * @param firstDayOfWeek The first day of the week. * * @see java.util.Calendar */ public void setFirstDayOfWeek(int firstDayOfWeek) { if (firstDayOfWeek == _firstDayOfWeek) { return; } _firstDayOfWeek = firstDayOfWeek; _cal.setFirstDayOfWeek(_firstDayOfWeek); repaint(); } /** * Gets the time zone. * * @return The <code>TimeZone</code> used by the <code>JXMonthView</code>. */ public TimeZone getTimeZone() { return _cal.getTimeZone(); } /** * Sets the time zone with the given time zone value. * * @param tz The <code>TimeZone</code>. */ public void setTimeZone(TimeZone tz) { _cal.setTimeZone(tz); } /** * Returns true if anti-aliased text is enabled for this component, false * otherwise. * * @return boolean <code>true</code> if anti-aliased text is enabled, * <code>false</code> otherwise. */ public boolean getAntialiased() { return _antiAlias; } /** * Turns on/off anti-aliased text for this component. * * @param antiAlias <code>true</code> for anti-aliased text, * <code>false</code> to turn it off. */ public void setAntialiased(boolean antiAlias) { if (_antiAlias == antiAlias) { return; } _antiAlias = antiAlias; repaint(); } /** public void setDropShadowMask(int mask) { _dropShadowMask = mask; repaint(); } */ /** * Returns the selected background color. * * @return the selected background color. */ public Color getSelectedBackground() { return _selectedBackground; } /** * Sets the selected background color to <code>c</code>. The default color * is <code>138, 173, 209 (Blue-ish)</code> * * @param c Selected background. */ public void setSelectedBackground(Color c) { _selectedBackground = c; } /** * Returns the color used when painting the today background. * * @return Color Color */ public Color getTodayBackground() { return _todayBackgroundColor; } /** * Sets the color used to draw the bounding box around today. The default * is the background of the <code>JXMonthView</code> component. */ public void setTodayBackground(Color c) { _todayBackgroundColor = c; repaint(); } /** * Returns the color used to paint the month string background. * * @return Color Color. */ public Color getMonthStringBackground() { return _monthStringBackground; } /** * Sets the color used to draw the background of the month string. The * default is <code>138, 173, 209 (Blue-ish)</code>. */ public void setMonthStringBackground(Color c) { _monthStringBackground = c; repaint(); } /** * Returns the color used to paint the month string foreground. * * @return Color Color. */ public Color getMonthStringForeground() { return _monthStringForeground; } /** * Sets the color used to draw the foreground of the month string. The * default is <code>Color.WHITE</code>. */ public void setMonthStringForeground(Color c) { _monthStringForeground = c; repaint(); } /** * Sets the color used to draw the foreground of each day of the week. These * are the titles */ public void setDaysOfTheWeekForeground(Color c) { _daysOfTheWeekForeground = c; repaint(); } /** * @return Color Color */ public Color getDaysOfTheWeekForeground() { return _daysOfTheWeekForeground; } /** * Set the color to be used for painting the specified day of the week. * Acceptable values are Calendar.SUNDAY - Calendar.SATURDAY. * * @dayOfWeek constant value defining the day of the week. * @c The color to be used for painting the numeric day of the week. */ public void setDayForeground(int dayOfWeek, Color c) { _dayToColorTable.put(dayOfWeek, c); } /** * Return the color that should be used for painting the numerical day of the week. * * @param dayOfWeek The day of week to get the color for. * @return The color to be used for painting the numeric day of the week. * If this was no color has yet been defined the component foreground color * will be returned. */ public Color getDayForeground(int dayOfWeek) { Color c; c = (Color)_dayToColorTable.get(dayOfWeek); if (c == null) { c = getForeground(); } return c; } /** * Returns a copy of the insets used to paint the month string background. * * @return Insets Month string insets. */ public Insets getMonthStringInsets() { return (Insets)_monthStringInsets.clone(); } /** * Insets used to modify the width/height when painting the background * of the month string area. * * @param insets Insets */ public void setMonthStringInsets(Insets insets) { if (insets == null) { _monthStringInsets.top = 0; _monthStringInsets.left = 0; _monthStringInsets.bottom = 0; _monthStringInsets.right = 0; } else { _monthStringInsets.top = insets.top; _monthStringInsets.left = insets.left; _monthStringInsets.bottom = insets.bottom; _monthStringInsets.right = insets.right; } repaint(); } /** * Returns the preferred number of columns to paint calendars in. * * @return int Columns of calendars. */ public int getPreferredCols() { return _minCalCols; } /** * The preferred number of columns to paint calendars. * * @param cols The number of columns of calendars. */ public void setPreferredCols(int cols) { if (cols <= 0) { return; } _minCalCols = cols; _dirty = true; revalidate(); repaint(); } /** * Returns the preferred number of rows to paint calendars in. * * @return int Rows of calendars. */ public int getPreferredRows() { return _minCalRows; } /** * Sets the preferred number of rows to paint calendars. * * @param rows The number of rows of calendars. */ public void setPreferredRows(int rows) { if (rows <= 0) { return; } _minCalRows = rows; _dirty = true; revalidate(); repaint(); } private void updateIfNecessary() { if (_dirty) { update(); _dirty = false; } } /** * Calculates size information necessary for laying out the month view. */ private void update() { // Loop through year and get largest representation of the month. // Keep track of the longest month so we can loop through it to // determine the width of a date box. int currDays; int longestMonth = 0; int daysInLongestMonth = 0; int currWidth; int longestMonthWidth = 0; // We use a bold font for figuring out size constraints since // it's larger and flaggedDates will be noted in this style. _derivedFont = getFont().deriveFont(Font.BOLD); FontMetrics fm = getFontMetrics(_derivedFont); _cal.set(Calendar.MONTH, _cal.getMinimum(Calendar.MONTH)); _cal.set(Calendar.DAY_OF_MONTH, _cal.getActualMinimum(Calendar.DAY_OF_MONTH)); for (int i = 0; i < _cal.getMaximum(Calendar.MONTH); i++) { currWidth = fm.stringWidth(_monthsOfTheYear[i]); if (currWidth > longestMonthWidth) { longestMonthWidth = currWidth; } currDays = _cal.getActualMaximum(Calendar.DAY_OF_MONTH); if (currDays > daysInLongestMonth) { longestMonth = _cal.get(Calendar.MONTH); daysInLongestMonth = currDays; } _cal.add(Calendar.MONTH, 1); } // Loop through the days of the week and adjust the box width // accordingly. _boxHeight = fm.getHeight(); for (int i = 0; i < _daysOfTheWeek.length; i++) { currWidth = fm.stringWidth(_daysOfTheWeek[i]); if (currWidth > _boxWidth) { _boxWidth = currWidth; } } // Loop through longest month and get largest representation of the day // of the month. _cal.set(Calendar.MONTH, longestMonth); _cal.set(Calendar.DAY_OF_MONTH, _cal.getActualMinimum(Calendar.DAY_OF_MONTH)); for (int i = 0; i < daysInLongestMonth; i++) { currWidth = fm.stringWidth( _dayOfMonthFormatter.format(_cal.getTime())); if (currWidth > _boxWidth) { _boxWidth = currWidth; } _cal.add(Calendar.DAY_OF_MONTH, 1); } // If the calendar is traversable, check the icon heights and // adjust the month box height accordingly. _monthBoxHeight = _boxHeight; if (_traversable) { int newHeight = _monthDownImage.getIconHeight() + _arrowPaddingY + _arrowPaddingY; if (newHeight > _monthBoxHeight) { _monthBoxHeight = newHeight; } } // Modify _boxWidth if month string is longer _dim.width = (_boxWidth + (2 * _boxPaddingX)) * DAYS_IN_WEEK; if (_dim.width < longestMonthWidth) { double diff = longestMonthWidth - _dim.width; if (_traversable) { diff += _monthDownImage.getIconWidth() + _monthUpImage.getIconWidth() + (_arrowPaddingX * 4); } _boxWidth += Math.ceil(diff / (double)DAYS_IN_WEEK); _dim.width = (_boxWidth + (2 * _boxPaddingX)) * DAYS_IN_WEEK; } // Keep track of calendar width and height for use later. _calendarWidth = (_boxWidth + (2 * _boxPaddingX)) * DAYS_IN_WEEK; _calendarHeight = ((_boxPaddingY + _boxHeight + _boxPaddingY) * 7) + (_boxPaddingY + _monthBoxHeight + _boxPaddingY); // Calculate minimum width/height for the component. _dim.height = (_calendarHeight * _minCalRows) + (CALENDAR_SPACING * (_minCalRows - 1)); _dim.width = (_calendarWidth * _minCalCols) + (CALENDAR_SPACING * (_minCalCols - 1)); // Add insets to the dimensions. Insets insets = getInsets(); _dim.width += insets.left + insets.right; _dim.height += insets.top + insets.bottom; // Restore calendar. _cal.setTimeInMillis(_firstDisplayedDate); calculateNumDisplayedCals(); calculateStartPosition(); if (_startSelectedDate != -1 || _endSelectedDate != -1) { if (_startSelectedDate > _lastDisplayedDate || _startSelectedDate < _firstDisplayedDate) { // Already does the recalculation for the dirty rect. ensureDateVisible(_startSelectedDate); } else { calculateDirtyRectForSelection(); } } } private void updateToday() { // Update _today. _cal.setTimeInMillis(_today); _cal.add(Calendar.DAY_OF_MONTH, 1); _today = _cal.getTimeInMillis(); // Restore calendar. _cal.setTimeInMillis(_firstDisplayedDate); repaint(); } /** * Returns the minimum size needed to display this component. * * @return Dimension Minimum size. */ public Dimension getMinimumSize() { return getPreferredSize(); } /** * Returns the preferred size of this component. * * @return Dimension Preferred size. */ public Dimension getPreferredSize() { updateIfNecessary(); return new Dimension(_dim); } /** * Returns the maximum size of this component. * * @return Dimension Maximum size. */ public Dimension getMaximumSize() { return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE); } /** * Sets the border of this component. The Border object is responsible * for defining the insets for the component (overriding any insets set * directly on the component) and for optionally rendering any border * decorations within the bounds of those insets. Borders should be used * (rather than insets) for creating both decorative and non-decorative * (such as margins and padding) regions for a swing component. Compound * borders can be used to nest multiple borders within a single component. * <p> * As the border may modify the bounds of the component, setting the border * may result in a reduced number of displayed calendars. * * @param border Border. */ public void setBorder(Border border) { super.setBorder(border); _dirty = true; } /** * Moves and resizes this component. The new location of the top-left * corner is specified by x and y, and the new size is specified by * width and height. * * @param x The new x-coordinate of this component * @param y The new y-coordinate of this component * @param width The new width of this component * @param height The new height of this component */ public void setBounds(int x, int y, int width, int height) { super.setBounds(x, y, width, height); _dirty = true; } /** * Moves and resizes this component to conform to the new bounding * rectangle r. This component's new position is specified by r.x and * r.y, and its new size is specified by r.width and r.height * * @param r The new bounding rectangle for this component */ public void setBounds(Rectangle r) { setBounds(r.x, r.y, r.width, r.height); } /** * Sets the language-sensitive orientation that is to be used to order * the elements or text within this component. Language-sensitive * LayoutManager and Component subclasses will use this property to * determine how to lay out and draw components. * <p> * At construction time, a component's orientation is set to * ComponentOrientation.UNKNOWN, indicating that it has not been * specified explicitly. The UNKNOWN orientation behaves the same as * ComponentOrientation.LEFT_TO_RIGHT. * * @param o The component orientation. */ public void setComponentOrientation(ComponentOrientation o) { super.setComponentOrientation(o); _ltr = o.isLeftToRight(); calculateStartPosition(); calculateDirtyRectForSelection(); } /** * Sets the font of this component. * * @param font The font to become this component's font; if this parameter * is null then this component will inherit the font of its parent. */ public void setFont(Font font) { super.setFont(font); _dirty = true; } /** * {@inheritDoc} */ public void removeNotify() { _todayTimer.stop(); super.removeNotify(); } /** * {@inheritDoc} */ public void addNotify() { super.addNotify(); // Setup timer to update the value of _today. int secondsTillTomorrow = 86400; if (_todayTimer == null) { _todayTimer = new Timer(secondsTillTomorrow * 1000, new ActionListener() { public void actionPerformed(ActionEvent e) { updateToday(); } }); } // Modify the initial delay by the current time. _cal.setTimeInMillis(System.currentTimeMillis()); secondsTillTomorrow = secondsTillTomorrow - (_cal.get(Calendar.HOUR_OF_DAY) * 3600) - (_cal.get(Calendar.MINUTE) * 60) - _cal.get(Calendar.SECOND); _todayTimer.setInitialDelay(secondsTillTomorrow * 1000); _todayTimer.start(); // Restore calendar _cal.setTimeInMillis(_firstDisplayedDate); } /** * {@inheritDoc} */ protected void paintComponent(Graphics g) { Object oldAAValue = null; Graphics2D g2 = (g instanceof Graphics2D) ? (Graphics2D)g : null; if (g2 != null && _antiAlias) { oldAAValue = g2.getRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); } Rectangle clip = g.getClipBounds(); updateIfNecessary(); if (isOpaque()) { g.setColor(getBackground()); g.fillRect(clip.x, clip.y, clip.width, clip.height); } g.setColor(getForeground()); Color shadowColor = g.getColor(); shadowColor = new Color(shadowColor.getRed(), shadowColor.getGreen(), shadowColor.getBlue(), (int)(.20 * 255)); FontMetrics fm = g.getFontMetrics(); // Reset the calendar. _cal.setTimeInMillis(_firstDisplayedDate); // Center the calendars vertically in the available space. int y = _startY; for (int row = 0; row < _numCalRows; row++) { // Center the calendars horizontally in the available space. int x = _startX; int tmpX, tmpY; // Check if this row falls in the clip region. _bounds.x = 0; _bounds.y = _startY + row * (_calendarHeight + CALENDAR_SPACING); _bounds.width = getWidth(); _bounds.height = _calendarHeight; if (!_bounds.intersects(clip)) { _cal.add(Calendar.MONTH, _numCalCols); y += _calendarHeight + CALENDAR_SPACING; continue; } for (int column = 0; column < _numCalCols; column++) { String monthName = _monthsOfTheYear[_cal.get(Calendar.MONTH)]; monthName = monthName + " " + _cal.get(Calendar.YEAR); _bounds.x = (_ltr ? x : x - _calendarWidth);// + 4; //4px of padding on the left _bounds.y = y + _boxPaddingY;// + 4; //4px of padding on the top _bounds.width = _calendarWidth;// - 8; //4px of padding on both sides _bounds.height = _monthBoxHeight; //4px of padding on top if (_bounds.intersects(clip)) { // Paint month name background. paintMonthStringBackground(g, _bounds.x, _bounds.y, _bounds.width, _bounds.height); // Paint arrow buttons for traversing months if enabled. if (_traversable) { tmpX = _bounds.x + _arrowPaddingX; tmpY = _bounds.y + (_bounds.height - _monthDownImage.getIconHeight()) / 2; g.drawImage(_monthDownImage.getImage(), tmpX, tmpY, null); tmpX = _bounds.x + _bounds.width - _arrowPaddingX - _monthUpImage.getIconWidth(); g.drawImage(_monthUpImage.getImage(), tmpX, tmpY, null); } // Paint month name. Font oldFont = getFont(); FontMetrics oldFM = fm; g.setFont(_derivedFont); fm = getFontMetrics(_derivedFont); g.setColor(_monthStringForeground); tmpX = _ltr ? x + (_calendarWidth / 2) - (fm.stringWidth(monthName) / 2) : x - (_calendarWidth / 2) - (fm.stringWidth(monthName) / 2) - 1; tmpY = _bounds.y + ((_monthBoxHeight - _boxHeight) / 2) + fm.getAscent(); if ((_dropShadowMask & MONTH_DROP_SHADOW) != 0) { g.setColor(shadowColor); g.drawString(monthName, tmpX + 1, tmpY + 1); g.setColor(_monthStringForeground); } g.drawString(monthName, tmpX, tmpY); g.setFont(oldFont); fm = oldFM; } g.setColor(getDaysOfTheWeekForeground()); _bounds.x = _ltr ? x : x - _calendarWidth; _bounds.y = y + _boxPaddingY + _monthBoxHeight + _boxPaddingY + _boxPaddingY; _bounds.width = _calendarWidth; _bounds.height = _boxHeight; if (_bounds.intersects(clip)) { _cal.set(Calendar.DAY_OF_MONTH, _cal.getActualMinimum(Calendar.DAY_OF_MONTH)); // Paint short representation of day of the week. int dayIndex = _firstDayOfWeek - 1; Font oldFont = g.getFont(); FontMetrics oldFM = fm; g.setFont(_derivedFont); fm = getFontMetrics(_derivedFont); for (int i = 0; i < DAYS_IN_WEEK; i++) { tmpX = _ltr ? x + (i * (_boxPaddingX + _boxWidth + _boxPaddingX)) + _boxPaddingX + (_boxWidth / 2) - (fm.stringWidth(_daysOfTheWeek[dayIndex]) / 2) : x - (i * (_boxPaddingX + _boxWidth + _boxPaddingX)) - _boxPaddingX - (_boxWidth / 2) - (fm.stringWidth(_daysOfTheWeek[dayIndex]) / 2); tmpY = _bounds.y + fm.getAscent(); if ((_dropShadowMask & WEEK_DROP_SHADOW) != 0) { g.setColor(shadowColor); g.drawString(_daysOfTheWeek[dayIndex], tmpX + 1, tmpY + 1); g.setColor(getDaysOfTheWeekForeground()); } g.drawString(_daysOfTheWeek[dayIndex], tmpX, tmpY); dayIndex++; if (dayIndex == 7) { dayIndex = 0; } } g.setFont(oldFont); fm = oldFM; } // Check if the month to paint falls in the clip. _bounds.x = _startX + (_ltr ? column * (_calendarWidth + CALENDAR_SPACING) : -(column * (_calendarWidth + CALENDAR_SPACING) + _calendarWidth)); _bounds.y = _startY + row * (_calendarHeight + CALENDAR_SPACING); _bounds.width = _calendarWidth; _bounds.height = _calendarHeight; // Paint the month if it intersects the clip. If we don't move // the calendar forward a month as it would have if paintMonth // was called. if (_bounds.intersects(clip)) { paintMonth(g, column, row); } else { _cal.add(Calendar.MONTH, 1); } x += _ltr ? _calendarWidth + CALENDAR_SPACING : -(_calendarWidth + CALENDAR_SPACING); } y += _calendarHeight + CALENDAR_SPACING; } // Restore the calendar. _cal.setTimeInMillis(_firstDisplayedDate); if (g2 != null && _antiAlias) { g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, oldAAValue); } } /** * Paints a month. It is assumed the calendar, _cal, is already set to the * first day of the month to be painted. * * @param col X (column) the calendar is displayed in. * @param row Y (row) the calendar is displayed in. * @param g Graphics object. */ private void paintMonth(Graphics g, int col, int row) { String numericDay; int days = _cal.getActualMaximum(Calendar.DAY_OF_MONTH); FontMetrics fm = g.getFontMetrics(); Rectangle clip = g.getClipBounds(); long nextFlaggedDate = -1; int flaggedDateIndex = 0; if (_flaggedDates != null && _flaggedDates.length > 0) { nextFlaggedDate = _flaggedDates[flaggedDateIndex]; } for (int i = 0; i < days; i++) { calculateBoundsForDay(_bounds); if (_bounds.intersects(clip)) { numericDay = _dayOfMonthFormatter.format(_cal.getTime()); // Paint bounding box around any date that falls within the // selection. if (isSelectedDate(_cal.getTimeInMillis())) { // Keep track of the rectangle for the currently // selected date so we don't have to recalculate it // later when it becomes unselected. This is only // useful for SINGLE_SELECTION mode. if (_selectionMode == SINGLE_SELECTION) { _dirtyRect.x = _bounds.x; _dirtyRect.y = _bounds.y; _dirtyRect.width = _bounds.width; _dirtyRect.height = _bounds.height; } paintSelectedDayBackground(g, _bounds.x, _bounds.y, _bounds.width, _bounds.height); g.setColor(getForeground()); } // Paint bounding box around today. if (_cal.getTimeInMillis() == _today) { paintTodayBackground(g, _bounds.x, _bounds.y, _bounds.width, _bounds.height); g.setColor(getForeground()); } // If the appointment date is less than the current // calendar date increment to the next appointment. while (nextFlaggedDate != -1 && nextFlaggedDate < _cal.getTimeInMillis()) { flaggedDateIndex++; if (flaggedDateIndex < _flaggedDates.length) { nextFlaggedDate = _flaggedDates[flaggedDateIndex]; } else { nextFlaggedDate = -1; } } // Paint numeric day of the month. g.setColor(getDayForeground(_cal.get(Calendar.DAY_OF_WEEK))); if (nextFlaggedDate != -1 && _cal.getTimeInMillis() == nextFlaggedDate) { Font oldFont = getFont(); FontMetrics oldFM = fm; g.setFont(_derivedFont); fm = getFontMetrics(_derivedFont); g.drawString(numericDay, _ltr ? _bounds.x + _boxPaddingX + _boxWidth - fm.stringWidth(numericDay): _bounds.x + _boxPaddingX + _boxWidth - fm.stringWidth(numericDay) - 1, _bounds.y + _boxPaddingY + fm.getAscent()); g.setFont(oldFont); fm = oldFM; } else { g.drawString(numericDay, _ltr ? _bounds.x + _boxPaddingX + _boxWidth - fm.stringWidth(numericDay): _bounds.x + _boxPaddingX + _boxWidth - fm.stringWidth(numericDay) - 1, _bounds.y + _boxPaddingY + fm.getAscent()); } } _cal.add(Calendar.DAY_OF_MONTH, 1); } } protected void paintMonthStringBackground(Graphics g, int x, int y, int width, int height) { // Modify bounds by the month string insets. x = _ltr ? x + _monthStringInsets.left : x + _monthStringInsets.right; y = y + _monthStringInsets.top; width = width - _monthStringInsets.left - _monthStringInsets.right; height = height - _monthStringInsets.top - _monthStringInsets.bottom; Graphics2D g2 = (Graphics2D)g; GradientPaint gp = new GradientPaint(x, y + height, new Color(238, 238, 238), x, y, new Color(204, 204, 204)); //paint the border // g.setColor(_monthStringBackground); g2.setPaint(gp); g2.fillRect(x, y, width - 1, height - 1); g2.setPaint(new Color(153, 153, 153)); g2.drawRect(x, y, width - 1, height - 1); //TODO The right side of the rect is being clipped } /** * Paints the background for today. The default is a rectangle drawn in * using the color set by <code>setTodayBackground</code> * * @see #setTodayBackground * @param g Graphics object to paint to. * @param x x-coordinate of upper left corner. * @param y y-coordinate of upper left corner. * @param width width of bounding box for the day. * @param height height of bounding box for the day. */ protected void paintTodayBackground(Graphics g, int x, int y, int width, int height) { // g.setColor(_todayBackgroundColor); // g.drawRect(x, y, width - 1, height - 1); //paint the gradiented border GradientPaint gp = new GradientPaint(x, y, new Color(91, 123, 145), x, y + height, new Color(68, 86, 98)); Graphics2D g2 = (Graphics2D)g; g2.setPaint(gp); g2.drawRect(x, y, width - 1, height - 1); } /** * Paint the background for a selected day. The default is a filled * rectangle in the in the component's background color. * * @param g Graphics object to paint to. * @param x x-coordinate of upper left corner. * @param y y-coordinate of upper left corner. * @param width width of bounding box for the day. * @param height height of bounding box for the day. */ protected void paintSelectedDayBackground(Graphics g, int x, int y, int width, int height) { g.setColor(getSelectedBackground()); g.fillRect(x, y, width, height); } /** * Returns true if the specified time falls within the _startSelectedDate * and _endSelectedDate range. */ private boolean isSelectedDate(long time) { if (time >= _startSelectedDate && time <= _endSelectedDate) { return true; } return false; } /** * Calculates the _numCalCols/_numCalRows that determine the number of * calendars that can be displayed. */ private void calculateNumDisplayedCals() { int oldNumCalCols = _numCalCols; int oldNumCalRows = _numCalRows; // Determine how many columns of calendars we want to paint. _numCalCols = 1; _numCalCols += (getWidth() - _calendarWidth) / (_calendarWidth + CALENDAR_SPACING); // Determine how many rows of calendars we want to paint. _numCalRows = 1; _numCalRows += (getHeight() - _calendarHeight) / (_calendarHeight + CALENDAR_SPACING); if (oldNumCalCols != _numCalCols || oldNumCalRows != _numCalRows) { calculateLastDisplayedDate(); } } /** * Calculates the _startX/_startY position for centering the calendars * within the available space. */ private void calculateStartPosition() { // Calculate offset in x-axis for centering calendars. _startX = (getWidth() - ((_calendarWidth * _numCalCols) + (CALENDAR_SPACING * (_numCalCols - 1)))) / 2; if (!_ltr) { _startX = getWidth() - _startX; } // Calculate offset in y-axis for centering calendars. _startY = (getHeight() - ((_calendarHeight * _numCalRows) + (CALENDAR_SPACING * (_numCalRows - 1 )))) / 2; } /** * Calculate the bounding box for drawing a date. It is assumed that the * calendar, _cal, is already set to the date you want to find the offset * for. * * @param bounds Bounds of the date to draw in. */ private void calculateBoundsForDay(Rectangle bounds) { int year = _cal.get(Calendar.YEAR); int month = _cal.get(Calendar.MONTH); int dayOfWeek = _cal.get(Calendar.DAY_OF_WEEK); int weekOfMonth = _cal.get(Calendar.WEEK_OF_MONTH); // Determine what row/column we are in. int diffMonths = month - _firstDisplayedMonth + ((year - _firstDisplayedYear) * 12); int calRowIndex = diffMonths / _numCalCols; int calColIndex = diffMonths - (calRowIndex * _numCalCols); // Modify the index relative to the first day of the week. bounds.x = dayOfWeek - _firstDayOfWeek; if (bounds.x < 0) { bounds.x += DAYS_IN_WEEK; } // Offset for location of the day in the week. bounds.x = _ltr ? bounds.x * (_boxPaddingX + _boxWidth + _boxPaddingX) : (bounds.x + 1) * (_boxPaddingX + _boxWidth + _boxPaddingX); // Offset for the column the calendar is displayed in. bounds.x += calColIndex * (_calendarWidth + CALENDAR_SPACING); // Adjust by centering value. bounds.x = _ltr ? _startX + bounds.x : _startX - bounds.x; // Initial offset for Month and Days of the Week display. bounds.y = _boxPaddingY + _monthBoxHeight + _boxPaddingY + + _boxPaddingY + _boxHeight + _boxPaddingY; // Offset for centering and row the calendar is displayed in. bounds.y += _startY + calRowIndex * (_calendarHeight + CALENDAR_SPACING); // Offset for Week of the Month. bounds.y += (weekOfMonth - 1) * (_boxPaddingY + _boxHeight + _boxPaddingY); bounds.width = _boxPaddingX + _boxWidth + _boxPaddingX; bounds.height = _boxPaddingY + _boxHeight + _boxPaddingY; } /** * Return a long representing the date at the specified x/y position. * The date returned will have a valid day, month and year. Other fields * such as hour, minute, second and milli-second will be set to 0. * * @param x X position * @param y Y position * @return long The date, -1 if position does not contain a date. */ public long getDayAt(int x, int y) { if (_ltr ? (_startX > x) : (_startX < x) || _startY > y) { return -1; } // Determine which column of calendars we're in. int calCol = (_ltr ? (x - _startX) : (_startX - x)) / (_calendarWidth + CALENDAR_SPACING); // Determine which row of calendars we're in. int calRow = (y - _startY) / (_calendarHeight + CALENDAR_SPACING); if (calRow > _numCalRows - 1 || calCol > _numCalCols - 1) { return -1; } // Determine what row (week) in the selected month we're in. int row = 1; row += (((y - _startY) - (calRow * (_calendarHeight + CALENDAR_SPACING))) - (_boxPaddingY + _monthBoxHeight + _boxPaddingY)) / (_boxPaddingY + _boxHeight + _boxPaddingY); // The first two lines in the calendar are the month and the days // of the week. Ignore them. row -= 2; if (row < 0 || row > 5) { return -1; } // Determine which column in the selected month we're in. int col = ((_ltr ? (x - _startX) : (_startX - x)) - (calCol * (_calendarWidth + CALENDAR_SPACING))) / (_boxPaddingX + _boxWidth + _boxPaddingX); if (col > DAYS_IN_WEEK - 1) { return -1; } // Use the first day of the month as a key point for determining the // date of our click. // The week index of the first day will always be 0. _cal.setTimeInMillis(_firstDisplayedDate); //_cal.set(Calendar.DAY_OF_MONTH, 1); _cal.add(Calendar.MONTH, calCol + (calRow * _numCalCols)); int dayOfWeek = _cal.get(Calendar.DAY_OF_WEEK); int firstDayIndex = dayOfWeek - _firstDayOfWeek; if (firstDayIndex < 0) { firstDayIndex += DAYS_IN_WEEK; } int daysToAdd = (row * DAYS_IN_WEEK) + (col - firstDayIndex); if (daysToAdd < 0 || daysToAdd > (_cal.getActualMaximum(Calendar.DAY_OF_MONTH) - 1)) { return -1; } _cal.add(Calendar.DAY_OF_MONTH, daysToAdd); long selected = _cal.getTimeInMillis(); // Restore the time. _cal.setTimeInMillis(_firstDisplayedDate); return selected; } /** * Returns an index defining which, if any, of the buttons for * traversing the month was pressed. This method should only be * called when <code>setTraversable</code> is set to true. * * @return MONTH_UP, MONTH_DOWN or -1 when no button is selected. */ protected int getTraversableButtonAt(int x, int y) { if (_ltr ? (_startX > x) : (_startX < x) || _startY > y) { return -1; } // Determine which column of calendars we're in. int calCol = (_ltr ? (x - _startX) : (_startX - x)) / (_calendarWidth + CALENDAR_SPACING); // Determine which row of calendars we're in. int calRow = (y - _startY) / (_calendarHeight + CALENDAR_SPACING); if (calRow > _numCalRows - 1 || calCol > _numCalCols - 1) { return -1; } // See if we're in the month string area. y = ((y - _startY) - (calRow * (_calendarHeight + CALENDAR_SPACING))) - _boxPaddingY; if (y < _arrowPaddingY || y > (_monthBoxHeight - _arrowPaddingY)) { return -1; } x = ((_ltr ? (x - _startX) : (_startX - x)) - (calCol * (_calendarWidth + CALENDAR_SPACING))); if (x > _arrowPaddingX && x < (_arrowPaddingX + _monthDownImage.getIconWidth() + _arrowPaddingX)) { return MONTH_DOWN; } if (x > (_calendarWidth - _arrowPaddingX * 2 - _monthUpImage.getIconWidth()) && x < (_calendarWidth - _arrowPaddingX)) { return MONTH_UP; } return -1; } private void calculateDirtyRectForSelection() { if (_startSelectedDate == -1 || _endSelectedDate == -1) { _dirtyRect.x = 0; _dirtyRect.y = 0; _dirtyRect.width = 0; _dirtyRect.height = 0; } else { _cal.setTimeInMillis(_startSelectedDate); calculateBoundsForDay(_dirtyRect); _cal.add(Calendar.DAY_OF_MONTH, 1); Rectangle tmpRect; while (_cal.getTimeInMillis() <= _endSelectedDate) { calculateBoundsForDay(_bounds); tmpRect = _dirtyRect.union(_bounds); _dirtyRect.x = tmpRect.x; _dirtyRect.y = tmpRect.y; _dirtyRect.width = tmpRect.width; _dirtyRect.height = tmpRect.height; _cal.add(Calendar.DAY_OF_MONTH, 1); } // Restore the time. _cal.setTimeInMillis(_firstDisplayedDate); } } /** * Returns the string currently used to identiy fired ActionEvents. * * @return String The string used for identifying ActionEvents. */ public String getActionCommand() { return _actionCommand; } /** * Sets the string used to identify fired ActionEvents. * * @param actionCommand The string used for identifying ActionEvents. */ public void setActionCommand(String actionCommand) { _actionCommand = actionCommand; } /** * Adds an ActionListener. * <p> * The ActionListener will receive an ActionEvent when a selection has * been made. * * @param l The ActionListener that is to be notified */ public void addActionListener(ActionListener l) { listenerList.add(ActionListener.class, l); } /** * Removes an ActionListener. * * @param l The action listener to remove. */ public void removeActionListener(ActionListener l) { listenerList.remove(ActionListener.class, l); } /** * Fires an ActionEvent to all listeners. */ protected void fireActionPerformed() { Object[] listeners = listenerList.getListenerList(); ActionEvent e = null; for (int i = listeners.length - 2; i >= 0; i -=2) { if (listeners[i] == ActionListener.class) { if (e == null) { e = new ActionEvent(JXMonthView.this, ActionEvent.ACTION_PERFORMED, _actionCommand); } ((ActionListener)listeners[i + 1]).actionPerformed(e); } } } /** * {@inheritDoc} */ protected void processMouseEvent(MouseEvent e) { if (!isEnabled()) { return; } int id = e.getID(); // Check if one of the month traverse buttons was pushed. if (id == MouseEvent.MOUSE_PRESSED && _traversable) { int arrowType = getTraversableButtonAt(e.getX(), e.getY()); if (arrowType == MONTH_DOWN) { setFirstDisplayedDate( DateUtils.getPreviousMonth(getFirstDisplayedDate())); return; } else if (arrowType == MONTH_UP) { setFirstDisplayedDate( DateUtils.getNextMonth(getFirstDisplayedDate())); return; } } if (_selectionMode == NO_SELECTION) { return; } if (id == MouseEvent.MOUSE_PRESSED) { long selected = getDayAt(e.getX(), e.getY()); if (selected == -1) { return; } // Update the selected dates. _startSelectedDate = selected; _endSelectedDate = selected; if (_selectionMode == MULTIPLE_SELECTION || _selectionMode == WEEK_SELECTION) { _pivotDate = selected; } // Determine the dirty rectangle of the new selected date so we // draw the bounding box around it. This dirty rect includes the // visual border of the selected date. _cal.setTimeInMillis(selected); calculateBoundsForDay(_bounds); _cal.setTimeInMillis(_firstDisplayedDate); // Repaint the old dirty area. repaint(_dirtyRect); // Repaint the new dirty area. repaint(_bounds); // Update the dirty area. _dirtyRect.x = _bounds.x; _dirtyRect.y = _bounds.y; _dirtyRect.width = _bounds.width; _dirtyRect.height = _bounds.height; // Arm so we fire action performed on mouse release. _asKirkWouldSay_FIRE = true; } else if (id == MouseEvent.MOUSE_RELEASED) { if (_asKirkWouldSay_FIRE) { fireActionPerformed(); } _asKirkWouldSay_FIRE = false; } super.processMouseEvent(e); } /** * {@inheritDoc} */ protected void processMouseMotionEvent(MouseEvent e) { if (!isEnabled() || _selectionMode == NO_SELECTION) { return; } int id = e.getID(); if (id == MouseEvent.MOUSE_DRAGGED) { int x = e.getX(); int y = e.getY(); long selected = getDayAt(x, y); if (selected == -1) { return; } long oldStart = _startSelectedDate; long oldEnd = _endSelectedDate; if (_selectionMode == SINGLE_SELECTION) { if (selected == oldStart) { return; } _startSelectedDate = selected; _endSelectedDate = selected; } else { if (selected <= _pivotDate) { _startSelectedDate = selected; _endSelectedDate = _pivotDate; } else if (selected > _pivotDate) { _startSelectedDate = _pivotDate; _endSelectedDate = selected; } } if (_selectionMode == WEEK_SELECTION) { // Do we span a week. long start = (selected > _pivotDate) ? _pivotDate : selected; long end = (selected > _pivotDate) ? selected : _pivotDate; _cal.setTimeInMillis(start); int count = 1; while (_cal.getTimeInMillis() < end) { _cal.add(Calendar.DAY_OF_MONTH, 1); count++; } if (count > DAYS_IN_WEEK) { // Move the start date to the first day of the week. _cal.setTimeInMillis(start); int dayOfWeek = _cal.get(Calendar.DAY_OF_WEEK); int daysFromStart = dayOfWeek - _firstDayOfWeek; if (daysFromStart < 0) { daysFromStart += DAYS_IN_WEEK; } _cal.add(Calendar.DAY_OF_MONTH, -daysFromStart); _startSelectedDate = _cal.getTimeInMillis(); // Move the end date to the last day of the week. _cal.setTimeInMillis(end); dayOfWeek = _cal.get(Calendar.DAY_OF_WEEK); int lastDayOfWeek = _firstDayOfWeek - 1; if (lastDayOfWeek == 0) { lastDayOfWeek = Calendar.SATURDAY; } int daysTillEnd = lastDayOfWeek - dayOfWeek; if (daysTillEnd < 0) { daysTillEnd += DAYS_IN_WEEK; } _cal.add(Calendar.DAY_OF_MONTH, daysTillEnd); _endSelectedDate = _cal.getTimeInMillis(); } } if (oldStart == _startSelectedDate && oldEnd == _endSelectedDate) { return; } // Repaint the old dirty area. repaint(_dirtyRect); // Repaint the new dirty area. calculateDirtyRectForSelection(); repaint(_dirtyRect); // Set trigger. _asKirkWouldSay_FIRE = true; } super.processMouseMotionEvent(e); } }
// You are free to use it for your own good as long as it doesn't hurt anybody. // For questions or suggestions please contact me at httpeter@gmail.com package org.op.data.repository; import java.io.Serializable; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.EntityManager; import javax.persistence.Persistence; import javax.persistence.TypedQuery; /** * Simple extendable repository for use with JPA2 offering basic list retrieval * en persistence functionalities. Requires the name of the used Persistence * Unit. * */ public class DefaultRepository implements Serializable { private static DefaultRepository instance = null; private static final Logger logger = Logger.getLogger(DefaultRepository.class .getName()); private static final long serialVersionUID = 7086626098229281352L; private EntityManager em; public static DefaultRepository getInstance(String puName) { if (instance == null) { //temp System.out.println("\n\n\n====== CREATING NEW EMF!!!!! ======\n\n\n"); instance = new DefaultRepository(); instance.setEm(Persistence.createEntityManagerFactory(puName) .createEntityManager()); } return instance; } public void setEm(EntityManager em) { this.em = em; } public EntityManager getEm() { return em; } /** * Checking whether Entity Manager and Entity Manager Factory are open. made * public so that it can be used by classes that extend DefaultRepository. * * @return * */ public boolean emIsOpen() { return instance.em.isOpen(); } /** * Saving an object to the database. If EntityManager or * EntityManagerFactory are closed an error is thrown. The latter can be * checked with 'emIsOpen'. * * @param object * @return */ public boolean persisted(Object object) { if (instance.emIsOpen()) { try { instance.em.getTransaction().begin(); instance.em.persist(object); instance.em.getTransaction().commit(); instance.em.clear(); return true; } catch (Exception e) { logger.log(Level.WARNING, e.getCause().getMessage()); try { instance.em.getTransaction().rollback(); } catch (Exception e1) { logger.log(Level.WARNING, e1.getCause().getMessage()); } return false; } } else { System.out.println("EntityManagerFactor or EntityManager are closed"); return false; } } /** * Retrieve a list of objects according to their type from the DB. * * @param c * @return */ public List getResultList(Class c) { if (instance.emIsOpen()) { TypedQuery q = instance.em.createQuery("select o from " + c.getSimpleName() + " o", c); return q.getResultList(); } return null; } /** * Delete a specific object from the DB. Does not work with objects * extending Collection! If the EntityManager and the EntityManagerFactory * are closed, an error is thrown * * @param object * @return */ public boolean deleted(Object object) { if (instance.emIsOpen()) { instance.em.getTransaction().begin(); instance.em.remove(object); instance.em.getTransaction() .commit(); instance.em.clear(); return true; } else { System.out.println("EntityManagerFactory or EntityManager are closed"); instance.em.getTransaction() .rollback(); return false; } } /** * Method for closing the EntityManager and the EntityManagerFactory. If * closed, other methods persistence breaks. */ public void closeEM() { if (instance.emIsOpen()) { instance.em.clear(); instance.em.close(); } } }
package org.opentdc.wtt.file; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Logger; import javax.servlet.ServletContext; import org.opentdc.service.exception.DuplicateException; import org.opentdc.service.exception.InternalServerErrorException; import org.opentdc.service.exception.NotFoundException; import org.opentdc.service.exception.ValidationException; import org.opentdc.util.PrettyPrinter; import org.opentdc.file.AbstractFileServiceProvider; import org.opentdc.wtt.CompanyModel; import org.opentdc.wtt.ProjectModel; import org.opentdc.wtt.ProjectTreeNodeModel; import org.opentdc.wtt.ResourceRefModel; import org.opentdc.wtt.ServiceProvider; public class FileServiceProvider extends AbstractFileServiceProvider<WttCompany> implements ServiceProvider { protected static Map<String, WttCompany> companyIndex = null; // companyId, WttCompany protected static Map<String, WttProject> projectIndex = null; // projectId, WttProject protected static Map<String, ResourceRefModel> resourceIndex = null; // resourceRefId, ResourceRefModel private static final Logger logger = Logger.getLogger(FileServiceProvider.class.getName()); public FileServiceProvider( ServletContext context, String prefix ) throws IOException { super(context, prefix); if (companyIndex == null) { // initialize the indexes companyIndex = new ConcurrentHashMap<String, WttCompany>(); projectIndex = new ConcurrentHashMap<String, WttProject>(); resourceIndex = new ConcurrentHashMap<String, ResourceRefModel>(); List<WttCompany> _companies = importJson(); // load the data into the local transient storage recursively for (WttCompany _company : _companies) { companyIndex.put(_company.getModel().getId(), _company); for (WttProject _project : _company.getProjects()) { indexProjectRecursively(_project); } } logger.info("indexed " + companyIndex.size() + " Companies, " + projectIndex.size() + " Projects, " + resourceIndex.size() + " Resources."); } } /** * List all companies. * * @return a list containing the companies. */ @Override public ArrayList<CompanyModel> listCompanies( String query, String queryType, int position, int size ) { ArrayList<CompanyModel> _companies = new ArrayList<CompanyModel>(); for (WttCompany _wttc : companyIndex.values()) { _companies.add(_wttc.getModel()); } Collections.sort(_companies, CompanyModel.CompanyComparator); ArrayList<CompanyModel> _selection = new ArrayList<CompanyModel>(); for (int i = 0; i < _companies.size(); i++) { if (i >= position && i < (position + size)) { _selection.add(_companies.get(i)); } } logger.info("list(<" + query + ">, <" + queryType + ">, <" + position + ">, <" + size + ">) -> " + _selection.size() + " companies."); return _selection; } /** * Create a new company. * * @param company * @return the newly created company * @throws DuplicateException when a company with the same id already exists * @throws ValidationException when the id was generated on the client */ @Override public CompanyModel createCompany( CompanyModel company ) throws DuplicateException, ValidationException { logger.info("createCompany(" + PrettyPrinter.prettyPrintAsJSON(company) + ")"); String _id = company.getId(); if (_id == null || _id == "") { _id = UUID.randomUUID().toString(); } else { if (companyIndex.get(_id) != null) { // object with same ID exists already throw new DuplicateException("company <" + _id + "> exists already."); } else { // a new ID was set on the client; we do not allow this throw new ValidationException("company <" + _id + "> contains an ID generated on the client. This is not allowed."); } } if (company.getTitle() == null || company.getTitle().length() == 0) { throw new ValidationException("company <" + _id + "> must contain a valid title."); } company.setId(_id); Date _date = new Date(); company.setCreatedAt(_date); company.setCreatedBy("DUMMY_USER"); company.setModifiedAt(_date); company.setModifiedBy("DUMMY_USER"); WttCompany _newCompany = new WttCompany(); _newCompany.setModel(company); companyIndex.put(_id, _newCompany); logger.info("createCompany() -> " + PrettyPrinter.prettyPrintAsJSON(company)); if (isPersistent) { exportJson(companyIndex.values()); } return company; } /** * Find a company by ID. * * @param id * the company ID * @return the company * @throws NotFoundException when no compan with this id could be found * if there exists no company with this ID */ @Override public CompanyModel readCompany( String id ) throws NotFoundException { CompanyModel _c = readWttCompany(id).getModel(); logger.info("readCompany(" + id + ") -> " + PrettyPrinter.prettyPrintAsJSON(_c)); return _c; } private WttCompany readWttCompany( String id ) throws NotFoundException { WttCompany _company = companyIndex.get(id); if (_company == null) { throw new NotFoundException("company <" + id + "> was not found."); } logger.info("readWttCompany(" + id + ") -> " + PrettyPrinter.prettyPrintAsJSON(_company)); return _company; } /** * Update a company with new attribute values. * * @param compId the ID of the company to update * @param newCompany * the new version of the company * @return the updated company * @throws NotFoundException * if an object with the same ID did not exist * @throws NotAllowedException if createdAt or createdBy was changed on the client */ @Override public CompanyModel updateCompany( String compId, CompanyModel newCompany ) throws NotFoundException, ValidationException { WttCompany _c = readWttCompany(compId); CompanyModel _cm = _c.getModel(); if (! _cm.getCreatedAt().equals(newCompany.getCreatedAt())) { throw new ValidationException("company<" + compId + ">: it is not allowed to change createAt on the client."); } if (! _cm.getCreatedBy().equalsIgnoreCase(newCompany.getCreatedBy())) { throw new ValidationException("company<" + compId + ">: it is not allowed to change createBy on the client."); } _cm.setTitle(newCompany.getTitle()); _cm.setDescription(newCompany.getDescription()); _cm.setModifiedAt(new Date()); _cm.setModifiedBy("DUMMY_USER"); _c.setModel(_cm); companyIndex.put(compId, _c); logger.info("updateCompany(" + compId + ") -> " + PrettyPrinter.prettyPrintAsJSON(_cm)); if (isPersistent) { exportJson(companyIndex.values()); } return _cm; } @Override public void deleteCompany( String id) throws NotFoundException, InternalServerErrorException { WttCompany _c = readWttCompany(id); removeProjectsFromIndexRecursively(_c.getProjects()); if (companyIndex.remove(id) == null) { throw new InternalServerErrorException("company <" + id + "> can not be removed, because it does not exist in the index"); }; logger.info("deleteCompany(" + id + ")"); if (isPersistent) { exportJson(companyIndex.values()); } } @Override public ProjectTreeNodeModel readAsTree( String id) throws NotFoundException { WttCompany _c = readWttCompany(id); ProjectTreeNodeModel _projectTree = new ProjectTreeNodeModel(); _projectTree.setId(id); _projectTree.setTitle(_c.getModel().getTitle()); for (WttProject _p : _c.getProjects()) { _projectTree.addProject(convertTree(_p)); } logger.info("readAsTree(" + id + ") -> " + PrettyPrinter.prettyPrintAsJSON(_projectTree)); return _projectTree; } private ProjectTreeNodeModel convertTree(WttProject p) { ProjectTreeNodeModel _node = new ProjectTreeNodeModel(); _node.setId(p.getModel().getId()); _node.setTitle(p.getModel().getTitle()); for (WttProject _p : p.getProjects()) { _node.addProject(convertTree(_p)); } for (ResourceRefModel _resource : p.getResources()) { _node.addResource(_resource.getId()); } logger.info("convertTree(" + p.getModel().getId() + ") -> " + PrettyPrinter.prettyPrintAsJSON(_node)); return _node; } /** * Return the top-level projects of a company without subprojects. * * @param compId the company ID * @param query * @param queryType * @param position * @param size * @return all list of all top-level projects of the company */ @Override public ArrayList<ProjectModel> listProjects( String compId, String query, String queryType, int position, int size ) { ArrayList<ProjectModel> _projects = new ArrayList<ProjectModel>(); for (WttProject _wttp : readWttCompany(compId).getProjects()) { _projects.add(_wttp.getModel()); } Collections.sort(_projects, ProjectModel.ProjectComparator); ArrayList<ProjectModel> _selection = new ArrayList<ProjectModel>(); for (int i = 0; i < _projects.size(); i++) { if (i >= position && i < (position + size)) { _selection.add(_projects.get(i)); } } logger.info("listProjects(<" + compId + ">, <" + query + ">, <" + queryType + ">, <" + position + ">, <" + size + ">) -> " + _selection.size() + " values"); return _selection; } @Override public ProjectModel createProject( String compId, ProjectModel newProject ) throws DuplicateException, NotFoundException, ValidationException { WttCompany _company = readWttCompany(compId); WttProject _project = createWttProject(newProject); ProjectModel _pm = _project.getModel(); projectIndex.put(_pm.getId(), _project); _company.addProject(_project); logger.info("createProject(" + compId + ") -> " + PrettyPrinter.prettyPrintAsJSON(_pm)); if (isPersistent) { exportJson(companyIndex.values()); } return _pm; } private WttProject createWttProject( ProjectModel project) throws DuplicateException, ValidationException { String _id = project.getId(); if (_id == null || _id == "") { _id = UUID.randomUUID().toString(); } else { if (projectIndex.get(_id) != null) { // project with same ID exists already throw new DuplicateException("project <" + project.getId() + "> exists already."); } else { // a new ID was set on the client; we do not allow this throw new ValidationException("project <" + _id + "> contains an ID generated on the client. This is not allowed."); } } project.setId(_id); Date _date = new Date(); project.setCreatedAt(_date); project.setCreatedBy("DUMMY_USER"); project.setModifiedAt(_date); project.setModifiedBy("DUMMY_USER"); WttProject _newWttProject = new WttProject(); _newWttProject.setModel(project); return _newWttProject; } @Override public ProjectModel readProject( String compId, String projId) throws NotFoundException { readWttCompany(compId); ProjectModel _p = readWttProject(projId).getModel(); logger.info("readProject(" + projId + ") -> " + PrettyPrinter.prettyPrintAsJSON(_p)); return _p; } private WttProject readWttProject( String projId) throws NotFoundException { WttProject _p = projectIndex.get(projId); if (_p == null) { throw new NotFoundException("project <" + projId + "> was not found."); } return _p; } @Override public ProjectModel updateProject( String compId, String projId, ProjectModel project ) throws NotFoundException, ValidationException { readWttCompany(compId); WttProject _wttProject = readWttProject(projId); ProjectModel _pm = _wttProject.getModel(); if (! _pm.getCreatedAt().equals(project.getCreatedAt())) { throw new ValidationException("project<" + projId + ">: it is not allowed to change createAt on the client."); } if (! _pm.getCreatedBy().equalsIgnoreCase(project.getCreatedBy())) { throw new ValidationException("project<" + projId + ">: it is not allowed to change createBy on the client."); } _pm.setTitle(project.getTitle()); _pm.setDescription(project.getDescription()); _pm.setModifiedAt(new Date()); _pm.setModifiedBy("DUMMY_USER"); _wttProject.setModel(_pm); projectIndex.put(projId, _wttProject); logger.info("updateProject(" + compId + ", " + projId + ") -> " + PrettyPrinter.prettyPrintAsJSON(_pm)); if (isPersistent) { exportJson(companyIndex.values()); } return _pm; } @Override public void deleteProject( String compId, String projId ) throws NotFoundException, InternalServerErrorException { WttCompany _company = readWttCompany(compId); WttProject _project = readWttProject(projId); // 1) remove all subprojects from this project removeProjectsFromIndexRecursively(_project.getProjects()); // 2) remove the project from the index if (projectIndex.remove(projId) == null) { throw new InternalServerErrorException("project <" + projId + "> can not be removed, because it does not exist in the index."); } // 3) remove the project from its company (if projId is a top-level project) if (_company.removeProject(_project) == false) { // 4) remove the subproject from its parent-project (if projId is a subproject) if (projectIndex.remove(projId) == null) { throw new InternalServerErrorException("project <" + projId + "> can not be removed, because it is an orphan."); } } logger.info("deleteProject(" + compId + ", " + projId + ") -> OK"); if (isPersistent) { exportJson(companyIndex.values()); } } @Override public List<ProjectModel> listSubprojects( String compId, String projId, String query, String queryType, int position, int size) { readWttCompany(compId); // validate existence of company ArrayList<ProjectModel> _subprojects = new ArrayList<ProjectModel>(); for (WttProject _wttp : readWttProject(projId).getProjects()) { _subprojects.add(_wttp.getModel()); } Collections.sort(_subprojects, ProjectModel.ProjectComparator); ArrayList<ProjectModel> _selection = new ArrayList<ProjectModel>(); for (int i = 0; i < _subprojects.size(); i++) { if (i >= position && i < (position + size)) { _selection.add(_subprojects.get(i)); } } logger.info("listProjects(<" + compId + ">, <" + projId + ">, <"+ query + ">, <" + queryType + ">, <" + position + ">, <" + size + ">) -> " + _selection.size() + " values"); return _selection; } @Override public ProjectModel createSubproject( String compId, String projId, ProjectModel project) throws DuplicateException, NotFoundException, ValidationException { readWttCompany(compId); // validate existence of company WttProject _parentProject = readWttProject(projId); WttProject _subProject = createWttProject(project); ProjectModel _pm = _subProject.getModel(); projectIndex.put(_pm.getId(), _subProject); _parentProject.addProject(_subProject); logger.info("createSubproject(" + compId + ", " + projId + ") -> " + PrettyPrinter.prettyPrintAsJSON(_pm)); if (isPersistent) { exportJson(companyIndex.values()); } return _pm; } @Override public ProjectModel readSubproject( String compId, String projId, String subprojId) throws NotFoundException { readWttCompany(compId); // validate existence of company readWttProject(projId); // validate existence of parent project ProjectModel _p = readWttProject(subprojId).getModel(); logger.info("readSubproject(" + subprojId + ") -> " + PrettyPrinter.prettyPrintAsJSON(_p)); return _p; } @Override public ProjectModel updateSubproject( String compId, String projId, String subprojId, ProjectModel subproject) throws NotFoundException, ValidationException { readWttCompany(compId); // validate existence of company readWttProject(projId); // validate existence of parent project WttProject _wttSubProject = readWttProject(subprojId); ProjectModel _pm = _wttSubProject.getModel(); if (! _pm.getCreatedAt().equals(subproject.getCreatedAt())) { throw new ValidationException("subproject<" + projId + ">: it is not allowed to change createAt on the client."); } if (! _pm.getCreatedBy().equalsIgnoreCase(subproject.getCreatedBy())) { throw new ValidationException("subproject<" + projId + ">: it is not allowed to change createBy on the client."); } _pm.setTitle(subproject.getTitle()); _pm.setDescription(subproject.getDescription()); _pm.setModifiedAt(new Date()); _pm.setModifiedBy("DUMMY_USER"); _wttSubProject.setModel(_pm); projectIndex.put(subprojId, _wttSubProject); logger.info("updateSubProject(" + compId + ", " + projId + ", " + subprojId + ") -> " + PrettyPrinter.prettyPrintAsJSON(_pm)); if (isPersistent) { exportJson(companyIndex.values()); } return _pm; } @Override public void deleteSubproject(String compId, String projId, String subprojId) throws NotFoundException, InternalServerErrorException { readWttCompany(compId); WttProject _parentProject = readWttProject(projId); WttProject _subProject = readWttProject(subprojId); // 1) remove all subprojects from this project removeProjectsFromIndexRecursively(_subProject.getProjects()); // 2) remove the project from the index if (projectIndex.remove(subprojId) == null) { throw new InternalServerErrorException("subproject <" + subprojId + "> can not be removed, because it does not exist in the index."); } // 3) remove the subproject from its parent project if (_parentProject.removeProject(_subProject) == false) { throw new InternalServerErrorException("subproject <" + subprojId + "> can not be removed, because it is an orphan."); } logger.info("deleteSubproject(" + compId + ", " + projId + ", " + subprojId + ") -> OK"); if (isPersistent) { exportJson(companyIndex.values()); } } @Override public List<ResourceRefModel> listResources( String compId, String projId, String query, String queryType, int position, int size ) { readWttCompany(compId); // verify existence of compId List<ResourceRefModel> _resources = readWttProject(projId).getResources(); Collections.sort(_resources, ResourceRefModel.ResourceRefComparator); ArrayList<ResourceRefModel> _selection = new ArrayList<ResourceRefModel>(); for (int i = 0; i < _resources.size(); i++) { if (i >= position && i < (position + size)) { _selection.add(_resources.get(i)); } } logger.info("listResources(" + compId + ", " + projId + ", " + query + ", " + queryType + ", " + position + ", " + size + ") -> " + _selection.size() + " values"); return _selection; } // this _adds_ (or creates) an existing resourceRef to the resource list in project projId. // it does not create a new resource // the idea is to get (and administer) a resource in a separate service (e.g. AddressBook) @Override public ResourceRefModel addResource( String compId, String projId, ResourceRefModel resourceRef) throws NotFoundException, DuplicateException, ValidationException { readWttCompany(compId); // verify existence of compId WttProject _p = readWttProject(projId); // TODO: verify the validity of the referenced resourceId /* String _rid = resourceRef.getResourceId(); if (_rid == null || _rid == "") { throw new NotFoundException("a resourceRef with empty or null id is not valid, because its resource can not be found"); // TODO: check whether the referenced resource exists -> NotFoundException // TODO: verify firstName and lastName (these attributes are only cached from Resource) } */ String _id = resourceRef.getId(); if (_id == null || _id == "") { _id = UUID.randomUUID().toString(); } else { if (resourceIndex.get(_id) != null) { // resourceRef with same ID exists already throw new DuplicateException("resourceRef <" + resourceRef.getId() + "> exists already."); } else { // a new ID was set on the client; we do not allow this throw new ValidationException("resourceRef <" + resourceRef.getId() + "> contains an ID generated on the client. This is not allowed."); } } resourceRef.setId(_id); Date _date = new Date(); resourceRef.setCreatedAt(_date); resourceRef.setCreatedBy("DUMMY_USER"); resourceRef.setModifiedAt(_date); resourceRef.setModifiedBy("DUMMY_USER"); resourceIndex.put(_id, resourceRef); _p.addResource(resourceRef); return resourceRef; } @Override public void removeResource( String compId, String projId, String resourceId) throws NotFoundException, InternalServerErrorException { readWttCompany(compId); // verify existence of compId WttProject _p = readWttProject(projId); if (! _p.removeResource(resourceId)) { throw new NotFoundException("resource <" + resourceId + "> was not found in project <" + projId + ">."); } if (resourceIndex.remove(resourceId) == null) { throw new InternalServerErrorException("resource <" + resourceId + "> can not be removed, because it was not in the index."); } if (isPersistent) { exportJson(companyIndex.values()); } logger.info("removeResource(" + projId + ", " + resourceId + ") -> resource removed."); } /** * Recursively add all subprojects to the index. * * @param project * the new entry */ private void indexProjectRecursively( WttProject project) { projectIndex.put(project.getModel().getId(), project); for (WttProject _childProject : project.getProjects()) { indexProjectRecursively(_childProject); } for (ResourceRefModel _r : project.getResources()) { resourceIndex.put(_r.getId(), _r); } } /** * Recursively delete all subprojects from the index. * * @param childProjects */ private void removeProjectsFromIndexRecursively( List<WttProject> childProjects) { if (childProjects != null) { for (WttProject _project : childProjects) { removeProjectsFromIndexRecursively(_project.getProjects()); if ((projectIndex.remove(_project.getModel().getId())) == null) { throw new InternalServerErrorException("project <" + _project.getModel().getId() + "> can not be removed, because it does not exist in the index."); }; } } } }
package jp.kobe_u.cspiral.norakore; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Date; import java.util.Calendar; import java.util.List; import java.util.Random; import javax.imageio.ImageIO; import jp.kobe_u.cspiral.norakore.model.*; import jp.kobe_u.cspiral.norakore.util.DBUtils; import org.bson.types.ObjectId; import com.mongodb.BasicDBList; import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.sun.jersey.core.util.Base64; public class NorakoreController { private final String NyavatarColl_Name = "nyavatar"; private final String UserColl_Name = "user"; private final String PictureColl_Name = "picture"; private final String IconColl_Name = "icon"; private DBCollection NyavatarColl; private DBCollection UserColl; private DBCollection PictureColl; private DBCollection IconColl; public NorakoreController() { this.NyavatarColl = DBUtils.getInstance().getDb().getCollection(NyavatarColl_Name); this.UserColl = DBUtils.getInstance().getDb().getCollection(UserColl_Name); this.PictureColl = DBUtils.getInstance().getDb().getCollection(PictureColl_Name); this.IconColl = DBUtils.getInstance().getDb().getCollection(IconColl_Name); } public NyavatarList searchNyavatar(double lon, double lat) { final double search_range = 0.01; NyavatarList result = new NyavatarList(); List<Nyavatar> list = new ArrayList<Nyavatar>(); // (lon-0.01 < location.lon < lon+0.01) and (lat-0.01 < location.lat < lat+0.01) DBObject query = new BasicDBObject("location.lon", new BasicDBObject("$gt",lon-search_range).append("$lt", lon+search_range)). append("location.lat", new BasicDBObject("$gt",lat-search_range).append("$lt", lat+search_range)); DBCursor cursor = NyavatarColl.find(query); for (DBObject nya : cursor) { list.add(new Nyavatar(nya)); } result.setList(list); return result; } public NyavatarList getUsersNyavatar(String userID) throws Exception { NyavatarList result = new NyavatarList(); try { // retrieve the specified user's DBObject // DBObject query = new BasicDBObject("_id", new ObjectId(userID)); DBObject query = new BasicDBObject("_id", userID); DBObject userdbo = UserColl.findOne(query); if (userdbo == null) throw new Exception("Specified user is not found."); // get user's nyavatar list BasicDBList id_list = (BasicDBList)userdbo.get("nyavatarList"); if (id_list == null) throw new Exception("user's nyavatarList is not found."); // generate nyavatar list from id list List<Nyavatar> ny_list = new ArrayList<Nyavatar>(); for(Object id: id_list) { ObjectId oid = new ObjectId((String)id); DBObject ny_dbo = NyavatarColl.findOne(new BasicDBObject("_id", oid)); if (ny_dbo == null) throw new Exception("There is lost-nyavatar on db."); ny_list.add(new Nyavatar(ny_dbo)); } // generate result object result.setList(ny_list); } catch (IllegalArgumentException e) { throw new Exception(MessageFormat.format("Invalid userID, userID={0}", userID)); } return result; } public NyavatarDetail getNyavatarDetail(String nyavatarID, String userID){ NyavatarDetail result = new NyavatarDetail(); DBObject query = new BasicDBObject("_id",new ObjectId(nyavatarID)); DBObject queryResult = NyavatarColl.findOne(query); result.setNyavatarID(queryResult.get("_id").toString()); result.setName((String)queryResult.get("name")); result.setType((String)queryResult.get("type")); result.setPictureID((String)queryResult.get("pictureID")); result.setIconID((String)queryResult.get("iconID")); result.setDate((Date)queryResult.get("date")); result.setLocation(new Location((DBObject)queryResult.get("location"))); // TODO: LostCatIDAPILostCatsID // TODO: say result.setSay((String)queryResult.get("say")); return result; } public int likeNyavatar(String nyavatarID, String userID) throws Exception{ DBObject query = new BasicDBObject("_id", new ObjectId(nyavatarID)); DBObject userdbo = NyavatarColl.findOne(query); if (userdbo == null) throw new Exception(MessageFormat.format( "Specified nyavatar is not found. id={0}", nyavatarID)); // get nyavatar's likeUser list BasicDBList like_list = (BasicDBList)userdbo.get("likeUserList"); if (like_list == null) throw new Exception("The nyavatar has no likeUserList."); // add user to the list if (like_list.contains(userID)) throw new Exception("user already like the nyavatar."); like_list.add(userID); userdbo.put("likeUserList", like_list); NyavatarColl.update(query, userdbo); return like_list.size(); } public RegisterResult registerNyavatar(String userID, String name, String type, String picture, double lon, double lat) throws Exception { NyavatarDetail nya = new NyavatarDetail(); nya.setName(name); nya.setType(type); if (picture == null || picture.length() == 0) throw new Exception( "Param:picture is not specified."); String picid = saveImage(picture, "picture"); if (picid == "") throw new Exception("saveImage failed."); nya.setPictureID(picid); // iconID String iconid = "nullID"; Random rnd = new Random(); int ran = rnd.nextInt(3); switch(ran){ case 0: case 1: iconid = "563374c731b1b0e407093a9f"; break; case 2: iconid = "563374d831b1b0e408093a9f"; break; } nya.setIconID(iconid); Location loc = new Location(); loc.setLon(lon); loc.setLat(lat); nya.setLocation(loc); nya.setSay(""); nya.determineParams(userID); // TODO: picture DBObject dbo = nya.toDBObject(); NyavatarColl.insert(dbo); String nya_id = dbo.get("_id").toString(); //DBObject query = new BasicDBObject("_id", new ObjectId(userID)); DBObject query = new BasicDBObject("_id", userID); DBObject userdbo = UserColl.findOne(query); if (userdbo == null) throw new Exception("Specified user is not found."); BasicDBList list = (BasicDBList)userdbo.get("nyavatarList"); if (list == null) throw new Exception("user's nyavatarList is not found."); list.add(nya_id); userdbo.put("nyavatarList", list); Double bonitos = (Double)userdbo.get("bonitos") + 10; userdbo.put("bonitos", bonitos); UserColl.update(query, userdbo); RegisterResult result = new RegisterResult(); result.setNyavatarID(nya_id); result.setBonitos(bonitos.intValue()); return result; } public UserResult getUserInfo(String userID){ UserResult result = new UserResult(); DBObject query = new BasicDBObject("_id",userID); DBObject queryResult = UserColl.findOne(query); result.setUserID((String)queryResult.get("_id")); result.setName((String)queryResult.get("name")); result.setBonitos(((Double)queryResult.get("bonitos")).intValue()); // TODO: BasicDBList list = (BasicDBList)queryResult.get("itemList"); List<String> itemList = new ArrayList<String>(); for(Object el: list) { itemList.add((String) el); } result.setItemIDList(itemList); // nyavatarIDListiconIDList BasicDBList nyavatarlist = (BasicDBList)queryResult.get("nyavatarList"); List<String> iconList = new ArrayList<String>(); for(Object el: nyavatarlist) { DBObject querynya = new BasicDBObject("_id",new ObjectId((String)el)); DBObject querynyaResult = NyavatarColl.findOne(querynya); iconList.add((String)querynyaResult.get("iconID")); } result.setIconIDList(iconList); return result; } public String saveImage(String data, String res) { DBObject dbo = new BasicDBObject("src", data); if (res.equals("picture")){ PictureColl.save(dbo); }else if (res.equals("icon")){ IconColl.save(dbo); }else return ""; String id = dbo.get("_id").toString(); return id; } public ByteArrayOutputStream getImage(String id, String res) { DBObject query = new BasicDBObject("_id", new ObjectId(id)); String type; DBObject o; if (res.equals("picture")){ o = PictureColl.findOne(query); type = "jpg"; }else if (res.equals("icon")){ o = IconColl.findOne(query); type = "png"; }else return null; if (o == null) return null; String src = (String)o.get("src"); src = src.split(",")[1]; byte[] bytes = Base64.decode(src); try { BufferedImage bImage = ImageIO.read(new ByteArrayInputStream(bytes)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bImage, type, baos); return baos; } catch (IOException e) { // TODO catch e.printStackTrace(); } return null; } }
package be.crydust.tokenreplacer; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Objects; import java.util.concurrent.Callable; /** * * @author kristof */ public class FileReader implements Callable<String> { // 1 megabyte private static final long MAX_SIZE = 1 * 1024 * 1024; private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8; private final Path path; private final Charset encoding; /** * FileReader with default encoding (UTF_8) * * @param path */ public FileReader(Path path) { this(path, DEFAULT_ENCODING); } /** * FileReader with custom encoding * * @param path * @param encoding */ public FileReader(Path path, Charset encoding) { Objects.requireNonNull(path); Objects.requireNonNull(encoding); this.path = path; this.encoding = encoding; } @Override public String call() throws Exception { if (Files.size(path) > MAX_SIZE) { throw new RuntimeException("file is too large to read"); } byte[] encoded = Files.readAllBytes(path); return encoding.decode(ByteBuffer.wrap(encoded)).toString(); } }
package betterwithaddons.block; import betterwithaddons.item.rbdtools.ItemMatchPick; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.properties.PropertyBool; import net.minecraft.block.properties.PropertyDirection; import net.minecraft.block.state.BlockFaceShape; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.SoundEvents; import net.minecraft.item.ItemFlintAndSteel; import net.minecraft.item.ItemStack; import net.minecraft.util.*; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import java.util.Random; public class BlockLantern extends BlockBase { public static PropertyBool LIT = PropertyBool.create("lit"); public static PropertyDirection FACING = PropertyDirection.create("facing"); public BlockLantern(String name, Material materialIn) { super(name, materialIn); setDefaultState(getDefaultState().withProperty(FACING,EnumFacing.UP).withProperty(LIT,false)); } @Override public int getLightValue(IBlockState state) { return state.getValue(LIT) ? 15 : 0; } public boolean canPlaceBlockAt(World worldIn, BlockPos pos) { boolean canStay = false; for(EnumFacing facing : EnumFacing.VALUES) { if(canBlockStay(worldIn,pos,facing)) canStay = true; } return super.canPlaceBlockAt(worldIn, pos) && canStay; } @Override public void updateTick(World worldIn, BlockPos pos, IBlockState state, Random rand) { checkAndDrop(worldIn,state,pos); } @Override public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn, BlockPos frompos) { super.neighborChanged(state, worldIn, pos, blockIn,frompos); checkAndDrop(worldIn,state,pos); } @Override public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) { boolean isLit = state.getValue(LIT); ItemStack heldItem = playerIn.getHeldItem(hand); if(!isLit && !heldItem.isEmpty() && (heldItem.getItem() instanceof ItemFlintAndSteel || heldItem.getItem() instanceof ItemMatchPick)) { worldIn.setBlockState(pos,state.withProperty(LIT,true)); worldIn.playSound(null, pos, SoundEvents.ITEM_FIRECHARGE_USE, SoundCategory.BLOCKS, 1.0f, 1.5f); worldIn.playSound(null, pos, SoundEvents.ITEM_FLINTANDSTEEL_USE, SoundCategory.BLOCKS, 1.0f, 0.2f); heldItem.damageItem(1,playerIn); return true; } else if(isLit && heldItem.isEmpty() && playerIn.isSneaking()) { worldIn.setBlockState(pos,state.withProperty(LIT,false)); worldIn.playSound(null, pos, SoundEvents.BLOCK_FIRE_EXTINGUISH, SoundCategory.BLOCKS, 1.0f, 3f); return true; } return false; } public void checkAndDrop(World worldIn, IBlockState state, BlockPos pos) { if (!worldIn.isRemote && !canBlockStay(worldIn, pos, state.getValue(FACING))) { this.dropBlockAsItem(worldIn, pos, state, 0); worldIn.setBlockToAir(pos); } } public boolean canBlockStay(World worldIn, BlockPos pos, EnumFacing attachDir) { BlockPos attachPos = pos.offset(attachDir); IBlockState attach = worldIn.getBlockState(attachPos); return isSuitableAttachment(attach.getBlockFaceShape(worldIn, attachPos,attachDir.getOpposite()),attachDir); } private boolean isSuitableAttachment(BlockFaceShape shape, EnumFacing attachDir) { switch (shape) { case SOLID: case CENTER_BIG: return true; case CENTER_SMALL: return attachDir == EnumFacing.DOWN; case CENTER: return attachDir.getAxis() == EnumFacing.Axis.Y; default: return false; } } @Override public IBlockState getStateForPlacement(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer) { EnumFacing attachDir = facing.getOpposite(); if (canBlockStay(worldIn, pos, attachDir)) { return this.getDefaultState().withProperty(FACING, attachDir); } else { for (EnumFacing enumfacing : EnumFacing.Plane.HORIZONTAL) { if (canBlockStay(worldIn, pos, enumfacing)) { return this.getDefaultState().withProperty(FACING, enumfacing); } } return this.getDefaultState(); } } public boolean isOpaqueCube(IBlockState state) { return false; } public boolean isFullCube(IBlockState state) { return false; } public BlockRenderLayer getBlockLayer() { return BlockRenderLayer.CUTOUT; } public IBlockState withRotation(IBlockState state, Rotation rot) { return state.withProperty(FACING, rot.rotate(state.getValue(FACING))); } public IBlockState withMirror(IBlockState state, Mirror mirrorIn) { return state.withRotation(mirrorIn.toRotation(state.getValue(FACING))); } @Override public IBlockState getStateFromMeta(int meta) { return getDefaultState().withProperty(FACING, EnumFacing.getFront(meta & 7)).withProperty(LIT,(meta & 8) == 8); } @Override public int getMetaFromState(IBlockState state) { return state.getValue(FACING).getIndex() | (state.getValue(LIT) ? 8 : 0); } @Override protected BlockStateContainer createBlockState() { return new BlockStateContainer(this, LIT, FACING); } @Override public BlockFaceShape getBlockFaceShape(IBlockAccess worldIn, IBlockState state, BlockPos pos, EnumFacing face) { return face == EnumFacing.DOWN && state.getValue(FACING) == EnumFacing.DOWN ? BlockFaceShape.CENTER_BIG : BlockFaceShape.UNDEFINED; } }
package main.java.bschecker.bluesheets; import java.util.ArrayList; import main.java.bschecker.util.Error; import main.java.bschecker.util.ErrorList; import main.java.bschecker.util.Tools; /** * Finds errors with vague use of this or which. (4) * @author tedpyne */ public class VagueThisWhich extends Bluesheet { public final int ERROR_NUMBER = 4; /** * for testing purposes */ public static void main(String[] args){ Tools.initializeOpenNLP(); String input = ""; System.out.println("\ninput: " + input + "\n\n" + (new VagueThisWhich().findErrors(input)).tokensToChars(0, new ArrayList<Integer>())); } /** * finds any vague which or this in the given paragraph * @param line the paragraph in which to find errors * @param parses a String array of the parses of each sentence of the line * @return an ErrorList which for each error references start and end tokens, the bluesheet number (4), and, optionally, a note */ @Override protected ErrorList findErrors(String line, String[] parses){ String tokens[] = Tools.getTokenizer().tokenize(line); String[] tags = Tools.getPOSTagger().tag(tokens); ErrorList errors = new ErrorList(line, true); for(int i = 0; i < tokens.length; i++) if(tokens[i].equalsIgnoreCase("this") && isVagueThis(tokens,tags,i)) errors.add(new Error(i, ERROR_NUMBER, true, "Vague this")); else if(tokens[i].equalsIgnoreCase("which") && (i == 0 || (tags[i-1].charAt(0)!='N' && tags[i-1].charAt(0)!='I'))) errors.add(new Error(i, ERROR_NUMBER, true, "Vague which")); return errors; } /** * loops through tokens after "this" until a noun or verb is found * @param tokens the tokens to look through * @param tags the tags of those tokens * @param index the index to start looking from * @return true if followed by verb and is thus vague, false if followed by noun and is thus not vague */ private boolean isVagueThis(String[] tokens, String[] tags, int index) { if(index==tokens.length-1) return true; for(int j = index+1; j < tokens.length; j++){ if(tags[j].charAt(0)=='N') return false; if(tags[j].charAt(0)=='V' || tags[j].charAt(0)=='.' || tags[j].charAt(0)==':') return true; } return true; } }
package cc.tinker.controller; import com.google.gson.Gson; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController @RequestMapping("/auth") public class Authentication { @RequestMapping("/verification.do") public String authentication(){ return new Gson().toJson("{ret:0,msg:''}"); } }
package ch.tkuhn.nanopub.monitor; import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map; import org.nanopub.extra.server.ServerInfo; import org.nanopub.extra.server.ServerIterator; import com.google.common.collect.ImmutableList; public class ServerList implements Serializable { private static final long serialVersionUID = -6272932136983159574L; private static ServerList serverList; private static ServerIpInfo monitorIpInfo; public static ServerList get() { if (serverList == null) { serverList = new ServerList(); } return serverList; } private static Map<String,ServerData> servers = new HashMap<String,ServerData>(); private ServerList() { refresh(); } public List<ServerData> getServerData() { return ImmutableList.copyOf(servers.values()); } public ServerData getServerData(String serverUrl) { return servers.get(serverUrl); } public int getServerCount() { return servers.size(); } public ServerIpInfo getMonitorIpInfo() { if (monitorIpInfo == null) { try { monitorIpInfo = ServerData.fetchIpInfo(""); } catch (Exception ex) { ex.printStackTrace(); } } return monitorIpInfo; } public void refresh() { ServerIterator serverIterator = new ServerIterator(); while (serverIterator.hasNext()) { ServerInfo si = serverIterator.next(); String url = si.getPublicUrl(); try { if (servers.containsKey(url)) { servers.get(url).update(si); } else { servers.put(url, new ServerData(si)); } } catch (Exception ex) { ex.printStackTrace(); if (servers.containsKey(url)) { servers.get(url).update(null); } } } } }
package cn.momia.mapi.api.v1.user; import cn.momia.api.course.CouponServiceApi; import cn.momia.api.course.CourseServiceApi; import cn.momia.api.course.OrderServiceApi; import cn.momia.api.course.SubjectServiceApi; import cn.momia.api.course.dto.BookedCourse; import cn.momia.api.course.dto.Favorite; import cn.momia.api.course.dto.SubjectPackage; import cn.momia.api.course.dto.SubjectOrder; import cn.momia.api.course.dto.TimelineUnit; import cn.momia.api.course.dto.UserCoupon; import cn.momia.api.course.dto.UserCourseComment; import cn.momia.api.feed.FeedServiceApi; import cn.momia.api.feed.dto.UserFeed; import cn.momia.api.im.ImServiceApi; import cn.momia.api.user.dto.User; import cn.momia.common.api.dto.PagedList; import cn.momia.common.api.http.MomiaHttpResponse; import cn.momia.api.user.UserServiceApi; import cn.momia.common.util.SexUtil; import cn.momia.common.webapp.config.Configuration; import cn.momia.mapi.api.AbstractApi; import com.alibaba.fastjson.JSONObject; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.Date; import java.util.List; @RestController @RequestMapping("/v1/user") public class UserV1Api extends AbstractApi { @Autowired private CourseServiceApi courseServiceApi; @Autowired private SubjectServiceApi subjectServiceApi; @Autowired private CouponServiceApi couponServiceApi; @Autowired private OrderServiceApi orderServiceApi; @Autowired private FeedServiceApi feedServiceApi; @Autowired private ImServiceApi imServiceApi; @Autowired private UserServiceApi userServiceApi; @RequestMapping(method = RequestMethod.GET) public MomiaHttpResponse getUser(@RequestParam String utoken) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; return MomiaHttpResponse.SUCCESS(completeUserImgs(userServiceApi.get(utoken))); } @RequestMapping(value = "/nickname", method = RequestMethod.POST) public MomiaHttpResponse updateNickName(@RequestParam String utoken, @RequestParam(value = "nickname") String nickName) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (StringUtils.isBlank(nickName)) return MomiaHttpResponse.FAILED(""); if (nickName.contains("")) return MomiaHttpResponse.FAILED("“”"); User user = completeUserImgs(userServiceApi.updateNickName(utoken, nickName)); imServiceApi.updateImNickName(user.getToken(), user.getNickName()); return MomiaHttpResponse.SUCCESS(user); } @RequestMapping(value = "/avatar", method = RequestMethod.POST) public MomiaHttpResponse updateAvatar(@RequestParam String utoken, @RequestParam String avatar) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (StringUtils.isBlank(avatar)) return MomiaHttpResponse.FAILED(""); User user = completeUserImgs(userServiceApi.updateAvatar(utoken, avatar)); imServiceApi.updateImAvatar(user.getToken(), user.getAvatar()); return MomiaHttpResponse.SUCCESS(user); } @RequestMapping(value = "/cover", method = RequestMethod.POST) public MomiaHttpResponse updateCover(@RequestParam String utoken, @RequestParam String cover) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (StringUtils.isBlank(cover)) return MomiaHttpResponse.FAILED(""); return MomiaHttpResponse.SUCCESS(completeUserImgs(userServiceApi.updateCover(utoken, cover))); } @RequestMapping(value = "/name", method = RequestMethod.POST) public MomiaHttpResponse updateName(@RequestParam String utoken, @RequestParam String name) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (StringUtils.isBlank(name)) return MomiaHttpResponse.FAILED(""); return MomiaHttpResponse.SUCCESS(completeUserImgs(userServiceApi.updateName(utoken, name))); } @RequestMapping(value = "/sex", method = RequestMethod.POST) public MomiaHttpResponse updateSex(@RequestParam String utoken, @RequestParam String sex) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (StringUtils.isBlank(sex) || SexUtil.isInvalid(sex)) return MomiaHttpResponse.FAILED(""); return MomiaHttpResponse.SUCCESS(completeUserImgs(userServiceApi.updateSex(utoken, sex))); } @RequestMapping(value = "/birthday", method = RequestMethod.POST) public MomiaHttpResponse updateBirthday(@RequestParam String utoken, @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date birthday) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (birthday == null) return MomiaHttpResponse.FAILED(""); return MomiaHttpResponse.SUCCESS(completeUserImgs(userServiceApi.updateBirthday(utoken, birthday))); } @RequestMapping(value = "/city", method = RequestMethod.POST) public MomiaHttpResponse updateCity(@RequestParam String utoken, @RequestParam(value = "city") int cityId) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (cityId <= 0) return MomiaHttpResponse.FAILED("ID"); return MomiaHttpResponse.SUCCESS(completeUserImgs(userServiceApi.updateCity(utoken, cityId))); } @RequestMapping(value = "/region", method = RequestMethod.POST) public MomiaHttpResponse updateRegion(@RequestParam String utoken, @RequestParam(value = "region") int regionId) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (regionId <= 0) return MomiaHttpResponse.FAILED("ID"); return MomiaHttpResponse.SUCCESS(completeUserImgs(userServiceApi.updateRegion(utoken, regionId))); } @RequestMapping(value = "/address", method = RequestMethod.POST) public MomiaHttpResponse updateAddress(@RequestParam String utoken, @RequestParam String address) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (StringUtils.isBlank(address)) return MomiaHttpResponse.FAILED(""); return MomiaHttpResponse.SUCCESS(completeUserImgs(userServiceApi.updateAddress(utoken, address))); } @RequestMapping(value = "/course/notfinished", method = RequestMethod.GET) public MomiaHttpResponse listNotFinished(@RequestParam String utoken, @RequestParam int start) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; User user = userServiceApi.get(utoken); PagedList<BookedCourse> courses = courseServiceApi.queryNotFinishedByUser(user.getId(), start, Configuration.getInt("PageSize.Course")); completeMiddleCoursesImgs(courses.getList()); return MomiaHttpResponse.SUCCESS(courses); } @RequestMapping(value = "/course/finished", method = RequestMethod.GET) public MomiaHttpResponse listFinished(@RequestParam String utoken, @RequestParam int start) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; User user = userServiceApi.get(utoken); PagedList<BookedCourse> courses = courseServiceApi.queryFinishedByUser(user.getId(), start, Configuration.getInt("PageSize.Course")); completeMiddleCoursesImgs(courses.getList()); return MomiaHttpResponse.SUCCESS(courses); } @RequestMapping(value = "/bookable", method = RequestMethod.GET) public MomiaHttpResponse listBookableOrders(@RequestParam String utoken, @RequestParam(value = "oid", required = false, defaultValue = "0") long orderId, @RequestParam int start) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (start < 0) return MomiaHttpResponse.BAD_REQUEST; PagedList<SubjectPackage> packages = orderServiceApi.listBookable(utoken, orderId, start, Configuration.getInt("PageSize.Subject")); for (SubjectPackage orderPackage : packages.getList()) { orderPackage.setCover(completeMiddleImg(orderPackage.getCover())); } return MomiaHttpResponse.SUCCESS(packages); } @RequestMapping(value = "/order", method = RequestMethod.GET) public MomiaHttpResponse listOrders(@RequestParam String utoken, @RequestParam int status, @RequestParam int start) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (status <= 0 || start < 0) return MomiaHttpResponse.BAD_REQUEST; PagedList<SubjectOrder> orders = orderServiceApi.listOrders(utoken, status, start, Configuration.getInt("PageSize.Order")); for (SubjectOrder order : orders.getList()) { order.setCover(completeMiddleImg(order.getCover())); } return MomiaHttpResponse.SUCCESS(orders); } @RequestMapping(value = "/coupon", method = RequestMethod.GET) public MomiaHttpResponse listCoupons(@RequestParam String utoken, @RequestParam(required = false, defaultValue = "0") int status, @RequestParam int start) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (status < 0 || status > 3 || start < 0) return MomiaHttpResponse.BAD_REQUEST; PagedList<UserCoupon> userCoupons = couponServiceApi.listUserCoupons(utoken, status, start, Configuration.getInt("PageSize.UserCoupon")); return MomiaHttpResponse.SUCCESS(userCoupons); } @RequestMapping(value = "/favorite", method = RequestMethod.GET) public MomiaHttpResponse listFavorites(@RequestParam String utoken, @RequestParam(defaultValue = "1") int type, @RequestParam int start) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (start < 0) return MomiaHttpResponse.BAD_REQUEST; User user = userServiceApi.get(utoken); PagedList<Favorite> favorites; switch (type) { case Favorite.Type.SUBJECT: favorites = subjectServiceApi.listFavorites(user.getId(), start, Configuration.getInt("PageSize.Favorite")); completeFavoritesImgs(favorites); break; default: favorites = courseServiceApi.listFavorites(user.getId(), start, Configuration.getInt("PageSize.Favorite")); completeFavoritesImgs(favorites); } return MomiaHttpResponse.SUCCESS(favorites); } private void completeFavoritesImgs(PagedList<Favorite> favorites) { for (Favorite favorite : favorites.getList()) { JSONObject ref = favorite.getRef(); ref.put("cover", completeMiddleImg(ref.getString("cover"))); } } @RequestMapping(value = "/feed", method = RequestMethod.GET) public MomiaHttpResponse listFeeds(@RequestParam String utoken, @RequestParam int start) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (start < 0) return MomiaHttpResponse.BAD_REQUEST; User user = userServiceApi.get(utoken); PagedList<UserFeed> pagedFeeds = feedServiceApi.listFeedsOfUser(user.getId(), start, Configuration.getInt("PageSize.Feed")); completeFeedsImgs(pagedFeeds.getList()); return MomiaHttpResponse.SUCCESS(pagedFeeds); } @RequestMapping(value = "/info", method = RequestMethod.GET) public MomiaHttpResponse getInfo(@RequestParam(value = "uid") long userId, @RequestParam int start) { JSONObject infoJson = new JSONObject(); if (start == 0) { User user = userServiceApi.get(userId); if (!user.exists()) return MomiaHttpResponse.FAILED(""); infoJson.put("user", completeUserImgs(user)); } PagedList<UserFeed> pagedFeeds = feedServiceApi.listFeedsOfUser(userId, start, Configuration.getInt("PageSize.Feed")); completeFeedsImgs(pagedFeeds.getList()); infoJson.put("feeds", pagedFeeds); return MomiaHttpResponse.SUCCESS(infoJson); } @RequestMapping(value = "/timeline", method = RequestMethod.GET) public MomiaHttpResponse timeline(@RequestParam(value = "uid") long userId, @RequestParam int start) { if (userId <=0 || start < 0) return MomiaHttpResponse.BAD_REQUEST; JSONObject timelineJson = new JSONObject(); if (start == 0) { User user = userServiceApi.get(userId); if (!user.exists()) return MomiaHttpResponse.FAILED(""); timelineJson.put("user", completeUserImgs(user)); } PagedList<TimelineUnit> timeline = courseServiceApi.timelineOfUser(userId, start, Configuration.getInt("PageSize.Timeline")); completeTimelineImgs(timeline.getList()); timelineJson.put("timeline", timeline); return MomiaHttpResponse.SUCCESS(timelineJson); } private List<TimelineUnit> completeTimelineImgs(List<TimelineUnit> list) { for (TimelineUnit unit : list) { UserCourseComment comment = unit.getComment(); if (comment != null) completeCourseCommentImgs(comment); } return list; } @RequestMapping(value = "/comment/timeline", method = RequestMethod.GET) public MomiaHttpResponse commentTimeline(@RequestParam(value = "uid") long userId, @RequestParam int start) { if (userId <=0 || start < 0) return MomiaHttpResponse.BAD_REQUEST; JSONObject timelineJson = new JSONObject(); if (start == 0) { User user = userServiceApi.get(userId); if (!user.exists()) return MomiaHttpResponse.FAILED(""); timelineJson.put("user", completeUserImgs(user)); } PagedList<TimelineUnit> timeline = courseServiceApi.commentTimelineOfUser(userId, start, Configuration.getInt("PageSize.Timeline")); completeTimelineImgs(timeline.getList()); timelineJson.put("timeline", timeline); return MomiaHttpResponse.SUCCESS(timelineJson); } }
package cn.wizzer.common.filter; import cn.wizzer.common.base.Globals; import cn.wizzer.modules.back.sys.models.Sys_route; import org.nutz.lang.Lang; import org.nutz.log.Log; import org.nutz.log.Logs; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class RouteFilter implements Filter { private static final Log log = Logs.get(); @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest req2 = (HttpServletRequest) req; HttpServletResponse res2 = (HttpServletResponse) res; res2.setCharacterEncoding("utf-8"); req2.setCharacterEncoding("utf-8"); Sys_route route = Globals.RouteMap.get(req2.getRequestURI()); if (route != null) { if ("show".equals(route.getType())) { res2.sendRedirect(route.getToUrl()); } else { req2.getRequestDispatcher(route.getToUrl()).forward(req2, res2); } } else chain.doFilter(req2, res2); } @Override public void init(FilterConfig arg0) throws ServletException { } @Override public void destroy() { } }
package com.akiban.qp.operator; import com.akiban.qp.row.HKey; import com.akiban.qp.row.Row; import com.akiban.server.service.session.Session; import com.akiban.server.error.ErrorCode; import com.akiban.server.error.InvalidOperationException; import com.akiban.server.types.AkType; import com.akiban.server.types.ValueSource; import java.util.Date; public interface QueryContext { /** * Gets the value bound to the given index. * @param index the index to look up * @return the value at that index * @throws BindingNotSetException if the given index wasn't set */ public ValueSource getValue(int index); /** * Bind a value to the given index. * @param index the index to set * @param value the value to assign */ public void setValue(int index, ValueSource value); /** * Bind a value to the given index. * @param index the index to set * @param value the value to assign * @param type the type to convert the value to for binding */ public void setValue(int index, ValueSource value, AkType type); /** * Bind a value to the given index. * @param index the index to set * @param value the value to assign */ public void setValue(int index, Object value); /** * Bind a value to the given index. * @param index the index to set * @param value the value to assign */ public void setValue(int index, Object value, AkType type); /** * Gets the row bound to the given index. * @param index the index to look up * @return the row at that index * @throws BindingNotSetException if the given index wasn't set */ public Row getRow(int index); /** * Bind a row to the given index. * @param index the index to set * @param row the row to assign */ public void setRow(int index, Row row); /** * Gets the hKey bound to the given index. * @param index the index to look up * @return the hKey at that index * @throws BindingNotSetException if the given index wasn't set */ public HKey getHKey(int index); /** * Bind an hkey to the given index. * @param index the index to set * @param hKey the hKey to assign */ public void setHKey(int index, HKey hKey); /** * Get the store associated with this query. */ public StoreAdapter getStore(); /** * Get the session associated with this context. */ public Session getSession(); /** * Get the current date. * This time may be frozen from the start of a transaction. */ public Date getCurrentDate(); /** * Get the current schema name. */ public String getCurrentUser(); /** * Get the server user name. */ public String getSessionUser(); /** * Get the system identity of the server process. */ public String getSystemUser(); /** * Get the system time at which the query started. */ public long getStartTime(); /** * Possible notification levels for {@link #notifyClient}. */ public enum NotificationLevel { WARNING, INFO, DEBUG } /** * Send a warning (or other) notification to the remote client. * The message will be delivered as part of the current operation, * perhaps immediately or perhaps at its completion, depending on * the implementation. */ public void notifyClient(NotificationLevel level, ErrorCode errorCode, String message); /** * Send a warning notification to the remote client from the given exception. */ public void warnClient(InvalidOperationException exception); /** Get the query timeout in seconds or <code>-1</code> if no limit. */ public long getQueryTimeoutSec(); /** Check whether query has been cancelled or timeout has been exceeded. */ public void checkQueryCancelation(); }
package com.alonkadury.initialState; import com.google.gson.Gson; import javax.net.ssl.HttpsURLConnection; import java.io.*; import java.net.URL; import java.util.HashMap; public class Account { private String accessKey; private final static String X_ACCESS_KEY = "X-IS-AccessKey"; private final static String METHOD_TYPE = "POST"; private final static String CONTENT_TYPE_KEY = "Content-Type"; private final static String CONTENT_TYPE_VALUE = "application/json"; private final static String ACCEPT_VERSION_KEY = "Accept-Version"; private final static String ACCEPT_VERSION_VALUE = "~0"; private final static String BUCKET_KEY = "X-IS-BucketKey"; private Gson gson; // thread safe according to docs public Account(String accessKey) { this.accessKey = accessKey; gson = new Gson(); } public void createBucket(Bucket bucket) { sendRequest(bucket.getEndpoint(), null, gson.toJson(bucket)); } public void createData(Bucket bucket, Data data) { HashMap<String, String> hash = new HashMap<String, String>(); hash.put(BUCKET_KEY, bucket.getKey()); sendRequest(data.getEndpoint(), hash, gson.toJson(data)); } public void createBulkData(Bucket bucket, Data[] bulkData) { HashMap<String, String> hash = new HashMap<String, String>(); hash.put(BUCKET_KEY, bucket.getKey()); sendRequest(bulkData[0].getEndpoint(), hash, gson.toJson(bulkData)); } private boolean sendRequest(String endpoint, HashMap<String, String> customHeaders, String body) { try { URL url = new URL(endpoint); HttpsURLConnection con = (HttpsURLConnection)url.openConnection(); //add reuqest headers con.setRequestMethod(METHOD_TYPE); con.setRequestProperty(CONTENT_TYPE_KEY, CONTENT_TYPE_VALUE); con.setRequestProperty(X_ACCESS_KEY, accessKey); con.setRequestProperty(ACCEPT_VERSION_KEY, ACCEPT_VERSION_VALUE); if (customHeaders != null) customHeaders.forEach((k, v) -> con.setRequestProperty(k, v)); con.setDoOutput(true); con.setDoInput(true); DataOutputStream writer = new DataOutputStream(con.getOutputStream()); writer.writeBytes(body); writer.flush(); writer.close(); int responseCode = con.getResponseCode(); //System.out.println("Response Code : " + responseCode); //InputStream is = con.getInputStream(); //BufferedReader reader = new BufferedReader(new InputStreamReader(is)); //String line; //StringBuffer response = new StringBuffer(); //while((line = reader.readLine()) != null) { // response.append(line); // response.append('\r'); //reader.close(); //System.err.println(response.toString()); con.disconnect(); if (responseCode >= 200 && responseCode < 300) return true; else return false; } catch (IOException ex) { System.err.println(ex.toString()); return false; } } }
package com.arckenver.nations; import java.io.File; import java.io.IOException; import org.spongepowered.api.Sponge; import org.spongepowered.api.world.World; import com.arckenver.nations.object.Nation; import ninja.leaping.configurate.commented.CommentedConfigurationNode; import ninja.leaping.configurate.hocon.HoconConfigurationLoader; import ninja.leaping.configurate.loader.ConfigurationLoader; public class ConfigHandler { private static File configFile; private static ConfigurationLoader<CommentedConfigurationNode> configManager; private static CommentedConfigurationNode config; public static void init(File rootDir) { configFile = new File(rootDir, "config.conf"); configManager = HoconConfigurationLoader.builder().setPath(configFile.toPath()).build(); } public static void load() { // load file try { if (!configFile.exists()) { configFile.getParentFile().mkdirs(); configFile.createNewFile(); config = configManager.load(); configManager.save(config); } config = configManager.load(); } catch (IOException e) { NationsPlugin.getLogger().error("Could not load or create config file !"); e.printStackTrace(); } // check integrity Utils.ensurePositiveNumber(config.getNode("prices").getNode("nationCreationPrice"), 2500); Utils.ensurePositiveNumber(config.getNode("prices").getNode("upkeepPerCitizen"), 100); Utils.ensurePositiveNumber(config.getNode("prices").getNode("unclaimRefundPercentage"), 0); Utils.ensurePositiveNumber(config.getNode("prices").getNode("extraPrice"), 0.5); Utils.ensurePositiveNumber(config.getNode("prices").getNode("blockClaimPrice"), 0.3); Utils.ensurePositiveNumber(config.getNode("others").getNode("blocksPerCitizen"), 1000); Utils.ensurePositiveNumber(config.getNode("others").getNode("blocksPerSpawn"), 3500); Utils.ensurePositiveNumber(config.getNode("others").getNode("minNationDistance"), 500); Utils.ensurePositiveNumber(config.getNode("others").getNode("maxExtra"), 5000); Utils.ensurePositiveNumber(config.getNode("others").getNode("minNationNameLength"), 3); Utils.ensurePositiveNumber(config.getNode("others").getNode("maxNationNameLength"), 13); Utils.ensureBoolean(config.getNode("nations").getNode("flags").getNode("pvp"), false); Utils.ensureBoolean(config.getNode("nations").getNode("flags").getNode("mobs"), false); Utils.ensureBoolean(config.getNode("nations").getNode("flags").getNode("fire"), false); Utils.ensureBoolean(config.getNode("nations").getNode("flags").getNode("explosions"), false); Utils.ensureBoolean(config.getNode("nations").getNode("perms").getNode(Nation.TYPE_OUTSIDER).getNode(Nation.PERM_BUILD), false); Utils.ensureBoolean(config.getNode("nations").getNode("perms").getNode(Nation.TYPE_OUTSIDER).getNode(Nation.PERM_INTERACT), false); Utils.ensureBoolean(config.getNode("nations").getNode("perms").getNode(Nation.TYPE_CITIZEN).getNode(Nation.PERM_BUILD), false); Utils.ensureBoolean(config.getNode("nations").getNode("perms").getNode(Nation.TYPE_CITIZEN).getNode(Nation.PERM_INTERACT), true); Utils.ensureBoolean(config.getNode("zones").getNode("perms").getNode(Nation.TYPE_OUTSIDER).getNode(Nation.PERM_BUILD), false); Utils.ensureBoolean(config.getNode("zones").getNode("perms").getNode(Nation.TYPE_OUTSIDER).getNode(Nation.PERM_INTERACT), false); Utils.ensureBoolean(config.getNode("zones").getNode("perms").getNode(Nation.TYPE_CITIZEN).getNode(Nation.PERM_BUILD), false); Utils.ensureBoolean(config.getNode("zones").getNode("perms").getNode(Nation.TYPE_CITIZEN).getNode(Nation.PERM_INTERACT), true); Utils.ensureBoolean(config.getNode("zones").getNode("perms").getNode(Nation.TYPE_COOWNER).getNode(Nation.PERM_BUILD), true); Utils.ensureBoolean(config.getNode("zones").getNode("perms").getNode(Nation.TYPE_COOWNER).getNode(Nation.PERM_INTERACT), true); for (World world : Sponge.getServer().getWorlds()) { CommentedConfigurationNode node = config.getNode("worlds").getNode(world.getName()); Utils.ensureBoolean(node.getNode("enabled"), true); if (node.getNode("enabled").getBoolean()) { Utils.ensureBoolean(node.getNode("perms").getNode(Nation.PERM_BUILD), true); Utils.ensureBoolean(node.getNode("perms").getNode(Nation.PERM_INTERACT), true); Utils.ensureBoolean(node.getNode("flags").getNode("pvp"), true); Utils.ensureBoolean(node.getNode("flags").getNode("mobs"), true); Utils.ensureBoolean(node.getNode("flags").getNode("fire"), true); Utils.ensureBoolean(node.getNode("flags").getNode("explosions"), true); } else { node.removeChild("perms"); node.removeChild("flags"); } } save(); } public static void save() { try { configManager.save(config); } catch (IOException e) { NationsPlugin.getLogger().error("Could not save config file !"); } } public static CommentedConfigurationNode getNode(String path) { return config.getNode(path); } public static class Utils { public static void ensurePositiveNumber(CommentedConfigurationNode node, String def) { if (node.getString() == null) { node.setValue(def); } } public static void ensurePositiveNumber(CommentedConfigurationNode node, Number def) { if (!(node.getValue() instanceof Number) || node.getDouble(-1) < 0) { node.setValue(def); } } public static void ensureBoolean(CommentedConfigurationNode node, boolean def) { if (!(node.getValue() instanceof Boolean)) { node.setValue(def); } } } }
package com.cisco.trex.stateless; import com.cisco.trex.ClientBase; import com.cisco.trex.stateless.exception.ServiceModeRequiredException; import com.cisco.trex.stateless.exception.TRexConnectionException; import com.cisco.trex.stateless.model.ApiVersionHandler; import com.cisco.trex.stateless.model.Ipv6Node; import com.cisco.trex.stateless.model.Port; import com.cisco.trex.stateless.model.PortStatus; import com.cisco.trex.stateless.model.Stream; import com.cisco.trex.stateless.model.StreamMode; import com.cisco.trex.stateless.model.StreamModeRate; import com.cisco.trex.stateless.model.StreamRxStats; import com.cisco.trex.stateless.model.StreamVM; import com.cisco.trex.stateless.model.TRexClientResult; import com.cisco.trex.stateless.model.port.PortVlan; import com.cisco.trex.stateless.model.stats.ActivePGIds; import com.cisco.trex.stateless.model.stats.ActivePGIdsRPCResult; import com.cisco.trex.stateless.model.stats.PGIdStatsRPCResult; import com.cisco.trex.stateless.model.vm.VMInstruction; import com.cisco.trex.util.Constants; import com.google.common.collect.Lists; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.net.Inet4Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.MessageFormat; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import org.pcap4j.packet.ArpPacket; import org.pcap4j.packet.Dot1qVlanTagPacket; import org.pcap4j.packet.EthernetPacket; import org.pcap4j.packet.IcmpV4CommonPacket; import org.pcap4j.packet.IcmpV4EchoPacket; import org.pcap4j.packet.IcmpV4EchoReplyPacket; import org.pcap4j.packet.IllegalRawDataException; import org.pcap4j.packet.IpV4Packet; import org.pcap4j.packet.IpV4Rfc791Tos; import org.pcap4j.packet.Packet; import org.pcap4j.packet.namednumber.ArpHardwareType; import org.pcap4j.packet.namednumber.ArpOperation; import org.pcap4j.packet.namednumber.EtherType; import org.pcap4j.packet.namednumber.IcmpV4Code; import org.pcap4j.packet.namednumber.IcmpV4Type; import org.pcap4j.packet.namednumber.IpNumber; import org.pcap4j.packet.namednumber.IpVersion; import org.pcap4j.util.ByteArrays; import org.pcap4j.util.MacAddress; /** TRex client for stateless traffic */ public class TRexClient extends ClientBase { private static final String TYPE = "type"; private static final String STREAM = "stream"; private static final String STREAM_ID = "stream_id"; private static final EtherType QInQ = new EtherType((short) 0x88a8, "802.1Q Provider Bridge (Q-in-Q)"); private static final int SESSON_ID = 123456789; TRexClient(TRexTransport transport, Set<String> supportedCommands) { // For unit testing this.transport = transport; this.host = "testHost"; this.port = "testPort"; this.userName = "testUser"; supportedCmds.addAll(supportedCommands); } /** * constructor * * @param host * @param port * @param userName */ public TRexClient(String host, String port, String userName) { this.host = host; this.port = port; this.userName = userName; supportedCmds.add("api_sync_v2"); supportedCmds.add("get_supported_cmds"); EtherType.register(QInQ); } @Override protected void serverAPISync() throws TRexConnectionException { LOGGER.info("Sync API with the TRex"); Map<String, Object> parameters = new HashMap<>(); parameters.put("name", "STL"); parameters.put("major", Constants.STL_API_VERSION_MAJOR); parameters.put("minor", Constants.STL_API_VERSION_MINOR); TRexClientResult<ApiVersionHandler> result = callMethod("api_sync_v2", parameters, ApiVersionHandler.class); if (result.get() == null) { TRexConnectionException e = new TRexConnectionException( MessageFormat.format( "Unable to connect to TRex server. Required API version is {0}.{1}. Error: {2}", Constants.STL_API_VERSION_MAJOR, Constants.STL_API_VERSION_MINOR, result.getError())); LOGGER.error("Unable to sync client with TRex server due to: API_H is null.", e.getMessage()); throw e; } apiH = result.get().getApiH(); LOGGER.info("Received api_H: {}", apiH); } @Deprecated @Override public PortStatus acquirePort(int portIndex, Boolean force) { Map<String, Object> payload = createPayload(portIndex); payload.put("session_id", SESSON_ID); payload.put("user", userName); payload.put("force", force); String json = callMethod("acquire", payload); String handler = getResultFromResponse(json).getAsString(); portHandlers.put(portIndex, handler); return getPortStatus(portIndex).get(); } /** * Reset port stop traffic, remove all streams, remove rx queue, disable service mode and release * port * * @param portIndex */ public void resetPort(int portIndex) { acquirePort(portIndex, true); stopTraffic(portIndex); for (String profileId : getProfileIds(portIndex)) { removeAllStreams(portIndex, profileId); } removeRxQueue(portIndex); serviceMode(portIndex, false); releasePort(portIndex); } /** * Set port in service mode, needed to be able to do arp resolution and packet captureing * * @param portIndex * @param isOn * @return PortStatus */ public PortStatus serviceMode(int portIndex, Boolean isOn) { LOGGER.info("Set service mode : {}", isOn ? "on" : "off"); Map<String, Object> payload = createPayload(portIndex); payload.put("enabled", isOn); callMethod("service", payload); return getPortStatus(portIndex).get(); } public void addStream(int portIndex, Stream stream) { addStream(portIndex, "", stream.getId(), stream); } public void addStream(int portIndex, String profileId, Stream stream) { addStream(portIndex, profileId, stream.getId(), stream); } public void addStream(int portIndex, int streamId, JsonObject stream) { addStream(portIndex, "", streamId, stream); } public void addStream(int portIndex, String profileId, int streamId, JsonObject stream) { addStream(portIndex, profileId, streamId, stream); } private void addStream(int portIndex, String profileId, int streamId, Object streamObject) { Map<String, Object> payload = createPayload(portIndex, profileId); payload.put(STREAM_ID, streamId); payload.put(STREAM, streamObject); callMethod("add_stream", payload); } public Stream getStream(int portIndex, int streamId) { Map<String, Object> payload = createPayload(portIndex); payload.put("get_pkt", true); payload.put(STREAM_ID, streamId); String json = callMethod("get_stream", payload); JsonObject stream = getResultFromResponse(json).getAsJsonObject().get(STREAM).getAsJsonObject(); return GSON.fromJson(stream, Stream.class); } public void removeStream(int portIndex, int streamId) { Map<String, Object> payload = createPayload(portIndex); payload.put(STREAM_ID, streamId); callMethod("remove_stream", payload); } public void removeStream(int portIndex, String profileId, int streamId) { Map<String, Object> payload = createPayload(portIndex, profileId); payload.put(STREAM_ID, streamId); callMethod("remove_stream", payload); } public void removeAllStreams(int portIndex) { removeAllStreams(portIndex, ""); } public void removeAllStreams(int portIndex, String profileId) { Map<String, Object> payload = createPayload(portIndex, profileId); callMethod("remove_all_streams", payload); } public List<Stream> getAllStreams(int portIndex) { return getAllStreams(portIndex, ""); } public List<Stream> getAllStreams(int portIndex, String profileId) { Map<String, Object> payload = createPayload(portIndex, profileId); String json = callMethod("get_all_streams", payload); JsonObject streams = getResultFromResponse(json).getAsJsonObject().get("streams").getAsJsonObject(); ArrayList<Stream> streamList = new ArrayList<>(); for (Map.Entry<String, JsonElement> stream : streams.entrySet()) { streamList.add(GSON.fromJson(stream.getValue(), Stream.class)); } return streamList; } public List<Integer> getStreamIds(int portIndex) { return getStreamIds(portIndex, ""); } public List<Integer> getStreamIds(int portIndex, String profileId) { Map<String, Object> payload = createPayload(portIndex, profileId); String json = callMethod("get_stream_list", payload); JsonArray ids = getResultFromResponse(json).getAsJsonArray(); return StreamSupport.stream(ids.spliterator(), false) .map(JsonElement::getAsInt) .collect(Collectors.toList()); } public void pauseStreams(int portIndex, List<Integer> streams) { Map<String, Object> payload = createPayload(portIndex); payload.put("stream_ids", streams); callMethod("pause_streams", payload); } public void resumeStreams(int portIndex, List<Integer> streams) { Map<String, Object> payload = createPayload(portIndex); payload.put("stream_ids", streams); callMethod("resume_streams", payload); } public void updateStreams( int portIndex, List<Integer> streams, boolean force, Map<String, Object> multiplier) { Map<String, Object> payload = createPayload(portIndex); payload.put("force", force); payload.put("mul", multiplier); payload.put("stream_ids", streams); callMethod("update_streams", payload); } public List<String> getProfileIds(int portIndex) { Map<String, Object> payload = createPayload(portIndex); String json = callMethod("get_profile_list", payload); JsonArray ids = getResultFromResponse(json).getAsJsonArray(); return StreamSupport.stream(ids.spliterator(), false) .map(JsonElement::getAsString) .collect(Collectors.toList()); } public ActivePGIds getActivePgids() { Map<String, Object> parameters = new HashMap<>(); parameters.put("pgids", ""); return callMethod("get_active_pgids", parameters, ActivePGIdsRPCResult.class).get().getIds(); } public PGIdStatsRPCResult getPgidStats(int[] ids) { Map<String, Object> parameters = new HashMap<>(); parameters.put("pgids", ids); return callMethod("get_pgid_stats", parameters, PGIdStatsRPCResult.class).get(); } public void startTraffic( int portIndex, double duration, boolean force, Map<String, Object> mul, int coreMask) { startTraffic(portIndex, "", duration, force, mul, coreMask); } public void startTraffic( int portIndex, String profileId, double duration, boolean force, Map<String, Object> mul, int coreMask) { Map<String, Object> payload = createPayload(portIndex, profileId); payload.put("core_mask", coreMask); payload.put("mul", mul); payload.put("duration", duration); payload.put("force", force); callMethod("start_traffic", payload); } public void startAllTraffic( int portIndex, double duration, boolean force, Map<String, Object> mul, int coreMask) { List<String> profileIds = getProfileIds(portIndex); for (String profileId : profileIds) { startTraffic(portIndex, profileId, duration, force, mul, coreMask); } } public void pauseTraffic(int portIndex) { Map<String, Object> payload = createPayload(portIndex); callMethod("pause_traffic", payload); } public void resumeTraffic(int portIndex) { Map<String, Object> payload = createPayload(portIndex); callMethod("resume_traffic", payload); } public void setRxQueue(int portIndex, int size) { Map<String, Object> payload = createPayload(portIndex); payload.put(TYPE, "queue"); payload.put("enabled", true); payload.put("size", size); callMethod("set_rx_feature", payload); } public void removeRxQueue(int portIndex) { Map<String, Object> payload = createPayload(portIndex); payload.put(TYPE, "queue"); payload.put("enabled", false); callMethod("set_rx_feature", payload); } /** Set promiscuous mode, Enable interface to receive packets from all mac addresses */ public void setPromiscuousMode(int portIndex, boolean enabled) { Map<String, Object> payload = createPayload(portIndex); Map<String, Object> attributes = new HashMap<>(); Map<String, Object> promiscuousValue = new HashMap<>(); promiscuousValue.put("enabled", enabled); attributes.put("promiscuous", promiscuousValue); payload.put("attr", attributes); callMethod("set_port_attr", payload); } /** Set flow control mode, Flow control: 0 = none, 1 = tx, 2 = rx, 3 = full */ public void setFlowControlMode(int portIndex, int mode) { Map<String, Object> payload = createPayload(portIndex); Map<String, Object> attributes = new HashMap<>(); Map<String, Object> flowCtrlValue = new HashMap<>(); flowCtrlValue.put("enabled", mode); attributes.put("flow_ctrl_mode", flowCtrlValue); payload.put("attr", attributes); callMethod("set_port_attr", payload); } public synchronized void sendPacket(int portIndex, Packet pkt) { Stream stream = build1PktSingleBurstStream(pkt); removeAllStreams(portIndex); addStream(portIndex, stream); Map<String, Object> mul = new HashMap<>(); mul.put("op", "abs"); mul.put(TYPE, "pps"); mul.put("value", 1.0); startTraffic(portIndex, 1, true, mul, 1); } public synchronized void startStreamsIntermediate(int portIndex, List<Stream> streams) { removeRxQueue(portIndex); setRxQueue(portIndex, 1000); removeAllStreams(portIndex); streams.forEach(s -> addStream(portIndex, s)); Map<String, Object> mul = new HashMap<>(); mul.put("op", "abs"); mul.put(TYPE, "percentage"); mul.put("value", 100); startTraffic(portIndex, -1, true, mul, 1); } public synchronized void sendPackets(int portIndex, List<Packet> pkts) { removeAllStreams(portIndex); for (Packet pkt : pkts) { addStream(portIndex, build1PktSingleBurstStream(pkt)); } Map<String, Object> mul = new HashMap<>(); mul.put("op", "abs"); mul.put(TYPE, "pps"); mul.put("value", 1.0); startTraffic(portIndex, 1, true, mul, 1); stopTraffic(portIndex); } public String resolveArp(int portIndex, String srcIp, String dstIp) { String srcMac = getPortByIndex(portIndex).hw_mac; PortVlan vlan = getPortStatus(portIndex).get().getAttr().getVlan(); return resolveArp(portIndex, vlan, srcIp, srcMac, dstIp); } public String resolveArp(int portIndex, String srcIp, String srcMac, String dstIp) { PortVlan vlan = getPortStatus(portIndex).get().getAttr().getVlan(); return resolveArp(portIndex, vlan, srcIp, srcMac, dstIp); } public String resolveArp( int portIndex, PortVlan vlan, String srcIp, String srcMac, String dstIp) { removeRxQueue(portIndex); setRxQueue(portIndex, 1000); EthernetPacket pkt = buildArpPkt(srcMac, srcIp, dstIp, vlan); sendPacket(portIndex, pkt); Predicate<EthernetPacket> arpReplyFilter = etherPkt -> { Queue<Integer> vlanTags = new LinkedList<>(vlan.getTags()); Packet nextPkt = etherPkt; boolean vlanOutsideMatches = true; if (etherPkt.getHeader().getType() == QInQ) { try { Dot1qVlanTagPacket qInqPkt = Dot1qVlanTagPacket.newPacket( etherPkt.getRawData(), etherPkt.getHeader().length(), etherPkt.getPayload().length()); vlanOutsideMatches = qInqPkt.getHeader().getVidAsInt() == vlanTags.poll(); nextPkt = qInqPkt.getPayload(); } catch (IllegalRawDataException e) { return false; } } boolean vlanInsideMatches = true; if (nextPkt.contains(Dot1qVlanTagPacket.class)) { Dot1qVlanTagPacket dot1qVlanTagPacket = nextPkt.get(Dot1qVlanTagPacket.class); vlanInsideMatches = dot1qVlanTagPacket.getHeader().getVid() == vlanTags.poll(); } if (nextPkt.contains(ArpPacket.class)) { ArpPacket arp = nextPkt.get(ArpPacket.class); ArpOperation arpOp = arp.getHeader().getOperation(); String replyDstMac = arp.getHeader().getDstHardwareAddr().toString(); boolean arpMatches = ArpOperation.REPLY.equals(arpOp) && replyDstMac.equals(srcMac); return arpMatches && vlanOutsideMatches && vlanInsideMatches; } return false; }; List<org.pcap4j.packet.Packet> pkts = new ArrayList<>(); try { int steps = 10; while (steps > 0) { steps -= 1; Thread.sleep(500); pkts.addAll(getRxQueue(portIndex, arpReplyFilter)); if (!pkts.isEmpty()) { ArpPacket arpPacket = getArpPkt(pkts.get(0)); if (arpPacket != null) { return arpPacket.getHeader().getSrcHardwareAddr().toString(); } } } LOGGER.info("Unable to get ARP reply in {} seconds", steps); } catch (InterruptedException ignored) { } finally { removeRxQueue(portIndex); if (getPortStatus(portIndex).get().getState().equals("TX")) { stopTraffic(portIndex); } removeAllStreams(portIndex); } return null; } private static ArpPacket getArpPkt(Packet pkt) { if (pkt.contains(ArpPacket.class)) { return pkt.get(ArpPacket.class); } try { Dot1qVlanTagPacket unwrapedFromVlanPkt = Dot1qVlanTagPacket.newPacket( pkt.getRawData(), pkt.getHeader().length(), pkt.getPayload().length()); return unwrapedFromVlanPkt.get(ArpPacket.class); } catch (IllegalRawDataException ignored) { } return null; } private static EthernetPacket buildArpPkt( String srcMac, String srcIp, String dstIp, PortVlan vlan) { ArpPacket.Builder arpBuilder = new ArpPacket.Builder(); MacAddress srcMacAddress = MacAddress.getByName(srcMac); try { arpBuilder .hardwareType(ArpHardwareType.ETHERNET) .protocolType(EtherType.IPV4) .hardwareAddrLength((byte) MacAddress.SIZE_IN_BYTES) .protocolAddrLength((byte) ByteArrays.INET4_ADDRESS_SIZE_IN_BYTES) .operation(ArpOperation.REQUEST) .srcHardwareAddr(srcMacAddress) .srcProtocolAddr(InetAddress.getByName(srcIp)) .dstHardwareAddr(MacAddress.getByName("00:00:00:00:00:00")) .dstProtocolAddr(InetAddress.getByName(dstIp)); } catch (UnknownHostException e) { throw new IllegalArgumentException(e); } AbstractMap.SimpleEntry<EtherType, Packet.Builder> payload = new AbstractMap.SimpleEntry<>(EtherType.ARP, arpBuilder); if (!vlan.getTags().isEmpty()) { payload = buildVlan(arpBuilder, vlan); } EthernetPacket.Builder etherBuilder = new EthernetPacket.Builder(); etherBuilder .dstAddr(MacAddress.ETHER_BROADCAST_ADDRESS) .srcAddr(srcMacAddress) .type(payload.getKey()) .payloadBuilder(payload.getValue()) .paddingAtBuild(true); return etherBuilder.build(); } private static AbstractMap.SimpleEntry<EtherType, Packet.Builder> buildVlan( ArpPacket.Builder arpBuilder, PortVlan vlan) { Queue<Integer> vlanTags = new LinkedList<>(Lists.reverse(vlan.getTags())); Packet.Builder resultPayloadBuilder = arpBuilder; EtherType resultEtherType = EtherType.ARP; if (vlanTags.peek() != null) { Dot1qVlanTagPacket.Builder vlanInsideBuilder = new Dot1qVlanTagPacket.Builder(); vlanInsideBuilder .type(EtherType.ARP) .vid(vlanTags.poll().shortValue()) .payloadBuilder(arpBuilder); resultPayloadBuilder = vlanInsideBuilder; resultEtherType = EtherType.DOT1Q_VLAN_TAGGED_FRAMES; if (vlanTags.peek() != null) { Dot1qVlanTagPacket.Builder vlanOutsideBuilder = new Dot1qVlanTagPacket.Builder(); vlanOutsideBuilder .type(EtherType.DOT1Q_VLAN_TAGGED_FRAMES) .vid(vlanTags.poll().shortValue()) .payloadBuilder(vlanInsideBuilder); resultPayloadBuilder = vlanOutsideBuilder; resultEtherType = QInQ; } } return new AbstractMap.SimpleEntry<>(resultEtherType, resultPayloadBuilder); } private static Stream build1PktSingleBurstStream(Packet pkt) { int streamId = (int) (Math.random() * 1000); return new Stream( streamId, true, 3, 0.0, new StreamMode( 2, 2, 1, 1.0, new StreamModeRate(StreamModeRate.Type.pps, 1.0), StreamMode.Type.single_burst), -1, pkt, new StreamRxStats(true, true, true, streamId), new StreamVM("", Collections.<VMInstruction>emptyList()), true, false, null, -1); } public String resolveIpv6(int portIndex, String dstIp) throws ServiceModeRequiredException { removeRxQueue(portIndex); setRxQueue(portIndex, 1000); EthernetPacket naPacket = new IPv6NeighborDiscoveryService(this).sendNeighborSolicitation(portIndex, 5, dstIp); if (naPacket != null) { return naPacket.getHeader().getSrcAddr().toString(); } return null; } public List<EthernetPacket> getRxQueue(int portIndex, Predicate<EthernetPacket> filter) { Map<String, Object> payload = createPayload(portIndex); String json = callMethod("get_rx_queue_pkts", payload); JsonArray pkts = getResultFromResponse(json).getAsJsonObject().getAsJsonArray("pkts"); return StreamSupport.stream(pkts.spliterator(), false) .map(this::buildEthernetPkt) .filter(filter) .collect(Collectors.toList()); } private EthernetPacket buildEthernetPkt(JsonElement jsonElement) { try { byte[] binary = Base64.getDecoder().decode(jsonElement.getAsJsonObject().get("binary").getAsString()); EthernetPacket pkt = EthernetPacket.newPacket(binary, 0, binary.length); LOGGER.info("Received pkt: {}", pkt.toString()); return pkt; } catch (IllegalRawDataException e) { return null; } } public boolean setL3Mode( int portIndex, String nextHopMac, String sourceIp, String destinationIp) { Map<String, Object> payload = createPayload(portIndex); payload.put("src_addr", sourceIp); payload.put("dst_addr", destinationIp); if (nextHopMac != null) { payload.put("resolved_mac", nextHopMac); } payload.put("block", false); callMethod("set_l3", payload); return true; } public void updatePortHandler(int portID, String handler) { portHandlers.put(portID, handler); } public void invalidatePortHandler(int portID) { portHandlers.remove(portID); } // TODO: move to upper layer public EthernetPacket sendIcmpEcho( int portIndex, String host, int reqId, int seqNumber, long waitResponse) throws UnknownHostException { Port port = getPortByIndex(portIndex); PortStatus portStatus = getPortStatus(portIndex).get(); String srcIp = portStatus.getAttr().getLayerConiguration().getL3Configuration().getSrc(); EthernetPacket icmpRequest = buildIcmpV4Request(port.hw_mac, port.dst_macaddr, srcIp, host, reqId, seqNumber); removeAllStreams(portIndex); setRxQueue(portIndex, 1000); sendPacket(portIndex, icmpRequest); try { Thread.sleep(waitResponse); } catch (InterruptedException ignored) { } try { List<EthernetPacket> receivedPkts = getRxQueue(portIndex, etherPkt -> etherPkt.contains(IcmpV4EchoReplyPacket.class)); if (!receivedPkts.isEmpty()) { return receivedPkts.get(0); } return null; } finally { removeRxQueue(portIndex); } } // TODO: move to upper layer private EthernetPacket buildIcmpV4Request( String srcMac, String dstMac, String srcIp, String dstIp, int reqId, int seqNumber) throws UnknownHostException { IcmpV4EchoPacket.Builder icmpReqBuilder = new IcmpV4EchoPacket.Builder(); icmpReqBuilder.identifier((short) reqId); icmpReqBuilder.sequenceNumber((short) seqNumber); IcmpV4CommonPacket.Builder icmpv4CommonPacketBuilder = new IcmpV4CommonPacket.Builder(); icmpv4CommonPacketBuilder .type(IcmpV4Type.ECHO) .code(IcmpV4Code.NO_CODE) .correctChecksumAtBuild(true) .payloadBuilder(icmpReqBuilder); IpV4Packet.Builder ipv4Builder = new IpV4Packet.Builder(); ipv4Builder .version(IpVersion.IPV4) .tos(IpV4Rfc791Tos.newInstance((byte) 0)) .ttl((byte) 64) .protocol(IpNumber.ICMPV4) .srcAddr((Inet4Address) Inet4Address.getByName(srcIp)) .dstAddr((Inet4Address) Inet4Address.getByName(dstIp)) .correctChecksumAtBuild(true) .correctLengthAtBuild(true) .payloadBuilder(icmpv4CommonPacketBuilder); EthernetPacket.Builder eb = new EthernetPacket.Builder(); eb.srcAddr(MacAddress.getByName(srcMac)) .dstAddr(MacAddress.getByName(dstMac)) .type(EtherType.IPV4) .paddingAtBuild(true) .payloadBuilder(ipv4Builder); return eb.build(); } public void stopTraffic(int portIndex) { stopTraffic(portIndex, ""); } public void stopTraffic(int portIndex, String profileId) { Map<String, Object> payload = createPayload(portIndex, profileId); callMethod("stop_traffic", payload); } public void stopAllTraffic(int portIndex) { List<String> profileIds = getProfileIds(portIndex); for (String profileId : profileIds) { stopTraffic(portIndex, profileId); } } public Map<String, Ipv6Node> scanIPv6(int portIndex) throws ServiceModeRequiredException { return new IPv6NeighborDiscoveryService(this).scan(portIndex, 10, null, null); } public EthernetPacket sendIcmpV6Echo( int portIndex, String dstIp, int icmpId, int icmpSeq, int timeOut) throws ServiceModeRequiredException { return new IPv6NeighborDiscoveryService(this) .sendIcmpV6Echo(portIndex, dstIp, icmpId, icmpSeq, timeOut); } }
package com.danubetech.libsovrin; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.CompletableFuture; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; public class SovrinJava { /* * API */ public static class API { protected static final int FIXED_COMMAND_HANDLE = 0; protected static boolean checkCallback(CompletableFuture<? extends SovrinJava.Result> future, int xcommand_handle, int err) { assert(xcommand_handle == FIXED_COMMAND_HANDLE); ErrorCode errorCode = ErrorCode.valueOf(err); if (! ErrorCode.Success.equals(errorCode)) { future.completeExceptionally(SovrinException.fromErrorCode(errorCode)); return false; } return true; } protected static void checkResult(int result) throws SovrinException { ErrorCode errorCode = ErrorCode.valueOf(result); if (! ErrorCode.Success.equals(errorCode)) throw SovrinException.fromErrorCode(errorCode); } } /* * JSON parameter */ public abstract static class JsonParameter { protected Map<String, Object> map = new HashMap<String, Object> (); public final String toJson() { StringBuilder builder = new StringBuilder(); builder.append("{"); for (Iterator<Map.Entry<String, Object>> iterator = this.map.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry<String, Object> entry = iterator.next(); String key = entry.getKey(); Object value = entry.getValue(); builder.append("\"" + key + "\":\""); builder.append(escapeJson(value.toString())); builder.append("\""); if (iterator.hasNext()) builder.append(","); } builder.append("}"); return builder.toString(); } private static String escapeJson(String string) { return string.replace("\\", "\\\\").replace("\"", "\\\""); } @Override public int hashCode() { return this.map.hashCode(); } @Override public boolean equals(Object other) { return this.map.equals(other); } @Override public String toString() { return this.toJson(); } } /* * Result */ public abstract static class Result { @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this, false); } @Override public boolean equals(Object other) { return EqualsBuilder.reflectionEquals(this, other, false); } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } } }