MailcapCommandMap.java 21.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
/* MailcapCommandMap.java -- Command map implementation using a mailcap file.
   Copyright (C) 2004 Free Software Foundation, Inc.

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */

package javax.activation;

import gnu.java.lang.CPStringBuilder;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Implementation of a command map using a <code>mailcap</code> file (RFC
 * 1524). Mailcap files are searched for in the following places:
 * <ol>
 * <li>Programmatically added entries to this interface</li>
 * <li>the file <tt>.mailcap</tt> in the user's home directory</li>
 * <li>the file <i>&lt;java.home&gt;</i><tt>/lib/mailcap</tt></li>
 * <li>the resource <tt>META-INF/mailcap</tt></li>
 * <li>the resource <tt>META-INF/mailcap.default</tt> in the JAF
 * distribution</li>
 * </ol>
 *
 * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a>
 * @version 1.1
 */
public class MailcapCommandMap
    extends CommandMap
{

  private static final int PROG = 0;
  private static final int HOME = 1;
  private static final int SYS = 2;
  private static final int JAR = 3;
  private static final int DEF = 4;
  private static boolean debug = false;
  private static final int NORMAL = 0;
  private static final int FALLBACK = 1;
85 86

  static
87 88 89 90 91 92 93 94 95 96
  {
    try
      {
        String d = System.getProperty("javax.activation.debug");
        debug = Boolean.valueOf(d).booleanValue();
      }
    catch (SecurityException e)
      {
      }
  }
97

98
  private Map<String,Map<String,List<String>>>[][] mailcaps;
99

100 101 102 103 104 105 106
  /**
   * Default constructor.
   */
  public MailcapCommandMap()
  {
    init(null);
  }
107

108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
  /**
   * Constructor specifying a filename.
   * @param fileName the name of the file to read mailcap entries from
   */
  public MailcapCommandMap(String fileName)
    throws IOException
  {
    Reader in = null;
    try
      {
        in = new FileReader(fileName);
      }
    catch (IOException e)
      {
      }
    init(in);
    if (in != null)
      {
        try
          {
            in.close();
          }
        catch (IOException e)
          {
          }
      }
  }
135

136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
  /**
   * Constructor specifying an input stream.
   * @param is the input stream to read mailcap entries from
   */
  public MailcapCommandMap(InputStream is)
  {
    init(new InputStreamReader(is));
  }

  private void init(Reader in)
  {
    mailcaps = new Map[5][2];
    for (int i = 0; i < 5; i++)
      {
        for (int j = 0; j < 2; j++)
          {
            mailcaps[i][j] =
153
              new LinkedHashMap<String,Map<String,List<String>>>();
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
          }
      }
    if (in != null)
      {
        if (debug)
          {
            System.out.println("MailcapCommandMap: load PROG");
          }
        try
          {
            parse(PROG, in);
          }
        catch (IOException e)
          {
          }
      }
170

171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
    if (debug)
      {
        System.out.println("MailcapCommandMap: load HOME");
      }
    try
      {
        String home = System.getProperty("user.home");
        if (home != null)
          {
            parseFile(HOME, new CPStringBuilder(home)
                      .append(File.separatorChar)
                      .append(".mailcap")
                      .toString());
          }
      }
    catch (SecurityException e)
      {
      }
189

190 191 192 193 194 195
    if (debug)
      {
        System.out.println("MailcapCommandMap: load SYS");
      }
    try
      {
196
        parseFile(SYS,
197
                  new CPStringBuilder(System.getProperty("java.home"))
198 199
                  .append(File.separatorChar)
                  .append("lib")
200 201 202 203 204 205 206
                  .append(File.separatorChar)
                  .append("mailcap")
                  .toString());
      }
    catch (SecurityException e)
      {
      }
207

208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
    if (debug)
      {
        System.out.println("MailcapCommandMap: load JAR");
      }
    List<URL> systemResources = getSystemResources("META-INF/mailcap");
    int len = systemResources.size();
    if (len > 0)
      {
        for (int i = 0; i < len ; i++)
          {
            Reader urlIn = null;
            URL url = systemResources.get(i);
            try
              {
                if (debug)
                  {
                    System.out.println("\t" + url.toString());
                  }
                urlIn = new InputStreamReader(url.openStream());
                parse(JAR, urlIn);
              }
            catch (IOException e)
              {
                if (debug)
                  {
                    System.out.println(e.getClass().getName() + ": " +
                                       e.getMessage());
                  }
              }
            finally
              {
                if (urlIn != null)
                  {
                    try
                      {
                        urlIn.close();
                      }
                    catch (IOException e)
                      {
                      }
                  }
              }
          }
      }
    else
      {
        parseResource(JAR, "/META-INF/mailcap");
      }
256

257 258 259 260 261 262
    if (debug)
      {
        System.out.println("MailcapCommandMap: load DEF");
      }
    parseResource(DEF, "/META-INF/mailcap.default");
  }
263

264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
  /**
   * Returns the list of preferred commands for a given MIME type.
   * @param mimeType the MIME type
   */
  public synchronized CommandInfo[] getPreferredCommands(String mimeType)
  {
    List<CommandInfo> cmdList = new ArrayList<CommandInfo>();
    List<String> verbList = new ArrayList<String>();
    for (int i = 0; i < 2; i++)
      {
        for (int j = 0; j < 5; j++)
          {
            Map<String,List<String>> map = getCommands(mailcaps[j][i], mimeType);
            if (map != null)
              {
                for (Map.Entry<String,List<String>> entry : map.entrySet())
                  {
                    String verb = entry.getKey();
                    if (!verbList.contains(verb))
                      {
                        List<String> classNames = entry.getValue();
                        String className = classNames.get(0);
                        CommandInfo cmd = new CommandInfo(verb, className);
                        cmdList.add(cmd);
                        verbList.add(verb);
                      }
                  }
              }
          }
      }
    CommandInfo[] cmds = new CommandInfo[cmdList.size()];
    cmdList.toArray(cmds);
    return cmds;
  }
298

299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
  /**
   * Returns all commands for the given MIME type.
   * @param mimeType the MIME type
   */
  public synchronized CommandInfo[] getAllCommands(String mimeType)
  {
    List<CommandInfo> cmdList = new ArrayList<CommandInfo>();
    for (int i = 0; i < 2; i++)
      {
        for (int j = 0; j < 5; j++)
          {
            Map<String,List<String>> map = getCommands(mailcaps[j][i], mimeType);
            if (map != null)
              {
                for (Map.Entry<String,List<String>> entry : map.entrySet())
                  {
                    String verb = entry.getKey();
                    List<String> classNames = entry.getValue();
                    int len = classNames.size();
                    for (int l = 0; l < len; l++)
                      {
                        String className = classNames.get(l);
                        CommandInfo cmd = new CommandInfo(verb, className);
                        cmdList.add(cmd);
                      }
                  }
              }
          }
      }
    CommandInfo[] cmds = new CommandInfo[cmdList.size()];
    cmdList.toArray(cmds);
    return cmds;
  }

  /**
   * Returns the command with the specified name for the given MIME type.
   * @param mimeType the MIME type
   * @param cmdName the command verb
   */
  public synchronized CommandInfo getCommand(String mimeType,
                                             String cmdName)
  {
    for (int i = 0; i < 2; i++)
      {
        for (int j = 0; j < 5; j++)
          {
            Map<String,List<String>> map =
346
              getCommands(mailcaps[j][i], mimeType);
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
            if (map != null)
              {
                List<String> classNames = map.get(cmdName);
                if (classNames == null)
                  {
                    classNames = map.get("x-java-" + cmdName);
                  }
                if (classNames != null)
                  {
                    String className = classNames.get(0);
                    return new CommandInfo(cmdName, className);
                  }
              }
          }
      }
    return null;
  }

  /**
   * Adds entries programmatically to the registry.
   * @param mailcap a mailcap string
   */
  public synchronized void addMailcap(String mailcap)
  {
    if (debug)
      {
        System.out.println("MailcapCommandMap: add to PROG");
      }
    try
      {
        parse(PROG, new StringReader(mailcap));
      }
    catch (IOException e)
      {
      }
  }

  /**
   * Returns the DCH for the specified MIME type.
   * @param mimeType the MIME type
   */
  public synchronized DataContentHandler
    createDataContentHandler(String mimeType)
  {
    if (debug)
      {
        System.out.println("MailcapCommandMap: " +
                           "createDataContentHandler for " + mimeType);
      }
    for (int i = 0; i < 2; i++)
      {
        for (int j = 0; j < 5; j++)
          {
            if (debug)
              {
                System.out.println("  search DB #" + i);
              }
            Map<String,List<String>> map = getCommands(mailcaps[j][i], mimeType);
            if (map != null)
              {
                List<String> classNames = map.get("content-handler");
                if (classNames == null)
                  {
                    classNames = map.get("x-java-content-handler");
                  }
                if (classNames != null)
                  {
                    String className = classNames.get(0);
                    if (debug)
                      {
                        System.out.println("  In " + nameOf(j) +
                                           ", content-handler=" + className);
                      }
                    try
                      {
                        Class<?> clazz = Class.forName(className);
                        return (DataContentHandler)clazz.newInstance();
                      }
                    catch (IllegalAccessException e)
                      {
                        if (debug)
                          {
                            e.printStackTrace();
                          }
                      }
                    catch (ClassNotFoundException e)
                      {
                        if (debug)
                      {
                        e.printStackTrace();
                      }
                      }
                    catch (InstantiationException e)
                      {
                        if (debug)
                          {
                            e.printStackTrace();
                          }
                      }
                  }
              }
          }
      }
    return null;
  }
452

453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
  /**
   * Get the native commands for the given MIME type.
   * Returns an array of strings where each string is
   * an entire mailcap file entry.  The application
   * will need to parse the entry to extract the actual
   * command as well as any attributes it needs. See
   * <a href="http://www.ietf.org/rfc/rfc1524.txt">RFC 1524</a>
   * for details of the mailcap entry syntax.  Only mailcap
   * entries that specify a view command for the specified
   * MIME type are returned.
   * @return array of native command entries
   * @since JAF 1.1
   */
  public String[] getNativeCommands(String mimeType)
  {
    List<String> acc = new ArrayList<String>();
    for (int i = 0; i < 2; i++)
      {
        for (int j = 0; j < 5; j++)
          {
            addNativeCommands(acc, mailcaps[j][i], mimeType);
          }
      }
    String[] ret = new String[acc.size()];
    acc.toArray(ret);
    return ret;
  }

  private void addNativeCommands(List<String> acc,
482 483
                                 Map<String,Map<String,List<String>>> mailcap,
                                 String mimeType)
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
  {
    for (Map.Entry<String,Map<String,List<String>>> mEntry : mailcap.entrySet())
      {
        String entryMimeType = mEntry.getKey();
        if (!entryMimeType.equals(mimeType))
          {
            continue;
          }
        Map<String,List<String>> commands = mEntry.getValue();
        String viewCommand = commands.get("view-command").get(0);
        if (viewCommand == null)
          {
            continue;
          }
        CPStringBuilder buf = new CPStringBuilder();
        buf.append(mimeType);
        buf.append(';');
        buf.append(' ');
        buf.append(viewCommand);
        for (Map.Entry<String,List<String>> cEntry : commands.entrySet())
          {
            String verb = cEntry.getKey();
            List<String> classNames = cEntry.getValue();
            if (!"view-command".equals(verb))
              {
                for (String command : classNames)
                  {
                    buf.append(';');
                    buf.append(' ');
                    buf.append(verb);
                    buf.append('=');
                    buf.append(command);
                  }
              }
          }
        if (buf.length() > 0)
          {
            acc.add(buf.toString());
          }
      }
  }
525

526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
  private static String nameOf(int mailcap)
  {
    switch (mailcap)
      {
      case PROG:
        return "PROG";
      case HOME:
        return "HOME";
      case SYS:
        return "SYS";
      case JAR:
        return "JAR";
      case DEF:
        return "DEF";
      default:
        return "ERR";
542
      }
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
  }

  private void parseFile(int index, String filename)
  {
    Reader in = null;
    try
      {
        if (debug)
          {
            System.out.println("\t" + filename);
          }
        in = new FileReader(filename);
        parse(index, in);
      }
    catch (IOException e)
      {
        if (debug)
          {
            System.out.println(e.getClass().getName() + ": " +
                               e.getMessage());
          }
      }
    finally
      {
        if (in != null)
          {
            try
              {
                in.close();
              }
            catch (IOException e)
              {
              }
          }
      }
  }
579

580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
  private void parseResource(int index, String name)
  {
    Reader in = null;
    try
      {
        InputStream is = getClass().getResourceAsStream(name);
        if (is != null)
          {
            if (debug)
              {
                System.out.println("\t" + name);
              }
            in = new InputStreamReader(is);
            parse(index, in);
          }
      }
    catch (IOException e)
      {
        if (debug)
          {
            System.out.println(e.getClass().getName() + ": " +
                               e.getMessage());
          }
      }
    finally
      {
        if (in != null)
          {
            try
              {
                in.close();
              }
            catch (IOException e)
              {
              }
          }
      }
  }
618

619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
  private void parse(int index, Reader in)
    throws IOException
  {
    BufferedReader br = new BufferedReader(in);
    CPStringBuilder buf = null;
    for (String line = br.readLine(); line != null; line = br.readLine())
      {
        line = line.trim();
        int len = line.length();
        if (len == 0 || line.charAt(0) == '#')
          {
            continue; // Comment
          }
        if (line.charAt(len - 1) == '\\')
          {
            if (buf == null)
              {
                buf = new CPStringBuilder();
              }
            buf.append(line.substring(0, len - 1));
          }
        else if (buf != null)
          {
            buf.append(line);
            parseEntry(index, buf.toString());
            buf = null;
          }
        else
          {
            parseEntry(index, line);
          }
      }
  }
652

653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
  private void parseEntry(int index, String line)
  {
    // Tokenize entry into fields
    char[] chars = line.toCharArray();
    int len = chars.length;
    boolean inQuotedString = false;
    boolean fallback = false;
    CPStringBuilder buffer = new CPStringBuilder();
    List<String> fields = new ArrayList<String>();
    for (int i = 0; i < len; i++)
      {
        char c = chars[i];
        if (c == '\\')
          {
            c = chars[++i]; // qchar
          }
        if (c == ';' && !inQuotedString)
          {
            String field = buffer.toString().trim();
            if ("x-java-fallback-entry".equals(field))
              {
                fallback = true;
              }
            fields.add(field);
            buffer.setLength(0);
          }
        else
          {
            if (c == '"')
              {
                inQuotedString = !inQuotedString;
              }
            buffer.append(c);
          }
      }
    String field = buffer.toString().trim();
    if ("x-java-fallback-entry".equals(field))
      {
        fallback = true;
      }
    fields.add(field);
694

695 696 697 698 699 700 701 702 703
    len = fields.size();
    if (len < 2)
      {
        if (debug)
          {
            System.err.println("Invalid mailcap entry: " + line);
          }
        return;
      }
704

705 706 707 708 709 710 711 712 713
    Map<String,Map<String,List<String>>> mailcap =
      fallback ? mailcaps[index][FALLBACK] : mailcaps[index][NORMAL];
    String mimeType = fields.get(0);
    addField(mailcap, mimeType, "view-command", (String) fields.get(1));
    for (int i = 2; i < len; i++)
      {
        addField(mailcap, mimeType, null, (String) fields.get(i));
      }
  }
714

715
  private void addField(Map<String,Map<String,List<String>>> mailcap,
716
                        String mimeType, String verb, String command)
717 718 719 720 721 722 723 724 725 726 727 728 729 730
  {
    if (verb == null)
      {
        int ei = command.indexOf('=');
        if (ei != -1)
          {
            verb = command.substring(0, ei);
            command = command.substring(ei + 1);
          }
      }
    if (command.length() == 0 || verb == null || verb.length() == 0)
      {
        return; // Invalid field or flag
      }
731

732 733 734 735 736 737 738 739 740 741 742 743 744 745
    Map<String,List<String>> commands = mailcap.get(mimeType);
    if (commands == null)
      {
        commands = new LinkedHashMap<String,List<String>>();
        mailcap.put(mimeType, commands);
      }
    List<String> classNames = commands.get(verb);
    if (classNames == null)
      {
        classNames = new ArrayList<String>();
        commands.put(verb, classNames);
      }
    classNames.add(command);
  }
746

747 748
  private Map<String,List<String>>
    getCommands(Map<String,Map<String,List<String>>> mailcap,
749
                String mimeType)
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
  {
    int si = mimeType.indexOf('/');
    String genericMimeType = new CPStringBuilder(mimeType.substring(0, si))
      .append('/')
      .append('*')
      .toString();
    Map<String,List<String>> specific = mailcap.get(mimeType);
    Map<String,List<String>> generic = mailcap.get(genericMimeType);
    if (generic == null)
      {
        return specific;
      }
    if (specific == null)
      {
        return generic;
      }
    Map<String,List<String>> combined = new LinkedHashMap<String,List<String>>();
    combined.putAll(specific);
    for (String verb : generic.keySet())
      {
        List<String> genericClassNames = generic.get(verb);
        List<String> classNames = combined.get(verb);
        if (classNames == null)
          {
            combined.put(verb, genericClassNames);
          }
        else
          {
            classNames.addAll(genericClassNames);
          }
      }
    return combined;
  }

  // -- Utility methods --
785

786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
  private List<URL> getSystemResources(String name)
  {
    List<URL> acc = new ArrayList<URL>();
    try
      {
        for (Enumeration<URL> i = ClassLoader.getSystemResources(name);
             i.hasMoreElements(); )
          {
            acc.add(i.nextElement());
          }
      }
    catch (IOException e)
      {
      }
    return acc;
  }

803
}