Exemplo n.º 1
0
 public static void updateRepositoryUsingElements(
     final ProvisioningUI ui, final MetadataRepositoryElement[] elements) {
   ui.signalRepositoryOperationStart();
   IMetadataRepositoryManager metaManager = ProvUI.getMetadataRepositoryManager(ui.getSession());
   IArtifactRepositoryManager artManager = ProvUI.getArtifactRepositoryManager(ui.getSession());
   try {
     int visibilityFlags = ui.getRepositoryTracker().getMetadataRepositoryFlags();
     URI[] currentlyEnabled = metaManager.getKnownRepositories(visibilityFlags);
     URI[] currentlyDisabled =
         metaManager.getKnownRepositories(
             IRepositoryManager.REPOSITORIES_DISABLED | visibilityFlags);
     for (int i = 0; i < elements.length; i++) {
       URI location = elements[i].getLocation();
       if (elements[i].isEnabled()) {
         if (containsURI(currentlyDisabled, location))
           // It should be enabled and is not currently
           setColocatedRepositoryEnablement(ui, location, true);
         else if (!containsURI(currentlyEnabled, location)) {
           // It is not known as enabled or disabled.  Add it.
           metaManager.addRepository(location);
           artManager.addRepository(location);
         }
       } else {
         if (containsURI(currentlyEnabled, location))
           // It should be disabled, and is currently enabled
           setColocatedRepositoryEnablement(ui, location, false);
         else if (!containsURI(currentlyDisabled, location)) {
           // It is not known as enabled or disabled.  Add it and then disable it.
           metaManager.addRepository(location);
           artManager.addRepository(location);
           setColocatedRepositoryEnablement(ui, location, false);
         }
       }
       String name = elements[i].getName();
       if (name != null && name.length() > 0) {
         metaManager.setRepositoryProperty(location, IRepository.PROP_NICKNAME, name);
         artManager.setRepositoryProperty(location, IRepository.PROP_NICKNAME, name);
       }
     }
     // Are there any elements that need to be deleted?  Go over the original state
     // and remove any elements that weren't in the elements we were given
     Set<String> nowKnown = new HashSet<String>();
     for (int i = 0; i < elements.length; i++)
       nowKnown.add(URIUtil.toUnencodedString(elements[i].getLocation()));
     for (int i = 0; i < currentlyEnabled.length; i++) {
       if (!nowKnown.contains(URIUtil.toUnencodedString(currentlyEnabled[i]))) {
         metaManager.removeRepository(currentlyEnabled[i]);
         artManager.removeRepository(currentlyEnabled[i]);
       }
     }
     for (int i = 0; i < currentlyDisabled.length; i++) {
       if (!nowKnown.contains(URIUtil.toUnencodedString(currentlyDisabled[i]))) {
         metaManager.removeRepository(currentlyDisabled[i]);
         artManager.removeRepository(currentlyDisabled[i]);
       }
     }
   } finally {
     ui.signalRepositoryOperationComplete(null, true);
   }
 }
