@Override
  /**
   * Returns the size of the image in bytes.
   *
   * @param sourceString the image link.
   * @return the file size in bytes of the image link provided; -1 if the size isn't available or
   *     exceeds the max allowed image size.
   */
  public int getImageSize(String sourceString) {
    int length = -1;
    try {

      URL url = new URL(sourceString);
      String protocol = url.getProtocol();
      if (protocol.equals("http") || protocol.equals("https")) {
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        length = connection.getContentLength();
        connection.disconnect();
      } else if (protocol.equals("ftp")) {
        FTPUtils ftp = new FTPUtils(sourceString);
        length = ftp.getSize();
        ftp.disconnect();
      }

      if (length > imgMaxSize) {
        length = -1;
      }
    } catch (Exception e) {
      logger.debug("Failed to get the length of the image in bytes", e);
    }
    return length;
  }
  /**
   * Gets the max allowed size value in bytes from Configuration service and sets the value to
   * <tt>imgMaxSize</tt> if succeed. If the configuration property isn't available or the value
   * can't be parsed correctly the value of <tt>imgMaxSize</tt> isn't changed.
   */
  private void setMaxImgSizeFromConf() {
    ConfigurationService configService = DirectImageActivator.getConfigService();

    if (configService != null) {
      String confImgSizeStr = (String) configService.getProperty(MAX_IMG_SIZE);
      try {
        if (confImgSizeStr != null) {
          imgMaxSize = Long.parseLong(confImgSizeStr);
        } else {
          configService.setProperty(MAX_IMG_SIZE, imgMaxSize);
        }
      } catch (NumberFormatException e) {
        if (logger.isDebugEnabled())
          logger.debug(
              "Failed to parse max image size: " + confImgSizeStr + ". Going for default.");
      }
    }
  }
 /**
  * Returns true if the content type of the resource pointed by sourceString is an image.
  *
  * @param sourceString the original image link.
  * @return true if the content type of the resource pointed by sourceString is an image.
  */
 @Override
 public boolean isDirectImage(String sourceString) {
   boolean isDirectImage = false;
   try {
     URL url = new URL(sourceString);
     String protocol = url.getProtocol();
     if (protocol.equals("http") || protocol.equals("https")) {
       HttpURLConnection connection = (HttpURLConnection) url.openConnection();
       isDirectImage = connection.getContentType().contains("image");
       connection.disconnect();
     } else if (protocol.equals("ftp")) {
       if (sourceString.endsWith(".png")
           || sourceString.endsWith(".jpg")
           || sourceString.endsWith(".gif")) {
         isDirectImage = true;
       }
     }
   } catch (Exception e) {
     logger.debug("Failed to retrieve content type information for" + sourceString, e);
   }
   return isDirectImage;
 }
