Java Code Examples for org.apache.axiom.om.OMElement#getAttribute()

The following examples show how to use org.apache.axiom.om.OMElement#getAttribute() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: XMLComparator.java    From product-ei with Apache License 2.0 6 votes vote down vote up
private static boolean compareAttributes(OMElement elementOne, OMElement elementTwo) {
    int elementOneAttribCount = 0;
    int elementTwoAttribCount = 0;
    Iterator attributes = elementOne.getAllAttributes();
    while (attributes.hasNext()) {
        OMAttribute omAttribute = (OMAttribute) attributes.next();
        OMAttribute attr = elementTwo.getAttribute(omAttribute.getQName());
        if (attr == null) {
            return false;
        }
        elementOneAttribCount++;
    }

    Iterator elementTwoIter = elementTwo.getAllAttributes();
    while (elementTwoIter.hasNext()) {
        elementTwoIter.next();
        elementTwoAttribCount++;

    }

    return elementOneAttribCount == elementTwoAttribCount;
}
 
Example 2
Source File: APIGatewayManager.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
private void addSequence(API api, int tenantId, GatewayAPIDTO gatewayAPIDTO, String sequenceType,
                         String sequenceExtension,String sequenceName) throws APIManagementException, XMLStreamException {

    OMElement inSequence = APIUtil.getCustomSequence(sequenceName, tenantId, sequenceType, api.getId());

    if (inSequence != null) {
        String inSeqExt = APIUtil.getSequenceExtensionName(api) + sequenceExtension;
        if (inSequence.getAttribute(new QName("name")) != null) {
            inSequence.getAttribute(new QName("name")).setAttributeValue(inSeqExt);
        }
        GatewayContentDTO sequenceDto = new GatewayContentDTO();
        sequenceDto.setName(inSeqExt);
        sequenceDto.setContent(APIUtil.convertOMtoString(inSequence));
        gatewayAPIDTO.setSequenceToBeAdd(addGatewayContentToList(sequenceDto, gatewayAPIDTO.getSequenceToBeAdd()));
    }

}
 
Example 3
Source File: XdsTest.java    From openxds with Apache License 2.0 5 votes vote down vote up
/**
 * Submit one document to support ProvideAndRegisterDocumentSet-b (ITI-41)
 * 
 * @return XDSDocumentEntry.uuid
 * @throws  
 * @throws Exception 
 */
protected String submitOneDocument(String patientId) throws Exception {		
	String message = IOUtils.toString( ProvideAndRegisterDocumentSetTest.class.getResourceAsStream("/data/submit_document.xml"));
	String document = IOUtils.toString(ProvideAndRegisterDocumentSetTest.class.getResourceAsStream("/data/referral_summary.xml"));
	//replace document and submission set uniqueId variables with actual uniqueIds. 
	message = message.replace("$XDSDocumentEntry.uniqueId", "2.16.840.1.113883.3.65.2." + System.currentTimeMillis());
	message = message.replace("$XDSSubmissionSet.uniqueId", "1.3.6.1.4.1.21367.2009.1.2.108." + System.currentTimeMillis());
	//replace the document uuid.
	String uuid = "urn:uuid:" + UUID.randomUUID().toString();
	message = message.replace("$doc1", uuid);
	//replace the patient id
	if (patientId != null) 
		message = message.replace("$patientId", patientId);

	
	ServiceClient sender = getRepositoryServiceClient();			
	
	OMElement request = OMUtil.xmlStringToOM(message);			
	
	//Add a document
	request = addOneDocument(request, document, uuid);
       
	System.out.println("Request:\n" +request);

	OMElement response = sender.sendReceive( request );
	assertNotNull(response); 

	OMAttribute status = response.getAttribute(new QName("status"));
	assertEquals("urn:oasis:names:tc:ebxml-regrep:ResponseStatusType:Success", status.getAttributeValue());

	String result = response.toString();
	System.out.println("Result:\n" +result);
	
	return uuid;
}
 
