Example #1
1
 public static OMElement serializeHandlerConfiguration(HandlerConfigurationBean bean) {
   OMFactory factory = OMAbstractFactory.getOMFactory();
   OMElement handler = factory.createOMElement("handler", null);
   handler.addAttribute(factory.createOMAttribute("class", null, bean.getHandlerClass()));
   if (bean.getTenant() != null) {
     handler.addAttribute(factory.createOMAttribute("tenant", null, bean.getTenant()));
   }
   StringBuilder sb = new StringBuilder();
   for (String method : bean.getMethods()) {
     if (method != null && method.length() > 0) {
       sb.append(method).append(",");
     }
   }
   // Remove last ","
   if (sb.length() > 0) {
     sb.deleteCharAt(sb.length() - 1);
     handler.addAttribute(factory.createOMAttribute("methods", null, sb.toString()));
   }
   for (String property : bean.getPropertyList()) {
     OMElement temp = factory.createOMElement("property", null);
     temp.addAttribute(factory.createOMAttribute("name", null, property));
     OMElement xmlProperty = bean.getXmlProperties().get(property);
     if (xmlProperty != null) {
       //                The serialization happens by adding the whole XML property value to the
       // bean.
       //                Therefore if it is a XML property, we take that whole element.
       handler.addChild(xmlProperty);
     } else {
       String nonXMLProperty = bean.getNonXmlProperties().get(property);
       if (nonXMLProperty != null) {
         temp.setText(nonXMLProperty);
         handler.addChild(temp);
       }
     }
   }
   OMElement filter = factory.createOMElement("filter", null);
   filter.addAttribute(
       factory.createOMAttribute("class", null, bean.getFilter().getFilterClass()));
   for (String property : bean.getFilter().getPropertyList()) {
     OMElement temp = factory.createOMElement("property", null);
     temp.addAttribute(factory.createOMAttribute("name", null, property));
     OMElement xmlProperty = bean.getFilter().getXmlProperties().get(property);
     if (xmlProperty != null) {
       temp.addAttribute(factory.createOMAttribute("type", null, "xml"));
       temp.addChild(xmlProperty);
       filter.addChild(temp);
     } else {
       String nonXMLProperty = bean.getFilter().getNonXmlProperties().get(property);
       if (nonXMLProperty != null) {
         temp.setText(nonXMLProperty);
         filter.addChild(temp);
       }
     }
   }
   handler.addChild(filter);
   return handler;
 }
  /**
   * Creates endpoint element for REST service
   *
   * @param requestContext information about current request.
   * @param wadlElement wadl document.
   * @param version wadl version.
   * @return Endpoint Path.
   * @throws RegistryException If fails to create endpoint element.
   */
  private String createEndpointElement(
      RequestContext requestContext, OMElement wadlElement, String version)
      throws RegistryException {
    OMNamespace wadlNamespace = wadlElement.getNamespace();
    String wadlNamespaceURI = wadlNamespace.getNamespaceURI();
    String wadlNamespacePrefix = wadlNamespace.getPrefix();
    OMElement resourcesElement =
        wadlElement.getFirstChildWithName(
            new QName(wadlNamespaceURI, "resources", wadlNamespacePrefix));
    if (resourcesElement != null) {
      String endpointUrl = resourcesElement.getAttributeValue(new QName("base"));
      if (endpointUrl != null) {
        String endpointPath = EndpointUtils.deriveEndpointFromUrl(endpointUrl);
        String endpointName = EndpointUtils.deriveEndpointNameFromUrl(endpointUrl);
        String endpointContent =
            EndpointUtils.getEndpointContentWithOverview(
                endpointUrl, endpointPath, endpointName, version);
        OMElement endpointElement;
        try {
          endpointElement = AXIOMUtil.stringToOM(endpointContent);
        } catch (XMLStreamException e) {
          throw new RegistryException("Error in creating the endpoint element. ", e);
        }

        return RESTServiceUtils.addEndpointToRegistry(
            requestContext, endpointElement, endpointPath);
      } else {
        log.warn("Base path does not exist. endpoint creation may fail. ");
      }
    } else {
      log.warn("Resources element is null. ");
    }
    return null;
  }
 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;
 }
