Java源码示例:org.apache.olingo.odata2.api.exception.ODataException
示例1
@Override
public ODataResponse executeFunctionImportValue(final GetFunctionImportUriInfo uriInfo, final String contentType)
throws ODataException {
final EdmFunctionImport functionImport = uriInfo.getFunctionImport();
final EdmSimpleType type = (EdmSimpleType) functionImport.getReturnType().getType();
final Object data = dataSource.readData(
functionImport,
mapFunctionParameters(uriInfo.getFunctionImportParameters()),
null);
if (data == null) {
throw new ODataNotFoundException(ODataHttpException.COMMON);
}
ODataResponse response;
if (type == EdmSimpleTypeKind.Binary.getEdmSimpleTypeInstance()) {
response = EntityProvider.writeBinary(((BinaryData) data).getMimeType(), ((BinaryData) data).getData());
} else {
final String value = type.valueToString(data, EdmLiteralKind.DEFAULT, null);
response = EntityProvider.writeText(value == null ? "" : value);
}
return ODataResponse.fromResponse(response).build();
}
示例2
/**
* Function Import implementation for getting customer by email address
*
* @param emailAddress
* email address of the customer
* @return customer entity.
* @throws ODataException
*/
@SuppressWarnings("unchecked")
@EdmFunctionImport(name = "GetCustomerByEmailAddress", entitySet = "Customers", returnType = @ReturnType(type = Type.ENTITY, isCollection = true))
public List<Customer> getCustomerByEmailAddress(
@EdmFunctionImportParameter(name = "EmailAddress") String emailAddress) throws ODataException {
EntityManagerFactory emf = Utility.getEntityManagerFactory();
EntityManager em = emf.createEntityManager();
List<Customer> custList = null;
try {
Query query = em.createNamedQuery("Customer.getCustomerByEmailAddress");
query.setParameter("emailAddress", emailAddress);
try {
custList = query.getResultList();
return custList;
} catch (NoResultException e) {
throw new ODataApplicationException("No matching customer with Email Address:" + emailAddress,
Locale.ENGLISH, HttpStatusCodes.BAD_REQUEST, e);
}
} finally {
em.close();
}
}
示例3
@Override
public List<EdmEntitySetInfo> getEntitySetInfos() throws ODataException {
if(edmProvider == null){
throw new ODataException(EDM_PROVIDER_EXEPTION);
}
if (entitySetInfos == null) {
entitySetInfos = new ArrayList<EdmEntitySetInfo>();
if (schemas == null) {
schemas = edmProvider.getSchemas();
}
for (Schema schema : schemas) {
for (EntityContainer entityContainer : listOrEmptyList(schema.getEntityContainers())) {
for (EntitySet entitySet : listOrEmptyList(entityContainer.getEntitySets())) {
EdmEntitySetInfo entitySetInfo = new EdmEntitySetInfoImplProv(entitySet, entityContainer);
entitySetInfos.add(entitySetInfo);
}
}
}
}
return entitySetInfos;
}
示例4
@Test
public void serializeAtomEntry() throws IOException, XpathException, SAXException, XMLStreamException,
FactoryConfigurationError, ODataException {
final EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(BASE_URI).build();
AtomEntityProvider ser = createAtomEntityProvider();
ODataResponse response =
ser.writeEntry(MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"), roomData, properties);
String xmlString = verifyResponse(response);
assertXpathExists("/a:entry", xmlString);
assertXpathEvaluatesTo(BASE_URI.toASCIIString(), "/a:entry/@xml:base", xmlString);
assertXpathExists("/a:entry/a:content", xmlString);
assertXpathEvaluatesTo(ContentType.APPLICATION_XML.toString(), "/a:entry/a:content/@type", xmlString);
assertXpathExists("/a:entry/a:content/m:properties", xmlString);
}
示例5
private <T> T readEntryData(final List<T> data, final EdmEntityType entityType, final Map<String, Object> key)
throws ODataException {
for (final T entryData : data) {
boolean found = true;
for (final EdmProperty keyProperty : entityType.getKeyProperties()) {
if (!valueAccess.getPropertyValue(entryData, keyProperty).equals(key.get(keyProperty.getName()))) {
found = false;
break;
}
}
if (found) {
return entryData;
}
}
return null;
}
示例6
@Test
public void createTransportTest() throws UnexpectedHttpResponseException, IOException, URISyntaxException, ODataException {
Map<String, Object> transport = Transport.getTransportCreationRequestMap("ODATA", "my transport", "A5T", "", "W");
Transport created = examinee.createTransport(transport);
assertThat(created, is(not(nullValue())));
assertThat(created.getTransportID(), is(not(nullValue())));
assertThat(created.getTransportID().trim(), is(not("")));
assertThat(created.getOwner(), is(equalTo("ODATA")));
assertThat(created.getTargetSystem(), is(equalTo("A5T")));
assertThat(created.getDescription(), is(equalTo("my transport")));
assertThat(created.getStatus(), is(equalTo("D")));
assertThat(created.getType(), is(equalTo("W")));
assertThat(created.getCloud(), is(equalTo("X")));
}
示例7
private Object retrieveData(final EdmEntitySet startEntitySet, final List<KeyPredicate> keyPredicates,
final EdmFunctionImport functionImport, final Map<String, Object> functionImportParameters,
final List<NavigationSegment> navigationSegments) throws ODataException {
Object data;
final Map<String, Object> keys = mapKey(keyPredicates);
ODataContext context = getContext();
final int timingHandle = context.startRuntimeMeasurement(getClass().getSimpleName(), "retrieveData");
try {
data = functionImport == null ?
keys.isEmpty() ?
dataSource.readData(startEntitySet) : dataSource.readData(startEntitySet, keys) :
dataSource.readData(functionImport, functionImportParameters, keys);
EdmEntitySet currentEntitySet =
functionImport == null ? startEntitySet : functionImport.getEntitySet();
for (NavigationSegment navigationSegment : navigationSegments) {
data = dataSource.readRelatedData(
currentEntitySet,
data,
navigationSegment.getEntitySet(),
mapKey(navigationSegment.getKeyPredicates()));
currentEntitySet = navigationSegment.getEntitySet();
}
} finally {
context.stopRuntimeMeasurement(timingHandle);
}
return data;
}
示例8
@Override
public ODataResponse build(final GetEntityLinkUriInfo resultsView, final Object jpaEntity,
final String contentType) throws ODataNotFoundException,
ODataJPARuntimeException {
if (jpaEntity == null) {
throw new ODataNotFoundException(ODataNotFoundException.ENTITY);
}
EdmEntityType edmEntityType = null;
ODataResponse odataResponse = null;
try {
EdmEntitySet entitySet = resultsView.getTargetEntitySet();
edmEntityType = entitySet.getEntityType();
Map<String, Object> edmPropertyValueMap = null;
JPAEntityParser jpaResultParser = new JPAEntityParser();
edmPropertyValueMap = jpaResultParser.parse2EdmPropertyValueMap(jpaEntity, edmEntityType.getKeyProperties());
EntityProviderWriteProperties entryProperties =
EntityProviderWriteProperties.serviceRoot(oDataJPAContext.getODataContext().getPathInfo().getServiceRoot())
.build();
ODataResponse response = EntityProvider.writeLink(contentType, entitySet, edmPropertyValueMap, entryProperties);
odataResponse = ODataResponse.fromResponse(response).build();
} catch (ODataException e) {
throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e);
}
return odataResponse;
}
示例9
@Test
public void testWrappedODataNotFoundException() throws Exception {
// prepare
Exception causeException = new ODataNotFoundException(ODataNotFoundException.ENTITY);
String exceptionMessage = "Some odd exception";
Exception exception = new ODataException(exceptionMessage, causeException);
// execute
Response response = exceptionMapper.toResponse(exception);
// verify
verifyResponse(response, MessageService.getMessage(Locale.ENGLISH, ODataNotFoundException.ENTITY).getText(),
HttpStatusCodes.NOT_FOUND);
}
示例10
@Override
public List<Schema> getSchemas() throws ODataException {
if (schemas == null && jpaEdmModel != null) {
jpaEdmModel.getBuilder().build();
schemas = new ArrayList<Schema>();
schemas.add(jpaEdmModel.getEdmSchemaView().getEdmSchema());
}
if (jpaEdmModel == null) {
throw ODataJPAModelException.throwException(ODataJPAModelException.BUILDER_NULL, null);
}
return schemas;
}
示例11
public Client(final String serviceUrl, final Proxy.Type protocol, final String proxy, final int port)
throws IOException, ODataException,
HttpException {
this.serviceUrl = serviceUrl;
this.protocol = protocol;
this.proxy = proxy;
this.port = port;
useProxy = true;
useAuthentication = false;
edm = getEdmInternal();
}
示例12
@Test
public void checkAcceptuablesLanguage() throws ODataException, ClientProtocolException, IOException {
final HttpGet get = new HttpGet(URI.create(getEndpoint().toString() + "/$metadata"));
get.setHeader("Accept-Language", "de, en");
getHttpClient().execute(get);
final ODataContext ctx = getService().getProcessor().getContext();
assertNotNull(ctx);
assertEquals("[de, en]", ctx.getAcceptableLanguages().toString());
}
示例13
@Override
public ODataResponse executeBatch(BatchHandler handler, String contentType, InputStream content)
throws ODataException {
ODataContext ctx = ODataJPAContextImpl.getContextInThreadLocal();
authorization.setContext((HttpServletRequest) ctx.getParameter(ODataContext.HTTP_SERVLET_REQUEST_OBJECT));
return super.executeBatch(handler, contentType, content);
}
示例14
@Test
public void readMetadata() throws ClientProtocolException, IOException, ODataException {
final HttpResponse response = executeGetRequest("$metadata");
assertEquals(HttpStatusCodes.OK.getStatusCode(), response.getStatusLine().getStatusCode());
final String payload = StringHelper.inputStreamToString(response.getEntity().getContent());
assertEquals("metadata", payload);
}
示例15
protected void startCustomServer(Class<? extends FitStaticServiceFactory> factoryClass){
try {
service = createService();
server.startServer(service, factoryClass);
} catch (final ODataException e) {
throw new TestUtilRuntimeException(e);
}
}
示例16
@Test
public void testCreateEntity() {
try {
Assert.assertNotNull(objODataJPAProcessorDefault.createEntity(getPostUriInfo(), getMockedInputStreamContent(),
HttpContentType.APPLICATION_XML, HttpContentType.APPLICATION_XML));
} catch (ODataException e) {
Assert.assertTrue(true); // Expected TODO - need to revisit
}
}
示例17
/**
* Function Import implementation for cancelling a sales order
*
* @param salesOrderId
* sales order id of sales order to be cancelled
* @return SalesOrderHeader entity
* @throws ODataException
*/
@SuppressWarnings("unchecked")
@EdmFunctionImport(name = "CancelSalesOrder", entitySet = "SalesOrderHeaders", returnType = @ReturnType(type = Type.ENTITY, isCollection = true))
public List<SalesOrderHeader> cancelSalesOrder(
@EdmFunctionImportParameter(name = "SalesOrderId") String salesOrderId) throws ODataException {
EntityManagerFactory emf = Utility.getEntityManagerFactory();
EntityManager em = emf.createEntityManager();
try {
Query query = em.createNamedQuery("SalesOrderHeader.getSOHBySaledOrderId");
query.setParameter("salesOrderId", salesOrderId);
try {
SalesOrderHeader so = (SalesOrderHeader) query.getSingleResult();
em.getTransaction().begin();
so.setLifeCycleStatus("X");
so.setLifeCycleStatusName("Cancelled");
em.persist(so);
em.getTransaction().commit();
List<SalesOrderHeader> salesOrderList = null;
query = em.createNamedQuery("SalesOrderHeader.getSOHBySaledOrderId");
query.setParameter("salesOrderId", salesOrderId);
salesOrderList = query.getResultList();
return salesOrderList;
} catch (NoResultException e) {
throw new ODataApplicationException("No Sales Order with Sales Order Id:" + salesOrderId,
Locale.ENGLISH, HttpStatusCodes.BAD_REQUEST , e);
}
} finally {
em.close();
}
}
示例18
@Override
protected ODataSingleProcessor createProcessor() throws ODataException {
final ODataSingleProcessor processor = mock(ODataSingleProcessor.class);
when(((MetadataProcessor) processor).readMetadata(any(GetMetadataUriInfo.class), any(String.class))).thenReturn(
ODataResponse.entity("metadata").status(HttpStatusCodes.OK).build());
return processor;
}
示例19
@Override
public ODataResponse readEntityLink(final GetEntityLinkUriInfo uriInfo, final String contentType)
throws ODataException {
final Object data = retrieveData(
uriInfo.getStartEntitySet(),
uriInfo.getKeyPredicates(),
uriInfo.getFunctionImport(),
mapFunctionParameters(uriInfo.getFunctionImportParameters()),
uriInfo.getNavigationSegments());
if (data == null) {
throw new ODataNotFoundException(ODataNotFoundException.ENTITY);
}
final EdmEntitySet entitySet = uriInfo.getTargetEntitySet();
Map<String, Object> values = new HashMap<String, Object>();
for (final EdmProperty property : entitySet.getEntityType().getKeyProperties()) {
values.put(property.getName(), valueAccess.getPropertyValue(data, property));
}
ODataContext context = getContext();
final EntityProviderWriteProperties entryProperties = EntityProviderWriteProperties
.serviceRoot(context.getPathInfo().getServiceRoot())
.build();
final int timingHandle = context.startRuntimeMeasurement("EntityProvider", "writeLink");
final ODataResponse response = EntityProvider.writeLink(contentType, entitySet, values, entryProperties);
context.stopRuntimeMeasurement(timingHandle);
return ODataResponse.fromResponse(response).build();
}
示例20
private static PathInfoImpl splitPath(final SubLocatorParameter param) throws ODataException {
PathInfoImpl pathInfo = new PathInfoImpl();
List<javax.ws.rs.core.PathSegment> precedingPathSegments;
List<javax.ws.rs.core.PathSegment> pathSegments;
if (param.getPathSplit() == 0) {
precedingPathSegments = Collections.emptyList();
pathSegments = param.getPathSegments();
} else {
if (param.getPathSegments().size() < param.getPathSplit()) {
throw new ODataBadRequestException(ODataBadRequestException.URLTOOSHORT);
}
precedingPathSegments = param.getPathSegments().subList(0, param.getPathSplit());
final int pathSegmentCount = param.getPathSegments().size();
pathSegments = param.getPathSegments().subList(param.getPathSplit(), pathSegmentCount);
}
// Percent-decode only the preceding path segments.
// The OData path segments are decoded during URI parsing.
pathInfo.setPrecedingPathSegment(convertPathSegmentList(precedingPathSegments));
List<PathSegment> odataSegments = new ArrayList<PathSegment>();
for (final javax.ws.rs.core.PathSegment segment : pathSegments) {
if (segment.getMatrixParameters() == null || segment.getMatrixParameters().isEmpty()) {
odataSegments.add(new ODataPathSegmentImpl(segment.getPath(), null));
} else {
// post condition: we do not allow matrix parameters in OData path segments
throw new ODataNotFoundException(ODataNotFoundException.MATRIX.addContent(segment.getMatrixParameters()
.keySet(), segment.getPath()));
}
}
pathInfo.setODataPathSegment(odataSegments);
return pathInfo;
}
示例21
@Test
public void buildPutEntityTestWithoutListener() {
try {
EdmMapping mapping = (EdmMapping) mockMapping();
assertNotNull(builder.build((PutMergePatchUriInfo) mockURIInfoForDeleteAndPut(mapping)));
} catch (ODataException e) {
fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2);
}
}
示例22
/**
* Sets the value of an EDM property for the given data object.
* @param data the Java data object
* @param property the {@link EdmProperty}
* @param value the new value of the property
*/
@Override
public <T, V> void setPropertyValue(final T data, final EdmProperty property, final V value) throws ODataException {
if (data != null) {
if (annotationHelper.isEdmAnnotated(data)) {
annotationHelper.setValueForProperty(data, property.getName(), value);
} else {
throw new ODataNotImplementedException(ODataNotImplementedException.COMMON);
}
}
}
示例23
@Override
protected ODataSingleProcessor createProcessor() throws ODataException {
final ODataSingleProcessor processor = mock(ODataSingleProcessor.class);
when(((MetadataProcessor) processor).readMetadata(any(GetMetadataUriInfo.class), any(String.class)))
.thenReturn(ODataResponse.entity("metadata").status(HttpStatusCodes.OK).build());
when(
((ServiceDocumentProcessor) processor).readServiceDocument(any(GetServiceDocumentUriInfo.class),
any(String.class)))
.thenReturn(ODataResponse.entity("service document").status(HttpStatusCodes.OK).build());
return processor;
}
示例24
@Override
public ComplexType getComplexType(final FullQualifiedName edmFQName) throws ODataException {
if (NAMESPACE.equals(edmFQName.getNamespace())) {
if (COMPLEX_TYPE.getName().equals(edmFQName.getName())) {
List<Property> properties = new ArrayList<Property>();
properties.add(new SimpleProperty().setName("Street").setType(EdmSimpleTypeKind.String));
properties.add(new SimpleProperty().setName("City").setType(EdmSimpleTypeKind.String));
properties.add(new SimpleProperty().setName("ZipCode").setType(EdmSimpleTypeKind.String));
properties.add(new SimpleProperty().setName("Country").setType(EdmSimpleTypeKind.String));
return new ComplexType().setName(COMPLEX_TYPE.getName()).setProperties(properties);
}
}
return null;
}
示例25
@Override
public Object getProperty (String prop_name) throws ODataException
{
if (prop_name.equals (AttributeEntitySet.VALUE)) return getValue ();
return super.getProperty (prop_name);
}
示例26
@Override
public Object getProperty (String prop_name) throws ODataException
{
if (prop_name.equals (NetworkStatisticEntitySet.ID)) return 0;
if (prop_name.equals (NetworkStatisticEntitySet.ACTIVITYPERIOD))
return abuseMetrics.getPeriod ();
if (prop_name.equals (NetworkStatisticEntitySet.CONNECTIONNUMBER))
return abuseMetrics.getCalls ();
throw new ODataException ("Property '" + prop_name + "' not found.");
}
示例27
@Test
public void testNullGetEntityContainerInfo() {
EntityContainerInfo entityContainer = null;
try {
entityContainer = edmProvider.getEntityContainerInfo("salesorderprocessingContainer");
} catch (ODataException e) {
fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2);
}
assertNull(entityContainer);
}
示例28
@Test
public void checkHttpRequest() throws ClientProtocolException, IOException, ODataException {
final HttpGet get = new HttpGet(URI.create(getEndpoint().toString() + "/$metadata"));
getHttpClient().execute(get);
final ODataContext ctx = getService().getProcessor().getContext();
assertNotNull(ctx);
final Object requestObject = ctx.getParameter(ODataContext.HTTP_SERVLET_REQUEST_OBJECT);
assertNotNull(requestObject);
assertTrue(requestObject instanceof HttpServletRequest);
}
示例29
@Override
public ODataResponse readEntitySet(GetEntitySetUriInfo uriInfo, String contentType) throws ODataException {
if ("Employees".equals(uriInfo.getTargetEntitySet().getName())) {
ODataContext context = getContext();
EntityProviderWriteProperties writeProperties =
EntityProviderWriteProperties.serviceRoot(context.getPathInfo().getServiceRoot()).build();
List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
data.add(new HashMap<String, Object>());
return EntityProvider.writeFeed(contentType, uriInfo.getTargetEntitySet(), data, writeProperties);
} else {
throw new ODataApplicationException("Wrong testcall", Locale.getDefault(), HttpStatusCodes.NOT_IMPLEMENTED);
}
}
示例30
private ODataContext getLocalODataContext() {
ODataContext objODataContext = null;
try {
ODataContextMock contextMock = new ODataContextMock();
contextMock.setODataService(new ODataServiceMock().mock());
contextMock.setPathInfo(getLocalPathInfo());
objODataContext = contextMock.mock();
} catch (ODataException e) {
fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2);
}
return objODataContext;
}