Is it possible to replace the "official" ExceptionMiddleware HotChocolate classe by my own middleware classe?
I plan to "complete" the catch by including AgregationException .Net exception and create IError[] array by looping AgregationException.InnerExceptions property (see below the original ExceptionMiddleware).
I would like to replace it by my own implementation.
Is it possible ? How can I do this ?
Thanks.
Kind Regards
internal sealed class ExceptionMiddleware
{
private readonly RequestDelegate _next;
private readonly IErrorHandler _errorHandler;
public ExceptionMiddleware(RequestDelegate next, IErrorHandler errorHandler)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
_errorHandler = errorHandler ?? throw new ArgumentNullException(nameof(errorHandler));
}
public async ValueTask InvokeAsync(IRequestContext context)
{
try
{
await _next(context).ConfigureAwait(false);
}
catch (GraphQLException ex)
{
context.Exception = ex;
context.Result = QueryResultBuilder.CreateError(_errorHandler.Handle(ex.Errors));
}
catch (Exception ex)
{
context.Exception = ex;
IError error = _errorHandler.CreateUnexpectedError(ex).Build();
context.Result = QueryResultBuilder.CreateError(_errorHandler.Handle(error));
}
}
}
Related
I found the following error in a Mule 4 components. How can I report this issue to Mulesoft?
Mule 4 XML Module 1.2.3 introduced a bug that causes the wrong Mule error to be raised in the module.
When validating an invalid XML payload (non-xml string, "XML" with unclosed or unpaired tags, etc) version 1.2.2 of the component would raise mule error XML-MODULE:INVALID_INPUT_XML, but with version 1.2.3 of the component the error is now XML-MODULE:TRANSFORMATION.
The problem seems to be that version 1.2.3 of the module removed the call to XMLUtils.toDOMNode, which was used to do an initial validation of the message and threw exception of class InvalidInputXmlException when processing an invalid XML.
XML module : 1.2.2
public class SchemaValidatorOperation extends PooledTransformerOperation<SchemaValidatorOperation.SchemaKey, Validator> {
private LSResourceResolver resourceResolver = (LSResourceResolver)new MuleResourceResolver();
#Validator
#Execution(ExecutionType.CPU_INTENSIVE)
#Throws({SchemaValidatorErrorTypeProvider.class})
public void validateSchema(#Path(type = PathModel.Type.FILE, acceptedFileExtensions = {"xsd"}) String schemas, #Optional(defaultValue = "W3C") SchemaLanguage schemaLanguage, #Content(primary = true) InputStream content, #Config XmlModule config) {
Node node = XMLUtils.toDOMNode(content, this.documentBuilderFactory);
withTransformer(new SchemaKey(schemas, schemaLanguage.getLanguageUri(), this.expandEntities), validator -> {
validator.setResourceResolver(this.resourceResolver);
final List<SchemaViolation> errors = new LinkedList<>();
validator.setErrorHandler(new ErrorHandler() {
public void warning(SAXParseException exception) {}
public void error(SAXParseException exception) {
trackError(exception);
}
public void fatalError(SAXParseException exception) {
trackError(exception);
}
private void trackError(SAXParseException exception) {
errors.add(new SchemaViolation(exception.getLineNumber(), exception.getColumnNumber(), exception.getMessage()));
}
});
try {
validator.validate(new DOMSource(node));
} catch (SAXParseException e) {
throw new TransformationException("Failed to validate schema. " + e.getMessage(), e);
} catch (IOException e) {
throw new InvalidInputXmlException("Could not validate schema because the input was not valid XML. " + e.getMessage(), e);
}
if (!errors.isEmpty())
throw new SchemaValidationException("Input XML was not compliant with the schema. Check this error's Mule message for the list of problems (e.g: #[error.errorMessage.payload[0].description)", errors);
return null;
});
}
XML module : 1.2.3
public class SchemaValidatorOperation extends PooledTransformerOperation<SchemaValidatorOperation.SchemaKey, Validator> {
private LSResourceResolver resourceResolver = (LSResourceResolver)new MuleResourceResolver();
#Validator
#Execution(ExecutionType.CPU_INTENSIVE)
#Throws({SchemaValidatorErrorTypeProvider.class})
public void validateSchema(#Path(type = PathModel.Type.FILE, acceptedFileExtensions = {"xsd"}) String schemas, #Optional(defaultValue = "W3C") SchemaLanguage schemaLanguage, #Content(primary = true) InputStream content, #Config XmlModule config) {
withTransformer(new SchemaKey(schemas, schemaLanguage.getLanguageUri(), this.expandEntities), validator -> {
validator.setResourceResolver(this.resourceResolver);
final List<SchemaViolation> errors = new LinkedList<>();
validator.setErrorHandler(new ErrorHandler() {
public void warning(SAXParseException exception) {}
public void error(SAXParseException exception) {
trackError(exception);
}
public void fatalError(SAXParseException exception) {
trackError(exception);
}
private void trackError(SAXParseException exception) {
errors.add(new SchemaViolation(exception.getLineNumber(), exception.getColumnNumber(), exception.getMessage()));
}
});
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setFeature("http://xml.org/sax/features/external-general-entities", this.expandEntities.isAcceptExternalEntities());
spf.setFeature("http://xml.org/sax/features/external-parameter-entities", this.expandEntities.isAcceptExternalEntities());
spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", !this.expandEntities.isExpandInternalEntities());
spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", this.expandEntities.isExpandInternalEntities());
validator.validate(new SAXSource(spf.newSAXParser().getXMLReader(), new InputSource(content)));
} catch (SAXParseException e) {
throw new TransformationException("Failed to validate schema. " + e.getMessage(), e);
} catch (IOException e) {
throw new InvalidInputXmlException("Could not validate schema because the input was not valid XML. " + e.getMessage(), e);
}
if (!errors.isEmpty())
throw new SchemaValidationException("Input XML was not compliant with the schema. Check this error's Mule message for the list of problems (e.g: #[error.errorMessage.payload[0].description)", errors);
return null;
});
}
Not that XMLUtils.toDOMNode was perfect since it catched any Exception, but at least it was useful to detect instances when trying to validate an incorrect xml.
XMLUtils.toDOMNode
public class XMLUtils {
public static Node toDOMNode(InputStream src, DocumentBuilderFactory factory) {
return toDOMNode(src, factory, null);
}
public static Node toDOMNode(InputStream src, DocumentBuilderFactory factory, EntityResolver entityResolver) {
try {
DocumentBuilder documentBuilder = factory.newDocumentBuilder();
if (entityResolver != null)
documentBuilder.setEntityResolver(entityResolver);
return documentBuilder.parse(src);
} catch (Exception e) {
throw new InvalidInputXmlException("Cannot parse input XML because it is invalid.", e);
}
}
}
For open source components of Mule like the XML Module you can open a JIRA ticket in MuleSoft open tracker: https://www.mulesoft.org/jira/projects/MULE. The sources for the XML module are at https://github.com/mulesoft/mule-xml-module so you could attach a push request to the ticket if you create one.
If you are a current customer of MuleSoft you can engage their Support directly.
I was trying to get specific data from database but every time I'm getting the following error!
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.lglsys.entity.TDasProductDownload
So this is my QueryService class
#Dependent
public class QueryService {
List<TDasProductDownload> downloadLink = new ArrayList();
final private Logger logger =
LogManager.getLogger(QueryService.class.getName());
#PersistenceContext(unitName="DownloadServices")
EntityManager em;
public QueryService() { super(); }
public List<TDasProductDownload> findAllDownloadLinks() {
try {
downloadLink=
em.createQuery(queryForDownloadLinks,TDasProductDownload.class)
.getResultList();
return downloadLink;
} catch (Exception e) {
logger.info(e.toString());
return null;
}
}
}
program gives error in this class /
EndPoint class
public class PreControlWSEndPoint {
private Session session;
final private Logger logger = LogManager.getLogger(PreControlWSEndPoint.class.getName());
List<TDasProductDownload> downloadLink = new ArrayList();
#PersistenceContext(unitName="DownloadServices")
EntityManager em;
#Inject
QueryService service;
#OnOpen
public void Open(Session session) throws IOException, InterruptedException {
this.session = session;
this.sendMessage("Connection Oppened");
logger.info("EndPoint Opened");
try {
downloadLink = service.findAllDownloadLinks();
logger.info(downloadLink.size());
TDasProductDownload str = downloadLink.get(0);
logger.info(str.getDownloadStatus()); //**Eror line!!**
} catch (Exception e) {
logger.info(e.toString() + " .D");
}
}
#OnMessage
public void onMessage(String message) {}
#OnClose
public void Close() {}
}
I can't see what's happening in my code.
I fixed it!
public List<String> findAllDownloadLinks() {
try {
downloadLink=
em.createQuery(queryForDownloadLinks,String.class)
.getResultList();
return downloadLink;
} catch (Exception e) {
logger.info(e.toString());
return null;
}
}
then i can print like so
for(int temp=0;temp<=downloadLink.size();temp++){
logger.info(downloadLink.get(temp));
}
Hi i need to download a file from url and save in internal storage,so the download process run in async task.
First, I have tried to write a string in a file with async task but give me error: Failed to create oat file.
The same code work without task, so my question is i must download the file in external storage and after move in internal?
private void writeInFile() {
FileOutputStream output = null;
String text = "TEXT";
try {
output = openFileOutput("nameFile.abc",Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
output.write(text.getBytes());
output.flush();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
But if i call this function in doInBackground of class that extend AsyncTask i receive the error.
LicenzaTask mt = new LicenzaTask(this);
mt.execute();
public class LicenzaTask extends AsyncTask<Void, Void, Void> {
private Context mContext;
public LicenzaTask(MainActivity mainActivity) {
mContext = mainActivity;
}
#Override
protected Void doInBackground(Void... voids) {
modifyFile();
return null;
}
private void modifyFile() {
File file = new File(mContext.getFilesDir() + "nome.abc");
String text = "text";
BufferedWriter output = null;
try {
output = new BufferedWriter(new FileWriter(file));
output.write(text);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
}
}
}
}
I want to execute a method periodically, this method get informations from database it show it into a label, I tried the following code :
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//update information
miseAjour();
}
}, 0, 2000);
when i run the main program, the background service run also normaly but when the informations changes on db i get this exception:
Exception in thread "Timer-0" java.lang.IllegalStateException: Not on FX application thread; currentThread = Timer-0
And this is the code of method miseAjour :
public void miseAjour(){
try {
dbConnection db = new dbConnection();
Connection connect = db.connectiondb();
connect.setAutoCommit(false);
Statement stmt= connect.createStatement();
ResultSet rs = stmt.executeQuery("SELECT count(*) as nbrAderent FROM gss_aderent ");
int nbrAderent = rs.getInt("nbrAderent");
rs.close();
stmt.close();
connect.commit();
connect.close();
main_nbrAdrTot.setText(nbrAderent + "");
} catch (SQLException ex) {
Logger.getLogger(SimpleController.class.getName()).log(Level.SEVERE, null, ex);
}
}
You can Timer for this, but I would recommend to use the JavaFX provided API called as ScheduledService.
ScheduledService is made to execute the same Task at regular intervals and since it creates a Task internally, there are API which help you to bind the value to the UI controls.
ScheduledService<Object> service = new ScheduledService<Object>() {
protected Task<Object> createTask() {
return new Task<Object>() {
protected Object call() {
// Call the method and update the message
updateMessage(miseAjour());
return object; // Useful in case you want to return data, else null
}
};
}
};
service.setPeriod(Duration.seconds(10)); //Runs every 10 seconds
//bind the service message properties to your Label
label.textProperty().bind(service.messageProperty()); // or use your label -> main_nbrAdrTot
Inside the dbcall method miseAjour, return the value that you have fetched and you want to update the label with :
public String miseAjour(){
String nbrAderent = null;
try {
dbConnection db = new dbConnection();
Connection connect = db.connectiondb();
connect.setAutoCommit(false);
Statement stmt= connect.createStatement();
ResultSet rs = stmt.executeQuery("SELECT count(*) as nbrAderent FROM gss_aderent ");
nbrAderent = String.valueOf(rs.getInt("nbrAderent"));
connect.commit();
} catch (SQLException ex) {
Logger.getLogger(SimpleController.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
rs.close();
stmt.close();
connect.close();
}
return nbrAderent;
}
Finnaly i resolved the problem ,here is the code :
public class TimerServiceApp {
public void start() throws Exception {
TimerService service = new TimerService();
service.setPeriod(Duration.seconds(10));
service.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent t) {
main_nbrAdrTot.setText(t.getSource().getMessage());
}
});
service.start();
}
private class TimerService extends ScheduledService<Integer> {
private final StringProperty nbrTotAderent = new SimpleStringProperty();
public final void setTotalAderentNumber(String value ) {
nbrTotAderent.set(value);
}
public String getTotalAderentNumber() throws SQLException {
String nbrAderent = null;
ResultSet rs=null;
Statement stmt=null;
Connection connect=null;
try {
dbConnection db = new dbConnection();
connect = db.connectiondb();
connect.setAutoCommit(false);
stmt= connect.createStatement();
rs = stmt.executeQuery("SELECT count(*) as nbrAderent FROM gss_aderent ");
nbrAderent = String.valueOf(rs.getInt("nbrAderent"));
connect.commit();
} catch (SQLException ex) {
Logger.getLogger(SimpleController.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
rs.close();
stmt.close();
connect.close();
}
System.out.println(" Total aderent number updated to :" + nbrAderent + " Aderents ");
return nbrAderent;
}
protected Task<Integer> createTask() {
return new Task<Integer>() {
protected Integer call() throws SQLException {
nbrTotAderent.setValue(getTotalAderentNumber());
updateMessage(getTotalAderentNumber());
return Integer.parseInt(getTotalAderentNumber());
}
};
}
}
} `
and i called this service by :
TimerServiceApp s = new TimerServiceApp();
s.start();
i dont know if the solution is optimised but it work :) thank you #ItachiUchiha i took the solution from yout answer in the following link
i did not find any answer for question "How to handle method validation exceptions?", which is thrown automatically by Bean Validation 1.1.
I have following environment:
Glassfish 4
hibernate-validator-5.0.1.Final.jar (in ear)
Now I try to implement auto validation of method parameters:
#Local
#ValidateOnExecution(type = ExecutableType.ALL)
public interface SomeServiceLocal {
String someMethod(#Size(max = 1) String value);
}
in execution of:
#Stateless
public class OtherBean implements OtherBeanLocal {
#EJB
private SomeServiceLocal someService;
#Override
public String otherMethod() {
return someService.someMethod("abc");
}
}
}
Now, when I call otherMethod a receive:
javax.ejb.EJBTransactionRolledbackException
at com.sun.ejb.containers.BaseContainer.mapLocal3xException(BaseContainer.java:2279)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2060)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1979)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:220)
followed by
Caused by: javax.validation.ConstraintViolationException: 1 constraint violation(s) occurred during method validation
...
Constraint violations:
(1) Kind: PARAMETER
parameter index: 3
message: size must be between 0 and 1
What is a best practice to handle violation exceptions?
I've created cdi interceptor which handles EJBException and extract constraint violations. It works perfect:
#MyValidation
#Interceptor
public class MyValidationExceptionInterceptor implements Serializable {
private static final long serialVersionUID = -5280505156146359055L;
#AroundInvoke
public Object processViolationException(InvocationContext ctx) throws Exception {
try {
return ctx.proceed();
} catch (EJBTransactionRolledbackException e) {
Throwable throwable = e.getCause();
if (throwable != null && throwable.getCause() != null && throwable.getCause() instanceof ConstraintViolationException) {
ConstraintViolationException cve = (ConstraintViolationException) throwable.getCause();
throw new MyException(getMessage(cve));
}
throw e;
} catch (Exception e) {
throw e;
}
}
private String getMessage(ConstraintViolationException cve) {
StringBuilder builder = new StringBuilder();
for(ConstraintViolation<?> violation : cve.getConstraintViolations()) {
builder.append(violation.getMessage()).append(';');
}
return builder.toString();
}
}