Exemplo n.º 2
0
 @Override
 public String getSourceLocation() {
   IResource sourceResource;
   String sourceLocation = null;
   if (fFileSystemObject.isDirectory()) {
     sourceResource =
         ResourcesPlugin.getWorkspace()
             .getRoot()
             .getContainerForLocation(Path.fromOSString(fFileSystemObject.getAbsolutePath()));
   } else {
     sourceResource =
         ResourcesPlugin.getWorkspace()
             .getRoot()
             .getFileForLocation(Path.fromOSString(fFileSystemObject.getAbsolutePath()));
   }
   if (sourceResource != null && sourceResource.exists()) {
     try {
       sourceLocation = sourceResource.getPersistentProperty(TmfCommonConstants.SOURCE_LOCATION);
     } catch (CoreException e) {
       // Something went wrong with the already existing resource.
       // This is not a problem, we'll assign a new location below.
     }
   }
   if (sourceLocation == null) {
     try {
       sourceLocation = URIUtil.toUnencodedString(fFileSystemObject.getCanonicalFile().toURI());
     } catch (IOException e) {
       // Something went wrong canonicalizing the file. We can still
       // use the URI but there might be extra ../ in it.
       sourceLocation = URIUtil.toUnencodedString(fFileSystemObject.toURI());
     }
   }
   return sourceLocation;
 }
  /**
   * Given a relative path, derive its absolute path from the given class.
   *
   * @param testClass
   * @param path
   * @return
   */
  private static String getBundlePath(Class<?> testClass, Path path) {
    Bundle bundle = FrameworkUtil.getBundle(testClass);
    File file = null;
    try {
      URL url = FileLocator.find(bundle, path, null);
      URL fileURL = FileLocator.toFileURL(url);
      file = URIUtil.toFile(URIUtil.toURI(fileURL));
    } catch (Exception ex) {
      ex.printStackTrace();
      Assert.fail("Unable to open the data file \"" + path + "\""); // $NON-NLS-1$ //$NON-NLS-2$
    }

    return file.getAbsolutePath();
  }
 /**
  * Test sample project with a virtual folder that points to configure scripts. Tests Bug 434275 -
  * Autotools configuration in subfolder not found
  *
  * @throws Exception
  */
 @Test
 public void testAutotoolsVirtualFolder() throws Exception {
   Path p = new Path("zip/project2.zip");
   IWorkspaceRoot root = ProjectTools.getWorkspaceRoot();
   IPath rootPath = root.getLocation();
   IPath configPath = rootPath.append("config");
   File configDir = configPath.toFile();
   configDir.deleteOnExit();
   assertTrue(configDir.mkdir());
   ProjectTools.createLinkedFolder(
       testProject, "src", URIUtil.append(root.getLocationURI(), "config"));
   ProjectTools.addSourceContainerWithImport(testProject, "src", p);
   assertTrue(testProject.hasNature(AutotoolsNewProjectNature.AUTOTOOLS_NATURE_ID));
   assertTrue(exists("src/ChangeLog"));
   ProjectTools.setConfigDir(testProject, "src");
   ProjectTools.markExecutable(testProject, "src/autogen.sh");
   assertFalse(exists("src/configure"));
   assertFalse(exists("src/Makefile.in"));
   assertFalse(exists("src/sample/Makefile.in"));
   assertFalse(exists("src/aclocal.m4"));
   assertTrue(ProjectTools.build());
   assertTrue(exists("src/configure"));
   assertTrue(exists("src/Makefile.in"));
   assertTrue(exists("src/sample/Makefile.in"));
   assertTrue(exists("src/aclocal.m4"));
   assertTrue(exists("config.status"));
   assertTrue(exists("Makefile"));
   String extension = Platform.getOS().equals(Platform.OS_WIN32) ? ".exe" : "";
   assertTrue(exists("sample/a.out" + extension));
   assertTrue(exists("sample/Makefile"));
 }