Example 4
Source File: RegistrytStoredQueryTest.java    From openxds with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetDocumentsAndAssociations() throws Exception {
	//1. Submit a document first for a random patientId
	String patientId = generateAPatientId();
	String uuid = submitOneDocument(patientId);
	
	//2. Generate StoredQuery request message
	String message = GetDocumentsQuery(uuid, false,"urn:uuid:bab9529a-4a10-40b3-a01f-f68a615d247a");
	OMElement request = OMUtil.xmlStringToOM(message);			
	System.out.println("Request:\n" +request);

	//3. Send a StoredQuery
	ServiceClient sender = getRegistryServiceClient();															 
	OMElement response = sender.sendReceive( request );
	assertNotNull(response); 

	//4. Verify the response is correct
	OMAttribute status = response.getAttribute(new QName("status"));
	assertEquals("urn:oasis:names:tc:ebxml-regrep:ResponseStatusType:Success", status.getAttributeValue()); 
	
	//5. Verify that the given PatientId is found from the StoredQuery response. 
	NodeList nodes = getPatientIdNodes(response, patientId, "getDocuments");
	assertTrue(nodes.getLength() == 1); 
	
	//6. Verify that the Association object found from the StoredQuery response. 
	NodeList nodes1 = getPatientIdNodes(response, patientId, "getAssociations");
	assertTrue(nodes1.getLength() == 1); 

	String result = response.toString();
	System.out.println("Result:\n" +result);
}
 
Example 5
Source File: AuthenticationMethodNameTranslatorImpl.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private void processAmrEntry(OMElement amrEntryElement, Map<String, Set<String>> amrInternalToExternalMap,
        Map<String, String> amrExternalToInternalMap) {

    String uri = amrEntryElement.getAttributeValue(URI_ATTR_QNAME);
    String method = amrEntryElement.getAttributeValue(METHOD_ATTR_QNAME);
    if (amrEntryElement.getAttribute(NIL_QNAME) == null) {
        Set<String> externalMappings = amrInternalToExternalMap.get(method);
        if (externalMappings == null) {
            externalMappings = new HashSet<>();
            amrInternalToExternalMap.put(method, externalMappings);
        }
        externalMappings.add(uri);
    }
    amrExternalToInternalMap.put(uri, method);
}
 
Example 6
Source File: RegistrytStoredQueryTest.java    From openxds with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAssociations() throws Exception {
	//1. Submit a document first for a random patientId
	String patientId = generateAPatientId();
	String uuid = submitOneDocument(patientId);
	
	//2. Generate StoredQuery request message
	String message = GetAssociationsQuery(uuid);
	OMElement request = OMUtil.xmlStringToOM(message);			
	System.out.println("Request:\n" +request);

	//3. Send a StoredQuery
	ServiceClient sender = getRegistryServiceClient();															 
	OMElement response = sender.sendReceive( request );
	assertNotNull(response); 

	//4. Verify the response is correct
	OMAttribute status = response.getAttribute(new QName("status"));
	assertEquals("urn:oasis:names:tc:ebxml-regrep:ResponseStatusType:Success", status.getAttributeValue()); 
	
	//5. Verify that the Association object found from the StoredQuery response. 
	NodeList nodes = getPatientIdNodes(response, patientId, "getAssociations");
	assertTrue(nodes.getLength() == 1); 

	String result = response.toString();
	System.out.println("Result:\n" +result);
}
 
Example 7
Source File: CrossGatewayQueryTest.java    From openxds with Apache License 2.0 5 votes vote down vote up
/**
 * Tis test initiate a GetDocuments Cross-Gateway Query (XGQ) to the XDS
 * Registry server's Responding Gateway for documents discovered in
 * test 12306. Request LeafClass be returned.
 * @throws Exception
 */