Example #4
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;
  }
Example #5
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;
 }
 private OMElement getTextElement(String content) {
   OMFactory factory = OMAbstractFactory.getOMFactory();
   OMElement textElement = factory.createOMElement(TEXT_ELEMENT);
   if (content == null) {
     content = "";
   }
   textElement.setText(content);
   return textElement;
 }
 public static OMElement getChildWithName(OMElement head, String widgetName, String namespace) {
   String adjustedName = getDataElementName(widgetName);
   if (adjustedName == null) {
     return null;
   }
   OMElement child = head.getFirstChildWithName(new QName(namespace, adjustedName));
   if (child == null) {
     // this piece of code is for the backward compatibility
     child = head.getFirstChildWithName(new QName(null, widgetName.replaceAll(" ", "-")));
   }
   return child;
 }
  /**
   * Replaces the payload format with property values from messageContext.
   *
   * @param format
   * @param resultCTX
   * @param synCtx
   */
  private void replaceCTX(String format, StringBuffer resultCTX, MessageContext synCtx) {
    Matcher ctxMatcher;

    if (mediaType != null && (mediaType.equals(JSON_TYPE) || mediaType.equals(TEXT_TYPE))) {
      ctxMatcher = ctxPattern.matcher(format);
    } else {
      ctxMatcher = ctxPattern.matcher("<pfPadding>" + format + "</pfPadding>");
    }
    while (ctxMatcher.find()) {
      String ctxMatchSeq = ctxMatcher.group();
      String expressionTxt = ctxMatchSeq.substring(5, ctxMatchSeq.length());

      String replaceValue = synCtx.getProperty(expressionTxt).toString();

      if (mediaType.equals(JSON_TYPE) && inferReplacementType(replaceValue).equals(XML_TYPE)) {
        // XML to JSON conversion here
        try {
          replaceValue = "<jsonObject>" + replaceValue + "</jsonObject>";
          OMElement omXML = AXIOMUtil.stringToOM(replaceValue);
          replaceValue = JsonUtil.toJsonString(omXML).toString();
        } catch (XMLStreamException e) {
          handleException(
              "Error parsing XML for JSON conversion, please check your property values return valid XML: ",
              synCtx);
        } catch (AxisFault e) {
          handleException("Error converting XML to JSON", synCtx);
        }
      } else if (mediaType.equals(XML_TYPE)
          && inferReplacementType(replaceValue).equals(JSON_TYPE)) {
        // JSON to XML conversion here
        try {
          OMElement omXML = JsonUtil.toXml(IOUtils.toInputStream(replaceValue), false);
          if (JsonUtil.isAJsonPayloadElement(omXML)) { // remove <jsonObject/> from result.
            Iterator children = omXML.getChildElements();
            String childrenStr = "";
            while (children.hasNext()) {
              childrenStr += (children.next()).toString().trim();
            }
            replaceValue = childrenStr;
          } else {
            replaceValue = omXML.toString();
          }
        } catch (AxisFault e) {
          handleException(
              "Error converting JSON to XML, please check your property values return valid JSON: ",
              synCtx);
        }
      }
      ctxMatcher.appendReplacement(resultCTX, replaceValue);
    }
    ctxMatcher.appendTail(resultCTX);
  }
 public static OMElement buildOMElement(String payload) throws RegistryException {
   OMElement element;
   try {
     element = AXIOMUtil.stringToOM(payload);
     element.build();
   } catch (Exception e) {
     String message =
         "Unable to parse the XML configuration. Please validate the XML configuration";
     log.error(message, e);
     throw new RegistryException(message, e);
   }
   return element;
 }
 public static String getNameFromContent(OMElement head) {
   OMElement overview = head.getFirstChildWithName(new QName("Overview"));
   if (overview != null) {
     return overview.getFirstChildWithName(new QName("Name")).getText();
   }
   overview =
       head.getFirstChildWithName(new QName(UIGeneratorConstants.DATA_NAMESPACE, "overview"));
   if (overview != null) {
     return overview
         .getFirstChildWithName(new QName(UIGeneratorConstants.DATA_NAMESPACE, "name"))
         .getText();
   }
   return null;
 }
 private boolean checkAndReplaceEnvelope(OMElement resultElement, MessageContext synCtx) {
   OMElement firstChild = resultElement.getFirstElement();
   QName resultQName = firstChild.getQName();
   if (resultQName.getLocalPart().equals("Envelope")
       && (resultQName.getNamespaceURI().equals(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI)
           || resultQName.getNamespaceURI().equals(SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI))) {
     SOAPEnvelope soapEnvelope = AXIOMUtils.getSOAPEnvFromOM(resultElement.getFirstElement());
     if (soapEnvelope != null) {
       try {
         soapEnvelope.buildWithAttachments();
         synCtx.setEnvelope(soapEnvelope);
       } catch (AxisFault axisFault) {
         handleException("Unable to attach SOAPEnvelope", axisFault, synCtx);
       }
     }
   } else {
     return false;
   }
   return true;
 }
 private boolean mediate(MessageContext synCtx, String format) {
   if (!isDoingXml(synCtx) && !isDoingJson(synCtx)) {
     log.error(
         "#mediate. Could not identify the payload format of the existing payload prior to mediate.");
     return false;
   }
   org.apache.axis2.context.MessageContext axis2MessageContext =
       ((Axis2MessageContext) synCtx).getAxis2MessageContext();
   StringBuffer result = new StringBuffer();
   StringBuffer resultCTX = new StringBuffer();
   regexTransformCTX(resultCTX, synCtx, format);
   replace(resultCTX.toString(), result, synCtx);
   String out = result.toString().trim();
   if (log.isDebugEnabled()) {
     log.debug("#mediate. Transformed payload format>>> " + out);
   }
   if (mediaType.equals(XML_TYPE)) {
     try {
       JsonUtil.removeJsonPayload(axis2MessageContext);
       OMElement omXML = AXIOMUtil.stringToOM(out);
       if (!checkAndReplaceEnvelope(
           omXML,
           synCtx)) { // check if the target of the PF 'format' is the entire SOAP envelop, not
                      // just the body.
         axis2MessageContext.getEnvelope().getBody().addChild(omXML.getFirstElement());
       }
     } catch (XMLStreamException e) {
       handleException("Error creating SOAP Envelope from source " + out, synCtx);
     }
   } else if (mediaType.equals(JSON_TYPE)) {
     JsonUtil.newJsonPayload(axis2MessageContext, out, true, true);
   } else if (mediaType.equals(TEXT_TYPE)) {
     JsonUtil.removeJsonPayload(axis2MessageContext);
     axis2MessageContext.getEnvelope().getBody().addChild(getTextElement(out));
   }
   // need to honour a content-type of the payload media-type as output from the payload
   // {re-merging patch https://wso2.org/jira/browse/ESBJAVA-3014}
   setContentType(synCtx);
   return true;
 }
 /**
  * Calls the replaceCTX function. isFormatDynamic check is used to remove indentations which come
  * from registry based configurations.
  *
  * @param resultCTX
  * @param synCtx
  * @param format
  */
 private void regexTransformCTX(StringBuffer resultCTX, MessageContext synCtx, String format) {
   if (isFormatDynamic()) {
     String key = formatKey.evaluateValue(synCtx);
     Object entry = synCtx.getEntry(key);
     if (entry == null) {
       handleException("Key " + key + " not found ", synCtx);
     }
     String text = "";
     if (entry instanceof OMElement) {
       OMElement e = (OMElement) entry;
       removeIndentations(e);
       text = e.toString();
     } else if (entry instanceof OMText) {
       text = ((OMText) entry).getText();
     } else if (entry instanceof String) {
       text = (String) entry;
     }
     replaceCTX(text, resultCTX, synCtx);
   } else {
     replaceCTX(format, resultCTX, synCtx);
   }
 }
 public static List<OMElement> getChildsWithName(
     OMElement head, String widgetName, String namespace) {
   String adjustedName = getDataElementName(widgetName);
   if (adjustedName == null) {
     return null;
   }
   List<OMElement> list = new ArrayList<OMElement>();
   Iterator headingList = head.getChildrenWithName(new QName(namespace, adjustedName));
   while (headingList.hasNext()) {
     OMElement subheading = (OMElement) headingList.next();
     list.add(subheading);
   }
   return list;
 }
 /**
  * Helper function to remove indentations.
  *
  * @param element
  * @param removables
  */
 private void removeIndentations(OMElement element, List<OMText> removables) {
   Iterator children = element.getChildren();
   while (children.hasNext()) {
     Object next = children.next();
     if (next instanceof OMText) {
       OMText text = (OMText) next;
       if (text.getText().trim().equals("")) {
         removables.add(text);
       }
     } else if (next instanceof OMElement) {
       removeIndentations((OMElement) next, removables);
     }
   }
 }
  public static OMElement addExtraElements(OMElement data, HttpServletRequest request) {
    OMFactory fac = OMAbstractFactory.getOMFactory();
    // adding required fields at the top of the xml which will help to easily read in service side
    OMElement operation = fac.createOMElement("operation", null);
    OMElement currentName = fac.createOMElement("currentName", null);
    OMElement currentNamespace = fac.createOMElement("currentNamespace", null);

    String operationValue = request.getParameter("operation");
    if (operationValue != null) {
      operation.setText(operationValue);
      data.addChild(operation);
    }
    String name = request.getParameter("currentname");
    if (name != null) {
      currentName.setText(name);
      data.addChild(currentName);
    }
    String namespace = request.getParameter("currentnamespace");
    if (namespace != null) {
      currentNamespace.setText(namespace);
      data.addChild(currentNamespace);
    }
    return data;
  }
  /*
  * This method is used to capture the lifecycle attribute from the configuration.
  *
  * expected configuration elements are
  *
  * <field type="options">
          <name label="Lifecycle Name" >Lifecycle Name</name>
          <values class="org.wso2.carbon.governance.generic.ui.utils.LifecycleListPopulator"/>
      </field>
  *
  * or
  *
  *  <field type="options">
          <name label="Lifecycle Name" >Lifecycle Name</name>
          <values class="com.foo.bar.LifecycleListPopulator" isLifecycle="true"/>
      </field>
  *  */
  private static String BuilLifecycleAttribute(
      GovernanceArtifactConfiguration configuration,
      String defaultLifecycleGeneratorClass,
      String lifecycleAttribute) {
    try {
      //            This part checks whether the user has given a lifecycle populates.
      //            If not, then we check whether there is an attribute called, "isLifecycle"
      //            This attribute will identify the lifecycle attribute from the configuration.
      OMElement configurationElement = configuration.getContentDefinition();
      String xpathExpression = "//@class";

      AXIOMXPath xpath = new AXIOMXPath(xpathExpression);
      List resultNodes = xpath.selectNodes(configurationElement);

      if (resultNodes != null && resultNodes.size() > 0) {
        String lifecycleParentName = null;
        String lifecycleName = null;

        for (Object resultNode : resultNodes) {
          OMElement parentElement = ((OMAttribute) resultNode).getOwner();
          if (parentElement
              .getAttributeValue(new QName("class"))
              .equals(defaultLifecycleGeneratorClass)) {
            Iterator childrenIterator = parentElement.getParent().getChildrenWithLocalName("name");
            while (childrenIterator.hasNext()) {
              OMElement next = (OMElement) childrenIterator.next();
              lifecycleName = next.getAttributeValue(new QName("label"));
            }
            OMElement rootElement = (OMElement) ((OMElement) parentElement.getParent()).getParent();
            lifecycleParentName = rootElement.getAttributeValue(new QName("name"));
            break;
          } else if (parentElement.getAttributeValue(new QName("isLifecycle")) != null
              && parentElement.getAttributeValue(new QName("isLifecycle")).equals("true")) {
            Iterator childrenIterator = parentElement.getParent().getChildrenWithLocalName("name");
            while (childrenIterator.hasNext()) {
              OMElement next = (OMElement) childrenIterator.next();
              lifecycleName = next.getAttributeValue(new QName("label"));
            }
            OMElement rootElement = (OMElement) ((OMElement) parentElement.getParent()).getParent();
            lifecycleParentName = rootElement.getAttributeValue(new QName("name"));
            break;
          }
        }
        if (lifecycleParentName != null && lifecycleName != null) {
          return convertName(lifecycleParentName.split(" "))
              + "_"
              + convertName(lifecycleName.split(" "));
        }
      }

    } catch (OMException e) {
      log.error(
          "Governance artifact configuration of configuration key:"
              + configuration.getKey()
              + " is invalid",
          e);
    } catch (JaxenException e) {
      log.error("Error in getting the lifecycle attribute", e);
    }
    return null;
  }