Exemplo n.º 5
0
 private boolean handlePost(
     HttpServletRequest request, HttpServletResponse response, IFileStore dir)
     throws JSONException, CoreException, ServletException, IOException {
   // setup and precondition checks
   JSONObject requestObject = OrionServlet.readJSONRequest(request);
   String name = computeName(request, requestObject);
   if (name.length() == 0)
     return statusHandler.handleRequest(
         request,
         response,
         new ServerStatus(
             IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "File name not specified.", null));
   int options = getCreateOptions(request);
   IFileStore toCreate = dir.getChild(name);
   boolean destinationExists = toCreate.fetchInfo().exists();
   if (!validateOptions(request, response, toCreate, destinationExists, options)) return true;
   // perform the operation
   if (performPost(request, response, requestObject, toCreate, options)) {
     // write the response
     URI location = URIUtil.append(getURI(request), name);
     JSONObject result = ServletFileStoreHandler.toJSON(toCreate, toCreate.fetchInfo(), location);
     OrionServlet.writeJSONResponse(request, response, result);
     response.setHeader(ProtocolConstants.HEADER_LOCATION, location.toString());
     // response code should indicate if a new resource was actually created or not
     response.setStatus(
         destinationExists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_CREATED);
   }
   return true;
 }
  /**
   * Returns paths constructed by rewriting pathInfo using rules from the hosted site's mappings.
   * Paths are ordered from most to least specific match.
   *
   * @param site The hosted site.
   * @param pathInfo Path to be rewritten.
   * @param queryString
   * @return The rewritten path. May be either:
   *     <ul>
   *       <li>A path to a file in the Orion workspace, eg. <code>/ProjectA/foo/bar.txt</code>
   *       <li>An absolute URL pointing to another site, eg. <code>http://foo.com/bar.txt</code>
   *     </ul>
   *
   * @return The rewritten paths.
   * @throws URISyntaxException
   */
  private URI[] getMapped(IHostedSite site, IPath pathInfo, String queryString)
      throws URISyntaxException {
    final Map<String, List<String>> map = site.getMappings();
    final IPath originalPath = pathInfo;
    IPath path = originalPath.removeTrailingSeparator();

    List<URI> uris = new ArrayList<URI>();
    String rest = null;
    final int count = path.segmentCount();
    for (int i = 0; i <= count; i++) {
      List<String> base = map.get(path.toString());
      if (base != null) {
        rest = originalPath.removeFirstSegments(count - i).toString();
        for (int j = 0; j < base.size(); j++) {
          URI uri =
              rest.equals("") ? new URI(base.get(j)) : URIUtil.append(new URI(base.get(j)), rest);
          uris.add(
              new URI(
                  uri.getScheme(),
                  uri.getUserInfo(),
                  uri.getHost(),
                  uri.getPort(),
                  uri.getPath(),
                  queryString,
                  uri.getFragment()));
        }
      }
      path = path.removeLastSegments(1);
    }
    if (uris.size() == 0)
      // No mapping for /
      return null;
    else return uris.toArray(new URI[uris.size()]);
  }
 private org.eclipse.equinox.internal.simpleconfigurator.utils.BundleInfo[] convertBundleInfos(
     BundleInfo[] configuration, URI installArea) {
   // convert to SimpleConfigurator BundleInfo Type
   org.eclipse.equinox.internal.simpleconfigurator.utils.BundleInfo[] simpleInfos =
       new org.eclipse.equinox.internal.simpleconfigurator.utils.BundleInfo[configuration.length];
   for (int i = 0; i < configuration.length; i++) {
     BundleInfo bundleInfo = configuration[i];
     URI location = bundleInfo.getLocation();
     if (bundleInfo.getSymbolicName() == null
         || bundleInfo.getVersion() == null
         || location == null)
       throw new IllegalArgumentException(
           "Cannot persist bundleinfo: " + bundleInfo.toString()); // $NON-NLS-1$
     // only need to make a new BundleInfo if we are changing it.
     if (installArea != null) location = URIUtil.makeRelative(location, installArea);
     simpleInfos[i] =
         new org.eclipse.equinox.internal.simpleconfigurator.utils.BundleInfo(
             bundleInfo.getSymbolicName(),
             bundleInfo.getVersion(),
             location,
             bundleInfo.getStartLevel(),
             bundleInfo.isMarkedAsStarted());
     simpleInfos[i].setBaseLocation(bundleInfo.getBaseLocation());
   }
   return simpleInfos;
 }
