Example usage for javax.xml.namespace QName QName

List of usage examples for javax.xml.namespace QName QName

Introduction

In this page you can find the example usage for javax.xml.namespace QName QName.

Prototype

public QName(final String namespaceURI, final String localPart) 

Source Link

Document

QName constructor specifying the Namespace URI and local part.

If the Namespace URI is null, it is set to javax.xml.XMLConstants#NULL_NS_URI XMLConstants.NULL_NS_URI .

Usage

From source file:org.apache.servicemix.camel.nmr.ws.policy.WSPolicyTest.java

public void testUsingAddressing() throws Exception {
    SpringBusFactory bf = new SpringBusFactory();
    bus = bf.createBus("/org/apache/servicemix/camel/ws/policy/addr.xml");
    LoggingInInterceptor in = new LoggingInInterceptor();
    bus.getInInterceptors().add(in);/*w  ww .j  a va 2 s.  co m*/
    bus.getInFaultInterceptors().add(in);
    LoggingOutInterceptor out = new LoggingOutInterceptor();
    bus.getOutInterceptors().add(out);
    bus.getOutFaultInterceptors().add(out);
    URL wsdl = getClass().getResource("/wsdl/greeter_control.wsdl");
    QName serviceName = new QName("http://cxf.apache.org/greeter_control", "BasicGreeterService");
    BasicGreeterService gs = new BasicGreeterService(wsdl, serviceName);
    final Greeter greeter = gs.getGreeterPort();
    LOG.info("Created greeter client.");
    if ("HP-UX".equals(System.getProperty("os.name"))) {
        ConnectionHelper.setKeepAliveConnection(greeter, true);
    }

    //set timeout to 30 secs to avoid intermitly failed
    ((ClientImpl) ClientProxy.getClient(greeter)).setSynchronousTimeout(30000);

    // oneway
    greeter.greetMeOneWay("CXF");

    // two-way

    assertEquals("CXF", greeter.greetMe("cxf"));

    // exception

    try {
        greeter.pingMe();
    } catch (PingMeFault ex) {
        fail("First invocation should have succeeded.");
    }

    try {
        greeter.pingMe();
        fail("Expected PingMeFault not thrown.");
    } catch (PingMeFault ex) {
        assertEquals(2, (int) ex.getFaultInfo().getMajor());
        assertEquals(1, (int) ex.getFaultInfo().getMinor());
    }
}

From source file:org.apache.servicemix.camel.JbiInOnlyWithErrorHandledTrueSpringDSLTest.java

@Override
protected void appendJbiActivationSpecs(List<ActivationSpec> activationSpecList) {
    activationSpecList.add(createActivationSpec(new ReturnNullPointerExceptionErrorComponent(),
            new QName("urn:test", "npe-error-service")));

    activationSpecList.add(createActivationSpec(receiver, new QName("urn:test", "receiver-service")));
    activationSpecList.add(createActivationSpec(deadLetter, new QName("urn:test", "deadLetter-service")));
}

From source file:com.evolveum.midpoint.repo.common.commandline.CommandLineScriptExecutor.java