@Test
public void testGetDocuments() throws Exception {
	//1. Submit a document first for a random patientId
	String patientId = generateAPatientId();
	String uuids = submitMultipleDocuments(patientId);
	
	//2. Generate StoredQuery request message
	String message = GetDocumentsQuery(uuids, false, homeProperty);
	OMElement request = OMUtil.xmlStringToOM(message);			
	System.out.println("Request:\n" +request);

	//3. Send a StoredQuery
	ServiceClient sender = getRegistryGateWayClient();															 
	OMElement response = sender.sendReceive( request );
	assertNotNull(response); 

	//4. Verify the response is correct
	OMAttribute status = response.getAttribute(new QName("status"));
	assertEquals("urn:oasis:names:tc:ebxml-regrep:ResponseStatusType:Success", status.getAttributeValue()); 
	
	//5. Verify that the 2 Documents found from the StoredQuery response. 
	NodeList count = getNodeCount(response, "ExtrinsicObject");
	assertTrue(count.getLength() == 2); 
	
	String result = response.toString();
	System.out.println("Result:\n" +result);
}
 
Example 8
Source File: Name.java    From openxds with Apache License 2.0 5 votes vote down vote up
void parse() throws MetadataException {
	((RegistryItem)this).parse();
	OMElement loc = MetadataSupport.firstChildWithLocalName(get(), "LocalizedString");
	if (loc == null)
		throw new MetadataException("Name.java: Name element does not have a 'LocalizedString' sub-element");
	this.name_att = loc.getAttribute(MetadataSupport.value_qname);
}
 
Example 9
Source File: FileBasedConfigurationBuilder.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private void readAuthenticationEndpointRedirectParams(OMElement documentElement) {

        OMElement authEndpointRedirectParamsElem = documentElement.getFirstChildWithName(
                IdentityApplicationManagementUtil.getQNameWithIdentityApplicationNS(
                        FrameworkConstants.Config.QNAME_AUTH_ENDPOINT_REDIRECT_PARAMS));

        if (authEndpointRedirectParamsElem != null) {

            authEndpointRedirectParamsConfigAvailable = true;
            OMAttribute actionAttr = authEndpointRedirectParamsElem.getAttribute(new QName(
                    FrameworkConstants.Config.ATTR_AUTH_ENDPOINT_QUERY_PARAM_ACTION));
            OMAttribute removeOnConsumeAttr = authEndpointRedirectParamsElem.getAttribute(new QName(
                    FrameworkConstants.Config.REMOVE_PARAM_ON_CONSUME));
            authEndpointRedirectParamsAction = FrameworkConstants.AUTH_ENDPOINT_QUERY_PARAMS_ACTION_EXCLUDE;

            if (actionAttr != null) {
                String actionValue = actionAttr.getAttributeValue();

                if (actionValue != null && !actionValue.isEmpty()) {
                    authEndpointRedirectParamsAction = actionValue;
                }
            }

            if (removeOnConsumeAttr != null) {
                removeAPIParametersOnConsume = Boolean.parseBoolean(removeOnConsumeAttr.getAttributeValue());
            }

            for (Iterator authEndpointRedirectParamElems = authEndpointRedirectParamsElem
                    .getChildrenWithLocalName(FrameworkConstants.Config.ELEM_AUTH_ENDPOINT_REDIRECT_PARAM);
                 authEndpointRedirectParamElems.hasNext(); ) {
                String redirectParamName = processAuthEndpointQueryParamElem((OMElement) authEndpointRedirectParamElems
                        .next());

                if (redirectParamName != null) {
                    this.authEndpointRedirectParams.add(redirectParamName);
                }
            }
        }
    }
 
Example 10
Source File: CrossGatewayQueryTest.java    From openxds with Apache License 2.0 5 votes vote down vote up
/**
 * This test issues a FindDocuments Cross Gateway Query (XGQ)
 *  to the XDS Registry's Receiving Gateway requesting ObjectRefs (document references) be returned. 
 * @throws Exception
 */
@Test
public void testFindDocsObjectRef() throws Exception {
	//1. Submit a document first for a random patientId
	String patientId = generateAPatientId();
	String uuids = submitMultipleDocuments(patientId);
	
	//2. Generate StoredQuery request message
	String message = findDocumentsQuery(patientId, "Approved", "ObjectRef");
	OMElement request = OMUtil.xmlStringToOM(message);			
	System.out.println("Request:\n" +request);

	//3. Send a StoredQuery
	ServiceClient sender = getRegistryGateWayClient();															 
	OMElement response = sender.sendReceive( request );
	assertNotNull(response); 
	
	//4. Verify the response is correct
	OMAttribute status = response.getAttribute(new QName("status"));
	assertEquals("urn:oasis:names:tc:ebxml-regrep:ResponseStatusType:Success", status.getAttributeValue()); 
	
	//5. Verify that the 2 ObjectRefs found from the StoredQuery response. 
	NodeList count = getNodeCount(response, "ObjectRef");
	assertTrue(count.getLength() == 2); 
	
	String result = response.toString();
	System.out.println("Result:\n" +result);
}
 