Exemplo n.º 8
0
  private ServerStatus getSpaces(List<Space> spaces, JSONObject orgJSON) throws Exception {
    URI targetURI = URIUtil.toURI(target.getUrl());
    URI spaceURI = targetURI.resolve(orgJSON.getJSONObject("entity").getString("spaces_url"));

    GetMethod getDomainsMethod = new GetMethod(spaceURI.toString());
    HttpUtil.configureHttpMethod(getDomainsMethod, target);
    getDomainsMethod.setQueryString("inline-relations-depth=1"); // $NON-NLS-1$

    ServerStatus status = HttpUtil.executeMethod(getDomainsMethod);
    if (!status.isOK()) return status;

    /* extract available spaces */
    JSONObject orgs = status.getJsonData();

    if (orgs.getInt(CFProtocolConstants.V2_KEY_TOTAL_RESULTS) < 1) {
      return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK);
    }

    /* look if the domain is available */
    int resources = orgs.getJSONArray(CFProtocolConstants.V2_KEY_RESOURCES).length();
    for (int k = 0; k < resources; ++k) {
      JSONObject spaceJSON =
          orgs.getJSONArray(CFProtocolConstants.V2_KEY_RESOURCES).getJSONObject(k);
      spaces.add(new Space().setCFJSON(spaceJSON));
    }

    return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK);
  }
  private void saveConfiguration(
      BundleInfo[] configuration, File outputFile, URI installArea, boolean backup)
      throws IOException {
    if (backup && outputFile.exists()) {
      File backupFile = Utils.getSimpleDataFormattedFile(outputFile);
      if (!outputFile.renameTo(backupFile)) {
        throw new IOException("Fail to rename from (" + outputFile + ") to (" + backupFile + ")");
      }
    }

    org.eclipse.equinox.internal.simpleconfigurator.utils.BundleInfo[] simpleInfos =
        convertBundleInfos(configuration, installArea);

    // if empty remove the configuration file
    if (simpleInfos == null || simpleInfos.length == 0) {
      if (outputFile.exists()) {
        outputFile.delete();
      }
      File parentDir = outputFile.getParentFile();
      if (parentDir.exists()) {
        parentDir.delete();
      }
      return;
    }
    SimpleConfiguratorManipulatorUtils.writeConfiguration(simpleInfos, outputFile);
    if (CONFIG_LIST.equals(outputFile.getName())
        && installArea != null
        && isSharedInstallSetup(URIUtil.toFile(installArea), outputFile))
      rememberSharedBundlesInfoTimestamp(installArea, outputFile.getParentFile());
  }
  /*
   * InputStream must be closed
   * (non-Javadoc)
   * @see org.eclipse.equinox.simpleconfigurator.manipulator.SimpleConfiguratorManipulator#loadConfiguration(java.io.InputStream, java.net.URI)
   */
  public BundleInfo[] loadConfiguration(InputStream stream, URI installArea) throws IOException {
    if (stream == null) return NULL_BUNDLEINFOS;

    List simpleBundles = SimpleConfiguratorUtils.readConfiguration(stream, installArea);

    // convert to FrameworkAdmin BundleInfo Type
    BundleInfo[] result = new BundleInfo[simpleBundles.size()];
    int i = 0;
    for (Iterator iterator = simpleBundles.iterator(); iterator.hasNext(); ) {
      org.eclipse.equinox.internal.simpleconfigurator.utils.BundleInfo simpleInfo =
          (org.eclipse.equinox.internal.simpleconfigurator.utils.BundleInfo) iterator.next();
      URI location = simpleInfo.getLocation();
      if (!location.isAbsolute() && simpleInfo.getBaseLocation() != null)
        location = URIUtil.makeAbsolute(location, simpleInfo.getBaseLocation());

      BundleInfo bundleInfo =
          new BundleInfo(
              simpleInfo.getSymbolicName(),
              simpleInfo.getVersion(),
              location,
              simpleInfo.getStartLevel(),
              simpleInfo.isMarkedAsStarted());
      bundleInfo.setBaseLocation(simpleInfo.getBaseLocation());
      result[i++] = bundleInfo;
    }
    return result;
  }
Exemplo n.º 11
0
  private URI doReplacement(
      String pattern,
      String repoLocation,
      String classifier,
      String id,
      String version,
      String format) {
    try {
      // currently our mapping rules assume the repo URL is not "/" terminated.
      // This may be the case for repoURLs in the root of a URL space e.g. root of a jar file or
      // file:/c:/
      if (repoLocation.endsWith("/")) // $NON-NLS-1$
      repoLocation = repoLocation.substring(0, repoLocation.length() - 1);

      StringBuffer output = new StringBuffer(pattern);
      int index = 0;
      while (index < output.length()) {
        int beginning = output.indexOf("${", index); // $NON-NLS-1$
        if (beginning == -1) return URIUtil.fromString(output.toString());

        int end = output.indexOf("}", beginning); // $NON-NLS-1$
        if (end == -1) return URIUtil.fromString(pattern);

        String varName = output.substring(beginning + 2, end);
        String varValue = null;
        if (varName.equalsIgnoreCase(CLASSIFIER)) {
          varValue = classifier;
        } else if (varName.equalsIgnoreCase(ID)) {
          varValue = id;
        } else if (varName.equalsIgnoreCase(VERSION)) {
          varValue = version;
        } else if (varName.equalsIgnoreCase(REPOURL)) {
          varValue = repoLocation;
        } else if (varName.equalsIgnoreCase(FORMAT)) {
          varValue = format;
        }
        if (varValue == null) varValue = ""; // $NON-NLS-1$

        output.replace(beginning, end + 1, varValue);
        index = beginning + varValue.length();
      }
      return URIUtil.fromString(output.toString());
    } catch (URISyntaxException e) {
      return null;
    }
  }
Exemplo n.º 12
0
 /**
  * Returns the {@link File} of a <code>file:</code> URL. This method tries to recover from bad
  * URLs, e.g. the unencoded form we used to use in persistent storage.
  *
  * @param url a <code>file:</code> URL
  * @return the file
  * @since 3.9
  */
 public static File toFile(URL url) {
   try {
     return URIUtil.toFile(url.toURI());
   } catch (URISyntaxException e) {
     JavaPlugin.log(e);
     return new File(url.getFile());
   }
 }
