java .util.concurrent.ExecutionException: io.swagger.client.ApiException: java .io.InterruptedIOException: поток прерван - PullRequest
0 голосов
/ 31 марта 2020

Я использую ExecutorService Framework для управления 5 задачами, и код почти всегда работает хорошо. Я получаю случайное сообщение об ошибке, которое я написал в заголовке. Это трассировка стека:

java.util.concurrent.ExecutionException: io.swagger.client.ApiException: java.io.InterruptedIOException: thread interrupted
    at java.util.concurrent.FutureTask.report(Unknown Source)
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at com.ids.utilities.AnalizeReceptionFileAndDocuments.checkDocuments(AnalizeReceptionFileAndDocuments.java:233)
    at com.ids.utilities.AnalizeReceptionFileAndDocuments.checkFile(AnalizeReceptionFileAndDocuments.java:113)
    at com.ids.application.listinvoicesrx.InvoicesListRxOffset.checkOffset(InvoicesListRxOffset.java:77)
    at com.ids.application.ManageListInvoicesRx.receptionNotification(ManageListInvoicesRx.java:93)
    at com.ids.main.IdsMain.main(IdsMain.java:117)
Caused by: io.swagger.client.ApiException: java.io.InterruptedIOException: thread interrupted
    at io.swagger.client.ApiClient.downloadFileFromResponse(ApiClient.java:768)
    at io.swagger.client.ApiClient.deserialize(ApiClient.java:688)
    at io.swagger.client.ApiClient.handleResponse(ApiClient.java:912)
    at io.swagger.client.ApiClient.execute(ApiClient.java:841)
    at io.swagger.client.api.ReceptionInvoicesDownloadApi.getReceptionInvoicePdfWithHttpInfo(ReceptionInvoicesDownloadApi.java:1446)
    at io.swagger.client.api.ReceptionInvoicesDownloadApi.getReceptionInvoicePdf(ReceptionInvoicesDownloadApi.java:1428)
    at com.ids.downloadfiles.DownloadPdf.call(DownloadPdf.java:53)
    at com.ids.downloadfiles.DownloadPdf.call(DownloadPdf.java:1)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.io.InterruptedIOException: thread interrupted
    at okio.Timeout.throwIfReached(Timeout.java:145)
    at okio.Okio$1.write(Okio.java:77)
    at okio.RealBufferedSink.emitCompleteSegments(RealBufferedSink.java:176)
    at okio.RealBufferedSink.writeAll(RealBufferedSink.java:104)
    at io.swagger.client.ApiClient.downloadFileFromResponse(ApiClient.java:764)
    ... 11 more

Я не могу понять, потому что я запускаю свое приложение 10 раз, и 9 раз идет хорошо, и как только я ловлю это исключение.

Может быть, какой-то код проиллюстрирует точка:

         //do something
           int sleepTime = 200;   
           Class thisClass = new Object(){}.getClass();
           methodName = thisClass.getEnclosingMethod().getName();

           index = Integer.parseInt(n_index);

           ExecutorService downloadService =Executors.newFixedThreadPool(4);

           pdfFile = downloadService.submit(new DownloadPdf(recDownload, downloadNots, ds, invoiceUID, index,sleepTime));
           htmlFile = downloadService.submit(new DownloadHtml(recDownload, downloadNots, ds, invoiceUID, index, html,sleepTime));
           htmlMinFile = downloadService.submit(new DownloadHtml(recDownload, downloadNots, ds, invoiceUID, index, htmlMin, sleepTime));
           attach = downloadService.submit(new Attachment(stringXml, sleepTime));
           bodyXmlFile = downloadService.submit(new ConvertStringToClob(xmlBody, bodyXml, ds, sleepTime));

           TimeUnit.MILLISECONDS.sleep(sleepTime);


           downloadService.shutdown();

           try 
           {
                if (!downloadService.awaitTermination(2000, TimeUnit.MILLISECONDS)) {
                    downloadService.shutdownNow();
                } 
            } catch (InterruptedException e) {

                e.printStackTrace();
                downloadService.shutdownNow();
            }

           try 
           {
               pdf = pdfFile.get();
               html = htmlFile.get();
               htmlMin = htmlMinFile.get();
               attachment = attach.get();
               bodyXml = bodyXmlFile.get();
           }

           catch(InterruptedException e) 
           {
               e.printStackTrace();
               ds.getConn().rollback();
               internalReturnCode=5011;
               ds.getOracleFactory().getReturnCodeDAO().updateTableFe_Log(ds, methodName, internalReturnCode, 999999, e.getMessage(), TABLENAME_CHECKDOCUMENTS,invoiceUID);
           }
           catch(ExecutionException e) 
           {
               e.printStackTrace();
               ds.getConn().rollback();
               internalReturnCode=5012;
               ds.getOracleFactory().getReturnCodeDAO().updateTableFe_Log(ds, methodName, internalReturnCode, 999999, e.getMessage(), TABLENAME_CHECKDOCUMENTS,invoiceUID);
           }


           ds.getOracleFactory().getDownloadNotificationDAO().insertDatiDocuments(ds.getConn(), invoiceUID, index, pdf, html, docType, invoiceNumber, 
                                                                                    deliveryDate, currency, protocol, attachment, bodyXml, htmlMin);
           html.free();
           bodyXml.free();
           htmlMin.free();
        }
        catch(SQLException e) 
        {
            ds.getConn().rollback();
            internalReturnCode=6;
            ds.getOracleFactory().getReturnCodeDAO().updateTableFe_Log(ds, methodName, internalReturnCode, e.getErrorCode(), e.getMessage(), TABLENAME_CHECKDOCUMENTS,invoiceUID);
        }

    }

