Beispiel #1
0
  public static boolean addDefaultHandlersIfNotAvailable(Registry configSystemRegistry)
      throws RegistryException, FileNotFoundException, XMLStreamException {

    if (!configSystemRegistry.resourceExists(RegistryConstants.HANDLER_CONFIGURATION_PATH)) {
      Collection handlerConfigurationCollection = new CollectionImpl();
      String description = "Handler configurations are stored here.";
      handlerConfigurationCollection.setDescription(description);
      configSystemRegistry.put(
          RegistryConstants.HANDLER_CONFIGURATION_PATH, handlerConfigurationCollection);
      // We don't have any default handler configuration as in lifecycles.
    } else {
      // configue all handlers
      Resource handlerRoot = configSystemRegistry.get(getContextRoot());
      if (!(handlerRoot instanceof Collection)) {
        String msg =
            "Failed to continue as the handler configuration root: "
                + getContextRoot()
                + " is not a collection.";
        log.error(msg);
        throw new RegistryException(msg);
      }
      Collection handlerRootCol = (Collection) handlerRoot;
      String[] handlerConfigPaths = handlerRootCol.getChildren();
      if (handlerConfigPaths != null) {
        for (String handlerConfigPath : handlerConfigPaths) {
          generateHandler(configSystemRegistry, handlerConfigPath);
        }
      }
    }

    return true;
  }
Beispiel #2
0
  public static boolean addHandler(Registry configSystemRegistry, String payload)
      throws RegistryException, XMLStreamException {
    String name;
    OMElement element = AXIOMUtil.stringToOM(payload);
    if (element != null) {
      name = element.getAttributeValue(new QName("class"));
    } else return false;

    if (isHandlerNameInUse(name))
      throw new RegistryException("The added handler name is already in use!");

    String path = getContextRoot() + name;
    Resource resource;
    if (!handlerExists(configSystemRegistry, name)) {
      resource = new ResourceImpl();
    } else {
      throw new RegistryException("The added handler name is already in use!");
    }
    resource.setContent(payload);
    try {
      configSystemRegistry.beginTransaction();
      configSystemRegistry.put(path, resource);
      generateHandler(configSystemRegistry, path);
      configSystemRegistry.commitTransaction();
    } catch (Exception e) {
      configSystemRegistry.rollbackTransaction();
      throw new RegistryException("Unable to generate handler", e);
    }
    return true;
  }
Beispiel #3
0
  public static String[] getHandlerList(Registry configSystemRegistry) throws RegistryException {
    Collection collection;
    try {
      collection = (Collection) configSystemRegistry.get(getContextRoot());
    } catch (Exception e) {
      return null;
    }

    if (collection == null) {
      CollectionImpl handlerCollection = new CollectionImpl();
      configSystemRegistry.put(getContextRoot(), handlerCollection);
      return null;
    } else {
      if (collection.getChildCount() == 0) {
        return null;
      }

      String[] childrenList = collection.getChildren();
      String[] handlerNameList = new String[collection.getChildCount()];
      for (int i = 0; i < childrenList.length; i++) {
        String path = childrenList[i];
        handlerNameList[i] = path.substring(path.lastIndexOf(RegistryConstants.PATH_SEPARATOR) + 1);
      }
      return handlerNameList;
    }
  }
Beispiel #4
0
  public static void loadPlayer(Registry registry) {
    Player p = (Player) getPlayers().get(player);
    if (p != null) {
      p.setTransient(registry);
    }

    GameController gc = registry.getGameController();
    registry.getPlayerManager().clearPlayers();
    registry.getPlayerManager().registerPlayer(p);
    BlockManager bm = (BlockManager) blockManagers.get(player);
    bm.name = "Saved";
    bm = (BlockManager) bm.clone();
    bm.name = "Clone";
    bm.setTransient(registry);
    gc.setBlockManager(bm);
    PlaceableManager pm = (PlaceableManager) placeableManagers.get(player).clone();
    gc.setPlaceableManager(pm);
    MonsterManager mm = (MonsterManager) monsterManagers.get(player).clone();
    mm.setTransient(registry);
    gc.setMonsterManager(mm);

    if (p != null) {
      p.resetPlayer();
    }

    // unloadUnused();
  }
Beispiel #5
0
 /**
  * ***************************************************************
  *
  * @param ip
  * @param port
  * @return
  */
 public ChordMessageInterface rmiChord(String ip, int port) {
   ChordMessageInterface chord = null;
   try {
     Registry registry = LocateRegistry.getRegistry(ip, port);
     chord = (ChordMessageInterface) (registry.lookup("Chord"));
     return chord;
   } catch (RemoteException e) {
     e.printStackTrace();
   } catch (NotBoundException e) {
     e.printStackTrace();
   }
   return null;
 }