Exemplo n.º 13
0
 /** Find out the name of the directory that fits better to this UUID. */
 public URI folderFor(byte[] uuid) {
   byte hash = hashUUIDbytes(uuid);
   hash &= mask; // limit the range of the directory
   return URIUtil.append(
       store,
       Integer.toHexString(hash + (128 & mask))
           + '/'); // +(128 & mask) makes sure 00h is the lower value
 }
  private static void runCommandLine(String commandLine, String[] arguments)
      throws IOException, URISyntaxException, CoreException {
    URL classPathUrl = ArgumentsPrinter.class.getResource("/"); // $NON-NLS-1$
    classPathUrl = FileLocator.toFileURL(classPathUrl);
    File classPathFile = URIUtil.toFile(URIUtil.toURI(classPathUrl));

    String[] execArgs = new String[arguments.length + 4];
    execArgs[0] =
        new Path(System.getProperty("java.home"))
            .append("bin/java")
            .toOSString(); //$NON-NLS-1$ //$NON-NLS-2$
    execArgs[1] = "-cp"; // $NON-NLS-1$
    execArgs[2] = classPathFile.getAbsolutePath();
    execArgs[3] = ArgumentsPrinter.class.getName();
    System.arraycopy(arguments, 0, execArgs, 4, arguments.length);

    ArrayList<String> resultArgs = runCommandLine(execArgs);

    assertEquals(
        "unexpected exec result;", //$NON-NLS-1$
        Arrays.asList(arguments).toString(),
        resultArgs.toString());

    if (!Platform.getOS().equals(Constants.OS_WIN32)) {
      execArgs =
          new String[] {
            "sh",
            "-c",
            execArgs[0]
                + " "
                + execArgs[1]
                + " "
                + execArgs[2]
                + " "
                + execArgs[3]
                + " "
                + commandLine
          }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
      resultArgs = runCommandLine(execArgs);
      assertEquals(
          "unexpected sh exec result;", //$NON-NLS-1$
          Arrays.asList(arguments).toString(),
          resultArgs.toString());
    }
  }
 /**
  * Returns the file path where the given resolved bundle can be found. Used to group bundles by
  * file path in the tree.
  *
  * @param bundle bundle to lookup parent path for
  * @return path of parent directory, if unknown it will be a path object containing "Unknown"
  */
 private IPath getParentPath(IResolvedBundle bundle) {
   URI location = bundle.getBundleInfo().getLocation();
   if (location == null) {
     return new Path(Messages.TargetContentsGroup_8);
   }
   IPath path = new Path(URIUtil.toUnencodedString(location));
   path = path.removeLastSegments(1);
   return path;
 }
Exemplo n.º 16
0
  public static IFileArtifactRepository getAggregatedBundleRepository(
      IProvisioningAgent agent, IProfile profile, int repoFilter) {
    List<IFileArtifactRepository> bundleRepositories = new ArrayList<IFileArtifactRepository>();

    // we check for a shared bundle pool first as it should be preferred over the user bundle pool
    // in a shared install
    IArtifactRepositoryManager manager = getArtifactRepositoryManager(agent);
    if ((repoFilter & AGGREGATE_SHARED_CACHE) != 0) {
      String sharedCache = profile.getProperty(IProfile.PROP_SHARED_CACHE);
      if (sharedCache != null) {
        try {
          URI repoLocation = new File(sharedCache).toURI();
          IArtifactRepository repository = manager.loadRepository(repoLocation, null);
          if (repository != null
              && repository instanceof IFileArtifactRepository
              && !bundleRepositories.contains(repository))
            bundleRepositories.add((IFileArtifactRepository) repository);
        } catch (ProvisionException e) {
          // skip repository if it could not be read
        }
      }
    }

    if ((repoFilter & AGGREGATE_CACHE) != 0) {
      IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(agent, profile);
      if (bundlePool != null) bundleRepositories.add(bundlePool);
    }

    if ((repoFilter & AGGREGATE_CACHE_EXTENSIONS) != 0) {
      List<String> repos = getListProfileProperty(profile, CACHE_EXTENSIONS);
      for (String repo : repos) {
        try {
          URI repoLocation;
          try {
            repoLocation = new URI(repo);
          } catch (URISyntaxException e) {
            // in 1.0 we wrote unencoded URL strings, so try as an unencoded string
            repoLocation = URIUtil.fromString(repo);
          }
          IArtifactRepository repository = manager.loadRepository(repoLocation, null);
          if (repository != null
              && repository instanceof IFileArtifactRepository
              && !bundleRepositories.contains(repository))
            bundleRepositories.add((IFileArtifactRepository) repository);
        } catch (ProvisionException e) {
          // skip repositories that could not be read
        } catch (URISyntaxException e) {
          // unexpected, URLs should be pre-checked
          LogHelper.log(new Status(IStatus.ERROR, Activator.ID, e.getMessage(), e));
        }
      }
    }
    return new AggregatedBundleRepository(agent, bundleRepositories);
  }
