Exemple #1
0
  @Test(
      groups = "wso2.esb",
      description =
          "- Pass through proxy"
              + "- Create a proxy service and pick the endpoint from registry (config)")
  public void testPassThroughProxy() throws Exception {

    OMElement response =
        axis2Client.sendSimpleStockQuoteRequest(
            getProxyServiceURL("StockQuoteProxy"), null, "WSO2");

    String lastPrice =
        response
            .getFirstElement()
            .getFirstChildWithName(new QName("http://services.samples/xsd", "last"))
            .getText();
    assertNotNull(lastPrice, "Fault: response message 'last' price null");

    String symbol =
        response
            .getFirstElement()
            .getFirstChildWithName(new QName("http://services.samples/xsd", "symbol"))
            .getText();
    assertEquals(symbol, "WSO2", "Fault: value 'symbol' mismatched");
  }
  /**
   *
   *
   * <pre>
   * <loadBalancerConfig xmlns="http://ws.apache.org/ns/synapse">
   * <property name="ec2PrivateKey" value="/mnt/payload/pk.pem"/>
   * <property name="ec2Cert" value="/mnt/payload/cert.pem"/>
   * <property name="sshKey" value="stratos-1.0.0-keypair"/>
   * <property name="instanceMgtEPR" value="https://ec2.amazonaws.com/"/>
   * <property name="disableApiTermination" value="true"/>
   * <property name="enableMonitoring" value="true"/>
   * <loadBalancer>
   * <property name="securityGroups" value="stratos-appserver-lb"/>
   * <property name="instanceType" value="m1.large"/>
   * <property name="instances" value="1"/>
   * <property name="elasticIP" value="${ELASTIC_IP}"/>
   * <property name="availabilityZone" value="us-east-1c"/>
   * <property name="payload" value="/mnt/payload.zip"/>
   * </loadBalancer>
   * <p/>
   * <services>
   * <defaults>
   * <property name="payload" value="resources/cluster_node.zip"/>
   * <property name="availabilityZone" value="us-east-1c"/>
   * <property name="securityGroups" value="default-2011-02-23"/>
   * <property name="instanceType" value="m1.large"/>
   * <property name="minAppInstances" value="1"/>
   * <property name="maxAppInstances" value="5"/>
   * <property name="queueLengthPerNode" value="400"/>
   * <property name="roundsToAverage" value="10"/>
   * <property name="instancesPerScaleUp" value="1"/>
   * <property name="messageExpiryTime" value="60000"/>
   * <property name="preserveOldestInstance" value="true"/>
   * </defaults>
   * <service>
   * <hosts>
   * <host>cloud-test.wso2.com</host>
   * </hosts>
   * <domain>wso2.manager.domain</domain>
   * </service>
   * <service>
   * <hosts>
   * <host>appserver.cloud-test.wso2.com</host>
   * <host>as.cloud-test.wso2.com</host>
   * </hosts>
   * <domain>wso2.as.domain</domain>
   * <p/>
   * <property name="payload" value="resources/cluster_node.zip"/>
   * <property name="availabilityZone" value="us-east-1c"/>
   * </service>
   * <service>
   * <hosts>
   * <host>esb.cloud-test.wso2.com</host>
   * </hosts>
   * <domain>wso2.esb.domain</domain>
   * <p/>
   * <property name="payload" value="resources/cluster_node.zip"/>
   * <property name="minAppInstances" value="1"/>
   * <property name="maxAppInstances" value="5"/>
   * <property name="queueLengthPerNode" value="400"/>
   * <property name="roundsToAverage" value="10"/>
   * <property name="instancesPerScaleUp" value="1"/>
   * <property name="availabilityZone" value="us-east-1c"/>
   * <property name="securityGroups" value="ds-2011-02-23"/>
   * </service>
   * <service>
   * <hosts>
   * <host>governance.cloud-test.wso2.com</host>
   * </hosts>
   * <domain>wso2.governance.domain</domain>
   * </service>
   * <service>
   * <hosts>
   * <host>identity.cloud-test.wso2.com</host>
   * </hosts>
   * <domain>wso2.is.domain</domain>
   * </service>
   * </services>
   * </loadBalancerConfig>
   * </pre>
   *
   * @param configURL URL of the load balancer config
   */
  public void init(String configURL) {
    if (configURL.startsWith("$system:")) {
      configURL = System.getProperty(configURL.substring("$system:".length()));
    }
    StAXOMBuilder builder;
    try {
      builder = new StAXOMBuilder(new URL(configURL).openStream());
    } catch (Exception e) {
      throw new RuntimeException("Cannot read configuration file from URL " + configURL);
    }
    OMElement loadBalancerConfigEle = builder.getDocumentElement();

    // Set all properties
    try {
      for (Iterator<OMElement> iter = loadBalancerConfigEle.getChildrenWithLocalName("property");
          iter.hasNext(); ) {
        setProperty(this, iter.next());
      }
    } catch (Exception e) {
      throw new RuntimeException("Error setting values to " + this.getClass().getName(), e);
    }

    // Set load balancer config
    OMElement loadBalancerEle =
        loadBalancerConfigEle.getFirstChildWithName(
            new QName(SynapseConstants.SYNAPSE_NAMESPACE, "loadBalancer"));
    createLoadBalancerConfig(loadBalancerEle);

    // Set services config
    OMElement servicesEle =
        loadBalancerConfigEle.getFirstChildWithName(
            new QName(SynapseConstants.SYNAPSE_NAMESPACE, "services"));
    createServicesConfig(servicesEle);
  }
  private java.lang.Object fromOM(
      org.apache.axiom.om.OMElement param, java.lang.Class type, java.util.Map extraNamespaces)
      throws org.apache.axis2.AxisFault {

    try {

      if (com.pa.SetEmp.class.equals(type)) {

        return com.pa.SetEmp.Factory.parse(param.getXMLStreamReaderWithoutCaching());
      }

      if (com.pa.GetEmp.class.equals(type)) {

        return com.pa.GetEmp.Factory.parse(param.getXMLStreamReaderWithoutCaching());
      }

      if (com.pa.GetEmpResponse.class.equals(type)) {

        return com.pa.GetEmpResponse.Factory.parse(param.getXMLStreamReaderWithoutCaching());
      }

    } catch (java.lang.Exception e) {
      throw org.apache.axis2.AxisFault.makeFault(e);
    }
    return null;
  }
  public OMElement serialize(OMFactory fac) {

    if (log.isDebugEnabled() || log.isTraceEnabled()) {
      log.debug("Serialize command");
    }

    /*
     * org.apache.axiom.om.OMNamespace nullNS = fac.createOMNamespace(
     * XMLConfigConstants.NULL_NAMESPACE, "");
     */
    ValueSerializer valueSerializer = new ValueSerializer();

    OMElement root = AuditMediatorUtils.createTag(fac, this.type);

    for (Iterator iterator = params.iterator(); iterator.hasNext(); ) {
      Param param = (Param) iterator.next();

      OMElement paramTag = AuditMediatorUtils.createTag(fac, AuditMediatorUtils.PARAM_TAG_NAME);

      root.addChild(paramTag);

      paramTag.addAttribute(
          fac.createOMAttribute(
              AuditMediatorUtils.NAME_ATT_NAME, AuditMediatorUtils.nullNS, param.getName()));

      valueSerializer.serializeValue(param.getValue(), AuditMediatorUtils.VALUE_ATT_NAME, paramTag);
    }

    return root;
  }
  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;
  }
