/** @return a list of uris of all xmi files registered */
  public static Map<URI, Map<String, String>> getExtensionURIS() {
    final Map<URI, Map<String, String>> ret = new LinkedHashMap<URI, Map<String, String>>();
    final IConfigurationElement[] files =
        Platform.getExtensionRegistry().getConfigurationElementsFor(FILE_EXTENSION);
    final URIConverter converter = new ResourceSetImpl().getURIConverter();
    for (final IConfigurationElement file : files) {
      final String filePath = file.getAttribute(FILEPATH_ATTRIBUTE);

      final IConfigurationElement[] children = file.getChildren(FILTER_ELEMENT);
      final Map<String, String> keyValuePairs = new LinkedHashMap<String, String>();
      for (final IConfigurationElement child : children) {
        final String key = child.getAttribute(FILTER_KEY_ATTRIBUTE);
        final String value = child.getAttribute(FILTER_VALUE_ATTRIBUTE);
        keyValuePairs.put(key, value);
      }

      URI uri;
      final String bundleName = file.getContributor().getName();
      final String path = bundleName + '/' + filePath;
      uri = URI.createPlatformPluginURI(path, false);
      if (converter.exists(uri, null)) {
        ret.put(uri, keyValuePairs);
      } else {
        uri = URI.createPlatformResourceURI(filePath, false);
        if (converter.exists(uri, null)) {
          ret.put(uri, keyValuePairs);
        }
      }
    }
    return ret;
  }
Esempio n. 2
0
  @SuppressWarnings("unchecked")
  private static URI createNewResource(
      Resource projectResource, String projectPath, ProjectElement projectElement) {
    int i = 0;
    List<Resource> list = projectResource.getResourceSet().getResources();
    URIConverter uriConverter = projectResource.getResourceSet().getURIConverter();
    URI uri = null;
    boolean found = false;
    do {
      found = false;
      i++;
      // TODO Add file extension name to ProjectElement
      uri = generateResourceName(projectPath, projectElement, i);

      URI normalizedURI = uriConverter.normalize(uri);
      for (Resource resource2 : list) {
        if (uriConverter.normalize(resource2.getURI()).equals(normalizedURI)) {
          found = true;
          break;
        }
      }
      if (!found) {
        File file = new File(uri.toFileString());
        if (file.exists()) found = true;
      }
    } while (found);
    uri.deresolve(projectResource.getURI(), true, true, true);
    return uri;
  }
 private boolean pickedAnotherAird(Session existingSession) {
   if (existingSession.getSessionResource() != null) {
     URI sessURI = existingSession.getSessionResource().getURI();
     URIConverter conv =
         existingSession.getTransactionalEditingDomain().getResourceSet().getURIConverter();
     if (sessURI != null && conv != null) {
       return !conv.normalize(airdFilePage.getURI()).equals(conv.normalize(sessURI));
     }
   }
   return true;
 }
 private void copyProfileApplicationViaFileStream(URI originalPaURI, URI newPaURI)
     throws IOException {
   URIConverter uriConverter = new ExtensibleURIConverterImpl();
   InputStream inputStream = uriConverter.createInputStream(originalPaURI);
   OutputStream outputStream = uriConverter.createOutputStream(newPaURI);
   int b;
   while ((b = inputStream.read()) != -1) {
     outputStream.write(b);
   }
   inputStream.close();
   outputStream.close();
 }