Exemplo n.º 17
0
  protected void processParameter(String arg, String parameter, PublisherInfo pinfo)
      throws URISyntaxException {
    super.processParameter(arg, parameter, pinfo);

    this.append = true; // Always append, otherwise we will end up with nothing

    if (arg.equalsIgnoreCase("-categoryQualifier")) // $NON-NLS-1$
    categoryQualifier = parameter;

    if (arg.equalsIgnoreCase("-categoryDefinition")) // $NON-NLS-1$
    categoryDefinition = URIUtil.fromString(parameter);
  }
 /* (non-Javadoc)
  * @see org.eclipse.wst.jsdt.debug.core.jsdi.ScriptReference#sourceURI()
  */
 public synchronized URI sourceURI() {
   if (sourceuri == null) {
     try {
       sourceuri = URIUtil.fromString(url);
     } catch (IllegalArgumentException iae) {
       try {
         sourceuri = CrossFirePlugin.fileURI(new Path(url));
       } catch (URISyntaxException e) {
         CrossFirePlugin.log(e);
       }
     } catch (URISyntaxException urise) {
       CrossFirePlugin.log(urise);
     }
   }
   return sourceuri;
 }
Exemplo n.º 19
0
 @Override
 protected IStatus performJob() {
   IStatus result = doClone();
   if (result.isOK()) {
     return result;
   } else {
     try {
       if (project != null) GitCloneHandlerV1.removeProject(user, project);
       else FileUtils.delete(URIUtil.toFile(clone.getContentLocation()), FileUtils.RECURSIVE);
     } catch (IOException e) {
       String msg = "An error occured when cleaning up after a clone failure";
       result =
           new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
     }
     return result;
   }
 }
Exemplo n.º 20
0
 /**
  * The limit is the maximum number of directories managed by this store. This number must be power
  * of 2 and do not exceed 256. The location should be an existing valid directory.
  */
 public BlobStore(URI store, int limit) {
   Assert.isNotNull(store);
   this.store = store;
   fileBased = "file".equalsIgnoreCase(store.getScheme()); // $NON-NLS-1$
   if (fileBased) Assert.isTrue(!URIUtil.toFile(store).isFile());
   Assert.isTrue(
       limit == 256
           || limit == 128
           || limit == 64
           || limit == 32
           || limit == 16
           || limit == 8
           || limit == 4
           || limit == 2
           || limit == 1);
   mask = (byte) (limit - 1);
 }
  private boolean hasBaseChanged(URI installArea, File outputFolder) {
    String rememberedTimestamp;
    try {
      rememberedTimestamp =
          (String)
              loadProperties(
                      new File(
                          outputFolder, SimpleConfiguratorImpl.BASE_TIMESTAMP_FILE_BUNDLESINFO))
                  .get(SimpleConfiguratorImpl.KEY_BUNDLESINFO_TIMESTAMP);
    } catch (IOException e) {
      return false;
    }
    if (rememberedTimestamp == null) return false;

    File sharedBundlesInfo = new File(URIUtil.append(installArea, SHARED_BUNDLES_INFO));
    if (!sharedBundlesInfo.exists()) return true;
    return !String.valueOf(sharedBundlesInfo.lastModified()).equals(rememberedTimestamp);
  }
Exemplo n.º 22
0
  public void addProfile(String id, Map properties) {
    IProfile profile = registry.getProfile(id);
    if (profile != null || properties == null) return;
    String location = new File(URIUtil.append(dataLocation, id)).toString();
    String environment = "osgi.os=" + properties.get("osgi.os");
    environment += ",osgi.ws=" + properties.get("osgi.ws");
    environment += ",osgi.arch=" + properties.get("osgi.arch");
    Map props = new HashMap();
    props.put(IProfile.PROP_INSTALL_FOLDER, location);
    props.put(IProfile.PROP_CACHE, location);
    props.put(IProfile.PROP_ENVIRONMENTS, environment);

    try {
      profile = registry.addProfile(id, props);
    } catch (ProvisionException e) {
      LogUtility.logError("Error adding profile: " + id, e);
    }
  }