Example #18
0
  public static HandlerConfigurationBean deserializeHandlerConfiguration(
      OMElement configurationElement) {
    if (configurationElement == null || !"handler".equals(configurationElement.getLocalName())) {
      return null;
    }
    HandlerConfigurationBean handlerConfigurationBean = new HandlerConfigurationBean();
    handlerConfigurationBean.setHandlerClass(
        configurationElement.getAttributeValue(new QName("class")));
    handlerConfigurationBean.setTenant(configurationElement.getAttributeValue(new QName("tenant")));
    String methodsAttribute = configurationElement.getAttributeValue(new QName("methods"));
    if (methodsAttribute != null && methodsAttribute.length() != 0) {
      handlerConfigurationBean.setMethods(methodsAttribute.split(","));
    }
    @SuppressWarnings("unchecked")
    Iterator<OMElement> handlerProps =
        configurationElement.getChildrenWithName(new QName("property"));
    while (handlerProps.hasNext()) {
      OMElement propElement = handlerProps.next();
      String propName = propElement.getAttributeValue(new QName("name"));
      String propType = propElement.getAttributeValue(new QName("type"));

      if (propType != null && "xml".equals(propType)) {
        handlerConfigurationBean.getXmlProperties().put(propName, propElement);
      } else {
        handlerConfigurationBean.getNonXmlProperties().put(propName, propElement.getText());
      }
      handlerConfigurationBean.getPropertyList().add(propName);
    }
    FilterConfigurationBean filterConfigurationBean = new FilterConfigurationBean();
    OMElement filterElement = configurationElement.getFirstChildWithName(new QName("filter"));
    filterConfigurationBean.setFilterClass(filterElement.getAttributeValue(new QName("class")));
    @SuppressWarnings("unchecked")
    Iterator<OMElement> filterProps = filterElement.getChildrenWithName(new QName("property"));
    while (filterProps.hasNext()) {
      OMElement propElement = filterProps.next();
      String propName = propElement.getAttributeValue(new QName("name"));
      String propType = propElement.getAttributeValue(new QName("type"));

      if (propType != null && "xml".equals(propType)) {
        filterConfigurationBean.getXmlProperties().put(propName, propElement);
      } else {
        filterConfigurationBean.getNonXmlProperties().put(propName, propElement.getText());
      }
      filterConfigurationBean.getPropertyList().add(propName);
    }
    handlerConfigurationBean.setFilter(filterConfigurationBean);
    return handlerConfigurationBean;
  }
 public static void buildMenuItems(HttpServletRequest request, String s, String s1, String s2) {
   int menuOrder = 50;
   if (CarbonUIUtil.isUserAuthorized(request, "/permission/admin/manage/resources/ws-api")) {
     HttpSession session = request.getSession();
     String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
     try {
       WSRegistryServiceClient registry = new WSRegistryServiceClient(s2, cookie);
       List<GovernanceArtifactConfiguration> configurations =
           GovernanceUtils.findGovernanceArtifactConfigurations(registry);
       Map<String, String> customAddUIMap = new LinkedHashMap<String, String>();
       Map<String, String> customViewUIMap = new LinkedHashMap<String, String>();
       List<Menu> userCustomMenuItemsList = new LinkedList<Menu>();
       for (GovernanceArtifactConfiguration configuration : configurations) {
         Component component = new Component();
         OMElement uiConfigurations = configuration.getUIConfigurations();
         String key = configuration.getKey();
         String configurationPath =
             RegistryConstants.CONFIG_REGISTRY_BASE_PATH
                 + RegistryConstants.GOVERNANCE_COMPONENT_PATH
                 + "/configuration/";
         String layoutStoragePath = configurationPath + key;
         RealmService realmService = registry.getRegistryContext().getRealmService();
         if (realmService
                 .getTenantUserRealm(realmService.getTenantManager().getTenantId(s1))
                 .getAuthorizationManager()
                 .isUserAuthorized(s, configurationPath, ActionConstants.PUT)
             || registry.resourceExists(layoutStoragePath)) {
           List<Menu> menuList = component.getMenusList();
           if (uiConfigurations != null) {
             ComponentBuilder.processMenus("artifactType", uiConfigurations, component);
             ComponentBuilder.processCustomUIs(uiConfigurations, component);
           }
           if (menuList.size() == 0) {
             // if no menu definitions were present, define the default ones.
             menuOrder = buildMenuList(request, configuration, menuList, key, menuOrder);
           }
           userCustomMenuItemsList.addAll(menuList);
           customAddUIMap.putAll(component.getCustomAddUIMap());
           Map<String, String> viewUIMap = component.getCustomViewUIMap();
           if (viewUIMap.isEmpty()) {
             // if no custom UI definitions were present, define the default.
             buildViewUI(configuration, viewUIMap, key);
           }
           customViewUIMap.putAll(viewUIMap);
           OMElement layout = configuration.getContentDefinition();
           if (layout != null && !registry.resourceExists(layoutStoragePath)) {
             Resource resource = registry.newResource();
             resource.setContent(RegistryUtils.encodeString(layout.toString()));
             resource.setMediaType("application/xml");
             registry.put(layoutStoragePath, resource);
           }
         }
       }
       session.setAttribute(
           MenuAdminClient.USER_CUSTOM_MENU_ITEMS,
           userCustomMenuItemsList.toArray(new Menu[userCustomMenuItemsList.size()]));
       session.setAttribute("customAddUI", customAddUIMap);
       session.setAttribute("customViewUI", customViewUIMap);
     } catch (RegistryException e) {
       log.error("unable to create connection to registry");
     } catch (org.wso2.carbon.user.api.UserStoreException e) {
       log.error("unable to realm service");
     }
   }
 }