Example 11
Source File: FileBasedConfigurationBuilder.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private void processAuthenticatorNameMappingElement(OMElement authenticatorNameMappingElem) {

        OMAttribute nameAttr = authenticatorNameMappingElem.getAttribute(new QName(FrameworkConstants.Config.ATTR_AUTHENTICATOR_NAME_MAPPING_NAME));
        OMAttribute aliasAttr = authenticatorNameMappingElem.getAttribute(new QName(FrameworkConstants.Config.ATTR_AUTHENTICATOR_NAME_MAPPING_ALIAS));

        if (nameAttr == null || aliasAttr == null) {
            log.warn("An AuthenticatorNameMapping must contain \'name\' and \'alias\' attributes. Skipping the element.");
            return;
        }

        authenticatorNameMappings.put(aliasAttr.getAttributeValue(), nameAttr.getAttributeValue());
    }
 
Example 12
Source File: DBDeployer.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * This method checks if the given data service has a corresponding "services.xml" is available,
 * if so, the AxisService representing the data service is applied the instructions from its
 * "services.xml".
 */
private AxisService handleTransports(DeploymentFileData file, AxisService axisService) throws DataServiceFault {
	try (FileInputStream fis = new FileInputStream(file.getFile().getAbsoluteFile())) {
		StAXOMBuilder builder = new StAXOMBuilder(fis);
           OMElement documentElement =  builder.getDocumentElement();
           OMAttribute transports = documentElement.getAttribute(new QName(DBSFields.TRANSPORTS));
           if (transports != null) {
               String [] transportArr = transports.getAttributeValue().split(" ");
               axisService.setExposedTransports(Arrays.asList(transportArr));
           }
	} catch (Exception e) {
		throw new DataServiceFault(e, "Error in processing transports info");
	}
	return axisService;
}
 
Example 13
Source File: FileBasedConfigurationBuilder.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private String processAuthEndpointQueryParamElem(OMElement authEndpointQueryParamElem) {

        OMAttribute nameAttr = authEndpointQueryParamElem.getAttribute(new QName(
                FrameworkConstants.Config.ATTR_AUTH_ENDPOINT_QUERY_PARAM_NAME));

        if (nameAttr == null) {
            log.warn("Each Authentication Endpoint Query Param should have a unique name attribute. This Query Param will skipped.");
            return null;
        }

        return nameAttr.getAttributeValue();
    }
 
Example 14
Source File: CrossGatewayQueryTest.java    From openxds with Apache License 2.0 5 votes vote down vote up
/**
 * This test initiate a FindDocuments Cross-Gateway Query (XGQ) to the XDS
 * 	Registry server's Responding Gateway for a pre-determined Patient ID.
 * 	Request ObjectRefs be returned.
 * @throws Exception
 */
@Test
public void testFindDocusMulObjectRefs() throws Exception {
	//1. Submit a document first for a random patientId
	String patientId = generateAPatientId();
	String uuids = submitMultipleDocuments(patientId);
	
	//2. Generate StoredQuery request message
	String message = findDocumentsQuery(patientId, "Approved", "ObjectRef");
	OMElement request = OMUtil.xmlStringToOM(message);			
	System.out.println("Request:\n" +request);

	//3. Send a StoredQuery
	ServiceClient sender = getRegistryGateWayClient();															 
	OMElement response = sender.sendReceive( request );
	assertNotNull(response); 

	//4. Verify the response is correct
	OMAttribute status = response.getAttribute(new QName("status"));
	assertEquals("urn:oasis:names:tc:ebxml-regrep:ResponseStatusType:Success", status.getAttributeValue()); 
	
	//5. Verify that the 2 Documents found from the StoredQuery response. 
	NodeList count = getNodeCount(response, "ObjectRef");
	assertTrue(count.getLength() == 2); 

	String result = response.toString();
	System.out.println("Result:\n" +result);
}
 