Exemplo n.º 23
0
  @Override
  protected ServerStatus _doIt() {
    try {
      /* get available orgs */
      URI targetURI = URIUtil.toURI(target.getUrl());
      URI orgsURI = targetURI.resolve("/v2/organizations");

      GetMethod getDomainsMethod = new GetMethod(orgsURI.toString());
      HttpUtil.configureHttpMethod(getDomainsMethod, target);
      getDomainsMethod.setQueryString("inline-relations-depth=1"); // $NON-NLS-1$

      ServerStatus status = HttpUtil.executeMethod(getDomainsMethod);
      if (!status.isOK()) return status;

      /* extract available orgs */
      JSONObject orgs = status.getJsonData();

      if (orgs.getInt(CFProtocolConstants.V2_KEY_TOTAL_RESULTS) < 1) {
        return new ServerStatus(IStatus.OK, HttpServletResponse.SC_OK, null, null);
      }

      /* look if the domain is available */
      JSONObject result = new JSONObject();
      int resources = orgs.getJSONArray(CFProtocolConstants.V2_KEY_RESOURCES).length();
      for (int k = 0; k < resources; ++k) {
        JSONObject orgJSON =
            orgs.getJSONArray(CFProtocolConstants.V2_KEY_RESOURCES).getJSONObject(k);
        List<Space> spaces = new ArrayList<Space>();
        status = getSpaces(spaces, orgJSON);
        if (!status.isOK()) return status;
        OrgWithSpaces orgWithSpaces = new OrgWithSpaces();
        orgWithSpaces.setCFJSON(orgJSON);
        orgWithSpaces.setSpaces(spaces);
        result.append("Orgs", orgWithSpaces.toJSON());
      }

      return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result);
    } catch (Exception e) {
      String msg =
          NLS.bind("An error occured when performing operation {0}", commandName); // $NON-NLS-1$
      logger.error(msg, e);
      return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
    }
  }
Exemplo n.º 24
0
  private static String getLocation(
      final IConfigurationElement element, final Map<String, String> filter) throws Exception {
    final Bundle bundle = Platform.getBundle(element.getContributor().getName());
    final String path = element.getAttribute(LOCATION_ATTRIBUTE_NAME);
    if (bundle != null && path != null && path.length() > 0) {
      final URL[] bundleURLs = FileLocator.findEntries(bundle, new Path(path), filter);
      for (int i = 0; i < bundleURLs.length; i++) {
        final URI fileURI = URIUtil.toURI(FileLocator.toFileURL(bundleURLs[i]));
        if (fileURI.getScheme().equals("file")) { // $NON-NLS-1$
          final File file = new File(fileURI);
          if (file.exists() && file.isDirectory() && file.list().length > 0) {
            return file.getAbsolutePath();
          }
        }
      }
    }

    return null;
  }
Exemplo n.º 25
0
  private void runMigrationOnSinglePath(String path)
      throws IOException, MalformedURLException, URISyntaxException, Throwable {
    URL sampleFolderUnEscapedURL = FileLocator.toFileURL(new URL(path)); // $NON-NLS-1$
    // FileLocator.toFileURL will not escape special chars when creating the URL see bug
    // https://bugs.eclipse.org/bugs/show_bug.cgi?id=145096
    // so we use the URI constructor to create an escaped URI
    URI escapedUri =
        new URI(
            sampleFolderUnEscapedURL.getProtocol(),
            sampleFolderUnEscapedURL.getPath(),
            null); // calling
    // the
    // URI(String)
    // constructor does not escape
    // the URL

    File sampleFolder = URIUtil.toFile(escapedUri);
    TestMigrationOnAllItemsInFolder(sampleFolder, false);
  }