Esempio n. 4
0
  /**
   * Creates an instance of <tt>ShowPreviewDialog</tt>
   *
   * @param chatPanel The <tt>ChatConversationPanel</tt> that is associated with this dialog.
   */
  ShowPreviewDialog(final ChatConversationPanel chatPanel) {
    this.chatPanel = chatPanel;

    this.setTitle(
        GuiActivator.getResources().getI18NString("service.gui.SHOW_PREVIEW_DIALOG_TITLE"));
    okButton = new JButton(GuiActivator.getResources().getI18NString("service.gui.OK"));
    cancelButton = new JButton(GuiActivator.getResources().getI18NString("service.gui.CANCEL"));

    JPanel mainPanel = new TransparentPanel();
    mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
    mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    // mainPanel.setPreferredSize(new Dimension(200, 150));
    this.getContentPane().add(mainPanel);

    JTextPane descriptionMsg = new JTextPane();
    descriptionMsg.setEditable(false);
    descriptionMsg.setOpaque(false);
    descriptionMsg.setText(
        GuiActivator.getResources().getI18NString("service.gui.SHOW_PREVIEW_WARNING_DESCRIPTION"));

    Icon warningIcon = null;
    try {
      warningIcon =
          new ImageIcon(
              ImageIO.read(
                  GuiActivator.getResources().getImageURL("service.gui.icons.WARNING_ICON")));
    } catch (IOException e) {
      logger.debug("failed to load the warning icon");
    }
    JLabel warningSign = new JLabel(warningIcon);

    JPanel warningPanel = new TransparentPanel();
    warningPanel.setLayout(new BoxLayout(warningPanel, BoxLayout.X_AXIS));
    warningPanel.add(warningSign);
    warningPanel.add(Box.createHorizontalStrut(10));
    warningPanel.add(descriptionMsg);

    enableReplacement =
        new JCheckBox(
            GuiActivator.getResources()
                .getI18NString("plugin.chatconfig.replacement.ENABLE_REPLACEMENT_STATUS"));
    enableReplacement.setOpaque(false);
    enableReplacement.setSelected(cfg.getBoolean(ReplacementProperty.REPLACEMENT_ENABLE, true));
    enableReplacementProposal =
        new JCheckBox(
            GuiActivator.getResources()
                .getI18NString("plugin.chatconfig.replacement.ENABLE_REPLACEMENT_PROPOSAL"));
    enableReplacementProposal.setOpaque(false);

    JPanel checkBoxPanel = new TransparentPanel();
    checkBoxPanel.setLayout(new BoxLayout(checkBoxPanel, BoxLayout.Y_AXIS));
    checkBoxPanel.add(enableReplacement);
    checkBoxPanel.add(enableReplacementProposal);

    JPanel buttonsPanel = new TransparentPanel(new FlowLayout(FlowLayout.CENTER));
    buttonsPanel.add(okButton);
    buttonsPanel.add(cancelButton);

    mainPanel.add(warningPanel);
    mainPanel.add(Box.createVerticalStrut(10));
    mainPanel.add(checkBoxPanel);
    mainPanel.add(buttonsPanel);

    okButton.addActionListener(this);
    cancelButton.addActionListener(this);

    this.setPreferredSize(new Dimension(390, 230));
  }