Esempio n. 5
0
  /**
   * This implementation delegates to the {@link #getURIConverter(Map) URI converter}'s {@link
   * URIConverter#getContentHandlers() content handlers}.
   */
  @SuppressWarnings("null")
  public Map<String, ?> contentDescription(URI uri, Map<?, ?> options) throws IOException {
    URIConverter uriConverter = (URIConverter) options.get(URIConverter.OPTION_URI_CONVERTER);
    InputStream inputStream = null;
    Map<String, ?> result = null;
    Map<Object, Object> context = new HashMap<Object, Object>();
    try {
      for (ContentHandler contentHandler : uriConverter.getContentHandlers()) {
        if (contentHandler.canHandle(uri)) {
          if (inputStream == null) {
            try {
              inputStream = createInputStream(uri, options);
            } catch (IOException exception) {
              inputStream = new ByteArrayInputStream(new byte[0]);
            }
            if (!inputStream.markSupported()) {
              inputStream = new BufferedInputStream(inputStream);
            }
            inputStream.mark(Integer.MAX_VALUE);
          } else {
            inputStream.reset();
          }
          Map<String, ?> contentDescription =
              contentHandler.contentDescription(uri, inputStream, options, context);
          switch ((ContentHandler.Validity)
              contentDescription.get(ContentHandler.VALIDITY_PROPERTY)) {
            case VALID:
              {
                return contentDescription;
              }
            case INDETERMINATE:
              {
                if (result == null) {
                  result = contentDescription;
                }
                break;
              }
            case INVALID:
              {
                break;
              }
          }
        }
      }
    } finally {
      if (inputStream != null) {
        inputStream.close();
      }
    }

    return result == null ? ContentHandler.INVALID_CONTENT_DESCRIPTION : result;
  }
 /**
  * {@inheritDoc}
  *
  * @see org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#getURIMap()
  */
 @Override
 public Map<URI, URI> getURIMap() {
   if (parent != null) {
     return parent.getURIMap();
   }
   return super.getURIMap();
 }
 /**
  * {@inheritDoc}
  *
  * @see
  *     org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#createInputStream(org.eclipse.emf.common.util.URI)
  */
 @Override
 public InputStream createInputStream(URI uri) throws IOException {
   if (parent != null) {
     return parent.createInputStream(uri);
   }
   return super.createInputStream(uri);
 }
 /**
  * {@inheritDoc}
  *
  * @see
  *     org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#createOutputStream(org.eclipse.emf.common.util.URI,
  *     java.util.Map)
  */
 @Override
 public OutputStream createOutputStream(URI uri, Map<?, ?> options) throws IOException {
   if (parent != null) {
     return parent.createOutputStream(uri, options);
   }
   return super.createOutputStream(uri, options);
 }
  public static String getETag(URIConverter uriConverter, URI file) {
    if (uriConverter.exists(file, null)) {
      URI eTagFile = file.appendFileExtension("etag");
      if (uriConverter.exists(eTagFile, null)) {
        try {
          return new String(BaseUtil.readFile(uriConverter, null, eTagFile), "UTF-8");
        } catch (IORuntimeException ex) {
          // If we can't read the ETag, we'll just return null.
        } catch (UnsupportedEncodingException ex) {
          // All systems support UTF-8.
        }
      }
    }

    return null;
  }
      @Override
      protected IStatus perform(IProgressMonitor monitor) {
        URI key = getKey();
        ETagMirror workPool = getWorkPool();

        try {
          workPool.getMonitor().subTask("Mirroring " + key);
        } catch (Exception ex) {
          SetupCorePlugin.INSTANCE.log(ex, IStatus.WARNING);
        }

        try {
          if (TEST_SLOW_NETWORK) {
            try {
              Thread.sleep(5000);
            } catch (InterruptedException ex) {
              ex.printStackTrace();
            }
          }

          URI_CONVERTER.createInputStream(key, workPool.options).close();
        } catch (IOException ex) {
          SetupCorePlugin.INSTANCE.log(ex);
        } finally {
          try {
            workPool.getMonitor().worked(1);
          } catch (Exception ex) {
            SetupCorePlugin.INSTANCE.log(ex, IStatus.WARNING);
          }
        }

        return Status.OK_STATUS;
      }
 /**
  * {@inheritDoc}
  *
  * @see org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#getURIHandlers()
  */
 @Override
 public EList<URIHandler> getURIHandlers() {
   if (parent != null) {
     return parent.getURIHandlers();
   }
   return super.getURIHandlers();
 }
 /**
  * {@inheritDoc}
  *
  * @see
  *     org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#getAttributes(org.eclipse.emf.common.util.URI,
  *     java.util.Map)
  */
 @Override
 public Map<String, ?> getAttributes(URI uri, Map<?, ?> options) {
   if (parent != null) {
     return parent.getAttributes(uri, options);
   }
   return super.getAttributes(uri, options);
 }
 /**
  * {@inheritDoc}
  *
  * @see
  *     org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#getURIHandler(org.eclipse.emf.common.util.URI)
  */
 @Override
 public URIHandler getURIHandler(URI uri) {
   if (parent != null) {
     return parent.getURIHandler(uri);
   }
   return super.getURIHandler(uri);
 }
 /**
  * {@inheritDoc}
  *
  * @see
  *     org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#exists(org.eclipse.emf.common.util.URI,
  *     java.util.Map)
  */
 @Override
 public boolean exists(URI uri, Map<?, ?> options) {
   if (parent != null) {
     return parent.exists(uri, options);
   }
   return super.exists(uri, options);
 }
 /**
  * {@inheritDoc}
  *
  * @see
  *     org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#contentDescription(org.eclipse.emf.common.util.URI,
  *     java.util.Map)
  */
 @Override
 public Map<String, ?> contentDescription(URI uri, Map<?, ?> options) throws IOException {
   if (parent != null) {
     return parent.contentDescription(uri, options);
   }
   return super.contentDescription(uri, options);
 }
 /**
  * {@inheritDoc}
  *
  * @see
  *     org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#delete(org.eclipse.emf.common.util.URI,
  *     java.util.Map)
  */
 @Override
 public void delete(URI uri, Map<?, ?> options) throws IOException {
   if (parent != null) {
     parent.delete(uri, options);
   }
   super.delete(uri, options);
 }
 /**
  * {@inheritDoc}
  *
  * @see
  *     org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#setAttributes(org.eclipse.emf.common.util.URI,
  *     java.util.Map, java.util.Map)
  */
 @Override
 public void setAttributes(URI uri, Map<String, ?> attributes, Map<?, ?> options)
     throws IOException {
   if (parent != null) {
     parent.setAttributes(uri, attributes, options);
   }
   super.setAttributes(uri, attributes, options);
 }