private String expandMacros(CommandLineScriptType scriptType, ExpressionVariables variables, String shortDesc,
        Task task, OperationResult result) throws SchemaException, ExpressionEvaluationException,
        ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException {
    String code = scriptType.getCode();
    for (ProvisioningScriptArgumentType macroDef : scriptType.getMacro()) {

        String macroName = macroDef.getName();
        QName macroQName = new QName(SchemaConstants.NS_C, macroName);

        String expressionOutput = "";

        PrismPropertyDefinitionImpl<String> outputDefinition = new PrismPropertyDefinitionImpl(
                ExpressionConstants.OUTPUT_ELEMENT_NAME, DOMUtil.XSD_STRING, prismContext);
        outputDefinition.setMaxOccurs(1);
        Expression<PrismPropertyValue<String>, PrismPropertyDefinition<String>> expression = expressionFactory
                .makeExpression(macroDef, outputDefinition, shortDesc, task, result);

        Collection<Source<?, ?>> sources = new ArrayList<>(1);
        ExpressionEvaluationContext context = new ExpressionEvaluationContext(sources, variables, shortDesc,
                task, result);/*w  w  w  .j  av a 2  s  .com*/

        Object defaultObject = variables.get(macroQName);
        if (defaultObject != null) {
            Item sourceItem;
            if (defaultObject instanceof Item) {
                sourceItem = (Item) defaultObject;
            } else if (defaultObject instanceof String) {
                PrismPropertyDefinitionImpl<String> sourceDefinition = new PrismPropertyDefinitionImpl(
                        ExpressionConstants.OUTPUT_ELEMENT_NAME, DOMUtil.XSD_STRING, prismContext);
                sourceDefinition.setMaxOccurs(1);
                PrismProperty<String> sourceProperty = sourceDefinition.instantiate();
                sourceProperty.setRealValue(defaultObject == null ? null : defaultObject.toString());
                sourceItem = sourceProperty;
            } else {
                sourceItem = null;
            }
            Source<?, ?> defaultSource = new Source<>(sourceItem, null, sourceItem, macroQName);
            context.setDefaultSource(defaultSource);
            sources.add(defaultSource);
        }

        PrismValueDeltaSetTriple<PrismPropertyValue<String>> outputTriple = expression.evaluate(context);

        LOGGER.trace("Result of the expression evaluation: {}", outputTriple);

        if (outputTriple != null) {
            Collection<PrismPropertyValue<String>> nonNegativeValues = outputTriple.getNonNegativeValues();
            if (nonNegativeValues != null && !nonNegativeValues.isEmpty()) {
                Collection<String> expressionOutputs = PrismValue
                        .getRealValuesOfCollection((Collection) nonNegativeValues);
                if (expressionOutputs != null && !expressionOutputs.isEmpty()) {
                    expressionOutput = StringUtils.join(expressionOutputs, ",");
                }
            }
        }

        code = replaceMacro(code, macroDef.getName(), expressionOutput);
    }
    return code;
}

From source file:com.amalto.core.history.accessor.AttributeAccessor.java

private QName getQName(Document domDocument) {
    QName qName;/*from  w  w w .j  a  va  2  s.  co  m*/
    String prefix = StringUtils.substringBefore(attributeName, ":"); //$NON-NLS-1$
    String name = StringUtils.substringAfter(attributeName, ":"); //$NON-NLS-1$
    if (name.isEmpty()) {
        // No prefix (so prefix is attribute name due to substring calls).
        String attributeNamespaceURI = domDocument.getDocumentURI();
        if (attributeNamespaceURI == null || attributeNamespaceURI.isEmpty()) {
            Node attributeNode = getAttributeNode(domDocument);
            if (attributeNode != null) {
                attributeNamespaceURI = attributeNode.getNamespaceURI();
            }
        }
        qName = new QName(attributeNamespaceURI, prefix);
    } else {
        String attributeNamespaceURI = domDocument.lookupNamespaceURI(prefix);
        if (attributeNamespaceURI == null || attributeNamespaceURI.isEmpty()) {
            Node attributeNode = getAttributeNode(domDocument);
            if (attributeNode != null) {
                attributeNamespaceURI = attributeNode.lookupNamespaceURI(prefix);
            }
        }
        qName = new QName(attributeNamespaceURI, name, prefix);
    }
    return qName;
}

From source file:de.drv.dsrv.spoc.web.webservice.spring.SpocMessageDispatcherServlet.java