Esempio n. 5
0
public class ShowPreviewDialog extends SIPCommDialog
    implements ActionListener, ChatLinkClickedListener {
  /** Serial version UID. */
  private static final long serialVersionUID = 1L;

  /**
   * The <tt>Logger</tt> used by the <tt>ShowPreviewDialog</tt> class and its instances for logging
   * output.
   */
  private static final Logger logger = Logger.getLogger(ShowPreviewDialog.class);

  ConfigurationService cfg = GuiActivator.getConfigurationService();

  /** The Ok button. */
  private final JButton okButton;

  /** The cancel button. */
  private final JButton cancelButton;

  /** Checkbox that indicates whether or not to show this dialog next time. */
  private final JCheckBox enableReplacementProposal;

  /** Checkbox that indicates whether or not to show previews automatically */
  private final JCheckBox enableReplacement;

  /** The <tt>ChatConversationPanel</tt> that this dialog is associated with. */
  private final ChatConversationPanel chatPanel;

  /** Mapping between messageID and the string representation of the chat message. */
  private Map<String, String> msgIDToChatString = new ConcurrentHashMap<String, String>();

  /**
   * Mapping between the pair (messageID, link position) and the actual link in the string
   * representation of the chat message.
   */
  private Map<String, String> msgIDandPositionToLink = new ConcurrentHashMap<String, String>();

  /**
   * Mapping between link and replacement for this link that is acquired from it's corresponding
   * <tt>ReplacementService</tt>.
   */
  private Map<String, String> linkToReplacement = new ConcurrentHashMap<String, String>();

  /** The id of the message that is currently associated with this dialog. */
  private String currentMessageID = "";

  /** The position of the link in the current message. */
  private String currentLinkPosition = "";

  /**
   * Creates an instance of <tt>ShowPreviewDialog</tt>
   *
   * @param chatPanel The <tt>ChatConversationPanel</tt> that is associated with this dialog.
   */
  ShowPreviewDialog(final ChatConversationPanel chatPanel) {
    this.chatPanel = chatPanel;

    this.setTitle(
        GuiActivator.getResources().getI18NString("service.gui.SHOW_PREVIEW_DIALOG_TITLE"));
    okButton = new JButton(GuiActivator.getResources().getI18NString("service.gui.OK"));
    cancelButton = new JButton(GuiActivator.getResources().getI18NString("service.gui.CANCEL"));

    JPanel mainPanel = new TransparentPanel();
    mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
    mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    // mainPanel.setPreferredSize(new Dimension(200, 150));
    this.getContentPane().add(mainPanel);

    JTextPane descriptionMsg = new JTextPane();
    descriptionMsg.setEditable(false);
    descriptionMsg.setOpaque(false);
    descriptionMsg.setText(
        GuiActivator.getResources().getI18NString("service.gui.SHOW_PREVIEW_WARNING_DESCRIPTION"));

    Icon warningIcon = null;
    try {
      warningIcon =
          new ImageIcon(
              ImageIO.read(
                  GuiActivator.getResources().getImageURL("service.gui.icons.WARNING_ICON")));
    } catch (IOException e) {
      logger.debug("failed to load the warning icon");
    }
    JLabel warningSign = new JLabel(warningIcon);

    JPanel warningPanel = new TransparentPanel();
    warningPanel.setLayout(new BoxLayout(warningPanel, BoxLayout.X_AXIS));
    warningPanel.add(warningSign);
    warningPanel.add(Box.createHorizontalStrut(10));
    warningPanel.add(descriptionMsg);

    enableReplacement =
        new JCheckBox(
            GuiActivator.getResources()
                .getI18NString("plugin.chatconfig.replacement.ENABLE_REPLACEMENT_STATUS"));
    enableReplacement.setOpaque(false);
    enableReplacement.setSelected(cfg.getBoolean(ReplacementProperty.REPLACEMENT_ENABLE, true));
    enableReplacementProposal =
        new JCheckBox(
            GuiActivator.getResources()
                .getI18NString("plugin.chatconfig.replacement.ENABLE_REPLACEMENT_PROPOSAL"));
    enableReplacementProposal.setOpaque(false);

    JPanel checkBoxPanel = new TransparentPanel();
    checkBoxPanel.setLayout(new BoxLayout(checkBoxPanel, BoxLayout.Y_AXIS));
    checkBoxPanel.add(enableReplacement);
    checkBoxPanel.add(enableReplacementProposal);

    JPanel buttonsPanel = new TransparentPanel(new FlowLayout(FlowLayout.CENTER));
    buttonsPanel.add(okButton);
    buttonsPanel.add(cancelButton);

    mainPanel.add(warningPanel);
    mainPanel.add(Box.createVerticalStrut(10));
    mainPanel.add(checkBoxPanel);
    mainPanel.add(buttonsPanel);

    okButton.addActionListener(this);
    cancelButton.addActionListener(this);

    this.setPreferredSize(new Dimension(390, 230));
  }

  @Override
  public void actionPerformed(ActionEvent arg0) {
    if (arg0.getSource().equals(okButton)) {
      cfg.setProperty(ReplacementProperty.REPLACEMENT_ENABLE, enableReplacement.isSelected());
      cfg.setProperty(
          ReplacementProperty.REPLACEMENT_PROPOSAL, enableReplacementProposal.isSelected());
      SwingWorker worker =
          new SwingWorker() {
            /**
             * Called on the event dispatching thread (not on the worker thread) after the <code>
             * construct</code> method has returned.
             */
            @Override
            public void finished() {
              String newChatString = (String) get();

              if (newChatString != null) {
                try {
                  Element elem = chatPanel.document.getElement(currentMessageID);
                  chatPanel.document.setOuterHTML(elem, newChatString);
                  msgIDToChatString.put(currentMessageID, newChatString);
                } catch (BadLocationException ex) {
                  logger.error("Could not replace chat message", ex);
                } catch (IOException ex) {
                  logger.error("Could not replace chat message", ex);
                }
              }
            }

            @Override
            protected Object construct() throws Exception {
              String newChatString = msgIDToChatString.get(currentMessageID);
              try {
                String originalLink =
                    msgIDandPositionToLink.get(currentMessageID + "#" + currentLinkPosition);
                String replacementLink = linkToReplacement.get(originalLink);
                String replacement;
                DirectImageReplacementService source =
                    GuiActivator.getDirectImageReplacementSource();
                if (originalLink.equals(replacementLink)
                    && (!source.isDirectImage(originalLink)
                        || source.getImageSize(originalLink) == -1)) {
                  replacement = originalLink;
                } else {
                  replacement =
                      "<IMG HEIGHT=\"90\" WIDTH=\"120\" SRC=\""
                          + replacementLink
                          + "\" BORDER=\"0\" ALT=\""
                          + originalLink
                          + "\"></IMG>";
                }

                String old =
                    originalLink
                        + "</A> <A href=\"jitsi://"
                        + ShowPreviewDialog.this.getClass().getName()
                        + "/SHOWPREVIEW?"
                        + currentMessageID
                        + "#"
                        + currentLinkPosition
                        + "\">"
                        + GuiActivator.getResources().getI18NString("service.gui.SHOW_PREVIEW");

                newChatString = newChatString.replace(old, replacement);
              } catch (Exception ex) {
                logger.error("Could not replace chat message", ex);
              }
              return newChatString;
            }
          };
      worker.start();
      this.setVisible(false);
    } else if (arg0.getSource().equals(cancelButton)) {
      this.setVisible(false);
    }
  }

  @Override
  public void chatLinkClicked(URI url) {
    String action = url.getPath();
    if (action.equals("/SHOWPREVIEW")) {
      enableReplacement.setSelected(cfg.getBoolean(ReplacementProperty.REPLACEMENT_ENABLE, true));
      enableReplacementProposal.setSelected(
          cfg.getBoolean(ReplacementProperty.REPLACEMENT_PROPOSAL, true));

      currentMessageID = url.getQuery();
      currentLinkPosition = url.getFragment();

      this.setVisible(true);
      this.setLocationRelativeTo(chatPanel);
    }
  }

  /**
   * Returns mapping between messageID and the string representation of the chat message.
   *
   * @return mapping between messageID and chat string.
   */
  Map<String, String> getMsgIDToChatString() {
    return msgIDToChatString;
  }

  /**
   * Returns mapping between the pair (messageID, link position) and the actual link in the string
   * representation of the chat message.
   *
   * @return mapping between (messageID, linkPosition) and link.
   */
  Map<String, String> getMsgIDandPositionToLink() {
    return msgIDandPositionToLink;
  }

  /**
   * Returns mapping between link and replacement for this link that was acquired from it's
   * corresponding <tt>ReplacementService</tt>.
   *
   * @return mapping between link and it's corresponding replacement.
   */
  Map<String, String> getLinkToReplacement() {
    return linkToReplacement;
  }
}
 /** Constructor for <tt>ReplacementServiceDirectImageImpl</tt>. */
 public ReplacementServiceDirectImageImpl() {
   setMaxImgSizeFromConf();
   logger.trace("Creating a Direct Image Link Source.");
 }