Example #20
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 static String getRXTKeyFromContent(String payload) throws RegistryException {
   OMElement element = buildOMElement(payload);
   return element.getAttributeValue(new QName("shortName"));
 }
  /**
   * Replaces the payload format with SynapsePath arguments which are evaluated using
   * getArgValues().
   *
   * @param format
   * @param result
   * @param synCtx
   */
  private void replace(String format, StringBuffer result, MessageContext synCtx) {
    HashMap<String, String>[] argValues = getArgValues(synCtx);
    HashMap<String, String> replacement;
    Map.Entry<String, String> replacementEntry;
    String replacementValue = null;
    Matcher matcher;

    matcher = pattern.matcher(format);
    try {
      while (matcher.find()) {
        String matchSeq = matcher.group();
        int argIndex;
        try {
          argIndex = Integer.parseInt(matchSeq.substring(1, matchSeq.length()));
        } catch (NumberFormatException e) {
          argIndex = Integer.parseInt(matchSeq.substring(2, matchSeq.length() - 1));
        }
        replacement = argValues[argIndex - 1];
        replacementEntry = replacement.entrySet().iterator().next();
        if (mediaType.equals(JSON_TYPE)
            && inferReplacementType(replacementEntry).equals(XML_TYPE)) {
          // XML to JSON conversion here
          try {
            replacementValue = "<jsonObject>" + replacementEntry.getKey() + "</jsonObject>";
            OMElement omXML = AXIOMUtil.stringToOM(replacementValue);
            replacementValue =
                JsonUtil.toJsonString(omXML)
                    .toString()
                    .replaceAll(
                        ESCAPE_DOUBLE_QUOTE_WITH_FIVE_BACK_SLASHES,
                        ESCAPE_DOUBLE_QUOTE_WITH_NINE_BACK_SLASHES)
                    .replaceAll(
                        ESCAPE_DOLLAR_WITH_TEN_BACK_SLASHES, ESCAPE_DOLLAR_WITH_SIX_BACK_SLASHES);
            replacementValue = JsonUtil.toJsonString(omXML).toString();
          } catch (XMLStreamException e) {
            handleException(
                "Error parsing XML for JSON conversion, please check your xPath expressions return valid XML: ",
                synCtx);
          } catch (AxisFault e) {
            handleException("Error converting XML to JSON", synCtx);
          }
        } else if (mediaType.equals(XML_TYPE)
            && inferReplacementType(replacementEntry).equals(JSON_TYPE)) {
          // JSON to XML conversion here
          try {
            OMElement omXML =
                JsonUtil.toXml(IOUtils.toInputStream(replacementEntry.getKey()), false);
            if (JsonUtil.isAJsonPayloadElement(omXML)) { // remove <jsonObject/> from result.
              Iterator children = omXML.getChildElements();
              String childrenStr = "";
              while (children.hasNext()) {
                childrenStr += (children.next()).toString().trim();
              }
              replacementValue = childrenStr;
            } else { /// ~
              replacementValue = omXML.toString();
            }
            // replacementValue = omXML.toString();
          } catch (AxisFault e) {
            handleException(
                "Error converting JSON to XML, please check your JSON Path expressions return valid JSON: ",
                synCtx);
          }
        } else {
          // No conversion required, as path evaluates to regular String.
          replacementValue = replacementEntry.getKey();
          // This is to replace " with \" and \\ with \\\\
          if (mediaType.equals(JSON_TYPE)
              && inferReplacementType(replacementEntry).equals(STRING_TYPE)
              && (!replacementValue.startsWith("{") && !replacementValue.startsWith("["))) {
            replacementValue =
                replacementValue
                    .replaceAll(
                        Matcher.quoteReplacement("\\\\"),
                        ESCAPE_BACK_SLASH_WITH_SIXTEEN_BACK_SLASHES)
                    .replaceAll("\"", ESCAPE_DOUBLE_QUOTE_WITH_TEN_BACK_SLASHES);
          } else if ((mediaType.equals(JSON_TYPE)
                  && inferReplacementType(replacementEntry).equals(JSON_TYPE))
              && (!replacementValue.startsWith("{") && !replacementValue.startsWith("["))) {
            // This is to handle only the string value
            replacementValue =
                replacementValue.replaceAll("\"", ESCAPE_DOUBLE_QUOTE_WITH_TEN_BACK_SLASHES);
          }
        }
        matcher.appendReplacement(result, replacementValue);
      }
    } catch (ArrayIndexOutOfBoundsException e) {
      log.error("#replace. Mis-match detected between number of formatters and arguments", e);
    }
    matcher.appendTail(result);
  }
Example #23
0
  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;
  }
Example #24
0
  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();
  }