private void createExtraErrorAndWriteResponse(final HttpServletResponse httpServletResponse,
        final String errorText)
        throws SOAPException, JAXBException, DatatypeConfigurationException, IOException {

    final MessageFactory factory = MessageFactory.newInstance();
    final SOAPMessage message = factory.createMessage();
    final SOAPBody body = message.getSOAPBody();

    final SOAPFault fault = body.addFault();
    final QName faultName = new QName(SOAPConstants.URI_NS_SOAP_ENVELOPE, FaultCode.CLIENT.toString());
    fault.setFaultCode(faultName);//from   w w  w . j a  va  2 s .  c  o  m
    fault.setFaultString(this.soapFaultString);

    final Detail detail = fault.addDetail();

    final ExtraJaxbMarshaller extraJaxbMarshaller = new ExtraJaxbMarshaller();
    final ExtraErrorReasonType reason = ExtraErrorReasonType.INVALID_REQUEST;
    final ExtraErrorType extraError = ExtraHelper.generateError(reason, this.extraErrorCode, errorText);
    extraJaxbMarshaller.marshalExtraError(extraError, detail);

    // Schreibt die SOAPMessage in einen String.
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    message.writeTo(out);
    // Das Encoding, in dem sich die Message rausschreibt, kann man als
    // Property abfragen.
    final Object encodingProperty = message.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
    String soapMessageEncoding = "UTF-8";
    if (encodingProperty != null) {
        soapMessageEncoding = encodingProperty.toString();
    }
    final String errorXml = out.toString(soapMessageEncoding);

    httpServletResponse.setStatus(HttpServletResponse.SC_OK);
    httpServletResponse.setContentType("text/xml");
    httpServletResponse.getWriter().write(errorXml);
    httpServletResponse.getWriter().flush();
    httpServletResponse.getWriter().close();
}

From source file:argendata.api.DatasetAPIService.java

@GET
@Path("/by/title/{t}.json")
@Produces("application/json" + ";charset=UTF-8")
public Dataset getDatasetByTitleJSON(@PathParam(value = "t") String title) {
    try {// ww  w.j ava 2  s  .  c  om

        try {
            title = URLDecoder.decode(title, "UTF-8");
            validate(title);
            title = Parsing.withoutSpecialCharacters(title);
        } catch (Exception e1) {
            throw new NotFoundException("Recurso no encontrado");
        }

        if (title == null || title.isEmpty() || title.length() > MAX_QUERY_PARAM) {
            throw new Exception();
        }
        QName qName = new QName(properties.getNamespace(), "Dataset:" + title);

        Dataset d = datasetDao.getById(qName);

        Organization o = new Organization();
        o.setName(d.getPublisher().getName());
        Distribution dis = null;
        if (d.getDistribution() instanceof WebService) {
            dis = new WebService();
        } else if (d.getDistribution() instanceof Feed) {
            dis = new Feed();
        } else if (d.getDistribution() instanceof Download) {
            dis = new Download();
        }
        dis.setAccessURL(d.getAccessURL());
        dis.setFormat(d.getFormat());
        dis.setSize(d.getSize());
        Dataset dataset = new Dataset(d.getTitle(), d.getDescription(), d.getLicense(), d.getKeyword(),
                d.getDataQuality(), d.getModified(), d.getSpatial(), d.getTemporal(), d.getLocation(), o, dis,
                Parsing.withoutSpecialCharacters(d.getTitleId()));

        return dataset;
    } catch (Exception e) {
        throw new NotFoundException("Recurso no encontrado");
    }
}

From source file:Java_BWS_Sample.SampleBwsClient.java

/*******************************************************************************************************************
 *
 * Initialize the BWS and BWSUtil services.
 *
 * @return Returns true when the setup is successful, and false otherwise.
 *
 *******************************************************************************************************************
 *//* w  w w.j  a  v a 2  s.  c  om*/