/**
 * Implements the {@link ReplacementService} to provide previews for direct image links.
 *
 * @author Purvesh Sahoo
 * @author Marin Dzhigarov
 */
public class ReplacementServiceDirectImageImpl implements DirectImageReplacementService {
  /** The logger for this class. */
  private static final Logger logger = Logger.getLogger(ReplacementServiceDirectImageImpl.class);

  /** The regex used to match the link in the message. */
  public static final String URL_PATTERN = "https?\\:\\/\\/(www\\.)*.*\\.(?:jpg|png|gif)";

  /** Configuration label shown in the config form. */
  public static final String DIRECT_IMAGE_CONFIG_LABEL = "Direct Image Link";

  /** Source name; also used as property label. */
  public static final String SOURCE_NAME = "DIRECTIMAGE";

  /** Maximum allowed size of the image in bytes. The default size is 2MB. */
  private long imgMaxSize = 2097152;

  /** Configuration property name for maximum allowed size of the image in bytes. */
  private static final String MAX_IMG_SIZE =
      "net.java.sip.communicator.impl.replacement.directimage.MAX_IMG_SIZE";

  /** Constructor for <tt>ReplacementServiceDirectImageImpl</tt>. */
  public ReplacementServiceDirectImageImpl() {
    setMaxImgSizeFromConf();
    logger.trace("Creating a Direct Image Link Source.");
  }