Exemple #6
0
  /**
   * Method processAttributes.
   *
   * @param node
   */
  protected void processAttributes(OMElement node) {
    int attribCount = parser.getAttributeCount();
    for (int i = 0; i < attribCount; i++) {
      String uri = parser.getAttributeNamespace(i);
      String prefix = parser.getAttributePrefix(i);

      OMNamespace namespace = null;
      if (uri != null && uri.length() > 0) {

        // prefix being null means this elements has a default namespace or it has inherited
        // a default namespace from its parent
        namespace = node.findNamespace(uri, prefix);
        if (namespace == null) {
          if (prefix == null || "".equals(prefix)) {
            prefix = OMSerializerUtil.getNextNSPrefix();
          }
          namespace = node.declareNamespace(uri, prefix);
        }
      }

      // todo if the attributes are supposed to namespace qualified all the time
      // todo then this should throw an exception here

      OMAttribute attr =
          node.addAttribute(
              parser.getAttributeLocalName(i), parser.getAttributeValue(i), namespace);
      attr.setAttributeType(parser.getAttributeType(i));
    }
  }
  @Test(groups = "wso2.esb", description = "Tests small message in small number ~100")
  public void testLargeNumbers() throws Exception {
    int beforeLogSize = logViewer.getAllRemoteSystemLogs().length;

    OMElement response = null;
    for (int i = 0; i < 100; i++) {
      response = axis2Client.sendCustomQuoteRequest(getMainSequenceURL(), null, "MSFT" + symbol);
      Assert.assertNotNull(response);
      Assert.assertTrue(
          response.toString().contains("MSFT"),
          "Incorrect symbol in response. Could not find symbol MSFT ..");
      response = null;
    }

    LogEvent[] logs = logViewer.getAllRemoteSystemLogs();
    int afterLogSize = logs.length;
    int forEachCount = 0;

    for (int i = (afterLogSize - beforeLogSize - 1); i >= 0; i--) {
      String message = logs[i].getMessage();
      if (message.contains("foreach = in")) {
        if (!message.contains("MSFT")) {
          Assert.fail("Incorrect message entered ForEach scope");
        }
        forEachCount++;
      }
    }

    Assert.assertEquals(forEachCount, 100, "Count of messages entered ForEach scope is incorrect");
  }
 private void processCredentialElement(
     OMElement bamServerConfig, BAMServerProfile bamServerProfile) throws CryptoException {
   OMElement credentialElement =
       bamServerConfig.getFirstChildWithName(
           new QName(BPELConstants.BAM_SERVER_PROFILE_NS, "Credential"));
   if (credentialElement != null) {
     OMAttribute userNameAttr = credentialElement.getAttribute(new QName("userName"));
     OMAttribute passwordAttr = credentialElement.getAttribute(new QName("password"));
     // OMAttribute secureAttr = credentialElement.getAttribute(new QName("secure"));
     if (userNameAttr != null
         && passwordAttr != null
         && /*secureAttr != null &&*/ !userNameAttr.getAttributeValue().equals("")
         && !passwordAttr.getAttributeValue().equals("")
     /*&& !secureAttr.getAttributeValue().equals("")*/ ) {
       bamServerProfile.setUserName(userNameAttr.getAttributeValue());
       bamServerProfile.setPassword(
           new String(
               CryptoUtil.getDefaultCryptoUtil()
                   .base64DecodeAndDecrypt(passwordAttr.getAttributeValue())));
     } else {
       String errMsg = "Username or Password not found for BAM server profile: " + profileLocation;
       handleError(errMsg);
     }
   } else {
     String errMsg = "Credentials not found for BAM server profile: " + profileLocation;
     handleError(errMsg);
   }
 }
 private void processKeyStoreElement(
     OMElement bamServerConfig, BAMServerProfile bamServerProfile) {
   OMElement keyStoreElement =
       bamServerConfig.getFirstChildWithName(
           new QName(BPELConstants.BAM_SERVER_PROFILE_NS, "KeyStore"));
   if (keyStoreElement != null) {
     OMAttribute locationAttr = keyStoreElement.getAttribute(new QName("location"));
     OMAttribute passwordAttr = keyStoreElement.getAttribute(new QName("password"));
     if (locationAttr != null
         && passwordAttr != null
         && !locationAttr.getAttributeValue().equals("")
         && !passwordAttr.getAttributeValue().equals("")) {
       bamServerProfile.setKeyStoreLocation(locationAttr.getAttributeValue());
       bamServerProfile.setKeyStorePassword(passwordAttr.getAttributeValue());
     } else {
       String errMsg =
           "Key store details location or password not found for BAM "
               + "server profile: "
               + profileLocation;
       handleError(errMsg);
     }
   } else {
     String errMsg = "Key store element not found for BAM server profile: " + profileLocation;
     handleError(errMsg);
   }
 }
  private static OMElement loadConfigXML() throws ManagementConfigurationException {

    String carbonHome = System.getProperty(ServerConstants.CARBON_CONFIG_DIR_PATH);
    String path = carbonHome + File.separator + ConfigurationConstants.CEP_MANAGEMENT_XML;

    BufferedInputStream inputStream = null;
    try {
      inputStream = new BufferedInputStream(new FileInputStream(new File(path)));
      XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
      StAXOMBuilder builder = new StAXOMBuilder(parser);
      OMElement omElement = builder.getDocumentElement();
      omElement.build();
      return omElement;
    } catch (FileNotFoundException e) {
      throw new ManagementConfigurationException(
          ConfigurationConstants.CEP_MANAGEMENT_XML + "cannot be found in the path : " + path, e);
    } catch (XMLStreamException e) {
      throw new ManagementConfigurationException(
          "Invalid XML for "
              + ConfigurationConstants.CEP_MANAGEMENT_XML
              + " located in the path : "
              + path,
          e);
    } finally {
      try {
        if (inputStream != null) {
          inputStream.close();
        }
      } catch (IOException e) {
        log.error("Can not shutdown the input stream", e);
      }
    }
  }
  public static OMElement read(String filePath) throws FileNotFoundException, XMLStreamException {
    OMElement documentElement = null;
    XMLStreamReader parser = null;
    InputStreamReader in = null;

    try {

      in = new InputStreamReader(new FileInputStream(filePath), Charset.defaultCharset());
      parser = XMLInputFactory.newInstance().createXMLStreamReader(in);
      // create the builder
      StAXOMBuilder builder = new StAXOMBuilder(parser);
      // get the root element
      documentElement = builder.getDocumentElement();
      documentElement.build();
    } finally {
      if (parser != null) {
        parser.close();
      }

      try {
        if (in != null) in.close();
      } catch (IOException e) {
        // ignore
      }
    }
    return documentElement;
  }
  public void testCheckSecurityScenario15CSVDataService() throws Exception {
    ServiceManagement instServiceManagement = new ServiceManagement(browser);

    String serviceName = "CSVDataService";
    String nameSpace = "http://ws.wso2.org/dataservice";
    String soapAction = "urn:getAllCustomer";
    String operation = "getAllCustomer";

    instServiceManagement.Login();
    instServiceManagement.enableSecurityScenario(serviceName, "scenario14");
    OMElement result =
        new SecurityClient()
            .runSecurityClient("scenario14", serviceName, nameSpace, soapAction, operation, "s");
    System.out.println(result);

    String csvExpectedResult = "Boston";
    String output =
        result
            .getFirstElement()
            .getAttributeValue(new QName("http://ws.wso2.org/dataservice", "address"));
    assertEquals(csvExpectedResult, output);

    Thread.sleep(1000);
    instServiceManagement.disableSecurity(serviceName);
  }
  private SOAPEnvelope buildSoapEnvelope(String clientID, String value) {

    String targetEPR = "http://localhost:9000/soap/Service1";
    String opration = "sampleOperation";

    SOAPFactory soapFactory = OMAbstractFactory.getSOAP12Factory();

    OMNamespace wsaNamespace =
        soapFactory.createOMNamespace("http://www.w3.org/2005/08/addressing", "wsa");

    SOAPEnvelope envelope = soapFactory.createSOAPEnvelope();

    SOAPHeader header = soapFactory.createSOAPHeader();
    envelope.addChild(header);

    OMNamespace synNamespace =
        soapFactory.createOMNamespace("http://ws.apache.org/ns/synapse", "syn");
    OMElement clientIDElement = soapFactory.createOMElement("ClientID", synNamespace);
    clientIDElement.setText(clientID);
    header.addChild(clientIDElement);

    SOAPBody body = soapFactory.createSOAPBody();
    envelope.addChild(body);

    OMElement valueElement = soapFactory.createOMElement("Value", null);
    valueElement.setText(value);
    body.addChild(valueElement);

    return envelope;
  }