Exemplo n.º 26
0
  public URI map(
      URI repositoryLocation, String classifier, String id, String version, String format) {
    String locationString = URIUtil.toUnencodedString(repositoryLocation);
    Dictionary<String, Object> values = new Hashtable<String, Object>(5);
    if (repositoryLocation != null) values.put(REPOURL, locationString);

    if (classifier != null) values.put(CLASSIFIER, classifier);

    if (id != null) values.put(ID, id);

    if (version != null) values.put(VERSION, version);

    if (format != null) values.put(FORMAT, format);

    for (int i = 0; i < filters.length; i++) {
      if (filters[i].match(values))
        return doReplacement(outputStrings[i], locationString, classifier, id, version, format);
    }
    return null;
  }
Exemplo n.º 27
0
 private void encodeChildren(IFileStore dir, URI location, JSONObject result, int depth)
     throws CoreException {
   if (depth <= 0) return;
   JSONArray children = new JSONArray();
   IFileStore[] childStores = dir.childStores(EFS.NONE, null);
   for (IFileStore childStore : childStores) {
     IFileInfo childInfo = childStore.fetchInfo();
     String name = childInfo.getName();
     if (childInfo.isDirectory()) name += "/"; // $NON-NLS-1$
     URI childLocation = URIUtil.append(location, name);
     JSONObject childResult = ServletFileStoreHandler.toJSON(childStore, childInfo, childLocation);
     if (childInfo.isDirectory())
       encodeChildren(childStore, childLocation, childResult, depth - 1);
     children.put(childResult);
   }
   try {
     result.put(ProtocolConstants.KEY_CHILDREN, children);
   } catch (JSONException e) {
     // cannot happen
     throw new RuntimeException(e);
   }
 }
  @Override
  protected ServerStatus _doIt() {
    try {

      /* unmap route from application */
      URI targetURI = URIUtil.toURI(target.getUrl());
      DeleteMethod unmapRouteMethod =
          new DeleteMethod(
              targetURI
                  .resolve("/v2/apps/" + app.getGuid() + "/routes/" + route.getGuid())
                  .toString()); //$NON-NLS-1$//$NON-NLS-2$
      ServerStatus confStatus = HttpUtil.configureHttpMethod(unmapRouteMethod, target.getCloud());
      if (!confStatus.isOK()) return confStatus;

      return HttpUtil.executeMethod(unmapRouteMethod);

    } catch (Exception e) {
      String msg =
          NLS.bind("An error occured when performing operation {0}", commandName); // $NON-NLS-1$
      logger.error(msg, e);
      return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
    }
  }
  private void rememberSharedBundlesInfoTimestamp(URI installArea, File outputFolder) {
    if (installArea == null) return;

    File sharedBundlesInfo = new File(URIUtil.append(installArea, SHARED_BUNDLES_INFO));
    if (!sharedBundlesInfo.exists()) return;

    Properties timestampToPersist = new Properties();
    timestampToPersist.put(
        SimpleConfiguratorImpl.KEY_BUNDLESINFO_TIMESTAMP,
        Long.toString(sharedBundlesInfo.lastModified()));
    OutputStream os = null;
    try {
      try {
        File outputFile =
            new File(outputFolder, SimpleConfiguratorImpl.BASE_TIMESTAMP_FILE_BUNDLESINFO);
        os = new BufferedOutputStream(new FileOutputStream(outputFile));
        timestampToPersist.store(os, "Written by " + this.getClass()); // $NON-NLS-1$
      } finally {
        if (os != null) os.close();
      }
    } catch (IOException e) {
      return;
    }
  }
Exemplo n.º 30
0
 /**
  * Parse a URL from a String. This method first tries to treat <code>url</code> as a valid,
  * encoded URL. If that didn't work, it tries to recover from bad URLs, e.g. the unencoded form we
  * used to use in persistent storage.
  *
  * @param url a URL
  * @return the parsed URL or <code>null</code> if the URL couldn't be parsed
  * @since 3.9
  */
 public static URL parseURL(String url) {
   try {
     try {
       return new URI(url).toURL();
     } catch (URISyntaxException e) {
       try {
         // don't log, since we used to store bad (unencoded) URLs
         if (url.startsWith("file:/")) { // $NON-NLS-1$
           // workaround for a bug in the 3-arg URI constructor for paths that contain '[' or ']':
           return new URI("file", null, url.substring(5), null).toURL(); // $NON-NLS-1$
         } else {
           return URIUtil.fromString(url).toURL();
         }
       } catch (URISyntaxException e1) {
         // last try, not expected to happen
         JavaPlugin.log(e);
         return new URL(url);
       }
     }
   } catch (MalformedURLException e) {
     JavaPlugin.log(e);
     return null;
   }
 }