answer
stringlengths
17
10.2M
package mytown.core; import net.minecraft.util.EnumChatFormatting; import org.lwjgl.Sys; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.HashMap; import java.util.Map; /** * Loads and handles Localization files * * @author Joe Goett */ public class Localization { /** * The localization map */ Map<String, String> localizations; public Map<Character, String> colorMap; Reader reader = null; /** * Specifies the {@link Reader} to use when reading the localization * * @param r */ public Localization(Reader r) { reader = r; localizations = new HashMap<String, String>(); colorMap = new HashMap<Character, String>(); colorMap.put('0', "BLACK"); colorMap.put('1', "DARK_BLUE"); colorMap.put('2', "DARK_GREEN"); colorMap.put('3', "DARK_AQUA"); colorMap.put('4', "DARK_RED"); colorMap.put('5', "DARK_PURPLE"); colorMap.put('6', "GOLD"); colorMap.put('7', "GRAY"); colorMap.put('8', "DARK_GRAY"); colorMap.put('9', "BLUE"); colorMap.put('a', "GREEN"); colorMap.put('b', "AQUA"); colorMap.put('c', "RED"); colorMap.put('d', "LIGHT_PURPLE"); colorMap.put('e', "YELLOW"); colorMap.put('f', "WHITE"); } /** * Specifies the file to load via a {@link File} * * @param file * @throws FileNotFoundException */ public Localization(File file) throws FileNotFoundException { this(new FileReader(file)); } /** * Specifies the file to load via a filename * * @param filename * @throws FileNotFoundException */ public Localization(String filename) throws FileNotFoundException { this(new File(filename)); } /** * Do the actual loading of the Localization file * * @throws IOException */ public void load() throws IOException { BufferedReader br = new BufferedReader(reader); String line; while ((line = br.readLine()) != null) { line = line.trim(); // Trim it in-case there is spaces before the actual key-value pairs if (line.startsWith("#") || line.isEmpty()) { continue; // Ignore comments and empty lines } String[] entry = line.split("="); if (entry.length < 2) { continue; // Ignore entries that are not formatted correctly (maybe log later) } localizations.put(entry[0].trim(), entry[1].trim()); } br.close(); } private String getLocalizationFromKey(String key) { String localized = localizations.get(key); if(localized != null) { for(int i = 0; i < localized.length(); i++) { if(localized.charAt(i) == '&') { if(EnumChatFormatting.valueOf(colorMap.get(localized.charAt(i+1))) != null) { localized = localized.substring(0, i) + EnumChatFormatting.valueOf(colorMap.get(localized.charAt(i + 1))) + localized.substring(i + 2); } else { localized = localized.substring(0, i) + localized.substring(i+2); } } } } return localized == null ? key : localized; } /** * Returns the localized version of the given unlocalized key * * @param key * @param args * @return */ public String getLocalization(String key, Object... args) { if (args.length > 0) { return String.format(getLocalizationFromKey(key), args); } else return getLocalizationFromKey(key); } public Map<String, String> getLocalizationMap() { return localizations; } }
package net.pla1.tweettooter; import org.sikuli.basics.Settings; import org.sikuli.script.*; import java.io.FileInputStream; import java.io.IOException; import java.util.Date; import java.util.Properties; public class Bot { private final String URL_MASTODON = "https://octodon.social/auth/sign_in"; private final String URL_TWITTER = "https://twitter.com/search?f=tweets&vertical=default&q=chswx&src=typd"; public static void main(String[] args) throws Exception { System.out.format("%s", new Date()); Bot bot = new Bot(); try { bot.startBrowser(); bot.monitorForNewResults(); } catch (FindFailed findFailed) { findFailed.printStackTrace(); } System.out.format("Done. %s\n", new Date()); System.exit(0); } private void loginToTwitter() throws FindFailed, IOException { Properties properties = new Properties(); properties.load(new FileInputStream(Utils.PROPERTY_FILE_NAME)); Screen s = new Screen(); Utils.sleep(5); s.click("images/login.png"); s.click("images/username_field.png"); s.type(properties.getProperty(Utils.PROPERTY_TWITTER_USER_NAME)); s.click("images/password_field.png"); s.type(properties.getProperty(Utils.PROPERTY_TWITTER_PASSWORD)); s.type(Key.TAB); Settings.MinSimilarity = 0.9; s.click("images/login_button_authenticate.png"); s.click("images/search_twitter_field.png"); s.type("chswx"); s.type(Key.ENTER); s.click("images/latest_label.png"); } private void startBrowser() throws FindFailed, IOException { Screen s = new Screen(); System.out.println(Utils.run(new String[]{"/usr/bin/killall", "chromium-browser"})); Utils.runNoOutput(new String[]{"/usr/bin/chromium-browser", "--incognito", URL_TWITTER}); Utils.waitForImage(s, "images/latest_label.png", 10); s.type(Key.ESC); s.type("t", KeyModifier.CTRL); s.type(URL_MASTODON); s.type(Key.ENTER); Utils.waitForImage(s, "images/mastodon_logo.png", 10); Properties properties = new Properties(); properties.load(new FileInputStream(Utils.PROPERTY_FILE_NAME)); s.type(properties.getProperty(Utils.PROPERTY_MASTODON_EMAIL_ADDRESS)); s.type(Key.TAB); s.type(properties.getProperty(Utils.PROPERTY_MASTODON_PASSWORD)); s.type(Key.ENTER); s.type(Key.TAB, KeyModifier.CTRL); } private Region getRegionToMonitorForNewResults() throws FindFailed { Screen s = new Screen(); Utils.waitForImage(s, "images/twitter_banner.png", 60); Match match = s.find("images/twitter_banner.png"); System.out.format("Found Twitter banner - X:%d Y:%d H:%d W:%d\n", match.x, match.y, match.h, match.w); Region region = new Region(match.x + match.w - 200, match.y, 400, 120); String screenCaptureFileName = region.saveScreenCapture(); System.out.format("Screen capture file name for region to monitor is: %s.\nRegion: %s\n",screenCaptureFileName, region.toString()); return region; } private void monitorForNewResults() throws FindFailed { Screen s = new Screen(); Region regionToMonitor = getRegionToMonitorForNewResults(); while (true) { System.out.format("Wait for new result. %s\n", new Date()); regionToMonitor.wait("images/new_result_label.png", Settings.FOREVER); System.out.println("Type period"); s.type("."); System.out.println("Sleep 3 seconds."); Utils.sleep(3); System.out.println("Press ENTER."); s.type(Key.ENTER); Utils.sleep(5); s.type(Key.TAB); s.type(Key.TAB); s.type(Key.TAB); s.type(Key.SPACE); System.out.println("Click copy link to tweet."); s.type(Key.DOWN); s.type(Key.ENTER); Utils.waitForImage(s, "images/url_for_this_tweet.png", 10); System.out.println("Ctrl-c"); s.type("c", KeyModifier.CTRL); String clipboardContents = Utils.getClipboard(); System.out.format("Clipboard contents: %s\n", clipboardContents); s.type(Key.ESC); Utils.sleep(2); Match topLeftCornerMatch = s.find("images/top_left_corner.png"); System.out.format("Top left corner at H: %s W: %d X: %d Y: %d\n", topLeftCornerMatch.h, topLeftCornerMatch.w, topLeftCornerMatch.x, topLeftCornerMatch.y); Match bottomRightCornerMatch = s.find("images/bottom_right_corner.png"); System.out.format("Bottom right corner at H: %s W: %d X: %d Y: %d\n", bottomRightCornerMatch.h, bottomRightCornerMatch.w, bottomRightCornerMatch.x, bottomRightCornerMatch.y); Region region = new Region( topLeftCornerMatch.x, topLeftCornerMatch.y, (bottomRightCornerMatch.x - topLeftCornerMatch.x) + bottomRightCornerMatch.w, bottomRightCornerMatch.y - topLeftCornerMatch.y); System.out.format("Region X:%d Y:%d W:%d H:%d.\n", region.x, region.y, region.w, region.h); String fileName = region.saveScreenCapture(); String copiedFile = Utils.copyFile(fileName); System.out.format("Image captured as %s and a copy %s.\n", fileName, copiedFile); s.type(Key.ESC); s.type(Key.TAB, KeyModifier.CTRL); if (Utils.isNotBlank(fileName) && Utils.isNotBlank(clipboardContents) && region.w > 200) { Utils.waitForImage(s,"images/mastodon_media_button.png",10); s.click("images/mastodon_media_button.png"); s.click("images/file_system_label.png"); s.type(fileName); s.type(Key.ENTER); Utils.sleep(3); s.type(clipboardContents); s.type(" #chswx "); s.click("images/toot_button.png"); } else { System.out.format("Requirements for a successful post were not met.\n\tScreenshot file name: %s\n\tClipboard contents: \"%s\"\n\tRegion width: %d\n", fileName, clipboardContents, region.w); } Utils.sleep(2); s.type(Key.TAB, KeyModifier.CTRL); } } }
package ninja.joshdavis; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.File; import java.io.IOException; import java.util.LinkedHashMap; import java.util.Map.Entry; /** * Main window manager * */ public class AppFrame extends JFrame { private FileListPane srcFileListPane; private FileListPane destFileListPane; private Editor editor; private TextField searchInput; private TextField replaceInput; private JButton dirBrowseButton; private JFileChooser dirChooser; private TextField dirInput; private File currentDir; private JCheckBox showHidden; private JCheckBox globalSearch; private JCheckBox caseInsensitiveSearch; private JCheckBox regexSearch; private JButton alterFiles; private LinkedHashMap<File,File> renameMap; private class InputListener implements ActionListener { public void actionPerformed(ActionEvent ev) { updateEditor(); updateFilePanes(); } } private class AlterFilesListener implements ActionListener { public void actionPerformed(ActionEvent ev) { int confirmOption = JOptionPane.showConfirmDialog(null, "Confirm file modifications?", "Are you sure?", JOptionPane.OK_CANCEL_OPTION); if(confirmOption == JOptionPane.OK_OPTION) { for(Entry<File,File> entry: renameMap.entrySet()) { entry.getKey().renameTo(entry.getValue()); } searchInput.setText(""); replaceInput.setText(""); updateEditor(); updateFilePanes(); } } } private class DirChooserListener implements ActionListener { public void actionPerformed(ActionEvent ev) { dirChooser.setFileHidingEnabled(!showHidden.isSelected()); dirChooser.showDialog(AppFrame.this, null); File file = dirChooser.getSelectedFile(); setCurrentDir(file); } } private class DirInputListener implements ActionListener { public void actionPerformed(ActionEvent ev) { File file = new File(dirInput.getText()); setCurrentDir(file); } } private void setCurrentDir(File file) { if(file != null && file.exists() && file.isDirectory()) { currentDir = file; dirInput.setText(file.getAbsolutePath()); updateFilePanes(); } else { JOptionPane.showMessageDialog(null, file.getAbsolutePath()+ " is not a valid directory.", "File error", JOptionPane.ERROR_MESSAGE); dirInput.setText(currentDir.getAbsolutePath()); } } private void updateEditor() { String searchInputString = searchInput.getText(); String replaceInputString = replaceInput.getText(); //TODO: sanitize inputs editor.setSearchString(searchInputString); editor.setReplaceString(replaceInputString); editor.setGlobalSearch(globalSearch.isSelected()); editor.setCaseInsensitiveSearch(caseInsensitiveSearch.isSelected()); editor.setLiteralSearch(!regexSearch.isSelected()); } private void updateRenameMap() { renameMap.clear(); File[] allFiles = currentDir.listFiles(); for(File srcFile: allFiles) { if( !srcFile.isHidden() || showHidden.isSelected() ) { String destName = editor.edit(srcFile.getName()); if(destName != null && !destName.isEmpty()) { File destFile = new File(currentDir,destName); renameMap.put(srcFile,destFile); } } } } private void updateFilePanes() { updateRenameMap(); String srcText = ""; String destText = ""; for(Entry<File,File> entry: renameMap.entrySet()) { srcText = srcText + entry.getKey().getName() + "\n"; destText = destText + entry.getValue().getName() + "\n"; } srcFileListPane.setText(srcText); destFileListPane.setText(destText); } public AppFrame() { super("Remoniker"); setLayout(new FlowLayout()); /* File panes */ srcFileListPane = new FileListPane(); addWithTitledBorder(srcFileListPane, "Files"); destFileListPane = new FileListPane(); addWithTitledBorder(destFileListPane, "Preview"); /* Editor */ editor = new Editor(); /* Directory pane */ JPanel dirPane = new JPanel(); dirPane.setBorder(BorderFactory.createTitledBorder("Current directory")); add(dirPane); dirInput = new TextField(20); dirPane.add(dirInput); ActionListener dirInputListener = new DirInputListener(); dirInput.addActionListener(dirInputListener); dirChooser = new JFileChooser(); dirChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); ActionListener dirChooserListener = new DirChooserListener(); dirBrowseButton = new JButton("Browse"); dirBrowseButton.addActionListener(dirChooserListener); dirPane.add(dirBrowseButton); /* Search & replace fields */ ActionListener inputListener = new InputListener(); searchInput = addNewTextField("Search", inputListener); replaceInput = addNewTextField("Replace", inputListener); /* Options */ showHidden = new JCheckBox("Show hidden files"); showHidden.addActionListener(inputListener); add(showHidden); globalSearch = new JCheckBox("Global search"); globalSearch.addActionListener(inputListener); add(globalSearch); caseInsensitiveSearch = new JCheckBox("Case insensitive"); caseInsensitiveSearch.addActionListener(inputListener); add(caseInsensitiveSearch); regexSearch = new JCheckBox("Use regular expressions"); regexSearch.addActionListener(inputListener); add(regexSearch); /* Rename action button */ alterFiles = new JButton("Rename files"); add(alterFiles); ActionListener alterFilesListener = new AlterFilesListener(); alterFiles.addActionListener(alterFilesListener); // Init rename map renameMap = new LinkedHashMap<File,File>(); // Set initial directory setCurrentDir(new File(System.getProperty("user.home"))); } private void addWithTitledBorder(Component comp, String title) { JPanel pane = new JPanel(); pane.setBorder(BorderFactory.createTitledBorder(title)); pane.add(comp); add(pane); } private TextField addNewTextField(String title, ActionListener listener) { TextField res = new TextField(20); res.addActionListener(listener); addWithTitledBorder(res,title); return res; } }
package openmods.block; import java.util.ArrayList; import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import openmods.Log; import openmods.api.*; import openmods.config.IRegisterableBlock; import openmods.sync.SyncableDirection; import openmods.tileentity.OpenTileEntity; import openmods.tileentity.SyncedTileEntity; import openmods.utils.BlockNotifyFlags; import openmods.utils.BlockUtils; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public abstract class OpenBlock extends Block implements IRegisterableBlock { private static final String SYNCED_ROTATION_VAR = "_rotation2"; public static final int OPEN_MODS_TE_GUI = -1; /*** * The block rotation mode. Defines how many levels of rotation * a block can have */ public enum BlockRotationMode { NONE(), FOUR_DIRECTIONS(ForgeDirection.UP, ForgeDirection.DOWN), SIX_DIRECTIONS(ForgeDirection.VALID_DIRECTIONS), TWENTYFOUR_DIRECTIONS(ForgeDirection.VALID_DIRECTIONS); private BlockRotationMode(ForgeDirection... rotations) { this.rotations = rotations; } private final ForgeDirection[] rotations; } /*** * The block placement mode. Does it rotate based on the surface * it's placed on, or the */ public enum BlockPlacementMode { ENTITY_ANGLE, SURFACE } private String blockName; private String modId; /** * The tile entity class associated with this block */ private Class<? extends TileEntity> teClass = null; protected BlockRotationMode blockRotationMode; protected BlockPlacementMode blockPlacementMode; protected ForgeDirection inventoryRenderRotation = ForgeDirection.WEST; public IIcon[] textures = new IIcon[6]; protected OpenBlock(Material material) { super(material); setHardness(1.0F); setRotationMode(BlockRotationMode.NONE); setPlacementMode(BlockPlacementMode.ENTITY_ANGLE); // I dont think vanilla actually uses this.. isBlockContainer = false; } protected void setPlacementMode(BlockPlacementMode mode) { this.blockPlacementMode = mode; } protected void setRotationMode(BlockRotationMode mode) { this.blockRotationMode = mode; } public BlockRotationMode getRotationMode() { return this.blockRotationMode; } protected BlockPlacementMode getPlacementMode() { return this.blockPlacementMode; } protected void setInventoryRenderRotation(ForgeDirection rotation) { inventoryRenderRotation = rotation; } @SideOnly(Side.CLIENT) public ForgeDirection getInventoryRenderRotation() { return inventoryRenderRotation; } /** * Set block bounds based on rotation * * @param direction * direction to apply bounds to */ public void setBoundsBasedOnRotation(ForgeDirection direction) { } /** * Helper function to get the OpenBlock class for a block in the world * * @param world * world to get the block from * @param x * X coord * @param y * Y coord * @param z * Z coord * @return OpenBlock instance of the block, or null if invalid */ public static OpenBlock getOpenBlock(IBlockAccess world, int x, int y, int z) { if (world == null) return null; Block block = world.getBlock(x, y, z); if (block instanceof OpenBlock) return (OpenBlock)block; return null; } @Override public TileEntity createTileEntity(World world, int metadata) { final TileEntity te = createTileEntity(); te.blockType = this; if (te instanceof OpenTileEntity) { ((OpenTileEntity)te).setup(); } return te; } public TileEntity createTileEntityForRender() { final TileEntity te = createTileEntity(); te.blockType = this; te.blockMetadata = 0; return te; } protected TileEntity createTileEntity() { try { if (teClass != null) return teClass.getConstructor(new Class[0]).newInstance(); } catch (NoSuchMethodException nsm) { Log.warn(nsm, "Notice: Cannot create TE automatically due to constructor requirements"); } catch (Exception ex) { Log.warn(ex, "Notice: Error creating tile entity"); } return null; } public Class<? extends TileEntity> getTileClass() { return teClass; } @SideOnly(Side.CLIENT) @Override public void registerBlockIcons(IIconRegister registry) { this.blockIcon = registry.registerIcon(String.format("%s:%s", modId, blockName)); } @Override public void breakBlock(World world, int x, int y, int z, Block par5, int par6) { final TileEntity te = world.getTileEntity(x, y, z); if (te instanceof IBreakAwareTile) ((IBreakAwareTile)te).onBlockBroken(); world.removeTileEntity(x, y, z); super.breakBlock(world, x, y, z, par5, par6); } private void getTileEntityDrops(TileEntity te, List<ItemStack> result) { if (te != null) { BlockUtils.getTileInventoryDrops(te, result); if (te instanceof ISpecialDrops) ((ISpecialDrops)te).addDrops(result); getCustomTileEntityDrops(te, result); } } protected void getCustomTileEntityDrops(TileEntity te, List<ItemStack> result) {} protected boolean hasNormalDrops() { return true; } protected boolean hasTileEntityDrops() { return true; } @Override public boolean removedByPlayer(World world, EntityPlayer player, int x, int y, int z) { // This is last place we have TE, before it's removed, // When removed by player, it will be already unavailable in // getBlockDropped if (hasTileEntityDrops() && !player.capabilities.isCreativeMode) { final TileEntity te = world.getTileEntity(x, y, z); List<ItemStack> teDrops = Lists.newArrayList(); getTileEntityDrops(te, teDrops); for (ItemStack drop : teDrops) dropBlockAsItem(world, x, y, z, drop); } return super.removedByPlayer(world, player, x, y, z); } @Override public ArrayList<ItemStack> getDrops(World world, int x, int y, int z, int metadata, int fortune) { ArrayList<ItemStack> result = Lists.newArrayList(); if (hasNormalDrops()) result.addAll(super.getDrops(world, x, y, z, metadata, fortune)); if (hasTileEntityDrops()) { final TileEntity te = world.getTileEntity(x, y, z); getTileEntityDrops(te, result); } return result; } @Override public void setupBlock(String modId, String blockName, Class<? extends TileEntity> tileEntity, Class<? extends ItemBlock> itemClass) { this.blockName = blockName; this.modId = modId; if (tileEntity != null) { this.teClass = tileEntity; isBlockContainer = true; if (blockRotationMode == BlockRotationMode.TWENTYFOUR_DIRECTIONS) { Preconditions.checkArgument(SyncedTileEntity.class.isAssignableFrom(tileEntity), "To use 24-direction rotations TE class '%s' needs to implement SyncedTileEntity", tileEntity); } } } @Override public boolean hasTileEntity(int metadata) { return teClass != null; } public final static boolean isNeighborBlockSolid(IBlockAccess world, int x, int y, int z, ForgeDirection side) { x += side.offsetX; y += side.offsetY; z += side.offsetZ; //TODO: issBlockSolid?? (check when possible) return world.isSideSolid(x, y, z, side.getOpposite(), false); } public final static boolean areNeighborBlocksSolid(World world, int x, int y, int z, ForgeDirection... sides) { for (ForgeDirection side : sides) { if (isNeighborBlockSolid(world, x, y, z, side)) { return true; } } return false; } @Override public void onNeighborBlockChange(World world, int x, int y, int z, Block neighbour) { TileEntity te = world.getTileEntity(x, y, z); if (te instanceof INeighbourAwareTile) ((INeighbourAwareTile)te).onNeighbourChanged(); if (te instanceof ISurfaceAttachment) { ForgeDirection direction = ((ISurfaceAttachment)te).getSurfaceDirection(); if (!isNeighborBlockSolid(world, x, y, z, direction)) { world.func_147480_a(x, y, z, true); } } } @Override public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ) { TileEntity te = world.getTileEntity(x, y, z); if (te instanceof IHasGui && ((IHasGui)te).canOpenGui(player) && !player.isSneaking()) { if (!world.isRemote) openGui(player, world, x, y, z); return true; } if (te instanceof IActivateAwareTile) return ((IActivateAwareTile)te).onBlockActivated(player, side, hitX, hitY, hitZ); return false; } @Override public boolean renderAsNormalBlock() { return isOpaqueCube(); } @Override public boolean onBlockEventReceived(World world, int x, int y, int z, int eventId, int eventParam) { super.onBlockEventReceived(world, x, y, z, eventId, eventParam); TileEntity te = getTileEntity(world, x, y, z, TileEntity.class); if (te != null) { return te.receiveClientEvent(eventId, eventParam); } return false; } protected void setupDimensionsFromCenter(float x, float y, float z, float width, float height, float depth) { setupDimensions(x - width, y, z - depth, x + width, y + height, z + depth); } protected void setupDimensions(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { this.minX = minX; this.minY = minY; this.minZ = minZ; this.maxX = maxX; this.maxY = maxY; this.maxZ = maxZ; } @Override public AxisAlignedBB getSelectedBoundingBoxFromPool(World world, int x, int y, int z) { setBlockBoundsBasedOnState(world, x, y, z); return super.getSelectedBoundingBoxFromPool(world, x, y, z); } @Override public AxisAlignedBB getCollisionBoundingBoxFromPool(World world, int x, int y, int z) { setBlockBoundsBasedOnState(world, x, y, z); return super.getCollisionBoundingBoxFromPool(world, x, y, z); } @SuppressWarnings("unchecked") public static <U> U getTileEntity(IBlockAccess world, int x, int y, int z, Class<U> T) { TileEntity te = world.getTileEntity(x, y, z); if (te != null && T.isAssignableFrom(te.getClass())) { return (U)te; } return null; } /*** * An extended block placement function which includes ALL the details * you'll ever need. * This is called if your ItemBlock extends ItemOpenBlock */ public void onBlockPlacedBy(World world, EntityPlayer player, ItemStack stack, int x, int y, int z, ForgeDirection side, float hitX, float hitY, float hitZ, int meta) { ForgeDirection additionalRotation = null; // We use both for 24's, so force to angle if (getRotationMode() == BlockRotationMode.TWENTYFOUR_DIRECTIONS) { setPlacementMode(BlockPlacementMode.ENTITY_ANGLE); } switch (this.blockPlacementMode) { case SURFACE: meta = side.getOpposite().ordinal(); break; default: switch (getRotationMode()) { case FOUR_DIRECTIONS: meta = BlockUtils.get2dOrientation(player).ordinal(); break; case SIX_DIRECTIONS: meta = BlockUtils.get3dOrientation(player).ordinal(); break; case TWENTYFOUR_DIRECTIONS: meta = side.getOpposite().ordinal(); additionalRotation = BlockUtils.get2dOrientation(player); break; default: break; } } world.setBlockMetadataWithNotify(x, y, z, meta, BlockNotifyFlags.ALL); TileEntity te = world.getTileEntity(x, y, z); if (additionalRotation != null) { Preconditions.checkState(te instanceof SyncedTileEntity, "For 6+ levels of rotation you need to use a SyncedTileEntity, but '%s' on block '%s' is not one", te, this); SyncedTileEntity ste = (SyncedTileEntity)te; ste.addSyncedObject(SYNCED_ROTATION_VAR, new SyncableDirection(additionalRotation)); ste.sync(); } if (te instanceof IPlaceAwareTile) ((IPlaceAwareTile)te).onBlockPlacedBy(player, side, stack, hitX, hitY, hitZ); } @Override public final boolean canPlaceBlockOnSide(World world, int x, int y, int z, int side) { return canPlaceBlockOnSide(world, x, y, z, ForgeDirection.getOrientation(side).getOpposite()); } /*** * * @param world * @param x * @param y * @param z * @param side * @return */ public boolean canPlaceBlockOnSide(World world, int x, int y, int z, ForgeDirection side) { return canPlaceBlockAt(world, x, y, z); // default to vanilla rules } protected boolean isOnTopOfSolidBlock(World world, int x, int y, int z, ForgeDirection side) { return side == ForgeDirection.DOWN && isNeighborBlockSolid(world, x, y, z, ForgeDirection.DOWN); } public void setTexture(ForgeDirection direction, IIcon icon) { textures[direction.ordinal()] = icon; } protected final IIcon getUnrotatedTexture(ForgeDirection direction) { if (direction != ForgeDirection.UNKNOWN) { final int directionId = direction.ordinal(); if (textures[directionId] != null) return textures[directionId]; } return blockIcon; } /** * This method should be overriden if needed. We're getting the texture for * the UNROTATED block for a particular side (direction). Feel free to look * up data in the TileEntity to grab additional information here */ public IIcon getUnrotatedTexture(ForgeDirection direction, IBlockAccess world, int x, int y, int z) { return getUnrotatedTexture(direction); } /** * Get the texture, but rotate the block around the metadata rotation first */ @Override @SideOnly(Side.CLIENT) public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) { ForgeDirection direction = rotateSideByMetadata(side, world.getBlockMetadata(x, y, z)); IIconProvider provider = getTileEntity(world, x, y, z, IIconProvider.class); IIcon teIcon = null; if (provider != null) teIcon = provider.getIcon(direction); return teIcon != null? teIcon : getUnrotatedTexture(direction, world, x, y, z); } /*** * This is called by the blockrenderer when rendering an item into the * inventory. * We'll return the block, rotated as we wish, but without any additional * texture * changes that are caused by the blocks current state */ @Override @SideOnly(Side.CLIENT) public IIcon getIcon(int side, int metadata) { ForgeDirection newRotation = rotateSideByMetadata(side, metadata); return getUnrotatedTexture(newRotation); } /*** * I'm sure there's a better way of doing this, but the idea is that we * rotate the block based on the metadata (rotation), so when we try to get * a texture we're referencing the side when 'unrotated' */ public ForgeDirection rotateSideByMetadata(int side, int metadata) { ForgeDirection rotation = ForgeDirection.getOrientation(metadata); ForgeDirection dir = ForgeDirection.getOrientation(side); switch (getRotationMode()) { case FOUR_DIRECTIONS: case NONE: switch (rotation) { case EAST: dir = dir.getRotation(ForgeDirection.DOWN); break; case SOUTH: dir = dir.getRotation(ForgeDirection.UP); dir = dir.getRotation(ForgeDirection.UP); break; case WEST: dir = dir.getRotation(ForgeDirection.UP); break; default: break; } return dir; default: switch (rotation) { case DOWN: dir = dir.getRotation(ForgeDirection.SOUTH); dir = dir.getRotation(ForgeDirection.SOUTH); break; case EAST: dir = dir.getRotation(ForgeDirection.NORTH); break; case NORTH: dir = dir.getRotation(ForgeDirection.WEST); break; case SOUTH: dir = dir.getRotation(ForgeDirection.EAST); break; case WEST: dir = dir.getRotation(ForgeDirection.SOUTH); break; default: break; } } return dir; } public void setDefaultTexture(IIcon icon) { this.blockIcon = icon; } public abstract boolean shouldRenderBlock(); protected abstract Object getModInstance(); public void openGui(EntityPlayer player, World world, int x, int y, int z) { player.openGui(getModInstance(), OPEN_MODS_TE_GUI, world, x, y, z); } public boolean useTESRForInventory() { return true; } public boolean canRotateWithTool() { return true; } @Override public boolean rotateBlock(World worldObj, int x, int y, int z, ForgeDirection axis) { return canRotateWithTool() && RotationHelper.rotateBlock(this, worldObj, x, y, z, axis); } @Override public ForgeDirection[] getValidRotations(World worldObj, int x, int y, int z) { if (!canRotateWithTool()) return BlockRotationMode.NONE.rotations; return blockRotationMode.rotations; } }
package org.jtrfp.trcl; import java.awt.geom.Point2D; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Collection; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.jtrfp.trcl.beh.NAVTargetableBehavior; import org.jtrfp.trcl.core.TR; import org.jtrfp.trcl.game.Game; import org.jtrfp.trcl.game.TVF3Game; import org.jtrfp.trcl.gui.DashboardLayout; import org.jtrfp.trcl.miss.Mission; import org.jtrfp.trcl.miss.NAVObjective; import org.jtrfp.trcl.obj.MiniMap; import org.jtrfp.trcl.obj.NAVRadarBlipFactory; import org.jtrfp.trcl.obj.NavArrow; import org.jtrfp.trcl.obj.WorldObject; import org.jtrfp.trcl.obj.WorldObject.RenderFlags; public class NAVSystem extends RenderableSpacePartitioningGrid { private final NavArrow arrow; private final MiniMap miniMap; private final TR tr; private NAVRadarBlipFactory blips; private final DashboardLayout layout; public NAVSystem(TR tr, DashboardLayout layout) { super(); this.tr=tr; this.layout=layout; System.out.println("Setting up NAV system..."); arrow = new NavArrow(tr,layout, new Point2D.Double(.16,.16), "NAVSystem.arrow"); miniMap = new MiniMap(tr); miniMap.setPosition(0,0,.00001); miniMap.setImmuneToOpaqueDepthTest(true); miniMap.setRenderFlag(RenderFlags.IgnoreCamera); miniMap.setActive(true); miniMap.setVisible(true); tr.addPropertyChangeListener(TR.RUN_STATE, new RunStateListener()); final double mmRadius = layout.getMiniMapRadius(); miniMap.setModelSize(new double[]{mmRadius,mmRadius}); final Point2D.Double pos = layout.getMiniMapPosition(); final double [] aPos = arrow.getPosition(); aPos[0]=pos.getX(); aPos[1]=pos.getY(); aPos[2]=.00001; System.arraycopy(aPos, 0, miniMap.getPosition(), 0, 3); miniMap.getPosition()[2]=.001; miniMap.notifyPositionChange(); miniMap.setMapPositionFromTile(0, 0); arrow.notifyPositionChange(); arrow.setRenderFlag(RenderFlags.IgnoreCamera); add(arrow); add(miniMap); final Point2D.Double mmPos = layout.getMiniMapPosition(); getBlips().setPositionOrigin(new Vector3D(mmPos.getX(), mmPos.getY(), 0.)); System.out.println("...Done."); }//end constructor private class RunStateListener implements PropertyChangeListener{ @Override public void propertyChange(PropertyChangeEvent evt) { final Object runState = evt.getNewValue(); final MiniMap miniMap = getMiniMap(); if(runState instanceof Mission.OverworldState){ miniMap.setTextureMesh(tr.getGame().getCurrentMission().getOverworldSystem().getTextureMesh()); miniMap.setVisible(true); }else { miniMap.setVisible(false); miniMap.setTextureMesh(null); } }//end propertyChange(...) }//end RunStateListener public void updateNAVState(){ final Game game = tr.getGame(); if(game==null)return; final Mission mission = game.getCurrentMission(); if(mission==null)return; final NAVObjective obj = mission.currentNAVObjective(); if(obj==null)return; ((TVF3Game)tr.getGame()).getHUDSystem(). getObjective(). setContent(layout.getHumanReadableObjective(obj)); final WorldObject target = obj.getTarget(); if(target!=null) target.probeForBehaviors(ntbSubmitter, NAVTargetableBehavior.class); }//end updateNAVState() private final Submitter<NAVTargetableBehavior> ntbSubmitter = new Submitter<NAVTargetableBehavior>(){ @Override public void submit(NAVTargetableBehavior item) { item.notifyBecomingCurrentTarget(); } @Override public void submit(Collection<NAVTargetableBehavior> items) { for(NAVTargetableBehavior i:items){this.submit(i);} } };//end ntbSubmitter /** * @return the blips */ public NAVRadarBlipFactory getBlips() { if(blips == null) blips = generateBlips(); return blips; }//end getBlips() protected NAVRadarBlipFactory generateBlips(){ return new NAVRadarBlipFactory(tr,this,"NAVSystem.blips", true); }//end generateBlips() public double[] getHeadingXY() { return arrow.getTopArray(); } public void activate(){ //tr.getDefaultGrid().addBranch(this); updateNAVState(); } public MiniMap getMiniMap() { return miniMap; } }//end NAVSystem
/* * This is free and unencumbered software released into the public domain. */ package org.rolesample; /** * ... * * @author Shawn McKinney * @version $Rev$ */ public class GlobalIds { public static final String BOTH_USER = "johndoe"; public static final String SELLER_USER = "rtaylor"; public static final String BUYER_USER = "ssmith"; public static final String USER_ID = "userId"; public static final String PSWD_FIELD = "pswdField"; public static final String LOGIN = "login"; public static final String PAGE_BUYERS = "BuyersPage"; public static final String PAGE_BUYERS_LINK = "Buyers Page"; public static final String PAGE_SELLERS = "SellersPage"; public static final String PAGE_SELLERS_LINK = "Sellers Page"; public static final String BTN_ITEM_SEARCH = "item.search"; public static final String BTN_ITEM_BID = "item.bid"; public static final String BTN_ITEM_BUY = "item.buy"; public static final String BTN_ITEM_SHIP = "item.ship"; public static final String BTN_ACCOUNT_CREATE = "account.create"; public static final String BTN_AUCTION_CREATE = "auction.create"; public static final String BTN_SWITCH_BUYER = "roles.switch.buyer"; public static final String BTN_SWITCH_SELLER = "roles.switch.seller"; public static final String LOGOUT = "logout"; public static final String INFO_FIELD = "infoField"; }
package org.scm4j.vcs.svn; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.scm4j.vcs.api.*; import org.scm4j.vcs.api.exceptions.EVCSBranchExists; import org.scm4j.vcs.api.exceptions.EVCSException; import org.scm4j.vcs.api.exceptions.EVCSFileNotFound; import org.scm4j.vcs.api.exceptions.EVCSTagExists; import org.scm4j.vcs.api.workingcopy.IVCSLockedWorkingCopy; import org.scm4j.vcs.api.workingcopy.IVCSRepositoryWorkspace; import org.scm4j.vcs.api.workingcopy.IVCSWorkspace; import org.tmatesoft.svn.core.*; import org.tmatesoft.svn.core.auth.BasicAuthenticationManager; import org.tmatesoft.svn.core.auth.SVNAuthentication; import org.tmatesoft.svn.core.auth.SVNPasswordAuthentication; import org.tmatesoft.svn.core.internal.wc.DefaultSVNOptions; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.core.io.SVNRepositoryFactory; import org.tmatesoft.svn.core.wc.*; import org.tmatesoft.svn.core.wc2.*; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileWriter; import java.nio.charset.StandardCharsets; import java.util.*; public class SVNVCS implements IVCS { private static final int SVN_PATH_IS_NOT_WORKING_COPY_ERROR_CODE = 155007; private static final int SVN_ITEM_EXISTS_ERROR_CODE = 160020; private static final int SVN_FILE_NOT_FOUND_ERROR_CODE = 160013; private BasicAuthenticationManager authManager; private SVNRepository repository; private ISVNOptions options; private SVNClientManager clientManager; private SVNURL trunkSVNUrl; private SVNAuthentication userPassAuth; private final IVCSRepositoryWorkspace repo; private String repoUrl; public static final String MASTER_PATH= "trunk/"; public static final String BRANCHES_PATH = "branches/"; public static final String TAGS_PATH = "tags/"; public static final String SVN_VCS_TYPE_STRING = "svn"; public void setClientManager(SVNClientManager clientManager) { this.clientManager = clientManager; } public SVNClientManager getClientManager() { return clientManager; } public ISVNOptions getOptions() { return options; } public SVNURL getTrunkSVNUrl() { return trunkSVNUrl; } public SVNRepository getSVNRepository() { return repository; } public void setSVNRepository(SVNRepository repository) { this.repository = repository; } public SVNVCS(IVCSRepositoryWorkspace repo, String user, String password) { this.repo = repo; repoUrl = repo.getRepoUrl().trim(); if (!repoUrl.endsWith("/") && !repoUrl.endsWith("\\")) { repoUrl += "/"; } options = SVNWCUtil.createDefaultOptions(true); try { trunkSVNUrl = SVNURL.parseURIEncoded(repo.getRepoUrl().replace("\\", "/")); repository = SVNRepositoryFactory.create(trunkSVNUrl); } catch (SVNException e) { throw new EVCSException(e); } userPassAuth = SVNPasswordAuthentication.newInstance(user, (password == null ? null : password.toCharArray()), true, trunkSVNUrl, false); authManager = new BasicAuthenticationManager(new SVNAuthentication[] {userPassAuth}); repository.setAuthenticationManager(authManager); clientManager = SVNClientManager.newInstance( options, repository.getAuthenticationManager()); } public SVNURL getBranchUrl(String branchPath) throws Exception { return SVNURL.parseURIEncoded(repoUrl + getBranchName(branchPath)); } @Override public void createBranch(String srcBranchName, String dstBranchName, String commitMessage) throws EVCSBranchExists { SVNURL fromUrl; SVNURL toUrl; try { fromUrl = getBranchUrl(srcBranchName); toUrl = getBranchUrl(dstBranchName); } catch (Exception e) { throw new RuntimeException(e); } createBranch(fromUrl, toUrl, commitMessage); } public void createBranch(SVNURL fromUrl, SVNURL toUrl, String commitMessage) { try { getBranchUrl("test"); // for exceptions rethrowing test only SVNCopyClient copyClient = clientManager.getCopyClient(); SVNCopySource copySource = new SVNCopySource(SVNRevision.HEAD, SVNRevision.HEAD, fromUrl); copySource.setCopyContents(false); copyClient.doCopy(new SVNCopySource[] { copySource }, toUrl, false, // isMove true, // make parents true, // failWhenDstExistsb commitMessage, // commit message null); // SVNProperties } catch (SVNException e) { if (e.getErrorMessage().getErrorCode().getCode() == SVN_ITEM_EXISTS_ERROR_CODE) { throw new EVCSBranchExists(e); } throw new EVCSException (e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void deleteBranch(String branchName, String commitMessage) { try { clientManager .getCommitClient() .doDelete(new SVNURL[] { getBranchUrl(branchName) }, commitMessage); } catch (SVNException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public VCSMergeResult merge(String srcBranchName, String dstBranchName, String commitMessage) { SVNDiffClient diffClient = clientManager.getDiffClient(); try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy()) { checkout(getBranchUrl(dstBranchName), wc.getFolder(), null); DefaultSVNOptions options = (DefaultSVNOptions) diffClient.getOptions(); final List<String> conflictingFiles = new ArrayList<>(); options.setConflictHandler(new ISVNConflictHandler() { @Override public SVNConflictResult handleConflict(SVNConflictDescription conflictDescription) throws SVNException { conflictingFiles.add(conflictDescription.getMergeFiles().getLocalPath()); return new SVNConflictResult(SVNConflictChoice.POSTPONE, conflictDescription.getMergeFiles().getResultFile()); } }); SVNRevisionRange range = new SVNRevisionRange(SVNRevision.create(1), SVNRevision.HEAD); try { diffClient.doMerge(getBranchUrl(srcBranchName), SVNRevision.HEAD, Collections.singleton(range), wc.getFolder(), SVNDepth.UNKNOWN, true, false, false, false); Boolean success = conflictingFiles.isEmpty(); if (success) { clientManager .getCommitClient() .doCommit(new File[] {wc.getFolder()}, false, commitMessage, new SVNProperties(), null, true, true, SVNDepth.INFINITY); } else { try { SVNWCClient wcClient = getRevertClient(options); wcClient.doRevert(new File[] {wc.getFolder()}, SVNDepth.INFINITY, null); } catch (Exception e) { // It doesn't matter if we failed to revert. Just make the workspace corrupted. wc.setCorrupted(true); } } return new VCSMergeResult(success, conflictingFiles); } catch (Exception e) { wc.setCorrupted(true); throw e; } } catch (SVNException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } public SVNWCClient getRevertClient(DefaultSVNOptions options) { return new SVNWCClient(authManager, options); } public void checkout(SVNURL sourceUrl, File destPath, String revision) throws Exception { SVNUpdateClient updateClient = clientManager.getUpdateClient(); updateClient.setIgnoreExternals(false); SVNRevision svnRevision = revision == null ? SVNRevision.HEAD : SVNRevision.parse(revision); if (isWorkingCopyInited(destPath)) { updateClient.doSwitch(destPath, sourceUrl, svnRevision, svnRevision, SVNDepth.INFINITY, false, false); } else { updateClient.doCheckout(sourceUrl, destPath, svnRevision, svnRevision, SVNDepth.UNKNOWN, false); } } public boolean isWorkingCopyInited(File destPath) { try { clientManager.getStatusClient().doStatus(destPath, false); return true; } catch (SVNException e) { if (e.getErrorMessage().getErrorCode().getCode() == SVN_PATH_IS_NOT_WORKING_COPY_ERROR_CODE) { return false; } else { throw new EVCSException(e); } } } @Override public void setCredentials(String user, String password) { userPassAuth = SVNPasswordAuthentication.newInstance(user, password == null ? null : password.toCharArray(), true, trunkSVNUrl, false); authManager.setAuthentications(new SVNAuthentication[] {userPassAuth}); clientManager = SVNClientManager.newInstance( options, repository.getAuthenticationManager()); } @Override public void setProxy(String host, int port, String proxyUser, String proxyPassword) { authManager.setProxy(host, port, proxyUser, proxyPassword.toCharArray()); } @Override public String getFileContent(String branchName, String filePath, String revision) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { repository.getFile(new File(getBranchName(branchName), filePath).getPath().replace("\\", "/"), (revision == null || revision.isEmpty()) ? -1 : Long.parseLong(revision), new SVNProperties(), baos); return baos.toString(StandardCharsets.UTF_8.name()); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode().getCode() == SVN_FILE_NOT_FOUND_ERROR_CODE) { throw new EVCSFileNotFound(e); } throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } private String getBranchName(String branchName) { return branchName == null ? MASTER_PATH : BRANCHES_PATH + branchName; } @Override public VCSCommit setFileContent(String branchName, String filePath, String content, String commitMessage) { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy()) { checkout(getBranchUrl(branchName), wc.getFolder(), null); File file = new File(wc.getFolder(), filePath); Boolean needToAdd = !file.exists(); if (!file.exists()) { FileUtils.forceMkdir(file.getParentFile()); file.createNewFile(); } FileWriter writer = new FileWriter(file); writer.write(content); writer.close(); if (needToAdd) { clientManager .getWCClient() .doAdd(file, true /* force, avoiding "file is already under version control" exception */, false, false, SVNDepth.EMPTY, false, true); } try { SVNCommitInfo newCommit = clientManager .getCommitClient() .doCommit(new File[] { wc.getFolder() }, false, commitMessage, new SVNProperties(), null, false, false, SVNDepth.INFINITY); return newCommit == SVNCommitInfo.NULL ? VCSCommit.EMPTY : new VCSCommit(Long.toString(newCommit.getNewRevision()), commitMessage, newCommit.getAuthor()); } catch (SVNException e) { wc.setCorrupted(true); throw e; } } catch (SVNException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public String getRepoUrl() { return repo.getRepoUrl(); } private List<VCSDiffEntry> fillUnifiedDiffs(final String srcBranchName, final String dstBranchName, List<VCSDiffEntry> entries) throws Exception { List<VCSDiffEntry> res = new ArrayList<>(); for (VCSDiffEntry entry : entries) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); final SvnOperationFactory svnOperationFactory = new SvnOperationFactory(); final SvnDiff diff = svnOperationFactory.createDiff(); if (entry.getChangeType() == VCSChangeType.ADD) { SVNLogEntry firstCommit = getBranchFirstCommit(dstBranchName); diff.setSource(SvnTarget.fromURL(getBranchUrl(srcBranchName).appendPath(entry.getFilePath(), true), SVNRevision.HEAD), SVNRevision.create(firstCommit.getRevision()), SVNRevision.create(repository.info(getBranchName(dstBranchName), -1).getRevision())); } else if (entry.getChangeType() == VCSChangeType.DELETE) { SVNLogEntry firstCommit = getBranchFirstCommit(dstBranchName); diff.setSource(SvnTarget.fromURL(getBranchUrl(dstBranchName).appendPath(entry.getFilePath(), true), SVNRevision.HEAD), SVNRevision.create(repository.info(getBranchName(dstBranchName), -1).getRevision()), SVNRevision.create(firstCommit.getRevision())); } else { diff.setSources( SvnTarget.fromURL(getBranchUrl(dstBranchName).appendPath(entry.getFilePath(), true), SVNRevision.HEAD), SvnTarget.fromURL(getBranchUrl(srcBranchName).appendPath(entry.getFilePath(), true), SVNRevision.HEAD)); } diff.setOutput(baos); diff.run(); res.add(new VCSDiffEntry(entry.getFilePath(), entry.getChangeType(), baos.toString("UTF-8"))); } return res; } protected SVNLogEntry getBranchFirstCommit(final String branchPath) throws Exception { final List<SVNLogEntry> logEntries = new ArrayList<>(); repository.log(new String[] { getBranchName(branchPath) }, -1 /* start from head descending */, 0, true, true, -1, new ISVNLogEntryHandler() { @Override public void handleLogEntry(SVNLogEntry logEntry) throws SVNException { logEntries.add(logEntry); } }); return logEntries.get(logEntries.size() - 1); } private List<VCSDiffEntry> getDiffEntries(final String srcBranchName, final String dstBranchName) throws Exception { final SvnOperationFactory svnOperationFactory = new SvnOperationFactory(); final SvnDiffSummarize summarizeDiff = svnOperationFactory.createDiffSummarize(); final List<VCSDiffEntry> res = new ArrayList<>(); summarizeDiff.setSources( SvnTarget.fromURL(getBranchUrl(dstBranchName), SVNRevision.HEAD), SvnTarget.fromURL(getBranchUrl(srcBranchName), SVNRevision.HEAD)); summarizeDiff.setReceiver(new ISvnObjectReceiver<SvnDiffStatus>() { public void receive(SvnTarget target, SvnDiffStatus diffStatus) throws SVNException { if (diffStatus.getPath().length() == 0) { return; } VCSDiffEntry entry = new VCSDiffEntry(diffStatus.getPath(), SVNChangeTypeToVCSChangeType(diffStatus.getModificationType()), null); res.add(entry); } }); summarizeDiff.run(); return res; } public VCSChangeType SVNChangeTypeToVCSChangeType(SVNStatusType modificationType) { if (SVNStatusType.STATUS_ADDED.equals(modificationType)) { return VCSChangeType.ADD; } else if (SVNStatusType.STATUS_DELETED.equals(modificationType)) { return VCSChangeType.DELETE; } else if (SVNStatusType.STATUS_MODIFIED.equals(modificationType)) { return VCSChangeType.MODIFY; } else { return VCSChangeType.UNKNOWN; } } @Override public List<VCSDiffEntry> getBranchesDiff(final String srcBranchName, final String dstBranchName) { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy()) { checkout(getBranchUrl(dstBranchName), wc.getFolder(), null); List<VCSDiffEntry> entries = getDiffEntries(srcBranchName, dstBranchName); entries = fillUnifiedDiffs(srcBranchName, dstBranchName, entries); return entries; } catch (SVNException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public Set<String> getBranches(String path) { try { List<String> entries = listEntries(SVNVCS.BRANCHES_PATH + (path == null ? "" : path)); Set<String> tempRes = new HashSet<>(entries); if (repository.checkPath(MASTER_PATH, -1) == SVNNodeKind.DIR) { if (path == null || MASTER_PATH.startsWith(path) ) { tempRes.add(MASTER_PATH.replace("/", "")); } } Set<String> res = new HashSet<>(); for (String str : tempRes) { res.add(StringUtils.removeStart(str, SVNVCS.BRANCHES_PATH)); } return res; } catch (SVNException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } protected List<String> listEntries(String path) throws Exception { List<String> res = new ArrayList<>(); if (repository.checkPath(path , -1) == SVNNodeKind.NONE) { return res; } @SuppressWarnings("unchecked") Collection<SVNDirEntry> entries = repository.getDir(path, -1 , null , (Collection<SVNDirEntry>) null); List<SVNDirEntry> entriesList = new ArrayList<>(entries); Collections.sort(entriesList, new Comparator<SVNDirEntry>() { @Override public int compare(SVNDirEntry o1, SVNDirEntry o2) { if (o1.getRevision() < o2.getRevision()) { return -1; } if (o1.getRevision() > o2.getRevision()) { return 1; } return 0; } }); for (SVNDirEntry entry : entriesList) { if (entry.getKind() == SVNNodeKind.DIR) { res.add((path.isEmpty() ? "" : StringUtils.appendIfMissing(path, "/")) + entry.getName()); res.addAll(listEntries((path.equals("")) ? entry.getName() : path + entry.getName())); } } return res; } @Override public List<VCSCommit> log(String branchName, int limit) { final List<VCSCommit> res = new ArrayList<>(); try { getBranchUrl(branchName); // for exception test only repository.log(new String[] { getBranchName(branchName) }, -1L /* start from head descending */, 0L, true, true, limit, new ISVNLogEntryHandler() { @Override public void handleLogEntry(SVNLogEntry logEntry) throws SVNException { res.add(svnLogEntryToVCSCommit(logEntry)); } }); return res; } catch (SVNException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public String getVCSTypeString() { return SVN_VCS_TYPE_STRING; } @Override public VCSCommit removeFile(String branchName, String filePath, String commitMessage) { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy()) { SVNCommitInfo res = clientManager .getCommitClient() .doDelete(new SVNURL[] {getBranchUrl(branchName).appendPath(filePath, true)}, commitMessage); return new VCSCommit(Long.toString(res.getNewRevision()), commitMessage, res.getAuthor()); } catch (SVNException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public List<VCSCommit> getCommitsRange(String branchName, String firstCommitId, WalkDirection direction, int limit) { final List<VCSCommit> res = new ArrayList<>(); try { Long sinceCommit; Long untilCommit; if (direction == WalkDirection.ASC) { sinceCommit = firstCommitId == null ? getBranchFirstCommit(branchName).getRevision() : Long.parseLong(firstCommitId); untilCommit = Long.parseLong(getHeadCommit(branchName).getRevision()); } else { sinceCommit = firstCommitId == null ? Long.parseLong(getHeadCommit(branchName).getRevision()) : Long.parseLong(firstCommitId); untilCommit = getBranchFirstCommit(branchName).getRevision(); } repository.log(new String[] { getBranchName(branchName) }, sinceCommit, untilCommit, true, true, limit, new ISVNLogEntryHandler() { @Override public void handleLogEntry(SVNLogEntry logEntry) throws SVNException { VCSCommit commit = svnLogEntryToVCSCommit(logEntry); res.add(commit); } }); return res; } catch (SVNException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } private VCSCommit svnLogEntryToVCSCommit(SVNLogEntry logEntry) { return new VCSCommit(Long.toString(logEntry.getRevision()), logEntry.getMessage(), logEntry.getAuthor()); } @Override public List<VCSCommit> getCommitsRange(String branchName, String firstCommitId, String untilCommitId) { final List<VCSCommit> res = new ArrayList<>(); try { Long sinceCommit = firstCommitId == null ? getBranchFirstCommit(branchName).getRevision() : Long.parseLong(firstCommitId); Long untilCommit = untilCommitId == null ? -1L : Long.parseLong(untilCommitId); repository.log(new String[] { getBranchName(branchName) }, sinceCommit, untilCommit, true, true, 0 /* limit */, new ISVNLogEntryHandler() { @Override public void handleLogEntry(SVNLogEntry logEntry) throws SVNException { res.add(svnLogEntryToVCSCommit(logEntry)); } }); return res; } catch (SVNException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public IVCSWorkspace getWorkspace() { return repo.getWorkspace(); } @Override public VCSCommit getHeadCommit(String branchName) { try { SVNLogEntry entry = revToSVNEntry(getBranchName(branchName), -1L); if (entry != null) { return svnLogEntryToVCSCommit(entry); } return null; } catch (SVNException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public String toString() { return "SVNVCS [url=" + repo.getRepoUrl() + "]"; } @Override public Boolean fileExists(String branchName, String filePath) { try { SVNNodeKind nodeKind = repository.checkPath( new File(getBranchName(branchName), filePath).getPath().replace("\\", "/") , -1 ); return nodeKind == SVNNodeKind.FILE; } catch (SVNException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public VCSTag createTag(String branchName, String tagName, String tagMessage, String revisionToTag) throws EVCSTagExists { try { SVNURL srcURL = getBranchUrl(branchName); SVNURL dstURL = SVNURL.parseURIEncoded(repoUrl + TAGS_PATH + tagName); SVNLogEntry copyFromEntry = revToSVNEntry(getBranchName(branchName), revisionToTag == null ? SVNRevision.HEAD.getNumber() : Long.parseLong(revisionToTag)); SVNCopySource copySource = revisionToTag == null ? new SVNCopySource(SVNRevision.HEAD, SVNRevision.create(copyFromEntry.getRevision()), srcURL) : new SVNCopySource(SVNRevision.parse(revisionToTag), SVNRevision.parse(revisionToTag), srcURL); clientManager.getCopyClient().doCopy(new SVNCopySource[] {copySource}, dstURL, false, false, true, tagMessage, null); SVNDirEntry entry = repository.info(TAGS_PATH + tagName, -1); return new VCSTag(tagName, tagMessage, entry.getAuthor(), svnLogEntryToVCSCommit(copyFromEntry)); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode().getCode() == SVN_ITEM_EXISTS_ERROR_CODE) { throw new EVCSTagExists(e); } throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } protected SVNLogEntry revToSVNEntry(String branchName, Long rev) throws Exception { SVNDirEntry info = repository.info(branchName, rev); @SuppressWarnings("unchecked") Collection<SVNLogEntry> entries = repository.log(new String[] {branchName}, null, info.getRevision(), info.getRevision(), true, true); if (entries != null) { return entries.iterator().next(); } return null; } private class SVNTagBaseCommit implements ISVNLogEntryHandler { private Long copyFromRevision; public Long getCopyFromRevision() { return copyFromRevision; } @Override public void handleLogEntry(SVNLogEntry logEntry) throws SVNException { for (String s : logEntry.getChangedPaths().keySet()) { SVNLogEntryPath entryPath = logEntry.getChangedPaths().get(s); copyFromRevision = entryPath.getCopyRevision(); } } } @Override public List<VCSTag> getTags() { try { List<String> entries = listEntries(TAGS_PATH); List<VCSTag> res = new ArrayList<>(); SVNTagBaseCommit handler; for (String entryStr : entries) { SVNLogEntry entry = revToSVNEntry(entryStr, -1L); handler = new SVNTagBaseCommit(); repository.log(new String[] { entryStr }, -1 /* start from head descending */, 0, true, true, -1, handler); SVNDirEntry copyFromEntry = repository.info("", handler.getCopyFromRevision()); res.add(new VCSTag(entryStr.replace(TAGS_PATH, ""), entry.getMessage(), entry.getAuthor(), new VCSCommit(Long.toString(copyFromEntry.getRevision()), copyFromEntry.getCommitMessage(), copyFromEntry.getAuthor()))); } return res; } catch (SVNException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void removeTag(String tagName) { try { getBranchUrl(null); // for test exceptions throwing only clientManager .getCommitClient() .doDelete(new SVNURL[] { SVNURL.parseURIEncoded(repoUrl + TAGS_PATH + tagName) }, null); } catch (SVNException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void checkout(String branchName, String targetPath, String revision) { try { checkout(getBranchUrl(branchName), new File(targetPath), revision); } catch (SVNException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public List<VCSTag> getTagsOnRevision(String revision) { try { List<VCSTag> res = new ArrayList<>(); if (repository.checkPath(TAGS_PATH , -1) == SVNNodeKind.NONE) { return res; } List<String> tagEntries = new ArrayList<>(); @SuppressWarnings("unchecked") Collection<SVNDirEntry> entries = repository.getDir(TAGS_PATH, -1 , null , (Collection<SVNDirEntry>) null); for (SVNDirEntry entry : entries) { if (entry.getKind() == SVNNodeKind.DIR) { tagEntries.add(TAGS_PATH + entry.getName()); } } SVNTagBaseCommit handler; for (String tagEntryStr : tagEntries) { SVNLogEntry entry = revToSVNEntry(tagEntryStr, -1L); handler = new SVNTagBaseCommit(); repository.log(new String[] { tagEntryStr }, -1 /* start from head descending */, 0, true, true, -1, handler); if (handler.getCopyFromRevision().equals(Long.parseLong(revision))) { SVNDirEntry copyFromEntry = repository.info("", handler.getCopyFromRevision()); res.add(new VCSTag(tagEntryStr.replace(TAGS_PATH, ""), entry.getMessage(), entry.getAuthor(), new VCSCommit(Long.toString(copyFromEntry.getRevision()), copyFromEntry.getCommitMessage(), copyFromEntry.getAuthor()))); } } return res; } catch (SVNException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } }
package processes; import interface_objects.DatabaseHandler; import managers.Logger; import objects.DatabaseQuery; import java.net.URI; import java.net.URISyntaxException; import java.sql.*; public class DatabaseClient { /** * entry point of the database client process * @param args */ @SuppressWarnings("InfiniteLoopStatement") public static void main(String[] args) { DatabaseQuery query; while (true) { // get a query query = null; Logger.log("DatabaseClient", "waiting for query"); while (query == null) query = DatabaseHandler.receiveQuery(); Logger.log("DatabaseClient", "got query " + query.query); ResultSet rs = executeQuery(query); Logger.log("DatabaseClient", "query " + query.query + " got " + rs); DatabaseHandler.addResponse(query.id, rs); } } /** * executed the given {@code dbQuery} * @param dbQuery the query to execute * @return * <p> * {@link ResultSet} if query is a select, null otherwise. * </p> * <p> * will not return the error if one occurred, * to check for errors check the {@code dbQuery} field {@link DatabaseQuery#error} * </p> */ public static ResultSet executeQuery(DatabaseQuery dbQuery) { ResultSet rs = null; Connection connection = null; try { connection = getConnection(); addSqlTypes(connection); Statement stmt = connection.createStatement(); if (dbQuery.query.startsWith("SELECT")) rs = stmt.executeQuery(dbQuery.query); else stmt.executeUpdate(dbQuery.query); } catch (Exception e) { dbQuery.error = e.getMessage(); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { if (dbQuery.error == null) dbQuery.error = ""; else dbQuery.error += "\n"; dbQuery.error += e.getMessage(); } } } return rs; } /** * adds the custom sql types to the connection * @param con the connection to add sql types to */ public static void addSqlTypes(Connection con) { try { java.util.Map<String, Class<?>> map = con.getTypeMap(); map.put("public.command_access", Class.forName("database_objects.CommandAccessSqlType")); con.setTypeMap(map); Logger.log("DatabaseClient.addSqlType", "adding types succeeded"); } catch (Exception e) { Logger.log("DatabaseClient.addSqlType", "adding types failed, " + e.getMessage()); } } /** * gets a database connection * @return a database connection * @throws URISyntaxException syntax exception * @throws SQLException sql exception */ private static Connection getConnection() throws URISyntaxException, SQLException { URI dbUri = new URI(System.getenv("DATABASE_URL")); int port = dbUri.getPort(); String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ":" + port + dbUri.getPath(); if (dbUri.getUserInfo() != null) { String username = dbUri.getUserInfo().split(":")[0]; String password = dbUri.getUserInfo().split(":")[1]; return DriverManager.getConnection(dbUrl, username, password); } else { return DriverManager.getConnection(dbUrl); } } /* try { connection = getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)"); stmt.executeUpdate("INSERT INTO ticks VALUES (now())"); ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); ArrayList<String> output = new ArrayList<String>(); while (rs.next()) { output.add( "Read from DB: " + rs.getTimestamp("tick")); } attributes.put("results", output); return new ModelAndView(attributes, "db.ftl"); } catch (Exception e) { attributes.put("message", "There was an error: " + e); return new ModelAndView(attributes, "error.ftl"); } finally { if (connection != null) try{connection.close();} catch(SQLException e){} } */ }
package space.pxls.data; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.exceptions.NoResultsException; import space.pxls.App; import space.pxls.server.Packet; import space.pxls.user.Role; import space.pxls.user.User; import java.io.Closeable; import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import static java.lang.Math.toIntExact; public class Database implements Closeable { private final DBI dbi; private Map<Thread,Database_handle> handles = new ConcurrentHashMap<>();; public Database() { try { Class.forName("org.mariadb.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } HikariConfig config = new HikariConfig(); config.setJdbcUrl(App.getConfig().getString("database.url")); config.setUsername(App.getConfig().getString("database.user")); config.setPassword(App.getConfig().getString("database.pass")); config.addDataSourceProperty("cachePrepStmts", "true"); config.addDataSourceProperty("prepStmtCacheSize", "250"); config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); config.addDataSourceProperty("allowMultiQueries", "true"); config.setMaximumPoolSize(200); // this is plenty, the websocket uses 32 dbi = new DBI(new HikariDataSource(config)); getHandle().createPixelsTable(); getHandle().createUsersTable(); getHandle().createSessionsTable(); getHandle().createAdminLogTable(); getHandle().createReportsTable(); } private DAO getHandle() { Thread t = Thread.currentThread(); Database_handle h = handles.get(t); if (h != null) { h.last_use = System.currentTimeMillis(); return h.dao; } h = new Database_handle(); h.dao = dbi.open(DAO.class); h.last_use = System.currentTimeMillis(); System.out.println("Creating new mariadb connection..."); System.out.println(h); handles.put(t, h); return h.dao; } public void cleanup() { for (Thread t : handles.keySet()) { Database_handle d = handles.get(t); if (d.last_use + (1000 * 60 * 5) < System.currentTimeMillis()) { // ok destroy it System.out.println("Destroying mariadb connection..."); System.out.println(d.dao); d.dao.close(); handles.remove(t); } } } public void placePixel(int x, int y, int color, User who, boolean mod_action) { getHandle().putPixel(x, y, (byte) color, who != null ? who.getId() : 0, mod_action); } public void updateUserTime(int uid, long seconds) { getHandle().updateUserTime(uid, seconds); } public DBPixelPlacement getPixelAt(int x, int y) { return getHandle().getPixel(x, y); } public DBPixelPlacementUser getPixelAtUser(int x, int y) { return getHandle().getPixelUser(x, y); } public DBPixelPlacement getPixelByID(int id) { return getHandle().getPixel(id); } // returns ids of all pixels that should be rolled back and the DBPixelPlacement for all pixels to rollback to // DBRollbackPixel is (DBPixelPlacement and fromID) so it has all the info needed to rollback public List<DBRollbackPixel> getRollbackPixels(User who, int fromSeconds) { Handle h = dbi.open(); List<Map<String, Object>> output = h .createQuery("SELECT id, secondary_id FROM pixels WHERE most_recent AND who = :who AND (time + INTERVAL :seconds SECOND > NOW())") .bind("who", who.getId()) .bind("seconds", fromSeconds) .list(); //this selects all pixels by the banned user that are the most_recent List<DBRollbackPixel> pixels = new ArrayList<>(); for (Map<String, Object> entry : output) { DBPixelPlacement toPixel; try { int prevId = toIntExact((long) entry.get("secondary_id")); toPixel = getHandle().getPixel(prevId); //if previous pixel exists // while the user who placed the previous pixel is banned while (toPixel.role.lessThan(Role.GUEST) || toPixel.ban_expiry > Instant.now().toEpochMilli() || toPixel.userId == who.getId()) { if (toPixel.secondaryId != 0) { toPixel = getHandle().getPixel(toPixel.secondaryId); //if is banned gets previous pixel } else { toPixel = null; // if is banned but no previous pixel exists return blank pixel break; // and no reason to loop because blank pixel isn't placed by an user } } } catch (NullPointerException e) { // .get() throws NullPointerException if secondary_id is NULL toPixel = null; //blank pixel } pixels.add(new DBRollbackPixel(toPixel, toIntExact((long) entry.get("id")))); //add and later return } h.close(); return pixels; } public List<DBPixelPlacement> getUndoPixels(User who) { Handle h = dbi.open(); List<Map<String, Object>> output = h .createQuery("SELECT DISTINCT secondary_id FROM pixels WHERE rollback_action AND who = :who AND secondary_id IS NOT NULL") .bind("who", who.getId()) .list(); // this selects all pixels that we previously have rolled back. List<DBPixelPlacement> pixels = new ArrayList<>(); for (Map<String, Object> entry : output) { int fromId = toIntExact((long) entry.get("secondary_id")); DBPixelPlacement fromPixel = getHandle().getPixel(fromId); // get the original pixel, the one that we previously rolled back boolean can_undo = getHandle().getCanUndo(fromPixel.x, fromPixel.y, fromPixel.id); if (can_undo) { // this basically checks if there are pixels that are more recent pixels.add(fromPixel); // add and later return } } h.close(); return pixels; } public void putUndoPixel(int x, int y, int color, User who, int fromId) { getHandle().putUndoPixel(x, y, (byte) color, who.getId(), fromId); } public void putRollbackPixel(User who, int fromId, int toId) { getHandle().putRollbackPixel(who.getId(), fromId, toId); } public void putRollbackPixelNoPrevious(int x, int y, User who, int fromId) { getHandle().putRollbackPixelNoPrevious(x, y, who.getId(), fromId, (byte) App.getConfig().getInt("board.defaultColor")); } public DBPixelPlacement getUserUndoPixel(User who){ return getHandle().getUserUndoPixel(who.getId()); } public void putUserUndoPixel(DBPixelPlacement backPixel, User who, int fromId) { getHandle().putUserUndoPixel(backPixel.x, backPixel.y, (byte) backPixel.color, who.getId(), backPixel.id, fromId); } public void putUserUndoPixel(int x, int y, int color, User who, int fromId) { getHandle().putUserUndoPixel(x, y, (byte) color, who.getId(), 0, fromId); } public void close() { getHandle().close(); } public DBUser getUserByLogin(String login) { return getHandle().getUserByLogin(login); } public DBUser getUserByName(String name) { return getHandle().getUserByName(name); } public DBUser getUserByToken(String token) { return getHandle().getUserByToken(token); } public DBUser createUser(String name, String login, String ip) { getHandle().createUser(name, login, ip); return getUserByName(name); } public void createSession(int who, String token) { getHandle().createSession(who, token); } public void destroySession(String token) { getHandle().destroySession(token); } public void updateSession(String token) { getHandle().updateSession(token); } public void setUserRole(User user, Role role) { getHandle().updateUserRole(user.getId(), role.name()); } public void updateBan(User user, long timeFromNowSeconds, String reason) { getHandle().updateUserBan(user.getId(), timeFromNowSeconds, reason); } public void updateBanReason(User user, String reason) { getHandle().updateUserBanReason(user.getId(), reason); } public void updateUserIP(User user, String ip) { getHandle().updateUserIP(user.getId(), ip); } public String getUserBanReason(int id) { return getHandle().getUserBanReason(id).ban_reason; } public void clearOldSessions() { getHandle().clearOldSessions(); } public boolean didPixelChange(int x, int y) { return getHandle().didPixelChange(x, y); } public void adminLog(String message, int uid) { getHandle().adminLog(message, uid); } public void adminLogServer(String message) { getHandle().adminLogServer(message); } public void addReport(int who, int pixel_id, int x, int y, String message) { getHandle().addReport(who, pixel_id, x, y, message); } } class Database_handle { public DAO dao; public long last_use; }
package water.fvec; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.concurrent.Future; import java.util.zip.*; import jsr166y.CountedCompleter; import jsr166y.ForkJoinTask; import jsr166y.ForkJoinWorkerThread; import jsr166y.RecursiveAction; import water.*; import water.H2O.H2OCountedCompleter; import water.fvec.Vec.VectorGroup; import water.nbhm.NonBlockingHashMap; import water.nbhm.NonBlockingSetInt; import water.parser.*; import water.parser.CustomParser.DataOut; import water.parser.CustomParser.ParserSetup; import water.parser.CustomParser.ParserType; import water.parser.CustomParser.StreamDataOut; import water.parser.Enum; import water.util.FrameUtils; import water.util.Log; import water.util.Utils.IcedHashMap; import water.util.Utils.IcedInt; import water.util.Utils; public final class ParseDataset2 extends Job { public final Key _progress; // Job progress Key private MultiFileParseTask _mfpt; // Access to partially built vectors for cleanup after parser crash public static enum Compression { NONE, ZIP, GZIP } public static Key [] filterEmptyFiles(Key [] keys){ Arrays.sort(keys); // first check if there are any empty files and if so remove them Vec [] vecs = new Vec [keys.length]; int c = 0; for(int i = 0; i < vecs.length; ++i) { vecs[i] = getVec(keys[i]); if(vecs[i].length() == 0) c++; } if(c > 0){ // filter out empty files Key[] ks = new Key[keys.length-c]; Vec[] vs = new Vec[vecs.length-c]; int j = 0; for(int i = 0; i < keys.length; ++i) if(vecs[i].length() != 0){ ks[j] = keys[i]; vs[j] = vecs[i]; ++j; } keys = ks; } return keys; } // Parse an array of csv input/file keys into an array of distributed output Vecs public static Frame parse(Key okey, Key [] keys) { return parse(okey,keys,new GuessSetup.GuessSetupTsk(new ParserSetup(),true).invoke(keys)._gSetup._setup,true); } public static Frame parse(Key okey, Key[] keys, CustomParser.ParserSetup globalSetup, boolean delete_on_done) { if( globalSetup._ncols == 0 ) throw new java.lang.IllegalArgumentException(globalSetup.toString()); return forkParseDataset(okey, keys, globalSetup, delete_on_done).get(); } // Same parse, as a backgroundable Job public static ParseDataset2 forkParseDataset(final Key dest, Key[] keys, final CustomParser.ParserSetup setup, boolean delete_on_done) { keys = filterEmptyFiles(keys); setup.checkDupColumnNames(); // Some quick sanity checks: no overwriting your input key, and a resource check. long sum=0; for( Key k : keys ) { if( dest.equals(k) ) throw new IllegalArgumentException("Destination key "+dest+" must be different from all sources"); sum += DKV.get(k).length(); // Sum of all input filesizes } long memsz=0; // Cluster memory for( H2ONode h2o : H2O.CLOUD._memary ) memsz += h2o.get_max_mem(); if( sum > memsz*4 ) throw new IllegalArgumentException("Total input file size of "+PrettyPrint.bytes(sum)+" is much larger than total cluster memory of "+PrettyPrint.bytes(memsz)+", please use either a larger cluster or smaller data."); ParseDataset2 job = new ParseDataset2(dest, keys); new Frame(job.dest(),new String[0],new Vec[0]).delete_and_lock(job.self()); // Lock BEFORE returning for( Key k : keys ) Lockable.read_lock(k,job.self()); // Lock BEFORE returning ParserFJTask fjt = new ParserFJTask(job, keys, setup, delete_on_done); // Fire off background parse // Make a wrapper class that only *starts* when the ParserFJTask fjt // completes - especially it only starts even when fjt completes // exceptionally... thus the fjt onExceptionalCompletion code runs // completely before this empty task starts - providing a simple barrier. // Threads blocking on the job will block on the "cleanup" task, which will // block until the fjt runs the onCompletion or onExceptionCompletion code. H2OCountedCompleter cleanup = new H2OCountedCompleter() { @Override public void compute2() { } @Override public boolean onExceptionalCompletion(Throwable ex, CountedCompleter caller) { return true; } }; fjt.setCompleter(cleanup); job.start(cleanup); H2O.submitTask(fjt); return job; } // Setup a private background parse job private ParseDataset2(Key dest, Key[] fkeys) { destination_key = dest; // Job progress Key _progress = Key.make((byte) 0, Key.JOB); UKV.put(_progress, ParseProgress.make(fkeys)); } // Simple internal class doing background parsing, with trackable Job status public static class ParserFJTask extends H2OCountedCompleter { final ParseDataset2 _job; Key[] _keys; CustomParser.ParserSetup _setup; boolean _delete_on_done; public ParserFJTask( ParseDataset2 job, Key[] keys, CustomParser.ParserSetup setup, boolean delete_on_done) { _job = job; _keys = keys; _setup = setup; _delete_on_done = delete_on_done; } @Override public void compute2() { parse_impl(_job, _keys, _setup, _delete_on_done); tryComplete(); } // Took a crash/NPE somewhere in the parser. Attempt cleanup. @Override public boolean onExceptionalCompletion(Throwable ex, CountedCompleter caller){ Futures fs = new Futures(); if( _job != null ) { UKV.remove(_job.destination_key,fs); UKV.remove(_job._progress,fs); // Find & remove all partially-built output vecs & chunks if( _job._mfpt != null ) _job._mfpt.onExceptionCleanup(fs); } // Assume the input is corrupt - or already partially deleted after // parsing. Nuke it all - no partial Vecs lying around. for( Key k : _keys ) UKV.remove(k,fs); fs.blockForPending(); // As soon as the job is canceled, threads blocking on the job will // wake up. Better have all cleanup done first! if( _job != null ) _job.cancel(ex); return true; } } // Parser progress static class ParseProgress extends Iced { final long _total; long _value; DException _ex; ParseProgress(long val, long total){_value = val; _total = total;} // Total number of steps is equal to total bytecount across files static ParseProgress make( Key[] fkeys ) { long total = 0; for( Key fkey : fkeys ) total += getVec(fkey).length(); return new ParseProgress(0,total); } public void setException(DException ex){_ex = ex;} public DException getException(){return _ex;} } static void onProgress(final long len, final Key progress) { new TAtomic<ParseProgress>() { @Override public ParseProgress atomic(ParseProgress old) { if (old == null) return null; old._value += len; return old; } }.fork(progress); } @Override public float progress() { ParseProgress progress = UKV.get(_progress); if( progress == null || progress._total == 0 ) return 0; return progress._value / (float) progress._total; } @Override public void remove() { DKV.remove(_progress); super.remove(); } /** Task to update enum values to match the global numbering scheme. * Performs update in place so that values originally numbered using * node-local unordered numbering will be numbered using global numbering. * @author tomasnykodym */ private static class EnumUpdateTask extends MRTask2<EnumUpdateTask> { private transient int[][][] _emap; final Key _eKey; private final ValueString [][] _gDomain; private final Enum [][] _lEnums; private final int [] _chunk2Enum; private final int [] _colIds; private EnumUpdateTask(ValueString [][] gDomain, Enum [][] lEnums, int [] chunk2Enum, Key lDomKey, int [] colIds){ _gDomain = gDomain; _lEnums = lEnums; _chunk2Enum = chunk2Enum; _eKey = lDomKey; _colIds = colIds; } private int[][] emap(int nodeId) { if( _emap == null ) _emap = new int[_lEnums.length][][]; if( _emap[nodeId] == null ) { int[][] emap = new int[_gDomain.length][]; for( int i = 0; i < _gDomain.length; ++i ) { if( _gDomain[i] != null ) { assert _lEnums[nodeId] != null : "missing lEnum of node " + nodeId + ", enums = " + Arrays.toString(_lEnums); final Enum e = _lEnums[nodeId][_colIds[i]]; emap[i] = new int[e.maxId()+1]; Arrays.fill(emap[i], -1); for(int j = 0; j < _gDomain[i].length; ++j) { ValueString vs = _gDomain[i][j]; if( e.containsKey(vs) ) { assert e.getTokenId(vs) <= e.maxId():"maxIdx = " + e.maxId() + ", got " + e.getTokenId(vs); emap[i][e.getTokenId(vs)] = j; } } } } _emap[nodeId] = emap; } return _emap[nodeId]; } @Override public void map(Chunk [] chks){ int[][] emap = emap(_chunk2Enum[chks[0].cidx()]); final int cidx = chks[0].cidx(); for(int i = 0; i < chks.length; ++i) { Chunk chk = chks[i]; if(_gDomain[i] == null) // killed, replace with all NAs DKV.put(chk._vec.chunkKey(chk.cidx()),new C0DChunk(Double.NaN,chk._len)); else for( int j = 0; j < chk._len; ++j){ if( chk.isNA0(j) )continue; long l = chk.at80(j); if (l < 0 || l >= emap[i].length) reportBrokenEnum(chk, i, j, l, emap); if(emap[i][(int)l] < 0) throw new RuntimeException(H2O.SELF.toString() + ": missing enum at col:" + i + ", line: " + j + ", val = " + l + ", chunk=" + chk.getClass().getSimpleName()); chk.set0(j, emap[i][(int)l]); } chk.close(cidx, _fs); } } private void reportBrokenEnum( Chunk chk, int i, int j, long l, int[][] emap ) { Chunk chk2 = chk._chk2; chk._chk2 = null; StringBuilder sb = new StringBuilder("Enum renumber task, column # " + i + ": Found OOB index " + l + " (expected 0 - " + emap[i].length + ", global domain has " + _gDomain[i].length + " levels) pulled from " + chk.getClass().getSimpleName() + "\n"); int k = 0; for(; k < Math.min(5,chk._len); ++k) sb.append("at8[" + (k+chk._start) + "] = " + chk.at80(k) + ", chk2 = " + (chk2 != null?chk2.at80(k):"") + "\n"); k = Math.max(k,j-2); sb.append("...\n"); for(; k < Math.min(chk._len,j+2); ++k) sb.append("at8[" + (k+chk._start) + "] = " + chk.at80(k) + ", chk2 = " + (chk2 != null?chk2.at80(k):"") + "\n"); sb.append("...\n"); k = Math.max(k,chk._len-5); for(; k < chk._len; ++k) sb.append("at8[" + (k+chk._start) + "] = " + chk.at80(k) + ", chk2 = " + (chk2 != null?chk2.at80(k):"") + "\n"); throw new RuntimeException(sb.toString()); } } private static class EnumFetchTask extends MRTask<EnumFetchTask> { private final Key _k; private final int[] _ecols; private final int _homeNode; // node where the computation started, enum from this node MUST be cloned! private Enum[] _gEnums; // global enums per column private Enum[][] _lEnums; // local enums per node per column private EnumFetchTask(int homeNode, Key k, int[] ecols){_homeNode = homeNode; _k = k;_ecols = ecols;} @Override public void map(Key key) { _lEnums = new Enum[H2O.CLOUD.size()][]; if(MultiFileParseTask._enums.containsKey(_k)){ _lEnums[H2O.SELF.index()] = _gEnums = MultiFileParseTask._enums.get(_k); // if we are the original node (i.e. there will be no sending over // wire), we have to clone the enums not to share the same object // (causes problems when computing column domain and renumbering maps). if( H2O.SELF.index() == _homeNode ) { _gEnums = _gEnums.clone(); for(int i = 0; i < _gEnums.length; ++i) _gEnums[i] = _gEnums[i].clone(); } MultiFileParseTask._enums.remove(_k); } } @Override public void reduce(EnumFetchTask etk) { if(_gEnums == null) { _gEnums = etk._gEnums; _lEnums = etk._lEnums; } else if (etk._gEnums != null) { for( int i : _ecols ) _gEnums[i].merge(etk._gEnums[i]); for( int i = 0; i < _lEnums.length; ++i ) if( _lEnums[i] == null ) _lEnums[i] = etk._lEnums[i]; else assert etk._lEnums[i] == null; } } } // Run once on all nodes; fill in missing zero chunks private static class SVFTask extends MRTask<SVFTask> { private final Frame _f; private SVFTask( Frame f ) { _f = f; } @Override public void map(Key key) { Vec v0 = _f.anyVec(); ArrayList<RecursiveAction> rs = new ArrayList<RecursiveAction>(); for( int i = 0; i < v0.nChunks(); ++i ) { if( !v0.chunkKey(i).home() ) continue; final int fi = i; rs.add(new RecursiveAction() { @Override protected void compute() { // First find the nrows as the # rows of non-missing chunks; done on // locally-homed chunks only - to keep the data distribution. int nlines = 0; for( Vec vec : _f.vecs() ) { Value val = H2O.get(vec.chunkKey(fi)); // Local-get only if( val != null ) { nlines = ((Chunk)val.get())._len; break; } } final int fnlines = nlines; // Now fill in appropriate-sized zero chunks for(int j = 0; j < _f.numCols(); ++j) { Vec vec = _f.vec(j); Key k = vec.chunkKey(fi); Value val = H2O.get(k); // Local-get only if( val == null ) // Missing? Fill in w/zero chunk H2O.putIfMatch(k, new Value(k, new C0DChunk(0, fnlines)), null); } } }); } ForkJoinTask.invokeAll(rs); } @Override public void reduce( SVFTask drt ) {} } private static Vec getVec(Key key) { Object o = UKV.get(key); return o instanceof Vec ? (ByteVec) o : ((Frame) o).vecs()[0]; } private static String [] genericColumnNames(int ncols){ String [] res = new String[ncols]; for(int i = 0; i < res.length; ++i) res[i] = "C" + String.valueOf(i+1); return res; } // Log information about the dataset we just parsed. private static void logParseResults(ParseDataset2 job, Frame fr) { try { long numRows = fr.anyVec().length(); Log.info("Parse result for " + job.dest() + " (" + Long.toString(numRows) + " rows):"); Vec[] vecArr = fr.vecs(); for( int i = 0; i < vecArr.length; i++ ) { Vec v = vecArr[i]; boolean isCategorical = v.isEnum(); boolean isConstant = (v.min() == v.max()); String CStr = String.format("C%d:", i+1); String typeStr = String.format("%s", (v._isUUID ? "UUID" : (isCategorical ? "categorical" : "numeric"))); String minStr = String.format("min(%f)", v.min()); String maxStr = String.format("max(%f)", v.max()); long numNAs = v.naCnt(); String naStr = (numNAs > 0) ? String.format("na(%d)", numNAs) : ""; String isConstantStr = isConstant ? "constant" : ""; String numLevelsStr = isCategorical ? String.format("numLevels(%d)", v.domain().length) : ""; boolean printLogSeparatorToStdout = false; boolean printColumnToStdout; { // Print information to stdout for this many leading columns. final int MAX_HEAD_TO_PRINT_ON_STDOUT = 10; // Print information to stdout for this many trailing columns. final int MAX_TAIL_TO_PRINT_ON_STDOUT = 10; if (vecArr.length <= (MAX_HEAD_TO_PRINT_ON_STDOUT + MAX_TAIL_TO_PRINT_ON_STDOUT)) { // For small numbers of columns, print them all. printColumnToStdout = true; } else if (i < MAX_HEAD_TO_PRINT_ON_STDOUT) { printColumnToStdout = true; } else if (i == MAX_HEAD_TO_PRINT_ON_STDOUT) { printLogSeparatorToStdout = true; printColumnToStdout = false; } else if ((i + MAX_TAIL_TO_PRINT_ON_STDOUT) < vecArr.length) { printColumnToStdout = false; } else { printColumnToStdout = true; } } if (printLogSeparatorToStdout) { System.out.println("Additional column information only sent to log file..."); } if (printColumnToStdout) { // Log to both stdout and log file. Log.info(String.format(" %-8s %15s %20s %20s %15s %11s %16s", CStr, typeStr, minStr, maxStr, naStr, isConstantStr, numLevelsStr)); } else { // Log only to log file. Log.info_no_stdout(String.format(" %-8s %15s %20s %20s %15s %11s %16s", CStr, typeStr, minStr, maxStr, naStr, isConstantStr, numLevelsStr)); } } Log.info(FrameUtils.chunkSummary(fr).toString()); } catch (Exception ignore) {} // Don't fail due to logging issues. Just ignore them. } // Top-level parser driver private static void parse_impl(ParseDataset2 job, Key[] fkeys, CustomParser.ParserSetup setup, boolean delete_on_done) { assert setup._ncols > 0; if( fkeys.length == 0) { job.cancel(); return; } // Remove any previous instance and insert a sentinel (to ensure no one has // been writing to the same keys during our parse)! Vec v = getVec(fkeys[0]); int reserveKeys = setup._pType == ParserType.SVMLight?25000000:setup._ncols; VectorGroup vg = v.group(); int vecIdStart = vg.reserveKeys(reserveKeys); MultiFileParseTask mfpt = job._mfpt = new MultiFileParseTask(v.group(),vecIdStart,setup,job._progress); mfpt.invoke(fkeys); EnumUpdateTask eut = null; // Calculate enum domain int n = 0; AppendableVec [] avs = mfpt.vecs(); if(avs.length < reserveKeys) vg.tryReturnKeys(vecIdStart+reserveKeys,vecIdStart + avs.length); int [] ecols = new int[avs.length]; for( int i = 0; i < ecols.length; ++i ) if(avs[i].shouldBeEnum()) ecols[n++] = i; ecols = Arrays.copyOf(ecols, n); if( ecols.length > 0 ) { EnumFetchTask eft = new EnumFetchTask(H2O.SELF.index(), mfpt._eKey, ecols).invokeOnAllNodes(); Enum[] enums = eft._gEnums; ValueString[][] ds = new ValueString[ecols.length][]; int j = 0; for( int i : ecols ) avs[i]._domain = ValueString.toString(ds[j++] = enums[i].computeColumnDomain()); eut = new EnumUpdateTask(ds, eft._lEnums, mfpt._chunk2Enum, mfpt._eKey, ecols); } final Frame fr = new Frame(job.dest(),setup._columnNames != null?setup._columnNames:genericColumnNames(avs.length),AppendableVec.closeAll(avs)); // SVMLight is sparse format, there may be missing chunks with all 0s, fill them in new SVFTask(fr).invokeOnAllNodes(); fr.checkCompatible(); // Update enums to the globally agreed numbering if( eut != null ) { Vec[] evecs = new Vec[ecols.length]; for( int i = 0; i < evecs.length; ++i ) evecs[i] = fr.vecs()[ecols[i]]; eut.doAll(evecs); } Futures fs = new Futures(); for(Vec v2:fr.vecs()) v2.rollupStats(fs); fs.blockForPending(); logParseResults(job, fr); // Release the frame for overwriting fr.unlock(job.self()); // Remove CSV files from H2O memory if( delete_on_done ) for( Key k : fkeys ) Lockable.delete(k,job.self()); else for( Key k : fkeys ) { Lockable l = UKV.get(k); l.unlock(job.self()); } job.remove(); } public static class ParseProgressMonitor extends Iced implements Job.ProgressMonitor { final Key _progressKey; private long _progress; public ParseProgressMonitor(Key pKey){_progressKey = pKey;} @Override public void update(long n) { ParseDataset2.onProgress(n, _progressKey); _progress += n; } public long progress() { return _progress; } } // We want to do a standard MRTask with a collection of file-keys (so the // files are parsed in parallel across the cluster), but we want to throttle // the parallelism on each node. private static class MultiFileParseTask extends MRTask<MultiFileParseTask> { private final CustomParser.ParserSetup _setup; // The expected column layout private final VectorGroup _vg; // vector group of the target dataset private final int _vecIdStart; // Start of available vector keys // Shared against all concurrent unrelated parses, a map to the node-local // Enum lists for each concurrent parse. private static NonBlockingHashMap<Key, Enum[]> _enums = new NonBlockingHashMap<Key, Enum[]>(); // The Key used to sort out *this* parse's Enum[] private final Key _eKey = Key.make(); private final Key _progress; // Mapping from Chunk# to cluster-node-number holding the enum mapping. // It is either self for all the non-parallel parses, or the Chunk-home for parallel parses. private int[] _chunk2Enum; // All column data for this one file // Vec _vecs[];M // A mapping of Key+ByteVec to rolling total Chunk counts. private IcedHashMap<Key,IcedInt> _fileChunkOffsets; // OUTPUT fields: private FVecDataOut [] _dout; public AppendableVec[] vecs(){ if(_dout.length == 1) return _dout[0]._vecs; int nCols = 0; for(FVecDataOut dout:_dout) nCols = Math.max(dout._vecs.length,nCols); AppendableVec [] res = new AppendableVec[nCols]; int nchunks = 0; for(FVecDataOut dout:_dout) nchunks += dout.nChunks(); long [] espc = MemoryManager.malloc8(nchunks); for(int i = 0; i < res.length; ++i) { res[i] = new AppendableVec(_vg.vecKey(_vecIdStart + i), espc, 0); res[i]._chunkTypes = MemoryManager.malloc1(nchunks); } for(int i = 0; i < _dout.length; ++i) for(int j = 0; j < _dout[i]._vecs.length; ++j) res[j].setSubRange(_dout[i]._vecs[j]); return res; } public String _parserr; // NULL if parse is OK, else an error string MultiFileParseTask(VectorGroup vg, int vecIdStart, CustomParser.ParserSetup setup, Key progress ) { _vg = vg; _setup = setup; _progress = progress; _vecIdStart = vecIdStart; _runSingleThreaded = true; } @Override public void init(){ super.init(); _dout = new FVecDataOut[_keys.length]; } @Override public MultiFileParseTask dfork(Key... keys){ // init(); _fileChunkOffsets = new IcedHashMap<Key, IcedInt>(); int len = 0; for( Key k:keys) { _fileChunkOffsets.put(k,new IcedInt(len)); len += getVec(k).nChunks(); } // Mapping from Chunk# to cluster-node-number _chunk2Enum = MemoryManager.malloc4(len); Arrays.fill(_chunk2Enum, -1); return super.dfork(keys); } private FVecDataOut makeDout(ParserSetup localSetup, int chunkOff, int nchunks) { AppendableVec [] avs = new AppendableVec[localSetup._ncols]; long [] espc = MemoryManager.malloc8(nchunks); for(int i = 0; i < avs.length; ++i) avs[i] = new AppendableVec(_vg.vecKey(i + _vecIdStart),espc, chunkOff); return localSetup._pType == ParserType.SVMLight ?new SVMLightFVecDataOut(_vg,0,avs,_vecIdStart,chunkOff,enums(_eKey,localSetup._ncols)) :new FVecDataOut(_vg, chunkOff, chunkOff, enums(_eKey,localSetup._ncols), avs); } // Called once per file @Override public void map( Key key ) { // Get parser setup info for this chunk ByteVec vec = (ByteVec) getVec(key); byte [] bits = vec.chunkForChunkIdx(0)._mem; if(bits == null || bits.length == 0){ assert false:"encountered empty file during multifile parse? should've been filtered already"; return; // should not really get here } final int chunkOff = _fileChunkOffsets.get(key)._val; Compression cpr = Utils.guessCompressionMethod(bits); CustomParser.ParserSetup localSetup = GuessSetup.guessSetup(Utils.unzipBytes(bits,cpr), _setup,false)._setup; // Local setup: nearly the same as the global all-files setup, but maybe // has the header-flag changed. if(!localSetup.isCompatible(_setup)) { _parserr = "Conflicting file layouts, expecting: " + _setup + " but found "+localSetup; return; } // Allow dup headers, if they are equals-ignoring-case boolean has_hdr = _setup._header && localSetup._header; if( has_hdr ) { // Both have headers? for( int i = 0; has_hdr && i < localSetup._columnNames.length; ++i ) has_hdr = localSetup._columnNames[i].equalsIgnoreCase(_setup._columnNames[i]); if( !has_hdr ) // Headers not compatible? // Then treat as no-headers, i.e., parse it as a normal row localSetup = new CustomParser.ParserSetup(ParserType.CSV,localSetup._separator, false); } // Parse the file try { switch( cpr ) { case NONE: if( localSetup._pType.parallelParseSupported ) { DParse dp = new DParse(_vg, localSetup, _vecIdStart, chunkOff,this, vec.nChunks()); addToPendingCount(1); dp._removeKey = vec._key; dp.exec(new Frame(vec)); for( int i = 0; i < vec.nChunks(); ++i ) _chunk2Enum[chunkOff + i] = vec.chunkKey(i).home_node().index(); } else { ParseProgressMonitor pmon = new ParseProgressMonitor(_progress); _dout[_lo] = streamParse(vec.openStream(pmon), localSetup, makeDout(localSetup,chunkOff,vec.nChunks()), pmon); for(int i = 0; i < vec.nChunks(); ++i) _chunk2Enum[chunkOff + i] = H2O.SELF.index(); } break; case ZIP: { // Zipped file; no parallel decompression; ParseProgressMonitor pmon = new ParseProgressMonitor(_progress); ZipInputStream zis = new ZipInputStream(vec.openStream(pmon)); ZipEntry ze = zis.getNextEntry(); // Get the *FIRST* entry // SVMLightFVecDataOut(VectorGroup vg, int cidx, AppendableVec [] avs, int vecIdStart, int chunkOff, Enum [] enums) // There is at least one entry in zip file and it is not a directory. if( ze != null && !ze.isDirectory() ) _dout[_lo] = streamParse(zis, localSetup, makeDout(localSetup,chunkOff,vec.nChunks()), pmon); else zis.close(); // Confused: which zipped file to decompress // set this node as the one which rpocessed all the chunks for(int i = 0; i < vec.nChunks(); ++i) _chunk2Enum[chunkOff + i] = H2O.SELF.index(); break; } case GZIP: // Zipped file; no parallel decompression; ParseProgressMonitor pmon = new ParseProgressMonitor(_progress); _dout[_lo] = streamParse(new GZIPInputStream(vec.openStream(pmon)),localSetup,makeDout(localSetup,chunkOff,vec.nChunks()), pmon); // set this node as the one which processed all the chunks for(int i = 0; i < vec.nChunks(); ++i) _chunk2Enum[chunkOff + i] = H2O.SELF.index(); break; } } catch( IOException ioe ) { throw new RuntimeException(ioe); } } // Reduce: combine errors from across files. // Roll-up other meta data @Override public void reduce( MultiFileParseTask mfpt ) { assert this != mfpt; // Combine parse errors from across files if( _parserr == null ) _parserr = mfpt._parserr; else if( mfpt._parserr != null ) _parserr += mfpt._parserr; // Collect & combine columns across files if( _dout == null ) _dout = mfpt._dout; else if(_dout != mfpt._dout) _dout = Utils.append(_dout,mfpt._dout); if( _chunk2Enum == null ) _chunk2Enum = mfpt._chunk2Enum; else if(_chunk2Enum != mfpt._chunk2Enum) { // we're sharing global array! for( int i = 0; i < _chunk2Enum.length; ++i ) { if( _chunk2Enum[i] == -1 ) _chunk2Enum[i] = mfpt._chunk2Enum[i]; else assert mfpt._chunk2Enum[i] == -1 : Arrays.toString(_chunk2Enum) + " :: " + Arrays.toString(mfpt._chunk2Enum); } } } private static Enum [] enums(Key eKey, int ncols){ if(!_enums.containsKey(eKey)){ Enum [] enums = new Enum[ncols]; for(int i = 0; i < enums.length; ++i)enums[i] = new Enum(); _enums.putIfAbsent(eKey, enums); } return _enums.get(eKey); } // Zipped file; no parallel decompression; decompress into local chunks, // parse local chunks; distribute chunks later. private FVecDataOut streamParse( final InputStream is, final CustomParser.ParserSetup localSetup, FVecDataOut dout, ParseProgressMonitor pmon) throws IOException { // All output into a fresh pile of NewChunks, one per column CustomParser p = localSetup.parser(); // assume 2x inflation rate //if( localSetup._pType.parallelParseSupported ) if( localSetup._pType.parallelParseSupported ) try{p.streamParse(is, dout, pmon);}catch(IOException e){throw new RuntimeException(e);} else try{p.streamParse(is, dout);}catch(Exception e){throw new RuntimeException(e);} // Parse all internal "chunks", until we drain the zip-stream dry. Not // real chunks, just flipping between 32K buffers. Fills up the single // very large NewChunk. dout.close(_fs); return dout; } private static class DParse extends MRTask2<DParse> { private final CustomParser.ParserSetup _setup; private final int _vecIdStart; private final int _chunkOff; // for multifile parse, offset of the first chunk in the final dataset private final VectorGroup _vg; private FVecDataOut _dout; private final Key _eKey; final Key _progress; Key _removeKey; private transient final MultiFileParseTask _outerMFPT; final int _nchunks; private transient NonBlockingSetInt _visited; private transient long [] _espc; DParse(VectorGroup vg, CustomParser.ParserSetup setup, int vecIdstart, int startChunkIdx, MultiFileParseTask mfpt, int nchunks) { super(mfpt); _vg = vg; _setup = setup; _vecIdStart = vecIdstart; _chunkOff = startChunkIdx; _outerMFPT = mfpt; _eKey = mfpt._eKey; _progress = mfpt._progress; _nchunks = nchunks; } @Override public void setupLocal(){ super.setupLocal(); _espc = MemoryManager.malloc8(_nchunks); _visited = new NonBlockingSetInt(); } @Override public void map( Chunk in) { AppendableVec [] avs = new AppendableVec[_setup._ncols]; for(int i = 0; i < avs.length; ++i) avs[i] = new AppendableVec(_vg.vecKey(_vecIdStart + i), _espc, _chunkOff); Enum [] enums = enums(_eKey,_setup._ncols); // Break out the input & output vectors before the parse loop // The Parser FVecDataIn din = new FVecDataIn(in); FVecDataOut dout; CustomParser p; switch(_setup._pType) { case CSV: p = new CsvParser(_setup); dout = new FVecDataOut(_vg,_chunkOff, _chunkOff + in.cidx(),enums,avs); break; case SVMLight: p = new SVMLightParser(_setup); dout = new SVMLightFVecDataOut(_vg, _chunkOff + in.cidx(), avs, _vecIdStart, _chunkOff, enums); break; default: throw H2O.unimpl(); } p.parallelParse(in.cidx(),din,dout); (_dout = dout).close(_fs); onProgress(in._len, _progress); // Record bytes parsed // remove parsed data right away (each chunk is used by 2) final int cidx = in.cidx(); if(!_visited.add(cidx)) { Value v = H2O.get(in._vec.chunkKey(cidx)); if(v != null && v.isPersisted()) { v.freePOJO(); v.freeMem(); } } if(!_visited.add(cidx+1)) { Value v = H2O.get(in._vec.chunkKey(cidx+1)); if(v != null && v.isPersisted()) { v.freePOJO(); v.freeMem(); } } } @Override public void reduce(DParse dp) { if(_dout == null)_dout = dp._dout; else _dout.reduce(dp._dout); } @Override public void postGlobal() { super.postGlobal(); _outerMFPT._dout[_outerMFPT._lo] = _dout; _dout = null; // Reclaim GC eagerly if(_removeKey != null) UKV.remove(_removeKey); } } // Find & remove all partially built output chunks & vecs private Futures onExceptionCleanup(Futures fs) { int nchunks = _chunk2Enum.length; int ncols = _setup._ncols; for( int i = 0; i < ncols; ++i ) { Key vkey = _vg.vecKey(_vecIdStart + i); DKV.remove(vkey,fs); for( int c = 0; c < nchunks; ++c ) DKV.remove(Vec.chunkKey(vkey,c),fs); } cancel(true); return fs; } } /** Parsed data output specialized for fluid vecs. * @author tomasnykodym */ static class FVecDataOut extends Iced implements CustomParser.StreamDataOut { protected transient NewChunk [] _nvs; public final int _chunkOff; protected AppendableVec []_vecs; private transient final Enum [] _enums; protected byte [] _ctypes; long _nLines; int _col = -1; final int _cidx; int _nChunks; boolean _closedVecs = false; private final VectorGroup _vg; static final protected byte UCOL = 0; // unknown col type static final protected byte NCOL = 1; // numeric col type static final protected byte ECOL = 2; // enum col type static final protected byte TCOL = 3; // time col typ static final protected byte ICOL = 4; // UUID col typ public int nChunks(){return _nChunks;} // private static AppendableVec[] newAppendables(int n, VectorGroup vg, int vecIdStart){ // AppendableVec [] apps = new AppendableVec[n]; // for(int i = 0; i < n; ++i) // apps[i] = new AppendableVec(vg.vecKey(vecIdStart + i)); // return apps; // public FVecDataOut(VectorGroup vg, int cidx, int ncols, int vecIdStart, Enum[] enums){ // this(vg,cidx,ncols,vecIdStart,enums,newAppendables(ncols,vg,vecIdStart)); public FVecDataOut(VectorGroup vg, int chunkOff, int cidx, Enum [] enums, AppendableVec [] appendables){ assert cidx - chunkOff >= 0:"incompatible cidx/chunkOff " + chunkOff + ", " + cidx; _vecs = appendables; _chunkOff = chunkOff; _enums = enums; _cidx = cidx; _vg = vg; _ctypes = MemoryManager.malloc1(appendables.length); _nvs = new NewChunk[appendables.length]; for(int i = 0; i < appendables.length; ++i) _nvs[i] = (NewChunk)_vecs[i].chunkForChunkIdx(_cidx); } @Override public FVecDataOut reduce(StreamDataOut sdout){ FVecDataOut dout = (FVecDataOut)sdout; _nChunks += dout._nChunks; if( dout!=null && _vecs != dout._vecs){ if(dout._vecs.length > _vecs.length){ AppendableVec [] v = _vecs; _vecs = dout._vecs; dout._vecs = v; } for(int i = 0; i < dout._vecs.length; ++i) _vecs[i].reduce(dout._vecs[i]); } return this; } @Override public FVecDataOut close(){ Futures fs = new Futures(); close(fs); fs.blockForPending(); return this; } public void check(){ if(_nvs != null) for(NewChunk nv:_nvs) assert (nv._len == _nLines):"unexpected number of lines in NewChunk, got " + nv._len + ", but expected " + _nLines; } @Override public FVecDataOut close(final Futures fs){ if( _nvs == null ) return this; // Might call close twice for(NewChunk nc:_nvs) assert nc._len == _nLines:"incompatible lengths after parsing chunk, " + _nLines + " != " + nc._len; RecursiveAction [] rs = new RecursiveAction[_nvs.length]; for(int i = 0; i < _nvs.length; ++i) { final int fi = i; rs[i] = new RecursiveAction() { @Override protected void compute() { _nvs[fi].close(_cidx, fs); _nvs[fi] = null; // Free for GC } }; } ForkJoinTask.invokeAll(rs); _nChunks++; _nvs = null; // Free for GC return this; } @Override public FVecDataOut nextChunk(){ return new FVecDataOut(_vg, _chunkOff,_cidx+1,_enums, _vecs); } // protected Vec [] closeVecs(){ // Futures fs = new Futures(); // _closedVecs = true; // Vec [] res = new Vec[_vecs.length]; // for(int i = 0; i < _vecs.length; ++i) // res[i] = _vecs[i].close(fs); // _vecs = null; // Free for GC // fs.blockForPending(); // return res; @Override public void newLine() { if(_col >= 0){ ++_nLines; for(int i = _col+1; i < _vecs.length; ++i) addInvalidCol(i); } _col = -1; } @Override public void addNumCol(int colIdx, long number, int exp) { if( colIdx < _vecs.length ) { _nvs[_col = colIdx].addNum(number, exp); if(_ctypes[colIdx] == UCOL ) _ctypes[colIdx] = NCOL; } } @Override public void addInvalidCol(int colIdx) { if(colIdx < _vecs.length) _nvs[_col = colIdx].addNA(); } @Override public final boolean isString(int colIdx) { return false; } @Override public final void addStrCol(int colIdx, ValueString str) { if(colIdx < _nvs.length){ if(_ctypes[colIdx] == NCOL){ // support enforced types addInvalidCol(colIdx); return; } if(_ctypes[colIdx] == UCOL && ParseTime.attemptTimeParse(str) > 0) _ctypes[colIdx] = TCOL; if( _ctypes[colIdx] == UCOL ) { // Attempt UUID parse int old = str.get_off(); ParseTime.attemptUUIDParse0(str); ParseTime.attemptUUIDParse1(str); if( str.get_off() != -1 ) _ctypes[colIdx] = ICOL; str.setOff(old); } if( _ctypes[colIdx] == TCOL ) { long l = ParseTime.attemptTimeParse(str); if( l == Long.MIN_VALUE ) addInvalidCol(colIdx); else { int time_pat = ParseTime.decodePat(l); // Get time pattern l = ParseTime.decodeTime(l); // Get time addNumCol(colIdx, l, 0); // Record time in msec _nvs[_col]._timCnt[time_pat]++; // Count histo of time parse patterns } } else if( _ctypes[colIdx] == ICOL ) { // UUID column? Only allow UUID parses long lo = ParseTime.attemptUUIDParse0(str); long hi = ParseTime.attemptUUIDParse1(str); if( str.get_off() == -1 ) { lo = C16Chunk._LO_NA; hi = C16Chunk._HI_NA; } if( colIdx < _vecs.length ) _nvs[_col = colIdx].addUUID(lo, hi); } else if(!_enums[_col = colIdx].isKilled()) { // store enum id into exponent, so that it will be interpreted as NA if compressing as numcol. int id = _enums[colIdx].addKey(str); if(_ctypes[colIdx] == UCOL && id > 1) _ctypes[colIdx] = ECOL; _nvs[colIdx].addEnum(id); } else // turn the column into NAs by adding value overflowing Enum.MAX_SIZE _nvs[colIdx].addEnum(Integer.MAX_VALUE); } //else System.err.println("additional column (" + colIdx + ":" + str + ") on line " + linenum()); } /** Adds double value to the column. */ @Override public void addNumCol(int colIdx, double value) { if (Double.isNaN(value)) { addInvalidCol(colIdx); } else { double d= value; int exp = 0; long number = (long)d; while (number != d) { d = d * 10; --exp; number = (long)d; } addNumCol(colIdx, number, exp); } } @Override public void setColumnNames(String [] names){} @Override public final void rollbackLine() {} @Override public void invalidLine(String err) { newLine(); } @Override public void invalidValue(int line, int col) {} } /** Parser data in taking data from fluid vec chunk. * @author tomasnykodym */ private static class FVecDataIn implements CustomParser.DataIn { final Vec _vec; Chunk _chk; int _idx; final long _firstLine; public FVecDataIn(Chunk chk){ _chk = chk; _idx = _chk.cidx(); _firstLine = _chk._start; _vec = chk._vec; } @Override public byte[] getChunkData(int cidx) { if(cidx != _idx) _chk = cidx < _vec.nChunks()?_vec.chunkForChunkIdx(_idx = cidx):null; return (_chk == null)?null:_chk._mem; } @Override public int getChunkDataStart(int cidx) { return -1; } @Override public void setChunkDataStart(int cidx, int offset) { } } }
package org.deidentifier.arx; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * This class provides access to the data types supported by the ARX framework * * @author Prasser, Kohlmayer */ public abstract class DataType<T> { /** * Base class for date/time types * @author Fabian Prasser */ public static class ARXDate extends DataType<Date> implements DataTypeWithFormat { /** The description of the data type*/ private static final DataTypeDescription<Date> description = new DataTypeDescription<Date>(Date.class, "Date/Time", true, listDateFormats()){ @Override public DataType<Date> newInstance() { return DATE; } @Override public DataType<Date> newInstance(String format) {return DATE(format);} }; private SimpleDateFormat format; private String string; private ARXDate() { string = "dd.MM.yyyy"; format = new SimpleDateFormat(string); } private ARXDate(final String format) { this.format = new SimpleDateFormat(format); this.string = format; } @Override public DataType<Date> clone() { return new ARXDate(string); } @Override public int compare(final String s1, final String s2) throws ParseException { return format.parse(s1).compareTo(format.parse(s2)); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ARXDate other = (ARXDate) obj; if (string == null) { if (other.string != null) { return false; } } else if (!string.equals(other.string)) { return false; } return true; } @Override public Date fromString(String s) { try { return format.parse(s); } catch (ParseException e) { throw new RuntimeException(e); } } @Override public DataTypeDescription<Date> getDescription(){ return description; } @Override public String getFormat() { return string; } @Override public int hashCode() { if (string==null) return 0; else return string.hashCode(); } @Override public String toString() { return "Date(" + string + ")"; } @Override public String toString(Date s){ return format.format(s); } } /** * Base class for numeric types * @author Fabian Prasser */ public static class ARXDecimal extends DataType<Double> implements DataTypeWithFormat { /** The description of the data type*/ private static final DataTypeDescription<Double> description = new DataTypeDescription<Double>(Double.class, "Decimal", true, listDecimalFormats()){ @Override public DataType<Double> newInstance() { return DECIMAL; } @Override public DataType<Double> newInstance(String format) {return DECIMAL(format);} }; private DecimalFormat format; private String string; private ARXDecimal(){ this.format = null; this.string = null; } private ARXDecimal(String format){ if (format != null){ this.format = new DecimalFormat(format); this.string = format; } else { this.format = null; this.string = null; } } @Override public DataType<Double> clone() { return this; } @Override public int compare(final String s1, final String s2) throws NumberFormatException { return fromString(s1).compareTo(fromString(s2)); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ARXDecimal other = (ARXDecimal) obj; if (string == null) { if (other.string != null) { return false; } } else if (!string.equals(other.string)) { return false; } return true; } @Override public Double fromString(String s) { if (format==null){ return Double.valueOf(s); } else { try { return format.parse(s).doubleValue(); } catch (ParseException e) { throw new NumberFormatException(e.getMessage()); } } } @Override public DataTypeDescription<Double> getDescription(){ return description; } @Override public String getFormat() { return string; } @Override public int hashCode() { if (string==null) return 0; else return string.hashCode(); } @Override public String toString() { return "Decimal"; } @Override public String toString(Double s){ if (format==null){ return String.valueOf(s); } else { return format.format(s); } } } /** * Base class for numeric types * @author Fabian Prasser */ public static class ARXInteger extends DataType<Long> implements DataTypeWithFormat { /** The description of the data type*/ private static final DataTypeDescription<Long> description = new DataTypeDescription<Long>(Long.class, "Integer", false, new ArrayList<String>()){ @Override public DataType<Long> newInstance() { return INTEGER; } @Override public DataType<Long> newInstance(String format) {return INTEGER(format);} }; private DecimalFormat format; private String string; private ARXInteger(){ this.format = null; this.string = null; } private ARXInteger(String format){ if (format != null){ this.format = new DecimalFormat(format); this.string = format; } else { this.format = null; this.string = null; } } @Override public DataType<Long> clone() { return this; } @Override public int compare(final String s1, final String s2) throws NumberFormatException { return fromString(s1).compareTo(fromString(s2)); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ARXInteger other = (ARXInteger) obj; if (string == null) { if (other.string != null) { return false; } } else if (!string.equals(other.string)) { return false; } return true; } @Override public Long fromString(String s) { if (format==null){ return Long.valueOf(s); } else { try { return format.parse(s).longValue(); } catch (ParseException e) { throw new NumberFormatException(e.getMessage()); } } } @Override public DataTypeDescription<Long> getDescription(){ return description; } @Override public String getFormat() { return string; } @Override public int hashCode() { if (string==null) return 0; else return string.hashCode(); } @Override public String toString() { return "Integer"; } @Override public String toString(Long s){ if (format==null){ return String.valueOf(s); } else { return format.format(s); } } } /** * Base class for string types * @author Fabian Prasser */ public static class ARXString extends DataType<String> { /** The description of the data type*/ private static final DataTypeDescription<String> description = new DataTypeDescription<String>(String.class, "String", false, new ArrayList<String>()){ @Override public DataType<String> newInstance() { return STRING; } @Override public DataType<String> newInstance(String format) {return STRING;} }; @Override public DataType<String> clone() { return this; } @Override public int compare(final String s1, final String s2) { return s1.compareTo(s2); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } return true; } @Override public String fromString(String s) { return s; } @Override public DataTypeDescription<String> getDescription(){ return description; } @Override public int hashCode() { return ARXString.class.hashCode(); } @Override public String toString() { return "String"; } @Override public String toString(String s){ return s; } } /** * An entry in the list of available data types * @author Fabian Prasser * @param <T> */ public static abstract class DataTypeDescription<T> { /** The wrapped java class*/ private Class<?> clazz; /** If yes, a list of available formats*/ private List<String> exampleFormats; /** Can the type be parameterized with a format string*/ private boolean hasFormat; /** A human readable label*/ private String label; /** * Internal constructor * @param label * @param hasFormat * @param exampleFormats */ private DataTypeDescription(Class<T> clazz, String label, boolean hasFormat, List<String> exampleFormats) { this.clazz = clazz; this.label = label; this.hasFormat = hasFormat; this.exampleFormats = exampleFormats; } /** * Returns a list of example formats * @return */ public List<String> getExampleFormats() { return exampleFormats; } /** * Returns a human readable label * @return */ public String getLabel() { return label; } /** * Returns the wrapped java class * @return */ public Class<?> getWrappedClass() { return clazz; } /** * Returns whether the type be parameterized with a format string. Note that every data type * can be instantiated without a format string, using a default format. * @return */ public boolean hasFormat() { return hasFormat; } /** * Creates a new instance with default format string * @return */ public abstract DataType<T> newInstance(); /** * Creates a new instance with the given format string * @param format * @return */ public abstract DataType<T> newInstance(String format); } /** * An interface for data types with format * @author Fabian Prasser */ public static interface DataTypeWithFormat { public abstract String getFormat(); } /** A date data type with default format dd.mm.yyyy */ public static final DataType<Date> DATE = new ARXDate(); /** A generic decimal data type */ public static final DataType<Double> DECIMAL = new ARXDecimal(); /** A generic integer data type */ public static final DataType<Long> INTEGER = new ARXInteger(); /** A string data type */ public static final DataType<String> STRING = new ARXString(); /** Provides a list of all available data types */ public static final List<DataTypeDescription<?>> LIST = listDataTypes(); /** * A date data type with given format * * @see SimpleDateFormat * @param format * @return */ public static final DataType<Date> DATE(final String format) { return new ARXDate(format); } /** * A decimal data type with given format * * @see DecimalFormat * @param format * @return */ public static final DataType<Double> DECIMAL(final String format) { return new ARXDecimal(format); } /** * An integer data type with given format * * @see DecimalFormat * @param format * @return */ public static final DataType<Long> INTEGER(final String format) { return new ARXInteger(format); } /** * Returns a datatype for the given class * @param clazz * @return */ @SuppressWarnings("unchecked") public static final <U> DataTypeDescription<U> LIST(Class<U> clazz){ for (DataTypeDescription<?> entry : LIST) { if (entry.getWrappedClass() == clazz) { return (DataTypeDescription<U>)entry; } } return null; } /** * Lists all available data types * @return */ private static final List<DataTypeDescription<?>> listDataTypes(){ List<DataTypeDescription<?>> list = new ArrayList<DataTypeDescription<?>>(); list.add(STRING.getDescription()); list.add(DATE.getDescription()); list.add(DECIMAL.getDescription()); list.add(INTEGER.getDescription()); return list; } /** * Provides a list of example formats for the <code>Date</code> data type * @return */ private static List<String> listDateFormats(){ List<String> result = new ArrayList<String>(); result.add("yyyy-MM-dd'T'HH:mm:ss'Z'"); result.add("yyyy-MM-ddZZ"); result.add("yyyy-MM-dd'T'HH:mm:ssz"); result.add("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); result.add("EEE MMM d hh:mm:ss z yyyy"); result.add("EEE MMM dd HH:mm:ss yyyy"); result.add("EEEE, dd-MMM-yy HH:mm:ss zzz"); result.add("EEE, dd MMM yyyy HH:mm:ss zzz"); result.add("EEE, dd MMM yy HH:mm:ss z"); result.add("EEE, dd MMM yy HH:mm z"); result.add("EEE, dd MMM yyyy HH:mm:ss z"); result.add("yyyy-MM-dd'T'HH:mm:ss"); result.add("EEE, dd MMM yyyy HH:mm:ss Z"); result.add("dd MMM yy HH:mm:ss z"); result.add("dd MMM yy HH:mm z"); result.add("'T'HH:mm:ss"); result.add("'T'HH:mm:ssZZ"); result.add("HH:mm:ss"); result.add("HH:mm:ssZZ"); result.add("yyyy-MM-dd"); result.add("yyyy-MM-dd hh:mm:ss"); result.add("yyyy-MM-dd HH:mm:ss"); result.add("yyyy-MM-dd'T'HH:mm:ssz"); result.add("yyyy-MM-dd'T'HH:mm:ss"); result.add("yyyy-MM-dd'T'HH:mm:ssZZ"); result.add("yyyy-MM-dd"); return result; } /** * Provides a list of example formats for the <code>Decimal</code> data type * @return */ private static List<String> listDecimalFormats(){ List<String> result = new ArrayList<String>(); result.add(" result.add(" result.add(" result.add("¤ return result; } @Override public abstract DataType<T> clone(); /** * Compares two values * @param s1 * @param s2 * @return * @throws NumberFormatException * @throws ParseException */ public abstract int compare(String s1, String s2) throws NumberFormatException, ParseException; /** * Converts a string into a value * @param s * @return */ public abstract T fromString(String s); /** * Returns a description of the data type * @return */ public abstract DataTypeDescription<T> getDescription(); /** * Converts a value into a string * @param t * @return */ public abstract String toString(T t); }
package org.xbill.DNS; import java.io.*; import java.util.*; /** * A cache of DNS records. The cache obeys TTLs, so items are purged after * their validity period is complete. Negative answers are cached, to * avoid repeated failed DNS queries. The credibility of each RRset is * maintained, so that more credible records replace less credible records, * and lookups can specify the minimum credibility of data they are requesting. * @see RRset * @see Credibility * * @author Brian Wellington */ public class Cache { private interface Element extends TypedObject { public boolean expired(); public int compareCredibility(int cred); public int getType(); } private static int limitExpire(long ttl, long maxttl) { if (maxttl >= 0 && maxttl < ttl) ttl = maxttl; int expire = (int)((System.currentTimeMillis() / 1000) + ttl); if (expire < 0 || expire > Integer.MAX_VALUE) return Integer.MAX_VALUE; return expire; } private static class CacheRRset extends RRset implements Element { int credibility; int expire; public CacheRRset(Record rec, int cred, long maxttl) { super(); this.credibility = cred; this.expire = limitExpire(rec.getTTL(), maxttl); addRR(rec); } public CacheRRset(RRset rrset, int cred, long maxttl) { super(rrset); this.credibility = cred; this.expire = limitExpire(rrset.getTTL(), maxttl); } public final boolean expired() { int now = (int)(System.currentTimeMillis() / 1000); return (now >= expire); } public final int compareCredibility(int cred) { return credibility - cred; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append(super.toString()); sb.append(" cl = "); sb.append(credibility); return sb.toString(); } } private static class NegativeElement implements Element { int type; Name name; SOARecord soa; int credibility; int expire; public NegativeElement(Name name, int type, SOARecord soa, int cred, long maxttl) { this.name = name; this.type = type; this.soa = soa; long cttl = 0; if (soa != null) cttl = soa.getMinimum(); this.credibility = cred; this.expire = limitExpire(cttl, maxttl); } public int getType() { return type; } public final boolean expired() { int now = (int)(System.currentTimeMillis() / 1000); return (now >= expire); } public final int compareCredibility(int cred) { return credibility - cred; } public String toString() { StringBuffer sb = new StringBuffer(); if (type == 0) sb.append("NXDOMAIN " + name); else sb.append("NXRRSET " + name + " " + Type.string(type)); sb.append(" cl = "); sb.append(credibility); return sb.toString(); } } private static class CacheMap extends LinkedHashMap { private int maxsize = -1; CacheMap(int maxsize) { super(16, (float) 0.75, true); this.maxsize = maxsize; } int getMaxSize() { return maxsize; } void setMaxSize(int maxsize) { /* * Note that this doesn't shrink the size of the map if * the maximum size is lowered, but it should shrink as * entries expire. */ this.maxsize = maxsize; } protected boolean removeEldestEntry(Map.Entry eldest) { return maxsize >= 0 && size() > maxsize; } } private CacheMap data; private int maxEntries = 50000; private int maxncache = -1; private int maxcache = -1; private int dclass; /** * Creates an empty Cache * * @param dclass The DNS class of this cache * @see DClass */ public Cache(int dclass) { this.dclass = dclass; data = new CacheMap(maxEntries); } /** * Creates an empty Cache * * @param dclass The DNS class of this cache * @param cleanInterval unused * @deprecated Use Cache(int) instead. */ public Cache(int dclass, int cleanInterval) { this(dclass); } /** * Creates an empty Cache for class IN. * @see DClass */ public Cache() { this(DClass.IN); } /** * Creates a Cache which initially contains all records in the specified file. */ public Cache(String file) throws IOException { data = new CacheMap(maxEntries); Master m = new Master(file); Record record; while ((record = m.nextRecord()) != null) addRecord(record, Credibility.HINT, m); } private synchronized Object exactName(Name name) { return data.get(name); } private synchronized void removeName(Name name) { data.remove(name); } private synchronized Element [] allElements(Object types) { if (types instanceof List) { List typelist = (List) types; int size = typelist.size(); return (Element []) typelist.toArray(new Element[size]); } else { Element set = (Element) types; return new Element[] {set}; } } private synchronized Element oneElement(Name name, Object types, int type, int minCred) { Element found = null; if (type == Type.ANY) throw new IllegalArgumentException("oneElement(ANY)"); if (types instanceof List) { List list = (List) types; for (int i = 0; i < list.size(); i++) { Element set = (Element) list.get(i); if (set.getType() == type) { found = set; break; } } } else { Element set = (Element) types; if (set.getType() == type) found = set; } if (found == null) return null; if (found.expired()) { removeElement(name, type); return null; } if (found.compareCredibility(minCred) < 0) return null; return found; } private synchronized Element findElement(Name name, int type, int minCred) { Object types = exactName(name); if (types == null) return null; return oneElement(name, types, type, minCred); } private synchronized void addElement(Name name, Element element) { Object types = data.get(name); if (types == null) { data.put(name, element); return; } int type = element.getType(); if (types instanceof List) { List list = (List) types; for (int i = 0; i < list.size(); i++) { Element elt = (Element) list.get(i); if (elt.getType() == type) { list.set(i, element); return; } } list.add(element); } else { Element elt = (Element) types; if (elt.getType() == type) data.put(name, element); else { LinkedList list = new LinkedList(); list.add(elt); list.add(element); data.put(name, list); } } } private synchronized void removeElement(Name name, int type) { Object types = data.get(name); if (types == null) { return; } if (types instanceof List) { List list = (List) types; for (int i = 0; i < list.size(); i++) { Element elt = (Element) list.get(i); if (elt.getType() == type) { list.remove(i); if (list.size() == 0) data.remove(name); return; } } } else { Element elt = (Element) types; if (elt.getType() != type) return; data.remove(name); } } /** Empties the Cache. */ public void clearCache() { synchronized (this) { data.clear(); } } /** * Adds a record to the Cache. * @param r The record to be added * @param cred The credibility of the record * @param o The source of the record (this could be a Message, for example) * @see Record */ public void addRecord(Record r, int cred, Object o) { Name name = r.getName(); int type = r.getRRsetType(); if (!Type.isRR(type)) return; Element element = findElement(name, type, cred); if (element == null) { CacheRRset crrset = new CacheRRset(r, cred, maxcache); addRRset(crrset, cred); } else if (element.compareCredibility(cred) == 0) { if (element instanceof CacheRRset) { CacheRRset crrset = (CacheRRset) element; crrset.addRR(r); } } } /** * Adds an RRset to the Cache. * @param rrset The RRset to be added * @param cred The credibility of these records * @see RRset */ public void addRRset(RRset rrset, int cred) { long ttl = rrset.getTTL(); Name name = rrset.getName(); int type = rrset.getType(); Element element = findElement(name, type, cred); if (ttl == 0) { if (element != null && element.compareCredibility(cred) < 0) removeElement(name, type); } else { if (element == null) { CacheRRset crrset; if (rrset instanceof CacheRRset) crrset = (CacheRRset) rrset; else crrset = new CacheRRset(rrset, cred, maxcache); addElement(name, crrset); } } } /** * Adds a negative entry to the Cache. * @param name The name of the negative entry * @param type The type of the negative entry * @param soa The SOA record to add to the negative cache entry, or null. * The negative cache ttl is derived from the SOA. * @param cred The credibility of the negative entry */ public void addNegative(Name name, int type, SOARecord soa, int cred) { long ttl = 0; if (soa != null) ttl = soa.getTTL(); Element element = findElement(name, type, cred); if (ttl == 0) { if (element != null && element.compareCredibility(cred) < 0) removeElement(name, type); } else { if (element == null) addElement(name, new NegativeElement(name, type, soa, cred, maxncache)); } } /** * Finds all matching sets or something that causes the lookup to stop. */ protected synchronized SetResponse lookup(Name name, int type, int minCred) { int labels; int tlabels; Element element; CacheRRset crrset; Name tname; Object types; SetResponse sr; labels = name.labels(); for (tlabels = labels; tlabels >= 1; tlabels boolean isRoot = (tlabels == 1); boolean isExact = (tlabels == labels); if (isRoot) tname = Name.root; else if (isExact) tname = name; else tname = new Name(name, labels - tlabels); types = data.get(tname); if (types == null) continue; /* If this is an ANY lookup, return everything. */ if (isExact && type == Type.ANY) { sr = new SetResponse(SetResponse.SUCCESSFUL); Element [] elements = allElements(types); int added = 0; for (int i = 0; i < elements.length; i++) { element = elements[i]; if (element.expired()) { removeElement(tname, element.getType()); continue; } if (!(element instanceof CacheRRset)) continue; if (element.compareCredibility(minCred) < 0) continue; sr.addRRset((CacheRRset)element); added++; } /* There were positive entries */ if (added > 0) return sr; } /* Look for an NS */ element = oneElement(tname, types, Type.NS, minCred); if (element != null && element instanceof CacheRRset) return new SetResponse(SetResponse.DELEGATION, (CacheRRset) element); /* * If this is the name, look for the actual type or a CNAME. * Otherwise, look for a DNAME. */ if (isExact) { element = oneElement(tname, types, type, minCred); if (element != null && element instanceof CacheRRset) { sr = new SetResponse(SetResponse.SUCCESSFUL); sr.addRRset((CacheRRset) element); return sr; } else if (element != null) { sr = new SetResponse(SetResponse.NXRRSET); return sr; } element = oneElement(tname, types, Type.CNAME, minCred); if (element != null && element instanceof CacheRRset) { return new SetResponse(SetResponse.CNAME, (CacheRRset) element); } } else { element = oneElement(tname, types, Type.DNAME, minCred); if (element != null && element instanceof CacheRRset) { return new SetResponse(SetResponse.DNAME, (CacheRRset) element); } } /* Check for the special NXDOMAIN element. */ if (isExact) { element = oneElement(tname, types, 0, minCred); if (element != null) return SetResponse.ofType(SetResponse.NXDOMAIN); } } return SetResponse.ofType(SetResponse.UNKNOWN); } /** * Looks up Records in the Cache. This follows CNAMEs and handles negatively * cached data. * @param name The name to look up * @param type The type to look up * @param minCred The minimum acceptable credibility * @return A SetResponse object * @see SetResponse * @see Credibility */ public SetResponse lookupRecords(Name name, int type, int minCred) { return lookup(name, type, minCred); } private RRset [] findRecords(Name name, int type, int minCred) { SetResponse cr = lookupRecords(name, type, minCred); if (cr.isSuccessful()) return cr.answers(); else return null; } /** * Looks up credible Records in the Cache (a wrapper around lookupRecords). * Unlike lookupRecords, this given no indication of why failure occurred. * @param name The name to look up * @param type The type to look up * @return An array of RRsets, or null * @see Credibility */ public RRset [] findRecords(Name name, int type) { return findRecords(name, type, Credibility.NORMAL); } /** * Looks up Records in the Cache (a wrapper around lookupRecords). Unlike * lookupRecords, this given no indication of why failure occurred. * @param name The name to look up * @param type The type to look up * @return An array of RRsets, or null * @see Credibility */ public RRset [] findAnyRecords(Name name, int type) { return findRecords(name, type, Credibility.GLUE); } private final int getCred(int section, boolean isAuth) { if (section == Section.ANSWER) { if (isAuth) return Credibility.AUTH_ANSWER; else return Credibility.NONAUTH_ANSWER; } else if (section == Section.AUTHORITY) { if (isAuth) return Credibility.AUTH_AUTHORITY; else return Credibility.NONAUTH_AUTHORITY; } else if (section == Section.ADDITIONAL) { return Credibility.ADDITIONAL; } else throw new IllegalArgumentException("getCred: invalid section"); } private static void markAdditional(RRset rrset, Set names) { Record first = rrset.first(); if (first.getAdditionalName() == null) return; Iterator it = rrset.rrs(); while (it.hasNext()) { Record r = (Record) it.next(); Name name = r.getAdditionalName(); if (name != null) names.add(name); } } /** * Adds all data from a Message into the Cache. Each record is added with * the appropriate credibility, and negative answers are cached as such. * @param in The Message to be added * @return A SetResponse that reflects what would be returned from a cache * lookup, or null if nothing useful could be cached from the message. * @see Message */ public SetResponse addMessage(Message in) { boolean isAuth = in.getHeader().getFlag(Flags.AA); Record question = in.getQuestion(); Name qname; Name curname; int qtype; int qclass; int cred; int rcode = in.getHeader().getRcode(); boolean haveAnswer = false; boolean completed = false; RRset [] answers, auth, addl; SetResponse response = null; boolean verbose = Options.check("verbosecache"); HashSet additionalNames; if ((rcode != Rcode.NOERROR && rcode != Rcode.NXDOMAIN) || question == null) return null; qname = question.getName(); qtype = question.getType(); qclass = question.getDClass(); curname = qname; additionalNames = new HashSet(); answers = in.getSectionRRsets(Section.ANSWER); for (int i = 0; i < answers.length; i++) { if (answers[i].getDClass() != qclass) continue; int type = answers[i].getType(); Name name = answers[i].getName(); cred = getCred(Section.ANSWER, isAuth); if ((type == qtype || qtype == Type.ANY) && name.equals(curname)) { addRRset(answers[i], cred); completed = true; haveAnswer = true; if (curname == qname) { if (response == null) response = new SetResponse( SetResponse.SUCCESSFUL); response.addRRset(answers[i]); } markAdditional(answers[i], additionalNames); } else if (type == Type.CNAME && name.equals(curname)) { CNAMERecord cname; addRRset(answers[i], cred); if (curname == qname) response = new SetResponse(SetResponse.CNAME, answers[i]); cname = (CNAMERecord) answers[i].first(); curname = cname.getTarget(); haveAnswer = true; } else if (type == Type.DNAME && curname.subdomain(name)) { DNAMERecord dname; addRRset(answers[i], cred); if (curname == qname) response = new SetResponse(SetResponse.DNAME, answers[i]); dname = (DNAMERecord) answers[i].first(); try { curname = curname.fromDNAME(dname); } catch (NameTooLongException e) { break; } haveAnswer = true; } } auth = in.getSectionRRsets(Section.AUTHORITY); RRset soa = null, ns = null; for (int i = 0; i < auth.length; i++) { if (auth[i].getType() == Type.SOA && curname.subdomain(auth[i].getName())) soa = auth[i]; else if (auth[i].getType() == Type.NS && curname.subdomain(auth[i].getName())) ns = auth[i]; } if (!completed) { /* This is a negative response or a referral. */ int cachetype = (rcode == Rcode.NXDOMAIN) ? 0 : qtype; if (soa != null || ns == null) { /* Negative response */ cred = getCred(Section.AUTHORITY, isAuth); SOARecord soarec = null; if (soa != null) soarec = (SOARecord) soa.first(); addNegative(curname, cachetype, soarec, cred); if (response == null) { int responseType; if (rcode == Rcode.NXDOMAIN) responseType = SetResponse.NXDOMAIN; else responseType = SetResponse.NXRRSET; response = SetResponse.ofType(responseType); } /* NXT records are not cached yet. */ } else { /* Referral response */ cred = getCred(Section.AUTHORITY, isAuth); addRRset(ns, cred); markAdditional(ns, additionalNames); if (response == null) response = new SetResponse( SetResponse.DELEGATION, ns); } } else if (rcode == Rcode.NOERROR && ns != null) { /* Cache the NS set from a positive response. */ cred = getCred(Section.AUTHORITY, isAuth); addRRset(ns, cred); markAdditional(ns, additionalNames); } addl = in.getSectionRRsets(Section.ADDITIONAL); for (int i = 0; i < addl.length; i++) { int type = addl[i].getType(); if (type != Type.A && type != Type.AAAA && type != Type.A6) continue; Name name = addl[i].getName(); if (!additionalNames.contains(name)) continue; cred = getCred(Section.ADDITIONAL, isAuth); addRRset(addl[i], cred); } if (verbose) System.out.println("addMessage: " + response); return (response); } /** * Flushes an RRset from the cache * @param name The name of the records to be flushed * @param type The type of the records to be flushed * @see RRset */ public void flushSet(Name name, int type) { removeElement(name, type); } /** * Flushes all RRsets with a given name from the cache * @param name The name of the records to be flushed * @see RRset */ public void flushName(Name name) { removeName(name); } /** * Sets the maximum length of time that a negative response will be stored * in this Cache. A negative value disables this feature (that is, sets * no limit). */ public void setMaxNCache(int seconds) { maxncache = seconds; } /** * Gets the maximum length of time that a negative response will be stored * in this Cache. A negative value indicates no limit. */ public int getMaxNCache() { return maxncache; } /** * Sets the maximum length of time that records will be stored in this * Cache. A negative value disables this feature (that is, sets no limit). */ public void setMaxCache(int seconds) { maxcache = seconds; } /** * Gets the maximum length of time that records will be stored * in this Cache. A negative value indicates no limit. */ public int getMaxCache() { return maxcache; } /** * Gets the current number of entries in the Cache, where an entry consists * of all records with a specific Name. */ public int getSize() { return data.size(); } /** * Gets the maximum number of entries in the Cache, where an entry consists * of all records with a specific Name. A negative value is treated as an * infinite limit. */ public int getMaxEntries() { return data.getMaxSize(); } /** * Sets the maximum number of entries in the Cache, where an entry consists * of all records with a specific Name. A negative value is treated as an * infinite limit. * * Note that setting this to a value lower than the current number * of entries will not cause the Cache to shrink immediately. * * The default maximum number of entries is 50000. * * @param entries The maximum number of entries in the Cache. */ public void setMaxEntries(int entries) { data.setMaxSize(entries); } /** * Returns the DNS class of this cache. */ public int getDClass() { return dclass; } /** * @deprecated Caches are no longer periodically cleaned. */ public void setCleanInterval(int cleanInterval) { } /** * Returns the contents of the Cache as a string. */ public String toString() { StringBuffer sb = new StringBuffer(); synchronized (this) { Iterator it = data.values().iterator(); while (it.hasNext()) { Element [] elements = allElements(it.next()); for (int i = 0; i < elements.length; i++) { sb.append(elements[i]); sb.append("\n"); } } } return sb.toString(); } }
package org.xbill.DNS; import java.util.*; /** * A set of Records with the same name, type, and class. Also included * are all SIG/RRSIG records signing the data records. * @see Record * @see SIGRecord * @see RRSIGRecord * * @author Brian Wellington */ public class RRset implements TypedObject { private List rrs; private List sigs; private int start; private int securityStatus; /** Creates an empty RRset */ public RRset() { rrs = new ArrayList(1); sigs = null; start = 0; securityStatus = DNSSEC.Insecure; } /** Creates an RRset with the contents of an existing RRset */ public RRset(RRset rrset) { synchronized (rrset) { rrs = (List) ((ArrayList)rrset.rrs).clone(); if (rrset.sigs != null) sigs = (List) ((ArrayList)rrset.sigs).clone(); securityStatus = rrset.securityStatus; } } /** Adds a Record to an RRset */ public synchronized void addRR(Record r) { if (!(r instanceof SIGBase)) { if (!rrs.contains(r)) rrs.add(r); start = 0; } else { if (sigs == null) sigs = new ArrayList(); if (!sigs.contains(r)) sigs.add(r); } } /** Deletes a Record from an RRset */ public synchronized void deleteRR(Record r) { if (!(r instanceof SIGBase)) { rrs.remove(r); start = 0; } else if (sigs != null) sigs.remove(r); } /** Deletes all Records from an RRset */ public synchronized void clear() { rrs.clear(); start = 0; sigs = null; } /** * Returns an Iterator listing all (data) records. This cycles through * the records, so each Iterator will start with a different record. */ public synchronized Iterator rrs() { int size = rrs.size(); if (size == 0) return Collections.EMPTY_LIST.iterator(); if (start == size) start = 0; if (start++ == 0) return (rrs.iterator()); List list = new ArrayList(rrs.subList(start - 1, size)); list.addAll(rrs.subList(0, start - 1)); return list.iterator(); } /** Returns an Iterator listing all signature records */ public synchronized Iterator sigs() { if (sigs == null) return Collections.EMPTY_LIST.iterator(); else return sigs.iterator(); } /** Returns the number of (data) records */ public int size() { return rrs.size(); } /** * Returns the name of the records * @see Name */ public Name getName() { Record r = first(); if (r == null) return null; return r.getName(); } /** * Returns the type of the records * @see Type */ public int getType() { Record r = first(); if (r == null) return 0; return r.getType(); } /** * Returns the class of the records * @see DClass */ public int getDClass() { Record r = first(); if (r == null) return 0; return r.getDClass(); } /** Returns the ttl of the records */ public synchronized long getTTL() { if (rrs.size() == 0) return 0; long ttl = 0xFFFFFFFFL; Iterator it = rrs.iterator(); while (it.hasNext()) { Record r = (Record)it.next(); if (r.getTTL() < ttl) ttl = r.getTTL(); } return ttl; } /** Returns the first record */ public Record first() { try { return (Record) rrs.get(0); } catch (IndexOutOfBoundsException e) { return null; } } /** Sets the DNSSEC security of the RRset. */ void setSecurity(int status) { securityStatus = status; } /** Returns the DNSSEC security of the RRset. */ public int getSecurity() { return securityStatus; } private String iteratorToString(Iterator it) { StringBuffer sb = new StringBuffer(); while (it.hasNext()) { Record rr = (Record) it.next(); sb.append("["); sb.append(rr.rdataToString()); sb.append("]"); if (it.hasNext()) sb.append(" "); } return sb.toString(); } /** Converts the RRset to a String */ public String toString() { if (rrs == null) return ("{empty}"); StringBuffer sb = new StringBuffer(); sb.append("{ "); sb.append(getName() + " "); sb.append(getTTL() + " "); sb.append(DClass.string(getDClass()) + " "); sb.append(Type.string(getType()) + " "); sb.append(iteratorToString(rrs.iterator())); if (sigs != null) { sb.append(" sigs: "); sb.append(iteratorToString(sigs.iterator())); } sb.append(" }"); return sb.toString(); } }
package hudson.model; import com.infradna.tool.bridge_method_injector.WithBridgeMethods; import hudson.Extension; import hudson.ExtensionPoint; import hudson.FilePath; import hudson.FileSystemProvisioner; import hudson.Launcher; import hudson.model.Descriptor.FormException; import hudson.model.Queue.Task; import hudson.model.labels.LabelAtom; import hudson.model.queue.CauseOfBlockage; import hudson.node_monitors.NodeMonitor; import hudson.remoting.VirtualChannel; import hudson.security.ACL; import hudson.security.AccessControlled; import hudson.security.Permission; import hudson.slaves.ComputerListener; import hudson.slaves.NodeDescriptor; import hudson.slaves.NodeProperty; import hudson.slaves.NodePropertyDescriptor; import hudson.slaves.OfflineCause; import hudson.util.ClockDifference; import hudson.util.DescribableList; import hudson.util.EnumConverter; import hudson.util.TagCloud; import hudson.util.TagCloud.WeightFunction; import java.io.IOException; import java.lang.reflect.Type; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.List; import java.util.logging.Logger; import net.sf.json.JSONObject; import org.kohsuke.stapler.BindInterceptor; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.export.ExportedBean; import org.kohsuke.stapler.export.Exported; /** * Base type of Hudson slaves (although in practice, you probably extend {@link Slave} to define a new slave type.) * * <p> * As a special case, {@link Hudson} extends from here. * * @author Kohsuke Kawaguchi * @see NodeMonitor * @see NodeDescriptor */ @ExportedBean public abstract class Node extends AbstractModelObject implements ReconfigurableDescribable<Node>, ExtensionPoint, AccessControlled { private static final Logger LOGGER = Logger.getLogger(Node.class.getName()); /** * Newly copied slaves get this flag set, so that Hudson doesn't try to start this node until its configuration * is saved once. */ protected volatile transient boolean holdOffLaunchUntilSave; public String getDisplayName() { return getNodeName(); // default implementation } public String getSearchUrl() { return "computer/"+getNodeName(); } public boolean isHoldOffLaunchUntilSave() { return holdOffLaunchUntilSave; } /** * Name of this node. * * @return * "" if this is master */ @Exported(visibility=999) public abstract String getNodeName(); /** * When the user clones a {@link Node}, Hudson uses this method to change the node name right after * the cloned {@link Node} object is instantiated. * * <p> * This method is never used for any other purpose, and as such for all practical intents and purposes, * the node name should be treated like immutable. * * @deprecated to indicate that this method isn't really meant to be called by random code. */ public abstract void setNodeName(String name); /** * Human-readable description of this node. */ @Exported public abstract String getNodeDescription(); /** * Returns a {@link Launcher} for executing programs on this node. * * <p> * The callee must call {@link Launcher#decorateFor(Node)} before returning to complete the decoration. */ public abstract Launcher createLauncher(TaskListener listener); /** * Returns the number of {@link Executor}s. * * This may be different from <code>getExecutors().size()</code> * because it takes time to adjust the number of executors. */ @Exported public abstract int getNumExecutors(); /** * Returns {@link Mode#EXCLUSIVE} if this node is only available * for those jobs that exclusively specifies this node * as the assigned node. */ @Exported public abstract Mode getMode(); /** * Gets the corresponding {@link Computer} object. * * @return * this method can return null if there's no {@link Computer} object for this node, * such as when this node has no executors at all. */ public final Computer toComputer() { return Hudson.getInstance().getComputer(this); } /** * Gets the current channel, if the node is connected and online, or null. * * This is just a convenience method for {@link Computer#getChannel()} with null check. */ public final VirtualChannel getChannel() { Computer c = toComputer(); return c==null ? null : c.getChannel(); } /** * Creates a new {@link Computer} object that acts as the UI peer of this {@link Node}. * Nobody but {@link Hudson#updateComputerList()} should call this method. */ protected abstract Computer createComputer(); /** * Let Nodes be aware of the lifecycle of their own {@link Computer}. */ @Extension public static class InternalComputerListener extends ComputerListener { @Override public void onOnline(Computer c, TaskListener listener) { Node node = c.getNode(); // At startup, we need to restore any previously in-effect temp offline cause. // We wait until the computer is started rather than getting the data to it sooner // so that the normal computer start up processing works as expected. if (node.temporaryOfflineCause != null && node.temporaryOfflineCause != c.getOfflineCause()) { c.setTemporarilyOffline(true, node.temporaryOfflineCause); } } } private OfflineCause temporaryOfflineCause; /** * Enable a {@link Computer} to inform its node when it is taken * temporarily offline. */ void setTemporaryOfflineCause(OfflineCause cause) { try { if (temporaryOfflineCause != cause) { temporaryOfflineCause = cause; Hudson.getInstance().save(); // Gotta be a better way to do this } } catch (java.io.IOException e) { LOGGER.warning("Unable to complete save, temporary offline status will not be persisted: " + e.getMessage()); } } /** * Return the possibly empty tag cloud for the labels of this node. */ public TagCloud<LabelAtom> getLabelCloud() { return new TagCloud<LabelAtom>(getAssignedLabels(),new WeightFunction<LabelAtom>() { public float weight(LabelAtom item) { return item.getTiedJobs().size(); } }); } /** * Returns the possibly empty set of labels that are assigned to this node, * including the automatic {@link #getSelfLabel() self label}, manually * assigned labels and dynamically assigned labels via the * {@link LabelFinder} extension point. * * This method has a side effect of updating the hudson-wide set of labels * and should be called after events that will change that - e.g. a slave * connecting. */ @Exported public Set<LabelAtom> getAssignedLabels() { Set<LabelAtom> r = Label.parse(getLabelString()); r.add(getSelfLabel()); r.addAll(getDynamicLabels()); return Collections.unmodifiableSet(r); } /** * Return all the labels assigned dynamically to this node. * This calls all the LabelFinder implementations with the node converts * the results into Labels. * @return HashSet<Label>. */ private HashSet<LabelAtom> getDynamicLabels() { HashSet<LabelAtom> result = new HashSet<LabelAtom>(); for (LabelFinder labeler : LabelFinder.all()) { // Filter out any bad(null) results from plugins // for compatibility reasons, findLabels may return LabelExpression and not atom. for (Label label : labeler.findLabels(this)) if (label instanceof LabelAtom) result.add((LabelAtom)label); } return result; } /** * Returns the manually configured label for a node. The list of assigned * and dynamically determined labels is available via * {@link #getAssignedLabels()} and includes all labels that have been * manually configured. * * Mainly for form binding. */ public abstract String getLabelString(); /** * Gets the special label that represents this node itself. */ @WithBridgeMethods(Label.class) public LabelAtom getSelfLabel() { return LabelAtom.get(getNodeName()); } /** * Called by the {@link Queue} to determine whether or not this node can * take the given task. The default checks include whether or not this node * is part of the task's assigned label, whether this node is in * {@link Mode#EXCLUSIVE} mode if it is not in the task's assigned label, * and whether or not any of this node's {@link NodeProperty}s say that the * task cannot be run. * * @since 1.360 */ public CauseOfBlockage canTake(Task task) { Label l = task.getAssignedLabel(); if(l!=null && !l.contains(this)) return CauseOfBlockage.fromMessage(Messages._Node_LabelMissing(getNodeName(),l)); // the task needs to be executed on label that this node doesn't have. if(l==null && getMode()== Mode.EXCLUSIVE) return CauseOfBlockage.fromMessage(Messages._Node_BecauseNodeIsReserved(getNodeName())); // this node is reserved for tasks that are tied to it // Check each NodeProperty to see whether they object to this node // taking the task for (NodeProperty prop: getNodeProperties()) { CauseOfBlockage c = prop.canTake(task); if (c!=null) return c; } // Looks like we can take the task return null; } /** * Returns a "workspace" directory for the given {@link TopLevelItem}. * * <p> * Workspace directory is usually used for keeping out the checked out * source code, but it can be used for anything. * * @return * null if this node is not connected hence the path is not available */ // TODO: should this be modified now that getWorkspace is moved from AbstractProject to AbstractBuild? public abstract FilePath getWorkspaceFor(TopLevelItem item); /** * Gets the root directory of this node. * * <p> * Hudson always owns a directory on every node. This method * returns that. * * @return * null if the node is offline and hence the {@link FilePath} * object is not available. */ public abstract FilePath getRootPath(); /** * Gets the {@link FilePath} on this node. */ public FilePath createPath(String absolutePath) { VirtualChannel ch = getChannel(); if(ch==null) return null; // offline return new FilePath(ch,absolutePath); } public FileSystemProvisioner getFileSystemProvisioner() { // TODO: make this configurable or auto-detectable or something else return FileSystemProvisioner.DEFAULT; } /** * Gets the {@link NodeProperty} instances configured for this {@link Node}. */ public abstract DescribableList<NodeProperty<?>, NodePropertyDescriptor> getNodeProperties(); // used in the Jelly script to expose descriptors public List<NodePropertyDescriptor> getNodePropertyDescriptors() { return NodeProperty.for_(this); } public ACL getACL() { return Hudson.getInstance().getAuthorizationStrategy().getACL(this); } public final void checkPermission(Permission permission) { getACL().checkPermission(permission); } public final boolean hasPermission(Permission permission) { return getACL().hasPermission(permission); } public Node reconfigure(StaplerRequest req, JSONObject form) throws FormException { if (form==null) return null; final JSONObject jsonForProperties = form.optJSONObject("nodeProperties"); BindInterceptor old = req.setBindListener(new BindInterceptor() { @Override public Object onConvert(Type targetType, Class targetTypeErasure, Object jsonSource) { if (jsonForProperties!=jsonSource) return DEFAULT; try { DescribableList<NodeProperty<?>, NodePropertyDescriptor> tmp = new DescribableList<NodeProperty<?>, NodePropertyDescriptor>(Saveable.NOOP,getNodeProperties().toList()); tmp.rebuild(req, jsonForProperties, NodeProperty.all()); return tmp.toList(); } catch (FormException e) { throw new IllegalArgumentException(e); } catch (IOException e) { throw new IllegalArgumentException(e); } } }); try { return getDescriptor().newInstance(req, form); } finally { req.setBindListener(old); } } public abstract NodeDescriptor getDescriptor(); /** * Estimates the clock difference with this slave. * * @return * always non-null. * @throws InterruptedException * if the operation is aborted. */ public abstract ClockDifference getClockDifference() throws IOException, InterruptedException; /** * Constants that control how Hudson allocates jobs to slaves. */ public enum Mode { NORMAL(Messages.Node_Mode_NORMAL()), EXCLUSIVE(Messages.Node_Mode_EXCLUSIVE()); private final String description; public String getDescription() { return description; } public String getName() { return name(); } Mode(String description) { this.description = description; } static { Stapler.CONVERT_UTILS.register(new EnumConverter(), Mode.class); } } }
package application.rest.v1; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import java.util.ArrayList; @Path("hello") public class Example { @GET @Produces(MediaType.TEXT_PLAIN) public String greet() throws java.net.UnknownHostException { List<String> list = new ArrayList<>(); //return a simple list of strings list.add("Some data"); return "Hello from "+ java.net.InetAddress.getLocalHost().getHostName(); } }
package com.couchbase.lite; import com.couchbase.lite.internal.RevisionInternal; import com.couchbase.lite.internal.InterfaceAudience; import com.couchbase.lite.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; /** * A CouchbaseLite document (as opposed to any specific revision of it.) */ public class Document { /** * The document's owning database. */ private Database database; /** * The document's ID. */ private String documentId; /** * The current/latest revision. This object is cached. */ private SavedRevision currentRevision; /** * Application-defined model object representing this document */ private Object model; /** * Change Listeners */ private List<ChangeListener> changeListeners = new ArrayList<ChangeListener>(); /** * Constructor * * @param database The document's owning database * @param documentId The document's ID */ @InterfaceAudience.Private public Document(Database database, String documentId) { this.database = database; this.documentId = documentId; } /** * Get the document's owning database. */ @InterfaceAudience.Public public Database getDatabase() { return database; } /** * Get the document's ID */ @InterfaceAudience.Public public String getId() { return documentId; } /** * Is this document deleted? (That is, does its current revision have the '_deleted' property?) * @return boolean to indicate whether deleted or not */ @InterfaceAudience.Public public boolean isDeleted() { return getCurrentRevision().isDeletion(); } /** * Get the ID of the current revision */ @InterfaceAudience.Public public String getCurrentRevisionId() { SavedRevision rev = getCurrentRevision(); if(rev == null){ return null; } return rev.getId(); } /** * Get the current revision */ @InterfaceAudience.Public public SavedRevision getCurrentRevision() { if (currentRevision == null) { currentRevision = getRevisionWithId(null); } return currentRevision; } /** * Returns the document's history as an array of CBLRevisions. (See SavedRevision's method.) * * @return document's history * @throws CouchbaseLiteException */ @InterfaceAudience.Public public List<SavedRevision> getRevisionHistory() throws CouchbaseLiteException { if (getCurrentRevision() == null) { Log.w(Database.TAG, "getRevisionHistory() called but no currentRevision"); return null; } return getCurrentRevision().getRevisionHistory(); } /** * Returns all the current conflicting revisions of the document. If the document is not * in conflict, only the single current revision will be returned. * * @return all current conflicting revisions of the document * @throws CouchbaseLiteException */ @InterfaceAudience.Public public List<SavedRevision> getConflictingRevisions() throws CouchbaseLiteException { return getLeafRevisions(false); } /** * Returns all the leaf revisions in the document's revision tree, * including deleted revisions (i.e. previously-resolved conflicts.) * * @return all the leaf revisions in the document's revision tree * @throws CouchbaseLiteException */ @InterfaceAudience.Public public List<SavedRevision> getLeafRevisions() throws CouchbaseLiteException { return getLeafRevisions(true); } /** * The contents of the current revision of the document. * This is shorthand for self.currentRevision.properties. * Any keys in the dictionary that begin with "_", such as "_id" and "_rev", contain CouchbaseLite metadata. * * @return contents of the current revision of the document. */ @InterfaceAudience.Public public Map<String,Object> getProperties() { return getCurrentRevision().getProperties(); } /** * The user-defined properties, without the ones reserved by CouchDB. * This is based on -properties, with every key whose name starts with "_" removed. * * @return user-defined properties, without the ones reserved by CouchDB. */ @InterfaceAudience.Public public Map<String,Object> getUserProperties() { return getCurrentRevision().getUserProperties(); } /** * Deletes this document by adding a deletion revision. * This will be replicated to other databases. * * @return boolean to indicate whether deleted or not * @throws CouchbaseLiteException */ @InterfaceAudience.Public public boolean delete() throws CouchbaseLiteException { return getCurrentRevision().deleteDocument() != null; } /** * Purges this document from the database; this is more than deletion, it forgets entirely about it. * The purge will NOT be replicated to other databases. * * @return boolean to indicate whether purged or not * @throws CouchbaseLiteException */ @InterfaceAudience.Public public boolean purge() throws CouchbaseLiteException { Map<String, List<String>> docsToRevs = new HashMap<String, List<String>>(); List<String> revs = new ArrayList<String>(); revs.add("*"); docsToRevs.put(documentId, revs); database.purgeRevisions(docsToRevs); database.removeDocumentFromCache(this); return true; } /** * The revision with the specified ID. * * * @param id the revision ID * @return the SavedRevision object */ @InterfaceAudience.Public public SavedRevision getRevision(String id) { if (id.equals(currentRevision.getId())) { return currentRevision; } EnumSet<Database.TDContentOptions> contentOptions = EnumSet.noneOf(Database.TDContentOptions.class); RevisionInternal revisionInternal = database.getDocumentWithIDAndRev(getId(), id, contentOptions); SavedRevision revision = null; revision = getRevisionFromRev(revisionInternal); return revision; } /** * Creates an unsaved new revision whose parent is the currentRevision, * or which will be the first revision if the document doesn't exist yet. * You can modify this revision's properties and attachments, then save it. * No change is made to the database until/unless you save the new revision. * * @return the newly created revision */ @InterfaceAudience.Public public UnsavedRevision createRevision() { return new UnsavedRevision(this, getCurrentRevision()); } /** * Shorthand for getProperties().get(key) */ @InterfaceAudience.Public public Object getProperty(String key) { return getCurrentRevision().getProperties().get(key); } /** * Saves a new revision. The properties dictionary must have a "_rev" property * whose ID matches the current revision's (as it will if it's a modified * copy of this document's .properties property.) * * @param properties the contents to be saved in the new revision * @return a new SavedRevision */ @InterfaceAudience.Public public SavedRevision putProperties(Map<String,Object> properties) throws CouchbaseLiteException { String prevID = (String) properties.get("_rev"); return putProperties(properties, prevID); } /** * Saves a new revision by letting the caller update the existing properties. * This method handles conflicts by retrying (calling the block again). * The DocumentUpdater implementation should modify the properties of the new revision and return YES to save or * NO to cancel. Be careful: the DocumentUpdater can be called multiple times if there is a conflict! * * @param updater the callback DocumentUpdater implementation. Will be called on each * attempt to save. Should update the given revision's properties and then * return YES, or just return NO to cancel. * @return The new saved revision, or null on error or cancellation. * @throws CouchbaseLiteException */ @InterfaceAudience.Public public SavedRevision update(DocumentUpdater updater) throws CouchbaseLiteException { int lastErrorCode = Status.UNKNOWN; do { UnsavedRevision newRev = createRevision(); if (updater.update(newRev) == false) { break; } try { SavedRevision savedRev = newRev.save(); if (savedRev != null) { return savedRev; } } catch (CouchbaseLiteException e) { lastErrorCode = e.getCBLStatus().getCode(); } } while (lastErrorCode == Status.CONFLICT); return null; } @InterfaceAudience.Public public void addChangeListener(ChangeListener changeListener) { changeListeners.add(changeListener); } @InterfaceAudience.Public public void removeChangeListener(ChangeListener changeListener) { changeListeners.remove(changeListener); } /** * Gets a reference to an optional application-defined model object representing this Document. */ @InterfaceAudience.Public public Object getModel() { return model; } /** * Sets a reference to an optional application-defined model object representing this Document. */ @InterfaceAudience.Public public void setModel(Object model) { this.model = model; } /** * Get the document's abbreviated ID */ public String getAbbreviatedId() { String abbreviated = documentId; if (documentId.length() > 10) { String firstFourChars = documentId.substring(0, 4); String lastFourChars = documentId.substring(abbreviated.length() - 4); return String.format("%s..%s", firstFourChars, lastFourChars); } return documentId; } List<SavedRevision> getLeafRevisions(boolean includeDeleted) throws CouchbaseLiteException { List<SavedRevision> result = new ArrayList<SavedRevision>(); RevisionList revs = database.getAllRevisionsOfDocumentID(documentId, true); for (RevisionInternal rev : revs) { // add it to result, unless we are not supposed to include deleted and it's deleted if (!includeDeleted && rev.isDeleted()) { // don't add it } else { result.add(getRevisionFromRev(rev)); } } return Collections.unmodifiableList(result); } SavedRevision putProperties(Map<String,Object> properties, String prevID) throws CouchbaseLiteException { String newId = null; if (properties != null && properties.containsKey("_id")) { newId = (String) properties.get("_id"); } if (newId != null && !newId.equalsIgnoreCase(getId())) { Log.w(Database.TAG, String.format("Trying to put wrong _id to this: %s properties: %s", this, properties)); } // Process _attachments dict, converting CBLAttachments to dicts: Map<String, Object> attachments = null; if (properties != null && properties.containsKey("__attachments")) { attachments = (Map<String, Object>) properties.get("_attachments"); } if (attachments != null && attachments.size() > 0) { Map<String, Object> updatedAttachments = Attachment.installAttachmentBodies(attachments, database); properties.put("_attachments", updatedAttachments); } boolean hasTrueDeletedProperty = false; if (properties != null) { hasTrueDeletedProperty = properties.get("_deleted") != null && ((Boolean)properties.get("_deleted")).booleanValue(); } boolean deleted = (properties == null) || hasTrueDeletedProperty; RevisionInternal rev = new RevisionInternal(documentId, null, deleted, database); if (properties != null) { rev.setProperties(properties); } RevisionInternal newRev = database.putRevision(rev, prevID, false); if (newRev == null) { return null; } return new SavedRevision(this, newRev); } SavedRevision getRevisionFromRev(RevisionInternal internalRevision) { if (internalRevision == null) { return null; } else if (currentRevision != null && internalRevision.getRevId().equals(currentRevision.getId())) { return currentRevision; } else { return new SavedRevision(this, internalRevision); } } SavedRevision getRevisionWithId(String revId) { if (revId != null && currentRevision != null && revId.equals(currentRevision.getId())) { return currentRevision; } return getRevisionFromRev( database.getDocumentWithIDAndRev(getId(), revId, EnumSet.noneOf(Database.TDContentOptions.class)) ); } public static interface DocumentUpdater { public boolean update(UnsavedRevision newRevision); } void loadCurrentRevisionFrom(QueryRow row) { if (row.getDocumentRevisionId() == null) { return; } String revId = row.getDocumentRevisionId(); if (currentRevision == null || revIdGreaterThanCurrent(revId)) { Map<String, Object> properties = row.getDocumentProperties(); if (properties != null) { RevisionInternal rev = new RevisionInternal(properties, row.getDatabase()); currentRevision = new SavedRevision(this, rev); } } } private boolean revIdGreaterThanCurrent(String revId) { return (RevisionInternal.CBLCompareRevIDs(revId, currentRevision.getId()) > 0); } void revisionAdded(DocumentChange documentChange) { // TODO: in the iOS code, it calls CBL_Revision* rev = change.winningRevision; RevisionInternal rev = documentChange.getRevisionInternal(); if (currentRevision != null && !rev.getRevId().equals(currentRevision.getId())) { currentRevision = new SavedRevision(this, rev); } DocumentChange change = DocumentChange.tempFactory(rev, null); for (ChangeListener listener : changeListeners) { listener.changed(new ChangeEvent(this, change)); } } public static class ChangeEvent { private Document source; private DocumentChange change; public ChangeEvent(Document source, DocumentChange documentChange) { this.source = source; this.change = documentChange; } public Document getSource() { return source; } public DocumentChange getChange() { return change; } } public static interface ChangeListener { public void changed(ChangeEvent event); } }
package com.home.server; import com.heroku.sdk.jdbc.DatabaseUrl; import com.home.db.DB; import com.home.db.HerokuPostgreSQL; import com.home.parser.PokemonParser; import org.telegram.telegrambots.ApiContextInitializer; import org.telegram.telegrambots.TelegramBotsApi; import org.telegram.telegrambots.api.methods.send.SendMessage; import org.telegram.telegrambots.api.objects.Message; import org.telegram.telegrambots.api.objects.Update; import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.exceptions.TelegramApiException; import java.net.URISyntaxException; import java.sql.ResultSet; import java.sql.SQLException; import static com.home.db.Constants.parseFromUrl; import static com.home.server.Constants.*; public class TelegramBot extends TelegramLongPollingBot { @Override public void onUpdateReceived(Update update) { // Receive message Message receivedMes = update.getMessage(); String answer = ""; // Check is blank if (receivedMes.hasText()) { // Input validation String[] pok_names = receivedMes.getText().split(" [v|V][s|S] "); if (pok_names.length > 0) { // Work with each pokemon for(String s : pok_names) { // Open connection with db DB db = null; try { db = new HerokuPostgreSQL(DatabaseUrl.extract().getConnection()); } catch (URISyntaxException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } // Try to find pokemon ResultSet pokeInfo = db.getPokemon(s); try { if (!pokeInfo.next()) { // If failed answer += "In db there are no pokemons named \'" + s + "\'\n"; } else { // Pokemon exists -> Format its info table // Normalize name(starts from uppercase) char[] lowerName = s.toCharArray(); String normalName = null; lowerName[0] = Character.toUpperCase(lowerName[0]); normalName = new String(lowerName); answer += (normalName + "\n"); // Stats String stats = String.format( " att def stam maxCP gainCP\n%5s%5s%6s%7s%8.1f", pokeInfo.getString("attack"), pokeInfo.getString("defense"), pokeInfo.getString("stamina"), pokeInfo.getString("max_cp"), Float.parseFloat(pokeInfo.getString("cp_gain")) ); answer += (stats + "\n"); } } catch (SQLException e) { e.printStackTrace(); } } } } if (answer.equals("")) answer = "I don't understand you( Please use following format:" + "\nPokemon_name vs Pokemon_name\nwhere \"Pokemon_name\" - any existing pokemon, case insensitive"; // Send answer SendMessage sendMes = new SendMessage(); sendMes.setChatId(receivedMes.getChatId().toString()); sendMes.setText(answer); try { sendMessage(sendMes); } catch (TelegramApiException e) { e.printStackTrace(); } } @Override public String getBotUsername() { return botName; } @Override public String getBotToken() { return botToken; } public static void main(String[] Args) { // Create remote db | Was run first time /*try { DB db = new HerokuPostgreSQL(DatabaseUrl.extract().getConnection()); db.createDB(); PokemonParser.parseToDB(parseFromUrl, db); } catch (SQLException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); }*/ // Start bot ApiContextInitializer.init(); TelegramBotsApi botsApi = new TelegramBotsApi(); try { botsApi.registerBot(new TelegramBot()); System.out.println("Bot is ready for work)"); } catch (TelegramApiException e) { e.printStackTrace(); } } }
package io.nats.client.examples; import io.nats.client.AsyncSubscription; import io.nats.client.ClosedCallback; import io.nats.client.Connection; import io.nats.client.ConnectionEvent; import io.nats.client.ConnectionFactory; import io.nats.client.DisconnectedCallback; import io.nats.client.ExceptionHandler; import io.nats.client.Message; import io.nats.client.MessageHandler; import io.nats.client.NATSException; import io.nats.client.Subscription; import io.nats.client.benchmark.Benchmark; import io.nats.client.benchmark.Sample; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Phaser; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; /** * A utility class for measuring NATS performance. * */ public class NatsBench { static final Logger log = LoggerFactory.getLogger(NatsBench.class); // Default test values private int numMsgs = 100000; private int numPubs = 1; private int numSubs = 0; private int size = 128; private String urls = ConnectionFactory.DEFAULT_URL; private String subject; private AtomicInteger sent = new AtomicInteger(); private AtomicInteger received = new AtomicInteger(); private String csvFileName; private ConnectionFactory cf; private Thread shutdownHook; private final AtomicBoolean shutdown = new AtomicBoolean(false); private boolean secure; private Benchmark bench; static final String usageString = "\nUsage: java NatsBench [-s server] [-tls] [-np num] [-ns num] [-n num] [-ms size] " + "[-csv file] <subject>\n\nOptions:\n" + " -s <urls> The nats server URLs (comma-separated)\n" + " -tls Use TLS secure connection\n" + " -np Number of concurrent publishers\n" + " -ns Number of concurrent subscribers\n" + " -n Number of messages to publish\n" + " -ms Size of the message\n" + " -csv Save bench data to csv file\n"; /** * Main constructor for NatsBench. * * @param args configuration parameters */ public NatsBench(String[] args) { if (args == null || args.length < 1) { usage(); return; } parseArgs(args); cf = new ConnectionFactory(urls); cf.setSecure(secure); cf.setReconnectAllowed(false); bench = new Benchmark("NATS", numSubs, numPubs); } class Worker implements Runnable { // protected final CountDownLatch startLatch; // protected final CountDownLatch doneLatch; protected final Phaser phaser; protected final int num; protected final int size; Worker(Phaser phaser, int numMsgs, int size) { this.phaser = phaser; this.num = numMsgs; this.size = size; } @Override public void run() {} } class SubWorker extends Worker { SubWorker(Phaser phaser, int numMsgs, int size) { super(phaser, numMsgs, size); } @Override public void run() { try { runSubscriber(); } catch (Exception e) { e.printStackTrace(); phaser.arrive(); } } public void runSubscriber() throws Exception { final Connection nc = cf.createConnection(); nc.setDisconnectedCallback(new DisconnectedCallback() { @Override public void onDisconnect(ConnectionEvent ev) { log.error("Subscriber disconnected after {} msgs", received.get()); } }); nc.setClosedCallback(new ClosedCallback() { @Override public void onClose(ConnectionEvent ev) { log.error("Subscriber connection closed after {} msgs", received.get()); } }); nc.setExceptionHandler(new ExceptionHandler() { @Override public void onException(NATSException ex) { log.error("Subscriber connection exception", ex); AsyncSubscription sub = (AsyncSubscription) ex.getSubscription(); log.error("Sent={}, Received={}", sent.get(), received.get()); log.error("Messages dropped (total) = {}", sub.getDropped()); System.exit(-1); } }); final long start = System.nanoTime(); Subscription sub = nc.subscribe(subject, new MessageHandler() { @Override public void onMessage(Message msg) { received.incrementAndGet(); if (received.get() >= numMsgs) { bench.addSubSample(new Sample(numMsgs, size, start, System.nanoTime(), nc)); phaser.arrive(); nc.setDisconnectedCallback(null); nc.setClosedCallback(null); nc.close(); } } }); sub.setPendingLimits(10000000, 1000000000); nc.flush(); phaser.arrive(); while (received.get() < numMsgs) { } } } class PubWorker extends Worker { PubWorker(Phaser phaser, int numMsgs, int size) { super(phaser, numMsgs, size); } @Override public void run() { try { runPublisher(); phaser.arrive(); } catch (Exception e) { e.printStackTrace(); phaser.arrive(); } } public void runPublisher() throws Exception { try (Connection nc = cf.createConnection()) { byte[] payload = null; if (size > 0) { payload = new byte[size]; } final long start = System.nanoTime(); for (int i = 0; i < numMsgs; i++) { sent.incrementAndGet(); nc.publish(subject, payload); } nc.flush(); bench.addPubSample(new Sample(numMsgs, size, start, System.nanoTime(), nc)); } } } /** * Runs the benchmark. * * @throws Exception if an exception occurs */ public void run() throws Exception { ExecutorService exec = Executors.newCachedThreadPool(); final Phaser phaser = new Phaser(); installShutdownHook(); phaser.register(); // Run Subscribers first for (int i = 0; i < numSubs; i++) { phaser.register(); exec.execute(new SubWorker(phaser, numMsgs, size)); } // Wait for subscribers threads to initialize phaser.arriveAndAwaitAdvance(); // Now publishers for (int i = 0; i < numPubs; i++) { phaser.register(); exec.execute(new PubWorker(phaser, numMsgs, size)); } System.out.printf("Starting benchmark [msgs=%d, msgsize=%d, pubs=%d, subs=%d]\n", numMsgs, size, numPubs, numSubs); // Wait for subscribers and publishers to finish phaser.arriveAndAwaitAdvance(); // We're done. Clean up and report. Runtime.getRuntime().removeShutdownHook(shutdownHook); bench.close(); System.out.println(bench.report()); if (csvFileName != null) { List<String> csv = bench.csv(); Path csvFile = Paths.get(csvFileName); Files.write(csvFile, csv, Charset.forName("UTF-8")); } } void installShutdownHook() { shutdownHook = new Thread(new Runnable() { @Override public void run() { System.err.println("\nCaught CTRL-C, shutting down gracefully...\n"); shutdown.set(true); System.err.printf("Sent=%d\n", sent.get()); System.err.printf("Received=%d\n", received.get()); } }); Runtime.getRuntime().addShutdownHook(shutdownHook); } void usage() { System.err.println(usageString); System.exit(-1); } long backlog() { return sent.get() - received.get(); } private void parseArgs(String[] args) { List<String> argList = new ArrayList<String>(Arrays.asList(args)); subject = argList.get(argList.size() - 1); argList.remove(argList.size() - 1); // Anything left is flags + args Iterator<String> it = argList.iterator(); while (it.hasNext()) { String arg = it.next(); switch (arg) { case "-s": case "--server": if (!it.hasNext()) { usage(); } it.remove(); urls = it.next(); it.remove(); continue; case "-tls": if (!it.hasNext()) { usage(); } it.remove(); secure = true; continue; case "-np": if (!it.hasNext()) { usage(); } it.remove(); numPubs = Integer.parseInt(it.next()); it.remove(); continue; case "-ns": if (!it.hasNext()) { usage(); } it.remove(); numSubs = Integer.parseInt(it.next()); it.remove(); continue; case "-n": if (!it.hasNext()) { usage(); } it.remove(); numMsgs = Integer.parseInt(it.next()); // hashModulo = numMsgs / 100; it.remove(); continue; case "-ms": if (!it.hasNext()) { usage(); } it.remove(); size = Integer.parseInt(it.next()); // hashModulo = numMsgs / 100; it.remove(); continue; case "-csv": if (!it.hasNext()) { usage(); } it.remove(); csvFileName = it.next(); it.remove(); continue; default: System.err.printf("Unexpected token: '%s'\n", arg); usage(); break; } } } /** * The main program executive. * * @param args command line arguments */ public static void main(String[] args) { try { new NatsBench(args).run(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } System.exit(0); } }
package com.tpg.nnode; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.stream.ActorMaterializer; import akka.stream.actor.AbstractActorPublisher; import akka.stream.javadsl.Source; import com.tpg.nnode.rabbit.RabbitQueueSourceActor; import com.tpg.pnode.rules.PasswordRule; import com.tpg.pnode.rules.Rule; import com.tpg.pnode.rules.RuleSet; import com.tpg.pnode.rules.RuleSetBuilder; import com.tpg.rabbit.RabbitConn; import org.easyrules.api.RulesEngine; import org.reactivestreams.Publisher; import scala.runtime.BoxedUnit; import java.io.IOException; import java.util.Set; public class ProcessingApp { public static void main(String[] args) throws IOException { ActorSystem aSys = ActorSystem.create("aSys"); ActorMaterializer aMaterializer = ActorMaterializer.create(aSys); ActorRef producer = aSys.actorOf(Props.create(RabbitQueueSourceActor.class), "producer"); Publisher<RabbitQueueSourceActor.RabbitMsg> pub = AbstractActorPublisher.create(producer); final ActorRef listener = aSys.actorOf(Props.create(ListenerActor.class, () -> new ListenerActor(producer)), "listener"); RabbitConn.setUpRabbit(aSys, listener); final RuleSet reSet = (new RuleSetBuilder()).add(new PasswordRule()).build(); final RulesEngine rulesEngine = reSet.getRulesEngine(); final Source<RabbitQueueSourceActor.RabbitMsg, BoxedUnit> rabbitMessagesSrc = Source.from(pub); rabbitMessagesSrc.runForeach( m -> { final String rm = m.getMsg(); System.out.println(String.format("Sink-ed: %s", rm)); reSet.setInput(rm); rulesEngine.fireRules(); }, aMaterializer); System.in.read(); aSys.shutdown(); } }
package com.vrachieru.cnp4j; import com.vrachieru.cnp4j.exception.InvalidCenturyException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public enum Century { NINETEENTH(1800, 1899), TWENTIETH(1900, 1999), TWENTY_FIRST(2000, 2999); private static Map<Integer, Century> MAPPING = new HashMap<Integer, Century>(); static { for (int i : Arrays.asList(3, 4)) { MAPPING.put(i, NINETEENTH); } for (int i : Arrays.asList(1, 2, 7, 8, 9)) { MAPPING.put(i, TWENTIETH); } for (int i : Arrays.asList(5, 6)) { MAPPING.put(i, TWENTY_FIRST); } } private int startYear; private int endYear; Century(int startYear, int endYear) { this.startYear = startYear; this.endYear = endYear; } public int getStartYear() { return this.startYear; } public int getEndYear() { return this.endYear; } public static Map<Integer, Century> getMapping() { return MAPPING; } public static Century getByCode(final int code) { if (!MAPPING.containsKey(code)) { throw new InvalidCenturyException(); } return MAPPING.get(code); } public static Century getFromYear(final int year) { if (year < NINETEENTH.startYear || year > TWENTY_FIRST.endYear) { throw new InvalidCenturyException(); } int century = year / 100 * 100; if (NINETEENTH.startYear == century) { return NINETEENTH; } else if (TWENTIETH.startYear == century) { return TWENTIETH; } else { return TWENTY_FIRST; } } }
package edu.mayo.query; import com.mongodb.BasicDBList; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import edu.mayo.ve.message.Querry; import edu.mayo.ve.message.SampleGroup; import java.util.ArrayList; import java.util.List; public class QueryBuilder { private enum Zygosity { HETEROZYGOUS, HOMOZYGOUS, EITHER }; /** * * Translates a {@link Querry} into an Aggregation Pipeline. * * NOTE: The documents are not limited in any way. This is done so that other downstream logic can optionally * add a $limit stage if it makes sense. * * @param q * The {@link Querry} object that captures the query state to be translated. * @return * A list of {@link DBObject}, each representing a stage of the Aggregation Pipeline. */ public static List<DBObject> buildAggregationPipeline(Querry q) { List<DBObject> stages = new ArrayList<DBObject>(); // stage that wraps the original find() query stages.add(buildWrapInMatchStage(q)); // add sample group stages for (SampleGroup grp: q.getSampleGroups()) { Zygosity zygosity; if (grp.getZygosity().equalsIgnoreCase("heterozygous")) { zygosity = Zygosity.HETEROZYGOUS; } else if (grp.getZygosity().equalsIgnoreCase("homozygous")) { zygosity = Zygosity.HOMOZYGOUS; } else { zygosity = Zygosity.EITHER; } // stage that looks for AT LEAST 1 match stages.add(buildMatchAtLeast1Stage(zygosity, grp.getSamples(), grp.isInSample())); // stage that checks the sample matches OR non-matches meets the criteria stages.add(buildCheckSamplesStage(zygosity, grp.getSamples(), grp.getMinMatchingSamplesInVariant(), grp.isInSample())); } return stages; } /** * Builds stage that takes the query created from {@link edu.mayo.ve.message.Querry#createQuery()} and * wraps it into a $match stage. * * @return An Aggregation Pipeline stage. */ private static DBObject buildWrapInMatchStage(Querry q) { DBObject query = q.createQuery(); DBObject matchStage = new BasicDBObject("$match", query); return matchStage; } /** * match variants where at least 1 sample from group matches * a sample in the current variant's HET/HOM array * * Example for zygosity=homozygous, group={A,B}, inSample=true: * <code> * * { * $match: { * $or: [ {"FORMAT.HomozygousList": "A"}, {"FORMAT.HomozygousList": "B"} ] * } * } * * </code> * * Example for zygosity=homozygous, group={A,B}, inSample=false: * <code> * * { * $match: { * $or: [ {"FORMAT.HomozygousList": {"$nin": ["A"]}}, {"FORMAT.HomozygousList": {"$nin": ["B"]}} ] * } * } * * </code> * * @param zygosity The {@link Zygosity} setting for the sample group. * @param sampleNames The samples that are part of the sample group. * @param inSample TRUE indicates "Sample in Group" and FALSE indicates "Sample Not In Group". * @return An Aggregation Pipeline stage. */ private static DBObject buildMatchAtLeast1Stage(Zygosity zygosity, List<String> sampleNames, boolean inSample) { BasicDBObject query; // dynamically build OR clause // inSample=true, AT LEAST 1 sample from the group should be in the HOM/HET/POS array // inSample=false, AT LEAST 1 sample from the group should NOT be in the HOM/HET/POS array BasicDBList orClauseArray = new BasicDBList(); for (String sample: sampleNames) { switch (zygosity) { case HETEROZYGOUS: orClauseArray.add(buildArrayCheckClause(inSample, "FORMAT.HeterozygousList", sample)); break; case HOMOZYGOUS: orClauseArray.add(buildArrayCheckClause(inSample, "FORMAT.HomozygousList", sample)); break; case EITHER: orClauseArray.add(buildArrayCheckClause(inSample, "FORMAT.GenotypePositiveList", sample)); break; } } query = new BasicDBObject("$or", orClauseArray); DBObject matchStage = new BasicDBObject("$match", query); return matchStage; } /** * Helper to build a clause that checks whether the given value is IN or NOT IN the specified array. * * @param inArray True if the given value should be IN the array. False if the value should NOT be in the array. * @param jsonArrayField The JSON array field to be checked. * @param value The value to check against the array. * @return The clause. */ private static DBObject buildArrayCheckClause(boolean inArray, String jsonArrayField, String value) { if (inArray) { // should be in the array return new BasicDBObject(jsonArrayField, value); } else { // should NOT be in the array BasicDBList ninArray = new BasicDBList(); ninArray.add(value); return new BasicDBObject(jsonArrayField, new BasicDBObject("$nin", ninArray)); } } /** * Keep only variant documents where # of missing samples <= inverseThreshold * * Example for zygosity=homozygous, group={A,B,C,D,E,F}, minMatches=4, inSample=true: * <code> * * { * $redact: { * $cond: { * if: { * $lte: [{$size: {$setDifference: [["A","B","C","D","E","F"], "$FORMAT.HomozygousList"]}}, 2] * }, * then: "$$KEEP", * else: "$$PRUNE" * } * } * } * * </code> * * Example for zygosity=homozygous, group={A,B,C,D,E,F}, minMatches=4, inSample=false: * <code> * * { * $redact: { * $cond: { * if: { * $lt: [{$size: {$setDifference: [["A","B","C","D","E","F"], "$FORMAT.HomozygousList"]}}, 4] * }, * then: "$$KEEP", * else: "$$PRUNE" * } * } * } * * </code> * * @param zygosity The {@link Zygosity} setting for the sample group. * @param sampleNames The samples that are part of the sample group. * @param minMatches The minimum # of sample matches between group and variant. * @param inSample TRUE indicates "Sample in Group" and FALSE indicates "Sample Not In Group". * @return An Aggregation Pipeline stage. */ private static DBObject buildCheckSamplesStage(Zygosity zygosity, List<String> sampleNames, int minMatches, boolean inSample) { final int maxMisses = sampleNames.size() - minMatches; BasicDBList groupSampleSet = new BasicDBList(); for (String sample: sampleNames) { groupSampleSet.add(sample); } BasicDBList setDiffArgs = new BasicDBList(); setDiffArgs.add(groupSampleSet); switch (zygosity) { case HETEROZYGOUS: setDiffArgs.add("$FORMAT.HeterozygousList"); break; case HOMOZYGOUS: setDiffArgs.add("$FORMAT.HomozygousList"); break; case EITHER: setDiffArgs.add("$FORMAT.GenotypePositiveList"); break; } DBObject missingSamples = new BasicDBObject("$setDifference", setDiffArgs); DBObject missingSampleCount = new BasicDBObject("$size", missingSamples); DBObject conditionalCheck; if (inSample) { // Looking at group samples IN the current variant // IF (# of missing samples) <= (maximum # of match misses between group and variant) BasicDBList ifCheckArgs = new BasicDBList(); ifCheckArgs.add(missingSampleCount); ifCheckArgs.add(maxMisses); conditionalCheck = new BasicDBObject("$lte", ifCheckArgs); } else { // Looking at group samples NOT IN the current variant // IF (# of missing samples) >= (minimum # of matches between group and variant) BasicDBList ifCheckArgs = new BasicDBList(); ifCheckArgs.add(missingSampleCount); ifCheckArgs.add(maxMisses); conditionalCheck = new BasicDBObject("$gt", ifCheckArgs); // ifCheckArgs.add(minMatches); // conditionalCheck = new BasicDBObject("$lte", ifCheckArgs); } BasicDBObject conditionVal = new BasicDBObject(); conditionVal.append("if", conditionalCheck); conditionVal.append("then", "$$KEEP"); conditionVal.append("else", "$$PRUNE"); DBObject condition = new BasicDBObject("$cond", conditionVal); DBObject redactStage = new BasicDBObject("$redact", condition); return redactStage; } }
package fizzbuzz; public class FizzBuzzCalculator { static final String FIZZ = "fizz"; static final String BUZZ = "buzz"; static final String FIZZ_BUZZ = FIZZ + BUZZ; static final String LUCKY = "lucky"; private static final int FIZZ_DIVISOR = 3; private static final int BUZZ_DIVISOR = 5; private static final String LUCKY_NUMBER = "3"; /** * Evaulate {@code fizzbuzz} to establish it's Fizz Buzz value. * @param fizzBuzz number to evaluate. * @return {@link #FIZZ}, {@link #BUZZ}, {@link #FIZZ_BUZZ} or the original integer. */ public String evaluate(final int fizzBuzz) { final String stringFizzBuzz = String.valueOf(fizzBuzz); final boolean isLucky = containsThree(stringFizzBuzz); final boolean isFizz = isDivisibleBy(fizzBuzz, FIZZ_DIVISOR); final boolean isBuzz = isDivisibleBy(fizzBuzz, BUZZ_DIVISOR); if (isLucky) { return LUCKY; } else if (isFizz && isBuzz) { return FIZZ_BUZZ; } else if (isFizz) { return FIZZ; } else if (isBuzz) { return BUZZ; } else { return stringFizzBuzz; } } private static boolean containsThree(final String fizzBuzz) { return fizzBuzz.contains(LUCKY_NUMBER); } private static boolean isDivisibleBy(final int dividend, final int divisor) { return dividend % divisor == 0; } }
package gvs.access; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.Socket; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import org.dom4j.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; /** * This class is the endpoint for each incoming connection. * * The class handles protocol commands and stores the incoming data in a xml * file. * * @author mwieland */ public class ClientConnection extends Thread { private final Socket socketClient; private final ConnectionMonitor monitor; private final ModelBuilder modelBuilder; private final GvsXmlReader xmlReader; // protocol messages private static final String OK = "OK"; private static final String FAILED = "FAILED"; private static final String DEFAULT_FILE_NAME = "input.xml"; private static final String THREAD_NAME = "Client Connection Thread"; private static final Logger logger = LoggerFactory .getLogger(ClientConnection.class); /** * Default constructor. * * @param client * incoming client connection. * @param modelBuilder * modelbuilder which processes the parsed xml. * @param monitor * monitor to reserve the GVS service * @param xmlReaderFactory * xml reader used to read the created xml */ @Inject public ClientConnection(ConnectionMonitor monitor, ModelBuilder modelBuilder, XmlReaderFactory xmlReaderFactory, @Assisted Socket client) { super(THREAD_NAME); this.modelBuilder = modelBuilder; this.socketClient = client; this.monitor = monitor; this.xmlReader = xmlReaderFactory.create(DEFAULT_FILE_NAME); } /** * Read the incoming protocol messages and interpret them. Try to get the * monitor lock of {@link ConnectionMonitor} If successful, read the * transfered data and store it locally in a XML file. */ @Override public void run() { processInputStream(); } /** * Read the input line by line. * */ private void processInputStream() { try (BufferedReader inputReader = new BufferedReader( new InputStreamReader(socketClient.getInputStream()))) { StringBuffer data = new StringBuffer(); String line; while ((line = inputReader.readLine()) != null) { int endCharIndex = line.indexOf(ProtocolCommand.DATA_END.toString()); if (line.equals(ProtocolCommand.RESERVE_GVS.toString())) { logger.info("Reserve command detected."); reserveService(); } else if (line.equals(ProtocolCommand.RELEASE_GVS.toString())) { logger.info("Release command detected."); releaseService(); break; } else if (endCharIndex != -1) { logger.info("End of data detected."); data.append(line.substring(0, endCharIndex)); storeDataOnFilesystem(data.toString()); readAndTransformModel(); data.setLength(0); } else { logger.info("Data detected"); data.append(line); } } } catch (IOException e) { logger.error("Unable to read incoming message of client {}", socketClient.getInetAddress(), e); } } /** * Try to get the monitor lock and send status message back to the client. * * @throws IOException * I/O error occurred when creating the output stream */ private void reserveService() throws IOException { String remoteHost = socketClient.getRemoteSocketAddress().toString(); try { monitor.reserveService(remoteHost); logger.info("Service reserved."); sendMessage(OK); } catch (InterruptedException e) { logger.info("Service busy."); sendMessage(FAILED); } } /** * Release monitor lock. */ private void releaseService() { String remoteHost = socketClient.getRemoteSocketAddress().toString(); monitor.releaseService(remoteHost); } /** * Send a message to the connected client * * @param message * hard coded message * * @throws IOException * I/O error occurred when creating the output stream */ private void sendMessage(String message) throws IOException { PrintStream outStream = new PrintStream(socketClient.getOutputStream(), true); outStream.println(message); } /** * Store the incoming data locally. * * @param line * data line * @throws IOException * io exception */ private void storeDataOnFilesystem(String line) throws IOException { Path path = Paths.get(DEFAULT_FILE_NAME); try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) { writer.write(line); writer.flush(); } } /** * Read the just written xml file and transform to graph model. */ private void readAndTransformModel() { logger.info("Build model from parsed xml"); Document document = xmlReader.read(); if (document != null) { modelBuilder.buildModelFromXML(document); } else { logger.warn("XmlReader could not read xml file."); } } }
package hu.bme.mit.spaceship; /** * A simple spaceship with two proton torpedos and four lasers */ public class GT4500 implements SpaceShip { private TorpedoStore primaryTorpedoStore; private TorpedoStore secondaryTorpedoStore; private boolean wasPrimaryFiredLast = false; public GT4500() { this.primaryTorpedoStore = new TorpedoStore(10); this.secondaryTorpedoStore = new TorpedoStore(10); } public boolean fireLasers(FiringMode firingMode) { return false; } /** * Tries to fire the torpedo stores of the ship. * * @param firingMode how many torpedo bays to fire * SINGLE: fires only one of the bays. * - For the first time the primary store is fired. * - To give some cooling time to the torpedo stores, torpedo stores are fired alternating. * - But if the store next in line is empty the ship tries to fire the other store. * - If the fired store reports a failure, the ship does not try to fire the other one. * ALL: tries to fire both of the torpedo stores. * * @return whether at least one torpedo was fired successfully */ @Override public boolean fireTorpedos(FiringMode firingMode) { boolean firingSuccess = false; if(firingMode == SINGLE){ if (wasPrimaryFiredLast) { // try to fire the secondary first if (! secondaryTorpedoStore.isEmpty()) { firingSuccess = secondaryTorpedoStore.fire(1); wasPrimaryFiredLast = false; } else { // although primary was fired last time, but the secondary is empty // thus try to fire primary again if (! primaryTorpedoStore.isEmpty()) { firingSuccess = primaryTorpedoStore.fire(1); wasPrimaryFiredLast = true; } // if both of the stores are empty, nothing can be done, return failure } } else { // try to fire the primary first if (! primaryTorpedoStore.isEmpty()) { firingSuccess = primaryTorpedoStore.fire(1); wasPrimaryFiredLast = true; } else { // although secondary was fired last time, but primary is empty // thus try to fire secondary again if (! secondaryTorpedoStore.isEmpty()) { firingSuccess = secondaryTorpedoStore.fire(1); wasPrimaryFiredLast = false; } // if both of the stores are empty, nothing can be done, return failure } } } else{ // try to fire both of the torpedos firingSuccess = (primaryTorpedoStore.fire(1) || secondaryTorpedoStore.fire(1)); } return firingSuccess; } }
package hudson.plugins.ec2; import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; import com.amazonaws.ClientConfiguration; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; import com.cloudbees.jenkins.plugins.awscredentials.AWSCredentialsImpl; import com.cloudbees.jenkins.plugins.awscredentials.AmazonWebServicesCredentials; import com.cloudbees.plugins.credentials.Credentials; import com.cloudbees.plugins.credentials.CredentialsMatchers; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.CredentialsScope; import com.cloudbees.plugins.credentials.CredentialsStore; import com.cloudbees.plugins.credentials.SystemCredentialsProvider; import com.cloudbees.plugins.credentials.common.StandardListBoxModel; import com.cloudbees.plugins.credentials.domains.Domain; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.Nullable; import hudson.ProxyConfiguration; import hudson.model.Computer; import hudson.model.Descriptor; import hudson.model.Hudson; import hudson.model.Label; import hudson.model.Node; import hudson.security.ACL; import hudson.slaves.Cloud; import hudson.slaves.NodeProvisioner.PlannedNode; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringReader; import java.io.StringWriter; import java.net.InetSocketAddress; import java.net.MalformedURLException; import java.net.Proxy; import java.net.URL; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.EnumSet; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.HashMap; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; import javax.servlet.ServletException; import hudson.model.TaskListener; import hudson.util.FormValidation; import hudson.util.HttpResponses; import hudson.util.ListBoxModel; import hudson.util.Secret; import hudson.util.StreamTaskListener; import jenkins.model.Jenkins; import org.apache.commons.lang.StringUtils; import org.kohsuke.stapler.HttpResponse; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import com.amazonaws.AmazonClientException; import com.amazonaws.ClientConfiguration; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.auth.InstanceProfileCredentialsProvider; import com.amazonaws.internal.StaticCredentialsProvider; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.ec2.model.CreateKeyPairRequest; import com.amazonaws.services.ec2.model.DescribeSpotInstanceRequestsRequest; import com.amazonaws.services.ec2.model.Filter; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.InstanceStateName; import com.amazonaws.services.ec2.model.InstanceType; import com.amazonaws.services.ec2.model.KeyPair; import com.amazonaws.services.ec2.model.KeyPairInfo; import com.amazonaws.services.ec2.model.Reservation; import com.amazonaws.services.ec2.model.SpotInstanceRequest; import com.amazonaws.services.ec2.model.Tag; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest; import hudson.ProxyConfiguration; import hudson.model.Computer; import hudson.model.Descriptor; import hudson.model.Hudson; import hudson.model.Label; import hudson.model.Node; import hudson.slaves.Cloud; import hudson.slaves.NodeProvisioner.PlannedNode; import hudson.util.FormValidation; import hudson.util.HttpResponses; import hudson.util.Secret; import hudson.util.StreamTaskListener; /** * Hudson's view of EC2. * * @author Kohsuke Kawaguchi */ public abstract class EC2Cloud extends Cloud { private static final Logger LOGGER = Logger.getLogger(EC2Cloud.class.getName()); public static final String DEFAULT_EC2_HOST = "us-east-1"; public static final String AWS_URL_HOST = "amazonaws.com"; public static final String EC2_SLAVE_TYPE_SPOT = "spot"; public static final String EC2_SLAVE_TYPE_DEMAND = "demand"; private static final SimpleFormatter sf = new SimpleFormatter(); private final boolean useInstanceProfileForCredentials; /** * Id of the {@link AmazonWebServicesCredentials} used to connect to Amazon ECS */ @CheckForNull private String credentialsId; @CheckForNull @Deprecated private transient String accessId; @CheckForNull @Deprecated private transient Secret secretKey; protected final EC2PrivateKey privateKey; /** * Upper bound on how many instances we may provision. */ public final int instanceCap; private final List<? extends SlaveTemplate> templates; private transient KeyPair usableKeyPair; protected transient AmazonEC2 connection; private static AWSCredentialsProvider awsCredentialsProvider; protected EC2Cloud(String id, boolean useInstanceProfileForCredentials, String credentialsId, String privateKey, String instanceCapStr, List<? extends SlaveTemplate> templates) { super(id); this.useInstanceProfileForCredentials = useInstanceProfileForCredentials; this.credentialsId = credentialsId; this.privateKey = new EC2PrivateKey(privateKey); if (templates == null) { this.templates = Collections.emptyList(); } else { this.templates = templates; } if (instanceCapStr.isEmpty()) { this.instanceCap = Integer.MAX_VALUE; } else { this.instanceCap = Integer.parseInt(instanceCapStr); } readResolve(); // set parents } public abstract URL getEc2EndpointUrl() throws IOException; public abstract URL getS3EndpointUrl() throws IOException; protected Object readResolve() { for (SlaveTemplate t : templates) t.parent = this; if (this.accessId != null && this.secretKey != null && credentialsId == null) { String secretKeyEncryptedValue = this.secretKey.getEncryptedValue(); // REPLACE this.accessId and this.secretId by a credential SystemCredentialsProvider systemCredentialsProvider = SystemCredentialsProvider.getInstance(); // ITERATE ON EXISTING CREDS AND DON'T CREATE IF EXIST for (Credentials credentials: systemCredentialsProvider.getCredentials()) { if (credentials instanceof AmazonWebServicesCredentials) { AmazonWebServicesCredentials awsCreds = (AmazonWebServicesCredentials) credentials; AWSCredentials awsCredentials = awsCreds.getCredentials(); if (accessId.equals(awsCredentials.getAWSAccessKeyId()) && Secret.toString(this.secretKey).equals(awsCredentials.getAWSSecretKey())) { this.credentialsId = awsCreds.getId(); this.accessId = null; this.secretKey = null; return this; } } } // CREATE for (CredentialsStore credentialsStore: CredentialsProvider.lookupStores(Jenkins.getInstance())) { if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) { try { String credsId = UUID.randomUUID().toString(); credentialsStore.addCredentials(Domain.global(), new AWSCredentialsImpl( CredentialsScope.SYSTEM, credsId, this.accessId, secretKeyEncryptedValue, "EC2 Cloud - " + getDisplayName())); this.credentialsId = credsId; this.accessId = null; this.secretKey = null; return this; } catch (IOException e) { this.credentialsId = null; LOGGER.log(Level.WARNING, "Exception converting legacy configuration to the new credentials API", e); } } } // PROBLEM, GLOBAL STORE NOT FOUND LOGGER.log(Level.WARNING, "EC2 Plugin could not migrate credentials to the Jenkins Global Credentials Store, EC2 Plugin for cloud {0} must be manually reconfigured", getDisplayName()); } return this; } public boolean isUseInstanceProfileForCredentials() { return useInstanceProfileForCredentials; } public String getCredentialsId() { return credentialsId; } public EC2PrivateKey getPrivateKey() { return privateKey; } public String getInstanceCapStr() { if (instanceCap == Integer.MAX_VALUE) return ""; else return String.valueOf(instanceCap); } public List<SlaveTemplate> getTemplates() { return Collections.unmodifiableList(templates); } public SlaveTemplate getTemplate(String template) { for (SlaveTemplate t : templates) { if (t.description.equals(template)) { return t; } } return null; } /** * Gets {@link SlaveTemplate} that has the matching {@link Label}. */ public SlaveTemplate getTemplate(Label label) { for (SlaveTemplate t : templates) { if (t.getMode() == Node.Mode.NORMAL) { if (label == null || label.matches(t.getLabelSet())) { return t; } } else if (t.getMode() == Node.Mode.EXCLUSIVE) { if (label != null && label.matches(t.getLabelSet())) { return t; } } } return null; } /** * Gets the {@link KeyPairInfo} used for the launch. */ public synchronized KeyPair getKeyPair() throws AmazonClientException, IOException { if (usableKeyPair == null) usableKeyPair = privateKey.find(connect()); return usableKeyPair; } /** * Debug command to attach to a running instance. */ public void doAttach(StaplerRequest req, StaplerResponse rsp, @QueryParameter String id) throws ServletException, IOException, AmazonClientException { checkPermission(PROVISION); SlaveTemplate t = getTemplates().get(0); StringWriter sw = new StringWriter(); StreamTaskListener listener = new StreamTaskListener(sw); EC2AbstractSlave node = t.attach(id, listener); Jenkins.getInstance().addNode(node); rsp.sendRedirect2(req.getContextPath() + "/computer/" + node.getNodeName()); } public HttpResponse doProvision(@QueryParameter String template) throws ServletException, IOException { checkPermission(PROVISION); if (template == null) { throw HttpResponses.error(SC_BAD_REQUEST, "The 'template' query parameter is missing"); } SlaveTemplate t = getTemplate(template); if (t == null) { throw HttpResponses.error(SC_BAD_REQUEST, "No such template: " + template); } try { List<EC2AbstractSlave> nodes = getNewOrExistingAvailableSlave(t, 1, true); if (nodes == null || nodes.isEmpty()) throw HttpResponses.error(SC_BAD_REQUEST, "Cloud or AMI instance cap would be exceeded for: " + template); //Reconnect a stopped instance, the ADD is invoking the connect only for the node creation Computer c = nodes.get(0).toComputer(); if (nodes.get(0).getStopOnTerminate() && c != null) { c.connect(false); } Jenkins.getInstance().addNode(nodes.get(0)); return HttpResponses.redirectViaContextPath("/computer/" + nodes.get(0).getNodeName()); } catch (AmazonClientException e) { throw HttpResponses.error(SC_INTERNAL_SERVER_ERROR, e); } } /** * Counts the number of instances in EC2 that can be used with the specified image and a template. Also removes any * nodes associated with canceled requests. * * @param template If left null, then all instances are counted. */ private int countCurrentEC2Slaves(SlaveTemplate template) throws AmazonClientException { LOGGER.log(Level.FINE, "Counting current slaves: " + (template != null ? (" AMI: " + template.getAmi()) : " All AMIS")); int n = 0; Set<String> instanceIds = new HashSet<String>(); String description = template != null ? template.description : null; for (Reservation r : connect().describeInstances().getReservations()) { for (Instance i : r.getInstances()) { if (isEc2ProvisionedAmiSlave(i.getTags(), description) && (template == null || template.getAmi().equals(i.getImageId()))) { InstanceStateName stateName = InstanceStateName.fromValue(i.getState().getName()); if (stateName != InstanceStateName.Terminated && stateName != InstanceStateName.ShuttingDown) { LOGGER.log(Level.FINE, "Existing instance found: " + i.getInstanceId() + " AMI: " + i.getImageId() + " Template: " + description); n++; instanceIds.add(i.getInstanceId()); } } } } List<SpotInstanceRequest> sirs = null; List<Filter> filters = new ArrayList<Filter>(); List<String> values; if (template != null) { values = new ArrayList<String>(); values.add(template.getAmi()); filters.add(new Filter("launch.image-id", values)); } values = new ArrayList<String>(); values.add(EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE); filters.add(new Filter("tag-key", values)); DescribeSpotInstanceRequestsRequest dsir = new DescribeSpotInstanceRequestsRequest().withFilters(filters); try { sirs = connect().describeSpotInstanceRequests(dsir).getSpotInstanceRequests(); } catch (Exception ex) { // Some ec2 implementations don't implement spot requests (Eucalyptus) LOGGER.log(Level.FINEST, "Describe spot instance requests failed", ex); } Set<SpotInstanceRequest> sirSet = new HashSet(); if (sirs != null) { for (SpotInstanceRequest sir : sirs) { sirSet.add(sir); if (sir.getState().equals("open") || sir.getState().equals("active")) { if (sir.getInstanceId() != null && instanceIds.contains(sir.getInstanceId())) continue; if (isEc2ProvisionedAmiSlave(sir.getTags(), description)) { LOGGER.log(Level.FINE, "Spot instance request found: " + sir.getSpotInstanceRequestId() + " AMI: " + sir.getInstanceId() + " state: " + sir.getState() + " status: " + sir.getStatus()); n++; if (sir.getInstanceId() != null) instanceIds.add(sir.getInstanceId()); } } else { // Canceled or otherwise dead for (Node node : Jenkins.getInstance().getNodes()) { try { if (!(node instanceof EC2SpotSlave)) continue; EC2SpotSlave ec2Slave = (EC2SpotSlave) node; if (ec2Slave.getSpotInstanceRequestId().equals(sir.getSpotInstanceRequestId())) { LOGGER.log(Level.INFO, "Removing dead request: " + sir.getSpotInstanceRequestId() + " AMI: " + sir.getInstanceId() + " state: " + sir.getState() + " status: " + sir.getStatus()); Jenkins.getInstance().removeNode(node); break; } } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to remove node for dead request: " + sir.getSpotInstanceRequestId() + " AMI: " + sir.getInstanceId() + " state: " + sir.getState() + " status: " + sir.getStatus(), e); } } } } } // Count nodes where the spot request does not yet exist (sometimes it takes time for the request to appear // in the EC2 API) for (Node node : Jenkins.getInstance().getNodes()) { if (!(node instanceof EC2SpotSlave)) continue; EC2SpotSlave ec2Slave = (EC2SpotSlave) node; SpotInstanceRequest sir = ec2Slave.getSpotRequest(); if (sir == null) { LOGGER.log(Level.FINE, "Found spot node without request: " + ec2Slave.getSpotInstanceRequestId()); n++; continue; } if (sirSet.contains(sir)) continue; sirSet.add(sir); if (sir.getState().equals("open") || sir.getState().equals("active")) { if (template != null) { List<Tag> instanceTags = sir.getTags(); for (Tag tag : instanceTags) { if (StringUtils.equals(tag.getKey(), EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE) && StringUtils.equals(tag.getValue(), getSlaveTypeTagValue(EC2_SLAVE_TYPE_SPOT, template.description)) && sir.getLaunchSpecification().getImageId().equals(template.getAmi())) { if (sir.getInstanceId() != null && instanceIds.contains(sir.getInstanceId())) continue; LOGGER.log(Level.FINE, "Spot instance request found (from node): " + sir.getSpotInstanceRequestId() + " AMI: " + sir.getInstanceId() + " state: " + sir.getState() + " status: " + sir.getStatus()); n++; if (sir.getInstanceId() != null) instanceIds.add(sir.getInstanceId()); } } } } } return n; } private boolean isEc2ProvisionedAmiSlave(List<Tag> tags, String description) { for (Tag tag : tags) { if (StringUtils.equals(tag.getKey(), EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE)) { if (description == null) { return true; } else if (StringUtils.equals(tag.getValue(), EC2Cloud.EC2_SLAVE_TYPE_DEMAND) || StringUtils.equals(tag.getValue(), EC2Cloud.EC2_SLAVE_TYPE_SPOT)) { // To handle cases where description is null and also upgrade cases for existing slave nodes. return true; } else if (StringUtils.equals(tag.getValue(), getSlaveTypeTagValue(EC2Cloud.EC2_SLAVE_TYPE_DEMAND, description)) || StringUtils.equals(tag.getValue(), getSlaveTypeTagValue(EC2Cloud.EC2_SLAVE_TYPE_SPOT, description))) { return true; } else { return false; } } } return false; } /** * Returns the maximum number of possible slaves that can be created. */ private int getPossibleNewSlavesCount(SlaveTemplate template) throws AmazonClientException { int estimatedTotalSlaves = countCurrentEC2Slaves(null); int estimatedAmiSlaves = countCurrentEC2Slaves(template); int availableTotalSlaves = instanceCap - estimatedTotalSlaves; int availableAmiSlaves = template.getInstanceCap() - estimatedAmiSlaves; LOGGER.log(Level.FINE, "Available Total Slaves: " + availableTotalSlaves + " Available AMI slaves: " + availableAmiSlaves + " AMI: " + template.getAmi() + " TemplateDesc: " + template.description); return Math.min(availableAmiSlaves, availableTotalSlaves); } /** * Obtains a slave whose AMI matches the AMI of the given template, and that also has requiredLabel (if requiredLabel is non-null) * forceCreateNew specifies that the creation of a new slave is required. Otherwise, an existing matching slave may be re-used */ private synchronized List<EC2AbstractSlave> getNewOrExistingAvailableSlave(SlaveTemplate t, int number, boolean forceCreateNew) { /* * Note this is synchronized between counting the instances and then allocating the node. Once the node is * allocated, we don't look at that instance as available for provisioning. */ int possibleSlavesCount = getPossibleNewSlavesCount(t); if (possibleSlavesCount <= 0) { LOGGER.log(Level.INFO, "{0}. Cannot provision - no capacity for instances: " + possibleSlavesCount, t); return null; } try { EnumSet<SlaveTemplate.ProvisionOptions> provisionOptions; if (forceCreateNew) provisionOptions = EnumSet.of(SlaveTemplate.ProvisionOptions.FORCE_CREATE); else provisionOptions = EnumSet.of(SlaveTemplate.ProvisionOptions.ALLOW_CREATE); if (number > possibleSlavesCount) { LOGGER.log(Level.INFO, String.format("%d nodes were requested for the template %s, " + "but because of instance cap only %d can be provisioned", number, t, possibleSlavesCount)); number = possibleSlavesCount; } return t.provision(number, provisionOptions); } catch (IOException e) { LOGGER.log(Level.WARNING, t + ". Exception during provisioning", e); return null; } } @Override public Collection<PlannedNode> provision(final Label label, int excessWorkload) { final SlaveTemplate t = getTemplate(label); List<PlannedNode> plannedNodes = new ArrayList<>(); try { LOGGER.log(Level.INFO, "{0}. Attempting to provision slave needed by excess workload of " + excessWorkload + " units", t); int number = Math.max(excessWorkload / t.getNumExecutors(), 1); final List<EC2AbstractSlave> slaves = getNewOrExistingAvailableSlave(t, number, false); if (slaves == null || slaves.isEmpty()) { LOGGER.warning("Can't raise nodes for " + t); return Collections.emptyList(); } for (final EC2AbstractSlave slave : slaves) { if (slave == null) { LOGGER.warning("Can't raise node for " + t); continue; } plannedNodes.add(createPlannedNode(t, slave)); excessWorkload -= t.getNumExecutors(); } LOGGER.log(Level.INFO, "{0}. Attempting provision finished, excess workload: " + excessWorkload, t); LOGGER.log(Level.INFO, "We have now {0} computers, waiting for {1} more", new Object[]{Jenkins.getInstance().getComputers().length, plannedNodes.size()}); return plannedNodes; } catch (AmazonClientException e) { LOGGER.log(Level.WARNING, t + ". Exception during provisioning", e); return Collections.emptyList(); } } private PlannedNode createPlannedNode(final SlaveTemplate t, final EC2AbstractSlave slave) { return new PlannedNode(t.getDisplayName(), Computer.threadPoolForRemoting.submit(new Callable<Node>() { public Node call() throws Exception { while (true) { String instanceId = slave.getInstanceId(); if (slave instanceof EC2SpotSlave) { if (((EC2SpotSlave) slave).isSpotRequestDead()) { LOGGER.log(Level.WARNING, "{0} Spot request died, can't do anything. Terminate provisioning", t); return null; } // Spot Instance does not have instance id yet. if (StringUtils.isEmpty(instanceId)) { Thread.sleep(5000); continue; } } Instance instance = CloudHelper.getInstance(instanceId, slave.getCloud()); if (instance == null) { LOGGER.log(Level.WARNING, "{0} Can't find instance with instance id `{1}` in cloud {2}. Terminate provisioning ", new Object[]{t, instanceId, slave.cloudName}); return null; } InstanceStateName state = InstanceStateName.fromValue(instance.getState().getName()); if (state.equals(InstanceStateName.Running)) { //Spot instance are not reconnected automatically, // but could be new orphans that has the option enable Computer c = slave.toComputer(); if (slave.getStopOnTerminate() && (c != null )) { c.connect(false); } long startTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - instance.getLaunchTime().getTime()); LOGGER.log(Level.INFO, "{0} Node {1} moved to RUNNING state in {2} seconds and is ready to be connected by Jenkins", new Object[]{t, slave.getNodeName(), startTime}); return slave; } if (!state.equals(InstanceStateName.Pending)) { LOGGER.log(Level.WARNING, "{0}. Node {1} is neither pending, neither running, it's {2}. Terminate provisioning", new Object[]{t, state, slave.getNodeName()}); return null; } Thread.sleep(5000); } } }) , t.getNumExecutors()); } @Override public boolean canProvision(Label label) { return getTemplate(label) != null; } private AWSCredentialsProvider createCredentialsProvider() { return createCredentialsProvider(useInstanceProfileForCredentials, credentialsId); } public static String getSlaveTypeTagValue(String slaveType, String templateDescription) { return templateDescription != null ? slaveType + "_" + templateDescription : slaveType; } public static AWSCredentialsProvider createCredentialsProvider(final boolean useInstanceProfileForCredentials, final String credentialsId) { if (useInstanceProfileForCredentials) { return new InstanceProfileCredentialsProvider(); } else if (StringUtils.isBlank(credentialsId)) { return new DefaultAWSCredentialsProviderChain(); } else { AmazonWebServicesCredentials credentials = getCredentials(credentialsId); if (credentials != null) return new StaticCredentialsProvider(credentials.getCredentials()); } return new DefaultAWSCredentialsProviderChain(); } @CheckForNull private static AmazonWebServicesCredentials getCredentials(@Nullable String credentialsId) { if (StringUtils.isBlank(credentialsId)) { return null; } return (AmazonWebServicesCredentials) CredentialsMatchers.firstOrNull( CredentialsProvider.lookupCredentials(AmazonWebServicesCredentials.class, Jenkins.getInstance(), ACL.SYSTEM, Collections.EMPTY_LIST), CredentialsMatchers.withId(credentialsId)); } /** * Connects to EC2 and returns {@link AmazonEC2}, which can then be used to communicate with EC2. */ public synchronized AmazonEC2 connect() throws AmazonClientException { try { if (connection == null) { connection = connect(createCredentialsProvider(), getEc2EndpointUrl()); } return connection; } catch (IOException e) { throw new AmazonClientException("Failed to retrieve the endpoint", e); } } /*** * Connect to an EC2 instance. * * @return {@link AmazonEC2} client */ public synchronized static AmazonEC2 connect(AWSCredentialsProvider credentialsProvider, URL endpoint) { awsCredentialsProvider = credentialsProvider; ClientConfiguration config = new ClientConfiguration(); config.setMaxErrorRetry(16); // Default retry limit (3) is low and often // cause problems. Raise it a bit. config.setSignerOverride("AWS4SignerType"); ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy; Proxy proxy = proxyConfig == null ? Proxy.NO_PROXY : proxyConfig.createProxy(endpoint.getHost()); if (!proxy.equals(Proxy.NO_PROXY) && proxy.address() instanceof InetSocketAddress) { InetSocketAddress address = (InetSocketAddress) proxy.address(); config.setProxyHost(address.getHostName()); config.setProxyPort(address.getPort()); if (null != proxyConfig.getUserName()) { config.setProxyUsername(proxyConfig.getUserName()); config.setProxyPassword(proxyConfig.getPassword()); } } AmazonEC2 client = new AmazonEC2Client(credentialsProvider, config); client.setEndpoint(endpoint.toString()); return client; } /*** * Convert a configured hostname like 'us-east-1' to a FQDN or ip address */ public static String convertHostName(String ec2HostName) { if (ec2HostName == null || ec2HostName.length() == 0) ec2HostName = DEFAULT_EC2_HOST; if (!ec2HostName.contains(".")) ec2HostName = "ec2." + ec2HostName + "." + AWS_URL_HOST; return ec2HostName; } /*** * Convert a user entered string into a port number "" -&gt; -1 to indicate default based on SSL setting */ public static Integer convertPort(String ec2Port) { if (ec2Port == null || ec2Port.length() == 0) return -1; return Integer.parseInt(ec2Port); } /** * Computes the presigned URL for the given S3 resource. * * @param path String like "/bucketName/folder/folder/abc.txt" that represents the resource to request. */ public URL buildPresignedURL(String path) throws AmazonClientException { AWSCredentials credentials = awsCredentialsProvider.getCredentials(); long expires = System.currentTimeMillis() + 60 * 60 * 1000; GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(path, credentials.getAWSSecretKey()); request.setExpiration(new Date(expires)); AmazonS3 s3 = new AmazonS3Client(credentials); return s3.generatePresignedUrl(request); } /* Parse a url or return a sensible error */ public static URL checkEndPoint(String url) throws FormValidation { try { return new URL(url); } catch (MalformedURLException ex) { throw FormValidation.error("Endpoint URL is not a valid URL"); } } public static abstract class DescriptorImpl extends Descriptor<Cloud> { public InstanceType[] getInstanceTypes() { return InstanceType.values(); } public FormValidation doCheckUseInstanceProfileForCredentials(@QueryParameter boolean value) { if (value) { try { new InstanceProfileCredentialsProvider().getCredentials(); } catch (AmazonClientException e) { return FormValidation.error(Messages.EC2Cloud_FailedToObtainCredentailsFromEC2(), e.getMessage()); } } return FormValidation.ok(); } public FormValidation doCheckPrivateKey(@QueryParameter String value) throws IOException, ServletException { boolean hasStart = false, hasEnd = false; BufferedReader br = new BufferedReader(new StringReader(value)); String line; while ((line = br.readLine()) != null) { if (line.equals(" hasStart = true; if (line.equals(" hasEnd = true; } if (!hasStart) return FormValidation.error("This doesn't look like a private key at all"); if (!hasEnd) return FormValidation .error("The private key is missing the trailing 'END RSA PRIVATE KEY' marker. Copy&paste error?"); return FormValidation.ok(); } protected FormValidation doTestConnection(URL ec2endpoint, boolean useInstanceProfileForCredentials, String credentialsId, String privateKey) throws IOException, ServletException { try { AWSCredentialsProvider credentialsProvider = createCredentialsProvider(useInstanceProfileForCredentials, credentialsId); AmazonEC2 ec2 = connect(credentialsProvider, ec2endpoint); ec2.describeInstances(); if (privateKey == null) return FormValidation.error("Private key is not specified. Click 'Generate Key' to generate one."); if (privateKey.trim().length() > 0) { // check if this key exists EC2PrivateKey pk = new EC2PrivateKey(privateKey); if (pk.find(ec2) == null) return FormValidation .error("The EC2 key pair private key isn't registered to this EC2 region (fingerprint is " + pk.getFingerprint() + ")"); } return FormValidation.ok(Messages.EC2Cloud_Success()); } catch (AmazonClientException e) { LOGGER.log(Level.WARNING, "Failed to check EC2 credential", e); return FormValidation.error(e.getMessage()); } } public FormValidation doGenerateKey(StaplerResponse rsp, URL ec2EndpointUrl, boolean useInstanceProfileForCredentials, String credentialsId) throws IOException, ServletException { try { AWSCredentialsProvider credentialsProvider = createCredentialsProvider(useInstanceProfileForCredentials, credentialsId); AmazonEC2 ec2 = connect(credentialsProvider, ec2EndpointUrl); List<KeyPairInfo> existingKeys = ec2.describeKeyPairs().getKeyPairs(); int n = 0; while (true) { boolean found = false; for (KeyPairInfo k : existingKeys) { if (k.getKeyName().equals("hudson-" + n)) found = true; } if (!found) break; n++; } CreateKeyPairRequest request = new CreateKeyPairRequest("hudson-" + n); KeyPair key = ec2.createKeyPair(request).getKeyPair(); rsp.addHeader("script", "findPreviousFormItem(button,'privateKey').value='" + key.getKeyMaterial().replace("\n", "\\n") + "'"); return FormValidation.ok(Messages.EC2Cloud_Success()); } catch (AmazonClientException e) { LOGGER.log(Level.WARNING, "Failed to check EC2 credential", e); return FormValidation.error(e.getMessage()); } } public ListBoxModel doFillCredentialsIdItems() { return new StandardListBoxModel() .withEmptySelection() .withMatching( CredentialsMatchers.always(), CredentialsProvider.lookupCredentials(AmazonWebServicesCredentials.class, Jenkins.getInstance(), ACL.SYSTEM, Collections.EMPTY_LIST)); } } public static void log(Logger logger, Level level, TaskListener listener, String message) { log(logger, level, listener, message, null); } public static void log(Logger logger, Level level, TaskListener listener, String message, Throwable exception) { logger.log(level, message, exception); if (listener != null) { if (exception != null) message += " Exception: " + exception; LogRecord lr = new LogRecord(level, message); lr.setLoggerName(LOGGER.getName()); PrintStream printStream = listener.getLogger(); printStream.print(sf.format(lr)); } } }
package javax.time; import java.util.Set; /** * Internal state class providing calendrical information and calculations. * <p> * CalendricalState is an abstract class and must be implemented with care to * ensure other classes in the framework operate correctly. * All instantiable subclasses must be final, immutable and thread-safe. * * @author Stephen Colebourne */ public abstract class CalendricalState { /** * Is the state contiguous, which is true if it defines time from a base * unit within a fixed range. * <p> * For example, time of day is contiguous as all points in time can be * determined within its boundaries. However, a calendrical object * representing 'Friday the Thirteenth' is not contiguous, as day of week * overlaps day of month. * * @return true if the field is contiguous */ public abstract boolean isContiguous(); /** * Gets the smallest duration unit of any of the contained fields. * <p> * If the calendrical is contiguous, this will be unambiguous. * * @return the smallest duration unit, never null */ public abstract DurationFieldRule getSmallestDurationUnit(); /** * Gets the largest duration range of any of the contained fields. * <p> * If the calendrical is contiguous, this will be unambiguous. * * @return the largest duration range, never null */ public abstract DurationFieldRule getLargestDurationRange(); /** * Checks is the specified field is supported. * * @param fieldRule the field rule to check, null returns false * @return true if the field is supported, false if not */ public abstract boolean isSupported(TimeFieldRule fieldRule); /** * Gets the value of the specified field. * * @param fieldRule the field rule to query, not null * @return the value for the requested field * @throws NullPointerException if the specified field rule is null * @throws UnsupportedOperationException if the field is not supported */ public abstract int get(TimeFieldRule fieldRule); /** * Gets the value of the specified field. * * @return the set of supported fields, never null * @throws NullPointerException if the specified field rule is null * @throws UnsupportedOperationException if the field is not supported */ public abstract Set<TimeFieldRule> getSupportedFields(); /** * Derive the value of the specified field. * * @param fieldRule the field rule to query, not null * @return the value for the requested field * @throws NullPointerException if the specified field rule is null * @throws UnsupportedOperationException if the field cannot be derived */ public abstract int getDerived(TimeFieldRule fieldRule); }
package com.braintreepayments.api.dropin.view; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.os.Build; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.LinearLayout; import com.braintreepayments.api.dropin.R; import com.braintreepayments.api.dropin.interfaces.AddPaymentUpdateListener; import com.braintreepayments.api.exceptions.BraintreeError; import com.braintreepayments.api.exceptions.ErrorWithResponse; import com.braintreepayments.api.models.Configuration; import com.braintreepayments.cardform.OnCardFormFieldFocusedListener; import com.braintreepayments.cardform.OnCardFormSubmitListener; import com.braintreepayments.cardform.view.CardEditText; import com.braintreepayments.cardform.view.CardForm; public class EditCardView extends LinearLayout implements OnCardFormFieldFocusedListener, OnClickListener, OnCardFormSubmitListener { private CardForm mCardForm; private AnimatedButtonView mAnimatedButtonView; private Configuration mConfiguration; private AddPaymentUpdateListener mListener; public EditCardView(Context context) { super(context); init(); } public EditCardView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public EditCardView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public EditCardView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(); } private void init() { if (isInEditMode()) { return; } setOrientation(VERTICAL); LayoutInflater.from(getContext()).inflate(R.layout.bt_edit_card, this); mCardForm = (CardForm) findViewById(R.id.bt_card_form); mCardForm.setOnFormFieldFocusedListener(this); mCardForm.setOnCardFormSubmitListener(this); mAnimatedButtonView = (AnimatedButtonView) findViewById(R.id.bt_animated_button_view); mAnimatedButtonView.setClickListener(this); } public void setup(Activity activity, Configuration configuration) { mConfiguration = configuration; mCardForm.cardRequired(true) .expirationRequired(true) .cvvRequired(configuration.isCvvChallengePresent()) .postalCodeRequired(configuration.isPostalCodeChallengePresent()) .setup(activity); } public void setAddPaymentUpdatedListener(AddPaymentUpdateListener listener) { mListener = listener; } public CardForm getCardForm() { return mCardForm; } public void setCardNumber(String cardNumber) { mCardForm.getCardEditText().setText(cardNumber); mCardForm.getCardEditText().focusNextView(); } public void setErrors(ErrorWithResponse errors) { BraintreeError cardErrors = errors.errorFor("creditCard"); if (cardErrors != null) { if (cardErrors.errorFor("number") != null) { mCardForm.setCardNumberError(getContext().getString(R.string.bt_card_number_invalid)); } if (cardErrors.errorFor("expirationYear") != null || cardErrors.errorFor("expirationMonth") != null || cardErrors.errorFor("expirationDate") != null) { mCardForm.setExpirationError(getContext().getString(R.string.bt_expiration_invalid)); } if (cardErrors.errorFor("cvv") != null) { mCardForm.setCvvError(getContext().getString(R.string.bt_cvv_invalid)); } if (cardErrors.errorFor("billingAddress") != null) { mCardForm.setPostalCodeError(getContext().getString(R.string.bt_postal_code_invalid)); } } } public void useUnionPay(Activity activity, boolean useUnionPay) { if (useUnionPay) { mCardForm.cardRequired(true) .expirationRequired(true) .cvvRequired(true) .postalCodeRequired(mConfiguration.isPostalCodeChallengePresent()) .mobileNumberRequired(true) .setup(activity); } } @Override public void onCardFormSubmit() { if (mCardForm.isValid()) { mAnimatedButtonView.showLoading(); if (mListener != null) { mListener.onPaymentUpdated(this); } } else { mAnimatedButtonView.showButton(); mCardForm.validate(); } } @Override public void onClick(View view) { onCardFormSubmit(); } @Override public void onCardFormFieldFocused(View field) { if (field instanceof CardEditText && mListener != null) { mListener.onBackRequested(this); } } @Override public void setVisibility(int visibility) { super.setVisibility(visibility); mAnimatedButtonView.showButton(); if (visibility == VISIBLE) { mCardForm.getExpirationDateEditText().requestFocus(); } } }
package kr.jm.utils.helper; import java.util.List; import java.util.regex.Pattern; import kr.jm.utils.AutoStringBuilder; public class JMString { public static final String COMMA = ","; public static final Pattern NUMBER_PATTERN = Pattern .compile("[+-]?\\d*(\\.\\d+)?"); public static final String lineSeperator = System .getProperty("line.separator"); public static boolean isNumber(String numberString) { return NUMBER_PATTERN.matcher(numberString).matches(); } public static List<String> splitLineByLine(String stringByLine) { return JMCollections .buildListWithDelimeter(stringByLine, lineSeperator); } public static String buildCsvString(List<String> stringList) { return buildCsvString(stringList.toArray(new String[stringList.size()])); } public static String buildCsvString(String... strings) { return new AutoStringBuilder(COMMA).append(strings).autoToString(); } public static boolean isNullOrEmpty(String keyTypeExpression) { return keyTypeExpression == null || "".equals(keyTypeExpression); } }
package me.pagar.model; import java.util.Collection; import java.util.Map; import javax.ws.rs.HttpMethod; import org.joda.time.DateTime; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.annotations.Expose; import com.google.gson.reflect.TypeToken; import java.util.HashMap; import java.util.List; import me.pagar.model.Transaction.PaymentMethod; import me.pagar.SubscriptionStatus; import me.pagar.util.JSONUtils; public class Subscription extends PagarMeModel<String> { @Expose(deserialize = false) private String cardHash; @Expose(deserialize = false) private String cardId; @Expose(deserialize = false) private String planId; @Expose private Customer customer; @Expose private String postbackUrl; @Expose private PaymentMethod paymentMethod; @Expose private DateTime currentPeriodStart; @Expose private DateTime currentPeriodEnd; @Expose private Map<String, Object> metadata; @Expose(deserialize = false) private Collection<SplitRule> splitRules; @Expose(serialize = false) private Plan plan; @Expose(serialize = false) private Transaction currentTransaction; @Expose(serialize = false) private Integer charges; @Expose(serialize = false) private SubscriptionStatus status; @Expose(serialize = false) private Phone phone; @Expose(serialize = false) private Address address; @Expose private Card card; @Expose private List<Integer> settledCharges; public Subscription save() throws PagarMeException { final Subscription saved = super.save(getClass()); copy(saved); return saved; } public Subscription find(String id) throws PagarMeException { final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s", getClassName(), id)); final Subscription other = JSONUtils.getAsObject((JsonObject) request.execute(), Subscription.class); copy(other); flush(); return other; } public Collection<Subscription> findCollection(Integer totalPerPage, Integer page) throws PagarMeException { return JSONUtils.getAsList(super.paginate(totalPerPage, page), new TypeToken<Collection<Subscription>>() { }.getType()); } public Subscription cancel() throws PagarMeException { validateId(); final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST, String.format("/%s/%s/cancel", getClassName(), getId())); final Subscription other = JSONUtils.getAsObject((JsonObject) request.execute(), Subscription.class); copy(other); flush(); return other; } public Collection<Transaction> transactions(Integer count, Integer page) throws PagarMeException { validateId(); final Transaction transaction = new Transaction(); final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s", getClassName(), getId(), transaction.getClassName())); Map<String, Object> params = new HashMap<String, Object>(); params.put("count", count); params.put("page", page); request.setParameters(params); return JSONUtils.getAsList((JsonArray) request.execute(), new TypeToken<Collection<Transaction>>() { }.getType()); } public Collection<Transaction> transactions() throws PagarMeException{ return transactions(10,1); } public Subscription refresh() throws PagarMeException { final Subscription other = JSONUtils.getAsObject(refreshModel(), Subscription.class); copy(other); flush(); return other; } public Collection<Postback> postbacks() throws PagarMeException { validateId(); final Postback postback = new Postback(); final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s", getClassName(), getId(), postback.getClassName())); return JSONUtils.getAsList((JsonArray) request.execute(), new TypeToken<Collection<Postback>>() { }.getType()); } public Postback postbacks(final String postbackId) throws PagarMeException { validateId(); final Postback postback = new Postback(); final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s/%s", getClassName(), getId(), postback.getClassName(), postbackId)); return JSONUtils.getAsObject((JsonObject) request.execute(), Postback.class); } public Subscription settleCharges(Integer chargesToSettle) throws PagarMeException { validateId(); final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST, String.format("/%s/%s/settle_charge", getClassName(), getId())); if (chargesToSettle != null) { Map<String, Object> charges = new HashMap<String, Object>(); charges.put("charges", chargesToSettle); request.setParameters(charges); } return JSONUtils.getAsObject((JsonObject) request.execute(), Subscription.class); } public Subscription settleCharges() throws PagarMeException { return settleCharges(null); } private void copy(Subscription other) { super.copy(other); this.plan = other.getPlan(); this.currentTransaction = other.getCurrentTransaction(); this.postbackUrl = other.getPostbackUrl(); this.currentPeriodStart = other.getCurrentPeriodStart(); this.currentPeriodEnd = other.getCurrentPeriodEnd(); this.charges = other.getCharges(); this.status = other.getStatus(); this.metadata = other.getMetadata(); this.customer = other.getCustomer(); this.paymentMethod = other.getPaymentMethod(); this.splitRules = other.getSplitRules(); this.phone = other.getPhone(); this.address = other.getAddress(); this.card = other.getCard(); this.settledCharges = other.getSettledCharges(); } public void setCreditCardSubscriptionWithCardHash(String planId, String cardHash, Customer customer) { this.planId = planId; this.cardHash = cardHash; this.customer = customer; this.paymentMethod = PaymentMethod.CREDIT_CARD; } public void setCreditCardSubscriptionWithCardId(String planId, String cardId, Customer customer) { this.planId = planId; this.cardId = cardId; this.customer = customer; this.paymentMethod = PaymentMethod.CREDIT_CARD; } public void setBoletoSubscription(String planId, Customer customer) { this.planId = planId; this.paymentMethod = PaymentMethod.BOLETO; this.customer = customer; } public void setRequiredUpdateParameters(String id) { setId(id); } @Deprecated public void setUpdatableParameters(String cardId, String cardHash, String planId) { this.planId = planId; this.cardId = cardId; this.cardHash = cardHash; } public void setPostbackUrl(String postbackUrl) { this.postbackUrl = postbackUrl; } public void setCardId(String cardId) { this.cardId = cardId; } public void setCardHash(String cardHash) { this.cardHash = cardHash; } public void setPlanId(String planId) { this.planId = planId; } public void setPaymentMethod(PaymentMethod paymentMethod) { this.paymentMethod = paymentMethod; } public void setSplitRules(final Collection<SplitRule> splitRules) { this.splitRules = splitRules; } public void setMetadata(final Map<String, Object> metadata) { this.metadata = metadata; } public String getCardHash() { return cardHash; } public String getCardId() { return cardId; } public String getPlanId() { return planId; } public Plan getPlan() { return plan; } public Transaction getCurrentTransaction() { return currentTransaction; } public String getPostbackUrl() { return postbackUrl; } public PaymentMethod getPaymentMethod() { return paymentMethod; } public Collection<SplitRule> getSplitRules() { return splitRules; } public DateTime getCurrentPeriodStart() { return currentPeriodStart; } public DateTime getCurrentPeriodEnd() { return currentPeriodEnd; } public Integer getCharges() { return charges; } public SubscriptionStatus getStatus() { return status; } public Phone getPhone() { return phone; } public Address getAddress() { return address; } public Customer getCustomer() { return customer; } public Card getCard() { return card; } public Map<String, Object> getMetadata() { return metadata; } public List<Integer> getSettledCharges() { return settledCharges; } }
package com.googlecode.iqapps.IQTimeSheet; import java.util.Locale; import android.app.AlertDialog; import android.app.Dialog; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.NotificationCompat; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.View; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.Checkable; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.github.rtyley.android.sherlock.roboguice.activity.RoboSherlockFragmentActivity; import com.github.rtyley.android.sherlock.roboguice.fragment.RoboSherlockDialogFragment; import com.googlecode.iqapps.TimeHelpers; public class TimeSheetActivity extends RoboSherlockFragmentActivity { // TabSwipeActivity private static final String TAG = "TimeSheetActivity"; protected static long day = TimeHelpers.millisNow(); /** * The {@link android.support.v4.view.PagerAdapter} that will provide * fragments for each of the sections. We use a * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which * will keep every loaded fragment in memory. If this becomes too memory * intensive, it may be best to switch to a * {@link android.support.v4.app.FragmentStatePagerAdapter}. */ SectionsPagerAdapter mSectionsPagerAdapter; /** * The {@link ViewPager} that will host the section contents. */ ViewPager mViewPager; private Menu optionsMenu; private static final int CROSS_DIALOG = 0x40; private static final int CONFIRM_RESTORE_DIALOG = 0x41; private static final int MY_NOTIFICATION_ID = 0x73; static PreferenceHelper prefs; // static NotificationManager notificationManager; static Notification myNotification; static PendingIntent contentIntent; // @Override protected void onCreateOff(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "onCreate"); setContentView(R.layout.activity_time_sheet); prefs = new PreferenceHelper(getApplicationContext()); // addTab("Test Frag", TestFragment.class, // TestFragment.createBundle("Test Fragment")); // addTab("Select Task", TaskSelectionFragment.class, // TaskSelectionFragment.createBundle("Select Task")); // addTab("Day Report", DayReportFragment.class, // DayReportFragment.createBundle("Day Report")); // addTab("Week Report", WeekReportFragment.class, // WeekReportFragment.createBundle("Week Report")); setSelected(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "onCreate"); setContentView(R.layout.activity_time_sheet); prefs = new PreferenceHelper(getApplicationContext()); // Create the adapter that will return a fragment for each of the three // primary sections of the app. mSectionsPagerAdapter = new SectionsPagerAdapter( getSupportFragmentManager()); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); mViewPager.setOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // Log.i(TAG, "Should I handle onPageScrolled??"); } @Override public void onPageSelected(int position) { switch (position) { case 0: { Log.d(TAG, "Selected task page"); refreshTaskListAdapter(); } case 1: { Log.d(TAG, "Selected day report page"); refreshReportListAdapter(); } case 2: { Log.d(TAG, "Selected week report page"); refreshWeekReportListAdapter(); } } } @Override public void onPageScrollStateChanged(int state) { // Log.i(TAG, "Should I handle onPageScrollStateChanged??"); } }); setSelected(); } public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getSupportMenuInflater().inflate(R.menu.time_sheet, menu); // Hanging on to this so it can be used for testing. optionsMenu = menu; return true; } /** * This method is called when the sending activity has finished, with the * result it supplied. * * @param requestCode * The original request code as given to startActivity(). * @param resultCode * From sending activity as per setResult(). * @param data * From sending activity as per setResult(). */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { TimeSheetDbAdapter db = new TimeSheetDbAdapter(getApplicationContext()); db.open(); // Check to see that what we received is what we wanted to see. if (requestCode == ActivityCodes.TASKADD.ordinal()) { // This is a standard resultCode that is sent back if the // activity doesn't supply an explicit result. It will also // be returned if the activity failed to launch. if (resultCode == RESULT_OK) { // Our protocol with the sending activity is that it will send // text in 'data' as its result. if (data != null) { try { if (!data.hasExtra("parent")) db.createTask(data.getAction()); else { db.createTask(data.getAction(), data.getStringExtra("parent"), data.getIntExtra("percentage", 100)); } } catch (NullPointerException e) { Log.d(TAG, "TaskAdd Result: " + e.toString()); } } try { refreshTaskListAdapter((ListView) findViewById(R.id.tasklistfragment)); } catch (NullPointerException e) { Log.d(TAG, "TaskAdd refreshTaskListAdapter: " + e.toString()); } } } else if (requestCode == ActivityCodes.TASKREVIVE.ordinal()) { // This one is a special case, since it has its own database // adapter, we let it change the state itself rather than passing // the result back to us. if (resultCode == RESULT_OK) { try { refreshTaskListAdapter((ListView) findViewById(R.id.tasklistfragment)); } catch (NullPointerException e) { Log.d(TAG, "TaskRevive refreshTaskListAdapter: " + e.toString()); } } } else if (requestCode == ActivityCodes.TASKEDIT.ordinal()) { if (resultCode == RESULT_OK) { if (data != null) { String result = data.getAction(); String oldData = null; Bundle extras = data.getExtras(); if (extras != null) { oldData = extras.getString("oldTaskName"); } // TODO: Determine what needs to be done to change these // database fields. if (data.hasExtra("parent")) { long taskID = db.getTaskIDByName(oldData); // int oldSplit = db.getSplitTaskFlag(oldData); long parentID = db.getTaskIDByName(data .getStringExtra("parent")); db.alterSplitTask(taskID, parentID, data.getIntExtra("percentage", 100), data.getIntExtra("split", 0)); } if (oldData != null && result != null) { db.renameTask(oldData, result); } } try { // refreshTaskListAdapter((ListView) // findViewById(R.id.tasklistfragment)); // refreshReportListAdapter((ListView) // findViewById(R.id.reportList)); // refreshWeekReportListAdapter((ListView) // findViewById(R.id.weekList)); refreshTaskListAdapter(); refreshReportListAdapter(); refreshWeekReportListAdapter(); } catch (NullPointerException e) { Log.d(TAG, "TaskEdit refreshTaskListAdapter: " + e.toString()); } } } db.close(); } public boolean onOptionsItemSelected(MenuItem menuItem) { switch (menuItem.getItemId()) { case R.id.menu_settings: { Intent intent = new Intent(getApplicationContext(), MyPreferenceActivity.class); try { startActivityForResult(intent, ActivityCodes.PREFS.ordinal()); } catch (RuntimeException e) { Log.e(TAG, "RuntimeException caught in " + "onOptionsItemSelected for MyPreferenceActivity"); Log.e(TAG, e.getLocalizedMessage()); } return true; } case R.id.menu_edit_day_entries: { Intent intent = new Intent(getApplicationContext(), EditDayEntriesHandler.class); try { startActivityForResult(intent, ActivityCodes.EDIT.ordinal()); } catch (RuntimeException e) { Log.e(TAG, "RuntimeException caught in " + "onOptionsItemSelected for EditDayEntriesHandler"); Log.e(TAG, e.getLocalizedMessage()); } return true; } case R.id.menu_revive_task: { Intent intent = new Intent(getApplicationContext(), ReviveTaskFragment.class); try { startActivityForResult(intent, ActivityCodes.TASKREVIVE.ordinal()); } catch (RuntimeException e) { Log.e(TAG, "RuntimeException caught in " + "onOptionsItemSelected for ReviveTaskHandler"); Log.e(TAG, e.getLocalizedMessage()); } return true; } case R.id.menu_new_task: { Intent intent = new Intent(getApplicationContext(), AddTaskHandler.class); try { startActivityForResult(intent, ActivityCodes.TASKADD.ordinal()); } catch (RuntimeException e) { Log.e(TAG, "RuntimeException caught in " + "onOptionsItemSelected for AddTaskHandler"); Log.e(TAG, e.getLocalizedMessage()); } return true; } case R.id.menu_backup: { if (!SDBackup.doSDBackup(TimeSheetDbAdapter.DATABASE_NAME, getApplicationContext().getPackageName())) { Log.w(TAG, "doSDBackup failed."); Toast.makeText(getApplicationContext(), "Database backup failed.", Toast.LENGTH_LONG).show(); } else { Log.i(TAG, "doSDBackup succeeded."); Toast.makeText(getApplicationContext(), "Database backup succeeded.", Toast.LENGTH_SHORT) .show(); } return true; } case R.id.menu_restore: { Log.d(TAG, "in onOptionsItemSelected (restore)"); if (prefs.getSDCardBackup()) { // showDialog(CONFIRM_RESTORE_DIALOG); RoboSherlockDialogFragment newFragment = MyYesNoDialog .newInstance(R.string.restore_title); newFragment.show(getSupportFragmentManager(), "restore_dialog"); } // FIXME: Need to trigger task list view refresh here!!! refreshTaskListAdapter(); setSelected(); return true; } case R.id.menu_about: { Intent intent = new Intent(getApplicationContext(), AboutDialog.class); try { startActivity(intent); } catch (RuntimeException e) { Log.e(TAG, "RuntimeException caught in " + "onOptionsItemSelected for AboutDialog"); Log.e(TAG, e.getLocalizedMessage()); } return true; } default: return super .onOptionsItemSelected((android.view.MenuItem) menuItem); } } /* * (non-Javadoc) * * @see android.app.Activity#onCreateContextMenu(android.view.ContextMenu, * android.view.View, android.view.ContextMenu.ContextMenuInfo) */ @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(0, ActivityCodes.EDIT_ID.ordinal(), 0, R.string.taskedit); menu.add(0, ActivityCodes.RETIRE_ID.ordinal(), 0, R.string.taskretire); } /* * (non-Javadoc) * * @see android.app.Activity#onContextItemSelected(android.view.MenuItem) */ @Override public boolean onContextItemSelected(android.view.MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); if (item.getItemId() == ActivityCodes.EDIT_ID.ordinal()) { Log.d(TAG, "Edit task: " + info.id); Intent intent = new Intent(getApplicationContext(), EditTaskHandler.class); intent.putExtra("taskName", ((TextView) info.targetView).getText() .toString()); try { startActivityForResult(intent, ActivityCodes.TASKEDIT.ordinal()); } catch (RuntimeException e) { Toast.makeText(getApplicationContext(), "RuntimeException", Toast.LENGTH_SHORT).show(); Log.d(TAG, e.getLocalizedMessage()); Log.e(TAG, "RuntimeException caught."); } refreshTaskListAdapter((ListView) info.targetView.getParent()); return true; } if (item.getItemId() == ActivityCodes.RETIRE_ID.ordinal()) { TimeSheetDbAdapter db = new TimeSheetDbAdapter( getApplicationContext()); db.open(); db.deactivateTask(((TextView) info.targetView).getText().toString()); db.close(); refreshTaskListAdapter((ListView) info.targetView.getParent()); return true; } return super.onContextItemSelected(item); } /** * Called when the activity is first created to create a dialog. */ @Override protected Dialog onCreateDialog(int dialogId) { Log.d(TAG, "In onCreateDialog"); Dialog dialog = null; AlertDialog.Builder builder; switch (dialogId) { case CROSS_DIALOG: builder = new AlertDialog.Builder(getApplicationContext()); builder.setMessage( "The last entry is still open from yesterday." + " What should I do?") .setCancelable(false) .setPositiveButton("Close", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { TimeSheetDbAdapter db = new TimeSheetDbAdapter( getApplicationContext()); db.closeEntry(); db.close(); clearSelected(); } }) .setNegativeButton("Close & Re-open", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { TimeSheetDbAdapter db = new TimeSheetDbAdapter( getApplicationContext()); long taskID = db.taskIDForLastClockEntry(); long now = TimeHelpers.millisNow(); long today = TimeHelpers .millisToStartOfDay(now); db.createEntry(taskID, today); db.close(); setSelected(); } }); dialog = builder.create(); break; // This may be dead code now... case CONFIRM_RESTORE_DIALOG: Log.d(TAG, "in onCreateDialog (restore)"); builder = new AlertDialog.Builder(getApplicationContext()); builder.setMessage( "This will overwrite the database." + " Proceed?") .setCancelable(true) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Log.d(TAG, "in onClick (restore dialog)"); if (!SDBackup.doSDRestore( TimeSheetDbAdapter.DATABASE_NAME, getApplicationContext() .getPackageName())) { Log.w(TAG, "doSDRestore failed."); Toast.makeText(getApplicationContext(), "Database restore failed.", Toast.LENGTH_LONG).show(); } else { Log.i(TAG, "doSDRestore succeeded."); Toast.makeText(getApplicationContext(), "Database restore succeeded.", Toast.LENGTH_SHORT).show(); } // fillData(); Log.d(TAG, "onCreateDialog restore dialog. Calling refreshTaskListAdapter"); // refreshTaskListAdapter((ListView) // findViewById(R.id.tasklistfragment)); refreshTaskListAdapter(); setSelected(); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); dialog = builder.create(); break; } return dialog; } /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to * one of the sections/tabs/pages. */ public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. // Return a DummySectionFragment (defined as a static inner class // below) with the page number as its lone argument. Fragment fragment = new SectionFragment(); Bundle args = new Bundle(); args.putInt(SectionFragment.ARG_SECTION_NUMBER, position + 1); fragment.setArguments(args); return fragment; } @Override public int getCount() { // Show 3 total pages. return 3; } @Override public CharSequence getPageTitle(int position) { Locale l = Locale.getDefault(); switch (position) { case 0: return getString(R.string.title_section1).toUpperCase(l); case 1: return getString(R.string.title_section2).toUpperCase(l); case 2: return getString(R.string.title_section3).toUpperCase(l); } return null; } } /** * Notify the task list that there are no items selected. */ void clearSelected() { Log.d(TAG, "in clearSelected()"); ListView myTaskList = (ListView) findViewById(R.id.tasklistfragment); if (myTaskList == null) { Log.i(TAG, "findViewByID(tasklistfragment) returned null."); return; } clearSelected(myTaskList); } /** * Notify the task list that there are no items selected. * * @param myTaskList * The view ID of the task list. */ void clearSelected(ListView myTaskList) { Log.d(TAG, "clearSelected"); myTaskList.clearChoices(); for (int i = 0; i < myTaskList.getCount(); i++) try { ((Checkable) myTaskList.getChildAt(i)).setChecked(false); } catch (NullPointerException e) { Log.d(TAG, "NullPointerException at item " + i); } } /** * Enable the currently selected item in the task list. */ void setSelected() { Log.d(TAG, "in setSelected()"); ListView myTaskList = (ListView) findViewById(R.id.tasklistfragment); if (myTaskList == null) { Log.i(TAG, "findViewByID(tasklistfragment) returned null."); return; } setSelected(myTaskList); } /** * Enable the currently selected item in the task list. * * @param myTaskList * The view ID of the task list. */ void setSelected(ListView myTaskList) { Log.d(TAG, "in setSelected"); TimeSheetDbAdapter db = new TimeSheetDbAdapter(getApplicationContext()); db.open(); long timeOut = db.timeOutForLastClockEntry(); Log.d(TAG, "Last Time Out: " + timeOut + " / " + TimeHelpers.millisToTimeDate(timeOut)); if (timeOut != 0) { Log.d(TAG, "Returning."); db.close(); return; } Log.e(TAG, "myTaskList child count is: " + myTaskList.getCount()); myTaskList.clearChoices(); long lastTaskID = db.taskIDForLastClockEntry(); Log.d(TAG, "Last Task ID: " + lastTaskID); String taskName = db.getTaskNameByID(lastTaskID); // TODO: There should be a better way to do this. // Iterate over the entire ListView to find the name of the // entry that is to be selected. for (int i = 0; i < myTaskList.getCount(); i++) { if (taskName.equalsIgnoreCase((String) myTaskList .getItemAtPosition(i))) { myTaskList.setItemChecked(i, true); myTaskList.setSelection(i); } } db.close(); } /** * Refresh the task list. Looking up the list view. */ void refreshTaskListAdapter() { Log.d(TAG, "In refreshTaskListAdapter()"); refreshTaskListAdapter((ListView) findViewById(R.id.tasklistfragment)); } /** * Refresh the task list. * * @param myTaskList * The view ID of the task list. */ void refreshTaskListAdapter(ListView myTaskList) { Log.d(TAG, "In refreshTaskListAdapter"); TimeSheetDbAdapter db = new TimeSheetDbAdapter(getApplicationContext()); db.open(); // (Re-)Populate the ListView with an array adapter with the task items. myTaskList.setAdapter(new MyArrayAdapter<String>( getApplicationContext(), android.R.layout.simple_list_item_single_choice, db .getTasksList())); setSelected(myTaskList); updateTitleBar(); } /** * Refresh the day report list. Looking up the list view. */ void refreshReportListAdapter() { Log.d(TAG, "In refreshReportListAdapter()"); refreshReportListAdapter((ListView) findViewById(R.id.reportList)); } /** * Refresh the day report list. * * @param myReportList * The view ID of the list to refresh. */ void refreshReportListAdapter(ListView myReportList) { Log.d(TAG, "In refreshReportListAdapter"); TimeSheetDbAdapter db = new TimeSheetDbAdapter(getApplicationContext()); float dayHours = TimeSheetActivity.prefs.getHoursPerDay(); String date = TimeHelpers.millisToDate(day); Log.d(TAG, "refreshReportListAdapter: Updating to " + TimeHelpers.millisToTimeDate(day)); TextView headerView = (TextView) myReportList.getRootView() .findViewById(R.id.reportheader); headerView.setText("Day Report - " + date); TextView footerView = (TextView) myReportList.getRootView() .findViewById(R.id.reportfooter); footerView .setText("Hours worked this day: 0\nHours remaining this day: " + String.format("%.2f", dayHours)); Cursor timeEntryCursor; // = db.dayEntryReport(); // If the day being reported is the current week, most probably // where the current open task exists, then include it, otherwise // omit. if (day >= TimeHelpers.millisToStartOfDay(TimeHelpers.millisNow()) && day <= TimeHelpers.millisToEndOfDay(TimeHelpers.millisNow())) { timeEntryCursor = db.daySummary(day, false); } else { timeEntryCursor = db.daySummary(day, true); } try { timeEntryCursor.moveToFirst(); } catch (NullPointerException e) { Log.e(TAG, "timeEntryCursor.moveToFirst: " + e.toString()); myReportList.setAdapter(null); return; } catch (Exception e) { Log.e(TAG, "timeEntryCursor.moveToFirst: " + e.toString()); return; } float accum = 0; while (!timeEntryCursor.isAfterLast()) { accum = accum + timeEntryCursor.getFloat(timeEntryCursor .getColumnIndex(TimeSheetDbAdapter.KEY_TOTAL)); timeEntryCursor.moveToNext(); } footerView.setText("Hours worked this day: " + String.format("%.2f", accum) + "\nHours remaining this day: " + String.format("%.2f", dayHours - accum)); try { myReportList.setAdapter(new ReportCursorAdapter( getApplicationContext(), R.layout.mysimple_list_item_2, timeEntryCursor, new String[] { TimeSheetDbAdapter.KEY_TASK, TimeSheetDbAdapter.KEY_TOTAL }, new int[] { android.R.id.text1, android.R.id.text2 })); Log.i(TAG, "reportList.setAdapter: updated"); } catch (Exception e) { Log.e(TAG, "reportList.setAdapter: " + e.toString()); } } /** * Refresh the week report list. Looking up the list view. */ void refreshWeekReportListAdapter() { Log.d(TAG, "In refreshWeekReportListAdapter()"); refreshWeekReportListAdapter((ListView) findViewById(R.id.weekList)); } /** * Refresh the week report list. * * @param myReportList * The view ID of the list to refresh. */ void refreshWeekReportListAdapter(ListView myReportList) { Log.d(TAG, "In refreshWeekReportListAdapter"); TimeSheetDbAdapter db = new TimeSheetDbAdapter(getApplicationContext()); float weekHours = TimeSheetActivity.prefs.getHoursPerWeek(); String date = TimeHelpers.millisToDate(TimeHelpers .millisToEndOfWeek(day)); Log.d(TAG, "refreshWeekReportListAdapter: Updating to " + TimeHelpers.millisToTimeDate(TimeHelpers .millisToEndOfWeek(day))); try { TextView headerView = (TextView) myReportList.getRootView() .findViewById(R.id.weekheader); headerView.setText("Week Report - W/E: " + date); } catch (NullPointerException e) { Log.d(TAG, "Caught NullPointerException in refreshWeekReportListAdapter."); return; } TextView footerView = (TextView) myReportList.getRootView() .findViewById(R.id.weekfooter); footerView .setText("Hours worked this week: 0\nHours remaining this week: " + String.format("%.2f", weekHours)); Cursor timeEntryCursor;// = db.weekEntryReport(); // If the day being reported is the current week, most probably // where the current open task exists, then include it, otherwise // omit. if (day >= TimeHelpers.millisToStartOfWeek(TimeHelpers.millisNow()) && day <= TimeHelpers .millisToEndOfWeek(TimeHelpers.millisNow())) { timeEntryCursor = db.weekSummary(day, false); } else { timeEntryCursor = db.weekSummary(day, true); } try { timeEntryCursor.moveToFirst(); } catch (NullPointerException e) { Log.e(TAG, "timeEntryCursor.moveToFirst: " + e.toString()); myReportList.setAdapter(null); return; } catch (Exception e) { Log.e(TAG, "timeEntryCursor.moveToFirst: " + e.toString()); return; } float accum = 0; while (!timeEntryCursor.isAfterLast()) { accum = accum + timeEntryCursor.getFloat(timeEntryCursor .getColumnIndex(TimeSheetDbAdapter.KEY_TOTAL)); timeEntryCursor.moveToNext(); } footerView.setText("Hours worked this week: " + String.format("%.2f", accum) + "\nHours remaining this week: " + String.format("%.2f", weekHours - accum)); try { myReportList.setAdapter(new ReportCursorAdapter( getApplicationContext(), R.layout.mysimple_list_item_2, timeEntryCursor, new String[] { TimeSheetDbAdapter.KEY_TASK, TimeSheetDbAdapter.KEY_TOTAL }, new int[] { android.R.id.text1, android.R.id.text2 })); } catch (Exception e) { Log.e(TAG, "reportList.setAdapter: " + e.toString()); } } /** * Instantiate the persistent notification. * * @param taskName * Name of the task currently active (clocked into) * @param timeIn * The time (in nanoseconds) the task started */ void startNotification(String taskName, long timeIn) { if (!prefs.getPersistentNotification()) { return; } Notification myNotification = new NotificationCompat.Builder( getApplicationContext()) .setContentTitle( getResources().getString(R.string.notification_title)) .setContentText(taskName).setWhen(timeIn) .setContentIntent(contentIntent).setAutoCancel(false).setOngoing(true) .setSmallIcon(R.drawable.icon_small).getNotification(); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(MY_NOTIFICATION_ID, myNotification); } /** * Stop / turn off the persistent notification. */ void stopNotification() { try { NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancel(MY_NOTIFICATION_ID); } catch (NullPointerException e) { // Do nothing. The preference was probably set to false, so this was // never created. } } /** * Handle the button event from the restore dialog. */ public void doRestoreClick() { Log.d(TAG, "in doRestoreClick"); if (!SDBackup.doSDRestore(TimeSheetDbAdapter.DATABASE_NAME, getApplicationContext().getPackageName())) { Log.w(TAG, "doSDRestore failed."); Toast.makeText(getApplicationContext(), "Database restore failed.", Toast.LENGTH_LONG).show(); } else { Log.i(TAG, "doSDRestore succeeded."); Toast.makeText(getApplicationContext(), "Database restore succeeded.", Toast.LENGTH_SHORT).show(); refreshTaskListAdapter(); refreshReportListAdapter(); // refreshWeekReportListAdapter(); setSelected(); } Log.d(TAG, "leaving doRestoreClick"); } /** * Update the subtitle in the Action Bar. */ void updateTitleBar() { Log.d(TAG, "updateTitleBar"); final String format = "(%.2fh / %.2fh) / (%.2fh / %.2fh)"; float hoursPerDay = prefs.getHoursPerDay(); float hoursPerWeek = prefs.getHoursPerWeek(); float dayAdder = 0; float weekAdder = 0; TimeSheetDbAdapter db = new TimeSheetDbAdapter(getApplicationContext()); // Display the time accumulated for today with time remaining. Cursor reportCursor = db.daySummary(false); if (reportCursor == null) { getSupportActionBar().setSubtitle( String.format(format, dayAdder, hoursPerDay, weekAdder, hoursPerWeek)); return; } reportCursor.moveToFirst(); if (!reportCursor.isAfterLast()) { int column = reportCursor .getColumnIndex(TimeSheetDbAdapter.KEY_TOTAL); while (!reportCursor.isAfterLast()) { dayAdder = dayAdder + reportCursor.getFloat(column); reportCursor.moveToNext(); } } try { reportCursor.close(); } catch (IllegalStateException e) { Log.d(TAG, "updateTitleBar " + e.toString()); } reportCursor = db.weekSummary(TimeHelpers.millisNow(), false); if (reportCursor == null) { getSupportActionBar().setSubtitle( String.format(format, dayAdder, hoursPerDay - dayAdder, weekAdder, hoursPerWeek)); return; } reportCursor.moveToFirst(); if (!reportCursor.isAfterLast()) { int column = reportCursor .getColumnIndex(TimeSheetDbAdapter.KEY_TOTAL); while (!reportCursor.isAfterLast()) { weekAdder = weekAdder + reportCursor.getFloat(column); reportCursor.moveToNext(); } } try { reportCursor.close(); } catch (IllegalStateException e) { Log.d(TAG, "updateTitleBar " + e.toString()); } getSupportActionBar().setSubtitle( String.format(format, dayAdder, hoursPerDay - dayAdder, weekAdder, hoursPerWeek - weekAdder)); } /** * Return the menu object for testing. * * @return optionMenu */ public Menu getOptionsMenu() { return optionsMenu; } }
package net.ihiroky.niotty; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** * Provides an loop to process tasks which is queued in a task queue. * <p> * The task, which implements {@link Task}, is queued by * {@link #offer(Task)}. It is processed by a dedicated * thread in queued (FIFO) order. A queue blocking strategy is determined by * {@link #poll(long, TimeUnit)} and {@link #wakeUp()} of this sub class, this class provides * the queue only. * </p> * <p> * This class has a timer to process a task with some delay. * {@link #schedule(Task, long, java.util.concurrent.TimeUnit)} * is used to register a task to the timer. If a task returns a positive value, the task is * registered to the timer implicitly to be processed after the returned value. If returns * zero, the task is inserted to the task queue to processed again immediately. * </p> * <p> * This class holds a set of {@link net.ihiroky.niotty.TaskSelection}. The selection shows * a object which is associated with this task loop. The sum of the weight of the selections * can be used to control the balancing of the association. * </p> */ public abstract class TaskLoop implements Runnable, Comparable<TaskLoop> { private final Queue<Task> taskQueue_; private final Queue<TaskFuture> delayQueue_; private volatile Thread thread_; private final Set<TaskSelection> selectionSet_; private final AtomicInteger weight_ = new AtomicInteger(); private Logger logger_ = LoggerFactory.getLogger(TaskLoop.class); private static final TimeUnit TIME_UNIT = TimeUnit.NANOSECONDS; private static final int INITIAL_TASK_BUFFER_SIZE = 1024; private static final int INITIAL_DELAY_QUEUE_SIZE = 1024; /** * Creates a new instance. */ protected TaskLoop() { taskQueue_ = new ConcurrentLinkedQueue<>(); delayQueue_ = new PriorityQueue<>(INITIAL_DELAY_QUEUE_SIZE); selectionSet_ = new HashSet<>(); } /** * Inserts a specified task to the task queue. * @param task the task to be inserted to the task queue * @throws NullPointerException the task is null */ public void offer(Task task) { taskQueue_.offer(task); wakeUp(); } /** * Registers a specified task to the timer with specified delay time. * @param task the task to be registered to the timer * @param delay the delay of task execution * @param timeUnit unit of the delay * @return a future representing pending completion of the task * @throws NullPointerException if task or timeUnit is null */ public TaskFuture schedule(final Task task, long delay, TimeUnit timeUnit) { Objects.requireNonNull(task, "task"); Objects.requireNonNull(timeUnit, "timeUnit"); long expire = System.nanoTime() + timeUnit.toNanos(delay); final TaskFuture future = new TaskFuture(expire, task); if (isInLoopThread()) { delayQueue_.offer(future); wakeUp(); return future; } taskQueue_.offer(new Task() { @Override public long execute(TimeUnit timeUnit) throws Exception { delayQueue_.offer(future); return DONE; } }); wakeUp(); return future; } /** * If a caller is executed in the loop thread, run the task immediately. * Otherwise, inserts the task to the task queue. * @param task the task * @throws NullPointerException if the task is null */ public void execute(Task task) { if (isInLoopThread()) { try { long waitTimeNanos = task.execute(TIME_UNIT); if (waitTimeNanos > 0) { TaskFuture future = new TaskFuture(System.nanoTime() + waitTimeNanos, task); delayQueue_.offer(future); } else if (waitTimeNanos == Task.RETRY_IMMEDIATELY) { taskQueue_.offer(task); } } catch (Exception e) { logger_.warn("[execute] Unexpected exception.", e); } } else { taskQueue_.offer(task); wakeUp(); } } void waitUntilStarted() throws InterruptedException { synchronized (this) { while (thread_ == null) { wait(); } } } /** * Executes the loop especially on a thread provided by {@link net.ihiroky.niotty.TaskLoopGroup}. */ public void run() { Deque<Task> taskBuffer = new ArrayDeque<>(INITIAL_TASK_BUFFER_SIZE); Queue<Task> taskQueue = taskQueue_; Queue<TaskFuture> delayQueue = delayQueue_; try { synchronized (this) { thread_ = Thread.currentThread(); onOpen(); notifyAll(); // Counter part: waitUntilStarted() } long delayNanos = Task.DONE; while (thread_ != null) { try { poll(taskQueue.isEmpty() ? delayNanos : Task.RETRY_IMMEDIATELY, TIME_UNIT); processTasks(taskQueue, taskBuffer, delayQueue); delayNanos = processDelayedTask(taskQueue, delayQueue); } catch (InterruptedException ie) { logger_.debug("[run] Interrupted.", ie); break; } catch (Exception e) { if (thread_ != null) { logger_.warn("[run] Unexpected exception.", e); } } } } finally { onClose(); taskQueue.clear(); synchronized (selectionSet_) { selectionSet_.clear(); } thread_ = null; } } private void processTasks( Queue<Task> taskQueue, Deque<Task> buffer, Queue<TaskFuture> delayQueue) throws Exception { Task task; for (;;) { task = taskQueue.poll(); if (task == null) { break; } buffer.offerLast(task); } for (;;) { task = buffer.pollFirst(); if (task == null) { break; } long retryDelay = task.execute(TIME_UNIT); if (retryDelay <= Task.DONE) { continue; } if (retryDelay == Task.RETRY_IMMEDIATELY) { taskQueue.offer(task); } else { // if (retryDelay > 0) { long expire = System.nanoTime() + retryDelay; delayQueue.offer(new TaskFuture(expire, task)); } } } private long processDelayedTask(Queue<Task> taskQueue, Queue<TaskFuture> delayQueue) throws Exception { long now = System.nanoTime(); TaskFuture f; for (;;) { f = delayQueue.peek(); if (f == null || f.expire() > now) { break; } if (!f.readyToDispatch()) { delayQueue.poll(); continue; } try { delayQueue.poll(); long waitTimeNanos = f.task_.execute(TIME_UNIT); if (waitTimeNanos > 0) { f.setExpire(now + waitTimeNanos); delayQueue.offer(f); continue; } else if (waitTimeNanos == Task.RETRY_IMMEDIATELY) { taskQueue.offer(f.task_); } f.dispatched(); } catch (Exception ex) { logger_.warn("[execute] Unexpected exception.", ex); } } while (f != null && f.isCancelled()) { delayQueue.poll(); f = delayQueue.peek(); } return (f != null) ? f.expire() - now : Task.DONE; } /** * Returns true if the caller is executed on the thread which executes this loop. * @return true if the caller is executed on the thread which executes this loop */ protected boolean isInLoopThread() { return Thread.currentThread() == thread_; } /** * Returns true if the thread which executes this loop is alive. * @return true if the thread which executes this loop is alive */ protected boolean isAlive() { Thread t = thread_; return (t != null) && t.isAlive(); } void close() { Thread t = thread_; if (t != null) { t.interrupt(); thread_ = null; } } @Override public String toString() { return (thread_ != null) ? thread_.getName() : super.toString(); } @Override public int compareTo(TaskLoop that) { return this.weight_.get() - that.weight_.get(); } /** * Returns true if a object specified by the selection is associated with this object. * @param selection the object to test * @return true if a object specified by the selection is associated with this object */ public boolean contains(TaskSelection selection) { synchronized (selectionSet_) { return selectionSet_.contains(selection); } } /** * Associates a object specified by the selection with this object. * @param selection the object to be associated * @return sum of the selection's weight associated with this object * @throws NullPointerException if selection is null */ public int accept(TaskSelection selection) { Objects.requireNonNull(selection, "selection"); int weight = -1; synchronized (selectionSet_) { if (!selectionSet_.contains(selection)) { weight = addWeight(selection.weight()); selectionSet_.add(selection); } } return weight; } /** * Dissociate a object specified by the selection from this object. * @param selection the object to be dissociate * @return sum of the selection's weight associated with this object, exclude the selection */ public int reject(TaskSelection selection) { Objects.requireNonNull(selection, "selection"); int weight = -1; synchronized (selectionSet_) { if (selectionSet_.contains(selection)) { weight = addWeight(-selection.weight()); selectionSet_.remove(selection); } } return weight; } /** * Returns a view of the selections associated with this object. * @return a view of the selections associated with this object */ public Collection<TaskSelection> selectionView() { List<TaskSelection> copy; synchronized (selectionSet_) { copy = new ArrayList<>(selectionSet_); } return copy; } private int addWeight(int weight) { for (;;) { int value = weight_.get(); int added = value + weight; if (added < 0) { added = (weight > 0) ? Integer.MAX_VALUE : 0; } if (weight_.compareAndSet(value, added)) { return added; } } } /** * Returns sum of the weight of selections which is associated with this object. * @return sum of the weight of selections */ protected int weight() { return weight_.get(); } /** * This method is called once when the loop is initialized. */ protected abstract void onOpen(); /** * This method is called once when the loop is ready to terminate. */ protected abstract void onClose(); /** * Executes any procedure. * This method returns when the procedure was executed, the method {@link #wakeUp()} is invoked, * the current thread is interrupted, or the given timeout period expires, whichever comes first. * * @param timeout a time to block for up to timeout, more or less, * while waiting for a channel to become ready; if zero, block indefinitely; * if negative, returns immediately * @param timeUnit the unit of the timeout * @throws Exception if some error occurs */ protected abstract void poll(long timeout, TimeUnit timeUnit) throws Exception; /** * This method is called when a new task is inserted to the task queue. * The implementation is required to wake up the thread executing * {@link #poll(long, java.util.concurrent.TimeUnit)} on waiting timeout. */ protected abstract void wakeUp(); }
package net.spy.memcached; import java.io.IOException; import java.net.InetSocketAddress; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import javax.naming.ConfigurationException; import net.spy.memcached.ops.Operation; import net.spy.memcached.ops.OperationCallback; import net.spy.memcached.ops.OperationStatus; import net.spy.memcached.ops.TapOperation; import net.spy.memcached.tapmessage.RequestMessage; import net.spy.memcached.tapmessage.ResponseMessage; import net.spy.memcached.tapmessage.TapAck; import net.spy.memcached.tapmessage.TapOpcode; import net.spy.memcached.tapmessage.TapStream; /** * A tap client for memcached. */ public class TapClient { protected BlockingQueue<Object> rqueue; protected final HashMap<TapStream, TapConnectionProvider> omap; protected long messagesRead; private List<InetSocketAddress> addrs; /** * Creates a tap client against the specified servers. * * This type of TapClient will TAP the specified servers, but will not be able * to react to changes in the number of cluster nodes. Using the constructor * which bootstraps itself from the cluster REST interface is preferred. * * @param ia the addresses of each node in the cluster. */ public TapClient(InetSocketAddress... ia) { this(Arrays.asList(ia)); } /** * Creates a tap client against the specified servers. * * This type of TapClient will TAP the specified servers, but will not be able * to react to changes in the number of cluster nodes. Using the constructor * which bootstraps itself from the cluster REST interface is preferred. * * @param addrs a list of addresses containing each node in the cluster. */ public TapClient(List<InetSocketAddress> addrs) { this.rqueue = new LinkedBlockingQueue<Object>(); this.omap = new HashMap<TapStream, TapConnectionProvider>(); this.addrs = addrs; this.messagesRead = 0; } /** * Gets the next tap message from the queue of received tap messages. * * @return The tap message at the head of the queue or null if the queue is * empty for more than one second. */ public ResponseMessage getNextMessage() { return getNextMessage(10, TimeUnit.SECONDS); } /** * Gets the next tap message from the queue of received tap messages. * * @param time the amount of time to wait for a message. * @param timeunit the unit of time to use. * @return The tap message at the head of the queue or null if the queue is * empty for the given amount of time. */ public ResponseMessage getNextMessage(long time, TimeUnit timeunit) { try { Object m = rqueue.poll(time, timeunit); if (m == null) { return null; } else if (m instanceof ResponseMessage) { return (ResponseMessage) m; } else if (m instanceof TapAck) { TapAck ack = (TapAck) m; tapAck(ack.getConn(), ack.getNode(), ack.getOpcode(), ack.getOpaque(), ack.getCallback()); return null; } else { throw new RuntimeException("Unexpected tap message type"); } } catch (InterruptedException e) { shutdown(); return null; } } /** * Decides whether the client has received tap messages or will receive more * messages in the future. * * @return true if the client has tap responses or expects to have responses * in the future. False otherwise. */ public boolean hasMoreMessages() { if (!rqueue.isEmpty()) { return true; } else { synchronized (omap) { Iterator<TapStream> itr = omap.keySet().iterator(); while (itr.hasNext()) { TapStream ts = itr.next(); if (ts.isCompleted() || ts.isCancelled() || ts.hasErrored()) { omap.get(ts).shutdown(); omap.remove(ts); } } if (omap.size() > 0) { return true; } } } return false; } /** * Allows the user to specify a custom tap message. * * @param id the named tap id that can be used to resume a disconnected tap * stream * @param message the custom tap message that will be used to initiate the tap * stream. * @return the operation that controls the tap stream. * @throws ConfigurationException a bad configuration was received from the * memcached cluster. * @throws IOException if there are errors connecting to the cluster. */ public TapStream tapCustom(final String id, final RequestMessage message) throws ConfigurationException, IOException { final TapConnectionProvider conn = new TapConnectionProvider(addrs); final TapStream ts = new TapStream(); conn.broadcastOp(new BroadcastOpFactory() { public Operation newOp(final MemcachedNode n, final CountDownLatch latch) { Operation op = conn.getOpFactory().tapCustom(id, message, new TapOperation.Callback() { public void receivedStatus(OperationStatus status) { } public void gotData(ResponseMessage tapMessage) { rqueue.add(tapMessage); messagesRead++; } public void gotAck(MemcachedNode node, TapOpcode opcode, int opaque) { rqueue.add(new TapAck(conn, node, opcode, opaque, this)); } public void complete() { latch.countDown(); } }); ts.addOp((TapOperation)op); return op; } }); synchronized (omap) { omap.put(ts, conn); } return ts; } /** * Specifies a tap stream that will take a snapshot of items in memcached and * send them through a tap stream. * * @param id the named tap id that can be used to resume a disconnected tap * stream * @return the operation that controls the tap stream. * @throws ConfigurationException a bad configuration was received from the * memcached cluster. * @throws IOException If there are errors connecting to the cluster. */ public TapStream tapDump(final String id) throws IOException, ConfigurationException { final TapConnectionProvider conn = new TapConnectionProvider(addrs); final TapStream ts = new TapStream(); conn.broadcastOp(new BroadcastOpFactory() { public Operation newOp(final MemcachedNode n, final CountDownLatch latch) { Operation op = conn.getOpFactory().tapDump(id, new TapOperation.Callback() { public void receivedStatus(OperationStatus status) { } public void gotData(ResponseMessage tapMessage) { rqueue.add(tapMessage); messagesRead++; } public void gotAck(MemcachedNode node, TapOpcode opcode, int opaque) { rqueue.add(new TapAck(conn, node, opcode, opaque, this)); } public void complete() { latch.countDown(); } }); ts.addOp((TapOperation)op); return op; } }); synchronized (omap) { omap.put(ts, conn); } return ts; } private void tapAck(TapConnectionProvider conn, MemcachedNode node, TapOpcode opcode, int opaque, OperationCallback cb) { final Operation op = conn.getOpFactory().tapAck(opcode, opaque, cb); conn.addTapAckOp(node, op); } /** * Shuts down all tap streams that are currently running. */ public void shutdown() { synchronized (omap) { for (Map.Entry<TapStream, TapConnectionProvider> me : omap.entrySet()) { me.getValue().shutdown(); } } } /** * The number of messages read by all of the tap streams created with this * client. This will include a count of all tap response types. * * @return The number of messages read */ public long getMessagesRead() { return messagesRead; } }
package nl.tudelft.jpacman; import java.awt.event.KeyEvent; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import nl.tudelft.jpacman.board.BoardFactory; import nl.tudelft.jpacman.board.Direction; import nl.tudelft.jpacman.board.Square; import nl.tudelft.jpacman.game.Game; import nl.tudelft.jpacman.game.GameFactory; import nl.tudelft.jpacman.level.Level; import nl.tudelft.jpacman.level.LevelFactory; import nl.tudelft.jpacman.level.MapParser; import nl.tudelft.jpacman.level.Player; import nl.tudelft.jpacman.level.PlayerFactory; import nl.tudelft.jpacman.npc.ghost.GhostFactory; import nl.tudelft.jpacman.sprite.PacManSprites; import nl.tudelft.jpacman.ui.Action; import nl.tudelft.jpacman.ui.PacManUI; import nl.tudelft.jpacman.ui.PacManUiBuilder; /** * Creates and launches the JPacMan UI. * * @author Jeroen Roosen */ public class Launcher { private static final PacManSprites SPRITE_STORE = new PacManSprites(); private PacManUI pacManUI; private Game game; /** * @return The game object this launcher will start when {@link #launch()} * is called. */ public Game getGame() { return game; } /** * Creates a new game using the level from {@link #makeLevel()}. * * @return a new Game. */ public Game makeGame() { GameFactory gf = getGameFactory(); Level level = makeLevel(); return gf.createSinglePlayerGame(level); } /** * Creates a new level. By default this method will use the map parser to * parse the default board stored in the <code>board.txt</code> resource. * * @return A new level. */ public Level makeLevel() { MapParser parser = getMapParser(); try (InputStream boardStream = Launcher.class .getResourceAsStream("/board.txt")) { return parser.parseMap(boardStream); } catch (IOException e) { throw new PacmanConfigurationException("Unable to create level.", e); } } /** * @return A new map parser object using the factories from * {@link #getLevelFactory()} and {@link #getBoardFactory()}. */ protected MapParser getMapParser() { return new MapParser(getLevelFactory(), getBoardFactory()); } /** * @return A new board factory using the sprite store from * {@link #getSpriteStore()}. */ protected BoardFactory getBoardFactory() { return new BoardFactory(getSpriteStore()); } /** * @return The default {@link PacManSprites}. */ protected PacManSprites getSpriteStore() { return SPRITE_STORE; } /** * @return A new factory using the sprites from {@link #getSpriteStore()} * and the ghosts from {@link #getGhostFactory()}. */ protected LevelFactory getLevelFactory() { return new LevelFactory(getSpriteStore(), getGhostFactory()); } /** * @return A new factory using the sprites from {@link #getSpriteStore()}. */ protected GhostFactory getGhostFactory() { return new GhostFactory(getSpriteStore()); } /** * @return A new factory using the players from {@link #getPlayerFactory()}. */ protected GameFactory getGameFactory() { return new GameFactory(getPlayerFactory()); } /** * @return A new factory using the sprites from {@link #getSpriteStore()}. */ protected PlayerFactory getPlayerFactory() { return new PlayerFactory(getSpriteStore()); } /** * Adds key events UP, DOWN, LEFT and RIGHT to a game. * * @param builder * The {@link PacManUiBuilder} that will provide the UI. * @param game * The game that will process the events. */ protected void addSinglePlayerKeys(final PacManUiBuilder builder, final Game game) { final Player p1 = getSinglePlayer(game); builder.addKey(KeyEvent.VK_UP, new Action() { @Override public void doAction() { game.move(p1, Direction.NORTH); } }).addKey(KeyEvent.VK_DOWN, new Action() { @Override public void doAction() { game.move(p1, Direction.SOUTH); } }).addKey(KeyEvent.VK_LEFT, new Action() { @Override public void doAction() { game.move(p1, Direction.WEST); } }).addKey(KeyEvent.VK_RIGHT, new Action() { @Override public void doAction() { game.move(p1, Direction.EAST); } }); } private Player getSinglePlayer(final Game game) { List<Player> players = game.getPlayers(); if (players.isEmpty()) { throw new IllegalArgumentException("Game has 0 players."); } final Player p1 = players.get(0); return p1; } /** * Creates and starts a JPac-Man game. */ public void launch() { game = makeGame(); PacManUiBuilder builder = new PacManUiBuilder().withDefaultButtons(); //addSinglePlayerKeys(builder, game); addSinglePlayerKeysContinuousMove(builder, game); pacManUI = builder.build(game); pacManUI.start(); } /** * Disposes of the UI. For more information see {@link javax.swing.JFrame#dispose()}. */ public void dispose() { pacManUI.dispose(); } /** * Main execution method for the Launcher. * * @param args * The command line arguments - which are ignored. * @throws IOException * When a resource could not be read. */ public static void main(String[] args) throws IOException { new Launcher().launch(); } /* !!!!!!!!!!! NEW FUNCTIONALITY : CONTINUOUS MOVE !!!!!!!!!!! !! */ protected Direction direction; protected void addSinglePlayerKeysContinuousMove(final PacManUiBuilder builder, final Game game) { final Player p1 = getSinglePlayer(game); ScheduledExecutorService service = Executors .newSingleThreadScheduledExecutor(); service.schedule(new PlayerMoveTask(p1, service), 200, TimeUnit.MILLISECONDS); builder.addKey(KeyEvent.VK_UP, new Action() { @Override public void doAction() { if(isAccessible(Direction.NORTH)) direction = Direction.NORTH; } }).addKey(KeyEvent.VK_DOWN, new Action() { @Override public void doAction() { if(isAccessible(Direction.SOUTH)) direction = Direction.SOUTH; } }).addKey(KeyEvent.VK_LEFT, new Action() { @Override public void doAction() { if(isAccessible(Direction.WEST)) direction = Direction.WEST; } }).addKey(KeyEvent.VK_RIGHT, new Action() { @Override public void doAction() { if(isAccessible(Direction.EAST)) direction = Direction.EAST; } }); } private final class PlayerMoveTask implements Runnable{ private final Player player; private final ScheduledExecutorService service; private PlayerMoveTask(Player player, ScheduledExecutorService service) { this.player = player; this.service = service; } @Override public void run() { Direction nextMove = direction; if(nextMove != null) game.move(player, nextMove); service.schedule(this, 200, TimeUnit.MILLISECONDS); } } boolean isAccessible(Direction direction){ Square square = getSinglePlayer(game).getSquare(); List<Direction> directions = new ArrayList<>(); for (Direction d : Direction.values()) { if (square.getSquareAt(d).isAccessibleTo(getSinglePlayer(game))) { directions.add(d); } } if (direction != null && directions.contains(direction)) { return true; } else{ return false; } } }
package alma.acs.nc.refactored; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.omg.CORBA.portable.IDLEntity; import alma.ADMINTEST1.statusBlockEvent1; import alma.ADMINTEST2.statusBlockEvent2; import alma.acs.component.client.ComponentClientTestCase; import alma.acs.exceptions.AcsJException; import alma.acs.nc.AcsEventPublisher; import alma.acs.nc.AcsEventSubscriber.Callback; import alma.acs.nc.AcsEventSubscriber.GenericCallback; import alma.acs.nc.CannotAddSubscriptionException; import alma.acs.nc.SubscriptionNotFoundException; import alma.acsnc.EventDescription; /** * Test class for the new generation of NC Subscribers. * * @author rtobar */ public class NCSubscriberTest extends ComponentClientTestCase { private static String CHANNEL_NAME = "pink-floyd"; private NCSubscriber m_subscriber; private AcsEventPublisher m_publisher; private enum EventType { statusBlock1, statusBlock2 }; public NCSubscriberTest() throws Exception { super("NCSubscriberTest"); } public void setUp() throws Exception { super.setUp(); m_publisher = getContainerServices().createNotificationChannelPublisher(CHANNEL_NAME); m_subscriber = (NCSubscriber)getContainerServices().createNotificationChannelSubscriber(CHANNEL_NAME); // This is the all-exclusive filter assertEquals(1, m_subscriber.proxySupplier.get_all_filters().length); } public void tearDown() throws Exception { m_publisher.disconnect(); super.tearDown(); } @SuppressWarnings({ "unchecked", "rawtypes" }) public void testAddSubscription() throws Exception { // Invalid receiver (returns null) try { m_subscriber.addSubscription(new EventReceiver1() { public Class<statusBlockEvent1> getEventType() { return null; } }); fail("Event receiver is invalid, as it returns a null event type"); } catch(CannotAddSubscriptionException e) { } // Invalid receiver (returns String.class) try { m_subscriber.addSubscription(new Callback() { public void receive(IDLEntity event, EventDescription eventDescrip) { } public Class getEventType() { return String.class; } }); fail("Event receiver is invalid, as it returns a java.lang.String as the event type"); } catch(CannotAddSubscriptionException e) { } // Several receiver subscriptions for the same type overwrite the previous one m_subscriber.addSubscription(new EventReceiver1()); m_subscriber.addSubscription(new EventReceiver1()); m_subscriber.addSubscription(new EventReceiver1()); m_subscriber.addSubscription(new EventReceiver1()); assertEquals(1, m_subscriber.subscriptionsFilters.size()); assertEquals(1, m_subscriber.receivers.size()); assertNull(m_subscriber.genericReceiver); assertEquals(2, m_subscriber.proxySupplier.get_all_filters().length); m_subscriber.addSubscription(new EventReceiver2()); m_subscriber.addSubscription(new EventReceiver2()); m_subscriber.addSubscription(new EventReceiver2()); m_subscriber.addSubscription(new EventReceiver2()); assertEquals(2, m_subscriber.subscriptionsFilters.size()); assertEquals(2, m_subscriber.receivers.size()); assertNull(m_subscriber.genericReceiver); assertEquals(3, m_subscriber.proxySupplier.get_all_filters().length); m_subscriber.addGenericSubscription(new GenericEventReceiver()); m_subscriber.addGenericSubscription(new GenericEventReceiver()); m_subscriber.addGenericSubscription(new GenericEventReceiver()); m_subscriber.addGenericSubscription(new GenericEventReceiver()); assertEquals(3, m_subscriber.subscriptionsFilters.size()); assertEquals(2, m_subscriber.receivers.size()); assertNotNull(m_subscriber.genericReceiver); assertEquals(4, m_subscriber.proxySupplier.get_all_filters().length); } public void testRemoveSubscription() throws Exception { // Invalid removals, then subscription // // event 1 try { m_subscriber.removeSubscription(statusBlockEvent1.class); fail("Should fail because we don't have a subscription yet to statusBlockEvent1"); } catch (SubscriptionNotFoundException e) { } m_subscriber.addSubscription(new EventReceiver1()); // event 2 try { m_subscriber.removeSubscription(statusBlockEvent2.class); fail("Should fail because we don't have a subscription yet to statusBlockEvent2"); } catch (SubscriptionNotFoundException e) { } m_subscriber.addSubscription(new EventReceiver2()); // generic try { m_subscriber.removeGenericSubscription(); fail("Should fail because we don't have a generic subscription"); } catch(SubscriptionNotFoundException e) {} m_subscriber.addGenericSubscription(new GenericEventReceiver()); // Now we can safely remove all subscriptions m_subscriber.removeGenericSubscription(); m_subscriber.removeSubscription(statusBlockEvent1.class); m_subscriber.removeSubscription(statusBlockEvent2.class); assertEquals(0, m_subscriber.subscriptionsFilters.size()); assertEquals(0, m_subscriber.receivers.size()); assertNull(m_subscriber.genericReceiver); // After we remove all subscriptions, only the all-exclusive filter is set in the server assertEquals(1, m_subscriber.proxySupplier.get_all_filters().length); // Trying to remove subscriptions should fail now try { m_subscriber.removeSubscription(statusBlockEvent1.class); fail("Should fail because we don't have a subscription yet to statusBlockEvent1"); } catch (SubscriptionNotFoundException e) { } try { m_subscriber.removeSubscription(statusBlockEvent2.class); fail("Should fail because we don't have a subscription yet to statusBlockEvent2"); } catch (SubscriptionNotFoundException e) { } } public void testSubscriptionbyEventTypeReceiving() throws Exception { int nEvents = 10; // Simple case: 1 receiver per event type, publisher publishes same amount of events for each type CountDownLatch c1 = new CountDownLatch(nEvents); CountDownLatch c2 = new CountDownLatch(nEvents); m_subscriber.addSubscription(new EventReceiver1(c1)); m_subscriber.addSubscription(new EventReceiver2(c2)); m_subscriber.startReceivingEvents(); publish(nEvents, EventType.statusBlock1); publish(nEvents, EventType.statusBlock2); c1.await(10, TimeUnit.SECONDS); c2.await(10, TimeUnit.SECONDS); m_subscriber.disconnect(); assertEquals(0, c1.getCount()); assertEquals(0, c2.getCount()); // Overriding case: 1 receiver per event type, 2nd receiver is overridden m_subscriber = (NCSubscriber)getContainerServices().createNotificationChannelSubscriber(CHANNEL_NAME); c1 = new CountDownLatch(nEvents); c2 = new CountDownLatch(nEvents); CountDownLatch c3 = new CountDownLatch(nEvents); m_subscriber.addSubscription(new EventReceiver1(c1)); m_subscriber.addSubscription(new EventReceiver2(c2)); m_subscriber.addSubscription(new EventReceiver2(c3)); m_subscriber.startReceivingEvents(); publish(nEvents, EventType.statusBlock1); publish(nEvents, EventType.statusBlock2); c1.await(10, TimeUnit.SECONDS); c2.await(10, TimeUnit.SECONDS); c3.await(10, TimeUnit.SECONDS); m_subscriber.disconnect(); assertEquals(0, c1.getCount()); assertEquals(10, c2.getCount()); assertEquals(0, c3.getCount()); // Overriding case 2: 1 receiver per event type, 2nd receiver is overridden two times, but second time is invalid m_subscriber = (NCSubscriber)getContainerServices().createNotificationChannelSubscriber(CHANNEL_NAME); c1 = new CountDownLatch(nEvents); c2 = new CountDownLatch(nEvents); c3 = new CountDownLatch(nEvents); m_subscriber.addSubscription(new EventReceiver1(c1)); m_subscriber.addSubscription(new EventReceiver2(c2)); try { m_subscriber.addSubscription(new EventReceiver1(c3) { public Class<statusBlockEvent1> getEventType() { return null; } }); fail("Event receiver is invalid, as it returns a null event type"); } catch(CannotAddSubscriptionException e) { } m_subscriber.startReceivingEvents(); publish(nEvents, EventType.statusBlock1); publish(nEvents, EventType.statusBlock2); c1.await(10, TimeUnit.SECONDS); c2.await(10, TimeUnit.SECONDS); c3.await(10, TimeUnit.SECONDS); m_subscriber.disconnect(); assertEquals(0, c1.getCount()); assertEquals(0, c2.getCount()); assertEquals(nEvents, c3.getCount()); } public void testSubscriptionGenericReceiving() throws Exception { int nEvents = 10; // Simple case: just the generic receiver, receiving 2 event types CountDownLatch c1 = new CountDownLatch(2*nEvents); m_subscriber.addGenericSubscription(new GenericEventReceiver(c1)); m_subscriber.startReceivingEvents(); publish(nEvents, EventType.statusBlock1); publish(nEvents, EventType.statusBlock2); c1.await(10, TimeUnit.SECONDS); m_subscriber.disconnect(); assertEquals(0, c1.getCount()); // Overriding case: generic subscriber, then overridden by a different one m_subscriber = (NCSubscriber)getContainerServices().createNotificationChannelSubscriber(CHANNEL_NAME); c1 = new CountDownLatch(2*nEvents); CountDownLatch c2 = new CountDownLatch(2*nEvents); m_subscriber.addGenericSubscription(new GenericEventReceiver(c1)); m_subscriber.addGenericSubscription(new GenericEventReceiver(c2)); m_subscriber.startReceivingEvents(); publish(nEvents, EventType.statusBlock1); publish(nEvents, EventType.statusBlock2); c1.await(10, TimeUnit.SECONDS); c2.await(10, TimeUnit.SECONDS); m_subscriber.disconnect(); assertEquals(2*nEvents, c1.getCount()); assertEquals(0, c2.getCount()); // Add/remove case: add generic subscription, then remove it, then listen: nothing should arrive m_subscriber = (NCSubscriber)getContainerServices().createNotificationChannelSubscriber(CHANNEL_NAME); c1 = new CountDownLatch(2*nEvents); m_subscriber.addGenericSubscription(new GenericEventReceiver(c1)); m_subscriber.removeGenericSubscription(); m_subscriber.startReceivingEvents(); publish(nEvents, EventType.statusBlock1); publish(nEvents, EventType.statusBlock2); c1.await(10, TimeUnit.SECONDS); m_subscriber.disconnect(); assertEquals(2*nEvents, c1.getCount()); // Mixed case: a generic receiver + receiver for event type 1 m_subscriber = (NCSubscriber)getContainerServices().createNotificationChannelSubscriber(CHANNEL_NAME); c1 = new CountDownLatch(2*nEvents); c2 = new CountDownLatch(nEvents); m_subscriber.addGenericSubscription(new GenericEventReceiver(c1)); m_subscriber.addSubscription(new EventReceiver2(c2)); m_subscriber.startReceivingEvents(); publish(nEvents, EventType.statusBlock1); publish(nEvents, EventType.statusBlock2); c1.await(10, TimeUnit.SECONDS); c2.await(10, TimeUnit.SECONDS); m_subscriber.disconnect(); assertEquals(10, c1.getCount()); // we set 2*nEvents as the initial count for c1 assertEquals(0, c2.getCount()); } public void testLifecycle() throws Exception { try { m_subscriber.suspend(); fail("suspend() should fail, as we're not yet connected"); } catch(IllegalStateException e) { } try { m_subscriber.resume(); fail("resume() should fail, as we're not yet connected"); } catch(IllegalStateException e) { } try { m_subscriber.disconnect(); fail("disconnect() should fail, as we're not yet connected"); } catch(IllegalStateException e) { } m_subscriber.startReceivingEvents(); assertFalse(m_subscriber.isDisconnected()); // Verify that client can connect multiple times. // This is an (ugly) side effect of having to enable -AllowReconnect in the TAO notify service configuration file, // which is needed for reconnection after a notify service crash. // See also TAO/ACE_wrappers/build/linux/TAO/docs/notification/reliability.html // and email by Jorge Avarias from 2011-02-18 ("NotifyService -AllowReconnect option"): // "[...] component is able to detect that NC was down, but when the component tries // to reconnect to the NC it fails with several CORBA Exceptions because is unable to reconnect to the NC." try { m_subscriber.startReceivingEvents(); } catch(IllegalStateException e) { fail("Second call to startReceivingEvents() should be OK. Check TAO option -AllowReconnect!"); } try { m_subscriber.resume(); fail("resume() should fail, as we're not suspended yet"); } catch(IllegalStateException e) { } m_subscriber.suspend(); try { m_subscriber.suspend(); fail("suspend() should fail, as we're already suspended"); } catch (IllegalStateException e) { } try { m_subscriber.startReceivingEvents(); fail("startReceivingEvents() should fail, as we're already connected"); } catch (IllegalStateException e) { } m_subscriber.resume(); m_subscriber.disconnect(); assertTrue(m_subscriber.isDisconnected()); try { m_subscriber.disconnect(); fail("disconnect() should fail, as we're already disconnected"); } catch (IllegalStateException e) { } try { m_subscriber.suspend(); fail("suspend() should fail, as we're already disconnected"); } catch (IllegalStateException e) { } try { m_subscriber.resume(); fail("resume() should fail, as we're already disconnected"); } catch (IllegalStateException e) { } } /* Support methods */ private void publish(int nEvents, EventType type) { IDLEntity event = null; if( type.equals(EventType.statusBlock1) ) { event = new statusBlockEvent1(); ((statusBlockEvent1)event).counter1 = 0; ((statusBlockEvent1)event).counter2 = 0; ((statusBlockEvent1)event).flipFlop = true; ((statusBlockEvent1)event).onOff = alma.ADMINTEST1.OnOffStates.ON; } else if( type.equals(EventType.statusBlock2) ) { event = new statusBlockEvent2(); ((statusBlockEvent2)event).counter1 = 0; ((statusBlockEvent2)event).counter2 = 0; ((statusBlockEvent2)event).flipFlop = true; ((statusBlockEvent2)event).onOff = alma.ADMINTEST2.OnOffStates.ON; } try { for(int i=0; i!=nEvents; i++) m_publisher.publishEvent(event); } catch (AcsJException e) { e.printStackTrace(); } } /* Support classes */ private abstract class EventReceiverWithCounter { private CountDownLatch m_countDownLatch; public EventReceiverWithCounter(CountDownLatch c) { m_countDownLatch = c; } public void receive(EventDescription event) { if( m_countDownLatch != null ) m_countDownLatch.countDown(); } } private class EventReceiver1 extends EventReceiverWithCounter implements Callback<statusBlockEvent1> { public EventReceiver1() { super(null); } public EventReceiver1(CountDownLatch c) { super(c); } public void receive(statusBlockEvent1 event, EventDescription eventDescrip) { super.receive(eventDescrip); } public Class<statusBlockEvent1> getEventType() { return statusBlockEvent1.class; } } private class EventReceiver2 extends EventReceiverWithCounter implements Callback<statusBlockEvent2> { public EventReceiver2() { super(null); } public EventReceiver2(CountDownLatch c) { super(c); } public void receive(statusBlockEvent2 event, EventDescription eventDescrip) { super.receive(eventDescrip); } public Class<statusBlockEvent2> getEventType() { return statusBlockEvent2.class; } } private class GenericEventReceiver extends EventReceiverWithCounter implements GenericCallback { public GenericEventReceiver() { super(null); } public GenericEventReceiver(CountDownLatch c) { super(c); } public void receive(IDLEntity event, EventDescription eventDescrip) { super.receive(eventDescrip); } } }
package no.finn.unleash; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.BiFunction; public final class FakeUnleash implements Unleash { private boolean enableAll = false; private boolean disableAll = false; private Map<String, Boolean> features = new HashMap<>(); private Map<String, Variant> variants = new HashMap<>(); @Override public boolean isEnabled(String toggleName) { return isEnabled(toggleName, false); } @Override public boolean isEnabled(String toggleName, boolean defaultSetting) { if(enableAll) { return true; } else if(disableAll) { return false; } else { return features.getOrDefault(toggleName, defaultSetting); } } @Override public boolean isEnabled(String toggleName, UnleashContext context, BiFunction<String, UnleashContext, Boolean> fallbackAction) { return isEnabled(toggleName, fallbackAction); } @Override public boolean isEnabled(String toggleName, BiFunction<String, UnleashContext, Boolean> fallbackAction) { if(!features.containsKey(toggleName)) { return fallbackAction.apply(toggleName, UnleashContext.builder().build()); } return isEnabled(toggleName); } @Override public Variant getVariant(String toggleName, UnleashContext context) { return getVariant(toggleName, Variant.DISABLED_VARIANT); } @Override public Variant getVariant(String toggleName, UnleashContext context, Variant defaultValue) { return getVariant(toggleName, defaultValue); } @Override public Variant getVariant(String toggleName) { return getVariant(toggleName, Variant.DISABLED_VARIANT); } @Override public Variant getVariant(String toggleName, Variant defaultValue) { if(isEnabled(toggleName) && variants.containsKey(toggleName)) { return variants.get(toggleName); } else { return defaultValue; } } @Override public List<String> getFeatureToggleNames() { return new ArrayList<>(features.keySet()); } public void enableAll() { disableAll = false; enableAll = true; features.clear(); } public void disableAll() { disableAll = true; enableAll = false; features.clear(); } public void resetAll() { disableAll = false; enableAll = false; features.clear(); variants.clear(); } public void enable(String... features) { for(String name: features) { this.features.put(name, true); } } public void disable(String... features) { for(String name: features) { this.features.put(name, false); } } public void reset(String... features) { for(String name: features) { this.features.remove(name); } } public void setVariant(String t1, Variant a) { variants.put(t1, a); } }
package de.slg.leoapp.sqlite; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import de.slg.klausurplan.utility.Klausur; import de.slg.leoapp.utility.Utils; public class SQLiteConnectorKlausurplan extends SQLiteOpenHelper { public static final String DATABASE_NAME = "klausurplan"; private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.GERMANY); private static final String TABLE_KLAUSUREN = "klausuren"; private static final String KLAUSUR_ID = "id"; private static final String KLAUSUR_TITEL = "title"; private static final String KLAUSUR_STUFE = "stufe"; private static final String KLAUSUR_DATUM = "datum"; public static final String WHERE_ONLY_GRADE = WHERE_ONLY_CREATED + " OR (" + KLAUSUR_STUFE + " = '" + Utils.getUserStufe() + "' AND " + KLAUSUR_DATUM + " > '" + getMinDate() + "')"; private static final String KLAUSUR_NOTIZ = "notiz"; private static final String KLAUSUR_IN_STUNDENPLAN = "in_stundenplan"; public static final String WHERE_ONLY_TIMETABLE = WHERE_ONLY_CREATED + " OR (" + KLAUSUR_STUFE + " = '" + Utils.getUserStufe() + "' AND " + KLAUSUR_IN_STUNDENPLAN + " = 1 AND " + KLAUSUR_DATUM + " > '" + getMinDate() + "')"; private static final String KLAUSUR_HERUNTERGELADEN = "heruntergeladen"; public static final String WHERE_ONLY_CREATED = KLAUSUR_HERUNTERGELADEN + " = 0"; private final SQLiteDatabase database; public SQLiteConnectorKlausurplan(Context context) { super(context, DATABASE_NAME, null, 1); database = getWritableDatabase(); } private static String getMinDate() { Calendar calendar = new GregorianCalendar(); calendar.add(Calendar.MONTH, -Utils.getController().getPreferences().getInt("pref_key_delete", 12)); return dateFormat.format(calendar.getTime()); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_KLAUSUREN + " (" + KLAUSUR_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + KLAUSUR_TITEL + " TEXT NOT NULL, " + KLAUSUR_STUFE + " TEXT NOT NULL, " + KLAUSUR_DATUM + " TEXT NOT NULL, " + KLAUSUR_NOTIZ + " INTEGER NOT NULL, " + KLAUSUR_IN_STUNDENPLAN + " INTEGER NOT NULL, " + KLAUSUR_HERUNTERGELADEN + " INTEGER NOT NULL" + ")"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_KLAUSUREN); onCreate(db); } @Override public synchronized void close() { super.close(); database.close(); } public long insert(String titel, String stufe, Date datum, String notiz, boolean inStundenplan, boolean heruntergeladen) { ContentValues values = new ContentValues(); values.put(KLAUSUR_TITEL, titel); values.put(KLAUSUR_STUFE, stufe); values.put(KLAUSUR_DATUM, dateFormat.format(datum)); values.put(KLAUSUR_NOTIZ, notiz); values.put(KLAUSUR_IN_STUNDENPLAN, inStundenplan); values.put(KLAUSUR_HERUNTERGELADEN, heruntergeladen); return database.insert(TABLE_KLAUSUREN, null, values); } public void setTitel(long id, String titel) { ContentValues values = new ContentValues(); values.put(KLAUSUR_TITEL, titel); database.update(TABLE_KLAUSUREN, values, KLAUSUR_ID + " = " + id, null); } public void setDatum(long id, Date datum) { ContentValues values = new ContentValues(); values.put(KLAUSUR_DATUM, dateFormat.format(datum)); database.update(TABLE_KLAUSUREN, values, KLAUSUR_ID + " = " + id, null); } public void setNotiz(long id, String notiz) { ContentValues values = new ContentValues(); values.put(KLAUSUR_NOTIZ, notiz); database.update(TABLE_KLAUSUREN, values, KLAUSUR_ID + " = " + id, null); } public void updateStundenplan(String fach, boolean schriftlich) { ContentValues values = new ContentValues(); values.put(KLAUSUR_IN_STUNDENPLAN, schriftlich); database.update(TABLE_KLAUSUREN, values, KLAUSUR_TITEL + " LIKE '" + fach + "%'", null); } public Klausur[] getExams(String where) { Utils.logDebug(where); Cursor cursor = database.query(TABLE_KLAUSUREN, new String[]{KLAUSUR_ID, KLAUSUR_TITEL, KLAUSUR_DATUM, KLAUSUR_NOTIZ}, where, null, null, null, KLAUSUR_DATUM); Klausur[] klausuren = new Klausur[cursor.getCount()]; int i = 0; for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext(), i++) { klausuren[i] = new Klausur(cursor.getInt(0), cursor.getString(1), parse(cursor.getString(2)), cursor.getString(3)); } cursor.close(); return klausuren; } public Klausur getNextExam() { Cursor cursor = database.query(TABLE_KLAUSUREN, new String[]{KLAUSUR_ID, KLAUSUR_TITEL, KLAUSUR_DATUM, KLAUSUR_NOTIZ}, KLAUSUR_DATUM + " = '" + getDate() + "' AND " + KLAUSUR_IN_STUNDENPLAN + " = 1 OR " + KLAUSUR_HERUNTERGELADEN + " = 0", null, null, null, KLAUSUR_DATUM, "1"); Klausur k = null; if (cursor.getCount() > 0) { cursor.moveToFirst(); k = new Klausur(cursor.getInt(0), cursor.getString(1), parse(cursor.getString(2)), cursor.getString(3)); } cursor.close(); return k; } public void deleteAllDownloaded() { database.delete(TABLE_KLAUSUREN, KLAUSUR_HERUNTERGELADEN + " = 1", null); } public void delete(long id) { database.delete(TABLE_KLAUSUREN, KLAUSUR_ID + " = " + id, null); } private Date parse(String date) { try { return dateFormat.parse(date); } catch (ParseException e) { e.printStackTrace(); return null; } } private String getDate() { Calendar calendar = new GregorianCalendar(); if (calendar.get(Calendar.HOUR_OF_DAY) >= 15) { calendar.add(Calendar.DAY_OF_MONTH, 1); } return dateFormat.format(calendar.getTime()); } }
package org.basex.query; import static org.basex.query.QueryText.*; import static org.basex.query.util.Err.*; import static org.basex.util.Token.*; import static org.basex.util.ft.FTFlag.*; import java.io.*; import java.util.*; import org.basex.core.*; import org.basex.io.*; import org.basex.io.serial.*; import org.basex.query.expr.*; import org.basex.query.expr.CmpG.OpG; import org.basex.query.expr.CmpN.OpN; import org.basex.query.expr.CmpV.OpV; import org.basex.query.expr.Expr.Use; import org.basex.query.expr.Context; import org.basex.query.expr.List; import org.basex.query.flwor.*; import org.basex.query.ft.*; import org.basex.query.func.*; import org.basex.query.iter.*; import org.basex.query.path.*; import org.basex.query.up.expr.*; import org.basex.query.util.*; import org.basex.query.util.format.*; import org.basex.query.value.*; import org.basex.query.value.item.*; import org.basex.query.value.seq.*; import org.basex.query.value.type.*; import org.basex.query.value.type.SeqType.Occ; import org.basex.util.*; import org.basex.util.ft.*; import org.basex.util.hash.*; import org.basex.util.list.*; public class QueryParser extends InputParser { /** QName check: URI is mandatory. */ private static final byte[] URICHECK = {}; /** QName check: skip namespace check. */ private static final byte[] SKIPCHECK = {}; /** Reserved function names (sorted). */ private static final byte[][] KEYWORDS = { NodeType.ATT.string(), NodeType.COM.string(), NodeType.DOC.string(), NodeType.ELM.string(), token(EMPTY_SEQUENCE), FuncType.ANY_FUN.string(), token(IF), AtomType.ITEM.string(), NodeType.NSP.string(), NodeType.NOD.string(), NodeType.PI.string(), token(SCHEMA_ATTRIBUTE), token(SCHEMA_ELEMENT), token(SWITCH), NodeType.TXT.string(), token(TYPESWITCH) }; /** Query context. */ final QueryContext ctx; /** Temporary token builder. */ private final TokenBuilder tok = new TokenBuilder(); /** Modules loaded by the current file. */ private final TokenList modules = new TokenList(); /** Name of current module. */ private QNm module; /** Alternative error output. */ private Err alter; /** Alternative error description. */ private QNm alterFunc; /** Alternative position. */ private int ap; /** Declared serialization options. */ private final StringList serial = new StringList(); /** Declaration flag. */ private boolean declElem; /** Declaration flag. */ private boolean declFunc; /** Declaration flag. */ private boolean declColl; /** Declaration flag. */ private boolean declConstr; /** Declaration flag. */ private boolean declSpaces; /** Declaration flag. */ private boolean declOrder; /** Declaration flag. */ private boolean declReval; /** Declaration flag. */ private boolean declGreat; /** Declaration flag. */ private boolean declPres; /** Declaration flag. */ private boolean declBase; /** Declaration flag. */ private boolean declItem; /** Declaration flag. */ private boolean declVars; /** Cached QNames. */ private final ArrayList<QNmCheck> names = new ArrayList<QNmCheck>(); /** * Constructor. * @param in input * @param c query context * @throws QueryException query exception */ public QueryParser(final String in, final QueryContext c) throws QueryException { super(in); ctx = c; // parse pre-defined external variables final String bind = ctx.context.prop.get(Prop.BINDINGS).trim(); final StringBuilder key = new StringBuilder(); final StringBuilder val = new StringBuilder(); boolean first = true; final int sl = bind.length(); for(int s = 0; s < sl; s++) { final char ch = bind.charAt(s); if(first) { if(ch == '=') { first = false; } else { key.append(ch); } } else { if(ch == ',') { if(s + 1 == sl || bind.charAt(s + 1) != ',') { bind(key, val); key.setLength(0); val.setLength(0); first = true; continue; } // commas are escaped by a second comma s++; } val.append(ch); } } bind(key, val); } /** * Binds the specified variable. * If a URI is specified, the query is treated as a module. * @param key key * @param val value * @throws QueryException query exception */ private void bind(final StringBuilder key, final StringBuilder val) throws QueryException { final String k = key.toString().trim(); if(!k.isEmpty()) ctx.bind(k, new Atm(val.toString()), null); } /** * Parses the query. * @return resulting root expression * @throws QueryException query exception */ public final Expr parse() throws QueryException { return parse(null); } /** * Parses the specified query or module. * If the specified uri is {@code null}, the query is parsed as main module. * @param uri module uri. * @return resulting expression, or the name of the module * @throws QueryException query exception */ public final Expr parse(final byte[] uri) throws QueryException { file(ctx.sc.baseIO(), ctx.context); if(!more()) error(QUERYEMPTY); // checks if the query string contains invalid characters for(int i = 0; i < il;) { // only retrieve code points for large character codes (faster) int cp = input.charAt(i); final boolean hs = cp >= Character.MIN_HIGH_SURROGATE; if(hs) cp = input.codePointAt(i); if(!XMLToken.valid(cp)) { ip = i; error(QUERYINV, cp); } i += hs ? Character.charCount(cp) : 1; } final Expr expr = module(uri); if(more()) { if(alter != null) error(); final String rest = rest(); ip++; if(uri != null) error(MODEXPR, rest); error(QUERYEND, rest); } // completes the parsing step assignURI(0); if(ctx.sc.nsElem != null) ctx.sc.ns.add(EMPTY, ctx.sc.nsElem, null); // set default decimal format final byte[] empty = new QNm(EMPTY).eqname(); if(ctx.sc.decFormats.get(empty) == null) { ctx.sc.decFormats.add(empty, new DecFormatter()); } // check function calls ctx.funcs.check(); // check placement of updating expressions if any updating expressions have been found if(ctx.updates != null) { ctx.funcs.checkUp(); ctx.vars.checkUp(); expr.checkUp(); } return expr; } /** * Parses the specified query and starts with the "Module" rule. * If the specified uri is {@code null}, the query is parsed as main module. * @param u module uri * @return resulting expression * @throws QueryException query exception */ public final Expr module(final byte[] u) throws QueryException { try { Expr expr = null; versionDecl(); if(u == null) { final int i = ip; if(wsConsumeWs(MODULE, NSPACE, null)) error(MAINMOD); ip = i; expr = mainModule(); if(expr == null) { if(alter != null) error(); else error(EXPREMPTY); } } else { expr = moduleDecl(u); } return expr; } catch(final QueryException ex) { mark(); ex.pos(this); throw ex; } } /** * Parses the "VersionDecl" rule. * @throws QueryException query exception */ private void versionDecl() throws QueryException { final int i = ip; if(!wsConsumeWs(XQUERY)) return; final boolean version = wsConsumeWs(VERSION); if(version) { // parse xquery version final String ver = string(stringLiteral()); if(ver.equals(XQ10)) ctx.sc.xquery3 = false; else if(eq(ver, XQ11, XQ30)) ctx.sc.xquery3 = true; else error(XQUERYVER, ver); } // parse xquery encoding (ignored, as input always comes in as string) if((version || ctx.sc.xquery3) && wsConsumeWs(ENCODING)) { final String enc = string(stringLiteral()); if(!supported(enc)) error(XQUERYENC2, enc); } else if(!version) { ip = i; return; } wsCheck(";"); } /** * Parses the "MainModule" rule. * Parses the "Setter" rule. * Parses the "QueryBody (= Expr)" rule. * @return query expression * @throws QueryException query exception */ private Expr mainModule() throws QueryException { prolog1(); prolog2(); return expr(); } /** * Parses the "ModuleDecl" rule. * @param u module uri (may be empty) * @return name of module * @throws QueryException query exception */ private QNm moduleDecl(final byte[] u) throws QueryException { wsCheck(MODULE); wsCheck(NSPACE); skipWS(); final byte[] name = ncName(XPNAME); wsCheck(IS); final byte[] uri = stringLiteral(); if(uri.length == 0) error(NSMODURI); module = new QNm(name, uri); ctx.sc.ns.add(name, uri, info()); skipWS(); check(';'); prolog1(); prolog2(); // check if import and declaration uri match // skip test if module has not been imported (in this case, URI is empty) if(u.length != 0 && !eq(u, uri)) error(WRONGMODULE, module.uri(), file); return module; } /** * Parses the "Prolog" rule. * Parses the "Setter" rule. * @throws QueryException query exception */ private void prolog1() throws QueryException { while(true) { final int i = ip; if(wsConsumeWs(DECLARE)) { if(wsConsumeWs(DEFAULT)) { if(!defaultNamespaceDecl() && !defaultCollationDecl() && !emptyOrderDecl() && !(ctx.sc.xquery3 && decimalFormatDecl(true))) error(DECLINCOMPLETE); } else if(wsConsumeWs(BOUNDARY_SPACE)) { boundarySpaceDecl(); } else if(wsConsumeWs(BASE_URI)) { baseURIDecl(); } else if(wsConsumeWs(CONSTRUCTION)) { constructionDecl(); } else if(wsConsumeWs(ORDERING)) { orderingModeDecl(); } else if(wsConsumeWs(REVALIDATION)) { revalidationDecl(); } else if(wsConsumeWs(COPY_NAMESPACES)) { copyNamespacesDecl(); } else if(ctx.sc.xquery3 && wsConsumeWs(DECIMAL_FORMAT)) { decimalFormatDecl(false); } else if(wsConsumeWs(NSPACE)) { namespaceDecl(); } else if(wsConsumeWs(FT_OPTION)) { final FTOpt fto = new FTOpt(); while(ftMatchOption(fto)); ctx.ftOpt().copy(fto); } else { ip = i; return; } } else if(wsConsumeWs(IMPORT)) { if(wsConsumeWs(SCHEMA)) { schemaImport(); } else if(wsConsumeWs(MODULE)) { moduleImport(); } else { ip = i; return; } } else { return; } skipWS(); check(';'); } } /** * Parses the "Prolog" rule. * @throws QueryException query exception */ private void prolog2() throws QueryException { while(true) { final int i = ip; if(!wsConsumeWs(DECLARE)) return; if(ctx.sc.xquery3 && wsConsumeWs(CONTEXT)) { contextItemDecl(); } else if(wsConsumeWs(OPTION)) { optionDecl(); } else if(wsConsumeWs(DEFAULT)) { error(PROLOGORDER); } else { final Ann ann = new Ann(); while(true) { if(wsConsumeWs(UPDATING)) { addAnnotation(ann, Ann.Q_UPDATING, Empty.SEQ); } else if(ctx.sc.xquery3 && consume('%')) { annotation(ann); } else { break; } } if(wsConsumeWs(VARIABLE)) { // variables cannot be updating if(ann.contains(Ann.Q_UPDATING)) error(UPDATINGVAR); varDecl(ann); } else if(wsConsumeWs(FUNCTION)) { functionDecl(ann); } else if(!ann.isEmpty()) { error(VARFUNC); } else { ip = i; return; } } skipWS(); check(';'); } } /** * Parses the "Annotation" rule. * @return annotations * @throws QueryException query exception */ private Ann annotations() throws QueryException { final Ann ann = new Ann(); while(wsConsume("%")) annotation(ann); skipWS(); return ann; } /** * Parses a single annotation. * @param ann annotations * @throws QueryException query exception */ private void annotation(final Ann ann) throws QueryException { final QNm name = eQName(QNAMEINV, ctx.sc.nsFunc); final ValueBuilder vb = new ValueBuilder(1); if(wsConsumeWs(PAR1)) { do { final Item it = literal(); if(it == null) error(ANNVALUE); vb.add(it); } while(wsConsumeWs(COMMA)); wsCheck(PAR2); } skipWS(); addAnnotation(ann, name, vb.value()); } /** * Adds a single annotation. * @param ann annotations * @param name name * @param value value * @throws QueryException query exception */ private void addAnnotation(final Ann ann, final QNm name, final Value value) throws QueryException { if(name.eq(Ann.Q_UPDATING)) { if(ann.contains(Ann.Q_UPDATING)) error(DUPLUPD); } else if(name.eq(Ann.Q_PUBLIC) || name.eq(Ann.Q_PRIVATE)) { // only one visibility modifier allowed if(ann.contains(Ann.Q_PUBLIC) || ann.contains(Ann.Q_PRIVATE)) error(DUPLVIS); } else if(NSGlobal.reserved(name.uri())) { // no global namespaces allowed error(ANNRES, name); } ann.add(name, value); } /** * Parses the "NamespaceDecl" rule. * @throws QueryException query exception */ private void namespaceDecl() throws QueryException { final byte[] pref = ncName(XPNAME); wsCheck(IS); final byte[] uri = stringLiteral(); if(ctx.sc.ns.staticURI(pref) != null) error(DUPLNSDECL, pref); ctx.sc.ns.add(pref, uri, info()); } /** * Parses the "RevalidationDecl" rule. * @throws QueryException query exception */ private void revalidationDecl() throws QueryException { if(declReval) error(DUPLREVAL); declReval = true; if(wsConsumeWs(STRICT) || wsConsumeWs(LAX)) error(NOREVAL); wsCheck(SKIP); } /** * Parses the "BoundarySpaceDecl" rule. * @throws QueryException query exception */ private void boundarySpaceDecl() throws QueryException { if(declSpaces) error(DUPLBOUND); declSpaces = true; final boolean spaces = wsConsumeWs(PRESERVE); if(!spaces) wsCheck(STRIP); ctx.sc.spaces = spaces; } /** * Parses the "DefaultNamespaceDecl" rule. * @return true if declaration was found * @throws QueryException query exception */ private boolean defaultNamespaceDecl() throws QueryException { final boolean elem = wsConsumeWs(ELEMENT); if(!elem && !wsConsumeWs(FUNCTION)) return false; wsCheck(NSPACE); final byte[] uri = stringLiteral(); if(eq(XMLURI, uri)) error(BINDXMLURI, uri, XML); if(eq(XMLNSURI, uri)) error(BINDXMLURI, uri, XMLNS); if(elem) { if(declElem) error(DUPLNS); declElem = true; ctx.sc.nsElem = uri.length == 0 ? null : uri; } else { if(declFunc) error(DUPLNS); declFunc = true; ctx.sc.nsFunc = uri.length == 0 ? null : uri; } return true; } /** * Parses the "OptionDecl" rule. * @throws QueryException query exception */ private void optionDecl() throws QueryException { skipWS(); final QNm name = eQName(QNAMEINV, URICHECK); final byte[] val = stringLiteral(); if(ctx.sc.xquery3 && eq(name.prefix(), OUTPUT)) { // output declaration final String key = string(name.local()); if(module != null) error(MODOUT); if(ctx.serProp == null) ctx.serProp = new SerializerProp(); if(ctx.serProp.get(key) == null) error(OUTWHICH, key); if(serial.contains(key)) error(OUTDUPL, key); ctx.serProp.set(key, string(val)); serial.add(key); } else if(eq(name.prefix(), DB)) { // project-specific declaration final String key = string(uc(name.local())); final Object obj = ctx.context.prop.get(key); if(obj == null) error(BASX_OPTIONS, key); // cache old value (to be reset after query evaluation) ctx.globalOpt.put(key, obj); ctx.dbOptions.put(key, string(val)); } // ignore unknown options } /** * Parses the "OrderingModeDecl" rule. * @throws QueryException query exception */ private void orderingModeDecl() throws QueryException { if(declOrder) error(DUPLORD); declOrder = true; ctx.sc.ordered = wsConsumeWs(ORDERED); if(!ctx.sc.ordered) wsCheck(UNORDERED); } /** * Parses the "emptyOrderDecl" rule. * @return true if declaration was found * @throws QueryException query exception */ private boolean emptyOrderDecl() throws QueryException { if(!wsConsumeWs(ORDER)) return false; wsCheck(EMPTYORD); if(declGreat) error(DUPLORDEMP); declGreat = true; ctx.sc.orderGreatest = wsConsumeWs(GREATEST); if(!ctx.sc.orderGreatest) wsCheck(LEAST); return true; } /** * Parses the "copyNamespacesDecl" rule. * Parses the "PreserveMode" rule. * Parses the "InheritMode" rule. * @throws QueryException query exception */ private void copyNamespacesDecl() throws QueryException { if(declPres) error(DUPLCOPYNS); declPres = true; ctx.sc.nsPreserve = wsConsumeWs(PRESERVE); if(!ctx.sc.nsPreserve) wsCheck(NO_PRESERVE); wsCheck(COMMA); ctx.sc.nsInherit = wsConsumeWs(INHERIT); if(!ctx.sc.nsInherit) wsCheck(NO_INHERIT); } /** * Parses the "DecimalFormatDecl" rule. * @param def default flag * @return true if declaration was found * @throws QueryException query exception */ private boolean decimalFormatDecl(final boolean def) throws QueryException { if(def && !wsConsumeWs(DECIMAL_FORMAT)) return false; // use empty name for default declaration final QNm name = def ? new QNm() : eQName(QNAMEINV, null); // check if format has already been declared if(ctx.sc.decFormats.get(name.eqname()) != null) error(DECDUPL); // create new format final HashMap<String, String> map = new HashMap<String, String>(); // collect all property declarations int n; do { n = map.size(); skipWS(); final String prop = string(ncName(null)); for(final String s : DECFORMATS) { if(!prop.equals(s)) continue; if(map.get(s) != null) error(DECDUPLPROP, s); wsCheck(IS); map.put(s, string(stringLiteral())); break; } if(map.isEmpty()) error(NODECLFORM, prop); } while(n != map.size()); // completes the format declaration ctx.sc.decFormats.add(name.eqname(), new DecFormatter(info(), map)); return true; } /** * Parses the "DefaultCollationDecl" rule. * @return query expression * @throws QueryException query exception */ private boolean defaultCollationDecl() throws QueryException { if(!wsConsumeWs(COLLATION)) return false; if(declColl) error(DUPLCOLL); declColl = true; final byte[] cl = ctx.sc.baseURI().resolve(Uri.uri(stringLiteral())).string(); if(!eq(URLCOLL, cl)) error(COLLWHICH, cl); return true; } /** * Parses the "BaseURIDecl" rule. * @throws QueryException query exception */ private void baseURIDecl() throws QueryException { if(declBase) error(DUPLBASE); declBase = true; final byte[] base = stringLiteral(); if(base.length != 0) ctx.sc.baseURI(string(base)); } /** * Parses the "SchemaImport" rule. * Parses the "SchemaPrefix" rule. * @throws QueryException query exception */ private void schemaImport() throws QueryException { if(wsConsumeWs(NSPACE)) { ncName(XPNAME); wsCheck(IS); } else if(wsConsumeWs(DEFAULT)) { wsCheck(ELEMENT); wsCheck(NSPACE); } final byte[] ns = stringLiteral(); if(ns.length == 0) error(NSEMPTY); if(wsConsumeWs(AT)) { do stringLiteral(); while(wsConsumeWs(COMMA)); } error(IMPLSCHEMA); } /** * Parses the "ModuleImport" rule. * @throws QueryException query exception */ private void moduleImport() throws QueryException { byte[] ns = EMPTY; if(wsConsumeWs(NSPACE)) { ns = ncName(XPNAME); wsCheck(IS); } final byte[] uri = trim(stringLiteral()); if(uri.length == 0) error(NSMODURI); if(modules.contains(uri)) error(DUPLMODULE, uri); modules.add(uri); // add non-default namespace if(ns != EMPTY) ctx.sc.ns.add(ns, uri, info()); try { // check modules at specified locations if(wsConsumeWs(AT)) { do { module(stringLiteral(), uri); } while(wsConsumeWs(COMMA)); return; } // check pre-declared module files final byte[] path = ctx.modDeclared.get(uri); if(path != null) { module(path, uri); return; } // check built-in modules for(final byte[] u : Function.URIS.values()) if(eq(uri, u)) return; // resolve module uri if(ctx.modules.addImport(uri, info(), this)) return; error(NOMODULE, uri); } catch(final StackOverflowError ex) { Util.debug(ex); error(CIRCMODULE); } } /** * Parses the specified module. * @param path file path * @param uri module uri * @throws QueryException query exception */ public void module(final byte[] path, final byte[] uri) throws QueryException { // get absolute path final IO io = ctx.sc.io(string(path)); final byte[] p = token(io.path()); // check if module has already been parsed final byte[] u = ctx.modParsed.get(p); if(u != null) { if(!eq(uri, u)) error(WRONGMODULE, uri, ctx.context.user.has(Perm.ADMIN) ? io.path() : io.name()); return; } ctx.modParsed.add(p, uri); // read module String qu = null; try { qu = string(io.read()); } catch(final IOException ex) { error(NOMODULEFILE, ctx.context.user.has(Perm.ADMIN) ? io.path() : io.name()); } final StaticContext sc = ctx.sc; ctx.sc = new StaticContext(); ctx.sc.baseURI(io.path()); ctx.sc.xquery3 = sc.xquery3; new QueryParser(qu, ctx).parse(uri); ctx.sc = sc; } /** * Parses the "ContextItemDecl" rule. * @throws QueryException query exception */ private void contextItemDecl() throws QueryException { wsCheck(ITEMM); if(declItem) error(DUPLITEM); declItem = true; if(module != null) error(DECITEM); ctx.sc.initType = wsConsumeWs(AS) ? itemType().type : null; if(!wsConsumeWs(EXTERNAL)) wsCheck(ASSIGN); else if(!wsConsumeWs(ASSIGN)) return; ctx.ctxItem = check(single(), NOVARDECL); if(ctx.ctxItem.uses(Use.UPD)) UPCTX.thrw(info(), ctx.ctxItem); } /** * Parses the "VarDecl" rule. * @param ann annotations * @throws QueryException query exception */ private void varDecl(final Ann ann) throws QueryException { final Var v = typedVar(ann); if(module != null && !eq(v.name.uri(), module.uri())) error(MODNS, v); // check if variable has already been declared final Var old = ctx.vars.get(v.name); // throw no error if a variable has been externally bound if(old != null && old.declared) error(VARDEFINE, old); (old != null ? old : v).declared = true; if(wsConsumeWs(EXTERNAL)) { // bind value with new type if(old != null && v.type != null) old.reset(v.type, ctx); // bind default value if(ctx.sc.xquery3 && wsConsumeWs(ASSIGN)) { v.bind(check(single(), NOVARDECL), ctx); } } else { wsCheck(ASSIGN); v.bind(check(single(), NOVARDECL), ctx); } // bind variable if not done yet if(old == null) ctx.vars.updateGlobal(v); } /** * Parses a variable declaration with optional type. * @param ann annotations * @return parsed variable * @throws QueryException query exception */ private Var typedVar(final Ann ann) throws QueryException { return Var.create(ctx, info(), varName(), optAsType(), ann); } /** * Parses an optional SeqType declaration. * @return type if preceded by {@code as}, {@code null} otherwise * @throws QueryException query exception */ private SeqType optAsType() throws QueryException { return wsConsumeWs(AS) ? sequenceType() : null; } /** * Parses the "ConstructionDecl" rule. * @throws QueryException query exception */ private void constructionDecl() throws QueryException { if(declConstr) error(DUPLCONS); declConstr = true; ctx.sc.strip = wsConsumeWs(STRIP); if(!ctx.sc.strip) wsCheck(PRESERVE); } /** * Parses the "FunctionDecl" rule. * @param ann annotations * @throws QueryException query exception */ private void functionDecl(final Ann ann) throws QueryException { final QNm name = eQName(FUNCNAME, ctx.sc.nsFunc); if(keyword(name)) error(RESERVED, name); if(module != null && !eq(name.uri(), module.uri())) error(MODNS, name); wsCheck(PAR1); final VarStack vl = ctx.vars.cache(4); final Var[] args = paramList(); wsCheck(PAR2); final UserFunc func = new UserFunc(info(), name, args, optAsType(), ann, true); if(func.updating) ctx.updating(true); ctx.funcs.add(func, info()); if(!wsConsumeWs(EXTERNAL)) func.expr = enclosed(NOFUNBODY); ctx.vars.reset(vl); } /** * Checks if the specified name equals reserved function names. * @param name name to be checked * @return result of check */ private static boolean keyword(final QNm name) { if(name.hasPrefix()) return false; final byte[] str = name.string(); for(final byte[] key : KEYWORDS) if(eq(key, str)) return true; return false; } /** * Parses a ParamList. * @return declared variables * @throws QueryException query exception */ private Var[] paramList() throws QueryException { Var[] args = { }; skipWS(); while(true) { if(curr() != '$') { if(args.length == 0) break; check('$'); } final Var var = typedVar(null); ctx.vars.add(var); for(final Var v : args) if(v.name.eq(var.name)) error(FUNCDUPL, var); args = Array.add(args, var); if(!consume(',')) break; skipWS(); } return args; } /** * Parses the "EnclosedExpr" rule. * @param err error message * @return query expression * @throws QueryException query exception */ private Expr enclosed(final Err err) throws QueryException { wsCheck(BRACE1); final Expr e = check(expr(), err); wsCheck(BRACE2); return e; } /** * Parses the "Expr" rule. * @return query expression * @throws QueryException query exception */ private Expr expr() throws QueryException { final Expr e = single(); if(e == null) { if(more()) return null; if(alter != null) error(); else error(NOEXPR); } if(!wsConsume(COMMA)) return e; final ExprList el = new ExprList(e); do add(el, single()); while(wsConsume(COMMA)); return new List(info(), el.finish()); } /** * Parses the "ExprSingle" rule. * @return query expression * @throws QueryException query exception */ private Expr single() throws QueryException { alter = null; Expr e = flwor(); if(e == null) e = quantified(); if(e == null) e = switchh(); if(e == null) e = typeswitch(); if(e == null) e = iff(); if(e == null) e = tryCatch(); if(e == null) e = insert(); if(e == null) e = deletee(); if(e == null) e = rename(); if(e == null) e = replace(); if(e == null) e = transform(); if(e == null) e = or(); return e; } /** * Parses the "FLWORExpr" rule. * Parses the "WhereClause" rule. * Parses the "OrderByClause" rule. * Parses the "OrderSpecList" rule. * Parses the "GroupByClause" rule. * @return query expression * @throws QueryException query exception */ private Expr flwor() throws QueryException { // XQuery30: tumbling window, sliding window, count, allowing empty // (still to be parsed and implemented) final int s = ctx.vars.size(); final ForLet[] fl = forLet(); if(fl == null) return null; Expr where = null; if(wsConsumeWs(WHERE)) { ap = ip; where = check(single(), NOWHERE); alter = NOWHERE; } Group group = null; if(ctx.sc.xquery3 && wsConsumeWs(GROUP)) { wsCheck(BY); ap = ip; GroupSpec[] grp = null; do grp = groupSpec(fl, grp); while(wsConsume(COMMA)); // find all non-grouping variables that aren't shadowed final ArrayList<Var> ng = new ArrayList<Var>(); final TokenSet set = new TokenSet(); for(final GroupSpec spec : grp) set.add(spec.grp.name.eqname()); for(int i = fl.length; --i >= 0;) { for(final Var v : fl[i].vars()) { final byte[] eqn = v.name.eqname(); if(!set.contains(eqn)) { ng.add(v); set.add(eqn); } } } // add new copies for all non-grouping variables final Var[] ngrp = new Var[ng.size()]; for(int i = ng.size(); --i >= 0;) { final Var v = ng.get(i); // if one groups variables such as $x as xs:integer, then the resulting // sequence isn't compatible with the type and can't be assigned ngrp[i] = Var.create(ctx, info(), v.name, v.type != null && v.type.one() ? SeqType.get(v.type.type, Occ.ONE_MORE) : null, null); ctx.vars.add(ngrp[i]); } group = new Group(grp[0].info, grp, new Var[][] { ng.toArray(new Var[ng.size()]), ngrp }); alter = GRPBY; } Order order = null; final boolean stable = wsConsumeWs(STABLE); if(stable) wsCheck(ORDER); if(stable || wsConsumeWs(ORDER)) { wsCheck(BY); ap = ip; OrderBy[] ob = null; do ob = orderSpec(ob); while(wsConsume(COMMA)); // don't sort if all order-by clauses are empty if(ob != null) { ob = Array.add(ob, new OrderByStable(info())); order = new Order(ob[0].info, ob); } alter = ORDERBY; } if(!wsConsumeWs(RETURN)) { if(alter != null) error(); error(where == null ? FLWORWHERE : order == null ? FLWORORD : FLWORRET); } final Expr ret = check(single(), NORETURN); ctx.vars.size(s); return GFLWOR.get(fl, where, order, group, ret, info()); } /** * Parses the "ForClause" rule. * Parses the "PositionalVar" rule. * Parses the "LetClause" rule. * Parses the "FTScoreVar" rule. * @return query expression * @throws QueryException query exception */ private ForLet[] forLet() throws QueryException { ForLet[] fl = null; boolean comma = false; while(true) { final boolean fr = wsConsumeWs(FOR, DOLLAR, NOFOR); boolean score = !fr && wsConsumeWs(LET, SCORE, NOLET); if(score) wsCheck(SCORE); else if(!fr && !wsConsumeWs(LET, DOLLAR, NOLET)) return fl; do { if(comma && !fr) score = wsConsumeWs(SCORE); final QNm name = varName(); final SeqType type = score ? SeqType.DBL : optAsType(); final Var var = Var.create(ctx, info(), name, type, null); final Var ps = fr && wsConsumeWs(AT) ? Var.create(ctx, info(), varName(), SeqType.ITR, null) : null; final Var sc = fr && wsConsumeWs(SCORE) ? Var.create(ctx, info(), varName(), SeqType.DBL, null) : null; wsCheck(fr ? IN : ASSIGN); final Expr e = check(single(), NOVARDECL); ctx.vars.add(var); if(ps != null) { if(name.eq(ps.name)) error(DUPLVAR, var); ctx.vars.add(ps); } if(sc != null) { if(name.eq(sc.name)) error(DUPLVAR, var); if(ps != null && ps.name.eq(sc.name)) error(DUPLVAR, ps); ctx.vars.add(sc); } fl = fl == null ? new ForLet[1] : Arrays.copyOf(fl, fl.length + 1); fl[fl.length - 1] = fr ? new For(info(), e, var, ps, sc) : new Let( info(), e, var, score); score = false; comma = true; } while(wsConsume(COMMA)); comma = false; } } /** * Parses the "OrderSpec" rule. * Parses the "OrderModifier" rule. * * Empty order specs are ignored, {@code order} is then returned unchanged. * @param order order array * @return new order array * @throws QueryException query exception */ private OrderBy[] orderSpec(final OrderBy[] order) throws QueryException { final Expr e = check(single(), ORDERBY); boolean desc = false; if(!wsConsumeWs(ASCENDING)) desc = wsConsumeWs(DESCENDING); boolean least = !ctx.sc.orderGreatest; if(wsConsumeWs(EMPTYORD)) { least = !wsConsumeWs(GREATEST); if(least) wsCheck(LEAST); } if(wsConsumeWs(COLLATION)) { final byte[] coll = stringLiteral(); if(!eq(URLCOLL, coll)) error(WHICHCOLL, coll); } if(e.isEmpty()) return order; final OrderBy ord = new OrderByExpr(info(), e, desc, least); return order == null ? new OrderBy[] { ord } : Array.add(order, ord); } /** * Parses the "GroupingSpec" rule. * @param fl for/let clauses * @param group grouping specification * @return new group array * @throws QueryException query exception */ private GroupSpec[] groupSpec(final ForLet[] fl, final GroupSpec[] group) throws QueryException { final InputInfo ii = info(); final QNm name = varName(); final SeqType type = optAsType(); final Var var = Var.create(ctx, ii, name, type, null); final Expr by; if(type != null || wsConsume(ASSIGN)) { if(type != null) wsCheck(ASSIGN); by = check(single(), NOVARDECL); } else { final Var v = checkVar(var.name, GVARNOTDEFINED); // the grouping variable has to be declared by the same FLWOR expression boolean dec = false; for(final ForLet f : fl) { if(f.declares(v)) { dec = true; break; } } if(!dec) throw error(GVARNOTDEFINED, v); by = new VarRef(ii, v); } if(wsConsumeWs(COLLATION)) { final byte[] coll = stringLiteral(); if(!eq(URLCOLL, coll)) throw error(WHICHCOLL, coll); } // add the new grouping var ctx.vars.add(var); final GroupSpec grp = new GroupSpec(ii, var, by); return group == null ? new GroupSpec[] { grp } : Array.add(group, grp); } /** * Parses the "QuantifiedExpr" rule. * @return query expression * @throws QueryException query exception */ private Expr quantified() throws QueryException { final boolean some = wsConsumeWs(SOME, DOLLAR, NOSOME); if(!some && !wsConsumeWs(EVERY, DOLLAR, NOSOME)) return null; final int s = ctx.vars.size(); For[] fl = { }; do { final Var var = typedVar(null); wsCheck(IN); final Expr e = check(single(), NOSOME); ctx.vars.add(var); fl = Array.add(fl, new For(info(), e, var)); } while(wsConsume(COMMA)); wsCheck(SATISFIES); final Expr e = check(single(), NOSOME); ctx.vars.size(s); return new Quantifier(info(), fl, e, !some); } /** * Parses the "SwitchExpr" rule. * @return query expression * @throws QueryException query exception */ private Expr switchh() throws QueryException { if(!ctx.sc.xquery3 || !wsConsumeWs(SWITCH, PAR1, TYPEPAR)) return null; wsCheck(PAR1); final Expr expr = check(expr(), NOSWITCH); SwitchCase[] exprs = { }; wsCheck(PAR2); // collect all cases ExprList cases; do { cases = new ExprList(null); while(wsConsumeWs(CASE)) add(cases, single()); if(cases.size() == 1) { // add default case if(exprs.length == 0) error(WRONGCHAR, CASE, found()); wsCheck(DEFAULT); } wsCheck(RETURN); cases.set(0, single()); exprs = Array.add(exprs, new SwitchCase(info(), cases.finish())); } while(cases.size() != 1); return new Switch(info(), expr, exprs); } /** * Parses the "TypeswitchExpr" rule. * @return query expression * @throws QueryException query exception */ private Expr typeswitch() throws QueryException { if(!wsConsumeWs(TYPESWITCH, PAR1, TYPEPAR)) return null; wsCheck(PAR1); final Expr ts = check(expr(), NOTYPESWITCH); wsCheck(PAR2); TypeCase[] cases = { }; final int s = ctx.vars.size(); boolean cs; do { cs = wsConsumeWs(CASE); if(!cs) wsCheck(DEFAULT); skipWS(); QNm name = null; if(curr('$')) { name = varName(); if(cs) wsCheck(AS); } final Var v = Var.create(ctx, info(), name, cs ? sequenceType() : null, null); if(name != null) ctx.vars.add(v); wsCheck(RETURN); final Expr ret = check(single(), NOTYPESWITCH); cases = Array.add(cases, new TypeCase(info(), v, ret)); ctx.vars.size(s); } while(cs); if(cases.length == 1) error(NOTYPESWITCH); return new TypeSwitch(info(), ts, cases); } /** * Parses the "IfExpr" rule. * @return query expression * @throws QueryException query exception */ private Expr iff() throws QueryException { if(!wsConsumeWs(IF, PAR1, IFPAR)) return null; wsCheck(PAR1); final Expr iff = check(expr(), NOIF); wsCheck(PAR2); if(!wsConsumeWs(THEN)) error(NOIF); final Expr thn = check(single(), NOIF); if(!wsConsumeWs(ELSE)) error(NOIF); final Expr els = check(single(), NOIF); return new If(info(), iff, thn, els); } /** * Parses the "OrExpr" rule. * @return query expression * @throws QueryException query exception */ private Expr or() throws QueryException { final Expr e = and(); if(!wsConsumeWs(OR)) return e; final ExprList el = new ExprList(e); do add(el, and()); while(wsConsumeWs(OR)); return new Or(info(), el.finish()); } /** * Parses the "AndExpr" rule. * @return query expression * @throws QueryException query exception */ private Expr and() throws QueryException { final Expr e = comparison(); if(!wsConsumeWs(AND)) return e; final ExprList el = new ExprList(e); do add(el, comparison()); while(wsConsumeWs(AND)); return new And(info(), el.finish()); } /** * Parses the "ComparisonExpr" rule. * @return query expression * @throws QueryException query exception */ private Expr comparison() throws QueryException { final Expr e = ftContains(); if(e != null) { for(final OpV c : OpV.values()) if(wsConsumeWs(c.name)) return new CmpV(e, check(ftContains(), CMPEXPR), c, info()); for(final OpN c : OpN.values()) if(wsConsumeWs(c.name)) return new CmpN(e, check(ftContains(), CMPEXPR), c, info()); for(final OpG c : OpG.values()) if(wsConsumeWs(c.name)) return new CmpG(e, check(ftContains(), CMPEXPR), c, info()); } return e; } /** * Parses the "FTContainsExpr" rule. * @return query expression * @throws QueryException query exception */ private Expr ftContains() throws QueryException { final Expr e = stringConcat(); final int i = ip; // extensions to the official extension: "=>" and "<-" if(consume('=') && consume('>') || consume('<') && consume('-')) { skipWS(); } else if(!wsConsumeWs(CONTAINS) || !wsConsumeWs(TEXT)) { ip = i; return e; } final FTExpr select = ftSelection(false); if(wsConsumeWs(WITHOUT)) { wsCheck(CONTENT); union(); error(FTIGNORE); } return new FTContains(e, select, info()); } /** * Parses the "StringConcatExpr" rule. * @return query expression * @throws QueryException query exception */ private Expr stringConcat() throws QueryException { final Expr e = range(); if(e == null || !consume(CONCAT)) return e; final ExprList el = new ExprList(e); do add(el, range()); while(wsConsume(CONCAT)); return Function.CONCAT.get(info(), el.finish()); } /** * Parses the "RangeExpr" rule. * @return query expression * @throws QueryException query exception */ private Expr range() throws QueryException { final Expr e = additive(); if(!wsConsumeWs(TO)) return e; return new Range(info(), e, check(additive(), INCOMPLETE)); } /** * Parses the "AdditiveExpr" rule. * @return query expression * @throws QueryException query exception */ private Expr additive() throws QueryException { Expr e = multiplicative(); while(e != null) { final Calc c = consume('+') ? Calc.PLUS : consume('-') ? Calc.MINUS : null; if(c == null) break; e = new Arith(info(), e, check(multiplicative(), CALCEXPR), c); } return e; } /** * Parses the "MultiplicativeExpr" rule. * @return query expression * @throws QueryException query exception */ private Expr multiplicative() throws QueryException { Expr e = union(); while(e != null) { final Calc c = consume('*') ? Calc.MULT : wsConsumeWs(DIV) ? Calc.DIV : wsConsumeWs(IDIV) ? Calc.IDIV : wsConsumeWs(MOD) ? Calc.MOD : null; if(c == null) break; e = new Arith(info(), e, check(union(), CALCEXPR), c); } return e; } /** * Parses the "UnionExpr" rule. * @return query expression * @throws QueryException query exception */ private Expr union() throws QueryException { final Expr e = intersect(); if(e == null || !isUnion()) return e; final ExprList el = new ExprList(e); do add(el, intersect()); while(isUnion()); return new Union(info(), el.finish()); } /** * Checks if a union operator is found. * @return result of check * @throws QueryException query exception */ private boolean isUnion() throws QueryException { if(wsConsumeWs(UNION)) return true; final int i = ip; if(consume(PIPE) && !consume(PIPE)) return true; ip = i; return false; } /** * Parses the "IntersectExceptExpr" rule. * @return query expression * @throws QueryException query exception */ private Expr intersect() throws QueryException { final Expr e = instanceoff(); if(wsConsumeWs(INTERSECT)) { final ExprList el = new ExprList(e); do add(el, instanceoff()); while(wsConsumeWs(INTERSECT)); return new InterSect(info(), el.finish()); } if(wsConsumeWs(EXCEPT)) { final ExprList el = new ExprList(e); do add(el, instanceoff()); while(wsConsumeWs(EXCEPT)); return new Except(info(), el.finish()); } return e; } /** * Parses the "InstanceofExpr" rule. * @return query expression * @throws QueryException query exception */ private Expr instanceoff() throws QueryException { final Expr e = treat(); if(!wsConsumeWs(INSTANCE)) return e; wsCheck(OF); return new Instance(info(), e, sequenceType()); } /** * Parses the "TreatExpr" rule. * @return query expression * @throws QueryException query exception */ private Expr treat() throws QueryException { final Expr e = castable(); if(!wsConsumeWs(TREAT)) return e; wsCheck(AS); return new Treat(info(), e, sequenceType()); } /** * Parses the "CastableExpr" rule. * @return query expression * @throws QueryException query exception */ private Expr castable() throws QueryException { final Expr e = cast(); if(!wsConsumeWs(CASTABLE)) return e; wsCheck(AS); return new Castable(info(), e, simpleType()); } /** * Parses the "CastExpr" rule. * @return query expression * @throws QueryException query exception */ private Expr cast() throws QueryException { final Expr e = unary(); if(!wsConsumeWs(CAST)) return e; wsCheck(AS); return new Cast(info(), e, simpleType()); } /** * Parses the "UnaryExpr" rule. * @return query expression * @throws QueryException query exception */ private Expr unary() throws QueryException { boolean minus = false; boolean found = false; do { skipWS(); if(consume('-')) { minus ^= true; found = true; } else if(consume('+')) { found = true; } else { final Expr e = value(); return found ? new Unary(info(), check(e, EVALUNARY), minus) : e; } } while(true); } /** * Parses the "ValueExpr" rule. * @return query expression * @throws QueryException query exception */ private Expr value() throws QueryException { validate(); final Expr e = path(); return e != null ? e : extension(); } /** * Parses the "ValidateExpr" rule. * @throws QueryException query exception */ private void validate() throws QueryException { final int i = ip; if(!wsConsumeWs(VALIDATE)) return; boolean brace = true; if(consume(BRACE1)) { brace = false; } else if(consume(TYPE)) { final QNm qnm = eQName(QNAMEINV, SKIPCHECK); names.add(new QNmCheck(qnm)); } else if(!consume(STRICT) && !consume(LAX)) { ip = i; return; } if(brace) wsCheck(BRACE1); check(single(), NOVALIDATE); wsCheck(BRACE2); error(IMPLVAL); } /** * Parses the "ExtensionExpr" rule. * @return query expression * @throws QueryException query exception */ private Expr extension() throws QueryException { final Pragma[] pragmas = pragma(); return pragmas == null ? null : new Extension(info(), pragmas, enclosed(NOPRAGMA)); } /** * Parses the "Pragma" rule. * @return array of pragmas * @throws QueryException query exception */ private Pragma[] pragma() throws QueryException { if(!wsConsumeWs(PRAGMA)) return null; final ArrayList<Pragma> el = new ArrayList<Pragma>(); do { final QNm name = eQName(QNAMEINV, URICHECK); char c = curr(); if(c != ' tok.reset(); while(c != '#' || next() != ')') { if(c == 0) error(PRAGMAINV); tok.add(consume()); c = curr(); } el.add(new Pragma(name, tok.trim().finish())); ip += 2; } while(wsConsumeWs(PRAGMA)); return el.toArray(new Pragma[el.size()]); } /** * Parses the "PathExpr" rule. * @return query expression * @throws QueryException query exception */ private Expr path() throws QueryException { checkInit(); final ExprList el; Expr root = null; if(consume('/')) { root = new Root(info()); el = new ExprList(); final Expr ex; if(consume('/')) { // two slashes: absolute descendant path checkAxis(Axis.DESC); add(el, descOrSelf()); mark(); ex = step(); if(ex == null) { // two slashes, but no following step: error if(more()) checkInit(); error(PATHMISS, found()); } } else { // one slash: absolute child path checkAxis(Axis.CHILD); mark(); ex = step(); // no more steps: return root expression if(ex == null) return root; } add(el, ex); relativePath(el); } else { // relative path (no preceding slash) mark(); final Expr ex = step(); if(ex == null) return null; // return non-step expression if no path or map operator follows final boolean nostep = curr() != '/' && (curr() != '!' || next() == '='); if(nostep && !(ex instanceof AxisStep)) return ex; el = new ExprList(); if(ex instanceof AxisStep) add(el, ex); else root = ex; relativePath(el); } return Path.get(info(), root, el.finish()); } /** * Parses the "RelativePathExpr" rule. * @param el expression list * @throws QueryException query exception */ void relativePath(final ExprList el) throws QueryException { while(true) { boolean b = false; if(consume('/')) { if(consume('/')) { add(el, descOrSelf()); checkAxis(Axis.DESC); } else { checkAxis(Axis.CHILD); } } else if(next() != '=' && consume('!')) { b = true; } else { return; } mark(); Expr st = step(); if(st == null) error(PATHMISS, found()); if(b) st = new Bang(info(), st); add(el, st); } } /** * Returns a standard descendant-or-self::node() step. * @return step */ private AxisStep descOrSelf() { return AxisStep.get(info(), Axis.DESCORSELF, Test.NOD); } // methods for query suggestions /** * Performs an optional check init. */ protected void checkInit() { } /** * Performs an optional axis check. * @param axis axis */ @SuppressWarnings("unused") protected void checkAxis(final Axis axis) { } /** * Performs an optional test check. * @param test node test * @param attr attribute flag */ @SuppressWarnings("unused") protected void checkTest(final Test test, final boolean attr) { } /** * Checks a predicate. * @param open open flag */ @SuppressWarnings("unused") protected void checkPred(final boolean open) { } /** * Parses the "StepExpr" rule. * @return query expression * @throws QueryException query exception */ private Expr step() throws QueryException { final Expr e = postfix(); return e != null ? e : axisStep(); } /** * Parses the "AxisStep" rule. * @return query expression * @throws QueryException query exception */ private AxisStep axisStep() throws QueryException { Axis ax = null; Test test = null; if(wsConsume(DOT2)) { ax = Axis.PARENT; test = Test.NOD; checkTest(test, false); } else if(consume('@')) { ax = Axis.ATTR; test = nodeTest(true, true); checkTest(test, true); if(test == null) { --ip; error(NOATTNAME); } } else { for(final Axis a : Axis.values()) { final int i = ip; if(!wsConsumeWs(a.name)) continue; alter = NOLOCSTEP; if(wsConsumeWs(COLS)) { ap = ip; ax = a; test = nodeTest(a == Axis.ATTR, true); checkTest(test, a == Axis.ATTR); break; } ip = i; } } if(ax == null) { ax = Axis.CHILD; test = nodeTest(false, true); if(test != null && test.type == NodeType.ATT) ax = Axis.ATTR; checkTest(test, ax == Axis.ATTR); } if(test == null) return null; final ExprList el = new ExprList(); while(wsConsume(BR1)) { checkPred(true); add(el, expr()); wsCheck(BR2); checkPred(false); } return AxisStep.get(info(), ax, test, el.finish()); } /** * Parses the "NodeTest" rule. * Parses the "NameTest" rule. * Parses the "KindTest" rule. * @param att attribute flag * @param all check all tests, or only names * @return query expression * @throws QueryException query exception */ private Test nodeTest(final boolean att, final boolean all) throws QueryException { final int i = ip; if(consume('*')) { // name test: * if(!consume(':')) return new NameTest(att); // name test: *:name return new NameTest(new QNm(ncName(QNAMEINV)), NameTest.Mode.NAME, att); } if(ctx.sc.xquery3 && consume(EQNAME)) { // name test: {...}* final byte[] uri = bracedURILiteral(); if(consume('*')) { final QNm nm = new QNm(COLON, uri); return new NameTest(nm, NameTest.Mode.NS, att); } } final QNm name = eQName(null, SKIPCHECK); if(name != null) { final int i2 = ip; if(all && wsConsumeWs(PAR1)) { final NodeType type = NodeType.find(name); if(type != null) return kindTest(type); } else { ip = i2; // name test: prefix:name, name if(name.hasPrefix() || !consume(':')) { skipWS(); names.add(new QNmCheck(name, !att)); return new NameTest(name, NameTest.Mode.STD, att); } // name test: prefix:* if(consume('*')) { final QNm nm = new QNm(concat(name.string(), COLON)); names.add(new QNmCheck(nm, !att)); return new NameTest(nm, NameTest.Mode.NS, att); } } } ip = i; return null; } /** * Parses the "FilterExpr" rule. * Parses the "Predicate" rule. * @return postfix expression * @throws QueryException query exception */ private Expr postfix() throws QueryException { Expr e = primary(), old; do { old = e; if(wsConsume(BR1)) { if(e == null) error(PREDMISSING); final ExprList el = new ExprList(); do { add(el, expr()); wsCheck(BR2); } while(wsConsume(BR1)); e = new Filter(info(), e, el.finish()); } else if(e != null) { final Expr[] args = argumentList(e); if(args == null) break; final Var[] part = new Var[args.length]; final boolean pt = partial(args, part); e = new DynamicFunc(info(), e, args); if(pt) e = new PartFunc(info(), e, part); } } while(e != old); return e; } /** * Fills gaps from place-holders with variable references. * @param args argument array * @param vars variables array * @return variables bound */ private boolean partial(final Expr[] args, final Var[] vars) { final InputInfo ii = info(); boolean found = false; for(int i = 0; i < args.length; i++) { if(args[i] == null) { vars[i] = ctx.uniqueVar(ii, null); args[i] = new VarRef(ii, vars[i]); found = true; } } return found; } /** * Parses the "PrimaryExpr" rule. * Parses the "VarRef" rule. * Parses the "ContextItem" rule. * Parses the "Literal" rule. * @return query expression * @throws QueryException query exception */ private Expr primary() throws QueryException { skipWS(); final char c = curr(); // variables if(c == '$') return new VarRef(info(), checkVar(varName(), VARUNDEF)); // parentheses if(c == '(' && next() != '#') return parenthesized(); // direct constructor if(c == '<') return constructor(); // function item if(ctx.sc.xquery3) { final Expr e = functionItem(); if(e != null) return e; } // function call Expr e = functionCall(); if(e != null) return e; // computed constructors e = compConstructor(); if(e != null) return e; // ordered expression if(wsConsumeWs(ORDERED, BRACE1, INCOMPLETE) || wsConsumeWs(UNORDERED, BRACE1, INCOMPLETE)) return enclosed(NOENCLEXPR); // map literal if(wsConsumeWs(MAPSTR, BRACE1, INCOMPLETE)) return mapLiteral(); // context item if(c == '.' && !digit(next())) { if(next() == '.') return null; consume('.'); return new Context(info()); } // literals return literal(); } /** * Parses a literal map. * @return map literal * @throws QueryException query exception */ private Expr mapLiteral() throws QueryException { wsCheck(BRACE1); final ExprList el = new ExprList(); if(!wsConsume(BRACE2)) { do { add(el, check(single(), INVMAPKEY)); wsCheck(ASSIGN); add(el, check(single(), INVMAPVAL)); } while(wsConsume(COMMA)); wsCheck(BRACE2); } return new LitMap(info(), el.finish()); } /** * Parses the "FunctionItemExpr" rule. * Parses the "NamedFunctionRef" rule. * Parses the "LiteralFunctionItem" rule. * Parses the "InlineFunction" rule. * @return query expression, or {@code null} * @throws QueryException query exception */ private Expr functionItem() throws QueryException { skipWS(); final int pos = ip; // parse annotations final Ann ann = ctx.sc.xquery3 && curr('%') ? annotations() : null; // inline function if(wsConsume(FUNCTION) && wsConsume(PAR1)) { final int s = ctx.vars.size(); final Var[] args = paramList(); wsCheck(PAR2); final SeqType type = optAsType(); final Expr body = enclosed(NOFUNBODY); ctx.vars.size(s); return new InlineFunc(info(), type, args, body, ann); } // annotations not allowed here if(ann != null) error(NOANN); // named function reference ip = pos; final QNm name = eQName(null, ctx.sc.nsFunc); if(name != null && consume(' final long card = ((Int) numericLiteral(true)).itr(); if(card < 0 || card > Integer.MAX_VALUE) error(FUNCUNKNOWN, name); return Functions.get(name, card, false, ctx, info()); } ip = pos; return null; } /** * Parses the "Literal" rule. * @return query expression, or {@code null} * @throws QueryException query exception */ private Item literal() throws QueryException { final char c = curr(); // literals if(digit(c) || c == '.') return numericLiteral(false); // strings if(!quote(c)) return null; final int i = ip; final byte[] s = stringLiteral(); final int p2 = ip; if(consume(':')) { // check for EQName if(!consume('=')) { ip = i; return null; } ip = p2; } return Str.get(s); } /** * Parses the "NumericLiteral" rule. * Parses the "DecimalLiteral" rule. * Parses the "IntegerLiteral" rule. * @param itr integer flag * @return query expression * @throws QueryException query exception */ private Item numericLiteral(final boolean itr) throws QueryException { tok.reset(); while(digit(curr())) tok.add(consume()); final boolean dec = consume('.'); if(dec) { // decimal literal if(itr) error(NUMBERITR); tok.add('.'); while(digit(curr())) tok.add(consume()); } if(XMLToken.isNCStartChar(curr())) return checkDbl(); if(dec) return new Dec(tok.finish()); final long l = toLong(tok.finish()); if(l == Long.MIN_VALUE) error(RANGE, tok); return Int.get(l); } /** * Parses the "DoubleLiteral" rule. Checks if a number is followed by a * whitespace. * @return expression * @throws QueryException query exception */ private Dbl checkDbl() throws QueryException { if(!consume('e') && !consume('E')) error(NUMBERWS); tok.add('e'); if(curr('+') || curr('-')) tok.add(consume()); final int s = tok.size(); while(digit(curr())) tok.add(consume()); if(s == tok.size()) error(NUMBERINC, tok); if(XMLToken.isNCStartChar(curr())) error(NUMBERWS); return Dbl.get(tok.finish(), info()); } /** * Parses the "StringLiteral" rule. * @return query expression * @throws QueryException query exception */ private byte[] stringLiteral() throws QueryException { skipWS(); final char del = curr(); if(!quote(del)) error(NOQUOTE, found()); consume(); tok.reset(); while(true) { while(!consume(del)) { if(!more()) error(NOQUOTE, found()); entity(tok); } if(!consume(del)) break; tok.add(del); } return tok.finish(); } /** * Parses the "BracedURILiteral" rule without the "Q{" prefix. * @return query expression * @throws QueryException query exception */ private byte[] bracedURILiteral() throws QueryException { tok.reset(); while(!consume('}')) { if(!more()) error(WRONGCHAR, BRACE2, found()); entity(tok); } return tok.finish(); } /** * Parses the "VarName" rule. * @return query expression * @throws QueryException query exception */ private QNm varName() throws QueryException { wsCheck(DOLLAR); skipWS(); return eQName(NOVARNAME, null); } /** * Parses the "ParenthesizedExpr" rule. * @return query expression * @throws QueryException query exception */ private Expr parenthesized() throws QueryException { wsCheck(PAR1); final Expr e = expr(); wsCheck(PAR2); return e == null ? Empty.SEQ : e; } /** * Parses the "FunctionCall" rule. * @return query expression * @throws QueryException query exception */ private Expr functionCall() throws QueryException { final int i = ip; final QNm name = eQName(null, ctx.sc.nsFunc); if(name != null && !keyword(name)) { final Expr[] args = argumentList(name.string()); if(args != null) { alter = FUNCUNKNOWN; alterFunc = name; ap = ip; final Var[] vars = new Var[args.length]; final boolean part = partial(args, vars); final TypedFunc f = Functions.get(name, args, false, ctx, info()); if(f != null) { alter = null; return part ? new PartFunc(info(), f, vars) : f.fun; } } } ip = i; return null; } /** * Parses the "ArgumentList" rule. * @param name name of the function (item) * @return array of arguments, place-holders '?' are represented as * {@code null} entries * @throws QueryException query exception */ private Expr[] argumentList(final Object name) throws QueryException { if(!wsConsume(PAR1)) return null; Expr[] args = { }; if(!wsConsume(PAR2)) { do { Expr arg = null; if(!wsConsume(PLHOLDER) && (arg = single()) == null) error(FUNCMISS, name); // speeding up array creation final int a = args.length; final Expr[] tmp = new Expr[a + 1]; System.arraycopy(args, 0, tmp, 0, a); tmp[a] = arg; args = tmp; } while(wsConsume(COMMA)); if(!wsConsume(PAR2)) error(FUNCMISS, name); } return args; } /** * Parses the "Constructor" rule. * Parses the "DirectConstructor" rule. * @return query expression * @throws QueryException query exception */ private Expr constructor() throws QueryException { check('<'); return consume('!') ? dirComment() : consume('?') ? dirPI() : dirElement(); } /** * Parses the "DirElemConstructor" rule. * Parses the "DirAttributeList" rules. * @return query expression * @throws QueryException query exception */ private Expr dirElement() throws QueryException { // cache namespace information final int s = ctx.sc.ns.size(); final byte[] nse = ctx.sc.nsElem; final int npos = names.size(); final QNm tag = new QNm(qName(TAGNAME)); names.add(new QNmCheck(tag)); consumeWS(); final Atts ns = new Atts(); final ExprList cont = new ExprList(); // parse attributes... boolean xmlDecl = false; // xml prefix explicitly declared? while(true) { final byte[] atn = qName(null); if(atn.length == 0) break; final ExprList attv = new ExprList(); consumeWS(); check('='); consumeWS(); final char delim = consume(); if(!quote(delim)) error(NOQUOTE, found()); final TokenBuilder tb = new TokenBuilder(); boolean simple = true; do { while(!consume(delim)) { final char ch = curr(); if(ch == '{') { if(next() == '{') { tb.add(consume()); consume(); } else { final byte[] text = tb.finish(); if(text.length != 0) { add(attv, Str.get(text)); } else { add(attv, enclosed(NOENCLEXPR)); simple = false; } tb.reset(); } } else if(ch == '}') { consume(); check('}'); tb.add('}'); } else if(ch == '<' || ch == 0) { error(NOQUOTE, found()); } else if(ch == '\n' || ch == '\t') { tb.add(' '); consume(); } else if(ch == '\r') { if(next() != '\n') tb.add(' '); consume(); } else { entity(tb); } } if(!consume(delim)) break; tb.add(delim); } while(true); if(!tb.isEmpty()) add(attv, Str.get(tb.finish())); // parse namespace declarations final boolean pr = startsWith(atn, XMLNSC); if(pr || eq(atn, XMLNS)) { if(!simple) error(NSCONS); final byte[] pref = pr ? local(atn) : EMPTY; final byte[] uri = attv.isEmpty() ? EMPTY : ((Str) attv.get(0)).string(); if(eq(pref, XML) && eq(uri, XMLURI)) { if(xmlDecl) error(DUPLNSDEF, XML); xmlDecl = true; } else { if(pr) { if(uri.length == 0) error(NSEMPTYURI); if(eq(pref, XML, XMLNS)) error(BINDXML, pref); if(eq(uri, XMLURI)) error(BINDXMLURI, uri, XML); if(eq(uri, XMLNSURI)) error(BINDXMLURI, uri, XMLNS); ctx.sc.ns.add(pref, uri); } else { ctx.sc.nsElem = uri; } if(ns.get(pref) != -1) error(DUPLNSDEF, pref); ns.add(pref, uri); } } else { final QNm attn = new QNm(atn); names.add(new QNmCheck(attn, false)); add(cont, new CAttr(info(), false, attn, attv.finish())); } if(!consumeWS()) break; } if(consume('/')) { check('>'); } else { check('>'); while(curr() != '<' || next() != '/') { final Expr e = dirElemContent(tag.string()); if(e == null) continue; add(cont, e); } ip += 2; final byte[] close = qName(TAGNAME); consumeWS(); check('>'); if(!eq(tag.string(), close)) error(TAGWRONG, tag.string(), close); } assignURI(npos); ctx.sc.ns.size(s); ctx.sc.nsElem = nse; return new CElem(info(), tag, ns, cont.finish()); } /** * Parses the "DirElemContent" rule. * @param tag opening tag * @return query expression * @throws QueryException query exception */ private Expr dirElemContent(final byte[] tag) throws QueryException { final TokenBuilder tb = new TokenBuilder(); boolean strip = true; do { final char c = curr(); if(c == '<') { if(wsConsume(CDATA)) { tb.add(cDataSection()); strip = false; } else { final Str txt = text(tb, strip); return txt != null ? txt : next() == '/' ? null : constructor(); } } else if(c == '{') { if(next() == '{') { tb.add(consume()); consume(); } else { final Str txt = text(tb, strip); return txt != null ? txt : enclosed(NOENCLEXPR); } } else if(c == '}') { consume(); check('}'); tb.add('}'); } else if(c != 0) { strip &= !entity(tb); } else { error(NOCLOSING, tag); } } while(true); } /** * Returns a string item. * @param tb token builder * @param strip strip flag * @return text or {@code null} */ private Str text(final TokenBuilder tb, final boolean strip) { final byte[] t = tb.finish(); return t.length == 0 || strip && !ctx.sc.spaces && ws(t) ? null : Str.get(t); } /** * Parses the "DirCommentConstructor" rule. * @return query expression * @throws QueryException query exception */ private Expr dirComment() throws QueryException { check('-'); check('-'); final TokenBuilder tb = new TokenBuilder(); do { while(not('-')) tb.add(consume()); consume(); if(consume('-')) { check('>'); return new CComm(info(), Str.get(tb.finish())); } tb.add('-'); } while(true); } /** * Parses the "DirPIConstructor" rule. * Parses the "DirPIContents" rule. * @return query expression * @throws QueryException query exception */ private Expr dirPI() throws QueryException { final byte[] str = ncName(INVALPI); if(eq(lc(str), XML)) error(PIXML, str); final boolean space = skipWS(); final TokenBuilder tb = new TokenBuilder(); do { while(not('?')) { if(!space) error(PIWRONG); tb.add(consume()); } consume(); if(consume('>')) { return new CPI(info(), Str.get(str), Str.get(tb.finish())); } tb.add('?'); } while(true); } /** * Parses the "CDataSection" rule. * @return CData * @throws QueryException query exception */ private byte[] cDataSection() throws QueryException { final TokenBuilder tb = new TokenBuilder(); while(true) { while(not(']')) { char ch = consume(); if(ch == '\r') { ch = '\n'; if(curr(ch)) consume(); } tb.add(ch); } consume(); if(curr(']') && next() == '>') { ip += 2; return tb.finish(); } tb.add(']'); } } /** * Parses the "ComputedConstructor" rule. * @return query expression * @throws QueryException query exception */ private Expr compConstructor() throws QueryException { final int i = ip; if(wsConsumeWs(DOCUMENT)) return consume(compDoc(), i); if(wsConsumeWs(ELEMENT)) return consume(compElement(), i); if(wsConsumeWs(ATTRIBUTE)) return consume(compAttribute(), i); if(wsConsumeWs(NSPACE)) return consume(compNamespace(), i); if(wsConsumeWs(TEXT)) return consume(compText(), i); if(wsConsumeWs(COMMENT)) return consume(compComment(), i); if(wsConsumeWs(PI)) return consume(compPI(), i); return null; } /** * Consumes the specified expression or resets the query position. * @param expr expression * @param p query position * @return expression or {@code null} */ private Expr consume(final Expr expr, final int p) { if(expr == null) ip = p; return expr; } /** * Parses the "CompDocConstructor" rule. * @return query expression * @throws QueryException query exception */ private Expr compDoc() throws QueryException { if(!wsConsume(BRACE1)) return null; final Expr e = check(expr(), NODOCCONS); wsCheck(BRACE2); return new CDoc(info(), e); } /** * Parses the "CompElemConstructor" rule. * Parses the "ContextExpr" rule. * @return query expression * @throws QueryException query exception */ private Expr compElement() throws QueryException { skipWS(); Expr name; final QNm qn = eQName(null, SKIPCHECK); if(qn != null) { name = qn; names.add(new QNmCheck(qn)); } else { if(!wsConsume(BRACE1)) return null; name = check(expr(), NOTAG); wsCheck(BRACE2); } if(!wsConsume(BRACE1)) return null; final Expr e = expr(); wsCheck(BRACE2); return new CElem(info(), name, null, e == null ? new Expr[0] : new Expr[] { e }); } /** * Parses the "CompAttrConstructor" rule. * @return query expression * @throws QueryException query exception */ private Expr compAttribute() throws QueryException { skipWS(); Expr name; final QNm qn = eQName(null, SKIPCHECK); if(qn != null) { name = qn; names.add(new QNmCheck(qn, false)); } else { if(!wsConsume(BRACE1)) return null; name = expr(); wsCheck(BRACE2); } if(!wsConsume(BRACE1)) return null; final Expr e = expr(); wsCheck(BRACE2); return new CAttr(info(), true, name, e == null ? Empty.SEQ : e); } /** * Parses the "CompNamespaceConstructor" rule. * @return query expression * @throws QueryException query exception */ private Expr compNamespace() throws QueryException { if(!ctx.sc.xquery3) return null; skipWS(); Expr name; final byte[] str = ncName(null); if(str.length != 0) { name = Str.get(str); } else { if(!wsConsume(BRACE1)) return null; name = check(expr(), NSWRONG); wsCheck(BRACE2); } if(!wsConsume(BRACE1)) return null; final Expr e = expr(); wsCheck(BRACE2); return new CNSpace(info(), name, e == null ? Empty.SEQ : e); } /** * Parses the "CompTextConstructor" rule. * @return query expression * @throws QueryException query exception */ private Expr compText() throws QueryException { if(!wsConsume(BRACE1)) return null; final Expr e = check(expr(), NOTXTCONS); wsCheck(BRACE2); return new CTxt(info(), e); } /** * Parses the "CompCommentConstructor" rule. * @return query expression * @throws QueryException query exception */ private Expr compComment() throws QueryException { if(!wsConsume(BRACE1)) return null; final Expr e = check(expr(), NOCOMCONS); wsCheck(BRACE2); return new CComm(info(), e); } /** * Parses the "CompPIConstructor" rule. * @return query expression * @throws QueryException query exception */ private Expr compPI() throws QueryException { skipWS(); Expr name; final byte[] str = ncName(null); if(str.length != 0) { name = Str.get(str); } else { if(!wsConsume(BRACE1)) return null; name = check(expr(), PIWRONG); wsCheck(BRACE2); } if(!wsConsume(BRACE1)) return null; final Expr e = expr(); wsCheck(BRACE2); return new CPI(info(), name, e == null ? Empty.SEQ : e); } /** * Parses the "SimpleType" rule. * @return sequence type * @throws QueryException query exception */ private SeqType simpleType() throws QueryException { skipWS(); final QNm name = eQName(TYPEINVALID, ctx.sc.nsElem); final Type t = AtomType.find(name, false); if(t == null) error(TYPEUNKNOWN, name); if(t == AtomType.AAT || t == AtomType.NOT) error(CASTUNKNOWN, name); skipWS(); return SeqType.get(t, consume('?') ? Occ.ZERO_ONE : Occ.ONE); } /** * Parses the "SequenceType" rule. * Parses the "OccurrenceIndicator" rule. * Parses the "KindTest" rule. * @return sequence type * @throws QueryException query exception */ private SeqType sequenceType() throws QueryException { // empty sequence if(wsConsumeWs(EMPTY_SEQUENCE, PAR1, null)) { wsCheck(PAR1); wsCheck(PAR2); return SeqType.get(AtomType.ITEM, Occ.ZERO, null); } // parse item type and occurrence indicator final TypeWrapper tw = itemType(); skipWS(); final Occ occ = consume('?') ? Occ.ZERO_ONE : consume('+') ? Occ.ONE_MORE : consume('*') ? Occ.ZERO_MORE : Occ.ONE; skipWS(); return SeqType.get(tw.type, occ, tw.test); } /** * Parses the "ItemType" rule. * Parses the "ParenthesizedItemType" rule. * @return item type * @throws QueryException query exception */ private TypeWrapper itemType() throws QueryException { skipWS(); // parenthesized item type if(consume(PAR1)) { final TypeWrapper ret = itemType(); wsCheck(PAR2); return ret; } // parse optional annotation and type name final Ann ann = ctx.sc.xquery3 && curr('%') ? annotations() : null; final QNm name = eQName(TYPEINVALID, null); skipWS(); // check if name is followed by parentheses final boolean func = curr('('); // item type Type t = null; if(func) { consume(PAR1); // item type if(name.eq(AtomType.ITEM.name)) t = AtomType.ITEM; // node types if(t == null) t = NodeType.find(name); // function types if(t == null) { t = FuncType.find(name); // [LW] XQuery, function test: add annotation support if(t != null) return new TypeWrapper(functionTest(t)); } // no type found if(t == null) error(NOTYPE, name.string()); } else { // attach default element namespace if(!name.hasURI()) name.uri(ctx.sc.nsElem); // atomic types t = AtomType.find(name, false); // no type found if(t == null) error(TYPEUNKNOWN, name); } // annotations are not allowed for remaining types if(ann != null) error(NOANN); // atomic value, or closing parenthesis if(!func || wsConsume(PAR2)) return new TypeWrapper(t); // raise error if type different to node is not finalized by a parenthesis if(!(t instanceof NodeType)) wsCheck(PAR2); // return type with an optional kind test for node types return new TypeWrapper(t, kindTest((NodeType) t)); } /** * Parses the "FunctionTest" rule. * @param t function type * @return resulting type * @throws QueryException query exception */ private Type functionTest(final Type t) throws QueryException { // wildcard if(wsConsume(ASTERISK)) { wsCheck(PAR2); return t; } // map if(t.isMap()) { final Type key = itemType().type; if(!key.instanceOf(AtomType.AAT)) error(MAPTAAT, key); wsCheck(COMMA); final Type tp = MapType.get((AtomType) key, sequenceType()); wsCheck(PAR2); return tp; } // function type SeqType[] args = { }; if(!wsConsume(PAR2)) { // function has got arguments do { args = Array.add(args, sequenceType()); } while(wsConsume(COMMA)); wsCheck(PAR2); } wsCheck(AS); final SeqType st = sequenceType(); return FuncType.get(st, args); } /** * Parses the "ElementTest" rule without the type name and the opening bracket. * @param t type * @return arguments * @throws QueryException query exception */ private Test kindTest(final NodeType t) throws QueryException { Test tp = null; switch(t) { case DOC: tp = documentTest(); break; case ELM: tp = elementTest(); break; case ATT: tp = attributeTest(); break; case PI: tp = piTest(); break; case SCE: case SCA: tp = schemaTest(); break; default: break; } wsCheck(PAR2); return tp == null ? Test.get(t) : tp; } /** * Parses the "DocumentTest" rule without the leading keyword and its brackets. * @return arguments * @throws QueryException query exception */ private Test documentTest() throws QueryException { final boolean elem = consume(ELEMENT); if(!elem && !consume(SCHEMA_ELEMENT)) return null; wsCheck(PAR1); final Test t = elem ? elementTest() : schemaTest(); wsCheck(PAR2); return new DocTest(t != null ? t : Test.ELM); } /** * Parses the "ElementTest" rule without the leading keyword and its brackets. * @return arguments * @throws QueryException query exception */ private Test elementTest() throws QueryException { final QNm name = eQName(null, ctx.sc.nsElem); if(name == null && !consume(ASTERISK)) return null; Type type = null; if(wsConsumeWs(COMMA)) { // parse type name final QNm tn = eQName(QNAMEINV, ctx.sc.nsElem); type = AtomType.find(tn, true); if(type == null) error(TYPEUNDEF, tn); // parse optional question mark wsConsume(PLHOLDER); } return new ExtTest(NodeType.ELM, name, type, ctx.sc.strip); } /** * Parses the "ElementTest" rule without the leading keyword and its brackets. * @return arguments * @throws QueryException query exception */ private Test schemaTest() throws QueryException { final QNm name = eQName(QNAMEINV, ctx.sc.nsElem); throw error(SCHEMAINV, name); } /** * Parses the "AttributeTest" rule without the leading keyword and its brackets. * @return arguments * @throws QueryException query exception */ private Test attributeTest() throws QueryException { final QNm name = eQName(null, null); if(name == null && !consume(ASTERISK)) return null; Type type = null; if(wsConsumeWs(COMMA)) { // parse type name final QNm tn = eQName(QNAMEINV, ctx.sc.nsElem); type = AtomType.find(tn, true); if(type == null) error(TYPEUNDEF, tn); } return new ExtTest(NodeType.ATT, name, type, ctx.sc.strip); } /** * Parses the "PITest" rule without the leading keyword and its brackets. * @return arguments * @throws QueryException query exception */ private Test piTest() throws QueryException { final byte[] nm; tok.reset(); if(quote(curr())) { nm = trim(stringLiteral()); if(!XMLToken.isNCName(nm)) error(INVNCNAME, nm); } else if(ncName()) { nm = tok.finish(); } else { return null; } return new ExtTest(NodeType.PI, new QNm(nm)); } /** * Parses the "TryCatch" rules. * @return query expression * @throws QueryException query exception */ private Expr tryCatch() throws QueryException { if(!ctx.sc.xquery3 || !wsConsumeWs(TRY)) return null; final Expr tr = enclosed(NOENCLEXPR); wsCheck(CATCH); Catch[] ct = { }; do { QNm[] codes = { }; do { skipWS(); final Test test = nodeTest(false, false); if(test == null) error(NOCATCH); codes = Array.add(codes, test.name); } while(wsConsumeWs(PIPE)); final Catch c = new Catch(info(), codes, ctx); final int s = c.prepare(ctx); c.expr = enclosed(NOENCLEXPR); ctx.vars.size(s); ct = Array.add(ct, c); } while(wsConsumeWs(CATCH)); return new Try(info(), tr, ct); } /** * Parses the "FTSelection" rules. * @param prg pragma flag * @return query expression * @throws QueryException query exception */ private FTExpr ftSelection(final boolean prg) throws QueryException { FTExpr expr = ftOr(prg); FTExpr old; FTExpr first = null; boolean ordered = false; do { old = expr; if(wsConsumeWs(ORDERED)) { ordered = true; old = null; } else if(wsConsumeWs(WINDOW)) { expr = new FTWindow(info(), expr, additive(), ftUnit()); } else if(wsConsumeWs(DISTANCE)) { final Expr[] rng = ftRange(false); if(rng == null) error(FTRANGE); expr = new FTDistance(info(), expr, rng, ftUnit()); } else if(wsConsumeWs(AT)) { final boolean start = wsConsumeWs(START); final boolean end = !start && wsConsumeWs(END); if(!start && !end) error(INCOMPLETE); expr = new FTContent(info(), expr, start, end); } else if(wsConsumeWs(ENTIRE)) { wsCheck(CONTENT); expr = new FTContent(info(), expr, false, false); } else { final boolean same = wsConsumeWs(SAME); final boolean diff = !same && wsConsumeWs(DIFFERENT); if(same || diff) { FTUnit unit = null; if(wsConsumeWs(SENTENCE)) unit = FTUnit.SENTENCE; else if(wsConsumeWs(PARAGRAPH)) unit = FTUnit.PARAGRAPH; else error(INCOMPLETE); expr = new FTScope(info(), expr, unit, same); } } if(first == null && old != null && old != expr) first = expr; } while(old != expr); if(ordered) { if(first == null) return new FTOrder(info(), expr); first.expr[0] = new FTOrder(info(), first.expr[0]); } return expr; } /** * Parses the "FTOr" rule. * @param prg pragma flag * @return query expression * @throws QueryException query exception */ private FTExpr ftOr(final boolean prg) throws QueryException { final FTExpr e = ftAnd(prg); if(!wsConsumeWs(FTOR)) return e; FTExpr[] list = { e }; do list = Array.add(list, ftAnd(prg)); while(wsConsumeWs(FTOR)); return new FTOr(info(), list); } /** * Parses the "FTAnd" rule. * @param prg pragma flag * @return query expression * @throws QueryException query exception */ private FTExpr ftAnd(final boolean prg) throws QueryException { final FTExpr e = ftMildNot(prg); if(!wsConsumeWs(FTAND)) return e; FTExpr[] list = { e }; do list = Array.add(list, ftMildNot(prg)); while(wsConsumeWs(FTAND)); return new FTAnd(info(), list); } /** * Parses the "FTMildNot" rule. * @param prg pragma flag * @return query expression * @throws QueryException query exception */ private FTExpr ftMildNot(final boolean prg) throws QueryException { final FTExpr e = ftUnaryNot(prg); if(!wsConsumeWs(NOT)) return e; FTExpr[] list = { }; do { wsCheck(IN); list = Array.add(list, ftUnaryNot(prg)); } while(wsConsumeWs(NOT)); // convert "A not in B not in ..." to "A not in(B or ...)" return new FTMildNot(info(), e, list.length == 1 ? list[0] : new FTOr( info(), list)); } /** * Parses the "FTUnaryNot" rule. * @param prg pragma flag * @return query expression * @throws QueryException query exception */ private FTExpr ftUnaryNot(final boolean prg) throws QueryException { final boolean not = wsConsumeWs(FTNOT); final FTExpr e = ftPrimaryWithOptions(prg); return not ? new FTNot(info(), e) : e; } /** * Parses the "FTPrimaryWithOptions" rule. * @param prg pragma flag * @return query expression * @throws QueryException query exception */ private FTExpr ftPrimaryWithOptions(final boolean prg) throws QueryException { FTExpr expr = ftPrimary(prg); final FTOpt fto = new FTOpt(); boolean found = false; while(ftMatchOption(fto)) found = true; // check if specified language is not available if(fto.ln == null) fto.ln = Language.def(); if(!Tokenizer.supportFor(fto.ln)) error(FTNOTOK, fto.ln); if(fto.is(ST) && fto.sd == null && !Stemmer.supportFor(fto.ln)) error(FTNOSTEM, fto.ln); // consume weight option if(wsConsumeWs(WEIGHT)) expr = new FTWeight(info(), expr, enclosed(NOENCLEXPR)); // skip options if none were specified... return found ? new FTOptions(info(), expr, fto) : expr; } /** * Parses the "FTPrimary" rule. * @param prg pragma flag * @return query expression * @throws QueryException query exception */ private FTExpr ftPrimary(final boolean prg) throws QueryException { final Pragma[] pragmas = pragma(); if(pragmas != null) { wsCheck(BRACE1); final FTExpr e = ftSelection(true); wsCheck(BRACE2); return new FTExtensionSelection(info(), pragmas, e); } if(wsConsumeWs(PAR1)) { final FTExpr e = ftSelection(false); wsCheck(PAR2); return e; } skipWS(); final Expr e = curr('{') ? enclosed(NOENCLEXPR) : quote(curr()) ? Str.get(stringLiteral()) : null; if(e == null) error(prg ? NOPRAGMA : NOENCLEXPR); // FTAnyAllOption FTMode mode = FTMode.ANY; if(wsConsumeWs(ALL)) { mode = wsConsumeWs(WORDS) ? FTMode.ALL_WORDS : FTMode.ALL; } else if(wsConsumeWs(ANY)) { mode = wsConsumeWs(WORD) ? FTMode.ANY_WORD : FTMode.ANY; } else if(wsConsumeWs(PHRASE)) { mode = FTMode.PHRASE; } // FTTimes Expr[] occ = null; if(wsConsumeWs(OCCURS)) { occ = ftRange(false); if(occ == null) error(FTRANGE); wsCheck(TIMES); } return new FTWords(info(), e, mode, occ); } /** * Parses the "FTRange" rule. * @param i accept only integers ("FTLiteralRange") * @return query expression * @throws QueryException query exception */ private Expr[] ftRange(final boolean i) throws QueryException { final Expr[] occ = { Int.get(1), Int.get(Long.MAX_VALUE)}; if(wsConsumeWs(EXACTLY)) { occ[0] = ftAdditive(i); occ[1] = occ[0]; } else if(wsConsumeWs(AT)) { if(wsConsumeWs(LEAST)) { occ[0] = ftAdditive(i); } else { wsCheck(MOST); occ[0] = Int.get(0); occ[1] = ftAdditive(i); } } else if(wsConsumeWs(FROM)) { occ[0] = ftAdditive(i); wsCheck(TO); occ[1] = ftAdditive(i); } else { return null; } return occ; } /** * Returns an argument of the "FTRange" rule. * @param i accept only integers * @return query expression * @throws QueryException query exception */ private Expr ftAdditive(final boolean i) throws QueryException { if(!i) return additive(); skipWS(); tok.reset(); while(digit(curr())) tok.add(consume()); if(tok.isEmpty()) error(INTEXP); return Int.get(toLong(tok.finish())); } /** * Parses the "FTUnit" rule. * @return query expression * @throws QueryException query exception */ private FTUnit ftUnit() throws QueryException { if(wsConsumeWs(WORDS)) return FTUnit.WORD; if(wsConsumeWs(SENTENCES)) return FTUnit.SENTENCE; if(wsConsumeWs(PARAGRAPHS)) return FTUnit.PARAGRAPH; error(INCOMPLETE); return null; } /** * Parses the "FTMatchOption" rule. * @param opt options instance * @return false if no options were found * @throws QueryException query exception */ private boolean ftMatchOption(final FTOpt opt) throws QueryException { if(!wsConsumeWs(USING)) return false; if(wsConsumeWs(LOWERCASE)) { if(opt.isSet(LC) || opt.isSet(UC) || opt.isSet(CS)) error(FTDUP, CASE); opt.set(CS, true); opt.set(LC, true); } else if(wsConsumeWs(UPPERCASE)) { if(opt.isSet(LC) || opt.isSet(UC) || opt.isSet(CS)) error(FTDUP, CASE); opt.set(CS, true); opt.set(UC, true); } else if(wsConsumeWs(CASE)) { if(opt.isSet(LC) || opt.isSet(UC) || opt.isSet(CS)) error(FTDUP, CASE); opt.set(CS, wsConsumeWs(SENSITIVE)); if(!opt.is(CS)) wsCheck(INSENSITIVE); } else if(wsConsumeWs(DIACRITICS)) { if(opt.isSet(DC)) error(FTDUP, DIACRITICS); opt.set(DC, wsConsumeWs(SENSITIVE)); if(!opt.is(DC)) wsCheck(INSENSITIVE); } else if(wsConsumeWs(LANGUAGE)) { if(opt.ln != null) error(FTDUP, LANGUAGE); final byte[] lan = stringLiteral(); opt.ln = Language.get(string(lan)); if(opt.ln == null) error(FTNOTOK, lan); } else if(wsConsumeWs(OPTION)) { optionDecl(); } else { final boolean using = !wsConsumeWs(NO); if(wsConsumeWs(STEMMING)) { if(opt.isSet(ST)) error(FTDUP, STEMMING); opt.set(ST, using); } else if(wsConsumeWs(THESAURUS)) { if(opt.th != null) error(FTDUP, THESAURUS); opt.th = new ThesQuery(); if(using) { final boolean par = wsConsume(PAR1); if(!wsConsumeWs(DEFAULT)) ftThesaurusID(opt.th); while(par && wsConsume(COMMA)) ftThesaurusID(opt.th); if(par) wsCheck(PAR2); } } else if(wsConsumeWs(STOP)) { // add union/except wsCheck(WORDS); if(opt.sw != null) error(FTDUP, STOP + ' ' + WORDS); opt.sw = new StopWords(); if(wsConsumeWs(DEFAULT)) { if(!using) error(FTSTOP); } else { boolean union = false; boolean except = false; while(using) { if(wsConsume(PAR1)) { do { final byte[] sl = stringLiteral(); if(except) opt.sw.delete(sl); else if(!union || !opt.sw.contains(sl)) opt.sw.add(sl); } while(wsConsume(COMMA)); wsCheck(PAR2); } else if(wsConsumeWs(AT)) { final String fn = string(stringLiteral()); // optional: resolve URI reference final IO fl = ctx.stop != null ? ctx.stop.get(fn) : ctx.sc.io(fn); if(!opt.sw.read(fl, except)) error(NOSTOPFILE, fl); } else if(!union && !except) { error(FTSTOP); } union = wsConsumeWs(UNION); except = !union && wsConsumeWs(EXCEPT); if(!union && !except) break; } } } else if(wsConsumeWs(WILDCARDS)) { if(opt.isSet(WC)) error(FTDUP, WILDCARDS); if(opt.is(FZ)) error(BXFT_MATCH); opt.set(WC, using); } else if(wsConsumeWs(FUZZY)) { // extension to the official extension: "using fuzzy" if(opt.isSet(FZ)) error(FTDUP, FUZZY); if(opt.is(WC)) error(BXFT_MATCH); opt.set(FZ, using); } else { error(FTMATCH, consume()); return false; } } return true; } /** * Parses the "FTThesaurusID" rule. * @param thes link to thesaurus * @throws QueryException query exception */ private void ftThesaurusID(final ThesQuery thes) throws QueryException { wsCheck(AT); final String fn = string(stringLiteral()); // optional: resolve URI reference final IO fl = ctx.thes != null ? ctx.thes.get(fn) : ctx.sc.io(fn); final byte[] rel = wsConsumeWs(RELATIONSHIP) ? stringLiteral() : EMPTY; final Expr[] range = ftRange(true); long min = 0; long max = Long.MAX_VALUE; if(range != null) { wsCheck(LEVELS); // values will always be integer instances min = ((Int) range[0]).itr(); max = ((Int) range[1]).itr(); } thes.add(new Thesaurus(fl, rel, min, max, ctx.context)); } /** * Parses the "InsertExpr" rule. * @return query expression * @throws QueryException query exception */ private Expr insert() throws QueryException { final int i = ip; if(!wsConsumeWs(INSERT) || !wsConsumeWs(NODE) && !wsConsumeWs(NODES)) { ip = i; return null; } final Expr s = check(single(), INCOMPLETE); boolean first = false; boolean last = false; boolean before = false; boolean after = false; if(wsConsumeWs(AS)) { first = wsConsumeWs(FIRST); if(!first) { wsCheck(LAST); last = true; } wsCheck(INTO); } else if(!wsConsumeWs(INTO)) { after = wsConsumeWs(AFTER); before = !after && wsConsumeWs(BEFORE); if(!after && !before) error(INCOMPLETE); } final Expr trg = check(single(), INCOMPLETE); ctx.updating(true); return new Insert(info(), s, first, last, before, after, trg); } /** * Parses the "DeleteExpr" rule. * @return query expression * @throws QueryException query exception */ private Expr deletee() throws QueryException { final int i = ip; if(!wsConsumeWs(DELETE) || !wsConsumeWs(NODES) && !wsConsumeWs(NODE)) { ip = i; return null; } ctx.updating(true); return new Delete(info(), check(single(), INCOMPLETE)); } /** * Parses the "RenameExpr" rule. * @return query expression * @throws QueryException query exception */ private Expr rename() throws QueryException { final int i = ip; if(!wsConsumeWs(RENAME) || !wsConsumeWs(NODE)) { ip = i; return null; } final Expr trg = check(single(), INCOMPLETE); wsCheck(AS); final Expr n = check(single(), INCOMPLETE); ctx.updating(true); return new Rename(info(), trg, n); } /** * Parses the "ReplaceExpr" rule. * @return query expression * @throws QueryException query exception */ private Expr replace() throws QueryException { final int i = ip; if(!wsConsumeWs(REPLACE)) return null; final boolean v = wsConsumeWs(VALUEE); if(v) { wsCheck(OF); wsCheck(NODE); } else if(!wsConsumeWs(NODE)) { ip = i; return null; } final Expr t = check(single(), INCOMPLETE); wsCheck(WITH); final Expr r = check(single(), INCOMPLETE); ctx.updating(true); return new Replace(info(), t, r, v); } /** * Parses the "TransformExpr" rule. * @return query expression * @throws QueryException query exception */ private Expr transform() throws QueryException { if(!wsConsumeWs(COPY, DOLLAR, INCOMPLETE)) return null; final int s = ctx.vars.size(); final boolean u = ctx.updating; ctx.updating(false); Let[] fl = { }; do { final Var v = Var.create(ctx, info(), varName(), null); wsCheck(ASSIGN); final Expr e = check(single(), INCOMPLETE); ctx.vars.add(v); fl = Array.add(fl, new Let(info(), e, v)); } while(wsConsumeWs(COMMA)); wsCheck(MODIFY); final Expr m = check(single(), INCOMPLETE); wsCheck(RETURN); final Expr r = check(single(), INCOMPLETE); ctx.vars.size(s); ctx.updating = u; return new Transform(info(), fl, m, r); } /** * Parses the "NCName" rule. * @param err optional error message * @return string * @throws QueryException query exception */ private byte[] ncName(final Err err) throws QueryException { tok.reset(); if(ncName()) return tok.finish(); if(err != null) error(err, tok); return EMPTY; } /** * Parses the "EQName" rule. * @param err optional error message. Will be thrown if no EQName is found, * or ignored if set to {@code null} * @param def default namespace, or operation mode * ({@link #URICHECK}, {@link #SKIPCHECK}) * @return string * @throws QueryException query exception */ private QNm eQName(final Err err, final byte[] def) throws QueryException { final int i = ip; if(ctx.sc.xquery3 && consume(EQNAME)) { final byte[] uri = bracedURILiteral(); final byte[] name = ncName(null); if(name.length != 0) { if(def == URICHECK && uri.length == 0) error(NOURI, name); return new QNm(name, uri); } ip = i; } final byte[] nm = qName(err); if(nm.length == 0) return null; if(def == SKIPCHECK) return new QNm(nm); // create new EQName and set namespace final QNm name = new QNm(nm, ctx); if(!name.hasURI()) { if(def == URICHECK) error(NSMISS, name); if(name.hasPrefix()) error(NOURI, name); name.uri(def); } return name; } /** * Parses the "QName" rule. * @param err optional error message. Will be thrown if no QName is found, and * ignored if set to {@code null} * @return string * @throws QueryException query exception */ private byte[] qName(final Err err) throws QueryException { tok.reset(); if(!ncName()) { if(err != null) error(err, consume()); } else if(consume(':')) { if(!XMLToken.isNCStartChar(curr())) { --ip; } else { tok.add(':'); do { tok.add(consume()); } while(XMLToken.isNCChar(curr())); } } return tok.finish(); } /** * Helper method for parsing NCNames. * @return true for success */ private boolean ncName() { if(!XMLToken.isNCStartChar(curr())) return false; do { tok.add(consume()); } while(XMLToken.isNCChar(curr())); return true; } /** * Parses and converts entities. * @param tb token builder * @return true if an entity was found * @throws QueryException query exception */ private boolean entity(final TokenBuilder tb) throws QueryException { final int i = ip; final boolean ent = consume('&'); if(ent) { if(consume(' final int b = consume('x') ? 16 : 10; int n = 0; do { final char c = curr(); final boolean m = digit(c); final boolean h = b == 16 && (c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F'); if(!m && !h) entityError(i, INVENTITY); final long nn = n; n = n * b + (consume() & 15); if(n < nn) entityError(i, INVCHARREF); if(!m) n += 9; } while(!consume(';')); if(!XMLToken.valid(n)) entityError(i, INVCHARREF); tb.add(n); } else { if(consume("lt")) { tb.add('<'); } else if(consume("gt")) { tb.add('>'); } else if(consume("amp")) { tb.add('&'); } else if(consume("quot")) { tb.add('"'); } else if(consume("apos")) { tb.add('\''); } else { entityError(i, INVENTITY); } if(!consume(';')) entityError(i, INVENTITY); } } else { final char c = consume(); int ch = c; if(Character.isHighSurrogate(c) && curr() != 0 && Character.isLowSurrogate(curr())) { ch = Character.toCodePoint(c, consume()); } if(ch == '\r') { ch = '\n'; if(curr(ch)) consume(); } tb.add(ch); } return ent; } /** * Raises an entity error. * @param p start position * @param c error code * @throws QueryException query exception */ private void entityError(final int p, final Err c) throws QueryException { final String sub = input.substring(p, Math.min(p + 20, il)); final int sc = sub.indexOf(';'); final String ent = sc != -1 ? sub.substring(0, sc + 1) : sub; error(c, ent); } /** * Raises an error if the specified expression is empty. * @param <E> expression type * @param expr expression * @param err error message * @return expression * @throws QueryException query exception */ private <E extends Expr> E check(final E expr, final Err err) throws QueryException { if(expr == null) error(err); return expr; } /** * Raises an error if the specified character cannot be consumed. * @param ch character to be found * @throws QueryException query exception */ private void check(final int ch) throws QueryException { if(!consume(ch)) error(WRONGCHAR, (char) ch, found()); } /** * Skips whitespaces, raises an error if the specified string cannot be * consumed. * @param s string to be found * @throws QueryException query exception */ private void wsCheck(final String s) throws QueryException { if(!wsConsume(s)) error(WRONGCHAR, s, found()); } /** * Checks if a referenced variable is defined and throws the specified error * if not. * @param name variable name * @param err error to throw * @return referenced variable * @throws QueryException if the variable isn't defined */ private Var checkVar(final QNm name, final Err err) throws QueryException { Var v = ctx.vars.get(name); // dynamically assign variables from function modules if(v == null && !declVars) { declVars = true; v = ctx.vars.get(name); } if(v == null) error(err, '$' + string(name.string())); return v; } /** * Checks if the specified character is not found. An error is raised if the * input is exhausted. * @param ch character to be found * @return result of check * @throws QueryException query exception */ private boolean not(final char ch) throws QueryException { final char c = curr(); if(c == 0) error(WRONGCHAR, ch, found()); return c != ch; } /** * Consumes the specified token and surrounding whitespaces. * @param t token to consume * @return true if token was found * @throws QueryException query exception */ private boolean wsConsumeWs(final String t) throws QueryException { final int i = ip; if(!wsConsume(t)) return false; if(skipWS() || !XMLToken.isNCStartChar(t.charAt(0)) || !XMLToken.isNCChar(curr())) return true; ip = i; return false; } /** * Consumes the specified two strings or jumps back to the old query position. * If the strings are found, the cursor is placed after the first token. * @param s1 string to be consumed * @param s2 second string * @param expr alternative error message * @return result of check * @throws QueryException query exception */ private boolean wsConsumeWs(final String s1, final String s2, final Err expr) throws QueryException { final int i = ip; if(!wsConsumeWs(s1)) return false; alter = expr; ap = ip; final int i2 = ip; final boolean ok = wsConsume(s2); ip = ok ? i2 : i; return ok; } /** * Skips whitespaces, consumes the specified string and ignores trailing * characters. * @param str string to consume * @return true if string was found * @throws QueryException query exception */ private boolean wsConsume(final String str) throws QueryException { skipWS(); return consume(str); } /** * Consumes all whitespace characters from the remaining query. * @return true if whitespaces were found * @throws QueryException query exception */ private boolean skipWS() throws QueryException { final int i = ip; while(more()) { final int c = curr(); if(c == '(' && next() == ':') { comment(); } else { if(c <= 0 || c > ' ') return i != ip; ++ip; } } return i != ip; } /** * Consumes a comment. * @throws QueryException query exception */ private void comment() throws QueryException { ++ip; while(++ip < il) { if(curr('(') && next() == ':') comment(); if(curr(':') && next() == ')') { ip += 2; return; } } error(COMCLOSE); } /** * Consumes all following whitespace characters. * @return true if whitespaces were found */ private boolean consumeWS() { final int i = ip; while(more()) { final int c = curr(); if(c <= 0 || c > ' ') return i != ip; ++ip; } return true; } /** * Throws the alternative error message. * @throws QueryException query exception */ private void error() throws QueryException { ip = ap; if(alter != FUNCUNKNOWN) throw error(alter); ctx.funcs.funError(alterFunc, info()); throw error(alter, alterFunc.string()); } /** * Adds an expression to the specified array. * @param ar input array * @param e new expression * @throws QueryException query exception */ private void add(final ExprList ar, final Expr e) throws QueryException { if(e == null) error(INCOMPLETE); ar.add(e); } /** * Throws the specified error. * @param err error to be thrown * @param arg error arguments * @return never * @throws QueryException query exception */ public QueryException error(final Err err, final Object... arg) throws QueryException { throw err.thrw(info(), arg); } /** * Finalizes the QNames by assigning namespace URIs. * @param npos first entry to be checked * @throws QueryException query exception */ private void assignURI(final int npos) throws QueryException { for(int i = npos; i < names.size(); i++) { if(names.get(i).assign(npos == 0)) names.remove(i } } /** Type wrapper. */ private static class TypeWrapper { /** Type. */ final Type type; /** Kind test. */ final Test test; /** * Constructor. * @param t type */ TypeWrapper(final Type t) { this(t, null); } /** * Constructor. * @param t type * @param k kind test */ TypeWrapper(final Type t, final Test k) { type = t; test = k; } } /** Cache for checking QNames after their construction. */ private class QNmCheck { /** QName to be checked. */ final QNm name; /** Flag for assigning default element namespace. */ final boolean nsElem; /** * Constructor. * @param nm qname */ QNmCheck(final QNm nm) { this(nm, true); } /** * Constructor. * @param nm qname * @param nse default check */ QNmCheck(final QNm nm, final boolean nse) { name = nm; nsElem = nse; } /** * Assigns the namespace URI that is currently in scope. * @param check check if prefix URI was assigned * @return true if URI has a URI * @throws QueryException query exception */ boolean assign(final boolean check) throws QueryException { if(name.hasURI()) return true; if(name.hasPrefix()) { name.uri(ctx.sc.ns.uri(name.prefix())); if(check && !name.hasURI()) error(NOURI, name); } else if(nsElem) { name.uri(ctx.sc.nsElem); } return name.hasURI(); } } }
package com.elmakers.mine.bukkit.magic; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.MemoryConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.Plugin; import com.elmakers.mine.bukkit.api.spell.SpellKey; import com.elmakers.mine.bukkit.utility.CompatibilityUtils; import com.elmakers.mine.bukkit.utility.ConfigurationUtils; import com.google.common.collect.ImmutableSet; public class ConfigurationLoadTask implements Runnable { private final MagicController controller; private final File configFolder; private final Plugin plugin; private final CommandSender sender; private static final String[] CONFIG_FILES = {"messages", "materials", "attributes", "effects", "spells", "paths", "classes", "wands", "items", "crafting", "mobs", "automata"}; private static final ImmutableSet<String> DEFAULT_ON = ImmutableSet.of("messages", "materials"); private final Map<String, ConfigurationSection> loadedConfigurations = new HashMap<>(); private final Map<String, ConfigurationSection> spellConfigurations = new HashMap<>(); private final Map<String, ConfigurationSection> baseSpellConfigurations = new HashMap<>(); private static final Object loadLock = new Object(); private boolean allPvpRestricted = false; private boolean noPvpRestricted = false; private boolean saveDefaultConfigs = true; private boolean spellUpgradesEnabled = true; private String exampleDefaults = null; private String languageOverride = null; private Collection<String> addExamples = null; private ConfigurationSection mainConfiguration; private Set<String> resolvingKeys = new LinkedHashSet<>(); private boolean success; public ConfigurationLoadTask(MagicController controller, CommandSender sender) { this.controller = controller; this.sender = sender; plugin = controller.getPlugin(); configFolder = controller.getConfigFolder(); } private Logger getLogger() { return controller.getLogger(); } private void loadInitialProperties(ConfigurationSection properties) { spellUpgradesEnabled = properties.getBoolean("enable_spell_upgrades", true); allPvpRestricted = properties.getBoolean("pvp_restricted", false); noPvpRestricted = properties.getBoolean("allow_pvp_restricted", false); saveDefaultConfigs = properties.getBoolean("save_default_configs", true); exampleDefaults = properties.getString("example", exampleDefaults); addExamples = properties.getStringList("add_examples"); if (addExamples.isEmpty()) { addExamples = properties.getStringList("examples"); } languageOverride = properties.getString("language"); } private void info(String message) { controller.info(message); } private ConfigurationSection loadMainConfiguration() throws InvalidConfigurationException, IOException { ConfigurationSection configuration = loadMainConfiguration("config"); loadInitialProperties(configuration); boolean reloadConfig = false; if (addExamples != null && addExamples.size() > 0) { info("Adding examples: " + StringUtils.join(addExamples, ",")); reloadConfig = true; } if (exampleDefaults != null && exampleDefaults.length() > 0) { info("Overriding configuration with example: " + exampleDefaults); reloadConfig = true; } if (reloadConfig) { // Reload config, examples will be used this time. configuration = loadMainConfiguration("config"); } return configuration; } private ConfigurationSection loadMainConfiguration(String fileName) throws InvalidConfigurationException, IOException { ConfigurationSection overrides = loadOverrides(fileName); boolean usingExample = exampleDefaults != null && exampleDefaults.length() > 0; String examplesFileName = usingExample ? "examples/" + exampleDefaults + "/" + fileName + ".yml" : null; String defaultsFileName = "defaults/" + fileName + ".defaults.yml"; // Start with default configs YamlConfiguration config = CompatibilityUtils.loadConfiguration(plugin.getResource(defaultsFileName)); info(" Based on defaults " + defaultsFileName); // Load an example if one is specified if (usingExample) { InputStream input = plugin.getResource(examplesFileName); if (input != null) { ConfigurationSection exampleConfig = CompatibilityUtils.loadConfiguration(input); ConfigurationUtils.addConfigurations(config, exampleConfig); info(" Using " + examplesFileName); List<String> inherits = ConfigurationUtils.getStringList(exampleConfig, "inherit"); if (inherits != null) { for (String inheritFrom : inherits) { String inheritFileName = "examples/" + inheritFrom + "/" + fileName + ".yml"; InputStream inheritInput = plugin.getResource(inheritFileName); if (inheritInput != null) { ConfigurationSection inheritedConfig = CompatibilityUtils.loadConfiguration(inheritInput); ConfigurationUtils.addConfigurations(config, inheritedConfig, false); info(" Inheriting from " + inheritFrom); } } } } } // Add in examples if (addExamples != null && addExamples.size() > 0) { for (String example : addExamples) { examplesFileName = "examples/" + example + "/" + fileName + ".yml"; InputStream input = plugin.getResource(examplesFileName); if (input != null) { ConfigurationSection exampleConfig = CompatibilityUtils.loadConfiguration(input); ConfigurationUtils.addConfigurations(config, exampleConfig, false); info(" Added " + examplesFileName); } } } // Apply version-specific configs addVersionConfigs(config, fileName); // Apply overrides after loading defaults and examples ConfigurationUtils.addConfigurations(config, overrides); // Apply file overrides last File configSubFolder = new File(configFolder, fileName); loadConfigFolder(config, configSubFolder, false); // Save default configs for inspection if (saveDefaultConfigs) { try { // For the main config file we just save the defaults directly, it has a // lot of comments that are useful to see. plugin.saveResource(defaultsFileName, true); } catch (Exception ex) { getLogger().warning("Couldn't write defaults file: " + defaultsFileName); } } else { deleteDefaults(defaultsFileName); } return config; } private ConfigurationSection loadOverrides(String fileName) throws IOException, InvalidConfigurationException { String configFileName = fileName + ".yml"; File configFile = new File(configFolder, configFileName); if (!configFile.exists()) { info("Saving template " + configFileName + ", edit to customize configuration."); plugin.saveResource(configFileName, false); } info("Loading " + configFile.getName()); return CompatibilityUtils.loadConfiguration(configFile); } private ConfigurationSection loadConfigFile(String fileName, ConfigurationSection mainConfiguration) throws IOException, InvalidConfigurationException { boolean loadAllDefaults = mainConfiguration.getBoolean("load_default_configs", true); // materials and messages are hard to turn off if (DEFAULT_ON.contains(fileName)) { loadAllDefaults = true; } boolean loadDefaults = mainConfiguration.getBoolean("load_default_" + fileName, loadAllDefaults); boolean disableDefaults = mainConfiguration.getBoolean("disable_default_" + fileName, false); ConfigurationSection mainSection = mainConfiguration.getConfigurationSection(fileName); ConfigurationSection overrides = loadOverrides(fileName); boolean usingExample = exampleDefaults != null && exampleDefaults.length() > 0; String examplesFileName = usingExample ? "examples/" + exampleDefaults + "/" + fileName + ".yml" : null; String defaultsFileName = "defaults/" + fileName + ".defaults.yml"; YamlConfiguration config = new YamlConfiguration(); YamlConfiguration defaultConfig = CompatibilityUtils.loadConfiguration(plugin.getResource(defaultsFileName)); String header = defaultConfig.options().header(); // Load defaults if (loadDefaults) { info(" Based on defaults " + defaultsFileName); if (disableDefaults) { disableAll(defaultConfig); } ConfigurationUtils.addConfigurations(config, defaultConfig); } // Load example boolean disableInherited = false; if (usingExample && loadDefaults) { // Load inherited configs first List<String> inherits = ConfigurationUtils.getStringList(mainConfiguration, "inherit"); if (inherits != null) { List<String> skip = ConfigurationUtils.getStringList(mainConfiguration, "skip_inherited"); if (skip == null || !skip.contains(fileName)) { for (String inheritFrom : inherits) { String inheritFileName = "examples/" + inheritFrom + "/" + fileName + ".yml"; InputStream input = plugin.getResource(inheritFileName); if (input != null) { List<String> disable = ConfigurationUtils.getStringList(mainConfiguration, "disable_inherited"); ConfigurationSection inheritedConfig = CompatibilityUtils.loadConfiguration(input); if (disable != null && disable.contains(fileName)) { disableInherited = true; disableAll(inheritedConfig); } ConfigurationUtils.addConfigurations(config, inheritedConfig); info(" Inheriting from " + inheritFrom); } } } } InputStream input = plugin.getResource(examplesFileName); if (input != null) { ConfigurationSection exampleConfig = CompatibilityUtils.loadConfiguration(input); if (disableDefaults) { disableAll(exampleConfig); } else if (disableInherited) { enableAll(exampleConfig); } ConfigurationUtils.addConfigurations(config, exampleConfig); info(" Using " + examplesFileName); } } // Load anything relevant from the main config if (mainSection != null) { ConfigurationUtils.addConfigurations(overrides, mainSection); } // Re-enable anything we are overriding if (disableDefaults || disableInherited) { enableAll(overrides); } // Add in examples if (addExamples != null && addExamples.size() > 0) { for (String example : addExamples) { examplesFileName = "examples/" + example + "/" + fileName + ".yml"; InputStream input = plugin.getResource(examplesFileName); if (input != null) { ConfigurationSection exampleConfig = CompatibilityUtils.loadConfiguration(input); if (disableDefaults || disableInherited) { enableAll(exampleConfig); } ConfigurationUtils.addConfigurations(config, exampleConfig, false); info(" Added " + examplesFileName); } } } // Apply version-specific configs addVersionConfigs(config, fileName); // Apply language overrides, but only to the messages config if (fileName.equals("messages") && languageOverride != null) { String languageFileName = "examples/localizations/messages." + languageOverride + ".yml"; InputStream input = plugin.getResource(languageFileName); if (input != null) { ConfigurationSection languageConfig = CompatibilityUtils.loadConfiguration(input); ConfigurationUtils.addConfigurations(config, languageConfig); info(" Using " + languageFileName); } } // Apply overrides after loading defaults and examples ConfigurationUtils.addConfigurations(config, overrides); // Apply file overrides last File configSubFolder = new File(configFolder, fileName); loadConfigFolder(config, configSubFolder, disableDefaults || disableInherited); // Save defaults File savedDefaults = new File(configFolder, defaultsFileName); if (saveDefaultConfigs) { try { config.options().header(header); config.save(savedDefaults); } catch (Exception ex) { getLogger().warning("Couldn't write defaults file: " + defaultsFileName); } } else { deleteDefaults(defaultsFileName); } return config; } private void addVersionConfigs(ConfigurationSection config, String fileName) throws InvalidConfigurationException, IOException { int[] serverVersion = CompatibilityUtils.getServerVersion(); int majorVersion = serverVersion[0]; int minorVersion = serverVersion[1]; String versionExample = majorVersion + "." + minorVersion; String versionFileName = "examples/" + versionExample + "/" + fileName + ".yml"; InputStream versionInput = plugin.getResource(versionFileName); if (versionInput != null) { ConfigurationSection versionConfig = CompatibilityUtils.loadConfiguration(versionInput); // Version patches will never add to configs, the top-level nodes they are modifying must exist. // This allows them to tweak things from example configs but get safely ignored if not loading // those examples. ConfigurationUtils.addConfigurations(config, versionConfig, true, true); getLogger().info(" Using compatibility configs: " + versionFileName); } } private void deleteDefaults(String defaultsFileName) { File savedDefaults = new File(configFolder, defaultsFileName); if (savedDefaults.exists()) { try { savedDefaults.delete(); getLogger().info("Deleting defaults file: " + defaultsFileName + ", save_default_configs is false"); } catch (Exception ex) { getLogger().warning("Couldn't delete defaults file: " + defaultsFileName + ", contents may be outdated"); } } } private void enableAll(ConfigurationSection rootSection, boolean enabled) { Set<String> keys = rootSection.getKeys(false); for (String key : keys) { ConfigurationSection section = rootSection.getConfigurationSection(key); if (!section.isSet("enabled")) { section.set("enabled", enabled); } } } private void enableAll(ConfigurationSection rootSection) { enableAll(rootSection, true); } private void disableAll(ConfigurationSection rootSection) { enableAll(rootSection, false); } private ConfigurationSection loadConfigFolder(ConfigurationSection config, File configSubFolder, boolean setEnabled) throws IOException, InvalidConfigurationException { if (configSubFolder.exists()) { List<File> priorityFiles = new ArrayList<>(); File[] files = configSubFolder.listFiles(); for (File file : files) { if (file.getName().startsWith(".")) continue; if (file.isDirectory()) { config = loadConfigFolder(config, file, setEnabled); } else { if (file.getName().startsWith("_")) { priorityFiles.add(file); continue; } info(" Loading " + file.getName()); ConfigurationSection fileOverrides = CompatibilityUtils.loadConfiguration(file); if (setEnabled) { enableAll(fileOverrides); } config = ConfigurationUtils.addConfigurations(config, fileOverrides); } } for (File file : priorityFiles) { info(" Loading " + file.getName()); ConfigurationSection fileOverrides = CompatibilityUtils.loadConfiguration(file); if (setEnabled) { enableAll(fileOverrides); } config = ConfigurationUtils.addConfigurations(config, fileOverrides); } } else { configSubFolder.mkdir(); } return config; } private ConfigurationSection mapSpells(ConfigurationSection spellConfiguration) throws InvalidConfigurationException, IOException { ConfigurationSection spellConfigs = new MemoryConfiguration(); if (spellConfiguration == null) return spellConfigs; // Reset cached spell configs spellConfigurations.clear(); baseSpellConfigurations.clear(); Set<String> spellKeys = spellConfiguration.getKeys(false); for (String key : spellKeys) { if (key.equals("default") || key.equals("override")) continue; ConfigurationSection spellNode = getSpellConfig(key, spellConfiguration); if (spellNode == null || !spellNode.getBoolean("enabled", true)) { continue; } // Kind of a hacky way to do this, and only works with BaseSpell spells. if (noPvpRestricted) { spellNode.set("pvp_restricted", false); } else if (allPvpRestricted) { spellNode.set("pvp_restricted", true); } spellConfigs.set(key, spellNode); } return spellConfigs; } @Nullable private ConfigurationSection getSpellConfig(String key, ConfigurationSection config) { return getSpellConfig(key, config, true); } @Nullable private ConfigurationSection getSpellConfig(String key, ConfigurationSection config, boolean addInherited) { resolvingKeys.clear(); return getSpellConfig(key, config, addInherited, resolvingKeys); } @Nullable private ConfigurationSection getSpellConfig(String key, ConfigurationSection config, boolean addInherited, Set<String> resolving) { // Catch circular dependencies if (resolvingKeys.contains(key)) { getLogger().log(Level.WARNING, "Circular dependency detected in spell configs: " + StringUtils.join(resolvingKeys, " -> ") + " -> " + key); return config; } resolvingKeys.add(key); if (addInherited) { ConfigurationSection built = spellConfigurations.get(key); if (built != null) { return built; } } else { ConfigurationSection built = baseSpellConfigurations.get(key); if (built != null) { return built; } } ConfigurationSection spellNode = config.getConfigurationSection(key); if (spellNode == null) { getLogger().warning("Spell " + key + " not known"); return null; } spellNode = ConfigurationUtils.cloneConfiguration(spellNode); SpellKey spellKey = new SpellKey(key); String inheritFrom = spellNode.getString("inherit"); if (inheritFrom != null && inheritFrom.equalsIgnoreCase("false")) { inheritFrom = null; } String upgradeInheritsFrom = null; if (spellKey.isVariant()) { if (!spellUpgradesEnabled) { return null; } int level = spellKey.getLevel(); upgradeInheritsFrom = spellKey.getBaseKey(); if (level != 2) { upgradeInheritsFrom += "|" + (level - 1); } } boolean processInherited = addInherited && inheritFrom != null; if (processInherited || upgradeInheritsFrom != null) { if (processInherited && key.equals(inheritFrom)) { getLogger().warning("Spell " + key + " inherits from itself"); } else if (processInherited) { ConfigurationSection inheritConfig = getSpellConfig(inheritFrom, config, true, resolving); if (inheritConfig != null) { spellNode = ConfigurationUtils.addConfigurations(spellNode, inheritConfig, false); } else { getLogger().warning("Spell " + key + " inherits from unknown ancestor " + inheritFrom); } } if (upgradeInheritsFrom != null) { if (config.contains(upgradeInheritsFrom)) { ConfigurationSection baseInheritConfig = getSpellConfig(upgradeInheritsFrom, config, inheritFrom == null, resolving); spellNode = ConfigurationUtils.addConfigurations(spellNode, baseInheritConfig, inheritFrom != null); } else { getLogger().warning("Spell upgrade " + key + " inherits from unknown level " + upgradeInheritsFrom); } } } else { ConfigurationSection defaults = config.getConfigurationSection("default"); if (defaults != null) { spellNode = ConfigurationUtils.addConfigurations(spellNode, defaults, false); } } if (addInherited) { spellConfigurations.put(key, spellNode); } else { baseSpellConfigurations.put(key, spellNode); } // Apply spell override last ConfigurationSection override = config.getConfigurationSection("override"); if (override != null) { spellNode = ConfigurationUtils.addConfigurations(spellNode, override, true); } return spellNode; } private void run(boolean synchronous) { success = true; Logger logger = controller.getLogger(); // Load main configuration try { mainConfiguration = loadMainConfiguration(); } catch (Exception ex) { logger.log(Level.WARNING, "Error loading config.yml", ex); success = false; } // Load other configurations loadedConfigurations.clear(); for (String configurationFile : CONFIG_FILES) { try { ConfigurationSection configuration = loadConfigFile(configurationFile, mainConfiguration); // Spells require special processing if (configurationFile.equals("spells")) { configuration = mapSpells(configuration); } loadedConfigurations.put(configurationFile, configuration); } catch (Exception ex) { logger.log(Level.WARNING, "Error loading " + configurationFile, ex); loadedConfigurations.put(configurationFile, new MemoryConfiguration()); success = false; } } // Finalize configuration load if (synchronous) { controller.finalizeLoad(this, sender); } else { Plugin plugin = controller.getPlugin(); final ConfigurationLoadTask result = this; plugin.getServer().getScheduler().runTask(plugin, new Runnable() { @Override public void run() { controller.finalizeLoad(result, sender); } }); } } @Override public void run() { synchronized (loadLock) { run(false); } } public void runNow() { synchronized (loadLock) { run(true); } } public ConfigurationSection getMainConfiguration() { return mainConfiguration; } public ConfigurationSection getMessages() { return loadedConfigurations.get("messages"); } public ConfigurationSection getMaterials() { return loadedConfigurations.get("materials"); } public ConfigurationSection getWands() { return loadedConfigurations.get("wands"); } public ConfigurationSection getPaths() { return loadedConfigurations.get("paths"); } public ConfigurationSection getCrafting() { return loadedConfigurations.get("crafting"); } public ConfigurationSection getMobs() { return loadedConfigurations.get("mobs"); } public ConfigurationSection getItems() { return loadedConfigurations.get("items"); } public ConfigurationSection getClasses() { return loadedConfigurations.get("classes"); } public ConfigurationSection getAttributes() { return loadedConfigurations.get("attributes"); } public ConfigurationSection getAutomata() { return loadedConfigurations.get("automata"); } public ConfigurationSection getEffects() { return loadedConfigurations.get("effects"); } public ConfigurationSection getSpells() { return loadedConfigurations.get("spells"); } public boolean isSuccessful() { return success; } public String getExampleDefaults() { return exampleDefaults; } public Collection<String> getAddExamples() { return addExamples; } }
package io.grpc.stub; import com.google.common.base.Preconditions; import com.google.common.base.Throwables; import com.google.common.util.concurrent.ExecutionError; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import com.google.common.util.concurrent.UncheckedExecutionException; import io.grpc.Call; import io.grpc.Metadata; import io.grpc.MethodDescriptor; import io.grpc.Status; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.TimeUnit; /** * Utility functions for processing different call idioms. We have one-to-one correspondence * between utilities in this class and the potential signatures in a generated stub class so * that the runtime can vary behavior without requiring regeneration of the stub. */ public class Calls { /** * Creates a MethodDescriptor for a given method. * * @param fullServiceName fully qualified service name * @param method carries all invariants of the method */ public static <RequestT, ResponseT> MethodDescriptor<RequestT, ResponseT> createMethodDescriptor( String fullServiceName, Method<RequestT, ResponseT> method) { // TODO(zhangkun): if timeout is not defined in proto file, use a default timeout here. // If timeout is defined in proto file, Method should carry the timeout. return MethodDescriptor.create(method.getType(), fullServiceName + "/" + method.getName(), 1, TimeUnit.SECONDS, method.getRequestMarshaller(), method.getResponseMarshaller()); } /** * Execute a unary call and return a {@link ListenableFuture} to the response. * @return a future for the single response message. */ public static <ReqT, RespT> ListenableFuture<RespT> unaryFutureCall( Call<ReqT, RespT> call, ReqT param) { SettableFuture<RespT> responseFuture = SettableFuture.create(); asyncServerStreamingCall(call, param, new UnaryStreamToFuture<RespT>(responseFuture)); return responseFuture; } /** * Returns the result of calling {@link Future#get()} interruptably on a task known not to throw a * checked exception. * * <p>If interrupted, the interrupt is restored before throwing a {@code RuntimeException}. * * @throws RuntimeException if {@code get} is interrupted * @throws CancellationException if {@code get} throws a {@code CancellationException} * @throws UncheckedExecutionException if {@code get} throws an {@code ExecutionException} with an * {@code Exception} as its cause * @throws ExecutionError if {@code get} throws an {@code ExecutionException} with an {@code * Error} as its cause */ private static <V> V getUnchecked(Future<V> future) { try { return future.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } catch (ExecutionException e) { if (e.getCause() == null) { // Strange... throw new UncheckedExecutionException(e); } else { if (e.getCause() instanceof Error) { throw new ExecutionError((Error) e.getCause()); } else { throw new UncheckedExecutionException(e.getCause()); } } } } /** * Execute a unary call and block on the response. * @return the single response message. */ public static <ReqT, RespT> RespT blockingUnaryCall(Call<ReqT, RespT> call, ReqT param) { try { return getUnchecked(unaryFutureCall(call, param)); } catch (Throwable t) { call.cancel(); throw Throwables.propagate(t); } } /** * Execute a unary call with a response {@link StreamObserver}. */ public static <ReqT, RespT> void asyncUnaryCall( Call<ReqT, RespT> call, ReqT param, StreamObserver<RespT> observer) { asyncServerStreamingCall(call, param, observer); } /** * Execute a server-streaming call returning a blocking {@link Iterator} over the * response stream. * @return an iterator over the response stream. */ // TODO(lryan): Not clear if we want to use this idiom for 'simple' stubs. public static <ReqT, RespT> Iterator<RespT> blockingServerStreamingCall( Call<ReqT, RespT> call, ReqT param) { BlockingResponseStream<RespT> result = new BlockingResponseStream<RespT>(call); asyncServerStreamingCall(call, param, result.listener()); return result; } /** * Execute a server-streaming call with a response {@link StreamObserver}. */ public static <ReqT, RespT> void asyncServerStreamingCall( Call<ReqT, RespT> call, ReqT param, StreamObserver<RespT> responseObserver) { asyncServerStreamingCall(call, param, new StreamObserverToCallListenerAdapter<RespT>(call, responseObserver)); } private static <ReqT, RespT> void asyncServerStreamingCall( Call<ReqT, RespT> call, ReqT param, Call.Listener<RespT> responseListener) { call.start(responseListener, new Metadata.Headers()); call.request(1); try { call.sendPayload(param); call.halfClose(); } catch (Throwable t) { call.cancel(); throw Throwables.propagate(t); } } /** * Execute a client-streaming call with a blocking {@link Iterator} of request messages. * @return the single response value. */ public static <ReqT, RespT> RespT blockingClientStreamingCall( Call<ReqT, RespT> call, Iterator<ReqT> clientStream) { SettableFuture<RespT> responseFuture = SettableFuture.create(); call.start(new UnaryStreamToFuture<RespT>(responseFuture), new Metadata.Headers()); try { while (clientStream.hasNext()) { call.sendPayload(clientStream.next()); } call.halfClose(); } catch (Throwable t) { call.cancel(); throw Throwables.propagate(t); } try { return getUnchecked(responseFuture); } catch (Throwable t) { call.cancel(); throw Throwables.propagate(t); } } /** * Execute a client-streaming call returning a {@link StreamObserver} for the request messages. * @return request stream observer. */ public static <ReqT, RespT> StreamObserver<ReqT> asyncClientStreamingCall( Call<ReqT, RespT> call, StreamObserver<RespT> responseObserver) { return duplexStreamingCall(call, responseObserver); } /** * Execute a duplex-streaming call. * @return request stream observer. */ public static <ReqT, RespT> StreamObserver<ReqT> duplexStreamingCall(Call<ReqT, RespT> call, StreamObserver<RespT> responseObserver) { call.start(new StreamObserverToCallListenerAdapter<RespT>(call, responseObserver), new Metadata.Headers()); call.request(1); return new CallToStreamObserverAdapter<ReqT>(call); } private static class CallToStreamObserverAdapter<T> implements StreamObserver<T> { private final Call<T, ?> call; public CallToStreamObserverAdapter(Call<T, ?> call) { this.call = call; } @Override public void onValue(T value) { call.sendPayload(value); } @Override public void onError(Throwable t) { // TODO(ejona): log? call.cancel(); } @Override public void onCompleted() { call.halfClose(); } } private static class StreamObserverToCallListenerAdapter<RespT> extends Call.Listener<RespT> { private final Call<?, RespT> call; private final StreamObserver<RespT> observer; public StreamObserverToCallListenerAdapter(Call<?, RespT> call, StreamObserver<RespT> observer) { this.call = call; this.observer = observer; } @Override public void onHeaders(Metadata.Headers headers) { } @Override public void onPayload(RespT payload) { observer.onValue(payload); // Request delivery of the next inbound message. call.request(1); } @Override public void onClose(Status status, Metadata.Trailers trailers) { if (status.isOk()) { observer.onCompleted(); } else { observer.onError(status.asRuntimeException()); } } } /** * Complete a SettableFuture using {@link StreamObserver} events. */ private static class UnaryStreamToFuture<RespT> extends Call.Listener<RespT> { private final SettableFuture<RespT> responseFuture; private RespT value; public UnaryStreamToFuture(SettableFuture<RespT> responseFuture) { this.responseFuture = responseFuture; } @Override public void onHeaders(Metadata.Headers headers) { } @Override public void onPayload(RespT value) { if (this.value != null) { throw Status.INTERNAL.withDescription("More than one value received for unary call") .asRuntimeException(); } this.value = value; } @Override public void onClose(Status status, Metadata.Trailers trailers) { if (status.isOk()) { if (value == null) { // No value received so mark the future as an error responseFuture.setException( Status.INTERNAL.withDescription("No value received for unary call") .asRuntimeException().fillInStackTrace()); } responseFuture.set(value); } else { responseFuture.setException(status.asRuntimeException()); } } } /** * Convert events on a {@link io.grpc.Call.Listener} into a blocking * {@link Iterator}. * * <p>The class is not thread-safe, but it does permit Call.Listener calls in a separate thread * from Iterator calls. */ // TODO(ejona): determine how to allow Call.cancel() in case of application error. private static class BlockingResponseStream<T> implements Iterator<T> { // Due to flow control, only needs to hold up to 2 items: 1 for value, 1 for close. private final BlockingQueue<Object> buffer = new ArrayBlockingQueue<Object>(2); private final Call.Listener<T> listener = new QueuingListener(); private final Call<?, T> call; // Only accessed when iterating. private Object last; private BlockingResponseStream(Call<?, T> call) { this.call = call; } Call.Listener<T> listener() { return listener; } @Override public boolean hasNext() { try { // Will block here indefinitely waiting for content. RPC timeouts defend against permanent // hangs here as the call will become closed. last = (last == null) ? buffer.take() : last; } catch (InterruptedException ie) { Thread.interrupted(); throw new RuntimeException(ie); } if (last instanceof Throwable) { throw Throwables.propagate((Throwable) last); } return last != this; } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } try { call.request(1); @SuppressWarnings("unchecked") T tmp = (T) last; return tmp; } finally { last = null; } } @Override public void remove() { throw new UnsupportedOperationException(); } private class QueuingListener extends Call.Listener<T> { private boolean done = false; @Override public void onHeaders(Metadata.Headers headers) { } @Override public void onPayload(T value) { Preconditions.checkState(!done, "Call already closed"); buffer.add(value); } @Override public void onClose(Status status, Metadata.Trailers trailers) { Preconditions.checkState(!done, "Call already closed"); if (status.isOk()) { buffer.add(BlockingResponseStream.this); } else { buffer.add(status.asRuntimeException()); } done = true; } } } }
package org.cactoos.iterable; import java.util.Iterator; import org.cactoos.iterator.Mapped; /** * Synchronized iterable. * * <p> * This class should be used very carefully. You must understand that it will * fetch the entire content of the encapsulated {@link Iterable} on each method * call. It doesn't cache the data anyhow. If you don't need this * {@link Iterable} to re-fresh its content on every call, by doing round-trips * to the encapsulated iterable, use {@link Sticky}. * </p> * * <p> * Objects of this class are thread-safe. * </p> * @param <X> Type of item * @since 0.24 */ public final class Synced<X> implements Iterable<X> { /** * The iterable. */ private final Iterable<? extends X> origin; /** * Sync lock. */ private final Object lock; /** * Ctor. * @param src The underlying iterable */ @SafeVarargs public Synced(final X... src) { this(new IterableOf<>(src)); } /** * Ctor. * @param iterable The iterable synchronize access to. */ public Synced(final Iterable<? extends X> iterable) { this(new Object(), iterable); } /** * Ctor. * @param lck The lock to synchronize with. * @param iterable The iterable synchronize access to. */ public Synced(final Object lck, final Iterable<? extends X> iterable) { this.origin = iterable; this.lock = lck; } @SuppressWarnings("unchecked") @Override public Iterator<X> iterator() { synchronized (this.lock) { return (Iterator<X>) this.origin.iterator(); } } }
package eu.qualimaster.monitoring.storm; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.storm.curator.framework.CuratorFramework; import org.apache.thrift7.TException; import eu.qualimaster.coordination.HostPort; import eu.qualimaster.coordination.INameMapping; import eu.qualimaster.coordination.TaskAssignment; import eu.qualimaster.coordination.ZkUtils; import eu.qualimaster.coordination.INameMapping.Component; import eu.qualimaster.coordination.INameMapping.Component.Type; import eu.qualimaster.dataManagement.DataManager; import eu.qualimaster.infrastructure.InitializationMode; import eu.qualimaster.infrastructure.PipelineLifecycleEvent; import eu.qualimaster.monitoring.AbstractContainerMonitoringTask; import eu.qualimaster.monitoring.MonitoringConfiguration; import eu.qualimaster.monitoring.MonitoringManager; import eu.qualimaster.monitoring.MonitoringManager.PipelineInfo; import eu.qualimaster.monitoring.events.ComponentKey; import eu.qualimaster.monitoring.observations.ObservedValue; import eu.qualimaster.monitoring.systemState.PipelineNodeSystemPart; import eu.qualimaster.monitoring.systemState.PipelineSystemPart; import eu.qualimaster.monitoring.systemState.StateUtils; import eu.qualimaster.monitoring.systemState.SystemPart; import eu.qualimaster.monitoring.systemState.SystemState; import eu.qualimaster.monitoring.topology.PipelineTopology; import eu.qualimaster.observables.IObservable; import eu.qualimaster.observables.ResourceUsage; import eu.qualimaster.observables.TimeBehavior; import backtype.storm.event.EventManager; import backtype.storm.generated.BoltStats; import backtype.storm.generated.ClusterSummary; import backtype.storm.generated.ExecutorInfo; import backtype.storm.generated.ExecutorSpecificStats; import backtype.storm.generated.ExecutorStats; import backtype.storm.generated.ExecutorSummary; import backtype.storm.generated.NotAliveException; import backtype.storm.generated.StormTopology; import backtype.storm.generated.TopologyInfo; import backtype.storm.generated.TopologySummary; /** * A thrift-based monitoring task for Storm Pipelines. * * @author Holger Eichelberger */ public class ThriftMonitoringTask extends AbstractContainerMonitoringTask { static final String ALL_TIME = ":all-time"; static final String AT_10M = "600"; static final String AT_3H = "10800"; static final String AT_1D = "86400"; private static final Logger LOGGER = LogManager.getLogger(ThriftMonitoringTask.class); private String pipeline; private Set<String> topologyNames = new HashSet<String>(); private StormConnection connection; /** * Creates the monitoring task. * * @param pipeline the pipeline name * @param connection the Storm connection * @param state the system state to be modified due to monitoring */ ThriftMonitoringTask(String pipeline, StormConnection connection, SystemState state) { super(state); this.pipeline = pipeline; this.connection = connection; INameMapping mapping = MonitoringManager.getNameMapping(pipeline); if (null != mapping) { topologyNames.addAll(mapping.getPipelineNames()); } else { LOGGER.error("no name mapping for pipeline " + pipeline); } } @Override public void monitor() { if (connection.open()) { try { ClusterSummary summary = connection.getClusterSummary(); List<TopologySummary> topologies = summary.get_topologies(); Set<PipelineSystemPart> modified = new HashSet<PipelineSystemPart>(); for (int t = 0; t < topologies.size(); t++) { TopologySummary topologySummary = topologies.get(t); if (topologyNames.contains(topologySummary.get_name())) { try { PipelineSystemPart part = aggregateTopology( connection.getTopologyInfo(topologySummary.get_id())); if (null != part) { modified.add(part); } } catch (NotAliveException e) { } } } // not handled by further state correctly... just ignore for now /*Collection<PipelineSystemPart> pipelines = getState().getPipelines(); for (PipelineSystemPart pipeline : pipelines) { if (!modified.contains(pipeline) && pipeline.getStatus().wasStarted()) { pipeline.changeStatus(PipelineLifecycleEvent.Status.DISAPPEARED, true); } }*/ } catch (TException e) { LOGGER.error("Cannot obtain thrift data " + e.getMessage(), e); } catch (IllegalStateException e) { // monitoring runs longer than topology exists... ignore } } } /** * Testing. * * @param topology the topology */ @SuppressWarnings("unused") private void checkAssignment(TopologyInfo topology) { CuratorFramework curator = connection.getCurator(); if (null != curator) { try { List<HostPort> hosts = HostPort.toHostPort(ZkUtils.getAliveWorkers(curator, topology), HostPort.WORKERBEATS_HOSTPORT_PARSER); System.out.println("ALIVE " + hosts); Map<Integer, String> taskComponents = ZkUtils.taskComponentMapping(topology); Map<String, List<TaskAssignment>> componentAssignments = TaskAssignment.readTaskAssignments(ZkUtils.getAssignment(curator, topology), taskComponents); System.out.println("ASSNG " + componentAssignments); } catch (IOException e) { e.printStackTrace(); } } } /** * Returns whether the component assigned to <code>nodeName</code> is a sink. * * @param mapping the name mapping * @param nodeName the node name * @return <code>true</code> if it is a sink, <code>false</code> else */ @SuppressWarnings("unused") private boolean isSink(INameMapping mapping, String nodeName) { Component comp = mapping.getPipelineNodeComponent(nodeName); return null != comp && Type.SINK == comp.getType(); } /** * Prepares a topology for aggregation. * * @param topology the topology * @param mapping the mapping * @return the pipeline system part representing the pipeline * @throws NotAliveException in case that the requested topology is not alive * @throws TException in case of problems accessing the remote topology info */ private PipelineSystemPart preparePipelineAggregation(TopologyInfo topology, INameMapping mapping) throws TException, NotAliveException { SystemState state = getState(); String pipelineName = mapping.getPipelineName(); PipelineSystemPart part = state.obtainPipeline(pipelineName); // exists or creates if (null == part.getTopology()) { PipelineInfo info = MonitoringManager.getPipelineInfo(pipelineName); Map<StormTopology, TopologyInfo> topologies = new HashMap<StormTopology, TopologyInfo>(); topologies.put(connection.getTopology(topology), topology); for (PipelineInfo subInfo : info.getSubPipelines()) { String subName = subInfo.getName(); try { TopologyInfo si = connection.getTopologyInfoByName(subName); topologies.put(connection.getTopology(si), si); } catch (NotAliveException e) { LOGGER.info("Sub-topology not alive: " + subName); } } PipelineTopology topo = Utils.buildPipelineTopology(topologies, mapping); part.setTopology(topo); if (null != topo) { LOGGER.info("TOPOLOGY for " + mapping.getPipelineName() + " " + topo); } } if (PipelineLifecycleEvent.Status.INITIALIZED == part.getStatus() && !DataManager.isStarted()) { if (System.currentTimeMillis() - part.getLastStateChange() // TODO WORKAROUND FOR DML > MonitoringConfiguration.getPipelineStartNotificationDelay()) { part.changeStatus(PipelineLifecycleEvent.Status.STARTED, true); } } return part; } /** * Returns whether the given node is considered to be up. * * @param nodePart the node part * @param executor the executor * @return <code>true</code> for up, <code>false</code> else */ private static boolean isUp(PipelineNodeSystemPart nodePart, ExecutorSummary executor) { boolean up = false; int currentTasks = (int) nodePart.getObservedValue(ResourceUsage.TASKS); if (nodePart.getObservedValue(ResourceUsage.TASKS) > 0) { InitializationMode initMode = MonitoringConfiguration.getInitializationMode(); if (InitializationMode.DYNAMIC == initMode) { // dynamic: we need an algorithm change before up = null != nodePart.getCurrent(); if (MonitoringConfiguration.getStormExecutorStartupParallel()) { // enable debugging up &= currentTasks >= nodePart.getCurrentCount(); // relaxed condition, happens sometime // consider Utils.taskCount as required upper limit? } } else if (InitializationMode.ADAPTIVE == initMode) { // adaptive: nothing set, go to adaptive init as soon as possible but consider tasks if (MonitoringConfiguration.getStormExecutorStartupParallel()) { // enable debugging int neededTasks = Utils.taskCount(executor); up = currentTasks >= neededTasks; // relaxed condition, happens sometime } else { up = true; } } else { // static: don't care - as before up = true; } } return up; } /** * Returns the executor start waiting time. Disabled in adaptive startup mode as we have to rely on all events * being sent correctly. * * @return the executor start waiting time in seconds */ private static int getExecutorStartWaitingTime() { return InitializationMode.ADAPTIVE == MonitoringConfiguration.getInitializationMode() ? 0 : MonitoringConfiguration.getStormExecutorStartupWaitingTime(); } /** * Aggregates the values for the topology. * * @param topology the topology information to be aggregated * @return the affected / modified pipeline system part, may be <b>null</b> if the pipeline / topology yet does * not exist * @throws NotAliveException in case that the requested topology is not alive * @throws TException in case of problems accessing the remote topology info */ private PipelineSystemPart aggregateTopology(TopologyInfo topology) throws TException, NotAliveException { PipelineSystemPart part = null; INameMapping mapping = MonitoringManager.getNameMapping(pipeline); int executorStartWaitingTime = getExecutorStartWaitingTime(); if (null != mapping) { part = preparePipelineAggregation(topology, mapping); List<ExecutorSummary> executors = topology.get_executors(); PipelineStatistics pStat = new PipelineStatistics(part); List<String> uptime = new ArrayList<String>(); List<String> eventsReceived = new ArrayList<String>(); int executorRunningCount = 0; // first heuristics... uptime of executors - does not work in every case List<String> nonInternal = new ArrayList<String>(); // second heuristics... non-legacy pipelines via events int nonInternalRunningCount = 0; for (int e = 0; e < executors.size(); e++) { ExecutorSummary executor = executors.get(e); String nodeName = executor.get_component_id(); if (executorStartWaitingTime > 0 && executor.get_uptime_secs() > executorStartWaitingTime) { executorRunningCount++; uptime.add(nodeName); } boolean isInternal = Utils.isInternal(executor); ExecutorStats stats = executor.get_stats(); PipelineNodeSystemPart nodePart = check(SystemState.getNodePart(mapping, part, nodeName), isInternal); if (!isInternal) { nonInternal.add(nodeName); if (isUp(nodePart, executor)) { nonInternalRunningCount++; eventsReceived.add(nodeName); } } if (null != stats) { if (isInternal) { nodeName = "_SYSTEM_"; // TODO check whether a special node is better } if (doThrift(executor, nodePart, isInternal)) { // non-thrift happens along the events aggregateExecutor(executor, nodePart, isInternal); } if (!isInternal && nodePart.getParent() instanceof PipelineSystemPart) { // pipeline -> reduce load sendSummaryEvent(nodePart, part.getName(), MonitoringManager.DEMO_MSG_PROCESSING_ELEMENT); } } // no stats... in particular if pStat.collect(nodePart); } debugExecutors(executors, mapping, part); boolean allInitialized = pStat.commit(); sendSummaryEvent(part, null, MonitoringManager.DEMO_MSG_PIPELINE); boolean createdChanged = false; if ((PipelineLifecycleEvent.Status.UNKNOWN == part.getStatus() // shall not happen || PipelineLifecycleEvent.Status.STARTING == part.getStatus())) { // consider pipeline creation finished as soon as all executors are running and ready to work LOGGER.info("Trying to elevate '" + part.getName() + "' to CREATED: uptime " + uptime + " " + executors.size() + " " + executorRunningCount + " events expected " + nonInternal + " received " + eventsReceived + " " + nonInternal.size() + " " + nonInternalRunningCount); if (executors.size() == executorRunningCount || nonInternal.size() == nonInternalRunningCount) { part.changeStatus(PipelineLifecycleEvent.Status.CREATED, true); createdChanged = true; } } if (!createdChanged && PipelineLifecycleEvent.Status.CREATED == part.getStatus()) { logElevating(part, pStat); if (allInitialized && areSubpipelinesUp(part.getName())) { part.changeStatus(PipelineLifecycleEvent.Status.INITIALIZED, true); } } } else { LOGGER.error("no mapping for " + topology.get_name()); } return part; } /** * Checks whether <code>nodePart</code> shall be/is internal. * * @param nodePart the node part * @param isInternal the internal flag * @return <code>nodePart</code> */ private static PipelineNodeSystemPart check(PipelineNodeSystemPart nodePart, boolean isInternal) { if (isInternal) { nodePart.markAsInternal(); } return nodePart; } /** * Logs the elevation situation for INITIALIZED. * * @param part the pipeline system part * @param pStat the pipeline statistics */ private static void logElevating(PipelineSystemPart part, PipelineStatistics pStat) { LOGGER.info("Trying to elevate '" + part.getName() + "' to INITIALIZED: " + pStat.getNeedInitializationCount() + " " + pStat.getInitializedCount() + " needed " + pStat.toStringNeedInitialization() + " init " + pStat.toStringInitialized()); } /** * Returns whether all sub-pipelines on the cluster (not all configured ones) are up. * * @param pipelineName the name of the pipeline to check the sub-pipelines for * @return <code>true</code> if all are up or no sub-pipelines are defined, <code>false</code> if at least one * sub-pipeline is not up */ private boolean areSubpipelinesUp(String pipelineName) { PipelineInfo info = MonitoringManager.getPipelineInfo(pipelineName); boolean allConnected = true; if (null != info) { for (PipelineInfo subInfo : info.getSubPipelines()) { if (!(PipelineLifecycleEvent.Status.INITIALIZED == subInfo.getStatus() || PipelineLifecycleEvent.Status.STARTED == subInfo.getStatus())) { allConnected = false; } } } else { allConnected = true; } return allConnected; } /** * Debug-print the non-thrift executor states. * * @param executors the executors * @param mapping the name mapping * @param part the pipeline parts */ private void debugExecutors(List<ExecutorSummary> executors, INameMapping mapping, PipelineSystemPart part) { if (MonitoringConfiguration.debugThriftMonitoring()) { LogManager.getLogger(EventManager.class).info("from events " + part); for (int e = 0; e < executors.size(); e++) { ExecutorSummary executor = executors.get(e); boolean isInternal = Utils.isInternal(executor); String nodeName = executor.get_component_id(); PipelineNodeSystemPart nodePart = SystemState.getNodePart(mapping, part, nodeName); if (!doThrift(executor, nodePart, isInternal)) { LogManager.getLogger(EventManager.class).info("from events " + nodePart); } } } } /** * Returns the number of tasks handled by an executor. * * @param executor the executor (summary) * @return the number of tasks */ private static int getTaskCount(ExecutorSummary executor) { ExecutorInfo info = executor.get_executor_info(); return info.get_task_end() - info.get_task_start() + 1; } /** * Aggregates an executor. * * @param executor the executor * @param nodePart the target node part * @param isInternal whether it is considered as an internal Storm node */ private void aggregateExecutor(ExecutorSummary executor, PipelineNodeSystemPart nodePart, boolean isInternal) { List<ComponentKey> keys = toKeys(executor); ExecutorStats stats = executor.get_stats(); int tasks = keys.size(); for (int k = 0; k < tasks; k++) { ComponentKey key = keys.get(k); if (stats.get_specific().is_set_bolt()) { aggregateBolt(executor, nodePart, isInternal, key, tasks); } else if (stats.get_specific().is_set_spout()) { aggregateSpout(executor, nodePart, isInternal, key, tasks); } else { aggregateOther(executor, nodePart, isInternal, key, tasks); } } setValueToKeysAndClear(nodePart, keys, ResourceUsage.EXECUTORS, 1); setValueToKeysAndClear(nodePart, keys, ResourceUsage.TASKS, getTaskCount(executor)); } /** * Returns whether thrift monitoring shall be done for the given executor / node part. * * @param executor the executor * @param nodePart the node part * @param isInternal whether the executor is considered to be an internal node * @return <code>true</code> for thrift monitoring, <code>false</code> else */ private boolean doThrift(ExecutorSummary executor, PipelineNodeSystemPart nodePart, boolean isInternal) { boolean doThrift = nodePart.useThrift(); if (doThrift) { ExecutorStats stats = executor.get_stats(); if (null != stats && null != stats.get_specific() && (!stats.get_specific().is_set_bolt() && !stats.get_specific().is_set_spout())) { doThrift = isInternal; } } return doThrift; } /** * Aggregates a spout. * * @param executor the executor summary * @param part the system part representing the node * @param isInternal whether <code>executor</code> is internal * @param key the component to modify * @param keyCount the number of keys/tasks of <code>executor</code> */ private void aggregateSpout(ExecutorSummary executor, PipelineNodeSystemPart part, boolean isInternal, ComponentKey key, int keyCount) { // ack in a Spout corresponds to the totally acked items, not to the actual ones as in a Bolt // get_complete_ms_avg() measures the entire tree // relying on monitoring messages that deliver LATENCY and THROUGHPUT - updated there // :complete-latencies get_complete_ms_avg / get_acked if (MonitoringConfiguration.debugThriftMonitoring()) { LogManager.getLogger(EventManager.class).info("from thrift " + part.getName() + " capacity " + part.getObservedValue(ResourceUsage.CAPACITY, key) + " throughput " + part.getObservedValue(TimeBehavior.THROUGHPUT_ITEMS, key) + " key " + key + " -> " + part); } } /** * Aggregates an other node. * * @param executor the executor summary * @param part the system part representing the node * @param isInternal whether <code>executor</code> is internal * @param key the component to modify * @param keyCount the number of keys/tasks of <code>executor</code> */ private void aggregateOther(ExecutorSummary executor, PipelineNodeSystemPart part, boolean isInternal, ComponentKey key, int keyCount) { ExecutorStats stats = executor.get_stats(); ObservedValue executeLatencyValue = part.getObservedValue(TimeBehavior.LATENCY, key); double executeLatency = null == executeLatencyValue ? 0 : executeLatencyValue.get(); if (!isInternal) { long executedAll = getLongStatValue(stats.get_emitted(), ALL_TIME); StateUtils.setValue(part, TimeBehavior.THROUGHPUT_ITEMS, executedAll / keyCount, key); StateUtils.updateCapacity(part, key, true); if (MonitoringConfiguration.debugThriftMonitoring()) { LogManager.getLogger(EventManager.class).info("from thrift " + part.getName() + " executedAll " + executedAll + " execLatency " + executeLatency + " capacity " + part.getObservedValue(ResourceUsage.CAPACITY, key) + " throughput " + part.getObservedValue(TimeBehavior.THROUGHPUT_ITEMS, key) + " key " + key + " -> " + part); } } } /** * Handles a bolt. * * @param executor the executor summary * @param part the system part representing the node * @param isInternal whether <code>executor</code> is internal * @param key the component to modify * @param keyCount the number of keys/tasks of <code>executor</code> */ private void aggregateBolt(ExecutorSummary executor, PipelineNodeSystemPart part, boolean isInternal, ComponentKey key, int keyCount) { ExecutorStats stats = executor.get_stats(); ExecutorSpecificStats specificStats = stats.get_specific(); BoltStats boltStats = specificStats.get_bolt(); //executor_throughput_items = getBoltStatLongValueFromMap(boltStats.get_executed(), ALL_TIME); if (!isInternal) { double executeLatency; double executed; // :process-latencies process_ms_avg / get_acked; :execute-latencies execute_ms_avg / get_executed if (Type.SINK == part.getComponentType()) { // storm includes all outgoing streams executeLatency = getDoubleMinStatValue(boltStats.get_process_ms_avg(), AT_10M); executed = getLongStatValue(boltStats.get_executed(), AT_10M); } else { // storm includes all outgoing streams executeLatency = getDoubleMinStatValue(boltStats.get_process_ms_avg(), AT_10M); executed = getLongStatValue(stats.get_emitted(), AT_10M); } StateUtils.setValue(part, TimeBehavior.LATENCY, executeLatency, key); // average over all tasks // sum of all tasks StateUtils.setValue(part, TimeBehavior.THROUGHPUT_ITEMS, executed / keyCount, key); StateUtils.updateCapacity(part, key, true); if (MonitoringConfiguration.debugThriftMonitoring()) { LogManager.getLogger(EventManager.class).info("from thrift " + part.getName() + " executed " + executed + boltStats.get_executed() + " execLatency " + executeLatency + " " + boltStats.get_execute_ms_avg() + " processLatency " + getDoubleStatValue(boltStats.get_process_ms_avg(), AT_10M) + " " + boltStats.get_process_ms_avg() + " capacity " + part.getObservedValue(ResourceUsage.CAPACITY, key) + " throughput " + part.getObservedValue(TimeBehavior.THROUGHPUT_ITEMS, key) + " key " + key + " -> " + part); } } } /** * Sets the given <code>value</code> to all components in the observation of <code>observable</code> in * <code>part</code> and clears unnamed components. * * @param part the system part * @param keys the keys to set the value for (and to clear the remaining ones) * @param observable the observable to operate on * @param value the value to set */ private void setValueToKeysAndClear(PipelineNodeSystemPart part, List<ComponentKey> keys, IObservable observable, double value) { Set<Object> executorKeys = new HashSet<Object>(); executorKeys.addAll(part.getComponentKeys(observable)); setValue(part, observable, 1, keys); executorKeys.remove(keys); part.clearComponents(observable, executorKeys); } /** * Turns an executor summary into component keys. * * @param executor the executor summary * @return the component keys */ private List<ComponentKey> toKeys(ExecutorSummary executor) { List<ComponentKey> keys = new ArrayList<ComponentKey>(); ExecutorInfo info = executor.get_executor_info(); for (int t = info.get_task_start(); t <= info.get_task_end(); t++) { keys.add(new ComponentKey(executor.get_host(), executor.get_port(), t)); } return keys; } /** * Sets an observation value for multiple component keys. * * @param part the target system part * @param observable the observable * @param value the observed value * @param keys the component keys */ private void setValue(SystemPart part, IObservable observable, double value, List<ComponentKey> keys) { for (int k = 0; k < keys.size(); k++) { StateUtils.setValue(part, observable, value, keys.get(k)); } } // further conversions e.g. from long to double if required shall be added in the style of the value methods above /** * Returns a (sum) stat value from a value map. * * @param <T> the inner key type * @param map the value map * @param statName the stat name * @return the stat value */ public static <T> double getDoubleStatValue(Map<String, Map<T, Double>> map, String statName) { double result = 0.0; Map<?, Double> intermediateMap = map.get(statName); if (null != intermediateMap) { for (Map.Entry<?, Double> ent : intermediateMap.entrySet()) { Object streamId = ent.getKey(); if (null != streamId && !streamId.toString().startsWith("__")) { Double dbl = ent.getValue(); if (null != dbl) { result += dbl; } } } } return result; } /** * Returns a (min) stat value from a value map. * * @param <T> the inner key type * @param map the value map * @param statName the stat name * @return the stat value */ public static <T> double getDoubleMinStatValue(Map<String, Map<T, Double>> map, String statName) { double result = 0.0; int count = 0; Map<?, Double> intermediateMap = map.get(statName); if (null != intermediateMap) { for (Map.Entry<?, Double> ent : intermediateMap.entrySet()) { Object streamId = ent.getKey(); if (null != streamId && !streamId.toString().startsWith("__")) { Double dbl = ent.getValue(); if (null != dbl) { if (0 == count) { result = dbl; } else { result = Math.min(dbl, result); } } } } } return result; } /** * Returns a stat value from a value map. * * @param <T> the inner key type * @param map the value map * @param statName the stat name * @return the stat value */ public static <T> long getLongStatValue(Map<String, Map<T, Long>> map, String statName) { long result = 0; Map<?, Long> intermediateMap = map.get(statName); if (null != intermediateMap) { for (Map.Entry<?, Long> ent : intermediateMap.entrySet()) { Object streamId = ent.getKey(); if (null != streamId && !streamId.toString().startsWith("__")) { Long dbl = ent.getValue(); if (null != dbl) { result += dbl; } } } } return result; } @Override public boolean cancel() { return super.cancel(); } @Override public int getFrequency() { return MonitoringConfiguration.getPipelineMonitoringFrequency(); } @Override protected void failover(Throwable th) { connection.failover(th); } }
package org.jfree.chart.plot; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Composite; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.ResourceBundle; import java.util.Set; import java.util.TreeMap; import org.jfree.chart.JFreeChart; import org.jfree.chart.LegendItem; import org.jfree.chart.LegendItemCollection; import org.jfree.chart.annotations.Annotation; import org.jfree.chart.annotations.XYAnnotation; import org.jfree.chart.annotations.XYAnnotationBoundsInfo; import org.jfree.chart.axis.Axis; import org.jfree.chart.axis.AxisCollection; import org.jfree.chart.axis.AxisLocation; import org.jfree.chart.axis.AxisSpace; import org.jfree.chart.axis.AxisState; import org.jfree.chart.axis.TickType; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.axis.ValueTick; import org.jfree.chart.event.AnnotationChangeEvent; import org.jfree.chart.event.ChartChangeEventType; import org.jfree.chart.event.PlotChangeEvent; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.event.RendererChangeListener; import org.jfree.chart.renderer.RendererUtilities; import org.jfree.chart.renderer.xy.AbstractXYItemRenderer; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.chart.renderer.xy.XYItemRendererState; import org.jfree.chart.util.CloneUtils; import org.jfree.chart.util.ParamChecks; import org.jfree.chart.util.ResourceBundleWrapper; import org.jfree.chart.util.ShadowGenerator; import org.jfree.data.Range; import org.jfree.data.general.DatasetChangeEvent; import org.jfree.data.general.DatasetUtilities; import org.jfree.data.xy.XYDataset; import org.jfree.io.SerialUtilities; import org.jfree.ui.Layer; import org.jfree.ui.RectangleEdge; import org.jfree.ui.RectangleInsets; import org.jfree.util.ObjectUtilities; import org.jfree.util.PaintUtilities; import org.jfree.util.PublicCloneable; /** * A general class for plotting data in the form of (x, y) pairs. This plot can * use data from any class that implements the {@link XYDataset} interface. * <P> * {@code XYPlot} makes use of an {@link XYItemRenderer} to draw each point * on the plot. By using different renderers, various chart types can be * produced. * <p> * The {@link org.jfree.chart.ChartFactory} class contains static methods for * creating pre-configured charts. */ public class XYPlot extends Plot implements ValueAxisPlot, Pannable, Zoomable, RendererChangeListener, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 7044148245716569264L; /** The default grid line stroke. */ public static final Stroke DEFAULT_GRIDLINE_STROKE = new BasicStroke(0.5f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0.0f, new float[] {2.0f, 2.0f}, 0.0f); /** The default grid line paint. */ public static final Paint DEFAULT_GRIDLINE_PAINT = Color.lightGray; /** The default crosshair visibility. */ public static final boolean DEFAULT_CROSSHAIR_VISIBLE = false; /** The default crosshair stroke. */ public static final Stroke DEFAULT_CROSSHAIR_STROKE = DEFAULT_GRIDLINE_STROKE; /** The default crosshair paint. */ public static final Paint DEFAULT_CROSSHAIR_PAINT = Color.blue; /** The resourceBundle for the localization. */ protected static ResourceBundle localizationResources = ResourceBundleWrapper.getBundle( "org.jfree.chart.plot.LocalizationBundle"); /** The plot orientation. */ private PlotOrientation orientation; /** The offset between the data area and the axes. */ private RectangleInsets axisOffset; /** The domain axis / axes (used for the x-values). */ private Map<Integer, ValueAxis> domainAxes; /** The domain axis locations. */ private Map<Integer, AxisLocation> domainAxisLocations; /** The range axis (used for the y-values). */ private Map<Integer, ValueAxis> rangeAxes; /** The range axis location. */ private Map<Integer, AxisLocation> rangeAxisLocations; /** Storage for the datasets. */ private Map<Integer, XYDataset> datasets; /** Storage for the renderers. */ private Map<Integer, XYItemRenderer> renderers; /** * Storage for the mapping between datasets/renderers and domain axes. The * keys in the map are Integer objects, corresponding to the dataset * index. The values in the map are List objects containing Integer * objects (corresponding to the axis indices). If the map contains no * entry for a dataset, it is assumed to map to the primary domain axis * (index = 0). */ private Map<Integer, List<Integer>> datasetToDomainAxesMap; /** * Storage for the mapping between datasets/renderers and range axes. The * keys in the map are Integer objects, corresponding to the dataset * index. The values in the map are List objects containing Integer * objects (corresponding to the axis indices). If the map contains no * entry for a dataset, it is assumed to map to the primary domain axis * (index = 0). */ private Map<Integer, List<Integer>> datasetToRangeAxesMap; /** The origin point for the quadrants (if drawn). */ private transient Point2D quadrantOrigin = new Point2D.Double(0.0, 0.0); /** The paint used for each quadrant. */ private transient Paint[] quadrantPaint = new Paint[] {null, null, null, null}; /** A flag that controls whether the domain grid-lines are visible. */ private boolean domainGridlinesVisible; /** The stroke used to draw the domain grid-lines. */ private transient Stroke domainGridlineStroke; /** The paint used to draw the domain grid-lines. */ private transient Paint domainGridlinePaint; /** A flag that controls whether the range grid-lines are visible. */ private boolean rangeGridlinesVisible; /** The stroke used to draw the range grid-lines. */ private transient Stroke rangeGridlineStroke; /** The paint used to draw the range grid-lines. */ private transient Paint rangeGridlinePaint; /** * A flag that controls whether the domain minor grid-lines are visible. * * @since 1.0.12 */ private boolean domainMinorGridlinesVisible; /** * The stroke used to draw the domain minor grid-lines. * * @since 1.0.12 */ private transient Stroke domainMinorGridlineStroke; /** * The paint used to draw the domain minor grid-lines. * * @since 1.0.12 */ private transient Paint domainMinorGridlinePaint; /** * A flag that controls whether the range minor grid-lines are visible. * * @since 1.0.12 */ private boolean rangeMinorGridlinesVisible; /** * The stroke used to draw the range minor grid-lines. * * @since 1.0.12 */ private transient Stroke rangeMinorGridlineStroke; /** * The paint used to draw the range minor grid-lines. * * @since 1.0.12 */ private transient Paint rangeMinorGridlinePaint; /** * A flag that controls whether or not the zero baseline against the domain * axis is visible. * * @since 1.0.5 */ private boolean domainZeroBaselineVisible; /** * The stroke used for the zero baseline against the domain axis. * * @since 1.0.5 */ private transient Stroke domainZeroBaselineStroke; /** * The paint used for the zero baseline against the domain axis. * * @since 1.0.5 */ private transient Paint domainZeroBaselinePaint; /** * A flag that controls whether or not the zero baseline against the range * axis is visible. */ private boolean rangeZeroBaselineVisible; /** The stroke used for the zero baseline against the range axis. */ private transient Stroke rangeZeroBaselineStroke; /** The paint used for the zero baseline against the range axis. */ private transient Paint rangeZeroBaselinePaint; /** A flag that controls whether or not a domain crosshair is drawn..*/ private boolean domainCrosshairVisible; /** The domain crosshair value. */ private double domainCrosshairValue; /** The pen/brush used to draw the crosshair (if any). */ private transient Stroke domainCrosshairStroke; /** The color used to draw the crosshair (if any). */ private transient Paint domainCrosshairPaint; /** * A flag that controls whether or not the crosshair locks onto actual * data points. */ private boolean domainCrosshairLockedOnData = true; /** A flag that controls whether or not a range crosshair is drawn..*/ private boolean rangeCrosshairVisible; /** The range crosshair value. */ private double rangeCrosshairValue; /** The pen/brush used to draw the crosshair (if any). */ private transient Stroke rangeCrosshairStroke; /** The color used to draw the crosshair (if any). */ private transient Paint rangeCrosshairPaint; /** * A flag that controls whether or not the crosshair locks onto actual * data points. */ private boolean rangeCrosshairLockedOnData = true; /** A map of lists of foreground markers (optional) for the domain axes. */ private Map foregroundDomainMarkers; /** A map of lists of background markers (optional) for the domain axes. */ private Map backgroundDomainMarkers; /** A map of lists of foreground markers (optional) for the range axes. */ private Map foregroundRangeMarkers; /** A map of lists of background markers (optional) for the range axes. */ private Map backgroundRangeMarkers; /** * A (possibly empty) list of annotations for the plot. The list should * be initialised in the constructor and never allowed to be * {@code null}. */ private List<XYAnnotation> annotations; /** The paint used for the domain tick bands (if any). */ private transient Paint domainTickBandPaint; /** The paint used for the range tick bands (if any). */ private transient Paint rangeTickBandPaint; /** The fixed domain axis space. */ private AxisSpace fixedDomainAxisSpace; /** The fixed range axis space. */ private AxisSpace fixedRangeAxisSpace; /** * The order of the dataset rendering (REVERSE draws the primary dataset * last so that it appears to be on top). */ private DatasetRenderingOrder datasetRenderingOrder = DatasetRenderingOrder.REVERSE; /** * The order of the series rendering (REVERSE draws the primary series * last so that it appears to be on top). */ private SeriesRenderingOrder seriesRenderingOrder = SeriesRenderingOrder.REVERSE; /** * The weight for this plot (only relevant if this is a subplot in a * combined plot). */ private int weight; /** * An optional collection of legend items that can be returned by the * getLegendItems() method. */ private LegendItemCollection fixedLegendItems; /** * A flag that controls whether or not panning is enabled for the domain * axis/axes. * * @since 1.0.13 */ private boolean domainPannable; /** * A flag that controls whether or not panning is enabled for the range * axis/axes. * * @since 1.0.13 */ private boolean rangePannable; /** * The shadow generator ({@code null} permitted). * * @since 1.0.14 */ private ShadowGenerator shadowGenerator; /** * Creates a new {@code XYPlot} instance with no dataset, no axes and * no renderer. You should specify these items before using the plot. */ public XYPlot() { this(null, null, null, null); } /** * Creates a new plot with the specified dataset, axes and renderer. Any * of the arguments can be {@code null}, but in that case you should * take care to specify the value before using the plot (otherwise a * {@code NullPointerException} may be thrown). * * @param dataset the dataset ({@code null} permitted). * @param domainAxis the domain axis ({@code null} permitted). * @param rangeAxis the range axis ({@code null} permitted). * @param renderer the renderer ({@code null} permitted). */ public XYPlot(XYDataset dataset, ValueAxis domainAxis, ValueAxis rangeAxis, XYItemRenderer renderer) { super(); this.orientation = PlotOrientation.VERTICAL; this.weight = 1; // only relevant when this is a subplot this.axisOffset = RectangleInsets.ZERO_INSETS; // allocate storage for datasets, axes and renderers (all optional) this.domainAxes = new HashMap<Integer, ValueAxis>(); this.domainAxisLocations = new HashMap<Integer, AxisLocation>(); this.foregroundDomainMarkers = new HashMap(); this.backgroundDomainMarkers = new HashMap(); this.rangeAxes = new HashMap<Integer, ValueAxis>(); this.rangeAxisLocations = new HashMap<Integer, AxisLocation>(); this.foregroundRangeMarkers = new HashMap(); this.backgroundRangeMarkers = new HashMap(); this.datasets = new HashMap<Integer, XYDataset>(); this.renderers = new HashMap<Integer, XYItemRenderer>(); this.datasetToDomainAxesMap = new TreeMap(); this.datasetToRangeAxesMap = new TreeMap(); this.annotations = new java.util.ArrayList(); this.datasets.put(0, dataset); if (dataset != null) { dataset.addChangeListener(this); } this.renderers.put(0, renderer); if (renderer != null) { renderer.setPlot(this); renderer.addChangeListener(this); } this.domainAxes.put(0, domainAxis); mapDatasetToDomainAxis(0, 0); if (domainAxis != null) { domainAxis.setPlot(this); domainAxis.addChangeListener(this); } this.domainAxisLocations.put(0, AxisLocation.BOTTOM_OR_LEFT); this.rangeAxes.put(0, rangeAxis); mapDatasetToRangeAxis(0, 0); if (rangeAxis != null) { rangeAxis.setPlot(this); rangeAxis.addChangeListener(this); } this.rangeAxisLocations.put(0, AxisLocation.BOTTOM_OR_LEFT); configureDomainAxes(); configureRangeAxes(); this.domainGridlinesVisible = true; this.domainGridlineStroke = DEFAULT_GRIDLINE_STROKE; this.domainGridlinePaint = DEFAULT_GRIDLINE_PAINT; this.domainMinorGridlinesVisible = false; this.domainMinorGridlineStroke = DEFAULT_GRIDLINE_STROKE; this.domainMinorGridlinePaint = Color.white; this.domainZeroBaselineVisible = false; this.domainZeroBaselinePaint = Color.black; this.domainZeroBaselineStroke = new BasicStroke(0.5f); this.rangeGridlinesVisible = true; this.rangeGridlineStroke = DEFAULT_GRIDLINE_STROKE; this.rangeGridlinePaint = DEFAULT_GRIDLINE_PAINT; this.rangeMinorGridlinesVisible = false; this.rangeMinorGridlineStroke = DEFAULT_GRIDLINE_STROKE; this.rangeMinorGridlinePaint = Color.white; this.rangeZeroBaselineVisible = false; this.rangeZeroBaselinePaint = Color.black; this.rangeZeroBaselineStroke = new BasicStroke(0.5f); this.domainCrosshairVisible = false; this.domainCrosshairValue = 0.0; this.domainCrosshairStroke = DEFAULT_CROSSHAIR_STROKE; this.domainCrosshairPaint = DEFAULT_CROSSHAIR_PAINT; this.rangeCrosshairVisible = false; this.rangeCrosshairValue = 0.0; this.rangeCrosshairStroke = DEFAULT_CROSSHAIR_STROKE; this.rangeCrosshairPaint = DEFAULT_CROSSHAIR_PAINT; this.shadowGenerator = null; } /** * Returns the plot type as a string. * * @return A short string describing the type of plot. */ @Override public String getPlotType() { return localizationResources.getString("XY_Plot"); } /** * Returns the orientation of the plot. * * @return The orientation (never {@code null}). * * @see #setOrientation(PlotOrientation) */ @Override public PlotOrientation getOrientation() { return this.orientation; } /** * Sets the orientation for the plot and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param orientation the orientation ({@code null} not allowed). * * @see #getOrientation() */ public void setOrientation(PlotOrientation orientation) { ParamChecks.nullNotPermitted(orientation, "orientation"); if (orientation != this.orientation) { this.orientation = orientation; fireChangeEvent(); } } /** * Returns the axis offset. * * @return The axis offset (never {@code null}). * * @see #setAxisOffset(RectangleInsets) */ public RectangleInsets getAxisOffset() { return this.axisOffset; } /** * Sets the axis offsets (gap between the data area and the axes) and sends * a {@link PlotChangeEvent} to all registered listeners. * * @param offset the offset ({@code null} not permitted). * * @see #getAxisOffset() */ public void setAxisOffset(RectangleInsets offset) { ParamChecks.nullNotPermitted(offset, "offset"); this.axisOffset = offset; fireChangeEvent(); } /** * Returns the domain axis with index 0. If the domain axis for this plot * is {@code null}, then the method will return the parent plot's * domain axis (if there is a parent plot). * * @return The domain axis (possibly {@code null}). * * @see #getDomainAxis(int) * @see #setDomainAxis(ValueAxis) */ public ValueAxis getDomainAxis() { return getDomainAxis(0); } /** * Returns the domain axis with the specified index, or {@code null} if * there is no axis with that index. * * @param index the axis index. * * @return The axis ({@code null} possible). * * @see #setDomainAxis(int, ValueAxis) */ public ValueAxis getDomainAxis(int index) { ValueAxis result = this.domainAxes.get(index); if (result == null) { Plot parent = getParent(); if (parent instanceof XYPlot) { XYPlot xy = (XYPlot) parent; result = xy.getDomainAxis(index); } } return result; } /** * Sets the domain axis for the plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param axis the new axis ({@code null} permitted). * * @see #getDomainAxis() * @see #setDomainAxis(int, ValueAxis) */ public void setDomainAxis(ValueAxis axis) { setDomainAxis(0, axis); } /** * Sets a domain axis and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param index the axis index. * @param axis the axis ({@code null} permitted). * * @see #getDomainAxis(int) * @see #setRangeAxis(int, ValueAxis) */ public void setDomainAxis(int index, ValueAxis axis) { setDomainAxis(index, axis, true); } /** * Sets a domain axis and, if requested, sends a {@link PlotChangeEvent} to * all registered listeners. * * @param index the axis index. * @param axis the axis. * @param notify notify listeners? * * @see #getDomainAxis(int) */ public void setDomainAxis(int index, ValueAxis axis, boolean notify) { ValueAxis existing = getDomainAxis(index); if (existing != null) { existing.removeChangeListener(this); } if (axis != null) { axis.setPlot(this); } this.domainAxes.put(index, axis); if (axis != null) { axis.configure(); axis.addChangeListener(this); } if (notify) { fireChangeEvent(); } } /** * Sets the domain axes for this plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param axes the axes ({@code null} not permitted). * * @see #setRangeAxes(ValueAxis[]) */ public void setDomainAxes(ValueAxis[] axes) { for (int i = 0; i < axes.length; i++) { setDomainAxis(i, axes[i], false); } fireChangeEvent(); } /** * Returns the location of the primary domain axis. * * @return The location (never {@code null}). * * @see #setDomainAxisLocation(AxisLocation) */ public AxisLocation getDomainAxisLocation() { return (AxisLocation) this.domainAxisLocations.get(0); } /** * Sets the location of the primary domain axis and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param location the location ({@code null} not permitted). * * @see #getDomainAxisLocation() */ public void setDomainAxisLocation(AxisLocation location) { // delegate... setDomainAxisLocation(0, location, true); } /** * Sets the location of the domain axis and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param location the location ({@code null} not permitted). * @param notify notify listeners? * * @see #getDomainAxisLocation() */ public void setDomainAxisLocation(AxisLocation location, boolean notify) { // delegate... setDomainAxisLocation(0, location, notify); } /** * Returns the edge for the primary domain axis (taking into account the * plot's orientation). * * @return The edge. * * @see #getDomainAxisLocation() * @see #getOrientation() */ public RectangleEdge getDomainAxisEdge() { return Plot.resolveDomainAxisLocation(getDomainAxisLocation(), this.orientation); } /** * Returns the number of domain axes. * * @return The axis count. * * @see #getRangeAxisCount() */ public int getDomainAxisCount() { return this.domainAxes.size(); } /** * Clears the domain axes from the plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @see #clearRangeAxes() */ public void clearDomainAxes() { for (ValueAxis axis: this.domainAxes.values()) { if (axis != null) { axis.removeChangeListener(this); } } this.domainAxes.clear(); fireChangeEvent(); } /** * Configures the domain axes. */ public void configureDomainAxes() { for (ValueAxis axis: this.domainAxes.values()) { if (axis != null) { axis.configure(); } } } /** * Returns the location for a domain axis. If this hasn't been set * explicitly, the method returns the location that is opposite to the * primary domain axis location. * * @param index the axis index (must be &gt;= 0). * * @return The location (never {@code null}). * * @see #setDomainAxisLocation(int, AxisLocation) */ public AxisLocation getDomainAxisLocation(int index) { AxisLocation result = this.domainAxisLocations.get(index); if (result == null) { result = AxisLocation.getOpposite(getDomainAxisLocation()); } return result; } /** * Sets the location for a domain axis and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param index the axis index. * @param location the location ({@code null} not permitted for index * 0). * * @see #getDomainAxisLocation(int) */ public void setDomainAxisLocation(int index, AxisLocation location) { // delegate... setDomainAxisLocation(index, location, true); } /** * Sets the axis location for a domain axis and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the axis index (must be &gt;= 0). * @param location the location ({@code null} not permitted for * index 0). * @param notify notify listeners? * * @since 1.0.5 * * @see #getDomainAxisLocation(int) * @see #setRangeAxisLocation(int, AxisLocation, boolean) */ public void setDomainAxisLocation(int index, AxisLocation location, boolean notify) { if (index == 0 && location == null) { throw new IllegalArgumentException( "Null 'location' for index 0 not permitted."); } this.domainAxisLocations.put(index, location); if (notify) { fireChangeEvent(); } } /** * Returns the edge for a domain axis. * * @param index the axis index. * * @return The edge. * * @see #getRangeAxisEdge(int) */ public RectangleEdge getDomainAxisEdge(int index) { AxisLocation location = getDomainAxisLocation(index); return Plot.resolveDomainAxisLocation(location, this.orientation); } /** * Returns the range axis for the plot. If the range axis for this plot is * {@code null}, then the method will return the parent plot's range * axis (if there is a parent plot). * * @return The range axis. * * @see #getRangeAxis(int) * @see #setRangeAxis(ValueAxis) */ public ValueAxis getRangeAxis() { return getRangeAxis(0); } /** * Sets the range axis for the plot and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param axis the axis ({@code null} permitted). * * @see #getRangeAxis() * @see #setRangeAxis(int, ValueAxis) */ public void setRangeAxis(ValueAxis axis) { if (axis != null) { axis.setPlot(this); } // plot is likely registered as a listener with the existing axis... ValueAxis existing = getRangeAxis(); if (existing != null) { existing.removeChangeListener(this); } this.rangeAxes.put(0, axis); if (axis != null) { axis.configure(); axis.addChangeListener(this); } fireChangeEvent(); } /** * Returns the location of the primary range axis. * * @return The location (never {@code null}). * * @see #setRangeAxisLocation(AxisLocation) */ public AxisLocation getRangeAxisLocation() { return (AxisLocation) this.rangeAxisLocations.get(0); } /** * Sets the location of the primary range axis and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param location the location ({@code null} not permitted). * * @see #getRangeAxisLocation() */ public void setRangeAxisLocation(AxisLocation location) { // delegate... setRangeAxisLocation(0, location, true); } /** * Sets the location of the primary range axis and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param location the location ({@code null} not permitted). * @param notify notify listeners? * * @see #getRangeAxisLocation() */ public void setRangeAxisLocation(AxisLocation location, boolean notify) { // delegate... setRangeAxisLocation(0, location, notify); } /** * Returns the edge for the primary range axis. * * @return The range axis edge. * * @see #getRangeAxisLocation() * @see #getOrientation() */ public RectangleEdge getRangeAxisEdge() { return Plot.resolveRangeAxisLocation(getRangeAxisLocation(), this.orientation); } /** * Returns the range axis with the specified index, or {@code null} if * there is no axis with that index. * * @param index the axis index (must be &gt;= 0). * * @return The axis ({@code null} possible). * * @see #setRangeAxis(int, ValueAxis) */ public ValueAxis getRangeAxis(int index) { ValueAxis result = this.rangeAxes.get(index); if (result == null) { Plot parent = getParent(); if (parent instanceof XYPlot) { XYPlot xy = (XYPlot) parent; result = xy.getRangeAxis(index); } } return result; } /** * Sets a range axis and sends a {@link PlotChangeEvent} to all registered * listeners. * * @param index the axis index. * @param axis the axis ({@code null} permitted). * * @see #getRangeAxis(int) */ public void setRangeAxis(int index, ValueAxis axis) { setRangeAxis(index, axis, true); } /** * Sets a range axis and, if requested, sends a {@link PlotChangeEvent} to * all registered listeners. * * @param index the axis index. * @param axis the axis ({@code null} permitted). * @param notify notify listeners? * * @see #getRangeAxis(int) */ public void setRangeAxis(int index, ValueAxis axis, boolean notify) { ValueAxis existing = getRangeAxis(index); if (existing != null) { existing.removeChangeListener(this); } if (axis != null) { axis.setPlot(this); } this.rangeAxes.put(index, axis); if (axis != null) { axis.configure(); axis.addChangeListener(this); } if (notify) { fireChangeEvent(); } } /** * Sets the range axes for this plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param axes the axes ({@code null} not permitted). * * @see #setDomainAxes(ValueAxis[]) */ public void setRangeAxes(ValueAxis[] axes) { for (int i = 0; i < axes.length; i++) { setRangeAxis(i, axes[i], false); } fireChangeEvent(); } /** * Returns the number of range axes. * * @return The axis count. * * @see #getDomainAxisCount() */ public int getRangeAxisCount() { return this.rangeAxes.size(); } /** * Clears the range axes from the plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @see #clearDomainAxes() */ public void clearRangeAxes() { for (ValueAxis axis: this.rangeAxes.values()) { if (axis != null) { axis.removeChangeListener(this); } } this.rangeAxes.clear(); fireChangeEvent(); } /** * Configures the range axes. * * @see #configureDomainAxes() */ public void configureRangeAxes() { for (ValueAxis axis: this.rangeAxes.values()) { if (axis != null) { axis.configure(); } } } /** * Returns the location for a range axis. If this hasn't been set * explicitly, the method returns the location that is opposite to the * primary range axis location. * * @param index the axis index (must be &gt;= 0). * * @return The location (never {@code null}). * * @see #setRangeAxisLocation(int, AxisLocation) */ public AxisLocation getRangeAxisLocation(int index) { AxisLocation result = this.rangeAxisLocations.get(index); if (result == null) { result = AxisLocation.getOpposite(getRangeAxisLocation()); } return result; } /** * Sets the location for a range axis and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param index the axis index. * @param location the location ({@code null} permitted). * * @see #getRangeAxisLocation(int) */ public void setRangeAxisLocation(int index, AxisLocation location) { // delegate... setRangeAxisLocation(index, location, true); } /** * Sets the axis location for a domain axis and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the axis index. * @param location the location ({@code null} not permitted for * index 0). * @param notify notify listeners? * * @since 1.0.5 * * @see #getRangeAxisLocation(int) * @see #setDomainAxisLocation(int, AxisLocation, boolean) */ public void setRangeAxisLocation(int index, AxisLocation location, boolean notify) { if (index == 0 && location == null) { throw new IllegalArgumentException( "Null 'location' for index 0 not permitted."); } this.rangeAxisLocations.put(index, location); if (notify) { fireChangeEvent(); } } /** * Returns the edge for a range axis. * * @param index the axis index. * * @return The edge. * * @see #getRangeAxisLocation(int) * @see #getOrientation() */ public RectangleEdge getRangeAxisEdge(int index) { AxisLocation location = getRangeAxisLocation(index); return Plot.resolveRangeAxisLocation(location, this.orientation); } /** * Returns the primary dataset for the plot. * * @return The primary dataset (possibly {@code null}). * * @see #getDataset(int) * @see #setDataset(XYDataset) */ public XYDataset getDataset() { return getDataset(0); } /** * Returns the dataset with the specified index, or {@code null} if there * is no dataset with that index. * * @param index the dataset index (must be &gt;= 0). * * @return The dataset (possibly {@code null}). * * @see #setDataset(int, XYDataset) */ public XYDataset getDataset(int index) { return (XYDataset) this.datasets.get(index); } /** * Sets the primary dataset for the plot, replacing the existing dataset if * there is one. * * @param dataset the dataset ({@code null} permitted). * * @see #getDataset() * @see #setDataset(int, XYDataset) */ public void setDataset(XYDataset dataset) { setDataset(0, dataset); } /** * Sets a dataset for the plot and sends a change event to all registered * listeners. * * @param index the dataset index (must be &gt;= 0). * @param dataset the dataset ({@code null} permitted). * * @see #getDataset(int) */ public void setDataset(int index, XYDataset dataset) { XYDataset existing = getDataset(index); if (existing != null) { existing.removeChangeListener(this); } this.datasets.put(index, dataset); if (dataset != null) { dataset.addChangeListener(this); } // send a dataset change event to self... DatasetChangeEvent event = new DatasetChangeEvent(this, dataset); datasetChanged(event); } /** * Returns the number of datasets. * * @return The number of datasets. */ public int getDatasetCount() { return this.datasets.size(); } /** * Returns the index of the specified dataset, or {@code -1} if the * dataset does not belong to the plot. * * @param dataset the dataset ({@code null} not permitted). * * @return The index or -1. */ public int indexOf(XYDataset dataset) { for (Map.Entry<Integer, XYDataset> entry: this.datasets.entrySet()) { if (dataset == entry.getValue()) { return entry.getKey(); } } return -1; } /** * Maps a dataset to a particular domain axis. All data will be plotted * against axis zero by default, no mapping is required for this case. * * @param index the dataset index (zero-based). * @param axisIndex the axis index. * * @see #mapDatasetToRangeAxis(int, int) */ public void mapDatasetToDomainAxis(int index, int axisIndex) { List axisIndices = new java.util.ArrayList(1); axisIndices.add(new Integer(axisIndex)); mapDatasetToDomainAxes(index, axisIndices); } /** * Maps the specified dataset to the axes in the list. Note that the * conversion of data values into Java2D space is always performed using * the first axis in the list. * * @param index the dataset index (zero-based). * @param axisIndices the axis indices ({@code null} permitted). * * @since 1.0.12 */ public void mapDatasetToDomainAxes(int index, List axisIndices) { ParamChecks.requireNonNegative(index, "index"); checkAxisIndices(axisIndices); Integer key = new Integer(index); this.datasetToDomainAxesMap.put(key, new ArrayList(axisIndices)); // fake a dataset change event to update axes... datasetChanged(new DatasetChangeEvent(this, getDataset(index))); } /** * Maps a dataset to a particular range axis. All data will be plotted * against axis zero by default, no mapping is required for this case. * * @param index the dataset index (zero-based). * @param axisIndex the axis index. * * @see #mapDatasetToDomainAxis(int, int) */ public void mapDatasetToRangeAxis(int index, int axisIndex) { List axisIndices = new java.util.ArrayList(1); axisIndices.add(new Integer(axisIndex)); mapDatasetToRangeAxes(index, axisIndices); } /** * Maps the specified dataset to the axes in the list. Note that the * conversion of data values into Java2D space is always performed using * the first axis in the list. * * @param index the dataset index (zero-based). * @param axisIndices the axis indices ({@code null} permitted). * * @since 1.0.12 */ public void mapDatasetToRangeAxes(int index, List axisIndices) { ParamChecks.requireNonNegative(index, "index"); checkAxisIndices(axisIndices); Integer key = new Integer(index); this.datasetToRangeAxesMap.put(key, new ArrayList(axisIndices)); // fake a dataset change event to update axes... datasetChanged(new DatasetChangeEvent(this, getDataset(index))); } /** * This method is used to perform argument checking on the list of * axis indices passed to mapDatasetToDomainAxes() and * mapDatasetToRangeAxes(). * * @param indices the list of indices ({@code null} permitted). */ private void checkAxisIndices(List<Integer> indices) { // axisIndices can be: // 1. null; // 2. non-empty, containing only Integer objects that are unique. if (indices == null) { return; } int count = indices.size(); if (count == 0) { throw new IllegalArgumentException("Empty list not permitted."); } Set<Integer> set = new HashSet<Integer>(); for (Integer item : indices) { if (set.contains(item)) { throw new IllegalArgumentException("Indices must be unique."); } set.add(item); } } /** * Returns the number of renderer slots for this plot. * * @return The number of renderer slots. * * @since 1.0.11 */ public int getRendererCount() { return this.renderers.size(); } /** * Returns the renderer for the primary dataset. * * @return The item renderer (possibly {@code null}). * * @see #setRenderer(XYItemRenderer) */ public XYItemRenderer getRenderer() { return getRenderer(0); } /** * Returns the renderer with the specified index, or {@code null}. * * @param index the renderer index (must be &gt;= 0). * * @return The renderer (possibly {@code null}). * * @see #setRenderer(int, XYItemRenderer) */ public XYItemRenderer getRenderer(int index) { return (XYItemRenderer) this.renderers.get(index); } /** * Sets the renderer for the primary dataset and sends a change event to * all registered listeners. If the renderer is set to {@code null}, * no data will be displayed. * * @param renderer the renderer ({@code null} permitted). * * @see #getRenderer() */ public void setRenderer(XYItemRenderer renderer) { setRenderer(0, renderer); } /** * Sets the renderer for the dataset with the specified index and sends a * change event to all registered listeners. Note that each dataset should * have its own renderer, you should not use one renderer for multiple * datasets. * * @param index the index (must be &gt;= 0). * @param renderer the renderer. * * @see #getRenderer(int) */ public void setRenderer(int index, XYItemRenderer renderer) { setRenderer(index, renderer, true); } /** * Sets the renderer for the dataset with the specified index and, if * requested, sends a change event to all registered listeners. Note that * each dataset should have its own renderer, you should not use one * renderer for multiple datasets. * * @param index the index (must be &gt;= 0). * @param renderer the renderer. * @param notify notify listeners? * * @see #getRenderer(int) */ public void setRenderer(int index, XYItemRenderer renderer, boolean notify) { XYItemRenderer existing = getRenderer(index); if (existing != null) { existing.removeChangeListener(this); } this.renderers.put(index, renderer); if (renderer != null) { renderer.setPlot(this); renderer.addChangeListener(this); } configureDomainAxes(); configureRangeAxes(); if (notify) { fireChangeEvent(); } } /** * Sets the renderers for this plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param renderers the renderers ({@code null} not permitted). */ public void setRenderers(XYItemRenderer[] renderers) { for (int i = 0; i < renderers.length; i++) { setRenderer(i, renderers[i], false); } fireChangeEvent(); } /** * Returns the dataset rendering order. * * @return The order (never {@code null}). * * @see #setDatasetRenderingOrder(DatasetRenderingOrder) */ public DatasetRenderingOrder getDatasetRenderingOrder() { return this.datasetRenderingOrder; } /** * Sets the rendering order and sends a {@link PlotChangeEvent} to all * registered listeners. By default, the plot renders the primary dataset * last (so that the primary dataset overlays the secondary datasets). * You can reverse this if you want to. * * @param order the rendering order ({@code null} not permitted). * * @see #getDatasetRenderingOrder() */ public void setDatasetRenderingOrder(DatasetRenderingOrder order) { ParamChecks.nullNotPermitted(order, "order"); this.datasetRenderingOrder = order; fireChangeEvent(); } /** * Returns the series rendering order. * * @return the order (never {@code null}). * * @see #setSeriesRenderingOrder(SeriesRenderingOrder) */ public SeriesRenderingOrder getSeriesRenderingOrder() { return this.seriesRenderingOrder; } /** * Sets the series order and sends a {@link PlotChangeEvent} to all * registered listeners. By default, the plot renders the primary series * last (so that the primary series appears to be on top). * You can reverse this if you want to. * * @param order the rendering order ({@code null} not permitted). * * @see #getSeriesRenderingOrder() */ public void setSeriesRenderingOrder(SeriesRenderingOrder order) { ParamChecks.nullNotPermitted(order, "order"); this.seriesRenderingOrder = order; fireChangeEvent(); } /** * Returns the index of the specified renderer, or {@code -1} if the * renderer is not assigned to this plot. * * @param renderer the renderer ({@code null} permitted). * * @return The renderer index. */ public int getIndexOf(XYItemRenderer renderer) { for (Map.Entry<Integer, XYItemRenderer> entry : this.renderers.entrySet()) { if (entry.getValue() == renderer) { return entry.getKey(); } } return -1; } /** * Returns the renderer for the specified dataset (this is either the * renderer with the same index as the dataset or, if there isn't a * renderer with the same index, the default renderer). If the dataset * does not belong to the plot, this method will return {@code null}. * * @param dataset the dataset ({@code null} permitted). * * @return The renderer (possibly {@code null}). */ public XYItemRenderer getRendererForDataset(XYDataset dataset) { int datasetIndex = indexOf(dataset); if (datasetIndex < 0) { return null; } XYItemRenderer result = this.renderers.get(datasetIndex); if (result == null) { result = getRenderer(); } return result; } /** * Returns the weight for this plot when it is used as a subplot within a * combined plot. * * @return The weight. * * @see #setWeight(int) */ public int getWeight() { return this.weight; } /** * Sets the weight for the plot and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param weight the weight. * * @see #getWeight() */ public void setWeight(int weight) { this.weight = weight; fireChangeEvent(); } /** * Returns {@code true} if the domain gridlines are visible, and * {@code false} otherwise. * * @return {@code true} or {@code false}. * * @see #setDomainGridlinesVisible(boolean) */ public boolean isDomainGridlinesVisible() { return this.domainGridlinesVisible; } /** * Sets the flag that controls whether or not the domain grid-lines are * visible. * <p> * If the flag value is changed, a {@link PlotChangeEvent} is sent to all * registered listeners. * * @param visible the new value of the flag. * * @see #isDomainGridlinesVisible() */ public void setDomainGridlinesVisible(boolean visible) { if (this.domainGridlinesVisible != visible) { this.domainGridlinesVisible = visible; fireChangeEvent(); } } /** * Returns {@code true} if the domain minor gridlines are visible, and * {@code false} otherwise. * * @return {@code true} or {@code false}. * * @see #setDomainMinorGridlinesVisible(boolean) * * @since 1.0.12 */ public boolean isDomainMinorGridlinesVisible() { return this.domainMinorGridlinesVisible; } /** * Sets the flag that controls whether or not the domain minor grid-lines * are visible. * <p> * If the flag value is changed, a {@link PlotChangeEvent} is sent to all * registered listeners. * * @param visible the new value of the flag. * * @see #isDomainMinorGridlinesVisible() * * @since 1.0.12 */ public void setDomainMinorGridlinesVisible(boolean visible) { if (this.domainMinorGridlinesVisible != visible) { this.domainMinorGridlinesVisible = visible; fireChangeEvent(); } } /** * Returns the stroke for the grid-lines (if any) plotted against the * domain axis. * * @return The stroke (never {@code null}). * * @see #setDomainGridlineStroke(Stroke) */ public Stroke getDomainGridlineStroke() { return this.domainGridlineStroke; } public void setDomainGridlineStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.domainGridlineStroke = stroke; fireChangeEvent(); } /** * Returns the stroke for the minor grid-lines (if any) plotted against the * domain axis. * * @return The stroke (never {@code null}). * * @see #setDomainMinorGridlineStroke(Stroke) * * @since 1.0.12 */ public Stroke getDomainMinorGridlineStroke() { return this.domainMinorGridlineStroke; } public void setDomainMinorGridlineStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.domainMinorGridlineStroke = stroke; fireChangeEvent(); } /** * Returns the paint for the grid lines (if any) plotted against the domain * axis. * * @return The paint (never {@code null}). * * @see #setDomainGridlinePaint(Paint) */ public Paint getDomainGridlinePaint() { return this.domainGridlinePaint; } public void setDomainGridlinePaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.domainGridlinePaint = paint; fireChangeEvent(); } /** * Returns the paint for the minor grid lines (if any) plotted against the * domain axis. * * @return The paint (never {@code null}). * * @see #setDomainMinorGridlinePaint(Paint) * * @since 1.0.12 */ public Paint getDomainMinorGridlinePaint() { return this.domainMinorGridlinePaint; } public void setDomainMinorGridlinePaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.domainMinorGridlinePaint = paint; fireChangeEvent(); } /** * Returns {@code true} if the range axis grid is visible, and * {@code false} otherwise. * * @return A boolean. * * @see #setRangeGridlinesVisible(boolean) */ public boolean isRangeGridlinesVisible() { return this.rangeGridlinesVisible; } /** * Sets the flag that controls whether or not the range axis grid lines * are visible. * <p> * If the flag value is changed, a {@link PlotChangeEvent} is sent to all * registered listeners. * * @param visible the new value of the flag. * * @see #isRangeGridlinesVisible() */ public void setRangeGridlinesVisible(boolean visible) { if (this.rangeGridlinesVisible != visible) { this.rangeGridlinesVisible = visible; fireChangeEvent(); } } /** * Returns the stroke for the grid lines (if any) plotted against the * range axis. * * @return The stroke (never {@code null}). * * @see #setRangeGridlineStroke(Stroke) */ public Stroke getRangeGridlineStroke() { return this.rangeGridlineStroke; } /** * Sets the stroke for the grid lines plotted against the range axis, * and sends a {@link PlotChangeEvent} to all registered listeners. * * @param stroke the stroke ({@code null} not permitted). * * @see #getRangeGridlineStroke() */ public void setRangeGridlineStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.rangeGridlineStroke = stroke; fireChangeEvent(); } /** * Returns the paint for the grid lines (if any) plotted against the range * axis. * * @return The paint (never {@code null}). * * @see #setRangeGridlinePaint(Paint) */ public Paint getRangeGridlinePaint() { return this.rangeGridlinePaint; } /** * Sets the paint for the grid lines plotted against the range axis and * sends a {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint ({@code null} not permitted). * * @see #getRangeGridlinePaint() */ public void setRangeGridlinePaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.rangeGridlinePaint = paint; fireChangeEvent(); } /** * Returns {@code true} if the range axis minor grid is visible, and * {@code false} otherwise. * * @return A boolean. * * @see #setRangeMinorGridlinesVisible(boolean) * * @since 1.0.12 */ public boolean isRangeMinorGridlinesVisible() { return this.rangeMinorGridlinesVisible; } /** * Sets the flag that controls whether or not the range axis minor grid * lines are visible. * <p> * If the flag value is changed, a {@link PlotChangeEvent} is sent to all * registered listeners. * * @param visible the new value of the flag. * * @see #isRangeMinorGridlinesVisible() * * @since 1.0.12 */ public void setRangeMinorGridlinesVisible(boolean visible) { if (this.rangeMinorGridlinesVisible != visible) { this.rangeMinorGridlinesVisible = visible; fireChangeEvent(); } } /** * Returns the stroke for the minor grid lines (if any) plotted against the * range axis. * * @return The stroke (never {@code null}). * * @see #setRangeMinorGridlineStroke(Stroke) * * @since 1.0.12 */ public Stroke getRangeMinorGridlineStroke() { return this.rangeMinorGridlineStroke; } /** * Sets the stroke for the minor grid lines plotted against the range axis, * and sends a {@link PlotChangeEvent} to all registered listeners. * * @param stroke the stroke ({@code null} not permitted). * * @see #getRangeMinorGridlineStroke() * * @since 1.0.12 */ public void setRangeMinorGridlineStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.rangeMinorGridlineStroke = stroke; fireChangeEvent(); } /** * Returns the paint for the minor grid lines (if any) plotted against the * range axis. * * @return The paint (never {@code null}). * * @see #setRangeMinorGridlinePaint(Paint) * * @since 1.0.12 */ public Paint getRangeMinorGridlinePaint() { return this.rangeMinorGridlinePaint; } /** * Sets the paint for the minor grid lines plotted against the range axis * and sends a {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint ({@code null} not permitted). * * @see #getRangeMinorGridlinePaint() * * @since 1.0.12 */ public void setRangeMinorGridlinePaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.rangeMinorGridlinePaint = paint; fireChangeEvent(); } /** * Returns a flag that controls whether or not a zero baseline is * displayed for the domain axis. * * @return A boolean. * * @since 1.0.5 * * @see #setDomainZeroBaselineVisible(boolean) */ public boolean isDomainZeroBaselineVisible() { return this.domainZeroBaselineVisible; } /** * Sets the flag that controls whether or not the zero baseline is * displayed for the domain axis, and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param visible the flag. * * @since 1.0.5 * * @see #isDomainZeroBaselineVisible() */ public void setDomainZeroBaselineVisible(boolean visible) { this.domainZeroBaselineVisible = visible; fireChangeEvent(); } /** * Returns the stroke used for the zero baseline against the domain axis. * * @return The stroke (never {@code null}). * * @since 1.0.5 * * @see #setDomainZeroBaselineStroke(Stroke) */ public Stroke getDomainZeroBaselineStroke() { return this.domainZeroBaselineStroke; } /** * Sets the stroke for the zero baseline for the domain axis, * and sends a {@link PlotChangeEvent} to all registered listeners. * * @param stroke the stroke ({@code null} not permitted). * * @since 1.0.5 * * @see #getRangeZeroBaselineStroke() */ public void setDomainZeroBaselineStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.domainZeroBaselineStroke = stroke; fireChangeEvent(); } /** * Returns the paint for the zero baseline (if any) plotted against the * domain axis. * * @since 1.0.5 * * @return The paint (never {@code null}). * * @see #setDomainZeroBaselinePaint(Paint) */ public Paint getDomainZeroBaselinePaint() { return this.domainZeroBaselinePaint; } /** * Sets the paint for the zero baseline plotted against the domain axis and * sends a {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint ({@code null} not permitted). * * @since 1.0.5 * * @see #getDomainZeroBaselinePaint() */ public void setDomainZeroBaselinePaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.domainZeroBaselinePaint = paint; fireChangeEvent(); } /** * Returns a flag that controls whether or not a zero baseline is * displayed for the range axis. * * @return A boolean. * * @see #setRangeZeroBaselineVisible(boolean) */ public boolean isRangeZeroBaselineVisible() { return this.rangeZeroBaselineVisible; } /** * Sets the flag that controls whether or not the zero baseline is * displayed for the range axis, and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param visible the flag. * * @see #isRangeZeroBaselineVisible() */ public void setRangeZeroBaselineVisible(boolean visible) { this.rangeZeroBaselineVisible = visible; fireChangeEvent(); } /** * Returns the stroke used for the zero baseline against the range axis. * * @return The stroke (never {@code null}). * * @see #setRangeZeroBaselineStroke(Stroke) */ public Stroke getRangeZeroBaselineStroke() { return this.rangeZeroBaselineStroke; } /** * Sets the stroke for the zero baseline for the range axis, * and sends a {@link PlotChangeEvent} to all registered listeners. * * @param stroke the stroke ({@code null} not permitted). * * @see #getRangeZeroBaselineStroke() */ public void setRangeZeroBaselineStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.rangeZeroBaselineStroke = stroke; fireChangeEvent(); } /** * Returns the paint for the zero baseline (if any) plotted against the * range axis. * * @return The paint (never {@code null}). * * @see #setRangeZeroBaselinePaint(Paint) */ public Paint getRangeZeroBaselinePaint() { return this.rangeZeroBaselinePaint; } /** * Sets the paint for the zero baseline plotted against the range axis and * sends a {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint ({@code null} not permitted). * * @see #getRangeZeroBaselinePaint() */ public void setRangeZeroBaselinePaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.rangeZeroBaselinePaint = paint; fireChangeEvent(); } /** * Returns the paint used for the domain tick bands. If this is * {@code null}, no tick bands will be drawn. * * @return The paint (possibly {@code null}). * * @see #setDomainTickBandPaint(Paint) */ public Paint getDomainTickBandPaint() { return this.domainTickBandPaint; } /** * Sets the paint for the domain tick bands. * * @param paint the paint ({@code null} permitted). * * @see #getDomainTickBandPaint() */ public void setDomainTickBandPaint(Paint paint) { this.domainTickBandPaint = paint; fireChangeEvent(); } /** * Returns the paint used for the range tick bands. If this is * {@code null}, no tick bands will be drawn. * * @return The paint (possibly {@code null}). * * @see #setRangeTickBandPaint(Paint) */ public Paint getRangeTickBandPaint() { return this.rangeTickBandPaint; } /** * Sets the paint for the range tick bands. * * @param paint the paint ({@code null} permitted). * * @see #getRangeTickBandPaint() */ public void setRangeTickBandPaint(Paint paint) { this.rangeTickBandPaint = paint; fireChangeEvent(); } /** * Returns the origin for the quadrants that can be displayed on the plot. * This defaults to (0, 0). * * @return The origin point (never {@code null}). * * @see #setQuadrantOrigin(Point2D) */ public Point2D getQuadrantOrigin() { return this.quadrantOrigin; } /** * Sets the quadrant origin and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param origin the origin ({@code null} not permitted). * * @see #getQuadrantOrigin() */ public void setQuadrantOrigin(Point2D origin) { ParamChecks.nullNotPermitted(origin, "origin"); this.quadrantOrigin = origin; fireChangeEvent(); } /** * Returns the paint used for the specified quadrant. * * @param index the quadrant index (0-3). * * @return The paint (possibly {@code null}). * * @see #setQuadrantPaint(int, Paint) */ public Paint getQuadrantPaint(int index) { if (index < 0 || index > 3) { throw new IllegalArgumentException("The index value (" + index + ") should be in the range 0 to 3."); } return this.quadrantPaint[index]; } /** * Sets the paint used for the specified quadrant and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the quadrant index (0-3). * @param paint the paint ({@code null} permitted). * * @see #getQuadrantPaint(int) */ public void setQuadrantPaint(int index, Paint paint) { if (index < 0 || index > 3) { throw new IllegalArgumentException("The index value (" + index + ") should be in the range 0 to 3."); } this.quadrantPaint[index] = paint; fireChangeEvent(); } /** * Adds a marker for the domain axis and sends a {@link PlotChangeEvent} * to all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to the domain axis, however this is entirely up to the renderer. * * @param marker the marker ({@code null} not permitted). * * @see #addDomainMarker(Marker, Layer) * @see #clearDomainMarkers() */ public void addDomainMarker(Marker marker) { // defer argument checking... addDomainMarker(marker, Layer.FOREGROUND); } /** * Adds a marker for the domain axis in the specified layer and sends a * {@link PlotChangeEvent} to all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to the domain axis, however this is entirely up to the renderer. * * @param marker the marker ({@code null} not permitted). * @param layer the layer (foreground or background). * * @see #addDomainMarker(int, Marker, Layer) */ public void addDomainMarker(Marker marker, Layer layer) { addDomainMarker(0, marker, layer); } /** * Clears all the (foreground and background) domain markers and sends a * {@link PlotChangeEvent} to all registered listeners. * * @see #addDomainMarker(int, Marker, Layer) */ public void clearDomainMarkers() { if (this.backgroundDomainMarkers != null) { Set<Integer> keys = this.backgroundDomainMarkers.keySet(); for (Integer key : keys) { clearDomainMarkers(key); } this.backgroundDomainMarkers.clear(); } if (this.foregroundDomainMarkers != null) { Set<Integer> keys = this.foregroundDomainMarkers.keySet(); for (Integer key : keys) { clearDomainMarkers(key); } this.foregroundDomainMarkers.clear(); } fireChangeEvent(); } /** * Clears the (foreground and background) domain markers for a particular * renderer and sends a {@link PlotChangeEvent} to all registered listeners. * * @param index the renderer index. * * @see #clearRangeMarkers(int) */ public void clearDomainMarkers(int index) { Integer key = new Integer(index); if (this.backgroundDomainMarkers != null) { Collection markers = (Collection) this.backgroundDomainMarkers.get(key); if (markers != null) { Iterator iterator = markers.iterator(); while (iterator.hasNext()) { Marker m = (Marker) iterator.next(); m.removeChangeListener(this); } markers.clear(); } } if (this.foregroundRangeMarkers != null) { Collection markers = (Collection) this.foregroundDomainMarkers.get(key); if (markers != null) { Iterator iterator = markers.iterator(); while (iterator.hasNext()) { Marker m = (Marker) iterator.next(); m.removeChangeListener(this); } markers.clear(); } } fireChangeEvent(); } /** * Adds a marker for a specific dataset/renderer and sends a * {@link PlotChangeEvent} to all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to the domain axis (that the renderer is mapped to), however this is * entirely up to the renderer. * * @param index the dataset/renderer index. * @param marker the marker. * @param layer the layer (foreground or background). * * @see #clearDomainMarkers(int) * @see #addRangeMarker(int, Marker, Layer) */ public void addDomainMarker(int index, Marker marker, Layer layer) { addDomainMarker(index, marker, layer, true); } /** * Adds a marker for a specific dataset/renderer and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to the domain axis (that the renderer is mapped to), however this is * entirely up to the renderer. * * @param index the dataset/renderer index. * @param marker the marker. * @param layer the layer (foreground or background). * @param notify notify listeners? * * @since 1.0.10 */ public void addDomainMarker(int index, Marker marker, Layer layer, boolean notify) { ParamChecks.nullNotPermitted(marker, "marker"); ParamChecks.nullNotPermitted(layer, "layer"); Collection markers; if (layer == Layer.FOREGROUND) { markers = (Collection) this.foregroundDomainMarkers.get( new Integer(index)); if (markers == null) { markers = new java.util.ArrayList(); this.foregroundDomainMarkers.put(new Integer(index), markers); } markers.add(marker); } else if (layer == Layer.BACKGROUND) { markers = (Collection) this.backgroundDomainMarkers.get( new Integer(index)); if (markers == null) { markers = new java.util.ArrayList(); this.backgroundDomainMarkers.put(new Integer(index), markers); } markers.add(marker); } marker.addChangeListener(this); if (notify) { fireChangeEvent(); } } /** * Removes a marker for the domain axis and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param marker the marker. * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.7 */ public boolean removeDomainMarker(Marker marker) { return removeDomainMarker(marker, Layer.FOREGROUND); } /** * Removes a marker for the domain axis in the specified layer and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param marker the marker ({@code null} not permitted). * @param layer the layer (foreground or background). * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.7 */ public boolean removeDomainMarker(Marker marker, Layer layer) { return removeDomainMarker(0, marker, layer); } /** * Removes a marker for a specific dataset/renderer and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the dataset/renderer index. * @param marker the marker. * @param layer the layer (foreground or background). * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.7 */ public boolean removeDomainMarker(int index, Marker marker, Layer layer) { return removeDomainMarker(index, marker, layer, true); } /** * Removes a marker for a specific dataset/renderer and, if requested, * sends a {@link PlotChangeEvent} to all registered listeners. * * @param index the dataset/renderer index. * @param marker the marker. * @param layer the layer (foreground or background). * @param notify notify listeners? * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.10 */ public boolean removeDomainMarker(int index, Marker marker, Layer layer, boolean notify) { ArrayList markers; if (layer == Layer.FOREGROUND) { markers = (ArrayList) this.foregroundDomainMarkers.get( new Integer(index)); } else { markers = (ArrayList) this.backgroundDomainMarkers.get( new Integer(index)); } if (markers == null) { return false; } boolean removed = markers.remove(marker); if (removed && notify) { fireChangeEvent(); } return removed; } /** * Adds a marker for the range axis and sends a {@link PlotChangeEvent} to * all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to the range axis, however this is entirely up to the renderer. * * @param marker the marker ({@code null} not permitted). * * @see #addRangeMarker(Marker, Layer) */ public void addRangeMarker(Marker marker) { addRangeMarker(marker, Layer.FOREGROUND); } /** * Adds a marker for the range axis in the specified layer and sends a * {@link PlotChangeEvent} to all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to the range axis, however this is entirely up to the renderer. * * @param marker the marker ({@code null} not permitted). * @param layer the layer (foreground or background). * * @see #addRangeMarker(int, Marker, Layer) */ public void addRangeMarker(Marker marker, Layer layer) { addRangeMarker(0, marker, layer); } /** * Clears all the range markers and sends a {@link PlotChangeEvent} to all * registered listeners. * * @see #clearRangeMarkers() */ public void clearRangeMarkers() { if (this.backgroundRangeMarkers != null) { Set<Integer> keys = this.backgroundRangeMarkers.keySet(); for (Integer key : keys) { clearRangeMarkers(key); } this.backgroundRangeMarkers.clear(); } if (this.foregroundRangeMarkers != null) { Set<Integer> keys = this.foregroundRangeMarkers.keySet(); for (Integer key : keys) { clearRangeMarkers(key); } this.foregroundRangeMarkers.clear(); } fireChangeEvent(); } /** * Adds a marker for a specific dataset/renderer and sends a * {@link PlotChangeEvent} to all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to the range axis, however this is entirely up to the renderer. * * @param index the dataset/renderer index. * @param marker the marker. * @param layer the layer (foreground or background). * * @see #clearRangeMarkers(int) * @see #addDomainMarker(int, Marker, Layer) */ public void addRangeMarker(int index, Marker marker, Layer layer) { addRangeMarker(index, marker, layer, true); } /** * Adds a marker for a specific dataset/renderer and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to the range axis, however this is entirely up to the renderer. * * @param index the dataset/renderer index. * @param marker the marker. * @param layer the layer (foreground or background). * @param notify notify listeners? * * @since 1.0.10 */ public void addRangeMarker(int index, Marker marker, Layer layer, boolean notify) { Collection markers; if (layer == Layer.FOREGROUND) { markers = (Collection) this.foregroundRangeMarkers.get( new Integer(index)); if (markers == null) { markers = new java.util.ArrayList(); this.foregroundRangeMarkers.put(new Integer(index), markers); } markers.add(marker); } else if (layer == Layer.BACKGROUND) { markers = (Collection) this.backgroundRangeMarkers.get( new Integer(index)); if (markers == null) { markers = new java.util.ArrayList(); this.backgroundRangeMarkers.put(new Integer(index), markers); } markers.add(marker); } marker.addChangeListener(this); if (notify) { fireChangeEvent(); } } /** * Clears the (foreground and background) range markers for a particular * renderer. * * @param index the renderer index. */ public void clearRangeMarkers(int index) { Integer key = new Integer(index); if (this.backgroundRangeMarkers != null) { Collection markers = (Collection) this.backgroundRangeMarkers.get(key); if (markers != null) { Iterator iterator = markers.iterator(); while (iterator.hasNext()) { Marker m = (Marker) iterator.next(); m.removeChangeListener(this); } markers.clear(); } } if (this.foregroundRangeMarkers != null) { Collection markers = (Collection) this.foregroundRangeMarkers.get(key); if (markers != null) { Iterator iterator = markers.iterator(); while (iterator.hasNext()) { Marker m = (Marker) iterator.next(); m.removeChangeListener(this); } markers.clear(); } } fireChangeEvent(); } /** * Removes a marker for the range axis and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param marker the marker. * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.7 */ public boolean removeRangeMarker(Marker marker) { return removeRangeMarker(marker, Layer.FOREGROUND); } /** * Removes a marker for the range axis in the specified layer and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param marker the marker ({@code null} not permitted). * @param layer the layer (foreground or background). * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.7 */ public boolean removeRangeMarker(Marker marker, Layer layer) { return removeRangeMarker(0, marker, layer); } /** * Removes a marker for a specific dataset/renderer and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the dataset/renderer index. * @param marker the marker ({@code null} not permitted). * @param layer the layer (foreground or background). * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.7 */ public boolean removeRangeMarker(int index, Marker marker, Layer layer) { return removeRangeMarker(index, marker, layer, true); } /** * Removes a marker for a specific dataset/renderer and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the dataset/renderer index. * @param marker the marker ({@code null} not permitted). * @param layer the layer (foreground or background) ({@code null} not permitted). * @param notify notify listeners? * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.10 */ public boolean removeRangeMarker(int index, Marker marker, Layer layer, boolean notify) { ParamChecks.nullNotPermitted(marker, "marker"); ParamChecks.nullNotPermitted(layer, "layer"); List markers; if (layer == Layer.FOREGROUND) { markers = (List) this.foregroundRangeMarkers.get( new Integer(index)); } else { markers = (List) this.backgroundRangeMarkers.get( new Integer(index)); } if (markers == null) { return false; } boolean removed = markers.remove(marker); if (removed && notify) { fireChangeEvent(); } return removed; } /** * Adds an annotation to the plot and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param annotation the annotation ({@code null} not permitted). * * @see #getAnnotations() * @see #removeAnnotation(XYAnnotation) */ public void addAnnotation(XYAnnotation annotation) { addAnnotation(annotation, true); } /** * Adds an annotation to the plot and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param annotation the annotation ({@code null} not permitted). * @param notify notify listeners? * * @since 1.0.10 */ public void addAnnotation(XYAnnotation annotation, boolean notify) { ParamChecks.nullNotPermitted(annotation, "annotation"); this.annotations.add(annotation); annotation.addChangeListener(this); if (notify) { fireChangeEvent(); } } /** * Removes an annotation from the plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param annotation the annotation ({@code null} not permitted). * * @return A boolean (indicates whether or not the annotation was removed). * * @see #addAnnotation(XYAnnotation) * @see #getAnnotations() */ public boolean removeAnnotation(XYAnnotation annotation) { return removeAnnotation(annotation, true); } /** * Removes an annotation from the plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param annotation the annotation ({@code null} not permitted). * @param notify notify listeners? * * @return A boolean (indicates whether or not the annotation was removed). * * @since 1.0.10 */ public boolean removeAnnotation(XYAnnotation annotation, boolean notify) { ParamChecks.nullNotPermitted(annotation, "annotation"); boolean removed = this.annotations.remove(annotation); annotation.removeChangeListener(this); if (removed && notify) { fireChangeEvent(); } return removed; } /** * Returns the list of annotations. * * @return The list of annotations. * * @since 1.0.1 * * @see #addAnnotation(XYAnnotation) */ public List getAnnotations() { return new ArrayList(this.annotations); } /** * Clears all the annotations and sends a {@link PlotChangeEvent} to all * registered listeners. * * @see #addAnnotation(XYAnnotation) */ public void clearAnnotations() { for (XYAnnotation annotation : this.annotations) { annotation.removeChangeListener(this); } this.annotations.clear(); fireChangeEvent(); } /** * Returns the shadow generator for the plot, if any. * * @return The shadow generator (possibly {@code null}). * * @since 1.0.14 */ public ShadowGenerator getShadowGenerator() { return this.shadowGenerator; } /** * Sets the shadow generator for the plot and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param generator the generator ({@code null} permitted). * * @since 1.0.14 */ public void setShadowGenerator(ShadowGenerator generator) { this.shadowGenerator = generator; fireChangeEvent(); } /** * Calculates the space required for all the axes in the plot. * * @param g2 the graphics device. * @param plotArea the plot area. * * @return The required space. */ protected AxisSpace calculateAxisSpace(Graphics2D g2, Rectangle2D plotArea) { AxisSpace space = new AxisSpace(); space = calculateRangeAxisSpace(g2, plotArea, space); Rectangle2D revPlotArea = space.shrink(plotArea, null); space = calculateDomainAxisSpace(g2, revPlotArea, space); return space; } /** * Calculates the space required for the domain axis/axes. * * @param g2 the graphics device. * @param plotArea the plot area. * @param space a carrier for the result ({@code null} permitted). * * @return The required space. */ protected AxisSpace calculateDomainAxisSpace(Graphics2D g2, Rectangle2D plotArea, AxisSpace space) { if (space == null) { space = new AxisSpace(); } // reserve some space for the domain axis... if (this.fixedDomainAxisSpace != null) { if (this.orientation == PlotOrientation.HORIZONTAL) { space.ensureAtLeast(this.fixedDomainAxisSpace.getLeft(), RectangleEdge.LEFT); space.ensureAtLeast(this.fixedDomainAxisSpace.getRight(), RectangleEdge.RIGHT); } else if (this.orientation == PlotOrientation.VERTICAL) { space.ensureAtLeast(this.fixedDomainAxisSpace.getTop(), RectangleEdge.TOP); space.ensureAtLeast(this.fixedDomainAxisSpace.getBottom(), RectangleEdge.BOTTOM); } } else { // reserve space for the domain axes... for (ValueAxis axis: this.domainAxes.values()) { if (axis != null) { RectangleEdge edge = getDomainAxisEdge( findDomainAxisIndex(axis)); space = axis.reserveSpace(g2, this, plotArea, edge, space); } } } return space; } /** * Calculates the space required for the range axis/axes. * * @param g2 the graphics device. * @param plotArea the plot area. * @param space a carrier for the result ({@code null} permitted). * * @return The required space. */ protected AxisSpace calculateRangeAxisSpace(Graphics2D g2, Rectangle2D plotArea, AxisSpace space) { if (space == null) { space = new AxisSpace(); } // reserve some space for the range axis... if (this.fixedRangeAxisSpace != null) { if (this.orientation == PlotOrientation.HORIZONTAL) { space.ensureAtLeast(this.fixedRangeAxisSpace.getTop(), RectangleEdge.TOP); space.ensureAtLeast(this.fixedRangeAxisSpace.getBottom(), RectangleEdge.BOTTOM); } else if (this.orientation == PlotOrientation.VERTICAL) { space.ensureAtLeast(this.fixedRangeAxisSpace.getLeft(), RectangleEdge.LEFT); space.ensureAtLeast(this.fixedRangeAxisSpace.getRight(), RectangleEdge.RIGHT); } } else { // reserve space for the range axes... for (ValueAxis axis: this.rangeAxes.values()) { if (axis != null) { RectangleEdge edge = getRangeAxisEdge( findRangeAxisIndex(axis)); space = axis.reserveSpace(g2, this, plotArea, edge, space); } } } return space; } /** * Trims a rectangle to integer coordinates. * * @param rect the incoming rectangle. * * @return A rectangle with integer coordinates. */ private Rectangle integerise(Rectangle2D rect) { int x0 = (int) Math.ceil(rect.getMinX()); int y0 = (int) Math.ceil(rect.getMinY()); int x1 = (int) Math.floor(rect.getMaxX()); int y1 = (int) Math.floor(rect.getMaxY()); return new Rectangle(x0, y0, (x1 - x0), (y1 - y0)); } /** * Draws the plot within the specified area on a graphics device. * * @param g2 the graphics device. * @param area the plot area (in Java2D space). * @param anchor an anchor point in Java2D space ({@code null} * permitted). * @param parentState the state from the parent plot, if there is one * ({@code null} permitted). * @param info collects chart drawing information ({@code null} * permitted). */ @Override public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState, PlotRenderingInfo info) { // if the plot area is too small, just return... boolean b1 = (area.getWidth() <= MINIMUM_WIDTH_TO_DRAW); boolean b2 = (area.getHeight() <= MINIMUM_HEIGHT_TO_DRAW); if (b1 || b2) { return; } // record the plot area... if (info != null) { info.setPlotArea(area); } // adjust the drawing area for the plot insets (if any)... RectangleInsets insets = getInsets(); insets.trim(area); AxisSpace space = calculateAxisSpace(g2, area); Rectangle2D dataArea = space.shrink(area, null); this.axisOffset.trim(dataArea); dataArea = integerise(dataArea); if (dataArea.isEmpty()) { return; } createAndAddEntity((Rectangle2D) dataArea.clone(), info, null, null); if (info != null) { info.setDataArea(dataArea); } // draw the plot background and axes... drawBackground(g2, dataArea); Map axisStateMap = drawAxes(g2, area, dataArea, info); PlotOrientation orient = getOrientation(); // the anchor point is typically the point where the mouse last // clicked - the crosshairs will be driven off this point... if (anchor != null && !dataArea.contains(anchor)) { anchor = null; } CrosshairState crosshairState = new CrosshairState(); crosshairState.setCrosshairDistance(Double.POSITIVE_INFINITY); crosshairState.setAnchor(anchor); crosshairState.setAnchorX(Double.NaN); crosshairState.setAnchorY(Double.NaN); if (anchor != null) { ValueAxis domainAxis = getDomainAxis(); if (domainAxis != null) { double x; if (orient == PlotOrientation.VERTICAL) { x = domainAxis.java2DToValue(anchor.getX(), dataArea, getDomainAxisEdge()); } else { x = domainAxis.java2DToValue(anchor.getY(), dataArea, getDomainAxisEdge()); } crosshairState.setAnchorX(x); } ValueAxis rangeAxis = getRangeAxis(); if (rangeAxis != null) { double y; if (orient == PlotOrientation.VERTICAL) { y = rangeAxis.java2DToValue(anchor.getY(), dataArea, getRangeAxisEdge()); } else { y = rangeAxis.java2DToValue(anchor.getX(), dataArea, getRangeAxisEdge()); } crosshairState.setAnchorY(y); } } crosshairState.setCrosshairX(getDomainCrosshairValue()); crosshairState.setCrosshairY(getRangeCrosshairValue()); Shape originalClip = g2.getClip(); Composite originalComposite = g2.getComposite(); g2.clip(dataArea); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getForegroundAlpha())); AxisState domainAxisState = (AxisState) axisStateMap.get( getDomainAxis()); if (domainAxisState == null) { if (parentState != null) { domainAxisState = (AxisState) parentState.getSharedAxisStates() .get(getDomainAxis()); } } AxisState rangeAxisState = (AxisState) axisStateMap.get(getRangeAxis()); if (rangeAxisState == null) { if (parentState != null) { rangeAxisState = (AxisState) parentState.getSharedAxisStates() .get(getRangeAxis()); } } if (domainAxisState != null) { drawDomainTickBands(g2, dataArea, domainAxisState.getTicks()); } if (rangeAxisState != null) { drawRangeTickBands(g2, dataArea, rangeAxisState.getTicks()); } if (domainAxisState != null) { drawDomainGridlines(g2, dataArea, domainAxisState.getTicks()); drawZeroDomainBaseline(g2, dataArea); } if (rangeAxisState != null) { drawRangeGridlines(g2, dataArea, rangeAxisState.getTicks()); drawZeroRangeBaseline(g2, dataArea); } Graphics2D savedG2 = g2; BufferedImage dataImage = null; boolean suppressShadow = Boolean.TRUE.equals(g2.getRenderingHint( JFreeChart.KEY_SUPPRESS_SHADOW_GENERATION)); if (this.shadowGenerator != null && !suppressShadow) { dataImage = new BufferedImage((int) dataArea.getWidth(), (int)dataArea.getHeight(), BufferedImage.TYPE_INT_ARGB); g2 = dataImage.createGraphics(); g2.translate(-dataArea.getX(), -dataArea.getY()); g2.setRenderingHints(savedG2.getRenderingHints()); } // draw the markers that are associated with a specific dataset... for (XYDataset dataset: this.datasets.values()) { int datasetIndex = indexOf(dataset); drawDomainMarkers(g2, dataArea, datasetIndex, Layer.BACKGROUND); } for (XYDataset dataset: this.datasets.values()) { int datasetIndex = indexOf(dataset); drawRangeMarkers(g2, dataArea, datasetIndex, Layer.BACKGROUND); } // now draw annotations and render data items... boolean foundData = false; DatasetRenderingOrder order = getDatasetRenderingOrder(); List<Integer> rendererIndices = getRendererIndices(order); List<Integer> datasetIndices = getDatasetIndices(order); // draw background annotations for (int i : rendererIndices) { XYItemRenderer renderer = getRenderer(i); if (renderer != null) { ValueAxis domainAxis = getDomainAxisForDataset(i); ValueAxis rangeAxis = getRangeAxisForDataset(i); renderer.drawAnnotations(g2, dataArea, domainAxis, rangeAxis, Layer.BACKGROUND, info); } } // render data items... for (int datasetIndex : datasetIndices) { XYDataset dataset = this.getDataset(datasetIndex); foundData = render(g2, dataArea, datasetIndex, info, crosshairState) || foundData; } // draw foreground annotations for (int i : rendererIndices) { XYItemRenderer renderer = getRenderer(i); if (renderer != null) { ValueAxis domainAxis = getDomainAxisForDataset(i); ValueAxis rangeAxis = getRangeAxisForDataset(i); renderer.drawAnnotations(g2, dataArea, domainAxis, rangeAxis, Layer.FOREGROUND, info); } } // draw domain crosshair if required... int datasetIndex = crosshairState.getDatasetIndex(); ValueAxis xAxis = getDomainAxisForDataset(datasetIndex); RectangleEdge xAxisEdge = getDomainAxisEdge(getDomainAxisIndex(xAxis)); if (!this.domainCrosshairLockedOnData && anchor != null) { double xx; if (orient == PlotOrientation.VERTICAL) { xx = xAxis.java2DToValue(anchor.getX(), dataArea, xAxisEdge); } else { xx = xAxis.java2DToValue(anchor.getY(), dataArea, xAxisEdge); } crosshairState.setCrosshairX(xx); } setDomainCrosshairValue(crosshairState.getCrosshairX(), false); if (isDomainCrosshairVisible()) { double x = getDomainCrosshairValue(); Paint paint = getDomainCrosshairPaint(); Stroke stroke = getDomainCrosshairStroke(); drawDomainCrosshair(g2, dataArea, orient, x, xAxis, stroke, paint); } // draw range crosshair if required... ValueAxis yAxis = getRangeAxisForDataset(datasetIndex); RectangleEdge yAxisEdge = getRangeAxisEdge(getRangeAxisIndex(yAxis)); if (!this.rangeCrosshairLockedOnData && anchor != null) { double yy; if (orient == PlotOrientation.VERTICAL) { yy = yAxis.java2DToValue(anchor.getY(), dataArea, yAxisEdge); } else { yy = yAxis.java2DToValue(anchor.getX(), dataArea, yAxisEdge); } crosshairState.setCrosshairY(yy); } setRangeCrosshairValue(crosshairState.getCrosshairY(), false); if (isRangeCrosshairVisible()) { double y = getRangeCrosshairValue(); Paint paint = getRangeCrosshairPaint(); Stroke stroke = getRangeCrosshairStroke(); drawRangeCrosshair(g2, dataArea, orient, y, yAxis, stroke, paint); } if (!foundData) { drawNoDataMessage(g2, dataArea); } for (int i : rendererIndices) { drawDomainMarkers(g2, dataArea, i, Layer.FOREGROUND); } for (int i : rendererIndices) { drawRangeMarkers(g2, dataArea, i, Layer.FOREGROUND); } drawAnnotations(g2, dataArea, info); if (this.shadowGenerator != null && !suppressShadow) { BufferedImage shadowImage = this.shadowGenerator.createDropShadow(dataImage); g2 = savedG2; g2.drawImage(shadowImage, (int) dataArea.getX() + this.shadowGenerator.calculateOffsetX(), (int) dataArea.getY() + this.shadowGenerator.calculateOffsetY(), null); g2.drawImage(dataImage, (int) dataArea.getX(), (int) dataArea.getY(), null); } g2.setClip(originalClip); g2.setComposite(originalComposite); drawOutline(g2, dataArea); } /** * Returns the indices of the non-null datasets in the specified order. * * @param order the order ({@code null} not permitted). * * @return The list of indices. */ private List<Integer> getDatasetIndices(DatasetRenderingOrder order) { List<Integer> result = new ArrayList<Integer>(); for (Entry<Integer, XYDataset> entry : this.datasets.entrySet()) { if (entry.getValue() != null) { result.add(entry.getKey()); } } Collections.sort(result); if (order == DatasetRenderingOrder.REVERSE) { Collections.reverse(result); } return result; } private List<Integer> getRendererIndices(DatasetRenderingOrder order) { List<Integer> result = new ArrayList<Integer>(); for (Entry<Integer, XYItemRenderer> entry : this.renderers.entrySet()) { if (entry.getValue() != null) { result.add(entry.getKey()); } } Collections.sort(result); if (order == DatasetRenderingOrder.REVERSE) { Collections.reverse(result); } return result; } /** * Draws the background for the plot. * * @param g2 the graphics device. * @param area the area. */ @Override public void drawBackground(Graphics2D g2, Rectangle2D area) { fillBackground(g2, area, this.orientation); drawQuadrants(g2, area); drawBackgroundImage(g2, area); } /** * Draws the quadrants. * * @param g2 the graphics device. * @param area the area. * * @see #setQuadrantOrigin(Point2D) * @see #setQuadrantPaint(int, Paint) */ protected void drawQuadrants(Graphics2D g2, Rectangle2D area) { // 0 | 1 // 2 | 3 boolean somethingToDraw = false; ValueAxis xAxis = getDomainAxis(); if (xAxis == null) { // we can't draw quadrants without a valid x-axis return; } double x = xAxis.getRange().constrain(this.quadrantOrigin.getX()); double xx = xAxis.valueToJava2D(x, area, getDomainAxisEdge()); ValueAxis yAxis = getRangeAxis(); if (yAxis == null) { // we can't draw quadrants without a valid y-axis return; } double y = yAxis.getRange().constrain(this.quadrantOrigin.getY()); double yy = yAxis.valueToJava2D(y, area, getRangeAxisEdge()); double xmin = xAxis.getLowerBound(); double xxmin = xAxis.valueToJava2D(xmin, area, getDomainAxisEdge()); double xmax = xAxis.getUpperBound(); double xxmax = xAxis.valueToJava2D(xmax, area, getDomainAxisEdge()); double ymin = yAxis.getLowerBound(); double yymin = yAxis.valueToJava2D(ymin, area, getRangeAxisEdge()); double ymax = yAxis.getUpperBound(); double yymax = yAxis.valueToJava2D(ymax, area, getRangeAxisEdge()); Rectangle2D[] r = new Rectangle2D[] {null, null, null, null}; if (this.quadrantPaint[0] != null) { if (x > xmin && y < ymax) { if (this.orientation == PlotOrientation.HORIZONTAL) { r[0] = new Rectangle2D.Double(Math.min(yymax, yy), Math.min(xxmin, xx), Math.abs(yy - yymax), Math.abs(xx - xxmin)); } else { // PlotOrientation.VERTICAL r[0] = new Rectangle2D.Double(Math.min(xxmin, xx), Math.min(yymax, yy), Math.abs(xx - xxmin), Math.abs(yy - yymax)); } somethingToDraw = true; } } if (this.quadrantPaint[1] != null) { if (x < xmax && y < ymax) { if (this.orientation == PlotOrientation.HORIZONTAL) { r[1] = new Rectangle2D.Double(Math.min(yymax, yy), Math.min(xxmax, xx), Math.abs(yy - yymax), Math.abs(xx - xxmax)); } else { // PlotOrientation.VERTICAL r[1] = new Rectangle2D.Double(Math.min(xx, xxmax), Math.min(yymax, yy), Math.abs(xx - xxmax), Math.abs(yy - yymax)); } somethingToDraw = true; } } if (this.quadrantPaint[2] != null) { if (x > xmin && y > ymin) { if (this.orientation == PlotOrientation.HORIZONTAL) { r[2] = new Rectangle2D.Double(Math.min(yymin, yy), Math.min(xxmin, xx), Math.abs(yy - yymin), Math.abs(xx - xxmin)); } else { // PlotOrientation.VERTICAL r[2] = new Rectangle2D.Double(Math.min(xxmin, xx), Math.min(yymin, yy), Math.abs(xx - xxmin), Math.abs(yy - yymin)); } somethingToDraw = true; } } if (this.quadrantPaint[3] != null) { if (x < xmax && y > ymin) { if (this.orientation == PlotOrientation.HORIZONTAL) { r[3] = new Rectangle2D.Double(Math.min(yymin, yy), Math.min(xxmax, xx), Math.abs(yy - yymin), Math.abs(xx - xxmax)); } else { // PlotOrientation.VERTICAL r[3] = new Rectangle2D.Double(Math.min(xx, xxmax), Math.min(yymin, yy), Math.abs(xx - xxmax), Math.abs(yy - yymin)); } somethingToDraw = true; } } if (somethingToDraw) { Composite originalComposite = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getBackgroundAlpha())); for (int i = 0; i < 4; i++) { if (this.quadrantPaint[i] != null && r[i] != null) { g2.setPaint(this.quadrantPaint[i]); g2.fill(r[i]); } } g2.setComposite(originalComposite); } } /** * Draws the domain tick bands, if any. * * @param g2 the graphics device. * @param dataArea the data area. * @param ticks the ticks. * * @see #setDomainTickBandPaint(Paint) */ public void drawDomainTickBands(Graphics2D g2, Rectangle2D dataArea, List ticks) { Paint bandPaint = getDomainTickBandPaint(); if (bandPaint != null) { boolean fillBand = false; ValueAxis xAxis = getDomainAxis(); double previous = xAxis.getLowerBound(); Iterator iterator = ticks.iterator(); while (iterator.hasNext()) { ValueTick tick = (ValueTick) iterator.next(); double current = tick.getValue(); if (fillBand) { getRenderer().fillDomainGridBand(g2, this, xAxis, dataArea, previous, current); } previous = current; fillBand = !fillBand; } double end = xAxis.getUpperBound(); if (fillBand) { getRenderer().fillDomainGridBand(g2, this, xAxis, dataArea, previous, end); } } } /** * Draws the range tick bands, if any. * * @param g2 the graphics device. * @param dataArea the data area. * @param ticks the ticks. * * @see #setRangeTickBandPaint(Paint) */ public void drawRangeTickBands(Graphics2D g2, Rectangle2D dataArea, List ticks) { Paint bandPaint = getRangeTickBandPaint(); if (bandPaint != null) { boolean fillBand = false; ValueAxis axis = getRangeAxis(); double previous = axis.getLowerBound(); Iterator iterator = ticks.iterator(); while (iterator.hasNext()) { ValueTick tick = (ValueTick) iterator.next(); double current = tick.getValue(); if (fillBand) { getRenderer().fillRangeGridBand(g2, this, axis, dataArea, previous, current); } previous = current; fillBand = !fillBand; } double end = axis.getUpperBound(); if (fillBand) { getRenderer().fillRangeGridBand(g2, this, axis, dataArea, previous, end); } } } /** * A utility method for drawing the axes. * * @param g2 the graphics device ({@code null} not permitted). * @param plotArea the plot area ({@code null} not permitted). * @param dataArea the data area ({@code null} not permitted). * @param plotState collects information about the plot ({@code null} * permitted). * * @return A map containing the state for each axis drawn. */ protected Map<Axis, AxisState> drawAxes(Graphics2D g2, Rectangle2D plotArea, Rectangle2D dataArea, PlotRenderingInfo plotState) { AxisCollection axisCollection = new AxisCollection(); // add domain axes to lists... for (ValueAxis axis : this.domainAxes.values()) { if (axis != null) { int axisIndex = findDomainAxisIndex(axis); axisCollection.add(axis, getDomainAxisEdge(axisIndex)); } } // add range axes to lists... for (ValueAxis axis : this.rangeAxes.values()) { if (axis != null) { int axisIndex = findRangeAxisIndex(axis); axisCollection.add(axis, getRangeAxisEdge(axisIndex)); } } Map axisStateMap = new HashMap(); // draw the top axes double cursor = dataArea.getMinY() - this.axisOffset.calculateTopOutset( dataArea.getHeight()); Iterator iterator = axisCollection.getAxesAtTop().iterator(); while (iterator.hasNext()) { ValueAxis axis = (ValueAxis) iterator.next(); AxisState info = axis.draw(g2, cursor, plotArea, dataArea, RectangleEdge.TOP, plotState); cursor = info.getCursor(); axisStateMap.put(axis, info); } // draw the bottom axes cursor = dataArea.getMaxY() + this.axisOffset.calculateBottomOutset(dataArea.getHeight()); iterator = axisCollection.getAxesAtBottom().iterator(); while (iterator.hasNext()) { ValueAxis axis = (ValueAxis) iterator.next(); AxisState info = axis.draw(g2, cursor, plotArea, dataArea, RectangleEdge.BOTTOM, plotState); cursor = info.getCursor(); axisStateMap.put(axis, info); } // draw the left axes cursor = dataArea.getMinX() - this.axisOffset.calculateLeftOutset(dataArea.getWidth()); iterator = axisCollection.getAxesAtLeft().iterator(); while (iterator.hasNext()) { ValueAxis axis = (ValueAxis) iterator.next(); AxisState info = axis.draw(g2, cursor, plotArea, dataArea, RectangleEdge.LEFT, plotState); cursor = info.getCursor(); axisStateMap.put(axis, info); } // draw the right axes cursor = dataArea.getMaxX() + this.axisOffset.calculateRightOutset(dataArea.getWidth()); iterator = axisCollection.getAxesAtRight().iterator(); while (iterator.hasNext()) { ValueAxis axis = (ValueAxis) iterator.next(); AxisState info = axis.draw(g2, cursor, plotArea, dataArea, RectangleEdge.RIGHT, plotState); cursor = info.getCursor(); axisStateMap.put(axis, info); } return axisStateMap; } /** * Draws a representation of the data within the dataArea region, using the * current renderer. * <P> * The {@code info} and {@code crosshairState} arguments may be * {@code null}. * * @param g2 the graphics device. * @param dataArea the region in which the data is to be drawn. * @param index the dataset index. * @param info an optional object for collection dimension information. * @param crosshairState collects crosshair information * ({@code null} permitted). * * @return A flag that indicates whether any data was actually rendered. */ public boolean render(Graphics2D g2, Rectangle2D dataArea, int index, PlotRenderingInfo info, CrosshairState crosshairState) { boolean foundData = false; XYDataset dataset = getDataset(index); if (!DatasetUtilities.isEmptyOrNull(dataset)) { foundData = true; ValueAxis xAxis = getDomainAxisForDataset(index); ValueAxis yAxis = getRangeAxisForDataset(index); if (xAxis == null || yAxis == null) { return foundData; // can't render anything without axes } XYItemRenderer renderer = getRenderer(index); if (renderer == null) { renderer = getRenderer(); if (renderer == null) { // no default renderer available return foundData; } } XYItemRendererState state = renderer.initialise(g2, dataArea, this, dataset, info); int passCount = renderer.getPassCount(); SeriesRenderingOrder seriesOrder = getSeriesRenderingOrder(); if (seriesOrder == SeriesRenderingOrder.REVERSE) { //render series in reverse order for (int pass = 0; pass < passCount; pass++) { int seriesCount = dataset.getSeriesCount(); for (int series = seriesCount - 1; series >= 0; series int firstItem = 0; int lastItem = dataset.getItemCount(series) - 1; if (lastItem == -1) { continue; } if (state.getProcessVisibleItemsOnly()) { int[] itemBounds = RendererUtilities.findLiveItems( dataset, series, xAxis.getLowerBound(), xAxis.getUpperBound()); firstItem = Math.max(itemBounds[0] - 1, 0); lastItem = Math.min(itemBounds[1] + 1, lastItem); } state.startSeriesPass(dataset, series, firstItem, lastItem, pass, passCount); for (int item = firstItem; item <= lastItem; item++) { renderer.drawItem(g2, state, dataArea, info, this, xAxis, yAxis, dataset, series, item, crosshairState, pass); } state.endSeriesPass(dataset, series, firstItem, lastItem, pass, passCount); } } } else { //render series in forward order for (int pass = 0; pass < passCount; pass++) { int seriesCount = dataset.getSeriesCount(); for (int series = 0; series < seriesCount; series++) { int firstItem = 0; int lastItem = dataset.getItemCount(series) - 1; if (state.getProcessVisibleItemsOnly()) { int[] itemBounds = RendererUtilities.findLiveItems( dataset, series, xAxis.getLowerBound(), xAxis.getUpperBound()); firstItem = Math.max(itemBounds[0] - 1, 0); lastItem = Math.min(itemBounds[1] + 1, lastItem); } state.startSeriesPass(dataset, series, firstItem, lastItem, pass, passCount); for (int item = firstItem; item <= lastItem; item++) { renderer.drawItem(g2, state, dataArea, info, this, xAxis, yAxis, dataset, series, item, crosshairState, pass); } state.endSeriesPass(dataset, series, firstItem, lastItem, pass, passCount); } } } } return foundData; } /** * Returns the domain axis for a dataset. * * @param index the dataset index (must be &gt;= 0). * * @return The axis. */ public ValueAxis getDomainAxisForDataset(int index) { ParamChecks.requireNonNegative(index, "index"); ValueAxis valueAxis; List axisIndices = (List) this.datasetToDomainAxesMap.get( new Integer(index)); if (axisIndices != null) { // the first axis in the list is used for data <--> Java2D Integer axisIndex = (Integer) axisIndices.get(0); valueAxis = getDomainAxis(axisIndex.intValue()); } else { valueAxis = getDomainAxis(0); } return valueAxis; } /** * Returns the range axis for a dataset. * * @param index the dataset index (must be &gt;= 0). * * @return The axis. */ public ValueAxis getRangeAxisForDataset(int index) { ParamChecks.requireNonNegative(index, "index"); ValueAxis valueAxis; List axisIndices = (List) this.datasetToRangeAxesMap.get( new Integer(index)); if (axisIndices != null) { // the first axis in the list is used for data <--> Java2D Integer axisIndex = (Integer) axisIndices.get(0); valueAxis = getRangeAxis(axisIndex.intValue()); } else { valueAxis = getRangeAxis(0); } return valueAxis; } /** * Draws the gridlines for the plot, if they are visible. * * @param g2 the graphics device. * @param dataArea the data area. * @param ticks the ticks. * * @see #drawRangeGridlines(Graphics2D, Rectangle2D, List) */ protected void drawDomainGridlines(Graphics2D g2, Rectangle2D dataArea, List ticks) { // no renderer, no gridlines... if (getRenderer() == null) { return; } // draw the domain grid lines, if any... if (isDomainGridlinesVisible() || isDomainMinorGridlinesVisible()) { Stroke gridStroke = null; Paint gridPaint = null; Iterator iterator = ticks.iterator(); boolean paintLine; while (iterator.hasNext()) { paintLine = false; ValueTick tick = (ValueTick) iterator.next(); if ((tick.getTickType() == TickType.MINOR) && isDomainMinorGridlinesVisible()) { gridStroke = getDomainMinorGridlineStroke(); gridPaint = getDomainMinorGridlinePaint(); paintLine = true; } else if ((tick.getTickType() == TickType.MAJOR) && isDomainGridlinesVisible()) { gridStroke = getDomainGridlineStroke(); gridPaint = getDomainGridlinePaint(); paintLine = true; } XYItemRenderer r = getRenderer(); if ((r instanceof AbstractXYItemRenderer) && paintLine) { ((AbstractXYItemRenderer) r).drawDomainLine(g2, this, getDomainAxis(), dataArea, tick.getValue(), gridPaint, gridStroke); } } } } /** * Draws the gridlines for the plot's primary range axis, if they are * visible. * * @param g2 the graphics device. * @param area the data area. * @param ticks the ticks. * * @see #drawDomainGridlines(Graphics2D, Rectangle2D, List) */ protected void drawRangeGridlines(Graphics2D g2, Rectangle2D area, List ticks) { // no renderer, no gridlines... if (getRenderer() == null) { return; } // draw the range grid lines, if any... if (isRangeGridlinesVisible() || isRangeMinorGridlinesVisible()) { Stroke gridStroke = null; Paint gridPaint = null; ValueAxis axis = getRangeAxis(); if (axis != null) { Iterator iterator = ticks.iterator(); boolean paintLine; while (iterator.hasNext()) { paintLine = false; ValueTick tick = (ValueTick) iterator.next(); if ((tick.getTickType() == TickType.MINOR) && isRangeMinorGridlinesVisible()) { gridStroke = getRangeMinorGridlineStroke(); gridPaint = getRangeMinorGridlinePaint(); paintLine = true; } else if ((tick.getTickType() == TickType.MAJOR) && isRangeGridlinesVisible()) { gridStroke = getRangeGridlineStroke(); gridPaint = getRangeGridlinePaint(); paintLine = true; } if ((tick.getValue() != 0.0 || !isRangeZeroBaselineVisible()) && paintLine) { getRenderer().drawRangeLine(g2, this, getRangeAxis(), area, tick.getValue(), gridPaint, gridStroke); } } } } } /** * Draws a base line across the chart at value zero on the domain axis. * * @param g2 the graphics device. * @param area the data area. * * @see #setDomainZeroBaselineVisible(boolean) * * @since 1.0.5 */ protected void drawZeroDomainBaseline(Graphics2D g2, Rectangle2D area) { if (isDomainZeroBaselineVisible()) { XYItemRenderer r = getRenderer(); // FIXME: the renderer interface doesn't have the drawDomainLine() // method, so we have to rely on the renderer being a subclass of // AbstractXYItemRenderer (which is lame) if (r instanceof AbstractXYItemRenderer) { AbstractXYItemRenderer renderer = (AbstractXYItemRenderer) r; renderer.drawDomainLine(g2, this, getDomainAxis(), area, 0.0, this.domainZeroBaselinePaint, this.domainZeroBaselineStroke); } } } /** * Draws a base line across the chart at value zero on the range axis. * * @param g2 the graphics device. * @param area the data area. * * @see #setRangeZeroBaselineVisible(boolean) */ protected void drawZeroRangeBaseline(Graphics2D g2, Rectangle2D area) { if (isRangeZeroBaselineVisible()) { getRenderer().drawRangeLine(g2, this, getRangeAxis(), area, 0.0, this.rangeZeroBaselinePaint, this.rangeZeroBaselineStroke); } } /** * Draws the annotations for the plot. * * @param g2 the graphics device. * @param dataArea the data area. * @param info the chart rendering info. */ public void drawAnnotations(Graphics2D g2, Rectangle2D dataArea, PlotRenderingInfo info) { Iterator iterator = this.annotations.iterator(); while (iterator.hasNext()) { XYAnnotation annotation = (XYAnnotation) iterator.next(); ValueAxis xAxis = getDomainAxis(); ValueAxis yAxis = getRangeAxis(); annotation.draw(g2, this, dataArea, xAxis, yAxis, 0, info); } } /** * Draws the domain markers (if any) for an axis and layer. This method is * typically called from within the draw() method. * * @param g2 the graphics device. * @param dataArea the data area. * @param index the dataset/renderer index. * @param layer the layer (foreground or background). */ protected void drawDomainMarkers(Graphics2D g2, Rectangle2D dataArea, int index, Layer layer) { XYItemRenderer r = getRenderer(index); if (r == null) { return; } // check that the renderer has a corresponding dataset (it doesn't // matter if the dataset is null) if (index >= getDatasetCount()) { return; } Collection markers = getDomainMarkers(index, layer); ValueAxis axis = getDomainAxisForDataset(index); if (markers != null && axis != null) { Iterator iterator = markers.iterator(); while (iterator.hasNext()) { Marker marker = (Marker) iterator.next(); r.drawDomainMarker(g2, this, axis, marker, dataArea); } } } /** * Draws the range markers (if any) for a renderer and layer. This method * is typically called from within the draw() method. * * @param g2 the graphics device. * @param dataArea the data area. * @param index the renderer index. * @param layer the layer (foreground or background). */ protected void drawRangeMarkers(Graphics2D g2, Rectangle2D dataArea, int index, Layer layer) { XYItemRenderer r = getRenderer(index); if (r == null) { return; } // check that the renderer has a corresponding dataset (it doesn't // matter if the dataset is null) if (index >= getDatasetCount()) { return; } Collection markers = getRangeMarkers(index, layer); ValueAxis axis = getRangeAxisForDataset(index); if (markers != null && axis != null) { Iterator iterator = markers.iterator(); while (iterator.hasNext()) { Marker marker = (Marker) iterator.next(); r.drawRangeMarker(g2, this, axis, marker, dataArea); } } } /** * Returns the list of domain markers (read only) for the specified layer. * * @param layer the layer (foreground or background). * * @return The list of domain markers. * * @see #getRangeMarkers(Layer) */ public Collection getDomainMarkers(Layer layer) { return getDomainMarkers(0, layer); } /** * Returns the list of range markers (read only) for the specified layer. * * @param layer the layer (foreground or background). * * @return The list of range markers. * * @see #getDomainMarkers(Layer) */ public Collection getRangeMarkers(Layer layer) { return getRangeMarkers(0, layer); } /** * Returns a collection of domain markers for a particular renderer and * layer. * * @param index the renderer index. * @param layer the layer. * * @return A collection of markers (possibly {@code null}). * * @see #getRangeMarkers(int, Layer) */ public Collection getDomainMarkers(int index, Layer layer) { Collection result = null; Integer key = new Integer(index); if (layer == Layer.FOREGROUND) { result = (Collection) this.foregroundDomainMarkers.get(key); } else if (layer == Layer.BACKGROUND) { result = (Collection) this.backgroundDomainMarkers.get(key); } if (result != null) { result = Collections.unmodifiableCollection(result); } return result; } /** * Returns a collection of range markers for a particular renderer and * layer. * * @param index the renderer index. * @param layer the layer. * * @return A collection of markers (possibly {@code null}). * * @see #getDomainMarkers(int, Layer) */ public Collection getRangeMarkers(int index, Layer layer) { Collection result = null; Integer key = new Integer(index); if (layer == Layer.FOREGROUND) { result = (Collection) this.foregroundRangeMarkers.get(key); } else if (layer == Layer.BACKGROUND) { result = (Collection) this.backgroundRangeMarkers.get(key); } if (result != null) { result = Collections.unmodifiableCollection(result); } return result; } /** * Utility method for drawing a horizontal line across the data area of the * plot. * * @param g2 the graphics device. * @param dataArea the data area. * @param value the coordinate, where to draw the line. * @param stroke the stroke to use. * @param paint the paint to use. */ protected void drawHorizontalLine(Graphics2D g2, Rectangle2D dataArea, double value, Stroke stroke, Paint paint) { ValueAxis axis = getRangeAxis(); if (getOrientation() == PlotOrientation.HORIZONTAL) { axis = getDomainAxis(); } if (axis.getRange().contains(value)) { double yy = axis.valueToJava2D(value, dataArea, RectangleEdge.LEFT); Line2D line = new Line2D.Double(dataArea.getMinX(), yy, dataArea.getMaxX(), yy); g2.setStroke(stroke); g2.setPaint(paint); g2.draw(line); } } /** * Draws a domain crosshair. * * @param g2 the graphics target. * @param dataArea the data area. * @param orientation the plot orientation. * @param value the crosshair value. * @param axis the axis against which the value is measured. * @param stroke the stroke used to draw the crosshair line. * @param paint the paint used to draw the crosshair line. * * @since 1.0.4 */ protected void drawDomainCrosshair(Graphics2D g2, Rectangle2D dataArea, PlotOrientation orientation, double value, ValueAxis axis, Stroke stroke, Paint paint) { if (!axis.getRange().contains(value)) { return; } Line2D line; if (orientation == PlotOrientation.VERTICAL) { double xx = axis.valueToJava2D(value, dataArea, RectangleEdge.BOTTOM); line = new Line2D.Double(xx, dataArea.getMinY(), xx, dataArea.getMaxY()); } else { double yy = axis.valueToJava2D(value, dataArea, RectangleEdge.LEFT); line = new Line2D.Double(dataArea.getMinX(), yy, dataArea.getMaxX(), yy); } Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL); g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE); g2.setStroke(stroke); g2.setPaint(paint); g2.draw(line); g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved); } /** * Utility method for drawing a vertical line on the data area of the plot. * * @param g2 the graphics device. * @param dataArea the data area. * @param value the coordinate, where to draw the line. * @param stroke the stroke to use. * @param paint the paint to use. */ protected void drawVerticalLine(Graphics2D g2, Rectangle2D dataArea, double value, Stroke stroke, Paint paint) { ValueAxis axis = getDomainAxis(); if (getOrientation() == PlotOrientation.HORIZONTAL) { axis = getRangeAxis(); } if (axis.getRange().contains(value)) { double xx = axis.valueToJava2D(value, dataArea, RectangleEdge.BOTTOM); Line2D line = new Line2D.Double(xx, dataArea.getMinY(), xx, dataArea.getMaxY()); g2.setStroke(stroke); g2.setPaint(paint); g2.draw(line); } } /** * Draws a range crosshair. * * @param g2 the graphics target. * @param dataArea the data area. * @param orientation the plot orientation. * @param value the crosshair value. * @param axis the axis against which the value is measured. * @param stroke the stroke used to draw the crosshair line. * @param paint the paint used to draw the crosshair line. * * @since 1.0.4 */ protected void drawRangeCrosshair(Graphics2D g2, Rectangle2D dataArea, PlotOrientation orientation, double value, ValueAxis axis, Stroke stroke, Paint paint) { if (!axis.getRange().contains(value)) { return; } Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL); g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE); Line2D line; if (orientation == PlotOrientation.HORIZONTAL) { double xx = axis.valueToJava2D(value, dataArea, RectangleEdge.BOTTOM); line = new Line2D.Double(xx, dataArea.getMinY(), xx, dataArea.getMaxY()); } else { double yy = axis.valueToJava2D(value, dataArea, RectangleEdge.LEFT); line = new Line2D.Double(dataArea.getMinX(), yy, dataArea.getMaxX(), yy); } g2.setStroke(stroke); g2.setPaint(paint); g2.draw(line); g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved); } /** * Handles a 'click' on the plot by updating the anchor values. * * @param x the x-coordinate, where the click occurred, in Java2D space. * @param y the y-coordinate, where the click occurred, in Java2D space. * @param info object containing information about the plot dimensions. */ @Override public void handleClick(int x, int y, PlotRenderingInfo info) { Rectangle2D dataArea = info.getDataArea(); if (dataArea.contains(x, y)) { // set the anchor value for the horizontal axis... ValueAxis xaxis = getDomainAxis(); if (xaxis != null) { double hvalue = xaxis.java2DToValue(x, info.getDataArea(), getDomainAxisEdge()); setDomainCrosshairValue(hvalue); } // set the anchor value for the vertical axis... ValueAxis yaxis = getRangeAxis(); if (yaxis != null) { double vvalue = yaxis.java2DToValue(y, info.getDataArea(), getRangeAxisEdge()); setRangeCrosshairValue(vvalue); } } } /** * A utility method that returns a list of datasets that are mapped to a * particular axis. * * @param axisIndex the axis index ({@code null} not permitted). * * @return A list of datasets. */ private List<XYDataset> getDatasetsMappedToDomainAxis(Integer axisIndex) { ParamChecks.nullNotPermitted(axisIndex, "axisIndex"); List<XYDataset> result = new ArrayList<XYDataset>(); for (Entry<Integer, XYDataset> entry : this.datasets.entrySet()) { int index = entry.getKey(); List<Integer> mappedAxes = this.datasetToDomainAxesMap.get(index); if (mappedAxes == null) { if (axisIndex.equals(ZERO)) { result.add(entry.getValue()); } } else { if (mappedAxes.contains(axisIndex)) { result.add(entry.getValue()); } } } return result; } /** * A utility method that returns a list of datasets that are mapped to a * particular axis. * * @param axisIndex the axis index ({@code null} not permitted). * * @return A list of datasets. */ private List<XYDataset> getDatasetsMappedToRangeAxis(Integer axisIndex) { ParamChecks.nullNotPermitted(axisIndex, "axisIndex"); List<XYDataset> result = new ArrayList<XYDataset>(); for (Entry<Integer, XYDataset> entry : this.datasets.entrySet()) { int index = entry.getKey(); List<Integer> mappedAxes = this.datasetToRangeAxesMap.get(index); if (mappedAxes == null) { if (axisIndex.equals(ZERO)) { result.add(entry.getValue()); } } else { if (mappedAxes.contains(axisIndex)) { result.add(entry.getValue()); } } } return result; } /** * Returns the index of the given domain axis. * * @param axis the axis. * * @return The axis index. * * @see #getRangeAxisIndex(ValueAxis) */ public int getDomainAxisIndex(ValueAxis axis) { int result = findDomainAxisIndex(axis); if (result < 0) { // try the parent plot Plot parent = getParent(); if (parent instanceof XYPlot) { XYPlot p = (XYPlot) parent; result = p.getDomainAxisIndex(axis); } } return result; } private int findDomainAxisIndex(ValueAxis axis) { for (Map.Entry<Integer, ValueAxis> entry : this.domainAxes.entrySet()) { if (entry.getValue() == axis) { return entry.getKey(); } } return -1; } /** * Returns the index of the given range axis. * * @param axis the axis. * * @return The axis index. * * @see #getDomainAxisIndex(ValueAxis) */ public int getRangeAxisIndex(ValueAxis axis) { int result = findRangeAxisIndex(axis); if (result < 0) { // try the parent plot Plot parent = getParent(); if (parent instanceof XYPlot) { XYPlot p = (XYPlot) parent; result = p.getRangeAxisIndex(axis); } } return result; } private int findRangeAxisIndex(ValueAxis axis) { for (Map.Entry<Integer, ValueAxis> entry : this.rangeAxes.entrySet()) { if (entry.getValue() == axis) { return entry.getKey(); } } return -1; } /** * Returns the range for the specified axis. * * @param axis the axis. * * @return The range. */ @Override public Range getDataRange(ValueAxis axis) { Range result = null; List<XYDataset> mappedDatasets = new ArrayList<XYDataset>(); List<XYAnnotation> includedAnnotations = new ArrayList<XYAnnotation>(); boolean isDomainAxis = true; // is it a domain axis? int domainIndex = getDomainAxisIndex(axis); if (domainIndex >= 0) { isDomainAxis = true; mappedDatasets.addAll(getDatasetsMappedToDomainAxis(domainIndex)); if (domainIndex == 0) { // grab the plot's annotations Iterator iterator = this.annotations.iterator(); while (iterator.hasNext()) { XYAnnotation annotation = (XYAnnotation) iterator.next(); if (annotation instanceof XYAnnotationBoundsInfo) { includedAnnotations.add(annotation); } } } } // or is it a range axis? int rangeIndex = getRangeAxisIndex(axis); if (rangeIndex >= 0) { isDomainAxis = false; mappedDatasets.addAll(getDatasetsMappedToRangeAxis(rangeIndex)); if (rangeIndex == 0) { Iterator iterator = this.annotations.iterator(); while (iterator.hasNext()) { XYAnnotation annotation = (XYAnnotation) iterator.next(); if (annotation instanceof XYAnnotationBoundsInfo) { includedAnnotations.add(annotation); } } } } // iterate through the datasets that map to the axis and get the union // of the ranges. for (XYDataset d : mappedDatasets) { if (d != null) { XYItemRenderer r = getRendererForDataset(d); if (isDomainAxis) { if (r != null) { result = Range.combine(result, r.findDomainBounds(d)); } else { result = Range.combine(result, DatasetUtilities.findDomainBounds(d)); } } else { if (r != null) { result = Range.combine(result, r.findRangeBounds(d)); } else { result = Range.combine(result, DatasetUtilities.findRangeBounds(d)); } } // FIXME: the XYItemRenderer interface doesn't specify the // getAnnotations() method but it should if (r instanceof AbstractXYItemRenderer) { AbstractXYItemRenderer rr = (AbstractXYItemRenderer) r; Collection c = rr.getAnnotations(); Iterator i = c.iterator(); while (i.hasNext()) { XYAnnotation a = (XYAnnotation) i.next(); if (a instanceof XYAnnotationBoundsInfo) { includedAnnotations.add(a); } } } } } Iterator it = includedAnnotations.iterator(); while (it.hasNext()) { XYAnnotationBoundsInfo xyabi = (XYAnnotationBoundsInfo) it.next(); if (xyabi.getIncludeInDataBounds()) { if (isDomainAxis) { result = Range.combine(result, xyabi.getXRange()); } else { result = Range.combine(result, xyabi.getYRange()); } } } return result; } /** * Receives notification of a change to an {@link Annotation} added to * this plot. * * @param event information about the event (not used here). * * @since 1.0.14 */ @Override public void annotationChanged(AnnotationChangeEvent event) { if (getParent() != null) { getParent().annotationChanged(event); } else { PlotChangeEvent e = new PlotChangeEvent(this); notifyListeners(e); } } /** * Receives notification of a change to the plot's dataset. * <P> * The axis ranges are updated if necessary. * * @param event information about the event (not used here). */ @Override public void datasetChanged(DatasetChangeEvent event) { configureDomainAxes(); configureRangeAxes(); if (getParent() != null) { getParent().datasetChanged(event); } else { PlotChangeEvent e = new PlotChangeEvent(this); e.setType(ChartChangeEventType.DATASET_UPDATED); notifyListeners(e); } } /** * Receives notification of a renderer change event. * * @param event the event. */ @Override public void rendererChanged(RendererChangeEvent event) { // if the event was caused by a change to series visibility, then // the axis ranges might need updating... if (event.getSeriesVisibilityChanged()) { configureDomainAxes(); configureRangeAxes(); } fireChangeEvent(); } /** * Returns a flag indicating whether or not the domain crosshair is visible. * * @return The flag. * * @see #setDomainCrosshairVisible(boolean) */ public boolean isDomainCrosshairVisible() { return this.domainCrosshairVisible; } /** * Sets the flag indicating whether or not the domain crosshair is visible * and, if the flag changes, sends a {@link PlotChangeEvent} to all * registered listeners. * * @param flag the new value of the flag. * * @see #isDomainCrosshairVisible() */ public void setDomainCrosshairVisible(boolean flag) { if (this.domainCrosshairVisible != flag) { this.domainCrosshairVisible = flag; fireChangeEvent(); } } /** * Returns a flag indicating whether or not the crosshair should "lock-on" * to actual data values. * * @return The flag. * * @see #setDomainCrosshairLockedOnData(boolean) */ public boolean isDomainCrosshairLockedOnData() { return this.domainCrosshairLockedOnData; } /** * Sets the flag indicating whether or not the domain crosshair should * "lock-on" to actual data values. If the flag value changes, this * method sends a {@link PlotChangeEvent} to all registered listeners. * * @param flag the flag. * * @see #isDomainCrosshairLockedOnData() */ public void setDomainCrosshairLockedOnData(boolean flag) { if (this.domainCrosshairLockedOnData != flag) { this.domainCrosshairLockedOnData = flag; fireChangeEvent(); } } /** * Returns the domain crosshair value. * * @return The value. * * @see #setDomainCrosshairValue(double) */ public double getDomainCrosshairValue() { return this.domainCrosshairValue; } /** * Sets the domain crosshair value and sends a {@link PlotChangeEvent} to * all registered listeners (provided that the domain crosshair is visible). * * @param value the value. * * @see #getDomainCrosshairValue() */ public void setDomainCrosshairValue(double value) { setDomainCrosshairValue(value, true); } /** * Sets the domain crosshair value and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners (provided that the * domain crosshair is visible). * * @param value the new value. * @param notify notify listeners? * * @see #getDomainCrosshairValue() */ public void setDomainCrosshairValue(double value, boolean notify) { this.domainCrosshairValue = value; if (isDomainCrosshairVisible() && notify) { fireChangeEvent(); } } /** * Returns the {@link Stroke} used to draw the crosshair (if visible). * * @return The crosshair stroke (never {@code null}). * * @see #setDomainCrosshairStroke(Stroke) * @see #isDomainCrosshairVisible() * @see #getDomainCrosshairPaint() */ public Stroke getDomainCrosshairStroke() { return this.domainCrosshairStroke; } /** * Sets the Stroke used to draw the crosshairs (if visible) and notifies * registered listeners that the axis has been modified. * * @param stroke the new crosshair stroke ({@code null} not * permitted). * * @see #getDomainCrosshairStroke() */ public void setDomainCrosshairStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.domainCrosshairStroke = stroke; fireChangeEvent(); } /** * Returns the domain crosshair paint. * * @return The crosshair paint (never {@code null}). * * @see #setDomainCrosshairPaint(Paint) * @see #isDomainCrosshairVisible() * @see #getDomainCrosshairStroke() */ public Paint getDomainCrosshairPaint() { return this.domainCrosshairPaint; } /** * Sets the paint used to draw the crosshairs (if visible) and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param paint the new crosshair paint ({@code null} not permitted). * * @see #getDomainCrosshairPaint() */ public void setDomainCrosshairPaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.domainCrosshairPaint = paint; fireChangeEvent(); } /** * Returns a flag indicating whether or not the range crosshair is visible. * * @return The flag. * * @see #setRangeCrosshairVisible(boolean) * @see #isDomainCrosshairVisible() */ public boolean isRangeCrosshairVisible() { return this.rangeCrosshairVisible; } /** * Sets the flag indicating whether or not the range crosshair is visible. * If the flag value changes, this method sends a {@link PlotChangeEvent} * to all registered listeners. * * @param flag the new value of the flag. * * @see #isRangeCrosshairVisible() */ public void setRangeCrosshairVisible(boolean flag) { if (this.rangeCrosshairVisible != flag) { this.rangeCrosshairVisible = flag; fireChangeEvent(); } } /** * Returns a flag indicating whether or not the crosshair should "lock-on" * to actual data values. * * @return The flag. * * @see #setRangeCrosshairLockedOnData(boolean) */ public boolean isRangeCrosshairLockedOnData() { return this.rangeCrosshairLockedOnData; } /** * Sets the flag indicating whether or not the range crosshair should * "lock-on" to actual data values. If the flag value changes, this method * sends a {@link PlotChangeEvent} to all registered listeners. * * @param flag the flag. * * @see #isRangeCrosshairLockedOnData() */ public void setRangeCrosshairLockedOnData(boolean flag) { if (this.rangeCrosshairLockedOnData != flag) { this.rangeCrosshairLockedOnData = flag; fireChangeEvent(); } } /** * Returns the range crosshair value. * * @return The value. * * @see #setRangeCrosshairValue(double) */ public double getRangeCrosshairValue() { return this.rangeCrosshairValue; } /** * Sets the range crosshair value. * <P> * Registered listeners are notified that the plot has been modified, but * only if the crosshair is visible. * * @param value the new value. * * @see #getRangeCrosshairValue() */ public void setRangeCrosshairValue(double value) { setRangeCrosshairValue(value, true); } /** * Sets the range crosshair value and sends a {@link PlotChangeEvent} to * all registered listeners, but only if the crosshair is visible. * * @param value the new value. * @param notify a flag that controls whether or not listeners are * notified. * * @see #getRangeCrosshairValue() */ public void setRangeCrosshairValue(double value, boolean notify) { this.rangeCrosshairValue = value; if (isRangeCrosshairVisible() && notify) { fireChangeEvent(); } } /** * Returns the stroke used to draw the crosshair (if visible). * * @return The crosshair stroke (never {@code null}). * * @see #setRangeCrosshairStroke(Stroke) * @see #isRangeCrosshairVisible() * @see #getRangeCrosshairPaint() */ public Stroke getRangeCrosshairStroke() { return this.rangeCrosshairStroke; } /** * Sets the stroke used to draw the crosshairs (if visible) and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param stroke the new crosshair stroke ({@code null} not * permitted). * * @see #getRangeCrosshairStroke() */ public void setRangeCrosshairStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.rangeCrosshairStroke = stroke; fireChangeEvent(); } /** * Returns the range crosshair paint. * * @return The crosshair paint (never {@code null}). * * @see #setRangeCrosshairPaint(Paint) * @see #isRangeCrosshairVisible() * @see #getRangeCrosshairStroke() */ public Paint getRangeCrosshairPaint() { return this.rangeCrosshairPaint; } /** * Sets the paint used to color the crosshairs (if visible) and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param paint the new crosshair paint ({@code null} not permitted). * * @see #getRangeCrosshairPaint() */ public void setRangeCrosshairPaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.rangeCrosshairPaint = paint; fireChangeEvent(); } /** * Returns the fixed domain axis space. * * @return The fixed domain axis space (possibly {@code null}). * * @see #setFixedDomainAxisSpace(AxisSpace) */ public AxisSpace getFixedDomainAxisSpace() { return this.fixedDomainAxisSpace; } /** * Sets the fixed domain axis space and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param space the space ({@code null} permitted). * * @see #getFixedDomainAxisSpace() */ public void setFixedDomainAxisSpace(AxisSpace space) { setFixedDomainAxisSpace(space, true); } /** * Sets the fixed domain axis space and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param space the space ({@code null} permitted). * @param notify notify listeners? * * @see #getFixedDomainAxisSpace() * * @since 1.0.9 */ public void setFixedDomainAxisSpace(AxisSpace space, boolean notify) { this.fixedDomainAxisSpace = space; if (notify) { fireChangeEvent(); } } /** * Returns the fixed range axis space. * * @return The fixed range axis space (possibly {@code null}). * * @see #setFixedRangeAxisSpace(AxisSpace) */ public AxisSpace getFixedRangeAxisSpace() { return this.fixedRangeAxisSpace; } /** * Sets the fixed range axis space and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param space the space ({@code null} permitted). * * @see #getFixedRangeAxisSpace() */ public void setFixedRangeAxisSpace(AxisSpace space) { setFixedRangeAxisSpace(space, true); } /** * Sets the fixed range axis space and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param space the space ({@code null} permitted). * @param notify notify listeners? * * @see #getFixedRangeAxisSpace() * * @since 1.0.9 */ public void setFixedRangeAxisSpace(AxisSpace space, boolean notify) { this.fixedRangeAxisSpace = space; if (notify) { fireChangeEvent(); } } /** * Returns {@code true} if panning is enabled for the domain axes, * and {@code false} otherwise. * * @return A boolean. * * @since 1.0.13 */ @Override public boolean isDomainPannable() { return this.domainPannable; } /** * Sets the flag that enables or disables panning of the plot along the * domain axes. * * @param pannable the new flag value. * * @since 1.0.13 */ public void setDomainPannable(boolean pannable) { this.domainPannable = pannable; } /** * Returns {@code true} if panning is enabled for the range axis/axes, * and {@code false} otherwise. The default value is {@code false}. * * @return A boolean. * * @since 1.0.13 */ @Override public boolean isRangePannable() { return this.rangePannable; } /** * Sets the flag that enables or disables panning of the plot along * the range axis/axes. * * @param pannable the new flag value. * * @since 1.0.13 */ public void setRangePannable(boolean pannable) { this.rangePannable = pannable; } /** * Pans the domain axes by the specified percentage. * * @param percent the distance to pan (as a percentage of the axis length). * @param info the plot info * @param source the source point where the pan action started. * * @since 1.0.13 */ @Override public void panDomainAxes(double percent, PlotRenderingInfo info, Point2D source) { if (!isDomainPannable()) { return; } int domainAxisCount = getDomainAxisCount(); for (int i = 0; i < domainAxisCount; i++) { ValueAxis axis = getDomainAxis(i); if (axis == null) { continue; } if (axis.isInverted()) { percent = -percent; } axis.pan(percent); } } /** * Pans the range axes by the specified percentage. * * @param percent the distance to pan (as a percentage of the axis length). * @param info the plot info * @param source the source point where the pan action started. * * @since 1.0.13 */ @Override public void panRangeAxes(double percent, PlotRenderingInfo info, Point2D source) { if (!isRangePannable()) { return; } int rangeAxisCount = getRangeAxisCount(); for (int i = 0; i < rangeAxisCount; i++) { ValueAxis axis = getRangeAxis(i); if (axis == null) { continue; } if (axis.isInverted()) { percent = -percent; } axis.pan(percent); } } /** * Multiplies the range on the domain axis/axes by the specified factor. * * @param factor the zoom factor. * @param info the plot rendering info. * @param source the source point (in Java2D space). * * @see #zoomRangeAxes(double, PlotRenderingInfo, Point2D) */ @Override public void zoomDomainAxes(double factor, PlotRenderingInfo info, Point2D source) { // delegate to other method zoomDomainAxes(factor, info, source, false); } /** * Multiplies the range on the domain axis/axes by the specified factor. * * @param factor the zoom factor. * @param info the plot rendering info. * @param source the source point (in Java2D space). * @param useAnchor use source point as zoom anchor? * * @see #zoomRangeAxes(double, PlotRenderingInfo, Point2D, boolean) * * @since 1.0.7 */ @Override public void zoomDomainAxes(double factor, PlotRenderingInfo info, Point2D source, boolean useAnchor) { // perform the zoom on each domain axis for (ValueAxis xAxis : this.domainAxes.values()) { if (xAxis == null) { continue; } if (useAnchor) { // get the relevant source coordinate given the plot orientation double sourceX = source.getX(); if (this.orientation == PlotOrientation.HORIZONTAL) { sourceX = source.getY(); } double anchorX = xAxis.java2DToValue(sourceX, info.getDataArea(), getDomainAxisEdge()); xAxis.resizeRange2(factor, anchorX); } else { xAxis.resizeRange(factor); } } } /** * Zooms in on the domain axis/axes. The new lower and upper bounds are * specified as percentages of the current axis range, where 0 percent is * the current lower bound and 100 percent is the current upper bound. * * @param lowerPercent a percentage that determines the new lower bound * for the axis (e.g. 0.20 is twenty percent). * @param upperPercent a percentage that determines the new upper bound * for the axis (e.g. 0.80 is eighty percent). * @param info the plot rendering info. * @param source the source point (ignored). * * @see #zoomRangeAxes(double, double, PlotRenderingInfo, Point2D) */ @Override public void zoomDomainAxes(double lowerPercent, double upperPercent, PlotRenderingInfo info, Point2D source) { for (ValueAxis xAxis : this.domainAxes.values()) { if (xAxis != null) { xAxis.zoomRange(lowerPercent, upperPercent); } } } /** * Multiplies the range on the range axis/axes by the specified factor. * * @param factor the zoom factor. * @param info the plot rendering info. * @param source the source point. * * @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D, boolean) */ @Override public void zoomRangeAxes(double factor, PlotRenderingInfo info, Point2D source) { // delegate to other method zoomRangeAxes(factor, info, source, false); } /** * Multiplies the range on the range axis/axes by the specified factor. * * @param factor the zoom factor. * @param info the plot rendering info. * @param source the source point. * @param useAnchor a flag that controls whether or not the source point * is used for the zoom anchor. * * @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D, boolean) * * @since 1.0.7 */ @Override public void zoomRangeAxes(double factor, PlotRenderingInfo info, Point2D source, boolean useAnchor) { // perform the zoom on each range axis for (ValueAxis yAxis : this.rangeAxes.values()) { if (yAxis == null) { continue; } if (useAnchor) { // get the relevant source coordinate given the plot orientation double sourceY = source.getY(); if (this.orientation == PlotOrientation.HORIZONTAL) { sourceY = source.getX(); } double anchorY = yAxis.java2DToValue(sourceY, info.getDataArea(), getRangeAxisEdge()); yAxis.resizeRange2(factor, anchorY); } else { yAxis.resizeRange(factor); } } } /** * Zooms in on the range axes. * * @param lowerPercent the lower bound. * @param upperPercent the upper bound. * @param info the plot rendering info. * @param source the source point. * * @see #zoomDomainAxes(double, double, PlotRenderingInfo, Point2D) */ @Override public void zoomRangeAxes(double lowerPercent, double upperPercent, PlotRenderingInfo info, Point2D source) { for (ValueAxis yAxis : this.rangeAxes.values()) { if (yAxis != null) { yAxis.zoomRange(lowerPercent, upperPercent); } } } /** * Returns {@code true}, indicating that the domain axis/axes for this * plot are zoomable. * * @return A boolean. * * @see #isRangeZoomable() */ @Override public boolean isDomainZoomable() { return true; } /** * Returns {@code true}, indicating that the range axis/axes for this * plot are zoomable. * * @return A boolean. * * @see #isDomainZoomable() */ @Override public boolean isRangeZoomable() { return true; } /** * Returns the number of series in the primary dataset for this plot. If * the dataset is {@code null}, the method returns 0. * * @return The series count. */ public int getSeriesCount() { int result = 0; XYDataset dataset = getDataset(); if (dataset != null) { result = dataset.getSeriesCount(); } return result; } /** * Returns the fixed legend items, if any. * * @return The legend items (possibly {@code null}). * * @see #setFixedLegendItems(LegendItemCollection) */ public LegendItemCollection getFixedLegendItems() { return this.fixedLegendItems; } /** * Sets the fixed legend items for the plot. Leave this set to * {@code null} if you prefer the legend items to be created * automatically. * * @param items the legend items ({@code null} permitted). * * @see #getFixedLegendItems() */ public void setFixedLegendItems(LegendItemCollection items) { this.fixedLegendItems = items; fireChangeEvent(); } /** * Returns the legend items for the plot. Each legend item is generated by * the plot's renderer, since the renderer is responsible for the visual * representation of the data. * * @return The legend items. */ @Override public LegendItemCollection getLegendItems() { if (this.fixedLegendItems != null) { return this.fixedLegendItems; } LegendItemCollection result = new LegendItemCollection(); for (XYDataset dataset : this.datasets.values()) { if (dataset == null) { continue; } int datasetIndex = indexOf(dataset); XYItemRenderer renderer = getRenderer(datasetIndex); if (renderer == null) { renderer = getRenderer(0); } if (renderer != null) { int seriesCount = dataset.getSeriesCount(); for (int i = 0; i < seriesCount; i++) { if (renderer.isSeriesVisible(i) && renderer.isSeriesVisibleInLegend(i)) { LegendItem item = renderer.getLegendItem( datasetIndex, i); if (item != null) { result.add(item); } } } } } return result; } /** * Tests this plot for equality with another object. * * @param obj the object ({@code null} permitted). * * @return {@code true} or {@code false}. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof XYPlot)) { return false; } XYPlot that = (XYPlot) obj; if (this.weight != that.weight) { return false; } if (this.orientation != that.orientation) { return false; } if (!this.domainAxes.equals(that.domainAxes)) { return false; } if (!this.domainAxisLocations.equals(that.domainAxisLocations)) { return false; } if (this.rangeCrosshairLockedOnData != that.rangeCrosshairLockedOnData) { return false; } if (this.domainGridlinesVisible != that.domainGridlinesVisible) { return false; } if (this.rangeGridlinesVisible != that.rangeGridlinesVisible) { return false; } if (this.domainMinorGridlinesVisible != that.domainMinorGridlinesVisible) { return false; } if (this.rangeMinorGridlinesVisible != that.rangeMinorGridlinesVisible) { return false; } if (this.domainZeroBaselineVisible != that.domainZeroBaselineVisible) { return false; } if (this.rangeZeroBaselineVisible != that.rangeZeroBaselineVisible) { return false; } if (this.domainCrosshairVisible != that.domainCrosshairVisible) { return false; } if (this.domainCrosshairValue != that.domainCrosshairValue) { return false; } if (this.domainCrosshairLockedOnData != that.domainCrosshairLockedOnData) { return false; } if (this.rangeCrosshairVisible != that.rangeCrosshairVisible) { return false; } if (this.rangeCrosshairValue != that.rangeCrosshairValue) { return false; } if (!ObjectUtilities.equal(this.axisOffset, that.axisOffset)) { return false; } if (!ObjectUtilities.equal(this.renderers, that.renderers)) { return false; } if (!ObjectUtilities.equal(this.rangeAxes, that.rangeAxes)) { return false; } if (!this.rangeAxisLocations.equals(that.rangeAxisLocations)) { return false; } if (!ObjectUtilities.equal(this.datasetToDomainAxesMap, that.datasetToDomainAxesMap)) { return false; } if (!ObjectUtilities.equal(this.datasetToRangeAxesMap, that.datasetToRangeAxesMap)) { return false; } if (!ObjectUtilities.equal(this.domainGridlineStroke, that.domainGridlineStroke)) { return false; } if (!PaintUtilities.equal(this.domainGridlinePaint, that.domainGridlinePaint)) { return false; } if (!ObjectUtilities.equal(this.rangeGridlineStroke, that.rangeGridlineStroke)) { return false; } if (!PaintUtilities.equal(this.rangeGridlinePaint, that.rangeGridlinePaint)) { return false; } if (!ObjectUtilities.equal(this.domainMinorGridlineStroke, that.domainMinorGridlineStroke)) { return false; } if (!PaintUtilities.equal(this.domainMinorGridlinePaint, that.domainMinorGridlinePaint)) { return false; } if (!ObjectUtilities.equal(this.rangeMinorGridlineStroke, that.rangeMinorGridlineStroke)) { return false; } if (!PaintUtilities.equal(this.rangeMinorGridlinePaint, that.rangeMinorGridlinePaint)) { return false; } if (!PaintUtilities.equal(this.domainZeroBaselinePaint, that.domainZeroBaselinePaint)) { return false; } if (!ObjectUtilities.equal(this.domainZeroBaselineStroke, that.domainZeroBaselineStroke)) { return false; } if (!PaintUtilities.equal(this.rangeZeroBaselinePaint, that.rangeZeroBaselinePaint)) { return false; } if (!ObjectUtilities.equal(this.rangeZeroBaselineStroke, that.rangeZeroBaselineStroke)) { return false; } if (!ObjectUtilities.equal(this.domainCrosshairStroke, that.domainCrosshairStroke)) { return false; } if (!PaintUtilities.equal(this.domainCrosshairPaint, that.domainCrosshairPaint)) { return false; } if (!ObjectUtilities.equal(this.rangeCrosshairStroke, that.rangeCrosshairStroke)) { return false; } if (!PaintUtilities.equal(this.rangeCrosshairPaint, that.rangeCrosshairPaint)) { return false; } if (!ObjectUtilities.equal(this.foregroundDomainMarkers, that.foregroundDomainMarkers)) { return false; } if (!ObjectUtilities.equal(this.backgroundDomainMarkers, that.backgroundDomainMarkers)) { return false; } if (!ObjectUtilities.equal(this.foregroundRangeMarkers, that.foregroundRangeMarkers)) { return false; } if (!ObjectUtilities.equal(this.backgroundRangeMarkers, that.backgroundRangeMarkers)) { return false; } if (!ObjectUtilities.equal(this.foregroundDomainMarkers, that.foregroundDomainMarkers)) { return false; } if (!ObjectUtilities.equal(this.backgroundDomainMarkers, that.backgroundDomainMarkers)) { return false; } if (!ObjectUtilities.equal(this.foregroundRangeMarkers, that.foregroundRangeMarkers)) { return false; } if (!ObjectUtilities.equal(this.backgroundRangeMarkers, that.backgroundRangeMarkers)) { return false; } if (!ObjectUtilities.equal(this.annotations, that.annotations)) { return false; } if (!ObjectUtilities.equal(this.fixedLegendItems, that.fixedLegendItems)) { return false; } if (!PaintUtilities.equal(this.domainTickBandPaint, that.domainTickBandPaint)) { return false; } if (!PaintUtilities.equal(this.rangeTickBandPaint, that.rangeTickBandPaint)) { return false; } if (!this.quadrantOrigin.equals(that.quadrantOrigin)) { return false; } for (int i = 0; i < 4; i++) { if (!PaintUtilities.equal(this.quadrantPaint[i], that.quadrantPaint[i])) { return false; } } if (!ObjectUtilities.equal(this.shadowGenerator, that.shadowGenerator)) { return false; } return super.equals(obj); } /** * Returns a clone of the plot. * * @return A clone. * * @throws CloneNotSupportedException this can occur if some component of * the plot cannot be cloned. */ @Override public Object clone() throws CloneNotSupportedException { XYPlot clone = (XYPlot) super.clone(); clone.domainAxes = CloneUtils.cloneMapValues(this.domainAxes); for (ValueAxis axis : clone.domainAxes.values()) { if (axis != null) { axis.setPlot(clone); axis.addChangeListener(clone); } } clone.rangeAxes = CloneUtils.cloneMapValues(this.rangeAxes); for (ValueAxis axis : clone.rangeAxes.values()) { if (axis != null) { axis.setPlot(clone); axis.addChangeListener(clone); } } clone.domainAxisLocations = new HashMap<Integer, AxisLocation>( this.domainAxisLocations); clone.rangeAxisLocations = new HashMap<Integer, AxisLocation>( this.rangeAxisLocations); // the datasets are not cloned, but listeners need to be added... clone.datasets = new HashMap<Integer, XYDataset>(this.datasets); for (XYDataset dataset : clone.datasets.values()) { if (dataset != null) { dataset.addChangeListener(clone); } } clone.datasetToDomainAxesMap = new TreeMap(); clone.datasetToDomainAxesMap.putAll(this.datasetToDomainAxesMap); clone.datasetToRangeAxesMap = new TreeMap(); clone.datasetToRangeAxesMap.putAll(this.datasetToRangeAxesMap); clone.renderers = CloneUtils.cloneMapValues(this.renderers); for (XYItemRenderer renderer : clone.renderers.values()) { if (renderer != null) { renderer.setPlot(clone); renderer.addChangeListener(clone); } } clone.foregroundDomainMarkers = (Map) ObjectUtilities.clone( this.foregroundDomainMarkers); clone.backgroundDomainMarkers = (Map) ObjectUtilities.clone( this.backgroundDomainMarkers); clone.foregroundRangeMarkers = (Map) ObjectUtilities.clone( this.foregroundRangeMarkers); clone.backgroundRangeMarkers = (Map) ObjectUtilities.clone( this.backgroundRangeMarkers); clone.annotations = (List) ObjectUtilities.deepClone(this.annotations); if (this.fixedDomainAxisSpace != null) { clone.fixedDomainAxisSpace = (AxisSpace) ObjectUtilities.clone( this.fixedDomainAxisSpace); } if (this.fixedRangeAxisSpace != null) { clone.fixedRangeAxisSpace = (AxisSpace) ObjectUtilities.clone( this.fixedRangeAxisSpace); } if (this.fixedLegendItems != null) { clone.fixedLegendItems = (LegendItemCollection) this.fixedLegendItems.clone(); } clone.quadrantOrigin = (Point2D) ObjectUtilities.clone( this.quadrantOrigin); clone.quadrantPaint = this.quadrantPaint.clone(); return clone; } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writeStroke(this.domainGridlineStroke, stream); SerialUtilities.writePaint(this.domainGridlinePaint, stream); SerialUtilities.writeStroke(this.rangeGridlineStroke, stream); SerialUtilities.writePaint(this.rangeGridlinePaint, stream); SerialUtilities.writeStroke(this.domainMinorGridlineStroke, stream); SerialUtilities.writePaint(this.domainMinorGridlinePaint, stream); SerialUtilities.writeStroke(this.rangeMinorGridlineStroke, stream); SerialUtilities.writePaint(this.rangeMinorGridlinePaint, stream); SerialUtilities.writeStroke(this.rangeZeroBaselineStroke, stream); SerialUtilities.writePaint(this.rangeZeroBaselinePaint, stream); SerialUtilities.writeStroke(this.domainCrosshairStroke, stream); SerialUtilities.writePaint(this.domainCrosshairPaint, stream); SerialUtilities.writeStroke(this.rangeCrosshairStroke, stream); SerialUtilities.writePaint(this.rangeCrosshairPaint, stream); SerialUtilities.writePaint(this.domainTickBandPaint, stream); SerialUtilities.writePaint(this.rangeTickBandPaint, stream); SerialUtilities.writePoint2D(this.quadrantOrigin, stream); for (int i = 0; i < 4; i++) { SerialUtilities.writePaint(this.quadrantPaint[i], stream); } SerialUtilities.writeStroke(this.domainZeroBaselineStroke, stream); SerialUtilities.writePaint(this.domainZeroBaselinePaint, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.domainGridlineStroke = SerialUtilities.readStroke(stream); this.domainGridlinePaint = SerialUtilities.readPaint(stream); this.rangeGridlineStroke = SerialUtilities.readStroke(stream); this.rangeGridlinePaint = SerialUtilities.readPaint(stream); this.domainMinorGridlineStroke = SerialUtilities.readStroke(stream); this.domainMinorGridlinePaint = SerialUtilities.readPaint(stream); this.rangeMinorGridlineStroke = SerialUtilities.readStroke(stream); this.rangeMinorGridlinePaint = SerialUtilities.readPaint(stream); this.rangeZeroBaselineStroke = SerialUtilities.readStroke(stream); this.rangeZeroBaselinePaint = SerialUtilities.readPaint(stream); this.domainCrosshairStroke = SerialUtilities.readStroke(stream); this.domainCrosshairPaint = SerialUtilities.readPaint(stream); this.rangeCrosshairStroke = SerialUtilities.readStroke(stream); this.rangeCrosshairPaint = SerialUtilities.readPaint(stream); this.domainTickBandPaint = SerialUtilities.readPaint(stream); this.rangeTickBandPaint = SerialUtilities.readPaint(stream); this.quadrantOrigin = SerialUtilities.readPoint2D(stream); this.quadrantPaint = new Paint[4]; for (int i = 0; i < 4; i++) { this.quadrantPaint[i] = SerialUtilities.readPaint(stream); } this.domainZeroBaselineStroke = SerialUtilities.readStroke(stream); this.domainZeroBaselinePaint = SerialUtilities.readPaint(stream); // register the plot as a listener with its axes, datasets, and // renderers... for (ValueAxis axis : this.domainAxes.values()) { if (axis != null) { axis.setPlot(this); axis.addChangeListener(this); } } for (ValueAxis axis : this.rangeAxes.values()) { if (axis != null) { axis.setPlot(this); axis.addChangeListener(this); } } for (XYDataset dataset : this.datasets.values()) { if (dataset != null) { dataset.addChangeListener(this); } } for (XYItemRenderer renderer : this.renderers.values()) { if (renderer != null) { renderer.addChangeListener(this); } } } }
package org.jpc.query; import java.lang.reflect.Type; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.jpc.Jpc; import org.jpc.engine.prolog.PrologEngine; import org.jpc.term.Term; import org.jpc.term.Variable; public class QuerySolution implements Map<String,Term> { public static final String EXCEPTION_VAR_NAME = "JPC_EXCEPTION_VAR"; private PrologEngine prologEngine; private Map<String, Term> solution; private Jpc context; private Term errorTerm; public QuerySolution(Map<String, Term> solution, PrologEngine prologEngine, Jpc context) { this.solution = new HashMap<>(solution); this.prologEngine = prologEngine; this.context = context; configure(); } private void configure() { if(solution.containsKey(EXCEPTION_VAR_NAME)) { Term errorTerm = solution.get(EXCEPTION_VAR_NAME); if(!(errorTerm instanceof Variable)) { this.errorTerm = errorTerm; } solution.remove(EXCEPTION_VAR_NAME); } } public boolean isError() { return errorTerm != null; } public Term getErrorTerm() { return errorTerm; } @Override public int size() { return solution.size(); } @Override public boolean isEmpty() { return solution.isEmpty(); } @Override public boolean containsKey(Object key) { return solution.containsKey(key); } @Override public boolean containsValue(Object value) { return solution.containsValue(value); } @Override public Term get(Object key) { return solution.get(key); } @Override public Term put(String key, Term value) { throw new UnsupportedOperationException(); } @Override public Term remove(Object key) { throw new UnsupportedOperationException(); } @Override public void putAll(Map<? extends String, ? extends Term> m) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public Set<String> keySet() { return solution.keySet(); } @Override public Collection<Term> values() { return solution.values(); } @Override public Set<java.util.Map.Entry<String, Term>> entrySet() { return solution.entrySet(); } public Byte getByte(String key) { return getObject(key, Byte.class); } public Short getShort(String key) { return getObject(key, Short.class); } public Integer getInt(String key) { return getObject(key, Integer.class); } public Long getLong(String key) { return getObject(key, Long.class); } public Float getFloat(String key) { return getObject(key, Float.class); } public Double getDouble(String key) { return getObject(key, Double.class); } public Boolean getBoolean(String key) { return getObject(key, Boolean.class); } public Character getChar(String key) { return getObject(key, Character.class); } public String getString(String key) { return getObject(key, String.class); } public <O> O getObject(String key) { return context.fromTerm(get(key)); } public <O> O getObject(String key, Type type) { return context.fromTerm(get(key), type); } public <O> O asObject(String selector) { return asObject(asTerm(selector), Object.class); } public <O> O asObject(String selector, Type targetType) { return asObject(asTerm(selector), targetType); } public <O> O asObject(Term selector) { return asObject(selector, Object.class); } public <O> O asObject(Term selector, Type targetType) { return (O) new TermToObjectFunction(context, targetType).apply(selector); } private Term asTerm(String termString) { return prologEngine.asTerm(termString, context); } }
package org.jtrfp.trcl.flow; import java.awt.Point; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.jtrfp.trcl.Camera; import org.jtrfp.trcl.NAVSystem; import org.jtrfp.trcl.OverworldSystem; import org.jtrfp.trcl.SkySystem; import org.jtrfp.trcl.Tunnel; import org.jtrfp.trcl.World; import org.jtrfp.trcl.beh.Behavior; import org.jtrfp.trcl.beh.CollidesWithTerrain; import org.jtrfp.trcl.beh.CollidesWithTunnelWalls; import org.jtrfp.trcl.beh.HeadingXAlwaysPositiveBehavior; import org.jtrfp.trcl.beh.LoopingPositionBehavior; import org.jtrfp.trcl.beh.MatchDirection; import org.jtrfp.trcl.beh.MatchPosition; import org.jtrfp.trcl.beh.SkyCubeCloudModeUpdateBehavior; import org.jtrfp.trcl.beh.phy.MovesByVelocity; import org.jtrfp.trcl.core.Renderer; import org.jtrfp.trcl.core.ResourceManager; import org.jtrfp.trcl.core.TR; import org.jtrfp.trcl.file.AbstractTriplet; import org.jtrfp.trcl.file.DirectionVector; import org.jtrfp.trcl.file.LVLFile; import org.jtrfp.trcl.file.Location3D; import org.jtrfp.trcl.file.NAVFile.NAVSubObject; import org.jtrfp.trcl.file.NAVFile.START; import org.jtrfp.trcl.file.TDFFile; import org.jtrfp.trcl.flow.LoadingProgressReporter.UpdateHandler; import org.jtrfp.trcl.flow.NAVObjective.Factory; import org.jtrfp.trcl.obj.ObjectDirection; import org.jtrfp.trcl.obj.Player; import org.jtrfp.trcl.obj.PortalExit; import org.jtrfp.trcl.obj.Projectile; import org.jtrfp.trcl.obj.ProjectileFactory; import org.jtrfp.trcl.obj.Propelled; import org.jtrfp.trcl.obj.TunnelEntranceObject; import org.jtrfp.trcl.obj.WorldObject; import org.jtrfp.trcl.snd.GPUResidentMOD; import org.jtrfp.trcl.snd.MusicPlaybackEvent; import org.jtrfp.trcl.snd.SoundSystem; public class Mission { // PROPERTIES public static final String MISSION_MODE = "missionMode"; public static final String SATELLITE_VIEW = "satelliteView"; private final TR tr; private final List<NAVObjective> navs = new LinkedList<NAVObjective>(); private final LVLFile lvl; private final HashMap<String, Tunnel> tunnels = new HashMap<String, Tunnel>(); private final HashMap<Integer, PortalExit> tunnelPortals = new HashMap<Integer, PortalExit>(); private double[] playerStartPosition = new double[3]; private List<NAVSubObject> navSubObjects; private ObjectDirection playerStartDirection; private final Game game; private final String levelName; private OverworldSystem overworldSystem; private final Result[] missionEnd = new Result[]{null}; private int groundTargetsDestroyed=0, airTargetsDestroyed=0, foliageDestroyed=0; private int totalNumTunnels; private final LinkedList<Tunnel> tunnelsRemaining = new LinkedList<Tunnel>(); private final boolean showIntro; private volatile MusicPlaybackEvent bgMusic; private final Object missionLock = new Object(); private final Map<Integer,TunnelEntranceObject> tunnelMap = new HashMap<Integer,TunnelEntranceObject>(); private boolean bossFight = false, satelliteView = false; private MissionMode missionMode = new Mission.LoadingMode(); private final PropertyChangeSupport pcs = new PropertyChangeSupport(this); private Tunnel currentTunnel; private enum LoadingStages { navs, tunnels, overworld }// end LoadingStages public Mission(TR tr, Game game, LVLFile lvl, String levelName, boolean showIntro) { this.tr = tr; this.lvl = lvl; this.game = game; this.levelName = levelName; this.showIntro = showIntro; }// end Mission /* public TRFutureTask<Result> go(){ synchronized(missionTask){ missionTask[0] = tr.getThreadManager().submitToThreadPool(new Callable<Result>(){ @Override public Result call() throws Exception { return _go(); }}); }//end sync{} return missionTask[0]; }//end go() */ public Result go() { setMissionMode(new Mission.LoadingMode()); synchronized(missionLock){ synchronized(missionEnd){ if(missionEnd[0]!=null) return missionEnd[0]; } tr.getThreadManager().setPaused(true); for(ProjectileFactory pf:tr.getResourceManager().getProjectileFactories()) for(Projectile proj:pf.getProjectiles()) proj.destroy(); System.out.println("Starting GampeplayLevel loading sequence..."); final LoadingProgressReporter rootProgress = LoadingProgressReporter.Impl .createRoot(new UpdateHandler() { @Override public void update(double unitProgress) { game.getLevelLoadingScreen().setLoadingProgress(unitProgress); } }); final LoadingProgressReporter[] progressStages = rootProgress .generateSubReporters(LoadingStages.values().length); final Renderer renderer = tr.mainRenderer.get(); renderer.getCamera().probeForBehavior(SkyCubeCloudModeUpdateBehavior.class).setEnable(false); renderer.getSkyCube().setSkyCubeGen(GameShell.DEFAULT_GRADIENT); final Camera camera = renderer.getCamera(); camera.setHeading(Vector3D.PLUS_I); camera.setTop(Vector3D.PLUS_J); game.setDisplayMode(game.levelLoadingMode); game.getUpfrontDisplay().submitPersistentMessage(levelName); try { final ResourceManager rm = tr.getResourceManager(); final Player player = tr.getGame().getPlayer(); final World world = tr.getWorld(); final TDFFile tdf = rm.getTDFData(lvl.getTunnelDefinitionFile()); player.setActive(false); // Abort check synchronized(missionEnd){ if(missionEnd[0]!=null) return missionEnd[0]; } overworldSystem = new OverworldSystem(tr, progressStages[LoadingStages.overworld.ordinal()]); getOverworldSystem().loadLevel(lvl, tdf); System.out.println("\t...Done."); // Install NAVs final NAVSystem navSystem = tr.getGame().getNavSystem(); navSubObjects = rm.getNAVData(lvl.getNavigationFile()) .getNavObjects(); START s = (START) navSubObjects.get(0); Location3D l3d = s.getLocationOnMap(); playerStartPosition[0] = TR.legacy2Modern(l3d.getZ()); playerStartPosition[2] = TR.legacy2Modern(l3d.getX()); final double HEIGHT_PADDING = 10000; playerStartPosition[1] = Math.max(HEIGHT_PADDING + (world.sizeY/2) * getOverworldSystem().getAltitudeMap().heightAt( TR.legacy2MapSquare(l3d.getZ()), TR.legacy2MapSquare(l3d.getX())),TR.legacy2Modern(l3d.getY())); playerStartDirection = new ObjectDirection(s.getRoll(), s.getPitch(), s.getYaw()); // ////// INITIAL HEADING player.setPosition(getPlayerStartPosition()); player.setDirection(getPlayerStartDirection()); player.setHeading(player.getHeading().negate());// Kludge to fix // incorrect heading ///////// STATE final Propelled propelled = player.probeForBehavior(Propelled.class); propelled.setPropulsion(propelled.getMinPropulsion()); installTunnels(tdf,progressStages[LoadingStages.tunnels.ordinal()]); Factory f = new NAVObjective.Factory(tr); final LoadingProgressReporter[] navProgress = progressStages[LoadingStages.navs .ordinal()].generateSubReporters(navSubObjects.size()); for (int i = 0; i < navSubObjects.size(); i++) { final NAVSubObject obj = navSubObjects.get(i); f.create(tr, obj, navs); navProgress[i].complete(); }// end for(navSubObjects) navSystem.updateNAVState(); player.resetVelocityRotMomentum(); final String startX = System.getProperty("org.jtrfp.trcl.startX"); final String startY = System.getProperty("org.jtrfp.trcl.startY"); final String startZ = System.getProperty("org.jtrfp.trcl.startZ"); final double[] playerPos = player.getPosition(); if (startX != null && startY != null && startZ != null) { System.out.println("Using user-specified start point"); final int sX = Integer.parseInt(startX); final int sY = Integer.parseInt(startY); final int sZ = Integer.parseInt(startZ); playerPos[0] = sX; playerPos[1] = sY; playerPos[2] = sZ; player.notifyPositionChange(); }// end if(user start point) System.out.println("Start position set to " + player.getPosition()[0]+" "+player.getPosition()[1]+" "+player.getPosition()[2]); System.out.println("Setting sun vector"); final AbstractTriplet sunVector = lvl.getSunlightDirectionVector(); tr.getThreadManager().submitToGL(new Callable<Void>() { @Override public Void call() throws Exception { tr.mainRenderer.get().setSunVector( new Vector3D(sunVector.getX(), sunVector.getY(), sunVector.getZ()).normalize()); return null; } }).get(); System.out.println("\t...Done."); } catch (Exception e) { e.printStackTrace(); } if (System.getProperties().containsKey( "org.jtrfp.trcl.flow.Mission.skipNavs")) { try { final int skips = Integer.parseInt(System .getProperty("org.jtrfp.trcl.flow.Mission.skipNavs")); System.out.println("Skipping " + skips + " navs."); for (int i = 0; i < skips; i++) { removeNAVObjective(currentNAVObjective()); }// end for(skips) } catch (NumberFormatException e) { System.err .println("Invalid format for property \"org.jtrfp.trcl.flow.Mission.skipNavs\". Must be integer."); } }// end if(containsKey) //System.out.println("Invoking JVM's garbage collector..."); //TR.nuclearGC(); //System.out.println("Mission.go() complete."); // Transition to gameplay mode. // Abort check synchronized (missionEnd) { if (missionEnd[0] != null) return missionEnd[0]; }//end sync(missionEnd) tr.getThreadManager().submitToThreadPool(new Callable<Void>() { @Override public Void call() throws Exception { final SoundSystem ss = Mission.this.tr.soundSystem.get(); MusicPlaybackEvent evt; Mission.this.tr.soundSystem.get().enqueuePlaybackEvent( evt =ss .getMusicFactory() .create(new GPUResidentMOD(tr, tr .getResourceManager().getMOD( lvl.getBackgroundMusicFile())), true)); synchronized(Mission.this){ if(bgMusic!=null) return null; bgMusic=evt; bgMusic.play(); }//end sync(Mission.this) return null; }// end call() }); game.getUpfrontDisplay().removePersistentMessage(); tr.getThreadManager().setPaused(false); if(showIntro){ setMissionMode(new Mission.IntroMode()); game.getBriefingScreen().briefingSequence(lvl); } setMissionMode(new Mission.AboveGroundMode()); final SkySystem skySystem = getOverworldSystem().getSkySystem(); tr.mainRenderer.get().getCamera().probeForBehavior(SkyCubeCloudModeUpdateBehavior.class).setEnable(true); renderer.getSkyCube().setSkyCubeGen(skySystem.getBelowCloudsSkyCubeGen()); renderer.setAmbientLight(skySystem.getSuggestedAmbientLight()); renderer.setSunColor(skySystem.getSuggestedSunColor()); World.relevanceExecutor.submit(new Runnable(){ @Override public void run() { game.getNavSystem() .activate(); getOverworldSystem() .activate(); }}); game.setDisplayMode(game.gameplayMode); game.getPlayer() .setActive(true); tr.getGame().setPaused(false); //Wait for mission end synchronized(missionEnd){ while(missionEnd[0]==null){try{missionEnd.wait();} catch(InterruptedException e){break;}}} //Completion summary if(missionEnd[0]!=null) if(!missionEnd[0].isAbort()){ setMissionMode(new Mission.MissionSummaryMode()); game.getBriefingScreen().missionCompleteSummary(lvl,missionEnd[0]); }//end if(proper ending) tr.getThreadManager().submitToThreadPool(new Callable<Void>() { @Override public Void call() throws Exception { bgMusic.stop(); return null; }// end call() }); cleanup(); return missionEnd[0]; }//end sync }// end go() public NAVObjective currentNAVObjective() { if (navs.isEmpty()) return null; return navs.get(0); }//end currentNAVObjective() public void removeNAVObjective(NAVObjective o) { navs.remove(o); if (navs.size() == 0) { missionCompleteSequence(); } else tr.getGame().getNavSystem().updateNAVState(); }// end removeNAVObjective(...) public static class Result { private final int airTargetsDestroyed, groundTargetsDestroyed,foliageDestroyed; private final double tunnelsFoundPctNorm; private boolean abort=false; public Result(int airTargetsDestroyed, int groundTargetsDestroyed, int foliageDestroyed, double tunnelsFoundPctNorm) { this.airTargetsDestroyed =airTargetsDestroyed; this.groundTargetsDestroyed =groundTargetsDestroyed; this.foliageDestroyed =foliageDestroyed; this.tunnelsFoundPctNorm =tunnelsFoundPctNorm; }//end constructor /** * @return the airTargetsDestroyed */ public int getAirTargetsDestroyed() { return airTargetsDestroyed; } /** * @return the groundTargetsDestroyed */ public int getGroundTargetsDestroyed() { return groundTargetsDestroyed; } /** * @return the foliageDestroyed */ public int getFoliageDestroyed() { return foliageDestroyed; } /** * @return the tunnelsFoundPctNorm */ public double getTunnelsFoundPctNorm() { return tunnelsFoundPctNorm; } /** * @return the abort */ public boolean isAbort() { return abort; } /** * @param abort the abort to set */ public void setAbort(boolean abort) { this.abort = abort; } }// end Result /** * @return the playerStartPosition */ public double[] getPlayerStartPosition() { return playerStartPosition; } /** * @return the playerStartDirection */ public ObjectDirection getPlayerStartDirection() { return playerStartDirection; } private void installTunnels(TDFFile tdf, LoadingProgressReporter reporter){ TDFFile.Tunnel[] tuns = tdf.getTunnels(); tuns = tuns == null?new TDFFile.Tunnel[0]:tuns;//Null means no tunnels. final LoadingProgressReporter[] reporters = reporter .generateSubReporters(tuns.length); if (tuns != null) { int tIndex = 0; // Build tunnels for (TDFFile.Tunnel tun : tuns) { tr .getReporter() .report("org.jtrfp.trcl.TunnelInstaller.tunnel." + tIndex + ".entrance", tun.getEntrance()); tr .getReporter() .report("org.jtrfp.trcl.TunnelInstaller.tunnel." + tIndex + ".exit", tun.getExit()); newTunnel(tun,reporters[tIndex]); tIndex++; }//end if(tuns!=null) }// end if(tuns!=null) totalNumTunnels = tunnelsRemaining.size(); }//end installTunnels() private Tunnel newTunnel(org.jtrfp.trcl.file.TDFFile.Tunnel tun, LoadingProgressReporter reporter) { final Tunnel result = new Tunnel(tr, tun, reporter); DirectionVector v = tun.getEntrance(); tunnelsRemaining.add(result); final Point point = new Point( (int)(TR.legacy2MapSquare(v.getZ())), (int)(TR.legacy2MapSquare(v.getX()))); addTunnelEntrance(point,result); final PortalExit portalExit = getTunnelEntrancePortal(point);//TODO: Returning null portalExit.setPosition(Tunnel.TUNNEL_START_POS.toArray()); portalExit.getControlledCamera();//TODO: Add tunnel to camera tunnels.put(tun.getTunnelLVLFile().toUpperCase(), result); return result; } public Tunnel getTunnelByFileName(String tunnelFileName) { return tunnels.get(tunnelFileName.toUpperCase()); } public TunnelEntranceObject getNearestTunnelEntrance(double xInLegacyUnits, double yInLegacyUnits, double zInLegacyUnits) { TunnelEntranceObject result = null; double closestDistance = Double.POSITIVE_INFINITY; final Vector3D entPos = new Vector3D( TR.legacy2Modern(zInLegacyUnits),//Intentionally backwards TR.legacy2Modern(yInLegacyUnits), TR.legacy2Modern(xInLegacyUnits) ); System.out.println("Requested entry pos="+entPos); for (TunnelEntranceObject teo : tunnelMap.values()) { final Vector3D pos = new Vector3D(teo.getPosition()); System.out.println("Found tunnel at "+pos); final double distance = pos.distance(entPos); if (distance < closestDistance) { closestDistance = distance; result = teo; } }// end for(tunnels) return result; }// end getTunnelWhoseEntranceClosestTo(...) private void missionCompleteSequence() { new Thread() { @Override public void run() { // TODO: Behavior change: Camera XZ static, lag Y by ~16 // squares, heading/top affix toward player // TODO: Turn off all player control behavior // TODO: Behavior change: Player turns upward, top rolls on // heading, speed at full throttle // TODO: Wait 3 seconds // TODO: Lightning shell on // TODO: Wait 1 second // TODO: Turbo forward // TODO: Wait 500ms // TODO: Jet thrust noise // TODO: Player invisible. System.out.println("MISSION COMPLETE."); notifyMissionEnd( new Result( airTargetsDestroyed, groundTargetsDestroyed, foliageDestroyed, 1.-(double)tunnelsRemaining.size()/(double)totalNumTunnels)); }// end run() }.start(); }//end missionCompleteSequence() public void playerDestroyed() { new Thread() { @Override public void run() { // TODO Behavior change: Camera XYZ static, heading/top affix // toward player // TODO: Turn off all player control behavior // TODO Player behavior change: Slow spin along heading axis, // slow downward drift of heading // TODO: Add behavior: explode and destroy on impact with ground System.out.println("MISSION FAILED."); notifyMissionEnd(null); }// end run() }.start(); }// end playerDestroyed() private void notifyMissionEnd(Result r){ synchronized(missionEnd){ missionEnd[0]=r; missionEnd.notifyAll();} }//end notifyMissionEnd() public List<NAVObjective> getRemainingNAVObjectives() { return navs; } /** * @return the navSubObjects */ public List<NAVSubObject> getNavSubObjects() { return navSubObjects; } /** * @param navSubObjects * the navSubObjects to set */ public void setNavSubObjects(List<NAVSubObject> navSubObjects) { this.navSubObjects = navSubObjects; } public void missionComplete() { missionCompleteSequence(); } public OverworldSystem getOverworldSystem() { return overworldSystem; } public Mission notifyAirTargetDestroyed(){ airTargetsDestroyed++; return this; } public Mission notifyGroundTargetDestroyed(){ groundTargetsDestroyed++; return this; } public Mission notifyTunnelFound(Tunnel tun){ tunnelsRemaining.remove(tun); return this; } public Mission notifyFoliageDestroyed(){ foliageDestroyed++; return this; } public void enterBossMode(final String bossMusicFile){ setBossFight(true); tr.getThreadManager().submitToThreadPool(new Callable<Void>() { @Override public Void call() throws Exception { MusicPlaybackEvent evt; final SoundSystem ss = Mission.this.tr.soundSystem.get(); Mission.this.tr.soundSystem.get().enqueuePlaybackEvent( evt =ss .getMusicFactory() .create(tr.getResourceManager().gpuResidentMODs.get(bossMusicFile), true)); synchronized(Mission.this){ evt.play(); if(bgMusic!=null) bgMusic.stop(); bgMusic=evt; } return null; }// end call() }); }//end enterBossMode() public void exitBossMode(){ setBossFight(false); tr.getThreadManager().submitToThreadPool(new Callable<Void>() { @Override public Void call() throws Exception { MusicPlaybackEvent evt; final SoundSystem ss = Mission.this.tr.soundSystem.get(); Mission.this.tr.soundSystem.get().enqueuePlaybackEvent( evt =ss .getMusicFactory() .create(tr.getResourceManager().gpuResidentMODs.get(lvl.getBackgroundMusicFile()), true)); synchronized(Mission.this){ evt.play(); bgMusic.stop(); bgMusic=evt;} return null; }// end call() }); }//end exitBossMode() public void abort() { final Result result = new Result( airTargetsDestroyed, groundTargetsDestroyed, foliageDestroyed, 1.-(double)tunnelsRemaining.size()/(double)totalNumTunnels); result.setAbort(true); notifyMissionEnd(result); //Wait for mission to end synchronized(missionLock){//Don't execute while mission is in progress. cleanup(); }//end sync{} }//end abort() private void cleanup() { try{World.relevanceExecutor.submit(new Runnable(){ @Override public void run() { if(overworldSystem!=null) overworldSystem.deactivate(); }}).get();}catch(Exception e){e.printStackTrace();} } /** * Find a tunnel at the given map square, if any. * @param mapSquareXZ Position in cells, not world coords. * @return The Tunnel at this map square, or null if none here. * @since Jan 13, 2015 */ public TunnelEntranceObject getTunnelEntranceObject(Point mapSquareXZ){ final int key = pointToHash(mapSquareXZ); System.out.println("getTunnelEntranceObject "+mapSquareXZ); for(TunnelEntranceObject teo:tunnelMap.values()) System.out.print(" "+new Vector3D(teo.getPosition()).scalarMultiply(1/TR.mapSquareSize)); System.out.println(); return tunnelMap.get(key); } public void registerTunnelEntrancePortal(Point mapSquareXZ, PortalExit exit){ tunnelPortals.put(pointToHash(mapSquareXZ),exit); } PortalExit getTunnelEntrancePortal(Point mapSquareXZ){ return tunnelPortals.get(pointToHash(mapSquareXZ)); } public void addTunnelEntrance(Point mapSquareXZ, Tunnel tunnel){ TunnelEntranceObject teo; overworldSystem.add(teo = new TunnelEntranceObject(tr,tunnel)); tunnelMap.put(pointToHash(mapSquareXZ),teo); } private int pointToHash(Point point){ final int key =(int)point.getX()+(int)point.getY()*65536; return key; } public void enterTunnel(final Tunnel tunnel) { final Game game = tr.getGame(); final OverworldSystem overworldSystem = game.getCurrentMission().getOverworldSystem(); currentTunnel = tunnel; game.getCurrentMission().notifyTunnelFound(tunnel); setMissionMode(new TunnelMode()); tunnel.blockingActivate(); overworldSystem.nonBlockingDeactivate(); //Move player to tunnel tr.mainRenderer.get().getSkyCube().setSkyCubeGen(Tunnel.TUNNEL_SKYCUBE_GEN); //Ensure chamber mode is off overworldSystem.setChamberMode(false); overworldSystem.setTunnelMode(true); //Update debug data tr.getReporter().report("org.jtrfp.Tunnel.isInTunnel?", "true"); final ProjectileFactory [] pfs = tr.getResourceManager().getProjectileFactories(); for(ProjectileFactory pf:pfs){ Projectile [] projectiles = pf.getProjectiles(); for(Projectile proj:projectiles){ ((WorldObject)proj). getBehavior(). probeForBehavior(LoopingPositionBehavior.class). setEnable(false); }//end for(projectiles) }//end for(projectileFactories) final Player player = tr.getGame().getPlayer(); player.setActive(false); player.resetVelocityRotMomentum(); final Behavior playerBehavior = player.getBehavior(); playerBehavior.probeForBehavior(CollidesWithTunnelWalls.class).setEnable(true); playerBehavior.probeForBehavior(MovesByVelocity.class).setVelocity(Vector3D.ZERO); playerBehavior.probeForBehavior(LoopingPositionBehavior.class).setEnable(false); playerBehavior.probeForBehavior(HeadingXAlwaysPositiveBehavior.class).setEnable(true); playerBehavior.probeForBehavior(CollidesWithTerrain.class).setEnable(false); //entranceObject.getBehavior().probeForBehaviors(TELsubmitter, TunnelEntryListener.class); tunnel.dispatchTunnelEntryNotifications(); player.setPosition(Tunnel.TUNNEL_START_POS.toArray()); player.setDirection(Tunnel.TUNNEL_START_DIRECTION); player.notifyPositionChange(); /* final NAVObjective navObjective = getNavObjectiveToRemove(); if(navObjective!=null && navTargeted){ final Mission m = game.getCurrentMission(); if(!(onlyRemoveIfCurrent&&navObjective!=m.currentNAVObjective()))m.removeNAVObjective(navObjective); }//end if(have NAV to remove */ player.setActive(true); /* try{World.relevanceExecutor.submit(new Runnable(){ @Override public void run() { //Turn off overworld //overworldSystem.deactivate(); //Turn on tunnel //tunnel.activate(); }}).get();}catch(Exception e){throw new RuntimeException(e);} */ }//end enterTunnel() /** * @param listener * @see java.beans.PropertyChangeSupport#addPropertyChangeListener(java.beans.PropertyChangeListener) */ public void addPropertyChangeListener(PropertyChangeListener listener) { pcs.addPropertyChangeListener(listener); } /** * @param propertyName * @param listener * @see java.beans.PropertyChangeSupport#addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) */ public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { pcs.addPropertyChangeListener(propertyName, listener); } /** * @return * @see java.beans.PropertyChangeSupport#getPropertyChangeListeners() */ public PropertyChangeListener[] getPropertyChangeListeners() { return pcs.getPropertyChangeListeners(); } /** * @param propertyName * @return * @see java.beans.PropertyChangeSupport#getPropertyChangeListeners(java.lang.String) */ public PropertyChangeListener[] getPropertyChangeListeners( String propertyName) { return pcs.getPropertyChangeListeners(propertyName); } /** * @param propertyName * @return * @see java.beans.PropertyChangeSupport#hasListeners(java.lang.String) */ public boolean hasListeners(String propertyName) { return pcs.hasListeners(propertyName); } /** * @param listener * @see java.beans.PropertyChangeSupport#removePropertyChangeListener(java.beans.PropertyChangeListener) */ public void removePropertyChangeListener(PropertyChangeListener listener) { pcs.removePropertyChangeListener(listener); } /** * @param propertyName * @param listener * @see java.beans.PropertyChangeSupport#removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) */ public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { pcs.removePropertyChangeListener(propertyName, listener); } public static interface MissionMode{} public static class LoadingMode implements MissionMode{} public static class BriefingMode implements MissionMode{} public static class IntroMode extends BriefingMode{} public static class EnemyIntroMode extends IntroMode{} public static class PlanetIntroMode extends IntroMode{} public static class MissionSummaryMode extends BriefingMode{} public static class GameplayMode implements MissionMode{} public static class TunnelMode extends GameplayMode{} public static class ChamberMode extends GameplayMode{} public static class AboveGroundMode extends GameplayMode{} /** * @return the missionMode */ public MissionMode getMissionMode() { return missionMode; } /** * @param missionMode the missionMode to set */ public void setMissionMode(MissionMode missionMode) { pcs.firePropertyChange(MISSION_MODE, this.missionMode, missionMode); this.missionMode = missionMode; } /** * @return the bossFight */ public boolean isBossFight() { return bossFight; } /** * @param bossFight the bossFight to set */ public void setBossFight(boolean bossFight) { pcs.firePropertyChange("bossFight", this.bossFight, bossFight); this.bossFight = bossFight; } public void setSatelliteView(boolean satelliteView) { if(!(getMissionMode() instanceof AboveGroundMode)&&satelliteView) throw new IllegalArgumentException("Cannot activate satellite view while mission mode is "+getMissionMode().getClass().getSimpleName()); if(satelliteView && tr.getGame().isPaused()) throw new IllegalArgumentException("Cannot activate satellite view while paused."); pcs.firePropertyChange(SATELLITE_VIEW, this.satelliteView, satelliteView); if(satelliteView!=this.satelliteView){ final Game game = tr.getGame(); final Camera cam = tr.mainRenderer.get().getCamera(); if(satelliteView){//Switched on tr.getThreadManager().setPaused(true); World.relevanceExecutor.submit(new Runnable(){ @Override public void run() { game.getNavSystem().deactivate(); game.getHUDSystem().deactivate(); }}); cam.setFogEnabled(false); cam.probeForBehavior(MatchPosition.class).setEnable(false); cam.probeForBehavior(MatchDirection.class).setEnable(false); final Vector3D pPos = new Vector3D(game.getPlayer().getPosition()); final Vector3D pHeading = tr.getGame().getPlayer().getHeading(); cam.setPosition(new Vector3D(pPos.getX(),TR.mapSquareSize*25,pPos.getZ())); cam.setHeading(Vector3D.MINUS_J); cam.setTop(new Vector3D(pHeading.getX(),.0000000001,pHeading.getZ()).normalize()); tr.getGame().getSatDashboard().setVisible(true); }else{//Switched off tr.getThreadManager().setPaused(false); World.relevanceExecutor.submit(new Runnable(){ @Override public void run() { tr.getGame().getNavSystem().activate(); game.getHUDSystem().activate(); }}); cam.setFogEnabled(true); cam.probeForBehavior(MatchPosition.class).setEnable(true); cam.probeForBehavior(MatchDirection.class).setEnable(true); tr.getGame().getSatDashboard().setVisible(false); }//end !satelliteView }//end if(change) this.satelliteView=satelliteView; } /** * @return the satelliteView */ public boolean isSatelliteView() { System.out.println("isSatelliteView="+satelliteView); return satelliteView; } public Tunnel getCurrentTunnel() { if(!(getMissionMode() instanceof TunnelMode))return null; return currentTunnel; } }// end Mission
package jp.ac.kansai_u.kutc.firefly.packetcam.readpcap; import java.io.File; import java.io.IOException; import android.util.Log; import org.jnetstream.capture.Captures; import org.jnetstream.capture.FileMode; import org.jnetstream.capture.file.pcap.PcapFile; /** * readpcap * @author akasaka */ public class PcapManager { private static PcapManager instance = new PcapManager(); private PcapFile pcapFile; /** * * @return */ public static PcapManager getInstance(){ return instance; } private PcapManager(){ pcapFile = null; } /** * PcapFile * @param path * @return b */ public boolean openPcapFile(String path){ if(pcapFile.isOpen()){ // PcapFile closePcapFile(); pcapFile = null; } try { pcapFile = Captures.openFile(PcapFile.class, new File(path), FileMode.ReadOnly); } catch (IOException e) { Log.d("PcapManager.java", "FAILED TO OPEN"); return false; } return true; } /** * PcapFile * */ public void closePcapFile(){ try { pcapFile.close(); } catch (IOException e) { Log.d("PcapManager.java", "FAILED TO CLOSE"); } } /** * PcapFilenull * @return PcapFile null */ public PcapFile getPcapFile(){ return pcapFile; } }
package org.lantern; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.security.SecureRandom; import java.util.Collection; import java.util.Timer; import java.util.TimerTask; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.SystemUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.lantern.event.Events; import org.lantern.event.MessageEvent; import org.lantern.state.Model; import org.lantern.state.Notification.MessageType; import org.lantern.util.HttpClientFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Optional; import com.google.common.collect.Lists; import com.google.common.io.Files; /** * This class continually fetches new Lantern configuration files on S3, * dispatching events to any interested classes when and if a new configuration * file is found. */ public class S3ConfigFetcher { private static final Logger log = LoggerFactory.getLogger(S3ConfigFetcher.class); // DRY: wrapper.install4j and configureUbuntu.txt private static final String URL_FILENAME = ".lantern-configurl.txt"; private final Optional<String> url; private final SecureRandom random = new SecureRandom(); private static final File URL_CONFIG_FILE = new File(LanternClientConstants.CONFIG_DIR, URL_FILENAME); private final Timer configCheckTimer = new Timer("S3-Config-Check", true); private final Model model; /** * Creates a new class for fetching the Lantern config from S3. * * @param model The persistent settings. */ public S3ConfigFetcher(final Model model) { log.debug("Creating s3 config fetcher..."); this.model = model; this.url = readUrl(); } public void start() { log.debug("Starting config loading..."); if (LanternUtils.isFallbackProxy()) { return; } if (!this.url.isPresent()) { log.debug("No url to use for downloading config"); return; } final S3Config config = model.getS3Config(); // Always check for a new config right away. We do this on the same // thread here because a lot depends on this value, particularly on // the first run of Lantern, and we want to make sure it takes priority. if (config != null) { // The config in the model could just be the default, so check // for actual fallbacks. final Collection<FallbackProxy> fallbacks = config.getFallbacks(); if (fallbacks == null || fallbacks.isEmpty()) { recheck(); } else { log.debug("Using existing config..."); Events.asyncEventBus().post(config); // If we've already got valid fallbacks, thread this so we // don't hold up the rest of Lantern initialization. scheduleConfigRecheck(0.0); } } else { recheck(); } } private void scheduleConfigRecheck(final double minutesToSleep) { log.debug("Scheduling config check..."); configCheckTimer.schedule(new TimerTask() { @Override public void run() { recheck(); } }, (long)(minutesToSleep * 60000)); } private void recheck() { recheckConfig(); final S3Config config = model.getS3Config(); final double newMinutesToSleep // Temporary network problems? Let's retry in a few seconds. = (config == null) ? 0.2 : lerp(config.getMinpoll(), config.getMaxpoll(), random.nextDouble()); scheduleConfigRecheck(newMinutesToSleep); } private void recheckConfig() { log.debug("Rechecking configuration"); final Optional<S3Config> newConfig = fetchConfig(); if (!newConfig.isPresent()) { log.error("Couldn't get new config."); return; } final S3Config config = this.model.getS3Config(); this.model.setS3Config(newConfig.get()); boolean changed; if (config == null) { log.warn("Rechecking config with no old one."); changed = true; } else { changed = !newConfig.get().equals(config); } if (changed) { log.info("Configuration changed! Reapplying..."); Events.eventBus().post(newConfig.get()); } else { log.debug("Configuration unchanged."); } } /** Linear interpolation. */ private double lerp(double a, double b, double t) { return a + (b - a) * t; } private Optional<String> readUrl() { try { copyUrlFile(); if (!URL_CONFIG_FILE.isFile()) { log.error("Still no config file at {}", URL_CONFIG_FILE); return Optional.absent(); } } catch (final IOException e) { log.warn("Couldn't copy config URL file?", e); return Optional.absent(); } try { final String folder = FileUtils.readFileToString(URL_CONFIG_FILE, "UTF-8"); return Optional.of(LanternConstants.S3_CONFIG_BASE_URL + folder.trim() + "/config.json"); } catch (final IOException e) { log.error("Couldn't read config URL file?", e); } return Optional.absent(); } private Optional<S3Config> fetchConfig() { if (!url.isPresent()) { log.error("URL initialization failed."); return Optional.absent(); } final HttpClient client = HttpClientFactory.newDirectClient(); final HttpGet get = new HttpGet(url.get()); InputStream is = null; try { final HttpResponse res = client.execute(get); is = res.getEntity().getContent(); final String cfgStr = IOUtils.toString(is); final S3Config cfg = JsonUtils.OBJECT_MAPPER.readValue(cfgStr, S3Config.class); log.debug("Controller: " + cfg.getController()); log.debug("Minimum poll time: " + cfg.getMinpoll()); log.debug("Maximum poll time: " + cfg.getMaxpoll()); for (final FallbackProxy fp : cfg.getFallbacks()) { log.debug("Proxy: " + fp); } return Optional.of(cfg); } catch (final IOException e) { log.error("Couldn't fetch config at "+url.get(), e); } finally { IOUtils.closeQuietly(is); get.reset(); } return Optional.absent(); } private void copyUrlFile() throws IOException { log.debug("Copying config URL file"); final Collection<File> filesToTry = Lists.newArrayList( new File(SystemUtils.getUserHome(), URL_FILENAME), new File(SystemUtils.getUserDir(), URL_FILENAME) ); if (SystemUtils.IS_OS_WINDOWS) { filesToTry.add(new File(System.getenv("APPDATA"))); } final File par = LanternClientConstants.CONFIG_DIR; if (!par.isDirectory() && !par.mkdirs()) { log.error("Could not make config dir at "+par); throw new IOException("Could not make config dir at "+par); } for (final File from : filesToTry) { if (!from.getParentFile().isDirectory()) { log.error("Parent file is not a directory at {}", from.getParentFile()); } if (from.isFile() && isFileNewer(from, URL_CONFIG_FILE)) { log.debug("Copying from {} to {}", from, URL_CONFIG_FILE); Files.copy(from, URL_CONFIG_FILE); return; } else { log.debug("No config file at {}", from); } } if (!URL_CONFIG_FILE.isFile()) { // If we exit the loop and end up here it means we could not find // a config file to copy in any of the expected locations. log.error("Config file not found at any of {}", filesToTry); Events.asyncEventBus().post( new MessageEvent(Tr.tr(MessageKey.NO_CONFIG), MessageType.error)); } } private boolean isFileNewer(final File file, final File reference) { if (reference == null || !reference.isFile()) { return true; } return FileUtils.isFileNewer(file, reference); } }
package org.lightmare.config; import java.util.Arrays; import java.util.HashSet; import org.lightmare.cache.DeploymentDirectory; /** * Keeps keys and default values for configuration * * @author Levan * */ public enum Config { // Default properties // Path where stored administrative users ADMIN_USERS_PATH("adminUsersPath", "./config/admin/users.properties"), // Netty server / client configuration properties for RPC calls IP_ADDRESS("listeningIp", "0.0.0.0"), PORT("listeningPort", "1199"), // port BOSS_POOL("bossPoolSize", 1), // boss pool WORKER_POOL_KEY("workerPoolSize", 3), // Worker pool CONNECTION_TIMEOUT("timeout", 1000), // Connection timeout // Properties for data source path and deployment path DEMPLOYMENT_PATH("deploymentPath", new HashSet<DeploymentDirectory>( Arrays.asList(new DeploymentDirectory("./deploy", Boolean.TRUE)))), DATA_SOURCE_PATH("dataSourcePath", new HashSet<String>( Arrays.asList("./ds"))), // data // source // path // Properties which version of server is running remote it requires server // client RPC infrastructure or local (embedded mode) SERVER("server", Boolean.TRUE), REMOTE("remote", Boolean.FALSE), CLIENT_KEY("client", Boolean.FALSE), // Configuration keys properties for deployment DEPLOY_CONFIG("deployConfiguration"), // Deploy config ADMIN_USER_PATH("adminPath"); // Admin user path HOT_DEPLOYMENT("hotDeployment"); //Hot deployment private static final String WATCH_STATUS_KEY = "watchStatus"; private static final String LIBRARY_PATH_KEY = "libraryPaths"; // Persistence provider property keys private static final String PERSISTENCE_CONFIG_KEY = "persistenceConfig"; private static final String SCAN_FOR_ENTITIES_KEY = "scanForEntities"; private static final String ANNOTATED_UNIT_NAME_KEY = "annotatedUnitName"; private static final String PERSISTENCE_XML_PATH_KEY = "persistanceXmlPath"; private static final String PERSISTENCE_XML_FROM_JAR_KEY = "persistenceXmlFromJar"; private static final String SWAP_DATASOURCE_KEY = "swapDataSource"; private static final String SCAN_ARCHIVES_KEY = "scanArchives"; private static final String POOLED_DATA_SOURCE_KEY = "pooledDataSource"; private static final String PERSISTENCE_PROPERTIES_KEY = "persistenceProperties"; // Connection pool provider property keys private static final String POOL_CONFIG_KEY = "poolConfig"; private static final String POOL_PROPERTIES_PATH_KEY = "poolPropertiesPath"; private static final String POOL_PROVIDER_TYPE_KEY = "poolProviderType"; private static final String POOL_PROPERTIES_KEY = "poolProperties"; public String key; public Object value; private Config(String key) { this.key = key; } private Config(String key, Object value) { this(key); this.value = value; } }
package org.normandra; public interface Transactional { /** * close session, release any associated resources */ void close(); /** * executes a worker within a transaction context */ void withTransaction(Runnable worker) throws NormandraException; /** * start transaction or unit of work * * @return Returns a transaction instance, which should be closed. */ Transaction beginTransaction() throws NormandraException; /** * @return Returns true if we have begun a unit of work (i.e. transaction). */ boolean pendingWork(); /** * being unit of work */ void beginWork() throws NormandraException; /** * commit unit of work, executing any stored/batched operations */ void commitWork() throws NormandraException; /** * rollback unit of work, clearing stored/batched operations */ void rollbackWork() throws NormandraException; }
package org.omo.jms; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.concurrent.Executor; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageListener; import javax.jms.MessageProducer; import javax.jms.ObjectMessage; import javax.jms.Session; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; // TODO: reuse more code between these classes... // TODO: support topic/multi-shot result aggregation // TODO: server should probably support a lifecycle ? // TODO: test multiple client/topic/multiple server scenarios... public class RemotingFactory<T> { private final Session session; private final Class<?> interfaze; private final SimpleMethodMapper mapper; private final long timeout; private final MessageProducer producer; public RemotingFactory(Session session, Class<?> interfaze, long timeout) throws JMSException { this.session = session; this.interfaze = interfaze; this.mapper = new SimpleMethodMapper(interfaze); this.timeout = timeout; producer = session.createProducer(null); } public class Server implements MessageListener { private final Log log; private final T target; private final MessageConsumer consumer; private final Executor executor; public Server(T target, Destination destination, Executor executor) throws JMSException { this.target = target; this.executor = executor; log = LogFactory.getLog(Server.class); consumer = session.createConsumer(destination); // permanently allocates a thread... and an fd ? log.info("consuming messages on: " + destination); consumer.setMessageListener(this); } @Override public void onMessage(final Message message) { Runnable runnable = new Runnable() { @Override public void run() { process(message); } }; executor.execute(runnable); } public void process(Message message) { String correlationId = null; Destination replyTo = null; boolean isException = false; Object result = null; // input try { correlationId = message.getJMSCorrelationID(); replyTo = message.getJMSReplyTo(); ObjectMessage request = (ObjectMessage)message; Client.setCurrentSession(session); Invocation invocation = (Invocation)request.getObject(); int methodIndex = invocation.getMethodIndex(); Object args[] = invocation.getArgs(); Method method = mapper.getMethod(methodIndex); log.trace("RECEIVING: " + method + " <- " + message.getJMSDestination()); result = method.invoke(Server.this.target, args); } catch (JMSException e) { isException = true; result = e; } catch (IllegalAccessException e) { isException = true; result = e; } catch (InvocationTargetException e) { isException = true; result = e.getTargetException(); } if (isException) log.warn(result); if (correlationId != null && replyTo != null) { ObjectMessage response = null; try { response = session.createObjectMessage(); response.setJMSCorrelationID(correlationId); Results results = new Results(isException, result); response.setObject(results); log.trace("SENDING: " + results + " -> " + replyTo); producer.send(replyTo, response); } catch (JMSException e) { log.warn("problem replying to message: " + response, e); } } } } public T createServer(T target, Destination destination, Executor executor) throws JMSException { new Server(target, destination, executor); return target; } public T createSynchronousClient(Destination destination, boolean trueAsync) throws IllegalArgumentException, JMSException { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); return (T)Proxy.newProxyInstance(contextClassLoader, new Class[]{interfaze}, new SynchronousClient(session, destination, interfaze, timeout, true)); } public T createSynchronousClient(String destinationName, boolean trueAsync) throws IllegalArgumentException, JMSException { Destination destination = session.createQueue(destinationName); ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); return (T)Proxy.newProxyInstance(contextClassLoader, new Class[]{interfaze}, new SynchronousClient(session, destination, interfaze, timeout, true)); } public AsynchronousClient createAsynchronousClient(Destination destination, boolean trueAsync) throws JMSException { return new AsynchronousClient(session, destination, interfaze, timeout, trueAsync); } }
package img; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.drew.imaging.ImageMetadataReader; import com.drew.metadata.Directory; import com.drew.metadata.Metadata; import com.drew.metadata.Tag; import com.google.common.io.Files; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.util.Objects; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicInteger; /** * : * : ldl * : 2017-09-03 15:52 */ public class ImgClassification { private static String newFilePath = null; private static final Long MAX_SIZE = 1048576L; private static LinkedBlockingQueue queue = new LinkedBlockingQueue(5000); private static ExecutorService executor = Executors.newFixedThreadPool(3); private static CountDownLatch latch = new CountDownLatch(3); private static AtomicInteger count = new AtomicInteger(0); public static void main(String[] args) throws Exception { if (args == null) { throw new Exception(""); } if (args[0] == null) { throw new Exception(""); } if (args[1] == null) { throw new Exception(""); } long start = System.currentTimeMillis(); newFilePath = args[1]; File parent = new File(args[0]); toQueue(parent); for (int i = 0; i < 3; i++) { executor.submit(new imageTask()); } latch.await(); System.out.println(",:" + count + ",:" + (System.currentTimeMillis() - start) / 1000); executor.shutdown(); } @SuppressWarnings("unchecked") private static void toQueue(File root) throws Exception { if (root.isDirectory()) { File[] files = root.listFiles(); if (files != null) { for (File file : files) { toQueue(file); } } } else { if (root.getName().contains(".jpg") && root.length() > MAX_SIZE) { queue.add(root); } } } private static class imageTask implements Runnable { /** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object's * <code>run</code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code>run</code> is that it may * take any action whatsoever. * * @see Thread#run() */ @Override public void run() { while (!queue.isEmpty()) { File image = null; image = (File) queue.poll(); if (image != null) { try { System.out.println("" + count + ""); printImageTags(image); count.addAndGet(1); } catch (Exception e) { e.printStackTrace(); } } } latch.countDown(); } } private static void moveFile(String newFilePath, Location location, File file, String createDate) throws Exception { if (createDate == null) { createDate = ""; } if (location != null) { File targetFile = new File(newFilePath + "/" + location.getProvince() + "/" + location.getCity() + "/" + location.getDistrict() + "/" + createDate + "/" + file.getName()); File newFile = new File(newFilePath + "/" + location.getProvince() + "/" + location.getCity() + "/" + location.getDistrict() + "/" + createDate); createFileAndMove(file, targetFile, newFile); } else { File targetFile = new File(newFilePath + "/" + createDate + "/" + file.getName()); File newFile = new File(newFilePath + "/" + createDate); createFileAndMove(file, targetFile, newFile); } } private static void createFileAndMove(File file, File targetFile, File newFile) throws Exception { if (!newFile.exists()) { boolean isTrue = newFile.mkdirs(); if (!isTrue) { throw new Exception("!"); } Files.move(file, targetFile); } else { Files.move(file, targetFile); } } private static void printImageTags(File file) throws Exception { Metadata metadata = ImageMetadataReader.readMetadata(file); String createDate = null; String lat = null; String lon = null; for (Directory directory : metadata.getDirectories()) { for (Tag tag : directory.getTags()) { String tagName = tag.getTagName(); String desc = tag.getDescription(); switch (tagName) { case "Date/Time Original": createDate = desc.split(" ")[0].replace(":", "-"); break; case "GPS Latitude": lat = desc; break; case "GPS Longitude": lon = desc; break; } } } moveFile(newFilePath, getposition(pointToLatlong(lat), pointToLatlong(lon)), file, createDate); } /** * , * * @param point * @return */ private static String pointToLatlong(String point) { if (point == null) { return null; } Double du = Double.parseDouble(point.substring(0, point.indexOf("°")).trim()); Double fen = Double.parseDouble(point.substring(point.indexOf("°") + 1, point.indexOf("'")).trim()); Double miao = Double.parseDouble(point.substring(point.indexOf("'") + 1, point.indexOf("\"")).trim()); Double duStr = du + fen / 60 + miao / 60 / 60; return duStr.toString(); } private static Location getposition(String latitude, String longitude) throws MalformedURLException { if (latitude == null || longitude == null) { return null; } BufferedReader in; URL tirc = new URL("http://api.map.baidu.com/geocoder?location=" + latitude + "," + longitude + "&output=json&key=" + "E4805d16520de693a3fe707cdc962045"); try { in = new BufferedReader(new InputStreamReader(tirc.openStream(), "UTF-8")); String res; StringBuilder sb = new StringBuilder(""); while ((res = in.readLine()) != null) { sb.append(res.trim()); } JSONObject object = JSON.parseObject(sb.toString()); if (object.get("status") != null && Objects.equals(object.getString("status"), "OK")) { JSONObject result = JSON.parseObject(object.getString("result")); return JSON.parseObject(result.getString("addressComponent"), Location.class); } } catch (IOException e) { e.printStackTrace(); } return null; } static class Location { private String city; private String district; private String province; public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getDistrict() { return district; } public void setDistrict(String district) { this.district = district; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } @Override public String toString() { return "Location{" + "city='" + city + '\'' + ", district='" + district + '\'' + ", province='" + province + '\'' + '}'; } } }
package org.psjava.ds.math; public class Vector2D<T> { private final T x, y; public static <T> Vector2D<T> create(T x, T y) { return new Vector2D<T>(x, y); } private Vector2D(T x, T y) { this.x = x; this.y = y; } public T x() { return x; } public T y() { return y; } @Override public String toString() { return getClass().getSimpleName() + "(" + x + "," + y + ")"; } }
package org.scijava.util; import java.io.File; import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * Useful methods for working with {@link Class} objects and primitive types. * * @author Curtis Rueden */ public final class ClassUtils { private ClassUtils() { // prevent instantiation of utility class } private static final FieldCache fieldCache = new FieldCache(); private static final MethodCache methodCache = new MethodCache(); // -- Class loading, querying and reflection -- /** * Loads the class with the given name, using the current thread's context * class loader, or null if it cannot be loaded. * * @see #loadClass(String, ClassLoader) */ public static Class<?> loadClass(final String className) { return loadClass(className, null); } /** * Loads the class with the given name, using the specified * {@link ClassLoader}, or null if it cannot be loaded. * <p> * This method is capable of parsing several different class name syntaxes. In * particular, array classes (including primitives) represented using either * square brackets or internal Java array name syntax are supported. Examples: * </p> * <ul> * <li>{@code boolean} is loaded as {@code boolean.class}</li> * <li>{@code Z} is loaded as {@code boolean.class}</li> * <li>{@code double[]} is loaded as {@code double[].class}</li> * <li>{@code string[]} is loaded as {@code java.lang.String.class}</li> * <li>{@code [F} is loaded as {@code float[].class}</li> * </ul> * * @param name The name of the class to load. * @param classLoader The class loader with which to load the class; if null, * the current thread's context class loader will be used. */ public static Class<?> loadClass(final String name, final ClassLoader classLoader) { // handle primitive types if (name.equals("Z") || name.equals("boolean")) return boolean.class; if (name.equals("B") || name.equals("byte")) return byte.class; if (name.equals("C") || name.equals("char")) return char.class; if (name.equals("D") || name.equals("double")) return double.class; if (name.equals("F") || name.equals("float")) return float.class; if (name.equals("I") || name.equals("int")) return int.class; if (name.equals("J") || name.equals("long")) return long.class; if (name.equals("S") || name.equals("short")) return short.class; if (name.equals("V") || name.equals("void")) return void.class; // handle built-in class shortcuts final String className; if (name.equals("string")) className = "java.lang.String"; else className = name; // handle source style arrays (e.g.: "java.lang.String[]") if (name.endsWith("[]")) { final String elementClassName = name.substring(0, name.length() - 2); return getArrayClass(loadClass(elementClassName, classLoader)); } // handle non-primitive internal arrays (e.g.: "[Ljava.lang.String;") if (name.startsWith("[L") && name.endsWith(";")) { final String elementClassName = name.substring(2, name.length() - 1); return getArrayClass(loadClass(elementClassName, classLoader)); } // handle other internal arrays (e.g.: "[I", "[[I", "[[Ljava.lang.String;") if (name.startsWith("[")) { final String elementClassName = name.substring(1); return getArrayClass(loadClass(elementClassName, classLoader)); } // load the class! try { final ClassLoader cl = classLoader == null ? Thread.currentThread().getContextClassLoader() : classLoader; return cl.loadClass(className); } catch (final Throwable t) { // NB: Do not allow any failure to load the class to crash us. // Not ClassNotFoundException. // Not NoClassDefFoundError. // Not UnsupportedClassVersionError! return null; } } /** * Gets the array class corresponding to the given element type. * <p> * For example, {@code getArrayClass(double.class)} returns * {@code double[].class}. * </p> */ public static Class<?> getArrayClass(final Class<?> elementClass) { if (elementClass == null) return null; // NB: It appears the reflection API has no built-in way to do this. // So unfortunately, we must allocate a new object and then inspect it. try { return Array.newInstance(elementClass, 0).getClass(); } catch (final IllegalArgumentException exc) { return null; } } /** Checks whether a class with the given name exists. */ public static boolean hasClass(final String className) { return hasClass(className, null); } /** Checks whether a class with the given name exists. */ public static boolean hasClass(final String className, final ClassLoader classLoader) { return loadClass(className, classLoader) != null; } /** * Gets the base location of the given class. * <p> * If the class is directly on the file system (e.g., * "/path/to/my/package/MyClass.class") then it will return the base directory * (e.g., "/path/to"). * </p> * <p> * If the class is within a JAR file (e.g., * "/path/to/my-jar.jar!/my/package/MyClass.class") then it will return the * path to the JAR (e.g., "/path/to/my-jar.jar"). * </p> * * @param className The name of the class whose location is desired. * @see FileUtils#urlToFile(URL) to convert the result to a {@link File}. */ public static URL getLocation(final String className) { return getLocation(className, null); } /** * Gets the base location of the given class. * <p> * If the class is directly on the file system (e.g., * "/path/to/my/package/MyClass.class") then it will return the base directory * (e.g., "/path/to"). * </p> * <p> * If the class is within a JAR file (e.g., * "/path/to/my-jar.jar!/my/package/MyClass.class") then it will return the * path to the JAR (e.g., "/path/to/my-jar.jar"). * </p> * * @param className The name of the class whose location is desired. * @param classLoader The class loader to use when loading the class. * @see FileUtils#urlToFile(URL) to convert the result to a {@link File}. */ public static URL getLocation(final String className, final ClassLoader classLoader) { final Class<?> c = loadClass(className, classLoader); return getLocation(c); } /** * Gets the base location of the given class. * <p> * If the class is directly on the file system (e.g., * "/path/to/my/package/MyClass.class") then it will return the base directory * (e.g., "file:/path/to"). * </p> * <p> * If the class is within a JAR file (e.g., * "/path/to/my-jar.jar!/my/package/MyClass.class") then it will return the * path to the JAR (e.g., "file:/path/to/my-jar.jar"). * </p> * * @param c The class whose location is desired. * @see FileUtils#urlToFile(URL) to convert the result to a {@link File}. */ public static URL getLocation(final Class<?> c) { if (c == null) return null; // could not load the class // try the easy way first try { final URL codeSourceLocation = c.getProtectionDomain().getCodeSource().getLocation(); if (codeSourceLocation != null) return codeSourceLocation; } catch (final SecurityException e) { // NB: Cannot access protection domain. } catch (final NullPointerException e) { // NB: Protection domain or code source is null. } // NB: The easy way failed, so we try the hard way. We ask for the class // itself as a resource, then strip the class's path from the URL string, // leaving the base path. // get the class's raw resource path final URL classResource = c.getResource(c.getSimpleName() + ".class"); if (classResource == null) return null; // cannot find class resource final String url = classResource.toString(); final String suffix = c.getCanonicalName().replace('.', '/') + ".class"; if (!url.endsWith(suffix)) return null; // weird URL // strip the class's path from the URL string final String base = url.substring(0, url.length() - suffix.length()); String path = base; // remove the "jar:" prefix and "!/" suffix, if present if (path.startsWith("jar:")) path = path.substring(4, path.length() - 2); try { return new URL(path); } catch (final MalformedURLException e) { e.printStackTrace(); return null; } } /** * Gets the given class's {@link Method}s marked with the annotation of the * specified class. * <p> * Unlike {@link Class#getMethods()}, the result will include any non-public * methods, including methods defined in supertypes of the given class. * </p> * * @param c The class to scan for annotated methods. * @param annotationClass The type of annotation for which to scan. * @return A new list containing all methods with the requested annotation. */ public static <A extends Annotation> List<Method> getAnnotatedMethods( final Class<?> c, final Class<A> annotationClass) { List<Method> methods = methodCache.getList(c, annotationClass); if (methods == null) { methods = new ArrayList<Method>(); getAnnotatedMethods(c, annotationClass, methods); } return methods; } /** * Gets the given class's {@link Method}s marked with the annotation of the * specified class. * <p> * Unlike {@link Class#getMethods()}, the result will include any non-public * methods, including methods defined in supertypes of the given class. * </p> * * @param c The class to scan for annotated methods. * @param annotationClass The type of annotation for which to scan. * @param methods The list to which matching methods will be added. */ public static <A extends Annotation> void getAnnotatedMethods(final Class<?> c, final Class<A> annotationClass, final List<Method> methods) { List<Method> cachedMethods = methodCache.getList(c, annotationClass); if (cachedMethods == null) { final Query query = new Query(); query.put(annotationClass, Method.class); cacheAnnotatedObjects(c, query); cachedMethods = methodCache.getList(c, annotationClass); } if (cachedMethods != null) methods.addAll(cachedMethods); } /** * Gets the given class's {@link Field}s marked with the annotation of the * specified class. * <p> * Unlike {@link Class#getFields()}, the result will include any non-public * fields, including fields defined in supertypes of the given class. * </p> * * @param c The class to scan for annotated fields. * @param annotationClass The type of annotation for which to scan. * @return A new list containing all fields with the requested annotation. */ public static <A extends Annotation> List<Field> getAnnotatedFields( final Class<?> c, final Class<A> annotationClass) { List<Field> fields = fieldCache.getList(c, annotationClass); if (fields == null) { fields = new ArrayList<Field>(); getAnnotatedFields(c, annotationClass, fields); } return fields; } /** * Gets the given class's {@link Field}s marked with the annotation of the * specified class. * <p> * Unlike {@link Class#getFields()}, the result will include any non-public * fields, including fields defined in supertypes of the given class. * </p> * * @param c The class to scan for annotated fields. * @param annotationClass The type of annotation for which to scan. * @param fields The list to which matching fields will be added. */ public static <A extends Annotation> void getAnnotatedFields( final Class<?> c, final Class<A> annotationClass, final List<Field> fields) { List<Field> cachedFields = fieldCache.getList(c, annotationClass); if (cachedFields == null) { final Query query = new Query(); query.put(annotationClass, Field.class); cacheAnnotatedObjects(c, query); cachedFields = fieldCache.getList(c, annotationClass); } fields.addAll(cachedFields); } /** * This method scans the provided class, its superclasses and interfaces for * all supported {@link Annotation} : {@link AnnotatedElement} pairs. * These are then cached to remove the need for future queries. * <p> * By combining multiple {@code Annotation : AnnotatedElement} pairs in one * query, we can limit the number of times a class's superclass and interface * hierarchy are traversed. * </p> * * @param scannedClass Class to scan * @param query Pairs of {@link Annotation} and {@link AnnotatedElement}s to * discover. */ public static void cacheAnnotatedObjects(final Class<?> scannedClass, final Query query) { // Only allow one thread at a time to populate cached objects for a given // class. This lock is technically overkill - the minimal lock would be // on the provided Query contents + class. Devising a way to obtain this // lock could be useful - as if Query A and Query B were executed on the // same class by different threads, there are three scenarios: // 1) intersection of A + B is empty - then they can run on separate threads // 2) A == B - whichever was received second must wait for the first to // finish. // 3) A != B and intersection of A + B is not empty - the intersection subset // can be safely performed on a separate thread, but the later query must // still wait for the earlier query to complete. // NB: an alternative would be to update the getAnnotatedxxx methods to // return Sets instead of Lists. Then threads can pretty much go nuts // as long as you double lock the Set creation in a synchronized block. // NB: another possibility would be to keep this synchronized entry point // but divide the work for each Query into asynchronous blocks. However, it // has not been investigated how much of a performance boost that would // provide as it would then cause multiple traversals of the class hierarchy // - which is exactly what the Query notation was created to avoid. synchronized (scannedClass) { // NB: The java.lang.Object class does not have any annotated methods. // And even if it did, it definitely does not have any methods annotated // with SciJava annotations such as org.scijava.event.EventHandler, which // are the main sorts of methods we are interested in. if (scannedClass == null || scannedClass == Object.class) return; // Initialize step - determine which queries are solved final Set<Class<? extends Annotation>> keysToDrop = new HashSet<Class<? extends Annotation>>(); for (final Class<? extends Annotation> annotationClass : query.keySet()) { // Fields if (fieldCache.getList(scannedClass, annotationClass) != null) { keysToDrop.add(annotationClass); } else if (methodCache.getList(scannedClass, annotationClass) != null) { keysToDrop.add(annotationClass); } } // Clean up resolved keys for (final Class<? extends Annotation> key : keysToDrop) { query.remove(key); } // Stop now if we know all requested information is cached if (query.isEmpty()) return; final List<Class<?>> inherited = new ArrayList<Class<?>>(); // cache all parents recursively final Class<?> superClass = scannedClass.getSuperclass(); if (superClass != null) { // Recursive step cacheAnnotatedObjects(superClass, new Query(query)); inherited.add(superClass); } // cache all interfaces recursively for (final Class<?> ifaceClass : scannedClass.getInterfaces()) { // Recursive step cacheAnnotatedObjects(ifaceClass, new Query(query)); inherited.add(ifaceClass); } // Populate supported objects for scanned class for (final Class<? extends Annotation> annotationClass : query.keySet()) { final Class<? extends AnnotatedElement> objectClass = query.get(annotationClass); try { // Methods if (Method.class.isAssignableFrom(objectClass)) { populateCache(scannedClass, inherited, annotationClass, methodCache, scannedClass.getDeclaredMethods()); } // Fields else if (Field.class.isAssignableFrom(objectClass)) { populateCache(scannedClass, inherited, annotationClass, fieldCache, scannedClass.getDeclaredFields()); } } catch (final Throwable t) { // NB: No action needed? } } } } /** * Gets the specified field of the given class, or null if it does not exist. */ public static Field getField(final String className, final String fieldName) { return getField(loadClass(className), fieldName); } /** * Gets the specified field of the given class, or null if it does not exist. */ public static Field getField(final Class<?> c, final String fieldName) { if (c == null) return null; try { return c.getDeclaredField(fieldName); } catch (final NoSuchFieldException e) { return null; } } /** * Gets the given field's value of the specified object instance, or null if * the value cannot be obtained. */ public static Object getValue(final Field field, final Object instance) { try { field.setAccessible(true); return field.get(instance); } catch (final IllegalAccessException e) { return null; } } // FIXME: Move to ConvertService and deprecate this signature. public static void setValue(final Field field, final Object instance, final Object value) { try { field.setAccessible(true); final Object compatibleValue; if (value == null || field.getType().isInstance(value)) { // the given value is compatible with the field compatibleValue = value; } else { // the given value needs to be converted to a compatible type final Type fieldType = GenericUtils.getFieldType(field, instance.getClass()); @SuppressWarnings("deprecation") final Object convertedValue = ConversionUtils.convert(value, fieldType); compatibleValue = convertedValue; } field.set(instance, compatibleValue); } catch (final IllegalAccessException e) { throw new IllegalArgumentException("No access to field: " + field.getName(), e); } } // -- Type querying -- public static boolean isBoolean(final Class<?> type) { return type == boolean.class || Boolean.class.isAssignableFrom(type); } public static boolean isByte(final Class<?> type) { return type == byte.class || Byte.class.isAssignableFrom(type); } public static boolean isCharacter(final Class<?> type) { return type == char.class || Character.class.isAssignableFrom(type); } public static boolean isDouble(final Class<?> type) { return type == double.class || Double.class.isAssignableFrom(type); } public static boolean isFloat(final Class<?> type) { return type == float.class || Float.class.isAssignableFrom(type); } public static boolean isInteger(final Class<?> type) { return type == int.class || Integer.class.isAssignableFrom(type); } public static boolean isLong(final Class<?> type) { return type == long.class || Long.class.isAssignableFrom(type); } public static boolean isShort(final Class<?> type) { return type == short.class || Short.class.isAssignableFrom(type); } public static boolean isNumber(final Class<?> type) { return Number.class.isAssignableFrom(type) || type == byte.class || type == double.class || type == float.class || type == int.class || type == long.class || type == short.class; } public static boolean isText(final Class<?> type) { return String.class.isAssignableFrom(type) || isCharacter(type); } // -- Comparison -- /** * Compares two {@link Class} objects using their fully qualified names. * <p> * Note: this method provides a natural ordering that may be inconsistent with * equals. Specifically, two unequal classes may return 0 when compared in * this fashion if they represent the same class loaded using two different * {@link ClassLoader}s. Hence, if this method is used as a basis for * implementing {@link Comparable#compareTo} or * {@link java.util.Comparator#compare}, that implementation may want to * impose logic beyond that of this method, for breaking ties, if a total * ordering consistent with equals is always required. * </p> * * @see org.scijava.Priority#compare(org.scijava.Prioritized, * org.scijava.Prioritized) */ public static int compare(final Class<?> c1, final Class<?> c2) { if (c1 == c2) return 0; final String name1 = c1 == null ? null : c1.getName(); final String name2 = c2 == null ? null : c2.getName(); return MiscUtils.compare(name1, name2); } // -- Helper methods -- /** * Populates the cache of annotated elements for a particular class by looking * for all inherited and declared instances annotated with the specified * annotationClass. If no matches are found, an empty mapping is created to * mark this class complete. */ private static <T extends AnnotatedElement> void populateCache( final Class<?> scannedClass, final List<Class<?>> inherited, final Class<? extends Annotation> annotationClass, final CacheMap<T> cacheMap, final T[] declaredElements) { // Add inherited elements for (final Class<?> inheritedClass : inherited) { final List<T> annotatedElements = cacheMap.getList(inheritedClass, annotationClass); if (annotatedElements != null && !annotatedElements.isEmpty()) { final List<T> scannedElements = cacheMap.makeList(scannedClass, annotationClass); scannedElements.addAll(annotatedElements); } } // Add declared elements if (declaredElements != null && declaredElements.length > 0) { List<T> scannedElements = null; for (final T t : declaredElements) { if (t.getAnnotation(annotationClass) != null) { if (scannedElements == null) { scannedElements = cacheMap.makeList(scannedClass, annotationClass); } scannedElements.add(t); } } } // If there were no elements for this query, map an empty // list to mark the query complete if (cacheMap.getList(scannedClass, annotationClass) == null) { cacheMap.putList(scannedClass, annotationClass, Collections .<T> emptyList()); } } // -- Deprecated methods -- /** @deprecated use {@link ConversionUtils#convert(Object, Class)} */ @Deprecated public static <T> T convert(final Object value, final Class<T> type) { return ConversionUtils.convert(value, type); } /** @deprecated use {@link ConversionUtils#canConvert(Class, Class)} */ @Deprecated public static boolean canConvert(final Class<?> c, final Class<?> type) { return ConversionUtils.canConvert(c, type); } /** @deprecated use {@link ConversionUtils#canConvert(Object, Class)} */ @Deprecated public static boolean canConvert(final Object value, final Class<?> type) { return ConversionUtils.canConvert(value, type); } /** @deprecated use {@link ConversionUtils#cast(Object, Class)} */ @Deprecated public static <T> T cast(final Object obj, final Class<T> type) { return ConversionUtils.cast(obj, type); } /** @deprecated use {@link ConversionUtils#canCast(Class, Class)} */ @Deprecated public static boolean canCast(final Class<?> c, final Class<?> type) { return ConversionUtils.canCast(c, type); } /** @deprecated use {@link ConversionUtils#canCast(Object, Class)} */ @Deprecated public static boolean canCast(final Object obj, final Class<?> type) { return ConversionUtils.canCast(obj, type); } /** @deprecated use {@link ConversionUtils#getNonprimitiveType(Class)} */ @Deprecated public static <T> Class<T> getNonprimitiveType(final Class<T> type) { return ConversionUtils.getNonprimitiveType(type); } /** @deprecated use {@link ConversionUtils#getNullValue(Class)} */ @Deprecated public static <T> T getNullValue(final Class<T> type) { return ConversionUtils.getNullValue(type); } /** @deprecated use {@link GenericUtils#getFieldClasses(Field, Class)} */ @Deprecated public static List<Class<?>> getTypes(final Field field, final Class<?> type) { return GenericUtils.getFieldClasses(field, type); } /** @deprecated use {@link GenericUtils#getFieldType(Field, Class)} */ @Deprecated public static Type getGenericType(final Field field, final Class<?> type) { return GenericUtils.getFieldType(field, type); } // -- Helper classes -- /** * Convenience class for a {@link CacheMap} that stores annotated * {@link Field}s. */ private static class FieldCache extends CacheMap<Field> { // Trivial subclass to narrow generic params } /** * Convenience class for a {@link CacheMap} that stores annotated * {@link Method}s. */ private static class MethodCache extends CacheMap<Method> { // Trivial subclass to narrow generic params } /** * Convenience class for {@code Map > Map > List} hierarchy. Cleans up * generics and contains helper methods for traversing the two map levels. * <p> * The intent for this class is to allow subclasses to specify the generic * parameter ultimately referenced by the at the end of these maps. * </p> * <p> * The first map key is a base class, presumably with various types of * annotations. The second map key is the annotation class, for example * {@link Method} or {@link Field}. The list then contains all instances of * the annotated type within the original base class. * </p> * * @param <T> - The type of {@link AnnotatedElement} contained by the * {@link List} ultimately referenced by these {@link Map}s */ private static class CacheMap<T extends AnnotatedElement> extends HashMap<Class<?>, Map<Class<? extends Annotation>, List<T>>> { /** * @param c Base class of interest * @param annotationClass {@link Annotation} type within the base class * @return A {@link List} of instances in the base class with the specified * {@link Annotation}, or null if a cached list does not exist. */ public List<T> getList(final Class<?> c, final Class<? extends Annotation> annotationClass) { List<T> annotatedFields = null; final Map<Class<? extends Annotation>, List<T>> annotationTypes = get(c); if (annotationTypes != null) { annotatedFields = annotationTypes.get(annotationClass); } return annotatedFields; } /** * Creates a {@code base class > annotation > list of elements} mapping to * the provided list, creating the intermediate map if needed. * * @param c Base class of interest * @param annotationClass {@link Annotation} type of interest * @param annotatedElements List of {@link AnnotatedElement}s to map */ public void putList(final Class<?> c, final Class<? extends Annotation> annotationClass, final List<T> annotatedElements) { Map<Class<? extends Annotation>, List<T>> map = get(c); if (map == null) { map = new HashMap<Class<? extends Annotation>, List<T>>(); put(c, map); } map.put(annotationClass, annotatedElements); } /** * Generates mappings as in {@link #putList(Class, Class, List)}, but also * creates the {@link List} if it doesn't already exist. Returns the final * list at this mapping, for external population. * * @param c Base class of interest * @param annotationClass {@link Annotation} type of interest * @return Cached list of {@link AnnotatedElement}s in the base class with * the specified {@link Annotation}. */ public List<T> makeList(final Class<?> c, final Class<? extends Annotation> annotationClass) { List<T> elements = getList(c, annotationClass); if (elements == null) { elements = new ArrayList<T>(); putList(c, annotationClass, elements); } return elements; } } }
package pointGroups.gui; import java.awt.BorderLayout; import java.awt.Color; import java.util.logging.Logger; import javax.swing.JPanel; import pointGroups.geometry.Fundamental; import pointGroups.gui.event.EventDispatcher; import pointGroups.gui.event.types.ChangeCoordinate3DPointEvent; import pointGroups.gui.event.types.ChangeCoordinate3DPointHandler; import pointGroups.gui.event.types.ChangeCoordinate4DPointEvent; import pointGroups.gui.event.types.ChangeCoordinate4DPointHandler; import pointGroups.gui.event.types.DimensionSwitchEvent; import pointGroups.gui.event.types.DimensionSwitchHandler; import pointGroups.gui.event.types.FundamentalResultEvent; import pointGroups.gui.event.types.FundamentalResultHandler; import pointGroups.gui.event.types.ScaleFundamentalDomainEvent; import pointGroups.gui.event.types.ScaleFundamentalDomainHandler; import pointGroups.gui.event.types.Schlegel3DComputeEvent; import pointGroups.gui.event.types.Schlegel4DComputeEvent; import pointGroups.gui.event.types.Symmetry3DChooseEvent; import pointGroups.gui.event.types.Symmetry3DChooseHandler; import pointGroups.gui.event.types.Symmetry4DChooseEvent; import pointGroups.gui.event.types.Symmetry4DChooseHandler; import pointGroups.util.LoggerFactory; import pointGroups.util.jreality.JRealityUtility; import pointGroups.util.point.PointUtil; import pointGroups.util.polymake.FundamentalTransformer; import de.jreality.geometry.Primitives; import de.jreality.scene.Appearance; import de.jreality.scene.Geometry; import de.jreality.scene.PointSet; import de.jreality.scene.SceneGraphComponent; import de.jreality.scene.data.Attribute; import de.jreality.scene.data.StorageModel; import de.jreality.shader.DefaultGeometryShader; import de.jreality.shader.DefaultPointShader; import de.jreality.shader.ShaderUtility; import de.jreality.tools.DragEventTool; import de.jreality.tools.PointDragEvent; import de.jreality.tools.PointDragListener; public class PointPicker extends JPanel implements FundamentalResultHandler, DimensionSwitchHandler, ChangeCoordinate3DPointHandler, ChangeCoordinate4DPointHandler, Symmetry3DChooseHandler, Symmetry4DChooseHandler, ScaleFundamentalDomainHandler { private static final long serialVersionUID = -3642299900579728806L; private final boolean responsive; private double scale = 1; private Symmetry3DChooseEvent lastSymmetry3DChooseEvent; private Symmetry4DChooseEvent lastSymmetry4DChooseEvent; final protected Logger logger = LoggerFactory.getSingle(PointPicker.class); protected final UiViewer uiViewer = new UiViewer(this) { public final SceneGraphComponent point = new SceneGraphComponent(); public final Appearance pointAppearance = new Appearance(); public final SceneGraphComponent fundamental = new SceneGraphComponent(); @Override public void onInitialized() { SceneGraphComponent root = getSceneRoot(); point.setGeometry(Primitives.point(new double[] { 0, 0, 0 })); setPointAppearance(pointAppearance); point.setAppearance(pointAppearance); root.addChild(fundamental); root.addChild(point); DragEventTool dragTool = new DragEventTool(); dragTool.addPointDragListener(new PointDragListener() { @Override public void pointDragStart(PointDragEvent e) { logger.finest("drag start of vertex no " + e.getIndex()); } @Override public void pointDragged(PointDragEvent e) { PointSet pointSet = e.getPointSet(); double[][] points = new double[pointSet.getNumPoints()][]; pointSet.getVertexAttributes(Attribute.COORDINATES).toDoubleArrayArray( points); points[e.getIndex()] = e.getPosition(); pointSet.setVertexAttributes(Attribute.COORDINATES, StorageModel.DOUBLE_ARRAY.array(3).createReadOnly(points)); /* * for (double[] point : points) { * System.out.printf("[%2f, %2f, %2f]\n", point[0], point[1], * point[2]); } */ // TODO: // because the point scene has only one vertex, pointSet should only // contain one point; and therefore only the statements below should // be sufficient for point picking. double[] pickedPoint = e.getPosition(); if (responsive) selectPoint(pickedPoint); } @Override public void pointDragEnd(PointDragEvent e) { logger.finest("drag end of vertex no " + e.getIndex()); if (!responsive) selectPoint(e.getPosition()); } }); point.addTool(dragTool); } private void setPointAppearance(Appearance ap) { // make points a little bigger, than the default. DefaultGeometryShader dgs; DefaultPointShader dpts; dgs = ShaderUtility.createDefaultGeometryShader(ap, true); dgs.setShowPoints(true); dpts = (DefaultPointShader) dgs.createPointShader("default"); dpts.setDiffuseColor(Color.MAGENTA); dpts.setSpheresDraw(true); dpts.setPointSize(0.1); dpts.setPointRadius(0.1); } }; // The current Fundamental Domain protected Fundamental fundamental; protected boolean isSet; protected EventDispatcher dispatcher; protected int dim; /** * Creates the Point Picker, to choose a point graphically. * * @param responsive - true => ChangeCoordinateEvent on Drag, False => Change * Coordinate Event on Release */ public PointPicker(boolean responsive) { super(); setLayout(new BorderLayout()); /* * JButton button3 = new JButton("VIEW"); PointPicker.this.add(button3, * BorderLayout.PAGE_END); */ this.isSet = false; this.dim = 2; this.dispatcher = EventDispatcher.get(); this.responsive = responsive; // Register PointPicker on Events this.dispatcher.addHandler(FundamentalResultEvent.TYPE, this); this.dispatcher.addHandler(DimensionSwitchEvent.TYPE, this); this.dispatcher.addHandler(ChangeCoordinate3DPointEvent.TYPE, this); this.dispatcher.addHandler(ChangeCoordinate4DPointEvent.TYPE, this); this.dispatcher.addHandler(Symmetry4DChooseEvent.TYPE, this); this.dispatcher.addHandler(Symmetry3DChooseEvent.TYPE, this); this.dispatcher.addHandler(ScaleFundamentalDomainEvent.TYPE, this); } public void dispose() { uiViewer.dispose(); } @Override public void onFundamentalResultEvent(FundamentalResultEvent event) { this.isSet = true; this.fundamental = event.getResult(); // Maybe check for dimension this.showFundamental(); } // Maybe i need this. @Override public void onDimensionSwitchEvent(DimensionSwitchEvent event) { if (event.switchedTo3D()) { logger.fine("Point Picker switched to 2D Mode."); this.dim = 2; uiViewer.set2DMode(); } else if (event.switchedTo4D()) { logger.fine("Point Picker switched to 3D Mode."); this.dim = 3; uiViewer.set3DMode(); } else { this.dim = 0; this.isSet = false; } } // Method to fire coordinate Changed Event, should be executed by click inside // the fundamental domain. protected void selectPoint(double[] point) { if (!isSet || (this.dim != 2 && this.dim != 3)) { logger.info("Point was picked with no useable Fundamental Region."); return; } logger.info("Selected Point (" + point[0] + "," + point[1] + (this.dim == 3 ? "," + point[2] : "") + ")"); if (!isSet) return; // Maybe the view is translated or smt // point = Rotate * point - translation // Recalculate to Unitsphere on dim+1 dimensions // Only take the first dim components double[] selComp = new double[this.dim]; for (int i = 0; i < this.dim; i++) selComp[i] = point[i]; double[] resP = this.fundamental.revertPoint(selComp); logger.fine("Point Picker calculated Point (" + resP[0] + "," + resP[1] + "," + resP[2] + (this.dim == 3 ? "," + resP[3] : "") + ")"); resP = PointUtil.mult(this.scale, resP); System.out.println("Scale: " + this.scale + ", point : " + PointUtil.showPoint(resP)); // Fire Event, that the coordinate changed if (dim == 2) { this.dispatcher.fireEvent(new ChangeCoordinate3DPointEvent( JRealityUtility.asPoint3D(resP), this)); // if (responsive) this.dispatcher.fireEvent(new Schlegel3DComputeEvent( lastSymmetry3DChooseEvent, JRealityUtility.asPoint3D(resP))); } else if (dim == 3) { this.dispatcher.fireEvent(new ChangeCoordinate4DPointEvent( JRealityUtility.asPoint4D(resP), this)); // if (responsive) this.dispatcher.fireEvent(new Schlegel4DComputeEvent( lastSymmetry4DChooseEvent, JRealityUtility.asPoint4D(resP))); } } protected void showFundamental() { logger.info("Showing new Fundamental Domain."); Geometry g; // Calculate the new fundamental if (this.fundamental.isKnown()) { g = JRealityUtility.generateGraph(this.fundamental.getVertices(), JRealityUtility.convertEdges(this.fundamental.getEdges())); } else { if (this.dim == 2) g = JRealityUtility.circle(0, 0, 1); else g = Primitives.sphere(20); } // Reset tools (3D rotation, 2D no Rotation) logger.fine("A new Fundamental Region is shown."); uiViewer.setGeometry(g); } @Override public void onChangeCoordinate4DPointEvent(ChangeCoordinate4DPointEvent event) { // Calculate if the point is in the Fundamental Domain and // show it, if possible // For start test just show the point // uiViewer.setGeometry(Primitives.point(new double[] { 0.5, 0.5 })); return; } @Override public void onChangeCoordinate3DPointEvent(ChangeCoordinate3DPointEvent event) { // Calculate if the point is in the Fundamental Domain and // show it, if possible // For start test just show the point // uiViewer.setGeometry(Primitives.point(new double[] { 0.5, 0.5 })); return; } @Override public void onSymmetry4DChooseEvent(Symmetry4DChooseEvent event) { this.lastSymmetry4DChooseEvent = event; this.dim = 3; } @Override public void onSymmetry3DChooseEvent(Symmetry3DChooseEvent event) { this.lastSymmetry3DChooseEvent = event; this.dim = 2; } @Override public void onScaleFundamentalDomainEvent(ScaleFundamentalDomainEvent event) { this.scale = 1.0 * event.getScale(); } }
package prm4j.logic; import prm4j.api.MatchHandler; import prm4j.api.Symbol; import prm4j.indexing.AbstractBaseMonitor; /** * A base monitor holding a {@link MonitorState} which is updated when processing {@link Symbol}s. * */ public class StatefulMonitor extends AbstractBaseMonitor<Symbol> { private MonitorState state; public StatefulMonitor(MonitorState state) { this.state = state; } @Override public boolean processEvent(Symbol baseEvent) { state = state.getSuccessor(baseEvent); MatchHandler matchHandler = state.getMatchHandler(); if (matchHandler != null) { matchHandler.handleMatch(getBindings()); // when a state is a final state, it is still possible we will reach another final state (or loop on a // final state), so we don't return false here } return true; } @Override public StatefulMonitor copy() { return new StatefulMonitor(state); } @Override public boolean isFinalStateReachable() { // TODO co-enable set calculation or similar return true; } }
package scrum.client; import ilarkesto.gwt.client.AGwtEntity; import ilarkesto.gwt.client.AWidget; import ilarkesto.gwt.client.GwtLogger; import ilarkesto.gwt.client.ObjectMappedFlowPanel; import ilarkesto.gwt.client.SwitcherWidget; import ilarkesto.gwt.client.SwitchingNavigatorWidget; import java.util.List; import scrum.client.admin.ProjectUserConfigWidget; import scrum.client.admin.PunishmentsWidget; import scrum.client.admin.User; import scrum.client.calendar.CalendarWidget; import scrum.client.calendar.SimpleEvent; import scrum.client.collaboration.Comment; import scrum.client.collaboration.WikiWidget; import scrum.client.common.AScrumComponent; import scrum.client.context.UserHighlightSupport; import scrum.client.dashboard.DashboardWidget; import scrum.client.files.File; import scrum.client.files.FileRepositoryWidget; import scrum.client.impediments.Impediment; import scrum.client.impediments.ImpedimentListWidget; import scrum.client.issues.Issue; import scrum.client.issues.IssueListWidget; import scrum.client.journal.JournalWidget; import scrum.client.project.ProductBacklogWidget; import scrum.client.project.Project; import scrum.client.project.ProjectOverviewWidget; import scrum.client.project.Quality; import scrum.client.project.QualityBacklogWidget; import scrum.client.project.Requirement; import scrum.client.risks.Risk; import scrum.client.risks.RiskListWidget; import scrum.client.sprint.NextSprintWidget; import scrum.client.sprint.SprintBacklogWidget; import scrum.client.sprint.SprintHistoryWidget; import scrum.client.sprint.Task; import scrum.client.tasks.TaskOverviewWidget; import scrum.client.tasks.WhiteboardWidget; import scrum.client.test.WidgetsTesterWidget; import scrum.client.workspace.ProjectSidebarWidget; import com.google.gwt.user.client.ui.Widget; public class ProjectContext extends AScrumComponent { private Project project; private ProjectSidebarWidget sidebar = new ProjectSidebarWidget(); private DashboardWidget dashboard; private ProjectOverviewWidget projectOverview; private TaskOverviewWidget taskOverview; private WhiteboardWidget whiteboard; private SprintBacklogWidget sprintBacklog; private ProductBacklogWidget productBacklog; private QualityBacklogWidget qualityBacklog; private CalendarWidget calendar; private NextSprintWidget nextSprint; private ImpedimentListWidget impedimentList; private IssueListWidget issueList; private RiskListWidget riskList; private WikiWidget wiki; private SprintHistoryWidget sprintHistory; private ProjectUserConfigWidget projectUserConfig; private WidgetsTesterWidget widgetsTester; private PunishmentsWidget punishments; private JournalWidget projectEventList; private FileRepositoryWidget fileRepository; private boolean searchResultsAdded; private User highlightedUser; ProjectContext() { projectOverview = new ProjectOverviewWidget(); dashboard = new DashboardWidget(); taskOverview = new TaskOverviewWidget(); whiteboard = new WhiteboardWidget(); sprintBacklog = new SprintBacklogWidget(); productBacklog = new ProductBacklogWidget(); qualityBacklog = new QualityBacklogWidget(); calendar = new CalendarWidget(); nextSprint = new NextSprintWidget(); impedimentList = new ImpedimentListWidget(); issueList = new IssueListWidget(); riskList = new RiskListWidget(); projectUserConfig = new ProjectUserConfigWidget(); sprintHistory = new SprintHistoryWidget(); wiki = new WikiWidget(); widgetsTester = new WidgetsTesterWidget(); punishments = new PunishmentsWidget(); projectEventList = new JournalWidget(); fileRepository = new FileRepositoryWidget(); SwitchingNavigatorWidget navigator = getSidebar().getNavigator(); // navigator.addItem("Project Overview", getProjectOverview()); navigator.addItem("Dashboard", dashboard); // navigator.addItem("Task Overview", getTaskOverview()); navigator.addItem("Whiteboard", getWhiteboard()); navigator.addItem("Sprint Backlog", getSprintBacklog()); navigator.addItem("Product Backlog", getProductBacklog()); navigator.addItem("Quality Backlog", getQualityBacklog()); navigator.addItem("Calendar", calendar); navigator.addItem("Impediment List", getImpedimentList()); navigator.addItem("Issue List", getIssueList()); navigator.addItem("Risk Management", getRiskList()); navigator.addItem("Wiki", getWiki()); navigator.addItem("File Repository", fileRepository); navigator.addItem("Project Journal", getProjectEventList()); navigator.addItem("Next Sprint", getNextSprint()); navigator.addItem("Sprint History", getSprintHistory()); navigator.addItem("Courtroom", punishments); navigator.addItem("Personal Preferences", getProjectUserConfig()); navigator.addItem("WidgetsTester", getWidgetsTester()); } @Override protected void onDestroy() { ObjectMappedFlowPanel.objectHeights.clear(); } public void activate() { cm.getUi().show(sidebar, dashboard); } public void openProject(Project project) { this.project = project; cm.getUi().lock("Loading project..."); cm.getApp().callSelectProject(project.getId(), new Runnable() { public void run() { activate(); } }); cm.getEventBus().fireProjectOpened(); } public void closeProject(boolean activateHomeView) { assert project != null; cm.getUi().lock("Closing project..."); project = null; cm.getApp().callCloseProject(); cm.getEventBus().fireProjectClosed(); if (activateHomeView) cm.getHomeContext().activate(); } public Project getProject() { return project; } public boolean isProjectOpen() { return project != null; } public List<Comment> getComments(AGwtEntity entity) { return cm.getDao().getCommentsByParent(entity); } public void highlightUser(User user) { if (highlightedUser == user) return; Widget currentWidget = getWorkarea().getCurrentWidget(); if (currentWidget instanceof UserHighlightSupport) { ((UserHighlightSupport) currentWidget).highlightUser(user); } highlightedUser = user; } public ProjectUserConfigWidget getProjectUserConfig() { return projectUserConfig; } public void showSearchResults() { SwitchingNavigatorWidget navigator = getSidebar().getNavigator(); SearchResultsWidget results = cm.getSearch().getResultsWidget(); if (!searchResultsAdded) { navigator.addItem("Search Results", results); searchResultsAdded = true; } navigator.select(results); } public void showEntityByReference(final String reference) { assert project != null; GwtLogger.DEBUG("Showing entity by reference:", reference); if (reference.length() > 4 && reference.startsWith("[[")) { String page = reference.substring(2, reference.length() - 2); showWiki(page); return; } AGwtEntity entity = cm.getDao().getEntityByReference(reference); if (entity != null) { showEntity(entity); return; } cm.getUi().lock("Searching for " + reference); cm.getApp().callRequestEntityByReference(reference, new Runnable() { public void run() { AGwtEntity entity = cm.getDao().getEntityByReference(reference); if (entity == null) { cm.getUi().unlock(); cm.getChat().postSystemMessage("Object does not exist: " + reference, false); return; } cm.getUi().unlock(); showEntity(entity); } }); } public void showEntity(AGwtEntity entity) { GwtLogger.DEBUG("Showing entity:", entity); if (entity instanceof Task) { showTask((Task) entity); } else if (entity instanceof Requirement) { showRequirement((Requirement) entity); } else if (entity instanceof Issue) { showIssue((Issue) entity); } else if (entity instanceof Risk) { showRisk((Risk) entity); } else if (entity instanceof Quality) { showQuality((Quality) entity); } else if (entity instanceof Impediment) { showImpediment((Impediment) entity); } else if (entity instanceof File) { showFile((File) entity); } else { throw new RuntimeException("Showing entity not supported: " + entity.getClass().getName()); } } public void showIssue(Issue issue) { select(issueList); issueList.select(issue); } public void showQuality(Quality quality) { select(qualityBacklog); qualityBacklog.select(quality); } public void showImpediment(Impediment impediment) { select(impedimentList); impedimentList.select(impediment); } public void showFile(File file) { select(fileRepository); fileRepository.select(file); } public void showRisk(Risk risk) { select(riskList); riskList.select(risk); } public void showTask(Task task) { if (getWorkarea().isShowing(whiteboard)) { showWhiteboard(task); } else if (getWorkarea().isShowing(taskOverview)) { showTaskOverview(task); } else { showSprintBacklog(task); } } public void showRequirement(Requirement requirement) { boolean inCurrentSprint = getCurrentProject().isCurrentSprint(requirement.getSprint()); if (inCurrentSprint) { if (getWorkarea().isShowing(productBacklog)) { showProductBacklog(requirement); } else { showSprintBacklog(requirement); } } else { showProductBacklog(requirement); } } public void showWiki(String page) { select(wiki); if (page != null) wiki.showPage(page); } private SwitcherWidget getWorkarea() { return cm.getUi().getWorkspace().getWorkarea(); } public void showWhiteboard(Task task) { select(whiteboard); whiteboard.selectTask(task); } public void showSprintBacklog(Task task) { select(sprintBacklog); sprintBacklog.selectTask(task); } public void showTaskOverview(Task task) { select(taskOverview); taskOverview.selectTask(task); } public void showSprintBacklog(Requirement requirement) { select(sprintBacklog); if (requirement != null) sprintBacklog.selectRequirement(requirement); } public void showProductBacklog(Requirement requirement) { select(productBacklog); productBacklog.selectRequirement(requirement); } public void showImpedimentList(Impediment impediment) { select(impedimentList); impedimentList.showImpediment(impediment); } public void showIssueList(Issue issue) { select(issueList); issueList.showIssue(issue); } public void showQualityBacklog(Quality quality) { select(qualityBacklog); qualityBacklog.showQuality(quality); } public void showRiskList(Risk risk) { select(riskList); riskList.showRisk(risk); } public void showCalendar(SimpleEvent event) { select(calendar); calendar.showEvent(event); } private void select(AWidget widget) { getSidebar().getNavigator().select(widget); } public WikiWidget getWiki() { return wiki; } public SprintHistoryWidget getSprintHistory() { return sprintHistory; } public CalendarWidget getCalendar() { return calendar; } public JournalWidget getProjectEventList() { return projectEventList; } public ImpedimentListWidget getImpedimentList() { return impedimentList; } public FileRepositoryWidget getFileRepository() { return fileRepository; } public IssueListWidget getIssueList() { return issueList; } public NextSprintWidget getNextSprint() { return nextSprint; } public ProductBacklogWidget getProductBacklog() { return productBacklog; } public ProjectOverviewWidget getProjectOverview() { return projectOverview; } public QualityBacklogWidget getQualityBacklog() { return qualityBacklog; } public RiskListWidget getRiskList() { return riskList; } public ProjectSidebarWidget getSidebar() { return sidebar; } public SprintBacklogWidget getSprintBacklog() { return sprintBacklog; } public TaskOverviewWidget getTaskOverview() { return taskOverview; } public WhiteboardWidget getWhiteboard() { return whiteboard; } public WidgetsTesterWidget getWidgetsTester() { return widgetsTester; } }
package com.shyamu.translocwidget; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.RemoteViews; import android.widget.Spinner; public class WidgetConfigurationActivity extends Activity { private int mAppWidgetId = 0; private String agencyId = ""; private String routeId = ""; private int agencyPosition = -1; private int routePosition = -1; private int stopPosition = -1; Spinner sSelectAgency, sSelectRoute, sSelectStop; Button bReset, bMakeWidget; ArrayList<String> agencyLongNameArray = new ArrayList<String>(); ArrayList<String> agencyShortNameArray = new ArrayList<String>(); ArrayList<String> agencyIdArray = new ArrayList<String>(); ArrayList<String> routeLongNameArray = new ArrayList<String>(); ArrayList<String> routeShortNameArray = new ArrayList<String>(); ArrayList<String> routeIdArray = new ArrayList<String>(); ArrayList<String> stopNameArray = new ArrayList<String>(); ArrayList<String> stopShortNameArray = new ArrayList<String>(); ArrayList<String> stopIdArray = new ArrayList<String>(); ArrayAdapter<String> agencyArrayAdapter; ArrayAdapter<String> routeArrayAdapter; ArrayAdapter<String> stopArrayAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.configuration_activity); // Getting references to Spinners and Buttons sSelectAgency = (Spinner) findViewById(R.id.sSelectAgency); sSelectRoute = (Spinner) findViewById(R.id.sSelectRoute); sSelectStop = (Spinner) findViewById(R.id.sSelectStop); bReset = (Button) findViewById(R.id.bReset); bMakeWidget = (Button) findViewById(R.id.bMakeWidget); // Make agency selected listener AdapterView.OnItemSelectedListener agencySelectedListener = new AgencySpinnerActivity(); sSelectAgency.setOnItemSelectedListener(agencySelectedListener); // Make route selected listener AdapterView.OnItemSelectedListener routeSelectedListener = new RouteSpinnerActivity(); sSelectRoute.setOnItemSelectedListener(routeSelectedListener); // Make stop selected listener AdapterView.OnItemSelectedListener stopSelectedListener = new StopSpinnerActivity(); sSelectStop.setOnItemSelectedListener(stopSelectedListener); // Populate agency spinner PopulateAgenciesTask task = new PopulateAgenciesTask(); task.execute(); // Defining a click event listener for the button "Reset" OnClickListener setResetClickedListener = new OnClickListener() { @Override public void onClick(View v) { doReset(); } }; // Defining a click event listener for the button "Make Widget" OnClickListener setMakeWidgetClickedListener = new OnClickListener() { @Override public void onClick(View v) { doMakeWidget(); } }; Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (extras != null) { mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); } // Setting the click listener on the buttons bReset.setOnClickListener(setResetClickedListener); bMakeWidget.setOnClickListener(setMakeWidgetClickedListener); } private void doReset() { PopulateAgenciesTask task = new PopulateAgenciesTask(); task.execute(); agencyArrayAdapter.notifyDataSetChanged(); routeArrayAdapter.notifyDataSetChanged(); stopArrayAdapter.notifyDataSetChanged(); } private void doMakeWidget() { Log.v("TESTING","Now testing variables"); Log.v("TESTING","agency ID: " + agencyId); Log.v("TESTING","agency long name:" + agencyLongNameArray.get(agencyPosition)); Log.v("TESTING","agency short name:" + agencyShortNameArray.get(agencyPosition)); Log.v("TESTING","route ID: + " + routeId); Log.v("TESTING","route long name:" + routeLongNameArray.get(routePosition)); Log.v("TESTING","route short name:" + routeShortNameArray.get(routePosition)); Log.v("TESTING","stop ID: + " + stopIdArray.get(stopPosition)); // Log.v("TESTING","stop long name:" + stopShortNameArray.get(stopPosition)); Log.v("TESTING","stop name:" + stopNameArray.get(stopPosition)); Intent intent = new Intent(getBaseContext(), WidgetConfigurationActivity.class); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId); intent.setData(Uri.parse("tel:/" + (int) System.currentTimeMillis())); // Creating a pending intent, which will be invoked when the user // clicks on the widget PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); // Getting an instance of WidgetManager AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getBaseContext()); // Instantiating the class RemoteViews with widget_layout RemoteViews views = new RemoteViews(getBaseContext().getPackageName(), R.layout.widget_layout); //Set the time remaining of the widget //views.setInt(R.id.widget_aclock, "setBackgroundColor", color); // Attach an on-click listener to the time to update when clicked views.setOnClickPendingIntent(R.id.tvRemainingTime, pendingIntent); // Tell the AppWidgetManager to perform an update on the app widget appWidgetManager.updateAppWidget(mAppWidgetId, views); // Return RESULT_OK from this activity Intent resultValue = new Intent(); resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId); setResult(RESULT_OK, resultValue); finish(); } private class PopulateAgenciesTask extends AsyncTask<Void, Void, Void> { protected Void doInBackground(Void... voids) { String response = getJsonResponse("http://api.transloc.com/1.1/agencies.json"); try { JSONObject jObject = new JSONObject(response); JSONArray jArray = jObject.getJSONArray("data"); for (int i = 0; i < jArray.length(); i++) { Log.v("From jArray", jArray.getJSONObject(i).getString( "long_name")); agencyLongNameArray.add(jArray.getJSONObject(i).getString( "long_name")); agencyShortNameArray.add(jArray.getJSONObject(i).getString( "short_name")); agencyIdArray.add(jArray.getJSONObject(i).getString( "agency_id")); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); Log.e("JSON", "ERROR in getting JSON data"); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); agencyArrayAdapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1, agencyLongNameArray); sSelectAgency.setAdapter(agencyArrayAdapter); } } private class PopulateRoutesTask extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { agencyPosition = sSelectAgency.getSelectedItemPosition(); agencyId = agencyIdArray.get(agencyPosition); Log.v("DEBUG", "Selected agency ID is " + agencyId); routeLongNameArray.clear(); routeIdArray.clear(); routeShortNameArray.clear(); stopShortNameArray.clear(); stopNameArray.clear(); stopIdArray.clear(); } protected Void doInBackground(Void... voids) { String response = getJsonResponse("http://api.transloc.com/1.1/routes.json?agencies=" + agencyId); Log.v("DEBUG", response); try { JSONObject jObject = new JSONObject(response); JSONObject jObjectData = jObject.getJSONObject("data"); JSONArray jArrayAgency = jObjectData.getJSONArray(agencyId); for (int i = 0; i < jArrayAgency.length(); i++) { routeLongNameArray.add(jArrayAgency.getJSONObject(i).getString( "long_name")); routeShortNameArray.add(jArrayAgency.getJSONObject(i).getString( "short_name")); routeIdArray.add(jArrayAgency.getJSONObject(i).getString( "route_id")); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); Log.e("JSON", "ERROR in getting JSON data"); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); routeArrayAdapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1, routeLongNameArray); sSelectRoute.setAdapter(routeArrayAdapter); } } private class PopulateStopsTask extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { for(int i = 0; i < routeIdArray.size(); i++) { Log.v("DEBUG", routeLongNameArray.get(i)); Log.v("DEBUG", routeIdArray.get(i)); } routePosition = sSelectRoute.getSelectedItemPosition(); routeId = routeIdArray.get(routePosition); Log.v("DEBUG", "Selected route ID is " + routeId); stopIdArray.clear(); stopNameArray.clear(); stopShortNameArray.clear(); } protected Void doInBackground(Void... voids) { String response = getJsonResponse("http://api.transloc.com/1.1/stops.json?agencies=" + agencyId); Log.v("DEBUG", response); try { JSONObject jObject = new JSONObject(response); JSONArray jArrayData = jObject.getJSONArray("data"); for(int i = 0; i < jArrayData.length(); i++) { JSONObject jObjectStop = jArrayData.getJSONObject(i); JSONArray jArrayStopRoutes = jObjectStop.getJSONArray("routes"); for(int j = 0; j < jArrayStopRoutes.length(); j++) { if(jArrayStopRoutes.get(j).equals(routeId)) { stopNameArray.add((String) jObjectStop.get("name")); stopIdArray.add((String) jObjectStop.get("stop_id")); break; } } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); Log.e("JSON", "ERROR in getting JSON data"); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); stopArrayAdapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1, stopNameArray); sSelectStop.setAdapter(stopArrayAdapter); } } /* * public void colorPicker() { * * // initialColor is the initially-selected color to be shown in the * rectangle on the left of the arrow. // for example, 0xff000000 is black, * 0xff0000ff is blue. Please be aware of the initial 0xff which is the * alpha. AmbilWarnaDialog dialog = new AmbilWarnaDialog(this, 0xff0000ff, * new OnAmbilWarnaListener() { * * // Executes, when user click Cancel button * * @Override public void onCancel(AmbilWarnaDialog dialog){ } * * // Executes, when user click OK button * * @Override public void onOk(AmbilWarnaDialog dialog, int color) { // * Create an Intent to launch WidgetConfigurationActivity screen Intent * intent = new Intent(getBaseContext(), WidgetConfigurationActivity.class); * * intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId); * * // This is needed to make this intent different from its previous intents * intent.setData(Uri.parse("tel:/"+ (int)System.currentTimeMillis())); * * // Creating a pending intent, which will be invoked when the user // * clicks on the widget PendingIntent pendingIntent = * PendingIntent.getActivity(getBaseContext(), 0, intent, * PendingIntent.FLAG_UPDATE_CURRENT); * * // Getting an instance of WidgetManager AppWidgetManager appWidgetManager * = AppWidgetManager.getInstance(getBaseContext()); * * // Instantiating the class RemoteViews with widget_layout RemoteViews * views = new RemoteViews(getBaseContext().getPackageName(), * R.layout.widget_layout); * * // Setting the background color of the widget * views.setInt(R.id.widget_aclock, "setBackgroundColor", color); * * // Attach an on-click listener to the clock * views.setOnClickPendingIntent(R.id.widget_aclock, pendingIntent); * * // Tell the AppWidgetManager to perform an update on the app widget * appWidgetManager.updateAppWidget(mAppWidgetId, views); * * // Return RESULT_OK from this activity Intent resultValue = new Intent(); * resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId); * setResult(RESULT_OK, resultValue); finish(); } }); dialog.show(); * * } */ private class AgencySpinnerActivity extends Activity implements AdapterView.OnItemSelectedListener { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { // An item was selected. You can retrieve the selected item using // parent.getItemAtPosition(pos) sSelectRoute.setEnabled(true); // Get routes PopulateRoutesTask task = new PopulateRoutesTask(); task.execute(); } public void onNothingSelected(AdapterView<?> parent) { // Another interface callback } } private class RouteSpinnerActivity extends Activity implements AdapterView.OnItemSelectedListener { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { // An item was selected. You can retrieve the selected item using // parent.getItemAtPosition(pos) sSelectStop.setEnabled(true); // Get routes PopulateStopsTask task = new PopulateStopsTask(); task.execute(); } public void onNothingSelected(AdapterView<?> parent) { // Another interface callback } } private class StopSpinnerActivity extends Activity implements AdapterView.OnItemSelectedListener { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { // An item was selected. You can retrieve the selected item using // parent.getItemAtPosition(pos) sSelectStop.setEnabled(true); // assign variables stopPosition = pos; } public void onNothingSelected(AdapterView<?> parent) { // Another interface callback } } private String getJsonResponse(String url) { String response = ""; DefaultHttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); try { HttpResponse execute = client.execute(httpGet); InputStream content = execute.getEntity().getContent(); BufferedReader buffer = new BufferedReader( new InputStreamReader(content)); String s = ""; while ((s = buffer.readLine()) != null) { response += s; } } catch (Exception e) { e.printStackTrace(); } return response; } }
package trikita.obsqr; import android.view.View; import android.view.ViewGroup; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.hardware.Camera; import android.hardware.Camera.Size; import android.hardware.Camera.CameraInfo; import android.content.Context; import android.util.AttributeSet; import android.os.Handler; import java.util.List; import java.io.IOException; import android.util.Log; import android.view.Surface; /** * A simple wrapper around a Camera and a SurfaceView that renders a centered preview of the Camera * to the surface. Also provided autofocus effect. * */ class CameraPreview extends ViewGroup implements SurfaceHolder.Callback, Camera.AutoFocusCallback, Camera.PreviewCallback { private final static String tag = "CameraPreview"; /* It'll be 2 sec between two autoFocus() calls */ private final static int AUTOFOCUS_FREQUENCY = 2000; private final Zbar zbar = new Zbar(); private SurfaceView mSurfaceView; private SurfaceHolder mHolder; private Size mPreviewSize; private List<Size> mSupportedPreviewSizes; private Camera mCamera; private Camera.Parameters mParams = null; private int mCameraId; private boolean mRotated = false; private boolean mFocusModeOn; private OnQrDecodedListener mOnQrDecodedListener; private final Handler mAutoFocusHandler = new Handler(); private final Runnable mAutoFocusRunnable = new Runnable() { @Override public void run() { mFocusModeOn = true; if (mCamera != null) { mCamera.autoFocus(CameraPreview.this); } } }; public interface OnQrDecodedListener { public void onQrDecoded(String url); } public CameraPreview(Context context) { this(context, null, 0); } public CameraPreview(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CameraPreview(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); Log.d(tag, "Create CameraPreview"); mSurfaceView = new SurfaceView(context); addView(mSurfaceView); // install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed. mHolder = mSurfaceView.getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } public void setOnQrDecodedListener(OnQrDecodedListener l) { mOnQrDecodedListener = l; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // We purposely disregard child measurements because act as a // wrapper to a SurfaceView that centers the camera preview instead // of stretching it. Log.d(tag, "onMeasure"); final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec); final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec); setMeasuredDimension(width, height); Log.d(tag, "setMeasuredDimension w=" + width + " h=" + height); if (mSupportedPreviewSizes != null) { mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height); Log.d(tag, "mPreviewSize w=" + mPreviewSize.width + " h=" + mPreviewSize.height); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { Log.d(tag, "onLayout"); if (changed && getChildCount() > 0) { final View child = getChildAt(0); final int width = r - l; final int height = b - t; int previewWidth = width; int previewHeight = height; if (mPreviewSize != null) { if (mRotated) { previewWidth = mPreviewSize.width; previewHeight = mPreviewSize.height; } else { previewWidth = mPreviewSize.height; previewHeight = mPreviewSize.width; } } Log.d(tag, "Preview width="+previewWidth+" height="+previewHeight); Log.d(tag, "View width="+width+", height="+height); // Center the child SurfaceView within the parent. if (previewWidth * height > width * previewHeight) { Log.d(tag, "Scaling by height"); final int scaledChildWidth = previewWidth * height / previewHeight; int dx = (int)((width - scaledChildWidth) * 0.5); Log.d(tag, "Scaled width: " + scaledChildWidth + ", dx="+dx); child.layout(dx, 0, width - dx, height); Log.d(tag, "l="+dx+" t=0"+" r="+(width-dx)+" b="+height); } else { Log.d(tag, "Scaling by width"); final int scaledChildHeight = previewHeight * width / previewWidth; int dy = (int)((height - scaledChildHeight) * 0.5); Log.d(tag, "Scaled height: " + scaledChildHeight+ ", dy="+dy); child.layout(0, 0, width, height - 2*dy); Log.d(tag, "l="+0+" t="+dy+" r="+width+" b="+(height-dy)); } } else { Log.d(tag, "Nothing to do in onLayout()"); } } private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) { final double ASPECT_TOLERANCE = 0.1; double targetRatio = (double) w / h; if (sizes == null) return null; Size optimalSize = null; double minDiff = Double.MAX_VALUE; Log.d(tag, "getOptimalPreviewSize for w=" + w + " h=" + h); // Try to find an size match aspect ratio and size for (Size size : sizes) { double ratio = (double) size.width / size.height; if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue; double diff = Math.pow(Math.abs(size.height - h), 2) + Math.pow(Math.abs(size.width - w), 2); if (diff < minDiff) { optimalSize = size; minDiff = diff; } } // Cannot find the one match the aspect ratio, ignore the requirement if (optimalSize == null) { minDiff = Double.MAX_VALUE; for (Size size : sizes) { double diff = Math.pow(Math.abs(size.height - h), 2) + Math.pow(Math.abs(size.width - w), 2); if (diff < minDiff) { optimalSize = size; minDiff = diff; } } } Log.d(tag, "Optimal size is " + optimalSize.width + "x" + optimalSize.height); return optimalSize; } private void setCameraDisplayOrientation(int rotation) { Log.d(tag, "setCameraDisplayOrientation"); if (mCamera == null) return; CameraInfo info = new CameraInfo(); Log.d(tag, "mCameraId="+mCameraId); Camera.getCameraInfo(mCameraId, info); int degrees = 0; switch (rotation) { case Surface.ROTATION_0: degrees = 0; mRotated = false; break; case Surface.ROTATION_90: degrees = 90; mRotated = true; break; case Surface.ROTATION_180: degrees = 180; mRotated = false; break; case Surface.ROTATION_270: degrees = 270; mRotated = true; break; default: mRotated = true; } Log.d(tag, "Camera rotated: " + degrees + " degrees"); int result; if (info.facing == CameraInfo.CAMERA_FACING_FRONT) { Log.d(tag, "Front facing camera"); result = (info.orientation + degrees) % 360; result = (360 - result) % 360; // compensate the mirror } else { // back-facing Log.d(tag, "Back facing camera"); result = (info.orientation - degrees + 360) % 360; } mCamera.stopPreview(); mCamera.setDisplayOrientation(result); } public boolean acquireCamera(int rotation) { Log.d(tag, "acquireCamera"); if (mCamera != null) { setCameraDisplayOrientation(rotation); mCamera.startPreview(); mCamera.setPreviewCallback(this); mAutoFocusHandler.postDelayed(mAutoFocusRunnable, AUTOFOCUS_FREQUENCY); } else { mCamera = openCamera(); if (mCamera == null) { return false; } mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes(); if (mSupportedPreviewSizes == null) { Log.d(tag, "mSupportedPreviewSizes is null"); } for (Size s : mSupportedPreviewSizes) { Log.d(tag, "Preview size: " + s.width + "x" + s.height); } requestFocus(); setCameraDisplayOrientation(rotation); } return true; } private Camera openCamera() { Camera camera = null; try { camera = Camera.open(); } catch (RuntimeException e) { Log.d(tag, "RuntimeException was thrown while opening the camera"); return null; } if (camera != null) { Log.d(tag, "Back facing camera open by default"); mCameraId = CameraInfo.CAMERA_FACING_BACK; } else { // open first found available camera on a device int cameraCount = Camera.getNumberOfCameras(); for (int camIdx = 0; camIdx < cameraCount; camIdx++) { if (camera != null) break; try { camera = Camera.open(camIdx); CameraInfo info = new CameraInfo(); Camera.getCameraInfo(camIdx, info); mCameraId = camIdx; if (info.facing == CameraInfo.CAMERA_FACING_BACK) { Log.d(tag, "Back camera open"); } else if (info.facing == CameraInfo.CAMERA_FACING_FRONT) { Log.d(tag, "Front camera open"); } else { Log.d(tag, "Unknown camera facing"); } } catch (RuntimeException e) { Log.d(tag, "Camera failed to open: " + e.toString()); } } } return camera; } public void releaseCamera() { mAutoFocusHandler.removeCallbacks(mAutoFocusRunnable); if (mCamera != null) { mCamera.stopPreview(); mCamera.cancelAutoFocus(); } } public void surfaceCreated(SurfaceHolder holder) { // the Surface has been created, acquire the camera and tell it where // to draw. Log.d(tag, "surfaceCreated"); try { if (mCamera != null) { mCamera.setPreviewDisplay(mHolder); mCamera.setPreviewCallback(this); } } catch (IOException exception) { if (mCamera != null) { mCamera.release(); mCamera = null; } Log.e(tag, "IOException caused by setPreviewDisplay()", exception); } } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // now that the size is known, set up the camera parameters and begin // the preview. Log.d(tag, "surfaceChanged: w="+w+",h="+h); if (mCamera != null) { mParams = mCamera.getParameters(); mParams.setPreviewSize(mPreviewSize.width, mPreviewSize.height); requestLayout(); mCamera.setParameters(mParams); mCamera.startPreview(); // Launch autofocus mode mAutoFocusHandler.postDelayed(mAutoFocusRunnable, AUTOFOCUS_FREQUENCY); } } public void surfaceDestroyed(SurfaceHolder holder) { // the surface will be destroyed when we return, so stop the preview. Log.d(tag, "surfaceDestroyed"); if (mCamera != null) { mCamera.stopPreview(); mCamera.setPreviewCallback(null); mCamera.release(); mCamera = null; } } private int mLastKnownWidth = -1; private int mLastKnownHeight = -1; public void onPreviewFrame(byte[] data, Camera camera) { if (mFocusModeOn) return; mCamera.setPreviewCallback(null); int width = mParams.getPreviewSize().width; int height = mParams.getPreviewSize().height; if (width != mLastKnownWidth || height != mLastKnownHeight) { Log.d(tag, "onPreviewFrame w=" + width + " h=" + height); mLastKnownWidth = width; mLastKnownHeight = height; } // Get decoded string String s = zbar.process(width, height, data); if (s != null) { Log.d(tag, "============= URL: " + s + " ================="); mOnQrDecodedListener.onQrDecoded(s); } mCamera.setPreviewCallback(this); } @Override public void onAutoFocus(boolean success, Camera camera) { Log.d(tag, "onAutoFocus()"); mAutoFocusHandler.postDelayed(mAutoFocusRunnable, AUTOFOCUS_FREQUENCY); mFocusModeOn = false; } }
package com.napontaratan.vibernate; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.*; import com.napontaratan.vibernate.model.TimerConflictException; import com.napontaratan.vibernate.model.TimerSession; import com.napontaratan.vibernate.model.TimerSessionHolder; import com.napontaratan.vibernate.view.ColorPickerDialog; import com.napontaratan.vibernate.view.ColorPickerSwatch; import com.napontaratan.vibernate.view.CreateTimerTimePicker; import java.util.ArrayList; import java.util.Calendar; import java.util.List; public class CreateTimerActivity extends FragmentActivity { static final int TIME_DIALOG = 0; DialogFragment timePicker; List<ToggleButton> days; int colorPicked; boolean[] bDays = new boolean[7]; @Override public void onCreate(Bundle savedInstance){ super.onCreate(savedInstance); setContentView(R.layout.create_timer); timePicker = new CreateTimerTimePicker(); /* toolbar */ Toolbar toolbar = (Toolbar) findViewById(R.id.create_timer_toolbar); toolbar.setTitle("New Timer"); toolbar.setNavigationIcon(R.drawable.abc_ic_clear_mtrl_alpha); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); //Menu toolbar.inflateMenu(R.menu.color_menu); toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { String[] color_array = getBaseContext().getResources().getStringArray(R.array.default_color_choice_values); int[] cArray = new int[color_array.length]; for(int k = 0; k < color_array.length; k++){; cArray[k] = Color.parseColor(color_array[k]); } ColorPickerDialog colorCalendar = ColorPickerDialog.newInstance( R.string.color_picker_default_title, cArray, R.color.blue, 5, ColorPickerDialog.SIZE_SMALL); //Implement listener to get selected color value colorCalendar.setOnColorSelectedListener(new ColorPickerSwatch.OnColorSelectedListener() { @Override public void onColorSelected(int color) { Toast.makeText(getBaseContext(), "Color is " + color, Toast.LENGTH_SHORT).show(); colorPicked = color; System.out.println("colorPicked is " + colorPicked); } }); colorCalendar.show(getFragmentManager(),"cal"); return false; } }); /* name field */ final EditText nameField = (EditText) findViewById(R.id.create_timer_name_field); nameField.clearFocus(); /* vibrate or silent mode */ final ToggleButton typeVibrate = (ToggleButton) findViewById(R.id.create_timer_type_vibrate); final ToggleButton typeSilent = (ToggleButton) findViewById(R.id.create_timer_type_silent); typeVibrate.setChecked(true); typeVibrate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(typeSilent.isChecked()) { typeSilent.setChecked(false); } } }); typeSilent.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(typeVibrate.isChecked()) { typeVibrate.setChecked(false); } } }); /* start time & end time */ final TextView startTime = (TextView) findViewById(R.id.create_timer_start_time_clock); final TextView endTime = (TextView) findViewById(R.id.create_timer_end_time_clock); Calendar c = Calendar.getInstance(); int currentHour = c.get(Calendar.HOUR_OF_DAY); int currentMin = c.get(Calendar.MINUTE); int nextHour = currentHour + 1; String minString = (currentMin < 10)? "0" + currentMin: Integer.toString(currentMin); String currentString = currentHour + ":" + minString; String nextString = nextHour + ":" + minString; startTime.setText(currentString); endTime.setText(nextString); startTime.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { timePicker.show(getSupportFragmentManager(), "startTimePicker"); } }); endTime.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { timePicker.show(getSupportFragmentManager(), "endTimePicker"); } }); /* choosing days */ final ToggleButton weekdays_btn = (ToggleButton) findViewById(R.id.create_timer_weekdays_btn); final ToggleButton weekends_btn = (ToggleButton) findViewById(R.id.create_timer_weekends_btn); days = new ArrayList<ToggleButton>(); days.add((ToggleButton) findViewById(R.id.create_timer_sun)); days.add((ToggleButton) findViewById(R.id.create_timer_mon)); days.add((ToggleButton) findViewById(R.id.create_timer_tue)); days.add((ToggleButton) findViewById(R.id.create_timer_wed)); days.add((ToggleButton) findViewById(R.id.create_timer_thu)); days.add((ToggleButton) findViewById(R.id.create_timer_fri)); days.add((ToggleButton) findViewById(R.id.create_timer_sat)); // if sunday is clicked days.get(0).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(days.get(0).isChecked()) { bDays[0] = true; if (days.get(6).isChecked()) weekends_btn.setChecked(true); else weekends_btn.setChecked(false); } else { bDays[0] = false; } } }); // if saturday is clicked days.get(6).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(days.get(6).isChecked()) { bDays[6] = true; if (days.get(0).isChecked()) weekends_btn.setChecked(true); else weekends_btn.setChecked(false); } else { bDays[6] = false; } } }); // if one of the days from mon-fri is clicked for(int i = 1; i < 6; i++){ final int finalI = i; days.get(i).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(days.get(finalI).isChecked()) { bDays[finalI] = true; for(int j = 1; j < 6; j++){ if(!days.get(j).isChecked()) return; } weekdays_btn.setChecked(true); } else { weekdays_btn.setChecked(false); bDays[finalI] = false; } } }); } weekdays_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(weekdays_btn.isChecked()) { for(int i = 0; i < 7; i++){ if(i != 0 && i != 6) { days.get(i).setChecked(true); bDays[i] = true; } } } else { for(int i = 0; i < 7; i++){ if(i != 0 && i != 6) days.get(i).setChecked(false); bDays[i] = false; } } } }); weekends_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(weekends_btn.isChecked()) { for(int i = 0; i < 7; i++){ if(i == 0 || i == 6) { days.get(i).setChecked(true); bDays[i] = true; } } } else { for(int i = 0; i < 7; i++){ if(i == 0 || i == 6) { days.get(i).setChecked(false); bDays[i] = false; } } } } }); /* Click on check mark */ ImageButton done = (ImageButton) findViewById(R.id.add_timer_button); done.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { TimerSession.TimerSessionType type; if(typeVibrate.isChecked()) type = TimerSession.TimerSessionType.VIBRATE; else type = TimerSession.TimerSessionType.SILENT; String start = startTime.getText().toString().replace(":",""); String end = endTime.getText().toString().replace(":",""); createTimerSession(nameField.getText().toString(), type, Integer.parseInt(start.substring(0, 2)), Integer.parseInt(start.substring((2))), Integer.parseInt(end.substring(0, 2)), Integer.parseInt(end.substring((2))), days, R.color.colorAccent); //TODO: color } }); } private void createTimerSession (String name, TimerSession.TimerSessionType type, int startHour, int startMin, int endHour, int endMin, List<ToggleButton> days, int color) { if(name == null || name.equals("")) { createDialog("Insufficient info", "Please specify a timer name."); return; } boolean daySelected = false; for(int i = 0; i < 7; i++) { if(bDays[i]){ daySelected = true; break; } } if(!daySelected) { createDialog("Insufficient info", "Please specify a day."); return; } Calendar start = generateCalendar(startHour, startMin); Calendar end = generateCalendar(endHour, endMin); TimerSession newTimer = new TimerSession(name, type, start, end, bDays,color); try { TimerSessionHolder.getInstance().addTimer(newTimer); } catch (TimerConflictException e) { createDialog("Timer Conflict", "The time specified is in conflict with another timer. Please try again."); return; } Log.d("CreateTimer", "creating timer with the following information: \n" + "Name: " + name + "\n" + "Type: " + type + "\n" + "StartTime" + start.get(Calendar.HOUR_OF_DAY) + ":" + start.get(Calendar.MINUTE) + "\n" + "EndTime" + end.get(Calendar.HOUR_OF_DAY) + ":" + end.get(Calendar.MINUTE) + "\n"); finish(); } private Calendar generateCalendar(int hour, int minute) { Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY, hour); cal.set(Calendar.MINUTE, minute); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal; } public void createDialog(String title, String msg) { new AlertDialog.Builder(this) .setTitle(title) .setMessage(msg) .setIcon(android.R.drawable.ic_dialog_alert) .setNeutralButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); } }).show(); } }
/* vim: set et ts=4 sts=4 sw=4 tw=72 : */ package uk.ac.cam.cl.git; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.LinkedList; import javax.ws.rs.core.Response; import uk.ac.cam.cl.git.public_interfaces.WebInterface; public class GitService implements WebInterface { @Override public Response listRepositories() { List<Repository> repos = ConfigDatabase.getRepos(); List<String> toReturn = new LinkedList<String>(); for (Repository repo : repos) { toReturn.add(repo.getName()); } return Response.status(200).entity(toReturn).build(); } @Override public Response listFiles(String repoName) throws IOException { if (repoName == null) return Response.status(400) .entity("No repository given.").build(); Repository repo = ConfigDatabase.getRepoByName(repoName); if (repo == null) return Response.status(404) .entity("Repository not found in database! " + "It may exist on disk though.").build(); try { repo.openLocal(repoName); } catch (org.eclipse.jgit.errors.RepositoryNotFoundException e) { /* Stale repository entry, remove from database */ ConfigDatabase.delRepoByName(repoName); return Response.status(500) .entity("Repository not found on disk! " + "Removed from database.").build(); } Collection<String> files = repo.getSources(); List<String> rtn = new LinkedList<String>(); if (files != null) for (String file : files) rtn.add(file); return Response.status(200).entity(rtn).build(); } @Override public Response getFile(String fileName , String repoName) throws IOException { if (repoName == null) return Response.status(400) .entity("No repository given.").build(); Repository repo = ConfigDatabase.getRepoByName(repoName); if (repo == null) return Response.status(404) .entity("Repository not found in database! " + "It may exist on disk though.").build(); try { repo.openLocal(repoName); } catch (org.eclipse.jgit.errors.RepositoryNotFoundException e) { /* Stale repository entry, remove from database */ ConfigDatabase.delRepoByName(repoName); return Response.status(500) .entity("Repository not found on disk! " + "Removed from database.").build(); } String output = repo.getFile(fileName); if (output == null) return Response.status(404).build(); return Response.status(200).entity(output).build(); } @Override public Response getForkURL() { // TODO implement return Response.status(503).build(); } }
package net.unikernel.bummel.visual_editor; import com.kitfox.svg.SVGException; import java.awt.Point; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.net.MalformedURLException; import java.util.List; import javax.swing.AbstractAction; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import net.unikernel.bummel.project_model.api.BasicElement; import net.unikernel.bummel.project_model.api.Circuit; import net.unikernel.bummel.project_model.api.Toggle; import org.netbeans.api.visual.action.*; import org.netbeans.api.visual.action.WidgetAction.State; import org.netbeans.api.visual.action.WidgetAction.WidgetMouseEvent; import org.netbeans.api.visual.anchor.AnchorFactory; import org.netbeans.api.visual.anchor.AnchorShape; import org.netbeans.api.visual.anchor.PointShape; import org.netbeans.api.visual.graph.GraphPinScene; import org.netbeans.api.visual.router.RouterFactory; import org.netbeans.api.visual.vmd.VMDConnectionWidget; import org.netbeans.api.visual.widget.ConnectionWidget; import org.netbeans.api.visual.widget.LayerWidget; import org.netbeans.api.visual.widget.Scene; import org.netbeans.api.visual.widget.Widget; import org.openide.nodes.Node; import org.openide.nodes.NodeTransfer; import org.openide.util.Exceptions; /** * * @author mcangel */ public class CircuitGraphPinScene extends GraphPinScene<ElementNode, String, ElementPortNode> { private LayerWidget mainLayer = new LayerWidget(this); private LayerWidget connectionLayer = new LayerWidget(this); private LayerWidget interractionLayer = new LayerWidget(this); private long edgeCounter = 0; private WidgetAction connectAction = ActionFactory.createConnectAction(interractionLayer, new SceneConnectProvider()); private WidgetAction reconnetAction = ActionFactory.createReconnectAction(new SceneReconnectProvider()); private WidgetAction toggleGeneratorAction = new WidgetAction.Adapter(){ @Override public State mouseClicked(Widget widget, WidgetMouseEvent event) { ((ElementNode)findObject(widget)).getLookup().lookup(BasicElement.class).setState( (((ElementNode)findObject(widget)).getLookup().lookup(BasicElement.class).getState()+1)%2); hardcodedCircuitRun(); return State.CONSUMED; } }; private Circuit circuit; public CircuitGraphPinScene(final Circuit circuit) { this.circuit = circuit; this.addChild(mainLayer); this.addChild(connectionLayer); this.addChild(interractionLayer); getActions().addAction(ActionFactory.createAcceptAction(new AcceptProvider() { @Override public ConnectorState isAcceptable(Widget widget, Point point, Transferable transferable) { Node node = NodeTransfer.node(transferable, NodeTransfer.DND_COPY); if (node != null && (node.getLookup().lookup(BasicElement.class)) != null) return ConnectorState.ACCEPT; return ConnectorState.REJECT_AND_STOP; } @Override public void accept(Widget widget, Point point, Transferable transferable) { Node node = NodeTransfer.node(transferable, NodeTransfer.DND_COPY);//Defines the instance from drag and drop action. BasicElement el = node.getLookup().lookup(BasicElement.class); //Get BasicElement instance try { el = el.getClass().newInstance(); //create new instance of it to avoid equality circuit.addElement(el);//add element to the model ElementNode elNode = new ElementNode(el); //create new element node with default constructor Widget nodeWidget = addNode(elNode);//add new ElementNode to the scene nodeWidget.setPreferredLocation(widget.convertLocalToScene(point)); for (String port : el.getPorts()) {//add pins to the scene addPin(elNode, new ElementPortNode(port)); } validate(); nodeWidget.repaint(); } catch (InstantiationException | IllegalAccessException ex) { Exceptions.printStackTrace(ex); } } })); } @Override protected Widget attachNodeWidget(ElementNode node) { ElementWidget widget = null; try { widget = new ElementWidget(this, node); } catch (MalformedURLException | SVGException ex) { Exceptions.printStackTrace(ex); } mainLayer.addChild(widget); if(node.getLookup().lookup(BasicElement.class) instanceof Toggle) { widget.getActions().addAction(toggleGeneratorAction); } widget.getActions().addAction(createSelectAction()); widget.getActions().addAction(ActionFactory.createMoveAction()); widget.getActions().addAction(ActionFactory.createPopupMenuAction(new PopupMenuProvider() { @Override public JPopupMenu getPopupMenu(Widget widget, Point localLocation) { final Widget w = widget; JPopupMenu menu = new JPopupMenu("Menu"); JMenuItem mi = new JMenuItem(new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { circuit.removeElement(((ElementNode)findObject(w)) .getLookup().lookup(BasicElement.class)); CircuitGraphPinScene.this.internalNodeRemove((ElementNode)findObject(w)); hardcodedCircuitRun(); } }); mi.setText("Remove"); menu.add(mi); return menu; } })); return widget; } //TODO - remake this through another thread!!! private void hardcodedCircuitRun() { for(int i = 0, n = circuit.getElements().size(); i < n; i++, circuit.step()){} } /** * Removes object and it's widget from the scene. * @param object - object to be removed. */ private void internalObjectRemove(final Object object) { final List<Widget> widgets = findWidgets(object); //removeObject() does not remove widgets for (final Widget widget : widgets) { widget.removeFromParent(); } } private void internalNodeRemove(final ElementNode node) { //first remove all node pins for(ElementPortNode pin : getNodePins(node)) { //removing pin first romeve all connected edges for(String edge : findPinEdges(pin, true, true)) { internalObjectRemove(edge); } //remove pin itself internalObjectRemove(pin); } //remove node itself internalObjectRemove(node); } @Override protected Widget attachPinWidget(ElementNode node, ElementPortNode pin) { ElementPortWidget widget = new ElementPortWidget(this, node, pin.getPort()); ((ElementWidget) findWidget(node)).attachPortWidget(widget); widget.getActions().addAction(createObjectHoverAction()); widget.getActions().addAction(createSelectAction()); widget.getActions().addAction(connectAction); return widget; } @Override protected Widget attachEdgeWidget(String edge) { VMDConnectionWidget connection = new VMDConnectionWidget(this, RouterFactory.createOrthogonalSearchRouter(mainLayer, connectionLayer)); connection.setTargetAnchorShape(AnchorShape.NONE); connection.setEndPointShape(PointShape.SQUARE_FILLED_BIG); connection.getActions().addAction(createObjectHoverAction()); connection.getActions().addAction(createSelectAction()); connection.getActions().addAction(reconnetAction); connection.getActions().addAction(ActionFactory.createOrthogonalMoveControlPointAction()); connectionLayer.addChild(connection); return connection; } @Override protected void attachEdgeSourceAnchor(String edge, ElementPortNode oldSourcePin, ElementPortNode sourcePin) { Widget w = sourcePin != null ? findWidget(sourcePin) : null; ((ConnectionWidget) findWidget(edge)).setSourceAnchor(AnchorFactory.createRectangularAnchor(w)); //((ConnectionWidget) findWidget(edge)).setSourceAnchor(((ElementPortWidget)w).getAnchor()); //((ConnectionWidget) findWidget(edge)).setSourceAnchor(AnchorFactory.createRectangularAnchor(((ElementPortWidget)w).getAnchorWidget())); } @Override protected void attachEdgeTargetAnchor(String edge, ElementPortNode oldTargetPin, ElementPortNode targetPin) { Widget w = targetPin != null ? findWidget(targetPin) : null; ((ConnectionWidget) findWidget(edge)).setTargetAnchor(AnchorFactory.createRectangularAnchor(w)); //((ConnectionWidget) findWidget(edge)).setSourceAnchor(((ElementPortWidget)w).getAnchor()); //((ConnectionWidget) findWidget(edge)).setSourceAnchor(AnchorFactory.createRectangularAnchor(((ElementPortWidget)w).getAnchorWidget())); } private class SceneConnectProvider implements ConnectProvider { private ElementPortNode source = null; private ElementPortNode target = null; @Override public boolean isSourceWidget(Widget sourceWidget) { Object object = findObject(sourceWidget); source = isPin(object) ? (ElementPortNode) object : null; return source != null; } @Override public ConnectorState isTargetWidget(Widget sourceWidget, Widget targetWidget) { //TODO: add single connection check Object object = findObject(targetWidget); target = isPin(object) ? (ElementPortNode) object : null; if (target != null) { return !source.equals(target) ? ConnectorState.ACCEPT : ConnectorState.REJECT_AND_STOP; } return object != null ? ConnectorState.REJECT_AND_STOP : ConnectorState.REJECT; } @Override public boolean hasCustomTargetWidgetResolver(Scene scene) { return false; } @Override public Widget resolveTargetWidget(Scene scene, Point sceneLocation) { return null; } @Override public void createConnection(Widget sourceWidget, Widget targetWidget) { //connect elements in the model BasicElement srcElem = getPinNode(source) .getLookup().lookup(BasicElement.class); BasicElement tgtElem = getPinNode(target) .getLookup().lookup(BasicElement.class); circuit.connectElements(srcElem, source.getPort(), tgtElem, target.getPort()); hardcodedCircuitRun(); String edge = "edge" + edgeCounter++; addEdge(edge); setEdgeSource(edge, source); setEdgeTarget(edge, target); } } private class SceneReconnectProvider implements ReconnectProvider { String edge; ElementPortNode originalNode; ElementPortNode replacementNode; @Override public void reconnectingStarted(ConnectionWidget connectionWidget, boolean reconnectingSource) { } @Override public void reconnectingFinished(ConnectionWidget connectionWidget, boolean reconnectingSource) { } @Override public boolean isSourceReconnectable(ConnectionWidget connectionWidget) { Object object = findObject(connectionWidget); edge = isEdge(object) ? (String) object : null; originalNode = edge != null ? getEdgeSource(edge) : null; return originalNode != null; } @Override public boolean isTargetReconnectable(ConnectionWidget connectionWidget) { Object object = findObject(connectionWidget); edge = isEdge(object) ? (String) object : null; originalNode = edge != null ? getEdgeTarget(edge) : null; return originalNode != null; } @Override public ConnectorState isReplacementWidget(ConnectionWidget connectionWidget, Widget replacementWidget, boolean reconnectingSource) { Object object = findObject(replacementWidget); replacementNode = isPin(object) ? (ElementPortNode) object : null; if (replacementNode != null) { return ConnectorState.ACCEPT; } return object != null ? ConnectorState.REJECT_AND_STOP : ConnectorState.REJECT; } @Override public boolean hasCustomReplacementWidgetResolver(Scene scene) { return false; } @Override public Widget resolveReplacementWidget(Scene scene, Point sceneLocation) { return null; } @Override public void reconnect(ConnectionWidget connectionWidget, Widget replacementWidget, boolean reconnectingSource) { //remove old connection from the model BasicElement srcElem = getPinNode(getEdgeSource(edge)) .getLookup().lookup(BasicElement.class); BasicElement tgtElem = getPinNode(getEdgeTarget(edge)) .getLookup().lookup(BasicElement.class); circuit.disconnectElements(srcElem, getEdgeSource(edge).getPort(), tgtElem, getEdgeTarget(edge).getPort()); if (replacementWidget == null) { //disconnection already done removeEdge(edge); } else if (reconnectingSource) { //create new connection in the model srcElem = getPinNode(replacementNode) .getLookup().lookup(BasicElement.class); circuit.connectElements(srcElem, replacementNode.getPort(), tgtElem, getEdgeTarget(edge).getPort()); setEdgeSource(edge, replacementNode); } else { //create new connection in the model tgtElem = getPinNode(replacementNode) .getLookup().lookup(BasicElement.class); circuit.connectElements(srcElem, getEdgeSource(edge).getPort(), tgtElem, replacementNode.getPort()); setEdgeTarget(edge, replacementNode); } hardcodedCircuitRun(); } } }
package stanhebben.zenscript.type.expand; import java.util.ArrayList; import java.util.List; import stanhebben.zenscript.compiler.IEnvironmentGlobal; import stanhebben.zenscript.compiler.IEnvironmentMethod; import stanhebben.zenscript.expression.Expression; import stanhebben.zenscript.expression.ExpressionCallStatic; import stanhebben.zenscript.expression.ExpressionCallVirtual; import stanhebben.zenscript.expression.ExpressionInvalid; import stanhebben.zenscript.expression.partial.IPartialExpression; import stanhebben.zenscript.symbols.IZenSymbol; import stanhebben.zenscript.type.ZenType; import stanhebben.zenscript.type.natives.IJavaMethod; import stanhebben.zenscript.type.natives.JavaMethod; import static stanhebben.zenscript.util.StringUtil.methodMatchingError; import stanhebben.zenscript.util.ZenPosition; /** * * @author Stan */ public class ZenExpandMember { private final String type; private final String name; private IJavaMethod getter; private IJavaMethod setter; private final List<IJavaMethod> methods = new ArrayList<IJavaMethod>(); public ZenExpandMember(String type, String name) { this.type = type; this.name = name; } public IPartialExpression instance(ZenPosition position, IEnvironmentGlobal environment, IPartialExpression value) { return new InstanceGetValue(position, value); } public IPartialExpression instance(ZenPosition position, IEnvironmentGlobal environment) { return new StaticGetValue(position); } public void setGetter(IJavaMethod getter) { if (this.getter != null) { throw new RuntimeException(type + "." + name + " already has a getter"); } else { this.getter = getter; } } public void setSetter(IJavaMethod setter) { if (this.setter != null) { throw new RuntimeException(type + "." + name + " already has a setter"); } else { this.setter = setter; } } public void addMethod(IJavaMethod method) { methods.add(method); } private class InstanceGetValue implements IPartialExpression { private final ZenPosition position; private final IPartialExpression value; public InstanceGetValue(ZenPosition position, IPartialExpression value) { this.position = position; this.value = value; } @Override public Expression eval(IEnvironmentGlobal environment) { return new ExpressionCallStatic(position, environment, getter, value.eval(environment)); } @Override public Expression assign(ZenPosition position, IEnvironmentGlobal environment, Expression other) { return new ExpressionCallStatic(position, environment, setter, value.eval(environment), other); } @Override public IPartialExpression getMember(ZenPosition position, IEnvironmentGlobal environment, String name) { return getter.getReturnType().getMember(position, environment, this, name); } @Override public Expression call(ZenPosition position, IEnvironmentMethod environment, Expression... values) { Expression[] newValues = new Expression[values.length + 1]; newValues[0] = value.eval(environment); System.arraycopy(values, 0, newValues, 1, values.length); IJavaMethod method = JavaMethod.select(true, methods, environment, newValues); if (method == null) { environment.error(position, methodMatchingError(methods, values)); return new ExpressionInvalid(position); } else { return new ExpressionCallStatic(position, environment, method, newValues); } } @Override public IZenSymbol toSymbol() { return null; } @Override public ZenType getType() { return getter.getReturnType(); } @Override public ZenType toType(IEnvironmentGlobal environment) { environment.error(position, "not a valid type"); return ZenType.ANY; } @Override public ZenType[] predictCallTypes(int numArguments) { ZenType[] base = JavaMethod.predict(methods, numArguments + 1); ZenType[] result = new ZenType[base.length - 1]; for (int i = 0; i < result.length; i++) { result[i] = base[i + 1]; } return result; } } private class StaticGetValue implements IPartialExpression { private final ZenPosition position; public StaticGetValue(ZenPosition position) { this.position = position; } @Override public Expression eval(IEnvironmentGlobal environment) { return new ExpressionCallStatic(position, environment, getter); } @Override public Expression assign(ZenPosition position, IEnvironmentGlobal environment, Expression other) { return new ExpressionCallStatic(position, environment, setter, other); } @Override public IPartialExpression getMember(ZenPosition position, IEnvironmentGlobal environment, String name) { return getter.getReturnType().getMember(position, environment, this, name); } @Override public Expression call(ZenPosition position, IEnvironmentMethod environment, Expression... values) { IJavaMethod method = JavaMethod.select(true, methods, environment, values); if (method == null) { environment.error(position, methodMatchingError(methods, values)); return new ExpressionInvalid(position); } else { return new ExpressionCallStatic(position, environment, method, values); } } @Override public IZenSymbol toSymbol() { return new StaticSymbol(); } @Override public ZenType getType() { return getter.getReturnType(); } @Override public ZenType toType(IEnvironmentGlobal environment) { environment.error(position, "not a valid type"); return ZenType.ANY; } @Override public ZenType[] predictCallTypes(int numArguments) { return JavaMethod.predict(methods, numArguments); } } private class StaticSymbol implements IZenSymbol { @Override public IPartialExpression instance(ZenPosition position) { return new StaticGetValue(position); } } }
package ruby.keyboardwarrior.ui; import ruby.keyboardwarrior.data.task.Task; import java.util.ArrayList; import java.util.List; //@@author A0139716X /** * Used for formatting text for display. e.g. for adding text decorations. */ public class Formatter { /** * Format of indexed list item */ private static final String MESSAGE_INDEXED_LIST_ITEM = "\t%1$d) %2$s"; /** * Offset required to convert between 1-indexing and 0-indexing. */ private static final int DISPLAYED_INDEX_OFFSET = 1; /** * Formats the given strings for displaying to the user. */ public String format(String... messages) { StringBuilder sb = new StringBuilder(); for (String m : messages) { sb.append(m + "\n"); } return sb.toString(); } /** * Formats the given list of task for displaying to the user. */ public String format(List<Task> Tasks) { final List<String> formattedTasks = new ArrayList<>(); for (Task Task : Tasks) { formattedTasks.add(Task.toString()); } return format(asIndexedList(formattedTasks)); } /** * Formats a list of strings as an indexed list. */ private static String asIndexedList(List<String> listItems) { final StringBuilder formatted = new StringBuilder(); int displayIndex = 0 + DISPLAYED_INDEX_OFFSET; for (String listItem : listItems) { if(displayIndex == listItems.size()) formatted.append(getIndexedListItem(displayIndex, listItem)); else formatted.append(getIndexedListItem(displayIndex, listItem)).append("\n"); displayIndex++; } return formatted.toString(); } /** * Formats a string as an indexed list item. * * @param visibleIndex index for this listing */ private static String getIndexedListItem(int visibleIndex, String listItem) { return String.format(MESSAGE_INDEXED_LIST_ITEM, visibleIndex, listItem); } }
package org.springframework.roo.addon.dbre; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import org.jvnet.inflector.Noun; import org.springframework.roo.addon.dbre.model.Column; import org.springframework.roo.addon.dbre.model.Database; import org.springframework.roo.addon.dbre.model.ForeignKey; import org.springframework.roo.addon.dbre.model.JoinTable; import org.springframework.roo.addon.dbre.model.Reference; import org.springframework.roo.addon.dbre.model.Table; import org.springframework.roo.addon.entity.EntityMetadata; import org.springframework.roo.addon.entity.RooEntity; import org.springframework.roo.addon.entity.RooIdentifier; import org.springframework.roo.classpath.PhysicalTypeIdentifier; import org.springframework.roo.classpath.PhysicalTypeIdentifierNamingUtils; import org.springframework.roo.classpath.PhysicalTypeMetadata; import org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails; import org.springframework.roo.classpath.details.DefaultFieldMetadata; import org.springframework.roo.classpath.details.DefaultMethodMetadata; import org.springframework.roo.classpath.details.FieldMetadata; import org.springframework.roo.classpath.details.MemberFindingUtils; import org.springframework.roo.classpath.details.MethodMetadata; import org.springframework.roo.classpath.details.annotations.AnnotatedJavaType; import org.springframework.roo.classpath.details.annotations.AnnotationAttributeValue; import org.springframework.roo.classpath.details.annotations.AnnotationMetadata; import org.springframework.roo.classpath.details.annotations.ArrayAttributeValue; import org.springframework.roo.classpath.details.annotations.DefaultAnnotationMetadata; import org.springframework.roo.classpath.details.annotations.EnumAttributeValue; import org.springframework.roo.classpath.details.annotations.IntegerAttributeValue; import org.springframework.roo.classpath.details.annotations.NestedAnnotationAttributeValue; import org.springframework.roo.classpath.details.annotations.StringAttributeValue; import org.springframework.roo.classpath.details.annotations.populator.AutoPopulationUtils; import org.springframework.roo.classpath.itd.AbstractItdTypeDetailsProvidingMetadataItem; import org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder; import org.springframework.roo.classpath.operations.Cardinality; import org.springframework.roo.classpath.operations.jsr303.SetField; import org.springframework.roo.metadata.MetadataIdentificationUtils; import org.springframework.roo.metadata.MetadataService; import org.springframework.roo.model.DataType; import org.springframework.roo.model.EnumDetails; import org.springframework.roo.model.JavaPackage; import org.springframework.roo.model.JavaSymbolName; import org.springframework.roo.model.JavaType; import org.springframework.roo.project.Path; import org.springframework.roo.support.util.Assert; import org.springframework.roo.support.util.StringUtils; /** * Metadata for {@link RooDbManaged}. * * <p> * Creates and manages entity relationships, such as many-valued and single-valued associations. * * <p> * One-to-many and one-to-one associations are created based on the following laws: * <ul> * <li>Primary Key (PK) - Foreign Key (FK) LAW #1: If the foreign key column is part of the primary key (or part of an index) then the relationship between the tables will be one to many (1:M). * <li>Primary Key (PK) - Foreign Key (FK) LAW #2: If the foreign key column represents the entire primary key (or the entire index) then the relationship between the tables will be one to one (1:1). * </ul> * * <p> * Many-to-many associations are created if a join table is detected. To be identified as a many-to-many join table, the table must have have exactly two primary keys and have exactly two foreign-keys * pointing to other entity tables and have no other columns. * * @author Alan Stewart * @since 1.1 */ public class DbreMetadata extends AbstractItdTypeDetailsProvidingMetadataItem { private static final String PROVIDES_TYPE_STRING = DbreMetadata.class.getName(); private static final String PROVIDES_TYPE = MetadataIdentificationUtils.create(PROVIDES_TYPE_STRING); private static final JavaType ONE_TO_ONE = new JavaType("javax.persistence.OneToOne"); private static final JavaType ONE_TO_MANY = new JavaType("javax.persistence.OneToMany"); private static final JavaType MANY_TO_ONE = new JavaType("javax.persistence.ManyToOne"); private static final JavaType MANY_TO_MANY = new JavaType("javax.persistence.ManyToMany"); private static final JavaType JOIN_COLUMN = new JavaType("javax.persistence.JoinColumn"); private static final JavaSymbolName NAME = new JavaSymbolName("name"); private static final JavaSymbolName VALUE = new JavaSymbolName("value"); private static final JavaSymbolName MAPPED_BY = new JavaSymbolName("mappedBy"); private static final JavaSymbolName REFERENCED_COLUMN = new JavaSymbolName("referencedColumnName"); private EntityMetadata entityMetadata; private MetadataService metadataService; private TableModelService tableModelService; public DbreMetadata(String identifier, JavaType aspectName, PhysicalTypeMetadata governorPhysicalTypeMetadata, EntityMetadata entityMetadata, MetadataService metadataService, TableModelService tableModelService, Database database) { super(identifier, aspectName, governorPhysicalTypeMetadata); Assert.isTrue(isValid(identifier), "Metadata identification string '" + identifier + "' does not appear to be a valid"); this.entityMetadata = entityMetadata; this.metadataService = metadataService; this.tableModelService = tableModelService; // Process values from the annotation, if present AnnotationMetadata annotation = MemberFindingUtils.getDeclaredTypeAnnotation(governorTypeDetails, new JavaType(RooDbManaged.class.getName())); if (annotation != null) { AutoPopulationUtils.populate(this, annotation); } JavaType javaType = governorPhysicalTypeMetadata.getPhysicalTypeDetails().getName(); Table table = database.findTable(tableModelService.suggestTableNameForNewType(javaType)); if (table == null) { return; } // Add fields for many-valued associations with many-to-many multiplicity addManyToManyFields(database, table); // Add fields for many-valued associations with one-to-many multiplicity addOneToManyFields(database, table); // Add fields for single-valued associations to other entities that have many-to-one multiplicity addManyToOneFields(database, table); // Add fields for single-valued associations to other entities that have one-to-one multiplicity addOneToOneFields(database, table); // Add remaining fields from columns addOtherFields(javaType, table); // Create a representation of the desired output ITD itdTypeDetails = builder.build(); } private void addManyToManyFields(Database database, Table table) { int manyToManyCount = database.getJoinTables().size() > 1 ? 1 : 0; for (JoinTable joinTable : database.getJoinTables()) { if (joinTable.getOwningSideTable().equals(table)) { String fieldNameStr = getInflectorPlural(tableModelService.suggestFieldName(joinTable.getInverseSideTable().getName())); if (manyToManyCount > 0) { fieldNameStr += String.valueOf(manyToManyCount); } JavaSymbolName fieldName = new JavaSymbolName(fieldNameStr); FieldMetadata field = getManyToManyOwningSideField(fieldName, joinTable, database.getJavaPackage()); addToBuilder(field); } if (joinTable.getInverseSideTable().equals(table)) { String fieldNameStr = getInflectorPlural(tableModelService.suggestFieldName(joinTable.getOwningSideTable().getName())); String mappedByFieldNameStr = getInflectorPlural(tableModelService.suggestFieldName(joinTable.getInverseSideTable().getName())); if (manyToManyCount > 0) { fieldNameStr += String.valueOf(manyToManyCount); mappedByFieldNameStr += String.valueOf(manyToManyCount); } JavaSymbolName fieldName = new JavaSymbolName(fieldNameStr); JavaSymbolName mappedByFieldName = new JavaSymbolName(mappedByFieldNameStr); FieldMetadata field = getManyToManyInverseSideField(fieldName, mappedByFieldName, joinTable, database.getJavaPackage()); addToBuilder(field); } manyToManyCount++; } } private void addOneToManyFields(Database database, Table table) { if (!database.isJoinTable(table)) { for (ForeignKey exportedKey : table.getExportedKeys()) { if (!database.isJoinTable(exportedKey.getForeignTable())) { String foreignTableName = exportedKey.getForeignTableName(); Table foreignTable = database.findTable(foreignTableName); Assert.notNull(foreignTable, "Related table '" + foreignTableName + "' could not be found but was referenced by table '" + table.getName() + "'"); boolean isOneToOne = true; Iterator<ForeignKey> foreignKeyIterator = foreignTable.getForeignKeys().iterator(); while (isOneToOne && foreignKeyIterator.hasNext()) { isOneToOne &= isOneToOne(foreignTable, foreignKeyIterator.next()); } if (!isOneToOne) { int oneToManyCount = exportedKey.getReferenceCount(); for (int i = 1; i <= oneToManyCount; i++) { String fieldSuffix = oneToManyCount > 1 ? String.valueOf(i) : ""; String fieldNameStr = getInflectorPlural(tableModelService.suggestFieldName(foreignTableName)) + fieldSuffix; String mappedByFieldNameStr = tableModelService.suggestFieldName(table.getName()) + fieldSuffix; JavaSymbolName fieldName = new JavaSymbolName(fieldNameStr); JavaSymbolName mappedByFieldName = new JavaSymbolName(mappedByFieldNameStr); FieldMetadata field = getOneToManyMappedByField(fieldName, mappedByFieldName, foreignTableName, database.getJavaPackage()); addToBuilder(field); } } } } } } private void addManyToOneFields(Database database, Table table) { // Add unique many-to-one fields Map<JavaSymbolName, FieldMetadata> uniqueFields = new LinkedHashMap<JavaSymbolName, FieldMetadata>(); for (Column column : table.getColumns()) { String columnName = column.getName(); ForeignKey foreignKey = table.findForeignKeyByLocalColumnName(columnName); if (foreignKey != null && !isOneToOne(table, foreignKey)) { // Assume many-to-one multiplicity int manyToOneCount = foreignKey.getReferenceCount() > 1 ? 1 : 0; for (Reference reference : foreignKey.getReferences()) { String fieldNameStr = tableModelService.suggestFieldName(foreignKey.getForeignTableName()); if (manyToOneCount > 0) { fieldNameStr += String.valueOf(manyToOneCount); } JavaSymbolName fieldName = new JavaSymbolName(fieldNameStr); JavaType fieldType = tableModelService.suggestTypeNameForNewTable(foreignKey.getForeignTableName(), database.getJavaPackage()); Assert.notNull(fieldType, getErrorMsg(foreignKey.getForeignTableName())); FieldMetadata field = getManyToOneField(fieldName, fieldType, reference.getLocalColumn(), reference.getForeignColumn()); uniqueFields.put(fieldName, field); manyToOneCount++; } } } for (FieldMetadata field : uniqueFields.values()) { addToBuilder(field); } } private void addOneToOneFields(Database database, Table table) { // Add unique one-to-one fields Map<JavaSymbolName, FieldMetadata> uniqueFields = new LinkedHashMap<JavaSymbolName, FieldMetadata>(); for (Column column : table.getColumns()) { ForeignKey foreignKey = table.findForeignKeyByLocalColumnName(column.getName()); if (foreignKey != null && isOneToOne(table, foreignKey)) { JavaSymbolName fieldName = new JavaSymbolName(tableModelService.suggestFieldName(foreignKey.getForeignTableName())); JavaType fieldType = tableModelService.suggestTypeNameForNewTable(foreignKey.getForeignTableName(), database.getJavaPackage()); Assert.notNull(fieldType, getErrorMsg(foreignKey.getForeignTableName())); FieldMetadata field = getOneToOneField(fieldName, fieldType, foreignKey, column); uniqueFields.put(fieldName, field); } } for (FieldMetadata field : uniqueFields.values()) { addToBuilder(field); } // Add one-to-one mapped-by fields if (!database.isJoinTable(table)) { for (ForeignKey exportedKey : table.getExportedKeys()) { if (!database.isJoinTable(exportedKey.getForeignTable())) { String foreignTableName = exportedKey.getForeignTableName(); Table foreignTable = database.findTable(foreignTableName); Assert.notNull(foreignTable, "Related table '" + foreignTableName + "' could not be found but was referenced by table '" + table.getName() + "'"); boolean isOneToOne = true; Iterator<ForeignKey> foreignKeyIterator = foreignTable.getForeignKeys().iterator(); while (isOneToOne && foreignKeyIterator.hasNext()) { isOneToOne &= isOneToOne(foreignTable, foreignKeyIterator.next()); } if (isOneToOne) { JavaSymbolName fieldName = new JavaSymbolName(tableModelService.suggestFieldName(foreignTableName)); JavaType fieldType = tableModelService.findTypeForTableName(foreignTableName, database.getJavaPackage()); Assert.notNull(fieldType, getErrorMsg(foreignTableName)); JavaSymbolName mappedByFieldName = new JavaSymbolName(tableModelService.suggestFieldName(table.getName())); FieldMetadata field = getOneToOneMappedByField(fieldName, fieldType, mappedByFieldName); addToBuilder(field); } } } } } private FieldMetadata getManyToManyOwningSideField(JavaSymbolName fieldName, JoinTable joinTable, JavaPackage javaPackage) { List<JavaType> params = new ArrayList<JavaType>(); JavaType element = tableModelService.findTypeForTableName(joinTable.getInverseSideTable().getName(), javaPackage); Assert.notNull(element, getErrorMsg(joinTable.getInverseSideTable().getName())); params.add(element); String physicalTypeIdentifier = PhysicalTypeIdentifier.createIdentifier(element, Path.SRC_MAIN_JAVA); SetField fieldDetails = new SetField(physicalTypeIdentifier, new JavaType("java.util.Set", 0, DataType.TYPE, null, params), fieldName, element, Cardinality.MANY_TO_MANY); // Add annotations to field List<AnnotationMetadata> annotations = new ArrayList<AnnotationMetadata>(); // Add @ManyToMany annotation AnnotationMetadata manyToManyAnnotation = new DefaultAnnotationMetadata(MANY_TO_MANY, new ArrayList<AnnotationAttributeValue<?>>()); annotations.add(manyToManyAnnotation); // Add @JoinTable annotation List<AnnotationAttributeValue<?>> joinTableAnnotationAttributes = new ArrayList<AnnotationAttributeValue<?>>(); joinTableAnnotationAttributes.add(new StringAttributeValue(NAME, joinTable.getTable().getName())); // Add joinColumns attribute containing nested @JoinColumn annotation List<NestedAnnotationAttributeValue> joinColumnArrayValues = new ArrayList<NestedAnnotationAttributeValue>(); List<AnnotationAttributeValue<?>> joinColumnAttributes = new ArrayList<AnnotationAttributeValue<?>>(); joinColumnAttributes.add(new StringAttributeValue(NAME, joinTable.getPrimaryKeyOfOwningSideTable())); AnnotationMetadata joinColumnAnnotation = new DefaultAnnotationMetadata(JOIN_COLUMN, joinColumnAttributes); joinColumnArrayValues.add(new NestedAnnotationAttributeValue(VALUE, joinColumnAnnotation)); joinTableAnnotationAttributes.add(new ArrayAttributeValue<NestedAnnotationAttributeValue>(new JavaSymbolName("joinColumns"), joinColumnArrayValues)); // Add inverseJoinColumns attribute containing nested @JoinColumn annotation List<NestedAnnotationAttributeValue> inverseJoinColumnArrayValues = new ArrayList<NestedAnnotationAttributeValue>(); List<AnnotationAttributeValue<?>> inverseJoinColumnAttributes = new ArrayList<AnnotationAttributeValue<?>>(); inverseJoinColumnAttributes.add(new StringAttributeValue(NAME, joinTable.getPrimaryKeyOfInverseSideTable())); AnnotationMetadata inverseJoinColumnAnnotation = new DefaultAnnotationMetadata(JOIN_COLUMN, inverseJoinColumnAttributes); inverseJoinColumnArrayValues.add(new NestedAnnotationAttributeValue(VALUE, inverseJoinColumnAnnotation)); joinTableAnnotationAttributes.add(new ArrayAttributeValue<NestedAnnotationAttributeValue>(new JavaSymbolName("inverseJoinColumns"), inverseJoinColumnArrayValues)); AnnotationMetadata joinTableAnnotation = new DefaultAnnotationMetadata(new JavaType("javax.persistence.JoinTable"), joinTableAnnotationAttributes); annotations.add(joinTableAnnotation); return new DefaultFieldMetadata(getId(), Modifier.PRIVATE, fieldDetails.getFieldName(), fieldDetails.getFieldType(), null, annotations); } private FieldMetadata getManyToManyInverseSideField(JavaSymbolName fieldName, JavaSymbolName mappedByFieldName, JoinTable joinTable, JavaPackage javaPackage) { List<JavaType> params = new ArrayList<JavaType>(); JavaType element = tableModelService.findTypeForTableName(joinTable.getOwningSideTable().getName(), javaPackage); Assert.notNull(element, getErrorMsg(joinTable.getOwningSideTable().getName())); params.add(element); String physicalTypeIdentifier = PhysicalTypeIdentifier.createIdentifier(element, Path.SRC_MAIN_JAVA); SetField fieldDetails = new SetField(physicalTypeIdentifier, new JavaType("java.util.Set", 0, DataType.TYPE, null, params), fieldName, element, Cardinality.MANY_TO_MANY); // Add annotations to field List<AnnotationMetadata> annotations = new ArrayList<AnnotationMetadata>(); List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>(); attributes.add(new StringAttributeValue(MAPPED_BY, mappedByFieldName.getSymbolName())); AnnotationMetadata annotation = new DefaultAnnotationMetadata(MANY_TO_MANY, attributes); annotations.add(annotation); return new DefaultFieldMetadata(getId(), Modifier.PRIVATE, fieldDetails.getFieldName(), fieldDetails.getFieldType(), null, annotations); } private FieldMetadata getOneToManyMappedByField(JavaSymbolName fieldName, JavaSymbolName mappedByFieldName, String foreignTableName, JavaPackage javaPackage) { List<JavaType> params = new ArrayList<JavaType>(); JavaType element = tableModelService.findTypeForTableName(foreignTableName, javaPackage); Assert.notNull(element, getErrorMsg(foreignTableName)); params.add(element); String physicalTypeIdentifier = PhysicalTypeIdentifier.createIdentifier(element, Path.SRC_MAIN_JAVA); SetField fieldDetails = new SetField(physicalTypeIdentifier, new JavaType("java.util.Set", 0, DataType.TYPE, null, params), fieldName, element, Cardinality.ONE_TO_MANY); // Add @OneToMany annotation List<AnnotationMetadata> annotations = new ArrayList<AnnotationMetadata>(); List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>(); attributes.add(new StringAttributeValue(MAPPED_BY, mappedByFieldName.getSymbolName())); AnnotationMetadata annotation = new DefaultAnnotationMetadata(ONE_TO_MANY, attributes); annotations.add(annotation); return new DefaultFieldMetadata(getId(), Modifier.PRIVATE, fieldDetails.getFieldName(), fieldDetails.getFieldType(), null, annotations); } public FieldMetadata getManyToOneField(JavaSymbolName fieldName, JavaType fieldType, Column localColumn, Column foreignColumn) { // Add annotations to field List<AnnotationMetadata> annotations = new ArrayList<AnnotationMetadata>(); // Add @ManyToOne annotation AnnotationMetadata manyToOneAnnotation = new DefaultAnnotationMetadata(MANY_TO_ONE, new ArrayList<AnnotationAttributeValue<?>>()); annotations.add(manyToOneAnnotation); // Add @JoinColumn annotation List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>(); attributes.add(new StringAttributeValue(NAME, localColumn.getName())); attributes.add(new StringAttributeValue(REFERENCED_COLUMN, foreignColumn.getName())); AnnotationMetadata joinColumnAnnotation = new DefaultAnnotationMetadata(JOIN_COLUMN, attributes); annotations.add(joinColumnAnnotation); return new DefaultFieldMetadata(getId(), Modifier.PRIVATE, fieldName, fieldType, null, annotations); } public boolean isOneToOne(Table table, ForeignKey foreignKey) { boolean equals = table.getPrimaryKeyCount() == foreignKey.getReferenceCount(); Iterator<Column> primaryKeyIterator = table.getPrimaryKeys().iterator(); while (equals && primaryKeyIterator.hasNext()) { equals &= foreignKey.hasLocalColumn(primaryKeyIterator.next()); } return equals; } public FieldMetadata getOneToOneField(JavaSymbolName fieldName, JavaType fieldType, ForeignKey foreignKey, Column column) { // Add annotations to field List<AnnotationMetadata> annotations = new ArrayList<AnnotationMetadata>(); // Add @OneToOne annotation AnnotationMetadata oneToOneAnnotation = new DefaultAnnotationMetadata(ONE_TO_ONE, new ArrayList<AnnotationAttributeValue<?>>()); annotations.add(oneToOneAnnotation); if (foreignKey.getReferenceCount() == 1) { // Add @JoinColumn annotation List<AnnotationAttributeValue<?>> joinColumnAttributes = new ArrayList<AnnotationAttributeValue<?>>(); joinColumnAttributes.add(new StringAttributeValue(NAME, column.getName())); AnnotationMetadata joinColumnAnnotation = new DefaultAnnotationMetadata(JOIN_COLUMN, joinColumnAttributes); annotations.add(joinColumnAnnotation); } else { // Add @JoinColumns annotations List<NestedAnnotationAttributeValue> joinColumnsArrayValues = new ArrayList<NestedAnnotationAttributeValue>(); for (org.springframework.roo.addon.dbre.model.Reference reference : foreignKey.getReferences()) { List<AnnotationAttributeValue<?>> joinColumnAttributes = new ArrayList<AnnotationAttributeValue<?>>(); joinColumnAttributes.add(new StringAttributeValue(NAME, reference.getLocalColumnName())); joinColumnAttributes.add(new StringAttributeValue(REFERENCED_COLUMN, reference.getForeignColumnName())); AnnotationMetadata joinColumnAnnotation = new DefaultAnnotationMetadata(JOIN_COLUMN, joinColumnAttributes); joinColumnsArrayValues.add(new NestedAnnotationAttributeValue(VALUE, joinColumnAnnotation)); } List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>(); attributes.add(new ArrayAttributeValue<NestedAnnotationAttributeValue>(VALUE, joinColumnsArrayValues)); AnnotationMetadata joinColumnsAnnotation = new DefaultAnnotationMetadata(new JavaType("javax.persistence.JoinColumns"), attributes); annotations.add(joinColumnsAnnotation); } return new DefaultFieldMetadata(getId(), Modifier.PRIVATE, fieldName, fieldType, null, annotations); } private FieldMetadata getOneToOneMappedByField(JavaSymbolName fieldName, JavaType fieldType, JavaSymbolName mappedByFieldName) { // Add @OneToOne annotation List<AnnotationMetadata> annotations = new ArrayList<AnnotationMetadata>(); List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>(); attributes.add(new StringAttributeValue(MAPPED_BY, mappedByFieldName.getSymbolName())); AnnotationMetadata oneToOneAnnotation = new DefaultAnnotationMetadata(ONE_TO_ONE, attributes); annotations.add(oneToOneAnnotation); return new DefaultFieldMetadata(getId(), Modifier.PRIVATE, fieldName, fieldType, null, annotations); } private void addOtherFields(JavaType javaType, Table table) { Map<JavaSymbolName, FieldMetadata> uniqueFields = new LinkedHashMap<JavaSymbolName, FieldMetadata>(); for (Column column : table.getColumns()) { String columnName = column.getName(); JavaSymbolName fieldName = new JavaSymbolName(tableModelService.suggestFieldName(columnName)); boolean isCompositeKeyField = isCompositeKeyField(fieldName, javaType); FieldMetadata field = null; if ((isEmbeddedIdField(fieldName) && !isCompositeKeyField) || (isIdField(fieldName) && !column.isPrimaryKey())) { fieldName = getUniqueFieldName(fieldName); field = getField(fieldName, column); uniqueFields.put(fieldName, field); } else if ((getIdField() != null && column.isPrimaryKey()) || table.findForeignKeyByLocalColumnName(columnName) != null || (table.findExportedKeyByLocalColumnName(columnName) != null && table.findUniqueReference(columnName) != null)) { field = null; } else if (!isCompositeKeyField) { field = getField(fieldName, column); uniqueFields.put(fieldName, field); } } for (FieldMetadata field : uniqueFields.values()) { addToBuilder(field); } } @SuppressWarnings("unchecked") public boolean isCompositeKeyField(JavaSymbolName fieldName, JavaType javaType) { // Check for identifier class and exclude fields that are part of the composite primary key AnnotationMetadata entityAnnotation = MemberFindingUtils.getDeclaredTypeAnnotation(governorTypeDetails, new JavaType(RooEntity.class.getName())); AnnotationAttributeValue<?> identifierTypeAttribute = entityAnnotation.getAttribute(new JavaSymbolName("identifierType")); if (identifierTypeAttribute != null) { // Attribute identifierType exists so get the value JavaType identifierType = (JavaType) identifierTypeAttribute.getValue(); if (identifierType != null && !identifierType.getFullyQualifiedTypeName().startsWith("java.lang")) { // The identifierType is not a simple type, ie not of type 'java.lang', so find the type String declaredByMetadataId = PhysicalTypeIdentifier.createIdentifier(identifierType, Path.SRC_MAIN_JAVA); PhysicalTypeMetadata identifierPhysicalTypeMetadata = (PhysicalTypeMetadata) metadataService.get(declaredByMetadataId); if (identifierPhysicalTypeMetadata != null) { // The identifierType exists ClassOrInterfaceTypeDetails identifierTypeDetails = (ClassOrInterfaceTypeDetails) identifierPhysicalTypeMetadata.getPhysicalTypeDetails(); if (identifierTypeDetails != null) { // Check governor for declared fields List<? extends FieldMetadata> identifierFields = identifierTypeDetails.getDeclaredFields(); // Loop through declared fields to check the supplied field exists on the governor for (FieldMetadata field : identifierFields) { if (fieldName.equals(field.getFieldName())) { return true; } } // Field doesn't exists so then check @RooIdentifier annotation for idFields attribute AnnotationMetadata identifierAnnotation = MemberFindingUtils.getAnnotationOfType(identifierTypeDetails.getTypeAnnotations(), new JavaType(RooIdentifier.class.getName())); if (identifierAnnotation != null) { ArrayAttributeValue<StringAttributeValue> idFieldsAttribute = (ArrayAttributeValue<StringAttributeValue>) identifierAnnotation.getAttribute(new JavaSymbolName("idFields")); if (idFieldsAttribute != null) { List<StringAttributeValue> idFields = idFieldsAttribute.getValue(); for (StringAttributeValue idField : idFields) { if (fieldName.equals(new JavaSymbolName(idField.getValue()))) { // Attribute idFields contains the field return true; } } } } } } } } return false; } public boolean isIdField(JavaSymbolName fieldName) { List<FieldMetadata> idFields = MemberFindingUtils.getFieldsWithAnnotation(governorTypeDetails, new JavaType("javax.persistence.Id")); if (idFields.size() > 0) { Assert.isTrue(idFields.size() == 1, "More than one field was annotated with @Id in '" + governorTypeDetails.getName().getFullyQualifiedTypeName() + "'"); return idFields.get(0).getFieldName().equals(fieldName); } return false; } public JavaSymbolName getIdField() { List<FieldMetadata> idFields = MemberFindingUtils.getFieldsWithAnnotation(governorTypeDetails, new JavaType("javax.persistence.Id")); if (idFields.size() > 0) { Assert.isTrue(idFields.size() == 1, "More than one field was annotated with @Id in '" + governorTypeDetails.getName().getFullyQualifiedTypeName() + "'"); return idFields.get(0).getFieldName(); } return null; } public boolean isEmbeddedIdField(JavaSymbolName fieldName) { List<FieldMetadata> embeddedIdFields = MemberFindingUtils.getFieldsWithAnnotation(governorTypeDetails, new JavaType("javax.persistence.EmbeddedId")); if (embeddedIdFields.size() > 0) { Assert.isTrue(embeddedIdFields.size() == 1, "More than one field was annotated with @EmbeddedId in '" + governorTypeDetails.getName().getFullyQualifiedTypeName() + "'"); return embeddedIdFields.get(0).getFieldName().equals(fieldName); } return false; } public FieldMetadata getField(JavaSymbolName fieldName, Column column) { JavaType fieldType = column.getType().getJavaType(); // Add annotations to field List<AnnotationMetadata> annotations = new ArrayList<AnnotationMetadata>(); // Add @NotNull if applicable if (column.isRequired()) { AnnotationMetadata notNullAnnotation = new DefaultAnnotationMetadata(new JavaType("javax.validation.constraints.NotNull"), new ArrayList<AnnotationAttributeValue<?>>()); annotations.add(notNullAnnotation); } // Add @Column annotation List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>(); attributes.add(new StringAttributeValue(NAME, column.getName())); // Add length attribute for Strings if (fieldType.equals(JavaType.STRING_OBJECT)) { attributes.add(new IntegerAttributeValue(new JavaSymbolName("length"), column.getSize())); } // Add JSR 220 @Temporal annotation to date fields if (fieldType.equals(new JavaType("java.util.Date"))) { List<AnnotationAttributeValue<?>> attrs = new ArrayList<AnnotationAttributeValue<?>>(); attrs.add(new EnumAttributeValue(new JavaSymbolName("value"), new EnumDetails(new JavaType("javax.persistence.TemporalType"), new JavaSymbolName(column.getType().name())))); AnnotationMetadata temporalAnnotation = new DefaultAnnotationMetadata(new JavaType("javax.persistence.Temporal"), attrs); annotations.add(temporalAnnotation); } AnnotationMetadata columnAnnotation = new DefaultAnnotationMetadata(new JavaType("javax.persistence.Column"), attributes); annotations.add(columnAnnotation); return new DefaultFieldMetadata(getId(), Modifier.PRIVATE, fieldName, fieldType, null, annotations); } private void addToBuilder(FieldMetadata field) { if (field != null && !hasField(field)) { builder.addField(field); // Check for an existing accessor in the governor or in the entity metadata if (!hasAccessor(field)) { builder.addMethod(getAccessor(field)); } // Check for an existing mutator in the governor or in the entity metadata if (!hasMutator(field)) { builder.addMethod(getMutator(field)); } } } private JavaSymbolName getUniqueFieldName(JavaSymbolName fieldName) { int index = -1; JavaSymbolName uniqueField = null; while (true) { // Compute the required field name index++; String uniqueFieldName = ""; for (int i = 0; i < index; i++) { uniqueFieldName = uniqueFieldName + "_"; } uniqueFieldName = uniqueFieldName + fieldName; uniqueField = new JavaSymbolName(uniqueFieldName); if (MemberFindingUtils.getField(governorTypeDetails, uniqueField) == null) { // Found a usable field name break; } } return uniqueField; } public boolean hasAccessor(FieldMetadata field) { String requiredAccessorName = getRequiredAccessorName(field); // Check governor for accessor method if (MemberFindingUtils.getMethod(governorTypeDetails, new JavaSymbolName(requiredAccessorName), new ArrayList<JavaType>()) != null) { return true; } // Check entity ITD for accessor method List<? extends MethodMetadata> itdMethods = entityMetadata.getItdTypeDetails().getDeclaredMethods(); for (MethodMetadata method : itdMethods) { if (method.getMethodName().equals(new JavaSymbolName(requiredAccessorName))) { return true; } } return false; } public boolean hasField(JavaSymbolName fieldName, JavaType javaType) { // Check governor for field if (MemberFindingUtils.getField(governorTypeDetails, fieldName) != null) { return true; } // Check entity ITD for field List<? extends FieldMetadata> itdFields = entityMetadata.getItdTypeDetails().getDeclaredFields(); for (FieldMetadata itdField : itdFields) { if (itdField.getFieldName().equals(fieldName)) { return true; } } return false; } public boolean hasField(FieldMetadata field) { return hasField(field.getFieldName(), field.getFieldType()); } public MethodMetadata getAccessor(FieldMetadata field) { Assert.notNull(field, "Field required"); // Compute the accessor method name String requiredAccessorName = getRequiredAccessorName(field); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine("return this." + field.getFieldName().getSymbolName() + ";"); return new DefaultMethodMetadata(getId(), Modifier.PUBLIC, new JavaSymbolName(requiredAccessorName), field.getFieldType(), new ArrayList<AnnotatedJavaType>(), new ArrayList<JavaSymbolName>(), new ArrayList<AnnotationMetadata>(), new ArrayList<JavaType>(), bodyBuilder.getOutput()); } private String getRequiredAccessorName(FieldMetadata field) { String methodName; if (field.getFieldType().equals(JavaType.BOOLEAN_PRIMITIVE)) { methodName = "is" + StringUtils.capitalize(field.getFieldName().getSymbolName()); } else { methodName = "get" + StringUtils.capitalize(field.getFieldName().getSymbolName()); } return methodName; } public boolean hasMutator(FieldMetadata field) { String requiredMutatorName = getRequiredMutatorName(field); // Check governor for mutator method if (MemberFindingUtils.getMethod(governorTypeDetails, new JavaSymbolName(requiredMutatorName), new ArrayList<JavaType>()) != null) { return true; } // Check entity ITD for mutator method List<? extends MethodMetadata> itdMethods = entityMetadata.getItdTypeDetails().getDeclaredMethods(); for (MethodMetadata method : itdMethods) { if (method.getMethodName().equals(new JavaSymbolName(requiredMutatorName))) { return true; } } return false; } public MethodMetadata getMutator(FieldMetadata field) { String requiredMutatorName = getRequiredMutatorName(field); List<JavaType> paramTypes = new ArrayList<JavaType>(); paramTypes.add(field.getFieldType()); List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(); paramNames.add(field.getFieldName()); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine("this." + field.getFieldName().getSymbolName() + " = " + field.getFieldName().getSymbolName() + ";"); return new DefaultMethodMetadata(getId(), Modifier.PUBLIC, new JavaSymbolName(requiredMutatorName), JavaType.VOID_PRIMITIVE, AnnotatedJavaType.convertFromJavaTypes(paramTypes), paramNames, new ArrayList<AnnotationMetadata>(), new ArrayList<JavaType>(), bodyBuilder.getOutput()); } private String getRequiredMutatorName(FieldMetadata field) { return "set" + StringUtils.capitalize(field.getFieldName().getSymbolName()); } public String getInflectorPlural(String term) { try { return Noun.pluralOf(term, Locale.ENGLISH); } catch (RuntimeException re) { // Inflector failed (see for example ROO-305), so don't pluralize it return term; } } private String getErrorMsg(String tableName) { return "Type for table '" + tableName + "' could not be found"; } public static final String getMetadataIdentiferType() { return PROVIDES_TYPE; } public static final String createIdentifier(JavaType javaType, Path path) { return PhysicalTypeIdentifierNamingUtils.createIdentifier(PROVIDES_TYPE_STRING, javaType, path); } public static final JavaType getJavaType(String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.getJavaType(PROVIDES_TYPE_STRING, metadataIdentificationString); } public static final Path getPath(String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.getPath(PROVIDES_TYPE_STRING, metadataIdentificationString); } public static boolean isValid(String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.isValid(PROVIDES_TYPE_STRING, metadataIdentificationString); } }
package org.akvo.flow.events; import java.io.IOException; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.codehaus.jackson.map.ObjectMapper; import org.waterforpeople.mapping.app.web.rest.security.user.GaeUser; import com.gallatinsystems.survey.domain.SurveyGroup; import com.gallatinsystems.survey.domain.SurveyGroup.PrivacyLevel; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.Text; public class EventUtils { private static Logger log = Logger.getLogger(EventUtils.class.getName()); private static final ObjectMapper objectMapper = new ObjectMapper(); public enum EventSourceType { USER, DEVICE, SENSOR, WEBFORM, API, UNKNOWN, SYSTEM }; public enum EntityType { SURVEY_GROUP, FORM, QUESTION_GROUP, QUESTION, DATA_POINT, FORM_INSTANCE, ANSWER, DEVICE_FILE }; // names of kinds in Google App Engine static public class Kind { public static final String SURVEY_GROUP = "SurveyGroup"; public static final String FORM = "Survey"; public static final String QUESTION_GROUP = "QuestionGroup"; public static final String QUESTION = "Question"; public static final String DATA_POINT = "SurveyedLocale"; public static final String FORM_INSTANCE = "SurveyInstance"; public static final String ANSWER = "QuestionAnswerStore"; public static final String DEVICE_FILE = "DeviceFiles"; } // How we name the actions static class Action { public static final String SURVEY_GROUP = "surveyGroup"; public static final String FORM = "form"; public static final String QUESTION_GROUP = "questionGroup"; public static final String QUESTION = "question"; public static final String DATA_POINT = "dataPoint"; public static final String FORM_INSTANCE = "formInstance"; public static final String ANSWER = "answer"; public static final String DEVICE_FILE = "deviceFile"; public static final String DELETED = "Deleted"; public static final String CREATED = "Created"; public static final String UPDATED = "Updated"; public static final String UNIFIED_LOG_NOTIFIED = "unifiedLogNotified"; } static class Key { public static final String ID = "id"; public static final String EMAIL = "email"; public static final String DISPLAY_TEXT = "displayText"; public static final String NAME = "name"; public static final String DESCRIPTION = "description"; public static final String TIMESTAMP = "timestamp"; public static final String SOURCE = "source"; public static final String TYPE = "type"; public static final String ORDER = "order"; public static final String LAT = "lat"; public static final String LON = "lon"; public static final String ORG_ID = "orgId"; public static final String SURVEY_ID = "surveyId"; public static final String QUESTION_TYPE = "questionType"; public static final String ANSWER_TYPE = "answerType"; public static final String PARENT_ID = "parentId"; public static final String FORM_ID = "formId"; public static final String QUESTION_GROUP_ID = "questionGroupId"; public static final String QUESTION_ID = "questionId"; public static final String FORM_INSTANCE_ID = "formInstanceId"; public static final String ANSWER_ID = "answerId"; public static final String DATA_POINT_ID = "dataPointId"; public static final String SUBMITTER_NAME = "submitterName"; public static final String COLLECTION_DATE = "collectionDate"; public static final String SURVEYAL_TIME = "surveyalTime"; public static final String PUBLIC = "public"; public static final String VALUE = "value"; public static final String IDENTIFIER = "identifier"; public static final String SURVEY_GROUP_TYPE = "surveyGroupType"; public static final String APP_ID = "orgId"; public static final String URL = "url"; public static final String ITERATION = "iteration"; } static class Prop { public static final String SURVEY_INSTANCE_ID = "surveyInstanceId"; public static final String TYPE = "type"; public static final String VALUE = "value"; public static final String VALUE_TEXT = "valueText"; public static final String SURVEY_ID = "surveyId"; public static final String SURVEYED_LOCALE_ID = "surveyedLocaleId"; public static final String COLLECTION_DATE = "collectionDate"; public static final String SURVEYAL_TIME = "surveyalTime"; public static final String IDENTIFIER = "identifier"; public static final String LATITUDE = "latitude"; public static final String LONGITUDE = "longitude"; public static final String DISPLAY_NAME = "displayName"; public static final String NAME = "name"; public static final String PARENT_ID = "parentId"; public static final String DESCRIPTION = "description"; public static final String PRIVACY_LEVEL = "privacyLevel"; public static final String DESC = "desc"; public static final String SURVEY_GROUP_ID = "surveyGroupId"; public static final String ORDER = "order"; public static final String TEXT = "text"; public static final String QUESTION_ID = "questionID"; public static final String QUESTION_IDENTIFIER = "questionId"; public static final String QUESTION_GROUP_ID = "questionGroupId"; public static final String PROJECT_TYPE = "projectType"; public static final String LAST_UPDATE_DATE_TIME = "lastUpdateDateTime"; public static final String CREATED_DATE_TIME = "createdDateTime"; public static final String ALIAS = "alias"; public static final String EVENT_NOTIFICATION = "eventNotification"; public static final String ENABLE_CHANGE_EVENTS = "enableChangeEvents"; public static final String ITERATION = "iteration"; } public static final String SURVEY_GROUP_TYPE_SURVEY = "SURVEY"; public static final String SURVEY_GROUP_TYPE_FOLDER = "FOLDER"; public static class EventTypes { public final EntityType type; public final String action; public EventTypes(EntityType type, String action) { this.type = type; this.action = action; } } public static EventTypes getEventAndActionType(String kindName) { switch (kindName) { case Kind.ANSWER: return new EventTypes(EntityType.ANSWER, Action.ANSWER); case Kind.FORM_INSTANCE: return new EventTypes(EntityType.FORM_INSTANCE, Action.FORM_INSTANCE); case Kind.DATA_POINT: return new EventTypes(EntityType.DATA_POINT, Action.DATA_POINT); case Kind.SURVEY_GROUP: return new EventTypes(EntityType.SURVEY_GROUP, Action.SURVEY_GROUP); case Kind.FORM: return new EventTypes(EntityType.FORM, Action.FORM); case Kind.QUESTION_GROUP: return new EventTypes(EntityType.QUESTION_GROUP, Action.QUESTION_GROUP); case Kind.QUESTION: return new EventTypes(EntityType.QUESTION, Action.QUESTION); case Kind.DEVICE_FILE: return new EventTypes(EntityType.DEVICE_FILE, Action.DEVICE_FILE); } return null; } private static Map<String, Object> addProperty(String key, Object val, Map<String, Object> data) { if (val != null) { data.put(key, val); } return data; } private static Map<String, Object> addProperty(String key, Object val, Object defaultVal, Map<String, Object> data) { if (val != null) { data.put(key, val); } else { data.put(key, defaultVal); } return data; } public static Map<String, Object> populateEntityProperties(EntityType type, Entity e, Map<String, Object> data) { switch (type) { case ANSWER: addProperty(Key.FORM_INSTANCE_ID, e.getProperty(Prop.SURVEY_INSTANCE_ID), data); addProperty(Key.ANSWER_TYPE, e.getProperty(Prop.TYPE), data); addProperty(Key.QUESTION_ID, Long.valueOf((String) e.getProperty(Prop.QUESTION_ID)), data); Object value = e.getProperty(Prop.VALUE); if (value == null) { Object text = e.getProperty(Prop.VALUE_TEXT); if (text != null && text instanceof Text) { value = ((Text) text).getValue(); } } addProperty(Key.VALUE, value, data); addProperty(Key.FORM_ID, e.getProperty(Prop.SURVEY_ID), data); addProperty(Key.ITERATION, e.getProperty(Prop.ITERATION), data); break; case FORM_INSTANCE: addProperty(Key.FORM_ID, e.getProperty(Prop.SURVEY_ID), data); addProperty(Key.DATA_POINT_ID, e.getProperty(Prop.SURVEYED_LOCALE_ID), data); addProperty(Key.COLLECTION_DATE, e.getProperty(Prop.COLLECTION_DATE), data); addProperty(Key.SURVEYAL_TIME, e.getProperty(Prop.SURVEYAL_TIME), data); break; case DATA_POINT: addProperty(Key.IDENTIFIER, e.getProperty(Prop.IDENTIFIER), data); addProperty(Key.LAT, e.getProperty(Prop.LATITUDE), data); addProperty(Key.LON, e.getProperty(Prop.LONGITUDE), data); addProperty(Key.NAME, e.getProperty(Prop.DISPLAY_NAME), data); addProperty(Key.SURVEY_ID, e.getProperty(Prop.SURVEY_GROUP_ID), data); break; case SURVEY_GROUP: addProperty(Key.NAME, e.getProperty(Prop.NAME), "<name missing>", data); addProperty(Key.PARENT_ID, e.getProperty(Prop.PARENT_ID), data); if (e.getProperty(Prop.PROJECT_TYPE).toString() .equals(SurveyGroup.ProjectType.PROJECT.toString())) { data.put(Key.SURVEY_GROUP_TYPE, SURVEY_GROUP_TYPE_SURVEY); } else if (e.getProperty(Prop.PROJECT_TYPE).toString() .equals(SurveyGroup.ProjectType.PROJECT_FOLDER.toString())) { data.put(Key.SURVEY_GROUP_TYPE, SURVEY_GROUP_TYPE_FOLDER); } addProperty(Key.DESCRIPTION, e.getProperty(Prop.DESCRIPTION), data); addProperty(Key.PUBLIC, String.valueOf(e.getProperty(Prop.PRIVACY_LEVEL)) .equals(PrivacyLevel.PUBLIC.toString()), data); break; case FORM: addProperty(Key.NAME, e.getProperty(Prop.NAME), data); addProperty(Key.DESCRIPTION, e.getProperty(Prop.DESC), data); addProperty(Key.SURVEY_ID, e.getProperty(Prop.SURVEY_GROUP_ID), data); break; case QUESTION_GROUP: addProperty(Key.NAME, e.getProperty(Prop.NAME), "<name missing>", data); addProperty(Key.ORDER, e.getProperty(Prop.ORDER), data); addProperty(Key.FORM_ID, e.getProperty(Prop.SURVEY_ID), data); break; case QUESTION: addProperty(Key.DISPLAY_TEXT, e.getProperty(Prop.TEXT), data); addProperty(Key.IDENTIFIER, e.getProperty(Prop.QUESTION_IDENTIFIER), data); addProperty(Key.QUESTION_GROUP_ID, e.getProperty(Prop.QUESTION_GROUP_ID), data); addProperty(Key.FORM_ID, e.getProperty(Prop.SURVEY_ID), data); addProperty(Key.QUESTION_TYPE, e.getProperty(Prop.TYPE), data); break; case DEVICE_FILE: // FIXME move those keys to the proper place addProperty("uri", e.getProperty("URI"), data); addProperty("checksum", e.getProperty("checksum"), data); addProperty("phoneNumber", e.getProperty("phoneNumber"), data); addProperty("imei", e.getProperty("imei"), data); break; } return data; } public static Map<String, Object> newEvent(String orgId, String eventType, Map<String, Object> entity, Map<String, Object> context) throws AssertionError { assert orgId != null : "orgId is required"; assert eventType != null : "eventType is required"; assert entity != null : "entity is required"; assert context != null : "context is required"; Map<String, Object> result = new HashMap<String, Object>(); result.put("orgId", orgId); result.put("eventType", eventType); result.put("entity", entity); result.put("context", context); return result; } public static Map<String, Object> newSource(Object principal) { Map<String, Object> source = new HashMap<String, Object>(); if (principal instanceof String) { // Tasks related events get an "anonymousUser" as principal source.put(Key.TYPE, EventSourceType.SYSTEM); } else if (principal instanceof GaeUser) { GaeUser usr = (GaeUser) principal; source.put(Key.TYPE, EventSourceType.USER); source.put(Key.EMAIL, usr.getEmail()); source.put(Key.ID, usr.getUserId()); } else { log.log(Level.WARNING, "Unable to identify source from authentication principal: " + principal.toString()); } return source; } public static Map<String, Object> newContext(Date timestamp, Map<String, Object> source) { Map<String, Object> context = new HashMap<String, Object>(); context.put(Key.TIMESTAMP, timestamp); context.put(Key.SOURCE, source); return context; } public static Map<String, Object> newEntity(EntityType type, Long id) { Map<String, Object> entity = new HashMap<String, Object>(); entity.put(Key.TYPE, type); entity.put(Key.ID, id); return entity; } public static void sendEvents(String urlString, List<Map<String, Object>> events) throws IOException { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url .openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); OutputStreamWriter writer = new OutputStreamWriter( connection.getOutputStream()); objectMapper.writeValue(writer, events); System.out.println(" " + connection.getResponseCode()); writer.close(); connection.disconnect(); } }
package com.apwglobal.nice.rest; import com.google.gson.annotations.SerializedName; public class RestApiSession { @SerializedName("access_token") private String accessToken; @SerializedName("refresh_token") private String refreshRoken; public String getAccessToken() { return accessToken; } public String getRefreshRoken() { return refreshRoken; } @Override public String toString() { return "RestApiSession{" + "accessToken='" + accessToken + '\'' + ", refreshRoken='" + refreshRoken + '\'' + '}'; } }
package com.smartdevicelink.proxy; import android.annotation.TargetApi; import android.app.Service; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.os.SystemClock; import android.support.annotation.NonNull; import android.telephony.TelephonyManager; import android.util.DisplayMetrics; import android.util.Log; import android.util.SparseArray; import android.view.Display; import android.view.InputDevice; import android.view.MotionEvent; import android.view.Surface; import com.smartdevicelink.BuildConfig; import com.smartdevicelink.Dispatcher.IDispatchingStrategy; import com.smartdevicelink.Dispatcher.ProxyMessageDispatcher; import com.smartdevicelink.SdlConnection.ISdlConnectionListener; import com.smartdevicelink.SdlConnection.SdlConnection; import com.smartdevicelink.SdlConnection.SdlSession; import com.smartdevicelink.SdlConnection.SdlSession2; import com.smartdevicelink.encoder.VirtualDisplayEncoder; import com.smartdevicelink.exception.SdlException; import com.smartdevicelink.exception.SdlExceptionCause; import com.smartdevicelink.haptic.HapticInterfaceManager; import com.smartdevicelink.managers.lifecycle.RpcConverter; import com.smartdevicelink.marshal.JsonRPCMarshaller; import com.smartdevicelink.protocol.ProtocolMessage; import com.smartdevicelink.protocol.enums.FunctionID; import com.smartdevicelink.protocol.enums.MessageType; import com.smartdevicelink.protocol.enums.SessionType; import com.smartdevicelink.protocol.heartbeat.HeartbeatMonitor; import com.smartdevicelink.proxy.LockScreenManager.OnLockScreenIconDownloadedListener; import com.smartdevicelink.proxy.callbacks.InternalProxyMessage; import com.smartdevicelink.proxy.callbacks.OnError; import com.smartdevicelink.proxy.callbacks.OnProxyClosed; import com.smartdevicelink.proxy.callbacks.OnServiceEnded; import com.smartdevicelink.proxy.callbacks.OnServiceNACKed; import com.smartdevicelink.proxy.interfaces.IAudioStreamListener; import com.smartdevicelink.proxy.interfaces.IProxyListenerBase; import com.smartdevicelink.proxy.interfaces.IPutFileResponseListener; import com.smartdevicelink.proxy.interfaces.ISdl; import com.smartdevicelink.proxy.interfaces.ISdlServiceListener; import com.smartdevicelink.proxy.interfaces.IVideoStreamListener; import com.smartdevicelink.proxy.interfaces.OnSystemCapabilityListener; import com.smartdevicelink.proxy.rpc.*; import com.smartdevicelink.proxy.rpc.enums.AppHMIType; import com.smartdevicelink.proxy.rpc.enums.AudioStreamingState; import com.smartdevicelink.proxy.rpc.enums.AudioType; import com.smartdevicelink.proxy.rpc.enums.BitsPerSample; import com.smartdevicelink.proxy.rpc.enums.ButtonName; import com.smartdevicelink.proxy.rpc.enums.DriverDistractionState; import com.smartdevicelink.proxy.rpc.enums.FileType; import com.smartdevicelink.proxy.rpc.enums.GlobalProperty; import com.smartdevicelink.proxy.rpc.enums.HMILevel; import com.smartdevicelink.proxy.rpc.enums.ImageType; import com.smartdevicelink.proxy.rpc.enums.InteractionMode; import com.smartdevicelink.proxy.rpc.enums.Language; import com.smartdevicelink.proxy.rpc.enums.PrerecordedSpeech; import com.smartdevicelink.proxy.rpc.enums.RequestType; import com.smartdevicelink.proxy.rpc.enums.Result; import com.smartdevicelink.proxy.rpc.enums.SamplingRate; import com.smartdevicelink.proxy.rpc.enums.SdlConnectionState; import com.smartdevicelink.proxy.rpc.enums.SdlDisconnectedReason; import com.smartdevicelink.proxy.rpc.enums.SdlInterfaceAvailability; import com.smartdevicelink.proxy.rpc.enums.SystemCapabilityType; import com.smartdevicelink.proxy.rpc.enums.TextAlignment; import com.smartdevicelink.proxy.rpc.enums.TouchType; import com.smartdevicelink.proxy.rpc.enums.UpdateMode; import com.smartdevicelink.proxy.rpc.listeners.OnMultipleRequestListener; import com.smartdevicelink.proxy.rpc.listeners.OnPutFileUpdateListener; import com.smartdevicelink.proxy.rpc.listeners.OnRPCListener; import com.smartdevicelink.proxy.rpc.listeners.OnRPCNotificationListener; import com.smartdevicelink.proxy.rpc.listeners.OnRPCRequestListener; import com.smartdevicelink.proxy.rpc.listeners.OnRPCResponseListener; import com.smartdevicelink.security.SdlSecurityBase; import com.smartdevicelink.streaming.StreamRPCPacketizer; import com.smartdevicelink.streaming.audio.AudioStreamingCodec; import com.smartdevicelink.streaming.audio.AudioStreamingParams; import com.smartdevicelink.streaming.video.SdlRemoteDisplay; import com.smartdevicelink.streaming.video.VideoStreamingParameters; import com.smartdevicelink.trace.SdlTrace; import com.smartdevicelink.trace.TraceDeviceInfo; import com.smartdevicelink.trace.enums.InterfaceActivityDirection; import com.smartdevicelink.transport.BaseTransportConfig; import com.smartdevicelink.transport.MultiplexTransportConfig; import com.smartdevicelink.transport.SiphonServer; import com.smartdevicelink.transport.USBTransportConfig; import com.smartdevicelink.transport.enums.TransportType; import com.smartdevicelink.util.CorrelationIdGenerator; import com.smartdevicelink.util.DebugTool; import com.smartdevicelink.util.FileUtls; import com.smartdevicelink.util.Version; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Hashtable; import java.util.List; import java.util.Vector; import java.util.concurrent.Callable; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; import java.util.concurrent.ScheduledExecutorService; @SuppressWarnings({"WeakerAccess", "Convert2Diamond"}) public abstract class SdlProxyBase<proxyListenerType extends IProxyListenerBase> { // Used for calls to Android Log class. public static final String TAG = "SdlProxy"; private static final String SDL_LIB_TRACE_KEY = "42baba60-eb57-11df-98cf-0800200c9a66"; private static final int PROX_PROT_VER_ONE = 1; private static final int RESPONSE_WAIT_TIME = 2000; public static final com.smartdevicelink.util.Version MAX_SUPPORTED_RPC_VERSION = new com.smartdevicelink.util.Version("6.0.0"); private SdlSession sdlSession = null; private proxyListenerType _proxyListener = null; protected Service _appService = null; private Context _appContext; private String sPoliciesURL = ""; //for testing only // Protected Correlation IDs private final int REGISTER_APP_INTERFACE_CORRELATION_ID = 65529, UNREGISTER_APP_INTERFACE_CORRELATION_ID = 65530, POLICIES_CORRELATION_ID = 65535; // Sdl Synchronization Objects private static final Object CONNECTION_REFERENCE_LOCK = new Object(), INCOMING_MESSAGE_QUEUE_THREAD_LOCK = new Object(), OUTGOING_MESSAGE_QUEUE_THREAD_LOCK = new Object(), INTERNAL_MESSAGE_QUEUE_THREAD_LOCK = new Object(), ON_UPDATE_LISTENER_LOCK = new Object(), RPC_LISTENER_LOCK = new Object(), ON_NOTIFICATION_LISTENER_LOCK = new Object(); private final Object APP_INTERFACE_REGISTERED_LOCK = new Object(); private int iFileCount = 0; private boolean navServiceStartResponseReceived = false; private boolean navServiceStartResponse = false; private List<String> navServiceStartRejectedParams = null; private boolean pcmServiceStartResponseReceived = false; private boolean pcmServiceStartResponse = false; @SuppressWarnings("FieldCanBeLocal") private List<String> pcmServiceStartRejectedParams = null; private boolean navServiceEndResponseReceived = false; private boolean navServiceEndResponse = false; private boolean pcmServiceEndResponseReceived = false; private boolean pcmServiceEndResponse = false; private boolean rpcProtectedResponseReceived = false; private boolean rpcProtectedStartResponse = false; // Device Info for logging private TraceDeviceInfo _traceDeviceInterrogator = null; // Declare Queuing Threads private ProxyMessageDispatcher<ProtocolMessage> _incomingProxyMessageDispatcher; private ProxyMessageDispatcher<ProtocolMessage> _outgoingProxyMessageDispatcher; private ProxyMessageDispatcher<InternalProxyMessage> _internalProxyMessageDispatcher; // Flag indicating if callbacks should be called from UIThread private Boolean _callbackToUIThread = false; // UI Handler private Handler _mainUIHandler = null; final int HEARTBEAT_CORRELATION_ID = 65531; // SdlProxy Advanced Lifecycle Management protected Boolean _advancedLifecycleManagementEnabled = false; // Parameters passed to the constructor from the app to register an app interface private String _applicationName = null; private final long instanceDateTime = System.currentTimeMillis(); private String sConnectionDetails = "N/A"; private Vector<TTSChunk> _ttsName = null; private String _ngnMediaScreenAppName = null; private Boolean _isMediaApp = null; private Language _sdlLanguageDesired = null; private Language _hmiDisplayLanguageDesired = null; private Vector<AppHMIType> _appType = null; private String _appID = null; private TemplateColorScheme _dayColorScheme = null; private TemplateColorScheme _nightColorScheme = null; @SuppressWarnings({"FieldCanBeLocal", "unused"}) //Need to understand what this is used for private String _autoActivateIdDesired = null; private String _lastHashID = null; private SdlMsgVersion _sdlMsgVersionRequest = null; private Vector<String> _vrSynonyms = null; private boolean _bAppResumeEnabled = false; private OnSystemRequest lockScreenIconRequest = null; private TelephonyManager telephonyManager = null; private DeviceInfo deviceInfo = null; /** * Contains current configuration for the transport that was selected during * construction of this object */ private BaseTransportConfig _transportConfig = null; // Proxy State Variables protected Boolean _appInterfaceRegisterd = false; protected Boolean _preRegisterd = false; @SuppressWarnings({"unused", "FieldCanBeLocal"}) private Boolean _haveReceivedFirstNonNoneHMILevel = false; protected Boolean _haveReceivedFirstFocusLevel = false; protected Boolean _haveReceivedFirstFocusLevelFull = false; protected Boolean _proxyDisposed = false; protected SdlConnectionState _sdlConnectionState = null; protected SdlInterfaceAvailability _sdlIntefaceAvailablity = null; protected HMILevel _hmiLevel = null; protected OnHMIStatus lastHmiStatus; protected AudioStreamingState _audioStreamingState = null; // Variables set by RegisterAppInterfaceResponse protected SdlMsgVersion _sdlMsgVersion = null; protected String _autoActivateIdReturned = null; protected Language _sdlLanguage = null; protected Language _hmiDisplayLanguage = null; protected List<PrerecordedSpeech> _prerecordedSpeech = null; protected VehicleType _vehicleType = null; protected String _systemSoftwareVersion = null; protected List<Integer> _diagModes = null; protected Boolean firstTimeFull = true; protected String _proxyVersionInfo = null; protected Boolean _bResumeSuccess = false; protected List<Class<? extends SdlSecurityBase>> _secList = null; protected SystemCapabilityManager _systemCapabilityManager; protected Boolean _iconResumed = false; protected RegisterAppInterfaceResponse raiResponse = null; private final CopyOnWriteArrayList<IPutFileResponseListener> _putFileListenerList = new CopyOnWriteArrayList<IPutFileResponseListener>(); protected com.smartdevicelink.util.Version protocolVersion = new com.smartdevicelink.util.Version(1,0,0); protected com.smartdevicelink.util.Version rpcSpecVersion; protected SparseArray<OnRPCResponseListener> rpcResponseListeners = null; protected SparseArray<CopyOnWriteArrayList<OnRPCNotificationListener>> rpcNotificationListeners = null; protected SparseArray<CopyOnWriteArrayList<OnRPCRequestListener>> rpcRequestListeners = null; protected SparseArray<CopyOnWriteArrayList<OnRPCListener>> rpcListeners = null; protected VideoStreamingManager manager; //Will move to SdlSession once the class becomes public protected String authToken; private Version minimumProtocolVersion; private Version minimumRPCVersion; // Interface broker private SdlInterfaceBroker _interfaceBroker = null; //We create an easily passable anonymous class of the interface so that we don't expose the internal interface to developers private ISdl _internalInterface = new ISdl() { @Override public void start() { try{ initializeProxy(); }catch (SdlException e){ e.printStackTrace(); } } @Override public void stop() { try{ dispose(); }catch (SdlException e){ e.printStackTrace(); } } @Override public boolean isConnected() { return getIsConnected(); } @Override public void addServiceListener(SessionType serviceType, ISdlServiceListener sdlServiceListener) { SdlProxyBase.this.addServiceListener(serviceType,sdlServiceListener); } @Override public void removeServiceListener(SessionType serviceType, ISdlServiceListener sdlServiceListener) { SdlProxyBase.this.removeServiceListener(serviceType,sdlServiceListener); } @Override public void startVideoService(VideoStreamingParameters parameters, boolean encrypted) { if(isConnected()){ sdlSession.setDesiredVideoParams(parameters); sdlSession.startService(SessionType.NAV,sdlSession.getSessionId(),encrypted); } } @Override public void stopVideoService() { if(isConnected()){ sdlSession.endService(SessionType.NAV,sdlSession.getSessionId()); } } @Override public void stopAudioService() { if(isConnected()){ sdlSession.endService(SessionType.PCM,sdlSession.getSessionId()); } } @Override public void sendRPCRequest(RPCRequest message){ try { SdlProxyBase.this.sendRPCRequest(message); } catch (SdlException e) { e.printStackTrace(); } } @Override public void sendRPC(RPCMessage message) { try { SdlProxyBase.this.sendRPC(message); } catch (SdlException e) { e.printStackTrace(); } } @Override public void sendRequests(List<? extends RPCRequest> rpcs, OnMultipleRequestListener listener) { try { SdlProxyBase.this.sendRequests(rpcs, listener); } catch (SdlException e) { e.printStackTrace(); } } @Override public void sendSequentialRPCs(List<? extends RPCMessage> rpcs, OnMultipleRequestListener listener) { try{ SdlProxyBase.this.sendSequentialRequests(rpcs,listener); }catch (SdlException e ){ DebugTool.logError("Issue sending sequential RPCs ", e); } } @Override public void addOnRPCNotificationListener(FunctionID notificationId, OnRPCNotificationListener listener) { SdlProxyBase.this.addOnRPCNotificationListener(notificationId,listener); } @Override public boolean removeOnRPCNotificationListener(FunctionID notificationId, OnRPCNotificationListener listener) { return SdlProxyBase.this.removeOnRPCNotificationListener(notificationId,listener); } @Override public void addOnRPCRequestListener(FunctionID functionID, OnRPCRequestListener listener) { SdlProxyBase.this.addOnRPCRequestListener(functionID,listener); } @Override public boolean removeOnRPCRequestListener(FunctionID functionID, OnRPCRequestListener listener) { return SdlProxyBase.this.removeOnRPCRequestListener(functionID,listener); } @Override public void addOnRPCListener(FunctionID responseId, OnRPCListener listener) { SdlProxyBase.this.addOnRPCListener(responseId, listener); } @Override public boolean removeOnRPCListener(FunctionID responseId, OnRPCListener listener) { return SdlProxyBase.this.removeOnRPCListener(responseId, listener); } @Override public Object getCapability(SystemCapabilityType systemCapabilityType){ return SdlProxyBase.this.getCapability(systemCapabilityType); } @Override public void getCapability(SystemCapabilityType systemCapabilityType, OnSystemCapabilityListener scListener) { SdlProxyBase.this.getCapability(systemCapabilityType, scListener); } @Override public SdlMsgVersion getSdlMsgVersion(){ try { return SdlProxyBase.this.getSdlMsgVersion(); } catch (SdlException e) { e.printStackTrace(); } return null; } @Override public com.smartdevicelink.util.Version getProtocolVersion() { return SdlProxyBase.this.protocolVersion; } @Override public boolean isCapabilitySupported(SystemCapabilityType systemCapabilityType){ return SdlProxyBase.this.isCapabilitySupported(systemCapabilityType); } @Override public void addOnSystemCapabilityListener(SystemCapabilityType systemCapabilityType, OnSystemCapabilityListener listener) { SdlProxyBase.this.removeOnSystemCapabilityListener(systemCapabilityType, listener); } @Override public boolean removeOnSystemCapabilityListener(SystemCapabilityType systemCapabilityType, OnSystemCapabilityListener listener) { return SdlProxyBase.this.removeOnSystemCapabilityListener(systemCapabilityType, listener); } @Override public boolean isTransportForServiceAvailable(SessionType serviceType) { return SdlProxyBase.this.sdlSession != null && SdlProxyBase.this.sdlSession.isTransportForServiceAvailable(serviceType); } @Override public void startAudioService(boolean isEncrypted, AudioStreamingCodec codec, AudioStreamingParams params) { if(getIsConnected()){ SdlProxyBase.this.startAudioStream(isEncrypted, codec, params); } } @Override public void startAudioService(boolean encrypted) { if(isConnected()){ sdlSession.startService(SessionType.PCM,sdlSession.getSessionId(),encrypted); } } @Override public IVideoStreamListener startVideoStream(boolean isEncrypted, VideoStreamingParameters parameters){ return SdlProxyBase.this.startVideoStream(isEncrypted, parameters); } @Override public IAudioStreamListener startAudioStream(boolean isEncrypted, AudioStreamingCodec codec, AudioStreamingParams params) { return SdlProxyBase.this.startAudioStream(isEncrypted, codec, params); } }; private void notifyPutFileStreamError(Exception e, String info) { for (IPutFileResponseListener _putFileListener : _putFileListenerList) { _putFileListener.onPutFileStreamError(e, info); } } private void notifyPutFileStreamResponse(PutFileResponse msg) { for (IPutFileResponseListener _putFileListener : _putFileListenerList) { _putFileListener.onPutFileResponse(msg); } } public void addPutFileResponseListener(IPutFileResponseListener _putFileListener) { _putFileListenerList.addIfAbsent(_putFileListener); } public void remPutFileResponseListener(IPutFileResponseListener _putFileListener) { _putFileListenerList.remove(_putFileListener); } // Private Class to Interface with SdlConnection private class SdlInterfaceBroker implements ISdlConnectionListener { @Override public void onTransportDisconnected(String info) { // proxyOnTransportDisconnect is called to alert the proxy that a requested // disconnect has completed notifyPutFileStreamError(null, info); //if (!_advancedLifecycleManagementEnabled) { // If original model, notify app the proxy is closed so it will delete and reinstanciate Log.d(TAG, "notifying proxy of closed"); notifyProxyClosed(info, new SdlException("Transport disconnected.", SdlExceptionCause.SDL_UNAVAILABLE), SdlDisconnectedReason.TRANSPORT_DISCONNECT); //}// else If ALM, nothing is required to be done here } @Override public void onTransportDisconnected(String info, boolean altTransportAvailable, BaseTransportConfig transportConfig) { notifyPutFileStreamError(null, info); if( altTransportAvailable){ SdlProxyBase.this._transportConfig = transportConfig; Log.d(TAG, "notifying RPC session ended, but potential primary transport available"); cycleProxy(SdlDisconnectedReason.PRIMARY_TRANSPORT_CYCLE_REQUEST); }else{ notifyProxyClosed(info, new SdlException("Transport disconnected.", SdlExceptionCause.SDL_UNAVAILABLE), SdlDisconnectedReason.TRANSPORT_DISCONNECT); } } @Override public void onTransportError(String info, Exception e) { DebugTool.logError("Transport failure: " + info, e); notifyPutFileStreamError(e, info); if (_advancedLifecycleManagementEnabled) { // Cycle the proxy if(SdlConnection.isLegacyModeEnabled()){ //FIXME cycleProxy(SdlDisconnectedReason.LEGACY_BLUETOOTH_MODE_ENABLED); }else{ cycleProxy(SdlDisconnectedReason.TRANSPORT_ERROR); } } else { notifyProxyClosed(info, e, SdlDisconnectedReason.TRANSPORT_ERROR); } } @Override public void onProtocolMessageReceived(ProtocolMessage msg) { // AudioPathThrough is coming WITH BulkData but WITHOUT JSON Data // Policy Snapshot is coming WITH BulkData and WITH JSON Data if ((msg.getData() != null && msg.getData().length > 0) || (msg.getBulkData() != null && msg.getBulkData().length > 0)) { queueIncomingMessage(msg); } } @Override public void onProtocolSessionStarted(SessionType sessionType, byte sessionID, byte version, String correlationID, int hashID, boolean isEncrypted) { Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "onProtocolSessionStarted"); updateBroadcastIntent(sendIntent, "COMMENT1", "SessionID: " + sessionID); updateBroadcastIntent(sendIntent, "COMMENT2", " ServiceType: " + sessionType.getName()); updateBroadcastIntent(sendIntent, "COMMENT3", " Encrypted: " + isEncrypted); sendBroadcastIntent(sendIntent); if(sdlSession!= null){ setProtocolVersion(sdlSession.getProtocolVersion()); }else{ setProtocolVersion(new com.smartdevicelink.util.Version(version,0,0)); } if (minimumProtocolVersion != null && minimumProtocolVersion.isNewerThan(getProtocolVersion()) == 1){ Log.w(TAG, String.format("Disconnecting from head unit, the configured minimum protocol version %s is greater than the supported protocol version %s", minimumProtocolVersion, getProtocolVersion())); endService(sessionType); try { cleanProxy(SdlDisconnectedReason.MINIMUM_PROTOCOL_VERSION_HIGHER_THAN_SUPPORTED); } catch (SdlException e) { e.printStackTrace(); } return; } if (sessionType.eq(SessionType.RPC)) { if (!isEncrypted) { if ( (_transportConfig.getHeartBeatTimeout() != Integer.MAX_VALUE) && (version > 2)) { HeartbeatMonitor outgoingHeartbeatMonitor = new HeartbeatMonitor(); outgoingHeartbeatMonitor.setInterval(_transportConfig.getHeartBeatTimeout()); sdlSession.setOutgoingHeartbeatMonitor(outgoingHeartbeatMonitor); HeartbeatMonitor incomingHeartbeatMonitor = new HeartbeatMonitor(); incomingHeartbeatMonitor.setInterval(_transportConfig.getHeartBeatTimeout()); sdlSession.setIncomingHeartbeatMonitor(incomingHeartbeatMonitor); } startRPCProtocolSession(); } else { RPCProtectedServiceStarted(); } } else if (sessionType.eq(SessionType.NAV)) { NavServiceStarted(); } else if (sessionType.eq(SessionType.PCM)) { AudioServiceStarted(); } else if (sessionType.eq(SessionType.RPC)){ cycleProxy(SdlDisconnectedReason.RPC_SESSION_ENDED); } else if (protocolVersion!= null && protocolVersion.getMajor() > 1) { //If version is 2 or above then don't need to specify a Session Type startRPCProtocolSession(); } //else{} Handle other protocol session types here } @Override public void onProtocolSessionStartedNACKed(SessionType sessionType, byte sessionID, byte version, String correlationID, List<String> rejectedParams) { OnServiceNACKed message = new OnServiceNACKed(sessionType); queueInternalMessage(message); if (sessionType.eq(SessionType.NAV)) { Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "onProtocolSessionStartedNACKed"); updateBroadcastIntent(sendIntent, "COMMENT1", "SessionID: " + sessionID); updateBroadcastIntent(sendIntent, "COMMENT2", " NACK ServiceType: " + sessionType.getName()); sendBroadcastIntent(sendIntent); NavServiceStartedNACK(rejectedParams); } else if (sessionType.eq(SessionType.PCM)) { Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "onProtocolSessionStartedNACKed"); updateBroadcastIntent(sendIntent, "COMMENT1", "SessionID: " + sessionID); updateBroadcastIntent(sendIntent, "COMMENT2", " NACK ServiceType: " + sessionType.getName()); sendBroadcastIntent(sendIntent); AudioServiceStartedNACK(rejectedParams); } } @Override public void onProtocolSessionEnded(SessionType sessionType, byte sessionID, String correlationID) { OnServiceEnded message = new OnServiceEnded(sessionType); queueInternalMessage(message); if (sessionType.eq(SessionType.NAV)) { Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "onProtocolSessionEnded"); updateBroadcastIntent(sendIntent, "COMMENT1", "SessionID: " + sessionID); updateBroadcastIntent(sendIntent, "COMMENT2", " End ServiceType: " + sessionType.getName()); sendBroadcastIntent(sendIntent); NavServiceEnded(); } else if (sessionType.eq(SessionType.PCM)) { Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "onProtocolSessionEnded"); updateBroadcastIntent(sendIntent, "COMMENT1", "SessionID: " + sessionID); updateBroadcastIntent(sendIntent, "COMMENT2", " End ServiceType: " + sessionType.getName()); sendBroadcastIntent(sendIntent); AudioServiceEnded(); } } @Override public void onProtocolError(String info, Exception e) { notifyPutFileStreamError(e, info); passErrorToProxyListener(info, e); } @Override public void onHeartbeatTimedOut(byte sessionID) { final String msg = "Heartbeat timeout"; DebugTool.logInfo(msg); Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "onHeartbeatTimedOut"); updateBroadcastIntent(sendIntent, "COMMENT1", "Heartbeat timeout for SessionID: " + sessionID); sendBroadcastIntent(sendIntent); notifyProxyClosed(msg, new SdlException(msg, SdlExceptionCause.HEARTBEAT_PAST_DUE), SdlDisconnectedReason.HB_TIMEOUT); } @Override public void onProtocolSessionEndedNACKed(SessionType sessionType, byte sessionID, String correlationID) { if (sessionType.eq(SessionType.NAV)) { Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "onProtocolSessionEndedNACKed"); updateBroadcastIntent(sendIntent, "COMMENT1", "SessionID: " + sessionID); updateBroadcastIntent(sendIntent, "COMMENT2", " End NACK ServiceType: " + sessionType.getName()); sendBroadcastIntent(sendIntent); NavServiceEndedNACK(); } else if (sessionType.eq(SessionType.PCM)) { Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "onProtocolSessionEndedNACKed"); updateBroadcastIntent(sendIntent, "COMMENT1", "SessionID: " + sessionID); updateBroadcastIntent(sendIntent, "COMMENT2", " End NACK ServiceType: " + sessionType.getName()); sendBroadcastIntent(sendIntent); AudioServiceEndedNACK(); } } public void onProtocolServiceDataACK(SessionType sessionType, final int dataSize, byte sessionID) { if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onServiceDataACK(dataSize); } }); } else { _proxyListener.onServiceDataACK(dataSize); } } @Override public void onAuthTokenReceived(String authToken, byte sessionID) { SdlProxyBase.this.authToken = authToken; } } protected SdlProxyBase(){} /** * Used by the SdlManager * * @param listener Type of listener for this proxy base. * @param context Application context. * @param appName Client application name. * @param shortAppName Client short application name. * @param isMediaApp Flag that indicates that client application if media application or not. * @param languageDesired Desired language. * @param hmiDisplayLanguageDesired Desired language for HMI. * @param appType Type of application. * @param appID Application identifier. * @param dayColorScheme TemplateColorScheme for the day * @param nightColorScheme TemplateColorScheme for the night * @param transportConfig Configuration of transport to be used by underlying connection. * @param vrSynonyms List of synonyms. * @param ttsName TTS name. * @throws SdlException */ public SdlProxyBase(proxyListenerType listener, Context context, String appName,String shortAppName, Boolean isMediaApp, Language languageDesired, Language hmiDisplayLanguageDesired, Vector<AppHMIType> appType, String appID, BaseTransportConfig transportConfig, Vector<String> vrSynonyms, Vector<TTSChunk> ttsName, TemplateColorScheme dayColorScheme, TemplateColorScheme nightColorScheme) throws SdlException { performBaseCommon(listener, null, true, appName, ttsName, shortAppName, vrSynonyms, isMediaApp, null, languageDesired, hmiDisplayLanguageDesired, appType, appID, null, dayColorScheme,nightColorScheme, false, false, null, null, transportConfig); _appContext = context; } /** * Constructor. * * @param listener Type of listener for this proxy base. * @param sdlProxyConfigurationResources Configuration resources for this proxy. * @param enableAdvancedLifecycleManagement Flag that ALM should be enabled or not. * @param appName Client application name. * @param ttsName TTS name. * @param ngnMediaScreenAppName Media Screen Application name. * @param vrSynonyms List of synonyms. * @param isMediaApp Flag that indicates that client application if media application or not. * @param sdlMsgVersion Version of Sdl Message. * @param languageDesired Desired language. * @param hmiDisplayLanguageDesired Desired language for HMI. * @param appType Type of application. * @param appID Application identifier. * @param autoActivateID Auto activation identifier. * @param callbackToUIThread Flag that indicates that this proxy should send callback to UI thread or not. * @param transportConfig Configuration of transport to be used by underlying connection. * @throws SdlException if there is an unrecoverable error class might throw an exception. */ protected SdlProxyBase(proxyListenerType listener, SdlProxyConfigurationResources sdlProxyConfigurationResources, boolean enableAdvancedLifecycleManagement, String appName, Vector<TTSChunk> ttsName, String ngnMediaScreenAppName, Vector<String> vrSynonyms, Boolean isMediaApp, SdlMsgVersion sdlMsgVersion, Language languageDesired, Language hmiDisplayLanguageDesired, Vector<AppHMIType> appType, String appID, String autoActivateID, boolean callbackToUIThread, BaseTransportConfig transportConfig) throws SdlException { performBaseCommon(listener, sdlProxyConfigurationResources, enableAdvancedLifecycleManagement, appName, ttsName, ngnMediaScreenAppName, vrSynonyms, isMediaApp, sdlMsgVersion, languageDesired, hmiDisplayLanguageDesired, appType, appID, autoActivateID, null, null, callbackToUIThread, null, null, null, transportConfig); } @SuppressWarnings("ConstantConditions") private void performBaseCommon(proxyListenerType listener, SdlProxyConfigurationResources sdlProxyConfigurationResources, boolean enableAdvancedLifecycleManagement, String appName, Vector<TTSChunk> ttsName, String ngnMediaScreenAppName, Vector<String> vrSynonyms, Boolean isMediaApp, SdlMsgVersion sdlMsgVersion, Language languageDesired, Language hmiDisplayLanguageDesired, Vector<AppHMIType> appType, String appID, String autoActivateID, TemplateColorScheme dayColorScheme, TemplateColorScheme nightColorScheme, boolean callbackToUIThread, Boolean preRegister, String sHashID, Boolean bAppResumeEnab, BaseTransportConfig transportConfig) throws SdlException { Log.i(TAG, "SDL_LIB_VERSION: " + BuildConfig.VERSION_NAME); setProtocolVersion(new Version(PROX_PROT_VER_ONE,0,0)); if (preRegister != null && preRegister) { _appInterfaceRegisterd = preRegister; _preRegisterd = preRegister; } if (bAppResumeEnab != null && bAppResumeEnab) { _bAppResumeEnabled = true; _lastHashID = sHashID; } _interfaceBroker = new SdlInterfaceBroker(); _callbackToUIThread = callbackToUIThread; if (_callbackToUIThread) { _mainUIHandler = new Handler(Looper.getMainLooper()); } // Set variables for Advanced Lifecycle Management _advancedLifecycleManagementEnabled = enableAdvancedLifecycleManagement; _applicationName = appName; _ttsName = ttsName; _ngnMediaScreenAppName = ngnMediaScreenAppName; _isMediaApp = isMediaApp; _sdlMsgVersionRequest = sdlMsgVersion; _vrSynonyms = vrSynonyms; _sdlLanguageDesired = languageDesired; _hmiDisplayLanguageDesired = hmiDisplayLanguageDesired; _appType = appType; _appID = appID; _autoActivateIdDesired = autoActivateID; _dayColorScheme = dayColorScheme; _nightColorScheme = nightColorScheme; _transportConfig = transportConfig; // Test conditions to invalidate the proxy if (listener == null) { throw new IllegalArgumentException("IProxyListener listener must be provided to instantiate SdlProxy object."); } if (_advancedLifecycleManagementEnabled) { if (_isMediaApp == null) { throw new IllegalArgumentException("isMediaApp must not be null when using SdlProxyALM."); } } _proxyListener = listener; // Get information from sdlProxyConfigurationResources if (sdlProxyConfigurationResources != null) { telephonyManager = sdlProxyConfigurationResources.getTelephonyManager(); } // Use the telephonyManager to get and log phone info if (telephonyManager != null) { // Following is not quite thread-safe (because m_traceLogger could test null twice), // so we need to fix this, but vulnerability (i.e. two instances of listener) is // likely harmless. if (_traceDeviceInterrogator == null) { _traceDeviceInterrogator = new TraceDeviceInfo(telephonyManager); } // end-if } // end-if // Setup Internal ProxyMessage Dispatcher synchronized(INTERNAL_MESSAGE_QUEUE_THREAD_LOCK) { // Ensure internalProxyMessageDispatcher is null if (_internalProxyMessageDispatcher != null) { _internalProxyMessageDispatcher.dispose(); _internalProxyMessageDispatcher = null; } _internalProxyMessageDispatcher = new ProxyMessageDispatcher<InternalProxyMessage>("INTERNAL_MESSAGE_DISPATCHER", new IDispatchingStrategy<InternalProxyMessage>() { @Override public void dispatch(InternalProxyMessage message) { dispatchInternalMessage(message); } @Override public void handleDispatchingError(String info, Exception ex) { handleErrorsFromInternalMessageDispatcher(info, ex); } @Override public void handleQueueingError(String info, Exception ex) { handleErrorsFromInternalMessageDispatcher(info, ex); } }); } // Setup Incoming ProxyMessage Dispatcher synchronized(INCOMING_MESSAGE_QUEUE_THREAD_LOCK) { // Ensure incomingProxyMessageDispatcher is null if (_incomingProxyMessageDispatcher != null) { _incomingProxyMessageDispatcher.dispose(); _incomingProxyMessageDispatcher = null; } _incomingProxyMessageDispatcher = new ProxyMessageDispatcher<ProtocolMessage>("INCOMING_MESSAGE_DISPATCHER",new IDispatchingStrategy<ProtocolMessage>() { @Override public void dispatch(ProtocolMessage message) { dispatchIncomingMessage(message); } @Override public void handleDispatchingError(String info, Exception ex) { handleErrorsFromIncomingMessageDispatcher(info, ex); } @Override public void handleQueueingError(String info, Exception ex) { handleErrorsFromIncomingMessageDispatcher(info, ex); } }); } // Setup Outgoing ProxyMessage Dispatcher synchronized(OUTGOING_MESSAGE_QUEUE_THREAD_LOCK) { // Ensure outgoingProxyMessageDispatcher is null if (_outgoingProxyMessageDispatcher != null) { _outgoingProxyMessageDispatcher.dispose(); _outgoingProxyMessageDispatcher = null; } _outgoingProxyMessageDispatcher = new ProxyMessageDispatcher<ProtocolMessage>("OUTGOING_MESSAGE_DISPATCHER",new IDispatchingStrategy<ProtocolMessage>() { @Override public void dispatch(ProtocolMessage message) { dispatchOutgoingMessage(message); } @Override public void handleDispatchingError(String info, Exception ex) { handleErrorsFromOutgoingMessageDispatcher(info, ex); } @Override public void handleQueueingError(String info, Exception ex) { handleErrorsFromOutgoingMessageDispatcher(info, ex); } }); } rpcResponseListeners = new SparseArray<OnRPCResponseListener>(); rpcNotificationListeners = new SparseArray<CopyOnWriteArrayList<OnRPCNotificationListener>>(); rpcRequestListeners = new SparseArray<CopyOnWriteArrayList<OnRPCRequestListener>>(); rpcListeners = new SparseArray<CopyOnWriteArrayList<OnRPCListener>>(); // Initialize the proxy try { initializeProxy(); } catch (SdlException e) { // Couldn't initialize the proxy // Dispose threads and then rethrow exception if (_internalProxyMessageDispatcher != null) { _internalProxyMessageDispatcher.dispose(); _internalProxyMessageDispatcher = null; } if (_incomingProxyMessageDispatcher != null) { _incomingProxyMessageDispatcher.dispose(); _incomingProxyMessageDispatcher = null; } if (_outgoingProxyMessageDispatcher != null) { _outgoingProxyMessageDispatcher.dispose(); _outgoingProxyMessageDispatcher = null; } throw e; } // Trace that ctor has fired SdlTrace.logProxyEvent("SdlProxy Created, instanceID=" + this.toString(), SDL_LIB_TRACE_KEY); } protected SdlProxyBase(proxyListenerType listener, SdlProxyConfigurationResources sdlProxyConfigurationResources, boolean enableAdvancedLifecycleManagement, String appName, Vector<TTSChunk> ttsName, String ngnMediaScreenAppName, Vector<String> vrSynonyms, Boolean isMediaApp, SdlMsgVersion sdlMsgVersion, Language languageDesired, Language hmiDisplayLanguageDesired, Vector<AppHMIType> appType, String appID, String autoActivateID, TemplateColorScheme dayColorScheme, TemplateColorScheme nightColorScheme, boolean callbackToUIThread, boolean preRegister, String sHashID, Boolean bEnableResume, BaseTransportConfig transportConfig) throws SdlException { performBaseCommon(listener, sdlProxyConfigurationResources, enableAdvancedLifecycleManagement, appName, ttsName, ngnMediaScreenAppName, vrSynonyms, isMediaApp, sdlMsgVersion, languageDesired, hmiDisplayLanguageDesired, appType, appID, autoActivateID, dayColorScheme, nightColorScheme, callbackToUIThread, preRegister, sHashID, bEnableResume, transportConfig); } /** * Constructor. * * @param listener Type of listener for this proxy base. * @param sdlProxyConfigurationResources Configuration resources for this proxy. * @param enableAdvancedLifecycleManagement Flag that ALM should be enabled or not. * @param appName Client application name. * @param ttsName TTS name. * @param ngnMediaScreenAppName Media Screen Application name. * @param vrSynonyms List of synonyms. * @param isMediaApp Flag that indicates that client application if media application or not. * @param sdlMsgVersion Version of Sdl Message. * @param languageDesired Desired language. * @param hmiDisplayLanguageDesired Desired language for HMI. * @param appType Type of application. * @param appID Application identifier. * @param autoActivateID Auto activation identifier. * @param callbackToUIThread Flag that indicates that this proxy should send callback to UI thread or not. * @param preRegister Flag that indicates that this proxy should be pre-registerd or not. * @param transportConfig Configuration of transport to be used by underlying connection. * @throws SdlException if there is an unrecoverable error class might throw an exception. */ protected SdlProxyBase(proxyListenerType listener, SdlProxyConfigurationResources sdlProxyConfigurationResources, boolean enableAdvancedLifecycleManagement, String appName, Vector<TTSChunk> ttsName, String ngnMediaScreenAppName, Vector<String> vrSynonyms, Boolean isMediaApp, SdlMsgVersion sdlMsgVersion, Language languageDesired, Language hmiDisplayLanguageDesired, Vector<AppHMIType> appType, String appID, String autoActivateID, boolean callbackToUIThread, boolean preRegister, BaseTransportConfig transportConfig) throws SdlException { performBaseCommon(listener, sdlProxyConfigurationResources, enableAdvancedLifecycleManagement, appName, ttsName, ngnMediaScreenAppName, vrSynonyms, isMediaApp, sdlMsgVersion, languageDesired, hmiDisplayLanguageDesired, appType, appID, autoActivateID, null, null, callbackToUIThread, preRegister, null, null, transportConfig); } /** * Constructor. * * @param listener Type of listener for this proxy base. * @param sdlProxyConfigurationResources Configuration resources for this proxy. * @param enableAdvancedLifecycleManagement Flag that ALM should be enabled or not. * @param appName Client application name. * @param ttsName TTS name. * @param ngnMediaScreenAppName Media Screen Application name. * @param vrSynonyms List of synonyms. * @param isMediaApp Flag that indicates that client application if media application or not. * @param sdlMsgVersion Version of Sdl Message. * @param languageDesired Desired language. * @param hmiDisplayLanguageDesired Desired language for HMI. * @param appType Type of application. * @param appID Application identifier. * @param autoActivateID Auto activation identifier. * @param dayColorScheme Day color scheme. * @param dayColorScheme Night color scheme. * @param callbackToUIThread Flag that indicates that this proxy should send callback to UI thread or not. * @param preRegister Flag that indicates that this proxy should be pre-registerd or not. * @param transportConfig Configuration of transport to be used by underlying connection. * @throws SdlException if there is an unrecoverable error class might throw an exception. */ protected SdlProxyBase(proxyListenerType listener, SdlProxyConfigurationResources sdlProxyConfigurationResources, boolean enableAdvancedLifecycleManagement, String appName, Vector<TTSChunk> ttsName, String ngnMediaScreenAppName, Vector<String> vrSynonyms, Boolean isMediaApp, SdlMsgVersion sdlMsgVersion, Language languageDesired, Language hmiDisplayLanguageDesired, Vector<AppHMIType> appType, String appID, String autoActivateID, TemplateColorScheme dayColorScheme, TemplateColorScheme nightColorScheme, boolean callbackToUIThread, boolean preRegister, BaseTransportConfig transportConfig) throws SdlException { performBaseCommon(listener, sdlProxyConfigurationResources, enableAdvancedLifecycleManagement, appName, ttsName, ngnMediaScreenAppName, vrSynonyms, isMediaApp, sdlMsgVersion, languageDesired, hmiDisplayLanguageDesired, appType, appID, autoActivateID, dayColorScheme, nightColorScheme, callbackToUIThread, preRegister, null, null, transportConfig); } private Intent createBroadcastIntent() { Intent sendIntent = new Intent(); sendIntent.setAction("com.smartdevicelink.broadcast"); sendIntent.putExtra("APP_NAME", this._applicationName); sendIntent.putExtra("APP_ID", this._appID); sendIntent.putExtra("RPC_NAME", ""); sendIntent.putExtra("TYPE", ""); sendIntent.putExtra("SUCCESS", true); sendIntent.putExtra("CORRID", 0); sendIntent.putExtra("FUNCTION_NAME", ""); sendIntent.putExtra("COMMENT1", ""); sendIntent.putExtra("COMMENT2", ""); sendIntent.putExtra("COMMENT3", ""); sendIntent.putExtra("COMMENT4", ""); sendIntent.putExtra("COMMENT5", ""); sendIntent.putExtra("COMMENT6", ""); sendIntent.putExtra("COMMENT7", ""); sendIntent.putExtra("COMMENT8", ""); sendIntent.putExtra("COMMENT9", ""); sendIntent.putExtra("COMMENT10", ""); sendIntent.putExtra("DATA", ""); sendIntent.putExtra("SHOW_ON_UI", true); return sendIntent; } private void updateBroadcastIntent(Intent sendIntent, String sKey, String sValue) { if (sValue == null) sValue = ""; sendIntent.putExtra(sKey, sValue); } private void updateBroadcastIntent(Intent sendIntent, String sKey, boolean bValue) { sendIntent.putExtra(sKey, bValue); } private void updateBroadcastIntent(Intent sendIntent, String sKey, int iValue) { sendIntent.putExtra(sKey, iValue); } private Service getService() { try { Service myService = null; if (_proxyListener != null && _proxyListener instanceof Service) { myService = (Service) _proxyListener; } else if (_appService != null) { myService = _appService; } else if (_appContext != null && _appContext instanceof Service) { myService = (Service) _appContext; } return myService; } catch (Exception ex){ return null; } } private void sendBroadcastIntent(Intent sendIntent) { Service myService = null; if (_proxyListener != null && _proxyListener instanceof Service) { myService = (Service) _proxyListener; } else if (_appService != null) { myService = _appService; } Context myContext; if (myService != null){ myContext = myService.getApplicationContext(); } else if (_appContext != null){ myContext = _appContext; } else { return; } try { if (myContext != null) myContext.sendBroadcast(sendIntent); } catch(Exception ex) { //If the service or context has become unavailable unexpectedly, catch the exception and move on -- no broadcast log will occur. } } private HttpURLConnection getURLConnection(Headers myHeader, String sURLString, int Timeout, int iContentLen) { String sContentType = "application/json"; int CONNECTION_TIMEOUT = Timeout * 1000; int READ_TIMEOUT = Timeout * 1000; boolean bDoOutput = true; boolean bDoInput = true; boolean bUsesCaches = false; String sRequestMeth = "POST"; boolean bInstFolRed = false; String sCharSet = "utf-8"; int iContentLength = iContentLen; URL url; HttpURLConnection urlConnection; Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "getURLConnection"); updateBroadcastIntent(sendIntent, "COMMENT1", "Actual Content Length: " + iContentLen); if (myHeader != null) { //if the header isn't null, use it and replace the hardcoded params int iTimeout; int iReadTimeout; sContentType = myHeader.getContentType(); iTimeout = myHeader.getConnectTimeout(); bDoOutput = myHeader.getDoOutput(); bDoInput = myHeader.getDoInput(); bUsesCaches = myHeader.getUseCaches(); sRequestMeth = myHeader.getRequestMethod(); iReadTimeout = myHeader.getReadTimeout(); bInstFolRed = myHeader.getInstanceFollowRedirects(); sCharSet = myHeader.getCharset(); iContentLength = myHeader.getContentLength(); CONNECTION_TIMEOUT = iTimeout*1000; READ_TIMEOUT = iReadTimeout*1000; updateBroadcastIntent(sendIntent, "COMMENT2", "\nHeader Defined Content Length: " + iContentLength); } try { url = new URL(sURLString); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(CONNECTION_TIMEOUT); urlConnection.setDoOutput(bDoOutput); urlConnection.setDoInput(bDoInput); urlConnection.setRequestMethod(sRequestMeth); urlConnection.setReadTimeout(READ_TIMEOUT); urlConnection.setInstanceFollowRedirects(bInstFolRed); urlConnection.setRequestProperty("Content-Type", sContentType); urlConnection.setRequestProperty("charset", sCharSet); urlConnection.setRequestProperty("Content-Length", "" + Integer.toString(iContentLength)); urlConnection.setUseCaches(bUsesCaches); return urlConnection; } catch (Exception e) { return null; } finally { sendBroadcastIntent(sendIntent); } } private void sendOnSystemRequestToUrl(OnSystemRequest msg) { Intent sendIntent = createBroadcastIntent(); Intent sendIntent2 = createBroadcastIntent(); HttpURLConnection urlConnection = null; boolean bLegacy = false; String sURLString; if (!getPoliciesURL().equals("")) { sURLString = sPoliciesURL; } else { sURLString = msg.getUrl(); } Integer iTimeout = msg.getTimeout(); if (iTimeout == null) iTimeout = 2000; Headers myHeader = msg.getHeader(); RequestType requestType = msg.getRequestType(); updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "sendOnSystemRequestToUrl"); updateBroadcastIntent(sendIntent, "COMMENT5", "\r\nCloud URL: " + sURLString); try { if (myHeader == null) { updateBroadcastIntent(sendIntent, "COMMENT7", "\r\nHTTPRequest Header is null"); } String sBodyString = msg.getBody(); JSONObject jsonObjectToSendToServer; String valid_json = ""; int length; if (sBodyString == null) { if(requestType == RequestType.HTTP ){ length = msg.getBulkData().length; Intent sendIntent3 = createBroadcastIntent(); updateBroadcastIntent(sendIntent3, "FUNCTION_NAME", "replace"); updateBroadcastIntent(sendIntent3, "COMMENT1", "Valid Json length before replace: " + length); sendBroadcastIntent(sendIntent3); }else{ List<String> legacyData = msg.getLegacyData(); JSONArray jsonArrayOfSdlPPackets = new JSONArray(legacyData); jsonObjectToSendToServer = new JSONObject(); jsonObjectToSendToServer.put("data", jsonArrayOfSdlPPackets); bLegacy = true; updateBroadcastIntent(sendIntent, "COMMENT6", "\r\nLegacy SystemRequest: true"); valid_json = jsonObjectToSendToServer.toString().replace("\\", ""); length = valid_json.getBytes("UTF-8").length; } } else { Intent sendIntent3 = createBroadcastIntent(); updateBroadcastIntent(sendIntent3, "FUNCTION_NAME", "replace"); updateBroadcastIntent(sendIntent3, "COMMENT1", "Valid Json length before replace: " + sBodyString.getBytes("UTF-8").length); sendBroadcastIntent(sendIntent3); valid_json = sBodyString.replace("\\", ""); length = valid_json.getBytes("UTF-8").length; } urlConnection = getURLConnection(myHeader, sURLString, iTimeout, length); if (urlConnection == null) { Log.i(TAG, "urlConnection is null, check RPC input parameters"); updateBroadcastIntent(sendIntent, "COMMENT2", "urlConnection is null, check RPC input parameters"); return; } DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream()); if(requestType == RequestType.HTTP){ wr.write(msg.getBulkData()); }else{ wr.writeBytes(valid_json); } wr.flush(); wr.close(); long BeforeTime = System.currentTimeMillis(); long AfterTime = System.currentTimeMillis(); final long roundtriptime = AfterTime - BeforeTime; updateBroadcastIntent(sendIntent, "COMMENT4", " Round trip time: " + roundtriptime); updateBroadcastIntent(sendIntent, "COMMENT1", "Received response from cloud, response code=" + urlConnection.getResponseCode() + " "); int iResponseCode = urlConnection.getResponseCode(); if (iResponseCode != HttpURLConnection.HTTP_OK) { Log.i(TAG, "Response code not HTTP_OK, returning from sendOnSystemRequestToUrl."); updateBroadcastIntent(sendIntent, "COMMENT2", "Response code not HTTP_OK, aborting request. "); return; } InputStream is = urlConnection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuilder response = new StringBuilder(); while((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); //We've read the body if(requestType == RequestType.HTTP){ // Create the SystemRequest RPC to send to module. PutFile putFile = new PutFile(); putFile.setFileType(FileType.JSON); putFile.setCorrelationID(POLICIES_CORRELATION_ID); putFile.setSdlFileName("response_data"); putFile.setFileData(response.toString().getBytes("UTF-8")); putFile.setCRC(response.toString().getBytes()); updateBroadcastIntent(sendIntent, "DATA", "Data from cloud response: " + response.toString()); sendRPCMessagePrivate(putFile); Log.i("sendSystemRequestToUrl", "sent to sdl"); updateBroadcastIntent(sendIntent2, "RPC_NAME", FunctionID.PUT_FILE.toString()); updateBroadcastIntent(sendIntent2, "TYPE", RPCMessage.KEY_REQUEST); updateBroadcastIntent(sendIntent2, "CORRID", putFile.getCorrelationID()); }else{ Vector<String> cloudDataReceived = new Vector<String>(); final String dataKey = "data"; // Convert the response to JSON JSONObject jsonResponse = new JSONObject(response.toString()); if(jsonResponse.has(dataKey)){ if (jsonResponse.get(dataKey) instanceof JSONArray) { JSONArray jsonArray = jsonResponse.getJSONArray(dataKey); for (int i=0; i<jsonArray.length(); i++) { if (jsonArray.get(i) instanceof String) { cloudDataReceived.add(jsonArray.getString(i)); //Log.i("sendSystemRequestToUrl", "jsonArray.getString(i): " + jsonArray.getString(i)); } } } else if (jsonResponse.get(dataKey) instanceof String) { cloudDataReceived.add(jsonResponse.getString(dataKey)); //Log.i("sendSystemRequestToUrl", "jsonResponse.getString(data): " + jsonResponse.getString("data")); } } else { DebugTool.logError("sendSystemRequestToUrl: Data in JSON Object neither an array nor a string."); //Log.i("sendSystemRequestToUrl", "sendSystemRequestToUrl: Data in JSON Object neither an array nor a string."); return; } String sResponse = cloudDataReceived.toString(); if (sResponse.length() > 512) { sResponse = sResponse.substring(0, 511); } updateBroadcastIntent(sendIntent, "DATA", "Data from cloud response: " + sResponse); // Send new SystemRequest to SDL SystemRequest mySystemRequest = null; if (bLegacy){ if(cloudDataReceived != null) { mySystemRequest = new SystemRequest(true); mySystemRequest.setCorrelationID(getPoliciesReservedCorrelationID()); mySystemRequest.setLegacyData(cloudDataReceived); } }else{ if (response != null) { mySystemRequest = new SystemRequest(); mySystemRequest.setRequestType(RequestType.PROPRIETARY); mySystemRequest.setCorrelationID(getPoliciesReservedCorrelationID()); mySystemRequest.setBulkData(response.toString().getBytes()); } } if (getIsConnected()) { sendRPCMessagePrivate(mySystemRequest); Log.i("sendSystemRequestToUrl", "sent to sdl"); updateBroadcastIntent(sendIntent2, "RPC_NAME", FunctionID.SYSTEM_REQUEST.toString()); updateBroadcastIntent(sendIntent2, "TYPE", RPCMessage.KEY_REQUEST); updateBroadcastIntent(sendIntent2, "CORRID", mySystemRequest.getCorrelationID()); } } } catch (SdlException e) { DebugTool.logError("sendSystemRequestToUrl: Could not get data from JSONObject received.", e); updateBroadcastIntent(sendIntent, "COMMENT3", " SdlException encountered sendOnSystemRequestToUrl: "+ e); //Log.i("pt", "sendSystemRequestToUrl: Could not get data from JSONObject received."+ e); } catch (JSONException e) { DebugTool.logError("sendSystemRequestToUrl: JSONException: ", e); updateBroadcastIntent(sendIntent, "COMMENT3", " JSONException encountered sendOnSystemRequestToUrl: "+ e); //Log.i("pt", "sendSystemRequestToUrl: JSONException: "+ e); } catch (UnsupportedEncodingException e) { DebugTool.logError("sendSystemRequestToUrl: Could not encode string.", e); updateBroadcastIntent(sendIntent, "COMMENT3", " UnsupportedEncodingException encountered sendOnSystemRequestToUrl: "+ e); //Log.i("pt", "sendSystemRequestToUrl: Could not encode string."+ e); } catch (ProtocolException e) { DebugTool.logError("sendSystemRequestToUrl: Could not set request method to post.", e); updateBroadcastIntent(sendIntent, "COMMENT3", " ProtocolException encountered sendOnSystemRequestToUrl: "+ e); //Log.i("pt", "sendSystemRequestToUrl: Could not set request method to post."+ e); } catch (MalformedURLException e) { DebugTool.logError("sendSystemRequestToUrl: URL Exception when sending SystemRequest to an external server.", e); updateBroadcastIntent(sendIntent, "COMMENT3", " MalformedURLException encountered sendOnSystemRequestToUrl: "+ e); //Log.i("pt", "sendSystemRequestToUrl: URL Exception when sending SystemRequest to an external server."+ e); } catch (IOException e) { DebugTool.logError("sendSystemRequestToUrl: IOException: ", e); updateBroadcastIntent(sendIntent, "COMMENT3", " IOException while sending to cloud: IOException: "+ e); //Log.i("pt", "sendSystemRequestToUrl: IOException: "+ e); } catch (Exception e) { DebugTool.logError("sendSystemRequestToUrl: Unexpected Exception: ", e); updateBroadcastIntent(sendIntent, "COMMENT3", " Exception encountered sendOnSystemRequestToUrl: "+ e); //Log.i("pt", "sendSystemRequestToUrl: Unexpected Exception: " + e); } finally { sendBroadcastIntent(sendIntent); sendBroadcastIntent(sendIntent2); if (iFileCount < 10) iFileCount++; else iFileCount = 0; if(urlConnection != null) { urlConnection.disconnect(); } } } private int getPoliciesReservedCorrelationID() { return POLICIES_CORRELATION_ID; } // Test correlationID private boolean isCorrelationIDProtected(Integer correlationID) { return correlationID != null && (HEARTBEAT_CORRELATION_ID == correlationID || REGISTER_APP_INTERFACE_CORRELATION_ID == correlationID || UNREGISTER_APP_INTERFACE_CORRELATION_ID == correlationID || POLICIES_CORRELATION_ID == correlationID); } // Protected isConnected method to allow legacy proxy to poll isConnected state public Boolean getIsConnected() { return sdlSession != null && sdlSession.getIsConnected(); } /** * Returns whether the application is registered in SDL. Note: for testing * purposes, it's possible that the connection is established, but the * application is not registered. * * @return true if the application is registered in SDL */ public Boolean getAppInterfaceRegistered() { return _appInterfaceRegisterd; } // Function to initialize new proxy connection public void initializeProxy() throws SdlException { // Reset all of the flags and state variables _haveReceivedFirstNonNoneHMILevel = false; _haveReceivedFirstFocusLevel = false; _haveReceivedFirstFocusLevelFull = false; _appInterfaceRegisterd = _preRegisterd; _putFileListenerList.clear(); _sdlIntefaceAvailablity = SdlInterfaceAvailability.SDL_INTERFACE_UNAVAILABLE; //Initialize _systemCapabilityManager here. _systemCapabilityManager = new SystemCapabilityManager(_internalInterface); // Setup SdlConnection synchronized(CONNECTION_REFERENCE_LOCK) { //Handle legacy USB connections if(_transportConfig != null && TransportType.USB.equals(_transportConfig.getTransportType())){ //A USB transport config was provided USBTransportConfig usbTransportConfig = (USBTransportConfig)_transportConfig; if(usbTransportConfig.getUsbAccessory() == null){ DebugTool.logInfo("Legacy USB transport config was used, but received null for accessory. Attempting to connect with router service"); //The accessory was null which means it came from a router service MultiplexTransportConfig multiplexTransportConfig = new MultiplexTransportConfig(usbTransportConfig.getUSBContext(),_appID); multiplexTransportConfig.setRequiresHighBandwidth(true); multiplexTransportConfig.setSecurityLevel(MultiplexTransportConfig.FLAG_MULTI_SECURITY_OFF); multiplexTransportConfig.setPrimaryTransports(Collections.singletonList(TransportType.USB)); multiplexTransportConfig.setSecondaryTransports(new ArrayList<TransportType>()); _transportConfig = multiplexTransportConfig; } } if(_transportConfig.getTransportType().equals(TransportType.MULTIPLEX)){ this.sdlSession = new SdlSession2(_interfaceBroker,(MultiplexTransportConfig)_transportConfig); }else{ this.sdlSession = SdlSession.createSession((byte)getProtocolVersion().getMajor(),_interfaceBroker, _transportConfig); } } synchronized(CONNECTION_REFERENCE_LOCK) { this.sdlSession.startSession(); sendTransportBroadcast(); } } /** * This method will fake the multiplex connection event */ @SuppressWarnings("unused") public void forceOnConnected(){ synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null) { Log.d(TAG, "Forcing on connected.... might actually need this"); //FIXME /*if(sdlSession.getSdlConnection()==null){ //There is an issue when switching from v1 to v2+ where the connection is closed. So we restart the session during this call. try { sdlSession.startSession(); } catch (SdlException e) { e.printStackTrace(); } } sdlSession.getSdlConnection().forceHardwareConnectEvent(TransportType.BLUETOOTH); */ } } } public void sendTransportBroadcast() { if (sdlSession == null || _transportConfig == null) return; String sTransComment = sdlSession.getBroadcastComment(_transportConfig); if (sTransComment == null || sTransComment.equals("")) return; Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "initializeProxy"); updateBroadcastIntent(sendIntent, "COMMENT1", sTransComment); sendBroadcastIntent(sendIntent); } /** * Public method to enable the siphon transport */ @SuppressWarnings("unused") public void enableSiphonDebug() { short enabledPortNumber = SiphonServer.enableSiphonServer(); String sSiphonPortNumber = "Enabled Siphon Port Number: " + enabledPortNumber; Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "enableSiphonDebug"); updateBroadcastIntent(sendIntent, "COMMENT1", sSiphonPortNumber); sendBroadcastIntent(sendIntent); } /** * Public method to disable the Siphon Trace Server */ @SuppressWarnings("unused") public void disableSiphonDebug() { short disabledPortNumber = SiphonServer.disableSiphonServer(); if (disabledPortNumber != -1) { String sSiphonPortNumber = "Disabled Siphon Port Number: " + disabledPortNumber; Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "disableSiphonDebug"); updateBroadcastIntent(sendIntent, "COMMENT1", sSiphonPortNumber); sendBroadcastIntent(sendIntent); } } /** * Public method to enable the Debug Tool */ public static void enableDebugTool() { DebugTool.enableDebugTool(); } /** * Public method to disable the Debug Tool */ public static void disableDebugTool() { DebugTool.disableDebugTool(); } /** * Public method to determine Debug Tool enabled */ @SuppressWarnings("BooleanMethodIsAlwaysInverted") public static boolean isDebugEnabled() { return DebugTool.isDebugEnabled(); } /** * Check to see if it a transport is available to perform audio streaming. * <br><strong>NOTE:</strong> This is only for the audio streaming service, not regular * streaming of media playback. * @return true if there is either an audio streaming supported * transport currently connected or a transport is * available to connect with. false if there is no * transport connected to support audio streaming and * no possibility in the foreseeable future. */ public boolean isAudioStreamTransportAvailable(){ return sdlSession!= null && sdlSession.isTransportForServiceAvailable(SessionType.PCM); } /** * Check to see if it a transport is available to perform video streaming. * @return true if there is either an video streaming supported * transport currently connected or a transport is * available to connect with. false if there is no * transport connected to support video streaming and * no possibility in the foreseeable future. */ public boolean isVideoStreamTransportAvailable(){ return sdlSession!= null && sdlSession.isTransportForServiceAvailable(SessionType.NAV); } @SuppressWarnings("unused") @Deprecated public void close() throws SdlException { dispose(); } @SuppressWarnings("UnusedParameters") private void cleanProxy(SdlDisconnectedReason disconnectedReason) throws SdlException { if (disconnectedReason == SdlDisconnectedReason.MINIMUM_PROTOCOL_VERSION_HIGHER_THAN_SUPPORTED || disconnectedReason == SdlDisconnectedReason.MINIMUM_RPC_VERSION_HIGHER_THAN_SUPPORTED){ notifyProxyClosed(disconnectedReason.toString(), null, disconnectedReason); sdlSession.resetSession(); } try { // ALM Specific Cleanup if (_advancedLifecycleManagementEnabled) { _sdlConnectionState = SdlConnectionState.SDL_DISCONNECTED; firstTimeFull = true; // Should we wait for the interface to be unregistered? Boolean waitForInterfaceUnregistered = false; // Unregister app interface synchronized(CONNECTION_REFERENCE_LOCK) { if (getIsConnected() && getAppInterfaceRegistered()) { waitForInterfaceUnregistered = true; unregisterAppInterfacePrivate(UNREGISTER_APP_INTERFACE_CORRELATION_ID); } } // Wait for the app interface to be unregistered if (waitForInterfaceUnregistered) { synchronized(APP_INTERFACE_REGISTERED_LOCK) { try { APP_INTERFACE_REGISTERED_LOCK.wait(3000); } catch (InterruptedException e) { // Do nothing } } } } if(rpcResponseListeners != null){ rpcResponseListeners.clear(); } if(rpcNotificationListeners != null){ rpcNotificationListeners.clear(); } // Clean up SDL Connection synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null) sdlSession.close(); } } finally { SdlTrace.logProxyEvent("SdlProxy cleaned.", SDL_LIB_TRACE_KEY); } } /** * Terminates the App's Interface Registration, closes the transport connection, ends the protocol session, and frees any resources used by the proxy. */ public void dispose() throws SdlException { if (_proxyDisposed) { throw new SdlException("This object has been disposed, it is no long capable of executing methods.", SdlExceptionCause.SDL_PROXY_DISPOSED); } _proxyDisposed = true; SdlTrace.logProxyEvent("Application called dispose() method.", SDL_LIB_TRACE_KEY); try{ // Clean the proxy cleanProxy(SdlDisconnectedReason.APPLICATION_REQUESTED_DISCONNECT); // Close IncomingProxyMessageDispatcher thread synchronized(INCOMING_MESSAGE_QUEUE_THREAD_LOCK) { if (_incomingProxyMessageDispatcher != null) { _incomingProxyMessageDispatcher.dispose(); _incomingProxyMessageDispatcher = null; } } // Close OutgoingProxyMessageDispatcher thread synchronized(OUTGOING_MESSAGE_QUEUE_THREAD_LOCK) { if (_outgoingProxyMessageDispatcher != null) { _outgoingProxyMessageDispatcher.dispose(); _outgoingProxyMessageDispatcher = null; } } // Close InternalProxyMessageDispatcher thread synchronized(INTERNAL_MESSAGE_QUEUE_THREAD_LOCK) { if (_internalProxyMessageDispatcher != null) { _internalProxyMessageDispatcher.dispose(); _internalProxyMessageDispatcher = null; } } _traceDeviceInterrogator = null; rpcResponseListeners = null; } finally { SdlTrace.logProxyEvent("SdlProxy disposed.", SDL_LIB_TRACE_KEY); } } // end-method private final static Object CYCLE_LOCK = new Object(); private boolean _cycling = false; // Method to cycle the proxy, only called in ALM protected void cycleProxy(SdlDisconnectedReason disconnectedReason) { if (_cycling) return; synchronized(CYCLE_LOCK) { try{ _cycling = true; cleanProxy(disconnectedReason); if(SdlDisconnectedReason.LANGUAGE_CHANGE.equals(disconnectedReason) ){ //The VR engine might need time to reset Thread.sleep(5000); } initializeProxy(); if(!SdlDisconnectedReason.LEGACY_BLUETOOTH_MODE_ENABLED.equals(disconnectedReason) && !SdlDisconnectedReason.PRIMARY_TRANSPORT_CYCLE_REQUEST.equals(disconnectedReason)){//We don't want to alert higher if we are just cycling for legacy bluetooth notifyProxyClosed("Sdl Proxy Cycled", new SdlException("Sdl Proxy Cycled", SdlExceptionCause.SDL_PROXY_CYCLED), disconnectedReason); } } catch (SdlException e) { Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "cycleProxy"); updateBroadcastIntent(sendIntent, "COMMENT1", "Proxy cycled, exception cause: " + e.getSdlExceptionCause()); sendBroadcastIntent(sendIntent); switch(e.getSdlExceptionCause()) { case BLUETOOTH_DISABLED: notifyProxyClosed("Bluetooth is disabled. Bluetooth must be enabled to connect to SDL. Reattempt a connection once Bluetooth is enabled.", new SdlException("Bluetooth is disabled. Bluetooth must be enabled to connect to SDL. Reattempt a connection once Bluetooth is enabled.", SdlExceptionCause.BLUETOOTH_DISABLED), SdlDisconnectedReason.BLUETOOTH_DISABLED); break; case BLUETOOTH_ADAPTER_NULL: notifyProxyClosed("Cannot locate a Bluetooth adapater. A SDL connection is impossible on this device until a Bluetooth adapter is added.", new SdlException("Cannot locate a Bluetooth adapater. A SDL connection is impossible on this device until a Bluetooth adapter is added.", SdlExceptionCause.BLUETOOTH_ADAPTER_NULL), SdlDisconnectedReason.BLUETOOTH_ADAPTER_ERROR); break; default : notifyProxyClosed("Cycling the proxy failed.", e, SdlDisconnectedReason.GENERIC_ERROR); break; } } catch (Exception e) { notifyProxyClosed("Cycling the proxy failed.", e, SdlDisconnectedReason.GENERIC_ERROR); } _cycling = false; } } private void dispatchIncomingMessage(ProtocolMessage message) { try{ // Dispatching logic if (message.getSessionType().equals(SessionType.RPC) ||message.getSessionType().equals(SessionType.BULK_DATA) ) { try { if (protocolVersion!= null && protocolVersion.getMajor() == 1 && message.getVersion() > 1) { if(sdlSession != null && sdlSession.getProtocolVersion()!= null && sdlSession.getProtocolVersion().getMajor() > 1){ setProtocolVersion(sdlSession.getProtocolVersion()); }else{ setProtocolVersion(new Version(message.getVersion(),0,0)); } } Hashtable<String, Object> hash = new Hashtable<String, Object>(); if (protocolVersion!= null && protocolVersion.getMajor() > 1) { Hashtable<String, Object> hashTemp = new Hashtable<String, Object>(); hashTemp.put(RPCMessage.KEY_CORRELATION_ID, message.getCorrID()); if (message.getJsonSize() > 0) { final Hashtable<String, Object> mhash = JsonRPCMarshaller.unmarshall(message.getData()); //hashTemp.put(Names.parameters, mhash.get(Names.parameters)); if (mhash != null) { hashTemp.put(RPCMessage.KEY_PARAMETERS, mhash); } } String functionName = FunctionID.getFunctionName(message.getFunctionID()); if (functionName != null) { hashTemp.put(RPCMessage.KEY_FUNCTION_NAME, functionName); } else { DebugTool.logWarning("Dispatch Incoming Message - function name is null unknown RPC. FunctionId: " + message.getFunctionID()); return; } if (message.getRPCType() == 0x00) { hash.put(RPCMessage.KEY_REQUEST, hashTemp); } else if (message.getRPCType() == 0x01) { hash.put(RPCMessage.KEY_RESPONSE, hashTemp); } else if (message.getRPCType() == 0x02) { hash.put(RPCMessage.KEY_NOTIFICATION, hashTemp); } if (message.getBulkData() != null) hash.put(RPCStruct.KEY_BULK_DATA, message.getBulkData()); if (message.getPayloadProtected()) hash.put(RPCStruct.KEY_PROTECTED, true); } else { hash = JsonRPCMarshaller.unmarshall(message.getData()); } handleRPCMessage(hash); } catch (final Exception excp) { DebugTool.logError("Failure handling protocol message: " + excp.toString(), excp); passErrorToProxyListener("Error handing incoming protocol message.", excp); } // end-catch } //else { Handle other protocol message types here} } catch (final Exception e) { // Pass error to application through listener DebugTool.logError("Error handing proxy event.", e); passErrorToProxyListener("Error handing incoming protocol message.", e); } } /** * Get the SDL protocol spec version being used * @return Version of the protocol spec */ public @NonNull Version getProtocolVersion(){ if(this.protocolVersion == null){ this.protocolVersion = new Version(1,0,0); } return this.protocolVersion; } private void setProtocolVersion(@NonNull Version version) { this.protocolVersion = version; } public String serializeJSON(RPCMessage msg) { try { return msg.serializeJSON((byte)this.getProtocolVersion().getMajor()).toString(2); } catch (final Exception e) { DebugTool.logError("Error handing proxy event.", e); passErrorToProxyListener("Error serializing message.", e); return null; } } private void handleErrorsFromIncomingMessageDispatcher(String info, Exception e) { passErrorToProxyListener(info, e); } private void dispatchOutgoingMessage(ProtocolMessage message) { synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null) { sdlSession.sendMessage(message); } } SdlTrace.logProxyEvent("SdlProxy sending Protocol Message: " + message.toString(), SDL_LIB_TRACE_KEY); } private void handleErrorsFromOutgoingMessageDispatcher(String info, Exception e) { passErrorToProxyListener(info, e); } void dispatchInternalMessage(final InternalProxyMessage message) { try{ switch (message.getFunctionName()) { case InternalProxyMessage.OnProxyError: { final OnError msg = (OnError) message; if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onError(msg.getInfo(), msg.getException()); } }); } else { _proxyListener.onError(msg.getInfo(), msg.getException()); } break; } case InternalProxyMessage.OnServiceEnded: { final OnServiceEnded msg = (OnServiceEnded) message; if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onServiceEnded(msg); } }); } else { _proxyListener.onServiceEnded(msg); } break; } case InternalProxyMessage.OnServiceNACKed: { final OnServiceNACKed msg = (OnServiceNACKed) message; if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onServiceNACKed(msg); } }); } else { _proxyListener.onServiceNACKed(msg); } break; } case InternalProxyMessage.OnProxyOpened: if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { ((IProxyListener) _proxyListener).onProxyOpened(); } }); } else { ((IProxyListener) _proxyListener).onProxyOpened(); } break; case InternalProxyMessage.OnProxyClosed: { final OnProxyClosed msg = (OnProxyClosed) message; if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onProxyClosed(msg.getInfo(), msg.getException(), msg.getReason()); } }); } else { _proxyListener.onProxyClosed(msg.getInfo(), msg.getException(), msg.getReason()); } break; } default: // Diagnostics SdlTrace.logProxyEvent("Unknown RPC Message encountered. Check for an updated version of the SDL Proxy.", SDL_LIB_TRACE_KEY); DebugTool.logError("Unknown RPC Message encountered. Check for an updated version of the SDL Proxy."); break; } SdlTrace.logProxyEvent("Proxy fired callback: " + message.getFunctionName(), SDL_LIB_TRACE_KEY); } catch(final Exception e) { // Pass error to application through listener DebugTool.logError("Error handing proxy event.", e); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onError("Error handing proxy event.", e); } }); } else { _proxyListener.onError("Error handing proxy event.", e); } } } private void handleErrorsFromInternalMessageDispatcher(String info, Exception e) { DebugTool.logError(info, e); // This error cannot be passed to the user, as it indicates an error // in the communication between the proxy and the application. DebugTool.logError("InternalMessageDispatcher failed.", e); // Note, this is the only place where the _proxyListener should be referenced asdlhronously, // with an error on the internalMessageDispatcher, we have no other reliable way of // communicating with the application. notifyProxyClosed("Proxy callback dispatcher is down. Proxy instance is invalid.", e, SdlDisconnectedReason.GENERIC_ERROR); _proxyListener.onError("Proxy callback dispatcher is down. Proxy instance is invalid.", e); } // Private sendRPCMessagePrivate method. All RPCMessages are funneled through this method after error checking. protected void sendRPCMessagePrivate(RPCMessage message) throws SdlException { try { SdlTrace.logRPCEvent(InterfaceActivityDirection.Transmit, message, SDL_LIB_TRACE_KEY); //FIXME this is temporary until the next major release of the library where OK is removed if (message.getMessageType().equals(RPCMessage.KEY_REQUEST)) { RPCRequest request = (RPCRequest) message; if (FunctionID.SUBSCRIBE_BUTTON.toString().equals(request.getFunctionName()) || FunctionID.UNSUBSCRIBE_BUTTON.toString().equals(request.getFunctionName()) || FunctionID.BUTTON_PRESS.toString().equals(request.getFunctionName())) { ButtonName buttonName = (ButtonName) request.getObject(ButtonName.class, SubscribeButton.KEY_BUTTON_NAME); if (rpcSpecVersion != null) { if (rpcSpecVersion.getMajor() < 5) { if (ButtonName.PLAY_PAUSE.equals(buttonName)) { request.setParameters(SubscribeButton.KEY_BUTTON_NAME, ButtonName.OK); } } else { //Newer than version 5.0.0 if (ButtonName.OK.equals(buttonName)) { RPCRequest request2 = new RPCRequest(request); request2.setParameters(SubscribeButton.KEY_BUTTON_NAME, ButtonName.PLAY_PAUSE); request2.setOnRPCResponseListener(request.getOnRPCResponseListener()); sendRPCMessagePrivate(request2); return; } } } } } message.format(rpcSpecVersion,true); byte[] msgBytes = JsonRPCMarshaller.marshall(message, (byte)getProtocolVersion().getMajor()); ProtocolMessage pm = new ProtocolMessage(); pm.setData(msgBytes); pm.setMessageType(MessageType.RPC); pm.setSessionType(SessionType.RPC); pm.setFunctionID(FunctionID.getFunctionId(message.getFunctionName())); pm.setPayloadProtected(message.isPayloadProtected()); if (sdlSession != null) { pm.setSessionID(sdlSession.getSessionId()); } if (message.getBulkData() != null) { pm.setBulkData(message.getBulkData()); } if (message.getMessageType().equals(RPCMessage.KEY_REQUEST)) { // Request Specifics pm.setRPCType((byte)0x00); RPCRequest request = (RPCRequest) message; if (request.getCorrelationID() == null) { //Log error here throw new SdlException("CorrelationID cannot be null. RPC: " + request.getFunctionName(), SdlExceptionCause.INVALID_ARGUMENT); } else { pm.setCorrID(request.getCorrelationID()); } if (request.getFunctionName().equalsIgnoreCase(FunctionID.PUT_FILE.name())) { pm.setPriorityCoefficient(1); } } else if (message.getMessageType().equals(RPCMessage.KEY_RESPONSE)) { // Response Specifics pm.setRPCType((byte)0x01); RPCResponse response = (RPCResponse) message; if (response.getCorrelationID() == null) { //Log error here throw new SdlException("CorrelationID cannot be null. RPC: " + response.getFunctionName(), SdlExceptionCause.INVALID_ARGUMENT); } else { pm.setCorrID(response.getCorrelationID()); } } else if (message.getMessageType().equals(RPCMessage.KEY_NOTIFICATION)) { // Notification Specifics pm.setRPCType((byte)0x02); } else { //Log error here throw new SdlException("RPC message is not a valid type", SdlExceptionCause.INVALID_ARGUMENT); } // Queue this outgoing message synchronized(OUTGOING_MESSAGE_QUEUE_THREAD_LOCK) { if (_outgoingProxyMessageDispatcher != null) { _outgoingProxyMessageDispatcher.queueMessage(pm); //Since the message is queued we can add it's listener to our list, if it is a Request if (message.getMessageType().equals(RPCMessage.KEY_REQUEST)) { RPCRequest request = (RPCRequest) message; OnRPCResponseListener listener = request.getOnRPCResponseListener(); addOnRPCResponseListener(listener, request.getCorrelationID(), msgBytes.length); } } } } catch (OutOfMemoryError e) { SdlTrace.logProxyEvent("OutOfMemory exception while sending message " + message.getFunctionName(), SDL_LIB_TRACE_KEY); throw new SdlException("OutOfMemory exception while sending message " + message.getFunctionName(), e, SdlExceptionCause.INVALID_ARGUMENT); } } /** * Only call this method for a PutFile response. It will cause a class cast exception if not. * @param correlationId correlation id of the packet being updated * @param bytesWritten how many bytes were written * @param totalSize the total size in bytes */ @SuppressWarnings("unused") public void onPacketProgress(int correlationId, long bytesWritten, long totalSize){ synchronized(ON_UPDATE_LISTENER_LOCK){ if(rpcResponseListeners !=null && rpcResponseListeners.indexOfKey(correlationId)>=0){ ((OnPutFileUpdateListener)rpcResponseListeners.get(correlationId)).onUpdate(correlationId, bytesWritten, totalSize); } } } /** * Will provide callback to the listener either onFinish or onError depending on the RPCResponses result code, * <p>Will automatically remove the listener for the list of listeners on completion. * @param msg The RPCResponse message that was received * @return if a listener was called or not */ @SuppressWarnings("UnusedReturnValue") private boolean onRPCResponseReceived(RPCResponse msg){ synchronized(ON_UPDATE_LISTENER_LOCK){ int correlationId = msg.getCorrelationID(); if(rpcResponseListeners !=null && rpcResponseListeners.indexOfKey(correlationId)>=0){ OnRPCResponseListener listener = rpcResponseListeners.get(correlationId); if(msg.getSuccess()){ listener.onResponse(correlationId, msg); }else{ listener.onError(correlationId, msg.getResultCode(), msg.getInfo()); } rpcResponseListeners.remove(correlationId); return true; } return false; } } /** * Add a listener that will receive the response to the specific RPCRequest sent with the corresponding correlation id * @param listener that will get called back when a response is received * @param correlationId of the RPCRequest that was sent * @param totalSize only include if this is an OnPutFileUpdateListener. Otherwise it will be ignored. */ public void addOnRPCResponseListener(OnRPCResponseListener listener,int correlationId, int totalSize){ synchronized(ON_UPDATE_LISTENER_LOCK){ if(rpcResponseListeners!=null && listener !=null){ if(listener.getListenerType() == OnRPCResponseListener.UPDATE_LISTENER_TYPE_PUT_FILE){ ((OnPutFileUpdateListener)listener).setTotalSize(totalSize); } listener.onStart(correlationId); rpcResponseListeners.put(correlationId, listener); } } } @SuppressWarnings("unused") public SparseArray<OnRPCResponseListener> getResponseListeners(){ synchronized(ON_UPDATE_LISTENER_LOCK){ return this.rpcResponseListeners; } } @SuppressWarnings("UnusedReturnValue") public boolean onRPCNotificationReceived(RPCNotification notification){ synchronized(ON_NOTIFICATION_LISTENER_LOCK){ CopyOnWriteArrayList<OnRPCNotificationListener> listeners = rpcNotificationListeners.get(FunctionID.getFunctionId(notification.getFunctionName())); if(listeners!=null && listeners.size()>0) { for (OnRPCNotificationListener listener : listeners) { listener.onNotified(notification); } return true; } return false; } } @SuppressWarnings("UnusedReturnValue") public boolean onRPCReceived(RPCMessage message){ synchronized(RPC_LISTENER_LOCK){ CopyOnWriteArrayList<OnRPCListener> listeners = rpcListeners.get(FunctionID.getFunctionId(message.getFunctionName())); if(listeners!=null && listeners.size()>0) { for (OnRPCListener listener : listeners) { listener.onReceived(message); } return true; } return false; } } @SuppressWarnings("UnusedReturnValue") public boolean onRPCRequestReceived(RPCRequest request){ synchronized(ON_NOTIFICATION_LISTENER_LOCK){ CopyOnWriteArrayList<OnRPCRequestListener> listeners = rpcRequestListeners.get(FunctionID.getFunctionId(request.getFunctionName())); if(listeners!=null && listeners.size()>0) { for (OnRPCRequestListener listener : listeners) { listener.onRequest(request); } return true; } return false; } } /** * This will ad a listener for the specific type of notification. As of now it will only allow * a single listener per notification function id * @param notificationId The notification type that this listener is designated for * @param listener The listener that will be called when a notification of the provided type is received */ @SuppressWarnings("unused") public void addOnRPCNotificationListener(FunctionID notificationId, OnRPCNotificationListener listener){ synchronized(ON_NOTIFICATION_LISTENER_LOCK){ if(notificationId != null && listener != null){ if(rpcNotificationListeners.indexOfKey(notificationId.getId()) < 0 ){ rpcNotificationListeners.put(notificationId.getId(),new CopyOnWriteArrayList<OnRPCNotificationListener>()); } rpcNotificationListeners.get(notificationId.getId()).add(listener); } } } /** * This will add a listener for the specific type of message. As of now it will only allow * a single listener per request function id * @param messageId The message type that this listener is designated for * @param listener The listener that will be called when a request of the provided type is received */ @SuppressWarnings("unused") public void addOnRPCListener(FunctionID messageId, OnRPCListener listener){ synchronized(RPC_LISTENER_LOCK){ if(messageId != null && listener != null){ if(rpcListeners.indexOfKey(messageId.getId()) < 0 ){ rpcListeners.put(messageId.getId(),new CopyOnWriteArrayList<OnRPCListener>()); } rpcListeners.get(messageId.getId()).add(listener); } } } public boolean removeOnRPCListener(FunctionID messageId, OnRPCListener listener){ synchronized(RPC_LISTENER_LOCK){ if(rpcListeners!= null && messageId != null && listener != null && rpcListeners.indexOfKey(messageId.getId()) >= 0){ return rpcListeners.get(messageId.getId()).remove(listener); } } return false; } /** * This will add a listener for the specific type of request. As of now it will only allow * a single listener per request function id * @param requestId The request type that this listener is designated for * @param listener The listener that will be called when a request of the provided type is received */ @SuppressWarnings("unused") public void addOnRPCRequestListener(FunctionID requestId, OnRPCRequestListener listener){ synchronized(ON_NOTIFICATION_LISTENER_LOCK){ if(requestId != null && listener != null){ if(rpcRequestListeners.indexOfKey(requestId.getId()) < 0 ){ rpcRequestListeners.put(requestId.getId(),new CopyOnWriteArrayList<OnRPCRequestListener>()); } rpcRequestListeners.get(requestId.getId()).add(listener); } } } /** * This method is no longer valid and will not remove the listener for the supplied notificaiton id * @param notificationId n/a * @see #removeOnRPCNotificationListener(FunctionID, OnRPCNotificationListener) */ @SuppressWarnings("unused") @Deprecated public void removeOnRPCNotificationListener(FunctionID notificationId){ synchronized(ON_NOTIFICATION_LISTENER_LOCK){ //rpcNotificationListeners.delete(notificationId.getId()); } } public boolean removeOnRPCNotificationListener(FunctionID notificationId, OnRPCNotificationListener listener){ synchronized(ON_NOTIFICATION_LISTENER_LOCK){ if(rpcNotificationListeners!= null && notificationId != null && listener != null && rpcNotificationListeners.indexOfKey(notificationId.getId()) >= 0){ return rpcNotificationListeners.get(notificationId.getId()).remove(listener); } } return false; } public boolean removeOnRPCRequestListener(FunctionID requestId, OnRPCRequestListener listener){ synchronized(ON_NOTIFICATION_LISTENER_LOCK){ if(rpcRequestListeners!= null && requestId != null && listener != null && rpcRequestListeners.indexOfKey(requestId.getId()) >= 0){ return rpcRequestListeners.get(requestId.getId()).remove(listener); } } return false; } private void processRaiResponse(RegisterAppInterfaceResponse rai) { if (rai == null) return; this.raiResponse = rai; VehicleType vt = rai.getVehicleType(); if (vt == null) return; String make = vt.getMake(); if (make == null) return; if (_secList == null) return; SdlSecurityBase sec; Service svc = getService(); SdlSecurityBase.setAppService(svc); if (svc != null && svc.getApplicationContext() != null){ SdlSecurityBase.setContext(svc.getApplicationContext()); } else { SdlSecurityBase.setContext(_appContext); } for (Class<? extends SdlSecurityBase> cls : _secList) { try { sec = cls.newInstance(); } catch (Exception e) { continue; } if ( (sec != null) && (sec.getMakeList() != null) ) { if (sec.getMakeList().contains(make)) { setSdlSecurity(sec); sec.setAppId(_appID); if (sdlSession != null) sec.handleSdlSession(sdlSession); return; } } } } private void handleRPCMessage(Hashtable<String, Object> hash) { if (hash == null){ DebugTool.logError("handleRPCMessage: hash is null, returning."); return; } RPCMessage rpcMsg = RpcConverter.convertTableToRpc(hash); if (rpcMsg == null){ DebugTool.logError("handleRPCMessage: rpcMsg is null, returning."); return; } SdlTrace.logRPCEvent(InterfaceActivityDirection.Receive, rpcMsg, SDL_LIB_TRACE_KEY); String functionName = rpcMsg.getFunctionName(); String messageType = rpcMsg.getMessageType(); rpcMsg.format(rpcSpecVersion, true); onRPCReceived(rpcMsg); // Should only be called for internal use // Requests need to be listened for using the SDLManager's addOnRPCRequestListener method. // Requests are not supported by IProxyListenerBase if (messageType.equals(RPCMessage.KEY_REQUEST)) { onRPCRequestReceived((RPCRequest) rpcMsg); } else if (messageType.equals(RPCMessage.KEY_RESPONSE)) { // Check to ensure response is not from an internal message (reserved correlation ID) if (isCorrelationIDProtected((new RPCResponse(hash)).getCorrelationID())) { // This is a response generated from an internal message, it can be trapped here // The app should not receive a response for a request it did not send if ((new RPCResponse(hash)).getCorrelationID() == REGISTER_APP_INTERFACE_CORRELATION_ID && _advancedLifecycleManagementEnabled && functionName.equals(FunctionID.REGISTER_APP_INTERFACE.toString())) { final RegisterAppInterfaceResponse msg = new RegisterAppInterfaceResponse(hash); msg.format(rpcSpecVersion, true); if (msg.getSuccess()) { _appInterfaceRegisterd = true; } processRaiResponse(msg); //Populate the system capability manager with the RAI response _systemCapabilityManager.parseRAIResponse(msg); Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "RPC_NAME", FunctionID.REGISTER_APP_INTERFACE.toString()); updateBroadcastIntent(sendIntent, "TYPE", RPCMessage.KEY_RESPONSE); updateBroadcastIntent(sendIntent, "SUCCESS", msg.getSuccess()); updateBroadcastIntent(sendIntent, "COMMENT1", msg.getInfo()); updateBroadcastIntent(sendIntent, "COMMENT2", msg.getResultCode().toString()); updateBroadcastIntent(sendIntent, "DATA",serializeJSON(msg)); updateBroadcastIntent(sendIntent, "CORRID", msg.getCorrelationID()); sendBroadcastIntent(sendIntent); //_autoActivateIdReturned = msg.getAutoActivateID(); /*Place holder for legacy support*/ _autoActivateIdReturned = "8675309"; _prerecordedSpeech = msg.getPrerecordedSpeech(); _sdlLanguage = msg.getLanguage(); _hmiDisplayLanguage = msg.getHmiDisplayLanguage(); _sdlMsgVersion = msg.getSdlMsgVersion(); if(_sdlMsgVersion != null){ rpcSpecVersion = new com.smartdevicelink.util.Version(_sdlMsgVersion.getMajorVersion(),_sdlMsgVersion.getMinorVersion(), _sdlMsgVersion.getPatchVersion()); }else{ rpcSpecVersion = MAX_SUPPORTED_RPC_VERSION; } if (minimumRPCVersion != null && minimumRPCVersion.isNewerThan(rpcSpecVersion) == 1){ Log.w(TAG, String.format("Disconnecting from head unit, the configured minimum RPC version %s is greater than the supported RPC version %s", minimumRPCVersion, rpcSpecVersion)); try { unregisterAppInterfacePrivate(UNREGISTER_APP_INTERFACE_CORRELATION_ID); } catch (SdlException e) { e.printStackTrace(); } try { cleanProxy(SdlDisconnectedReason.MINIMUM_RPC_VERSION_HIGHER_THAN_SUPPORTED); } catch (SdlException e) { e.printStackTrace(); } return; } _vehicleType = msg.getVehicleType(); _systemSoftwareVersion = msg.getSystemSoftwareVersion(); _proxyVersionInfo = BuildConfig.VERSION_NAME; _iconResumed = msg.getIconResumed(); if (_iconResumed == null){ _iconResumed = false; } if (_bAppResumeEnabled) { if ( (_sdlMsgVersion.getMajorVersion() > 2) && (_lastHashID != null) && (msg.getSuccess()) && (msg.getResultCode() != Result.RESUME_FAILED) ) _bResumeSuccess = true; else { _bResumeSuccess = false; _lastHashID = null; } } _diagModes = msg.getSupportedDiagModes(); String sVersionInfo = "SDL Proxy Version: " + _proxyVersionInfo; if (!isDebugEnabled()) { enableDebugTool(); DebugTool.logInfo(sVersionInfo, false); disableDebugTool(); } else DebugTool.logInfo(sVersionInfo, false); sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "RAI_RESPONSE"); updateBroadcastIntent(sendIntent, "COMMENT1", sVersionInfo); sendBroadcastIntent(sendIntent); // Send onSdlConnected message in ALM _sdlConnectionState = SdlConnectionState.SDL_CONNECTED; // If registerAppInterface failed, exit with OnProxyUnusable if (!msg.getSuccess()) { notifyProxyClosed("Unable to register app interface. Review values passed to the SdlProxy constructor. RegisterAppInterface result code: ", new SdlException("Unable to register app interface. Review values passed to the SdlProxy constructor. RegisterAppInterface result code: " + msg.getResultCode(), SdlExceptionCause.SDL_REGISTRATION_ERROR), SdlDisconnectedReason.SDL_REGISTRATION_ERROR); } if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { if (_proxyListener instanceof IProxyListener) { ((IProxyListener)_proxyListener).onRegisterAppInterfaceResponse(msg); } onRPCResponseReceived(msg); } }); } else { if (_proxyListener instanceof IProxyListener) { ((IProxyListener)_proxyListener).onRegisterAppInterfaceResponse(msg); } onRPCResponseReceived(msg); } } else if ((new RPCResponse(hash)).getCorrelationID() == POLICIES_CORRELATION_ID && functionName.equals(FunctionID.ON_ENCODED_SYNC_P_DATA.toString())) { Log.i("pt", "POLICIES_CORRELATION_ID SystemRequest Notification (Legacy)"); final OnSystemRequest msg = new OnSystemRequest(hash); // If url is not null, then send to URL if ( (msg.getUrl() != null) ) { // URL has data, attempt to post request to external server Thread handleOffboardTransmissionThread = new Thread() { @Override public void run() { sendOnSystemRequestToUrl(msg); } }; handleOffboardTransmissionThread.start(); } } else if ((new RPCResponse(hash)).getCorrelationID() == POLICIES_CORRELATION_ID && functionName.equals(FunctionID.ENCODED_SYNC_P_DATA.toString())) { Log.i("pt", "POLICIES_CORRELATION_ID SystemRequest Response (Legacy)"); final SystemRequestResponse msg = new SystemRequestResponse(hash); Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "RPC_NAME", FunctionID.SYSTEM_REQUEST.toString()); updateBroadcastIntent(sendIntent, "TYPE", RPCMessage.KEY_RESPONSE); updateBroadcastIntent(sendIntent, "SUCCESS", msg.getSuccess()); updateBroadcastIntent(sendIntent, "COMMENT1", msg.getInfo()); updateBroadcastIntent(sendIntent, "COMMENT2", msg.getResultCode().toString()); updateBroadcastIntent(sendIntent, "CORRID", msg.getCorrelationID()); sendBroadcastIntent(sendIntent); } else if ((new RPCResponse(hash)).getCorrelationID() == POLICIES_CORRELATION_ID && functionName.equals(FunctionID.SYSTEM_REQUEST.toString())) { final SystemRequestResponse msg = new SystemRequestResponse(hash); Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "RPC_NAME", FunctionID.SYSTEM_REQUEST.toString()); updateBroadcastIntent(sendIntent, "TYPE", RPCMessage.KEY_RESPONSE); updateBroadcastIntent(sendIntent, "SUCCESS", msg.getSuccess()); updateBroadcastIntent(sendIntent, "COMMENT1", msg.getInfo()); updateBroadcastIntent(sendIntent, "COMMENT2", msg.getResultCode().toString()); updateBroadcastIntent(sendIntent, "CORRID", msg.getCorrelationID()); updateBroadcastIntent(sendIntent, "DATA", serializeJSON(msg)); sendBroadcastIntent(sendIntent); } else if (functionName.equals(FunctionID.UNREGISTER_APP_INTERFACE.toString())) { // UnregisterAppInterface _appInterfaceRegisterd = false; synchronized(APP_INTERFACE_REGISTERED_LOCK) { APP_INTERFACE_REGISTERED_LOCK.notify(); } final UnregisterAppInterfaceResponse msg = new UnregisterAppInterfaceResponse(hash); msg.format(rpcSpecVersion, true); Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "RPC_NAME", FunctionID.UNREGISTER_APP_INTERFACE.toString()); updateBroadcastIntent(sendIntent, "TYPE", RPCMessage.KEY_RESPONSE); updateBroadcastIntent(sendIntent, "SUCCESS", msg.getSuccess()); updateBroadcastIntent(sendIntent, "COMMENT1", msg.getInfo()); updateBroadcastIntent(sendIntent, "COMMENT2", msg.getResultCode().toString()); updateBroadcastIntent(sendIntent, "DATA",serializeJSON(msg)); updateBroadcastIntent(sendIntent, "CORRID", msg.getCorrelationID()); sendBroadcastIntent(sendIntent); } return; } if (functionName.equals(FunctionID.REGISTER_APP_INTERFACE.toString())) { final RegisterAppInterfaceResponse msg = new RegisterAppInterfaceResponse(hash); msg.format(rpcSpecVersion, true); if (msg.getSuccess()) { _appInterfaceRegisterd = true; } processRaiResponse(msg); //Populate the system capability manager with the RAI response _systemCapabilityManager.parseRAIResponse(msg); //_autoActivateIdReturned = msg.getAutoActivateID(); /*Place holder for legacy support*/ _autoActivateIdReturned = "8675309"; _prerecordedSpeech = msg.getPrerecordedSpeech(); _sdlLanguage = msg.getLanguage(); _hmiDisplayLanguage = msg.getHmiDisplayLanguage(); _sdlMsgVersion = msg.getSdlMsgVersion(); rpcSpecVersion = new com.smartdevicelink.util.Version(_sdlMsgVersion.getMajorVersion(),_sdlMsgVersion.getMinorVersion(), _sdlMsgVersion.getPatchVersion()); _vehicleType = msg.getVehicleType(); _systemSoftwareVersion = msg.getSystemSoftwareVersion(); _proxyVersionInfo = BuildConfig.VERSION_NAME; if (_bAppResumeEnabled) { if ( (_sdlMsgVersion.getMajorVersion() > 2) && (_lastHashID != null) && (msg.getSuccess()) && (msg.getResultCode() != Result.RESUME_FAILED) ) _bResumeSuccess = true; else { _bResumeSuccess = false; _lastHashID = null; } } _diagModes = msg.getSupportedDiagModes(); if (!isDebugEnabled()) { enableDebugTool(); DebugTool.logInfo("SDL Proxy Version: " + _proxyVersionInfo); disableDebugTool(); } else DebugTool.logInfo("SDL Proxy Version: " + _proxyVersionInfo); // RegisterAppInterface if (_advancedLifecycleManagementEnabled) { // Send onSdlConnected message in ALM _sdlConnectionState = SdlConnectionState.SDL_CONNECTED; // If registerAppInterface failed, exit with OnProxyUnusable if (!msg.getSuccess()) { notifyProxyClosed("Unable to register app interface. Review values passed to the SdlProxy constructor. RegisterAppInterface result code: ", new SdlException("Unable to register app interface. Review values passed to the SdlProxy constructor. RegisterAppInterface result code: " + msg.getResultCode(), SdlExceptionCause.SDL_REGISTRATION_ERROR), SdlDisconnectedReason.SDL_REGISTRATION_ERROR); } } else { if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { if (_proxyListener instanceof IProxyListener) { ((IProxyListener)_proxyListener).onRegisterAppInterfaceResponse(msg); } onRPCResponseReceived(msg); } }); } else { if (_proxyListener instanceof IProxyListener) { ((IProxyListener)_proxyListener).onRegisterAppInterfaceResponse(msg); } onRPCResponseReceived(msg); } } } else if (functionName.equals(FunctionID.SPEAK.toString())) { // SpeakResponse final SpeakResponse msg = new SpeakResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onSpeakResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onSpeakResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.ALERT.toString())) { // AlertResponse final AlertResponse msg = new AlertResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onAlertResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onAlertResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SHOW.toString())) { // ShowResponse final ShowResponse msg = new ShowResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onShowResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onShowResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.ADD_COMMAND.toString())) { // AddCommand final AddCommandResponse msg = new AddCommandResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onAddCommandResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onAddCommandResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.DELETE_COMMAND.toString())) { // DeleteCommandResponse final DeleteCommandResponse msg = new DeleteCommandResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onDeleteCommandResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onDeleteCommandResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.ADD_SUB_MENU.toString())) { // AddSubMenu final AddSubMenuResponse msg = new AddSubMenuResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onAddSubMenuResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onAddSubMenuResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.DELETE_SUB_MENU.toString())) { // DeleteSubMenu final DeleteSubMenuResponse msg = new DeleteSubMenuResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onDeleteSubMenuResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onDeleteSubMenuResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SUBSCRIBE_BUTTON.toString())) { // SubscribeButton final SubscribeButtonResponse msg = new SubscribeButtonResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onSubscribeButtonResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onSubscribeButtonResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.UNSUBSCRIBE_BUTTON.toString())) { // UnsubscribeButton final UnsubscribeButtonResponse msg = new UnsubscribeButtonResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onUnsubscribeButtonResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onUnsubscribeButtonResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SET_MEDIA_CLOCK_TIMER.toString())) { // SetMediaClockTimer final SetMediaClockTimerResponse msg = new SetMediaClockTimerResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onSetMediaClockTimerResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onSetMediaClockTimerResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.ENCODED_SYNC_P_DATA.toString())) { final SystemRequestResponse msg = new SystemRequestResponse(hash); msg.format(rpcSpecVersion,true); Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "RPC_NAME", FunctionID.SYSTEM_REQUEST.toString()); updateBroadcastIntent(sendIntent, "TYPE", RPCMessage.KEY_RESPONSE); updateBroadcastIntent(sendIntent, "SUCCESS", msg.getSuccess()); updateBroadcastIntent(sendIntent, "COMMENT1", msg.getInfo()); updateBroadcastIntent(sendIntent, "COMMENT2", msg.getResultCode().toString()); updateBroadcastIntent(sendIntent, "CORRID", msg.getCorrelationID()); sendBroadcastIntent(sendIntent); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onSystemRequestResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onSystemRequestResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.CREATE_INTERACTION_CHOICE_SET.toString())) { // CreateInteractionChoiceSet final CreateInteractionChoiceSetResponse msg = new CreateInteractionChoiceSetResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onCreateInteractionChoiceSetResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onCreateInteractionChoiceSetResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.DELETE_INTERACTION_CHOICE_SET.toString())) { // DeleteInteractionChoiceSet final DeleteInteractionChoiceSetResponse msg = new DeleteInteractionChoiceSetResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onDeleteInteractionChoiceSetResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onDeleteInteractionChoiceSetResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.PERFORM_INTERACTION.toString())) { // PerformInteraction final PerformInteractionResponse msg = new PerformInteractionResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onPerformInteractionResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onPerformInteractionResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SET_GLOBAL_PROPERTIES.toString())) { // SetGlobalPropertiesResponse final SetGlobalPropertiesResponse msg = new SetGlobalPropertiesResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onSetGlobalPropertiesResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onSetGlobalPropertiesResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.RESET_GLOBAL_PROPERTIES.toString())) { // ResetGlobalProperties final ResetGlobalPropertiesResponse msg = new ResetGlobalPropertiesResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onResetGlobalPropertiesResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onResetGlobalPropertiesResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.UNREGISTER_APP_INTERFACE.toString())) { // UnregisterAppInterface _appInterfaceRegisterd = false; synchronized(APP_INTERFACE_REGISTERED_LOCK) { APP_INTERFACE_REGISTERED_LOCK.notify(); } final UnregisterAppInterfaceResponse msg = new UnregisterAppInterfaceResponse(hash); msg.format(rpcSpecVersion,true); Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "RPC_NAME", FunctionID.UNREGISTER_APP_INTERFACE.toString()); updateBroadcastIntent(sendIntent, "TYPE", RPCMessage.KEY_RESPONSE); updateBroadcastIntent(sendIntent, "SUCCESS", msg.getSuccess()); updateBroadcastIntent(sendIntent, "COMMENT1", msg.getInfo()); updateBroadcastIntent(sendIntent, "COMMENT2", msg.getResultCode().toString()); updateBroadcastIntent(sendIntent, "DATA",serializeJSON(msg)); updateBroadcastIntent(sendIntent, "CORRID", msg.getCorrelationID()); sendBroadcastIntent(sendIntent); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { if (_proxyListener instanceof IProxyListener) { ((IProxyListener)_proxyListener).onUnregisterAppInterfaceResponse(msg); } onRPCResponseReceived(msg); } }); } else { if (_proxyListener instanceof IProxyListener) { ((IProxyListener)_proxyListener).onUnregisterAppInterfaceResponse(msg); } onRPCResponseReceived(msg); } notifyProxyClosed("UnregisterAppInterfaceResponse", null, SdlDisconnectedReason.APP_INTERFACE_UNREG); } else if (functionName.equals(FunctionID.GENERIC_RESPONSE.toString())) { // GenericResponse (Usually and error) final GenericResponse msg = new GenericResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onGenericResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onGenericResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SLIDER.toString())) { // Slider final SliderResponse msg = new SliderResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onSliderResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onSliderResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.PUT_FILE.toString())) { // PutFile final PutFileResponse msg = new PutFileResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onPutFileResponse(msg); onRPCResponseReceived(msg); notifyPutFileStreamResponse(msg); } }); } else { _proxyListener.onPutFileResponse(msg); onRPCResponseReceived(msg); notifyPutFileStreamResponse(msg); } } else if (functionName.equals(FunctionID.DELETE_FILE.toString())) { // DeleteFile final DeleteFileResponse msg = new DeleteFileResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onDeleteFileResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onDeleteFileResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.LIST_FILES.toString())) { // ListFiles final ListFilesResponse msg = new ListFilesResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onListFilesResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onListFilesResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SET_APP_ICON.toString())) { // SetAppIcon final SetAppIconResponse msg = new SetAppIconResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onSetAppIconResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onSetAppIconResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SCROLLABLE_MESSAGE.toString())) { // ScrollableMessage final ScrollableMessageResponse msg = new ScrollableMessageResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onScrollableMessageResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onScrollableMessageResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.CHANGE_REGISTRATION.toString())) { // ChangeLanguageRegistration final ChangeRegistrationResponse msg = new ChangeRegistrationResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onChangeRegistrationResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onChangeRegistrationResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SET_DISPLAY_LAYOUT.toString())) { // SetDisplayLayout final SetDisplayLayoutResponse msg = new SetDisplayLayoutResponse(hash); msg.format(rpcSpecVersion,true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onSetDisplayLayoutResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onSetDisplayLayoutResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.PERFORM_AUDIO_PASS_THRU.toString())) { // PerformAudioPassThru final PerformAudioPassThruResponse msg = new PerformAudioPassThruResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onPerformAudioPassThruResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onPerformAudioPassThruResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.END_AUDIO_PASS_THRU.toString())) { // EndAudioPassThru final EndAudioPassThruResponse msg = new EndAudioPassThruResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onEndAudioPassThruResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onEndAudioPassThruResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SUBSCRIBE_VEHICLE_DATA.toString())) { // SubscribeVehicleData final SubscribeVehicleDataResponse msg = new SubscribeVehicleDataResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onSubscribeVehicleDataResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onSubscribeVehicleDataResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.UNSUBSCRIBE_VEHICLE_DATA.toString())) { // UnsubscribeVehicleData final UnsubscribeVehicleDataResponse msg = new UnsubscribeVehicleDataResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onUnsubscribeVehicleDataResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onUnsubscribeVehicleDataResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.GET_VEHICLE_DATA.toString())) { // GetVehicleData final GetVehicleDataResponse msg = new GetVehicleDataResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onGetVehicleDataResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onGetVehicleDataResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SUBSCRIBE_WAY_POINTS.toString())) { // SubscribeWayPoints final SubscribeWayPointsResponse msg = new SubscribeWayPointsResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onSubscribeWayPointsResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onSubscribeWayPointsResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.UNSUBSCRIBE_WAY_POINTS.toString())) { // UnsubscribeWayPoints final UnsubscribeWayPointsResponse msg = new UnsubscribeWayPointsResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onUnsubscribeWayPointsResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onUnsubscribeWayPointsResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.GET_WAY_POINTS.toString())) { // GetWayPoints final GetWayPointsResponse msg = new GetWayPointsResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onGetWayPointsResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onGetWayPointsResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.READ_DID.toString())) { final ReadDIDResponse msg = new ReadDIDResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onReadDIDResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onReadDIDResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.GET_DTCS.toString())) { final GetDTCsResponse msg = new GetDTCsResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onGetDTCsResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onGetDTCsResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.DIAGNOSTIC_MESSAGE.toString())) { final DiagnosticMessageResponse msg = new DiagnosticMessageResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onDiagnosticMessageResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onDiagnosticMessageResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SYSTEM_REQUEST.toString())) { final SystemRequestResponse msg = new SystemRequestResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onSystemRequestResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onSystemRequestResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SEND_LOCATION.toString())) { final SendLocationResponse msg = new SendLocationResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onSendLocationResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onSendLocationResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.DIAL_NUMBER.toString())) { final DialNumberResponse msg = new DialNumberResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onDialNumberResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onDialNumberResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SHOW_CONSTANT_TBT.toString())) { final ShowConstantTbtResponse msg = new ShowConstantTbtResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onShowConstantTbtResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onShowConstantTbtResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.ALERT_MANEUVER.toString())) { final AlertManeuverResponse msg = new AlertManeuverResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onAlertManeuverResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onAlertManeuverResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.UPDATE_TURN_LIST.toString())) { final UpdateTurnListResponse msg = new UpdateTurnListResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onUpdateTurnListResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onUpdateTurnListResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SET_INTERIOR_VEHICLE_DATA.toString())) { final SetInteriorVehicleDataResponse msg = new SetInteriorVehicleDataResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onSetInteriorVehicleDataResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onSetInteriorVehicleDataResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.GET_INTERIOR_VEHICLE_DATA.toString())) { final GetInteriorVehicleDataResponse msg = new GetInteriorVehicleDataResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onGetInteriorVehicleDataResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onGetInteriorVehicleDataResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.GET_SYSTEM_CAPABILITY.toString())) { // GetSystemCapabilityResponse final GetSystemCapabilityResponse msg = new GetSystemCapabilityResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onGetSystemCapabilityResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onGetSystemCapabilityResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.BUTTON_PRESS.toString())) { final ButtonPressResponse msg = new ButtonPressResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onButtonPressResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onButtonPressResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SEND_HAPTIC_DATA.toString())) { final SendHapticDataResponse msg = new SendHapticDataResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onSendHapticDataResponse( msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onSendHapticDataResponse( msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SET_CLOUD_APP_PROPERTIES.toString())) { final SetCloudAppPropertiesResponse msg = new SetCloudAppPropertiesResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onSetCloudAppProperties(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onSetCloudAppProperties(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.GET_CLOUD_APP_PROPERTIES.toString())) { final GetCloudAppPropertiesResponse msg = new GetCloudAppPropertiesResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onGetCloudAppProperties(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onGetCloudAppProperties(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.PUBLISH_APP_SERVICE.toString())) { final PublishAppServiceResponse msg = new PublishAppServiceResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onPublishAppServiceResponse( msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onPublishAppServiceResponse( msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.GET_APP_SERVICE_DATA.toString())) { final GetAppServiceDataResponse msg = new GetAppServiceDataResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onGetAppServiceDataResponse( msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onGetAppServiceDataResponse( msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.GET_FILE.toString())) { final GetFileResponse msg = new GetFileResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onGetFileResponse( msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onGetFileResponse( msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.PERFORM_APP_SERVICES_INTERACTION.toString())) { final PerformAppServiceInteractionResponse msg = new PerformAppServiceInteractionResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onPerformAppServiceInteractionResponse( msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onPerformAppServiceInteractionResponse( msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.CLOSE_APPLICATION.toString())) { final CloseApplicationResponse msg = new CloseApplicationResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onCloseApplicationResponse( msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onCloseApplicationResponse( msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.UNPUBLISH_APP_SERVICE.toString())) { final UnpublishAppServiceResponse msg = new UnpublishAppServiceResponse(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onUnpublishAppServiceResponse( msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onUnpublishAppServiceResponse( msg); onRPCResponseReceived(msg); } } else { if (_sdlMsgVersion != null) { DebugTool.logError("Unrecognized response Message: " + functionName + " SDL Message Version = " + _sdlMsgVersion); } else { DebugTool.logError("Unrecognized response Message: " + functionName); } } // end-if } else if (messageType.equals(RPCMessage.KEY_NOTIFICATION)) { if (functionName.equals(FunctionID.ON_HMI_STATUS.toString())) { // OnHMIStatus final OnHMIStatus msg = new OnHMIStatus(hash); //setup lockscreeninfo if (sdlSession != null) { sdlSession.getLockScreenMan().setHMILevel(msg.getHmiLevel()); } msg.setFirstRun(firstTimeFull); if (msg.getHmiLevel() == HMILevel.HMI_FULL) firstTimeFull = false; _hmiLevel = msg.getHmiLevel(); _audioStreamingState = msg.getAudioStreamingState(); msg.format(rpcSpecVersion, true); lastHmiStatus = msg; if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnHMIStatus(msg); _proxyListener.onOnLockScreenNotification(sdlSession.getLockScreenMan().getLockObj()); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnHMIStatus(msg); _proxyListener.onOnLockScreenNotification(sdlSession.getLockScreenMan().getLockObj()); onRPCNotificationReceived(msg); } } else if (functionName.equals(FunctionID.ON_COMMAND.toString())) { // OnCommand final OnCommand msg = new OnCommand(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnCommand(msg); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnCommand(msg); onRPCNotificationReceived(msg); } } else if (functionName.equals(FunctionID.ON_DRIVER_DISTRACTION.toString())) { // OnDriverDistration final OnDriverDistraction msg = new OnDriverDistraction(hash); //setup lockscreeninfo if (sdlSession != null) { DriverDistractionState drDist = msg.getState(); sdlSession.getLockScreenMan().setDriverDistStatus(drDist == DriverDistractionState.DD_ON); } msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnDriverDistraction(msg); _proxyListener.onOnLockScreenNotification(sdlSession.getLockScreenMan().getLockObj()); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnDriverDistraction(msg); _proxyListener.onOnLockScreenNotification(sdlSession.getLockScreenMan().getLockObj()); onRPCNotificationReceived(msg); } } else if (functionName.equals(FunctionID.ON_ENCODED_SYNC_P_DATA.toString())) { final OnSystemRequest msg = new OnSystemRequest(hash); Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "RPC_NAME", FunctionID.ON_SYSTEM_REQUEST.toString()); updateBroadcastIntent(sendIntent, "TYPE", RPCMessage.KEY_NOTIFICATION); // If url is null, then send notification to the app, otherwise, send to URL if (msg.getUrl() == null) { updateBroadcastIntent(sendIntent, "COMMENT1", "URL is a null value (received)"); sendBroadcastIntent(sendIntent); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnSystemRequest(msg); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnSystemRequest(msg); onRPCNotificationReceived(msg); } } else { updateBroadcastIntent(sendIntent, "COMMENT1", "Sending to cloud: " + msg.getUrl()); sendBroadcastIntent(sendIntent); Log.i("pt", "send to url"); if ( (msg.getUrl() != null) ) { Thread handleOffboardTransmissionThread = new Thread() { @Override public void run() { sendOnSystemRequestToUrl(msg); } }; handleOffboardTransmissionThread.start(); } } } else if (functionName.equals(FunctionID.ON_PERMISSIONS_CHANGE.toString())) { final OnPermissionsChange msg = new OnPermissionsChange(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnPermissionsChange(msg); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnPermissionsChange(msg); onRPCNotificationReceived(msg); } } else if (functionName.equals(FunctionID.ON_TBT_CLIENT_STATE.toString())) { // OnTBTClientState final OnTBTClientState msg = new OnTBTClientState(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnTBTClientState(msg); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnTBTClientState(msg); onRPCNotificationReceived(msg); } } else if (functionName.equals(FunctionID.ON_BUTTON_PRESS.toString())) { // OnButtonPress final OnButtonPress msg = new OnButtonPress(hash); msg.format(rpcSpecVersion, true); final OnButtonPress onButtonPressCompat = (OnButtonPress)handleButtonNotificationFormatting(msg); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnButtonPress(msg); onRPCNotificationReceived(msg); if(onButtonPressCompat != null){ onRPCNotificationReceived(onButtonPressCompat); _proxyListener.onOnButtonPress(onButtonPressCompat); } } }); } else { _proxyListener.onOnButtonPress(msg); onRPCNotificationReceived(msg); if(onButtonPressCompat != null){ onRPCNotificationReceived(onButtonPressCompat); _proxyListener.onOnButtonPress(onButtonPressCompat); } } } else if (functionName.equals(FunctionID.ON_BUTTON_EVENT.toString())) { // OnButtonEvent final OnButtonEvent msg = new OnButtonEvent(hash); msg.format(rpcSpecVersion, true); final OnButtonEvent onButtonEventCompat = (OnButtonEvent)handleButtonNotificationFormatting(msg); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnButtonEvent(msg); onRPCNotificationReceived(msg); if(onButtonEventCompat != null){ onRPCNotificationReceived(onButtonEventCompat); _proxyListener.onOnButtonEvent(onButtonEventCompat); } } }); } else { _proxyListener.onOnButtonEvent(msg); onRPCNotificationReceived(msg); if(onButtonEventCompat != null){ onRPCNotificationReceived(onButtonEventCompat); _proxyListener.onOnButtonEvent(onButtonEventCompat); } } } else if (functionName.equals(FunctionID.ON_LANGUAGE_CHANGE.toString())) { // OnLanguageChange final OnLanguageChange msg = new OnLanguageChange(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnLanguageChange(msg); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnLanguageChange(msg); onRPCNotificationReceived(msg); } } else if (functionName.equals(FunctionID.ON_HASH_CHANGE.toString())) { // OnLanguageChange final OnHashChange msg = new OnHashChange(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnHashChange(msg); onRPCNotificationReceived(msg); if (_bAppResumeEnabled) { _lastHashID = msg.getHashID(); } } }); } else { _proxyListener.onOnHashChange(msg); onRPCNotificationReceived(msg); if (_bAppResumeEnabled) { _lastHashID = msg.getHashID(); } } } else if (functionName.equals(FunctionID.ON_SYSTEM_REQUEST.toString())) { // OnSystemRequest final OnSystemRequest msg = new OnSystemRequest(hash); msg.format(rpcSpecVersion,true); RequestType requestType = msg.getRequestType(); if(msg.getUrl() != null) { if (((requestType == RequestType.PROPRIETARY) && (msg.getFileType() == FileType.JSON)) || ((requestType == RequestType.HTTP) && (msg.getFileType() == FileType.BINARY))) { Thread handleOffboardTransmissionThread = new Thread() { @Override public void run() { sendOnSystemRequestToUrl(msg); } }; handleOffboardTransmissionThread.start(); } else if (requestType == RequestType.LOCK_SCREEN_ICON_URL) { //Cache this for when the lockscreen is displayed lockScreenIconRequest = msg; } else if (requestType == RequestType.ICON_URL) { //Download the icon file and send SystemRequest RPC Thread handleOffBoardTransmissionThread = new Thread() { @Override public void run() { byte[] file = FileUtls.downloadFile(msg.getUrl()); if (file != null) { SystemRequest systemRequest = new SystemRequest(); systemRequest.setFileName(msg.getUrl()); systemRequest.setBulkData(file); systemRequest.setRequestType(RequestType.ICON_URL); try { sendRPCMessagePrivate(systemRequest); } catch (SdlException e) { e.printStackTrace(); } } else { DebugTool.logError("File was null at: " + msg.getUrl()); } } }; handleOffBoardTransmissionThread.start(); } } if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnSystemRequest(msg); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnSystemRequest(msg); onRPCNotificationReceived(msg); } } else if (functionName.equals(FunctionID.ON_AUDIO_PASS_THRU.toString())) { // OnAudioPassThru final OnAudioPassThru msg = new OnAudioPassThru(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnAudioPassThru(msg); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnAudioPassThru(msg); onRPCNotificationReceived(msg); } } else if (functionName.equals(FunctionID.ON_VEHICLE_DATA.toString())) { // OnVehicleData final OnVehicleData msg = new OnVehicleData(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnVehicleData(msg); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnVehicleData(msg); onRPCNotificationReceived(msg); } } else if (functionName.equals(FunctionID.ON_APP_INTERFACE_UNREGISTERED.toString())) { // OnAppInterfaceUnregistered _appInterfaceRegisterd = false; synchronized(APP_INTERFACE_REGISTERED_LOCK) { APP_INTERFACE_REGISTERED_LOCK.notify(); } final OnAppInterfaceUnregistered msg = new OnAppInterfaceUnregistered(hash); msg.format(rpcSpecVersion,true); Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "RPC_NAME", FunctionID.ON_APP_INTERFACE_UNREGISTERED.toString()); updateBroadcastIntent(sendIntent, "TYPE", RPCMessage.KEY_NOTIFICATION); updateBroadcastIntent(sendIntent, "DATA",serializeJSON(msg)); sendBroadcastIntent(sendIntent); if (_advancedLifecycleManagementEnabled) { // This requires the proxy to be cycled if(_mainUIHandler == null){ _mainUIHandler = new Handler(Looper.getMainLooper()); } //This needs to be ran on the main thread _mainUIHandler.post(new Runnable() { @Override public void run() { cycleProxy(SdlDisconnectedReason.convertAppInterfaceUnregisteredReason(msg.getReason())); } }); } else { if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { ((IProxyListener)_proxyListener).onOnAppInterfaceUnregistered(msg); onRPCNotificationReceived(msg); } }); } else { ((IProxyListener)_proxyListener).onOnAppInterfaceUnregistered(msg); onRPCNotificationReceived(msg); } notifyProxyClosed("OnAppInterfaceUnregistered", null, SdlDisconnectedReason.APP_INTERFACE_UNREG); } } else if (functionName.equals(FunctionID.ON_KEYBOARD_INPUT.toString())) { final OnKeyboardInput msg = new OnKeyboardInput(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnKeyboardInput(msg); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnKeyboardInput(msg); onRPCNotificationReceived(msg); } } else if (functionName.equals(FunctionID.ON_TOUCH_EVENT.toString())) { final OnTouchEvent msg = new OnTouchEvent(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnTouchEvent(msg); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnTouchEvent(msg); onRPCNotificationReceived(msg); } } else if (functionName.equals(FunctionID.ON_WAY_POINT_CHANGE.toString())) { final OnWayPointChange msg = new OnWayPointChange(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnWayPointChange(msg); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnWayPointChange(msg); onRPCNotificationReceived(msg); } } else if (functionName.equals(FunctionID.ON_INTERIOR_VEHICLE_DATA.toString())) { final OnInteriorVehicleData msg = new OnInteriorVehicleData(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnInteriorVehicleData(msg); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnInteriorVehicleData(msg); onRPCNotificationReceived(msg); } } else if (functionName.equals(FunctionID.ON_RC_STATUS.toString())) { final OnRCStatus msg = new OnRCStatus(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnRCStatus(msg); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnRCStatus(msg); onRPCNotificationReceived(msg); } } else if (functionName.equals(FunctionID.ON_APP_SERVICE_DATA.toString())) { final OnAppServiceData msg = new OnAppServiceData(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnAppServiceData(msg); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnAppServiceData(msg); onRPCNotificationReceived(msg); } } else if (functionName.equals(FunctionID.ON_SYSTEM_CAPABILITY_UPDATED.toString())) { final OnSystemCapabilityUpdated msg = new OnSystemCapabilityUpdated(hash); msg.format(rpcSpecVersion, true); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnSystemCapabilityUpdated(msg); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnSystemCapabilityUpdated(msg); onRPCNotificationReceived(msg); } } else { if (_sdlMsgVersion != null) { DebugTool.logInfo("Unrecognized notification Message: " + functionName + " connected to SDL using message version: " + _sdlMsgVersion.getMajorVersion() + "." + _sdlMsgVersion.getMinorVersion()); } else { DebugTool.logInfo("Unrecognized notification Message: " + functionName); } } // end-if } // end-if notification SdlTrace.logProxyEvent("Proxy received RPC Message: " + functionName, SDL_LIB_TRACE_KEY); } //FIXME /** * Temporary method to bridge the new PLAY_PAUSE and OKAY button functionality with the old * OK button name. This should be removed during the next major release * @param notification */ private RPCNotification handleButtonNotificationFormatting(RPCNotification notification){ if(FunctionID.ON_BUTTON_EVENT.toString().equals(notification.getFunctionName()) || FunctionID.ON_BUTTON_PRESS.toString().equals(notification.getFunctionName())){ ButtonName buttonName = (ButtonName)notification.getObject(ButtonName.class, OnButtonEvent.KEY_BUTTON_NAME); ButtonName compatBtnName = null; if(rpcSpecVersion != null && rpcSpecVersion.getMajor() >= 5){ if(ButtonName.PLAY_PAUSE.equals(buttonName)){ compatBtnName = ButtonName.OK; } }else{ // rpc spec version is either null or less than 5 if(ButtonName.OK.equals(buttonName)){ compatBtnName = ButtonName.PLAY_PAUSE; } } try { if (compatBtnName != null) { //There is a button name that needs to be swapped out RPCNotification notification2; //The following is done because there is currently no way to make a deep copy //of an RPC. Since this code will be removed, it's ugliness is borderline acceptable. if (notification instanceof OnButtonEvent) { OnButtonEvent onButtonEvent = new OnButtonEvent(); onButtonEvent.setButtonEventMode(((OnButtonEvent) notification).getButtonEventMode()); onButtonEvent.setCustomButtonID(((OnButtonEvent) notification).getCustomButtonID()); notification2 = onButtonEvent; } else if (notification instanceof OnButtonPress) { OnButtonPress onButtonPress = new OnButtonPress(); onButtonPress.setButtonPressMode(((OnButtonPress) notification).getButtonPressMode()); onButtonPress.setCustomButtonName(((OnButtonPress) notification).getCustomButtonName()); notification2 = onButtonPress; } else { return null; } notification2.setParameters(OnButtonEvent.KEY_BUTTON_NAME, compatBtnName); return notification2; } }catch (Exception e){ //Should never get here } } return null; } /** * Get SDL Message Version * @return SdlMsgVersion * @throws SdlException */ public SdlMsgVersion getSdlMsgVersion() throws SdlException{ return _sdlMsgVersion; } /** * Takes a list of RPCMessages and sends it to SDL in a synchronous fashion. Responses are captured through callback on OnMultipleRequestListener. * For sending requests asynchronously, use sendRequests <br> * * <strong>NOTE: This will override any listeners on individual RPCs</strong> * * @param rpcs is the list of RPCMessages being sent * @param listener listener for updates and completions * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void sendSequentialRequests(final List<? extends RPCMessage> rpcs, final OnMultipleRequestListener listener) throws SdlException { if (_proxyDisposed) { throw new SdlException("This object has been disposed, it is no long capable of executing methods.", SdlExceptionCause.SDL_PROXY_DISPOSED); } SdlTrace.logProxyEvent("Application called sendSequentialRequests", SDL_LIB_TRACE_KEY); synchronized(CONNECTION_REFERENCE_LOCK) { if (!getIsConnected()) { SdlTrace.logProxyEvent("Application attempted to call sendSequentialRequests without a connected transport.", SDL_LIB_TRACE_KEY); throw new SdlException("There is no valid connection to SDL. sendSequentialRequests cannot be called until SDL has been connected.", SdlExceptionCause.SDL_UNAVAILABLE); } } if (rpcs == null){ //Log error here throw new SdlException("You must send some RPCs", SdlExceptionCause.INVALID_ARGUMENT); } // Break out of recursion, we have finished the requests if (rpcs.size() == 0) { if(listener != null){ listener.onFinished(); } return; } RPCMessage rpc = rpcs.remove(0); // Request Specifics if (rpc.getMessageType().equals(RPCMessage.KEY_REQUEST)) { RPCRequest request = (RPCRequest) rpc; request.setCorrelationID(CorrelationIdGenerator.generateId()); final OnRPCResponseListener devOnRPCResponseListener = request.getOnRPCResponseListener(); request.setOnRPCResponseListener(new OnRPCResponseListener() { @Override public void onResponse(int correlationId, RPCResponse response) { if (devOnRPCResponseListener != null){ devOnRPCResponseListener.onResponse(correlationId, response); } if (listener != null) { listener.onResponse(correlationId, response); listener.onUpdate(rpcs.size()); } try { // recurse after onResponse sendSequentialRequests(rpcs, listener); } catch (SdlException e) { e.printStackTrace(); if (listener != null) { listener.onError(correlationId, Result.GENERIC_ERROR, e.toString()); } } } @Override public void onError(int correlationId, Result resultCode, String info) { if (devOnRPCResponseListener != null){ devOnRPCResponseListener.onError(correlationId, resultCode, info); } if (listener != null) { listener.onError(correlationId, resultCode, info); listener.onUpdate(rpcs.size()); } try { // recurse after onError sendSequentialRequests(rpcs, listener); } catch (SdlException e) { e.printStackTrace(); if (listener != null) { listener.onError(correlationId, Result.GENERIC_ERROR, e.toString()); } } } }); sendRPCMessagePrivate(request); } else { // Notifications and Responses sendRPCMessagePrivate(rpc); if (listener != null) { listener.onUpdate(rpcs.size()); } // recurse after sending a notification or response as there is no response. try { sendSequentialRequests(rpcs, listener); } catch (SdlException e) { e.printStackTrace(); if (listener != null) { listener.onError(0, Result.GENERIC_ERROR, e.toString()); } } } } /** * Takes a list of RPCMessages and sends it to SDL. Responses are captured through callback on OnMultipleRequestListener. * For sending requests synchronously, use sendSequentialRequests <br> * * <strong>NOTE: This will override any listeners on individual RPCs</strong> * * @param rpcs is the list of RPCMessages being sent * @param listener listener for updates and completions * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void sendRequests(List<? extends RPCMessage> rpcs, final OnMultipleRequestListener listener) throws SdlException { if (_proxyDisposed) { throw new SdlException("This object has been disposed, it is no long capable of executing methods.", SdlExceptionCause.SDL_PROXY_DISPOSED); } SdlTrace.logProxyEvent("Application called sendRequests", SDL_LIB_TRACE_KEY); synchronized(CONNECTION_REFERENCE_LOCK) { if (!getIsConnected()) { SdlTrace.logProxyEvent("Application attempted to call sendRequests without a connected transport.", SDL_LIB_TRACE_KEY); throw new SdlException("There is no valid connection to SDL. sendRequests cannot be called until SDL has been connected.", SdlExceptionCause.SDL_UNAVAILABLE); } } if (rpcs == null){ //Log error here throw new SdlException("You must send some RPCs, the array is null", SdlExceptionCause.INVALID_ARGUMENT); } int arraySize = rpcs.size(); if (arraySize == 0) { throw new SdlException("You must send some RPCs, the array is empty", SdlExceptionCause.INVALID_ARGUMENT); } for (int i = 0; i < arraySize; i++) { RPCMessage rpc = rpcs.get(i); // Request Specifics if (rpc.getMessageType().equals(RPCMessage.KEY_REQUEST)) { RPCRequest request = (RPCRequest) rpc; final OnRPCResponseListener devOnRPCResponseListener = request.getOnRPCResponseListener(); request.setCorrelationID(CorrelationIdGenerator.generateId()); if (listener != null) { listener.addCorrelationId(request.getCorrelationID()); request.setOnRPCResponseListener(new OnRPCResponseListener() { @Override public void onResponse(int correlationId, RPCResponse response) { if (devOnRPCResponseListener != null){ devOnRPCResponseListener.onResponse(correlationId, response); } if (listener.getSingleRpcResponseListener() != null) { listener.getSingleRpcResponseListener().onResponse(correlationId, response); } } @Override public void onError(int correlationId, Result resultCode, String info) { super.onError(correlationId, resultCode, info); if (devOnRPCResponseListener != null){ devOnRPCResponseListener.onError(correlationId, resultCode, info); } if (listener.getSingleRpcResponseListener() != null) { listener.getSingleRpcResponseListener().onError(correlationId, resultCode, info); } } }); } sendRPCMessagePrivate(request); }else { // Notifications and Responses sendRPCMessagePrivate(rpc); if (listener != null){ listener.onUpdate(rpcs.size()); if (rpcs.size() == 0){ listener.onFinished(); } } } } } public void sendRPC(RPCMessage message) throws SdlException { if (_proxyDisposed) { throw new SdlException("This object has been disposed, it is no long capable of executing methods.", SdlExceptionCause.SDL_PROXY_DISPOSED); } // Test if request is null if (message == null) { SdlTrace.logProxyEvent("Application called sendRPCRequest method with a null RPCRequest.", SDL_LIB_TRACE_KEY); throw new IllegalArgumentException("sendRPCRequest cannot be called with a null request."); } SdlTrace.logProxyEvent("Application called sendRPCRequest method for RPCRequest: ." + message.getFunctionName(), SDL_LIB_TRACE_KEY); // Test if SdlConnection is null synchronized(CONNECTION_REFERENCE_LOCK) { if (!getIsConnected()) { SdlTrace.logProxyEvent("Application attempted to send and RPCRequest without a connected transport.", SDL_LIB_TRACE_KEY); throw new SdlException("There is no valid connection to SDL. sendRPCRequest cannot be called until SDL has been connected.", SdlExceptionCause.SDL_UNAVAILABLE); } } if (message.getMessageType().equals(RPCMessage.KEY_REQUEST)) { RPCRequest request = (RPCRequest) message; if (isCorrelationIDProtected(request.getCorrelationID())) { SdlTrace.logProxyEvent("Application attempted to use the reserved correlation ID, " + request.getCorrelationID(), SDL_LIB_TRACE_KEY); throw new SdlException("Invalid correlation ID. The correlation ID, " + request.getCorrelationID() + " , is a reserved correlation ID.", SdlExceptionCause.RESERVED_CORRELATION_ID); } } // Throw exception if RPCRequest is sent when SDL is unavailable if (!_appInterfaceRegisterd && !message.getFunctionName().equals(FunctionID.REGISTER_APP_INTERFACE.toString())) { SdlTrace.logProxyEvent("Application attempted to send an RPCRequest (non-registerAppInterface), before the interface was registerd.", SDL_LIB_TRACE_KEY); throw new SdlException("SDL is currently unavailable. RPC Requests cannot be sent.", SdlExceptionCause.SDL_UNAVAILABLE); } if (_advancedLifecycleManagementEnabled) { if (message.getFunctionName().equals(FunctionID.REGISTER_APP_INTERFACE.toString()) || message.getFunctionName().equals(FunctionID.UNREGISTER_APP_INTERFACE.toString())) { SdlTrace.logProxyEvent("Application attempted to send a RegisterAppInterface or UnregisterAppInterface while using ALM.", SDL_LIB_TRACE_KEY); throw new SdlException("The RPCRequest, " + message.getFunctionName() + ", is un-allowed using the Advanced Lifecycle Management Model.", SdlExceptionCause.INCORRECT_LIFECYCLE_MODEL); } } sendRPCMessagePrivate(message); } /** * Takes an RPCRequest and sends it to SDL. Responses are captured through callback on IProxyListener. * * @param request is the RPCRequest being sent * @throws SdlException if an unrecoverable error is encountered * @deprecated - use sendRPC instead */ @Deprecated public void sendRPCRequest(RPCRequest request) throws SdlException { sendRPC(request); } protected void notifyProxyClosed(final String info, final Exception e, final SdlDisconnectedReason reason) { SdlTrace.logProxyEvent("NotifyProxyClose", SDL_LIB_TRACE_KEY); Log.d(TAG, "notifyProxyClosed: " + info); OnProxyClosed message = new OnProxyClosed(info, e, reason); queueInternalMessage(message); } private void passErrorToProxyListener(final String info, final Exception e) { OnError message = new OnError(info, e); queueInternalMessage(message); } private void startRPCProtocolSession() { // Set Proxy Lifecyclek Available if (_advancedLifecycleManagementEnabled) { try { registerAppInterfacePrivate( _sdlMsgVersionRequest, _applicationName, _ttsName, _ngnMediaScreenAppName, _vrSynonyms, _isMediaApp, _sdlLanguageDesired, _hmiDisplayLanguageDesired, _appType, _appID, _dayColorScheme, _nightColorScheme, REGISTER_APP_INTERFACE_CORRELATION_ID); } catch (Exception e) { notifyProxyClosed("Failed to register application interface with SDL. Check parameter values given to SdlProxy constructor.", e, SdlDisconnectedReason.SDL_REGISTRATION_ERROR); } } else { InternalProxyMessage message = new InternalProxyMessage(InternalProxyMessage.OnProxyOpened); queueInternalMessage(message); } } // Queue internal callback message private void queueInternalMessage(InternalProxyMessage message) { synchronized(INTERNAL_MESSAGE_QUEUE_THREAD_LOCK) { if (_internalProxyMessageDispatcher != null) { _internalProxyMessageDispatcher.queueMessage(message); } } } // Queue incoming ProtocolMessage private void queueIncomingMessage(ProtocolMessage message) { synchronized(INCOMING_MESSAGE_QUEUE_THREAD_LOCK) { if (_incomingProxyMessageDispatcher != null) { _incomingProxyMessageDispatcher.queueMessage(message); } } } private FileInputStream getFileInputStream(String sLocalFile) { FileInputStream is = null; try { is = new FileInputStream(sLocalFile); } catch (IOException e1) { e1.printStackTrace(); } return is; } private Long getFileInputStreamSize(FileInputStream is) { Long lSize = null; try { lSize = is.getChannel().size(); } catch (IOException e) { e.printStackTrace(); } return lSize; } private void closeFileInputStream(FileInputStream is) { try { is.close(); } catch (Exception e) { e.printStackTrace(); } } @SuppressWarnings("unchecked") private RPCStreamController startRPCStream(String sLocalFile, PutFile request, SessionType sType, byte rpcSessionID, Version protocolVersion) { if (sdlSession == null) return null; FileInputStream is = getFileInputStream(sLocalFile); if (is == null) return null; Long lSize = getFileInputStreamSize(is); if (lSize == null) { closeFileInputStream(is); return null; } try { StreamRPCPacketizer rpcPacketizer = new StreamRPCPacketizer((SdlProxyBase<IProxyListenerBase>) this, sdlSession, is, request, sType, rpcSessionID, protocolVersion, rpcSpecVersion, lSize, sdlSession); rpcPacketizer.start(); return new RPCStreamController(rpcPacketizer, request.getCorrelationID()); } catch (Exception e) { Log.e("SyncConnection", "Unable to start streaming:" + e.toString()); return null; } } @SuppressWarnings({"unchecked", "UnusedReturnValue"}) private RPCStreamController startRPCStream(InputStream is, PutFile request, SessionType sType, byte rpcSessionID, Version protocolVersion) { if (sdlSession == null) return null; Long lSize = request.getLength(); if (lSize == null) { return null; } try { StreamRPCPacketizer rpcPacketizer = new StreamRPCPacketizer((SdlProxyBase<IProxyListenerBase>) this, sdlSession, is, request, sType, rpcSessionID, protocolVersion, rpcSpecVersion, lSize, sdlSession); rpcPacketizer.start(); return new RPCStreamController(rpcPacketizer, request.getCorrelationID()); } catch (Exception e) { Log.e("SyncConnection", "Unable to start streaming:" + e.toString()); return null; } } private RPCStreamController startPutFileStream(String sPath, PutFile msg) { if (sdlSession == null) return null; return startRPCStream(sPath, msg, SessionType.RPC, sdlSession.getSessionId(), protocolVersion); } private RPCStreamController startPutFileStream(InputStream is, PutFile msg) { if (sdlSession == null) return null; if (is == null) return null; return startRPCStream(is, msg, SessionType.RPC, sdlSession.getSessionId(), protocolVersion); } @SuppressWarnings("UnusedReturnValue") public boolean startRPCStream(InputStream is, RPCRequest msg) { if (sdlSession == null) return false; sdlSession.startRPCStream(is, msg, SessionType.RPC, sdlSession.getSessionId(), (byte)getProtocolVersion().getMajor()); return true; } public OutputStream startRPCStream(RPCRequest msg) { if (sdlSession == null) return null; return sdlSession.startRPCStream(msg, SessionType.RPC, sdlSession.getSessionId(), (byte)getProtocolVersion().getMajor()); } public void endRPCStream() { if (sdlSession == null) return; sdlSession.stopRPCStream(); } private class CallableMethod implements Callable<Void> { private final long waitTime; public CallableMethod(int timeInMillis){ this.waitTime=timeInMillis; } @Override public Void call() { try { Thread.sleep(waitTime); } catch (InterruptedException e) { e.printStackTrace(); } return null; } } public FutureTask<Void> createFutureTask(CallableMethod callMethod){ return new FutureTask<Void>(callMethod); } public ScheduledExecutorService createScheduler(){ return Executors.newSingleThreadScheduledExecutor(); } @SuppressWarnings("unused") public void startService(SessionType serviceType, boolean isEncrypted){ sdlSession.startService(serviceType, sdlSession.getSessionId(), isEncrypted); } @SuppressWarnings("unused") public void endService(SessionType serviceType){ sdlSession.endService(serviceType, sdlSession.getSessionId()); } /** * @deprecated *Opens the video service (serviceType 11) and subsequently streams raw H264 video from an InputStream provided by the app *@return true if service is opened successfully and stream is started, return false otherwise * @see #startRemoteDisplayStream(Context, Class, VideoStreamingParameters, boolean) startRemoteDisplayStream * @see #startVideoStream(boolean, VideoStreamingParameters) startVideoStream * @see #createOpenGLInputSurface(int, int, int, int, int, boolean) createOpenGLInputSurface */ @SuppressWarnings("unused") @Deprecated public boolean startH264(InputStream is, boolean isEncrypted) { if (sdlSession == null) return false; navServiceStartResponseReceived = false; navServiceStartResponse = false; navServiceStartRejectedParams = null; // When startH264() API is used, we will not send video format / width / height information // with StartService. (Reasons: InputStream does not provide timestamp information so RTP // cannot be used. startH264() does not provide with/height information.) VideoStreamingParameters emptyParam = new VideoStreamingParameters(); emptyParam.setResolution(null); emptyParam.setFormat(null); sdlSession.setDesiredVideoParams(emptyParam); sdlSession.startService(SessionType.NAV, sdlSession.getSessionId(), isEncrypted); FutureTask<Void> fTask = createFutureTask(new CallableMethod(RESPONSE_WAIT_TIME)); ScheduledExecutorService scheduler = createScheduler(); scheduler.execute(fTask); //noinspection StatementWithEmptyBody while (!navServiceStartResponseReceived && !fTask.isDone()); scheduler.shutdown(); if (navServiceStartResponse) { try { sdlSession.startStream(is, SessionType.NAV, sdlSession.getSessionId()); return true; } catch (Exception e) { return false; } } else { return false; } } /** * @deprecated *Opens the video service (serviceType 11) and subsequently provides an OutputStream to the app to use for a raw H264 video stream *@return OutputStream if service is opened successfully and stream is started, return null otherwise * @see #startRemoteDisplayStream(Context, Class, VideoStreamingParameters, boolean) startRemoteDisplayStream * @see #startVideoStream(boolean, VideoStreamingParameters) startVideoStream * @see #createOpenGLInputSurface(int, int, int, int, int, boolean) createOpenGLInputSurface */ @SuppressWarnings("unused") @Deprecated public OutputStream startH264(boolean isEncrypted) { if (sdlSession == null) return null; navServiceStartResponseReceived = false; navServiceStartResponse = false; navServiceStartRejectedParams = null; // When startH264() API is used, we will not send video format / width / height information // with StartService. (Reasons: OutputStream does not provide timestamp information so RTP // cannot be used. startH264() does not provide with/height information.) VideoStreamingParameters emptyParam = new VideoStreamingParameters(); emptyParam.setResolution(null); emptyParam.setFormat(null); sdlSession.setDesiredVideoParams(emptyParam); sdlSession.startService(SessionType.NAV, sdlSession.getSessionId(), isEncrypted); FutureTask<Void> fTask = createFutureTask(new CallableMethod(RESPONSE_WAIT_TIME)); ScheduledExecutorService scheduler = createScheduler(); scheduler.execute(fTask); //noinspection StatementWithEmptyBody while (!navServiceStartResponseReceived && !fTask.isDone()); scheduler.shutdown(); if (navServiceStartResponse) { try { return sdlSession.startStream(SessionType.NAV, sdlSession.getSessionId()); } catch (Exception e) { return null; } } else { return null; } } /** *Closes the opened video service (serviceType 11) *@return true if the video service is closed successfully, return false otherwise */ @SuppressWarnings("unused") @Deprecated public boolean endH264() { return endVideoStream(); } /** *Pauses the stream for the opened audio service (serviceType 10) *@return true if the audio service stream is paused successfully, return false otherwise */ @SuppressWarnings("unused") @Deprecated public boolean pausePCM() { return pauseAudioStream(); } /** *Pauses the stream for the opened video service (serviceType 11) *@return true if the video service stream is paused successfully, return false otherwise */ @SuppressWarnings("unused") @Deprecated public boolean pauseH264() { return pauseVideoStream(); } /** *Resumes the stream for the opened audio service (serviceType 10) *@return true if the audio service stream is resumed successfully, return false otherwise */ @SuppressWarnings("unused") @Deprecated public boolean resumePCM() { return resumeAudioStream(); } /** *Resumes the stream for the opened video service (serviceType 11) *@return true if the video service is resumed successfully, return false otherwise */ @SuppressWarnings("unused") @Deprecated public boolean resumeH264() { return resumeVideoStream(); } /** *Opens the audio service (serviceType 10) and subsequently streams raw PCM audio from an InputStream provided by the app *@return true if service is opened successfully and stream is started, return false otherwise */ @SuppressWarnings("unused") @Deprecated public boolean startPCM(InputStream is, boolean isEncrypted) { if (sdlSession == null) return false; pcmServiceStartResponseReceived = false; pcmServiceStartResponse = false; sdlSession.startService(SessionType.PCM, sdlSession.getSessionId(), isEncrypted); FutureTask<Void> fTask = createFutureTask(new CallableMethod(RESPONSE_WAIT_TIME)); ScheduledExecutorService scheduler = createScheduler(); scheduler.execute(fTask); //noinspection StatementWithEmptyBody while (!pcmServiceStartResponseReceived && !fTask.isDone()); scheduler.shutdown(); if (pcmServiceStartResponse) { try { sdlSession.startStream(is, SessionType.PCM, sdlSession.getSessionId()); return true; } catch (Exception e) { return false; } } else { return false; } } /** *Opens the audio service (serviceType 10) and subsequently provides an OutputStream to the app *@return OutputStream if service is opened successfully and stream is started, return null otherwise */ @SuppressWarnings("unused") @Deprecated public OutputStream startPCM(boolean isEncrypted) { if (sdlSession == null) return null; pcmServiceStartResponseReceived = false; pcmServiceStartResponse = false; sdlSession.startService(SessionType.PCM, sdlSession.getSessionId(), isEncrypted); FutureTask<Void> fTask = createFutureTask(new CallableMethod(RESPONSE_WAIT_TIME)); ScheduledExecutorService scheduler = createScheduler(); scheduler.execute(fTask); //noinspection StatementWithEmptyBody while (!pcmServiceStartResponseReceived && !fTask.isDone()); scheduler.shutdown(); if (pcmServiceStartResponse) { try { return sdlSession.startStream(SessionType.PCM, sdlSession.getSessionId()); } catch (Exception e) { return null; } } else { if (pcmServiceStartRejectedParams != null) { StringBuilder builder = new StringBuilder(); for (String paramName : pcmServiceStartRejectedParams) { if (builder.length() > 0) { builder.append(", "); } builder.append(paramName); } DebugTool.logWarning("StartService for nav failed. Rejected params: " + builder.toString()); } else { DebugTool.logWarning("StartService for nav failed (rejected params not supplied)"); } return null; } } /** *Closes the opened audio service (serviceType 10) *@return true if the audio service is closed successfully, return false otherwise */ @SuppressWarnings("unused") @Deprecated public boolean endPCM() { return endAudioStream(); } /** * Opens a video service (service type 11) and subsequently provides an IVideoStreamListener * to the app to send video data. The supplied VideoStreamingParameters will be set as desired parameters * that will be used to negotiate * * <br><br><b>NOTE: IF USING SECONDARY TRANSPORTS, THE VIDEO SERVICE MUST BE STARTED BEFORE CALLING THIS * THIS METHOD. USE A `ISdlServiceListener` TO BE NOTIFIED THAT IT STARTS THEN CALL THIS METHOD TO * START STREAMING. ADD A LISTENER USE {@link #addServiceListener(SessionType, ISdlServiceListener)}.</b> * * @param isEncrypted Specify true if packets on this service have to be encrypted * @param parameters Video streaming parameters including: codec which will be used for streaming (currently, only * VideoStreamingCodec.H264 is accepted), height and width of the video in pixels. * * @return IVideoStreamListener interface if service is opened successfully and streaming is * started, null otherwise * * @see ISdlServiceListener */ @SuppressWarnings("unused") public IVideoStreamListener startVideoStream(boolean isEncrypted, VideoStreamingParameters parameters) { if (sdlSession == null) { DebugTool.logWarning("SdlSession is not created yet."); return null; } if (!sdlSession.getIsConnected()) { DebugTool.logWarning("Connection is not available."); return null; } sdlSession.setDesiredVideoParams(parameters); VideoStreamingParameters acceptedParams = tryStartVideoStream(isEncrypted, parameters); if (acceptedParams != null) { return sdlSession.startVideoStream(); } else { return null; } } /** *Closes the opened video service (serviceType 11) *@return true if the video service is closed successfully, return false otherwise */ @SuppressWarnings("unused") public boolean endVideoStream() { if (sdlSession == null){ return false; } navServiceEndResponseReceived = false; navServiceEndResponse = false; sdlSession.stopVideoStream(); FutureTask<Void> fTask = createFutureTask(new CallableMethod(RESPONSE_WAIT_TIME)); ScheduledExecutorService scheduler = createScheduler(); scheduler.execute(fTask); //noinspection StatementWithEmptyBody while (!navServiceEndResponseReceived && !fTask.isDone()); scheduler.shutdown(); return navServiceEndResponse; } /** *Pauses the stream for the opened video service (serviceType 11) *@return true if the video service stream is paused successfully, return false otherwise */ @SuppressWarnings("unused") public boolean pauseVideoStream() { return sdlSession != null && sdlSession.pauseVideoStream(); } /** *Resumes the stream for the opened video service (serviceType 11) *@return true if the video service is resumed successfully, return false otherwise */ @SuppressWarnings("unused") public boolean resumeVideoStream() { return sdlSession != null && sdlSession.resumeVideoStream(); } /** * Opens the video service (serviceType 11) and creates a Surface (used for streaming video) with input parameters provided by the app * @param frameRate - specified rate of frames to utilize for creation of Surface * @param iFrameInterval - specified interval to utilize for creation of Surface * @param width - specified width to utilize for creation of Surface * @param height - specified height to utilize for creation of Surface * @param bitrate - specified bitrate to utilize for creation of Surface *@return Surface if service is opened successfully and stream is started, return null otherwise */ @SuppressWarnings("unused") public Surface createOpenGLInputSurface(int frameRate, int iFrameInterval, int width, int height, int bitrate, boolean isEncrypted) { if (sdlSession == null || !sdlSession.getIsConnected()){ return null; } VideoStreamingParameters desired = new VideoStreamingParameters(); desired.setFrameRate(frameRate); desired.setInterval(iFrameInterval); ImageResolution resolution = new ImageResolution(); resolution.setResolutionWidth(width); resolution.setResolutionHeight(height); desired.setResolution(resolution); desired.setBitrate(bitrate); VideoStreamingParameters acceptedParams = tryStartVideoStream(isEncrypted, desired); if (acceptedParams != null) { return sdlSession.createOpenGLInputSurface(frameRate, iFrameInterval, width, height, bitrate, SessionType.NAV, sdlSession.getSessionId()); } else { return null; } } /** * Starts streaming a remote display to the module if there is a connected session. This method of streaming requires the device to be on API level 19 or higher * @param context a context that can be used to create the remote display * @param remoteDisplay class object of the remote display. This class will be used to create an instance of the remote display and will be projected to the module * @param parameters streaming parameters to be used when streaming. If null is sent in, the default/optimized options will be used. * If you are unsure about what parameters to be used it is best to just send null and let the system determine what * works best for the currently connected module. * * @param encrypted a flag of if the stream should be encrypted. Only set if you have a supplied encryption library that the module can understand. */ @TargetApi(19) public void startRemoteDisplayStream(Context context, final Class<? extends SdlRemoteDisplay> remoteDisplay, final VideoStreamingParameters parameters, final boolean encrypted){ if(protocolVersion!= null && protocolVersion.getMajor() >= 5 && !_systemCapabilityManager.isCapabilitySupported(SystemCapabilityType.VIDEO_STREAMING)){ Log.e(TAG, "Video streaming not supported on this module"); return; } //Create streaming manager if(manager == null){ manager = new VideoStreamingManager(context,this._internalInterface); } if(parameters == null){ if(protocolVersion!= null && protocolVersion.getMajor() >= 5) { _systemCapabilityManager.getCapability(SystemCapabilityType.VIDEO_STREAMING, new OnSystemCapabilityListener() { @Override public void onCapabilityRetrieved(Object capability) { VideoStreamingParameters params = new VideoStreamingParameters(); params.update((VideoStreamingCapability)capability); //Streaming parameters are ready time to stream sdlSession.setDesiredVideoParams(params); manager.startVideoStreaming(remoteDisplay, params, encrypted); } @Override public void onError(String info) { Log.e(TAG, "Error retrieving video streaming capability: " + info); } }); }else{ //We just use default video streaming params VideoStreamingParameters params = new VideoStreamingParameters(); DisplayCapabilities dispCap = (DisplayCapabilities)_systemCapabilityManager.getCapability(SystemCapabilityType.DISPLAY); if(dispCap !=null){ params.setResolution(dispCap.getScreenParams().getImageResolution()); } sdlSession.setDesiredVideoParams(params); manager.startVideoStreaming(remoteDisplay,params, encrypted); } }else{ sdlSession.setDesiredVideoParams(parameters); manager.startVideoStreaming(remoteDisplay,parameters, encrypted); } } /** * Stops the remote display stream if one has been started */ public void stopRemoteDisplayStream(){ if(manager!=null){ manager.dispose(); } manager = null; } /** * Try to open a video service by using the video streaming parameters supplied. * * Only information from codecs, width and height are used during video format negotiation. * * @param isEncrypted Specify true if packets on this service have to be encrypted * @param parameters VideoStreamingParameters that are desired. Does not guarantee this is what will be accepted. * * @return If the service is opened successfully, an instance of VideoStreamingParams is * returned which contains accepted video format. If the service is opened with legacy * mode (i.e. without any negotiation) then an instance of VideoStreamingParams is * returned. If the service was not opened then null is returned. */ @SuppressWarnings("unused") private VideoStreamingParameters tryStartVideoStream(boolean isEncrypted, VideoStreamingParameters parameters) { if (sdlSession == null) { DebugTool.logWarning("SdlSession is not created yet."); return null; } if(protocolVersion!= null && protocolVersion.getMajor() >= 5 && !_systemCapabilityManager.isCapabilitySupported(SystemCapabilityType.VIDEO_STREAMING)){ DebugTool.logWarning("Module doesn't support video streaming."); return null; } if (parameters == null) { DebugTool.logWarning("Video parameters were not supplied."); return null; } if(!navServiceStartResponseReceived || !navServiceStartResponse //If we haven't started the service before || (navServiceStartResponse && isEncrypted && !sdlSession.isServiceProtected(SessionType.NAV))) { //Or the service has been started but we'd like to start an encrypted one sdlSession.setDesiredVideoParams(parameters); navServiceStartResponseReceived = false; navServiceStartResponse = false; navServiceStartRejectedParams = null; sdlSession.startService(SessionType.NAV, sdlSession.getSessionId(), isEncrypted); FutureTask<Void> fTask = createFutureTask(new CallableMethod(RESPONSE_WAIT_TIME)); ScheduledExecutorService scheduler = createScheduler(); scheduler.execute(fTask); //noinspection StatementWithEmptyBody while (!navServiceStartResponseReceived && !fTask.isDone()) ; scheduler.shutdown(); } if (navServiceStartResponse) { if(protocolVersion!= null && protocolVersion.getMajor() < 5){ //Versions 1-4 do not support streaming parameter negotiations sdlSession.setAcceptedVideoParams(parameters); } return sdlSession.getAcceptedVideoParams(); } if (navServiceStartRejectedParams != null) { StringBuilder builder = new StringBuilder(); for (String paramName : navServiceStartRejectedParams) { if (builder.length() > 0) { builder.append(", "); } builder.append(paramName); } DebugTool.logWarning("StartService for nav failed. Rejected params: " + builder.toString()); } else { DebugTool.logWarning("StartService for nav failed (rejected params not supplied)"); } return null; } /** *Starts the MediaCodec encoder utilized in conjunction with the Surface returned via the createOpenGLInputSurface method */ @SuppressWarnings("unused") public void startEncoder () { if (sdlSession == null || !sdlSession.getIsConnected()) return; sdlSession.startEncoder(); } /** *Releases the MediaCodec encoder utilized in conjunction with the Surface returned via the createOpenGLInputSurface method */ @SuppressWarnings("unused") public void releaseEncoder() { if (sdlSession == null || !sdlSession.getIsConnected()) return; sdlSession.releaseEncoder(); } /** *Releases the MediaCodec encoder utilized in conjunction with the Surface returned via the createOpenGLInputSurface method */ @SuppressWarnings("unused") public void drainEncoder(boolean endOfStream) { if (sdlSession == null || !sdlSession.getIsConnected()) return; sdlSession.drainEncoder(endOfStream); } /** * Opens a audio service (service type 10) and subsequently provides an IAudioStreamListener * to the app to send audio data. * * Currently information passed by "params" are ignored, since Audio Streaming feature lacks * capability negotiation mechanism. App should configure audio stream data to align with * head unit's capability by checking (upcoming) pcmCapabilities. The default format is in * 16kHz and 16 bits. * * @param isEncrypted Specify true if packets on this service have to be encrypted * @param codec Audio codec which will be used for streaming. Currently, only * AudioStreamingCodec.LPCM is accepted. * @param params (Reserved for future use) Additional configuration information for each * codec. If "codec" is AudioStreamingCodec.LPCM, "params" must be an * instance of LPCMParams class. * * @return IAudioStreamListener interface if service is opened successfully and streaming is * started, null otherwise */ @SuppressWarnings("unused") public IAudioStreamListener startAudioStream(boolean isEncrypted, AudioStreamingCodec codec, AudioStreamingParams params) { if (sdlSession == null) { DebugTool.logWarning("SdlSession is not created yet."); return null; } if (!sdlSession.getIsConnected()) { DebugTool.logWarning("Connection is not available."); return null; } if (codec != AudioStreamingCodec.LPCM) { DebugTool.logWarning("Audio codec " + codec + " is not supported."); return null; } pcmServiceStartResponseReceived = false; pcmServiceStartResponse = false; sdlSession.startService(SessionType.PCM, sdlSession.getSessionId(), isEncrypted); FutureTask<Void> fTask = createFutureTask(new CallableMethod(RESPONSE_WAIT_TIME)); ScheduledExecutorService scheduler = createScheduler(); scheduler.execute(fTask); //noinspection StatementWithEmptyBody while (!pcmServiceStartResponseReceived && !fTask.isDone()); scheduler.shutdown(); if (pcmServiceStartResponse) { DebugTool.logInfo("StartService for audio succeeded"); return sdlSession.startAudioStream(); } else { if (pcmServiceStartRejectedParams != null) { StringBuilder builder = new StringBuilder(); for (String paramName : pcmServiceStartRejectedParams) { if (builder.length() > 0) { builder.append(", "); } builder.append(paramName); } DebugTool.logWarning("StartService for audio failed. Rejected params: " + builder.toString()); } else { DebugTool.logWarning("StartService for audio failed (rejected params not supplied)"); } return null; } } /** *Closes the opened audio service (serviceType 10) *@return true if the audio service is closed successfully, return false otherwise */ @SuppressWarnings("unused") public boolean endAudioStream() { if (sdlSession == null || !sdlSession.getIsConnected()) return false; pcmServiceEndResponseReceived = false; pcmServiceEndResponse = false; sdlSession.stopAudioStream(); FutureTask<Void> fTask = createFutureTask(new CallableMethod(RESPONSE_WAIT_TIME)); ScheduledExecutorService scheduler = createScheduler(); scheduler.execute(fTask); //noinspection StatementWithEmptyBody while (!pcmServiceEndResponseReceived && !fTask.isDone()); scheduler.shutdown(); return pcmServiceEndResponse; } /** *Pauses the stream for the opened audio service (serviceType 10) *@return true if the audio service stream is paused successfully, return false otherwise */ @SuppressWarnings("unused") public boolean pauseAudioStream() { return sdlSession != null && sdlSession.pauseAudioStream(); } /** *Resumes the stream for the opened audio service (serviceType 10) *@return true if the audio service stream is resumed successfully, return false otherwise */ @SuppressWarnings("unused") public boolean resumeAudioStream() { return sdlSession != null && sdlSession.resumeAudioStream(); } private void NavServiceStarted() { navServiceStartResponseReceived = true; navServiceStartResponse = true; } private void NavServiceStartedNACK(List<String> rejectedParams) { navServiceStartResponseReceived = true; navServiceStartResponse = false; navServiceStartRejectedParams = rejectedParams; } private void AudioServiceStarted() { pcmServiceStartResponseReceived = true; pcmServiceStartResponse = true; } private void RPCProtectedServiceStarted() { rpcProtectedResponseReceived = true; rpcProtectedStartResponse = true; } private void AudioServiceStartedNACK(List<String> rejectedParams) { pcmServiceStartResponseReceived = true; pcmServiceStartResponse = false; pcmServiceStartRejectedParams = rejectedParams; } private void NavServiceEnded() { navServiceEndResponseReceived = true; navServiceEndResponse = true; } private void NavServiceEndedNACK() { navServiceEndResponseReceived = true; navServiceEndResponse = false; } private void AudioServiceEnded() { pcmServiceEndResponseReceived = true; pcmServiceEndResponse = true; } private void AudioServiceEndedNACK() { pcmServiceEndResponseReceived = true; pcmServiceEndResponse = false; } public void setAppService(Service mService) { _appService = mService; } @SuppressWarnings("unused") public boolean startProtectedRPCService() { rpcProtectedResponseReceived = false; rpcProtectedStartResponse = false; sdlSession.startService(SessionType.RPC, sdlSession.getSessionId(), true); FutureTask<Void> fTask = createFutureTask(new CallableMethod(RESPONSE_WAIT_TIME)); ScheduledExecutorService scheduler = createScheduler(); scheduler.execute(fTask); //noinspection StatementWithEmptyBody while (!rpcProtectedResponseReceived && !fTask.isDone()); scheduler.shutdown(); return rpcProtectedStartResponse; } @SuppressWarnings("unused") public void getLockScreenIcon(final OnLockScreenIconDownloadedListener l){ if(lockScreenIconRequest == null){ l.onLockScreenIconDownloadError(new SdlException("This version of SDL core may not support lock screen icons.", SdlExceptionCause.LOCK_SCREEN_ICON_NOT_SUPPORTED)); return; } LockScreenManager lockMan = sdlSession.getLockScreenMan(); Bitmap bitmap = lockMan.getLockScreenIcon(); // read bitmap if it was already downloaded so we don't have to download it every time if(bitmap != null){ l.onLockScreenIconDownloaded(bitmap); } else{ String url = lockScreenIconRequest.getUrl(); sdlSession.getLockScreenMan().downloadLockScreenIcon(url, l); } } /*Begin V1 Enhanced helper*/ /** *Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener. * *@param commandID -Unique command ID of the command to add. *@param menuText -Menu text for optional sub value containing menu parameters. *@param parentID -Menu parent ID for optional sub value containing menu parameters. *@param position -Menu position for optional sub value containing menu parameters. *@param vrCommands -VR synonyms for this AddCommand. *@param IconValue -A static hex icon value or the binary image file name identifier (sent by the PutFile RPC). *@param IconType -Describes whether the image is static or dynamic *@param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("SameParameterValue") public void addCommand(@NonNull Integer commandID, String menuText, Integer parentID, Integer position, Vector<String> vrCommands, String IconValue, ImageType IconType, Integer correlationID) throws SdlException { AddCommand msg = new AddCommand(commandID); msg.setCorrelationID(correlationID); if (vrCommands != null) msg.setVrCommands(vrCommands); Image cmdIcon = null; if (IconValue != null && IconType != null) { cmdIcon = new Image(); cmdIcon.setValue(IconValue); cmdIcon.setImageType(IconType); } if (cmdIcon != null) msg.setCmdIcon(cmdIcon); if(menuText != null || parentID != null || position != null) { MenuParams menuParams = new MenuParams(); menuParams.setMenuName(menuText); menuParams.setPosition(position); menuParams.setParentID(parentID); msg.setMenuParams(menuParams); } sendRPCRequest(msg); } /** *Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener. * *@param commandID -Unique command ID of the command to add. *@param menuText -Menu text for optional sub value containing menu parameters. *@param position -Menu position for optional sub value containing menu parameters. *@param vrCommands -VR synonyms for this AddCommand. *@param IconValue -A static hex icon value or the binary image file name identifier (sent by the PutFile RPC). *@param IconType -Describes whether the image is static or dynamic *@param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void addCommand(Integer commandID, String menuText, Integer position, Vector<String> vrCommands, String IconValue, ImageType IconType, Integer correlationID) throws SdlException { addCommand(commandID, menuText, null, position, vrCommands, IconValue, IconType, correlationID); } /** *Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener. * *@param commandID -Unique command ID of the command to add. *@param menuText -Menu text for optional sub value containing menu parameters. *@param position -Menu position for optional sub value containing menu parameters. *@param IconValue -A static hex icon value or the binary image file name identifier (sent by the PutFile RPC). *@param IconType -Describes whether the image is static or dynamic *@param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void addCommand(Integer commandID, String menuText, Integer position, String IconValue, ImageType IconType, Integer correlationID) throws SdlException { addCommand(commandID, menuText, null, position, null, IconValue, IconType, correlationID); } /** *Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener. * *@param commandID -Unique command ID of the command to add. *@param menuText -Menu text for optional sub value containing menu parameters. *@param IconValue -A static hex icon value or the binary image file name identifier (sent by the PutFile RPC). *@param IconType -Describes whether the image is static or dynamic *@param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void addCommand(Integer commandID, String menuText, String IconValue, ImageType IconType, Integer correlationID) throws SdlException { addCommand(commandID, menuText, null, null, null, IconValue, IconType, correlationID); } /** * Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param commandID -Unique command ID of the command to add. * @param menuText -Menu text for optional sub value containing menu parameters. * @param vrCommands -VR synonyms for this AddCommand. * @param IconValue -A static hex icon value or the binary image file name identifier (sent by the PutFile RPC). * @param IconType -Describes whether the image is static or dynamic * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void addCommand(Integer commandID, String menuText, Vector<String> vrCommands, String IconValue, ImageType IconType, Integer correlationID) throws SdlException { addCommand(commandID, menuText, null, null, vrCommands, IconValue, IconType, correlationID); } /** * Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param commandID -Unique command ID of the command to add. * @param vrCommands -VR synonyms for this AddCommand. * @param IconValue -A static hex icon value or the binary image file name identifier (sent by the PutFile RPC). * @param IconType -Describes whether the image is static or dynamic * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void addCommand(Integer commandID, Vector<String> vrCommands, String IconValue, ImageType IconType, Integer correlationID) throws SdlException { addCommand(commandID, null, null, null, vrCommands, IconValue, IconType, correlationID); } /*End V1 Enhanced helper*/ /** *Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener. * *@param commandID -Unique command ID of the command to add. *@param menuText -Menu text for optional sub value containing menu parameters. *@param parentID -Menu parent ID for optional sub value containing menu parameters. *@param position -Menu position for optional sub value containing menu parameters. *@param vrCommands -VR synonyms for this AddCommand. *@param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("SameParameterValue") public void addCommand(@NonNull Integer commandID, String menuText, Integer parentID, Integer position, Vector<String> vrCommands, Integer correlationID) throws SdlException { AddCommand msg = new AddCommand(commandID); msg.setCorrelationID(correlationID); msg.setVrCommands(vrCommands); if(menuText != null || parentID != null || position != null) { MenuParams menuParams = new MenuParams(); menuParams.setMenuName(menuText); menuParams.setPosition(position); menuParams.setParentID(parentID); msg.setMenuParams(menuParams); } sendRPCRequest(msg); } /** *Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener. * *@param commandID -Unique command ID of the command to add. *@param menuText -Menu text for optional sub value containing menu parameters. *@param position -Menu position for optional sub value containing menu parameters. *@param vrCommands -VR synonyms for this AddCommand. *@param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void addCommand(Integer commandID, String menuText, Integer position, Vector<String> vrCommands, Integer correlationID) throws SdlException { addCommand(commandID, menuText, null, position, vrCommands, correlationID); } /** *Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener. * *@param commandID -Unique command ID of the command to add. *@param menuText -Menu text for optional sub value containing menu parameters. *@param position -Menu position for optional sub value containing menu parameters. *@param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void addCommand(Integer commandID, String menuText, Integer position, Integer correlationID) throws SdlException { addCommand(commandID, menuText, null, position, null, correlationID); } /** *Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener. * *@param commandID -Unique command ID of the command to add. *@param menuText -Menu text for optional sub value containing menu parameters. *@param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void addCommand(Integer commandID, String menuText, Integer correlationID) throws SdlException { addCommand(commandID, menuText, null, null, (Vector<String>)null, correlationID); } /** * Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener. * *@param commandID -Unique command ID of the command to add. *@param menuText -Menu text for optional sub value containing menu parameters. *@param vrCommands -VR synonyms for this AddCommand. *@param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void addCommand(Integer commandID, String menuText, Vector<String> vrCommands, Integer correlationID) throws SdlException { addCommand(commandID, menuText, null, null, vrCommands, correlationID); } /** * Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener. * *@param commandID -Unique command ID of the command to add. *@param vrCommands -VR synonyms for this AddCommand. *@param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void addCommand(Integer commandID, Vector<String> vrCommands, Integer correlationID) throws SdlException { addCommand(commandID, null, null, null, vrCommands, correlationID); } /** * Sends an AddSubMenu RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param menuID -Unique ID of the sub menu to add. * @param menuName -Text to show in the menu for this sub menu. * @param position -Position within the items that are are at top level of the in application menu. * @param menuIcon -Image to be be shown along with the submenu item * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("SameParameterValue") public void addSubMenu(@NonNull Integer menuID, @NonNull String menuName, Integer position, Image menuIcon, Integer correlationID) throws SdlException { AddSubMenu msg = new AddSubMenu(menuID, menuName); msg.setCorrelationID(correlationID); msg.setPosition(position); msg.setMenuIcon(menuIcon); sendRPCRequest(msg); } /** * Sends an AddSubMenu RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param menuID -Unique ID of the sub menu to add. * @param menuName -Text to show in the menu for this sub menu. * @param position -Position within the items that are are at top level of the in application menu. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @Deprecated @SuppressWarnings("SameParameterValue") public void addSubMenu(@NonNull Integer menuID, @NonNull String menuName, Integer position, Integer correlationID) throws SdlException { addSubMenu(menuID, menuName, position, null, correlationID); } /** * Sends an AddSubMenu RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param menuID -Unique ID of the sub menu to add. * @param menuName -Text to show in the menu for this sub menu. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @Deprecated @SuppressWarnings("unused") public void addSubMenu(Integer menuID, String menuName, Integer correlationID) throws SdlException { addSubMenu(menuID, menuName, null, null, correlationID); } /*Begin V1 Enhanced helper*/ /** * Sends an Alert RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param ttsText -The text to speech message in the form of a string. * @param alertText1 -The first line of the alert text field. * @param alertText2 -The second line of the alert text field. * @param alertText3 -The optional third line of the alert text field. * @param playTone -Defines if tone should be played. * @param duration -Timeout in milliseconds. * @param softButtons -A list of App defined SoftButtons. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("SameParameterValue") public void alert(String ttsText, String alertText1, String alertText2, String alertText3, Boolean playTone, Integer duration, Vector<SoftButton> softButtons, Integer correlationID) throws SdlException { Vector<TTSChunk> chunks = TTSChunkFactory.createSimpleTTSChunks(ttsText); Alert msg = new Alert(); msg.setCorrelationID(correlationID); msg.setAlertText1(alertText1); msg.setAlertText2(alertText2); msg.setAlertText3(alertText3); msg.setDuration(duration); msg.setPlayTone(playTone); msg.setTtsChunks(chunks); msg.setSoftButtons(softButtons); sendRPCRequest(msg); } /** * Sends an Alert RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param ttsChunks -Text/phonemes to speak in the form of ttsChunks. * @param alertText1 -The first line of the alert text field. * @param alertText2 -The second line of the alert text field. * @param alertText3 -The optional third line of the alert text field. * @param playTone -Defines if tone should be played. * @param duration -Timeout in milliseconds. * @param softButtons -A list of App defined SoftButtons. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ public void alert(Vector<TTSChunk> ttsChunks, String alertText1, String alertText2, String alertText3, Boolean playTone, Integer duration, Vector<SoftButton> softButtons, Integer correlationID) throws SdlException { Alert msg = new Alert(); msg.setCorrelationID(correlationID); msg.setAlertText1(alertText1); msg.setAlertText2(alertText2); msg.setAlertText3(alertText3); msg.setDuration(duration); msg.setPlayTone(playTone); msg.setTtsChunks(ttsChunks); msg.setSoftButtons(softButtons); sendRPCRequest(msg); } /** * Sends an Alert RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param ttsText -The text to speech message in the form of a string. * @param playTone -Defines if tone should be played. * @param softButtons -A list of App defined SoftButtons. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void alert(String ttsText, Boolean playTone, Vector<SoftButton> softButtons, Integer correlationID) throws SdlException { alert(ttsText, null, null, null, playTone, null, softButtons, correlationID); } /** * Sends an Alert RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param chunks -A list of text/phonemes to speak in the form of ttsChunks. * @param playTone -Defines if tone should be played. * @param softButtons -A list of App defined SoftButtons. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void alert(Vector<TTSChunk> chunks, Boolean playTone, Vector<SoftButton> softButtons, Integer correlationID) throws SdlException { alert(chunks, null, null, null, playTone, null, softButtons, correlationID); } /** * Sends an Alert RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param alertText1 -The first line of the alert text field. * @param alertText2 -The second line of the alert text field. * @param alertText3 -The optional third line of the alert text field. * @param playTone -Defines if tone should be played. * @param duration -Timeout in milliseconds. * @param softButtons -A list of App defined SoftButtons. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void alert(String alertText1, String alertText2, String alertText3, Boolean playTone, Integer duration, Vector<SoftButton> softButtons, Integer correlationID) throws SdlException { alert((Vector<TTSChunk>)null, alertText1, alertText2, alertText3, playTone, duration, softButtons, correlationID); } /*End V1 Enhanced helper*/ /** * Sends an Alert RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param ttsText -The text to speech message in the form of a string. * @param alertText1 -The first line of the alert text field. * @param alertText2 -The second line of the alert text field. * @param playTone -Defines if tone should be played. * @param duration -Timeout in milliseconds. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("SameParameterValue") public void alert(String ttsText, String alertText1, String alertText2, Boolean playTone, Integer duration, Integer correlationID) throws SdlException { Vector<TTSChunk> chunks = TTSChunkFactory.createSimpleTTSChunks(ttsText); Alert msg = new Alert(); msg.setCorrelationID(correlationID); msg.setAlertText1(alertText1); msg.setAlertText2(alertText2); msg.setDuration(duration); msg.setPlayTone(playTone); msg.setTtsChunks(chunks); sendRPCRequest(msg); } /** * Sends an Alert RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param ttsChunks -A list of text/phonemes to speak in the form of ttsChunks. * @param alertText1 -The first line of the alert text field. * @param alertText2 -The second line of the alert text field. * @param playTone -Defines if tone should be played. * @param duration -Timeout in milliseconds. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ public void alert(Vector<TTSChunk> ttsChunks, String alertText1, String alertText2, Boolean playTone, Integer duration, Integer correlationID) throws SdlException { Alert msg = new Alert(); msg.setCorrelationID(correlationID); msg.setAlertText1(alertText1); msg.setAlertText2(alertText2); msg.setDuration(duration); msg.setPlayTone(playTone); msg.setTtsChunks(ttsChunks); sendRPCRequest(msg); } /** * Sends an Alert RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param ttsText -The text to speech message in the form of a string. * @param playTone -Defines if tone should be played. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void alert(String ttsText, Boolean playTone, Integer correlationID) throws SdlException { alert(ttsText, null, null, playTone, null, correlationID); } /** * Sends an Alert RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param chunks -A list of text/phonemes to speak in the form of ttsChunks. * @param playTone -Defines if tone should be played. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void alert(Vector<TTSChunk> chunks, Boolean playTone, Integer correlationID) throws SdlException { alert(chunks, null, null, playTone, null, correlationID); } /** * Sends an Alert RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param alertText1 -The first line of the alert text field. * @param alertText2 -The second line of the alert text field. * @param playTone -Defines if tone should be played. * @param duration -Timeout in milliseconds. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void alert(String alertText1, String alertText2, Boolean playTone, Integer duration, Integer correlationID) throws SdlException { alert((Vector<TTSChunk>)null, alertText1, alertText2, playTone, duration, correlationID); } /** * Sends a CreateInteractionChoiceSet RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param choiceSet to be sent to the module * @param interactionChoiceSetID to be used in reference to the supplied choiceSet * @param correlationID to be set to the RPCRequest * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void createInteractionChoiceSet( @NonNull Vector<Choice> choiceSet, @NonNull Integer interactionChoiceSetID, Integer correlationID) throws SdlException { CreateInteractionChoiceSet msg = new CreateInteractionChoiceSet(interactionChoiceSetID, choiceSet); msg.setCorrelationID(correlationID); sendRPCRequest(msg); } /** * Sends a DeleteCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param commandID -ID of the command(s) to delete. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void deleteCommand(@NonNull Integer commandID, Integer correlationID) throws SdlException { DeleteCommand msg = new DeleteCommand(commandID); msg.setCorrelationID(correlationID); sendRPCRequest(msg); } /** * Sends a DeleteInteractionChoiceSet RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param interactionChoiceSetID -ID of the interaction choice set to delete. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void deleteInteractionChoiceSet( @NonNull Integer interactionChoiceSetID, Integer correlationID) throws SdlException { DeleteInteractionChoiceSet msg = new DeleteInteractionChoiceSet(interactionChoiceSetID); msg.setCorrelationID(correlationID); sendRPCRequest(msg); } /** * Sends a DeleteSubMenu RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param menuID -The menuID of the submenu to delete. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void deleteSubMenu(Integer menuID, Integer correlationID) throws SdlException { DeleteSubMenu msg = new DeleteSubMenu(menuID); msg.setCorrelationID(correlationID); sendRPCRequest(msg); } /*Begin V1 Enhanced helper*/ /** * Sends a PerformInteraction RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param initPrompt -Intial prompt spoken to the user at the start of an interaction. * @param displayText -Text to be displayed first. * @param interactionChoiceSetID -Interaction choice set IDs to use with an interaction. * @param vrHelp -Suggested VR Help Items to display on-screen during Perform Interaction. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void performInteraction(String initPrompt, @NonNull String displayText, @NonNull Integer interactionChoiceSetID, Vector<VrHelpItem> vrHelp, Integer correlationID) throws SdlException { Vector<Integer> interactionChoiceSetIDs = new Vector<Integer>(); interactionChoiceSetIDs.add(interactionChoiceSetID); Vector<TTSChunk> initChunks = TTSChunkFactory.createSimpleTTSChunks(initPrompt); PerformInteraction msg = new PerformInteraction(displayText, InteractionMode.BOTH, interactionChoiceSetIDs); msg.setInitialPrompt(initChunks); msg.setVrHelp(vrHelp); msg.setCorrelationID(correlationID); sendRPCRequest(msg); } /** * Sends a PerformInteraction RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param initPrompt -Intial prompt spoken to the user at the start of an interaction. * @param displayText -Text to be displayed first. * @param interactionChoiceSetID -Interaction choice set IDs to use with an interaction. * @param helpPrompt -Help text that is spoken when a user speaks "help" during the interaction. * @param timeoutPrompt -Timeout text that is spoken when a VR interaction times out. * @param interactionMode - The method in which the user is notified and uses the interaction (Manual,VR,Both). * @param timeout -Timeout in milliseconds. * @param vrHelp -Suggested VR Help Items to display on-screen during Perform Interaction. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void performInteraction(String initPrompt, @NonNull String displayText, @NonNull Integer interactionChoiceSetID, String helpPrompt, String timeoutPrompt, @NonNull InteractionMode interactionMode, Integer timeout, Vector<VrHelpItem> vrHelp, Integer correlationID) throws SdlException { Vector<Integer> interactionChoiceSetIDs = new Vector<Integer>(); interactionChoiceSetIDs.add(interactionChoiceSetID); Vector<TTSChunk> initChunks = TTSChunkFactory.createSimpleTTSChunks(initPrompt); Vector<TTSChunk> helpChunks = TTSChunkFactory.createSimpleTTSChunks(helpPrompt); Vector<TTSChunk> timeoutChunks = TTSChunkFactory.createSimpleTTSChunks(timeoutPrompt); PerformInteraction msg = new PerformInteraction(displayText, interactionMode, interactionChoiceSetIDs); msg.setInitialPrompt(initChunks); msg.setTimeout(timeout); msg.setHelpPrompt(helpChunks); msg.setTimeoutPrompt(timeoutChunks); msg.setVrHelp(vrHelp); msg.setCorrelationID(correlationID); sendRPCRequest(msg); } /** * Sends a PerformInteraction RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param initPrompt -Intial prompt spoken to the user at the start of an interaction. * @param displayText -Text to be displayed first. * @param interactionChoiceSetIDList -A list of interaction choice set IDs to use with an interaction. * @param helpPrompt -Help text that is spoken when a user speaks "help" during the interaction. * @param timeoutPrompt -Timeout text that is spoken when a VR interaction times out. * @param interactionMode - The method in which the user is notified and uses the interaction (Manual,VR,Both). * @param timeout -Timeout in milliseconds. * @param vrHelp -Suggested VR Help Items to display on-screen during Perform Interaction. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void performInteraction(String initPrompt, @NonNull String displayText, @NonNull Vector<Integer> interactionChoiceSetIDList, String helpPrompt, String timeoutPrompt, @NonNull InteractionMode interactionMode, Integer timeout, Vector<VrHelpItem> vrHelp, Integer correlationID) throws SdlException { Vector<TTSChunk> initChunks = TTSChunkFactory.createSimpleTTSChunks(initPrompt); Vector<TTSChunk> helpChunks = TTSChunkFactory.createSimpleTTSChunks(helpPrompt); Vector<TTSChunk> timeoutChunks = TTSChunkFactory.createSimpleTTSChunks(timeoutPrompt); PerformInteraction msg = new PerformInteraction(displayText, interactionMode, interactionChoiceSetIDList); msg.setInitialPrompt(initChunks); msg.setTimeout(timeout); msg.setHelpPrompt(helpChunks); msg.setTimeoutPrompt(timeoutChunks); msg.setVrHelp(vrHelp); msg.setCorrelationID(correlationID); sendRPCRequest(msg); } /** * Sends a PerformInteraction RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param initChunks -A list of text/phonemes to speak for the initial prompt in the form of ttsChunks. * @param displayText -Text to be displayed first. * @param interactionChoiceSetIDList -A list of interaction choice set IDs to use with an interaction. * @param helpChunks -A list of text/phonemes to speak for the help text that is spoken when a user speaks "help" during the interaction. * @param timeoutChunks A list of text/phonems to speak for the timeout text that is spoken when a VR interaction times out. * @param interactionMode - The method in which the user is notified and uses the interaction (Manual,VR,Both). * @param timeout -Timeout in milliseconds. * @param vrHelp -Suggested VR Help Items to display on-screen during Perform Interaction. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void performInteraction( Vector<TTSChunk> initChunks, @NonNull String displayText, @NonNull Vector<Integer> interactionChoiceSetIDList, Vector<TTSChunk> helpChunks, Vector<TTSChunk> timeoutChunks, @NonNull InteractionMode interactionMode, Integer timeout, Vector<VrHelpItem> vrHelp, Integer correlationID) throws SdlException { PerformInteraction msg = new PerformInteraction(displayText, interactionMode, interactionChoiceSetIDList); msg.setInitialPrompt(initChunks); msg.setTimeout(timeout); msg.setHelpPrompt(helpChunks); msg.setTimeoutPrompt(timeoutChunks); msg.setVrHelp(vrHelp); msg.setCorrelationID(correlationID); sendRPCRequest(msg); } /*End V1 Enhanced*/ /** * Sends a PerformInteraction RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param initPrompt -Intial prompt spoken to the user at the start of an interaction. * @param displayText -Text to be displayed first. * @param interactionChoiceSetID -Interaction choice set IDs to use with an interaction. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void performInteraction(String initPrompt, @NonNull String displayText, @NonNull Integer interactionChoiceSetID, Integer correlationID) throws SdlException { Vector<Integer> interactionChoiceSetIDs = new Vector<Integer>(); interactionChoiceSetIDs.add(interactionChoiceSetID); Vector<TTSChunk> initChunks = TTSChunkFactory.createSimpleTTSChunks(initPrompt); PerformInteraction msg = new PerformInteraction(displayText, InteractionMode.BOTH, interactionChoiceSetIDs); msg.setInitialPrompt(initChunks); msg.setCorrelationID(correlationID); sendRPCRequest(msg); } /** * Sends a PerformInteraction RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param initPrompt -Intial prompt spoken to the user at the start of an interaction. * @param displayText -Text to be displayed first. * @param interactionChoiceSetID -Interaction choice set IDs to use with an interaction. * @param helpPrompt -Help text that is spoken when a user speaks "help" during the interaction. * @param timeoutPrompt -Timeout text that is spoken when a VR interaction times out. * @param interactionMode - The method in which the user is notified and uses the interaction (Manual,VR,Both). * @param timeout -Timeout in milliseconds. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void performInteraction(String initPrompt, @NonNull String displayText, @NonNull Integer interactionChoiceSetID, String helpPrompt, String timeoutPrompt, @NonNull InteractionMode interactionMode, Integer timeout, Integer correlationID) throws SdlException { Vector<Integer> interactionChoiceSetIDs = new Vector<Integer>(); interactionChoiceSetIDs.add(interactionChoiceSetID); Vector<TTSChunk> initChunks = TTSChunkFactory.createSimpleTTSChunks(initPrompt); Vector<TTSChunk> helpChunks = TTSChunkFactory.createSimpleTTSChunks(helpPrompt); Vector<TTSChunk> timeoutChunks = TTSChunkFactory.createSimpleTTSChunks(timeoutPrompt); PerformInteraction msg = new PerformInteraction(displayText, interactionMode, interactionChoiceSetIDs); msg.setInitialPrompt(initChunks); msg.setTimeout(timeout); msg.setHelpPrompt(helpChunks); msg.setTimeoutPrompt(timeoutChunks); msg.setCorrelationID(correlationID); sendRPCRequest(msg); } /** * Sends a PerformInteraction RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param initPrompt -Intial prompt spoken to the user at the start of an interaction. * @param displayText -Text to be displayed first. * @param interactionChoiceSetIDList -A list of interaction choice set IDs to use with an interaction. * @param helpPrompt -Help text that is spoken when a user speaks "help" during the interaction. * @param timeoutPrompt -Timeout text that is spoken when a VR interaction times out. * @param interactionMode - The method in which the user is notified and uses the interaction (Manual,VR,Both). * @param timeout -Timeout in milliseconds. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void performInteraction(String initPrompt, @NonNull String displayText, @NonNull Vector<Integer> interactionChoiceSetIDList, String helpPrompt, String timeoutPrompt, @NonNull InteractionMode interactionMode, Integer timeout, Integer correlationID) throws SdlException { Vector<TTSChunk> initChunks = TTSChunkFactory.createSimpleTTSChunks(initPrompt); Vector<TTSChunk> helpChunks = TTSChunkFactory.createSimpleTTSChunks(helpPrompt); Vector<TTSChunk> timeoutChunks = TTSChunkFactory.createSimpleTTSChunks(timeoutPrompt); PerformInteraction msg = new PerformInteraction(displayText, interactionMode, interactionChoiceSetIDList); msg.setInitialPrompt(initChunks); msg.setTimeout(timeout); msg.setHelpPrompt(helpChunks); msg.setTimeoutPrompt(timeoutChunks); msg.setCorrelationID(correlationID); sendRPCRequest(msg); } /** * Sends a PerformInteraction RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param initChunks -A list of text/phonemes to speak for the initial prompt in the form of ttsChunks. * @param displayText -Text to be displayed first. * @param interactionChoiceSetIDList -A list of interaction choice set IDs to use with an interaction. * @param helpChunks -A list of text/phonemes to speak for the help text that is spoken when a user speaks "help" during the interaction. * @param timeoutChunks A list of text/phonems to speak for the timeout text that is spoken when a VR interaction times out. * @param interactionMode - The method in which the user is notified and uses the interaction (Manual,VR,Both). * @param timeout -Timeout in milliseconds. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void performInteraction( Vector<TTSChunk> initChunks, @NonNull String displayText, @NonNull Vector<Integer> interactionChoiceSetIDList, Vector<TTSChunk> helpChunks, Vector<TTSChunk> timeoutChunks, @NonNull InteractionMode interactionMode, Integer timeout, Integer correlationID) throws SdlException { PerformInteraction msg = new PerformInteraction(displayText, interactionMode, interactionChoiceSetIDList); msg.setInitialPrompt(initChunks); msg.setTimeout(timeout); msg.setHelpPrompt(helpChunks); msg.setTimeoutPrompt(timeoutChunks); msg.setCorrelationID(correlationID); sendRPCRequest(msg); } // Protected registerAppInterface used to ensure only non-ALM applications call // reqisterAppInterface protected void registerAppInterfacePrivate( @NonNull SdlMsgVersion sdlMsgVersion, @NonNull String appName, Vector<TTSChunk> ttsName, String ngnMediaScreenAppName, Vector<String> vrSynonyms, @NonNull Boolean isMediaApp, @NonNull Language languageDesired, @NonNull Language hmiDisplayLanguageDesired, Vector<AppHMIType> appType, @NonNull String appID, TemplateColorScheme dayColorScheme, TemplateColorScheme nightColorScheme, Integer correlationID) throws SdlException { String carrierName = null; if(telephonyManager != null){ carrierName = telephonyManager.getNetworkOperatorName(); } DeviceInfo deviceInfo = new DeviceInfo(); deviceInfo.setHardware(android.os.Build.MODEL); deviceInfo.setOs(DeviceInfo.DEVICE_OS); deviceInfo.setOsVersion(Build.VERSION.RELEASE); deviceInfo.setCarrier(carrierName); if (sdlMsgVersion == null) { sdlMsgVersion = new SdlMsgVersion(); if(protocolVersion.getMajor() == 1) { DebugTool.logInfo("Connected to an older module, must send 1.0.0 as RPC spec"); sdlMsgVersion.setMajorVersion(1); sdlMsgVersion.setMinorVersion(0); }else { sdlMsgVersion.setMajorVersion(MAX_SUPPORTED_RPC_VERSION.getMajor()); sdlMsgVersion.setMinorVersion(MAX_SUPPORTED_RPC_VERSION.getMinor()); } } if (languageDesired == null) { languageDesired = Language.EN_US; } if (hmiDisplayLanguageDesired == null) { hmiDisplayLanguageDesired = Language.EN_US; } RegisterAppInterface msg = new RegisterAppInterface(sdlMsgVersion, appName, isMediaApp, languageDesired, hmiDisplayLanguageDesired, appID); if (correlationID != null) { msg.setCorrelationID(correlationID); } msg.setDeviceInfo(deviceInfo); msg.setTtsName(ttsName); if (ngnMediaScreenAppName == null) { ngnMediaScreenAppName = appName; } msg.setNgnMediaScreenAppName(ngnMediaScreenAppName); if (vrSynonyms == null) { vrSynonyms = new Vector<String>(); vrSynonyms.add(appName); } msg.setVrSynonyms(vrSynonyms); msg.setAppHMIType(appType); msg.setDayColorScheme(dayColorScheme); msg.setNightColorScheme(nightColorScheme); if (_bAppResumeEnabled) { if (_lastHashID != null) msg.setHashID(_lastHashID); } Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "RPC_NAME", FunctionID.REGISTER_APP_INTERFACE.toString()); updateBroadcastIntent(sendIntent, "TYPE", RPCMessage.KEY_REQUEST); updateBroadcastIntent(sendIntent, "CORRID", msg.getCorrelationID()); updateBroadcastIntent(sendIntent, "DATA",serializeJSON(msg)); sendBroadcastIntent(sendIntent); sendRPCMessagePrivate(msg); } /*Begin V1 Enhanced helper function*/ /** * Sends a SetGlobalProperties RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param helpPrompt that will be used for the VR screen * @param timeoutPrompt string to be displayed after timeout * @param vrHelpTitle string that may be displayed on VR prompt dialog * @param vrHelp a list of VR synonyms that may be displayed to user * @param correlationID to be attached to the request * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void setGlobalProperties( String helpPrompt, String timeoutPrompt, String vrHelpTitle, Vector<VrHelpItem> vrHelp, Integer correlationID) throws SdlException { SetGlobalProperties req = new SetGlobalProperties(); req.setCorrelationID(correlationID); req.setHelpPrompt(TTSChunkFactory.createSimpleTTSChunks(helpPrompt)); req.setTimeoutPrompt(TTSChunkFactory.createSimpleTTSChunks(timeoutPrompt)); req.setVrHelpTitle(vrHelpTitle); req.setVrHelp(vrHelp); sendRPCRequest(req); } /** * Sends a SetGlobalProperties RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param helpChunks tts chunks that should be used when prompting the user * @param timeoutChunks tts chunks that will be used when a timeout occurs * @param vrHelpTitle string that may be displayed on VR prompt dialog * @param vrHelp a list of VR synonyms that may be displayed to user * @param correlationID ID to be attached to the RPCRequest that correlates the RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void setGlobalProperties( Vector<TTSChunk> helpChunks, Vector<TTSChunk> timeoutChunks, String vrHelpTitle, Vector<VrHelpItem> vrHelp, Integer correlationID) throws SdlException { SetGlobalProperties req = new SetGlobalProperties(); req.setCorrelationID(correlationID); req.setHelpPrompt(helpChunks); req.setTimeoutPrompt(timeoutChunks); req.setVrHelpTitle(vrHelpTitle); req.setVrHelp(vrHelp); sendRPCRequest(req); } /*End V1 Enhanced helper function*/ /** * Sends a SetGlobalProperties RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param helpPrompt that will be used for the VR screen * @param timeoutPrompt string to be displayed after timeout * @param correlationID ID to be attached to the RPCRequest that correlates the RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void setGlobalProperties( String helpPrompt, String timeoutPrompt, Integer correlationID) throws SdlException { SetGlobalProperties req = new SetGlobalProperties(); req.setCorrelationID(correlationID); req.setHelpPrompt(TTSChunkFactory.createSimpleTTSChunks(helpPrompt)); req.setTimeoutPrompt(TTSChunkFactory.createSimpleTTSChunks(timeoutPrompt)); sendRPCRequest(req); } /** * Sends a SetGlobalProperties RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param helpChunks tts chunks that should be used when prompting the user * @param timeoutChunks tts chunks that will be used when a timeout occurs * @param correlationID ID to be attached to the RPCRequest that correlates the RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void setGlobalProperties( Vector<TTSChunk> helpChunks, Vector<TTSChunk> timeoutChunks, Integer correlationID) throws SdlException { SetGlobalProperties req = new SetGlobalProperties(); req.setCorrelationID(correlationID); req.setHelpPrompt(helpChunks); req.setTimeoutPrompt(timeoutChunks); sendRPCRequest(req); } @SuppressWarnings("unused") public void resetGlobalProperties(Vector<GlobalProperty> properties, Integer correlationID) throws SdlException { ResetGlobalProperties req = new ResetGlobalProperties(); req.setCorrelationID(correlationID); req.setProperties(properties); sendRPCRequest(req); } /** * Sends a SetMediaClockTimer RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param hours integer for hours * @param minutes integer for minutes * @param seconds integer for seconds * @param updateMode mode in which the media clock timer should be updated * @param correlationID ID to be attached to the RPCRequest that correlates the RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void setMediaClockTimer(Integer hours, Integer minutes, Integer seconds, @NonNull UpdateMode updateMode, Integer correlationID) throws SdlException { SetMediaClockTimer msg = new SetMediaClockTimer(updateMode); if (hours != null || minutes != null || seconds != null) { StartTime startTime = new StartTime(hours, minutes, seconds); msg.setStartTime(startTime); } msg.setCorrelationID(correlationID); sendRPCRequest(msg); } /** * Pauses the media clock. Responses are captured through callback on IProxyListener. * * @param correlationID ID to be attached to the RPCRequest that correlates the RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void pauseMediaClockTimer(Integer correlationID) throws SdlException { SetMediaClockTimer msg = new SetMediaClockTimer(UpdateMode.PAUSE); StartTime startTime = new StartTime(0, 0, 0); msg.setStartTime(startTime); msg.setCorrelationID(correlationID); sendRPCRequest(msg); } /** * Resumes the media clock. Responses are captured through callback on IProxyListener. * * @param correlationID ID to be attached to the RPCRequest that correlates the RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void resumeMediaClockTimer(Integer correlationID) throws SdlException { SetMediaClockTimer msg = new SetMediaClockTimer(UpdateMode.RESUME); StartTime startTime = new StartTime(0, 0, 0); msg.setStartTime(startTime); msg.setCorrelationID(correlationID); sendRPCRequest(msg); } /** * Clears the media clock. Responses are captured through callback on IProxyListener. * * @param correlationID ID to be attached to the RPCRequest that correlates the RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void clearMediaClockTimer(Integer correlationID) throws SdlException { Show msg = new Show(); msg.setCorrelationID(correlationID); msg.setMediaClock(" "); sendRPCRequest(msg); } /*Begin V1 Enhanced helper*/ /** * Sends a Show RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param mainText1 text displayed in a single or upper display line. * @param mainText2 text displayed on the second display line. * @param mainText3 text displayed on the second "page" first display line. * @param mainText4 text displayed on the second "page" second display line. * @param statusBar text is placed in the status bar area (Only valid for NAVIGATION apps) * @param mediaClock text value for MediaClock field. * @param mediaTrack text displayed in the track field. * @param graphic image struct determining whether static or dynamic image to display in app. * @param softButtons app defined SoftButtons. * @param customPresets app labeled on-screen presets. * @param alignment specifies how mainText1 and mainText2s texts should be aligned on display. * @param correlationID ID to be attached to the RPCRequest that correlates the RPCResponse -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("SameParameterValue") public void show(String mainText1, String mainText2, String mainText3, String mainText4, String statusBar, String mediaClock, String mediaTrack, Image graphic, Vector<SoftButton> softButtons, Vector <String> customPresets, TextAlignment alignment, Integer correlationID) throws SdlException { Show msg = new Show(); msg.setCorrelationID(correlationID); msg.setMainField1(mainText1); msg.setMainField2(mainText2); msg.setStatusBar(statusBar); msg.setMediaClock(mediaClock); msg.setMediaTrack(mediaTrack); msg.setAlignment(alignment); msg.setMainField3(mainText3); msg.setMainField4(mainText4); msg.setGraphic(graphic); msg.setSoftButtons(softButtons); msg.setCustomPresets(customPresets); sendRPCRequest(msg); } /** * Sends a Show RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param mainText1 -Text displayed in a single or upper display line. * @param mainText2 -Text displayed on the second display line. * @param mainText3 -Text displayed on the second "page" first display line. * @param mainText4 -Text displayed on the second "page" second display line. * @param graphic -Image struct determining whether static or dynamic image to display in app. * @param softButtons -App defined SoftButtons. * @param customPresets -App labeled on-screen presets. * @param alignment -Specifies how mainText1 and mainText2s texts should be aligned on display. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void show(String mainText1, String mainText2, String mainText3, String mainText4, Image graphic, Vector<SoftButton> softButtons, Vector <String> customPresets, TextAlignment alignment, Integer correlationID) throws SdlException { show(mainText1, mainText2, mainText3, mainText4, null, null, null, graphic, softButtons, customPresets, alignment, correlationID); } /*End V1 Enhanced helper*/ /** * Sends a Show RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param mainText1 text displayed in a single or upper display line. * @param mainText2 text displayed on the second display line. * @param statusBar text is placed in the status bar area (Only valid for NAVIGATION apps) * @param mediaClock text value for MediaClock field. * @param mediaTrack text displayed in the track field. * @param alignment specifies how mainText1 and mainText2s texts should be aligned on display. * @param correlationID unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("SameParameterValue") public void show(String mainText1, String mainText2, String statusBar, String mediaClock, String mediaTrack, TextAlignment alignment, Integer correlationID) throws SdlException { Show msg = new Show(); msg.setCorrelationID(correlationID); msg.setMainField1(mainText1); msg.setMainField2(mainText2); msg.setStatusBar(statusBar); msg.setMediaClock(mediaClock); msg.setMediaTrack(mediaTrack); msg.setAlignment(alignment); sendRPCRequest(msg); } /** * Sends a Show RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param mainText1 -Text displayed in a single or upper display line. * @param mainText2 -Text displayed on the second display line. * @param alignment -Specifies how mainText1 and mainText2s texts should be aligned on display. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void show(String mainText1, String mainText2, TextAlignment alignment, Integer correlationID) throws SdlException { show(mainText1, mainText2, null, null, null, alignment, correlationID); } /** * Sends a Speak RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param ttsText -The text to speech message in the form of a string. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void speak(@NonNull String ttsText, Integer correlationID) throws SdlException { Speak msg = new Speak(TTSChunkFactory.createSimpleTTSChunks(ttsText)); msg.setCorrelationID(correlationID); sendRPCRequest(msg); } /** * Sends a Speak RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param ttsChunks -Text/phonemes to speak in the form of ttsChunks. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void speak(@NonNull Vector<TTSChunk> ttsChunks, Integer correlationID) throws SdlException { Speak msg = new Speak(ttsChunks); msg.setCorrelationID(correlationID); sendRPCRequest(msg); } /** * Sends a SubscribeButton RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param buttonName -Name of the button to subscribe. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void subscribeButton(@NonNull ButtonName buttonName, Integer correlationID) throws SdlException { SubscribeButton msg = new SubscribeButton(buttonName); msg.setCorrelationID(correlationID); sendRPCRequest(msg); } // Protected unregisterAppInterface used to ensure no non-ALM app calls // unregisterAppInterface. protected void unregisterAppInterfacePrivate(Integer correlationID) throws SdlException { UnregisterAppInterface msg = new UnregisterAppInterface(); msg.setCorrelationID(correlationID); Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "RPC_NAME", FunctionID.UNREGISTER_APP_INTERFACE.toString()); updateBroadcastIntent(sendIntent, "TYPE", RPCMessage.KEY_REQUEST); updateBroadcastIntent(sendIntent, "CORRID", msg.getCorrelationID()); updateBroadcastIntent(sendIntent, "DATA",serializeJSON(msg)); sendBroadcastIntent(sendIntent); sendRPCMessagePrivate(msg); } /** * Sends an UnsubscribeButton RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param buttonName -Name of the button to unsubscribe. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void unsubscribeButton(@NonNull ButtonName buttonName, Integer correlationID) throws SdlException { UnsubscribeButton msg = new UnsubscribeButton(buttonName); msg.setCorrelationID(correlationID); sendRPCRequest(msg); } /** * Creates a choice to be added to a choiceset. Choice has both a voice and a visual menu component. * * @param choiceID -Unique ID used to identify this choice (returned in callback). * @param choiceMenuName -Text name displayed for this choice. * @param choiceVrCommands -Vector of vrCommands used to select this choice by voice. Must contain * at least one non-empty element. * @return Choice created. */ @SuppressWarnings("unused") public Choice createChoiceSetChoice(Integer choiceID, String choiceMenuName, Vector<String> choiceVrCommands) { Choice returnChoice = new Choice(); returnChoice.setChoiceID(choiceID); returnChoice.setMenuName(choiceMenuName); returnChoice.setVrCommands(choiceVrCommands); return returnChoice; } /** * Starts audio pass thru session. Responses are captured through callback on IProxyListener. * * @param initialPrompt -SDL will speak this prompt before opening the audio pass thru session. * @param audioPassThruDisplayText1 -First line of text displayed during audio capture. * @param audioPassThruDisplayText2 -Second line of text displayed during audio capture. * @param samplingRate -Allowable values of 8 khz or 16 or 22 or 44 khz. * @param maxDuration -The maximum duration of audio recording in milliseconds. * @param bitsPerSample -Specifies the quality the audio is recorded. Currently 8 bit or 16 bit. * @param audioType -Specifies the type of audio data being requested. * @param muteAudio -Defines if the current audio source should be muted during the APT session. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void performaudiopassthru(String initialPrompt, String audioPassThruDisplayText1, String audioPassThruDisplayText2, @NonNull SamplingRate samplingRate, @NonNull Integer maxDuration, @NonNull BitsPerSample bitsPerSample, @NonNull AudioType audioType, Boolean muteAudio, Integer correlationID) throws SdlException { Vector<TTSChunk> chunks = TTSChunkFactory.createSimpleTTSChunks(initialPrompt); PerformAudioPassThru msg = new PerformAudioPassThru(samplingRate, maxDuration, bitsPerSample, audioType); msg.setCorrelationID(correlationID); msg.setInitialPrompt(chunks); msg.setAudioPassThruDisplayText1(audioPassThruDisplayText1); msg.setAudioPassThruDisplayText2(audioPassThruDisplayText2); msg.setMuteAudio(muteAudio); sendRPCRequest(msg); } /** * Ends audio pass thru session. Responses are captured through callback on IProxyListener. * * @param correlationID ID to be attached to the RPCRequest that correlates the RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void endaudiopassthru(Integer correlationID) throws SdlException { EndAudioPassThru msg = new EndAudioPassThru(); msg.setCorrelationID(correlationID); sendRPCRequest(msg); } /** * Subscribes for specific published data items. The data will be only sent if it has changed. * Responses are captured through callback on IProxyListener. * * @param gps -Subscribes to GPS data. * @param speed -Subscribes to vehicle speed data in kilometers per hour. * @param rpm -Subscribes to number of revolutions per minute of the engine. * @param fuelLevel -Subscribes to fuel level in the tank (percentage). * @param fuelLevel_State -Subscribes to fuel level state. * @param instantFuelConsumption -Subscribes to instantaneous fuel consumption in microlitres. * @param externalTemperature -Subscribes to the external temperature in degrees celsius. * @param prndl -Subscribes to PRNDL data that houses the selected gear. * @param tirePressure -Subscribes to the TireStatus data containing status and pressure of tires. * @param odometer -Subscribes to Odometer data in km. * @param beltStatus -Subscribes to status of the seat belts. * @param bodyInformation -Subscribes to body information including power modes. * @param deviceStatus -Subscribes to device status including signal and battery strength. * @param driverBraking -Subscribes to the status of the brake pedal. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") @Deprecated public void subscribevehicledata(boolean gps, boolean speed, boolean rpm, boolean fuelLevel, boolean fuelLevel_State, boolean instantFuelConsumption, boolean externalTemperature, boolean prndl, boolean tirePressure, boolean odometer, boolean beltStatus, boolean bodyInformation, boolean deviceStatus, boolean driverBraking, Integer correlationID) throws SdlException { SubscribeVehicleData msg = new SubscribeVehicleData(); msg.setGps(gps); msg.setSpeed(speed); msg.setRpm(rpm); msg.setFuelLevel(fuelLevel); msg.setFuelLevel_State(fuelLevel_State); msg.setInstantFuelConsumption(instantFuelConsumption); msg.setExternalTemperature(externalTemperature); msg.setPrndl(prndl); msg.setTirePressure(tirePressure); msg.setOdometer(odometer); msg.setBeltStatus(beltStatus); msg.setBodyInformation(bodyInformation); msg.setDeviceStatus(deviceStatus); msg.setDriverBraking(driverBraking); msg.setCorrelationID(correlationID); sendRPCRequest(msg); } /** * Subscribes for specific published data items. The data will be only sent if it has changed. * Responses are captured through callback on IProxyListener. * * @param gps -Subscribes to GPS data. * @param speed -Subscribes to vehicle speed data in kilometers per hour. * @param rpm -Subscribes to number of revolutions per minute of the engine. * @param fuelLevel -Subscribes to fuel level in the tank (percentage). * @param fuelLevel_State -Subscribes to fuel level state. * @param instantFuelConsumption -Subscribes to instantaneous fuel consumption in microlitres. * @param externalTemperature -Subscribes to the external temperature in degrees celsius. * @param prndl -Subscribes to PRNDL data that houses the selected gear. * @param tirePressure -Subscribes to the TireStatus data containing status and pressure of tires. * @param engineOilLife -Subscribes to Engine Oil Life data. * @param odometer -Subscribes to Odometer data in km. * @param beltStatus -Subscribes to status of the seat belts. * @param bodyInformation -Subscribes to body information including power modes. * @param deviceStatus -Subscribes to device status including signal and battery strength. * @param driverBraking -Subscribes to the status of the brake pedal. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void subscribevehicledata(boolean gps, boolean speed, boolean rpm, boolean fuelLevel, boolean fuelLevel_State, boolean instantFuelConsumption, boolean externalTemperature, boolean prndl, boolean tirePressure, boolean engineOilLife, boolean odometer, boolean beltStatus, boolean bodyInformation, boolean deviceStatus, boolean driverBraking, Integer correlationID) throws SdlException { SubscribeVehicleData msg = new SubscribeVehicleData(); msg.setGps(gps); msg.setSpeed(speed); msg.setRpm(rpm); msg.setFuelLevel(fuelLevel); msg.setFuelLevel_State(fuelLevel_State); msg.setInstantFuelConsumption(instantFuelConsumption); msg.setExternalTemperature(externalTemperature); msg.setPrndl(prndl); msg.setTirePressure(tirePressure); msg.setEngineOilLife(engineOilLife); msg.setOdometer(odometer); msg.setBeltStatus(beltStatus); msg.setBodyInformation(bodyInformation); msg.setDeviceStatus(deviceStatus); msg.setDriverBraking(driverBraking); msg.setCorrelationID(correlationID); sendRPCRequest(msg); } /** * Unsubscribes for specific published data items. * Responses are captured through callback on IProxyListener. * * @param gps -Unsubscribes to GPS data. * @param speed -Unsubscribes to vehicle speed data in kilometers per hour. * @param rpm -Unsubscribes to number of revolutions per minute of the engine. * @param fuelLevel -Unsubscribes to fuel level in the tank (percentage). * @param fuelLevel_State -Unsubscribes to fuel level state. * @param instantFuelConsumption -Unsubscribes to instantaneous fuel consumption in microlitres. * @param externalTemperature -Unsubscribes to the external temperature in degrees celsius. * @param prndl -Unsubscribes to PRNDL data that houses the selected gear. * @param tirePressure -Unsubscribes to the TireStatus data containing status and pressure of tires. * @param odometer -Unsubscribes to Odometer data in km. * @param beltStatus -Unsubscribes to status of the seat belts. * @param bodyInformation -Unsubscribes to body information including power modes. * @param deviceStatus -Unsubscribes to device status including signal and battery strength. * @param driverBraking -Unsubscribes to the status of the brake pedal. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") @Deprecated public void unsubscribevehicledata(boolean gps, boolean speed, boolean rpm, boolean fuelLevel, boolean fuelLevel_State, boolean instantFuelConsumption, boolean externalTemperature, boolean prndl, boolean tirePressure, boolean odometer, boolean beltStatus, boolean bodyInformation, boolean deviceStatus, boolean driverBraking, Integer correlationID) throws SdlException { UnsubscribeVehicleData msg = new UnsubscribeVehicleData(); msg.setGps(gps); msg.setSpeed(speed); msg.setRpm(rpm); msg.setFuelLevel(fuelLevel); msg.setFuelLevel_State(fuelLevel_State); msg.setInstantFuelConsumption(instantFuelConsumption); msg.setExternalTemperature(externalTemperature); msg.setPrndl(prndl); msg.setTirePressure(tirePressure); msg.setOdometer(odometer); msg.setBeltStatus(beltStatus); msg.setBodyInformation(bodyInformation); msg.setDeviceStatus(deviceStatus); msg.setDriverBraking(driverBraking); msg.setCorrelationID(correlationID); sendRPCRequest(msg); } /** * Unsubscribes for specific published data items. * Responses are captured through callback on IProxyListener. * * @param gps -Unsubscribes to GPS data. * @param speed -Unsubscribes to vehicle speed data in kilometers per hour. * @param rpm -Unsubscribes to number of revolutions per minute of the engine. * @param fuelLevel -Unsubscribes to fuel level in the tank (percentage). * @param fuelLevel_State -Unsubscribes to fuel level state. * @param instantFuelConsumption -Unsubscribes to instantaneous fuel consumption in microlitres. * @param externalTemperature -Unsubscribes to the external temperature in degrees celsius. * @param prndl -Unsubscribes to PRNDL data that houses the selected gear. * @param tirePressure -Unsubscribes to the TireStatus data containing status and pressure of tires. * @param engineOilLife -Unsubscribes to Engine Oil Life data. * @param odometer -Unsubscribes to Odometer data in km. * @param beltStatus -Unsubscribes to status of the seat belts. * @param bodyInformation -Unsubscribes to body information including power modes. * @param deviceStatus -Unsubscribes to device status including signal and battery strength. * @param driverBraking -Unsubscribes to the status of the brake pedal. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void unsubscribevehicledata(boolean gps, boolean speed, boolean rpm, boolean fuelLevel, boolean fuelLevel_State, boolean instantFuelConsumption, boolean externalTemperature, boolean prndl, boolean tirePressure, boolean engineOilLife, boolean odometer, boolean beltStatus, boolean bodyInformation, boolean deviceStatus, boolean driverBraking, Integer correlationID) throws SdlException { UnsubscribeVehicleData msg = new UnsubscribeVehicleData(); msg.setGps(gps); msg.setSpeed(speed); msg.setRpm(rpm); msg.setFuelLevel(fuelLevel); msg.setFuelLevel_State(fuelLevel_State); msg.setInstantFuelConsumption(instantFuelConsumption); msg.setExternalTemperature(externalTemperature); msg.setPrndl(prndl); msg.setTirePressure(tirePressure); msg.setEngineOilLife(engineOilLife); msg.setOdometer(odometer); msg.setBeltStatus(beltStatus); msg.setBodyInformation(bodyInformation); msg.setDeviceStatus(deviceStatus); msg.setDriverBraking(driverBraking); msg.setCorrelationID(correlationID); sendRPCRequest(msg); } /** * Performs a Non periodic vehicle data read request. * Responses are captured through callback on IProxyListener. * * @param gps -Performs an ad-hoc request for GPS data. * @param speed -Performs an ad-hoc request for vehicle speed data in kilometers per hour. * @param rpm -Performs an ad-hoc request for number of revolutions per minute of the engine. * @param fuelLevel -Performs an ad-hoc request for fuel level in the tank (percentage). * @param fuelLevel_State -Performs an ad-hoc request for fuel level state. * @param instantFuelConsumption -Performs an ad-hoc request for instantaneous fuel consumption in microlitres. * @param externalTemperature -Performs an ad-hoc request for the external temperature in degrees celsius. * @param vin -Performs an ad-hoc request for the Vehicle identification number * @param prndl -Performs an ad-hoc request for PRNDL data that houses the selected gear. * @param tirePressure -Performs an ad-hoc request for the TireStatus data containing status and pressure of tires. * @param odometer -Performs an ad-hoc request for Odometer data in km. * @param beltStatus -Performs an ad-hoc request for status of the seat belts. * @param bodyInformation -Performs an ad-hoc request for body information including power modes. * @param deviceStatus -Performs an ad-hoc request for device status including signal and battery strength. * @param driverBraking -Performs an ad-hoc request for the status of the brake pedal. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") @Deprecated public void getvehicledata(boolean gps, boolean speed, boolean rpm, boolean fuelLevel, boolean fuelLevel_State, boolean instantFuelConsumption, boolean externalTemperature, boolean vin, boolean prndl, boolean tirePressure, boolean odometer, boolean beltStatus, boolean bodyInformation, boolean deviceStatus, boolean driverBraking, Integer correlationID) throws SdlException { GetVehicleData msg = new GetVehicleData(); msg.setGps(gps); msg.setSpeed(speed); msg.setRpm(rpm); msg.setFuelLevel(fuelLevel); msg.setFuelLevel_State(fuelLevel_State); msg.setInstantFuelConsumption(instantFuelConsumption); msg.setExternalTemperature(externalTemperature); msg.setVin(vin); msg.setPrndl(prndl); msg.setTirePressure(tirePressure); msg.setOdometer(odometer); msg.setBeltStatus(beltStatus); msg.setBodyInformation(bodyInformation); msg.setDeviceStatus(deviceStatus); msg.setDriverBraking(driverBraking); msg.setCorrelationID(correlationID); sendRPCRequest(msg); } /** * Performs a Non periodic vehicle data read request. * Responses are captured through callback on IProxyListener. * * @param gps -Performs an ad-hoc request for GPS data. * @param speed -Performs an ad-hoc request for vehicle speed data in kilometers per hour. * @param rpm -Performs an ad-hoc request for number of revolutions per minute of the engine. * @param fuelLevel -Performs an ad-hoc request for fuel level in the tank (percentage). * @param fuelLevel_State -Performs an ad-hoc request for fuel level state. * @param instantFuelConsumption -Performs an ad-hoc request for instantaneous fuel consumption in microlitres. * @param externalTemperature -Performs an ad-hoc request for the external temperature in degrees celsius. * @param vin -Performs an ad-hoc request for the Vehicle identification number * @param prndl -Performs an ad-hoc request for PRNDL data that houses the selected gear. * @param tirePressure -Performs an ad-hoc request for the TireStatus data containing status and pressure of tires. * @param engineOilLife -Performs an ad-hoc request for Engine Oil Life data. * @param odometer -Performs an ad-hoc request for Odometer data in km. * @param beltStatus -Performs an ad-hoc request for status of the seat belts. * @param bodyInformation -Performs an ad-hoc request for body information including power modes. * @param deviceStatus -Performs an ad-hoc request for device status including signal and battery strength. * @param driverBraking -Performs an ad-hoc request for the status of the brake pedal. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void getvehicledata(boolean gps, boolean speed, boolean rpm, boolean fuelLevel, boolean fuelLevel_State, boolean instantFuelConsumption, boolean externalTemperature, boolean vin, boolean prndl, boolean tirePressure, boolean engineOilLife, boolean odometer, boolean beltStatus, boolean bodyInformation, boolean deviceStatus, boolean driverBraking, Integer correlationID) throws SdlException { GetVehicleData msg = new GetVehicleData(); msg.setGps(gps); msg.setSpeed(speed); msg.setRpm(rpm); msg.setFuelLevel(fuelLevel); msg.setFuelLevel_State(fuelLevel_State); msg.setInstantFuelConsumption(instantFuelConsumption); msg.setExternalTemperature(externalTemperature); msg.setVin(vin); msg.setPrndl(prndl); msg.setTirePressure(tirePressure); msg.setEngineOilLife(engineOilLife); msg.setOdometer(odometer); msg.setBeltStatus(beltStatus); msg.setBodyInformation(bodyInformation); msg.setDeviceStatus(deviceStatus); msg.setDriverBraking(driverBraking); msg.setCorrelationID(correlationID); sendRPCRequest(msg); } /** * Creates a full screen overlay containing a large block of formatted text that can be scrolled with up to 8 SoftButtons defined. * Responses are captured through callback on IProxyListener. * * @param scrollableMessageBody -Body of text that can include newlines and tabs. * @param timeout -App defined timeout. Indicates how long of a timeout from the last action. * @param softButtons -App defined SoftButtons. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void scrollablemessage(@NonNull String scrollableMessageBody, Integer timeout, Vector<SoftButton> softButtons, Integer correlationID) throws SdlException { ScrollableMessage msg = new ScrollableMessage(scrollableMessageBody); msg.setCorrelationID(correlationID); msg.setTimeout(timeout); msg.setSoftButtons(softButtons); sendRPCRequest(msg); } /** * Creates a full screen or pop-up overlay (depending on platform) with a single user controlled slider. * Responses are captured through callback on IProxyListener. * * @param numTicks -Number of selectable items on a horizontal axis. * @param position -Initial position of slider control (cannot exceed numTicks). * @param sliderHeader -Text header to display. * @param sliderFooter - Text footer to display (meant to display min/max threshold descriptors). * @param timeout -App defined timeout. Indicates how long of a timeout from the last action. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void slider(@NonNull Integer numTicks, @NonNull Integer position, @NonNull String sliderHeader, Vector<String> sliderFooter, Integer timeout, Integer correlationID) throws SdlException { Slider msg = new Slider(numTicks, position, sliderHeader); msg.setCorrelationID(correlationID); msg.setSliderFooter(sliderFooter); msg.setTimeout(timeout); sendRPCRequest(msg); } /** * Responses are captured through callback on IProxyListener. * * @param language requested SDL voice engine (VR+TTS) language registration * @param hmiDisplayLanguage request display language registration. * @param correlationID ID to be attached to the RPCRequest that correlates the RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void changeregistration(@NonNull Language language, @NonNull Language hmiDisplayLanguage, Integer correlationID) throws SdlException { ChangeRegistration msg = new ChangeRegistration(language, hmiDisplayLanguage); msg.setCorrelationID(correlationID); sendRPCRequest(msg); } /** * Used to push a binary stream of file data onto the module from a mobile device. * Responses are captured through callback on IProxyListener. * * @param is - The input stream of byte data that putFileStream will read from * @param sdlFileName - The file reference name used by the putFile RPC. * @param iOffset - The data offset in bytes, a value of zero is used to indicate data starting from the beginging of the file. * A value greater than zero is used for resuming partial data chunks. * @param iLength - The total length of the file being sent. * @throws SdlException if an unrecoverable error is encountered * @see #putFileStream(InputStream, String, Long, Long) */ @SuppressWarnings("unused") @Deprecated public void putFileStream(InputStream is, @NonNull String sdlFileName, Integer iOffset, Integer iLength) throws SdlException { PutFile msg = new PutFile(sdlFileName, FileType.BINARY); msg.setCorrelationID(10000); msg.setSystemFile(true); msg.setOffset(iOffset); msg.setLength(iLength); startRPCStream(is, msg); } /** * Used to push a binary stream of file data onto the module from a mobile * device. Responses are captured through callback on IProxyListener. * * @param inputStream The input stream of byte data that will be read from. * @param fileName The SDL file reference name used by the RPC. * @param offset The data offset in bytes. A value of zero is used to * indicate data starting from the beginning of the file and a value greater * than zero is used for resuming partial data chunks. * @param length The total length of the file being sent. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void putFileStream(InputStream inputStream, @NonNull String fileName, Long offset, Long length) throws SdlException { PutFile msg = new PutFile(fileName, FileType.BINARY); msg.setCorrelationID(10000); msg.setSystemFile(true); msg.setOffset(offset); msg.setLength(length); startRPCStream(inputStream, msg); } /** * Used to push a binary stream of file data onto the module from a mobile device. * Responses are captured through callback on IProxyListener. * * @param sdlFileName - The file reference name used by the putFile RPC. * @param iOffset - The data offset in bytes, a value of zero is used to indicate data starting from the beginging of a file. * A value greater than zero is used for resuming partial data chunks. * @param iLength - The total length of the file being sent. * * @return OutputStream - The output stream of byte data that is written to by the app developer * @throws SdlException if an unrecoverable error is encountered * @see #putFileStream(String, Long, Long) */ @SuppressWarnings("unused") @Deprecated public OutputStream putFileStream(@NonNull String sdlFileName, Integer iOffset, Integer iLength) throws SdlException { PutFile msg = new PutFile(sdlFileName, FileType.BINARY); msg.setCorrelationID(10000); msg.setSystemFile(true); msg.setOffset(iOffset); msg.setLength(iLength); return startRPCStream(msg); } /** * Used to push a binary stream of file data onto the module from a mobile * device. Responses are captured through callback on IProxyListener. * * @param fileName The SDL file reference name used by the RPC. * @param offset The data offset in bytes. A value of zero is used to * indicate data starting from the beginning of the file and a value greater * than zero is used for resuming partial data chunks. * @param length The total length of the file being sent. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public OutputStream putFileStream(@NonNull String fileName, Long offset, Long length) throws SdlException { PutFile msg = new PutFile(fileName, FileType.BINARY); msg.setCorrelationID(10000); msg.setSystemFile(true); msg.setOffset(offset); msg.setLength(length); return startRPCStream(msg); } /** * Used to push a binary stream of file data onto the module from a mobile device. * Responses are captured through callback on IProxyListener. * * @param is - The input stream of byte data that PutFileStream will read from * @param sdlFileName - The file reference name used by the putFile RPC. * @param iOffset - The data offset in bytes, a value of zero is used to indicate data starting from the beginging of the file. * A value greater than zero is used for resuming partial data chunks. * @param iLength - The total length of the file being sent. * @param fileType - The selected file type -- see the FileType enumeration for details * @param bPersistentFile - Indicates if the file is meant to persist between sessions / ignition cycles. * @param bSystemFile - Indicates if the file is meant to be passed thru core to elsewhere on the system. * @throws SdlException if an unrecoverable error is encountered * @see #putFileStream(InputStream, String, Long, Long, FileType, Boolean, Boolean, OnPutFileUpdateListener) */ @SuppressWarnings("unused") @Deprecated public void putFileStream(InputStream is, @NonNull String sdlFileName, Integer iOffset, Integer iLength, @NonNull FileType fileType, Boolean bPersistentFile, Boolean bSystemFile) throws SdlException { PutFile msg = new PutFile(sdlFileName, fileType); msg.setCorrelationID(10000); msg.setPersistentFile(bPersistentFile); msg.setSystemFile(bSystemFile); msg.setOffset(iOffset); msg.setLength(iLength); startRPCStream(is, msg); } /** * Used to push a binary stream of file data onto the module from a mobile * device. Responses are captured through callback on IProxyListener. * * @param inputStream The input stream of byte data that will be read from. * @param fileName The SDL file reference name used by the RPC. * @param offset The data offset in bytes. A value of zero is used to * indicate data starting from the beginning of the file and a value greater * than zero is used for resuming partial data chunks. * @param length The total length of the file being sent. * @param fileType The selected file type. See the {@link FileType} enum for * details. * @param isPersistentFile Indicates if the file is meant to persist between * sessions / ignition cycles. * @param isSystemFile Indicates if the file is meant to be passed through * core to elsewhere in the system. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void putFileStream(InputStream inputStream, @NonNull String fileName, Long offset, Long length, FileType fileType, Boolean isPersistentFile, Boolean isSystemFile, OnPutFileUpdateListener cb) throws SdlException { PutFile msg = new PutFile(fileName, FileType.BINARY); msg.setCorrelationID(10000); msg.setSystemFile(true); msg.setOffset(offset); msg.setLength(length); msg.setOnPutFileUpdateListener(cb); startRPCStream(inputStream, msg); } /** * Used to push a binary stream of file data onto the module from a mobile device. * Responses are captured through callback on IProxyListener. * * @param sdlFileName - The file reference name used by the putFile RPC. * @param iOffset - The data offset in bytes, a value of zero is used to indicate data starting from the beginging of a file. * A value greater than zero is used for resuming partial data chunks. * @param iLength - The total length of the file being sent. * @param fileType - The selected file type -- see the FileType enumeration for details * @param bPersistentFile - Indicates if the file is meant to persist between sessions / ignition cycles. * @param bSystemFile - Indicates if the file is meant to be passed thru core to elsewhere on the system. * @return OutputStream - The output stream of byte data that is written to by the app developer * @throws SdlException if an unrecoverable error is encountered * @see #putFileStream(String, Long, Long, FileType, Boolean, Boolean, OnPutFileUpdateListener) */ @SuppressWarnings("unused") @Deprecated public OutputStream putFileStream(@NonNull String sdlFileName, Integer iOffset, Integer iLength, @NonNull FileType fileType, Boolean bPersistentFile, Boolean bSystemFile) throws SdlException { PutFile msg = new PutFile(sdlFileName, fileType); msg.setCorrelationID(10000); msg.setPersistentFile(bPersistentFile); msg.setSystemFile(bSystemFile); msg.setOffset(iOffset); msg.setLength(iLength); return startRPCStream(msg); } /** * Used to push a binary stream of file data onto the module from a mobile * device. Responses are captured through callback on IProxyListener. * * @param fileName The SDL file reference name used by the RPC. * @param offset The data offset in bytes. A value of zero is used to * indicate data starting from the beginning of the file and a value greater * than zero is used for resuming partial data chunks. * @param length The total length of the file being sent. * @param fileType The selected file type. See the {@link FileType} enum for * details. * @param isPersistentFile Indicates if the file is meant to persist between * sessions / ignition cycles. * @param isSystemFile Indicates if the file is meant to be passed through * core to elsewhere in the system. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public OutputStream putFileStream(@NonNull String fileName, Long offset, Long length, FileType fileType, Boolean isPersistentFile, Boolean isSystemFile, OnPutFileUpdateListener cb) throws SdlException { PutFile msg = new PutFile(fileName, FileType.BINARY); msg.setCorrelationID(10000); msg.setSystemFile(true); msg.setOffset(offset); msg.setLength(length); msg.setOnPutFileUpdateListener(cb); return startRPCStream(msg); } /** * Used to push a stream of putfile RPC's containing binary data from a mobile device to the module. * Responses are captured through callback on IProxyListener. * * @param sPath - The physical file path on the mobile device. * @param sdlFileName - The file reference name used by the putFile RPC. * @param iOffset - The data offset in bytes, a value of zero is used to indicate data starting from the beginging of a file. * A value greater than zero is used for resuming partial data chunks. * @param fileType - The selected file type -- see the FileType enumeration for details * @param bPersistentFile - Indicates if the file is meant to persist between sessions / ignition cycles. * @param bSystemFile - Indicates if the file is meant to be passed thru core to elsewhere on the system. * @param iCorrelationID - A unique ID that correlates each RPCRequest and RPCResponse. * @return RPCStreamController - If the putFileStream was not started successfully null is returned, otherwise a valid object reference is returned * @throws SdlException if an unrecoverable error is encountered * @see #putFileStream(String, String, Long, FileType, Boolean, Boolean, Boolean, Integer, OnPutFileUpdateListener) */ @SuppressWarnings("unused") @Deprecated public RPCStreamController putFileStream(String sPath, @NonNull String sdlFileName, Integer iOffset, @NonNull FileType fileType, Boolean bPersistentFile, Boolean bSystemFile, Integer iCorrelationID) throws SdlException { PutFile msg = new PutFile(sdlFileName, fileType); msg.setCorrelationID(iCorrelationID); msg.setPersistentFile(bPersistentFile); msg.setSystemFile(bSystemFile); msg.setOffset(iOffset); msg.setLength(0); return startPutFileStream(sPath, msg); } /** * Used to push a binary stream of file data onto the module from a mobile * device. Responses are captured through callback on IProxyListener. * * @param path The physical file path on the mobile device. * @param fileName The SDL file reference name used by the RPC. * @param offset The data offset in bytes. A value of zero is used to * indicate data starting from the beginning of the file and a value greater * than zero is used for resuming partial data chunks. * @param fileType The selected file type. See the {@link FileType} enum for * details. * @param isPersistentFile Indicates if the file is meant to persist between * sessions / ignition cycles. * @param isSystemFile Indicates if the file is meant to be passed through * core to elsewhere in the system. * @param correlationId A unique id that correlates each RPCRequest and * RPCResponse. * @return RPCStreamController If the putFileStream was not started * successfully null is returned, otherwise a valid object reference is * returned . * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public RPCStreamController putFileStream(String path, @NonNull String fileName, Long offset, @NonNull FileType fileType, Boolean isPersistentFile, Boolean isSystemFile, Boolean isPayloadProtected, Integer correlationId, OnPutFileUpdateListener cb ) throws SdlException { PutFile msg = new PutFile(fileName, fileType); msg.setCorrelationID(correlationId); msg.setPersistentFile(isPersistentFile); msg.setSystemFile(isSystemFile); msg.setOffset(offset); msg.setLength(0L); msg.setPayloadProtected(isPayloadProtected); msg.setOnPutFileUpdateListener(cb); return startPutFileStream(path,msg); } /** * Used to push a stream of putfile RPC's containing binary data from a mobile device to the module. * Responses are captured through callback on IProxyListener. * * @param is - The input stream of byte data that putFileStream will read from. * @param sdlFileName - The file reference name used by the putFile RPC. * @param iOffset - The data offset in bytes, a value of zero is used to indicate data starting from the beginging of a file. * A value greater than zero is used for resuming partial data chunks. * @param fileType - The selected file type -- see the FileType enumeration for details * @param bPersistentFile - Indicates if the file is meant to persist between sessions / ignition cycles. * @param bSystemFile - Indicates if the file is meant to be passed thru core to elsewhere on the system. * @param iCorrelationID - A unique ID that correlates each RPCRequest and RPCResponse. * @return RPCStreamController - If the putFileStream was not started successfully null is returned, otherwise a valid object reference is returned * @throws SdlException if an unrecoverable error is encountered * @see #putFileStream(InputStream, String, Long, Long, FileType, Boolean, Boolean, Boolean, Integer) */ @SuppressWarnings("unused") @Deprecated public RPCStreamController putFileStream(InputStream is, @NonNull String sdlFileName, Integer iOffset, Integer iLength, @NonNull FileType fileType, Boolean bPersistentFile, Boolean bSystemFile, Integer iCorrelationID) throws SdlException { PutFile msg = new PutFile(sdlFileName, fileType); msg.setCorrelationID(iCorrelationID); msg.setPersistentFile(bPersistentFile); msg.setSystemFile(bSystemFile); msg.setOffset(iOffset); msg.setLength(iLength); return startPutFileStream(is, msg); } /** * Used to push a binary stream of file data onto the module from a mobile * device. Responses are captured through callback on IProxyListener. * * @param inputStream The input stream of byte data that will be read from. * @param fileName The SDL file reference name used by the RPC. * @param offset The data offset in bytes. A value of zero is used to * indicate data starting from the beginning of the file and a value greater * than zero is used for resuming partial data chunks. * @param length The total length of the file being sent. * @param fileType The selected file type. See the {@link FileType} enum for * details. * @param isPersistentFile Indicates if the file is meant to persist between * sessions / ignition cycles. * @param isSystemFile Indicates if the file is meant to be passed through * core to elsewhere in the system. * @param correlationId A unique id that correlates each RPCRequest and * RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public RPCStreamController putFileStream(InputStream inputStream, @NonNull String fileName, Long offset, Long length, @NonNull FileType fileType, Boolean isPersistentFile, Boolean isSystemFile, Boolean isPayloadProtected, Integer correlationId) throws SdlException { PutFile msg = new PutFile(fileName, fileType); msg.setCorrelationID(correlationId); msg.setPersistentFile(isPersistentFile); msg.setSystemFile(isSystemFile); msg.setOffset(offset); msg.setLength(length); msg.setPayloadProtected(isPayloadProtected); return startPutFileStream(inputStream, msg); } /** * * Used to end an existing putFileStream that was previously initiated with any putFileStream method. * */ @SuppressWarnings("unused") public void endPutFileStream() { endRPCStream(); } /** * Used to push a binary data onto the SDL module from a mobile device, such as icons and album art. Not supported on first generation SDL vehicles. * Responses are captured through callback on IProxyListener. * * @param sdlFileName -File reference name. * @param fileType -Selected file type. * @param persistentFile -Indicates if the file is meant to persist between sessions / ignition cycles. * @param fileData byte array of data of the file that is to be sent * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void putfile(@NonNull String sdlFileName, @NonNull FileType fileType, Boolean persistentFile, byte[] fileData, Integer correlationID) throws SdlException { PutFile msg = new PutFile(sdlFileName, fileType); msg.setCorrelationID(correlationID); msg.setPersistentFile(persistentFile); msg.setBulkData(fileData); sendRPCRequest(msg); } /** * Used to delete a file resident on the SDL module in the app's local cache. Not supported on first generation SDL vehicles. * Responses are captured through callback on IProxyListener. * * @param sdlFileName -File reference name. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void deletefile(@NonNull String sdlFileName, Integer correlationID) throws SdlException { DeleteFile msg = new DeleteFile(sdlFileName); msg.setCorrelationID(correlationID); sendRPCRequest(msg); } /** * Requests the current list of resident filenames for the registered app. Not supported on first generation SDL vehicles. * Responses are captured through callback on IProxyListener. * * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void listfiles(Integer correlationID) throws SdlException { ListFiles msg = new ListFiles(); msg.setCorrelationID(correlationID); sendRPCRequest(msg); } /** * Used to set existing local file on SDL as the app's icon. Not supported on first generation SDL vehicles. * Responses are captured through callback on IProxyListener. * * @param sdlFileName -File reference name. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void setappicon(@NonNull String sdlFileName, Integer correlationID) throws SdlException { SetAppIcon msg = new SetAppIcon(sdlFileName); msg.setCorrelationID(correlationID); sendRPCRequest(msg); } /** * Set an alternate display layout. If not sent, default screen for given platform will be shown. * Responses are captured through callback on IProxyListener. * * @param displayLayout -Predefined or dynamically created screen layout. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void setdisplaylayout(@NonNull String displayLayout, Integer correlationID) throws SdlException { SetDisplayLayout msg = new SetDisplayLayout(displayLayout); msg.setCorrelationID(correlationID); sendRPCRequest(msg); } /** * Set an alternate display layout. If not sent, default screen for given platform will be shown. * Responses are captured through callback on IProxyListener. * * @param displayLayout -Predefined or dynamically created screen layout. * @param dayColorScheme a TemplateColorScheme object representing the colors that will be used for day color scheme * @param nightColorScheme a TemplateColorScheme object representing the colors that will be used for night color scheme * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void setdisplaylayout(String displayLayout, TemplateColorScheme dayColorScheme, TemplateColorScheme nightColorScheme, Integer correlationID) throws SdlException { SetDisplayLayout msg = new SetDisplayLayout(displayLayout); msg.setCorrelationID(correlationID); msg.setDayColorScheme(dayColorScheme); msg.setNightColorScheme(nightColorScheme); sendRPCRequest(msg); } /** * Gets the SystemCapabilityManager. <br> * @return a SystemCapabilityManager object */ public SystemCapabilityManager getSystemCapabilityManager() { return _systemCapabilityManager; } @SuppressWarnings("unused") public boolean isCapabilitySupported(SystemCapabilityType systemCapabilityType) { return _systemCapabilityManager != null && _systemCapabilityManager.isCapabilitySupported(systemCapabilityType); } @SuppressWarnings("unused") public void getCapability(SystemCapabilityType systemCapabilityType, OnSystemCapabilityListener scListener){ if(_systemCapabilityManager != null){ _systemCapabilityManager.getCapability(systemCapabilityType, scListener); } } @SuppressWarnings("unused") public Object getCapability(SystemCapabilityType systemCapabilityType){ if(_systemCapabilityManager != null ){ return _systemCapabilityManager.getCapability(systemCapabilityType); }else{ return null; } } /** * Add a listener to be called whenever a new capability is retrieved * @param systemCapabilityType Type of capability desired * @param listener callback to execute upon retrieving capability */ public void addOnSystemCapabilityListener(final SystemCapabilityType systemCapabilityType, final OnSystemCapabilityListener listener) { if(_systemCapabilityManager != null){ _systemCapabilityManager.addOnSystemCapabilityListener(systemCapabilityType, listener); } } /** * Remove an OnSystemCapabilityListener that was previously added * @param systemCapabilityType Type of capability * @param listener the listener that should be removed */ public boolean removeOnSystemCapabilityListener(final SystemCapabilityType systemCapabilityType, final OnSystemCapabilityListener listener){ if(_systemCapabilityManager != null){ return _systemCapabilityManager.removeOnSystemCapabilityListener(systemCapabilityType, listener); } return false; } /** * Gets type of transport currently used by this SdlProxy. * * @return One of TransportType enumeration values. * * @see TransportType */ @SuppressWarnings("unused") public TransportType getCurrentTransportType() throws IllegalStateException { if (sdlSession == null) { throw new IllegalStateException("Incorrect state of SdlProxyBase: Calling for getCurrentTransportType() while connection is not initialized"); } return sdlSession.getCurrentTransportType(); } public void setSdlSecurityClassList(List<Class<? extends SdlSecurityBase>> list) { _secList = list; } private void setSdlSecurity(SdlSecurityBase sec) { if (sdlSession != null) { sdlSession.setSdlSecurity(sec); } } /** * Sets the minimum protocol version that will be permitted to connect. * If the protocol version of the head unit connected is below this version, * the app will disconnect with an EndService protocol message and will not register. * @param minimumProtocolVersion */ public void setMinimumProtocolVersion(Version minimumProtocolVersion){ this.minimumProtocolVersion = minimumProtocolVersion; } /** * The minimum RPC version that will be permitted to connect. * If the RPC version of the head unit connected is below this version, an UnregisterAppInterface will be sent. * @param minimumRPCVersion */ public void setMinimumRPCVersion(Version minimumRPCVersion){ this.minimumRPCVersion = minimumRPCVersion; } @SuppressWarnings("unused") public boolean isServiceTypeProtected(SessionType sType) { return sdlSession != null && sdlSession.isServiceProtected(sType); } public void addServiceListener(SessionType serviceType, ISdlServiceListener sdlServiceListener){ if(serviceType != null && sdlSession != null && sdlServiceListener != null){ sdlSession.addServiceListener(serviceType, sdlServiceListener); } } public void removeServiceListener(SessionType serviceType, ISdlServiceListener sdlServiceListener){ if(serviceType != null && sdlSession != null && sdlServiceListener != null){ sdlSession.removeServiceListener(serviceType, sdlServiceListener); } } @SuppressWarnings("unused") public VideoStreamingParameters getAcceptedVideoParams(){ return sdlSession.getAcceptedVideoParams(); } public IProxyListenerBase getProxyListener() { return _proxyListener; } @SuppressWarnings("unused") public String getAppName() { return _applicationName; } @SuppressWarnings("unused") public String getNgnAppName() { return _ngnMediaScreenAppName; } @SuppressWarnings("unused") public String getAppID() { return _appID; } @SuppressWarnings("unused") public DeviceInfo getDeviceInfo() { return deviceInfo; } @SuppressWarnings("unused") public long getInstanceDT() { return instanceDateTime; } @SuppressWarnings("unused") public void setConnectionDetails(String sDetails) { sConnectionDetails = sDetails; } @SuppressWarnings("unused") public String getConnectionDetails() { return sConnectionDetails; } //for testing only @SuppressWarnings("unused") public void setPoliciesURL(String sText) { sPoliciesURL = sText; } //for testing only public String getPoliciesURL() { return sPoliciesURL; } /** * Tells developer whether or not their app icon has been resumed on core. * @return boolean - true if icon was resumed, false if not * @throws SdlException if proxy is disposed or app is not registered */ public boolean getIconResumed() throws SdlException { // Test if proxy has been disposed if (_proxyDisposed) { throw new SdlException("This object has been disposed, it is no long capable of executing methods.", SdlExceptionCause.SDL_PROXY_DISPOSED); } // Test SDL availability if (!_appInterfaceRegisterd) { throw new SdlException("SDL is not connected. Unable to determine if app icon was resumed.", SdlExceptionCause.SDL_UNAVAILABLE); } return _iconResumed; } /** * Method to retrieve the RegisterAppInterface Response message that was sent back from the * module. It contains various attributes about the connected module and can be used to adapt * to different module types and their supported features. * * @return RegisterAppInterfaceResponse received from the module or null if the app has not yet * registered with the module. */ public RegisterAppInterfaceResponse getRegisterAppInterfaceResponse(){ return this.raiResponse; } /** * Get the current OnHMIStatus * @return OnHMIStatus object represents the current OnHMIStatus */ public OnHMIStatus getCurrentHMIStatus(){ return lastHmiStatus; } /** * Retrieves the auth token, if any, that was attached to the StartServiceACK for the RPC * service from the module. For example, this should be used to login to a user account. * @return the string representation of the auth token */ public String getAuthToken(){ return this.authToken; } /** * VideoStreamingManager houses all the elements needed to create a scoped, streaming manager for video projection. It is only a private, instance * dependant class at the moment until it can become public. Once the class is public and API defined, it will be moved into the SdlSession class */ @TargetApi(19) private class VideoStreamingManager implements ISdlServiceListener{ Context context; ISdl internalInterface; volatile VirtualDisplayEncoder encoder; private Class<? extends SdlRemoteDisplay> remoteDisplayClass = null; SdlRemoteDisplay remoteDisplay; IVideoStreamListener streamListener; float[] touchScalar = {1.0f,1.0f}; //x, y private HapticInterfaceManager hapticManager; SdlMotionEvent sdlMotionEvent = null; VideoStreamingParameters videoStreamingParameters; public VideoStreamingManager(Context context,ISdl iSdl){ this.context = context; this.internalInterface = iSdl; encoder = new VirtualDisplayEncoder(); internalInterface.addServiceListener(SessionType.NAV,this); //Take care of the touch events internalInterface.addOnRPCNotificationListener(FunctionID.ON_TOUCH_EVENT, new OnRPCNotificationListener() { @Override public void onNotified(RPCNotification notification) { if (notification != null && remoteDisplay != null) { List<MotionEvent> events = convertTouchEvent((OnTouchEvent) notification); if (events != null && !events.isEmpty()) { for (MotionEvent ev : events) { remoteDisplay.handleMotionEvent(ev); } } } } }); } /** * Starts the video service, caches the supplied params and prepares for the stream to start. * @param remoteDisplayClass the extension of SdlRemoteDisplay that will be streamed * @param parameters desired video streaming params * @param encrypted if the service is to be encrypted or not */ public void startVideoStreaming(Class<? extends SdlRemoteDisplay> remoteDisplayClass, VideoStreamingParameters parameters, boolean encrypted){ this.remoteDisplayClass = remoteDisplayClass; this.videoStreamingParameters = parameters; //Make sure the service is started, allows multi transports to connect and register without timing out internalInterface.startVideoService(parameters, encrypted); //After this, look to the } /** * The video service should already be started at this point. Once called, it will start * the encoders and fire up the remote display supplied by the user * @param parameters * @param encrypted */ private void startStream(VideoStreamingParameters parameters, boolean encrypted){ //Start the service first //streamListener = startVideoStream(encrypted,parameters);d streamListener = sdlSession.startVideoStream(); if(streamListener == null){ Log.e(TAG, "Error starting video service"); return; } VideoStreamingCapability capability = (VideoStreamingCapability)_systemCapabilityManager.getCapability(SystemCapabilityType.VIDEO_STREAMING); if(capability != null && capability.getIsHapticSpatialDataSupported()){ hapticManager = new HapticInterfaceManager(internalInterface); } try { encoder.init(context, streamListener, parameters); //We are all set so we can start streaming at at this point encoder.start(); //Encoder should be up and running createRemoteDisplay(encoder.getVirtualDisplay()); } catch (Exception e) { e.printStackTrace(); } Log.d(TAG, parameters.toString()); } public void stopStreaming(){ if(remoteDisplay!=null){ remoteDisplay.stop(); remoteDisplay = null; } if(encoder!=null){ encoder.shutDown(); } if(internalInterface!=null){ internalInterface.stopVideoService(); } } public void dispose(){ stopStreaming(); internalInterface.removeServiceListener(SessionType.NAV,this); } private void createRemoteDisplay(final Display disp){ try{ if (disp == null){ return; } // Dismiss the current presentation if the display has changed. if (remoteDisplay != null && remoteDisplay.getDisplay() != disp) { remoteDisplay.dismissPresentation(); } FutureTask<Boolean> fTask = new FutureTask<Boolean>( new SdlRemoteDisplay.Creator(context, disp, remoteDisplay, remoteDisplayClass, new SdlRemoteDisplay.Callback(){ @Override public void onCreated(final SdlRemoteDisplay remoteDisplay) { //Remote display has been created. //Now is a good time to do parsing for spatial data SdlProxyBase.VideoStreamingManager.this.remoteDisplay = remoteDisplay; if(hapticManager != null) { remoteDisplay.getMainView().post(new Runnable() { @Override public void run() { hapticManager.refreshHapticData(remoteDisplay.getMainView()); } }); } //Get touch scalars ImageResolution resolution = null; if(protocolVersion!= null && protocolVersion.getMajor()>=5){ //At this point we should already have the capability VideoStreamingCapability capability = (VideoStreamingCapability)_systemCapabilityManager.getCapability(SystemCapabilityType.VIDEO_STREAMING); if (capability != null) { resolution = capability.getPreferredResolution(); } } if(resolution == null){ //Either the protocol version is too low to access video streaming caps, or they were null DisplayCapabilities dispCap = (DisplayCapabilities) internalInterface.getCapability(SystemCapabilityType.DISPLAY); if (dispCap != null) { resolution = (dispCap.getScreenParams().getImageResolution()); } } if(resolution != null){ DisplayMetrics displayMetrics = new DisplayMetrics(); disp.getMetrics(displayMetrics); touchScalar[0] = ((float)displayMetrics.widthPixels) / resolution.getResolutionWidth(); touchScalar[1] = ((float)displayMetrics.heightPixels) / resolution.getResolutionHeight(); } } @Override public void onInvalidated(final SdlRemoteDisplay remoteDisplay) { //Our view has been invalidated //A good time to refresh spatial data if(hapticManager != null) { remoteDisplay.getMainView().post(new Runnable() { @Override public void run() { hapticManager.refreshHapticData(remoteDisplay.getMainView()); } }); } } } )); Thread showPresentation = new Thread(fTask); showPresentation.start(); } catch (Exception ex) { Log.e(TAG, "Unable to create Virtual Display."); } } @Override public void onServiceStarted(SdlSession session, SessionType type, boolean isEncrypted) { if(SessionType.NAV.equals(type) && session != null ){ DebugTool.logInfo("Video service has been started. Starting video stream from proxy"); if(session.getAcceptedVideoParams() != null){ videoStreamingParameters = session.getAcceptedVideoParams(); } startStream(videoStreamingParameters, isEncrypted); } } @Override public void onServiceEnded(SdlSession session, SessionType type) { if(SessionType.NAV.equals(type)){ if(remoteDisplay!=null){ stopStreaming(); } } } @Override public void onServiceError(SdlSession session, SessionType type, String reason) { } private List<MotionEvent> convertTouchEvent(OnTouchEvent onTouchEvent) { List<MotionEvent> motionEventList = new ArrayList<MotionEvent>(); List<TouchEvent> touchEventList = onTouchEvent.getEvent(); if (touchEventList == null || touchEventList.size() == 0) return null; TouchType touchType = onTouchEvent.getType(); if (touchType == null) { return null; } if (sdlMotionEvent == null) { if (touchType == TouchType.BEGIN) { sdlMotionEvent = new SdlMotionEvent(); } else { return null; } } SdlMotionEvent.Pointer pointer; MotionEvent motionEvent; for (TouchEvent touchEvent : touchEventList) { if (touchEvent == null || touchEvent.getId() == null) { continue; } List<TouchCoord> touchCoordList = touchEvent.getTouchCoordinates(); if (touchCoordList == null || touchCoordList.size() == 0) { continue; } TouchCoord touchCoord = touchCoordList.get(touchCoordList.size() - 1); if (touchCoord == null) { continue; } int motionEventAction = sdlMotionEvent.getMotionEventAction(touchType, touchEvent); long downTime = sdlMotionEvent.downTime; long eventTime = sdlMotionEvent.eventTime; pointer = sdlMotionEvent.getPointerById(touchEvent.getId()); if (pointer != null) { pointer.setCoords(touchCoord.getX() * touchScalar[0], touchCoord.getY() * touchScalar[1]); } MotionEvent.PointerProperties[] pointerProperties = new MotionEvent.PointerProperties[sdlMotionEvent.pointers.size()]; MotionEvent.PointerCoords[] pointerCoords = new MotionEvent.PointerCoords[sdlMotionEvent.pointers.size()]; for (int i = 0; i < sdlMotionEvent.pointers.size(); i++) { pointerProperties[i] = new MotionEvent.PointerProperties(); pointerProperties[i].id = sdlMotionEvent.getPointerByIndex(i).id; pointerProperties[i].toolType = MotionEvent.TOOL_TYPE_FINGER; pointerCoords[i] = new MotionEvent.PointerCoords(); pointerCoords[i].x = sdlMotionEvent.getPointerByIndex(i).x; pointerCoords[i].y = sdlMotionEvent.getPointerByIndex(i).y; pointerCoords[i].orientation = 0; pointerCoords[i].pressure = 1.0f; pointerCoords[i].size = 1; } motionEvent = MotionEvent.obtain(downTime, eventTime, motionEventAction, sdlMotionEvent.pointers.size(), pointerProperties, pointerCoords, 0, 0, 1, 1, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0); motionEventList.add(motionEvent); if (motionEventAction == MotionEvent.ACTION_UP || motionEventAction == MotionEvent.ACTION_CANCEL) { //If the motion event should be finished we should clear our reference sdlMotionEvent.pointers.clear(); sdlMotionEvent = null; break; } else if ((motionEventAction & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_POINTER_UP) { sdlMotionEvent.removePointerById(touchEvent.getId()); } } return motionEventList; } } /** * Keeps track of the current motion event for VPM */ private static class SdlMotionEvent { class Pointer { int id; float x; float y; Pointer(int id) { this.id = id; this.x = 0.0f; this.y = 0.0f; } void setCoords(float x, float y) { this.x = x; this.y = y; } } private CopyOnWriteArrayList<Pointer> pointers = new CopyOnWriteArrayList<>(); private long downTime; private long downTimeOnHMI; private long eventTime; SdlMotionEvent() { downTimeOnHMI = 0; } /** * Handles the SDL Touch Event to keep track of pointer status and returns the appropriate * Android MotionEvent according to this events status * * @param touchType The SDL TouchType that was received from the module * @param touchEvent The SDL TouchEvent that was received from the module * @return the correct native Android MotionEvent action to dispatch */ synchronized int getMotionEventAction(TouchType touchType, TouchEvent touchEvent) { eventTime = 0; int motionEventAction = -1; switch (touchType) { case BEGIN: if (pointers.size() == 0) { //The motion event has just begun motionEventAction = MotionEvent.ACTION_DOWN; downTime = SystemClock.uptimeMillis(); downTimeOnHMI = touchEvent.getTimestamps().get(touchEvent.getTimestamps().size() - 1); eventTime = downTime; } else { motionEventAction = MotionEvent.ACTION_POINTER_DOWN | pointers.size() << MotionEvent.ACTION_POINTER_INDEX_SHIFT; eventTime = downTime + touchEvent.getTimestamps().get(touchEvent.getTimestamps().size() - 1) - downTimeOnHMI; } pointers.add(new Pointer(touchEvent.getId())); break; case MOVE: motionEventAction = MotionEvent.ACTION_MOVE; eventTime = downTime + touchEvent.getTimestamps().get(touchEvent.getTimestamps().size() - 1) - downTimeOnHMI; break; case END: if(pointers.size() <= 1){ //The motion event has just ended motionEventAction = MotionEvent.ACTION_UP; } else { int pointerIndex = pointers.indexOf(getPointerById(touchEvent.getId())); if (pointerIndex != -1) { motionEventAction = MotionEvent.ACTION_POINTER_UP | pointerIndex << MotionEvent.ACTION_POINTER_INDEX_SHIFT; } else { motionEventAction = MotionEvent.ACTION_UP; } } eventTime = downTime + touchEvent.getTimestamps().get(touchEvent.getTimestamps().size() - 1) - downTimeOnHMI; break; case CANCEL: //Assuming this cancels the entire event motionEventAction = MotionEvent.ACTION_CANCEL; eventTime = downTime + touchEvent.getTimestamps().get(touchEvent.getTimestamps().size() - 1) - downTimeOnHMI; break; default: break; } return motionEventAction; } Pointer getPointerById(int id) { if (pointers != null && !pointers.isEmpty()) { for (Pointer pointer : pointers) { if (pointer.id == id) { return pointer; } } } return null; } Pointer getPointerByIndex(int index) { return pointers.get(index); } void removePointerById(int id) { pointers.remove(getPointerById(id)); } } } // end-class
package io.keen.client.android; import io.keen.client.java.KeenNetworkStatusHandler; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.Manifest; import android.content.pm.PackageManager; import java.lang.Override; /** * This class implements the KeenNetworkStatusHandler. It uses the available * native android functions for checking the network status. * * @author Simon Murtha Smith * @since 2.1.0 */ public class AndroidNetworkStatusHandler implements KeenNetworkStatusHandler { private final Context context; public AndroidNetworkStatusHandler(Context context) { this.context = context; } @Override public boolean isNetworkConnected() { boolean canCheckNetworkState = context.checkCallingOrSelfPermission(Manifest.permission.ACCESS_NETWORK_STATE) == PackageManager.PERMISSION_GRANTED; if (!canCheckNetworkState) return true; // Check if there is an active network connection ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } }
package org.appcelerator.titanium.proxy; import org.appcelerator.kroll.KrollProxy; import org.appcelerator.kroll.annotations.Kroll; import org.appcelerator.titanium.TiApplication; import org.appcelerator.titanium.TiC; import org.appcelerator.titanium.util.TiFileHelper; import org.appcelerator.titanium.util.TiUrl; import android.app.ActionBar; import android.app.Activity; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Message; @Kroll.proxy(propertyAccessors = { TiC.PROPERTY_ON_HOME_ICON_ITEM_SELECTED }) public class ActionBarProxy extends KrollProxy { private static final int MSG_FIRST_ID = KrollProxy.MSG_LAST_ID + 1; private static final int MSG_DISPLAY_HOME_AS_UP = MSG_FIRST_ID + 100; private static final int MSG_SET_BACKGROUND_IMAGE = MSG_FIRST_ID + 101; private static final int MSG_SET_TITLE = MSG_FIRST_ID + 102; private static final int MSG_SHOW = MSG_FIRST_ID + 103; private static final int MSG_HIDE = MSG_FIRST_ID + 104; private static final int MSG_SET_LOGO = MSG_FIRST_ID + 105; private static final int MSG_SET_ICON = MSG_FIRST_ID + 106; private static final int MSG_SET_HOME_BUTTON_ENABLED = MSG_FIRST_ID + 107; private static final int MSG_SET_NAVIGATION_MODE = MSG_FIRST_ID + 108; private static final String SHOW_HOME_AS_UP = "showHomeAsUp"; private static final String BACKGROUND_IMAGE = "backgroundImage"; private static final String TITLE = "title"; private static final String LOGO = "logo"; private static final String ICON = "icon"; private static final String NAVIGATION_MODE = "navigationMode"; private ActionBar actionBar; public ActionBarProxy(Activity activity) { super(); actionBar = activity.getActionBar(); } @Kroll.method @Kroll.setProperty public void setDisplayHomeAsUp(boolean showHomeAsUp) { if(TiApplication.isUIThread()) { handlesetDisplayHomeAsUp(showHomeAsUp); } else { Message message = getMainHandler().obtainMessage(MSG_DISPLAY_HOME_AS_UP, showHomeAsUp); message.getData().putBoolean(SHOW_HOME_AS_UP, showHomeAsUp); message.sendToTarget(); } } @Kroll.method @Kroll.setProperty public void setNavigationMode(int navigationMode) { if (TiApplication.isUIThread()) { handlesetNavigationMode(navigationMode); } else { Message message = getMainHandler().obtainMessage(MSG_SET_NAVIGATION_MODE, navigationMode); message.getData().putInt(NAVIGATION_MODE, navigationMode); message.sendToTarget(); } } @Kroll.method @Kroll.setProperty public void setBackgroundImage(String url) { if (TiApplication.isUIThread()) { handleSetBackgroundImage(url); } else { Message message = getMainHandler().obtainMessage(MSG_SET_BACKGROUND_IMAGE, url); message.getData().putString(BACKGROUND_IMAGE, url); message.sendToTarget(); } } @Kroll.method @Kroll.setProperty public void setTitle(String title) { if (TiApplication.isUIThread()) { handleSetTitle(title); } else { Message message = getMainHandler().obtainMessage(MSG_SET_TITLE, title); message.getData().putString(TITLE, title); message.sendToTarget(); } } @Kroll.method @Kroll.getProperty public String getTitle() { if (actionBar == null) { return null; } return (String) actionBar.getTitle(); } @Kroll.method @Kroll.getProperty public int getNavigationMode() { if (actionBar == null) { return 0; } return (int) actionBar.getNavigationMode(); } @Kroll.method public void show() { if (TiApplication.isUIThread()) { handleShow(); } else { getMainHandler().obtainMessage(MSG_SHOW).sendToTarget(); } } @Kroll.method public void hide() { if (TiApplication.isUIThread()) { handleHide(); } else { getMainHandler().obtainMessage(MSG_HIDE).sendToTarget(); } } @Kroll.method @Kroll.setProperty public void setLogo(String url) { if (Build.VERSION.SDK_INT >= TiC.API_LEVEL_ICE_CREAM_SANDWICH) { if (TiApplication.isUIThread()) { handleSetLogo(url); } else { Message message = getMainHandler().obtainMessage(MSG_SET_LOGO, url); message.getData().putString(LOGO, url); message.sendToTarget(); } } } @Kroll.method @Kroll.setProperty public void setIcon(String url) { if (Build.VERSION.SDK_INT >= TiC.API_LEVEL_ICE_CREAM_SANDWICH) { if (TiApplication.isUIThread()) { handleSetIcon(url); } else { Message message = getMainHandler().obtainMessage(MSG_SET_ICON, url); message.getData().putString(ICON, url); message.sendToTarget(); } } } private void handleSetIcon(String url) { Drawable icon = getDrawableFromUrl(url); if (icon != null) { actionBar.setIcon(icon); } } private void handleSetTitle(String title) { actionBar.setDisplayShowTitleEnabled(true); actionBar.setTitle(title); } private void handleShow() { actionBar.show(); } private void handleHide() { actionBar.hide(); } private void handleSetBackgroundImage(String url) { Drawable backgroundImage = getDrawableFromUrl(url); if (backgroundImage != null) { actionBar.setBackgroundDrawable(backgroundImage); } } private void handlesetDisplayHomeAsUp(boolean showHomeAsUp) { actionBar.setDisplayHomeAsUpEnabled(showHomeAsUp); } private void handlesetNavigationMode(int navigationMode) { actionBar.setNavigationMode(navigationMode); } private void handleSetLogo(String url) { Drawable logo = getDrawableFromUrl(url); if (logo != null) { actionBar.setLogo(logo); } } private Drawable getDrawableFromUrl(String url) { TiUrl imageUrl = new TiUrl((String) url); TiFileHelper tfh = new TiFileHelper(TiApplication.getInstance()); return tfh.loadDrawable(imageUrl.resolve(), false); } @Override public boolean handleMessage(Message msg) { switch (msg.what) { case MSG_DISPLAY_HOME_AS_UP: handlesetDisplayHomeAsUp(msg.getData().getBoolean(SHOW_HOME_AS_UP)); return true; case MSG_SET_NAVIGATION_MODE: handlesetNavigationMode(msg.getData().getInt(NAVIGATION_MODE)); return true; case MSG_SET_BACKGROUND_IMAGE: handleSetBackgroundImage(msg.getData().getString(BACKGROUND_IMAGE)); return true; case MSG_SET_TITLE: handleSetTitle(msg.getData().getString(TITLE)); return true; case MSG_SHOW: handleShow(); return true; case MSG_HIDE: handleHide(); return true; case MSG_SET_LOGO: handleSetLogo(msg.getData().getString(LOGO)); return true; case MSG_SET_ICON: handleSetIcon(msg.getData().getString(ICON)); return true; case MSG_SET_HOME_BUTTON_ENABLED: actionBar.setHomeButtonEnabled(true); return true; } return super.handleMessage(msg); } @Override public void onPropertyChanged(String name, Object value) { if (Build.VERSION.SDK_INT >= TiC.API_LEVEL_ICE_CREAM_SANDWICH && TiC.PROPERTY_ON_HOME_ICON_ITEM_SELECTED.equals(name)) { // If we have a listener on the home icon item, then enable the home button (we need to do this for ICS and // above) if (TiApplication.isUIThread()) { actionBar.setHomeButtonEnabled(true); } else { getMainHandler().obtainMessage(MSG_SET_HOME_BUTTON_ENABLED).sendToTarget(); } } super.onPropertyChanged(name, value); } }
package org.sagebionetworks.bridge.play.controllers; import static org.apache.commons.lang3.StringUtils.isNotBlank; import static org.sagebionetworks.bridge.BridgeConstants.STUDY_PROPERTY; import java.util.Collections; import org.sagebionetworks.bridge.BridgeConstants; import org.sagebionetworks.bridge.Roles; import org.sagebionetworks.bridge.exceptions.ConcurrentModificationException; import org.sagebionetworks.bridge.exceptions.ConsentRequiredException; import org.sagebionetworks.bridge.exceptions.EntityNotFoundException; import org.sagebionetworks.bridge.json.JsonUtils; import org.sagebionetworks.bridge.models.CriteriaContext; import org.sagebionetworks.bridge.models.accounts.Email; import org.sagebionetworks.bridge.models.accounts.EmailVerification; import org.sagebionetworks.bridge.models.accounts.PasswordReset; import org.sagebionetworks.bridge.models.accounts.SignIn; import org.sagebionetworks.bridge.models.accounts.StudyParticipant; import org.sagebionetworks.bridge.models.accounts.UserSession; import org.sagebionetworks.bridge.models.accounts.UserSessionInfo; import org.sagebionetworks.bridge.models.studies.Study; import org.sagebionetworks.bridge.models.studies.StudyIdentifier; import org.sagebionetworks.bridge.models.studies.StudyIdentifierImpl; import org.springframework.stereotype.Controller; import play.mvc.Result; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; @Controller public class AuthenticationController extends BaseController { public Result signIn() throws Exception { return signInWithRetry(5); } public Result signOut() throws Exception { final UserSession session = getSessionIfItExists(); if (session != null) { authenticationService.signOut(session); } response().discardCookie(BridgeConstants.SESSION_TOKEN_HEADER); return okResult("Signed out."); } public Result signUp() throws Exception { JsonNode json = requestToJSON(request()); StudyParticipant participant = parseJson(request(), StudyParticipant.class); // You cannot set roles through the signUp() method. if (!participant.getRoles().isEmpty()) { participant = new StudyParticipant.Builder().copyOf(participant).withRoles(ImmutableSet.of()).build(); } Study study = getStudyOrThrowException(json); authenticationService.signUp(study, participant, true); return createdResult("Signed up."); } public Result verifyEmail() throws Exception { JsonNode json = requestToJSON(request()); EmailVerification emailVerification = parseJson(request(), EmailVerification.class); Study study = getStudyOrThrowException(json); CriteriaContext context = getCriteriaContext(study.getStudyIdentifier()); UserSession session = authenticationService.verifyEmail(study, context, emailVerification); writeSessionInfoToMetrics(session); setSessionToken(session.getSessionToken()); // In normal course of events (verify email, consent to research), // an exception is thrown. Code after this line will rarely execute if (!session.getUser().doesConsent()) { throw new ConsentRequiredException(session); } return okResult(new UserSessionInfo(session)); } public Result resendEmailVerification() throws Exception { JsonNode json = requestToJSON(request()); Email email = parseJson(request(), Email.class); StudyIdentifier studyIdentifier = getStudyIdentifierOrThrowException(json); authenticationService.resendEmailVerification(studyIdentifier, email); return okResult("If registered with the study, we'll email you instructions on how to verify your account."); } public Result requestResetPassword() throws Exception { JsonNode json = requestToJSON(request()); Email email = parseJson(request(), Email.class); Study study = getStudyOrThrowException(json); authenticationService.requestResetPassword(study, email); return okResult("If registered with the study, we'll email you instructions on how to change your password."); } public Result resetPassword() throws Exception { PasswordReset passwordReset = parseJson(request(), PasswordReset.class); authenticationService.resetPassword(passwordReset); return okResult("Password has been changed."); } /** * Retries sign-in on lock. * * @param retryCounter the number of retries, excluding the initial try */ private Result signInWithRetry(int retryCounter) throws Exception { UserSession session = getSessionIfItExists(); if (session == null) { JsonNode json = requestToJSON(request()); SignIn signIn = parseJson(request(), SignIn.class); Study study = getStudyOrThrowException(json); CriteriaContext context = getCriteriaContext(study.getStudyIdentifier()); try { session = authenticationService.signIn(study, context, signIn); } catch (ConcurrentModificationException e) { if (retryCounter > 0) { final long retryDelayInMillis = 200; Thread.sleep(retryDelayInMillis); return signInWithRetry(retryCounter - 1); } throw e; } writeSessionInfoToMetrics(session); } // Set session token. This way, even if we get a ConsentRequiredException, users are still able to sign consent setSessionToken(session.getSessionToken()); // You can proceed if 1) you're some kind of system administrator (developer, researcher), or 2) // you've consented to research. if (!session.getUser().doesConsent() && !session.getUser().isInRole(Roles.ADMINISTRATIVE_ROLES)) { throw new ConsentRequiredException(session); } return okResult(new UserSessionInfo(session)); } /** * Unauthenticated calls that require a study (most of the calls not requiring authentication, including this one), * should include the study identifier as part of the JSON payload. This call handles such JSON and converts it to a * study. As a fallback for existing clients, it also looks for the study information in the query string or * headers. If the study cannot be found in any of these places, it throws an exception, because the API will not * work correctly without it. * * @param email * @return */ private Study getStudyOrThrowException(JsonNode node) { String studyId = getStudyStringOrThrowException(node); Study study = studyService.getStudy(studyId); verifySupportedVersionOrThrowException(study); return study; } private StudyIdentifier getStudyIdentifierOrThrowException(JsonNode node) { String studyId = getStudyStringOrThrowException(node); return new StudyIdentifierImpl(studyId); } private String getStudyStringOrThrowException(JsonNode node) { String studyId = JsonUtils.asText(node, STUDY_PROPERTY); if (isNotBlank(studyId)) { return studyId; } throw new EntityNotFoundException(Study.class); } }
package aashrai.android.gettowork.model; import aashrai.android.gettowork.di.SettingsScope; import aashrai.android.gettowork.utils.Utils; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import com.fernandocejas.frodo.annotation.RxLogObservable; import java.util.List; import javax.inject.Inject; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers; @SettingsScope public class ApplicationInfoFetcher { private final Context context; @Inject public ApplicationInfoFetcher(Context context) { this.context = context; } @RxLogObservable public Observable<List<ApplicationInfo>> getAllApplications() { return Observable.from( context.getPackageManager().getInstalledApplications(PackageManager.GET_META_DATA)) .observeOn(Schedulers.computation()) .filter(Utils.removeSelfPackage(context)) .filter(Utils.removeLaunchers(context)) .filter(Utils.removeSystemApps()) .toSortedList(Utils.getApplicationSortFunction(context)) .observeOn(AndroidSchedulers.mainThread()) .cache(); } public Observable<List<ApplicationInfo>> getFilteredApplications(String query) { return getAllApplications().flatMap( new Func1<List<ApplicationInfo>, Observable<ApplicationInfo>>() { @Override public Observable<ApplicationInfo> call(List<ApplicationInfo> applicationInfoList) { return Observable.from(applicationInfoList); } }) .observeOn(Schedulers.computation()) .filter(new PackageQueryFilter(context, query)) .toList() .observeOn(AndroidSchedulers.mainThread()); } private static class PackageQueryFilter implements Func1<ApplicationInfo, Boolean> { private final Context context; private final String query; private PackageQueryFilter(Context context, String query) { this.query = query.toLowerCase().trim(); this.context = context; } @Override public Boolean call(ApplicationInfo applicationInfo) { return query.isEmpty() || Utils.getApplicationName(applicationInfo, context).contains(query); } } }
package com.commit451.gitlab.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.commit451.gitlab.LabCoatApp; import com.commit451.gitlab.R; import com.commit451.gitlab.event.BuildChangedEvent; import com.commit451.gitlab.model.api.Build; import com.commit451.gitlab.model.api.Project; import com.commit451.gitlab.model.api.RepositoryCommit; import com.commit451.gitlab.model.api.Runner; import com.commit451.gitlab.util.DateUtils; import com.squareup.otto.Subscribe; import org.parceler.Parcels; import java.util.Date; import butterknife.Bind; import butterknife.ButterKnife; /** * Shows the details of a build */ public class BuildDescriptionFragment extends BaseFragment { private static final String KEY_PROJECT = "project"; private static final String KEY_BUILD = "build"; public static BuildDescriptionFragment newInstance(Project project, Build build) { BuildDescriptionFragment fragment = new BuildDescriptionFragment(); Bundle args = new Bundle(); args.putParcelable(KEY_PROJECT, Parcels.wrap(project)); args.putParcelable(KEY_BUILD, Parcels.wrap(build)); fragment.setArguments(args); return fragment; } @Bind(R.id.root) ViewGroup mRoot; @Bind(R.id.text_duration) TextView mTextDuration; @Bind(R.id.text_created) TextView mTextCreated; @Bind(R.id.text_finished) TextView mTextFinished; @Bind(R.id.text_runner) TextView mTextRunner; @Bind(R.id.text_author) TextView mTextAuthor; @Bind(R.id.text_message) TextView mTextMessage; Project mProject; Build mBuild; EventReceiver mEventReceiver; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mProject = Parcels.unwrap(getArguments().getParcelable(KEY_PROJECT)); mBuild = Parcels.unwrap(getArguments().getParcelable(KEY_BUILD)); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_build_description, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ButterKnife.bind(this, view); bindBuild(mBuild); mEventReceiver = new EventReceiver(); LabCoatApp.bus().register(mEventReceiver); } private void bindBuild(Build build) { Date finishedTime = build.getFinishedAt(); if (finishedTime == null) { finishedTime = new Date(); } String timeTaken = DateUtils.getTimeTaken(build.getStartedAt(), finishedTime); String duration = String.format(getString(R.string.build_duration), timeTaken); mTextDuration.setText(duration); String created = String.format(getString(R.string.build_created), DateUtils.getRelativeTimeSpanString(getActivity(), build.getCreatedAt())); mTextCreated.setText(created); if (build.getFinishedAt() != null) { String finished = String.format(getString(R.string.build_finished), DateUtils.getRelativeTimeSpanString(getActivity(), build.getFinishedAt())); mTextFinished.setText(finished); mTextFinished.setVisibility(View.VISIBLE); } else { mTextFinished.setVisibility(View.GONE); } bindRunner(build.getRunner()); bindCommit(build.getCommit()); } private void bindRunner(Runner runner) { String runnerNum = String.format(getString(R.string.runner_number), String.valueOf(runner.getId())); mTextRunner.setText(runnerNum); } private void bindCommit(RepositoryCommit commit) { String authorText = String.format(getString(R.string.build_commit_author), commit.getAuthorName()); mTextAuthor.setText(authorText); String messageText = String.format(getString(R.string.build_commit_message), commit.getMessage()); mTextMessage.setText(messageText); } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); LabCoatApp.bus().unregister(mEventReceiver); } private class EventReceiver { @Subscribe public void onBuildChangedEvent(BuildChangedEvent event) { if (mBuild.getId() == event.build.getId()) { mBuild = event.build; bindBuild(mBuild); } } } }
package com.example.android.popularmovies; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.view.MenuItemCompat; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.example.android.popularmovies.data.MoviesContract; import com.squareup.picasso.Picasso; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; public class MainActivityFragment extends Fragment { public ArrayList<String[]> mThumbIds; boolean recallFlag = true; String sortType; private ImageAdapter mImageAdapter; private GridView gridview; public MainActivityFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mThumbIds = new ArrayList<>(); //Initialized with dummy values to prevent on load freeze String[] arr = {"https://s5.postimg.org/b3evudzxz/blank.png", "", "", "", "", ""}; mThumbIds.add(arr); if (savedInstanceState != null) { sortType = savedInstanceState.getString("SORT_TYPE"); recallFlag = false; } else { sortType = getString(R.string.base_uri_popular); recallFlag = true; } setHasOptionsMenu(true); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.menu_fragment_main, menu); MenuItem item = menu.findItem(R.id.spinner); Spinner spinner = (Spinner) MenuItemCompat.getActionView(item); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.sort_array, R.layout.spinner_layout); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); int selection; if (sortType.equals(getString(R.string.base_uri_toprated))) { selection = 1; } else if (sortType.equals(getString(R.string.base_uri_favorites))) { selection = 2; } else { selection = 0; } spinner.setSelection(selection); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { // your code here String headerText; if (position == 0) { sortType = getString(R.string.base_uri_popular); headerText = getString(R.string.popularHeader); } else if (position == 1) { sortType = getString(R.string.base_uri_toprated); headerText = getString(R.string.topHeader); } else { sortType = getString(R.string.base_uri_favorites); headerText = getString(R.string.topFavorites); } TextView mainHeader = (TextView) getActivity().findViewById(R.id.mainHeader); mainHeader.setText(headerText); updateMovieThumbs(sortType); if (gridview != null) { gridview.setSelection(0); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); spinner.setPopupBackgroundResource(R.color.colorAccent); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_main, container, false); return v; } @Override public void onStart() { super.onStart(); if (recallFlag || sortType == getString(R.string.base_uri_favorites)) { updateMovieThumbs(sortType); } } @Override public void onSaveInstanceState(Bundle savedInstanceState) { savedInstanceState.putString("SORT_TYPE", sortType); super.onSaveInstanceState(savedInstanceState); } @Override public boolean onOptionsItemSelected(MenuItem item) { return true; } private void updateMovieThumbs(String sortType) { ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); if (isConnected || sortType == getString(R.string.base_uri_favorites)) { FetchMovieDatabase movieTask = new FetchMovieDatabase(); movieTask.execute(sortType); } else { if (gridview != null) { gridview.setAdapter(null); Toast.makeText(getActivity(), "No Internet Connection", Toast.LENGTH_SHORT).show(); } } } public interface Callback { public void onItemSelected(ArrayList<String[]> mThumbIds, int position); } public class FetchMovieDatabase extends AsyncTask<String, Void, ArrayList<String[]>> { private final String LOG_TAG = FetchMovieDatabase.class.getSimpleName(); private ArrayList<String[]> getMovieDataJson(String movieJsonStr) throws JSONException { final String RESULTS = "results"; final String ORIGINAL_TITLE = "original_title"; final String POSTER = "poster_path"; final String OVERVIEW = "overview"; final String VOTES = "vote_average"; final String RELEASE = "release_date"; final String ID = "id"; ArrayList<String[]> newThumbids = new ArrayList<String[]>(); JSONObject movieJson = new JSONObject(movieJsonStr); JSONArray movieArray = movieJson.getJSONArray(RESULTS); for (int i = 0; i < movieArray.length(); i++) { JSONObject results = movieArray.getJSONObject(i); String posterPath = getString(R.string.api_image_base_path) + results.getString(POSTER); String title = results.getString(ORIGINAL_TITLE); String overview = results.getString(OVERVIEW); String voteAvg = results.getString(VOTES); String releaseDate = results.getString(RELEASE); String id = results.getString(ID); String[] outputAttr = {posterPath, title, overview, voteAvg, releaseDate, id}; newThumbids.add(outputAttr); } return newThumbids; } private ArrayList<String[]> getFavorites() { ArrayList<String[]> newThumbids = new ArrayList<>(); ContentResolver cr = getActivity().getContentResolver(); Cursor c = cr.query(MoviesContract.MovieEntry.CONTENT_URI, null, null, null, null); if (c.moveToFirst()) { do { String[] outputAttr = {c.getString(2), c.getString(3), c.getString(4), c.getString(6), c.getString(5), c.getString(1)}; newThumbids.add(outputAttr); } while (c.moveToNext()); } c.close(); return newThumbids; } @Override protected ArrayList<String[]> doInBackground(String... params) { if (params.length == 0) { return null; } if (params[0] == getString(R.string.base_uri_favorites)) { return getFavorites(); } else { HttpURLConnection urlConnection = null; BufferedReader reader = null; String movieJsonStr = null; try { final String BASE_URL = params[0]; final String API_KEY = "api_key"; Uri builtUri = Uri.parse(BASE_URL).buildUpon() .appendQueryParameter(API_KEY, BuildConfig.MOVIES_API_KEY) .build(); URL url = new URL(builtUri.toString()); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) { // Nothing to do. return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { buffer.append(line + "\n"); } if (buffer.length() == 0) { return null; } movieJsonStr = buffer.toString(); } catch (IOException e) { Log.e(LOG_TAG, "Error ", e); return null; } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e(LOG_TAG, "Error closing stream", e); } } } try { return getMovieDataJson(movieJsonStr); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } return null; } } @Override protected void onPostExecute(ArrayList<String[]> result) { if (result != null) { if (mThumbIds.size() > 0) { mThumbIds.clear(); } mThumbIds = (ArrayList<String[]>) result.clone(); if (gridview == null) { gridview = (GridView) getActivity().findViewById(R.id.gridview); mImageAdapter = new ImageAdapter(getActivity()); gridview.setAdapter(mImageAdapter); gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { ((Callback) getActivity()).onItemSelected(mThumbIds, position); } }); } mImageAdapter.notifyDataSetChanged(); } } } static class ViewHolder{ ImageView iv; TextView titleText; TextView releaseDate; TextView voteAvg; } public class ImageAdapter extends BaseAdapter { private Context mContext; private LayoutInflater inflater; public ImageAdapter(Context c) { mContext = c; } public int getCount() { return mThumbIds.size(); } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if (inflater == null) inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); if (convertView == null){ convertView = inflater.inflate(R.layout.card_layout, null); ViewHolder holder=new ViewHolder(); holder.titleText = (TextView) convertView.findViewById(R.id.cardMovieTitle); holder.releaseDate = (TextView) convertView.findViewById(R.id.cardMovieDate); holder.voteAvg = (TextView) convertView.findViewById(R.id.cardMovieRating); holder.iv = (ImageView) convertView.findViewById(R.id.cardImagePoster); convertView.setTag(holder); } viewHolder = (ViewHolder) convertView.getTag(); viewHolder.titleText.setText(mThumbIds.get(position)[1].trim()); viewHolder.releaseDate.setText(mThumbIds.get(position)[4].trim()); viewHolder.voteAvg.setText(mThumbIds.get(position)[3].trim()); Picasso.with(mContext).load(mThumbIds.get(position)[0]).into(viewHolder.iv); return convertView; } } }
package com.nutomic.syncthingandroid.service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Environment; import android.os.PowerManager; import android.text.TextUtils; import android.util.Log; import com.google.common.base.Charsets; import com.google.common.io.Files; import com.nutomic.syncthingandroid.R; import com.nutomic.syncthingandroid.SyncthingApp; import com.nutomic.syncthingandroid.service.Constants; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataOutputStream; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.security.InvalidParameterException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import javax.inject.Inject; import eu.chainfire.libsuperuser.Shell; public class SyncthingRunnable implements Runnable { private static final String TAG = "SyncthingRunnable"; private static final String TAG_NATIVE = "SyncthingNativeCode"; private static final String TAG_NICE = "SyncthingRunnableIoNice"; private static final String TAG_KILL = "SyncthingRunnableKill"; private static final int LOG_FILE_MAX_LINES = 10; private static final AtomicReference<Process> mSyncthing = new AtomicReference<>(); private final Context mContext; private final File mSyncthingBinary; private String[] mCommand; private final File mLogFile; @Inject SharedPreferences mPreferences; private final boolean mUseRoot; @Inject NotificationHandler mNotificationHandler; public enum Command { deviceid, // Output the device ID to the command line. generate, // Generate keys, a config file and immediately exit. main, // Run the main Syncthing application. resetdatabase, // Reset Syncthing's database resetdeltas, // Reset Syncthing's delta indexes } /** * Constructs instance. * * @param command Which type of Syncthing command to execute. */ public SyncthingRunnable(Context context, Command command) { ((SyncthingApp) context.getApplicationContext()).component().inject(this); mContext = context; mSyncthingBinary = Constants.getSyncthingBinary(mContext); mLogFile = Constants.getLogFile(mContext); // Get preferences relevant to starting syncthing core. mUseRoot = mPreferences.getBoolean(Constants.PREF_USE_ROOT, false) && Shell.SU.available(); switch (command) { case deviceid: mCommand = new String[]{ mSyncthingBinary.getPath(), "-home", mContext.getFilesDir().toString(), "--device-id" }; break; case generate: mCommand = new String[]{ mSyncthingBinary.getPath(), "-generate", mContext.getFilesDir().toString(), "-logflags=0" }; break; case main: mCommand = new String[]{ mSyncthingBinary.getPath(), "-home", mContext.getFilesDir().toString(), "-no-browser", "-logflags=0" }; break; case resetdatabase: mCommand = new String[]{ mSyncthingBinary.getPath(), "-home", mContext.getFilesDir().toString(), "-reset-database", "-logflags=0" }; break; case resetdeltas: mCommand = new String[]{ mSyncthingBinary.getPath(), "-home", mContext.getFilesDir().toString(), "-reset-deltas", "-logflags=0" }; break; default: throw new InvalidParameterException("Unknown command option"); } } @Override public void run() { run(false); } public String run(boolean returnStdOut) { trimLogFile(); int ret; String capturedStdOut = ""; // Make sure Syncthing is executable try { ProcessBuilder pb = new ProcessBuilder("chmod", "500", mSyncthingBinary.getPath()); Process p = pb.start(); p.waitFor(); } catch (IOException|InterruptedException e) { Log.w(TAG, "Failed to chmod Syncthing", e); } // Loop Syncthing Process process = null; // Potential fix for #498, keep the CPU running while native binary is running PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wakeLock = useWakeLock() ? pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG) : null; try { if (wakeLock != null) wakeLock.acquire(); HashMap<String, String> targetEnv = buildEnvironment(); process = setupAndLaunch(targetEnv); mSyncthing.set(process); Thread lInfo = null; Thread lWarn = null; if (returnStdOut) { BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(process.getInputStream(), Charsets.UTF_8)); String line; while ((line = br.readLine()) != null) { Log.println(Log.INFO, TAG_NATIVE, line); capturedStdOut = capturedStdOut + line + "\n"; } } catch (IOException e) { Log.w(TAG, "Failed to read Syncthing's command line output", e); } finally { if (br != null) br.close(); } } else { lInfo = log(process.getInputStream(), Log.INFO, true); lWarn = log(process.getErrorStream(), Log.WARN, true); } niceSyncthing(); ret = process.waitFor(); Log.i(TAG, "Syncthing exited with code " + ret); mSyncthing.set(null); if (lInfo != null) lInfo.join(); if (lWarn != null) lWarn.join(); switch (ret) { case 0: case 137: // Syncthing was shut down (via API or SIGKILL), do nothing. break; case 1: Log.w(TAG, "Another Syncthing instance is already running, requesting restart via SyncthingService intent"); //fallthrough case 3: // Restart was requested via Rest API call. Log.i(TAG, "Restarting syncthing"); mContext.startService(new Intent(mContext, SyncthingService.class) .setAction(SyncthingService.ACTION_RESTART)); break; default: Log.w(TAG, "Syncthing has crashed (exit code " + ret + ")"); mNotificationHandler.showCrashedNotification(R.string.notification_crash_title, false); } } catch (IOException | InterruptedException e) { Log.e(TAG, "Failed to execute syncthing binary or read output", e); } finally { if (wakeLock != null) wakeLock.release(); if (process != null) process.destroy(); } return capturedStdOut; } private void putCustomEnvironmentVariables(Map<String, String> environment, SharedPreferences sp) { String customEnvironment = sp.getString("environment_variables", null); if (TextUtils.isEmpty(customEnvironment)) return; for (String e : customEnvironment.split(" ")) { String[] e2 = e.split("="); environment.put(e2[0], e2[1]); } } /** * Returns true if the experimental setting for using wake locks has been enabled in settings. */ private boolean useWakeLock() { return mPreferences.getBoolean(Constants.PREF_USE_WAKE_LOCK, false); } /** * Look for running libsyncthing.so processes and return an array * containing the PIDs of found instances. */ private List<String> getSyncthingPIDs() { List<String> syncthingPIDs = new ArrayList<String>(); Process ps = null; DataOutputStream psOut = null; BufferedReader br = null; try { ps = Runtime.getRuntime().exec((mUseRoot) ? "su" : "sh"); psOut = new DataOutputStream(ps.getOutputStream()); psOut.writeBytes("ps\n"); psOut.writeBytes("exit\n"); psOut.flush(); ps.waitFor(); br = new BufferedReader(new InputStreamReader(ps.getInputStream(), "UTF-8")); String line; while ((line = br.readLine()) != null) { if (line.contains(Constants.FILENAME_SYNCTHING_BINARY)) { String syncthingPID = line.trim().split("\\s+")[1]; Log.v(TAG, "getSyncthingPIDs: Found process PID [" + syncthingPID + "]"); syncthingPIDs.add(syncthingPID); } } } catch (IOException | InterruptedException e) { Log.w(TAG_KILL, "Failed list Syncthing processes", e); } finally { try { if (br != null) { br.close(); } if (psOut != null) { psOut.close(); } } catch (IOException e) { Log.w(TAG_KILL, "Failed close the psOut stream", e); } if (ps != null) { ps.destroy(); } } return syncthingPIDs; } /** * Look for a running libsyncthing.so process and nice its IO. */ private void niceSyncthing() { new Thread() { public void run() { Process nice = null; DataOutputStream niceOut = null; int ret = 1; try { Thread.sleep(1000); // Wait a second before getting the pid List<String> syncthingPIDs = getSyncthingPIDs(); if (syncthingPIDs.isEmpty()) { Log.w(TAG, "niceSyncthing: Found no running instances of " + Constants.FILENAME_SYNCTHING_BINARY); } else { nice = Runtime.getRuntime().exec((mUseRoot) ? "su" : "sh"); niceOut = new DataOutputStream(nice.getOutputStream()); for (String syncthingPID : syncthingPIDs) { // Set best-effort, low priority using ionice. niceOut.writeBytes("ionice " + syncthingPID + " be 7\n"); } niceOut.writeBytes("exit\n"); log(nice.getErrorStream(), Log.WARN, false); niceOut.flush(); ret = nice.waitFor(); Log.i(TAG_NICE, "ionice performed on " + Constants.FILENAME_SYNCTHING_BINARY); } } catch (IOException | InterruptedException e) { Log.e(TAG_NICE, "Failed to execute ionice binary", e); } finally { try { if (niceOut != null) { niceOut.close(); } } catch (IOException e) { Log.w(TAG_NICE, "Failed to close shell stream", e); } if (nice != null) { nice.destroy(); } if (ret != 0) { Log.e(TAG_NICE, "Failed to set ionice " + Integer.toString(ret)); } } } }.start(); } public interface OnSyncthingKilled { void onKilled(); } /** * Look for running libsyncthing.so processes and kill them. * Try a SIGINT first, then try again with SIGKILL. */ public void killSyncthing(OnSyncthingKilled onKilledListener) { new Thread(() -> { for (int i = 0; i < 2; i++) { List<String> syncthingPIDs = getSyncthingPIDs(); if (syncthingPIDs.isEmpty()) { Log.d(TAG, "killSyncthing: Found no more running instances of " + Constants.FILENAME_SYNCTHING_BINARY); break; } for (String syncthingPID : syncthingPIDs) { killProcessId(syncthingPID, i > 0); } } onKilledListener.onKilled(); }).start(); } /** * Kill a given process ID * * @param force Whether to use a SIGKILL. */ private void killProcessId(String id, boolean force) { Process kill = null; DataOutputStream killOut = null; try { kill = Runtime.getRuntime().exec((mUseRoot) ? "su" : "sh"); killOut = new DataOutputStream(kill.getOutputStream()); if (!force) { killOut.writeBytes("kill -SIGINT " + id + "\n"); killOut.writeBytes("sleep 1\n"); } else { killOut.writeBytes("sleep 3\n"); killOut.writeBytes("kill -SIGKILL " + id + "\n"); } killOut.writeBytes("exit\n"); killOut.flush(); kill.waitFor(); Log.i(TAG_KILL, "Killed Syncthing process "+id); } catch (IOException | InterruptedException e) { Log.w(TAG_KILL, "Failed to kill process id "+id, e); } finally { try { if (killOut != null) killOut.close(); } catch (IOException e) { Log.w(TAG_KILL, "Failed close the killOut stream", e);} if (kill != null) { kill.destroy(); } } } /** * Logs the outputs of a stream to logcat and mNativeLog. * * @param is The stream to log. * @param priority The priority level. * @param saveLog True if the log should be stored to {@link #mLogFile}. */ private Thread log(final InputStream is, final int priority, final boolean saveLog) { Thread t = new Thread(() -> { BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(is, Charsets.UTF_8)); String line; while ((line = br.readLine()) != null) { Log.println(priority, TAG_NATIVE, line); if (saveLog) { Files.append(line + "\n", mLogFile, Charsets.UTF_8); } } } catch (IOException e) { Log.w(TAG, "Failed to read Syncthing's command line output", e); } if (br != null) { try { br.close(); } catch (IOException e) { Log.w(TAG, "log: Failed to close bufferedReader", e); } } }); t.start(); return t; } /** * Only keep last {@link #LOG_FILE_MAX_LINES} lines in log file, to avoid bloat. */ private void trimLogFile() { if (!mLogFile.exists()) return; try { LineNumberReader lnr = new LineNumberReader(new FileReader(mLogFile)); lnr.skip(Long.MAX_VALUE); int lineCount = lnr.getLineNumber(); lnr.close(); File tempFile = new File(mContext.getExternalFilesDir(null), "syncthing.log.tmp"); BufferedReader reader = new BufferedReader(new FileReader(mLogFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile)); String currentLine; int startFrom = lineCount - LOG_FILE_MAX_LINES; for (int i = 0; (currentLine = reader.readLine()) != null; i++) { if (i > startFrom) { writer.write(currentLine + "\n"); } } writer.close(); reader.close(); tempFile.renameTo(mLogFile); } catch (IOException e) { Log.w(TAG, "Failed to trim log file", e); } } private HashMap<String, String> buildEnvironment() { HashMap<String, String> targetEnv = new HashMap<>(); // Set home directory to data folder for web GUI folder picker. targetEnv.put("HOME", Environment.getExternalStorageDirectory().getAbsolutePath()); targetEnv.put("STTRACE", mPreferences.getString("sttrace", "")); File externalFilesDir = mContext.getExternalFilesDir(null); if (externalFilesDir != null) targetEnv.put("STGUIASSETS", externalFilesDir.getAbsolutePath() + "/gui"); targetEnv.put("STNORESTART", "1"); targetEnv.put("STNOUPGRADE", "1"); // Disable hash benchmark for faster startup. targetEnv.put("STHASHING", "minio"); if (mPreferences.getBoolean(Constants.PREF_USE_TOR, false)) { targetEnv.put("all_proxy", "socks5://localhost:9050"); targetEnv.put("ALL_PROXY_NO_FALLBACK", "1"); } else { String socksProxyAddress = mPreferences.getString(Constants.PREF_SOCKS_PROXY_ADDRESS, ""); if (!socksProxyAddress.equals("")) { targetEnv.put("all_proxy", socksProxyAddress); } String httpProxyAddress = mPreferences.getString(Constants.PREF_HTTP_PROXY_ADDRESS, ""); if (!httpProxyAddress.equals("")) { targetEnv.put("http_proxy", httpProxyAddress); targetEnv.put("https_proxy", httpProxyAddress); } } if (mPreferences.getBoolean("use_legacy_hashing", false)) targetEnv.put("STHASHING", "standard"); putCustomEnvironmentVariables(targetEnv, mPreferences); return targetEnv; } private Process setupAndLaunch(HashMap<String, String> env) throws IOException { if (mUseRoot) { ProcessBuilder pb = new ProcessBuilder("su"); Process process = pb.start(); // The su binary prohibits the inheritance of environment variables. // Even with --preserve-environment the environment gets messed up. // We therefore start a root shell, and set all the environment variables manually. DataOutputStream suOut = new DataOutputStream(process.getOutputStream()); for (Map.Entry<String, String> entry : env.entrySet()) { suOut.writeBytes(String.format("export %s=\"%s\"\n", entry.getKey(), entry.getValue())); } suOut.flush(); // Exec will replace the su process image by Syncthing as execlp in C does. // Without using exec, the process will drop to the root shell as soon as Syncthing terminates like a normal shell does. // If we did not use exec, we would wait infinitely for the process to terminate (ret = process.waitFor(); in run()). // With exec the whole process terminates when Syncthing exits. suOut.writeBytes("exec " + TextUtils.join(" ", mCommand) + "\n"); // suOut.flush has to be called to fix issue - #1005 Endless loader after enabling "Superuser mode" suOut.flush(); return process; } else { ProcessBuilder pb = new ProcessBuilder(mCommand); pb.environment().putAll(env); return pb.start(); } } }
package com.worldspotlightapp.android.ui; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.TimeUnit; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.Fragment; import android.content.Intent; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.text.Layout; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.squareup.picasso.Callback; import com.squareup.picasso.Picasso; import com.worldspotlightapp.android.R; import com.worldspotlightapp.android.model.Video; public class VideosPreviewFragment extends Fragment { private Activity mActivity; private Picasso mPicasso; /** * The unique id of the video */ private String mObjectId; private String mThumbnailUrl; private String mTitle; private String mDescription; private String mNavigation; // Views private RelativeLayout mVideoPreviewRelativeLayout; private ImageView mThumbnailImageView; private TextView mTitleTextView; private TextView mDescriptionTextView; public static VideosPreviewFragment newInstance(String objectId, String thumbnailUrl, String title, String description) { VideosPreviewFragment videosPreviewFragment = new VideosPreviewFragment(); Bundle args = new Bundle(); args.putString(Video.INTENT_KEY_OBJECT_ID, objectId); args.putString(Video.INTENT_KEY_THUMBNAIL_URL, thumbnailUrl); args.putString(Video.INTENT_KEY_TITLE, title); args.putString(Video.INTENT_KEY_DESCRIPTION, description); videosPreviewFragment.setArguments(args); return videosPreviewFragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); // Set the content of the view mVideoPreviewRelativeLayout = (RelativeLayout)inflater.inflate(R.layout.video_preview_layout, container, false); // Link the layout mThumbnailImageView = (ImageView) mVideoPreviewRelativeLayout.findViewById(R.id.thumbnail_image_view); mTitleTextView = (TextView) mVideoPreviewRelativeLayout.findViewById(R.id.title_text_view); mDescriptionTextView = (TextView) mVideoPreviewRelativeLayout.findViewById(R.id.description_text_view); return mVideoPreviewRelativeLayout; } @Override public void onAttach(Activity activity) { super.onAttach(activity); this.mActivity = activity; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Get the offer Id from the arguments Bundle bundle = getArguments(); if (bundle == null || !bundle.containsKey(Video.INTENT_KEY_OBJECT_ID) || !bundle.containsKey(Video.INTENT_KEY_THUMBNAIL_URL) || !bundle.containsKey(Video.INTENT_KEY_TITLE) || !bundle.containsKey(Video.INTENT_KEY_DESCRIPTION) ) { throw new IllegalArgumentException("You must instantiate this fragment using the method newInstance"); } mObjectId = bundle.getString(Video.INTENT_KEY_OBJECT_ID); // Load images mPicasso = Picasso.with(mActivity); mPicasso.load(mThumbnailUrl); mThumbnailUrl = bundle.getString(Video.INTENT_KEY_THUMBNAIL_URL); // Title mTitle = bundle.getString(Video.INTENT_KEY_TITLE); mTitleTextView.setText(mTitle); mDescription = bundle.getString(Video.INTENT_KEY_DESCRIPTION); mDescriptionTextView.setText(mDescription); mVideoPreviewRelativeLayout.setOnClickListener(onClickListener); } private OnClickListener onClickListener = new OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.video_preview_relative_layout: // Start the video details activity Intent startVideoDetailsActivityIntent = new Intent(mActivity, VideoDetailsActivity.class); startVideoDetailsActivityIntent.putExtra(Video.INTENT_KEY_OBJECT_ID, mObjectId); startActivity(startVideoDetailsActivityIntent); break; } } }; }
package me.devsaki.hentoid.fragments.viewer; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Point; import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.widget.Toolbar; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.lifecycle.ViewModelProvider; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.LinearSmoothScroller; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.snackbar.BaseTransientBottomBar; import com.google.android.material.snackbar.Snackbar; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.annotation.Nonnull; import io.reactivex.Observable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; import me.devsaki.hentoid.R; import me.devsaki.hentoid.activities.ImageViewerActivity; import me.devsaki.hentoid.activities.PrefsActivity; import me.devsaki.hentoid.activities.bundles.PrefsActivityBundle; import me.devsaki.hentoid.adapters.ImagePagerAdapter; import me.devsaki.hentoid.database.domains.Content; import me.devsaki.hentoid.database.domains.ImageFile; import me.devsaki.hentoid.util.Debouncer; import me.devsaki.hentoid.util.Preferences; import me.devsaki.hentoid.util.ThemeHelper; import me.devsaki.hentoid.util.ToastUtil; import me.devsaki.hentoid.util.exception.ContentNotRemovedException; import me.devsaki.hentoid.viewmodels.ImageViewerViewModel; import me.devsaki.hentoid.viewmodels.ViewModelFactory; import me.devsaki.hentoid.views.ZoomableFrame; import me.devsaki.hentoid.views.ZoomableRecyclerView; import me.devsaki.hentoid.widget.OnZoneTapListener; import me.devsaki.hentoid.widget.PageSnapWidget; import me.devsaki.hentoid.widget.PrefetchLinearLayoutManager; import me.devsaki.hentoid.widget.ScrollPositionListener; import me.devsaki.hentoid.widget.VolumeKeyListener; import timber.log.Timber; import static androidx.core.view.ViewCompat.requireViewById; import static java.lang.String.format; import static me.devsaki.hentoid.util.Preferences.Constant; // TODO : better document and/or encapsulate the difference between // - paper roll mode (currently used for vertical display) // - independent page mode (currently used for horizontal display) public class ImagePagerFragment extends Fragment implements GoToPageDialogFragment.Parent, BrowseModeDialogFragment.Parent, BookPrefsDialogFragment.Parent { private static final String KEY_HUD_VISIBLE = "hud_visible"; private static final String KEY_GALLERY_SHOWN = "gallery_shown"; private static final String KEY_SLIDESHOW_ON = "slideshow_on"; private final RequestOptions glideRequestOptions = new RequestOptions().centerInside(); private ImagePagerAdapter adapter; private PrefetchLinearLayoutManager llm; private PageSnapWidget pageSnapWidget; private final SharedPreferences.OnSharedPreferenceChangeListener listener = this::onSharedPreferenceChanged; private ImageViewerViewModel viewModel; private int imageIndex = -1; // 0-based image index private int highestImageIndexReached = -1; // To manage "Mark book as read after N pages" pref private int maxPosition; // For navigation private int maxPageNumber; // For display; when pages are missing, maxPosition < maxPageNumber private boolean hasGalleryBeenShown = false; private final ScrollPositionListener scrollListener = new ScrollPositionListener(this::onScrollPositionChange); private Disposable slideshowTimer = null; private Map<String, String> bookPreferences; // Preferences of current book; to feed the book prefs dialog private long contentId; private final Debouncer<Integer> indexRefreshDebouncer = new Debouncer<>(75, this::applyStartingIndexInternal); // Starting index management private boolean isComputingImageList = false; private int targetStartingIndex = -1; // == CONTROLS == private TextView pageNumberOverlay; private ZoomableFrame zoomFrame; private ZoomableRecyclerView recyclerView; private RecyclerView.SmoothScroller smoothScroller; // Controls overlay private View controlsOverlay; // Top menu items private MenuItem showFavoritePagesButton; private MenuItem shuffleButton; // Bottom bar controls private ImageView previewImage1; private ImageView previewImage2; private ImageView previewImage3; private SeekBar seekBar; private TextView pageCurrentNumber; private TextView pageMaxNumber; private View prevBookButton; private View nextBookButton; private View galleryBtn; private View favouritesGalleryBtn; @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_viewer_pager, container, false); Preferences.registerPrefsChangedListener(listener); initPager(rootView); initControlsOverlay(rootView); onBrowseModeChange(); onUpdateSwipeToFling(); onUpdatePageNumDisplay(); // Top bar controls Toolbar toolbar = requireViewById(rootView, R.id.viewer_pager_toolbar); toolbar.setNavigationOnClickListener(v -> onBackClick()); toolbar.setOnMenuItemClickListener(clickedMenuItem -> { switch (clickedMenuItem.getItemId()) { case R.id.action_show_favorite_pages: onShowFavouriteClick(); break; case R.id.action_page_menu: onPageMenuClick(); break; case R.id.action_app_settings: onAppSettingsClick(); break; case R.id.action_book_settings: onBookSettingsClick(); break; case R.id.action_shuffle: onShuffleClick(); break; case R.id.action_slideshow: startSlideshow(); break; case R.id.action_delete_book: onDeleteBook(); break; default: // Nothing to do here } return true; }); showFavoritePagesButton = toolbar.getMenu().findItem(R.id.action_show_favorite_pages); shuffleButton = toolbar.getMenu().findItem(R.id.action_shuffle); return rootView; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ViewModelFactory vmFactory = new ViewModelFactory(requireActivity().getApplication()); viewModel = new ViewModelProvider(requireActivity(), vmFactory).get(ImageViewerViewModel.class); viewModel.onRestoreState(savedInstanceState); viewModel.getContent() .observe(getViewLifecycleOwner(), this::onContentChanged); viewModel.getImages() .observe(getViewLifecycleOwner(), this::onImagesChanged); viewModel.getStartingIndex() .observe(getViewLifecycleOwner(), this::onStartingIndexChanged); viewModel.getShuffled() .observe(getViewLifecycleOwner(), this::onShuffleChanged); } @Override public void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); if (controlsOverlay != null) outState.putInt(KEY_HUD_VISIBLE, controlsOverlay.getVisibility()); outState.putBoolean(KEY_SLIDESHOW_ON, (slideshowTimer != null)); outState.putBoolean(KEY_GALLERY_SHOWN, hasGalleryBeenShown); if (viewModel != null) { viewModel.setStartingIndex(imageIndex); // Memorize the current page viewModel.onSaveState(outState); } } @Override public void onViewStateRestored(@Nullable Bundle savedInstanceState) { super.onViewStateRestored(savedInstanceState); int hudVisibility = View.INVISIBLE; // Default state at startup if (savedInstanceState != null) { hudVisibility = savedInstanceState.getInt(KEY_HUD_VISIBLE, View.INVISIBLE); hasGalleryBeenShown = savedInstanceState.getBoolean(KEY_GALLERY_SHOWN, false); if (savedInstanceState.getBoolean(KEY_SLIDESHOW_ON, false)) startSlideshow(false); } controlsOverlay.setVisibility(hudVisibility); } @Override public void onStart() { super.onStart(); ((ImageViewerActivity) requireActivity()).registerKeyListener( new VolumeKeyListener() .setOnVolumeDownListener(this::previousPage) .setOnVolumeUpListener(this::nextPage) .setOnBackListener(this::onBackClick)); } @Override public void onResume() { super.onResume(); setSystemBarsVisible(controlsOverlay.getVisibility() == View.VISIBLE); // System bars are visible only if HUD is visible if (Preferences.Constant.PREF_VIEWER_BROWSE_NONE == Preferences.getViewerBrowseMode()) BrowseModeDialogFragment.invoke(this); updatePageDisplay(); updateFavouritesGalleryButtonDisplay(); } // Make sure position is saved when app is closed by the user @Override public void onStop() { viewModel.onLeaveBook(imageIndex, highestImageIndexReached); if (slideshowTimer != null) slideshowTimer.dispose(); ((ImageViewerActivity) requireActivity()).unregisterKeyListener(); super.onStop(); } @Override public void onDestroy() { Preferences.unregisterPrefsChangedListener(listener); adapter.setRecyclerView(null); adapter.destroy(); if (recyclerView != null) recyclerView.setAdapter(null); recyclerView = null; super.onDestroy(); } private void initPager(View rootView) { adapter = new ImagePagerAdapter(requireContext()); zoomFrame = requireViewById(rootView, R.id.image_viewer_zoom_frame); recyclerView = requireViewById(rootView, R.id.image_viewer_zoom_recycler); recyclerView.setAdapter(adapter); recyclerView.setHasFixedSize(true); recyclerView.addOnScrollListener(scrollListener); recyclerView.setOnGetMaxDimensionsListener(this::onGetMaxDimensions); recyclerView.requestFocus(); recyclerView.setOnScaleListener(scale -> { if (pageSnapWidget != null && Preferences.Constant.PREF_VIEWER_ORIENTATION_HORIZONTAL == Preferences.getViewerOrientation()) { if (1.0 == scale && !pageSnapWidget.isPageSnapEnabled()) pageSnapWidget.setPageSnapEnabled(true); else if (1.0 != scale && pageSnapWidget.isPageSnapEnabled()) pageSnapWidget.setPageSnapEnabled(false); } }); recyclerView.setLongTapListener(ev -> false); OnZoneTapListener onHorizontalZoneTapListener = new OnZoneTapListener(recyclerView) .setOnLeftZoneTapListener(this::onLeftTap) .setOnRightZoneTapListener(this::onRightTap) .setOnMiddleZoneTapListener(this::onMiddleTap); OnZoneTapListener onVerticalZoneTapListener = new OnZoneTapListener(recyclerView) .setOnMiddleZoneTapListener(this::onMiddleTap); recyclerView.setTapListener(onVerticalZoneTapListener); // For paper roll mode (vertical) adapter.setItemTouchListener(onHorizontalZoneTapListener); // For independent images mode (horizontal) adapter.setRecyclerView(recyclerView); llm = new PrefetchLinearLayoutManager(getContext()); llm.setExtraLayoutSpace(10); recyclerView.setLayoutManager(llm); pageSnapWidget = new PageSnapWidget(recyclerView); smoothScroller = new LinearSmoothScroller(requireContext()) { @Override protected int getVerticalSnapPreference() { return LinearSmoothScroller.SNAP_TO_START; } }; scrollListener.setOnStartOutOfBoundScrollListener(() -> { if (Preferences.isViewerContinuous()) previousBook(); }); scrollListener.setOnEndOutOfBoundScrollListener(() -> { if (Preferences.isViewerContinuous()) nextBook(); }); } private void initControlsOverlay(View rootView) { controlsOverlay = requireViewById(rootView, R.id.image_viewer_controls_overlay); // Page number button pageCurrentNumber = requireViewById(rootView, R.id.viewer_current_page_text); pageCurrentNumber.setOnClickListener(v -> GoToPageDialogFragment.invoke(this)); pageMaxNumber = requireViewById(rootView, R.id.viewer_max_page_text); pageNumberOverlay = requireViewById(rootView, R.id.viewer_pagenumber_text); // Next/previous book prevBookButton = requireViewById(rootView, R.id.viewer_prev_book_btn); prevBookButton.setOnClickListener(v -> previousBook()); nextBookButton = requireViewById(rootView, R.id.viewer_next_book_btn); nextBookButton.setOnClickListener(v -> nextBook()); // Slider and preview previewImage1 = requireViewById(rootView, R.id.viewer_image_preview1); previewImage2 = requireViewById(rootView, R.id.viewer_image_preview2); previewImage3 = requireViewById(rootView, R.id.viewer_image_preview3); seekBar = requireViewById(rootView, R.id.viewer_seekbar); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onStartTrackingTouch(SeekBar seekBar) { previewImage1.setVisibility(View.VISIBLE); previewImage2.setVisibility(View.VISIBLE); previewImage3.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.INVISIBLE); } @Override public void onStopTrackingTouch(SeekBar seekBar) { previewImage1.setVisibility(View.INVISIBLE); previewImage2.setVisibility(View.INVISIBLE); previewImage3.setVisibility(View.INVISIBLE); recyclerView.setVisibility(View.VISIBLE); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) seekToPosition(progress); } }); // Gallery galleryBtn = requireViewById(rootView, R.id.viewer_gallery_btn); galleryBtn.setOnClickListener(v -> displayGallery(false)); favouritesGalleryBtn = requireViewById(rootView, R.id.viewer_favourites_btn); favouritesGalleryBtn.setOnClickListener(v -> displayGallery(true)); } /** * Back button handler */ private void onBackClick() { requireActivity().onBackPressed(); } /** * Show the app viewer settings dialog */ private void onAppSettingsClick() { Intent intent = new Intent(requireActivity(), PrefsActivity.class); PrefsActivityBundle.Builder builder = new PrefsActivityBundle.Builder(); builder.setIsViewerPrefs(true); intent.putExtras(builder.getBundle()); requireContext().startActivity(intent); } /** * Show the book viewer settings dialog */ private void onBookSettingsClick() { BookPrefsDialogFragment.invoke(this, bookPreferences); } /** * Handle click on "Shuffle" action button */ private void onShuffleClick() { goToPage(1); viewModel.onShuffleClick(); } /** * Handle click on "Show favourite pages" action button */ private void onShowFavouriteClick() { viewModel.toggleShowFavouritePages(this::updateShowFavouriteDisplay); } /** * Handle click on "Page menu" action button */ private void onPageMenuClick() { float currentScale = adapter.getScaleAtPosition(imageIndex); ImageBottomSheetFragment.show(requireContext(), requireActivity().getSupportFragmentManager(), imageIndex, currentScale); } /** * Observer for changes in the book's list of images * * @param images Book's list of images */ private void onImagesChanged(List<ImageFile> images) { isComputingImageList = true; adapter.submitList(images, this::differEndCallback); } /** * Callback for the end of image list diff calculations * Activated when all displayed items are placed on their definitive position */ private void differEndCallback() { maxPosition = adapter.getItemCount() - 1; seekBar.setMax(maxPosition); // Can't access the gallery when there's no page to display if (maxPosition > -1) galleryBtn.setVisibility(View.VISIBLE); else galleryBtn.setVisibility(View.GONE); if (targetStartingIndex > -1) applyStartingIndex(targetStartingIndex); else updatePageDisplay(); isComputingImageList = false; } /** * Observer for changes on the book's starting image index * * @param startingIndex Book's starting image index */ private void onStartingIndexChanged(Integer startingIndex) { if (!isComputingImageList) applyStartingIndex(startingIndex); else targetStartingIndex = startingIndex; } private void applyStartingIndex(int startingIndex) { indexRefreshDebouncer.submit(startingIndex); targetStartingIndex = -1; } private void applyStartingIndexInternal(int startingIndex) { int currentPosition = Math.max(llm.findFirstVisibleItemPosition(), llm.findFirstCompletelyVisibleItemPosition()); // When target position is the same as current scroll index (0), scrolling is pointless // -> activate scroll listener manually if (currentPosition == startingIndex) onScrollPositionChange(startingIndex); else { if (Preferences.Constant.PREF_VIEWER_ORIENTATION_HORIZONTAL == Preferences.getViewerOrientation() && recyclerView != null) recyclerView.scrollToPosition(startingIndex); else llm.scrollToPositionWithOffset(startingIndex, 0); } } /** * Observer for changes on the current book * * @param content Loaded book */ private void onContentChanged(Content content) { if (null == content) { onBackClick(); return; } bookPreferences = content.getBookPreferences(); // Updating the same book may mean its preferences have changed and the display has to be updated // Don't do that when content has changed since display is always updated when new images come in if (contentId == content.getId()) { // onBrowseModeChange(); onUpdateImageDisplay(); } contentId = content.getId(); updateBookNavigation(content); } /** * Observer for changes on the shuffled state * * @param isShuffled New shuffled state */ private void onShuffleChanged(boolean isShuffled) { if (isShuffled) { shuffleButton.setIcon(R.drawable.ic_menu_sort_123); shuffleButton.setTitle(R.string.viewer_order_123); } else { shuffleButton.setIcon(R.drawable.ic_menu_sort_random); shuffleButton.setTitle(R.string.viewer_order_shuffle); } } private void onDeleteBook() { new MaterialAlertDialogBuilder(requireContext(), ThemeHelper.getIdForCurrentTheme(requireContext(), R.style.Theme_Light_Dialog)) .setIcon(R.drawable.ic_warning) .setCancelable(false) .setTitle(R.string.app_name) .setMessage(R.string.viewer_ask_delete_book) .setPositiveButton(android.R.string.yes, (dialog1, which) -> { dialog1.dismiss(); viewModel.deleteBook(this::onDeleteError); }) .setNegativeButton(android.R.string.no, (dialog12, which) -> dialog12.dismiss()) .create() .show(); } /** * Callback for the failure of the "delete item" action */ private void onDeleteError(Throwable t) { Timber.e(t); if (t instanceof ContentNotRemovedException) { ContentNotRemovedException e = (ContentNotRemovedException) t; String message = (null == e.getMessage()) ? "Content removal failed" : e.getMessage(); Snackbar.make(recyclerView, message, BaseTransientBottomBar.LENGTH_LONG).show(); } } /** * Scroll / page change listener * * @param scrollPosition New 0-based scroll position */ private void onScrollPositionChange(int scrollPosition) { if (scrollPosition != imageIndex) { boolean isScrollLTR = true; if (Constant.PREF_VIEWER_DIRECTION_LTR == Preferences.getViewerDirection() && imageIndex > scrollPosition) isScrollLTR = false; else if (Constant.PREF_VIEWER_DIRECTION_RTL == Preferences.getViewerDirection() && imageIndex < scrollPosition) isScrollLTR = false; adapter.setScrollLTR(isScrollLTR); } imageIndex = scrollPosition; highestImageIndexReached = Math.max(imageIndex, highestImageIndexReached); // Resets zoom if we're using horizontal (independent pages) mode if (Preferences.Constant.PREF_VIEWER_ORIENTATION_HORIZONTAL == Preferences.getViewerOrientation()) adapter.resetScaleAtPosition(scrollPosition); updatePageDisplay(); updateFavouritesGalleryButtonDisplay(); } /** * Update the display of page position controls (text and bar) */ private void updatePageDisplay() { ImageFile img = adapter.getImageAt(imageIndex); if (null == img) { Timber.w("No image at position %s", imageIndex); return; } String pageNum = img.getOrder() + ""; String maxPage = maxPageNumber + ""; pageCurrentNumber.setText(pageNum); pageMaxNumber.setText(maxPage); pageNumberOverlay.setText(format("%s / %s", pageNum, maxPage)); seekBar.setProgress(imageIndex); } /** * Update the visibility of "next/previous book" buttons * * @param content Current book */ private void updateBookNavigation(@Nonnull Content content) { if (content.isFirst()) prevBookButton.setVisibility(View.INVISIBLE); else prevBookButton.setVisibility(View.VISIBLE); if (content.isLast()) nextBookButton.setVisibility(View.INVISIBLE); else nextBookButton.setVisibility(View.VISIBLE); maxPageNumber = content.getQtyPages(); updatePageDisplay(); } /** * Update the display of the favourites gallery launcher */ private void updateFavouritesGalleryButtonDisplay() { if (adapter.isFavouritePresent()) favouritesGalleryBtn.setVisibility(View.VISIBLE); else favouritesGalleryBtn.setVisibility(View.INVISIBLE); } /** * Update the display of the "favourite page" action button * * @param showFavouritePages True if the button has to represent a favourite page; false instead */ private void updateShowFavouriteDisplay(boolean showFavouritePages) { if (showFavouritePages) { showFavoritePagesButton.setIcon(R.drawable.ic_filter_favs_on); showFavoritePagesButton.setTitle(R.string.viewer_filter_favourite_on); } else { showFavoritePagesButton.setIcon(R.drawable.ic_filter_favs_off); showFavoritePagesButton.setTitle(R.string.viewer_filter_favourite_off); } } /** * Listener for preference changes (from the settings dialog) * * @param prefs Shared preferences object * @param key Key that has been changed */ public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { switch (key) { case Preferences.Key.PREF_VIEWER_BROWSE_MODE: case Preferences.Key.PREF_VIEWER_HOLD_TO_ZOOM: case Preferences.Key.PREF_VIEWER_CONTINUOUS: onBrowseModeChange(); break; case Preferences.Key.PREF_VIEWER_KEEP_SCREEN_ON: onUpdatePrefsScreenOn(); break; case Preferences.Key.PREF_VIEWER_ZOOM_TRANSITIONS: case Preferences.Key.PREF_VIEWER_SEPARATING_BARS: case Preferences.Key.PREF_VIEWER_IMAGE_DISPLAY: case Preferences.Key.PREF_VIEWER_AUTO_ROTATE: // TODO maybe use onBrowseModeChange which is supposed to recreate all viewholders case Preferences.Key.PREF_VIEWER_RENDERING: onUpdateImageDisplay(); break; case Preferences.Key.PREF_VIEWER_SWIPE_TO_FLING: onUpdateSwipeToFling(); break; case Preferences.Key.PREF_VIEWER_DISPLAY_PAGENUM: onUpdatePageNumDisplay(); break; default: // Other changes aren't handled here } } public void onBookPreferenceChanged(@NonNull final Map<String, String> newPrefs) { viewModel.updateBookPreferences(newPrefs); } private void onUpdatePrefsScreenOn() { if (Preferences.isViewerKeepScreenOn()) requireActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); else requireActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } private void onUpdateSwipeToFling() { int flingFactor = Preferences.isViewerSwipeToFling() ? 75 : 0; pageSnapWidget.setFlingSensitivity(flingFactor / 100f); } private void onUpdateImageDisplay() { adapter.refreshPrefs(); adapter.notifyDataSetChanged(); // NB : will re-run onBindViewHolder for all displayed pictures } private void onUpdatePageNumDisplay() { pageNumberOverlay.setVisibility(Preferences.isViewerDisplayPageNum() ? View.VISIBLE : View.GONE); } @Override public void onBrowseModeChange() { int currentLayoutDirection; // LinearLayoutManager.setReverseLayout behaves _relatively_ to current Layout Direction // => need to know that direction before deciding how to set setReverseLayout if (View.LAYOUT_DIRECTION_LTR == controlsOverlay.getLayoutDirection()) currentLayoutDirection = Preferences.Constant.PREF_VIEWER_DIRECTION_LTR; else currentLayoutDirection = Preferences.Constant.PREF_VIEWER_DIRECTION_RTL; llm.setReverseLayout(Preferences.getViewerDirection() != currentLayoutDirection); // Resets the views to switch between paper roll mode (vertical) and independent page mode (horizontal) recyclerView.resetScale(); onUpdateImageDisplay(); // TODO we should do more than that as a simple rebind won't recreate existing holders if (Preferences.Constant.PREF_VIEWER_ORIENTATION_VERTICAL == Preferences.getViewerOrientation()) { zoomFrame.enable(); recyclerView.setLongTapZoomEnabled(Preferences.isViewerHoldToZoom()); } else { zoomFrame.disable(); recyclerView.setLongTapZoomEnabled(!Preferences.isViewerHoldToZoom()); } llm.setOrientation(getOrientation()); pageSnapWidget.setPageSnapEnabled(Preferences.Constant.PREF_VIEWER_ORIENTATION_HORIZONTAL == Preferences.getViewerOrientation()); } /** * Transforms current Preferences orientation into LinearLayoutManager orientation code * * @return Preferred orientation, as LinearLayoutManager orientation code */ private int getOrientation() { if (Preferences.Constant.PREF_VIEWER_ORIENTATION_HORIZONTAL == Preferences.getViewerOrientation()) { return LinearLayoutManager.HORIZONTAL; } else { return LinearLayoutManager.VERTICAL; } } /** * Load next page */ private void nextPage() { if (imageIndex == maxPosition) { if (Preferences.isViewerContinuous()) nextBook(); return; } if (Preferences.isViewerTapTransitions()) { if (Preferences.Constant.PREF_VIEWER_ORIENTATION_HORIZONTAL == Preferences.getViewerOrientation()) recyclerView.smoothScrollToPosition(imageIndex + 1); else { smoothScroller.setTargetPosition(imageIndex + 1); llm.startSmoothScroll(smoothScroller); } } else { if (Preferences.Constant.PREF_VIEWER_ORIENTATION_HORIZONTAL == Preferences.getViewerOrientation()) recyclerView.scrollToPosition(imageIndex + 1); else llm.scrollToPositionWithOffset(imageIndex + 1, 0); } } /** * Load previous page */ private void previousPage() { if (0 == imageIndex) { if (Preferences.isViewerContinuous()) previousBook(); return; } if (Preferences.isViewerTapTransitions()) recyclerView.smoothScrollToPosition(imageIndex - 1); else recyclerView.scrollToPosition(imageIndex - 1); } /** * Load next book */ private void nextBook() { viewModel.onLeaveBook(imageIndex, highestImageIndexReached); highestImageIndexReached = -1; viewModel.loadNextContent(); } /** * Load previous book */ private void previousBook() { viewModel.onLeaveBook(imageIndex, highestImageIndexReached); highestImageIndexReached = -1; viewModel.loadPreviousContent(); } /** * Seek to the given position; update preview images if they are visible * * @param position Position to go to (0-indexed) */ private void seekToPosition(int position) { if (View.VISIBLE == previewImage2.getVisibility()) { ImageFile img = adapter.getImageAt(position - 1); if (img != null) { Glide.with(previewImage1) .load(Uri.parse(img.getFileUri())) .apply(glideRequestOptions) .into(previewImage1); previewImage1.setVisibility(View.VISIBLE); } else previewImage1.setVisibility(View.INVISIBLE); img = adapter.getImageAt(position); if (img != null) Glide.with(previewImage2) .load(Uri.parse(img.getFileUri())) .apply(glideRequestOptions) .into(previewImage2); img = adapter.getImageAt(position + 1); if (img != null) { Glide.with(previewImage3) .load(Uri.parse(img.getFileUri())) .apply(glideRequestOptions) .into(previewImage3); previewImage3.setVisibility(View.VISIBLE); } else previewImage3.setVisibility(View.INVISIBLE); } if (position == imageIndex + 1 || position == imageIndex - 1) { recyclerView.smoothScrollToPosition(position); } else { recyclerView.scrollToPosition(position); } } /** * Go to the given page number * * @param pageNum Page number to go to (1-indexed) */ @Override public void goToPage(int pageNum) { int position = pageNum - 1; if (position == imageIndex || position < 0 || position > maxPosition) return; seekToPosition(position); } /** * Handler for tapping on the left zone of the screen */ private void onLeftTap() { // Stop slideshow if it is on if (slideshowTimer != null) { stopSlideshow(); return; } // Side-tapping disabled when view is zoomed if (recyclerView != null && recyclerView.getScale() != 1.0) return; // Side-tapping disabled when disabled in preferences if (!Preferences.isViewerTapToTurn()) return; if (Preferences.Constant.PREF_VIEWER_DIRECTION_LTR == Preferences.getViewerDirection()) previousPage(); else nextPage(); } /** * Handler for tapping on the right zone of the screen */ private void onRightTap() { // Stop slideshow if it is on if (slideshowTimer != null) { stopSlideshow(); return; } // Side-tapping disabled when view is zoomed if (recyclerView != null && recyclerView.getScale() != 1.0) return; // Side-tapping disabled when disabled in preferences if (!Preferences.isViewerTapToTurn()) return; if (Preferences.Constant.PREF_VIEWER_DIRECTION_LTR == Preferences.getViewerDirection()) nextPage(); else previousPage(); } /** * Handler for tapping on the middle zone of the screen */ private void onMiddleTap() { // Stop slideshow if it is on if (slideshowTimer != null) { stopSlideshow(); return; } if (View.VISIBLE == controlsOverlay.getVisibility()) hideControlsOverlay(); else showControlsOverlay(); } private void showControlsOverlay() { controlsOverlay.animate() .alpha(1.0f) .setDuration(100) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); controlsOverlay.setVisibility(View.VISIBLE); setSystemBarsVisible(true); } }); } private void hideControlsOverlay() { controlsOverlay.animate() .alpha(0.0f) .setDuration(100) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); controlsOverlay.setVisibility(View.INVISIBLE); } }); setSystemBarsVisible(false); } /** * Display the viewer gallery * * @param filterFavourites True if only favourite pages have to be shown; false for all pages */ private void displayGallery(boolean filterFavourites) { hasGalleryBeenShown = true; viewModel.setStartingIndex(imageIndex); // Memorize the current page if (getParentFragmentManager().getBackStackEntryCount() > 0) { // Gallery mode (Library -> gallery -> pager) getParentFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); // Leave only the latest element in the back stack } else { // Pager mode (Library -> pager -> gallery -> pager) getParentFragmentManager() .beginTransaction() .replace(android.R.id.content, ImageGalleryFragment.newInstance(filterFavourites)) .addToBackStack(null) .commit(); } } /** * Show / hide bottom and top Android system bars * * @param visible True if bars have to be shown; false instead */ private void setSystemBarsVisible(boolean visible) { int uiOptions; if (visible) { uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; } else { uiOptions = View.SYSTEM_UI_FLAG_IMMERSIVE // Set the content to appear under the system bars so that the // content doesn't resize when the system bars hide and show. | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // Hide the nav bar and status bar | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN; } // Defensive programming here because crash reports show that getView() sometimes is null // (just don't ask me why...) View v = getView(); if (v != null) v.setSystemUiVisibility(uiOptions); } private void onGetMaxDimensions(Point maxDimensions) { adapter.setMaxDimensions(maxDimensions.x, maxDimensions.y); } private void startSlideshow() { startSlideshow(true); } private void startSlideshow(boolean showToast) { // Hide UI hideControlsOverlay(); // Compute slideshow delay int delayPref = Preferences.getViewerSlideshowDelay(); int delaySec; switch (delayPref) { case Constant.PREF_VIEWER_SLIDESHOW_DELAY_4: delaySec = 4; break; case Constant.PREF_VIEWER_SLIDESHOW_DELAY_8: delaySec = 8; break; case Constant.PREF_VIEWER_SLIDESHOW_DELAY_16: delaySec = 16; break; default: delaySec = 2; } if (showToast) ToastUtil.toast(String.format("Starting slideshow (delay %ss)", delaySec)); scrollListener.disableScroll(); slideshowTimer = Observable.timer(delaySec, TimeUnit.SECONDS) .subscribeOn(Schedulers.computation()) .repeat() .observeOn(AndroidSchedulers.mainThread()) .subscribe(v -> nextPage()); } private void stopSlideshow() { if (slideshowTimer != null) { slideshowTimer.dispose(); slideshowTimer = null; scrollListener.enableScroll(); ToastUtil.toast("Slideshow stopped"); } } }
package org.gdg.frisbee.android.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import com.google.android.gms.analytics.HitBuilders; import com.google.android.gms.plus.PlusShare; import org.gdg.frisbee.android.Const; import org.gdg.frisbee.android.app.App; import org.gdg.frisbee.android.chapter.MainActivity; import org.gdg.frisbee.android.event.EventActivity; import timber.log.Timber; public class ParseDeepLinkActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent target = null; String deepLinkId = PlusShare.getDeepLinkId(getIntent()); if (!TextUtils.isEmpty(deepLinkId)) { target = parseDeepLinkId(deepLinkId); } else { if (Intent.ACTION_VIEW.equals(getIntent().getAction())) { target = new Intent(); target.setClass(getApplicationContext(), EventActivity.class); target.putExtra(Const.EXTRA_EVENT_ID, getIntent().getData().getLastPathSegment()); target.putExtra(Const.EXTRA_SECTION, EventActivity.EventPagerAdapter.SECTION_OVERVIEW); } } if (target != null) { if (target.resolveActivity(getPackageManager()) != null) { startActivity(target); } } finish(); } /** * Get the intent for an activity corresponding to the deep-link ID. * * @param deepLinkId The deep-link ID to parse. * @return The intent corresponding to the deep-link ID. */ @Nullable private Intent parseDeepLinkId(@NonNull String deepLinkId) { Intent route = new Intent(); Timber.d("Deep Link id: %s", deepLinkId); String[] parts = deepLinkId.split("/"); App.getInstance().getTracker().send(new HitBuilders.EventBuilder() .setCategory("gplus") .setAction("deepLink") .setLabel(deepLinkId) .build()); // or <plus_id>/events/<eventId>/join join is optional if (deepLinkId.startsWith(Const.URL_DEVELOPERS_GOOGLE_COM)) { route.setClass(getApplicationContext(), EventActivity.class); route.putExtra(Const.EXTRA_EVENT_ID, parts[4]); route.putExtra(Const.EXTRA_SECTION, EventActivity.EventPagerAdapter.SECTION_OVERVIEW); } else { // Fallback to the MainActivity in your app. route.setClass(getApplicationContext(), MainActivity.class); } return route; } }
package ve.com.abicelis.remindy.app.activities; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.BaseTransientBottomBar; import android.support.design.widget.Snackbar; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.support.v7.widget.helper.ItemTouchHelper; import android.view.Gravity; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.github.clans.fab.FloatingActionButton; import com.github.clans.fab.FloatingActionMenu; import com.transitionseverywhere.Slide; import com.transitionseverywhere.TransitionManager; import java.io.File; import java.util.ArrayList; import java.util.List; import ve.com.abicelis.remindy.R; import ve.com.abicelis.remindy.app.adapters.AttachmentAdapter; import ve.com.abicelis.remindy.database.RemindyDAO; import ve.com.abicelis.remindy.enums.AttachmentType; import ve.com.abicelis.remindy.enums.TaskCategory; import ve.com.abicelis.remindy.exception.CouldNotInsertDataException; import ve.com.abicelis.remindy.model.Task; import ve.com.abicelis.remindy.model.attachment.Attachment; import ve.com.abicelis.remindy.model.attachment.AudioAttachment; import ve.com.abicelis.remindy.model.attachment.LinkAttachment; import ve.com.abicelis.remindy.model.attachment.TextAttachment; import ve.com.abicelis.remindy.util.ConversionUtil; import ve.com.abicelis.remindy.util.FileUtil; import ve.com.abicelis.remindy.util.SnackbarUtil; public class NewTaskActivity extends AppCompatActivity implements View.OnClickListener { //CONST //DATA private List<String> reminderCategories; private int addAttachmentHintState = 0; private boolean attachmentLongClickOptionsDialogHintShown; private Task mTask = new Task(); private AttachmentAdapter mAdapter; private Toolbar mToolbar; private RelativeLayout mHeaderBasicInfo; private RelativeLayout mHeaderAttachments; private LinearLayout mContainer; private LinearLayout mContainerBasicInfo; private TextView mTaskTitle; private TextView mTaskDescription; private Spinner mTaskCategory; private TextView mAttachmentsFabHint; private FloatingActionMenu mAttachmentsFabMenu; private FloatingActionButton mAttachmentsFabList; private FloatingActionButton mAttachmentsFabText; private FloatingActionButton mAttachmentsFabLink; private FloatingActionButton mAttachmentsFabImage; private FloatingActionButton mAttachmentsFabAudio; private RecyclerView mRecyclerView; private LinearLayoutManager mLayoutManager; private RelativeLayout mNoItemsContainer; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_new_task); mHeaderBasicInfo = (RelativeLayout) findViewById(R.id.activity_new_task_header_basic_info); ((TextView) mHeaderBasicInfo.findViewById(R.id.item_task_header_title)).setText(R.string.activity_new_task_header_basic_info); mHeaderAttachments = (RelativeLayout) findViewById(R.id.activity_new_task_header_attachments); ((TextView) mHeaderAttachments.findViewById(R.id.item_task_header_title)).setText(R.string.activity_new_task_header_attachments); mContainer = (LinearLayout) findViewById(R.id.activity_new_task_container); mContainerBasicInfo = (LinearLayout) findViewById(R.id.activity_new_task_basic_info_container); mTaskTitle = (TextView) findViewById(R.id.activity_new_task_title); mTaskTitle.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(hasFocus) { mAttachmentsFabMenu.close(true); } } }); mTaskDescription = (TextView) findViewById(R.id.activity_new_task_description); mTaskDescription.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(hasFocus) { mAttachmentsFabMenu.close(true); } } }); mTaskCategory = (Spinner) findViewById(R.id.activity_new_task_category); //mAttachmentsFabHintContainer = (FrameLayout) findViewById(R.id.activity_new_task_add_attachment_hint_container); mAttachmentsFabHint = (TextView) findViewById(R.id.activity_new_task_add_attachment_hint); mAttachmentsFabMenu = (FloatingActionMenu) findViewById(R.id.activity_new_task_add_attachment); mAttachmentsFabMenu.setOnMenuToggleListener(new FloatingActionMenu.OnMenuToggleListener() { @Override public void onMenuToggle(boolean opened) { //Hide keyboard ((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(mContainer.getWindowToken(), 0); if(addAttachmentHintState == 1) { //Slide out FAB hint addAttachmentHintState = 2; TransitionManager.beginDelayedTransition(mContainer, new Slide(Gravity.START)); mAttachmentsFabHint.setVisibility(View.INVISIBLE); } } }); mAttachmentsFabList = (FloatingActionButton) findViewById(R.id.activity_new_task_add_list_attachment); mAttachmentsFabText = (FloatingActionButton) findViewById(R.id.activity_new_task_add_text_attachment); mAttachmentsFabLink = (FloatingActionButton) findViewById(R.id.activity_new_task_add_link_attachment); mAttachmentsFabImage = (FloatingActionButton) findViewById(R.id.activity_new_task_add_image_attachment); mAttachmentsFabAudio = (FloatingActionButton) findViewById(R.id.activity_new_task_add_audio_attachment); mAttachmentsFabList.setOnClickListener(this); mAttachmentsFabText.setOnClickListener(this); mAttachmentsFabLink.setOnClickListener(this); mAttachmentsFabImage.setOnClickListener(this); mAttachmentsFabAudio.setOnClickListener(this); mRecyclerView = (RecyclerView) findViewById(R.id.activity_new_task_recycler); mNoItemsContainer = (RelativeLayout) findViewById(R.id.activity_new_task_no_items_container); setUpRecyclerView(); setupSpinners(); setUpToolbar(); } @Override public void onWindowFocusChanged(boolean hasFocus) { //Slide in FAB hint if(addAttachmentHintState == 0) { addAttachmentHintState = 1; TransitionManager.beginDelayedTransition(mContainer, new Slide(Gravity.START)); mAttachmentsFabHint.setVisibility(View.VISIBLE); } } private void setUpRecyclerView() { mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); mAdapter = new AttachmentAdapter(this, mTask.getAttachments()); mAdapter.setShowAttachmentHintListener(new AttachmentAdapter.ShowAttachmentHintListener() { @Override public void onShowAttachmentHint() { if (!attachmentLongClickOptionsDialogHintShown) { attachmentLongClickOptionsDialogHintShown = true; SnackbarUtil.showSnackbar(mContainer, SnackbarUtil.SnackbarType.NOTICE, R.string.activity_new_task_snackbar_notice_attachments_options_hint, SnackbarUtil.SnackbarDuration.LONG, null); } } }); DividerItemDecoration itemDecoration = new DividerItemDecoration(this, mLayoutManager.getOrientation()); itemDecoration.setDrawable(ContextCompat.getDrawable(this, R.drawable.item_decoration_half_line)); mRecyclerView.addItemDecoration(itemDecoration); mRecyclerView.setLayoutManager(mLayoutManager); mRecyclerView.setAdapter(mAdapter); //TODO: Reenable or delete this code // ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) { // @Override // public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { // return false; // @Override // public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) { // int position = viewHolder.getAdapterPosition(); // Toast.makeText(NewTaskActivity.this, "Swiped position " + position + " into direction=" + swipeDir, Toast.LENGTH_SHORT).show(); // if(AttachmentType.AUDIO.equals(mTask.getAttachments().get(position).getType())) { // String filename = ((AudioAttachment)mTask.getAttachments().get(position)).getAudioFilename(); // if(filename != null && !filename.isEmpty()) { //Delete file // File audioAttachmentDir = FileUtil.getAudioAttachmentDir(NewTaskActivity.this); // File audioFile = new File(audioAttachmentDir, filename); // audioFile.delete(); // mTask.getAttachments().remove(position); // mAdapter.notifyItemRemoved(position); // mAdapter.notifyItemRangeChanged(position, mAdapter.getItemCount()); // ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback); // itemTouchHelper.attachToRecyclerView(mRecyclerView); } private void setUpToolbar() { mToolbar = (Toolbar) findViewById(R.id.activity_new_task_toolbar); mToolbar.setTitle(getResources().getString( R.string.activity_new_task_toolbar_title)); mToolbar.setNavigationIcon(ContextCompat.getDrawable(this, R.drawable.icon_back_material)); //Set toolbar as actionbar setSupportActionBar(mToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); } private void setupSpinners() { reminderCategories = TaskCategory.getFriendlyValues(this); ArrayAdapter reminderCategoryAdapter = new ArrayAdapter<>(this, R.layout.spinner_item, reminderCategories); reminderCategoryAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item); mTaskCategory.setAdapter(reminderCategoryAdapter); } private void addAttachment(Attachment attachment) { mTask.addAttachment(attachment); if(mAdapter.getItemCount() == 1) mAdapter.notifyDataSetChanged(); else mAdapter.notifyItemInserted(mAdapter.getItemCount()); } @Override public void onClick(View v) { int id = v.getId(); mAttachmentsFabMenu.close(true); if(addAttachmentHintState == 2) { addAttachmentHintState = 3; //Fade in headers TransitionManager.beginDelayedTransition(mContainer); mHeaderBasicInfo.setVisibility(View.VISIBLE); mHeaderAttachments.setVisibility(View.VISIBLE); RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mContainerBasicInfo.getLayoutParams(); lp.setMargins(ConversionUtil.dpToPx(16, getResources()), 0, 0, 0); mContainerBasicInfo.setLayoutParams(lp); } switch (id) { case R.id.activity_new_task_add_list_attachment: //TODO: Add list attachment to recycler! Toast.makeText(this, "TODO: add list attachment", Toast.LENGTH_SHORT).show(); break; case R.id.activity_new_task_add_text_attachment: addAttachment(new TextAttachment("")); break; case R.id.activity_new_task_add_link_attachment: addAttachment(new LinkAttachment("")); break; case R.id.activity_new_task_add_image_attachment: //TODO: Add image attachment to recycler! Toast.makeText(this, "TODO: add image attachment", Toast.LENGTH_SHORT).show(); break; case R.id.activity_new_task_add_audio_attachment: addAttachment(new AudioAttachment()); break; } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_task_new, menu); return true; } @Override public void onBackPressed() { AlertDialog dialog = new AlertDialog.Builder(this) .setTitle(getResources().getString(R.string.activity_new_task_exit_dialog_title)) .setMessage(getResources().getString(R.string.activity_new_task_exit_dialog_message)) .setPositiveButton(getResources().getString(R.string.activity_new_task_exit_dialog_positive), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); setResult(RESULT_CANCELED); //Task was NOT created, set result to CANCELLED finish(); } }) .setNegativeButton(getResources().getString(R.string.activity_new_task_exit_dialog_negative), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .create(); dialog.show(); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); switch (id) { case android.R.id.home: onBackPressed(); return true; case R.id.menu_task_new_next: AlertDialog dialog = new AlertDialog.Builder(this) .setTitle(getResources().getString(R.string.activity_new_task_next_dialog_title)) .setMessage(getResources().getString(R.string.activity_new_task_next_dialog_message)) .setPositiveButton(getResources().getString(R.string.activity_new_task_next_dialog_positive), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //TODO: Go to add-a-reminder activity Toast.makeText(NewTaskActivity.this, "Under construction!", Toast.LENGTH_SHORT).show(); dialog.dismiss(); } }) .setNegativeButton(getResources().getString(R.string.activity_new_task_next_dialog_negative), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { handleTaskSave(); dialog.dismiss(); } }) .create(); dialog.show(); break; } return false; } private void handleTaskSave() { //Check data if(mTaskTitle.getText().toString().isEmpty()) { SnackbarUtil.showSnackbar(mContainer, SnackbarUtil.SnackbarType.ERROR, R.string.activity_new_task_snackbar_error_no_title, SnackbarUtil.SnackbarDuration.LONG, null); return; } TaskCategory category = TaskCategory.values()[mTaskCategory.getSelectedItemPosition()]; mTask.setCategory(category); mTask.setTitle(mTaskTitle.getText().toString()); mTask.setDescription(mTaskDescription.getText().toString()); //TODO: Clear "blank" attachments, maybe warn user? try { RemindyDAO dao = new RemindyDAO(this); dao.insertTask(mTask); BaseTransientBottomBar.BaseCallback<Snackbar> callback = new BaseTransientBottomBar.BaseCallback<Snackbar>() { @Override public void onDismissed(Snackbar transientBottomBar, int event) { super.onDismissed(transientBottomBar, event); //TODO: Do this better: Send the activity the type of reminder that was added, // then swipe viewpager to proper page, then insert item into recycler, // not just refresh the whole viewpager //Intent returnIntent = new Intent(); //returnIntent.putExtra("REMIDNERTYPE", mTask.getReminderType().name()); //setResult(RESULT_OK,returnIntent); //Task was created, set result to OK setResult(RESULT_OK); //Task was created, set result to OK finish(); } }; SnackbarUtil.showSnackbar(mContainer, SnackbarUtil.SnackbarType.SUCCESS, R.string.activity_new_task_snackbar_save_successful, SnackbarUtil.SnackbarDuration.SHORT, callback); } catch (CouldNotInsertDataException e) { SnackbarUtil.showSnackbar(mContainer, SnackbarUtil.SnackbarType.ERROR, R.string.activity_new_task_snackbar_error_saving, SnackbarUtil.SnackbarDuration.SHORT, null); } } }
package pt.fccn.arquivo.pages; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.NoSuchElementException; import java.lang.RuntimeException; import java.net.URL; import javax.xml.parsers.*; import org.w3c.dom.*; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.Element; /** * @author Simao Fontes * */ public class IndexPage { // Webdriver that handles page interractions private final WebDriver driver; private static final String pageURLCheck = "index.jsp"; private String url =null; private static final String searchBox = "txtSearch"; private static final String searchButton = "btnSubmit"; private static final String highlightId = "ver-destaques"; private static final String linkTextEN = "English"; private String termsandconditionstitleTextPT = "Termos e Condições"; private static final String linkTextPT = "Português"; private static final String titleTextEN = "Arquivo.pt - the Portuguese Web Archive: search pages from the past"; private static final String titleTextPT = "Arquivo.pt: pesquisa sobre o passado"; private static final String cssTermsConditions = "#terms-conditions"; private boolean isPreProd=false; /** * Starts a new Index page */ public IndexPage(WebDriver driver){ this.driver = driver; try { Thread.sleep(5000); //wait for page to load } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } // Check that we're on the right page. String pageTitle= driver.getTitle(); if (!(pageTitle.contentEquals(titleTextEN) || (pageTitle.contentEquals(titleTextPT)))){ throw new IllegalStateException("This is not the index page\n Title of current page: " + pageTitle); } } /** * @param pre_prod * @return */ public boolean setPreProd(String pre_prod){ if (driver.getCurrentUrl().contains(pre_prod)){ this.isPreProd=true; } return isPreProd; } /** * Searches for a string in the interface * @param searchTerms String of terms to search for * @return result page for query */ public SearchPage search(String searchTerms){ WebElement searchBoxElement = (new WebDriverWait(driver, 25)) /* Wait Up to 25 seconds should throw RunTimeExcpetion*/ .until(ExpectedConditions.presenceOfElementLocated(By.id(searchBox))); searchBoxElement.clear(); searchBoxElement.sendKeys(searchTerms); WebElement searchButtonElement = (new WebDriverWait(driver, 25)) /* Wait Up to 25 seconds should throw RunTimeExcpetion*/ .until(ExpectedConditions.presenceOfElementLocated(By.id(searchButton))); searchButtonElement.submit(); return new SearchPage(driver,isPreProd); } private static Document loadTestDocument(String url) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); return factory.newDocumentBuilder().parse(new URL(url).openStream()); } /** * Searches for a string in the interface * @param searchTerms String of terms to search for * @return result page for query */ public OpenSearchPage opensearch(String searchTerms,boolean isPredprod){ Document doc = null; try { String[] Url = driver.getCurrentUrl().split(".pt"); DocumentBuilderFactory f = DocumentBuilderFactory.newInstance(); DocumentBuilder b = f.newDocumentBuilder(); doc = b.parse(Url[0]+".pt/opensearch?query="+searchTerms); doc.getDocumentElement().normalize(); System.out.println("URL: " + Url[0]+".pt/opensearch?query="+searchTerms); /*driver.get(Url[0]+".pt/opensearch?query="+searchTerms);*/ /* NodeList nList = doc.getElementsByTagName("item"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); System.out.println("\nCurrent Element :" + nNode.getNodeName()); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; System.out.println("URL: " + eElement.getElementsByTagName("link").item(0).getTextContent()); System.out.println("Arcname: " + eElement.getElementsByTagName("pwa:arcname").item(0).getTextContent()); } } */ }catch(Exception e){System.out.println("Error loading XML: " + e);} return new OpenSearchPage(driver,isPredprod,doc); } /** * Change language of the page to english */ public void langToEnglish(){ try{ WebElement langElem = driver.findElement(By.linkText(linkTextEN)); langElem.click(); try { Thread.sleep(5000); //wait for page to load } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } String pageTitle = driver.getTitle(); if (!titleTextEN.contentEquals(pageTitle)) throw new IllegalStateException("Expected Title: "+ titleTextEN + "\nFound Title: " + pageTitle); }catch (Exception e ){ System.out.println("Problems changing language to English"); e.printStackTrace(); throw e; } } /** * Click the Highlights page */ public HighlightsPage goToHighlightsPage(){ WebElement highligthLink = driver.findElement(By.id(highlightId)); highligthLink.click(); return new HighlightsPage(driver); } /** * Return the terms and conditions page * @return terms and conditions page */ public TermsAndConditionsPage getTermsAndConditionsPage(){ WebElement termsandconditionstitleTextPTElement = (new WebDriverWait(driver, 25)) /* Wait Up to 25 seconds should throw RunTimeExcpetion*/ /** * Return the image source from sponsor * @return the image */ public boolean isSponsorGovImageCorrect (){ WebElement image = driver.findElement(By.cssSelector("img[usemap=\"#logomap\"]")); String src = image.getAttribute("src"); return src.endsWith("mec-web.png"); } /** * Click the Highlights page */ public AdvancedPage goToAdvancedPage(){ try{ System.out.println("Waiting 50seconds for advanced search link"); WebElement advancedLink = (new WebDriverWait(driver, 50)) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until(ExpectedConditions.presenceOfElementLocated(By.id("pesquisa-avancada"))); advancedLink.click(); } catch(NoSuchElementException e){ System.out.println("Could not find the pesquisa-avancada element"); throw e; } catch (Exception e){ System.out.println("Unexpected Error. Unable to go to AdvancedPage"); throw e; } return new AdvancedPage(driver); } /** * Click the Highlights page */ public Arcproxyinspection arcProxy(Boolean isPreProd){ return new Arcproxyinspection(driver,isPreProd); } /** * Make a search by URL and inspect if the hostname is not case-sensitive * for instance, fccn.pt and fccn.PT are the same * @param query * @return */ public boolean searchbyURL(String query,String queryPT){ this.url = driver.getCurrentUrl(); /** * Get the anchor href of link matching xpath expression * */ public String getVersionURL(String query,String xpath){ try{ driver.get(this.url); WebElement txtSearchElement = (new WebDriverWait(driver, 25)) /* Wait Up to 25 seconds should throw RunTimeExcpetion*/ .until(ExpectedConditions.presenceOfElementLocated(By.id("txtSearch"))); txtSearchElement.clear(); txtSearchElement.sendKeys(query); WebElement btnSubmitElement = (new WebDriverWait(driver, 25)) /* Wait Up to 25 seconds should throw RunTimeExcpetion*/ .until(ExpectedConditions.presenceOfElementLocated(By.id("btnSubmit"))); btnSubmitElement.click(); WebElement dateAnchorElement = (new WebDriverWait(driver, 25)) /* Wait Up to 25 seconds should throw RunTimeExcpetion*/ .until(ExpectedConditions.presenceOfElementLocated(By.xpath(xpath))); return dateAnchorElement.getAttribute("href"); }catch(RuntimeException e ){ throw new IllegalStateException("Timed Out");} catch (Exception e ){ throw new IllegalStateException("Exception. Can't evaluate webpage title"); } } }
package services.galaxy; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import network.packets.soe.Disconnect; import network.packets.soe.Disconnect.DisconnectReason; import network.packets.swg.zone.HeartBeatMessage; import intents.CloseConnectionIntent; import intents.GalacticPacketIntent; import intents.PlayerEventIntent; import resources.control.Intent; import resources.control.Service; import resources.player.Player; import resources.player.PlayerEvent; import resources.player.PlayerFlags; import resources.player.PlayerState; public class ConnectionService extends Service { private static final double LD_THRESHOLD = TimeUnit.MINUTES.toMillis(3); // Time since last packet private static final double DISAPPEAR_THRESHOLD = TimeUnit.MINUTES.toMillis(2); // Time after the LD private final ScheduledExecutorService updateService; private final Runnable updateRunnable; private final Runnable disappearRunnable; private final Queue <Player> disappearPlayers; private final List <Player> zonedInPlayers; public ConnectionService() { updateService = Executors.newSingleThreadScheduledExecutor(); zonedInPlayers = new LinkedList<Player>(); disappearPlayers = new LinkedList<Player>(); updateRunnable = new Runnable() { public void run() { synchronized (zonedInPlayers) { for (Player p : zonedInPlayers) { if (p.getTimeSinceLastPacket() > LD_THRESHOLD) { logOut(p); disconnect(p, DisconnectReason.TIMEOUT); } } } } }; disappearRunnable = new Runnable() { public void run() { Player p = disappearPlayers.poll(); synchronized (zonedInPlayers) { if (p != null && zonedInPlayers.contains(p)) disappear(p); } } }; } @Override public boolean initialize() { registerForIntent(PlayerEventIntent.TYPE); registerForIntent(GalacticPacketIntent.TYPE); return super.initialize(); } @Override public boolean start() { updateService.scheduleAtFixedRate(updateRunnable, 10, 10, TimeUnit.SECONDS); return super.start(); } @Override public boolean terminate() { updateService.shutdownNow(); boolean success = false; try { success = updateService.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } return super.terminate() && success; } @Override public void onIntentReceived(Intent i) { if (i instanceof PlayerEventIntent) { if (((PlayerEventIntent)i).getEvent() == PlayerEvent.PE_ZONE_IN) { Player p = ((PlayerEventIntent)i).getPlayer(); synchronized (zonedInPlayers) { removeOld(p); zonedInPlayers.add(p); } } else if (((PlayerEventIntent)i).getEvent() == PlayerEvent.PE_DISAPPEAR) { synchronized (zonedInPlayers) { zonedInPlayers.remove(((PlayerEventIntent)i).getPlayer()); } } } else if (i instanceof GalacticPacketIntent) { if (((GalacticPacketIntent)i).getPacket() instanceof HeartBeatMessage) { GalacticPacketIntent gpi = (GalacticPacketIntent) i; Player p = gpi.getPlayerManager().getPlayerFromNetworkId(gpi.getNetworkId()); if (p != null) p.sendPacket(gpi.getPacket()); } else if (((GalacticPacketIntent)i).getPacket() instanceof Disconnect) { GalacticPacketIntent gpi = (GalacticPacketIntent) i; Player p = gpi.getPlayerManager().getPlayerFromNetworkId(gpi.getNetworkId()); if (p != null) { if (p.getPlayerState() != PlayerState.DISCONNECTED) { logOut(p); disconnect(p, DisconnectReason.TIMEOUT); } else { disconnect(p, DisconnectReason.OTHER_SIDE_TERMINATED); } } } } } private void removeOld(Player nPlayer) { synchronized (zonedInPlayers) { Iterator <Player> zonedIterator = zonedInPlayers.iterator(); while (zonedIterator.hasNext()) { Player old = zonedIterator.next(); if (old.equals(nPlayer)) { zonedIterator.remove(); disconnect(old, DisconnectReason.NEW_CONNECTION_ATTEMPT); } } } } private void logOut(Player p) { if (p.getPlayerState() != PlayerState.LOGGED_OUT) System.out.println("[" + p.getUsername() +"] Logged out " + p.getCharacterName()); p.setPlayerState(PlayerState.LOGGED_OUT); p.getPlayerObject().setFlagBitmask(PlayerFlags.LD); disappearPlayers.add(p); updateService.schedule(disappearRunnable, (long) DISAPPEAR_THRESHOLD, TimeUnit.MILLISECONDS); } private void disappear(Player p) { p.setPlayerState(PlayerState.DISCONNECTED); System.out.println("[" + p.getUsername() +"] " + p.getCharacterName() + " disappeared"); new PlayerEventIntent(p, PlayerEvent.PE_DISAPPEAR).broadcast(); } private void disconnect(Player player, DisconnectReason reason) { new CloseConnectionIntent(player.getConnectionId(), player.getNetworkId(), reason).broadcast(); } }
package com.ca.apm.swat.epaplugins.utils; /** * Contains all constants for CA App Synthetic Monitor EPA plugin. * @author Guenter Grossberger - CA APM SWAT Team * */ public interface AsmProperties { // constants public static final String TRUE = "true"; public static final String FALSE = "false"; public static final String EMPTY_STRING = ""; public static final String[] EMPTY_STRING_ARRAY = new String[0]; public static final String ZERO = "0"; public static final String ONE = "1"; public static final String YES = "y"; public static final String NO = "n"; public static final String NO_TYPE = "no type"; public static final String DATE_FORMAT = "yyyy-MM-dd"; public static final String DEFAULT_DELIMITER = ","; public static final String BLANK = " "; public static final String ASM_PRODUCT_NAME = "App Synthetic Monitor"; public static final String ASM_PRODUCT_NAME_SHORT = "ASM"; public static final String PROPERTY_FILE_NAME = "AppSyntheticMonitor.properties"; public static final String PASSWORD_URL = "https://dashboard.cloudmonitor.ca.com/en/change_passwd.php"; public static final String LOCALE = "asm.locale"; public static final String DEFAULT_LOCALE = "en_US"; public static final String ENCODING = "asm.encoding"; public static final String WAIT_TIME = "asm.waittime"; public static final String DISPLAY_CHECKPOINTS = "asm.displaycheckpoints"; // which metrics to get and display public static final String METRICS_STATS_FOLDER = "asm.metrics.stats.folder"; public static final String METRICS_STATS_RULE = "asm.metrics.stats.rule"; public static final String METRICS_CREDITS = "asm.metrics.credits"; public static final String METRICS_PUBLIC = "asm.metrics.public"; public static final String METRICS_LOGS = "asm.metrics.logs"; public static final String USE_PROXY = "asm.useProxy"; public static final String PROXY_HOST = "asm.proxyHost"; public static final String PROXY_PORT = "asm.proxyPort"; public static final String PROXY_USER = "asm.proxyUser"; public static final String PROXY_PASSWORD_ENCRYPTED = "asm.proxyPasswordEncrypted"; public static final String PROXY_PASSWORD = "asm.proxyPassword"; public static final String LOCAL_TEST = "asm.localtest"; public static final String LOCAL_TEST_PATH = "asm.localtestpath"; public static final String URL = "asm.URL"; public static final String USER = "asm.userEmail"; public static final String PASSWORD = "asm.APIPassword"; public static final String PASSWORD_ENCRYPTED = "asm.APIPasswordEncrypted"; public static final String INCLUDE_FOLDERS = "asm.includeFolders"; public static final String EXCLUDE_FOLDERS = "asm.excludeFolders"; public static final String SKIP_INACTIVE_FOLDERS = "asm.skipInactiveFolders"; public static final String SKIP_INACTIVE_MONITORS = "asm.skipInactiveMonitors"; public static final String FOLDER_PREFIX = "asm.folder."; public static final String NUM_LOGS = "asm.numlogs"; // folder and other constants in properties public static final String ROOT_FOLDER = "root_folder"; public static final String ALL_FOLDERS = "all_folders"; // TODO: not implemented yet!!! public static final String INCLUDE_TAGS = "asm.includeTags"; public static final String INCLUDE_MONITORS = "asm.includeMonitors"; public static final String RESULT_GROUPS = "asm.resultsGroups"; public static final String ALL_RULES = "all_rules"; public static final String ALL_TAGS = "all_tags"; public static final String GROUP_BY_FOLDER = "by_folder"; public static final String GROUP_BY_STATION = "by_station"; public static final String GROUP_MIXED = "mixed"; public static final String GROUP_NONE = "no_groups"; public static final String REPORT_JMETER_STEPS = "asm.reportJMeterSteps"; public static final String SUPPRESS_STEP_WITH_CODES = "asm.suppressStepsWithCodes"; public static final String HTTP_CODE_TRANSLATION = "asm.HTTPCodeTrans"; public static final String REPORT_STRING_RESULTS = "asm.reportStringResults"; public static final String REPORT_ASSERTION_FAILURES_AS = "asm.reportAssertionFailureAs"; public static final String LOG_ASM_ISSUES = "asm.logASMIssues="; // error codes public static final int ERROR_OK = 0; public static final int ERROR_AUTHORIZATION = 1000; public static final int ERROR_NORM = 1001; public static final int ERROR_SESSION_EXPIRED = 1008; // result codes public static final int RESULT_NOT_FOUND = 404; public static final int RESULT_PAGE_LOAD_TIMEOUT = 1043; public static final int RESULT_BANDWITH_EXCEEDED = 1060; public static final int RESULT_DOMAIN_REDIRECT = 6001; public static final int RESULT_PAGE_ELEMENT_404 = 6404; public static final int RESULT_CONNECTION_TERMINATED = 6007; public static final int RESULT_URL_CANNOT_BE_SHOWN = 6101; public static final int RESULT_RESPONSE_ASSERTION = 7001; public static final int RESULT_ASSERTION_NOT_MATCHED = 9501; // retries public static final int INIT_RETRIES = 10; public static final int THREAD_RETRIES = 10; public static final int BUFFER_WAIT_TIME = 60000; public static final String JAVA_NET_EXCEPTION_REGEX = ".*(BindException|ConnectException|HttpRetryException|NoRouteToHostException|" + "ProtocolException|SocketException|SocketTimeoutException|UnknownHostException).*"; // JSON constants public static final String JSON_PATTERN = "\\p{InCombiningDiacriticalMarks}+"; // Crypto constants public static final String kAlgorithm = "PBEWithMD5AndDES"; public static final String MESSAGE_DIGEST = "1D0NTF33LT4RDY"; // metric categories public static final String METRIC_TREE = "App Synthetic Monitor"; public static final String CREDITS_CATEGORY = "Credits"; public static final String LOG_CATEGORY = "Log"; public static final String PSP_CATEGORY = "Public Stats"; public static final String STATS_CATEGORY = "Stats"; public static final String MONITOR_METRIC_PREFIX = "Monitors|"; public static final String STATUS_METRIC_PREFIX = "Status Monitoring|"; public static final String METRIC_PATH_SEPARATOR = "|"; public static final String METRIC_NAME_SEPARATOR = ":"; // API commands public static final String HTTP_POST = "POST"; public static final String LOGIN_CMD = "acct_token"; public static final String LOGOUT_CMD = "acct_logout"; public static final String CREDITS_CMD = "acct_credits"; public static final String CHECKPOINTS_CMD = "cp_list"; public static final String FOLDER_CMD = "fldr_get"; public static final String RULE_CMD = "rule_get"; public static final String PSP_CMD = "rule_psp"; public static final String STATS_CMD = "rule_stats"; public static final String LOGS_CMD = "rule_log"; // command parameters public static final String NKEY_PARAM = "nkey="; public static final String CALLBACK_PARAM = "&callback="; public static final String DO_CALLBACK = "doCallback"; public static final String FOLDER_PARAM = "&folder="; public static final String NAME_PARAM = "&name="; public static final String REVERSE_PARAM = "&reverse=y"; public static final String NUM_PARAM = "&num="; public static final String START_DATE_PARAM = "&start_date="; public static final String ACCOUNT_PARAM = "&acct="; public static final String FULL_PARAM = "&full=y"; // response tags public static final String XML_PREFIX = "<?xml"; public static final String ACTIVE_TAG = "active"; public static final String AVAILABLE_TAG = "available"; public static final String AREA_TAG = "areas"; public static final String COUNTRY_TAG = "country_name"; public static final String CITY_TAG = "city"; public static final String CODE_TAG = "code"; public static final String CHECKPOINTS_TAG = "checkpoints"; public static final String CREDITS_TAG = "credits"; public static final String RESULT_TAG = "result"; public static final String NKEY_TAG = "nkey"; public static final String ERROR_TAG = "error"; public static final String ERRORS_TAG = "errors"; public static final String FOLDER_TAG = "folder"; public static final String FOLDERS_TAG = "folders"; public static final String RULES_TAG = "rules"; public static final String INFO_TAG = "info"; public static final String NAME_TAG = "name"; public static final String DESCR_TAG = "descr"; public static final String LOCATION_TAG = "loc"; public static final String MONITORS_TAG = "monitors"; public static final String STATS_TAG = "stats"; public static final String COLOR_TAG = "color"; public static final String COLORS_TAG = "colors"; public static final String ELAPSED_TAG = "elapsed"; public static final String TYPE_TAG = "type"; public static final String VERSION_TAG = "version"; public static final String OUTPUT_TAG = "output"; public static final String TAGS_TAG = "tags"; public static final String HAR_OR_LOG_TAG = "{\"har\""; //"{\"har\": {\"log\""; public static final String UNDEFINED = "Undefined"; // rule types public static final String HTTP_RULE = "http"; public static final String HTTPS_RULE = "https"; public static final String SCRIPT_RULE = "script"; public static final String BROWSER_RULE = "browser"; public static final String RBM_RULE = "script_firefox"; // JMeter log result tags public static final String TEST_RESULTS = "testResults"; public static final String RESPONSE_CODE_TAG = "rc"; public static final String RESPONSE_MESSAGE_TAG = "rm"; public static final String SUCCESS_FLAG_TAG = "s"; public static final String ERROR_COUNT_TAG = "ec"; public static final String TEST_URL_TAG = "lb"; public static final String UNDEFINED_ASSERTION = "Undefined Assertion"; public static final String ASSERTION_RESULT = "assertionResult"; public static final String FAILURE = "failure"; public static final String STEP = "Step "; public static final String ASSERTION_FAILURE = " - Assertion Failure"; public static final String ASSERTION_ERROR = " - Assertion Error"; // JMeter metrics public static final String STATUS_MESSAGE = "Status Message"; public static final String STATUS_MESSAGE_VALUE = "Status Message Value"; public static final String RESPONSE_CODE = "Response Code"; public static final String ERROR_COUNT = "Error Count"; public static final String ASSERTION_FAILURES = "Assertion Failures"; public static final String ASSERTION_ERRORS = "Assertion Errors"; public static final String TEST_URL = "URL"; // status indicator colors, see AsmPropertiesImpl.APM_CM_COLORS public static final String GREEN = "green"; public static final String YELLOW = "yellow"; public static final String ORANGE = "orange"; public static final String RED = "red"; }
package helpers.db.dao; import helpers.db.PaginatedList; import helpers.db.PaginatedLists; import helpers.db.QueryParam; import helpers.db.filter.FilterCriteria; import helpers.db.sort.SortCriteria; import java.util.List; /** * Base DAO. * * @author jtremeaux */ public abstract class BaseDao<T, C> { /** * Search items by criteria. * * @param list Paginated list (updated by side effects) * @param criteria Search criteria * @param sortCriteria Sort criteria * @param filterCriteria Filter criteria */ public void findByCriteria(PaginatedList<T> list, C criteria, SortCriteria sortCriteria, FilterCriteria filterCriteria) { PaginatedLists.executePaginatedQuery(list, getQueryParam(criteria, filterCriteria), sortCriteria); } /** * Search items by criteria. * * @param list Paginated list (updated by side effects) * @param criteria Search criteria * @param sortCriteria Sort criteria */ public void findByCriteria(PaginatedList<T> list, C criteria, SortCriteria sortCriteria) { PaginatedLists.executePaginatedQuery(list, getQueryParam(criteria, null), sortCriteria); } /** * Search items by criteria. * * @param criteria Search criteria * @param sortCriteria Sort criteria * @param filterCriteria Filter criteria */ public List<T> findByCriteria(C criteria, SortCriteria sortCriteria, FilterCriteria filterCriteria) { return PaginatedLists.executeQuery(getQueryParam(criteria, filterCriteria), sortCriteria); } /** * Search items by criteria. * * @param criteria Search criteria * @param sortCriteria Sort criteria */ public List<T> findByCriteria(C criteria, SortCriteria sortCriteria) { return PaginatedLists.executeQuery(getQueryParam(criteria, null), sortCriteria); } /** * Search items by criteria. * * @param criteria Search criteria */ public List<T> findByCriteria(C criteria) { return findByCriteria(criteria, null, null); } /** * Search items by criteria. * * @param criteria Search criteria */ public T findFirstByCriteria(C criteria) { List<T> list = PaginatedLists.executeQuery(getQueryParam(criteria, null), null); return !list.isEmpty() ? list.iterator().next() : null; } protected abstract QueryParam getQueryParam(C criteria, FilterCriteria filterCriteria); }
package me.winspeednl.libz.level; import java.util.ArrayList; import me.winspeednl.libz.core.GameCore; import me.winspeednl.libz.image.Sprite; import me.winspeednl.libz.screen.Render; public class Level { private ArrayList<Tile> tiles; private ArrayList<Tile> mapTiles; private ArrayList<String> mapData; private int width, height, tileSize; private String[] rawMapData; private Tile[] rawMapTiles; public Level() { tiles = new ArrayList<Tile>(); mapTiles = new ArrayList<Tile>(); mapData = new ArrayList<String>(); } public void loadMap(String[] mapData, int w, int h, Tile[] tileList, int s) { this.rawMapData = mapData; this.rawMapTiles = tileList; width = w; height = h; tileSize = s; for (Tile tile : tileList) { mapTiles.add(tile); } for (String data : mapData) { this.mapData.add(data); } for (int i = 0; i < mapData.length; i++) { Tile tile = mapTiles.get(Integer.parseInt(this.mapData.get(i))); int X = i * tileSize; int Y = 0; if (i != 0) { Y = Integer.parseInt(String.valueOf((i / width)).split(",")[0]) * tileSize; X -= Y * width; } else Y = 0; Tile newTile = createTile(tile.getSprite(), X, Y, tileSize, tileSize, tile.getRotationRadians(), tile.isSolid(), tile.isFlippedX(), tile.isFlippedY()); tiles.add(newTile); } } public int getWidth() { return width; } public int getHeight() { return height; } public int getTileSize() { return tileSize; } public void addTile(Tile tile) { tiles.add(tile); } public Tile getTile(int x, int y) { return tiles.get(x + y * width); } public Tile createTile(String sprite, int x, int y, int w, int h, boolean isSolid) { Tile tile = new Tile(sprite, x, y, w, h, isSolid, 0, false, false); return tile; } public Tile createTile(String sprite, int x, int y, int w, int h, double rot, boolean isSolid) { Tile tile = new Tile(sprite, x, y, w, h, isSolid, Math.toRadians(rot), false, false); return tile; } public Tile createTile(String sprite, int x, int y, int w, int h, double rot, boolean isSolid, boolean flipX, boolean flipY) { Tile tile = new Tile(sprite, x, y, w, h, isSolid, Math.toRadians(rot), flipX, flipY); return tile; } public Tile createTile(Sprite sprite, int x, int y, int w, int h, boolean isSolid) { Tile tile = new Tile(sprite, x, y, w, h, isSolid, 0, false, false); return tile; } public void removeTile(Tile tile) { tiles.remove(tile); } public void removeTile(int x, int y) { Tile tile = null; synchronized (tiles) { for (Tile t : tiles) { if (t.getX() == x && t.getY() == y) { tile = t; break; } } } tiles.remove(tile); } public ArrayList<Tile> getTiles() { return tiles; } public void setTile(int index, Tile tile) { tiles.set(index, tile); } public Tile[] getMapTiles() { return rawMapTiles; } public String[] getMapData() { return rawMapData; } public void render(GameCore gc, Render r) { synchronized (getTiles()) { for (int i = 0; i < getTiles().size(); i++) { Tile tile = getTiles().get(i); if (tile.getX() > gc.getOffsetX() - tile.getWidth() && tile.getX() < gc.getWidth() + gc.getOffsetX()) { if (tile.getY() > gc.getOffsetY() - tile.getHeight() && tile.getY() < gc.getHeight() + gc.getOffsetY()) { for (int x = 0; x < tile.getWidth(); x++) { for (int y = 0; y < tile.getHeight(); y++) { if (tile.getPixels()[x + y * tile.getWidth()] != gc.getSpriteBGColor()) r.setPixel(tile.getX() + x, tile.getY() + y, tile.getPixels()[x + y * tile.getWidth()]); } } } } } } } }
package com.jenjinstudios.world; import com.jenjinstudios.world.state.MoveState; import java.util.LinkedList; import java.util.logging.Level; import java.util.logging.Logger; import static com.jenjinstudios.world.state.MoveState.IDLE; public class Actor extends SightedObject { /** The length of each step. */ public static final float STEP_LENGTH = 5; /** The maximum number of steps this actor is allowed to correct. */ public static final int MAX_CORRECT = 10; /** The logger for this class. */ private static final Logger LOGGER = Logger.getLogger(Actor.class.getName()); /** The next move. */ private final LinkedList<MoveState> nextMoveStates; /** The current move. */ private MoveState currentMoveState; /** The number of steps taken since the last move. */ private int stepsTaken = 0; /** The number of steps in the last completed move. */ private int stepsInLastCompletedMove; /** Flags whether this actor has changed to a new state during this update. */ private boolean newState; /** Keeps track of the next state in the queue. */ private MoveState nextState; /** Flags whether the state of this actor was forced during this update. */ private boolean forcedState; /** Construct a new Actor. */ public Actor() { this(DEFAULT_NAME); } /** * Construct an Actor with the given name. * * @param name The name. */ public Actor(String name) { super(name); currentMoveState = new MoveState(IDLE, 0, 0); nextMoveStates = new LinkedList<>(); } /** * Add a new MoveState to the actor's queue. * * @param newState The MoveState to add. */ public void addMoveState(MoveState newState) { if (nextState == null) nextState = newState; else nextMoveStates.add(newState); } @Override public void update() { resetFlags(); // Store the current state (before step) Location oldLocation = getLocation(); step(); // If we're in a new locations after stepping, update the visible array. if (oldLocation != getLocation() || getVisibleLocations().isEmpty()) resetVisibleLocations(); // Reset the array of visible actors. resetVisibleObjects(); } /** Reset the flags used by this actor. */ private void resetFlags() { newState = false; forcedState = false; } /** Take a step, changing state and correcting steps if necessary. */ public void step() { tryStateChange(); stepForward(); stepsTaken++; } /** Change to the next state, and correct for any over steps. */ private void tryStateChange() { if (nextState == null) return; int overStepped = stepsTaken - nextState.stepsUntilChange; if (overStepped >= MAX_CORRECT) { stopMaxCorrect(); } else if (overStepped >= 0) { doStateChange(overStepped); } } /** * Perform a state change. * * @param overStepped The number of steps beyond what the actor should have taken. */ private void doStateChange(int overStepped) { // Store the old state. MoveState oldState = currentMoveState; stepsInLastCompletedMove = nextState.stepsUntilChange; currentMoveState = nextState; if (!nextMoveStates.isEmpty()) nextState = nextMoveStates.remove(); newState = true; stepsTaken = 0; setDirection(currentMoveState.moveAngle); // Correct for any "over" steps. correctSteps(overStepped, oldState); } /** Stop the actor from correcting more steps than the allowed maximum. */ private void stopMaxCorrect() { nextState = null; nextMoveStates.clear(); setForcedState(currentMoveState); } /** * Correct the given number of steps at the specified angles. * * @param overstepped The number of steps over. * @param oldState The */ private void correctSteps(int overstepped, MoveState oldState) { if (oldState.direction != MoveState.IDLE) for (int i = 0; i < overstepped; i++) stepBack(oldState.stepAngle); for (int i = 0; i < overstepped; i++) stepForward(); } /** Take a step according to the current move state. */ public void stepForward() { if (currentMoveState.direction == IDLE) return; try { setVector2D(getVector2D().getVectorInDirection(STEP_LENGTH, currentMoveState.stepAngle)); } catch (InvalidLocationException ex) { // TODO This is where we need to force-idle, and raise the forced-state flag. setForcedState(new MoveState(IDLE, stepsTaken, currentMoveState.moveAngle)); } } /** * Take a step back in according to the given forward angle. * * @param stepAngle The angle in which to move backward. */ private void stepBack(double stepAngle) { stepAngle -= Math.PI; if (currentMoveState.direction == IDLE) return; try { setVector2D(getVector2D().getVectorInDirection(STEP_LENGTH, stepAngle)); } catch (InvalidLocationException ex) { // Something very strange is happening if corrected steps lead out of bounds... LOGGER.log(Level.SEVERE, "Error while correcting client steps.", ex); } } /** * Get whether this actor has initialized a new state during this update. * * @return Whether the actor has changed moved states since the beginning of this update. */ public boolean isNewState() {return newState;} /** * Get the direction in which the object is currently facing. * * @return The direction in which the object is currently facing. */ public double getCurrentAngle() {return currentMoveState.moveAngle;} /** * Get the number of steps taken since the last state change. * * @return The number of steps taken since the last state change. */ public int getStepsTaken() {return stepsTaken;} /** * Get the steps taken to complete the previous move. * * @return The steps taken to complete the previous move. */ public int getStepsInLastCompletedMove() {return stepsInLastCompletedMove;} /** * Get the actor's current move state. * * @return The actor's current move state. */ public MoveState getCurrentMoveState() { return currentMoveState; } /** * Get whether this actor was forced into a state during the most recent update. * * @return Whether this actor was forced into a state during the most recent update. */ public boolean isForcedState() { return forcedState; } /** * Force the state of this actor to the given state and raise the forcedState flag. * * @param forced The state to which to force this actor. */ public void setForcedState(MoveState forced) { stepBack(currentMoveState.stepAngle); this.currentMoveState = forced; forcedState = true; } }
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ package processing.app; import cc.arduino.packages.MonitorFactory; import cc.arduino.view.StubMenuListener; import cc.arduino.view.findreplace.FindReplace; import com.google.common.base.Predicate; import com.jcraft.jsch.JSchException; import jssc.SerialPortException; import processing.app.debug.*; import processing.app.forms.PasswordAuthorizationDialog; import processing.app.helpers.OSUtils; import processing.app.helpers.PreferencesMapException; import processing.app.legacy.PApplet; import processing.app.syntax.*; import processing.app.tools.*; import static processing.app.I18n._; import java.awt.*; import java.awt.datatransfer.*; import java.awt.event.*; import java.awt.print.*; import java.io.*; import java.net.*; import java.util.*; import java.util.List; import java.util.zip.*; import javax.swing.*; import javax.swing.border.MatteBorder; import javax.swing.event.*; import javax.swing.text.*; import javax.swing.undo.*; import org.fife.ui.rsyntaxtextarea.RSyntaxDocument; import org.fife.ui.rsyntaxtextarea.RSyntaxTextAreaEditorKit; import org.fife.ui.rsyntaxtextarea.RSyntaxUtilities; import org.fife.ui.rtextarea.Gutter; import org.fife.ui.rtextarea.RTextScrollPane; import cc.arduino.packages.BoardPort; import cc.arduino.packages.Uploader; import cc.arduino.packages.uploaders.SerialUploader; /** * Main editor panel for the Processing Development Environment. */ @SuppressWarnings("serial") public class Editor extends JFrame implements RunnerListener { public static final int MAX_TIME_AWAITING_FOR_RESUMING_SERIAL_MONITOR = 5000; private final Platform platform; private JMenu recentSketchesMenu; private JMenu programmersMenu; private static class ShouldSaveIfModified implements Predicate<Sketch> { @Override public boolean apply(Sketch sketch) { return PreferencesData.getBoolean("editor.save_on_verify") && sketch.isModified() && !sketch.isReadOnly(); } } private static class ShouldSaveReadOnly implements Predicate<Sketch> { @Override public boolean apply(Sketch sketch) { return sketch.isReadOnly(); } } private final static List<String> BOARD_PROTOCOLS_ORDER = Arrays.asList("serial", "network"); private final static List<String> BOARD_PROTOCOLS_ORDER_TRANSLATIONS = Arrays.asList(_("Serial ports"), _("Network ports")); final Base base; // otherwise, if the window is resized with the message label // set to blank, it's preferredSize() will be fukered private static final String EMPTY = " " + " " + " "; /** Command on Mac OS X, Ctrl on Windows and Linux */ private static final int SHORTCUT_KEY_MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); /** Command-W on Mac OS X, Ctrl-W on Windows and Linux */ static final KeyStroke WINDOW_CLOSE_KEYSTROKE = KeyStroke.getKeyStroke('W', SHORTCUT_KEY_MASK); /** Command-Option on Mac OS X, Ctrl-Alt on Windows and Linux */ static final int SHORTCUT_ALT_KEY_MASK = ActionEvent.ALT_MASK | Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); /** * true if this file has not yet been given a name by the user */ boolean untitled; private PageFormat pageFormat; // file, sketch, and tools menus for re-inserting items private JMenu fileMenu; private JMenu toolsMenu; private int numTools = 0; private final EditorToolbar toolbar; // these menus are shared so that they needn't be rebuilt for all windows // each time a sketch is created, renamed, or moved. static JMenu toolbarMenu; static JMenu sketchbookMenu; static JMenu examplesMenu; static JMenu importMenu; private static JMenu portMenu; static volatile AbstractMonitor serialMonitor; final EditorHeader header; EditorStatus status; EditorConsole console; private JSplitPane splitPane; // currently opened program Sketch sketch; private EditorLineStatus lineStatus; //JEditorPane editorPane; private SketchTextArea textarea; private RTextScrollPane scrollPane; //Runner runtime; private JMenuItem saveMenuItem; private JMenuItem saveAsMenuItem; //boolean presenting; private boolean uploading; // undo fellers private JMenuItem undoItem; private JMenuItem redoItem; protected UndoAction undoAction; protected RedoAction redoAction; private FindReplace find; Runnable runHandler; Runnable presentHandler; private Runnable runAndSaveHandler; private Runnable presentAndSaveHandler; private Runnable stopHandler; Runnable exportHandler; private Runnable exportAppHandler; public Editor(Base ibase, File file, int[] storedLocation, int[] defaultLocation, Platform platform) throws Exception { super("Arduino"); this.base = ibase; this.platform = platform; Base.setIcon(this); // Install default actions for Run, Present, etc. resetHandlers(); // add listener to handle window close box hit event addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { base.handleClose(Editor.this); } }); // don't close the window when clicked, the app will take care // of that via the handleQuitInternal() methods setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // When bringing a window to front, let the Base know addWindowListener(new WindowAdapter() { public void windowActivated(WindowEvent e) { base.handleActivated(Editor.this); } // added for 1.0.5 public void windowDeactivated(WindowEvent e) { fileMenu.remove(sketchbookMenu); fileMenu.remove(examplesMenu); List<Component> toolsMenuItemsToRemove = new LinkedList<Component>(); for (Component menuItem : toolsMenu.getMenuComponents()) { if (menuItem instanceof JComponent) { Object removeOnWindowDeactivation = ((JComponent) menuItem).getClientProperty("removeOnWindowDeactivation"); if (removeOnWindowDeactivation != null && Boolean.valueOf(removeOnWindowDeactivation.toString())) { toolsMenuItemsToRemove.add(menuItem); } } } for (Component menuItem : toolsMenuItemsToRemove) { toolsMenu.remove(menuItem); } toolsMenu.remove(portMenu); } }); //PdeKeywords keywords = new PdeKeywords(); //sketchbook = new Sketchbook(this); buildMenuBar(); // For rev 0120, placing things inside a JPanel Container contentPain = getContentPane(); contentPain.setLayout(new BorderLayout()); JPanel pain = new JPanel(); pain.setLayout(new BorderLayout()); contentPain.add(pain, BorderLayout.CENTER); Box box = Box.createVerticalBox(); Box upper = Box.createVerticalBox(); if (toolbarMenu == null) { toolbarMenu = new JMenu(); base.rebuildToolbarMenu(toolbarMenu); } toolbar = new EditorToolbar(this, toolbarMenu); upper.add(toolbar); header = new EditorHeader(this); upper.add(header); textarea = createTextArea(); textarea.setName("editor"); // assemble console panel, consisting of status area and the console itself JPanel consolePanel = new JPanel(); consolePanel.setLayout(new BorderLayout()); status = new EditorStatus(this); consolePanel.add(status, BorderLayout.NORTH); console = new EditorConsole(this); console.setName("console"); // windows puts an ugly border on this guy console.setBorder(null); consolePanel.add(console, BorderLayout.CENTER); lineStatus = new EditorLineStatus(); consolePanel.add(lineStatus, BorderLayout.SOUTH); // RTextScrollPane scrollPane = new RTextScrollPane(textarea, true); scrollPane.setBorder(new MatteBorder(0, 6, 0, 0, Theme.getColor("editor.bgcolor"))); scrollPane.setViewportBorder(BorderFactory.createEmptyBorder()); scrollPane.setLineNumbersEnabled(PreferencesData.getBoolean("editor.linenumbers")); scrollPane.setIconRowHeaderEnabled(false); Gutter gutter = scrollPane.getGutter(); gutter.setBookmarkingEnabled(false); //gutter.setBookmarkIcon(CompletionsRenderer.getIcon(CompletionType.TEMPLATE)); gutter.setIconRowHeaderInheritsGutterBackground(true); upper.add(scrollPane); splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, upper, consolePanel); splitPane.setOneTouchExpandable(true); // repaint child panes while resizing splitPane.setContinuousLayout(true); // if window increases in size, give all of increase to // the textarea in the uppper pane splitPane.setResizeWeight(1D); // to fix ugliness.. normally macosx java 1.3 puts an // ugly white border around this object, so turn it off. splitPane.setBorder(null); // the default size on windows is too small and kinda ugly int dividerSize = PreferencesData.getInteger("editor.divider.size"); if (dividerSize != 0) { splitPane.setDividerSize(dividerSize); } // the following changed from 600, 400 for netbooks splitPane.setMinimumSize(new Dimension(600, 100)); box.add(splitPane); // hopefully these are no longer needed w/ swing // (har har har.. that was wishful thinking) // listener = new EditorListener(this, textarea); pain.add(box); // get shift down/up events so we can show the alt version of toolbar buttons textarea.addKeyListener(toolbar); pain.setTransferHandler(new FileDropHandler()); // System.out.println("t1"); // Finish preparing Editor (formerly found in Base) pack(); // System.out.println("t2"); // Set the window bounds and the divider location before setting it visible setPlacement(storedLocation, defaultLocation); // Set the minimum size for the editor window setMinimumSize(new Dimension(PreferencesData.getInteger("editor.window.width.min"), PreferencesData.getInteger("editor.window.height.min"))); // System.out.println("t3"); // Bring back the general options for the editor applyPreferences(); // System.out.println("t4"); // Open the document that was passed in boolean loaded = handleOpenInternal(file); if (!loaded) sketch = null; // System.out.println("t5"); // All set, now show the window //setVisible(true); } /** * Handles files dragged & dropped from the desktop and into the editor * window. Dragging files into the editor window is the same as using * "Sketch &rarr; Add File" for each file. */ private class FileDropHandler extends TransferHandler { public boolean canImport(JComponent dest, DataFlavor[] flavors) { return true; } @SuppressWarnings("unchecked") public boolean importData(JComponent src, Transferable transferable) { int successful = 0; try { DataFlavor uriListFlavor = new DataFlavor("text/uri-list;class=java.lang.String"); if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { List<File> list = (List<File>) transferable.getTransferData(DataFlavor.javaFileListFlavor); for (File file : list) { if (sketch.addFile(file)) { successful++; } } } else if (transferable.isDataFlavorSupported(uriListFlavor)) { // Some platforms (Mac OS X and Linux, when this began) preferred // this method of moving files. String data = (String)transferable.getTransferData(uriListFlavor); String[] pieces = PApplet.splitTokens(data, "\r\n"); for (String piece : pieces) { if (piece.startsWith("#")) continue; String path = null; if (piece.startsWith("file: path = piece.substring(7); } else if (piece.startsWith("file:/")) { path = piece.substring(5); } if (sketch.addFile(new File(path))) { successful++; } } } } catch (Exception e) { e.printStackTrace(); return false; } if (successful == 0) { statusError(_("No files were added to the sketch.")); } else if (successful == 1) { statusNotice(_("One file added to the sketch.")); } else { statusNotice( I18n.format(_("{0} files added to the sketch."), successful)); } return true; } } private void setPlacement(int[] storedLocation, int[] defaultLocation) { if (storedLocation.length > 5 && storedLocation[5] != 0) { setExtendedState(storedLocation[5]); setPlacement(defaultLocation); } else { setPlacement(storedLocation); } } private void setPlacement(int[] location) { setBounds(location[0], location[1], location[2], location[3]); if (location[4] != 0) { splitPane.setDividerLocation(location[4]); } } protected int[] getPlacement() { int[] location = new int[6]; // Get the dimensions of the Frame Rectangle bounds = getBounds(); location[0] = bounds.x; location[1] = bounds.y; location[2] = bounds.width; location[3] = bounds.height; // Get the current placement of the divider location[4] = splitPane.getDividerLocation(); location[5] = getExtendedState() & MAXIMIZED_BOTH; return location; } /** * Hack for #@#)$(* Mac OS X 10.2. * <p/> * This appears to only be required on OS X 10.2, and is not * even being called on later versions of OS X or Windows. */ // public Dimension getMinimumSize() { // //System.out.println("getting minimum size"); // return new Dimension(500, 550); /** * Read and apply new values from the preferences, either because * the app is just starting up, or the user just finished messing * with things in the Preferences window. */ public void applyPreferences() { // apply the setting for 'use external editor' boolean external = PreferencesData.getBoolean("editor.external"); textarea.setEditable(!external); saveMenuItem.setEnabled(!external); saveAsMenuItem.setEnabled(!external); textarea.setCodeFoldingEnabled(PreferencesData.getBoolean("editor.code_folding")); scrollPane.setLineNumbersEnabled(PreferencesData.getBoolean("editor.linenumbers")); if (external) { // disable line highlight and turn off the caret when disabling textarea.setBackground(Theme.getColor("editor.external.bgcolor")); textarea.setHighlightCurrentLine(false); textarea.setEditable(false); } else { textarea.setBackground(Theme.getColor("editor.bgcolor")); textarea.setHighlightCurrentLine(PreferencesData.getBoolean("editor.linehighlight")); textarea.setEditable(true); } // apply changes to the font size for the editor //TextAreaPainter painter = textarea.getPainter(); textarea.setFont(PreferencesData.getFont("editor.font")); //Font font = painter.getFont(); //textarea.getPainter().setFont(new Font("Courier", Font.PLAIN, 36)); // in case tab expansion stuff has changed // listener.applyPreferences(); // in case moved to a new location // For 0125, changing to async version (to be implemented later) //sketchbook.rebuildMenus(); // For 0126, moved into Base, which will notify all editors. //base.rebuildMenusAsync(); } private void buildMenuBar() { JMenuBar menubar = new JMenuBar(); final JMenu fileMenu = buildFileMenu(); fileMenu.addMenuListener(new StubMenuListener() { @Override public void menuSelected(MenuEvent e) { List<Component> components = Arrays.asList(fileMenu.getComponents()); if (!components.contains(sketchbookMenu)) { fileMenu.insert(sketchbookMenu, 3); } if (!components.contains(sketchbookMenu)) { fileMenu.insert(examplesMenu, 4); } fileMenu.revalidate(); validate(); } }); menubar.add(fileMenu); menubar.add(buildEditMenu()); final JMenu sketchMenu = new JMenu(_("Sketch")); sketchMenu.setMnemonic(KeyEvent.VK_S); sketchMenu.addMenuListener(new StubMenuListener() { @Override public void menuSelected(MenuEvent e) { buildSketchMenu(sketchMenu); sketchMenu.revalidate(); validate(); } }); buildSketchMenu(sketchMenu); menubar.add(sketchMenu); final JMenu toolsMenu = buildToolsMenu(); toolsMenu.addMenuListener(new StubMenuListener() { @Override public void menuSelected(MenuEvent e) { List<Component> components = Arrays.asList(toolsMenu.getComponents()); int offset = 0; for (JMenu menu : base.getBoardsCustomMenus()) { if (!components.contains(menu)) { toolsMenu.insert(menu, numTools + offset); offset++; } } if (!components.contains(portMenu)) { toolsMenu.insert(portMenu, numTools + offset); } programmersMenu.removeAll(); base.getProgrammerMenus().forEach(programmersMenu::add); toolsMenu.revalidate(); validate(); } }); menubar.add(toolsMenu); menubar.add(buildHelpMenu()); setJMenuBar(menubar); } private JMenu buildFileMenu() { JMenuItem item; fileMenu = new JMenu(_("File")); fileMenu.setMnemonic(KeyEvent.VK_F); item = newJMenuItem(_("New"), 'N'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { base.handleNew(); } catch (Exception e1) { e1.printStackTrace(); } } }); fileMenu.add(item); item = Editor.newJMenuItem(_("Open..."), 'O'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { base.handleOpenPrompt(); } catch (Exception e1) { e1.printStackTrace(); } } }); fileMenu.add(item); base.rebuildRecentSketchesMenuItems(); recentSketchesMenu = new JMenu(_("Open Recent")); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { rebuildRecentSketchesMenu(); } }); fileMenu.add(recentSketchesMenu); if (sketchbookMenu == null) { sketchbookMenu = new JMenu(_("Sketchbook")); MenuScroller.setScrollerFor(sketchbookMenu); base.rebuildSketchbookMenu(sketchbookMenu); } fileMenu.add(sketchbookMenu); if (examplesMenu == null) { examplesMenu = new JMenu(_("Examples")); MenuScroller.setScrollerFor(examplesMenu); base.rebuildExamplesMenu(examplesMenu); } fileMenu.add(examplesMenu); item = Editor.newJMenuItem(_("Close"), 'W'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handleClose(Editor.this); } }); fileMenu.add(item); saveMenuItem = newJMenuItem(_("Save"), 'S'); saveMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSave(false); } }); fileMenu.add(saveMenuItem); saveAsMenuItem = newJMenuItemShift(_("Save As..."), 'S'); saveAsMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSaveAs(); } }); fileMenu.add(saveAsMenuItem); fileMenu.addSeparator(); item = newJMenuItemShift(_("Page Setup"), 'P'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePageSetup(); } }); fileMenu.add(item); item = newJMenuItem(_("Print"), 'P'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePrint(); } }); fileMenu.add(item); // macosx already has its own preferences and quit menu if (!OSUtils.isMacOS()) { fileMenu.addSeparator(); item = newJMenuItem(_("Preferences"), ','); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handlePrefs(); } }); fileMenu.add(item); fileMenu.addSeparator(); item = newJMenuItem(_("Quit"), 'Q'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handleQuit(); } }); fileMenu.add(item); } return fileMenu; } public void rebuildRecentSketchesMenu() { recentSketchesMenu.removeAll(); for (JMenuItem recentSketchMenuItem : base.getRecentSketchesMenuItems()) { recentSketchesMenu.add(recentSketchMenuItem); } } private void buildSketchMenu(JMenu sketchMenu) { sketchMenu.removeAll(); JMenuItem item = newJMenuItem(_("Verify / Compile"), 'R'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleRun(false, Editor.this.presentHandler, Editor.this.runHandler); } }); sketchMenu.add(item); item = newJMenuItem(_("Upload"), 'U'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleExport(false); } }); sketchMenu.add(item); item = newJMenuItemShift(_("Upload Using Programmer"), 'U'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleExport(true); } }); sketchMenu.add(item); item = newJMenuItemAlt(_("Export compiled Binary"), 'S'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleRun(false, new ShouldSaveReadOnly(), Editor.this.presentAndSaveHandler, Editor.this.runAndSaveHandler); } }); sketchMenu.add(item); // item = new JMenuItem("Stop"); // item.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent e) { // handleStop(); // sketchMenu.add(item); sketchMenu.addSeparator(); item = newJMenuItem(_("Show Sketch Folder"), 'K'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.openFolder(sketch.getFolder()); } }); sketchMenu.add(item); item.setEnabled(Base.openFolderAvailable()); if (importMenu == null) { importMenu = new JMenu(_("Include Library")); MenuScroller.setScrollerFor(importMenu); base.rebuildImportMenu(importMenu); } sketchMenu.add(importMenu); item = new JMenuItem(_("Add File...")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { sketch.handleAddFile(); } }); sketchMenu.add(item); } private JMenu buildToolsMenu() { toolsMenu = new JMenu(_("Tools")); toolsMenu.setMnemonic(KeyEvent.VK_T); addInternalTools(toolsMenu); JMenuItem item = newJMenuItemShift(_("Serial Monitor"), 'M'); item.addActionListener(e -> handleSerial()); toolsMenu.add(item); addTools(toolsMenu, BaseNoGui.getToolsFolder()); File sketchbookTools = new File(BaseNoGui.getSketchbookFolder(), "tools"); addTools(toolsMenu, sketchbookTools); toolsMenu.addSeparator(); numTools = toolsMenu.getItemCount(); // XXX: DAM: these should probably be implemented using the Tools plugin // API, if possible (i.e. if it supports custom actions, etc.) base.getBoardsCustomMenus().stream().forEach(toolsMenu::add); if (portMenu == null) portMenu = new JMenu(_("Port")); populatePortMenu(); toolsMenu.add(portMenu); toolsMenu.addSeparator(); base.rebuildProgrammerMenu(); programmersMenu = new JMenu(_("Programmer")); base.getProgrammerMenus().stream().forEach(programmersMenu::add); toolsMenu.add(programmersMenu); item = new JMenuItem(_("Burn Bootloader")); item.addActionListener(e -> handleBurnBootloader()); toolsMenu.add(item); toolsMenu.addMenuListener(new StubMenuListener() { public void menuSelected(MenuEvent e) { //System.out.println("Tools menu selected."); populatePortMenu(); for (Component c : toolsMenu.getMenuComponents()) { if ((c instanceof JMenu) && c.isVisible()) { JMenu menu = (JMenu)c; String name = menu.getText(); if (name == null) continue; String basename = name; int index = name.indexOf(':'); if (index > 0) basename = name.substring(0, index); String sel = null; int count = menu.getItemCount(); for (int i=0; i < count; i++) { JMenuItem item = menu.getItem(i); if (item != null && item.isSelected()) { sel = item.getText(); if (sel != null) break; } } if (sel == null) { if (!name.equals(basename)) menu.setText(basename); } else { if (sel.length() > 50) sel = sel.substring(0, 50) + "..."; String newname = basename + ": \"" + sel + "\""; if (!name.equals(newname)) menu.setText(newname); } } } } }); return toolsMenu; } private void addTools(JMenu menu, File sourceFolder) { if (sourceFolder == null) return; Map<String, JMenuItem> toolItems = new HashMap<String, JMenuItem>(); File[] folders = sourceFolder.listFiles(new FileFilter() { public boolean accept(File folder) { if (folder.isDirectory()) { //System.out.println("checking " + folder); File subfolder = new File(folder, "tool"); return subfolder.exists(); } return false; } }); if (folders == null || folders.length == 0) { return; } for (File folder : folders) { File toolDirectory = new File(folder, "tool"); try { // add dir to classpath for .classes //urlList.add(toolDirectory.toURL()); // add .jar files to classpath File[] archives = toolDirectory.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return (name.toLowerCase().endsWith(".jar") || name.toLowerCase().endsWith(".zip")); } }); URL[] urlList = new URL[archives.length]; for (int j = 0; j < urlList.length; j++) { urlList[j] = archives[j].toURI().toURL(); } URLClassLoader loader = new URLClassLoader(urlList); String className = null; for (File archive : archives) { className = findClassInZipFile(folder.getName(), archive); if (className != null) break; } // If no class name found, just move on. if (className == null) continue; Class<?> toolClass = Class.forName(className, true, loader); final Tool tool = (Tool) toolClass.newInstance(); tool.init(Editor.this); String title = tool.getMenuTitle(); JMenuItem item = new JMenuItem(title); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(tool); //new Thread(tool).start(); } }); //menu.add(item); toolItems.put(title, item); } catch (Exception e) { e.printStackTrace(); } } ArrayList<String> toolList = new ArrayList<String>(toolItems.keySet()); if (toolList.size() == 0) return; menu.addSeparator(); Collections.sort(toolList); for (String title : toolList) { menu.add(toolItems.get(title)); } } private String findClassInZipFile(String base, File file) { // Class file to search for String classFileName = "/" + base + ".class"; ZipFile zipFile = null; try { zipFile = new ZipFile(file); Enumeration<?> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (!entry.isDirectory()) { String name = entry.getName(); //System.out.println("entry: " + name); if (name.endsWith(classFileName)) { //int slash = name.lastIndexOf('/'); //String packageName = (slash == -1) ? "" : name.substring(0, slash); // Remove .class and convert slashes to periods. return name.substring(0, name.length() - 6).replace('/', '.'); } } } } catch (IOException e) { //System.err.println("Ignoring " + filename + " (" + e.getMessage() + ")"); e.printStackTrace(); } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { // noop } } } return null; } private SketchTextArea createTextArea() throws IOException { final SketchTextArea textArea = new SketchTextArea(base.getPdeKeywords()); textArea.setFocusTraversalKeysEnabled(false); textArea.requestFocusInWindow(); textArea.setMarkOccurrences(PreferencesData.getBoolean("editor.advanced")); textArea.setMarginLineEnabled(false); textArea.setCodeFoldingEnabled(PreferencesData.getBoolean("editor.code_folding")); textArea.setAntiAliasingEnabled(PreferencesData.getBoolean("editor.antialias")); textArea.setTabsEmulated(PreferencesData.getBoolean("editor.tabs.expand")); textArea.setTabSize(PreferencesData.getInteger("editor.tabs.size")); textArea.setEditorListener(new EditorListener(this)); textArea.addHyperlinkListener(new HyperlinkListener() { @Override public void hyperlinkUpdate(HyperlinkEvent hyperlinkEvent) { try { platform.openURL(sketch.getFolder(), hyperlinkEvent.getURL().toExternalForm()); } catch (Exception e) { Base.showWarning(e.getMessage(), e.getMessage(), e); } } }); textArea.addCaretListener(new CaretListener() { @Override public void caretUpdate(CaretEvent e) { int lineStart = textArea.getDocument().getDefaultRootElement().getElementIndex(e.getMark()); int lineEnd = textArea.getDocument().getDefaultRootElement().getElementIndex(e.getDot()); lineStatus.set(lineStart, lineEnd); } }); ToolTipManager.sharedInstance().registerComponent(textArea); configurePopupMenu(textArea); return textArea; } private JMenuItem createToolMenuItem(String className) { try { Class<?> toolClass = Class.forName(className); final Tool tool = (Tool) toolClass.newInstance(); JMenuItem item = new JMenuItem(tool.getMenuTitle()); tool.init(Editor.this); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(tool); } }); return item; } catch (Exception e) { e.printStackTrace(); return null; } } private void addInternalTools(JMenu menu) { JMenuItem item; item = createToolMenuItem("cc.arduino.packages.formatter.AStyle"); if (item == null) { throw new NullPointerException("Tool cc.arduino.packages.formatter.AStyle unavailable"); } item.setName("menuToolsAutoFormat"); int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); item.setAccelerator(KeyStroke.getKeyStroke('T', modifiers)); menu.add(item); //menu.add(createToolMenuItem("processing.app.tools.CreateFont")); //menu.add(createToolMenuItem("processing.app.tools.ColorSelector")); menu.add(createToolMenuItem("processing.app.tools.Archiver")); menu.add(createToolMenuItem("processing.app.tools.FixEncoding")); } class SerialMenuListener implements ActionListener { private final String serialPort; public SerialMenuListener(String serialPort) { this.serialPort = serialPort; } public void actionPerformed(ActionEvent e) { selectSerialPort(serialPort); base.onBoardOrPortChange(); } } private void selectSerialPort(String name) { if(portMenu == null) { System.out.println(_("serialMenu is null")); return; } if (name == null) { System.out.println(_("name is null")); return; } JCheckBoxMenuItem selection = null; for (int i = 0; i < portMenu.getItemCount(); i++) { JMenuItem menuItem = portMenu.getItem(i); if (!(menuItem instanceof JCheckBoxMenuItem)) { continue; } JCheckBoxMenuItem checkBoxMenuItem = ((JCheckBoxMenuItem) menuItem); checkBoxMenuItem.setState(false); if (name.equals(checkBoxMenuItem.getText())) selection = checkBoxMenuItem; } if (selection != null) selection.setState(true); //System.out.println(item.getLabel()); BaseNoGui.selectSerialPort(name); if (serialMonitor != null) { try { serialMonitor.close(); serialMonitor.setVisible(false); } catch (Exception e) { // ignore } } base.onBoardOrPortChange(); //System.out.println("set to " + get("serial.port")); } private void populatePortMenu() { portMenu.removeAll(); String selectedPort = PreferencesData.get("serial.port"); List<BoardPort> ports = Base.getDiscoveryManager().discovery(); ports = platform.filterPorts(ports, PreferencesData.getBoolean("serial.ports.showall")); Collections.sort(ports, new Comparator<BoardPort>() { @Override public int compare(BoardPort o1, BoardPort o2) { return BOARD_PROTOCOLS_ORDER.indexOf(o1.getProtocol()) - BOARD_PROTOCOLS_ORDER.indexOf(o2.getProtocol()); } }); String lastProtocol = null; String lastProtocolTranslated; for (BoardPort port : ports) { if (lastProtocol == null || !port.getProtocol().equals(lastProtocol)) { if (lastProtocol != null) { portMenu.addSeparator(); } lastProtocol = port.getProtocol(); if (BOARD_PROTOCOLS_ORDER.indexOf(port.getProtocol()) != -1) { lastProtocolTranslated = BOARD_PROTOCOLS_ORDER_TRANSLATIONS.get(BOARD_PROTOCOLS_ORDER.indexOf(port.getProtocol())); } else { lastProtocolTranslated = port.getProtocol(); } JMenuItem lastProtocolMenuItem = new JMenuItem(_(lastProtocolTranslated)); lastProtocolMenuItem.setEnabled(false); portMenu.add(lastProtocolMenuItem); } String address = port.getAddress(); String label = port.getLabel(); JCheckBoxMenuItem item = new JCheckBoxMenuItem(label, address.equals(selectedPort)); item.addActionListener(new SerialMenuListener(address)); portMenu.add(item); } portMenu.setEnabled(portMenu.getMenuComponentCount() > 0); } private JMenu buildHelpMenu() { // To deal with a Mac OS X 10.5 bug, add an extra space after the name // so that the OS doesn't try to insert its slow help menu. JMenu menu = new JMenu(_("Help")); menu.setMnemonic(KeyEvent.VK_H); JMenuItem item; item = new JMenuItem(_("Getting Started")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showArduinoGettingStarted(); } }); menu.add(item); item = new JMenuItem(_("Environment")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showEnvironment(); } }); menu.add(item); item = new JMenuItem(_("Troubleshooting")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showTroubleshooting(); } }); menu.add(item); item = new JMenuItem(_("Reference")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showReference(); } }); menu.add(item); menu.addSeparator(); item = new JMenuItem(_("Galileo Help")); item.setEnabled(false); menu.add(item); item = new JMenuItem(_("Getting Started")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showReference("reference/Galileo_help_files", "ArduinoIDE_guide_galileo"); } }); menu.add(item); item = new JMenuItem(_("Troubleshooting")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showReference("reference/Galileo_help_files", "Guide_Troubleshooting_Galileo"); } }); menu.add(item); menu.addSeparator(); item = new JMenuItem(_("Edison Help")); item.setEnabled(false); menu.add(item); item = new JMenuItem(_("Getting Started")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showReference("reference/Edison_help_files", "ArduinoIDE_guide_edison"); } }); menu.add(item); item = new JMenuItem(_("Troubleshooting")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showReference("reference/Edison_help_files", "Guide_Troubleshooting_Edison"); } }); menu.add(item); menu.addSeparator(); item = newJMenuItemShift(_("Find in Reference"), 'F'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // if (textarea.isSelectionActive()) { // handleFindReference(); handleFindReference(); } }); menu.add(item); item = new JMenuItem(_("Frequently Asked Questions")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showFAQ(); } }); menu.add(item); item = new JMenuItem(_("Visit Arduino.cc")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.openURL(_("http: } }); menu.add(item); // macosx already has its own about menu if (!OSUtils.isMacOS()) { menu.addSeparator(); item = new JMenuItem(_("About Arduino")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handleAbout(); } }); menu.add(item); } return menu; } private JMenu buildEditMenu() { JMenu menu = new JMenu(_("Edit")); menu.setName("menuEdit"); menu.setMnemonic(KeyEvent.VK_E); undoItem = newJMenuItem(_("Undo"), 'Z'); undoItem.setName("menuEditUndo"); undoItem.addActionListener(undoAction = new UndoAction()); menu.add(undoItem); if (!OSUtils.isMacOS()) { redoItem = newJMenuItem(_("Redo"), 'Y'); } else { redoItem = newJMenuItemShift(_("Redo"), 'Z'); } redoItem.setName("menuEditRedo"); redoItem.addActionListener(redoAction = new RedoAction()); menu.add(redoItem); menu.addSeparator(); // TODO "cut" and "copy" should really only be enabled // if some text is currently selected JMenuItem cutItem = newJMenuItem(_("Cut"), 'X'); cutItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleCut(); } }); menu.add(cutItem); JMenuItem copyItem = newJMenuItem(_("Copy"), 'C'); copyItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.copy(); } }); menu.add(copyItem); JMenuItem copyForumItem = newJMenuItemShift(_("Copy for Forum"), 'C'); copyForumItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // SwingUtilities.invokeLater(new Runnable() { // public void run() { new DiscourseFormat(Editor.this, false).show(); } }); menu.add(copyForumItem); JMenuItem copyHTMLItem = newJMenuItemAlt(_("Copy as HTML"), 'C'); copyHTMLItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // SwingUtilities.invokeLater(new Runnable() { // public void run() { new DiscourseFormat(Editor.this, true).show(); } }); menu.add(copyHTMLItem); JMenuItem pasteItem = newJMenuItem(_("Paste"), 'V'); pasteItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.paste(); sketch.setModified(true); } }); menu.add(pasteItem); JMenuItem selectAllItem = newJMenuItem(_("Select All"), 'A'); selectAllItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.selectAll(); } }); menu.add(selectAllItem); menu.addSeparator(); JMenuItem commentItem = newJMenuItem(_("Comment/Uncomment"), '/'); commentItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleCommentUncomment(); } }); menu.add(commentItem); JMenuItem increaseIndentItem = new JMenuItem(_("Increase Indent")); increaseIndentItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0)); increaseIndentItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleIndentOutdent(true); } }); menu.add(increaseIndentItem); JMenuItem decreseIndentItem = new JMenuItem(_("Decrease Indent")); decreseIndentItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_MASK)); decreseIndentItem.setName("menuDecreaseIndent"); decreseIndentItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleIndentOutdent(false); } }); menu.add(decreseIndentItem); menu.addSeparator(); JMenuItem findItem = newJMenuItem(_("Find..."), 'F'); findItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (find == null) { find = new FindReplace(Editor.this, Base.FIND_DIALOG_STATE); } if (!OSUtils.isMacOS()) { find.setFindText(getSelectedText()); } find.setLocationRelativeTo(Editor.this); find.setVisible(true); } }); menu.add(findItem); JMenuItem findNextItem = newJMenuItem(_("Find Next"), 'G'); findNextItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (find != null) { find.findNext(); } } }); menu.add(findNextItem); JMenuItem findPreviousItem = newJMenuItemShift(_("Find Previous"), 'G'); findPreviousItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (find != null) { find.findPrevious(); } } }); menu.add(findPreviousItem); if (OSUtils.isMacOS()) { JMenuItem useSelectionForFindItem = newJMenuItem(_("Use Selection For Find"), 'E'); useSelectionForFindItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (find == null) { find = new FindReplace(Editor.this, Base.FIND_DIALOG_STATE); } find.setFindText(getSelectedText()); } }); menu.add(useSelectionForFindItem); } return menu; } /** * A software engineer, somewhere, needs to have his abstraction * taken away. In some countries they jail or beat people for writing * the sort of API that would require a five line helper function * just to set the command key for a menu item. */ static public JMenuItem newJMenuItem(String title, int what) { JMenuItem menuItem = new JMenuItem(title); menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_KEY_MASK)); return menuItem; } /** * Like newJMenuItem() but adds shift as a modifier for the key command. */ static public JMenuItem newJMenuItemShift(String title, int what) { JMenuItem menuItem = new JMenuItem(title); menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_KEY_MASK | ActionEvent.SHIFT_MASK)); return menuItem; } /** * Same as newJMenuItem(), but adds the ALT (on Linux and Windows) * or OPTION (on Mac OS X) key as a modifier. */ private static JMenuItem newJMenuItemAlt(String title, int what) { JMenuItem menuItem = new JMenuItem(title); menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_ALT_KEY_MASK)); return menuItem; } class UndoAction extends AbstractAction { public UndoAction() { super("Undo"); this.setEnabled(false); } public void actionPerformed(ActionEvent e) { try { textarea.undoLastAction(); sketch.setModified(true); } catch (CannotUndoException ex) { //System.out.println("Unable to undo: " + ex); //ex.printStackTrace(); } } protected void updateUndoState() { UndoManager undo = textarea.getUndoManager(); if (undo.canUndo()) { this.setEnabled(true); undoItem.setEnabled(true); undoItem.setText(undo.getUndoPresentationName()); putValue(Action.NAME, undo.getUndoPresentationName()); } else { this.setEnabled(false); undoItem.setEnabled(false); undoItem.setText(_("Undo")); putValue(Action.NAME, "Undo"); } } } class RedoAction extends AbstractAction { public RedoAction() { super("Redo"); this.setEnabled(false); } public void actionPerformed(ActionEvent e) { try { textarea.redoLastAction(); sketch.setModified(true); } catch (CannotRedoException ex) { //System.out.println("Unable to redo: " + ex); //ex.printStackTrace(); } } protected void updateRedoState() { UndoManager undo = textarea.getUndoManager(); if (undo.canRedo()) { redoItem.setEnabled(true); redoItem.setText(undo.getRedoPresentationName()); putValue(Action.NAME, undo.getRedoPresentationName()); } else { this.setEnabled(false); redoItem.setEnabled(false); redoItem.setText(_("Redo")); putValue(Action.NAME, "Redo"); } } } // these will be done in a more generic way soon, more like: // setHandler("action name", Runnable); // but for the time being, working out the kinks of how many things to // abstract from the editor in this fashion. private void resetHandlers() { runHandler = new BuildHandler(); presentHandler = new BuildHandler(true); runAndSaveHandler = new BuildHandler(false, true); presentAndSaveHandler = new BuildHandler(true, true); stopHandler = new DefaultStopHandler(); exportHandler = new DefaultExportHandler(); exportAppHandler = new DefaultExportAppHandler(); } /** * Gets the current sketch object. */ public Sketch getSketch() { return sketch; } /** * Get the TextArea object for use (not recommended). This should only * be used in obscure cases that really need to hack the internals of the * JEditTextArea. Most tools should only interface via the get/set functions * found in this class. This will maintain compatibility with future releases, * which will not use TextArea. */ public SketchTextArea getTextArea() { return textarea; } /** * Get the contents of the current buffer. Used by the Sketch class. */ public String getText() { return textarea.getText(); } /** * Replace the entire contents of the front-most tab. */ public void setText(String what) { textarea.setText(what); } /** * Called to update the text but not switch to a different set of code * (which would affect the undo manager). */ // public void setText2(String what, int start, int stop) { // beginCompoundEdit(); // textarea.setText(what); // endCompoundEdit(); // // make sure that a tool isn't asking for a bad location // start = Math.max(0, Math.min(start, textarea.getDocumentLength())); // stop = Math.max(0, Math.min(start, textarea.getDocumentLength())); // textarea.select(start, stop); // textarea.requestFocus(); // get the caret blinking public String getSelectedText() { return textarea.getSelectedText(); } public void setSelectedText(String what) { textarea.replaceSelection(what); } public void setSelection(int start, int stop) { textarea.select(start, stop); } /** * Get the beginning point of the current selection. */ public int getSelectionStart() { return textarea.getSelectionStart(); } /** * Get the end point of the current selection. */ public int getSelectionStop() { return textarea.getSelectionEnd(); } /** * Get text for a specified line. */ private String getLineText(int line) { try { return textarea.getText(textarea.getLineStartOffset(line), textarea.getLineEndOffset(line)); } catch (BadLocationException e) { return ""; } } public int getScrollPosition() { return scrollPane.getVerticalScrollBar().getValue(); } /** * Switch between tabs, this swaps out the Document object * that's currently being manipulated. */ protected void setCode(final SketchCodeDocument codeDoc) { RSyntaxDocument document = (RSyntaxDocument) codeDoc.getDocument(); if (document == null) { // this document not yet inited document = new RSyntaxDocument(new ArduinoTokenMakerFactory(base.getPdeKeywords()), RSyntaxDocument.SYNTAX_STYLE_CPLUSPLUS); document.putProperty(PlainDocument.tabSizeAttribute, PreferencesData.getInteger("editor.tabs.size")); // insert the program text into the document object try { document.insertString(0, codeDoc.getCode().getProgram(), null); } catch (BadLocationException bl) { bl.printStackTrace(); } // set up this guy's own undo manager // code.undo = new UndoManager(); codeDoc.setDocument(document); } if(codeDoc.getUndo() == null){ codeDoc.setUndo(new LastUndoableEditAwareUndoManager(textarea, this)); document.addUndoableEditListener(codeDoc.getUndo()); } // Update the document object that's in use textarea.switchDocument(document, codeDoc.getUndo()); // HACK multiple tabs: for update Listeners of Gutter, forcin call: Gutter.setTextArea(RTextArea) scrollPane.setViewportView(textarea); textarea.select(codeDoc.getSelectionStart(), codeDoc.getSelectionStop()); textarea.requestFocus(); // get the caret blinking final int position = codeDoc.getScrollPosition(); // invokeLater: Expect the document to be rendered correctly to set the new position SwingUtilities.invokeLater(new Runnable() { @Override public void run() { scrollPane.getVerticalScrollBar().setValue(position); undoAction.updateUndoState(); redoAction.updateRedoState(); } }); } /** * Implements Edit &rarr; Cut. */ private void handleCut() { textarea.cut(); } private void handleDiscourseCopy() { new DiscourseFormat(Editor.this, false).show(); } private void handleHTMLCopy() { new DiscourseFormat(Editor.this, true).show(); } void handleCommentUncomment() { Action action = textarea.getActionMap().get(RSyntaxTextAreaEditorKit.rstaToggleCommentAction); action.actionPerformed(null); } private void handleIndentOutdent(boolean indent) { if (indent) { int caretPosition = textarea.getCaretPosition(); boolean noSelec = !textarea.isSelectionActive(); // if no selection, focus on first char. if (noSelec) { try { int line = textarea.getCaretLineNumber(); int startOffset = textarea.getLineStartOffset(line); textarea.setCaretPosition(startOffset); } catch (BadLocationException e) { } } // Insert Tab or Spaces.. Action action = textarea.getActionMap().get(RSyntaxTextAreaEditorKit.insertTabAction); action.actionPerformed(null); if (noSelec) { textarea.setCaretPosition(caretPosition); } } else { Action action = textarea.getActionMap().get(RSyntaxTextAreaEditorKit.rstaDecreaseIndentAction); action.actionPerformed(null); } } private String getCurrentKeyword() { String text = ""; if (textarea.getSelectedText() != null) text = textarea.getSelectedText().trim(); try { int current = textarea.getCaretPosition(); int startOffset = 0; int endIndex = current; String tmp = textarea.getDocument().getText(current, 1); // TODO probably a regexp that matches Arduino lang special chars // already exists. String regexp = "[\\s\\n();\\\\.!='\\[\\]{}]"; while (!tmp.matches(regexp)) { endIndex++; tmp = textarea.getDocument().getText(endIndex, 1); } // For some reason document index start at 2. // if( current - start < 2 ) return; tmp = ""; while (!tmp.matches(regexp)) { startOffset++; if (current - startOffset < 0) { tmp = textarea.getDocument().getText(0, 1); break; } else tmp = textarea.getDocument().getText(current - startOffset, 1); } startOffset int length = endIndex - current + startOffset; text = textarea.getDocument().getText(current - startOffset, length); } catch (BadLocationException bl) { bl.printStackTrace(); } return text; } private void handleFindReference() { String text = getCurrentKeyword(); String referenceFile = base.getPdeKeywords().getReference(text); if (referenceFile == null) { statusNotice(I18n.format(_("No reference available for \"{0}\""), text)); } else { Base.showReference("Reference/" + referenceFile); } } /** * Implements Sketch &rarr; Run. * @param verbose Set true to run with verbose output. * @param verboseHandler * @param nonVerboseHandler */ public void handleRun(final boolean verbose, Runnable verboseHandler, Runnable nonVerboseHandler) { handleRun(verbose, new ShouldSaveIfModified(), verboseHandler, nonVerboseHandler); } private void handleRun(final boolean verbose, Predicate<Sketch> shouldSavePredicate, Runnable verboseHandler, Runnable nonVerboseHandler) { internalCloseRunner(); if (shouldSavePredicate.apply(sketch)) { handleSave(true); } toolbar.activate(EditorToolbar.RUN); status.progress(_("Compiling sketch...")); // do this to advance/clear the terminal window / dos prompt / etc for (int i = 0; i < 10; i++) System.out.println(); // clear the console on each run, unless the user doesn't want to if (PreferencesData.getBoolean("console.auto_clear")) { console.clear(); } // Cannot use invokeLater() here, otherwise it gets // placed on the event thread and causes a hang--bad idea all around. new Thread(verbose ? verboseHandler : nonVerboseHandler).start(); } class BuildHandler implements Runnable { private final boolean verbose; private final boolean saveHex; public BuildHandler() { this(false); } public BuildHandler(boolean verbose) { this(verbose, false); } public BuildHandler(boolean verbose, boolean saveHex) { this.verbose = verbose; this.saveHex = saveHex; } @Override public void run() { try { textarea.removeAllLineHighlights(); sketch.prepare(); sketch.build(verbose, saveHex); statusNotice(_("Done compiling.")); } catch (PreferencesMapException e) { statusError(I18n.format( _("Error while compiling: missing '{0}' configuration parameter"), e.getMessage())); } catch (Exception e) { status.unprogress(); statusError(e); } status.unprogress(); toolbar.deactivate(EditorToolbar.RUN); } } private class DefaultStopHandler implements Runnable { public void run() { // TODO // DAM: we should try to kill the compilation or upload process here. } } /** * Implements Sketch &rarr; Stop, or pressing Stop on the toolbar. */ private void handleStop() { // called by menu or buttons // toolbar.activate(EditorToolbar.STOP); internalCloseRunner(); toolbar.deactivate(EditorToolbar.RUN); // toolbar.deactivate(EditorToolbar.STOP); // focus the PDE again after quitting presentation mode [toxi 030903] toFront(); } /** * Handle internal shutdown of the runner. */ public void internalCloseRunner() { if (stopHandler != null) try { stopHandler.run(); } catch (Exception e) { } } /** * Check if the sketch is modified and ask user to save changes. * @return false if canceling the close/quit operation */ protected boolean checkModified() { if (!sketch.isModified()) return true; // As of Processing 1.0.10, this always happens immediately. toFront(); String prompt = I18n.format(_("Save changes to \"{0}\"? "), sketch.getName()); if (!OSUtils.isMacOS()) { int result = JOptionPane.showConfirmDialog(this, prompt, _("Close"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); switch (result) { case JOptionPane.YES_OPTION: return handleSave(true); case JOptionPane.NO_OPTION: return true; // ok to continue case JOptionPane.CANCEL_OPTION: case JOptionPane.CLOSED_OPTION: // Escape key pressed return false; default: throw new IllegalStateException(); } } else { // This code is disabled unless Java 1.5 is being used on Mac OS X // because of a Java bug that prevents the initial value of the // dialog from being set properly (at least on my MacBook Pro). // The bug causes the "Don't Save" option to be the highlighted, // blinking, default. This sucks. But I'll tell you what doesn't // suck--workarounds for the Mac and Apple's snobby attitude about it! // I think it's nifty that they treat their developers like dirt. // Pane formatting adapted from the quaqua guide JOptionPane pane = new JOptionPane(_("<html> " + "<head> <style type=\"text/css\">"+ "b { font: 13pt \"Lucida Grande\" }"+ "p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+ "</style> </head>" + "<b>Do you want to save changes to this sketch<BR>" + " before closing?</b>" + "<p>If you don't save, your changes will be lost."), JOptionPane.QUESTION_MESSAGE); String[] options = new String[] { _("Save"), _("Cancel"), _("Don't Save") }; pane.setOptions(options); // highlight the safest option ala apple hig pane.setInitialValue(options[0]); // on macosx, setting the destructive property places this option // away from the others at the lefthand side pane.putClientProperty("Quaqua.OptionPane.destructiveOption", 2); JDialog dialog = pane.createDialog(this, null); dialog.setVisible(true); Object result = pane.getValue(); if (result == options[0]) { // save (and close/quit) return handleSave(true); } else { return result == options[2]; } } } /** * Open a sketch from a particular path, but don't check to save changes. * Used by Sketch.saveAs() to re-open a sketch after the "Save As" */ protected void handleOpenUnchecked(File file, int codeIndex, int selStart, int selStop, int scrollPos) { internalCloseRunner(); handleOpenInternal(file); // Replacing a document that may be untitled. If this is an actual // untitled document, then editor.untitled will be set by Base. untitled = false; sketch.setCurrentCode(codeIndex); textarea.select(selStart, selStop); scrollPane.getVerticalScrollBar().setValue(scrollPos); } /** * Second stage of open, occurs after having checked to see if the * modifications (if any) to the previous sketch need to be saved. */ protected boolean handleOpenInternal(File sketchFile) { // check to make sure that this .pde file is // in a folder of the same name String fileName = sketchFile.getName(); File file = SketchData.checkSketchFile(sketchFile); if (file == null) { if (!fileName.endsWith(".ino") && !fileName.endsWith(".pde")) { Base.showWarning(_("Bad file selected"), _("Arduino can only open its own sketches\n" + "and other files ending in .ino or .pde"), null); return false; } else { String properParent = fileName.substring(0, fileName.length() - 4); Object[] options = { _("OK"), _("Cancel") }; String prompt = I18n.format(_("The file \"{0}\" needs to be inside\n" + "a sketch folder named \"{1}\".\n" + "Create this folder, move the file, and continue?"), fileName, properParent); int result = JOptionPane.showOptionDialog(this, prompt, _("Moving"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (result == JOptionPane.YES_OPTION) { // create properly named folder File properFolder = new File(sketchFile.getParent(), properParent); if (properFolder.exists()) { Base.showWarning(_("Error"), I18n.format( _("A folder named \"{0}\" already exists. " + "Can't open sketch."), properParent ), null); return false; } if (!properFolder.mkdirs()) { //throw new IOException("Couldn't create sketch folder"); Base.showWarning(_("Error"), _("Could not create the sketch folder."), null); return false; } // copy the sketch inside File properPdeFile = new File(properFolder, sketchFile.getName()); try { Base.copyFile(sketchFile, properPdeFile); } catch (IOException e) { Base.showWarning(_("Error"), _("Could not copy to a proper location."), e); return false; } // remove the original file, so user doesn't get confused sketchFile.delete(); // update with the new path file = properPdeFile; } else if (result == JOptionPane.NO_OPTION) { return false; } } } try { sketch = new Sketch(this, file); } catch (IOException e) { Base.showWarning(_("Error"), _("Could not create the sketch."), e); return false; } header.rebuild(); setTitle(I18n.format(_("{0} | Arduino {1}"), sketch.getName(), BaseNoGui.VERSION_NAME_LONG)); // Disable untitled setting from previous document, if any untitled = false; // opening was successful return true; // } catch (Exception e) { // e.printStackTrace(); // statusError(e); // return false; } public boolean handleSave(boolean immediately) { //stopRunner(); handleStop(); // 0136 textarea.removeAllLineHighlights(); if (untitled) { return handleSaveAs(); // need to get the name, user might also cancel here } else if (immediately) { return handleSave2(); } else { SwingUtilities.invokeLater(new Runnable() { public void run() { handleSave2(); } }); } return true; } private boolean handleSave2() { toolbar.activate(EditorToolbar.SAVE); statusNotice(_("Saving...")); boolean saved = false; try { boolean wasReadOnly = sketch.isReadOnly(); String previousMainFilePath = sketch.getMainFilePath(); saved = sketch.save(); if (saved) { statusNotice(_("Done Saving.")); if (wasReadOnly) { base.removeRecentSketchPath(previousMainFilePath); } base.storeRecentSketches(sketch); base.rebuildRecentSketchesMenuItems(); } else { statusEmpty(); } // rebuild sketch menu in case a save-as was forced // Disabling this for 0125, instead rebuild the menu inside // the Save As method of the Sketch object, since that's the // only one who knows whether something was renamed. //sketchbook.rebuildMenus(); //sketchbook.rebuildMenusAsync(); } catch (Exception e) { // show the error as a message in the window statusError(e); // zero out the current action, // so that checkModified2 will just do nothing //checkModifiedMode = 0; // this is used when another operation calls a save } //toolbar.clear(); toolbar.deactivate(EditorToolbar.SAVE); return saved; } public boolean handleSaveAs() { //stopRunner(); // formerly from 0135 handleStop(); toolbar.activate(EditorToolbar.SAVE); //SwingUtilities.invokeLater(new Runnable() { //public void run() { statusNotice(_("Saving...")); try { if (sketch.saveAs()) { base.storeRecentSketches(sketch); base.rebuildRecentSketchesMenuItems(); statusNotice(_("Done Saving.")); // Disabling this for 0125, instead rebuild the menu inside // the Save As method of the Sketch object, since that's the // only one who knows whether something was renamed. //sketchbook.rebuildMenusAsync(); } else { statusNotice(_("Save Canceled.")); return false; } } catch (Exception e) { // show the error as a message in the window statusError(e); } finally { // make sure the toolbar button deactivates toolbar.deactivate(EditorToolbar.SAVE); } return true; } private boolean serialPrompt() { int count = portMenu.getItemCount(); Object[] names = new Object[count]; for (int i = 0; i < count; i++) { names[i] = portMenu.getItem(i).getText(); } String result = (String) JOptionPane.showInputDialog(this, I18n.format( _("Serial port {0} not found.\n" + "Retry the upload with another serial port?"), PreferencesData.get("serial.port") ), "Serial port not found", JOptionPane.PLAIN_MESSAGE, null, names, 0); if (result == null) return false; selectSerialPort(result); base.onBoardOrPortChange(); return true; } /** * Called by Sketch &rarr; Export. * Handles calling the export() function on sketch, and * queues all the gui status stuff that comes along with it. * <p/> * Made synchronized to (hopefully) avoid problems of people * hitting export twice, quickly, and horking things up. */ /** * Handles calling the export() function on sketch, and * queues all the gui status stuff that comes along with it. * * Made synchronized to (hopefully) avoid problems of people * hitting export twice, quickly, and horking things up. */ synchronized public void handleExport(final boolean usingProgrammer) { if (PreferencesData.getBoolean("editor.save_on_verify")) { if (sketch.isModified() && !sketch.isReadOnly()) { handleSave(true); } } toolbar.activate(EditorToolbar.EXPORT); console.clear(); status.progress(_("Uploading to I/O Board...")); new Thread(usingProgrammer ? exportAppHandler : exportHandler).start(); } // DAM: in Arduino, this is upload class DefaultExportHandler implements Runnable { public void run() { try { textarea.removeAllLineHighlights(); if (serialMonitor != null) { serialMonitor.suspend(); } uploading = true; boolean success = sketch.exportApplet(false); if (success) { statusNotice(_("Done uploading.")); } } catch (SerialNotFoundException e) { if (portMenu.getItemCount() == 0) statusError(e); else if (serialPrompt()) run(); else statusNotice(_("Upload canceled.")); } catch (PreferencesMapException e) { statusError(I18n.format( _("Error while uploading: missing '{0}' configuration parameter"), e.getMessage())); } catch (RunnerException e) { //statusError("Error during upload."); //e.printStackTrace(); status.unprogress(); statusError(e); } catch (Exception e) { e.printStackTrace(); } finally { populatePortMenu(); } status.unprogress(); uploading = false; //toolbar.clear(); toolbar.deactivate(EditorToolbar.EXPORT); resumeOrCloseSerialMonitor(); base.onBoardOrPortChange(); } } private void resumeOrCloseSerialMonitor() { // Return the serial monitor window to its initial state if (serialMonitor != null) { BoardPort boardPort = BaseNoGui.getDiscoveryManager().find(PreferencesData.get("serial.port")); long sleptFor = 0; while (boardPort == null && sleptFor < MAX_TIME_AWAITING_FOR_RESUMING_SERIAL_MONITOR) { try { Thread.sleep(100); sleptFor += 100; boardPort = BaseNoGui.getDiscoveryManager().find(PreferencesData.get("serial.port")); } catch (InterruptedException e) { // noop } } try { if (boardPort == null) { serialMonitor.close(); handleSerial(); } else { serialMonitor.resume(boardPort); } } catch (Exception e) { statusError(e); } } } // DAM: in Arduino, this is upload (with verbose output) class DefaultExportAppHandler implements Runnable { public void run() { try { if (serialMonitor != null) { serialMonitor.suspend(); } uploading = true; boolean success = sketch.exportApplet(true); if (success) { statusNotice(_("Done uploading.")); } } catch (SerialNotFoundException e) { if (portMenu.getItemCount() == 0) statusError(e); else if (serialPrompt()) run(); else statusNotice(_("Upload canceled.")); } catch (PreferencesMapException e) { statusError(I18n.format( _("Error while uploading: missing '{0}' configuration parameter"), e.getMessage())); } catch (RunnerException e) { //statusError("Error during upload."); //e.printStackTrace(); status.unprogress(); statusError(e); } catch (Exception e) { e.printStackTrace(); } finally { populatePortMenu(); } status.unprogress(); uploading = false; //toolbar.clear(); toolbar.deactivate(EditorToolbar.EXPORT); resumeOrCloseSerialMonitor(); base.onBoardOrPortChange(); } } public void handleSerial() { if (serialMonitor != null) { // The serial monitor already exists if (serialMonitor.isClosed()) { serialMonitor.dispose(); // If it's closed, clear the refrence to the existing // monitor and create a new one serialMonitor = null; } else { // If it's not closed, give it the focus try { serialMonitor.toFront(); serialMonitor.requestFocus(); return; } catch (Exception e) { // noop } } } BoardPort port = Base.getDiscoveryManager().find(PreferencesData.get("serial.port")); if (port == null) { statusError(I18n.format("Board at {0} is not available", PreferencesData.get("serial.port"))); return; } serialMonitor = new MonitorFactory().newMonitor(port); serialMonitor.setIconImage(getIconImage()); // If currently uploading, disable the monitor (it will be later // enabled when done uploading) if (uploading) { try { serialMonitor.suspend(); } catch (Exception e) { statusError(e); } } boolean success = false; do { if (serialMonitor.requiresAuthorization() && !PreferencesData.has(serialMonitor.getAuthorizationKey())) { PasswordAuthorizationDialog dialog = new PasswordAuthorizationDialog(this, _("Type board password to access its console")); dialog.setLocationRelativeTo(this); dialog.setVisible(true); if (dialog.isCancelled()) { statusNotice(_("Unable to open serial monitor")); return; } PreferencesData.set(serialMonitor.getAuthorizationKey(), dialog.getPassword()); } try { serialMonitor.open(); serialMonitor.setVisible(true); success = true; } catch (ConnectException e) { statusError(_("Unable to connect: is the sketch using the bridge?")); } catch (JSchException e) { statusError(_("Unable to connect: wrong password?")); } catch (SerialException e) { String errorMessage = e.getMessage(); if (e.getCause() != null && e.getCause() instanceof SerialPortException) { errorMessage += " (" + ((SerialPortException) e.getCause()).getExceptionType() + ")"; } statusError(errorMessage); try { serialMonitor.close(); } catch (Exception e1) { // noop } } catch (Exception e) { statusError(e); } finally { if (serialMonitor.requiresAuthorization() && !success) { PreferencesData.remove(serialMonitor.getAuthorizationKey()); } } } while (serialMonitor.requiresAuthorization() && !success); } private void handleBurnBootloader() { console.clear(); statusNotice(_("Burning bootloader to I/O Board (this may take a minute)...")); SwingUtilities.invokeLater(new Runnable() { public void run() { try { Uploader uploader = new SerialUploader(); if (uploader.burnBootloader()) { statusNotice(_("Done burning bootloader.")); } else { statusError(_("Error while burning bootloader.")); // error message will already be visible } } catch (PreferencesMapException e) { statusError(I18n.format( _("Error while burning bootloader: missing '{0}' configuration parameter"), e.getMessage())); } catch (RunnerException e) { statusError(e.getMessage()); } catch (Exception e) { statusError(_("Error while burning bootloader.")); e.printStackTrace(); } } }); } /** * Handler for File &rarr; Page Setup. */ private void handlePageSetup() { PrinterJob printerJob = PrinterJob.getPrinterJob(); if (pageFormat == null) { pageFormat = printerJob.defaultPage(); } pageFormat = printerJob.pageDialog(pageFormat); } /** * Handler for File &rarr; Print. */ private void handlePrint() { statusNotice(_("Printing...")); //printerJob = null; PrinterJob printerJob = PrinterJob.getPrinterJob(); if (pageFormat != null) { //System.out.println("setting page format " + pageFormat); printerJob.setPrintable(textarea, pageFormat); } else { printerJob.setPrintable(textarea); } // set the name of the job to the code name printerJob.setJobName(sketch.getCurrentCode().getPrettyName()); if (printerJob.printDialog()) { try { printerJob.print(); statusNotice(_("Done printing.")); } catch (PrinterException pe) { statusError(_("Error while printing.")); pe.printStackTrace(); } } else { statusNotice(_("Printing canceled.")); } //printerJob = null; // clear this out? } /** * Show an error int the status bar. */ public void statusError(String what) { System.err.println(what); status.error(what); //new Exception("deactivating RUN").printStackTrace(); toolbar.deactivate(EditorToolbar.RUN); } /** * Show an exception in the editor status bar. */ public void statusError(Exception e) { e.printStackTrace(); // if (e == null) { // System.err.println("Editor.statusError() was passed a null exception."); // return; if (e instanceof RunnerException) { RunnerException re = (RunnerException) e; if (re.hasCodeIndex()) { sketch.setCurrentCode(re.getCodeIndex()); } if (re.hasCodeLine()) { int line = re.getCodeLine(); // subtract one from the end so that the \n ain't included if (line >= textarea.getLineCount()) { // The error is at the end of this current chunk of code, // so the last line needs to be selected. line = textarea.getLineCount() - 1; if (getLineText(line).length() == 0) { // The last line may be zero length, meaning nothing to select. // If so, back up one more line. line } } if (line < 0 || line >= textarea.getLineCount()) { System.err.println(I18n.format(_("Bad error line: {0}"), line)); } else { try { textarea.addLineHighlight(line, new Color(1, 0, 0, 0.2f)); textarea.setCaretPosition(textarea.getLineStartOffset(line)); } catch (BadLocationException e1) { e1.printStackTrace(); } } } } // Since this will catch all Exception types, spend some time figuring // out which kind and try to give a better error message to the user. String mess = e.getMessage(); if (mess != null) { String javaLang = "java.lang."; if (mess.indexOf(javaLang) == 0) { mess = mess.substring(javaLang.length()); } String rxString = "RuntimeException: "; if (mess.indexOf(rxString) == 0) { mess = mess.substring(rxString.length()); } statusError(mess); } // e.printStackTrace(); } /** * Show a notice message in the editor status bar. */ public void statusNotice(String msg) { status.notice(msg); } /** * Clear the status area. */ private void statusEmpty() { statusNotice(EMPTY); } protected void onBoardOrPortChange() { Map<String, String> boardPreferences = BaseNoGui.getBoardPreferences(); if (boardPreferences != null) lineStatus.setBoardName(boardPreferences.get("name")); else lineStatus.setBoardName("-"); lineStatus.setSerialPort(PreferencesData.get("serial.port")); lineStatus.repaint(); } private void configurePopupMenu(final SketchTextArea textarea){ JPopupMenu menu = textarea.getPopupMenu(); menu.addSeparator(); JMenuItem item = createToolMenuItem("cc.arduino.packages.formatter.AStyle"); if (item == null) { throw new NullPointerException("Tool cc.arduino.packages.formatter.AStyle unavailable"); } item.setName("menuToolsAutoFormat"); menu.add(item); item = newJMenuItem(_("Comment/Uncomment"), '/'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleCommentUncomment(); } }); menu.add(item); item = newJMenuItem(_("Increase Indent"), ']'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleIndentOutdent(true); } }); menu.add(item); item = newJMenuItem(_("Decrease Indent"), '['); item.setName("menuDecreaseIndent"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleIndentOutdent(false); } }); menu.add(item); item = new JMenuItem(_("Copy for Forum")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleDiscourseCopy(); } }); menu.add(item); item = new JMenuItem(_("Copy as HTML")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleHTMLCopy(); } }); menu.add(item); final JMenuItem referenceItem = new JMenuItem(_("Find in Reference")); referenceItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleFindReference(); } }); menu.add(referenceItem); final JMenuItem openURLItem = new JMenuItem(_("Open URL")); openURLItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.openURL(e.getActionCommand()); } }); menu.add(openURLItem); menu.addPopupMenuListener(new PopupMenuListener() { @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) { String referenceFile = base.getPdeKeywords().getReference(getCurrentKeyword()); referenceItem.setEnabled(referenceFile != null); int offset = textarea.getCaretPosition(); org.fife.ui.rsyntaxtextarea.Token token = RSyntaxUtilities.getTokenAtOffset(textarea, offset); if (token != null && token.isHyperlink()) { openURLItem.setEnabled(true); openURLItem.setActionCommand(token.getLexeme()); } else { openURLItem.setEnabled(false); } } @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { } @Override public void popupMenuCanceled(PopupMenuEvent e) { } }); } }
package shadow.build.closure; import clojure.lang.*; import com.google.javascript.jscomp.*; import com.google.javascript.jscomp.Compiler; import com.google.javascript.jscomp.parsing.parser.FeatureSet; import com.google.javascript.rhino.Node; import java.io.IOException; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.List; public class JsInspector { public static final Keyword KW_STRING = RT.keyword(null, "string"); public static final Keyword KW_OFFSET = RT.keyword(null, "offset"); public static final Keyword KW_IMPORT = RT.keyword(null, "import"); public static class FileInfo implements NodeTraversal.Callback { JsAst.ParseResult parseResult; final FeatureSet features; public FileInfo(JsAst.ParseResult parseResult, FeatureSet features) { this.parseResult = parseResult; this.features = features; } ITransientCollection googRequires = PersistentVector.EMPTY.asTransient(); ITransientCollection googProvides = PersistentVector.EMPTY.asTransient(); ITransientCollection requires = PersistentVector.EMPTY.asTransient(); ITransientCollection invalidRequires = PersistentVector.EMPTY.asTransient(); ITransientCollection imports = PersistentVector.EMPTY.asTransient(); ITransientCollection strOffsets = PersistentVector.EMPTY.asTransient(); boolean esm = false; boolean usesGlobalBuffer = false; boolean usesGlobalProcess = false; String googModule = null; @Override public boolean shouldTraverse(NodeTraversal t, Node node, Node parent) { if (node.isFunction()) { Node params = node.getSecondChild(); // NodeUtil.getFunctionParameters(node) does a precondition we just did Node param = params.getFirstChild(); while (param != null) { // do not traverse into any function that declares a require local // non-minified browserify bundles might do this // function(require, module, exports) {} // as that is not a require we should resolves if (param.isName() && param.getString().equals("require")) { return false; } param = param.getNext(); } } else if (NodeUtil.isCallTo(node, "require.ensure")) { return false; } return true; } public void recordStrOffset(Node x, boolean isImport) { strOffsets = strOffsets.conj( RT.map( KW_STRING, x.getString(), KW_OFFSET, x.getSourceOffset(), KW_IMPORT, isImport ) ); } public static boolean isProcessEnvNode(Node node) { Node p = node.getParent(); if (p != null && p.isGetProp()) { p = p.getParent(); if (p != null && p.isGetProp() && "process.env.NODE_ENV".equals(p.getQualifiedName())) { // special case for files that only use process.env.NODE_ENV but nothing else from process // no need to add the process polyfill in those cases since process.env.NODE_ENV will be inlined later return true; } } return false; } @Override public void visit(NodeTraversal t, Node node, Node parent) { // closure treats all files that have import or export as ESM if (node.isImport() || node.isExport()) { esm = true; } if (NodeUtil.isCallTo(node, "require")) { Node requireString = node.getSecondChild(); if (requireString.isString()) { String require = requireString.getString(); requires = requires.conj(require); recordStrOffset(requireString, false); } else { invalidRequires = invalidRequires.conj( RT.map( KW_LINE, node.getLineno(), KW_COLUMN, node.getCharno() )); } } else if (node.isImport() || (node.isExport() && node.hasTwoChildren())) { Node importString = node.getLastChild(); String from = importString.getString(); imports = imports.conj(from); recordStrOffset(importString, true); } else if (NodeUtil.isCallTo(node, "goog.require")) { String x = node.getLastChild().getString(); googRequires = googRequires.conj(x); } else if (NodeUtil.isCallTo(node, "goog.provide")) { String x = node.getLastChild().getString(); googProvides = googProvides.conj(x); } else if (NodeUtil.isCallTo(node, "goog.module")) { googModule = node.getLastChild().getString(); } else if (node.isName() && node.getString().equals("Buffer") && t.getScope().getVar("Buffer") == null) { usesGlobalBuffer = true; } else if (node.isName() && node.getString().equals("process") && t.getScope().getVar("process") == null) { usesGlobalProcess = usesGlobalProcess || !isProcessEnvNode(node); } } } public static final Keyword KW_LINE = RT.keyword(null, "line"); public static final Keyword KW_COLUMN = RT.keyword(null, "column"); public static final Keyword KW_MESSAGE = RT.keyword(null, "message"); public static IPersistentVector errorsAsData(List errors) { ITransientCollection result = PersistentVector.EMPTY.asTransient(); for (int i = 0; i < errors.size(); i++) { JsAst.RhinoError error = (JsAst.RhinoError) errors.get(i); Object data = RT.map( KW_LINE, error.line, KW_COLUMN, error.lineOffset, KW_MESSAGE, error.message ); result = result.conj(data); } return (IPersistentVector) result.persistent(); } public static final String NS = null; public static final Keyword KW_INVALID_REQUIRES = RT.keyword(NS, "js-invalid-requires"); public static final Keyword KW_REQUIRES = RT.keyword(NS, "js-requires"); public static final Keyword KW_IMPORTS = RT.keyword(NS, "js-imports"); public static final Keyword KW_ERRORS = RT.keyword(NS, "js-errors"); public static final Keyword KW_WARNINGS = RT.keyword(NS, "js-warnings"); public static final Keyword KW_LANGUAGE = RT.keyword(NS, "js-language"); public static final Keyword KW_ESM = RT.keyword(NS, "js-esm"); public static final Keyword KW_STR_OFFSETS = RT.keyword(NS, "js-str-offsets"); public static final Keyword KW_GOOG_PROVIDES = RT.keyword(NS, "goog-provides"); public static final Keyword KW_GOOG_REQUIRES = RT.keyword(NS, "goog-requires"); public static final Keyword KW_GOOG_MODULE = RT.keyword(NS, "goog-module"); public static final Keyword KW_USES_GLOBAL_BUFFER = RT.keyword(NS, "uses-global-buffer"); public static final Keyword KW_USES_GLOBAL_PROCESS = RT.keyword(NS, "uses-global-process"); public static FileInfo getFileInfo(Compiler cc, SourceFile srcFile) { JsAst ast = new JsAst(srcFile); Node node = ast.getAstRoot(cc); JsAst.ParseResult result = (JsAst.ParseResult) node.getProp(Node.PARSE_RESULTS); FeatureSet features = ast.getFeatures(cc); // FIXME: don't do this if result has errors? FileInfo fileInfo = new FileInfo(result, features); NodeTraversal.traverse(cc, node, fileInfo); return fileInfo; } public static IPersistentMap getFileInfoMap(Compiler cc, SourceFile srcFile) { FileInfo fileInfo = getFileInfo(cc, srcFile); return asMap(fileInfo); } public static IPersistentMap asMap(FileInfo fileInfo) { IPersistentMap map = RT.map( KW_REQUIRES, fileInfo.requires.persistent(), KW_IMPORTS, fileInfo.imports.persistent(), KW_ESM, fileInfo.esm, KW_GOOG_PROVIDES, fileInfo.googProvides.persistent(), KW_GOOG_REQUIRES, fileInfo.googRequires.persistent(), KW_GOOG_MODULE, fileInfo.googModule, KW_INVALID_REQUIRES, fileInfo.invalidRequires.persistent(), KW_LANGUAGE, fileInfo.features.version(), KW_STR_OFFSETS, fileInfo.strOffsets.persistent(), KW_USES_GLOBAL_BUFFER, fileInfo.usesGlobalBuffer, KW_USES_GLOBAL_PROCESS, fileInfo.usesGlobalProcess ); if (fileInfo.parseResult != null) { map = map.assoc(KW_ERRORS, errorsAsData(fileInfo.parseResult.errors)).assoc(KW_WARNINGS, errorsAsData(fileInfo.parseResult.warnings)); } return map; } public static void main(String... args) throws IOException { Compiler cc = new Compiler(); CompilerOptions co = new CompilerOptions(); co.setLanguageIn(CompilerOptions.LanguageMode.ECMASCRIPT_2017); cc.initOptions(co); SourceFile srcFile = SourceFile.fromCode("foo.js", "var x = function(require) { require('DONT'); }; require('react'); require('./foo'); import 'foo'; import { x } from 'bar';"); //System.out.println(getFileInfoMap(cc, srcFile)); SourceFile exportFrom = SourceFile.fromCode("foo.js", "export * from './foo';"); //System.out.println(getFileInfoMap(cc, exportFrom)); SourceFile goog = SourceFile.fromCode("foo.js", "goog.provide('foo'); goog.require('thing');"); System.out.println(getFileInfoMap(cc, goog)); SourceFile jsxFile = SourceFile.fromCode( "jsx.js", "var x = require('foo'); function render() { return <div>foo</div> };" ); //System.out.println(getFileInfoMap(cc, jsxFile)); // babel es6 conversion pattern SourceFile esm1 = SourceFile.fromCode( "esm.js", "Object.defineProperty(exports, \"__esModule\", {\n" + " value: true\n" + "});" ); System.out.println(getFileInfoMap(cc, esm1)); // other es6 conversion pattern SourceFile esm2 = SourceFile.fromCode("esm2.js", "exports.__esModule = true;"); System.out.println(getFileInfoMap(cc, esm2)); SourceFile esm3 = SourceFile.fromCode("esm3.js", "module.exports = { \"default\": __webpack_require__(270), __esModule: true };"); System.out.println(getFileInfoMap(cc, esm3)); SourceFile esm4 = SourceFile.fromCode("process.js", "process.env.NODE_ENV"); System.out.println(getFileInfoMap(cc, esm4)); SourceFile esm5 = SourceFile.fromCode("process.js", "process.cwd()"); System.out.println(getFileInfoMap(cc, esm5)); SourceFile esm6 = SourceFile.fromCode("process.js", "process.env.FOO"); System.out.println(getFileInfoMap(cc, esm6)); long start = System.currentTimeMillis(); getFileInfoMap(cc, srcFile); getFileInfoMap(cc, srcFile); getFileInfoMap(cc, srcFile); long runtime = System.currentTimeMillis() - start; //System.out.println(getFileInfoMap(cc, srcFile)); if (false) { Files.walkFileTree(Paths.get("node_modules"), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (file.getFileName().toString().endsWith(".js")) { String content = new String(Files.readAllBytes(file)); if (content.contains("__esModule")) { SourceFile test = SourceFile.fromCode("esm.js", content); FileInfo fi = getFileInfo(cc, test); System.out.println(file); System.out.println(asMap(fi)); } } return super.visitFile(file, attrs); } }); } System.out.format("runtime:%d%n", runtime); } }
package com.jme3.math; import com.jme3.export.*; import com.jme3.util.TempVars; import java.io.*; import java.util.logging.Logger; /** * <code>Quaternion</code> defines a single example of a more general class of * hypercomplex numbers. Quaternions extends a rotation in three dimensions to a * rotation in four dimensions. This avoids "gimbal lock" and allows for smooth * continuous rotation. * * <code>Quaternion</code> is defined by four floating point numbers: {x y z w}. * * @author Mark Powell * @author Joshua Slack */ public final class Quaternion implements Savable, Cloneable, java.io.Serializable { static final long serialVersionUID = 1; private static final Logger logger = Logger.getLogger(Quaternion.class.getName()); /** * Represents the identity quaternion rotation (0, 0, 0, 1). */ public static final Quaternion IDENTITY = new Quaternion(); /** * another instance of the identity Quaternion (0, 0, 0, 1) */ public static final Quaternion DIRECTION_Z = new Quaternion(); /** * The zero quaternion (0, 0, 0, 0) doesn't represent any rotation. */ public static final Quaternion ZERO = new Quaternion(0, 0, 0, 0); static { DIRECTION_Z.fromAxes(Vector3f.UNIT_X, Vector3f.UNIT_Y, Vector3f.UNIT_Z); } /** * the X component (not an angle!) */ protected float x; /** * the Y component (not an angle!) */ protected float y; /** * the Z component (not an angle!) */ protected float z; /** * the W (real) component (not an angle!) */ protected float w; /** * Constructor instantiates a new <code>Quaternion</code> object * initializing all values to zero, except w which is initialized to 1. * */ public Quaternion() { x = 0; y = 0; z = 0; w = 1; } /** * Constructor instantiates a new <code>Quaternion</code> object from the * given list of parameters. * * @param x the x value of the quaternion. * @param y the y value of the quaternion. * @param z the z value of the quaternion. * @param w the w value of the quaternion. */ public Quaternion(float x, float y, float z, float w) { this.x = x; this.y = y; this.z = z; this.w = w; } /** * Determine the X component. * * @return x */ public float getX() { return x; } /** * Determine the Y component. * * @return y */ public float getY() { return y; } /** * Determine the Z component. * * @return z */ public float getZ() { return z; } /** * Determine the W (real) component. * * @return w */ public float getW() { return w; } /** * sets the data in a <code>Quaternion</code> object from the given list of * parameters. * * @param x the x value of the quaternion. * @param y the y value of the quaternion. * @param z the z value of the quaternion. * @param w the w value of the quaternion. * @return this */ public Quaternion set(float x, float y, float z, float w) { this.x = x; this.y = y; this.z = z; this.w = w; return this; } /** * Sets the data in this <code>Quaternion</code> object to be equal to the * passed <code>Quaternion</code> object. The values are copied producing * a new object. * * @param q The Quaternion to copy values from. * @return this */ public Quaternion set(Quaternion q) { this.x = q.x; this.y = q.y; this.z = q.z; this.w = q.w; return this; } /** * Constructor instantiates a new <code>Quaternion</code> object from a * collection of rotation angles. * * @param angles * the angles of rotation (x, y, z) that will define the * <code>Quaternion</code>. */ public Quaternion(float[] angles) { fromAngles(angles); } /** * Constructor instantiates a new <code>Quaternion</code> object from an * interpolation between two other quaternions. * * @param q1 * the first quaternion. * @param q2 * the second quaternion. * @param interp * the amount to interpolate between the two quaternions. */ public Quaternion(Quaternion q1, Quaternion q2, float interp) { slerp(q1, q2, interp); } /** * Constructor instantiates a new <code>Quaternion</code> object from an * existing quaternion, creating a copy. * * @param q the quaternion to copy. */ public Quaternion(Quaternion q) { this.x = q.x; this.y = q.y; this.z = q.z; this.w = q.w; } /** * Sets this Quaternion to {0, 0, 0, 1}. Same as calling set(0,0,0,1). */ public void loadIdentity() { x = y = z = 0; w = 1; } /** * @return true if this Quaternion is {0,0,0,1} */ public boolean isIdentity() { if (x == 0 && y == 0 && z == 0 && w == 1) { return true; } else { return false; } } /** * <code>fromAngles</code> builds a quaternion from the Euler rotation * angles (x,y,z) aka (pitch, yaw, roll). * * @param angles * the Euler angles of rotation (in radians). * @return this */ public Quaternion fromAngles(float[] angles) { if (angles.length != 3) { throw new IllegalArgumentException( "Angles array must have three elements"); } return fromAngles(angles[0], angles[1], angles[2]); } public Quaternion fromAngles(float xAngle, float yAngle, float zAngle) { float angle; float sinY, sinZ, sinX, cosY, cosZ, cosX; angle = zAngle * 0.5f; sinZ = FastMath.sin(angle); cosZ = FastMath.cos(angle); angle = yAngle * 0.5f; sinY = FastMath.sin(angle); cosY = FastMath.cos(angle); angle = xAngle * 0.5f; sinX = FastMath.sin(angle); cosX = FastMath.cos(angle); // variables used to reduce multiplication calls. float cosYXcosZ = cosY * cosZ; float sinYXsinZ = sinY * sinZ; float cosYXsinZ = cosY * sinZ; float sinYXcosZ = sinY * cosZ; w = (cosYXcosZ * cosX - sinYXsinZ * sinX); x = (cosYXcosZ * sinX + sinYXsinZ * cosX); y = (sinYXcosZ * cosX + cosYXsinZ * sinX); z = (cosYXsinZ * cosX - sinYXcosZ * sinX); normalizeLocal(); return this; } public float[] toAngles(float[] angles) { if (angles == null) { angles = new float[3]; } else if (angles.length != 3) { throw new IllegalArgumentException("Angles array must have three elements"); } float sqw = w * w; float sqx = x * x; float sqy = y * y; float sqz = z * z; float unit = sqx + sqy + sqz + sqw; // if normalized is one, otherwise // is correction factor float test = x * y + z * w; if (test > 0.499 * unit) { // singularity at north pole angles[1] = 2 * FastMath.atan2(x, w); angles[2] = FastMath.HALF_PI; angles[0] = 0; } else if (test < -0.499 * unit) { // singularity at south pole angles[1] = -2 * FastMath.atan2(x, w); angles[2] = -FastMath.HALF_PI; angles[0] = 0; } else { angles[1] = FastMath.atan2(2 * y * w - 2 * x * z, sqx - sqy - sqz + sqw); // yaw or heading angles[2] = FastMath.asin(2 * test / unit); // roll or bank angles[0] = FastMath.atan2(2 * x * w - 2 * y * z, -sqx + sqy - sqz + sqw); // pitch or attitude } return angles; } /** * <code>fromRotationMatrix</code> generates a quaternion from a supplied * matrix. This matrix is assumed to be a rotational matrix. * * @param matrix * the matrix that defines the rotation. * @return this */ public Quaternion fromRotationMatrix(Matrix3f matrix) { return fromRotationMatrix(matrix.m00, matrix.m01, matrix.m02, matrix.m10, matrix.m11, matrix.m12, matrix.m20, matrix.m21, matrix.m22); } /** * Set this quaternion based on a rotation matrix with the specified * elements. * * @param m00 the matrix element in row 0, column 0 * @param m01 the matrix element in row 0, column 1 * @param m02 the matrix element in row 0, column 2 * @param m10 the matrix element in row 1, column 0 * @param m11 the matrix element in row 1, column 1 * @param m12 the matrix element in row 1, column 2 * @param m20 the matrix element in row 2, column 0 * @param m21 the matrix element in row 2, column 1 * @param m22 the matrix element in row 2, column 2 * @return this Quaternion */ public Quaternion fromRotationMatrix(float m00, float m01, float m02, float m10, float m11, float m12, float m20, float m21, float m22) { // first normalize the forward (F), up (U) and side (S) vectors of the rotation matrix // so that the scale does not affect the rotation float lengthSquared = m00 * m00 + m10 * m10 + m20 * m20; if (lengthSquared != 1f && lengthSquared != 0f) { lengthSquared = 1.0f / FastMath.sqrt(lengthSquared); m00 *= lengthSquared; m10 *= lengthSquared; m20 *= lengthSquared; } lengthSquared = m01 * m01 + m11 * m11 + m21 * m21; if (lengthSquared != 1f && lengthSquared != 0f) { lengthSquared = 1.0f / FastMath.sqrt(lengthSquared); m01 *= lengthSquared; m11 *= lengthSquared; m21 *= lengthSquared; } lengthSquared = m02 * m02 + m12 * m12 + m22 * m22; if (lengthSquared != 1f && lengthSquared != 0f) { lengthSquared = 1.0f / FastMath.sqrt(lengthSquared); m02 *= lengthSquared; m12 *= lengthSquared; m22 *= lengthSquared; } // Use the Graphics Gems code, from // *NOT* the "Matrix and Quaternions FAQ", which has errors! // the trace is the sum of the diagonal elements; see float t = m00 + m11 + m22; // we protect the division by s by ensuring that s>=1 if (t >= 0) { // |w| >= .5 float s = FastMath.sqrt(t + 1); w = 0.5f * s; s = 0.5f / s; // so this division isn't bad x = (m21 - m12) * s; y = (m02 - m20) * s; z = (m10 - m01) * s; } else if ((m00 > m11) && (m00 > m22)) { float s = FastMath.sqrt(1.0f + m00 - m11 - m22); x = s * 0.5f; // |x| >= .5 s = 0.5f / s; y = (m10 + m01) * s; z = (m02 + m20) * s; w = (m21 - m12) * s; } else if (m11 > m22) { float s = FastMath.sqrt(1.0f + m11 - m00 - m22); y = s * 0.5f; // |y| >= .5 s = 0.5f / s; x = (m10 + m01) * s; z = (m21 + m12) * s; w = (m02 - m20) * s; } else { float s = FastMath.sqrt(1.0f + m22 - m00 - m11); z = s * 0.5f; // |z| >= .5 s = 0.5f / s; x = (m02 + m20) * s; y = (m21 + m12) * s; w = (m10 - m01) * s; } return this; } /** * <code>toRotationMatrix</code> converts this quaternion to a rotational * matrix. Note: the result is created from a normalized version of this quat. * * @return the rotation matrix representation of this quaternion. */ public Matrix3f toRotationMatrix() { Matrix3f matrix = new Matrix3f(); return toRotationMatrix(matrix); } /** * <code>toRotationMatrix</code> converts this quaternion to a rotational * matrix. The result is stored in result. * * @param result * The Matrix3f to store the result in. * @return the rotation matrix representation of this quaternion. */ public Matrix3f toRotationMatrix(Matrix3f result) { float norm = norm(); // we explicitly test norm against one here, saving a division // at the cost of a test and branch. Is it worth it? float s = (norm == 1f) ? 2f : (norm > 0f) ? 2f / norm : 0; // compute xs/ys/zs first to save 6 multiplications, since xs/ys/zs // will be used 2-4 times each. float xs = x * s; float ys = y * s; float zs = z * s; float xx = x * xs; float xy = x * ys; float xz = x * zs; float xw = w * xs; float yy = y * ys; float yz = y * zs; float yw = w * ys; float zz = z * zs; float zw = w * zs; // using s=2/norm (instead of 1/norm) saves 9 multiplications by 2 here result.m00 = 1 - (yy + zz); result.m01 = (xy - zw); result.m02 = (xz + yw); result.m10 = (xy + zw); result.m11 = 1 - (xx + zz); result.m12 = (yz - xw); result.m20 = (xz - yw); result.m21 = (yz + xw); result.m22 = 1 - (xx + yy); return result; } /** * <code>toTransformMatrix</code> converts this quaternion to a transform * matrix. The result is stored in result. * Note this method won't preserve the scale of the given matrix. * * @param store The Matrix3f to store the result in. * @return the transform matrix with the rotation representation of this quaternion. */ public Matrix4f toTransformMatrix(Matrix4f store) { float norm = norm(); // we explicitly test norm against one here, saving a division // at the cost of a test and branch. Is it worth it? float s = (norm == 1f) ? 2f : (norm > 0f) ? 2f / norm : 0; // compute xs/ys/zs first to save 6 multiplications, since xs/ys/zs // will be used 2-4 times each. float xs = x * s; float ys = y * s; float zs = z * s; float xx = x * xs; float xy = x * ys; float xz = x * zs; float xw = w * xs; float yy = y * ys; float yz = y * zs; float yw = w * ys; float zz = z * zs; float zw = w * zs; // using s=2/norm (instead of 1/norm) saves 9 multiplications by 2 here store.m00 = 1 - (yy + zz); store.m01 = (xy - zw); store.m02 = (xz + yw); store.m10 = (xy + zw); store.m11 = 1 - (xx + zz); store.m12 = (yz - xw); store.m20 = (xz - yw); store.m21 = (yz + xw); store.m22 = 1 - (xx + yy); return store; } /** * <code>toRotationMatrix</code> converts this quaternion to a rotational * matrix. The result is stored in result. 4th row and 4th column values are * untouched. Note: the result is created from a normalized version of this quat. * Note that this method will preserve the scale of the given matrix * * @param result * The Matrix4f to store the result in. * @return the rotation matrix representation of this quaternion. */ public Matrix4f toRotationMatrix(Matrix4f result) { TempVars tempv = TempVars.get(); Vector3f originalScale = tempv.vect1; result.toScaleVector(originalScale); result.setScale(1, 1, 1); float norm = norm(); // we explicitly test norm against one here, saving a division // at the cost of a test and branch. Is it worth it? float s = (norm == 1f) ? 2f : (norm > 0f) ? 2f / norm : 0; // compute xs/ys/zs first to save 6 multiplications, since xs/ys/zs // will be used 2-4 times each. float xs = x * s; float ys = y * s; float zs = z * s; float xx = x * xs; float xy = x * ys; float xz = x * zs; float xw = w * xs; float yy = y * ys; float yz = y * zs; float yw = w * ys; float zz = z * zs; float zw = w * zs; // using s=2/norm (instead of 1/norm) saves 9 multiplications by 2 here result.m00 = 1 - (yy + zz); result.m01 = (xy - zw); result.m02 = (xz + yw); result.m10 = (xy + zw); result.m11 = 1 - (xx + zz); result.m12 = (yz - xw); result.m20 = (xz - yw); result.m21 = (yz + xw); result.m22 = 1 - (xx + yy); result.setScale(originalScale); tempv.release(); return result; } /** * <code>getRotationColumn</code> returns one of three columns specified * by the parameter. This column is returned as a <code>Vector3f</code> * object. * * @param i the column to retrieve. Must be between 0 and 2. * @return the column specified by the index. */ public Vector3f getRotationColumn(int i) { return getRotationColumn(i, null); } /** * <code>getRotationColumn</code> returns one of three columns specified * by the parameter. This column is returned as a <code>Vector3f</code> * object. The value is retrieved as if this quaternion was first normalized. * * @param i the column to retrieve. Must be between 0 and 2. * @param store * the vector object to store the result in. if null, a new one * is created. * @return the column specified by the index. */ public Vector3f getRotationColumn(int i, Vector3f store) { if (store == null) { store = new Vector3f(); } float norm = norm(); if (norm != 1.0f) { norm = FastMath.invSqrt(norm); } float xx = x * x * norm; float xy = x * y * norm; float xz = x * z * norm; float xw = x * w * norm; float yy = y * y * norm; float yz = y * z * norm; float yw = y * w * norm; float zz = z * z * norm; float zw = z * w * norm; switch (i) { case 0: store.x = 1 - 2 * (yy + zz); store.y = 2 * (xy + zw); store.z = 2 * (xz - yw); break; case 1: store.x = 2 * (xy - zw); store.y = 1 - 2 * (xx + zz); store.z = 2 * (yz + xw); break; case 2: store.x = 2 * (xz + yw); store.y = 2 * (yz - xw); store.z = 1 - 2 * (xx + yy); break; default: logger.warning("Invalid column index."); throw new IllegalArgumentException("Invalid column index. " + i); } return store; } /** * <code>fromAngleAxis</code> sets this quaternion to the values specified * by an angle and an axis of rotation. This method creates an object, so * use fromAngleNormalAxis if your axis is already normalized. * * @param angle * the angle to rotate (in radians). * @param axis * the axis of rotation. * @return this quaternion */ public Quaternion fromAngleAxis(float angle, Vector3f axis) { Vector3f normAxis = axis.normalize(); fromAngleNormalAxis(angle, normAxis); return this; } /** * <code>fromAngleNormalAxis</code> sets this quaternion to the values * specified by an angle and a normalized axis of rotation. * * @param angle * the angle to rotate (in radians). * @param axis * the axis of rotation (already normalized). * @return this */ public Quaternion fromAngleNormalAxis(float angle, Vector3f axis) { if (axis.x == 0 && axis.y == 0 && axis.z == 0) { loadIdentity(); } else { float halfAngle = 0.5f * angle; float sin = FastMath.sin(halfAngle); w = FastMath.cos(halfAngle); x = sin * axis.x; y = sin * axis.y; z = sin * axis.z; } return this; } /** * <code>toAngleAxis</code> sets a given angle and axis to that * represented by the current quaternion. The values are stored as * follows: The axis is provided as a parameter and built by the method, * the angle is returned as a float. * * @param axisStore * the object we'll store the computed axis in. * @return the angle of rotation in radians. */ public float toAngleAxis(Vector3f axisStore) { float sqrLength = x * x + y * y + z * z; float angle; if (sqrLength == 0.0f) { angle = 0.0f; if (axisStore != null) { axisStore.x = 1.0f; axisStore.y = 0.0f; axisStore.z = 0.0f; } } else { angle = (2.0f * FastMath.acos(w)); if (axisStore != null) { float invLength = (1.0f / FastMath.sqrt(sqrLength)); axisStore.x = x * invLength; axisStore.y = y * invLength; axisStore.z = z * invLength; } } return angle; } /** * <code>slerp</code> sets this quaternion's value as an interpolation * between two other quaternions. * * @param q1 * the first quaternion. * @param q2 * the second quaternion. * @param t the amount to interpolate between the two quaternions. * @return this */ public Quaternion slerp(Quaternion q1, Quaternion q2, float t) { // Create a local quaternion to store the interpolated quaternion if (q1.x == q2.x && q1.y == q2.y && q1.z == q2.z && q1.w == q2.w) { this.set(q1); return this; } float result = (q1.x * q2.x) + (q1.y * q2.y) + (q1.z * q2.z) + (q1.w * q2.w); if (result < 0.0f) { // Negate the second quaternion and the result of the dot product q2.x = -q2.x; q2.y = -q2.y; q2.z = -q2.z; q2.w = -q2.w; result = -result; } // Set the first and second scale for the interpolation float scale0 = 1 - t; float scale1 = t; // Check if the angle between the 2 quaternions was big enough to // warrant such calculations if ((1 - result) > 0.1f) {// Get the angle between the 2 quaternions, // and then store the sin() of that angle float theta = FastMath.acos(result); float invSinTheta = 1f / FastMath.sin(theta); // Calculate the scale for q1 and q2, according to the angle and // its sine scale0 = FastMath.sin((1 - t) * theta) * invSinTheta; scale1 = FastMath.sin((t * theta)) * invSinTheta; } // Calculate the x, y, z and w values for the quaternion by using a // special // form of linear interpolation for quaternions. this.x = (scale0 * q1.x) + (scale1 * q2.x); this.y = (scale0 * q1.y) + (scale1 * q2.y); this.z = (scale0 * q1.z) + (scale1 * q2.z); this.w = (scale0 * q1.w) + (scale1 * q2.w); // Return the interpolated quaternion return this; } /** * Sets the values of this quaternion to the slerp from itself to q2 by * changeAmnt * * @param q2 * Final interpolation value * @param changeAmnt * The amount difference */ public void slerp(Quaternion q2, float changeAmnt) { if (this.x == q2.x && this.y == q2.y && this.z == q2.z && this.w == q2.w) { return; } float result = (this.x * q2.x) + (this.y * q2.y) + (this.z * q2.z) + (this.w * q2.w); if (result < 0.0f) { // Negate the second quaternion and the result of the dot product q2.x = -q2.x; q2.y = -q2.y; q2.z = -q2.z; q2.w = -q2.w; result = -result; } // Set the first and second scale for the interpolation float scale0 = 1 - changeAmnt; float scale1 = changeAmnt; // Check if the angle between the 2 quaternions was big enough to // warrant such calculations if ((1 - result) > 0.1f) { // Get the angle between the 2 quaternions, and then store the sin() // of that angle float theta = FastMath.acos(result); float invSinTheta = 1f / FastMath.sin(theta); // Calculate the scale for q1 and q2, according to the angle and // its sine scale0 = FastMath.sin((1 - changeAmnt) * theta) * invSinTheta; scale1 = FastMath.sin((changeAmnt * theta)) * invSinTheta; } // Calculate the x, y, z and w values for the quaternion by using a // special // form of linear interpolation for quaternions. this.x = (scale0 * this.x) + (scale1 * q2.x); this.y = (scale0 * this.y) + (scale1 * q2.y); this.z = (scale0 * this.z) + (scale1 * q2.z); this.w = (scale0 * this.w) + (scale1 * q2.w); } /** * Sets the values of this quaternion to the nlerp from itself to q2 by blend. * * @param q2 * @param blend */ public void nlerp(Quaternion q2, float blend) { float dot = dot(q2); float blendI = 1.0f - blend; if (dot < 0.0f) { x = blendI * x - blend * q2.x; y = blendI * y - blend * q2.y; z = blendI * z - blend * q2.z; w = blendI * w - blend * q2.w; } else { x = blendI * x + blend * q2.x; y = blendI * y + blend * q2.y; z = blendI * z + blend * q2.z; w = blendI * w + blend * q2.w; } normalizeLocal(); } /** * <code>add</code> adds the values of this quaternion to those of the * parameter quaternion. The result is returned as a new quaternion. * * @param q the quaternion to add to this. * @return the new quaternion. */ public Quaternion add(Quaternion q) { return new Quaternion(x + q.x, y + q.y, z + q.z, w + q.w); } /** * <code>add</code> adds the values of this quaternion to those of the * parameter quaternion. The result is stored in this Quaternion. * * @param q the quaternion to add to this. * @return This Quaternion after addition. */ public Quaternion addLocal(Quaternion q) { this.x += q.x; this.y += q.y; this.z += q.z; this.w += q.w; return this; } /** * <code>subtract</code> subtracts the values of the parameter quaternion * from those of this quaternion. The result is returned as a new * quaternion. * * @param q the quaternion to subtract from this. * @return the new quaternion. */ public Quaternion subtract(Quaternion q) { return new Quaternion(x - q.x, y - q.y, z - q.z, w - q.w); } /** * <code>subtract</code> subtracts the values of the parameter quaternion * from those of this quaternion. The result is stored in this Quaternion. * * @param q the quaternion to subtract from this. * @return This Quaternion after subtraction. */ public Quaternion subtractLocal(Quaternion q) { this.x -= q.x; this.y -= q.y; this.z -= q.z; this.w -= q.w; return this; } /** * <code>mult</code> multiplies this quaternion by a parameter quaternion. * The result is returned as a new quaternion. It should be noted that * quaternion multiplication is not commutative so q * p != p * q. * * @param q the quaternion to multiply this quaternion by. * @return the new quaternion. */ public Quaternion mult(Quaternion q) { return mult(q, null); } /** * <code>mult</code> multiplies this quaternion by a parameter quaternion. * The result is returned as a new quaternion. It should be noted that * quaternion multiplication is not commutative so q * p != p * q. * * It IS safe for q and res to be the same object. * It IS NOT safe for this and res to be the same object. * * @param q the quaternion to multiply this quaternion by. * @param res * the quaternion to store the result in. * @return the new quaternion. */ public Quaternion mult(Quaternion q, Quaternion res) { if (res == null) { res = new Quaternion(); } float qw = q.w, qx = q.x, qy = q.y, qz = q.z; res.x = x * qw + y * qz - z * qy + w * qx; res.y = -x * qz + y * qw + z * qx + w * qy; res.z = x * qy - y * qx + z * qw + w * qz; res.w = -x * qx - y * qy - z * qz + w * qw; return res; } /** * <code>apply</code> multiplies this quaternion by a parameter matrix * internally. * * @param matrix * the matrix to apply to this quaternion. */ public void apply(Matrix3f matrix) { float oldX = x, oldY = y, oldZ = z, oldW = w; fromRotationMatrix(matrix); float tempX = x, tempY = y, tempZ = z, tempW = w; x = oldX * tempW + oldY * tempZ - oldZ * tempY + oldW * tempX; y = -oldX * tempZ + oldY * tempW + oldZ * tempX + oldW * tempY; z = oldX * tempY - oldY * tempX + oldZ * tempW + oldW * tempZ; w = -oldX * tempX - oldY * tempY - oldZ * tempZ + oldW * tempW; } /** * * <code>fromAxes</code> creates a <code>Quaternion</code> that * represents the coordinate system defined by three axes. These axes are * assumed to be orthogonal and no error checking is applied. Thus, the user * must insure that the three axes being provided indeed represents a proper * right handed coordinate system. * * @param axis * the array containing the three vectors representing the * coordinate system. * @return this */ public Quaternion fromAxes(Vector3f[] axis) { if (axis.length != 3) { throw new IllegalArgumentException( "Axis array must have three elements"); } return fromAxes(axis[0], axis[1], axis[2]); } /** * * <code>fromAxes</code> creates a <code>Quaternion</code> that * represents the coordinate system defined by three axes. These axes are * assumed to be orthogonal and no error checking is applied. Thus, the user * must insure that the three axes being provided indeed represents a proper * right handed coordinate system. * * @param xAxis vector representing the x-axis of the coordinate system. * @param yAxis vector representing the y-axis of the coordinate system. * @param zAxis vector representing the z-axis of the coordinate system. * @return this */ public Quaternion fromAxes(Vector3f xAxis, Vector3f yAxis, Vector3f zAxis) { return fromRotationMatrix(xAxis.x, yAxis.x, zAxis.x, xAxis.y, yAxis.y, zAxis.y, xAxis.z, yAxis.z, zAxis.z); } /** * * <code>toAxes</code> takes in an array of three vectors. Each vector * corresponds to an axis of the coordinate system defined by the quaternion * rotation. * * @param axis the array of vectors to be filled. */ public void toAxes(Vector3f axis[]) { Matrix3f tempMat = toRotationMatrix(); axis[0] = tempMat.getColumn(0, axis[0]); axis[1] = tempMat.getColumn(1, axis[1]); axis[2] = tempMat.getColumn(2, axis[2]); } /** * <code>mult</code> multiplies this quaternion by a parameter vector. The * result is returned as a new vector. * * @param v the vector to multiply this quaternion by. * @return the new vector. */ public Vector3f mult(Vector3f v) { return mult(v, null); } /** * <code>mult</code> multiplies this quaternion by a parameter vector. The * result is stored in the supplied vector * * @param v the vector to multiply this quaternion by. * @return v */ public Vector3f multLocal(Vector3f v) { float tempX, tempY; tempX = w * w * v.x + 2 * y * w * v.z - 2 * z * w * v.y + x * x * v.x + 2 * y * x * v.y + 2 * z * x * v.z - z * z * v.x - y * y * v.x; tempY = 2 * x * y * v.x + y * y * v.y + 2 * z * y * v.z + 2 * w * z * v.x - z * z * v.y + w * w * v.y - 2 * x * w * v.z - x * x * v.y; v.z = 2 * x * z * v.x + 2 * y * z * v.y + z * z * v.z - 2 * w * y * v.x - y * y * v.z + 2 * w * x * v.y - x * x * v.z + w * w * v.z; v.x = tempX; v.y = tempY; return v; } /** * Multiplies this Quaternion by the supplied quaternion. The result is * stored in this Quaternion, which is also returned for chaining. Similar * to this *= q. * * @param q The Quaternion to multiply this one by. * @return This Quaternion, after multiplication. */ public Quaternion multLocal(Quaternion q) { float x1 = x * q.w + y * q.z - z * q.y + w * q.x; float y1 = -x * q.z + y * q.w + z * q.x + w * q.y; float z1 = x * q.y - y * q.x + z * q.w + w * q.z; w = -x * q.x - y * q.y - z * q.z + w * q.w; x = x1; y = y1; z = z1; return this; } /** * Multiplies this Quaternion by the supplied quaternion. The result is * stored in this Quaternion, which is also returned for chaining. Similar * to this *= q. * * @param qx quat x value * @param qy quat y value * @param qz quat z value * @param qw quat w value * * @return This Quaternion, after multiplication. */ public Quaternion multLocal(float qx, float qy, float qz, float qw) { float x1 = x * qw + y * qz - z * qy + w * qx; float y1 = -x * qz + y * qw + z * qx + w * qy; float z1 = x * qy - y * qx + z * qw + w * qz; w = -x * qx - y * qy - z * qz + w * qw; x = x1; y = y1; z = z1; return this; } /** * <code>mult</code> multiplies this quaternion by a parameter vector. The * result is returned as a new vector. * * @param v * the vector to multiply this quaternion by. * @param store * the vector to store the result in. It IS safe for v and store * to be the same object. * @return the result vector. */ public Vector3f mult(Vector3f v, Vector3f store) { if (store == null) { store = new Vector3f(); } if (v.x == 0 && v.y == 0 && v.z == 0) { store.set(0, 0, 0); } else { float vx = v.x, vy = v.y, vz = v.z; store.x = w * w * vx + 2 * y * w * vz - 2 * z * w * vy + x * x * vx + 2 * y * x * vy + 2 * z * x * vz - z * z * vx - y * y * vx; store.y = 2 * x * y * vx + y * y * vy + 2 * z * y * vz + 2 * w * z * vx - z * z * vy + w * w * vy - 2 * x * w * vz - x * x * vy; store.z = 2 * x * z * vx + 2 * y * z * vy + z * z * vz - 2 * w * y * vx - y * y * vz + 2 * w * x * vy - x * x * vz + w * w * vz; } return store; } /** * <code>mult</code> multiplies this quaternion by a parameter scalar. The * result is returned as a new quaternion. * * @param scalar * the quaternion to multiply this quaternion by. * @return the new quaternion. */ public Quaternion mult(float scalar) { return new Quaternion(scalar * x, scalar * y, scalar * z, scalar * w); } /** * <code>mult</code> multiplies this quaternion by a parameter scalar. The * result is stored locally. * * @param scalar * the quaternion to multiply this quaternion by. * @return this. */ public Quaternion multLocal(float scalar) { w *= scalar; x *= scalar; y *= scalar; z *= scalar; return this; } /** * <code>dot</code> calculates and returns the dot product of this * quaternion with that of the parameter quaternion. * * @param q the quaternion to calculate the dot product of. * @return the dot product of this and the parameter quaternion. */ public float dot(Quaternion q) { return w * q.w + x * q.x + y * q.y + z * q.z; } /** * <code>norm</code> returns the norm of this quaternion. This is the dot * product of this quaternion with itself. * * @return the norm of the quaternion. */ public float norm() { return w * w + x * x + y * y + z * z; } // /** // * <code>normalize</code> normalizes the current <code>Quaternion</code> // * @deprecated The naming of this method doesn't follow convention. // * Please use {@link Quaternion#normalizeLocal() } instead. // */ // @Deprecated // public void normalize() { // float n = FastMath.invSqrt(norm()); // x *= n; // y *= n; // z *= n; // w *= n; /** * <code>normalize</code> normalizes the current <code>Quaternion</code>. * The result is stored internally. * * @return this */ public Quaternion normalizeLocal() { float n = FastMath.invSqrt(norm()); x *= n; y *= n; z *= n; w *= n; return this; } /** * <code>inverse</code> returns the inverse of this quaternion as a new * quaternion. If this quaternion does not have an inverse (if its normal is * 0 or less), then null is returned. * * @return the inverse of this quaternion or null if the inverse does not * exist. */ public Quaternion inverse() { float norm = norm(); if (norm > 0.0) { float invNorm = 1.0f / norm; return new Quaternion(-x * invNorm, -y * invNorm, -z * invNorm, w * invNorm); } // return an invalid result to flag the error return null; } /** * <code>inverse</code> calculates the inverse of this quaternion and * returns this quaternion after it is calculated. If this quaternion does * not have an inverse (if its normal is 0 or less), nothing happens * * @return the inverse of this quaternion */ public Quaternion inverseLocal() { float norm = norm(); if (norm > 0.0) { float invNorm = 1.0f / norm; x *= -invNorm; y *= -invNorm; z *= -invNorm; w *= invNorm; } return this; } /** * Flip the signs of all components of this Quaternion. */ public void negate() { x *= -1; y *= -1; z *= -1; w *= -1; } /** * <code>toString</code> returns a string representation of this * <code>Quaternion</code>. The format is: * * (X.XXXX, Y.YYYY, Z.ZZZZ, W.WWWW) * * @return the string representation of this object. * @see java.lang.Object#toString() */ @Override public String toString() { return "(" + x + ", " + y + ", " + z + ", " + w + ")"; } /** * <code>equals</code> determines if two quaternions are logically equal, * that is, if the values of (x, y, z, w) are the same for both quaternions. * * @param o the object to compare for equality * @return true if they are equal, false otherwise. */ @Override public boolean equals(Object o) { if (!(o instanceof Quaternion)) { return false; } if (this == o) { return true; } Quaternion comp = (Quaternion) o; if (Float.compare(x, comp.x) != 0) { return false; } if (Float.compare(y, comp.y) != 0) { return false; } if (Float.compare(z, comp.z) != 0) { return false; } if (Float.compare(w, comp.w) != 0) { return false; } return true; } /** * Returns true if this quaternion is similar to the specified quaternion * within some value of epsilon. * * @param other the Quaternion to compare with (not null, unaffected) * @param epsilon the error tolerance for each component * @return true if all 4 components are within tolerance, otherwise false */ public boolean isSimilar(Quaternion other, float epsilon) { if (other == null) { return false; } if (Float.compare(Math.abs(other.x - x), epsilon) > 0) { return false; } if (Float.compare(Math.abs(other.y - y), epsilon) > 0) { return false; } if (Float.compare(Math.abs(other.z - z), epsilon) > 0) { return false; } if (Float.compare(Math.abs(other.w - w), epsilon) > 0) { return false; } return true; } /** * <code>hashCode</code> returns the hash code value as an integer and is * supported for the benefit of hashing based collection classes such as * Hashtable, HashMap, HashSet etc. * * @return the hashcode for this instance of Quaternion. * @see java.lang.Object#hashCode() */ @Override public int hashCode() { int hash = 37; hash = 37 * hash + Float.floatToIntBits(x); hash = 37 * hash + Float.floatToIntBits(y); hash = 37 * hash + Float.floatToIntBits(z); hash = 37 * hash + Float.floatToIntBits(w); return hash; } /** * <code>readExternal</code> builds a quaternion from an * <code>ObjectInput</code> object. <br> * NOTE: Used with serialization. Not to be called manually. * * @param in * the ObjectInput value to read from. * @throws IOException * if the ObjectInput value has problems reading a float. * @see java.io.Externalizable */ public void readExternal(ObjectInput in) throws IOException { x = in.readFloat(); y = in.readFloat(); z = in.readFloat(); w = in.readFloat(); } /** * <code>writeExternal</code> writes this quaternion out to a * <code>ObjectOutput</code> object. NOTE: Used with serialization. Not to * be called manually. * * @param out * the object to write to. * @throws IOException * if writing to the ObjectOutput fails. * @see java.io.Externalizable */ public void writeExternal(ObjectOutput out) throws IOException { out.writeFloat(x); out.writeFloat(y); out.writeFloat(z); out.writeFloat(w); } /** * <code>lookAt</code> is a convienence method for auto-setting the * quaternion based on a direction and an up vector. It computes * the rotation to transform the z-axis to point into 'direction' * and the y-axis to 'up'. * * @param direction * where to look at in terms of local coordinates * @param up * a vector indicating the local up direction. * (typically {0, 1, 0} in jME.) * @return this */ public Quaternion lookAt(Vector3f direction, Vector3f up) { TempVars vars = TempVars.get(); vars.vect3.set(direction).normalizeLocal(); vars.vect1.set(up).crossLocal(direction).normalizeLocal(); vars.vect2.set(direction).crossLocal(vars.vect1).normalizeLocal(); fromAxes(vars.vect1, vars.vect2, vars.vect3); vars.release(); return this; } /** * Serialize this quaternion to the specified exporter, for example when * saving to a J3O file. * * @param e (not null) * @throws IOException from the exporter */ @Override public void write(JmeExporter e) throws IOException { OutputCapsule cap = e.getCapsule(this); cap.write(x, "x", 0); cap.write(y, "y", 0); cap.write(z, "z", 0); cap.write(w, "w", 1); } /** * De-serialize this quaternion from the specified importer, for example * when loading from a J3O file. * * @param e (not null) * @throws IOException from the importer */ @Override public void read(JmeImporter e) throws IOException { InputCapsule cap = e.getCapsule(this); x = cap.readFloat("x", 0); y = cap.readFloat("y", 0); z = cap.readFloat("z", 0); w = cap.readFloat("w", 1); } /** * @return A new quaternion that describes a rotation that would point you * in the exact opposite direction of this Quaternion. */ public Quaternion opposite() { return opposite(null); } /** * FIXME: This seems to have singularity type issues with angle == 0, possibly others such as PI. * * @param store * A Quaternion to store our result in. If null, a new one is * created. * @return The store quaternion (or a new Quaternion, if store is null) that * describes a rotation that would point you in the exact opposite * direction of this Quaternion. */ public Quaternion opposite(Quaternion store) { if (store == null) { store = new Quaternion(); } Vector3f axis = new Vector3f(); float angle = toAngleAxis(axis); store.fromAngleAxis(FastMath.PI + angle, axis); return store; } /** * @return This Quaternion, altered to describe a rotation that would point * you in the exact opposite direction of where it is pointing * currently. */ public Quaternion oppositeLocal() { return opposite(this); } /** * Create a copy of this quaternion. * * @return a new instance, equivalent to this one */ @Override public Quaternion clone() { try { return (Quaternion) super.clone(); } catch (CloneNotSupportedException e) { throw new AssertionError(); // can not happen } } }
package jolie.net; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.server.rpc.RPC; import com.google.gwt.user.server.rpc.RPCRequest; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.URI; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import jolie.Interpreter; import jolie.lang.NativeType; import jolie.net.http.HttpMessage; import jolie.net.http.HttpParser; import jolie.net.http.HttpUtils; import jolie.net.http.json.JsonUtils; import joliex.gwt.server.JolieGWTConverter; import jolie.net.http.Method; import jolie.net.http.MultiPartFormDataParser; import jolie.net.ports.Interface; import jolie.net.protocols.CommProtocol; import jolie.runtime.ByteArray; import jolie.runtime.Value; import jolie.runtime.ValueVector; import jolie.runtime.VariablePath; import jolie.runtime.typing.OneWayTypeDescription; import jolie.runtime.typing.RequestResponseTypeDescription; import jolie.runtime.typing.Type; import jolie.runtime.typing.TypeCastingException; import jolie.util.LocationParser; import jolie.xml.XmlUtils; import joliex.gwt.client.JolieService; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * HTTP protocol implementation * @author Fabrizio Montesi */ public class HttpProtocol extends CommProtocol { private static final byte[] NOT_IMPLEMENTED_HEADER = "HTTP/1.1 501 Not Implemented".getBytes(); //private static final byte[] INTERNAL_SERVER_ERROR_HEADER = "HTTP/1.1 500 Internal Server error".getBytes(); private static class Parameters { private static String DEBUG = "debug"; private static String COOKIES = "cookies"; private static String METHOD = "method"; private static String ALIAS = "alias"; private static String MULTIPART_HEADERS = "multipartHeaders"; private static String CONCURRENT = "concurrent"; private static class MultiPartHeaders { private static String FILENAME = "filename"; } } private static class Headers { private static String JOLIE_MESSAGE_ID = "X-Jolie-MessageID"; } private String inputId = null; private final Transformer transformer; private final DocumentBuilderFactory docBuilderFactory; private final DocumentBuilder docBuilder; private final URI uri; private final boolean inInputPort; private MultiPartFormDataParser multiPartFormDataParser = null; public final static String CRLF = new String( new char[] { 13, 10 } ); public String name() { return "http"; } public boolean isThreadSafe() { return checkBooleanParameter( Parameters.CONCURRENT ); } public HttpProtocol( VariablePath configurationPath, URI uri, boolean inInputPort, TransformerFactory transformerFactory, DocumentBuilderFactory docBuilderFactory, DocumentBuilder docBuilder ) throws TransformerConfigurationException { super( configurationPath ); this.uri = uri; this.inInputPort = inInputPort; this.transformer = transformerFactory.newTransformer(); this.docBuilderFactory = docBuilderFactory; this.docBuilder = docBuilder; transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" ); } private void valueToDocument( Value value, Node node, Document doc ) { node.appendChild( doc.createTextNode( value.strValue() ) ); Element currentElement; for( Entry< String, ValueVector > entry : value.children().entrySet() ) { if ( !entry.getKey().startsWith( "@" ) ) { for( Value val : entry.getValue() ) { currentElement = doc.createElement( entry.getKey() ); node.appendChild( currentElement ); Map< String, ValueVector > attrs = jolie.xml.XmlUtils.getAttributesOrNull( val ); if ( attrs != null ) { for( Entry< String, ValueVector > attrEntry : attrs.entrySet() ) { currentElement.setAttribute( attrEntry.getKey(), attrEntry.getValue().first().strValue() ); } } valueToDocument( val, currentElement, doc ); } } } } public String getMultipartHeaderForPart( String operationName, String partName ) { if ( hasOperationSpecificParameter( operationName, Parameters.MULTIPART_HEADERS ) ) { Value v = getOperationSpecificParameterFirstValue( operationName, Parameters.MULTIPART_HEADERS ); if ( v.hasChildren( partName ) ) { v = v.getFirstChild( partName ); if ( v.hasChildren( Parameters.MultiPartHeaders.FILENAME ) ) { v = v.getFirstChild( Parameters.MultiPartHeaders.FILENAME ); return v.strValue(); } } } return null; } private final static String BOUNDARY = "----Jol13H77p$$Bound4r1$$"; private void send_appendCookies( CommMessage message, String hostname, StringBuilder headerBuilder ) { Value cookieParam = null; if ( hasOperationSpecificParameter( message.operationName(), Parameters.COOKIES ) ) { cookieParam = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.COOKIES ); } else if ( hasParameter( Parameters.COOKIES ) ) { cookieParam = getParameterFirstValue( Parameters.COOKIES ); } if ( cookieParam != null ) { Value cookieConfig; String domain; StringBuilder cookieSB = new StringBuilder(); for( Entry< String, ValueVector > entry : cookieParam.children().entrySet() ) { cookieConfig = entry.getValue().first(); if ( message.value().hasChildren( cookieConfig.strValue() ) ) { domain = cookieConfig.hasChildren( "domain" ) ? cookieConfig.getFirstChild( "domain" ).strValue() : ""; if ( domain.isEmpty() || hostname.endsWith( domain ) ) { cookieSB .append( entry.getKey() ) .append( '=' ) .append( message.value().getFirstChild( cookieConfig.strValue() ).strValue() ) .append( ";" ); } } } if ( cookieSB.length() > 0 ) { headerBuilder .append( "Cookie: " ) .append( cookieSB ) .append( CRLF ); } } } private void send_appendSetCookieHeader( CommMessage message, StringBuilder headerBuilder ) { Value cookieParam = null; if ( hasOperationSpecificParameter( message.operationName(), Parameters.COOKIES ) ) { cookieParam = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.COOKIES ); } else if ( hasParameter( Parameters.COOKIES ) ) { cookieParam = getParameterFirstValue( Parameters.COOKIES ); } if ( cookieParam != null ) { Value cookieConfig; for( Entry< String, ValueVector > entry : cookieParam.children().entrySet() ) { cookieConfig = entry.getValue().first(); if ( message.value().hasChildren( cookieConfig.strValue() ) ) { headerBuilder .append( "Set-Cookie: " ) .append( entry.getKey() ).append( '=' ) .append( message.value().getFirstChild( cookieConfig.strValue() ).strValue() ) .append( "; expires=" ) .append( cookieConfig.hasChildren( "expires" ) ? cookieConfig.getFirstChild( "expires" ).strValue() : "" ) .append( "; domain=" ) .append( cookieConfig.hasChildren( "domain" ) ? cookieConfig.getFirstChild( "domain" ).strValue() : "" ) .append( "; path=" ) .append( cookieConfig.hasChildren( "path" ) ? cookieConfig.getFirstChild( "path" ).strValue() : "" ); if ( cookieConfig.hasChildren( "secure" ) && cookieConfig.getFirstChild( "secure" ).intValue() > 0 ) { headerBuilder.append( "; secure" ); } headerBuilder.append( CRLF ); } } } } private String requestFormat = null; private void send_appendQuerystring( Value value, String charset, StringBuilder headerBuilder ) throws IOException { if ( value.children().isEmpty() == false ) { headerBuilder.append( '?' ); for( Entry< String, ValueVector > entry : value.children().entrySet() ) { headerBuilder .append( entry.getKey() ) .append( '=' ) .append( URLEncoder.encode( entry.getValue().first().strValue(), charset ) ) .append( '&' ); } } } private void send_appendParsedAlias( String alias, Value value, String charset, StringBuilder headerBuilder ) throws IOException { int offset = 0; String currStrValue; String currKey; StringBuilder result = new StringBuilder( alias ); Matcher m = Pattern.compile( "%(!)?\\{[^\\}]*\\}" ).matcher( alias ); while( m.find() ) { if ( m.group( 1 ) == null ) { // We have to use URLEncoder currKey = alias.substring( m.start() + 2, m.end() - 1 ); if ( "$".equals( currKey ) ) { currStrValue = URLEncoder.encode( value.strValue(), charset ); } else { currStrValue = URLEncoder.encode( value.getFirstChild( currKey ).strValue(), charset ); } } else { // We have to insert the string raw currKey = alias.substring( m.start() + 3, m.end() - 1 ); if ( "$".equals( currKey ) ) { currStrValue = value.strValue(); } else { currStrValue = value.getFirstChild( currKey ).strValue(); } } result.replace( m.start() + offset, m.end() + offset, currStrValue ); offset += currStrValue.length() - 3 - currKey.length(); } headerBuilder.append( result ); } private String getCharset() { String charset = "UTF-8"; if ( hasParameter( "charset" ) ) { charset = getStringParameter( "charset" ); } return charset; } private String send_getFormat() { String format = "xml"; if ( inInputPort && requestFormat != null ) { format = requestFormat; requestFormat = null; } else if ( hasParameter( "format" ) ) { format = getStringParameter( "format" ); } return format; } private static class EncodedContent { private ByteArray content = null; private String contentType = ""; private String contentDisposition = ""; } private EncodedContent send_encodeContent( CommMessage message, Method method, String charset, String format ) throws IOException { EncodedContent ret = new EncodedContent(); if ( inInputPort == false && method == Method.GET ) { // We are building a GET request return ret; } if ( "xml".equals( format ) ) { Document doc = docBuilder.newDocument(); Element root = doc.createElement( message.operationName() + (( inInputPort ) ? "Response" : "") ); doc.appendChild( root ); if ( message.isFault() ) { Element faultElement = doc.createElement( message.fault().faultName() ); root.appendChild( faultElement ); valueToDocument( message.fault().value(), faultElement, doc ); } else { valueToDocument( message.value(), root, doc ); } Source src = new DOMSource( doc ); ByteArrayOutputStream tmpStream = new ByteArrayOutputStream(); Result dest = new StreamResult( tmpStream ); try { transformer.transform( src, dest ); } catch( TransformerException e ) { throw new IOException( e ); } ret.content = new ByteArray( tmpStream.toByteArray() ); ret.contentType = "text/xml"; } else if ( "binary".equals( format ) ) { if ( message.value().isByteArray() ) { ret.content = (ByteArray) message.value().valueObject(); ret.contentType = "application/octet-stream"; } } else if ( "html".equals( format ) ) { ret.content = new ByteArray( message.value().strValue().getBytes( charset ) ); ret.contentType = "text/html"; } else if ( "multipart/form-data".equals( format ) ) { ret.contentType = "multipart/form-data; boundary=" + BOUNDARY; StringBuilder builder = new StringBuilder(); for( Entry< String, ValueVector > entry : message.value().children().entrySet() ) { if ( !entry.getKey().startsWith( "@" ) ) { builder.append( "--" ).append( BOUNDARY ).append( CRLF ); builder.append( "Content-Disposition: form-data; name=\"" ).append( entry.getKey() ).append( '\"' ).append( CRLF ).append( CRLF ); builder.append( entry.getValue().first().strValue() ).append( CRLF ); } } builder.append( "--" + BOUNDARY + "--" ); ret.content = new ByteArray( builder.toString().getBytes( charset ) ); } else if ( "x-www-form-urlencoded".equals( format ) ) { ret.contentType = "application/x-www-form-urlencoded"; Iterator< Entry< String, ValueVector > > it = message.value().children().entrySet().iterator(); Entry< String, ValueVector > entry; StringBuilder builder = new StringBuilder(); while( it.hasNext() ) { entry = it.next(); builder.append( entry.getKey() ) .append( "=" ) .append( URLEncoder.encode( entry.getValue().first().strValue(), "UTF-8" ) ); if ( it.hasNext() ) { builder.append( '&' ); } } ret.content = new ByteArray( builder.toString().getBytes( charset ) ); } else if ( "text/x-gwt-rpc".equals( format ) ) { ret.contentType = "text/x-gwt-rpc"; try { if ( message.isFault() ) { ret.content = new ByteArray( RPC.encodeResponseForFailure( JolieService.class.getMethods()[0], JolieGWTConverter.jolieToGwtFault( message.fault() ) ).getBytes( charset ) ); } else { joliex.gwt.client.Value v = new joliex.gwt.client.Value(); JolieGWTConverter.jolieToGwtValue( message.value(), v ); ret.content = new ByteArray( RPC.encodeResponseForSuccess( JolieService.class.getMethods()[0], v ).getBytes( charset ) ); } } catch( SerializationException e ) { throw new IOException( e ); } } else if ( "json".equals( format ) ) { ret.contentType = "application/json"; StringBuilder jsonStringBuilder = new StringBuilder(); JsonUtils.valueToJsonString( message.value(), jsonStringBuilder ); ret.content = new ByteArray( jsonStringBuilder.toString().getBytes( charset ) ); } return ret; } private void send_appendResponseHeaders( CommMessage message, StringBuilder headerBuilder ) { String redirect = getStringParameter( "redirect" ); if ( redirect.isEmpty() ) { headerBuilder.append( "HTTP/1.1 200 OK" + CRLF ); } else { headerBuilder.append( "HTTP/1.1 303 See Other" + CRLF ); headerBuilder.append( "Location: " + redirect + CRLF ); } send_appendSetCookieHeader( message, headerBuilder ); headerBuilder.append( "Server: JOLIE" ).append( CRLF ); StringBuilder cacheControlHeader = new StringBuilder(); if ( hasParameter( "cacheControl" ) ) { Value cacheControl = getParameterFirstValue( "cacheControl" ); if ( cacheControl.hasChildren( "maxAge" ) ) { cacheControlHeader.append( "max-age=" ).append( cacheControl.getFirstChild( "maxAge" ).intValue() ); } } if ( cacheControlHeader.length() > 0 ) { headerBuilder.append( "Cache-Control: " ).append( cacheControlHeader ).append( CRLF ); } } private void send_appendRequestMethod( Method method, StringBuilder headerBuilder ) { headerBuilder.append( method.id() ); } private void send_appendRequestPath( CommMessage message, Method method, StringBuilder headerBuilder, String charset ) throws IOException { if ( uri.getPath().length() < 1 || uri.getPath().charAt( 0 ) != '/' ) { headerBuilder.append( '/' ); } headerBuilder.append( uri.getPath() ); String alias = getOperationSpecificStringParameter( message.operationName(), Parameters.ALIAS ); if ( alias.isEmpty() ) { headerBuilder.append( message.operationName() ); } else { send_appendParsedAlias( alias, message.value(), charset, headerBuilder ); } if ( method == Method.GET ) { send_appendQuerystring( message.value(), charset, headerBuilder ); } } private static void send_appendAuthorizationHeader( CommMessage message, StringBuilder headerBuilder ) { if ( message.value().hasChildren( jolie.lang.Constants.Predefined.HTTP_BASIC_AUTHENTICATION.token().content() ) ) { Value v = message.value().getFirstChild( jolie.lang.Constants.Predefined.HTTP_BASIC_AUTHENTICATION.token().content() ); //String realm = v.getFirstChild( "realm" ).strValue(); String userpass = v.getFirstChild( "userid" ).strValue() + ":" + v.getFirstChild( "password" ).strValue(); sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder(); userpass = encoder.encode( userpass.getBytes() ); headerBuilder.append( "Authorization: Basic " ).append( userpass ).append( CRLF ); } } private Method send_getRequestMethod( CommMessage message ) throws IOException { try { Method method; if ( hasOperationSpecificParameter( message.operationName(), Parameters.METHOD ) ) { method = Method.fromString( getOperationSpecificStringParameter( message.operationName(), Parameters.METHOD ).toUpperCase() ); } else if ( hasParameter( Parameters.METHOD ) ) { method = Method.fromString( getStringParameter( Parameters.METHOD ).toUpperCase() ); } else { method = Method.POST; } return method; } catch( Method.UnsupportedMethodException e ) { throw new IOException( e ); } } private void send_appendRequestHeaders( CommMessage message, Method method, StringBuilder headerBuilder, String charset ) throws IOException { send_appendRequestMethod( method, headerBuilder ); headerBuilder.append( ' ' ); send_appendRequestPath( message, method, headerBuilder, charset ); headerBuilder.append( " HTTP/1.1" + CRLF ); headerBuilder.append( "Host: " + uri.getHost() + CRLF ); send_appendCookies( message, uri.getHost(), headerBuilder ); send_appendAuthorizationHeader( message, headerBuilder ); } private void send_appendGenericHeaders( CommMessage message, EncodedContent encodedContent, String charset, StringBuilder headerBuilder ) { String param; if ( checkBooleanParameter( "keepAlive" ) == false || channel().toBeClosed() ) { channel().setToBeClosed( true ); headerBuilder.append( "Connection: close" + CRLF ); } if ( checkBooleanParameter( Parameters.CONCURRENT ) ) { headerBuilder.append( Headers.JOLIE_MESSAGE_ID ).append( ": " ).append( message.id() ).append( CRLF ); } if ( encodedContent.content != null ) { String contentType = getStringParameter( "contentType" ); if ( contentType.length() > 0 ) { encodedContent.contentType = contentType; } headerBuilder.append( "Content-Type: " + encodedContent.contentType ); if ( charset != null ) { headerBuilder.append( "; charset=" + charset.toLowerCase() ); } headerBuilder.append( CRLF ); param = getStringParameter( "contentTransferEncoding" ); if ( !param.isEmpty() ) { headerBuilder.append( "Content-Transfer-Encoding: " + param + CRLF ); } String contentDisposition = getStringParameter( "contentDisposition" ); if ( contentDisposition.length() > 0 ) { encodedContent.contentDisposition = contentDisposition; headerBuilder.append( "Content-Disposition: " + encodedContent.contentDisposition + CRLF ); } headerBuilder.append( "Content-Length: " + (encodedContent.content.size() + 2) + CRLF ); } else { headerBuilder.append( "Content-Length: 0" + CRLF ); } } private void send_logDebugInfo( CharSequence header, EncodedContent encodedContent ) { if ( checkBooleanParameter( "debug" ) ) { StringBuilder debugSB = new StringBuilder(); debugSB.append( "[HTTP debug] Sending:\n" ); debugSB.append( header ); if ( getParameterVector( "debug" ).first().getFirstChild( "showContent" ).intValue() > 0 && encodedContent.content != null ) { debugSB.append( encodedContent.content.toString() ); } Interpreter.getInstance().logInfo( debugSB.toString() ); } } public void send( OutputStream ostream, CommMessage message, InputStream istream ) throws IOException { Method method = send_getRequestMethod( message ); String charset = getCharset(); String format = send_getFormat(); EncodedContent encodedContent = send_encodeContent( message, method, charset, format ); StringBuilder headerBuilder = new StringBuilder(); if ( inInputPort ) { // We're responding to a request send_appendResponseHeaders( message, headerBuilder ); } else { // We're sending a notification or a solicit send_appendRequestHeaders( message, method, headerBuilder, charset ); } send_appendGenericHeaders( message, encodedContent, charset, headerBuilder ); headerBuilder.append( CRLF ); send_logDebugInfo( headerBuilder, encodedContent ); inputId = message.operationName(); /*if ( charset == null ) { charset = "UTF8"; }*/ ostream.write( headerBuilder.toString().getBytes( charset ) ); if ( encodedContent.content != null ) { ostream.write( encodedContent.content.getBytes() ); ostream.write( CRLF.getBytes( charset ) ); } } private void parseXML( HttpMessage message, Value value ) throws IOException { try { if ( message.size() > 0 ) { DocumentBuilder builder = docBuilderFactory.newDocumentBuilder(); InputSource src = new InputSource( new ByteArrayInputStream( message.content() ) ); Document doc = builder.parse( src ); XmlUtils.documentToValue( doc, value ); } } catch( ParserConfigurationException pce ) { throw new IOException( pce ); } catch( SAXException saxe ) { throw new IOException( saxe ); } } private static void parseJson( HttpMessage message, Value value ) throws IOException { JsonUtils.parseJsonIntoValue( new InputStreamReader( new ByteArrayInputStream( message.content() ) ), value ); } private static void parseForm( HttpMessage message, Value value, String charset ) throws IOException { String line = new String( message.content(), "UTF8" ); String[] s, pair; s = line.split( "&" ); for( int i = 0; i < s.length; i++ ) { pair = s[i].split( "=", 2 ); value.getChildren( pair[0] ).first().setValue( URLDecoder.decode( pair[1], charset ) ); } } private void parseMultiPartFormData( HttpMessage message, Value value ) throws IOException { multiPartFormDataParser = new MultiPartFormDataParser( message, value ); multiPartFormDataParser.parse(); } private static String parseGWTRPC( HttpMessage message, Value value ) throws IOException { RPCRequest request = RPC.decodeRequest( new String( message.content(), "UTF8" ) ); String operationName = (String)request.getParameters()[0]; joliex.gwt.client.Value requestValue = (joliex.gwt.client.Value)request.getParameters()[1]; JolieGWTConverter.gwtToJolieValue( requestValue, value ); return operationName; } private void recv_checkForSetCookie( HttpMessage message, Value value ) throws IOException { if ( hasParameter( Parameters.COOKIES ) ) { String type; Value cookies = getParameterFirstValue( Parameters.COOKIES ); Value cookieConfig; Value v; for( HttpMessage.Cookie cookie : message.setCookies() ) { if ( cookies.hasChildren( cookie.name() ) ) { cookieConfig = cookies.getFirstChild( cookie.name() ); if ( cookieConfig.isString() ) { v = value.getFirstChild( cookieConfig.strValue() ); if ( cookieConfig.hasChildren( "type" ) ) { type = cookieConfig.getFirstChild( "type" ).strValue(); } else { type = "string"; } recv_assignCookieValue( cookie.value(), v, type ); } } /*currValue = Value.create(); currValue.getNewChild( "expires" ).setValue( cookie.expirationDate() ); currValue.getNewChild( "path" ).setValue( cookie.path() ); currValue.getNewChild( "name" ).setValue( cookie.name() ); currValue.getNewChild( "value" ).setValue( cookie.value() ); currValue.getNewChild( "domain" ).setValue( cookie.domain() ); currValue.getNewChild( "secure" ).setValue( (cookie.secure() ? 1 : 0) ); cookieVec.add( currValue );*/ } } } private void recv_assignCookieValue( String cookieValue, Value value, String typeKeyword ) throws IOException { NativeType type = NativeType.fromString( typeKeyword ); if ( NativeType.INT == type ) { try { value.setValue( new Integer( cookieValue ) ); } catch( NumberFormatException e ) { throw new IOException( e ); } } else if ( NativeType.LONG == type ) { try { value.setValue( new Long( cookieValue ) ); } catch( NumberFormatException e ) { throw new IOException( e ); } } else if ( NativeType.STRING == type ) { value.setValue( cookieValue ); } else if ( NativeType.DOUBLE == type ) { try { value.setValue( new Double( cookieValue ) ); } catch( NumberFormatException e ) { throw new IOException( e ); } } else if ( NativeType.BOOL == type ) { value.setValue( Boolean.valueOf( cookieValue ) ); } else { value.setValue( cookieValue ); } } private void recv_checkForCookies( HttpMessage message, DecodedMessage decodedMessage ) throws IOException { Value cookies = null; if ( hasOperationSpecificParameter( decodedMessage.operationName, Parameters.COOKIES ) ) { cookies = getOperationSpecificParameterFirstValue( decodedMessage.operationName, Parameters.COOKIES ); } else if ( hasParameter( Parameters.COOKIES ) ) { cookies = getParameterFirstValue( Parameters.COOKIES ); } if ( cookies != null ) { Value v; String type; for( Entry< String, String > entry : message.cookies().entrySet() ) { if ( cookies.hasChildren( entry.getKey() ) ) { Value cookieConfig = cookies.getFirstChild( entry.getKey() ); if ( cookieConfig.isString() ) { v = decodedMessage.value.getFirstChild( cookieConfig.strValue() ); if ( cookieConfig.hasChildren( "type" ) ) { type = cookieConfig.getFirstChild( "type" ).strValue(); } else { type = "string"; } recv_assignCookieValue( entry.getValue(), v, type ); } } } } } private static void recv_parseQueryString( HttpMessage message, Value value ) { String queryString = message.requestPath() == null ? "" : message.requestPath(); String[] kv = queryString.split( "\\?" ); if ( kv.length > 1 ) { queryString = kv[1]; String[] params = queryString.split( "&" ); for( String param : params ) { kv = param.split( "=", 2 ); if ( kv.length > 1 ) { value.getFirstChild( kv[0] ).setValue( kv[1] ); } } } } /* * Prints debug information about a received message */ private void recv_logDebugInfo( HttpMessage message ) { StringBuilder debugSB = new StringBuilder(); debugSB.append( "[HTTP debug] Receiving:\n" ); debugSB.append( "HTTP Code: " + message.httpCode() + "\n" ); debugSB.append( "Resource: " + message.requestPath() + "\n" ); debugSB.append( "--> Header properties\n" ); for( Entry< String, String > entry : message.properties() ) { debugSB.append( '\t' + entry.getKey() + ": " + entry.getValue() + '\n' ); } for( HttpMessage.Cookie cookie : message.setCookies() ) { debugSB.append( "\tset-cookie: " + cookie.toString() + '\n' ); } for( Entry< String, String > entry : message.cookies().entrySet() ) { debugSB.append( "\tcookie: " + entry.getKey() + '=' + entry.getValue() + '\n' ); } if ( getParameterFirstValue( "debug" ).getFirstChild( "showContent" ).intValue() > 0 && message.content() != null ) { debugSB.append( "--> Message content\n" ); debugSB.append( new String( message.content() ) ); } Interpreter.getInstance().logInfo( debugSB.toString() ); } private void recv_parseMessage( HttpMessage message, DecodedMessage decodedMessage, String charset ) throws IOException { requestFormat = null; String format = "xml"; if ( hasParameter( "format" ) ) { format = getStringParameter( "format" ); } String type = message.getProperty( "content-type" ).split( ";" )[0]; if ( "text/html".equals( type ) ) { decodedMessage.value.setValue( new String( message.content() ) ); } else if ( "application/x-www-form-urlencoded".equals( type ) ) { parseForm( message, decodedMessage.value, charset ); } else if ( "text/xml".equals( type ) ) { parseXML( message, decodedMessage.value ); } else if ( "text/x-gwt-rpc".equals( type ) ) { decodedMessage.operationName = parseGWTRPC( message, decodedMessage.value ); requestFormat = "text/x-gwt-rpc"; } else if ( "multipart/form-data".equals( type ) ) { parseMultiPartFormData( message, decodedMessage.value ); } else if ( "application/octet-stream".equals( type ) ) { decodedMessage.value.setValue( new ByteArray( message.content() ) ); } else if ( "application/json".equals( type ) ) { parseJson( message, decodedMessage.value ); } else if ( "xml".equals( format ) || "rest".equals( format ) ) { parseXML( message, decodedMessage.value ); } else if ( "json".equals( format ) ) { parseJson( message, decodedMessage.value ); } else { decodedMessage.value.setValue( new String( message.content() ) ); } } private void recv_checkReceivingOperation( HttpMessage message, DecodedMessage decodedMessage ) { if ( decodedMessage.operationName == null ) { String requestPath = message.requestPath().split( "\\?" )[0]; decodedMessage.operationName = requestPath; Matcher m = LocationParser.RESOURCE_SEPARATOR_PATTERN.matcher( decodedMessage.operationName ); if ( m.find() ) { int resourceStart = m.end(); if ( m.find() ) { decodedMessage.resourcePath = requestPath.substring( resourceStart - 1, m.start() ); decodedMessage.operationName = requestPath.substring( m.end(), requestPath.length() ); } } } if ( decodedMessage.resourcePath.equals( "/" ) && !channel().parentInputPort().canHandleInputOperation( decodedMessage.operationName ) ) { String defaultOpId = getStringParameter( "default" ); if ( defaultOpId.length() > 0 ) { Value body = decodedMessage.value; decodedMessage.value = Value.create(); decodedMessage.value.getChildren( "data" ).add( body ); decodedMessage.value.getFirstChild( "operation" ).setValue( decodedMessage.operationName ); Value cookies = decodedMessage.value.getFirstChild( "cookies" ); for( Entry< String, String > cookie : message.cookies().entrySet() ) { cookies.getFirstChild( cookie.getKey() ).setValue( cookie.getValue() ); } decodedMessage.operationName = defaultOpId; } } } private void recv_checkForMultiPartHeaders( DecodedMessage decodedMessage ) { if ( multiPartFormDataParser != null ) { String target; for( Entry< String, MultiPartFormDataParser.PartProperties > entry : multiPartFormDataParser.getPartPropertiesSet() ) { if ( entry.getValue().filename() != null ) { target = getMultipartHeaderForPart( decodedMessage.operationName, entry.getKey() ); if ( target != null ) { decodedMessage.value.getFirstChild( target ).setValue( entry.getValue().filename() ); } } } multiPartFormDataParser = null; } } private void recv_checkForMessageProperties( HttpMessage message, DecodedMessage decodedMessage ) throws IOException { recv_checkForCookies( message, decodedMessage ); recv_checkForMultiPartHeaders( decodedMessage );// message, decodedMessage ); String property; if ( (property=message.getProperty( "user-agent" )) != null && hasParameter( "userAgent" ) ) { getParameterFirstValue( "userAgent" ).setValue( property ); } } private static class DecodedMessage { private String operationName = null; private Value value = Value.create(); private String resourcePath = "/"; private long id = CommMessage.GENERIC_ID; } public CommMessage recv( InputStream istream, OutputStream ostream ) throws IOException { CommMessage retVal = null; DecodedMessage decodedMessage = new DecodedMessage(); HttpMessage message = new HttpParser( istream ).parse(); if ( message.isSupported() == false ) { ostream.write( NOT_IMPLEMENTED_HEADER ); ostream.write( CRLF.getBytes() ); ostream.write( CRLF.getBytes() ); ostream.flush(); return null; } String charset = getCharset(); if ( message.getProperty( "connection" ) != null ) { HttpUtils.recv_checkForChannelClosing( message, channel() ); } else if ( hasParameter( "keepAlive" ) ) { channel().setToBeClosed( checkBooleanParameter( "keepAlive" ) == false ); } if ( checkBooleanParameter( Parameters.DEBUG ) ) { recv_logDebugInfo( message ); } if ( message.size() > 0 ) { recv_parseMessage( message, decodedMessage, charset ); } if ( checkBooleanParameter( Parameters.CONCURRENT ) ) { String messageId = message.getProperty( Headers.JOLIE_MESSAGE_ID ); if ( messageId != null ) { try { decodedMessage.id = Long.parseLong( messageId ); } catch( NumberFormatException e ) {} } } if ( message.isResponse() ) { recv_checkForSetCookie( message, decodedMessage.value ); retVal = new CommMessage( decodedMessage.id, inputId, decodedMessage.resourcePath, decodedMessage.value, null ); } else if ( message.isError() == false ) { if ( message.isGet() ) { recv_parseQueryString( message, decodedMessage.value ); } recv_checkReceivingOperation( message, decodedMessage ); recv_checkForMessageProperties( message, decodedMessage ); retVal = new CommMessage( decodedMessage.id, decodedMessage.operationName, decodedMessage.resourcePath, decodedMessage.value, null ); } if ( "/".equals( retVal.resourcePath() ) && channel().parentPort() != null && channel().parentPort().getInterface().containsOperation( retVal.operationName() ) ) { try { // The message is for this service Interface iface = channel().parentPort().getInterface(); OneWayTypeDescription oneWayTypeDescription = iface.oneWayOperations().get( retVal.operationName() ); if ( oneWayTypeDescription != null && message.isResponse() == false ) { // We are receiving a One-Way message oneWayTypeDescription.requestType().cast( retVal.value() ); } else { RequestResponseTypeDescription rrTypeDescription = iface.requestResponseOperations().get( retVal.operationName() ); if ( retVal.isFault() ) { Type faultType = rrTypeDescription.faults().get( retVal.fault().faultName() ); if ( faultType != null ) { faultType.cast( retVal.value() ); } } else { if ( message.isResponse() ) { rrTypeDescription.responseType().cast( retVal.value() ); } else { rrTypeDescription.requestType().cast( retVal.value() ); } } } } catch( TypeCastingException e ) { // TODO: do something here? } } return retVal; } }
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ package processing.app; import processing.app.debug.*; import processing.app.syntax.*; import processing.app.tools.*; import processing.core.*; import static processing.app.I18n._; import java.awt.*; import java.awt.datatransfer.*; import java.awt.event.*; import java.awt.print.*; import java.io.*; import java.net.*; import java.util.*; import java.util.zip.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.text.*; import javax.swing.undo.*; import gnu.io.*; /** * Main editor panel for the Processing Development Environment. */ @SuppressWarnings("serial") public class Editor extends JFrame implements RunnerListener { Base base; // otherwise, if the window is resized with the message label // set to blank, it's preferredSize() will be fukered static protected final String EMPTY = " " + " " + " "; /** Command on Mac OS X, Ctrl on Windows and Linux */ static final int SHORTCUT_KEY_MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); /** Command-W on Mac OS X, Ctrl-W on Windows and Linux */ static final KeyStroke WINDOW_CLOSE_KEYSTROKE = KeyStroke.getKeyStroke('W', SHORTCUT_KEY_MASK); /** Command-Option on Mac OS X, Ctrl-Alt on Windows and Linux */ static final int SHORTCUT_ALT_KEY_MASK = ActionEvent.ALT_MASK | Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); /** * true if this file has not yet been given a name by the user */ boolean untitled; PageFormat pageFormat; PrinterJob printerJob; // file, sketch, and tools menus for re-inserting items JMenu fileMenu; JMenu sketchMenu; JMenu toolsMenu; int numTools = 0; EditorToolbar toolbar; // these menus are shared so that they needn't be rebuilt for all windows // each time a sketch is created, renamed, or moved. static JMenu toolbarMenu; static JMenu sketchbookMenu; static JMenu examplesMenu; static JMenu importMenu; // these menus are shared so that the board and serial port selections // are the same for all windows (since the board and serial port that are // actually used are determined by the preferences, which are shared) static JMenu boardsMenu; static JMenu serialMenu; static SerialMenuListener serialMenuListener; static SerialMonitor serialMonitor; EditorHeader header; EditorStatus status; EditorConsole console; JSplitPane splitPane; JPanel consolePanel; JLabel lineNumberComponent; // currently opened program Sketch sketch; EditorLineStatus lineStatus; //JEditorPane editorPane; JEditTextArea textarea; EditorListener listener; // runtime information and window placement Point sketchWindowLocation; //Runner runtime; JMenuItem exportAppItem; JMenuItem saveMenuItem; JMenuItem saveAsMenuItem; boolean running; //boolean presenting; boolean uploading; // undo fellers JMenuItem undoItem, redoItem; protected UndoAction undoAction; protected RedoAction redoAction; UndoManager undo; // used internally, and only briefly CompoundEdit compoundEdit; FindReplace find; Runnable runHandler; Runnable presentHandler; Runnable stopHandler; Runnable exportHandler; Runnable exportAppHandler; public Editor(Base ibase, String path, int[] location) { super("Arduino"); this.base = ibase; Base.setIcon(this); // Install default actions for Run, Present, etc. resetHandlers(); // add listener to handle window close box hit event addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { base.handleClose(Editor.this); } }); // don't close the window when clicked, the app will take care // of that via the handleQuitInternal() methods setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // When bringing a window to front, let the Base know addWindowListener(new WindowAdapter() { public void windowActivated(WindowEvent e) { // System.err.println("activate"); // not coming through base.handleActivated(Editor.this); // re-add the sub-menus that are shared by all windows fileMenu.insert(sketchbookMenu, 2); fileMenu.insert(examplesMenu, 3); sketchMenu.insert(importMenu, 4); toolsMenu.insert(boardsMenu, numTools); toolsMenu.insert(serialMenu, numTools + 1); } // added for 1.0.5 public void windowDeactivated(WindowEvent e) { // System.err.println("deactivate"); // not coming through fileMenu.remove(sketchbookMenu); fileMenu.remove(examplesMenu); sketchMenu.remove(importMenu); toolsMenu.remove(boardsMenu); toolsMenu.remove(serialMenu); } }); //PdeKeywords keywords = new PdeKeywords(); //sketchbook = new Sketchbook(this); if (serialMonitor == null) { serialMonitor = new SerialMonitor(Preferences.get("serial.port")); serialMonitor.setIconImage(getIconImage()); } buildMenuBar(); // For rev 0120, placing things inside a JPanel Container contentPain = getContentPane(); contentPain.setLayout(new BorderLayout()); JPanel pain = new JPanel(); pain.setLayout(new BorderLayout()); contentPain.add(pain, BorderLayout.CENTER); Box box = Box.createVerticalBox(); Box upper = Box.createVerticalBox(); if (toolbarMenu == null) { toolbarMenu = new JMenu(); base.rebuildToolbarMenu(toolbarMenu); } toolbar = new EditorToolbar(this, toolbarMenu); upper.add(toolbar); header = new EditorHeader(this); upper.add(header); textarea = new JEditTextArea(new PdeTextAreaDefaults()); textarea.setRightClickPopup(new TextAreaPopup()); textarea.setHorizontalOffset(6); // assemble console panel, consisting of status area and the console itself consolePanel = new JPanel(); consolePanel.setLayout(new BorderLayout()); status = new EditorStatus(this); consolePanel.add(status, BorderLayout.NORTH); console = new EditorConsole(this); // windows puts an ugly border on this guy console.setBorder(null); consolePanel.add(console, BorderLayout.CENTER); lineStatus = new EditorLineStatus(textarea); consolePanel.add(lineStatus, BorderLayout.SOUTH); upper.add(textarea); splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, upper, consolePanel); splitPane.setOneTouchExpandable(true); // repaint child panes while resizing splitPane.setContinuousLayout(true); // if window increases in size, give all of increase to // the textarea in the uppper pane splitPane.setResizeWeight(1D); // to fix ugliness.. normally macosx java 1.3 puts an // ugly white border around this object, so turn it off. splitPane.setBorder(null); // the default size on windows is too small and kinda ugly int dividerSize = Preferences.getInteger("editor.divider.size"); if (dividerSize != 0) { splitPane.setDividerSize(dividerSize); } splitPane.setMinimumSize(new Dimension(600, 400)); box.add(splitPane); // hopefully these are no longer needed w/ swing // (har har har.. that was wishful thinking) listener = new EditorListener(this, textarea); pain.add(box); // get shift down/up events so we can show the alt version of toolbar buttons textarea.addKeyListener(toolbar); pain.setTransferHandler(new FileDropHandler()); // System.out.println("t1"); // Finish preparing Editor (formerly found in Base) pack(); // System.out.println("t2"); // Set the window bounds and the divider location before setting it visible setPlacement(location); // Set the minimum size for the editor window setMinimumSize(new Dimension(Preferences.getInteger("editor.window.width.min"), Preferences.getInteger("editor.window.height.min"))); // System.out.println("t3"); // Bring back the general options for the editor applyPreferences(); // System.out.println("t4"); // Open the document that was passed in boolean loaded = handleOpenInternal(path); if (!loaded) sketch = null; // System.out.println("t5"); // All set, now show the window //setVisible(true); } /** * Handles files dragged & dropped from the desktop and into the editor * window. Dragging files into the editor window is the same as using * "Sketch &rarr; Add File" for each file. */ class FileDropHandler extends TransferHandler { public boolean canImport(JComponent dest, DataFlavor[] flavors) { return true; } @SuppressWarnings("unchecked") public boolean importData(JComponent src, Transferable transferable) { int successful = 0; try { DataFlavor uriListFlavor = new DataFlavor("text/uri-list;class=java.lang.String"); if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { java.util.List list = (java.util.List) transferable.getTransferData(DataFlavor.javaFileListFlavor); for (int i = 0; i < list.size(); i++) { File file = (File) list.get(i); if (sketch.addFile(file)) { successful++; } } } else if (transferable.isDataFlavorSupported(uriListFlavor)) { // Some platforms (Mac OS X and Linux, when this began) preferred // this method of moving files. String data = (String)transferable.getTransferData(uriListFlavor); String[] pieces = PApplet.splitTokens(data, "\r\n"); for (int i = 0; i < pieces.length; i++) { if (pieces[i].startsWith("#")) continue; String path = null; if (pieces[i].startsWith("file: path = pieces[i].substring(7); } else if (pieces[i].startsWith("file:/")) { path = pieces[i].substring(5); } if (sketch.addFile(new File(path))) { successful++; } } } } catch (Exception e) { e.printStackTrace(); return false; } if (successful == 0) { statusError(_("No files were added to the sketch.")); } else if (successful == 1) { statusNotice(_("One file added to the sketch.")); } else { statusNotice( I18n.format(_("{0} files added to the sketch."), successful)); } return true; } } protected void setPlacement(int[] location) { setBounds(location[0], location[1], location[2], location[3]); if (location[4] != 0) { splitPane.setDividerLocation(location[4]); } } protected int[] getPlacement() { int[] location = new int[5]; // Get the dimensions of the Frame Rectangle bounds = getBounds(); location[0] = bounds.x; location[1] = bounds.y; location[2] = bounds.width; location[3] = bounds.height; // Get the current placement of the divider location[4] = splitPane.getDividerLocation(); return location; } /** * Hack for #@#)$(* Mac OS X 10.2. * <p/> * This appears to only be required on OS X 10.2, and is not * even being called on later versions of OS X or Windows. */ // public Dimension getMinimumSize() { // //System.out.println("getting minimum size"); // return new Dimension(500, 550); /** * Read and apply new values from the preferences, either because * the app is just starting up, or the user just finished messing * with things in the Preferences window. */ protected void applyPreferences() { // apply the setting for 'use external editor' boolean external = Preferences.getBoolean("editor.external"); textarea.setEditable(!external); saveMenuItem.setEnabled(!external); saveAsMenuItem.setEnabled(!external); TextAreaPainter painter = textarea.getPainter(); if (external) { // disable line highlight and turn off the caret when disabling Color color = Theme.getColor("editor.external.bgcolor"); painter.setBackground(color); painter.setLineHighlightEnabled(false); textarea.setCaretVisible(false); } else { Color color = Theme.getColor("editor.bgcolor"); painter.setBackground(color); boolean highlight = Preferences.getBoolean("editor.linehighlight"); painter.setLineHighlightEnabled(highlight); textarea.setCaretVisible(true); } // apply changes to the font size for the editor //TextAreaPainter painter = textarea.getPainter(); painter.setFont(Preferences.getFont("editor.font")); //Font font = painter.getFont(); //textarea.getPainter().setFont(new Font("Courier", Font.PLAIN, 36)); // in case tab expansion stuff has changed listener.applyPreferences(); // in case moved to a new location // For 0125, changing to async version (to be implemented later) //sketchbook.rebuildMenus(); // For 0126, moved into Base, which will notify all editors. //base.rebuildMenusAsync(); } protected void buildMenuBar() { JMenuBar menubar = new JMenuBar(); menubar = new JMenuBar(); menubar.add(buildFileMenu()); menubar.add(buildEditMenu()); menubar.add(buildSketchMenu()); menubar.add(buildToolsMenu()); menubar.add(buildHelpMenu()); setJMenuBar(menubar); } protected JMenu buildFileMenu() { JMenuItem item; fileMenu = new JMenu(_("File")); item = newJMenuItem(_("New"), 'N'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handleNew(); } }); fileMenu.add(item); item = Editor.newJMenuItem(_("Open..."), 'O'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handleOpenPrompt(); } }); fileMenu.add(item); if (sketchbookMenu == null) { sketchbookMenu = new JMenu(_("Sketchbook")); base.rebuildSketchbookMenu(sketchbookMenu); } fileMenu.add(sketchbookMenu); if (examplesMenu == null) { examplesMenu = new JMenu(_("Examples")); base.rebuildExamplesMenu(examplesMenu); } fileMenu.add(examplesMenu); item = Editor.newJMenuItem(_("Close"), 'W'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handleClose(Editor.this); } }); fileMenu.add(item); saveMenuItem = newJMenuItem(_("Save"), 'S'); saveMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSave(false); } }); fileMenu.add(saveMenuItem); saveAsMenuItem = newJMenuItemShift(_("Save As..."), 'S'); saveAsMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSaveAs(); } }); fileMenu.add(saveAsMenuItem); item = newJMenuItem(_("Upload"), 'U'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleExport(false); } }); fileMenu.add(item); item = newJMenuItemShift(_("Upload Using Programmer"), 'U'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleExport(true); } }); fileMenu.add(item); fileMenu.addSeparator(); item = newJMenuItemShift(_("Page Setup"), 'P'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePageSetup(); } }); fileMenu.add(item); item = newJMenuItem(_("Print"), 'P'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePrint(); } }); fileMenu.add(item); // macosx already has its own preferences and quit menu if (!Base.isMacOS()) { fileMenu.addSeparator(); item = newJMenuItem(_("Preferences"), ','); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handlePrefs(); } }); fileMenu.add(item); fileMenu.addSeparator(); item = newJMenuItem(_("Quit"), 'Q'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handleQuit(); } }); fileMenu.add(item); } return fileMenu; } protected JMenu buildSketchMenu() { JMenuItem item; sketchMenu = new JMenu(_("Sketch")); item = newJMenuItem(_("Verify / Compile"), 'R'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleRun(false); } }); sketchMenu.add(item); // item = newJMenuItemShift("Verify / Compile (verbose)", 'R'); // item.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent e) { // handleRun(true); // sketchMenu.add(item); // item = new JMenuItem("Stop"); // item.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent e) { // handleStop(); // sketchMenu.add(item); sketchMenu.addSeparator(); if (importMenu == null) { importMenu = new JMenu(_("Import Library...")); base.rebuildImportMenu(importMenu); } sketchMenu.add(importMenu); item = newJMenuItem(_("Show Sketch Folder"), 'K'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.openFolder(sketch.getFolder()); } }); sketchMenu.add(item); item.setEnabled(Base.openFolderAvailable()); item = new JMenuItem(_("Add File...")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { sketch.handleAddFile(); } }); sketchMenu.add(item); return sketchMenu; } protected JMenu buildToolsMenu() { toolsMenu = new JMenu(_("Tools")); JMenu menu = toolsMenu; JMenuItem item; addInternalTools(menu); item = newJMenuItemShift(_("Serial Monitor"), 'M'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSerial(); } }); menu.add(item); addTools(menu, Base.getToolsFolder()); File sketchbookTools = new File(Base.getSketchbookFolder(), "tools"); addTools(menu, sketchbookTools); menu.addSeparator(); numTools = menu.getItemCount(); // XXX: DAM: these should probably be implemented using the Tools plugin // API, if possible (i.e. if it supports custom actions, etc.) if (boardsMenu == null) { boardsMenu = new JMenu(_("Board")); base.rebuildBoardsMenu(boardsMenu); } menu.add(boardsMenu); if (serialMenuListener == null) serialMenuListener = new SerialMenuListener(); if (serialMenu == null) serialMenu = new JMenu(_("Serial Port")); populateSerialMenu(); menu.add(serialMenu); menu.addSeparator(); JMenu programmerMenu = new JMenu(_("Programmer")); base.rebuildProgrammerMenu(programmerMenu); menu.add(programmerMenu); item = new JMenuItem(_("Burn Bootloader")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleBurnBootloader(); } }); menu.add(item); menu.addMenuListener(new MenuListener() { public void menuCanceled(MenuEvent e) {} public void menuDeselected(MenuEvent e) {} public void menuSelected(MenuEvent e) { //System.out.println("Tools menu selected."); populateSerialMenu(); } }); return menu; } protected void addTools(JMenu menu, File sourceFolder) { HashMap<String, JMenuItem> toolItems = new HashMap<String, JMenuItem>(); File[] folders = sourceFolder.listFiles(new FileFilter() { public boolean accept(File folder) { if (folder.isDirectory()) { //System.out.println("checking " + folder); File subfolder = new File(folder, "tool"); return subfolder.exists(); } return false; } }); if (folders == null || folders.length == 0) { return; } for (int i = 0; i < folders.length; i++) { File toolDirectory = new File(folders[i], "tool"); try { // add dir to classpath for .classes //urlList.add(toolDirectory.toURL()); // add .jar files to classpath File[] archives = toolDirectory.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return (name.toLowerCase().endsWith(".jar") || name.toLowerCase().endsWith(".zip")); } }); URL[] urlList = new URL[archives.length]; for (int j = 0; j < urlList.length; j++) { urlList[j] = archives[j].toURI().toURL(); } URLClassLoader loader = new URLClassLoader(urlList); String className = null; for (int j = 0; j < archives.length; j++) { className = findClassInZipFile(folders[i].getName(), archives[j]); if (className != null) break; } // If no class name found, just move on. if (className == null) continue; Class<?> toolClass = Class.forName(className, true, loader); final Tool tool = (Tool) toolClass.newInstance(); tool.init(Editor.this); String title = tool.getMenuTitle(); JMenuItem item = new JMenuItem(title); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(tool); //new Thread(tool).start(); } }); //menu.add(item); toolItems.put(title, item); } catch (Exception e) { e.printStackTrace(); } } ArrayList<String> toolList = new ArrayList<String>(toolItems.keySet()); if (toolList.size() == 0) return; menu.addSeparator(); Collections.sort(toolList); for (String title : toolList) { menu.add((JMenuItem) toolItems.get(title)); } } protected String findClassInZipFile(String base, File file) { // Class file to search for String classFileName = "/" + base + ".class"; try { ZipFile zipFile = new ZipFile(file); Enumeration<?> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (!entry.isDirectory()) { String name = entry.getName(); //System.out.println("entry: " + name); if (name.endsWith(classFileName)) { //int slash = name.lastIndexOf('/'); //String packageName = (slash == -1) ? "" : name.substring(0, slash); // Remove .class and convert slashes to periods. return name.substring(0, name.length() - 6).replace('/', '.'); } } } } catch (IOException e) { //System.err.println("Ignoring " + filename + " (" + e.getMessage() + ")"); e.printStackTrace(); } return null; } protected JMenuItem createToolMenuItem(String className) { try { Class<?> toolClass = Class.forName(className); final Tool tool = (Tool) toolClass.newInstance(); JMenuItem item = new JMenuItem(tool.getMenuTitle()); tool.init(Editor.this); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(tool); } }); return item; } catch (Exception e) { e.printStackTrace(); return null; } } protected JMenu addInternalTools(JMenu menu) { JMenuItem item; item = createToolMenuItem("processing.app.tools.AutoFormat"); int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); item.setAccelerator(KeyStroke.getKeyStroke('T', modifiers)); menu.add(item); //menu.add(createToolMenuItem("processing.app.tools.CreateFont")); //menu.add(createToolMenuItem("processing.app.tools.ColorSelector")); menu.add(createToolMenuItem("processing.app.tools.Archiver")); menu.add(createToolMenuItem("processing.app.tools.FixEncoding")); // // These are temporary entries while Android mode is being worked out. // // The mode will not be in the tools menu, and won't involve a cmd-key // if (!Base.RELEASE) { // item = createToolMenuItem("processing.app.tools.android.AndroidTool"); // item.setAccelerator(KeyStroke.getKeyStroke('D', modifiers)); // menu.add(item); // menu.add(createToolMenuItem("processing.app.tools.android.Reset")); return menu; } class SerialMenuListener implements ActionListener { //public SerialMenuListener() { } public void actionPerformed(ActionEvent e) { selectSerialPort(((JCheckBoxMenuItem)e.getSource()).getText()); base.onBoardOrPortChange(); } /* public void actionPerformed(ActionEvent e) { System.out.println(e.getSource()); String name = e.getActionCommand(); PdeBase.properties.put("serial.port", name); System.out.println("set to " + get("serial.port")); //editor.skOpen(path + File.separator + name, name); // need to push "serial.port" into PdeBase.properties } */ } protected void selectSerialPort(String name) { if(serialMenu == null) { System.out.println(_("serialMenu is null")); return; } if (name == null) { System.out.println(_("name is null")); return; } JCheckBoxMenuItem selection = null; for (int i = 0; i < serialMenu.getItemCount(); i++) { JCheckBoxMenuItem item = ((JCheckBoxMenuItem)serialMenu.getItem(i)); if (item == null) { System.out.println(_("name is null")); continue; } item.setState(false); if (name.equals(item.getText())) selection = item; } if (selection != null) selection.setState(true); //System.out.println(item.getLabel()); Preferences.set("serial.port", name); serialMonitor.closeSerialPort(); serialMonitor.setVisible(false); serialMonitor = new SerialMonitor(Preferences.get("serial.port")); //System.out.println("set to " + get("serial.port")); } protected void populateSerialMenu() { // getting list of ports JMenuItem rbMenuItem; //System.out.println("Clearing serial port menu."); serialMenu.removeAll(); boolean empty = true; try { for (Enumeration enumeration = CommPortIdentifier.getPortIdentifiers(); enumeration.hasMoreElements();) { CommPortIdentifier commportidentifier = (CommPortIdentifier)enumeration.nextElement(); //System.out.println("Found communication port: " + commportidentifier); if (commportidentifier.getPortType() == CommPortIdentifier.PORT_SERIAL) { //System.out.println("Adding port to serial port menu: " + commportidentifier); String curr_port = commportidentifier.getName(); rbMenuItem = new JCheckBoxMenuItem(curr_port, curr_port.equals(Preferences.get("serial.port"))); rbMenuItem.addActionListener(serialMenuListener); //serialGroup.add(rbMenuItem); serialMenu.add(rbMenuItem); empty = false; } } if (!empty) { //System.out.println("enabling the serialMenu"); serialMenu.setEnabled(true); } } catch (Exception exception) { System.out.println(_("error retrieving port list")); exception.printStackTrace(); } if (serialMenu.getItemCount() == 0) { serialMenu.setEnabled(false); } //serialMenu.addSeparator(); //serialMenu.add(item); } protected JMenu buildHelpMenu() { // To deal with a Mac OS X 10.5 bug, add an extra space after the name // so that the OS doesn't try to insert its slow help menu. JMenu menu = new JMenu(_("Help")); JMenuItem item; item = new JMenuItem(_("Getting Started")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showGettingStarted(); } }); menu.add(item); item = new JMenuItem(_("Environment")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showEnvironment(); } }); menu.add(item); item = new JMenuItem(_("Troubleshooting")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showTroubleshooting(); } }); menu.add(item); item = new JMenuItem(_("Reference")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showReference(); } }); menu.add(item); item = newJMenuItemShift(_("Find in Reference"), 'F'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (textarea.isSelectionActive()) { handleFindReference(); } } }); menu.add(item); item = new JMenuItem(_("Frequently Asked Questions")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showFAQ(); } }); menu.add(item); item = new JMenuItem(_("Visit Arduino.cc")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.openURL(_("http://arduino.cc/")); } }); menu.add(item); // macosx already has its own about menu if (!Base.isMacOS()) { menu.addSeparator(); item = new JMenuItem(_("About Arduino")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handleAbout(); } }); menu.add(item); } return menu; } protected JMenu buildEditMenu() { JMenu menu = new JMenu(_("Edit")); JMenuItem item; undoItem = newJMenuItem(_("Undo"), 'Z'); undoItem.addActionListener(undoAction = new UndoAction()); menu.add(undoItem); redoItem = newJMenuItem(_("Redo"), 'Y'); redoItem.addActionListener(redoAction = new RedoAction()); menu.add(redoItem); menu.addSeparator(); // TODO "cut" and "copy" should really only be enabled // if some text is currently selected item = newJMenuItem(_("Cut"), 'X'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleCut(); } }); menu.add(item); item = newJMenuItem(_("Copy"), 'C'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.copy(); } }); menu.add(item); item = newJMenuItemShift(_("Copy for Forum"), 'C'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // SwingUtilities.invokeLater(new Runnable() { // public void run() { new DiscourseFormat(Editor.this, false).show(); } }); menu.add(item); item = newJMenuItemAlt(_("Copy as HTML"), 'C'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // SwingUtilities.invokeLater(new Runnable() { // public void run() { new DiscourseFormat(Editor.this, true).show(); } }); menu.add(item); item = newJMenuItem(_("Paste"), 'V'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.paste(); sketch.setModified(true); } }); menu.add(item); item = newJMenuItem(_("Select All"), 'A'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.selectAll(); } }); menu.add(item); menu.addSeparator(); item = newJMenuItem(_("Comment/Uncomment"), '/'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleCommentUncomment(); } }); menu.add(item); item = newJMenuItem(_("Increase Indent"), ']'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleIndentOutdent(true); } }); menu.add(item); item = newJMenuItem(_("Decrease Indent"), '['); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleIndentOutdent(false); } }); menu.add(item); menu.addSeparator(); item = newJMenuItem(_("Find..."), 'F'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (find == null) { find = new FindReplace(Editor.this); } //new FindReplace(Editor.this).show(); find.setVisible(true); //find.setVisible(true); } }); menu.add(item); // TODO find next should only be enabled after a // search has actually taken place item = newJMenuItem(_("Find Next"), 'G'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (find != null) { //find.find(true); //FindReplace find = new FindReplace(Editor.this); //.show(); find.find(true); } } }); menu.add(item); return menu; } /** * A software engineer, somewhere, needs to have his abstraction * taken away. In some countries they jail or beat people for writing * the sort of API that would require a five line helper function * just to set the command key for a menu item. */ static public JMenuItem newJMenuItem(String title, int what) { JMenuItem menuItem = new JMenuItem(title); int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); menuItem.setAccelerator(KeyStroke.getKeyStroke(what, modifiers)); return menuItem; } /** * Like newJMenuItem() but adds shift as a modifier for the key command. */ static public JMenuItem newJMenuItemShift(String title, int what) { JMenuItem menuItem = new JMenuItem(title); int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); modifiers |= ActionEvent.SHIFT_MASK; menuItem.setAccelerator(KeyStroke.getKeyStroke(what, modifiers)); return menuItem; } /** * Same as newJMenuItem(), but adds the ALT (on Linux and Windows) * or OPTION (on Mac OS X) key as a modifier. */ static public JMenuItem newJMenuItemAlt(String title, int what) { JMenuItem menuItem = new JMenuItem(title); //int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); //menuItem.setAccelerator(KeyStroke.getKeyStroke(what, modifiers)); menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_ALT_KEY_MASK)); return menuItem; } class UndoAction extends AbstractAction { public UndoAction() { super("Undo"); this.setEnabled(false); } public void actionPerformed(ActionEvent e) { try { undo.undo(); } catch (CannotUndoException ex) { //System.out.println("Unable to undo: " + ex); //ex.printStackTrace(); } updateUndoState(); redoAction.updateRedoState(); } protected void updateUndoState() { if (undo.canUndo()) { this.setEnabled(true); undoItem.setEnabled(true); undoItem.setText(undo.getUndoPresentationName()); putValue(Action.NAME, undo.getUndoPresentationName()); if (sketch != null) { sketch.setModified(true); // 0107 } } else { this.setEnabled(false); undoItem.setEnabled(false); undoItem.setText(_("Undo")); putValue(Action.NAME, "Undo"); if (sketch != null) { sketch.setModified(false); // 0107 } } } } class RedoAction extends AbstractAction { public RedoAction() { super("Redo"); this.setEnabled(false); } public void actionPerformed(ActionEvent e) { try { undo.redo(); } catch (CannotRedoException ex) { //System.out.println("Unable to redo: " + ex); //ex.printStackTrace(); } updateRedoState(); undoAction.updateUndoState(); } protected void updateRedoState() { if (undo.canRedo()) { redoItem.setEnabled(true); redoItem.setText(undo.getRedoPresentationName()); putValue(Action.NAME, undo.getRedoPresentationName()); } else { this.setEnabled(false); redoItem.setEnabled(false); redoItem.setText(_("Redo")); putValue(Action.NAME, "Redo"); } } } // these will be done in a more generic way soon, more like: // setHandler("action name", Runnable); // but for the time being, working out the kinks of how many things to // abstract from the editor in this fashion. public void setHandlers(Runnable runHandler, Runnable presentHandler, Runnable stopHandler, Runnable exportHandler, Runnable exportAppHandler) { this.runHandler = runHandler; this.presentHandler = presentHandler; this.stopHandler = stopHandler; this.exportHandler = exportHandler; this.exportAppHandler = exportAppHandler; } public void resetHandlers() { runHandler = new DefaultRunHandler(); presentHandler = new DefaultPresentHandler(); stopHandler = new DefaultStopHandler(); exportHandler = new DefaultExportHandler(); exportAppHandler = new DefaultExportAppHandler(); } /** * Gets the current sketch object. */ public Sketch getSketch() { return sketch; } /** * Get the JEditTextArea object for use (not recommended). This should only * be used in obscure cases that really need to hack the internals of the * JEditTextArea. Most tools should only interface via the get/set functions * found in this class. This will maintain compatibility with future releases, * which will not use JEditTextArea. */ public JEditTextArea getTextArea() { return textarea; } /** * Get the contents of the current buffer. Used by the Sketch class. */ public String getText() { return textarea.getText(); } /** * Get a range of text from the current buffer. */ public String getText(int start, int stop) { return textarea.getText(start, stop - start); } /** * Replace the entire contents of the front-most tab. */ public void setText(String what) { startCompoundEdit(); textarea.setText(what); stopCompoundEdit(); } public void insertText(String what) { startCompoundEdit(); int caret = getCaretOffset(); setSelection(caret, caret); textarea.setSelectedText(what); stopCompoundEdit(); } /** * Called to update the text but not switch to a different set of code * (which would affect the undo manager). */ // public void setText2(String what, int start, int stop) { // beginCompoundEdit(); // textarea.setText(what); // endCompoundEdit(); // // make sure that a tool isn't asking for a bad location // start = Math.max(0, Math.min(start, textarea.getDocumentLength())); // stop = Math.max(0, Math.min(start, textarea.getDocumentLength())); // textarea.select(start, stop); // textarea.requestFocus(); // get the caret blinking public String getSelectedText() { return textarea.getSelectedText(); } public void setSelectedText(String what) { textarea.setSelectedText(what); } public void setSelection(int start, int stop) { // make sure that a tool isn't asking for a bad location start = PApplet.constrain(start, 0, textarea.getDocumentLength()); stop = PApplet.constrain(stop, 0, textarea.getDocumentLength()); textarea.select(start, stop); } /** * Get the position (character offset) of the caret. With text selected, * this will be the last character actually selected, no matter the direction * of the selection. That is, if the user clicks and drags to select lines * 7 up to 4, then the caret position will be somewhere on line four. */ public int getCaretOffset() { return textarea.getCaretPosition(); } /** * True if some text is currently selected. */ public boolean isSelectionActive() { return textarea.isSelectionActive(); } /** * Get the beginning point of the current selection. */ public int getSelectionStart() { return textarea.getSelectionStart(); } /** * Get the end point of the current selection. */ public int getSelectionStop() { return textarea.getSelectionStop(); } /** * Get text for a specified line. */ public String getLineText(int line) { return textarea.getLineText(line); } /** * Replace the text on a specified line. */ public void setLineText(int line, String what) { startCompoundEdit(); textarea.select(getLineStartOffset(line), getLineStopOffset(line)); textarea.setSelectedText(what); stopCompoundEdit(); } /** * Get character offset for the start of a given line of text. */ public int getLineStartOffset(int line) { return textarea.getLineStartOffset(line); } /** * Get character offset for end of a given line of text. */ public int getLineStopOffset(int line) { return textarea.getLineStopOffset(line); } /** * Get the number of lines in the currently displayed buffer. */ public int getLineCount() { return textarea.getLineCount(); } /** * Use before a manipulating text to group editing operations together as a * single undo. Use stopCompoundEdit() once finished. */ public void startCompoundEdit() { compoundEdit = new CompoundEdit(); } /** * Use with startCompoundEdit() to group edit operations in a single undo. */ public void stopCompoundEdit() { compoundEdit.end(); undo.addEdit(compoundEdit); undoAction.updateUndoState(); redoAction.updateRedoState(); compoundEdit = null; } public int getScrollPosition() { return textarea.getScrollPosition(); } /** * Switch between tabs, this swaps out the Document object * that's currently being manipulated. */ protected void setCode(SketchCode code) { SyntaxDocument document = (SyntaxDocument) code.getDocument(); if (document == null) { // this document not yet inited document = new SyntaxDocument(); code.setDocument(document); // turn on syntax highlighting document.setTokenMarker(new PdeKeywords()); // insert the program text into the document object try { document.insertString(0, code.getProgram(), null); } catch (BadLocationException bl) { bl.printStackTrace(); } // set up this guy's own undo manager // code.undo = new UndoManager(); // connect the undo listener to the editor document.addUndoableEditListener(new UndoableEditListener() { public void undoableEditHappened(UndoableEditEvent e) { if (compoundEdit != null) { compoundEdit.addEdit(e.getEdit()); } else if (undo != null) { undo.addEdit(e.getEdit()); undoAction.updateUndoState(); redoAction.updateRedoState(); } } }); } // update the document object that's in use textarea.setDocument(document, code.getSelectionStart(), code.getSelectionStop(), code.getScrollPosition()); textarea.requestFocus(); // get the caret blinking this.undo = code.getUndo(); undoAction.updateUndoState(); redoAction.updateRedoState(); } /** * Implements Edit &rarr; Cut. */ public void handleCut() { textarea.cut(); sketch.setModified(true); } /** * Implements Edit &rarr; Copy. */ public void handleCopy() { textarea.copy(); } protected void handleDiscourseCopy() { new DiscourseFormat(Editor.this, false).show(); } protected void handleHTMLCopy() { new DiscourseFormat(Editor.this, true).show(); } /** * Implements Edit &rarr; Paste. */ public void handlePaste() { textarea.paste(); sketch.setModified(true); } /** * Implements Edit &rarr; Select All. */ public void handleSelectAll() { textarea.selectAll(); } protected void handleCommentUncomment() { startCompoundEdit(); int startLine = textarea.getSelectionStartLine(); int stopLine = textarea.getSelectionStopLine(); int lastLineStart = textarea.getLineStartOffset(stopLine); int selectionStop = textarea.getSelectionStop(); // If the selection ends at the beginning of the last line, // then don't (un)comment that line. if (selectionStop == lastLineStart) { // Though if there's no selection, don't do that if (textarea.isSelectionActive()) { stopLine } } // If the text is empty, ignore the user. // Also ensure that all lines are commented (not just the first) // when determining whether to comment or uncomment. int length = textarea.getDocumentLength(); boolean commented = true; for (int i = startLine; commented && (i <= stopLine); i++) { int pos = textarea.getLineStartOffset(i); if (pos + 2 > length) { commented = false; } else { // Check the first two characters to see if it's already a comment. String begin = textarea.getText(pos, 2); //System.out.println("begin is '" + begin + "'"); commented = begin.equals(" } } for (int line = startLine; line <= stopLine; line++) { int location = textarea.getLineStartOffset(line); if (commented) { // remove a comment textarea.select(location, location+2); if (textarea.getSelectedText().equals(" textarea.setSelectedText(""); } } else { // add a comment textarea.select(location, location); textarea.setSelectedText(" } } // Subtract one from the end, otherwise selects past the current line. // (Which causes subsequent calls to keep expanding the selection) textarea.select(textarea.getLineStartOffset(startLine), textarea.getLineStopOffset(stopLine) - 1); stopCompoundEdit(); } protected void handleIndentOutdent(boolean indent) { int tabSize = Preferences.getInteger("editor.tabs.size"); String tabString = Editor.EMPTY.substring(0, tabSize); startCompoundEdit(); int startLine = textarea.getSelectionStartLine(); int stopLine = textarea.getSelectionStopLine(); // If the selection ends at the beginning of the last line, // then don't (un)comment that line. int lastLineStart = textarea.getLineStartOffset(stopLine); int selectionStop = textarea.getSelectionStop(); if (selectionStop == lastLineStart) { // Though if there's no selection, don't do that if (textarea.isSelectionActive()) { stopLine } } for (int line = startLine; line <= stopLine; line++) { int location = textarea.getLineStartOffset(line); if (indent) { textarea.select(location, location); textarea.setSelectedText(tabString); } else { // outdent textarea.select(location, location + tabSize); // Don't eat code if it's not indented if (textarea.getSelectedText().equals(tabString)) { textarea.setSelectedText(""); } } } // Subtract one from the end, otherwise selects past the current line. // (Which causes subsequent calls to keep expanding the selection) textarea.select(textarea.getLineStartOffset(startLine), textarea.getLineStopOffset(stopLine) - 1); stopCompoundEdit(); } protected void handleFindReference() { String text = textarea.getSelectedText().trim(); if (text.length() == 0) { statusNotice(_("First select a word to find in the reference.")); } else { String referenceFile = PdeKeywords.getReference(text); //System.out.println("reference file is " + referenceFile); if (referenceFile == null) { statusNotice( I18n.format(_("No reference available for \"{0}\""), text) ); } else { Base.showReference(I18n.format(_("{0}.html"), referenceFile)); } } } /** * Implements Sketch &rarr; Run. * @param verbose Set true to run with verbose output. */ public void handleRun(final boolean verbose) { internalCloseRunner(); running = true; toolbar.activate(EditorToolbar.RUN); status.progress(_("Compiling sketch...")); // do this to advance/clear the terminal window / dos prompt / etc for (int i = 0; i < 10; i++) System.out.println(); // clear the console on each run, unless the user doesn't want to if (Preferences.getBoolean("console.auto_clear")) { console.clear(); } // Cannot use invokeLater() here, otherwise it gets // placed on the event thread and causes a hang--bad idea all around. new Thread(verbose ? presentHandler : runHandler).start(); } // DAM: in Arduino, this is compile class DefaultRunHandler implements Runnable { public void run() { try { sketch.prepare(); sketch.build(false); statusNotice(_("Done compiling.")); } catch (Exception e) { status.unprogress(); statusError(e); } status.unprogress(); toolbar.deactivate(EditorToolbar.RUN); } } // DAM: in Arduino, this is compile (with verbose output) class DefaultPresentHandler implements Runnable { public void run() { try { sketch.prepare(); sketch.build(true); statusNotice(_("Done compiling.")); } catch (Exception e) { status.unprogress(); statusError(e); } status.unprogress(); toolbar.deactivate(EditorToolbar.RUN); } } class DefaultStopHandler implements Runnable { public void run() { try { // DAM: we should try to kill the compilation or upload process here. } catch (Exception e) { statusError(e); } } } /** * Set the location of the sketch run window. Used by Runner to update the * Editor about window drag events while the sketch is running. */ public void setSketchLocation(Point p) { sketchWindowLocation = p; } /** * Get the last location of the sketch's run window. Used by Runner to make * the window show up in the same location as when it was last closed. */ public Point getSketchLocation() { return sketchWindowLocation; } /** * Implements Sketch &rarr; Stop, or pressing Stop on the toolbar. */ public void handleStop() { // called by menu or buttons // toolbar.activate(EditorToolbar.STOP); internalCloseRunner(); toolbar.deactivate(EditorToolbar.RUN); // toolbar.deactivate(EditorToolbar.STOP); // focus the PDE again after quitting presentation mode [toxi 030903] toFront(); } /** * Deactivate the Run button. This is called by Runner to notify that the * sketch has stopped running, usually in response to an error (or maybe * the sketch completing and exiting?) Tools should not call this function. * To initiate a "stop" action, call handleStop() instead. */ public void internalRunnerClosed() { running = false; toolbar.deactivate(EditorToolbar.RUN); } /** * Handle internal shutdown of the runner. */ public void internalCloseRunner() { running = false; if (stopHandler != null) try { stopHandler.run(); } catch (Exception e) { } sketch.cleanup(); } /** * Check if the sketch is modified and ask user to save changes. * @return false if canceling the close/quit operation */ protected boolean checkModified() { if (!sketch.isModified()) return true; // As of Processing 1.0.10, this always happens immediately. String prompt = I18n.format(_("Save changes to \"{0}\"? "), sketch.getName()); if (!Base.isMacOS()) { int result = JOptionPane.showConfirmDialog(this, prompt, _("Close"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (result == JOptionPane.YES_OPTION) { return handleSave(true); } else if (result == JOptionPane.NO_OPTION) { return true; // ok to continue } else if (result == JOptionPane.CANCEL_OPTION) { return false; } else { throw new IllegalStateException(); } } else { // This code is disabled unless Java 1.5 is being used on Mac OS X // because of a Java bug that prevents the initial value of the // dialog from being set properly (at least on my MacBook Pro). // The bug causes the "Don't Save" option to be the highlighted, // blinking, default. This sucks. But I'll tell you what doesn't // suck--workarounds for the Mac and Apple's snobby attitude about it! // I think it's nifty that they treat their developers like dirt. // Pane formatting adapted from the quaqua guide JOptionPane pane = new JOptionPane(_("<html> " + "<head> <style type=\"text/css\">"+ "b { font: 13pt \"Lucida Grande\" }"+ "p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+ "</style> </head>" + "<b>Do you want to save changes to this sketch<BR>" + " before closing?</b>" + "<p>If you don't save, your changes will be lost."), JOptionPane.QUESTION_MESSAGE); String[] options = new String[] { _("Save"), _("Cancel"), _("Don't Save") }; pane.setOptions(options); // highlight the safest option ala apple hig pane.setInitialValue(options[0]); // on macosx, setting the destructive property places this option // away from the others at the lefthand side pane.putClientProperty("Quaqua.OptionPane.destructiveOption", new Integer(2)); JDialog dialog = pane.createDialog(this, null); dialog.setVisible(true); Object result = pane.getValue(); if (result == options[0]) { // save (and close/quit) return handleSave(true); } else if (result == options[2]) { // don't save (still close/quit) return true; } else { // cancel? return false; } } } /** * Open a sketch from a particular path, but don't check to save changes. * Used by Sketch.saveAs() to re-open a sketch after the "Save As" */ protected void handleOpenUnchecked(String path, int codeIndex, int selStart, int selStop, int scrollPos) { internalCloseRunner(); handleOpenInternal(path); // Replacing a document that may be untitled. If this is an actual // untitled document, then editor.untitled will be set by Base. untitled = false; sketch.setCurrentCode(codeIndex); textarea.select(selStart, selStop); textarea.setScrollPosition(scrollPos); } /** * Second stage of open, occurs after having checked to see if the * modifications (if any) to the previous sketch need to be saved. */ protected boolean handleOpenInternal(String path) { // check to make sure that this .pde file is // in a folder of the same name File file = new File(path); String fileName = file.getName(); File parent = file.getParentFile(); String parentName = parent.getName(); String pdeName = parentName + ".pde"; File altPdeFile = new File(parent, pdeName); String inoName = parentName + ".ino"; File altInoFile = new File(parent, pdeName); if (pdeName.equals(fileName) || inoName.equals(fileName)) { // no beef with this guy } else if (altPdeFile.exists()) { // user selected a .java from the same sketch, but open the .pde instead path = altPdeFile.getAbsolutePath(); } else if (altInoFile.exists()) { path = altInoFile.getAbsolutePath(); } else if (!path.endsWith(".ino") && !path.endsWith(".pde")) { Base.showWarning(_("Bad file selected"), _("Processing can only open its own sketches\n" + "and other files ending in .ino or .pde"), null); return false; } else { String properParent = fileName.substring(0, fileName.length() - 4); Object[] options = { _("OK"), _("Cancel") }; String prompt = I18n.format( _("The file \"{0}\" needs to be inside\n" + "a sketch folder named \"{1}\".\n" + "Create this folder, move the file, and continue?"), fileName, properParent ); int result = JOptionPane.showOptionDialog(this, prompt, _("Moving"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (result == JOptionPane.YES_OPTION) { // create properly named folder File properFolder = new File(file.getParent(), properParent); if (properFolder.exists()) { Base.showWarning(_("Error"), I18n.format( _("A folder named \"{0}\" already exists. " + "Can't open sketch."), properParent ), null); return false; } if (!properFolder.mkdirs()) { //throw new IOException("Couldn't create sketch folder"); Base.showWarning(_("Error"), _("Could not create the sketch folder."), null); return false; } // copy the sketch inside File properPdeFile = new File(properFolder, file.getName()); File origPdeFile = new File(path); try { Base.copyFile(origPdeFile, properPdeFile); } catch (IOException e) { Base.showWarning(_("Error"), _("Could not copy to a proper location."), e); return false; } // remove the original file, so user doesn't get confused origPdeFile.delete(); // update with the new path path = properPdeFile.getAbsolutePath(); } else if (result == JOptionPane.NO_OPTION) { return false; } } try { sketch = new Sketch(this, path); } catch (IOException e) { Base.showWarning(_("Error"), _("Could not create the sketch."), e); return false; } header.rebuild(); // Set the title of the window to "sketch_070752a - Processing 0126" setTitle( I18n.format( _("{0} | Arduino {1}"), sketch.getName(), Base.VERSION_NAME ) ); // Disable untitled setting from previous document, if any untitled = false; // Store information on who's open and running // (in case there's a crash or something that can't be recovered) base.storeSketches(); Preferences.save(); // opening was successful return true; // } catch (Exception e) { // e.printStackTrace(); // statusError(e); // return false; } public boolean handleSave(boolean immediately) { //stopRunner(); handleStop(); // 0136 if (untitled) { return handleSaveAs(); // need to get the name, user might also cancel here } else if (immediately) { return handleSave2(); } else { SwingUtilities.invokeLater(new Runnable() { public void run() { handleSave2(); } }); } return true; } protected boolean handleSave2() { toolbar.activate(EditorToolbar.SAVE); statusNotice(_("Saving...")); boolean saved = false; try { saved = sketch.save(); if (saved) statusNotice(_("Done Saving.")); else statusEmpty(); // rebuild sketch menu in case a save-as was forced // Disabling this for 0125, instead rebuild the menu inside // the Save As method of the Sketch object, since that's the // only one who knows whether something was renamed. //sketchbook.rebuildMenus(); //sketchbook.rebuildMenusAsync(); } catch (Exception e) { // show the error as a message in the window statusError(e); // zero out the current action, // so that checkModified2 will just do nothing //checkModifiedMode = 0; // this is used when another operation calls a save } //toolbar.clear(); toolbar.deactivate(EditorToolbar.SAVE); return saved; } public boolean handleSaveAs() { //stopRunner(); // formerly from 0135 handleStop(); toolbar.activate(EditorToolbar.SAVE); //SwingUtilities.invokeLater(new Runnable() { //public void run() { statusNotice(_("Saving...")); try { if (sketch.saveAs()) { statusNotice(_("Done Saving.")); // Disabling this for 0125, instead rebuild the menu inside // the Save As method of the Sketch object, since that's the // only one who knows whether something was renamed. //sketchbook.rebuildMenusAsync(); } else { statusNotice(_("Save Canceled.")); return false; } } catch (Exception e) { // show the error as a message in the window statusError(e); } finally { // make sure the toolbar button deactivates toolbar.deactivate(EditorToolbar.SAVE); } return true; } public boolean serialPrompt() { int count = serialMenu.getItemCount(); Object[] names = new Object[count]; for (int i = 0; i < count; i++) { names[i] = ((JCheckBoxMenuItem)serialMenu.getItem(i)).getText(); } String result = (String) JOptionPane.showInputDialog(this, I18n.format( _("Serial port {0} not found.\n" + "Retry the upload with another serial port?"), Preferences.get("serial.port") ), "Serial port not found", JOptionPane.PLAIN_MESSAGE, null, names, 0); if (result == null) return false; selectSerialPort(result); base.onBoardOrPortChange(); return true; } /** * Called by Sketch &rarr; Export. * Handles calling the export() function on sketch, and * queues all the gui status stuff that comes along with it. * <p/> * Made synchronized to (hopefully) avoid problems of people * hitting export twice, quickly, and horking things up. */ /** * Handles calling the export() function on sketch, and * queues all the gui status stuff that comes along with it. * * Made synchronized to (hopefully) avoid problems of people * hitting export twice, quickly, and horking things up. */ synchronized public void handleExport(final boolean usingProgrammer) { //if (!handleExportCheckModified()) return; toolbar.activate(EditorToolbar.EXPORT); console.clear(); status.progress(_("Uploading to I/O Board...")); new Thread(usingProgrammer ? exportAppHandler : exportHandler).start(); } // DAM: in Arduino, this is upload class DefaultExportHandler implements Runnable { public void run() { try { serialMonitor.closeSerialPort(); serialMonitor.setVisible(false); uploading = true; boolean success = sketch.exportApplet(false); if (success) { statusNotice(_("Done uploading.")); } else { // error message will already be visible } } catch (SerialNotFoundException e) { populateSerialMenu(); if (serialMenu.getItemCount() == 0) statusError(e); else if (serialPrompt()) run(); else statusNotice(_("Upload canceled.")); } catch (RunnerException e) { //statusError("Error during upload."); //e.printStackTrace(); status.unprogress(); statusError(e); } catch (Exception e) { e.printStackTrace(); } status.unprogress(); uploading = false; //toolbar.clear(); toolbar.deactivate(EditorToolbar.EXPORT); } } // DAM: in Arduino, this is upload (with verbose output) class DefaultExportAppHandler implements Runnable { public void run() { try { serialMonitor.closeSerialPort(); serialMonitor.setVisible(false); uploading = true; boolean success = sketch.exportApplet(true); if (success) { statusNotice(_("Done uploading.")); } else { // error message will already be visible } } catch (SerialNotFoundException e) { populateSerialMenu(); if (serialMenu.getItemCount() == 0) statusError(e); else if (serialPrompt()) run(); else statusNotice(_("Upload canceled.")); } catch (RunnerException e) { //statusError("Error during upload."); //e.printStackTrace(); status.unprogress(); statusError(e); } catch (Exception e) { e.printStackTrace(); } status.unprogress(); uploading = false; //toolbar.clear(); toolbar.deactivate(EditorToolbar.EXPORT); } } protected boolean handleExportCheckModified() { if (!sketch.isModified()) return true; Object[] options = { _("OK"), _("Cancel") }; int result = JOptionPane.showOptionDialog(this, _("Save changes before export?"), _("Save"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (result == JOptionPane.OK_OPTION) { handleSave(true); } else { // why it's not CANCEL_OPTION is beyond me (at least on the mac) // but f-- it.. let's get this shite done.. //} else if (result == JOptionPane.CANCEL_OPTION) { statusNotice(_("Export canceled, changes must first be saved.")); //toolbar.clear(); return false; } return true; } public void handleSerial() { if (uploading) return; try { serialMonitor.openSerialPort(); serialMonitor.setVisible(true); } catch (SerialException e) { statusError(e); } } protected void handleBurnBootloader() { console.clear(); statusNotice(_("Burning bootloader to I/O Board (this may take a minute)...")); SwingUtilities.invokeLater(new Runnable() { public void run() { try { Uploader uploader = new AvrdudeUploader(); if (uploader.burnBootloader()) { statusNotice(_("Done burning bootloader.")); } else { statusError(_("Error while burning bootloader.")); // error message will already be visible } } catch (RunnerException e) { statusError(_("Error while burning bootloader.")); e.printStackTrace(); //statusError(e); } catch (Exception e) { statusError(_("Error while burning bootloader.")); e.printStackTrace(); } }}); } /** * Handler for File &rarr; Page Setup. */ public void handlePageSetup() { //printerJob = null; if (printerJob == null) { printerJob = PrinterJob.getPrinterJob(); } if (pageFormat == null) { pageFormat = printerJob.defaultPage(); } pageFormat = printerJob.pageDialog(pageFormat); //System.out.println("page format is " + pageFormat); } /** * Handler for File &rarr; Print. */ public void handlePrint() { statusNotice(_("Printing...")); //printerJob = null; if (printerJob == null) { printerJob = PrinterJob.getPrinterJob(); } if (pageFormat != null) { //System.out.println("setting page format " + pageFormat); printerJob.setPrintable(textarea.getPainter(), pageFormat); } else { printerJob.setPrintable(textarea.getPainter()); } // set the name of the job to the code name printerJob.setJobName(sketch.getCurrentCode().getPrettyName()); if (printerJob.printDialog()) { try { printerJob.print(); statusNotice(_("Done printing.")); } catch (PrinterException pe) { statusError(_("Error while printing.")); pe.printStackTrace(); } } else { statusNotice(_("Printing canceled.")); } //printerJob = null; // clear this out? } /** * Show an error int the status bar. */ public void statusError(String what) { status.error(what); //new Exception("deactivating RUN").printStackTrace(); toolbar.deactivate(EditorToolbar.RUN); } /** * Show an exception in the editor status bar. */ public void statusError(Exception e) { e.printStackTrace(); // if (e == null) { // System.err.println("Editor.statusError() was passed a null exception."); // return; if (e instanceof RunnerException) { RunnerException re = (RunnerException) e; if (re.hasCodeIndex()) { sketch.setCurrentCode(re.getCodeIndex()); } if (re.hasCodeLine()) { int line = re.getCodeLine(); // subtract one from the end so that the \n ain't included if (line >= textarea.getLineCount()) { // The error is at the end of this current chunk of code, // so the last line needs to be selected. line = textarea.getLineCount() - 1; if (textarea.getLineText(line).length() == 0) { // The last line may be zero length, meaning nothing to select. // If so, back up one more line. line } } if (line < 0 || line >= textarea.getLineCount()) { System.err.println(I18n.format(_("Bad error line: {0}"), line)); } else { textarea.select(textarea.getLineStartOffset(line), textarea.getLineStopOffset(line) - 1); } } } // Since this will catch all Exception types, spend some time figuring // out which kind and try to give a better error message to the user. String mess = e.getMessage(); if (mess != null) { String javaLang = "java.lang."; if (mess.indexOf(javaLang) == 0) { mess = mess.substring(javaLang.length()); } String rxString = "RuntimeException: "; if (mess.indexOf(rxString) == 0) { mess = mess.substring(rxString.length()); } statusError(mess); } // e.printStackTrace(); } /** * Show a notice message in the editor status bar. */ public void statusNotice(String msg) { status.notice(msg); } /** * Clear the status area. */ public void statusEmpty() { statusNotice(EMPTY); } protected void onBoardOrPortChange() { Map<String, String> boardPreferences = Base.getBoardPreferences(); lineStatus.setBoardName(boardPreferences.get("name")); lineStatus.setSerialPort(Preferences.get("serial.port")); lineStatus.repaint(); } /** * Returns the edit popup menu. */ class TextAreaPopup extends JPopupMenu { //private String currentDir = System.getProperty("user.dir"); private String referenceFile = null; private JMenuItem cutItem; private JMenuItem copyItem; private JMenuItem discourseItem; private JMenuItem referenceItem; private JMenuItem openURLItem; private JSeparator openURLItemSeparator; private String clickedURL; public TextAreaPopup() { openURLItem = new JMenuItem(_("Open URL")); openURLItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.openURL(clickedURL); } }); add(openURLItem); openURLItemSeparator = new JSeparator(); add(openURLItemSeparator); cutItem = new JMenuItem(_("Cut")); cutItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleCut(); } }); add(cutItem); copyItem = new JMenuItem(_("Copy")); copyItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleCopy(); } }); add(copyItem); discourseItem = new JMenuItem(_("Copy for Forum")); discourseItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleDiscourseCopy(); } }); add(discourseItem); discourseItem = new JMenuItem(_("Copy as HTML")); discourseItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleHTMLCopy(); } }); add(discourseItem); JMenuItem item = new JMenuItem(_("Paste")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePaste(); } }); add(item); item = new JMenuItem(_("Select All")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSelectAll(); } }); add(item); addSeparator(); item = new JMenuItem(_("Comment/Uncomment")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleCommentUncomment(); } }); add(item); item = new JMenuItem(_("Increase Indent")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleIndentOutdent(true); } }); add(item); item = new JMenuItem(_("Decrease Indent")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleIndentOutdent(false); } }); add(item); addSeparator(); referenceItem = new JMenuItem(_("Find in Reference")); referenceItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleFindReference(); } }); add(referenceItem); } // if no text is selected, disable copy and cut menu items public void show(Component component, int x, int y) { int lineNo = textarea.getLineOfOffset(textarea.xyToOffset(x, y)); int offset = textarea.xToOffset(lineNo, x); String line = textarea.getLineText(lineNo); clickedURL = textarea.checkClickedURL(line, offset); if (clickedURL != null) { openURLItem.setVisible(true); openURLItemSeparator.setVisible(true); } else { openURLItem.setVisible(false); openURLItemSeparator.setVisible(false); } if (textarea.isSelectionActive()) { cutItem.setEnabled(true); copyItem.setEnabled(true); discourseItem.setEnabled(true); String sel = textarea.getSelectedText().trim(); referenceFile = PdeKeywords.getReference(sel); referenceItem.setEnabled(referenceFile != null); } else { cutItem.setEnabled(false); copyItem.setEnabled(false); discourseItem.setEnabled(false); referenceItem.setEnabled(false); } super.show(component, x, y); } } }
package com.google.rolecall.repos; import com.google.rolecall.models.Unavailability; import org.springframework.data.repository.CrudRepository; public interface UnavailabilityRepository extends CrudRepository<Unavailability, Integer> { }
package org.apache.james.nntpserver; import org.apache.avalon.cornerstone.services.connection.ConnectionHandler; import org.apache.avalon.excalibur.pool.Poolable; import org.apache.avalon.framework.activity.Disposable; import org.apache.avalon.framework.component.ComponentException; import org.apache.avalon.framework.component.ComponentManager; import org.apache.avalon.framework.component.Composable; import org.apache.avalon.framework.configuration.Configurable; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.avalon.framework.logger.AbstractLogEnabled; import org.apache.avalon.framework.logger.Logger; import org.apache.james.nntpserver.repository.NNTPArticle; import org.apache.james.nntpserver.repository.NNTPGroup; import org.apache.james.nntpserver.repository.NNTPLineReaderImpl; import org.apache.james.nntpserver.repository.NNTPRepository; import org.apache.james.services.UsersRepository; import org.apache.james.services.UsersStore; import org.apache.james.util.InternetPrintWriter; import org.apache.james.util.RFC977DateFormat; import org.apache.james.util.RFC2980DateFormat; import org.apache.james.util.SimplifiedDateFormat; import org.apache.james.util.watchdog.Watchdog; import org.apache.james.util.watchdog.WatchdogTarget; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; import java.text.DateFormat; import java.text.ParseException; import java.util.*; public class NNTPHandler extends AbstractLogEnabled implements ConnectionHandler, Poolable { /** * used to calculate DATE from - see 11.3 */ private static final SimplifiedDateFormat DF_RFC977 = new RFC977DateFormat(); /** * Date format for the DATE keyword - see 11.1.1 */ private static final SimplifiedDateFormat DF_RFC2980 = new RFC2980DateFormat(); /** * The UTC offset for this time zone. */ public static final long UTC_OFFSET = Calendar.getInstance().get(Calendar.ZONE_OFFSET); /** * The text string for the NNTP MODE command. */ private final static String COMMAND_MODE = "MODE"; /** * The text string for the NNTP LIST command. */ private final static String COMMAND_LIST = "LIST"; /** * The text string for the NNTP GROUP command. */ private final static String COMMAND_GROUP = "GROUP"; /** * The text string for the NNTP NEXT command. */ private final static String COMMAND_NEXT = "NEXT"; /** * The text string for the NNTP LAST command. */ private final static String COMMAND_LAST = "LAST"; /** * The text string for the NNTP ARTICLE command. */ private final static String COMMAND_ARTICLE = "ARTICLE"; /** * The text string for the NNTP HEAD command. */ private final static String COMMAND_HEAD = "HEAD"; /** * The text string for the NNTP BODY command. */ private final static String COMMAND_BODY = "BODY"; /** * The text string for the NNTP STAT command. */ private final static String COMMAND_STAT = "STAT"; /** * The text string for the NNTP POST command. */ private final static String COMMAND_POST = "POST"; /** * The text string for the NNTP IHAVE command. */ private final static String COMMAND_IHAVE = "IHAVE"; /** * The text string for the NNTP QUIT command. */ private final static String COMMAND_QUIT = "QUIT"; /** * The text string for the NNTP DATE command. */ private final static String COMMAND_DATE = "DATE"; /** * The text string for the NNTP HELP command. */ private final static String COMMAND_HELP = "HELP"; /** * The text string for the NNTP NEWGROUPS command. */ private final static String COMMAND_NEWGROUPS = "NEWGROUPS"; /** * The text string for the NNTP NEWNEWS command. */ private final static String COMMAND_NEWNEWS = "NEWNEWS"; /** * The text string for the NNTP LISTGROUP command. */ private final static String COMMAND_LISTGROUP = "LISTGROUP"; /** * The text string for the NNTP OVER command. */ private final static String COMMAND_OVER = "OVER"; /** * The text string for the NNTP XOVER command. */ private final static String COMMAND_XOVER = "XOVER"; /** * The text string for the NNTP HDR command. */ private final static String COMMAND_HDR = "HDR"; /** * The text string for the NNTP XHDR command. */ private final static String COMMAND_XHDR = "XHDR"; /** * The text string for the NNTP AUTHINFO command. */ private final static String COMMAND_AUTHINFO = "AUTHINFO"; /** * The text string for the NNTP MODE READER parameter. */ private final static String MODE_TYPE_READER = "READER"; /** * The text string for the NNTP MODE STREAM parameter. */ private final static String MODE_TYPE_STREAM = "STREAM"; /** * The text string for the NNTP AUTHINFO USER parameter. */ private final static String AUTHINFO_PARAM_USER = "USER"; /** * The text string for the NNTP AUTHINFO PASS parameter. */ private final static String AUTHINFO_PARAM_PASS = "PASS"; /** * The thread executing this handler */ private Thread handlerThread; /** * The TCP/IP socket over which the POP3 interaction * is occurring */ private Socket socket; /** * The reader associated with incoming characters. */ private BufferedReader reader; /** * The writer to which outgoing messages are written. */ private PrintWriter writer; /** * The current newsgroup. */ private NNTPGroup group; /** * The current newsgroup. */ private int currentArticleNumber = -1; /** * Per-service configuration data that applies to all handlers * associated with the service. */ private NNTPHandlerConfigurationData theConfigData; /** * The user id associated with the NNTP dialogue */ private String user = null; /** * The password associated with the NNTP dialogue */ private String password = null; /** * Whether the user for this session has already authenticated. * Used to optimize authentication checks */ boolean isAlreadyAuthenticated = false; /** * The watchdog being used by this handler to deal with idle timeouts. */ private Watchdog theWatchdog; /** * The watchdog target that idles out this handler. */ private WatchdogTarget theWatchdogTarget = new NNTPWatchdogTarget(); /** * Set the configuration data for the handler * * @param theData configuration data for the handler */ void setConfigurationData(NNTPHandlerConfigurationData theData) { theConfigData = theData; } /** * Set the Watchdog for use by this handler. * * @param theWatchdog the watchdog */ void setWatchdog(Watchdog theWatchdog) { this.theWatchdog = theWatchdog; } /** * Gets the Watchdog Target that should be used by Watchdogs managing * this connection. * * @return the WatchdogTarget */ WatchdogTarget getWatchdogTarget() { return theWatchdogTarget; } /** * Idle out this connection */ void idleClose() { if (getLogger() != null) { getLogger().error("NNTP Connection has idled out."); } try { if (socket != null) { socket.close(); } } catch (Exception e) { // ignored } finally { socket = null; } synchronized (this) { // Interrupt the thread to recover from internal hangs if (handlerThread != null) { handlerThread.interrupt(); handlerThread = null; } } } /** * @see org.apache.avalon.cornerstone.services.connection.ConnectionHandler#handleConnection(Socket) */ public void handleConnection( Socket connection ) throws IOException { try { this.socket = connection; synchronized (this) { handlerThread = Thread.currentThread(); } reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "ASCII"), 1024); writer = new InternetPrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()), 1024), true); } catch (Exception e) { getLogger().error( "Cannot open connection from: " + e.getMessage(), e ); } try { // section 7.1 if ( theConfigData.getNNTPRepository().isReadOnly() ) { StringBuffer respBuffer = new StringBuffer(128) .append("201 ") .append(theConfigData.getHelloName()) .append(" NNTP Service Ready, posting prohibited"); writeLoggedFlushedResponse(respBuffer.toString()); } else { StringBuffer respBuffer = new StringBuffer(128) .append("200 ") .append(theConfigData.getHelloName()) .append(" NNTP Service Ready, posting permitted"); writeLoggedFlushedResponse(respBuffer.toString()); } theWatchdog.start(); while (parseCommand(reader.readLine())) { theWatchdog.reset(); } theWatchdog.stop(); getLogger().debug("Connection closed"); } catch (Exception e) { // if the connection has been idled out, the // socket will be closed and null. Do NOT // log the exception or attempt to send the // closing connection message if (socket != null) { try { doQUIT(null); } catch(Throwable t) { } getLogger().error( "Exception during connection:" + e.getMessage(), e ); } } finally { resetHandler(); } } /** * Resets the handler data to a basic state. */ private void resetHandler() { // Clear the Watchdog if (theWatchdog != null) { if (theWatchdog instanceof Disposable) { ((Disposable)theWatchdog).dispose(); } theWatchdog = null; } // Clear the streams try { if (reader != null) { reader.close(); } } catch (IOException ioe) { getLogger().warn("NNTPHandler: Unexpected exception occurred while closing reader: " + ioe); } finally { reader = null; } if (writer != null) { writer.close(); writer = null; } try { if (socket != null) { socket.close(); } } catch (IOException ioe) { getLogger().warn("NNTPHandler: Unexpected exception occurred while closing socket: " + ioe); } finally { socket = null; } synchronized (this) { handlerThread = null; } // Clear the selected group, article info group = null; currentArticleNumber = -1; // Clear the authentication info user = null; password = null; isAlreadyAuthenticated = false; // Clear the config data theConfigData = null; } /** * This method parses NNTP commands read off the wire in handleConnection. * Actual processing of the command (possibly including additional back and * forth communication with the client) is delegated to one of a number of * command specific handler methods. The primary purpose of this method is * to parse the raw command string to determine exactly which handler should * be called. It returns true if expecting additional commands, false otherwise. * * @param commandRaw the raw command string passed in over the socket * * @return whether additional commands are expected. */ private boolean parseCommand(String commandRaw) { if (commandRaw == null) { return false; } if (getLogger().isDebugEnabled()) { getLogger().debug("Command received: " + commandRaw); } String command = commandRaw.trim(); String argument = null; int spaceIndex = command.indexOf(" "); if (spaceIndex >= 0) { argument = command.substring(spaceIndex + 1); command = command.substring(0, spaceIndex); } command = command.toUpperCase(Locale.US); if (!isAuthorized(command) ) { writeLoggedFlushedResponse("502 User is not authenticated"); getLogger().debug("Command not allowed."); return true; } if ((command.equals(COMMAND_MODE)) && (argument != null) && argument.toUpperCase(Locale.US).equals(MODE_TYPE_READER)) { doMODEREADER(argument); } else if ( command.equals(COMMAND_LIST)) { doLIST(argument); } else if ( command.equals(COMMAND_GROUP) ) { doGROUP(argument); } else if ( command.equals(COMMAND_NEXT) ) { doNEXT(argument); } else if ( command.equals(COMMAND_LAST) ) { doLAST(argument); } else if ( command.equals(COMMAND_ARTICLE) ) { doARTICLE(argument); } else if ( command.equals(COMMAND_HEAD) ) { doHEAD(argument); } else if ( command.equals(COMMAND_BODY) ) { doBODY(argument); } else if ( command.equals(COMMAND_STAT) ) { doSTAT(argument); } else if ( command.equals(COMMAND_POST) ) { doPOST(argument); } else if ( command.equals(COMMAND_IHAVE) ) { doIHAVE(argument); } else if ( command.equals(COMMAND_QUIT) ) { doQUIT(argument); } else if ( command.equals(COMMAND_DATE) ) { doDATE(argument); } else if ( command.equals(COMMAND_HELP) ) { doHELP(argument); } else if ( command.equals(COMMAND_NEWGROUPS) ) { doNEWGROUPS(argument); } else if ( command.equals(COMMAND_NEWNEWS) ) { doNEWNEWS(argument); } else if ( command.equals(COMMAND_LISTGROUP) ) { doLISTGROUP(argument); } else if ( command.equals(COMMAND_OVER) ) { doOVER(argument); } else if ( command.equals(COMMAND_XOVER) ) { doXOVER(argument); } else if ( command.equals(COMMAND_HDR) ) { doHDR(argument); } else if ( command.equals(COMMAND_XHDR) ) { doXHDR(argument); } else if ( command.equals(COMMAND_AUTHINFO) ) { doAUTHINFO(argument); } else if ( command.equals("PAT") ) { doPAT(argument); } else { doUnknownCommand(command, argument); } return (command.equals(COMMAND_QUIT) == false); } /** * Handles an unrecognized command, logging that. * * @param command the command received from the client * @param argument the argument passed in with the command */ private void doUnknownCommand(String command, String argument) { if (getLogger().isDebugEnabled()) { StringBuffer logBuffer = new StringBuffer(128) .append("Received unknown command ") .append(command) .append(" with argument ") .append(argument); getLogger().debug(logBuffer.toString()); } writeLoggedFlushedResponse("500 Unknown command"); } /** * Implements only the originnal AUTHINFO. * for simple and generic AUTHINFO, 501 is sent back. This is as * per article 3.1.3 of RFC 2980 * * @param argument the argument passed in with the AUTHINFO command */ private void doAUTHINFO(String argument) { String command = null; String value = null; if (argument != null) { int spaceIndex = argument.indexOf(" "); if (spaceIndex >= 0) { command = argument.substring(0, spaceIndex); value = argument.substring(spaceIndex + 1); } } if (command == null) { writeLoggedFlushedResponse("501 Syntax error"); return; } if ( command.equals(AUTHINFO_PARAM_USER) ) { // Reject re-authentication if ( isAlreadyAuthenticated ) { writeLoggedFlushedResponse("482 Already authenticated - rejecting new credentials"); } // Reject doubly sent user if (user != null) { user = null; password = null; isAlreadyAuthenticated = false; writeLoggedFlushedResponse("482 User already specified - rejecting new user"); return; } user = value; writeLoggedFlushedResponse("381 More authentication information required"); } else if ( command.equals(AUTHINFO_PARAM_PASS) ) { // Reject password sent before user if (user == null) { writeLoggedFlushedResponse("482 User not yet specified. Rejecting user."); return; } // Reject doubly sent password if (password != null) { user = null; password = null; isAlreadyAuthenticated = false; writeLoggedFlushedResponse("482 Password already specified - rejecting new password"); return; } password = value; isAlreadyAuthenticated = isAuthenticated(); if ( isAlreadyAuthenticated ) { writeLoggedFlushedResponse("281 Authentication accepted"); } else { writeLoggedFlushedResponse("482 Authentication rejected"); // Clear bad authentication user = null; password = null; } } else { writeLoggedFlushedResponse("501 Syntax error"); return; } } /** * Lists the articles posted since the date passed in as * an argument. * * @param argument the argument passed in with the NEWNEWS command. * Should be NEWNEWS newsgroups date time [GMT] [<distribution>] * see RFC 977 #3.8, RFC 2980 #4.5. */ private void doNEWNEWS(String argument) { String wildmat = "*"; if (argument != null) { int spaceIndex = argument.indexOf(" "); if (spaceIndex >= 0) { wildmat = argument.substring(0, spaceIndex); argument = argument.substring(spaceIndex + 1); } else { getLogger().error("NEWNEWS had an invalid argument"); writeLoggedFlushedResponse("501 Syntax error"); return; } } else { getLogger().error("NEWNEWS had a null argument"); writeLoggedFlushedResponse("501 Syntax error"); return; } Date theDate = null; try { theDate = getDateFrom(argument); } catch (NNTPException nntpe) { getLogger().error("NEWNEWS had an invalid argument", nntpe); writeLoggedFlushedResponse("501 Syntax error"); return; } writeLoggedFlushedResponse("230 list of new articles by message-id follows"); Iterator groups = theConfigData.getNNTPRepository().getMatchedGroups(wildmat); while (groups.hasNext() ) { Iterator articles = ((NNTPGroup)(groups.next())).getArticlesSince(theDate); while ( articles.hasNext() ) { StringBuffer iterBuffer = new StringBuffer(64) .append("<") .append(((NNTPArticle)articles.next()).getUniqueID()) .append(">"); writeLoggedResponse(iterBuffer.toString()); } } writeLoggedFlushedResponse("."); } /** * Lists the groups added since the date passed in as * an argument. * * @param argument the argument passed in with the NEWNEWS command. * Should be a date. */ private void doNEWGROUPS(String argument) { // see section 11.3 // both draft-ietf-nntpext-base-15.txt and rfc977 have only group names // in response lines, but INN sends // '<group name> <last article> <first article> <posting allowed>' // NOTE: following INN over either document. // doesn't mention the supposed discrepancy. Consider changing code to // be in line with spec. Date theDate = null; try { theDate = getDateFrom(argument); } catch (NNTPException nntpe) { getLogger().error("NEWGROUPS had an invalid argument", nntpe); writeLoggedFlushedResponse("501 Syntax error"); return; } Iterator iter = theConfigData.getNNTPRepository().getGroupsSince(theDate); writeLoggedFlushedResponse("231 list of new newsgroups follows"); while ( iter.hasNext() ) { NNTPGroup currentGroup = (NNTPGroup)iter.next(); StringBuffer iterBuffer = new StringBuffer(128) .append(currentGroup.getName()) .append(" ") .append(currentGroup.getLastArticleNumber()) .append(" ") .append(currentGroup.getFirstArticleNumber()) .append(" ") .append((currentGroup.isPostAllowed()?"y":"n")); writeLoggedResponse(iterBuffer.toString()); } writeLoggedFlushedResponse("."); } /** * Lists the help text for the service. * * @param argument the argument passed in with the HELP command. */ private void doHELP(String argument) { writeLoggedResponse("100 Help text follows"); writeLoggedFlushedResponse("."); } /** * Returns the current date according to the news server. * * @param argument the argument passed in with the DATE command */ private void doDATE(String argument) { Date dt = new Date(System.currentTimeMillis()-UTC_OFFSET); String dtStr = DF_RFC2980.format(new Date(dt.getTime() - UTC_OFFSET)); writeLoggedFlushedResponse("111 "+dtStr); } /** * Quits the transaction. * * @param argument the argument passed in with the QUIT command */ private void doQUIT(String argument) { writeLoggedFlushedResponse("205 closing connection"); } /** * Handles the LIST command and its assorted extensions. * * @param argument the argument passed in with the LIST command. */ private void doLIST(String argument) { // see section 9.4.1 String wildmat = "*"; boolean isListNewsgroups = false; String extension = argument; if (argument != null) { int spaceIndex = argument.indexOf(" "); if (spaceIndex >= 0) { wildmat = argument.substring(spaceIndex + 1); extension = argument.substring(0, spaceIndex); } extension = extension.toUpperCase(Locale.US); } if (extension != null) { if (extension.equals("ACTIVE")) { isListNewsgroups = false; } else if (extension.equals("NEWSGROUPS") ) { isListNewsgroups = true; } else if (extension.equals("EXTENSIONS") ) { doLISTEXTENSIONS(); return; } else if (extension.equals("OVERVIEW.FMT") ) { doLISTOVERVIEWFMT(); return; } else if (extension.equals("ACTIVE.TIMES") ) { // not supported - 9.4.2.1, 9.4.3.1, 9.4.4.1 writeLoggedFlushedResponse("503 program error, function not performed"); return; } else if (extension.equals("DISTRIBUTIONS") ) { // not supported - 9.4.2.1, 9.4.3.1, 9.4.4.1 writeLoggedFlushedResponse("503 program error, function not performed"); return; } else if (extension.equals("DISTRIB.PATS") ) { // not supported - 9.4.2.1, 9.4.3.1, 9.4.4.1 writeLoggedFlushedResponse("503 program error, function not performed"); return; } else { writeLoggedFlushedResponse("501 Syntax error"); return; } } Iterator iter = theConfigData.getNNTPRepository().getMatchedGroups(wildmat); writeLoggedFlushedResponse("215 list of newsgroups follows"); while ( iter.hasNext() ) { NNTPGroup theGroup = (NNTPGroup)iter.next(); if (isListNewsgroups) { writeLoggedResponse(theGroup.getListNewsgroupsFormat()); } else { writeLoggedResponse(theGroup.getListFormat()); } } writeLoggedFlushedResponse("."); } /** * Informs the server that the client has an article with the specified * message-ID. * * @param id the message id */ private void doIHAVE(String id) { // see section 9.3.2.1 if (!isMessageId(id)) { writeLoggedFlushedResponse("501 command syntax error"); return; } NNTPArticle article = theConfigData.getNNTPRepository().getArticleFromID(id); if ( article != null ) { writeLoggedFlushedResponse("435 article not wanted - do not send it"); } else { writeLoggedFlushedResponse("335 send article to be transferred. End with <CR-LF>.<CR-LF>"); createArticle(); writeLoggedFlushedResponse("235 article received ok"); } } /** * Posts an article to the news server. * * @param argument the argument passed in with the POST command */ private void doPOST(String argument) { // see section 9.3.1.1 if ( argument != null ) { writeLoggedFlushedResponse("501 Syntax error - unexpected parameter"); } writeLoggedFlushedResponse("340 send article to be posted. End with <CR-LF>.<CR-LF>"); createArticle(); writeLoggedFlushedResponse("240 article received ok"); } /** * Executes the STAT command. Sets the current article pointer, * returns article information. * * @param the argument passed in to the STAT command, * which should be an article number or message id. * If no parameter is provided, the current selected * article is used. */ private void doSTAT(String param) { // section 9.2.4 NNTPArticle article = null; if (isMessageId(param)) { article = theConfigData.getNNTPRepository().getArticleFromID(param); if ( article == null ) { writeLoggedFlushedResponse("430 no such article"); return; } else { StringBuffer respBuffer = new StringBuffer(64) .append("223 0 ") .append(param); writeLoggedFlushedResponse(respBuffer.toString()); } } else { int newArticleNumber = currentArticleNumber; if ( group == null ) { writeLoggedFlushedResponse("412 no newsgroup selected"); return; } else { if ( param == null ) { if ( currentArticleNumber < 0 ) { writeLoggedFlushedResponse("420 no current article selected"); return; } else { article = group.getArticle(currentArticleNumber); } } else { newArticleNumber = Integer.parseInt(param); article = group.getArticle(newArticleNumber); } if ( article == null ) { writeLoggedFlushedResponse("423 no such article number in this group"); return; } else { currentArticleNumber = newArticleNumber; String articleID = article.getUniqueID(); if (articleID == null) { articleID = "<0>"; } StringBuffer respBuffer = new StringBuffer(128) .append("223 ") .append(article.getArticleNumber()) .append(" ") .append(articleID); writeLoggedFlushedResponse(respBuffer.toString()); } } } } /** * Executes the BODY command. Sets the current article pointer, * returns article information and body. * * @param the argument passed in to the BODY command, * which should be an article number or message id. * If no parameter is provided, the current selected * article is used. */ private void doBODY(String param) { // section 9.2.3 NNTPArticle article = null; if (isMessageId(param)) { article = theConfigData.getNNTPRepository().getArticleFromID(param); if ( article == null ) { writeLoggedFlushedResponse("430 no such article"); return; } else { StringBuffer respBuffer = new StringBuffer(64) .append("222 0 ") .append(param); writeLoggedFlushedResponse(respBuffer.toString()); } } else { int newArticleNumber = currentArticleNumber; if ( group == null ) { writeLoggedFlushedResponse("412 no newsgroup selected"); return; } else { if ( param == null ) { if ( currentArticleNumber < 0 ) { writeLoggedFlushedResponse("420 no current article selected"); return; } else { article = group.getArticle(currentArticleNumber); } } else { newArticleNumber = Integer.parseInt(param); article = group.getArticle(newArticleNumber); } if ( article == null ) { writeLoggedFlushedResponse("423 no such article number in this group"); return; } else { currentArticleNumber = newArticleNumber; String articleID = article.getUniqueID(); if (articleID == null) { articleID = "<0>"; } StringBuffer respBuffer = new StringBuffer(128) .append("222 ") .append(article.getArticleNumber()) .append(" ") .append(articleID); writeLoggedFlushedResponse(respBuffer.toString()); } } } if (article != null) { article.writeBody(writer); writeLoggedFlushedResponse("."); } } /** * Executes the HEAD command. Sets the current article pointer, * returns article information and headers. * * @param the argument passed in to the HEAD command, * which should be an article number or message id. * If no parameter is provided, the current selected * article is used. */ private void doHEAD(String param) { // section 9.2.2 NNTPArticle article = null; if (isMessageId(param)) { article = theConfigData.getNNTPRepository().getArticleFromID(param); if ( article == null ) { writeLoggedFlushedResponse("430 no such article"); return; } else { StringBuffer respBuffer = new StringBuffer(64) .append("221 0 ") .append(param); writeLoggedFlushedResponse(respBuffer.toString()); } } else { int newArticleNumber = currentArticleNumber; if ( group == null ) { writeLoggedFlushedResponse("412 no newsgroup selected"); return; } else { if ( param == null ) { if ( currentArticleNumber < 0 ) { writeLoggedFlushedResponse("420 no current article selected"); return; } else { article = group.getArticle(currentArticleNumber); } } else { newArticleNumber = Integer.parseInt(param); article = group.getArticle(newArticleNumber); } if ( article == null ) { writeLoggedFlushedResponse("423 no such article number in this group"); return; } else { currentArticleNumber = newArticleNumber; String articleID = article.getUniqueID(); if (articleID == null) { articleID = "<0>"; } StringBuffer respBuffer = new StringBuffer(128) .append("221 ") .append(article.getArticleNumber()) .append(" ") .append(articleID); writeLoggedFlushedResponse(respBuffer.toString()); } } } if (article != null) { article.writeHead(writer); writeLoggedFlushedResponse("."); } } /** * Executes the ARTICLE command. Sets the current article pointer, * returns article information and contents. * * @param the argument passed in to the ARTICLE command, * which should be an article number or message id. * If no parameter is provided, the current selected * article is used. */ private void doARTICLE(String param) { // section 9.2.1 NNTPArticle article = null; if (isMessageId(param)) { article = theConfigData.getNNTPRepository().getArticleFromID(param); if ( article == null ) { writeLoggedFlushedResponse("430 no such article"); return; } else { StringBuffer respBuffer = new StringBuffer(64) .append("220 0 ") .append(param); writeLoggedResponse(respBuffer.toString()); } } else { int newArticleNumber = currentArticleNumber; if ( group == null ) { writeLoggedFlushedResponse("412 no newsgroup selected"); return; } else { if ( param == null ) { if ( currentArticleNumber < 0 ) { writeLoggedFlushedResponse("420 no current article selected"); return; } else { article = group.getArticle(currentArticleNumber); } } else { newArticleNumber = Integer.parseInt(param); article = group.getArticle(newArticleNumber); } if ( article == null ) { writeLoggedFlushedResponse("423 no such article number in this group"); return; } else { currentArticleNumber = newArticleNumber; String articleID = article.getUniqueID(); if (articleID == null) { articleID = "<0>"; } StringBuffer respBuffer = new StringBuffer(128) .append("220 ") .append(article.getArticleNumber()) .append(" ") .append(articleID); writeLoggedFlushedResponse(respBuffer.toString()); } } } if (article != null) { article.writeArticle(writer); writeLoggedFlushedResponse("."); } } /** * Advances the current article pointer to the next article in the group. * * @param argument the argument passed in with the NEXT command */ private void doNEXT(String argument) { // section 9.1.1.3.1 if ( argument != null ) { writeLoggedFlushedResponse("501 Syntax error - unexpected parameter"); } else if ( group == null ) { writeLoggedFlushedResponse("412 no newsgroup selected"); } else if ( currentArticleNumber < 0 ) { writeLoggedFlushedResponse("420 no current article has been selected"); } else if ( currentArticleNumber >= group.getLastArticleNumber() ) { writeLoggedFlushedResponse("421 no next article in this group"); } else { currentArticleNumber++; NNTPArticle article = group.getArticle(currentArticleNumber); StringBuffer respBuffer = new StringBuffer(64) .append("223 ") .append(article.getArticleNumber()) .append(" ") .append(article.getUniqueID()); writeLoggedFlushedResponse(respBuffer.toString()); } } /** * Moves the currently selected article pointer to the article * previous to the currently selected article in the selected group. * * @param argument the argument passed in with the LAST command */ private void doLAST(String argument) { // section 9.1.1.2.1 if ( argument != null ) { writeLoggedFlushedResponse("501 Syntax error - unexpected parameter"); } else if ( group == null ) { writeLoggedFlushedResponse("412 no newsgroup selected"); } else if ( currentArticleNumber < 0 ) { writeLoggedFlushedResponse("420 no current article has been selected"); } else if ( currentArticleNumber <= group.getFirstArticleNumber() ) { writeLoggedFlushedResponse("422 no previous article in this group"); } else { currentArticleNumber NNTPArticle article = group.getArticle(currentArticleNumber); StringBuffer respBuffer = new StringBuffer(64) .append("223 ") .append(article.getArticleNumber()) .append(" ") .append(article.getUniqueID()); writeLoggedFlushedResponse(respBuffer.toString()); } } /** * Selects a group to be the current newsgroup. * * @param group the name of the group being selected. */ private void doGROUP(String groupName) { if (groupName == null) { writeLoggedFlushedResponse("501 Syntax error - missing required parameter"); return; } NNTPGroup newGroup = theConfigData.getNNTPRepository().getGroup(groupName); // section 9.1.1.1 if ( newGroup == null ) { writeLoggedFlushedResponse("411 no such newsgroup"); } else { group = newGroup; // if the number of articles in group == 0 // then the server may return this information in 3 ways, // The clients must honor all those 3 ways. // our response is: // highWaterMark == lowWaterMark and number of articles == 0 int articleCount = group.getNumberOfArticles(); int lowWaterMark = group.getFirstArticleNumber(); int highWaterMark = group.getLastArticleNumber(); // Set the current article pointer. If no // articles are in the group, the current article // pointer should be explicitly unset. if (articleCount != 0) { currentArticleNumber = lowWaterMark; } else { currentArticleNumber = -1; } StringBuffer respBuffer = new StringBuffer(128) .append("211 ") .append(articleCount) .append(" ") .append(lowWaterMark) .append(" ") .append(highWaterMark) .append(" ") .append(group.getName()) .append(" group selected"); writeLoggedFlushedResponse(respBuffer.toString()); } } /** * Lists the extensions supported by this news server. */ private void doLISTEXTENSIONS() { // 8.1.1 writeLoggedResponse("202 Extensions supported:"); writeLoggedResponse("LISTGROUP"); writeLoggedResponse("AUTHINFO"); writeLoggedResponse("OVER"); writeLoggedResponse("XOVER"); writeLoggedResponse("HDR"); writeLoggedResponse("XHDR"); writeLoggedFlushedResponse("."); } /** * Informs the server that the client is a newsreader. * * @param argument the argument passed in with the MODE READER command */ private void doMODEREADER(String argument) { writeLoggedFlushedResponse(theConfigData.getNNTPRepository().isReadOnly() ? "201 Posting Not Permitted" : "200 Posting Permitted"); } /** * Gets a listing of article numbers in specified group name * or in the already selected group if the groupName is null. * * @param groupName the name of the group to list */ private void doLISTGROUP(String groupName) { // 9.5.1.1.1 if (groupName==null) { if ( group == null) { writeLoggedFlushedResponse("412 no news group currently selected"); return; } } else { group = theConfigData.getNNTPRepository().getGroup(groupName); if ( group == null ) { writeLoggedFlushedResponse("411 no such newsgroup"); return; } } if ( group != null ) { this.group = group; // Set the current article pointer. If no // articles are in the group, the current article // pointer should be explicitly unset. if (group.getNumberOfArticles() > 0) { currentArticleNumber = group.getFirstArticleNumber(); } else { currentArticleNumber = -1; } writeLoggedFlushedResponse("211 list of article numbers follow"); Iterator iter = group.getArticles(); while (iter.hasNext()) { NNTPArticle article = (NNTPArticle)iter.next(); writeLoggedResponse(article.getArticleNumber() + ""); } writeLoggedFlushedResponse("."); } } /** * Handles the LIST OVERVIEW.FMT command. Not supported. */ private void doLISTOVERVIEWFMT() { // 9.5.3.1.1 writeLoggedFlushedResponse("215 Information follows"); String[] overviewHeaders = theConfigData.getNNTPRepository().getOverviewFormat(); for (int i = 0; i < overviewHeaders.length; i++) { writeLoggedResponse(overviewHeaders[i]); } writeLoggedFlushedResponse("."); } /** * Handles the PAT command. Not supported. * * @param argument the argument passed in with the PAT command */ private void doPAT(String argument) { // 9.5.3.1.1 in draft-12 writeLoggedFlushedResponse("500 Command not recognized"); } /** * Get the values of the headers for the selected newsgroup, * with an optional range modifier. * * @param argument the argument passed in with the XHDR command. */ private void doXHDR(String argument) { doHDR(argument); } /** * Get the values of the headers for the selected newsgroup, * with an optional range modifier. * * @param argument the argument passed in with the HDR command. */ private void doHDR(String argument) { // 9.5.3 if (argument == null) { writeLoggedFlushedResponse("501 Syntax error - missing required parameter"); return; } String hdr = argument; String range = null; int spaceIndex = hdr.indexOf(" "); if (spaceIndex >= 0 ) { range = hdr.substring(spaceIndex + 1); hdr = hdr.substring(0, spaceIndex); } if (group == null ) { writeLoggedFlushedResponse("412 No news group currently selected."); return; } if ((range == null) && (currentArticleNumber < 0)) { writeLoggedFlushedResponse("420 No current article selected"); return; } NNTPArticle[] article = getRange(range); if ( article == null ) { writeLoggedFlushedResponse("412 no newsgroup selected"); } else if ( article.length == 0 ) { writeLoggedFlushedResponse("430 no such article"); } else { writeLoggedFlushedResponse("221 Header follows"); for ( int i = 0 ; i < article.length ; i++ ) { String val = article[i].getHeader(hdr); if ( val == null ) { val = ""; } StringBuffer hdrBuffer = new StringBuffer(128) .append(article[i].getArticleNumber()) .append(" ") .append(val); writeLoggedResponse(hdrBuffer.toString()); } writeLoggedFlushedResponse("."); } } /** * Returns information from the overview database regarding the * current article, or a range of articles. * * @param range the optional article range. */ private void doXOVER(String range) { doOVER(range); } /** * Returns information from the overview database regarding the * current article, or a range of articles. * * @param range the optional article range. */ private void doOVER(String range) { // 9.5.2.2.1 if ( group == null ) { writeLoggedFlushedResponse("412 No newsgroup selected"); return; } if ((range == null) && (currentArticleNumber < 0)) { writeLoggedFlushedResponse("420 No current article selected"); return; } NNTPArticle[] article = getRange(range); if ( article.length == 0 ) { writeLoggedFlushedResponse("420 No article(s) selected"); } else { writeLoggedResponse("224 Overview information follows"); for ( int i = 0 ; i < article.length ; i++ ) { article[i].writeOverview(writer); if (i % 100 == 0) { // Reset the watchdog ever hundred headers or so // to ensure the connection doesn't timeout for slow // clients theWatchdog.reset(); } } writeLoggedFlushedResponse("."); } } /** * Handles the transaction for getting the article data. */ private void createArticle() { theConfigData.getNNTPRepository().createArticle(new NNTPLineReaderImpl(reader)); } /** * Returns the date from @param input. * The input tokens are assumed to be in format date time [GMT|UTC] . * 'date' is in format [XX]YYMMDD. 'time' is in format 'HHMMSS' * NOTE: This routine could do with some format checks. * * @param argument the date string */ private Date getDateFrom(String argument) { if (argument == null) { throw new NNTPException("Date argument was absent."); } StringTokenizer tok = new StringTokenizer(argument, " "); if (tok.countTokens() < 2) { throw new NNTPException("Date argument was ill-formed."); } String date = tok.nextToken(); String time = tok.nextToken(); boolean utc = ( tok.hasMoreTokens() ); Date d = new Date(); try { StringBuffer dateStringBuffer = new StringBuffer(64) .append(date) .append(" ") .append(time); Date dt = DF_RFC977.parse(dateStringBuffer.toString()); if ( utc ) { dt = new Date(dt.getTime()+UTC_OFFSET); } return dt; } catch ( ParseException pe ) { StringBuffer exceptionBuffer = new StringBuffer(128) .append("Date extraction failed: ") .append(date) .append(",") .append(time) .append(",") .append(utc); throw new NNTPException(exceptionBuffer.toString()); } } /** * Returns the list of articles that match the range. * * A precondition of this method is that the selected * group be non-null. The current article pointer must * be valid if no range is explicitly provided. * * @return null indicates insufficient information to * fetch the list of articles */ private NNTPArticle[] getRange(String range) { // check for msg id if ( isMessageId(range)) { NNTPArticle article = theConfigData.getNNTPRepository().getArticleFromID(range); return ( article == null ) ? new NNTPArticle[0] : new NNTPArticle[] { article }; } if ( range == null ) { range = "" + currentArticleNumber; } int start = -1; int end = -1; int idx = range.indexOf('-'); if ( idx == -1 ) { start = Integer.parseInt(range); end = start; } else { start = Integer.parseInt(range.substring(0,idx)); if ( (idx + 1) == range.length() ) { end = group.getLastArticleNumber(); } else { end = Integer.parseInt(range.substring(idx + 1)); } } List list = new ArrayList(); for ( int i = start ; i <= end ; i++ ) { NNTPArticle article = group.getArticle(i); if ( article != null ) { list.add(article); } } return (NNTPArticle[])list.toArray(new NNTPArticle[0]); } /** * Return whether the user associated with the connection (possibly no * user) is authorized to execute the command. * * @param the command being tested * @return whether the command is authorized */ private boolean isAuthorized(String command) { isAlreadyAuthenticated = isAlreadyAuthenticated || isAuthenticated(); if (isAlreadyAuthenticated) { return true; } // some commands are authorized, even if the user is not authenticated boolean allowed = command.equals("AUTHINFO"); allowed = allowed || command.equals("MODE"); allowed = allowed || command.equals("QUIT"); return allowed; } /** * Return whether the connection has been authenticated. * * @return whether the connection has been authenticated. */ private boolean isAuthenticated() { if ( theConfigData.isAuthRequired() ) { if ((user != null) && (password != null) && (theConfigData.getUsersRepository() != null)) { return theConfigData.getUsersRepository().test(user,password); } else { return false; } } else { return true; } } /** * Tests a string to see whether it is formatted as a message * ID. * * @param testString the string to test * * @return whether the string is a candidate message ID */ private static boolean isMessageId(String testString) { if ((testString != null) && (testString.startsWith("<")) && (testString.endsWith(">"))) { return true; } else { return false; } } /** * This method logs at a "DEBUG" level the response string that * was sent to the SMTP client. The method is provided largely * as syntactic sugar to neaten up the code base. It is declared * private and final to encourage compiler inlining. * * @param responseString the response string sent to the client */ private final void logResponseString(String responseString) { if (getLogger().isDebugEnabled()) { getLogger().debug("Sent: " + responseString); } } /** * Write and flush a response string. The response is also logged. * Should be used for the last line of a multi-line response or * for a single line response. * * @param responseString the response string sent to the client */ final void writeLoggedFlushedResponse(String responseString) { writer.println(responseString); writer.flush(); logResponseString(responseString); } /** * Write a response string. The response is also logged. * Used for multi-line responses. * * @param responseString the response string sent to the client */ final void writeLoggedResponse(String responseString) { writer.println(responseString); logResponseString(responseString); } /** * A private inner class which serves as an adaptor * between the WatchdogTarget interface and this * handler class. */ private class NNTPWatchdogTarget implements WatchdogTarget { /** * @see org.apache.james.util.watchdog.WatchdogTarget#execute() */ public void execute() { NNTPHandler.this.idleClose(); } } }
package brix.plugin.site.node.tilepage; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.jcr.Node; import org.apache.wicket.model.IModel; import brix.Brix; import brix.BrixNodeModel; import brix.exception.NodeNotFoundException; import brix.jcr.api.JcrNode; import brix.jcr.api.JcrNodeIterator; import brix.jcr.api.JcrPropertyIterator; import brix.jcr.api.JcrSession; import brix.jcr.wrapper.BrixFileNode; import brix.jcr.wrapper.BrixNode; import brix.plugin.site.SitePlugin; import brix.plugin.site.node.tilepage.admin.Tile; import brix.plugin.site.node.tilepage.markup.TilePageMarkupSource; import brix.web.nodepage.markup.Item; import brix.web.nodepage.markup.variable.VariableKeyProvider; import brix.web.nodepage.markup.variable.VariableTransformer; import brix.web.nodepage.markup.variable.VariableValueProvider; public abstract class TileContainerNode extends BrixFileNode implements VariableValueProvider, VariableKeyProvider { public TileContainerNode(Node delegate, JcrSession session) { super(delegate, session); } /** Name of markup attribute used to identify tile id inside brix:tile tag */ public static final String MARKUP_TILE_ID = "id"; /** Name of the Tile nodes(s) */ public static final String TILE_NODE_NAME = Brix.NS_PREFIX + "tile"; /** JCR type of Tile nodes */ public static final String JCR_TYPE_BRIX_TILE = Brix.NS_PREFIX + "tile"; private static class Properties { public static final String TITLE = Brix.NS_PREFIX + "title"; public static final String TEMPLATE = Brix.NS_PREFIX + "template"; public static final String REQUIRES_SSL = Brix.NS_PREFIX + "requiresSSL"; public static final String TILE_ID = Brix.NS_PREFIX + "tileId"; public static final String TILE_CLASS = Brix.NS_PREFIX + "tileClass"; } public String getTitle() { if (hasProperty(Properties.TITLE)) return getProperty(Properties.TITLE).getString(); else return null; } public void setTitle(String title) { setProperty(Properties.TITLE, title); } public BrixNode getTile(String id) { return getTile(this, id); } public static BrixNode getTile(BrixNode container, String id) { if (id == null) { throw new IllegalArgumentException("tile id cannot be null"); } JcrNodeIterator iterator = container.getNodes(TILE_NODE_NAME); while (iterator.hasNext()) { BrixNode node = (BrixNode) iterator.nextNode(); if (node.isNodeType(JCR_TYPE_BRIX_TILE) && id.equals(getTileId(node))) { return node; } } return null; } public List<BrixNode> getTileNodes() { return getTileNodes(this); } public static List<BrixNode> getTileNodes(BrixNode container) { List<BrixNode> result = new ArrayList<BrixNode>(); JcrNodeIterator iterator = container.getNodes(TILE_NODE_NAME); while (iterator.hasNext()) { BrixNode node = (BrixNode) iterator.nextNode(); if (node.isNodeType(JCR_TYPE_BRIX_TILE)) { result.add(node); } } return result; } public static String getTileId(BrixNode tile) { if (tile.hasProperty(Properties.TILE_ID)) { return tile.getProperty(Properties.TILE_ID).getString(); } else { return null; } } public static String getTileClassName(BrixNode tile) { if (tile.hasProperty(Properties.TILE_CLASS)) { return tile.getProperty(Properties.TILE_CLASS).getString(); } else { return null; } } public String getTileClassName(String tileId) { BrixNode tile = getTile(tileId); if (tile != null) { return getTileClassName(tile); } else { return null; } } public TileTemplateNode getTemplate() { if (hasProperty(Properties.TEMPLATE)) { return (TileTemplateNode) getProperty(Properties.TEMPLATE).getNode(); } else { return null; } } public void setTemplate(BrixNode node) { setProperty(Properties.TEMPLATE, node); } public void setTemplatePath(String path) { if (path == null) { setTemplate(null); } else { BrixNode node = (BrixNode) SitePlugin.get().nodeForPath(this, path); if (node == null) { throw new NodeNotFoundException("No node found on path '" + path + "'."); } setTemplate((BrixNode) node); } } public String getTemplatePath() { BrixNode template = getTemplate(); return template != null ? SitePlugin.get().pathForNode(template) : null; } public BrixNode createTile(String tileId, String typeName) { return createTile(this, tileId, typeName); } public static BrixNode createTile(BrixNode container, String tileId, String typeName) { if (tileId == null) { throw new IllegalArgumentException("Argument 'tileId' may not be null."); } if (typeName == null) { throw new IllegalArgumentException("Argument 'typeName' may not be null."); } // TODO this check needs to be fixed? // if (isValidNodeName(tileId) == false) // node name."); // if (hasNode(tileId)) // throw new BrixException("Tile with id '" + tileId + "' already // exists."); BrixNode tile = (BrixNode) container.addNode(TILE_NODE_NAME, JCR_TYPE_BRIX_TILE); tile.setProperty(Properties.TILE_ID, tileId); tile.setProperty(Properties.TILE_CLASS, typeName); return tile; } public void setRequiresSSL(boolean value) { if (value == false) { setProperty(Properties.REQUIRES_SSL, (String) null); } else { setProperty(Properties.REQUIRES_SSL, true); } } public boolean isRequiresSSL() { if (hasProperty(Properties.REQUIRES_SSL)) { return getProperty(Properties.REQUIRES_SSL).getBoolean(); } else { return false; } } public boolean requiresSSL() { return isRequiresSSL() || anyTileRequiresSSL(); } @Override public Protocol getRequiredProtocol() { if (requiresSSL()) { return Protocol.HTTPS; } else { return Protocol.HTTP; } } public TileNodePlugin getNodePlugin() { return (TileNodePlugin) SitePlugin.get().getNodePluginForNode(this); } private boolean anyTileRequiresSSL() { List<BrixNode> tiles = getTileNodes(); for (BrixNode tileNode : tiles) { String className = getTileClassName(tileNode); Tile tile = getNodePlugin().getTileOfType(className); IModel<BrixNode> tileNodeModel = new BrixNodeModel(tileNode); if (tile.requiresSSL(tileNodeModel)) return true; } return false; }; private static final String VARIABLES_NODE_NAME = Brix.NS_PREFIX + "variables"; public String getVariableValue(String key) { if (hasNode(VARIABLES_NODE_NAME)) { JcrNode node = getNode(VARIABLES_NODE_NAME); if (node.hasProperty(key)) { return node.getProperty(key).getString(); } } TileTemplateNode template = getTemplate(); if (template != null) { return template.getVariableValue(key); } return null; } public void setVariableValue(String key, String value) { final JcrNode node; if (hasNode(VARIABLES_NODE_NAME)) { node = getNode(VARIABLES_NODE_NAME); } else { node = addNode(VARIABLES_NODE_NAME, "nt:unstructured"); } node.setProperty(key, value); save(); } /** * Returns collection of possible variable keys for this node. */ public Collection<String> getVariableKeys() { Set<String> keys = new HashSet<String>(); TilePageMarkupSource source = new TilePageMarkupSource(this); VariableTransformer transfomer = new VariableTransformer(source, this); Item i = transfomer.nextMarkupItem(); while (i != null) { if (i instanceof VariableKeyProvider) { Collection<String> k = ((VariableKeyProvider) i).getVariableKeys(); if (k != null) { keys.addAll(k); } } i = transfomer.nextMarkupItem(); } return keys; } public List<String> getSavedVariableKeys() { if (hasNode(VARIABLES_NODE_NAME)) { JcrNode node = getNode(VARIABLES_NODE_NAME); List<String> result = new ArrayList<String>(); JcrPropertyIterator i = node.getProperties(); while (i.hasNext()) { result.add(i.nextProperty().getName()); } return result; } else { return Collections.emptyList(); } } }
package net.bytebuddy.implementation; import net.bytebuddy.ByteBuddy; import net.bytebuddy.description.method.MethodDescription; import net.bytebuddy.description.modifier.Ownership; import net.bytebuddy.description.modifier.Visibility; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.dynamic.DynamicType; import net.bytebuddy.dynamic.loading.ClassLoadingStrategy; import net.bytebuddy.dynamic.scaffold.FieldLocator; import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy; import net.bytebuddy.implementation.bytecode.StackManipulation; import net.bytebuddy.implementation.bytecode.assign.Assigner; import net.bytebuddy.implementation.bytecode.constant.TextConstant; import net.bytebuddy.implementation.bytecode.member.MethodReturn; import net.bytebuddy.matcher.ElementMatchers; import net.bytebuddy.test.utility.CallTraceable; import net.bytebuddy.test.utility.JavaVersionRule; import net.bytebuddy.test.utility.MockitoRule; import net.bytebuddy.utility.JavaConstant; import net.bytebuddy.utility.JavaType; import org.hamcrest.CoreMatchers; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.MethodRule; import org.junit.rules.TestRule; import org.mockito.Mock; import org.mockito.Mockito; import java.lang.reflect.Method; import java.util.concurrent.Callable; import static net.bytebuddy.matcher.ElementMatchers.*; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.*; public class MethodCallTest { private static final String FOO = "foo", BAR = "bar", QUX = "qux", INVOKE_FOO = "invokeFoo"; private static final String SINGLE_DEFAULT_METHOD = "net.bytebuddy.test.precompiled.SingleDefaultMethodInterface"; @Rule public TestRule methodRule = new MockitoRule(this); @Rule public MethodRule javaVersionRule = new JavaVersionRule(); @Mock private Assigner nonAssigner; private static Object makeMethodType(Class<?> returnType, Class<?>... parameterType) throws Exception { return JavaType.METHOD_TYPE.load().getDeclaredMethod("methodType", Class.class, Class[].class).invoke(null, returnType, parameterType); } private static Object makeMethodHandle() throws Exception { Object lookup = Class.forName("java.lang.invoke.MethodHandles").getDeclaredMethod("publicLookup").invoke(null); return JavaType.METHOD_HANDLES_LOOKUP.load().getDeclaredMethod("findStatic", Class.class, String.class, JavaType.METHOD_TYPE.load()) .invoke(lookup, Foo.class, BAR, makeMethodType(String.class, Object.class, Object.class)); } @Before public void setUp() throws Exception { when(nonAssigner.assign(Mockito.any(TypeDescription.Generic.class), Mockito.any(TypeDescription.Generic.class), Mockito.any(Assigner.Typing.class))).thenReturn(StackManipulation.Illegal.INSTANCE); } @Test public void testStaticMethodInvocationWithoutArguments() throws Exception { DynamicType.Loaded<SimpleMethod> loaded = new ByteBuddy() .subclass(SimpleMethod.class) .method(named(FOO)) .intercept(MethodCall.invoke(SimpleMethod.class.getDeclaredMethod(BAR))) .make() .load(SimpleMethod.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); SimpleMethod instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.foo(), is(BAR)); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(SimpleMethod.class))); assertThat(instance, instanceOf(SimpleMethod.class)); } @Test public void testExternalStaticMethodInvocationWithoutArguments() throws Exception { DynamicType.Loaded<SimpleMethod> loaded = new ByteBuddy() .subclass(SimpleMethod.class) .method(named(FOO)) .intercept(MethodCall.invoke(StaticExternalMethod.class.getDeclaredMethod(BAR))) .make() .load(SimpleMethod.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); SimpleMethod instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.foo(), is(BAR)); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(SimpleMethod.class))); assertThat(instance, instanceOf(SimpleMethod.class)); } @Test public void testInstanceMethodInvocationWithoutArguments() throws Exception { DynamicType.Loaded<InstanceMethod> loaded = new ByteBuddy() .subclass(InstanceMethod.class) .method(named(FOO)) .intercept(MethodCall.invoke(InstanceMethod.class.getDeclaredMethod(BAR))) .make() .load(SimpleMethod.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); InstanceMethod instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.foo(), is(BAR)); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(InstanceMethod.class))); assertThat(instance, instanceOf(InstanceMethod.class)); } @Test public void testInstanceMethodInvocationWithoutArgumentsByMatcher() throws Exception { DynamicType.Loaded<InstanceMethod> loaded = new ByteBuddy() .subclass(InstanceMethod.class) .method(named(FOO)) .intercept(MethodCall.invoke(named(BAR))) .make() .load(SimpleMethod.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); InstanceMethod instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.foo(), is(BAR)); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(InstanceMethod.class))); assertThat(instance, instanceOf(InstanceMethod.class)); } @Test public void testMethodInvocationUsingStackManipulation() throws Exception { DynamicType.Loaded<SimpleMethod> loaded = new ByteBuddy() .subclass(SimpleMethod.class) .method(named(FOO)) .intercept(MethodCall.invoke(String.class.getMethod("toUpperCase")).on(new TextConstant(FOO), String.class)) .make() .load(SimpleMethod.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); SimpleMethod instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.foo(), is(FOO.toUpperCase())); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(SimpleMethod.class))); assertThat(instance, instanceOf(SimpleMethod.class)); } @Test(expected = IllegalStateException.class) public void testMatchedCallAmbiguous() throws Exception { new ByteBuddy() .subclass(InstanceMethod.class) .method(named(FOO)) .intercept(MethodCall.invoke(ElementMatchers.any())) .make(); } @Test(expected = IllegalArgumentException.class) public void testOnArgumentInvocationNegativeArgument() throws Exception { MethodCall.invoke(Object.class.getDeclaredMethod("toString")).onArgument(-1); } @Test(expected = IllegalArgumentException.class) public void testOnArgumentInvocationNonExisting() throws Exception { new ByteBuddy() .subclass(ArgumentCall.class) .method(isDeclaredBy(ArgumentCall.class)) .intercept(MethodCall.invoke(Object.class.getDeclaredMethod("toString")).onArgument(10)) .make(); } @Test public void testInvokeOnArgument() throws Exception { DynamicType.Loaded<ArgumentCall> loaded = new ByteBuddy() .subclass(ArgumentCall.class) .method(isDeclaredBy(ArgumentCall.class)) .intercept(MethodCall.invoke(ArgumentCall.Target.class.getDeclaredMethod("foo")).onArgument(0)) .make() .load(ArgumentCall.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); ArgumentCall instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.foo(new ArgumentCall.Target(BAR)), is(BAR)); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(InstanceMethod.class))); assertThat(instance, instanceOf(ArgumentCall.class)); } @Test public void testInvokeOnArgumentUsingMatcher() throws Exception { DynamicType.Loaded<ArgumentCall> loaded = new ByteBuddy() .subclass(ArgumentCall.class) .method(named("foo")) .intercept(MethodCall.invoke(named("toUpperCase").and(takesArguments(0))).onMethodCall(MethodCall.invoke(named("foo")).onArgument(0))) .make() .load(ArgumentCall.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); ArgumentCall instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.foo(new ArgumentCall.Target("foo")), is("FOO")); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(InstanceMethod.class))); assertThat(instance, instanceOf(ArgumentCall.class)); } @Test(expected = IllegalStateException.class) public void testInvokeOnArgumentNonAssignable() throws Exception { new ByteBuddy() .subclass(ArgumentCallDynamic.class) .method(isDeclaredBy(ArgumentCallDynamic.class)) .intercept(MethodCall.invoke(ArgumentCallDynamic.Target.class.getDeclaredMethod("foo")).onArgument(0)) .make(); } @Test(expected = IllegalStateException.class) public void testInvokeOnArgumentNonVirtual() throws Exception { new ByteBuddy() .subclass(ArgumentCallDynamic.class) .method(isDeclaredBy(ArgumentCallDynamic.class)) .intercept(MethodCall.invoke(NonVirtual.class.getDeclaredMethod("foo")).onArgument(0)) .make(); } @Test public void testInvokeOnArgumentDynamic() throws Exception { DynamicType.Loaded<ArgumentCallDynamic> loaded = new ByteBuddy() .subclass(ArgumentCallDynamic.class) .method(isDeclaredBy(ArgumentCallDynamic.class)) .intercept(MethodCall.invoke(ArgumentCallDynamic.Target.class.getDeclaredMethod("foo")).onArgument(0) .withAssigner(Assigner.DEFAULT, Assigner.Typing.DYNAMIC)) .make() .load(ArgumentCallDynamic.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); ArgumentCallDynamic instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.foo(new ArgumentCallDynamic.Target(BAR)), is(BAR)); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(InstanceMethod.class))); assertThat(instance, instanceOf(ArgumentCallDynamic.class)); } @Test public void testInvokeOnMethodCall() throws Exception { DynamicType.Loaded<MethodCallChaining> loaded = new ByteBuddy() .subclass(MethodCallChaining.class) .method(named("foobar")) .intercept(MethodCall.invoke(String.class.getMethod("toUpperCase")) .onMethodCall(MethodCall.invoke(named("bar")))) .make() .load(MethodCallChaining.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); MethodCallChaining instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.foobar(), is("BAR")); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(InstanceMethod.class))); assertThat(instance, instanceOf(MethodCallChaining.class)); } @Test public void testInvokeOnMethodCallUsingMatcher() throws Exception { DynamicType.Loaded<MethodCallChaining> loaded = new ByteBuddy() .subclass(MethodCallChaining.class) .method(named("foobar")) .intercept(MethodCall.invoke(named("toUpperCase").and(takesArguments(0))) .onMethodCall(MethodCall.invoke(named("bar")))) .make() .load(MethodCallChaining.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); MethodCallChaining instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.foobar(), is("BAR")); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(InstanceMethod.class))); assertThat(instance, instanceOf(MethodCallChaining.class)); } @Test(expected = IllegalStateException.class) public void testInvokeOnIncompatibleMethodCall() throws Exception { new ByteBuddy() .subclass(MethodCallChaining.class) .method(named("foobar")) .intercept(MethodCall.invoke(Integer.class.getMethod("toString")) .onMethodCall(MethodCall.invoke(named("bar")))) .make(); } @Test public void testStaticOnStaticFieldFromAnotherClass() throws Exception { DynamicType.Loaded<Object> loaded = new ByteBuddy() .subclass(Object.class) .invokable(isTypeInitializer()) .intercept(MethodCall.invoke(named("println").and(takesArguments(Object.class))) .onField("out", new FieldLocator.ForExactType.Factory(TypeDescription.ForLoadedType.of(System.class))) .with("")) .make() .load(Object.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(0)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); Object instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance, instanceOf(Object.class)); } @Test public void testStaticFieldExplicit() throws Exception { DynamicType.Loaded<Object> loaded = new ByteBuddy() .subclass(Object.class) .invokable(isTypeInitializer()) .intercept(MethodCall.invoke(isEquals()) .onField(System.class.getField("out")) .with("")) .make() .load(Object.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(0)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); Object instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance, instanceOf(Object.class)); } @Test public void testOnStaticFieldFromAnotherClass() throws Exception { DynamicType.Loaded<Object> loaded = new ByteBuddy() .subclass(Object.class) .defineMethod("foo", void.class) .intercept(MethodCall.invoke(isEquals()) .onField("out", new FieldLocator.ForExactType.Factory(TypeDescription.ForLoadedType.of(System.class))) .with("fooCall")) .make() .load(Object.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); Object instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance, instanceOf(Object.class)); } @Test public void testOnFieldUsingMatcher() throws Exception { DynamicType.Loaded<MethodCallOnField> loaded = new ByteBuddy() .subclass(MethodCallOnField.class) .method(named("foo")) .intercept(MethodCall.invoke(named("trim")).onField("foo")) .make() .load(MethodCallOnField.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredMethod(FOO), not(nullValue(Method.class))); assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); MethodCallOnField instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); instance.foo = " abc "; assertThat(instance, instanceOf(MethodCallOnField.class)); assertThat(instance.foo(), is("abc")); } @Test public void testSuperConstructorInvocationWithoutArguments() throws Exception { DynamicType.Loaded<Object> loaded = new ByteBuddy() .subclass(Object.class) .constructor(ElementMatchers.any()) .intercept(MethodCall.invoke(Object.class.getDeclaredConstructor()).onSuper()) .make() .load(Object.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(0)); assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); Object instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(Object.class))); assertThat(instance, instanceOf(Object.class)); } @Test public void testSuperConstructorInvocationUsingMatcher() throws Exception { assertThat(new ByteBuddy() .subclass(Object.class, ConstructorStrategy.Default.NO_CONSTRUCTORS) .defineConstructor(Visibility.PUBLIC) .intercept(MethodCall.invoke(isConstructor()).onSuper()) .make() .load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER) .getLoaded() .getConstructor() .newInstance(), notNullValue(Object.class)); } @Test public void testObjectConstruction() throws Exception { DynamicType.Loaded<SelfReference> loaded = new ByteBuddy() .subclass(SelfReference.class) .method(isDeclaredBy(SelfReference.class)) .intercept(MethodCall.construct(SelfReference.class.getDeclaredConstructor())) .make() .load(SelfReference.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); SelfReference instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); SelfReference created = instance.foo(); assertThat(created.getClass(), CoreMatchers.<Class<?>>is(SelfReference.class)); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(SelfReference.class))); assertThat(instance, instanceOf(SelfReference.class)); assertThat(created, not(instance)); } @Test public void testSelfInvocation() throws Exception { SuperMethodInvocation delegate = mock(SuperMethodInvocation.class); when(delegate.foo()).thenReturn(FOO); DynamicType.Loaded<SuperMethodInvocation> loaded = new ByteBuddy() .subclass(SuperMethodInvocation.class) .method(takesArguments(0).and(named(FOO))) .intercept(MethodCall.invokeSelf().on(delegate)) .make() .load(SuperMethodInvocation.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredMethod(FOO), not(nullValue(Method.class))); assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(1)); SuperMethodInvocation instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(SuperMethodInvocation.class))); assertThat(instance, instanceOf(SuperMethodInvocation.class)); assertThat(instance.foo(), is(FOO)); verify(delegate).foo(); verifyNoMoreInteractions(delegate); } @Test public void testSuperInvocation() throws Exception { DynamicType.Loaded<SuperMethodInvocation> loaded = new ByteBuddy() .subclass(SuperMethodInvocation.class) .method(takesArguments(0).and(named(FOO))) .intercept(MethodCall.invokeSuper()) .make() .load(SuperMethodInvocation.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredMethod(FOO), not(nullValue(Method.class))); assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); SuperMethodInvocation instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(SuperMethodInvocation.class))); assertThat(instance, instanceOf(SuperMethodInvocation.class)); assertThat(instance.foo(), is(FOO)); } @Test public void testWithExplicitArgumentConstantPool() throws Exception { DynamicType.Loaded<MethodCallWithExplicitArgument> loaded = new ByteBuddy() .subclass(MethodCallWithExplicitArgument.class) .method(isDeclaredBy(MethodCallWithExplicitArgument.class)) .intercept(MethodCall.invokeSuper().with(FOO)) .make() .load(MethodCallWithExplicitArgument.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredMethod(FOO, String.class), not(nullValue(Method.class))); assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); MethodCallWithExplicitArgument instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(MethodCallWithExplicitArgument.class))); assertThat(instance, instanceOf(MethodCallWithExplicitArgument.class)); assertThat(instance.foo(BAR), is(FOO)); } @Test(expected = IllegalStateException.class) public void testWithExplicitArgumentConstantPoolNonAssignable() throws Exception { new ByteBuddy() .subclass(MethodCallWithExplicitArgument.class) .method(isDeclaredBy(MethodCallWithExplicitArgument.class)) .intercept(MethodCall.invokeSuper().with(FOO).withAssigner(nonAssigner, Assigner.Typing.STATIC)) .make(); } @Test public void testWithExplicitArgumentStackManipulation() throws Exception { DynamicType.Loaded<MethodCallWithExplicitArgument> loaded = new ByteBuddy() .subclass(MethodCallWithExplicitArgument.class) .method(isDeclaredBy(MethodCallWithExplicitArgument.class)) .intercept(MethodCall.invokeSuper().with(new TextConstant(FOO), String.class)) .make() .load(MethodCallWithExplicitArgument.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredMethod(FOO, String.class), not(nullValue(Method.class))); assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); MethodCallWithExplicitArgument instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(MethodCallWithExplicitArgument.class))); assertThat(instance, instanceOf(MethodCallWithExplicitArgument.class)); assertThat(instance.foo(BAR), is(FOO)); } @Test public void testWithExplicitArgumentField() throws Exception { DynamicType.Loaded<MethodCallWithExplicitArgument> loaded = new ByteBuddy() .subclass(MethodCallWithExplicitArgument.class) .method(isDeclaredBy(MethodCallWithExplicitArgument.class)) .intercept(MethodCall.invokeSuper().withReference(FOO)) .make() .load(MethodCallWithExplicitArgument.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredMethod(FOO, String.class), not(nullValue(Method.class))); assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(1)); MethodCallWithExplicitArgument instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(MethodCallWithExplicitArgument.class))); assertThat(instance, instanceOf(MethodCallWithExplicitArgument.class)); assertThat(instance.foo(BAR), is(FOO)); } @Test(expected = IllegalStateException.class) public void testWithExplicitArgumentFieldNonAssignable() throws Exception { new ByteBuddy() .subclass(MethodCallWithExplicitArgument.class) .method(isDeclaredBy(MethodCallWithExplicitArgument.class)) .intercept(MethodCall.invokeSuper().withReference(FOO).withAssigner(nonAssigner, Assigner.Typing.STATIC)) .make(); } @Test public void testWithArgument() throws Exception { DynamicType.Loaded<MethodCallWithExplicitArgument> loaded = new ByteBuddy() .subclass(MethodCallWithExplicitArgument.class) .method(isDeclaredBy(MethodCallWithExplicitArgument.class)) .intercept(MethodCall.invokeSuper().withArgument(0)) .make() .load(MethodCallWithExplicitArgument.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredMethod(FOO, String.class), not(nullValue(Method.class))); assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); MethodCallWithExplicitArgument instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(MethodCallWithExplicitArgument.class))); assertThat(instance, instanceOf(MethodCallWithExplicitArgument.class)); assertThat(instance.foo(BAR), is(BAR)); } @Test public void testWithAllArguments() throws Exception { DynamicType.Loaded<MethodCallWithExplicitArgument> loaded = new ByteBuddy() .subclass(MethodCallWithExplicitArgument.class) .method(isDeclaredBy(MethodCallWithExplicitArgument.class)) .intercept(MethodCall.invokeSuper().withAllArguments()) .make() .load(MethodCallWithExplicitArgument.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredMethod(FOO, String.class), not(nullValue(Method.class))); assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); MethodCallWithExplicitArgument instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(MethodCallWithExplicitArgument.class))); assertThat(instance, instanceOf(MethodCallWithExplicitArgument.class)); assertThat(instance.foo(BAR), is(BAR)); } @Test public void testWithAllArgumentsTwoArguments() throws Exception { DynamicType.Loaded<MethodCallWithTwoExplicitArguments> loaded = new ByteBuddy() .subclass(MethodCallWithTwoExplicitArguments.class) .method(isDeclaredBy(MethodCallWithTwoExplicitArguments.class)) .intercept(MethodCall.invokeSuper().withAllArguments()) .make() .load(MethodCallWithTwoExplicitArguments.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredMethod(FOO, String.class, String.class), not(nullValue(Method.class))); assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); MethodCallWithTwoExplicitArguments instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(MethodCallWithTwoExplicitArguments.class))); assertThat(instance, instanceOf(MethodCallWithTwoExplicitArguments.class)); assertThat(instance.foo(FOO, BAR), is(FOO + BAR)); } @Test public void testWithArgumentsAsArray() throws Exception { DynamicType.Loaded<ArrayConsuming> loaded = new ByteBuddy() .subclass(ArrayConsuming.class) .method(named(FOO)) .intercept(MethodCall.invoke(ArrayConsuming.class.getDeclaredMethod(BAR, String[].class)).withArgumentArray()) .make() .load(ArrayConsuming.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredMethod(FOO, String.class, String.class), not(nullValue(Method.class))); assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); ArrayConsuming instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(ArrayConsuming.class))); assertThat(instance, instanceOf(ArrayConsuming.class)); assertThat(instance.foo(FOO, BAR), is(FOO + BAR)); } @Test public void testWithArgumentsFromArray() throws Exception { DynamicType.Loaded<MethodCallWithExplicitArgument> loaded = new ByteBuddy() .subclass(MethodCallWithExplicitArgument.class) .implement(MethodCallDelegator.class) .intercept(MethodCall.invoke(MethodCallWithExplicitArgument.class.getDeclaredMethod("foo", String.class)).withArgumentArrayElements(0, 1)) .make() .load(MethodCallDelegator.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredMethod(INVOKE_FOO, String[].class), not(nullValue(Method.class))); assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); MethodCallDelegator instance = (MethodCallDelegator) loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(MethodCallWithExplicitArgument.class))); assertThat(instance, instanceOf(MethodCallDelegator.class)); assertThat(instance.invokeFoo(BAR), is(BAR)); } @Test public void testWithArgumentsFromArrayComplete() throws Exception { DynamicType.Loaded<MethodCallWithExplicitArgument> loaded = new ByteBuddy() .subclass(MethodCallWithExplicitArgument.class) .implement(MethodCallDelegator.class) .intercept(MethodCall.invoke(MethodCallWithExplicitArgument.class.getDeclaredMethod("foo", String.class)).withArgumentArrayElements(0)) .make() .load(MethodCallDelegator.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredMethod(INVOKE_FOO, String[].class), not(nullValue(Method.class))); assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); MethodCallDelegator instance = (MethodCallDelegator) loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(MethodCallWithExplicitArgument.class))); assertThat(instance, instanceOf(MethodCallDelegator.class)); assertThat(instance.invokeFoo(BAR), is(BAR)); } @Test public void testWithArgumentsFromArrayExplicitSize() throws Exception { DynamicType.Loaded<MethodCallWithExplicitArgument> loaded = new ByteBuddy() .subclass(MethodCallWithExplicitArgument.class) .implement(MethodCallDelegator.class) .intercept(MethodCall.invoke(MethodCallWithExplicitArgument.class.getDeclaredMethod("foo", String.class)).withArgumentArrayElements(0, 1, 1)) .make() .load(MethodCallDelegator.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredMethod(INVOKE_FOO, String[].class), not(nullValue(Method.class))); assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); MethodCallDelegator instance = (MethodCallDelegator) loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(MethodCallWithExplicitArgument.class))); assertThat(instance, instanceOf(MethodCallDelegator.class)); assertThat(instance.invokeFoo(FOO, BAR, FOO), is(BAR)); } @Test(expected = IllegalStateException.class) public void testWithArgumentsFromArrayDoesNotExist() throws Exception { new ByteBuddy() .subclass(MethodCallWithExplicitArgument.class) .implement(MethodCallDelegator.class) .intercept(MethodCall.invoke(MethodCallWithExplicitArgument.class.getDeclaredMethod("foo", String.class)).withArgumentArrayElements(1, 1)) .make(); } @Test(expected = IllegalStateException.class) public void testWithArgumentsFromArrayDoesNotExistCompleteArray() throws Exception { new ByteBuddy() .subclass(MethodCallWithExplicitArgument.class) .implement(MethodCallDelegator.class) .intercept(MethodCall.invoke(MethodCallWithExplicitArgument.class.getDeclaredMethod("foo", String.class)).withArgumentArrayElements(1)) .make(); } @Test(expected = IllegalStateException.class) public void testWithArgumentsFromArrayIllegalType() throws Exception { new ByteBuddy() .subclass(MethodCallWithExplicitArgument.class) .implement(IllegalMethodCallDelegator.class) .intercept(MethodCall.invoke(MethodCallWithExplicitArgument.class.getDeclaredMethod("foo", String.class)).withArgumentArrayElements(0, 1)) .make(); } @Test(expected = IllegalStateException.class) public void testWithArgumentsFromArrayIllegalTypeCompleteArray() throws Exception { new ByteBuddy() .subclass(MethodCallWithExplicitArgument.class) .implement(IllegalMethodCallDelegator.class) .intercept(MethodCall.invoke(MethodCallWithExplicitArgument.class.getDeclaredMethod("foo", String.class)).withArgumentArrayElements(0)) .make(); } @Test(expected = IllegalArgumentException.class) public void testNegativeIndex() throws Exception { MethodCall.invoke(MethodCallWithExplicitArgument.class.getDeclaredMethod("foo", String.class)).withArgumentArrayElements(-1, 1); } @Test(expected = IllegalArgumentException.class) public void testNegativeIndexComplete() throws Exception { MethodCall.invoke(MethodCallWithExplicitArgument.class.getDeclaredMethod("foo", String.class)).withArgumentArrayElements(-1); } @Test(expected = IllegalArgumentException.class) public void testNegativeStartIndex() throws Exception { MethodCall.invoke(MethodCallWithExplicitArgument.class.getDeclaredMethod("foo", String.class)).withArgumentArrayElements(0, -1, 1); } @Test(expected = IllegalArgumentException.class) public void testNegativeSize() throws Exception { MethodCall.invoke(MethodCallWithExplicitArgument.class.getDeclaredMethod("foo", String.class)).withArgumentArrayElements(0, 1, -1); } @Test public void testSameSize() throws Exception { MethodCall methodCall = MethodCall.invoke(MethodCallWithExplicitArgument.class.getDeclaredMethod("foo", String.class)); assertThat(methodCall.withArgumentArrayElements(0, 0), sameInstance(methodCall)); } @Test(expected = IllegalStateException.class) public void testWithTooBigParameter() throws Exception { new ByteBuddy() .subclass(MethodCallWithExplicitArgument.class) .method(isDeclaredBy(MethodCallWithExplicitArgument.class)) .intercept(MethodCall.invokeSuper().withArgument(1)) .make(); } @Test(expected = IllegalStateException.class) public void testWithParameterNonAssignable() throws Exception { new ByteBuddy() .subclass(MethodCallWithExplicitArgument.class) .method(isDeclaredBy(MethodCallWithExplicitArgument.class)) .intercept(MethodCall.invokeSuper().withArgument(0).withAssigner(nonAssigner, Assigner.Typing.STATIC)) .make(); } @Test public void testWithField() throws Exception { DynamicType.Loaded<MethodCallWithField> loaded = new ByteBuddy() .subclass(MethodCallWithField.class) .method(isDeclaredBy(MethodCallWithField.class)) .intercept(MethodCall.invokeSuper().withField(FOO)) .make() .load(MethodCallWithField.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredMethod(FOO, String.class), not(nullValue(Method.class))); assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); MethodCallWithField instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); instance.foo = FOO; assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(MethodCallWithField.class))); assertThat(instance, instanceOf(MethodCallWithField.class)); assertThat(instance.foo(BAR), is(FOO)); } @Test(expected = IllegalStateException.class) public void testWithFieldNotExist() throws Exception { new ByteBuddy() .subclass(MethodCallWithField.class) .method(isDeclaredBy(MethodCallWithField.class)) .intercept(MethodCall.invokeSuper().withField(BAR)) .make(); } @Test(expected = IllegalStateException.class) public void testWithFieldNonAssignable() throws Exception { new ByteBuddy() .subclass(MethodCallWithField.class) .method(isDeclaredBy(MethodCallWithField.class)) .intercept(MethodCall.invokeSuper().withField(FOO).withAssigner(nonAssigner, Assigner.Typing.STATIC)) .make(); } @Test public void testWithFieldHierarchyVisibility() throws Exception { DynamicType.Loaded<InvisibleMethodCallWithField> loaded = new ByteBuddy() .subclass(InvisibleMethodCallWithField.class) .method(isDeclaredBy(InvisibleMethodCallWithField.class)) .intercept(MethodCall.invokeSuper().withField(FOO)) .make() .load(InvisibleMethodCallWithField.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredMethod(FOO, String.class), not(nullValue(Method.class))); assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); InvisibleMethodCallWithField instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); ((InvisibleBase) instance).foo = FOO; assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(InvisibleMethodCallWithField.class))); assertThat(instance, instanceOf(InvisibleMethodCallWithField.class)); assertThat(instance.foo(BAR), is(FOO)); } @Test public void testWithThis() throws Exception { DynamicType.Loaded<MethodCallWithThis> loaded = new ByteBuddy() .subclass(MethodCallWithThis.class) .method(isDeclaredBy(MethodCallWithThis.class)) .intercept(MethodCall.invokeSuper().withThis()) .make() .load(MethodCallWithThis.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredMethod(FOO, MethodCallWithThis.class), not(nullValue(Method.class))); assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); MethodCallWithThis instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(MethodCallWithThis.class))); assertThat(instance, instanceOf(MethodCallWithThis.class)); assertThat(instance.foo(null), is(instance)); } @Test public void testWithOwnType() throws Exception { DynamicType.Loaded<MethodCallWithOwnType> loaded = new ByteBuddy() .subclass(MethodCallWithOwnType.class) .method(isDeclaredBy(MethodCallWithOwnType.class)) .intercept(MethodCall.invokeSuper().withOwnType()) .make() .load(MethodCallWithOwnType.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredMethod(FOO, Class.class), not(nullValue(Method.class))); assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); MethodCallWithOwnType instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(MethodCallWithThis.class))); assertThat(instance, instanceOf(MethodCallWithOwnType.class)); assertThat(instance.foo(null), CoreMatchers.<Class<?>>is(loaded.getLoaded())); } @Test public void testInvokeWithMethodCall() throws Exception { DynamicType.Loaded<MethodCallChaining> loaded = new ByteBuddy() .subclass(MethodCallChaining.class) .method(named("foobar")) .intercept(MethodCall.invoke(named("foo")).withMethodCall(MethodCall.invoke(named("bar")))) .make() .load(MethodCallChaining.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); MethodCallChaining instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredMethod("foobar"), not(nullValue(Method.class))); assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); assertThat(instance.foobar(), is("foobar")); } @Test(expected = IllegalStateException.class) public void testStaticInvokeWithMethodCall() throws Exception { new ByteBuddy() .subclass(MethodCallChaining.class) .defineMethod("staticFoobar", String.class, Ownership.STATIC) .intercept(MethodCall.invoke(named("foo")).withMethodCall(MethodCall.invoke(named("bar")))) .make(); } @Test(expected = IllegalStateException.class) public void testInvokeWithIncompatibleMethodCall() throws Exception { new ByteBuddy() .subclass(MethodCallChaining.class) .method(named("foobar")) .intercept(MethodCall.invoke(named("foo")).withMethodCall(MethodCall.invoke(named("someInt")))) .make(); } @Test public void testImplementationAppendingMethod() throws Exception { DynamicType.Loaded<MethodCallAppending> loaded = new ByteBuddy() .subclass(MethodCallAppending.class) .method(isDeclaredBy(MethodCallAppending.class)) .intercept(MethodCall.invokeSuper().andThen(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE))) .make() .load(MethodCallAppending.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredMethod(FOO), not(nullValue(Method.class))); assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); MethodCallAppending instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(MethodCallAppending.class))); assertThat(instance, instanceOf(MethodCallAppending.class)); assertThat(instance.foo(), is((Object) FOO)); instance.assertOnlyCall(FOO); } @Test public void testImplementationAppendingConstructor() throws Exception { DynamicType.Loaded<MethodCallAppending> loaded = new ByteBuddy() .subclass(MethodCallAppending.class) .method(isDeclaredBy(MethodCallAppending.class)) .intercept(MethodCall.construct(Object.class.getDeclaredConstructor()) .andThen(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE))) .make() .load(MethodCallAppending.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredMethod(FOO), not(nullValue(Method.class))); assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); MethodCallAppending instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(MethodCallAppending.class))); assertThat(instance, instanceOf(MethodCallAppending.class)); assertThat(instance.foo(), is((Object) FOO)); instance.assertZeroCalls(); } @Test public void testWithExplicitTarget() throws Exception { Object target = new Object(); DynamicType.Loaded<ExplicitTarget> loaded = new ByteBuddy() .subclass(ExplicitTarget.class) .method(isDeclaredBy(ExplicitTarget.class)) .intercept(MethodCall.invoke(Object.class.getDeclaredMethod("toString")).on(target)) .make() .load(ExplicitTarget.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredMethod(FOO), not(nullValue(Method.class))); assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(1)); ExplicitTarget instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(ExplicitTarget.class))); assertThat(instance, instanceOf(ExplicitTarget.class)); assertThat(instance.foo(), is(target.toString())); } @Test public void testWithFieldTarget() throws Exception { Object target = new Object(); DynamicType.Loaded<ExplicitTarget> loaded = new ByteBuddy() .subclass(ExplicitTarget.class) .defineField(FOO, Object.class, Visibility.PUBLIC) .method(isDeclaredBy(ExplicitTarget.class)) .intercept(MethodCall.invoke(Object.class.getDeclaredMethod("toString")).onField(FOO)) .make() .load(ExplicitTarget.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredMethod(FOO), not(nullValue(Method.class))); assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(1)); ExplicitTarget instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); loaded.getLoaded().getDeclaredField(FOO).set(instance, target); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(ExplicitTarget.class))); assertThat(instance, instanceOf(ExplicitTarget.class)); assertThat(instance.foo(), is(target.toString())); } @Test public void testUnloadedType() throws Exception { DynamicType.Loaded<SimpleMethod> loaded = new ByteBuddy() .subclass(SimpleMethod.class) .method(named(FOO)) .intercept(MethodCall.invoke(Foo.class.getDeclaredMethod(BAR, Object.class, Object.class)).with(TypeDescription.OBJECT, TypeDescription.STRING)) .make() .load(SimpleMethod.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); SimpleMethod instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.foo(), is("" + Object.class + String.class)); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(SimpleMethod.class))); assertThat(instance, instanceOf(SimpleMethod.class)); } @Test @JavaVersionRule.Enforce(value = 7, hotSpot = 7) public void testJava7Types() throws Exception { DynamicType.Loaded<SimpleMethod> loaded = new ByteBuddy() .subclass(SimpleMethod.class) .method(named(FOO)) .intercept(MethodCall.invoke(Foo.class.getDeclaredMethod(BAR, Object.class, Object.class)).with(makeMethodHandle(), makeMethodType(void.class))) .make() .load(SimpleMethod.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); SimpleMethod instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.foo(), is("" + makeMethodHandle() + makeMethodType(void.class))); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(SimpleMethod.class))); assertThat(instance, instanceOf(SimpleMethod.class)); } @Test @JavaVersionRule.Enforce(value = 7, hotSpot = 7) public void testJava7TypesExplicit() throws Exception { DynamicType.Loaded<SimpleMethod> loaded = new ByteBuddy() .subclass(SimpleMethod.class) .method(named(FOO)) .intercept(MethodCall.invoke(Foo.class.getDeclaredMethod(BAR, Object.class, Object.class)) .with(JavaConstant.MethodHandle.ofLoaded(makeMethodHandle()), JavaConstant.MethodType.ofLoaded(makeMethodType(void.class)))) .make() .load(SimpleMethod.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0)); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); assertThat(loaded.getLoaded().getDeclaredFields().length, is(0)); SimpleMethod instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.foo(), is("" + makeMethodHandle() + makeMethodType(void.class))); assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(SimpleMethod.class))); assertThat(instance, instanceOf(SimpleMethod.class)); } @Test @JavaVersionRule.Enforce(8) public void testDefaultMethod() throws Exception { DynamicType.Loaded<Object> loaded = new ByteBuddy() .subclass(Object.class) .implement(Class.forName(SINGLE_DEFAULT_METHOD)) .method(ElementMatchers.not(isDeclaredBy(Object.class))) .intercept(MethodCall.invoke(Class.forName(SINGLE_DEFAULT_METHOD).getDeclaredMethod(FOO)).onDefault()) .make() .load(Class.forName(SINGLE_DEFAULT_METHOD).getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1)); Method method = loaded.getLoaded().getDeclaredMethod(FOO); Object instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(method.invoke(instance), is((Object) FOO)); } @Test public void testCallable() throws Exception { Traceable traceable = new Traceable(); DynamicType.Loaded<SimpleStringMethod> loaded = new ByteBuddy() .subclass(SimpleStringMethod.class) .method(isDeclaredBy(SimpleStringMethod.class)) .intercept(MethodCall.call(traceable)) .make() .load(SimpleStringMethod.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoaded().getDeclaredConstructor().newInstance().foo(), is(FOO)); traceable.assertOnlyCall(FOO); } @Test public void testRunnable() throws Exception { Traceable traceable = new Traceable(); DynamicType.Loaded<SimpleStringMethod> loaded = new ByteBuddy() .subclass(SimpleStringMethod.class) .method(isDeclaredBy(SimpleStringMethod.class)) .intercept(MethodCall.run(traceable)) .make() .load(SimpleStringMethod.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); assertThat(loaded.getLoaded().getDeclaredConstructor().newInstance().foo(), nullValue(String.class)); traceable.assertOnlyCall(FOO); } @Test public void testFieldSetting() throws Exception { DynamicType.Loaded<FieldSetting> loaded = new ByteBuddy() .subclass(FieldSetting.class) .method(named(FOO)) .intercept(MethodCall.invoke(FieldSetting.class.getMethod(BAR)).setsField(FieldSetting.class.getField(FOO))) .make() .load(FieldSetting.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); FieldSetting instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); instance.foo(); assertThat(instance.foo, is((Object) instance.bar())); } @Test public void testFieldSettingWithMatcher() throws Exception { DynamicType.Loaded<FieldSetting> loaded = new ByteBuddy() .subclass(FieldSetting.class) .method(named(FOO)) .intercept(MethodCall.invoke(FieldSetting.class.getMethod(BAR)).setsField(ElementMatchers.is(FieldSetting.class.getField(FOO)))) .make() .load(FieldSetting.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); FieldSetting instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); instance.foo(); assertThat(instance.foo, is((Object) instance.bar())); } @Test(expected = IllegalStateException.class) public void testFieldSettingLast() throws Exception { new ByteBuddy() .subclass(FieldSetting.class) .method(named(QUX)) .intercept(MethodCall.invoke(FieldSetting.class.getMethod(BAR)).setsField(FieldSetting.class.getField(FOO))) .make(); } @Test public void testFieldSettingLastChained() throws Exception { DynamicType.Loaded<FieldSetting> loaded = new ByteBuddy() .subclass(FieldSetting.class) .method(named(QUX)) .intercept(MethodCall.invoke(FieldSetting.class.getMethod(BAR)) .setsField(ElementMatchers.is(FieldSetting.class.getField(FOO))) .andThen(StubMethod.INSTANCE)) .make() .load(FieldSetting.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER); FieldSetting instance = loaded.getLoaded().getDeclaredConstructor().newInstance(); assertThat(instance.qux(), nullValue(Object.class)); assertThat(instance.foo, is((Object) instance.bar())); } @Test public void testConstructorIsAccessibleFromDifferentPackage() throws Exception { assertThat(new ByteBuddy() .subclass(ProtectedConstructor.class, ConstructorStrategy.Default.NO_CONSTRUCTORS) .name("foo.Bar") .defineConstructor(Visibility.PUBLIC) .intercept(MethodCall.invoke(ProtectedConstructor.class.getDeclaredConstructor()).onSuper()) .make() .load(Foo.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER) .getLoaded() .newInstance(), instanceOf(ProtectedConstructor.class)); } @Test(expected = IllegalStateException.class) public void testDefaultMethodNotCompatible() throws Exception { new ByteBuddy() .subclass(Object.class) .method(isDeclaredBy(Object.class)) .intercept(MethodCall.invoke(String.class.getDeclaredMethod("toString")).onDefault()) .make(); } @Test(expected = IllegalStateException.class) public void testMethodTypeIncompatible() throws Exception { new ByteBuddy() .subclass(InstanceMethod.class) .method(isDeclaredBy(InstanceMethod.class)) .intercept(MethodCall.invoke(String.class.getDeclaredMethod("toLowerCase"))) .make(); } @Test(expected = IllegalStateException.class) public void testArgumentIncompatibleTooFew() throws Exception { new ByteBuddy() .subclass(InstanceMethod.class) .method(named(FOO)) .intercept(MethodCall.invoke(StaticIncompatibleExternalMethod.class.getDeclaredMethod("bar", String.class))) .make(); } @Test(expected = IllegalStateException.class) public void testArgumentIncompatibleTooMany() throws Exception { new ByteBuddy() .subclass(InstanceMethod.class) .method(named(FOO)) .intercept(MethodCall.invoke(StaticIncompatibleExternalMethod.class.getDeclaredMethod("bar", String.class)).with(FOO, BAR)) .make(); } @Test(expected = IllegalStateException.class) public void testArgumentIncompatibleNotAssignable() throws Exception { new ByteBuddy() .subclass(InstanceMethod.class) .method(named(FOO)) .intercept(MethodCall.invoke(StaticIncompatibleExternalMethod.class.getDeclaredMethod("bar", String.class)).with(new Object())) .make(); } @Test(expected = IllegalArgumentException.class) public void testConstructNonConstructorThrowsException() throws Exception { MethodCall.construct(mock(MethodDescription.class)); } @Test(expected = IllegalArgumentException.class) public void testIllegalIndex() throws Exception { MethodCall.invokeSuper().withArgument(-1); } @Test(expected = IllegalStateException.class) public void testMethodCallNonVirtual() throws Exception { new ByteBuddy() .subclass(InstanceMethod.class) .method(named(FOO)) .intercept(MethodCall.invoke(StaticIncompatibleExternalMethod.class.getDeclaredMethod("bar", String.class)).on(new StaticIncompatibleExternalMethod()).with(FOO)) .make(); } @Test(expected = IllegalStateException.class) public void testMethodCallIncompatibleInstance() throws Exception { new ByteBuddy() .subclass(InstanceMethod.class) .method(named(FOO)) .intercept(MethodCall.invoke(StaticIncompatibleExternalMethod.class.getDeclaredMethod("bar", String.class)).on(new Object()).with(FOO)) .make(); } @Test(expected = IllegalStateException.class) public void testMethodCallNonVisibleType() throws Exception { new ByteBuddy() .subclass(Object.class) .method(isDeclaredBy(Object.class)) .intercept(MethodCall.invoke(PackagePrivateType.class.getDeclaredMethod("foo")).on(new PackagePrivateType())) .make(); } @Test(expected = IllegalStateException.class) public void testMethodCallStaticTargetNonVisibleType() throws Exception { new ByteBuddy() .subclass(Object.class) .method(isDeclaredBy(Object.class)) .intercept(MethodCall.invoke(PackagePrivateType.class.getDeclaredMethod("bar"))) .make(); } @Test(expected = IllegalStateException.class) public void testMethodCallSuperCallNonInvokable() throws Exception { new ByteBuddy() .subclass(Object.class) .method(isDeclaredBy(Object.class)) .intercept(MethodCall.invoke(Bar.class.getDeclaredMethod("bar")).onSuper()) .make(); } @Test(expected = IllegalStateException.class) public void testMethodCallDefaultCallNonInvokable() throws Exception { new ByteBuddy() .subclass(Object.class) .method(isDeclaredBy(Object.class)) .intercept(MethodCall.invoke(Bar.class.getDeclaredMethod("bar")).onDefault()) .make(); } @Test(expected = IllegalStateException.class) public void testMethodCallFieldDoesNotExist() throws Exception { new ByteBuddy() .subclass(ExplicitTarget.class) .method(isDeclaredBy(ExplicitTarget.class)) .intercept(MethodCall.invoke(Object.class.getDeclaredMethod("toString")).onField(FOO)) .make(); } @Test(expected = IllegalStateException.class) public void testMethodCallIsNotAccessible() throws Exception { new ByteBuddy() .subclass(Object.class) .defineField(FOO, Object.class) .method(isDeclaredBy(Object.class)) .intercept(MethodCall.invokeSelf().onField(FOO).withAllArguments()) .make(); } @Test(expected = IllegalStateException.class) public void testInstanceCallFromStaticMethod() throws Exception { new ByteBuddy() .subclass(Object.class) .defineMethod(FOO, void.class) .intercept(StubMethod.INSTANCE) .defineMethod(BAR, void.class, Ownership.STATIC) .intercept(MethodCall.invoke(named(FOO))) .make(); } @Test(expected = IllegalStateException.class) public void testCallConstructorFromMethod() throws Exception { new ByteBuddy() .subclass(Object.class) .defineMethod(FOO, void.class) .intercept(MethodCall.invoke(Object.class.getConstructor())) .make(); } @Test(expected = IllegalStateException.class) public void testConstructorCallFromNonRelatedConstructor() throws Exception { new ByteBuddy() .subclass(Number.class) .constructor(ElementMatchers.any()) .intercept(MethodCall.invoke(Object.class.getConstructor())) .make(); } public static class SimpleMethod { public String foo() { return null; } public String bar() { return BAR; } } public static class StaticExternalMethod { public static String bar() { return BAR; } } public static class InstanceMethod { public String foo() { return null; } public String bar() { return BAR; } } public abstract static class ArgumentCall { public abstract String foo(Target target); public static class Target { private final String value; public Target(String value) { this.value = value; } public String foo() { return value; } } } public abstract static class ArgumentCallDynamic { public abstract String foo(Object target); public static class Target { private final String value; public Target(String value) { this.value = value; } public String foo() { return value; } } } public static class SelfReference { public SelfReference foo() { return null; } } public static class SuperMethodInvocation { public String foo() { return FOO; } } public static class MethodCallWithExplicitArgument { public String foo(String value) { return value; } } public static class MethodCallWithTwoExplicitArguments { public String foo(String first, String second) { return first + second; } } public interface MethodCallDelegator { String invokeFoo(String... argument); } public interface IllegalMethodCallDelegator { String invokeFoo(String argument); } @SuppressWarnings("unused") public static class MethodCallWithField { public String foo; public String foo(String value) { return value; } } public static class MethodCallOnField { public String foo; public String foo() { return foo; } } @SuppressWarnings("unused") public static class InvisibleMethodCallWithField extends InvisibleBase { private String foo; public String foo(String value) { return value; } } public static class InvisibleBase { public String foo; } public static class MethodCallWithThis { public MethodCallWithThis foo(MethodCallWithThis value) { return value; } } public static class MethodCallWithOwnType { public Class<?> foo(Class<?> value) { return value; } } public static abstract class MethodCallChaining { public String foo(String bar) { return "foo" + bar; } public String bar() { return "bar"; } public abstract String foobar(); public int someInt() { return 0xCAFEBABE; } } public static class MethodCallAppending extends CallTraceable { public Object foo() { register(FOO); return null; } } public static class ExplicitTarget { public String foo() { return null; } } @SuppressWarnings("unused") public static class StaticIncompatibleExternalMethod { public static String bar(String value) { return null; } } public static class Foo { public static String bar(Object arg0, Object arg1) { return "" + arg0 + arg1; } } static class PackagePrivateType { public String foo() { return FOO; } public static String bar() { return BAR; } } public static class Bar { public void bar() { /* empty */ } } public static class SimpleStringMethod { public String foo() { return null; } } public static class Traceable extends CallTraceable implements Runnable, Callable<String> { public String call() throws Exception { register(FOO); return FOO; } public void run() { register(FOO); } } public static class NonVirtual { public static void foo() { /* empty */ } } public abstract static class ArrayConsuming { public abstract String foo(String arg1, String arg2); public String bar(String[] arg) { return arg[0] + arg[1]; } } public static class FieldSetting { public String foo; public void foo() { throw new AssertionError(); } public String bar() { return FOO; } public String qux() { throw new AssertionError(); } } public static class ProtectedConstructor { protected ProtectedConstructor() { /* empty */ } } }
package com.microsoft.rest.serializer; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.joda.JodaModule; import com.google.common.reflect.TypeToken; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import retrofit.Converter; import retrofit.JacksonConverterFactory; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; /** * A serialization helper class wrapped around {@link JacksonConverterFactory} and {@link ObjectMapper}. */ public class JacksonHelper { private static ObjectMapper objectMapper; private static JacksonConverterFactory converterFactory; private JacksonHelper() {} /** * Gets a static instance of {@link ObjectMapper}. * * @return an instance of {@link ObjectMapper}. */ public static ObjectMapper getObjectMapper() { if (objectMapper == null) { objectMapper = new ObjectMapper() .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) .configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true) //.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .setSerializationInclusion(JsonInclude.Include.NON_NULL) .registerModule(new JodaModule()) .registerModule(ByteArraySerializer.getModule()) .registerModule(DateTimeSerializer.getModule()); } return objectMapper; } /** * Gets a static instance of {@link Converter.Factory}. * * @return an instance of {@link Converter.Factory}. */ public static JacksonConverterFactory getConverterFactory() { if (converterFactory == null) { converterFactory = JacksonConverterFactory.create(getObjectMapper()); } return converterFactory; } /** * Serializes an object into a JSON string using the current {@link ObjectMapper}. * * @param object the object to serialize. * @return the serialized string. Null if the object to serialize is null. */ public static String serialize(Object object) { if (object == null) return null; try { StringWriter writer = new StringWriter(); getObjectMapper().writeValue(writer, object); return writer.toString(); } catch (Exception e) { return null; } } /** * Serializes an object into a raw string using the current {@link ObjectMapper}. * The leading and trailing quotes will be trimmed. * * @param object the object to serialize. * @return the serialized string. Null if the object to serialize is null. */ public static String serializeRaw(Object object) { if (object == null) return null; return StringUtils.strip(serialize(object), "\""); } /** * Serializes a list into a string with the delimiter specified with the * Swagger collection format joining each individual serialized items in * the list. * * @param list the list to serialize. * @param format the Swagger collection format. * @return the serialized string */ public static String serializeList(List<?> list, CollectionFormat format) { if (list == null) return null; List<String> serialized = new ArrayList<String>(); for (Object element : list) { String raw = serializeRaw(element); serialized.add(raw != null ? raw : ""); } return StringUtils.join(serialized, format.getDelimiter()); } /** * Deserializes a string into a {@link T} object using the current {@link ObjectMapper}. * * @param value the string value to deserialize. * @param <T> the type of the deserialized object. * @return the deserialized object. */ @SuppressWarnings("unchecked") public static <T> T deserialize(String value, TypeReference<?> type) throws IOException { if (value == null || value.isEmpty()) return null; return (T)getObjectMapper().readValue(value, type); } /** * Deserializes an input stream into a {@link T} object using the current {@link ObjectMapper}. * @param input the input stream to deserialize. * @param <T> the type of the deserialized object. * @return the deserialized object. */ public static <T> T deserialize(InputStream input, TypeReference<?> type) throws IOException { if (input == null) return null; return deserialize(IOUtils.toString(input), type); } }
package com.intellij.codeInsight.lookup.impl; import com.intellij.codeInsight.CodeInsightSettings; import com.intellij.codeInsight.lookup.*; import com.intellij.codeInsight.template.Template; import com.intellij.codeInsight.template.impl.TemplateSettings; import com.intellij.ide.ui.UISettings; import com.intellij.lang.properties.PropertiesFileType; import com.intellij.lang.properties.PropertiesHighlighter; import com.intellij.lang.properties.psi.PropertiesFile; import com.intellij.lang.properties.psi.Property; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.editor.colors.EditorFontType; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.util.Iconable; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.psi.meta.PsiMetaDataBase; import com.intellij.psi.util.PsiFormatUtil; import com.intellij.ui.RowIcon; import com.intellij.ui.StrikeoutLabel; import com.intellij.util.IconUtil; import com.intellij.util.ui.EmptyIcon; import com.intellij.util.ui.UIUtil; import com.intellij.xml.XmlElementDescriptor; import org.jetbrains.annotations.NonNls; import javax.swing.*; import java.awt.*; class LookupCellRenderer implements ListCellRenderer { private final int ICON_FLAGS; private final Icon EMPTY_ICON; public final int ICON_WIDTH; private final Font NORMAL_FONT; private final Font BOLD_FONT; private final Font SMALL_FONT; private final int FONT_WIDTH; public static final Color BACKGROUND_COLOR = new Color(235, 244, 254); private static final Color FOREGROUND_COLOR = Color.black; private static final Color GRAYED_FOREGROUND_COLOR = new Color(160, 160, 160); private static final Color SELECTED_BACKGROUND_COLOR = new Color(0, 82, 164); private static final Color SELECTED_FOREGROUND_COLOR = Color.white; private static final Color SELECTED_GRAYED_FOREGROUND_COLOR = Color.white; private static final Color PREFIX_FOREGROUND_COLOR = new Color(176, 0, 176); private static final Color SELECTED_PREFIX_FOREGROUND_COLOR = new Color(249, 236, 204); private static final Color EMPTY_ITEM_FOREGROUND_COLOR = FOREGROUND_COLOR; private static final int MAX_LENGTH = 70; private final boolean SHOW_SIGNATURES; private LookupImpl myLookup; private StrikeoutLabel myLabel0; // highlighted part of name private StrikeoutLabel myLabel1; // rest of name private StrikeoutLabel myLabel2; // parameters and tail text private JLabel myLabel3; // type private JPanel myPanel; private boolean myHasNonTemplates; private int myMaxTemplateDescriptionLength = 0; public LookupCellRenderer(LookupImpl lookup) { EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme(); NORMAL_FONT = scheme.getFont(EditorFontType.PLAIN); BOLD_FONT = scheme.getFont(EditorFontType.BOLD); SMALL_FONT = NORMAL_FONT; CodeInsightSettings settings = CodeInsightSettings.getInstance(); SHOW_SIGNATURES = settings.SHOW_SIGNATURES_IN_LOOKUPS; ICON_FLAGS = SHOW_SIGNATURES ? Iconable.ICON_FLAG_VISIBILITY : 0; EMPTY_ICON = IconUtil.getEmptyIcon(SHOW_SIGNATURES); ICON_WIDTH = EMPTY_ICON.getIconWidth(); myLookup = lookup; myLabel0 = new StrikeoutLabel("", SwingConstants.LEFT); myLabel0.setOpaque(true); myLabel1 = new StrikeoutLabel("", SwingConstants.LEFT); myLabel1.setOpaque(true); myLabel2 = new StrikeoutLabel("", SwingConstants.LEFT); myLabel2.setOpaque(true); myLabel3 = new JLabel("", SwingConstants.LEFT); myLabel3.setOpaque(true); myPanel = new JPanel(new BorderLayout()){ public void paint(Graphics g){ UISettings.setupAntialiasing(g); super.paint(g); } }; myPanel.add(myLabel0, BorderLayout.WEST); JPanel panel = new JPanel(new BorderLayout()); myPanel.add(panel, BorderLayout.CENTER); panel.add(myLabel1, BorderLayout.WEST); panel.add(myLabel2, BorderLayout.CENTER); panel.add(myLabel3, BorderLayout.EAST); JLabel label = myLabel0; //noinspection HardCodedStringLiteral label.setText("A"); label.setIcon(null); label.setFont(NORMAL_FONT); FONT_WIDTH = label.getPreferredSize().width; final LookupItem[] items = lookup.getItems(); if (items.length > 0) lookup.getList().setPrototypeCellValue(items[0]); for (LookupItem item : items) { if (!(item.getObject() instanceof Template)) { myHasNonTemplates = true; break; } else { Template template = (Template)item.getObject(); final String description = template.getDescription(); if (description != null) { myMaxTemplateDescriptionLength = Math.max(myMaxTemplateDescriptionLength, description.length()); } } } UIUtil.removeQuaquaVisualMarginsIn(myPanel); } public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean hasFocus) { LookupItem item = (LookupItem)value; Color background = isSelected ? SELECTED_BACKGROUND_COLOR : BACKGROUND_COLOR; Color foreground = isSelected ? SELECTED_FOREGROUND_COLOR : FOREGROUND_COLOR; getLabel0(item, background, isSelected); getLabel1(item, background, foreground); getLabel2(item, background, foreground, isSelected); getLabel3(item, background, foreground); return myPanel; } private static boolean isBold(Object o) { return o instanceof PsiKeyword || o instanceof LookupValueWithUIHint && ((LookupValueWithUIHint)o).isBold(); } private void getLabel0(LookupItem item, final Color background, final boolean selected){ Object o = item.getObject(); final String prefix = myLookup.getPrefix(); String name = getName(item); String text; Icon icon; if (prefix.length() > 0 && StringUtil.startsWithIgnoreCase(name, prefix)){ text = name.substring(0, prefix.length()); icon = getIcon(item); } else{ text = ""; icon = null; } boolean highlighted = item.getAttribute(LookupItem.HIGHLIGHTED_ATTR) != null; boolean bold = highlighted || isBold(o); boolean strikeout = isToStrikeout(item); StrikeoutLabel label = myLabel0; label.setText(text); label.setIcon(icon); label.setFont(bold ? BOLD_FONT : NORMAL_FONT); label.setStrikeout(strikeout); label.setBackground(background); label.setForeground(selected ? SELECTED_PREFIX_FOREGROUND_COLOR : PREFIX_FOREGROUND_COLOR); } private void getLabel1(LookupItem item, final Color background, final Color foreground){ Object o = item.getObject(); final String prefix = myLookup.getPrefix(); String name = getName(item); String text; Icon icon; if (prefix.length() > 0 && StringUtil.startsWithIgnoreCase(name, prefix)){ text = name.substring(prefix.length()); icon = null; } else{ text = name; icon = getIcon(item); } boolean highlighted = item.getAttribute(LookupItem.HIGHLIGHTED_ATTR) != null; boolean bold = highlighted || isBold(o); boolean overstrike = isToStrikeout(item); StrikeoutLabel label = myLabel1; label.setText(text); label.setIcon(icon); label.setFont(bold ? BOLD_FONT : NORMAL_FONT); label.setStrikeout(overstrike); label.setBackground(background); label.setForeground(foreground); } private void getLabel2(final LookupItem item, Color background, Color foreground, final boolean selected){ String text = getText2(item, false); StrikeoutLabel label = myLabel2; if (text != null){ String s = text; int width = getTextWidth(item); int n = width - MAX_LENGTH * FONT_WIDTH; if (n > 0){ n = Math.min(n, (s.length() - 7) * FONT_WIDTH); if (n >= 0){ s = s.substring(0, s.length() - n / FONT_WIDTH - 3) + "..."; } } label.setText(s); } else{ label.setText(""); } boolean isSmall = item.getAttribute(LookupItem.TAIL_TEXT_SMALL_ATTR) != null; Font font = isSmall ? SMALL_FONT : NORMAL_FONT; boolean overstrike = isToStrikeout(item); label.setStrikeout(overstrike); if (item.getObject() instanceof Property) { TextAttributes value = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(PropertiesHighlighter.PROPERTY_VALUE); //background = value.getBackgroundColor(); foreground = selected ? SELECTED_FOREGROUND_COLOR : value.getForegroundColor(); font = BOLD_FONT; } label.setBackground(background); label.setForeground(foreground); label.setFont(font); if (isSmall){ label.setForeground(selected ? SELECTED_GRAYED_FOREGROUND_COLOR : GRAYED_FOREGROUND_COLOR); } } private String getText2(final LookupItem item, final boolean trim) { String text = null; Object o = item.getObject(); if (showSignature(item)){ if (o instanceof PsiElement) { final PsiElement element = (PsiElement)o; if (element.isValid() && element instanceof PsiMethod){ PsiMethod method = (PsiMethod)element; final PsiSubstitutor substitutor = (PsiSubstitutor) item.getAttribute(LookupItem.SUBSTITUTOR); text = PsiFormatUtil.formatMethod(method, substitutor != null ? substitutor : PsiSubstitutor.EMPTY, PsiFormatUtil.SHOW_PARAMETERS, PsiFormatUtil.SHOW_NAME | PsiFormatUtil.SHOW_TYPE); } } } if (o instanceof Property) { Property property = (Property)o; PropertiesFile propertiesFile = property.getContainingFile(); PropertiesFile defaultPropertiesFile = propertiesFile.getResourceBundle().getDefaultPropertiesFile(propertiesFile.getProject()); Property defaultProperty = defaultPropertiesFile.findPropertyByKey(property.getKey()); String value = defaultProperty == null ? property.getValue() : defaultProperty.getValue(); if (trim && value != null && value.length() > 10) value = value.substring(0, 10) + "..."; text = "="+ value; } String tailText = (String)item.getAttribute(LookupItem.TAIL_TEXT_ATTR); if (tailText != null){ if (text == null){ text = tailText; } else{ text += tailText; } } if(item.getAttribute(LookupItem.INDICATE_ANONYMOUS) != null){ if(o instanceof PsiClass){ final PsiClass psiClass = (PsiClass) o; if(psiClass.isInterface() || psiClass.hasModifierProperty(PsiModifier.ABSTRACT)){ text += "{...}"; } } } return text; } private boolean showSignature(LookupItem item) { return SHOW_SIGNATURES || item.getAttribute(LookupItem.FORCE_SHOW_SIGNATURE_ATTR) != null; } private void getLabel3(LookupItem item, final Color background, Color foreground){ myLabel3.setHorizontalTextPosition(SwingConstants.RIGHT); String text = getText3(item); JLabel label = myLabel3; label.setText(text != null ? text + " " : ""); label.setFont(NORMAL_FONT); Color sampleBackground = background; Object o = item.getObject(); if (o instanceof LookupValueWithUIHint && label.getText().length() == 0) { Color proposedBackground = ((LookupValueWithUIHint)o).getColorHint(); if (proposedBackground == null) { proposedBackground = BACKGROUND_COLOR; } sampleBackground = proposedBackground; label.setText(" "); } if (item.getAttribute(LookupImpl.EMPTY_ITEM_ATTRIBUTE) != null){ foreground = EMPTY_ITEM_FOREGROUND_COLOR; } label.setBackground(sampleBackground); label.setForeground(foreground); } private String getText3(final LookupItem item) { Object o = item.getObject(); String text = null; myLabel3.setIcon(null); if (o instanceof PsiElement){ if (showSignature(item)) { PsiType typeAttr = (PsiType)item.getAttribute(LookupItem.TYPE_ATTR); if (typeAttr != null){ text = typeAttr.getPresentableText(); } else{ final PsiElement element = (PsiElement)o; if (element.isValid()) { if (element instanceof PsiMethod){ PsiMethod method = (PsiMethod)element; PsiType returnType = method.getReturnType(); if (returnType != null){ final PsiSubstitutor substitutor = (PsiSubstitutor) item.getAttribute(LookupItem.SUBSTITUTOR); if (substitutor != null) { text = substitutor.substitute(returnType).getPresentableText(); } else { text = returnType.getPresentableText(); } } } else if (element instanceof PsiVariable){ PsiVariable variable = (PsiVariable)element; text = variable.getType().getPresentableText(); } else if (element instanceof PsiExpression){ PsiExpression expression = (PsiExpression)element; PsiType type = expression.getType(); if (type != null){ text = type.getPresentableText(); } } else if (o instanceof Property) { Property property = (Property)o; text = property.getContainingFile().getResourceBundle().getBaseName(); myLabel3.setIcon(PropertiesFileType.FILE_ICON); } } } } } else if (o instanceof Template){ text = getTemplateDescriptionString((Template)o); } else if (o instanceof LookupValueWithUIHint) { text = ((LookupValueWithUIHint)o).getTypeHint(); } else { text = (String)item.getAttribute(LookupItem.TYPE_TEXT_ATTR); } return text; } private static String getName(final LookupItem item){ final Object o = item.getObject(); String name = item.getLookupString(); if (o instanceof PsiElement) { final PsiElement element = (PsiElement)o; if (element.isValid()) { if (element instanceof PsiAnonymousClass) { name = null; } else if(element instanceof PsiClass){ PsiSubstitutor substitutor = (PsiSubstitutor)item.getAttribute(LookupItem.SUBSTITUTOR); if (substitutor != null && !substitutor.isValid()) { PsiType type = (PsiType)item.getAttribute(LookupItem.TYPE); if (type != null) { name = type.getPresentableText(); } } else { name = formatTypeName((PsiClass)element, substitutor, name); } } else if (element instanceof PsiKeyword || element instanceof PsiExpression || element instanceof PsiTypeElement){ name = element.getText(); } else if (o instanceof Property) { Property property = (Property)o; name = property.getKey(); } } } else if (o instanceof PsiArrayType){ name = ((PsiArrayType)o).getDeepComponentType().getPresentableText(); } else if (o instanceof PsiType){ name = ((PsiType)o).getPresentableText(); } else if (o instanceof Template){ name = getKeyString((Template)o); } else if (o instanceof XmlElementDescriptor) { name = ((XmlElementDescriptor)o).getDefaultName(); } else if (o instanceof PsiMetaDataBase) { name = ((PsiMetaDataBase)o).getName(); } else if (o instanceof PresentableLookupValue ) { name = ((PresentableLookupValue)o).getPresentation(); } else { name = String.valueOf(o); } if (name == null){ name = ""; } return name; } private Icon getIcon(LookupItem item){ Icon icon = (Icon)item.getAttribute(LookupItem.ICON_ATTR); if (icon == null) { Object o = item.getObject(); if (o instanceof Iconable && !(o instanceof PsiElement)) { icon = ((Iconable)o).getIcon(ICON_FLAGS); } else { if (o instanceof LookupValueWithPsiElement) { o = ((LookupValueWithPsiElement)o).getElement(); } if (o instanceof PsiElement) { final PsiElement element = (PsiElement)o; if (element.isValid()) { icon = element.getIcon(ICON_FLAGS); } } } } if (icon == null){ icon = EMPTY_ICON; } else if (icon.getIconWidth() < EMPTY_ICON.getIconWidth()) { final RowIcon rowIcon = new RowIcon(2); rowIcon.setIcon(icon, 0); rowIcon.setIcon(new EmptyIcon(EMPTY_ICON.getIconWidth() - icon.getIconWidth()), 1); icon = rowIcon; } return icon; } public int getMaximumWidth(final LookupItem[] items){ int maxWidth = 0; for (LookupItem item : items) { maxWidth = Math.max(maxWidth, getTextWidth(item)); } maxWidth = Math.min(maxWidth, MAX_LENGTH * FONT_WIDTH); return maxWidth + EMPTY_ICON.getIconWidth() + myLabel0.getIconTextGap() + FONT_WIDTH; } /** * Should be called in atomic action. * @return width in pixels */ private int getTextWidth(LookupItem item){ String text = getName(item); final @NonNls String TYPE_GAP = "XXX"; text += getText3(item) + TYPE_GAP; int width = myPanel.getFontMetrics(NORMAL_FONT).stringWidth(text) + 2; String text2 = getText2(item, true); if (text2 != null){ boolean isSmall = item.getAttribute(LookupItem.TAIL_TEXT_SMALL_ATTR) != null; FontMetrics fontMetrics = myPanel.getFontMetrics(isSmall ? SMALL_FONT : NORMAL_FONT); width += fontMetrics.stringWidth(text2); } return width; } private static boolean isToStrikeout(LookupItem item) { final PsiMethod[] allMethods = (PsiMethod[])item.getAttribute(LookupImpl.ALL_METHODS_ATTRIBUTE); if (allMethods != null){ for (PsiMethod method : allMethods) { if (!method.isValid()) { return false; } if (!isDeprecated(method)) { return false; } } return true; } else{ Object o = item.getObject(); if (o instanceof LookupValueWithUIHint2) { return ((LookupValueWithUIHint2)o).isStrikeout(); } if (o instanceof LookupValueWithPsiElement) { o = ((LookupValueWithPsiElement)o).getElement(); } if (o instanceof PsiElement) { final PsiElement element = (PsiElement)o; if (element.isValid()) { return isDeprecated(element); } } } return false; } private static boolean isDeprecated(PsiElement element) { return element instanceof PsiDocCommentOwner && ((PsiDocCommentOwner)element).isDeprecated(); } private static String getKeyString(Template template) { return template.getKey(); } private String getTemplateDescriptionString(Template template) { final int KEY_LENGTH_LIMIT = 10; // longer keys are not really useful, but make popup ugly int max = MAX_LENGTH - Math.min(KEY_LENGTH_LIMIT, TemplateSettings.getInstance().getMaxKeyLength()); max = Math.min(max, myMaxTemplateDescriptionLength + 1); StringBuilder buffer = new StringBuilder(max); buffer.append(' '); buffer.append(template.getDescription()); if (buffer.length() > max){ final String ellipsis = "..."; if (max > ellipsis.length()){ buffer.setLength(max - ellipsis.length()); buffer.append(ellipsis); } } else if (!myHasNonTemplates){ while(buffer.length() < max){ buffer.append(' '); } } return buffer.toString(); } private static String formatTypeName(final PsiClass element, final PsiSubstitutor substitutor, String name) { final CodeStyleSettings styleSettings = CodeStyleSettingsManager.getSettings(element.getProject()); if(substitutor != null){ final PsiTypeParameter[] params = element.getTypeParameters(); if(params.length > 0){ StringBuffer buffer = new StringBuffer(); buffer.append("<"); boolean flag = true; for(int i = 0; i < params.length; i++){ final PsiTypeParameter param = params[i]; final PsiType type = substitutor.substitute(param); if(type == null){ flag = false; break; } buffer.append(type.getPresentableText()); if(i < params.length - 1){ buffer.append(","); if(styleSettings.SPACE_AFTER_COMMA) buffer.append(" "); } } buffer.append(">"); if(flag) name += buffer; } } return name; } }
package com.tazine.thread.lock.spinlock; /** * * * @author frank * @date 2019/05/17 */ public class ReSpinLock { private SpinLock lock = new SpinLock(); public void a() { try { lock.lock(); Thread.sleep(2000); System.out.println(Thread.currentThread().getName() + " a "); b(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } public void b() { try { lock.lock(); Thread.sleep(200); System.out.println(Thread.currentThread().getName() + " b "); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } }
package com.bbn.bue.common.collections; import com.google.common.annotations.Beta; import com.google.common.base.Function; import com.google.common.collect.ImmutableTable; import com.google.common.collect.Table; import java.util.Map; @Beta public class TableUtils { public static <R, C, V> ImmutableTable<R, C, V> tableFromIndexFunctions(final Iterable<V> values, final Function<V, R> rowIndexFunction, final Function<V, C> columnIndexFunction) { final ImmutableTable.Builder<R, C, V> builder = ImmutableTable.builder(); // this must be done in an imperative style since the column or row (or both) index functions // are not necessarily unique for (V v : values) { builder.put(rowIndexFunction.apply(v), columnIndexFunction.apply(v), v); } return builder.build(); } public static <R, C, V, C2> ImmutableTable<R, C2, V> columnTransformerByKeyOnly( final Table<R, C, V> table, final Function<C, C2> columnTransformer) { return columnTransformerByCell(table, new Function<Table.Cell<R, C, V>, C2>() { @Override public C2 apply(final Table.Cell<R, C, V> input) { return columnTransformer.apply(input.getColumnKey()); } }); } /** * columnTransformer has access to Key, Value information in each Table.Cell * @param table * @param columnTransformer * @param <R> * @param <C> * @param <V> * @param <C2> * @return */ public static <R, C, V, C2> ImmutableTable<R, C2, V> columnTransformerByCell( final Table<R, C, V> table, final Function<Table.Cell<R, C, V>, C2> columnTransformer) { final ImmutableTable.Builder<R, C2, V> newTable = ImmutableTable.builder(); for(Table.Cell<R, C, V> cell : table.cellSet()) { C2 col = columnTransformer.apply(cell); newTable.put(cell.getRowKey(), col, cell.getValue()); } return newTable.build(); } public static <R, C, V, R2> ImmutableTable<R2, C, V> rowTransformerByKeyOnly( final Table<R, C, V> table, final Function<R, R2> rowTransformer) { return rowTransformerByCell(table, new Function<Table.Cell<R, C, V>, R2>() { @Override public R2 apply(final Table.Cell<R, C, V> input) { return rowTransformer.apply(input.getRowKey()); } }); } public static <R, C, V, R2> ImmutableTable<R2, C, V> rowTransformerByCell( final Table<R, C,V> table, final Function<Table.Cell<R, C, V>, R2> rowTransformer) { final ImmutableTable.Builder<R2, C, V> newTable = ImmutableTable.builder(); for(Table.Cell<R, C, V> cell : table.cellSet()) { R2 row = rowTransformer.apply(cell); newTable.put(row, cell.getColumnKey(), cell.getValue()); } return newTable.build(); } public static <R,C,V> void addColumnToBuilder(ImmutableTable.Builder<R,C,V> builder, R row, Map<C,V> column) { for(Map.Entry<C,V> e: column.entrySet()) { builder.put(row, e.getKey(), e.getValue()); } } /** * Creates a new {@link ImmutableTable} from the provided {@link com.google.common.collect.Table.Cell}s. * The iteration order of the resulting table will respect the iteration order of the input cells. * Null keys and values are forbidden. */ public static <R, C, V> ImmutableTable<R, C, V> copyOf(Iterable<Table.Cell<R, C, V>> cells) { final ImmutableTable.Builder<R, C, V> ret = ImmutableTable.builder(); for (final Table.Cell<R, C, V> cell : cells) { ret.put(cell.getRowKey(), cell.getColumnKey(), cell.getValue()); } return ret.build(); } /** * Guava {@link Function} to transform a cell to its row key. */ public static <R, C, V> Function<Table.Cell<R, C, V>, R> toRowKeyFunction() { return new Function<Table.Cell<R, C, V>, R>() { @Override public R apply(final Table.Cell<R, C, V> input) { return input.getRowKey(); } }; } /** * Guava {@link Function} to transform a cell to its column key. */ public static <R, C, V> Function<Table.Cell<R, C, V>, C> toColumnKeyFunction() { return new Function<Table.Cell<R, C, V>, C>() { @Override public C apply(final Table.Cell<R, C, V> input) { return input.getColumnKey(); } }; } }
package org.opencb.commons.containers.map; import java.util.List; import java.util.Map; public class QueryOptions extends ObjectMap { private static final long serialVersionUID = -6331081481906004636L; public QueryOptions() { } public QueryOptions(String key, Object value) { super(key, value); } public QueryOptions(String json) { super(json); } public QueryOptions(Map<String, ?> inputOptions) { this.putAll(inputOptions); } public QueryOptions(Map<String, ?> inputOptions, boolean pickFirstValue) { if (pickFirstValue) { for (Map.Entry<String, ?> option : inputOptions.entrySet()) { if (option.getValue() instanceof List) { this.put(option.getKey(), ((List) option.getValue()).get(0)); } } } else { this.putAll(inputOptions); } } }
package com.yahoo.searchdefinition; import com.yahoo.config.application.api.ApplicationPackage; import com.yahoo.config.application.api.DeployLogger; import com.yahoo.config.application.api.FileRegistry; import com.yahoo.config.model.api.ModelContext; import com.yahoo.config.model.application.provider.BaseDeployLogger; import com.yahoo.config.model.application.provider.MockFileRegistry; import com.yahoo.config.model.deploy.TestProperties; import com.yahoo.config.model.test.MockApplicationPackage; import com.yahoo.document.DocumentTypeManager; import com.yahoo.io.IOUtils; import com.yahoo.io.reader.NamedReader; import com.yahoo.path.Path; import com.yahoo.search.query.profile.QueryProfileRegistry; import com.yahoo.search.query.profile.config.QueryProfileXMLReader; import com.yahoo.searchdefinition.parser.ConvertSchemaCollection; import com.yahoo.searchdefinition.parser.IntermediateCollection; import com.yahoo.searchdefinition.parser.IntermediateParser; import com.yahoo.searchdefinition.parser.ParseException; import com.yahoo.searchdefinition.parser.SDParser; import com.yahoo.searchdefinition.parser.SimpleCharStream; import com.yahoo.searchdefinition.parser.TokenMgrException; import com.yahoo.searchdefinition.processing.Processor; import com.yahoo.vespa.documentmodel.DocumentModel; import com.yahoo.vespa.model.container.search.QueryProfiles; import com.yahoo.yolean.Exceptions; import java.io.File; import java.io.IOException; import java.io.Reader; import java.nio.file.Files; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Application builder. Usage: * 1) Add all schemas, using the addXXX() methods, * 2) provide the available rank types and rank expressions, using the setRankXXX() methods, * 3) invoke the {@link #build} method */ public class ApplicationBuilder { private final IntermediateCollection mediator; private final ApplicationPackage applicationPackage; private final List<Schema> schemas = new ArrayList<>(); private final DocumentTypeManager documentTypeManager = new DocumentTypeManager(); private final RankProfileRegistry rankProfileRegistry; private final QueryProfileRegistry queryProfileRegistry; private final FileRegistry fileRegistry; private final DeployLogger deployLogger; private final ModelContext.Properties properties; /** True to build the document aspect only, skipping instantiation of rank profiles */ private final boolean documentsOnly; private Application application; private final Set<Class<? extends Processor>> processorsToSkip = new HashSet<>(); /** For testing only */ public ApplicationBuilder() { this(new RankProfileRegistry(), new QueryProfileRegistry()); } /** For testing only */ public ApplicationBuilder(DeployLogger deployLogger) { this(MockApplicationPackage.createEmpty(), deployLogger); } /** For testing only */ public ApplicationBuilder(DeployLogger deployLogger, RankProfileRegistry rankProfileRegistry) { this(MockApplicationPackage.createEmpty(), deployLogger, rankProfileRegistry); } /** Used for generating documents for typed access to document fields in Java */ public ApplicationBuilder(boolean documentsOnly) { this(MockApplicationPackage.createEmpty(), new MockFileRegistry(), new BaseDeployLogger(), new TestProperties(), new RankProfileRegistry(), new QueryProfileRegistry(), documentsOnly); } /** For testing only */ public ApplicationBuilder(ApplicationPackage app, DeployLogger deployLogger) { this(app, new MockFileRegistry(), deployLogger, new TestProperties(), new RankProfileRegistry(), new QueryProfileRegistry()); } /** For testing only */ public ApplicationBuilder(ApplicationPackage app, DeployLogger deployLogger, RankProfileRegistry rankProfileRegistry) { this(app, new MockFileRegistry(), deployLogger, new TestProperties(), rankProfileRegistry, new QueryProfileRegistry()); } /** For testing only */ public ApplicationBuilder(RankProfileRegistry rankProfileRegistry) { this(rankProfileRegistry, new QueryProfileRegistry()); } /** For testing only */ public ApplicationBuilder(RankProfileRegistry rankProfileRegistry, QueryProfileRegistry queryProfileRegistry) { this(rankProfileRegistry, queryProfileRegistry, new TestProperties()); } /** For testing only */ public ApplicationBuilder(ModelContext.Properties properties) { this(new RankProfileRegistry(), new QueryProfileRegistry(), properties); } /** For testing only */ public ApplicationBuilder(RankProfileRegistry rankProfileRegistry, QueryProfileRegistry queryProfileRegistry, ModelContext.Properties properties) { this(MockApplicationPackage.createEmpty(), new MockFileRegistry(), new BaseDeployLogger(), properties, rankProfileRegistry, queryProfileRegistry); } /** normal constructor */ public ApplicationBuilder(ApplicationPackage app, FileRegistry fileRegistry, DeployLogger deployLogger, ModelContext.Properties properties, RankProfileRegistry rankProfileRegistry, QueryProfileRegistry queryProfileRegistry) { this(app, fileRegistry, deployLogger, properties, rankProfileRegistry, queryProfileRegistry, false); } private ApplicationBuilder(ApplicationPackage applicationPackage, FileRegistry fileRegistry, DeployLogger deployLogger, ModelContext.Properties properties, RankProfileRegistry rankProfileRegistry, QueryProfileRegistry queryProfileRegistry, boolean documentsOnly) { this.mediator = new IntermediateCollection(deployLogger, properties); this.applicationPackage = applicationPackage; this.rankProfileRegistry = rankProfileRegistry; this.queryProfileRegistry = queryProfileRegistry; this.fileRegistry = fileRegistry; this.deployLogger = deployLogger; this.properties = properties; this.documentsOnly = documentsOnly; for (NamedReader reader : applicationPackage.getSchemas()) addSchema(reader); } /** * Adds a schema to this application. * * @param fileName the name of the file to import * @throws IOException thrown if the file can not be read for some reason * @throws ParseException thrown if the file does not contain a valid search definition */ public void addSchemaFile(String fileName) throws IOException, ParseException { if (properties.featureFlags().experimentalSdParsing()) { var parsedName = mediator.addSchemaFromFile(fileName); addRankProfileFiles(parsedName); return; } File file = new File(fileName); addSchema(IOUtils.readFile(file)); } /** * Reads and parses the schema string provided by the given reader. Once all schemas have been * imported, call {@link #build}. * * @param reader the reader whose content to import */ public void addSchema(NamedReader reader) { if (properties.featureFlags().experimentalSdParsing()) { try { var parsedName = mediator.addSchemaFromReader(reader); addRankProfileFiles(parsedName); } catch (ParseException e) { throw new IllegalArgumentException("Could not parse schema file '" + reader.getName() + "'", e); } return; } try { Schema schema = createSchema(IOUtils.readAll(reader)); add(schema); String schemaName = schema.getName(); String schemaFileName = stripSuffix(reader.getName(), ApplicationPackage.SD_NAME_SUFFIX); if ( ! schemaFileName.equals(schemaName)) { throw new IllegalArgumentException("The file containing schema '" + schemaName + "' must be named '" + schemaName + ApplicationPackage.SD_NAME_SUFFIX + "', not " + reader.getName()); } } catch (ParseException e) { throw new IllegalArgumentException("Could not parse schema file '" + reader.getName() + "'", e); } catch (IOException e) { throw new IllegalArgumentException("Could not read schema file '" + reader.getName() + "'", e); } finally { closeIgnoreException(reader.getReader()); } } private static String stripSuffix(String readerName, String suffix) { if ( ! readerName.endsWith(suffix)) throw new IllegalArgumentException("Schema '" + readerName + "' does not end with " + suffix); return readerName.substring(0, readerName.length() - suffix.length()); } /** * Adds a schema to this * * @param schemaString the content of the schema */ public void addSchema(String schemaString) throws ParseException { if (properties.featureFlags().experimentalSdParsing()) { var parsed = mediator.addSchemaFromString(schemaString); addRankProfileFiles(parsed.name()); return; } add(createSchema(schemaString)); } public Schema add(Schema schema) { if (schema.getName() == null) throw new IllegalArgumentException("Schema has no name"); schemas.add(schema); return schema; } private Schema createSchema(String schemaString) throws ParseException { Schema schema = parseSchema(schemaString); addRankProfileFiles(schema); return schema; } private Schema parseSchema(String schemaString) throws ParseException { if (properties.featureFlags().experimentalSdParsing()) { throw new IllegalArgumentException("should use new parser only"); } SimpleCharStream stream = new SimpleCharStream(schemaString); try { return parserOf(stream).schema(documentTypeManager); } catch (TokenMgrException e) { throw new ParseException("Unknown symbol: " + e.getMessage()); } catch (ParseException pe) { throw new ParseException(stream.formatException(Exceptions.toMessageString(pe))); } } private void addRankProfileFiles(Schema schema) { if (applicationPackage == null) return; if (properties.featureFlags().experimentalSdParsing()) { throw new IllegalArgumentException("should use new parser only"); } Path legacyRankProfilePath = ApplicationPackage.SEARCH_DEFINITIONS_DIR.append(schema.getName()); for (NamedReader reader : applicationPackage.getFiles(legacyRankProfilePath, ".profile")) parseRankProfile(reader, schema); Path rankProfilePath = ApplicationPackage.SCHEMAS_DIR.append(schema.getName()); for (NamedReader reader : applicationPackage.getFiles(rankProfilePath, ".profile")) parseRankProfile(reader, schema); } private void addRankProfileFiles(String schemaName) throws ParseException { if (applicationPackage == null) return; if (! properties.featureFlags().experimentalSdParsing()) { throw new IllegalArgumentException("should use old parser only"); } Path legacyRankProfilePath = ApplicationPackage.SEARCH_DEFINITIONS_DIR.append(schemaName); for (NamedReader reader : applicationPackage.getFiles(legacyRankProfilePath, ".profile")) { mediator.addRankProfileFile(schemaName, reader); } Path rankProfilePath = ApplicationPackage.SCHEMAS_DIR.append(schemaName); for (NamedReader reader : applicationPackage.getFiles(rankProfilePath, ".profile")) { mediator.addRankProfileFile(schemaName, reader); } } /** Parses the rank profile of the given reader and adds it to the rank profile registry for this schema. */ private void parseRankProfile(NamedReader reader, Schema schema) { if (properties.featureFlags().experimentalSdParsing()) { throw new IllegalArgumentException("should use new parser only"); } try { SimpleCharStream stream = new SimpleCharStream(IOUtils.readAll(reader.getReader())); try { parserOf(stream).rankProfile(schema); } catch (TokenMgrException e) { throw new ParseException("Unknown symbol: " + e.getMessage()); } catch (ParseException pe) { throw new ParseException(stream.formatException(Exceptions.toMessageString(pe))); } } catch (IOException e) { throw new IllegalArgumentException("Could not read rank profile " + reader.getName(), e); } catch (ParseException e) { throw new IllegalArgumentException("Could not parse rank profile " + reader.getName(), e); } } private SDParser parserOf(SimpleCharStream stream) { return new SDParser(stream, applicationPackage, fileRegistry, deployLogger, properties, rankProfileRegistry, documentsOnly); } public Application build(boolean validate) { if (application != null) throw new IllegalStateException("Application already built"); if (properties.featureFlags().experimentalSdParsing()) { var converter = new ConvertSchemaCollection(mediator, documentTypeManager, applicationPackage, fileRegistry, deployLogger, properties, rankProfileRegistry, documentsOnly); for (var schema : converter.convertToSchemas()) { add(schema); } } application = new Application(applicationPackage, schemas, rankProfileRegistry, new QueryProfiles(queryProfileRegistry, deployLogger), properties, documentsOnly, validate, processorsToSkip, deployLogger); return application; } /** Returns a modifiable set of processors we should skip for these schemas. Useful for testing. */ public Set<Class<? extends Processor>> processorsToSkip() { return processorsToSkip; } public Schema getSchema() { if (application == null) throw new IllegalStateException("Application not built"); if (application.schemas().size() != 1) throw new IllegalStateException("This call only works if we have 1 schema. Schemas: " + application.schemas().values()); return application.schemas().values().stream().findAny().get(); } public DocumentModel getModel() { return application.documentModel(); } public Schema getSchema(String name) { if (application == null) throw new IllegalStateException("Application not built"); if (name == null) return getSchema(); return application.schemas().get(name); } public Application application() { return application; } /** * Convenience method to return a list of all built {@link Schema} objects. * * @return the list of built searches */ public List<Schema> getSchemaList() { return new ArrayList<>(application.schemas().values()); } /** * Convenience factory method to import and build a {@link Schema} object from a string. * * @param sd the string to build from * @return the built {@link ApplicationBuilder} object * @throws ParseException thrown if there is a problem parsing the string */ public static ApplicationBuilder createFromString(String sd) throws ParseException { return createFromString(sd, new BaseDeployLogger()); } public static ApplicationBuilder createFromString(String sd, DeployLogger logger) throws ParseException { ApplicationBuilder builder = new ApplicationBuilder(logger); builder.addSchema(sd); builder.build(true); return builder; } public static ApplicationBuilder createFromStrings(DeployLogger logger, String ... schemas) throws ParseException { ApplicationBuilder builder = new ApplicationBuilder(logger); for (var schema : schemas) builder.addSchema(schema); builder.build(true); return builder; } /** * Convenience factory method to import and build a {@link Schema} object from a file. Only for testing. * * @param fileName the file to build from * @return the built {@link ApplicationBuilder} object * @throws IOException if there was a problem reading the file. * @throws ParseException if there was a problem parsing the file content. */ public static ApplicationBuilder createFromFile(String fileName) throws IOException, ParseException { return createFromFile(fileName, new BaseDeployLogger()); } /** * Convenience factory methdd to create a SearchBuilder from multiple SD files. Only for testing. */ public static ApplicationBuilder createFromFiles(Collection<String> fileNames) throws IOException, ParseException { return createFromFiles(fileNames, new BaseDeployLogger()); } public static ApplicationBuilder createFromFile(String fileName, DeployLogger logger) throws IOException, ParseException { return createFromFile(fileName, logger, new RankProfileRegistry(), new QueryProfileRegistry()); } private static ApplicationBuilder createFromFiles(Collection<String> fileNames, DeployLogger logger) throws IOException, ParseException { return createFromFiles(fileNames, new MockFileRegistry(), logger, new TestProperties(), new RankProfileRegistry(), new QueryProfileRegistry()); } /** * Convenience factory method to import and build a {@link Schema} object from a file. * * @param fileName the file to build from. * @param deployLogger logger for deploy messages. * @param rankProfileRegistry registry for rank profiles. * @return the built {@link ApplicationBuilder} object. * @throws IOException if there was a problem reading the file. * @throws ParseException if there was a problem parsing the file content. */ private static ApplicationBuilder createFromFile(String fileName, DeployLogger deployLogger, RankProfileRegistry rankProfileRegistry, QueryProfileRegistry queryprofileRegistry) throws IOException, ParseException { return createFromFiles(Collections.singletonList(fileName), new MockFileRegistry(), deployLogger, new TestProperties(), rankProfileRegistry, queryprofileRegistry); } /** * Convenience factory methdd to create a SearchBuilder from multiple SD files.. */ private static ApplicationBuilder createFromFiles(Collection<String> fileNames, FileRegistry fileRegistry, DeployLogger deployLogger, ModelContext.Properties properties, RankProfileRegistry rankProfileRegistry, QueryProfileRegistry queryprofileRegistry) throws IOException, ParseException { ApplicationBuilder builder = new ApplicationBuilder(MockApplicationPackage.createEmpty(), fileRegistry, deployLogger, properties, rankProfileRegistry, queryprofileRegistry); for (String fileName : fileNames) { builder.addSchemaFile(fileName); } builder.build(true); return builder; } public static ApplicationBuilder createFromDirectory(String dir, FileRegistry fileRegistry, DeployLogger logger, ModelContext.Properties properties) throws IOException, ParseException { return createFromDirectory(dir, fileRegistry, logger, properties, new RankProfileRegistry()); } public static ApplicationBuilder createFromDirectory(String dir, FileRegistry fileRegistry, DeployLogger logger, ModelContext.Properties properties, RankProfileRegistry rankProfileRegistry) throws IOException, ParseException { return createFromDirectory(dir, fileRegistry, logger, properties, rankProfileRegistry, createQueryProfileRegistryFromDirectory(dir)); } private static ApplicationBuilder createFromDirectory(String dir, FileRegistry fileRegistry, DeployLogger logger, ModelContext.Properties properties, RankProfileRegistry rankProfileRegistry, QueryProfileRegistry queryProfileRegistry) throws IOException, ParseException { return createFromDirectory(dir, MockApplicationPackage.fromSearchDefinitionAndRootDirectory(dir), fileRegistry, logger, properties, rankProfileRegistry, queryProfileRegistry); } private static ApplicationBuilder createFromDirectory(String dir, ApplicationPackage applicationPackage, FileRegistry fileRegistry, DeployLogger deployLogger, ModelContext.Properties properties, RankProfileRegistry rankProfileRegistry, QueryProfileRegistry queryProfileRegistry) throws IOException, ParseException { ApplicationBuilder builder = new ApplicationBuilder(applicationPackage, fileRegistry, deployLogger, properties, rankProfileRegistry, queryProfileRegistry); for (var i = Files.list(new File(dir).toPath()).filter(p -> p.getFileName().toString().endsWith(".sd")).iterator(); i.hasNext(); ) { builder.addSchemaFile(i.next().toString()); } builder.build(true); return builder; } private static QueryProfileRegistry createQueryProfileRegistryFromDirectory(String dir) { File queryProfilesDir = new File(dir, "query-profiles"); if ( ! queryProfilesDir.exists()) return new QueryProfileRegistry(); return new QueryProfileXMLReader().read(queryProfilesDir.toString()); } // TODO: The build methods below just call the create methods above - remove /** * Convenience factory method to import and build a {@link Schema} object from a file. Only for testing. * * @param fileName the file to build from * @return the built {@link Schema} object * @throws IOException thrown if there was a problem reading the file * @throws ParseException thrown if there was a problem parsing the file content */ public static Schema buildFromFile(String fileName) throws IOException, ParseException { return buildFromFile(fileName, new BaseDeployLogger(), new RankProfileRegistry(), new QueryProfileRegistry()); } /** * Convenience factory method to import and build a {@link Schema} object from a file. * * @param fileName the file to build from * @param rankProfileRegistry registry for rank profiles * @return the built {@link Schema} object * @throws IOException thrown if there was a problem reading the file * @throws ParseException thrown if there was a problem parsing the file content */ public static Schema buildFromFile(String fileName, RankProfileRegistry rankProfileRegistry, QueryProfileRegistry queryProfileRegistry) throws IOException, ParseException { return buildFromFile(fileName, new BaseDeployLogger(), rankProfileRegistry, queryProfileRegistry); } /** * Convenience factory method to import and build a {@link Schema} from a file. * * @param fileName the file to build from * @param deployLogger logger for deploy messages * @param rankProfileRegistry registry for rank profiles * @return the built {@link Schema} object * @throws IOException thrown if there was a problem reading the file * @throws ParseException thrown if there was a problem parsing the file content */ public static Schema buildFromFile(String fileName, DeployLogger deployLogger, RankProfileRegistry rankProfileRegistry, QueryProfileRegistry queryProfileRegistry) throws IOException, ParseException { return createFromFile(fileName, deployLogger, rankProfileRegistry, queryProfileRegistry).getSchema(); } /** * Convenience factory method to import and build a {@link Schema} object from a raw object. * * @param rawSchema the raw object to build from * @return the built {@link ApplicationBuilder} object * @see #add(Schema) */ public static ApplicationBuilder createFromRawSchema(Schema rawSchema, RankProfileRegistry rankProfileRegistry, QueryProfileRegistry queryProfileRegistry) { ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry, queryProfileRegistry); builder.add(rawSchema); builder.build(true); return builder; } /** * Convenience factory method to import and build a {@link Schema} object from a raw object. * * @param rawSchema the raw object to build from * @return the built {@link Schema} object * @see #add(Schema) */ public static Schema buildFromRawSchema(Schema rawSchema, RankProfileRegistry rankProfileRegistry, QueryProfileRegistry queryProfileRegistry) { return createFromRawSchema(rawSchema, rankProfileRegistry, queryProfileRegistry).getSchema(); } public RankProfileRegistry getRankProfileRegistry() { return rankProfileRegistry; } public QueryProfileRegistry getQueryProfileRegistry() { return queryProfileRegistry; } public ModelContext.Properties getProperties() { return properties; } public DeployLogger getDeployLogger() { return deployLogger; } @SuppressWarnings("EmptyCatchBlock") private static void closeIgnoreException(Reader reader) { try { reader.close(); } catch(Exception e) {} } }
package admin; import java.io.IOException; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Admin; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.Delete; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos; import org.apache.hadoop.hbase.util.Bytes; import util.HBaseHelper; // cc SnapshotExample Example showing the use of the admin snapshot API public class SnapshotExample { public static void main(String[] args) throws IOException, InterruptedException { Configuration conf = HBaseConfiguration.create(); conf.setInt("hbase.client.retries.number", 1); HBaseHelper helper = HBaseHelper.getHelper(conf); helper.dropTable("testtable"); helper.dropTable("testtable2"); helper.dropTable("testtable3"); helper.createTable("testtable", 3, "colfam1", "colfam2"); helper.put("testtable", new String[]{"row1"}, new String[]{"colfam1", "colfam2"}, new String[]{"qual1", "qual1", "qual2", "qual2", "qual3", "qual3"}, new long[]{1, 2, 3, 4, 5, 6}, new String[]{"val1", "val1", "val2", "val2", "val3", "val3"}); System.out.println("Before snapshot calls..."); helper.dump("testtable", new String[]{"row1"}, null, null); Connection connection = ConnectionFactory.createConnection(conf); TableName tableName = TableName.valueOf("testtable"); Table table = connection.getTable(tableName); Admin admin = connection.getAdmin(); /* When you try to snapshot with an existing name: Exception in thread "main" org.apache.hadoop.hbase.client.RetriesExhaustedException: Failed after attempts=1, exceptions: Mon Apr 13 11:21:58 CEST 2015, RpcRetryingCaller{globalStartTime=1428916918532, pause=100, retries=1}, org.apache.hadoop.hbase.ipc.RemoteWithExtrasException(org.apache.hadoop.hbase.snapshot.SnapshotExistsException): org.apache.hadoop.hbase.snapshot.SnapshotExistsException: Snapshot 'snapshot2' already stored on the filesystem. at org.apache.hadoop.hbase.master.snapshot.SnapshotManager.takeSnapshot(SnapshotManager.java:518) */ admin.deleteSnapshots("snapshot.*"); // vv SnapshotExample admin.snapshot("snapshot1", tableName); // co SnapshotExample-1-Snap1 Create a snapshot of the initial table, then list all available snapshots next. List<HBaseProtos.SnapshotDescription> snaps = admin.listSnapshots(); System.out.println("Snapshots after snapshot 1: " + snaps); Delete delete = new Delete(Bytes.toBytes("row1")); delete.addColumn(Bytes.toBytes("colfam1"), Bytes.toBytes("qual1")); // co SnapshotExample-2-Delete Remove one column and do two more snapshots, one without first flushing, then another with a preceding flush. table.delete(delete); admin.snapshot("snapshot2", tableName, HBaseProtos.SnapshotDescription.Type.SKIPFLUSH); admin.snapshot("snapshot3", tableName, HBaseProtos.SnapshotDescription.Type.FLUSH); snaps = admin.listSnapshots(); System.out.println("Snapshots after snapshot 2 & 3: " + snaps); Put put = new Put(Bytes.toBytes("row2")) .addColumn(Bytes.toBytes("colfam1"), Bytes.toBytes("qual10"), // co SnapshotExample-3-Put Add a new row to the table and take yet another snapshot. Bytes.toBytes("val10")); table.put(put); HBaseProtos.SnapshotDescription snapshotDescription = HBaseProtos.SnapshotDescription.newBuilder() .setName("snapshot4") .setTable(tableName.getNameAsString()) .build(); admin.takeSnapshotAsync(snapshotDescription); snaps = admin.listSnapshots(); System.out.println("Snapshots before waiting: " + snaps); System.out.println("Waiting..."); while (!admin.isSnapshotFinished(snapshotDescription)) { // co SnapshotExample-4-Wait Wait for the asynchronous snapshot to complete. List the snapshots before and after the waiting. Thread.sleep(1 * 1000); System.out.print("."); } System.out.println(); System.out.println("Snapshot completed."); snaps = admin.listSnapshots(); System.out.println("Snapshots after waiting: " + snaps); System.out.println("Table before restoring snapshot 1"); helper.dump("testtable", new String[]{"row1", "row2"}, null, null); // ^^ SnapshotExample /* If the table is not disabled you will receive this error: Exception in thread "main" org.apache.hadoop.hbase.TableNotDisabledException: testtable at org.apache.hadoop.hbase.client.HBaseAdmin.restoreSnapshot(HBaseAdmin.java:3153) at org.apache.hadoop.hbase.client.HBaseAdmin.restoreSnapshot(HBaseAdmin.java:3088) at admin.SnapshotExample.main(SnapshotExample.java:88) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140) */ // vv SnapshotExample admin.disableTable(tableName); admin.restoreSnapshot("snapshot1"); // co SnapshotExample-5-Restore Restore the first snapshot, recreating the initial table. This needs to be done on a disabled table. admin.enableTable(tableName); System.out.println("Table after restoring snapshot 1"); helper.dump("testtable", new String[]{"row1", "row2"}, null, null); admin.deleteSnapshot("snapshot1"); // co SnapshotExample-6-DelSnap1 Remove the first snapshot, and list the available ones again. snaps = admin.listSnapshots(); System.out.println("Snapshots after deletion: " + snaps); admin.cloneSnapshot("snapshot2", TableName.valueOf("testtable2")); System.out.println("New table after cloning snapshot 2"); helper.dump("testtable2", new String[]{"row1", "row2"}, null, null); admin.cloneSnapshot("snapshot3", TableName.valueOf("testtable3")); // co SnapshotExample-7-Clone Clone the second and third snapshot into a new table, dump the content to show the difference between the "skipflush" and "flush" types. System.out.println("New table after cloning snapshot 3"); helper.dump("testtable3", new String[]{"row1", "row2"}, null, null); // ^^ SnapshotExample table.close(); connection.close(); helper.close(); } }
package com.gauravbytes.java8.supplier; import java.util.logging.Level; import java.util.logging.Logger; import com.gauravbytes.java8.lambda.LambdaTest; /** * * @author Gaurav Rai Mazra * */ public class SupplierExample { public static void main(String[] args) { lazyEvalInJavaWithSupplier(); } private static final Logger logger = Logger.getLogger(LambdaTest.class.getName()); static class LogMessage { private String message; public LogMessage(String message) { this.message = message; } public String asJson() { return "{\"message\" : " + message + "}"; } } private static void lazyEvalInJavaWithSupplier() { LogMessage message = new LogMessage("I am sinner!!!"); logger.log(Level.FINE, message.asJson()); // improved way because if the log level set for logging is not the one you // passed, we have wasted effort of decorating logMessage which won't be // used by anyone. logger.log(Level.FINE, () -> message.asJson()); // or just logger.log(Level.FINE, message::asJson); } }