Example 15
Source File: RegistrytStoredQueryTest.java    From openxds with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetSubmissionSets() throws Exception {
	//1. Submit a document first for a random patientId
	String patientId = generateAPatientId();
	String uuid = submitOneDocument(patientId);
	
	//2. Generate StoredQuery request message
	String message = GetSubmissionSetsQuery(uuid);
	OMElement request = OMUtil.xmlStringToOM(message);			
	System.out.println("Request:\n" +request);

	//3. Send a StoredQuery
	ServiceClient sender = getRegistryServiceClient();															 
	OMElement response = sender.sendReceive( request );
	assertNotNull(response); 

	//4. Verify the response is correct
	OMAttribute status = response.getAttribute(new QName("status"));
	assertEquals("urn:oasis:names:tc:ebxml-regrep:ResponseStatusType:Success", status.getAttributeValue()); 
	
	//5. Verify that the given PatientId is found from the StoredQuery response. 
	NodeList nodes = getPatientIdNodes(response, patientId, "getSubmissionSets");
	assertTrue(nodes.getLength() == 1); 

	String result = response.toString();
	System.out.println("Result:\n" +result);
}
 
Example 16
Source File: DataServiceCallMediatorFactory.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
private List<Param> extractParams(OMElement elem, DataServiceCallMediator mediator) {
    List<Param> paramList = new ArrayList<>();
    if (elem != null) {
        Iterator paramsIterator = elem.getChildrenWithName(new QName(DataServiceCallMediatorConstants.PARAM));
        while (paramsIterator.hasNext()) {
            OMElement paramElement = (OMElement) paramsIterator.next();
            OMAttribute nameAtr = paramElement.getAttribute(new QName(DataServiceCallMediatorConstants.NAME));

            if (nameAtr != null) {
                String paramName = nameAtr.getAttributeValue();
                String paramValue = paramElement.getAttributeValue(new QName(DataServiceCallMediatorConstants.VALUE));
                String paramType = paramElement.getAttributeValue(new QName(DataServiceCallMediatorConstants.TYPE));
                String evaluator = paramElement.getAttributeValue(new QName(DataServiceCallMediatorConstants.
                        EVALUATOR));
                String paramExpression = paramElement.getAttributeValue(new QName(DataServiceCallMediatorConstants.
                        EXPRESSION));
                Param param = mediator.new Param(paramName, paramType);
                param.setParamValue(paramValue);
                param.setEvaluator(evaluator);
                try {
                    if (paramExpression != null) {
                        if (evaluator != null && evaluator.equals(DataServiceCallMediatorConstants.JSON_TYPE)) {
                            if (paramExpression.startsWith("json-eval(")) {
                                paramExpression = paramExpression.substring(10, paramExpression.length() - 1);
                            }
                            param.setParamExpression(SynapseJsonPathFactory.getSynapseJsonPath(paramExpression));
                            // we have to explicitly define the path type since we are not going to mark
                            // JSON Path's with prefix "json-eval(".
                            param.getParamExpression().setPathType(SynapsePath.JSON_PATH);
                        } else {
                            SynapseXPath sxp = SynapseXPathFactory.getSynapseXPath(paramElement, ATT_EXPRN);
                            //we need to disable stream Xpath forcefully
                            sxp.setForceDisableStreamXpath(Boolean.TRUE);
                            param.setParamExpression(sxp);
                            param.getParamExpression().setPathType(SynapsePath.X_PATH);
                        }
                    }
                } catch (JaxenException e) {
                    handleException("Invalid XPath expression for attribute expression : " +
                            paramExpression, e);
                }
                paramList.add(param);
            }
        }
    }
    return paramList;
}
 
