public static OMElement serializeHandlerConfiguration(HandlerConfigurationBean bean) { OMFactory factory = OMAbstractFactory.getOMFactory(); OMElement handler = factory.createOMElement("handler", null); handler.addAttribute(factory.createOMAttribute("class", null, bean.getHandlerClass())); if (bean.getTenant() != null) { handler.addAttribute(factory.createOMAttribute("tenant", null, bean.getTenant())); } StringBuilder sb = new StringBuilder(); for (String method : bean.getMethods()) { if (method != null && method.length() > 0) { sb.append(method).append(","); } } // Remove last "," if (sb.length() > 0) { sb.deleteCharAt(sb.length() - 1); handler.addAttribute(factory.createOMAttribute("methods", null, sb.toString())); } for (String property : bean.getPropertyList()) { OMElement temp = factory.createOMElement("property", null); temp.addAttribute(factory.createOMAttribute("name", null, property)); OMElement xmlProperty = bean.getXmlProperties().get(property); if (xmlProperty != null) { // The serialization happens by adding the whole XML property value to the // bean. // Therefore if it is a XML property, we take that whole element. handler.addChild(xmlProperty); } else { String nonXMLProperty = bean.getNonXmlProperties().get(property); if (nonXMLProperty != null) { temp.setText(nonXMLProperty); handler.addChild(temp); } } } OMElement filter = factory.createOMElement("filter", null); filter.addAttribute( factory.createOMAttribute("class", null, bean.getFilter().getFilterClass())); for (String property : bean.getFilter().getPropertyList()) { OMElement temp = factory.createOMElement("property", null); temp.addAttribute(factory.createOMAttribute("name", null, property)); OMElement xmlProperty = bean.getFilter().getXmlProperties().get(property); if (xmlProperty != null) { temp.addAttribute(factory.createOMAttribute("type", null, "xml")); temp.addChild(xmlProperty); filter.addChild(temp); } else { String nonXMLProperty = bean.getFilter().getNonXmlProperties().get(property); if (nonXMLProperty != null) { temp.setText(nonXMLProperty); filter.addChild(temp); } } } handler.addChild(filter); return handler; }
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; }
/** * Creates endpoint element for REST service * * @param requestContext information about current request. * @param wadlElement wadl document. * @param version wadl version. * @return Endpoint Path. * @throws RegistryException If fails to create endpoint element. */ private String createEndpointElement( RequestContext requestContext, OMElement wadlElement, String version) throws RegistryException { OMNamespace wadlNamespace = wadlElement.getNamespace(); String wadlNamespaceURI = wadlNamespace.getNamespaceURI(); String wadlNamespacePrefix = wadlNamespace.getPrefix(); OMElement resourcesElement = wadlElement.getFirstChildWithName( new QName(wadlNamespaceURI, "resources", wadlNamespacePrefix)); if (resourcesElement != null) { String endpointUrl = resourcesElement.getAttributeValue(new QName("base")); if (endpointUrl != null) { String endpointPath = EndpointUtils.deriveEndpointFromUrl(endpointUrl); String endpointName = EndpointUtils.deriveEndpointNameFromUrl(endpointUrl); String endpointContent = EndpointUtils.getEndpointContentWithOverview( endpointUrl, endpointPath, endpointName, version); OMElement endpointElement; try { endpointElement = AXIOMUtil.stringToOM(endpointContent); } catch (XMLStreamException e) { throw new RegistryException("Error in creating the endpoint element. ", e); } return RESTServiceUtils.addEndpointToRegistry( requestContext, endpointElement, endpointPath); } else { log.warn("Base path does not exist. endpoint creation may fail. "); } } else { log.warn("Resources element is null. "); } return null; }
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; }
private OMElement resolveImports( OMElement grammarsElement, String wadlBaseUri, String wadlVersion) throws RegistryException { String wadlNamespace = grammarsElement.getNamespace().getNamespaceURI(); Iterator<OMElement> grammarElements = grammarsElement.getChildrenWithName(new QName(wadlNamespace, "include")); while (grammarElements.hasNext()) { OMElement childElement = grammarElements.next(); OMAttribute refAttr = childElement.getAttribute(new QName("href")); String importUrl = refAttr.getAttributeValue(); if (importUrl.endsWith(".xsd")) { if (!importUrl.startsWith("http")) { if (registry.resourceExists(importUrl)) { continue; } else { if (wadlBaseUri != null) { importUrl = wadlBaseUri + importUrl; } } } String schemaPath = saveSchema(importUrl, wadlVersion); importedSchemas.add(schemaPath); refAttr.setAttributeValue(schemaPath); childElement.addAttribute(refAttr); } } return grammarsElement; }
public void sendUsingMTOM(String fileName, String targetEPR) throws IOException { OMFactory factory = OMAbstractFactory.getOMFactory(); OMNamespace ns = factory.createOMNamespace("http://services.samples", "m0"); OMElement payload = factory.createOMElement("uploadFileUsingMTOM", ns); OMElement request = factory.createOMElement("request", ns); OMElement image = factory.createOMElement("image", ns); FileDataSource fileDataSource = new FileDataSource(new File(fileName)); DataHandler dataHandler = new DataHandler(fileDataSource); OMText textData = factory.createOMText(dataHandler, true); image.addChild(textData); request.addChild(image); payload.addChild(request); ServiceClient serviceClient = new ServiceClient(); Options options = new Options(); options.setTo(new EndpointReference(targetEPR)); options.setAction("urn:uploadFileUsingMTOM"); options.setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE); options.setCallTransportCleanup(true); serviceClient.setOptions(options); OMElement response = serviceClient.sendReceive(payload); Assert.assertTrue( response .toString() .contains( "<m:testMTOM xmlns:m=\"http://services.samples/xsd\">" + "<m:test1>testMTOM</m:test1></m:testMTOM>")); }
public static MessageContext sendUsingSwA(String fileName, String targetEPR) throws IOException { Options options = new Options(); options.setTo(new EndpointReference(targetEPR)); options.setAction("urn:uploadFileUsingSwA"); options.setProperty(Constants.Configuration.ENABLE_SWA, Constants.VALUE_TRUE); ServiceClient sender = new ServiceClient(); sender.setOptions(options); OperationClient mepClient = sender.createClient(ServiceClient.ANON_OUT_IN_OP); MessageContext mc = new MessageContext(); System.out.println("Sending file : " + fileName + " as SwA"); FileDataSource fileDataSource = new FileDataSource(new File(fileName)); DataHandler dataHandler = new DataHandler(fileDataSource); String attachmentID = mc.addAttachment(dataHandler); SOAPFactory factory = OMAbstractFactory.getSOAP11Factory(); SOAPEnvelope env = factory.getDefaultEnvelope(); OMNamespace ns = factory.createOMNamespace("http://services.samples/xsd", "m0"); OMElement payload = factory.createOMElement("uploadFileUsingSwA", ns); OMElement request = factory.createOMElement("request", ns); OMElement imageId = factory.createOMElement("imageId", ns); imageId.setText(attachmentID); request.addChild(imageId); payload.addChild(request); env.getBody().addChild(payload); mc.setEnvelope(env); mepClient.addMessageContext(mc); mepClient.execute(true); MessageContext response = mepClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE); SOAPBody body = response.getEnvelope().getBody(); String imageContentId = body.getFirstChildWithName( new QName("http://services.samples/xsd", "uploadFileUsingSwAResponse")) .getFirstChildWithName(new QName("http://services.samples/xsd", "response")) .getFirstChildWithName(new QName("http://services.samples/xsd", "imageId")) .getText(); Attachments attachment = response.getAttachmentMap(); dataHandler = attachment.getDataHandler(imageContentId); File tempFile = File.createTempFile("swa-", ".gif"); FileOutputStream fos = new FileOutputStream(tempFile); dataHandler.writeTo(fos); fos.flush(); fos.close(); System.out.println("Saved response to file : " + tempFile.getAbsolutePath()); return response; }
public static HandlerConfigurationBean deserializeHandlerConfiguration( OMElement configurationElement) { if (configurationElement == null || !"handler".equals(configurationElement.getLocalName())) { return null; } HandlerConfigurationBean handlerConfigurationBean = new HandlerConfigurationBean(); handlerConfigurationBean.setHandlerClass( configurationElement.getAttributeValue(new QName("class"))); handlerConfigurationBean.setTenant(configurationElement.getAttributeValue(new QName("tenant"))); String methodsAttribute = configurationElement.getAttributeValue(new QName("methods")); if (methodsAttribute != null && methodsAttribute.length() != 0) { handlerConfigurationBean.setMethods(methodsAttribute.split(",")); } @SuppressWarnings("unchecked") Iterator<OMElement> handlerProps = configurationElement.getChildrenWithName(new QName("property")); while (handlerProps.hasNext()) { OMElement propElement = handlerProps.next(); String propName = propElement.getAttributeValue(new QName("name")); String propType = propElement.getAttributeValue(new QName("type")); if (propType != null && "xml".equals(propType)) { handlerConfigurationBean.getXmlProperties().put(propName, propElement); } else { handlerConfigurationBean.getNonXmlProperties().put(propName, propElement.getText()); } handlerConfigurationBean.getPropertyList().add(propName); } FilterConfigurationBean filterConfigurationBean = new FilterConfigurationBean(); OMElement filterElement = configurationElement.getFirstChildWithName(new QName("filter")); filterConfigurationBean.setFilterClass(filterElement.getAttributeValue(new QName("class"))); @SuppressWarnings("unchecked") Iterator<OMElement> filterProps = filterElement.getChildrenWithName(new QName("property")); while (filterProps.hasNext()) { OMElement propElement = filterProps.next(); String propName = propElement.getAttributeValue(new QName("name")); String propType = propElement.getAttributeValue(new QName("type")); if (propType != null && "xml".equals(propType)) { filterConfigurationBean.getXmlProperties().put(propName, propElement); } else { filterConfigurationBean.getNonXmlProperties().put(propName, propElement.getText()); } filterConfigurationBean.getPropertyList().add(propName); } handlerConfigurationBean.setFilter(filterConfigurationBean); return handlerConfigurationBean; }
public static boolean updateHandler(Registry configSystemRegistry, String oldName, String payload) throws RegistryException, XMLStreamException { if (isHandlerNameInUse(oldName)) throw new RegistryException("Could not update handler since it is already in use!"); String newName = null; OMElement element = AXIOMUtil.stringToOM(payload); if (element != null) { newName = element.getAttributeValue(new QName("class")); } if (newName == null || newName.equals("")) return false; // invalid configuration if (oldName == null || oldName.equals("")) { String path = getContextRoot() + newName; Resource resource; if (handlerExists(configSystemRegistry, newName)) { return false; // we are adding a new handler } else { resource = new ResourceImpl(); } resource.setContent(payload); try { configSystemRegistry.beginTransaction(); configSystemRegistry.put(path, resource); generateHandler(configSystemRegistry, path); configSystemRegistry.commitTransaction(); } catch (Exception e) { configSystemRegistry.rollbackTransaction(); throw new RegistryException("Unable to generate handler", e); } return true; } if (newName.equals(oldName)) { // updating the rest of the content String oldPath = getContextRoot() + oldName; Resource resource; if (handlerExists(configSystemRegistry, oldName)) { resource = configSystemRegistry.get(oldPath); } else { resource = new ResourceImpl(); // will this ever happen? } resource.setContent(payload); try { configSystemRegistry.beginTransaction(); removeHandler(configSystemRegistry, oldName); configSystemRegistry.put(oldPath, resource); generateHandler(configSystemRegistry, oldPath); configSystemRegistry.commitTransaction(); } catch (Exception e) { configSystemRegistry.rollbackTransaction(); throw new RegistryException("Unable to generate handler", e); } return true; } else { String oldPath = getContextRoot() + oldName; String newPath = getContextRoot() + newName; if (handlerExists(configSystemRegistry, newName)) { return false; // we are trying to use the name of a existing handler } Resource resource; if (handlerExists(configSystemRegistry, oldName)) { resource = configSystemRegistry.get(oldPath); } else { resource = new ResourceImpl(); // will this ever happen? } resource.setContent(payload); try { configSystemRegistry.beginTransaction(); configSystemRegistry.put(newPath, resource); generateHandler(configSystemRegistry, newPath); removeHandler(configSystemRegistry, oldName); configSystemRegistry.delete(oldPath); configSystemRegistry.commitTransaction(); } catch (Exception e) { configSystemRegistry.rollbackTransaction(); throw new RegistryException("Unable to renew handler", e); } return true; } }
public String addWadlToRegistry( RequestContext requestContext, Resource resource, String resourcePath, boolean skipValidation) throws RegistryException { String wadlName = RegistryUtils.getResourceName(resourcePath); String version = requestContext.getResource().getProperty(RegistryConstants.VERSION_PARAMETER_NAME); if (version == null) { version = CommonConstants.WADL_VERSION_DEFAULT_VALUE; requestContext.getResource().setProperty(RegistryConstants.VERSION_PARAMETER_NAME, version); } OMElement wadlElement; String wadlContent; Object resourceContent = resource.getContent(); if (resourceContent instanceof String) { wadlContent = (String) resourceContent; } else { wadlContent = new String((byte[]) resourceContent); } try { XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(wadlContent)); StAXOMBuilder builder = new StAXOMBuilder(reader); wadlElement = builder.getDocumentElement(); } catch (XMLStreamException e) { // This exception is unexpected because the WADL already validated String msg = "Unexpected error occured " + "while reading the WADL at " + resourcePath + "."; log.error(msg); throw new RegistryException(msg, e); } String wadlNamespace = wadlElement.getNamespace().getNamespaceURI(); String namespaceSegment = CommonUtil.derivePathFragmentFromNamespace(wadlNamespace).replace("//", "/"); String actualPath = getChrootedWadlLocation(requestContext.getRegistryContext()) + namespaceSegment + version + "/" + wadlName; OMElement grammarsElement = wadlElement.getFirstChildWithName(new QName(wadlNamespace, "grammars")); if (StringUtils.isNotBlank(requestContext.getSourceURL())) { String uri = requestContext.getSourceURL(); if (!skipValidation) { validateWADL(uri); } if (resource.getUUID() == null) { resource.setUUID(UUID.randomUUID().toString()); } String wadlBaseUri = uri.substring(0, uri.lastIndexOf("/") + 1); if (grammarsElement != null) { // This is to avoid evaluating the grammars import when building AST grammarsElement.detach(); wadlElement.addChild(resolveImports(grammarsElement, wadlBaseUri, version)); } } else { if (!skipValidation) { File tempFile = null; BufferedWriter bufferedWriter = null; try { tempFile = File.createTempFile(wadlName, null); bufferedWriter = new BufferedWriter(new FileWriter(tempFile)); bufferedWriter.write(wadlElement.toString()); bufferedWriter.flush(); } catch (IOException e) { String msg = "Error occurred while reading the WADL File"; log.error(msg, e); throw new RegistryException(msg, e); } finally { if (bufferedWriter != null) { try { bufferedWriter.close(); } catch (IOException e) { String msg = "Error occurred while closing File writer"; log.warn(msg, e); } } } validateWADL(tempFile.toURI().toString()); try { delete(tempFile); } catch (IOException e) { String msg = "An error occurred while deleting the temporary files from local file system."; log.warn(msg, e); throw new RegistryException(msg, e); } } if (grammarsElement != null) { grammarsElement = resolveImports(grammarsElement, null, version); wadlElement.addChild(grammarsElement); } } requestContext.setResourcePath(new ResourcePath(actualPath)); if (resource.getProperty(CommonConstants.SOURCE_PROPERTY) == null) { resource.setProperty(CommonConstants.SOURCE_PROPERTY, CommonConstants.SOURCE_AUTO); } registry.put(actualPath, resource); addImportAssociations(actualPath); if (getCreateService()) { OMElement serviceElement = RESTServiceUtils.createRestServiceArtifact( wadlElement, wadlName, version, RegistryUtils.getRelativePath(requestContext.getRegistryContext(), actualPath)); String servicePath = RESTServiceUtils.addServiceToRegistry(requestContext, serviceElement); registry.addAssociation(servicePath, actualPath, CommonConstants.DEPENDS); registry.addAssociation(actualPath, servicePath, CommonConstants.USED_BY); String endpointPath = createEndpointElement(requestContext, wadlElement, version); if (endpointPath != null) { registry.addAssociation(servicePath, endpointPath, CommonConstants.DEPENDS); registry.addAssociation(endpointPath, servicePath, CommonConstants.USED_BY); } } return resource.getPath(); }
public String importWADLToRegistry( RequestContext requestContext, String commonLocation, boolean skipValidation) throws RegistryException { ResourcePath resourcePath = requestContext.getResourcePath(); String wadlName = RegistryUtils.getResourceName(resourcePath.getPath()); String version = requestContext.getResource().getProperty(RegistryConstants.VERSION_PARAMETER_NAME); if (version == null) { version = CommonConstants.WADL_VERSION_DEFAULT_VALUE; requestContext.getResource().setProperty(RegistryConstants.VERSION_PARAMETER_NAME, version); } String uri = requestContext.getSourceURL(); if (!skipValidation) { validateWADL(uri); } Registry registry = requestContext.getRegistry(); Resource resource = registry.newResource(); if (resource.getUUID() == null) { resource.setUUID(UUID.randomUUID().toString()); } resource.setMediaType(wadlMediaType); resource.setProperties(requestContext.getResource().getProperties()); ByteArrayOutputStream outputStream; OMElement wadlElement; try { InputStream inputStream = new URL(uri).openStream(); outputStream = new ByteArrayOutputStream(); int nextChar; while ((nextChar = inputStream.read()) != -1) { outputStream.write(nextChar); } outputStream.flush(); wadlElement = AXIOMUtil.stringToOM(new String(outputStream.toByteArray())); // to validate XML wadlElement.toString(); } catch (Exception e) { // This exception is unexpected because the WADL already validated throw new RegistryException( "Unexpected error occured " + "while reading the WADL at" + uri, e); } String wadlNamespace = wadlElement.getNamespace().getNamespaceURI(); String namespaceSegment = CommonUtil.derivePathFragmentFromNamespace(wadlNamespace).replace("//", "/"); OMElement grammarsElement = wadlElement.getFirstChildWithName(new QName(wadlNamespace, "grammars")); String wadlBaseUri = uri.substring(0, uri.lastIndexOf("/") + 1); if (grammarsElement != null) { grammarsElement.detach(); wadlElement.addChild(resolveImports(grammarsElement, wadlBaseUri, version)); } String actualPath; if (commonLocation != null) { actualPath = commonLocation + namespaceSegment + version + "/" + wadlName; } else { actualPath = RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + commonWADLLocation + namespaceSegment + version + "/" + wadlName; } if (resource.getProperty(CommonConstants.SOURCE_PROPERTY) == null) { resource.setProperty(CommonConstants.SOURCE_PROPERTY, CommonConstants.SOURCE_AUTO); } resource.setContent(wadlElement.toString()); requestContext.setResourcePath(new ResourcePath(actualPath)); registry.put(actualPath, resource); addImportAssociations(actualPath); if (createService) { OMElement serviceElement = RESTServiceUtils.createRestServiceArtifact( wadlElement, wadlName, version, RegistryUtils.getRelativePath(requestContext.getRegistryContext(), actualPath)); String servicePath = RESTServiceUtils.addServiceToRegistry(requestContext, serviceElement); addDependency(servicePath, actualPath); String endpointPath = createEndpointElement(requestContext, wadlElement, version); if (endpointPath != null) { addDependency(servicePath, endpointPath); } } return actualPath; }