use of org.eclipse.persistence.queries.DatabaseQuery in project eclipselink by eclipse-ee4j.
the class AbstractPersistenceUnitResource method addQueries.
private void addQueries(List<Query> queryList, PersistenceContext context, String javaClassName) {
Map<String, List<DatabaseQuery>> queries = context.getServerSession().getQueries();
List<DatabaseQuery> returnQueries = new ArrayList<>();
for (List<DatabaseQuery> keyQueries : queries.values()) {
Iterator<DatabaseQuery> queryIterator = keyQueries.iterator();
while (queryIterator.hasNext()) {
DatabaseQuery query = queryIterator.next();
if (javaClassName == null || (query.getReferenceClassName() != null && query.getReferenceClassName().equals(javaClassName))) {
returnQueries.add(query);
}
}
}
Iterator<DatabaseQuery> queryIterator = returnQueries.iterator();
while (queryIterator.hasNext()) {
queryList.add(getQuery(queryIterator.next(), context));
}
}
use of org.eclipse.persistence.queries.DatabaseQuery in project eclipselink by eclipse-ee4j.
the class AbstractSingleResultQueryResource method namedQuerySingleResultInternal.
/**
* Named query single result.
*
* @param version the version
* @param persistenceUnit the persistence unit
* @param queryName the query name
* @param headers the http headers
* @param uriInfo the uriInfo
* @return the response
*/
@SuppressWarnings("rawtypes")
protected Response namedQuerySingleResultInternal(String version, String persistenceUnit, String queryName, HttpHeaders headers, UriInfo uriInfo) {
JPARSLogger.entering(CLASS_NAME, "namedQuerySingleResultInternal", new Object[] { "GET", version, persistenceUnit, queryName, uriInfo.getRequestUri().toASCIIString() });
try {
final PersistenceContext context = getPersistenceContext(persistenceUnit, null, uriInfo.getBaseUri(), version, null);
final Query query = context.buildQuery(getMatrixParameters(uriInfo, persistenceUnit), queryName, getMatrixParameters(uriInfo, queryName), getQueryParameters(uriInfo));
final DatabaseQuery dbQuery = ((EJBQueryImpl<?>) query).getDatabaseQuery();
final FeatureResponseBuilder responseBuilder = context.getSupportedFeatureSet().getResponseBuilder(Feature.NO_PAGING);
if (dbQuery instanceof ReportQuery) {
final List<ReportItem> reportItems = ((ReportQuery) dbQuery).getItems();
final Object queryResults = query.getSingleResult();
final Object response = responseBuilder.buildSingleResultQueryResponse(context, getQueryParameters(uriInfo), queryResults, reportItems, uriInfo);
if (response != null && response instanceof SingleResultQuery) {
final SingleResultQuery singleResultQuery = (SingleResultQuery) response;
final List<JAXBElement<?>> item = singleResultQuery.getFields();
if ((item != null) && (item.size() == 1)) {
// Fix for Bug 393320 - JPA-RS: Respect the Accept Header for a singleResultQuery
// If there is only one item in the select clause and if value of that item is binary, we will create a response with
// that binary data without converting its to Base64.
JAXBElement element = item.get(0);
Object elementValue = element.getValue();
if (elementValue instanceof byte[]) {
List<MediaType> acceptableMediaTypes = headers.getAcceptableMediaTypes();
if (acceptableMediaTypes.contains(MediaType.APPLICATION_OCTET_STREAM_TYPE)) {
return Response.ok(new StreamingOutputMarshaller(context, elementValue, headers.getAcceptableMediaTypes())).build();
}
}
}
return Response.ok(new StreamingOutputMarshaller(context, response, headers.getAcceptableMediaTypes())).build();
} else {
// something went wrong with the descriptors, return error
throw JPARSException.responseCouldNotBeBuiltForNamedQueryRequest(queryName, context.getName());
}
}
final Object queryResult = query.getSingleResult();
return Response.ok(new StreamingOutputMarshaller(context, responseBuilder.buildSingleEntityResponse(context, getQueryParameters(uriInfo), queryResult, uriInfo), headers.getAcceptableMediaTypes())).build();
} catch (Exception ex) {
throw JPARSException.exceptionOccurred(ex);
}
}
use of org.eclipse.persistence.queries.DatabaseQuery in project eclipselink by eclipse-ee4j.
the class MetadataResource method buildQueryMetadataResponse.
private Response buildQueryMetadataResponse(String version, String persistenceUnit, String queryName, HttpHeaders httpHeaders, UriInfo uriInfo) {
JPARSLogger.entering(CLASS_NAME, "buildQueryMetadataResponse", new Object[] { "GET", version, persistenceUnit, queryName, uriInfo.getRequestUri().toASCIIString() });
final String result;
try {
final PersistenceContext context = getPersistenceContext(persistenceUnit, null, uriInfo.getBaseUri(), version, null);
// We need to make sure that query with given name exists
final DatabaseQuery query = context.getServerSession().getQuery(queryName);
if (query == null) {
JPARSLogger.error(context.getSessionLog(), "jpars_could_not_find_query", new Object[] { queryName, persistenceUnit });
throw JPARSException.responseCouldNotBeBuiltForNamedQueryRequest(queryName, context.getName());
}
final String mediaType = StreamingOutputMarshaller.mediaType(httpHeaders.getAcceptableMediaTypes()).toString();
final Resource resource = buildQueryMetadata(context, query);
result = marshallMetadata(resource, mediaType);
} catch (JAXBException e) {
throw JPARSException.exceptionOccurred(e);
}
return Response.ok(new StreamingOutputMarshaller(null, result, httpHeaders.getAcceptableMediaTypes())).build();
}
use of org.eclipse.persistence.queries.DatabaseQuery in project eclipselink by eclipse-ee4j.
the class OracleHelper method buildQueryForProcedureType.
/**
* Build a Query for the given ProcedureType instance and add
* it to the given OR project's list of queries.
*/
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void buildQueryForProcedureType(ProcedureType procType, Project orProject, Project oxProject, ProcedureOperationModel opModel, boolean hasPLSQLArgs) {
// if there are one or more PL/SQL args, then we need a PLSQLStoredProcedureCall
StoredProcedureCall call;
ArgumentType returnArg = procType.isFunctionType() ? ((FunctionType) procType).getReturnArgument() : null;
// check for PL/SQL cursor arg
boolean hasCursor = hasPLSQLCursorArg(getArgumentListForProcedureType(procType));
hasPLSQLArgs = hasPLSQLArgs || hasCursor || opModel.isPLSQLProcedureOperation();
if (hasPLSQLArgs) {
if (procType.isFunctionType()) {
org.eclipse.persistence.internal.helper.DatabaseType dType = buildDatabaseTypeFromMetadataType(returnArg, procType.getCatalogName());
if (hasCursor) {
call = new PLSQLStoredFunctionCall();
// constructor by default adds a RETURN argument, so remove it
((PLSQLStoredFunctionCall) call).getArguments().remove(0);
((PLSQLStoredFunctionCall) call).useNamedCursorOutputAsResultSet(CURSOR_STR, dType);
} else {
Class wrapperClass = getWrapperClass(dType);
if (wrapperClass != null) {
((ComplexDatabaseType) dType).setJavaType(wrapperClass);
}
call = new PLSQLStoredFunctionCall(dType);
// check for non-associative collection
if (returnArg.getEnclosedType().isPLSQLCollectionType() && !((PLSQLCollectionType) returnArg.getEnclosedType()).isIndexed()) {
PLSQLargument plsqlArg = ((PLSQLStoredFunctionCall) call).getArguments().get(0);
((PLSQLCollection) plsqlArg.databaseType).setIsNestedTable(true);
}
}
} else {
call = new PLSQLStoredProcedureCall();
}
} else {
if (procType.isFunctionType()) {
String javaTypeName = returnArg.getTypeName();
ClassDescriptor desc = oxProject.getDescriptorForAlias(getGeneratedAlias(javaTypeName));
if (desc != null) {
javaTypeName = desc.getJavaClassName();
}
if (returnArg.isComposite()) {
DatabaseType dataType = returnArg.getEnclosedType();
if (dataType.isVArrayType() || dataType.isObjectTableType()) {
call = new StoredFunctionCall(Types.ARRAY, returnArg.getTypeName(), javaTypeName, buildFieldForNestedType(dataType));
} else {
// assumes ObjectType
call = new StoredFunctionCall(Types.STRUCT, returnArg.getTypeName(), javaTypeName);
}
} else {
// scalar
call = new StoredFunctionCall();
if (returnArg.getEnclosedType().isBlobType()) {
// handle BLOBs
((StoredFunctionCall) call).setResult(null, ClassConstants.BLOB);
} else {
int resultType = Util.getJDBCTypeFromTypeName(javaTypeName);
// need special handling for Date types
if (resultType == Types.DATE || resultType == Types.TIME || resultType == Types.TIMESTAMP) {
((StoredFunctionCall) call).setResult(null, ClassConstants.TIMESTAMP);
} else if (returnArg.getEnclosedType() == ScalarDatabaseTypeEnum.XMLTYPE_TYPE) {
// special handling for XMLType types
((StoredFunctionCall) call).setResult(getJDBCTypeForTypeName(XMLTYPE_STR), XMLTYPE_STR, ClassConstants.OBJECT);
} else if (resultType == Types.OTHER || resultType == Types.CLOB) {
// default to OBJECT for OTHER, CLOB and LONG types
((StoredFunctionCall) call).setResult(null, ClassConstants.OBJECT);
} else {
((StoredFunctionCall) call).setResult(null, resultType);
}
}
}
} else {
call = new StoredProcedureCall();
}
}
String cat = procType.getCatalogName();
String catalogPrefix = (cat == null || cat.length() == 0) ? EMPTY_STRING : cat + DOT;
call.setProcedureName(catalogPrefix + procType.getProcedureName());
String returnType = opModel.getReturnType();
boolean hasResponse = returnType != null;
DatabaseQuery dq = null;
if (hasCursor || (hasResponse && opModel.isCollection())) {
dq = new DataReadQuery();
} else {
dq = new ValueReadQuery();
}
dq.bindAllParameters();
dq.setName(getNameForQueryOperation(opModel, procType));
dq.setCall(call);
for (ArgumentType arg : procType.getArguments()) {
// handle optional arg
if (arg.optional()) {
call.addOptionalArgument(arg.getArgumentName());
}
DatabaseType argType = arg.getEnclosedType();
ArgumentTypeDirection direction = arg.getDirection();
// for PL/SQL
org.eclipse.persistence.internal.helper.DatabaseType databaseType = null;
// for Advanced JDBC
String javaTypeName = null;
if (hasPLSQLArgs) {
databaseType = buildDatabaseTypeFromMetadataType(argType, cat);
} else {
javaTypeName = argType.getTypeName();
ClassDescriptor desc = oxProject.getDescriptorForAlias(getGeneratedAlias(javaTypeName));
if (desc != null) {
// anything there's a descriptor for will include "packagename." in the class name
javaTypeName = desc.getJavaClassName();
}
}
if (direction == IN) {
if (hasPLSQLArgs) {
Class wrapperClass = getWrapperClass(databaseType);
if (wrapperClass != null) {
((ComplexDatabaseType) databaseType).setJavaType(wrapperClass);
}
((PLSQLStoredProcedureCall) call).addNamedArgument(arg.getArgumentName(), databaseType);
// check for non-associative collection
if (argType.isPLSQLCollectionType() && !((PLSQLCollectionType) argType).isIndexed()) {
PLSQLargument plsqlArg = ((PLSQLStoredProcedureCall) call).getArguments().get(((PLSQLStoredProcedureCall) call).getArguments().size() - 1);
((PLSQLCollection) plsqlArg.databaseType).setIsNestedTable(true);
}
} else {
if (argType.isVArrayType()) {
dq.addArgument(arg.getArgumentName());
call.addNamedArgument(arg.getArgumentName(), arg.getArgumentName(), Types.ARRAY, argType.getTypeName(), javaTypeName);
} else if (argType.isObjectType()) {
dq.addArgument(arg.getArgumentName());
call.addNamedArgument(arg.getArgumentName(), arg.getArgumentName(), Types.STRUCT, argType.getTypeName(), javaTypeName);
} else if (argType.isObjectTableType()) {
dq.addArgument(arg.getArgumentName(), java.sql.Array.class);
call.addNamedArgument(arg.getArgumentName(), arg.getArgumentName(), Types.ARRAY, argType.getTypeName(), getWrapperClass(javaTypeName), buildFieldForNestedType(argType));
} else {
dq.addArgument(arg.getArgumentName());
call.addNamedArgument(arg.getArgumentName(), arg.getArgumentName(), Util.getJDBCTypeFromTypeName(argType.getTypeName()));
}
}
} else if (direction == OUT) {
if (hasPLSQLArgs) {
if (arg.isPLSQLCursorType()) {
((PLSQLStoredProcedureCall) call).useNamedCursorOutputAsResultSet(arg.getArgumentName(), databaseType);
} else {
Class wrapperClass = getWrapperClass(databaseType);
if (wrapperClass != null) {
((ComplexDatabaseType) databaseType).setJavaType(wrapperClass);
}
((PLSQLStoredProcedureCall) call).addNamedOutputArgument(arg.getArgumentName(), databaseType);
}
} else {
if (argType.isComposite()) {
Class wrapperClass = getWrapperClass(javaTypeName);
if (argType.isVArrayType() || argType.isObjectTableType()) {
call.addNamedOutputArgument(arg.getArgumentName(), arg.getArgumentName(), Types.ARRAY, argType.getTypeName(), wrapperClass, buildFieldForNestedType(argType));
} else {
// assumes ObjectType
call.addNamedOutputArgument(arg.getArgumentName(), arg.getArgumentName(), Types.STRUCT, argType.getTypeName(), wrapperClass);
}
} else {
// need special handling for XMLType - we want the type code to be 'OPAQUE' (2007)
if (argType == ScalarDatabaseTypeEnum.XMLTYPE_TYPE) {
call.addNamedOutputArgument(arg.getArgumentName(), arg.getArgumentName(), getJDBCTypeForTypeName(XMLTYPE_STR), XMLTYPE_STR);
} else if (argType == ScalarDatabaseTypeEnum.SYS_REFCURSOR_TYPE) {
call.addNamedCursorOutputArgument(arg.getArgumentName());
} else {
call.addNamedOutputArgument(arg.getArgumentName(), arg.getArgumentName(), Util.getJDBCTypeFromTypeName(argType.getTypeName()));
}
}
}
} else {
// INOUT
if (hasPLSQLArgs) {
Class wrapperClass = getWrapperClass(databaseType);
if (wrapperClass != null) {
((ComplexDatabaseType) databaseType).setJavaType(wrapperClass);
}
((PLSQLStoredProcedureCall) call).addNamedInOutputArgument(arg.getArgumentName(), databaseType);
// check for non-associative collection
if (argType.isPLSQLCollectionType() && !((PLSQLCollectionType) argType).isIndexed()) {
PLSQLargument plsqlArg = ((PLSQLStoredProcedureCall) call).getArguments().get(((PLSQLStoredProcedureCall) call).getArguments().size() - 1);
((PLSQLCollection) plsqlArg.databaseType).setIsNestedTable(true);
}
} else {
dq.addArgument(arg.getArgumentName());
if (argType.isComposite()) {
Class wrapperClass = getWrapperClass(javaTypeName);
if (argType.isVArrayType() || argType.isObjectTableType()) {
call.addNamedInOutputArgument(arg.getArgumentName(), arg.getArgumentName(), arg.getArgumentName(), Types.ARRAY, argType.getTypeName(), wrapperClass, buildFieldForNestedType(argType));
} else {
// assumes ObjectType
call.addNamedInOutputArgument(arg.getArgumentName(), arg.getArgumentName(), arg.getArgumentName(), Types.STRUCT, argType.getTypeName());
}
} else {
// for some reason setting "java.lang.String" as the java type causes problems at runtime
Class javaType = getClassFromJDBCType(argType.getTypeName(), dbwsBuilder.getDatabasePlatform());
if (shouldSetJavaType(javaType.getName())) {
call.addNamedInOutputArgument(arg.getArgumentName(), arg.getArgumentName(), arg.getArgumentName(), Util.getJDBCTypeFromTypeName(argType.getTypeName()), argType.getTypeName(), javaType);
} else {
call.addNamedInOutputArgument(arg.getArgumentName());
}
}
}
}
if (hasPLSQLArgs && (direction == IN || direction == INOUT)) {
ClassDescriptor xdesc = null;
if (hasResponse) {
int idx = returnType.indexOf(COLON);
if (idx == -1) {
idx = returnType.indexOf(CLOSE_PAREN);
}
if (idx > 0) {
String typ = returnType.substring(idx + 1);
for (XMLDescriptor xd : (List<XMLDescriptor>) (List) oxProject.getOrderedDescriptors()) {
if (xd.getSchemaReference() != null) {
String context = xd.getSchemaReference().getSchemaContext();
if (context.substring(1).equals(typ)) {
xdesc = xd;
break;
}
}
}
}
}
if (xdesc != null) {
dq.addArgumentByTypeName(arg.getArgumentName(), xdesc.getJavaClassName());
} else {
if (databaseType instanceof PLSQLCollection || databaseType instanceof VArrayType) {
dq.addArgument(arg.getArgumentName(), Array.class);
} else if (databaseType instanceof PLSQLrecord || databaseType instanceof OracleObjectType) {
dq.addArgument(arg.getArgumentName(), Struct.class);
} else {
dq.addArgument(arg.getArgumentName(), JDBCTypes.getClassForCode(databaseType.getConversionCode()));
}
}
}
}
orProject.getQueries().add(dq);
}
use of org.eclipse.persistence.queries.DatabaseQuery in project eclipselink by eclipse-ee4j.
the class JDBCHelper method buildProcedureOperation.
@Override
public void buildProcedureOperation(ProcedureOperationModel procedureOperationModel) {
String name = procedureOperationModel.getName();
boolean isMySQL = dbwsBuilder.getDatabasePlatform().getClass().getName().contains("MySQL");
for (ProcedureType storedProcedure : procedureOperationModel.getDbStoredProcedures()) {
StringBuilder sb = new StringBuilder();
if (name == null || name.length() == 0) {
if (storedProcedure.getOverload() > 0) {
sb.append(storedProcedure.getOverload());
sb.append('_');
}
if (storedProcedure.getCatalogName() != null && storedProcedure.getCatalogName().length() > 0) {
sb.append(storedProcedure.getCatalogName());
sb.append('_');
}
if (storedProcedure.getSchema() != null && storedProcedure.getSchema().length() > 0) {
sb.append(storedProcedure.getSchema());
sb.append('_');
}
sb.append(storedProcedure.getProcedureName());
} else {
sb.append(name);
}
QueryOperation qo = new QueryOperation();
qo.setName(sb.toString());
QueryHandler qh;
if (storedProcedure.isFunctionType()) {
qh = new StoredFunctionQueryHandler();
} else {
qh = new StoredProcedureQueryHandler();
}
sb = new StringBuilder();
if (!isMySQL) {
if (storedProcedure.getCatalogName() != null && storedProcedure.getCatalogName().length() > 0) {
sb.append(storedProcedure.getCatalogName());
sb.append('.');
}
}
if (storedProcedure.getSchema() != null && storedProcedure.getSchema().length() > 0) {
sb.append(storedProcedure.getSchema());
sb.append('.');
}
sb.append(storedProcedure.getProcedureName());
((StoredProcedureQueryHandler) qh).setName(sb.toString());
dbwsBuilder.logMessage(FINEST, "Building QueryOperation for " + sb.toString());
// before assigning queryHandler, check for named query in OR project
List<DatabaseQuery> queries = dbwsBuilder.getOrProject().getQueries();
if (queries.size() > 0) {
for (DatabaseQuery q : queries) {
if (q.getName().equals(qo.getName())) {
qh = new NamedQueryHandler();
((NamedQueryHandler) qh).setName(qo.getName());
}
}
}
qo.setQueryHandler(qh);
String returnType = procedureOperationModel.getReturnType();
boolean isCollection = procedureOperationModel.isCollection();
boolean isSimpleXMLFormat = procedureOperationModel.isSimpleXMLFormat();
Result result = null;
if (storedProcedure.isFunctionType()) {
FunctionType storedFunction = (FunctionType) storedProcedure;
DatabaseType rarg = storedFunction.getReturnArgument();
if (rarg.getTypeName().contains("CURSOR")) {
result = new CollectionResult();
result.setType(SXF_QNAME_CURSOR);
} else {
result = new Result();
int rargJdbcType = Util.getJDBCTypeFromTypeName(rarg.getTypeName());
switch(rargJdbcType) {
case STRUCT:
case ARRAY:
case OTHER:
if (returnType != null) {
result.setType(buildCustomQName(returnType, dbwsBuilder));
} else {
result.setType(ANY_QNAME);
}
break;
default:
result.setType(getXMLTypeFromJDBCType(rargJdbcType));
break;
}
}
} else {
// if user overrides returnType, assume they're right
if (returnType != null) {
result = new Result();
result.setType(buildCustomQName(returnType, dbwsBuilder));
} else {
if (isCollection) {
result = new CollectionResult();
if (isSimpleXMLFormat) {
result.setType(SXF_QNAME_CURSOR);
}
} else {
result = new Result();
result.setType(SXF_QNAME);
}
}
}
if (procedureOperationModel.getBinaryAttachment()) {
Attachment attachment = new Attachment();
attachment.setMimeType("application/octet-stream");
result.setAttachment(attachment);
}
for (ArgumentType arg : storedProcedure.getArguments()) {
String argName = arg.getArgumentName();
if (argName != null) {
ProcedureArgument pa = null;
Parameter parm = null;
ArgumentTypeDirection direction = arg.getDirection();
QName xmlType = null;
switch(Util.getJDBCTypeFromTypeName(arg.getTypeName())) {
case STRUCT:
case ARRAY:
case OTHER:
String typeString = nct.generateSchemaAlias(arg.getTypeName());
xmlType = buildCustomQName(typeString, dbwsBuilder);
break;
default:
xmlType = getXMLTypeFromJDBCType(Util.getJDBCTypeFromTypeName(arg.getTypeName()));
break;
}
if (direction == IN) {
parm = new Parameter();
parm.setName(argName);
parm.setType(xmlType);
pa = new ProcedureArgument();
pa.setName(argName);
pa.setParameterName(argName);
if (qh instanceof StoredProcedureQueryHandler) {
((StoredProcedureQueryHandler) qh).getInArguments().add(pa);
}
} else {
// the first OUT/INOUT arg determines singleResult vs. collectionResult
pa = new ProcedureOutputArgument();
ProcedureOutputArgument pao = (ProcedureOutputArgument) pa;
pao.setName(argName);
pao.setParameterName(argName);
if (arg.getTypeName().contains("CURSOR") && returnType == null) {
// if user overrides returnType, assume they're right
pao.setResultType(SXF_QNAME_CURSOR);
if (result == null) {
result = new CollectionResult();
result.setType(SXF_QNAME_CURSOR);
}
} else {
// Hmm, multiple OUT's gonna be a problem - later!
if (returnType != null && !isSimpleXMLFormat) {
xmlType = qNameFromString("{" + dbwsBuilder.getTargetNamespace() + "}" + returnType, dbwsBuilder.getSchema());
}
pao.setResultType(xmlType);
if (result == null) {
if (isCollection) {
result = new CollectionResult();
} else {
result = new Result();
}
result.setType(xmlType);
}
}
if (direction == INOUT) {
parm = new Parameter();
parm.setName(argName);
parm.setType(xmlType);
result.setType(xmlType);
// use of INOUT precludes SimpleXMLFormat
isSimpleXMLFormat = false;
if (qh instanceof StoredProcedureQueryHandler) {
((StoredProcedureQueryHandler) qh).getInOutArguments().add(pao);
}
} else {
if (qh instanceof StoredProcedureQueryHandler) {
((StoredProcedureQueryHandler) qh).getOutArguments().add(pao);
}
}
}
if (parm != null) {
qo.getParameters().add(parm);
}
}
}
handleSimpleXMLFormat(isSimpleXMLFormat, result, procedureOperationModel);
qo.setResult(result);
dbwsBuilder.getXrServiceModel().getOperations().put(qo.getName(), qo);
}
finishProcedureOperation();
}
Aggregations