Exemple #14
0
  /**
   * Make sure that the endpoints created by the factory has a name
   *
   * @param epConfig OMElement containing the endpoint configuration.
   * @param anonymousEndpoint false if the endpoint has a name. true otherwise.
   * @param properties bag of properties to pass in any information to the factory
   * @return Endpoint implementation for the given configuration.
   */
  private Endpoint createEndpointWithName(
      OMElement epConfig, boolean anonymousEndpoint, Properties properties) {

    Endpoint ep = createEndpoint(epConfig, anonymousEndpoint, properties);
    OMElement descriptionElem = epConfig.getFirstChildWithName(DESCRIPTION_Q);
    if (descriptionElem != null) {
      ep.setDescription(descriptionElem.getText());
    }

    // if the endpoint doesn't have a name we will generate a unique name.
    if (anonymousEndpoint && ep.getName() == null) {
      String uuid = UIDGenerator.generateUID();
      uuid = uuid.replace(':', '_');
      ep.setName(ENDPOINT_NAME_PREFIX + uuid);
      if (ep instanceof AbstractEndpoint) {
        ((AbstractEndpoint) ep).setAnonymous(true);
      }
    }

    OMAttribute onFaultAtt = epConfig.getAttribute(ON_FAULT_Q);
    if (onFaultAtt != null) {
      ep.setErrorHandler(onFaultAtt.getAttributeValue());
    }
    return ep;
  }