private static boolean setup() {
    final String METHOD_NAME = "setup()";
    logMessage("Entering %s", METHOD_NAME);
    boolean returnValue = false;
    REQUEST_METADATA.setClientVersion(CLIENT_VERSION);
    REQUEST_METADATA.setLocale(LOCALE);
    REQUEST_METADATA.setOrganizationUid(ORG_UID);

    URL bwsServiceUrl = null;
    URL bwsUtilServiceUrl = null;

    try {
        // These are the URLs that point to the web services used for all calls.
        bwsServiceUrl = new URL("https://" + BWS_HOST_NAME + "/enterprise/admin/ws");
        bwsUtilServiceUrl = new URL("https://" + BWS_HOST_NAME + "/enterprise/admin/util/ws");
    } catch (MalformedURLException e) {

        logMessage("Cannot initialize web service URLs");
        logMessage("Exiting %s with value \"%s\"", METHOD_NAME, returnValue);
        return returnValue;
    }

    // Initialize the BWS web service stubs that will be used for all calls.
    logMessage("Initializing BWS web service stub");
    QName serviceBWS = new QName("http://ws.rim.com/enterprise/admin", "BWSService");
    QName portBWS = new QName("http://ws.rim.com/enterprise/admin", "BWS");
    _bwsService = new BWSService(null, serviceBWS);
    _bwsService.addPort(portBWS, "http://schemas.xmlsoap.org/soap/", bwsServiceUrl.toString());
    _bws = _bwsService.getPort(portBWS, BWS.class);
    logMessage("BWS web service stub initialized");

    logMessage("Initializing BWSUtil web service stub");
    QName serviceUtil = new QName("http://ws.rim.com/enterprise/admin", "BWSUtilService");
    QName portUtil = new QName("http://ws.rim.com/enterprise/admin", "BWSUtil");
    _bwsUtilService = new BWSUtilService(null, serviceUtil);
    _bwsUtilService.addPort(portUtil, "http://schemas.xmlsoap.org/soap/", bwsUtilServiceUrl.toString());
    _bwsUtil = _bwsUtilService.getPort(portUtil, BWSUtil.class);
    logMessage("BWSUtil web service stub initialized");
    // Set the connection timeout to 60 seconds.
    HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
    httpClientPolicy.setConnectionTimeout(60000);

    httpClientPolicy.setAllowChunking(false);
    httpClientPolicy.setReceiveTimeout(60000);

    Client client = ClientProxy.getClient(_bws);
    HTTPConduit http = (HTTPConduit) client.getConduit();
    http.setClient(httpClientPolicy);

    client = ClientProxy.getClient(_bwsUtil);
    http = (HTTPConduit) client.getConduit();
    http.setClient(httpClientPolicy);

    Authenticator authenticator = getAuthenticator(AUTHENTICATOR_NAME);
    if (authenticator != null) {
        String encodedUsername = getEncodedUserName(USERNAME, authenticator);
        if (encodedUsername != null && !encodedUsername.isEmpty()) {
            /*
             * Set the HTTP basic authentication on the BWS service.
             * BWSUtilService is a utility web service that does not require
             * authentication.
             */
            BindingProvider bp = (BindingProvider) _bws;
            bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, encodedUsername);
            bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, PASSWORD);

            returnValue = true;
        } else {
            logMessage("'encodedUsername' is null or empty");
        }
    } else {
        logMessage("'authenticator' is null");
    }

    logMessage("Exiting %s with value \"%s\"", METHOD_NAME, returnValue);
    return returnValue;
}

From source file:com.cisco.dvbu.ps.common.util.wsapi.CisApiFactory.java

/**
 * Returns the ResourcePort of AdminAPI/*w w  w  .  j a va  2  s  .  co  m*/
 * @param server Composite Server
 * @return ResourcePort of AdminAPI
 */