И это две из пяти задач:

public class DownloadPdf implements Callable<File>{

    private static final String TABLENAME_CHECKDOCUMENTS = "FE_LOG";

    private File fileOrig;
    private ReceptionInvoicesDownloadApi recDownload;
    private IXInvoicesList downloadNots;
    private DataSetting ds;
    private String invoiceUID;
    private int index;
    private int sleepTime;

    public DownloadPdf(ReceptionInvoicesDownloadApi recDownload,
            IXInvoicesList downloadNots, DataSetting ds, String invoiceUID, int index,int sleepTime) {
        super();
        this.fileOrig = fileOrig;
        this.recDownload = recDownload;
        this.downloadNots = downloadNots;
        this.ds = ds;
        this.invoiceUID = invoiceUID;
        this.index = index;
        this.sleepTime = sleepTime;
    }

    @Override
    public File call() throws Exception {

        File fileOrig = null;
        int internalReturnCode = 0;
        String methodName = null;

            Class thisClass = new Object(){}.getClass();
            methodName = thisClass.getEnclosingMethod().getName();
            fileOrig = recDownload.getReceptionInvoicePdf(UUID.fromString(downloadNots.getAoo()), downloadNots.getUo(), 
                                                         invoiceUID, index, downloadNots.getLoginToken());
            TimeUnit.MILLISECONDS.sleep(sleepTime);

        return fileOrig;
    }
}

public class DownloadHtml implements Callable<Clob>{

    private static final String TABLENAME_CHECKDOCUMENTS = "FE_LOG";

    private ReceptionInvoicesDownloadApi recDownload;
    private IXInvoicesList downloadNots;
    private DataSetting ds;
    private String invoiceUID;
    private int index;
    private Clob html;
    private int sleepTime;


    public DownloadHtml(ReceptionInvoicesDownloadApi recDownload, IXInvoicesList downloadNots, DataSetting ds,
            String invoiceUID, int index, Clob html, int sleepTime) {
        super();
        this.recDownload = recDownload;
        this.downloadNots = downloadNots;
        this.ds = ds;
        this.invoiceUID = invoiceUID;
        this.index = index;
        this.html = html;
        this.sleepTime = sleepTime;
    }


    @Override
    public Clob call() throws Exception 
    {
        String str=null;
        Writer clobWriter=null;
        File fileOrig = null;
        int internalReturnCode = 0;
        String methodName = null;

                Class thisClass = new Object(){}.getClass();
                methodName = thisClass.getEnclosingMethod().getName();
                fileOrig = recDownload.getReceptionInvoiceHtml(UUID.fromString(downloadNots.getAoo()), downloadNots.getUo(), invoiceUID, 
                                                               index, downloadNots.getLoginToken(), "Custom");

                  clobWriter = html.setCharacterStream(1);
                 str = readFile(fileOrig.getAbsolutePath(), clobWriter);

                 for(int i=0; i<str.length();i++) 
                 {
                    if(str.charAt(i)!='<') str=str.replace(str.charAt(i), ' ');
                    else break;
                 }      

                 html.setString(1, str.trim());
                 TimeUnit.MILLISECONDS.sleep(sleepTime);

        return html;
    }

    /**
     * writes this stream of characters; the stream is from the file specified by the String fileName. 
     * method reads the file line-by-line specified by the file fileName and writes it to the Writer 
     * object specified by writerArg.
     * @param fileName
     * @param writerArg
     * @return 
     */
   private synchronized String readFile(String fileName, Writer writerArg) throws FileNotFoundException, IOException,Exception
       {

    BufferedReader br = new BufferedReader(new FileReader(fileName));
            String nextLine = "";
            StringBuffer sb = new StringBuffer();
            while ((nextLine = br.readLine()) != null) {
             // System.out.println("Writing: " + nextLine);
                writerArg.write(nextLine);
               // sb.append(nextLine);
                 sb.append(nextLine+"\n");
            }       // Convert the content into to a string
            String clobData = sb.toString();
            // Return the data.
            return clobData;

       }
}

Я думаю и предполагаю, что проблема в HttpRequest каждого запроса. Например:

fileOrig = recDownload.getReceptionInvoiceHtml(UUID.fromString(downloadNots.getAoo()), downloadNots.getUo(), invoiceUID, 
                                                               index, downloadNots.getLoginToken(), "Custom");

Этот API-интерфейс создает URL-адрес для микросервиса для загрузки файла html.

Возможно, SleepTime недостаточно, и вызов снижается, но я ' Я не уверен. Иногда у меня возникает эта ошибка при изменении значения sleepTime. Также у меня есть эта ошибка с тем же значением sleepTime. Поэтому я хотел бы запустить приложение 10 раз и не иметь ошибок, но я не понимаю, где я был не прав.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...