Exemple #15
0
  /**
   * @param m
   * @param backendRegistry
   * @throws XdsException
   */
  private void updateFolderContentsOnDocumentReplace(Metadata m, BackendRegistry backendRegistry)
      throws XdsException {
    // If this submission includes a DocumentEntry replace and the original DocumentEntry is in a
    // folder
    // then the replacement document must be put into the folder as well.  This must happen here
    // so the following logic to update folder lastUpdateTime can be triggered.

    HashMap<String, String> rplcToOrigIds = new HashMap<String, String>();
    for (OMElement assoc : m.getAssociations()) {
      if (MetadataSupport.xdsB_ihe_assoc_type_rplc.equals(m.getAssocType(assoc))) {
        rplcToOrigIds.put(m.getAssocSource(assoc), m.getAssocTarget(assoc));
      }
    }
    for (String replacementDocumentId : rplcToOrigIds.keySet()) {
      String originalDocumentId = rplcToOrigIds.get(replacementDocumentId);
      // for each original document, find the collection of folders it belongs to
      Metadata me = this.findFoldersForDocumentByUuid(originalDocumentId, backendRegistry);
      List<String> folderIds = me.getObjectIds(me.getObjectRefs());
      // for each folder, add an association placing replacment in that folder
      // This brings up interesting question, should the Assoc between SS and Assoc be generated
      // also?  YES!
      for (String fid : folderIds) {
        OMElement assoc =
            m.addAssociation(
                m.makeAssociation(
                    MetadataSupport.xdsB_eb_assoc_type_has_member, fid, replacementDocumentId));
        OMElement assoc2 =
            m.addAssociation(
                m.makeAssociation(
                    MetadataSupport.xdsB_eb_assoc_type_has_member,
                    m.getSubmissionSetId(),
                    assoc.getAttributeValue(MetadataSupport.id_qname)));
      }
    }
  }
  public ReportParameters[] getReportParam(String reportName)
      throws ReportingException, XMLStreamException {

    String reportContent = getReportResources(null, reportName);
    List<ReportParameters> parameterList = new ArrayList<ReportParameters>();
    ReportParameters[] parametersArray;
    if (reportContent != null) {
      OMElement reportTemplateOmElement = OMElementHandler.createOMElement(reportContent);
      if (reportTemplateOmElement != null) {
        Iterator iterator = reportTemplateOmElement.getChildrenWithName(new QName("parameter"));
        if (iterator != null) {

          while (iterator.hasNext()) {
            ReportParameters parameter = new ReportParameters();
            OMElement omElement = (OMElement) iterator.next();
            String paramName = omElement.getAttribute(new QName("name")).getAttributeValue();
            parameter.setParamName(paramName);
            String paramValue = omElement.getAttribute(new QName("class")).getAttributeValue();
            parameter.setParamValue(paramValue);
            parameterList.add(parameter);
          }
        }
      }
      parametersArray = parameterList.toArray(new ReportParameters[parameterList.size()]);

    } else {
      log.error("Did not find a report called " + reportName);
      return null;
    }
    return parametersArray;
  }
 protected void deserialize(OMElement documentElement) {
   String fragmentHostAttribute = getAttribute(documentElement, "fragment-host");
   setFragmentHost(fragmentHostAttribute);
   List<OMElement> childElements = getChildElements(documentElement, "jar");
   for (OMElement element : childElements) {
     String jarName = getAttribute(element, "name");
     List<String> packages = new ArrayList<String>();
     List<OMElement> exportPackagesElements = getChildElements(element, "export-packages");
     for (OMElement exportPackages : exportPackagesElements) {
       List<OMElement> exportPackageElements = getChildElements(exportPackages, "export-package");
       for (OMElement packageElement : exportPackageElements) {
         packages.add(packageElement.getText());
       }
     }
     getExportedPackageListsFromJar().put(jarName, packages);
   }
   childElements = getChildElements(documentElement, "project");
   for (OMElement element : childElements) {
     String projectName = getAttribute(element, "name");
     List<String> packages = new ArrayList<String>();
     List<OMElement> exportPackagesElements = getChildElements(element, "export-packages");
     for (OMElement exportPackages : exportPackagesElements) {
       List<OMElement> exportPackageElements = getChildElements(exportPackages, "export-package");
       for (OMElement packageElement : exportPackageElements) {
         packages.add(packageElement.getText());
       }
     }
     IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
     if (project != null) {
       getExportedPackageListsFromProject().put(project, packages);
     }
   }
 }
 @Test
 public void testGsonXMLStreamReaderWithDataTypes() throws Exception {
   String jsonString =
       "{\"response\":{\"return\":{\"name\":\"kate\",\"homes\":1,\"age\":23,\"height\":5.5,"
           + "\"image\":\"iVBORw0KGg\"}}}";
   String xmlString =
       "<response xmlns=\"http://www.w3schools.com\"><return><name>kate</name><homes>1</homes>"
           + "<age>23</age><height>5.5</height><image>iVBORw0KGg</image></return></response>";
   InputStream inputStream = new ByteArrayInputStream(jsonString.getBytes());
   JsonReader jsonReader = new JsonReader(new InputStreamReader(inputStream, "UTF-8"));
   String fileName = "test-resources/custom_schema/testSchema_3.xsd";
   InputStream is = new FileInputStream(fileName);
   XmlSchemaCollection schemaCol = new XmlSchemaCollection();
   XmlSchema schema = schemaCol.read(new StreamSource(is), null);
   List<XmlSchema> schemaList = new ArrayList<XmlSchema>();
   schemaList.add(schema);
   QName elementQName = new QName("http://www.w3schools.com", "response");
   ConfigurationContext configCtxt = new ConfigurationContext(new AxisConfiguration());
   GsonXMLStreamReader gsonXMLStreamReader = new GsonXMLStreamReader(jsonReader);
   gsonXMLStreamReader.initXmlStreamReader(elementQName, schemaList, configCtxt);
   StAXOMBuilder stAXOMBuilder = new StAXOMBuilder(gsonXMLStreamReader);
   OMElement omElement = stAXOMBuilder.getDocumentElement();
   String actual = omElement.toString();
   inputStream.close();
   is.close();
   Assert.assertEquals(xmlString, actual);
 }
  public void createSoapBody(
      org.apache.axiom.soap.SOAPBody sb,
      SOAPBody soapBody,
      Message msgDef,
      Element message,
      String rpcWrapper)
      throws AxisFault {
    OMElement partHolder =
        isRPC
            ? soapFactory.createOMElement(
                new QName(soapBody.getNamespaceURI(), rpcWrapper, "odens"), sb)
            : sb;
    List<Part> parts = msgDef.getOrderedParts(soapBody.getParts());

    for (Part part : parts) {
      Element srcPartEl = DOMUtils.findChildByName(message, new QName(null, part.getName()));
      if (srcPartEl == null) {
        throw new AxisFault("Missing required part in ODE Message");
      }

      OMElement omPart = OMUtils.toOM(srcPartEl, soapFactory);
      if (isRPC) {
        partHolder.addChild(omPart);
      } else {
        for (Iterator<OMNode> i = omPart.getChildren(); i.hasNext(); ) {
          partHolder.addChild(i.next());
        }
      }
    }
  }
  @Test(groups = "wso2.esb", description = "Custom sequences and endpoints with proxy services")
  public void sample153Test() throws Exception {
    String policyPath =
        FrameworkPathUtil.getSystemResourceLocation()
            + "security"
            + File.separator
            + "policies"
            + File.separator
            + "scenario27-policy.xml";
    OMElement response =
        new SecureStockQuoteClient()
            .sendSecuredSimpleStockQuoteRequest(
                null, null, getProxyServiceURLHttp("StockQuoteProxy"), policyPath, "Secured");

    String lastPrice =
        response
            .getFirstElement()
            .getFirstChildWithName(new QName("http://services.samples/xsd", "last"))
            .getText();
    assertNotNull(lastPrice, "Fault: response message 'last' price null");

    String symbol =
        response
            .getFirstElement()
            .getFirstChildWithName(new QName("http://services.samples/xsd", "symbol"))
            .getText();
    assertEquals(symbol, "Secured", "Fault: value 'symbol' mismatched");
  }
  public void parse(OMElement paramsTag) {

    if (log.isDebugEnabled() || log.isTraceEnabled()) {
      log.debug("Parse params");
    }

    ValueFactory valueFactory = new ValueFactory();

    this.type = paramsTag.getLocalName();

    for (Iterator iterator = paramsTag.getChildElements(); iterator.hasNext(); ) {
      OMElement param = (OMElement) iterator.next();

      if (AuditMediatorUtils.isTag(param, AuditMediatorUtils.PARAM_TAG_NAME)) {

        String name = param.getAttributeValue(AuditMediatorUtils.NAME_ATT_QNAME);

        Value value = valueFactory.createValue(AuditMediatorUtils.VALUE_ATT_NAME, param);

        if (StringUtils.isBlank(name) || value == null) {
          log.error("Error, attributes name and value required");
          break;
        }

        params.add(new Param(name, value));

      } else {
        log.error(
            "Unable to create the Audit mediator. "
                + "Unexpected element: "
                + param
                + " inside the Params TAG of Audit mediator configuration");
      }
    }
  }