Beispiel #6
0
  public static boolean removeHandler(Registry configSystemRegistry, String handlerName)
      throws RegistryException, XMLStreamException {
    String handlerConfiguration = getHandlerConfiguration(configSystemRegistry, handlerName);
    if (handlerConfiguration != null) {
      OMElement element = AXIOMUtil.stringToOM(handlerConfiguration);
      try {
        try {
          configSystemRegistry.beginTransaction();
          RegistryConfigurationProcessor.HandlerDefinitionObject handlerDefinitionObject =
              new RegistryConfigurationProcessor.HandlerDefinitionObject(null, element).invoke();
          String[] methods = handlerDefinitionObject.getMethods();
          Filter filter = handlerDefinitionObject.getFilter();
          Handler handler = handlerDefinitionObject.getHandler();
          if (handlerDefinitionObject.getTenantId() != -1) {
            CurrentSession.setCallerTenantId(handlerDefinitionObject.getTenantId());
            // We need to swap the tenant id for this call, if the handler has overriden the
            // default value.
            configSystemRegistry
                .getRegistryContext()
                .getHandlerManager()
                .removeHandler(
                    methods, filter, handler, HandlerLifecycleManager.USER_DEFINED_HANDLER_PHASE);
            CurrentSession.removeCallerTenantId();
          } else {
            configSystemRegistry
                .getRegistryContext()
                .getHandlerManager()
                .removeHandler(
                    methods, filter, handler, HandlerLifecycleManager.USER_DEFINED_HANDLER_PHASE);
          }

          configSystemRegistry.commitTransaction();
          return true;
        } catch (Exception e) {
          configSystemRegistry.rollbackTransaction();
          throw e;
        }
      } catch (Exception e) {
        if (e instanceof RegistryException) {
          throw (RegistryException) e;
        } else if (e instanceof XMLStreamException) {
          throw (XMLStreamException) e;
        }
        throw new RegistryException("Unable to build handler configuration", e);
      }
    }
    return false;
  }
 private OMElement resolveImports(
     OMElement grammarsElement, String wadlBaseUri, String wadlVersion) throws RegistryException {
   String wadlNamespace = grammarsElement.getNamespace().getNamespaceURI();
   Iterator<OMElement> grammarElements =
       grammarsElement.getChildrenWithName(new QName(wadlNamespace, "include"));
   while (grammarElements.hasNext()) {
     OMElement childElement = grammarElements.next();
     OMAttribute refAttr = childElement.getAttribute(new QName("href"));
     String importUrl = refAttr.getAttributeValue();
     if (importUrl.endsWith(".xsd")) {
       if (!importUrl.startsWith("http")) {
         if (registry.resourceExists(importUrl)) {
           continue;
         } else {
           if (wadlBaseUri != null) {
             importUrl = wadlBaseUri + importUrl;
           }
         }
       }
       String schemaPath = saveSchema(importUrl, wadlVersion);
       importedSchemas.add(schemaPath);
       refAttr.setAttributeValue(schemaPath);
       childElement.addAttribute(refAttr);
     }
   }
   return grammarsElement;
 }