public static ResourcePortType getResourcePort(CompositeServer server) {

    Authenticator.setDefault(new BasicAuthenticator(server));

    URL url = null;
    String protocol = "http";
    int wsPort = server.getPort();
    if (server.isUseHttps()) {
        protocol = "https";
        wsPort += 2;
    }
    try {
        url = new URL(protocol + "://" + server.getHostname() + ":" + wsPort + "/services/system/admin?wsdl");
        if (logger.isDebugEnabled()) {
            logger.debug("Entering CisApiFactory.getResourcePort() with following params " + " url: " + url);
        }
    } catch (MalformedURLException e) {
        String errorMessage = DeployUtil.constructMessage(DeployUtil.MessageType.ERROR.name(),
                "Creating Resource Port", "Admin API", "ExecutePort", server);
        CompositeLogger.logException(e, errorMessage);
        throw new CompositeException(errorMessage, e);
    }

    int retry = 0;
    while (retry < numRetries) {
        retry++;
        try {
            Resource res = new Resource(url, new QName(nsResourceUrl, nsResourceName)); // Get the connection to the server.      
            if (logger.isDebugEnabled()) {
                if (res != null)
                    logger.debug("Entering CisApiFactory.getResourcePort(). Resource acquired " + " Resource: "
                            + res.toString());
            }
            ResourcePortType port = res.getResourcePort(); // Get the server port
            if (logger.isDebugEnabled()) {
                if (port != null)
                    logger.debug("Entering CisApiFactory.getResourcePort(). Port acquired " + " Port: "
                            + port.toString());
            }
            return port; // Return the port connection to the server.
        } catch (Exception e) {
            String errorMessage = DeployUtil.constructMessage(DeployUtil.MessageType.ERROR.name(),
                    "Getting Server Port, [CONNECT ATTEMPT=" + retry + "]", "Admin API", "ServerPort", server);
            if (retry == numRetries) {
                throw new CompositeException(errorMessage, e);
            } else {
                // Log the error and sleep before retrying
                CompositeLogger.logException(e, errorMessage);
                Sleep.sleep(sleepDebug, sleepRetry);
            }
        }
    }
    throw new CompositeException(
            "Maximum connection attempts reached without connecting to the Composite Information Server.");

}

From source file:com._4dconcept.springframework.data.marklogic.repository.query.PartTreeMarklogicQueryTest.java

@Test
public void differentFieldsLevelShouldBeConsidered() {
    Query query = deriveQueryFromMethod("findByLastnameAndAddressCountry", "foo", "France");

    assertThat(query.getCriteria().getOperator(), is(Criteria.Operator.and));
    assertThat(query.getCriteria().getCriteriaObject(), instanceOf(List.class));

    List<Criteria> criteriaList = extractListCriteria(query.getCriteria());

    assertCriteria(criteriaList.get(0), is(new QName("http://spring.data.marklogic/test/contact", "lastname")),
            is("foo"));

    assertCriteria(criteriaList.get(1), is(new QName("http://spring.data.marklogic/test/contact", "country")),
            is("France"));
}

From source file:de.intevation.test.irixservice.UploadReportTest.java

/**
 * Test that the webservice can be created and accepts a valid report.
 */// ww  w. j  a  va  2s .  co m
@Test
public void testServiceCreated() throws MalformedURLException, IOException, UploadReportException {
    Endpoint endpoint = Endpoint.publish("http://localhost:18913/upload-report", testObj);
    Assert.assertTrue(endpoint.isPublished());
    Assert.assertEquals("http://schemas.xmlsoap.org/wsdl/soap/http", endpoint.getBinding().getBindingID());

    URL wsdlDocumentLocation = new URL("http://localhost:18913/upload-report?wsdl");
    String namespaceURI = "http://irixservice.intevation.de/";
    String servicePart = "UploadReportService";
    String portName = "UploadReportPort";
    QName serviceQN = new QName(namespaceURI, servicePart);
    QName portQN = new QName(namespaceURI, portName);

    Service serv = Service.create(wsdlDocumentLocation, serviceQN);
    UploadReportInterface service = serv.getPort(portQN, UploadReportInterface.class);
    ReportType report = getReportFromFile(VALID_REPORT);
    service.uploadReport(report);
    String uuid = report.getIdentification().getReportUUID();
    String expectedPath = testObj.outputDir + "/" + uuid + ".xml";
    Assert.assertTrue(new File(expectedPath).exists());
}