Exemple #22
0
  private void loadMaxInstanceLimit(IaasProvider iaas, final OMElement iaasElt) {

    Iterator<?> it =
        iaasElt.getChildrenWithName(new QName(CloudControllerConstants.MAX_INSTANCE_LIMIT_ELEMENT));

    if (it.hasNext()) {
      OMElement maxInstanceLimitElt = (OMElement) it.next();

      try {
        iaas.setMaxInstanceLimit(Integer.parseInt(maxInstanceLimitElt.getText()));
      } catch (NumberFormatException e) {
        String msg =
            CloudControllerConstants.MAX_INSTANCE_LIMIT_ELEMENT
                + " element contained"
                + " in "
                + xmlSource
                + ""
                + " has a value which is not an Integer value.";
        handleException(msg, e);
      }
    }

    if (it.hasNext()) {
      log.warn(
          xmlSource
              + " contains more than one "
              + CloudControllerConstants.MAX_INSTANCE_LIMIT_ELEMENT
              + " elements!"
              + " Elements other than the first will be neglected.");
    }
  }
  private java.lang.Object fromOM(
      final org.apache.axiom.om.OMElement param,
      final java.lang.Class<?> type,
      final java.util.Map<String, String> extraNamespaces)
      throws org.apache.axis2.AxisFault {
    try {

      if (CadConsultaCadastro2Stub.NfeDadosMsg.class.equals(type)) {
        return CadConsultaCadastro2Stub.NfeDadosMsg.Factory.parse(
            param.getXMLStreamReaderWithoutCaching());
      }

      if (CadConsultaCadastro2Stub.ConsultaCadastro2Result.class.equals(type)) {
        return CadConsultaCadastro2Stub.ConsultaCadastro2Result.Factory.parse(
            param.getXMLStreamReaderWithoutCaching());
      }

      if (CadConsultaCadastro2Stub.NfeCabecMsgE.class.equals(type)) {
        return CadConsultaCadastro2Stub.NfeCabecMsgE.Factory.parse(
            param.getXMLStreamReaderWithoutCaching());
      }

      if (CadConsultaCadastro2Stub.NfeCabecMsgE.class.equals(type)) {
        return CadConsultaCadastro2Stub.NfeCabecMsgE.Factory.parse(
            param.getXMLStreamReaderWithoutCaching());
      }

    } catch (final java.lang.Exception e) {
      throw org.apache.axis2.AxisFault.makeFault(e);
    }
    return null;
  }
