1 12 package org.eclipse.update.internal.core; 13 14 import java.io.BufferedWriter ; 15 import java.io.File ; 16 import java.io.FileNotFoundException ; 17 import java.io.FileOutputStream ; 18 import java.io.IOException ; 19 import java.io.InputStream ; 20 import java.io.OutputStream ; 21 import java.io.OutputStreamWriter ; 22 import java.io.PrintWriter ; 23 import java.io.UnsupportedEncodingException ; 24 import java.net.MalformedURLException ; 25 import java.net.URL ; 26 import java.util.ArrayList ; 27 import java.util.Arrays ; 28 import java.util.Date ; 29 import java.util.EmptyStackException ; 30 import java.util.HashMap ; 31 import java.util.List ; 32 import java.util.Locale ; 33 import java.util.Map ; 34 import java.util.ResourceBundle ; 35 import java.util.Stack ; 36 import java.util.StringTokenizer ; 37 38 import org.eclipse.core.runtime.Assert; 39 import org.eclipse.core.runtime.CoreException; 40 import org.eclipse.core.runtime.Platform; 41 import org.eclipse.osgi.util.NLS; 42 import org.eclipse.update.core.ContentReference; 43 import org.eclipse.update.core.IFeature; 44 import org.eclipse.update.core.IFeatureReference; 45 import org.eclipse.update.core.IImport; 46 import org.eclipse.update.core.IIncludedFeatureReference; 47 import org.eclipse.update.core.IPlatformEnvironment; 48 import org.eclipse.update.core.IPluginEntry; 49 import org.eclipse.update.core.InstallMonitor; 50 import org.eclipse.update.core.Site; 51 import org.eclipse.update.core.SiteManager; 52 import org.eclipse.update.core.Utilities; 53 import org.eclipse.update.core.model.InstallAbortedException; 54 import org.eclipse.update.internal.core.connection.ConnectionFactory; 55 import org.eclipse.update.internal.core.connection.IResponse; 56 import org.osgi.framework.Bundle; 57 import org.osgi.framework.Constants; 58 import org.osgi.service.packageadmin.PackageAdmin; 59 60 63 public class UpdateManagerUtils { 64 65 private static boolean OS_UNIX = org.eclipse.osgi.service.environment.Constants.OS_HPUX 66 .equals(Platform.getOS()) 67 || org.eclipse.osgi.service.environment.Constants.OS_AIX 68 .equals(Platform.getOS()) 69 || org.eclipse.osgi.service.environment.Constants.OS_LINUX 70 .equals(Platform.getOS()) 71 || org.eclipse.osgi.service.environment.Constants.OS_SOLARIS 72 .equals(Platform.getOS()); 73 private static FragmentEntry[] noFragments = new FragmentEntry[0]; 74 private static Map table; 75 76 static { 77 table = new HashMap (); 78 table.put("compatible", new Integer (IImport.RULE_COMPATIBLE)); table.put("perfect", new Integer (IImport.RULE_PERFECT)); table.put("equivalent", new Integer (IImport.RULE_EQUIVALENT)); table.put("greaterOrEqual", new Integer (IImport.RULE_GREATER_OR_EQUAL)); } 83 84 private static Writer writer; 85 private static Map urlFileMap; 87 88 private static Map localFileFragmentMap; 89 private static Stack bufferPool; 90 private static final int BUFFER_SIZE = 4096; private static final int INCREMENT_SIZE = 10240; 98 public static URL getURL(URL rootURL, String urlString, String defaultURL) throws MalformedURLException { 99 URL url = null; 100 101 if (urlString == null || urlString.trim().equals("")) { 104 if (defaultURL == null || defaultURL.trim().equals("")) return null; 107 else 108 urlString = defaultURL; 109 } 110 111 if (urlString.startsWith("/") && urlString.length() > 1) urlString = urlString.substring(1); 114 try { 115 url = new URL (urlString); 116 } catch (MalformedURLException e) { 117 url = new URL (rootURL, urlString); 120 } 121 122 return url; 123 } 124 125 131 public static String getURLAsString(URL rootURL, URL url) { 132 String result = null; 133 134 if (rootURL == null) { 135 return (url == null) ? null : url.toString(); 136 } 137 138 if (url != null) { 140 141 result = url.toExternalForm(); 142 143 if (rootURL.getHost() != null && !rootURL.getHost().equals(url.getHost())) 144 return result; 145 146 if (rootURL.getProtocol() != null && !rootURL.getProtocol().equals(url.getProtocol())) 147 return result; 148 149 if (rootURL.getPort() != url.getPort()) 150 return result; 151 152 String rootURLFileString = rootURL.getFile(); 153 rootURLFileString = rootURLFileString.replace(File.separatorChar, '/'); 154 if (!rootURLFileString.endsWith("/")) { int index = rootURLFileString.lastIndexOf('/'); 156 if (index != -1) { 157 rootURLFileString = rootURLFileString.substring(0, index); 158 } 159 } 160 String urlFileString = url.getFile(); 161 162 if (urlFileString.startsWith(rootURLFileString)) { 163 result = urlFileString.substring(rootURLFileString.length()); 164 result = result.replace(File.separatorChar, '/'); 165 } else { 166 if ("file".equalsIgnoreCase(url.getProtocol())) { File rootFile = new File (rootURLFileString); 170 File urlFile = new File (urlFileString); 171 172 File relativePath = urlFile; 173 while (relativePath != null && !rootFile.equals(relativePath.getParentFile())) { 174 relativePath = relativePath.getParentFile(); 175 } 176 177 if (relativePath == null) { 178 UpdateCore.warn("Cannot calculate relative path"); return url.toString(); 180 } else { 181 String relativeRootString = relativePath.getParentFile().getAbsolutePath(); 182 String fullString = urlFile.getAbsolutePath(); 183 if (!fullString.startsWith(relativeRootString)) { 184 UpdateCore.warn("Full path:" + fullString + " does not start with " + relativeRootString); return url.toString(); 186 } else { 187 String returnString = fullString.substring(relativeRootString.length() + 1); 188 if (urlFile.isDirectory()) 189 returnString += File.separator; 190 returnString = returnString.replace(File.separatorChar, '/'); 192 return returnString; 193 } 194 195 } 196 197 } else { 198 result = url.toString(); 199 } 200 } 201 } 202 203 return result; 204 } 205 206 209 public static String getResourceString(String infoURL, ResourceBundle bundle) { 210 String result = null; 211 if (infoURL != null) { 212 result = Platform.getResourceString(UpdateCore.getPlugin().getBundle(), infoURL, bundle); 213 } 214 return result; 215 } 216 217 220 public static URL copyToLocal(InputStream sourceContentReferenceStream, String localName, InstallMonitor monitor) throws MalformedURLException , IOException , InstallAbortedException { 221 URL result = null; 222 File localFile = new File (localName); 226 int index = localFile.getPath().lastIndexOf(File.separator); 227 if (index != -1) { 228 File dir = new File (localFile.getPath().substring(0, index)); 229 if (!dir.exists()) 230 dir.mkdirs(); 231 } 232 233 if (!localFile.isDirectory()) { 235 OutputStream localContentReferenceStream = new FileOutputStream (localFile); 236 try { 237 Utilities.copy(sourceContentReferenceStream, localContentReferenceStream, monitor); 238 } finally { 239 try { 240 localContentReferenceStream.close(); 241 } catch (IOException e){} 242 } 243 } 244 result = localFile.toURL(); 245 return result; 246 } 247 248 252 public static void checkPermissions(ContentReference ref, String filePath) { 253 254 if (ref.getPermission() != 0) { 255 UpdateCore.warn("Change permission for " + filePath + " to " + ref.getPermission()); } 258 259 if (filePath != null && OS_UNIX && ref.getPermission() != 0) { 260 try { 264 Process pr = Runtime.getRuntime().exec(new String [] { "chmod", "a+x", filePath }); Thread chmodOutput = new StreamConsumer(pr.getInputStream()); 266 chmodOutput.setName("chmod output reader"); chmodOutput.start(); 268 Thread chmodError = new StreamConsumer(pr.getErrorStream()); 269 chmodError.setName("chmod error reader"); chmodError.start(); 271 } catch (IOException ioe) { 272 } 273 274 } 275 } 276 277 286 public static String getLocalRandomIdentifier(String remotePath, Date date) { 287 int dotIndex = remotePath.lastIndexOf("."); int fileIndex = remotePath.lastIndexOf(File.separator); 289 String ext = (dotIndex != -1 && fileIndex < dotIndex) ? remotePath.substring(dotIndex) : ""; if (fileIndex == -1) 296 fileIndex = 0; 297 if (dotIndex == -1) 298 dotIndex = remotePath.length(); 299 String name = (fileIndex < dotIndex) ? remotePath.substring(fileIndex, dotIndex) : "Eclipse_Update_TMP_"; String result = name + date.getTime() + ext; 303 return result; 304 } 305 306 310 public static void removeFromFileSystem(File file) { 311 if (!file.exists() || !file.canWrite()) 312 return; 313 314 if (file.isDirectory()) { 315 String [] files = file.list(); 316 if (files != null) for (int i = 0; i < files.length; ++i) 318 removeFromFileSystem(new File (file, files[i])); 319 } 320 321 if (!file.delete()) { 322 String msg = NLS.bind(Messages.UpdateManagerUtils_UnableToRemoveFile, (new String [] { file.getAbsolutePath() })); 323 UpdateCore.log(msg, new Exception ()); 324 } 325 } 326 327 331 public static void removeEmptyDirectoriesFromFileSystem(File file) { 332 if (!file.isDirectory()) 333 return; 334 335 String [] files = file.list(); 336 if (files != null) { for (int i = 0; i < files.length; ++i) { 338 removeEmptyDirectoriesFromFileSystem(new File (file, files[i])); 339 } 340 } 341 if (!file.delete()) { 342 String msg = NLS.bind(Messages.UpdateManagerUtils_UnableToRemoveFile, (new String [] { file.getAbsolutePath() })); 343 UpdateCore.log(msg, new Exception ()); 344 } 345 } 346 347 351 public static IPluginEntry[] diff(IPluginEntry[] sourceArray, IPluginEntry[] targetArray) { if (sourceArray == null || sourceArray.length == 0) { 353 return new IPluginEntry[0]; 354 } if (targetArray == null || targetArray.length == 0) { 356 return sourceArray; 357 } List list1 = Arrays.asList(targetArray); 360 List result = new ArrayList (0); 361 for (int i = 0; i < sourceArray.length; i++) { 362 if (!list1.contains(sourceArray[i])) 363 result.add(sourceArray[i]); 364 } 365 366 IPluginEntry[] resultEntry = new IPluginEntry[result.size()]; 367 if (result.size() > 0) 368 result.toArray(resultEntry); 369 return resultEntry; 370 } 371 372 391 public static URL getParent(URL url) { 392 String file = url.getFile(); 393 int len = file.length(); 394 if (len == 0 || len == 1 && file.charAt(0) == '/') 395 return null; 396 int lastSlashIndex = -1; 397 for (int i = len - 2; lastSlashIndex == -1 && i >= 0; --i) { 398 if (file.charAt(i) == '/') 399 lastSlashIndex = i; 400 } 401 if (lastSlashIndex == -1) 402 file = ""; else 404 file = file.substring(0, lastSlashIndex + 1); 405 try { 406 url = new URL (url.getProtocol(), url.getHost(), url.getPort(), file); 407 } catch (MalformedURLException e) { 408 Assert.isTrue(false, e.getMessage()); 409 } 410 return url; 411 } 412 413 416 public static URL asDirectoryURL(URL url) throws MalformedURLException { 417 String path = url.getFile(); 419 if (!path.endsWith("/")) { int index = path.lastIndexOf('/'); 421 if (index != -1) 422 path = path.substring(0, index + 1); 423 url = new URL (url.getProtocol(), url.getHost(), url.getPort(), path); 425 } 426 return url; 427 } 428 429 433 public static boolean sameURL(URL url1, URL url2) { 434 435 if (url1 == null || url2 == null) 436 return false; 437 if (url1 == url2) 438 return true; 439 if (url1.equals(url2)) 440 return true; 441 442 if (!"file".equalsIgnoreCase(url1.getProtocol())) return false; 448 if (!"file".equalsIgnoreCase(url2.getProtocol())) return false; 450 451 File file1 = getFileFor(url1); File file2 = getFileFor(url2); 453 454 if (file1 == null) 455 return false; 456 457 return (file1.equals(file2)); 458 } 459 460 465 private static File getFileFor(URL url1) { 466 if (urlFileMap == null) urlFileMap = new HashMap (); 467 if (urlFileMap.get(url1)!=null) return (File )urlFileMap.get(url1); 468 File newFile = new File (url1.getFile()); 469 urlFileMap.put(url1,newFile); 470 return newFile; 471 } 472 473 480 public static IFeatureReference[] getParentFeatures(IFeature childFeature, IFeatureReference[] possiblesParent, boolean onlyOptional) throws CoreException { 481 482 if (childFeature == null) 483 return new IFeatureReference[0]; 484 485 List parentList = new ArrayList (); 486 IIncludedFeatureReference[] children = null; 487 IFeature compareFeature = null; 488 for (int i = 0; i < possiblesParent.length; i++) { 489 try { 490 IFeature possibleParentFeature = possiblesParent[i].getFeature(null); 491 if (possibleParentFeature != null) { 492 children = possibleParentFeature.getIncludedFeatureReferences(); 493 for (int j = 0; j < children.length; j++) { 494 try { 495 compareFeature = children[j].getFeature(null); 496 } catch (CoreException e) { 497 UpdateCore.warn("", e); } 499 if (childFeature.equals(compareFeature)) { 500 if (onlyOptional) { 501 if (UpdateManagerUtils.isOptional(children[j])) { 502 parentList.add(possiblesParent[i]); 503 } else { 504 UpdateCore.warn("Feature :" + children[j] + " not optional. Not included in parents list."); } 506 } else { 507 parentList.add(possiblesParent[i]); 508 } 509 } 510 } 511 } 512 } catch (CoreException e) { 513 UpdateCore.warn("", e); } 515 } 516 517 IFeatureReference[] parents = new IFeatureReference[0]; 518 if (parentList.size() > 0) { 519 parents = new IFeatureReference[parentList.size()]; 520 parentList.toArray(parents); 521 } 522 return parents; 523 } 524 525 532 public static IFeatureReference[] getParentFeatures(IFeatureReference child, IFeatureReference[] possiblesParent, boolean onlyOptional) throws CoreException { 533 534 if (child == null) 535 return new IFeatureReference[0]; 536 537 IFeature childFeature = null; 538 try { 539 childFeature = child.getFeature(null); 540 } catch (CoreException e) { 541 UpdateCore.warn(null, e); 542 } 543 544 if (childFeature == null) 545 return new IFeatureReference[0]; 546 547 return getParentFeatures(childFeature, possiblesParent, onlyOptional); 548 } 549 550 555 public static void checkConnectionResult(IResponse response,URL url) throws IOException { 556 int result = response.getStatusCode(); 558 559 if (result != IStatusCodes.HTTP_OK) { 560 String serverMsg = response.getStatusMessage(); 561 response.close(); 562 throw new FatalIOException(NLS.bind(Messages.ContentReference_HttpNok, (new Object [] { new Integer (result), serverMsg, url }))); 563 } 564 } 565 566 public static class StreamConsumer extends Thread { 567 InputStream is; 568 byte[] buf; 569 public StreamConsumer(InputStream inputStream) { 570 super(); 571 this.setDaemon(true); 572 this.is = inputStream; 573 buf = new byte[512]; 574 } 575 public void run() { 576 try { 577 int n = 0; 578 while (n >= 0) 579 n = is.read(buf); 580 } catch (IOException ioe) { 581 } 582 } 583 } 584 585 595 public static IFeatureReference[] optionalChildrenToInstall(IFeatureReference[] children, IFeatureReference[] optionalfeatures) { 596 597 List optionalChildrenToInstall = new ArrayList (); 598 for (int i = 0; i < children.length; i++) { 599 IFeatureReference optionalFeature = children[i]; 600 if (!UpdateManagerUtils.isOptional(optionalFeature)) { 601 optionalChildrenToInstall.add(optionalFeature); 602 } else { 603 for (int j = 0; j < optionalfeatures.length; j++) { 604 if (optionalFeature.equals(optionalfeatures[j])) { 605 optionalChildrenToInstall.add(optionalFeature); 606 break; 607 } 608 } 609 } 610 } 611 612 IFeatureReference[] result = new IFeatureReference[optionalChildrenToInstall.size()]; 613 if (optionalChildrenToInstall.size() > 0) { 614 optionalChildrenToInstall.toArray(result); 615 } 616 617 return result; 618 } 619 620 626 public static int getMatchingRule(String rule) { 627 if (rule == null) 628 return IImport.RULE_COMPATIBLE; 629 int ruleInt = ((Integer ) table.get(rule)).intValue(); 630 if (ruleInt == IImport.RULE_NONE) 631 return IImport.RULE_PERFECT; 632 return ruleInt; 633 } 634 635 641 public static int getMatchingIdRule(String rule) { 642 643 if (rule == null) 644 return IImport.RULE_COMPATIBLE; 645 if (rule!=null && rule.equalsIgnoreCase("prefix")) return IImport.RULE_PREFIX; 647 return IImport.RULE_PERFECT; 648 } 649 650 655 public static boolean isOptional(IFeatureReference featureReference) { 656 if (featureReference==null) return false; 657 if (featureReference instanceof IIncludedFeatureReference){ 658 return ((IIncludedFeatureReference)featureReference).isOptional(); 659 } 660 return false; 661 } 662 663 666 public static boolean isValidEnvironment(IPlatformEnvironment candidate) { 667 if (candidate==null) return false; 668 String os = candidate.getOS(); 669 String ws = candidate.getWS(); 670 String arch = candidate.getOSArch(); 671 String nl = candidate.getNL(); 672 if (os!=null && !isMatching(os, SiteManager.getOS())) return false; 673 if (ws!=null && !isMatching(ws, SiteManager.getWS())) return false; 674 if (arch!=null && !isMatching(arch, SiteManager.getOSArch())) return false; 675 if (nl!=null && !isMatchingLocale(nl, SiteManager.getNL())) return false; 676 return true; 677 } 678 679 694 695 698 699 private static boolean isMatching(String candidateValues, String siteValues) { 700 if (siteValues==null) return false; 701 if ("*".equals(candidateValues)) return true; if ("".equals(candidateValues)) return true; StringTokenizer siteTokens = new StringTokenizer (siteValues, ","); while(siteTokens.hasMoreTokens()) { 706 StringTokenizer candidateTokens = new StringTokenizer 707 (candidateValues, ","); String siteValue = siteTokens.nextToken(); 709 while (candidateTokens.hasMoreTokens()) { 710 if (siteValue.equalsIgnoreCase 711 (candidateTokens.nextToken())) return true; 712 } 713 } 714 return false; 715 } 716 717 718 721 private static boolean isMatchingLocale(String candidateValues, String locale) { 722 if (locale==null) return false; 723 if ("*".equals(candidateValues)) return true; if ("".equals(candidateValues)) return true; 726 locale = locale.toUpperCase(); 727 candidateValues = candidateValues.toUpperCase(); 728 StringTokenizer stok = new StringTokenizer (candidateValues, ","); while (stok.hasMoreTokens()) { 730 String candidate = stok.nextToken(); 731 if (locale.indexOf(candidate) == 0) 732 return true; 733 if (candidate.indexOf(locale) == 0) 734 return true; 735 } 736 return false; 737 } 738 739 740 743 public static class Writer { 744 745 private PrintWriter w; 746 private OutputStream out; 747 private OutputStreamWriter outWriter; 748 private BufferedWriter buffWriter; 749 private String encoding; 750 751 754 private Writer() { 755 super(); 756 } 757 758 public void init(File file, String encoding) throws FileNotFoundException , UnsupportedEncodingException { 759 this.encoding = encoding; 760 out = new FileOutputStream (file); 761 outWriter = new OutputStreamWriter (out, encoding); 762 buffWriter = new BufferedWriter (outWriter); 763 w = new PrintWriter (buffWriter); 764 } 765 766 767 770 public void write(IWritable element) { 771 w.println("<?xml version=\"1.0\" encoding=\""+encoding+"\"?>"); w.println(""); w.println("<!-- File written by Update manager 2.0 -->"); w.println("<!-- comments in this file are not preserved -->"); w.println(""); element.write(0, w); 777 close(); 778 } 779 780 783 public void close(){ 784 w.close(); 785 } 786 787 790 private static void appendEscapedChar(StringBuffer buffer, char c) { 791 String replacement = getReplacement(c); 792 if (replacement != null) { 793 buffer.append('&'); 794 buffer.append(replacement); 795 buffer.append(';'); 796 } else { 797 if ((c >= ' ' && c <= 0x7E) || c == '\n' || c == '\r' || c == '\t') { 798 buffer.append(c); 799 } else { 800 buffer.append("&#"); buffer.append(Integer.toString(c)); 802 buffer.append(';'); 803 } 804 } 805 } 806 807 810 public static String xmlSafe(String s) { 811 StringBuffer result = new StringBuffer (s.length() + 10); 812 for (int i = 0; i < s.length(); ++i) 813 appendEscapedChar(result, s.charAt(i)); 814 return result.toString(); 815 } 816 817 820 private static String getReplacement(char c) { 821 switch (c) { 824 case '<' : 825 return "lt"; case '>' : 827 return "gt"; case '"' : 829 return "quot"; case '\'' : 831 return "apos"; case '&' : 833 return "amp"; } 835 return null; 836 } 837 } 838 public static Writer getWriter(File file,String encoding) throws FileNotFoundException , UnsupportedEncodingException { 839 if (writer==null) writer = new Writer (); 840 writer.init(file,encoding); 841 return writer; 842 } 843 844 public static boolean isSameTimestamp(URL url, long timestamp) { 845 try { 846 if (UpdateCore.getPlugin().getUpdateSession().isVisited(url)) { 847 return true; 848 } 849 URL resolvedURL = URLEncoder.encode(url); 850 IResponse response = ConnectionFactory.get(resolvedURL); 851 long remoteLastModified = response.getLastModified(); 852 return Math.abs(remoteLastModified - timestamp)/1000 <= 2; 855 } catch (MalformedURLException e) { 856 return false; 857 } catch (IOException e) { 858 return false; 859 } 860 } 861 866 public synchronized static void mapLocalFileFragment(String key, FileFragment temp) { 867 if (key != null) { 869 if (localFileFragmentMap == null) 870 localFileFragmentMap = new HashMap (); 871 localFileFragmentMap.put(key, temp); 872 } 873 } 874 875 879 public synchronized static void unMapLocalFileFragment(String key) { 880 if (key != null && localFileFragmentMap !=null) { 882 localFileFragmentMap.remove(key); 883 } 884 } 885 886 893 public static synchronized FileFragment lookupLocalFileFragment(String key) { 894 if (localFileFragmentMap == null) 895 return null; 896 return (FileFragment) localFileFragmentMap.get(key); 897 } 898 899 910 public static long copy(InputStream is, OutputStream os, InstallMonitor monitor, long expectedLength) { 911 byte[] buf = getBuffer(); 912 long offset=0; 913 try { 914 int len = is.read(buf); 915 int nextIncrement = 0; 916 while (len != -1) { 917 os.write(buf, 0, len); 918 offset += len; 919 if (monitor != null) { 920 nextIncrement += len; 921 if (nextIncrement >= INCREMENT_SIZE){ 923 monitor.incrementCount(nextIncrement); 924 nextIncrement = 0; 925 } 926 if (monitor.isCanceled()) { 927 return offset; 928 } 929 } 930 if (expectedLength > 0 && offset == expectedLength) { 931 break; 934 } 935 936 len = is.read(buf); 937 } 938 if (nextIncrement > 0 && monitor != null) 939 monitor.incrementCount(nextIncrement); 940 if(expectedLength>0 && offset!=expectedLength) 941 throw new IOException (NLS.bind(Messages.UpdateManagerUtils_inputStreamEnded, (new String [] { String.valueOf(offset), String.valueOf(expectedLength) }))); 942 return -1; 943 } catch(IOException e){ 944 UpdateCore.log(Messages.UpdateManagerUtils_copy + offset, e); 947 return offset; 948 } finally { 949 freeBuffer(buf); 950 } 951 } 952 953 public static class CopyException extends Exception { 954 955 private static final long serialVersionUID = 1L; 956 Exception rootException; 957 int bytesCopied; 958 959 962 public CopyException(Exception rootException, int bytesCopied) { 963 super(); 964 this.rootException= rootException; 965 this.bytesCopied=bytesCopied; 966 } 967 971 public Exception getRootException(){ 972 return rootException; 973 } 974 public int getBytesCopied(){ 975 return bytesCopied; 976 } 977 978 } 979 980 private static synchronized byte[] getBuffer() { 981 if (bufferPool == null) { 982 return new byte[BUFFER_SIZE]; 983 } 984 985 try { 986 return (byte[]) bufferPool.pop(); 987 } catch (EmptyStackException e) { 988 return new byte[BUFFER_SIZE]; 989 } 990 } 991 992 private static synchronized void freeBuffer(byte[] buf) { 993 if (bufferPool == null) 994 bufferPool = new Stack (); 995 bufferPool.push(buf); 996 } 997 998 999 1003 public static FragmentEntry[] getFragments(Bundle bundle) { 1004 PackageAdmin pkgAdmin = UpdateCore.getPlugin().getPackageAdmin(); 1005 Bundle [] fragmentBundles = pkgAdmin.getFragments(bundle); 1006 if (fragmentBundles == null) 1007 return noFragments; 1008 1009 FragmentEntry[] fragments = new FragmentEntry[fragmentBundles.length]; 1010 for (int i = 0; i < fragments.length; i++) { 1011 fragments[i] = new FragmentEntry((String ) fragmentBundles[i] 1012 .getHeaders().get(Constants.BUNDLE_SYMBOLICNAME), 1013 (String ) fragmentBundles[i].getHeaders().get( 1014 Constants.BUNDLE_VERSION), Platform 1015 .getResourceString(fragmentBundles[i], 1016 (String ) fragmentBundles[i].getHeaders() 1017 .get(Constants.BUNDLE_VERSION)), 1018 fragmentBundles[i].getLocation()); 1019 } 1020 return fragments; 1021 } 1022 1023 public static String getWritableXMLString(String value) { 1024 StringBuffer buf = new StringBuffer (); 1025 if(value == null) 1026 return buf.toString(); 1027 for (int i = 0; i < value.length(); i++) { 1028 char c = value.charAt(i); 1029 switch (c) { 1030 case '&' : 1031 buf.append("&"); break; 1033 case '<' : 1034 buf.append("<"); break; 1036 case '>' : 1037 buf.append(">"); break; 1039 case '\'' : 1040 buf.append("'"); break; 1042 case '\"' : 1043 buf.append("""); break; 1045 default : 1046 buf.append(c); 1047 break; 1048 } 1049 } 1050 return buf.toString(); 1051 } 1052 1053 public static LiteFeature[] getLightFeatures(ExtendedSite site) { 1054 1055 URL fullDigestURL; 1056 try { 1057 fullDigestURL = getFullDigestURL( site, Locale.getDefault().getCountry(), Locale.getDefault().getLanguage()); 1058 } catch (MalformedURLException e) { 1059 UpdateCore.log("Could not access digest on the site: " + e.getMessage(), null); return null; 1061 } 1062 1063 Digest digest = new Digest( fullDigestURL); 1064 try { 1065 LiteFeature[] features = (LiteFeature[])digest.parseDigest(); 1066 for(int i = 0; i < features.length; i++) { 1067 features[i].setSite(site); 1068 } 1069 return features; 1070 } catch(Exception e){ 1071 UpdateCore.log("Digest could not be parsed:" + e.getMessage(), null); return null; 1073 } 1074 } 1075 1076 private static URL getFullDigestURL(ExtendedSite site, String country, String language) throws MalformedURLException { 1077 1078 String digestURL = (site.getDigestURL().endsWith("/")? site.getDigestURL(): site.getDigestURL() + "/"); 1080 if (digestURL.indexOf("://") == -1) { String siteURL = site.getLocationURL().toExternalForm(); 1082 if (siteURL.endsWith(Site.SITE_XML)) { 1083 siteURL = siteURL.substring(0, siteURL.length() - Site.SITE_XML.length()); 1084 } 1085 if (digestURL.equals("/")) { digestURL = siteURL; 1087 } else { 1088 if (digestURL.startsWith("/")) { digestURL = digestURL.substring(1, digestURL.length()); 1090 } 1091 digestURL = siteURL + digestURL; 1092 } 1093 } 1094 1095 digestURL += "digest"; 1097 if ( isLocalSupported(site, country, language)) { 1098 return new URL (digestURL + "_" + language + "_" + country + ".zip"); } 1100 if ( isLangaugeSupported(site, language)) { 1101 return new URL (digestURL + "_" + language + ".zip"); } 1103 return new URL (digestURL + ".zip"); } 1105 1106 private static boolean isLangaugeSupported(ExtendedSite site, String language) { 1107 String [] availableLanguages = site.getAvailableLocals(); 1108 if ((availableLanguages == null) || (availableLanguages.length == 0)) { 1109 return false; 1110 } 1111 for(int i = 0; i < availableLanguages.length; i++) { 1112 if (availableLanguages[i].equals(language)) { 1113 return true; 1114 } 1115 } 1116 return false; 1117 } 1118 1119 private static boolean isLocalSupported(ExtendedSite site, String country, String language) { 1120 String localeCode = language + "_" + country; String [] availableLocals = site.getAvailableLocals(); 1122 if ((availableLocals == null) || (availableLocals.length == 0)) { 1123 return false; 1124 } 1125 for(int i = 0; i < availableLocals.length; i++) { 1126 if (availableLocals[i].equals(localeCode)) { 1127 return true; 1128 } 1129 } 1130 return false; 1131 } 1132} 1133 | Popular Tags |