Esempio n. 18
0
  public synchronized URI update(ModelLoader loader, List<ContextEnquiryLink> toUpdate)
      throws Exception {
    URI emfURI = URI.createURI(FILE_URI);
    Resource r = loader.getResource(emfURI);
    URIConverter uriConverter = r.getResourceSet().getURIConverter();
    List<ContextEnquiryLink> list = null;

    try {
      InputStream is = uriConverter.createInputStream(emfURI);
      list = load(is);
    } catch (Exception e) {
      /*
       * Certainly the file doesn't exist (first time)
       */
      list = new ArrayList<ContextEnquiryLink>();
    }

    String sLastContextEnquiry = null;

    for (ContextEnquiryLink link : toUpdate) {
      String sCurrentContextEnquiry = link.getFullyQualifiedLinkName();
      // eg : T24.ctxCurrency.CtxEnq_CurrencyRates
      int pos = sCurrentContextEnquiry.lastIndexOf(".");
      sCurrentContextEnquiry = sCurrentContextEnquiry.substring(0, pos + 1); // keep the .
      // eg : T24.ctxCurrency.

      if (sLastContextEnquiry != null && sLastContextEnquiry.equals(sCurrentContextEnquiry)) {
        /*
         * Already removed, continue
         */
        continue;
      }

      sLastContextEnquiry = sCurrentContextEnquiry;

      /*
       * remove them all !
       */
      Iterator<ContextEnquiryLink> iter = list.iterator();
      while (iter.hasNext()) {
        if (iter.next().getFullyQualifiedLinkName().startsWith(sLastContextEnquiry)) {
          iter.remove();
        }
      }
    }

    /*
     * now simply add all the link to update in the current list
     */
    list.addAll(toUpdate);

    /*
     * Now we have to check for duplicate based on resourceName and description.
     * This is because of IRIS crashing if there are duplicates on these 2 fields ...
     */
    Set<String> tmp = new HashSet<String>();
    for (ContextEnquiryLink link : list) {
      String sKey = link.getResourceName() + "." + link.getDescription();
      int idx = 1;

      while (tmp.contains(sKey)) {
        String sDesc = link.getDescription();
        int pos = sDesc.lastIndexOf("#");

        if (pos > 0) {
          idx = Integer.parseInt(sDesc.substring(pos + 1).trim());
          sDesc = sDesc.substring(pos - 1);
        }

        idx++;
        link.setDescription(sDesc + " #" + idx);
        sKey = link.getResourceName() + "." + link.getDescription();
      }

      tmp.add(sKey);
    }

    OutputStream os = uriConverter.createOutputStream(emfURI);
    save(os, list);

    /*
     * return the URI so we can generate java or more ....
     */
    return emfURI;
  }
  @Override
  public InputStream createInputStream(URI uri, Map<?, ?> options) throws IOException {
    if (TEST_IO_EXCEPTION) {
      File folder = new File(CACHE_FOLDER.toFileString());
      if (folder.isDirectory()) {
        System.out.println("Deleting cache folder: " + folder);
        IOUtil.deleteBestEffort(folder);
      }

      throw new IOException("Simulated network problem");
    }

    CacheHandling cacheHandling = getCacheHandling(options);
    URIConverter uriConverter = getURIConverter(options);
    URI cacheURI = getCacheFile(uri);
    String eTag =
        cacheHandling == CacheHandling.CACHE_IGNORE ? null : getETag(uriConverter, cacheURI);
    String expectedETag = cacheHandling == CacheHandling.CACHE_IGNORE ? null : getExpectedETag(uri);
    if (expectedETag != null
        || cacheHandling == CacheHandling.CACHE_ONLY
        || cacheHandling == CacheHandling.CACHE_WITHOUT_ETAG_CHECKING) {
      if (cacheHandling == CacheHandling.CACHE_ONLY
              || cacheHandling == CacheHandling.CACHE_WITHOUT_ETAG_CHECKING
          ? eTag != null
          : expectedETag.equals(eTag)) {
        try {
          setExpectedETag(uri, expectedETag);
          return uriConverter.createInputStream(cacheURI, options);
        } catch (IOException ex) {
          // Perhaps another JVM is busy writing this file.
          // Proceed as if it doesn't exit.
        }
      }
    }

    String username;
    String password;

    String uriString = uri.toString();
    Proxy proxy = ProxySetupHelper.getProxy(uriString);
    if (proxy != null) {
      username = proxy.getUsername();
      password = proxy.getPassword();
    } else {
      username = null;
      password = null;
    }

    IContainer container = createContainer();

    AuthorizationHandler authorizatonHandler = getAuthorizatonHandler(options);
    Authorization authorization = getAuthorizaton(options);
    int triedReauthorization = 0;
    for (int i = 0; ; ++i) {
      IRetrieveFileTransferContainerAdapter fileTransfer =
          container.getAdapter(IRetrieveFileTransferContainerAdapter.class);

      if (proxy != null) {
        fileTransfer.setProxy(proxy);

        if (username != null) {
          fileTransfer.setConnectContextForAuthentication(
              ConnectContextFactory.createUsernamePasswordConnectContext(username, password));
        } else if (password != null) {
          fileTransfer.setConnectContextForAuthentication(
              ConnectContextFactory.createPasswordConnectContext(password));
        }
      }

      FileTransferListener transferListener = new FileTransferListener(eTag);

      try {
        FileTransferID fileTransferID =
            new FileTransferID(new FileTransferNamespace(), IOUtil.newURI(uriString));
        Map<Object, Object> requestOptions = new HashMap<Object, Object>();
        requestOptions.put(IRetrieveFileTransferOptions.CONNECT_TIMEOUT, 10000);
        requestOptions.put(IRetrieveFileTransferOptions.READ_TIMEOUT, 10000);
        if (authorization != null && authorization.isAuthorized()) {
          requestOptions.put(
              IRetrieveFileTransferOptions.REQUEST_HEADERS,
              Collections.singletonMap("Authorization", authorization.getAuthorization()));
        }

        fileTransfer.sendRetrieveRequest(fileTransferID, transferListener, requestOptions);
      } catch (IncomingFileTransferException ex) {
        throw new IOExceptionWithCause(ex);
      }
      try {
        transferListener.receiveLatch.await();
      } catch (InterruptedException ex) {
        throw new IOExceptionWithCause(ex);
      }

      if (transferListener.exception != null) {
        if (!(transferListener.exception instanceof UserCancelledException)) {
          if (transferListener.exception.getCause() instanceof SocketTimeoutException && i <= 2) {
            continue;
          }

          if (authorizatonHandler != null
              && transferListener.exception instanceof IncomingFileTransferException) {
            // We assume contents can be accessed via the github API
            // https://developer.github.com/v3/repos/contents/#get-contents
            // That API, for security reasons, does not return HTTP_UNAUTHORIZED, so we need this
            // special case for that host.
            IncomingFileTransferException incomingFileTransferException =
                (IncomingFileTransferException) transferListener.exception;
            int errorCode = incomingFileTransferException.getErrorCode();
            if (errorCode == HttpURLConnection.HTTP_UNAUTHORIZED
                || API_GITHUB_HOST.equals(getHost(uri))
                    && errorCode == HttpURLConnection.HTTP_NOT_FOUND) {
              if (authorization == null) {
                authorization = authorizatonHandler.authorize(uri);
                if (authorization.isAuthorized()) {
                  --i;
                  continue;
                }
              }

              if (!authorization.isUnauthorizeable() && triedReauthorization++ < 3) {
                authorization = authorizatonHandler.reauthorize(uri, authorization);
                if (authorization.isAuthorized()) {
                  --i;
                  continue;
                }
              }
            }
          }
        }

        if (!CacheHandling.CACHE_IGNORE.equals(cacheHandling)
            && uriConverter.exists(cacheURI, options)
            && (!(transferListener.exception instanceof IncomingFileTransferException)
                || ((IncomingFileTransferException) transferListener.exception).getErrorCode()
                    != HttpURLConnection.HTTP_NOT_FOUND)) {
          setExpectedETag(uri, transferListener.eTag == null ? eTag : transferListener.eTag);
          return uriConverter.createInputStream(cacheURI, options);
        }

        throw new IOExceptionWithCause(transferListener.exception);
      }

      byte[] bytes = transferListener.out.toByteArray();

      // In the case of the Github API, the bytes will be JSON that contains a "content" pair
      // containing the Base64 encoding of the actual contents.
      if (API_GITHUB_HOST.equals(getHost(uri))) {
        // Find the start tag in the JSON value.
        String value = new String(bytes, "UTF-8");
        int start = value.indexOf(CONTENT_TAG);
        if (start != -1) {
          // Find the ending quote of the encoded contents.
          start += CONTENT_TAG.length();
          int end = value.indexOf('"', start);
          if (end != -1) {
            // The content is delimited by \n so split on that during the conversion.
            String content = value.substring(start, end);
            String[] split = content.split("\\\\n");

            // Write the converted bytes to a new stream and process those bytes instead.
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            for (String line : split) {
              byte[] binary = XMLTypeFactory.eINSTANCE.createBase64Binary(line);
              out.write(binary);
            }

            out.close();
            bytes = out.toByteArray();
          }
        }
      }

      try {
        BaseUtil.writeFile(uriConverter, options, cacheURI, bytes);
      } catch (IORuntimeException ex) {
        // Ignore attempts to write out to the cache file.
        // This may collide with another JVM doing exactly the same thing.
        transferListener.eTag = null;
      } finally {
        setETag(uriConverter, cacheURI, transferListener.eTag);
      }

      setExpectedETag(uri, transferListener.eTag);
      Map<Object, Object> response = getResponse(options);
      if (response != null) {
        response.put(URIConverter.RESPONSE_TIME_STAMP_PROPERTY, transferListener.lastModified);
      }

      ETagMirror etagMirror = (ETagMirror) options.get(ETagMirror.OPTION_ETAG_MIRROR);
      if (etagMirror != null) {
        etagMirror.cacheUpdated(uri);
      }

      return new ByteArrayInputStream(bytes);
    }
  }
 /**
  * Normalizes the given URI using the parent environment.
  *
  * @param uri The uri we are to normalize.
  * @return The normalized form of <code>uri</code>.
  */
 private URI normalizeWithParent(URI uri) {
   if (parent != null) {
     return parent.normalize(uri);
   }
   return uri;
 }