  /**
   * Gets the max allowed size value in bytes from Configuration service and sets the value to
   * <tt>imgMaxSize</tt> if succeed. If the configuration property isn't available or the value
   * can't be parsed correctly the value of <tt>imgMaxSize</tt> isn't changed.
   */
  private void setMaxImgSizeFromConf() {
    ConfigurationService configService = DirectImageActivator.getConfigService();

    if (configService != null) {
      String confImgSizeStr = (String) configService.getProperty(MAX_IMG_SIZE);
      try {
        if (confImgSizeStr != null) {
          imgMaxSize = Long.parseLong(confImgSizeStr);
        } else {
          configService.setProperty(MAX_IMG_SIZE, imgMaxSize);
        }
      } catch (NumberFormatException e) {
        if (logger.isDebugEnabled())
          logger.debug(
              "Failed to parse max image size: " + confImgSizeStr + ". Going for default.");
      }
    }
  }

  /**
   * Returns the thumbnail URL of the image link provided.
   *
   * @param sourceString the original image link.
   * @return the thumbnail image link; the original link in case of no match.
   */
  public String getReplacement(String sourceString) {
    return sourceString;
  }

  /**
   * Returns the source name
   *
   * @return the source name
   */
  public String getSourceName() {
    return SOURCE_NAME;
  }

  /**
   * Returns the pattern of the source
   *
   * @return the source pattern
   */
  public String getPattern() {
    return URL_PATTERN;
  }

  @Override
  /**
   * Returns the size of the image in bytes.
   *
   * @param sourceString the image link.
   * @return the file size in bytes of the image link provided; -1 if the size isn't available or
   *     exceeds the max allowed image size.
   */
  public int getImageSize(String sourceString) {
    int length = -1;
    try {

      URL url = new URL(sourceString);
      String protocol = url.getProtocol();
      if (protocol.equals("http") || protocol.equals("https")) {
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        length = connection.getContentLength();
        connection.disconnect();
      } else if (protocol.equals("ftp")) {
        FTPUtils ftp = new FTPUtils(sourceString);
        length = ftp.getSize();
        ftp.disconnect();
      }

      if (length > imgMaxSize) {
        length = -1;
      }
    } catch (Exception e) {
      logger.debug("Failed to get the length of the image in bytes", e);
    }
    return length;
  }

  /**
   * Returns true if the content type of the resource pointed by sourceString is an image.
   *
   * @param sourceString the original image link.
   * @return true if the content type of the resource pointed by sourceString is an image.
   */
  @Override
  public boolean isDirectImage(String sourceString) {
    boolean isDirectImage = false;
    try {
      URL url = new URL(sourceString);
      String protocol = url.getProtocol();
      if (protocol.equals("http") || protocol.equals("https")) {
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        isDirectImage = connection.getContentType().contains("image");
        connection.disconnect();
      } else if (protocol.equals("ftp")) {
        if (sourceString.endsWith(".png")
            || sourceString.endsWith(".jpg")
            || sourceString.endsWith(".gif")) {
          isDirectImage = true;
        }
      }
    } catch (Exception e) {
      logger.debug("Failed to retrieve content type information for" + sourceString, e);
    }
    return isDirectImage;
  }
}