Example 17
Source File: DataServiceCallMediatorFactory.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
public Mediator createSpecificMediator(OMElement elem, Properties properties) {

        DataServiceCallMediator mediator = new DataServiceCallMediator();
        processAuditStatus(mediator, elem);
        String dsName = elem.getAttributeValue(new QName(DataServiceCallMediatorConstants.SERVICE_NAME));
        if (dsName == null) {
            handleException("The 'serviceName' attribute in 'dataServicesCall' element  is missing " +
                    "in the configuration.");
        }
        mediator.setDsName(dsName);
        OMElement operationsTypeElement = elem.getFirstElement();
        if (!operationsTypeElement.getLocalName().equals(DataServiceCallMediatorConstants.OPERATIONS)) {
            handleException("The 'operations' element in 'dataServicesCall' element  is missing in the configuration.");
        }
        String operationType = operationsTypeElement.getAttributeValue(new QName(DataServiceCallMediatorConstants.TYPE));
        if (operationType == null) {
            handleException("The 'type' attribute in 'operations' element  is missing in the configuration.");
        }
        OperationsType operationsType = OperationsType.valueOf(operationType.toUpperCase());
        List operationList = extractOperations(operationsTypeElement, mediator);
        if (OperationsType.SINGLE_REQ.equals(operationsType) && operationList.size() > 1) {
            handleException("The 'single operation' should contain one operation in the configuration.");
        }
        Operations operations = mediator.new Operations(operationsType, operationList);
        mediator.setOperations(operations);

        OMElement targetElement = elem.getFirstChildWithName(TARGET_Q);
        if (targetElement != null) {
            OMAttribute typeAtr = targetElement.getAttribute(TYPE_Q);
            if (typeAtr != null) {
                String type = typeAtr.getAttributeValue();
                mediator.setTargetType(type);
                if (type.equals(DataServiceCallMediatorConstants.PROPERTY)) {
                    OMAttribute propertyAtr = targetElement.getAttribute(NAME_Q);
                    if (propertyAtr != null) {
                        if (!propertyAtr.getAttributeValue().isEmpty()) {
                            String propertyName = propertyAtr.getAttributeValue();
                            mediator.setPropertyName(propertyName);
                        } else {
                            handleException("The 'name' attribute in 'target' element is empty. " +
                                    "Please enter a value.");
                        }
                    } else {
                        handleException("The 'name' attribute in 'target' element  is missing " +
                                "in the configuration.");
                    }
                }
            } else {
                handleException("The 'type' attribute in 'target' element is required for the configuration");
            }
        } else {
            handleException("The 'target' element is missing in the configuration.");
        }
        return mediator;
    }
 