Exemple #24
0
  private void loadProvider(final IaasProvider iaas, final OMElement iaasElt) {

    Iterator<?> it =
        iaasElt.getChildrenWithName(new QName(CloudControllerConstants.PROVIDER_ELEMENT));

    if (it.hasNext()) {
      OMElement providerElt = (OMElement) it.next();
      iaas.setProvider(providerElt.getText());
    }

    if (it.hasNext()) {
      log.warn(
          xmlSource
              + " contains more than one "
              + CloudControllerConstants.PROVIDER_ELEMENT
              + " elements!"
              + " Elements other than the first will be neglected.");
    }

    if (iaas.getProvider() == null) {
      String msg =
          "Essential '"
              + CloudControllerConstants.PROVIDER_ELEMENT
              + "' element "
              + "has not specified in "
              + xmlSource;
      handleException(msg);
    }
  }
 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 handleSLORequest(MessageContext messageContext, LogoutRequest logoutRequest) {

    // Get the session index from the SLORequest and remove the relevant session.
    String sessionIndex = logoutRequest.getSessionIndexes().get(0).getSessionIndex();

    String sessionId = CacheManager.getInstance().getSessionIndexMappingCache().get(sessionIndex);

    if (sessionId != null) {
      GatewayUtils.logWithRequestInfo(
          log,
          messageContext,
          String.format(
              "Found a session id (md5 : '%s')for the given session index in the SLO request: '%s'. Clearing the session",
              GatewayUtils.getMD5Hash(sessionId), sessionIndex));
      SessionStore.getInstance().removeSession(sessionId);
      CacheManager.getInstance().getSessionIndexMappingCache().remove(sessionIndex);
    } else {
      GatewayUtils.logWithRequestInfo(
          log,
          messageContext,
          String.format(
              "Couldn't find a session id for the given session index : '%s'", sessionIndex));
    }

    OMFactory fac = OMAbstractFactory.getOMFactory();
    OMNamespace ns = fac.createOMNamespace("http://wso2.org/appm", "appm");
    OMElement payload = fac.createOMElement("SLOResponse", ns);

    OMElement errorMessage = fac.createOMElement("message", ns);
    errorMessage.setText("SLORequest has been successfully processed by WSO2 App Manager");

    payload.addChild(errorMessage);

    return payload;
  }
  public static OutputMapping fromOM(OMElement mappingElement)
      throws EventFormatterValidationException, EventFormatterConfigurationException {

    MapOutputMapping mapOutputMapping = new MapOutputMapping();

    String customMappingEnabled =
        mappingElement.getAttributeValue(new QName(EventFormatterConstants.EF_ATTR_CUSTOM_MAPPING));
    if (customMappingEnabled == null
        || (customMappingEnabled.equals(EventFormatterConstants.TM_VALUE_ENABLE))) {
      mapOutputMapping.setCustomMappingEnabled(true);
      if (!validateMapEventMapping(mappingElement)) {
        throw new EventFormatterConfigurationException(
            "Map Mapping is not valid, check the output mapping");
      }

      if (mappingElement != null) {
        Iterator propertyIterator =
            mappingElement.getChildrenWithName(
                new QName(
                    EventFormatterConstants.EF_CONF_NS, EventFormatterConstants.EF_ELE_PROPERTY));
        while (propertyIterator.hasNext()) {
          OMElement propertyOMElement = (OMElement) propertyIterator.next();
          EventOutputProperty eventOutputProperty = getOutputPropertyFromOM(propertyOMElement);
          mapOutputMapping.addOutputPropertyConfiguration(eventOutputProperty);
        }
      }
    } else {
      mapOutputMapping.setCustomMappingEnabled(false);
    }

    return mapOutputMapping;
  }
  /**
   * Modify request body before sending to the end point.
   *
   * @param messageContext MessageContext - The message context.
   * @throws ConnectException if connection is failed.
   */
  @SuppressWarnings("unchecked")
  public void connect(MessageContext messageContext) throws ConnectException {

    SOAPEnvelope envelope = messageContext.getEnvelope();
    SOAPBody body = envelope.getBody();
    Iterator<OMElement> nameValueListElements = body.getChildrenWithLocalName(SEARCH_BY_MODULE_TAG);

    try {

      OMElement nameValueListElement = nameValueListElements.next();
      Iterator<OMElement> omElementIterator =
          nameValueListElement.getChildrenWithLocalName(MODULES_TAG);

      if (omElementIterator.hasNext()) {
        OMFactory omFactory = OMAbstractFactory.getOMFactory();
        OMElement item = omElementIterator.next();
        String moduleListString =
            (String) ConnectorUtils.lookupTemplateParamater(messageContext, MODULES_TAG);
        SugarCRMUtil.getItemElement(omFactory, messageContext, item, moduleListString);
      }

    } catch (Exception e) {
      log.error(SugarCRMUtil.EXCEPTION + SugarCRMUtil.getStackTraceAsString(e));
      throw new ConnectException(e);
    }
  }