Beispiel #8
0
 public static String getHandlerConfiguration(Registry configSystemRegistry, String name)
     throws RegistryException, XMLStreamException {
   String path = getContextRoot() + name;
   Resource resource;
   if (handlerExists(configSystemRegistry, name)) {
     resource = configSystemRegistry.get(path);
     return RegistryUtils.decodeBytes((byte[]) resource.getContent());
   }
   return null;
 }
  public static void main(String[] args) {
    try {
      String serverAddress = args[0];
      int port = Integer.parseInt(args[1]);
      String localAddress = args[2];

      /** create a httpServer */
      System.out.println("Starting HTTP server");
      HttpServer httpServer = HttpServer.create(new InetSocketAddress(80), 0);
      httpServer.createContext("/", new HttpFileHandler());
      httpServer.setExecutor(null);
      httpServer.start();

      System.out.println("Creating RMI Registry");
      Registry registry = LocateRegistry.createRegistry(1099);
      Reference reference =
          new javax.naming.Reference(
              "client.ExportObject", "client.ExportObject", "http://" + localAddress + "/");
      ReferenceWrapper referenceWrapper = new com.sun.jndi.rmi.registry.ReferenceWrapper(reference);
      registry.bind("Object", referenceWrapper);

      System.out.println("Connecting to server " + serverAddress + ":" + port);
      Socket socket = new Socket(serverAddress, port);
      System.out.println("Connected to server");
      String jndiAddress = "rmi://" + localAddress + ":1099/Object";

      org.springframework.transaction.jta.JtaTransactionManager object =
          new org.springframework.transaction.jta.JtaTransactionManager();
      object.setUserTransactionName(jndiAddress);

      System.out.println("Sending object to server...");
      ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
      objectOutputStream.writeObject(object);
      objectOutputStream.flush();
      /*
      while(true) {
      	Thread.sleep(1000);
      }
      */
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public ArrayList<KeyValueServerInterface> getServersList() throws RemoteException {
    //
    ArrayList<KeyValueServerInterface> res = new ArrayList();

    try {
      Registry registry = LocateRegistry.getRegistry();
      String[] name = registry.list();
      for (String str : name) {

        // if( str.equals(server_name) ) continue;

        KeyValueServerInterface obj = (KeyValueServerInterface) registry.lookup(str);
        res.add(obj);
      }

    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
    return res;
  }
Beispiel #11
0
  public static boolean deleteHandler(Registry configSystemRegistry, String name)
      throws RegistryException, XMLStreamException {
    if (isHandlerNameInUse(name))
      throw new RegistryException("Handler could not be deleted, since it is already in use!");

    String path = getContextRoot() + name;
    if (configSystemRegistry.resourceExists(path)) {
      try {
        configSystemRegistry.beginTransaction();
        removeHandler(configSystemRegistry, name);
        configSystemRegistry.delete(path);
        configSystemRegistry.commitTransaction();
      } catch (Exception e) {
        configSystemRegistry.rollbackTransaction();
        throw new RegistryException("Unable to remove handler", e);
      }
      return true;
    }
    return false;
  }
  private static void addToRegistry(String rootPath, File file, int tenantId) {
    try {
      Registry registry = getRegistry(tenantId);

      // This path is used to store the file resource under registry
      String fileRegistryPath =
          REGISTRY_GADGET_STORAGE_PATH
              + file.getAbsolutePath().substring(rootPath.length()).replaceAll("[/\\\\]+", "/");

      // Adding the file to the Registry
      Resource fileResource = registry.newResource();
      fileResource.setMediaType("application/vnd.wso2-gadget+xml");
      fileResource.setContentStream(new FileInputStream(file));
      registry.put(fileRegistryPath, fileResource);

    } catch (RegistryException e) {
      log.error(e.getMessage(), e);
    } catch (FileNotFoundException e) {
      log.error(e.getMessage(), e);
    }
  }
Beispiel #13
0
 public static boolean generateHandler(Registry configSystemRegistry, String resourceFullPath)
     throws RegistryException, XMLStreamException {
   RegistryContext registryContext = configSystemRegistry.getRegistryContext();
   if (registryContext == null) {
     return false;
   }
   Resource resource = configSystemRegistry.get(resourceFullPath);
   if (resource != null) {
     String content = null;
     if (resource.getContent() != null) {
       content = RegistryUtils.decodeBytes((byte[]) resource.getContent());
     }
     if (content != null) {
       OMElement handler = AXIOMUtil.stringToOM(content);
       if (handler != null) {
         OMElement dummy = OMAbstractFactory.getOMFactory().createOMElement("dummy", null);
         dummy.addChild(handler);
         try {
           configSystemRegistry.beginTransaction();
           boolean status =
               RegistryConfigurationProcessor.updateHandler(
                   dummy,
                   configSystemRegistry.getRegistryContext(),
                   HandlerLifecycleManager.USER_DEFINED_HANDLER_PHASE);
           configSystemRegistry.commitTransaction();
           return status;
         } catch (Exception e) {
           configSystemRegistry.rollbackTransaction();
           throw new RegistryException("Unable to add handler", e);
         }
       }
     }
   }
   return false;
 }
Beispiel #14
0
  /**
   * @param _port
   * @param id
   * @throws RemoteException
   * @throws UnknownHostException
   */
  public Chord(int _port, int id) throws RemoteException, UnknownHostException {
    finger = new Finger[(1 << M)]; // 1 << M = 2^(M)
    // TODO: set the fingers in the array to null
    i = id;
    port = _port;
    // TODO: determine the current IP of the machine

    predecessor = null;
    InetAddress ip = InetAddress.getLocalHost();
    successor = new Finger(ip.getHostAddress(), i, i);
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(
        new TimerTask() {
          @Override
          public void run() {
            try {
              stabilize();
            } catch (RemoteException | UnknownHostException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
            fixFingers();
            checkPredecessor();
          }
        },
        500,
        500);
    try {
      // create the registry and bind the name and object.
      System.out.println("Starting RMI at port=" + port);
      registry = LocateRegistry.createRegistry(port);
      registry.rebind("Chord", this);
    } catch (RemoteException e) {
      throw e;
    }
  }
 private void addDependency(String source, String target) throws RegistryException {
   registry.addAssociation(source, target, CommonConstants.DEPENDS);
   registry.addAssociation(target, source, CommonConstants.USED_BY);
 }
Beispiel #16
0
 public static boolean handlerExists(Registry configSystemRegistry, String name)
     throws RegistryException {
   return configSystemRegistry.resourceExists(getContextRoot() + name);
 }
  public String addWadlToRegistry(
      RequestContext requestContext, Resource resource, String resourcePath, boolean skipValidation)
      throws RegistryException {
    String wadlName = RegistryUtils.getResourceName(resourcePath);
    String version =
        requestContext.getResource().getProperty(RegistryConstants.VERSION_PARAMETER_NAME);

    if (version == null) {
      version = CommonConstants.WADL_VERSION_DEFAULT_VALUE;
      requestContext.getResource().setProperty(RegistryConstants.VERSION_PARAMETER_NAME, version);
    }

    OMElement wadlElement;
    String wadlContent;
    Object resourceContent = resource.getContent();
    if (resourceContent instanceof String) {
      wadlContent = (String) resourceContent;
    } else {
      wadlContent = new String((byte[]) resourceContent);
    }

    try {
      XMLStreamReader reader =
          XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(wadlContent));
      StAXOMBuilder builder = new StAXOMBuilder(reader);
      wadlElement = builder.getDocumentElement();
    } catch (XMLStreamException e) {
      // This exception is unexpected because the WADL already validated
      String msg = "Unexpected error occured " + "while reading the WADL at " + resourcePath + ".";
      log.error(msg);
      throw new RegistryException(msg, e);
    }

    String wadlNamespace = wadlElement.getNamespace().getNamespaceURI();
    String namespaceSegment =
        CommonUtil.derivePathFragmentFromNamespace(wadlNamespace).replace("//", "/");
    String actualPath =
        getChrootedWadlLocation(requestContext.getRegistryContext())
            + namespaceSegment
            + version
            + "/"
            + wadlName;

    OMElement grammarsElement =
        wadlElement.getFirstChildWithName(new QName(wadlNamespace, "grammars"));

    if (StringUtils.isNotBlank(requestContext.getSourceURL())) {
      String uri = requestContext.getSourceURL();
      if (!skipValidation) {
        validateWADL(uri);
      }

      if (resource.getUUID() == null) {
        resource.setUUID(UUID.randomUUID().toString());
      }

      String wadlBaseUri = uri.substring(0, uri.lastIndexOf("/") + 1);
      if (grammarsElement != null) {
        // This is to avoid evaluating the grammars import when building AST
        grammarsElement.detach();
        wadlElement.addChild(resolveImports(grammarsElement, wadlBaseUri, version));
      }
    } else {
      if (!skipValidation) {
        File tempFile = null;
        BufferedWriter bufferedWriter = null;
        try {
          tempFile = File.createTempFile(wadlName, null);
          bufferedWriter = new BufferedWriter(new FileWriter(tempFile));
          bufferedWriter.write(wadlElement.toString());
          bufferedWriter.flush();
        } catch (IOException e) {
          String msg = "Error occurred while reading the WADL File";
          log.error(msg, e);
          throw new RegistryException(msg, e);
        } finally {
          if (bufferedWriter != null) {
            try {
              bufferedWriter.close();
            } catch (IOException e) {
              String msg = "Error occurred while closing File writer";
              log.warn(msg, e);
            }
          }
        }
        validateWADL(tempFile.toURI().toString());
        try {
          delete(tempFile);
        } catch (IOException e) {
          String msg =
              "An error occurred while deleting the temporary files from local file system.";
          log.warn(msg, e);
          throw new RegistryException(msg, e);
        }
      }

      if (grammarsElement != null) {
        grammarsElement = resolveImports(grammarsElement, null, version);
        wadlElement.addChild(grammarsElement);
      }
    }

    requestContext.setResourcePath(new ResourcePath(actualPath));
    if (resource.getProperty(CommonConstants.SOURCE_PROPERTY) == null) {
      resource.setProperty(CommonConstants.SOURCE_PROPERTY, CommonConstants.SOURCE_AUTO);
    }
    registry.put(actualPath, resource);
    addImportAssociations(actualPath);
    if (getCreateService()) {
      OMElement serviceElement =
          RESTServiceUtils.createRestServiceArtifact(
              wadlElement,
              wadlName,
              version,
              RegistryUtils.getRelativePath(requestContext.getRegistryContext(), actualPath));
      String servicePath = RESTServiceUtils.addServiceToRegistry(requestContext, serviceElement);
      registry.addAssociation(servicePath, actualPath, CommonConstants.DEPENDS);
      registry.addAssociation(actualPath, servicePath, CommonConstants.USED_BY);
      String endpointPath = createEndpointElement(requestContext, wadlElement, version);
      if (endpointPath != null) {
        registry.addAssociation(servicePath, endpointPath, CommonConstants.DEPENDS);
        registry.addAssociation(endpointPath, servicePath, CommonConstants.USED_BY);
      }
    }

    return resource.getPath();
  }
Beispiel #18
0
  public static boolean save() {
    if (registry.isSaving) {
      return false;
    }

    boolean status = true;

    registry.isSaving = true;

    resolutions.add("800x600");
    resolutions.add("1024x768");
    resolutions.add("1152x864");
    resolutions.add("1280x720");
    resolutions.add("1280x768");
    resolutions.add("1280x800");
    resolutions.add("1280x960");
    resolutions.add("1280x1024");
    resolutions.add("1360x768");
    resolutions.add("1366x768");
    resolutions.add("1440x900");
    resolutions.add("1600x900");
    resolutions.add("1600x1024");
    resolutions.add("1680x1050");
    resolutions.add("1920x1080");
    resolutions.add("1920x1200");
    // resolutions.add("Full Screen");

    // try to save the settings file
    try {
      FileOutputStream settingsFile = new FileOutputStream("SettingsTemp.dat");
      ObjectOutputStream settings = new ObjectOutputStream(settingsFile);

      settings.writeObject(new Integer(1)); // settings file version
      settings.writeObject(new Integer(resolution));
      if (volumeMusic == 0) {
        settings.writeObject(new Integer(-1));
      } else {
        settings.writeObject(new Integer(volumeMusic));
      }
      if (volumeFX == 0) {
        settings.writeObject(new Integer(-1));
      } else {
        settings.writeObject(new Integer(volumeFX));
      }
      settings.writeObject(new Integer(buttonMoveRight));
      settings.writeObject(new Integer(buttonMoveLeft));
      settings.writeObject(new Integer(buttonJump));
      settings.writeObject(new Integer(buttonAction));
      settings.writeObject(new Integer(buttonRobot));
      settings.writeObject(new Integer(buttonInventory));
      settings.writeObject(new Integer(buttonPause));

      settings.close();

      moveFile("SettingsTemp.dat", "Settings.dat");
      EIError.debugMsg("Saved Settings", EIError.ErrorLevel.Notice);
    } catch (Exception e) {
      status = false;
      EIError.debugMsg("Couldn't save settings " + e.getMessage(), EIError.ErrorLevel.Error);
    }

    // try to save the players
    for (int i = 1; i <= NUMBER_OF_PLAYER_SLOTS; i++) {
      try {
        if (player == i - 1) {
          FileOutputStream playerFile = new FileOutputStream("PlayerTemp.dat");
          ObjectOutputStream playerInfo = new ObjectOutputStream(playerFile);

          playerInfo.writeObject(new Integer(2)); // settings file version
          playerInfo.writeObject(players.get(i - 1));
          if (registry.getGameController().multiplayerMode != GameController.MultiplayerMode.CLIENT
              && player == i - 1) {
            blockManagers.set(i - 1, registry.getBlockManager());
            placeableManagers.set(i - 1, registry.getPlaceableManager());
            monsterManagers.set(i - 1, registry.getMonsterManager());
          }
          playerInfo.writeObject(blockManagers.get(i - 1));
          playerInfo.writeObject(placeableManagers.get(i - 1));
          playerInfo.writeObject(monsterManagers.get(i - 1));

          playerInfo.close();

          moveFile("PlayerTemp.dat", "Player" + i + ".dat");
          EIError.debugMsg("Saved Player " + i, EIError.ErrorLevel.Notice);
        }
      } catch (Exception e) {
        status = false;
        EIError.debugMsg(
            "Couldn't save Player " + i + " " + e.getMessage(), EIError.ErrorLevel.Error);
      }
    }

    registry.isSaving = false;

    return status;
  }
  private static void transferDirectoryContentToRegistry(
      File rootDirectory, Registry registry, String rootPath, int tenantId) throws Exception {

    try {

      File[] filesAndDirs = rootDirectory.listFiles();
      List<File> filesDirs = Arrays.asList(filesAndDirs);

      for (File file : filesDirs) {

        if (!file.isFile()) {
          // This is a Directory add a new collection
          // This path is used to store the file resource under registry
          String directoryRegistryPath =
              REGISTRY_GADGET_STORAGE_PATH
                  + file.getAbsolutePath().substring(rootPath.length()).replaceAll("[/\\\\]+", "/");

          // If the collection exists no need to create it. If not, create.
          if (!registry.resourceExists(directoryRegistryPath)) {
            Collection newCollection = registry.newCollection();
            registry.put(directoryRegistryPath, newCollection);
          }

          // Set permission for anonymous read. We do it here because it should happen always in
          // order
          // to support mounting a remote registry.
          UserRegistry userRegistry = getRegistry(tenantId);
          AuthorizationManager accessControlAdmin =
              userRegistry.getUserRealm().getAuthorizationManager();

          if (!accessControlAdmin.isRoleAuthorized(
              CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME,
              RegistryConstants.CONFIG_REGISTRY_BASE_PATH + REGISTRY_GADGET_STORAGE_PATH,
              ActionConstants.GET)) {
            accessControlAdmin.authorizeRole(
                CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME,
                RegistryConstants.CONFIG_REGISTRY_BASE_PATH + REGISTRY_GADGET_STORAGE_PATH,
                ActionConstants.GET);
          }

          // recurse
          transferDirectoryContentToRegistry(file, registry, rootPath, tenantId);
        } else {
          // Adding gadget to the gadget browser: gadget conf.xml need to be present
          if (file.getName().equals(GADGET_CONF_FILE)) {
            FileInputStream fis = new FileInputStream(file);
            XMLInputFactory xif = XMLInputFactory.newInstance();
            XMLStreamReader reader = xif.createXMLStreamReader(fis);

            StAXOMBuilder builder = new StAXOMBuilder(reader);
            OMElement omEle = builder.getDocumentElement();

            String gadgetName = omEle.getFirstChildWithName(new QName("name")).getText();
            String gadgetPath = omEle.getFirstChildWithName(new QName("path")).getText();
            String gadgetDesc = omEle.getFirstChildWithName(new QName("description")).getText();

            Resource res = registry.newResource();
            res.setProperty(DashboardConstants.GADGET_NAME, gadgetName);
            res.setProperty(DashboardConstants.GADGET_DESC, gadgetDesc);
            res.setProperty(DashboardConstants.GADGET_URL, gadgetPath);

            registry.put(
                DashboardConstants.SYSTEM_GADGETREPO_REGISTRY_ROOT
                    + DashboardConstants.GADGETS_COL
                    + "/"
                    + gadgetName,
                res);

          } else {
            // Add this to registry
            addToRegistry(rootPath, file, tenantId);
          }
        }
      }
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      throw new Exception(e);
    }
  }
Beispiel #20
0
 static {
   Registry.set("video_jitter_buffer_MIN_SIZE", FMJ_VIDEO_JITTER_BUFFER_MIN_SIZE);
 }
Beispiel #21
0
  /**
   * Simulates a configSystemRegistry operation.
   *
   * <p>Operation criteria: get - path put - path, resourcePath (existing resource), optional :
   * mediaType resourceExists - path delete - path importResource - path, param1 (URL: source URL),
   * optional : mediaType copy - path, param1 (target path) move - path, param1 (target path) rename
   * - path, param1 (target path) removeLink - path createLink - path, param1 (target path),
   * optional : param2 (target sub-path) invokeAspect - path, param1 (aspect name), param2 (action)
   * addAssociation - path, param1 (target path), param2 (association type) removeAssociation -
   * path, param1 (target path), param2 (association type) getAssociations - path, param1
   * (association type) getAllAssociations - path createVersion - path restoreVersion - path
   * getVersions - path applyTag - path, param1 (tag) removeTag - path, param1 (tag) getTags - path
   * getResourcePathsWithTag - param1 (tag) rateResource - path, param1 (Number: rating) getRating -
   * path, param1 (username) getAverageRating - path addComment - path, param1 (comment)
   * removeComment - path editComment - path, param1 (comment) getComments - path searchContent -
   * param1 (keywords) executeQuery - param1 (Map: parameters, ex:- key1:val1,key2:val2,...),
   * optional: path
   *
   * <p>Operations not-supported dump restore
   *
   * @param simulationRequest the simulation request.
   * @throws Exception if an exception occurs while executing any operation, or if an invalid
   *     parameter was entered.
   */
  public static void simulateRegistryOperation(
      Registry rootRegistry, SimulationRequest simulationRequest) throws Exception {
    String operation = simulationRequest.getOperation();
    if (operation == null) {
      return;
    }
    if (operation.toLowerCase().equals("get")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.get(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("resourceexists")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.resourceExists(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("put")) {
      String path = simulationRequest.getPath();
      String resourcePath = simulationRequest.getResourcePath();
      String type = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        type = params[0];
      }

      if (isInvalidateValue(path) || isInvalidateValue(type)) {
        return;
      }
      Resource resource;
      if (!isInvalidateValue(resourcePath) && rootRegistry.resourceExists(resourcePath)) {
        resource = rootRegistry.get(resourcePath);
      } else if (type.toLowerCase().equals("collection")) {
        resource = rootRegistry.newCollection();
      } else {
        resource = rootRegistry.newResource();
      }
      simulationService.setSimulation(true);
      resource.setMediaType(simulationRequest.getMediaType());
      rootRegistry.put(path, resource);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("delete")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.delete(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("importresource")) {
      String path = simulationRequest.getPath();
      String sourceURL = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        sourceURL = params[0];
      }
      if (isInvalidateValue(path) || isInvalidateValue(sourceURL)) {
        return;
      }
      simulationService.setSimulation(true);
      Resource resource = rootRegistry.newResource();
      resource.setMediaType(simulationRequest.getMediaType());
      rootRegistry.importResource(path, sourceURL, resource);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("rename")) {
      String path = simulationRequest.getPath();
      String target = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        target = params[0];
      }
      if (isInvalidateValue(path) || isInvalidateValue(target)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.rename(path, target);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("move")) {
      String path = simulationRequest.getPath();
      String target = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        target = params[0];
      }
      if (isInvalidateValue(path) || isInvalidateValue(target)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.move(path, target);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("copy")) {
      String path = simulationRequest.getPath();
      String target = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        target = params[0];
      }
      if (isInvalidateValue(path) || isInvalidateValue(target)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.copy(path, target);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("removelink")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.removeLink(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("createlink")) {
      String path = simulationRequest.getPath();
      String target = null;
      String targetSubPath = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length > 0) {
        target = params[0];
        if (params.length > 1) {
          targetSubPath = params[1];
        }
      }
      if (isInvalidateValue(path) || isInvalidateValue(target)) {
        return;
      }
      simulationService.setSimulation(true);
      if (isInvalidateValue(targetSubPath)) {
        rootRegistry.createLink(path, target);
      } else {
        rootRegistry.createLink(path, target, targetSubPath);
      }
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("invokeaspect")) {
      String path = simulationRequest.getPath();
      String aspectName = null;
      String action = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 2) {
        aspectName = params[0];
        action = params[1];
      }
      if (isInvalidateValue(path) || isInvalidateValue(aspectName) || isInvalidateValue(action)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.invokeAspect(path, aspectName, action);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("addassociation")) {
      String path = simulationRequest.getPath();
      String target = null;
      String associationType = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 2) {
        target = params[0];
        associationType = params[1];
      }
      if (isInvalidateValue(path)
          || isInvalidateValue(target)
          || isInvalidateValue(associationType)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.addAssociation(path, target, associationType);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("removeassociation")) {
      String path = simulationRequest.getPath();
      String target = null;
      String associationType = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 2) {
        target = params[0];
        associationType = params[1];
      }
      if (isInvalidateValue(path)
          || isInvalidateValue(target)
          || isInvalidateValue(associationType)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.removeAssociation(path, target, associationType);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("getassociations")) {
      String path = simulationRequest.getPath();
      String associationType = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        associationType = params[0];
      }
      if (isInvalidateValue(path) || isInvalidateValue(associationType)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.getAssociations(path, associationType);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("getallassociations")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.getAllAssociations(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("createversion")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.createVersion(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("restoreversion")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.restoreVersion(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("getversions")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.getVersions(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("applytag")) {
      String path = simulationRequest.getPath();
      String tag = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        tag = params[0];
      }
      if (isInvalidateValue(path) || isInvalidateValue(tag)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.applyTag(path, tag);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("removetag")) {
      String path = simulationRequest.getPath();
      String tag = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        tag = params[0];
      }
      if (isInvalidateValue(path) || isInvalidateValue(tag)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.removeTag(path, tag);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("gettags")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.getTags(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("getresourcepathswithtag")) {
      String tag = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        tag = params[0];
      }
      if (isInvalidateValue(tag)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.getResourcePathsWithTag(tag);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("rateresource")) {
      String path = simulationRequest.getPath();
      int rating = -1;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        try {
          rating = Integer.parseInt(params[0]);
        } catch (NumberFormatException ignored) {
          return;
        }
      }
      if (isInvalidateValue(path) || rating == -1) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.rateResource(path, rating);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("getrating")) {
      String path = simulationRequest.getPath();
      String username = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        username = params[0];
      }
      if (isInvalidateValue(path) || isInvalidateValue(username)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.getRating(path, username);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("getaveragerating")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.getAverageRating(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("addcomment")) {
      String path = simulationRequest.getPath();
      String comment = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        comment = params[0];
      }
      if (isInvalidateValue(path) || isInvalidateValue(comment)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.addComment(path, new Comment(comment));
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("editcomment")) {
      String path = simulationRequest.getPath();
      String comment = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        comment = params[0];
      }
      if (isInvalidateValue(path) || isInvalidateValue(comment)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.editComment(path, comment);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("removeComment")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.removeComment(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("getcomments")) {
      String path = simulationRequest.getPath();
      if (isInvalidateValue(path)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.getComments(path);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("searchcontent")) {
      String keywords = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        keywords = params[0];
      }
      if (isInvalidateValue(keywords)) {
        return;
      }
      simulationService.setSimulation(true);
      rootRegistry.searchContent(keywords);
      simulationService.setSimulation(false);
    } else if (operation.toLowerCase().equals("executequery")) {
      String path = simulationRequest.getPath();
      String queryParams = null;
      String[] params = simulationRequest.getParameters();
      if (params != null && params.length >= 1) {
        queryParams = params[0];
      }
      Map<String, String> paramMap = new LinkedHashMap<String, String>();
      if (isInvalidateValue(queryParams)) {
        return;
      }
      String[] entries = queryParams.split(",");
      if (entries != null) {
        for (String entry : entries) {
          String[] keyValPair = entry.split(":");
          if (keyValPair != null && keyValPair.length == 2) {
            paramMap.put(keyValPair[0], keyValPair[1]);
          }
        }
      }
      simulationService.setSimulation(true);
      rootRegistry.executeQuery(path, paramMap);
      simulationService.setSimulation(false);
    } else {
      throw new Exception("Unsupported Registry Operation: " + operation);
    }
  }
  public void _jspService(
      final javax.servlet.http.HttpServletRequest request,
      final javax.servlet.http.HttpServletResponse response)
      throws java.io.IOException, javax.servlet.ServletException {

    final javax.servlet.jsp.PageContext pageContext;
    javax.servlet.http.HttpSession session = null;
    final javax.servlet.ServletContext application;
    final javax.servlet.ServletConfig config;
    javax.servlet.jsp.JspWriter out = null;
    final java.lang.Object page = this;
    javax.servlet.jsp.JspWriter _jspx_out = null;
    javax.servlet.jsp.PageContext _jspx_page_context = null;

    try {
      response.setContentType("text/html");
      pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\r\n\r\n");

      final DisplayState theDisplayState = (DisplayState) request.getAttribute(MasterServlet.STATE);
      final Frame frame = (Frame) request.getAttribute(AbstractChip.FRAME_KEY);

      /*
       //to be definitive NOT serializable
      InputStream noser = (InputStream)session.getAttribute( "NOT_SERIALIZABLE");
      if( noser==null )
      {
      	session.setAttribute( "NOT_SERIALIZABLE", new ByteArrayInputStream( new byte[0] ));
      }
      */

      out.write('\r');
      out.write('\n');

      final AbstractAutocompleterToolbarActionChip theChip =
          (AbstractAutocompleterToolbarActionChip) request.getAttribute(AbstractChip.CHIP_KEY);

      final String label = (theChip.getLabel() == null ? "" : localized(theChip.getLabel()));
      final String tooltip =
          (theChip.getTooltip() == null ? label : localized(theChip.getTooltip()));
      final String width =
          theChip.getWidth() != null && theChip.getWidth().length() > 0
              ? theChip.getWidth()
              : "200px";
      final String value = theChip.getValue() != null ? "value=\"" + theChip.getValue() + "\"" : "";

      final String contextMenu =
          theChip.hasVisibleContextMenuEntries()
              ? "(new Menu("
                  + theChip.createMenuEntriesForJS(theChip.getMenuEntries())
                  + ", event, null, null, { uniqueName: '"
                  + theChip.getUniqueName()
                  + "'} )).show(); return false;"
              : "return false;";

      out.write("\r\n\r\n<td title=\"");
      out.print(tooltip);
      out.write("\" class=\"toolbar-autocomplete\" oncontextmenu=\"");
      out.print(contextMenu);
      out.write(
          "\">\r\n\t<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\r\n\t\t<tr>\r\n\t\t\t<td class=\"label\">");
      out.print(label);
      out.write(":</td>\r\n\t\t\t<td><input type=\"text\" \r\n\t\t\t\t\t\t id=\"");
      out.print(theChip.getInputID());
      out.write("\" \r\n\t\t\t\t\t\t style=\"width:");
      out.print(width);
      out.write(";\"\r\n\t\t\t\t\t\t name=\"");
      out.print(theChip.getEventID(AbstractAutocompleterToolbarActionChip.VALUE));
      out.write("\" \r\n\t\t\t\t\t\t ");
      out.print(value);
      out.write("/><div id=\"");
      out.print(theChip.getMatchesID());
      out.write("\" class=\"autocomplete\"></div></td>\r\n\t\t</tr>\r\n\t</table>\r\n</td>\r\n");

      final String options =
          "{ paramName: '"
              + AbstractAutocompleterToolbarActionChip.SEARCH
              + "',"
              + "afterUpdateElement: function(inputElement, selectedListItem) "
              + "{ if( selectedListItem.nodeName == \"LI\" )"
              + "{ setEvent('"
              + theChip.getCommandID(AbstractAutocompleterToolbarActionChip.SELECT)
              + "', domQuery('span.hidden', selectedListItem)[0].firstChild.nodeValue);setScrollAndSubmit(); }"
              + "else "
              + "{	inputElement.value = \"\"; }},"
              + "onShow:       function(element, update)"
              + "{ if(!update.style.position || update.style.position=='absolute')"
              + "{	update.style.position = 'absolute'; Position.clone(element, update, { setHeight: false, setWidth:false, offsetTop: element.offsetHeight }); }"
              + "Effect.Appear(update,{duration:0.15}); } }";
      final String tenantIDStr =
          Registry.getCurrentTenant() instanceof SlaveTenant
              ? ";tenantID=" + Registry.getCurrentTenant().getTenantID()
              : "";

      out.write("\r\n<script language=\"JavaScript1.2\">\r\n\t\r\n\tnew Ajax.Autocompleter(\"");
      out.print(theChip.getInputID());
      out.write("\", \"");
      out.print(theChip.getMatchesID());
      out.write("\", \"prototype");
      out.print(tenantIDStr);
      out.write('?');
      out.print(PrototypeServlet.CHIPID);
      out.write('=');
      out.print(theChip.getID());
      out.write('"');
      out.write(',');
      out.write(' ');
      out.print(options);
      out.write(");\r\n\r\n</script>\r\n\t\t\n");
    } catch (java.lang.Throwable t) {
      if (!(t instanceof javax.servlet.jsp.SkipPageException)) {
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try {
            if (response.isCommitted()) {
              out.flush();
            } else {
              out.clearBuffer();
            }
          } catch (java.io.IOException e) {
          }
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else throw new ServletException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
Beispiel #23
0
  public static boolean updateHandler(Registry configSystemRegistry, String oldName, String payload)
      throws RegistryException, XMLStreamException {
    if (isHandlerNameInUse(oldName))
      throw new RegistryException("Could not update handler since it is already in use!");

    String newName = null;
    OMElement element = AXIOMUtil.stringToOM(payload);
    if (element != null) {
      newName = element.getAttributeValue(new QName("class"));
    }

    if (newName == null || newName.equals("")) return false; // invalid configuration

    if (oldName == null || oldName.equals("")) {
      String path = getContextRoot() + newName;
      Resource resource;
      if (handlerExists(configSystemRegistry, newName)) {
        return false; // we are adding a new handler
      } else {
        resource = new ResourceImpl();
      }
      resource.setContent(payload);
      try {
        configSystemRegistry.beginTransaction();
        configSystemRegistry.put(path, resource);
        generateHandler(configSystemRegistry, path);
        configSystemRegistry.commitTransaction();
      } catch (Exception e) {
        configSystemRegistry.rollbackTransaction();
        throw new RegistryException("Unable to generate handler", e);
      }
      return true;
    }

    if (newName.equals(oldName)) {
      // updating the rest of the content
      String oldPath = getContextRoot() + oldName;
      Resource resource;
      if (handlerExists(configSystemRegistry, oldName)) {
        resource = configSystemRegistry.get(oldPath);
      } else {
        resource = new ResourceImpl(); // will this ever happen?
      }
      resource.setContent(payload);
      try {
        configSystemRegistry.beginTransaction();
        removeHandler(configSystemRegistry, oldName);
        configSystemRegistry.put(oldPath, resource);
        generateHandler(configSystemRegistry, oldPath);
        configSystemRegistry.commitTransaction();
      } catch (Exception e) {
        configSystemRegistry.rollbackTransaction();
        throw new RegistryException("Unable to generate handler", e);
      }
      return true;
    } else {
      String oldPath = getContextRoot() + oldName;
      String newPath = getContextRoot() + newName;

      if (handlerExists(configSystemRegistry, newName)) {
        return false; // we are trying to use the name of a existing handler
      }

      Resource resource;
      if (handlerExists(configSystemRegistry, oldName)) {
        resource = configSystemRegistry.get(oldPath);
      } else {
        resource = new ResourceImpl(); // will this ever happen?
      }

      resource.setContent(payload);
      try {
        configSystemRegistry.beginTransaction();
        configSystemRegistry.put(newPath, resource);
        generateHandler(configSystemRegistry, newPath);
        removeHandler(configSystemRegistry, oldName);
        configSystemRegistry.delete(oldPath);
        configSystemRegistry.commitTransaction();
      } catch (Exception e) {
        configSystemRegistry.rollbackTransaction();
        throw new RegistryException("Unable to renew handler", e);
      }
      return true;
    }
  }
  public String importWADLToRegistry(
      RequestContext requestContext, String commonLocation, boolean skipValidation)
      throws RegistryException {

    ResourcePath resourcePath = requestContext.getResourcePath();
    String wadlName = RegistryUtils.getResourceName(resourcePath.getPath());
    String version =
        requestContext.getResource().getProperty(RegistryConstants.VERSION_PARAMETER_NAME);

    if (version == null) {
      version = CommonConstants.WADL_VERSION_DEFAULT_VALUE;
      requestContext.getResource().setProperty(RegistryConstants.VERSION_PARAMETER_NAME, version);
    }

    String uri = requestContext.getSourceURL();
    if (!skipValidation) {
      validateWADL(uri);
    }

    Registry registry = requestContext.getRegistry();
    Resource resource = registry.newResource();
    if (resource.getUUID() == null) {
      resource.setUUID(UUID.randomUUID().toString());
    }
    resource.setMediaType(wadlMediaType);
    resource.setProperties(requestContext.getResource().getProperties());

    ByteArrayOutputStream outputStream;
    OMElement wadlElement;
    try {
      InputStream inputStream = new URL(uri).openStream();

      outputStream = new ByteArrayOutputStream();
      int nextChar;
      while ((nextChar = inputStream.read()) != -1) {
        outputStream.write(nextChar);
      }
      outputStream.flush();
      wadlElement = AXIOMUtil.stringToOM(new String(outputStream.toByteArray()));
      // to validate XML
      wadlElement.toString();
    } catch (Exception e) {
      // This exception is unexpected because the WADL already validated
      throw new RegistryException(
          "Unexpected error occured " + "while reading the WADL at" + uri, e);
    }

    String wadlNamespace = wadlElement.getNamespace().getNamespaceURI();
    String namespaceSegment =
        CommonUtil.derivePathFragmentFromNamespace(wadlNamespace).replace("//", "/");

    OMElement grammarsElement =
        wadlElement.getFirstChildWithName(new QName(wadlNamespace, "grammars"));
    String wadlBaseUri = uri.substring(0, uri.lastIndexOf("/") + 1);
    if (grammarsElement != null) {
      grammarsElement.detach();
      wadlElement.addChild(resolveImports(grammarsElement, wadlBaseUri, version));
    }

    String actualPath;
    if (commonLocation != null) {
      actualPath = commonLocation + namespaceSegment + version + "/" + wadlName;
    } else {
      actualPath =
          RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH
              + commonWADLLocation
              + namespaceSegment
              + version
              + "/"
              + wadlName;
    }
    if (resource.getProperty(CommonConstants.SOURCE_PROPERTY) == null) {
      resource.setProperty(CommonConstants.SOURCE_PROPERTY, CommonConstants.SOURCE_AUTO);
    }

    resource.setContent(wadlElement.toString());
    requestContext.setResourcePath(new ResourcePath(actualPath));
    registry.put(actualPath, resource);
    addImportAssociations(actualPath);
    if (createService) {
      OMElement serviceElement =
          RESTServiceUtils.createRestServiceArtifact(
              wadlElement,
              wadlName,
              version,
              RegistryUtils.getRelativePath(requestContext.getRegistryContext(), actualPath));
      String servicePath = RESTServiceUtils.addServiceToRegistry(requestContext, serviceElement);
      addDependency(servicePath, actualPath);
      String endpointPath = createEndpointElement(requestContext, wadlElement, version);
      if (endpointPath != null) {
        addDependency(servicePath, endpointPath);
      }
    }

    return actualPath;
  }