Example 18
Source File: QueryFactory.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
private static Result getResultFromQueryElement(DataService dataService, OMElement queryEl)
           throws DataServiceFault {
	OMElement resEl = queryEl.getFirstChildWithName(new QName(DBSFields.RESULT));
	if (resEl == null) {
		return null;
	}

	// Checking data source case sensitivity mode
	OMAttribute datasourceIDAttribute = queryEl.getAttribute(new QName(DBSFields.USE_CONFIG));
	boolean isResultSetFieldsCaseSensitive;
	if (datasourceIDAttribute != null) {
		isResultSetFieldsCaseSensitive =
				dataService.getConfig(datasourceIDAttribute.getAttributeValue()).isResultSetFieldsCaseSensitive();
	} else {
		isResultSetFieldsCaseSensitive =
				dataService.getConfigs().values().iterator().next().isResultSetFieldsCaseSensitive();
	}

	String namespace = resEl.getAttributeValue(new QName(DBSFields.DEFAULT_NAMESPACE));
	if (namespace == null || namespace.trim().length() == 0) {
		namespace = dataService.getDefaultNamespace();
	}

       String xsltPath = resEl.getAttributeValue(new QName(DBSFields.XSLT_PATH));

       String outputType = resEl.getAttributeValue(new QName(DBSFields.OUTPUT_TYPE));
       int resultType = ResultTypes.XML;
       if (outputType == null || outputType.trim().length() == 0 || outputType.equals(
               DBSFields.RESULT_TYPE_XML)) {
           resultType = ResultTypes.XML;
       } else if (outputType.equals(DBSFields.RESULT_TYPE_RDF)) {
           resultType = ResultTypes.RDF;
       } else if (outputType.equals(DBSFields.RESULT_TYPE_JSON)) {
           resultType = ResultTypes.JSON;
       }

	Result result = new Result(xsltPath, resultType);

	boolean useColumnNumbers = false;
       String useColumnNumbersStr = resEl.getAttributeValue(new QName(DBSFields.USE_COLUMN_NUMBERS));
       if (!DBUtils.isEmptyString(useColumnNumbersStr)) {
       	useColumnNumbers = Boolean.parseBoolean(useColumnNumbersStr);
       }
       result.setUseColumnNumbers(useColumnNumbers);

       boolean escapeNonPrintableChar = false;
       String escapeNonPrintableCharStr = resEl.getAttributeValue(new QName(DBSFields.ESCAPE_NON_PRINTABLE_CHAR));
       if (!DBUtils.isEmptyString(escapeNonPrintableCharStr)) {
           escapeNonPrintableChar = Boolean.parseBoolean(escapeNonPrintableCharStr);
       }
       result.setEscapeNonPrintableChar(escapeNonPrintableChar);

	if (result.getResultType() == ResultTypes.XML) {
		populateXMLResult(result, dataService, resEl, namespace, isResultSetFieldsCaseSensitive);
	} else if (result.getResultType() == ResultTypes.RDF) {
		populateRDFResult(result, dataService, resEl, namespace, isResultSetFieldsCaseSensitive);
	} else if (result.getResultType() == ResultTypes.JSON) {
		populateJSONResult(result, dataService, resEl,
		                   calculateJSONXMLQueryNS(namespace, queryEl.getAttributeValue(new QName(DBSFields.ID))),
		                   isResultSetFieldsCaseSensitive);
	}

	return result;
}
 
Example 19
Source File: FileBasedConfigurationBuilder.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * Create StepDOs for each step entry
 *
 * @param stepElem
 * @return
 */
private StepConfig processStepElement(OMElement stepElem) {

    StepConfig stepConfig = new StepConfig();
    OMAttribute loginPageAttr = stepElem.getAttribute(new QName(FrameworkConstants.Config.ATTR_STEP_LOGIN_PAGE));

    if (loginPageAttr != null) {
        stepConfig.setLoginPage(loginPageAttr.getAttributeValue());
    }

    OMAttribute orderAttr = stepElem.getAttribute(new QName(FrameworkConstants.Config.ATTR_STEP_ORDER));

    if (orderAttr == null) {
        log.warn("Each Step Configuration should have an order. +"
                 + "Authenticators under this Step will not be registered.");
        return null;
    }

    stepConfig.setOrder(Integer.parseInt(orderAttr.getAttributeValue()));

    for (Iterator authenticatorElements = stepElem.getChildrenWithLocalName(FrameworkConstants.Config.ELEM_AUTHENTICATOR);
         authenticatorElements.hasNext(); ) {
        OMElement authenticatorElem = (OMElement) authenticatorElements.next();

        String authenticatorName = authenticatorElem.getAttributeValue(new QName(FrameworkConstants.Config.ATTR_AUTHENTICATOR_NAME));
        AuthenticatorConfig authenticatorConfig = authenticatorConfigMap.get(authenticatorName);
        String idps = authenticatorElem.getAttributeValue(new QName(FrameworkConstants.Config.ATTR_AUTHENTICATOR_IDPS));

        //if idps defined
        if (idps != null && !idps.isEmpty()) {
            String[] idpArr = idps.split(",");

            for (String idp : idpArr) {
                authenticatorConfig.getIdpNames().add(idp);
            }
        } else {
            authenticatorConfig.getIdpNames().add(FrameworkConstants.LOCAL_IDP_NAME);
        }

        stepConfig.getAuthenticatorList().add(authenticatorConfig);
    }

    return stepConfig;
}
 
Example 20
Source File: MockIaasConfigParser.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
/**
 * Parse mock iaas configuration and return configuration object.
 *
 * @param filePath
 * @return
 */
