/**
   * 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);
  }
 /**
  * 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);
   }
 }
  /**
   * 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);
  }
Пример #4
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();
  }
Пример #5
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;
  }
Пример #6
0
 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");
     }
   }
 }