Exemple #29
0
  private void processMessages(Iterator messages, AxisOperation operation)
      throws DeploymentException {
    while (messages.hasNext()) {
      OMElement messageElement = (OMElement) messages.next();
      OMAttribute label = messageElement.getAttribute(new QName(TAG_LABEL));

      if (label == null) {
        throw new DeploymentException(Messages.getMessage("messagelabelcannotfound"));
      }

      AxisMessage message = operation.getMessage(label.getAttributeValue());

      Iterator parameters = messageElement.getChildrenWithName(new QName(TAG_PARAMETER));

      // processing <wsp:Policy> .. </..> elements
      Iterator policyElements =
          messageElement.getChildrenWithName(new QName(POLICY_NS_URI, TAG_POLICY));

      if (policyElements != null) {
        processPolicyElements(policyElements, message.getPolicySubject());
      }

      // processing <wsp:PolicyReference> .. </..> elements
      Iterator policyRefElements =
          messageElement.getChildrenWithName(new QName(POLICY_NS_URI, TAG_POLICY_REF));

      if (policyRefElements != null) {
        processPolicyRefElements(policyRefElements, message.getPolicySubject());
      }

      processParameters(parameters, message, operation);
    }
  }
 private int getTenantId(MessageContext messageContext) {
   PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
   int tenantId = carbonContext.getTenantId();
   if (tenantId > -1 || tenantId == MultitenantConstants.SUPER_TENANT_ID) {
     return tenantId;
   }
   String domain = carbonContext.getTenantDomain();
   if (domain == null) {
     SOAPBody soapBody = messageContext.getEnvelope().getBody();
     if (soapBody != null && soapBody.getFirstElement() != null) {
       OMElement usernameElem =
           soapBody
               .getFirstElement()
               .getFirstChildWithName(
                   new QName(
                       ServerConstants.AUTHENTICATION_SERVICE_NS,
                       ServerConstants.AUTHENTICATION_SERVICE_USERNAME));
       if (usernameElem != null) {
         String userName = usernameElem.getText();
         domain = MultitenantUtils.getTenantDomain(userName);
       }
     }
   }
   if (domain != null) {
     try {
       tenantId = Util.getRealmService().getTenantManager().getTenantId(domain);
     } catch (org.wso2.carbon.user.api.UserStoreException e) {
       log.error("An error occurred while obtaining the tenant id.", e);
     }
   }
   return tenantId;
 }