public static MockIaasConfig parse(String filePath) {
    try {
        MockIaasConfig mockIaasConfig = new MockIaasConfig();
        MockHealthStatisticsConfig mockHealthStatisticsConfig = new MockHealthStatisticsConfig();
        mockIaasConfig.setMockHealthStatisticsConfig(mockHealthStatisticsConfig);

        OMElement document = AxiomXpathParserUtil.parse(new File(filePath));
        String enabledStr = document.getAttributeValue(ENABLED_ATTRIBUTE);
        if (StringUtils.isEmpty(enabledStr)) {
            throw new RuntimeException("Enabled attribute not found in mock-iaas element");
        }
        mockIaasConfig.setEnabled(Boolean.parseBoolean(enabledStr));

        Iterator statisticsIterator = document.getChildElements();

        while (statisticsIterator.hasNext()) {
            OMElement statisticsElement = (OMElement) statisticsIterator.next();

            if (HEALTH_STATISTICS_ELEMENT.equals(statisticsElement.getQName().getLocalPart())) {
                Iterator cartridgeIterator = statisticsElement.getChildElements();

                while (cartridgeIterator.hasNext()) {
                    OMElement cartridgeElement = (OMElement) cartridgeIterator.next();
                    OMAttribute typeAttribute = cartridgeElement.getAttribute(TYPE_ATTRIBUTE);
                    if (typeAttribute == null) {
                        throw new RuntimeException("Type attribute not found in cartridge element");
                    }
                    String cartridgeType = typeAttribute.getAttributeValue();
                    Iterator patternIterator = cartridgeElement.getChildElements();

                    while (patternIterator.hasNext()) {
                        OMElement patternElement = (OMElement) patternIterator.next();

                        OMAttribute factorAttribute = patternElement.getAttribute(FACTOR_ATTRIBUTE);
                        if (factorAttribute == null) {
                            throw new RuntimeException("Factor attribute not found in pattern element: " +
                                    "[cartridge-type] " + cartridgeType);
                        }
                        String factorStr = factorAttribute.getAttributeValue();
                        MockScalingFactor scalingFactor = convertScalingFactor(factorStr);

                        OMAttribute modeAttribute = patternElement.getAttribute(MODE_ATTRIBUTE);
                        if (modeAttribute == null) {
                            throw new RuntimeException("Mode attribute not found in pattern element: " +
                                    "[cartridge-type] " + cartridgeType);
                        }
                        String modeStr = modeAttribute.getAttributeValue();
                        StatisticsPatternMode mode = convertMode(modeStr);

                        String sampleValuesStr = null;
                        String sampleDurationStr = null;
                        Iterator patternChildIterator = patternElement.getChildElements();

                        while (patternChildIterator.hasNext()) {
                            OMElement patternChild = (OMElement) patternChildIterator.next();
                            if (SAMPLE_VALUES_ELEMENT.equals(patternChild.getQName().getLocalPart())) {
                                sampleValuesStr = patternChild.getText();
                            } else if (SAMPLE_DURATION_ELEMENT.equals(patternChild.getQName().getLocalPart())) {
                                sampleDurationStr = patternChild.getText();
                            }
                        }

                        if (sampleValuesStr == null) {
                            throw new RuntimeException("Sample values not found in pattern [factor] " + factorStr);
                        }
                        if (sampleDurationStr == null) {
                            throw new RuntimeException("Sample duration not found in pattern [factor] " + factorStr);
                        }

                        String[] sampleValuesArray = sampleValuesStr.split(",");
                        List<Integer> sampleValues = convertStringArrayToIntegerList(sampleValuesArray);
                        int sampleDuration = Integer.parseInt(sampleDurationStr);

                        MockHealthStatisticsPattern mockHealthStatisticsPattern = new MockHealthStatisticsPattern
                                (cartridgeType, scalingFactor, mode, sampleValues, sampleDuration);
                        mockHealthStatisticsConfig.addStatisticsPattern(mockHealthStatisticsPattern);
                    }
                }
            }
        }
        return mockIaasConfig;
    } catch (Exception e) {
        throw new RuntimeException("Could not parse mock health statistics configuration", e);
    }
}